react-semaphor 0.0.615 → 0.0.616
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunks/{_basePickBy-DoxAWdoa.js → _basePickBy-CBUK3LQZ.js} +2 -2
- package/dist/chunks/{_basePickBy-BjN-ebMF.js → _basePickBy-CF4sHVu5.js} +1 -1
- package/dist/chunks/{_baseUniq-DqyqOsmS.js → _baseUniq-C_wfwxLl.js} +1 -1
- package/dist/chunks/{_baseUniq-C6j27TNu.js → _baseUniq-CqIR1mFI.js} +1 -1
- package/dist/chunks/{arc-BqNFdUcO.js → arc-CcvXRu6P.js} +1 -1
- package/dist/chunks/{arc-Cum0xm0_.js → arc-CgQJTOhQ.js} +1 -1
- package/dist/chunks/{architecture-O4VJ6CD3-ZEfJFqmU.js → architecture-O4VJ6CD3-CWG1Sh-1.js} +1 -1
- package/dist/chunks/{architecture-O4VJ6CD3-DdZGsZCR.js → architecture-O4VJ6CD3-DloS2k8z.js} +1 -1
- package/dist/chunks/{architectureDiagram-KFL7JDKH-DOga74N1.js → architectureDiagram-KFL7JDKH-DEKqZHX8.js} +4 -4
- package/dist/chunks/{architectureDiagram-KFL7JDKH-DIGpJjcj.js → architectureDiagram-KFL7JDKH-JonPo-dN.js} +1 -1
- package/dist/chunks/{blockDiagram-ZYB65J3Q-DW1WkGMO.js → blockDiagram-ZYB65J3Q-Cvyjjlg1.js} +1 -1
- package/dist/chunks/{blockDiagram-ZYB65J3Q-D2anq3B5.js → blockDiagram-ZYB65J3Q-KOL-oLcr.js} +5 -5
- package/dist/chunks/{c4Diagram-AAMF2YG6-C7kDsbEV.js → c4Diagram-AAMF2YG6-B_xh9jXv.js} +1 -1
- package/dist/chunks/{c4Diagram-AAMF2YG6-D1nhaGMQ.js → c4Diagram-AAMF2YG6-Dk9gzcHg.js} +2 -2
- package/dist/chunks/channel-Cx51sV1C.js +1 -0
- package/dist/chunks/{channel-DqEwbkJ5.js → channel-pTWH5VlK.js} +1 -1
- package/dist/chunks/{chunk-ANTBXLJU-BGLg4kza.js → chunk-ANTBXLJU-BEt7iLHo.js} +1 -1
- package/dist/chunks/{chunk-ANTBXLJU-CK2uNBZ1.js → chunk-ANTBXLJU-DB6YRzoJ.js} +1 -1
- package/dist/chunks/{chunk-FHKO5MBM-U5X2zge_.js → chunk-FHKO5MBM-CDBkvH_8.js} +1 -1
- package/dist/chunks/{chunk-FHKO5MBM-Fi3oUOyz.js → chunk-FHKO5MBM-CwO7Y4L_.js} +1 -1
- package/dist/chunks/{chunk-GLLZNHP4-BLprlm7a.js → chunk-GLLZNHP4-C_LTdWfA.js} +1 -1
- package/dist/chunks/{chunk-GLLZNHP4-gwcRW5kd.js → chunk-GLLZNHP4-DM-tH8qN.js} +1 -1
- package/dist/chunks/{chunk-JBRWN2VN-DFbXAyDH.js → chunk-JBRWN2VN-CGkmp9iv.js} +1 -1
- package/dist/chunks/{chunk-JBRWN2VN-WfE9P3H9.js → chunk-JBRWN2VN-Cdrg7ipf.js} +4 -4
- package/dist/chunks/{chunk-LXBSTHXV-71APvWXI.js → chunk-LXBSTHXV-B6MJqnb9.js} +3 -3
- package/dist/chunks/{chunk-LXBSTHXV-Dxy3lBPi.js → chunk-LXBSTHXV-DY_risoK.js} +1 -1
- package/dist/chunks/{chunk-NRVI72HA-CwOhPG2b.js → chunk-NRVI72HA-CgHPPk9_.js} +1 -1
- package/dist/chunks/{chunk-NRVI72HA-DjbFjO3o.js → chunk-NRVI72HA-VCpZ8dT5.js} +1 -1
- package/dist/chunks/{chunk-OMD6QJNC-WKu2bzIs.js → chunk-OMD6QJNC-mLoP2am0.js} +1 -1
- package/dist/chunks/{chunk-OMD6QJNC-D4Voi3CS.js → chunk-OMD6QJNC-yURt4ZqD.js} +1 -1
- package/dist/chunks/{chunk-WVR4S24B-7uW2HbKb.js → chunk-WVR4S24B-C2gIEv2n.js} +1 -1
- package/dist/chunks/{chunk-WVR4S24B-DKGJcqAc.js → chunk-WVR4S24B-DuZUHyfp.js} +1 -1
- package/dist/chunks/{classDiagram-3BZAVTQC-BPY-1m6P.js → classDiagram-3BZAVTQC-0wK6utUW.js} +1 -1
- package/dist/chunks/{classDiagram-v2-QTMF73CY-C2gNsmci.js → classDiagram-3BZAVTQC-CR2TrZgY.js} +2 -2
- package/dist/chunks/{classDiagram-v2-QTMF73CY-BPY-1m6P.js → classDiagram-v2-QTMF73CY-0wK6utUW.js} +1 -1
- package/dist/chunks/{classDiagram-3BZAVTQC-C2gNsmci.js → classDiagram-v2-QTMF73CY-CR2TrZgY.js} +2 -2
- package/dist/chunks/clone-Ct5oP2ug.js +1 -0
- package/dist/chunks/{clone-DBXlyoxp.js → clone-GvES6CO7.js} +1 -1
- package/dist/chunks/{dagre-2BBEFEWP-C8zMRA3F.js → dagre-2BBEFEWP-BtEQwb5J.js} +6 -6
- package/dist/chunks/{dagre-2BBEFEWP-BcTumv5b.js → dagre-2BBEFEWP-ClSUmGwz.js} +1 -1
- package/dist/chunks/{dashboard-plus-yA1fkbzh.js → dashboard-plus-B10r1QRu.js} +65 -70
- package/dist/chunks/{dashboard-plus-Bh3rgtkD.js → dashboard-plus-BMWPXPIj.js} +5133 -5107
- package/dist/chunks/{diagram-4IRLE6MV-DUBGgzQy.js → diagram-4IRLE6MV-BDpp1460.js} +1 -1
- package/dist/chunks/{diagram-4IRLE6MV-Cbmi8Fyt.js → diagram-4IRLE6MV-C49eQphf.js} +4 -4
- package/dist/chunks/{diagram-GUPCWM2R-DSraOySI.js → diagram-GUPCWM2R-Cq1ov97D.js} +1 -1
- package/dist/chunks/{diagram-GUPCWM2R-BcbGeBZe.js → diagram-GUPCWM2R-LuvwZlWP.js} +3 -3
- package/dist/chunks/{diagram-RP2FKANI-m-6BWsEL.js → diagram-RP2FKANI-BLIHiui1.js} +1 -1
- package/dist/chunks/{diagram-RP2FKANI-BIcRcsy-.js → diagram-RP2FKANI-BZJN-7K9.js} +3 -3
- package/dist/chunks/{erDiagram-HZWUO2LU-DMYPXtez.js → erDiagram-HZWUO2LU-CPsjUGpr.js} +1 -1
- package/dist/chunks/{erDiagram-HZWUO2LU-lm0pJGHC.js → erDiagram-HZWUO2LU-Dtqq6c9d.js} +4 -4
- package/dist/chunks/{flowDiagram-THRYKUMA-Ddd_JDrQ.js → flowDiagram-THRYKUMA-B8gYyaTG.js} +5 -5
- package/dist/chunks/{flowDiagram-THRYKUMA-BxtQ5dvf.js → flowDiagram-THRYKUMA-DnwU9q2v.js} +1 -1
- package/dist/chunks/{ganttDiagram-WV7ZQ7D5-B9Kk1Q5C.js → ganttDiagram-WV7ZQ7D5-C_FBYO_8.js} +1 -1
- package/dist/chunks/{ganttDiagram-WV7ZQ7D5-BN1zCZwE.js → ganttDiagram-WV7ZQ7D5-GdDki4Q_.js} +3 -3
- package/dist/chunks/{gitGraph-ZV4HHKMB-B4DCa0__.js → gitGraph-ZV4HHKMB-DodL1Zrl.js} +1 -1
- package/dist/chunks/{gitGraph-ZV4HHKMB-xvxkWlWf.js → gitGraph-ZV4HHKMB-fUCqIWg0.js} +1 -1
- package/dist/chunks/{gitGraphDiagram-OJR772UL-ChFhW4jp.js → gitGraphDiagram-OJR772UL-B9jsyAKc.js} +1 -1
- package/dist/chunks/{gitGraphDiagram-OJR772UL-B6myB29E.js → gitGraphDiagram-OJR772UL-CRwVVClE.js} +4 -4
- package/dist/chunks/{graph-B6fgcGxx.js → graph-BH34NRXk.js} +1 -1
- package/dist/chunks/{graph-BF6LCaYH.js → graph-xRq7XmQC.js} +2 -2
- package/dist/chunks/{index-BwS-4oFh.js → index-D8tUqFuv.js} +14703 -14894
- package/dist/chunks/{index-CEBRe30q.js → index-DwpuFQtu.js} +213 -213
- package/dist/chunks/{info-63CPKGFF-C61AM7-q.js → info-63CPKGFF-CzlQqAhk.js} +1 -1
- package/dist/chunks/info-63CPKGFF-DZmt95MH.js +5 -0
- package/dist/chunks/{infoDiagram-DDUCL6P7-DpcIR8yV.js → infoDiagram-DDUCL6P7-_cNsLdvy.js} +1 -1
- package/dist/chunks/{infoDiagram-DDUCL6P7-Chr8bBqS.js → infoDiagram-DDUCL6P7-dPerJWnO.js} +2 -2
- package/dist/chunks/{journeyDiagram-FFXJYRFH-DNZogbvW.js → journeyDiagram-FFXJYRFH-Bvz2greh.js} +1 -1
- package/dist/chunks/{journeyDiagram-FFXJYRFH-BduSuiPB.js → journeyDiagram-FFXJYRFH-z8DYTQVE.js} +4 -4
- package/dist/chunks/{kanban-definition-KOZQBZVT-Cu7Lndxw.js → kanban-definition-KOZQBZVT-CNbQqeQV.js} +2 -2
- package/dist/chunks/{kanban-definition-KOZQBZVT-CUi8EJZV.js → kanban-definition-KOZQBZVT-KxzVSyOG.js} +1 -1
- package/dist/chunks/{layout-DLsbGTQz.js → layout-BAbpTM6P.js} +1 -1
- package/dist/chunks/{layout-Gthyofz2.js → layout-CDJPlONW.js} +4 -4
- package/dist/chunks/{linear-aBqM-t45.js → linear-BI3PREhR.js} +2 -2
- package/dist/chunks/{linear-Cm6KRnfp.js → linear-CN8g9v_Q.js} +1 -1
- package/dist/chunks/{mermaid-parser.core-DQqietT8.js → mermaid-parser.core-psOhnp_g.js} +2 -2
- package/dist/chunks/{mermaid-parser.core-IjhQ7eLj.js → mermaid-parser.core-xcQxi_jm.js} +11 -11
- package/dist/chunks/{mermaid.core-DUHba1Nm.js → mermaid.core-BAzkKVaz.js} +4 -4
- package/dist/chunks/{mermaid.core-lU3ermnX.js → mermaid.core-CvRAjOPA.js} +30 -30
- package/dist/chunks/{mindmap-definition-LNHGMQRG-CnRPozlJ.js → mindmap-definition-LNHGMQRG-DcUnODf3.js} +1 -1
- package/dist/chunks/{mindmap-definition-LNHGMQRG-CSWY7cEv.js → mindmap-definition-LNHGMQRG-duqAs_P0.js} +2 -2
- package/dist/chunks/{packet-HUATNLJX-DNiNJ_QS.js → packet-HUATNLJX-DMJ9cJ7_.js} +1 -1
- package/dist/chunks/{packet-HUATNLJX-e5GsrO0A.js → packet-HUATNLJX-_xaC-Mnx.js} +1 -1
- package/dist/chunks/pie-WTHONI2E-MAcq-iAM.js +5 -0
- package/dist/chunks/{pie-WTHONI2E-B0fw0fIH.js → pie-WTHONI2E-qncEw0OK.js} +1 -1
- package/dist/chunks/{pieDiagram-DBDJKBY4-Bgkas5gV.js → pieDiagram-DBDJKBY4-0F6DH4ah.js} +1 -1
- package/dist/chunks/{pieDiagram-DBDJKBY4-D8WvuNxG.js → pieDiagram-DBDJKBY4-BIZVIM67.js} +4 -4
- package/dist/chunks/{quadrantDiagram-YPSRARAO-BOwHTTTg.js → quadrantDiagram-YPSRARAO-BSEB2_Jk.js} +1 -1
- package/dist/chunks/{quadrantDiagram-YPSRARAO-B28GRBdC.js → quadrantDiagram-YPSRARAO-DYWhSOgC.js} +2 -2
- package/dist/chunks/radar-NJJJXTRR-Bbf79J2N.js +5 -0
- package/dist/chunks/{radar-NJJJXTRR-D4ESC23K.js → radar-NJJJXTRR-Cd4GsUl9.js} +1 -1
- package/dist/chunks/{requirementDiagram-EGVEC5DT-IVwVitxv.js → requirementDiagram-EGVEC5DT-B_lndsFG.js} +1 -1
- package/dist/chunks/{requirementDiagram-EGVEC5DT-CLbeqYB0.js → requirementDiagram-EGVEC5DT-CxAqR62-.js} +3 -3
- package/dist/chunks/{sankeyDiagram-HRAUVNP4-CxEb7Ili.js → sankeyDiagram-HRAUVNP4-BSpJVLiJ.js} +2 -2
- package/dist/chunks/{sankeyDiagram-HRAUVNP4-cBbImrbs.js → sankeyDiagram-HRAUVNP4-DU21EcHr.js} +1 -1
- package/dist/chunks/{sequenceDiagram-4MX5Z3NR-Bd5Er185.js → sequenceDiagram-4MX5Z3NR-BPzYnPk7.js} +1 -1
- package/dist/chunks/{sequenceDiagram-4MX5Z3NR-Cfs33Jna.js → sequenceDiagram-4MX5Z3NR-GNnlAP-V.js} +3 -3
- package/dist/chunks/{stateDiagram-UUKSUZ4H-DcpSvFtY.js → stateDiagram-UUKSUZ4H-DV7tDKxa.js} +4 -4
- package/dist/chunks/{stateDiagram-UUKSUZ4H-TvBHkgHV.js → stateDiagram-UUKSUZ4H-h1iPNm2A.js} +1 -1
- package/dist/chunks/{stateDiagram-v2-EYPG3UTE-D-j9wmD4.js → stateDiagram-v2-EYPG3UTE-CSJJtpE9.js} +2 -2
- package/dist/chunks/{stateDiagram-v2-EYPG3UTE-DN3C1cMv.js → stateDiagram-v2-EYPG3UTE-D2GBbdU2.js} +1 -1
- package/dist/chunks/{timeline-definition-3HZDQTIS-BuXUJ-V7.js → timeline-definition-3HZDQTIS-4ikiRpT2.js} +1 -1
- package/dist/chunks/{timeline-definition-3HZDQTIS-Br7UScbk.js → timeline-definition-3HZDQTIS-BQOjQU9_.js} +2 -2
- package/dist/chunks/{treemap-75Q7IDZK-xJ9nbk2Y.js → treemap-75Q7IDZK-BNTdZgSS.js} +1 -1
- package/dist/chunks/{treemap-75Q7IDZK-Dzq1jUW6.js → treemap-75Q7IDZK-Do9TU3vq.js} +1 -1
- package/dist/chunks/{xychartDiagram-FDP5SA34-_k9wVk1s.js → xychartDiagram-FDP5SA34-BgdOgAxv.js} +1 -1
- package/dist/chunks/{xychartDiagram-FDP5SA34-Cghmm2Lo.js → xychartDiagram-FDP5SA34-DBZfRejf.js} +3 -3
- package/dist/dashboard/index.cjs +1 -1
- package/dist/dashboard/index.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +3 -3
- package/dist/style.css +1 -1
- package/dist/surfboard/index.cjs +1 -1
- package/dist/surfboard/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunks/channel-BL1J4mcN.js +0 -1
- package/dist/chunks/clone-BbY68YHs.js +0 -1
- package/dist/chunks/info-63CPKGFF-D8cIYcqe.js +0 -5
- package/dist/chunks/pie-WTHONI2E-BUK-0d24.js +0 -5
- package/dist/chunks/radar-NJJJXTRR-Dn-O0H10.js +0 -5
|
@@ -1,49 +1,49 @@
|
|
|
1
|
-
"use strict";const e=require("react/jsx-runtime"),s=require("./index-
|
|
1
|
+
"use strict";const e=require("react/jsx-runtime"),s=require("./index-DwpuFQtu.js"),I=require("react");require("react-dom");function sa(t){const a=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const n in t)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(a,n,r.get?r:{enumerable:!0,get:()=>t[n]})}}return a.default=t,Object.freeze(a)}const ke=sa(I);/**
|
|
2
2
|
* @license lucide-react v0.453.0 - ISC
|
|
3
3
|
*
|
|
4
4
|
* This source code is licensed under the ISC license.
|
|
5
5
|
* See the LICENSE file in the root directory of this source tree.
|
|
6
|
-
*/const
|
|
6
|
+
*/const ta=s.createLucideIcon("ArrowDown10",[["path",{d:"m3 16 4 4 4-4",key:"1co6wj"}],["path",{d:"M7 20V4",key:"1yoxec"}],["path",{d:"M17 10V4h-2",key:"zcsr5x"}],["path",{d:"M15 10h4",key:"id2lce"}],["rect",{x:"15",y:"14",width:"4",height:"6",ry:"2",key:"33xykx"}]]);/**
|
|
7
7
|
* @license lucide-react v0.453.0 - ISC
|
|
8
8
|
*
|
|
9
9
|
* This source code is licensed under the ISC license.
|
|
10
10
|
* See the LICENSE file in the root directory of this source tree.
|
|
11
|
-
*/const
|
|
11
|
+
*/const aa=s.createLucideIcon("ArrowDownZA",[["path",{d:"m3 16 4 4 4-4",key:"1co6wj"}],["path",{d:"M7 4v16",key:"1glfcx"}],["path",{d:"M15 4h5l-5 6h5",key:"8asdl1"}],["path",{d:"M15 20v-3.5a2.5 2.5 0 0 1 5 0V20",key:"r6l5cz"}],["path",{d:"M20 18h-5",key:"18j1r2"}]]);/**
|
|
12
12
|
* @license lucide-react v0.453.0 - ISC
|
|
13
13
|
*
|
|
14
14
|
* This source code is licensed under the ISC license.
|
|
15
15
|
* See the LICENSE file in the root directory of this source tree.
|
|
16
|
-
*/const
|
|
16
|
+
*/const na=s.createLucideIcon("ArrowLeftRight",[["path",{d:"M8 3 4 7l4 4",key:"9rb6wj"}],["path",{d:"M4 7h16",key:"6tx8e3"}],["path",{d:"m16 21 4-4-4-4",key:"siv7j2"}],["path",{d:"M20 17H4",key:"h6l3hr"}]]);/**
|
|
17
17
|
* @license lucide-react v0.453.0 - ISC
|
|
18
18
|
*
|
|
19
19
|
* This source code is licensed under the ISC license.
|
|
20
20
|
* See the LICENSE file in the root directory of this source tree.
|
|
21
|
-
*/const
|
|
21
|
+
*/const ra=s.createLucideIcon("ArrowUp01",[["path",{d:"m3 8 4-4 4 4",key:"11wl7u"}],["path",{d:"M7 4v16",key:"1glfcx"}],["rect",{x:"15",y:"4",width:"4",height:"6",ry:"2",key:"1bwicg"}],["path",{d:"M17 20v-6h-2",key:"1qp1so"}],["path",{d:"M15 20h4",key:"1j968p"}]]);/**
|
|
22
22
|
* @license lucide-react v0.453.0 - ISC
|
|
23
23
|
*
|
|
24
24
|
* This source code is licensed under the ISC license.
|
|
25
25
|
* See the LICENSE file in the root directory of this source tree.
|
|
26
|
-
*/const
|
|
26
|
+
*/const la=s.createLucideIcon("ArrowUpAZ",[["path",{d:"m3 8 4-4 4 4",key:"11wl7u"}],["path",{d:"M7 4v16",key:"1glfcx"}],["path",{d:"M20 8h-5",key:"1vsyxs"}],["path",{d:"M15 10V6.5a2.5 2.5 0 0 1 5 0V10",key:"ag13bf"}],["path",{d:"M15 14h5l-5 6h5",key:"ur5jdg"}]]);/**
|
|
27
27
|
* @license lucide-react v0.453.0 - ISC
|
|
28
28
|
*
|
|
29
29
|
* This source code is licensed under the ISC license.
|
|
30
30
|
* See the LICENSE file in the root directory of this source tree.
|
|
31
|
-
*/const
|
|
31
|
+
*/const oa=s.createLucideIcon("Blocks",[["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["path",{d:"M10 21V8a1 1 0 0 0-1-1H4a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-5a1 1 0 0 0-1-1H3",key:"1fpvtg"}]]);/**
|
|
32
32
|
* @license lucide-react v0.453.0 - ISC
|
|
33
33
|
*
|
|
34
34
|
* This source code is licensed under the ISC license.
|
|
35
35
|
* See the LICENSE file in the root directory of this source tree.
|
|
36
|
-
*/const
|
|
36
|
+
*/const ia=s.createLucideIcon("BookOpenText",[["path",{d:"M12 7v14",key:"1akyts"}],["path",{d:"M16 12h2",key:"7q9ll5"}],["path",{d:"M16 8h2",key:"msurwy"}],["path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z",key:"ruj8y"}],["path",{d:"M6 12h2",key:"32wvfc"}],["path",{d:"M6 8h2",key:"30oboj"}]]);/**
|
|
37
37
|
* @license lucide-react v0.453.0 - ISC
|
|
38
38
|
*
|
|
39
39
|
* This source code is licensed under the ISC license.
|
|
40
40
|
* See the LICENSE file in the root directory of this source tree.
|
|
41
|
-
*/const
|
|
41
|
+
*/const ca=s.createLucideIcon("Box",[["path",{d:"M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z",key:"hh9hay"}],["path",{d:"m3.3 7 8.7 5 8.7-5",key:"g66t2b"}],["path",{d:"M12 22V12",key:"d0xqtd"}]]);/**
|
|
42
42
|
* @license lucide-react v0.453.0 - ISC
|
|
43
43
|
*
|
|
44
44
|
* This source code is licensed under the ISC license.
|
|
45
45
|
* See the LICENSE file in the root directory of this source tree.
|
|
46
|
-
*/const
|
|
46
|
+
*/const da=s.createLucideIcon("Braces",[["path",{d:"M8 3H7a2 2 0 0 0-2 2v5a2 2 0 0 1-2 2 2 2 0 0 1 2 2v5c0 1.1.9 2 2 2h1",key:"ezmyqa"}],["path",{d:"M16 21h1a2 2 0 0 0 2-2v-5c0-1.1.9-2 2-2a2 2 0 0 1-2-2V5a2 2 0 0 0-2-2h-1",key:"e1hn23"}]]);/**
|
|
47
47
|
* @license lucide-react v0.453.0 - ISC
|
|
48
48
|
*
|
|
49
49
|
* This source code is licensed under the ISC license.
|
|
@@ -58,7 +58,7 @@
|
|
|
58
58
|
*
|
|
59
59
|
* This source code is licensed under the ISC license.
|
|
60
60
|
* See the LICENSE file in the root directory of this source tree.
|
|
61
|
-
*/const
|
|
61
|
+
*/const ua=s.createLucideIcon("CircleCheckBig",[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]]);/**
|
|
62
62
|
* @license lucide-react v0.453.0 - ISC
|
|
63
63
|
*
|
|
64
64
|
* This source code is licensed under the ISC license.
|
|
@@ -68,27 +68,27 @@
|
|
|
68
68
|
*
|
|
69
69
|
* This source code is licensed under the ISC license.
|
|
70
70
|
* See the LICENSE file in the root directory of this source tree.
|
|
71
|
-
*/const
|
|
71
|
+
*/const Oe=s.createLucideIcon("Code",[["polyline",{points:"16 18 22 12 16 6",key:"z7tu5w"}],["polyline",{points:"8 6 2 12 8 18",key:"1eg1df"}]]);/**
|
|
72
72
|
* @license lucide-react v0.453.0 - ISC
|
|
73
73
|
*
|
|
74
74
|
* This source code is licensed under the ISC license.
|
|
75
75
|
* See the LICENSE file in the root directory of this source tree.
|
|
76
|
-
*/const
|
|
76
|
+
*/const ma=s.createLucideIcon("Columns3",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"M15 3v18",key:"14nvp0"}]]);/**
|
|
77
77
|
* @license lucide-react v0.453.0 - ISC
|
|
78
78
|
*
|
|
79
79
|
* This source code is licensed under the ISC license.
|
|
80
80
|
* See the LICENSE file in the root directory of this source tree.
|
|
81
|
-
*/const
|
|
81
|
+
*/const ha=s.createLucideIcon("Component",[["path",{d:"M15.536 11.293a1 1 0 0 0 0 1.414l2.376 2.377a1 1 0 0 0 1.414 0l2.377-2.377a1 1 0 0 0 0-1.414l-2.377-2.377a1 1 0 0 0-1.414 0z",key:"1uwlt4"}],["path",{d:"M2.297 11.293a1 1 0 0 0 0 1.414l2.377 2.377a1 1 0 0 0 1.414 0l2.377-2.377a1 1 0 0 0 0-1.414L6.088 8.916a1 1 0 0 0-1.414 0z",key:"10291m"}],["path",{d:"M8.916 17.912a1 1 0 0 0 0 1.415l2.377 2.376a1 1 0 0 0 1.414 0l2.377-2.376a1 1 0 0 0 0-1.415l-2.377-2.376a1 1 0 0 0-1.414 0z",key:"1tqoq1"}],["path",{d:"M8.916 4.674a1 1 0 0 0 0 1.414l2.377 2.376a1 1 0 0 0 1.414 0l2.377-2.376a1 1 0 0 0 0-1.414l-2.377-2.377a1 1 0 0 0-1.414 0z",key:"1x6lto"}]]);/**
|
|
82
82
|
* @license lucide-react v0.453.0 - ISC
|
|
83
83
|
*
|
|
84
84
|
* This source code is licensed under the ISC license.
|
|
85
85
|
* See the LICENSE file in the root directory of this source tree.
|
|
86
|
-
*/const
|
|
86
|
+
*/const xa=s.createLucideIcon("CopyPlus",[["line",{x1:"15",x2:"15",y1:"12",y2:"18",key:"1p7wdc"}],["line",{x1:"12",x2:"18",y1:"15",y2:"15",key:"1nscbv"}],["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]]);/**
|
|
87
87
|
* @license lucide-react v0.453.0 - ISC
|
|
88
88
|
*
|
|
89
89
|
* This source code is licensed under the ISC license.
|
|
90
90
|
* See the LICENSE file in the root directory of this source tree.
|
|
91
|
-
*/const
|
|
91
|
+
*/const pa=s.createLucideIcon("DatabaseZap",[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 15 21.84",key:"14ibmq"}],["path",{d:"M21 5V8",key:"1marbg"}],["path",{d:"M21 12L18 17H22L19 22",key:"zafso"}],["path",{d:"M3 12A9 3 0 0 0 14.59 14.87",key:"1y4wr8"}]]);/**
|
|
92
92
|
* @license lucide-react v0.453.0 - ISC
|
|
93
93
|
*
|
|
94
94
|
* This source code is licensed under the ISC license.
|
|
@@ -98,47 +98,42 @@
|
|
|
98
98
|
*
|
|
99
99
|
* This source code is licensed under the ISC license.
|
|
100
100
|
* See the LICENSE file in the root directory of this source tree.
|
|
101
|
-
*/const
|
|
101
|
+
*/const fa=s.createLucideIcon("EyeClosed",[["path",{d:"m15 18-.722-3.25",key:"1j64jw"}],["path",{d:"M2 8a10.645 10.645 0 0 0 20 0",key:"1e7gxb"}],["path",{d:"m20 15-1.726-2.05",key:"1cnuld"}],["path",{d:"m4 15 1.726-2.05",key:"1dsqqd"}],["path",{d:"m9 18 .722-3.25",key:"ypw2yx"}]]);/**
|
|
102
102
|
* @license lucide-react v0.453.0 - ISC
|
|
103
103
|
*
|
|
104
104
|
* This source code is licensed under the ISC license.
|
|
105
105
|
* See the LICENSE file in the root directory of this source tree.
|
|
106
|
-
*/const
|
|
106
|
+
*/const ga=s.createLucideIcon("FileCode2",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"m5 12-3 3 3 3",key:"oke12k"}],["path",{d:"m9 18 3-3-3-3",key:"112psh"}]]);/**
|
|
107
107
|
* @license lucide-react v0.453.0 - ISC
|
|
108
108
|
*
|
|
109
109
|
* This source code is licensed under the ISC license.
|
|
110
110
|
* See the LICENSE file in the root directory of this source tree.
|
|
111
|
-
*/const
|
|
111
|
+
*/const ja=s.createLucideIcon("FileJson2",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M4 12a1 1 0 0 0-1 1v1a1 1 0 0 1-1 1 1 1 0 0 1 1 1v1a1 1 0 0 0 1 1",key:"fq0c9t"}],["path",{d:"M8 18a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1 1 1 0 0 1-1-1v-1a1 1 0 0 0-1-1",key:"4gibmv"}]]);/**
|
|
112
112
|
* @license lucide-react v0.453.0 - ISC
|
|
113
113
|
*
|
|
114
114
|
* This source code is licensed under the ISC license.
|
|
115
115
|
* See the LICENSE file in the root directory of this source tree.
|
|
116
|
-
*/const
|
|
116
|
+
*/const ba=s.createLucideIcon("Fingerprint",[["path",{d:"M12 10a2 2 0 0 0-2 2c0 1.02-.1 2.51-.26 4",key:"1nerag"}],["path",{d:"M14 13.12c0 2.38 0 6.38-1 8.88",key:"o46ks0"}],["path",{d:"M17.29 21.02c.12-.6.43-2.3.5-3.02",key:"ptglia"}],["path",{d:"M2 12a10 10 0 0 1 18-6",key:"ydlgp0"}],["path",{d:"M2 16h.01",key:"1gqxmh"}],["path",{d:"M21.8 16c.2-2 .131-5.354 0-6",key:"drycrb"}],["path",{d:"M5 19.5C5.5 18 6 15 6 12a6 6 0 0 1 .34-2",key:"1tidbn"}],["path",{d:"M8.65 22c.21-.66.45-1.32.57-2",key:"13wd9y"}],["path",{d:"M9 6.8a6 6 0 0 1 9 5.2v2",key:"1fr1j5"}]]);/**
|
|
117
117
|
* @license lucide-react v0.453.0 - ISC
|
|
118
118
|
*
|
|
119
119
|
* This source code is licensed under the ISC license.
|
|
120
120
|
* See the LICENSE file in the root directory of this source tree.
|
|
121
|
-
*/const
|
|
121
|
+
*/const ya=s.createLucideIcon("GitCompareArrows",[["circle",{cx:"5",cy:"6",r:"3",key:"1qnov2"}],["path",{d:"M12 6h5a2 2 0 0 1 2 2v7",key:"1yj91y"}],["path",{d:"m15 9-3-3 3-3",key:"1lwv8l"}],["circle",{cx:"19",cy:"18",r:"3",key:"1qljk2"}],["path",{d:"M12 18H7a2 2 0 0 1-2-2V9",key:"16sdep"}],["path",{d:"m9 15 3 3-3 3",key:"1m3kbl"}]]);/**
|
|
122
122
|
* @license lucide-react v0.453.0 - ISC
|
|
123
123
|
*
|
|
124
124
|
* This source code is licensed under the ISC license.
|
|
125
125
|
* See the LICENSE file in the root directory of this source tree.
|
|
126
|
-
*/const
|
|
126
|
+
*/const va=s.createLucideIcon("Glasses",[["circle",{cx:"6",cy:"15",r:"4",key:"vux9w4"}],["circle",{cx:"18",cy:"15",r:"4",key:"18o8ve"}],["path",{d:"M14 15a2 2 0 0 0-2-2 2 2 0 0 0-2 2",key:"1ag4bs"}],["path",{d:"M2.5 13 5 7c.7-1.3 1.4-2 3-2",key:"1hm1gs"}],["path",{d:"M21.5 13 19 7c-.7-1.3-1.5-2-3-2",key:"1r31ai"}]]);/**
|
|
127
127
|
* @license lucide-react v0.453.0 - ISC
|
|
128
128
|
*
|
|
129
129
|
* This source code is licensed under the ISC license.
|
|
130
130
|
* See the LICENSE file in the root directory of this source tree.
|
|
131
|
-
*/const
|
|
131
|
+
*/const ns=s.createLucideIcon("Grid3x3",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 9h18",key:"1pudct"}],["path",{d:"M3 15h18",key:"5xshup"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"M15 3v18",key:"14nvp0"}]]);/**
|
|
132
132
|
* @license lucide-react v0.453.0 - ISC
|
|
133
133
|
*
|
|
134
134
|
* This source code is licensed under the ISC license.
|
|
135
135
|
* See the LICENSE file in the root directory of this source tree.
|
|
136
|
-
*/const
|
|
137
|
-
* @license lucide-react v0.453.0 - ISC
|
|
138
|
-
*
|
|
139
|
-
* This source code is licensed under the ISC license.
|
|
140
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
141
|
-
*/const Sa=s.createLucideIcon("Hammer",[["path",{d:"m15 12-8.373 8.373a1 1 0 1 1-3-3L12 9",key:"eefl8a"}],["path",{d:"m18 15 4-4",key:"16gjal"}],["path",{d:"m21.5 11.5-1.914-1.914A2 2 0 0 1 19 8.172V7l-2.26-2.26a6 6 0 0 0-4.202-1.756L9 2.96l.92.82A6.18 6.18 0 0 1 12 8.4V10l2 2h1.172a2 2 0 0 1 1.414.586L18.5 14.5",key:"b7pghm"}]]);/**
|
|
136
|
+
*/const Na=s.createLucideIcon("Hammer",[["path",{d:"m15 12-8.373 8.373a1 1 0 1 1-3-3L12 9",key:"eefl8a"}],["path",{d:"m18 15 4-4",key:"16gjal"}],["path",{d:"m21.5 11.5-1.914-1.914A2 2 0 0 1 19 8.172V7l-2.26-2.26a6 6 0 0 0-4.202-1.756L9 2.96l.92.82A6.18 6.18 0 0 1 12 8.4V10l2 2h1.172a2 2 0 0 1 1.414.586L18.5 14.5",key:"b7pghm"}]]);/**
|
|
142
137
|
* @license lucide-react v0.453.0 - ISC
|
|
143
138
|
*
|
|
144
139
|
* This source code is licensed under the ISC license.
|
|
@@ -148,37 +143,37 @@
|
|
|
148
143
|
*
|
|
149
144
|
* This source code is licensed under the ISC license.
|
|
150
145
|
* See the LICENSE file in the root directory of this source tree.
|
|
151
|
-
*/const
|
|
146
|
+
*/const Ca=s.createLucideIcon("LayoutList",[["rect",{width:"7",height:"7",x:"3",y:"3",rx:"1",key:"1g98yp"}],["rect",{width:"7",height:"7",x:"3",y:"14",rx:"1",key:"1bb6yr"}],["path",{d:"M14 4h7",key:"3xa0d5"}],["path",{d:"M14 9h7",key:"1icrd9"}],["path",{d:"M14 15h7",key:"1mj8o2"}],["path",{d:"M14 20h7",key:"11slyb"}]]);/**
|
|
152
147
|
* @license lucide-react v0.453.0 - ISC
|
|
153
148
|
*
|
|
154
149
|
* This source code is licensed under the ISC license.
|
|
155
150
|
* See the LICENSE file in the root directory of this source tree.
|
|
156
|
-
*/const
|
|
151
|
+
*/const Sa=s.createLucideIcon("ListEnd",[["path",{d:"M16 12H3",key:"1a2rj7"}],["path",{d:"M16 6H3",key:"1wxfjs"}],["path",{d:"M10 18H3",key:"13769t"}],["path",{d:"M21 6v10a2 2 0 0 1-2 2h-5",key:"ilrcs8"}],["path",{d:"m16 16-2 2 2 2",key:"kkc6pm"}]]);/**
|
|
157
152
|
* @license lucide-react v0.453.0 - ISC
|
|
158
153
|
*
|
|
159
154
|
* This source code is licensed under the ISC license.
|
|
160
155
|
* See the LICENSE file in the root directory of this source tree.
|
|
161
|
-
*/const
|
|
156
|
+
*/const wa=s.createLucideIcon("ListStart",[["path",{d:"M16 12H3",key:"1a2rj7"}],["path",{d:"M16 18H3",key:"12xzn7"}],["path",{d:"M10 6H3",key:"lf8lx7"}],["path",{d:"M21 18V8a2 2 0 0 0-2-2h-5",key:"1hghli"}],["path",{d:"m16 8-2-2 2-2",key:"160uvd"}]]);/**
|
|
162
157
|
* @license lucide-react v0.453.0 - ISC
|
|
163
158
|
*
|
|
164
159
|
* This source code is licensed under the ISC license.
|
|
165
160
|
* See the LICENSE file in the root directory of this source tree.
|
|
166
|
-
*/const
|
|
161
|
+
*/const Da=s.createLucideIcon("ListX",[["path",{d:"M11 12H3",key:"51ecnj"}],["path",{d:"M16 6H3",key:"1wxfjs"}],["path",{d:"M16 18H3",key:"12xzn7"}],["path",{d:"m19 10-4 4",key:"1tz659"}],["path",{d:"m15 10 4 4",key:"1n7nei"}]]);/**
|
|
167
162
|
* @license lucide-react v0.453.0 - ISC
|
|
168
163
|
*
|
|
169
164
|
* This source code is licensed under the ISC license.
|
|
170
165
|
* See the LICENSE file in the root directory of this source tree.
|
|
171
|
-
*/const
|
|
166
|
+
*/const ka=s.createLucideIcon("List",[["path",{d:"M3 12h.01",key:"nlz23k"}],["path",{d:"M3 18h.01",key:"1tta3j"}],["path",{d:"M3 6h.01",key:"1rqtza"}],["path",{d:"M8 12h13",key:"1za7za"}],["path",{d:"M8 18h13",key:"1lx6n3"}],["path",{d:"M8 6h13",key:"ik3vkj"}]]);/**
|
|
172
167
|
* @license lucide-react v0.453.0 - ISC
|
|
173
168
|
*
|
|
174
169
|
* This source code is licensed under the ISC license.
|
|
175
170
|
* See the LICENSE file in the root directory of this source tree.
|
|
176
|
-
*/const
|
|
171
|
+
*/const Ta=s.createLucideIcon("Lock",[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4",key:"fwvmzm"}]]);/**
|
|
177
172
|
* @license lucide-react v0.453.0 - ISC
|
|
178
173
|
*
|
|
179
174
|
* This source code is licensed under the ISC license.
|
|
180
175
|
* See the LICENSE file in the root directory of this source tree.
|
|
181
|
-
*/const
|
|
176
|
+
*/const Ea=s.createLucideIcon("Logs",[["path",{d:"M13 12h8",key:"h98zly"}],["path",{d:"M13 18h8",key:"oe0vm4"}],["path",{d:"M13 6h8",key:"15sg57"}],["path",{d:"M3 12h1",key:"lp3yf2"}],["path",{d:"M3 18h1",key:"1eiwyy"}],["path",{d:"M3 6h1",key:"rgxa97"}],["path",{d:"M8 12h1",key:"1con00"}],["path",{d:"M8 18h1",key:"13wk12"}],["path",{d:"M8 6h1",key:"tn6mkg"}]]);/**
|
|
182
177
|
* @license lucide-react v0.453.0 - ISC
|
|
183
178
|
*
|
|
184
179
|
* This source code is licensed under the ISC license.
|
|
@@ -188,27 +183,27 @@
|
|
|
188
183
|
*
|
|
189
184
|
* This source code is licensed under the ISC license.
|
|
190
185
|
* See the LICENSE file in the root directory of this source tree.
|
|
191
|
-
*/const
|
|
186
|
+
*/const Ia=s.createLucideIcon("Menu",[["line",{x1:"4",x2:"20",y1:"12",y2:"12",key:"1e0a9i"}],["line",{x1:"4",x2:"20",y1:"6",y2:"6",key:"1owob3"}],["line",{x1:"4",x2:"20",y1:"18",y2:"18",key:"yk5zj1"}]]);/**
|
|
192
187
|
* @license lucide-react v0.453.0 - ISC
|
|
193
188
|
*
|
|
194
189
|
* This source code is licensed under the ISC license.
|
|
195
190
|
* See the LICENSE file in the root directory of this source tree.
|
|
196
|
-
*/const
|
|
191
|
+
*/const Aa=s.createLucideIcon("MessageCircleMore",[["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z",key:"vv11sd"}],["path",{d:"M8 12h.01",key:"czm47f"}],["path",{d:"M12 12h.01",key:"1mp3jc"}],["path",{d:"M16 12h.01",key:"1l6xoz"}]]);/**
|
|
197
192
|
* @license lucide-react v0.453.0 - ISC
|
|
198
193
|
*
|
|
199
194
|
* This source code is licensed under the ISC license.
|
|
200
195
|
* See the LICENSE file in the root directory of this source tree.
|
|
201
|
-
*/const
|
|
196
|
+
*/const Ma=s.createLucideIcon("MessageCircle",[["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z",key:"vv11sd"}]]);/**
|
|
202
197
|
* @license lucide-react v0.453.0 - ISC
|
|
203
198
|
*
|
|
204
199
|
* This source code is licensed under the ISC license.
|
|
205
200
|
* See the LICENSE file in the root directory of this source tree.
|
|
206
|
-
*/const
|
|
201
|
+
*/const La=s.createLucideIcon("MessageSquareWarning",[["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}],["path",{d:"M12 7v2",key:"stiyo7"}],["path",{d:"M12 13h.01",key:"y0uutt"}]]);/**
|
|
207
202
|
* @license lucide-react v0.453.0 - ISC
|
|
208
203
|
*
|
|
209
204
|
* This source code is licensed under the ISC license.
|
|
210
205
|
* See the LICENSE file in the root directory of this source tree.
|
|
211
|
-
*/const
|
|
206
|
+
*/const Ra=s.createLucideIcon("Moon",[["path",{d:"M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z",key:"a7tn18"}]]);/**
|
|
212
207
|
* @license lucide-react v0.453.0 - ISC
|
|
213
208
|
*
|
|
214
209
|
* This source code is licensed under the ISC license.
|
|
@@ -223,37 +218,37 @@
|
|
|
223
218
|
*
|
|
224
219
|
* This source code is licensed under the ISC license.
|
|
225
220
|
* See the LICENSE file in the root directory of this source tree.
|
|
226
|
-
*/const
|
|
221
|
+
*/const Oa=s.createLucideIcon("Network",[["rect",{x:"16",y:"16",width:"6",height:"6",rx:"1",key:"4q2zg0"}],["rect",{x:"2",y:"16",width:"6",height:"6",rx:"1",key:"8cvhb9"}],["rect",{x:"9",y:"2",width:"6",height:"6",rx:"1",key:"1egb70"}],["path",{d:"M5 16v-3a1 1 0 0 1 1-1h12a1 1 0 0 1 1 1v3",key:"1jsf9p"}],["path",{d:"M12 12V8",key:"2874zd"}]]);/**
|
|
227
222
|
* @license lucide-react v0.453.0 - ISC
|
|
228
223
|
*
|
|
229
224
|
* This source code is licensed under the ISC license.
|
|
230
225
|
* See the LICENSE file in the root directory of this source tree.
|
|
231
|
-
*/const
|
|
226
|
+
*/const Ba=s.createLucideIcon("Palette",[["circle",{cx:"13.5",cy:"6.5",r:".5",fill:"currentColor",key:"1okk4w"}],["circle",{cx:"17.5",cy:"10.5",r:".5",fill:"currentColor",key:"f64h9f"}],["circle",{cx:"8.5",cy:"7.5",r:".5",fill:"currentColor",key:"fotxhn"}],["circle",{cx:"6.5",cy:"12.5",r:".5",fill:"currentColor",key:"qy21gx"}],["path",{d:"M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10c.926 0 1.648-.746 1.648-1.688 0-.437-.18-.835-.437-1.125-.29-.289-.438-.652-.438-1.125a1.64 1.64 0 0 1 1.668-1.668h1.996c3.051 0 5.555-2.503 5.555-5.554C21.965 6.012 17.461 2 12 2z",key:"12rzf8"}]]);/**
|
|
232
227
|
* @license lucide-react v0.453.0 - ISC
|
|
233
228
|
*
|
|
234
229
|
* This source code is licensed under the ISC license.
|
|
235
230
|
* See the LICENSE file in the root directory of this source tree.
|
|
236
|
-
*/const
|
|
231
|
+
*/const Fa=s.createLucideIcon("PenLine",[["path",{d:"M12 20h9",key:"t2du7b"}],["path",{d:"M16.376 3.622a1 1 0 0 1 3.002 3.002L7.368 18.635a2 2 0 0 1-.855.506l-2.872.838a.5.5 0 0 1-.62-.62l.838-2.872a2 2 0 0 1 .506-.854z",key:"1ykcvy"}]]);/**
|
|
237
232
|
* @license lucide-react v0.453.0 - ISC
|
|
238
233
|
*
|
|
239
234
|
* This source code is licensed under the ISC license.
|
|
240
235
|
* See the LICENSE file in the root directory of this source tree.
|
|
241
|
-
*/const
|
|
236
|
+
*/const Pa=s.createLucideIcon("Plug",[["path",{d:"M12 22v-5",key:"1ega77"}],["path",{d:"M9 8V2",key:"14iosj"}],["path",{d:"M15 8V2",key:"18g5xt"}],["path",{d:"M18 8v5a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V8Z",key:"osxo6l"}]]);/**
|
|
242
237
|
* @license lucide-react v0.453.0 - ISC
|
|
243
238
|
*
|
|
244
239
|
* This source code is licensed under the ISC license.
|
|
245
240
|
* See the LICENSE file in the root directory of this source tree.
|
|
246
|
-
*/const
|
|
241
|
+
*/const st=s.createLucideIcon("RefreshCw",[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]]);/**
|
|
247
242
|
* @license lucide-react v0.453.0 - ISC
|
|
248
243
|
*
|
|
249
244
|
* This source code is licensed under the ISC license.
|
|
250
245
|
* See the LICENSE file in the root directory of this source tree.
|
|
251
|
-
*/const
|
|
246
|
+
*/const za=s.createLucideIcon("Rows3",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M21 9H3",key:"1338ky"}],["path",{d:"M21 15H3",key:"9uk58r"}]]);/**
|
|
252
247
|
* @license lucide-react v0.453.0 - ISC
|
|
253
248
|
*
|
|
254
249
|
* This source code is licensed under the ISC license.
|
|
255
250
|
* See the LICENSE file in the root directory of this source tree.
|
|
256
|
-
*/const
|
|
251
|
+
*/const gs=s.createLucideIcon("Save",[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]]);/**
|
|
257
252
|
* @license lucide-react v0.453.0 - ISC
|
|
258
253
|
*
|
|
259
254
|
* This source code is licensed under the ISC license.
|
|
@@ -268,57 +263,57 @@
|
|
|
268
263
|
*
|
|
269
264
|
* This source code is licensed under the ISC license.
|
|
270
265
|
* See the LICENSE file in the root directory of this source tree.
|
|
271
|
-
*/const
|
|
266
|
+
*/const Va=s.createLucideIcon("Share",[["path",{d:"M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8",key:"1b2hhj"}],["polyline",{points:"16 6 12 2 8 6",key:"m901s6"}],["line",{x1:"12",x2:"12",y1:"2",y2:"15",key:"1p0rca"}]]);/**
|
|
272
267
|
* @license lucide-react v0.453.0 - ISC
|
|
273
268
|
*
|
|
274
269
|
* This source code is licensed under the ISC license.
|
|
275
270
|
* See the LICENSE file in the root directory of this source tree.
|
|
276
|
-
*/const
|
|
271
|
+
*/const _a=s.createLucideIcon("ShieldX",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m14.5 9.5-5 5",key:"17q4r4"}],["path",{d:"m9.5 9.5 5 5",key:"18nt4w"}]]);/**
|
|
277
272
|
* @license lucide-react v0.453.0 - ISC
|
|
278
273
|
*
|
|
279
274
|
* This source code is licensed under the ISC license.
|
|
280
275
|
* See the LICENSE file in the root directory of this source tree.
|
|
281
|
-
*/const
|
|
276
|
+
*/const Ua=s.createLucideIcon("Shrink",[["path",{d:"m15 15 6 6m-6-6v4.8m0-4.8h4.8",key:"17vawe"}],["path",{d:"M9 19.8V15m0 0H4.2M9 15l-6 6",key:"chjx8e"}],["path",{d:"M15 4.2V9m0 0h4.8M15 9l6-6",key:"lav6yq"}],["path",{d:"M9 4.2V9m0 0H4.2M9 9 3 3",key:"1pxi2q"}]]);/**
|
|
282
277
|
* @license lucide-react v0.453.0 - ISC
|
|
283
278
|
*
|
|
284
279
|
* This source code is licensed under the ISC license.
|
|
285
280
|
* See the LICENSE file in the root directory of this source tree.
|
|
286
|
-
*/const
|
|
281
|
+
*/const tt=s.createLucideIcon("Sigma",[["path",{d:"M18 7V5a1 1 0 0 0-1-1H6.5a.5.5 0 0 0-.4.8l4.5 6a2 2 0 0 1 0 2.4l-4.5 6a.5.5 0 0 0 .4.8H17a1 1 0 0 0 1-1v-2",key:"wuwx1p"}]]);/**
|
|
287
282
|
* @license lucide-react v0.453.0 - ISC
|
|
288
283
|
*
|
|
289
284
|
* This source code is licensed under the ISC license.
|
|
290
285
|
* See the LICENSE file in the root directory of this source tree.
|
|
291
|
-
*/const
|
|
286
|
+
*/const $a=s.createLucideIcon("SlidersHorizontal",[["line",{x1:"21",x2:"14",y1:"4",y2:"4",key:"obuewd"}],["line",{x1:"10",x2:"3",y1:"4",y2:"4",key:"1q6298"}],["line",{x1:"21",x2:"12",y1:"12",y2:"12",key:"1iu8h1"}],["line",{x1:"8",x2:"3",y1:"12",y2:"12",key:"ntss68"}],["line",{x1:"21",x2:"16",y1:"20",y2:"20",key:"14d8ph"}],["line",{x1:"12",x2:"3",y1:"20",y2:"20",key:"m0wm8r"}],["line",{x1:"14",x2:"14",y1:"2",y2:"6",key:"14e1ph"}],["line",{x1:"8",x2:"8",y1:"10",y2:"14",key:"1i6ji0"}],["line",{x1:"16",x2:"16",y1:"18",y2:"22",key:"1lctlv"}]]);/**
|
|
292
287
|
* @license lucide-react v0.453.0 - ISC
|
|
293
288
|
*
|
|
294
289
|
* This source code is licensed under the ISC license.
|
|
295
290
|
* See the LICENSE file in the root directory of this source tree.
|
|
296
|
-
*/const
|
|
291
|
+
*/const Ya=s.createLucideIcon("Square",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]]);/**
|
|
297
292
|
* @license lucide-react v0.453.0 - ISC
|
|
298
293
|
*
|
|
299
294
|
* This source code is licensed under the ISC license.
|
|
300
295
|
* See the LICENSE file in the root directory of this source tree.
|
|
301
|
-
*/const
|
|
296
|
+
*/const qa=s.createLucideIcon("Sun",[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"m17.66 17.66 1.41 1.41",key:"ptbguv"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m6.34 17.66-1.41 1.41",key:"1m8zz5"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}]]);/**
|
|
302
297
|
* @license lucide-react v0.453.0 - ISC
|
|
303
298
|
*
|
|
304
299
|
* This source code is licensed under the ISC license.
|
|
305
300
|
* See the LICENSE file in the root directory of this source tree.
|
|
306
|
-
*/const
|
|
301
|
+
*/const at=s.createLucideIcon("Tag",[["path",{d:"M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z",key:"vktsd0"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor",key:"kqv944"}]]);/**
|
|
307
302
|
* @license lucide-react v0.453.0 - ISC
|
|
308
303
|
*
|
|
309
304
|
* This source code is licensed under the ISC license.
|
|
310
305
|
* See the LICENSE file in the root directory of this source tree.
|
|
311
|
-
*/const
|
|
306
|
+
*/const Ga=s.createLucideIcon("Tags",[["path",{d:"m15 5 6.3 6.3a2.4 2.4 0 0 1 0 3.4L17 19",key:"1cbfv1"}],["path",{d:"M9.586 5.586A2 2 0 0 0 8.172 5H3a1 1 0 0 0-1 1v5.172a2 2 0 0 0 .586 1.414L8.29 18.29a2.426 2.426 0 0 0 3.42 0l3.58-3.58a2.426 2.426 0 0 0 0-3.42z",key:"135mg7"}],["circle",{cx:"6.5",cy:"9.5",r:".5",fill:"currentColor",key:"5pm5xn"}]]);/**
|
|
312
307
|
* @license lucide-react v0.453.0 - ISC
|
|
313
308
|
*
|
|
314
309
|
* This source code is licensed under the ISC license.
|
|
315
310
|
* See the LICENSE file in the root directory of this source tree.
|
|
316
|
-
*/const
|
|
311
|
+
*/const Ha=s.createLucideIcon("Terminal",[["polyline",{points:"4 17 10 11 4 5",key:"akl6gq"}],["line",{x1:"12",x2:"20",y1:"19",y2:"19",key:"q2wloq"}]]);/**
|
|
317
312
|
* @license lucide-react v0.453.0 - ISC
|
|
318
313
|
*
|
|
319
314
|
* This source code is licensed under the ISC license.
|
|
320
315
|
* See the LICENSE file in the root directory of this source tree.
|
|
321
|
-
*/const
|
|
316
|
+
*/const Me=s.createLucideIcon("ToggleLeft",[["rect",{width:"20",height:"12",x:"2",y:"6",rx:"6",ry:"6",key:"f2vt7d"}],["circle",{cx:"8",cy:"12",r:"2",key:"1nvbw3"}]]);/**
|
|
322
317
|
* @license lucide-react v0.453.0 - ISC
|
|
323
318
|
*
|
|
324
319
|
* This source code is licensed under the ISC license.
|
|
@@ -328,16 +323,16 @@
|
|
|
328
323
|
*
|
|
329
324
|
* This source code is licensed under the ISC license.
|
|
330
325
|
* See the LICENSE file in the root directory of this source tree.
|
|
331
|
-
*/const
|
|
326
|
+
*/const Be=s.createLucideIcon("User",[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2",key:"975kel"}],["circle",{cx:"12",cy:"7",r:"4",key:"17ys0d"}]]);/**
|
|
332
327
|
* @license lucide-react v0.453.0 - ISC
|
|
333
328
|
*
|
|
334
329
|
* This source code is licensed under the ISC license.
|
|
335
330
|
* See the LICENSE file in the root directory of this source tree.
|
|
336
|
-
*/const Ka=s.createLucideIcon("View",[["path",{d:"M21 17v2a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-2",key:"mrq65r"}],["path",{d:"M21 7V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v2",key:"be3xqs"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["path",{d:"M18.944 12.33a1 1 0 0 0 0-.66 7.5 7.5 0 0 0-13.888 0 1 1 0 0 0 0 .66 7.5 7.5 0 0 0 13.888 0",key:"11ak4c"}]]);function Ja(){const{setTheme:t}=s.useTheme(),a=s.useDashboardStore(n=>n.actions.setDashboardTheme);return e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsxs(s.Button,{className:"h-7 p-2",variant:"ghost",size:"sm",children:[e.jsx(Ga,{strokeWidth:1.5,className:"h-4 w-4 rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0"}),e.jsx(Oa,{strokeWidth:1.5,className:"absolute h-4 w-4 rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100"}),e.jsx("span",{className:"sr-only",children:"Toggle theme"})]})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsx(s.DropdownMenuItem,{onClick:()=>{t("light"),a("light")},children:"Light"}),e.jsx(s.DropdownMenuItem,{onClick:()=>{t("dark"),a("dark")},children:"Dark"}),e.jsx(s.DropdownMenuItem,{onClick:()=>{t("system"),a("system")},children:"System"})]})]})}function es(t){var a;return{...t,sheets:(a=t==null?void 0:t.sheets)==null?void 0:a.map(n=>{var r;return{...n,frames:(r=n.frames)==null?void 0:r.map(l=>{var o;return{...l,cards:(o=l.cards)==null?void 0:o.map(c=>rt(c))}})}})}}function rt(t){return{...t,customCfg:Qa(t.customCfg),data:[]}}function Qa(t){var a,n;return t?{...t,data:{...t==null?void 0:t.data,labels:[],datasets:(n=(a=t==null?void 0:t.data)==null?void 0:a.datasets)==null?void 0:n.map(r=>({...r,data:[]}))}}:null}async function Xa(t,a,n,r){if(!r)return null;const l=JSON.stringify(a);return await s.postRequest("https://semaphor.cloud/api/v1/lens",r,{name:t,template:l,filterValues:n,operation:"create"})}async function gs(t,a){if(!a)return null;const{id:n,template:r,filterValues:l,isDefault:o,shared:c}=t;return await s.postRequest("https://semaphor.cloud/api/v1/lens",a,{lensId:n,template:r,filterValues:l,isDefault:o,shared:c,operation:"update"})}async function Za(t,a){return a?await s.postRequest("https://semaphor.cloud/api/v1/lens",a,{operation:"delete",lensId:t}):null}function en(){const[t,a]=A.useState(""),[n,r]=A.useState(!1),l=s.useDashboardStore(p=>p.lenses),{setLenses:o,setSelectedLensId:c}=s.useDashboardActions(),[i,d]=A.useState(!1),[u,m]=A.useState(!1),h=s.useDashboardStore(p=>p.dashboard),f=s.useDashboardStore(p=>p.filterValues),{authToken:g}=s.useSemaphorContext();async function b(){d(!0);const p=es(h),j=await Xa(t,p,f,g==null?void 0:g.accessToken);j&&(o([...l||[],j]),c(j.id),m(!1)),d(!1)}return e.jsxs(s.Dialog,{open:u,onOpenChange:m,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"secondary",className:"h-7 p-2",size:"sm",children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Lens"]})}),e.jsxs(s.DialogContent,{className:"sm:max-w-[425px]",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Create Lens"}),e.jsx(s.DialogDescription,{children:"Lenses are private by default and are only visible to you."})]}),e.jsx("div",{className:"grid gap-4 py-4",children:e.jsxs("div",{className:"grid grid-cols-8 items-center gap-4",children:[e.jsx(s.Label,{className:"text-right",children:"Name"}),e.jsx(s.Input,{value:t,onChange:p=>{a(p.target.value)},id:"name",className:"col-span-7 focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0"})]})}),n&&e.jsx("p",{className:"text-sm",children:"The lens name already exists. Use a differnet name."}),e.jsx(s.DialogFooter,{children:e.jsx(s.Button,{size:"sm",variant:"outline",type:"submit",onClick:b,disabled:i,children:i?"Creating...":"Add"})})]})]})}function sn(){const[t,a]=A.useState(!1),n=s.useDashboardStore(m=>m.lenses),r=s.useDashboardStore(m=>m.selectedLensId),{setLenses:l,setSelectedLensId:o}=s.useDashboardActions(),{authToken:c}=s.useSemaphorContext();async function i(m){o(m)}async function d(m){if(await Za(m,c==null?void 0:c.accessToken)){const f=n==null?void 0:n.filter(g=>g.id!==m);l(f||[]),o("original")}}async function u(m){const h=n==null?void 0:n.map(b=>b.id===m.id?{...b,isDefault:!m.isDefault}:{...b,isDefault:!1});l(h||[]);const f={...m,isDefault:!m.isDefault};await gs(f,c==null?void 0:c.accessToken);const g=n==null?void 0:n.find(b=>b.isDefault);if(g&&g.id!==m.id){const b={...g,isDefault:!1};await gs(b,c==null?void 0:c.accessToken)}}return e.jsxs(s.DropdownMenu,{open:t,onOpenChange:a,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Lenses",className:"h-7 p-2",children:e.jsx(Ca,{className:"h-4 w-4"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"w-60",children:[e.jsx(s.DropdownMenuLabel,{className:"px-3",children:"Lenses"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuRadioGroup,{value:r,onValueChange:i,children:[e.jsx(s.DropdownMenuRadioItem,{value:"original",children:"Original"}),n==null?void 0:n.map(m=>e.jsxs(s.DropdownMenuRadioItem,{className:"group flex justify-between gap-2",value:m.id,children:[e.jsx("p",{children:m.name}),e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx(s.House,{onClick:h=>{h.preventDefault(),u(m)},className:s.cn("size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",{invisible:!m.isDefault,"text-green-500":m.isDefault}),strokeWidth:1.5}),e.jsx(s.Cross2Icon,{onClick:h=>{h.preventDefault(),d(m.id)},className:"invisible size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",strokeWidth:1.5})]})]},m.id))]})]})]})}function tn({iconClassName:t}){const[a,n]=A.useState(!1),[r,l]=A.useState(""),[o,c]=A.useState(!1),i=s.useDashboardStore(m=>m.isDownloadingPdf);async function d(){const m=s.ue.loading("Generating PDF... may take up to 60 seconds");try{await s.downloadPdf(),s.ue.dismiss(m),s.ue.success("PDF downloaded successfully!",{duration:2e3})}catch(h){s.ue.dismiss(m),s.ue.error("Failed to download PDF",{description:"Please try again or contact support.",richColors:!0}),console.error("PDF download error:",h)}}async function u(){if(!r)return;n(!1),l(""),c(!1);const m=s.ue.loading("Generating protected PDF... may take up to 60 seconds");try{await s.downloadPdf(r),s.ue.dismiss(m),s.ue.success("Protected PDF downloaded successfully!",{duration:2e3,position:"top-right"})}catch(h){s.ue.dismiss(m),s.ue.error("Failed to download protected PDF. Please try again."),console.error("Protected PDF download error:",h)}}return e.jsxs(e.Fragment,{children:[e.jsxs(s.DropdownMenu,{modal:!1,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 p-2",disabled:i,children:e.jsx(s.Download,{className:s.cn("size-4",t)})})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsxs(s.DropdownMenuItem,{onClick:d,children:[e.jsx(s.File,{className:"mr-2 h-4 w-4"}),"Download PDF"]}),e.jsxs(s.DropdownMenuItem,{onClick:()=>n(!0),children:[e.jsx(vs,{className:"mr-2 h-4 w-4"}),"Download Protected PDF"]})]})]}),e.jsx(s.Dialog,{open:a,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"sm:max-w-[425px]",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Download Protected PDF"}),e.jsx(s.DialogDescription,{children:"Enter a password to protect your PDF. The PDF will be encrypted and require this password to open."})]}),e.jsx("div",{className:"grid gap-4 py-4",children:e.jsxs("div",{className:"grid gap-2",children:[e.jsx(s.Label,{htmlFor:"password",children:"Password"}),e.jsxs("div",{className:"relative",children:[e.jsx(s.Input,{id:"password",type:o?"text":"password",value:r,onChange:m=>l(m.target.value),placeholder:"Enter password",className:"pr-10",onKeyDown:m=>{m.key==="Enter"&&r&&u()}}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent",onClick:()=>c(!o),children:o?e.jsx(s.EyeOff,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(s.Eye,{className:"h-4 w-4 text-muted-foreground"})})]})]})}),e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(s.Button,{onClick:u,disabled:!r,children:"Download"})]})]})})]})}function fe({defaultValue:t,label:a,options:n,value:r,onValueChange:l,className:o,icon:c,showPlaceholderLabel:i=!0}){return e.jsxs(s.Select,{defaultValue:t,value:r,onValueChange:l,children:[e.jsx(s.SelectTrigger,{className:s.cn("w-full focus:ring-0 focus:ring-offset-0",o),children:e.jsxs("div",{className:"flex items-center gap-2",children:[c&&e.jsx("span",{children:c}),i&&e.jsx(s.SelectValue,{placeholder:a})]})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:a}),n.map(d=>e.jsx(s.SelectItem,{value:d.value,children:d.label},d.value))]})})]})}const Vs=[{value:"daily",label:"Daily"},{value:"weekly",label:"Weekly"},{value:"biweekly",label:"Bi-Weekly"},{value:"monthly",label:"Monthly"}];function lt({triggerButtonClassName:t}){const{currentUser:a}=s.useCurrentUserInfo(),{data:n,handleScheduleSubscription:r,handleDeleteSubscription:l,status:o,error:c,isDeleting:i}=an(),[d,u]=A.useState((a==null?void 0:a.email)||""),[m,h]=A.useState(Vs[0].value),[f,g]=A.useState("06:00"),[b,p]=A.useState("");return e.jsx(s.TooltipProvider,{delayDuration:0,children:e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Schedule Dashboard",className:s.cn("h-7 p-2",t),children:e.jsx(s.Clock,{className:"size-4"})})}),e.jsx(s.PopoverContent,{align:"end",className:"w-80",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Schedule Subscription"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Subscribe to receive dashboard via email"})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"recipients",children:"Recipients"}),e.jsx(s.Input,{id:"recipients",value:d,onChange:j=>u(j.target.value),placeholder:a!=null&&a.email?"Add more emails separated by commas":"email@example.com, email2@example.com",className:`col-span-2 h-8 ${s.removeRing}`})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"subject",children:"Subject"}),e.jsx(s.Input,{id:"subject",placeholder:"Monthly Sales Report",value:b,onChange:j=>{p(j.target.value.replace(/[^a-zA-Z0-9\s-_]/g,""))},className:`col-span-2 h-8 ${s.removeRing}`})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"frequency",children:"Frequency"}),e.jsx(fe,{className:"col-span-2 h-8",label:"Select Frequency",options:Vs,value:m,onValueChange:j=>h(j)})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"time",children:"Time"}),e.jsx(s.Input,{id:"time",type:"time",value:f,onChange:j=>g(j.target.value),className:`col-span-2 h-8 ${s.removeRing}`})]}),e.jsx("div",{className:"mt-2 flex justify-end",children:e.jsxs(s.Button,{onClick:async()=>{await r({recipients:d,frequency:m,time:f,subject:b}),g("06:00"),u((a==null?void 0:a.email)||""),p("")},className:"h-8 p-2",disabled:o==="loading"||!d,children:[o==="loading"&&e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin"}),o==="success"&&e.jsx(s.Check,{className:"mr-2 size-4"}),o==="error"&&e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{children:e.jsx(Zs,{className:"mr-2 size-4 text-destructive"})}),e.jsx(s.TooltipContent,{children:e.jsx("p",{children:c})})]}),"Schedule"]})}),n&&n.length>0&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Subscriptions"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Active email subscriptions"})]}),s.isDevEnv]})}),e.jsx("div",{className:"grid max-h-48 gap-2 overflow-y-auto",children:n==null?void 0:n.map(j=>{const x=j.recipients?j.recipients.split(/[,;]/).filter(Boolean):[j.endUserEmail].filter(Boolean),v=x.length,k=new Date(j.nextRun),R=k<new Date;return e.jsx("div",{className:"group rounded-lg border bg-card p-3 transition-colors hover:bg-accent/50",children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:j.reportType==="VISUAL"?"secondary":"default",className:"text-xs",children:j.reportType==="VISUAL"?"Report":" Dashboard"}),e.jsxs("span",{className:"text-sm font-medium",children:[s.titleCase(j.frequency)," at"," ",j.time]})]}),j.subject&&e.jsx("p",{className:"text-xs text-muted-foreground",children:j.subject}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Mail,{className:"size-3 text-muted-foreground"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:v===1?x[0]:`${v} recipients`})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Clock,{className:s.cn("size-3",R?"text-orange-500":"text-muted-foreground")}),e.jsxs("span",{className:s.cn("text-xs",R?"font-medium text-orange-500":"text-muted-foreground"),children:["Next: ",k.toLocaleDateString()," at"," ",k.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})]})]})]}),e.jsx("div",{className:"flex items-center gap-1",children:i===j.id?e.jsx(s.LoaderCircle,{className:"size-4 animate-spin text-muted-foreground"}):e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>l(j.id),className:"h-7 w-7 p-0 hover:bg-destructive/10 hover:text-destructive",children:e.jsx(s.Trash2,{className:"size-3.5"})})})]})},j.id)})})]})]})]})})]})})}function an(){const[t,a]=A.useState("idle"),[n,r]=A.useState(""),[l,o]=A.useState(null),c=s.useDashboardStore(N=>N.authToken),i=s.useDashboardStore(N=>N.dashboard.id),d=s.useDashboardStore(N=>N.dashboard.title),u=s.useDashboardStore(N=>N.filterValues),{endUserId:m}=s.getTenantAndEndUserId((c==null?void 0:c.accessToken)||""),{currentUser:h}=s.useCurrentUserInfo(),f="https://semaphor.cloud/api/v1/subscriptions/get",g={dashboardId:i,userId:h==null?void 0:h.id},{data:b,isLoading:p,isError:j,isFetching:x,refetch:v}=s.useQuery({queryKey:["subscriptions",i,h==null?void 0:h.id],queryFn:()=>s.getRequest(f,(c==null?void 0:c.accessToken)||"",g),enabled:!!(c!=null&&c.accessToken)&&!!i&&!!(h!=null&&h.id)});async function k({recipients:N,subject:w,frequency:y,time:D}){const C=N.split(/[,;]/).map(O=>O.trim()).filter(O=>O),I=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,S=C.filter(O=>!I.test(O));if(S.length>0){a("error"),r(`Invalid email addresses: ${S.join(", ")}`);return}if(C.length===0){a("error"),r("Please enter at least one valid email address");return}const{authToken:F,...T}=s.getParamsForPrint(),E=Intl.DateTimeFormat().resolvedOptions().timeZone,M=s.formatFilterLine(u||[]),B={reportType:"DASHBOARD",recipients:N,createdBy:(h==null?void 0:h.id)||m,frequency:y,time:D,timezone:E,endUserId:m,endUserEmail:C[0],subject:w||d||"Scheduled Dashboard",dashboardId:i,dashboardParams:T,pageSettings:M?{filterLine:M}:void 0};a("loading");const L="https://semaphor.cloud/api/v1/subscriptions/create";try{const O=await s.postRequestRegular(L,(F==null?void 0:F.accessToken)||"",{...B});a("success"),r(""),v(),setTimeout(()=>{a("idle")},2e3)}catch(O){console.error(O),a("error"),r(O.message)}}async function R(N){const w="https://semaphor.cloud/api/v1/subscriptions/delete";o(N);try{await s.postRequestRegular(w,(c==null?void 0:c.accessToken)||"",{id:N}),v(),setTimeout(()=>{o(null)},2e3)}catch(y){console.error(y),o(null),a("error"),r(y.message)}}return{data:b,isLoading:p,isFetching:x,isError:j,isDeleting:l,refetch:v,handleScheduleSubscription:k,handleDeleteSubscription:R,status:t,error:n}}function ot(){return e.jsx(s.ScrollArea,{className:"w-full flex-1",children:e.jsxs("div",{className:"space-y-4 px-4",children:[e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-8 w-full rounded bg-muted"})}),e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-8 w-full rounded bg-muted"})}),e.jsx("div",{className:"space-y-2",children:[...Array(4)].map((t,a)=>e.jsx("div",{className:"animate-pulse",children:e.jsxs("div",{className:"group relative flex items-start gap-3 px-4 py-3",children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-md bg-muted"})}),e.jsxs("div",{className:"flex w-full items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("div",{className:"h-4 w-32 rounded bg-muted"})}),e.jsx("div",{className:"shrink-0",children:e.jsx("div",{className:"h-3.5 w-3.5 rounded bg-muted"})})]}),e.jsx("div",{className:"mt-0.5",children:e.jsx("div",{className:"h-3 w-48 rounded bg-muted"})})]}),e.jsx("div",{className:"absolute right-3 top-2",children:e.jsx("div",{className:"flex items-center opacity-0 transition-opacity duration-150 group-hover:opacity-100",children:e.jsx("div",{className:"h-6 w-6 rounded bg-muted"})})})]})]})},a))})]})})}function nn({visual:t,isDeleting:a,isDuplicating:n,isTitleUpdating:r=!1,isDescriptionUpdating:l=!1,onAddVisual:o,onEditVisual:c,onUpdateVisual:i,onDeleteClick:d,onDuplicateVisual:u,onShareVisual:m,formatDate:h}){var y,D,C;const{selectVisual:f}=s.useManagementActions(),g=s.useIsVisualSelected(t.id),{isConsoleMode:b}=s.useDashboardPreferences(),p=s.useDashboardStore(I=>I.actions.setIsDashboardPanelOpen),[j,x]=A.useState(!1),[v,k]=A.useState(!1);A.useEffect(()=>{n?(x(!0),k(!0)):v&&(x(!1),k(!1))},[n,v]);const R=()=>t.ownership.isOwner?t.ownership.status==="private"?e.jsx(vs,{className:"h-3 w-3 text-purple-500"}):e.jsx(s.Users,{className:"h-3.5 w-3.5 text-blue-600"}):e.jsx(De,{className:"h-3.5 w-3.5 text-slate-500"}),N=()=>e.jsx(s.ChartColumn,{className:"h-4 w-4 text-slate-400"}),w=()=>{f(t),c==null||c(t)};return e.jsxs("div",{className:s.cn("group relative flex cursor-pointer items-start gap-3 px-4 py-3 dark:border-slate-800","cursor-pointer transition-colors duration-150 hover:bg-slate-50 dark:hover:bg-slate-900/50",t.ownership.isOwner&&"border-blue-200 dark:border-blue-800",g&&"rounded-md bg-slate-50 ring-1 ring-inset ring-border dark:bg-slate-900/50"),tabIndex:0,onClick:w,children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-md bg-slate-100 dark:bg-slate-800",children:N()})}),e.jsxs("div",{className:"flex w-full items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(s.EditableText,{inputClassName:"text-sm font-medium text-slate-900 dark:text-slate-100",value:t.title,onSave:I=>i==null?void 0:i(t.id,{title:I}),isEditable:t.ownership.isOwner&&g,isPending:r,placeholder:"Untitled Visual",displayClassName:"line-clamp-1 max-w-[150px] text-sm font-medium text-slate-900 dark:text-slate-100"})}),e.jsx("div",{className:"shrink-0",children:R()})]}),e.jsx("div",{className:"mt-0.5",children:e.jsx(s.EditableText,{inputClassName:"line-clamp-1 text-xs text-slate-500 dark:text-slate-400",value:t.description||"",onSave:I=>i==null?void 0:i(t.id,{description:I}),isEditable:t.ownership.isOwner&&g,isPending:l,placeholder:"No description",displayClassName:"mt-0.5 max-w-[220px] line-clamp-1 text-xs text-slate-500 dark:text-slate-400"})})]}),e.jsx("div",{className:"absolute right-3 top-2 flex items-center justify-between text-xs text-muted-foreground",children:e.jsxs("div",{className:s.cn("flex items-center opacity-0 transition-opacity duration-150 group-hover:opacity-100"),children:[e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-7 w-7 p-0 hover:bg-slate-200 dark:hover:bg-slate-700",onClick:I=>{I.stopPropagation(),o(t)},children:e.jsx(s.Plus,{className:"h-3.5 w-3.5"})}),e.jsxs(s.DropdownMenu,{modal:!1,open:j,onOpenChange:x,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0 hover:bg-slate-200 dark:hover:bg-slate-700",onClick:I=>I.stopPropagation(),children:e.jsx(s.Ellipsis,{className:"h-3 w-3"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"z-[51] w-40",children:[e.jsxs(s.DropdownMenuItem,{onClick:I=>{I.stopPropagation(),o(t)},children:[e.jsx(s.Plus,{className:"mr-2 h-3 w-3"}),"Add"]}),e.jsxs(s.DropdownMenuItem,{onClick:I=>{I.preventDefault(),I.stopPropagation(),u(t.id)},disabled:n,children:[n?e.jsx(s.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(s.Copy,{className:"mr-2 h-3 w-3"}),n?"Duplicating...":"Duplicate"]}),t.ownership.isOwner&&e.jsxs(e.Fragment,{children:[e.jsxs(s.DropdownMenuItem,{onClick:I=>{I.stopPropagation(),c==null||c(t)},children:[e.jsx(Pa,{className:"mr-2 h-3 w-3"}),"Edit"]}),e.jsxs(s.DropdownMenuItem,{onClick:I=>{I.stopPropagation(),m(t)},children:[e.jsx(s.Users,{className:"mr-2 h-3 w-3"}),"Share"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:I=>{I.stopPropagation(),d(t),p(!1)},className:"text-destructive",disabled:a,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),a?"Deleting...":"Delete"]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs("div",{className:"space-y-1 px-2 py-2 text-xs text-slate-500 dark:text-slate-400",children:[(((y=t.ownership.createdBy)==null?void 0:y.type)==="tenant"||((D=t.ownership.createdBy)==null?void 0:D.type)==="organization"&&b)&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(De,{className:"h-3 w-3"}),e.jsx("span",{children:((C=t.ownership.createdBy)==null?void 0:C.name)||"Unknown"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Calendar,{className:"h-3 w-3"}),e.jsx("span",{children:h(t.lastModified)})]})]})]})]})]})})]})]},t.id)}function it({value:t,onChange:a,placeholder:n="Search users by name, email, or department..."}){return e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:n,value:t,onChange:r=>a(r.target.value),className:"pl-9"})]})}function ss({currentRole:t,onRoleChange:a,roleOptions:n,disabled:r=!1,className:l="",allowDropdown:o=!0}){var d;const c=((d=n.find(u=>u.value===t))==null?void 0:d.label)||t,i=n.filter(u=>u.value!==t);return o?e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Badge,{variant:"outline",className:`cursor-pointer hover:bg-muted ${r?"cursor-not-allowed opacity-50":""} ${l}`,onClick:()=>console.log("Badge clicked:",{currentRole:t,disabled:r,allowDropdown:o}),children:c})}),e.jsx(s.DropdownMenuContent,{className:"z-[51]",children:i.map(u=>e.jsx(s.DropdownMenuItem,{onClick:()=>{console.log("Dropdown item clicked:",{currentRole:t,newRole:u.value,disabled:r}),a(u.value)},disabled:r,children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{children:u.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:u.description})]})},u.value))})]}):e.jsx(s.Badge,{variant:"outline",className:`text-xs ${l}`,children:c})}function ct({selectedUsers:t,selectedUserObjects:a,onRemove:n,onRoleChange:r,getRoleOptions:l}){return t.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{className:"text-sm font-medium",children:["Selected Users (",t.length,")"]}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>t.forEach(o=>n(o.id)),className:"h-auto p-1 text-xs",children:"Clear all"})]}),e.jsx("div",{className:"flex max-h-20 flex-wrap gap-2 overflow-y-auto",children:a.map(o=>{const c=t.find(d=>d.id===o.id),i=l(o.type);return e.jsxs(s.Badge,{variant:"secondary",className:"gap-1",children:[o.name,e.jsx(ss,{currentRole:(c==null?void 0:c.role)||"VIEWER",onRoleChange:d=>r(o.id,d),roleOptions:i}),e.jsx("button",{onClick:()=>n(o.id),className:"ml-1 rounded-full p-0.5 hover:bg-muted-foreground/20",children:e.jsx(s.X,{className:"h-3 w-3"})})]},o.id)})}),e.jsx(s.Separator,{})]})}function dt({usersToRemove:t,allUsers:a,onRemove:n}){return t.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{className:"text-sm font-medium text-destructive",children:["Users to Remove Access (",t.length,")"]}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>t.forEach(r=>n(r)),className:"h-auto p-1 text-xs text-destructive hover:text-destructive",children:"Clear all"})]}),e.jsx("div",{className:"flex max-h-20 flex-wrap gap-2 overflow-y-auto",children:a.filter(r=>t.includes(r.id)).map(r=>e.jsxs(s.Badge,{variant:"destructive",className:"gap-1",children:[r.name,e.jsx("button",{onClick:()=>n(r.id),className:"ml-1 rounded-full p-0.5 hover:bg-destructive-foreground/20",children:e.jsx(s.X,{className:"h-3 w-3"})})]},r.id))}),e.jsx(s.Separator,{})]})}function ut({usersToUpdate:t,allUsers:a,onRemove:n,getRoleOptions:r}){if(t.length===0)return null;const l=r("tenant"),o=i=>{const d=a.find(u=>u.id===i);return(d==null?void 0:d.name)||"Unknown User"},c=i=>{const d=l.find(u=>u.value===i);return(d==null?void 0:d.label)||i};return e.jsxs("div",{className:"rounded-lg border border-orange-200 bg-orange-50 p-3",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(s.Users,{className:"h-4 w-4 text-orange-600"}),e.jsxs("span",{className:"text-sm font-medium text-orange-800",children:["Updating Access (",t.length,")"]})]}),e.jsx("div",{className:"space-y-2",children:t.map(i=>e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium",children:o(i.id)}),e.jsx("span",{className:"text-muted-foreground",children:"→"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:c(i.currentRole)}),e.jsx("span",{className:"text-muted-foreground",children:"→"}),e.jsx(s.Badge,{variant:"default",className:"text-xs",children:c(i.newRole)})]})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-muted-foreground hover:text-destructive",onClick:()=>n(i.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]},i.id))})]})}function mt(t,a={}){const{enabled:n=!0,eventType:r="mousedown"}=a,l=A.useRef(null);return A.useEffect(()=>{const o=c=>{const i=c.target;l.current&&l.current.contains(i)||i instanceof Element&&(i.closest("[data-radix-popper-content-wrapper]")||i.closest("[data-radix-select-content]")||i.closest("[data-radix-popover-content]")||i.closest("[data-radix-dropdown-menu-content]")||i.closest("[data-radix-tooltip-content]")||i.closest('[role="listbox"]')||i.closest('[role="option"]')||i.closest('[role="combobox"]'))||i instanceof Element&&i.hasAttribute("data-radix-")||t()};return n&&document.addEventListener(r,o),()=>{document.removeEventListener(r,o)}},[t,n,r]),l}function be(t,a){var n;return((n=a.find(r=>r.value===t))==null?void 0:n.label)||t}function rn(t){return["POWER_USER","ADMIN","EDITOR"].includes(t)}function ht(t){return"tenantId"in t&&t.tenantId?"tenant":"organization"}function ln(t,a,n){const r=ht(t),l=(n==null?void 0:n.type)||"organization";if(!(!a||!a.shares))if(l==="organization")if(r==="organization"){if("specificOrgUsers"in a.shares)return(a.shares.specificOrgUsers||[]).find(i=>i.orgUserId===t.id)}else return(a.shares.specificTenantUsers||[]).find(i=>i.tenantUserId===t.id);else return(a.shares.specificTenantUsers||[]).find(i=>i.tenantUserId===t.id)}function on({user:t}){return ht(t)==="tenant"?e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:t.role==="POWER_USER"?"Power User":"Viewer"}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:t.role==="ADMIN"?"Admin":t.role==="POWER_USER"?"Power User":"Viewer"})}function cn({user:t,userShare:a,usersToUpdate:n,currentUser:r,getRoleOptions:l,handleUpdateAccess:o}){if(!(a!=null&&a.role))return null;const c=rn((r==null?void 0:r.type)||""),i=n.some(h=>h.id===t.id),d=n.find(h=>h.id===t.id),u=d?d.newRole:a==null?void 0:a.role,m=l(t.type);return a?e.jsx("div",{className:"flex items-center gap-2",children:c?e.jsx(ss,{currentRole:u,onRoleChange:h=>{o(t.id,a.role,h)},roleOptions:m,disabled:!c,allowDropdown:c,className:i?"border-orange-300 bg-orange-100":""}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:be(u,m)})}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:"Unknown"})}function dn({hasAccess:t,isUserRemoving:a,isSelected:n,hasAccessFromAPI:r}){return e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[t&&!a&&e.jsxs(s.Badge,{variant:"outline",className:"border-green-200 bg-green-50 text-xs text-green-700",children:[e.jsx(s.Eye,{className:"mr-1 h-3 w-3"}),"Has Access"]}),a&&e.jsxs(s.Badge,{variant:"outline",className:"border-red-200 bg-red-50 text-xs text-red-700",children:[e.jsx(s.X,{className:"mr-1 h-3 w-3"}),"Remove Access"]}),n&&!r&&e.jsxs(s.Badge,{variant:"outline",className:"border-blue-200 bg-blue-50 text-xs text-blue-700",children:[e.jsx($e,{className:"mr-1 h-3 w-3"}),"Will Share"]})]})}function un({isUserRemoving:t,isSelected:a,hasAccess:n,isRemoving:r,isSharing:l}){return e.jsxs(e.Fragment,{children:[t&&e.jsx("span",{className:"text-xs font-medium text-red-600",children:r?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.LoaderCircle,{className:"h-3 w-3 animate-spin"}),"Removing..."]}):"⚠ Will remove access"}),a&&!n&&e.jsx("span",{className:"text-xs font-medium text-blue-600",children:l?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.LoaderCircle,{className:"h-3 w-3 animate-spin"}),"Sharing..."]}):"Will share"})]})}function mn({existingShares:t,allUsers:a,getRoleOptions:n,currentUser:r}){if(((r==null?void 0:r.type)||"organization")==="organization")if("specificOrgUsers"in t.shares){const c=t.shares,i=c.specificOrgUsers||[],d=c.specificTenantUsers||[],u=c.orgWide||[],m=c.orgUsersOnly||[],h=c.allTenantsOnly||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[i.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Org Users (",i.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[i.slice(0,3).map((f,g)=>{var x,v;const b=((x=a.find(k=>k.id===f.orgUserId))==null?void 0:x.name)||"Unknown User",p=((v=a.find(k=>k.id===f.orgUserId))==null?void 0:v.type)||"",j=be(f.role,n(p));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:b}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:j})]},g)}),i.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",i.length-3," more users"]})]})]}),d.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-green-600",children:["Specific Tenant Users (",d.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[d.slice(0,3).map((f,g)=>{var x,v;const b=((x=a.find(k=>k.id===f.tenantUserId))==null?void 0:x.name)||"Unknown User",p=((v=a.find(k=>k.id===f.tenantUserId))==null?void 0:v.type)||"",j=be(f.role,n(p));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:b}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:j})]},g)}),d.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",d.length-3," more users"]})]})]}),u.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-purple-600",children:"All Org Users"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:u.map((f,g)=>{const b=be(f.role,n(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Organization Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:b})]},g)})})]}),m.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-orange-600",children:"Org Users Only"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:m.map((f,g)=>{const b=be(f.role,n(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Org Users Only"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:b})]},g)})})]}),h.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-indigo-600",children:"All Tenants"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:h.map((f,g)=>{const b=be(f.role,n(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenants"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:b})]},g)})})]}),!i.length&&!d.length&&!u.length&&!m.length&&!h.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}else{const c=t.shares.specificTenantUsers||[],i=t.shares.tenantWide||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[c.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Users (",c.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[c.slice(0,3).map((d,u)=>{var g,b;const m=((g=a.find(p=>p.id===d.tenantUserId))==null?void 0:g.name)||"Unknown User",h=((b=a.find(p=>p.id===d.tenantUserId))==null?void 0:b.type)||"",f=be(d.role,n(h));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:m}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:f})]},u)}),c.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",c.length-3," more users"]})]})]}),i.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-green-600",children:"All Users"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:i.map((d,u)=>{const m=be(d.role,n(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenant Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:m})]},u)})})]}),!c.length&&!i.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}else{const o=t.shares.specificTenantUsers||[],c=t.shares.tenantWide||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[o.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Users (",o.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[o.slice(0,3).map((i,d)=>{var f,g;const u=((f=a.find(b=>b.id===i.tenantUserId))==null?void 0:f.name)||"Unknown User",m=((g=a.find(b=>b.id===i.tenantUserId))==null?void 0:g.type)||"",h=be(i.role,n(m));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:u}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:h})]},d)}),o.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",o.length-3," more users"]})]})]}),c.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-green-600",children:"All Users"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:c.map((i,d)=>{const u=be(i.role,n(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenant Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:u})]},d)})})]}),!o.length&&!c.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}}function hn({isInitialLoading:t,searchQuery:a,availableUsers:n}){return t?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(s.LoaderCircle,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Loading users..."})]})}):n.length===0?e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:a?"No users found matching your search.":"No users available to share with."}):null}function xn({user:t,userShare:a,isUserRemoving:n,hasAccess:r,hasAccessFromAPI:l,isSelected:o,selectedUser:c,roleOptions:i,currentUser:d,usersToUpdate:u,handleUserToggle:m,handleRemoveAccess:h,handleUpdateAccess:f,handleUserRoleChange:g}){return e.jsxs("div",{className:s.cn("flex items-center space-x-3 rounded-lg p-2 transition-colors",r&&!n?"border border-green-200 bg-green-50":n?"border border-red-200 bg-red-50":o?"border border-blue-200 bg-blue-50":"hover:bg-muted/50"),children:[e.jsx(s.Checkbox,{checked:l?!n:o,disabled:t.id===(d==null?void 0:d.id),onCheckedChange:()=>{l?n?m(t.id):h(t.id):m(t.id)}}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:t.name}),e.jsx(on,{user:t})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&!n?e.jsx(ss,{currentRole:a==null?void 0:a.role,onRoleChange:b=>f(t.id,a.role,b),roleOptions:i,disabled:!1,allowDropdown:!0}):e.jsx(cn,{user:t,userShare:a,usersToUpdate:u,currentUser:d,getRoleOptions:()=>i,handleUpdateAccess:f}),o&&!l&&e.jsx("div",{onClick:b=>b.stopPropagation(),children:e.jsx(ss,{currentRole:(c==null?void 0:c.role)||"VIEWER",onRoleChange:b=>g(t.id,b),roleOptions:i,disabled:!1})})]})]}),e.jsx("p",{className:"truncate text-xs text-muted-foreground",children:t.email}),e.jsx(dn,{hasAccess:r,isUserRemoving:n,isSelected:o,hasAccessFromAPI:l}),e.jsx(un,{isUserRemoving:n,isSelected:o,hasAccess:r,isRemoving:!1,isSharing:!1})]})]})}function xt({existingShares:t,isInitialLoading:a,isSearching:n,getRoleOptions:r,allUsers:l=[],currentUser:o,handleUserToggle:c,handleUserRoleChange:i,handleRemoveAccess:d,handleUpdateAccess:u}){const m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),f=s.useShareUsersToUpdate(),g=s.useShareSearchQuery(),b=s.useShareManagementActions(),p=c||(N=>{const w=m.some(D=>D.id===N),y=h.includes(N);w?b.removeSelectedUser(N):y?b.removeUserFromRemove(N):b.addSelectedUser({id:N,role:"VIEWER"})}),j=i||b.updateSelectedUserRole,x=d||b.addUserToRemove,v=u||((N,w,y)=>{b.addUserToUpdate({id:N,currentRole:w,newRole:y})}),k=l,R=h;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Label,{className:"text-sm font-medium",children:["All Users (",(k??[]).length,")"]}),e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",children:e.jsx(s.Info,{className:"h-4 w-4"})})}),e.jsx(s.TooltipContent,{className:"w-48 max-w-sm",children:e.jsx(mn,{existingShares:t,allUsers:l,getRoleOptions:r,currentUser:o})})]})})]}),(k==null?void 0:k.length)>0&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>{m.length===k.length?b.setSelectedUsers([]):b.setSelectedUsers(k.map(N=>({id:N.id,role:"VIEWER"})))},className:"h-auto p-1 text-xs",children:m.length===k.length?"Deselect all":"Select all"})]}),e.jsxs("div",{className:"max-h-60 space-y-1 overflow-y-auto rounded-md border p-2",children:[e.jsx(hn,{isInitialLoading:a,isSearching:n,searchQuery:g,availableUsers:k||[]}),!a&&!n&&(k==null?void 0:k.length)>0&&k.map(N=>{const w=t?ln(N,t,o):void 0,y=R.includes(N.id),D=!!w,C=D&&!y,I=m.some(T=>T.id===N.id),S=m.find(T=>T.id===N.id),F=r(N.type);return e.jsx(xn,{user:N,userShare:w,isUserRemoving:y,hasAccess:C,hasAccessFromAPI:D,isSelected:I,selectedUser:S,roleOptions:F,currentUser:o,usersToUpdate:f,handleUserToggle:p,handleRemoveAccess:x,handleUpdateAccess:v,handleUserRoleChange:j},N.id)})]})]})}function pt({shareType:t,onShareTypeChange:a,currentUser:n,options:r}){const l=(n==null?void 0:n.role)&&["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(n.role);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.RadioGroup,{value:t,onValueChange:a,className:`grid grid-cols-${r.length} gap-4`,children:r.map(o=>e.jsxs("div",{children:[e.jsx(s.RadioGroupItem,{value:o.value,id:o.value,className:"peer sr-only",disabled:o.disabled}),e.jsxs(s.Label,{htmlFor:o.value,className:`flex flex-col items-center justify-between rounded-md border-2 border-muted bg-popover p-4 hover:bg-accent hover:text-accent-foreground peer-data-[state=checked]:border-primary peer-data-[state=checked]:bg-primary/5 [&:has([data-state=checked])]:border-primary [&:has([data-state=checked])]:bg-primary/5 ${o.disabled?"cursor-not-allowed opacity-50":"cursor-pointer"}`,children:[o.icon||e.jsx(De,{className:"mb-3 h-6 w-6"}),e.jsxs("div",{className:"space-y-1 text-center",children:[e.jsx("p",{className:"text-sm font-medium leading-none",children:o.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:o.description})]})]})]},o.value))}),!l&&r.some(o=>o.value==="all_users")&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Only admins, authors, power users, and super admins can share with all users."})]})}const Ee=()=>[{value:"VIEWER",label:"Viewer",description:"Can view only"},{value:"EDITOR",label:"Editor",description:"Can view and edit"},{value:"CONTRIBUTOR",label:"Contributor",description:"Can view, edit, and share"},{value:"OWNER",label:"Owner",description:"Full access (view, edit, share, delete)"}];function pn({currentUser:t,currentShare:a,isSharing:n,onUpdateAccess:r,allUsersToUpdate:l=null,allUsersToRemove:o=!1,isUpdating:c=!1,isRemoving:i=!1}){const d=s.useShareCurrentMode(),u=Ee().filter(v=>v.value==="VIEWER"||v.value==="EDITOR"||v.value==="CONTRIBUTOR"),m=a.role!=="NONE"?a.role:"NONE",h=l?l.newRole:m,f=a.role!=="NONE"&&!o&&(!l||l.newRole===m),g=l!==null&&l.newRole!==m,b=o,p=m==="NONE"||!m,j=v=>{switch(v){case"VIEWER":return e.jsx(s.Eye,{className:"h-4 w-4"});case"EDITOR":return e.jsx(s.SquarePen,{className:"h-4 w-4"});case"CONTRIBUTOR":return e.jsx(_a,{className:"h-4 w-4"});default:return e.jsx(s.Eye,{className:"h-4 w-4"})}},x=v=>{r(m,v)};return e.jsx("div",{className:"space-y-4",children:e.jsxs(s.Card,{className:s.cn("pb-6",g&&!b&&!p?"border-orange-300 bg-orange-50":f?"border-green-300 bg-green-50":b||p?"border-destructive bg-destructive/10":""),children:[e.jsxs(s.CardHeader,{children:[e.jsxs(s.CardTitle,{className:"flex items-center gap-2 text-base",children:[e.jsx(s.Users,{className:"h-5 w-5"}),"Share with All"," ",d==="allOrgUsers"?"Organization":d==="allTenantUsers"?"Tenant":d==="specificOrgUsers"?"Org":"Tenant"," ","Users",f&&e.jsx(s.Badge,{variant:"default",className:"ml-2 border-green-400 bg-green-100 text-green-800",children:"Active"}),g&&e.jsx(s.Badge,{variant:"secondary",className:"ml-2 border-orange-400 bg-orange-100 text-orange-800",children:"Pending Update"}),(b||p)&&e.jsx(s.Badge,{variant:"destructive",className:"ml-2",children:"No Access"})]}),e.jsx(s.CardDescription,{children:b||p?"No access for all users.":"This will share the dashboard with all users in your "+((t==null?void 0:t.type)==="organization"?"organization":"tenant")+". Select an access level below."})]}),e.jsx(s.CardContent,{className:"space-y-4",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Select Access Level:"}),e.jsxs(s.HoverCard,{children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-4 w-4 p-0 text-muted-foreground hover:text-foreground",children:e.jsx(s.Info,{className:"h-3 w-3"})})}),e.jsx(s.HoverCardContent,{className:"w-80",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Share with All Users"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["This action will share the dashboard with all users in your"," ",(t==null?void 0:t.type)==="organization"?"organization":"tenant",". Users will receive the selected access level."]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Viewer:"})," Can view the dashboard"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Editor:"})," Can view and edit the dashboard"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Contributor:"})," Can view, edit, and share the dashboard"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"None:"})," No access for all users"]})]})]})})]})]}),e.jsx("div",{className:"grid grid-cols-2 gap-3",children:u.map(v=>e.jsxs(s.Button,{variant:h===v.value?"default":"outline",className:"h-auto flex-col items-start gap-2 p-3",onClick:()=>x(v.value),disabled:n||c||i,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[j(v.value),e.jsx("span",{className:"font-medium",children:v.label})]}),e.jsx("p",{className:"text-left text-xs text-muted-foreground",children:v.description})]},v.value))})]})})]})})}function ft({currentUser:t,currentShare:a,isSharing:n,isUpdating:r,isRemoving:l,onUpdateAccess:o,onRemoveAccess:c,allUsersToUpdate:i,allUsersToRemove:d}){const u=p=>p==="OWNER"?"CONTRIBUTOR":p,h=a?{role:u(a.role)}:{role:"NONE"},f=i?{currentRole:u(i.currentRole),newRole:u(i.newRole)}:null,g=(p,j)=>{o(p,j)},b=()=>{c()};return e.jsx(pn,{currentUser:t,currentShare:h,isSharing:n,isUpdating:r,isRemoving:l,onUpdateAccess:g,onRemoveAccess:b,allUsersToUpdate:f,allUsersToRemove:d})}const fn=async(t,a={})=>{const n={};return a.search&&(n.search=a.search),a.type&&(n.type=a.type),a.active!==void 0&&(n.active=a.active.toString()),a.tenantId&&(n.tenantId=a.tenantId),a.limit&&(n.limit=a.limit.toString()),a.offset&&(n.offset=a.offset.toString()),a.page&&(n.page=a.page.toString()),a.pageSize&&(n.pageSize=a.pageSize.toString()),await s.getRequest("https://semaphor.cloud/api/management/v1/unified-users",t,n)};function gn(t={}){var o,c,i;const{authToken:a,tokenProps:n}=s.useSemaphorContext(),r=(n==null?void 0:n.endUserId)||(n==null?void 0:n.orgUserId),l=s.useQuery({queryKey:["unified-users",t],queryFn:()=>fn((a==null?void 0:a.accessToken)||"",t),enabled:!!(a!=null&&a.accessToken)&&!!r,retry:(d,u)=>u instanceof Error&&u.message.includes("401")||u instanceof Error&&u.message.includes("403")?!1:d<2,retryDelay:d=>Math.min(1e3*2**d,3e4)});return{users:((o=l.data)==null?void 0:o.users)||[],userContext:(c=l.data)==null?void 0:c.userContext,total:((i=l.data)==null?void 0:i.total)||0,isLoading:l.isLoading,isError:l.isError,isFetching:l.isFetching,error:l.error,refetch:l.refetch}}function ke(t){const{debouncedSearchQuery:a,resourceId:n,resourceType:r=s.ResourceType.DASHBOARD,userType:l,tenantId:o}=t,c=A.useMemo(()=>({search:a,active:!0,...l?{type:l}:{},...l==="tenant"&&o?{tenantId:o}:{}}),[a,l,o]),{users:i,isLoading:d,isError:u}=gn(c),m=s.useResourceShares(r,n);return{allUsers:i,isLoadingUsers:d,isErrorLoadingUsers:u,existingShares:m.data,isLoadingShares:m.isLoading,isErrorLoadingShares:m.isError,isFetchingShares:m.isFetching}}function jn({resource:t,resourceType:a,currentUser:n,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:o=!1,isRemoving:c=!1}){var te,X;const i=s.useShareSelectedTab(),d=s.useShareSelectedTenant(),{searchQuery:u,setSearchQuery:m,debouncedSearchQuery:h}=s.useShareSearchWithDebounce(),f=s.useShareSelectedUsers(),g=s.useShareUsersToRemove(),b=s.useShareUsersToUpdate(),p=s.useShareCurrentMode(),j=s.useShareOrgWideRole(),x=s.useShareManagementActions(),[v,k]=A.useState("specific_users"),R=()=>{if(i==="org")return"organization";if(i==="tenant")return"tenant"},N=()=>{if(i==="tenant"&&d)return d},{allUsers:w,existingShares:y,isLoadingUsers:D}=ke({debouncedSearchQuery:h,resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:R(),tenantId:N()});A.useEffect(()=>{x.setCurrentContext("org-tab"),x.setCurrentMode(v==="all_users"?"allOrgUsers":"specificOrgUsers")},[x,v]);const C=q=>{var _,J;const H=q;if(k(H),r==null||r(H),x.setCurrentContext("org-tab"),H==="specific_users")x.setCurrentMode("specificOrgUsers");else if(H==="all_users"){x.setCurrentMode("allOrgUsers");const z=(J=(_=y==null?void 0:y.shares)==null?void 0:_.orgUsersOnly)==null?void 0:J[0];z&&z.role!==void 0&&x.setOrgWideRole(z.role)}},I=w.filter(q=>q.name.toLowerCase().includes(u.toLowerCase())||q.email.toLowerCase().includes(u.toLowerCase())),S=w.filter(q=>f.some(H=>H.id===q.id)),F=q=>{var z,U;const H=f.some(Z=>Z.id===q),_=g.includes(q),J=(U=(z=y==null?void 0:y.shares)==null?void 0:z.specificOrgUsers)==null?void 0:U.some(Z=>Z.orgUserId===q);H?x.removeSelectedUser(q):_?x.removeUserFromRemove(q):J||x.addSelectedUser({id:q,role:"VIEWER"})},T=(q,H)=>{x.updateSelectedUserRole(q,H)},E=q=>{x.addUserToRemove(q),x.removeSelectedUser(q)},M=q=>{x.removeUserFromRemove(q)},B=q=>{x.removeUserFromUpdate(q)},L=(q,H)=>{x.setOrgWideRole(H)},O=()=>{x.setOrgWideRole((P==null?void 0:P.role)||"NONE")},P=(X=(te=y==null?void 0:y.shares)==null?void 0:te.orgUsersOnly)==null?void 0:X[0];A.useEffect(()=>{v==="all_users"&&P&&P.role!==void 0&&x.setOrgWideRole(P.role)},[v,P,x]);const K=D,$=!1;return n?e.jsxs(e.Fragment,{children:[e.jsx(pt,{shareType:v,onShareTypeChange:C,currentUser:n,options:[{value:"specific_users",label:"Specific Org User",description:"Choose individual users to share with",icon:e.jsx(De,{className:"mb-3 h-6 w-6 text-orange-500"})},{value:"all_users",label:"All Org Users",description:`Share with all ${(n==null?void 0:n.type)==="organization"?"organization":"tenant"} users`,icon:e.jsx(s.Users,{className:"mb-3 h-6 w-6 text-indigo-500"}),disabled:!["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(n.role??"")}]}),v==="specific_users"?e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx(it,{value:u,onChange:m}),e.jsx(ct,{selectedUsers:f,selectedUserObjects:S,onRemove:F,onRoleChange:T,getRoleOptions:Ee}),e.jsx(dt,{usersToRemove:g,allUsers:I,onRemove:M}),e.jsx(ut,{usersToUpdate:b,allUsers:I,onRemove:B,getRoleOptions:Ee}),e.jsx(xt,{existingShares:y,isInitialLoading:K,isSearching:$,resource:t,onShare:()=>{},getRoleOptions:Ee,allUsers:I,currentUser:n,handleUserToggle:F,handleUserRoleChange:T,handleRemoveAccess:E,handleUpdateAccess:(q,H,_)=>{x.addUserToUpdate({id:q,currentRole:H,newRole:_})}})]}):e.jsx("div",{className:"mt-3",children:e.jsx(ft,{currentUser:n,currentShare:P,isSharing:l,isUpdating:o,isRemoving:c,onUpdateAccess:L,onRemoveAccess:O,allUsersToUpdate:p==="allOrgUsers"&&j!==((P==null?void 0:P.role)||"NONE")?{currentRole:(P==null?void 0:P.role)||"NONE",newRole:j}:null,allUsersToRemove:p==="allOrgUsers"&&(P==null?void 0:P.role)===void 0})})]}):null}function _s({resource:t,resourceType:a,currentUser:n,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:o=!1,isRemoving:c=!1}){var z;const{searchQuery:i,debouncedSearchQuery:d,setSearchQuery:u}=s.useShareSearchWithDebounce(),m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),f=s.useShareUsersToUpdate(),g=s.useShareCurrentMode(),b=s.useShareTenantWideRole(),p=s.useShareAllTenantsRole(),j=s.useShareSelectedTenant(),x=s.useShareManagementActions(),{data:v,isLoading:k}=s.useTenants({enabled:(n==null?void 0:n.type)==="organization"}),[R,N]=A.useState((n==null?void 0:n.type)==="organization"?"all_tenants":"specific_tenant_users");A.useEffect(()=>{(n==null?void 0:n.type)==="tenant"?(x.setCurrentContext("tenant-dialog"),x.setCurrentMode("specificTenantUsers")):(x.setCurrentContext("tenant-tab"),x.setCurrentMode("allTenants"))},[x,n==null?void 0:n.type]);const w=U=>{var le,V,se,ne;N(U);let Z;if(U==="specific_tenant_users"?Z="specific_users":U==="all_tenant_users"||U==="all_tenants"?Z="all_users":Z="specific_users",r==null||r(Z),(n==null?void 0:n.type)==="tenant"?(x.setCurrentContext("tenant-dialog"),U==="specific_tenant_users"?x.setCurrentMode("specificTenantUsers"):U==="all_tenant_users"&&(x.setCurrentMode("allTenantUsers"),n!=null&&n.tenantId&&x.setSelectedTenant(n.tenantId))):(x.setCurrentContext("tenant-tab"),U==="specific_tenant_users"?x.setCurrentMode("specificTenantUsers"):U==="all_tenant_users"?x.setCurrentMode("allTenantUsers"):U==="all_tenants"&&x.setCurrentMode("allTenants")),U==="all_tenant_users"){const Y=(V=(le=C==null?void 0:C.shares)==null?void 0:le.tenantWide)==null?void 0:V[0];Y&&Y.role!==void 0&&x.setTenantWideRole(Y.role)}else if(U==="all_tenants"){const Y=(ne=(se=C==null?void 0:C.shares)==null?void 0:se.allTenantsOnly)==null?void 0:ne[0];Y&&Y.role!==void 0&&x.setAllTenantsRole(Y.role)}},y=U=>{x.setSelectedTenant(U)},{allUsers:D,existingShares:C,isLoadingUsers:I,isErrorLoadingUsers:S,isLoadingShares:F,isErrorLoadingShares:T}=ke({debouncedSearchQuery:d,resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:"tenant",tenantId:(n==null?void 0:n.type)==="tenant"?n.tenantId:j}),E=U=>{var se,ne;const Z=m.some(Y=>Y.id===U),le=h.includes(U),V=(ne=(se=C==null?void 0:C.shares)==null?void 0:se.specificTenantUsers)==null?void 0:ne.some(Y=>Y.tenantUserId===U);Z?x.removeSelectedUser(U):le?x.removeUserFromRemove(U):V||x.addSelectedUser({id:U,role:"VIEWER"})},M=(U,Z)=>{x.updateSelectedUserRole(U,Z)},B=U=>{x.addUserToRemove(U),x.removeSelectedUser(U)},L=U=>{x.removeUserFromRemove(U)},O=U=>{x.removeUserFromUpdate(U)},P=(U,Z,le)=>{x.addUserToUpdate({id:U,currentRole:Z,newRole:le})},K=(U,Z)=>{R==="all_tenant_users"?x.setTenantWideRole(Z):R==="all_tenants"&&x.setAllTenantsRole(Z)},$=()=>{R==="all_tenant_users"?x.setTenantWideRole("VIEWER"):R==="all_tenants"&&x.setAllTenantsRole("VIEWER")},X=(()=>{var U,Z,le,V;return g==="allTenants"?(Z=(U=C==null?void 0:C.shares)==null?void 0:U.allTenantsOnly)==null?void 0:Z[0]:g==="allTenantUsers"?(V=(le=C==null?void 0:C.shares)==null?void 0:le.tenantWide)==null?void 0:V[0]:null})();A.useEffect(()=>{var U,Z,le,V;if(R==="all_tenant_users"){const se=(Z=(U=C==null?void 0:C.shares)==null?void 0:U.tenantWide)==null?void 0:Z[0];se&&se.role!==void 0&&x.setTenantWideRole(se.role)}else if(R==="all_tenants"){const se=(V=(le=C==null?void 0:C.shares)==null?void 0:le.allTenantsOnly)==null?void 0:V[0];se&&se.role!==void 0&&x.setAllTenantsRole(se.role)}},[R,C,x]);const q=D.filter(U=>m.some(Z=>Z.id===U.id)),H=I||F,_=S||T,J=()=>(n==null?void 0:n.type)==="tenant"||R==="all_tenants"?!0:j&&(R==="specific_tenant_users"||R==="all_tenant_users");return e.jsxs(e.Fragment,{children:[_&&e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(s.CircleAlert,{className:"mx-auto mb-2 h-8 w-8 text-destructive"}),e.jsx("p",{className:"mb-4 text-sm text-destructive",children:"Failed to load users or shares"}),e.jsx(s.Button,{variant:"outline",size:"sm",onClick:()=>window.location.reload(),children:"Retry"})]})}),!_&&n&&e.jsxs("div",{className:"max-h-[500px] space-y-4 overflow-y-auto",children:[e.jsx(pt,{shareType:R,onShareTypeChange:w,currentUser:n,options:(n==null?void 0:n.type)==="tenant"?[{value:"all_tenant_users",label:"All Users",description:"Share with all users of this tenant",icon:e.jsx(s.Users,{className:"mb-3 h-6 w-6 text-purple-500"})},{value:"specific_tenant_users",label:"Specific Users",description:"Share with specific tenant users",icon:e.jsx(De,{className:"mb-3 h-6 w-6 text-orange-500"})}]:[{value:"all_tenants",label:"All Tenants",description:"Share with all tenants and their users",icon:e.jsx(Fs,{className:"mb-3 h-6 w-6 text-purple-500"})},{value:"all_tenant_users",label:"Specific Tenant",description:"Share with all users of a specific tenant",icon:e.jsx(s.House,{className:"mb-3 h-6 w-6 text-blue-500"})},{value:"specific_tenant_users",label:"Specific Tenant User",description:"Share with users of a specific tenant",icon:e.jsx(De,{className:"mb-3 h-6 w-6 text-orange-500"})}]}),(n==null?void 0:n.type)==="organization"&&(R==="specific_tenant_users"||R==="all_tenant_users")&&e.jsxs("div",{className:"mt-4",children:[e.jsx(s.Label,{className:"mb-1 block text-sm font-medium",children:"Select Tenant"}),e.jsxs(s.Select,{value:j||"",onValueChange:y,disabled:k,children:[e.jsx(s.SelectTrigger,{className:"w-full",children:e.jsx(s.SelectValue,{placeholder:k?"Loading tenants...":"Select a tenant..."})}),e.jsx(s.SelectContent,{className:"z-[51]",children:(z=v==null?void 0:v.tenants)==null?void 0:z.map(U=>e.jsx(s.SelectItem,{value:U.id,children:U.name},U.id))})]})]}),J()?e.jsx(e.Fragment,{children:R==="specific_tenant_users"?e.jsxs("div",{className:"space-y-4",children:[e.jsx(it,{value:i,onChange:u}),e.jsx(ct,{selectedUsers:m,selectedUserObjects:q,onRemove:U=>E(U),onRoleChange:M,getRoleOptions:Ee}),e.jsx(dt,{usersToRemove:h,allUsers:D,onRemove:L}),e.jsx(ut,{usersToUpdate:f,allUsers:D,onRemove:O,getRoleOptions:Ee}),e.jsx(xt,{existingShares:C,isInitialLoading:!!H,isSearching:!1,resource:t,onShare:()=>{},getRoleOptions:Ee,allUsers:D,currentUser:n,handleUserToggle:E,handleUserRoleChange:M,handleRemoveAccess:B,handleUpdateAccess:P})]}):R==="all_tenant_users"||R==="all_tenants"?e.jsx("div",{className:"mt-6",children:e.jsx(ft,{currentUser:n,currentShare:X,isSharing:l,isUpdating:o,isRemoving:c,onUpdateAccess:K,onRemoveAccess:$,allUsersToUpdate:g==="allTenantUsers"&&((X==null?void 0:X.role)===void 0||b!==X.role)||g==="allTenants"&&((X==null?void 0:X.role)===void 0||p!==X.role)?{currentRole:(X==null?void 0:X.role)||"VIEWER",newRole:g==="allTenantUsers"?b:p}:null,allUsersToRemove:g==="allTenantUsers"&&(X==null?void 0:X.role)===void 0||g==="allTenants"&&(X==null?void 0:X.role)===void 0})}):null}):(n==null?void 0:n.type)==="organization"&&(R==="specific_tenant_users"||R==="all_tenant_users")&&e.jsx("div",{className:"mt-6 flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Fs,{className:"mx-auto mb-2 h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Please select a tenant to continue"})]})})]})]})}const gt=()=>{const t=s.useShareCurrentContext(),a=s.useShareCurrentMode(),n=s.useShareSelectedUsers(),r=s.useShareUsersToRemove(),l=s.useShareUsersToUpdate(),o=s.useShareSelectedTenant(),c=s.useShareOrgWideRole(),i=s.useShareAllTenantsRole(),d=s.useShareTenantWideRole(),u=A.useMemo(()=>()=>s.buildShareData({currentContext:t,currentMode:a,selectedUsers:n,usersToRemove:r,usersToUpdate:l,selectedTenant:o,orgWideRole:c,allTenantsRole:i,tenantWideRole:d}),[t,a,n,r,l,o,c,i,d]),m=A.useMemo(()=>f=>s.validateShareData(f),[]),h=A.useMemo(()=>{if(!t||!a)return!1;switch(t){case"org-tab":return a==="specificOrgUsers"?n.length>0||r.length>0||l.length>0:!0;case"tenant-tab":if(a==="allTenantUsers"){if(!o)return!1}else if(a==="specificTenantUsers")return o?n.length>0||r.length>0||l.length>0:!1;return!0;case"tenant-dialog":return a==="specificTenantUsers"?n.length>0||r.length>0||l.length>0:!0}return!1},[t,a,n,r,l,o]);return{buildShareData:u,validateShareData:m,isCurrentStateValid:h,currentContext:t,currentMode:a,selectedUsers:n,usersToRemove:r,usersToUpdate:l,selectedTenant:o,orgWideRole:c,allTenantsRole:i,tenantWideRole:d}};function Us({resource:t,existingShares:a,isSharing:n,isRemoving:r,isUpdating:l,onShare:o,onClose:c,shareTabType:i,currentAllUsersShare:d,onRemoveAccess:u}){const m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),f=s.useShareUsersToUpdate();s.useShareCurrentMode(),s.useShareCurrentContext();const g=s.useShareSelectedTenant();s.useShareSelectedTab();const b=s.useShareOrgWideRole(),p=s.useShareAllTenantsRole(),j=s.useShareTenantWideRole(),{buildShareData:x,validateShareData:v,isCurrentStateValid:k}=gt(),R=n||r||l,N=()=>{var I,S,F,T;if(R)return"Updating...";if(i==="specific_users"){if(m.length===0&&h.length===0&&f.length===0)return"Select users to share with";const E=m.length+h.length+f.length;return E===0?"Select users to share with":m.length>0&&h.length>0?`Update access for ${E} user${E!==1?"s":""}`:h.length>0&&m.length===0&&f.length===0?`Remove access for ${h.length} user${h.length!==1?"s":""}`:m.length>0&&h.length===0&&f.length===0?`Share with ${m.length} user${m.length!==1?"s":""}`:f.length>0&&m.length===0&&h.length===0?`Update access for ${f.length} user${f.length!==1?"s":""}`:`Update access for ${E} user${E!==1?"s":""}`}else if(i==="all_users"){if(!d||d.role===void 0)return"Share with All Users";const E=d.role;return b===E?"Remove Access":"Update Access"}else if(i==="all_tenants"){const E=(S=(I=a==null?void 0:a.shares)==null?void 0:I.allTenantsOnly)==null?void 0:S[0];if(!E||E.role===void 0)return"Share with All Tenants";const M=E.role;return p===M?"Remove Access":"Update Access"}else if(i==="all_tenant_users"){const E=(T=(F=a==null?void 0:a.shares)==null?void 0:F.tenantWide)==null?void 0:T[0];if(!E||E.role===void 0)return"Share with All Tenant Users";const M=E.role;return j===M?"Remove Access":"Update Access"}else if(i==="specific_tenant_users"){if(m.length===0&&h.length===0&&f.length===0)return"Select users to share with";const E=m.length+h.length+f.length;return E===0?"Select users to share with":m.length>0&&h.length>0?`Update access for ${E} user${E!==1?"s":""}`:h.length>0&&m.length===0&&f.length===0?`Remove access for ${h.length} user${h.length!==1?"s":""}`:m.length>0&&h.length===0&&f.length===0?`Share with ${m.length} user${m.length!==1?"s":""}`:f.length>0&&m.length===0&&h.length===0?`Update access for ${f.length} user${f.length!==1?"s":""}`:`Update access for ${E} user${E!==1?"s":""}`}return"Share"},w=()=>R||!t||i==="all_tenant_users"&&!g||i==="specific_tenant_users"&&!g?!0:!k,y=()=>{const I=x();I&&v(I)&&o(I)},D=()=>{var I,S,F,T;if(i==="all_users")if(!d||d.role===void 0){const E=x();E&&v(E)&&o(E)}else{const E=d.role;if(b===E)u==null||u();else{const B=x();if(B&&v(B)){const L={...B,updateAccess:!0};o(L)}}}else if(i==="all_tenants"){const E=(S=(I=a==null?void 0:a.shares)==null?void 0:I.allTenantsOnly)==null?void 0:S[0];if(!E||E.role===void 0){const M=x();M&&v(M)&&o(M)}else{const M=E.role;if(p===M)u==null||u();else{const L=x();if(L&&v(L)){const O={...L,updateAccess:!0};o(O)}}}}else if(i==="all_tenant_users"){const E=(T=(F=a==null?void 0:a.shares)==null?void 0:F.tenantWide)==null?void 0:T[0];if(!E||E.role===void 0){const M=x();M&&v(M)&&o(M)}else{const M=E.role;if(j===M)u==null||u();else{const L=x();if(L&&v(L)){const O={...L,updateAccess:!0};o(O)}}}}},C=()=>{var I,S,F,T;if(i==="all_users"){if(!d||d.role===void 0)return"default";const E=d.role;return b===E?"destructive":"default"}else if(i==="all_tenants"){const E=(S=(I=a==null?void 0:a.shares)==null?void 0:I.allTenantsOnly)==null?void 0:S[0];if(!E||E.role===void 0)return"default";const M=E.role;return p===M?"destructive":"default"}else if(i==="all_tenant_users"){const E=(T=(F=a==null?void 0:a.shares)==null?void 0:F.tenantWide)==null?void 0:T[0];if(!E||E.role===void 0)return"default";const M=E.role;return j===M?"destructive":"default"}return"default"};return e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:c,disabled:R,children:"Close"}),(i==="specific_users"||i==="specific_tenant_users")&&e.jsx(e.Fragment,{children:(m.length>0||h.length>0||f.length>0)&&e.jsxs(s.Button,{onClick:y,disabled:!t||R,variant:"default",children:[R?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx($e,{className:"mr-2 h-4 w-4"}),!R&&N()]})}),(i==="all_users"||i==="all_tenants"||i==="all_tenant_users")&&e.jsxs(s.Button,{onClick:D,disabled:w(),variant:C(),children:[R?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(s.Users,{className:"mr-2 h-4 w-4"}),!R&&N()]})]})}function bn({resource:t,isSharing:a,isRemoving:n,isUpdating:r,onShare:l,onClose:o,shareTabType:c,currentAllUsersShare:i}){const d=s.useShareSelectedUsers(),u=s.useShareUsersToRemove(),m=s.useShareUsersToUpdate();s.useShareCurrentMode(),s.useShareCurrentContext();const h=s.useShareTenantWideRole();s.useShareSelectedTenant();const{buildShareData:f,validateShareData:g,isCurrentStateValid:b}=gt(),p=a||n||r,j=()=>{if(p)return"Updating...";if(c==="specific_users"){if(d.length===0&&u.length===0&&m.length===0)return"Select users to share with";const N=d.length+u.length+m.length;return N===0?"Select users to share with":d.length>0&&u.length>0?`Update access for ${N} user${N!==1?"s":""}`:u.length>0&&d.length===0&&m.length===0?`Remove access for ${u.length} user${u.length!==1?"s":""}`:d.length>0&&u.length===0&&m.length===0?`Share with ${d.length} user${d.length!==1?"s":""}`:m.length>0&&d.length===0&&u.length===0?`Update access for ${m.length} user${m.length!==1?"s":""}`:`Update access for ${N} user${N!==1?"s":""}`}else if(c==="all_users"){if(!i||i.role==="NONE")return"Share with All Users";const N=i.role;return h===N?"Remove Access":"Update Access"}return"Share"},x=()=>p||!t?!0:!b,v=()=>{const N=f();N&&g(N)&&l(N)},k=()=>{if(!i||i.role==="NONE"){const N=f();N&&g(N)&&l(N)}else{const N=i.role;if(h===N){const y=f();if(y&&g(y)){const D={...y,removeAccess:!0};l(D)}}else{const y=f();if(y&&g(y)){const D={...y,updateAccess:!0};l(D)}}}},R=()=>!i||i.role==="NONE"?"default":"destructive";return e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:o,disabled:p,children:"Close"}),c==="specific_users"&&e.jsx(e.Fragment,{children:(d.length>0||u.length>0||m.length>0)&&e.jsxs(s.Button,{onClick:v,disabled:!t||p,variant:"default",children:[p?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx($e,{className:"mr-2 h-4 w-4"}),!p&&j()]})}),c==="all_users"&&e.jsxs(s.Button,{onClick:k,disabled:x(),variant:R(),children:[p?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx($e,{className:"mr-2 h-4 w-4"}),!p&&j()]})]})}function jt({resource:t,resourceType:a,isSharing:n,isRemoving:r,isUpdating:l,onClose:o,onShare:c,onRemoveAccess:i}){var y,D,C,I;const{currentUser:d}=s.useCurrentUserInfo(),[u,m]=A.useState("specific_users"),[h,f]=A.useState("specific_users"),g=s.useShareManagementActions(),b=s.useShareSelectedTab(),p=s.useShareCurrentMode(),{existingShares:j}=ke({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:"tenant"}),{existingShares:x}=ke({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:"organization"}),v=(D=(y=j==null?void 0:j.shares)==null?void 0:y.tenantWide)==null?void 0:D[0],k=(I=(C=x==null?void 0:x.shares)==null?void 0:C.orgUsersOnly)==null?void 0:I[0],R=()=>{if(b==="org")return h;switch(p){case"specificTenantUsers":return"specific_tenant_users";case"allTenantUsers":return"all_tenant_users";case"allTenants":return"all_tenants";default:return"specific_tenant_users"}},N=A.useCallback(()=>{g.resetShareState(),o()},[g,o]),w=(d==null?void 0:d.type)==="organization";return e.jsx(s.Dialog,{open:!0,onOpenChange:N,children:e.jsxs(s.DialogContent,{className:"z-[51] flex max-h-[80vh] max-w-3xl flex-col",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx($e,{className:"h-5 w-5"}),' Share "',t==null?void 0:t.title,'"']})}),e.jsx(s.DialogDescription,{children:w?"Share this resource with org users or tenant users. As a super admin, you can share with all users.":"Share this resource with other users in your tenant."})]}),w?e.jsxs(s.Tabs,{value:b,onValueChange:S=>{const F=S;g.setSelectedTab(F),g.resetUserSelections()},className:"mb-4 min-h-0 flex-1",children:[e.jsxs(s.TabsList,{className:"mb-2 grid w-full grid-cols-2",children:[e.jsx(s.TabsTrigger,{value:"org",children:"Org Users"}),e.jsx(s.TabsTrigger,{value:"tenant",children:"Tenant Users"})]}),e.jsx(s.TabsContent,{value:"org",className:"min-h-0 flex-1 overflow-hidden",children:e.jsx("div",{className:"h-full overflow-y-auto",children:e.jsx(jn,{resource:t,resourceType:a,currentUser:d,onShareTabTypeChange:f,isSharing:n,isUpdating:l,isRemoving:r})})}),e.jsx(s.TabsContent,{value:"tenant",className:"min-h-0 flex-1 overflow-hidden",children:e.jsx("div",{className:"h-full overflow-y-auto",children:e.jsx(_s,{resource:t,resourceType:a,currentUser:d,onShareTabTypeChange:S=>m(S),isSharing:n,isUpdating:l,isRemoving:r})})})]}):e.jsx("div",{className:"mb-4 min-h-0 flex-1 overflow-hidden",children:e.jsx("div",{className:"h-full overflow-y-auto",children:e.jsx(_s,{resource:t,resourceType:a,currentUser:d,onShareTabTypeChange:S=>m(S),isSharing:n,isUpdating:l,isRemoving:r})})}),e.jsx("div",{className:"mt-auto flex-shrink-0",children:w?b==="org"?e.jsx(Us,{resource:t,existingShares:x,isSharing:n,isRemoving:r,isUpdating:l,onShare:c,onClose:o,shareTabType:h,currentAllUsersShare:k,onRemoveAccess:i}):e.jsx(Us,{resource:t,existingShares:j,isSharing:n,isRemoving:r,isUpdating:l,onShare:c,onClose:o,shareTabType:R(),currentAllUsersShare:v,onRemoveAccess:i}):e.jsx(bn,{resource:t,isSharing:n,isRemoving:r,isUpdating:l,onShare:c,onClose:o,shareTabType:u,currentAllUsersShare:v,onRemoveAccess:i})})]})})}function pe(t,a,n){return{resourceType:t,resourceId:a,data:{shares:n}}}function we(t,a,n){return{resourceType:t,resourceId:a,data:{shares:n}}}function bt(t,a,n){const{resourceType:r,resourceId:l,shareMutation:o,removeMutation:c,existingShares:i,resetUserSelections:d}=a;if(l)switch(t.context){case"org-tab":if(t.mode==="allOrgUsers"){const u=pe(r,l,[{scope:"org_users_only",role:t.orgWideRole}]);o(u,{onSuccess:()=>{d()}})}else if(t.mode==="specificOrgUsers"){const{selectedUsers:u,usersToRemove:m,usersToUpdate:h}=t;if(u&&u.length>0){const f=pe(r,l,u.map(g=>({scope:"specific_org_user",orgUserId:g.id,role:g.role})));o(f,{onSuccess:()=>{d()}})}if(m&&m.length>0){const f=we(r,l,m.map(g=>{var p,j;const b=(j=(p=i==null?void 0:i.shares)==null?void 0:p.specificOrgUsers)==null?void 0:j.find(x=>x.orgUserId===g);return{scope:"specific_org_user",orgUserId:g,role:(b==null?void 0:b.role)||"VIEWER"}}));c(f,{onSuccess:()=>{d()}})}h&&h.length>0&&h.forEach(f=>{const g=pe(r,l,[{scope:"specific_org_user",orgUserId:f.id,role:f.newRole}]);o(g,{onSuccess:()=>{d()}})})}break;case"tenant-tab":if(t.mode==="allTenants"){const u=pe(r,l,[{scope:"all_tenants_only",role:t.allTenantsRole}]);o(u,{onSuccess:()=>{d()}})}else if(t.mode==="allTenantUsers"){const u=pe(r,l,[{scope:"all_tenant_users",tenantId:t.tenantId,role:t.tenantWideRole}]);o(u,{onSuccess:()=>{d()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:u,usersToRemove:m,usersToUpdate:h,tenantId:f}=t;if(m&&m.length>0){const g=we(r,l,m.map(b=>{var j,x;const p=(x=(j=i==null?void 0:i.shares)==null?void 0:j.specificTenantUsers)==null?void 0:x.find(v=>v.tenantUserId===b);return{scope:"specific_tenant_user",tenantUserId:b,tenantId:f,role:(p==null?void 0:p.role)||"VIEWER"}}));c(g,{onSuccess:()=>{d()}})}if(h&&h.length>0&&h.forEach(g=>{const b=pe(r,l,[{scope:"specific_tenant_user",tenantUserId:g.id,tenantId:f,role:g.newRole}]);o(b,{onSuccess:()=>{d()}})}),u&&u.length>0){const g=pe(r,l,u.map(b=>({scope:"specific_tenant_user",tenantUserId:b.id,tenantId:f,role:b.role})));o(g,{onSuccess:()=>{d()}})}}break;case"tenant-dialog":if(t.mode==="allTenantUsers")if(t.removeAccess){const u=we(r,l,[{scope:"all_tenant_users",role:"VIEWER"}]);c(u,{onSuccess:()=>{d()}})}else if(t.updateAccess){const u=pe(r,l,[{scope:"all_tenant_users",tenantId:n==null?void 0:n.tenantId,role:t.tenantWideRole}]);o(u,{onSuccess:()=>{d()}})}else{const u=pe(r,l,[{scope:"all_tenant_users",tenantId:n==null?void 0:n.tenantId,role:t.tenantWideRole}]);o(u,{onSuccess:()=>{d()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:u,usersToRemove:m,usersToUpdate:h}=t;if(u&&u.length>0){const f=pe(r,l,u.map(g=>({scope:"specific_tenant_user",tenantUserId:g.id,role:g.role})));o(f,{onSuccess:()=>{d()}})}if(m&&m.length>0){const f=we(r,l,m.map(g=>{var p,j;const b=(j=(p=i==null?void 0:i.shares)==null?void 0:p.specificTenantUsers)==null?void 0:j.find(x=>x.tenantUserId===g);return{scope:"specific_tenant_user",tenantUserId:g,role:(b==null?void 0:b.role)||"VIEWER"}}));c(f,{onSuccess:()=>{d()}})}h&&h.length>0&&h.forEach(f=>{const g=pe(r,l,[{scope:"specific_tenant_user",tenantUserId:f.id,role:f.newRole}]);o(g,{onSuccess:()=>{d()}})})}break}}function yt(t,a,n,r){var u,m,h,f,g,b;const{resourceType:l,resourceId:o,removeMutation:c,existingShares:i,resetUserSelections:d}=r;if(o)if(t.length>0){const p=we(l,o,t.map(j=>{var v,k;const x=(k=(v=i==null?void 0:i.shares)==null?void 0:v.specificTenantUsers)==null?void 0:k.find(R=>R.tenantUserId===j);return{scope:"specific_tenant_user",tenantUserId:j,role:(x==null?void 0:x.role)||"VIEWER"}}));c(p,{onSuccess:()=>{d()},onError:j=>{console.error("Remove access failed:",j)}})}else{const p=a==="tenant"&&n==="allTenants",j=a==="tenant"&&n==="allTenantUsers";if(p){const x=(m=(u=i==null?void 0:i.shares)==null?void 0:u.allTenantsOnly)==null?void 0:m[0];if(x){const v=we(l,o,[{scope:"all_tenants_only",role:x.role}]);c(v,{onSuccess:()=>{d()},onError:k=>{console.error("Remove all-tenants access failed:",k)}})}}else if(j){const x=(f=(h=i==null?void 0:i.shares)==null?void 0:h.tenantWide)==null?void 0:f[0];if(x){const v=we(l,o,[{scope:"all_tenant_users",role:x.role}]);c(v,{onSuccess:()=>{d()},onError:k=>{console.error("Remove all-tenant-users access failed:",k)}})}}else{const x=(b=(g=i==null?void 0:i.shares)==null?void 0:g.orgUsersOnly)==null?void 0:b[0];if(x){const v=we(l,o,[{scope:"org_users_only",role:x.role}]);c(v,{onSuccess:()=>{d()},onError:k=>{console.error("Remove org-wide access failed:",k)}})}}}}function yn(t,a,n){const r=s.useShareManagementActions(),l=s.useShareUsersToRemove(),o=s.useShareSelectedTab(),c=s.useShareCurrentMode(),{currentUser:i}=s.useCurrentUserInfo(),{existingShares:d}=ke({debouncedSearchQuery:"",resourceId:t||"",resourceType:s.ResourceType.DASHBOARD,userType:"tenant"}),u=A.useCallback(()=>{r.resetUserSelections()},[r]),m=A.useCallback(f=>{if(!t)return;const g={resourceType:s.ResourceType.DASHBOARD,resourceId:t,shareMutation:a,removeMutation:n,existingShares:d,resetUserSelections:u};bt(f,g,i)},[t,a,n,d,u,i]),h=A.useCallback(()=>{if(!t)return;const f={resourceType:s.ResourceType.DASHBOARD,resourceId:t,removeMutation:n,existingShares:d,resetUserSelections:u};yt(l,o||"",c||"",f)},[t,a,n,d,u,l,o,c]);return{handleShareSubmit:m,handleRemoveAccess:h}}function vn(t,a,n){const{currentUser:r}=s.useCurrentUserInfo(),l=s.useShareManagementActions(),o=s.useShareUsersToRemove(),c=s.useShareSelectedTab(),i=s.useShareCurrentMode(),{existingShares:d}=ke({debouncedSearchQuery:"",resourceId:t||"",resourceType:s.ResourceType.VISUAL,userType:"tenant"}),u=A.useCallback(()=>{l.resetUserSelections()},[l]),m=A.useCallback(f=>{if(!t)return;const g={resourceType:s.ResourceType.VISUAL,resourceId:t,shareMutation:a,removeMutation:n,existingShares:d,resetUserSelections:u};bt(f,g,r)},[t,a,n,d,u,r]),h=A.useCallback(()=>{if(!t)return;const f={resourceType:s.ResourceType.VISUAL,resourceId:t,removeMutation:n,existingShares:d,resetUserSelections:u};yt(o,c||"",i||"",f)},[t,a,n,d,u,o,c,i]);return{handleShareSubmit:m,handleRemoveAccess:h}}function Nn(t){const a=t.toUpperCase().indexOf("WHERE"),n=t.toUpperCase().indexOf("GROUP BY"),r=t.toUpperCase().indexOf("LIMIT"),l=t.toUpperCase().indexOf("ORDER BY");let o=t.length;if(l!==-1&&(o=l),r!==-1&&r<o&&(o=r),a!==-1){const c=t.substring(0,a),i=t.substring(a);return`${c} {{ filters | where }} AND ${i.substring(6)}`}else if(n!==-1){const c=t.substring(0,n),i=t.substring(n);return`${c} {{ filters | where }} ${i}`}else{const c=t.substring(0,o),i=t.substring(o);return console.log("beforeClause",c),console.log("afterClause",i),i?`${c} {{ filters | where }} ${i}`:`${c.replace(/;$/,"")} {{ filters | where }}`}}function Ns(t){const[a,n]=A.useState(null),[r,l]=A.useState(null);return A.useEffect(()=>{if(!t||t.trim()===""){n(null),l(null);return}(async()=>{try{if(!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`Invalid URL format: ${t}`);try{new URL(t)}catch{throw new Error(`Invalid URL: ${t}`)}const i=`${t.endsWith("/")?t:`${t}/`}index.js`;try{if(!(await fetch(i,{method:"HEAD"})).ok)throw new Error(`Module not found at ${i}`)}catch{}const d=await import(i);if(typeof d.useChartStore!="function")throw new Error("useChartStore is not a function");n(()=>d.useChartStore),l(null)}catch(c){const i=c instanceof Error?c.message:"Unknown error";console.error("Failed to load remote chart store:",i),l(i),n(null)}})()},[t]),a}function Cn(t,a){if(t.length===0)return"";if(a){const n=t.find(r=>r.id===a);if(n){const r=n.tabTitle;if(r=="All__Header")return t[0].id;if(r&&r.endsWith("__Header")){const o=r.split("__")[0],c=t.find(i=>i.tabTitle===o);return c?c.id:t[0].id}return a}}return t[0].id}async function $s(t,a,n){if(!t||!a)throw new Error("Missing auth token or visual ID");const r=["resource-by-id","visual",a],l=n.getQueryData(r);if(l)return console.log("Using cached visual data for:",a),{data:l,fromCache:!0};console.log("Fetching visual data from network for:",a);const o=s.ue.loading("Loading visual...",{position:"top-center"});try{const c=await fetch(`https://semaphor.cloud/api/management/v1/visuals/${a}`,{headers:{Authorization:`Bearer ${t}`}});if(!c.ok)throw new Error("Failed to load visual");const i=await c.json();return n.setQueryData(r,i),s.ue.dismiss(o),{data:i,fromCache:!1}}catch(c){throw s.ue.dismiss(o),c}}function Sn(t,a,n,r,l){const o=t.frameObject;a(o);const c=o.cards.find(i=>i.id===o.activeCardId);c&&n(c),r(!0),l(!0)}function wn(){var f;const{setCardSql:t}=s.useEditorActions(),a=s.useEditorStore(g=>g.frame),n=s.useEditorStore(g=>g.card),r=Ns(((f=n.customCardPreferences)==null?void 0:f.url)||""),l=s.useEditorStore(g=>g.selectedSchemaName),o=s.useEditorStore(g=>g.selectedDatamodelId),c=s.useEditorStore(g=>g.selectedDatabaseName),i=s.useEditorStore(g=>g.selectedTableName),d=s.useEditorStore(g=>g.selectedConnectionId),u=s.useEditorStore(g=>g.isShowingVisual),m=n.sql;return{getUpdatedFrame:A.useCallback(()=>{var x;let g=m;m&&!m.includes("{{")&&(g=Nn(m),t(g));const b=(x=r==null?void 0:r.getState())==null?void 0:x.settings,p={...n,dataSource:n.dataSource||{mode:"directSource"},lastSelectedSchema:l,lastSelectedDatamodelId:o,lastSelectedDatabase:c,lastSelectedTable:i,connectionId:d,sql:g,customCfg:u?n.customCfg:null,preferences:n.preferences,...b&&{customCardPreferences:{...n.customCardPreferences,settings:b}}},j=a.cards.map(v=>v.id===n.id?p:v);return{...a,cards:j,activeCardId:Cn(j,a.activeCardId)}},[n,a,u,l,o,c,i,d,t,r,m])}}function Cs(){const{authToken:t}=s.useSemaphorContext(),a=s.useQueryClient(),n=s.useSelectedVisual(),{selectVisual:r}=s.useManagementActions(),{setFrame:l,setCard:o}=s.useEditorActions(),{setIsDashboardEditing:c,setIsVisualEditing:i,setSelectedFrameId:d,addFrame:u,setIsDashboardPanelOpen:m}=s.useDashboardActions(),h=s.useDashboardStore(p=>p.selectedSheetId),f=s.useVisualById((n==null?void 0:n.id)||"",{enabled:!!(n!=null&&n.id)&&!!(t!=null&&t.accessToken)}),g=A.useCallback(async p=>{try{r(p);const{data:j,fromCache:x}=await $s((t==null?void 0:t.accessToken)||"",p.id,a);return Sn(j,l,o,c,i),{success:!0,fromCache:x}}catch(j){return console.error("Error editing visual:",j),{success:!1,error:"Failed to load visual for editing"}}},[t==null?void 0:t.accessToken,a,r,l,o,c,i]),b=A.useCallback(async p=>{try{if(r(p),!h)return{success:!1,error:"No sheet selected. Please select a sheet first."};const{data:j,fromCache:x}=await $s((t==null?void 0:t.accessToken)||"",p.id,a),v=j.frameObject;if(!v)return{success:!1,error:"Visual has no frame data"};const k={...v,id:s.v4()};return u(h,k,"end"),c(!0),d(k.id),m(!1),{success:!0,fromCache:x}}catch(j){return console.error("Error adding visual:",j),{success:!1,error:"Failed to add visual to dashboard"}}},[t==null?void 0:t.accessToken,a,r,h,u,c,d,m]);return{visual:f.data,isLoading:f.isLoading,isError:f.isError,error:f.error,handleEditLibraryVisual:g,handleAddLibraryVisual:b,getUpdatedFrame:wn().getUpdatedFrame,refetch:f.refetch}}function Dn(){const[t,a]=A.useState(""),[n,r]=A.useState(!1),[l,o]=A.useState(""),[c,i]=A.useState(""),[d,u]=A.useState(!1),[m,h]=A.useState(null),[f,g]=A.useState(!1),[b,p]=A.useState(null),[j,x]=A.useState(null),{setIsDashboardEditing:v,setIsVisualEditing:k}=s.useDashboardActions(),{handleEditLibraryVisual:R,handleAddLibraryVisual:N}=Cs(),{resources:w,isLoading:y,isError:D,createResource:C,updateResource:I,deleteResource:S,duplicateResource:F,shareResource:T,isCreating:E,isDeleting:M,removeResourceShares:B,isSharing:L,isRemovingShares:O,isUpdatingShares:P}=s.useVisualManagement(()=>{g(!1),p(null)},()=>{r(!1),o(""),i("")}),{handleShareSubmit:K,handleRemoveAccess:$}=vn((m==null?void 0:m.id)||null,T,B);s.useCurrentUserInfo();const te=w.filter(W=>{var re,ie;return((re=W==null?void 0:W.title)==null?void 0:re.toLowerCase().includes(t.toLowerCase()))||((ie=W==null?void 0:W.description)==null?void 0:ie.toLowerCase().includes(t.toLowerCase()))}),X=W=>new Date(W).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),q=()=>{l.trim()&&C({title:l,description:c,isPrivate:!1})},H=W=>{p(W),g(!0)},_=()=>{b&&S(b.id)},{startUpdating:J,stopUpdating:z,isUpdating:U}=s.useResourceUpdateState(),Z=(W,re)=>{const ie=re.title!==void 0?"title":"description";J(W,ie),I({resourceId:W,data:re},{onSuccess:()=>{z(W,ie)},onError:()=>{z(W,ie)}})},le=W=>{x(W),F(W,{onSettled:()=>x(null)})},V=W=>{R(W)},se=W=>{N(W)},ne=W=>{const re=w.find(ie=>ie.id===W);re&&I({resourceId:W,data:{isPrivate:!re.isPrivate}})},Y=W=>{h(W),u(!0)};return s.useShareUsersToRemove(),s.useShareManagementActions(),ke({debouncedSearchQuery:"",resourceId:(m==null?void 0:m.id)||"",resourceType:s.ResourceType.VISUAL,userType:"tenant"}),y?e.jsx(ot,{}):D?e.jsx(s.ScrollArea,{className:"w-full flex-1 pr-2",children:e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx("p",{className:"text-sm text-destructive",children:"Failed to load visuals"}),e.jsx(s.Button,{variant:"outline",size:"sm",className:"mt-2",onClick:()=>window.location.reload(),children:"Retry"})]})}):e.jsxs("div",{className:"mt-1 flex h-full flex-1 flex-col gap-3 px-4",children:[e.jsx("div",{className:"px-1",children:n?e.jsxs(s.Card,{className:"border-dashed p-4 pb-2",children:[e.jsx(s.CardHeader,{className:"px-0 pb-3 pt-0",children:e.jsx(s.CardTitle,{className:"text-sm",children:"New Visual"})}),e.jsxs(s.CardContent,{className:"space-y-3 px-0 pb-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"title",className:"text-xs",children:"Title"}),e.jsx(s.Input$1,{id:"title",placeholder:"Enter visual title...",value:l,onChange:W=>o(W.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"description",className:"text-xs",children:"Description (optional)"}),e.jsx(s.Input$1,{id:"description",placeholder:"Enter visual description...",value:c,onChange:W=>i(W.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(s.Button,{onClick:q,size:"sm",className:"h-7 text-xs",disabled:!l.trim()||E,children:E?"Creating...":"Create"}),e.jsx(s.Button,{onClick:()=>{r(!1),o(""),i("")},variant:"outline",size:"sm",className:"h-7 text-xs",disabled:E,children:"Cancel"})]})]})]}):e.jsxs(s.Button,{onClick:()=>r(!0),className:"h-8 w-full",size:"sm",disabled:E,children:[e.jsx(s.Plus,{className:"mr-2 h-3.5 w-3.5"}),E?"Creating...":"Create New Visual"]})}),e.jsx("div",{className:"space-y-2 px-1",children:e.jsx(s.Input$1,{id:"search",placeholder:"Search by title or description...",value:t,onChange:W=>a(W.target.value),className:"h-8"})}),e.jsx("div",{className:"mb-4 flex flex-1 flex-col",children:e.jsx("div",{className:"flex flex-1 basis-0 flex-col gap-2 overflow-y-auto p-1",children:te.length===0?e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx(s.ChartPie,{className:"mx-auto mb-2 h-8 w-8 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No visuals found"})]}):te.map(W=>e.jsx(nn,{visual:W,onAddVisual:se,onEditVisual:V,onUpdateVisual:Z,onDeleteClick:H,onDuplicateVisual:le,onTogglePrivacy:ne,onShareVisual:Y,isDeleting:M,isDuplicating:j===W.id,isTitleUpdating:U(W.id,"title"),isDescriptionUpdating:U(W.id,"description"),formatDate:X},W.id))})}),d&&m&&e.jsx(jt,{resource:m,resourceType:s.ResourceType.VISUAL,onShare:K,isSharing:L,isRemoving:O,isUpdating:P,onClose:()=>{u(!1),h(null)},onRemoveAccess:$}),e.jsx(s.AlertDialog,{open:f,onOpenChange:W=>{!W&&M||(g(W),W||p(null))},children:e.jsxs(s.AlertDialogContent,{children:[e.jsxs(s.AlertDialogHeader,{children:[e.jsx(s.AlertDialogTitle,{children:"Delete Visual"}),e.jsxs(s.AlertDialogDescription,{children:['Are you sure you want to delete "',b==null?void 0:b.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:M,children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:W=>{W.preventDefault(),W.stopPropagation(),_()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:M,children:M?"Deleting...":"Delete"})]})]})})]})}function kn({dashboard:t,isDeleting:a,isDuplicating:n,isTitleUpdating:r=!1,isDescriptionUpdating:l=!1,onLoadDashboard:o,onUpdateDashboard:c,onDeleteClick:i,onDuplicateDashboard:d,onShareDashboard:u,formatDate:m,onDashboardItemClick:h}){var y,D,C;const{selectDashboard:f}=s.useManagementActions(),g=s.useIsDashboardSelected(t.id),{isConsoleMode:b}=s.useDashboardPreferences(),[p,j]=A.useState(!1),[x,v]=A.useState(!1),k=s.useDashboardStore(I=>I.actions.setIsDashboardPanelOpen);A.useEffect(()=>{n?(j(!0),v(!0)):x&&(j(!1),v(!1))},[n,x]);const R=()=>t.ownership.isOwner?t.ownership.status==="private"?e.jsx(vs,{className:"h-3 w-3 text-purple-500"}):e.jsx(s.Users,{className:"h-3.5 w-3.5 text-blue-600"}):e.jsx(De,{className:"h-3.5 w-3.5 text-slate-500"}),N=()=>e.jsx(s.LayoutDashboard,{className:"h-4 w-4 text-slate-400"}),w=()=>{f(t),o(t.id),h==null||h(t.id)};return e.jsxs("div",{className:s.cn("group relative flex cursor-pointer items-start gap-3 px-4 py-3 dark:border-slate-800","cursor-pointer transition-colors duration-150 hover:bg-slate-50 dark:hover:bg-slate-900/50",t.ownership.isOwner&&"border-blue-200 dark:border-blue-800",g&&"rounded-md bg-slate-50 ring-1 ring-inset ring-border dark:bg-slate-900/50"),tabIndex:0,onClick:w,children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-md bg-slate-100 dark:bg-slate-800",children:N()})}),e.jsxs("div",{className:"flex w-full items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(s.EditableText,{inputClassName:"text-sm font-medium text-slate-900 dark:text-slate-100",value:t.title,onSave:I=>c==null?void 0:c(t.id,{title:I}),isEditable:t.permissions.canEdit&&g,isPending:r,placeholder:"Untitled Dashboard",displayClassName:"line-clamp-1 max-w-[220px] text-sm font-medium text-slate-900 dark:text-slate-100"})}),e.jsx("div",{className:"shrink-0",children:R()})]}),e.jsx("div",{className:"mt-0.5",children:e.jsx(s.EditableText,{inputClassName:"line-clamp-1 text-xs text-slate-500 dark:text-slate-400",value:t.description||"",onSave:I=>c==null?void 0:c(t.id,{description:I}),isEditable:t.permissions.canEdit&&g,isPending:l,placeholder:"No description",displayClassName:"mt-0.5 max-w-[250px] line-clamp-1 text-xs text-slate-500 dark:text-slate-400"})})]}),e.jsx("div",{className:"absolute right-3 top-2 flex items-center justify-between text-xs text-muted-foreground",children:e.jsx("div",{className:s.cn("flex items-center opacity-0 transition-opacity duration-150 group-hover:opacity-100"),children:e.jsxs(s.DropdownMenu,{modal:!1,open:p,onOpenChange:j,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0 hover:bg-slate-200 dark:hover:bg-slate-700",onClick:I=>I.stopPropagation(),children:e.jsx(s.Ellipsis,{className:"h-3 w-3"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"z-[51] w-40",children:[e.jsxs(s.DropdownMenuItem,{onClick:I=>{I.preventDefault(),I.stopPropagation(),d(t.id)},disabled:n,children:[n?e.jsx(s.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(s.Copy,{className:"mr-2 h-3 w-3"}),n?"Duplicating...":"Duplicate"]}),t.permissions.canEdit&&e.jsx(e.Fragment,{children:e.jsxs(s.DropdownMenuItem,{onClick:I=>{I.stopPropagation(),u(t)},children:[e.jsx(s.Users,{className:"mr-2 h-3 w-3"}),"Share"]})}),t.permissions.canDelete&&e.jsxs(e.Fragment,{children:[e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:I=>{I.stopPropagation(),i(t),k(!1)},className:"text-destructive",disabled:a,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),a?"Deleting...":"Delete"]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs("div",{className:"space-y-1 px-2 py-2 text-xs text-slate-500 dark:text-slate-400",children:[(((y=t.ownership.createdBy)==null?void 0:y.type)==="tenant"||((D=t.ownership.createdBy)==null?void 0:D.type)==="organization"&&b)&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(De,{className:"h-3 w-3"}),e.jsx("span",{children:((C=t.ownership.createdBy)==null?void 0:C.name)||"Unknown"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Calendar,{className:"h-3 w-3"}),e.jsx("span",{children:m(t.lastModified)})]})]})]})]})})})]})]},t.id)}function Tn({onRetry:t}){return e.jsx(s.ScrollArea,{className:"w-full flex-1 pr-2",children:e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx("p",{className:"text-sm text-destructive",children:"Failed to load dashboards"}),e.jsx(s.Button,{variant:"outline",size:"sm",className:"mt-2",onClick:t,children:"Retry"})]})})}function En(t){const[a,n]=A.useState(""),[r,l]=A.useState(!1),[o,c]=A.useState(""),[i,d]=A.useState(""),[u,m]=A.useState(!1),[h,f]=A.useState(null),[g,b]=A.useState(!1),[p,j]=A.useState(null),[x,v]=A.useState(null),k=s.useManagementStore(Q=>Q.lastSelectedDashboard),R=s.useManagementStore(Q=>Q.selectedDashboard),N=s.useManagementStore(Q=>Q.actions.selectDashboard),w=s.useManagementStore(Q=>Q.actions.clearSelectedDashboard);s.useShareManagementActions(),s.useShareUsersToRemove(),s.useShareSelectedTab(),s.useShareCurrentMode();const{tokenProps:y,id:D}=s.useSemaphorContext(),{permissions:C}=s.useRoleAwareDisplayPreferences(),{resources:I,isLoading:S,isError:F,createResource:T,updateResource:E,deleteResource:M,duplicateResource:B,isCreating:L,isDeleting:O,isSharing:P,isRemovingShares:K,isUpdatingShares:$,shareResource:te,removeResourceShares:X}=s.useDashboardManagement(()=>{b(!1);const Q=p==null?void 0:p.id;j(null),(R==null?void 0:R.id)===Q&&(!(y!=null&&y.dashboard_id)&&!D?w():k&&k.id!==Q&&N(k))},()=>{l(!1),c(""),d("")}),{handleShareSubmit:q,handleRemoveAccess:H}=yn((h==null?void 0:h.id)||null,te,X),{currentUser:_}=s.useCurrentUserInfo(),J=I.filter(Q=>{var oe,ee;return((oe=Q==null?void 0:Q.title)==null?void 0:oe.toLowerCase().includes(a.toLowerCase()))||((ee=Q==null?void 0:Q.description)==null?void 0:ee.toLowerCase().includes(a.toLowerCase()))}),z=Q=>new Date(Q).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),U=()=>{o.trim()&&T({title:o,description:i,isPrivate:!1})},Z=Q=>{var oe;(oe=t.onLoadDashboard)==null||oe.call(t,Q)},le=Q=>{j(Q),b(!0)},V=()=>{p&&M(p.id)},se=Q=>{v(Q),B(Q,{onSettled:()=>v(null)})},{startUpdating:ne,stopUpdating:Y,isUpdating:W}=s.useResourceUpdateState(),re=(Q,oe)=>{const ee=oe.title!==void 0?"title":"description";ne(Q,ee),E({resourceId:Q,data:oe},{onSuccess:()=>{Y(Q,ee)},onError:()=>{Y(Q,ee)}})},ie=Q=>{const oe=I.find(ee=>ee.id===Q);oe&&E({resourceId:Q,data:{isPrivate:!oe.isPrivate}})},he=Q=>{f(Q),_==null||_.type,m(!0)};return ke({debouncedSearchQuery:"",resourceId:(h==null?void 0:h.id)||"",resourceType:s.ResourceType.DASHBOARD,userType:"tenant"}),S?e.jsx(ot,{}):F?e.jsx(Tn,{onRetry:()=>window.location.reload()}):e.jsxs("div",{className:"mt-1 flex h-full flex-1 flex-col gap-3 px-4",children:[C.canCreateDashboards&&e.jsx("div",{className:"px-1",children:r?e.jsxs(s.Card,{className:"border-dashed p-4 pb-2",children:[e.jsx(s.CardHeader,{className:"px-0 pb-3 pt-0",children:e.jsx(s.CardTitle,{className:"text-sm",children:"New Dashboard"})}),e.jsxs(s.CardContent,{className:"space-y-3 px-0 pb-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"title",className:"text-xs",children:"Title"}),e.jsx(s.Input$1,{id:"title",placeholder:"Enter dashboard title...",value:o,onChange:Q=>c(Q.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"description",className:"text-xs",children:"Description (optional)"}),e.jsx(s.Input$1,{id:"description",placeholder:"Enter dashboard description...",value:i,onChange:Q=>d(Q.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(s.Button,{onClick:U,size:"sm",className:"h-7 text-xs",disabled:!o.trim()||L,children:L?"Creating...":"Create"}),e.jsx(s.Button,{onClick:()=>{l(!1),c(""),d("")},variant:"outline",size:"sm",className:"h-7 text-xs",disabled:L,children:"Cancel"})]})]})]}):e.jsxs(s.Button,{onClick:()=>l(!0),className:"h-8 w-full",size:"sm",disabled:L,children:[e.jsx(s.Plus,{className:"mr-2 h-3.5 w-3.5"}),L?"Creating...":"Create New Dashboard"]})}),I&&I.length>5&&e.jsx("div",{className:"space-y-2 px-1",children:e.jsx(s.Input$1,{id:"search",placeholder:"Search by title or description...",value:a,onChange:Q=>n(Q.target.value),className:"h-8"})}),e.jsx("div",{className:"mb-4 flex flex-1 flex-col",children:e.jsx("div",{className:"flex flex-1 basis-0 flex-col gap-2 overflow-y-auto p-1",children:J.length===0?e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx(va,{className:"mx-auto mb-2 h-8 w-8 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No dashboards found"})]}):J.map(Q=>e.jsx(kn,{dashboard:Q,isDeleting:O,isDuplicating:x===Q.id,isTitleUpdating:W(Q.id,"title"),isDescriptionUpdating:W(Q.id,"description"),onLoadDashboard:Z,onEditDashboard:t.onEditDashboard,onUpdateDashboard:re,onDeleteClick:le,onDuplicateDashboard:se,onTogglePrivacy:ie,onShareDashboard:he,formatDate:z,onDashboardItemClick:t.onDashboardItemClick},Q.id))})}),u&&h&&e.jsx(jt,{resource:h,resourceType:s.ResourceType.DASHBOARD,onShare:q,isSharing:P,isRemoving:K,isUpdating:$,onClose:()=>{m(!1),f(null)},onRemoveAccess:H}),e.jsx(s.AlertDialog,{open:g,onOpenChange:Q=>{!Q&&O||(b(Q),Q||j(null))},children:e.jsxs(s.AlertDialogContent,{children:[e.jsxs(s.AlertDialogHeader,{children:[e.jsx(s.AlertDialogTitle,{children:"Delete Dashboard"}),e.jsxs(s.AlertDialogDescription,{children:['Are you sure you want to delete "',p==null?void 0:p.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:O,children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:Q=>{Q.preventDefault(),Q.stopPropagation(),V()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:O,children:O?"Deleting...":"Delete"})]})]})})]})}function vt({isOpen:t,onClose:a,className:n,onDashboardItemClick:r}){s.useDashboardStore(j=>j.dashboard);const{setDashboard:l,addSheet:o}=s.useDashboardStore(j=>j.actions),{currentUser:c}=s.useCurrentUserInfo(),i=c,{permissions:d}=s.useRoleAwareDisplayPreferences(),u=(d.canAccessVisuals,"dashboards"),[m,h]=s.useLocalStorageState("resource-management-active-tab",u),f=d.canAccessVisuals?m:"dashboards",g=mt(a,{enabled:t}),b=j=>{},p=j=>{console.log("Editing dashboard:",j)};return e.jsx(s.TooltipProvider$1,{children:e.jsxs("div",{ref:g,className:s.cn("absolute inset-y-0 left-0 z-[51] flex w-96 flex-col border-r bg-background shadow-lg transition-transform duration-300 ease-in-out",t?"translate-x-0":"hidden -translate-x-full",n),children:[e.jsxs("div",{className:"flex items-center justify-between p-4",children:[e.jsx("div",{className:"flex items-center gap-3",children:i&&e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-2 rounded-lg border border-muted bg-muted/30 px-2 py-1",children:[e.jsxs(s.Avatar,{className:"h-5 w-5",children:[e.jsx(s.AvatarImage,{alt:i.name}),e.jsx(s.AvatarFallback,{className:"text-xs",children:i.name.charAt(0).toUpperCase()})]}),e.jsx("span",{className:"text-xs font-medium",children:i.name})]})}),e.jsx(s.TooltipContent,{side:"bottom",className:"ml-2 max-w-xs",children:e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"font-medium",children:i.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:i.email}),i.role&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Role:"," ",s.toTitleCase(i.role.replace(/_/g," "))]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["ID: ",i.id]})]})})]})})}),e.jsx(s.IconButton,{className:"h-6 p-1 text-muted-foreground hover:text-foreground",onClick:a,tooltip:"Hide Dashboard Management",children:e.jsx(s.X,{className:"h-3.5 w-3.5"})})]}),e.jsx("div",{className:"flex flex-1 flex-col overflow-hidden",children:e.jsxs(s.Tabs,{value:f,onValueChange:d.canAccessVisuals?h:void 0,className:"flex h-9 grow flex-col",children:[d.canAccessVisuals?e.jsx("div",{className:"px-5",children:e.jsxs(s.TabsList,{className:"grid h-8 w-full grid-cols-2",children:[e.jsx(s.TabsTrigger,{value:"dashboards",className:"h-6",children:"Dashboards"}),e.jsx(s.TabsTrigger,{value:"visuals",className:"h-6",children:"Visuals"})]})}):e.jsx("div",{className:"px-5 pb-2",children:e.jsx("h3",{className:"text-sm font-medium",children:"Dashboards"})}),e.jsx(s.TabsContent,{value:"dashboards",className:"flex-1",children:e.jsx(En,{onLoadDashboard:b,onEditDashboard:p,onDashboardItemClick:r})}),d.canAccessVisuals&&e.jsx(s.TabsContent,{value:"visuals",className:"flex-1",children:e.jsx(Dn,{})})]})})]})})}function In(){var se,ne;const{authToken:t,tokenProps:a,id:n}=s.useSemaphorContext(),{isLocalDev:r}=s.useDashboardPreferences(),{permissions:l}=s.useRoleAwareDisplayPreferences(),o=s.useHasDashboardId();s.useDashboardStore(Y=>Y.theme);const c=s.useDashboardStore(Y=>Y.lenses),i=s.useDashboardStore(Y=>Y.selectedLensId),d=c==null?void 0:c.find(Y=>Y.id===i),u=s.useDashboardStore(Y=>Y.dashboard);s.useDashboardStore(Y=>Y.selectedSheetId);const m=s.useDashboardStore(Y=>Y.isDashboardEditing),h=s.useEditorStore(Y=>Y.card),f=s.useEditorStore(Y=>Y.selectedConnectionId),[g,b]=A.useState(!1),p=s.useDashboardStore(Y=>Y.isDashboardPanelOpen),j=s.useDashboardStore(Y=>Y.actions.setIsDashboardPanelOpen),x=s.useDashboardStore(Y=>Y.filterValues),v=s.useDashboardStore(Y=>Y.isVisualEditing),k=s.useManagementStore(Y=>Y.selectedDashboard),R=s.useManagementStore(Y=>Y.initialDashboard),N=k?(ne=k==null?void 0:k.permissions)==null?void 0:ne.canEdit:(se=R==null?void 0:R.permissions)==null?void 0:se.canEdit,w=s.useDashboardStore(Y=>Y.showFilters),y=s.useDashboardStore(Y=>Y.showDashboardJSON),D=s.useDashboardStore(Y=>Y.onSaveFunction),C=s.useDashboardStore(Y=>Y.actions.setShowFilters),{addFrame:I,setSelectedFrameId:S}=s.useDashboardStore(Y=>Y.actions),{getSelectedSheet:F,setIsDashboardEditing:T,setShowDashboardJSON:E}=s.useDashboardStore(Y=>Y.actions),M=F(),{setInitialDashboard:B,clearSelectedDashboard:L}=s.useManagementStore(Y=>Y.actions),{resources:O}=s.useResourceManagement(s.ResourceType.DASHBOARD);A.useEffect(()=>{if(O&&O.length>0){const Y=u==null?void 0:u.id;if(Y){const W=O.find(re=>re.id===Y);W&&B(W)}}},[O,u==null?void 0:u.id,B]);const P=a.orgUserId||a.tenantId,K=m&&!v&&P&&N;function $(){var ie,he;const Y=h.dataSource;if(Y)return Y;const W=(he=(ie=u.aiContext)==null?void 0:ie.selectedEntities)==null?void 0:he[0],re=W==null?void 0:W.type;if(W)return{connectionId:W.connectionId,connectionType:W.connectionType,type:re,selectedEntities:[W]}}const te=()=>{if(!m||!M)return;const W={dataSource:$(),mode:"explorer",connectionId:f,id:s.v4(),title:"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[]},re={id:s.v4(),cards:[W],activeCardId:W.id};I(M.id,re),S(re.id)},X=()=>{T(!0)},[q,H]=A.useState(!1),_=s.useUpdateResource(s.ResourceType.DASHBOARD);async function J(){const Y=es(u);H(!0);const W={template:Y};_.mutate({resourceId:Y.id,data:W},{onSuccess:()=>{H(!1),s.ue.success("Dashboard saved!")},onError:()=>{H(!1),s.ue.error("Failed to save dashboard")}})}async function z(){if(b(!0),!i||!d)return;const Y=es(u),W=JSON.stringify(Y),re={...d,template:W,filterValues:x};await gs(re,t==null?void 0:t.accessToken),s.ue.success("Lens saved"),D==null||D(Y),b(!1)}if(v)return null;const U=(d==null?void 0:d.name)||u.title,le=O&&O.length>0&&(a.orgUserId||a.tenantId&&a.endUserId&&a.endUserEmail),V=k&&!(a!=null&&a.dashboard_id)&&!n;return e.jsxs("div",{className:"flex h-10 items-center justify-between gap-2 border-b py-2 pl-3 pr-2",role:"dashboard-controls",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[le&&e.jsxs(e.Fragment,{children:[V&&e.jsx(s.IconButton,{"aria-label":"Dashboard Hub",tooltip:"Back to Dashboard Hub",onClick:()=>L(),className:"h-7 p-2",children:e.jsx(s.House,{className:"h-4 w-4"})}),e.jsx(s.IconButton,{"aria-label":"Manage Dashboards",tooltip:o?"Manage Dashboards":"Select a dashboard to continue",onClick:()=>j(!0),className:"h-7 p-2",buttonProps:{disabled:!o},children:e.jsx(Aa,{className:"h-4 w-4"})})]}),!v&&o&&e.jsx(s.Label,{children:U})]}),e.jsxs("div",{className:"flex gap-2",children:[r&&e.jsx(s.IconButton,{tooltip:"Invalidate Token",onClick:s.invalidateToken,className:"h-7 p-2",children:e.jsx(Ua,{className:"h-4 w-4"})}),!v&&o&&e.jsx(tn,{}),!v&&o&&e.jsx(lt,{}),m&&!v&&P&&r&&o&&e.jsx(en,{}),!v&&P&&r&&o&&e.jsx(sn,{}),m&&!v&&P&&d&&r&&o&&e.jsxs(s.Button,{className:"h-7 p-2",variant:"secondary",disabled:g,onClick:z,size:"sm",children:[e.jsx(fs,{className:"mr-2 h-4 w-4"}),"Save Lens"]}),m&&!v&&o&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",size:"sm",disabled:!m,onClick:te,children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Frame"]}),!v&&!m&&l.canEdit&&o&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",onClick:X,size:"sm",children:[e.jsx(s.Pencil,{className:"mr-2 h-4 w-4"}),"Edit"]}),m&&!v&&o&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",onClick:()=>{T(!1),E(!1)},children:[e.jsx(s.Cross2Icon,{className:"mr-2 h-4 w-4"}),"Close"]}),K&&o&&e.jsxs(s.Button,{className:"h-7 p-2",variant:"outline",disabled:q,onClick:J,size:"sm",children:[q?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(fs,{className:"mr-2 h-4 w-4"}),q?"Saving...":"Save"]}),!w&&!v&&m&&l.canUseFilters&&o&&e.jsx(s.Button,{className:"h-7 p-2",variant:"outline",onClick:()=>C(!0),size:"sm",children:e.jsx(s.Filter,{className:"h-4 w-4"})}),!v&&m&&r&&o&&e.jsx("div",{className:"flex items-center space-x-2",children:e.jsx(s.Button,{className:"h-7 p-2",onClick:()=>E(!y),size:"sm",variant:"ghost",children:e.jsx(Be,{className:"h-4 w-4"})})}),!v&&r&&e.jsx(Ja,{}),!v&&e.jsx(vt,{isOpen:p,onClose:()=>j(!1)})]})]})}function An({name:t,items:a,value:n,onChange:r,isLoading:l,isError:o,refetch:c,className:i,icon:d,showNone:u=!1}){const m=Te.useRef(null),[h,f]=Te.useState(!1),[g,b]=Te.useState("100%"),p=u?[...a||[],{id:"none",name:"None"}]:a;Te.useLayoutEffect(()=>{m.current&&b(m.current.offsetWidth)},[]);function j(){var v;return l?"Loading...":o?"Error":n?(v=a==null?void 0:a.find(k=>k.id===n))==null?void 0:v.name:`Select ${t}`}function x(v,k){r(k),f(!1)}return e.jsxs(s.Popover,{open:h,onOpenChange:f,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{ref:m,variant:"outline",role:"combobox","aria-expanded":h,className:s.cn("flex h-9 w-full justify-between",i),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[d&&e.jsx("div",{className:"mr-2",children:d}),e.jsx("span",{className:"max-w-[150px] overflow-hidden truncate text-ellipsis whitespace-nowrap",children:j()})]}),e.jsx(s.ChevronDown,{className:"size-4 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-full p-0",style:{minWidth:g},children:e.jsxs(s.Command,{children:[e.jsxs("div",{className:"flex h-9 items-center justify-between border-b pr-1",children:[e.jsx(s.CommandInput,{className:"h-9",placeholder:"Search..."}),e.jsx(s.IconButton,{className:"h-7",onClick:c,children:e.jsx(tt,{className:s.cn("size-3.5 opacity-50",l&&"animate-spin")})})]}),e.jsxs(s.CommandList,{children:[e.jsxs(s.CommandEmpty,{children:["No ",t==null?void 0:t.toLowerCase()," found."]}),e.jsx(s.CommandGroup,{children:p==null?void 0:p.map(v=>e.jsx(s.CommandItem,{className:"overflow-x-auto",value:v.name,onSelect:k=>x(k,v.id),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Check,{className:s.cn("size-4",n===v.id?"opacity-100":"opacity-0")}),e.jsx("div",{title:v.name,children:v.name})]})},v.id))})]})]})})]})}function Oe({title:t,items:a,value:n,isLoading:r,isError:l,refetch:o,onChange:c,showNone:i=!1,className:d,disabled:u=!1,type:m="combobox"}){const h=r?"Loading...":l?"Error":n;function f(){if(t==="Connection")return e.jsx(za,{className:"size-4"});if(t==="Database")return e.jsx(s.Database,{className:"size-4"});if(t==="Schema")return e.jsx(Ba,{className:"size-4"});if(t==="Table")return e.jsx(s.Table2,{className:"size-4"});if(t==="Model")return e.jsx(da,{className:"size-4"})}function g(){return e.jsxs(s.Select,{disabled:u,value:h,onValueChange:c,children:[e.jsx(s.SelectTrigger,{className:s.cn("h-9 w-full border-muted focus:ring-1 focus:ring-offset-0",d),children:e.jsx(s.SelectValue,{placeholder:r?"Loading...":l?"Error":`Select ${t}`})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[r?e.jsx(s.SelectLabel,{children:"Loading..."}):e.jsxs(s.SelectLabel,{className:"flex items-center justify-between gap-2",children:[t,e.jsx(tt,{className:s.cn("mr-1 size-3 cursor-pointer text-muted-foreground hover:text-foreground",r&&"animate-spin"),onClick:o})]}),e.jsxs(e.Fragment,{children:[i&&e.jsx(s.SelectItem,{value:"none",children:"None"},"none"),a&&a.map((p,j)=>e.jsx(s.SelectItem,{value:p.id,children:p.name},j))]}),(r||l)&&e.jsx(s.SelectItem,{value:h,children:h})]})})]})}function b(){return e.jsx(An,{icon:f(),items:a,value:h,onChange:c||(()=>{}),isLoading:r,isError:l,refetch:o,name:t,showNone:i})}return e.jsx(s.TooltipProvider$1,{delayDuration:0,children:e.jsx("div",{className:"flex items-center gap-2",children:m==="select"?g():b()})})}function Mn({column:t}){const[a,n]=A.useState(!1),r=s.useEditorStore(p=>p.selectedTableName),l=s.useEditorStore(p=>p.selectedSchemaName),o=s.useEditorStore(p=>p.selectedDatabaseName),c=s.useEditorStore(p=>p.selectedDatamodelId),i=s.useEditorStore(p=>p.sqlGen),{modelItems:d,connectionType:u}=s.useEditorAside(),m=s.useEditorStore(p=>p.actions.setSqlGen),h=s.useEditorStore(p=>p.actions.setCardSql),f=s.useEditorStore(p=>p.actions.setRunSql);function g(p,j){var R;const x=s.createSqlGenConfig(p,i,j),v=(R=d==null?void 0:d.find(N=>N.id===c))==null?void 0:R.name;m(x);const k=s.getSql(x,s.fmt(l||""),s.fmt(r),v||"",u,o||"");k&&(h(k),f(!0)),n(!1)}function b(){return e.jsxs("ul",{className:"text-xs",children:[e.jsx("li",{onClick:()=>g(t,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),e.jsx("li",{onClick:()=>g(t,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),e.jsx("li",{onClick:()=>g(t,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),e.jsx("li",{onClick:()=>g(t,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),e.jsx("li",{onClick:()=>g(t,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return e.jsxs(s.HoverCard,{openDelay:0,open:a,onOpenChange:n,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.EllipsisVertical,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover:visible"})}),e.jsx(s.HoverCardContent,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:b()})]})}function Ln({dataType:t}){const a=s.getDataType(t);return a==="string"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(ge,{className:"h-3 w-3"})}):a==="number"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(Ne,{className:"h-3 w-3"})}):a==="date"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):a==="boolean"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Le,{className:"h-3 w-3"})}):a==="json"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Be,{className:"h-3 w-3"})}):a==="geo"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(_e,{className:"h-3 w-3"})}):a==="calculated"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(qe,{className:"h-3 w-3"})}):e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(ge,{className:"h-3 w-3"})})}function os({column:t,className:a}){return e.jsxs("div",{className:s.cn("flex min-h-8 grow items-center gap-2 px-3 py-[6px] text-sm",a),children:[e.jsx(Ln,{dataType:t.data_type}),e.jsx("span",{children:t.column_name})]})}function Rn({id:t,children:a,type:n="column"}){const{attributes:r,listeners:l,setNodeRef:o,transform:c}=s.useDraggable({id:t,data:{type:n}}),i=c?{translate:s.CSS.Translate.toString(c),transform:s.CSS.Transform.toString(c)}:void 0;return e.jsx("div",{ref:o,style:i,...l,...r,children:a})}function On({onClick:t,column:a}){const n=s.useDndStore(m=>m.activeId),r=s.useEditorStore(m=>{var h;return(h=m.card.queryConfig)==null?void 0:h.groupByColumns}),l=s.useEditorStore(m=>{var h;return(h=m.card.queryConfig)==null?void 0:h.metricColumns}),o=s.useEditorStore(m=>{var h;return(h=m.card.queryConfig)==null?void 0:h.filterColumns});function c(m){return i(m)||d(m)||u(m)}function i(m){return r==null?void 0:r.some(h=>h.name===m.column_name)}function d(m){return l==null?void 0:l.some(h=>h.name===m.column_name)}function u(m){return o==null?void 0:o.some(h=>h.name===m.column_name)}return e.jsxs("div",{onClick:()=>t(a),className:s.cn("group relative grow cursor-pointer overflow-x-hidden overflow-y-hidden border border-dashed border-background transition-colors hover:bg-muted/50",{"bg-muted":c(a)}),children:[n===a.column_name&&e.jsx(s.DragOverlay,{children:e.jsx(os,{column:a,className:"rounded-md border-2 border-dashed border-muted-foreground bg-muted shadow-md"})}),n===a.column_name&&e.jsx("div",{className:"absolute inset-0",children:n===a.column_name&&e.jsx(os,{column:a})}),e.jsx(Rn,{id:a.column_name,type:"column",children:e.jsx(os,{column:a})})]})}const is={id:"__placeholder__",role:"groupby",type:"string"},cs={id:"__placeholder__",role:"groupby",type:"string"},ds={id:"__placeholder__",role:"metric",type:"number"},us={name:"Filter",id:"__placeholder__",role:"filter",type:"string"},Nt={id:"__placeholder__"},Ie="droppable-group-by",Ae="droppable-metrics",Me="droppable-pivot-by",ts="sortable-group-by",js="sortable-metrics",as="sortable-pivot-by",bs="droppable-filters",ys="sortable-filters",Ss="sortable-order-by";function Bn(){const t=s.useDndStore(E=>E.insertIndex),a=s.useEditorStore(E=>{var M;return((M=E.card.queryConfig)==null?void 0:M.groupByColumns)||[]}),n=s.useEditorStore(E=>{var M;return((M=E.card.queryConfig)==null?void 0:M.metricColumns)||[]}),r=s.useEditorStore(E=>{var M;return((M=E.card.queryConfig)==null?void 0:M.filterColumns)||[]}),l=s.useEditorStore(E=>{var M;return((M=E.card.queryConfig)==null?void 0:M.orderBy)||[]}),o=s.useEditorStore(E=>{var M;return((M=E.card.queryConfig)==null?void 0:M.pivotColumns)||[]}),{setInsertIndex:c,setActiveId:i,setPreviewGroupByColumns:d,setPreviewMetricColumns:u,setPreviewFilterColumns:m,setPreviewPivotColumns:h}=s.useDndActions(),{setGroupByColumns:f,setMetricColumns:g,setFilterColumns:b,setOrderByColumns:p,setPivotByColumns:j}=s.useEditorActions(),{columns:x}=s.useDataColumns(),{formattedTableName:v}=s.useEditorAside(),k=s.useSensors(s.useSensor(s.MouseSensor,{activationConstraint:{distance:1}})),R=E=>{var L;const{active:M,over:B}=E;if(((L=M.data.current)==null?void 0:L.type)==="column"&&B){const O=B.id,P=x.find(X=>X.column_name===M.id);if(!P)return;const K=s.isNumberDataType(P.data_type),$=s.isTextDataType(P.data_type),te=s.isDateDataType(P.data_type);if($||te){if(a.some(q=>q.id===O)){const q=a.findIndex(_=>_.id===O);c(q);const H=a.filter(_=>_.id!==is.id);H.splice(q,0,is),d(H)}else if(B.id===Ie){c(a.length);const q=[...a,is];d(q),u(n),m(r)}}if($||te){if(o.some(q=>q.id===O)){const q=o.findIndex(_=>_.id===O);c(q);const H=o.filter(_=>_.id!==cs.id);H.splice(q,0,cs),h(H)}else if(B.id===Me){c(o.length);const q=[...o,cs];h(q),d(a),u(n),m(r)}}if(K||$){if(n.some(q=>q.id===O)){console.log("isOverMetricSortable",O);const q=n.findIndex(_=>_.id===O);c(q);const H=n.filter(_=>_.id!==ds.id);H.splice(q,0,ds),u(H)}else if(B.id===Ae){c(n.length);const q=[...n,ds];u(q),m(r),d(a),h(o)}}if(w(P)){if(r.some(q=>q.id===O)){const q=r.findIndex(_=>_.id===O);c(q);const H=r.filter(_=>_.id!==us.id);H.splice(q,0,us),m(H)}else if(B.id===bs){c(r.length);const q=[...r,us];m(q),u(n),d(a),h(o)}}}else d(a),u(n),m(r),h(o)};function N(E){i(E.active.id),c(null),d(a),u(n),m(r),h(o)}function w(E){return!r.some(M=>M.name===E.column_name)}function y(E,M="SUM"){const{column_name:B,data_type:L}=E,O=[...n],P=t!==null?t:n.length,K={...E,id:ye(B),name:B,label:Ye(B,M),type:L,role:"metric",aggregate:M};O.splice(P,0,K),g(O)}function D(E){const M=s.isTextDataType(E.data_type);s.isDateDataType(E.data_type);const B=[...o],L=t!==null?t:o.length;let O;M?O={...E,id:ye(E.column_name),name:E.column_name,type:E.data_type,role:"groupby"}:O={...E,id:ye(E.column_name),name:E.column_name,type:E.data_type,role:"groupby",label:Fe(E.column_name,"month"),granularity:"month"},B.splice(L,0,O),j(B)}function C(E){const M=s.isTextDataType(E.data_type);s.isDateDataType(E.data_type);const B=[...a],L=t!==null?t:a.length;let O;M?O={...E,id:ye(E.column_name),name:E.column_name,type:E.data_type,role:"groupby"}:O={...E,id:ye(E.column_name),name:E.column_name,type:E.data_type,role:"groupby",label:Fe(E.column_name,"month"),granularity:"month"},B.splice(L,0,O),f(B)}function I(E){const M=[...r],B=t!==null?t:r.length,L={...E,id:ye(E.column_name),name:E.column_name,type:E.data_type,sql:s.getDefaultFilterSql(E.data_type,v,s.fmt(E.column_name)),role:"filter"};M.splice(B,0,L),b(M)}function S(E){var O,P,K,$,te,X,q,H;const{active:M,over:B}=E,L=M.data.current;if((L==null?void 0:L.type)==="column"&&B){const _=x.find(Z=>Z.column_name===M.id);if(!_)return;const J=s.isNumberDataType(_.data_type),z=s.isTextDataType(_.data_type),U=s.isDateDataType(_.data_type);(z||U)&&(B.id===Ie||((O=B.data.current)==null?void 0:O.type)===ts)&&C(_),(z||U)&&(B.id===Me||((P=B.data.current)==null?void 0:P.type)===as)?D(_):(J||z)&&(B.id===Ae||((K=B.data.current)==null?void 0:K.type)===js)?(J&&y(_),z&&y(_,"COUNT")):w(_)&&(B.id===bs||(($=B.data.current)==null?void 0:$.type)===ys)&&I(_)}if(B&&((te=B.data.current)==null?void 0:te.type)===ts&&a.some(_=>_.id===M.id)){const _=a.findIndex(z=>z.id===M.id),J=a.findIndex(z=>z.id===B.id);if(_!==-1&&J!==-1&&_!==J){const z=[...a],[U]=z.splice(_,1);z.splice(J,0,U),f(z)}}if(B&&((X=B.data.current)==null?void 0:X.type)===as&&o.some(_=>_.id===M.id)){const _=o.findIndex(z=>z.id===M.id),J=o.findIndex(z=>z.id===B.id);if(_!==-1&&J!==-1&&_!==J){const z=[...o],[U]=z.splice(_,1);z.splice(J,0,U),j(z)}}if(B&&((q=B.data.current)==null?void 0:q.type)===js&&n.some(_=>_.id===M.id)){const _=n.findIndex(z=>z.id===M.id),J=n.findIndex(z=>z.id===B.id);if(_!==-1&&J!==-1&&_!==J){const z=[...n],[U]=z.splice(_,1);z.splice(J,0,U),g(z)}}if(B&&((H=B.data.current)==null?void 0:H.type)===ys&&r.some(_=>_.id===M.id)){const _=r.findIndex(z=>z.id===M.id),J=r.findIndex(z=>z.id===B.id);if(_!==-1&&J!==-1&&_!==J){const z=[...r],[U]=z.splice(_,1);z.splice(J,0,U),b(z)}}F(E),i(null),c(null),d(a),u(n),m(r),h(o)}function F(E){const{active:M,over:B}=E,L=M.data.current;if((L==null?void 0:L.type)===Ss&&B){const O=l.findIndex(K=>Ve(K.columnId)===M.id),P=l.findIndex(K=>Ve(K.columnId)===B.id);if(O!==-1&&P!==-1&&O!==P){const K=[...l],[$]=K.splice(O,1);K.splice(P,0,$),p(K)}}}function T(){i(null),c(null),d(a),u(n),m(r)}return{handleDragOver:R,handleDragEnd:S,handleDragStart:N,handleDragCancel:T,sensors:k}}function ye(t){return`${t}-${s.v4()}`}function Ye(t,a){const n=s.toTitleCase(t.replace(/_/g," "));switch(a){case"SUM":return`Sum of ${n}`;case"COUNT":return`Count of ${n}`;case"DISTINCT":return`Unique ${n}`;case"AVG":return`Average of ${n}`;case"MIN":return`Min of ${n}`;case"MAX":return`Max of ${n}`;default:return n}}function Ve(t){return`${Ss}-${t}`}function Fe(t,a){const n=s.toTitleCase(t.replace(/_/g," "));switch(a){case"day":return`Date of ${n}`;case"week":return`Week of ${n}`;case"month":return`Month of ${n}`;case"year":return`Year of ${n}`;default:return n}}function Fn({dataType:t}){const a=s.getDataType(t);return a==="string"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(ge,{className:"h-3 w-3"})}):a==="number"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(Ne,{className:"h-3 w-3"})}):a==="date"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):a==="boolean"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Le,{className:"h-3 w-3"})}):a==="json"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Be,{className:"h-3 w-3"})}):a==="geo"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(_e,{className:"h-3 w-3"})}):a==="calculated"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(qe,{className:"h-3 w-3"})}):e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(ge,{className:"h-3 w-3"})})}function Pn({schemaName:t,tableName:a,columns:n,status:r}){const[l,o]=A.useState(""),[c,i]=A.useState("all"),d=s.useEditorStore(O=>O.sqlGen),u=s.useEditorStore(O=>O.isDevMode);s.useEditorStore(O=>O.selectedConnectionId);const m=s.useEditorStore(O=>{var P,K;return(K=(P=O.card)==null?void 0:P.queryConfig)==null?void 0:K.metricColumns});s.useEditorStore(O=>{var P,K;return(K=(P=O.card)==null?void 0:P.queryConfig)==null?void 0:K.groupByColumns});const h=s.useEditorStore(O=>O.selectedDatabaseName);s.useEditorStore(O=>O.selectedSchemaName),s.useEditorStore(O=>O.selectedTableName);const f=s.useEditorStore(O=>O.selectedDatamodelId);s.useDashboardStore(O=>O.dashboard.aiScopeTables);const{addToAIScope:g,removeFromAIScope:b}=s.useDashboardActions(),{addColumnToMetricColumns:p,addColumnToGroupBy:j,setCardSql:x,setRunSql:v,setSqlGen:k,setIsShowingVisual:R}=s.useEditorActions(),{connectionType:N,modelItems:w,selectedDatamodelName:y}=s.useEditorAside();function D(O){var P;if(u){const K=s.createSqlGenConfig(O,d);k(K);const $=(P=w==null?void 0:w.find(X=>X.id===f))==null?void 0:P.name,te=s.getSql(K,s.fmt(t),s.fmt(a),$||"",N,h||"");te&&(x(te),v(!0))}if(!u){if(s.isTextDataType(O.data_type))if(m&&m.length>0){const K={...O,role:"groupby",id:ye(O.column_name),name:O.column_name,type:O.data_type};j(K)}else{const K={...O,role:"metric",id:ye(O.column_name),name:O.column_name,label:Ye(O.column_name,"COUNT"),type:O.data_type,aggregate:"COUNT"};p(K)}if(s.isDateDataType(O.data_type)){const K={...O,role:"groupby",id:ye(O.column_name),name:O.column_name,type:O.data_type,label:Fe(O.column_name,"month"),granularity:"month"};j(K)}if(s.isNumberDataType(O.data_type)){const K={...O,role:"metric",id:ye(O.column_name),name:O.column_name,label:Ye(O.column_name,"SUM"),type:O.data_type,aggregate:"SUM"};p(K)}}}function C(){const O=s.getFormattedTableNameForQuery({schemaName:t,tableName:a,modelName:y,connectionType:N,databaseName:h||""});R(!1);const P=N==="MSSQL"?`SELECT top 10 * FROM ${O}`:`SELECT * FROM ${O} LIMIT 10`;x(P),v(!0)}function I(){const O=s.getFormattedTableNameForQuery({schemaName:t,tableName:a,modelName:y,connectionType:N,databaseName:h||""});x(`SELECT COUNT(*) as count FROM ${O}`),v(!0)}const S=(n==null?void 0:n.filter(O=>O.column_name.toLowerCase().includes(l.toLowerCase())))||[],F=O=>s.isNumberDataType(O.data_type)?"number":"text",T=c==="all"?S:S.filter(O=>F(O)===c),E=S.filter(O=>F(O)==="text").length,M=S.filter(O=>F(O)==="number").length;function B(O){return u?e.jsxs("div",{className:"group flex cursor-pointer items-center justify-between border border-dashed border-background px-2 py-[6px] text-sm transition-colors hover:bg-muted/50",onClick:()=>D(O),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fn,{dataType:O.data_type}),e.jsx("span",{children:O.column_name})]}),e.jsx("div",{onClick:P=>P.stopPropagation(),className:"flex items-center justify-end",children:s.isNumberDataType(O.data_type)&&e.jsx(Mn,{column:O})})]}):e.jsx(On,{onClick:D,column:O})}function L(){return e.jsxs("div",{className:"flex grow gap-2",children:[e.jsxs(s.Button,{disabled:r!=="Success",onClick:C,size:"sm",variant:"secondary",className:"grow",children:[r!=="Success"?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(Ia,{className:"mr-2 size-4"}),"Top 10"]}),e.jsxs(s.Button,{disabled:r!=="Success",onClick:I,size:"sm",variant:"secondary",className:"grow",children:[r!=="Success"?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(at,{className:"mr-2 size-4"}),"Count"]})]})}return r!=="Success"?e.jsx("div",{className:"flex grow flex-col justify-start gap-2 px-4",children:Array.from({length:3}).map((O,P)=>e.jsx(s.Skeleton,{className:"h-8 w-full"},P))}):e.jsxs("div",{className:"flex grow flex-col",children:[e.jsxs("div",{className:"flex-shrink-0 space-y-3 px-4",children:[u&&e.jsx("div",{className:"flex items-center justify-center gap-2",children:L()}),n&&n.length>0&&e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 transform text-muted-foreground"}),e.jsx(s.Input$1,{className:"pl-10",type:"text",placeholder:"Search fields...",value:l,onChange:O=>o(O.target.value)})]}),S.length>0&&e.jsx(s.Tabs,{defaultValue:"all",value:c,onValueChange:O=>i(O),children:e.jsxs(s.TabsList,{className:"grid h-9 w-full grid-cols-3",children:[e.jsxs(s.TabsTrigger,{value:"all",className:"text-xs",children:["All",e.jsx("span",{className:"ml-2 text-xs font-semibold",children:S.length})]}),e.jsxs(s.TabsTrigger,{value:"text",className:"text-xs",children:[e.jsx(s.Layers,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:E})]}),e.jsxs(s.TabsTrigger,{value:"number",className:"text-xs",children:[e.jsx(s.ChartColumn,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:M})]})]})})]}),e.jsxs(s.CustomScrollArea,{className:"flex-1 basis-0 overflow-y-auto px-4 pt-3",children:[T.length===0&&l&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:['No fields found matching "',l,'"']}),T.length===0&&!l&&c!=="all"&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:["No ",c," fields found"]}),e.jsx("div",{className:"flex flex-col gap-1",children:T==null?void 0:T.map(O=>e.jsx("div",{children:B(O)},O.column_name))}),e.jsx(s.ScrollBar,{orientation:"vertical"}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Ct({ColumnsComponent:t,type:a}){var ee;const[n,r]=A.useState(!1),l=s.useEditorStore(ae=>ae.card),o=s.useEditorStore(ae=>ae.selectedConnectionId),c=s.useDashboardStore(ae=>ae.showFilters),i=s.useEditorStore(ae=>ae.selectedDatamodelId),d=s.useEditorStore(ae=>ae.selectedDatabaseName),u=s.useEditorStore(ae=>ae.selectedSchemaName),m=s.useEditorStore(ae=>ae.selectedTableName),h=s.useEditorStore(ae=>ae.isDevMode),{setSelectedTableName:f,setIsDevMode:g,setCardSql:b}=s.useEditorActions(),{connectionItems:p,modelItems:j,schemaItems:x,databaseItems:v,tableItems:k,columns:R,isConnectionsLoading:N,isModelsLoading:w,isConnectionsError:y,isModelsError:D,isDatabasesLoadingOrFetching:C,isDatabaseError:I,isSchemaLoadingOrFetching:S,isSchemaError:F,isColumnsError:T,isColumnsLoadingOrFetching:E,isTableLoadingOrFetching:M,isTableError:B,connectionType:L,isNonDbConnection:O,refetchDatabases:P,refetchModels:K,refetchSchemas:$,refetchTables:te,refetchColumns:X,refetchConnections:q,handleConnectionChange:H,handleDatabaseChange:_,handleSchemaChange:J,handleDatamodelChange:z,handleTableChange:U,tableName:Z,schemaName:le}=s.useEditorAside(),{data:V,refetch:se}=s.useDashboardCardQuery(l);function ne(){return t?t(le,Z,R):e.jsx(Pn,{schemaName:le,tableName:Z,columns:R,status:E?"Loading...":T?"Error":"Success"})}function Y(){window.location.href="mailto:support@semaphor.cloud?subject=Help&body=I need help with..."}function W(ae){ae===!0?V&&(b(V.userSql),setTimeout(()=>{se()},100)):b(""),g(ae)}function re(){if(!o||L==="S3"||L==="API")return null;if(!i||i==="none")return e.jsx(Oe,{refetch:P,showNone:!0,onChange:_,isError:I,isLoading:C,items:v,value:d||"",title:"Database",type:"combobox"})}function ie(){if(o&&!O&&(!d||d==="none")&&(!i||i==="none"))return e.jsxs("div",{className:"grid grid-cols-3",children:[e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(s.Separator,{})}),e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(s.Label,{children:"OR"})}),e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(s.Separator,{})})]})}function he(){if(!o||L==="S3"||L==="API")return null;if(!d||d==="none")return e.jsx(Oe,{refetch:K,showNone:!0,onChange:z,isError:D,isLoading:w,items:j,value:i||"",title:"Model",type:"combobox"})}function Q(){return!o||L==="S3"||L==="API"||!d||d==="none"?null:e.jsx(Oe,{refetch:$,onChange:J,isError:F,isLoading:S,items:x,value:u||"",title:"Schema",type:"combobox"})}function oe(){function ae(){let ue=!1;return L==="API"?(ue=!1,ue):((L==="S3"||o&&d&&d!=="none"&&u)&&(ue=!0),ue)}return ae()?e.jsx(Oe,{refetch:te,onChange:U,isError:B,items:k,isLoading:M,value:m||"",title:"Table",type:"combobox"}):null}return e.jsxs("aside",{className:s.cn("flex h-full min-w-[310px] max-w-[310px] flex-col justify-between rounded-none",{"border-r-[1px]":!c}),children:[e.jsxs("section",{className:s.cn("px-4",{"px-4 pb-0 pt-4":n,"px-4 py-4":!n}),children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between",children:[e.jsx("h2",{className:"text-brand-100 font-semibold",children:"Direct Source"}),e.jsx(s.Button,{onClick:()=>r(!n),size:"sm",variant:"ghost",className:"h-6 w-6 p-0",children:n?e.jsx(s.ChevronDown,{className:"h-4 w-4"}):e.jsx(s.ChevronUp,{className:"h-4 w-4"})})]}),!n&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(Oe,{refetch:q,items:p,title:"Connection",value:o||"",onChange:H,isLoading:N,isError:y,type:"combobox",connectionTooltip:((ee=p==null?void 0:p.find(ae=>ae.id===o))==null?void 0:ee.type)||""}),re(),ie(),he(),Q(),oe()]})]}),ne(),e.jsx("div",{className:"flex items-center justify-between gap-2 px-6 py-4",children:a==="main"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Switch,{className:"data-[state=checked]:bg-muted-foreground/80",checked:h,onCheckedChange:W,id:"dev-mode"}),e.jsx(s.Label,{htmlFor:"dev-mode",children:"Advanced Mode"})]}),e.jsxs(s.Button,{onClick:Y,size:"sm",variant:"secondary",className:"group flex items-center gap-2 rounded-full",children:[e.jsx(Ma,{className:"size-4"}),e.jsx("span",{className:"hidden group-hover:block",children:"Help"})]})]})})]})}function St({error:t,errorSql:a,onSendFeedback:n,className:r,showFeedbackButton:l=!0}){const[o,c]=A.useState(!1);return e.jsx("div",{className:s.cn("rounded-lg border border-destructive/30 bg-destructive/5 p-4",r),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(s.CircleAlert,{className:"mt-0.5 h-5 w-5 flex-shrink-0 text-destructive"}),e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium text-destructive",children:"Query Error"}),e.jsxs("div",{className:"relative rounded-md bg-background/60 p-3",children:[e.jsx(s.CopyButton,{text:t,className:"absolute right-2 top-2 h-6 w-6 z-10"}),e.jsx("div",{className:"max-h-40 overflow-auto pr-10",children:e.jsx("p",{className:"font-mono text-xs text-foreground/80 break-all",children:t})})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[a&&e.jsx(s.Collapsible,{open:o,onOpenChange:c,children:e.jsx(s.CollapsibleTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-8",children:o?e.jsxs(e.Fragment,{children:[e.jsx(s.ChevronUp,{className:"mr-1.5 h-3.5 w-3.5"}),"Hide Details"]}):e.jsxs(e.Fragment,{children:[e.jsx(s.ChevronDown,{className:"mr-1.5 h-3.5 w-3.5"}),"Show Details"]})})})}),l&&n&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8",onClick:n,children:[e.jsx(Ra,{className:"mr-1.5 h-3.5 w-3.5"}),"Send Feedback"]})]}),a&&e.jsx(s.Collapsible,{open:o,onOpenChange:c,children:e.jsx(s.CollapsibleContent,{className:"space-y-2",children:e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Error SQL Query"}),e.jsx(s.CopyButton,{text:a,className:"h-6 w-6"})]}),e.jsx("div",{className:"rounded-md bg-background/60 p-2 max-h-80 overflow-auto",children:e.jsx(s.CodeHighlighter,{code:a,language:"sql"})})]})})})]})]})})}function wt({sql:t,error:a,errorSql:n,onDebugWithAssistant:r}){const l=s.useEditorStore(u=>u.isDevMode),{setIsDevMode:o,setCardSql:c,setRunSql:i}=s.useEditorActions();function d(){o(!l),c(t),setTimeout(()=>{i(!0)},100)}return e.jsx("div",{className:"flex justify-between space-x-4",children:e.jsxs("div",{className:"flex grow flex-col space-y-3",children:[e.jsxs(s.ScrollArea,{className:"max-h-[250px] min-h-0 overflow-scroll text-xs leading-relaxed text-foreground/80",children:[a&&e.jsx(St,{error:a,errorSql:n,showFeedbackButton:!1}),!a&&t&&e.jsx("div",{className:"flex flex-col space-y-1.5",children:e.jsx("div",{className:"",children:e.jsx(s.CodeHighlighter,{code:t,language:"sql"})})})]}),!l&&t&&!a&&e.jsxs(s.Button,{onClick:d,variant:"secondary",size:"sm",children:[e.jsx(ja,{className:"mr-2 h-4 w-4"}),"View in SQL Editor"]}),a&&r&&e.jsxs(s.Button,{onClick:r,size:"sm",variant:"outline",children:[e.jsx(Sa,{className:"mr-2 h-4 w-4"}),"Debug with Assistant"]})]})})}function Dt({sql:t,error:a,errorSql:n,onDebugWithAssistant:r}){return e.jsxs(s.HoverCard,{openDelay:a?0:500,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"link",className:"h-5 p-0",children:a?e.jsx(Zs,{className:"h-4 w-4 text-red-500"}):e.jsx(s.Info,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsx(s.HoverCardContent,{align:"start",className:"flex w-[700px]",children:e.jsx(wt,{errorSql:n,sql:t,error:a,onDebugWithAssistant:r})})]})}function zn(t){return s.GenIcon({attr:{viewBox:"0 0 448 512"},child:[{tag:"path",attr:{d:"M439.8 200.5c-7.7-30.9-22.3-54.2-53.4-54.2h-40.1v47.4c0 36.8-31.2 67.8-66.8 67.8H172.7c-29.2 0-53.4 25-53.4 54.3v101.8c0 29 25.2 46 53.4 54.3 33.8 9.9 66.3 11.7 106.8 0 26.9-7.8 53.4-23.5 53.4-54.3v-40.7H226.2v-13.6h160.2c31.1 0 42.6-21.7 53.4-54.2 11.2-33.5 10.7-65.7 0-108.6zM286.2 404c11.1 0 20.1 9.1 20.1 20.3 0 11.3-9 20.4-20.1 20.4-11 0-20.1-9.2-20.1-20.4.1-11.3 9.1-20.3 20.1-20.3zM167.8 248.1h106.8c29.7 0 53.4-24.5 53.4-54.3V91.9c0-29-24.4-50.7-53.4-55.6-35.8-5.9-74.7-5.6-106.8.1-45.2 8-53.4 24.7-53.4 55.6v40.7h106.9v13.6h-147c-31.1 0-58.3 18.7-66.8 54.2-9.8 40.7-10.2 66.1 0 108.6 7.6 31.6 25.7 54.2 56.8 54.2H101v-48.8c0-35.3 30.5-66.4 66.8-66.4zm-6.7-142.6c-11.1 0-20.1-9.1-20.1-20.3.1-11.3 9-20.4 20.1-20.4 11 0 20.1 9.2 20.1 20.4s-9 20.3-20.1 20.3z"},child:[]}]})(t)}function kt(t){const{theme:a}=s.useTheme(),n=s.useDashboardStore(p=>p.theme),r=s.useEditorStore(p=>p.frame),l=s.useEditorStore(p=>p.card),o=s.useEditorStore(p=>p.activeTabCardId),c=s.Le(),{refetch:i}=s.useDashboardCardQuery(l),{updateCardTab:d,setRunSql:u}=s.useEditorActions(),m=A.useRef(),h=A.useRef({}),f=r.cards.find(p=>p.id===o),g=A.useCallback(()=>{let p="";return t==="python"&&(p=(f==null?void 0:f.python)||s.PYTHON_DEFAULT_CODE),t==="sql"&&(p=(f==null?void 0:f.sql)||""),p},[t,f]);A.useEffect(()=>{if(o&&l.id&&l.id!==o){if(m.current&&c){const p=m.current.getModel();p&&(h.current[l.id]=p);let j=h.current[o];if(!j){const x=g();j=c.editor.createModel(x,t),h.current[o]=j}m.current.setModel(j)}d(o,l),u(!0)}},[o,l,d,c,u,t,g]),A.useEffect(()=>{if(!c)return;const p=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",j=n==="system"?p:n;c.editor.defineTheme("default",{base:j==="light"?"vs":"vs-dark",inherit:!0,rules:[],colors:{"editor.background":j==="light"?"#ffffff":s.hslStringToHex("240 10% 10%")}}),c.editor.setTheme("default")},[a,n,c]),A.useEffect(()=>{const p=m.current;p&&c&&l&&p.addCommand(c.KeyMod.Shift|c.KeyCode.Enter,function(){return i(),!1})},[c,i,l]);function b(p,j){if(m.current=p,!h.current[l.id]){const x=p.getModel(),v=g();h.current[l.id]=x||(j==null?void 0:j.editor.createModel(v,t))||p.getModel()}p.setModel(h.current[l.id])}return{handleEditorDidMount:b}}function Vn(){const t=s.useEditorStore(c=>c.card.sql),a=s.useEditorStore(c=>c.sqlGen),{setCardSql:n,setSqlGen:r}=s.useEditorActions(),{handleEditorDidMount:l}=kt("sql");function o(c){n(c),s.isObjectEmpty(a)||r({})}return e.jsxs("div",{className:"relative h-full w-full",children:[!t&&e.jsx("div",{className:"pointer-events-none absolute left-[65px] top-3 z-10 font-mono text-sm text-muted-foreground",children:"Write your SQL here"}),e.jsx(s.Ft,{theme:"default",className:"pt-3",onChange:o,value:t||"",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"sql",onMount:l})]})}function _n(){const t=s.useEditorStore(l=>l.card.python),{setCardPython:a}=s.useEditorActions(),{handleEditorDidMount:n}=kt("python");function r(l){a(l)}return e.jsx(s.Ft,{className:"pt-3",theme:"default",onChange:r,value:t||s.PYTHON_DEFAULT_CODE,options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"python",onMount:n})}function Un({jsonString:t}){return e.jsx(s.Ft,{theme:"default",defaultLanguage:"json",className:"mt-1 min-h-[220px]",value:t,options:{readOnly:!0,minimap:{enabled:!1},lineNumbers:"off",glyphMargin:!1,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,renderLineHighlight:"none"}})}function ws({variant:t="outline"}){var c;const{setCardSql:a}=s.useEditorActions();s.useEditorStore(i=>i.frame);const n=s.useEditorStore(i=>i.card);Ns(((c=n.customCardPreferences)==null?void 0:c.url)||""),s.useEditorStore(i=>i.selectedSchemaName),s.useEditorStore(i=>i.selectedDatamodelId),s.useEditorStore(i=>i.selectedDatabaseName),s.useEditorStore(i=>i.selectedTableName),s.useEditorStore(i=>i.selectedConnectionId),s.useEditorStore(i=>i.isShowingVisual),n.sql;const r=s.useEditorStore(i=>i.onSave),{getUpdatedFrame:l}=Cs();function o(){const i=l();r==null||r(i)}return e.jsxs(s.Button,{onClick:o,className:"h-8",size:"sm",variant:t,children:[e.jsx(s.Check,{className:"mr-2 size-4 font-bold"}),"Accept"]})}function $n(){const t=s.useQueryClient(),[a,n]=A.useState(!1),r=s.useDashboardStore(u=>u.actions.setIsDashboardPanelOpen),{setIsVisualEditing:l}=s.useDashboardActions(),{getUpdatedFrame:o}=Cs(),c=s.useSelectedVisual(),i=s.useUpdateVisualMutation(),d=()=>{const u=o();if(!(c!=null&&c.id)){s.ue.error("No visual selected");return}n(!0),i.mutate({visualId:c.id,data:{frameObject:u}},{onSuccess:()=>{n(!1),l(!1),r(!0),s.ue.success("Visual updated successfully"),t.invalidateQueries({queryKey:["resource-by-id","visual",c.id],exact:!0})},onError:()=>{n(!1),s.ue.error("Failed to update visual")}})};return e.jsxs(s.Button,{onClick:d,className:"h-8",size:"sm",children:[a&&e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin font-bold"})," Saving"]}),!a&&e.jsxs(e.Fragment,{children:[e.jsx(fs,{className:"mr-2 size-4 font-bold"}),"Save"]})]})}function Ds(){const{setTempQueryData:t,setSqlGen:a}=s.useEditorActions(),n=s.useQueryClient(),r=s.useEditorStore(d=>d.tempQueryData),l=s.useEditorStore(d=>d.onClose),o=s.useEditorStore(d=>d.card),{queryKey:c}=s.useDashboardCardQuery(o);function i(){if(r){const{queryKey:d,queryData:u}=r;d&&u&&n.setQueryData(d,u)}a({}),l==null||l()}return e.jsxs(s.Button,{onClick:i,className:"h-8",size:"sm",variant:"outline",children:[e.jsx(s.X,{className:"mr-2 size-4"}),"Close"]})}function ns(){const{setTempQueryData:t}=s.useEditorActions(),a=s.useQueryClient(),n=s.useEditorStore(j=>j.isDevMode),r=s.useEditorStore(j=>j.tempQueryData),l=s.useEditorStore(j=>j.card),{queryKey:o}=s.useDashboardCardQuery(l),{setCardSql:c,setSqlGen:i,setCardPython:d,setCardCustomCfg:u,setCardPreferences:m,updateDataSource:h,clearQueryConfig:f,setCardConfig:g,setCardType:b}=s.useEditorActions();function p(){const j=a.getQueryData(o);r!=null&&r.queryData||t({queryKey:o,queryData:j}),a.setQueryData(o,null),a.removeQueries({queryKey:o,exact:!0}),n&&h(s.EMPTY_DATA_SOURCE),c(""),i({}),f(),g(void 0),d(""),u(""),m({}),b("bar")}return e.jsxs(s.Button,{onClick:p,className:"h-8",size:"sm",variant:"secondary",children:[e.jsx(s.SquarePen,{className:"mr-2 size-4"}),"Clear"]})}function Yn(){const t=s.useQueryClient(),[a,n]=A.useState(!1),[r,l]=A.useState(!1);s.useEditorStore($=>$.frame);const o=s.useEditorStore($=>$.card);s.useEditorStore($=>$.isShowingVisual),s.useEditorStore($=>$.selectedConnectionId),s.useEditorStore($=>$.tempQueryData),s.useEditorStore($=>$.selectedDatabaseName),s.useEditorStore($=>$.selectedDatamodelId),s.useEditorStore($=>$.selectedSchemaName);const c=s.useEditorStore($=>$.showAIDialog);s.useEditorStore($=>$.selectedTableName);const i=s.useEditorStore($=>{var te;return(te=$==null?void 0:$.card)==null?void 0:te.sql}),d=s.useEditorStore($=>{var te;return(te=$==null?void 0:$.card)==null?void 0:te.python}),{sheetFilterValues:u}=s.useSheetFilterValues(),{setCardCustomCfg:m,setQueryResultColumns:h,setCardSql:f,setTempQueryData:g,setPythonStdOut:b,setCardPreferences:p,setCardType:j,setCardPython:x,runAssistant:v,setShowAIDialog:k}=s.useEditorActions();s.useEditorStore($=>$.onSave),s.useEditorStore($=>$.onClose),s.useEditorStore($=>$.actions.setSqlGen);const R=s.useEditorStore($=>$.runSql),N=s.useEditorStore($=>$.actions.setRunSql),w=s.useEditorStore($=>$.actions.setIsSqlRunning),{data:y,isLoading:D,isFetching:C,isSuccess:I,isError:S,error:F,errorSql:T,queryKey:E,refetch:M,errorMessage:B}=s.useDashboardCardQuery(o);A.useEffect(()=>{if(y&&(y.rowLimitExceeded&&s.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),b((y==null?void 0:y.output)||""),y.records.length>0)){const{dimensionKeys:$}=s.getKeys(y.records);h($)}},[y,h,b]),A.useEffect(()=>{(D||C)&&w(!0),(S||I)&&w(!1),S&&(h([]),b(""))},[D,C,y,b,S,I,w,h,F]),A.useEffect(()=>{R&&(t.getQueryData(E)||M(),N(!1))},[R,M,N,E,t]);async function L(){const $=`Can you help me debug this query?
|
|
331
|
+
*/const Wa=s.createLucideIcon("View",[["path",{d:"M21 17v2a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-2",key:"mrq65r"}],["path",{d:"M21 7V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v2",key:"be3xqs"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["path",{d:"M18.944 12.33a1 1 0 0 0 0-.66 7.5 7.5 0 0 0-13.888 0 1 1 0 0 0 0 .66 7.5 7.5 0 0 0 13.888 0",key:"11ak4c"}]]);function Ka(){const{setTheme:t}=s.useTheme(),a=s.useDashboardStore(n=>n.actions.setDashboardTheme);return e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsxs(s.Button,{className:"h-7 p-2",variant:"ghost",size:"sm",children:[e.jsx(qa,{strokeWidth:1.5,className:"h-4 w-4 rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0"}),e.jsx(Ra,{strokeWidth:1.5,className:"absolute h-4 w-4 rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100"}),e.jsx("span",{className:"sr-only",children:"Toggle theme"})]})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsx(s.DropdownMenuItem,{onClick:()=>{t("light"),a("light")},children:"Light"}),e.jsx(s.DropdownMenuItem,{onClick:()=>{t("dark"),a("dark")},children:"Dark"}),e.jsx(s.DropdownMenuItem,{onClick:()=>{t("system"),a("system")},children:"System"})]})]})}function es(t){var a;return{...t,sheets:(a=t==null?void 0:t.sheets)==null?void 0:a.map(n=>{var r;return{...n,frames:(r=n.frames)==null?void 0:r.map(l=>{var o;return{...l,cards:(o=l.cards)==null?void 0:o.map(c=>nt(c))}})}})}}function nt(t){return{...t,customCfg:Ja(t.customCfg),data:[]}}function Ja(t){var a,n;return t?{...t,data:{...t==null?void 0:t.data,labels:[],datasets:(n=(a=t==null?void 0:t.data)==null?void 0:a.datasets)==null?void 0:n.map(r=>({...r,data:[]}))}}:null}async function Qa(t,a,n,r){if(!r)return null;const l=JSON.stringify(a);return await s.postRequest("https://semaphor.cloud/api/v1/lens",r,{name:t,template:l,filterValues:n,operation:"create"})}async function js(t,a){if(!a)return null;const{id:n,template:r,filterValues:l,isDefault:o,shared:c}=t;return await s.postRequest("https://semaphor.cloud/api/v1/lens",a,{lensId:n,template:r,filterValues:l,isDefault:o,shared:c,operation:"update"})}async function Xa(t,a){return a?await s.postRequest("https://semaphor.cloud/api/v1/lens",a,{operation:"delete",lensId:t}):null}function Za(){const[t,a]=I.useState(""),[n,r]=I.useState(!1),l=s.useDashboardStore(p=>p.lenses),{setLenses:o,setSelectedLensId:c}=s.useDashboardActions(),[i,d]=I.useState(!1),[u,m]=I.useState(!1),h=s.useDashboardStore(p=>p.dashboard),f=s.useDashboardStore(p=>p.filterValues),{authToken:g}=s.useSemaphorContext();async function b(){d(!0);const p=es(h),j=await Qa(t,p,f,g==null?void 0:g.accessToken);j&&(o([...l||[],j]),c(j.id),m(!1)),d(!1)}return e.jsxs(s.Dialog,{open:u,onOpenChange:m,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"secondary",className:"h-7 p-2",size:"sm",children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Lens"]})}),e.jsxs(s.DialogContent,{className:"sm:max-w-[425px]",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Create Lens"}),e.jsx(s.DialogDescription,{children:"Lenses are private by default and are only visible to you."})]}),e.jsx("div",{className:"grid gap-4 py-4",children:e.jsxs("div",{className:"grid grid-cols-8 items-center gap-4",children:[e.jsx(s.Label,{className:"text-right",children:"Name"}),e.jsx(s.Input,{value:t,onChange:p=>{a(p.target.value)},id:"name",className:"col-span-7 focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0"})]})}),n&&e.jsx("p",{className:"text-sm",children:"The lens name already exists. Use a differnet name."}),e.jsx(s.DialogFooter,{children:e.jsx(s.Button,{size:"sm",variant:"outline",type:"submit",onClick:b,disabled:i,children:i?"Creating...":"Add"})})]})]})}function en(){const[t,a]=I.useState(!1),n=s.useDashboardStore(m=>m.lenses),r=s.useDashboardStore(m=>m.selectedLensId),{setLenses:l,setSelectedLensId:o}=s.useDashboardActions(),{authToken:c}=s.useSemaphorContext();async function i(m){o(m)}async function d(m){if(await Xa(m,c==null?void 0:c.accessToken)){const f=n==null?void 0:n.filter(g=>g.id!==m);l(f||[]),o("original")}}async function u(m){const h=n==null?void 0:n.map(b=>b.id===m.id?{...b,isDefault:!m.isDefault}:{...b,isDefault:!1});l(h||[]);const f={...m,isDefault:!m.isDefault};await js(f,c==null?void 0:c.accessToken);const g=n==null?void 0:n.find(b=>b.isDefault);if(g&&g.id!==m.id){const b={...g,isDefault:!1};await js(b,c==null?void 0:c.accessToken)}}return e.jsxs(s.DropdownMenu,{open:t,onOpenChange:a,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Lenses",className:"h-7 p-2",children:e.jsx(va,{className:"h-4 w-4"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"w-60",children:[e.jsx(s.DropdownMenuLabel,{className:"px-3",children:"Lenses"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuRadioGroup,{value:r,onValueChange:i,children:[e.jsx(s.DropdownMenuRadioItem,{value:"original",children:"Original"}),n==null?void 0:n.map(m=>e.jsxs(s.DropdownMenuRadioItem,{className:"group flex justify-between gap-2",value:m.id,children:[e.jsx("p",{children:m.name}),e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx(s.House,{onClick:h=>{h.preventDefault(),u(m)},className:s.cn("size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",{invisible:!m.isDefault,"text-green-500":m.isDefault}),strokeWidth:1.5}),e.jsx(s.Cross2Icon,{onClick:h=>{h.preventDefault(),d(m.id)},className:"invisible size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",strokeWidth:1.5})]})]},m.id))]})]})]})}function sn({iconClassName:t}){const[a,n]=I.useState(!1),[r,l]=I.useState(""),[o,c]=I.useState(!1),i=s.useDashboardStore(m=>m.isDownloadingPdf);async function d(){const m=s.ue.loading("Generating PDF... may take up to 60 seconds");try{await s.downloadPdf(),s.ue.dismiss(m),s.ue.success("PDF downloaded successfully!",{duration:2e3})}catch(h){s.ue.dismiss(m),s.ue.error("Failed to download PDF",{description:"Please try again or contact support.",richColors:!0}),console.error("PDF download error:",h)}}async function u(){if(!r)return;n(!1),l(""),c(!1);const m=s.ue.loading("Generating protected PDF... may take up to 60 seconds");try{await s.downloadPdf(r),s.ue.dismiss(m),s.ue.success("Protected PDF downloaded successfully!",{duration:2e3,position:"top-right"})}catch(h){s.ue.dismiss(m),s.ue.error("Failed to download protected PDF. Please try again."),console.error("Protected PDF download error:",h)}}return e.jsxs(e.Fragment,{children:[e.jsxs(s.DropdownMenu,{modal:!1,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 p-2",disabled:i,children:e.jsx(s.Download,{className:s.cn("size-4",t)})})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsxs(s.DropdownMenuItem,{onClick:d,children:[e.jsx(s.File,{className:"mr-2 h-4 w-4"}),"Download PDF"]}),e.jsxs(s.DropdownMenuItem,{onClick:()=>n(!0),children:[e.jsx(Ta,{className:"mr-2 h-4 w-4"}),"Download Protected PDF"]})]})]}),e.jsx(s.Dialog,{open:a,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"sm:max-w-[425px]",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Download Protected PDF"}),e.jsx(s.DialogDescription,{children:"Enter a password to protect your PDF. The PDF will be encrypted and require this password to open."})]}),e.jsx("div",{className:"grid gap-4 py-4",children:e.jsxs("div",{className:"grid gap-2",children:[e.jsx(s.Label,{htmlFor:"password",children:"Password"}),e.jsxs("div",{className:"relative",children:[e.jsx(s.Input,{id:"password",type:o?"text":"password",value:r,onChange:m=>l(m.target.value),placeholder:"Enter password",className:"pr-10",onKeyDown:m=>{m.key==="Enter"&&r&&u()}}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent",onClick:()=>c(!o),children:o?e.jsx(s.EyeOff,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(s.Eye,{className:"h-4 w-4 text-muted-foreground"})})]})]})}),e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(s.Button,{onClick:u,disabled:!r,children:"Download"})]})]})})]})}function fe({defaultValue:t,label:a,options:n,value:r,onValueChange:l,className:o,icon:c,showPlaceholderLabel:i=!0}){return e.jsxs(s.Select,{defaultValue:t,value:r,onValueChange:l,children:[e.jsx(s.SelectTrigger,{className:s.cn("w-full focus:ring-0 focus:ring-offset-0",o),children:e.jsxs("div",{className:"flex items-center gap-2",children:[c&&e.jsx("span",{children:c}),i&&e.jsx(s.SelectValue,{placeholder:a})]})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:a}),n.map(d=>e.jsx(s.SelectItem,{value:d.value,children:d.label},d.value))]})})]})}const Vs=[{value:"daily",label:"Daily"},{value:"weekly",label:"Weekly"},{value:"biweekly",label:"Bi-Weekly"},{value:"monthly",label:"Monthly"}];function rt({triggerButtonClassName:t}){const{currentUser:a}=s.useCurrentUserInfo(),{data:n,handleScheduleSubscription:r,handleDeleteSubscription:l,status:o,error:c,isDeleting:i}=tn(),[d,u]=I.useState((a==null?void 0:a.email)||""),[m,h]=I.useState(Vs[0].value),[f,g]=I.useState("06:00"),[b,p]=I.useState("");return e.jsx(s.TooltipProvider,{delayDuration:0,children:e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Schedule Dashboard",className:s.cn("h-7 p-2",t),children:e.jsx(s.Clock,{className:"size-4"})})}),e.jsx(s.PopoverContent,{align:"end",className:"w-80",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Schedule Subscription"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Subscribe to receive dashboard via email"})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"recipients",children:"Recipients"}),e.jsx(s.Input,{id:"recipients",value:d,onChange:j=>u(j.target.value),placeholder:a!=null&&a.email?"Add more emails separated by commas":"email@example.com, email2@example.com",className:`col-span-2 h-8 ${s.removeRing}`})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"subject",children:"Subject"}),e.jsx(s.Input,{id:"subject",placeholder:"Monthly Sales Report",value:b,onChange:j=>{p(j.target.value.replace(/[^a-zA-Z0-9\s-_]/g,""))},className:`col-span-2 h-8 ${s.removeRing}`})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"frequency",children:"Frequency"}),e.jsx(fe,{className:"col-span-2 h-8",label:"Select Frequency",options:Vs,value:m,onValueChange:j=>h(j)})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(s.Label,{htmlFor:"time",children:"Time"}),e.jsx(s.Input,{id:"time",type:"time",value:f,onChange:j=>g(j.target.value),className:`col-span-2 h-8 ${s.removeRing}`})]}),e.jsx("div",{className:"mt-2 flex justify-end",children:e.jsxs(s.Button,{onClick:async()=>{await r({recipients:d,frequency:m,time:f,subject:b}),g("06:00"),u((a==null?void 0:a.email)||""),p("")},className:"h-8 p-2",disabled:o==="loading"||!d,children:[o==="loading"&&e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin"}),o==="success"&&e.jsx(s.Check,{className:"mr-2 size-4"}),o==="error"&&e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{children:e.jsx(Zs,{className:"mr-2 size-4 text-destructive"})}),e.jsx(s.TooltipContent,{children:e.jsx("p",{children:c})})]}),"Schedule"]})}),n&&n.length>0&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Subscriptions"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Active email subscriptions"})]}),s.isDevEnv]})}),e.jsx("div",{className:"grid max-h-48 gap-2 overflow-y-auto",children:n==null?void 0:n.map(j=>{const x=j.recipients?j.recipients.split(/[,;]/).filter(Boolean):[j.endUserEmail].filter(Boolean),v=x.length,k=new Date(j.nextRun),L=k<new Date;return e.jsx("div",{className:"group rounded-lg border bg-card p-3 transition-colors hover:bg-accent/50",children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:j.reportType==="VISUAL"?"secondary":"default",className:"text-xs",children:j.reportType==="VISUAL"?"Report":" Dashboard"}),e.jsxs("span",{className:"text-sm font-medium",children:[s.titleCase(j.frequency)," at"," ",j.time]})]}),j.subject&&e.jsx("p",{className:"text-xs text-muted-foreground",children:j.subject}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Mail,{className:"size-3 text-muted-foreground"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:v===1?x[0]:`${v} recipients`})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Clock,{className:s.cn("size-3",L?"text-orange-500":"text-muted-foreground")}),e.jsxs("span",{className:s.cn("text-xs",L?"font-medium text-orange-500":"text-muted-foreground"),children:["Next: ",k.toLocaleDateString()," at"," ",k.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})]})]})]}),e.jsx("div",{className:"flex items-center gap-1",children:i===j.id?e.jsx(s.LoaderCircle,{className:"size-4 animate-spin text-muted-foreground"}):e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>l(j.id),className:"h-7 w-7 p-0 hover:bg-destructive/10 hover:text-destructive",children:e.jsx(s.Trash2,{className:"size-3.5"})})})]})},j.id)})})]})]})]})})]})})}function tn(){const[t,a]=I.useState("idle"),[n,r]=I.useState(""),[l,o]=I.useState(null),c=s.useDashboardStore(C=>C.authToken),i=s.useDashboardStore(C=>C.dashboard.id),d=s.useDashboardStore(C=>C.dashboard.title),u=s.useDashboardStore(C=>C.filterValues),{endUserId:m}=s.getTenantAndEndUserId((c==null?void 0:c.accessToken)||""),{currentUser:h}=s.useCurrentUserInfo(),f="https://semaphor.cloud/api/v1/subscriptions/get",g={dashboardId:i,userId:h==null?void 0:h.id},{data:b,isLoading:p,isError:j,isFetching:x,refetch:v}=s.useQuery({queryKey:["subscriptions",i,h==null?void 0:h.id],queryFn:()=>s.getRequest(f,(c==null?void 0:c.accessToken)||"",g),enabled:!!(c!=null&&c.accessToken)&&!!i&&!!(h!=null&&h.id)});async function k({recipients:C,subject:S,frequency:y,time:D}){const N=C.split(/[,;]/).map(R=>R.trim()).filter(R=>R),B=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,w=N.filter(R=>!B.test(R));if(w.length>0){a("error"),r(`Invalid email addresses: ${w.join(", ")}`);return}if(N.length===0){a("error"),r("Please enter at least one valid email address");return}const{authToken:F,...T}=s.getParamsForPrint(),E=Intl.DateTimeFormat().resolvedOptions().timeZone,A=s.formatFilterLine(u||[]),O={reportType:"DASHBOARD",recipients:C,createdBy:(h==null?void 0:h.id)||m,frequency:y,time:D,timezone:E,endUserId:m,endUserEmail:N[0],subject:S||d||"Scheduled Dashboard",dashboardId:i,dashboardParams:T,pageSettings:A?{filterLine:A}:void 0};a("loading");const M="https://semaphor.cloud/api/v1/subscriptions/create";try{const R=await s.postRequestRegular(M,(F==null?void 0:F.accessToken)||"",{...O});a("success"),r(""),v(),setTimeout(()=>{a("idle")},2e3)}catch(R){console.error(R),a("error"),r(R.message)}}async function L(C){const S="https://semaphor.cloud/api/v1/subscriptions/delete";o(C);try{await s.postRequestRegular(S,(c==null?void 0:c.accessToken)||"",{id:C}),v(),setTimeout(()=>{o(null)},2e3)}catch(y){console.error(y),o(null),a("error"),r(y.message)}}return{data:b,isLoading:p,isFetching:x,isError:j,isDeleting:l,refetch:v,handleScheduleSubscription:k,handleDeleteSubscription:L,status:t,error:n}}function lt(){return e.jsx(s.ScrollArea,{className:"w-full flex-1",children:e.jsxs("div",{className:"space-y-4 px-4",children:[e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-8 w-full rounded bg-muted"})}),e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-8 w-full rounded bg-muted"})}),e.jsx("div",{className:"space-y-2",children:[...Array(4)].map((t,a)=>e.jsx("div",{className:"animate-pulse",children:e.jsxs("div",{className:"group relative flex items-start gap-3 px-4 py-3",children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-md bg-muted"})}),e.jsxs("div",{className:"flex w-full items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("div",{className:"h-4 w-32 rounded bg-muted"})}),e.jsx("div",{className:"shrink-0",children:e.jsx("div",{className:"h-3.5 w-3.5 rounded bg-muted"})})]}),e.jsx("div",{className:"mt-0.5",children:e.jsx("div",{className:"h-3 w-48 rounded bg-muted"})})]}),e.jsx("div",{className:"absolute right-3 top-2",children:e.jsx("div",{className:"flex items-center opacity-0 transition-opacity duration-150 group-hover:opacity-100",children:e.jsx("div",{className:"h-6 w-6 rounded bg-muted"})})})]})]})},a))})]})})}function an({visual:t,isDeleting:a,isDuplicating:n,isTitleUpdating:r=!1,isDescriptionUpdating:l=!1,onAddVisual:o,onEditVisual:c,onUpdateVisual:i,onDeleteClick:d,onDuplicateVisual:u,onShareVisual:m,formatDate:h}){var S,y,D;const{selectVisual:f}=s.useManagementActions(),g=s.useIsVisualSelected(t.id),{isConsoleMode:b}=s.useDashboardPreferences(),p=s.useDashboardStore(N=>N.actions.setIsDashboardPanelOpen),[j,x]=I.useState(!1),[v,k]=I.useState(!1);I.useEffect(()=>{n?(x(!0),k(!0)):v&&(x(!1),k(!1))},[n,v]);const L=()=>e.jsx(ns,{className:"h-4 w-4"}),C=()=>{f(t),c==null||c(t)};return e.jsx(s.Card,{className:s.cn("group p-3 hover:bg-accent/50 transition-colors cursor-pointer border-border/50",g&&"ring-1 ring-primary"),onClick:C,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"mt-0.5 p-1.5 rounded bg-muted",children:L()}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(s.EditableText,{inputClassName:"text-sm font-medium text-foreground",value:t.title,onSave:N=>i==null?void 0:i(t.id,{title:N}),isEditable:t.ownership.isOwner&&g,isPending:r,placeholder:"Untitled Visual",displayClassName:"font-medium text-sm text-foreground truncate"}),t.ownership.status==="shared"&&e.jsxs(s.Badge,{variant:"outline",className:"text-xs",children:[e.jsx(s.Users,{className:"h-2.5 w-2.5 mr-1"}),"Shared"]})]}),e.jsx(s.EditableText,{inputClassName:"text-xs text-muted-foreground line-clamp-2",value:t.description||"",onSave:N=>i==null?void 0:i(t.id,{description:N}),isEditable:t.ownership.isOwner&&g,isPending:l,placeholder:"No description",displayClassName:"text-xs text-muted-foreground line-clamp-2 mb-2"}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(s.Calendar,{className:"h-3 w-3"}),e.jsxs("span",{children:["Updated ",h(t.lastModified)]})]})]}),e.jsxs("div",{className:s.cn("opacity-0 transition-opacity duration-150 group-hover:opacity-100","ml-2 flex-shrink-0 flex items-center gap-1"),onClick:N=>N.stopPropagation(),children:[e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0",onClick:N=>{N.stopPropagation(),o(t)},title:"Add to dashboard",children:e.jsx(s.Plus,{className:"h-3.5 w-3.5"})}),e.jsxs(s.DropdownMenu,{modal:!1,open:j,onOpenChange:x,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0",children:e.jsx(s.Ellipsis,{className:"h-3 w-3"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"z-[51] w-40",children:[e.jsxs(s.DropdownMenuItem,{onClick:N=>{N.stopPropagation(),o(t)},children:[e.jsx(s.Plus,{className:"mr-2 h-3 w-3"}),"Add"]}),e.jsxs(s.DropdownMenuItem,{onClick:N=>{N.preventDefault(),N.stopPropagation(),u(t.id)},disabled:n,children:[n?e.jsx(s.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(s.Copy,{className:"mr-2 h-3 w-3"}),n?"Duplicating...":"Duplicate"]}),t.ownership.isOwner&&e.jsxs(e.Fragment,{children:[e.jsxs(s.DropdownMenuItem,{onClick:N=>{N.stopPropagation(),c==null||c(t)},children:[e.jsx(Fa,{className:"mr-2 h-3 w-3"}),"Edit"]}),e.jsxs(s.DropdownMenuItem,{onClick:N=>{N.stopPropagation(),m(t)},children:[e.jsx(s.Users,{className:"mr-2 h-3 w-3"}),"Share"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:N=>{N.stopPropagation(),d(t),p(!1)},className:"text-destructive",disabled:a,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),a?"Deleting...":"Delete"]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs("div",{className:"space-y-1 px-2 py-2 text-xs text-slate-500 dark:text-slate-400",children:[(((S=t.ownership.createdBy)==null?void 0:S.type)==="tenant"||((y=t.ownership.createdBy)==null?void 0:y.type)==="organization"&&b)&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Be,{className:"h-3 w-3"}),e.jsx("span",{children:((D=t.ownership.createdBy)==null?void 0:D.name)||"Unknown"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Calendar,{className:"h-3 w-3"}),e.jsx("span",{children:h(t.lastModified)})]})]})]})]})]})]})},t.id)}function ot({value:t,onChange:a,placeholder:n="Search users by name, email, or department..."}){return e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:n,value:t,onChange:r=>a(r.target.value),className:"pl-9"})]})}function ss({currentRole:t,onRoleChange:a,roleOptions:n,disabled:r=!1,className:l="",allowDropdown:o=!0}){var d;const c=((d=n.find(u=>u.value===t))==null?void 0:d.label)||t,i=n.filter(u=>u.value!==t);return o?e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Badge,{variant:"outline",className:`cursor-pointer hover:bg-muted ${r?"cursor-not-allowed opacity-50":""} ${l}`,onClick:()=>console.log("Badge clicked:",{currentRole:t,disabled:r,allowDropdown:o}),children:c})}),e.jsx(s.DropdownMenuContent,{className:"z-[51]",children:i.map(u=>e.jsx(s.DropdownMenuItem,{onClick:()=>{console.log("Dropdown item clicked:",{currentRole:t,newRole:u.value,disabled:r}),a(u.value)},disabled:r,children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{children:u.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:u.description})]})},u.value))})]}):e.jsx(s.Badge,{variant:"outline",className:`text-xs ${l}`,children:c})}function it({selectedUsers:t,selectedUserObjects:a,onRemove:n,onRoleChange:r,getRoleOptions:l}){return t.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{className:"text-sm font-medium",children:["Selected Users (",t.length,")"]}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>t.forEach(o=>n(o.id)),className:"h-auto p-1 text-xs",children:"Clear all"})]}),e.jsx("div",{className:"flex max-h-20 flex-wrap gap-2 overflow-y-auto",children:a.map(o=>{const c=t.find(d=>d.id===o.id),i=l(o.type);return e.jsxs(s.Badge,{variant:"secondary",className:"gap-1",children:[o.name,e.jsx(ss,{currentRole:(c==null?void 0:c.role)||"VIEWER",onRoleChange:d=>r(o.id,d),roleOptions:i}),e.jsx("button",{onClick:()=>n(o.id),className:"ml-1 rounded-full p-0.5 hover:bg-muted-foreground/20",children:e.jsx(s.X,{className:"h-3 w-3"})})]},o.id)})}),e.jsx(s.Separator,{})]})}function ct({usersToRemove:t,allUsers:a,onRemove:n}){return t.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{className:"text-sm font-medium text-destructive",children:["Users to Remove Access (",t.length,")"]}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>t.forEach(r=>n(r)),className:"h-auto p-1 text-xs text-destructive hover:text-destructive",children:"Clear all"})]}),e.jsx("div",{className:"flex max-h-20 flex-wrap gap-2 overflow-y-auto",children:a.filter(r=>t.includes(r.id)).map(r=>e.jsxs(s.Badge,{variant:"destructive",className:"gap-1",children:[r.name,e.jsx("button",{onClick:()=>n(r.id),className:"ml-1 rounded-full p-0.5 hover:bg-destructive-foreground/20",children:e.jsx(s.X,{className:"h-3 w-3"})})]},r.id))}),e.jsx(s.Separator,{})]})}function dt({usersToUpdate:t,allUsers:a,onRemove:n,getRoleOptions:r}){if(t.length===0)return null;const l=r("tenant"),o=i=>{const d=a.find(u=>u.id===i);return(d==null?void 0:d.name)||"Unknown User"},c=i=>{const d=l.find(u=>u.value===i);return(d==null?void 0:d.label)||i};return e.jsxs("div",{className:"rounded-lg border border-orange-200 bg-orange-50 p-3",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(s.Users,{className:"h-4 w-4 text-orange-600"}),e.jsxs("span",{className:"text-sm font-medium text-orange-800",children:["Updating Access (",t.length,")"]})]}),e.jsx("div",{className:"space-y-2",children:t.map(i=>e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium",children:o(i.id)}),e.jsx("span",{className:"text-muted-foreground",children:"→"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:c(i.currentRole)}),e.jsx("span",{className:"text-muted-foreground",children:"→"}),e.jsx(s.Badge,{variant:"default",className:"text-xs",children:c(i.newRole)})]})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-muted-foreground hover:text-destructive",onClick:()=>n(i.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]},i.id))})]})}function ut(t,a={}){const{enabled:n=!0,eventType:r="mousedown"}=a,l=I.useRef(null);return I.useEffect(()=>{const o=c=>{const i=c.target;l.current&&l.current.contains(i)||i instanceof Element&&(i.closest("[data-radix-popper-content-wrapper]")||i.closest("[data-radix-select-content]")||i.closest("[data-radix-popover-content]")||i.closest("[data-radix-dropdown-menu-content]")||i.closest("[data-radix-tooltip-content]")||i.closest('[role="listbox"]')||i.closest('[role="option"]')||i.closest('[role="combobox"]'))||i instanceof Element&&i.hasAttribute("data-radix-")||t()};return n&&document.addEventListener(r,o),()=>{document.removeEventListener(r,o)}},[t,n,r]),l}function be(t,a){var n;return((n=a.find(r=>r.value===t))==null?void 0:n.label)||t}function nn(t){return["POWER_USER","ADMIN","EDITOR"].includes(t)}function mt(t){return"tenantId"in t&&t.tenantId?"tenant":"organization"}function rn(t,a,n){const r=mt(t),l=(n==null?void 0:n.type)||"organization";if(!(!a||!a.shares))if(l==="organization")if(r==="organization"){if("specificOrgUsers"in a.shares)return(a.shares.specificOrgUsers||[]).find(i=>i.orgUserId===t.id)}else return(a.shares.specificTenantUsers||[]).find(i=>i.tenantUserId===t.id);else return(a.shares.specificTenantUsers||[]).find(i=>i.tenantUserId===t.id)}function ln({user:t}){return mt(t)==="tenant"?e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:t.role==="POWER_USER"?"Power User":"Viewer"}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:t.role==="ADMIN"?"Admin":t.role==="POWER_USER"?"Power User":"Viewer"})}function on({user:t,userShare:a,usersToUpdate:n,currentUser:r,getRoleOptions:l,handleUpdateAccess:o}){if(!(a!=null&&a.role))return null;const c=nn((r==null?void 0:r.type)||""),i=n.some(h=>h.id===t.id),d=n.find(h=>h.id===t.id),u=d?d.newRole:a==null?void 0:a.role,m=l(t.type);return a?e.jsx("div",{className:"flex items-center gap-2",children:c?e.jsx(ss,{currentRole:u,onRoleChange:h=>{o(t.id,a.role,h)},roleOptions:m,disabled:!c,allowDropdown:c,className:i?"border-orange-300 bg-orange-100":""}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:be(u,m)})}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:"Unknown"})}function cn({hasAccess:t,isUserRemoving:a,isSelected:n,hasAccessFromAPI:r}){return e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[t&&!a&&e.jsxs(s.Badge,{variant:"outline",className:"border-green-200 bg-green-50 text-xs text-green-700",children:[e.jsx(s.Eye,{className:"mr-1 h-3 w-3"}),"Has Access"]}),a&&e.jsxs(s.Badge,{variant:"outline",className:"border-red-200 bg-red-50 text-xs text-red-700",children:[e.jsx(s.X,{className:"mr-1 h-3 w-3"}),"Remove Access"]}),n&&!r&&e.jsxs(s.Badge,{variant:"outline",className:"border-blue-200 bg-blue-50 text-xs text-blue-700",children:[e.jsx($e,{className:"mr-1 h-3 w-3"}),"Will Share"]})]})}function dn({isUserRemoving:t,isSelected:a,hasAccess:n,isRemoving:r,isSharing:l}){return e.jsxs(e.Fragment,{children:[t&&e.jsx("span",{className:"text-xs font-medium text-red-600",children:r?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.LoaderCircle,{className:"h-3 w-3 animate-spin"}),"Removing..."]}):"⚠ Will remove access"}),a&&!n&&e.jsx("span",{className:"text-xs font-medium text-blue-600",children:l?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.LoaderCircle,{className:"h-3 w-3 animate-spin"}),"Sharing..."]}):"Will share"})]})}function un({existingShares:t,allUsers:a,getRoleOptions:n,currentUser:r}){if(((r==null?void 0:r.type)||"organization")==="organization")if("specificOrgUsers"in t.shares){const c=t.shares,i=c.specificOrgUsers||[],d=c.specificTenantUsers||[],u=c.orgWide||[],m=c.orgUsersOnly||[],h=c.allTenantsOnly||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[i.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Org Users (",i.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[i.slice(0,3).map((f,g)=>{var x,v;const b=((x=a.find(k=>k.id===f.orgUserId))==null?void 0:x.name)||"Unknown User",p=((v=a.find(k=>k.id===f.orgUserId))==null?void 0:v.type)||"",j=be(f.role,n(p));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:b}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:j})]},g)}),i.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",i.length-3," more users"]})]})]}),d.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-green-600",children:["Specific Tenant Users (",d.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[d.slice(0,3).map((f,g)=>{var x,v;const b=((x=a.find(k=>k.id===f.tenantUserId))==null?void 0:x.name)||"Unknown User",p=((v=a.find(k=>k.id===f.tenantUserId))==null?void 0:v.type)||"",j=be(f.role,n(p));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:b}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:j})]},g)}),d.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",d.length-3," more users"]})]})]}),u.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-purple-600",children:"All Org Users"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:u.map((f,g)=>{const b=be(f.role,n(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Organization Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:b})]},g)})})]}),m.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-orange-600",children:"Org Users Only"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:m.map((f,g)=>{const b=be(f.role,n(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Org Users Only"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:b})]},g)})})]}),h.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-indigo-600",children:"All Tenants"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:h.map((f,g)=>{const b=be(f.role,n(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenants"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:b})]},g)})})]}),!i.length&&!d.length&&!u.length&&!m.length&&!h.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}else{const c=t.shares.specificTenantUsers||[],i=t.shares.tenantWide||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[c.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Users (",c.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[c.slice(0,3).map((d,u)=>{var g,b;const m=((g=a.find(p=>p.id===d.tenantUserId))==null?void 0:g.name)||"Unknown User",h=((b=a.find(p=>p.id===d.tenantUserId))==null?void 0:b.type)||"",f=be(d.role,n(h));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:m}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:f})]},u)}),c.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",c.length-3," more users"]})]})]}),i.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-green-600",children:"All Users"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:i.map((d,u)=>{const m=be(d.role,n(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenant Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:m})]},u)})})]}),!c.length&&!i.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}else{const o=t.shares.specificTenantUsers||[],c=t.shares.tenantWide||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[o.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Users (",o.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[o.slice(0,3).map((i,d)=>{var f,g;const u=((f=a.find(b=>b.id===i.tenantUserId))==null?void 0:f.name)||"Unknown User",m=((g=a.find(b=>b.id===i.tenantUserId))==null?void 0:g.type)||"",h=be(i.role,n(m));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:u}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:h})]},d)}),o.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",o.length-3," more users"]})]})]}),c.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-green-600",children:"All Users"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:c.map((i,d)=>{const u=be(i.role,n(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenant Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:u})]},d)})})]}),!o.length&&!c.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}}function mn({isInitialLoading:t,searchQuery:a,availableUsers:n}){return t?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(s.LoaderCircle,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Loading users..."})]})}):n.length===0?e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:a?"No users found matching your search.":"No users available to share with."}):null}function hn({user:t,userShare:a,isUserRemoving:n,hasAccess:r,hasAccessFromAPI:l,isSelected:o,selectedUser:c,roleOptions:i,currentUser:d,usersToUpdate:u,handleUserToggle:m,handleRemoveAccess:h,handleUpdateAccess:f,handleUserRoleChange:g}){return e.jsxs("div",{className:s.cn("flex items-center space-x-3 rounded-lg p-2 transition-colors",r&&!n?"border border-green-200 bg-green-50":n?"border border-red-200 bg-red-50":o?"border border-blue-200 bg-blue-50":"hover:bg-muted/50"),children:[e.jsx(s.Checkbox,{checked:l?!n:o,disabled:t.id===(d==null?void 0:d.id),onCheckedChange:()=>{l?n?m(t.id):h(t.id):m(t.id)}}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:t.name}),e.jsx(ln,{user:t})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&!n?e.jsx(ss,{currentRole:a==null?void 0:a.role,onRoleChange:b=>f(t.id,a.role,b),roleOptions:i,disabled:!1,allowDropdown:!0}):e.jsx(on,{user:t,userShare:a,usersToUpdate:u,currentUser:d,getRoleOptions:()=>i,handleUpdateAccess:f}),o&&!l&&e.jsx("div",{onClick:b=>b.stopPropagation(),children:e.jsx(ss,{currentRole:(c==null?void 0:c.role)||"VIEWER",onRoleChange:b=>g(t.id,b),roleOptions:i,disabled:!1})})]})]}),e.jsx("p",{className:"truncate text-xs text-muted-foreground",children:t.email}),e.jsx(cn,{hasAccess:r,isUserRemoving:n,isSelected:o,hasAccessFromAPI:l}),e.jsx(dn,{isUserRemoving:n,isSelected:o,hasAccess:r,isRemoving:!1,isSharing:!1})]})]})}function ht({existingShares:t,isInitialLoading:a,isSearching:n,getRoleOptions:r,allUsers:l=[],currentUser:o,handleUserToggle:c,handleUserRoleChange:i,handleRemoveAccess:d,handleUpdateAccess:u}){const m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),f=s.useShareUsersToUpdate(),g=s.useShareSearchQuery(),b=s.useShareManagementActions(),p=c||(C=>{const S=m.some(D=>D.id===C),y=h.includes(C);S?b.removeSelectedUser(C):y?b.removeUserFromRemove(C):b.addSelectedUser({id:C,role:"VIEWER"})}),j=i||b.updateSelectedUserRole,x=d||b.addUserToRemove,v=u||((C,S,y)=>{b.addUserToUpdate({id:C,currentRole:S,newRole:y})}),k=l,L=h;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Label,{className:"text-sm font-medium",children:["All Users (",(k??[]).length,")"]}),e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",children:e.jsx(s.Info,{className:"h-4 w-4"})})}),e.jsx(s.TooltipContent,{className:"w-48 max-w-sm",children:e.jsx(un,{existingShares:t,allUsers:l,getRoleOptions:r,currentUser:o})})]})})]}),(k==null?void 0:k.length)>0&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>{m.length===k.length?b.setSelectedUsers([]):b.setSelectedUsers(k.map(C=>({id:C.id,role:"VIEWER"})))},className:"h-auto p-1 text-xs",children:m.length===k.length?"Deselect all":"Select all"})]}),e.jsxs("div",{className:"max-h-60 space-y-1 overflow-y-auto rounded-md border p-2",children:[e.jsx(mn,{isInitialLoading:a,isSearching:n,searchQuery:g,availableUsers:k||[]}),!a&&!n&&(k==null?void 0:k.length)>0&&k.map(C=>{const S=t?rn(C,t,o):void 0,y=L.includes(C.id),D=!!S,N=D&&!y,B=m.some(T=>T.id===C.id),w=m.find(T=>T.id===C.id),F=r(C.type);return e.jsx(hn,{user:C,userShare:S,isUserRemoving:y,hasAccess:N,hasAccessFromAPI:D,isSelected:B,selectedUser:w,roleOptions:F,currentUser:o,usersToUpdate:f,handleUserToggle:p,handleRemoveAccess:x,handleUpdateAccess:v,handleUserRoleChange:j},C.id)})]})]})}function xt({shareType:t,onShareTypeChange:a,currentUser:n,options:r}){const l=(n==null?void 0:n.role)&&["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(n.role);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.RadioGroup,{value:t,onValueChange:a,className:`grid grid-cols-${r.length} gap-4`,children:r.map(o=>e.jsxs("div",{children:[e.jsx(s.RadioGroupItem,{value:o.value,id:o.value,className:"peer sr-only",disabled:o.disabled}),e.jsxs(s.Label,{htmlFor:o.value,className:`flex flex-col items-center justify-between rounded-md border-2 border-muted bg-popover p-4 hover:bg-accent hover:text-accent-foreground peer-data-[state=checked]:border-primary peer-data-[state=checked]:bg-primary/5 [&:has([data-state=checked])]:border-primary [&:has([data-state=checked])]:bg-primary/5 ${o.disabled?"cursor-not-allowed opacity-50":"cursor-pointer"}`,children:[o.icon||e.jsx(Be,{className:"mb-3 h-6 w-6"}),e.jsxs("div",{className:"space-y-1 text-center",children:[e.jsx("p",{className:"text-sm font-medium leading-none",children:o.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:o.description})]})]})]},o.value))}),!l&&r.some(o=>o.value==="all_users")&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Only admins, authors, power users, and super admins can share with all users."})]})}const Te=()=>[{value:"VIEWER",label:"Viewer",description:"Can view only"},{value:"EDITOR",label:"Editor",description:"Can view and edit"},{value:"CONTRIBUTOR",label:"Contributor",description:"Can view, edit, and share"},{value:"OWNER",label:"Owner",description:"Full access (view, edit, share, delete)"}];function xn({currentUser:t,currentShare:a,isSharing:n,onUpdateAccess:r,allUsersToUpdate:l=null,allUsersToRemove:o=!1,isUpdating:c=!1,isRemoving:i=!1}){const d=s.useShareCurrentMode(),u=Te().filter(v=>v.value==="VIEWER"||v.value==="EDITOR"||v.value==="CONTRIBUTOR"),m=a.role!=="NONE"?a.role:"NONE",h=l?l.newRole:m,f=a.role!=="NONE"&&!o&&(!l||l.newRole===m),g=l!==null&&l.newRole!==m,b=o,p=m==="NONE"||!m,j=v=>{switch(v){case"VIEWER":return e.jsx(s.Eye,{className:"h-4 w-4"});case"EDITOR":return e.jsx(s.SquarePen,{className:"h-4 w-4"});case"CONTRIBUTOR":return e.jsx(Va,{className:"h-4 w-4"});default:return e.jsx(s.Eye,{className:"h-4 w-4"})}},x=v=>{r(m,v)};return e.jsx("div",{className:"space-y-4",children:e.jsxs(s.Card,{className:s.cn("pb-6",g&&!b&&!p?"border-orange-300 bg-orange-50":f?"border-green-300 bg-green-50":b||p?"border-destructive bg-destructive/10":""),children:[e.jsxs(s.CardHeader,{children:[e.jsxs(s.CardTitle,{className:"flex items-center gap-2 text-base",children:[e.jsx(s.Users,{className:"h-5 w-5"}),"Share with All"," ",d==="allOrgUsers"?"Organization":d==="allTenantUsers"?"Tenant":d==="specificOrgUsers"?"Org":"Tenant"," ","Users",f&&e.jsx(s.Badge,{variant:"default",className:"ml-2 border-green-400 bg-green-100 text-green-800",children:"Active"}),g&&e.jsx(s.Badge,{variant:"secondary",className:"ml-2 border-orange-400 bg-orange-100 text-orange-800",children:"Pending Update"}),(b||p)&&e.jsx(s.Badge,{variant:"destructive",className:"ml-2",children:"No Access"})]}),e.jsx(s.CardDescription,{children:b||p?"No access for all users.":"This will share the dashboard with all users in your "+((t==null?void 0:t.type)==="organization"?"organization":"tenant")+". Select an access level below."})]}),e.jsx(s.CardContent,{className:"space-y-4",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Select Access Level:"}),e.jsxs(s.HoverCard,{children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-4 w-4 p-0 text-muted-foreground hover:text-foreground",children:e.jsx(s.Info,{className:"h-3 w-3"})})}),e.jsx(s.HoverCardContent,{className:"w-80",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Share with All Users"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["This action will share the dashboard with all users in your"," ",(t==null?void 0:t.type)==="organization"?"organization":"tenant",". Users will receive the selected access level."]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Viewer:"})," Can view the dashboard"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Editor:"})," Can view and edit the dashboard"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Contributor:"})," Can view, edit, and share the dashboard"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"None:"})," No access for all users"]})]})]})})]})]}),e.jsx("div",{className:"grid grid-cols-2 gap-3",children:u.map(v=>e.jsxs(s.Button,{variant:h===v.value?"default":"outline",className:"h-auto flex-col items-start gap-2 p-3",onClick:()=>x(v.value),disabled:n||c||i,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[j(v.value),e.jsx("span",{className:"font-medium",children:v.label})]}),e.jsx("p",{className:"text-left text-xs text-muted-foreground",children:v.description})]},v.value))})]})})]})})}function pt({currentUser:t,currentShare:a,isSharing:n,isUpdating:r,isRemoving:l,onUpdateAccess:o,onRemoveAccess:c,allUsersToUpdate:i,allUsersToRemove:d}){const u=p=>p==="OWNER"?"CONTRIBUTOR":p,h=a?{role:u(a.role)}:{role:"NONE"},f=i?{currentRole:u(i.currentRole),newRole:u(i.newRole)}:null,g=(p,j)=>{o(p,j)},b=()=>{c()};return e.jsx(xn,{currentUser:t,currentShare:h,isSharing:n,isUpdating:r,isRemoving:l,onUpdateAccess:g,onRemoveAccess:b,allUsersToUpdate:f,allUsersToRemove:d})}const pn=async(t,a={})=>{const n={};return a.search&&(n.search=a.search),a.type&&(n.type=a.type),a.active!==void 0&&(n.active=a.active.toString()),a.tenantId&&(n.tenantId=a.tenantId),a.limit&&(n.limit=a.limit.toString()),a.offset&&(n.offset=a.offset.toString()),a.page&&(n.page=a.page.toString()),a.pageSize&&(n.pageSize=a.pageSize.toString()),await s.getRequest("https://semaphor.cloud/api/management/v1/unified-users",t,n)};function fn(t={}){var o,c,i;const{authToken:a,tokenProps:n}=s.useSemaphorContext(),r=(n==null?void 0:n.endUserId)||(n==null?void 0:n.orgUserId),l=s.useQuery({queryKey:["unified-users",t],queryFn:()=>pn((a==null?void 0:a.accessToken)||"",t),enabled:!!(a!=null&&a.accessToken)&&!!r,retry:(d,u)=>u instanceof Error&&u.message.includes("401")||u instanceof Error&&u.message.includes("403")?!1:d<2,retryDelay:d=>Math.min(1e3*2**d,3e4)});return{users:((o=l.data)==null?void 0:o.users)||[],userContext:(c=l.data)==null?void 0:c.userContext,total:((i=l.data)==null?void 0:i.total)||0,isLoading:l.isLoading,isError:l.isError,isFetching:l.isFetching,error:l.error,refetch:l.refetch}}function De(t){const{debouncedSearchQuery:a,resourceId:n,resourceType:r=s.ResourceType.DASHBOARD,userType:l,tenantId:o}=t,c=I.useMemo(()=>({search:a,active:!0,...l?{type:l}:{},...l==="tenant"&&o?{tenantId:o}:{}}),[a,l,o]),{users:i,isLoading:d,isError:u}=fn(c),m=s.useResourceShares(r,n);return{allUsers:i,isLoadingUsers:d,isErrorLoadingUsers:u,existingShares:m.data,isLoadingShares:m.isLoading,isErrorLoadingShares:m.isError,isFetchingShares:m.isFetching}}function gn({resource:t,resourceType:a,currentUser:n,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:o=!1,isRemoving:c=!1}){var te,X;const i=s.useShareSelectedTab(),d=s.useShareSelectedTenant(),{searchQuery:u,setSearchQuery:m,debouncedSearchQuery:h}=s.useShareSearchWithDebounce(),f=s.useShareSelectedUsers(),g=s.useShareUsersToRemove(),b=s.useShareUsersToUpdate(),p=s.useShareCurrentMode(),j=s.useShareOrgWideRole(),x=s.useShareManagementActions(),[v,k]=I.useState("specific_users"),L=()=>{if(i==="org")return"organization";if(i==="tenant")return"tenant"},C=()=>{if(i==="tenant"&&d)return d},{allUsers:S,existingShares:y,isLoadingUsers:D}=De({debouncedSearchQuery:h,resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:L(),tenantId:C()});I.useEffect(()=>{x.setCurrentContext("org-tab"),x.setCurrentMode(v==="all_users"?"allOrgUsers":"specificOrgUsers")},[x,v]);const N=q=>{var _,J;const H=q;if(k(H),r==null||r(H),x.setCurrentContext("org-tab"),H==="specific_users")x.setCurrentMode("specificOrgUsers");else if(H==="all_users"){x.setCurrentMode("allOrgUsers");const z=(J=(_=y==null?void 0:y.shares)==null?void 0:_.orgUsersOnly)==null?void 0:J[0];z&&z.role!==void 0&&x.setOrgWideRole(z.role)}},B=S.filter(q=>q.name.toLowerCase().includes(u.toLowerCase())||q.email.toLowerCase().includes(u.toLowerCase())),w=S.filter(q=>f.some(H=>H.id===q.id)),F=q=>{var z,U;const H=f.some(Z=>Z.id===q),_=g.includes(q),J=(U=(z=y==null?void 0:y.shares)==null?void 0:z.specificOrgUsers)==null?void 0:U.some(Z=>Z.orgUserId===q);H?x.removeSelectedUser(q):_?x.removeUserFromRemove(q):J||x.addSelectedUser({id:q,role:"VIEWER"})},T=(q,H)=>{x.updateSelectedUserRole(q,H)},E=q=>{x.addUserToRemove(q),x.removeSelectedUser(q)},A=q=>{x.removeUserFromRemove(q)},O=q=>{x.removeUserFromUpdate(q)},M=(q,H)=>{x.setOrgWideRole(H)},R=()=>{x.setOrgWideRole((P==null?void 0:P.role)||"NONE")},P=(X=(te=y==null?void 0:y.shares)==null?void 0:te.orgUsersOnly)==null?void 0:X[0];I.useEffect(()=>{v==="all_users"&&P&&P.role!==void 0&&x.setOrgWideRole(P.role)},[v,P,x]);const K=D,$=!1;return n?e.jsxs(e.Fragment,{children:[e.jsx(xt,{shareType:v,onShareTypeChange:N,currentUser:n,options:[{value:"specific_users",label:"Specific Org User",description:"Choose individual users to share with",icon:e.jsx(Be,{className:"mb-3 h-6 w-6 text-orange-500"})},{value:"all_users",label:"All Org Users",description:`Share with all ${(n==null?void 0:n.type)==="organization"?"organization":"tenant"} users`,icon:e.jsx(s.Users,{className:"mb-3 h-6 w-6 text-indigo-500"}),disabled:!["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(n.role??"")}]}),v==="specific_users"?e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx(ot,{value:u,onChange:m}),e.jsx(it,{selectedUsers:f,selectedUserObjects:w,onRemove:F,onRoleChange:T,getRoleOptions:Te}),e.jsx(ct,{usersToRemove:g,allUsers:B,onRemove:A}),e.jsx(dt,{usersToUpdate:b,allUsers:B,onRemove:O,getRoleOptions:Te}),e.jsx(ht,{existingShares:y,isInitialLoading:K,isSearching:$,resource:t,onShare:()=>{},getRoleOptions:Te,allUsers:B,currentUser:n,handleUserToggle:F,handleUserRoleChange:T,handleRemoveAccess:E,handleUpdateAccess:(q,H,_)=>{x.addUserToUpdate({id:q,currentRole:H,newRole:_})}})]}):e.jsx("div",{className:"mt-3",children:e.jsx(pt,{currentUser:n,currentShare:P,isSharing:l,isUpdating:o,isRemoving:c,onUpdateAccess:M,onRemoveAccess:R,allUsersToUpdate:p==="allOrgUsers"&&j!==((P==null?void 0:P.role)||"NONE")?{currentRole:(P==null?void 0:P.role)||"NONE",newRole:j}:null,allUsersToRemove:p==="allOrgUsers"&&(P==null?void 0:P.role)===void 0})})]}):null}function _s({resource:t,resourceType:a,currentUser:n,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:o=!1,isRemoving:c=!1}){var z;const{searchQuery:i,debouncedSearchQuery:d,setSearchQuery:u}=s.useShareSearchWithDebounce(),m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),f=s.useShareUsersToUpdate(),g=s.useShareCurrentMode(),b=s.useShareTenantWideRole(),p=s.useShareAllTenantsRole(),j=s.useShareSelectedTenant(),x=s.useShareManagementActions(),{data:v,isLoading:k}=s.useTenants({enabled:(n==null?void 0:n.type)==="organization"}),[L,C]=I.useState((n==null?void 0:n.type)==="organization"?"all_tenants":"specific_tenant_users");I.useEffect(()=>{(n==null?void 0:n.type)==="tenant"?(x.setCurrentContext("tenant-dialog"),x.setCurrentMode("specificTenantUsers")):(x.setCurrentContext("tenant-tab"),x.setCurrentMode("allTenants"))},[x,n==null?void 0:n.type]);const S=U=>{var le,V,se,ne;C(U);let Z;if(U==="specific_tenant_users"?Z="specific_users":U==="all_tenant_users"||U==="all_tenants"?Z="all_users":Z="specific_users",r==null||r(Z),(n==null?void 0:n.type)==="tenant"?(x.setCurrentContext("tenant-dialog"),U==="specific_tenant_users"?x.setCurrentMode("specificTenantUsers"):U==="all_tenant_users"&&(x.setCurrentMode("allTenantUsers"),n!=null&&n.tenantId&&x.setSelectedTenant(n.tenantId))):(x.setCurrentContext("tenant-tab"),U==="specific_tenant_users"?x.setCurrentMode("specificTenantUsers"):U==="all_tenant_users"?x.setCurrentMode("allTenantUsers"):U==="all_tenants"&&x.setCurrentMode("allTenants")),U==="all_tenant_users"){const Y=(V=(le=N==null?void 0:N.shares)==null?void 0:le.tenantWide)==null?void 0:V[0];Y&&Y.role!==void 0&&x.setTenantWideRole(Y.role)}else if(U==="all_tenants"){const Y=(ne=(se=N==null?void 0:N.shares)==null?void 0:se.allTenantsOnly)==null?void 0:ne[0];Y&&Y.role!==void 0&&x.setAllTenantsRole(Y.role)}},y=U=>{x.setSelectedTenant(U)},{allUsers:D,existingShares:N,isLoadingUsers:B,isErrorLoadingUsers:w,isLoadingShares:F,isErrorLoadingShares:T}=De({debouncedSearchQuery:d,resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:"tenant",tenantId:(n==null?void 0:n.type)==="tenant"?n.tenantId:j}),E=U=>{var se,ne;const Z=m.some(Y=>Y.id===U),le=h.includes(U),V=(ne=(se=N==null?void 0:N.shares)==null?void 0:se.specificTenantUsers)==null?void 0:ne.some(Y=>Y.tenantUserId===U);Z?x.removeSelectedUser(U):le?x.removeUserFromRemove(U):V||x.addSelectedUser({id:U,role:"VIEWER"})},A=(U,Z)=>{x.updateSelectedUserRole(U,Z)},O=U=>{x.addUserToRemove(U),x.removeSelectedUser(U)},M=U=>{x.removeUserFromRemove(U)},R=U=>{x.removeUserFromUpdate(U)},P=(U,Z,le)=>{x.addUserToUpdate({id:U,currentRole:Z,newRole:le})},K=(U,Z)=>{L==="all_tenant_users"?x.setTenantWideRole(Z):L==="all_tenants"&&x.setAllTenantsRole(Z)},$=()=>{L==="all_tenant_users"?x.setTenantWideRole("VIEWER"):L==="all_tenants"&&x.setAllTenantsRole("VIEWER")},X=(()=>{var U,Z,le,V;return g==="allTenants"?(Z=(U=N==null?void 0:N.shares)==null?void 0:U.allTenantsOnly)==null?void 0:Z[0]:g==="allTenantUsers"?(V=(le=N==null?void 0:N.shares)==null?void 0:le.tenantWide)==null?void 0:V[0]:null})();I.useEffect(()=>{var U,Z,le,V;if(L==="all_tenant_users"){const se=(Z=(U=N==null?void 0:N.shares)==null?void 0:U.tenantWide)==null?void 0:Z[0];se&&se.role!==void 0&&x.setTenantWideRole(se.role)}else if(L==="all_tenants"){const se=(V=(le=N==null?void 0:N.shares)==null?void 0:le.allTenantsOnly)==null?void 0:V[0];se&&se.role!==void 0&&x.setAllTenantsRole(se.role)}},[L,N,x]);const q=D.filter(U=>m.some(Z=>Z.id===U.id)),H=B||F,_=w||T,J=()=>(n==null?void 0:n.type)==="tenant"||L==="all_tenants"?!0:j&&(L==="specific_tenant_users"||L==="all_tenant_users");return e.jsxs(e.Fragment,{children:[_&&e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(s.CircleAlert,{className:"mx-auto mb-2 h-8 w-8 text-destructive"}),e.jsx("p",{className:"mb-4 text-sm text-destructive",children:"Failed to load users or shares"}),e.jsx(s.Button,{variant:"outline",size:"sm",onClick:()=>window.location.reload(),children:"Retry"})]})}),!_&&n&&e.jsxs("div",{className:"max-h-[500px] space-y-4 overflow-y-auto",children:[e.jsx(xt,{shareType:L,onShareTypeChange:S,currentUser:n,options:(n==null?void 0:n.type)==="tenant"?[{value:"all_tenant_users",label:"All Users",description:"Share with all users of this tenant",icon:e.jsx(s.Users,{className:"mb-3 h-6 w-6 text-purple-500"})},{value:"specific_tenant_users",label:"Specific Users",description:"Share with specific tenant users",icon:e.jsx(Be,{className:"mb-3 h-6 w-6 text-orange-500"})}]:[{value:"all_tenants",label:"All Tenants",description:"Share with all tenants and their users",icon:e.jsx(Fs,{className:"mb-3 h-6 w-6 text-purple-500"})},{value:"all_tenant_users",label:"Specific Tenant",description:"Share with all users of a specific tenant",icon:e.jsx(s.House,{className:"mb-3 h-6 w-6 text-blue-500"})},{value:"specific_tenant_users",label:"Specific Tenant User",description:"Share with users of a specific tenant",icon:e.jsx(Be,{className:"mb-3 h-6 w-6 text-orange-500"})}]}),(n==null?void 0:n.type)==="organization"&&(L==="specific_tenant_users"||L==="all_tenant_users")&&e.jsxs("div",{className:"mt-4",children:[e.jsx(s.Label,{className:"mb-1 block text-sm font-medium",children:"Select Tenant"}),e.jsxs(s.Select,{value:j||"",onValueChange:y,disabled:k,children:[e.jsx(s.SelectTrigger,{className:"w-full",children:e.jsx(s.SelectValue,{placeholder:k?"Loading tenants...":"Select a tenant..."})}),e.jsx(s.SelectContent,{className:"z-[51]",children:(z=v==null?void 0:v.tenants)==null?void 0:z.map(U=>e.jsx(s.SelectItem,{value:U.id,children:U.name},U.id))})]})]}),J()?e.jsx(e.Fragment,{children:L==="specific_tenant_users"?e.jsxs("div",{className:"space-y-4",children:[e.jsx(ot,{value:i,onChange:u}),e.jsx(it,{selectedUsers:m,selectedUserObjects:q,onRemove:U=>E(U),onRoleChange:A,getRoleOptions:Te}),e.jsx(ct,{usersToRemove:h,allUsers:D,onRemove:M}),e.jsx(dt,{usersToUpdate:f,allUsers:D,onRemove:R,getRoleOptions:Te}),e.jsx(ht,{existingShares:N,isInitialLoading:!!H,isSearching:!1,resource:t,onShare:()=>{},getRoleOptions:Te,allUsers:D,currentUser:n,handleUserToggle:E,handleUserRoleChange:A,handleRemoveAccess:O,handleUpdateAccess:P})]}):L==="all_tenant_users"||L==="all_tenants"?e.jsx("div",{className:"mt-6",children:e.jsx(pt,{currentUser:n,currentShare:X,isSharing:l,isUpdating:o,isRemoving:c,onUpdateAccess:K,onRemoveAccess:$,allUsersToUpdate:g==="allTenantUsers"&&((X==null?void 0:X.role)===void 0||b!==X.role)||g==="allTenants"&&((X==null?void 0:X.role)===void 0||p!==X.role)?{currentRole:(X==null?void 0:X.role)||"VIEWER",newRole:g==="allTenantUsers"?b:p}:null,allUsersToRemove:g==="allTenantUsers"&&(X==null?void 0:X.role)===void 0||g==="allTenants"&&(X==null?void 0:X.role)===void 0})}):null}):(n==null?void 0:n.type)==="organization"&&(L==="specific_tenant_users"||L==="all_tenant_users")&&e.jsx("div",{className:"mt-6 flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Fs,{className:"mx-auto mb-2 h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Please select a tenant to continue"})]})})]})]})}const ft=()=>{const t=s.useShareCurrentContext(),a=s.useShareCurrentMode(),n=s.useShareSelectedUsers(),r=s.useShareUsersToRemove(),l=s.useShareUsersToUpdate(),o=s.useShareSelectedTenant(),c=s.useShareOrgWideRole(),i=s.useShareAllTenantsRole(),d=s.useShareTenantWideRole(),u=I.useMemo(()=>()=>s.buildShareData({currentContext:t,currentMode:a,selectedUsers:n,usersToRemove:r,usersToUpdate:l,selectedTenant:o,orgWideRole:c,allTenantsRole:i,tenantWideRole:d}),[t,a,n,r,l,o,c,i,d]),m=I.useMemo(()=>f=>s.validateShareData(f),[]),h=I.useMemo(()=>{if(!t||!a)return!1;switch(t){case"org-tab":return a==="specificOrgUsers"?n.length>0||r.length>0||l.length>0:!0;case"tenant-tab":if(a==="allTenantUsers"){if(!o)return!1}else if(a==="specificTenantUsers")return o?n.length>0||r.length>0||l.length>0:!1;return!0;case"tenant-dialog":return a==="specificTenantUsers"?n.length>0||r.length>0||l.length>0:!0}return!1},[t,a,n,r,l,o]);return{buildShareData:u,validateShareData:m,isCurrentStateValid:h,currentContext:t,currentMode:a,selectedUsers:n,usersToRemove:r,usersToUpdate:l,selectedTenant:o,orgWideRole:c,allTenantsRole:i,tenantWideRole:d}};function Us({resource:t,existingShares:a,isSharing:n,isRemoving:r,isUpdating:l,onShare:o,onClose:c,shareTabType:i,currentAllUsersShare:d,onRemoveAccess:u}){const m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),f=s.useShareUsersToUpdate();s.useShareCurrentMode(),s.useShareCurrentContext();const g=s.useShareSelectedTenant();s.useShareSelectedTab();const b=s.useShareOrgWideRole(),p=s.useShareAllTenantsRole(),j=s.useShareTenantWideRole(),{buildShareData:x,validateShareData:v,isCurrentStateValid:k}=ft(),L=n||r||l,C=()=>{var B,w,F,T;if(L)return"Updating...";if(i==="specific_users"){if(m.length===0&&h.length===0&&f.length===0)return"Select users to share with";const E=m.length+h.length+f.length;return E===0?"Select users to share with":m.length>0&&h.length>0?`Update access for ${E} user${E!==1?"s":""}`:h.length>0&&m.length===0&&f.length===0?`Remove access for ${h.length} user${h.length!==1?"s":""}`:m.length>0&&h.length===0&&f.length===0?`Share with ${m.length} user${m.length!==1?"s":""}`:f.length>0&&m.length===0&&h.length===0?`Update access for ${f.length} user${f.length!==1?"s":""}`:`Update access for ${E} user${E!==1?"s":""}`}else if(i==="all_users"){if(!d||d.role===void 0)return"Share with All Users";const E=d.role;return b===E?"Remove Access":"Update Access"}else if(i==="all_tenants"){const E=(w=(B=a==null?void 0:a.shares)==null?void 0:B.allTenantsOnly)==null?void 0:w[0];if(!E||E.role===void 0)return"Share with All Tenants";const A=E.role;return p===A?"Remove Access":"Update Access"}else if(i==="all_tenant_users"){const E=(T=(F=a==null?void 0:a.shares)==null?void 0:F.tenantWide)==null?void 0:T[0];if(!E||E.role===void 0)return"Share with All Tenant Users";const A=E.role;return j===A?"Remove Access":"Update Access"}else if(i==="specific_tenant_users"){if(m.length===0&&h.length===0&&f.length===0)return"Select users to share with";const E=m.length+h.length+f.length;return E===0?"Select users to share with":m.length>0&&h.length>0?`Update access for ${E} user${E!==1?"s":""}`:h.length>0&&m.length===0&&f.length===0?`Remove access for ${h.length} user${h.length!==1?"s":""}`:m.length>0&&h.length===0&&f.length===0?`Share with ${m.length} user${m.length!==1?"s":""}`:f.length>0&&m.length===0&&h.length===0?`Update access for ${f.length} user${f.length!==1?"s":""}`:`Update access for ${E} user${E!==1?"s":""}`}return"Share"},S=()=>L||!t||i==="all_tenant_users"&&!g||i==="specific_tenant_users"&&!g?!0:!k,y=()=>{const B=x();B&&v(B)&&o(B)},D=()=>{var B,w,F,T;if(i==="all_users")if(!d||d.role===void 0){const E=x();E&&v(E)&&o(E)}else{const E=d.role;if(b===E)u==null||u();else{const O=x();if(O&&v(O)){const M={...O,updateAccess:!0};o(M)}}}else if(i==="all_tenants"){const E=(w=(B=a==null?void 0:a.shares)==null?void 0:B.allTenantsOnly)==null?void 0:w[0];if(!E||E.role===void 0){const A=x();A&&v(A)&&o(A)}else{const A=E.role;if(p===A)u==null||u();else{const M=x();if(M&&v(M)){const R={...M,updateAccess:!0};o(R)}}}}else if(i==="all_tenant_users"){const E=(T=(F=a==null?void 0:a.shares)==null?void 0:F.tenantWide)==null?void 0:T[0];if(!E||E.role===void 0){const A=x();A&&v(A)&&o(A)}else{const A=E.role;if(j===A)u==null||u();else{const M=x();if(M&&v(M)){const R={...M,updateAccess:!0};o(R)}}}}},N=()=>{var B,w,F,T;if(i==="all_users"){if(!d||d.role===void 0)return"default";const E=d.role;return b===E?"destructive":"default"}else if(i==="all_tenants"){const E=(w=(B=a==null?void 0:a.shares)==null?void 0:B.allTenantsOnly)==null?void 0:w[0];if(!E||E.role===void 0)return"default";const A=E.role;return p===A?"destructive":"default"}else if(i==="all_tenant_users"){const E=(T=(F=a==null?void 0:a.shares)==null?void 0:F.tenantWide)==null?void 0:T[0];if(!E||E.role===void 0)return"default";const A=E.role;return j===A?"destructive":"default"}return"default"};return e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:c,disabled:L,children:"Close"}),(i==="specific_users"||i==="specific_tenant_users")&&e.jsx(e.Fragment,{children:(m.length>0||h.length>0||f.length>0)&&e.jsxs(s.Button,{onClick:y,disabled:!t||L,variant:"default",children:[L?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx($e,{className:"mr-2 h-4 w-4"}),!L&&C()]})}),(i==="all_users"||i==="all_tenants"||i==="all_tenant_users")&&e.jsxs(s.Button,{onClick:D,disabled:S(),variant:N(),children:[L?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(s.Users,{className:"mr-2 h-4 w-4"}),!L&&C()]})]})}function jn({resource:t,isSharing:a,isRemoving:n,isUpdating:r,onShare:l,onClose:o,shareTabType:c,currentAllUsersShare:i}){const d=s.useShareSelectedUsers(),u=s.useShareUsersToRemove(),m=s.useShareUsersToUpdate();s.useShareCurrentMode(),s.useShareCurrentContext();const h=s.useShareTenantWideRole();s.useShareSelectedTenant();const{buildShareData:f,validateShareData:g,isCurrentStateValid:b}=ft(),p=a||n||r,j=()=>{if(p)return"Updating...";if(c==="specific_users"){if(d.length===0&&u.length===0&&m.length===0)return"Select users to share with";const C=d.length+u.length+m.length;return C===0?"Select users to share with":d.length>0&&u.length>0?`Update access for ${C} user${C!==1?"s":""}`:u.length>0&&d.length===0&&m.length===0?`Remove access for ${u.length} user${u.length!==1?"s":""}`:d.length>0&&u.length===0&&m.length===0?`Share with ${d.length} user${d.length!==1?"s":""}`:m.length>0&&d.length===0&&u.length===0?`Update access for ${m.length} user${m.length!==1?"s":""}`:`Update access for ${C} user${C!==1?"s":""}`}else if(c==="all_users"){if(!i||i.role==="NONE")return"Share with All Users";const C=i.role;return h===C?"Remove Access":"Update Access"}return"Share"},x=()=>p||!t?!0:!b,v=()=>{const C=f();C&&g(C)&&l(C)},k=()=>{if(!i||i.role==="NONE"){const C=f();C&&g(C)&&l(C)}else{const C=i.role;if(h===C){const y=f();if(y&&g(y)){const D={...y,removeAccess:!0};l(D)}}else{const y=f();if(y&&g(y)){const D={...y,updateAccess:!0};l(D)}}}},L=()=>!i||i.role==="NONE"?"default":"destructive";return e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:o,disabled:p,children:"Close"}),c==="specific_users"&&e.jsx(e.Fragment,{children:(d.length>0||u.length>0||m.length>0)&&e.jsxs(s.Button,{onClick:v,disabled:!t||p,variant:"default",children:[p?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx($e,{className:"mr-2 h-4 w-4"}),!p&&j()]})}),c==="all_users"&&e.jsxs(s.Button,{onClick:k,disabled:x(),variant:L(),children:[p?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx($e,{className:"mr-2 h-4 w-4"}),!p&&j()]})]})}function gt({resource:t,resourceType:a,isSharing:n,isRemoving:r,isUpdating:l,onClose:o,onShare:c,onRemoveAccess:i}){var y,D,N,B;const{currentUser:d}=s.useCurrentUserInfo(),[u,m]=I.useState("specific_users"),[h,f]=I.useState("specific_users"),g=s.useShareManagementActions(),b=s.useShareSelectedTab(),p=s.useShareCurrentMode(),{existingShares:j}=De({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:"tenant"}),{existingShares:x}=De({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:"organization"}),v=(D=(y=j==null?void 0:j.shares)==null?void 0:y.tenantWide)==null?void 0:D[0],k=(B=(N=x==null?void 0:x.shares)==null?void 0:N.orgUsersOnly)==null?void 0:B[0],L=()=>{if(b==="org")return h;switch(p){case"specificTenantUsers":return"specific_tenant_users";case"allTenantUsers":return"all_tenant_users";case"allTenants":return"all_tenants";default:return"specific_tenant_users"}},C=I.useCallback(()=>{g.resetShareState(),o()},[g,o]),S=(d==null?void 0:d.type)==="organization";return e.jsx(s.Dialog,{open:!0,onOpenChange:C,children:e.jsxs(s.DialogContent,{className:"z-[51] flex max-h-[80vh] max-w-3xl flex-col",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx($e,{className:"h-5 w-5"}),' Share "',t==null?void 0:t.title,'"']})}),e.jsx(s.DialogDescription,{children:S?"Share this resource with org users or tenant users. As a super admin, you can share with all users.":"Share this resource with other users in your tenant."})]}),S?e.jsxs(s.Tabs,{value:b,onValueChange:w=>{const F=w;g.setSelectedTab(F),g.resetUserSelections()},className:"mb-4 min-h-0 flex-1",children:[e.jsxs(s.TabsList,{className:"mb-2 grid w-full grid-cols-2",children:[e.jsx(s.TabsTrigger,{value:"org",children:"Org Users"}),e.jsx(s.TabsTrigger,{value:"tenant",children:"Tenant Users"})]}),e.jsx(s.TabsContent,{value:"org",className:"min-h-0 flex-1 overflow-hidden",children:e.jsx("div",{className:"h-full overflow-y-auto",children:e.jsx(gn,{resource:t,resourceType:a,currentUser:d,onShareTabTypeChange:f,isSharing:n,isUpdating:l,isRemoving:r})})}),e.jsx(s.TabsContent,{value:"tenant",className:"min-h-0 flex-1 overflow-hidden",children:e.jsx("div",{className:"h-full overflow-y-auto",children:e.jsx(_s,{resource:t,resourceType:a,currentUser:d,onShareTabTypeChange:w=>m(w),isSharing:n,isUpdating:l,isRemoving:r})})})]}):e.jsx("div",{className:"mb-4 min-h-0 flex-1 overflow-hidden",children:e.jsx("div",{className:"h-full overflow-y-auto",children:e.jsx(_s,{resource:t,resourceType:a,currentUser:d,onShareTabTypeChange:w=>m(w),isSharing:n,isUpdating:l,isRemoving:r})})}),e.jsx("div",{className:"mt-auto flex-shrink-0",children:S?b==="org"?e.jsx(Us,{resource:t,existingShares:x,isSharing:n,isRemoving:r,isUpdating:l,onShare:c,onClose:o,shareTabType:h,currentAllUsersShare:k,onRemoveAccess:i}):e.jsx(Us,{resource:t,existingShares:j,isSharing:n,isRemoving:r,isUpdating:l,onShare:c,onClose:o,shareTabType:L(),currentAllUsersShare:v,onRemoveAccess:i}):e.jsx(jn,{resource:t,isSharing:n,isRemoving:r,isUpdating:l,onShare:c,onClose:o,shareTabType:u,currentAllUsersShare:v,onRemoveAccess:i})})]})})}function pe(t,a,n){return{resourceType:t,resourceId:a,data:{shares:n}}}function we(t,a,n){return{resourceType:t,resourceId:a,data:{shares:n}}}function jt(t,a,n){const{resourceType:r,resourceId:l,shareMutation:o,removeMutation:c,existingShares:i,resetUserSelections:d}=a;if(l)switch(t.context){case"org-tab":if(t.mode==="allOrgUsers"){const u=pe(r,l,[{scope:"org_users_only",role:t.orgWideRole}]);o(u,{onSuccess:()=>{d()}})}else if(t.mode==="specificOrgUsers"){const{selectedUsers:u,usersToRemove:m,usersToUpdate:h}=t;if(u&&u.length>0){const f=pe(r,l,u.map(g=>({scope:"specific_org_user",orgUserId:g.id,role:g.role})));o(f,{onSuccess:()=>{d()}})}if(m&&m.length>0){const f=we(r,l,m.map(g=>{var p,j;const b=(j=(p=i==null?void 0:i.shares)==null?void 0:p.specificOrgUsers)==null?void 0:j.find(x=>x.orgUserId===g);return{scope:"specific_org_user",orgUserId:g,role:(b==null?void 0:b.role)||"VIEWER"}}));c(f,{onSuccess:()=>{d()}})}h&&h.length>0&&h.forEach(f=>{const g=pe(r,l,[{scope:"specific_org_user",orgUserId:f.id,role:f.newRole}]);o(g,{onSuccess:()=>{d()}})})}break;case"tenant-tab":if(t.mode==="allTenants"){const u=pe(r,l,[{scope:"all_tenants_only",role:t.allTenantsRole}]);o(u,{onSuccess:()=>{d()}})}else if(t.mode==="allTenantUsers"){const u=pe(r,l,[{scope:"all_tenant_users",tenantId:t.tenantId,role:t.tenantWideRole}]);o(u,{onSuccess:()=>{d()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:u,usersToRemove:m,usersToUpdate:h,tenantId:f}=t;if(m&&m.length>0){const g=we(r,l,m.map(b=>{var j,x;const p=(x=(j=i==null?void 0:i.shares)==null?void 0:j.specificTenantUsers)==null?void 0:x.find(v=>v.tenantUserId===b);return{scope:"specific_tenant_user",tenantUserId:b,tenantId:f,role:(p==null?void 0:p.role)||"VIEWER"}}));c(g,{onSuccess:()=>{d()}})}if(h&&h.length>0&&h.forEach(g=>{const b=pe(r,l,[{scope:"specific_tenant_user",tenantUserId:g.id,tenantId:f,role:g.newRole}]);o(b,{onSuccess:()=>{d()}})}),u&&u.length>0){const g=pe(r,l,u.map(b=>({scope:"specific_tenant_user",tenantUserId:b.id,tenantId:f,role:b.role})));o(g,{onSuccess:()=>{d()}})}}break;case"tenant-dialog":if(t.mode==="allTenantUsers")if(t.removeAccess){const u=we(r,l,[{scope:"all_tenant_users",role:"VIEWER"}]);c(u,{onSuccess:()=>{d()}})}else if(t.updateAccess){const u=pe(r,l,[{scope:"all_tenant_users",tenantId:n==null?void 0:n.tenantId,role:t.tenantWideRole}]);o(u,{onSuccess:()=>{d()}})}else{const u=pe(r,l,[{scope:"all_tenant_users",tenantId:n==null?void 0:n.tenantId,role:t.tenantWideRole}]);o(u,{onSuccess:()=>{d()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:u,usersToRemove:m,usersToUpdate:h}=t;if(u&&u.length>0){const f=pe(r,l,u.map(g=>({scope:"specific_tenant_user",tenantUserId:g.id,role:g.role})));o(f,{onSuccess:()=>{d()}})}if(m&&m.length>0){const f=we(r,l,m.map(g=>{var p,j;const b=(j=(p=i==null?void 0:i.shares)==null?void 0:p.specificTenantUsers)==null?void 0:j.find(x=>x.tenantUserId===g);return{scope:"specific_tenant_user",tenantUserId:g,role:(b==null?void 0:b.role)||"VIEWER"}}));c(f,{onSuccess:()=>{d()}})}h&&h.length>0&&h.forEach(f=>{const g=pe(r,l,[{scope:"specific_tenant_user",tenantUserId:f.id,role:f.newRole}]);o(g,{onSuccess:()=>{d()}})})}break}}function bt(t,a,n,r){var u,m,h,f,g,b;const{resourceType:l,resourceId:o,removeMutation:c,existingShares:i,resetUserSelections:d}=r;if(o)if(t.length>0){const p=we(l,o,t.map(j=>{var v,k;const x=(k=(v=i==null?void 0:i.shares)==null?void 0:v.specificTenantUsers)==null?void 0:k.find(L=>L.tenantUserId===j);return{scope:"specific_tenant_user",tenantUserId:j,role:(x==null?void 0:x.role)||"VIEWER"}}));c(p,{onSuccess:()=>{d()},onError:j=>{console.error("Remove access failed:",j)}})}else{const p=a==="tenant"&&n==="allTenants",j=a==="tenant"&&n==="allTenantUsers";if(p){const x=(m=(u=i==null?void 0:i.shares)==null?void 0:u.allTenantsOnly)==null?void 0:m[0];if(x){const v=we(l,o,[{scope:"all_tenants_only",role:x.role}]);c(v,{onSuccess:()=>{d()},onError:k=>{console.error("Remove all-tenants access failed:",k)}})}}else if(j){const x=(f=(h=i==null?void 0:i.shares)==null?void 0:h.tenantWide)==null?void 0:f[0];if(x){const v=we(l,o,[{scope:"all_tenant_users",role:x.role}]);c(v,{onSuccess:()=>{d()},onError:k=>{console.error("Remove all-tenant-users access failed:",k)}})}}else{const x=(b=(g=i==null?void 0:i.shares)==null?void 0:g.orgUsersOnly)==null?void 0:b[0];if(x){const v=we(l,o,[{scope:"org_users_only",role:x.role}]);c(v,{onSuccess:()=>{d()},onError:k=>{console.error("Remove org-wide access failed:",k)}})}}}}function bn(t,a,n){const r=s.useShareManagementActions(),l=s.useShareUsersToRemove(),o=s.useShareSelectedTab(),c=s.useShareCurrentMode(),{currentUser:i}=s.useCurrentUserInfo(),{existingShares:d}=De({debouncedSearchQuery:"",resourceId:t||"",resourceType:s.ResourceType.DASHBOARD,userType:"tenant"}),u=I.useCallback(()=>{r.resetUserSelections()},[r]),m=I.useCallback(f=>{if(!t)return;const g={resourceType:s.ResourceType.DASHBOARD,resourceId:t,shareMutation:a,removeMutation:n,existingShares:d,resetUserSelections:u};jt(f,g,i)},[t,a,n,d,u,i]),h=I.useCallback(()=>{if(!t)return;const f={resourceType:s.ResourceType.DASHBOARD,resourceId:t,removeMutation:n,existingShares:d,resetUserSelections:u};bt(l,o||"",c||"",f)},[t,a,n,d,u,l,o,c]);return{handleShareSubmit:m,handleRemoveAccess:h}}function yn(t,a,n){const{currentUser:r}=s.useCurrentUserInfo(),l=s.useShareManagementActions(),o=s.useShareUsersToRemove(),c=s.useShareSelectedTab(),i=s.useShareCurrentMode(),{existingShares:d}=De({debouncedSearchQuery:"",resourceId:t||"",resourceType:s.ResourceType.VISUAL,userType:"tenant"}),u=I.useCallback(()=>{l.resetUserSelections()},[l]),m=I.useCallback(f=>{if(!t)return;const g={resourceType:s.ResourceType.VISUAL,resourceId:t,shareMutation:a,removeMutation:n,existingShares:d,resetUserSelections:u};jt(f,g,r)},[t,a,n,d,u,r]),h=I.useCallback(()=>{if(!t)return;const f={resourceType:s.ResourceType.VISUAL,resourceId:t,removeMutation:n,existingShares:d,resetUserSelections:u};bt(o,c||"",i||"",f)},[t,a,n,d,u,o,c,i]);return{handleShareSubmit:m,handleRemoveAccess:h}}function vn(t){const a=t.toUpperCase().indexOf("WHERE"),n=t.toUpperCase().indexOf("GROUP BY"),r=t.toUpperCase().indexOf("LIMIT"),l=t.toUpperCase().indexOf("ORDER BY");let o=t.length;if(l!==-1&&(o=l),r!==-1&&r<o&&(o=r),a!==-1){const c=t.substring(0,a),i=t.substring(a);return`${c} {{ filters | where }} AND ${i.substring(6)}`}else if(n!==-1){const c=t.substring(0,n),i=t.substring(n);return`${c} {{ filters | where }} ${i}`}else{const c=t.substring(0,o),i=t.substring(o);return console.log("beforeClause",c),console.log("afterClause",i),i?`${c} {{ filters | where }} ${i}`:`${c.replace(/;$/,"")} {{ filters | where }}`}}function Ns(t){const[a,n]=I.useState(null),[r,l]=I.useState(null);return I.useEffect(()=>{if(!t||t.trim()===""){n(null),l(null);return}(async()=>{try{if(!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`Invalid URL format: ${t}`);try{new URL(t)}catch{throw new Error(`Invalid URL: ${t}`)}const i=`${t.endsWith("/")?t:`${t}/`}index.js`;try{if(!(await fetch(i,{method:"HEAD"})).ok)throw new Error(`Module not found at ${i}`)}catch{}const d=await import(i);if(typeof d.useChartStore!="function")throw new Error("useChartStore is not a function");n(()=>d.useChartStore),l(null)}catch(c){const i=c instanceof Error?c.message:"Unknown error";console.error("Failed to load remote chart store:",i),l(i),n(null)}})()},[t]),a}function Nn(t,a){if(t.length===0)return"";if(a){const n=t.find(r=>r.id===a);if(n){const r=n.tabTitle;if(r=="All__Header")return t[0].id;if(r&&r.endsWith("__Header")){const o=r.split("__")[0],c=t.find(i=>i.tabTitle===o);return c?c.id:t[0].id}return a}}return t[0].id}async function $s(t,a,n){if(!t||!a)throw new Error("Missing auth token or visual ID");const r=["resource-by-id","visual",a],l=n.getQueryData(r);if(l)return console.log("Using cached visual data for:",a),{data:l,fromCache:!0};console.log("Fetching visual data from network for:",a);const o=s.ue.loading("Loading visual...",{position:"top-center"});try{const c=await fetch(`https://semaphor.cloud/api/management/v1/visuals/${a}`,{headers:{Authorization:`Bearer ${t}`}});if(!c.ok)throw new Error("Failed to load visual");const i=await c.json();return n.setQueryData(r,i),s.ue.dismiss(o),{data:i,fromCache:!1}}catch(c){throw s.ue.dismiss(o),c}}function Cn(t,a,n,r,l){const o=t.frameObject;a(o);const c=o.cards.find(i=>i.id===o.activeCardId);c&&n(c),r(!0),l(!0)}function Sn(){var f;const{setCardSql:t}=s.useEditorActions(),a=s.useEditorStore(g=>g.frame),n=s.useEditorStore(g=>g.card),r=Ns(((f=n.customCardPreferences)==null?void 0:f.url)||""),l=s.useEditorStore(g=>g.selectedSchemaName),o=s.useEditorStore(g=>g.selectedDatamodelId),c=s.useEditorStore(g=>g.selectedDatabaseName),i=s.useEditorStore(g=>g.selectedTableName),d=s.useEditorStore(g=>g.selectedConnectionId),u=s.useEditorStore(g=>g.isShowingVisual),m=n.sql;return{getUpdatedFrame:I.useCallback(()=>{var x;let g=m;m&&!m.includes("{{")&&(g=vn(m),t(g));const b=(x=r==null?void 0:r.getState())==null?void 0:x.settings,p={...n,dataSource:n.dataSource||{mode:"directSource"},lastSelectedSchema:l,lastSelectedDatamodelId:o,lastSelectedDatabase:c,lastSelectedTable:i,connectionId:d,sql:g,customCfg:u?n.customCfg:null,preferences:n.preferences,...b&&{customCardPreferences:{...n.customCardPreferences,settings:b}}},j=a.cards.map(v=>v.id===n.id?p:v);return{...a,cards:j,activeCardId:Nn(j,a.activeCardId)}},[n,a,u,l,o,c,i,d,t,r,m])}}function Cs(){const{authToken:t}=s.useSemaphorContext(),a=s.useQueryClient(),n=s.useSelectedVisual(),{selectVisual:r}=s.useManagementActions(),{setFrame:l,setCard:o}=s.useEditorActions(),{setIsDashboardEditing:c,setIsVisualEditing:i,setSelectedFrameId:d,addFrame:u,setIsDashboardPanelOpen:m}=s.useDashboardActions(),h=s.useDashboardStore(p=>p.selectedSheetId),f=s.useVisualById((n==null?void 0:n.id)||"",{enabled:!!(n!=null&&n.id)&&!!(t!=null&&t.accessToken)}),g=I.useCallback(async p=>{try{r(p);const{data:j,fromCache:x}=await $s((t==null?void 0:t.accessToken)||"",p.id,a);return Cn(j,l,o,c,i),{success:!0,fromCache:x}}catch(j){return console.error("Error editing visual:",j),{success:!1,error:"Failed to load visual for editing"}}},[t==null?void 0:t.accessToken,a,r,l,o,c,i]),b=I.useCallback(async p=>{try{if(r(p),!h)return{success:!1,error:"No sheet selected. Please select a sheet first."};const{data:j,fromCache:x}=await $s((t==null?void 0:t.accessToken)||"",p.id,a),v=j.frameObject;if(!v)return{success:!1,error:"Visual has no frame data"};const k={...v,id:s.v4()};return u(h,k,"end"),c(!0),d(k.id),m(!1),{success:!0,fromCache:x}}catch(j){return console.error("Error adding visual:",j),{success:!1,error:"Failed to add visual to dashboard"}}},[t==null?void 0:t.accessToken,a,r,h,u,c,d,m]);return{visual:f.data,isLoading:f.isLoading,isError:f.isError,error:f.error,handleEditLibraryVisual:g,handleAddLibraryVisual:b,getUpdatedFrame:Sn().getUpdatedFrame,refetch:f.refetch}}function wn(){const[t,a]=I.useState(""),[n,r]=I.useState(!1),[l,o]=I.useState(""),[c,i]=I.useState(""),[d,u]=I.useState(!1),[m,h]=I.useState(null),[f,g]=I.useState(!1),[b,p]=I.useState(null),[j,x]=I.useState(null),{setIsDashboardEditing:v,setIsVisualEditing:k}=s.useDashboardActions(),{handleEditLibraryVisual:L,handleAddLibraryVisual:C}=Cs(),{resources:S,isLoading:y,isError:D,createResource:N,updateResource:B,deleteResource:w,duplicateResource:F,shareResource:T,isCreating:E,isDeleting:A,removeResourceShares:O,isSharing:M,isRemovingShares:R,isUpdatingShares:P}=s.useVisualManagement(()=>{g(!1),p(null)},()=>{r(!1),o(""),i("")}),{handleShareSubmit:K,handleRemoveAccess:$}=yn((m==null?void 0:m.id)||null,T,O);s.useCurrentUserInfo();const te=S.filter(W=>{var re,ie;return((re=W==null?void 0:W.title)==null?void 0:re.toLowerCase().includes(t.toLowerCase()))||((ie=W==null?void 0:W.description)==null?void 0:ie.toLowerCase().includes(t.toLowerCase()))}),X=W=>new Date(W).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),q=()=>{l.trim()&&N({title:l,description:c,isPrivate:!1})},H=W=>{p(W),g(!0)},_=()=>{b&&w(b.id)},{startUpdating:J,stopUpdating:z,isUpdating:U}=s.useResourceUpdateState(),Z=(W,re)=>{const ie=re.title!==void 0?"title":"description";J(W,ie),B({resourceId:W,data:re},{onSuccess:()=>{z(W,ie)},onError:()=>{z(W,ie)}})},le=W=>{x(W),F(W,{onSettled:()=>x(null)})},V=W=>{L(W)},se=W=>{C(W)},ne=W=>{const re=S.find(ie=>ie.id===W);re&&B({resourceId:W,data:{isPrivate:!re.isPrivate}})},Y=W=>{h(W),u(!0)};return s.useShareUsersToRemove(),s.useShareManagementActions(),De({debouncedSearchQuery:"",resourceId:(m==null?void 0:m.id)||"",resourceType:s.ResourceType.VISUAL,userType:"tenant"}),y?e.jsx(lt,{}):D?e.jsx(s.ScrollArea,{className:"w-full flex-1 pr-2",children:e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx("p",{className:"text-sm text-destructive",children:"Failed to load visuals"}),e.jsx(s.Button,{variant:"outline",size:"sm",className:"mt-2",onClick:()=>window.location.reload(),children:"Retry"})]})}):e.jsxs("div",{className:"mt-1 flex h-full flex-1 flex-col gap-3 px-4",children:[e.jsx("div",{className:"px-1",children:n?e.jsxs(s.Card,{className:"border-dashed p-4 pb-2",children:[e.jsx(s.CardHeader,{className:"px-0 pb-3 pt-0",children:e.jsx(s.CardTitle,{className:"text-sm",children:"New Visual"})}),e.jsxs(s.CardContent,{className:"space-y-3 px-0 pb-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"title",className:"text-xs",children:"Title"}),e.jsx(s.Input$1,{id:"title",placeholder:"Enter visual title...",value:l,onChange:W=>o(W.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"description",className:"text-xs",children:"Description (optional)"}),e.jsx(s.Input$1,{id:"description",placeholder:"Enter visual description...",value:c,onChange:W=>i(W.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(s.Button,{onClick:q,size:"sm",className:"h-7 text-xs",disabled:!l.trim()||E,children:E?"Creating...":"Create"}),e.jsx(s.Button,{onClick:()=>{r(!1),o(""),i("")},variant:"outline",size:"sm",className:"h-7 text-xs",disabled:E,children:"Cancel"})]})]})]}):e.jsxs(s.Button,{onClick:()=>r(!0),className:"w-full bg-primary hover:bg-primary/90 text-primary-foreground",disabled:E,children:[e.jsx(s.Plus,{className:"h-4 w-4 mr-2"}),E?"Creating...":"Create New Visual"]})}),S&&S.length>5&&e.jsx("div",{className:"space-y-2 px-1",children:e.jsx(s.Input$1,{id:"search",placeholder:"Search by title or description...",value:t,onChange:W=>a(W.target.value),className:"h-8"})}),e.jsx("div",{className:"mb-4 flex flex-1 flex-col",children:e.jsx("div",{className:"flex flex-1 basis-0 flex-col gap-2 overflow-y-auto p-1",children:te.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx("div",{className:"mb-3",children:e.jsx(ns,{className:"h-12 w-12 mx-auto text-muted-foreground/50"})}),e.jsx("h3",{className:"font-medium text-foreground mb-1",children:t?"No visuals found":"No visuals yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:t?"Try adjusting your search":"Create your first visual component to get started"}),!t&&e.jsxs(s.Button,{size:"sm",className:"bg-primary hover:bg-primary/90",onClick:()=>r(!0),children:[e.jsx(s.Plus,{className:"h-4 w-4 mr-2"}),"Create Visual"]})]}):te.map(W=>e.jsx(an,{visual:W,onAddVisual:se,onEditVisual:V,onUpdateVisual:Z,onDeleteClick:H,onDuplicateVisual:le,onTogglePrivacy:ne,onShareVisual:Y,isDeleting:A,isDuplicating:j===W.id,isTitleUpdating:U(W.id,"title"),isDescriptionUpdating:U(W.id,"description"),formatDate:X},W.id))})}),d&&m&&e.jsx(gt,{resource:m,resourceType:s.ResourceType.VISUAL,onShare:K,isSharing:M,isRemoving:R,isUpdating:P,onClose:()=>{u(!1),h(null)},onRemoveAccess:$}),e.jsx(s.AlertDialog,{open:f,onOpenChange:W=>{!W&&A||(g(W),W||p(null))},children:e.jsxs(s.AlertDialogContent,{children:[e.jsxs(s.AlertDialogHeader,{children:[e.jsx(s.AlertDialogTitle,{children:"Delete Visual"}),e.jsxs(s.AlertDialogDescription,{children:['Are you sure you want to delete "',b==null?void 0:b.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:A,children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:W=>{W.preventDefault(),W.stopPropagation(),_()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:A,children:A?"Deleting...":"Delete"})]})]})})]})}function Dn({dashboard:t,isDeleting:a,isDuplicating:n,isTitleUpdating:r=!1,isDescriptionUpdating:l=!1,onLoadDashboard:o,onUpdateDashboard:c,onDeleteClick:i,onDuplicateDashboard:d,onShareDashboard:u,formatDate:m,onDashboardItemClick:h}){var S,y,D;const{selectDashboard:f}=s.useManagementActions(),g=s.useIsDashboardSelected(t.id),{isConsoleMode:b}=s.useDashboardPreferences(),[p,j]=I.useState(!1),[x,v]=I.useState(!1),k=s.useDashboardStore(N=>N.actions.setIsDashboardPanelOpen);I.useEffect(()=>{n?(j(!0),v(!0)):x&&(j(!1),v(!1))},[n,x]);const L=()=>e.jsx(s.ChartColumn,{className:"h-4 w-4"}),C=()=>{f(t),o(t.id),h==null||h(t.id)};return e.jsx(s.Card,{className:s.cn("group p-3 hover:bg-accent/50 transition-colors cursor-pointer border-border/50",g&&"ring-1 ring-primary"),onClick:C,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"mt-0.5 p-1.5 rounded bg-muted",children:L()}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(s.EditableText,{inputClassName:"text-sm font-medium text-foreground",value:t.title,onSave:N=>c==null?void 0:c(t.id,{title:N}),isEditable:t.permissions.canEdit&&g,isPending:r,placeholder:"Untitled Dashboard",displayClassName:"font-medium text-sm text-foreground truncate"}),t.ownership.status==="shared"&&e.jsxs(s.Badge,{variant:"outline",className:"text-xs",children:[e.jsx(s.Users,{className:"h-2.5 w-2.5 mr-1"}),"Shared"]})]}),e.jsx(s.EditableText,{inputClassName:"text-xs text-muted-foreground line-clamp-2",value:t.description||"",onSave:N=>c==null?void 0:c(t.id,{description:N}),isEditable:t.permissions.canEdit&&g,isPending:l,placeholder:"No description",displayClassName:"text-xs text-muted-foreground line-clamp-2 mb-2"}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(s.Calendar,{className:"h-3 w-3"}),e.jsxs("span",{children:["Updated ",m(t.lastModified)]})]})]}),e.jsx("div",{className:s.cn("opacity-0 transition-opacity duration-150 group-hover:opacity-100","ml-2 flex-shrink-0"),onClick:N=>N.stopPropagation(),children:e.jsxs(s.DropdownMenu,{modal:!1,open:p,onOpenChange:j,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0",children:e.jsx(s.Ellipsis,{className:"h-3 w-3"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"z-[51] w-40",children:[e.jsxs(s.DropdownMenuItem,{onClick:N=>{N.preventDefault(),N.stopPropagation(),d(t.id)},disabled:n,children:[n?e.jsx(s.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(s.Copy,{className:"mr-2 h-3 w-3"}),n?"Duplicating...":"Duplicate"]}),t.permissions.canEdit&&e.jsx(e.Fragment,{children:e.jsxs(s.DropdownMenuItem,{onClick:N=>{N.stopPropagation(),u(t)},children:[e.jsx(s.Users,{className:"mr-2 h-3 w-3"}),"Share"]})}),t.permissions.canDelete&&e.jsxs(e.Fragment,{children:[e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:N=>{N.stopPropagation(),i(t),k(!1)},className:"text-destructive",disabled:a,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),a?"Deleting...":"Delete"]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs("div",{className:"space-y-1 px-2 py-2 text-xs text-slate-500 dark:text-slate-400",children:[(((S=t.ownership.createdBy)==null?void 0:S.type)==="tenant"||((y=t.ownership.createdBy)==null?void 0:y.type)==="organization"&&b)&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Be,{className:"h-3 w-3"}),e.jsx("span",{children:((D=t.ownership.createdBy)==null?void 0:D.name)||"Unknown"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Calendar,{className:"h-3 w-3"}),e.jsx("span",{children:m(t.lastModified)})]})]})]})]})})]})},t.id)}function kn({onRetry:t}){return e.jsx(s.ScrollArea,{className:"w-full flex-1 pr-2",children:e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx("p",{className:"text-sm text-destructive",children:"Failed to load dashboards"}),e.jsx(s.Button,{variant:"outline",size:"sm",className:"mt-2",onClick:t,children:"Retry"})]})})}function Tn(t){const[a,n]=I.useState(""),[r,l]=I.useState(!1),[o,c]=I.useState(""),[i,d]=I.useState(""),[u,m]=I.useState(!1),[h,f]=I.useState(null),[g,b]=I.useState(!1),[p,j]=I.useState(null),[x,v]=I.useState(null),k=s.useManagementStore(Q=>Q.lastSelectedDashboard),L=s.useManagementStore(Q=>Q.selectedDashboard),C=s.useManagementStore(Q=>Q.actions.selectDashboard),S=s.useManagementStore(Q=>Q.actions.clearSelectedDashboard);s.useShareManagementActions(),s.useShareUsersToRemove(),s.useShareSelectedTab(),s.useShareCurrentMode();const{tokenProps:y,id:D}=s.useSemaphorContext(),{permissions:N}=s.useRoleAwareDisplayPreferences(),{resources:B,isLoading:w,isError:F,createResource:T,updateResource:E,deleteResource:A,duplicateResource:O,isCreating:M,isDeleting:R,isSharing:P,isRemovingShares:K,isUpdatingShares:$,shareResource:te,removeResourceShares:X}=s.useDashboardManagement(()=>{b(!1);const Q=p==null?void 0:p.id;j(null),(L==null?void 0:L.id)===Q&&(!(y!=null&&y.dashboard_id)&&!D?S():k&&k.id!==Q&&C(k))},()=>{l(!1),c(""),d("")}),{handleShareSubmit:q,handleRemoveAccess:H}=bn((h==null?void 0:h.id)||null,te,X),{currentUser:_}=s.useCurrentUserInfo(),J=B.filter(Q=>{var oe,ee;return((oe=Q==null?void 0:Q.title)==null?void 0:oe.toLowerCase().includes(a.toLowerCase()))||((ee=Q==null?void 0:Q.description)==null?void 0:ee.toLowerCase().includes(a.toLowerCase()))}),z=Q=>new Date(Q).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),U=()=>{o.trim()&&T({title:o,description:i,isPrivate:!1})},Z=Q=>{var oe;(oe=t.onLoadDashboard)==null||oe.call(t,Q)},le=Q=>{j(Q),b(!0)},V=()=>{p&&A(p.id)},se=Q=>{v(Q),O(Q,{onSettled:()=>v(null)})},{startUpdating:ne,stopUpdating:Y,isUpdating:W}=s.useResourceUpdateState(),re=(Q,oe)=>{const ee=oe.title!==void 0?"title":"description";ne(Q,ee),E({resourceId:Q,data:oe},{onSuccess:()=>{Y(Q,ee)},onError:()=>{Y(Q,ee)}})},ie=Q=>{const oe=B.find(ee=>ee.id===Q);oe&&E({resourceId:Q,data:{isPrivate:!oe.isPrivate}})},he=Q=>{f(Q),_==null||_.type,m(!0)};return De({debouncedSearchQuery:"",resourceId:(h==null?void 0:h.id)||"",resourceType:s.ResourceType.DASHBOARD,userType:"tenant"}),w?e.jsx(lt,{}):F?e.jsx(kn,{onRetry:()=>window.location.reload()}):e.jsxs("div",{className:"mt-1 flex h-full flex-1 flex-col gap-3 px-4",children:[N.canCreateDashboards&&e.jsx("div",{className:"px-1",children:r?e.jsxs(s.Card,{className:"border-dashed p-4 pb-2",children:[e.jsx(s.CardHeader,{className:"px-0 pb-3 pt-0",children:e.jsx(s.CardTitle,{className:"text-sm",children:"New Dashboard"})}),e.jsxs(s.CardContent,{className:"space-y-3 px-0 pb-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"title",className:"text-xs",children:"Title"}),e.jsx(s.Input$1,{id:"title",placeholder:"Enter dashboard title...",value:o,onChange:Q=>c(Q.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"description",className:"text-xs",children:"Description (optional)"}),e.jsx(s.Input$1,{id:"description",placeholder:"Enter dashboard description...",value:i,onChange:Q=>d(Q.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(s.Button,{onClick:U,size:"sm",className:"h-7 text-xs",disabled:!o.trim()||M,children:M?"Creating...":"Create"}),e.jsx(s.Button,{onClick:()=>{l(!1),c(""),d("")},variant:"outline",size:"sm",className:"h-7 text-xs",disabled:M,children:"Cancel"})]})]})]}):e.jsxs(s.Button,{onClick:()=>l(!0),className:"w-full bg-primary hover:bg-primary/90 text-primary-foreground",disabled:M,children:[e.jsx(s.Plus,{className:"h-4 w-4 mr-2"}),M?"Creating...":"Create New Dashboard"]})}),B&&B.length>5&&e.jsx("div",{className:"space-y-2 px-1",children:e.jsx(s.Input$1,{id:"search",placeholder:"Search by title or description...",value:a,onChange:Q=>n(Q.target.value),className:"h-8"})}),e.jsx("div",{className:"mb-4 flex flex-1 flex-col",children:e.jsx("div",{className:"flex flex-1 basis-0 flex-col gap-2 overflow-y-auto p-1",children:J.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx("div",{className:"mb-3",children:e.jsx(s.ChartColumn,{className:"h-12 w-12 mx-auto text-muted-foreground/50"})}),e.jsx("h3",{className:"font-medium text-foreground mb-1",children:a?"No dashboards found":"No dashboards yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:a?"Try adjusting your search":N.canCreateDashboards?"Create your first dashboard to get started":"No dashboards have been shared with you yet"}),N.canCreateDashboards&&!a&&e.jsxs(s.Button,{size:"sm",className:"bg-primary hover:bg-primary/90",onClick:()=>l(!0),children:[e.jsx(s.Plus,{className:"h-4 w-4 mr-2"}),"Create Dashboard"]})]}):J.map(Q=>e.jsx(Dn,{dashboard:Q,isDeleting:R,isDuplicating:x===Q.id,isTitleUpdating:W(Q.id,"title"),isDescriptionUpdating:W(Q.id,"description"),onLoadDashboard:Z,onEditDashboard:t.onEditDashboard,onUpdateDashboard:re,onDeleteClick:le,onDuplicateDashboard:se,onTogglePrivacy:ie,onShareDashboard:he,formatDate:z,onDashboardItemClick:t.onDashboardItemClick},Q.id))})}),u&&h&&e.jsx(gt,{resource:h,resourceType:s.ResourceType.DASHBOARD,onShare:q,isSharing:P,isRemoving:K,isUpdating:$,onClose:()=>{m(!1),f(null)},onRemoveAccess:H}),e.jsx(s.AlertDialog,{open:g,onOpenChange:Q=>{!Q&&R||(b(Q),Q||j(null))},children:e.jsxs(s.AlertDialogContent,{children:[e.jsxs(s.AlertDialogHeader,{children:[e.jsx(s.AlertDialogTitle,{children:"Delete Dashboard"}),e.jsxs(s.AlertDialogDescription,{children:['Are you sure you want to delete "',p==null?void 0:p.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:R,children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:Q=>{Q.preventDefault(),Q.stopPropagation(),V()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:R,children:R?"Deleting...":"Delete"})]})]})})]})}function yt({isOpen:t,onClose:a,className:n,onDashboardItemClick:r}){s.useDashboardStore(j=>j.dashboard);const{setDashboard:l,addSheet:o}=s.useDashboardStore(j=>j.actions),{currentUser:c}=s.useCurrentUserInfo(),i=c,{permissions:d}=s.useRoleAwareDisplayPreferences(),u=(d.canAccessVisuals,"dashboards"),[m,h]=s.useLocalStorageState("resource-management-active-tab",u),f=d.canAccessVisuals?m:"dashboards",g=ut(a,{enabled:t}),b=j=>{},p=j=>{console.log("Editing dashboard:",j)};return e.jsx(s.TooltipProvider$1,{children:e.jsxs("div",{ref:g,className:s.cn("absolute inset-y-0 left-0 z-[51] flex w-96 flex-col border-r bg-background shadow-lg transition-transform duration-300 ease-in-out",t?"translate-x-0":"hidden -translate-x-full",n),children:[e.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-border",children:[e.jsx("div",{className:"flex items-center gap-2",children:i&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"h-8 w-8 rounded-full bg-primary/10 flex items-center justify-center",children:e.jsx("span",{className:"text-sm font-medium text-primary",children:i.name.charAt(0).toUpperCase()})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-foreground",children:i.name}),e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Badge,{variant:d.canCreateDashboards?"default":"secondary",className:"text-xs cursor-help",children:d.canCreateDashboards?e.jsxs(e.Fragment,{children:[e.jsx(s.Users,{className:"h-3 w-3 mr-1"}),"Power User"]}):e.jsxs(e.Fragment,{children:[e.jsx(s.Eye,{className:"h-3 w-3 mr-1"}),"Viewer"]})})}),e.jsx(s.TooltipContent,{side:"bottom",className:"max-w-xs",children:e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"font-medium",children:i.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:i.email}),i.role&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Role: ",s.toTitleCase(i.role.replace(/_/g," "))]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["ID: ",i.id]})]})})]})})]})]})}),e.jsx(s.IconButton,{className:"h-8 w-8 p-0 text-muted-foreground hover:text-foreground",onClick:a,tooltip:"Close panel",children:e.jsx(s.X,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"flex flex-1 flex-col overflow-hidden",children:e.jsxs(s.Tabs,{value:f,onValueChange:d.canAccessVisuals?h:void 0,className:"flex h-9 grow flex-col",children:[d.canAccessVisuals?e.jsx("div",{className:"px-4 pt-4",children:e.jsxs(s.TabsList,{className:"grid w-full grid-cols-2",children:[e.jsx(s.TabsTrigger,{value:"dashboards",className:"text-sm",children:"Dashboards"}),e.jsx(s.TabsTrigger,{value:"visuals",className:"text-sm",children:"Visuals"})]})}):e.jsx("div",{className:"px-4 pt-4 pb-0",children:e.jsx("h2",{className:"text-lg font-semibold text-foreground",children:"Dashboards"})}),e.jsx(s.TabsContent,{value:"dashboards",className:"flex-1 mt-4",children:e.jsx(Tn,{onLoadDashboard:b,onEditDashboard:p,onDashboardItemClick:r})}),d.canAccessVisuals&&e.jsx(s.TabsContent,{value:"visuals",className:"flex-1 mt-4",children:e.jsx(wn,{})})]})})]})})}function En(){var se,ne;const{authToken:t,tokenProps:a,id:n}=s.useSemaphorContext(),{isLocalDev:r}=s.useDashboardPreferences(),{permissions:l}=s.useRoleAwareDisplayPreferences(),o=s.useHasDashboardId();s.useDashboardStore(Y=>Y.theme);const c=s.useDashboardStore(Y=>Y.lenses),i=s.useDashboardStore(Y=>Y.selectedLensId),d=c==null?void 0:c.find(Y=>Y.id===i),u=s.useDashboardStore(Y=>Y.dashboard);s.useDashboardStore(Y=>Y.selectedSheetId);const m=s.useDashboardStore(Y=>Y.isDashboardEditing),h=s.useEditorStore(Y=>Y.card),f=s.useEditorStore(Y=>Y.selectedConnectionId),[g,b]=I.useState(!1),p=s.useDashboardStore(Y=>Y.isDashboardPanelOpen),j=s.useDashboardStore(Y=>Y.actions.setIsDashboardPanelOpen),x=s.useDashboardStore(Y=>Y.filterValues),v=s.useDashboardStore(Y=>Y.isVisualEditing),k=s.useManagementStore(Y=>Y.selectedDashboard),L=s.useManagementStore(Y=>Y.initialDashboard),C=k?(ne=k==null?void 0:k.permissions)==null?void 0:ne.canEdit:(se=L==null?void 0:L.permissions)==null?void 0:se.canEdit,S=s.useDashboardStore(Y=>Y.showFilters),y=s.useDashboardStore(Y=>Y.showDashboardJSON),D=s.useDashboardStore(Y=>Y.onSaveFunction),N=s.useDashboardStore(Y=>Y.actions.setShowFilters),{addFrame:B,setSelectedFrameId:w}=s.useDashboardStore(Y=>Y.actions),{getSelectedSheet:F,setIsDashboardEditing:T,setShowDashboardJSON:E}=s.useDashboardStore(Y=>Y.actions),A=F(),{setInitialDashboard:O,clearSelectedDashboard:M}=s.useManagementStore(Y=>Y.actions),{resources:R}=s.useResourceManagement(s.ResourceType.DASHBOARD);I.useEffect(()=>{if(R&&R.length>0){const Y=u==null?void 0:u.id;if(Y){const W=R.find(re=>re.id===Y);W&&O(W)}}},[R,u==null?void 0:u.id,O]);const P=a.orgUserId||a.tenantId,K=m&&!v&&P&&C;function $(){var ie,he;const Y=h.dataSource;if(Y)return Y;const W=(he=(ie=u.aiContext)==null?void 0:ie.selectedEntities)==null?void 0:he[0],re=W==null?void 0:W.type;if(W)return{connectionId:W.connectionId,connectionType:W.connectionType,type:re,selectedEntities:[W]}}const te=()=>{if(!m||!A)return;const W={dataSource:$(),mode:"explorer",connectionId:f,id:s.v4(),title:"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[]},re={id:s.v4(),cards:[W],activeCardId:W.id};B(A.id,re),w(re.id)},X=()=>{T(!0)},[q,H]=I.useState(!1),_=s.useUpdateResource(s.ResourceType.DASHBOARD);async function J(){const Y=es(u);H(!0);const W={template:Y};_.mutate({resourceId:Y.id,data:W},{onSuccess:()=>{H(!1),s.ue.success("Dashboard saved!")},onError:()=>{H(!1),s.ue.error("Failed to save dashboard")}})}async function z(){if(b(!0),!i||!d)return;const Y=es(u),W=JSON.stringify(Y),re={...d,template:W,filterValues:x};await js(re,t==null?void 0:t.accessToken),s.ue.success("Lens saved"),D==null||D(Y),b(!1)}if(v)return null;const U=(d==null?void 0:d.name)||u.title,le=R&&R.length>0&&(a.orgUserId||a.tenantId&&a.endUserId&&a.endUserEmail),V=k&&!(a!=null&&a.dashboard_id)&&!n;return e.jsxs("div",{className:"flex h-10 items-center justify-between gap-2 border-b py-2 pl-3 pr-2",role:"dashboard-controls",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[le&&e.jsxs(e.Fragment,{children:[V&&e.jsx(s.IconButton,{"aria-label":"Dashboard Hub",tooltip:"Back to Dashboard Hub",onClick:()=>M(),className:"h-7 p-2",children:e.jsx(s.House,{className:"h-4 w-4"})}),e.jsx(s.IconButton,{"aria-label":"Manage Dashboards",tooltip:o?"Manage Dashboards":"Select a dashboard to continue",onClick:()=>j(!0),className:"h-7 p-2",buttonProps:{disabled:!o},children:e.jsx(Ia,{className:"h-4 w-4"})})]}),!v&&o&&e.jsx(s.Label,{children:U})]}),e.jsxs("div",{className:"flex gap-2",children:[r&&e.jsx(s.IconButton,{tooltip:"Invalidate Token",onClick:s.invalidateToken,className:"h-7 p-2",children:e.jsx(_a,{className:"h-4 w-4"})}),!v&&o&&e.jsx(sn,{}),!v&&o&&e.jsx(rt,{}),m&&!v&&P&&r&&o&&e.jsx(Za,{}),!v&&P&&r&&o&&e.jsx(en,{}),m&&!v&&P&&d&&r&&o&&e.jsxs(s.Button,{className:"h-7 p-2",variant:"secondary",disabled:g,onClick:z,size:"sm",children:[e.jsx(gs,{className:"mr-2 h-4 w-4"}),"Save Lens"]}),m&&!v&&o&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",size:"sm",disabled:!m,onClick:te,children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Frame"]}),!v&&!m&&l.canEdit&&o&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",onClick:X,size:"sm",children:[e.jsx(s.Pencil,{className:"mr-2 h-4 w-4"}),"Edit"]}),m&&!v&&o&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",onClick:()=>{T(!1),E(!1)},children:[e.jsx(s.Cross2Icon,{className:"mr-2 h-4 w-4"}),"Close"]}),K&&o&&e.jsxs(s.Button,{className:"h-7 p-2",variant:"outline",disabled:q,onClick:J,size:"sm",children:[q?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(gs,{className:"mr-2 h-4 w-4"}),q?"Saving...":"Save"]}),!S&&!v&&m&&l.canUseFilters&&o&&e.jsx(s.Button,{className:"h-7 p-2",variant:"outline",onClick:()=>N(!0),size:"sm",children:e.jsx(s.Filter,{className:"h-4 w-4"})}),!v&&m&&r&&o&&e.jsx("div",{className:"flex items-center space-x-2",children:e.jsx(s.Button,{className:"h-7 p-2",onClick:()=>E(!y),size:"sm",variant:"ghost",children:e.jsx(Oe,{className:"h-4 w-4"})})}),!v&&r&&e.jsx(Ka,{}),!v&&e.jsx(yt,{isOpen:p,onClose:()=>j(!1)})]})]})}function In({name:t,items:a,value:n,onChange:r,isLoading:l,isError:o,refetch:c,className:i,icon:d,showNone:u=!1}){const m=ke.useRef(null),[h,f]=ke.useState(!1),[g,b]=ke.useState("100%"),p=u?[...a||[],{id:"none",name:"None"}]:a;ke.useLayoutEffect(()=>{m.current&&b(m.current.offsetWidth)},[]);function j(){var v;return l?"Loading...":o?"Error":n?(v=a==null?void 0:a.find(k=>k.id===n))==null?void 0:v.name:`Select ${t}`}function x(v,k){r(k),f(!1)}return e.jsxs(s.Popover,{open:h,onOpenChange:f,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{ref:m,variant:"outline",role:"combobox","aria-expanded":h,className:s.cn("flex h-9 w-full justify-between",i),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[d&&e.jsx("div",{className:"mr-2",children:d}),e.jsx("span",{className:"max-w-[150px] overflow-hidden truncate text-ellipsis whitespace-nowrap",children:j()})]}),e.jsx(s.ChevronDown,{className:"size-4 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-full p-0",style:{minWidth:g},children:e.jsxs(s.Command,{children:[e.jsxs("div",{className:"flex h-9 items-center justify-between border-b pr-1",children:[e.jsx(s.CommandInput,{className:"h-9",placeholder:"Search..."}),e.jsx(s.IconButton,{className:"h-7",onClick:c,children:e.jsx(st,{className:s.cn("size-3.5 opacity-50",l&&"animate-spin")})})]}),e.jsxs(s.CommandList,{children:[e.jsxs(s.CommandEmpty,{children:["No ",t==null?void 0:t.toLowerCase()," found."]}),e.jsx(s.CommandGroup,{children:p==null?void 0:p.map(v=>e.jsx(s.CommandItem,{className:"overflow-x-auto",value:v.name,onSelect:k=>x(k,v.id),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Check,{className:s.cn("size-4",n===v.id?"opacity-100":"opacity-0")}),e.jsx("div",{title:v.name,children:v.name})]})},v.id))})]})]})})]})}function Re({title:t,items:a,value:n,isLoading:r,isError:l,refetch:o,onChange:c,showNone:i=!1,className:d,disabled:u=!1,type:m="combobox"}){const h=r?"Loading...":l?"Error":n;function f(){if(t==="Connection")return e.jsx(Pa,{className:"size-4"});if(t==="Database")return e.jsx(s.Database,{className:"size-4"});if(t==="Schema")return e.jsx(Oa,{className:"size-4"});if(t==="Table")return e.jsx(s.Table2,{className:"size-4"});if(t==="Model")return e.jsx(ca,{className:"size-4"})}function g(){return e.jsxs(s.Select,{disabled:u,value:h,onValueChange:c,children:[e.jsx(s.SelectTrigger,{className:s.cn("h-9 w-full border-muted focus:ring-1 focus:ring-offset-0",d),children:e.jsx(s.SelectValue,{placeholder:r?"Loading...":l?"Error":`Select ${t}`})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[r?e.jsx(s.SelectLabel,{children:"Loading..."}):e.jsxs(s.SelectLabel,{className:"flex items-center justify-between gap-2",children:[t,e.jsx(st,{className:s.cn("mr-1 size-3 cursor-pointer text-muted-foreground hover:text-foreground",r&&"animate-spin"),onClick:o})]}),e.jsxs(e.Fragment,{children:[i&&e.jsx(s.SelectItem,{value:"none",children:"None"},"none"),a&&a.map((p,j)=>e.jsx(s.SelectItem,{value:p.id,children:p.name},j))]}),(r||l)&&e.jsx(s.SelectItem,{value:h,children:h})]})})]})}function b(){return e.jsx(In,{icon:f(),items:a,value:h,onChange:c||(()=>{}),isLoading:r,isError:l,refetch:o,name:t,showNone:i})}return e.jsx(s.TooltipProvider$1,{delayDuration:0,children:e.jsx("div",{className:"flex items-center gap-2",children:m==="select"?g():b()})})}function An({column:t}){const[a,n]=I.useState(!1),r=s.useEditorStore(p=>p.selectedTableName),l=s.useEditorStore(p=>p.selectedSchemaName),o=s.useEditorStore(p=>p.selectedDatabaseName),c=s.useEditorStore(p=>p.selectedDatamodelId),i=s.useEditorStore(p=>p.sqlGen),{modelItems:d,connectionType:u}=s.useEditorAside(),m=s.useEditorStore(p=>p.actions.setSqlGen),h=s.useEditorStore(p=>p.actions.setCardSql),f=s.useEditorStore(p=>p.actions.setRunSql);function g(p,j){var L;const x=s.createSqlGenConfig(p,i,j),v=(L=d==null?void 0:d.find(C=>C.id===c))==null?void 0:L.name;m(x);const k=s.getSql(x,s.fmt(l||""),s.fmt(r),v||"",u,o||"");k&&(h(k),f(!0)),n(!1)}function b(){return e.jsxs("ul",{className:"text-xs",children:[e.jsx("li",{onClick:()=>g(t,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),e.jsx("li",{onClick:()=>g(t,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),e.jsx("li",{onClick:()=>g(t,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),e.jsx("li",{onClick:()=>g(t,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),e.jsx("li",{onClick:()=>g(t,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return e.jsxs(s.HoverCard,{openDelay:0,open:a,onOpenChange:n,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.EllipsisVertical,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover:visible"})}),e.jsx(s.HoverCardContent,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:b()})]})}function Mn({dataType:t}){const a=s.getDataType(t);return a==="string"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(ge,{className:"h-3 w-3"})}):a==="number"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(Ne,{className:"h-3 w-3"})}):a==="date"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):a==="boolean"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Me,{className:"h-3 w-3"})}):a==="json"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Oe,{className:"h-3 w-3"})}):a==="geo"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(_e,{className:"h-3 w-3"})}):a==="calculated"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(qe,{className:"h-3 w-3"})}):e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(ge,{className:"h-3 w-3"})})}function is({column:t,className:a}){return e.jsxs("div",{className:s.cn("flex min-h-8 grow items-center gap-2 px-3 py-[6px] text-sm",a),children:[e.jsx(Mn,{dataType:t.data_type}),e.jsx("span",{children:t.column_name})]})}function Ln({id:t,children:a,type:n="column"}){const{attributes:r,listeners:l,setNodeRef:o,transform:c}=s.useDraggable({id:t,data:{type:n}}),i=c?{translate:s.CSS.Translate.toString(c),transform:s.CSS.Transform.toString(c)}:void 0;return e.jsx("div",{ref:o,style:i,...l,...r,children:a})}function Rn({onClick:t,column:a}){const n=s.useDndStore(m=>m.activeId),r=s.useEditorStore(m=>{var h;return(h=m.card.queryConfig)==null?void 0:h.groupByColumns}),l=s.useEditorStore(m=>{var h;return(h=m.card.queryConfig)==null?void 0:h.metricColumns}),o=s.useEditorStore(m=>{var h;return(h=m.card.queryConfig)==null?void 0:h.filterColumns});function c(m){return i(m)||d(m)||u(m)}function i(m){return r==null?void 0:r.some(h=>h.name===m.column_name)}function d(m){return l==null?void 0:l.some(h=>h.name===m.column_name)}function u(m){return o==null?void 0:o.some(h=>h.name===m.column_name)}return e.jsxs("div",{onClick:()=>t(a),className:s.cn("group relative grow cursor-pointer overflow-x-hidden overflow-y-hidden border border-dashed border-background transition-colors hover:bg-muted/50",{"bg-muted":c(a)}),children:[n===a.column_name&&e.jsx(s.DragOverlay,{children:e.jsx(is,{column:a,className:"rounded-md border-2 border-dashed border-muted-foreground bg-muted shadow-md"})}),n===a.column_name&&e.jsx("div",{className:"absolute inset-0",children:n===a.column_name&&e.jsx(is,{column:a})}),e.jsx(Ln,{id:a.column_name,type:"column",children:e.jsx(is,{column:a})})]})}const cs={id:"__placeholder__",role:"groupby",type:"string"},ds={id:"__placeholder__",role:"groupby",type:"string"},us={id:"__placeholder__",role:"metric",type:"number"},ms={name:"Filter",id:"__placeholder__",role:"filter",type:"string"},vt={id:"__placeholder__"},Ee="droppable-group-by",Ie="droppable-metrics",Ae="droppable-pivot-by",ts="sortable-group-by",bs="sortable-metrics",as="sortable-pivot-by",ys="droppable-filters",vs="sortable-filters",Ss="sortable-order-by";function On(){const t=s.useDndStore(E=>E.insertIndex),a=s.useEditorStore(E=>{var A;return((A=E.card.queryConfig)==null?void 0:A.groupByColumns)||[]}),n=s.useEditorStore(E=>{var A;return((A=E.card.queryConfig)==null?void 0:A.metricColumns)||[]}),r=s.useEditorStore(E=>{var A;return((A=E.card.queryConfig)==null?void 0:A.filterColumns)||[]}),l=s.useEditorStore(E=>{var A;return((A=E.card.queryConfig)==null?void 0:A.orderBy)||[]}),o=s.useEditorStore(E=>{var A;return((A=E.card.queryConfig)==null?void 0:A.pivotColumns)||[]}),{setInsertIndex:c,setActiveId:i,setPreviewGroupByColumns:d,setPreviewMetricColumns:u,setPreviewFilterColumns:m,setPreviewPivotColumns:h}=s.useDndActions(),{setGroupByColumns:f,setMetricColumns:g,setFilterColumns:b,setOrderByColumns:p,setPivotByColumns:j}=s.useEditorActions(),{columns:x}=s.useDataColumns(),{formattedTableName:v}=s.useEditorAside(),k=s.useSensors(s.useSensor(s.MouseSensor,{activationConstraint:{distance:1}})),L=E=>{var M;const{active:A,over:O}=E;if(((M=A.data.current)==null?void 0:M.type)==="column"&&O){const R=O.id,P=x.find(X=>X.column_name===A.id);if(!P)return;const K=s.isNumberDataType(P.data_type),$=s.isTextDataType(P.data_type),te=s.isDateDataType(P.data_type);if($||te){if(a.some(q=>q.id===R)){const q=a.findIndex(_=>_.id===R);c(q);const H=a.filter(_=>_.id!==cs.id);H.splice(q,0,cs),d(H)}else if(O.id===Ee){c(a.length);const q=[...a,cs];d(q),u(n),m(r)}}if($||te){if(o.some(q=>q.id===R)){const q=o.findIndex(_=>_.id===R);c(q);const H=o.filter(_=>_.id!==ds.id);H.splice(q,0,ds),h(H)}else if(O.id===Ae){c(o.length);const q=[...o,ds];h(q),d(a),u(n),m(r)}}if(K||$){if(n.some(q=>q.id===R)){console.log("isOverMetricSortable",R);const q=n.findIndex(_=>_.id===R);c(q);const H=n.filter(_=>_.id!==us.id);H.splice(q,0,us),u(H)}else if(O.id===Ie){c(n.length);const q=[...n,us];u(q),m(r),d(a),h(o)}}if(S(P)){if(r.some(q=>q.id===R)){const q=r.findIndex(_=>_.id===R);c(q);const H=r.filter(_=>_.id!==ms.id);H.splice(q,0,ms),m(H)}else if(O.id===ys){c(r.length);const q=[...r,ms];m(q),u(n),d(a),h(o)}}}else d(a),u(n),m(r),h(o)};function C(E){i(E.active.id),c(null),d(a),u(n),m(r),h(o)}function S(E){return!r.some(A=>A.name===E.column_name)}function y(E,A="SUM"){const{column_name:O,data_type:M}=E,R=[...n],P=t!==null?t:n.length,K={...E,id:ye(O),name:O,label:Ye(O,A),type:M,role:"metric",aggregate:A};R.splice(P,0,K),g(R)}function D(E){const A=s.isTextDataType(E.data_type);s.isDateDataType(E.data_type);const O=[...o],M=t!==null?t:o.length;let R;A?R={...E,id:ye(E.column_name),name:E.column_name,type:E.data_type,role:"groupby"}:R={...E,id:ye(E.column_name),name:E.column_name,type:E.data_type,role:"groupby",label:Fe(E.column_name,"month"),granularity:"month"},O.splice(M,0,R),j(O)}function N(E){const A=s.isTextDataType(E.data_type);s.isDateDataType(E.data_type);const O=[...a],M=t!==null?t:a.length;let R;A?R={...E,id:ye(E.column_name),name:E.column_name,type:E.data_type,role:"groupby"}:R={...E,id:ye(E.column_name),name:E.column_name,type:E.data_type,role:"groupby",label:Fe(E.column_name,"month"),granularity:"month"},O.splice(M,0,R),f(O)}function B(E){const A=[...r],O=t!==null?t:r.length,M={...E,id:ye(E.column_name),name:E.column_name,type:E.data_type,sql:s.getDefaultFilterSql(E.data_type,v,s.fmt(E.column_name)),role:"filter"};A.splice(O,0,M),b(A)}function w(E){var R,P,K,$,te,X,q,H;const{active:A,over:O}=E,M=A.data.current;if((M==null?void 0:M.type)==="column"&&O){const _=x.find(Z=>Z.column_name===A.id);if(!_)return;const J=s.isNumberDataType(_.data_type),z=s.isTextDataType(_.data_type),U=s.isDateDataType(_.data_type);(z||U)&&(O.id===Ee||((R=O.data.current)==null?void 0:R.type)===ts)&&N(_),(z||U)&&(O.id===Ae||((P=O.data.current)==null?void 0:P.type)===as)?D(_):(J||z)&&(O.id===Ie||((K=O.data.current)==null?void 0:K.type)===bs)?(J&&y(_),z&&y(_,"COUNT")):S(_)&&(O.id===ys||(($=O.data.current)==null?void 0:$.type)===vs)&&B(_)}if(O&&((te=O.data.current)==null?void 0:te.type)===ts&&a.some(_=>_.id===A.id)){const _=a.findIndex(z=>z.id===A.id),J=a.findIndex(z=>z.id===O.id);if(_!==-1&&J!==-1&&_!==J){const z=[...a],[U]=z.splice(_,1);z.splice(J,0,U),f(z)}}if(O&&((X=O.data.current)==null?void 0:X.type)===as&&o.some(_=>_.id===A.id)){const _=o.findIndex(z=>z.id===A.id),J=o.findIndex(z=>z.id===O.id);if(_!==-1&&J!==-1&&_!==J){const z=[...o],[U]=z.splice(_,1);z.splice(J,0,U),j(z)}}if(O&&((q=O.data.current)==null?void 0:q.type)===bs&&n.some(_=>_.id===A.id)){const _=n.findIndex(z=>z.id===A.id),J=n.findIndex(z=>z.id===O.id);if(_!==-1&&J!==-1&&_!==J){const z=[...n],[U]=z.splice(_,1);z.splice(J,0,U),g(z)}}if(O&&((H=O.data.current)==null?void 0:H.type)===vs&&r.some(_=>_.id===A.id)){const _=r.findIndex(z=>z.id===A.id),J=r.findIndex(z=>z.id===O.id);if(_!==-1&&J!==-1&&_!==J){const z=[...r],[U]=z.splice(_,1);z.splice(J,0,U),b(z)}}F(E),i(null),c(null),d(a),u(n),m(r),h(o)}function F(E){const{active:A,over:O}=E,M=A.data.current;if((M==null?void 0:M.type)===Ss&&O){const R=l.findIndex(K=>Ve(K.columnId)===A.id),P=l.findIndex(K=>Ve(K.columnId)===O.id);if(R!==-1&&P!==-1&&R!==P){const K=[...l],[$]=K.splice(R,1);K.splice(P,0,$),p(K)}}}function T(){i(null),c(null),d(a),u(n),m(r)}return{handleDragOver:L,handleDragEnd:w,handleDragStart:C,handleDragCancel:T,sensors:k}}function ye(t){return`${t}-${s.v4()}`}function Ye(t,a){const n=s.toTitleCase(t.replace(/_/g," "));switch(a){case"SUM":return`Sum of ${n}`;case"COUNT":return`Count of ${n}`;case"DISTINCT":return`Unique ${n}`;case"AVG":return`Average of ${n}`;case"MIN":return`Min of ${n}`;case"MAX":return`Max of ${n}`;default:return n}}function Ve(t){return`${Ss}-${t}`}function Fe(t,a){const n=s.toTitleCase(t.replace(/_/g," "));switch(a){case"day":return`Date of ${n}`;case"week":return`Week of ${n}`;case"month":return`Month of ${n}`;case"year":return`Year of ${n}`;default:return n}}function Bn({dataType:t}){const a=s.getDataType(t);return a==="string"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(ge,{className:"h-3 w-3"})}):a==="number"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(Ne,{className:"h-3 w-3"})}):a==="date"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):a==="boolean"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Me,{className:"h-3 w-3"})}):a==="json"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Oe,{className:"h-3 w-3"})}):a==="geo"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(_e,{className:"h-3 w-3"})}):a==="calculated"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(qe,{className:"h-3 w-3"})}):e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(ge,{className:"h-3 w-3"})})}function Fn({schemaName:t,tableName:a,columns:n,status:r}){const[l,o]=I.useState(""),[c,i]=I.useState("all"),d=s.useEditorStore(R=>R.sqlGen),u=s.useEditorStore(R=>R.isDevMode);s.useEditorStore(R=>R.selectedConnectionId);const m=s.useEditorStore(R=>{var P,K;return(K=(P=R.card)==null?void 0:P.queryConfig)==null?void 0:K.metricColumns});s.useEditorStore(R=>{var P,K;return(K=(P=R.card)==null?void 0:P.queryConfig)==null?void 0:K.groupByColumns});const h=s.useEditorStore(R=>R.selectedDatabaseName);s.useEditorStore(R=>R.selectedSchemaName),s.useEditorStore(R=>R.selectedTableName);const f=s.useEditorStore(R=>R.selectedDatamodelId);s.useDashboardStore(R=>R.dashboard.aiScopeTables);const{addToAIScope:g,removeFromAIScope:b}=s.useDashboardActions(),{addColumnToMetricColumns:p,addColumnToGroupBy:j,setCardSql:x,setRunSql:v,setSqlGen:k,setIsShowingVisual:L}=s.useEditorActions(),{connectionType:C,modelItems:S,selectedDatamodelName:y}=s.useEditorAside();function D(R){var P;if(u){const K=s.createSqlGenConfig(R,d);k(K);const $=(P=S==null?void 0:S.find(X=>X.id===f))==null?void 0:P.name,te=s.getSql(K,s.fmt(t),s.fmt(a),$||"",C,h||"");te&&(x(te),v(!0))}if(!u){if(s.isTextDataType(R.data_type))if(m&&m.length>0){const K={...R,role:"groupby",id:ye(R.column_name),name:R.column_name,type:R.data_type};j(K)}else{const K={...R,role:"metric",id:ye(R.column_name),name:R.column_name,label:Ye(R.column_name,"COUNT"),type:R.data_type,aggregate:"COUNT"};p(K)}if(s.isDateDataType(R.data_type)){const K={...R,role:"groupby",id:ye(R.column_name),name:R.column_name,type:R.data_type,label:Fe(R.column_name,"month"),granularity:"month"};j(K)}if(s.isNumberDataType(R.data_type)){const K={...R,role:"metric",id:ye(R.column_name),name:R.column_name,label:Ye(R.column_name,"SUM"),type:R.data_type,aggregate:"SUM"};p(K)}}}function N(){const R=s.getFormattedTableNameForQuery({schemaName:t,tableName:a,modelName:y,connectionType:C,databaseName:h||""});L(!1);const P=C==="MSSQL"?`SELECT top 10 * FROM ${R}`:`SELECT * FROM ${R} LIMIT 10`;x(P),v(!0)}function B(){const R=s.getFormattedTableNameForQuery({schemaName:t,tableName:a,modelName:y,connectionType:C,databaseName:h||""});x(`SELECT COUNT(*) as count FROM ${R}`),v(!0)}const w=(n==null?void 0:n.filter(R=>R.column_name.toLowerCase().includes(l.toLowerCase())))||[],F=R=>s.isNumberDataType(R.data_type)?"number":"text",T=c==="all"?w:w.filter(R=>F(R)===c),E=w.filter(R=>F(R)==="text").length,A=w.filter(R=>F(R)==="number").length;function O(R){return u?e.jsxs("div",{className:"group flex cursor-pointer items-center justify-between border border-dashed border-background px-2 py-[6px] text-sm transition-colors hover:bg-muted/50",onClick:()=>D(R),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Bn,{dataType:R.data_type}),e.jsx("span",{children:R.column_name})]}),e.jsx("div",{onClick:P=>P.stopPropagation(),className:"flex items-center justify-end",children:s.isNumberDataType(R.data_type)&&e.jsx(An,{column:R})})]}):e.jsx(Rn,{onClick:D,column:R})}function M(){return e.jsxs("div",{className:"flex grow gap-2",children:[e.jsxs(s.Button,{disabled:r!=="Success",onClick:N,size:"sm",variant:"secondary",className:"grow",children:[r!=="Success"?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(Ea,{className:"mr-2 size-4"}),"Top 10"]}),e.jsxs(s.Button,{disabled:r!=="Success",onClick:B,size:"sm",variant:"secondary",className:"grow",children:[r!=="Success"?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(tt,{className:"mr-2 size-4"}),"Count"]})]})}return r!=="Success"?e.jsx("div",{className:"flex grow flex-col justify-start gap-2 px-4",children:Array.from({length:3}).map((R,P)=>e.jsx(s.Skeleton,{className:"h-8 w-full"},P))}):e.jsxs("div",{className:"flex grow flex-col",children:[e.jsxs("div",{className:"flex-shrink-0 space-y-3 px-4",children:[u&&e.jsx("div",{className:"flex items-center justify-center gap-2",children:M()}),n&&n.length>0&&e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 transform text-muted-foreground"}),e.jsx(s.Input$1,{className:"pl-10",type:"text",placeholder:"Search fields...",value:l,onChange:R=>o(R.target.value)})]}),w.length>0&&e.jsx(s.Tabs,{defaultValue:"all",value:c,onValueChange:R=>i(R),children:e.jsxs(s.TabsList,{className:"grid h-9 w-full grid-cols-3",children:[e.jsxs(s.TabsTrigger,{value:"all",className:"text-xs",children:["All",e.jsx("span",{className:"ml-2 text-xs font-semibold",children:w.length})]}),e.jsxs(s.TabsTrigger,{value:"text",className:"text-xs",children:[e.jsx(s.Layers,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:E})]}),e.jsxs(s.TabsTrigger,{value:"number",className:"text-xs",children:[e.jsx(s.ChartColumn,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:A})]})]})})]}),e.jsxs(s.CustomScrollArea,{className:"flex-1 basis-0 overflow-y-auto px-4 pt-3",children:[T.length===0&&l&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:['No fields found matching "',l,'"']}),T.length===0&&!l&&c!=="all"&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:["No ",c," fields found"]}),e.jsx("div",{className:"flex flex-col gap-1",children:T==null?void 0:T.map(R=>e.jsx("div",{children:O(R)},R.column_name))}),e.jsx(s.ScrollBar,{orientation:"vertical"}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Nt({ColumnsComponent:t,type:a}){var ee;const[n,r]=I.useState(!1),l=s.useEditorStore(ae=>ae.card),o=s.useEditorStore(ae=>ae.selectedConnectionId),c=s.useDashboardStore(ae=>ae.showFilters),i=s.useEditorStore(ae=>ae.selectedDatamodelId),d=s.useEditorStore(ae=>ae.selectedDatabaseName),u=s.useEditorStore(ae=>ae.selectedSchemaName),m=s.useEditorStore(ae=>ae.selectedTableName),h=s.useEditorStore(ae=>ae.isDevMode),{setSelectedTableName:f,setIsDevMode:g,setCardSql:b}=s.useEditorActions(),{connectionItems:p,modelItems:j,schemaItems:x,databaseItems:v,tableItems:k,columns:L,isConnectionsLoading:C,isModelsLoading:S,isConnectionsError:y,isModelsError:D,isDatabasesLoadingOrFetching:N,isDatabaseError:B,isSchemaLoadingOrFetching:w,isSchemaError:F,isColumnsError:T,isColumnsLoadingOrFetching:E,isTableLoadingOrFetching:A,isTableError:O,connectionType:M,isNonDbConnection:R,refetchDatabases:P,refetchModels:K,refetchSchemas:$,refetchTables:te,refetchColumns:X,refetchConnections:q,handleConnectionChange:H,handleDatabaseChange:_,handleSchemaChange:J,handleDatamodelChange:z,handleTableChange:U,tableName:Z,schemaName:le}=s.useEditorAside(),{data:V,refetch:se}=s.useDashboardCardQuery(l);function ne(){return t?t(le,Z,L):e.jsx(Fn,{schemaName:le,tableName:Z,columns:L,status:E?"Loading...":T?"Error":"Success"})}function Y(){window.location.href="mailto:support@semaphor.cloud?subject=Help&body=I need help with..."}function W(ae){ae===!0?V&&(b(V.userSql),setTimeout(()=>{se()},100)):b(""),g(ae)}function re(){if(!o||M==="S3"||M==="API")return null;if(!i||i==="none")return e.jsx(Re,{refetch:P,showNone:!0,onChange:_,isError:B,isLoading:N,items:v,value:d||"",title:"Database",type:"combobox"})}function ie(){if(o&&!R&&(!d||d==="none")&&(!i||i==="none"))return e.jsxs("div",{className:"grid grid-cols-3",children:[e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(s.Separator,{})}),e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(s.Label,{children:"OR"})}),e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(s.Separator,{})})]})}function he(){if(!o||M==="S3"||M==="API")return null;if(!d||d==="none")return e.jsx(Re,{refetch:K,showNone:!0,onChange:z,isError:D,isLoading:S,items:j,value:i||"",title:"Model",type:"combobox"})}function Q(){return!o||M==="S3"||M==="API"||!d||d==="none"?null:e.jsx(Re,{refetch:$,onChange:J,isError:F,isLoading:w,items:x,value:u||"",title:"Schema",type:"combobox"})}function oe(){function ae(){let ue=!1;return M==="API"?(ue=!1,ue):((M==="S3"||o&&d&&d!=="none"&&u)&&(ue=!0),ue)}return ae()?e.jsx(Re,{refetch:te,onChange:U,isError:O,items:k,isLoading:A,value:m||"",title:"Table",type:"combobox"}):null}return e.jsxs("aside",{className:s.cn("flex h-full min-w-[310px] max-w-[310px] flex-col justify-between rounded-none",{"border-r-[1px]":!c}),children:[e.jsxs("section",{className:s.cn("px-4",{"px-4 pb-0 pt-4":n,"px-4 py-4":!n}),children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between",children:[e.jsx("h2",{className:"text-brand-100 font-semibold",children:"Direct Source"}),e.jsx(s.Button,{onClick:()=>r(!n),size:"sm",variant:"ghost",className:"h-6 w-6 p-0",children:n?e.jsx(s.ChevronDown,{className:"h-4 w-4"}):e.jsx(s.ChevronUp,{className:"h-4 w-4"})})]}),!n&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(Re,{refetch:q,items:p,title:"Connection",value:o||"",onChange:H,isLoading:C,isError:y,type:"combobox",connectionTooltip:((ee=p==null?void 0:p.find(ae=>ae.id===o))==null?void 0:ee.type)||""}),re(),ie(),he(),Q(),oe()]})]}),ne(),e.jsx("div",{className:"flex items-center justify-between gap-2 px-6 py-4",children:a==="main"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Switch,{className:"data-[state=checked]:bg-muted-foreground/80",checked:h,onCheckedChange:W,id:"dev-mode"}),e.jsx(s.Label,{htmlFor:"dev-mode",children:"Advanced Mode"})]}),e.jsxs(s.Button,{onClick:Y,size:"sm",variant:"secondary",className:"group flex items-center gap-2 rounded-full",children:[e.jsx(Aa,{className:"size-4"}),e.jsx("span",{className:"hidden group-hover:block",children:"Help"})]})]})})]})}function Ct({error:t,errorSql:a,onSendFeedback:n,className:r,showFeedbackButton:l=!0}){const[o,c]=I.useState(!1);return e.jsx("div",{className:s.cn("rounded-lg border border-destructive/30 bg-destructive/5 p-4",r),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(s.CircleAlert,{className:"mt-0.5 h-5 w-5 flex-shrink-0 text-destructive"}),e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium text-destructive",children:"Query Error"}),e.jsxs("div",{className:"relative rounded-md bg-background/60 p-3",children:[e.jsx(s.CopyButton,{text:t,className:"absolute right-2 top-2 h-6 w-6 z-10"}),e.jsx("div",{className:"max-h-40 overflow-auto pr-10",children:e.jsx("p",{className:"font-mono text-xs text-foreground/80 break-all",children:t})})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[a&&e.jsx(s.Collapsible,{open:o,onOpenChange:c,children:e.jsx(s.CollapsibleTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-8",children:o?e.jsxs(e.Fragment,{children:[e.jsx(s.ChevronUp,{className:"mr-1.5 h-3.5 w-3.5"}),"Hide Details"]}):e.jsxs(e.Fragment,{children:[e.jsx(s.ChevronDown,{className:"mr-1.5 h-3.5 w-3.5"}),"Show Details"]})})})}),l&&n&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8",onClick:n,children:[e.jsx(La,{className:"mr-1.5 h-3.5 w-3.5"}),"Send Feedback"]})]}),a&&e.jsx(s.Collapsible,{open:o,onOpenChange:c,children:e.jsx(s.CollapsibleContent,{className:"space-y-2",children:e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Error SQL Query"}),e.jsx(s.CopyButton,{text:a,className:"h-6 w-6"})]}),e.jsx("div",{className:"rounded-md bg-background/60 p-2 max-h-80 overflow-auto",children:e.jsx(s.CodeHighlighter,{code:a,language:"sql"})})]})})})]})]})})}function St({sql:t,error:a,errorSql:n,onDebugWithAssistant:r}){const l=s.useEditorStore(u=>u.isDevMode),{setIsDevMode:o,setCardSql:c,setRunSql:i}=s.useEditorActions();function d(){o(!l),c(t),setTimeout(()=>{i(!0)},100)}return e.jsx("div",{className:"flex justify-between space-x-4",children:e.jsxs("div",{className:"flex grow flex-col space-y-3",children:[e.jsxs(s.ScrollArea,{className:"max-h-[250px] min-h-0 overflow-scroll text-xs leading-relaxed text-foreground/80",children:[a&&e.jsx(Ct,{error:a,errorSql:n,showFeedbackButton:!1}),!a&&t&&e.jsx("div",{className:"flex flex-col space-y-1.5",children:e.jsx("div",{className:"",children:e.jsx(s.CodeHighlighter,{code:t,language:"sql"})})})]}),!l&&t&&!a&&e.jsxs(s.Button,{onClick:d,variant:"secondary",size:"sm",children:[e.jsx(ga,{className:"mr-2 h-4 w-4"}),"View in SQL Editor"]}),a&&r&&e.jsxs(s.Button,{onClick:r,size:"sm",variant:"outline",children:[e.jsx(Na,{className:"mr-2 h-4 w-4"}),"Debug with Assistant"]})]})})}function wt({sql:t,error:a,errorSql:n,onDebugWithAssistant:r}){return e.jsxs(s.HoverCard,{openDelay:a?0:500,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"link",className:"h-5 p-0",children:a?e.jsx(Zs,{className:"h-4 w-4 text-red-500"}):e.jsx(s.Info,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsx(s.HoverCardContent,{align:"start",className:"flex w-[700px]",children:e.jsx(St,{errorSql:n,sql:t,error:a,onDebugWithAssistant:r})})]})}function Pn(t){return s.GenIcon({attr:{viewBox:"0 0 448 512"},child:[{tag:"path",attr:{d:"M439.8 200.5c-7.7-30.9-22.3-54.2-53.4-54.2h-40.1v47.4c0 36.8-31.2 67.8-66.8 67.8H172.7c-29.2 0-53.4 25-53.4 54.3v101.8c0 29 25.2 46 53.4 54.3 33.8 9.9 66.3 11.7 106.8 0 26.9-7.8 53.4-23.5 53.4-54.3v-40.7H226.2v-13.6h160.2c31.1 0 42.6-21.7 53.4-54.2 11.2-33.5 10.7-65.7 0-108.6zM286.2 404c11.1 0 20.1 9.1 20.1 20.3 0 11.3-9 20.4-20.1 20.4-11 0-20.1-9.2-20.1-20.4.1-11.3 9.1-20.3 20.1-20.3zM167.8 248.1h106.8c29.7 0 53.4-24.5 53.4-54.3V91.9c0-29-24.4-50.7-53.4-55.6-35.8-5.9-74.7-5.6-106.8.1-45.2 8-53.4 24.7-53.4 55.6v40.7h106.9v13.6h-147c-31.1 0-58.3 18.7-66.8 54.2-9.8 40.7-10.2 66.1 0 108.6 7.6 31.6 25.7 54.2 56.8 54.2H101v-48.8c0-35.3 30.5-66.4 66.8-66.4zm-6.7-142.6c-11.1 0-20.1-9.1-20.1-20.3.1-11.3 9-20.4 20.1-20.4 11 0 20.1 9.2 20.1 20.4s-9 20.3-20.1 20.3z"},child:[]}]})(t)}function Dt(t){const{theme:a}=s.useTheme(),n=s.useDashboardStore(p=>p.theme),r=s.useEditorStore(p=>p.frame),l=s.useEditorStore(p=>p.card),o=s.useEditorStore(p=>p.activeTabCardId),c=s.Le(),{refetch:i}=s.useDashboardCardQuery(l),{updateCardTab:d,setRunSql:u}=s.useEditorActions(),m=I.useRef(),h=I.useRef({}),f=r.cards.find(p=>p.id===o),g=I.useCallback(()=>{let p="";return t==="python"&&(p=(f==null?void 0:f.python)||s.PYTHON_DEFAULT_CODE),t==="sql"&&(p=(f==null?void 0:f.sql)||""),p},[t,f]);I.useEffect(()=>{if(o&&l.id&&l.id!==o){if(m.current&&c){const p=m.current.getModel();p&&(h.current[l.id]=p);let j=h.current[o];if(!j){const x=g();j=c.editor.createModel(x,t),h.current[o]=j}m.current.setModel(j)}d(o,l),u(!0)}},[o,l,d,c,u,t,g]),I.useEffect(()=>{if(!c)return;const p=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",j=n==="system"?p:n;c.editor.defineTheme("default",{base:j==="light"?"vs":"vs-dark",inherit:!0,rules:[],colors:{"editor.background":j==="light"?"#ffffff":s.hslStringToHex("240 10% 10%")}}),c.editor.setTheme("default")},[a,n,c]),I.useEffect(()=>{const p=m.current;p&&c&&l&&p.addCommand(c.KeyMod.Shift|c.KeyCode.Enter,function(){return i(),!1})},[c,i,l]);function b(p,j){if(m.current=p,!h.current[l.id]){const x=p.getModel(),v=g();h.current[l.id]=x||(j==null?void 0:j.editor.createModel(v,t))||p.getModel()}p.setModel(h.current[l.id])}return{handleEditorDidMount:b}}function zn(){const t=s.useEditorStore(c=>c.card.sql),a=s.useEditorStore(c=>c.sqlGen),{setCardSql:n,setSqlGen:r}=s.useEditorActions(),{handleEditorDidMount:l}=Dt("sql");function o(c){n(c),s.isObjectEmpty(a)||r({})}return e.jsxs("div",{className:"relative h-full w-full",children:[!t&&e.jsx("div",{className:"pointer-events-none absolute left-[65px] top-3 z-10 font-mono text-sm text-muted-foreground",children:"Write your SQL here"}),e.jsx(s.Ft,{theme:"default",className:"pt-3",onChange:o,value:t||"",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"sql",onMount:l})]})}function Vn(){const t=s.useEditorStore(l=>l.card.python),{setCardPython:a}=s.useEditorActions(),{handleEditorDidMount:n}=Dt("python");function r(l){a(l)}return e.jsx(s.Ft,{className:"pt-3",theme:"default",onChange:r,value:t||s.PYTHON_DEFAULT_CODE,options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"python",onMount:n})}function _n({jsonString:t}){return e.jsx(s.Ft,{theme:"default",defaultLanguage:"json",className:"mt-1 min-h-[220px]",value:t,options:{readOnly:!0,minimap:{enabled:!1},lineNumbers:"off",glyphMargin:!1,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,renderLineHighlight:"none"}})}function ws({variant:t="outline"}){var c;const{setCardSql:a}=s.useEditorActions();s.useEditorStore(i=>i.frame);const n=s.useEditorStore(i=>i.card);Ns(((c=n.customCardPreferences)==null?void 0:c.url)||""),s.useEditorStore(i=>i.selectedSchemaName),s.useEditorStore(i=>i.selectedDatamodelId),s.useEditorStore(i=>i.selectedDatabaseName),s.useEditorStore(i=>i.selectedTableName),s.useEditorStore(i=>i.selectedConnectionId),s.useEditorStore(i=>i.isShowingVisual),n.sql;const r=s.useEditorStore(i=>i.onSave),{getUpdatedFrame:l}=Cs();function o(){const i=l();r==null||r(i)}return e.jsxs(s.Button,{onClick:o,className:"h-8",size:"sm",variant:t,children:[e.jsx(s.Check,{className:"mr-2 size-4 font-bold"}),"Accept"]})}function Un(){const t=s.useQueryClient(),[a,n]=I.useState(!1),r=s.useDashboardStore(u=>u.actions.setIsDashboardPanelOpen),{setIsVisualEditing:l}=s.useDashboardActions(),{getUpdatedFrame:o}=Cs(),c=s.useSelectedVisual(),i=s.useUpdateVisualMutation(),d=()=>{const u=o();if(!(c!=null&&c.id)){s.ue.error("No visual selected");return}n(!0),i.mutate({visualId:c.id,data:{frameObject:u}},{onSuccess:()=>{n(!1),l(!1),r(!0),s.ue.success("Visual updated successfully"),t.invalidateQueries({queryKey:["resource-by-id","visual",c.id],exact:!0})},onError:()=>{n(!1),s.ue.error("Failed to update visual")}})};return e.jsxs(s.Button,{onClick:d,className:"h-8",size:"sm",children:[a&&e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin font-bold"})," Saving"]}),!a&&e.jsxs(e.Fragment,{children:[e.jsx(gs,{className:"mr-2 size-4 font-bold"}),"Save"]})]})}function Ds(){const{setTempQueryData:t,setSqlGen:a}=s.useEditorActions(),n=s.useQueryClient(),r=s.useEditorStore(d=>d.tempQueryData),l=s.useEditorStore(d=>d.onClose),o=s.useEditorStore(d=>d.card),{queryKey:c}=s.useDashboardCardQuery(o);function i(){if(r){const{queryKey:d,queryData:u}=r;d&&u&&n.setQueryData(d,u)}a({}),l==null||l()}return e.jsxs(s.Button,{onClick:i,className:"h-8",size:"sm",variant:"outline",children:[e.jsx(s.X,{className:"mr-2 size-4"}),"Close"]})}function rs(){const{setTempQueryData:t}=s.useEditorActions(),a=s.useQueryClient(),n=s.useEditorStore(j=>j.isDevMode),r=s.useEditorStore(j=>j.tempQueryData),l=s.useEditorStore(j=>j.card),{queryKey:o}=s.useDashboardCardQuery(l),{setCardSql:c,setSqlGen:i,setCardPython:d,setCardCustomCfg:u,setCardPreferences:m,updateDataSource:h,clearQueryConfig:f,setCardConfig:g,setCardType:b}=s.useEditorActions();function p(){const j=a.getQueryData(o);r!=null&&r.queryData||t({queryKey:o,queryData:j}),a.setQueryData(o,null),a.removeQueries({queryKey:o,exact:!0}),n&&h(s.EMPTY_DATA_SOURCE),c(""),i({}),f(),g(void 0),d(""),u(""),m({}),b("bar")}return e.jsxs(s.Button,{onClick:p,className:"h-8",size:"sm",variant:"secondary",children:[e.jsx(s.SquarePen,{className:"mr-2 size-4"}),"Clear"]})}function $n(){const t=s.useQueryClient(),[a,n]=I.useState(!1),[r,l]=I.useState(!1);s.useEditorStore($=>$.frame);const o=s.useEditorStore($=>$.card);s.useEditorStore($=>$.isShowingVisual),s.useEditorStore($=>$.selectedConnectionId),s.useEditorStore($=>$.tempQueryData),s.useEditorStore($=>$.selectedDatabaseName),s.useEditorStore($=>$.selectedDatamodelId),s.useEditorStore($=>$.selectedSchemaName);const c=s.useEditorStore($=>$.showAIDialog);s.useEditorStore($=>$.selectedTableName);const i=s.useEditorStore($=>{var te;return(te=$==null?void 0:$.card)==null?void 0:te.sql}),d=s.useEditorStore($=>{var te;return(te=$==null?void 0:$.card)==null?void 0:te.python}),{sheetFilterValues:u}=s.useSheetFilterValues(),{setCardCustomCfg:m,setQueryResultColumns:h,setCardSql:f,setTempQueryData:g,setPythonStdOut:b,setCardPreferences:p,setCardType:j,setCardPython:x,runAssistant:v,setShowAIDialog:k}=s.useEditorActions();s.useEditorStore($=>$.onSave),s.useEditorStore($=>$.onClose),s.useEditorStore($=>$.actions.setSqlGen);const L=s.useEditorStore($=>$.runSql),C=s.useEditorStore($=>$.actions.setRunSql),S=s.useEditorStore($=>$.actions.setIsSqlRunning),{data:y,isLoading:D,isFetching:N,isSuccess:B,isError:w,error:F,errorSql:T,queryKey:E,refetch:A,errorMessage:O}=s.useDashboardCardQuery(o);I.useEffect(()=>{if(y&&(y.rowLimitExceeded&&s.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),b((y==null?void 0:y.output)||""),y.records.length>0)){const{dimensionKeys:$}=s.getKeys(y.records);h($)}},[y,h,b]),I.useEffect(()=>{(D||N)&&S(!0),(w||B)&&S(!1),w&&(h([]),b(""))},[D,N,y,b,w,B,S,h,F]),I.useEffect(()=>{L&&(t.getQueryData(E)||A(),C(!1))},[L,A,C,E,t]);async function M(){const $=`Can you help me debug this query?
|
|
337
332
|
|
|
338
333
|
Error:
|
|
339
334
|
|
|
340
|
-
${
|
|
335
|
+
${O}
|
|
341
336
|
|
|
342
337
|
Error SQL:
|
|
343
338
|
|
|
@@ -349,12 +344,12 @@
|
|
|
349
344
|
|
|
350
345
|
${d?`Python:
|
|
351
346
|
${d}`:""}
|
|
352
|
-
`;v($)}function O(){return e.jsxs(e.Fragment,{children:[r&&e.jsx("div",{className:"relative flex w-1/3 min-w-0 grow overflow-hidden text-xs",role:"editor-filter-container",children:e.jsx("div",{className:"mt-2 w-[99%]",children:e.jsx(Un,{jsonString:JSON.stringify(u,null,2)})})}),u&&u.length>0&&e.jsx(s.Button,{variant:"ghost",onClick:()=>l(!r),className:"absolute bottom-0 right-6 size-7 p-1",children:r?e.jsx(s.X,{className:"size-3.5 text-muted-foreground"}):e.jsx(s.Filter,{className:"size-3.5 text-muted-foreground"})})]})}function P(){return e.jsxs(s.ResizablePanelGroup,{className:"flex grow pb-1",direction:"vertical",role:"editor-resizable-group",children:[e.jsxs(s.ResizablePanel,{id:"1",order:1,defaultSize:a?20:100,className:"relative flex grow",children:[e.jsx("div",{id:"sql-container",className:"relative flex w-[99%]",children:e.jsx(Vn,{})}),a&&e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"sql"})]}),a&&e.jsxs(e.Fragment,{children:[e.jsx(s.ResizableHandle,{withHandle:!0,className:"border"}),e.jsxs(s.ResizablePanel,{id:"2",order:2,defaultSize:80,className:"relative flex grow",children:[e.jsx("div",{id:"python-container",className:"relative flex w-[99%] pt-0",children:e.jsx(_n,{})}),e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"python"})]})]})]})}function K(){return e.jsxs("div",{role:"editor-controls",className:"item-center flex flex-wrap justify-between gap-2 px-6 py-4",children:[e.jsxs("div",{className:"flex grow items-center gap-2",children:[e.jsxs(s.Button,{title:"Shift + Enter",disabled:D||C,onClick:()=>{M()},className:"h-8 shrink-0",size:"sm",children:[D||C?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(s.Play,{className:"mr-2 h-4 w-4"}),"Run"]}),e.jsx(Dt,{errorSql:T,sql:y==null?void 0:y.sql,error:B,onDebugWithAssistant:L}),e.jsx(ns,{}),e.jsx(s.Toggle,{pressed:a,onPressedChange:$=>n($),className:"h-8",size:"sm",variant:"outline",children:e.jsx(zn,{className:"size-4 text-foreground/70"})}),e.jsx("button",{disabled:c,onClick:()=>{k(!0)},className:"h-9 w-full cursor-text px-3 text-left text-sm text-muted-foreground",children:c?"":"Type your question..."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ds,{}),e.jsx(ws,{})]})]})}return e.jsxs("section",{role:"editor-section",className:"flex grow flex-col justify-end",children:[e.jsxs("div",{className:"relative flex grow justify-between overflow-y-scroll",children:[P(),O()]}),K()]})}const qn=[{value:"table",label:"Table",icon:s.Table2},{value:"aggregateTable",label:"Aggregate",icon:s.Layers},{value:"pivotTable",label:"Pivot",icon:st}];function Gn({className:t}){const a=s.useEditorStore(d=>d.card),{setCardType:n,setCard:r,updateCardInFrame:l}=s.useEditorActions(),o=["table","aggregateTable","pivotTable"].includes(a.type),c=s.hasValidCardConfig(a.config);if(!o||!c)return null;const i=d=>{var m;const u=d;if(u==="aggregateTable"&&((m=a.config)!=null&&m.pivotByColumns)&&a.config.pivotByColumns.length>0){const h={...a,type:u,config:{...a.config,pivotByColumns:[]}};r(h),l(h)}else{n(u);const h={...a,type:u};l(h)}};return e.jsx("div",{className:s.cn("flex items-center",t),children:e.jsx(s.RadioGroup,{value:a.type,onValueChange:i,className:"flex flex-row items-center justify-between gap-1 rounded-lg border p-1",children:qn.map(d=>{const u=d.icon;return e.jsxs("div",{className:"flex items-center",children:[e.jsx(s.RadioGroupItem,{value:d.value,id:`table-type-${d.value}`,className:"peer sr-only"}),e.jsxs(s.Label,{htmlFor:`table-type-${d.value}`,className:s.cn("flex cursor-pointer items-center gap-1.5 rounded-md px-3 py-1 text-sm font-medium transition-all","hover:bg-muted","peer-data-[state=checked]:bg-background peer-data-[state=checked]:shadow-sm"),children:[e.jsx(u,{className:"h-3.5 w-3.5"}),d.label]})]},d.value)})})})}function Hn({card:t}){var v,k,R,N,w,y,D,C,I,S,F;const[a,n]=A.useState(!1),[r,l]=A.useState([]),{authToken:o}=s.useSemaphorContext(),c=s.getTokenParams(o==null?void 0:o.accessToken),i=s.useDashboardStore(T=>T.themeStyle),d={colors:((k=(v=i==null?void 0:i.chart)==null?void 0:v.dataset)==null?void 0:k.backgroundColor)||[]};(R=t.customCardPreferences)!=null&&R.inputData;const{getCard:u}=s.useCustomVisual(((N=t.customCardPreferences)==null?void 0:N.url)||""),m=((w=t.customCardPreferences)==null?void 0:w.visualType)||"single",h=s.useEditorStore(T=>T.frame),{setCustomCardPreferences:f}=s.useEditorActions(),{data:g}=s.useDashboardCardQuery(t),b=A.useCallback((T,E)=>{l(M=>({...M,[T]:E}))},[]);if(!((y=t.customCardPreferences)!=null&&y.componentName))return null;const p=u((D=t.customCardPreferences)==null?void 0:D.componentName);function j(T){n(T)}const x=Object.keys(((C=t.customCardPreferences)==null?void 0:C.dataInputCardIds)||{}).map(T=>{var B,L,O;const E=(L=(B=t.customCardPreferences)==null?void 0:B.dataInputCardIds)==null?void 0:L[T].cardId,M=(O=h==null?void 0:h.cards)==null?void 0:O.find(P=>P.id===E);return M||null});return e.jsx("div",{className:"semaphor-custom mb-3 flex grow basis-0 flex-col space-y-2 overflow-y-auto",children:e.jsxs(A.Suspense,{fallback:e.jsx(e.Fragment,{}),children:[p&&m==="single"&&e.jsx(p,{editing:!0,params:c,theme:d,settings:(I=t.customCardPreferences)==null?void 0:I.settings,onDataChange:b,data:(g==null?void 0:g.records)||[]}),p&&m==="multiple"&&e.jsxs(e.Fragment,{children:[Object.keys(((S=t.customCardPreferences)==null?void 0:S.dataInputCardIds)||{}).map(T=>{var B,L,O;const E=(L=(B=t.customCardPreferences)==null?void 0:B.dataInputCardIds)==null?void 0:L[T].cardId,M=(O=h==null?void 0:h.cards)==null?void 0:O.find(P=>P.id===E);if(M)return e.jsx(s.MultiInputEmptyRenderer,{onLoadingStatus:j,onDataChange:b,dataInputIndex:T,card:M},M.id+T)}),e.jsx("div",{className:"flex flex-col gap-2",children:e.jsx(p,{theme:d,onDataChange:b,settings:x.map(T=>{var E;return(E=T==null?void 0:T.customCardPreferences)==null?void 0:E.settings}),data:x.map(T=>T!=null&&T.id?r==null?void 0:r[T.id]:[])})})]})]},(F=t.customCardPreferences)==null?void 0:F.componentName)})}function Tt({className:t,...a}){var D;const n=s.useEditorStore(C=>C.card),r=s.isExplorerCard(n),l=((D=n.customCardPreferences)==null?void 0:D.showCardHeader)??!0,o=s.useEditorStore(C=>C.frame),c=s.useDashboardStore(C=>C.dashboard.filters),i=s.useEditorStore(C=>C.actions.setRunSql),{updateFilter:d}=s.useDashboardActions(),u=c==null?void 0:c.find(C=>C.id===o.filterId),{data:m,isLoading:h,isFetching:f,errorMessage:g,pagination:b}=s.useDashboardCardQuery(n),{setCard:p,updateCardInFrame:j}=s.useEditorActions(),{data:x}=s.useTopoJson(n),v=A.useMemo(()=>{var C;return n.type!=="pivotTable"||!((C=m==null?void 0:m.records)!=null&&C.length)?null:{records:m.records,columnSubtotalMeta:m.columnSubtotalMeta,subtotalColumns:m.subtotalColumns||[],pivotSchema:m.pivotSchema||[],groupByColumns:m.groupByColumns}},[n.type,m==null?void 0:m.records,m==null?void 0:m.columnSubtotalMeta,m==null?void 0:m.subtotalColumns,m==null?void 0:m.pivotSchema,m==null?void 0:m.groupByColumns]),k=s.usePivotTableConfig(n,v),R=(C,I)=>{var F,T;const S={...n,paginationConfig:{page:C+1,pageSize:I}};p(S),j(S),n.sql&&((T=(F=n.preferences)==null?void 0:F.tablePrefs)!=null&&T.enableDevModePagination)&&i(!0)},N=A.useMemo(()=>!n.id||!(m!=null&&m.records)?null:s.createChartConfig({card:n,data:m==null?void 0:m.records,cardType:n.type,queryConfig:n.queryConfig,customCfg:n.customCfg,preferences:n.preferences,topoJson:x}),[n.id,m==null?void 0:m.records,n.type,n.queryConfig,n.customCfg,n.preferences,x]);function w(C){return e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(Hn,{card:C})})}function y(){if(m!=null&&m.records&&(m==null?void 0:m.records.length)===0&&!h&&!f)return g?e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(s.SearchX,{className:"size-8 text-destructive"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:r?"Error fetching data. Please check your chart configuration":"Error fetching data. Please check your SQL or Python code."})]}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(s.TreePalm,{className:"size-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No results to display"})]});if((h||f)&&n.type!=="table")return e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})});if(!n.id)return null;if(n.type==="custom")return w(n);if(!["table","pivotTable","aggregateTable","custom"].includes(n.type)&&N)return e.jsx("div",{className:"relative h-full min-h-0 w-full flex-1 grow basis-0",children:h||f?e.jsx(e.Fragment,{}):e.jsx(s.ChartJsVisual,{cfg:N})});if(n.type==="table")return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.TableVisual,{card:n,data:(m==null?void 0:m.records)||[],paginationMetadata:b,onPaginationChange:R,isLoading:h||f})});if(n.type==="pivotTable"&&k)return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.PivotTableVisual,{card:n,data:k.data,options:k.options,onAggregationChange:C=>{const I=s.handleAggregationChange(C,n.config),S={...n,config:I};p(S),j(S)},onAggregationLabelChange:C=>{const I=s.handleAggregationLabelChange(C,n.config),S={...n,config:I};p(S),j(S)}})});if(n.type==="aggregateTable")return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.AggregateTable,{card:n,data:(m==null?void 0:m.records)||[],groupByColumns:m==null?void 0:m.groupByColumns,pivotSchema:m==null?void 0:m.pivotSchema,paginationMetadata:b,onPaginationChange:R,onAggregationChange:C=>{const I=s.handleAggregationChange(C,n.config),S={...n,config:I};p(S),j(S)},isLoading:h||f})})}return e.jsxs(s.Card,{role:"editor-visual-card",className:s.cn("relative flex h-full flex-col rounded-none",t),...a,children:[l&&e.jsxs(s.CardHeader,{className:"flex flex-row items-start justify-between py-4",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-5",children:[e.jsx(s.CardTitle,{className:"text-base",children:e.jsx(s.EditableText,{value:n.title,onSave:C=>p({...n,title:C}),isEditable:!0,placeholder:"Add title",displayClassName:"text-base font-semibold",inputClassName:"text-base font-semibold"})}),e.jsx(Gn,{})]}),e.jsx("div",{className:"w-1/2",children:e.jsx(s.EditableText,{value:n.description||"",onSave:C=>p({...n,description:C}),isEditable:!0,placeholder:"Add description",displayClassName:"text-sm text-muted-foreground",inputClassName:"text-sm"})})]}),u&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Label,{className:"my-1",children:e.jsx(s.EditableText,{value:u.title||u.column,onSave:C=>d({...u,title:C}),isEditable:!0,placeholder:"Filter",displayClassName:"text-sm",inputClassName:"text-sm"})}),e.jsx(s.FilterComponent,{filter:u})]})]}),e.jsx(s.CardContent,{className:"flex grow flex-col",children:y()})]})}const ms=({language:t,value:a,onChange:n,readonly:r})=>e.jsx(s.Ft,{className:"h-full w-full overflow-hidden text-xs",theme:"default",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,lineHeight:16,renderLineHighlight:"none",readOnly:r},defaultLanguage:t,value:a,onChange:n}),Wn=()=>e.jsxs(s.DialogHeader,{children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(s.DialogTitle,{children:"Customize Card"})}),e.jsxs(s.DialogDescription,{children:["See the configuration options and documentation",e.jsx("a",{target:"_blank",className:"ml-1 text-blue-500 underline",href:"https://www.chartjs.org/docs/latest/samples/bar/vertical.html",children:"here."})]})]}),Kn=({customCode:t,cardCustomCfgString:a,mergedConfig:n,onConfigChange:r,onCodeChange:l})=>e.jsxs(s.Tabs,{defaultValue:"final-config",className:"flex w-1/2 flex-col",children:[e.jsxs(s.TabsList,{className:"justify-start rounded-sm rounded-b-none border border-b-0",children:[e.jsx(s.TabsTrigger,{value:"final-config",children:"Config"}),e.jsx(s.TabsTrigger,{value:"custom-config",children:"Changes"}),e.jsx(s.TabsTrigger,{value:"custom-code",children:"Custom Code"})]}),e.jsx(s.TabsContent,{value:"final-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(ms,{language:"json",value:n,onChange:r})}),e.jsx(s.TabsContent,{value:"custom-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(ms,{readonly:!0,language:"json",value:a,onChange:()=>{}})}),e.jsx(s.TabsContent,{value:"custom-code",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(ms,{language:"javascript",value:t,onChange:l})})]}),Jn=({error:t,hasCardCustomConfig:a,onReset:n,onApply:r,onClose:l})=>e.jsxs(s.DialogFooter,{className:"flex items-center",children:[e.jsx(s.Label,{className:"mr-2 text-red-500",children:t}),e.jsx(s.Button,{disabled:!a,onClick:n,variant:"outline",children:"Reset"}),e.jsx(s.Button,{onClick:r,variant:"outline",children:"Apply"}),e.jsx(s.Button,{onClick:l,variant:"outline",children:"Close"})]});function Qn(){const[t,a]=A.useState(!1),[n,r]=A.useState(""),[l,o]=A.useState(""),[c,i]=A.useState(""),[d,u]=A.useState(""),m=s.useEditorStore(N=>N.card),h=s.useEditorStore(N=>N.card.customCfg),f=h?JSON.stringify(h,null,2):"",{data:g}=s.useDashboardCardQuery(m),{data:b}=s.useTopoJson(m),{setCardCustomCfg:p,setCustomVisualCode:j}=s.useEditorActions(),x=N=>{var w,y;return JSON.stringify({...N,data:{...N.data,datasets:(y=(w=N.data)==null?void 0:w.datasets)==null?void 0:y.map(D=>({...D,data:[]}))}},null,2)},v=()=>{var w,y;if(!((w=g==null?void 0:g.records)!=null&&w.length))return;const N=s.createChartConfig({card:m,data:g.records,cardType:m.type,queryConfig:m.queryConfig,preferences:m.preferences,topoJson:b});if(N){r(x(N)),i(((y=m.preferences)==null?void 0:y.customVisualCode)||"");const D=s.merge(N,h);o(x(D))}},k=()=>{try{if(c&&j(c),l){const N=JSON.parse(l),w=s.getObjectDiff(JSON.parse(n),N);p(w),u("")}}catch{u("Invalid JSON configuration")}},R=Object.keys(h||{}).length===0;return e.jsxs(s.Dialog,{open:t,onOpenChange:a,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Customize Visual",onClick:v,className:R?"":"text-green-600 hover:text-green-700",children:e.jsx(s.Settings,{className:"h-4 w-4"})})}),e.jsxs(s.DialogContent,{className:"flex h-[600px] grow flex-col overflow-auto sm:min-w-[900px] lg:min-w-[1200px]",children:[e.jsx(Wn,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(Tt,{className:"w-1/2 rounded shadow-none"})}),e.jsx(Kn,{customCode:c,cardCustomCfgString:f,mergedConfig:l,onConfigChange:N=>o(N??""),onCodeChange:N=>i(N??"")})]}),e.jsx(Jn,{error:d,hasCardCustomConfig:!!h,onReset:()=>{o(n),p(null)},onApply:k,onClose:()=>a(!1)})]})]})}function rs(t){const[a,n]=A.useState(null);return a}function Et(){const{authToken:t}=s.useSemaphorContext(),{data:a,isLoading:n,isFetching:r,isError:l}=s.useQuery({queryKey:["plugins",t==null?void 0:t.accessToken],queryFn:()=>s.getPlugins(t==null?void 0:t.accessToken)});return{data:a,isLoading:n,isFetching:r,isError:l}}function It(){const{data:t,isLoading:a,isError:n}=Et(),r=s.useQueries({queries:((t==null?void 0:t.plugins)||[]).map(i=>({queryKey:["manifest",i.value],queryFn:()=>s.loadManifest(i.value),enabled:!!i.value,staleTime:5*60*1e3,gcTime:10*60*1e3,retry:2,retryDelay:d=>Math.min(1e3*2**d,3e4)}))}),l=[];let o=a,c=n;return r.forEach((i,d)=>{var u;if(i.isLoading&&(o=!0),i.isError&&(c=!0),i.data&&((u=t==null?void 0:t.plugins)!=null&&u[d])){const m=t.plugins[d],h=i.data.visuals.map(f=>({name:f.name,pluginName:m.label,componentType:f.componentType,pluginType:m.type,icon:f.icon,chartType:f.chartType,url:m.value}));l.push(...h)}}),{data:l,isLoading:o,isError:c}}function Xn({onChartTypeChange:t}){const{setCardCustomCfg:a,setCardPreferences:n,setCardType:r,setCustomCardPreferences:l}=s.useEditorActions(),{data:o,isLoading:c,isError:i}=It(),d=A.useCallback((u,m)=>{a(null),n({}),r(u),m&&l({type:"component",visualType:"single",url:m.url,componentName:m.name,icon:m.icon}),t==null||t()},[a,n,r,l,t]);return c?e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"grid grid-cols-4 place-items-center",children:e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading custom visuals..."})})]}):i?e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"grid grid-cols-4 place-items-center",children:e.jsx("div",{className:"text-sm text-destructive",children:"Failed to load custom visuals"})})]}):!o||o.length===0?null:e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"grid grid-cols-4 place-items-center",children:o.map((u,m)=>e.jsx(Zn,{text:u.name,onClick:()=>d("custom",u),icon:u.icon},`${u.url}-${u.name}-${m}`))})]})}const Zn=({text:t,icon:a,onClick:n})=>{const r=rs(),l=t.charAt(0).toUpperCase();return e.jsx(s.IconButton,{onClick:n,tooltip:t,children:r?e.jsx(r,{className:"h-4 w-4"}):l})};function At({onChartTypeChange:t,iconClassName:a}){const{setCardType:n,setCardPreferences:r,setIsDevMode:l}=s.useEditorStore(m=>m.actions),{setCardCustomCfg:o,setCustomCardPreferences:c,setQueryConfig:i}=s.useEditorActions();function d(m,h){o(null),r({}),n(m),["custom","text","map"].includes(m)&&(l(!0),i(void 0)),t==null||t()}const u=1e3;return e.jsxs("div",{className:"grid grid-cols-5 place-items-center",children:[e.jsx(s.IconButton,{openDelay:u,tooltip:"Table",onClick:()=>d("table"),className:"h-10 p-4",children:e.jsx(s.Table2,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Bar Chart",onClick:()=>d("bar"),className:"h-10 p-4",children:e.jsx(s.ChartColumnIncreasing,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Line Chart",onClick:()=>d("line"),className:"h-10 p-4",children:e.jsx(s.ChartLine,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Stacked Bar Chart",onClick:()=>d("stackedBar"),className:"h-10 p-4",children:e.jsx(s.ChartColumnStacked,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Stacked Line Chart",onClick:()=>d("stackedLine"),className:"h-10 p-4",children:e.jsx(s.MdStackedLineChart,{className:s.cn("size-5",a),strokeWidth:0})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Scatter Chart",onClick:()=>d("scatter"),className:"h-10 p-4",children:e.jsx(s.ChartScatter,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Bubble Chart",onClick:()=>d("bubble"),className:"h-10 p-4",children:e.jsx(s.TbChartBubble,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Pie Chart",onClick:()=>d("pie"),className:"h-10 p-4",children:e.jsx(s.ChartPie,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Doughnut Chart",onClick:()=>d("doughnut"),className:"h-10 p-4",children:e.jsx(s.Donut,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Funnel Chart",onClick:()=>d("funnel"),className:"h-10 p-4",children:e.jsx(s.TbChartFunnel,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Radar Chart",onClick:()=>d("radar"),className:"h-10 p-4",children:e.jsx(s.Radar,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Polar Area Chart",onClick:()=>d("polarArea"),className:"h-10 p-4",children:e.jsx(s.PiChartPolar,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Tornado Chart",onClick:()=>d("tornado"),className:"h-10 p-4",children:e.jsx(s.Tornado,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{tooltip:"Range Chart",onClick:()=>d("range"),className:"h-10 p-4",children:e.jsx(s.ChartNoAxesGantt,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"KPI",onClick:()=>d("kpi"),className:"h-10 p-4",children:e.jsx(s.TiSortNumerically,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Text",onClick:()=>d("text"),className:"h-10 p-4",children:e.jsx(s.BookType,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{tooltip:"Map",onClick:()=>d("map"),className:"h-10 p-4",children:e.jsx(s.Map,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Custom",onClick:()=>d("custom"),className:"h-10 p-4",children:e.jsx(Ue,{className:s.cn("size-5",a)})})]})}function er({chartType:t,className:a,customIcon:n,componentName:r}){const l=rs();switch(t){case"bar":return e.jsx(s.ChartColumnIncreasing,{className:a});case"line":return e.jsx(s.ChartLine,{className:a});case"pie":return e.jsx(s.ChartPie,{className:a});case"radar":return e.jsx(s.Radar,{className:a});case"scatter":return e.jsx(s.ChartScatter,{className:a});case"bubble":return e.jsx(s.TbChartBubble,{className:a});case"doughnut":return e.jsx(s.Donut,{className:a});case"stackedBar":return e.jsx(s.ChartColumnStacked,{className:a});case"stackedLine":return e.jsx(s.MdStackedLineChart,{className:a});case"polarArea":return e.jsx(s.PiChartPolar,{className:a});case"funnel":return e.jsx(s.TbChartFunnel,{className:a});case"tornado":case"pyramid":return e.jsx(s.Tornado,{className:a});case"range":return e.jsx(s.ChartNoAxesGantt,{className:a});case"kpi":return e.jsx(s.TiSortNumerically,{className:a});case"text":return e.jsx(ge,{className:a});case"map":return e.jsx(s.Map,{className:a});case"custom":return n&&l?e.jsx(l,{className:a}):r?r==null?void 0:r.charAt(0).toUpperCase():e.jsx(Ue,{className:a});default:return e.jsx(s.Table2,{className:a})}}function Mt({variant:t="ghost"}){var o,c;const[a,n]=A.useState(!1),r=s.useEditorStore(i=>i.card),l=r.type;return s.useDashboardStore(i=>i.isVisualEditing),e.jsxs(s.Popover,{open:a,onOpenChange:n,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:t||"ghost",children:e.jsx(er,{className:"size-4",chartType:l,customIcon:(o=r.customCardPreferences)==null?void 0:o.icon,componentName:(c=r.customCardPreferences)==null?void 0:c.componentName})})}),e.jsxs(s.PopoverContentCustom,{onOpenAutoFocus:i=>i.preventDefault(),className:"w-72 p-1",children:[e.jsx(At,{onChartTypeChange:()=>n(!1)}),e.jsx(Xn,{onChartTypeChange:()=>n(!1)})]})]})}function sr({error:t,className:a="",textClassName:n="",copyButtonClassName:r=""}){const[l,o]=A.useState(!1),c=A.useRef(null),i=A.useRef(!1);function d(){t&&!i.current&&navigator.clipboard.writeText(t)}function u(f){(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),d())}function m(){const f=window.getSelection();if(f&&f.toString().trim()!==""){const g=f.toString();navigator.clipboard.writeText(g),o(!0),i.current=!0,setTimeout(()=>{o(!1),i.current=!1},1e3)}else i.current=!1}function h(){o(!1),i.current=!1}return e.jsxs("div",{className:`relative rounded-md border border-red-200 bg-red-50 p-3 dark:border-red-800 dark:bg-red-950/20 ${a}`,children:[e.jsx("div",{className:"float-right mb-2 ml-2",children:e.jsx(s.CopyButton,{text:t,className:`h-6 w-6 p-0 text-red-600 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300 ${r}`})}),e.jsx("div",{ref:c,className:`cursor-pointer select-text break-all font-mono text-xs text-red-700 dark:text-red-300 ${n}`,onClick:d,onKeyDown:u,onMouseUp:m,onMouseDown:h,tabIndex:0,role:"button","aria-label":"Click to copy error message or select text to copy",children:t}),l&&e.jsx("div",{className:"absolute bottom-1 right-1 rounded bg-green-100 px-2 py-1 text-xs text-green-600 dark:bg-green-900/30 dark:text-green-400",children:"Copied!"}),e.jsx("div",{className:"clear-both"})]})}function tr(){const t=s.useEditorStore(o=>{var c,i;return(i=(c=o.card.preferences)==null?void 0:c.chartOptions)==null?void 0:i.indexAxis}),a=s.useEditorStore(o=>o.card.type),{setChartOrientation:n}=s.useEditorStore(o=>o.actions);function r(){return e.jsx(s.IconButton,{onClick:()=>{n(t==="x"||t===void 0?"y":"x")},tooltip:"Chart Orientation",children:t==="x"||t===void 0?e.jsx(zs,{className:"size-4"}):e.jsx(Ps,{className:"size-4"})})}function l(){return e.jsx(s.IconButton,{onClick:()=>{n(t==="y"||t===void 0?"x":"y")},tooltip:"Chart Orientation",children:t==="y"||t===void 0?e.jsx(zs,{className:"size-4"}):e.jsx(Ps,{className:"size-4"})})}return e.jsx(e.Fragment,{children:a==="funnel"?l():r()})}function Lt(){const t=s.useEditorStore(c=>c.card),a=s.useEditorStore(c=>c.isShowingVisual),n=s.useEditorStore(c=>{var i,d;return(d=(i=c.card)==null?void 0:i.preferences)==null?void 0:d.chartOptions}),r=s.getChartGridStyle(n),{setChartGrid:l}=s.useEditorActions();function o(){const c=["xy","none","x","y"],d=(c.indexOf(r)+1)%c.length;l(c[d])}return a?e.jsxs("div",{"data-info":"visual-settings",className:"flex items-center",children:[["line","bar","range","stackedBar","stackedLine","horizontalBar","funnel"].includes(t.type)&&e.jsx(e.Fragment,{children:e.jsx(tr,{})}),!["kpi","text","custom","table"].includes(t.type)&&e.jsx(e.Fragment,{}),!["pie","doughnut","funnel","radar","polarArea","table","custom","kpi","text","map"].includes(t.type)&&e.jsxs(s.IconButton,{tooltip:"Grid Style",onClick:o,children:[(r==="xy"||!r)&&e.jsx(st,{className:"size-4"}),r==="x"&&e.jsx(ha,{className:"size-4"}),r==="y"&&e.jsx(Va,{className:"size-4"}),r==="none"&&e.jsx(qa,{className:"size-4"})]})]}):null}function ar(){const t=s.useEditorStore(b=>b.frame),a=s.useEditorStore(b=>b.card),{setFrame:n,setActiveTabCardId:r,setCard:l,updateCardInFrame:o}=s.useEditorActions(),c=(b,p)=>{b.dataTransfer.setData("tabIndex",p.toString())},i=b=>{b.preventDefault()},d=(b,p)=>{const j=b.dataTransfer.getData("tabIndex");if(j===p.toString())return;const x=Array.from(t.cards),[v]=x.splice(parseInt(j),1);x.splice(p,0,v),n({...t,cards:x})};function u(b){const p=t.cards.filter(v=>v.id!==b),j=p[0],x={...t,cards:p,activeCardId:j.id};n(x),r(j.id),l(j)}function m(b,p){const j={...t,cards:[...t.cards,p],activeCardId:b.id};n(j),r(p.id)}function h(){const b={...a,id:s.v4(),title:`${a.title} Copy`,tabTitle:`${a.tabTitle||a.title} Copy`};m(a,b)}function f(b){const p={dataSource:b.dataSource,connectionId:b.connectionId,lastSelectedDatabase:b.lastSelectedDatabase,lastSelectedSchema:b.lastSelectedSchema,lastSelectedTable:b.lastSelectedTable,lastSelectedDatamodelId:b.lastSelectedDatamodelId,id:s.v4(),title:"Title",description:"",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[],mode:"explorer"};m(b,p)}function g(b,p){return b.cards.length===1&&(p.displayTab===!0||p.displayTab===void 0)||b.activeCardId!==p.id&&(p.displayTab===!0||p.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const j=p.displayTab===void 0?!1:!p.displayTab;l({...p,displayTab:j}),o({...p,displayTab:j})},children:p.displayTab===!0||p.displayTab===void 0?e.jsx(s.Eye,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"}):e.jsx(ga,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"})})}return e.jsx(s.TabsList,{className:"group mx-4 justify-between overflow-x-auto",children:e.jsxs("div",{className:"flex items-center",children:[t.cards.map((b,p)=>e.jsxs(s.TabsTrigger,{draggable:!0,onDragStart:j=>c(j,p),onDragOver:i,onDrop:j=>d(j,p),className:"",value:b.id,children:[g(t,b),e.jsx(s.Editable,{enabled:t.activeCardId===b.id,text:b.tabTitle||b.title,onSave:j=>{l({...a,tabTitle:j}),o({...a,tabTitle:j})},children:b.tabTitle||b.title},b.id),t.activeCardId===b.id&&t.cards.length>1&&e.jsx(s.X,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:()=>u(b.id)})]},b.id)),e.jsx(s.Button,{className:"ml-1 h-8 px-2 hover:bg-muted-foreground/50",variant:"outline",onClick:()=>f(a),children:e.jsx(s.Plus,{className:"h-4 w-4"})}),e.jsx(s.Button,{className:"invisible ml-1 h-8 px-2 hover:bg-muted-foreground/50 group-hover:visible",variant:"outline",onClick:h,children:e.jsx(pa,{className:"h-4 w-4"})})]})})}function Rt(){const t=s.useEditorStore(p=>p.frame),a=s.useEditorStore(p=>p.card),n=s.useEditorStore(p=>p.isSqlRunning),r=s.useEditorStore(p=>p.isDevMode),{setFrame:l,setActiveTabCardId:o,setCard:c,setIsDevMode:i,setRunSql:d}=s.useEditorActions(),{data:u,isLoading:m,isFetching:h}=s.useDashboardCardQuery(a);function f(p){const j=t.cards.find(x=>x.id===p);if(j!=null&&j.sql){r||i(!0),o(p);return}if(j!=null&&j.queryConfig){r&&i(!1),g(p),o(p);return}r||g(p),o(p)}function g(p){const j={...t,cards:t.cards.map(v=>v.id===a.id?a:v),activeCardId:p};l(j);const x=j.cards.find(v=>v.id===p);x.sql&&d(!0),c(x)}function b(){return a.type==="kpi"?m||h?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border border-border",children:e.jsx(s.KPICard,{card:a,data:u==null?void 0:u.records,isPending:m||h})})}):a.type==="text"?m||h?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border",children:e.jsx(s.ScrollArea,{className:"mx-3 my-6 h-[300px] overflow-y-auto break-words px-3",children:e.jsx(s.TextCard,{isLoading:n,card:a,data:u==null?void 0:u.records})})})}):e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(Tt,{className:"grow border-none shadow-none"})})}return e.jsxs(s.Tabs,{onValueChange:f,value:t.activeCardId,className:"flex grow flex-col",children:[t.cards.map(p=>e.jsx(s.TabsContent,{className:"mt-0 grow",value:p.id,children:b()},p.id)),e.jsx(ar,{})]})}function Je({children:t}){var R,N;s.useEditorStore(w=>w.frame);const a=s.useEditorStore(w=>w.card),n=s.useEditorStore(w=>w.isDevMode),r=s.useEditorStore(w=>w.isShowingVisual),l=s.useDashboardStore(w=>w.isVisualEditing),o=s.useEditorStore(w=>w.pythonStdOut);s.useEditorStore(w=>w.actions.setRunSql);const{setFrame:c,setCard:i,setActiveTabCardId:d,runAssistant:u,setIsDevMode:m,setCardPreferences:h}=s.useEditorActions(),{data:f,isLoading:g,isFetching:b,errorMessage:p,refetch:j}=s.useDashboardCardQuery(a);function x(){const w=JSON.stringify(f==null?void 0:f.records,null,2),y=new Blob([w],{type:"application/json"}),D=URL.createObjectURL(y),C=document.createElement("a");C.href=D,C.download=`${a.title}.json`,C.click()}function v(){const y=[Object.keys(f==null?void 0:f.records.reduce((S,F)=>({...S,...F}),{})).join(","),...((f==null?void 0:f.records)||[]).map(S=>Object.values(S).join(","))].join(`
|
|
353
|
-
`),D=new Blob([y],{type:"text/csv"}),C=URL.createObjectURL(D),I=document.createElement("a");I.href=C,I.download=`${a.title}.csv`,I.click()}function k(){const w=`Can you get the documentation for ${a.type} chart?`;u(w)}return a?e.jsxs("div",{className:"relative isolate flex h-full flex-col py-2 pb-3",children:[e.jsxs("div",{className:"z-10 mb-0 flex min-h-10 items-center justify-end gap-2 px-6",children:[r&&e.jsxs("div",{className:"flex grow items-center",children:[e.jsx(Mt,{}),l&&e.jsx(s.IconButton,{tooltip:"Visual Docs",onClick:k,children:e.jsx(ca,{className:"size-4"})}),!["table","custom"].includes(a.type)&&l&&e.jsx(Qn,{})]}),!r&&e.jsxs("div",{className:"flex grow items-center gap-1",children:[e.jsx(s.Button,{className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70",variant:"ghost",size:"icon",onClick:v,children:e.jsx(s.PiFileCsv,{className:"size-4"})}),e.jsx(s.Button,{className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70",variant:"ghost",size:"icon",onClick:x,children:e.jsx(ba,{strokeWidth:1.5,className:"size-4"})}),e.jsx(s.CopyButton,{text:JSON.stringify(f==null?void 0:f.records,null,2),className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[t,e.jsx(Lt,{})]}),a.type==="table"&&a.sql&&!s.hasValidCardConfig(a.config)&&e.jsxs("div",{className:"mr-2 flex items-center gap-3",children:[e.jsx(s.Checkbox,{id:"pagination",checked:((N=(R=a.preferences)==null?void 0:R.tablePrefs)==null?void 0:N.enableDevModePagination)??!1,onCheckedChange:w=>{var y;h({...a.preferences,tablePrefs:{...(y=a.preferences)==null?void 0:y.tablePrefs,enableDevModePagination:w}}),j()}}),e.jsx(s.Label,{htmlFor:"pagination",children:"Paginate Results"})]}),n&&e.jsx(rr,{})]}),r?e.jsx(Rt,{}):e.jsxs(s.ResizablePanelGroup,{className:"px-6",direction:"horizontal",children:[o&&e.jsxs(e.Fragment,{children:[e.jsx(s.ResizablePanel,{id:"1",order:1,defaultSize:30,minSize:10,className:"relative flex h-full min-h-0 w-full flex-1 basis-0",children:o&&e.jsx(nr,{})}),e.jsx(s.ResizableHandle,{})]}),e.jsxs(s.ResizablePanel,{id:"2",order:2,minSize:10,className:s.cn("relative flex h-full min-h-0 w-full flex-1 basis-0",{"px-6":o}),children:[(f==null?void 0:f.records)&&(f==null?void 0:f.records.length)>0&&e.jsx(s.TableVisual,{card:a,data:(f==null?void 0:f.records)||[]}),p&&e.jsx(sr,{error:p})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function nr(){const t=s.useEditorStore(n=>n.pythonStdOut);if(!t)return null;const a=t.replace(/\n/g,"<br>");return e.jsxs("div",{className:"relative flex w-full flex-col",children:[e.jsx("div",{className:"sticky top-0 flex max-h-11 min-h-11 grow items-center font-mono text-xs font-semibold text-foreground/70",children:"Python Output"}),e.jsxs(s.ScrollArea,{className:"overflow-y-auto pt-1 font-mono text-xs text-foreground/90",children:[e.jsx("div",{dangerouslySetInnerHTML:{__html:a}}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function rr(){const t=s.useEditorStore(n=>n.isShowingVisual),a=s.useEditorStore(n=>n.actions.setIsShowingVisual);return e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Label,{htmlFor:"visualize",children:"Chart"}),e.jsx(s.SmallSwitch,{checked:t,onCheckedChange:()=>a(!t),id:"visualize",className:"data-[state=checked]:bg-foreground/50"})]})}function lr(){var p,j;const t=s.useEditorStore(x=>x.card.customCardPreferences),{data:a}=Et(),n=(a==null?void 0:a.plugins)||[],r=s.useEditorStore(x=>x.card),l=s.useEditorStore(x=>x.frame),o=(t==null?void 0:t.visualType)||"single",{setCustomCardPreferences:c}=s.useEditorActions(),{components:i,manifest:d}=s.useCustomVisual((t==null?void 0:t.url)||""),u=(p=d==null?void 0:d.visuals)==null?void 0:p.find(x=>x.name===(t==null?void 0:t.componentName));function m(x,v){if(!t)return;const R={...(t==null?void 0:t.dataInputCardIds)||{},[x]:{cardId:v,hookRef:null}};c({...t,dataInputCardIds:R})}function h(x){var k,R;const v=(k=l==null?void 0:l.cards)==null?void 0:k.filter(N=>{var w;return((w=N==null?void 0:N.customCardPreferences)==null?void 0:w.visualType)!=="multiple"}).map(N=>({value:N.id,label:N.tabTitle||N.title}));return e.jsx("div",{className:"space-y-2",children:(R=x==null?void 0:x.dataInputs)==null?void 0:R.map((N,w)=>{var y,D;return e.jsxs("div",{className:"grid grid-cols-10 gap-2",children:[e.jsx("div",{className:"col-span-4 flex items-center",children:N}),e.jsx(fe,{className:"col-span-6 h-8 w-full justify-between",label:"",options:v||[],value:((D=(y=t==null?void 0:t.dataInputCardIds)==null?void 0:y[w])==null?void 0:D.cardId)||"",onValueChange:C=>m(w,C)})]},w+Math.random())})})}function f(x,v,k=[],R=""){var N,w;return t?x==="input"?e.jsx(s.Input,{className:`h-8 w-full ${s.removeRing}`,value:((N=t==null?void 0:t.settings)==null?void 0:N[v])||R,onChange:y=>{c({...t,settings:{...t==null?void 0:t.settings,[v]:y.target.value}})}},v):x==="select"?e.jsx(fe,{className:"h-8 w-full",label:"",options:k,value:((w=t==null?void 0:t.settings)==null?void 0:w[v])||R,onValueChange:y=>{c({...t,settings:{...t==null?void 0:t.settings,[v]:y}})}}):null:null}function g(x){const v=Object.entries((x==null?void 0:x.settings)||{});return e.jsx("div",{className:"space-y-3",children:v.map(([k,R])=>e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:R.title}),f(R.ui,k,R.options,R.defaultValue)]},k))})}function b(x){t&&c({...t,visualType:x,componentName:""})}return e.jsxs(s.Accordion,{type:"multiple",defaultValue:["component-settings"],className:"px-6 py-2",children:[e.jsxs(s.AccordionItem,{value:"plugin-settings",children:[e.jsx(s.AccordionTrigger,{children:"Plugin"}),e.jsx(s.AccordionContent,{children:e.jsxs("div",{className:"space-y-4 text-sm",children:[e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(fe,{icon:e.jsx(ia,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:n,value:(t==null?void 0:t.url)||"",onValueChange:x=>c({...t||{url:"",componentName:""},url:x})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&e.jsx(s.Tabs,{value:o,onValueChange:b,children:e.jsxs(s.TabsList,{className:"h-9 w-full",children:[e.jsx(s.TabsTrigger,{className:"h-7 w-full",value:"single",children:"Single Visual"}),e.jsx(s.TabsTrigger,{className:"h-7 w-full",value:"multiple",children:"Multi-Visual"})]})})]})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&t&&e.jsx(e.Fragment,{children:i&&e.jsx(fe,{icon:e.jsx(xa,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(i==null?void 0:i.filter(x=>x.type===o).map(x=>({value:x.name,label:x.name})))||[],value:t.componentName,onValueChange:x=>{console.log("changing value",x),c({...t,componentName:x})}})})]})})]}),((j=r==null?void 0:r.customCardPreferences)==null?void 0:j.componentName)&&e.jsxs(s.AccordionItem,{className:"border-none",value:"component-settings",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsxs(s.AccordionContent,{children:[u&&u.dataInputs&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Input Mapping"}),e.jsx("div",{className:"px-2",children:h(u)})]}),u&&u.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:g(u)})})]})]})]})}function Re(){const[t,a]=A.useState([]),n=s.useEditorStore(u=>u.card.preferences),{setFilterOnClickColumnIndex:r,setCardPreferences:l}=s.useEditorStore(u=>u.actions),o=s.useEditorStore(u=>u.queryResultColumns);s.useEditorStore(u=>{var m;return(m=u.card.preferences)==null?void 0:m.filterOnClickColumnIndex}),A.useEffect(()=>{o&&a(new Array(o.length).fill(!1))},[o]);function c(u,m){var h,f;m?n!=null&&n.onClickFilter&&((h=n==null?void 0:n.onClickFilter)==null?void 0:h.length)>0?l({...n,onClickFilter:[...n.onClickFilter,{columnIndex:u,expression:""}]}):l({...n,onClickFilter:[{columnIndex:u,expression:""}]}):(l({...n,onClickFilter:(f=n==null?void 0:n.onClickFilter)==null?void 0:f.filter(g=>g.columnIndex!==u)}),a(g=>{const b=[...g];return b[u]=!1,b}))}function i(u,m){var f;const h=(f=n==null?void 0:n.onClickFilter)==null?void 0:f.map(g=>g.columnIndex===u?{...g,expression:m.target.value}:g);l({...n,onClickFilter:h})}function d(u){var m,h,f,g;if(t!=null&&t[u]||(h=(m=n==null?void 0:n.onClickFilter)==null?void 0:m.find(b=>b.columnIndex===u))!=null&&h.expression)return e.jsx(s.Input,{value:(g=(f=n==null?void 0:n.onClickFilter)==null?void 0:f.find(b=>b.columnIndex===u))==null?void 0:g.expression,onChange:b=>i(u,b),type:"text",className:"h-9 w-full font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"Expression"})}return e.jsx("div",{className:"max-h-[150px] space-y-2 overflow-y-auto",children:o==null?void 0:o.map((u,m)=>{var h,f;return e.jsx("div",{className:"group flex items-center justify-between space-y-2",children:e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex items-center space-x-2 py-2",children:[e.jsx(s.Checkbox,{checked:!!((h=n==null?void 0:n.onClickFilter)!=null&&h.find(g=>g.columnIndex===m)),onCheckedChange:g=>c(m,g)}),e.jsx("label",{className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:u}),e.jsx("div",{className:"flex items-center gap-2",children:((f=n==null?void 0:n.onClickFilter)==null?void 0:f.find(g=>g.columnIndex===m))&&e.jsx(s.Pencil,{onClick:()=>{a(g=>{const b=[...g];return b[m]=!g[m],b})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),d(m)]})},u)})})}function or({idx:t}){var i;const a=s.useEditorStore(d=>{var u;return(u=d.card)==null?void 0:u.preferences}),n=s.useEditorStore(d=>{var u;return(u=d.card.preferences)==null?void 0:u.datasetOptions}),r=s.useEditorStore(d=>d.actions.setCardPreferences),l=(i=a==null?void 0:a.chartOptions)==null?void 0:i.indexAxis,o=n==null?void 0:n.find(d=>d.idx===t);function c(d,u){(d==="end"||d==="start")&&s.getContrastColor(s.getCanvasBackgroundColor());const m={display:d!=="none",align:d,anchor:d,clamp:!0};if(!o)r({...a,datasetOptions:[...n||[],{idx:u,datalabels:m}]});else{const h={...o};h.datalabels=m;const f=n==null?void 0:n.map(g=>g.idx===u?h:g);r({...a,datasetOptions:f})}}return e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{children:e.jsx(nt,{className:"size-4 rotate-[135deg] cursor-pointer text-muted-foreground hover:text-foreground"})}),e.jsx(s.PopoverContent,{className:"w-fit px-2 py-1",children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{onClick:()=>c("none",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(s.X,{className:"size-3.5"})}),e.jsx("button",{onClick:()=>c("start",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Da,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})}),e.jsx("button",{onClick:()=>c("center",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Ta,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})}),e.jsx("button",{onClick:()=>c("end",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(ka,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})})]})})]})}function ir(){const t=s.useEditorStore(o=>o.card),{data:a}=s.useDashboardCardQuery(t),{keys:n}=s.getKeys((a==null?void 0:a.records)||[]),r=n.slice(1).filter(o=>!s.METADATA_KEYS.includes(o));let l=r;if(["stackedBar","stackedLine"].includes(t.type)){const o=s.pivotData({dataArray:(a==null?void 0:a.records)||[],groupKey:n[0],pivotKey:n[1],valueKey:n[2]}),{keys:c}=s.getKeys(o);l=c.slice(1)}return{transformedMetricKeys:l,dimensionKeys:n.slice(0,1),keys:n,defaultMetricKeys:r}}function ls({children:t,className:a,delayDuration:n}){return e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{delayDuration:n,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:s.cn("overflow-hidden text-ellipsis whitespace-nowrap",a),children:t})}),e.jsx(s.TooltipContent,{children:t})]})})}function Ot(){const t=s.useEditorStore(d=>d.card),a=s.useEditorStore(d=>{var u,m,h;return(h=(m=(u=d==null?void 0:d.card)==null?void 0:u.preferences)==null?void 0:m.chartOptions)==null?void 0:h.indexAxis}),{data:n}=s.useDashboardCardQuery(t),r=a==="y"?"Metric":"Dimension",l=a==="y"?"Dimension":"Metric",{dimensionKeys:o,transformedMetricKeys:c,keys:i}=ir();return i.length===0?null:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:r}),e.jsx("div",{className:"max-h-[125px] space-y-1 overflow-y-auto",children:o.map(d=>e.jsx("p",{className:"flex h-8 items-center rounded-md bg-muted/70 px-3 hover:bg-muted",title:d,children:Bt(d)},d))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:l}),e.jsx("div",{className:"my-1 max-h-[125px] space-y-1 overflow-y-auto",children:c.map((d,u)=>e.jsx(Ft,{className:"flex h-8 items-center bg-muted/70 px-3 hover:bg-muted",iconClassName:"invisible group-hover:visible",col:d,idx:u},d))})]})]})}function Bt(t,a=30){return t.length>a?t.slice(0,a)+"...":t}function Ft({col:t,idx:a,className:n,iconClassName:r,children:l}){const o=s.useEditorStore(m=>{var h;return(h=m.card)==null?void 0:h.preferences}),c=s.useEditorStore(m=>{var h,f;return(f=(h=m.card)==null?void 0:h.preferences)==null?void 0:f.datasetOptions}),i=c==null?void 0:c.find(m=>m.idx===a),{setCardPreferences:d}=s.useEditorStore(m=>m.actions);function u(m){if(!i)d({...o,datasetOptions:[...c||[],{idx:a,type:m==="area"?"line":m,fill:m==="area"?"origin":""}]});else{const h={...i};h.type=m==="area"?"line":m,h.fill=m==="area"?"origin":"";const f=c==null?void 0:c.map(g=>g.idx===a?h:g);d({...o,datasetOptions:f})}}return e.jsxs("div",{className:s.cn("group flex items-center justify-between gap-2 rounded-md",n),children:[l||e.jsx(ls,{className:"max-w-[100px]",title:t,children:Bt(t)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.ChartColumnIncreasing,{onClick:()=>u("bar"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(s.ChartLine,{onClick:()=>u("line"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(s.ChartArea,{onClick:()=>u("area"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(or,{idx:a})]})]})}function ks(){const t=s.useEditorStore(g=>g.selectedConnectionId),a=s.useEditorStore(g=>g.selectedDatamodelId),n=s.useEditorStore(g=>g.selectedDatabaseName),r=s.useEditorStore(g=>g.selectedSchemaName),l=s.useEditorStore(g=>g.selectedTableName),o=s.useDashboardStore(g=>g.dashboard.filters)||[],c=s.useDashboardStore(g=>g.actions.addFilter),i=s.useDashboardStore(g=>g.actions.removeFilter),{removeFilterValues:d}=s.useDashboardActions(),{modelItems:u,tableName:m,connectionType:h}=s.useEditorAside();function f(g,b="dashboard",p){var D;const j=s.fmt(g.column_name),x=s.fmt(n||""),v=s.fmt(r||""),k=s.fmt(m);let R=s.getQualifiedTableName({schemaName:v,tableName:k,connectionType:h,databaseName:x}),N=`${R}.${j}`;const w=(D=u==null?void 0:u.find(C=>C.id===a))==null?void 0:D.name;a&&a!=="none"&&(N=`${s.DATAMODEL_NAMESPCACE}.${w}.${j}`,R=`${s.DATAMODEL_NAMESPCACE}.${w}`),p!=null&&p.qualifiedFieldName&&(N=p.qualifiedFieldName),p!=null&&p.entityName&&(R=p.entityName);const y=o==null?void 0:o.find(C=>C.column===N&&C.table===k&&(C.database===x||C.database===n));if(y)d(y.id),i(y.id);else{const C=s.v4();return m==="api"&&t?(c({location:b,id:C,column:N,title:g.column_name,dataType:g.data_type,table:"api",database:"",connectionId:t,operation:"in",sql:s.getDefaultFilterSql(g.data_type,R,j)}),C):(c({id:C,location:b,column:N,title:g.column_name,dataType:g.data_type,table:l||"",database:n||"",connectionId:t||"",operation:"in",sql:s.getDefaultFilterSql(g.data_type,R,j)}),C)}}return{assignFilter:f}}function Pe(){const t=s.useDashboardStore(i=>i.dashboard.filters),a=s.useEditorStore(i=>i.frame),{setFrame:n}=s.useEditorActions(),{columns:r}=s.useEditorAside(),{assignFilter:l}=ks();function o(i){const d=l(i,"frame");n({...a,filterId:d})}const c=t==null?void 0:t.find(i=>i.id===a.filterId);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Card Filter"}),e.jsx(cr,{onSelect:o,columns:r}),c&&e.jsx(s.FilterHeader,{filter:c})]})}function cr({columns:t,onSelect:a}){var c;const[n,r]=Te.useState(!1),[l,o]=Te.useState("");return e.jsxs(s.Popover,{open:n,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{size:"sm",variant:"outline",role:"combobox","aria-expanded":n,className:"w-full justify-between font-normal",children:[l?(c=t.find(i=>i.column_name===l))==null?void 0:c.column_name:"Select Column...",e.jsx(s.CaretSortIcon,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[200px] p-0",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search column",className:"h-9"}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No framework found."}),e.jsx(s.CommandGroup,{children:t==null?void 0:t.map(i=>e.jsxs(s.CommandItem,{value:i.column_name,onSelect:d=>{const u=d===l?"":d;o(u),r(!1),u&&a(i)},children:[i.column_name,e.jsx(s.CheckIcon,{className:s.cn("ml-auto h-4 w-4",l===i.column_name?"opacity-100":"opacity-0")})]},i.column_name))})]})]})})]})}function dr({cardType:t}){return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} Chart`}),e.jsxs(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT x-axis, y-axis-1, y-axis-2,... FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"x-axis - category"}),e.jsx("li",{children:"y-axis1 - number"}),e.jsx("li",{children:"y-axis2 - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:a=>a.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bar-line-area",children:"example"})," in the docs."]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsx(s.AccordionContent,{className:"space-y-4 px-2",children:e.jsx(Ot,{})})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Re,{}),e.jsx(Pe,{})]})]})]})})}function ur({cardType:t}){function a(n){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:n==="bubble"?"SELECT label, [group], x-axis, y-axis, radius FROM table":"SELECT label, [group], x-axis, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"group (optional) - category"}),e.jsx("li",{children:"x-axis - number"}),e.jsx("li",{children:"y-axis - number"}),n==="bubble"&&e.jsx("li",{children:"radius - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:o=>o.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bubble",children:"example"})," in the docs."]})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} Chart`}),e.jsx(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:a(t)})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Re,{}),e.jsx(Pe,{})]})]})]})})}function Pt(){const t=s.useEditorStore(i=>i.card.type),a=s.useEditorStore(i=>i.isDevMode),n=s.useEditorStore(i=>i.card.preferences),{setCardPreferences:r}=s.useEditorStore(i=>i.actions);function l(i){var m;const d={datalabels:{display:i!=="none",align:i,anchor:i,clamp:!0}},u={...n,chartOptions:{...n==null?void 0:n.chartOptions,plugins:{...(m=n==null?void 0:n.chartOptions)==null?void 0:m.plugins,...d}}};r(u)}function o(){var i,d,u;return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"font-medium",children:"Data Labels"}),e.jsxs(s.Select,{value:((u=(d=(i=n==null?void 0:n.chartOptions)==null?void 0:i.plugins)==null?void 0:d.datalabels)==null?void 0:u.anchor)||"none",onValueChange:l,defaultValue:"none",children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{placeholder:"Select position"})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Data Labels"}),e.jsx(s.SelectItem,{value:"none",children:"None"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{value:"start",children:"Start"}),e.jsx(s.SelectItem,{value:"center",children:"Center"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{value:"end",children:"End"})]})})]})]})}function c(){var i,d,u;return e.jsx("div",{children:e.jsxs(s.Select,{value:((u=(d=(i=n==null?void 0:n.chartOptions)==null?void 0:i.plugins)==null?void 0:d.datalabels)==null?void 0:u.anchor)||"none",onValueChange:l,defaultValue:"none",children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select position"})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"none",children:"None"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{className:"text-xs",value:"start",children:"Start"}),e.jsx(s.SelectItem,{className:"text-xs",value:"center",children:"Center"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{className:"text-xs",value:"end",children:"End"})]})})]})})}return e.jsx(e.Fragment,{children:a?o():c()})}const mr={datasets:[{type:"line",label:"Sum_sales",data:[]},{type:"bar",label:"Sum_profit",data:[]}]},hr={datasets:[{fill:"origin",type:"line",label:"Sum_sales",data:[]}]};function xr(){const t=s.useEditorStore(a=>a.card.type);return e.jsxs("div",{className:"space-y-6 p-6",children:[e.jsx(s.Accordion,{className:" ",type:"single",collapsible:!0,children:pr(t)}),!["kpi"].includes(t)&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(Pt,{}),e.jsx(Re,{}),e.jsx(Pe,{})]})]})}function pr(t){if(["line","bar"].includes(t))return e.jsxs(e.Fragment,{children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsx("p",{children:"Chart Query"})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT x-axis, y-axis-1, y-axis-2, y-axis-3,... FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"X-axis - Category (ex. city)"}),e.jsx("li",{children:"Y-axis - Number (ex. population)"})]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:"Mixed Chart"}),e.jsxs(s.AccordionContent,{className:"space-y-2 text-xs",children:[e.jsxs("p",{children:["Click ",e.jsx("b",{children:"Customize"})," and change the `type` property in the dataset."]}),e.jsx("pre",{children:JSON.stringify(mr,null,2)})]})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:"Area Chart"}),e.jsxs(s.AccordionContent,{className:"space-y-2 text-xs",children:[e.jsxs("p",{children:["Click ",e.jsx("b",{children:"Customize"})," and add `fill` property to the dataset. See",e.jsx("a",{className:"mx-1 text-blue-500 hover:underline",href:"https://www.chartjs.org/docs/latest/samples/area/line-boundaries.html",target:"_blank",children:"docs"}),"for more options."]}),e.jsx("pre",{children:JSON.stringify(hr,null,2)})]})]})]});if(t==="bubble")return e.jsx(e.Fragment,{children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:["How to create a ",e.jsx("span",{children:t})," chart query?"]})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, x-axis, y-axis, radius FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Bubble Group (opt) - Category (ex. state)"}),e.jsx("li",{children:"X-axis - Number (ex. avg. age)"}),e.jsx("li",{children:"Y-axis - Number (ex. avg. weight)"}),e.jsx("li",{children:"Radius - Number (ex. population)"})]})]})]})});if(t==="scatter")return e.jsx(e.Fragment,{children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:["How to create a ",e.jsx("span",{children:t})," chart query?"]})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, x-axis, y-axis FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Group (opt) - Category (ex. state)"}),e.jsx("li",{children:"X-axis - Number (ex. avg. age)"}),e.jsx("li",{children:"Y-axis - Number (ex. avg. weight)"})]})]})]})});if(["pie","doughnut","polarArea","funnel"].includes(t))return e.jsx(e.Fragment,{children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:[e.jsx("span",{children:t==="polarArea"?"Polar":t.charAt(0).toUpperCase()+t.slice(1)})," ","chart query"]})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, measure FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Measure - Number (ex. population)"})]})]})]})})}function fr({colorRanges:t,setColorRanges:a}){const n={start:-1/0,end:100,color:""};function r(c,i,d){const u=[...t];u[c]={...u[c],[i]:d},a(u)}function l(c){const i=[...t];i.splice(c,1),a(i)}function o(){a([...t,n])}return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{children:"Color Range"}),e.jsx(s.Button,{onClick:o,variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.Plus,{className:"size-3"})})]}),t.map((c,i)=>e.jsxs("div",{className:"flex items-center gap-2 px-2",children:[e.jsx(s.Input,{onChange:d=>r(i,"start",d.target.value),value:c.start,className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx("span",{children:"-"}),e.jsx(s.Input,{value:c.end,onChange:d=>r(i,"end",d.target.value),className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx(s.Input,{onChange:d=>r(i,"color",d.target.value),value:c.color,className:s.cn(`h-7 min-w-14 p-0 ${s.removeRing}`),type:"color",list:"presetColors"}),e.jsxs("datalist",{id:"presetColors",children:[e.jsx("option",{children:s.colors$1.green[600]}),e.jsx("option",{children:s.colors$1.red[500]}),e.jsx("option",{children:s.colors$1.yellow[400]}),e.jsx("option",{children:s.colors$1.orange[500]})]}),e.jsx(s.Button,{onClick:()=>l(i),variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.X,{className:"size-3"})})]},i))]})}function gr(){var m,h,f,g,b;const t=s.useEditorStore(p=>p.card.preferences),a=s.useEditorStore(p=>p.actions.setCardPreferences),n=s.useEditorStore(p=>p.card),r=s.isExplorerCard(n),l=s.useEditorStore(p=>p.actions.setNumberFormat);s.useEditorStore(p=>{var j,x;return(x=(j=p.card.preferences)==null?void 0:j.formatNumber)==null?void 0:x.decimalPlaces});const o=s.useEditorStore(p=>{var j,x;return(x=(j=p.card.preferences)==null?void 0:j.formatNumber)==null?void 0:x.locale}),c=s.useEditorStore(p=>{var j,x;return(x=(j=p.card.preferences)==null?void 0:j.formatNumber)==null?void 0:x.currency});s.useEditorStore(p=>p.actions.setFilterOnClickField);const i=s.useEditorStore(p=>{var j,x;return(x=(j=p.card.preferences)==null?void 0:j.formatNumber)==null?void 0:x.colorRanges})||[],d=s.useEditorStore(p=>p.actions.setColorRanges),u=[...new Set(s.LOCALE_CURRENCY_PAIRS.map(p=>p.currency))];return e.jsxs("div",{children:[!r&&e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx(s.Checkbox,{checked:!!((m=t==null?void 0:t.formatNumber)!=null&&m.enabled),onCheckedChange:p=>{a({...t,formatNumber:{...t==null?void 0:t.formatNumber,enabled:p}})}}),e.jsx(s.Label,{children:"Format Number"})]}),(((h=t==null?void 0:t.formatNumber)==null?void 0:h.enabled)===!0||r)&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("div",{children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Locale"}),e.jsxs(s.Select,{value:o||"none",onValueChange:p=>{var j,x,v;return l(((j=t==null?void 0:t.formatNumber)==null?void 0:j.decimalPlaces)||0,((x=t==null?void 0:t.formatNumber)==null?void 0:x.currency)||"",p,((v=t==null?void 0:t.formatNumber)==null?void 0:v.suffix)||"")},children:[e.jsx(s.SelectTrigger,{className:"col-span-6 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Format"}),e.jsx(s.SelectItem,{value:"none",children:"Auto"},"none"),s.LOCALE_CURRENCY_PAIRS.map(p=>e.jsx(s.SelectItem,{value:p.locale,children:p.locale},p.locale))]})})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Currency"}),e.jsxs(s.Select,{value:c||"none",onValueChange:p=>{var j,x,v;console.log("currency",p),l(((j=t==null?void 0:t.formatNumber)==null?void 0:j.decimalPlaces)||0,p==="none"?"":p,((x=t==null?void 0:t.formatNumber)==null?void 0:x.locale)||"",((v=t==null?void 0:t.formatNumber)==null?void 0:v.suffix)||"")},children:[e.jsx(s.SelectTrigger,{className:"col-span-6 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Currency"}),e.jsx(s.SelectItem,{value:"none",children:"None"},"none"),u.map(p=>e.jsx(s.SelectItem,{value:p,children:p},p))]})})]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Decimals"}),e.jsxs(s.Select,{value:((g=(f=t==null?void 0:t.formatNumber)==null?void 0:f.decimalPlaces)==null?void 0:g.toString())||"0",onValueChange:p=>{var j,x,v;return l(Number(p),((j=t==null?void 0:t.formatNumber)==null?void 0:j.currency)||"",((x=t==null?void 0:t.formatNumber)==null?void 0:x.locale)||"",((v=t==null?void 0:t.formatNumber)==null?void 0:v.suffix)||"")},children:[e.jsx(s.SelectTrigger,{className:"col-span-3 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:["0","1","2","3","4"].map(p=>e.jsx(s.SelectItem,{value:p,children:p},p))})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Suffix"}),e.jsx(s.Input,{value:((b=t==null?void 0:t.formatNumber)==null?void 0:b.suffix)||"",className:"h-8 font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"K, M, B, %",onChange:p=>{var j,x,v;return l(((j=t==null?void 0:t.formatNumber)==null?void 0:j.decimalPlaces)||0,((x=t==null?void 0:t.formatNumber)==null?void 0:x.currency)||"",((v=t==null?void 0:t.formatNumber)==null?void 0:v.locale)||"",p.target.value)}})]})]})]})}),e.jsx(s.Separator,{className:"my-3"}),e.jsx(fr,{colorRanges:i,setColorRanges:d})]})]})}function jr(){return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsx(s.Accordion,{type:"single",collapsible:!0,children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"",children:"KPI Query"}),e.jsxs(s.AccordionContent,{className:"font-mono",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs",children:"SELECT current, previous FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"current - number"}),e.jsx("li",{children:"previous - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/kpi",children:"example"})," in the docs."]})]})]})}),e.jsx("section",{className:"",children:e.jsx(gr,{})}),e.jsx("div",{}),e.jsx("div",{})]})}function hs({children:t,summary:a,open:n,className:r}){return e.jsxs("details",{open:n,className:s.cn("space-y-4 [&_summary>svg]:open:-rotate-180",r),children:[e.jsxs("summary",{className:"flex cursor-pointer list-none items-center justify-between gap-4",children:[e.jsx(s.Label,{children:a}),e.jsx(s.ChevronUp,{className:"h-4 w-4"})]}),e.jsx("div",{className:"transition-all ease-in-out",children:t})]})}const br=[{label:"Mercator",value:"mercator"},{label:"Azimuthal Equidistant",value:"azimuthalEquidistant"},{label:"Gnomonic",value:"gnomonic"},{label:"Orthographic",value:"orthographic"},{label:"Stereographic",value:"stereographic"},{label:"Equal Earth",value:"equalEarth"},{label:"Albers",value:"albers"},{label:"Albers USA",value:"albersUsa"},{label:"Conic Conformal",value:"conicConformal"},{label:"Conic Equal Area",value:"conicEqualArea"},{label:"Conic Equidistant",value:"conicEquidistant"},{label:"Equirectangular",value:"equirectangular"},{label:"Transverse Mercator",value:"transverseMercator"},{label:"Natural Earth 1",value:"naturalEarth1"}],yr=["blues","brBG","buGn","buPu","cividis","cool","cubehelixDefault","gnBu","greens","greys","inferno","magma","orRd","oranges","pRGn","piYG","plasma","puBu","puBuGn","puOr","puRd","purples","rainbow","rdBu","rdGy","rdPu","rdYlBu","rdYlGn","reds","sinebow","spectral","turbo","viridis","warm","ylGn","ylGnBu","ylOrBr","ylOrRd"],vr=yr.map(t=>({label:t,value:t}));function Nr(){var d,u,m,h,f,g,b,p,j,x,v,k,R,N,w,y,D,C;const t=s.useEditorStore(I=>I.card),a=(u=(d=t==null?void 0:t.preferences)==null?void 0:d.mapVisualOptions)==null?void 0:u.topoJsonUrl,[n,r]=A.useState(((h=(m=t==null?void 0:t.preferences)==null?void 0:m.mapVisualOptions)==null?void 0:h.customTopoJsonUrl)||""),{setCardPreferences:l}=s.useEditorActions(),{data:o}=s.useTopoJson(t),c=Object.keys((o==null?void 0:o.objects)||{}).map(I=>({label:I,value:I}))||[],i=[{label:"US States 10m",value:"https://unpkg.com/us-atlas/states-10m.json"},{label:"Countries 50m",value:"https://unpkg.com/world-atlas/countries-50m.json"},{label:"Custom",value:"custom"}];return e.jsxs("div",{className:"p-6",children:[e.jsx(hs,{summary:"Map Chart",children:e.jsx("p",{className:"rounded-md bg-muted p-2 font-mono text-xs",children:"SELECT country, value FROM table"})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(hs,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(fe,{className:"h-9",options:i,onValueChange:I=>{console.log("value",I),l({...t.preferences,mapVisualOptions:{topoJsonUrl:I}})},value:a||"",label:"Select Map"}),a==="custom"&&e.jsx(s.Input,{onChange:I=>{r(I.target.value)},onBlur:()=>{var I;console.log("onBlur",n),l({...t.preferences,mapVisualOptions:{...(I=t.preferences)==null?void 0:I.mapVisualOptions,customTopoJsonUrl:n}})},value:n,className:`h-9 w-full ${s.removeRing}`,placeholder:"Custom URL"}),o&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Map Object"}),e.jsx(fe,{className:"h-9",options:c,value:((g=(f=t.preferences)==null?void 0:f.mapVisualOptions)==null?void 0:g.objectKey)||"",label:"Map Object",onValueChange:I=>{var S;l({...t.preferences,mapVisualOptions:{...(S=t.preferences)==null?void 0:S.mapVisualOptions,objectKey:I}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Projection"}),e.jsx(fe,{className:"h-9",options:br,value:((p=(b=t.preferences)==null?void 0:b.mapVisualOptions)==null?void 0:p.projection)||"",label:"Projection",onValueChange:I=>{var S;l({...t.preferences,mapVisualOptions:{...(S=t.preferences)==null?void 0:S.mapVisualOptions,projection:I}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Colors"}),e.jsx(fe,{className:"h-9",options:vr,value:((x=(j=t.preferences)==null?void 0:j.mapVisualOptions)==null?void 0:x.colorScale)||"",label:"Select Color Scale",onValueChange:I=>{var S;l({...t.preferences,mapVisualOptions:{...(S=t.preferences)==null?void 0:S.mapVisualOptions,colorScale:I}})}})]})]})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(hs,{className:"",summary:"Scale Options",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:.1,value:((k=(v=t.preferences)==null?void 0:v.mapVisualOptions)==null?void 0:k.projectionScale)||1,onChange:I=>{var S;l({...t.preferences,mapVisualOptions:{...(S=t.preferences)==null?void 0:S.mapVisualOptions,projectionScale:Number(I.target.value)}})}}),e.jsx(s.Label,{children:"X"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((w=(N=(R=t.preferences)==null?void 0:R.mapVisualOptions)==null?void 0:N.projectionOffset)==null?void 0:w[0])||0,onChange:I=>{var S,F,T,E;l({...t.preferences,mapVisualOptions:{...(S=t.preferences)==null?void 0:S.mapVisualOptions,projectionOffset:[Number(I.target.value),((E=(T=(F=t.preferences)==null?void 0:F.mapVisualOptions)==null?void 0:T.projectionOffset)==null?void 0:E[1])||0]}})}}),e.jsx(s.Label,{children:"Y"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((C=(D=(y=t.preferences)==null?void 0:y.mapVisualOptions)==null?void 0:D.projectionOffset)==null?void 0:C[1])||0,onChange:I=>{var S,F,T,E;l({...t.preferences,mapVisualOptions:{...(S=t.preferences)==null?void 0:S.mapVisualOptions,projectionOffset:[((E=(T=(F=t.preferences)==null?void 0:F.mapVisualOptions)==null?void 0:T.projectionOffset)==null?void 0:E[0])||0,Number(I.target.value)]}})}})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(Re,{})]})}function Cr(){var r;const t=s.useEditorStore(l=>l.card.preferences),{setCardPreferences:a}=s.useEditorStore(l=>l.actions);function n(l){a({...t,textVisualOptions:{...t==null?void 0:t.textVisualOptions,isDynamicText:l==="dynamic"}})}return e.jsxs(s.RadioGroup,{value:(r=t==null?void 0:t.textVisualOptions)!=null&&r.isDynamicText?"dynamic":"static",onValueChange:n,className:"flex gap-3",defaultValue:"x",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"static",id:"r1"}),e.jsx("label",{className:"text-sm",htmlFor:"r1",children:"Static"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"dynamic",id:"r2"}),e.jsx("label",{className:"text-sm",htmlFor:"r2",children:"Dynamic"})]})]})}function Qe({cardType:t,docContent:a,suffix:n="Chart"}){let r="pie-donut-polar";return t==="funnel"&&(r="funnel"),e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} ${n}`}),e.jsx(s.AccordionContent,{children:a||e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT label, measure FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"measure - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:l=>l.stopPropagation(),className:"text-blue-700",href:`https://docs.semaphor.cloud/docs/charts/${r}`,children:"example"})," in the docs."]})]})})]}),t==="text"&&e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsx(s.AccordionContent,{className:"space-y-4 px-2 py-4",children:e.jsx(Cr,{})})]}),!["range","text"].includes(t)&&e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Re,{}),e.jsx(Pe,{})]})]})]})})}function Sr(){const t=s.useEditorStore(r=>{var l,o;return(o=(l=r==null?void 0:r.card)==null?void 0:l.preferences)==null?void 0:o.sortChart}),{setSortChart:a}=s.useEditorActions();function n(){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Sort"}),e.jsx(fe,{className:"h-8",label:"Sort Chart",options:[{label:"None",value:"none"},{label:"ASC",value:"asc"},{label:"DESC",value:"desc"}],value:t||"none",onValueChange:r=>{a(r)}})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:"Stacked Chart"}),e.jsxs(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT x-axis, stack-by, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"x-axis - category"}),e.jsx("li",{children:"stack by - category"}),e.jsx("li",{children:"y-axis - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:r=>r.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/stacked",children:"example"})," in the docs."]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[n(),e.jsx(Ot,{})]})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Re,{}),e.jsx(Pe,{})]})]})]})})}function wr({cardType:t="table"}){console.log("cardType",t);const a=s.useEditorStore(l=>{var o;return(o=l.card)==null?void 0:o.preferences}),n=s.useEditorStore(l=>l.actions.setCardPreferences),r=l=>{n({...a,allowDownload:l})};return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsx(s.Accordion,{defaultValue:["item-3"],type:"multiple",children:e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Re,{}),e.jsx(Pe,{})]})]})}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{onCheckedChange:r,id:"allow-download"}),e.jsx("label",{htmlFor:"allow-download",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Allow Download"})]})]})}function zt({color:t,onColorChange:a,onClose:n}){const[r,l]=A.useState(0),[o,c]=A.useState(100),[i,d]=A.useState(50),[u,m]=A.useState(t);A.useEffect(()=>{const j=Ys(t);if(j){const x=qs(j.r,j.g,j.b);l(x.h),c(x.s),d(x.l),m(t)}},[t]);const h=j=>{l(j),g(j,o,i)},f=j=>{const x=j.currentTarget.getBoundingClientRect(),v=Math.max(0,Math.min(1,(j.clientX-x.left)/x.width)),k=Math.max(0,Math.min(1,(j.clientY-x.top)/x.height)),R=v*100,N=(1-k)*100;c(R),d(N),g(r,R,N)},g=(j,x,v)=>{const k=kr(j,x,v),R=Dr(k.r,k.g,k.b);m(R)},b=j=>{if(m(j),/^#[0-9A-Fa-f]{6}$/.test(j)){const x=Ys(j);if(x){const v=qs(x.r,x.g,x.b);l(v.h),c(v.s),d(v.l)}}},p=()=>{/^#[0-9A-Fa-f]{6}$/.test(u)&&(a(u),n())};return e.jsxs("div",{className:"p-4 space-y-4 w-[320px]",children:[e.jsxs("div",{className:"relative h-[200px] rounded cursor-crosshair",style:{background:`hsl(${r}, 100%, 50%)`},onClick:f,onMouseMove:j=>{j.buttons===1&&f(j)},children:[e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to right, white, transparent)"}}),e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to bottom, transparent, black)"}}),e.jsx("div",{className:"absolute w-4 h-4 -ml-2 -mt-2 rounded-full border-2 border-white shadow-md",style:{left:`${o}%`,top:`${100-i}%`,backgroundColor:u}})]}),e.jsx("div",{className:"space-y-2",children:e.jsx("input",{type:"range",min:"0",max:"360",value:r,onChange:j=>h(Number(j.target.value)),className:"w-full h-4 rounded-lg appearance-none cursor-pointer",style:{background:"linear-gradient(to right, #ff0000, #ffff00, #00ff00, #00ffff, #0000ff, #ff00ff, #ff0000)"}})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"HEX"}),e.jsx(s.Input,{value:u,onChange:j=>b(j.target.value),placeholder:"#000000",className:"font-mono"})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full border shadow-sm",style:{backgroundColor:t}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"CURRENT"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full border shadow-sm",style:{backgroundColor:u}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"NEW"})]})]}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(s.Button,{variant:"outline",onClick:n,children:"Cancel"}),e.jsx(s.Button,{onClick:p,children:"OK"})]})]})}function Ys(t){const a=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);return a?{r:parseInt(a[1],16),g:parseInt(a[2],16),b:parseInt(a[3],16)}:null}function Dr(t,a,n){return"#"+((1<<24)+(t<<16)+(a<<8)+n).toString(16).slice(1)}function qs(t,a,n){t/=255,a/=255,n/=255;const r=Math.max(t,a,n),l=Math.min(t,a,n);let o=0,c=0;const i=(r+l)/2;if(r!==l){const d=r-l;switch(c=i>.5?d/(2-r-l):d/(r+l),r){case t:o=((a-n)/d+(a<n?6:0))/6;break;case a:o=((n-t)/d+2)/6;break;case n:o=((t-a)/d+4)/6;break}}return{h:Math.round(o*360),s:Math.round(c*100),l:Math.round(i*100)}}function kr(t,a,n){t/=360,a/=100,n/=100;let r,l,o;if(a===0)r=l=o=n;else{const c=(u,m,h)=>(h<0&&(h+=1),h>1&&(h-=1),h<.16666666666666666?u+(m-u)*6*h:h<.5?m:h<.6666666666666666?u+(m-u)*(.6666666666666666-h)*6:u),i=n<.5?n*(1+a):n+a-n*a,d=2*n-i;r=c(d,i,t+1/3),l=c(d,i,t),o=c(d,i,t-1/3)}return{r:Math.round(r*255),g:Math.round(l*255),b:Math.round(o*255)}}const Tr=["#000000","#ffffff","#6b7280","#dc2626","#ea580c","#ca8a04","#16a34a","#0891b2","#2563eb","#7c3aed","#c026d3","#e11d48","#0f172a","#f3f4f6","#fbbf24"];function Vt(){var k,R,N,w,y,D,C,I,S,F;const t=s.useEditorStore(T=>T.card),a=s.useEditorStore(T=>{var E;return(E=T.card)==null?void 0:E.preferences}),{setCardPreferences:n,updateCardInFrame:r}=s.useEditorActions(),{data:l}=s.useDashboardCardQuery(t),[o,c]=A.useState({}),[i,d]=A.useState(null),[u,m]=A.useState(null),h=A.useMemo(()=>{var B,L,O,P,K,$,te;if(!(l!=null&&l.records)||l.records.length===0)return[];const T=(t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine",E=(t==null?void 0:t.type)==="bar"||(t==null?void 0:t.type)==="line",M=((B=t==null?void 0:t.config)==null?void 0:B.pivotByColumns)&&t.config.pivotByColumns.length>0;if((T||E)&&M){if(l.pivotSchema&&Array.isArray(l.pivotSchema)){const X=new Set;return l.pivotSchema.forEach(q=>{q.alias&&X.add(q.alias)}),Array.from(X)}if(l.records.length>0){const X=l.records[0],q=Object.keys(X),H=new Set;(L=t==null?void 0:t.config)!=null&&L.groupByColumns&&t.config.groupByColumns.forEach(z=>{H.add(z.label||z.name),H.add(z.alias||z.name)});const _=new Set;return(O=t==null?void 0:t.config)!=null&&O.metricColumns&&t.config.metricColumns.forEach(z=>{const U=z.alias||z.name;_.add(U),_.add(`${U}_count`),_.add(`${U}_sum`),_.add(`${U}_avg`),_.add(`${U}_min`),_.add(`${U}_max`);const Z=z.entityName||z.qualifiedEntityName;Z&&(_.add(`${Z}_${U}`),_.add(`${Z}_${U}_count`))}),q.filter(z=>!H.has(z)&&!_.has(z))}}if((E||T)&&!M&&((K=(P=t==null?void 0:t.config)==null?void 0:P.metricColumns)!=null&&K.length))return t.config.metricColumns.map(X=>X.alias||X.label||X.name);if((te=($=t==null?void 0:t.config)==null?void 0:$.groupByColumns)!=null&&te.length){const X=t.config.groupByColumns[0],q=X.label||X.name,H=new Set;return l.records.forEach(_=>{const J=_[q];J!=null&&H.add(String(J))}),Array.from(H)}return[]},[l,(k=t==null?void 0:t.config)==null?void 0:k.groupByColumns,(R=t==null?void 0:t.config)==null?void 0:R.pivotByColumns,(N=t==null?void 0:t.config)==null?void 0:N.metricColumns,t==null?void 0:t.type]),f=A.useMemo(()=>s.getDefaultChartColors(),[]);A.useEffect(()=>{const T={};h.forEach((E,M)=>{T[E]=s.getColorForValue(E,M,a==null?void 0:a.colorConfig)}),c(T)},[h,a==null?void 0:a.colorConfig,f]);const g=(T,E)=>{const M={...o,[T]:E};c(M);const B={...a||{},colorConfig:{segments:M}};n(B);const L={...t,preferences:B};r(L)},b=(T,E)=>{var K;const M=f[E%f.length],{[T]:B,...L}=((K=a==null?void 0:a.colorConfig)==null?void 0:K.segments)||{},O={...a||{},colorConfig:{segments:L}};n(O);const P={...t,preferences:O};r(P),c($=>({...$,[T]:M}))};if(!h.length||!((t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine"?((y=(w=t==null?void 0:t.config)==null?void 0:w.groupByColumns)==null?void 0:y.length)||((C=(D=t==null?void 0:t.config)==null?void 0:D.pivotByColumns)==null?void 0:C.length):(S=(I=t==null?void 0:t.config)==null?void 0:I.groupByColumns)==null?void 0:S.length)||["table","kpi","text","custom"].includes(t.type))return null;const x=()=>{const T={...a||{},colorConfig:{segments:{}}};n(T);const E={...t,preferences:T};r(E);const M={};h.forEach((B,L)=>{M[B]=s.getColorForValue(B,L,void 0)}),c(M)},v=Object.keys(((F=a==null?void 0:a.colorConfig)==null?void 0:F.segments)||{}).length>0;return e.jsxs(s.AccordionItem,{value:"colors",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fa,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Colors"})]})}),e.jsx(s.AccordionContent,{className:"",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"space-y-2",children:e.jsx("div",{className:"flex items-center justify-between",children:v&&e.jsxs("button",{className:"ml-auto flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",onClick:x,children:[e.jsx(s.RotateCcw,{className:"h-3 w-3"}),"Reset All"]})})}),e.jsx("div",{className:"max-h-[200px] space-y-2 overflow-y-auto pr-1",children:h.map((T,E)=>{const M=s.isDefaultColor(o[T],E),B=!M;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Popover,{open:i===T,onOpenChange:L=>d(L?T:null),children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx("button",{className:"h-5 w-5 shrink-0 rounded border border-input shadow-sm transition-colors hover:border-gray-400 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",style:{backgroundColor:o[T]}})}),e.jsx(s.PopoverContent,{align:"start",className:"w-auto p-3",children:e.jsxs("div",{className:"space-y-2.5",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Theme Colors"}),e.jsx("div",{className:"grid grid-cols-5 gap-1.5",children:f.slice(0,10).map((L,O)=>e.jsxs("button",{className:s.cn("relative h-5 w-5 rounded border-2 transition-all hover:scale-110",o[T]===L?"border-gray-900":"border-transparent"),style:{backgroundColor:L},onClick:()=>{g(T,L),d(null)},children:[O===E%f.length&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("div",{className:"rounded-full bg-white/90 px-0.5 text-[8px] font-bold text-gray-900 shadow-sm",children:"D"})}),e.jsx("span",{className:"sr-only",children:L})]},`default-${O}`))})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Popular Colors"}),e.jsx("div",{className:"grid grid-cols-5 gap-1.5",children:Tr.map((L,O)=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border transition-all hover:scale-110",o[T]===L?"border-2 border-gray-900":L==="#ffffff"?"border border-gray-300":"border border-transparent"),style:{backgroundColor:L},onClick:()=>{g(T,L),d(null)},children:e.jsx("span",{className:"sr-only",children:L})},`preset-${O}`))})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2 pt-1",children:[e.jsx("button",{className:"text-sm font-medium text-blue-600 hover:text-blue-700",onClick:()=>{m({value:T,color:o[T]}),d(null)},children:"Custom color"}),!M&&e.jsxs("button",{className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",onClick:()=>{b(T,E),d(null)},children:[e.jsx(s.RotateCcw,{className:"h-3 w-3"}),"Reset"]})]})]})})]}),e.jsx("span",{className:"flex-1 truncate text-sm",children:T}),B&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(custom)"})]},T)})}),u&&e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/50",onClick:()=>m(null)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(zt,{color:u.color,onColorChange:T=>{g(u.value,T),m(null)},onClose:()=>m(null)})})]})]})})]})}function ve({value:t,onSave:a,placeholder:n="",type:r="text",className:l=""}){const[o,c]=A.useState(t??""),[i,d]=A.useState(!1);A.useEffect(()=>{c(t??"")},[t]);const u=()=>{a(o),d(!1)},m=()=>{c(t??""),d(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${l}`,children:[e.jsx(s.Input$1,{placeholder:n,type:r,value:i?o:t??"",onChange:h=>{c(h.target.value),d(!0)},onFocus:()=>d(!0),onClick:h=>h.stopPropagation(),className:"h-8 text-xs",onPointerDown:h=>h.stopPropagation(),onKeyDown:h=>{h.stopPropagation(),h.key==="Enter"&&i&&o!==t?u():h.key==="Escape"&&m()},"aria-label":n||"Edit field"}),i&&o!==t&&e.jsxs(e.Fragment,{children:[e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm edit",onClick:u,children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel edit",onClick:m,children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}const Er=["auto","number","currency","percent","scientific","date"],Ir=[{value:"USD",label:"USD - US Dollar"},{value:"EUR",label:"EUR - Euro"},{value:"JPY",label:"JPY - Japanese Yen"},{value:"GBP",label:"GBP - British Pound"},{value:"CNY",label:"CNY - Chinese Yuan"},{value:"CHF",label:"CHF - Swiss Franc"},{value:"CAD",label:"CAD - Canadian Dollar"},{value:"AUD",label:"AUD - Australian Dollar"},{value:"HKD",label:"HKD - Hong Kong Dollar"},{value:"SGD",label:"SGD - Singapore Dollar"},{value:"NZD",label:"NZD - New Zealand Dollar"},{value:"SEK",label:"SEK - Swedish Krona"},{value:"NOK",label:"NOK - Norwegian Krone"},{value:"DKK",label:"DKK - Danish Krone"},{value:"KRW",label:"KRW - South Korean Won"},{value:"INR",label:"INR - Indian Rupee"},{value:"RUB",label:"RUB - Russian Ruble"},{value:"BRL",label:"BRL - Brazilian Real"},{value:"MXN",label:"MXN - Mexican Peso"},{value:"TRY",label:"TRY - Turkish Lira"},{value:"ZAR",label:"ZAR - South African Rand"},{value:"SAR",label:"SAR - Saudi Riyal"},{value:"AED",label:"AED - UAE Dirham"},{value:"ARS",label:"ARS - Argentine Peso"},{value:"CLP",label:"CLP - Chilean Peso"},{value:"COP",label:"COP - Colombian Peso"},{value:"THB",label:"THB - Thai Baht"},{value:"IDR",label:"IDR - Indonesian Rupiah"},{value:"MYR",label:"MYR - Malaysian Ringgit"},{value:"PHP",label:"PHP - Philippine Peso"},{value:"PLN",label:"PLN - Polish Zloty"},{value:"NGN",label:"NGN - Nigerian Naira"},{value:"KES",label:"KES - Kenyan Shilling"},{value:"GHS",label:"GHS - Ghanaian Cedi"},{value:"ZMW",label:"ZMW - Zambian Kwacha"},{value:"ZWL",label:"ZWL - Zimbabwean Dollar"},{value:"EGP",label:"EGP - Egyptian Pound"},{value:"MAD",label:"MAD - Moroccan Dirham"},{value:"UAH",label:"UAH - Ukrainian Hryvnia"},{value:"HUF",label:"HUF - Hungarian Forint"},{value:"CZK",label:"CZK - Czech Koruna"},{value:"RON",label:"RON - Romanian Leu"},{value:"PKR",label:"PKR - Pakistani Rupee"},{value:"BDT",label:"BDT - Bangladeshi Taka"},{value:"VND",label:"VND - Vietnamese Dong"},{value:"TWD",label:"TWD - New Taiwan Dollar"},{value:"ILS",label:"ILS - Israeli New Shekel"}],Ar=[{value:"en-US",label:"English (US)"},{value:"en-GB",label:"English (UK)"},{value:"en-IN",label:"English (India)"},{value:"de-DE",label:"German"},{value:"fr-FR",label:"French"},{value:"es-ES",label:"Spanish"},{value:"it-IT",label:"Italian"},{value:"pt-BR",label:"Portuguese (Brazil)"},{value:"zh-CN",label:"Chinese (Simplified)"},{value:"ja-JP",label:"Japanese"},{value:"ko-KR",label:"Korean"},{value:"ru-RU",label:"Russian"},{value:"ar-SA",label:"Arabic"},{value:"hi-IN",label:"Hindi"},{value:"nl-NL",label:"Dutch"},{value:"sv-SE",label:"Swedish"}],Mr=t=>t.charAt(0).toUpperCase()+t.slice(1);function Ts({formatOptions:t={},onFormatOptionsChange:a,showTitle:n=!0,title:r="NUMBER FORMAT"}){const l=t.type||"auto",o=(i,d)=>{a({...t,[i]:d})},c=()=>l==="currency"?2:l==="percent"?1:0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[n&&e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:r}),e.jsxs(s.Select,{value:l,onValueChange:i=>o("type",i),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Er.map(i=>e.jsx(s.SelectItem,{value:i,className:"text-xs",children:i==="auto"?"Auto (Default)":Mr(i)},i))})]})]}),l!=="auto"&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-4",children:[["number","currency","percent"].includes(l)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Decimals"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{type:"number",min:"0",max:"10",placeholder:"0",value:t.decimalPlaces??c(),onChange:i=>o("decimalPlaces",parseInt(i.target.value)||0),className:"h-8 text-xs"})})]}),l==="currency"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Currency"}),e.jsxs(s.Select,{value:t.currency||"USD",onValueChange:i=>o("currency",i),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Ir.map(i=>e.jsx(s.SelectItem,{value:i.value,className:"text-xs",children:i.label},i.value))})]})]}),["number","currency"].includes(l)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Abbreviate (K, M, B)"}),e.jsx(s.SmallSwitch,{checked:t.useSuffix??!1,onCheckedChange:i=>o("useSuffix",i)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Locale"}),e.jsxs(s.Select,{value:t.locale||"en-US",onValueChange:i=>o("locale",i),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Ar.map(i=>e.jsx(s.SelectItem,{value:i.value,className:"text-xs",children:i.label},i.value))})]})]}),l==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Prefix"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{placeholder:"e.g., $",value:t.prefix||"",onChange:i=>o("prefix",i.target.value),className:"h-8 text-xs"})})]}),l==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Suffix"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{placeholder:"e.g., units",value:t.suffix||"",onChange:i=>o("suffix",i.target.value),className:"h-8 text-xs"})})]}),["number","currency"].includes(l)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Negative in ()"}),e.jsx(s.SmallSwitch,{checked:t.negativeInParentheses??!1,onCheckedChange:i=>o("negativeInParentheses",i)})]}),l==="percent"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Multiply By"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{type:"number",placeholder:"100",value:t.multiplyBy??"",onChange:i=>o("multiplyBy",i.target.value?parseFloat(i.target.value):void 0),className:"h-8 text-xs"})})]}),l==="date"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Format"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{type:"text",placeholder:"MM/DD/YYYY",value:t.dateFormat||"",onChange:i=>o("dateFormat",i.target.value),className:"h-8 text-xs"})})]})]})]})}function Gs({axis:t,label:a,type:n,config:r,onChange:l}){var h,f,g,b,p,j,x,v,k,R,N,w;const o=(y,D)=>{l({...r,[y]:D})},c=(y,D)=>{var C,I;l({...r,name:{enabled:y==="enabled"?D:((C=r==null?void 0:r.name)==null?void 0:C.enabled)??!1,text:y==="text"?D:(I=r==null?void 0:r.name)==null?void 0:I.text}})},i=(y,D)=>{var C,I;l({...r,labels:{enabled:y==="enabled"?D:((C=r==null?void 0:r.labels)==null?void 0:C.enabled)??!0,rotation:y==="rotation"?D:(I=r==null?void 0:r.labels)==null?void 0:I.rotation}})},d=(y,D)=>{l({...r,scale:{...r==null?void 0:r.scale,[y]:D===""?"auto":Number(D)}})},u=t==="x"?["auto","top","bottom"]:["auto","left","right"],m=["auto","0","45","90","-45","-90"];return e.jsxs(s.AccordionItem,{value:`${t}-axis`,className:"border-b-0",children:[e.jsxs("div",{className:"flex w-full items-center justify-between gap-2",children:[e.jsx(s.AccordionTrigger,{className:"flex grow items-center justify-between gap-3 py-2 text-sm font-medium hover:no-underline",children:e.jsx("div",{className:"flex grow items-center justify-between gap-2",children:e.jsx("span",{children:a})})}),e.jsx(s.SmallSwitch,{checked:(r==null?void 0:r.enabled)!==!1,onCheckedChange:y=>o("enabled",y),onClick:y=>y.stopPropagation()})]}),e.jsxs(s.AccordionContent,{className:"space-y-4 pt-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"TITLE"}),e.jsx(s.SmallSwitch,{checked:((h=r==null?void 0:r.name)==null?void 0:h.enabled)??!1,onCheckedChange:y=>c("enabled",y)})]}),((f=r==null?void 0:r.name)==null?void 0:f.enabled)&&e.jsx(ve,{placeholder:`${a} title`,value:((g=r==null?void 0:r.name)==null?void 0:g.text)||"",onSave:y=>c("text",y),className:""})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"POSITION"}),e.jsxs(s.Select,{value:(r==null?void 0:r.position)||"auto",onValueChange:y=>o("position",y),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:u.map(y=>e.jsx(s.SelectItem,{value:y,className:"text-xs",children:y==="auto"?"Auto (Default)":s.titleCase(y)},y))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"LABELS"}),e.jsx(s.SmallSwitch,{checked:((b=r==null?void 0:r.labels)==null?void 0:b.enabled)!==!1,onCheckedChange:y=>i("enabled",y)})]}),((p=r==null?void 0:r.labels)==null?void 0:p.enabled)!==!1&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Rotation"}),e.jsxs(s.Select,{value:String(((j=r==null?void 0:r.labels)==null?void 0:j.rotation)||"auto"),onValueChange:y=>i("rotation",y==="auto"?"auto":Number(y)),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:m.map(y=>e.jsx(s.SelectItem,{value:y,className:"text-xs",children:y==="auto"?"Auto (Default)":`${y}°`},y))})]})]})]}),n==="value"&&e.jsx(Ts,{formatOptions:(r==null?void 0:r.formatOptions)||{},onFormatOptionsChange:y=>l({...r,formatOptions:y}),showTitle:!0,title:"FORMAT"}),n==="value"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"SCALE"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Min"}),e.jsx("div",{className:"flex-1",children:e.jsx(ve,{type:"number",placeholder:"auto",value:((x=r==null?void 0:r.scale)==null?void 0:x.min)==="auto"||((v=r==null?void 0:r.scale)==null?void 0:v.min)===void 0?"":String(r.scale.min),onSave:y=>d("min",y),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Max"}),e.jsx("div",{className:"flex-1",children:e.jsx(ve,{type:"number",placeholder:"auto",value:((k=r==null?void 0:r.scale)==null?void 0:k.max)==="auto"||((R=r==null?void 0:r.scale)==null?void 0:R.max)===void 0?"":String(r.scale.max),onSave:y=>d("max",y),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Step"}),e.jsx("div",{className:"flex-1",children:e.jsx(ve,{type:"number",placeholder:"auto",value:((N=r==null?void 0:r.scale)==null?void 0:N.stepSize)==="auto"||((w=r==null?void 0:r.scale)==null?void 0:w.stepSize)===void 0?"":String(r.scale.stepSize),onSave:y=>d("stepSize",y),className:""})})]})]})]})]})]})}function _t(){const t=s.useEditorStore(c=>c.card),a=s.useEditorStore(c=>{var i;return(i=c.card)==null?void 0:i.preferences}),{setCardPreferences:n,updateCardInFrame:r}=s.useEditorActions();if(!t||["tornado","pyramid","kpi"].includes(t.type))return null;const l=s.AxisConfigurator.getAxisInfo(t.type,a);if(!l.hasXAxis&&!l.hasYAxis)return null;const o=(c,i)=>{const u={...a||{},[c==="x"?"xAxisConfig":"yAxisConfig"]:i};n(u);const m={...t,preferences:u};r(m)};return e.jsxs(s.AccordionItem,{value:"axes",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ya,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Axes"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full",children:[l.hasXAxis&&e.jsx(Gs,{axis:"x",label:"X-Axis",type:l.xAxisType,config:a==null?void 0:a.xAxisConfig,onChange:c=>o("x",c)}),l.hasYAxis&&e.jsx(Gs,{axis:"y",label:"Y-Axis",type:l.yAxisType,config:a==null?void 0:a.yAxisConfig,onChange:c=>o("y",c)})]})})]})}function Ut(){const t=s.useEditorStore(u=>u.card),a=s.useEditorStore(u=>{var m,h,f,g;return(g=(f=(h=(m=u.card)==null?void 0:m.preferences)==null?void 0:h.chartOptions)==null?void 0:f.plugins)==null?void 0:g.legend}),{setLegendOptions:n}=s.useEditorActions();if(!t||!s.chartSupportsLegend(t.type))return null;const r="bottom",l="center",o=!(t.type==="stackedBar"||t.type==="stackedLine"),c=(u,m)=>{const h={...a,[u]:m};n(h)},i=["top","bottom","left","right"],d=["start","center","end"];return e.jsxs(s.AccordionItem,{value:"legend",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(wa,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Legend"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Display"}),e.jsx(s.SmallSwitch,{checked:(a==null?void 0:a.display)??o,onCheckedChange:u=>c("display",u)})]}),((a==null?void 0:a.display)??o)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(s.Select,{value:(a==null?void 0:a.position)||r,onValueChange:u=>c("position",u),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:i.map(u=>e.jsx(s.SelectItem,{value:u,className:"text-xs",children:s.titleCase(u)},u))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Alignment"}),e.jsxs(s.Select,{value:(a==null?void 0:a.align)||l,onValueChange:u=>c("align",u),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:d.map(u=>e.jsx(s.SelectItem,{value:u,className:"text-xs",children:s.titleCase(u)},u))})]})]})]})]})})]})}function $t(){var D,C,I,S,F,T,E,M,B;const t=s.useEditorStore(L=>L.card),a=s.useEditorStore(L=>{var O,P;return(P=(O=L.card)==null?void 0:O.preferences)==null?void 0:P.dataLabelsConfig}),n=s.useEditorStore(L=>{var O;return(O=L.card)==null?void 0:O.preferences}),{setCardPreferences:r,updateCardInFrame:l}=s.useEditorActions();if(!t||!s.chartSupportsDataLabels(t.type))return null;const o=((D=n==null?void 0:n.chartOptions)==null?void 0:D.indexAxis)==="y",c=t.type==="stackedBar"||t.type==="stackedLine",i=t.type==="pie"||t.type==="doughnut"||t.type==="polarArea"||t.type==="funnel",d=!i,u=(I=(C=n==null?void 0:n.chartOptions)==null?void 0:C.plugins)==null?void 0:I.datalabels,m=(u==null?void 0:u.display)!==!1&&((u==null?void 0:u.anchor)||(u==null?void 0:u.align)),h=(a==null?void 0:a.enabled)!==void 0?a.enabled:m,f=(L,O)=>{const P={...a,[L]:O},K={...t.preferences||{},dataLabelsConfig:P};r(K);const $={...t,preferences:K};l($)},g=(L,O)=>{const P={...a,font:{...a==null?void 0:a.font,[L]:O}},K={...t.preferences||{},dataLabelsConfig:P};r(K);const $={...t,preferences:K};l($)},b=(L,O)=>{const P={...a,formatOptions:{...a==null?void 0:a.formatOptions,[L]:O}},K={...t.preferences||{},dataLabelsConfig:P};r(K);const $={...t,preferences:K};l($)},j=(()=>{const L=t.type;return L==="stackedBar"||L==="stackedLine"||L==="pie"||L==="doughnut"?"center":o?"right":"top"})();let x=[];c||i?x=["center"]:x=["auto",...(o?["center","left","right"]:["center","top","bottom"]).filter(O=>O!==j),"custom"];const v=()=>s.titleCase(j),k=["center","start","end"],R=["center","start","end","top","bottom"],N=d?["auto","number","currency","percent","none"]:["number","currency","percent","none"],w=[{value:"USD",label:"USD - US Dollar"},{value:"EUR",label:"EUR - Euro"},{value:"GBP",label:"GBP - British Pound"},{value:"JPY",label:"JPY - Japanese Yen"},{value:"CNY",label:"CNY - Chinese Yuan"},{value:"INR",label:"INR - Indian Rupee"},{value:"CAD",label:"CAD - Canadian Dollar"},{value:"AUD",label:"AUD - Australian Dollar"}],y=[{value:"en-US",label:"English (US)"},{value:"en-GB",label:"English (UK)"},{value:"de-DE",label:"German"},{value:"fr-FR",label:"French"},{value:"es-ES",label:"Spanish"},{value:"it-IT",label:"Italian"},{value:"pt-BR",label:"Portuguese (Brazil)"},{value:"zh-CN",label:"Chinese (Simplified)"}];return e.jsxs(s.AccordionItem,{value:"data-labels",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ha,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Data Labels"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Display"}),e.jsx(s.SmallSwitch,{checked:h,onCheckedChange:L=>f("enabled",L)})]}),h&&e.jsxs(e.Fragment,{children:[!c&&!i&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(s.Select,{value:(a==null?void 0:a.position)||"auto",onValueChange:L=>f("position",L),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:x.map(L=>e.jsx(s.SelectItem,{value:L,className:"text-xs",children:L==="auto"?v():L==="custom"?"Custom (Advanced)":s.titleCase(L)},L))})]})]}),c&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Show Total"}),e.jsx(s.SmallSwitch,{checked:(a==null?void 0:a.showTotal)??!1,onCheckedChange:L=>f("showTotal",L)})]}),(a==null?void 0:a.position)==="custom"&&e.jsxs("div",{className:"space-y-2 pl-4 border-l-2 border-muted",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-16",children:"Anchor"}),e.jsxs(s.Select,{value:(a==null?void 0:a.anchor)||"center",onValueChange:L=>f("anchor",L),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:k.map(L=>e.jsx(s.SelectItem,{value:L,className:"text-xs",children:s.titleCase(L)},L))})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-16",children:"Align"}),e.jsxs(s.Select,{value:String((a==null?void 0:a.align)||"center"),onValueChange:L=>f("align",L),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:R.map(L=>e.jsx(s.SelectItem,{value:L,className:"text-xs",children:s.titleCase(L)},L))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Format"}),e.jsxs(s.Select,{value:(a==null?void 0:a.format)||(d?"auto":"none"),onValueChange:L=>f("format",L),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:N.map(L=>e.jsx(s.SelectItem,{value:L,className:"text-xs",children:L==="auto"&&d?"Auto (Use Axis)":L==="none"?"None (Raw Value)":s.titleCase(L)},L))})]})]}),(a==null?void 0:a.format)&&!["auto","none"].includes(a.format)&&e.jsxs("div",{className:"space-y-2 pl-4 border-l-2 border-muted",children:[["number","currency","percent"].includes(a.format)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Decimals"}),e.jsx("div",{className:"flex-1",children:e.jsx(ve,{type:"number",placeholder:"0",value:String(((S=a==null?void 0:a.formatOptions)==null?void 0:S.decimalPlaces)??(a.format==="currency"?2:a.format==="percent"?1:0)),onSave:L=>b("decimalPlaces",Number(L)),className:""})})]}),a.format==="currency"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Currency"}),e.jsxs(s.Select,{value:((F=a==null?void 0:a.formatOptions)==null?void 0:F.currency)||"USD",onValueChange:L=>b("currency",L),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:w.map(L=>e.jsx(s.SelectItem,{value:L.value,className:"text-xs",children:L.label},L.value))})]})]}),["number","currency"].includes(a.format)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Abbreviate (K, M, B)"}),e.jsx(s.SmallSwitch,{checked:((T=a==null?void 0:a.formatOptions)==null?void 0:T.useSuffix)??!1,onCheckedChange:L=>b("useSuffix",L)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Locale"}),e.jsxs(s.Select,{value:((E=a==null?void 0:a.formatOptions)==null?void 0:E.locale)||"en-US",onValueChange:L=>b("locale",L),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:y.map(L=>e.jsx(s.SelectItem,{value:L.value,className:"text-xs",children:L.label},L.value))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Appearance"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Size"}),e.jsx("div",{className:"flex-1",children:e.jsx(ve,{type:"number",placeholder:"12",value:String(((M=a==null?void 0:a.font)==null?void 0:M.size)||12),onSave:L=>g("size",Number(L)),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Weight"}),e.jsxs(s.Select,{value:((B=a==null?void 0:a.font)==null?void 0:B.weight)||"normal",onValueChange:L=>g("weight",L),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"normal",className:"text-xs",children:"Normal"}),e.jsx(s.SelectItem,{value:"bold",className:"text-xs",children:"Bold"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Color"}),e.jsxs(s.Select,{value:(a==null?void 0:a.color)==="auto"||!(a!=null&&a.color)?"auto":"custom",onValueChange:L=>{L==="auto"&&f("color","auto")},children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"auto",className:"text-xs",children:"Auto (Smart Contrast)"}),e.jsx(s.SelectItem,{value:"custom",disabled:!0,className:"text-xs",children:"Custom (Coming Soon)"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Rotation"}),e.jsx("div",{className:"flex-1",children:e.jsx(ve,{type:"number",placeholder:"0",value:String((a==null?void 0:a.rotation)||0),onSave:L=>f("rotation",Number(L)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"degrees"})]})]})]})]})})]})}function Lr(){return e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx("h3",{className:"text-sm font-medium",children:"Chart Configuration"}),e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full px-2",children:[e.jsx(Vt,{}),e.jsx(_t,{}),e.jsx(Ut,{}),e.jsx($t,{})]})]})}const Rr=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT dimension, cohort, metric FROM table"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/tornado",children:"example"})," in the docs."]})]}),Or=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT y-axis, label, range-from, range-to, range-value FROM table"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/range",children:"example"})," in the docs."]})]}),Br=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT text FROM table limit 1"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/text",children:"example"})," in the docs."]})]});function Fr(){const t=s.useEditorStore(n=>n.card.type);function a(n){const r=["kpi","table","text","map","custom"],l=o=>r.includes(n)?o:e.jsxs(e.Fragment,{children:[o,e.jsx(Lr,{})]});switch(n){case"stackedBar":case"stackedLine":return l(e.jsx(Sr,{}));case"tornado":case"pyramid":return l(e.jsx(Qe,{docContent:Rr,cardType:n}));case"kpi":return e.jsx(jr,{});case"line":case"bar":return l(e.jsx(dr,{cardType:n}));case"range":return l(e.jsx(Qe,{docContent:Or,cardType:n}));case"pie":case"doughnut":case"polarArea":case"radar":case"funnel":return l(e.jsx(Qe,{cardType:n}));case"bubble":case"scatter":return l(e.jsx(ur,{cardType:n}));case"table":return e.jsx(wr,{cardType:n});case"text":return e.jsx(Qe,{docContent:Br,cardType:n,suffix:"Visual"});case"map":return e.jsx(Nr,{});case"custom":return e.jsx(lr,{});default:return l(e.jsx(xr,{}))}}return e.jsxs(s.ScrollArea,{className:"h-full w-full text-sm",children:[a(t),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})}function Yt({label:t,column:a,functions:n,onFunctionChange:r}){let l=n[0];"aggregate"in a?l=n.find(c=>c.value===a.aggregate)||n[0]:"granularity"in a&&(l=n.find(c=>c.value===a.granularity)||n[0]);function o(c){r(c)}return e.jsx(fe,{className:"flex h-8 w-8 justify-center overflow-clip rounded-none border-none bg-muted px-0 [&>svg]:hidden",icon:l.logo,options:n,value:l.value,onValueChange:c=>o(c),label:t,showPlaceholderLabel:!1})}const Pr=[{label:"Sum",value:"SUM",logo:e.jsx(at,{className:"size-3.5"})},{label:"Count",value:"COUNT",logo:e.jsx(Ne,{className:"size-3.5"})},{label:"Unique",value:"DISTINCT",logo:e.jsx(ya,{className:"size-3.5"})},{label:"Average",value:"AVG",logo:e.jsx(ra,{className:"size-3.5"})},{label:"Min",value:"MIN",logo:e.jsx(s.ArrowDown,{className:"size-3.5"})},{label:"Max",value:"MAX",logo:e.jsx(s.ArrowUp,{className:"size-3.5"})}];function zr({column:t}){const{updateMetricColumnOld:a}=s.useEditorActions();let n=Pr;s.isTextDataType(t.type)&&(n=n.filter(l=>["COUNT","DISTINCT"].includes(l.value))),s.isNumberDataType(t.type)&&(n=n.filter(l=>!["DISTINCT"].includes(l.value)));function r(l){const o={...t,aggregate:l,label:Ye(t.name,l)};a(t.id,o)}return e.jsx(Yt,{column:t,functions:n,onFunctionChange:l=>r(l),label:"Aggregation"})}const Vr=[{label:"Day (D)",value:"day",logo:e.jsx(s.Label,{className:"cursor-pointer text-xs",children:"D"})},{label:"Week (W)",value:"week",logo:e.jsx(s.Label,{className:"cursor-pointer text-xs",children:"W"})},{label:"Month (M)",value:"month",logo:e.jsx(s.Label,{className:"cursor-pointer text-xs",children:"M"})},{label:"Year (Y)",value:"year",logo:e.jsx(s.Label,{className:"cursor-pointer text-xs",children:"Y"})}];function _r({column:t}){const{updateGroupByColumnOld:a}=s.useEditorActions();function n(r){const l={...t,granularity:r,label:Fe(t.name,r)};a(t.id,l)}return e.jsx(Yt,{column:t,functions:Vr,onFunctionChange:r=>n(r),label:"Granularity"})}function Ur({col:t,onChange:a,droppableId:n}){const{columns:r}=s.useDataColumns(),l=A.useMemo(()=>{let i=[];(n===Ie||n===Ae||n===Me)&&(i=r);const d=i==null?void 0:i.filter(u=>u.column_name!==t.name);return d==null?void 0:d.map(u=>({id:u.column_name,value:u.column_name}))},[r,n,t.name]),o=[{id:t.name,value:t.name}];function c(i){const d=r==null?void 0:r.find(u=>{var m;return u.column_name===((m=i[0])==null?void 0:m.id)});d&&a(d)}return l!=null&&l.length?e.jsx(s.ComboBox2,{multiple:!1,options:l,selectedOptions:o,onChange:c,selectAllChecked:!1,onSelectAllCheckedChange:()=>{},inputClassName:"border-none bg-muted pl-0 pr-8"}):e.jsx("input",{disabled:!0,type:"text",className:"overflow-hidden truncate text-ellipsis whitespace-nowrap bg-muted text-sm",value:t.name})}function qt({column:t}){const a=s.useEditorStore(d=>d.card.type),n=s.useEditorStore(d=>{var u,m;return(m=(u=d.card)==null?void 0:u.config)==null?void 0:m.metricColumns}),r=(n==null?void 0:n.map(d=>d.label))||[],l=r==null?void 0:r.find(d=>d===t.label||d===t.name),o=l?r.indexOf(l):-1;function c(){return e.jsx("div",{className:"pr-1",children:l&&e.jsx(Ft,{idx:o,col:l,children:e.jsx("div",{className:"w-[130px] text-xs text-muted-foreground",children:"Display Series As"})})})}function i(){return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Data Labels"}),e.jsx(Pt,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(a)&&c(),["pie","doughnut"].includes(a)&&i()]})}function $r({column:t,type:a,onRemoveColumn:n,droppableId:r}){const[l,o]=A.useState(!1),{updateGroupByColumnOld:c,updateMetricColumnOld:i,updatePivotByColumnOld:d}=s.useEditorActions(),{attributes:u,listeners:m,setNodeRef:h,transform:f,transition:g,isDragging:b}=s.useSortable({id:t.id,data:{type:a}}),p=f?{opacity:b?.5:void 0,transform:s.CSS.Translate.toString(f),transition:g}:void 0,j=s.isTextDataType(t.type);function x(w){const y=s.isNumberDataType(w.data_type),D=s.isTextDataType(w.data_type),C=s.isDateDataType(w.data_type),I=y?"number":D?"string":C?"date":"string";if(r===Ie){if(D){const S={id:t.id,name:w.column_name,type:I,role:"groupby"};c(t.id,S)}if(C){const S={id:t.id,name:w.column_name,type:I,role:"groupby",label:Fe(w.column_name,"month"),granularity:"month"};c(t.id,S)}}if(r===Me){if(D){const S={id:t.id,name:w.column_name,type:I,role:"groupby"};d(t.id,S)}if(C){const S={id:t.id,name:w.column_name,type:I,label:Fe(w.column_name,"month"),granularity:"month",role:"groupby"};d(t.id,S)}}if(r===Ae){const S={id:t.id,name:w.column_name,type:I,role:"metric",label:Ye(w.column_name,"SUM"),aggregate:y?"SUM":"COUNT"};i(t.id,S)}}function v(){if(r===Ae)return e.jsx("div",{"data-setting-container":"",className:"mt-1.5 max-h-32 overflow-y-auto rounded-md border border-border p-3 text-sm",children:e.jsx(qt,{column:t})})}function k(){const w=s.isDateDataType(t.type);if(r===Ae)return e.jsx(zr,{column:t});if((r===Ie||r===Me)&&w)return e.jsx(_r,{column:t})}function R(){return e.jsx("div",{className:s.cn("grow",{"pl-3":(r===Ie||r===Me)&&j}),children:e.jsx(Ur,{col:t,onChange:x,droppableId:r})})}function N(){return e.jsx("div",{"data-setting-actions":"",className:"flex h-full items-center gap-2",children:e.jsx("button",{className:"h-full pl-2",onClick:()=>o(!l),children:l?e.jsx($a,{className:s.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")}):e.jsx(et,{className:s.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")})})})}return e.jsx("div",{...m,...u,ref:h,style:p,children:e.jsxs("div",{className:"group flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex h-8 grow items-center justify-between rounded-md bg-muted",children:[N(),k(),R()]}),l&&v()]}),e.jsx("div",{className:s.cn("opacity-0 transition-opacity duration-200 group-hover:opacity-100",{hidden:l}),children:e.jsx("button",{onClick:()=>n(t.id),children:e.jsx(s.X,{className:"size-3 cursor-pointer text-muted-foreground"})})})]})})}function xs({id:t,label:a,columns:n,previewColumns:r,sortableType:l,onRemoveColumn:o}){var p,j;const{setNodeRef:c,isOver:i,over:d}=s.useDroppable({id:t}),u=s.useDndStore(x=>x.activeId),m=s.useEditorStore(x=>{var v;return(v=x.card)==null?void 0:v.type}),h=i||((j=(p=d==null?void 0:d.data)==null?void 0:p.current)==null?void 0:j.type)===l,f=u?r:n,g=l===ts?"Rows":l===as?"Pivot Columns":"Columns";function b(){if(!f||f.length===0)return e.jsx("div",{className:"mr-5 flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground/80 bg-background px-2 py-1 text-sm text-muted-foreground",children:e.jsx("span",{className:"invisible text-muted-foreground/70 group-hover:visible",children:"Drag here"})})}return e.jsx(s.SortableContext,{items:n==null?void 0:n.map(x=>x.id),children:e.jsxs("div",{className:s.cn("group space-y-2 rounded-md p-4",h&&"border border-muted-foreground/20"),ref:c,children:[e.jsxs("div",{className:"flex items-center justify-between pr-5",children:[e.jsx(s.Label,{className:"text-sm",children:a}),m!=="table"&&e.jsx("span",{className:"text-xs text-muted-foreground/50",children:g})]}),b(),e.jsx("div",{className:"space-y-2",children:f==null?void 0:f.map(x=>x.id===Nt.id?e.jsx(Yr,{},x.id):e.jsx($r,{droppableId:t,type:l,column:x,onRemoveColumn:o},x.id))})]})})}function Yr(){return e.jsx("div",{className:"mr-5 flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground bg-background px-2 py-1 text-sm",children:e.jsx("span",{className:"text-muted-foreground/70",children:"Drop here"})})}function Gt({children:t,id:a,type:n}){const{attributes:r,listeners:l,setNodeRef:o,transform:c,transition:i,isDragging:d}=s.useSortable({id:a,data:{type:n}}),u=c?{opacity:d?.5:void 0,transform:s.CSS.Translate.toString(c),transition:i}:void 0;return e.jsx("div",{...l,...r,ref:o,style:u,children:t})}function qr(){const t=s.useEditorStore(x=>{var v;return(v=x.card.queryConfig)==null?void 0:v.orderBy})||[],a=s.useEditorStore(x=>{var v;return(v=x.card.queryConfig)==null?void 0:v.groupByColumns})||[],n=s.useEditorStore(x=>{var v;return(v=x.card.queryConfig)==null?void 0:v.metricColumns})||[],{addOrderByColumn:r,removeOrderByColumn:l,updateOrderByColumn:o}=s.useEditorActions(),c=[...a,...n];if(c.length===0)return e.jsx(e.Fragment,{});const i=e.jsx(oa,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),d=e.jsx(na,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),u=e.jsx(la,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),m=e.jsx(aa,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),h=c==null?void 0:c.filter(x=>!t.some(v=>v.columnId===x.id)).map(x=>({id:x.id,value:x.label||x.name}));function f(x,v){const k=g(x);return k?k.role==="metric"?v==="asc"?u:m:v==="asc"?i:d:null}function g(x){return c.find(v=>v.id===x)}function b(x){const v=t.find(k=>k.columnId===x);if(v){const k={...v,direction:v.direction==="asc"?"desc":"asc"};o(k)}}const p=x=>{r({columnId:x.id,direction:"asc"})};function j(x){const v=t.find(k=>k.columnId===x);v&&l(v)}return e.jsx(s.SortableContext,{items:t.map(x=>Ve(x.columnId)),children:e.jsxs("div",{className:"space-y-2 rounded-md p-4 text-sm",children:[e.jsx(s.Label,{className:"text-sm",children:"Sort By"}),h.length>0&&e.jsx("div",{className:"mr-5",children:e.jsx(s.ComboBox2,{multiple:!1,options:h,selectedOptions:[],onChange:x=>p(x[0]),selectAllChecked:!1,onSelectAllCheckedChange:()=>{},inputClassName:"h-8 bg-muted border-none"})}),t.map(x=>{var v,k;return e.jsx(Gt,{id:Ve(x.columnId),type:Ss,children:e.jsx("div",{className:"group flex h-8 items-center gap-2 rounded-sm p-0",children:e.jsxs("div",{className:"flex h-full grow items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex h-full grow items-center justify-between gap-2 rounded-sm bg-muted px-2",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(et,{className:"size-3 cursor-move text-muted-foreground hover:text-foreground"}),e.jsx(ls,{className:"w-[175px] text-sm",children:((v=g(x.columnId))==null?void 0:v.label)||((k=g(x.columnId))==null?void 0:k.name)})]}),e.jsx("button",{title:x.direction==="asc"?"Ascending":"Descending",onClick:()=>b(x.columnId),className:"rounded-sm p-0",children:f(x.columnId,x.direction)})]}),e.jsx("div",{children:e.jsx("button",{onClick:()=>j(x.columnId),className:"rounded-sm p-0",children:e.jsx(s.X,{className:"size-3 text-muted-foreground opacity-0 transition-opacity duration-200 hover:text-foreground group-hover:opacity-100"})})})]})},x.columnId)},Ve(x.columnId))})]})})}function Gr(){const t=s.useEditorStore(j=>{var x;return((x=j.card.queryConfig)==null?void 0:x.groupByColumns)||[]}),a=s.useEditorStore(j=>j.card.type),n=s.useDndStore(j=>j.previewGroupByColumns),r=s.useEditorStore(j=>{var x;return((x=j.card.queryConfig)==null?void 0:x.metricColumns)||[]}),l=s.useDndStore(j=>j.previewMetricColumns),o=s.useEditorStore(j=>{var x;return((x=j.card.queryConfig)==null?void 0:x.pivotColumns)||[]}),c=s.useDndStore(j=>j.previewPivotColumns),{removeColumnFromGroupBy:i,removeColumnFromMetricColumns:d,removeColumnFromPivotBy:u}=s.useEditorActions();function m(j){i(j)}function h(j){d(j)}function f(j){u(j)}let g="Group By",b="Metrics",p="Stack By";return a==="table"&&(g="Rows",b="Metrics",p="Columns"),e.jsxs("div",{className:"flex h-full w-full flex-col gap-3 py-4",children:[e.jsx(At,{iconClassName:"size-[19px]"}),e.jsxs(s.CustomScrollArea,{className:"flex min-h-0 grow basis-0 flex-col gap-4 overflow-y-auto",children:[e.jsxs("div",{className:"flex flex-col gap-4 p-4",children:[e.jsx(xs,{onRemoveColumn:m,sortableType:ts,id:Ie,label:g,columns:t,previewColumns:n}),e.jsx(xs,{onRemoveColumn:f,sortableType:as,id:Me,label:p,columns:o,previewColumns:c}),e.jsx(xs,{onRemoveColumn:h,sortableType:js,id:Ae,label:b,columns:r,previewColumns:l}),e.jsx(qr,{})]}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Es({children:t,column:a,id:n,sortableType:r,className:l}){const[o,c]=A.useState(!1),{removeEditorFilter:i,clearEditorFilter:d}=s.useEditorActions(),u=s.useEditorStore(h=>{var f,g;return(g=(f=h.card.queryConfig)==null?void 0:f.filters)==null?void 0:g.some(b=>b.filterColumnName===a.name)});function m(h){i(h)}return e.jsx(Gt,{id:n,type:r,children:e.jsxs("div",{className:s.cn("group space-y-1 rounded-md bg-muted px-3 py-2",{"border-border":o}),children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-sm",children:a.name}),u&&e.jsx("button",{onClick:()=>d(a),children:e.jsx(s.FilterX,{className:"size-3 cursor-pointer items-center justify-center text-muted-foreground hover:text-foreground"})})]}),e.jsx("div",{"data-setting-actions":"",className:"invisible flex h-full items-center gap-2 group-hover:visible",children:e.jsx("button",{onClick:()=>m(a),children:e.jsx(s.X,{className:"size-3.5 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground"})})})]}),e.jsxs("div",{className:s.cn("group flex items-center rounded-t-md text-sm",!o&&"rounded-b-md",o&&"border border-border"),children:[e.jsx("div",{children:e.jsx(s.GripVertical,{className:"mr-2 size-3.5 cursor-move items-center justify-center p-0 text-muted-foreground/60 hover:text-foreground"})}),e.jsx("div",{className:s.cn("grow cursor-pointer overflow-hidden truncate text-ellipsis whitespace-nowrap",l),children:t})]})]})})}function Hr({column:t,sortableType:a}){const n=s.useDashboardStore(k=>k.themeStyle),r=s.useEditorStore(k=>{var R,N;return(N=(R=k.card)==null?void 0:R.queryConfig)==null?void 0:N.filters}),l=s.useEditorStore(k=>{var R,N;return(N=(R=k.card.queryConfig)==null?void 0:R.filterColumns)==null?void 0:N.find(w=>w.name===t.name)}),{selectedConnectionId:o,selectedDatabaseName:c,selectedTableName:i}=s.useEditorAside(),d=A.useMemo(()=>{var k;return(k=r==null?void 0:r.find(R=>R.filterColumnName===t.name))==null?void 0:k.filterValue},[r,t.name]),u=A.useMemo(()=>Array.isArray(d)?d.map(k=>({id:k,value:k})):[],[d]),{updateEditorFilterValue:m}=s.useEditorActions(),h={column:t.name,sql:t.sql,id:t.name,connectionId:o,dataType:t.type},{data:f,isLoading:g,isFetching:b,isError:p}=s.useFilterQuery(h),j=A.useMemo(()=>{var R;return h.column?(R=f==null?void 0:f.records)==null?void 0:R.map(N=>{let w=h.column.split(".").slice(-1)[0].replace(/"/g,"");return N[w]===void 0&&(w=w.toLowerCase()),{id:N[w],value:N[w]}}):[]},[f,h.column]);function x(k){const R=k.map(N=>N.id);m(t.name,R)}function v(){return g||b?e.jsx(s.Skeleton,{style:{borderRadius:n==null?void 0:n.controlInputRadius},className:"h-8 min-w-60 bg-foreground/10"}):p?e.jsx("div",{className:"flex h-8 min-w-60 items-center bg-muted px-2 text-sm",children:"Error"}):e.jsx(s.ComboBox2,{renderFilterModeButton:()=>e.jsx(Wr,{columnName:t.name}),showNegativeIndicator:(l==null?void 0:l.mode)==="exclude",options:j,onChange:x,selectedOptions:u,selectAllChecked:!1,onSelectAllCheckedChange:()=>{}})}return e.jsx(Es,{className:"w-60",id:t.id,sortableType:a,column:t,children:v()})}function Wr({columnName:t}){const{setEditorFilterMode:a}=s.useEditorActions(),n=s.useEditorStore(l=>{var o,c;return(c=(o=l.card.queryConfig)==null?void 0:o.filterColumns)==null?void 0:c.find(i=>i.name===t)});function r(){(n==null?void 0:n.mode)==="exclude"?a(t,"include"):a(t,"exclude")}return e.jsx(s.Button,{onClick:r,variant:"secondary",size:"sm",className:s.cn("h-5 text-xs hover:underline",{}),children:s.titleCase((n==null?void 0:n.mode)==="exclude"?"exclude":"include")})}function Kr({open:t,setOpen:a,dateRange:n,setDateRange:r,containerClassName:l,inputClassName:o,title:c,onApply:i,onClear:d}){const u=s.useDashboardStore(m=>m.themeStyle);return e.jsx("div",{className:s.cn("grid gap-2",l),children:e.jsxs(s.Popover,{open:t,onOpenChange:a,children:[e.jsx(s.PopoverTrigger,{style:{borderRadius:u==null?void 0:u.controlInputRadius},asChild:!0,children:e.jsxs(s.Button,{size:"sm",id:"date",variant:"outline",className:s.cn("h-9 w-full justify-start rounded-sm text-left font-normal",!n&&"text-muted-foreground",o),children:[e.jsx(s.Calendar,{className:"mr-2 h-4 w-4"}),n!=null&&n.from?n.to?e.jsxs(e.Fragment,{children:[s.format(n.from,"LLL dd, y")," -"," ",s.format(n.to,"LLL dd, y")]}):s.format(n.from,"LLL dd, y"):e.jsx("span",{children:"Pick a date"})]})}),e.jsxs(s.PopoverContent,{style:{borderRadius:u==null?void 0:u.controlInputRadius},className:"w-auto p-0",align:"start",children:[e.jsx("div",{className:"px-4 pt-3",children:e.jsx(s.Label,{children:c})}),e.jsx(s.Calendar$1,{initialFocus:!0,mode:"range",defaultMonth:n==null?void 0:n.from,selected:n,onSelect:r,numberOfMonths:2}),e.jsxs("div",{className:"flex justify-end gap-2 px-4 py-3",children:[e.jsx(s.Button,{style:{borderRadius:u==null?void 0:u.controlInputRadius},size:"sm",variant:"outline",onClick:m=>{m.stopPropagation(),i(n),a(!1)},children:"Apply"}),e.jsx(s.Button,{style:{borderRadius:u==null?void 0:u.controlInputRadius},size:"sm",variant:"outline",onClick:d,children:"Clear"})]})]})]})})}function Jr({column:t,sortableType:a}){const[n,r]=A.useState(!1),{selectedConnectionId:l,selectedDatabaseName:o,selectedTableName:c}=s.useEditorAside(),i={column:t.name,sql:t.sql,id:t.name,connectionId:l,title:"",dataType:t.type},{isLoading:d,isFetching:u,isError:m,data:h}=s.useFilterQuery(i),f=h==null?void 0:h.records,{dateRange:g,setDateRange:b,initialDateRange:p}=s.useDateRangeFromRecords(f),{updateEditorFilterValue:j}=s.useEditorActions();function x(R){var w,y;const N={gte:(w=R==null?void 0:R.from)==null?void 0:w.toISOString(),lte:(y=R==null?void 0:R.to)==null?void 0:y.toISOString()};j(t.name,N)}function v(){j(t.name,null,!0),b(p)}function k(){return d||u?e.jsx("div",{children:e.jsx(s.Skeleton,{className:"h-8 w-72 bg-foreground/10"})}):m?e.jsx("div",{className:"h-8 w-72 bg-muted px-2",children:"Error"}):f?e.jsx(Kr,{title:i.title,open:n,inputClassName:"h-8",setOpen:r,dateRange:g,setDateRange:b,onApply:x,onClear:v}):e.jsx(s.Label,{className:"flex h-8 w-72 items-center bg-muted px-2",children:"No Data"})}return e.jsx(Es,{className:"w-72",id:t.id,sortableType:a,column:t,children:k()})}function Qr({id:t,label:a,columns:n,previewColumns:r,sortableType:l}){var b,p;const{setNodeRef:o,isOver:c,over:i}=s.useDroppable({id:t}),d=s.useDndStore(j=>j.activeId),u={},m=c||((p=(b=i==null?void 0:i.data)==null?void 0:b.current)==null?void 0:p.type)===l;function h(){if(!g||g.length===0)return e.jsx("div",{className:"flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground/80 bg-background px-2 py-1 text-sm text-muted-foreground",children:e.jsx("span",{className:"invisible text-muted-foreground/70 group-hover:visible",children:"Drag here"})})}function f(j){const x=s.isDateDataType(j.type);return j.id===Nt.id?e.jsx(Es,{id:j.id,sortableType:l,column:j,children:e.jsx(Xr,{})},j.id):x?e.jsx(Jr,{droppableId:t,sortableType:l,column:j},j.id):e.jsx(Hr,{droppableId:t,sortableType:l,column:j},j.id)}const g=d?r:n;return e.jsx(s.SortableContext,{items:n==null?void 0:n.map(j=>j.id),children:e.jsxs("div",{className:s.cn("group space-y-2 rounded-md border-muted-foreground/50 p-4",m&&"border border-muted-foreground/20"),ref:o,style:u,children:[e.jsx(s.Label,{className:"text-sm",children:a}),h(),e.jsx("div",{className:"flex flex-wrap items-center gap-4",children:g==null?void 0:g.map(j=>f(j))})]})})}function Xr(){return e.jsx("div",{className:"flex h-8 w-60 items-center space-x-2 rounded-md border border-dashed border-muted-foreground bg-background px-2 py-1 text-sm text-muted-foreground",children:"Drop here"})}function Zr(){const t=s.useEditorStore(l=>{var o;return((o=l.card.queryConfig)==null?void 0:o.filterColumns)||[]}),a=s.useDndStore(l=>l.previewFilterColumns),{removeColumnFromFilterColumns:n}=s.useEditorActions();function r(l){n(l)}return e.jsx("section",{className:"size-full px-4 pb-4",children:e.jsx(Qr,{onRemoveColumn:r,sortableType:ys,id:bs,label:"Filters",columns:t,previewColumns:a})})}function el(){const t=s.useEditorStore(c=>c.card),a=s.useEditorStore(c=>c.showAIDialog),{setShowAIDialog:n}=s.useEditorActions(),{data:r,errorMessage:l,errorSql:o}=s.useDashboardCardQuery(t);return e.jsxs("section",{className:"flex justify-between gap-2 p-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ns,{}),!a&&e.jsxs(s.Button,{onClick:()=>n(!0),variant:"secondary",size:"sm",children:[e.jsx(La,{className:"mr-2 h-4 w-4"}),"Assistant"]}),e.jsx(Dt,{sql:r==null?void 0:r.sql,error:l,errorSql:o})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"rounded-full bg-green-300 px-3 py-1 text-xs font-medium text-black",children:"Preview"}),e.jsx(Ds,{}),e.jsx(ws,{variant:"default"})]})]})}function sl(){const t=A.useRef(null),a=A.useRef(null),n=s.useEditorStore(i=>i.isShowingVisual),r=s.useEditorStore(i=>i.showAIDialog),l=s.useEditorStore(i=>i.isDevMode);A.useEffect(()=>{var i,d,u,m;r?((i=t.current)==null||i.resize(0),(d=a.current)==null||d.resize(0)):((u=t.current)==null||u.resize(25),(m=a.current)==null||m.resize(25))},[r]);function o(){return e.jsxs(e.Fragment,{children:[e.jsx(s.ResizablePanel,{role:"query-section",className:"flex",minSize:20,defaultSize:40,children:e.jsx(Yn,{})}),e.jsx(s.ResizableHandle,{withHandle:!0}),e.jsx(s.ResizablePanel,{className:"pb-1",role:"visual-section",minSize:0,defaultSize:60,children:n&&!r?e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(s.ResizablePanel,{ref:t,className:"flex",defaultSize:25,maxSize:30,children:e.jsx(Fr,{})})}),!r&&e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(Je,{})})]}):e.jsx(Je,{})})]})}function c(){return e.jsx(e.Fragment,{children:e.jsx("div",{className:"grow","data-biz-mode-container":"",children:n?e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(s.ResizablePanel,{ref:a,defaultSize:25,maxSize:30,children:e.jsx(Gr,{})})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{defaultSize:75,maxSize:100,children:e.jsxs(s.ResizablePanelGroup,{direction:"vertical",children:[e.jsxs(s.ResizablePanel,{className:"flex min-h-fit flex-col",minSize:10,defaultSize:20,children:[e.jsx(el,{}),e.jsx(Zr,{})]}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:60,defaultSize:80,children:e.jsx(Je,{})})]})})]}):e.jsx(Je,{})})})}return e.jsx(s.ResizablePanelGroup,{direction:"vertical",className:"min-h-[250px] min-w-full max-w-lg",children:l?o():c()})}function tl(t){s.useAIInteractionStore(V=>V.currentAIContext);const[a,n]=A.useState(""),[r,l]=A.useState(null),{authToken:o}=s.useSemaphorContext(),c=s.useEditorStore(V=>{var se;return(se=V==null?void 0:V.card)==null?void 0:se.sql}),i=s.useEditorStore(V=>V.isDevMode),d=s.useEditorStore(V=>{var se;return(se=V==null?void 0:V.card)==null?void 0:se.python}),{setCardPython:u,setCardSql:m,setRunSql:h,switchCardType:f,setQueryConfig:g}=s.useEditorActions(),b=s.useEditorStore(V=>V.currentAssitantScope)||[],p=s.useEditorStore(V=>V.userInputForAI),j=s.useEditorStore(V=>V.triggerAIRun),x=s.useEditorStore(V=>V.card),v=s.useEditorStore(V=>V.selectedDatabaseName),k=s.useEditorStore(V=>V.selectedTableName),R=s.useEditorStore(V=>V.selectedConnectionId),N=s.useEditorStore(V=>V.selectedSchemaName),w=s.useDashboardStore(V=>V.dashboard.aiScopeTables),{errorMessage:y,refetch:D,data:C}=s.useDashboardCardQuery(x),{setTriggerAIRun:I,setCurrentAssitantScope:S,setCardConfig:F}=s.useEditorActions(),{selectedDatamodelName:T,connectionType:E,selectedDatamodelId:M}=s.useEditorAside(),{messages:B,setMessages:L,regenerate:O,error:P,sendMessage:K,status:$,addToolResult:te,stop:X,clearError:q}=s.useChat({transport:new s.DefaultChatTransport({api:"https://semaphor.cloud/api/v1/assistant",headers:()=>({Authorization:`Bearer ${o==null?void 0:o.accessToken}`}),body:()=>{const V=s.useAIInteractionStore.getState();return{random:Math.random(),assistantId:"editor-assistant",isDevMode:i,aiContext:V.currentAIContext,reasoningEffort:V.reasoningEffort,showReasoning:V.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:V,body:se})=>({body:{...se,messages:s.cleanupIncompleteMessages(V)}})}),onError:V=>{console.log("on error",V)},onToolCall:H,onFinish(){n("")}});A.useEffect(()=>{j&&p&&(K({role:"user",parts:[{type:"text",text:p}]}),I(!1))},[j,p,K,I]);async function H({toolCall:V}){var se,ne,Y,W,re,ie,he,Q,oe,ee,ae,ue,je,Ge,He,We;if(["createChartFromSql","createForecast"].includes(V.toolName)){const ze=((se=V.input)==null?void 0:se.sql)??((ne=V.args)==null?void 0:ne.sql),Ce=((Y=V.input)==null?void 0:Y.python)??((W=V.args)==null?void 0:W.python),me=((re=V.input)==null?void 0:re.chartType)??((ie=V.args)==null?void 0:ie.chartType);f(me),m(ze),u(Ce),h(!0),te({tool:V.toolName,toolCallId:V.toolCallId,output:{status:"success",message:"Let the user know that chart is created"}})}else if(V.toolName==="getUserSql"){if(!c){te({tool:V.toolName,toolCallId:V.toolCallId,output:{status:"error",message:"No SQL found"}});return}te({tool:V.toolName,toolCallId:V.toolCallId,output:{status:"success",sql:c,python:d||""}})}else if(V.toolName==="generateQueryConfig"){n("Generating query config...");const ze=((he=V.input)==null?void 0:he.chartType)??((Q=V.args)==null?void 0:Q.chartType),Ce=((oe=V.input)==null?void 0:oe.queryConfig)??((ee=V.args)==null?void 0:ee.queryConfig);((ae=V.input)==null?void 0:ae.cardConfig)??((ue=V.args)==null||ue.cardConfig),f(ze),F(Ce),m(void 0),u(void 0);const me=await D();if((je=me==null?void 0:me.data)!=null&&je.error){te({tool:V.toolName,toolCallId:V.toolCallId,output:{status:"error",queryConfig:Ce,message:(Ge=me==null?void 0:me.data)==null?void 0:Ge.error.message}});return}if((He=me==null?void 0:me.data)!=null&&He.records){te({tool:V.toolName,toolCallId:V.toolCallId,output:{status:"success",queryConfig:Ce,message:"The data has been visualized"}});return}te({tool:V.toolName,toolCallId:V.toolCallId,output:{status:"success",queryConfig:Ce,message:"The data has been visualized",records:(We=me==null?void 0:me.data)==null?void 0:We.records}})}else n("Analyzing...")}function _(V){const se=s.removeFromScopeArray(b,V);J(se)}function J(V){const se=s.sanitizeAIScope(V);S(se),L(ne=>[...ne,{id:crypto.randomUUID(),role:"system",parts:[{type:"text",text:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(se)}`}]}])}function z(){const V={databaseName:v||"",schemaName:N||"",tableName:k||"",datamodelId:M||"",datamodelName:s.resolveDatamodelName(T),connectionId:R||"",connectionType:E||""},se=s.dedup([...b,V]);J(se)}function U(){const V={databaseName:v||"",schemaName:N||"",tableName:k||"",datamodelName:s.resolveDatamodelName(T),connectionId:R||"",connectionType:E||"",datamodelId:M||""};if(!s.isInAiScopeArray([...w||[],...b],V)||b.length===0){const ne=s.dedup([...w||[],...b,V]).filter(Y=>Y.connectionId===V.connectionId);J(ne)}}const Z=!["ready","error"].includes($),le=s.getErrorMessage(P);return{messages:B,setMessages:L,sendMessage:K,regenerate:O,isLoading:Z,handleSetAIScope:U,handleAddCurrentTableToScope:z,removeFromCurrentSelections:_,currentAssitantScope:b,setCurrentAssitantScope:S,stop:X,status:$,toolStatus:a,llmUsage:r,onFinish:t,errorMessage:le,clearError:q}}const al=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function Hs(){const t=A.useRef(null),[a,n]=A.useState(!1),[r,l]=A.useState(s.isDevEnv),[o,c]=A.useState(!1),[i,d]=A.useState(!1),u=s.useCurrentAIContext(),{setCurrentAIContext:m}=s.useAIActions(),{clearQueue:h}=s.useQueueActions(),{clearFileAttachments:f}=s.useFileActions(),g=s.useFileAttachments("editor"),b=s.useDashboardStore(ee=>ee.dashboard.aiContext),p=s.useEditorStore(ee=>ee.card.dataSource),j=s.useEditorStore(ee=>ee.actions.setCardSql),x=s.useEditorStore(ee=>ee.actions.setRunSql),v=s.useEditorStore(ee=>ee.showAIDialog),k=s.useDashboardStore(ee=>ee.handleOpenAssistantProfile),{setShowAIDialog:R,setCardPython:N}=s.useEditorActions(),{setDataSource:w}=s.useEditorActions(),{assistantProfile:y}=s.useAssistantProfile(),{messages:D,setMessages:C,sendMessage:I,isLoading:S,stop:F,status:T,llmUsage:E,errorMessage:M,clearError:B}=tl(),[L,O]=A.useState(""),P=ee=>{O(ee.target.value)},K=ee=>{ee.preventDefault();const ae=L.trim();if(!ae&&g.length===0)return;const ue=[];ae&&ue.push({type:"text",text:ae}),g.forEach(je=>{je.data&&ue.push({type:"file",mediaType:je.type,filename:je.name,url:`data:${je.type};base64,${je.data}`})}),I({role:"user",parts:ue}),O(""),f("editor"),Z({force:!0})},{visibleMessages:$,hasMoreMessages:te,totalMessageCount:X,loadMoreMessages:q,resetMessageWindow:H}=s.useMessageWindow(D,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:_,isAtBottom:J,hasNewMessages:z,newMessageCount:U,scrollToBottom:Z,handleScroll:le,resetNewMessageCount:V}=s.useAutoScroll($,{threshold:50,delay:0,dependencies:[T,D.length]});A.useEffect(()=>{var ee;v&&((ee=t.current)==null||ee.focus(),m({selectedEntities:(p==null?void 0:p.selectedEntities)||[]}))},[v,p,m]),s.useAutoSubmitQueue({assistantType:"editor",status:T,isLoading:S,sendMessage:I});const{hasActiveTools:se}=s.useActiveToolStatus(D);function ne(ee,ae){ae==="sql"?(j(ee),x(!0)):ae==="python"&&(N(ee),x(!0))}function Y(){var ee;(ee=b==null?void 0:b.selectedEntities)==null||ee[0],d(!0)}function W(){u.selectedEntities.length===0&&m({selectedEntities:(b==null?void 0:b.selectedEntities)||[]})}function re(ee){W();const ae={role:"user",parts:[{type:"text",text:ee.title+" "+ee.subtitle}]};I(ae)}function ie(ee){W(),I({role:"user",parts:[{type:"text",text:ee}]})}function he(){return e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{className:"h-7 p-2 text-muted-foreground/50 hover:text-foreground",size:"sm",variant:"ghost",children:e.jsx(s.EllipsisVertical,{className:"size-3.5"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsx(s.DropdownMenuLabel,{children:"Options"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsx(s.DropdownMenuCheckboxItem,{checked:a,onCheckedChange:n,children:"Token Usage"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:r,onCheckedChange:l,children:"Tool Invocations"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:o,onCheckedChange:c,children:"System Message"})]})]})}function Q(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const oe=(L==null?void 0:L.length)===0&&(D==null?void 0:D.filter(ee=>ee.role==="user").length)===0;return e.jsxs("div",{"data-role":"editor-assistant",className:"flex h-full w-full flex-col justify-between px-6 py-4",children:[e.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[Q(),k&&e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:k,children:(y==null?void 0:y.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[he(),s.isDevEnv,e.jsx(s.IconButton,{tooltip:"Add Context",className:"h-7 p-2 text-muted-foreground/50 hover:text-foreground",onClick:Y,children:e.jsx(s.Settings,{className:"size-4"})}),e.jsx(s.IconButton,{className:"h-7 p-2 text-muted-foreground/50 hover:text-foreground",tooltip:"New Chat",onClick:()=>{C([]),h("editor"),B(),H()},children:e.jsx(s.SquarePen,{className:"size-4"})}),e.jsx(s.Button,{variant:"ghost",className:"h-7 p-2 text-muted-foreground/50 hover:text-foreground",size:"sm",onClick:()=>{R(!1)},children:e.jsx(s.ArrowRightToLine,{className:"size-4"})})]})]}),e.jsx(s.CustomScrollArea,{ref:_,className:"mt-2 flex w-full grow basis-0",onScroll:le,children:e.jsxs("div",{className:"space-y-4 py-2 pr-3","data-role":"messages",children:[te&&e.jsx("div",{className:"flex justify-center py-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:q,className:"text-xs",children:["Load ",Math.min(5,X-$.length)," more messages (",X-$.length," hidden)"]})}),e.jsx(s.PrintMessages,{messages:$,showTools:r,handleRun:ne,showSystemMessage:o}),!se&&e.jsx(s.AssistantStatus,{status:T,errorMessage:M})]})}),!J&&e.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:e.jsxs(s.Button,{onClick:()=>{Z({force:!0}),V()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[e.jsx(s.ChevronDown,{className:"h-4 w-4"}),z&&U>0&&e.jsx("span",{className:"ml-1.5 flex h-5 w-5 items-center justify-center rounded-full bg-primary text-xs text-primary-foreground",children:U>9?"9+":U})]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[oe&&!y&&e.jsx(s.Placeholders,{onClick:re,placeholders:al}),e.jsx("div",{children:oe&&y&&e.jsx(s.SeedQuestions,{seedQuestions:y.seedQuestions||[],handleSeedQuestionClick:ie})})]}),e.jsx(s.PendingMessagesDisplay,{assistantType:"editor",className:"mb-3"}),e.jsx(s.ChatInputWithContext,{ref:t,setInput:O,stop:F,input:L,handleInputChange:P,handleSubmit:ee=>{W(),K(ee),Z({force:!0})},isLoading:S,status:T,assistantType:"editor",onFocus:()=>{}})]}),E&&a&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",E.inputTokens," prompt tokens, ",E.outputTokens," ","completion tokens, ",E.totalTokens," total tokens"]})}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(p==null?void 0:p.selectedEntities)||[],open:i,onOpenChange:d,dataSource:p||s.EMPTY_DATA_SOURCE,fallbackDataSource:s.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]})}const Is=t=>{var S;const{updateCardConfig:a,updateGroupByColumn:n,updateMetricColumn:r,updatePivotByColumn:l,updateSortByColumn:o,removeGroupByColumn:c,removeMetricColumn:i,removePivotByColumn:d,removeSortByColumn:u}=s.useEditorActions(),m=s.useEditorStore(F=>F.card.type),h=t==null?void 0:t.id,f=A.useCallback(F=>{if(!(t!=null&&t.config))return[];switch(F){case"groupBy":return(t.config.groupByColumns||[]).map(T=>({id:T.id,name:T.name,dataType:T.dataType,label:T.label!==void 0?T.label:T.name,qualifiedEntityName:T.qualifiedEntityName,entityId:T.entityId,entityName:T.entityName,entityType:T.entityType,dateFormat:T.dateFormat,customFormat:T.customFormat,granularity:T.granularity}));case"metrics":return t.config.metricColumns||[];case"pivotBy":return(t.config.pivotByColumns||[]).map(T=>({id:T.id,name:T.name,dataType:T.dataType,label:T.label!==void 0?T.label:T.name,qualifiedEntityName:T.qualifiedEntityName,entityId:T.entityId,entityName:T.entityName,entityType:T.entityType}));case"sortBy":return(t.config.sortByColumns||[]).map(T=>({id:T.id,name:T.name,dataType:T.dataType,label:T.label!==void 0?T.label:T.name,qualifiedEntityName:T.qualifiedEntityName,entityId:T.entityId,entityName:T.entityName,entityType:T.entityType,direction:T.direction}));case"source":return[];default:return[]}},[t]),g=A.useCallback((F,T)=>{if(h)switch(F){case"groupBy":{a(h,{groupByColumns:T});break}case"metrics":{a(h,{metricColumns:T});break}case"pivotBy":{a(h,{pivotByColumns:T});break}case"sortBy":{a(h,{sortByColumns:T});break}}},[h,a]),b=A.useCallback((F,T,E)=>{if(!h)return;const B=f(F)[T];if(B)switch(F){case"groupBy":n(h,B.id,{label:E});break;case"metrics":r(h,B.id,{label:E});break;case"pivotBy":l(h,B.id,{label:E});break;case"sortBy":o(h,B.id,{label:E});break}},[h,f,n,r,l,o]),p=A.useCallback((F,T)=>{if(!h)return;const M=f("metrics")[F];M&&r(h,M.id,{aggregate:T,label:s.getAggregationLabel(M.name,T)})},[h,f,r]),j=A.useCallback((F,T,E)=>{if(!h)return;const B=f("groupBy")[F];if(!B)return;const L={dateFormat:T};T==="custom"&&E?L.customFormat=E:L.customFormat=void 0,n(h,B.id,L)},[h,f,n]),x=A.useCallback((F,T)=>{if(!h)return;const M=f("groupBy")[F];M&&n(h,M.id,{granularity:T})},[h,f,n]),v=A.useCallback((F,T)=>{if(!h)return;const M=f("metrics")[F];M&&r(h,M.id,{aliasTemplate:T})},[h,f,r]),k=A.useCallback((F,T)=>{if(console.log("handleValueAliasesChange",F,T),!h)return;console.log("handleValueAliasesChange",F,T);const M=f("metrics")[F];M&&(console.log("handleValueAliasesChange",T),r(h,M.id,{valueAliases:T}))},[h,f,r]),R=A.useCallback(F=>{h&&a(h,{comparisonType:F})},[h,a]),N=A.useCallback(F=>{h&&a(h,{showTrendline:F})},[h,a]),w=A.useCallback(F=>{h&&a(h,{trendlineWindow:F})},[h,a]),y=A.useCallback(F=>{h&&a(h,{trendlineGranularity:F})},[h,a]),D=A.useCallback(F=>{h&&a(h,{targetValue:F})},[h,a]),C=A.useCallback(F=>{var P;if(!h)return;const T=[...f("groupBy"),...f("pivotBy"),...f("metrics"),...f("sortBy")],E=(P=t==null?void 0:t.config)==null?void 0:P.joinPlan,M=s.validateEntityConsistency(F,T,E);if(!M.isValid){M.showError&&s.showJoinRequiredNotification();return}const B=s.getSmartContainerForField(F,T),L=f(B);if(s.fieldAlreadyExists(F,L))return;const O=s.getNewField(F,B,L);O&&g(B,[...L,O])},[h,(S=t==null?void 0:t.config)==null?void 0:S.joinPlan,f,g]),I=A.useCallback((F,T)=>{if(!h)return;const M=f(F)[T];if(M){if(F!=="sortBy"){const B=f("sortBy"),L=B.filter(O=>!(O.name===M.name&&O.qualifiedEntityName===M.qualifiedEntityName));L.length!==B.length&&a(h,{sortByColumns:L})}switch(F){case"groupBy":c(h,M.id);break;case"metrics":i(h,M.id);break;case"pivotBy":d(h,M.id);break;case"sortBy":u(h,M.id);break}}},[h,f,c,i,d,u,a]);return{getFieldsForContainer:f,setFieldsForContainer:g,updateLabel:b,handleAggregationChange:p,handleDateFormatChange:j,handleGranularityChange:x,handleAliasTemplateChange:v,handleValueAliasesChange:k,removeField:I,handleFieldClick:C,handleKpiComparisonTypeChange:R,handleKpiShowTrendlineChange:N,handleKpiTrendlineWindowChange:w,handleKpiTrendlineGranularityChange:y,handleKpiTargetValueChange:D,cardType:m}};function nl({field:t}){return e.jsxs("div",{className:"w-64 bg-background p-0",children:[e.jsxs("div",{className:"mb-2 flex items-start justify-between gap-2",children:[e.jsx("h3",{className:"text-sm font-medium text-foreground",children:t.label||t.name}),e.jsx("span",{className:"rounded bg-muted px-2 py-0.5 font-mono text-xs text-muted-foreground",children:t.dataType})]}),t.description&&e.jsx("p",{className:"mb-3 text-xs text-muted-foreground",children:t.description}),e.jsx("div",{className:"overflow-x-auto border-t border-border pb-2 pt-2",children:e.jsx("span",{className:"font-mono text-xs text-muted-foreground",children:t.name})})]})}function rl({field:t}){const{attributes:a,listeners:n,setNodeRef:r,transform:l,transition:o,isDragging:c}=s.useSortable({id:t.id}),[i,d]=A.useState(!1),u=s.useEditorStore(b=>b.card),{handleFieldClick:m}=Is(u),h={transform:s.CSS.Transform.toString(l),transition:o};s.getDataType(t.dataType);const f=b=>{const p=(b||"").toLowerCase();switch(s.getDataType(p)){case"number":return Ne;case"date":return s.Calendar;case"boolean":return Le;case"json":return Be;case"geo":return _e;default:return ge}},g=b=>{const p=(b||"").toLowerCase(),j=s.getDataType(p);return j==="string"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(ge,{className:"h-3 w-3"})}):j==="number"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(Ne,{className:"h-3 w-3"})}):j==="date"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):j==="boolean"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Le,{className:"h-3 w-3"})}):j==="json"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Be,{className:"h-3 w-3"})}):j==="geo"?e.jsx("div",{className:"bg-orange -100 flex size-6 shrink-0 items-center justify-center rounded-sm text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(_e,{className:"h-3 w-3"})}):j==="calculated"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(qe,{className:"h-3 w-3"})}):null};return f(t.dataType),e.jsxs("div",{ref:r,style:h,...a,...n,className:`group/container overflow-hidden rounded-lg transition-all ${c?"scale-95 opacity-50":"border border-transparent hover:bg-muted"}`,children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3 p-2",onClick:()=>m(t),children:[g(t.dataType),e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:e.jsx("span",{className:`block text-sm text-foreground/80 hover:text-foreground dark:text-muted-foreground ${i?"whitespace-normal break-words":"truncate"}`,children:t.label||t.name})})}),e.jsx(s.TooltipContent,{side:"bottom",align:"start",className:"ml-5 max-w-xs px-4 pb-2 pt-4",children:e.jsx(nl,{field:t})})]})})]}),i&&e.jsx("div",{className:"text-muted-foreground-700 px-2 pb-3 text-sm",children:e.jsx(s.Card,{className:"",children:e.jsxs(s.CardContent,{className:"space-y-2 p-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(nt,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"break-all",children:t.label||t.name})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Wa,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"break-all",children:t.name})]}),e.jsx(s.Badge,{variant:"outline",className:"mt-2 text-xs",children:t.dataType})]})})})]})}function ll(){const[t,a]=A.useState(""),[n,r]=A.useState("all"),l=s.useEditorStore(k=>k.card.dataSource),{columns:o=[],columnGroups:c=[],isLoading:i,error:d}=s.useColumns(),u=o.filter(k=>k.name.toLowerCase().includes(t.toLowerCase())||k.dataType.toLowerCase().includes(t.toLowerCase())||k.qualifiedEntityName&&k.qualifiedEntityName.toLowerCase().includes(t.toLowerCase())),m=k=>{if(k.dataType==="number"||k.dataType==="integer"||k.dataType==="float"||k.dataType==="decimal"||k.dataType==="currency")return"metrics";const R=s.getDataType(k.dataType);return["date","string","boolean"].includes(R)?"dimensions":R==="number"?"metrics":"dimensions"},f=(n==="all"?u:u.filter(k=>m(k)===n)).reduce((k,R)=>{const N=R.qualifiedEntityName||"Other Fields";return k[N]||(k[N]={label:s.toLabel(R.entityName),fields:[]}),k[N].fields.push(R),k},{}),b=Object.keys(f),p=u.filter(k=>m(k)==="dimensions").length,j=u.filter(k=>m(k)==="metrics").length,x=u.filter(k=>m(k)==="calculated").length,v=u.length>0;return i?e.jsx("div",{className:"flex h-[calc(100vh-200px)] w-[290px] flex-col items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):d?e.jsxs("div",{className:"flex h-[calc(100vh-200px)] w-[290px] flex-col items-center justify-center",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-red-300"}),e.jsx("p",{className:"mb-2 text-sm text-red-500",children:"Error loading fields"}),e.jsx("p",{className:"px-4 text-center text-xs text-red-400",children:d.message||"Failed to load column data"})]}):!l||!l.selectedEntities||l.selectedEntities.length===0?e.jsx(s.ScrollArea,{className:"h-[calc(100vh-200px)] w-[290px]",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-gray-300"}),e.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),e.jsx("p",{className:"px-4 text-xs text-gray-400",children:"Select a table, view, or dataset from the data source panel to see available fields"})]})}):e.jsxs("div",{className:"mt-2 flex h-[calc(100vh-200px)] w-full grow flex-col gap-2 px-6 pb-6",children:[e.jsxs("div",{className:"mt-1 flex-shrink-0 space-y-2",children:[o.length>0&&e.jsxs("div",{className:"relative mb-4",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 transform text-muted-foreground"}),e.jsx(s.Input$1,{className:"pl-10",type:"text",placeholder:"Search fields...",value:t,onChange:k=>a(k.target.value)})]}),v&&e.jsx(s.Tabs,{defaultValue:"all",value:n,onValueChange:k=>r(k),className:"mb-4",children:e.jsxs(s.TabsList,{className:"grid h-9 w-full grid-cols-4",children:[e.jsxs(s.TabsTrigger,{value:"all",className:"text-xs",children:["All",e.jsx("span",{className:"ml-2 text-xs font-semibold",children:u.length})]}),e.jsxs(s.TabsTrigger,{value:"dimensions",className:"text-xs",children:[e.jsx(s.Layers,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:p})]}),e.jsxs(s.TabsTrigger,{value:"metrics",className:"text-xs",children:[e.jsx(s.ChartColumn,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:j})]}),e.jsxs(s.TabsTrigger,{value:"calculated",className:"text-xs",children:[e.jsx(qe,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:x})]})]})})]}),e.jsxs(s.CustomScrollArea,{className:"py-2",children:[e.jsx(s.Accordion,{type:"multiple",defaultValue:b,className:"space-y-2",children:Object.entries(f).map(([k,R])=>{const N=c.find(w=>w.entityName===k)||{entityName:k,label:R.label};return e.jsxs(s.AccordionItem,{value:k,className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:e.jsxs("div",{title:N.label||N.entityName,className:"flex items-center gap-2",children:[e.jsx("span",{className:"max-w-[190px] truncate text-ellipsis whitespace-nowrap text-sm font-medium text-primary",children:N.label||N.entityName}),e.jsx(s.Badge,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:R.fields.length})]})}),e.jsx(s.AccordionContent,{className:"pb-2",children:e.jsx("div",{className:"space-y-1",children:R.fields.map(w=>e.jsx(rl,{field:w},w.id))})})]},k)})}),Object.keys(f).length===0&&o.length===0&&e.jsxs("div",{className:"py-8 text-center text-sm text-gray-500",children:[e.jsx("p",{children:"No fields found for selected data source"}),e.jsx("p",{className:"mt-1 text-xs text-gray-400",children:"Try selecting different data sources"})]}),Object.keys(f).length===0&&o.length>0&&e.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"No fields found for this category"}),e.jsx(s.ScrollBar,{orientation:"horizontal"}),e.jsx(s.ScrollBar,{orientation:"vertical"})]})]})}function ol(){return e.jsxs("div",{className:" h-full flex flex-col items-center",children:[" ",e.jsx(ll,{})," "]})}function il({initialJoinPlan:t,availableDataSources:a}){const[n,r]=A.useState(t),[l,o]=A.useState(new Set),c=()=>{const w=n.joins.length>0?Math.max(...n.joins.map(D=>D.sequence))+1:1,y={id:`join-${Date.now()}`,source:{type:"table",name:"",database:"",schema:""},target:{type:"table",name:"",database:"",schema:""},joinType:"INNER",sequence:w,joinKeyGroups:[{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}]};r({...n,joins:[...n.joins,y]}),o(new Set([...l,y.id]))},i=w=>{r({...n,joins:n.joins.filter(y=>y.id!==w)}),o(new Set([...l].filter(y=>y!==w)))},d=(w,y)=>{var S,F;const D=n.joins.find(T=>T.id===w);if(!D)return;const C={...D,...y},I=n.joins.map(T=>T.id===w?C:T);if((S=C.source)!=null&&S.name&&((F=C.target)!=null&&F.name)&&C.joinKeyGroups[0].keys.length===0){const T=a.find(L=>{var O;return L.name===((O=C.source)==null?void 0:O.name)}),E=a.find(L=>{var O;return L.name===((O=C.target)==null?void 0:O.name)}),M={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(T==null?void 0:T.name)||"",entityName:(T==null?void 0:T.name)||"",entityType:(T==null?void 0:T.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(E==null?void 0:E.name)||"",entityName:(E==null?void 0:E.name)||"",entityType:(E==null?void 0:E.type)||"table"},operator:"="},B=[...C.joinKeyGroups];B[0]={...B[0],keys:[M]},C.joinKeyGroups=B,I[I.findIndex(L=>L.id===w)]=C}r({...n,joins:I})};return{joinPlan:n,expandedJoins:l,setJoinPlan:r,addJoin:c,removeJoin:i,updateJoin:d,moveJoinUp:w=>{const y=n.joins.findIndex(D=>D.id===w);if(y>0){const D=[...n.joins],C={...D[y]},I={...D[y-1]};D[y]=I,D[y-1]=C,D.forEach((F,T)=>{F.sequence=T+1});const S={...n,joins:D};r(S)}},moveJoinDown:w=>{const y=n.joins.findIndex(D=>D.id===w);if(y<n.joins.length-1){const D=[...n.joins],C={...D[y]},I={...D[y+1]};D[y]=I,D[y+1]=C,D.forEach((F,T)=>{F.sequence=T+1});const S={...n,joins:D};r(S)}},toggleJoinExpansion:w=>{const y=new Set(l);y.has(w)?y.delete(w):y.add(w),o(y)},getAvailableSourceEntities:w=>{if(n.joins.length===0)return a;const y=n.joins.findIndex(C=>C.id===w);if(y===0)return a;const D=new Set;return n.baseEntity.name&&D.add(n.baseEntity.name),n.joins.slice(0,y).forEach(C=>{D.add(C.source.name),D.add(C.target.name)}),a.filter(C=>D.has(C.name))},getAvailableTargetEntities:w=>a.filter(y=>y.name!==w),addJoinKeyGroup:w=>{const y=n.joins.find(C=>C.id===w);if(!y)return;const D=[...y.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];d(w,{joinKeyGroups:D})},updateGroupOperator:(w,y,D)=>{const C=n.joins.find(S=>S.id===w);if(!C)return;const I=[...C.joinKeyGroups];I[y]={...I[y],operator:D},d(w,{joinKeyGroups:I})},removeJoinKeyGroup:(w,y)=>{const D=n.joins.find(I=>I.id===w);if(!D)return;const C=[...D.joinKeyGroups];C.splice(y,1),d(w,{joinKeyGroups:C})},addJoinKey:(w,y)=>{const D=n.joins.find(T=>T.id===w);if(!D)return;const C=a.find(T=>T.name===D.source.name),I=a.find(T=>T.name===D.target.name),S=[...D.joinKeyGroups],F={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(C==null?void 0:C.name)||"",entityName:(C==null?void 0:C.name)||"",entityType:(C==null?void 0:C.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(I==null?void 0:I.name)||"",entityName:(I==null?void 0:I.name)||"",entityType:(I==null?void 0:I.type)||"table"},operator:"="};S[y]={...S[y],keys:[...S[y].keys,F]},d(w,{joinKeyGroups:S})},updateJoinKey:(w,y,D,C,I)=>{const S=n.joins.find(B=>B.id===w);if(!S)return;const F=a.find(B=>B.name===S.source.name),T=a.find(B=>B.name===S.target.name),E=[...S.joinKeyGroups],M=E[y].keys[D];C==="sourceColumnName"&&F?E[y].keys[D]={...M,source:{...M.source,name:I}}:C==="targetColumnName"&&T?E[y].keys[D]={...M,target:{...M.target,name:I}}:C==="operator"&&(E[y].keys[D]={...M,operator:I}),d(w,{joinKeyGroups:E})},removeJoinKey:(w,y,D)=>{const C=n.joins.find(S=>S.id===w);if(!C)return;const I=[...C.joinKeyGroups];I[y].keys.splice(D,1),d(w,{joinKeyGroups:I})},generateSQLPreview:()=>{const w=[...n.joins].sort((C,I)=>C.sequence-I.sequence),y=n.baseEntity;if(!y.name)return"SELECT * FROM table -- Please select a base entity";let D=`SELECT *
|
|
354
|
-
FROM ${y.name}`;return
|
|
355
|
-
${
|
|
356
|
-
ON ${F}`}),D},isValidConfiguration:()=>!(!n.baseEntity.name||n.joins.some(C=>!C.source.name||!C.target.name)||n.joins.some(C=>C.joinKeyGroups.some(I=>I.keys.length===0))||n.joins.some(C=>C.joinKeyGroups.some(I=>I.keys.some(S=>!S.source.name||!S.target.name||!S.operator))))}}function cl({joinPlan:t,availableDataSources:a,onSave:n,onRemove:r,onCancel:l}){const{setCardConfig:o}=s.useEditorActions();s.useEditorStore(S=>S.card.config);const{columnGroups:c}=s.useColumns(),{joinPlan:i,expandedJoins:d,setJoinPlan:u,addJoin:m,removeJoin:h,updateJoin:f,moveJoinUp:g,moveJoinDown:b,toggleJoinExpansion:p,getAvailableSourceEntities:j,getAvailableTargetEntities:x,addJoinKeyGroup:v,updateGroupOperator:k,removeJoinKeyGroup:R,addJoinKey:N,updateJoinKey:w,removeJoinKey:y,generateSQLPreview:D,isValidConfiguration:C}=il({initialJoinPlan:t,availableDataSources:a}),I=S=>{const F=c.find(T=>T.entityName===S);return(F==null?void 0:F.columns)||[]};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Base Entity (FROM clause)"}),e.jsxs(s.Select,{value:i.baseEntity.name,onValueChange:S=>{const F=a.find(T=>T.name===S);u({...i,baseEntity:{connectionId:(F==null?void 0:F.connectionId)||"",connectionType:(F==null?void 0:F.connectionType)||"none",type:(F==null?void 0:F.type)||"table",name:S,database:F==null?void 0:F.database,schema:F==null?void 0:F.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select base entity..."})}),e.jsx(s.SelectContent,{children:a.map(S=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:S.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:S.type}),S.name,e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]})},S.name))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This entity will be used as the base table in the FROM clause of the SQL query."})]}),e.jsxs("div",{className:"rounded-md border p-3",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"Join SQL Preview"}),e.jsx("code",{className:"block whitespace-pre-wrap break-all text-xs",children:D()})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{children:["Joins Configuration (",i.joins.length,")"]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:m,children:[e.jsx(s.Plus,{className:"mr-1 h-4 w-4"}),"Add Join"]})})]}),i.joins.length===0?e.jsx("div",{className:"rounded-lg border border-dashed py-8 text-center text-muted-foreground",children:e.jsx("p",{children:"No joins configured. Add a join to connect multiple data sources."})}):e.jsx("div",{className:"max-h-[300px] space-y-4 overflow-y-auto",children:i.joins.map(S=>{const F=a.find(M=>M.name===S.source.name),T=a.find(M=>M.name===S.target.name),E=d.has(S.id);return e.jsxs(s.Card,{className:"border",children:[e.jsx(s.CardHeader,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{children:S.sequence}),e.jsxs(s.CardTitle,{className:"text-sm",children:["Join ",S.sequence,F&&T&&e.jsxs("span",{className:"ml-2 font-normal text-gray-600",children:["(",F.name," → ",T.name,")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>g(S.id),disabled:S.sequence===1,children:e.jsx(s.ArrowUp,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>b(S.id),disabled:S.sequence===i.joins.length,children:e.jsx(s.ArrowDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>p(S.id),children:E?e.jsx(s.ChevronUp,{className:"h-4 w-4"}):e.jsx(s.ChevronDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>h(S.id),children:e.jsx(s.X,{className:"h-4 w-4"})})]})]})}),E&&e.jsxs(s.CardContent,{className:"space-y-4 pb-6",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Source"}),e.jsxs(s.Select,{value:S.source.name,onValueChange:M=>{const B=a.find(L=>L.name===M);f(S.id,{source:{connectionId:(B==null?void 0:B.connectionId)||"",connectionType:(B==null?void 0:B.connectionType)||"none",type:(B==null?void 0:B.type)||"table",name:M,database:B==null?void 0:B.database,schema:B==null?void 0:B.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select source..."})}),e.jsx(s.SelectContent,{children:j(S.id).map(M=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:M.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:M.type}),M.name]})},M.name))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Join Type"}),e.jsxs(s.Select,{value:S.joinType,onValueChange:M=>f(S.id,{joinType:M}),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"INNER",children:"INNER JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"LEFT",children:"LEFT JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"RIGHT",children:"RIGHT JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"FULL",children:"FULL JOIN"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Target"}),e.jsxs(s.Select,{value:S.target.name,onValueChange:M=>{const B=a.find(L=>L.name===M);f(S.id,{target:{connectionId:(B==null?void 0:B.connectionId)||"",connectionType:(B==null?void 0:B.connectionType)||"none",type:(B==null?void 0:B.type)||"table",name:M,database:B==null?void 0:B.database,schema:B==null?void 0:B.schema}})},disabled:!S.source.name,children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select target..."})}),e.jsx(s.SelectContent,{children:S.source.name?x(S.source.name).map(M=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:M.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:M.type}),M.name,M.name===S.source.name&&e.jsx(s.Badge,{variant:"outline",className:"text-xs text-yellow-600",children:"(Self-join)"})]})},M.name)):[]})]})]})]}),S.source.name&&S.target.name&&F&&T&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{children:"Join Conditions"}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>v(S.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition Group"]})]}),S.joinKeyGroups.length===0?e.jsx("div",{className:"rounded-md border p-3 text-center text-sm text-gray-500",children:"No join conditions defined. Add condition groups to specify how data sources should be joined."}):e.jsx("div",{className:"space-y-4",children:S.joinKeyGroups.map((M,B)=>e.jsxs("div",{className:"space-y-3 rounded-md border p-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Label,{children:["Group ",B+1]}),B>0&&e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-gray-100 px-2 py-1",children:[e.jsx(s.Label,{className:"text-xs font-normal",children:"Join with:"}),e.jsx("span",{className:"text-sm font-medium",children:"OR"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Select,{value:M.operator,onValueChange:L=>k(S.id,B,L),children:[e.jsx(s.SelectTrigger,{className:"w-[100px]",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(s.SelectItem,{value:"OR",children:"OR"})]})]}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",onClick:()=>R(S.id,B),children:e.jsx(s.Trash2,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[M.keys.length===0?e.jsx("div",{className:"rounded-md border border-dashed p-3 text-center text-sm text-gray-500",children:"No conditions in this group. Add conditions to specify join criteria."}):e.jsx("div",{className:"space-y-2",children:M.keys.map((L,O)=>e.jsxs("div",{className:"flex flex-col items-start gap-2 rounded-md border p-2 sm:flex-row sm:items-center",children:[O>0&&e.jsx("div",{className:"self-center rounded-md bg-gray-100 px-2 py-1 text-xs font-medium",children:M.operator}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:L.source.name,onValueChange:P=>w(S.id,B,O,"sourceColumnName",P),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Source column"})}),e.jsx(s.SelectContent,{children:I(S.source.name).map(P=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:P.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:P.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:P.dataType})]})},P.name))})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:w-20",children:e.jsxs(s.Select,{value:L.operator,onValueChange:P=>w(S.id,B,O,"operator",P),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"=",children:"="}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"<",children:"<"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:">",children:">"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"<=",children:"<="}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:">=",children:">="})]})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:L.target.name,onValueChange:P=>w(S.id,B,O,"targetColumnName",P),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Target column"})}),e.jsx(s.SelectContent,{children:I(S.target.name).map(P=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:P.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between hover:bg-muted",children:[e.jsx("span",{children:P.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:P.dataType})]})},P.name))})]})}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"self-center",onClick:()=>y(S.id,B,O),children:e.jsx(s.X,{className:"size-3.5"})})]},L.id||O))}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>N(S.id,B),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition"]})]})]},M.id))})]})]})]},S.id)})})]}),e.jsxs("div",{className:"flex justify-end gap-2 border-t pt-4",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>{r(),l()},children:"Remove All"}),e.jsx(s.Button,{variant:"outline",onClick:l,children:"Cancel"}),e.jsx(s.Button,{onClick:()=>n(i),disabled:!C(),children:"Save"})]})]})}function Ws({children:t,open:a,onOpenChange:n,joinPlan:r,availableDataSources:l,onRemove:o,onSave:c,onCancel:i}){return e.jsxs(s.Dialog,{open:a,onOpenChange:n,children:[e.jsxs(s.DialogContent,{className:"max-w-4xl",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Join Configuration"}),e.jsx(s.DialogDescription,{children:"Configure the join between the two entities to combine the fields."})]}),e.jsx(cl,{joinPlan:r,availableDataSources:l,onSave:c,onCancel:i,onRemove:o})]}),t]})}function dl({joins:t,baseEntityId:a,availableDataSources:n,generateSQLPreview:r}){return e.jsxs("div",{className:"divide-y divide-border",children:[t.length>0&&e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left font-semibold",children:"Join Chain"}),e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:(()=>{const l=[...t].sort((c,i)=>c.sequence-i.sequence),o=n.find(c=>c.name===a);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(s.Badge,{variant:"secondary",className:"text-xs",children:o==null?void 0:o.type}),e.jsx("span",{className:"text-xs font-medium",children:o==null?void 0:o.name}),e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]}),l.map(c=>{const i=n.find(d=>d.name===c.target.name);return e.jsxs("div",{className:"flex items-center",children:[e.jsxs("div",{className:"mx-1 flex items-center gap-1",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:c.joinType}),e.jsx("span",{className:"text-muted-foreground",children:"→"})]}),e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(s.Badge,{variant:"secondary",className:"text-xs",children:i==null?void 0:i.type}),e.jsx("span",{className:"text-xs font-medium",children:i==null?void 0:i.name})]})]},c.id)})]})})()})]}),e.jsxs("div",{className:"p-4",children:[e.jsxs("h3",{className:"mb-3 text-left text-sm font-medium",children:["Configured Joins (",t.length,")"]}),e.jsx("div",{className:"space-y-2",children:[...t].sort((l,o)=>l.sequence-o.sequence).map((l,o)=>{const c=n.find(d=>d.name===l.source.name),i=n.find(d=>d.name===l.target.name);return e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-muted p-2 text-left",children:[e.jsx(s.Badge,{variant:"secondary",className:"shrink-0 text-xs",children:o+1}),e.jsx(s.Badge,{variant:"outline",className:"shrink-0 text-xs",children:l.joinType}),e.jsxs("span",{className:"text-xs font-medium",children:[c==null?void 0:c.name," → ",i==null?void 0:i.name]}),e.jsxs(s.Badge,{variant:"outline",className:"ml-auto text-xs",children:[l.joinKeyGroups.reduce((d,u)=>d+u.keys.length,0)," ","condition",l.joinKeyGroups.reduce((d,u)=>d+u.keys.length,0)>1?"s":""]})]},l.id)})})]}),e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left text-sm font-medium",children:"SQL Query"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap break-all text-left font-mono text-xs text-muted-foreground",children:r()})})]})]})}function ul(){var m,h;const t=s.useEditorStore(f=>f.card),a=s.useEditorStore(f=>f.actions.updateCardConfig),n=((m=t==null?void 0:t.config)==null?void 0:m.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[r,l]=A.useState(!1),o=((h=t==null?void 0:t.dataSource)==null?void 0:h.selectedEntities)||[],c=f=>{a(t.id,{...t==null?void 0:t.config,joinPlan:f}),l(!1)},i=()=>{a(t.id,{...t==null?void 0:t.config,joinPlan:void 0})},d=()=>{l(!1)},u=()=>{const f=[...n.joins].sort((p,j)=>p.sequence-j.sequence),g=n.baseEntity;if(!g.name)return"SELECT * FROM table -- Please select a base entity";let b=`SELECT *
|
|
357
|
-
FROM ${g.name}`;return f.forEach(p=>{const j=o.find(k=>k.name===p.target.name);if(!j)return;const x=p.joinKeyGroups.filter(k=>k.keys&&k.keys.length>0).map(k=>{const
|
|
347
|
+
`;v($)}function R(){return e.jsxs(e.Fragment,{children:[r&&e.jsx("div",{className:"relative flex w-1/3 min-w-0 grow overflow-hidden text-xs",role:"editor-filter-container",children:e.jsx("div",{className:"mt-2 w-[99%]",children:e.jsx(_n,{jsonString:JSON.stringify(u,null,2)})})}),u&&u.length>0&&e.jsx(s.Button,{variant:"ghost",onClick:()=>l(!r),className:"absolute bottom-0 right-6 size-7 p-1",children:r?e.jsx(s.X,{className:"size-3.5 text-muted-foreground"}):e.jsx(s.Filter,{className:"size-3.5 text-muted-foreground"})})]})}function P(){return e.jsxs(s.ResizablePanelGroup,{className:"flex grow pb-1",direction:"vertical",role:"editor-resizable-group",children:[e.jsxs(s.ResizablePanel,{id:"1",order:1,defaultSize:a?20:100,className:"relative flex grow",children:[e.jsx("div",{id:"sql-container",className:"relative flex w-[99%]",children:e.jsx(zn,{})}),a&&e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"sql"})]}),a&&e.jsxs(e.Fragment,{children:[e.jsx(s.ResizableHandle,{withHandle:!0,className:"border"}),e.jsxs(s.ResizablePanel,{id:"2",order:2,defaultSize:80,className:"relative flex grow",children:[e.jsx("div",{id:"python-container",className:"relative flex w-[99%] pt-0",children:e.jsx(Vn,{})}),e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"python"})]})]})]})}function K(){return e.jsxs("div",{role:"editor-controls",className:"item-center flex flex-wrap justify-between gap-2 px-6 py-4",children:[e.jsxs("div",{className:"flex grow items-center gap-2",children:[e.jsxs(s.Button,{title:"Shift + Enter",disabled:D||N,onClick:()=>{A()},className:"h-8 shrink-0",size:"sm",children:[D||N?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(s.Play,{className:"mr-2 h-4 w-4"}),"Run"]}),e.jsx(wt,{errorSql:T,sql:y==null?void 0:y.sql,error:O,onDebugWithAssistant:M}),e.jsx(rs,{}),e.jsx(s.Toggle,{pressed:a,onPressedChange:$=>n($),className:"h-8",size:"sm",variant:"outline",children:e.jsx(Pn,{className:"size-4 text-foreground/70"})}),e.jsx("button",{disabled:c,onClick:()=>{k(!0)},className:"h-9 w-full cursor-text px-3 text-left text-sm text-muted-foreground",children:c?"":"Type your question..."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ds,{}),e.jsx(ws,{})]})]})}return e.jsxs("section",{role:"editor-section",className:"flex grow flex-col justify-end",children:[e.jsxs("div",{className:"relative flex grow justify-between overflow-y-scroll",children:[P(),R()]}),K()]})}const Yn=[{value:"table",label:"Table",icon:s.Table2},{value:"aggregateTable",label:"Aggregate",icon:s.Layers},{value:"pivotTable",label:"Pivot",icon:ns}];function qn({className:t}){const a=s.useEditorStore(d=>d.card),{setCardType:n,setCard:r,updateCardInFrame:l}=s.useEditorActions(),o=["table","aggregateTable","pivotTable"].includes(a.type),c=s.hasValidCardConfig(a.config);if(!o||!c)return null;const i=d=>{var m;const u=d;if(u==="aggregateTable"&&((m=a.config)!=null&&m.pivotByColumns)&&a.config.pivotByColumns.length>0){const h={...a,type:u,config:{...a.config,pivotByColumns:[]}};r(h),l(h)}else{n(u);const h={...a,type:u};l(h)}};return e.jsx("div",{className:s.cn("flex items-center",t),children:e.jsx(s.RadioGroup,{value:a.type,onValueChange:i,className:"flex flex-row items-center justify-between gap-1 rounded-lg border p-1",children:Yn.map(d=>{const u=d.icon;return e.jsxs("div",{className:"flex items-center",children:[e.jsx(s.RadioGroupItem,{value:d.value,id:`table-type-${d.value}`,className:"peer sr-only"}),e.jsxs(s.Label,{htmlFor:`table-type-${d.value}`,className:s.cn("flex cursor-pointer items-center gap-1.5 rounded-md px-3 py-1 text-sm font-medium transition-all","hover:bg-muted","peer-data-[state=checked]:bg-background peer-data-[state=checked]:shadow-sm"),children:[e.jsx(u,{className:"h-3.5 w-3.5"}),d.label]})]},d.value)})})})}function Gn({card:t}){var v,k,L,C,S,y,D,N,B,w,F;const[a,n]=I.useState(!1),[r,l]=I.useState([]),{authToken:o}=s.useSemaphorContext(),c=s.getTokenParams(o==null?void 0:o.accessToken),i=s.useDashboardStore(T=>T.themeStyle),d={colors:((k=(v=i==null?void 0:i.chart)==null?void 0:v.dataset)==null?void 0:k.backgroundColor)||[]};(L=t.customCardPreferences)!=null&&L.inputData;const{getCard:u}=s.useCustomVisual(((C=t.customCardPreferences)==null?void 0:C.url)||""),m=((S=t.customCardPreferences)==null?void 0:S.visualType)||"single",h=s.useEditorStore(T=>T.frame),{setCustomCardPreferences:f}=s.useEditorActions(),{data:g}=s.useDashboardCardQuery(t),b=I.useCallback((T,E)=>{l(A=>({...A,[T]:E}))},[]);if(!((y=t.customCardPreferences)!=null&&y.componentName))return null;const p=u((D=t.customCardPreferences)==null?void 0:D.componentName);function j(T){n(T)}const x=Object.keys(((N=t.customCardPreferences)==null?void 0:N.dataInputCardIds)||{}).map(T=>{var O,M,R;const E=(M=(O=t.customCardPreferences)==null?void 0:O.dataInputCardIds)==null?void 0:M[T].cardId,A=(R=h==null?void 0:h.cards)==null?void 0:R.find(P=>P.id===E);return A||null});return e.jsx("div",{className:"semaphor-custom mb-3 flex grow basis-0 flex-col space-y-2 overflow-y-auto",children:e.jsxs(I.Suspense,{fallback:e.jsx(e.Fragment,{}),children:[p&&m==="single"&&e.jsx(p,{editing:!0,params:c,theme:d,settings:(B=t.customCardPreferences)==null?void 0:B.settings,onDataChange:b,data:(g==null?void 0:g.records)||[]}),p&&m==="multiple"&&e.jsxs(e.Fragment,{children:[Object.keys(((w=t.customCardPreferences)==null?void 0:w.dataInputCardIds)||{}).map(T=>{var O,M,R;const E=(M=(O=t.customCardPreferences)==null?void 0:O.dataInputCardIds)==null?void 0:M[T].cardId,A=(R=h==null?void 0:h.cards)==null?void 0:R.find(P=>P.id===E);if(A)return e.jsx(s.MultiInputEmptyRenderer,{onLoadingStatus:j,onDataChange:b,dataInputIndex:T,card:A},A.id+T)}),e.jsx("div",{className:"flex flex-col gap-2",children:e.jsx(p,{theme:d,onDataChange:b,settings:x.map(T=>{var E;return(E=T==null?void 0:T.customCardPreferences)==null?void 0:E.settings}),data:x.map(T=>T!=null&&T.id?r==null?void 0:r[T.id]:[])})})]})]},(F=t.customCardPreferences)==null?void 0:F.componentName)})}function kt({className:t,...a}){var D;const n=s.useEditorStore(N=>N.card),r=s.isExplorerCard(n),l=((D=n.customCardPreferences)==null?void 0:D.showCardHeader)??!0,o=s.useEditorStore(N=>N.frame),c=s.useDashboardStore(N=>N.dashboard.filters),i=s.useEditorStore(N=>N.actions.setRunSql),{updateFilter:d}=s.useDashboardActions(),u=c==null?void 0:c.find(N=>N.id===o.filterId),{data:m,isLoading:h,isFetching:f,errorMessage:g,pagination:b}=s.useDashboardCardQuery(n),{setCard:p,updateCardInFrame:j}=s.useEditorActions(),{data:x}=s.useTopoJson(n),v=I.useMemo(()=>{var N;return n.type!=="pivotTable"||!((N=m==null?void 0:m.records)!=null&&N.length)?null:{records:m.records,columnSubtotalMeta:m.columnSubtotalMeta,subtotalColumns:m.subtotalColumns||[],pivotSchema:m.pivotSchema||[],groupByColumns:m.groupByColumns}},[n.type,m==null?void 0:m.records,m==null?void 0:m.columnSubtotalMeta,m==null?void 0:m.subtotalColumns,m==null?void 0:m.pivotSchema,m==null?void 0:m.groupByColumns]),k=s.usePivotTableConfig(n,v),L=(N,B)=>{var F,T;const w={...n,paginationConfig:{page:N+1,pageSize:B}};p(w),j(w),n.sql&&((T=(F=n.preferences)==null?void 0:F.tablePrefs)!=null&&T.enableDevModePagination)&&i(!0)},C=I.useMemo(()=>!n.id||!(m!=null&&m.records)?null:s.createChartConfig({card:n,data:m==null?void 0:m.records,cardType:n.type,queryConfig:n.queryConfig,customCfg:n.customCfg,preferences:n.preferences,topoJson:x}),[n.id,m==null?void 0:m.records,n.type,n.queryConfig,n.customCfg,n.preferences,x]);function S(N){return e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(Gn,{card:N})})}function y(){if(m!=null&&m.records&&(m==null?void 0:m.records.length)===0&&!h&&!f)return g?e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(s.SearchX,{className:"size-8 text-destructive"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:r?"Error fetching data. Please check your chart configuration":"Error fetching data. Please check your SQL or Python code."})]}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(s.TreePalm,{className:"size-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No results to display"})]});if((h||f)&&n.type!=="table")return e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})});if(!n.id)return null;if(n.type==="custom")return S(n);if(!["table","pivotTable","aggregateTable","custom"].includes(n.type)&&C)return e.jsx("div",{className:"relative h-full min-h-0 w-full flex-1 grow basis-0",children:h||f?e.jsx(e.Fragment,{}):e.jsx(s.ChartJsVisual,{cfg:C})});if(n.type==="table")return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.TableVisual,{card:n,data:(m==null?void 0:m.records)||[],paginationMetadata:b,onPaginationChange:L,isLoading:h||f})});if(n.type==="pivotTable"&&k)return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.PivotTableVisual,{card:n,data:k.data,options:k.options,onAggregationChange:N=>{const B=s.handleAggregationChange(N,n.config),w={...n,config:B};p(w),j(w)},onAggregationLabelChange:N=>{const B=s.handleAggregationLabelChange(N,n.config),w={...n,config:B};p(w),j(w)}})});if(n.type==="aggregateTable")return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.AggregateTable,{card:n,data:(m==null?void 0:m.records)||[],groupByColumns:m==null?void 0:m.groupByColumns,pivotSchema:m==null?void 0:m.pivotSchema,paginationMetadata:b,onPaginationChange:L,onAggregationChange:N=>{const B=s.handleAggregationChange(N,n.config),w={...n,config:B};p(w),j(w)},isLoading:h||f})})}return e.jsxs(s.Card,{role:"editor-visual-card",className:s.cn("relative flex h-full flex-col rounded-none",t),...a,children:[l&&e.jsxs(s.CardHeader,{className:"flex flex-row items-start justify-between py-4",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-5",children:[e.jsx(s.CardTitle,{className:"text-base",children:e.jsx(s.EditableText,{value:n.title,onSave:N=>p({...n,title:N}),isEditable:!0,placeholder:"Add title",displayClassName:"text-base font-semibold",inputClassName:"text-base font-semibold"})}),e.jsx(qn,{})]}),e.jsx("div",{className:"w-1/2",children:e.jsx(s.EditableText,{value:n.description||"",onSave:N=>p({...n,description:N}),isEditable:!0,placeholder:"Add description",displayClassName:"text-sm text-muted-foreground",inputClassName:"text-sm"})})]}),u&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Label,{className:"my-1",children:e.jsx(s.EditableText,{value:u.title||u.column,onSave:N=>d({...u,title:N}),isEditable:!0,placeholder:"Filter",displayClassName:"text-sm",inputClassName:"text-sm"})}),e.jsx(s.FilterComponent,{filter:u})]})]}),e.jsx(s.CardContent,{className:"flex grow flex-col",children:y()})]})}const hs=({language:t,value:a,onChange:n,readonly:r})=>e.jsx(s.Ft,{className:"h-full w-full overflow-hidden text-xs",theme:"default",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,lineHeight:16,renderLineHighlight:"none",readOnly:r},defaultLanguage:t,value:a,onChange:n}),Hn=()=>e.jsxs(s.DialogHeader,{children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(s.DialogTitle,{children:"Customize Card"})}),e.jsxs(s.DialogDescription,{children:["See the configuration options and documentation",e.jsx("a",{target:"_blank",className:"ml-1 text-blue-500 underline",href:"https://www.chartjs.org/docs/latest/samples/bar/vertical.html",children:"here."})]})]}),Wn=({customCode:t,cardCustomCfgString:a,mergedConfig:n,onConfigChange:r,onCodeChange:l})=>e.jsxs(s.Tabs,{defaultValue:"final-config",className:"flex w-1/2 flex-col",children:[e.jsxs(s.TabsList,{className:"justify-start rounded-sm rounded-b-none border border-b-0",children:[e.jsx(s.TabsTrigger,{value:"final-config",children:"Config"}),e.jsx(s.TabsTrigger,{value:"custom-config",children:"Changes"}),e.jsx(s.TabsTrigger,{value:"custom-code",children:"Custom Code"})]}),e.jsx(s.TabsContent,{value:"final-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(hs,{language:"json",value:n,onChange:r})}),e.jsx(s.TabsContent,{value:"custom-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(hs,{readonly:!0,language:"json",value:a,onChange:()=>{}})}),e.jsx(s.TabsContent,{value:"custom-code",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(hs,{language:"javascript",value:t,onChange:l})})]}),Kn=({error:t,hasCardCustomConfig:a,onReset:n,onApply:r,onClose:l})=>e.jsxs(s.DialogFooter,{className:"flex items-center",children:[e.jsx(s.Label,{className:"mr-2 text-red-500",children:t}),e.jsx(s.Button,{disabled:!a,onClick:n,variant:"outline",children:"Reset"}),e.jsx(s.Button,{onClick:r,variant:"outline",children:"Apply"}),e.jsx(s.Button,{onClick:l,variant:"outline",children:"Close"})]});function Jn(){const[t,a]=I.useState(!1),[n,r]=I.useState(""),[l,o]=I.useState(""),[c,i]=I.useState(""),[d,u]=I.useState(""),m=s.useEditorStore(C=>C.card),h=s.useEditorStore(C=>C.card.customCfg),f=h?JSON.stringify(h,null,2):"",{data:g}=s.useDashboardCardQuery(m),{data:b}=s.useTopoJson(m),{setCardCustomCfg:p,setCustomVisualCode:j}=s.useEditorActions(),x=C=>{var S,y;return JSON.stringify({...C,data:{...C.data,datasets:(y=(S=C.data)==null?void 0:S.datasets)==null?void 0:y.map(D=>({...D,data:[]}))}},null,2)},v=()=>{var S,y;if(!((S=g==null?void 0:g.records)!=null&&S.length))return;const C=s.createChartConfig({card:m,data:g.records,cardType:m.type,queryConfig:m.queryConfig,preferences:m.preferences,topoJson:b});if(C){r(x(C)),i(((y=m.preferences)==null?void 0:y.customVisualCode)||"");const D=s.merge(C,h);o(x(D))}},k=()=>{try{if(c&&j(c),l){const C=JSON.parse(l),S=s.getObjectDiff(JSON.parse(n),C);p(S),u("")}}catch{u("Invalid JSON configuration")}},L=Object.keys(h||{}).length===0;return e.jsxs(s.Dialog,{open:t,onOpenChange:a,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Customize Visual",onClick:v,className:L?"":"text-green-600 hover:text-green-700",children:e.jsx(s.Settings,{className:"h-4 w-4"})})}),e.jsxs(s.DialogContent,{className:"flex h-[600px] grow flex-col overflow-auto sm:min-w-[900px] lg:min-w-[1200px]",children:[e.jsx(Hn,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(kt,{className:"w-1/2 rounded shadow-none"})}),e.jsx(Wn,{customCode:c,cardCustomCfgString:f,mergedConfig:l,onConfigChange:C=>o(C??""),onCodeChange:C=>i(C??"")})]}),e.jsx(Kn,{error:d,hasCardCustomConfig:!!h,onReset:()=>{o(n),p(null)},onApply:k,onClose:()=>a(!1)})]})]})}function ls(t){const[a,n]=I.useState(null);return a}function Tt(){const{authToken:t}=s.useSemaphorContext(),{data:a,isLoading:n,isFetching:r,isError:l}=s.useQuery({queryKey:["plugins",t==null?void 0:t.accessToken],queryFn:()=>s.getPlugins(t==null?void 0:t.accessToken)});return{data:a,isLoading:n,isFetching:r,isError:l}}function Et(){const{data:t,isLoading:a,isError:n}=Tt(),r=s.useQueries({queries:((t==null?void 0:t.plugins)||[]).map(i=>({queryKey:["manifest",i.value],queryFn:()=>s.loadManifest(i.value),enabled:!!i.value,staleTime:5*60*1e3,gcTime:10*60*1e3,retry:2,retryDelay:d=>Math.min(1e3*2**d,3e4)}))}),l=[];let o=a,c=n;return r.forEach((i,d)=>{var u;if(i.isLoading&&(o=!0),i.isError&&(c=!0),i.data&&((u=t==null?void 0:t.plugins)!=null&&u[d])){const m=t.plugins[d],h=i.data.visuals.map(f=>({name:f.name,pluginName:m.label,componentType:f.componentType,pluginType:m.type,icon:f.icon,chartType:f.chartType,url:m.value}));l.push(...h)}}),{data:l,isLoading:o,isError:c}}function Qn({onChartTypeChange:t}){const{setCardCustomCfg:a,setCardPreferences:n,setCardType:r,setCustomCardPreferences:l}=s.useEditorActions(),{data:o,isLoading:c,isError:i}=Et(),d=I.useCallback((u,m)=>{a(null),n({}),r(u),m&&l({type:"component",visualType:"single",url:m.url,componentName:m.name,icon:m.icon}),t==null||t()},[a,n,r,l,t]);return c?e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"grid grid-cols-4 place-items-center",children:e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading custom visuals..."})})]}):i?e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"grid grid-cols-4 place-items-center",children:e.jsx("div",{className:"text-sm text-destructive",children:"Failed to load custom visuals"})})]}):!o||o.length===0?null:e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"grid grid-cols-4 place-items-center",children:o.map((u,m)=>e.jsx(Xn,{text:u.name,onClick:()=>d("custom",u),icon:u.icon},`${u.url}-${u.name}-${m}`))})]})}const Xn=({text:t,icon:a,onClick:n})=>{const r=ls(),l=t.charAt(0).toUpperCase();return e.jsx(s.IconButton,{onClick:n,tooltip:t,children:r?e.jsx(r,{className:"h-4 w-4"}):l})};function It({onChartTypeChange:t,iconClassName:a}){const{setCardType:n,setCardPreferences:r,setIsDevMode:l}=s.useEditorStore(m=>m.actions),{setCardCustomCfg:o,setCustomCardPreferences:c,setQueryConfig:i}=s.useEditorActions();function d(m,h){o(null),r({}),n(m),["custom","text","map"].includes(m)&&(l(!0),i(void 0)),t==null||t()}const u=1e3;return e.jsxs("div",{className:"grid grid-cols-5 place-items-center",children:[e.jsx(s.IconButton,{openDelay:u,tooltip:"Table",onClick:()=>d("table"),className:"h-10 p-4",children:e.jsx(s.Table2,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Bar Chart",onClick:()=>d("bar"),className:"h-10 p-4",children:e.jsx(s.ChartColumnIncreasing,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Line Chart",onClick:()=>d("line"),className:"h-10 p-4",children:e.jsx(s.ChartLine,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Stacked Bar Chart",onClick:()=>d("stackedBar"),className:"h-10 p-4",children:e.jsx(s.ChartColumnStacked,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Stacked Line Chart",onClick:()=>d("stackedLine"),className:"h-10 p-4",children:e.jsx(s.MdStackedLineChart,{className:s.cn("size-5",a),strokeWidth:0})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Scatter Chart",onClick:()=>d("scatter"),className:"h-10 p-4",children:e.jsx(s.ChartScatter,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Bubble Chart",onClick:()=>d("bubble"),className:"h-10 p-4",children:e.jsx(s.TbChartBubble,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Pie Chart",onClick:()=>d("pie"),className:"h-10 p-4",children:e.jsx(s.ChartPie,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Doughnut Chart",onClick:()=>d("doughnut"),className:"h-10 p-4",children:e.jsx(s.Donut,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Funnel Chart",onClick:()=>d("funnel"),className:"h-10 p-4",children:e.jsx(s.TbChartFunnel,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Radar Chart",onClick:()=>d("radar"),className:"h-10 p-4",children:e.jsx(s.Radar,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Polar Area Chart",onClick:()=>d("polarArea"),className:"h-10 p-4",children:e.jsx(s.PiChartPolar,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Tornado Chart",onClick:()=>d("tornado"),className:"h-10 p-4",children:e.jsx(s.Tornado,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{tooltip:"Range Chart",onClick:()=>d("range"),className:"h-10 p-4",children:e.jsx(s.ChartNoAxesGantt,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"KPI",onClick:()=>d("kpi"),className:"h-10 p-4",children:e.jsx(s.TiSortNumerically,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Text",onClick:()=>d("text"),className:"h-10 p-4",children:e.jsx(s.BookType,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{tooltip:"Map",onClick:()=>d("map"),className:"h-10 p-4",children:e.jsx(s.Map,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Custom",onClick:()=>d("custom"),className:"h-10 p-4",children:e.jsx(Ue,{className:s.cn("size-5",a)})})]})}function Zn({chartType:t,className:a,customIcon:n,componentName:r}){const l=ls();switch(t){case"bar":return e.jsx(s.ChartColumnIncreasing,{className:a});case"line":return e.jsx(s.ChartLine,{className:a});case"pie":return e.jsx(s.ChartPie,{className:a});case"radar":return e.jsx(s.Radar,{className:a});case"scatter":return e.jsx(s.ChartScatter,{className:a});case"bubble":return e.jsx(s.TbChartBubble,{className:a});case"doughnut":return e.jsx(s.Donut,{className:a});case"stackedBar":return e.jsx(s.ChartColumnStacked,{className:a});case"stackedLine":return e.jsx(s.MdStackedLineChart,{className:a});case"polarArea":return e.jsx(s.PiChartPolar,{className:a});case"funnel":return e.jsx(s.TbChartFunnel,{className:a});case"tornado":case"pyramid":return e.jsx(s.Tornado,{className:a});case"range":return e.jsx(s.ChartNoAxesGantt,{className:a});case"kpi":return e.jsx(s.TiSortNumerically,{className:a});case"text":return e.jsx(ge,{className:a});case"map":return e.jsx(s.Map,{className:a});case"custom":return n&&l?e.jsx(l,{className:a}):r?r==null?void 0:r.charAt(0).toUpperCase():e.jsx(Ue,{className:a});default:return e.jsx(s.Table2,{className:a})}}function At({variant:t="ghost"}){var o,c;const[a,n]=I.useState(!1),r=s.useEditorStore(i=>i.card),l=r.type;return s.useDashboardStore(i=>i.isVisualEditing),e.jsxs(s.Popover,{open:a,onOpenChange:n,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:t||"ghost",children:e.jsx(Zn,{className:"size-4",chartType:l,customIcon:(o=r.customCardPreferences)==null?void 0:o.icon,componentName:(c=r.customCardPreferences)==null?void 0:c.componentName})})}),e.jsxs(s.PopoverContentCustom,{onOpenAutoFocus:i=>i.preventDefault(),className:"w-72 p-1",children:[e.jsx(It,{onChartTypeChange:()=>n(!1)}),e.jsx(Qn,{onChartTypeChange:()=>n(!1)})]})]})}function er({error:t,className:a="",textClassName:n="",copyButtonClassName:r=""}){const[l,o]=I.useState(!1),c=I.useRef(null),i=I.useRef(!1);function d(){t&&!i.current&&navigator.clipboard.writeText(t)}function u(f){(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),d())}function m(){const f=window.getSelection();if(f&&f.toString().trim()!==""){const g=f.toString();navigator.clipboard.writeText(g),o(!0),i.current=!0,setTimeout(()=>{o(!1),i.current=!1},1e3)}else i.current=!1}function h(){o(!1),i.current=!1}return e.jsxs("div",{className:`relative rounded-md border border-red-200 bg-red-50 p-3 dark:border-red-800 dark:bg-red-950/20 ${a}`,children:[e.jsx("div",{className:"float-right mb-2 ml-2",children:e.jsx(s.CopyButton,{text:t,className:`h-6 w-6 p-0 text-red-600 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300 ${r}`})}),e.jsx("div",{ref:c,className:`cursor-pointer select-text break-all font-mono text-xs text-red-700 dark:text-red-300 ${n}`,onClick:d,onKeyDown:u,onMouseUp:m,onMouseDown:h,tabIndex:0,role:"button","aria-label":"Click to copy error message or select text to copy",children:t}),l&&e.jsx("div",{className:"absolute bottom-1 right-1 rounded bg-green-100 px-2 py-1 text-xs text-green-600 dark:bg-green-900/30 dark:text-green-400",children:"Copied!"}),e.jsx("div",{className:"clear-both"})]})}function sr(){const t=s.useEditorStore(o=>{var c,i;return(i=(c=o.card.preferences)==null?void 0:c.chartOptions)==null?void 0:i.indexAxis}),a=s.useEditorStore(o=>o.card.type),{setChartOrientation:n}=s.useEditorStore(o=>o.actions);function r(){return e.jsx(s.IconButton,{onClick:()=>{n(t==="x"||t===void 0?"y":"x")},tooltip:"Chart Orientation",children:t==="x"||t===void 0?e.jsx(zs,{className:"size-4"}):e.jsx(Ps,{className:"size-4"})})}function l(){return e.jsx(s.IconButton,{onClick:()=>{n(t==="y"||t===void 0?"x":"y")},tooltip:"Chart Orientation",children:t==="y"||t===void 0?e.jsx(zs,{className:"size-4"}):e.jsx(Ps,{className:"size-4"})})}return e.jsx(e.Fragment,{children:a==="funnel"?l():r()})}function Mt(){const t=s.useEditorStore(c=>c.card),a=s.useEditorStore(c=>c.isShowingVisual),n=s.useEditorStore(c=>{var i,d;return(d=(i=c.card)==null?void 0:i.preferences)==null?void 0:d.chartOptions}),r=s.getChartGridStyle(n),{setChartGrid:l}=s.useEditorActions();function o(){const c=["xy","none","x","y"],d=(c.indexOf(r)+1)%c.length;l(c[d])}return a?e.jsxs("div",{"data-info":"visual-settings",className:"flex items-center",children:[["line","bar","range","stackedBar","stackedLine","horizontalBar","funnel"].includes(t.type)&&e.jsx(e.Fragment,{children:e.jsx(sr,{})}),!["kpi","text","custom","table"].includes(t.type)&&e.jsx(e.Fragment,{}),!["pie","doughnut","funnel","radar","polarArea","table","custom","kpi","text","map"].includes(t.type)&&e.jsxs(s.IconButton,{tooltip:"Grid Style",onClick:o,children:[(r==="xy"||!r)&&e.jsx(ns,{className:"size-4"}),r==="x"&&e.jsx(ma,{className:"size-4"}),r==="y"&&e.jsx(za,{className:"size-4"}),r==="none"&&e.jsx(Ya,{className:"size-4"})]})]}):null}function tr(){const t=s.useEditorStore(b=>b.frame),a=s.useEditorStore(b=>b.card),{setFrame:n,setActiveTabCardId:r,setCard:l,updateCardInFrame:o}=s.useEditorActions(),c=(b,p)=>{b.dataTransfer.setData("tabIndex",p.toString())},i=b=>{b.preventDefault()},d=(b,p)=>{const j=b.dataTransfer.getData("tabIndex");if(j===p.toString())return;const x=Array.from(t.cards),[v]=x.splice(parseInt(j),1);x.splice(p,0,v),n({...t,cards:x})};function u(b){const p=t.cards.filter(v=>v.id!==b),j=p[0],x={...t,cards:p,activeCardId:j.id};n(x),r(j.id),l(j)}function m(b,p){const j={...t,cards:[...t.cards,p],activeCardId:b.id};n(j),r(p.id)}function h(){const b={...a,id:s.v4(),title:`${a.title} Copy`,tabTitle:`${a.tabTitle||a.title} Copy`};m(a,b)}function f(b){const p={dataSource:b.dataSource,connectionId:b.connectionId,lastSelectedDatabase:b.lastSelectedDatabase,lastSelectedSchema:b.lastSelectedSchema,lastSelectedTable:b.lastSelectedTable,lastSelectedDatamodelId:b.lastSelectedDatamodelId,id:s.v4(),title:"Title",description:"",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[],mode:"explorer"};m(b,p)}function g(b,p){return b.cards.length===1&&(p.displayTab===!0||p.displayTab===void 0)||b.activeCardId!==p.id&&(p.displayTab===!0||p.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const j=p.displayTab===void 0?!1:!p.displayTab;l({...p,displayTab:j}),o({...p,displayTab:j})},children:p.displayTab===!0||p.displayTab===void 0?e.jsx(s.Eye,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"}):e.jsx(fa,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"})})}return e.jsx(s.TabsList,{className:"group mx-4 justify-between overflow-x-auto",children:e.jsxs("div",{className:"flex items-center",children:[t.cards.map((b,p)=>e.jsxs(s.TabsTrigger,{draggable:!0,onDragStart:j=>c(j,p),onDragOver:i,onDrop:j=>d(j,p),className:"",value:b.id,children:[g(t,b),e.jsx(s.Editable,{enabled:t.activeCardId===b.id,text:b.tabTitle||b.title,onSave:j=>{l({...a,tabTitle:j}),o({...a,tabTitle:j})},children:b.tabTitle||b.title},b.id),t.activeCardId===b.id&&t.cards.length>1&&e.jsx(s.X,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:()=>u(b.id)})]},b.id)),e.jsx(s.Button,{className:"ml-1 h-8 px-2 hover:bg-muted-foreground/50",variant:"outline",onClick:()=>f(a),children:e.jsx(s.Plus,{className:"h-4 w-4"})}),e.jsx(s.Button,{className:"invisible ml-1 h-8 px-2 hover:bg-muted-foreground/50 group-hover:visible",variant:"outline",onClick:h,children:e.jsx(xa,{className:"h-4 w-4"})})]})})}function Lt(){const t=s.useEditorStore(p=>p.frame),a=s.useEditorStore(p=>p.card),n=s.useEditorStore(p=>p.isSqlRunning),r=s.useEditorStore(p=>p.isDevMode),{setFrame:l,setActiveTabCardId:o,setCard:c,setIsDevMode:i,setRunSql:d}=s.useEditorActions(),{data:u,isLoading:m,isFetching:h}=s.useDashboardCardQuery(a);function f(p){const j=t.cards.find(x=>x.id===p);if(j!=null&&j.sql){r||i(!0),o(p);return}if(j!=null&&j.queryConfig){r&&i(!1),g(p),o(p);return}r||g(p),o(p)}function g(p){const j={...t,cards:t.cards.map(v=>v.id===a.id?a:v),activeCardId:p};l(j);const x=j.cards.find(v=>v.id===p);x.sql&&d(!0),c(x)}function b(){return a.type==="kpi"?m||h?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border border-border",children:e.jsx(s.KPICard,{card:a,data:u==null?void 0:u.records,isPending:m||h})})}):a.type==="text"?m||h?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border",children:e.jsx(s.ScrollArea,{className:"mx-3 my-6 h-[300px] overflow-y-auto break-words px-3",children:e.jsx(s.TextCard,{isLoading:n,card:a,data:u==null?void 0:u.records})})})}):e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(kt,{className:"grow border-none shadow-none"})})}return e.jsxs(s.Tabs,{onValueChange:f,value:t.activeCardId,className:"flex grow flex-col",children:[t.cards.map(p=>e.jsx(s.TabsContent,{className:"mt-0 grow",value:p.id,children:b()},p.id)),e.jsx(tr,{})]})}function Je({children:t}){var L,C;s.useEditorStore(S=>S.frame);const a=s.useEditorStore(S=>S.card),n=s.useEditorStore(S=>S.isDevMode),r=s.useEditorStore(S=>S.isShowingVisual),l=s.useDashboardStore(S=>S.isVisualEditing),o=s.useEditorStore(S=>S.pythonStdOut);s.useEditorStore(S=>S.actions.setRunSql);const{setFrame:c,setCard:i,setActiveTabCardId:d,runAssistant:u,setIsDevMode:m,setCardPreferences:h}=s.useEditorActions(),{data:f,isLoading:g,isFetching:b,errorMessage:p,refetch:j}=s.useDashboardCardQuery(a);function x(){const S=JSON.stringify(f==null?void 0:f.records,null,2),y=new Blob([S],{type:"application/json"}),D=URL.createObjectURL(y),N=document.createElement("a");N.href=D,N.download=`${a.title}.json`,N.click()}function v(){const y=[Object.keys(f==null?void 0:f.records.reduce((w,F)=>({...w,...F}),{})).join(","),...((f==null?void 0:f.records)||[]).map(w=>Object.values(w).join(","))].join(`
|
|
348
|
+
`),D=new Blob([y],{type:"text/csv"}),N=URL.createObjectURL(D),B=document.createElement("a");B.href=N,B.download=`${a.title}.csv`,B.click()}function k(){const S=`Can you get the documentation for ${a.type} chart?`;u(S)}return a?e.jsxs("div",{className:"relative isolate flex h-full flex-col py-2 pb-3",children:[e.jsxs("div",{className:"z-10 mb-0 flex min-h-10 items-center justify-end gap-2 px-6",children:[r&&e.jsxs("div",{className:"flex grow items-center",children:[e.jsx(At,{}),l&&e.jsx(s.IconButton,{tooltip:"Visual Docs",onClick:k,children:e.jsx(ia,{className:"size-4"})}),!["table","custom"].includes(a.type)&&l&&e.jsx(Jn,{})]}),!r&&e.jsxs("div",{className:"flex grow items-center gap-1",children:[e.jsx(s.Button,{className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70",variant:"ghost",size:"icon",onClick:v,children:e.jsx(s.PiFileCsv,{className:"size-4"})}),e.jsx(s.Button,{className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70",variant:"ghost",size:"icon",onClick:x,children:e.jsx(ja,{strokeWidth:1.5,className:"size-4"})}),e.jsx(s.CopyButton,{text:JSON.stringify(f==null?void 0:f.records,null,2),className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[t,e.jsx(Mt,{})]}),a.type==="table"&&a.sql&&!s.hasValidCardConfig(a.config)&&e.jsxs("div",{className:"mr-2 flex items-center gap-3",children:[e.jsx(s.Checkbox,{id:"pagination",checked:((C=(L=a.preferences)==null?void 0:L.tablePrefs)==null?void 0:C.enableDevModePagination)??!1,onCheckedChange:S=>{var y;h({...a.preferences,tablePrefs:{...(y=a.preferences)==null?void 0:y.tablePrefs,enableDevModePagination:S}}),j()}}),e.jsx(s.Label,{htmlFor:"pagination",children:"Paginate Results"})]}),n&&e.jsx(nr,{})]}),r?e.jsx(Lt,{}):e.jsxs(s.ResizablePanelGroup,{className:"px-6",direction:"horizontal",children:[o&&e.jsxs(e.Fragment,{children:[e.jsx(s.ResizablePanel,{id:"1",order:1,defaultSize:30,minSize:10,className:"relative flex h-full min-h-0 w-full flex-1 basis-0",children:o&&e.jsx(ar,{})}),e.jsx(s.ResizableHandle,{})]}),e.jsxs(s.ResizablePanel,{id:"2",order:2,minSize:10,className:s.cn("relative flex h-full min-h-0 w-full flex-1 basis-0",{"px-6":o}),children:[(f==null?void 0:f.records)&&(f==null?void 0:f.records.length)>0&&e.jsx(s.TableVisual,{card:a,data:(f==null?void 0:f.records)||[]}),p&&e.jsx(er,{error:p})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function ar(){const t=s.useEditorStore(n=>n.pythonStdOut);if(!t)return null;const a=t.replace(/\n/g,"<br>");return e.jsxs("div",{className:"relative flex w-full flex-col",children:[e.jsx("div",{className:"sticky top-0 flex max-h-11 min-h-11 grow items-center font-mono text-xs font-semibold text-foreground/70",children:"Python Output"}),e.jsxs(s.ScrollArea,{className:"overflow-y-auto pt-1 font-mono text-xs text-foreground/90",children:[e.jsx("div",{dangerouslySetInnerHTML:{__html:a}}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function nr(){const t=s.useEditorStore(n=>n.isShowingVisual),a=s.useEditorStore(n=>n.actions.setIsShowingVisual);return e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Label,{htmlFor:"visualize",children:"Chart"}),e.jsx(s.SmallSwitch,{checked:t,onCheckedChange:()=>a(!t),id:"visualize",className:"data-[state=checked]:bg-foreground/50"})]})}function rr(){var p,j;const t=s.useEditorStore(x=>x.card.customCardPreferences),{data:a}=Tt(),n=(a==null?void 0:a.plugins)||[],r=s.useEditorStore(x=>x.card),l=s.useEditorStore(x=>x.frame),o=(t==null?void 0:t.visualType)||"single",{setCustomCardPreferences:c}=s.useEditorActions(),{components:i,manifest:d}=s.useCustomVisual((t==null?void 0:t.url)||""),u=(p=d==null?void 0:d.visuals)==null?void 0:p.find(x=>x.name===(t==null?void 0:t.componentName));function m(x,v){if(!t)return;const L={...(t==null?void 0:t.dataInputCardIds)||{},[x]:{cardId:v,hookRef:null}};c({...t,dataInputCardIds:L})}function h(x){var k,L;const v=(k=l==null?void 0:l.cards)==null?void 0:k.filter(C=>{var S;return((S=C==null?void 0:C.customCardPreferences)==null?void 0:S.visualType)!=="multiple"}).map(C=>({value:C.id,label:C.tabTitle||C.title}));return e.jsx("div",{className:"space-y-2",children:(L=x==null?void 0:x.dataInputs)==null?void 0:L.map((C,S)=>{var y,D;return e.jsxs("div",{className:"grid grid-cols-10 gap-2",children:[e.jsx("div",{className:"col-span-4 flex items-center",children:C}),e.jsx(fe,{className:"col-span-6 h-8 w-full justify-between",label:"",options:v||[],value:((D=(y=t==null?void 0:t.dataInputCardIds)==null?void 0:y[S])==null?void 0:D.cardId)||"",onValueChange:N=>m(S,N)})]},S+Math.random())})})}function f(x,v,k=[],L=""){var C,S;return t?x==="input"?e.jsx(s.Input,{className:`h-8 w-full ${s.removeRing}`,value:((C=t==null?void 0:t.settings)==null?void 0:C[v])||L,onChange:y=>{c({...t,settings:{...t==null?void 0:t.settings,[v]:y.target.value}})}},v):x==="select"?e.jsx(fe,{className:"h-8 w-full",label:"",options:k,value:((S=t==null?void 0:t.settings)==null?void 0:S[v])||L,onValueChange:y=>{c({...t,settings:{...t==null?void 0:t.settings,[v]:y}})}}):null:null}function g(x){const v=Object.entries((x==null?void 0:x.settings)||{});return e.jsx("div",{className:"space-y-3",children:v.map(([k,L])=>e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:L.title}),f(L.ui,k,L.options,L.defaultValue)]},k))})}function b(x){t&&c({...t,visualType:x,componentName:""})}return e.jsxs(s.Accordion,{type:"multiple",defaultValue:["component-settings"],className:"px-6 py-2",children:[e.jsxs(s.AccordionItem,{value:"plugin-settings",children:[e.jsx(s.AccordionTrigger,{children:"Plugin"}),e.jsx(s.AccordionContent,{children:e.jsxs("div",{className:"space-y-4 text-sm",children:[e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(fe,{icon:e.jsx(oa,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:n,value:(t==null?void 0:t.url)||"",onValueChange:x=>c({...t||{url:"",componentName:""},url:x})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&e.jsx(s.Tabs,{value:o,onValueChange:b,children:e.jsxs(s.TabsList,{className:"h-9 w-full",children:[e.jsx(s.TabsTrigger,{className:"h-7 w-full",value:"single",children:"Single Visual"}),e.jsx(s.TabsTrigger,{className:"h-7 w-full",value:"multiple",children:"Multi-Visual"})]})})]})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&t&&e.jsx(e.Fragment,{children:i&&e.jsx(fe,{icon:e.jsx(ha,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(i==null?void 0:i.filter(x=>x.type===o).map(x=>({value:x.name,label:x.name})))||[],value:t.componentName,onValueChange:x=>{console.log("changing value",x),c({...t,componentName:x})}})})]})})]}),((j=r==null?void 0:r.customCardPreferences)==null?void 0:j.componentName)&&e.jsxs(s.AccordionItem,{className:"border-none",value:"component-settings",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsxs(s.AccordionContent,{children:[u&&u.dataInputs&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Input Mapping"}),e.jsx("div",{className:"px-2",children:h(u)})]}),u&&u.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:g(u)})})]})]})]})}function Le(){const[t,a]=I.useState([]),n=s.useEditorStore(u=>u.card.preferences),{setFilterOnClickColumnIndex:r,setCardPreferences:l}=s.useEditorStore(u=>u.actions),o=s.useEditorStore(u=>u.queryResultColumns);s.useEditorStore(u=>{var m;return(m=u.card.preferences)==null?void 0:m.filterOnClickColumnIndex}),I.useEffect(()=>{o&&a(new Array(o.length).fill(!1))},[o]);function c(u,m){var h,f;m?n!=null&&n.onClickFilter&&((h=n==null?void 0:n.onClickFilter)==null?void 0:h.length)>0?l({...n,onClickFilter:[...n.onClickFilter,{columnIndex:u,expression:""}]}):l({...n,onClickFilter:[{columnIndex:u,expression:""}]}):(l({...n,onClickFilter:(f=n==null?void 0:n.onClickFilter)==null?void 0:f.filter(g=>g.columnIndex!==u)}),a(g=>{const b=[...g];return b[u]=!1,b}))}function i(u,m){var f;const h=(f=n==null?void 0:n.onClickFilter)==null?void 0:f.map(g=>g.columnIndex===u?{...g,expression:m.target.value}:g);l({...n,onClickFilter:h})}function d(u){var m,h,f,g;if(t!=null&&t[u]||(h=(m=n==null?void 0:n.onClickFilter)==null?void 0:m.find(b=>b.columnIndex===u))!=null&&h.expression)return e.jsx(s.Input,{value:(g=(f=n==null?void 0:n.onClickFilter)==null?void 0:f.find(b=>b.columnIndex===u))==null?void 0:g.expression,onChange:b=>i(u,b),type:"text",className:"h-9 w-full font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"Expression"})}return e.jsx("div",{className:"max-h-[150px] space-y-2 overflow-y-auto",children:o==null?void 0:o.map((u,m)=>{var h,f;return e.jsx("div",{className:"group flex items-center justify-between space-y-2",children:e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex items-center space-x-2 py-2",children:[e.jsx(s.Checkbox,{checked:!!((h=n==null?void 0:n.onClickFilter)!=null&&h.find(g=>g.columnIndex===m)),onCheckedChange:g=>c(m,g)}),e.jsx("label",{className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:u}),e.jsx("div",{className:"flex items-center gap-2",children:((f=n==null?void 0:n.onClickFilter)==null?void 0:f.find(g=>g.columnIndex===m))&&e.jsx(s.Pencil,{onClick:()=>{a(g=>{const b=[...g];return b[m]=!g[m],b})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),d(m)]})},u)})})}function lr({idx:t}){var i;const a=s.useEditorStore(d=>{var u;return(u=d.card)==null?void 0:u.preferences}),n=s.useEditorStore(d=>{var u;return(u=d.card.preferences)==null?void 0:u.datasetOptions}),r=s.useEditorStore(d=>d.actions.setCardPreferences),l=(i=a==null?void 0:a.chartOptions)==null?void 0:i.indexAxis,o=n==null?void 0:n.find(d=>d.idx===t);function c(d,u){(d==="end"||d==="start")&&s.getContrastColor(s.getCanvasBackgroundColor());const m={display:d!=="none",align:d,anchor:d,clamp:!0};if(!o)r({...a,datasetOptions:[...n||[],{idx:u,datalabels:m}]});else{const h={...o};h.datalabels=m;const f=n==null?void 0:n.map(g=>g.idx===u?h:g);r({...a,datasetOptions:f})}}return e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{children:e.jsx(at,{className:"size-4 rotate-[135deg] cursor-pointer text-muted-foreground hover:text-foreground"})}),e.jsx(s.PopoverContent,{className:"w-fit px-2 py-1",children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{onClick:()=>c("none",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(s.X,{className:"size-3.5"})}),e.jsx("button",{onClick:()=>c("start",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Sa,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})}),e.jsx("button",{onClick:()=>c("center",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Da,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})}),e.jsx("button",{onClick:()=>c("end",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(wa,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})})]})})]})}function or(){const t=s.useEditorStore(o=>o.card),{data:a}=s.useDashboardCardQuery(t),{keys:n}=s.getKeys((a==null?void 0:a.records)||[]),r=n.slice(1).filter(o=>!s.METADATA_KEYS.includes(o));let l=r;if(["stackedBar","stackedLine"].includes(t.type)){const o=s.pivotData({dataArray:(a==null?void 0:a.records)||[],groupKey:n[0],pivotKey:n[1],valueKey:n[2]}),{keys:c}=s.getKeys(o);l=c.slice(1)}return{transformedMetricKeys:l,dimensionKeys:n.slice(0,1),keys:n,defaultMetricKeys:r}}function os({children:t,className:a,delayDuration:n}){return e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{delayDuration:n,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:s.cn("overflow-hidden text-ellipsis whitespace-nowrap",a),children:t})}),e.jsx(s.TooltipContent,{children:t})]})})}function Rt(){const t=s.useEditorStore(d=>d.card),a=s.useEditorStore(d=>{var u,m,h;return(h=(m=(u=d==null?void 0:d.card)==null?void 0:u.preferences)==null?void 0:m.chartOptions)==null?void 0:h.indexAxis}),{data:n}=s.useDashboardCardQuery(t),r=a==="y"?"Metric":"Dimension",l=a==="y"?"Dimension":"Metric",{dimensionKeys:o,transformedMetricKeys:c,keys:i}=or();return i.length===0?null:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:r}),e.jsx("div",{className:"max-h-[125px] space-y-1 overflow-y-auto",children:o.map(d=>e.jsx("p",{className:"flex h-8 items-center rounded-md bg-muted/70 px-3 hover:bg-muted",title:d,children:Ot(d)},d))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:l}),e.jsx("div",{className:"my-1 max-h-[125px] space-y-1 overflow-y-auto",children:c.map((d,u)=>e.jsx(Bt,{className:"flex h-8 items-center bg-muted/70 px-3 hover:bg-muted",iconClassName:"invisible group-hover:visible",col:d,idx:u},d))})]})]})}function Ot(t,a=30){return t.length>a?t.slice(0,a)+"...":t}function Bt({col:t,idx:a,className:n,iconClassName:r,children:l}){const o=s.useEditorStore(m=>{var h;return(h=m.card)==null?void 0:h.preferences}),c=s.useEditorStore(m=>{var h,f;return(f=(h=m.card)==null?void 0:h.preferences)==null?void 0:f.datasetOptions}),i=c==null?void 0:c.find(m=>m.idx===a),{setCardPreferences:d}=s.useEditorStore(m=>m.actions);function u(m){if(!i)d({...o,datasetOptions:[...c||[],{idx:a,type:m==="area"?"line":m,fill:m==="area"?"origin":""}]});else{const h={...i};h.type=m==="area"?"line":m,h.fill=m==="area"?"origin":"";const f=c==null?void 0:c.map(g=>g.idx===a?h:g);d({...o,datasetOptions:f})}}return e.jsxs("div",{className:s.cn("group flex items-center justify-between gap-2 rounded-md",n),children:[l||e.jsx(os,{className:"max-w-[100px]",title:t,children:Ot(t)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.ChartColumnIncreasing,{onClick:()=>u("bar"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(s.ChartLine,{onClick:()=>u("line"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(s.ChartArea,{onClick:()=>u("area"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(lr,{idx:a})]})]})}function ks(){const t=s.useEditorStore(g=>g.selectedConnectionId),a=s.useEditorStore(g=>g.selectedDatamodelId),n=s.useEditorStore(g=>g.selectedDatabaseName),r=s.useEditorStore(g=>g.selectedSchemaName),l=s.useEditorStore(g=>g.selectedTableName),o=s.useDashboardStore(g=>g.dashboard.filters)||[],c=s.useDashboardStore(g=>g.actions.addFilter),i=s.useDashboardStore(g=>g.actions.removeFilter),{removeFilterValues:d}=s.useDashboardActions(),{modelItems:u,tableName:m,connectionType:h}=s.useEditorAside();function f(g,b="dashboard",p){var D;const j=s.fmt(g.column_name),x=s.fmt(n||""),v=s.fmt(r||""),k=s.fmt(m);let L=s.getQualifiedTableName({schemaName:v,tableName:k,connectionType:h,databaseName:x}),C=`${L}.${j}`;const S=(D=u==null?void 0:u.find(N=>N.id===a))==null?void 0:D.name;a&&a!=="none"&&(C=`${s.DATAMODEL_NAMESPCACE}.${S}.${j}`,L=`${s.DATAMODEL_NAMESPCACE}.${S}`),p!=null&&p.qualifiedFieldName&&(C=p.qualifiedFieldName),p!=null&&p.entityName&&(L=p.entityName);const y=o==null?void 0:o.find(N=>N.column===C&&N.table===k&&(N.database===x||N.database===n));if(y)d(y.id),i(y.id);else{const N=s.v4();return m==="api"&&t?(c({location:b,id:N,column:C,title:g.column_name,dataType:g.data_type,table:"api",database:"",connectionId:t,operation:"in",sql:s.getDefaultFilterSql(g.data_type,L,j)}),N):(c({id:N,location:b,column:C,title:g.column_name,dataType:g.data_type,table:l||"",database:n||"",connectionId:t||"",operation:"in",sql:s.getDefaultFilterSql(g.data_type,L,j)}),N)}}return{assignFilter:f}}function Pe(){const t=s.useDashboardStore(i=>i.dashboard.filters),a=s.useEditorStore(i=>i.frame),{setFrame:n}=s.useEditorActions(),{columns:r}=s.useEditorAside(),{assignFilter:l}=ks();function o(i){const d=l(i,"frame");n({...a,filterId:d})}const c=t==null?void 0:t.find(i=>i.id===a.filterId);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Card Filter"}),e.jsx(ir,{onSelect:o,columns:r}),c&&e.jsx(s.FilterHeader,{filter:c})]})}function ir({columns:t,onSelect:a}){var c;const[n,r]=ke.useState(!1),[l,o]=ke.useState("");return e.jsxs(s.Popover,{open:n,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{size:"sm",variant:"outline",role:"combobox","aria-expanded":n,className:"w-full justify-between font-normal",children:[l?(c=t.find(i=>i.column_name===l))==null?void 0:c.column_name:"Select Column...",e.jsx(s.CaretSortIcon,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[200px] p-0",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search column",className:"h-9"}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No framework found."}),e.jsx(s.CommandGroup,{children:t==null?void 0:t.map(i=>e.jsxs(s.CommandItem,{value:i.column_name,onSelect:d=>{const u=d===l?"":d;o(u),r(!1),u&&a(i)},children:[i.column_name,e.jsx(s.CheckIcon,{className:s.cn("ml-auto h-4 w-4",l===i.column_name?"opacity-100":"opacity-0")})]},i.column_name))})]})]})})]})}function cr({cardType:t}){return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} Chart`}),e.jsxs(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT x-axis, y-axis-1, y-axis-2,... FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"x-axis - category"}),e.jsx("li",{children:"y-axis1 - number"}),e.jsx("li",{children:"y-axis2 - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:a=>a.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bar-line-area",children:"example"})," in the docs."]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsx(s.AccordionContent,{className:"space-y-4 px-2",children:e.jsx(Rt,{})})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Le,{}),e.jsx(Pe,{})]})]})]})})}function dr({cardType:t}){function a(n){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:n==="bubble"?"SELECT label, [group], x-axis, y-axis, radius FROM table":"SELECT label, [group], x-axis, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"group (optional) - category"}),e.jsx("li",{children:"x-axis - number"}),e.jsx("li",{children:"y-axis - number"}),n==="bubble"&&e.jsx("li",{children:"radius - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:o=>o.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bubble",children:"example"})," in the docs."]})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} Chart`}),e.jsx(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:a(t)})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Le,{}),e.jsx(Pe,{})]})]})]})})}function Ft(){const t=s.useEditorStore(i=>i.card.type),a=s.useEditorStore(i=>i.isDevMode),n=s.useEditorStore(i=>i.card.preferences),{setCardPreferences:r}=s.useEditorStore(i=>i.actions);function l(i){var m;const d={datalabels:{display:i!=="none",align:i,anchor:i,clamp:!0}},u={...n,chartOptions:{...n==null?void 0:n.chartOptions,plugins:{...(m=n==null?void 0:n.chartOptions)==null?void 0:m.plugins,...d}}};r(u)}function o(){var i,d,u;return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"font-medium",children:"Data Labels"}),e.jsxs(s.Select,{value:((u=(d=(i=n==null?void 0:n.chartOptions)==null?void 0:i.plugins)==null?void 0:d.datalabels)==null?void 0:u.anchor)||"none",onValueChange:l,defaultValue:"none",children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{placeholder:"Select position"})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Data Labels"}),e.jsx(s.SelectItem,{value:"none",children:"None"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{value:"start",children:"Start"}),e.jsx(s.SelectItem,{value:"center",children:"Center"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{value:"end",children:"End"})]})})]})]})}function c(){var i,d,u;return e.jsx("div",{children:e.jsxs(s.Select,{value:((u=(d=(i=n==null?void 0:n.chartOptions)==null?void 0:i.plugins)==null?void 0:d.datalabels)==null?void 0:u.anchor)||"none",onValueChange:l,defaultValue:"none",children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select position"})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"none",children:"None"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{className:"text-xs",value:"start",children:"Start"}),e.jsx(s.SelectItem,{className:"text-xs",value:"center",children:"Center"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{className:"text-xs",value:"end",children:"End"})]})})]})})}return e.jsx(e.Fragment,{children:a?o():c()})}const ur={datasets:[{type:"line",label:"Sum_sales",data:[]},{type:"bar",label:"Sum_profit",data:[]}]},mr={datasets:[{fill:"origin",type:"line",label:"Sum_sales",data:[]}]};function hr(){const t=s.useEditorStore(a=>a.card.type);return e.jsxs("div",{className:"space-y-6 p-6",children:[e.jsx(s.Accordion,{className:" ",type:"single",collapsible:!0,children:xr(t)}),!["kpi"].includes(t)&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ft,{}),e.jsx(Le,{}),e.jsx(Pe,{})]})]})}function xr(t){if(["line","bar"].includes(t))return e.jsxs(e.Fragment,{children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsx("p",{children:"Chart Query"})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT x-axis, y-axis-1, y-axis-2, y-axis-3,... FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"X-axis - Category (ex. city)"}),e.jsx("li",{children:"Y-axis - Number (ex. population)"})]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:"Mixed Chart"}),e.jsxs(s.AccordionContent,{className:"space-y-2 text-xs",children:[e.jsxs("p",{children:["Click ",e.jsx("b",{children:"Customize"})," and change the `type` property in the dataset."]}),e.jsx("pre",{children:JSON.stringify(ur,null,2)})]})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:"Area Chart"}),e.jsxs(s.AccordionContent,{className:"space-y-2 text-xs",children:[e.jsxs("p",{children:["Click ",e.jsx("b",{children:"Customize"})," and add `fill` property to the dataset. See",e.jsx("a",{className:"mx-1 text-blue-500 hover:underline",href:"https://www.chartjs.org/docs/latest/samples/area/line-boundaries.html",target:"_blank",children:"docs"}),"for more options."]}),e.jsx("pre",{children:JSON.stringify(mr,null,2)})]})]})]});if(t==="bubble")return e.jsx(e.Fragment,{children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:["How to create a ",e.jsx("span",{children:t})," chart query?"]})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, x-axis, y-axis, radius FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Bubble Group (opt) - Category (ex. state)"}),e.jsx("li",{children:"X-axis - Number (ex. avg. age)"}),e.jsx("li",{children:"Y-axis - Number (ex. avg. weight)"}),e.jsx("li",{children:"Radius - Number (ex. population)"})]})]})]})});if(t==="scatter")return e.jsx(e.Fragment,{children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:["How to create a ",e.jsx("span",{children:t})," chart query?"]})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, x-axis, y-axis FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Group (opt) - Category (ex. state)"}),e.jsx("li",{children:"X-axis - Number (ex. avg. age)"}),e.jsx("li",{children:"Y-axis - Number (ex. avg. weight)"})]})]})]})});if(["pie","doughnut","polarArea","funnel"].includes(t))return e.jsx(e.Fragment,{children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:[e.jsx("span",{children:t==="polarArea"?"Polar":t.charAt(0).toUpperCase()+t.slice(1)})," ","chart query"]})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, measure FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Measure - Number (ex. population)"})]})]})]})})}function pr({colorRanges:t,setColorRanges:a}){const n={start:-1/0,end:100,color:""};function r(c,i,d){const u=[...t];u[c]={...u[c],[i]:d},a(u)}function l(c){const i=[...t];i.splice(c,1),a(i)}function o(){a([...t,n])}return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{children:"Color Range"}),e.jsx(s.Button,{onClick:o,variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.Plus,{className:"size-3"})})]}),t.map((c,i)=>e.jsxs("div",{className:"flex items-center gap-2 px-2",children:[e.jsx(s.Input,{onChange:d=>r(i,"start",d.target.value),value:c.start,className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx("span",{children:"-"}),e.jsx(s.Input,{value:c.end,onChange:d=>r(i,"end",d.target.value),className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx(s.Input,{onChange:d=>r(i,"color",d.target.value),value:c.color,className:s.cn(`h-7 min-w-14 p-0 ${s.removeRing}`),type:"color",list:"presetColors"}),e.jsxs("datalist",{id:"presetColors",children:[e.jsx("option",{children:s.colors$1.green[600]}),e.jsx("option",{children:s.colors$1.red[500]}),e.jsx("option",{children:s.colors$1.yellow[400]}),e.jsx("option",{children:s.colors$1.orange[500]})]}),e.jsx(s.Button,{onClick:()=>l(i),variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.X,{className:"size-3"})})]},i))]})}function fr(){var m,h,f,g,b;const t=s.useEditorStore(p=>p.card.preferences),a=s.useEditorStore(p=>p.actions.setCardPreferences),n=s.useEditorStore(p=>p.card),r=s.isExplorerCard(n),l=s.useEditorStore(p=>p.actions.setNumberFormat);s.useEditorStore(p=>{var j,x;return(x=(j=p.card.preferences)==null?void 0:j.formatNumber)==null?void 0:x.decimalPlaces});const o=s.useEditorStore(p=>{var j,x;return(x=(j=p.card.preferences)==null?void 0:j.formatNumber)==null?void 0:x.locale}),c=s.useEditorStore(p=>{var j,x;return(x=(j=p.card.preferences)==null?void 0:j.formatNumber)==null?void 0:x.currency});s.useEditorStore(p=>p.actions.setFilterOnClickField);const i=s.useEditorStore(p=>{var j,x;return(x=(j=p.card.preferences)==null?void 0:j.formatNumber)==null?void 0:x.colorRanges})||[],d=s.useEditorStore(p=>p.actions.setColorRanges),u=[...new Set(s.LOCALE_CURRENCY_PAIRS.map(p=>p.currency))];return e.jsxs("div",{children:[!r&&e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx(s.Checkbox,{checked:!!((m=t==null?void 0:t.formatNumber)!=null&&m.enabled),onCheckedChange:p=>{a({...t,formatNumber:{...t==null?void 0:t.formatNumber,enabled:p}})}}),e.jsx(s.Label,{children:"Format Number"})]}),(((h=t==null?void 0:t.formatNumber)==null?void 0:h.enabled)===!0||r)&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("div",{children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Locale"}),e.jsxs(s.Select,{value:o||"none",onValueChange:p=>{var j,x,v;return l(((j=t==null?void 0:t.formatNumber)==null?void 0:j.decimalPlaces)||0,((x=t==null?void 0:t.formatNumber)==null?void 0:x.currency)||"",p,((v=t==null?void 0:t.formatNumber)==null?void 0:v.suffix)||"")},children:[e.jsx(s.SelectTrigger,{className:"col-span-6 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Format"}),e.jsx(s.SelectItem,{value:"none",children:"Auto"},"none"),s.LOCALE_CURRENCY_PAIRS.map(p=>e.jsx(s.SelectItem,{value:p.locale,children:p.locale},p.locale))]})})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Currency"}),e.jsxs(s.Select,{value:c||"none",onValueChange:p=>{var j,x,v;console.log("currency",p),l(((j=t==null?void 0:t.formatNumber)==null?void 0:j.decimalPlaces)||0,p==="none"?"":p,((x=t==null?void 0:t.formatNumber)==null?void 0:x.locale)||"",((v=t==null?void 0:t.formatNumber)==null?void 0:v.suffix)||"")},children:[e.jsx(s.SelectTrigger,{className:"col-span-6 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Currency"}),e.jsx(s.SelectItem,{value:"none",children:"None"},"none"),u.map(p=>e.jsx(s.SelectItem,{value:p,children:p},p))]})})]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Decimals"}),e.jsxs(s.Select,{value:((g=(f=t==null?void 0:t.formatNumber)==null?void 0:f.decimalPlaces)==null?void 0:g.toString())||"0",onValueChange:p=>{var j,x,v;return l(Number(p),((j=t==null?void 0:t.formatNumber)==null?void 0:j.currency)||"",((x=t==null?void 0:t.formatNumber)==null?void 0:x.locale)||"",((v=t==null?void 0:t.formatNumber)==null?void 0:v.suffix)||"")},children:[e.jsx(s.SelectTrigger,{className:"col-span-3 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:["0","1","2","3","4"].map(p=>e.jsx(s.SelectItem,{value:p,children:p},p))})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Suffix"}),e.jsx(s.Input,{value:((b=t==null?void 0:t.formatNumber)==null?void 0:b.suffix)||"",className:"h-8 font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"K, M, B, %",onChange:p=>{var j,x,v;return l(((j=t==null?void 0:t.formatNumber)==null?void 0:j.decimalPlaces)||0,((x=t==null?void 0:t.formatNumber)==null?void 0:x.currency)||"",((v=t==null?void 0:t.formatNumber)==null?void 0:v.locale)||"",p.target.value)}})]})]})]})}),e.jsx(s.Separator,{className:"my-3"}),e.jsx(pr,{colorRanges:i,setColorRanges:d})]})]})}function gr(){return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsx(s.Accordion,{type:"single",collapsible:!0,children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"",children:"KPI Query"}),e.jsxs(s.AccordionContent,{className:"font-mono",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs",children:"SELECT current, previous FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"current - number"}),e.jsx("li",{children:"previous - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/kpi",children:"example"})," in the docs."]})]})]})}),e.jsx("section",{className:"",children:e.jsx(fr,{})}),e.jsx("div",{}),e.jsx("div",{})]})}function xs({children:t,summary:a,open:n,className:r}){return e.jsxs("details",{open:n,className:s.cn("space-y-4 [&_summary>svg]:open:-rotate-180",r),children:[e.jsxs("summary",{className:"flex cursor-pointer list-none items-center justify-between gap-4",children:[e.jsx(s.Label,{children:a}),e.jsx(s.ChevronUp,{className:"h-4 w-4"})]}),e.jsx("div",{className:"transition-all ease-in-out",children:t})]})}const jr=[{label:"Mercator",value:"mercator"},{label:"Azimuthal Equidistant",value:"azimuthalEquidistant"},{label:"Gnomonic",value:"gnomonic"},{label:"Orthographic",value:"orthographic"},{label:"Stereographic",value:"stereographic"},{label:"Equal Earth",value:"equalEarth"},{label:"Albers",value:"albers"},{label:"Albers USA",value:"albersUsa"},{label:"Conic Conformal",value:"conicConformal"},{label:"Conic Equal Area",value:"conicEqualArea"},{label:"Conic Equidistant",value:"conicEquidistant"},{label:"Equirectangular",value:"equirectangular"},{label:"Transverse Mercator",value:"transverseMercator"},{label:"Natural Earth 1",value:"naturalEarth1"}],br=["blues","brBG","buGn","buPu","cividis","cool","cubehelixDefault","gnBu","greens","greys","inferno","magma","orRd","oranges","pRGn","piYG","plasma","puBu","puBuGn","puOr","puRd","purples","rainbow","rdBu","rdGy","rdPu","rdYlBu","rdYlGn","reds","sinebow","spectral","turbo","viridis","warm","ylGn","ylGnBu","ylOrBr","ylOrRd"],yr=br.map(t=>({label:t,value:t}));function vr(){var d,u,m,h,f,g,b,p,j,x,v,k,L,C,S,y,D,N;const t=s.useEditorStore(B=>B.card),a=(u=(d=t==null?void 0:t.preferences)==null?void 0:d.mapVisualOptions)==null?void 0:u.topoJsonUrl,[n,r]=I.useState(((h=(m=t==null?void 0:t.preferences)==null?void 0:m.mapVisualOptions)==null?void 0:h.customTopoJsonUrl)||""),{setCardPreferences:l}=s.useEditorActions(),{data:o}=s.useTopoJson(t),c=Object.keys((o==null?void 0:o.objects)||{}).map(B=>({label:B,value:B}))||[],i=[{label:"US States 10m",value:"https://unpkg.com/us-atlas/states-10m.json"},{label:"Countries 50m",value:"https://unpkg.com/world-atlas/countries-50m.json"},{label:"Custom",value:"custom"}];return e.jsxs("div",{className:"p-6",children:[e.jsx(xs,{summary:"Map Chart",children:e.jsx("p",{className:"rounded-md bg-muted p-2 font-mono text-xs",children:"SELECT country, value FROM table"})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(xs,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(fe,{className:"h-9",options:i,onValueChange:B=>{console.log("value",B),l({...t.preferences,mapVisualOptions:{topoJsonUrl:B}})},value:a||"",label:"Select Map"}),a==="custom"&&e.jsx(s.Input,{onChange:B=>{r(B.target.value)},onBlur:()=>{var B;console.log("onBlur",n),l({...t.preferences,mapVisualOptions:{...(B=t.preferences)==null?void 0:B.mapVisualOptions,customTopoJsonUrl:n}})},value:n,className:`h-9 w-full ${s.removeRing}`,placeholder:"Custom URL"}),o&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Map Object"}),e.jsx(fe,{className:"h-9",options:c,value:((g=(f=t.preferences)==null?void 0:f.mapVisualOptions)==null?void 0:g.objectKey)||"",label:"Map Object",onValueChange:B=>{var w;l({...t.preferences,mapVisualOptions:{...(w=t.preferences)==null?void 0:w.mapVisualOptions,objectKey:B}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Projection"}),e.jsx(fe,{className:"h-9",options:jr,value:((p=(b=t.preferences)==null?void 0:b.mapVisualOptions)==null?void 0:p.projection)||"",label:"Projection",onValueChange:B=>{var w;l({...t.preferences,mapVisualOptions:{...(w=t.preferences)==null?void 0:w.mapVisualOptions,projection:B}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Colors"}),e.jsx(fe,{className:"h-9",options:yr,value:((x=(j=t.preferences)==null?void 0:j.mapVisualOptions)==null?void 0:x.colorScale)||"",label:"Select Color Scale",onValueChange:B=>{var w;l({...t.preferences,mapVisualOptions:{...(w=t.preferences)==null?void 0:w.mapVisualOptions,colorScale:B}})}})]})]})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(xs,{className:"",summary:"Scale Options",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:.1,value:((k=(v=t.preferences)==null?void 0:v.mapVisualOptions)==null?void 0:k.projectionScale)||1,onChange:B=>{var w;l({...t.preferences,mapVisualOptions:{...(w=t.preferences)==null?void 0:w.mapVisualOptions,projectionScale:Number(B.target.value)}})}}),e.jsx(s.Label,{children:"X"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((S=(C=(L=t.preferences)==null?void 0:L.mapVisualOptions)==null?void 0:C.projectionOffset)==null?void 0:S[0])||0,onChange:B=>{var w,F,T,E;l({...t.preferences,mapVisualOptions:{...(w=t.preferences)==null?void 0:w.mapVisualOptions,projectionOffset:[Number(B.target.value),((E=(T=(F=t.preferences)==null?void 0:F.mapVisualOptions)==null?void 0:T.projectionOffset)==null?void 0:E[1])||0]}})}}),e.jsx(s.Label,{children:"Y"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((N=(D=(y=t.preferences)==null?void 0:y.mapVisualOptions)==null?void 0:D.projectionOffset)==null?void 0:N[1])||0,onChange:B=>{var w,F,T,E;l({...t.preferences,mapVisualOptions:{...(w=t.preferences)==null?void 0:w.mapVisualOptions,projectionOffset:[((E=(T=(F=t.preferences)==null?void 0:F.mapVisualOptions)==null?void 0:T.projectionOffset)==null?void 0:E[0])||0,Number(B.target.value)]}})}})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(Le,{})]})}function Nr(){var r;const t=s.useEditorStore(l=>l.card.preferences),{setCardPreferences:a}=s.useEditorStore(l=>l.actions);function n(l){a({...t,textVisualOptions:{...t==null?void 0:t.textVisualOptions,isDynamicText:l==="dynamic"}})}return e.jsxs(s.RadioGroup,{value:(r=t==null?void 0:t.textVisualOptions)!=null&&r.isDynamicText?"dynamic":"static",onValueChange:n,className:"flex gap-3",defaultValue:"x",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"static",id:"r1"}),e.jsx("label",{className:"text-sm",htmlFor:"r1",children:"Static"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"dynamic",id:"r2"}),e.jsx("label",{className:"text-sm",htmlFor:"r2",children:"Dynamic"})]})]})}function Qe({cardType:t,docContent:a,suffix:n="Chart"}){let r="pie-donut-polar";return t==="funnel"&&(r="funnel"),e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} ${n}`}),e.jsx(s.AccordionContent,{children:a||e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT label, measure FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"measure - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:l=>l.stopPropagation(),className:"text-blue-700",href:`https://docs.semaphor.cloud/docs/charts/${r}`,children:"example"})," in the docs."]})]})})]}),t==="text"&&e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsx(s.AccordionContent,{className:"space-y-4 px-2 py-4",children:e.jsx(Nr,{})})]}),!["range","text"].includes(t)&&e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Le,{}),e.jsx(Pe,{})]})]})]})})}function Cr(){const t=s.useEditorStore(r=>{var l,o;return(o=(l=r==null?void 0:r.card)==null?void 0:l.preferences)==null?void 0:o.sortChart}),{setSortChart:a}=s.useEditorActions();function n(){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Sort"}),e.jsx(fe,{className:"h-8",label:"Sort Chart",options:[{label:"None",value:"none"},{label:"ASC",value:"asc"},{label:"DESC",value:"desc"}],value:t||"none",onValueChange:r=>{a(r)}})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:"Stacked Chart"}),e.jsxs(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT x-axis, stack-by, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"x-axis - category"}),e.jsx("li",{children:"stack by - category"}),e.jsx("li",{children:"y-axis - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:r=>r.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/stacked",children:"example"})," in the docs."]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[n(),e.jsx(Rt,{})]})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Le,{}),e.jsx(Pe,{})]})]})]})})}function Sr({cardType:t="table"}){console.log("cardType",t);const a=s.useEditorStore(l=>{var o;return(o=l.card)==null?void 0:o.preferences}),n=s.useEditorStore(l=>l.actions.setCardPreferences),r=l=>{n({...a,allowDownload:l})};return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsx(s.Accordion,{defaultValue:["item-3"],type:"multiple",children:e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Le,{}),e.jsx(Pe,{})]})]})}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{onCheckedChange:r,id:"allow-download"}),e.jsx("label",{htmlFor:"allow-download",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Allow Download"})]})]})}function Pt({color:t,onColorChange:a,onClose:n}){const[r,l]=I.useState(0),[o,c]=I.useState(100),[i,d]=I.useState(50),[u,m]=I.useState(t);I.useEffect(()=>{const j=Ys(t);if(j){const x=qs(j.r,j.g,j.b);l(x.h),c(x.s),d(x.l),m(t)}},[t]);const h=j=>{l(j),g(j,o,i)},f=j=>{const x=j.currentTarget.getBoundingClientRect(),v=Math.max(0,Math.min(1,(j.clientX-x.left)/x.width)),k=Math.max(0,Math.min(1,(j.clientY-x.top)/x.height)),L=v*100,C=(1-k)*100;c(L),d(C),g(r,L,C)},g=(j,x,v)=>{const k=Dr(j,x,v),L=wr(k.r,k.g,k.b);m(L)},b=j=>{if(m(j),/^#[0-9A-Fa-f]{6}$/.test(j)){const x=Ys(j);if(x){const v=qs(x.r,x.g,x.b);l(v.h),c(v.s),d(v.l)}}},p=()=>{/^#[0-9A-Fa-f]{6}$/.test(u)&&(a(u),n())};return e.jsxs("div",{className:"p-4 space-y-4 w-[320px]",children:[e.jsxs("div",{className:"relative h-[200px] rounded cursor-crosshair",style:{background:`hsl(${r}, 100%, 50%)`},onClick:f,onMouseMove:j=>{j.buttons===1&&f(j)},children:[e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to right, white, transparent)"}}),e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to bottom, transparent, black)"}}),e.jsx("div",{className:"absolute w-4 h-4 -ml-2 -mt-2 rounded-full border-2 border-white shadow-md",style:{left:`${o}%`,top:`${100-i}%`,backgroundColor:u}})]}),e.jsx("div",{className:"space-y-2",children:e.jsx("input",{type:"range",min:"0",max:"360",value:r,onChange:j=>h(Number(j.target.value)),className:"w-full h-4 rounded-lg appearance-none cursor-pointer",style:{background:"linear-gradient(to right, #ff0000, #ffff00, #00ff00, #00ffff, #0000ff, #ff00ff, #ff0000)"}})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"HEX"}),e.jsx(s.Input,{value:u,onChange:j=>b(j.target.value),placeholder:"#000000",className:"font-mono"})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full border shadow-sm",style:{backgroundColor:t}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"CURRENT"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full border shadow-sm",style:{backgroundColor:u}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"NEW"})]})]}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(s.Button,{variant:"outline",onClick:n,children:"Cancel"}),e.jsx(s.Button,{onClick:p,children:"OK"})]})]})}function Ys(t){const a=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);return a?{r:parseInt(a[1],16),g:parseInt(a[2],16),b:parseInt(a[3],16)}:null}function wr(t,a,n){return"#"+((1<<24)+(t<<16)+(a<<8)+n).toString(16).slice(1)}function qs(t,a,n){t/=255,a/=255,n/=255;const r=Math.max(t,a,n),l=Math.min(t,a,n);let o=0,c=0;const i=(r+l)/2;if(r!==l){const d=r-l;switch(c=i>.5?d/(2-r-l):d/(r+l),r){case t:o=((a-n)/d+(a<n?6:0))/6;break;case a:o=((n-t)/d+2)/6;break;case n:o=((t-a)/d+4)/6;break}}return{h:Math.round(o*360),s:Math.round(c*100),l:Math.round(i*100)}}function Dr(t,a,n){t/=360,a/=100,n/=100;let r,l,o;if(a===0)r=l=o=n;else{const c=(u,m,h)=>(h<0&&(h+=1),h>1&&(h-=1),h<.16666666666666666?u+(m-u)*6*h:h<.5?m:h<.6666666666666666?u+(m-u)*(.6666666666666666-h)*6:u),i=n<.5?n*(1+a):n+a-n*a,d=2*n-i;r=c(d,i,t+1/3),l=c(d,i,t),o=c(d,i,t-1/3)}return{r:Math.round(r*255),g:Math.round(l*255),b:Math.round(o*255)}}const kr=["#000000","#ffffff","#6b7280","#dc2626","#ea580c","#ca8a04","#16a34a","#0891b2","#2563eb","#7c3aed","#c026d3","#e11d48","#0f172a","#f3f4f6","#fbbf24"];function zt(){var k,L,C,S,y,D,N,B,w,F;const t=s.useEditorStore(T=>T.card),a=s.useEditorStore(T=>{var E;return(E=T.card)==null?void 0:E.preferences}),{setCardPreferences:n,updateCardInFrame:r}=s.useEditorActions(),{data:l}=s.useDashboardCardQuery(t),[o,c]=I.useState({}),[i,d]=I.useState(null),[u,m]=I.useState(null),h=I.useMemo(()=>{var O,M,R,P,K,$,te;if(!(l!=null&&l.records)||l.records.length===0)return[];const T=(t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine",E=(t==null?void 0:t.type)==="bar"||(t==null?void 0:t.type)==="line",A=((O=t==null?void 0:t.config)==null?void 0:O.pivotByColumns)&&t.config.pivotByColumns.length>0;if((T||E)&&A){if(l.pivotSchema&&Array.isArray(l.pivotSchema)){const X=new Set;return l.pivotSchema.forEach(q=>{q.alias&&X.add(q.alias)}),Array.from(X)}if(l.records.length>0){const X=l.records[0],q=Object.keys(X),H=new Set;(M=t==null?void 0:t.config)!=null&&M.groupByColumns&&t.config.groupByColumns.forEach(z=>{H.add(z.label||z.name),H.add(z.alias||z.name)});const _=new Set;return(R=t==null?void 0:t.config)!=null&&R.metricColumns&&t.config.metricColumns.forEach(z=>{const U=z.alias||z.name;_.add(U),_.add(`${U}_count`),_.add(`${U}_sum`),_.add(`${U}_avg`),_.add(`${U}_min`),_.add(`${U}_max`);const Z=z.entityName||z.qualifiedEntityName;Z&&(_.add(`${Z}_${U}`),_.add(`${Z}_${U}_count`))}),q.filter(z=>!H.has(z)&&!_.has(z))}}if((E||T)&&!A&&((K=(P=t==null?void 0:t.config)==null?void 0:P.metricColumns)!=null&&K.length))return t.config.metricColumns.map(X=>X.alias||X.label||X.name);if((te=($=t==null?void 0:t.config)==null?void 0:$.groupByColumns)!=null&&te.length){const X=t.config.groupByColumns[0],q=X.label||X.name,H=new Set;return l.records.forEach(_=>{const J=_[q];J!=null&&H.add(String(J))}),Array.from(H)}return[]},[l,(k=t==null?void 0:t.config)==null?void 0:k.groupByColumns,(L=t==null?void 0:t.config)==null?void 0:L.pivotByColumns,(C=t==null?void 0:t.config)==null?void 0:C.metricColumns,t==null?void 0:t.type]),f=I.useMemo(()=>s.getDefaultChartColors(),[]);I.useEffect(()=>{const T={};h.forEach((E,A)=>{T[E]=s.getColorForValue(E,A,a==null?void 0:a.colorConfig)}),c(T)},[h,a==null?void 0:a.colorConfig,f]);const g=(T,E)=>{const A={...o,[T]:E};c(A);const O={...a||{},colorConfig:{segments:A}};n(O);const M={...t,preferences:O};r(M)},b=(T,E)=>{var K;const A=f[E%f.length],{[T]:O,...M}=((K=a==null?void 0:a.colorConfig)==null?void 0:K.segments)||{},R={...a||{},colorConfig:{segments:M}};n(R);const P={...t,preferences:R};r(P),c($=>({...$,[T]:A}))};if(!h.length||!((t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine"?((y=(S=t==null?void 0:t.config)==null?void 0:S.groupByColumns)==null?void 0:y.length)||((N=(D=t==null?void 0:t.config)==null?void 0:D.pivotByColumns)==null?void 0:N.length):(w=(B=t==null?void 0:t.config)==null?void 0:B.groupByColumns)==null?void 0:w.length)||["table","kpi","text","custom"].includes(t.type))return null;const x=()=>{const T={...a||{},colorConfig:{segments:{}}};n(T);const E={...t,preferences:T};r(E);const A={};h.forEach((O,M)=>{A[O]=s.getColorForValue(O,M,void 0)}),c(A)},v=Object.keys(((F=a==null?void 0:a.colorConfig)==null?void 0:F.segments)||{}).length>0;return e.jsxs(s.AccordionItem,{value:"colors",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ba,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Colors"})]})}),e.jsx(s.AccordionContent,{className:"",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"space-y-2",children:e.jsx("div",{className:"flex items-center justify-between",children:v&&e.jsxs("button",{className:"ml-auto flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",onClick:x,children:[e.jsx(s.RotateCcw,{className:"h-3 w-3"}),"Reset All"]})})}),e.jsx("div",{className:"max-h-[200px] space-y-2 overflow-y-auto pr-1",children:h.map((T,E)=>{const A=s.isDefaultColor(o[T],E),O=!A;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Popover,{open:i===T,onOpenChange:M=>d(M?T:null),children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx("button",{className:"h-5 w-5 shrink-0 rounded border border-input shadow-sm transition-colors hover:border-gray-400 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",style:{backgroundColor:o[T]}})}),e.jsx(s.PopoverContent,{align:"start",className:"w-auto p-3",children:e.jsxs("div",{className:"space-y-2.5",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Theme Colors"}),e.jsx("div",{className:"grid grid-cols-5 gap-1.5",children:f.slice(0,10).map((M,R)=>e.jsxs("button",{className:s.cn("relative h-5 w-5 rounded border-2 transition-all hover:scale-110",o[T]===M?"border-gray-900":"border-transparent"),style:{backgroundColor:M},onClick:()=>{g(T,M),d(null)},children:[R===E%f.length&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("div",{className:"rounded-full bg-white/90 px-0.5 text-[8px] font-bold text-gray-900 shadow-sm",children:"D"})}),e.jsx("span",{className:"sr-only",children:M})]},`default-${R}`))})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Popular Colors"}),e.jsx("div",{className:"grid grid-cols-5 gap-1.5",children:kr.map((M,R)=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border transition-all hover:scale-110",o[T]===M?"border-2 border-gray-900":M==="#ffffff"?"border border-gray-300":"border border-transparent"),style:{backgroundColor:M},onClick:()=>{g(T,M),d(null)},children:e.jsx("span",{className:"sr-only",children:M})},`preset-${R}`))})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2 pt-1",children:[e.jsx("button",{className:"text-sm font-medium text-blue-600 hover:text-blue-700",onClick:()=>{m({value:T,color:o[T]}),d(null)},children:"Custom color"}),!A&&e.jsxs("button",{className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",onClick:()=>{b(T,E),d(null)},children:[e.jsx(s.RotateCcw,{className:"h-3 w-3"}),"Reset"]})]})]})})]}),e.jsx("span",{className:"flex-1 truncate text-sm",children:T}),O&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(custom)"})]},T)})}),u&&e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/50",onClick:()=>m(null)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(Pt,{color:u.color,onColorChange:T=>{g(u.value,T),m(null)},onClose:()=>m(null)})})]})]})})]})}function ve({value:t,onSave:a,placeholder:n="",type:r="text",className:l=""}){const[o,c]=I.useState(t??""),[i,d]=I.useState(!1);I.useEffect(()=>{c(t??"")},[t]);const u=()=>{a(o),d(!1)},m=()=>{c(t??""),d(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${l}`,children:[e.jsx(s.Input$1,{placeholder:n,type:r,value:i?o:t??"",onChange:h=>{c(h.target.value),d(!0)},onFocus:()=>d(!0),onClick:h=>h.stopPropagation(),className:"h-8 text-xs",onPointerDown:h=>h.stopPropagation(),onKeyDown:h=>{h.stopPropagation(),h.key==="Enter"&&i&&o!==t?u():h.key==="Escape"&&m()},"aria-label":n||"Edit field"}),i&&o!==t&&e.jsxs(e.Fragment,{children:[e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm edit",onClick:u,children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel edit",onClick:m,children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}const Tr=["auto","number","currency","percent","scientific","date"],Er=[{value:"USD",label:"USD - US Dollar"},{value:"EUR",label:"EUR - Euro"},{value:"JPY",label:"JPY - Japanese Yen"},{value:"GBP",label:"GBP - British Pound"},{value:"CNY",label:"CNY - Chinese Yuan"},{value:"CHF",label:"CHF - Swiss Franc"},{value:"CAD",label:"CAD - Canadian Dollar"},{value:"AUD",label:"AUD - Australian Dollar"},{value:"HKD",label:"HKD - Hong Kong Dollar"},{value:"SGD",label:"SGD - Singapore Dollar"},{value:"NZD",label:"NZD - New Zealand Dollar"},{value:"SEK",label:"SEK - Swedish Krona"},{value:"NOK",label:"NOK - Norwegian Krone"},{value:"DKK",label:"DKK - Danish Krone"},{value:"KRW",label:"KRW - South Korean Won"},{value:"INR",label:"INR - Indian Rupee"},{value:"RUB",label:"RUB - Russian Ruble"},{value:"BRL",label:"BRL - Brazilian Real"},{value:"MXN",label:"MXN - Mexican Peso"},{value:"TRY",label:"TRY - Turkish Lira"},{value:"ZAR",label:"ZAR - South African Rand"},{value:"SAR",label:"SAR - Saudi Riyal"},{value:"AED",label:"AED - UAE Dirham"},{value:"ARS",label:"ARS - Argentine Peso"},{value:"CLP",label:"CLP - Chilean Peso"},{value:"COP",label:"COP - Colombian Peso"},{value:"THB",label:"THB - Thai Baht"},{value:"IDR",label:"IDR - Indonesian Rupiah"},{value:"MYR",label:"MYR - Malaysian Ringgit"},{value:"PHP",label:"PHP - Philippine Peso"},{value:"PLN",label:"PLN - Polish Zloty"},{value:"NGN",label:"NGN - Nigerian Naira"},{value:"KES",label:"KES - Kenyan Shilling"},{value:"GHS",label:"GHS - Ghanaian Cedi"},{value:"ZMW",label:"ZMW - Zambian Kwacha"},{value:"ZWL",label:"ZWL - Zimbabwean Dollar"},{value:"EGP",label:"EGP - Egyptian Pound"},{value:"MAD",label:"MAD - Moroccan Dirham"},{value:"UAH",label:"UAH - Ukrainian Hryvnia"},{value:"HUF",label:"HUF - Hungarian Forint"},{value:"CZK",label:"CZK - Czech Koruna"},{value:"RON",label:"RON - Romanian Leu"},{value:"PKR",label:"PKR - Pakistani Rupee"},{value:"BDT",label:"BDT - Bangladeshi Taka"},{value:"VND",label:"VND - Vietnamese Dong"},{value:"TWD",label:"TWD - New Taiwan Dollar"},{value:"ILS",label:"ILS - Israeli New Shekel"}],Ir=[{value:"en-US",label:"English (US)"},{value:"en-GB",label:"English (UK)"},{value:"en-IN",label:"English (India)"},{value:"de-DE",label:"German"},{value:"fr-FR",label:"French"},{value:"es-ES",label:"Spanish"},{value:"it-IT",label:"Italian"},{value:"pt-BR",label:"Portuguese (Brazil)"},{value:"zh-CN",label:"Chinese (Simplified)"},{value:"ja-JP",label:"Japanese"},{value:"ko-KR",label:"Korean"},{value:"ru-RU",label:"Russian"},{value:"ar-SA",label:"Arabic"},{value:"hi-IN",label:"Hindi"},{value:"nl-NL",label:"Dutch"},{value:"sv-SE",label:"Swedish"}],Ar=t=>t.charAt(0).toUpperCase()+t.slice(1);function Ts({formatOptions:t={},onFormatOptionsChange:a,showTitle:n=!0,title:r="NUMBER FORMAT"}){const l=t.type||"auto",o=(i,d)=>{a({...t,[i]:d})},c=()=>l==="currency"?2:l==="percent"?1:0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[n&&e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:r}),e.jsxs(s.Select,{value:l,onValueChange:i=>o("type",i),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Tr.map(i=>e.jsx(s.SelectItem,{value:i,className:"text-xs",children:i==="auto"?"Auto (Default)":Ar(i)},i))})]})]}),l!=="auto"&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-4",children:[["number","currency","percent"].includes(l)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Decimals"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{type:"number",min:"0",max:"10",placeholder:"0",value:t.decimalPlaces??c(),onChange:i=>o("decimalPlaces",parseInt(i.target.value)||0),className:"h-8 text-xs"})})]}),l==="currency"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Currency"}),e.jsxs(s.Select,{value:t.currency||"USD",onValueChange:i=>o("currency",i),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Er.map(i=>e.jsx(s.SelectItem,{value:i.value,className:"text-xs",children:i.label},i.value))})]})]}),["number","currency"].includes(l)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Abbreviate (K, M, B)"}),e.jsx(s.SmallSwitch,{checked:t.useSuffix??!1,onCheckedChange:i=>o("useSuffix",i)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Locale"}),e.jsxs(s.Select,{value:t.locale||"en-US",onValueChange:i=>o("locale",i),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Ir.map(i=>e.jsx(s.SelectItem,{value:i.value,className:"text-xs",children:i.label},i.value))})]})]}),l==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Prefix"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{placeholder:"e.g., $",value:t.prefix||"",onChange:i=>o("prefix",i.target.value),className:"h-8 text-xs"})})]}),l==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Suffix"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{placeholder:"e.g., units",value:t.suffix||"",onChange:i=>o("suffix",i.target.value),className:"h-8 text-xs"})})]}),["number","currency"].includes(l)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Negative in ()"}),e.jsx(s.SmallSwitch,{checked:t.negativeInParentheses??!1,onCheckedChange:i=>o("negativeInParentheses",i)})]}),l==="percent"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Multiply By"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{type:"number",placeholder:"100",value:t.multiplyBy??"",onChange:i=>o("multiplyBy",i.target.value?parseFloat(i.target.value):void 0),className:"h-8 text-xs"})})]}),l==="date"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Format"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{type:"text",placeholder:"MM/DD/YYYY",value:t.dateFormat||"",onChange:i=>o("dateFormat",i.target.value),className:"h-8 text-xs"})})]})]})]})}function Gs({axis:t,label:a,type:n,config:r,onChange:l}){var h,f,g,b,p,j,x,v,k,L,C,S;const o=(y,D)=>{l({...r,[y]:D})},c=(y,D)=>{var N,B;l({...r,name:{enabled:y==="enabled"?D:((N=r==null?void 0:r.name)==null?void 0:N.enabled)??!1,text:y==="text"?D:(B=r==null?void 0:r.name)==null?void 0:B.text}})},i=(y,D)=>{var N,B;l({...r,labels:{enabled:y==="enabled"?D:((N=r==null?void 0:r.labels)==null?void 0:N.enabled)??!0,rotation:y==="rotation"?D:(B=r==null?void 0:r.labels)==null?void 0:B.rotation}})},d=(y,D)=>{l({...r,scale:{...r==null?void 0:r.scale,[y]:D===""?"auto":Number(D)}})},u=t==="x"?["auto","top","bottom"]:["auto","left","right"],m=["auto","0","45","90","-45","-90"];return e.jsxs(s.AccordionItem,{value:`${t}-axis`,className:"border-b-0",children:[e.jsxs("div",{className:"flex w-full items-center justify-between gap-2",children:[e.jsx(s.AccordionTrigger,{className:"flex grow items-center justify-between gap-3 py-2 text-sm font-medium hover:no-underline",children:e.jsx("div",{className:"flex grow items-center justify-between gap-2",children:e.jsx("span",{children:a})})}),e.jsx(s.SmallSwitch,{checked:(r==null?void 0:r.enabled)!==!1,onCheckedChange:y=>o("enabled",y),onClick:y=>y.stopPropagation()})]}),e.jsxs(s.AccordionContent,{className:"space-y-4 pt-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"TITLE"}),e.jsx(s.SmallSwitch,{checked:((h=r==null?void 0:r.name)==null?void 0:h.enabled)??!1,onCheckedChange:y=>c("enabled",y)})]}),((f=r==null?void 0:r.name)==null?void 0:f.enabled)&&e.jsx(ve,{placeholder:`${a} title`,value:((g=r==null?void 0:r.name)==null?void 0:g.text)||"",onSave:y=>c("text",y),className:""})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"POSITION"}),e.jsxs(s.Select,{value:(r==null?void 0:r.position)||"auto",onValueChange:y=>o("position",y),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:u.map(y=>e.jsx(s.SelectItem,{value:y,className:"text-xs",children:y==="auto"?"Auto (Default)":s.titleCase(y)},y))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"LABELS"}),e.jsx(s.SmallSwitch,{checked:((b=r==null?void 0:r.labels)==null?void 0:b.enabled)!==!1,onCheckedChange:y=>i("enabled",y)})]}),((p=r==null?void 0:r.labels)==null?void 0:p.enabled)!==!1&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Rotation"}),e.jsxs(s.Select,{value:String(((j=r==null?void 0:r.labels)==null?void 0:j.rotation)||"auto"),onValueChange:y=>i("rotation",y==="auto"?"auto":Number(y)),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:m.map(y=>e.jsx(s.SelectItem,{value:y,className:"text-xs",children:y==="auto"?"Auto (Default)":`${y}°`},y))})]})]})]}),n==="value"&&e.jsx(Ts,{formatOptions:(r==null?void 0:r.formatOptions)||{},onFormatOptionsChange:y=>l({...r,formatOptions:y}),showTitle:!0,title:"FORMAT"}),n==="value"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"SCALE"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Min"}),e.jsx("div",{className:"flex-1",children:e.jsx(ve,{type:"number",placeholder:"auto",value:((x=r==null?void 0:r.scale)==null?void 0:x.min)==="auto"||((v=r==null?void 0:r.scale)==null?void 0:v.min)===void 0?"":String(r.scale.min),onSave:y=>d("min",y),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Max"}),e.jsx("div",{className:"flex-1",children:e.jsx(ve,{type:"number",placeholder:"auto",value:((k=r==null?void 0:r.scale)==null?void 0:k.max)==="auto"||((L=r==null?void 0:r.scale)==null?void 0:L.max)===void 0?"":String(r.scale.max),onSave:y=>d("max",y),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Step"}),e.jsx("div",{className:"flex-1",children:e.jsx(ve,{type:"number",placeholder:"auto",value:((C=r==null?void 0:r.scale)==null?void 0:C.stepSize)==="auto"||((S=r==null?void 0:r.scale)==null?void 0:S.stepSize)===void 0?"":String(r.scale.stepSize),onSave:y=>d("stepSize",y),className:""})})]})]})]})]})]})}function Vt(){const t=s.useEditorStore(c=>c.card),a=s.useEditorStore(c=>{var i;return(i=c.card)==null?void 0:i.preferences}),{setCardPreferences:n,updateCardInFrame:r}=s.useEditorActions();if(!t||["tornado","pyramid","kpi"].includes(t.type))return null;const l=s.AxisConfigurator.getAxisInfo(t.type,a);if(!l.hasXAxis&&!l.hasYAxis)return null;const o=(c,i)=>{const u={...a||{},[c==="x"?"xAxisConfig":"yAxisConfig"]:i};n(u);const m={...t,preferences:u};r(m)};return e.jsxs(s.AccordionItem,{value:"axes",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($a,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Axes"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full",children:[l.hasXAxis&&e.jsx(Gs,{axis:"x",label:"X-Axis",type:l.xAxisType,config:a==null?void 0:a.xAxisConfig,onChange:c=>o("x",c)}),l.hasYAxis&&e.jsx(Gs,{axis:"y",label:"Y-Axis",type:l.yAxisType,config:a==null?void 0:a.yAxisConfig,onChange:c=>o("y",c)})]})})]})}function _t(){const t=s.useEditorStore(u=>u.card),a=s.useEditorStore(u=>{var m,h,f,g;return(g=(f=(h=(m=u.card)==null?void 0:m.preferences)==null?void 0:h.chartOptions)==null?void 0:f.plugins)==null?void 0:g.legend}),{setLegendOptions:n}=s.useEditorActions();if(!t||!s.chartSupportsLegend(t.type))return null;const r="bottom",l="center",o=!(t.type==="stackedBar"||t.type==="stackedLine"),c=(u,m)=>{const h={...a,[u]:m};n(h)},i=["top","bottom","left","right"],d=["start","center","end"];return e.jsxs(s.AccordionItem,{value:"legend",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ca,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Legend"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Display"}),e.jsx(s.SmallSwitch,{checked:(a==null?void 0:a.display)??o,onCheckedChange:u=>c("display",u)})]}),((a==null?void 0:a.display)??o)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(s.Select,{value:(a==null?void 0:a.position)||r,onValueChange:u=>c("position",u),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:i.map(u=>e.jsx(s.SelectItem,{value:u,className:"text-xs",children:s.titleCase(u)},u))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Alignment"}),e.jsxs(s.Select,{value:(a==null?void 0:a.align)||l,onValueChange:u=>c("align",u),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:d.map(u=>e.jsx(s.SelectItem,{value:u,className:"text-xs",children:s.titleCase(u)},u))})]})]})]})]})})]})}function Ut(){var D,N,B,w,F,T,E,A,O;const t=s.useEditorStore(M=>M.card),a=s.useEditorStore(M=>{var R,P;return(P=(R=M.card)==null?void 0:R.preferences)==null?void 0:P.dataLabelsConfig}),n=s.useEditorStore(M=>{var R;return(R=M.card)==null?void 0:R.preferences}),{setCardPreferences:r,updateCardInFrame:l}=s.useEditorActions();if(!t||!s.chartSupportsDataLabels(t.type))return null;const o=((D=n==null?void 0:n.chartOptions)==null?void 0:D.indexAxis)==="y",c=t.type==="stackedBar"||t.type==="stackedLine",i=t.type==="pie"||t.type==="doughnut"||t.type==="polarArea"||t.type==="funnel",d=!i,u=(B=(N=n==null?void 0:n.chartOptions)==null?void 0:N.plugins)==null?void 0:B.datalabels,m=(u==null?void 0:u.display)!==!1&&((u==null?void 0:u.anchor)||(u==null?void 0:u.align)),h=(a==null?void 0:a.enabled)!==void 0?a.enabled:m,f=(M,R)=>{const P={...a,[M]:R},K={...t.preferences||{},dataLabelsConfig:P};r(K);const $={...t,preferences:K};l($)},g=(M,R)=>{const P={...a,font:{...a==null?void 0:a.font,[M]:R}},K={...t.preferences||{},dataLabelsConfig:P};r(K);const $={...t,preferences:K};l($)},b=(M,R)=>{const P={...a,formatOptions:{...a==null?void 0:a.formatOptions,[M]:R}},K={...t.preferences||{},dataLabelsConfig:P};r(K);const $={...t,preferences:K};l($)},j=(()=>{const M=t.type;return M==="stackedBar"||M==="stackedLine"||M==="pie"||M==="doughnut"?"center":o?"right":"top"})();let x=[];c||i?x=["center"]:x=["auto",...(o?["center","left","right"]:["center","top","bottom"]).filter(R=>R!==j),"custom"];const v=()=>s.titleCase(j),k=["center","start","end"],L=["center","start","end","top","bottom"],C=d?["auto","number","currency","percent","none"]:["number","currency","percent","none"],S=[{value:"USD",label:"USD - US Dollar"},{value:"EUR",label:"EUR - Euro"},{value:"GBP",label:"GBP - British Pound"},{value:"JPY",label:"JPY - Japanese Yen"},{value:"CNY",label:"CNY - Chinese Yuan"},{value:"INR",label:"INR - Indian Rupee"},{value:"CAD",label:"CAD - Canadian Dollar"},{value:"AUD",label:"AUD - Australian Dollar"}],y=[{value:"en-US",label:"English (US)"},{value:"en-GB",label:"English (UK)"},{value:"de-DE",label:"German"},{value:"fr-FR",label:"French"},{value:"es-ES",label:"Spanish"},{value:"it-IT",label:"Italian"},{value:"pt-BR",label:"Portuguese (Brazil)"},{value:"zh-CN",label:"Chinese (Simplified)"}];return e.jsxs(s.AccordionItem,{value:"data-labels",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ga,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Data Labels"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Display"}),e.jsx(s.SmallSwitch,{checked:h,onCheckedChange:M=>f("enabled",M)})]}),h&&e.jsxs(e.Fragment,{children:[!c&&!i&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(s.Select,{value:(a==null?void 0:a.position)||"auto",onValueChange:M=>f("position",M),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:x.map(M=>e.jsx(s.SelectItem,{value:M,className:"text-xs",children:M==="auto"?v():M==="custom"?"Custom (Advanced)":s.titleCase(M)},M))})]})]}),c&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Show Total"}),e.jsx(s.SmallSwitch,{checked:(a==null?void 0:a.showTotal)??!1,onCheckedChange:M=>f("showTotal",M)})]}),(a==null?void 0:a.position)==="custom"&&e.jsxs("div",{className:"space-y-2 pl-4 border-l-2 border-muted",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-16",children:"Anchor"}),e.jsxs(s.Select,{value:(a==null?void 0:a.anchor)||"center",onValueChange:M=>f("anchor",M),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:k.map(M=>e.jsx(s.SelectItem,{value:M,className:"text-xs",children:s.titleCase(M)},M))})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-16",children:"Align"}),e.jsxs(s.Select,{value:String((a==null?void 0:a.align)||"center"),onValueChange:M=>f("align",M),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:L.map(M=>e.jsx(s.SelectItem,{value:M,className:"text-xs",children:s.titleCase(M)},M))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Format"}),e.jsxs(s.Select,{value:(a==null?void 0:a.format)||(d?"auto":"none"),onValueChange:M=>f("format",M),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:C.map(M=>e.jsx(s.SelectItem,{value:M,className:"text-xs",children:M==="auto"&&d?"Auto (Use Axis)":M==="none"?"None (Raw Value)":s.titleCase(M)},M))})]})]}),(a==null?void 0:a.format)&&!["auto","none"].includes(a.format)&&e.jsxs("div",{className:"space-y-2 pl-4 border-l-2 border-muted",children:[["number","currency","percent"].includes(a.format)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Decimals"}),e.jsx("div",{className:"flex-1",children:e.jsx(ve,{type:"number",placeholder:"0",value:String(((w=a==null?void 0:a.formatOptions)==null?void 0:w.decimalPlaces)??(a.format==="currency"?2:a.format==="percent"?1:0)),onSave:M=>b("decimalPlaces",Number(M)),className:""})})]}),a.format==="currency"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Currency"}),e.jsxs(s.Select,{value:((F=a==null?void 0:a.formatOptions)==null?void 0:F.currency)||"USD",onValueChange:M=>b("currency",M),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:S.map(M=>e.jsx(s.SelectItem,{value:M.value,className:"text-xs",children:M.label},M.value))})]})]}),["number","currency"].includes(a.format)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Abbreviate (K, M, B)"}),e.jsx(s.SmallSwitch,{checked:((T=a==null?void 0:a.formatOptions)==null?void 0:T.useSuffix)??!1,onCheckedChange:M=>b("useSuffix",M)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Locale"}),e.jsxs(s.Select,{value:((E=a==null?void 0:a.formatOptions)==null?void 0:E.locale)||"en-US",onValueChange:M=>b("locale",M),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:y.map(M=>e.jsx(s.SelectItem,{value:M.value,className:"text-xs",children:M.label},M.value))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Appearance"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Size"}),e.jsx("div",{className:"flex-1",children:e.jsx(ve,{type:"number",placeholder:"12",value:String(((A=a==null?void 0:a.font)==null?void 0:A.size)||12),onSave:M=>g("size",Number(M)),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Weight"}),e.jsxs(s.Select,{value:((O=a==null?void 0:a.font)==null?void 0:O.weight)||"normal",onValueChange:M=>g("weight",M),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"normal",className:"text-xs",children:"Normal"}),e.jsx(s.SelectItem,{value:"bold",className:"text-xs",children:"Bold"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Color"}),e.jsxs(s.Select,{value:(a==null?void 0:a.color)==="auto"||!(a!=null&&a.color)?"auto":"custom",onValueChange:M=>{M==="auto"&&f("color","auto")},children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"auto",className:"text-xs",children:"Auto (Smart Contrast)"}),e.jsx(s.SelectItem,{value:"custom",disabled:!0,className:"text-xs",children:"Custom (Coming Soon)"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Rotation"}),e.jsx("div",{className:"flex-1",children:e.jsx(ve,{type:"number",placeholder:"0",value:String((a==null?void 0:a.rotation)||0),onSave:M=>f("rotation",Number(M)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"degrees"})]})]})]})]})})]})}function Mr(){return e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx("h3",{className:"text-sm font-medium",children:"Chart Configuration"}),e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full px-2",children:[e.jsx(zt,{}),e.jsx(Vt,{}),e.jsx(_t,{}),e.jsx(Ut,{})]})]})}const Lr=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT dimension, cohort, metric FROM table"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/tornado",children:"example"})," in the docs."]})]}),Rr=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT y-axis, label, range-from, range-to, range-value FROM table"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/range",children:"example"})," in the docs."]})]}),Or=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT text FROM table limit 1"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/text",children:"example"})," in the docs."]})]});function Br(){const t=s.useEditorStore(n=>n.card.type);function a(n){const r=["kpi","table","text","map","custom"],l=o=>r.includes(n)?o:e.jsxs(e.Fragment,{children:[o,e.jsx(Mr,{})]});switch(n){case"stackedBar":case"stackedLine":return l(e.jsx(Cr,{}));case"tornado":case"pyramid":return l(e.jsx(Qe,{docContent:Lr,cardType:n}));case"kpi":return e.jsx(gr,{});case"line":case"bar":return l(e.jsx(cr,{cardType:n}));case"range":return l(e.jsx(Qe,{docContent:Rr,cardType:n}));case"pie":case"doughnut":case"polarArea":case"radar":case"funnel":return l(e.jsx(Qe,{cardType:n}));case"bubble":case"scatter":return l(e.jsx(dr,{cardType:n}));case"table":return e.jsx(Sr,{cardType:n});case"text":return e.jsx(Qe,{docContent:Or,cardType:n,suffix:"Visual"});case"map":return e.jsx(vr,{});case"custom":return e.jsx(rr,{});default:return l(e.jsx(hr,{}))}}return e.jsxs(s.ScrollArea,{className:"h-full w-full text-sm",children:[a(t),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})}function $t({label:t,column:a,functions:n,onFunctionChange:r}){let l=n[0];"aggregate"in a?l=n.find(c=>c.value===a.aggregate)||n[0]:"granularity"in a&&(l=n.find(c=>c.value===a.granularity)||n[0]);function o(c){r(c)}return e.jsx(fe,{className:"flex h-8 w-8 justify-center overflow-clip rounded-none border-none bg-muted px-0 [&>svg]:hidden",icon:l.logo,options:n,value:l.value,onValueChange:c=>o(c),label:t,showPlaceholderLabel:!1})}const Fr=[{label:"Sum",value:"SUM",logo:e.jsx(tt,{className:"size-3.5"})},{label:"Count",value:"COUNT",logo:e.jsx(Ne,{className:"size-3.5"})},{label:"Unique",value:"DISTINCT",logo:e.jsx(ba,{className:"size-3.5"})},{label:"Average",value:"AVG",logo:e.jsx(na,{className:"size-3.5"})},{label:"Min",value:"MIN",logo:e.jsx(s.ArrowDown,{className:"size-3.5"})},{label:"Max",value:"MAX",logo:e.jsx(s.ArrowUp,{className:"size-3.5"})}];function Pr({column:t}){const{updateMetricColumnOld:a}=s.useEditorActions();let n=Fr;s.isTextDataType(t.type)&&(n=n.filter(l=>["COUNT","DISTINCT"].includes(l.value))),s.isNumberDataType(t.type)&&(n=n.filter(l=>!["DISTINCT"].includes(l.value)));function r(l){const o={...t,aggregate:l,label:Ye(t.name,l)};a(t.id,o)}return e.jsx($t,{column:t,functions:n,onFunctionChange:l=>r(l),label:"Aggregation"})}const zr=[{label:"Day (D)",value:"day",logo:e.jsx(s.Label,{className:"cursor-pointer text-xs",children:"D"})},{label:"Week (W)",value:"week",logo:e.jsx(s.Label,{className:"cursor-pointer text-xs",children:"W"})},{label:"Month (M)",value:"month",logo:e.jsx(s.Label,{className:"cursor-pointer text-xs",children:"M"})},{label:"Year (Y)",value:"year",logo:e.jsx(s.Label,{className:"cursor-pointer text-xs",children:"Y"})}];function Vr({column:t}){const{updateGroupByColumnOld:a}=s.useEditorActions();function n(r){const l={...t,granularity:r,label:Fe(t.name,r)};a(t.id,l)}return e.jsx($t,{column:t,functions:zr,onFunctionChange:r=>n(r),label:"Granularity"})}function _r({col:t,onChange:a,droppableId:n}){const{columns:r}=s.useDataColumns(),l=I.useMemo(()=>{let i=[];(n===Ee||n===Ie||n===Ae)&&(i=r);const d=i==null?void 0:i.filter(u=>u.column_name!==t.name);return d==null?void 0:d.map(u=>({id:u.column_name,value:u.column_name}))},[r,n,t.name]),o=[{id:t.name,value:t.name}];function c(i){const d=r==null?void 0:r.find(u=>{var m;return u.column_name===((m=i[0])==null?void 0:m.id)});d&&a(d)}return l!=null&&l.length?e.jsx(s.ComboBox2,{multiple:!1,options:l,selectedOptions:o,onChange:c,selectAllChecked:!1,onSelectAllCheckedChange:()=>{},inputClassName:"border-none bg-muted pl-0 pr-8"}):e.jsx("input",{disabled:!0,type:"text",className:"overflow-hidden truncate text-ellipsis whitespace-nowrap bg-muted text-sm",value:t.name})}function Yt({column:t}){const a=s.useEditorStore(d=>d.card.type),n=s.useEditorStore(d=>{var u,m;return(m=(u=d.card)==null?void 0:u.config)==null?void 0:m.metricColumns}),r=(n==null?void 0:n.map(d=>d.label))||[],l=r==null?void 0:r.find(d=>d===t.label||d===t.name),o=l?r.indexOf(l):-1;function c(){return e.jsx("div",{className:"pr-1",children:l&&e.jsx(Bt,{idx:o,col:l,children:e.jsx("div",{className:"w-[130px] text-xs text-muted-foreground",children:"Display Series As"})})})}function i(){return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Data Labels"}),e.jsx(Ft,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(a)&&c(),["pie","doughnut"].includes(a)&&i()]})}function Ur({column:t,type:a,onRemoveColumn:n,droppableId:r}){const[l,o]=I.useState(!1),{updateGroupByColumnOld:c,updateMetricColumnOld:i,updatePivotByColumnOld:d}=s.useEditorActions(),{attributes:u,listeners:m,setNodeRef:h,transform:f,transition:g,isDragging:b}=s.useSortable({id:t.id,data:{type:a}}),p=f?{opacity:b?.5:void 0,transform:s.CSS.Translate.toString(f),transition:g}:void 0,j=s.isTextDataType(t.type);function x(S){const y=s.isNumberDataType(S.data_type),D=s.isTextDataType(S.data_type),N=s.isDateDataType(S.data_type),B=y?"number":D?"string":N?"date":"string";if(r===Ee){if(D){const w={id:t.id,name:S.column_name,type:B,role:"groupby"};c(t.id,w)}if(N){const w={id:t.id,name:S.column_name,type:B,role:"groupby",label:Fe(S.column_name,"month"),granularity:"month"};c(t.id,w)}}if(r===Ae){if(D){const w={id:t.id,name:S.column_name,type:B,role:"groupby"};d(t.id,w)}if(N){const w={id:t.id,name:S.column_name,type:B,label:Fe(S.column_name,"month"),granularity:"month",role:"groupby"};d(t.id,w)}}if(r===Ie){const w={id:t.id,name:S.column_name,type:B,role:"metric",label:Ye(S.column_name,"SUM"),aggregate:y?"SUM":"COUNT"};i(t.id,w)}}function v(){if(r===Ie)return e.jsx("div",{"data-setting-container":"",className:"mt-1.5 max-h-32 overflow-y-auto rounded-md border border-border p-3 text-sm",children:e.jsx(Yt,{column:t})})}function k(){const S=s.isDateDataType(t.type);if(r===Ie)return e.jsx(Pr,{column:t});if((r===Ee||r===Ae)&&S)return e.jsx(Vr,{column:t})}function L(){return e.jsx("div",{className:s.cn("grow",{"pl-3":(r===Ee||r===Ae)&&j}),children:e.jsx(_r,{col:t,onChange:x,droppableId:r})})}function C(){return e.jsx("div",{"data-setting-actions":"",className:"flex h-full items-center gap-2",children:e.jsx("button",{className:"h-full pl-2",onClick:()=>o(!l),children:l?e.jsx(Ua,{className:s.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")}):e.jsx(et,{className:s.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")})})})}return e.jsx("div",{...m,...u,ref:h,style:p,children:e.jsxs("div",{className:"group flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex h-8 grow items-center justify-between rounded-md bg-muted",children:[C(),k(),L()]}),l&&v()]}),e.jsx("div",{className:s.cn("opacity-0 transition-opacity duration-200 group-hover:opacity-100",{hidden:l}),children:e.jsx("button",{onClick:()=>n(t.id),children:e.jsx(s.X,{className:"size-3 cursor-pointer text-muted-foreground"})})})]})})}function ps({id:t,label:a,columns:n,previewColumns:r,sortableType:l,onRemoveColumn:o}){var p,j;const{setNodeRef:c,isOver:i,over:d}=s.useDroppable({id:t}),u=s.useDndStore(x=>x.activeId),m=s.useEditorStore(x=>{var v;return(v=x.card)==null?void 0:v.type}),h=i||((j=(p=d==null?void 0:d.data)==null?void 0:p.current)==null?void 0:j.type)===l,f=u?r:n,g=l===ts?"Rows":l===as?"Pivot Columns":"Columns";function b(){if(!f||f.length===0)return e.jsx("div",{className:"mr-5 flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground/80 bg-background px-2 py-1 text-sm text-muted-foreground",children:e.jsx("span",{className:"invisible text-muted-foreground/70 group-hover:visible",children:"Drag here"})})}return e.jsx(s.SortableContext,{items:n==null?void 0:n.map(x=>x.id),children:e.jsxs("div",{className:s.cn("group space-y-2 rounded-md p-4",h&&"border border-muted-foreground/20"),ref:c,children:[e.jsxs("div",{className:"flex items-center justify-between pr-5",children:[e.jsx(s.Label,{className:"text-sm",children:a}),m!=="table"&&e.jsx("span",{className:"text-xs text-muted-foreground/50",children:g})]}),b(),e.jsx("div",{className:"space-y-2",children:f==null?void 0:f.map(x=>x.id===vt.id?e.jsx($r,{},x.id):e.jsx(Ur,{droppableId:t,type:l,column:x,onRemoveColumn:o},x.id))})]})})}function $r(){return e.jsx("div",{className:"mr-5 flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground bg-background px-2 py-1 text-sm",children:e.jsx("span",{className:"text-muted-foreground/70",children:"Drop here"})})}function qt({children:t,id:a,type:n}){const{attributes:r,listeners:l,setNodeRef:o,transform:c,transition:i,isDragging:d}=s.useSortable({id:a,data:{type:n}}),u=c?{opacity:d?.5:void 0,transform:s.CSS.Translate.toString(c),transition:i}:void 0;return e.jsx("div",{...l,...r,ref:o,style:u,children:t})}function Yr(){const t=s.useEditorStore(x=>{var v;return(v=x.card.queryConfig)==null?void 0:v.orderBy})||[],a=s.useEditorStore(x=>{var v;return(v=x.card.queryConfig)==null?void 0:v.groupByColumns})||[],n=s.useEditorStore(x=>{var v;return(v=x.card.queryConfig)==null?void 0:v.metricColumns})||[],{addOrderByColumn:r,removeOrderByColumn:l,updateOrderByColumn:o}=s.useEditorActions(),c=[...a,...n];if(c.length===0)return e.jsx(e.Fragment,{});const i=e.jsx(la,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),d=e.jsx(aa,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),u=e.jsx(ra,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),m=e.jsx(ta,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),h=c==null?void 0:c.filter(x=>!t.some(v=>v.columnId===x.id)).map(x=>({id:x.id,value:x.label||x.name}));function f(x,v){const k=g(x);return k?k.role==="metric"?v==="asc"?u:m:v==="asc"?i:d:null}function g(x){return c.find(v=>v.id===x)}function b(x){const v=t.find(k=>k.columnId===x);if(v){const k={...v,direction:v.direction==="asc"?"desc":"asc"};o(k)}}const p=x=>{r({columnId:x.id,direction:"asc"})};function j(x){const v=t.find(k=>k.columnId===x);v&&l(v)}return e.jsx(s.SortableContext,{items:t.map(x=>Ve(x.columnId)),children:e.jsxs("div",{className:"space-y-2 rounded-md p-4 text-sm",children:[e.jsx(s.Label,{className:"text-sm",children:"Sort By"}),h.length>0&&e.jsx("div",{className:"mr-5",children:e.jsx(s.ComboBox2,{multiple:!1,options:h,selectedOptions:[],onChange:x=>p(x[0]),selectAllChecked:!1,onSelectAllCheckedChange:()=>{},inputClassName:"h-8 bg-muted border-none"})}),t.map(x=>{var v,k;return e.jsx(qt,{id:Ve(x.columnId),type:Ss,children:e.jsx("div",{className:"group flex h-8 items-center gap-2 rounded-sm p-0",children:e.jsxs("div",{className:"flex h-full grow items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex h-full grow items-center justify-between gap-2 rounded-sm bg-muted px-2",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(et,{className:"size-3 cursor-move text-muted-foreground hover:text-foreground"}),e.jsx(os,{className:"w-[175px] text-sm",children:((v=g(x.columnId))==null?void 0:v.label)||((k=g(x.columnId))==null?void 0:k.name)})]}),e.jsx("button",{title:x.direction==="asc"?"Ascending":"Descending",onClick:()=>b(x.columnId),className:"rounded-sm p-0",children:f(x.columnId,x.direction)})]}),e.jsx("div",{children:e.jsx("button",{onClick:()=>j(x.columnId),className:"rounded-sm p-0",children:e.jsx(s.X,{className:"size-3 text-muted-foreground opacity-0 transition-opacity duration-200 hover:text-foreground group-hover:opacity-100"})})})]})},x.columnId)},Ve(x.columnId))})]})})}function qr(){const t=s.useEditorStore(j=>{var x;return((x=j.card.queryConfig)==null?void 0:x.groupByColumns)||[]}),a=s.useEditorStore(j=>j.card.type),n=s.useDndStore(j=>j.previewGroupByColumns),r=s.useEditorStore(j=>{var x;return((x=j.card.queryConfig)==null?void 0:x.metricColumns)||[]}),l=s.useDndStore(j=>j.previewMetricColumns),o=s.useEditorStore(j=>{var x;return((x=j.card.queryConfig)==null?void 0:x.pivotColumns)||[]}),c=s.useDndStore(j=>j.previewPivotColumns),{removeColumnFromGroupBy:i,removeColumnFromMetricColumns:d,removeColumnFromPivotBy:u}=s.useEditorActions();function m(j){i(j)}function h(j){d(j)}function f(j){u(j)}let g="Group By",b="Metrics",p="Stack By";return a==="table"&&(g="Rows",b="Metrics",p="Columns"),e.jsxs("div",{className:"flex h-full w-full flex-col gap-3 py-4",children:[e.jsx(It,{iconClassName:"size-[19px]"}),e.jsxs(s.CustomScrollArea,{className:"flex min-h-0 grow basis-0 flex-col gap-4 overflow-y-auto",children:[e.jsxs("div",{className:"flex flex-col gap-4 p-4",children:[e.jsx(ps,{onRemoveColumn:m,sortableType:ts,id:Ee,label:g,columns:t,previewColumns:n}),e.jsx(ps,{onRemoveColumn:f,sortableType:as,id:Ae,label:p,columns:o,previewColumns:c}),e.jsx(ps,{onRemoveColumn:h,sortableType:bs,id:Ie,label:b,columns:r,previewColumns:l}),e.jsx(Yr,{})]}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Es({children:t,column:a,id:n,sortableType:r,className:l}){const[o,c]=I.useState(!1),{removeEditorFilter:i,clearEditorFilter:d}=s.useEditorActions(),u=s.useEditorStore(h=>{var f,g;return(g=(f=h.card.queryConfig)==null?void 0:f.filters)==null?void 0:g.some(b=>b.filterColumnName===a.name)});function m(h){i(h)}return e.jsx(qt,{id:n,type:r,children:e.jsxs("div",{className:s.cn("group space-y-1 rounded-md bg-muted px-3 py-2",{"border-border":o}),children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-sm",children:a.name}),u&&e.jsx("button",{onClick:()=>d(a),children:e.jsx(s.FilterX,{className:"size-3 cursor-pointer items-center justify-center text-muted-foreground hover:text-foreground"})})]}),e.jsx("div",{"data-setting-actions":"",className:"invisible flex h-full items-center gap-2 group-hover:visible",children:e.jsx("button",{onClick:()=>m(a),children:e.jsx(s.X,{className:"size-3.5 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground"})})})]}),e.jsxs("div",{className:s.cn("group flex items-center rounded-t-md text-sm",!o&&"rounded-b-md",o&&"border border-border"),children:[e.jsx("div",{children:e.jsx(s.GripVertical,{className:"mr-2 size-3.5 cursor-move items-center justify-center p-0 text-muted-foreground/60 hover:text-foreground"})}),e.jsx("div",{className:s.cn("grow cursor-pointer overflow-hidden truncate text-ellipsis whitespace-nowrap",l),children:t})]})]})})}function Gr({column:t,sortableType:a}){const n=s.useDashboardStore(k=>k.themeStyle),r=s.useEditorStore(k=>{var L,C;return(C=(L=k.card)==null?void 0:L.queryConfig)==null?void 0:C.filters}),l=s.useEditorStore(k=>{var L,C;return(C=(L=k.card.queryConfig)==null?void 0:L.filterColumns)==null?void 0:C.find(S=>S.name===t.name)}),{selectedConnectionId:o,selectedDatabaseName:c,selectedTableName:i}=s.useEditorAside(),d=I.useMemo(()=>{var k;return(k=r==null?void 0:r.find(L=>L.filterColumnName===t.name))==null?void 0:k.filterValue},[r,t.name]),u=I.useMemo(()=>Array.isArray(d)?d.map(k=>({id:k,value:k})):[],[d]),{updateEditorFilterValue:m}=s.useEditorActions(),h={column:t.name,sql:t.sql,id:t.name,connectionId:o,dataType:t.type},{data:f,isLoading:g,isFetching:b,isError:p}=s.useFilterQuery(h),j=I.useMemo(()=>{var L;return h.column?(L=f==null?void 0:f.records)==null?void 0:L.map(C=>{let S=h.column.split(".").slice(-1)[0].replace(/"/g,"");return C[S]===void 0&&(S=S.toLowerCase()),{id:C[S],value:C[S]}}):[]},[f,h.column]);function x(k){const L=k.map(C=>C.id);m(t.name,L)}function v(){return g||b?e.jsx(s.Skeleton,{style:{borderRadius:n==null?void 0:n.controlInputRadius},className:"h-8 min-w-60 bg-foreground/10"}):p?e.jsx("div",{className:"flex h-8 min-w-60 items-center bg-muted px-2 text-sm",children:"Error"}):e.jsx(s.ComboBox2,{renderFilterModeButton:()=>e.jsx(Hr,{columnName:t.name}),showNegativeIndicator:(l==null?void 0:l.mode)==="exclude",options:j,onChange:x,selectedOptions:u,selectAllChecked:!1,onSelectAllCheckedChange:()=>{}})}return e.jsx(Es,{className:"w-60",id:t.id,sortableType:a,column:t,children:v()})}function Hr({columnName:t}){const{setEditorFilterMode:a}=s.useEditorActions(),n=s.useEditorStore(l=>{var o,c;return(c=(o=l.card.queryConfig)==null?void 0:o.filterColumns)==null?void 0:c.find(i=>i.name===t)});function r(){(n==null?void 0:n.mode)==="exclude"?a(t,"include"):a(t,"exclude")}return e.jsx(s.Button,{onClick:r,variant:"secondary",size:"sm",className:s.cn("h-5 text-xs hover:underline",{}),children:s.titleCase((n==null?void 0:n.mode)==="exclude"?"exclude":"include")})}function Wr({open:t,setOpen:a,dateRange:n,setDateRange:r,containerClassName:l,inputClassName:o,title:c,onApply:i,onClear:d}){const u=s.useDashboardStore(m=>m.themeStyle);return e.jsx("div",{className:s.cn("grid gap-2",l),children:e.jsxs(s.Popover,{open:t,onOpenChange:a,children:[e.jsx(s.PopoverTrigger,{style:{borderRadius:u==null?void 0:u.controlInputRadius},asChild:!0,children:e.jsxs(s.Button,{size:"sm",id:"date",variant:"outline",className:s.cn("h-9 w-full justify-start rounded-sm text-left font-normal",!n&&"text-muted-foreground",o),children:[e.jsx(s.Calendar,{className:"mr-2 h-4 w-4"}),n!=null&&n.from?n.to?e.jsxs(e.Fragment,{children:[s.format(n.from,"LLL dd, y")," -"," ",s.format(n.to,"LLL dd, y")]}):s.format(n.from,"LLL dd, y"):e.jsx("span",{children:"Pick a date"})]})}),e.jsxs(s.PopoverContent,{style:{borderRadius:u==null?void 0:u.controlInputRadius},className:"w-auto p-0",align:"start",children:[e.jsx("div",{className:"px-4 pt-3",children:e.jsx(s.Label,{children:c})}),e.jsx(s.Calendar$1,{initialFocus:!0,mode:"range",defaultMonth:n==null?void 0:n.from,selected:n,onSelect:r,numberOfMonths:2}),e.jsxs("div",{className:"flex justify-end gap-2 px-4 py-3",children:[e.jsx(s.Button,{style:{borderRadius:u==null?void 0:u.controlInputRadius},size:"sm",variant:"outline",onClick:m=>{m.stopPropagation(),i(n),a(!1)},children:"Apply"}),e.jsx(s.Button,{style:{borderRadius:u==null?void 0:u.controlInputRadius},size:"sm",variant:"outline",onClick:d,children:"Clear"})]})]})]})})}function Kr({column:t,sortableType:a}){const[n,r]=I.useState(!1),{selectedConnectionId:l,selectedDatabaseName:o,selectedTableName:c}=s.useEditorAside(),i={column:t.name,sql:t.sql,id:t.name,connectionId:l,title:"",dataType:t.type},{isLoading:d,isFetching:u,isError:m,data:h}=s.useFilterQuery(i),f=h==null?void 0:h.records,{dateRange:g,setDateRange:b,initialDateRange:p}=s.useDateRangeFromRecords(f),{updateEditorFilterValue:j}=s.useEditorActions();function x(L){var S,y;const C={gte:(S=L==null?void 0:L.from)==null?void 0:S.toISOString(),lte:(y=L==null?void 0:L.to)==null?void 0:y.toISOString()};j(t.name,C)}function v(){j(t.name,null,!0),b(p)}function k(){return d||u?e.jsx("div",{children:e.jsx(s.Skeleton,{className:"h-8 w-72 bg-foreground/10"})}):m?e.jsx("div",{className:"h-8 w-72 bg-muted px-2",children:"Error"}):f?e.jsx(Wr,{title:i.title,open:n,inputClassName:"h-8",setOpen:r,dateRange:g,setDateRange:b,onApply:x,onClear:v}):e.jsx(s.Label,{className:"flex h-8 w-72 items-center bg-muted px-2",children:"No Data"})}return e.jsx(Es,{className:"w-72",id:t.id,sortableType:a,column:t,children:k()})}function Jr({id:t,label:a,columns:n,previewColumns:r,sortableType:l}){var b,p;const{setNodeRef:o,isOver:c,over:i}=s.useDroppable({id:t}),d=s.useDndStore(j=>j.activeId),u={},m=c||((p=(b=i==null?void 0:i.data)==null?void 0:b.current)==null?void 0:p.type)===l;function h(){if(!g||g.length===0)return e.jsx("div",{className:"flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground/80 bg-background px-2 py-1 text-sm text-muted-foreground",children:e.jsx("span",{className:"invisible text-muted-foreground/70 group-hover:visible",children:"Drag here"})})}function f(j){const x=s.isDateDataType(j.type);return j.id===vt.id?e.jsx(Es,{id:j.id,sortableType:l,column:j,children:e.jsx(Qr,{})},j.id):x?e.jsx(Kr,{droppableId:t,sortableType:l,column:j},j.id):e.jsx(Gr,{droppableId:t,sortableType:l,column:j},j.id)}const g=d?r:n;return e.jsx(s.SortableContext,{items:n==null?void 0:n.map(j=>j.id),children:e.jsxs("div",{className:s.cn("group space-y-2 rounded-md border-muted-foreground/50 p-4",m&&"border border-muted-foreground/20"),ref:o,style:u,children:[e.jsx(s.Label,{className:"text-sm",children:a}),h(),e.jsx("div",{className:"flex flex-wrap items-center gap-4",children:g==null?void 0:g.map(j=>f(j))})]})})}function Qr(){return e.jsx("div",{className:"flex h-8 w-60 items-center space-x-2 rounded-md border border-dashed border-muted-foreground bg-background px-2 py-1 text-sm text-muted-foreground",children:"Drop here"})}function Xr(){const t=s.useEditorStore(l=>{var o;return((o=l.card.queryConfig)==null?void 0:o.filterColumns)||[]}),a=s.useDndStore(l=>l.previewFilterColumns),{removeColumnFromFilterColumns:n}=s.useEditorActions();function r(l){n(l)}return e.jsx("section",{className:"size-full px-4 pb-4",children:e.jsx(Jr,{onRemoveColumn:r,sortableType:vs,id:ys,label:"Filters",columns:t,previewColumns:a})})}function Zr(){const t=s.useEditorStore(c=>c.card),a=s.useEditorStore(c=>c.showAIDialog),{setShowAIDialog:n}=s.useEditorActions(),{data:r,errorMessage:l,errorSql:o}=s.useDashboardCardQuery(t);return e.jsxs("section",{className:"flex justify-between gap-2 p-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(rs,{}),!a&&e.jsxs(s.Button,{onClick:()=>n(!0),variant:"secondary",size:"sm",children:[e.jsx(Ma,{className:"mr-2 h-4 w-4"}),"Assistant"]}),e.jsx(wt,{sql:r==null?void 0:r.sql,error:l,errorSql:o})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"rounded-full bg-green-300 px-3 py-1 text-xs font-medium text-black",children:"Preview"}),e.jsx(Ds,{}),e.jsx(ws,{variant:"default"})]})]})}function el(){const t=I.useRef(null),a=I.useRef(null),n=s.useEditorStore(i=>i.isShowingVisual),r=s.useEditorStore(i=>i.showAIDialog),l=s.useEditorStore(i=>i.isDevMode);I.useEffect(()=>{var i,d,u,m;r?((i=t.current)==null||i.resize(0),(d=a.current)==null||d.resize(0)):((u=t.current)==null||u.resize(25),(m=a.current)==null||m.resize(25))},[r]);function o(){return e.jsxs(e.Fragment,{children:[e.jsx(s.ResizablePanel,{role:"query-section",className:"flex",minSize:20,defaultSize:40,children:e.jsx($n,{})}),e.jsx(s.ResizableHandle,{withHandle:!0}),e.jsx(s.ResizablePanel,{className:"pb-1",role:"visual-section",minSize:0,defaultSize:60,children:n&&!r?e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(s.ResizablePanel,{ref:t,className:"flex",defaultSize:25,maxSize:30,children:e.jsx(Br,{})})}),!r&&e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(Je,{})})]}):e.jsx(Je,{})})]})}function c(){return e.jsx(e.Fragment,{children:e.jsx("div",{className:"grow","data-biz-mode-container":"",children:n?e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(s.ResizablePanel,{ref:a,defaultSize:25,maxSize:30,children:e.jsx(qr,{})})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{defaultSize:75,maxSize:100,children:e.jsxs(s.ResizablePanelGroup,{direction:"vertical",children:[e.jsxs(s.ResizablePanel,{className:"flex min-h-fit flex-col",minSize:10,defaultSize:20,children:[e.jsx(Zr,{}),e.jsx(Xr,{})]}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:60,defaultSize:80,children:e.jsx(Je,{})})]})})]}):e.jsx(Je,{})})})}return e.jsx(s.ResizablePanelGroup,{direction:"vertical",className:"min-h-[250px] min-w-full max-w-lg",children:l?o():c()})}function sl(t){s.useAIInteractionStore(V=>V.currentAIContext);const[a,n]=I.useState(""),[r,l]=I.useState(null),{authToken:o}=s.useSemaphorContext(),c=s.useEditorStore(V=>{var se;return(se=V==null?void 0:V.card)==null?void 0:se.sql}),i=s.useEditorStore(V=>V.isDevMode),d=s.useEditorStore(V=>{var se;return(se=V==null?void 0:V.card)==null?void 0:se.python}),{setCardPython:u,setCardSql:m,setRunSql:h,switchCardType:f,setQueryConfig:g}=s.useEditorActions(),b=s.useEditorStore(V=>V.currentAssitantScope)||[],p=s.useEditorStore(V=>V.userInputForAI),j=s.useEditorStore(V=>V.triggerAIRun),x=s.useEditorStore(V=>V.card),v=s.useEditorStore(V=>V.selectedDatabaseName),k=s.useEditorStore(V=>V.selectedTableName),L=s.useEditorStore(V=>V.selectedConnectionId),C=s.useEditorStore(V=>V.selectedSchemaName),S=s.useDashboardStore(V=>V.dashboard.aiScopeTables),{errorMessage:y,refetch:D,data:N}=s.useDashboardCardQuery(x),{setTriggerAIRun:B,setCurrentAssitantScope:w,setCardConfig:F}=s.useEditorActions(),{selectedDatamodelName:T,connectionType:E,selectedDatamodelId:A}=s.useEditorAside(),{messages:O,setMessages:M,regenerate:R,error:P,sendMessage:K,status:$,addToolResult:te,stop:X,clearError:q}=s.useChat({transport:new s.DefaultChatTransport({api:"https://semaphor.cloud/api/v1/assistant",headers:()=>({Authorization:`Bearer ${o==null?void 0:o.accessToken}`}),body:()=>{const V=s.useAIInteractionStore.getState();return{random:Math.random(),assistantId:"editor-assistant",isDevMode:i,aiContext:V.currentAIContext,reasoningEffort:V.reasoningEffort,showReasoning:V.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:V,body:se})=>({body:{...se,messages:s.cleanupIncompleteMessages(V)}})}),onError:V=>{console.log("on error",V)},onToolCall:H,onFinish(){n("")}});I.useEffect(()=>{j&&p&&(K({role:"user",parts:[{type:"text",text:p}]}),B(!1))},[j,p,K,B]);async function H({toolCall:V}){var se,ne,Y,W,re,ie,he,Q,oe,ee,ae,ue,je,Ge,He,We;if(["createChartFromSql","createForecast"].includes(V.toolName)){const ze=((se=V.input)==null?void 0:se.sql)??((ne=V.args)==null?void 0:ne.sql),Ce=((Y=V.input)==null?void 0:Y.python)??((W=V.args)==null?void 0:W.python),me=((re=V.input)==null?void 0:re.chartType)??((ie=V.args)==null?void 0:ie.chartType);f(me),m(ze),u(Ce),h(!0),te({tool:V.toolName,toolCallId:V.toolCallId,output:{status:"success",message:"Let the user know that chart is created"}})}else if(V.toolName==="getUserSql"){if(!c){te({tool:V.toolName,toolCallId:V.toolCallId,output:{status:"error",message:"No SQL found"}});return}te({tool:V.toolName,toolCallId:V.toolCallId,output:{status:"success",sql:c,python:d||""}})}else if(V.toolName==="generateQueryConfig"){n("Generating query config...");const ze=((he=V.input)==null?void 0:he.chartType)??((Q=V.args)==null?void 0:Q.chartType),Ce=((oe=V.input)==null?void 0:oe.queryConfig)??((ee=V.args)==null?void 0:ee.queryConfig);((ae=V.input)==null?void 0:ae.cardConfig)??((ue=V.args)==null||ue.cardConfig),f(ze),F(Ce),m(void 0),u(void 0);const me=await D();if((je=me==null?void 0:me.data)!=null&&je.error){te({tool:V.toolName,toolCallId:V.toolCallId,output:{status:"error",queryConfig:Ce,message:(Ge=me==null?void 0:me.data)==null?void 0:Ge.error.message}});return}if((He=me==null?void 0:me.data)!=null&&He.records){te({tool:V.toolName,toolCallId:V.toolCallId,output:{status:"success",queryConfig:Ce,message:"The data has been visualized"}});return}te({tool:V.toolName,toolCallId:V.toolCallId,output:{status:"success",queryConfig:Ce,message:"The data has been visualized",records:(We=me==null?void 0:me.data)==null?void 0:We.records}})}else n("Analyzing...")}function _(V){const se=s.removeFromScopeArray(b,V);J(se)}function J(V){const se=s.sanitizeAIScope(V);w(se),M(ne=>[...ne,{id:crypto.randomUUID(),role:"system",parts:[{type:"text",text:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(se)}`}]}])}function z(){const V={databaseName:v||"",schemaName:C||"",tableName:k||"",datamodelId:A||"",datamodelName:s.resolveDatamodelName(T),connectionId:L||"",connectionType:E||""},se=s.dedup([...b,V]);J(se)}function U(){const V={databaseName:v||"",schemaName:C||"",tableName:k||"",datamodelName:s.resolveDatamodelName(T),connectionId:L||"",connectionType:E||"",datamodelId:A||""};if(!s.isInAiScopeArray([...S||[],...b],V)||b.length===0){const ne=s.dedup([...S||[],...b,V]).filter(Y=>Y.connectionId===V.connectionId);J(ne)}}const Z=!["ready","error"].includes($),le=s.getErrorMessage(P);return{messages:O,setMessages:M,sendMessage:K,regenerate:R,isLoading:Z,handleSetAIScope:U,handleAddCurrentTableToScope:z,removeFromCurrentSelections:_,currentAssitantScope:b,setCurrentAssitantScope:w,stop:X,status:$,toolStatus:a,llmUsage:r,onFinish:t,errorMessage:le,clearError:q}}const tl=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function Hs(){const t=I.useRef(null),[a,n]=I.useState(!1),[r,l]=I.useState(s.isDevEnv),[o,c]=I.useState(!1),[i,d]=I.useState(!1),u=s.useCurrentAIContext(),{setCurrentAIContext:m}=s.useAIActions(),{clearQueue:h}=s.useQueueActions(),{clearFileAttachments:f}=s.useFileActions(),g=s.useFileAttachments("editor"),b=s.useDashboardStore(ee=>ee.dashboard.aiContext),p=s.useEditorStore(ee=>ee.card.dataSource),j=s.useEditorStore(ee=>ee.actions.setCardSql),x=s.useEditorStore(ee=>ee.actions.setRunSql),v=s.useEditorStore(ee=>ee.showAIDialog),k=s.useDashboardStore(ee=>ee.handleOpenAssistantProfile),{setShowAIDialog:L,setCardPython:C}=s.useEditorActions(),{setDataSource:S}=s.useEditorActions(),{assistantProfile:y}=s.useAssistantProfile(),{messages:D,setMessages:N,sendMessage:B,isLoading:w,stop:F,status:T,llmUsage:E,errorMessage:A,clearError:O}=sl(),[M,R]=I.useState(""),P=ee=>{R(ee.target.value)},K=ee=>{ee.preventDefault();const ae=M.trim();if(!ae&&g.length===0)return;const ue=[];ae&&ue.push({type:"text",text:ae}),g.forEach(je=>{je.data&&ue.push({type:"file",mediaType:je.type,filename:je.name,url:`data:${je.type};base64,${je.data}`})}),B({role:"user",parts:ue}),R(""),f("editor"),Z({force:!0})},{visibleMessages:$,hasMoreMessages:te,totalMessageCount:X,loadMoreMessages:q,resetMessageWindow:H}=s.useMessageWindow(D,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:_,isAtBottom:J,hasNewMessages:z,newMessageCount:U,scrollToBottom:Z,handleScroll:le,resetNewMessageCount:V}=s.useAutoScroll($,{threshold:50,delay:0,dependencies:[T,D.length]});I.useEffect(()=>{var ee;v&&((ee=t.current)==null||ee.focus(),m({selectedEntities:(p==null?void 0:p.selectedEntities)||[]}))},[v,p,m]),s.useAutoSubmitQueue({assistantType:"editor",status:T,isLoading:w,sendMessage:B});const{hasActiveTools:se}=s.useActiveToolStatus(D);function ne(ee,ae){ae==="sql"?(j(ee),x(!0)):ae==="python"&&(C(ee),x(!0))}function Y(){var ee;(ee=b==null?void 0:b.selectedEntities)==null||ee[0],d(!0)}function W(){u.selectedEntities.length===0&&m({selectedEntities:(b==null?void 0:b.selectedEntities)||[]})}function re(ee){W();const ae={role:"user",parts:[{type:"text",text:ee.title+" "+ee.subtitle}]};B(ae)}function ie(ee){W(),B({role:"user",parts:[{type:"text",text:ee}]})}function he(){return e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{className:"h-7 p-2 text-muted-foreground/50 hover:text-foreground",size:"sm",variant:"ghost",children:e.jsx(s.EllipsisVertical,{className:"size-3.5"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsx(s.DropdownMenuLabel,{children:"Options"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsx(s.DropdownMenuCheckboxItem,{checked:a,onCheckedChange:n,children:"Token Usage"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:r,onCheckedChange:l,children:"Tool Invocations"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:o,onCheckedChange:c,children:"System Message"})]})]})}function Q(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const oe=(M==null?void 0:M.length)===0&&(D==null?void 0:D.filter(ee=>ee.role==="user").length)===0;return e.jsxs("div",{"data-role":"editor-assistant",className:"flex h-full w-full flex-col justify-between px-6 py-4",children:[e.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[Q(),k&&e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:k,children:(y==null?void 0:y.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[he(),s.isDevEnv,e.jsx(s.IconButton,{tooltip:"Add Context",className:"h-7 p-2 text-muted-foreground/50 hover:text-foreground",onClick:Y,children:e.jsx(s.Settings,{className:"size-4"})}),e.jsx(s.IconButton,{className:"h-7 p-2 text-muted-foreground/50 hover:text-foreground",tooltip:"New Chat",onClick:()=>{N([]),h("editor"),O(),H()},children:e.jsx(s.SquarePen,{className:"size-4"})}),e.jsx(s.Button,{variant:"ghost",className:"h-7 p-2 text-muted-foreground/50 hover:text-foreground",size:"sm",onClick:()=>{L(!1)},children:e.jsx(s.ArrowRightToLine,{className:"size-4"})})]})]}),e.jsx(s.CustomScrollArea,{ref:_,className:"mt-2 flex w-full grow basis-0",onScroll:le,children:e.jsxs("div",{className:"space-y-4 py-2 pr-3","data-role":"messages",children:[te&&e.jsx("div",{className:"flex justify-center py-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:q,className:"text-xs",children:["Load ",Math.min(5,X-$.length)," more messages (",X-$.length," hidden)"]})}),e.jsx(s.PrintMessages,{messages:$,showTools:r,handleRun:ne,showSystemMessage:o}),!se&&e.jsx(s.AssistantStatus,{status:T,errorMessage:A})]})}),!J&&e.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:e.jsxs(s.Button,{onClick:()=>{Z({force:!0}),V()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[e.jsx(s.ChevronDown,{className:"h-4 w-4"}),z&&U>0&&e.jsx("span",{className:"ml-1.5 flex h-5 w-5 items-center justify-center rounded-full bg-primary text-xs text-primary-foreground",children:U>9?"9+":U})]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[oe&&!y&&e.jsx(s.Placeholders,{onClick:re,placeholders:tl}),e.jsx("div",{children:oe&&y&&e.jsx(s.SeedQuestions,{seedQuestions:y.seedQuestions||[],handleSeedQuestionClick:ie})})]}),e.jsx(s.PendingMessagesDisplay,{assistantType:"editor",className:"mb-3"}),e.jsx(s.ChatInputWithContext,{ref:t,setInput:R,stop:F,input:M,handleInputChange:P,handleSubmit:ee=>{W(),K(ee),Z({force:!0})},isLoading:w,status:T,assistantType:"editor",onFocus:()=>{}})]}),E&&a&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",E.inputTokens," prompt tokens, ",E.outputTokens," ","completion tokens, ",E.totalTokens," total tokens"]})}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(p==null?void 0:p.selectedEntities)||[],open:i,onOpenChange:d,dataSource:p||s.EMPTY_DATA_SOURCE,fallbackDataSource:s.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]})}const Is=t=>{var w;const{updateCardConfig:a,updateGroupByColumn:n,updateMetricColumn:r,updatePivotByColumn:l,updateSortByColumn:o,removeGroupByColumn:c,removeMetricColumn:i,removePivotByColumn:d,removeSortByColumn:u}=s.useEditorActions(),m=s.useEditorStore(F=>F.card.type),h=t==null?void 0:t.id,f=I.useCallback(F=>{if(!(t!=null&&t.config))return[];switch(F){case"groupBy":return(t.config.groupByColumns||[]).map(T=>({id:T.id,name:T.name,dataType:T.dataType,label:T.label!==void 0?T.label:T.name,qualifiedEntityName:T.qualifiedEntityName,entityId:T.entityId,entityName:T.entityName,entityType:T.entityType,dateFormat:T.dateFormat,customFormat:T.customFormat,granularity:T.granularity}));case"metrics":return t.config.metricColumns||[];case"pivotBy":return(t.config.pivotByColumns||[]).map(T=>({id:T.id,name:T.name,dataType:T.dataType,label:T.label!==void 0?T.label:T.name,qualifiedEntityName:T.qualifiedEntityName,entityId:T.entityId,entityName:T.entityName,entityType:T.entityType}));case"sortBy":return(t.config.sortByColumns||[]).map(T=>({id:T.id,name:T.name,dataType:T.dataType,label:T.label!==void 0?T.label:T.name,qualifiedEntityName:T.qualifiedEntityName,entityId:T.entityId,entityName:T.entityName,entityType:T.entityType,direction:T.direction}));case"source":return[];default:return[]}},[t]),g=I.useCallback((F,T)=>{if(h)switch(F){case"groupBy":{a(h,{groupByColumns:T});break}case"metrics":{a(h,{metricColumns:T});break}case"pivotBy":{a(h,{pivotByColumns:T});break}case"sortBy":{a(h,{sortByColumns:T});break}}},[h,a]),b=I.useCallback((F,T,E)=>{if(!h)return;const O=f(F)[T];if(O)switch(F){case"groupBy":n(h,O.id,{label:E});break;case"metrics":r(h,O.id,{label:E});break;case"pivotBy":l(h,O.id,{label:E});break;case"sortBy":o(h,O.id,{label:E});break}},[h,f,n,r,l,o]),p=I.useCallback((F,T)=>{if(!h)return;const A=f("metrics")[F];A&&r(h,A.id,{aggregate:T,label:s.getAggregationLabel(A.name,T)})},[h,f,r]),j=I.useCallback((F,T,E)=>{if(!h)return;const O=f("groupBy")[F];if(!O)return;const M={dateFormat:T};T==="custom"&&E?M.customFormat=E:M.customFormat=void 0,n(h,O.id,M)},[h,f,n]),x=I.useCallback((F,T)=>{if(!h)return;const A=f("groupBy")[F];A&&n(h,A.id,{granularity:T})},[h,f,n]),v=I.useCallback((F,T)=>{if(!h)return;const A=f("metrics")[F];A&&r(h,A.id,{aliasTemplate:T})},[h,f,r]),k=I.useCallback((F,T)=>{if(console.log("handleValueAliasesChange",F,T),!h)return;console.log("handleValueAliasesChange",F,T);const A=f("metrics")[F];A&&(console.log("handleValueAliasesChange",T),r(h,A.id,{valueAliases:T}))},[h,f,r]),L=I.useCallback(F=>{h&&a(h,{comparisonType:F})},[h,a]),C=I.useCallback(F=>{h&&a(h,{showTrendline:F})},[h,a]),S=I.useCallback(F=>{h&&a(h,{trendlineWindow:F})},[h,a]),y=I.useCallback(F=>{h&&a(h,{trendlineGranularity:F})},[h,a]),D=I.useCallback(F=>{h&&a(h,{targetValue:F})},[h,a]),N=I.useCallback(F=>{var P;if(!h)return;const T=[...f("groupBy"),...f("pivotBy"),...f("metrics"),...f("sortBy")],E=(P=t==null?void 0:t.config)==null?void 0:P.joinPlan,A=s.validateEntityConsistency(F,T,E);if(!A.isValid){A.showError&&s.showJoinRequiredNotification();return}const O=s.getSmartContainerForField(F,T),M=f(O);if(s.fieldAlreadyExists(F,M))return;const R=s.getNewField(F,O,M);R&&g(O,[...M,R])},[h,(w=t==null?void 0:t.config)==null?void 0:w.joinPlan,f,g]),B=I.useCallback((F,T)=>{if(!h)return;const A=f(F)[T];if(A){if(F!=="sortBy"){const O=f("sortBy"),M=O.filter(R=>!(R.name===A.name&&R.qualifiedEntityName===A.qualifiedEntityName));M.length!==O.length&&a(h,{sortByColumns:M})}switch(F){case"groupBy":c(h,A.id);break;case"metrics":i(h,A.id);break;case"pivotBy":d(h,A.id);break;case"sortBy":u(h,A.id);break}}},[h,f,c,i,d,u,a]);return{getFieldsForContainer:f,setFieldsForContainer:g,updateLabel:b,handleAggregationChange:p,handleDateFormatChange:j,handleGranularityChange:x,handleAliasTemplateChange:v,handleValueAliasesChange:k,removeField:B,handleFieldClick:N,handleKpiComparisonTypeChange:L,handleKpiShowTrendlineChange:C,handleKpiTrendlineWindowChange:S,handleKpiTrendlineGranularityChange:y,handleKpiTargetValueChange:D,cardType:m}};function al({field:t}){return e.jsxs("div",{className:"w-64 bg-background p-0",children:[e.jsxs("div",{className:"mb-2 flex items-start justify-between gap-2",children:[e.jsx("h3",{className:"text-sm font-medium text-foreground",children:t.label||t.name}),e.jsx("span",{className:"rounded bg-muted px-2 py-0.5 font-mono text-xs text-muted-foreground",children:t.dataType})]}),t.description&&e.jsx("p",{className:"mb-3 text-xs text-muted-foreground",children:t.description}),e.jsx("div",{className:"overflow-x-auto border-t border-border pb-2 pt-2",children:e.jsx("span",{className:"font-mono text-xs text-muted-foreground",children:t.name})})]})}function nl({field:t}){const{attributes:a,listeners:n,setNodeRef:r,transform:l,transition:o,isDragging:c}=s.useSortable({id:t.id}),[i,d]=I.useState(!1),u=s.useEditorStore(b=>b.card),{handleFieldClick:m}=Is(u),h={transform:s.CSS.Transform.toString(l),transition:o};s.getDataType(t.dataType);const f=b=>{const p=(b||"").toLowerCase();switch(s.getDataType(p)){case"number":return Ne;case"date":return s.Calendar;case"boolean":return Me;case"json":return Oe;case"geo":return _e;default:return ge}},g=b=>{const p=(b||"").toLowerCase(),j=s.getDataType(p);return j==="string"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(ge,{className:"h-3 w-3"})}):j==="number"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(Ne,{className:"h-3 w-3"})}):j==="date"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):j==="boolean"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Me,{className:"h-3 w-3"})}):j==="json"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Oe,{className:"h-3 w-3"})}):j==="geo"?e.jsx("div",{className:"bg-orange -100 flex size-6 shrink-0 items-center justify-center rounded-sm text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(_e,{className:"h-3 w-3"})}):j==="calculated"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(qe,{className:"h-3 w-3"})}):null};return f(t.dataType),e.jsxs("div",{ref:r,style:h,...a,...n,className:`group/container overflow-hidden rounded-lg transition-all ${c?"scale-95 opacity-50":"border border-transparent hover:bg-muted"}`,children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3 p-2",onClick:()=>m(t),children:[g(t.dataType),e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:e.jsx("span",{className:`block text-sm text-foreground/80 hover:text-foreground dark:text-muted-foreground ${i?"whitespace-normal break-words":"truncate"}`,children:t.label||t.name})})}),e.jsx(s.TooltipContent,{side:"bottom",align:"start",className:"ml-5 max-w-xs px-4 pb-2 pt-4",children:e.jsx(al,{field:t})})]})})]}),i&&e.jsx("div",{className:"text-muted-foreground-700 px-2 pb-3 text-sm",children:e.jsx(s.Card,{className:"",children:e.jsxs(s.CardContent,{className:"space-y-2 p-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(at,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"break-all",children:t.label||t.name})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ha,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"break-all",children:t.name})]}),e.jsx(s.Badge,{variant:"outline",className:"mt-2 text-xs",children:t.dataType})]})})})]})}function rl(){const[t,a]=I.useState(""),[n,r]=I.useState("all"),l=s.useEditorStore(k=>k.card.dataSource),{columns:o=[],columnGroups:c=[],isLoading:i,error:d}=s.useColumns(),u=o.filter(k=>k.name.toLowerCase().includes(t.toLowerCase())||k.dataType.toLowerCase().includes(t.toLowerCase())||k.qualifiedEntityName&&k.qualifiedEntityName.toLowerCase().includes(t.toLowerCase())),m=k=>{if(k.dataType==="number"||k.dataType==="integer"||k.dataType==="float"||k.dataType==="decimal"||k.dataType==="currency")return"metrics";const L=s.getDataType(k.dataType);return["date","string","boolean"].includes(L)?"dimensions":L==="number"?"metrics":"dimensions"},f=(n==="all"?u:u.filter(k=>m(k)===n)).reduce((k,L)=>{const C=L.qualifiedEntityName||"Other Fields";return k[C]||(k[C]={label:s.toLabel(L.entityName),fields:[]}),k[C].fields.push(L),k},{}),b=Object.keys(f),p=u.filter(k=>m(k)==="dimensions").length,j=u.filter(k=>m(k)==="metrics").length,x=u.filter(k=>m(k)==="calculated").length,v=u.length>0;return i?e.jsx("div",{className:"flex h-[calc(100vh-200px)] w-[290px] flex-col items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):d?e.jsxs("div",{className:"flex h-[calc(100vh-200px)] w-[290px] flex-col items-center justify-center",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-red-300"}),e.jsx("p",{className:"mb-2 text-sm text-red-500",children:"Error loading fields"}),e.jsx("p",{className:"px-4 text-center text-xs text-red-400",children:d.message||"Failed to load column data"})]}):!l||!l.selectedEntities||l.selectedEntities.length===0?e.jsx(s.ScrollArea,{className:"h-[calc(100vh-200px)] w-[290px]",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-gray-300"}),e.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),e.jsx("p",{className:"px-4 text-xs text-gray-400",children:"Select a table, view, or dataset from the data source panel to see available fields"})]})}):e.jsxs("div",{className:"mt-2 flex h-[calc(100vh-200px)] w-full grow flex-col gap-2 px-6 pb-6",children:[e.jsxs("div",{className:"mt-1 flex-shrink-0 space-y-2",children:[o.length>0&&e.jsxs("div",{className:"relative mb-4",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 transform text-muted-foreground"}),e.jsx(s.Input$1,{className:"pl-10",type:"text",placeholder:"Search fields...",value:t,onChange:k=>a(k.target.value)})]}),v&&e.jsx(s.Tabs,{defaultValue:"all",value:n,onValueChange:k=>r(k),className:"mb-4",children:e.jsxs(s.TabsList,{className:"grid h-9 w-full grid-cols-4",children:[e.jsxs(s.TabsTrigger,{value:"all",className:"text-xs",children:["All",e.jsx("span",{className:"ml-2 text-xs font-semibold",children:u.length})]}),e.jsxs(s.TabsTrigger,{value:"dimensions",className:"text-xs",children:[e.jsx(s.Layers,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:p})]}),e.jsxs(s.TabsTrigger,{value:"metrics",className:"text-xs",children:[e.jsx(s.ChartColumn,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:j})]}),e.jsxs(s.TabsTrigger,{value:"calculated",className:"text-xs",children:[e.jsx(qe,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:x})]})]})})]}),e.jsxs(s.CustomScrollArea,{className:"py-2",children:[e.jsx(s.Accordion,{type:"multiple",defaultValue:b,className:"space-y-2",children:Object.entries(f).map(([k,L])=>{const C=c.find(S=>S.entityName===k)||{entityName:k,label:L.label};return e.jsxs(s.AccordionItem,{value:k,className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:e.jsxs("div",{title:C.label||C.entityName,className:"flex items-center gap-2",children:[e.jsx("span",{className:"max-w-[190px] truncate text-ellipsis whitespace-nowrap text-sm font-medium text-primary",children:C.label||C.entityName}),e.jsx(s.Badge,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:L.fields.length})]})}),e.jsx(s.AccordionContent,{className:"pb-2",children:e.jsx("div",{className:"space-y-1",children:L.fields.map(S=>e.jsx(nl,{field:S},S.id))})})]},k)})}),Object.keys(f).length===0&&o.length===0&&e.jsxs("div",{className:"py-8 text-center text-sm text-gray-500",children:[e.jsx("p",{children:"No fields found for selected data source"}),e.jsx("p",{className:"mt-1 text-xs text-gray-400",children:"Try selecting different data sources"})]}),Object.keys(f).length===0&&o.length>0&&e.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"No fields found for this category"}),e.jsx(s.ScrollBar,{orientation:"horizontal"}),e.jsx(s.ScrollBar,{orientation:"vertical"})]})]})}function ll(){return e.jsxs("div",{className:" h-full flex flex-col items-center",children:[" ",e.jsx(rl,{})," "]})}function ol({initialJoinPlan:t,availableDataSources:a}){const[n,r]=I.useState(t),[l,o]=I.useState(new Set),c=()=>{const S=n.joins.length>0?Math.max(...n.joins.map(D=>D.sequence))+1:1,y={id:`join-${Date.now()}`,source:{type:"table",name:"",database:"",schema:""},target:{type:"table",name:"",database:"",schema:""},joinType:"INNER",sequence:S,joinKeyGroups:[{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}]};r({...n,joins:[...n.joins,y]}),o(new Set([...l,y.id]))},i=S=>{r({...n,joins:n.joins.filter(y=>y.id!==S)}),o(new Set([...l].filter(y=>y!==S)))},d=(S,y)=>{var w,F;const D=n.joins.find(T=>T.id===S);if(!D)return;const N={...D,...y},B=n.joins.map(T=>T.id===S?N:T);if((w=N.source)!=null&&w.name&&((F=N.target)!=null&&F.name)&&N.joinKeyGroups[0].keys.length===0){const T=a.find(M=>{var R;return M.name===((R=N.source)==null?void 0:R.name)}),E=a.find(M=>{var R;return M.name===((R=N.target)==null?void 0:R.name)}),A={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(T==null?void 0:T.name)||"",entityName:(T==null?void 0:T.name)||"",entityType:(T==null?void 0:T.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(E==null?void 0:E.name)||"",entityName:(E==null?void 0:E.name)||"",entityType:(E==null?void 0:E.type)||"table"},operator:"="},O=[...N.joinKeyGroups];O[0]={...O[0],keys:[A]},N.joinKeyGroups=O,B[B.findIndex(M=>M.id===S)]=N}r({...n,joins:B})};return{joinPlan:n,expandedJoins:l,setJoinPlan:r,addJoin:c,removeJoin:i,updateJoin:d,moveJoinUp:S=>{const y=n.joins.findIndex(D=>D.id===S);if(y>0){const D=[...n.joins],N={...D[y]},B={...D[y-1]};D[y]=B,D[y-1]=N,D.forEach((F,T)=>{F.sequence=T+1});const w={...n,joins:D};r(w)}},moveJoinDown:S=>{const y=n.joins.findIndex(D=>D.id===S);if(y<n.joins.length-1){const D=[...n.joins],N={...D[y]},B={...D[y+1]};D[y]=B,D[y+1]=N,D.forEach((F,T)=>{F.sequence=T+1});const w={...n,joins:D};r(w)}},toggleJoinExpansion:S=>{const y=new Set(l);y.has(S)?y.delete(S):y.add(S),o(y)},getAvailableSourceEntities:S=>{if(n.joins.length===0)return a;const y=n.joins.findIndex(N=>N.id===S);if(y===0)return a;const D=new Set;return n.baseEntity.name&&D.add(n.baseEntity.name),n.joins.slice(0,y).forEach(N=>{D.add(N.source.name),D.add(N.target.name)}),a.filter(N=>D.has(N.name))},getAvailableTargetEntities:S=>a.filter(y=>y.name!==S),addJoinKeyGroup:S=>{const y=n.joins.find(N=>N.id===S);if(!y)return;const D=[...y.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];d(S,{joinKeyGroups:D})},updateGroupOperator:(S,y,D)=>{const N=n.joins.find(w=>w.id===S);if(!N)return;const B=[...N.joinKeyGroups];B[y]={...B[y],operator:D},d(S,{joinKeyGroups:B})},removeJoinKeyGroup:(S,y)=>{const D=n.joins.find(B=>B.id===S);if(!D)return;const N=[...D.joinKeyGroups];N.splice(y,1),d(S,{joinKeyGroups:N})},addJoinKey:(S,y)=>{const D=n.joins.find(T=>T.id===S);if(!D)return;const N=a.find(T=>T.name===D.source.name),B=a.find(T=>T.name===D.target.name),w=[...D.joinKeyGroups],F={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(N==null?void 0:N.name)||"",entityName:(N==null?void 0:N.name)||"",entityType:(N==null?void 0:N.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(B==null?void 0:B.name)||"",entityName:(B==null?void 0:B.name)||"",entityType:(B==null?void 0:B.type)||"table"},operator:"="};w[y]={...w[y],keys:[...w[y].keys,F]},d(S,{joinKeyGroups:w})},updateJoinKey:(S,y,D,N,B)=>{const w=n.joins.find(O=>O.id===S);if(!w)return;const F=a.find(O=>O.name===w.source.name),T=a.find(O=>O.name===w.target.name),E=[...w.joinKeyGroups],A=E[y].keys[D];N==="sourceColumnName"&&F?E[y].keys[D]={...A,source:{...A.source,name:B}}:N==="targetColumnName"&&T?E[y].keys[D]={...A,target:{...A.target,name:B}}:N==="operator"&&(E[y].keys[D]={...A,operator:B}),d(S,{joinKeyGroups:E})},removeJoinKey:(S,y,D)=>{const N=n.joins.find(w=>w.id===S);if(!N)return;const B=[...N.joinKeyGroups];B[y].keys.splice(D,1),d(S,{joinKeyGroups:B})},generateSQLPreview:()=>{const S=[...n.joins].sort((N,B)=>N.sequence-B.sequence),y=n.baseEntity;if(!y.name)return"SELECT * FROM table -- Please select a base entity";let D=`SELECT *
|
|
349
|
+
FROM ${y.name}`;return S.forEach(N=>{const B=a.find(T=>T.name===N.target.name);if(!B)return;const w=N.joinKeyGroups.filter(T=>T.keys&&T.keys.length>0).map(T=>{const E=T.keys.filter(A=>{var O,M,R,P;return((O=A.source)==null?void 0:O.name)&&((M=A.target)==null?void 0:M.name)&&((R=A.source)==null?void 0:R.entityName)&&((P=A.target)==null?void 0:P.entityName)}).map(A=>`${A.source.entityName}.${A.source.name} ${A.operator} ${A.target.entityName}.${A.target.name}`);return E.length>1?`(${E.join(` ${T.operator} `)})`:E[0]}).filter(Boolean),F=w.length>1?w.join(" OR "):w[0]||"condition_here";D+=`
|
|
350
|
+
${N.joinType} JOIN ${B.name}
|
|
351
|
+
ON ${F}`}),D},isValidConfiguration:()=>!(!n.baseEntity.name||n.joins.some(N=>!N.source.name||!N.target.name)||n.joins.some(N=>N.joinKeyGroups.some(B=>B.keys.length===0))||n.joins.some(N=>N.joinKeyGroups.some(B=>B.keys.some(w=>!w.source.name||!w.target.name||!w.operator))))}}function il({joinPlan:t,availableDataSources:a,onSave:n,onRemove:r,onCancel:l}){const{setCardConfig:o}=s.useEditorActions();s.useEditorStore(w=>w.card.config);const{columnGroups:c}=s.useColumns(),{joinPlan:i,expandedJoins:d,setJoinPlan:u,addJoin:m,removeJoin:h,updateJoin:f,moveJoinUp:g,moveJoinDown:b,toggleJoinExpansion:p,getAvailableSourceEntities:j,getAvailableTargetEntities:x,addJoinKeyGroup:v,updateGroupOperator:k,removeJoinKeyGroup:L,addJoinKey:C,updateJoinKey:S,removeJoinKey:y,generateSQLPreview:D,isValidConfiguration:N}=ol({initialJoinPlan:t,availableDataSources:a}),B=w=>{const F=c.find(T=>T.entityName===w);return(F==null?void 0:F.columns)||[]};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Base Entity (FROM clause)"}),e.jsxs(s.Select,{value:i.baseEntity.name,onValueChange:w=>{const F=a.find(T=>T.name===w);u({...i,baseEntity:{connectionId:(F==null?void 0:F.connectionId)||"",connectionType:(F==null?void 0:F.connectionType)||"none",type:(F==null?void 0:F.type)||"table",name:w,database:F==null?void 0:F.database,schema:F==null?void 0:F.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select base entity..."})}),e.jsx(s.SelectContent,{children:a.map(w=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:w.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:w.type}),w.name,e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]})},w.name))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This entity will be used as the base table in the FROM clause of the SQL query."})]}),e.jsxs("div",{className:"rounded-md border p-3",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"Join SQL Preview"}),e.jsx("code",{className:"block whitespace-pre-wrap break-all text-xs",children:D()})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{children:["Joins Configuration (",i.joins.length,")"]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:m,children:[e.jsx(s.Plus,{className:"mr-1 h-4 w-4"}),"Add Join"]})})]}),i.joins.length===0?e.jsx("div",{className:"rounded-lg border border-dashed py-8 text-center text-muted-foreground",children:e.jsx("p",{children:"No joins configured. Add a join to connect multiple data sources."})}):e.jsx("div",{className:"max-h-[300px] space-y-4 overflow-y-auto",children:i.joins.map(w=>{const F=a.find(A=>A.name===w.source.name),T=a.find(A=>A.name===w.target.name),E=d.has(w.id);return e.jsxs(s.Card,{className:"border",children:[e.jsx(s.CardHeader,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{children:w.sequence}),e.jsxs(s.CardTitle,{className:"text-sm",children:["Join ",w.sequence,F&&T&&e.jsxs("span",{className:"ml-2 font-normal text-gray-600",children:["(",F.name," → ",T.name,")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>g(w.id),disabled:w.sequence===1,children:e.jsx(s.ArrowUp,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>b(w.id),disabled:w.sequence===i.joins.length,children:e.jsx(s.ArrowDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>p(w.id),children:E?e.jsx(s.ChevronUp,{className:"h-4 w-4"}):e.jsx(s.ChevronDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>h(w.id),children:e.jsx(s.X,{className:"h-4 w-4"})})]})]})}),E&&e.jsxs(s.CardContent,{className:"space-y-4 pb-6",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Source"}),e.jsxs(s.Select,{value:w.source.name,onValueChange:A=>{const O=a.find(M=>M.name===A);f(w.id,{source:{connectionId:(O==null?void 0:O.connectionId)||"",connectionType:(O==null?void 0:O.connectionType)||"none",type:(O==null?void 0:O.type)||"table",name:A,database:O==null?void 0:O.database,schema:O==null?void 0:O.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select source..."})}),e.jsx(s.SelectContent,{children:j(w.id).map(A=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:A.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:A.type}),A.name]})},A.name))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Join Type"}),e.jsxs(s.Select,{value:w.joinType,onValueChange:A=>f(w.id,{joinType:A}),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"INNER",children:"INNER JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"LEFT",children:"LEFT JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"RIGHT",children:"RIGHT JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"FULL",children:"FULL JOIN"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Target"}),e.jsxs(s.Select,{value:w.target.name,onValueChange:A=>{const O=a.find(M=>M.name===A);f(w.id,{target:{connectionId:(O==null?void 0:O.connectionId)||"",connectionType:(O==null?void 0:O.connectionType)||"none",type:(O==null?void 0:O.type)||"table",name:A,database:O==null?void 0:O.database,schema:O==null?void 0:O.schema}})},disabled:!w.source.name,children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select target..."})}),e.jsx(s.SelectContent,{children:w.source.name?x(w.source.name).map(A=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:A.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:A.type}),A.name,A.name===w.source.name&&e.jsx(s.Badge,{variant:"outline",className:"text-xs text-yellow-600",children:"(Self-join)"})]})},A.name)):[]})]})]})]}),w.source.name&&w.target.name&&F&&T&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{children:"Join Conditions"}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>v(w.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition Group"]})]}),w.joinKeyGroups.length===0?e.jsx("div",{className:"rounded-md border p-3 text-center text-sm text-gray-500",children:"No join conditions defined. Add condition groups to specify how data sources should be joined."}):e.jsx("div",{className:"space-y-4",children:w.joinKeyGroups.map((A,O)=>e.jsxs("div",{className:"space-y-3 rounded-md border p-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Label,{children:["Group ",O+1]}),O>0&&e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-gray-100 px-2 py-1",children:[e.jsx(s.Label,{className:"text-xs font-normal",children:"Join with:"}),e.jsx("span",{className:"text-sm font-medium",children:"OR"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Select,{value:A.operator,onValueChange:M=>k(w.id,O,M),children:[e.jsx(s.SelectTrigger,{className:"w-[100px]",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(s.SelectItem,{value:"OR",children:"OR"})]})]}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",onClick:()=>L(w.id,O),children:e.jsx(s.Trash2,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[A.keys.length===0?e.jsx("div",{className:"rounded-md border border-dashed p-3 text-center text-sm text-gray-500",children:"No conditions in this group. Add conditions to specify join criteria."}):e.jsx("div",{className:"space-y-2",children:A.keys.map((M,R)=>e.jsxs("div",{className:"flex flex-col items-start gap-2 rounded-md border p-2 sm:flex-row sm:items-center",children:[R>0&&e.jsx("div",{className:"self-center rounded-md bg-gray-100 px-2 py-1 text-xs font-medium",children:A.operator}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:M.source.name,onValueChange:P=>S(w.id,O,R,"sourceColumnName",P),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Source column"})}),e.jsx(s.SelectContent,{children:B(w.source.name).map(P=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:P.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:P.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:P.dataType})]})},P.name))})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:w-20",children:e.jsxs(s.Select,{value:M.operator,onValueChange:P=>S(w.id,O,R,"operator",P),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"=",children:"="}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"<",children:"<"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:">",children:">"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"<=",children:"<="}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:">=",children:">="})]})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:M.target.name,onValueChange:P=>S(w.id,O,R,"targetColumnName",P),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Target column"})}),e.jsx(s.SelectContent,{children:B(w.target.name).map(P=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:P.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between hover:bg-muted",children:[e.jsx("span",{children:P.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:P.dataType})]})},P.name))})]})}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"self-center",onClick:()=>y(w.id,O,R),children:e.jsx(s.X,{className:"size-3.5"})})]},M.id||R))}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>C(w.id,O),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition"]})]})]},A.id))})]})]})]},w.id)})})]}),e.jsxs("div",{className:"flex justify-end gap-2 border-t pt-4",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>{r(),l()},children:"Remove All"}),e.jsx(s.Button,{variant:"outline",onClick:l,children:"Cancel"}),e.jsx(s.Button,{onClick:()=>n(i),disabled:!N(),children:"Save"})]})]})}function Ws({children:t,open:a,onOpenChange:n,joinPlan:r,availableDataSources:l,onRemove:o,onSave:c,onCancel:i}){return e.jsxs(s.Dialog,{open:a,onOpenChange:n,children:[e.jsxs(s.DialogContent,{className:"max-w-4xl",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Join Configuration"}),e.jsx(s.DialogDescription,{children:"Configure the join between the two entities to combine the fields."})]}),e.jsx(il,{joinPlan:r,availableDataSources:l,onSave:c,onCancel:i,onRemove:o})]}),t]})}function cl({joins:t,baseEntityId:a,availableDataSources:n,generateSQLPreview:r}){return e.jsxs("div",{className:"divide-y divide-border",children:[t.length>0&&e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left font-semibold",children:"Join Chain"}),e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:(()=>{const l=[...t].sort((c,i)=>c.sequence-i.sequence),o=n.find(c=>c.name===a);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(s.Badge,{variant:"secondary",className:"text-xs",children:o==null?void 0:o.type}),e.jsx("span",{className:"text-xs font-medium",children:o==null?void 0:o.name}),e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]}),l.map(c=>{const i=n.find(d=>d.name===c.target.name);return e.jsxs("div",{className:"flex items-center",children:[e.jsxs("div",{className:"mx-1 flex items-center gap-1",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:c.joinType}),e.jsx("span",{className:"text-muted-foreground",children:"→"})]}),e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(s.Badge,{variant:"secondary",className:"text-xs",children:i==null?void 0:i.type}),e.jsx("span",{className:"text-xs font-medium",children:i==null?void 0:i.name})]})]},c.id)})]})})()})]}),e.jsxs("div",{className:"p-4",children:[e.jsxs("h3",{className:"mb-3 text-left text-sm font-medium",children:["Configured Joins (",t.length,")"]}),e.jsx("div",{className:"space-y-2",children:[...t].sort((l,o)=>l.sequence-o.sequence).map((l,o)=>{const c=n.find(d=>d.name===l.source.name),i=n.find(d=>d.name===l.target.name);return e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-muted p-2 text-left",children:[e.jsx(s.Badge,{variant:"secondary",className:"shrink-0 text-xs",children:o+1}),e.jsx(s.Badge,{variant:"outline",className:"shrink-0 text-xs",children:l.joinType}),e.jsxs("span",{className:"text-xs font-medium",children:[c==null?void 0:c.name," → ",i==null?void 0:i.name]}),e.jsxs(s.Badge,{variant:"outline",className:"ml-auto text-xs",children:[l.joinKeyGroups.reduce((d,u)=>d+u.keys.length,0)," ","condition",l.joinKeyGroups.reduce((d,u)=>d+u.keys.length,0)>1?"s":""]})]},l.id)})})]}),e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left text-sm font-medium",children:"SQL Query"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap break-all text-left font-mono text-xs text-muted-foreground",children:r()})})]})]})}function dl(){var m,h;const t=s.useEditorStore(f=>f.card),a=s.useEditorStore(f=>f.actions.updateCardConfig),n=((m=t==null?void 0:t.config)==null?void 0:m.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[r,l]=I.useState(!1),o=((h=t==null?void 0:t.dataSource)==null?void 0:h.selectedEntities)||[],c=f=>{a(t.id,{...t==null?void 0:t.config,joinPlan:f}),l(!1)},i=()=>{a(t.id,{...t==null?void 0:t.config,joinPlan:void 0})},d=()=>{l(!1)},u=()=>{const f=[...n.joins].sort((p,j)=>p.sequence-j.sequence),g=n.baseEntity;if(!g.name)return"SELECT * FROM table -- Please select a base entity";let b=`SELECT *
|
|
352
|
+
FROM ${g.name}`;return f.forEach(p=>{const j=o.find(k=>k.name===p.target.name);if(!j)return;const x=p.joinKeyGroups.filter(k=>k.keys&&k.keys.length>0).map(k=>{const L=k.keys.filter(C=>{var S,y,D,N;return((S=C.source)==null?void 0:S.name)&&((y=C.target)==null?void 0:y.name)&&((D=C.source)==null?void 0:D.entityName)&&((N=C.target)==null?void 0:N.entityName)}).map(C=>`${C.source.entityName}.${C.source.name} ${C.operator} ${C.target.entityName}.${C.target.name}`);return L.length>1?`(${L.join(` ${k.operator} `)})`:L[0]}).filter(Boolean),v=x.length>1?x.join(" OR "):x[0]||"condition_here";b+=`
|
|
358
353
|
${p.joinType} JOIN ${j.name}
|
|
359
|
-
ON ${v}`}),b};return o.length<2?null:e.jsx(e.Fragment,{children:e.jsx("div",{className:"space-y-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[n.joins.length>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-6 text-xs font-semibold",onClick:()=>l(!0),children:[e.jsx(s.Link,{className:s.cn("mr-1 h-3 w-3",{"text-blue-500":n.joins.length>0,"text-gray-500":n.joins.length===0})}),"Join",n.joins.length>1?"s":""," (",n.joins.length,")"]})}),e.jsx(s.TooltipContent,{side:"right",className:"max-w-md overflow-hidden p-0",children:e.jsx(dl,{joins:n.joins,baseEntityId:n.baseEntity.name,availableDataSources:o,generateSQLPreview:u})})]})}),e.jsx(Ws,{open:r,onOpenChange:l,joinPlan:n,availableDataSources:o,onSave:c,onCancel:d,onRemove:i,children:e.jsx("div",{})})]}),n.joins.length===0&&e.jsx(Ws,{open:r,onOpenChange:l,joinPlan:n,availableDataSources:o,onSave:c,onCancel:d,onRemove:i,children:e.jsxs(s.Button,{onClick:()=>l(!0),variant:"outline",size:"sm",className:"w-full",children:[e.jsx(s.Link,{className:"mr-3 size-4"}),"Configure Joins"]})})]})})})}function ml({open:t,onOpenChange:a}){const[n,r]=A.useState([]),{updateDataSource:l}=s.useEditorActions(),o=s.useDashboardStore(p=>p.dashboard.aiContext),c=(o==null?void 0:o.selectedEntities)||[];A.useEffect(()=>{t&&r([])},[t]);const i=p=>{r(j=>j.some(v=>v.name===p.name&&v.type===p.type)?j.filter(v=>!(v.name===p.name&&v.type===p.type)):[...j,p])},d=()=>{r([...c])},u=()=>{r([])},m=()=>{if(n.length===0)return;const p=n[0],j=p.connectionId||"",x=p.connectionType||"",k=n.some(N=>N.type==="dataset")?"semanticDomain":"database";l({connectionId:j,connectionType:x,mode:k,selectedEntities:n}),a(!1)},h=p=>{switch(p.type){case"table":return e.jsx(s.Table,{className:"h-4 w-4"});case"view":return e.jsx(Ka,{className:"h-4 w-4"});case"model":return e.jsx(fa,{className:"h-4 w-4"});case"dataset":return e.jsx(s.Database,{className:"h-4 w-4"});case"file":case"url":case"upload":return e.jsx(s.FileText,{className:"h-4 w-4"});default:return e.jsx(s.Database,{className:"h-4 w-4"})}},f=p=>"label"in p&&p.label?p.label:p.name,g=p=>{if("description"in p&&p.description)return p.description;const j=[];return p.database&&j.push(p.database),p.schema&&j.push(p.schema),p.name&&j.push(p.name),j.join(".")},b=p=>n.some(j=>j.name===p.name&&j.type===p.type);return c.length===0?e.jsx(s.Dialog,{open:t,onOpenChange:a,children:e.jsxs(s.DialogContent,{className:"max-w-md",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"No Data Available"}),e.jsx(s.DialogDescription,{children:"No entities are currently available in the AI context. Please add some data sources to the dashboard first."})]}),e.jsx(s.DialogFooter,{children:e.jsx(s.Button,{onClick:()=>a(!1),children:"Close"})})]})}):e.jsx(s.Dialog,{open:t,onOpenChange:a,children:e.jsxs(s.DialogContent,{className:"flex max-w-2xl flex-col",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Select Data to Analyze"}),e.jsx(s.DialogDescription,{children:"Choose entities from the dashboard's context"})]}),e.jsxs("div",{className:"flex-1 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"outline",size:"sm",onClick:d,disabled:n.length===c.length,children:"Select All"}),e.jsx(s.Button,{variant:"outline",size:"sm",onClick:u,disabled:n.length===0,children:"Clear All"})]}),e.jsxs(s.Badge,{variant:"secondary",children:[n.length," of ",c.length," selected"]})]}),e.jsx(s.Separator,{}),e.jsx(s.ScrollArea,{className:"h-64",children:e.jsx("div",{className:"space-y-2",children:c.map((p,j)=>e.jsxs("div",{className:s.cn("flex items-center gap-3 rounded-lg border p-3 transition-colors hover:bg-muted/50",b(p)&&"border-primary bg-primary/5"),children:[e.jsx(s.Checkbox,{checked:b(p),onCheckedChange:()=>i(p)}),e.jsx("div",{className:"flex items-center gap-2 text-muted-foreground",children:h(p)}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate font-medium",children:f(p)}),e.jsx("div",{className:"truncate text-sm text-muted-foreground",children:g(p)})]}),e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:p.type})]},`${p.type}-${p.name}-${j}`))})})]}),e.jsx(s.DialogFooter,{children:e.jsx("div",{className:"flex w-full justify-between",children:e.jsxs("div",{className:"flex grow justify-end gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsxs(s.Button,{onClick:m,disabled:n.length===0,children:["Select"," ",n.length>0?`(${n.length})`:""]})]})})})]})})}function hl({entity:t,title:a,maxDetails:n=10}){const l=s.getEntityDetails(t).slice(0,n),o=l.find(i=>i.label==="Description"),c=l.filter(i=>i.label==="Description"?!1:!["Connection","Database","Schema"].includes(i.label));return e.jsx(s.TooltipContent,{side:"top",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-sm font-medium",children:a||s.getDisplayName(t)}),o&&e.jsxs("div",{className:"border-t border-border pt-2",children:[e.jsx("div",{className:"mb-1 text-xs text-muted-foreground",children:"Description:"}),e.jsx("div",{className:"text-xs leading-relaxed",children:o.value})]}),c.length>0&&e.jsx("div",{className:"space-y-0.5",children:c.map((i,d)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[i.label,":"]}),e.jsx("span",{className:"font-mono",children:i.value})]},d))})]})})}function xl({entities:t}){return e.jsx(s.TooltipContent,{side:"top",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"text-sm font-medium",children:[t.length," more entities"]}),e.jsx("div",{className:"space-y-1",children:t.map((a,n)=>{const r=s.getEntityDetails(a),l=r.find(c=>c.label==="Description"),o=r.filter(c=>c.label==="Description"?!1:!["Connection","Database","Schema"].includes(c.label)).slice(0,3);return e.jsxs("div",{className:"border-b border-border pb-1 last:border-b-0",children:[e.jsx("div",{className:"text-xs font-medium",children:s.getDisplayName(a)}),l&&e.jsxs("div",{className:"mb-1 mt-1",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Description:"}),e.jsx("div",{className:"text-xs leading-relaxed",children:l.value})]}),o.length>0&&e.jsx("div",{className:"mt-1 space-y-0.5",children:o.map((c,i)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[c.label,":"]}),e.jsx("span",{className:"font-mono",children:c.value})]},i))})]},`remaining-${a.type}-${a.name}-${n}`)})})]})})}function pl({isVisible:t,onToggleVisibility:a}){const[n,r]=A.useState(!1),[l,o]=A.useState(!1),[c,i]=A.useState(!0),d=s.useEditorStore(f=>f.card.dataSource);s.useCurrentUserInfo();const{updateDataSource:u}=s.useEditorActions(),m={connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},h={...m,...d,selectedEntities:(d==null?void 0:d.selectedEntities)||[]};return e.jsxs("div",{className:s.cn("flex flex-col overflow-hidden bg-background transition-all duration-300 ease-in-out",{"w-[325px]":t,"w-0":!t}),children:[e.jsxs("div",{children:[e.jsx("div",{className:s.cn("p-4 px-6",{"pb-0":!c}),children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsxs("div",{className:"flex cursor-pointer items-center gap-2",children:[e.jsx("h2",{className:"text-brand-100 font-semibold",children:"Data Source"}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>i(!c),className:"h-6 w-6 p-0",children:c?e.jsx(s.ChevronDown,{className:"h-4 w-4"}):e.jsx(s.ChevronRight,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",onClick:a,title:"Hide Data Source Panel",children:e.jsx(s.EyeOff,{className:"h-3.5 w-3.5"})}),e.jsxs(s.Button,{size:"sm",variant:"outline",className:"h-7",onClick:()=>r(!0),children:[e.jsx(s.Plus,{className:"mr-1 h-3.5 w-3.5"}),"Add"]})]})]})}),e.jsxs("div",{className:`overflow-hidden px-6 ${c?"max-h-96 space-y-4":"max-h-0 py-0 opacity-0"}`,children:[h.selectedEntities.length>0&&e.jsx(s.TooltipProvider$1,{children:e.jsxs("div",{className:"flex flex-wrap gap-1",children:[h.selectedEntities.slice(0,3).map((f,g)=>e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Badge,{variant:"secondary",className:"group relative cursor-pointer pr-6 text-xs transition-colors hover:border-red-200 hover:bg-red-50 dark:hover:border-red-800 dark:hover:bg-red-950",children:[s.getDisplayName(f),e.jsx("button",{onClick:b=>{b.stopPropagation();const p=h.selectedEntities.filter(j=>!(j.name===f.name&&j.type===f.type));u({...m,...d,selectedEntities:p})},className:"absolute right-1 top-1/2 -translate-y-1/2 rounded-full p-0.5 hover:bg-red-100",children:e.jsx(s.X,{className:"h-2.5 w-2.5 group-hover:text-red-500"})})]})}),e.jsx(hl,{entity:f})]},`${f.type}-${f.name}-${g}`)),h.selectedEntities.length>3&&e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Badge,{variant:"outline",className:"text-xs",children:["+",h.selectedEntities.length-3," more"]})}),e.jsx(xl,{entities:h.selectedEntities.slice(3)})]})]})}),e.jsx(ul,{})]})]}),e.jsx(ol,{}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(d==null?void 0:d.selectedEntities)||[],dialogMode:"dataSource",open:n,onOpenChange:r,dataSource:h,fallbackDataSource:m}),e.jsx(ml,{open:l,onOpenChange:o})]})}const fl="chart-selector-standard-first";function gl(){const[t,a]=s.useLocalStorageState(fl,!0);return{standardFirst:t,updatePreference:a}}const Ks=({pluginVisual:t,index:a,onSelect:n})=>{const r=rs(t.icon||""),l=t.name.charAt(0).toUpperCase(),o=s.getAutoDetectedChartIcon(t.name);return e.jsx(s.CommandItem,{value:`${t.name} custom visual plugin component`,onSelect:n,className:"group flex items-center gap-2",children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[r?e.jsx(r,{className:"h-4 w-4"}):o||e.jsx("div",{className:"flex h-4 w-4 items-center justify-center rounded bg-muted text-xs font-medium",children:l}),e.jsx("span",{children:t.name})]}),e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{tabIndex:0,className:"opacity-0 outline-none transition-opacity group-hover:opacity-100",children:e.jsx(s.Info,{className:"ml-1 h-3.5 w-3.5 text-muted-foreground"})})}),e.jsx(s.TooltipContent,{side:"right",children:t.pluginName})]})]})},`${t.url}-${t.name}-${a}`)},Js=["default","standardPlugin","customPlugin"];function jl({selectedChart:t,onChartChange:a}){var R;const[n,r]=A.useState(!1),{data:l}=It();gl();const c=((R=s.useEditorStore(N=>N.card).customCardPreferences)==null?void 0:R.url)||"";Ns(c);const{setCardType:i,setCardPreferences:d,setIsDevMode:u}=s.useEditorStore(N=>N.actions),{setCardCustomCfg:m,setCustomCardPreferences:h,setQueryConfig:f}=s.useEditorActions(),[g,b]=s.useLocalStorageState("chart-section-active",null),p=A.useMemo(()=>g?[g,...Js.filter(N=>N!==g)]:Js,[g]);function j(N){m(null),d({}),i(N),["custom","map"].includes(N)&&(u(!0),f(void 0)),a(N),r(!1)}function x(N){m(null),d({}),i("custom"),h({type:"component",visualType:"single",url:N.url,componentName:N.name,icon:N.icon,pluginChartType:N.chartType}),f(void 0),a("custom"),r(!1)}const v=()=>{var w;if(t==="custom"){const y=s.useEditorStore.getState().card;return((w=y==null?void 0:y.customCardPreferences)==null?void 0:w.componentName)||"Custom Visual"}const N=s.chartTypes.find(y=>y.id===t);return(N==null?void 0:N.label)||"Select chart type"},k=()=>{var w,y;if(t==="custom"){const D=s.useEditorStore.getState().card,C=(w=D==null?void 0:D.customCardPreferences)==null?void 0:w.icon,I=(y=D==null?void 0:D.customCardPreferences)==null?void 0:y.componentName;if(C&&I)return e.jsx(bl,{icon:C,componentName:I});if(I){const S=s.getAutoDetectedChartIcon(I);if(S)return S}return e.jsx(Ue,{className:"h-4 w-4"})}const N=s.chartTypes.find(D=>D.id===t);if(N){const D=N.icon;return e.jsx(D,{className:"h-4 w-4"})}return e.jsx(Ue,{className:"h-4 w-4"})};return e.jsx("div",{className:"mb-6",children:e.jsxs(s.Popover,{open:n,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":n,className:"w-full justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[k(),e.jsx("span",{children:v()})]}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[300px] p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search chart types..."}),e.jsxs(s.CommandList,{className:"mb-2 max-h-[300px]",children:[e.jsx(s.CommandEmpty,{children:"No chart type found."}),p.map(N=>{if(N==="default")return e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"flex items-center gap-2",children:"Default Visuals"})}),e.jsx(s.TooltipContent,{side:"right",children:"These are the standard visuals available in Semaphor"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:g==="default",onCheckedChange:w=>b(w?"default":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:s.chartTypes.map(w=>{const y=w.icon;return e.jsx(s.CommandItem,{value:`${w.label} ${w.id} chart graph visualization`,onSelect:()=>j(w.id),className:"flex items-center gap-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(y,{className:"h-4 w-4"}),e.jsx("span",{children:w.label})]})},w.id)})},"default");if(N==="standardPlugin"){const w=l.filter(y=>y.pluginType==="standard");return w.length?e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsx("p",{children:"Standard Visuals"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:g==="standardPlugin",onCheckedChange:y=>b(y?"standardPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:w.filter(y=>y.componentType==="chart").map((y,D)=>e.jsx(Ks,{pluginVisual:y,index:D,onSelect:()=>x(y)},`${y.url}-${y.name}-${D}`))},"standardPlugin"):null}if(N==="customPlugin"){const w=l.filter(y=>y.pluginType==="custom");return w.length?e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs("span",{className:"flex items-center gap-2",children:["Custom Visuals",e.jsx(s.Info,{className:"h-3.5 w-3.5 text-muted-foreground"})]})}),e.jsx(s.TooltipContent,{side:"right",children:"External visuals that are specific to your project"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:g==="customPlugin",onCheckedChange:y=>b(y?"customPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:w.map((y,D)=>e.jsx(Ks,{pluginVisual:y,index:D,onSelect:()=>x(y)},`${y.url}-${y.name}-${D}`))},"customPlugin"):null}return null})]})]})})]})})}const bl=({icon:t,componentName:a})=>{const n=rs(),r=s.getAutoDetectedChartIcon(a);return n?e.jsx(n,{className:"h-4 w-4"}):r||e.jsx(Ue,{className:"h-4 w-4"})},yl=[{id:"table",icon:s.Table2,label:"Table"},{id:"bar",icon:s.ChartColumnIncreasing,label:"Bar Chart"},{id:"line",icon:s.ChartLine,label:"Line Chart"},{id:"stackedBar",icon:s.ChartColumnStacked,label:"Stacked Bar",requiresPivot:!0},{id:"pie",icon:s.ChartPie,label:"Pie Chart"},{id:"doughnut",icon:s.Donut,label:"Donut Chart"},{id:"kpi",icon:s.TiSortNumerically,label:"KPI"}];function vl({selectedChart:t,onChartChange:a}){var l;const n=s.useEditorStore(o=>o.card),r=((l=n==null?void 0:n.config)==null?void 0:l.pivotByColumns)&&n.config.pivotByColumns.length>0;return e.jsx("div",{className:"flex items-center gap-1",children:yl.map(o=>{if(o.requiresPivot&&!r)return null;const c=o.icon,i=t===o.id;return e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"ghost",size:"sm",onClick:()=>a(o.id),className:s.cn("h-8 w-8 p-0",i&&"bg-accent text-accent-foreground"),children:[e.jsx(c,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:o.label})]})}),e.jsx(s.TooltipContent,{side:"bottom",children:e.jsx("p",{children:o.label})})]},o.id)})})}const As=({dataType:t})=>{const a=s.getDataType(t);return a==="string"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(ge,{className:"h-3 w-3"})}):a==="number"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(Ne,{className:"h-3 w-3"})}):a==="date"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):a==="boolean"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Le,{className:"h-3 w-3"})}):e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(ge,{className:"h-3 w-3"})})};function Nl({aliasTemplate:t,onAliasTemplateChange:a}){var d;const[n,r]=A.useState(t),[l,o]=A.useState(!1),c=(d=s.useEditorStore(u=>{var m;return(m=u.card.config)==null?void 0:m.pivotByColumns}))==null?void 0:d[0],i=c?`e.g. Min Sales in {{${c.name}}}`:"e.g. Min Sales in {{region}}";return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-gray-600",children:"Pivot Alias Template"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Input$1,{placeholder:i,value:l?n:t,onChange:u=>{r(u.target.value),o(!0)},onFocus:()=>o(!0),onPointerDown:u=>u.stopPropagation(),className:"h-8 text-xs",onKeyDown:u=>{u.key==="Enter"&&l&&n!==t?(a(n),o(!1)):u.key==="Escape"&&(r(t),o(!1))},"aria-label":"Edit alias template"}),l&&n!==t&&e.jsxs(e.Fragment,{children:[e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm alias template",onClick:()=>{a(n),o(!1)},children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel alias template edit",onClick:()=>{r(t),o(!1)},children:e.jsx(s.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function Cl({valueAliases:t,onValueAliasesChange:a}){const[n,r]=A.useState(null),[l,o]=A.useState(""),[c,i]=A.useState(""),d=()=>{a({...t,"":""})},u=h=>{const f={...t};delete f[h],a(f)},m=h=>{const f={...t};delete f[h],f[l]=c,a(f),r(null)};return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Pivot Value Aliases"}),e.jsxs("div",{className:"space-y-2",children:[Object.entries(t).map(([h,f],g)=>e.jsx("div",{className:"flex items-center gap-2",children:n===h?e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:l,onChange:b=>o(b.target.value),className:"h-8 w-24 text-xs",onPointerDown:b=>b.stopPropagation(),onKeyDown:b=>{b.key==="Enter"?m(h):b.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:c,onChange:b=>i(b.target.value),className:"h-8 w-24 text-xs",onPointerDown:b=>b.stopPropagation(),onKeyDown:b=>{b.key==="Enter"?m(h):b.key==="Escape"&&r(null)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm value alias edit",onClick:()=>m(h),children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel value alias edit",onClick:()=>r(null),children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:h,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),o(h),i(f)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:f,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),o(h),i(f)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>u(h),"aria-label":"Remove value alias",children:e.jsx(s.X,{className:"h-3 w-3"})})]})},h+g)),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"mt-1 h-8 text-xs",onClick:d,children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Value Alias"]})]})]})}function Sl({field:t,searchQuery:a="",limit:n=500}){const{authToken:r}=s.useSemaphorContext(),l=s.useEditorStore(d=>d.card),o=l==null?void 0:l.dataSource,c=["attribute-values",t.entityName,t.name,a,n],i=s.useQuery({queryKey:c,queryFn:async()=>{if(!(o!=null&&o.connectionId))return console.warn("No connection ID available for attribute values query"),[];try{const d={groupByColumns:[{...t,role:"groupby"}],metricColumns:[],filters:a?{id:"search-filter",logicalOperator:"AND",negate:!1,conditions:[{id:"search-condition",field:t,operator:"contains",value:a}],groups:[]}:void 0,rowLimit:n},u={connection_id:o.connectionId,cardConfig:d,cardDataSource:o,cache_config:s.getCacheConfig({card:l})};console.log("requestBody",u);const m=await s.postRequestRegular("https://semaphor.cloud/api/v1/query",(r==null?void 0:r.accessToken)||"",u);if(m!=null&&m.error)return console.error("Error fetching attribute values:",m.error),[];const h=t.name;return((m==null?void 0:m.records)||[]).map(g=>{const b=g[h]||g[t.alias||h]||g[t.label];return{id:b||"",value:b||"",label:String(b||"(empty)")}})}catch(d){return console.error("Error fetching attribute values:",d),[]}},enabled:!!t&&!!(o!=null&&o.connectionId),staleTime:5*60*1e3,gcTime:10*60*1e3});return{values:i.data||[],isLoading:i.isLoading,isFetching:i.isFetching,isError:i.isError,error:i.error,refetch:i.refetch}}function wl({open:t,onOpenChange:a,availableFields:n,existingFilters:r,editingCondition:l,onSave:o}){var k,R;const c=!!l,[i,d]=A.useState(c?"values":"fields"),[u,m]=A.useState(""),[h,f]=A.useState({id:(l==null?void 0:l.id)||s.v4(),field:(l==null?void 0:l.field)||null,selectedValues:l?Array.isArray(l.value)?l.value:[l.value]:[]}),g=n.filter(N=>{var y;return c?!1:!((y=r==null?void 0:r.conditions)==null?void 0:y.some(D=>D.field.id===N.id))&&N.label.toLowerCase().includes(u.toLowerCase())}),b=N=>{f({...h,field:N}),d("values")},p=()=>{if(h.field&&h.selectedValues.length>0){const N={id:h.id,field:h.field,operator:"in",value:h.selectedValues};let w;if(c){const y=((r==null?void 0:r.conditions)||[]).map(D=>D.id===l.id?N:D);w={...r,conditions:y}}else{const y=(r==null?void 0:r.conditions)||[];w={id:(r==null?void 0:r.id)||s.v4(),logicalOperator:"AND",negate:!1,conditions:[...y,N],groups:[]}}o(w),a(!1)}},j=()=>{if(!c||!l)return;const N=((r==null?void 0:r.conditions)||[]).filter(w=>w.id!==l.id);if(N.length>0){const w={...r,conditions:N};o(w)}else o(void 0);a(!1)},x=N=>{f({...h,selectedValues:N})},v=()=>{c&&l?(f({id:l.id,field:l.field,selectedValues:Array.isArray(l.value)?l.value:[l.value]}),d("values")):(f({id:s.v4(),field:null,selectedValues:[]}),d("fields")),m("")};return A.useEffect(()=>{t&&v()},[t,c,l]),e.jsx(s.Dialog,{open:t,onOpenChange:a,children:e.jsxs(s.DialogContent,{className:"max-w-2xl",children:[e.jsx(s.DialogHeader,{children:e.jsx(s.DialogTitle,{children:c?`Edit Filter: ${(k=h.field)==null?void 0:k.label}`:i==="fields"?"Select Field to Filter":`Select Values for ${(R=h.field)==null?void 0:R.label}`})}),e.jsxs("div",{className:"space-y-4",children:[!c&&(r==null?void 0:r.conditions)&&r.conditions.length>0&&i==="fields"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Current Filters:"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:r.conditions.map(N=>e.jsxs("div",{className:"flex items-center gap-1 px-2 py-1 bg-muted rounded-md text-xs",children:[e.jsxs("span",{className:"font-medium",children:[N.field.label,":"]}),e.jsx("span",{className:"text-muted-foreground",children:Array.isArray(N.value)?`${N.value.length} values`:String(N.value)})]},N.id))})]}),i==="fields"&&!c?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:"Search fields...",value:u,onChange:N=>m(N.target.value),className:"pl-10"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2 max-h-[400px] overflow-y-auto",children:g.map(N=>e.jsxs(s.Button,{variant:"outline",className:"justify-start h-auto py-2 px-3",onClick:()=>b(N),children:[e.jsx(As,{dataType:s.getDataType(N.dataType)}),e.jsxs("div",{className:"ml-2 text-left",children:[e.jsx("div",{className:"text-sm font-medium",children:N.label}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[N.entityName,".",N.name]})]})]},N.id))}),g.length===0&&u&&e.jsxs("div",{className:"text-center py-4 text-sm text-muted-foreground",children:['No fields found matching "',u,'"']}),g.length===0&&!u&&n.length>0&&e.jsx("div",{className:"text-center py-4 text-sm text-muted-foreground",children:"All available fields are already filtered"})]}):e.jsx(Dl,{field:h.field,selectedValues:h.selectedValues,onValuesChange:x,onBack:c?void 0:()=>d("fields")}),e.jsxs("div",{className:"flex justify-between pt-4 border-t",children:[e.jsx("div",{children:c?e.jsx(s.Button,{variant:"destructive",onClick:j,children:"Delete Filter"}):e.jsx(s.Button,{variant:"outline",onClick:v,children:"Reset"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(s.Button,{onClick:p,disabled:!h.field||h.selectedValues.length===0,children:"Apply"})]})]})]})]})})}function Dl({field:t,selectedValues:a,onValuesChange:n,onBack:r}){const[l,o]=A.useState(""),{values:c,isLoading:i,isFetching:d}=Sl({field:t,searchQuery:l,limit:500}),u=l?c.filter(f=>String(f.value).toLowerCase().includes(l.toLowerCase())):c,m=f=>{const g=a.includes(f);n(g?a.filter(b=>b!==f):[...a,f])},h=()=>{a.length===u.length&&u.length>0?n([]):n(u.map(f=>f.value))};return e.jsxs("div",{className:"space-y-4",children:[r&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:r,children:"← Back"}),e.jsxs(s.Label,{className:"text-sm font-medium",children:["Select values for ",t.label]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:"Search values...",value:l,onChange:f=>o(f.target.value),className:"pl-10"})]}),i||d?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(s.LoaderCircle,{className:"h-6 w-6 animate-spin"})}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 pb-2 border-b",children:[e.jsx(s.Checkbox,{checked:a.length===u.length&&u.length>0,onCheckedChange:h}),e.jsxs(s.Label,{className:"text-sm",children:["Select All (",u.length,")"]})]}),e.jsx("div",{className:"max-h-[300px] overflow-y-auto space-y-1",children:u.map(f=>e.jsxs("div",{className:"flex items-center gap-2 p-2 hover:bg-muted/50 rounded cursor-pointer",onClick:()=>m(f.value),children:[e.jsx(s.Checkbox,{checked:a.includes(f.value),onCheckedChange:()=>m(f.value)}),e.jsx(ls,{className:"text-sm",children:f.label})]},f.id))})]})]})}function kl({field:t,zone:a,index:n,sortDirection:r,onSortDirectionChange:l,hasPivotColumns:o=!1,cardType:c}){var Rs,Os,Bs;const{attributes:i,listeners:d,setNodeRef:u,transform:m,transition:h,isDragging:f}=s.useSortable({id:t.id}),g=s.useEditorStore(G=>G.card),{updateLabel:b,handleAggregationChange:p,handleDateFormatChange:j,handleGranularityChange:x,handleAliasTemplateChange:v,handleValueAliasesChange:k,removeField:R,handleKpiComparisonTypeChange:N,handleKpiShowTrendlineChange:w,handleKpiTrendlineWindowChange:y,handleKpiTrendlineGranularityChange:D,handleKpiTargetValueChange:C}=Is(g),[I,S]=A.useState(!1),[F,T]=A.useState(!1),[E,M]=A.useState(null),[B,L]=A.useState(t.dateFormat||"YYYY-MM-DD"),[O,P]=A.useState(t.customFormat||""),[K,$]=A.useState(!!t.customFormat),[te,X]=A.useState(t.granularity||"day"),[q,H]=A.useState(t.aliasTemplate||""),[_,J]=A.useState(t.valueAliases||{}),[z,U]=A.useState((Rs=t.parameters)==null?void 0:Rs.filters),Z=G=>{G==="custom"?$(!0):($(!1),L(G),a==="groupBy"&&j(n,G,""))},le=G=>{P(G),a==="groupBy"&&j(n,"custom",G)},V=G=>{var xe;X(G);const de=(xe=ee(G)[0])==null?void 0:xe.value;de&&!K&&(L(de),a==="groupBy"&&j(n,de,"")),a==="groupBy"&&x(n,G)},se=G=>{H(G),a==="metrics"&&v(n,G)},ne=G=>{J(G),a==="metrics"&&k(n,G)},Y=G=>{b(a,n,G)},W=G=>{var ce;if(U(G),a==="metrics"){const de={...t,parameters:{...t.parameters,filters:G}},xe=[...((ce=g.config)==null?void 0:ce.metricColumns)||[]];xe[n]=de,s.useEditorStore.getState().actions.updateCardConfig(g.id,{metricColumns:xe})}T(!1)},re=()=>{R(a,n)},ie={transform:s.CSS.Transform.toString(m),transition:h},he=s.getDataType(t.dataType),Q=he==="date",oe=c==="kpi",ee=G=>{switch(G){case"day":return[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"MM/DD/YYYY",label:"01/15/2024 (MM/DD/YYYY)"},{value:"DD/MM/YYYY",label:"15/01/2024 (DD/MM/YYYY)"},{value:"MMMM DD, YYYY",label:"January 15, 2024 (MMMM DD, YYYY)"},{value:"MMM DD, YYYY",label:"Jan 15, 2024 (MMM DD, YYYY)"},{value:"DD MMM YYYY",label:"15 Jan 2024 (DD MMM YYYY)"},{value:"custom",label:"Custom Format..."}];case"week":return[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"Week of MMM DD, YYYY",label:"Week of Jan 15, 2024"},{value:"Week of MMMM DD, YYYY",label:"Week of January 15, 2024"},{value:"YYYY-WW",label:"2024-W03 (YYYY-WW)"},{value:"custom",label:"Custom Format..."}];case"month":return[{value:"MMM YYYY",label:"Jan 2024 (MMM YYYY)"},{value:"MMMM YYYY",label:"January 2024 (MMMM YYYY)"},{value:"YYYY-MM",label:"2024-01 (YYYY-MM)"},{value:"MM/YYYY",label:"01/2024 (MM/YYYY)"},{value:"YYYY MMM",label:"2024 Jan (YYYY MMM)"},{value:"custom",label:"Custom Format..."}];case"quarter":return[{value:"Q1 YYYY",label:"Q1 2024 (Q1 YYYY)"},{value:"YYYY Q1",label:"2024 Q1 (YYYY Q1)"},{value:"1st Quarter YYYY",label:"1st Quarter 2024"},{value:"YYYY-Q1",label:"2024-Q1 (YYYY-Q1)"},{value:"Quarter 1, YYYY",label:"Quarter 1, 2024"},{value:"custom",label:"Custom Format..."}];case"year":return[{value:"YYYY",label:"2024 (YYYY)"},{value:"YY",label:"24 (YY)"},{value:"custom",label:"Custom Format..."}];default:return[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"MM/DD/YYYY",label:"01/15/2024 (MM/DD/YYYY)"},{value:"DD/MM/YYYY",label:"15/01/2024 (DD/MM/YYYY)"},{value:"MMMM DD, YYYY",label:"January 15, 2024 (MMMM DD, YYYY)"},{value:"MMM DD, YYYY",label:"Jan 15, 2024 (MMM DD, YYYY)"},{value:"DD MMM YYYY",label:"15 Jan 2024 (DD MMM YYYY)"},{value:"YYYY-MM",label:"2024-01 (YYYY-MM)"},{value:"MMMM YYYY",label:"January 2024 (MMMM YYYY)"},{value:"custom",label:"Custom Format..."}]}},ae=ee(te),ue=a!=="pivotBy",je=Q&&a==="groupBy",Ge=!oe&&Q&&a==="groupBy",He=oe&&Q&&a==="groupBy",We=oe&&a==="metrics"&&((Os=g.config)==null?void 0:Os.comparisonType)==="target",ze=a==="metrics",Ce=()=>e.jsx("div",{title:`${t.entityName}.${t.name}`,onPointerDown:G=>{G.stopPropagation()},className:"max-w-[270px] cursor-default overflow-hidden text-ellipsis whitespace-nowrap px-0.5 text-xs text-gray-500",children:`${t.entityName}.${t.name}`}),me=()=>ue?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Label"}),e.jsx(ve,{value:t.label??"",onSave:Y,placeholder:"Display label...",type:"text"})]}):null,Ls=()=>je?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Granularity"}),e.jsxs(s.Select,{value:te,onValueChange:V,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select granularity..."})}),e.jsx(s.SelectContent,{children:["day","week","month","quarter","year"].map(G=>e.jsx(s.SelectItem,{className:"text-xs",value:G,children:s.toTitleCase(G)},G))})]})]}):null,Kt=()=>Ge?e.jsxs(e.Fragment,{children:[Ls(),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Date Format"}),e.jsxs(s.Select,{value:K?"custom":B,onValueChange:Z,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select date format..."})}),e.jsx(s.SelectContent,{children:ae.map(G=>e.jsx(s.SelectItem,{className:"text-xs",value:G.value,children:G.label},G.value))})]}),K&&e.jsxs("div",{className:"mt-2 space-y-1",children:[e.jsx(s.Input$1,{placeholder:"Enter custom format (e.g., YYYY-MM-DD HH:mm)",value:O,onChange:G=>{G.stopPropagation(),le(G.target.value)},onClick:G=>G.stopPropagation(),className:"h-8 text-xs"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Examples: YYYY-MM-DD, MM/DD/YY, DD-MMM-YYYY HH:mm"})]})]})]}):null,Jt=()=>{var G,ce,de,xe,Se;return He?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Comparison Type"}),e.jsxs(s.Select,{value:((G=g.config)==null?void 0:G.comparisonType)||"none",onValueChange:N,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select comparison type..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"none",children:"No Comparison"}),e.jsx(s.SelectItem,{value:"previous_period",children:"Previous Period"}),e.jsx(s.SelectItem,{value:"same_period_last_year",children:"Same Period Last Year"}),e.jsx(s.SelectItem,{value:"target",children:"Target Value"})]})]})]}),e.jsx("div",{className:"space-y-1",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Show Trendline"}),e.jsx(s.SmallSwitch,{checked:((ce=g.config)==null?void 0:ce.showTrendline)||!1,onCheckedChange:w})]})}),((de=g.config)==null?void 0:de.showTrendline)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Window"}),e.jsx(s.Input$1,{type:"number",min:"1",max:"365",value:((xe=g.config)==null?void 0:xe.trendlineWindow)||30,onChange:Ke=>{const sa=parseInt(Ke.target.value)||30;y(sa)},className:"h-8 text-xs",placeholder:"30"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Granularity"}),e.jsxs(s.Select,{value:((Se=g.config)==null?void 0:Se.trendlineGranularity)||"day",onValueChange:D,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select granularity..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"day",children:"Day"}),e.jsx(s.SelectItem,{value:"week",children:"Week"}),e.jsx(s.SelectItem,{value:"month",children:"Month"})]})]})]})]})]}):null},Qt=()=>{var G,ce;return We?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Target Value"}),e.jsx(ve,{value:((G=g.config)==null?void 0:G.targetValue)!==void 0&&((ce=g.config)==null?void 0:ce.targetValue)!==null?String(g.config.targetValue):"",onSave:de=>{!isNaN(Number(de))&&de!==null?C(Number(de)):C(0)},placeholder:"Enter target value...",type:"text"})]}):null},Xt=()=>ze?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Aggregation"}),e.jsxs(s.Select,{value:t.aggregate,onValueChange:G=>{p(n,G)},children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select function..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"COUNT",children:"Count"}),e.jsx(s.SelectItem,{className:"text-xs",value:"DISTINCT",children:"Count Distinct"}),s.getDataType(t.dataType)==="number"&&e.jsxs(e.Fragment,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"SUM",children:"Sum"}),e.jsx(s.SelectItem,{className:"text-xs",value:"AVG",children:"Average"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MIN",children:"Min"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MAX",children:"Max"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MEDIAN",children:"Median"})]})]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Attribute Filters"}),(z==null?void 0:z.conditions)&&z.conditions.length>0&&e.jsx("div",{className:"mb-2 space-y-1",children:z.conditions.map(G=>e.jsxs("div",{className:"flex cursor-pointer items-center gap-2 rounded bg-muted/50 p-2 text-xs transition-colors hover:bg-muted/70",onClick:()=>{M(G),T(!0)},children:[e.jsxs("span",{className:"font-medium",children:[G.field.label,":"]}),e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"cursor-help text-muted-foreground",children:Array.isArray(G.value)?G.value.length===1?String(G.value[0]):G.value.length<=2?G.value.join(", "):`${G.value.slice(0,2).join(", ")} +${G.value.length-2}`:String(G.value)})}),Array.isArray(G.value)&&G.value.length>1&&e.jsx(s.TooltipContent,{side:"top",className:"max-w-[300px]",children:e.jsxs("div",{className:"text-xs",children:[e.jsxs("div",{className:"mb-1 font-medium",children:["Selected values (",G.value.length,"):"]}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto",children:G.value.map((ce,de)=>e.jsx("div",{children:String(ce)},de))})]})})]})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"ml-auto h-4 w-4 p-0",onClick:ce=>{var xe;ce.stopPropagation();const de=z.conditions.filter(Se=>Se.id!==G.id);if(de.length>0){const Se={...z,conditions:de};W(Se)}else if(U(void 0),a==="metrics"){const Se={...t,parameters:{...t.parameters,filters:void 0}},Ke=[...((xe=g.config)==null?void 0:xe.metricColumns)||[]];Ke[n]=Se,s.useEditorStore.getState().actions.updateCardConfig(g.id,{metricColumns:Ke})}},children:e.jsx(s.X,{className:"h-3 w-3"})})]},G.id))}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>{M(null),T(!0)},children:[e.jsx(s.Filter,{className:"mr-2 h-3 w-3"}),"Add attribute filter"]})]}),e.jsx(qt,{column:t}),o&&e.jsxs(e.Fragment,{children:[e.jsx(Nl,{aliasTemplate:q,onAliasTemplateChange:se}),e.jsx(Cl,{valueAliases:_,onValueAliasesChange:ne})]})]}):null,{columns:Zt=[]}=s.useColumns(),ea=(z==null?void 0:z.conditions)&&z.conditions.length>0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{ref:u,style:ie,...i,...d,className:`group mx-auto flex w-full flex-col gap-2 rounded border border-border bg-background p-2 transition-all hover:shadow-sm dark:border-gray-800 ${f?"z-50 scale-95 opacity-50":"border-slate-200"} ${a==="filters"?"cursor-default":"cursor-move"}`,children:[e.jsxs("div",{className:"flex grow items-center gap-2",children:[e.jsx(As,{dataType:he}),e.jsx(ls,{className:s.cn("w-[140px] flex-1 text-sm",ea&&"w-[120px]"),children:s.getMetricDisplayLabel(t)}),a==="metrics"&&((Bs=z==null?void 0:z.conditions)==null?void 0:Bs.length)&&!I&&e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-1 rounded bg-primary/10 px-1.5 py-0.5 text-xs",children:[e.jsx(s.Filter,{className:"h-3 w-3"}),e.jsx("span",{children:z.conditions.length})]})}),e.jsx(s.TooltipContent,{side:"top",children:e.jsx("div",{className:"text-xs",children:z.conditions.map(G=>e.jsxs("div",{children:[G.field.label,":"," ",Array.isArray(G.value)?`${G.value.length} values`:String(G.value)]},G.id))})})]})}),a!=="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:G=>{G.stopPropagation(),S(!I)},children:e.jsx(s.ChevronDown,{className:`h-3 w-3 transition-transform ${I?"rotate-180":""}`})}),a==="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 group-hover:opacity-100",onClick:G=>{G.stopPropagation(),console.log("DraggableField - Current sortDirection:",r);const ce=r==="asc"?"desc":"asc";console.log("DraggableField - New direction to set:",ce),l(ce)},children:r==="asc"?e.jsx(s.ArrowUp,{className:"h-3 w-3"}):e.jsx(s.ArrowDown,{className:"h-3 w-3"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:G=>{G.stopPropagation(),re()},children:e.jsx(s.X,{className:"h-3 w-3"})})]}),I&&e.jsxs("div",{className:"space-y-3",children:[Ce(),me(),c==="kpi"&&Ls(),Kt(),Jt(),Qt(),Xt()]})]}),F&&e.jsx(wl,{open:F,onOpenChange:G=>{T(G),G||M(null)},availableFields:Zt,existingFilters:z,editingCondition:E,onSave:G=>{var ce;if(G)W(G);else if(U(void 0),a==="metrics"){const de={...t,parameters:{...t.parameters,filters:void 0}},xe=[...((ce=g.config)==null?void 0:ce.metricColumns)||[]];xe[n]=de,s.useEditorStore.getState().actions.updateCardConfig(g.id,{metricColumns:xe})}M(null)}})]})}function Tl({concept:t}){const a=()=>{switch(t){case"groupBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Rows = Group By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that define how your data is grouped into rows."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-100 text-xs font-medium dark:bg-blue-200/20",children:"Product"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Sales"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Profit"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/50 text-xs font-medium dark:bg-blue-200/20",children:"Electronics"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$5,200"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$1,300"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/30 text-xs font-medium dark:bg-blue-300/20",children:"Clothing"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$3,100"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$620"})]}),e.jsxs("div",{className:"flex",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/20 text-xs font-medium dark:bg-blue-200/20",children:"Food"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$2,400"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$480"})]})]})]});case"pivotBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Columns = Pivot By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that split your data into multiple columns or series."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Region"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"North"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"South"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"East"})]}),e.jsxs("div",{className:"flex border-b py-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$2,300"}),e.jsx("div",{className:"w-1/4 bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$1,800"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$3,400"})]}),e.jsxs("div",{className:"flex py-1",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$460"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$360"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$680"})]})]})]});case"metrics":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Metrics = Values (Cells)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that represent the values shown in your visualization."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"col-span-1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q2"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q3"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"rounded bg-blue-100 p-1 text-center text-xs dark:bg-blue-300/20",children:"$2,300"}),e.jsx("div",{className:"rounded bg-blue-200 p-1 text-center text-xs dark:bg-blue-400/20",children:"$3,100"}),e.jsx("div",{className:"rounded bg-blue-300 p-1 text-center text-xs dark:bg-blue-500/20",children:"$4,200"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"rounded bg-green-100 p-1 text-center text-xs dark:bg-green-300/20",children:"$460"}),e.jsx("div",{className:"rounded bg-green-200 p-1 text-center text-xs dark:bg-green-400/20",children:"$620"}),e.jsx("div",{className:"rounded bg-green-300 p-1 text-center text-xs dark:bg-green-500/20",children:"$840"})]})]})]});default:return null}};return e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{delayDuration:300,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.CircleHelp,{className:"size-4 text-muted-foreground hover:text-foreground"})}),e.jsx(s.TooltipContent,{side:"right",align:"start",className:"p-3",children:a()})]})})}function Xe({zone:t,fields:a,label:n,placeholder:r,shouldShow:l,hasPivotColumns:o=!1}){const{isOver:c,setNodeRef:i}=s.useDroppable({id:t}),{updateSortByColumn:d}=s.useEditorActions(),u=s.useEditorStore(b=>b.card),m=s.useEditorStore(b=>b.card.type),h=a.length>0,f=(b,p)=>{var x;!((x=u.config)!=null&&x.sortByColumns)||u.config.sortByColumns.findIndex(v=>v.id===b)===-1||d(u.id,b,{direction:p})};if(t==="sortBy"&&l===!1)return null;const g=t!=="sortBy"&&m!=="kpi";return e.jsxs("div",{className:"mb-4 w-full",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(s.Label,{className:s.cn("block text-sm font-medium",{}),children:n}),g&&e.jsx(Tl,{concept:t})]}),e.jsx("div",{ref:i,className:`rounded-lg border-2 border-dashed p-1 transition-all ${c?"border-blue-500 bg-blue-50 dark:bg-blue-950":h?"border-blue-200 bg-blue-50/30 dark:border-blue-800 dark:bg-blue-950/30":"min-h-[60px] border-muted-foreground/20 bg-background"}`,children:a.length===0?e.jsx("div",{className:"flex min-h-[40px] items-center justify-center text-sm text-gray-400",children:r}):e.jsx(s.SortableContext,{items:a.map(b=>b.id),strategy:s.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-1",children:a.map((b,p)=>{const x=b.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"flex-1",children:e.jsx(kl,{field:b,zone:t,index:p,sortDirection:x,onSortDirectionChange:v=>f(b.id,v),hasPivotColumns:o,cardType:m})})},b.id)})})})})]})}const Qs=[{value:"green",color:"#16a34a",label:"Green"},{value:"red",color:"#dc2626",label:"Red"},{value:"neutral",color:"#6b7280",label:"Neutral"}],El=["#16a34a","#dc2626","#6b7280","#2563eb","#ca8a04","#7c3aed","#0891b2","#e11d48","#ea580c"];function ps({value:t,onChange:a,label:n}){const[r,l]=A.useState(!1),[o,c]=A.useState(!1),i=()=>{const d=Qs.find(u=>u.value===t);return d?d.color:t.startsWith("#")?t:Qs[2].color};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Popover,{open:r,onOpenChange:l,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx("button",{className:"size-5 rounded border-2 border-input shadow-sm transition-all hover:scale-110 hover:border-gray-400",style:{backgroundColor:i()},"aria-label":`Change color for ${n}`})}),e.jsx(s.PopoverContent,{align:"start",className:"w-auto p-2",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"grid grid-cols-3 items-center justify-items-center gap-1",children:El.map(d=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border-2 transition-all",i()===d?"border-gray-900":"border-transparent"),style:{backgroundColor:d},onClick:()=>{a(d),l(!1)},children:e.jsx("span",{className:"sr-only",children:d})},d))}),e.jsx("button",{className:"w-full rounded border border-input px-2 py-1 text-xs hover:bg-muted",onClick:()=>{c(!0),l(!1)},children:"Custom color..."})]})})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:n})]}),o&&e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/50",onClick:()=>c(!1)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(zt,{color:i(),onColorChange:d=>{a(d),c(!1)},onClose:()=>c(!1)})})]})]})}const Ze={difference:{label:"Difference",description:"Shows the exact difference between two values.",formula:"Primary - Secondary",example:"Sales increased by $5,000 compared to last year."},change:{label:"Change",description:"Shows the percentage increase or decrease between two values.",formula:"(Primary - Secondary) / Secondary × 100%",example:"Year-over-year sales change of 25%."},change_difference:{label:"Change (difference)",description:"Shows both the percentage change and the exact difference between two values.",formula:`% Change: (Primary - Secondary) / Secondary × 100%
|
|
360
|
-
Difference: Primary - Secondary`,example:"Sales grew by 25% ($5,000) compared to last year."},ratio:{label:"Ratio",description:"Shows how much of one value is covered by another — useful for quotas and benchmarks.",formula:"Primary / Secondary × 100%",example:"You've achieved 80% of your sales quota."}};function Il(){var i,d,u,m,h,f,g,b,p,j;const t=s.useEditorStore(x=>x.card),{setCardPreferences:a}=s.useEditorActions(),n=((i=t.config)==null?void 0:i.metricColumns)||[],r=((d=t.config)==null?void 0:d.groupByColumns)||[];if(!(t.type==="kpi"&&(n.length>=2&&r.length===0||n.length>=1&&r.length>0)))return null;const o=((m=(u=t.preferences)==null?void 0:u.kpiVisualOptions)==null?void 0:m.metricComparison)||{},c=x=>{var k;const v={...t.preferences,kpiVisualOptions:{...(k=t.preferences)==null?void 0:k.kpiVisualOptions,metricComparison:{...o,...x}}};a(v)};return e.jsxs(s.AccordionItem,{value:"comparison",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Na,{className:"h-4 w-4"}),e.jsx("span",{children:"Comparison"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{htmlFor:"enable-comparison",className:"text-xs",children:"Enable Metric Comparison"}),e.jsx(s.SmallSwitch,{id:"enable-comparison",checked:o.enabled||!1,onCheckedChange:x=>c({enabled:x,...x&&!o.calculationType?{calculationType:"difference"}:{}})})]}),o.enabled&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"calculation-type",className:"text-xs font-medium uppercase text-muted-foreground",children:"Calculated as"}),e.jsxs(s.Select,{value:o.calculationType||"difference",onValueChange:x=>c({calculationType:x}),children:[e.jsx(s.SelectTrigger,{id:"calculation-type",className:"h-7 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Object.entries(Ze).map(([x,v])=>e.jsx(s.SelectItem,{value:x,className:"text-xs",children:v.label},x))})]}),(()=>{var v,k,R;const x=o.calculationType||"difference";return e.jsxs("div",{className:"space-y-2 rounded-md bg-muted/50 p-2 text-xs",children:[e.jsx("p",{className:"text-muted-foreground",children:(v=Ze[x])==null?void 0:v.description}),e.jsxs("div",{className:"text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Formula:"})," ",e.jsx("code",{className:"rounded bg-background px-1 py-0.5 text-[10px]",children:(k=Ze[x])==null?void 0:k.formula})]}),e.jsxs("div",{className:"border-t pt-1 italic text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Example:"})," ",(R=Ze[x])==null?void 0:R.example]})]})})()]}),e.jsx(Ts,{formatOptions:o.formatOptions||{},onFormatOptionsChange:x=>c({formatOptions:x}),showTitle:!0,title:"COMPARISON FORMAT"}),e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Indicator"}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Position"}),e.jsxs(s.Select,{value:o.position||"left",onValueChange:x=>c({position:x}),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-20 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"top",className:"text-xs",children:"Top"}),e.jsx(s.SelectItem,{value:"left",className:"text-xs",children:"Left"}),e.jsx(s.SelectItem,{value:"right",className:"text-xs",children:"Right"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"show-arrow",checked:o.showArrow!==!1,onCheckedChange:x=>c({showArrow:x})}),e.jsx(s.Label,{htmlFor:"show-arrow",className:"cursor-pointer text-xs text-muted-foreground",children:"Arrow"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"show-color",checked:o.showColor!==!1,onCheckedChange:x=>c({showColor:x})}),e.jsx(s.Label,{htmlFor:"show-color",className:"cursor-pointer text-xs text-muted-foreground",children:"Color"})]}),o.showColor!==!1&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-3",children:[e.jsx(ps,{value:((h=o.colorConfig)==null?void 0:h.increase)||"green",onChange:x=>c({colorConfig:{...o.colorConfig,increase:x}}),label:"Primary > Secondary"}),e.jsx(ps,{value:((f=o.colorConfig)==null?void 0:f.decrease)||"red",onChange:x=>c({colorConfig:{...o.colorConfig,decrease:x}}),label:"Primary < Secondary"}),e.jsx(ps,{value:((g=o.colorConfig)==null?void 0:g.noChange)||"neutral",onChange:x=>c({colorConfig:{...o.colorConfig,noChange:x}}),label:"Primary = Secondary"})]})]}),e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Label"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"conditional-label",checked:o.conditionalLabel||!1,onCheckedChange:x=>c({conditionalLabel:x})}),e.jsx(s.Label,{htmlFor:"conditional-label",className:"cursor-pointer text-xs text-muted-foreground",children:"Conditional"})]}),o.conditionalLabel?e.jsxs("div",{className:"space-y-3 border-l-2 border-muted pl-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"label-increase",className:"text-xs text-muted-foreground",children:["Primary ",">"," Secondary"]}),e.jsx(s.Input,{id:"label-increase",type:"text",value:((b=o.conditionalLabels)==null?void 0:b.increase)??"Increase",onChange:x=>c({conditionalLabels:{...o.conditionalLabels,increase:x.target.value}}),placeholder:"Increase",className:"h-7 text-xs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"label-decrease",className:"text-xs text-muted-foreground",children:["Primary ","<"," Secondary"]}),e.jsx(s.Input,{id:"label-decrease",type:"text",value:((p=o.conditionalLabels)==null?void 0:p.decrease)??"Decrease",onChange:x=>c({conditionalLabels:{...o.conditionalLabels,decrease:x.target.value}}),placeholder:"Decrease",className:"h-7 text-xs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"label-no-change",className:"text-xs text-muted-foreground",children:"Primary = Secondary"}),e.jsx(s.Input,{id:"label-no-change",type:"text",value:((j=o.conditionalLabels)==null?void 0:j.noChange)??"No change",onChange:x=>c({conditionalLabels:{...o.conditionalLabels,noChange:x.target.value}}),placeholder:"No change",className:"h-7 text-xs"})]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"label-name",className:"text-xs text-muted-foreground",children:"Name"}),e.jsx(s.Input,{id:"label-name",type:"text",value:o.labelName??"",onChange:x=>c({labelName:x.target.value}),placeholder:"e.g. Versus, Compared to",className:"h-7 text-xs"})]})]})]})]})]})}function Al(){var l,o;const t=s.useEditorStore(c=>c.card),{setCardPreferences:a}=s.useEditorActions();if(t.type!=="kpi")return null;const n=((o=(l=t.preferences)==null?void 0:l.kpiVisualOptions)==null?void 0:o.formatOptions)||{},r=c=>{var d;const i={...t.preferences,kpiVisualOptions:{...(d=t.preferences)==null?void 0:d.kpiVisualOptions,formatOptions:c}};a(i)};return e.jsxs(s.AccordionItem,{value:"kpi-format",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ne,{className:"h-4 w-4"}),e.jsx("span",{children:"Number Format"})]})}),e.jsx(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:e.jsx(Ts,{formatOptions:n,onFormatOptionsChange:r,showTitle:!1})})]})}function Ml({groupByFields:t,pivotByFields:a,metricsFields:n,sortByFields:r}){const l=s.useEditorStore(b=>{var p;return((p=b.card.customCardPreferences)==null?void 0:p.url)&&b.card.type==="custom"}),o=s.useEditorStore(b=>b.card),c=o==null?void 0:o.type,i=t.length>0||n.length>0,d=c!=="kpi",u=c!=="kpi"&&i,m=["pie","doughnut","polar","funnel","aggregateTable"].includes(c),h=d&&!m,f=()=>c==="kpi"?{label:"Trend By",placeholder:"Drop fields to trend data"}:{label:"Rows",placeholder:"Drop fields to group data"},g=()=>c==="kpi"?{label:"Metric",placeholder:"Drop field for KPI"}:{label:"Metrics",placeholder:"Drop fields to measure"};return e.jsxs(s.Accordion,{type:"single",collapsible:!0,defaultValue:"fields",className:"w-full",children:[e.jsxs(s.AccordionItem,{value:"fields",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ea,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"FIELDS"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pt-2",children:[e.jsx(Xe,{zone:"groupBy",fields:t,label:f().label,placeholder:f().placeholder}),h&&e.jsx(Xe,{zone:"pivotBy",fields:a,label:"Columns",placeholder:"Drop fields to pivot data"}),e.jsx(Xe,{zone:"metrics",fields:n,label:g().label,placeholder:g().placeholder,hasPivotColumns:a.length>0}),u&&e.jsx(Xe,{zone:"sortBy",fields:r,label:"Sort By",placeholder:"Drop fields from Rows or Metrics"})]})]}),!l&&e.jsxs(s.AccordionItem,{value:"configuration",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Settings,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"CONFIGURATION"})]})}),e.jsx(s.AccordionContent,{className:"rounded-md border border-border bg-muted/50 px-3 py-0",children:e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full",children:[e.jsx(Al,{}),e.jsx(Il,{}),e.jsx(Vt,{}),e.jsx(_t,{}),e.jsx(Ut,{}),e.jsx($t,{})]})})]})]})}function Ll({selectedChart:t,onChartChange:a,groupByFields:n,pivotByFields:r,metricsFields:l,sortByFields:o}){const c=s.useEditorStore(h=>h.showAIDialog),i=n.length>0||r.length>0||l.length>0,{setShowAIDialog:d}=s.useEditorActions(),u=s.useEditorStore(h=>h.card),{data:m}=s.useDashboardCardQuery(u);return e.jsxs("div",{"data-content":"Chart Configuration Panel",className:"flex w-[350px] flex-col",children:[e.jsxs("div",{className:"space-y-4 px-6 pt-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("h2",{className:"font-semibold",children:"Chart Configuration"})}),e.jsx(jl,{selectedChart:t,onChartChange:a}),e.jsx(vl,{selectedChart:t,onChartChange:a})]}),e.jsxs("div",{className:s.cn("flex justify-end gap-2 px-6 py-6"),children:[e.jsx("div",{className:s.cn("invisible",{visible:i||m}),children:e.jsx(ns,{})}),!c&&e.jsxs(s.Button,{onClick:()=>d(!c),variant:"outline",className:"h-8",size:"sm",children:[e.jsx(s.Sparkles,{className:"mr-2 size-4"}),"AI"]})]}),e.jsxs(s.ScrollArea,{className:"w-full flex-1 basis-0 px-6 pb-6",children:[e.jsx(Ml,{groupByFields:n,pivotByFields:r,metricsFields:l,sortByFields:o}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Rl({initialFilters:t,availableFields:a}={}){const[n,r]=A.useState(t||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});s.useEditorStore(N=>N.card.dataSource);const{columns:l,isLoading:o}=s.useColumns(),i=a||l||[],d={id:"default",qualifiedFieldName:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},u=N=>{const w=y=>{if(y.id===N){const D=i[0]||d,C=s.getDataType(D.dataType)==="date";return{...y,conditions:[...y.conditions,{id:`condition-${Date.now()}`,field:D,operator:C?"between":"=",value:C?[]:""}]}}return{...y,groups:y.groups.map(w)}};r(w(n))},m=N=>{const w=y=>{if(y.id===N){const D=i[0]||d,C=s.getDataType(D.dataType)==="date";return{...y,groups:[...y.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:D,operator:C?"between":"=",value:C?[]:""}],groups:[]}]}}return{...y,groups:y.groups.map(w)}};r(w(n))},h=(N,w)=>{const y=D=>D.id===N?{...D,conditions:D.conditions.filter(C=>C.id!==w)}:{...D,groups:D.groups.map(y)};r(y(n))},f=(N,w)=>{const y=D=>D.id===N?{...D,groups:D.groups.filter(C=>C.id!==w)}:{...D,groups:D.groups.map(y)};r(y(n))},g=(N,w,y,D)=>{if(y==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const C=I=>I.id===N?{...I,conditions:I.conditions.map(S=>S.id===w?{...S,[y]:D}:S)}:{...I,groups:I.groups.map(C)};r(C(n))},b=(N,w,y)=>{const D=C=>C.id===N?{...C,conditions:C.conditions.map(I=>I.id===w?{...I,...y}:I)}:{...C,groups:C.groups.map(D)};r(D(n))},p=(N,w)=>{const y=D=>D.id===N?{...D,logicalOperator:w}:{...D,groups:D.groups.map(y)};r(y(n))},j=(N,w)=>{const y=D=>D.id===N?{...D,negate:w}:{...D,groups:D.groups.map(y)};r(y(n))},x=(N,w,y)=>{const D=C=>C.id===N?{...C,conditions:s.arrayMove(C.conditions,w,y)}:{...C,groups:C.groups.map(D)};r(D(n))},v=(N,w,y)=>{const D=C=>C.id===N?{...C,groups:s.arrayMove(C.groups,w,y)}:{...C,groups:C.groups.map(D)};r(D(n))},k=N=>{if(!N||N.conditions.length===0&&N.groups.length===0)return"-- No filters defined";const w=D=>{let C="";typeof D.field=="object"?C=D.field.entityName?`${D.field.entityName}.${D.field.name}`:D.field.name:C=String(D.field);const I=D.operator;let S=D.value;if(D.field.dataType==="string"&&!["in","not in"].includes(D.operator))typeof S=="string"?S=`'${S}'`:Array.isArray(S)&&(S=`'${S.join(", ")}'`);else if(D.field.dataType==="date"||D.field.dataType==="datetime"||D.field.dataType==="timestamp")if(D.operator==="between"&&Array.isArray(S)&&S.length===2){const F=S[0]?`'${S[0]}'`:"NULL",T=S[1]?`'${S[1]}'`:"NULL";return`${C} BETWEEN ${F} AND ${T}`}else if((D.operator==="in"||D.operator==="not in")&&Array.isArray(S)){const F=S.map(T=>T?`'${T}'`:"NULL").join(", ");return`${C} ${I} (${F})`}else typeof S=="string"||S instanceof Date?S=`'${S}'`:Array.isArray(S)&&S.length>0&&(S=`'${S[0]}'`);else if(["in","not in"].includes(D.operator)){let F=[];Array.isArray(S)?F=S.map(T=>typeof T=="string"?`'${T}'`:String(T)):typeof S=="string"?F=S.split(",").map(T=>{const E=T.trim();return D.field.dataType==="string"?`'${E}'`:E}):typeof S=="number"&&(F=[String(S)]),S=`(${F.join(", ")})`}switch(I){case"contains":return typeof S=="string"?`${C} LIKE '%${S.replace(/'/g,"")}'`:`${C} LIKE '%${String(S)}'`;case"startsWith":return typeof S=="string"?`${C} LIKE '${S.replace(/'/g,"")}%'`:`${C} LIKE '${String(S)}%'`;case"endsWith":return typeof S=="string"?`${C} LIKE '%${S.replace(/'/g,"")}'`:`${C} LIKE '%${String(S)}'`;case"isNull":return`${C} IS NULL`;case"isNotNull":return`${C} IS NOT NULL`;default:return`${C} ${I} ${S}`}},y=D=>{const C=D.conditions.map(w),I=D.groups.map(E=>y(E)),S=[...C,...I].filter(Boolean);if(S.length===0)return"";const F=S.join(` ${D.logicalOperator} `),T=S.length>1?`(${F})`:F;return D.negate?`NOT ${T}`:T};return y(N)},R=n.conditions.length>0||n.groups.length>0;return{currentFilters:n,setCurrentFilters:r,availableFields:i,isLoading:o,addCondition:u,addGroup:m,removeCondition:h,removeGroup:f,updateCondition:g,updateConditionFields:b,updateGroupOperator:p,updateGroupNegate:j,reorderConditions:x,reorderGroups:v,generateSQLPreview:k,hasAnyFilters:R}}function Ol({children:t,className:a,delayDuration:n}){return e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{delayDuration:n,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:s.cn("w-[200px] overflow-hidden text-ellipsis whitespace-nowrap text-sm",a),children:t})}),e.jsx(s.PortalTooltipContent,{children:t})]})})}const Bl=t=>{switch(t){case"table":return e.jsx(s.Table,{className:"h-3 w-3"});case"view":return e.jsx(s.Eye,{className:"h-3 w-3"});case"dataset":return e.jsx(s.ChartColumn,{className:"h-3 w-3"});case"file":return e.jsx(s.File,{className:"h-3 w-3"});default:return e.jsx(s.Table,{className:"h-3 w-3"})}},Fl=t=>{if(t.qualifiedEntityName){const a=t.qualifiedEntityName.split(".");return a.length>1?a[0]:"default"}return"default"};function Pl({value:t,onValueChange:a,availableFields:n,placeholder:r="Select field",className:l="w-64"}){const[o,c]=A.useState(!1),i=A.useMemo(()=>{const d={};return n.forEach(u=>{const m=Fl(u);d[m]||(d[m]={}),d[m][u.entityId]||(d[m][u.entityId]=[]),d[m][u.entityId].push(u)}),d},[n]);return e.jsxs(s.Popover,{modal:!0,open:o,onOpenChange:c,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":o,className:s.cn("justify-between",!t&&"text-muted-foreground",l),children:[t?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(Ol,{children:[t.entityName,".",t.name]})}):r,e.jsx(s.ChevronsUpDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"z-50 w-80 p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search fields...",className:"h-9"}),e.jsx(s.CommandEmpty,{children:"No fields found."}),e.jsx(s.CommandList,{className:"max-h-80",children:Object.entries(i).map(([d,u])=>e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Database,{className:"h-3 w-3"}),d]}),children:Object.entries(u).map(([m,h])=>e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 bg-gray-50/50 px-2 py-1 text-xs font-medium text-gray-600",children:[Bl(h[0].entityType),e.jsx("span",{children:h[0].entityName})]}),h.map((f,g)=>e.jsxs(s.CommandItem,{value:f.id,onSelect:()=>{a(f),c(!1)},className:"overflow-x-auto",children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",(t==null?void 0:t.id)===f.id?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{className:"",children:f.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:f.description&&e.jsx("span",{children:f.description})})]})]},f.id+g))]},`${d}-${m}`))},d))})]})})]})}function Ms(t){var b;const a=s.useEditorStore(p=>p.card),{authToken:n}=s.useSemaphorContext(),r=s.useEditorStore(p=>p.card.config),l=r==null?void 0:r.joinPlan,o={...t,alias:t.name,label:"value",role:"groupby"},c={...t,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},i={...o,role:"sortby",direction:"asc"},d={joinPlan:l,groupByColumns:[o],metricColumns:[c],sortByColumns:[i]},u=((b=a.dataSource)==null?void 0:b.connectionId)||a.connectionId,{data:m,isPending:h,error:f}=s.useQuery({queryKey:["filterValues",t.entityId,t.name,t.qualifiedEntityName],queryFn:async()=>{try{return await s.postRequestRegular("https://semaphor.cloud/api/v1/query",(n==null?void 0:n.accessToken)||"",{connection_id:u,cardConfig:d,cardDataSource:a.dataSource})}catch(p){console.log(t),console.error("error",p)}},enabled:!!u,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((m==null?void 0:m.records)||[]).map(p=>({label:p.value||"BLANK",value:p.value||"BLANK",count:(p==null?void 0:p.count)||0})),isPending:h,error:f}}function zl({field:t,selected:a,onChange:n,placeholder:r="Select items...",className:l}){const[o,c]=Te.useState(!1),{filterValues:i}=Ms(t),d=m=>{n(a.filter(h=>h!==m))},u=m=>{a.includes(m)?n(a.filter(h=>h!==m)):n([...a,m])};return e.jsx("div",{className:s.cn("w-full",l),children:e.jsxs(s.Popover,{open:o,onOpenChange:c,modal:!0,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":o,className:"h-auto min-h-10 w-full justify-between p-2",children:[e.jsx("div",{className:"flex flex-1 flex-wrap gap-1",children:a.length>0?a.map(m=>{const h=i.find(f=>f.value===m);return e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[h==null?void 0:h.label,e.jsx("div",{className:"ml-1 rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:f=>{f.key==="Enter"&&d(m)},onMouseDown:f=>{f.preventDefault(),f.stopPropagation()},onClick:f=>{f.stopPropagation(),d(m)},children:e.jsx(s.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},m)}):e.jsx("span",{className:"text-muted-foreground",children:r})}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"z-50 w-fit overflow-auto p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search..."}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No results found."}),e.jsx(s.CommandGroup,{children:i.map((m,h)=>e.jsxs(s.CommandItem,{onSelect:()=>u(m.value),children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",a.includes(m.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:m.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:m.count})]})]},m.value+h))})]})]})})]})})}function Vl({field:t,value:a,onChange:n,placeholder:r="Select value...",className:l}){const{filterValues:o,isPending:c,error:i}=Ms(t);return c?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):i?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsxs(s.Select,{value:a,onValueChange:n,children:[e.jsx(s.SelectTrigger,{className:l||"flex-1",children:e.jsx(s.SelectValue,{placeholder:r,children:a})}),e.jsx(s.SelectContent,{children:o.map((d,u)=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:d.value,children:d.label},d.value+u))})]})}function _l({value:t,operator:a,onChange:n,className:r}){var d;const{tokenProps:l}=s.useSemaphorContext(),o=(d=l==null?void 0:l.params)==null?void 0:d.timeZone,c=A.useMemo(()=>{if(t){if(a==="between"||a==="not between"){if(Array.isArray(t)&&t.length===2){const u=t[0]?new Date(t[0]):void 0,m=t[1]?new Date(t[1]):void 0;if(u&&m)return{from:u,to:m}}}else if(a==="="||a==="!="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:u,to:u}}}else if(a===">"||a===">="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:u,to:void 0}}}else if(a==="<"||a==="<="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:void 0,to:u}}}else if((a==="in"||a==="not in")&&Array.isArray(t)&&t.length>0){const u=new Date(t[0]),m=t.length>1?new Date(t[t.length-1]):u;if(!isNaN(u.getTime()))return{from:u,to:m}}}},[t,a]),i=u=>{if(!u){n(void 0);return}if(u.from&&u.to)n([u.from.toISOString(),u.to.toISOString()]);else if(u.from){const m=new Date(u.from);m.setHours(23,59,59,999),n([u.from.toISOString(),m.toISOString()])}else if(u.to){const m=new Date(u.to);m.setHours(0,0,0,0),n([m.toISOString(),u.to.toISOString()])}};return e.jsx(s.DateRangePicker,{value:c,onChange:i,timezone:o,showRelativeTab:!0,className:r,placeholder:"Select date..."})}const Ul=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],$l=["=","!=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],Yl=["=","!=",">",">=","<","<=","in","not in","isNull","isNotNull"],ql=["=","!=","isNull","isNotNull"],Gl=["between","isNull","isNotNull"],Hl={"=":"Equals","!=":"Not Equals",">":"Greater Than",">=":"Greater Than or Equal","<":"Less Than","<=":"Less Than or Equal",contains:"Contains",startsWith:"Starts With",endsWith:"Ends With",in:"In","not in":"Not In",between:"Between",isNull:"Is Null",isNotNull:"Is Not Null"};function Xs(t){return Hl[t]||s.titleCase(t)}function Wl(t){switch(t){case"string":return $l;case"number":return Yl;case"boolean":return ql;case"date":return Gl;default:return Ul}}function Ht({condition:t,index:a,groupId:n,groupLogicalOperator:r,onUpdateCondition:l,onRemoveCondition:o,onUpdateGroupOperator:c,availableFields:i,updateConditionFields:d}){const{attributes:u,listeners:m,setNodeRef:h,transform:f,transition:g,isDragging:b}=s.useSortable({id:t.id}),{isPending:p,error:j}=Ms(t.field),x={transform:s.CSS.Transform.toString(f),transition:g};return e.jsxs("div",{ref:h,style:x,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${b?"z-50 opacity-50":""}`,children:[e.jsx("div",{...u,...m,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 flex-shrink-0 text-gray-400"})}),a>0&&e.jsxs(s.Select,{value:r,onValueChange:v=>c(n,v),children:[e.jsx(s.SelectTrigger,{className:"w-24",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"AND",children:"AND"}),e.jsx(s.SelectItem,{value:"OR",children:"OR"})]})]}),a===0&&e.jsx("div",{className:"w-24"}),e.jsx(Pl,{value:t.field,onValueChange:v=>{const k=v,R=s.getDataType(k.dataType)==="date";d(n,t.id,{field:k,value:"",operator:R?"between":"="})},availableFields:i,placeholder:"Select field",className:"w-64"}),e.jsxs(s.Select,{value:t.operator,onValueChange:v=>{v==="in"||v==="not in"?d(n,t.id,{operator:v,value:[]}):v==="isNull"||v==="isNotNull"?d(n,t.id,{operator:v,value:null}):d(n,t.id,{operator:v,value:""})},children:[e.jsx(s.SelectTrigger,{className:"w-32",children:e.jsx(s.SelectValue,{children:t.operator?Xs(t.operator):""})}),e.jsx(s.SelectContent,{children:Wl(s.getDataType(t.field.dataType)).map(v=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:v,children:Xs(v)},v))})]}),t.operator==="isNull"||t.operator==="isNotNull"?e.jsx("div",{className:"flex-1"}):s.getDataType(t.field.dataType)==="string"?t.operator==="in"||t.operator==="not in"?p?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):j?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsx(zl,{field:t.field,selected:Array.isArray(t.value)&&t.value.every(v=>typeof v=="string")?t.value:[],onChange:v=>d(n,t.id,{value:v}),placeholder:`Select values for ${t.operator}...`,className:"flex-1"}):["contains","startsWith","endsWith"].includes(t.operator)?e.jsx(s.Input$1,{value:typeof t.value=="string"?t.value:"",onChange:v=>d(n,t.id,{value:v.target.value}),className:"flex-1",placeholder:t.operator.charAt(0).toUpperCase()+t.operator.slice(1)+"..."}):e.jsx(Vl,{field:t.field,value:typeof t.value=="string"?t.value:"",onChange:v=>d(n,t.id,{value:v}),placeholder:"Select value...",className:"flex-1"}):s.getDataType(t.field.dataType)==="boolean"?e.jsxs(s.Select,{value:typeof t.value=="boolean"?String(t.value):"",onValueChange:v=>d(n,t.id,{value:v==="true"}),children:[e.jsx(s.SelectTrigger,{className:"flex-1",children:e.jsx(s.SelectValue,{placeholder:"Select value..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"true",children:"True"}),e.jsx(s.SelectItem,{value:"false",children:"False"})]})]}):s.getDataType(t.field.dataType)==="date"?e.jsx(_l,{value:t.value,operator:t.operator,onChange:v=>d(n,t.id,{value:v}),className:"flex-1"}):e.jsx(s.Input$1,{value:typeof t.value=="string"||typeof t.value=="number"?t.value:"",onChange:v=>l(n,t.id,"value",v.target.value),className:"flex-1",placeholder:t.operator==="in"||t.operator==="not in"?"value1, value2, value3":"Value"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 flex-shrink-0 p-0",onClick:()=>o(n,t.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})}function Kl({group:t,depth:a,parentGroupId:n,onUpdateGroupOperator:r,onUpdateGroupNegate:l,onRemoveGroup:o,onUpdateCondition:c,onUpdateField:i,onRemoveCondition:d,onReorderConditions:u,onReorderGroups:m,onAddCondition:h,onAddGroup:f,availableFields:g,renderFilterGroup:b,updateConditionFields:p}){const{attributes:j,listeners:x,setNodeRef:v,transform:k,transition:R,isDragging:N}=s.useSortable({id:t.id}),w={transform:s.CSS.Transform.toString(k),transition:R},y=C=>{const{active:I,over:S}=C;if(S&&I.id!==S.id){const F=t.conditions.findIndex(E=>E.id===I.id),T=t.conditions.findIndex(E=>E.id===S.id);F!==-1&&T!==-1&&u(t.id,F,T)}},D=C=>{const{active:I,over:S}=C;if(S&&I.id!==S.id&&n){const F=t.groups.findIndex(E=>E.id===I.id),T=t.groups.findIndex(E=>E.id===S.id);F!==-1&&T!==-1&&m(n,F,T)}};return e.jsxs("div",{ref:v,style:w,className:`rounded-lg ${a>0?"mt-2 border border-border":""} ${N?"z-50 opacity-50":""}`,children:[a>0&&e.jsxs("div",{className:"flex items-center justify-between rounded-t-lg bg-muted p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{...j,...x,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(s.Button,{variant:t.negate?"default":"outline",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>l(t.id,!t.negate),children:"NOT"}),e.jsxs(s.Select,{value:t.logicalOperator,onValueChange:C=>r(t.id,C),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-20",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"OR",children:"OR"})]})]}),e.jsx("span",{className:"text-sm font-medium",children:"Group"})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>n&&o(n,t.id),children:e.jsx(s.Trash2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:`p-3 ${a>0?"":"px-0"}`,children:[e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:y,children:e.jsx(s.SortableContext,{items:t.conditions.map(C=>C.id),strategy:s.verticalListSortingStrategy,children:t.conditions.map((C,I)=>e.jsx(Ht,{condition:C,index:I,groupId:t.id,groupLogicalOperator:t.logicalOperator,onUpdateCondition:c,onUpdateField:i,onRemoveCondition:d,onUpdateGroupOperator:r,availableFields:g,updateConditionFields:p},C.id))})}),e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:D,children:e.jsx(s.SortableContext,{items:t.groups.map(C=>C.id),strategy:s.verticalListSortingStrategy,children:t.groups.map(C=>b(C,a+1,t.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(s.Button,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>h(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>f(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function Jl({filters:t,availableFields:a,onSave:n,onClearAll:r,onCancel:l}){const{currentFilters:o,availableFields:c,isLoading:i,addCondition:d,addGroup:u,removeCondition:m,removeGroup:h,updateCondition:f,updateConditionFields:g,updateGroupOperator:b,updateGroupNegate:p,reorderConditions:j,reorderGroups:x,generateSQLPreview:v,hasAnyFilters:k,setCurrentFilters:R}=Rl({initialFilters:t,availableFields:a}),N=s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),[w,y]=A.useState(!1),D=(S,F,T)=>{const E=M=>M.id===S?{...M,conditions:M.conditions.map(B=>B.id===F?{...B,field:T,dataType:T.dataType}:B)}:{...M,groups:M.groups.map(E)};R(E(o))},C=(S,F=0,T)=>F===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(s.DndContext,{sensors:N,collisionDetection:s.closestCenter,onDragEnd:E=>{const{active:M,over:B}=E;if(B&&M.id!==B.id){const L=S.conditions.findIndex(P=>P.id===M.id),O=S.conditions.findIndex(P=>P.id===B.id);L!==-1&&O!==-1&&j(S.id,L,O)}},children:e.jsx(s.SortableContext,{items:S.conditions.map(E=>E.id),strategy:s.verticalListSortingStrategy,children:S.conditions.map((E,M)=>e.jsx(Ht,{condition:E,index:M,groupId:S.id,groupLogicalOperator:S.logicalOperator,onUpdateCondition:f,onUpdateField:D,onRemoveCondition:m,onUpdateGroupOperator:b,availableFields:c,updateConditionFields:g},E.id))})}),e.jsx(s.DndContext,{sensors:N,collisionDetection:s.closestCenter,onDragEnd:E=>{const{active:M,over:B}=E;if(B&&M.id!==B.id){const L=S.groups.findIndex(P=>P.id===M.id),O=S.groups.findIndex(P=>P.id===B.id);L!==-1&&O!==-1&&x(S.id,L,O)}},children:e.jsx(s.SortableContext,{items:S.groups.map(E=>E.id),strategy:s.verticalListSortingStrategy,children:S.groups.map(E=>C(E,F+1,S.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(s.Button,{size:"sm",className:"h-7 text-xs",variant:"outline",onClick:()=>d(S.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),w&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>u(S.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},S.id):e.jsx(Kl,{group:S,depth:F,parentGroupId:T,onUpdateGroupOperator:b,onUpdateGroupNegate:p,onRemoveGroup:h,onUpdateCondition:f,onUpdateField:D,onRemoveCondition:m,onReorderConditions:j,onReorderGroups:x,onAddCondition:d,onAddGroup:u,availableFields:c,renderFilterGroup:C,updateConditionFields:g},S.id),I=s.getFilterCount(t);return e.jsxs("div",{className:"space-y-4",children:[e.jsx(s.Card,{children:e.jsx(s.CardContent,{className:"p-4",children:e.jsxs("div",{className:"space-y-4",children:[i?e.jsxs("div",{className:"flex items-center justify-center p-4",children:[e.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-gray-300 border-t-gray-600"}),e.jsx("span",{className:"ml-2 text-sm text-gray-600",children:"Loading columns..."})]}):C(o),e.jsx("div",{className:"mt-4 border-t border-border pt-4",children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{id:"advanced-mode",checked:w,onCheckedChange:S=>y(!!S)}),e.jsx("label",{htmlFor:"advanced-mode",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Advanced mode (enable grouping)"})]})}),k&&e.jsxs("div",{className:"mt-4 border-t border-border pt-4",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"SQL WHERE Clause Preview"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap font-mono text-xs text-muted-foreground",children:v(o)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"outline",onClick:l,children:"Cancel"}),I>0&&e.jsx(s.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(s.Button,{size:"sm",onClick:()=>n(k?o:null),children:"Apply Filters"})]})]})}function Ql({cardId:t,filters:a,onFiltersChange:n,onClearFilters:r,availableFields:l,isOpen:o,onOpenChange:c}){const i=u=>{n(t,u),c(!1)},d=()=>{r(t),c(!1)};return e.jsxs(s.Dialog,{modal:!1,open:o,onOpenChange:c,children:[o&&e.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),e.jsxs(s.DialogContent,{className:"max-h-[80vh] max-w-4xl overflow-y-auto",onInteractOutside:u=>{u.preventDefault()},children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Card Filters"}),e.jsx(s.DialogDescription,{children:"Add filters to the card to limit the data that is displayed."})]}),e.jsx(Jl,{filters:a,availableFields:l,onSave:i,onCancel:()=>c(!1),onClearAll:d})]})]})}function Xl({activeCardId:t,sourceFields:a,getFieldsForContainer:n,setFieldsForContainer:r}){var g;const[l,o]=A.useState(null),c=s.useEditorStore(b=>b.card),i=(g=c==null?void 0:c.config)==null?void 0:g.joinPlan,d=[...a,...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")],u=A.useCallback(b=>b.startsWith("card-")?null:b.startsWith("source-")||a.find(p=>p.id===b)?"source":n("groupBy").find(p=>p.id===b)?"groupBy":n("metrics").find(p=>p.id===b)?"metrics":n("pivotBy").find(p=>p.id===b)?"pivotBy":n("sortBy").find(p=>p.id===b)?"sortBy":null,[a,n]),m=A.useCallback(b=>{o(b.active.id)},[]),h=A.useCallback(b=>{const{active:p,over:j}=b;if(!j||!t){o(null);return}const x=p.id,v=j.id,k=u(x),R=u(v)||v;if(R==="sortBy"){if(k==="source"){const N=a.find(y=>y.id===x);if(!N){o(null);return}if(!(n("groupBy").some(y=>y.name===N.name&&y.qualifiedEntityName===N.qualifiedEntityName)||n("metrics").some(y=>y.name===N.name&&y.qualifiedEntityName===N.qualifiedEntityName))){o(null);return}}else if(k==="pivotBy"){o(null);return}else if(k!=="groupBy"&&k!=="metrics"&&k!=="sortBy"){o(null);return}}if(k==="source"&&R==="sortBy"){const N=[...a].find(D=>D.id===x);if(!N){o(null);return}const w=n("sortBy");if(s.fieldAlreadyExists(N,w)){o(null);return}const y=s.getNewField(N,"sortBy",w);o(null),r("sortBy",[...w,y]);return}if(k==="source"&&R!=="source"&&R!=="sortBy"){const N=[...a].find(C=>C.id===x);if(!N){o(null);return}const w=[...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")];if(w.length>0){const C=w[0].qualifiedEntityName;if(!C){o(null);return}if(C!==N.qualifiedEntityName&&N.qualifiedEntityName)if(i){if(!s.areEntitiesJoined(C,N.qualifiedEntityName,i)){s.showJoinRequiredNotification(),o(null);return}}else{s.showJoinRequiredNotification(),o(null);return}}const y=n(R);if(s.fieldAlreadyExists(N,y)){o(null);return}const D=s.getNewField(N,R,y);o(null),r(R,[...y,D]);return}if(k&&R&&k!=="source"&&R!=="source"&&k!==R){const N=n(k),w=n(R),y=N.find(I=>I.id===x);if(!y){o(null);return}const D=s.getNewField(y,R,w);if(o(null),R==="sortBy"){s.fieldAlreadyExists(y,w)||r(R,[...w,D]);return}const C=N.filter(I=>I.id!==x);r(k,C),r(R,[...w,D]);return}if(k&&R&&k===R&&k!=="source"){const N=n(k),w=N.findIndex(D=>D.id===x),y=N.findIndex(D=>D.id===v);if(w!==y){const D=s.arrayMove(N,w,y);r(k,D)}}o(null)},[t,a,n,r,u,i]),f=l?d.find(b=>b.id===l):null;return{activeId:l,activeField:f,handleDragStart:m,handleDragEnd:h}}function Zl({dashboardFilterCount:t=0,cardFilterCount:a=0,clickFilterCount:n=0,onClick:r,className:l,showIcon:o=!0}){const c=t+a+n,i=c>0,d=t>0,u=a>0,m=n>0,h=e.jsxs(e.Fragment,{children:[o&&e.jsx(s.Filter,{className:"h-3.5 w-3.5"}),i&&e.jsx("span",{className:"font-medium",children:c})]}),f=e.jsx(s.Button,{variant:i?"secondary":"outline",size:"sm",onClick:r,className:s.cn("h-8 gap-1.5 transition-all",l),children:h});return i?e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{delayDuration:200,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:f}),e.jsx(s.TooltipContent,{side:"bottom",align:"start",className:"p-2 text-xs",children:e.jsxs("div",{className:"space-y-1.5",children:[d&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-2 w-2 rounded-full bg-purple-500"}),e.jsxs("span",{children:[t," Dashboard filter",t!==1?"s":""]})]}),u&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-2 w-2 rounded-full bg-blue-500"}),e.jsxs("span",{children:[a," Card filter",a!==1?"s":""]})]}),m&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-2 w-2 rounded-full bg-gray-500"}),e.jsxs("span",{children:[n," Click filter",n!==1?"s":""]})]})]})})]})}):f}function eo({onAdvancedToggle:t,onDebugToggle:a,onAccept:n}){const{currentUser:r}=s.useCurrentUserInfo();r==null||r.role;const[l,o]=A.useState(!1),c=s.useEditorStore(x=>x.isDevMode),i=s.useEditorStore(x=>x.card),d=s.useEditorStore(x=>x.card.dataSource);s.isExplorerCard(i);const{config:u}=A.useContext(s.SemaphorContext).tokenProps,m=(u==null?void 0:u.showAdvancedMode)!==!1,{setIsDevMode:h}=s.useEditorActions(),f=s.useEditorStore(x=>x.showAIDialog),g=s.useEditorStore(x=>x.frame),b=s.useManagementStore(x=>x.selectedVisual),p=(b==null?void 0:b.id)===(g==null?void 0:g.id),{setShowAIDialog:j}=s.useEditorActions();return e.jsxs("div",{className:s.cn("flex items-center justify-between px-6 py-3",f&&"justify-end",!m&&"justify-end"),children:[m&&t&&!f&&e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.SmallSwitch,{className:s.cn("",{}),checked:c,onCheckedChange:()=>h(!c),id:"advanced-mode"}),e.jsx("label",{htmlFor:"advanced-mode",className:"text-sm font-medium",children:"Advanced Mode"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Ds,{}),n&&!p&&e.jsx(ws,{variant:"default"}),p&&e.jsx($n,{}),a&&s.isDevEnv]}),l&&e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(d==null?void 0:d.selectedEntities)||[],open:l,onOpenChange:o,dataSource:d||s.EMPTY_DATA_SOURCE,fallbackDataSource:s.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]})}function so({activeView:t,onViewChange:a}){const n=s.useEditorStore(l=>l.card),{errorMessage:r}=s.useDashboardCardQuery(n);return e.jsx(s.Tabs,{value:t,onValueChange:l=>a(l),children:e.jsxs(s.TabsList,{className:"h-9 w-fit gap-1 bg-background p-0",children:[e.jsx(s.TabsTrigger,{value:"chart",className:"rounded-md transition data-[state=active]:bg-muted",children:"Chart"}),e.jsx(s.TabsTrigger,{value:"table",className:"rounded-md transition data-[state=active]:bg-muted",children:"Results"}),n.type!=="kpi"&&e.jsx(s.TabsTrigger,{value:"sql",className:s.cn("rounded-md transition data-[state=active]:bg-muted",r&&"text-destructive data-[state=active]:bg-destructive/10 data-[state=active]:text-destructive"),children:r?"Error":"Info"})]})})}const to=[{value:"10",label:"Top 10"},{value:"20",label:"Top 20"},{value:"50",label:"Top 50"},{value:"100",label:"Top 100"},{value:"200",label:"Top 200"},{value:"500",label:"Top 500"},{value:"1000",label:"Top 1000"}];function ao(){var d,u;const t=s.useEditorStore(m=>m.card),{updateRowLimit:a}=s.useEditorActions(),[n,r]=A.useState(!1),[l,o]=A.useState(""),c=m=>{if(m==="custom"){r(!0);return}r(!1),a(t.id,parseInt(m))},i=m=>{const h=m.target.value;o(h),h&&!isNaN(parseInt(h))&&a(t.id,parseInt(h))};return e.jsx("div",{className:"flex items-center gap-2",children:n?e.jsx(s.Input,{type:"number",value:l,onChange:i,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(s.Select,{value:((u=(d=t.config)==null?void 0:d.rowLimit)==null?void 0:u.toString())||"100",onValueChange:c,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-24 border-none px-1 [&>svg]:hidden",children:e.jsx(s.SelectValue,{placeholder:"Select limit"})}),e.jsx(s.SelectContent,{children:to.map(m=>e.jsx(s.SelectItem,{value:m.value,children:m.label},m.value))})]})})}function no({isOpen:t,onClose:a}){const n=mt(a,{enabled:t}),r=s.useEditorStore(m=>{var h;return((h=m.card.customCardPreferences)==null?void 0:h.url)||""}),l=s.useEditorStore(m=>m.card),o=s.useEditorStore(m=>{var h;return((h=m.card.customCardPreferences)==null?void 0:h.pluginChartType)||""}),c=s.useEditorStore(m=>{var h;return((h=m.card.customCardPreferences)==null?void 0:h.settings)||{}}),{data:i}=s.useDashboardCardQuery(l),{getCard:d}=s.useCustomVisual(r),u=A.useMemo(()=>!r||r.trim()===""?null:d("Chart Settings"),[d,r]);return e.jsx("div",{ref:n,className:s.cn("absolute right-0 top-0 z-40 h-full w-[350px] border-l bg-background shadow-lg transition-transform duration-300",t?"translate-x-0":"translate-x-full"),style:{willChange:"transform"},tabIndex:t?0:-1,"aria-hidden":!t,children:e.jsxs("div",{className:"flex h-full flex-col p-4 px-5 pr-4",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between",children:[e.jsx("h2",{className:"text-base font-semibold",children:"Chart Settings"}),e.jsx(s.IconButton,{"aria-label":"Hide Chart Settings",tooltip:"Hide",onClick:a,className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:e.jsx(s.X,{className:"size-3.5"})})]}),e.jsx("div",{className:"h-full min-h-0 flex-1",children:u&&e.jsx(A.Suspense,{fallback:e.jsx("div",{children:"Loading chart settings..."}),children:e.jsx(u,{chartData:(i==null?void 0:i.records)||[],chartType:o,settings:c})})})]})})}function ro(){const{authToken:t,tokenProps:a}=s.useSemaphorContext(),{currentUser:n}=s.useCurrentUserInfo(),r=s.useMutation({mutationFn:async l=>{if(!(t!=null&&t.accessToken))throw new Error("No authentication token available");const c="https://semaphor.cloud/api/v1/feedback",i={...l,user:n,tokenContext:a},d=await s.postRequestRegular(c,t.accessToken,i,"POST");if(!d||!d.success)throw new Error((d==null?void 0:d.error)||"Failed to send feedback");return d},onSuccess:l=>{s.ue.success(`Feedback sent successfully! Issue: ${l.issueNumber}`,{duration:5e3})},onError:l=>{console.error("Feedback submission error:",l),s.ue.error("Failed to send feedback. Please try again later.",{duration:5e3})}});return{sendFeedback:r.mutate,sendFeedbackAsync:r.mutateAsync,isLoading:r.isPending,isSuccess:r.isSuccess,isError:r.isError,error:r.error,data:r.data,reset:r.reset}}function lo(t,a,n){return{category:t,userMessage:n,systemState:a,metadata:{url:window.location.href,userAgent:navigator.userAgent,timestamp:new Date().toISOString(),viewport:`${window.innerWidth}x${window.innerHeight}`}}}function oo({open:t,onOpenChange:a,feedbackData:n}){var p,j,x,v,k,R;const[r,l]=A.useState(""),[o,c]=A.useState(!1),{sendFeedback:i,isLoading:d,isSuccess:u,data:m,reset:h}=ro(),f=()=>{const N={...n,userMessage:r.trim()||void 0};i(N)},g=()=>{l(""),c(!1),h(),a(!1)},b={category:n.category,error:{message:(p=n.systemState)==null?void 0:p.errorMessage,sql:(j=n.systemState)==null?void 0:j.generatedSql,errorSql:(x=n.systemState)==null?void 0:x.errorSql},cardConfig:(v=n.systemState)==null?void 0:v.cardConfig,dataSource:(k=n.systemState)==null?void 0:k.dataSource,filters:(R=n.systemState)==null?void 0:R.dashboardFilters,metadata:n.metadata};return e.jsx(s.Dialog,{open:t,onOpenChange:g,children:e.jsxs(s.DialogContent,{className:"max-w-2xl",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:u?"Feedback Sent Successfully":"Report Query Generation Issue"}),e.jsx(s.DialogDescription,{children:u?`Your feedback has been submitted with issue number: ${m==null?void 0:m.issueNumber}`:"Help us improve by reporting this query generation issue. Your feedback will be sent to our support team."})]}),!u&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"message",children:"Additional Information (Optional)"}),e.jsx(s.Textarea,{id:"message",placeholder:"Please describe what you were trying to do when this error occurred...",value:r,onChange:N=>l(N.target.value),className:"min-h-[100px] resize-none ring-inset focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-0",disabled:d})]}),e.jsxs(s.Collapsible,{open:o,onOpenChange:c,children:[e.jsx(s.CollapsibleTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"ghost",size:"sm",className:"flex w-full items-center justify-between p-2 hover:bg-muted",children:[e.jsx("span",{className:"text-sm font-medium",children:"View data to be sent"}),o?e.jsx(s.ChevronDown,{className:"h-4 w-4"}):e.jsx(s.ChevronRight,{className:"h-4 w-4"})]})}),e.jsx(s.CollapsibleContent,{children:e.jsx(s.ScrollArea,{className:"h-[300px] w-full rounded-md border bg-muted/50 p-4",children:e.jsx("div",{className:"text-xs",children:e.jsx(s.CodeHighlighter,{code:JSON.stringify(b,null,2),language:"json"})})})})]})]}),e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:g,disabled:d,children:"Cancel"}),e.jsx(s.Button,{onClick:f,disabled:d,className:"min-w-[100px]",children:d?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Sending..."]}):"Send Feedback"})]})]}),u&&e.jsxs("div",{className:"flex flex-col items-center space-y-4 py-6",children:[e.jsx(ma,{className:"h-12 w-12 text-green-600"}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-lg font-medium",children:"Thank you for your feedback!"}),e.jsxs("p",{className:"mt-2 text-sm text-muted-foreground",children:["Issue Number:"," ",e.jsx("span",{className:"font-mono font-medium",children:m==null?void 0:m.issueNumber})]}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Our support team will review your feedback and take appropriate action."})]}),e.jsx(s.Button,{onClick:g,className:"mt-4",children:"Close"})]})]})})}var Wt=(t=>(t.QUERY_GENERATION="query-generation",t))(Wt||{});function io({activeView:t,onViewChange:a,showDebug:n,onDebugToggle:r,onAccept:l,onClear:o,onAdvancedToggle:c,onFiltersClick:i,filterCount:d,activeCard:u,columns:m,columnsLoading:h,columnsError:f}){var _;const g=s.useEditorStore(J=>J.card),b=s.useDashboardStore(J=>J.filterValues),p=(b==null?void 0:b.length)||0,{updateCardConfig:j,setCard:x,updateCardInFrame:v,setCardId:k}=s.useEditorActions(),{updateCardId:R}=s.useDashboardActions(),[N,w]=A.useState(null),y=s.useEditorStore(J=>J.showAIDialog),[D,C]=A.useState(!1),[I,S]=A.useState(!1),[F,T]=A.useState(null),{isConsoleMode:E}=s.useDashboardPreferences(),M=s.useEditorStore(J=>{var z;return((z=J.card.customCardPreferences)==null?void 0:z.url)&&J.card.type==="custom"}),{data:B,errorMessage:L,isLoading:O,isFetching:P,errorSql:K,pagination:$}=s.useDashboardCardQuery(u),te=(J,z)=>{const U={...u,paginationConfig:{page:J+1,pageSize:z}};x(U),v(U)};function X(){return e.jsx("div",{className:"border-b border-border bg-background p-4",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Active Card Config"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(g.config||{},null,2)})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Dashboard Filters"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(b||{},null,2)})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Card Data Source State"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(u.dataSource||{},null,2)})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"mb-2 text-sm font-medium",children:["Columns (",m.length,")"]}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:h?"Loading...":f?"Error loading columns":JSON.stringify(m.slice(0,5),null,2)})]})]})})}const q=J=>{if(!g.config)return;if(!J.length){j(g.id,{...g.config,sortByColumns:[]});return}const z=g.config,U=J.map(({id:Z,desc:le})=>{var Y,W;const V=(Y=z.metricColumns)==null?void 0:Y.find(re=>re.label===Z),se=(W=z.groupByColumns)==null?void 0:W.find(re=>re.label===Z),ne=V||se;return ne?{id:s.getFieldId("sortBy",ne),name:ne.name,dataType:ne.dataType,label:ne.label,qualifiedEntityName:ne.qualifiedEntityName,entityId:ne.entityId,entityName:ne.entityName,entityType:ne.entityType,role:"sortby",direction:le?"desc":"asc"}:null}).filter(Z=>Z!==null);j(g.id,{...z,sortByColumns:U})},H=A.useMemo(()=>{var J,z;return(z=(J=g.config)==null?void 0:J.sortByColumns)==null?void 0:z.map(U=>({id:U.label,desc:U.direction==="desc"}))},[(_=g.config)==null?void 0:_.sortByColumns]);return e.jsxs("div",{className:"relative flex w-0 grow flex-col",children:[e.jsx(eo,{showDebug:n,onDebugToggle:r,onAccept:l,onClear:o,onAdvancedToggle:c,onFiltersClick:i,filterCount:d}),n&&X(),e.jsxs("div",{className:"group/visualization relative flex h-full max-w-full grow flex-col pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 px-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t==="chart"&&y&&e.jsx(Mt,{variant:"outline"}),e.jsx(so,{activeView:t,onViewChange:a}),i&&e.jsx(Zl,{dashboardFilterCount:p,cardFilterCount:d,onClick:i,className:"h-8"}),e.jsx("div",{className:"ml-2",children:e.jsx(ao,{})}),y&&e.jsx(ns,{})]}),e.jsx("div",{className:s.cn("flex grow items-center justify-end"),children:t==="chart"&&e.jsx(Lt,{})})]}),!D&&M&&e.jsx(s.IconButton,{"aria-label":"Open Chart Settings",tooltip:"Open Chart Settings",onClick:()=>C(!0),className:"absolute right-5 top-1/2 z-40 size-10 -translate-y-1/2 rounded-full border border-border bg-background shadow-lg hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",children:e.jsx(s.Settings2,{className:"size-4"})}),e.jsxs("div",{className:"mt-3 flex grow flex-col",children:[t==="chart"&&e.jsx("div",{className:"flex grow flex-col pb-6",children:e.jsx(Rt,{})}),t==="table"&&(B==null?void 0:B.records)&&e.jsx("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 p-6",children:e.jsx(s.TableVisual,{card:u,data:(B==null?void 0:B.records)||[],paginationMetadata:$,onPaginationChange:te,isLoading:O||P,onSortChange:q,sortState:H})}),t==="sql"&&e.jsx("div",{className:"px-6",children:e.jsxs("div",{className:"rounded-md bg-background",children:[e.jsxs("div",{className:"mb-2",children:[E&&e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Card ID:"}),e.jsx(s.EditableText,{value:g.id,onSave:J=>{const z=s.sanitizeCardId(J);if(!z){w("Card ID cannot be empty");return}const U=R(g.id,z);if(U.success){k(z);const Z={...g,id:z};x(Z),v(Z),w(null),s.ue.success("Card ID updated successfully")}else w(U.error||"Failed to update Card ID"),s.ue.error(U.error||"Failed to update Card ID")},isEditable:!0,placeholder:"Enter card ID",displayClassName:"font-mono text-xs text-muted-foreground hover:text-foreground",inputClassName:"font-mono text-xs"}),e.jsx(s.CopyButton,{text:g.id,className:"h-5 w-5"})]}),N&&e.jsx("p",{className:"text-xs text-destructive",children:N})]}),L||K?e.jsx(St,{error:L,errorSql:K,onSendFeedback:()=>{const J=lo(Wt.QUERY_GENERATION,{cardConfig:g.config,dataSource:u.dataSource,dashboardFilters:b,errorMessage:L,errorSql:K,generatedSql:B==null?void 0:B.sql});T(J),S(!0)}}):e.jsxs(e.Fragment,{children:[(B==null?void 0:B.sql)&&e.jsx("h3",{className:"mb-1 px-2 font-mono text-xs font-medium",children:"Generated SQL Query"}),e.jsx(wt,{sql:B==null?void 0:B.sql,error:L,errorSql:K})]})]})})]}),e.jsx(no,{isOpen:D,onClose:()=>C(!1)}),F&&e.jsx(oo,{open:I,onOpenChange:S,feedbackData:F})]})]})}function co({activeField:t}){const[a,n]=A.useState(!0);return A.useEffect(()=>{t&&n(!0)},[t]),t?e.jsxs("div",{className:`flex max-w-[300px] items-center gap-2 rounded-lg border border-blue-500 bg-background p-2 shadow-lg transition-all duration-200 ${a?"scale-100 opacity-100":"scale-95 opacity-0"}`,children:[e.jsx(s.GripVertical,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx(As,{dataType:t.dataType}),e.jsx("span",{className:"overflow-hidden text-ellipsis whitespace-nowrap text-sm dark:text-muted-foreground",children:t.label||t.name})]}):null}const uo=()=>{const t=console.error;console.error=(...r)=>{r.length>0&&typeof r[0]=="string"&&r[0].includes("ResizeObserver loop completed with undelivered notifications")||t.apply(console,r)};const a=r=>{if(r.message&&(r.message.includes("ResizeObserver loop completed with undelivered notifications")||r.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),r.stopPropagation(),!1},n=r=>{var l;if((l=r.reason)!=null&&l.message&&(r.reason.message.includes("ResizeObserver loop completed with undelivered notifications")||r.reason.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),!1};return window.addEventListener("error",a,!0),window.addEventListener("unhandledrejection",n,!0),()=>{console.error=t,window.removeEventListener("error",a,!0),window.removeEventListener("unhandledrejection",n,!0)}};function mo(){var X,q;const[t,a]=A.useState("chart"),[n,r]=A.useState(!1),[l,o]=A.useState(!1),[c,i]=A.useState(!0),d=s.useEditorStore(H=>H.showAIDialog),u=s.useDashboardStore(H=>H.isVisualEditing),{setCardType:m}=s.useEditorActions(),h=s.useEditorStore(H=>H.card.type);A.useEffect(()=>uo(),[]);const f=()=>{console.log("Accept clicked - would save/apply current configuration")},g=()=>{console.log("Clear clicked - would reset all configurations")},b=()=>{console.log("Advanced mode toggled")},p=()=>{o(!0)},j=H=>{m(H)},x=s.useEditorStore(H=>H.frame),v=s.useEditorStore(H=>H.card);s.useEditorStore(H=>H.activeTabCardId),s.useEditorStore(H=>H.actions.getAvailableFields);const{addCard:k,removeCard:R,updateCard:N,setActiveCard:w,updateFilters:y}=s.useEditorActions(),{columns:D=[],isLoading:C,error:I}=s.useColumns(),S=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),F=v,{getFieldsForContainer:T,setFieldsForContainer:E}=Is(F),{activeField:M,handleDragStart:B,handleDragEnd:L}=Xl({activeCardId:x.activeCardId,sourceFields:D,getFieldsForContainer:T,setFieldsForContainer:E}),O=(H,_)=>{_&&y(H,_)},P=H=>{var _;N(H,{config:{...(_=x.cards.find(J=>J.id===H))==null?void 0:_.config,filters:void 0}})},K=D,$=H=>{if(!H)return 0;let _=H.conditions.length;return H.groups.forEach(J=>{_+=$(J)}),_},te=$(((X=F==null?void 0:F.config)==null?void 0:X.filters)||null);return e.jsxs(s.DndContext,{sensors:S,collisionDetection:s.closestCenter,onDragStart:B,onDragEnd:L,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(pl,{isVisible:c,onToggleVisibility:()=>i(!c)}),e.jsxs("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:[!d&&e.jsx(Ll,{selectedChart:h,onChartChange:j,groupByFields:T("groupBy"),pivotByFields:T("pivotBy"),metricsFields:T("metrics"),sortByFields:T("sortBy")}),e.jsx(io,{selectedChart:h,activeView:t,onViewChange:a,showDebug:n,onDebugToggle:()=>r(!n),onAccept:f,onClear:g,onAdvancedToggle:b,onFiltersClick:p,filterCount:te,activeCard:F,dataSourceState:v.dataSource||s.EMPTY_DATA_SOURCE,columns:D,columnsLoading:C,columnsError:I,getFieldsForContainer:T,cards:x.cards,activeCardId:x.activeCardId,addCard:k,setActiveCard:w})]}),!c&&u&&e.jsx("div",{className:"fixed left-6 top-[105px] z-50",children:e.jsx(s.Button,{size:"sm",variant:"outline",className:"h-10 w-10 rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted",onClick:()=>i(!0),title:"Show Data Source Panel",children:e.jsx(s.Database,{className:"h-4 w-4"})})})]}),F&&e.jsx(Ql,{cardId:F.id,filters:((q=F.config)==null?void 0:q.filters)||null,onFiltersChange:O,onClearFilters:P,availableFields:K,isOpen:l,onOpenChange:o}),e.jsx(s.DragOverlay,{dropAnimation:null,children:e.jsx(co,{activeField:M||null})})]})}function ho({authToken:t,onSave:a,onClose:n}){const r=A.useRef(null),l=s.useEditorStore(v=>v.showAIDialog),o=s.useEditorStore(v=>v.isDevMode),{setAuthToken:c}=s.useDashboardActions(),{setShowAIDialog:i,setOnSave:d,setOnClose:u}=s.useEditorActions(),{handleDragOver:m,handleDragEnd:h,handleDragStart:f,handleDragCancel:g,sensors:b}=Bn();A.useEffect(()=>{a&&d(a),n&&u(n)},[a,d,n,u]),A.useEffect(()=>{t&&t.accessToken&&c(t)},[t,c]),A.useEffect(()=>{var v,k;l?((v=r.current)==null||v.resize(40),i(!0)):(i(!1),(k=r.current)==null||k.resize(0))},[l,i]);function p(v){v<1?i(!1):l||i(!0)}function j(){return e.jsxs(e.Fragment,{children:[e.jsx(Ct,{type:"main"}),e.jsxs(s.ResizablePanelGroup,{"data-content":"editor-main",className:"grow",direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(sl,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:p,defaultSize:0,children:e.jsx(Hs,{})})]})]})}function x(){return e.jsxs(s.ResizablePanelGroup,{"data-content":"explorer",className:"flex grow",direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(mo,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:p,defaultSize:0,children:e.jsx(Hs,{})})]})}return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:o?e.jsx(s.DndContext,{sensors:b,onDragStart:f,onDragEnd:h,onDragOver:m,onDragCancel:g,children:e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:j()})}):x()})}function xo(){s.useDashboardStore(c=>c.selectedCardId);const t=s.useDashboardStore(c=>c.selectedSheetId),{setIsVisualEditing:a}=s.useDashboardStore(c=>c.actions),n=s.useDashboardStore(c=>c.isVisualEditing),r=s.useDashboardStore(c=>c.actions.updateFrame);function l(c){t&&(r(t,c),a(!1))}function o(){a(!1)}return e.jsx("div",{role:"editor-container",className:s.cn("flex-1 grow basis-0 overflow-auto",{"max-h-0 overflow-hidden":!n}),children:e.jsx(ho,{onSave:l,onClose:o})})}function po({column:t}){return e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger$1,{className:"shrink-0",asChild:!0,children:s.isTextDataType(t.data_type)?e.jsx(s.TextIcon,{className:"size-3 text-muted-foreground"}):s.isNumberDataType(t.data_type)?e.jsx(Ne,{className:"size-3 text-muted-foreground"}):s.isDateDataType(t.data_type)?e.jsx(s.Calendar,{className:"size-3 text-muted-foreground"}):s.isBooleanDataType(t.data_type)?e.jsx(Le,{className:"size-3 text-muted-foreground"}):t.data_type.startsWith("json")?e.jsx(ua,{className:"size-3 text-muted-foreground"}):e.jsx(s.QuestionMarkIcon,{className:"size-3 text-muted-foreground"})}),e.jsx(s.TooltipContent,{children:e.jsx("p",{className:"text-xs",children:t.data_type})})]})}function fo(){const t=s.useEditorStore(o=>o.selectedDatabaseName),a=s.useEditorStore(o=>o.selectedTableName),n=s.useDashboardStore(o=>o.dashboard.filters)||[],{columns:r}=s.useEditorAside(),{assignFilter:l}=ks();return e.jsx(s.ScrollArea,{className:"flex-1 basis-0 flex-col px-3",children:r==null?void 0:r.map(o=>{const c=n==null?void 0:n.find(i=>i.column===s.fmt(o.column_name)&&i.table===a&&i.database===t);return e.jsx("div",{onClick:()=>l(o),className:s.cn("group flex cursor-pointer items-center justify-between border border-dashed border-background px-3 py-[6px] text-sm transition-colors hover:bg-muted/50",{"bg-muted":c}),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(po,{column:o}),e.jsx("span",{children:o.column_name})]})},o.column_name)})})}function go({dataType:t}){const a=s.getDataType(t);return a==="string"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(ge,{className:"h-3 w-3"})}):a==="number"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(Ne,{className:"h-3 w-3"})}):a==="date"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):a==="boolean"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Le,{className:"h-3 w-3"})}):a==="json"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Be,{className:"h-3 w-3"})}):a==="geo"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(_e,{className:"h-3 w-3"})}):a==="calculated"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(qe,{className:"h-3 w-3"})}):e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(ge,{className:"h-3 w-3"})})}function jo(){const[t,a]=A.useState(""),[n,r]=A.useState("all"),l=s.useDashboardStore(x=>x.dashboard.filters)||[],{assignFilter:o}=ks(),c=s.useEditorStore(x=>x.card.dataSource),{columns:i=[],isLoading:d,error:u}=s.useColumns(),m=i.filter(x=>x.name.toLowerCase().includes(t.toLowerCase())||x.dataType.toLowerCase().includes(t.toLowerCase())||x.label&&x.label.toLowerCase().includes(t.toLowerCase())),h=x=>{const v=s.getDataType(x.dataType);return v==="number"?"metrics":(["date","string","boolean"].includes(v),"dimensions")},f=n==="all"?m:m.filter(x=>h(x)===n),g=m.filter(x=>h(x)==="dimensions").length,b=m.filter(x=>h(x)==="metrics").length,p=x=>{const v={column_name:x.name,data_type:x.dataType,label:x.label,description:x.description};o(v,"dashboard",x)};if(d)return e.jsx("div",{className:"flex h-full grow flex-col items-center justify-center px-3",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading fields"})});if(u)return e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-3",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-red-300"}),e.jsx("p",{className:"mb-2 text-sm text-red-500",children:"Error loading fields"}),e.jsx("p",{className:"px-4 text-center text-xs text-red-400",children:u.message||"Failed to load column data"})]});if(!c||!c.selectedEntities||c.selectedEntities.length===0)return e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-8 text-center",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-gray-300"}),e.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),e.jsx("p",{className:"px-4 text-xs text-gray-400",children:"Select a table, view, or dataset from the data source panel to see available fields"})]});if(i.length===0)return e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-8 text-center",children:[e.jsx("p",{className:"text-sm text-gray-500",children:"No fields found for selected data source"}),e.jsx("p",{className:"mt-1 text-xs text-gray-400",children:"Try selecting different data sources"})]});const j=m.length>0;return e.jsxs("div",{className:"flex h-full grow flex-col pb-4",children:[e.jsxs("div",{className:"flex-shrink-0 space-y-3 px-3 pt-3",children:[i.length>0&&e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 transform text-muted-foreground"}),e.jsx(s.Input$1,{className:"pl-10",type:"text",placeholder:"Search fields...",value:t,onChange:x=>a(x.target.value)})]}),j&&e.jsx(s.Tabs,{defaultValue:"all",value:n,onValueChange:x=>r(x),children:e.jsxs(s.TabsList,{className:"grid h-9 w-full grid-cols-3",children:[e.jsxs(s.TabsTrigger,{value:"all",className:"text-xs",children:["All",e.jsx("span",{className:"ml-2 text-xs font-semibold",children:m.length})]}),e.jsxs(s.TabsTrigger,{value:"dimensions",className:"text-xs",children:[e.jsx(s.Layers,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:g})]}),e.jsxs(s.TabsTrigger,{value:"metrics",className:"text-xs",children:[e.jsx(s.ChartColumn,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:b})]})]})})]}),e.jsxs(s.ScrollArea,{className:"flex-1 basis-0 flex-col px-3 pt-3",children:[f.length===0&&t&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:['No fields found matching "',t,'"']}),f.length===0&&!t&&n!=="all"&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:["No ",n," fields found"]}),f.map(x=>{const v=l==null?void 0:l.some(k=>{var R;return k.title===x.name||((R=k.column)==null?void 0:R.includes(x.name))});return e.jsx("div",{onClick:()=>p(x),className:s.cn("group flex cursor-pointer items-center justify-between border border-dashed border-background px-3 py-[6px] text-sm transition-colors hover:bg-muted/50",{"bg-muted":v}),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(go,{dataType:x.dataType}),e.jsx("span",{children:x.label||x.name})]})},x.id)})]})]})}function bo(){var r;const t=s.useDashboardStore(l=>l.actions.setShowFilters),a=s.useCurrentActiveCard(),n=a&&((r=a.dataSource)==null?void 0:r.selectedEntities)&&a.dataSource.selectedEntities.length>0;return e.jsxs("section",{className:"relative flex min-w-[320px] grow flex-col border-l px-1",children:[e.jsxs("div",{className:"mt-4 flex items-center justify-between gap-2 px-3",children:[e.jsx(s.Label,{className:"px-2 text-lg",children:"Filters"}),e.jsx(s.Button,{onClick:()=>t(!1),className:"h-7 w-7 p-0",variant:"ghost",children:e.jsx(s.Cross2Icon,{})})]}),e.jsx("div",{className:"flex grow",children:n?e.jsx(jo,{}):e.jsx(Ct,{type:"filter",ColumnsComponent:()=>e.jsx(fo,{})})})]})}function yo(){const t=s.useDashboardStore(r=>r.dashboard.filters),a=s.useDashboardStore(r=>r.theme),n=t==null?void 0:t.filter(r=>r.hide);return n!=null&&n.length?e.jsx("div",{className:s.cn("mb-1 flex items-center gap-2 border-y px-0.5 pb-0.5",{"bg-[repeating-linear-gradient(45deg,_#ffffff_0_3px,_#f3f3f3_3px_6px)]":a==="light","bg-[repeating-linear-gradient(45deg,_#18171d_0_3px,_#272729_3px_6px)]":a==="dark"}),children:n==null?void 0:n.map(r=>e.jsxs("div",{className:"flex min-w-[250px] max-w-fit flex-col gap-1 p-2",children:[e.jsx(s.FilterHeader,{filter:r}),e.jsx(s.FilterComponent,{filter:r})]},r.id))}):null}function vo(){const t=s.useDashboardStore(r=>r.showFilters),a=s.useDashboardStore(r=>r.isVisualEditing),n=s.useDashboardStore(r=>r.isDashboardEditing);return e.jsxs("div",{role:"dashboard-plus-main",className:s.cn("",{"max-h-0 overflow-hidden":a,"flex grow overflow-auto":!a}),children:[e.jsxs("section",{className:"flex grow flex-col",children:[n&&e.jsx(yo,{}),e.jsx(s.DashboardTabs,{})]}),t&&e.jsx("div",{role:"filter-aside-container",className:"flex",children:e.jsx(bo,{})})]})}function No(){const t=s.useDashboardStore(l=>l.dashboard),a=s.useDashboardStore(l=>l.actions.setDashboard),n=s.useDashboardStore(l=>l.showDashboardJSON),r=s.useDashboardStore(l=>l.actions.setShowDashboardJSON);return e.jsxs("div",{className:s.cn("relative p-2",{hidden:!n}),children:[e.jsxs(s.Button,{variant:"secondary",size:"sm",className:"absolute right-2 top-2 z-10 h-8",onClick:()=>r(!1),children:[e.jsx(s.X,{className:"mr-2 h-4 w-4"}),"Close"]}),e.jsx(s.de,{onChange:l=>{if(l)try{JSON.parse(l),a(JSON.parse(l))}catch{}},defaultLanguage:"json",className:"h-[550px] overflow-y-auto",value:JSON.stringify(t,null,2),options:{minimap:{enabled:!1},glyphMargin:!1,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,renderLineHighlight:"none"}})]})}function Co({showControls:t=!1,showFooter:a=!0,...n}){if(typeof window>"u")return null;const{preferences:r}=n;return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:e.jsxs(s.SemaphorContextProvider,{dashboardProps:n,children:[e.jsx(s.$e,{}),e.jsx(s.UXProvider,{children:e.jsxs(s.DashboardPreferencesProvider,{preferences:r,children:[e.jsx(No,{}),e.jsxs("main",{className:"relative flex h-full w-full flex-col",children:[t&&e.jsx(In,{}),e.jsxs(s.Container,{...n,type:"dashboard",children:[e.jsx(xo,{}),e.jsx(vo,{})]})]})]})})]})})}exports.DashboardPlus=Co;exports.ResourceManagementPanel=vt;exports.ScheduleDashboard=lt;exports.SelectComponent=Oe;exports.cleanCard=rt;exports.getDashbaordStateWithoutData=es;
|
|
354
|
+
ON ${v}`}),b};return o.length<2?null:e.jsx(e.Fragment,{children:e.jsx("div",{className:"space-y-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[n.joins.length>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-6 text-xs font-semibold",onClick:()=>l(!0),children:[e.jsx(s.Link,{className:s.cn("mr-1 h-3 w-3",{"text-blue-500":n.joins.length>0,"text-gray-500":n.joins.length===0})}),"Join",n.joins.length>1?"s":""," (",n.joins.length,")"]})}),e.jsx(s.TooltipContent,{side:"right",className:"max-w-md overflow-hidden p-0",children:e.jsx(cl,{joins:n.joins,baseEntityId:n.baseEntity.name,availableDataSources:o,generateSQLPreview:u})})]})}),e.jsx(Ws,{open:r,onOpenChange:l,joinPlan:n,availableDataSources:o,onSave:c,onCancel:d,onRemove:i,children:e.jsx("div",{})})]}),n.joins.length===0&&e.jsx(Ws,{open:r,onOpenChange:l,joinPlan:n,availableDataSources:o,onSave:c,onCancel:d,onRemove:i,children:e.jsxs(s.Button,{onClick:()=>l(!0),variant:"outline",size:"sm",className:"w-full",children:[e.jsx(s.Link,{className:"mr-3 size-4"}),"Configure Joins"]})})]})})})}function ul({open:t,onOpenChange:a}){const[n,r]=I.useState([]),{updateDataSource:l}=s.useEditorActions(),o=s.useDashboardStore(p=>p.dashboard.aiContext),c=(o==null?void 0:o.selectedEntities)||[];I.useEffect(()=>{t&&r([])},[t]);const i=p=>{r(j=>j.some(v=>v.name===p.name&&v.type===p.type)?j.filter(v=>!(v.name===p.name&&v.type===p.type)):[...j,p])},d=()=>{r([...c])},u=()=>{r([])},m=()=>{if(n.length===0)return;const p=n[0],j=p.connectionId||"",x=p.connectionType||"",k=n.some(C=>C.type==="dataset")?"semanticDomain":"database";l({connectionId:j,connectionType:x,mode:k,selectedEntities:n}),a(!1)},h=p=>{switch(p.type){case"table":return e.jsx(s.Table,{className:"h-4 w-4"});case"view":return e.jsx(Wa,{className:"h-4 w-4"});case"model":return e.jsx(pa,{className:"h-4 w-4"});case"dataset":return e.jsx(s.Database,{className:"h-4 w-4"});case"file":case"url":case"upload":return e.jsx(s.FileText,{className:"h-4 w-4"});default:return e.jsx(s.Database,{className:"h-4 w-4"})}},f=p=>"label"in p&&p.label?p.label:p.name,g=p=>{if("description"in p&&p.description)return p.description;const j=[];return p.database&&j.push(p.database),p.schema&&j.push(p.schema),p.name&&j.push(p.name),j.join(".")},b=p=>n.some(j=>j.name===p.name&&j.type===p.type);return c.length===0?e.jsx(s.Dialog,{open:t,onOpenChange:a,children:e.jsxs(s.DialogContent,{className:"max-w-md",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"No Data Available"}),e.jsx(s.DialogDescription,{children:"No entities are currently available in the AI context. Please add some data sources to the dashboard first."})]}),e.jsx(s.DialogFooter,{children:e.jsx(s.Button,{onClick:()=>a(!1),children:"Close"})})]})}):e.jsx(s.Dialog,{open:t,onOpenChange:a,children:e.jsxs(s.DialogContent,{className:"flex max-w-2xl flex-col",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Select Data to Analyze"}),e.jsx(s.DialogDescription,{children:"Choose entities from the dashboard's context"})]}),e.jsxs("div",{className:"flex-1 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"outline",size:"sm",onClick:d,disabled:n.length===c.length,children:"Select All"}),e.jsx(s.Button,{variant:"outline",size:"sm",onClick:u,disabled:n.length===0,children:"Clear All"})]}),e.jsxs(s.Badge,{variant:"secondary",children:[n.length," of ",c.length," selected"]})]}),e.jsx(s.Separator,{}),e.jsx(s.ScrollArea,{className:"h-64",children:e.jsx("div",{className:"space-y-2",children:c.map((p,j)=>e.jsxs("div",{className:s.cn("flex items-center gap-3 rounded-lg border p-3 transition-colors hover:bg-muted/50",b(p)&&"border-primary bg-primary/5"),children:[e.jsx(s.Checkbox,{checked:b(p),onCheckedChange:()=>i(p)}),e.jsx("div",{className:"flex items-center gap-2 text-muted-foreground",children:h(p)}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate font-medium",children:f(p)}),e.jsx("div",{className:"truncate text-sm text-muted-foreground",children:g(p)})]}),e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:p.type})]},`${p.type}-${p.name}-${j}`))})})]}),e.jsx(s.DialogFooter,{children:e.jsx("div",{className:"flex w-full justify-between",children:e.jsxs("div",{className:"flex grow justify-end gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsxs(s.Button,{onClick:m,disabled:n.length===0,children:["Select"," ",n.length>0?`(${n.length})`:""]})]})})})]})})}function ml({entity:t,title:a,maxDetails:n=10}){const l=s.getEntityDetails(t).slice(0,n),o=l.find(i=>i.label==="Description"),c=l.filter(i=>i.label==="Description"?!1:!["Connection","Database","Schema"].includes(i.label));return e.jsx(s.TooltipContent,{side:"top",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-sm font-medium",children:a||s.getDisplayName(t)}),o&&e.jsxs("div",{className:"border-t border-border pt-2",children:[e.jsx("div",{className:"mb-1 text-xs text-muted-foreground",children:"Description:"}),e.jsx("div",{className:"text-xs leading-relaxed",children:o.value})]}),c.length>0&&e.jsx("div",{className:"space-y-0.5",children:c.map((i,d)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[i.label,":"]}),e.jsx("span",{className:"font-mono",children:i.value})]},d))})]})})}function hl({entities:t}){return e.jsx(s.TooltipContent,{side:"top",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"text-sm font-medium",children:[t.length," more entities"]}),e.jsx("div",{className:"space-y-1",children:t.map((a,n)=>{const r=s.getEntityDetails(a),l=r.find(c=>c.label==="Description"),o=r.filter(c=>c.label==="Description"?!1:!["Connection","Database","Schema"].includes(c.label)).slice(0,3);return e.jsxs("div",{className:"border-b border-border pb-1 last:border-b-0",children:[e.jsx("div",{className:"text-xs font-medium",children:s.getDisplayName(a)}),l&&e.jsxs("div",{className:"mb-1 mt-1",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Description:"}),e.jsx("div",{className:"text-xs leading-relaxed",children:l.value})]}),o.length>0&&e.jsx("div",{className:"mt-1 space-y-0.5",children:o.map((c,i)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[c.label,":"]}),e.jsx("span",{className:"font-mono",children:c.value})]},i))})]},`remaining-${a.type}-${a.name}-${n}`)})})]})})}function xl({isVisible:t,onToggleVisibility:a}){const[n,r]=I.useState(!1),[l,o]=I.useState(!1),[c,i]=I.useState(!0),d=s.useEditorStore(f=>f.card.dataSource);s.useCurrentUserInfo();const{updateDataSource:u}=s.useEditorActions(),m={connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},h={...m,...d,selectedEntities:(d==null?void 0:d.selectedEntities)||[]};return e.jsxs("div",{className:s.cn("flex flex-col overflow-hidden bg-background transition-all duration-300 ease-in-out",{"w-[325px]":t,"w-0":!t}),children:[e.jsxs("div",{children:[e.jsx("div",{className:s.cn("p-4 px-6",{"pb-0":!c}),children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsxs("div",{className:"flex cursor-pointer items-center gap-2",children:[e.jsx("h2",{className:"text-brand-100 font-semibold",children:"Data Source"}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>i(!c),className:"h-6 w-6 p-0",children:c?e.jsx(s.ChevronDown,{className:"h-4 w-4"}):e.jsx(s.ChevronRight,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",onClick:a,title:"Hide Data Source Panel",children:e.jsx(s.EyeOff,{className:"h-3.5 w-3.5"})}),e.jsxs(s.Button,{size:"sm",variant:"outline",className:"h-7",onClick:()=>r(!0),children:[e.jsx(s.Plus,{className:"mr-1 h-3.5 w-3.5"}),"Add"]})]})]})}),e.jsxs("div",{className:`overflow-hidden px-6 ${c?"max-h-96 space-y-4":"max-h-0 py-0 opacity-0"}`,children:[h.selectedEntities.length>0&&e.jsx(s.TooltipProvider$1,{children:e.jsxs("div",{className:"flex flex-wrap gap-1",children:[h.selectedEntities.slice(0,3).map((f,g)=>e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Badge,{variant:"secondary",className:"group relative cursor-pointer pr-6 text-xs transition-colors hover:border-red-200 hover:bg-red-50 dark:hover:border-red-800 dark:hover:bg-red-950",children:[s.getDisplayName(f),e.jsx("button",{onClick:b=>{b.stopPropagation();const p=h.selectedEntities.filter(j=>!(j.name===f.name&&j.type===f.type));u({...m,...d,selectedEntities:p})},className:"absolute right-1 top-1/2 -translate-y-1/2 rounded-full p-0.5 hover:bg-red-100",children:e.jsx(s.X,{className:"h-2.5 w-2.5 group-hover:text-red-500"})})]})}),e.jsx(ml,{entity:f})]},`${f.type}-${f.name}-${g}`)),h.selectedEntities.length>3&&e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Badge,{variant:"outline",className:"text-xs",children:["+",h.selectedEntities.length-3," more"]})}),e.jsx(hl,{entities:h.selectedEntities.slice(3)})]})]})}),e.jsx(dl,{})]})]}),e.jsx(ll,{}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(d==null?void 0:d.selectedEntities)||[],dialogMode:"dataSource",open:n,onOpenChange:r,dataSource:h,fallbackDataSource:m}),e.jsx(ul,{open:l,onOpenChange:o})]})}const pl="chart-selector-standard-first";function fl(){const[t,a]=s.useLocalStorageState(pl,!0);return{standardFirst:t,updatePreference:a}}const Ks=({pluginVisual:t,index:a,onSelect:n})=>{const r=ls(t.icon||""),l=t.name.charAt(0).toUpperCase(),o=s.getAutoDetectedChartIcon(t.name);return e.jsx(s.CommandItem,{value:`${t.name} custom visual plugin component`,onSelect:n,className:"group flex items-center gap-2",children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[r?e.jsx(r,{className:"h-4 w-4"}):o||e.jsx("div",{className:"flex h-4 w-4 items-center justify-center rounded bg-muted text-xs font-medium",children:l}),e.jsx("span",{children:t.name})]}),e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{tabIndex:0,className:"opacity-0 outline-none transition-opacity group-hover:opacity-100",children:e.jsx(s.Info,{className:"ml-1 h-3.5 w-3.5 text-muted-foreground"})})}),e.jsx(s.TooltipContent,{side:"right",children:t.pluginName})]})]})},`${t.url}-${t.name}-${a}`)},Js=["default","standardPlugin","customPlugin"];function gl({selectedChart:t,onChartChange:a}){var L;const[n,r]=I.useState(!1),{data:l}=Et();fl();const c=((L=s.useEditorStore(C=>C.card).customCardPreferences)==null?void 0:L.url)||"";Ns(c);const{setCardType:i,setCardPreferences:d,setIsDevMode:u}=s.useEditorStore(C=>C.actions),{setCardCustomCfg:m,setCustomCardPreferences:h,setQueryConfig:f}=s.useEditorActions(),[g,b]=s.useLocalStorageState("chart-section-active",null),p=I.useMemo(()=>g?[g,...Js.filter(C=>C!==g)]:Js,[g]);function j(C){m(null),d({}),i(C),["custom","map"].includes(C)&&(u(!0),f(void 0)),a(C),r(!1)}function x(C){m(null),d({}),i("custom"),h({type:"component",visualType:"single",url:C.url,componentName:C.name,icon:C.icon,pluginChartType:C.chartType}),f(void 0),a("custom"),r(!1)}const v=()=>{var S;if(t==="custom"){const y=s.useEditorStore.getState().card;return((S=y==null?void 0:y.customCardPreferences)==null?void 0:S.componentName)||"Custom Visual"}const C=s.chartTypes.find(y=>y.id===t);return(C==null?void 0:C.label)||"Select chart type"},k=()=>{var S,y;if(t==="custom"){const D=s.useEditorStore.getState().card,N=(S=D==null?void 0:D.customCardPreferences)==null?void 0:S.icon,B=(y=D==null?void 0:D.customCardPreferences)==null?void 0:y.componentName;if(N&&B)return e.jsx(jl,{icon:N,componentName:B});if(B){const w=s.getAutoDetectedChartIcon(B);if(w)return w}return e.jsx(Ue,{className:"h-4 w-4"})}const C=s.chartTypes.find(D=>D.id===t);if(C){const D=C.icon;return e.jsx(D,{className:"h-4 w-4"})}return e.jsx(Ue,{className:"h-4 w-4"})};return e.jsx("div",{className:"mb-6",children:e.jsxs(s.Popover,{open:n,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":n,className:"w-full justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[k(),e.jsx("span",{children:v()})]}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[300px] p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search chart types..."}),e.jsxs(s.CommandList,{className:"mb-2 max-h-[300px]",children:[e.jsx(s.CommandEmpty,{children:"No chart type found."}),p.map(C=>{if(C==="default")return e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"flex items-center gap-2",children:"Default Visuals"})}),e.jsx(s.TooltipContent,{side:"right",children:"These are the standard visuals available in Semaphor"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:g==="default",onCheckedChange:S=>b(S?"default":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:s.chartTypes.map(S=>{const y=S.icon;return e.jsx(s.CommandItem,{value:`${S.label} ${S.id} chart graph visualization`,onSelect:()=>j(S.id),className:"flex items-center gap-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(y,{className:"h-4 w-4"}),e.jsx("span",{children:S.label})]})},S.id)})},"default");if(C==="standardPlugin"){const S=l.filter(y=>y.pluginType==="standard");return S.length?e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsx("p",{children:"Standard Visuals"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:g==="standardPlugin",onCheckedChange:y=>b(y?"standardPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:S.filter(y=>y.componentType==="chart").map((y,D)=>e.jsx(Ks,{pluginVisual:y,index:D,onSelect:()=>x(y)},`${y.url}-${y.name}-${D}`))},"standardPlugin"):null}if(C==="customPlugin"){const S=l.filter(y=>y.pluginType==="custom");return S.length?e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs("span",{className:"flex items-center gap-2",children:["Custom Visuals",e.jsx(s.Info,{className:"h-3.5 w-3.5 text-muted-foreground"})]})}),e.jsx(s.TooltipContent,{side:"right",children:"External visuals that are specific to your project"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:g==="customPlugin",onCheckedChange:y=>b(y?"customPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:S.map((y,D)=>e.jsx(Ks,{pluginVisual:y,index:D,onSelect:()=>x(y)},`${y.url}-${y.name}-${D}`))},"customPlugin"):null}return null})]})]})})]})})}const jl=({icon:t,componentName:a})=>{const n=ls(),r=s.getAutoDetectedChartIcon(a);return n?e.jsx(n,{className:"h-4 w-4"}):r||e.jsx(Ue,{className:"h-4 w-4"})},bl=[{id:"table",icon:s.Table2,label:"Table"},{id:"bar",icon:s.ChartColumnIncreasing,label:"Bar Chart"},{id:"line",icon:s.ChartLine,label:"Line Chart"},{id:"stackedBar",icon:s.ChartColumnStacked,label:"Stacked Bar",requiresPivot:!0},{id:"pie",icon:s.ChartPie,label:"Pie Chart"},{id:"doughnut",icon:s.Donut,label:"Donut Chart"},{id:"kpi",icon:s.TiSortNumerically,label:"KPI"}];function yl({selectedChart:t,onChartChange:a}){var l;const n=s.useEditorStore(o=>o.card),r=((l=n==null?void 0:n.config)==null?void 0:l.pivotByColumns)&&n.config.pivotByColumns.length>0;return e.jsx("div",{className:"flex items-center gap-1",children:bl.map(o=>{if(o.requiresPivot&&!r)return null;const c=o.icon,i=t===o.id;return e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"ghost",size:"sm",onClick:()=>a(o.id),className:s.cn("h-8 w-8 p-0",i&&"bg-accent text-accent-foreground"),children:[e.jsx(c,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:o.label})]})}),e.jsx(s.TooltipContent,{side:"bottom",children:e.jsx("p",{children:o.label})})]},o.id)})})}const As=({dataType:t})=>{const a=s.getDataType(t);return a==="string"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(ge,{className:"h-3 w-3"})}):a==="number"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(Ne,{className:"h-3 w-3"})}):a==="date"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):a==="boolean"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Me,{className:"h-3 w-3"})}):e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(ge,{className:"h-3 w-3"})})};function vl({aliasTemplate:t,onAliasTemplateChange:a}){var d;const[n,r]=I.useState(t),[l,o]=I.useState(!1),c=(d=s.useEditorStore(u=>{var m;return(m=u.card.config)==null?void 0:m.pivotByColumns}))==null?void 0:d[0],i=c?`e.g. Min Sales in {{${c.name}}}`:"e.g. Min Sales in {{region}}";return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-gray-600",children:"Pivot Alias Template"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Input$1,{placeholder:i,value:l?n:t,onChange:u=>{r(u.target.value),o(!0)},onFocus:()=>o(!0),onPointerDown:u=>u.stopPropagation(),className:"h-8 text-xs",onKeyDown:u=>{u.key==="Enter"&&l&&n!==t?(a(n),o(!1)):u.key==="Escape"&&(r(t),o(!1))},"aria-label":"Edit alias template"}),l&&n!==t&&e.jsxs(e.Fragment,{children:[e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm alias template",onClick:()=>{a(n),o(!1)},children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel alias template edit",onClick:()=>{r(t),o(!1)},children:e.jsx(s.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function Nl({valueAliases:t,onValueAliasesChange:a}){const[n,r]=I.useState(null),[l,o]=I.useState(""),[c,i]=I.useState(""),d=()=>{a({...t,"":""})},u=h=>{const f={...t};delete f[h],a(f)},m=h=>{const f={...t};delete f[h],f[l]=c,a(f),r(null)};return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Pivot Value Aliases"}),e.jsxs("div",{className:"space-y-2",children:[Object.entries(t).map(([h,f],g)=>e.jsx("div",{className:"flex items-center gap-2",children:n===h?e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:l,onChange:b=>o(b.target.value),className:"h-8 w-24 text-xs",onPointerDown:b=>b.stopPropagation(),onKeyDown:b=>{b.key==="Enter"?m(h):b.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:c,onChange:b=>i(b.target.value),className:"h-8 w-24 text-xs",onPointerDown:b=>b.stopPropagation(),onKeyDown:b=>{b.key==="Enter"?m(h):b.key==="Escape"&&r(null)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm value alias edit",onClick:()=>m(h),children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel value alias edit",onClick:()=>r(null),children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:h,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),o(h),i(f)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:f,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),o(h),i(f)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>u(h),"aria-label":"Remove value alias",children:e.jsx(s.X,{className:"h-3 w-3"})})]})},h+g)),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"mt-1 h-8 text-xs",onClick:d,children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Value Alias"]})]})]})}function Cl({field:t,searchQuery:a="",limit:n=500}){const{authToken:r}=s.useSemaphorContext(),l=s.useEditorStore(d=>d.card),o=l==null?void 0:l.dataSource,c=["attribute-values",t.entityName,t.name,a,n],i=s.useQuery({queryKey:c,queryFn:async()=>{if(!(o!=null&&o.connectionId))return console.warn("No connection ID available for attribute values query"),[];try{const d={groupByColumns:[{...t,role:"groupby"}],metricColumns:[],filters:a?{id:"search-filter",logicalOperator:"AND",negate:!1,conditions:[{id:"search-condition",field:t,operator:"contains",value:a}],groups:[]}:void 0,rowLimit:n},u={connection_id:o.connectionId,cardConfig:d,cardDataSource:o,cache_config:s.getCacheConfig({card:l})};console.log("requestBody",u);const m=await s.postRequestRegular("https://semaphor.cloud/api/v1/query",(r==null?void 0:r.accessToken)||"",u);if(m!=null&&m.error)return console.error("Error fetching attribute values:",m.error),[];const h=t.name;return((m==null?void 0:m.records)||[]).map(g=>{const b=g[h]||g[t.alias||h]||g[t.label];return{id:b||"",value:b||"",label:String(b||"(empty)")}})}catch(d){return console.error("Error fetching attribute values:",d),[]}},enabled:!!t&&!!(o!=null&&o.connectionId),staleTime:5*60*1e3,gcTime:10*60*1e3});return{values:i.data||[],isLoading:i.isLoading,isFetching:i.isFetching,isError:i.isError,error:i.error,refetch:i.refetch}}function Sl({open:t,onOpenChange:a,availableFields:n,existingFilters:r,editingCondition:l,onSave:o}){var k,L;const c=!!l,[i,d]=I.useState(c?"values":"fields"),[u,m]=I.useState(""),[h,f]=I.useState({id:(l==null?void 0:l.id)||s.v4(),field:(l==null?void 0:l.field)||null,selectedValues:l?Array.isArray(l.value)?l.value:[l.value]:[]}),g=n.filter(C=>{var y;return c?!1:!((y=r==null?void 0:r.conditions)==null?void 0:y.some(D=>D.field.id===C.id))&&C.label.toLowerCase().includes(u.toLowerCase())}),b=C=>{f({...h,field:C}),d("values")},p=()=>{if(h.field&&h.selectedValues.length>0){const C={id:h.id,field:h.field,operator:"in",value:h.selectedValues};let S;if(c){const y=((r==null?void 0:r.conditions)||[]).map(D=>D.id===l.id?C:D);S={...r,conditions:y}}else{const y=(r==null?void 0:r.conditions)||[];S={id:(r==null?void 0:r.id)||s.v4(),logicalOperator:"AND",negate:!1,conditions:[...y,C],groups:[]}}o(S),a(!1)}},j=()=>{if(!c||!l)return;const C=((r==null?void 0:r.conditions)||[]).filter(S=>S.id!==l.id);if(C.length>0){const S={...r,conditions:C};o(S)}else o(void 0);a(!1)},x=C=>{f({...h,selectedValues:C})},v=()=>{c&&l?(f({id:l.id,field:l.field,selectedValues:Array.isArray(l.value)?l.value:[l.value]}),d("values")):(f({id:s.v4(),field:null,selectedValues:[]}),d("fields")),m("")};return I.useEffect(()=>{t&&v()},[t,c,l]),e.jsx(s.Dialog,{open:t,onOpenChange:a,children:e.jsxs(s.DialogContent,{className:"max-w-2xl",children:[e.jsx(s.DialogHeader,{children:e.jsx(s.DialogTitle,{children:c?`Edit Filter: ${(k=h.field)==null?void 0:k.label}`:i==="fields"?"Select Field to Filter":`Select Values for ${(L=h.field)==null?void 0:L.label}`})}),e.jsxs("div",{className:"space-y-4",children:[!c&&(r==null?void 0:r.conditions)&&r.conditions.length>0&&i==="fields"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Current Filters:"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:r.conditions.map(C=>e.jsxs("div",{className:"flex items-center gap-1 px-2 py-1 bg-muted rounded-md text-xs",children:[e.jsxs("span",{className:"font-medium",children:[C.field.label,":"]}),e.jsx("span",{className:"text-muted-foreground",children:Array.isArray(C.value)?`${C.value.length} values`:String(C.value)})]},C.id))})]}),i==="fields"&&!c?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:"Search fields...",value:u,onChange:C=>m(C.target.value),className:"pl-10"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2 max-h-[400px] overflow-y-auto",children:g.map(C=>e.jsxs(s.Button,{variant:"outline",className:"justify-start h-auto py-2 px-3",onClick:()=>b(C),children:[e.jsx(As,{dataType:s.getDataType(C.dataType)}),e.jsxs("div",{className:"ml-2 text-left",children:[e.jsx("div",{className:"text-sm font-medium",children:C.label}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[C.entityName,".",C.name]})]})]},C.id))}),g.length===0&&u&&e.jsxs("div",{className:"text-center py-4 text-sm text-muted-foreground",children:['No fields found matching "',u,'"']}),g.length===0&&!u&&n.length>0&&e.jsx("div",{className:"text-center py-4 text-sm text-muted-foreground",children:"All available fields are already filtered"})]}):e.jsx(wl,{field:h.field,selectedValues:h.selectedValues,onValuesChange:x,onBack:c?void 0:()=>d("fields")}),e.jsxs("div",{className:"flex justify-between pt-4 border-t",children:[e.jsx("div",{children:c?e.jsx(s.Button,{variant:"destructive",onClick:j,children:"Delete Filter"}):e.jsx(s.Button,{variant:"outline",onClick:v,children:"Reset"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(s.Button,{onClick:p,disabled:!h.field||h.selectedValues.length===0,children:"Apply"})]})]})]})]})})}function wl({field:t,selectedValues:a,onValuesChange:n,onBack:r}){const[l,o]=I.useState(""),{values:c,isLoading:i,isFetching:d}=Cl({field:t,searchQuery:l,limit:500}),u=l?c.filter(f=>String(f.value).toLowerCase().includes(l.toLowerCase())):c,m=f=>{const g=a.includes(f);n(g?a.filter(b=>b!==f):[...a,f])},h=()=>{a.length===u.length&&u.length>0?n([]):n(u.map(f=>f.value))};return e.jsxs("div",{className:"space-y-4",children:[r&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:r,children:"← Back"}),e.jsxs(s.Label,{className:"text-sm font-medium",children:["Select values for ",t.label]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:"Search values...",value:l,onChange:f=>o(f.target.value),className:"pl-10"})]}),i||d?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(s.LoaderCircle,{className:"h-6 w-6 animate-spin"})}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 pb-2 border-b",children:[e.jsx(s.Checkbox,{checked:a.length===u.length&&u.length>0,onCheckedChange:h}),e.jsxs(s.Label,{className:"text-sm",children:["Select All (",u.length,")"]})]}),e.jsx("div",{className:"max-h-[300px] overflow-y-auto space-y-1",children:u.map(f=>e.jsxs("div",{className:"flex items-center gap-2 p-2 hover:bg-muted/50 rounded cursor-pointer",onClick:()=>m(f.value),children:[e.jsx(s.Checkbox,{checked:a.includes(f.value),onCheckedChange:()=>m(f.value)}),e.jsx(os,{className:"text-sm",children:f.label})]},f.id))})]})]})}function Dl({field:t,zone:a,index:n,sortDirection:r,onSortDirectionChange:l,hasPivotColumns:o=!1,cardType:c}){var Rs,Os,Bs;const{attributes:i,listeners:d,setNodeRef:u,transform:m,transition:h,isDragging:f}=s.useSortable({id:t.id}),g=s.useEditorStore(G=>G.card),{updateLabel:b,handleAggregationChange:p,handleDateFormatChange:j,handleGranularityChange:x,handleAliasTemplateChange:v,handleValueAliasesChange:k,removeField:L,handleKpiComparisonTypeChange:C,handleKpiShowTrendlineChange:S,handleKpiTrendlineWindowChange:y,handleKpiTrendlineGranularityChange:D,handleKpiTargetValueChange:N}=Is(g),[B,w]=I.useState(!1),[F,T]=I.useState(!1),[E,A]=I.useState(null),[O,M]=I.useState(t.dateFormat||"YYYY-MM-DD"),[R,P]=I.useState(t.customFormat||""),[K,$]=I.useState(!!t.customFormat),[te,X]=I.useState(t.granularity||"day"),[q,H]=I.useState(t.aliasTemplate||""),[_,J]=I.useState(t.valueAliases||{}),[z,U]=I.useState((Rs=t.parameters)==null?void 0:Rs.filters),Z=G=>{G==="custom"?$(!0):($(!1),M(G),a==="groupBy"&&j(n,G,""))},le=G=>{P(G),a==="groupBy"&&j(n,"custom",G)},V=G=>{var xe;X(G);const de=(xe=ee(G)[0])==null?void 0:xe.value;de&&!K&&(M(de),a==="groupBy"&&j(n,de,"")),a==="groupBy"&&x(n,G)},se=G=>{H(G),a==="metrics"&&v(n,G)},ne=G=>{J(G),a==="metrics"&&k(n,G)},Y=G=>{b(a,n,G)},W=G=>{var ce;if(U(G),a==="metrics"){const de={...t,parameters:{...t.parameters,filters:G}},xe=[...((ce=g.config)==null?void 0:ce.metricColumns)||[]];xe[n]=de,s.useEditorStore.getState().actions.updateCardConfig(g.id,{metricColumns:xe})}T(!1)},re=()=>{L(a,n)},ie={transform:s.CSS.Transform.toString(m),transition:h},he=s.getDataType(t.dataType),Q=he==="date",oe=c==="kpi",ee=G=>{switch(G){case"day":return[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"MM/DD/YYYY",label:"01/15/2024 (MM/DD/YYYY)"},{value:"DD/MM/YYYY",label:"15/01/2024 (DD/MM/YYYY)"},{value:"MMMM DD, YYYY",label:"January 15, 2024 (MMMM DD, YYYY)"},{value:"MMM DD, YYYY",label:"Jan 15, 2024 (MMM DD, YYYY)"},{value:"DD MMM YYYY",label:"15 Jan 2024 (DD MMM YYYY)"},{value:"custom",label:"Custom Format..."}];case"week":return[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"Week of MMM DD, YYYY",label:"Week of Jan 15, 2024"},{value:"Week of MMMM DD, YYYY",label:"Week of January 15, 2024"},{value:"YYYY-WW",label:"2024-W03 (YYYY-WW)"},{value:"custom",label:"Custom Format..."}];case"month":return[{value:"MMM YYYY",label:"Jan 2024 (MMM YYYY)"},{value:"MMMM YYYY",label:"January 2024 (MMMM YYYY)"},{value:"YYYY-MM",label:"2024-01 (YYYY-MM)"},{value:"MM/YYYY",label:"01/2024 (MM/YYYY)"},{value:"YYYY MMM",label:"2024 Jan (YYYY MMM)"},{value:"custom",label:"Custom Format..."}];case"quarter":return[{value:"Q1 YYYY",label:"Q1 2024 (Q1 YYYY)"},{value:"YYYY Q1",label:"2024 Q1 (YYYY Q1)"},{value:"1st Quarter YYYY",label:"1st Quarter 2024"},{value:"YYYY-Q1",label:"2024-Q1 (YYYY-Q1)"},{value:"Quarter 1, YYYY",label:"Quarter 1, 2024"},{value:"custom",label:"Custom Format..."}];case"year":return[{value:"YYYY",label:"2024 (YYYY)"},{value:"YY",label:"24 (YY)"},{value:"custom",label:"Custom Format..."}];default:return[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"MM/DD/YYYY",label:"01/15/2024 (MM/DD/YYYY)"},{value:"DD/MM/YYYY",label:"15/01/2024 (DD/MM/YYYY)"},{value:"MMMM DD, YYYY",label:"January 15, 2024 (MMMM DD, YYYY)"},{value:"MMM DD, YYYY",label:"Jan 15, 2024 (MMM DD, YYYY)"},{value:"DD MMM YYYY",label:"15 Jan 2024 (DD MMM YYYY)"},{value:"YYYY-MM",label:"2024-01 (YYYY-MM)"},{value:"MMMM YYYY",label:"January 2024 (MMMM YYYY)"},{value:"custom",label:"Custom Format..."}]}},ae=ee(te),ue=a!=="pivotBy",je=Q&&a==="groupBy",Ge=!oe&&Q&&a==="groupBy",He=oe&&Q&&a==="groupBy",We=oe&&a==="metrics"&&((Os=g.config)==null?void 0:Os.comparisonType)==="target",ze=a==="metrics",Ce=()=>e.jsx("div",{title:`${t.entityName}.${t.name}`,onPointerDown:G=>{G.stopPropagation()},className:"max-w-[270px] cursor-default overflow-hidden text-ellipsis whitespace-nowrap px-0.5 text-xs text-gray-500",children:`${t.entityName}.${t.name}`}),me=()=>ue?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Label"}),e.jsx(ve,{value:t.label??"",onSave:Y,placeholder:"Display label...",type:"text"})]}):null,Ls=()=>je?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Granularity"}),e.jsxs(s.Select,{value:te,onValueChange:V,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select granularity..."})}),e.jsx(s.SelectContent,{children:["day","week","month","quarter","year"].map(G=>e.jsx(s.SelectItem,{className:"text-xs",value:G,children:s.toTitleCase(G)},G))})]})]}):null,Wt=()=>Ge?e.jsxs(e.Fragment,{children:[Ls(),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Date Format"}),e.jsxs(s.Select,{value:K?"custom":O,onValueChange:Z,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select date format..."})}),e.jsx(s.SelectContent,{children:ae.map(G=>e.jsx(s.SelectItem,{className:"text-xs",value:G.value,children:G.label},G.value))})]}),K&&e.jsxs("div",{className:"mt-2 space-y-1",children:[e.jsx(s.Input$1,{placeholder:"Enter custom format (e.g., YYYY-MM-DD HH:mm)",value:R,onChange:G=>{G.stopPropagation(),le(G.target.value)},onClick:G=>G.stopPropagation(),className:"h-8 text-xs"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Examples: YYYY-MM-DD, MM/DD/YY, DD-MMM-YYYY HH:mm"})]})]})]}):null,Kt=()=>{var G,ce,de,xe,Se;return He?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Comparison Type"}),e.jsxs(s.Select,{value:((G=g.config)==null?void 0:G.comparisonType)||"none",onValueChange:C,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select comparison type..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"none",children:"No Comparison"}),e.jsx(s.SelectItem,{value:"previous_period",children:"Previous Period"}),e.jsx(s.SelectItem,{value:"same_period_last_year",children:"Same Period Last Year"}),e.jsx(s.SelectItem,{value:"target",children:"Target Value"})]})]})]}),e.jsx("div",{className:"space-y-1",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Show Trendline"}),e.jsx(s.SmallSwitch,{checked:((ce=g.config)==null?void 0:ce.showTrendline)||!1,onCheckedChange:S})]})}),((de=g.config)==null?void 0:de.showTrendline)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Window"}),e.jsx(s.Input$1,{type:"number",min:"1",max:"365",value:((xe=g.config)==null?void 0:xe.trendlineWindow)||30,onChange:Ke=>{const ea=parseInt(Ke.target.value)||30;y(ea)},className:"h-8 text-xs",placeholder:"30"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Granularity"}),e.jsxs(s.Select,{value:((Se=g.config)==null?void 0:Se.trendlineGranularity)||"day",onValueChange:D,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select granularity..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"day",children:"Day"}),e.jsx(s.SelectItem,{value:"week",children:"Week"}),e.jsx(s.SelectItem,{value:"month",children:"Month"})]})]})]})]})]}):null},Jt=()=>{var G,ce;return We?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Target Value"}),e.jsx(ve,{value:((G=g.config)==null?void 0:G.targetValue)!==void 0&&((ce=g.config)==null?void 0:ce.targetValue)!==null?String(g.config.targetValue):"",onSave:de=>{!isNaN(Number(de))&&de!==null?N(Number(de)):N(0)},placeholder:"Enter target value...",type:"text"})]}):null},Qt=()=>ze?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Aggregation"}),e.jsxs(s.Select,{value:t.aggregate,onValueChange:G=>{p(n,G)},children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select function..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"COUNT",children:"Count"}),e.jsx(s.SelectItem,{className:"text-xs",value:"DISTINCT",children:"Count Distinct"}),s.getDataType(t.dataType)==="number"&&e.jsxs(e.Fragment,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"SUM",children:"Sum"}),e.jsx(s.SelectItem,{className:"text-xs",value:"AVG",children:"Average"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MIN",children:"Min"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MAX",children:"Max"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MEDIAN",children:"Median"})]})]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Attribute Filters"}),(z==null?void 0:z.conditions)&&z.conditions.length>0&&e.jsx("div",{className:"mb-2 space-y-1",children:z.conditions.map(G=>e.jsxs("div",{className:"flex cursor-pointer items-center gap-2 rounded bg-muted/50 p-2 text-xs transition-colors hover:bg-muted/70",onClick:()=>{A(G),T(!0)},children:[e.jsxs("span",{className:"font-medium",children:[G.field.label,":"]}),e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"cursor-help text-muted-foreground",children:Array.isArray(G.value)?G.value.length===1?String(G.value[0]):G.value.length<=2?G.value.join(", "):`${G.value.slice(0,2).join(", ")} +${G.value.length-2}`:String(G.value)})}),Array.isArray(G.value)&&G.value.length>1&&e.jsx(s.TooltipContent,{side:"top",className:"max-w-[300px]",children:e.jsxs("div",{className:"text-xs",children:[e.jsxs("div",{className:"mb-1 font-medium",children:["Selected values (",G.value.length,"):"]}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto",children:G.value.map((ce,de)=>e.jsx("div",{children:String(ce)},de))})]})})]})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"ml-auto h-4 w-4 p-0",onClick:ce=>{var xe;ce.stopPropagation();const de=z.conditions.filter(Se=>Se.id!==G.id);if(de.length>0){const Se={...z,conditions:de};W(Se)}else if(U(void 0),a==="metrics"){const Se={...t,parameters:{...t.parameters,filters:void 0}},Ke=[...((xe=g.config)==null?void 0:xe.metricColumns)||[]];Ke[n]=Se,s.useEditorStore.getState().actions.updateCardConfig(g.id,{metricColumns:Ke})}},children:e.jsx(s.X,{className:"h-3 w-3"})})]},G.id))}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>{A(null),T(!0)},children:[e.jsx(s.Filter,{className:"mr-2 h-3 w-3"}),"Add attribute filter"]})]}),e.jsx(Yt,{column:t}),o&&e.jsxs(e.Fragment,{children:[e.jsx(vl,{aliasTemplate:q,onAliasTemplateChange:se}),e.jsx(Nl,{valueAliases:_,onValueAliasesChange:ne})]})]}):null,{columns:Xt=[]}=s.useColumns(),Zt=(z==null?void 0:z.conditions)&&z.conditions.length>0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{ref:u,style:ie,...i,...d,className:`group mx-auto flex w-full flex-col gap-2 rounded border border-border bg-background p-2 transition-all hover:shadow-sm dark:border-gray-800 ${f?"z-50 scale-95 opacity-50":"border-slate-200"} ${a==="filters"?"cursor-default":"cursor-move"}`,children:[e.jsxs("div",{className:"flex grow items-center gap-2",children:[e.jsx(As,{dataType:he}),e.jsx(os,{className:s.cn("w-[140px] flex-1 text-sm",Zt&&"w-[120px]"),children:s.getMetricDisplayLabel(t)}),a==="metrics"&&((Bs=z==null?void 0:z.conditions)==null?void 0:Bs.length)&&!B&&e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-1 rounded bg-primary/10 px-1.5 py-0.5 text-xs",children:[e.jsx(s.Filter,{className:"h-3 w-3"}),e.jsx("span",{children:z.conditions.length})]})}),e.jsx(s.TooltipContent,{side:"top",children:e.jsx("div",{className:"text-xs",children:z.conditions.map(G=>e.jsxs("div",{children:[G.field.label,":"," ",Array.isArray(G.value)?`${G.value.length} values`:String(G.value)]},G.id))})})]})}),a!=="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:G=>{G.stopPropagation(),w(!B)},children:e.jsx(s.ChevronDown,{className:`h-3 w-3 transition-transform ${B?"rotate-180":""}`})}),a==="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 group-hover:opacity-100",onClick:G=>{G.stopPropagation(),console.log("DraggableField - Current sortDirection:",r);const ce=r==="asc"?"desc":"asc";console.log("DraggableField - New direction to set:",ce),l(ce)},children:r==="asc"?e.jsx(s.ArrowUp,{className:"h-3 w-3"}):e.jsx(s.ArrowDown,{className:"h-3 w-3"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:G=>{G.stopPropagation(),re()},children:e.jsx(s.X,{className:"h-3 w-3"})})]}),B&&e.jsxs("div",{className:"space-y-3",children:[Ce(),me(),c==="kpi"&&Ls(),Wt(),Kt(),Jt(),Qt()]})]}),F&&e.jsx(Sl,{open:F,onOpenChange:G=>{T(G),G||A(null)},availableFields:Xt,existingFilters:z,editingCondition:E,onSave:G=>{var ce;if(G)W(G);else if(U(void 0),a==="metrics"){const de={...t,parameters:{...t.parameters,filters:void 0}},xe=[...((ce=g.config)==null?void 0:ce.metricColumns)||[]];xe[n]=de,s.useEditorStore.getState().actions.updateCardConfig(g.id,{metricColumns:xe})}A(null)}})]})}function kl({concept:t}){const a=()=>{switch(t){case"groupBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Rows = Group By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that define how your data is grouped into rows."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-100 text-xs font-medium dark:bg-blue-200/20",children:"Product"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Sales"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Profit"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/50 text-xs font-medium dark:bg-blue-200/20",children:"Electronics"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$5,200"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$1,300"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/30 text-xs font-medium dark:bg-blue-300/20",children:"Clothing"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$3,100"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$620"})]}),e.jsxs("div",{className:"flex",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/20 text-xs font-medium dark:bg-blue-200/20",children:"Food"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$2,400"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$480"})]})]})]});case"pivotBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Columns = Pivot By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that split your data into multiple columns or series."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Region"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"North"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"South"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"East"})]}),e.jsxs("div",{className:"flex border-b py-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$2,300"}),e.jsx("div",{className:"w-1/4 bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$1,800"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$3,400"})]}),e.jsxs("div",{className:"flex py-1",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$460"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$360"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$680"})]})]})]});case"metrics":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Metrics = Values (Cells)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that represent the values shown in your visualization."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"col-span-1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q2"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q3"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"rounded bg-blue-100 p-1 text-center text-xs dark:bg-blue-300/20",children:"$2,300"}),e.jsx("div",{className:"rounded bg-blue-200 p-1 text-center text-xs dark:bg-blue-400/20",children:"$3,100"}),e.jsx("div",{className:"rounded bg-blue-300 p-1 text-center text-xs dark:bg-blue-500/20",children:"$4,200"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"rounded bg-green-100 p-1 text-center text-xs dark:bg-green-300/20",children:"$460"}),e.jsx("div",{className:"rounded bg-green-200 p-1 text-center text-xs dark:bg-green-400/20",children:"$620"}),e.jsx("div",{className:"rounded bg-green-300 p-1 text-center text-xs dark:bg-green-500/20",children:"$840"})]})]})]});default:return null}};return e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{delayDuration:300,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.CircleHelp,{className:"size-4 text-muted-foreground hover:text-foreground"})}),e.jsx(s.TooltipContent,{side:"right",align:"start",className:"p-3",children:a()})]})})}function Xe({zone:t,fields:a,label:n,placeholder:r,shouldShow:l,hasPivotColumns:o=!1}){const{isOver:c,setNodeRef:i}=s.useDroppable({id:t}),{updateSortByColumn:d}=s.useEditorActions(),u=s.useEditorStore(b=>b.card),m=s.useEditorStore(b=>b.card.type),h=a.length>0,f=(b,p)=>{var x;!((x=u.config)!=null&&x.sortByColumns)||u.config.sortByColumns.findIndex(v=>v.id===b)===-1||d(u.id,b,{direction:p})};if(t==="sortBy"&&l===!1)return null;const g=t!=="sortBy"&&m!=="kpi";return e.jsxs("div",{className:"mb-4 w-full",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(s.Label,{className:s.cn("block text-sm font-medium",{}),children:n}),g&&e.jsx(kl,{concept:t})]}),e.jsx("div",{ref:i,className:`rounded-lg border-2 border-dashed p-1 transition-all ${c?"border-blue-500 bg-blue-50 dark:bg-blue-950":h?"border-blue-200 bg-blue-50/30 dark:border-blue-800 dark:bg-blue-950/30":"min-h-[60px] border-muted-foreground/20 bg-background"}`,children:a.length===0?e.jsx("div",{className:"flex min-h-[40px] items-center justify-center text-sm text-gray-400",children:r}):e.jsx(s.SortableContext,{items:a.map(b=>b.id),strategy:s.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-1",children:a.map((b,p)=>{const x=b.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"flex-1",children:e.jsx(Dl,{field:b,zone:t,index:p,sortDirection:x,onSortDirectionChange:v=>f(b.id,v),hasPivotColumns:o,cardType:m})})},b.id)})})})})]})}const Qs=[{value:"green",color:"#16a34a",label:"Green"},{value:"red",color:"#dc2626",label:"Red"},{value:"neutral",color:"#6b7280",label:"Neutral"}],Tl=["#16a34a","#dc2626","#6b7280","#2563eb","#ca8a04","#7c3aed","#0891b2","#e11d48","#ea580c"];function fs({value:t,onChange:a,label:n}){const[r,l]=I.useState(!1),[o,c]=I.useState(!1),i=()=>{const d=Qs.find(u=>u.value===t);return d?d.color:t.startsWith("#")?t:Qs[2].color};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Popover,{open:r,onOpenChange:l,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx("button",{className:"size-5 rounded border-2 border-input shadow-sm transition-all hover:scale-110 hover:border-gray-400",style:{backgroundColor:i()},"aria-label":`Change color for ${n}`})}),e.jsx(s.PopoverContent,{align:"start",className:"w-auto p-2",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"grid grid-cols-3 items-center justify-items-center gap-1",children:Tl.map(d=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border-2 transition-all",i()===d?"border-gray-900":"border-transparent"),style:{backgroundColor:d},onClick:()=>{a(d),l(!1)},children:e.jsx("span",{className:"sr-only",children:d})},d))}),e.jsx("button",{className:"w-full rounded border border-input px-2 py-1 text-xs hover:bg-muted",onClick:()=>{c(!0),l(!1)},children:"Custom color..."})]})})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:n})]}),o&&e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/50",onClick:()=>c(!1)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(Pt,{color:i(),onColorChange:d=>{a(d),c(!1)},onClose:()=>c(!1)})})]})]})}const Ze={difference:{label:"Difference",description:"Shows the exact difference between two values.",formula:"Primary - Secondary",example:"Sales increased by $5,000 compared to last year."},change:{label:"Change",description:"Shows the percentage increase or decrease between two values.",formula:"(Primary - Secondary) / Secondary × 100%",example:"Year-over-year sales change of 25%."},change_difference:{label:"Change (difference)",description:"Shows both the percentage change and the exact difference between two values.",formula:`% Change: (Primary - Secondary) / Secondary × 100%
|
|
355
|
+
Difference: Primary - Secondary`,example:"Sales grew by 25% ($5,000) compared to last year."},ratio:{label:"Ratio",description:"Shows how much of one value is covered by another — useful for quotas and benchmarks.",formula:"Primary / Secondary × 100%",example:"You've achieved 80% of your sales quota."}};function El(){var i,d,u,m,h,f,g,b,p,j;const t=s.useEditorStore(x=>x.card),{setCardPreferences:a}=s.useEditorActions(),n=((i=t.config)==null?void 0:i.metricColumns)||[],r=((d=t.config)==null?void 0:d.groupByColumns)||[];if(!(t.type==="kpi"&&(n.length>=2&&r.length===0||n.length>=1&&r.length>0)))return null;const o=((m=(u=t.preferences)==null?void 0:u.kpiVisualOptions)==null?void 0:m.metricComparison)||{},c=x=>{var k;const v={...t.preferences,kpiVisualOptions:{...(k=t.preferences)==null?void 0:k.kpiVisualOptions,metricComparison:{...o,...x}}};a(v)};return e.jsxs(s.AccordionItem,{value:"comparison",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ya,{className:"h-4 w-4"}),e.jsx("span",{children:"Comparison"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{htmlFor:"enable-comparison",className:"text-xs",children:"Enable Metric Comparison"}),e.jsx(s.SmallSwitch,{id:"enable-comparison",checked:o.enabled||!1,onCheckedChange:x=>c({enabled:x,...x&&!o.calculationType?{calculationType:"difference"}:{}})})]}),o.enabled&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"calculation-type",className:"text-xs font-medium uppercase text-muted-foreground",children:"Calculated as"}),e.jsxs(s.Select,{value:o.calculationType||"difference",onValueChange:x=>c({calculationType:x}),children:[e.jsx(s.SelectTrigger,{id:"calculation-type",className:"h-7 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Object.entries(Ze).map(([x,v])=>e.jsx(s.SelectItem,{value:x,className:"text-xs",children:v.label},x))})]}),(()=>{var v,k,L;const x=o.calculationType||"difference";return e.jsxs("div",{className:"space-y-2 rounded-md bg-muted/50 p-2 text-xs",children:[e.jsx("p",{className:"text-muted-foreground",children:(v=Ze[x])==null?void 0:v.description}),e.jsxs("div",{className:"text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Formula:"})," ",e.jsx("code",{className:"rounded bg-background px-1 py-0.5 text-[10px]",children:(k=Ze[x])==null?void 0:k.formula})]}),e.jsxs("div",{className:"border-t pt-1 italic text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Example:"})," ",(L=Ze[x])==null?void 0:L.example]})]})})()]}),e.jsx(Ts,{formatOptions:o.formatOptions||{},onFormatOptionsChange:x=>c({formatOptions:x}),showTitle:!0,title:"COMPARISON FORMAT"}),e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Indicator"}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Position"}),e.jsxs(s.Select,{value:o.position||"left",onValueChange:x=>c({position:x}),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-20 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"top",className:"text-xs",children:"Top"}),e.jsx(s.SelectItem,{value:"left",className:"text-xs",children:"Left"}),e.jsx(s.SelectItem,{value:"right",className:"text-xs",children:"Right"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"show-arrow",checked:o.showArrow!==!1,onCheckedChange:x=>c({showArrow:x})}),e.jsx(s.Label,{htmlFor:"show-arrow",className:"cursor-pointer text-xs text-muted-foreground",children:"Arrow"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"show-color",checked:o.showColor!==!1,onCheckedChange:x=>c({showColor:x})}),e.jsx(s.Label,{htmlFor:"show-color",className:"cursor-pointer text-xs text-muted-foreground",children:"Color"})]}),o.showColor!==!1&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-3",children:[e.jsx(fs,{value:((h=o.colorConfig)==null?void 0:h.increase)||"green",onChange:x=>c({colorConfig:{...o.colorConfig,increase:x}}),label:"Primary > Secondary"}),e.jsx(fs,{value:((f=o.colorConfig)==null?void 0:f.decrease)||"red",onChange:x=>c({colorConfig:{...o.colorConfig,decrease:x}}),label:"Primary < Secondary"}),e.jsx(fs,{value:((g=o.colorConfig)==null?void 0:g.noChange)||"neutral",onChange:x=>c({colorConfig:{...o.colorConfig,noChange:x}}),label:"Primary = Secondary"})]})]}),e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Label"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"conditional-label",checked:o.conditionalLabel||!1,onCheckedChange:x=>c({conditionalLabel:x})}),e.jsx(s.Label,{htmlFor:"conditional-label",className:"cursor-pointer text-xs text-muted-foreground",children:"Conditional"})]}),o.conditionalLabel?e.jsxs("div",{className:"space-y-3 border-l-2 border-muted pl-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"label-increase",className:"text-xs text-muted-foreground",children:["Primary ",">"," Secondary"]}),e.jsx(s.Input,{id:"label-increase",type:"text",value:((b=o.conditionalLabels)==null?void 0:b.increase)??"Increase",onChange:x=>c({conditionalLabels:{...o.conditionalLabels,increase:x.target.value}}),placeholder:"Increase",className:"h-7 text-xs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"label-decrease",className:"text-xs text-muted-foreground",children:["Primary ","<"," Secondary"]}),e.jsx(s.Input,{id:"label-decrease",type:"text",value:((p=o.conditionalLabels)==null?void 0:p.decrease)??"Decrease",onChange:x=>c({conditionalLabels:{...o.conditionalLabels,decrease:x.target.value}}),placeholder:"Decrease",className:"h-7 text-xs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"label-no-change",className:"text-xs text-muted-foreground",children:"Primary = Secondary"}),e.jsx(s.Input,{id:"label-no-change",type:"text",value:((j=o.conditionalLabels)==null?void 0:j.noChange)??"No change",onChange:x=>c({conditionalLabels:{...o.conditionalLabels,noChange:x.target.value}}),placeholder:"No change",className:"h-7 text-xs"})]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"label-name",className:"text-xs text-muted-foreground",children:"Name"}),e.jsx(s.Input,{id:"label-name",type:"text",value:o.labelName??"",onChange:x=>c({labelName:x.target.value}),placeholder:"e.g. Versus, Compared to",className:"h-7 text-xs"})]})]})]})]})]})}function Il(){var l,o;const t=s.useEditorStore(c=>c.card),{setCardPreferences:a}=s.useEditorActions();if(t.type!=="kpi")return null;const n=((o=(l=t.preferences)==null?void 0:l.kpiVisualOptions)==null?void 0:o.formatOptions)||{},r=c=>{var d;const i={...t.preferences,kpiVisualOptions:{...(d=t.preferences)==null?void 0:d.kpiVisualOptions,formatOptions:c}};a(i)};return e.jsxs(s.AccordionItem,{value:"kpi-format",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ne,{className:"h-4 w-4"}),e.jsx("span",{children:"Number Format"})]})}),e.jsx(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:e.jsx(Ts,{formatOptions:n,onFormatOptionsChange:r,showTitle:!1})})]})}function Al({groupByFields:t,pivotByFields:a,metricsFields:n,sortByFields:r}){const l=s.useEditorStore(b=>{var p;return((p=b.card.customCardPreferences)==null?void 0:p.url)&&b.card.type==="custom"}),o=s.useEditorStore(b=>b.card),c=o==null?void 0:o.type,i=t.length>0||n.length>0,d=c!=="kpi",u=c!=="kpi"&&i,m=["pie","doughnut","polar","funnel","aggregateTable"].includes(c),h=d&&!m,f=()=>c==="kpi"?{label:"Trend By",placeholder:"Drop fields to trend data"}:{label:"Rows",placeholder:"Drop fields to group data"},g=()=>c==="kpi"?{label:"Metric",placeholder:"Drop field for KPI"}:{label:"Metrics",placeholder:"Drop fields to measure"};return e.jsxs(s.Accordion,{type:"single",collapsible:!0,defaultValue:"fields",className:"w-full",children:[e.jsxs(s.AccordionItem,{value:"fields",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ka,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"FIELDS"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pt-2",children:[e.jsx(Xe,{zone:"groupBy",fields:t,label:f().label,placeholder:f().placeholder}),h&&e.jsx(Xe,{zone:"pivotBy",fields:a,label:"Columns",placeholder:"Drop fields to pivot data"}),e.jsx(Xe,{zone:"metrics",fields:n,label:g().label,placeholder:g().placeholder,hasPivotColumns:a.length>0}),u&&e.jsx(Xe,{zone:"sortBy",fields:r,label:"Sort By",placeholder:"Drop fields from Rows or Metrics"})]})]}),!l&&e.jsxs(s.AccordionItem,{value:"configuration",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Settings,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"CONFIGURATION"})]})}),e.jsx(s.AccordionContent,{className:"rounded-md border border-border bg-muted/50 px-3 py-0",children:e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full",children:[e.jsx(Il,{}),e.jsx(El,{}),e.jsx(zt,{}),e.jsx(Vt,{}),e.jsx(_t,{}),e.jsx(Ut,{})]})})]})]})}function Ml({selectedChart:t,onChartChange:a,groupByFields:n,pivotByFields:r,metricsFields:l,sortByFields:o}){const c=s.useEditorStore(h=>h.showAIDialog),i=n.length>0||r.length>0||l.length>0,{setShowAIDialog:d}=s.useEditorActions(),u=s.useEditorStore(h=>h.card),{data:m}=s.useDashboardCardQuery(u);return e.jsxs("div",{"data-content":"Chart Configuration Panel",className:"flex w-[350px] flex-col",children:[e.jsxs("div",{className:"space-y-4 px-6 pt-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("h2",{className:"font-semibold",children:"Chart Configuration"})}),e.jsx(gl,{selectedChart:t,onChartChange:a}),e.jsx(yl,{selectedChart:t,onChartChange:a})]}),e.jsxs("div",{className:s.cn("flex justify-end gap-2 px-6 py-6"),children:[e.jsx("div",{className:s.cn("invisible",{visible:i||m}),children:e.jsx(rs,{})}),!c&&e.jsxs(s.Button,{onClick:()=>d(!c),variant:"outline",className:"h-8",size:"sm",children:[e.jsx(s.Sparkles,{className:"mr-2 size-4"}),"AI"]})]}),e.jsxs(s.ScrollArea,{className:"w-full flex-1 basis-0 px-6 pb-6",children:[e.jsx(Al,{groupByFields:n,pivotByFields:r,metricsFields:l,sortByFields:o}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Ll({initialFilters:t,availableFields:a}={}){const[n,r]=I.useState(t||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});s.useEditorStore(C=>C.card.dataSource);const{columns:l,isLoading:o}=s.useColumns(),i=a||l||[],d={id:"default",qualifiedFieldName:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},u=C=>{const S=y=>{if(y.id===C){const D=i[0]||d,N=s.getDataType(D.dataType)==="date";return{...y,conditions:[...y.conditions,{id:`condition-${Date.now()}`,field:D,operator:N?"between":"=",value:N?[]:""}]}}return{...y,groups:y.groups.map(S)}};r(S(n))},m=C=>{const S=y=>{if(y.id===C){const D=i[0]||d,N=s.getDataType(D.dataType)==="date";return{...y,groups:[...y.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:D,operator:N?"between":"=",value:N?[]:""}],groups:[]}]}}return{...y,groups:y.groups.map(S)}};r(S(n))},h=(C,S)=>{const y=D=>D.id===C?{...D,conditions:D.conditions.filter(N=>N.id!==S)}:{...D,groups:D.groups.map(y)};r(y(n))},f=(C,S)=>{const y=D=>D.id===C?{...D,groups:D.groups.filter(N=>N.id!==S)}:{...D,groups:D.groups.map(y)};r(y(n))},g=(C,S,y,D)=>{if(y==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const N=B=>B.id===C?{...B,conditions:B.conditions.map(w=>w.id===S?{...w,[y]:D}:w)}:{...B,groups:B.groups.map(N)};r(N(n))},b=(C,S,y)=>{const D=N=>N.id===C?{...N,conditions:N.conditions.map(B=>B.id===S?{...B,...y}:B)}:{...N,groups:N.groups.map(D)};r(D(n))},p=(C,S)=>{const y=D=>D.id===C?{...D,logicalOperator:S}:{...D,groups:D.groups.map(y)};r(y(n))},j=(C,S)=>{const y=D=>D.id===C?{...D,negate:S}:{...D,groups:D.groups.map(y)};r(y(n))},x=(C,S,y)=>{const D=N=>N.id===C?{...N,conditions:s.arrayMove(N.conditions,S,y)}:{...N,groups:N.groups.map(D)};r(D(n))},v=(C,S,y)=>{const D=N=>N.id===C?{...N,groups:s.arrayMove(N.groups,S,y)}:{...N,groups:N.groups.map(D)};r(D(n))},k=C=>{if(!C||C.conditions.length===0&&C.groups.length===0)return"-- No filters defined";const S=D=>{let N="";typeof D.field=="object"?N=D.field.entityName?`${D.field.entityName}.${D.field.name}`:D.field.name:N=String(D.field);const B=D.operator;let w=D.value;if(D.field.dataType==="string"&&!["in","not in"].includes(D.operator))typeof w=="string"?w=`'${w}'`:Array.isArray(w)&&(w=`'${w.join(", ")}'`);else if(D.field.dataType==="date"||D.field.dataType==="datetime"||D.field.dataType==="timestamp")if(D.operator==="between"&&Array.isArray(w)&&w.length===2){const F=w[0]?`'${w[0]}'`:"NULL",T=w[1]?`'${w[1]}'`:"NULL";return`${N} BETWEEN ${F} AND ${T}`}else if((D.operator==="in"||D.operator==="not in")&&Array.isArray(w)){const F=w.map(T=>T?`'${T}'`:"NULL").join(", ");return`${N} ${B} (${F})`}else typeof w=="string"||w instanceof Date?w=`'${w}'`:Array.isArray(w)&&w.length>0&&(w=`'${w[0]}'`);else if(["in","not in"].includes(D.operator)){let F=[];Array.isArray(w)?F=w.map(T=>typeof T=="string"?`'${T}'`:String(T)):typeof w=="string"?F=w.split(",").map(T=>{const E=T.trim();return D.field.dataType==="string"?`'${E}'`:E}):typeof w=="number"&&(F=[String(w)]),w=`(${F.join(", ")})`}switch(B){case"contains":return typeof w=="string"?`${N} LIKE '%${w.replace(/'/g,"")}'`:`${N} LIKE '%${String(w)}'`;case"startsWith":return typeof w=="string"?`${N} LIKE '${w.replace(/'/g,"")}%'`:`${N} LIKE '${String(w)}%'`;case"endsWith":return typeof w=="string"?`${N} LIKE '%${w.replace(/'/g,"")}'`:`${N} LIKE '%${String(w)}'`;case"isNull":return`${N} IS NULL`;case"isNotNull":return`${N} IS NOT NULL`;default:return`${N} ${B} ${w}`}},y=D=>{const N=D.conditions.map(S),B=D.groups.map(E=>y(E)),w=[...N,...B].filter(Boolean);if(w.length===0)return"";const F=w.join(` ${D.logicalOperator} `),T=w.length>1?`(${F})`:F;return D.negate?`NOT ${T}`:T};return y(C)},L=n.conditions.length>0||n.groups.length>0;return{currentFilters:n,setCurrentFilters:r,availableFields:i,isLoading:o,addCondition:u,addGroup:m,removeCondition:h,removeGroup:f,updateCondition:g,updateConditionFields:b,updateGroupOperator:p,updateGroupNegate:j,reorderConditions:x,reorderGroups:v,generateSQLPreview:k,hasAnyFilters:L}}function Rl({children:t,className:a,delayDuration:n}){return e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{delayDuration:n,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:s.cn("w-[200px] overflow-hidden text-ellipsis whitespace-nowrap text-sm",a),children:t})}),e.jsx(s.PortalTooltipContent,{children:t})]})})}const Ol=t=>{switch(t){case"table":return e.jsx(s.Table,{className:"h-3 w-3"});case"view":return e.jsx(s.Eye,{className:"h-3 w-3"});case"dataset":return e.jsx(s.ChartColumn,{className:"h-3 w-3"});case"file":return e.jsx(s.File,{className:"h-3 w-3"});default:return e.jsx(s.Table,{className:"h-3 w-3"})}},Bl=t=>{if(t.qualifiedEntityName){const a=t.qualifiedEntityName.split(".");return a.length>1?a[0]:"default"}return"default"};function Fl({value:t,onValueChange:a,availableFields:n,placeholder:r="Select field",className:l="w-64"}){const[o,c]=I.useState(!1),i=I.useMemo(()=>{const d={};return n.forEach(u=>{const m=Bl(u);d[m]||(d[m]={}),d[m][u.entityId]||(d[m][u.entityId]=[]),d[m][u.entityId].push(u)}),d},[n]);return e.jsxs(s.Popover,{modal:!0,open:o,onOpenChange:c,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":o,className:s.cn("justify-between",!t&&"text-muted-foreground",l),children:[t?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(Rl,{children:[t.entityName,".",t.name]})}):r,e.jsx(s.ChevronsUpDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"z-50 w-80 p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search fields...",className:"h-9"}),e.jsx(s.CommandEmpty,{children:"No fields found."}),e.jsx(s.CommandList,{className:"max-h-80",children:Object.entries(i).map(([d,u])=>e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Database,{className:"h-3 w-3"}),d]}),children:Object.entries(u).map(([m,h])=>e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 bg-gray-50/50 px-2 py-1 text-xs font-medium text-gray-600",children:[Ol(h[0].entityType),e.jsx("span",{children:h[0].entityName})]}),h.map((f,g)=>e.jsxs(s.CommandItem,{value:f.id,onSelect:()=>{a(f),c(!1)},className:"overflow-x-auto",children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",(t==null?void 0:t.id)===f.id?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{className:"",children:f.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:f.description&&e.jsx("span",{children:f.description})})]})]},f.id+g))]},`${d}-${m}`))},d))})]})})]})}function Ms(t){var b;const a=s.useEditorStore(p=>p.card),{authToken:n}=s.useSemaphorContext(),r=s.useEditorStore(p=>p.card.config),l=r==null?void 0:r.joinPlan,o={...t,alias:t.name,label:"value",role:"groupby"},c={...t,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},i={...o,role:"sortby",direction:"asc"},d={joinPlan:l,groupByColumns:[o],metricColumns:[c],sortByColumns:[i]},u=((b=a.dataSource)==null?void 0:b.connectionId)||a.connectionId,{data:m,isPending:h,error:f}=s.useQuery({queryKey:["filterValues",t.entityId,t.name,t.qualifiedEntityName],queryFn:async()=>{try{return await s.postRequestRegular("https://semaphor.cloud/api/v1/query",(n==null?void 0:n.accessToken)||"",{connection_id:u,cardConfig:d,cardDataSource:a.dataSource})}catch(p){console.log(t),console.error("error",p)}},enabled:!!u,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((m==null?void 0:m.records)||[]).map(p=>({label:p.value||"BLANK",value:p.value||"BLANK",count:(p==null?void 0:p.count)||0})),isPending:h,error:f}}function Pl({field:t,selected:a,onChange:n,placeholder:r="Select items...",className:l}){const[o,c]=ke.useState(!1),{filterValues:i}=Ms(t),d=m=>{n(a.filter(h=>h!==m))},u=m=>{a.includes(m)?n(a.filter(h=>h!==m)):n([...a,m])};return e.jsx("div",{className:s.cn("w-full",l),children:e.jsxs(s.Popover,{open:o,onOpenChange:c,modal:!0,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":o,className:"h-auto min-h-10 w-full justify-between p-2",children:[e.jsx("div",{className:"flex flex-1 flex-wrap gap-1",children:a.length>0?a.map(m=>{const h=i.find(f=>f.value===m);return e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[h==null?void 0:h.label,e.jsx("div",{className:"ml-1 rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:f=>{f.key==="Enter"&&d(m)},onMouseDown:f=>{f.preventDefault(),f.stopPropagation()},onClick:f=>{f.stopPropagation(),d(m)},children:e.jsx(s.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},m)}):e.jsx("span",{className:"text-muted-foreground",children:r})}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"z-50 w-fit overflow-auto p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search..."}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No results found."}),e.jsx(s.CommandGroup,{children:i.map((m,h)=>e.jsxs(s.CommandItem,{onSelect:()=>u(m.value),children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",a.includes(m.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:m.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:m.count})]})]},m.value+h))})]})]})})]})})}function zl({field:t,value:a,onChange:n,placeholder:r="Select value...",className:l}){const{filterValues:o,isPending:c,error:i}=Ms(t);return c?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):i?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsxs(s.Select,{value:a,onValueChange:n,children:[e.jsx(s.SelectTrigger,{className:l||"flex-1",children:e.jsx(s.SelectValue,{placeholder:r,children:a})}),e.jsx(s.SelectContent,{children:o.map((d,u)=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:d.value,children:d.label},d.value+u))})]})}function Vl({value:t,operator:a,onChange:n,className:r}){var d;const{tokenProps:l}=s.useSemaphorContext(),o=(d=l==null?void 0:l.params)==null?void 0:d.timeZone,c=I.useMemo(()=>{if(t){if(a==="between"||a==="not between"){if(Array.isArray(t)&&t.length===2){const u=t[0]?new Date(t[0]):void 0,m=t[1]?new Date(t[1]):void 0;if(u&&m)return{from:u,to:m}}}else if(a==="="||a==="!="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:u,to:u}}}else if(a===">"||a===">="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:u,to:void 0}}}else if(a==="<"||a==="<="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:void 0,to:u}}}else if((a==="in"||a==="not in")&&Array.isArray(t)&&t.length>0){const u=new Date(t[0]),m=t.length>1?new Date(t[t.length-1]):u;if(!isNaN(u.getTime()))return{from:u,to:m}}}},[t,a]),i=u=>{if(!u){n(void 0);return}if(u.from&&u.to)n([u.from.toISOString(),u.to.toISOString()]);else if(u.from){const m=new Date(u.from);m.setHours(23,59,59,999),n([u.from.toISOString(),m.toISOString()])}else if(u.to){const m=new Date(u.to);m.setHours(0,0,0,0),n([m.toISOString(),u.to.toISOString()])}};return e.jsx(s.DateRangePicker,{value:c,onChange:i,timezone:o,showRelativeTab:!0,className:r,placeholder:"Select date..."})}const _l=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],Ul=["=","!=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],$l=["=","!=",">",">=","<","<=","in","not in","isNull","isNotNull"],Yl=["=","!=","isNull","isNotNull"],ql=["between","isNull","isNotNull"],Gl={"=":"Equals","!=":"Not Equals",">":"Greater Than",">=":"Greater Than or Equal","<":"Less Than","<=":"Less Than or Equal",contains:"Contains",startsWith:"Starts With",endsWith:"Ends With",in:"In","not in":"Not In",between:"Between",isNull:"Is Null",isNotNull:"Is Not Null"};function Xs(t){return Gl[t]||s.titleCase(t)}function Hl(t){switch(t){case"string":return Ul;case"number":return $l;case"boolean":return Yl;case"date":return ql;default:return _l}}function Gt({condition:t,index:a,groupId:n,groupLogicalOperator:r,onUpdateCondition:l,onRemoveCondition:o,onUpdateGroupOperator:c,availableFields:i,updateConditionFields:d}){const{attributes:u,listeners:m,setNodeRef:h,transform:f,transition:g,isDragging:b}=s.useSortable({id:t.id}),{isPending:p,error:j}=Ms(t.field),x={transform:s.CSS.Transform.toString(f),transition:g};return e.jsxs("div",{ref:h,style:x,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${b?"z-50 opacity-50":""}`,children:[e.jsx("div",{...u,...m,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 flex-shrink-0 text-gray-400"})}),a>0&&e.jsxs(s.Select,{value:r,onValueChange:v=>c(n,v),children:[e.jsx(s.SelectTrigger,{className:"w-24",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"AND",children:"AND"}),e.jsx(s.SelectItem,{value:"OR",children:"OR"})]})]}),a===0&&e.jsx("div",{className:"w-24"}),e.jsx(Fl,{value:t.field,onValueChange:v=>{const k=v,L=s.getDataType(k.dataType)==="date";d(n,t.id,{field:k,value:"",operator:L?"between":"="})},availableFields:i,placeholder:"Select field",className:"w-64"}),e.jsxs(s.Select,{value:t.operator,onValueChange:v=>{v==="in"||v==="not in"?d(n,t.id,{operator:v,value:[]}):v==="isNull"||v==="isNotNull"?d(n,t.id,{operator:v,value:null}):d(n,t.id,{operator:v,value:""})},children:[e.jsx(s.SelectTrigger,{className:"w-32",children:e.jsx(s.SelectValue,{children:t.operator?Xs(t.operator):""})}),e.jsx(s.SelectContent,{children:Hl(s.getDataType(t.field.dataType)).map(v=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:v,children:Xs(v)},v))})]}),t.operator==="isNull"||t.operator==="isNotNull"?e.jsx("div",{className:"flex-1"}):s.getDataType(t.field.dataType)==="string"?t.operator==="in"||t.operator==="not in"?p?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):j?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsx(Pl,{field:t.field,selected:Array.isArray(t.value)&&t.value.every(v=>typeof v=="string")?t.value:[],onChange:v=>d(n,t.id,{value:v}),placeholder:`Select values for ${t.operator}...`,className:"flex-1"}):["contains","startsWith","endsWith"].includes(t.operator)?e.jsx(s.Input$1,{value:typeof t.value=="string"?t.value:"",onChange:v=>d(n,t.id,{value:v.target.value}),className:"flex-1",placeholder:t.operator.charAt(0).toUpperCase()+t.operator.slice(1)+"..."}):e.jsx(zl,{field:t.field,value:typeof t.value=="string"?t.value:"",onChange:v=>d(n,t.id,{value:v}),placeholder:"Select value...",className:"flex-1"}):s.getDataType(t.field.dataType)==="boolean"?e.jsxs(s.Select,{value:typeof t.value=="boolean"?String(t.value):"",onValueChange:v=>d(n,t.id,{value:v==="true"}),children:[e.jsx(s.SelectTrigger,{className:"flex-1",children:e.jsx(s.SelectValue,{placeholder:"Select value..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"true",children:"True"}),e.jsx(s.SelectItem,{value:"false",children:"False"})]})]}):s.getDataType(t.field.dataType)==="date"?e.jsx(Vl,{value:t.value,operator:t.operator,onChange:v=>d(n,t.id,{value:v}),className:"flex-1"}):e.jsx(s.Input$1,{value:typeof t.value=="string"||typeof t.value=="number"?t.value:"",onChange:v=>l(n,t.id,"value",v.target.value),className:"flex-1",placeholder:t.operator==="in"||t.operator==="not in"?"value1, value2, value3":"Value"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 flex-shrink-0 p-0",onClick:()=>o(n,t.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})}function Wl({group:t,depth:a,parentGroupId:n,onUpdateGroupOperator:r,onUpdateGroupNegate:l,onRemoveGroup:o,onUpdateCondition:c,onUpdateField:i,onRemoveCondition:d,onReorderConditions:u,onReorderGroups:m,onAddCondition:h,onAddGroup:f,availableFields:g,renderFilterGroup:b,updateConditionFields:p}){const{attributes:j,listeners:x,setNodeRef:v,transform:k,transition:L,isDragging:C}=s.useSortable({id:t.id}),S={transform:s.CSS.Transform.toString(k),transition:L},y=N=>{const{active:B,over:w}=N;if(w&&B.id!==w.id){const F=t.conditions.findIndex(E=>E.id===B.id),T=t.conditions.findIndex(E=>E.id===w.id);F!==-1&&T!==-1&&u(t.id,F,T)}},D=N=>{const{active:B,over:w}=N;if(w&&B.id!==w.id&&n){const F=t.groups.findIndex(E=>E.id===B.id),T=t.groups.findIndex(E=>E.id===w.id);F!==-1&&T!==-1&&m(n,F,T)}};return e.jsxs("div",{ref:v,style:S,className:`rounded-lg ${a>0?"mt-2 border border-border":""} ${C?"z-50 opacity-50":""}`,children:[a>0&&e.jsxs("div",{className:"flex items-center justify-between rounded-t-lg bg-muted p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{...j,...x,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(s.Button,{variant:t.negate?"default":"outline",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>l(t.id,!t.negate),children:"NOT"}),e.jsxs(s.Select,{value:t.logicalOperator,onValueChange:N=>r(t.id,N),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-20",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"OR",children:"OR"})]})]}),e.jsx("span",{className:"text-sm font-medium",children:"Group"})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>n&&o(n,t.id),children:e.jsx(s.Trash2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:`p-3 ${a>0?"":"px-0"}`,children:[e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:y,children:e.jsx(s.SortableContext,{items:t.conditions.map(N=>N.id),strategy:s.verticalListSortingStrategy,children:t.conditions.map((N,B)=>e.jsx(Gt,{condition:N,index:B,groupId:t.id,groupLogicalOperator:t.logicalOperator,onUpdateCondition:c,onUpdateField:i,onRemoveCondition:d,onUpdateGroupOperator:r,availableFields:g,updateConditionFields:p},N.id))})}),e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:D,children:e.jsx(s.SortableContext,{items:t.groups.map(N=>N.id),strategy:s.verticalListSortingStrategy,children:t.groups.map(N=>b(N,a+1,t.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(s.Button,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>h(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>f(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function Kl({filters:t,availableFields:a,onSave:n,onClearAll:r,onCancel:l}){const{currentFilters:o,availableFields:c,isLoading:i,addCondition:d,addGroup:u,removeCondition:m,removeGroup:h,updateCondition:f,updateConditionFields:g,updateGroupOperator:b,updateGroupNegate:p,reorderConditions:j,reorderGroups:x,generateSQLPreview:v,hasAnyFilters:k,setCurrentFilters:L}=Ll({initialFilters:t,availableFields:a}),C=s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),[S,y]=I.useState(!1),D=(w,F,T)=>{const E=A=>A.id===w?{...A,conditions:A.conditions.map(O=>O.id===F?{...O,field:T,dataType:T.dataType}:O)}:{...A,groups:A.groups.map(E)};L(E(o))},N=(w,F=0,T)=>F===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(s.DndContext,{sensors:C,collisionDetection:s.closestCenter,onDragEnd:E=>{const{active:A,over:O}=E;if(O&&A.id!==O.id){const M=w.conditions.findIndex(P=>P.id===A.id),R=w.conditions.findIndex(P=>P.id===O.id);M!==-1&&R!==-1&&j(w.id,M,R)}},children:e.jsx(s.SortableContext,{items:w.conditions.map(E=>E.id),strategy:s.verticalListSortingStrategy,children:w.conditions.map((E,A)=>e.jsx(Gt,{condition:E,index:A,groupId:w.id,groupLogicalOperator:w.logicalOperator,onUpdateCondition:f,onUpdateField:D,onRemoveCondition:m,onUpdateGroupOperator:b,availableFields:c,updateConditionFields:g},E.id))})}),e.jsx(s.DndContext,{sensors:C,collisionDetection:s.closestCenter,onDragEnd:E=>{const{active:A,over:O}=E;if(O&&A.id!==O.id){const M=w.groups.findIndex(P=>P.id===A.id),R=w.groups.findIndex(P=>P.id===O.id);M!==-1&&R!==-1&&x(w.id,M,R)}},children:e.jsx(s.SortableContext,{items:w.groups.map(E=>E.id),strategy:s.verticalListSortingStrategy,children:w.groups.map(E=>N(E,F+1,w.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(s.Button,{size:"sm",className:"h-7 text-xs",variant:"outline",onClick:()=>d(w.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),S&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>u(w.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},w.id):e.jsx(Wl,{group:w,depth:F,parentGroupId:T,onUpdateGroupOperator:b,onUpdateGroupNegate:p,onRemoveGroup:h,onUpdateCondition:f,onUpdateField:D,onRemoveCondition:m,onReorderConditions:j,onReorderGroups:x,onAddCondition:d,onAddGroup:u,availableFields:c,renderFilterGroup:N,updateConditionFields:g},w.id),B=s.getFilterCount(t);return e.jsxs("div",{className:"space-y-4",children:[e.jsx(s.Card,{children:e.jsx(s.CardContent,{className:"p-4",children:e.jsxs("div",{className:"space-y-4",children:[i?e.jsxs("div",{className:"flex items-center justify-center p-4",children:[e.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-gray-300 border-t-gray-600"}),e.jsx("span",{className:"ml-2 text-sm text-gray-600",children:"Loading columns..."})]}):N(o),e.jsx("div",{className:"mt-4 border-t border-border pt-4",children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{id:"advanced-mode",checked:S,onCheckedChange:w=>y(!!w)}),e.jsx("label",{htmlFor:"advanced-mode",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Advanced mode (enable grouping)"})]})}),k&&e.jsxs("div",{className:"mt-4 border-t border-border pt-4",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"SQL WHERE Clause Preview"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap font-mono text-xs text-muted-foreground",children:v(o)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"outline",onClick:l,children:"Cancel"}),B>0&&e.jsx(s.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(s.Button,{size:"sm",onClick:()=>n(k?o:null),children:"Apply Filters"})]})]})}function Jl({cardId:t,filters:a,onFiltersChange:n,onClearFilters:r,availableFields:l,isOpen:o,onOpenChange:c}){const i=u=>{n(t,u),c(!1)},d=()=>{r(t),c(!1)};return e.jsxs(s.Dialog,{modal:!1,open:o,onOpenChange:c,children:[o&&e.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),e.jsxs(s.DialogContent,{className:"max-h-[80vh] max-w-4xl overflow-y-auto",onInteractOutside:u=>{u.preventDefault()},children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Card Filters"}),e.jsx(s.DialogDescription,{children:"Add filters to the card to limit the data that is displayed."})]}),e.jsx(Kl,{filters:a,availableFields:l,onSave:i,onCancel:()=>c(!1),onClearAll:d})]})]})}function Ql({activeCardId:t,sourceFields:a,getFieldsForContainer:n,setFieldsForContainer:r}){var g;const[l,o]=I.useState(null),c=s.useEditorStore(b=>b.card),i=(g=c==null?void 0:c.config)==null?void 0:g.joinPlan,d=[...a,...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")],u=I.useCallback(b=>b.startsWith("card-")?null:b.startsWith("source-")||a.find(p=>p.id===b)?"source":n("groupBy").find(p=>p.id===b)?"groupBy":n("metrics").find(p=>p.id===b)?"metrics":n("pivotBy").find(p=>p.id===b)?"pivotBy":n("sortBy").find(p=>p.id===b)?"sortBy":null,[a,n]),m=I.useCallback(b=>{o(b.active.id)},[]),h=I.useCallback(b=>{const{active:p,over:j}=b;if(!j||!t){o(null);return}const x=p.id,v=j.id,k=u(x),L=u(v)||v;if(L==="sortBy"){if(k==="source"){const C=a.find(y=>y.id===x);if(!C){o(null);return}if(!(n("groupBy").some(y=>y.name===C.name&&y.qualifiedEntityName===C.qualifiedEntityName)||n("metrics").some(y=>y.name===C.name&&y.qualifiedEntityName===C.qualifiedEntityName))){o(null);return}}else if(k==="pivotBy"){o(null);return}else if(k!=="groupBy"&&k!=="metrics"&&k!=="sortBy"){o(null);return}}if(k==="source"&&L==="sortBy"){const C=[...a].find(D=>D.id===x);if(!C){o(null);return}const S=n("sortBy");if(s.fieldAlreadyExists(C,S)){o(null);return}const y=s.getNewField(C,"sortBy",S);o(null),r("sortBy",[...S,y]);return}if(k==="source"&&L!=="source"&&L!=="sortBy"){const C=[...a].find(N=>N.id===x);if(!C){o(null);return}const S=[...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")];if(S.length>0){const N=S[0].qualifiedEntityName;if(!N){o(null);return}if(N!==C.qualifiedEntityName&&C.qualifiedEntityName)if(i){if(!s.areEntitiesJoined(N,C.qualifiedEntityName,i)){s.showJoinRequiredNotification(),o(null);return}}else{s.showJoinRequiredNotification(),o(null);return}}const y=n(L);if(s.fieldAlreadyExists(C,y)){o(null);return}const D=s.getNewField(C,L,y);o(null),r(L,[...y,D]);return}if(k&&L&&k!=="source"&&L!=="source"&&k!==L){const C=n(k),S=n(L),y=C.find(B=>B.id===x);if(!y){o(null);return}const D=s.getNewField(y,L,S);if(o(null),L==="sortBy"){s.fieldAlreadyExists(y,S)||r(L,[...S,D]);return}const N=C.filter(B=>B.id!==x);r(k,N),r(L,[...S,D]);return}if(k&&L&&k===L&&k!=="source"){const C=n(k),S=C.findIndex(D=>D.id===x),y=C.findIndex(D=>D.id===v);if(S!==y){const D=s.arrayMove(C,S,y);r(k,D)}}o(null)},[t,a,n,r,u,i]),f=l?d.find(b=>b.id===l):null;return{activeId:l,activeField:f,handleDragStart:m,handleDragEnd:h}}function Xl({dashboardFilterCount:t=0,cardFilterCount:a=0,clickFilterCount:n=0,onClick:r,className:l,showIcon:o=!0}){const c=t+a+n,i=c>0,d=t>0,u=a>0,m=n>0,h=e.jsxs(e.Fragment,{children:[o&&e.jsx(s.Filter,{className:"h-3.5 w-3.5"}),i&&e.jsx("span",{className:"font-medium",children:c})]}),f=e.jsx(s.Button,{variant:i?"secondary":"outline",size:"sm",onClick:r,className:s.cn("h-8 gap-1.5 transition-all",l),children:h});return i?e.jsx(s.TooltipProvider$1,{children:e.jsxs(s.Tooltip,{delayDuration:200,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:f}),e.jsx(s.TooltipContent,{side:"bottom",align:"start",className:"p-2 text-xs",children:e.jsxs("div",{className:"space-y-1.5",children:[d&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-2 w-2 rounded-full bg-purple-500"}),e.jsxs("span",{children:[t," Dashboard filter",t!==1?"s":""]})]}),u&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-2 w-2 rounded-full bg-blue-500"}),e.jsxs("span",{children:[a," Card filter",a!==1?"s":""]})]}),m&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-2 w-2 rounded-full bg-gray-500"}),e.jsxs("span",{children:[n," Click filter",n!==1?"s":""]})]})]})})]})}):f}function Zl({onAdvancedToggle:t,onDebugToggle:a,onAccept:n}){const{currentUser:r}=s.useCurrentUserInfo();r==null||r.role;const[l,o]=I.useState(!1),c=s.useEditorStore(x=>x.isDevMode),i=s.useEditorStore(x=>x.card),d=s.useEditorStore(x=>x.card.dataSource);s.isExplorerCard(i);const{config:u}=I.useContext(s.SemaphorContext).tokenProps,m=(u==null?void 0:u.showAdvancedMode)!==!1,{setIsDevMode:h}=s.useEditorActions(),f=s.useEditorStore(x=>x.showAIDialog),g=s.useEditorStore(x=>x.frame),b=s.useManagementStore(x=>x.selectedVisual),p=(b==null?void 0:b.id)===(g==null?void 0:g.id),{setShowAIDialog:j}=s.useEditorActions();return e.jsxs("div",{className:s.cn("flex items-center justify-between px-6 py-3",f&&"justify-end",!m&&"justify-end"),children:[m&&t&&!f&&e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.SmallSwitch,{className:s.cn("",{}),checked:c,onCheckedChange:()=>h(!c),id:"advanced-mode"}),e.jsx("label",{htmlFor:"advanced-mode",className:"text-sm font-medium",children:"Advanced Mode"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Ds,{}),n&&!p&&e.jsx(ws,{variant:"default"}),p&&e.jsx(Un,{}),a&&s.isDevEnv]}),l&&e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(d==null?void 0:d.selectedEntities)||[],open:l,onOpenChange:o,dataSource:d||s.EMPTY_DATA_SOURCE,fallbackDataSource:s.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]})}function eo({activeView:t,onViewChange:a}){const n=s.useEditorStore(l=>l.card),{errorMessage:r}=s.useDashboardCardQuery(n);return e.jsx(s.Tabs,{value:t,onValueChange:l=>a(l),children:e.jsxs(s.TabsList,{className:"h-9 w-fit gap-1 bg-background p-0",children:[e.jsx(s.TabsTrigger,{value:"chart",className:"rounded-md transition data-[state=active]:bg-muted",children:"Chart"}),e.jsx(s.TabsTrigger,{value:"table",className:"rounded-md transition data-[state=active]:bg-muted",children:"Results"}),n.type!=="kpi"&&e.jsx(s.TabsTrigger,{value:"sql",className:s.cn("rounded-md transition data-[state=active]:bg-muted",r&&"text-destructive data-[state=active]:bg-destructive/10 data-[state=active]:text-destructive"),children:r?"Error":"Info"})]})})}const so=[{value:"10",label:"Top 10"},{value:"20",label:"Top 20"},{value:"50",label:"Top 50"},{value:"100",label:"Top 100"},{value:"200",label:"Top 200"},{value:"500",label:"Top 500"},{value:"1000",label:"Top 1000"}];function to(){var d,u;const t=s.useEditorStore(m=>m.card),{updateRowLimit:a}=s.useEditorActions(),[n,r]=I.useState(!1),[l,o]=I.useState(""),c=m=>{if(m==="custom"){r(!0);return}r(!1),a(t.id,parseInt(m))},i=m=>{const h=m.target.value;o(h),h&&!isNaN(parseInt(h))&&a(t.id,parseInt(h))};return e.jsx("div",{className:"flex items-center gap-2",children:n?e.jsx(s.Input,{type:"number",value:l,onChange:i,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(s.Select,{value:((u=(d=t.config)==null?void 0:d.rowLimit)==null?void 0:u.toString())||"100",onValueChange:c,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-24 border-none px-1 [&>svg]:hidden",children:e.jsx(s.SelectValue,{placeholder:"Select limit"})}),e.jsx(s.SelectContent,{children:so.map(m=>e.jsx(s.SelectItem,{value:m.value,children:m.label},m.value))})]})})}function ao({isOpen:t,onClose:a}){const n=ut(a,{enabled:t}),r=s.useEditorStore(m=>{var h;return((h=m.card.customCardPreferences)==null?void 0:h.url)||""}),l=s.useEditorStore(m=>m.card),o=s.useEditorStore(m=>{var h;return((h=m.card.customCardPreferences)==null?void 0:h.pluginChartType)||""}),c=s.useEditorStore(m=>{var h;return((h=m.card.customCardPreferences)==null?void 0:h.settings)||{}}),{data:i}=s.useDashboardCardQuery(l),{getCard:d}=s.useCustomVisual(r),u=I.useMemo(()=>!r||r.trim()===""?null:d("Chart Settings"),[d,r]);return e.jsx("div",{ref:n,className:s.cn("absolute right-0 top-0 z-40 h-full w-[350px] border-l bg-background shadow-lg transition-transform duration-300",t?"translate-x-0":"translate-x-full"),style:{willChange:"transform"},tabIndex:t?0:-1,"aria-hidden":!t,children:e.jsxs("div",{className:"flex h-full flex-col p-4 px-5 pr-4",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between",children:[e.jsx("h2",{className:"text-base font-semibold",children:"Chart Settings"}),e.jsx(s.IconButton,{"aria-label":"Hide Chart Settings",tooltip:"Hide",onClick:a,className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:e.jsx(s.X,{className:"size-3.5"})})]}),e.jsx("div",{className:"h-full min-h-0 flex-1",children:u&&e.jsx(I.Suspense,{fallback:e.jsx("div",{children:"Loading chart settings..."}),children:e.jsx(u,{chartData:(i==null?void 0:i.records)||[],chartType:o,settings:c})})})]})})}function no(){const{authToken:t,tokenProps:a}=s.useSemaphorContext(),{currentUser:n}=s.useCurrentUserInfo(),r=s.useMutation({mutationFn:async l=>{if(!(t!=null&&t.accessToken))throw new Error("No authentication token available");const c="https://semaphor.cloud/api/v1/feedback",i={...l,user:n,tokenContext:a},d=await s.postRequestRegular(c,t.accessToken,i,"POST");if(!d||!d.success)throw new Error((d==null?void 0:d.error)||"Failed to send feedback");return d},onSuccess:l=>{s.ue.success(`Feedback sent successfully! Issue: ${l.issueNumber}`,{duration:5e3})},onError:l=>{console.error("Feedback submission error:",l),s.ue.error("Failed to send feedback. Please try again later.",{duration:5e3})}});return{sendFeedback:r.mutate,sendFeedbackAsync:r.mutateAsync,isLoading:r.isPending,isSuccess:r.isSuccess,isError:r.isError,error:r.error,data:r.data,reset:r.reset}}function ro(t,a,n){return{category:t,userMessage:n,systemState:a,metadata:{url:window.location.href,userAgent:navigator.userAgent,timestamp:new Date().toISOString(),viewport:`${window.innerWidth}x${window.innerHeight}`}}}function lo({open:t,onOpenChange:a,feedbackData:n}){var p,j,x,v,k,L;const[r,l]=I.useState(""),[o,c]=I.useState(!1),{sendFeedback:i,isLoading:d,isSuccess:u,data:m,reset:h}=no(),f=()=>{const C={...n,userMessage:r.trim()||void 0};i(C)},g=()=>{l(""),c(!1),h(),a(!1)},b={category:n.category,error:{message:(p=n.systemState)==null?void 0:p.errorMessage,sql:(j=n.systemState)==null?void 0:j.generatedSql,errorSql:(x=n.systemState)==null?void 0:x.errorSql},cardConfig:(v=n.systemState)==null?void 0:v.cardConfig,dataSource:(k=n.systemState)==null?void 0:k.dataSource,filters:(L=n.systemState)==null?void 0:L.dashboardFilters,metadata:n.metadata};return e.jsx(s.Dialog,{open:t,onOpenChange:g,children:e.jsxs(s.DialogContent,{className:"max-w-2xl",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:u?"Feedback Sent Successfully":"Report Query Generation Issue"}),e.jsx(s.DialogDescription,{children:u?`Your feedback has been submitted with issue number: ${m==null?void 0:m.issueNumber}`:"Help us improve by reporting this query generation issue. Your feedback will be sent to our support team."})]}),!u&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"message",children:"Additional Information (Optional)"}),e.jsx(s.Textarea,{id:"message",placeholder:"Please describe what you were trying to do when this error occurred...",value:r,onChange:C=>l(C.target.value),className:"min-h-[100px] resize-none ring-inset focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-0",disabled:d})]}),e.jsxs(s.Collapsible,{open:o,onOpenChange:c,children:[e.jsx(s.CollapsibleTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"ghost",size:"sm",className:"flex w-full items-center justify-between p-2 hover:bg-muted",children:[e.jsx("span",{className:"text-sm font-medium",children:"View data to be sent"}),o?e.jsx(s.ChevronDown,{className:"h-4 w-4"}):e.jsx(s.ChevronRight,{className:"h-4 w-4"})]})}),e.jsx(s.CollapsibleContent,{children:e.jsx(s.ScrollArea,{className:"h-[300px] w-full rounded-md border bg-muted/50 p-4",children:e.jsx("div",{className:"text-xs",children:e.jsx(s.CodeHighlighter,{code:JSON.stringify(b,null,2),language:"json"})})})})]})]}),e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:g,disabled:d,children:"Cancel"}),e.jsx(s.Button,{onClick:f,disabled:d,className:"min-w-[100px]",children:d?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Sending..."]}):"Send Feedback"})]})]}),u&&e.jsxs("div",{className:"flex flex-col items-center space-y-4 py-6",children:[e.jsx(ua,{className:"h-12 w-12 text-green-600"}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-lg font-medium",children:"Thank you for your feedback!"}),e.jsxs("p",{className:"mt-2 text-sm text-muted-foreground",children:["Issue Number:"," ",e.jsx("span",{className:"font-mono font-medium",children:m==null?void 0:m.issueNumber})]}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Our support team will review your feedback and take appropriate action."})]}),e.jsx(s.Button,{onClick:g,className:"mt-4",children:"Close"})]})]})})}var Ht=(t=>(t.QUERY_GENERATION="query-generation",t))(Ht||{});function oo({activeView:t,onViewChange:a,showDebug:n,onDebugToggle:r,onAccept:l,onClear:o,onAdvancedToggle:c,onFiltersClick:i,filterCount:d,activeCard:u,columns:m,columnsLoading:h,columnsError:f}){var _;const g=s.useEditorStore(J=>J.card),b=s.useDashboardStore(J=>J.filterValues),p=(b==null?void 0:b.length)||0,{updateCardConfig:j,setCard:x,updateCardInFrame:v,setCardId:k}=s.useEditorActions(),{updateCardId:L}=s.useDashboardActions(),[C,S]=I.useState(null),y=s.useEditorStore(J=>J.showAIDialog),[D,N]=I.useState(!1),[B,w]=I.useState(!1),[F,T]=I.useState(null),{isConsoleMode:E}=s.useDashboardPreferences(),A=s.useEditorStore(J=>{var z;return((z=J.card.customCardPreferences)==null?void 0:z.url)&&J.card.type==="custom"}),{data:O,errorMessage:M,isLoading:R,isFetching:P,errorSql:K,pagination:$}=s.useDashboardCardQuery(u),te=(J,z)=>{const U={...u,paginationConfig:{page:J+1,pageSize:z}};x(U),v(U)};function X(){return e.jsx("div",{className:"border-b border-border bg-background p-4",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Active Card Config"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(g.config||{},null,2)})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Dashboard Filters"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(b||{},null,2)})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Card Data Source State"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(u.dataSource||{},null,2)})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"mb-2 text-sm font-medium",children:["Columns (",m.length,")"]}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:h?"Loading...":f?"Error loading columns":JSON.stringify(m.slice(0,5),null,2)})]})]})})}const q=J=>{if(!g.config)return;if(!J.length){j(g.id,{...g.config,sortByColumns:[]});return}const z=g.config,U=J.map(({id:Z,desc:le})=>{var Y,W;const V=(Y=z.metricColumns)==null?void 0:Y.find(re=>re.label===Z),se=(W=z.groupByColumns)==null?void 0:W.find(re=>re.label===Z),ne=V||se;return ne?{id:s.getFieldId("sortBy",ne),name:ne.name,dataType:ne.dataType,label:ne.label,qualifiedEntityName:ne.qualifiedEntityName,entityId:ne.entityId,entityName:ne.entityName,entityType:ne.entityType,role:"sortby",direction:le?"desc":"asc"}:null}).filter(Z=>Z!==null);j(g.id,{...z,sortByColumns:U})},H=I.useMemo(()=>{var J,z;return(z=(J=g.config)==null?void 0:J.sortByColumns)==null?void 0:z.map(U=>({id:U.label,desc:U.direction==="desc"}))},[(_=g.config)==null?void 0:_.sortByColumns]);return e.jsxs("div",{className:"relative flex w-0 grow flex-col",children:[e.jsx(Zl,{showDebug:n,onDebugToggle:r,onAccept:l,onClear:o,onAdvancedToggle:c,onFiltersClick:i,filterCount:d}),n&&X(),e.jsxs("div",{className:"group/visualization relative flex h-full max-w-full grow flex-col pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 px-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t==="chart"&&y&&e.jsx(At,{variant:"outline"}),e.jsx(eo,{activeView:t,onViewChange:a}),i&&e.jsx(Xl,{dashboardFilterCount:p,cardFilterCount:d,onClick:i,className:"h-8"}),e.jsx("div",{className:"ml-2",children:e.jsx(to,{})}),y&&e.jsx(rs,{})]}),e.jsx("div",{className:s.cn("flex grow items-center justify-end"),children:t==="chart"&&e.jsx(Mt,{})})]}),!D&&A&&e.jsx(s.IconButton,{"aria-label":"Open Chart Settings",tooltip:"Open Chart Settings",onClick:()=>N(!0),className:"absolute right-5 top-1/2 z-40 size-10 -translate-y-1/2 rounded-full border border-border bg-background shadow-lg hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",children:e.jsx(s.Settings2,{className:"size-4"})}),e.jsxs("div",{className:"mt-3 flex grow flex-col",children:[t==="chart"&&e.jsx("div",{className:"flex grow flex-col pb-6",children:e.jsx(Lt,{})}),t==="table"&&(O==null?void 0:O.records)&&e.jsx("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 p-6",children:e.jsx(s.TableVisual,{card:u,data:(O==null?void 0:O.records)||[],paginationMetadata:$,onPaginationChange:te,isLoading:R||P,onSortChange:q,sortState:H})}),t==="sql"&&e.jsx("div",{className:"px-6",children:e.jsxs("div",{className:"rounded-md bg-background",children:[e.jsxs("div",{className:"mb-2",children:[E&&e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Card ID:"}),e.jsx(s.EditableText,{value:g.id,onSave:J=>{const z=s.sanitizeCardId(J);if(!z){S("Card ID cannot be empty");return}const U=L(g.id,z);if(U.success){k(z);const Z={...g,id:z};x(Z),v(Z),S(null),s.ue.success("Card ID updated successfully")}else S(U.error||"Failed to update Card ID"),s.ue.error(U.error||"Failed to update Card ID")},isEditable:!0,placeholder:"Enter card ID",displayClassName:"font-mono text-xs text-muted-foreground hover:text-foreground",inputClassName:"font-mono text-xs"}),e.jsx(s.CopyButton,{text:g.id,className:"h-5 w-5"})]}),C&&e.jsx("p",{className:"text-xs text-destructive",children:C})]}),M||K?e.jsx(Ct,{error:M,errorSql:K,onSendFeedback:()=>{const J=ro(Ht.QUERY_GENERATION,{cardConfig:g.config,dataSource:u.dataSource,dashboardFilters:b,errorMessage:M,errorSql:K,generatedSql:O==null?void 0:O.sql});T(J),w(!0)}}):e.jsxs(e.Fragment,{children:[(O==null?void 0:O.sql)&&e.jsx("h3",{className:"mb-1 px-2 font-mono text-xs font-medium",children:"Generated SQL Query"}),e.jsx(St,{sql:O==null?void 0:O.sql,error:M,errorSql:K})]})]})})]}),e.jsx(ao,{isOpen:D,onClose:()=>N(!1)}),F&&e.jsx(lo,{open:B,onOpenChange:w,feedbackData:F})]})]})}function io({activeField:t}){const[a,n]=I.useState(!0);return I.useEffect(()=>{t&&n(!0)},[t]),t?e.jsxs("div",{className:`flex max-w-[300px] items-center gap-2 rounded-lg border border-blue-500 bg-background p-2 shadow-lg transition-all duration-200 ${a?"scale-100 opacity-100":"scale-95 opacity-0"}`,children:[e.jsx(s.GripVertical,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx(As,{dataType:t.dataType}),e.jsx("span",{className:"overflow-hidden text-ellipsis whitespace-nowrap text-sm dark:text-muted-foreground",children:t.label||t.name})]}):null}const co=()=>{const t=console.error;console.error=(...r)=>{r.length>0&&typeof r[0]=="string"&&r[0].includes("ResizeObserver loop completed with undelivered notifications")||t.apply(console,r)};const a=r=>{if(r.message&&(r.message.includes("ResizeObserver loop completed with undelivered notifications")||r.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),r.stopPropagation(),!1},n=r=>{var l;if((l=r.reason)!=null&&l.message&&(r.reason.message.includes("ResizeObserver loop completed with undelivered notifications")||r.reason.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),!1};return window.addEventListener("error",a,!0),window.addEventListener("unhandledrejection",n,!0),()=>{console.error=t,window.removeEventListener("error",a,!0),window.removeEventListener("unhandledrejection",n,!0)}};function uo(){var X,q;const[t,a]=I.useState("chart"),[n,r]=I.useState(!1),[l,o]=I.useState(!1),[c,i]=I.useState(!0),d=s.useEditorStore(H=>H.showAIDialog),u=s.useDashboardStore(H=>H.isVisualEditing),{setCardType:m}=s.useEditorActions(),h=s.useEditorStore(H=>H.card.type);I.useEffect(()=>co(),[]);const f=()=>{console.log("Accept clicked - would save/apply current configuration")},g=()=>{console.log("Clear clicked - would reset all configurations")},b=()=>{console.log("Advanced mode toggled")},p=()=>{o(!0)},j=H=>{m(H)},x=s.useEditorStore(H=>H.frame),v=s.useEditorStore(H=>H.card);s.useEditorStore(H=>H.activeTabCardId),s.useEditorStore(H=>H.actions.getAvailableFields);const{addCard:k,removeCard:L,updateCard:C,setActiveCard:S,updateFilters:y}=s.useEditorActions(),{columns:D=[],isLoading:N,error:B}=s.useColumns(),w=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),F=v,{getFieldsForContainer:T,setFieldsForContainer:E}=Is(F),{activeField:A,handleDragStart:O,handleDragEnd:M}=Ql({activeCardId:x.activeCardId,sourceFields:D,getFieldsForContainer:T,setFieldsForContainer:E}),R=(H,_)=>{_&&y(H,_)},P=H=>{var _;C(H,{config:{...(_=x.cards.find(J=>J.id===H))==null?void 0:_.config,filters:void 0}})},K=D,$=H=>{if(!H)return 0;let _=H.conditions.length;return H.groups.forEach(J=>{_+=$(J)}),_},te=$(((X=F==null?void 0:F.config)==null?void 0:X.filters)||null);return e.jsxs(s.DndContext,{sensors:w,collisionDetection:s.closestCenter,onDragStart:O,onDragEnd:M,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(xl,{isVisible:c,onToggleVisibility:()=>i(!c)}),e.jsxs("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:[!d&&e.jsx(Ml,{selectedChart:h,onChartChange:j,groupByFields:T("groupBy"),pivotByFields:T("pivotBy"),metricsFields:T("metrics"),sortByFields:T("sortBy")}),e.jsx(oo,{selectedChart:h,activeView:t,onViewChange:a,showDebug:n,onDebugToggle:()=>r(!n),onAccept:f,onClear:g,onAdvancedToggle:b,onFiltersClick:p,filterCount:te,activeCard:F,dataSourceState:v.dataSource||s.EMPTY_DATA_SOURCE,columns:D,columnsLoading:N,columnsError:B,getFieldsForContainer:T,cards:x.cards,activeCardId:x.activeCardId,addCard:k,setActiveCard:S})]}),!c&&u&&e.jsx("div",{className:"fixed left-6 top-[105px] z-50",children:e.jsx(s.Button,{size:"sm",variant:"outline",className:"h-10 w-10 rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted",onClick:()=>i(!0),title:"Show Data Source Panel",children:e.jsx(s.Database,{className:"h-4 w-4"})})})]}),F&&e.jsx(Jl,{cardId:F.id,filters:((q=F.config)==null?void 0:q.filters)||null,onFiltersChange:R,onClearFilters:P,availableFields:K,isOpen:l,onOpenChange:o}),e.jsx(s.DragOverlay,{dropAnimation:null,children:e.jsx(io,{activeField:A||null})})]})}function mo({authToken:t,onSave:a,onClose:n}){const r=I.useRef(null),l=s.useEditorStore(v=>v.showAIDialog),o=s.useEditorStore(v=>v.isDevMode),{setAuthToken:c}=s.useDashboardActions(),{setShowAIDialog:i,setOnSave:d,setOnClose:u}=s.useEditorActions(),{handleDragOver:m,handleDragEnd:h,handleDragStart:f,handleDragCancel:g,sensors:b}=On();I.useEffect(()=>{a&&d(a),n&&u(n)},[a,d,n,u]),I.useEffect(()=>{t&&t.accessToken&&c(t)},[t,c]),I.useEffect(()=>{var v,k;l?((v=r.current)==null||v.resize(40),i(!0)):(i(!1),(k=r.current)==null||k.resize(0))},[l,i]);function p(v){v<1?i(!1):l||i(!0)}function j(){return e.jsxs(e.Fragment,{children:[e.jsx(Nt,{type:"main"}),e.jsxs(s.ResizablePanelGroup,{"data-content":"editor-main",className:"grow",direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(el,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:p,defaultSize:0,children:e.jsx(Hs,{})})]})]})}function x(){return e.jsxs(s.ResizablePanelGroup,{"data-content":"explorer",className:"flex grow",direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(uo,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:p,defaultSize:0,children:e.jsx(Hs,{})})]})}return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:o?e.jsx(s.DndContext,{sensors:b,onDragStart:f,onDragEnd:h,onDragOver:m,onDragCancel:g,children:e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:j()})}):x()})}function ho(){s.useDashboardStore(c=>c.selectedCardId);const t=s.useDashboardStore(c=>c.selectedSheetId),{setIsVisualEditing:a}=s.useDashboardStore(c=>c.actions),n=s.useDashboardStore(c=>c.isVisualEditing),r=s.useDashboardStore(c=>c.actions.updateFrame);function l(c){t&&(r(t,c),a(!1))}function o(){a(!1)}return e.jsx("div",{role:"editor-container",className:s.cn("flex-1 grow basis-0 overflow-auto",{"max-h-0 overflow-hidden":!n}),children:e.jsx(mo,{onSave:l,onClose:o})})}function xo({column:t}){return e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger$1,{className:"shrink-0",asChild:!0,children:s.isTextDataType(t.data_type)?e.jsx(s.TextIcon,{className:"size-3 text-muted-foreground"}):s.isNumberDataType(t.data_type)?e.jsx(Ne,{className:"size-3 text-muted-foreground"}):s.isDateDataType(t.data_type)?e.jsx(s.Calendar,{className:"size-3 text-muted-foreground"}):s.isBooleanDataType(t.data_type)?e.jsx(Me,{className:"size-3 text-muted-foreground"}):t.data_type.startsWith("json")?e.jsx(da,{className:"size-3 text-muted-foreground"}):e.jsx(s.QuestionMarkIcon,{className:"size-3 text-muted-foreground"})}),e.jsx(s.TooltipContent,{children:e.jsx("p",{className:"text-xs",children:t.data_type})})]})}function po(){const t=s.useEditorStore(o=>o.selectedDatabaseName),a=s.useEditorStore(o=>o.selectedTableName),n=s.useDashboardStore(o=>o.dashboard.filters)||[],{columns:r}=s.useEditorAside(),{assignFilter:l}=ks();return e.jsx(s.ScrollArea,{className:"flex-1 basis-0 flex-col px-3",children:r==null?void 0:r.map(o=>{const c=n==null?void 0:n.find(i=>i.column===s.fmt(o.column_name)&&i.table===a&&i.database===t);return e.jsx("div",{onClick:()=>l(o),className:s.cn("group flex cursor-pointer items-center justify-between border border-dashed border-background px-3 py-[6px] text-sm transition-colors hover:bg-muted/50",{"bg-muted":c}),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xo,{column:o}),e.jsx("span",{children:o.column_name})]})},o.column_name)})})}function fo({dataType:t}){const a=s.getDataType(t);return a==="string"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(ge,{className:"h-3 w-3"})}):a==="number"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(Ne,{className:"h-3 w-3"})}):a==="date"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):a==="boolean"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Me,{className:"h-3 w-3"})}):a==="json"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Oe,{className:"h-3 w-3"})}):a==="geo"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(_e,{className:"h-3 w-3"})}):a==="calculated"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(qe,{className:"h-3 w-3"})}):e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(ge,{className:"h-3 w-3"})})}function go(){const[t,a]=I.useState(""),[n,r]=I.useState("all"),l=s.useDashboardStore(x=>x.dashboard.filters)||[],{assignFilter:o}=ks(),c=s.useEditorStore(x=>x.card.dataSource),{columns:i=[],isLoading:d,error:u}=s.useColumns(),m=i.filter(x=>x.name.toLowerCase().includes(t.toLowerCase())||x.dataType.toLowerCase().includes(t.toLowerCase())||x.label&&x.label.toLowerCase().includes(t.toLowerCase())),h=x=>{const v=s.getDataType(x.dataType);return v==="number"?"metrics":(["date","string","boolean"].includes(v),"dimensions")},f=n==="all"?m:m.filter(x=>h(x)===n),g=m.filter(x=>h(x)==="dimensions").length,b=m.filter(x=>h(x)==="metrics").length,p=x=>{const v={column_name:x.name,data_type:x.dataType,label:x.label,description:x.description};o(v,"dashboard",x)};if(d)return e.jsx("div",{className:"flex h-full grow flex-col items-center justify-center px-3",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading fields"})});if(u)return e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-3",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-red-300"}),e.jsx("p",{className:"mb-2 text-sm text-red-500",children:"Error loading fields"}),e.jsx("p",{className:"px-4 text-center text-xs text-red-400",children:u.message||"Failed to load column data"})]});if(!c||!c.selectedEntities||c.selectedEntities.length===0)return e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-8 text-center",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-gray-300"}),e.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),e.jsx("p",{className:"px-4 text-xs text-gray-400",children:"Select a table, view, or dataset from the data source panel to see available fields"})]});if(i.length===0)return e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-8 text-center",children:[e.jsx("p",{className:"text-sm text-gray-500",children:"No fields found for selected data source"}),e.jsx("p",{className:"mt-1 text-xs text-gray-400",children:"Try selecting different data sources"})]});const j=m.length>0;return e.jsxs("div",{className:"flex h-full grow flex-col pb-4",children:[e.jsxs("div",{className:"flex-shrink-0 space-y-3 px-3 pt-3",children:[i.length>0&&e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 transform text-muted-foreground"}),e.jsx(s.Input$1,{className:"pl-10",type:"text",placeholder:"Search fields...",value:t,onChange:x=>a(x.target.value)})]}),j&&e.jsx(s.Tabs,{defaultValue:"all",value:n,onValueChange:x=>r(x),children:e.jsxs(s.TabsList,{className:"grid h-9 w-full grid-cols-3",children:[e.jsxs(s.TabsTrigger,{value:"all",className:"text-xs",children:["All",e.jsx("span",{className:"ml-2 text-xs font-semibold",children:m.length})]}),e.jsxs(s.TabsTrigger,{value:"dimensions",className:"text-xs",children:[e.jsx(s.Layers,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:g})]}),e.jsxs(s.TabsTrigger,{value:"metrics",className:"text-xs",children:[e.jsx(s.ChartColumn,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:b})]})]})})]}),e.jsxs(s.ScrollArea,{className:"flex-1 basis-0 flex-col px-3 pt-3",children:[f.length===0&&t&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:['No fields found matching "',t,'"']}),f.length===0&&!t&&n!=="all"&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:["No ",n," fields found"]}),f.map(x=>{const v=l==null?void 0:l.some(k=>{var L;return k.title===x.name||((L=k.column)==null?void 0:L.includes(x.name))});return e.jsx("div",{onClick:()=>p(x),className:s.cn("group flex cursor-pointer items-center justify-between border border-dashed border-background px-3 py-[6px] text-sm transition-colors hover:bg-muted/50",{"bg-muted":v}),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(fo,{dataType:x.dataType}),e.jsx("span",{children:x.label||x.name})]})},x.id)})]})]})}function jo(){var r;const t=s.useDashboardStore(l=>l.actions.setShowFilters),a=s.useCurrentActiveCard(),n=a&&((r=a.dataSource)==null?void 0:r.selectedEntities)&&a.dataSource.selectedEntities.length>0;return e.jsxs("section",{className:"relative flex min-w-[320px] grow flex-col border-l px-1",children:[e.jsxs("div",{className:"mt-4 flex items-center justify-between gap-2 px-3",children:[e.jsx(s.Label,{className:"px-2 text-lg",children:"Filters"}),e.jsx(s.Button,{onClick:()=>t(!1),className:"h-7 w-7 p-0",variant:"ghost",children:e.jsx(s.Cross2Icon,{})})]}),e.jsx("div",{className:"flex grow",children:n?e.jsx(go,{}):e.jsx(Nt,{type:"filter",ColumnsComponent:()=>e.jsx(po,{})})})]})}function bo(){const t=s.useDashboardStore(r=>r.dashboard.filters),a=s.useDashboardStore(r=>r.theme),n=t==null?void 0:t.filter(r=>r.hide);return n!=null&&n.length?e.jsx("div",{className:s.cn("mb-1 flex items-center gap-2 border-y px-0.5 pb-0.5",{"bg-[repeating-linear-gradient(45deg,_#ffffff_0_3px,_#f3f3f3_3px_6px)]":a==="light","bg-[repeating-linear-gradient(45deg,_#18171d_0_3px,_#272729_3px_6px)]":a==="dark"}),children:n==null?void 0:n.map(r=>e.jsxs("div",{className:"flex min-w-[250px] max-w-fit flex-col gap-1 p-2",children:[e.jsx(s.FilterHeader,{filter:r}),e.jsx(s.FilterComponent,{filter:r})]},r.id))}):null}function yo(){const t=s.useDashboardStore(r=>r.showFilters),a=s.useDashboardStore(r=>r.isVisualEditing),n=s.useDashboardStore(r=>r.isDashboardEditing);return e.jsxs("div",{role:"dashboard-plus-main",className:s.cn("",{"max-h-0 overflow-hidden":a,"flex grow overflow-auto":!a}),children:[e.jsxs("section",{className:"flex grow flex-col",children:[n&&e.jsx(bo,{}),e.jsx(s.DashboardTabs,{})]}),t&&e.jsx("div",{role:"filter-aside-container",className:"flex",children:e.jsx(jo,{})})]})}function vo(){const t=s.useDashboardStore(l=>l.dashboard),a=s.useDashboardStore(l=>l.actions.setDashboard),n=s.useDashboardStore(l=>l.showDashboardJSON),r=s.useDashboardStore(l=>l.actions.setShowDashboardJSON);return e.jsxs("div",{className:s.cn("relative p-2",{hidden:!n}),children:[e.jsxs(s.Button,{variant:"secondary",size:"sm",className:"absolute right-2 top-2 z-10 h-8",onClick:()=>r(!1),children:[e.jsx(s.X,{className:"mr-2 h-4 w-4"}),"Close"]}),e.jsx(s.de,{onChange:l=>{if(l)try{JSON.parse(l),a(JSON.parse(l))}catch{}},defaultLanguage:"json",className:"h-[550px] overflow-y-auto",value:JSON.stringify(t,null,2),options:{minimap:{enabled:!1},glyphMargin:!1,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,renderLineHighlight:"none"}})]})}function No({showControls:t=!1,showFooter:a=!0,...n}){if(typeof window>"u")return null;const{preferences:r}=n;return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:e.jsxs(s.SemaphorContextProvider,{dashboardProps:n,children:[e.jsx(s.$e,{}),e.jsx(s.UXProvider,{children:e.jsxs(s.DashboardPreferencesProvider,{preferences:r,children:[e.jsx(vo,{}),e.jsxs("main",{className:"relative flex h-full w-full flex-col",children:[t&&e.jsx(En,{}),e.jsxs(s.Container,{...n,type:"dashboard",children:[e.jsx(ho,{}),e.jsx(yo,{})]})]})]})})]})})}exports.DashboardPlus=No;exports.ResourceManagementPanel=yt;exports.ScheduleDashboard=rt;exports.SelectComponent=Re;exports.cleanCard=nt;exports.getDashbaordStateWithoutData=es;
|