PageSourceSearch

https://xynergy.ai/_next/static/chunks/1582.a7611d4be5e70e74.js

js xynergy.ai collected 2026-10-05 16:02:03 UTC 173,682 bytes, 1 lines download raw bytes

1"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[1582],{21:(e,t,r)=>{r.d(t,{s:()=>p});var a=r(24571),n=r(76458),i=r(15418);let l=i.k5(["expense-ratio","debt-ratio","emergency-fund-coverage","financial-freedom","savings-rate","investment-ratio","debt-to-income","net-worth-growth","housing-expense","loan-to-value","current-ratio","investment-diversification","excess-cash-ratio"]),o=i.Ik({id:i.ai().int().positive(),type:l,title:i.Yj().min(1,"指標標題不能為空"),value:i.ai(),target:i.ai()}),s=i.Ik({financialIndicators:i.YO(o),availableIndicators:i.YO(o),lastUpdated:i.bz()});i.Ik({userId:i.Yj().min(1,"userId 不能為空"),indicatorType:l,value:i.ai(),calculatedAt:i.bz(),metadata:i.g1(i.Yj(),i.L5()).optional()});let d=i.Ik({alerts:i.zM().default(!0),tasks:i.zM().default(!0)}),c=i.Ik({enabled:i.zM().default(!1),categories:d.default({alerts:!0,tasks:!0}),volume:i.ai().min(0).max(1).default(.7)}),u=i.YO(i.ai().int().min(0)).transform(e=>Array.from(new Set(e)).sort((e,t)=>t-e)).default([14,7,3]),m=i.Ik({userId:i.Yj().min(1,"userId 不能為空"),lastSelectedIncomeAccountId:i.Yj().optional(),lastSelectedExpenseAccountId:i.Yj().optional(),lastIncomeAmount:i.ai().min(0).optional(),lastExpenseAmount:i.ai().min(0).optional(),preferredIncomeMonth:i.Yj().regex(/^\d{4}-\d{2}$/,"月份格式必須為 YYYY-MM").optional(),preferredExpenseMonth:i.Yj().regex(/^\d{4}-\d{2}$/,"月份格式必須為 YYYY-MM").optional(),creditCardPaymentReminderDisabled:i.zM().optional(),premiumReminderDays:u.optional(),soundSettings:c.optional(),financialIndicators:s.optional(),bookkeepingMode:i.k5(["simple","detailed"]).default("detailed").optional(),createdAt:i.bz().optional(),updatedAt:i.bz().optional()});var f=r(8958);let h="user_preferences",p={async getPreferences(e){if(!n.db)throw Error("Firestore 尚未初始化");if(!e)throw Error("用戶 ID 未提供");let t=(0,a.doc)(n.db,h,e),r=await (0,a.getDoc)(t);return r.exists()?{id:r.id,...r.data()}:null},async setPreferences(e,t){if(!n.db)throw Error("Firestore 尚未初始化");if(!e)throw Error("用戶 ID 未提供");let r=(0,a.doc)(n.db,h,e),i=await (0,a.getDoc)(r),l=a.Timestamp.now(),o={userId:e,...t,updatedAt:l};i.exists()||(o.createdAt=l);let s=Object.fromEntries(Object.entries(m.parse(o)).filter(([e,t])=>void 0!==t));await (0,a.setDoc)(r,s,{merge:!0})},async updatePreference(e,t,r){await this.setPreferences(e,{[t]:r})},async getSoundSettings(e){if(!n.db)throw Error("Firestore 尚未初始化");if(!e)throw Error("用戶 ID 未提供");try{let t=await this.getPreferences(e);if(t?.soundSettings)return{enabled:t.soundSettings.enabled??f.wK.enabled,categories:{alerts:t.soundSettings.categories?.alerts??f.wK.categories.alerts,tasks:t.soundSettings.categories?.tasks??f.wK.categories.tasks},volume:t.soundSettings.volume??f.wK.volume};return{...f.wK}}catch(e){return console.warn("[userPreferencesOperations] 取得音效設定失敗:",e),{...f.wK}}},async setSoundSettings(e,t){if(!n.db)throw Error("Firestore 尚未初始化");if(!e)throw Error("用戶 ID 未提供");
1let r=await this.getSoundSettings(e),a={enabled:t.enabled??r.enabled,categories:{alerts:t.categories?.alerts??r.categories.alerts,tasks:t.categories?.tasks??r.categories.tasks},volume:t.volume??r.volume};await this.setPreferences(e,{soundSettings:a})},async setSoundEnabled(e,t){await this.setSoundSettings(e,{enabled:t})},async setSoundVolume(e,t){let r=Math.max(0,Math.min(1,t));await this.setSoundSettings(e,{volume:r})},async setSoundCategoryEnabled(e,t,r){let a=await this.getSoundSettings(e);await this.setSoundSettings(e,{categories:{...a.categories,[t]:r}})}}},2962:(e,t,r)=>{r.d(t,{A0:()=>o,BF:()=>s,Gg:()=>d,Hj:()=>c,XI:()=>l,nA:()=>m,nd:()=>u});var a=r(85047),n=r(31615),i=r(34961);let l=n.forwardRef(({className:e,...t},r)=>(0,a.jsx)("div",{className:"relative w-full overflow-auto",children:(0,a.jsx)("table",{ref:r,className:(0,i.cn)("w-full caption-bottom text-sm",e),...t})}));l.displayName="Table";let o=n.forwardRef(({className:e,...t},r)=>(0,a.jsx)("thead",{ref:r,className:(0,i.cn)("[&_tr]:border-b",e),...t}));o.displayName="TableHeader";let s=n.forwardRef(({className:e,...t},r)=>(0,a.jsx)("tbody",{ref:r,className:(0,i.cn)("[&_tr:last-child]:border-0",e),...t}));s.displayName="TableBody";let d=n.forwardRef(({className:e,...t},r)=>(0,a.jsx)("tfoot",{ref:r,className:(0,i.cn)("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",e),...t}));d.displayName="TableFooter";let c=n.forwardRef(({className:e,...t},r)=>(0,a.jsx)("tr",{ref:r,className:(0,i.cn)("border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted",e),...t}));c.displayName="TableRow";let u=n.forwardRef(({className:e,...t},r)=>(0,a.jsx)("th",{ref:r,className:(0,i.cn)("h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0",e),...t}));u.displayName="TableHead";let m=n.forwardRef(({className:e,...t},r)=>(0,a.jsx)("td",{ref:r,className:(0,i.cn)("p-4 align-middle [&:has([role=checkbox])]:pr-0",e),...t}));m.displayName="TableCell",n.forwardRef(({className:e,...t},r)=>(0,a.jsx)("caption",{ref:r,className:(0,i.cn)("mt-4 text-sm text-muted-foreground",e),...t})).displayName="TableCaption"},3303:(e,t,r)=>{r.d(t,{EZ:()=>k,Gy:()=>C,Ru:()=>N,ec:()=>S,w0:()=>A});var a=r(94430),n=r(40975),i=r(99307),l=r(75020),o=r(92737),s=r(17938),d=r(71143),c=r(2622),u=r(75123),m=r(78118),f=r(39337),h=r(57481),p=r(90612),g=r(48043),b=r(29778),x=r(77606),y=r(76089),v=r(73370),w=r(41860),j=r(19726);let S=[{id:"dashboard",label:"儀表板",title:"儀表板",desc:"一眼掌握淨值、現金流與財務指標達成狀況",kind:"table",icon:a.A},{id:"accounts",label:"帳戶",title:"帳戶",desc:"管理你的收入、支出、投資與儲蓄帳戶",kind:"table",icon:n.A},{id:"documents",label:"文件",title:"文件",desc:"集中管理保單、帳戶餘額截圖與稅務文件;檔案僅本人可上傳,顧問需經您授權後方可檢視",kind:"table",icon:i.A},{id:"income",label:"收入",title:"收入",desc:"追蹤各項收入來源、金額與週期",kind:"table",icon:l.A},{id:"expense",label:"支出",title:"支出",desc:"掌握每月各類支出結構與變化",kind:"table",icon:o.A},{id:"assets",label:"資產",title:"資產",desc:"盤點不動產、現金、投資等各類資產",kind:"table",icon:s.A},{id:"liabilities",label:"負債",title:"負債",desc:"追蹤貸款、卡債與各項負債",kind:"table",icon:d.A},{id:"investments",label:"投資",title:"投資",desc:"管理投資持倉、成本與報酬",kind:"table",icon:c.A},{id:"insurance",label:"保險",title:"保險",desc:"檢視保單保障、保費與缺口",kind:"table",icon:u.A},{id:"retirement",label:"退休",title:"退休",desc:"規劃退休金與被動收入目標",kind:"function",icon:m.A},{id:"tax",label:"稅務",title:"稅務",desc:"整理所得、扣除額與申報狀態",kind:"table",icon:f.A},{id:"estate",label:"傳承",title:"傳承",desc:"規劃遺囑、監護與傳承文件",kind:"function",icon:h.A},{id:"trust",label:"信託",title:"信託",desc:"管理信託安排與受益人",kind:"function",icon:p.A},{id:"advisor",label:"顧問",title:"顧問",desc:"尋找、預約與管理你的理財顧問",kind:"table",icon:g.A},{id:"tasks",label:"任務",title:"任務中心",desc:"完成任務獲得經驗值,提升等級解鎖更多功能",kind:"function",icon:b.A},{id:"settings",label:"設定",title:"設定",desc:"管理個人資料、通知、安全與帳號設定",kind:"function",showInTabs:!1,icon:x.A}
1,{id:"learn",label:"學習",title:"學習",desc:"理財知識文章與課程",kind:"function",showInTabs:!1,icon:y.A},{id:"tools",label:"工具",title:"工具",desc:"理財試算與規劃工具",kind:"function",showInTabs:!1,icon:v.A},{id:"help",label:"說明",title:"說明中心",desc:"操作指南、常見問題與開發者文件",kind:"function",showInTabs:!1,icon:w.A},{id:"admin",label:"管理",title:"管理後台",desc:"系統設定與內容管理(僅管理員)",kind:"function",showInTabs:!1,icon:j.A}],N="dashboard",C=S.filter(e=>!1!==e.showInTabs);function k(e){return S.find(t=>t.id===e)}function A(e){return S.some(t=>t.id===e&&!1===t.showInTabs)}},3379:(e,t,r)=>{r.d(t,{R7:()=>m,jR:()=>u,gU:()=>d});var a=r(30274),n=r(24571),i=r(76458),l=r(18654);async function o(e,t=6){let r="ABCDEFGHJKLMNPQRSTUVWXYZ23456789",a="",i=!0;for(;i;){a=Array.from({length:t},()=>r.charAt(Math.floor(Math.random()*r.length))).join("");let l=(0,n.P)((0,n.rJ)(e,"users"),(0,n._M)("referralCode","==",a));i=!(await (0,n.GG)(l)).empty}return a}let s=new a.GoogleAuthProvider;s.addScope("email"),s.addScope("profile"),s.setCustomParameters({prompt:"select_account"});let d=async()=>{if(!i.auth)throw Error("Firebase Auth 尚未初始化");try{let e=await (0,a.signInWithPopup)(i.auth,s);return await c(e.user),e}catch(t){let e=t?.code??"";if("auth/multi-factor-auth-required"===e)throw t;if("auth/popup-closed-by-user"===e)throw(0,l.MD)("Google 登入:使用者關閉彈窗",{code:e}),Error("登入視窗被關閉,請重試");if("auth/popup-blocked"===e)throw(0,l.MD)("Google 登入:彈窗被瀏覽器阻擋",{code:e}),Error("彈出視窗被瀏覽器阻擋,請允許彈出視窗後重試");if((0,l.vV)("Google 登入失敗:",t),"auth/network-request-failed"===e)throw Error("網路連線失敗,請檢查網路連線後重試");throw Error(`Google 登入失敗: ${t.message}`)}},c=async e=>{if(!i.db)return void(0,l.vV)("Firestore 尚未初始化");try{await e.getIdToken(!0),(0,l.fH)("開始同步使用者資料到 Firestore",{uid:e.uid});let t=(0,n.doc)(i.db,i.USERS,e.uid),r=await (0,n.getDoc)(t),a="string"==typeof e.displayName&&e.displayName.trim()?e.displayName.trim().slice(0,80):"",s={uid:e.uid,email:e.email,displayName:e.displayName,photoURL:e.photoURL,emailVerified:e.emailVerified,providerData:e.providerData.map(e=>({providerId:e.providerId,uid:e.uid,displayName:e.displayName,email:e.email,photoURL:e.photoURL})),lastSignInTime:e.metadata.lastSignInTime,creationTime:e.metadata.creationTime,updatedAt:(0,n.serverTimestamp)()};if(r.exists()){let i=r.data(),o="string"==typeof i?.name?i.name.trim():"",d={...s};!o&&a&&(d.name=a),await (0,n.setDoc)(t,d,{merge:!0}),(0,l.fH)("Google 使用者資料已更新",{uid:e.uid})}else{let r=await o(i.db,6);await (0,n.setDoc)(t,{...s,name:a,createdAt:(0,n.serverTimestamp)(),isActive:!0,profile:{firstName:e.displayName?.split(" ")[0]||"",lastName:e.displayName?.split(" ").slice(1).join(" ")||"",phone:"",address:"",city:"",country:"TW",timezone:Intl.DateTimeFormat().resolvedOptions().timeZone},preferences:{language:"zh-TW",currency:"TWD",notifications:{email:!0,push:!0,sms:!1}},referralCode:r}),(0,l.fH)("新 Google 使用者資料已建立",{uid:e.uid})}}catch(e){(0,l.vV)("同步使用者資料到 Firestore 失敗:",e.message)}},u=e=>e.providerData.some(e=>"google.com"===e.providerId),m=e=>{let t=e.providerData.find(e=>"google.com"===e.providerId);return t?{displayName:t.displayName,email:t.email,photoURL:t.photoURL,uid:t.uid}:null}},4153:(e,t,r)=>{let a;r.d(t,{Bm:()=>i,Wm:()=>l,_K:()=>n});let n={firebase:{apiKey:"AIzaSyB_r1_v5qmFmrnzJkpTZL3ryRWtSfDHD3E",authDomain:(a="finance-app-263bf",`${a}.firebaseapp.com`),projectId:"finance-app-263bf",storageBucket:"finance-app-263bf.firebasestorage.app",messagingSenderId:"307877483016",appId:"1:307877483016:web:9287c046d1c533e254f7bd",measurementId:"G-S5B380JDF7"},app:{url:"https://xynergy.ai",name:"鑫世紀理財",description:"專業的個人財務管理平台"},api:{baseUrl:r(32407).env.NEXT_PUBLIC_API_URL||"/api"},analytics:{googleAnalyticsId:"G-S5B380JDF7"},nodeEnv:"production",isDevelopment:!1,isProduction:!0}
1,i={paymentDisabled:!1,minCustomAmount:200,presetAmounts:[200,600,800,1200],costBreakdown:{lastUpdated:"2026-05-30",updateCadence:"每月更新",items:[{id:"gcp",label:"GCP",description:"Firebase、App Hosting、Cloud Functions、Firestore",defaultBillingPeriod:"monthly"},{id:"cursor",label:"Cursor",description:"IDE 訂閱",defaultBillingPeriod:"monthly"},{id:"claude-code",label:"Claude Code",description:"AI 輔助開發",defaultBillingPeriod:"monthly"},{id:"gemini",label:"Gemini",description:"AI API 用量",defaultBillingPeriod:"monthly"},{id:"developer",label:"開發者",description:"人力成本分攤",defaultBillingPeriod:"monthly"},{id:"domain",label:"域名",description:"xynergy.ai 等",defaultBillingPeriod:"yearly"},{id:"payment",label:"金流",description:"ECPay 手續費(隨贊助收入變動)",defaultBillingPeriod:"monthly"}]}},l={globalEnabled:!1,aiAssistantV2:{enabled:!1,label:"AI 助理 2.0"},advancedReports:{enabled:!1,label:"進階報表 Beta"}}},6386:(e,t,r)=>{r.d(t,{Xi:()=>d,av:()=>c,j7:()=>s,tU:()=>o});var a=r(85047),n=r(31615),i=r(27997),l=r(34961);let o=i.bL,s=n.forwardRef(({className:e,...t},r)=>{let o=n.useRef(null),{indicator:s,mounted:d}=function(e){let[t,r]=n.useState({left:0,width:0,top:0,height:0}),[a,i]=n.useState(!1),l=n.useCallback(()=>{let t=e.current;if(!t)return;let a=t.querySelector("[data-state=active]");a&&r({left:a.offsetLeft,width:a.offsetWidth,top:a.offsetTop,height:a.offsetHeight}),i(!0)},[e]);return n.useLayoutEffect(()=>{l();let t=e.current;if(!t)return;let r=new MutationObserver(l);r.observe(t,{subtree:!0,attributes:!0,attributeFilter:["data-state"]});let a=new ResizeObserver(l);return a.observe(t),()=>{r.disconnect(),a.disconnect()}},[e,l]),{indicator:t,mounted:a}}(o);return n.useEffect(()=>{let e=o.current;if(!e)return;let t=!1,r=!1,a=0,n=0,i=()=>e.scrollWidth>e.clientWidth+1,l=()=>{e.style.cursor=i()?"grab":""},s=i=>{if(!t)return;let l=i.clientX-a;!r&&Math.abs(l)>5&&(r=!0,e.style.cursor="grabbing",e.style.userSelect="none"),r&&(e.scrollLeft=n-l,i.preventDefault())},d=()=>{if(window.removeEventListener("pointermove",s),window.removeEventListener("pointerup",d),r){let t=e=>{e.stopPropagation(),e.preventDefault()};e.addEventListener("click",t,{capture:!0,once:!0}),window.setTimeout(()=>e.removeEventListener("click",t,!0),0)}t=!1,r=!1,e.style.userSelect="",l()},c=l=>{0===l.button&&i()&&(t=!0,r=!1,a=l.clientX,n=e.scrollLeft,window.addEventListener("pointermove",s),window.addEventListener("pointerup",d))},u=t=>{i()&&0!==t.deltaY&&(e.scrollLeft+=t.deltaY,t.preventDefault())};l();let m=new ResizeObserver(l);return m.observe(e),e.addEventListener("pointerdown",c),e.addEventListener("wheel",u,{passive:!1}),()=>{m.disconnect(),e.removeEventListener("pointerdown",c),e.removeEventListener("wheel",u),window.removeEventListener("pointermove",s),window.removeEventListener("pointerup",d)}},[o]),(0,a.jsxs)(i.B8,{ref:e=>{o.current=e,"function"==typeof r?r(e):r&&(r.current=e)},className:(0,l.cn)("relative inline-flex h-10 items-center justify-start rounded-md bg-transparent p-1 text-muted-foreground w-full overflow-x-auto scrollbar-hide",e),...t,children:[(0,a.jsx)("span",{"aria-hidden":!0,className:(0,l.cn)("absolute rounded-md bg-muted shadow-sm pointer-events-none",d&&"opacity-100 transition-[left,width,top,height] ease-in-out",!d&&"opacity-0"),style:{left:s.left,width:s.width,top:s.top,height:s.height,transitionDuration:d?"500ms":void 0}}),t.children]})});s.displayName=i.B8.displayName;let d=n.forwardRef(({className:e,...t},r)=>(0,a.jsx)(i.l9,{ref:r,className:(0,l.cn)("relative z-[1] inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=inactive]:hover:text-foreground/80 data-[state=active]:text-foreground","data-[state=inactive]:hover:bg-muted/30 data-[state=inactive]:hover:rounded-md",e),...t}));d.displayName=i.l9.displayName;let c=n.forwardRef(({className:e,...t},r)=>(0,a.jsx)(i.UC,{ref:r,className:(0,l.cn)("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",e),...t}));c.displayName=i.UC.displayName},13139:(e,t,r)=>{r.d(t,{CG:()=>c,Fm:()=>p,Qs:()=>b,cj:()=>d,h:()=>h,qp:()=>g});var a=r(85047),n=r(31615),i=r(49083),l=r(63610),o=r(42165),s=r(34961);let d=i.bL,c=i.l9;i.bm;let u=i.ZL,m=n.forwardRef(({className:e,...t},r)=>(0,a.jsx)(i.hJ,{className:(0,s.cn)("fixed inset-0 z-50 bg-black/80  data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t,ref:r}));m.displayName=i.hJ.displayName;let f=(0,l.F)("fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:duration-500",{variants:{side:{top:"inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",bottom:"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",left:"inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",right:"inset-y-0 right-0 h-full w-3/4  border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm"}},defaultVariants:{side:"right"}}),h=n.forwardRef(({side:e="right",className:t,children:r,...n},l)=>(0,a.jsxs)(u,{children:[(0,a.jsx)(m,{}),(0,a.jsxs)(i.UC,{ref:l,className:(0,s.cn)(f({side:e}),t),...n,children:[r,(0,a.jsxs)(i.bm,{className:"absolute right-4 top-4 roun
1ded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-secondary",children:[(0,a.jsx)(o.A,{className:"h-4 w-4"}),(0,a.jsx)("span",{className:"sr-only",children:"Close"})]})]})]}));h.displayName=i.UC.displayName;let p=({className:e,...t})=>(0,a.jsx)("div",{className:(0,s.cn)("flex flex-col space-y-2 text-center sm:text-left",e),...t});p.displayName="SheetHeader";let g=n.forwardRef(({className:e,...t},r)=>(0,a.jsx)(i.hE,{ref:r,className:(0,s.cn)("text-lg font-semibold text-foreground",e),...t}));g.displayName=i.hE.displayName;let b=n.forwardRef(({className:e,...t},r)=>(0,a.jsx)(i.VY,{ref:r,className:(0,s.cn)("text-sm text-muted-foreground",e),...t}));b.displayName=i.VY.displayName},21582:(e,t,r)=>{r.d(t,{bq:()=>m,eb:()=>g,gC:()=>p,l6:()=>c,yv:()=>u});var a=r(85047),n=r(31615),i=r(63824),l=r(26345),o=r(92788),s=r(68341),d=r(34961);let c=i.bL;i.YJ;let u=i.WT,m=n.forwardRef(({className:e,children:t,...r},n)=>(0,a.jsxs)(i.l9,{ref:n,className:(0,d.cn)("flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm r
1ing-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",e),...r,children:[t,(0,a.jsx)(i.In,{asChild:!0,children:(0,a.jsx)(l.A,{className:"h-4 w-4 opacity-50"})})]}));m.displayName=i.l9.displayName;let f=n.forwardRef(({className:e,...t},r)=>(0,a.jsx)(i.PP,{ref:r,className:(0,d.cn)("flex cursor-default items-center justify-center py-1",e),...t,children:(0,a.jsx)(o.A,{className:"h-4 w-4"})}));f.displayName=i.PP.displayName;let h=n.forwardRef(({className:e,...t},r)=>(0,a.jsx)(i.wn,{ref:r,className:(0,d.cn)("flex cursor-default items-center justify-center py-1",e),...t,children:(0,a.jsx)(l.A,{className:"h-4 w-4"})}));h.displayName=i.wn.displayName;let p=n.forwardRef(({className:e,children:t,position:r="popper",...n},l)=>(0,a.jsx)(i.ZL,{children:(0,a.jsxs)(i.UC,{ref:l,className:(0,d.cn)("relative z-[70] max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2","popper"===r&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:r,...n,children:[(0,a.jsx)(f,{}),(0,a.jsx)(i.LM,{className:(0,d.cn)("p-1","popper"===r&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),(0,a.jsx)(h,{})]})}));p.displayName=i.UC.displayName,n.forwardRef(({className:e,...t},r)=>(0,a.jsx)(i.JU,{ref:r,className:(0,d.cn)("py-1.5 pl-8 pr-2 text-sm font-semibold",e),...t})).displayName=i.JU.displayName;let g=n.forwardRef(({className:e,children:t,...r},n)=>(0,a.jsxs)(i.q7,{ref:n,className:(0,d.cn)("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...r,children:[(0,a.jsx)("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:(0,a.jsx)(i.VF,{children:(0,a.jsx)(s.A,{className:"h-4 w-4"})})}),(0,a.jsx)(i.p4,{children:t})]}));g.displayName=i.q7.displayName,n.forwardRef(({className:e,...t},r)=>(0,a.jsx)(i.wv,{ref:r,className:(0,d.cn)("-mx-1 my-1 h-px bg-muted",e),...t})).displayName=i.wv.displayName},34390:(e,t,r)=>{r.d(t,{A1:()=>s,IM:()=>o,N$:()=>l});var a=r(47026),n=r(41482);let i=(e,t)=>(0,a.A7)(Number(e)||0,(0,a.WC)(String(t??"twd")));function l(e,t){return(0,n.ng)(e,t??[],i).totalCash}function o(e){return(0,n.JV)(e,i)}function s(e,t){return 0}},39730:(e,t,r)=>{r.r(t),r.d(t,{CustomizableDashboard:()=>tK});var a=r(85047),n=r(31615),i=r(18710),l=r(41178),o=r(93027),s=r(90481),d=r(73521),c=r(15418),u=r(18654);let m=c.Ik({id:c.Yj(),type:c.Yj(),enabled:c.zM(),order:c.ai()}),f=c.Ik({id:c.Yj(),indicatorId:c.Yj(),priority:c.k5(["critical","secondary","advanced"]),hidden:c.zM()}).passthrough(),h=c.Ik({id:c.Yj(),type:c.k5(["indicator","chart","netWorth","financialHealth"]),metricKey:c.Yj(),title:c.Yj().optional()}),p=c.Ik({version:c.ai(),cardStyle:c.k5(["glass","flat","shadow"]).default("shadow"),colorMode:c.k5(["standard","inverted"]).default("standard"),charts:c.YO(m),indicators:c.YO(f),activeChartTab:c.Yj().optional(),activeIndicatorTab:c.k5(["critical","secondary","advanced"]).default("critical"),lastUpdated:c.Yj(),dashboardCards:c.YO(h).max(20).default([]),rowStarts:c.YO(c.ai()).optional(),columnWidths:c.YO(c.YO(c.ai().positive())).optional()}),g=function(e){return Array.isArray(e)?e.filter(e=>"quickInput"!==e.type&&"goals"!==e.type&&"cashflowSummary"!==e.type&&"income-distribution"!==e.type):[]},b={version:1,cardStyle:"shadow",colorMode:"standard",charts:[{id:"income-expense-trend",type:"income-expense-trend",enabled:!0,order:0},{id:"asset-liability",type:"asset-liability",enabled:!0,order:1},{id:"networth-growth",type:"networth-growth",enabled:!0,order:2},{id:"income-trend",type:"income-trend",enabled:!0,order:3},{id:"income-pie",type:"income-pie",enabled:!0,order:4},{id:"expense-trend",type:"expense-trend",enabled:!0,order:5},{id:"expense-pie",type:"expense-pie",enabled:!0,order:6},{id:"asset-distribution",type:"asset-distribution",enabled:!0,order:7},{id:"liability-distribution",type:"liability-distribution",enabled:!0,order:8},{id:"investment-accounts",type:"investment-accounts",enabled:!0,order:9},{id:"investment-assets",type:"investment-assets",enabled:!0,order:10},{id:"investment-industry",type:"investment-industry",enabled:!0,order:11},{id:"insurance-medical",type:"insurance-medical",enabled:!0,order:12},{id:"insurance-life",type:"insurance-life",enabled:!0,order:13},{id:"insurance-coverage-gap",type:"insurance-coverage-gap",enabled:!0,order:14}],indicators:[],activeIndicatorTab:"critical",lastUpdated:new Date().toISOString(),dashboardCards:[]};function x(e){return e<=0?[]:1===e?[8]:2===e?[4,4]:3===e?[2,3,3]:e>=4?Array(e).fill(2):[]}function y(e,t,r,a){let n=e?.length?[...e]:[0],i=[];for(let e=0;e<r.length;e++){let l=r[e],o=e+1<r.length?r[e+1]:a,s=0;for(let e=0;e<n.length;e++)if(l<(e+1<n.length?n[e+1]:a)){s=e;break}let d=n[s]??0,c=t[s];Array.isArray(c)&&c.length>=o-d?i.push(c.slice(l-d,o-d)):i.push(x(o-l))}return i}var v=r(80221),w=r(48019);let j=[{level:1,min:0,max:9,label:"病危",tone:"現在偏病危,
1先處理最傷的那一塊"},{level:2,min:10,max:19,label:"半殘",tone:"有點半殘,先把基本盤顧好"},{level:3,min:20,max:29,label:"虛弱",tone:"體質偏虛,補一補就會好很多"},{level:4,min:30,max:39,label:"感冒",tone:"像感冒,別急,一步一步來"},{level:5,min:40,max:49,label:"普通",tone:"普普通通,有進步空間"},{level:6,min:50,max:59,label:"還行",tone:"整體還行,再補強一兩個點"},{level:7,min:60,max:69,label:"不錯",tone:"不錯喔,繼續維持好習慣"},{level:8,min:70,max:79,label:"健康",tone:"狀態健康,維持就好"},{level:9,min:80,max:89,label:"活力",tone:"活力很好!再細修會更穩"},{level:10,min:90,max:100,label:"滿血",tone:"滿血狀態!繼續保持"}],S={"expense-ratio":60,"debt-ratio":50,"emergency-fund-coverage":6,"financial-freedom":50,"savings-rate":30,"investment-ratio":50,"debt-to-income":35,"net-worth-growth":10,"housing-expense":30,"loan-to-value":80,"current-ratio":200,"investment-diversification":70,"excess-cash-ratio":100},N={cashflow:[{type:"expense-ratio",weight:10},{type:"savings-rate",weight:12},{type:"housing-expense",weight:8}],resilience:[{type:"emergency-fund-coverage",weight:18},{type:"current-ratio",weight:7},{type:"excess-cash-ratio",weight:5}],debt:[{type:"debt-ratio",weight:10},{type:"debt-to-income",weight:10},{type:"loan-to-value",weight:5}],growth:[{type:"net-worth-growth",weight:5},{type:"investment-diversification",weight:4},{type:"investment-ratio",weight:3},{type:"financial-freedom",weight:3}]},C={cashflow:"日常收支",resilience:"安全韌性",debt:"負債壓力",growth:"長期成長"},k={"expense-ratio":"支出比","debt-ratio":"負債比","emergency-fund-coverage":"緊急預備金","financial-freedom":"財務自由度","savings-rate":"儲蓄率","investment-ratio":"投資比例","debt-to-income":"債務收入比","net-worth-growth":"淨值增長率","housing-expense":"住房支出比","loan-to-value":"財務槓桿","current-ratio":"流動比率","investment-diversification":"投資分散度","excess-cash-ratio":"超額現金比"},A={"expense-ratio":"把支出佔收入的比例壓低一點","debt-ratio":"降低負債相對資產的比重","emergency-fund-coverage":"先存到約 6 個月支出的緊急預備金","financial-freedom":"慢慢增加被動/非工作收入","savings-rate":"提高每月能留下來的儲蓄比例","investment-ratio":"適度提高投資性資產佔比","debt-to-income":"讓每月還款不要吃掉太多收入","net-worth-growth":"持續讓淨值往上走","housing-expense":"住房相關支出別佔收入太高","loan-to-value":"降低槓桿,別讓負債相對淨值過高","current-ratio":"提高流動資產、降低短期負債壓力","investment-diversification":"投資別過度集中在單一類型","excess-cash-ratio":"超額現金可逐步配置,提高資金利用率"},T={"expense-ratio":"expense","debt-ratio":"liabilities","emergency-fund-coverage":"accounts","financial-freedom":"income","savings-rate":"income","investment-ratio":"investments","debt-to-income":"liabilities","net-worth-growth":"assets","housing-expense":"expense","loan-to-value":"liabilities","current-ratio":"assets","investment-diversification":"investments","excess-cash-ratio":"investments"};function E(e){return Number.isFinite(e)?Math.max(0,Math.min(1,e)):0}function I(e){let t=Math.max(0,Math.min(100,e));for(let e of j)if(t<=e.max)return e;return j[j.length-1]}function R(e){let t=e.reduce((e,t)=>e+t.weight,0);return t<=0?null:e.reduce((e,t)=>e+t.score*t.weight,0)/t*100}let M="dashboardConfig_v2",L="dashboardColumnWidths_v2",z={id:"card-financial-health",type:"financialHealth",metricKey:"financial-health",title:"財務健康"};function D(e){return e.some(e=>"financialHealth"===e.type)?e:[z,...e].slice(0,20)}function F(e,t){if(e<=t)return[0];let r=[0];for(let a=t;a<e;a+=t)r.push(a);return r}function V(e,t,r){if(!Array.isArray(e)||e.length!==t.length)return!1;for(let a=0;a<t.length;a++){let n=t[a]??0,i=(a+1<t.length?t[a+1]:r)-n,l=e[a];if(!Array.isArray(l)||l.length!==i||8!==l.reduce((e,t)=>e+t,0)||!l.every(e=>e>=2&&e<=8&&Number.isInteger(e)))return!1}return!0}let P=["expense-ratio","debt-ratio","emergency-fund-coverage"],O=["savings-rate","investment-ratio","housing-expense"],W=["financial-freedom","debt-to-income","net-worth-growth"];function _(e){try{localStorage.setItem(M,JSON.stringify(e))}catch(e){console.error("儲存儀表板配置失敗:",e)}}function $(e){if(!Array.isArray(e)||0===e.length)return[];let t=new Set(P),r=new Set(O),a=new Set(W);return e.map(e=>{let n=String(e.id),i=e.type;return t.has(i)?{id:`indicator-${n}`,indicatorId:n,priority:"critical",hidden:!1}:r.has(i)?{id:`indicator-${n}`,indicatorId:n,priority:"secondary",hidden:!1}:a.has(i)?{id:`indicator-${n}`,indicatorId:n,priority:"advanced",hidden:!1}:{id:`indicator-${n}`,indicatorId:n,priority:"advanced",hidden:!0}})}var H=r(54830),G=r(97756),U=r(51045),B=r(34961),K=r(82520),q=r(21410),Y=r(42165);let J=(0,n.createContext)(void 0);function Q({children:e,suppressInnerBorder:t}){return(0,a.jsx)(J.Provider,{value:{suppressInnerBorder:t},children:e})}function Z(){return(0,n.useContext)(J)}var X=r(60154),ee=r(88758),et=r(14188),er=r(9164);let ea={glass:"backdrop-blur-2xl bg-gradient-to-br from-white/95 via-white/80 to-white/60 dark:from-gray-900/95 dark:via-gray-900/80 dark:to-gray-900/60 shadow-[0_8px_32px_0_rgba(31,38,135,0.37)] dark:shadow-[0_8px_32px_0_rgba(0,0,0,0.6)]",flat:"bg-card shadow-none",shadow:"bg-card shadow-[0_4px_6px_-1px_rgba(0,0,0,0.1),0_2px_4px_-1px_rgba(0,0,0,0.06)] dark:shadow-[0_4px_6px_-1px_rgba(0,0,0,0.3),0_2px_4px_-1px_rgba(0,0,0,0.2)] hover:shadow-[0_10px_15px_-3px_rgba(0,0,0,0.1),0_4px_6px_-2px_rgba(0,0,0,0.05)] dark:hover:shadow-[0_10px_15px_-3px_rgba(0,0,0,0.4),0_4px_6px_-2px_rgba(0,0,0,0.3)] hover:-translate-y-0.5"},en={"green-50":"bg-gradient-to-br from-green-50 to-emerald-100 dark:from-green-900/20 dark:to-emerald-900/20","red-50":"bg-gradient-to-br from-red-50 to-rose-100 dar
1k:from-red-900/20 dark:to-rose-900/20","yellow-50":"bg-gradient-to-br from-yellow-50 to-amber-100 dark:from-yellow-900/20 dark:to-amber-900/20","blue-50":"bg-gradient-to-br from-blue-50 to-indigo-100 dark:from-blue-900/20 dark:to-indigo-900/20"},ei={"green-300":"border-2 border-green-300 dark:border-green-700","red-300":"border-2 border-red-300 dark:border-red-700","yellow-300":"border-2 border-yellow-300 dark:border-yellow-700","blue-300":"border-2 border-blue-300 dark:border-blue-700","purple-300":"border-2 border-purple-300 dark:border-purple-700","violet-300":"border-2 border-violet-300 dark:border-violet-700"};function el(e){return ei[e]??"border-0"}function eo({id:e,title:t,children:r,className:n,headerClassName:i,contentClassName:l,isResizable:o=!0,isDraggable:s=!0,onRemove:d,onTogglePin:c,isVisible:u=!0,pinned:m=!1,minW:f=1,minH:h=1,maxW:p=4,maxH:g=4,gradientFrom:b,gradientTo:x,borderColor:y,cardStyle:v,headerActions:w,titleClassName:j,noBorder:S=!1}){let N=Z(),C=S||(N?.suppressInnerBorder??!1),k=v?ea[v]:b&&x&&en[b||""]?en[b||""]:"bg-card",A="";if(v)if(y&&ei[y]){let e=(ei[y].match(/(?:dark:)?border-[a-z]+-\d+/g)||[]).join(" ");A="glass"===v?`border ${e} opacity-80`:"flat"===v?`border-2 ${e}`:`border ${e}`}else A="glass"===v?"border border-white/30 dark:border-white/10":"flat"===v?"border-2 border-border":"border border-border/50";else A=y&&ei[y]?ei[y]:"border";let T=C?"border-0":A,E=(0,B.cn)("relative h-full flex flex-col overflow-hidden",C||"glass"!==v?C||"flat"!==v?"rounded-xl transition-all duration-300":"rounded-md transition-none":"rounded-2xl transition-all duration-300",C?"bg-transparent shadow-none":k,T,n),I=(0,a.jsxs)(a.Fragment,{children:[(0,a.jsxs)(K.aR,{className:(0,B.cn)("flex flex-row items-center justify-between space-y-0 pb-2 flex-shrink-0",i),children:[(0,a.jsx)(K.ZB,{className:(0,B.cn)("text-base font-bold tracking-tight flex items-center gap-2 truncate min-w-0",j),children:t}),(0,a.jsxs)("div",{className:"flex items-center gap-2",children:[w,c&&(0,a.jsx)("button",{type:"button",onClick:e=>{e.stopPropagation(),e.preventDefault(),c()},onMouseDown:e=>e.stopPropagation(),className:(0,B.cn)("text-muted-foreground hover:text-foreground transition-colors flex-shrink-0 z-10",m&&"text-foreground"),title:m?"取消釘選":"釘選卡片",children:m?(0,a.jsx)(X.A,{className:"h-4 w-4"}):(0,a.jsx)(ee.A,{className:"h-4 w-4"})}),d&&(0,a.jsx)("button",{type:"button",onClick:e=>{e.stopPropagation(),e.preventDefault(),d&&d()},onMouseDown:e=>{e.stopPropagation()},className:"text-muted-foreground hover:text-foreground transition-colors flex-shrink-0 z-10",title:u?"隱藏":"顯示",children:u?(0,a.jsx)(et.A,{className:"h-4 w-4"}):(0,a.jsx)(er.A,{className:"h-4 w-4"})})]})]}),(0,a.jsx)(K.Wu,{className:(0,B.cn)("pt-0 flex-1 min-h-0 overflow-hidden",l),children:(0,a.jsx)("div",{className:"h-full w-full min-h-0 overflow-hidden relative",children:r})})]});return C?(0,a.jsx)("div",{className:E,children:I}):(0,a.jsx)(K.Zp,{className:E,children:I})}function es(e,t,r="positive"){let a=e>=0;return("standard"===t?"positive"===r?a:!a:"positive"===r?!a:a)?{text:"text-green-600 dark:text-green-400",bg:"bg-green-50 dark:bg-green-900/20",border:"border-green-300 dark:border-green-700",gradient:"from-green-50 to-emerald-100 dark:from-green-900/20 dark:to-emerald-900/20",accentBar:"bg-green-500/85 dark:bg-green-400/90",borderAccent:"border-l-emerald-600 dark:border-l-emerald-500",heroTint:"from-green-600/[0.14] via-transparent to-transparent dark:from-green-400/[0.18]"}:{text:"text-red-600 dark:text-red-400",bg:"bg-red-50 dark:bg-red-900/20",border:"border-red-300 dark:border-red-700",gradient:"from-red-50 to-rose-100 dark:from-red-900/20 dark:to-rose-900/20",accentBar:"bg-red-500/85 dark:bg-red-400/90",borderAccent:"border-l-red-600 dark:border-l-red-500",heroTint:"from-red-600/[0.14] via-transparent to-transparent dark:from-red-400/[0.18]"}}function ed(e){return["expense-ratio","debt-ratio","debt-to-income","loan-to-value","housing-expense"].includes(e)?"negative":"positive"}var ec=r(95042),eu=r(2622),em=r(63972),ef=r(19726),eh=r(79319),ep=r(17938),eg=r(40975),eb=r(49793),ex=r(61414),ey=r(96104),ev=r(75020),ew=r(21285);function ej({type:e,className:t}){let r=(0,B.cn)("shrink-0",t);switch(e){case"savings-rate":return(0,a.jsx)(ec.A,{className:r});case"investment-ratio":return(0,a.jsx)(eu.A,{className:r});case"financial-freedom":return(0,a.jsx)(em.A,{className:r});case"emergency-fund-coverage":return(0,a.jsx)(ef.A,{className:r});case"current-ratio":return(0,a.jsx)(eh.A,{className:r});case"expense-ratio":case"excess-cash-ratio":return(0,a.jsx)(ep.A,{className:r});case"debt-ratio":case"debt-to-income":return(0,a.jsx)(eg.A,{className:r});case"housing-expense":return(0,a.jsx)(eb.A,{className:r});case"investment-diversification":return(0,a.jsx)(ex.A,{className:r});case"loan-to-value":return(0,a.jsx)(ey.A,{className:r});case"net-worth-growth":return(0,a.jsx)(ev.A,{className:r});default:return(0,a.jsx)(ew.A,{className:r})}}let eS=2*Math.PI*46,eN=({indicator:e,financialSummary:t=null,cardStyle:r="shadow",colorMode:i="standard",onRemove:l,onToggleHidden:o,className:s,sourceItems:d})=>
1{let[c,u]=(0,n.useState)(!1),m=(0,n.useRef)(null),f=null!=t?parseFloat((0,v.v$)(e.type,t).toFixed(1)):e.value,h=(0,w.Tb)(f,e.target,e.type),p=(0,w.Ns)(e.target,e.type),g=ed(e.type),b=es(f-e.target,i,g),x=(0,w.F4)(f,e.target,e.type),y=Math.min(Math.max(h,0),100),j="emergency-fund-coverage"===e.type?`${f.toFixed(1)}個月`:`${f.toFixed(1)}%`,S=x?{track:"rgba(16,185,129,0.14)",fill:"#10b981"}:y>=70?{track:"rgba(99,102,241,0.14)",fill:"url(#ringGrad)"}:y>=40?{track:"rgba(245,158,11,0.14)",fill:"#f59e0b"}:{track:"rgba(239,68,68,0.11)",fill:"#ef4444"},N=(0,n.useCallback)(()=>{m.current=setTimeout(()=>u(!0),500)},[]),C=(0,n.useCallback)(()=>{m.current&&(clearTimeout(m.current),m.current=null)},[]),k=(0,n.useCallback)(()=>{c&&u(!1)},[c]),A=(0,a.jsx)("span",{className:(0,B.cn)("inline-flex items-center rounded-full px-2 py-0.5 text-[11px] font-semibold leading-none",x?"bg-emerald-500/15 text-emerald-600 dark:text-emerald-400":"bg-muted/60 text-muted-foreground"),children:x?"已達標":"未達標"});return(0,a.jsx)(eo,{id:`indicator-${e.id}`,title:e.title,cardStyle:r,borderColor:void 0,className:s,headerClassName:"px-4 pt-3 pb-0 sm:px-5 sm:pt-4",contentClassName:"p-0",headerActions:A,children:(0,a.jsxs)("div",{className:"relative flex h-full min-h-0 flex-col overflow-hidden px-4 pb-4 pt-2 sm:px-5 sm:pb-5 select-none",onMouseDown:N,onMouseUp:C,onMouseLeave:C,onTouchStart:N,onTouchEnd:C,onClick:k,children:[c&&d&&d.length>0&&(0,a.jsxs)("div",{className:"absolute inset-0 z-10 flex flex-col justify-center gap-2 rounded-xl px-5 py-4 bg-card/95 backdrop-blur-sm border border-border/40",children:[(0,a.jsx)("p",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-1",children:"資料來源"}),(0,a.jsx)("ul",{className:"space-y-1.5",children:d.map((e,t)=>(0,a.jsxs)("li",{className:"flex justify-between gap-3 text-xs",children:[(0,a.jsx)("span",{className:"text-muted-foreground",children:e.label}),(0,a.jsx)("span",{className:"font-medium tabular-nums text-foreground/90",children:e.value})]},t))})]}),(0,a.jsxs)("div",{className:"flex flex-1 min-h-0 items-center gap-4 py-2",children:[(0,a.jsxs)("div",{className:"relative h-full min-h-0 aspect-square shrink-0",children:[(0,a.jsxs)("svg",{viewBox:"0 0 118 118",className:"w-full h-full","aria-label":`${e.title},現況 ${j},${p}`,role:"img",children:[(0,a.jsx)("defs",{children:(0,a.jsxs)("linearGradient",{id:"ringGrad",x1:"0%",y1:"0%",x2:"100%",y2:"100%",children:[(0,a.jsx)("stop",{offset:"0%",stopColor:"#6366f1"}),(0,a.jsx)("stop",{offset:"100%",stopColor:"#8b5cf6"})]})}),(0,a.jsx)("circle",{cx:59,cy:59,r:46,fill:"none",stroke:S.track,strokeWidth:11}),(0,a.jsx)("circle",{cx:59,cy:59,r:46,fill:"none",stroke:S.fill,strokeWidth:11,strokeLinecap:"round",strokeDasharray:eS,strokeDashoffset:eS*(1-y/100),transform:"rotate(-90 59 59)",style:{transition:"stroke-dashoffset 0.65s cubic-bezier(0.34,1.56,0.64,1)"}})]}),(0,a.jsx)("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:(0,a.jsx)(ej,{type:e.type,className:(0,B.cn)("w-[28%] h-[28%]",x?"text-emerald-500/55 dark:text-emerald-400/55":"text-muted-foreground/45")})})]}),(0,a.jsxs)("div",{className:"flex flex-col justify-center gap-3 min-w-0 flex-1",children:[(0,a.jsxs)("div",{className:"flex flex-col gap-0.5",children:[(0,a.jsx)("span",{className:"text-[11px] font-medium tracking-wider text-muted-foreground/50 uppercase",children:"現況"}),(0,a.jsx)("span",{className:(0,B.cn)("text-3xl font-extrabold tabular-nums tracking-tight leading-none",x?"text-emerald-500 dark:text-emerald-400":b.text),children:j})]}),(0,a.jsx)("div",{className:"h-px w-full bg-border/30"}),(0,a.jsxs)("div",{className:"flex flex-col gap-0.5",children:[(0,a.jsx)("span",{className:"text-[11px] font-medium tracking-wider text-muted-foreground/50 uppercase",children:"目標"}),(0,a.jsx)("span",{className:"text-xl font-semibold tabular-nums leading-none text-foreground/65",children:p.replace(/^[^::]+[::]\s*/,"")})]})]})]}),(0,a.jsx)("div",{className:"border-t border-border/35 pt-2.5",children:(0,a.jsx)("p",{className:"text-xs leading-relaxed text-muted-foreground",children:(e=>{switch(e){case"expense-ratio":return"月支出佔收入比例,衡量消費控制能力。健康水準建議低於 70%,比率愈低代表財務紀律愈好。";case"debt-ratio":return"總負債佔總資產比例,反映整體財務風險。建議低於 40%,超過 60% 表示負債壓力偏重。";case"emergency-fund-coverage":return"緊急備用金可支應的月數,用於應對失業或突發支出。建議至少備足 3–6 個月的生活費。";case"savings-rate":return"每月儲蓄佔收入比例,是累積財富的關鍵指標。建議至少達到 20%,比率愈高財務安全感愈強。";case"investment-ratio":return"投資資產佔總資產比例,反映資產增值潛力。建議維持 30–60%,適度投資有助於長期財富增長。";case"housing-expense":return"住房相關支出(房租/房貸)佔月收入比例。建議控制在 30% 以內,超過則可能擠壓其他財務空間。";case"financial-freedom":return"被動收入相對月支出的覆蓋比例,衡量財務獨立程度。達到 100% 代表無需工作也能維持生活水準。";case"loan-to-value":return"總負債相對淨資產的槓桿比率,數值愈低代表財務結構愈穩健。建議維持在 50% 以下。";case"debt-to-income":return"每月債務還款佔月收入比例,衡量還款壓力。建議低於 36%,超過 43% 通常被視ç
1‚ºé«˜é¢¨éšªã€‚";case"net-worth-growth":return"淨值(資產-負債)的年化增長率,是衡量整體財富累積速度的核心指標。";case"current-ratio":return"流動資產相對流動負債的比率,衡量短期償債能力。建議至少達到 1,比率愈高代表短期財務彈性愈大。";case"investment-diversification":return"投資組合跨資產類別的分散程度,分散投資可降低單一資產波動帶來的風險。";case"excess-cash-ratio":return"活存餘額相對緊急預備金目標的比例,衡量閒置現金利用率。過高代表資金未被有效配置與增值。";default:return""}})(e.type)})})]})})};var eC=r(35617);function ek({financialSummary:e,cardStyle:t="shadow",colorMode:r="standard"}){let n=Z(),i=n?.suppressInnerBorder??!1,l=e?.netWorth??0,o=es(l,r,"positive"),s="shadow"===t?"bg-card shadow-[0_4px_6px_-1px_rgba(0,0,0,0.1),0_2px_4px_-1px_rgba(0,0,0,0.06)] dark:shadow-[0_4px_6px_-1px_rgba(0,0,0,0.3),0_2px_4px_-1px_rgba(0,0,0,0.2)]":ea[t];return(0,a.jsx)(K.Zp,{className:(0,B.cn)("p-4 sm:p-6 h-full flex flex-col justify-center transition-all duration-200",s,"glass"===t?"rounded-2xl":"flat"===t?"rounded-md":"rounded-xl",i?"border-0 shadow-none":o.border),children:(0,a.jsxs)("div",{className:"space-y-1 sm:space-y-2",children:[(0,a.jsx)("h3",{className:"text-xs sm:text-sm font-medium text-muted-foreground",children:"目前淨值"}),(0,a.jsx)("div",{className:(0,B.cn)("text-xl sm:text-2xl md:text-3xl font-bold break-words",o.text),children:(0,eC.C)(l)}),(0,a.jsx)("p",{className:"text-xs text-muted-foreground",children:l>=0?"財務狀況良好":"需要改善財務狀況"})]})})}var eA=r(26052),eT=r.n(eA),eE=r(2929),eI=r(54387),eR=r(38187),eM=r(42226);let eL={病危:"text-red-600 dark:text-red-400",半殘:"text-red-500 dark:text-red-400",虛弱:"text-orange-600 dark:text-orange-400",感冒:"text-amber-600 dark:text-amber-400",普通:"text-muted-foreground",還行:"text-sky-600 dark:text-sky-400",不錯:"text-blue-600 dark:text-blue-400",健康:"text-emerald-600 dark:text-emerald-400",活力:"text-emerald-500 dark:text-emerald-300",滿血:"text-accent"},ez={1:"bg-red-500",2:"bg-red-400",3:"bg-orange-500",4:"bg-amber-500",5:"bg-muted-foreground/50",6:"bg-sky-500",7:"bg-blue-500",8:"bg-emerald-500",9:"bg-emerald-400",10:"bg-accent"};function eD({level:e,ready:t}){return(0,a.jsx)("div",{className:(0,B.cn)("relative flex h-3.5 w-full gap-0.5 overflow-hidden rounded-full bg-muted/70 p-0.5","shadow-[inset_0_1px_3px_rgba(0,0,0,0.06)] dark:shadow-[inset_0_1px_4px_rgba(0,0,0,0.4)]","ring-1 ring-border/30"),role:"img","aria-label":t&&e?`財務健康第 ${e} 級`:"資料不足",children:j.map(r=>{let n=t&&null!=e&&r.level<=e;return(0,a.jsx)("div",{title:r.label,className:(0,B.cn)("h-full min-w-0 flex-1 rounded-sm transition-colors",n?ez[r.level]:"bg-transparent")},r.level)})})}function eF({variant:e,className:t,cardStyle:r="shadow",resultOverride:n}){let{financialSummary:i,isLoading:l}=(0,s.P)(),o=n??function(e){let t,r,a,n,i,l,o,s={ready:!1,level:null,label:null,tone:"資料還不夠,先補齊收支與資產負債再說",index:null,coverageRatio:0,pillars:Object.keys(N).map(e=>({id:e,label:C[e],level:null,healthLabel:null,index:null,evaluatedWeight:0,totalWeight:N[e].reduce((e,t)=>e+t.weight,0)})),weakItems:[],nextAction:null,missingDataHint:"補齊收入、支出、帳戶與負債資料後,就能看出財務健康程度"};if(!e)return s;let d=function(e){let t=[];for(let[l,o]of Object.entries(N))for(let s of o){var r,a,n,i;let o=(r=s.type,"current-ratio"===r&&(e.shortTermLiabilitiesTotal??0)<=0?S["current-ratio"]:"debt-to-income"===r&&(e.totalLiabilities??0)<=0||"loan-to-value"===r&&(e.totalLiabilities??0)<=0?0:"loan-to-value"===r&&(e.netWorth??0)<=0&&(e.totalLiabilities??0)>0?3*S["loan-to-value"]:(0,v.v$)(r,e));if(!function(e,t,r){let a=t.monthlyIncome??0,n=t.emergencyFundCoverageMonths??0,i=t.totalLiabilities??0;switch(e){case"expense-ratio":case"savings-rate":case"housing-expense":case"debt-to-income":if(!(a>0)||"debt-to-income"===e&&!1===t.debtToIncomeEvaluable)return!1;return!0;case"emergency-fund-coverage":return(t.averageMonthlyExpenses??0)>0;case"excess-cash-ratio":return n>=6&&(t.emergencyFundTargetAmount??0)>0;case"current-ratio":case"loan-to-value":case"investment-ratio":case"investment-diversification":case"financial-freedom":case"net-worth-growth":return!0;case"debt-ratio":return(t.totalAssets??0)>0||i>0;default:return Number.isFinite(r)}}(s.type,e,o))continue;let d=S[s.type],c=(a=s.type,n=o,i=d,Number.isFinite(n)&&Number.isFinite(i)&&!(i<=0)?(0,w.Rt)(a)?n<=i?1:E(i/n):E(n/i):0);t.push({type:s.type,weight:s.weight,pillar:l,value:o,score:c})}return t}(e),c=Object.values(N).reduce((e,t)=>
1e+t.reduce((e,t)=>e+t.weight,0),0),u=d.reduce((e,t)=>e+t.weight,0),m=c>0?u/c:0,f=["cashflow","resilience","debt","growth"].map(e=>{let t=d.filter(t=>t.pillar===e),r=N[e].reduce((e,t)=>e+t.weight,0),a=t.reduce((e,t)=>e+t.weight,0),n=R(t);if(null==n)return{id:e,label:C[e],level:null,healthLabel:null,index:null,evaluatedWeight:a,totalWeight:r};let i=I(n);return{id:e,label:C[e],level:i.level,healthLabel:i.label,index:Math.round(10*n)/10,evaluatedWeight:a,totalWeight:r}}),h=["cashflow","resilience","debt"].every(e=>d.some(t=>t.pillar===e));if(!(m>=.6&&h))return{...s,coverageRatio:m,pillars:f,missingDataHint:"資料覆蓋還不夠,先補齊收支、預備金與負債相關資料"};let p=R(d);if(null==p)return{...s,coverageRatio:m,pillars:f};let g=(t=p,r=e.netWorth??0,a=e.totalLiabilities??0,n=e.monthlyIncome??0,i=e.monthlyExpenses??0,l=e.emergencyFundCoverageMonths??0,o=e.averageMonthlyExpenses??0,r<=0&&a>0&&(t=Math.min(t,9)),n>0&&i>n&&(t=Math.min(t,39)),o>0&&l<1&&(t=Math.min(t,39)),t),b=I(g),x=function(e,t=2){return[...e].sort((e,t)=>e.score-t.score||t.weight-e.weight).slice(0,t).map(e=>({type:e.type,label:k[e.type],hint:A[e.type],score:e.score,section:T[e.type]}))}(d,2);return{ready:!0,level:b.level,label:b.label,tone:b.tone,index:Math.round(10*g)/10,coverageRatio:m,pillars:f,weakItems:x,nextAction:x[0]??null,missingDataHint:null}}(i);if(l&&!n)return(0,a.jsx)(eo,{id:"financial-health",title:"財務健康",cardStyle:r,borderColor:void 0,className:(0,B.cn)("h-full",t),headerClassName:"px-4 pb-2 pt-4 sm:px-5 sm:pt-5",contentClassName:"p-0",children:(0,a.jsx)("div",{className:"flex h-full min-h-[120px] items-center justify-center text-sm text-muted-foreground",children:"載入中…"})});let d=o.ready&&o.label?eL[o.label]:"text-muted-foreground",c=o.ready?null!=o.level&&o.level>=8?"狀態佳":"可加強":"資料不足",u=(0,eM.PF)("advisor"),m=o.nextAction?`${o.nextAction.label} \xb7 ${o.nextAction.hint}`:o.ready?"各面向都不錯,繼續保持":o.missingDataHint??"補齊資料後就能評估";return(0,a.jsx)(eo,{id:"financial-health",title:"財務健康",cardStyle:r,borderColor:void 0,className:(0,B.cn)("h-full",t),headerClassName:"px-4 pb-2 pt-4 sm:px-5 sm:pt-5",contentClassName:"p-0",children:(0,a.jsx)("div",{className:"relative flex h-full min-h-0 flex-col overflow-hidden px-4 pb-4 sm:px-5 sm:pb-5",children:(0,a.jsxs)("div",{className:"relative z-[1] flex min-h-0 min-w-0 flex-1 flex-col",children:[(0,a.jsxs)("div",{className:"flex shrink-0 min-w-0 items-start gap-3",children:[(0,a.jsx)("span",{className:(0,B.cn)("flex h-12 w-12 shrink-0 items-center justify-center rounded-full","border border-border/50 bg-muted/30 text-muted-foreground dark:bg-muted/20"),children:(0,a.jsx)(eE.A,{className:"h-5 w-5","aria-hidden":!0})}),(0,a.jsx)("div",{className:"flex min-w-0 flex-1 flex-col gap-2",children:(0,a.jsxs)("div",{className:"flex min-w-0 flex-wrap items-baseline gap-x-2.5 gap-y-1",children:[(0,a.jsx)("p",{className:(0,B.cn)("text-4xl font-bold tracking-tight text-balance leading-tight sm:text-[2.5rem]",d),children:o.ready&&o.label?o.label:"資料不足"}),(0,a.jsx)(eR.E,{variant:"outline",className:(0,B.cn)("shrink-0 border px-2 py-0.5 text-xs font-semibold",o.ready&&null!=o.level&&o.level>=8?"border-emerald-500/40 bg-emerald-500/10 text-emerald-700 dark:border-emerald-500/35 dark:bg-emerald-500/10 dark:text-emerald-400":"border-border/70 bg-muted/30 text-muted-foreground"),children:c})]})})]}),(0,a.jsxs)("div",{className:"mt-4 w-full min-w-0 shrink-0 space-y-2",children:[(0,a.jsx)(eD,{level:o.level,ready:o.ready}),(0,a.jsxs)("div",{className:"flex justify-between gap-2 text-xs text-muted-foreground",children:[(0,a.jsx)("span",{children:"健康程度"}),(0,a.jsx)("span",{className:"font-medium text-foreground/90",children:o.ready&&o.label?o.label:"尚無法評估"})]})]}),(0,a.jsx)("div",{className:"min-h-0 min-w-0 flex-1","aria-hidden":!0}),(0,a.jsxs)("div",{className:"shrink-0 border-t border-border/35 pt-3",children:[(0,a.jsx)("p",{className:"line-clamp-2 hyphens-auto break-words text-xs leading-relaxed text-muted-foreground",children:m}),(0,a.jsxs)(eT(),{href:u,className:(0,B.cn)("mt-2.5 inline-flex items-center gap-1.5 rounded-md px-2 py-1.5 -ml-2","text-xs font-medium text-muted-foreground","transition-colors hover:bg-muted/60 hover:text-foreground","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background"),children:["諮詢顧
1問",(0,a.jsx)(eI.A,{className:"h-3.5 w-3.5 opacity-70","aria-hidden":!0})]})]})]})})})}var eV=r(6386),eP=r(87884),eO=r(60996),eW=r(75116),e_=r(91595),e$=r(79632),eH=r(34788);function eG(e){if(e?.container?.closest&&e.container.closest("[data-chart-fullscreen-overlay]"))return{maxHeight:600}}function eU(e,t){if(!e?.container)return!1;let r=t?.maxHeight??360;try{let t=e.container.parentElement||e.container,a=t.clientWidth||t.offsetWidth||0,n=t.clientHeight||t.offsetHeight||0,i=0===n||n<150;if(i){let e=n||r;n=Math.min(r,Math.max(150,e))}return n>r&&n<600&&(n=r),a>0&&n>0&&"function"==typeof e.setSize&&e.setSize(a,n),a>0&&n>0&&"function"==typeof e.reflow&&e.reflow(),i}catch{return!1}}function eB(e,t){let r=(0,n.useRef)(e);r.current=e,(0,n.useEffect)(()=>{let e=()=>{let e=r.current?.current;eU(e,eG(e))};window.addEventListener("dashboard-columns-resized",e);let t=setTimeout(e,200),a=null,n=()=>{let e=r.current?.current,t=e?.container;if(!t||"u"<typeof ResizeObserver)return!1;let n=t.parentElement||t;return eU(e,eG(e)),(a=new ResizeObserver(()=>{requestAnimationFrame(()=>{let e=r.current?.current;eU(e,eG(e))&&setTimeout(()=>{let e=r.current?.current;eU(e,eG(e))},400)})})).observe(n),!0};if(!n()){let r=0,i=setInterval(()=>{r+=1,(n()||r>=20)&&clearInterval(i)},100);return()=>{window.removeEventListener("dashboard-columns-resized",e),clearTimeout(t),a?.disconnect(),clearInterval(i)}}return()=>{window.removeEventListener("dashboard-columns-resized",e),clearTimeout(t),a?.disconnect()}},[])}var eK=r(47026);function eq(e){if(!e)return null;if("string"==typeof e)return/^\d{4}-\d{2}/.test(e)||/^\d{4}-\d{2}-\d{2}T/.test(e)?e.slice(0,7):null;if("function"==typeof e?.toDate)try{let t=e.toDate();return t?.toISOString?.()?.slice(0,7)??null}catch{return null}return e instanceof Date?e.toISOString().slice(0,7):null}function eY(e){if(!e)return null;if("string"==typeof e)return/^\d{4}-\d{2}/.test(e)||/^\d{4}-\d{2}-\d{2}T/.test(e)?e.slice(0,7):null;if("function"==typeof e?.toDate)try{let t=e.toDate();return t?.toISOString?.()?.slice(0,7)??null}catch{return null}return e instanceof Date?e.toISOString().slice(0,7):null}var eJ=r(2687),eQ=r(96813),eZ=r(99922);function eX(){return(0,eZ.D)(),(0,e_.py)()}var e0=r(56878),e1=r(27387),e2=r(63955),e5=r(34390);let e4=[{value:"cash",label:"現金"},{value:"stocks",label:"股票"},{value:"bonds",label:"債券"},{value:"funds",label:"基金"},{value:"insurance",label:"保險"},{value:"vehicle",label:"車輛"},{value:"real-estate",label:"不動產"},{value:"crypto",label:"加密貨幣"},{value:"collectibles",label:"收藏品"},{value:"other-asset",label:"其他資產"}];var e3=r(94170),e6=r(36093);function e8(e,t){let r=new Date(e.year,e.monthIndex0,1);return r.setMonth(r.getMonth()+t),{year:r.getFullYear(),monthIndex0:r.getMonth()}}function e9(e,t){return e.year!==t.year?e.year-t.year:e.monthIndex0-t.monthIndex0}let e7={mortgage:{label:"房貸",color:"#f59e0b"},"car-loan":{label:"車貸",color:"#22c55e"},"credit-card":{label:"信用卡",color:"#ec4899"},"bank-loan":{label:"銀行貸款",color:"#ef4444"},"personal-loan":{label:"個人貸款",color:"#06b6d4"},"student-loan":{label:"學貸",color:"#8b5cf6"},"business-loan":{label:"創業貸款",color:"#a855f7"},"margin-loan":{label:"融資融券",color:"#0ea5e9"},"other-liability":{label:"其他負債",color:"#6b7280"}};var te=r(71467),tt=r(46136),tr=r(63600),ta=r(21016),tn=r(41442),ti=r(61595),tl=r(2416);let to=(0,tn.zJ)().map(e=>({value:e.pageKey,label:e.tabLabel}));function ts({userId:e,chartKey:t="insuranceMedicalChart"}){let r=eX(),i=(0,n.useRef)(null),l=(0,n.useRef)(null),[o,s]=(0,n.useState)(!1);eB(i);let{policies:d}=(0,tt.I5)(e),{recommendations:c}=(0,tr.Q)(e,"medical"),{productRulesByProductId:u,benefitItemsByProductId:m}=(0,ti.j)(d),{currentData:f,targetData:h,uncategorizedMedicalCount:p}=(0,n.useMemo)(()=>{let{byPageKey:e,uncategorizedMedicalCount:t}=(0,tn.Kh)(d,c,u,m);return{currentData:to.map(({value:t})=>e[t]?.current??0),targetData:to.map(({value:t})=>e[t]?.target??0),uncategorizedMedicalCount:t}},[d,c,u,m]),g=h.some(e=>e>0);(0,n.useEffect)(()=>{let e=l.current;e&&s(null!=e.closest("[data-chart-fullscreen-overlay]"))},[g]);let b=(0,n.useMemo)(()=>
1{if(!g)return null;let e=to.map(e=>e.label);return{chart:{type:"bar",backgroundColor:"transparent",reflow:!0,style:{color:r.text}},title:{text:""},xAxis:{categories:e,lineColor:r.border,tickColor:r.border,gridLineColor:r.muted,labels:{style:{color:r.text,fontSize:"12px"}}},yAxis:{title:{text:"保額(萬元)",style:{color:r.text}},lineColor:r.border,tickColor:r.border,gridLineColor:r.muted,labels:{format:"{value:,.0f}",style:{color:r.mutedForeground,fontSize:"11px"}}},tooltip:{shared:!0,useHTML:!0,headerFormat:"",pointFormat:'<span style="color:{series.color}">●</span> {series.name}: <b>{point.y:,.0f}</b><br/>',backgroundColor:r.background,borderColor:r.border,style:{color:r.text}},plotOptions:{bar:{grouping:!0,borderWidth:0,dataLabels:{enabled:!0,format:"{y:,.0f}",style:{color:r.text,fontSize:"10px"}}}},legend:{align:"center",verticalAlign:"bottom",itemStyle:{color:r.text,fontSize:"12px",fontWeight:"500"},itemHoverStyle:{color:r.mutedForeground}},series:[{name:"目標保額",data:h,color:"#22c55e"},{name:"現有保額",data:f,color:"#60a5fa"}],credits:{enabled:!1}}},[f,h,g,r]);return g?(0,a.jsxs)("div",{ref:l,className:`flex h-full min-h-0 w-full flex-col overflow-hidden ${o?"min-h-[280px]":""}`,children:[p>0?(0,a.jsxs)(ta.Fc,{className:"mx-2 mt-2 shrink-0 border-amber-500/50 bg-amber-500/10",children:[(0,a.jsx)(tl.A,{className:"h-4 w-4 text-amber-600 dark:text-amber-400"}),(0,a.jsx)(ta.XL,{className:"text-amber-900 dark:text-amber-100",children:"未對照險種的醫療保單"}),(0,a.jsxs)(ta.TN,{className:"text-amber-800/90 dark:text-amber-200/90",children:["有 ",p," 張醫療保單的險種無法對照到標準分類,保額已暫列入「其他」計算。"]})]}):null,(0,a.jsx)("div",{"data-chart":t,className:o?"flex min-h-0 w-full flex-1 flex-col items-center justify-center py-2":"flex min-h-0 h-full w-full flex-1 flex-col",children:(0,a.jsx)("div",{className:o?"h-[min(70vh,560px)] w-full max-w-4xl min-h-[280px] min-w-0":"min-h-0 h-full w-full min-w-0 flex-1",children:(0,a.jsx)(eO.A,{highcharts:eP.A,options:b,containerProps:{style:{width:"100%",height:"100%"}},callback:e=>{if(!e)return;i.current=e;let r=()=>{if(!e.container)return void setTimeout(r,100);if(window[t]=e,e.getSVG||(e.getSVG=function(){try{let t=e.container||e.renderTo;if(t){let e=t instanceof HTMLElement?t:"string"==typeof t?document.querySelector(t):null;if(e){let t=e.querySelector("svg");if(t)return t.outerHTML}}throw Error("無法找到 SVG 元素")}catch(e){throw console.error(`[${t}] SVG 取得失敗:`,e),e}}),window[`${t}HasData`]=!0,"function"==typeof e.reflow)try{e.reflow()}catch{}};r()}})})})]}):(0,a.jsx)("div",{ref:l,className:"flex h-full min-h-0 w-full flex-col items-center justify-center overflow-hidden p-4",children:(0,a.jsx)(ta.Fc,{className:"max-w-md",children:(0,a.jsx)(ta.TN,{children:"請先執行需求計算器取得醫療險的建議保額,才能顯示比較圖表。"})})})}var td=r(53855);let tc=[{value:"wholeLife",label:"終身"},{value:"term",label:"定期"},{value:"investment",label:"投資型"},{value:"annuity",label:"年金"}];function tu({userId:e,chartKey:t="insuranceLifeChart"}){let r=(0,e_.py)(),i=(0,n.useRef)(null),l=(0,n.useRef)(null),[o,s]=(0,n.useState)(!1);eB(i);let{policies:d}=(0,tt.I5)(e),{recommendations:c}=(0,tr.Q)(e,"life"),u=(0,n.useMemo)(()=>{let e={};return tc.forEach(({value:t})=>{e[t]=0}),d.filter(e=>"life"===e.category).forEach(t=>{let r=(0,td.J)(t),a=t.insuranceType;e.hasOwnProperty(a)&&(e[a]+=r)}),tc.map(({value:t})=>e[t]||0)},[d]),m=(0,n.useMemo)(()=>u.reduce((e,t)=>e+t,0),[u]),f=(0,n.useMemo)(()=>{let e=0;if(c.filter(e=>"life"===e.category&&"lifeGap"===e.type).forEach(t=>{e=t.targetCoverage}),0===e)return tc.map(()=>0);let t=m+e,r={};return m>
10?tc.forEach(({value:e},a)=>{let n=u[a]/m;r[e]=t*n}):tc.forEach(({value:e})=>{r[e]="wholeLife"===e?t:0}),tc.map(({value:e})=>r[e]||0)},[c,m,u]),h=f.some(e=>e>0);(0,n.useEffect)(()=>{let e=l.current;e&&s(null!=e.closest("[data-chart-fullscreen-overlay]"))},[h]);let p=(0,n.useMemo)(()=>{if(!h)return null;let e=tc.map(e=>e.label);return(0,e_.dt)("column",{chart:{type:"column",backgroundColor:"transparent",reflow:!0},title:{text:""},xAxis:{categories:e,labels:{style:{color:r.text,fontSize:"12px"}}},yAxis:{title:{text:"保額",style:{color:r.text}},labels:{format:"{value:,.0f}",style:{color:r.mutedForeground,fontSize:"11px"}}},plotOptions:{column:{grouping:!0,dataLabels:{enabled:!0,format:"{y:,.0f}",style:{color:r.text,fontSize:"10px"}}}},tooltip:{shared:!0,useHTML:!0,headerFormat:"",pointFormat:'<span style="color:{series.color}">●</span> {series.name}: <b>{point.y:,.0f}</b><br/>',backgroundColor:r.background,borderColor:r.border,style:{color:r.text}},series:[{name:"目標保額",data:f,color:"#22c55e"},{name:"現有保額",data:u,color:"#60a5fa"}],credits:{enabled:!1}})},[u,f,h,r]);return h?(0,a.jsx)("div",{ref:l,className:`flex h-full min-h-0 w-full flex-col overflow-hidden ${o?"min-h-[280px]":""}`,children:(0,a.jsx)("div",{"data-chart":t,className:o?"flex min-h-0 w-full flex-1 flex-col items-center justify-center py-2":"flex min-h-0 h-full w-full flex-1 flex-col",children:(0,a.jsx)("div",{className:o?"h-[min(70vh,560px)] w-full max-w-4xl min-h-[280px] min-w-0":"min-h-0 h-full w-full min-w-0 flex-1",children:(0,a.jsx)(eO.A,{highcharts:eP.A,options:p,containerProps:{style:{width:"100%",height:"100%"}},callback:e=>{if(!e)return;i.current=e;let r=()=>{if(!e.container)return void setTimeout(r,100);if(window[t]=e,e.getSVG||(e.getSVG=function(){try{let t=e.container||e.renderTo;if(t){let e=t instanceof HTMLElement?t:"string"==typeof t?document.querySelector(t):null;if(e){let t=e.querySelector("svg");if(t)return t.outerHTML}}throw Error("無法找到 SVG 元素")}catch(e){throw console.error(`[${t}] SVG 取得失敗:`,e),e}}),window[`${t}HasData`]=!0,"function"==typeof e.reflow)try{e.reflow()}catch{}};r()}})})})}):(0,a.jsx)("div",{ref:l,className:"flex h-full min-h-0 w-full flex-col items-center justify-center overflow-hidden p-4",children:(0,a.jsx)(ta.Fc,{className:"max-w-md",children:(0,a.jsx)(ta.TN,{children:"請先執行需求計算器取得壽險的建議保額,才能顯示比較圖表。"})})})}let tm=["#60a5fa","#fbbf24","#22c55e","#8b5cf6","#ec4899","#14b8a6","#f59e0b","#6366f1"],tf={"income-expense-trend":"green-300","asset-liability":"blue-300","networth-growth":"green-300","income-trend":"green-300","income-pie":"green-300","expense-trend":"red-300","expense-pie":"red-300","asset-distribution":"blue-300","liability-distribution":"violet-300","investment-accounts":"purple-300","investment-assets":"purple-300","investment-industry":"purple-300","insurance-medical":"yellow-300","insurance-life":"yellow-300","insurance-coverage-gap":"yellow-300"}
1,th={"income-expense-trend":{label:"收入支出趨勢",component:function({cardStyle:e="shadow",colorMode:t="standard",onRemove:r,onTogglePin:i,isVisible:l=!0,pinned:o=!1,showShareButton:d=!1}){var c;let{rawData:u}=(0,s.P)(),m=(0,e_.py)(),f=(c=u||{},(0,n.useMemo)(()=>{let e=Array.isArray(c?.ledgerEntries)?c.ledgerEntries:[];return(0,eW.PC)(e,6)},[c?.ledgerEntries])),h=f.some(e=>0!==e.income||0!==e.expense),p=(0,n.useRef)(null),[g,b]=(0,n.useState)(!1),x="incomeExpenseTrendChart";eB(p),(0,n.useEffect)(()=>{let e,t=p.current;if(!t)return;let r=()=>{if(t&&t.container&&"function"==typeof t.reflow)try{t.reflow()}catch(e){console.warn("Chart reflow failed:",e)}},a=()=>{clearTimeout(e),e=setTimeout(r,150)};window.addEventListener("resize",a);let n=new ResizeObserver(a),i=t.container;return i&&n.observe(i.parentElement||i),()=>{window.removeEventListener("resize",a),n.disconnect(),clearTimeout(e)}},[]);let y=(0,n.useMemo)(()=>{if(!f.length)return null;let e=f.map(e=>e.month),t=f.map(e=>Number(e.income.toFixed(2))),r=f.map(e=>Number(e.expense.toFixed(2)));return(0,e_.dt)("line",{chart:{backgroundColor:"transparent"},title:{text:void 0},xAxis:{categories:e,title:{text:"月份"}},yAxis:{title:{text:"金額 (新台幣)"}},tooltip:{shared:!0,useHTML:!0,headerFormat:"<strong>{point.key}</strong><br/>",pointFormat:'<span style="color:{series.color}">{series.name}</span>: {point.y:,.0f}<br/>'},series:[{type:"spline",name:"收入",data:t,color:m.chart3,lineWidth:2,marker:{enabled:!0,radius:3}},{type:"area",name:"支出",data:r,color:m.chart1,fillOpacity:.1,lineWidth:2,marker:{enabled:!0,radius:3}}]})},[f,m.chart1,m.chart3]);return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(eo,{id:"income-expense-trend",title:"收入 / 支出趨勢",cardStyle:e,borderColor:"green-300",contentClassName:"flex h-full !p-0",headerActions:d?(0,a.jsx)(e$.S,{onClick:()=>b(!0),variant:"ghost",size:"icon"}):void 0,children:f.length&&h?(0,a.jsx)("div",{className:"w-full h-full min-h-0",children:y?(0,a.jsx)(eO.A,{highcharts:eP.A,options:y,callback:e=>{if(!e)return;p.current=e;let t=()=>{if(!e.container)return void setTimeout(t,100);if(window[x]=e,e.getSVG||(e.getSVG=function(){try{let e=this.container||this.renderTo;if(e){let t=e instanceof HTMLElement?e:"string"==typeof e?document.querySelector(e):null;if(t){let e=t.querySelector("svg");if(e)return e.outerHTML}}throw Error("無法找到 SVG 元素")}catch(e){throw console.error(`[${x}] SVG 取得失敗:`,e),e}}),window[`${x}HasData`]=h&&f.length>0,e&&e.container&&"function"==typeof e.reflow)try{e.reflow()}catch(e){console.warn("Chart reflow failed:",e)}};t()}}):(0,a.jsx)("div",{className:"flex h-full items-center justify-center text-sm text-muted-foreground",children:"圖表初始化中…"})}):(0,a.jsx)("div",{className:"flex flex-col items-center justify-center w-full text-sm text-muted-foreground",children:"目前沒有足夠的收入或支出紀錄可供繪製趨勢"})}),(0,a.jsx)(eH.Q,{open:g,onOpenChange:b,chartKey:x,chartTitle:"收入 / 支出趨勢"})]})}},"asset-liability":{label:"資產負債趨勢",component:function({cardStyle:e="shadow",colorMode:t="standard",onRemove:r,onTogglePin:i,isVisible:l=!0,pinned:o=!1,showShareButton:d=!1}){let{rawData:c}=(0,s.P)(),u=(0,e_.py)(),m=(0,n.useRef)(null),[f,h]=(0,n.useState)(!1),p="assetLiabilityTrendChart";eB(m),(0,n.useEffect)(()=>{let e,t=m.current;if(!t)return;let r=()=>{if(t&&t.container&&"function"==typeof t.reflow)try{t.reflow()}catch(e){console.warn("Chart reflow failed:",e)}},a=()=>{clearTimeout(e),e=setTimeout(r,150)};window.addEventListener("resize",a);let n=new ResizeObserver(a),i=t.container;return i&&n.observe(i.parentElement||i),()=>{window.removeEventListener("resize",a),n.disconnect(),clearTimeout(e)}},[]);let{categories:g,assetData:b,liabilityData:x}=(0,n.useMemo)(()=>{let e=Array.isArray(c?.assets)?c.assets:[],t=Array.isArray(c?.liabilities)?c.liabilities:[],r=new Set;e.forEach(e=>{let t=eq(e?.createdAt);t&&r.add(t)}),t.forEach(e=>{let t=eq(e?.createdAt);t&&r.add(t)});let a=Array.from(r).sort(),n=[],i=[],l=0,o=0;return a.forEach(r=>{let a=e.filter(e=>eq(e?.createdAt)===r).reduce((e,t)=>
1e+(0,eK.A7)(Number(t?.value||0),t?.currency?(0,eK.WC)(t.currency):"twd"),0),s=t.filter(e=>eq(e?.createdAt)===r).reduce((e,t)=>e+(0,eK.A7)(Number(t?.value||0),t?.currency?(0,eK.WC)(t.currency):"twd"),0);l+=a,o+=s,n.push(Number.isFinite(l)?l:0),i.push(Number.isFinite(o)?o:0)}),{categories:a,assetData:n,liabilityData:i}},[c?.assets,c?.liabilities]),y=g.length>0&&(b.some(e=>e>0)||x.some(e=>e>0)),v=(0,n.useMemo)(()=>(0,e_.dt)("line",{chart:{backgroundColor:"transparent",spacing:[20,20,20,20]},title:{text:null},xAxis:{categories:g,title:{text:"月份"}},yAxis:{title:{text:"金額 (新台幣)"}},series:[{name:"資產",data:b,color:u.primary,type:"spline",lineWidth:2,marker:{enabled:!0,radius:3,symbol:"circle"},states:{hover:{lineWidth:3}}},{name:"負債",data:x,color:u.destructive,type:"spline",lineWidth:2,marker:{enabled:!0,radius:3,symbol:"circle"},states:{hover:{lineWidth:3}}}],legend:{enabled:!0,align:"center",verticalAlign:"bottom"}}),[g,b,x,u]);return(0,a.jsxs)(eo,{id:p,title:"資產負債趨勢",cardStyle:e,className:"h-full",contentClassName:"flex h-full !p-0",children:[(0,a.jsxs)("div",{className:"relative h-full min-h-0 flex flex-col",children:[d&&(0,a.jsx)("div",{className:"absolute top-4 right-4 z-10",children:(0,a.jsx)(e$.S,{onClick:()=>h(!0)})}),y?(0,a.jsx)("div",{className:"flex-1 min-h-0 w-full",children:(0,a.jsx)(eO.A,{highcharts:eP.A,options:v,callback:e=>{e&&(m.current=e,setTimeout(()=>{if(e&&e.container&&"function"==typeof e.reflow)try{e.reflow()}catch(e){console.warn("Chart reflow failed:",e)}},100))}})}):(0,a.jsx)("div",{className:"flex-1 flex items-center justify-center text-muted-foreground text-sm",children:"目前沒有可用的資產負債資料"})]}),(0,a.jsx)(eH.Q,{open:f,onOpenChange:h,chartKey:p,chartTitle:"資產負債趨勢"})]})}},"networth-growth":{label:"淨值成長",component:function({cardStyle:e="shadow",colorMode:t="standard",onRemove:r,onTogglePin:i,isVisible:l=!0,pinned:o=!1,showShareButton:d=!1}){let{rawData:c}=(0,s.P)(),u=(0,e_.py)(),m=(0,n.useRef)(null),[f,h]=(0,n.useState)(!1),p="netWorthGrowthChart";eB(m),(0,n.useEffect)(()=>{let e,t=m.current;if(!t)return;let r=()=>{if(t&&t.container&&"function"==typeof t.reflow)try{t.reflow()}catch(e){console.warn("Chart reflow failed:",e)}},a=()=>{clearTimeout(e),e=setTimeout(r,150)};window.addEventListener("resize",a);let n=new ResizeObserver(a),i=t.container;return i&&n.observe(i.parentElement||i),()=>{window.removeEventListener("resize",a),n.disconnect(),clearTimeout(e)}},[]);let{categories:g,netData:b}=(0,n.useMemo)(()=>{let e=Array.isArray(c?.assets)?c.assets:[],t=Array.isArray(c?.liabilities)?c.liabilities:[],r=new Set;e.forEach(e=>{let t=eY(e?.createdAt);t&&r.add(t)}),t.forEach(e=>{let t=eY(e?.createdAt);t&&r.add(t)});let a=Array.from(r).sort(),n=0,i=[];return a.forEach(r=>{let a=e.filter(e=>eY(e?.createdAt)===r).reduce((e,t)=>e+(0,eK.A7)(Number(t?.value||0),t?.currency?(0,eK.WC)(t.currency):"twd"),0),l=t.filter(e=>eY(e?.createdAt)===r).reduce((e,t)=>e+(0,eK.A7)(Number(t?.value||0),t?.currency?(0,eK.WC)(t.currency):"twd"),0);n+=a-l,i.push(Number.isFinite(n)?n:0)}),{categories:a,netData:i}},[c?.assets,c?.liabilities]),x=g.length>0&&b.some(e=>0!==e),y=(0,n.useMemo)(()=>(0,e_.dt)("line",{chart:{backgroundColor:"transparent",spacing:[20,20,20,20]},title:{text:null},xAxis:{categories:g,title:{text:"月份"}},yAxis:{title:{text:"金額 (新台幣)"}},series:[{name:"淨值",data:b,color:u.primary,type:"spline",lineWidth:2,marker:{enabled:!0,radius:3,symbol:"circle"},states:{hover:{lineWidth:3}}}]}),[g,b,u]);return(0,a.jsxs)(eo,{id:p,title:"淨值成長",cardStyle:e,className:"h-full",contentClassName:"flex h-full !p-0",children:[(0,a.jsxs)("div",{className:"relative h-full min-h-0 flex flex-col",children:[d&&(0,a.jsx)("div",{className:"absolute top-4 right-4 z-10",children:(0,a.jsx)(e$.S,{onClick:()=>h(!0)})}),x?(0,a.jsx)("div",{className:"flex-1 min-h-0 w-full",children:(0,a.jsx)(eO.A,{highcharts:eP.A,options:y,callback:e=>{e&&(m.current=e,setTimeout(()=>{if(e&&e.container&&"function"==typeof e.reflow)try{e.reflow()}catch(e){console.warn("Chart reflow failed:",e)}},100))}})}):(0,a.jsx)("div",{className:"flex-1 flex items-center justify-center text-muted-foreground text-sm",children:"目前沒有可用的淨值資料"})]}),(0,a.jsx)(eH.Q,{open:f,onOpenChange:h,chartKey:p,chartTitle:"淨值成長"})]})}},"income-trend":{label:"每月收入趨勢圖",component:function({cardStyle:e="shadow",colorMode:t="standard",onRemove:r,onTogglePin:i,isVisible:l=!0,pinned:o=!1,showShareButton:d=!1}){let{rawData:c}
1=(0,s.P)(),u=(0,n.useRef)(null),[m,f]=(0,n.useState)(!1),[h,p]=(0,n.useState)(!1),g="incomeTrendChart";eB(u),(0,n.useEffect)(()=>{p(!0)},[]);let b=(0,n.useMemo)(()=>Array.isArray(c?.ledgerEntries)?c.ledgerEntries:[],[c?.ledgerEntries]),x=(0,n.useMemo)(()=>(0,eQ.$9)(12).slice().reverse(),[]),y=(0,n.useMemo)(()=>{let e=new Set;for(let t of x)for(let r of(0,eQ.lz)(b,t,"income").keys())e.add(r);return Array.from(e).map(e=>({type:"column",name:(0,eJ.F$)(e),data:x.map(t=>{let r=(0,eQ.lz)(b,t,"income").get(e)??0;return{y:r,custom:{formattedValue:(0,eC.C)(r)}}})}))},[b,x]),v=(0,n.useMemo)(()=>x.map(e=>(0,eQ.s$)(b,e,"income")),[x,b]);(0,n.useEffect)(()=>{let e,t=u.current;if(!t)return;let r=()=>{if(t&&t.container&&"function"==typeof t.reflow)try{t.reflow()}catch(e){console.warn("Chart reflow failed:",e)}},a=()=>{clearTimeout(e),e=setTimeout(r,150)};window.addEventListener("resize",a);let n=new ResizeObserver(a),i=t.container;return i&&n.observe(i.parentElement||i),()=>{window.removeEventListener("resize",a),n.disconnect(),clearTimeout(e)}},[]);let w=(0,n.useMemo)(()=>x.length&&y.length?{chart:{type:"column",backgroundColor:"transparent"},title:{text:null},xAxis:{categories:x},yAxis:{min:0,title:{text:"金額 (新台幣)"},labels:{format:"{value:,.0f}"}},tooltip:{shared:!0,useHTML:!0,headerFormat:"<b>{point.key}</b><br/>",pointFormat:'<span style="color:{point.color}">●</span> {series.name}: {point.custom.formattedValue}<br/>'},plotOptions:{column:{stacking:"normal"}},series:[...y,{type:"spline",name:"總收入",data:v.map(e=>({y:e,custom:{formattedValue:(0,eC.C)(e)}})),lineWidth:3,zIndex:2,marker:{enabled:!1}}],credits:{enabled:!1}}:null,[x,y,v]),j=y.length>0&&v.some(e=>e>0);return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(eo,{id:"income-trend",title:"每月收入趨勢圖",cardStyle:e,borderColor:"green-300",contentClassName:"flex h-full !p-0",headerActions:d?(0,a.jsx)(e$.S,{onClick:()=>f(!0),variant:"ghost",size:"icon"}):void 0,onRemove:r,onTogglePin:i,isVisible:l,pinned:o,children:j?(0,a.jsx)("div",{className:"w-full h-full min-h-0",children:h&&w?(0,a.jsx)(eO.A,{highcharts:eP.A,options:w,callback:e=>{if(!e)return;u.current=e;let t=()=>{if(!e.container)return void setTimeout(t,100);if(window[g]=e,e.getSVG||(e.getSVG=function(){try{let e=this.container||this.renderTo;if(e){let t=e instanceof HTMLElement?e:"string"==typeof e?document.querySelector(e):null;if(t){let e=t.querySelector("svg");if(e)return e.outerHTML}}throw Error("無法找到 SVG 元素")}catch(e){throw console.error(`[${g}] SVG 取得失敗:`,e),e}}),window[`${g}HasData`]=j,e&&e.container&&"function"==typeof e.reflow)try{e.reflow()}catch(e){console.warn("Chart reflow failed:",e)}};t()}}):(0,a.jsx)("div",{className:"flex h-full items-center justify-center text-sm text-muted-foreground",children:"圖表初始化中…"})}):(0,a.jsx)("div",{className:"flex flex-col items-center justify-center w-full h-full text-sm text-muted-foreground",children:"目前沒有足夠的收入紀錄可供繪製趨勢"})}),(0,a.jsx)(eH.Q,{open:m,onOpenChange:f,chartKey:g,chartTitle:"每月收入趨勢圖"})]})}},"income-pie":{label:"當月各類型收入占比",component:function({cardStyle:e="shadow",colorMode:t="standard",onRemove:r,onTogglePin:i,isVisible:l=!0,pinned:o=!1,showShareButton:d=!1}){let{rawData:c}=(0,s.P)(),u=eX(),m=(0,n.useRef)(null),[f,h]=(0,n.useState)(!1),[p,g]=(0,n.useState)(!1),b="incomePieChart";eB(m,{pieChart:!0}),(0,n.useEffect)(()=>{g(!0)},[]);let x=(0,n.useMemo)(()=>Array.isArray(c?.ledgerEntries)?c.ledgerEntries:[],[c?.ledgerEntries]),y=(0,n.useMemo)(()=>(0,eQ.$9)(1)[0]??"",[]);(0,n.useEffect)(()=>{let e,t=m.current;if(!t)return;let r=()=>{if(t&&t.container&&"function"==typeof t.reflow)try{t.reflow()}catch(e){console.warn("Chart reflow failed:",e)}},a=()=>{clearTimeout(e),e=setTimeout(r,150)};window.addEventListener("resize",a);let n=new ResizeObserver(a),i=t.container;return i&&n.observe(i.parentElement||i),()=>{window.removeEventListener("resize",a),n.disconnect(),clearTimeout(e)}},[]);let v=(0,n.useMemo)(()=>y?Array.from((0,eQ.lz)(x,y,"income").entries()).filter(([,e])=>e>0).map(([e,t])=>({name:(0,eJ.F$)(e),y:t})):[],[y,x]),w=(0,n.useMemo)(()=>
1{if(!y||!v.length)return null;let e=v.map(e=>({...e,custom:{formattedValue:(0,eC.C)(e.y??0)}}));return{chart:{type:"pie",backgroundColor:"transparent",marginBottom:48,style:{color:u.text}},title:{text:null},colors:[u.chart1,u.chart2,u.chart3,u.chart4,u.chart5],plotOptions:{pie:{innerSize:"60%",size:"85%",borderWidth:0,dataLabels:{enabled:!1}}},legend:{enabled:!0,verticalAlign:"bottom",align:"center",layout:"horizontal",itemStyle:{color:u.text,fontWeight:"500",fontSize:"12px"},itemHoverStyle:{color:u.mutedForeground},itemHiddenStyle:{color:u.mutedForeground},symbolRadius:0,symbolHeight:8,symbolWidth:12,itemDistance:16},tooltip:{enabled:!0,headerFormat:"<b>{point.name}</b><br/>",pointFormat:"{point.custom.formattedValue}<br/>占比:<b>{point.percentage:.1f}%</b>",backgroundColor:u.background,borderColor:u.border,style:{fontSize:"12px",fontWeight:"500",color:u.text}},series:[{type:"pie",name:"占比",showInLegend:!0,data:e}],credits:{enabled:!1}}},[y,v,u]),j=v.length>0;return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(eo,{id:"income-pie",title:"當月各類型收入占比",cardStyle:e,borderColor:"green-300",contentClassName:"flex h-full !p-0",headerActions:d?(0,a.jsx)(e$.S,{onClick:()=>h(!0),variant:"ghost",size:"icon"}):void 0,onRemove:r,onTogglePin:i,isVisible:l,pinned:o,children:j?(0,a.jsx)("div",{className:"w-full h-full min-h-0",children:p&&w?(0,a.jsx)(eO.A,{highcharts:eP.A,options:w,callback:e=>{if(!e)return;m.current=e;let t=()=>{if(!e.container)return void setTimeout(t,100);if(window[b]=e,e.getSVG||(e.getSVG=function(){try{let e=this.container||this.renderTo;if(e){let t=e instanceof HTMLElement?e:"string"==typeof e?document.querySelector(e):null;if(t){let e=t.querySelector("svg");if(e)return e.outerHTML}}throw Error("無法找到 SVG 元素")}catch(e){throw console.error(`[${b}] SVG 取得失敗:`,e),e}}),window[`${b}HasData`]=j,e&&e.container&&"function"==typeof e.reflow)try{e.reflow()}catch{}};t()}}):(0,a.jsx)("div",{className:"flex h-full items-center justify-center text-sm text-muted-foreground",children:"圖表初始化中…"})}):(0,a.jsx)("div",{className:"flex flex-col items-center justify-center w-full h-full text-sm text-muted-foreground",children:y?"該月份尚無收入資料":"尚無收入資料"})}),(0,a.jsx)(eH.Q,{open:f,onOpenChange:h,chartKey:b,chartTitle:"當月各類型收入占比"})]})}},"expense-trend":{label:"每月支出趨勢圖",component:function({cardStyle:e="shadow",colorMode:t="standard",onRemove:r,onTogglePin:i,isVisible:l=!0,pinned:o=!1,showShareButton:d=!1}){let{rawData:c}=(0,s.P)(),u=(0,n.useRef)(null),[m,f]=(0,n.useState)(!1),[h,p]=(0,n.useState)(!1),g="expenseTrendChart";eB(u),(0,n.useEffect)(()=>{p(!0)},[]);let b=(0,n.useMemo)(()=>Array.isArray(c?.ledgerEntries)?c.ledgerEntries:[],[c?.ledgerEntries]),x=(0,n.useMemo)(()=>(0,eQ.$9)(12).slice().reverse(),[]),y=(0,n.useMemo)(()=>{let e=new Set;for(let t of x)for(let r of(0,eQ.lz)(b,t,"expense").keys())e.add(r);return Array.from(e).map(e=>({type:"column",name:(0,eJ.F$)(e),data:x.map(t=>{let r=(0,eQ.lz)(b,t,"expense").get(e)??0;return{y:r,custom:{formattedValue:(0,eC.C)(r)}}})}))},[b,x]),v=(0,n.useMemo)(()=>x.map(e=>(0,eQ.s$)(b,e,"expense")),[x,b]);(0,n.useEffect)(()=>{let e,t=u.current;if(!t)return;let r=()=>{if(t&&t.container&&"function"==typeof t.reflow)try{t.reflow()}catch(e){console.warn("Chart reflow failed:",e)}},a=()=>{clearTimeout(e),e=setTimeout(r,150)};window.addEventListener("resize",a);let n=new ResizeObserver(a),i=t.container;return i&&n.observe(i.parentElement||i),()=>{window.removeEventListener("resize",a),n.disconnect(),clearTimeout(e)}},[]);let w=(0,n.useMemo)(()=>x.length&&y.length?{chart:{type:"column",backgroundColor:"transparent"},title:{text:null},xAxis:{categories:x},yAxis:{min:0,title:{text:"金額 (新台幣)"},labels:{format:"{value:,.0f}"}},tooltip:{shared:!0,useHTML:!0,headerFormat:"<b>{point.key}</b><br/>",pointFormat:'<span style="color:{point.color}">●</span> {series.name}: {point.custom.formattedValue}<br/>'},plotOptions:{column:{stacking:"normal"}},series:[...y,{type:"spline",name:"總支出",data:v.map(e=>({y:e,custom:{formattedValue:(0,eC.C)(e)}})),lineWidth:3,zIndex:2,marker:{enabled:!1}}],credits:{enabled:!1}}:null,[x,y,v]),j=y.length>0&&v.some(e=>e>0);return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(eo,{id:"expense-trend",title:"每月支出趨勢圖",cardStyle:e,borderColor:"red-300",contentClassName:"flex h-full !p-0",headerActions:d?(0,a.jsx)(e$.S,{onClick:()=>f(!0),variant:"ghost",size:"icon"}):void 0,onRemove:r,onTogglePin:i,isVisible:l,pinned:o,children:j?(0,a.jsx)("div",{className:"w-full h-full min-h-0",children:h&&w?(0,a.jsx)(eO.A,{highcharts:eP.A,options:w,callback:e=>{if(!e)return;u.current=e;let t=()=>{if(!e.container)return void setTimeout(t,100);if(window[g]=e,e.getSVG||(e.getSVG=function(){try{let e=this.container||this.renderTo;if(e){let t=e instanceof HTMLElement?e:"string"==typeof e?document.querySelector(e):null;if(t){let e=t.querySelector("svg");if(e)return e.outerHTML}}throw Error("無法找到 SVG 元素")}catch(e){throw console.error(`[${g}] SVG 取得失敗:`,e),e}}),window[`${g}HasData`]=j,e&&e.container&&"function"==typeof e.reflow)try{e.reflow()}catch(e){console.warn("Chart reflow failed:",e)}};t()}}):(0,a.jsx)("div",{className:"flex h-full items-center justify-center text-sm text-muted-foreground",children:"圖表初始化中…"})}):(0,a.jsx)("div",{className:"flex flex-col items-center justify-center w-full h-full text-sm text-muted-foreground",children:"目前沒有足夠的支出紀錄可供繪製趨勢"})}),(0,a.jsx)(eH.Q,{open:m,onOpenChange:f,chartKey:g,chartTitle:"每月支出趨勢圖"})]})}},"expense-pie":{label:"當月各類型支出占比",component:function({cardStyle:e="shadow",colorMode:t="standard",onRemove:r,onTogglePin:i,isVisible:l=!0,pinned:o=!1,showShareButton:d=!1}){let{rawData:c}
1=(0,s.P)(),u=eX(),m=(0,n.useRef)(null),[f,h]=(0,n.useState)(!1),[p,g]=(0,n.useState)(!1),b="expensePieChart";eB(m,{pieChart:!0}),(0,n.useEffect)(()=>{g(!0)},[]);let x=(0,n.useMemo)(()=>Array.isArray(c?.ledgerEntries)?c.ledgerEntries:[],[c?.ledgerEntries]),y=(0,n.useMemo)(()=>(0,eQ.$9)(1)[0]??"",[]);(0,n.useEffect)(()=>{let e,t=m.current;if(!t)return;let r=()=>{if(t&&t.container&&"function"==typeof t.reflow)try{t.reflow()}catch(e){console.warn("Chart reflow failed:",e)}},a=()=>{clearTimeout(e),e=setTimeout(r,150)};window.addEventListener("resize",a);let n=new ResizeObserver(a),i=t.container;return i&&n.observe(i.parentElement||i),()=>{window.removeEventListener("resize",a),n.disconnect(),clearTimeout(e)}},[]);let v=(0,n.useMemo)(()=>y?Array.from((0,eQ.lz)(x,y,"expense").entries()).filter(([,e])=>e>0).map(([e,t])=>({name:(0,eJ.F$)(e),y:t})):[],[y,x]),w=(0,n.useMemo)(()=>{if(!y||!v.length)return null;let e=v.map(e=>({...e,custom:{formattedValue:(0,eC.C)(e.y??0)}}));return{chart:{type:"pie",backgroundColor:"transparent",marginBottom:48,style:{color:u.text}},title:{text:null},colors:[u.chart1,u.chart2,u.chart3,u.chart4,u.chart5],plotOptions:{pie:{innerSize:"60%",size:"85%",borderWidth:0,dataLabels:{enabled:!1}}},legend:{enabled:!0,verticalAlign:"bottom",align:"center",layout:"horizontal",itemStyle:{color:u.text,fontWeight:"500",fontSize:"12px"},itemHoverStyle:{color:u.mutedForeground},itemHiddenStyle:{color:u.mutedForeground},symbolRadius:0,symbolHeight:8,symbolWidth:12,itemDistance:16},tooltip:{enabled:!0,headerFormat:"<b>{point.name}</b><br/>",pointFormat:"{point.custom.formattedValue}<br/>占比:<b>{point.percentage:.1f}%</b>",backgroundColor:u.background,borderColor:u.border,style:{fontSize:"12px",fontWeight:"500",color:u.text}},series:[{type:"pie",name:"占比",showInLegend:!0,data:e}],credits:{enabled:!1}}},[y,v,u]),j=v.length>0;return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(eo,{id:"expense-pie",title:"當月各類型支出占比",cardStyle:e,borderColor:"red-300",contentClassName:"flex h-full !p-0",headerActions:d?(0,a.jsx)(e$.S,{onClick:()=>h(!0),variant:"ghost",size:"icon"}):void 0,onRemove:r,onTogglePin:i,isVisible:l,pinned:o,children:j?(0,a.jsx)("div",{className:"w-full h-full min-h-0",children:p&&w?(0,a.jsx)(eO.A,{highcharts:eP.A,options:w,callback:e=>{if(!e)return;m.current=e;let t=()=>{if(!e.container)return void setTimeout(t,100);if(window[b]=e,e.getSVG||(e.getSVG=function(){try{let e=this.container||this.renderTo;if(e){let t=e instanceof HTMLElement?e:"string"==typeof e?document.querySelector(e):null;if(t){let e=t.querySelector("svg");if(e)return e.outerHTML}}throw Error("無法找到 SVG 元素")}catch(e){throw console.error(`[${b}] SVG 取得失敗:`,e),e}}),window[`${b}HasData`]=j,e&&e.container&&"function"==typeof e.reflow)try{e.reflow()}catch{}};t()}}):(0,a.jsx)("div",{className:"flex h-full items-center justify-center text-sm text-muted-foreground",children:"圖表初始化中…"})}):(0,a.jsx)("div",{className:"flex flex-col items-center justify-center w-full h-full text-sm text-muted-foreground",children:y?"該月份尚無支出資料":"尚無支出資料"})}),(0,a.jsx)(eH.Q,{open:f,onOpenChange:h,chartKey:b,chartTitle:"當月各類型支出占比"})]})}},"asset-distribution":{label:"資產分布圖",component:function({cardStyle:e="shadow",colorMode:t="standard",onRemove:r,onTogglePin:i,isVisible:l=!0,pinned:o=!1,showShareButton:s=!1}){let{user:c,viewingUserId:u}=(0,d.A)(),m=u||c?.uid,{assets:f}=(0,e0.d)(m),{accounts:h,monthlyBalances:p}=(0,e1.x)(m),{investments:g}
1=(0,e2.sC)(m),b=eX(),x=(0,n.useRef)(null),[y,v]=(0,n.useState)(!1),[w,j]=(0,n.useState)(!1),S="assetDistributionChart";eB(x,{pieChart:!0}),(0,n.useEffect)(()=>{j(!0)},[]),(0,n.useEffect)(()=>{let e,t=x.current;if(!t)return;let r=()=>{if(t?.container&&"function"==typeof t.reflow)try{t.reflow()}catch{}},a=()=>{clearTimeout(e),e=setTimeout(r,150)};window.addEventListener("resize",a);let n=new ResizeObserver(a),i=t.container;return i&&n.observe(i.parentElement||i),()=>{window.removeEventListener("resize",a),n.disconnect(),clearTimeout(e)}},[]);let N=(0,n.useMemo)(()=>f||[],[f]),C=(0,n.useMemo)(()=>Array.isArray(g)?g:[],[g]),k=(0,n.useMemo)(()=>h&&0!==h.length&&p&&0!==p.length?(0,e5.A1)(h,p):0,[h,p]),{otherAssets:A}=(0,n.useMemo)(()=>({otherAssets:N.filter(e=>"cash"!==e.type)}),[N]),T=(0,n.useCallback)(e=>{if(["stocks","bonds","funds"].includes(e.type)){let t=C.find(t=>t.accountId===e.accountId&&t.symbol===e.name);if(t)return(t.quantity||0)*(t.price||0)}return e.value||0},[C]),E=(0,n.useMemo)(()=>{let e=new Map;return e.set("cash",k),A.forEach(t=>{let r=t.type,a=(0,eK.A7)(T(t),t.currency);e.set(r,(e.get(r)||0)+a)}),e},[k,A,T]),I=(0,n.useMemo)(()=>{let e=e4.reduce((e,t)=>(e[t.value]=t.label,e),{});return Array.from(E.entries()).filter(([,e])=>e>0).map(([t,r])=>({name:e[t]||t,y:r}))},[E]);(0,n.useEffect)(()=>{let e,t=x.current;if(!t)return;let r=()=>{if(t&&t.container&&"function"==typeof t.reflow)try{t.reflow()}catch(e){console.warn("Chart reflow failed:",e)}},a=()=>{clearTimeout(e),e=setTimeout(r,150)};window.addEventListener("resize",a);let n=new ResizeObserver(a),i=t.container;return i&&n.observe(i.parentElement||i),()=>{window.removeEventListener("resize",a),n.disconnect(),clearTimeout(e)}},[]);let R=(0,n.useMemo)(()=>{if(!I.length)return null;let e=I.map(e=>({...e,custom:{...e.custom??{},formattedValue:(0,eC.C)(e?.y??0)}}));return{chart:{type:"pie",backgroundColor:"transparent",marginBottom:48,style:{color:b.text}},title:{text:null},colors:[b.chart1,b.chart2,b.chart3,b.chart4,b.chart5],plotOptions:{pie:{innerSize:"60%",size:"85%",borderWidth:0,dataLabels:{enabled:!1}}},legend:{enabled:!0,verticalAlign:"bottom",align:"center",layout:"horizontal",itemStyle:{color:b.text,fontWeight:"500",fontSize:"12px"},itemHoverStyle:{color:b.mutedForeground},itemHiddenStyle:{color:b.mutedForeground},symbolRadius:0,symbolHeight:8,symbolWidth:12,itemDistance:16},tooltip:{enabled:!0,headerFormat:"<b>{point.name}</b><br/>",pointFormat:"{point.custom.formattedValue}<br/>占比:<b>{point.percentage:.1f}%</b>",backgroundColor:b.background,borderColor:b.border,style:{fontSize:"12px",fontWeight:"500",color:b.text}},series:[{type:"pie",name:"資產分布",showInLegend:!0,data:e}],credits:{enabled:!1}}},[I,b]),M=I.length>0;return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(eo,{id:"asset-distribution",title:"資產分布圖",cardStyle:e,borderColor:"blue-300",contentClassName:"flex h-full !p-0",headerActions:s?(0,a.jsx)(e$.S,{onClick:()=>v(!0),variant:"ghost",size:"icon"}):void 0,onRemove:r,onTogglePin:i,isVisible:l,pinned:o,children:M?(0,a.jsx)("div",{className:"w-full h-full min-h-0","data-chart":S,children:w&&R?(0,a.jsx)(eO.A,{highcharts:eP.A,options:R,callback:e=>{if(!e)return;x.current=e;let t=()=>{if(!e.container)return void setTimeout(t,100);if(window[S]=e,e.getSVG||(e.getSVG=function(){try{let e=this.container||this.renderTo;if(e){let t=e instanceof HTMLElement?e:"string"==typeof e?document.querySelector(e):null;if(t){let e=t.querySelector("svg");if(e)return e.outerHTML}}throw Error("無法找到 SVG 元素")}catch(e){throw console.error(`[${S}] SVG 取得失敗:`,e),e}}),window[`${S}HasData`]=M,e&&e.container&&"function"==typeof e.reflow)try{e.reflow()}catch{}};t()}}):(0,a.jsx)("div",{className:"flex h-full items-center justify-center text-sm text-muted-foreground",children:"圖表初始化中…"})}):(0,a.jsx)("div",{className:"flex flex-col items-center justify-center w-full h-full text-sm text-muted-foreground",children:"目前沒有資產資料可供繪製分布圖"})}),(0,a.jsx)(eH.Q,{open:y,onOpenChange:v,chartKey:S,chartTitle:"資產分布圖"})]})}},"liability-distribution":{label:"負債分布圖",component:function e({cardStyle:t="shadow",colorMode:r="standard",onRemove:i,onTogglePin:l,isVisible:o=!0,pinned:s=!1,showShareButton:c=!1}){let{user:u,viewingUserId:m}=(0,d.A)(),{isViewMode:f}=(0,e3.a)(),h=m||u?.uid,{liabilities:p,updateLiability:g}=(0,e0.d)(h),b=(0,n.useMemo)(()=>
1p||[],[p]),x=eX(),y=(0,n.useRef)(null),[v,w]=(0,n.useState)(!1),[j,S]=(0,n.useState)(!1),N="liabilityDistributionChart";eB(y,{pieChart:!0}),(0,n.useEffect)(()=>{S(!0)},[]),(0,n.useEffect)(()=>{let e,t=y.current;if(!t)return;let r=()=>{if(t?.container&&"function"==typeof t.reflow)try{t.reflow()}catch{}},a=()=>{clearTimeout(e),e=setTimeout(r,150)};window.addEventListener("resize",a);let n=new ResizeObserver(a),i=t.container;return i&&n.observe(i.parentElement||i),()=>{window.removeEventListener("resize",a),n.disconnect(),clearTimeout(e)}},[]);let C=(0,n.useMemo)(()=>b.map(e=>[e.id,e.value,e.annualRate??"",e.minimumPayment??"",e.startDate??"",e.autoDeductedThrough??""].join(":")).join("|"),[b]),k=(0,n.useRef)("");(0,n.useEffect)(()=>{if(f||!u?.uid||!h||h!==u.uid||C===k.current||!b||0===b.length)return;k.current=C;let e=new Date;e.setHours(0,0,0,0);let t=b.filter(e=>{let t=Number(e.value)||0,r=e.annualRate,a=e.minimumPayment,n=e.startDate;return t>0&&null!=r&&""!==r&&Number.isFinite(Number(r))&&null!=a&&Number(a)>0&&!!n});(async()=>{let r=t.map(async t=>{let r=function(e){var t;let r,a,n=e.asOf?new Date(e.asOf):new Date;n.setHours(0,0,0,0);let i="number"==typeof e.maxMonths&&e.maxMonths>0?e.maxMonths:1200,l=Number(e.balance),o=Number(e.annualRate),s=Number(e.monthlyPayment);if(!Number.isFinite(l)||l<=0)return{newBalance:Math.max(0,Number.isFinite(l)?l:0),newAutoDeductedThrough:e.autoDeductedThrough,monthsApplied:0};if(!Number.isFinite(o)||o<0||!Number.isFinite(s)||s<=0)return{newBalance:l,newAutoDeductedThrough:e.autoDeductedThrough,monthsApplied:0};let d=function(e){if(!e)return null;let t=/^(\d{4})-(\d{2})-(\d{2})/.exec(e);if(t){let e=new Date(Number(t[1]),Number(t[2])-1,Number(t[3]));return e.setHours(0,0,0,0),Number.isNaN(e.getTime())?null:e}let r=new Date(e);return Number.isNaN(r.getTime())?null:(r.setHours(0,0,0,0),r)}(e.startDateIso);if(!d)return{newBalance:l,newAutoDeductedThrough:e.autoDeductedThrough,monthsApplied:0};let c=d.getDate(),u={year:d.getFullYear(),monthIndex0:d.getMonth()},m={year:n.getFullYear(),monthIndex0:n.getMonth()},f=(e.autoDeductedThrough?function(e){let t=/^(\d{4})-(\d{2})$/.exec(e);if(!t)return null;let r=Number(t[1]),a=Number(t[2]);return!Number.isFinite(r)||!Number.isFinite(a)||a<1||a>12?null:{year:r,monthIndex0:a-1}}(e.autoDeductedThrough):null)??e8(u,-1),h=e8(f,1),p=0,g=l,b=o/100/12;for(0>e9(h,u)&&(h={...u});0>=e9(h,m)&&p<i&&(r=Math.min(Math.max(1,c),new Date((t=h).year,t.monthIndex0+1,0).getDate()),(a=new Date(t.year,t.monthIndex0,r)).setHours(0,0,0,0),!(a>n));){let e=g*b;if((g=g+e-s)<=0&&(g=0),p++,f.year=h.year,f.monthIndex0=h.monthIndex0,g<=0){h=e8(h,1);break}h=e8(h,1)}return{newBalance:Math.round(100*g)/100,newAutoDeductedThrough:p>0?`${f.year}-${String(f.monthIndex0+1).padStart(2,"0")}`:e.autoDeductedThrough,monthsApplied:p}}({balance:Number(t.value)||0,annualRate:Number(t.annualRate)||0,monthlyPayment:Number(t.minimumPayment)||0,startDateIso:String(t.startDate),autoDeductedThrough:t.autoDeductedThrough,asOf:e});if(r.monthsApplied<=0)return;let a={value:r.newBalance};r.newAutoDeductedThrough&&(a.autoDeductedThrough=r.newAutoDeductedThrough),await g(t.id,a)});await Promise.allSettled(r)})()},[C,f,u?.uid,h,b,g]);let A=(0,n.useMemo)(()=>{let e=new Map;return b.forEach(t=>{let r=String(t.type||"other-liability");e7[r];let a=(0,eK.A7)(Number(t.value||0),t.currency||"twd");a<=0||e.set(r,(e.get(r)||0)+a)}),Array.from(e.entries()).map(([e,t])=>{let r=e7[e]??{label:e,color:"#6b7280"};return{name:r.label,y:t,color:r.color}})},[b]);(0,n.useEffect)(()=>{let e,t=y.current;if(!t)return;let r=()=>{if(t&&t.container&&"function"==typeof t.reflow)try{t.reflow()}catch{}},a=()=>{clearTimeout(e),e=setTimeout(r,150)};window.addEventListener("resize",a);let n=new ResizeObserver(a),i=t.container;return i&&n.observe(i.parentElement||i),()=>{window.removeEventListener("resize",a),n.disconnect(),clearTimeout(e)}},[]);let T=(0,n.useMemo)(()=>{if(!A.length)return null;let e=A.map(e=>({...e,custom:{...e.custom??{},formattedValue:(0,eC.C)(e?.y??0)}}));return{chart:{type:"pie",backgroundColor:"transparent",marginBottom:48,style:{color:x.text}},title:{text:null},plotOptions:{pie:{innerSize:"60%",size:"85%",borderWidth:0,dataLabels:{enabled:!1}}},tooltip:{enabled:!0,headerFormat:"<b>{point.name}</b><br/>",pointFormat:"{point.custom.formattedValue}<br/>占比:<b>{point.percentage:.1f}%</b>",backgroundColor:x.background,borderColor:x.border,style:{fontSize:"12px",fontWeight:"500",color:x.text}},series:[{type:"pie",name:"負債分布",showInLegend:!0,data:e}],legend:{enabled:!0,verticalAlign:"bottom",align:"center",layout:"horizontal",itemStyle:{color:x.text,fontWeight:"500",fontSize:"12px"},itemHoverStyle:{color:x.mutedForeground},itemHiddenStyle:{color:x.mutedForeground}
1,symbolRadius:0,symbolHeight:8,symbolWidth:12,itemDistance:16},credits:{enabled:!1}}},[A,x]),E=A.length>0;return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(eo,{id:"liability-distribution",title:"負債分布圖",cardStyle:t,borderColor:"violet-300",contentClassName:"flex h-full !p-0",headerActions:c?(0,a.jsx)(e$.S,{onClick:()=>w(!0),variant:"ghost",size:"icon"}):void 0,onRemove:i,onTogglePin:l,isVisible:o,pinned:s,children:E?(0,a.jsx)(e6.N,{className:"h-full min-h-0 w-full",renderFullscreenContent:()=>(0,a.jsx)(e,{cardStyle:t,colorMode:r,onRemove:i,onTogglePin:l,isVisible:o,pinned:s}),children:(0,a.jsx)("div",{className:"w-full h-full min-h-0","data-chart":N,children:j&&T?(0,a.jsx)(eO.A,{highcharts:eP.A,options:T,callback:e=>{if(!e)return;y.current=e,window[N]=e;let t=()=>{if(!e.container)return void setTimeout(t,100);if(e&&e.container&&"function"==typeof e.reflow)try{e.reflow()}catch{}};t()}}):(0,a.jsx)("div",{className:"flex items-center justify-center w-full h-full text-sm text-muted-foreground",children:"載入圖表中..."})})}):(0,a.jsx)("div",{className:"flex flex-col items-center justify-center w-full h-full text-sm text-muted-foreground",children:"目前沒有負債資料可供繪製分布圖"})}),(0,a.jsx)(eH.Q,{open:v,onOpenChange:w,chartKey:N,chartTitle:"負債分布圖"})]})}},"investment-accounts":{label:"投資各別帳戶",component:function({cardStyle:e="shadow",colorMode:t="standard",onRemove:r,onTogglePin:i,isVisible:l=!0,pinned:o=!1,showShareButton:s=!1}){let{user:c,viewingUserId:u}=(0,d.A)(),m=u||c?.uid,{investments:f}=(0,e2.sC)(m),{accounts:h}=(0,e1.x)(m),p=eX(),g=(0,n.useRef)(null),[b,x]=(0,n.useState)(!1),[y,v]=(0,n.use
1State)(!1),w="investmentAccountsChart";eB(g),(0,n.useEffect)(()=>{v(!0)},[]);let j=(0,te.bm)(f||[],h||[]);(0,n.useEffect)(()=>{let e,t=g.current;if(!t)return;let r=()=>{if(t&&t.container&&"function"==typeof t.reflow)try{t.reflow()}catch(e){console.warn("Chart reflow failed:",e)}},a=()=>{clearTimeout(e),e=setTimeout(r,150)};window.addEventListener("resize",a);let n=new ResizeObserver(a),i=t.container;return i&&n.observe(i.parentElement||i),()=>{window.removeEventListener("resize",a),n.disconnect(),clearTimeout(e)}},[]);let S=(0,n.useMemo)(()=>{if(!j.length)return null;let e=j.map(e=>({...e,custom:{...e.custom??{},formattedValue:(0,eC.C)(e?.y??0)}}));return{chart:{type:"pie",backgroundColor:"transparent",marginBottom:48,style:{color:p.text}},title:{text:null},colors:[p.chart1,p.chart2,p.chart3,p.chart4,p.chart5],plotOptions:{pie:{innerSize:"60%",size:"85%",borderWidth:0,dataLabels:{enabled:!1}}},legend:{enabled:!0,verticalAlign:"bottom",align:"center",layout:"horizontal",itemStyle:{color:p.text,fontWeight:"500",fontSize:"12px"},itemHoverStyle:{color:p.mutedForeground},itemHiddenStyle:{color:p.mutedForeground},symbolRadius:0,symbolHeight:8,symbolWidth:12,itemDistance:16},series:[{type:"pie",name:"帳戶占比",showInLegend:!0,data:e}],tooltip:{enabled:!0,headerFormat:"<b>{point.name}</b><br/>",pointFormat:"{point.custom.formattedValue}<br/>占比:<b>{point.percentage:.1f}%</b>",backgroundColor:p.background,borderColor:p.border,style:{fontSize:"12px",fontWeight:"500",color:p.text}},credits:{enabled:!1}}},[j,p]),N=j.length>0;return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(eo,{id:"investment-accounts",title:"投資各別帳戶",cardStyle:e,borderColor:"purple-300",contentClassName:"flex h-full !p-0",headerActions:s?(0,a.jsx)(e$.S,{onClick:()=>x(!0),variant:"ghost",size:"icon"}):void 0,onRemove:r,onTogglePin:i,isVisible:l,pinned:o,children:N?(0,a.jsx)("div",{className:"w-full h-full min-h-0",children:y&&S?(0,a.jsx)(eO.A,{highcharts:eP.A,options:S,callback:e=>{if(!e)return;g.current=e;let t=()=>{if(!e.container)return void setTimeout(t,100);if(window[w]=e,e.getSVG||(e.getSVG=function(){try{let e=this.container||this.renderTo;if(e){let t=e instanceof HTMLElement?e:"string"==typeof e?document.querySelector(e):null;if(t){let e=t.querySelector("svg");if(e)return e.outerHTML}}throw Error("無法找到 SVG 元素")}catch(e){throw console.error(`[${w}] SVG 取得失敗:`,e),e}}),window[`${w}HasData`]=N,e&&e.container&&"function"==typeof e.reflow)try{e.reflow()}catch(e){console.warn("Chart reflow failed:",e)}};t()}}):(0,a.jsx)("div",{className:"flex h-full items-center justify-center text-sm text-muted-foreground",children:"圖表初始化中…"})}):(0,a.jsx)("div",{className:"flex flex-col items-center justify-center w-full h-full text-sm text-muted-foreground",children:"目前沒有投資帳戶資料可供繪製圖表"})}),(0,a.jsx)(eH.Q,{open:b,onOpenChange:x,chartKey:w,chartTitle:"投資各別帳戶"})]})}},"investment-assets":{label:"投資資產占比",component:function({cardStyle:e="shadow",colorMode:t="standard",onRemove:r,onTogglePin:i,isVisible:l=!0,pinned:o=!1,showShareButton:s=!1}){let{user:c,viewingUserId:u}=(0,d.A)(),m=u||c?.uid,{investments:f}=(0,e2.sC)(m),h=eX(),p=(0,n.useRef)(null),[g,b]=(0,n.useState)(!1),[x,y]=(0,n.useState)(!1),v="investmentAssetsChart";eB(p,{pieChart:!0}),(0,n.useEffect)(()=>{y(!0)},[]);let w=(0,te._m)(f||[]);(0,n.useEffect)(()=>{let e,t=p.current;if(!t)return;let r=()=>{if(t&&t.container&&"function"==typeof t.reflow)try{t.reflow()}catch(e){console.warn("Chart reflow failed:",e)}},a=()=>{clearTimeout(e),e=setTimeout(r,150)};window.addEventListener("resize",a);let n=new ResizeObserver(a),i=t.container;return i&&n.observe(i.parentElement||i),()=>{window.removeEventListener("resize",a),n.disconnect(),clearTimeout(e)}},[]);let j=(0,n.useMemo)(()=>{if(!w.length)return null;let e=w.map(e=>({...e,custom:{...e.custom??{},formattedValue:(0,eC.C)(e?.y??0)}}));return{chart:{type:"pie",backgroundColor:"transparent",marginBottom:48,style:{color:h.text}},title:{text:null},colors:[h.chart1,h.chart2,h.chart3,h.chart4,h.chart5],plotOptions:{pie:{innerSize:"60%",size:"85%",borderWidth:0,dataLabels:{enabled:!1}}},legend:{enabled:!0,verticalAlign:"bottom",align:"center",layout:"horizontal",itemStyle:{color:h.text,fontWeight:"500",fontSize:"12px"},itemHoverStyle:{color:h.mutedForeground},itemHiddenStyle:{color:h.mutedForeground}
1,symbolRadius:0,symbolHeight:8,symbolWidth:12,itemDistance:16},series:[{type:"pie",name:"資產分配",showInLegend:!0,data:e}],tooltip:{enabled:!0,headerFormat:"<b>{point.name}</b><br/>",pointFormat:"{point.custom.formattedValue}<br/>占比:<b>{point.percentage:.1f}%</b>",backgroundColor:h.background,borderColor:h.border,style:{fontSize:"12px",fontWeight:"500",color:h.text}},credits:{enabled:!1}}},[w,h]),S=w.length>0;return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(eo,{id:"investment-assets",title:"投資資產占比",cardStyle:e,borderColor:"purple-300",contentClassName:"flex h-full !p-0",headerActions:s?(0,a.jsx)(e$.S,{onClick:()=>b(!0),variant:"ghost",size:"icon"}):void 0,onRemove:r,onTogglePin:i,isVisible:l,pinned:o,children:S?(0,a.jsx)("div",{className:"w-full h-full min-h-0",children:x&&j?(0,a.jsx)(eO.A,{highcharts:eP.A,options:j,callback:e=>{if(!e)return;p.current=e;let t=()=>{if(!e.container)return void setTimeout(t,100);if(window[v]=e,e.getSVG||(e.getSVG=function(){try{let e=this.container||this.renderTo;if(e){let t=e instanceof HTMLElement?e:"string"==typeof e?document.querySelector(e):null;if(t){let e=t.querySelector("svg");if(e)return e.outerHTML}}throw Error("無法找到 SVG 元素")}catch(e){throw console.error(`[${v}] SVG 取得失敗:`,e),e}}),window[`${v}HasData`]=S,e&&e.container&&"function"==typeof e.reflow)try{e.reflow()}catch(e){console.warn("Chart reflow failed:",e)}};t()}}):(0,a.jsx)("div",{className:"flex h-full items-center justify-center text-sm text-muted-foreground",children:"圖表初始化中…"})}):(0,a.jsx)("div",{className:"flex flex-col items-center justify-center w-full h-full text-sm text-muted-foreground",children:"目前沒有投資資產資料可供繪製圖表"})}),(0,a.jsx)(eH.Q,{open:g,onOpenChange:b,chartKey:v,chartTitle:"投資資產占比"})]})}},"investment-industry":{label:"股票產業別分布",component:function({cardStyle:e="shadow",colorMode:t="standard",onRemove:r,onTogglePin:i,isVisible:l=!0,pinned:o=!1,showShareButton:s=!1}){let{user:c,viewingUserId:u}=(0,d.A)(),m=u||c?.uid,{investments:f}=(0,e2.sC)(m),h=eX(),p=(0,n.useRef)(null),[g,b]=(0,n.useState)(!1),[x,y]=(0,n.useState)(!1),v="investmentIndustryChart";eB(p,{pieChart:!0}),(0,n.useEffect)(()=>{y(!0)},[]);let{industryMap:w}=(0,e2.Ub)(f||[]),j=(0,e2.iY)(f||[],w);(0,n.useEffect)(()=>{let e,t=p.current;if(!t)return;let r=()=>{if(t&&t.container&&"function"==typeof t.reflow)try{t.reflow()}catch(e){console.warn("Chart reflow failed:",e)}},a=()=>{clearTimeout(e),e=setTimeout(r,150)};window.addEventListener("resize",a);let n=new ResizeObserver(a),i=t.container;return i&&n.observe(i.parentElement||i),()=>{window.removeEventListener("resize",a),n.disconnect(),clearTimeout(e)}},[]);let S=(0,n.useMemo)(()=>{if(!j.length)return null;let e=j.map(e=>({...e,custom:{...e.custom??{},formattedValue:(0,eC.C)(e?.y??0)}}));return{chart:{type:"pie",backgroundColor:"transparent",marginBottom:48,style:{color:h.text}},title:{text:null},colors:[h.chart1,h.chart2,h.chart3,h.chart4,h.chart5],plotOptions:{pie:{innerSize:"60%",size:"85%",borderWidth:0,dataLabels:{enabled:!1}}},legend:{enabled:!0,verticalAlign:"bottom",align:"center",layout:"horizontal",itemStyle:{color:h.text},itemHoverStyle:{color:h.text,fontWeight:"500"},symbolRadius:0,symbolHeight:8,symbolWidth:12,itemDistance:16},series:[{type:"pie",name:"股票產業別",showInLegend:!0,data:e}],tooltip:{enabled:!0,headerFormat:"<b>{point.name}</b><br/>",pointFormat:"{point.custom.formattedValue}<br/>占比:<b>{point.percentage:.1f}%</b>",backgroundColor:h.background,borderColor:h.border,style:{fontSize:"12px",fontWeight:"500",color:h.text}},credits:{enabled:!1}}},[j,h]),N=j.length>0;return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(eo,{id:"investment-industry",title:"股票產業別分布",cardStyle:e,borderColor:"purple-300",contentClassName:"flex h-full !p-0",headerActions:s?(0,a.jsx)(e$.S,{onClick:()=>b(!0),variant:"ghost",size:"icon"}):void 0,onRemove:r,onTogglePin:i,isVisible:l,pinned:o,children:N?(0,a.jsx)("div",{className:"w-full h-full min-h-0",children:x&&S?(0,a.jsx)(eO.A,{highcharts:eP.A,options:S,callback:e=>{if(!e)return;p.current=e;let t=()=>{if(!e.container)return void setTimeout(t,100);if(window[v]=e,e.getSVG||(e.getSVG=function(){try{let e=this.container||this.renderTo;if(e){let t=e instanceof HTMLElement?e:"string"==typeof e?document.querySelector(e):null;if(t){let e=t.querySelector("svg");if(e)return e.outerHTML}}throw Error("無法找到 SVG 元素")}catch(e){throw console.error(`[${v}
1] SVG 取得失敗:`,e),e}}),window[`${v}HasData`]=N,e&&e.container&&"function"==typeof e.reflow)try{e.reflow()}catch(e){console.warn("Chart reflow failed:",e)}};t()}}):(0,a.jsx)("div",{className:"flex h-full items-center justify-center text-sm text-muted-foreground",children:"圖表初始化中…"})}):(0,a.jsx)("div",{className:"flex flex-col items-center justify-center w-full h-full text-sm text-muted-foreground",children:"目前沒有股票產業別資料可供繪製圖表"})}),(0,a.jsx)(eH.Q,{open:g,onOpenChange:b,chartKey:v,chartTitle:"股票產業別分布"})]})}},"insurance-medical":{label:"醫療險保額分佈",component:function({cardStyle:e="shadow",colorMode:t="standard",onRemove:r,onTogglePin:i,isVisible:l=!0,pinned:o=!1,showShareButton:s=!1}){let{user:c,viewingUserId:u}=(0,d.A)(),m=u||c?.uid,[f,h]=(0,n.useState)(!1),p="insuranceMedicalChart";return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(eo,{id:"insurance-medical",title:"醫療險保額分佈",cardStyle:e,borderColor:"yellow-300",contentClassName:"flex h-full flex-col !p-0",headerActions:s?(0,a.jsx)(e$.S,{onClick:()=>h(!0),variant:"ghost",size:"icon"}):void 0,onRemove:r,onTogglePin:i,isVisible:l,pinned:o,children:(0,a.jsx)("div",{className:"flex h-full min-h-0 flex-1 flex-col overflow-hidden",children:(0,a.jsx)(ts,{userId:m,chartKey:p})})}),(0,a.jsx)(eH.Q,{open:f,onOpenChange:h,chartKey:p,chartTitle:"醫療險保額分佈"})]})}},"insurance-life":{label:"壽險保額分佈",component:function({cardStyle:e="shadow",colorMode:t="standard",onRemove:r,onTogglePin:i,isVisible:l=!0,pinned:o=!1,showShareButton:s=!1}){let{user:c,viewingUserId:u}=(0,d.A)(),m=u||c?.uid,[f,h]=(0,n.useState)(!1),p="insuranceLifeChart";return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(eo,{id:"insurance-life",title:"壽險保額分佈",cardStyle:e,borderColor:"yellow-300",contentClassName:"flex h-full flex-col !p-0",headerActions:s?(0,a.jsx)(e$.S,{onClick:()=>h(!0),variant:"ghost",size:"icon"}):void 0,onRemove:r,onTogglePin:i,isVisible:l,pinned:o,children:(0,a.jsx)("div",{className:"flex h-full min-h-0 flex-1 flex-col overflow-hidden",children:(0,a.jsx)(tu,{userId:m,chartKey:p})})}),(0,a.jsx)(eH.Q,{open:f,onOpenChange:h,chartKey:p,chartTitle:"壽險保額分佈"})]})}},"insurance-coverage-gap":{label:"保額缺口分析",component:function({cardStyle:e="shadow",colorMode:t="standard",onRemove:i,onTogglePin:l,isVisible:o=!0,pinned:s=!1,showShareButton:c=!1}){let{user:u,viewingUserId:m}=(0,d.A)(),f=m||u?.uid,{resolvedTheme:h}=(0,eZ.D)(),p="dark"===h,g=eX(),{policies:b}=(0,tt.I5)(f),{recommendations:x}=(0,tr.Q)(f),{productRulesByProductId:y,benefitItemsByProductId:v}=(0,ti.j)(b),[w,j]=(0,n.useState)(!1),[S,N]=(0,n.useState)(!1),C=(0,n.useRef)(null),k=(0,n.useRef)(null),A="insuranceCoverageGapChart";eB(C,{pieChart:!0}),(0,n.useEffect)(()=>{if("object"==typeof eP.A)try{let e=r(4442);e&&"function"==typeof e?e(eP.A):e.default&&"function"==typeof e.default&&e.default(eP.A);let t=r(46944);t&&"function"==typeof t?t(eP.A):t.default&&"function"==typeof t.default&&t.default(eP.A)}catch(e){}},[]);let{items:T,uncategorizedMedicalCount:E}=(0,n.useMemo)(()=>(0,tn.Rs)(b,x,y,v),[b,x,y,v]),I=(0,n.useMemo)(()=>0===T.length?null:T.map(e=>({name:e.name,ratio:e.ratioPercent,current:e.current,target:e.target,gaugeMax:e.gaugeMax,fillValue:e.fillValue,noRecommendationTarget:e.noRecommendationTarget,supplementBlock:null!=e.tooltipSupplement&&""!==e.tooltipSupplement?`<br/><span style="font-size:11px;line-height:1.35;color:${g.mutedForeground}">${e.tooltipSupplement.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}</span>`:""})),[T,g]),R=(0,n.useMemo)(()=>{if(!I||0===I.length)return null;let e=I.length,t=100/e,r=Array.from({length:e},(e,r)=>{let a=100-r*t,n=Math.max(a-.88*t,.25);return{outerRadius:`${a}%`,innerRadius:`${n}%`}}),a=r.map(()=>p?"rgba(255, 255, 255, 0.12)":"rgba(15, 23, 42, 0.08)"),n=r.map((e,t)=>({outerRadius:e.outerRadius,innerRadius:e.innerRadius,backgroundColor:a[t],borderWidth:0,shape:"arc"})),i=I.map((e,t)=>({min:0,max:e.gaugeMax>0?e.gaugeMax:1,lineWidth:0,tickPositions:[],pane:t})),l=I.map((e,t)=>({center:["50%","50%"],size:"100%",startAngle:0,endAngle:360,background:[n[t]]})),o=I.map((e,t)=>{let a=tm[t%tm.length],n=r[t],i=e.fillValue,l=e.ratio;return{name:e.name,data:[{color:a,radius:n.outerRadius,innerRadius:n.innerRadius,y:i,name:e.name,custom:{formattedValue:(0,eC.C)(e.current),formattedTarget:e.noRecommendationTarget?"—(尚未設定建議保額)":(0,eC.C)(e.target),ratio:l,ratioNote:e.noRecommendationTarget?"(尚無建議目標,僅顯示既有保額)":"",supplementBlock:e.supplementBlock??""}}],type:"solidgauge",pane:t,yAxis:t}});return{chart:{type:"solidgauge",backgroundColor:"transparent",reflow:!0,spacingTop:20,spacingBottom:20,spacingLeft:20,spacingRight:20},title:{text:""},tooltip:{backgroundColor:g.background,borderColor:g.border,fixed:!1,useHTML:!0,headerFormat:"<b>{series.name}</b><br/>",pointFormat:'<span style="font-size: 1.2em; color: {point.color}; font-weight: bold">現有: {point.custom.formattedValue}</span><br/>目標: {point.custom.formattedTarget}<br/>達成率: {point.custom.ratio:.1f}% {point.custom.ratioNote}{point.custom.supplementBlock}',style:{fontSize:"12px",color:g.text}},pane:l,yAxis:i,plotOptions:{solidgauge:{dataLabels:{enabled:!1},linecap:"round",stickyTracking:!1,rounded:!0}},series:o,credits:{enabled:!1}}},[I,g,p]),M=I&&I.length>0;return(0,n.useEffect)(()=>{let e=k.current;e&&N(null!=e.closest("[data-chart-fullscreen-overlay]"))},[M]),(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(eo,{id:"insurance-coverage-gap",title:"保額缺口分析",cardStyle:e,borderColor:"yellow-300",contentClassName:"flex h-full flex-col !p-0",headerActions:c?(0,a.jsx)(e$.S,{onClick:()=>j(!0),variant:"ghost",size:"icon"}):void 0,onRemove:i,onTogglePin:l,isVisible:o,pinned:s,children:M?(0,a.jsx)("div",{ref:k,className:`w-full flex-1 min-h-0 flex flex-col ${S?"overflow-auto":"h-full overflow-hidden"}`,children:R?(0,a.jsxs)(a.Fragment,{children:[E>0?(0,a.jsxs)(ta.Fc,{variant:"default",className:"mx-3 mt-3 shrink-0 border-amber-500/50 bg-amber-500/10",children:[(0,a.jsx)(tl.A,{className:"h-4 w-4 text-amber-600 dar
1k:text-amber-400"}),(0,a.jsx)(ta.XL,{className:"text-amber-900 dark:text-amber-100",children:"未對照險種的醫療保單"}),(0,a.jsxs)(ta.TN,{className:"text-amber-800/90 dark:text-amber-200/90",children:["有 ",E," 張醫療保單的險種無法對照到標準分類,保額已暫列入「其他」計算。請至保險頁確認險種是否選擇正確。"]})]}):null,S&&I&&I.length>0?(0,a.jsx)("div",{className:"flex flex-wrap justify-center gap-x-6 gap-y-2 pb-4 border-b border-border/50 flex-shrink-0",children:I.map((e,t)=>(0,a.jsxs)("div",{className:"flex items-center gap-2",children:[(0,a.jsx)("span",{className:"shrink-0 w-3 h-3 rounded-full",style:{backgroundColor:tm[t%tm.length]},"aria-hidden":!0}),(0,a.jsx)("span",{className:"text-sm text-muted-foreground",children:e.name})]},e.name))}):null,(0,a.jsx)("div",{className:S?"flex-1 min-h-0 w-full flex items-center justify-center":"flex-1 min-h-0 w-full h-full min-h-0",children:(0,a.jsx)("div",{"data-chart":A,className:S?"w-full aspect-square max-h-full min-w-0 min-h-0 max-w-[min(70vmin,640px)] max-h-[min(70vmin,640px)]":"h-full w-full min-h-0 min-w-0",children:(0,a.jsx)(eO.A,{highcharts:eP.A,options:R,containerProps:{style:{width:"100%",height:"100%"}},callback:e=>{if(!e)return;C.current=e;let t=()=>{if(!e.container)return void setTimeout(t,100);if(window[A]=e,e.getSVG||(e.getSVG=function(){try{let e=this.container||this.renderTo;if(e){let t=e instanceof HTMLElement?e:"string"==typeof e?document.querySelector(e):null;if(t){let e=t.querySelector("svg");if(e)return e.outerHTML}}throw Error("無法找到 SVG 元素")}catch(e){throw console.error(`[${A}] SVG 取得失敗:`,e),e}}),window[`${A}HasData`]=M,e&&e.container&&"function"==typeof e.reflow)try{e.reflow()}catch(e){console.warn("Chart reflow failed:",e)}};t()}})})})]}):(0,a.jsx)("div",{className:"flex h-full items-center justify-center text-sm text-muted-foreground",children:"圖表初始化中…"})}):(0,a.jsx)("div",{className:"flex flex-col items-center justify-center flex-1 text-sm text-muted-foreground",children:0===x.length?"請先執行需求計算器取得建議保額":"尚無可顯示的保障分項(請確認是否已新增保單)"})}),(0,a.jsx)(eH.Q,{open:w,onOpenChange:j,chartKey:A,chartTitle:"保額缺口分析"})]})}}};var tp=r(63474);function tg({card:e,isEditing:t,cardStyle:r,colorMode:i,indicators:l,charts:o,financialSummary:s,onRemove:d}){let c,u,m=(0,n.useMemo)(()=>l.find(t=>String(t.id)===e.metricKey),[l,e.metricKey]),f=(0,n.useMemo)(()=>o.find(t=>t.type===e.metricKey||t.id===e.metricKey),[o,e.metricKey]),h=f?th[f.type]:null,p=(0,n.useMemo)(()=>{if("indicator"===e.type&&m){let e=ed(m.type),t=es(m.value-m.target,i,e).border.match(/border-([a-z]+-\d+)/);return t?t[1]:void 0}if("chart"===e.type&&f)return tf[f.type];if("netWorth"===e.type){let e=es(s?.netWorth??0,i,"positive").border.match(/border-([a-z]+-\d+)/);return e?e[1]:void 0}},[e.type,m,i,f,s?.netWorth]),g="financialHealth"===e.type?(0,a.jsx)(eF,{cardStyle:r}):"netWorth"===e.type?(0,a.jsx)(ek,{financialSummary:s,cardStyle:r,colorMode:i}):"indicator"===e.type&&m?(0,a.jsx)(eN,{indicator:m,financialSummary:s,cardStyle:r,colorMode:i,sourceItems:function(e,t){if(!t)return[];let r=e=>(0,eC.C)("number"==typeof e&&Number.isFinite(e)?e:0),a=e=>`${("number"==typeof e&&Number.isFinite(e)?e:0).toFixed(1)}%`;switch(e){case"expense-ratio":return[{label:"月支出",value:r(t.monthlyExpenses)},{label:"當月收入",value:r(t.monthlyIncome)}];case"debt-ratio":return[{label:"總負債",value:r(t.totalLiabilities)},{label:"總資產",value:r(t.totalAssets)}];case"debt-to-income":return[{label:"每月最低還款",value:r(t.monthlyMinimumDebtPayment)},{label:"當月收入",value:r(t.monthlyIncome)},...!1===t.debtToIncomeEvaluable?[{label:"資料狀態",value:"部分負債缺少最低還款,暫無法評估"}]:[]];case"housing-expense":return[{label:"住房支出",value:r(t.housingExpenses)},{label:"當月收入",value:r(t.monthlyIncome)}];case"emergency-fund-coverage":{let e="number"==typeof t.emergencyFundCoverageMonths&&Number.isFinite(t.emergencyFundCoverageMonths)?t.emergencyFundCoverageMonths.toFixed(1):"0";return[{label:"目前現金",value:r(t.totalCashFromAccounts)}
1,{label:"近12個月平均月支出",value:r(t.averageMonthlyExpenses)},{label:"覆蓋月數",value:`${e}個月`}]}case"savings-rate":return[{label:"儲蓄率",value:a(t.savingsRate)}];case"investment-ratio":return[{label:"投資比例",value:a(t.investmentRatio)}];case"financial-freedom":return[{label:"財務自由度進度",value:a(t.financialFreedomProgress)}];case"net-worth-growth":return[{label:"淨值增長率",value:a(t.netWorthGrowthRate)}];case"loan-to-value":return[{label:"總負債",value:r(t.totalLiabilities)},{label:"淨資產",value:r(t.netWorth)},{label:"財務槓桿比率",value:a((0,tp.s)(t))}];case"current-ratio":return[{label:"流動資產",value:r(t.liquidAssetsTotal)},{label:"短期負債",value:r(t.shortTermLiabilitiesTotal)},{label:"流動比率",value:a(t.currentRatio)}];case"investment-diversification":return[{label:"投資分散度",value:a(t.investmentDiversification)}];case"excess-cash-ratio":return[{label:"目前餘額",value:r(t.totalCashFromAccounts)},{label:"緊急預備金目標",value:r(t.emergencyFundTargetAmount)},{label:"超額現金比",value:a(t.excessCashRatio)}];default:return[]}}(m.type,s??null)}):"chart"===e.type&&h?(c=h.component,u={cardStyle:r,colorMode:i,onRemove:void 0,onTogglePin:void 0,isVisible:!0,pinned:!1,showShareButton:!1},(0,a.jsx)(e6.N,{className:"h-full min-h-0 w-full",renderFullscreenContent:()=>(0,a.jsx)(c,{...u,showShareButton:!0}),disableClickToFullscreen:t,children:(0,a.jsx)(c,{...u})})):(0,a.jsx)("div",{className:"flex min-h-[80px] items-center justify-center rounded-lg border border-dashed text-sm text-muted-foreground",children:"indicator"===e.type?"找不到指標":"chart"===e.type?"找不到圖表":"無法顯示"}),b=p?"indicator"===e.type?p?({"green-300":"border border-green-600/28 dark:border-green-400/38","red-300":"border border-red-600/28 dark:border-red-400/38","yellow-300":"border border-amber-600/28 dark:border-amber-400/38","blue-300":"border border-blue-600/28 dark:border-blue-400/38","purple-300":"border border-purple-600/28 dark:border-purple-400/38","violet-300":"border border-violet-600/28 dark:border-violet-400/38"})[p]??el(p):"border-0":el(p):"border-0";return(0,a.jsxs)(K.Zp,{className:(0,B.cn)("relative h-full min-h-0 overflow-hidden transition-all",b),children:[t&&d&&(0,a.jsx)("div",{className:"absolute right-1 top-1 z-[110] flex items-center gap-1",onPointerDown:e=>e.stopPropagation(),children:(0,a.jsx)(q.$,{type:"button",variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0 text-muted-foreground hover:bg-destructive/10 hover:text-destructive","aria-label":"移除卡片",onClick:t=>{t.stopPropagation(),d(e.id)},children:(0,a.jsx)(Y.A,{className:"h-4 w-4","aria-hidden":!0})})}),(0,a.jsx)(Q,{suppressInnerBorder:!0,children:(0,a.jsx)("div",{className:(0,B.cn)("h-full border-0","indicator"===e.type||"financialHealth"===e.type?"p-1":"p-2"),children:g})})]})}var tb=r(42119);let tx="data-dashboard-card-index",ty="dashboard-new-row-after-",tv="dashboard-new-row-bottom";function tw(e,t,r,a){let n=e??[];return n.length===t.length?n.map((e,n)=>n===r?a:e??x(t[n]?.length??0)):t.map((e,t)=>t===r?a:x(e?.length??0))}function tj(e){return e.length>0&&e.every(e=>e.length>0&&8===e.reduce((e,t)=>e+t,0))}function tS(e,t){for(let r=0;r<e.length;r++)if(e[r].includes(t))return r;return -1}function tN(e,t,r){let a=e.map(e=>[...e]),n=-1,i=-1;for(let e=0;e<a.length;e++){let r=a[e].indexOf(t);if(r>=0){n=e,i=r;break}}if(n<0)return e;a[n].splice(i,1),0===a[n].length&&a.splice(n,1);let l=r+1;return n<r&&l--,[...a.slice(0,l),[t],...a.slice(l)]}let tC=e=>{let t=(0,H.TT)(e);if(t.length>0){let e=t.find(e=>String(e.id)===tv);if(e)return[e];let r=t.find(e=>String(e.id).startsWith(ty));return r?[r]:t}return(0,H.y$)(e)};function tk({rowIdx:e,showBar:t}){let r=`${ty}${e}`,{setNodeRef:n,isOver:i}=(0,H.zM)({id:r});return(0,a.jsx)("div",{ref:n,"data-dashboard-new-row-after":e,className:"min-h-14 -mt-1 flex items-center justify-center relative z-10","aria-label":`在此新增一列(第 ${e+1} 列下方)`,children:(t||i)&&(0,a.jsx)("span",{className:"absolute left-0 right-0 h-1 rounded-full bg-blue-400 dark:bg-blue-600 z-20 pointer-events-none","aria-hidden":!0})})}function tA({onBottomAddCard:e}){let{setNodeRef:t,isOver:r}=(0,H.zM)({id:tv});return(0,a.jsxs)("div",{ref:t,className:(0,B.cn)("w-full shrink-0 flex flex-col items-center gap-3 py-4 rounded-lg relative z-10 border-none bg-transparent",e?"min-h-[min(40vh,320px)] justify-center":"min-h-20 justify-center"),"aria-label":"將卡片拖到此處或底部按鈕上以在末端新增一列",children:[r?(0,a.jsx)("span",{className:"sr-only",children:"放開以新增一列"}):null,e?(0,a.jsx)("div",{className:"flex justify-center",onPointerDown:e=>e.stopPropagation(),children:(0,a.jsx)(q.$,{type:"button",size:"icon",className:"h-9 w-9 rounded-full shadow-md",onClick:e,"aria-label":"新增卡片",children:(0,a.jsx)(tb.A,{className:"h-4 w-4"})})}):null]})}function tT({card:e,span:t,globalIndex:r,isEditing:n,highlightCardId:i,cardStyle:l,colorMode:o,indicators:s,charts:d,financialSummary:c,onRemoveCard:u}
1){let{attributes:m,listeners:f,setNodeRef:h,transform:p,transition:g,isDragging:b}=(0,G.gl)({id:e.id}),x={gridColumn:`span ${t}`,transform:U.Ks.Transform.toString(p),transition:g},y=!!(i&&e.id===i);return(0,a.jsx)("div",{ref:h,style:x,...m,...f,[tx]:r,className:(0,B.cn)("relative h-full min-h-0 min-w-0 overflow-visible flex flex-col touch-manipulation cursor-grab active:cursor-grabbing",y&&"ring-2 ring-ring ring-offset-2 ring-offset-background rounded-lg bg-muted/30",b&&"opacity-50"),"data-dashboard-card-id":e.id,children:(0,a.jsx)("div",{className:"min-h-0 min-w-0 flex-1 flex flex-col overflow-y-auto overflow-x-hidden",children:(0,a.jsx)(tg,{card:e,isEditing:n,cardStyle:l,colorMode:o,indicators:s,charts:d,financialSummary:c,onRemove:u})})})}function tE({cards:e,rowStarts:t,maxPerRow:r,isEditing:i,highlightCardId:l,cardStyle:o,colorMode:s,indicators:d,charts:c,financialSummary:u,onRemoveCard:m,onApplyDragLayout:f,columnWidths:h,onColumnWidthsChange:p,onAddCardToRow:g,onBottomAddCard:b,rowHeightPx:y,chartRowHeightPx:v}){let w=y??360,j=v??w,S=e=>e.some(e=>"chart"===e.type)?j:w,N=(0,n.useMemo)(()=>e.slice(0,20),[e]),C=(0,n.useMemo)(()=>{let e=t?.length?t.filter(e=>e<N.length):[0];return e.length?e:[0]},[t,N.length]),k=(0,n.useMemo)(()=>C.map((e,t)=>N.slice(e,t+1<C.length?C[t+1]:N.length)),[N,C]),A=(0,n.useMemo)(()=>new Map(N.map(e=>[e.id,e])),[N]),[T,E]=(0,n.useState)(()=>k.map(e=>e.map(e=>e.id))),I=(0,n.useRef)(T);I.current=T;let[R,M]=(0,n.useState)(null),[L,z]=(0,n.useState)(null);(0,n.useEffect)(()=>{null===R&&E(k.map(e=>e.map(e=>e.id)))},[k,R]);let D=(0,n.useMemo)(()=>T.map(e=>e.map(e=>A.get(e)).filter(e=>!!e)),[T,A]),F=i?D:k,V=(0,n.useMemo)(()=>{if(!i)return C;let e=0;return D.map(t=>{let r=e;return e+=t.length,r})},[i,C,D]),P=(0,n.useCallback)(()=>{E(k.map(e=>e.map(e=>e.id)))},[k]),O=(0,H.FR)((0,H.MS)(H.AN,{activationConstraint:{distance:8}}),(0,H.MS)(H.IG,{activationConstraint:{delay:200,tolerance:5}}),(0,H.MS)(H.uN,{coordinateGetter:G.JR})),W=(0,n.useCallback)(e=>{M(String(e.active.id)),z(null)},[]),_=(0,n.useCallback)(e=>{let{active:t,over:a}=e;if(null==a)return void z(null);if(t.id===a.id)return;let n=String(a.id);if(n===tv){let e=I.current;e.length>0&&z(e.length-1);return}if(n.startsWith(ty)){let e=parseInt(n.slice(ty.length),10);isNaN(e)||z(e);return}z(null),E(e=>{let i=tS(e,String(t.id)),l=tS(e,n);if(i<0||l<0)return e;if(i===l){let r=[...e[i]],a=r.indexOf(String(t.id)),l=r.indexOf(n);return a<0||l<0||a===l?e:e.map((e,t)=>t===i?(0,G.be)(r,a,l):e)}if(null!=r&&r>=1&&e[l].length>=r)return e;let o=[...e[i]],s=[...e[l]],d=o.indexOf(String(t.id)),c=s.indexOf(n);if(d<0||c<0)return e;let u=!!t.rect.current.translated&&t.rect.current.translated.top>a.rect.top+a.rect.height,m=c>=0?c+ +!!u:s.length+1,f=o.filter(e=>e!==String(t.id)),h=[...s.slice(0,m),String(t.id),...s.slice(m)];return e.map((e,t)=>t===i?f:t===l?h:e).filter(e=>e.length>0)})},[r]),$=(0,n.useCallback)(e=>{let{active:t,over:a}=e;if(M(null),z(null),!i||!f||!a)return void P();let n=String(a.id),l=I.current,o=l;if(n===tv){let e=Math.max(0,l.length-1);o=tN(l,String(t.id),e)}else if(n.startsWith(ty)){let e=parseInt(n.slice(ty.length),10);isNaN(e)||(o=tN(l,String(t.id),e))}let s=o.map(e=>[...e]).filter(e=>e.length>0),d=s.map(e=>e.map(e=>A.get(e)).filter(e=>!!e));d.flat().length!==N.length?P():k.map(e=>e.map(e=>e.id).join(",")).join("|")===s.map(e=>e.join(",")).join("|")?P():f(d,{maxPerRow:r??4})},[i,f,A,N.length,k,r,P]),U=(0,n.useCallback)(()=>{M(null),z(null),P()},[P]);(0,n.useEffect)(()=>{if(null!==R)return document.body.classList.add("cursor-grabbing"),()=>document.body.classList.remove("cursor-grabbing")},[R]);let K=(0,n.useRef)(h);K.current=h;let[Y,J]=(0,n.useState)(null),[Q,Z]=(0,n.useState)(null),X=(0,n.useRef)(Y);X.current=Y;let ee=(0,n.useRef)(Q);ee.current=Q;let et=(0,n.useCallback)(e=>{let t=X.current;if(null===t)return;let r=document.querySelector(`[data-dashboard-row="${t.rowIdx}"]`);if(!r||!p)return;let a=r.getBoundingClientRect().width;if(a<=0)return;let{colIdx:n,startX:i,startSpans:l}=t,o=l[n]??2,s=o+(l[n+1]??2),d=Math.max(2,Math.min(s-2,o+Math.round((e-i)/(a/8)))),c=s-d,u=[...l];u[n]=d,u[n+1]=c,Z({rowIdx:t.rowIdx,widths:u});let m=tw(K.current,F,t.rowIdx,u);tj(m)&&p(m,V);let f={...t,startX:e,startSpans:u};X.current=f,J(f)},[p,F,V]),er=(0,n.useCallback)(()=>{let e=X.current;if(null!==e&&p){let t=ee.current,r=t?.rowIdx===e.rowIdx&&t.widths.length>
10?t.widths:e.startSpans,a=tw(K.current,F,e.rowIdx,r);tj(a)&&p(a,V)}Z(null),X.current=null,J(null),window.dispatchEvent(new CustomEvent("dashboard-columns-resized"))},[p,F,V]);(0,n.useEffect)(()=>(null!==Y&&document.body.setAttribute("data-dashboard-resizing",""),()=>document.body.removeAttribute("data-dashboard-resizing")),[Y]);let ea=R?A.get(R)??null:null;if(0===N.length)return(0,a.jsxs)("div",{className:"rounded-lg border border-dashed p-8 text-center text-muted-foreground",children:[(0,a.jsx)("p",{className:"text-sm",children:"尚無卡片"}),(0,a.jsx)("p",{className:"text-xs mt-1",children:i?"點擊右側或下方「新增」按鈕加入指標或圖表":"請切換「編輯儀表板」後新增卡片"})]});let en=(0,a.jsxs)("div",{className:"flex flex-col gap-4 w-full",children:[F.map((e,t)=>{let n,b,y;return b=(n=h?.[t]?.length===e.length?h[t]:null)&&8===n.reduce((e,t)=>e+t,0)&&n.every(e=>e>=2&&e<=8)?n:x(e.length),y=Q?.rowIdx===t&&Q.widths.length===e.length?Q.widths:b,(0,a.jsxs)("div",{className:"flex flex-col gap-0 relative",children:[(0,a.jsxs)("div",{className:"flex flex-row gap-4 items-stretch",children:[(0,a.jsxs)("div",{className:"flex-1 min-w-0 relative min-h-0",style:{height:S(e)},children:[(0,a.jsx)("div",{"data-dashboard-row":t,className:"grid h-full min-h-0 gap-4 w-full relative",style:{gridTemplateColumns:"repeat(8, minmax(0, 1fr))",gridAutoRows:`${S(e)}px`},children:i&&f?(0,a.jsx)(G.gB,{items:T[t]??[],strategy:G.m$,children:e.map((e,r)=>{let n=y[r]??2,f=V[t]+r;return(0,a.jsx)(tT,{card:e,span:n,globalIndex:f,isEditing:i,highlightCardId:l,cardStyle:o,colorMode:s,indicators:d,charts:c,financialSummary:u,onRemoveCard:m},e.id)})},`sort-row-${t}`):e.map((e,r)=>{let n=y[r]??2,f=V[t]+r;return(0,a.jsx)("div",{style:{gridColumn:`span ${n}`},[tx]:f,"data-dashboard-card-id":e.id,className:(0,B.cn)("relative h-full min-h-0 min-w-0 overflow-visible flex flex-col",l&&e.id===l?"ring-2 ring-ring ring-offset-2 ring-offset-background rounded-lg bg-muted/30":null),children:(0,a.jsx)("div",{className:"min-h-0 min-w-0 flex-1 flex flex-col overflow-y-auto overflow-x-hidden",children:(0,a.jsx)(tg,{card:e,isEditing:i,cardStyle:o,colorMode:s,indicators:d,charts:c,financialSummary:u,onRemove:m})})},e.id)})}),i&&p&&e.length>1&&e.slice(0,-1).map((e,r)=>{let n=12.5*y.slice(0,r+1).reduce((e,t)=>e+(t??2),0),i=Y?.rowIdx===t&&Y?.colIdx===r;return(0,a.jsx)("div",{role:"separator","aria-label":"調整欄寬","data-testid":`dashboard-resize-handle-row-${t}-col-${r}`,"data-resizing":!!i||void 0,className:(0,B.cn)("absolute top-0 bottom-0 w-12 -translate-x-1/2 cursor-col-resize z-[100] flex items-center justify-center group touch-none sm:w-10"),style:{left:`${n}%`},onPointerDown:e=>{if(0!==e.button)return;e.preventDefault(),e.stopPropagation();let a={rowIdx:t,colIdx:r,startX:e.clientX,startSpans:y};X.current=a,e.currentTarget.setPointerCapture(e.pointerId),J(a)},onPointerMove:e=>{null!==X.current&&(e.preventDefault(),et(e.clientX))},onPointerUp:e=>{0===e.button&&null!==X.current&&er()},onPointerCancel:()=>{null!==X.current&&er()},children:(0,a.jsx)("span",{className:(0,B.cn)("absolute left-1/2 top-[10%] h-[80%
1] -translate-x-1/2 rounded-full pointer-events-none transition-[background-color,box-shadow,width] duration-150",i?"w-1.5 max-w-[6px] bg-blue-500 shadow-sm dark:bg-blue-400":"w-px max-w-[3px] bg-blue-400/90 shadow-none dark:bg-blue-500/90 group-hover:w-1.5 group-hover:max-w-[6px] group-hover:bg-blue-500 group-hover:shadow-sm dark:group-hover:bg-blue-400 group-active:w-1.5 group-active:max-w-[6px] group-active:bg-blue-500 dark:group-active:bg-blue-400"),"aria-hidden":!0})},r)})]}),i&&g&&e.length<(r??1/0)&&(0,a.jsx)(q.$,{type:"button",size:"icon",className:"h-9 w-9 shrink-0 self-center rounded-full shadow-md",onClick:()=>g(V[t]+e.length),"aria-label":"新增卡片",children:(0,a.jsx)(tb.A,{className:"h-4 w-4"})})]}),i&&f&&(0,a.jsx)(tk,{rowIdx:t,showBar:L===t})]},`row-${t}-${e.map(e=>e.id).join("-")}`)}),i&&f?(0,a.jsx)(tA,{onBottomAddCard:b}):null]});if(!i||!f)return en;let ei=ea?.title??(ea?.type==="chart"?c.find(e=>e.type===ea.metricKey||e.id===ea.metricKey)?.type??"圖表":ea?.type==="indicator"?"指標":ea?.metricKey??"卡片");return(0,a.jsxs)(H.Mp,{sensors:O,collisionDetection:tC,onDragStart:W,onDragOver:_,onDragEnd:$,onDragCancel:U,children:[en,(0,a.jsx)(H.Hd,{dropAnimation:null,children:ea?(0,a.jsxs)("div",{className:"pointer-events-none w-[min(100vw-2rem,320px)] rounded-lg border-2 border-primary/40 bg-card p-3 shadow-xl",children:[(0,a.jsx)("p",{className:"text-sm font-medium truncate",children:ei}),(0,a.jsx)("p",{className:"text-xs text-muted-foreground capitalize",children:ea.type})]}):null})]})}let tI={investor:{name:"投資者",description:"專注於投資報酬與資產成長,適合積極投資的使用者",getConfig:(e,t)=>({...e,charts:e.charts.map(e=>({...e,enabled:["income-expense-trend","networth-growth","asset-liability"].includes(e.type)})),indicators:t.map(e=>{let t=["investment-ratio","net-worth-growth","investment-diversification"].includes(e.type),r=["savings-rate","financial-freedom","current-ratio"].includes(e.type);return{id:`indicator-${e.id}`,indicatorId:String(e.id),priority:t?"critical":r?"secondary":"advanced",favorite:t,hidden:!t&&!r}})})},saving:{name:"存錢",description:"重視儲蓄與財務安全,適合穩健理財的使用者",getConfig:(e,t)=>({...e,charts:e.charts.map(e=>({...e,enabled:["income-expense-trend"].includes(e.type)})),indicators:t.map(e=>{let t=["savings-rate","emergency-fund-coverage","expense-ratio"].includes(e.type),r=["financial-freedom","current-ratio","excess-cash-ratio"].includes(e.type);return{id:`indicator-${e.id}`,indicatorId:String(e.id),priority:t?"critical":r?"secondary":"advanced",favorite:t,hidden:!t&&!r}})})},debtManagement:{name:"負債管理",description:"專注於債務控制與還款進度,適合有負債的使用者",getConfig:(e,t)=>({...e,charts:e.charts.map(e=>({...e,enabled:["income-expense-trend","asset-liability"].includes(e.type)})),indicators:t.map(e=>{let t=["debt-ratio","debt-to-income","loan-to-value"].includes(e.type),r=["expense-ratio","savings-rate","current-ratio"].includes(e.type);return{id:`indicator-${e.id}`,indicatorId:String(e.id),priority:t?"critical":r?"secondary":"advanced",favorite:t,hidden:!t&&!r}})})}};function tR({currentConfig:e,availableIndicators:t,onApplyPreset:r}){let{toast:n}=(0,l.dj)(),i=a=>{let i=tI[a];r(i.getConfig(e,t)),n({title:"範本已套用",description:`已套用「${i.name}」版面配置`})};return(0,a.jsxs)("div",{className:"space-y-4 py-4",children:[(0,a.jsxs)("div",{children:[(0,a.jsx)("h3",{className:"text-lg font-semibold mb-2",children:"版面配置範本"}),(0,a.jsx)("p",{className:"text-sm text-muted-foreground mb-4",children:"選擇預設的版面配置範本,快速套用不同的儀表板佈局"})]}),(0,a.jsx)("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:Object.entries(tI).map(([e,t])=>(0,a.jsxs)(K.Zp,{className:"cursor-pointer hover:border-primary transition-colors",onClick:()=>i(e),children:[(0,a.jsxs)(K.aR,{children:[(0,a.jsx)(K.ZB,{className:"text-base",children:t.name}),(0,a.jsx)(K.BT,{className:"text-sm",children:t.description})]}),(0,a.jsx)(K.Wu,{children:(0,a.jsx)(q.$,{variant:"outline",size:"sm",className:"w-full",onClick:t=>{t.stopPropagation(),i(e)},children:"套用此範本"})})]},e))})]})}var tM=r(78954),tL=r(41819),tz=r(94430);function tD({title:e="儀表板",isEditing:t,onEditingChange:r}){return(0,a.jsxs)("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4",children:[(0,a.jsxs)("div",{className:"flex items-center gap-2",children:[(0,a.jsx)(tz.A,{className:"h-6 w-6 text-muted-foreground"}),(0,a.jsx)("h1",{className:"text-xl font-semibold",children:e})]}),(0,a.jsx)("div",{className:"flex items-center gap-3",children:(0,a.jsx)(tL.m_,{content:"切換後可新增、移除或調整卡片",children:(0,a.jsx)("span",{className:"inline-flex items-center",children:(0,a.jsx)(tM.d,{id:"dashboard-edit-mode",checked:t,onCheckedChange:r})})})})]})}var tF=r(13139),tV=r(866),tP=r(5779),tO=r(41403),tW=r(10250);function t_({open:e,onOpenChange:t,indicators:r,charts:i,currentCardCount:l,dashboardCards:o=[],onSelect:s}
1){let[d,c]=(0,n.useState)(""),u=l>=20,m=(0,n.useMemo)(()=>new Set(o.map(e=>`${e.type}:${e.metricKey}`)),[o]),f=(0,n.useMemo)(()=>[{type:"financialHealth",metricKey:"financial-health",label:"財務健康"},...r.map(e=>({type:"indicator",metricKey:String(e.id),label:e.title})),...[...i].sort((e,t)=>e.order-t.order).map(e=>{let t=th[e.type];return{type:"chart",metricKey:e.type,label:t?.label??e.type}})],[r,i]),h=e=>{let t=f;if("indicator"===e&&(t=f.filter(e=>"indicator"===e.type)),"chart"===e&&(t=f.filter(e=>"chart"===e.type)),!d.trim())return t;let r=d.trim().toLowerCase();return t.filter(e=>e.label.toLowerCase().includes(r))},p=e=>{u||m.has(`${e.type}:${e.metricKey}`)||(s({type:e.type,metricKey:e.metricKey}),t(!1))};return(0,a.jsx)(tF.cj,{open:e,onOpenChange:t,children:(0,a.jsxs)(tF.h,{side:"right",className:"flex flex-col w-full sm:max-w-md overflow-hidden",children:[(0,a.jsx)(tF.Fm,{children:(0,a.jsx)(tF.qp,{children:"新增卡片"})}),(0,a.jsxs)("div",{className:"flex-1 flex flex-col min-h-0 pt-4",children:[(0,a.jsxs)("div",{className:"relative mb-4",children:[(0,a.jsx)(tP.A,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),(0,a.jsx)(tV.p,{placeholder:"搜尋指標或圖表...",value:d,onChange:e=>c(e.target.value),className:"pl-9"})]}),(0,a.jsxs)(eV.tU,{defaultValue:"all",className:"flex-1 flex flex-col min-h-0",children:[(0,a.jsxs)(eV.j7,{className:"grid w-full grid-cols-3",children:[(0,a.jsx)(eV.Xi,{value:"all",children:"全部"}),(0,a.jsx)(eV.Xi,{value:"indicator",children:"指標"}),(0,a.jsx)(eV.Xi,{value:"chart",children:"圖表"})]}),(0,a.jsx)(eV.av,{value:"all",className:"flex-1 overflow-auto mt-4 data-[state=inactive]:hidden",children:(0,a.jsx)(t$,{items:h("all"),atLimit:u,usedSet:m,onSelect:p})}),(0,a.jsx)(eV.av,{value:"indicator",className:"flex-1 overflow-auto mt-4 data-[state=inactive]:hidden",children:(0,a.jsx)(t$,{items:h("indicator"),atLimit:u,usedSet:m,onSelect:p})}),(0,a.jsx)(eV.av,{value:"chart",className:"flex-1 overflow-auto mt-4 data-[state=inactive]:hidden",children:(0,a.jsx)(t$,{items:h("chart"),atLimit:u,usedSet:m,onSelect:p})})]}),(0,a.jsxs)("div",{className:"pt-4 border-t mt-auto",children:[(0,a.jsxs)("p",{className:"text-sm text-muted-foreground",children:["目前 ",l," / ",20," 張卡片"]}),u&&(0,a.jsx)("p",{className:"text-sm text-amber-600 dark:text-amber-500 mt-1",children:"已達上限,請移除部分卡片或建立新儀表板後再新增。"})]})]})]})})}function t$({items:e,atLimit:t,usedSet:r,onSelect:n}){return(0,a.jsxs)("ul",{className:"space-y-1",children:[e.map(e=>{let i=r.has(`${e.type}:${e.metricKey}`);return(0,a.jsx)("li",{children:(0,a.jsxs)(q.$,{variant:"ghost",className:(0,B.cn)("w-full justify-start gap-2 h-auto py-2",(t||i)&&"opacity-60 pointer-events-none"),onClick:()=>n(e),children:["indicator"===e.type?(0,a.jsx)(tO.A,{className:"h-4 w-4 shrink-0 text-muted-foreground"}):"chart"===e.type?(0,a.jsx)(tz.A,{className:"h-4 w-4 shrink-0 text-muted-foreground"}):"financialHealth"===e.type?(0,a.jsx)(eE.A,{className:"h-4 w-4 shrink-0 text-muted-foreground"}):(0,a.jsx)(ep.A,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),(0,a.jsx)("span",{className:"truncate flex-1 text-left",children:e.label}),i&&(0,a.jsxs)("span",{className:"ml-auto flex items-center gap-1 text-[11px] text-emerald-600 dark:text-emerald-400 font-medium shrink-0",children:[(0,a.jsx)(tW.A,{className:"h-3.5 w-3.5"}),"已新增"]})]})},`${e.type}-${e.metricKey}`)}),0===e.length&&(0,a.jsx)("li",{className:"text-sm text-muted-foreground py-4 text-center",children:"沒有符合的項目"})]})}var tH=r(54306),tG=r(44650);function tU(e,t){let r=t>0&&t<768;if(e<=0)return r?1:4;let a=Math.min(e<=0?1:Math.max(1,Math.floor((e+16)/336)),4);return r&&(a=Math.min(a,1)),a}let tB=(0,i.default)(()=>r.e(969).then(r.bind(r,70969)).then(e=>e.PremiumProjectionChart),{loadableGenerated:{webpack:()=>[70969]},ssr:!1,loading:()=>(0,a.jsx)("div",{className:"rounded-lg border p-10 text-center text-sm text-muted-foreground",children:"載入保費走勢…"})});function tK({embedded:e=!1}){let{toast:t}=(0,l.dj)(),{user:r}=(0,d.A)(),i=(0,tG.A)(),{currentUser:m,loading:f}=(0,o.A)(),{financialSummary:w,isLoading:j,error:S}=(0,s.P)(),{config:N,importConfig:C,addDashboardCard:k,removeDashboardCard:A,applyDashboardDragLayout:T,updateRowColumnWidths:E}=function(){let{currentUser:e}=(0,o.A)(),{financialIndicators:t}
1=(0,v.rl)(e?.uid),[r,a]=(0,n.useState)(b),[i,l]=(0,n.useState)(null),s=(0,n.useRef)(r);s.current=r,(0,n.useEffect)(()=>{try{let e=localStorage.getItem(M);if(e){let t,r,n=JSON.parse(e),i=n?.version;if(null==i||i<2){try{localStorage.removeItem(L)}catch{}let e={...b,version:2,lastUpdated:new Date().toISOString()};_(e),l(null),a(e);return}let o=g(n.dashboardCards),s=o.length!==(n.dashboardCards?.length??0),d=s?(r=(t=F(o.length,4)).map((e,r)=>{let a=r+1<t.length?t[r+1]:o.length;return x(a-e)}),{rowStarts:t,columnWidths:r}):null,c={...b,...n,dashboardCards:o,...d??{}},u=p.parse(c);if(s){u={...u,lastUpdated:new Date().toISOString()},_(u);try{d&&localStorage.setItem(L,JSON.stringify(d.columnWidths))}catch{}}let m=u.columnWidths;if(Array.isArray(m)&&m.length>0&&m.some(e=>e.some(e=>e<2||!Number.isInteger(e)))){let e=u.rowStarts?.length?u.rowStarts:[0],t=u.dashboardCards.length;u={...u,columnWidths:e.map((r,a)=>{let n=a+1<e.length?e[a+1]:t;return x(n-r)})}}if(u.dashboardCards.length>0&&(!u.rowStarts||0===u.rowStarts.length)){let e=u.dashboardCards.length,t=e>4?F(e,4):[0];u={...u,rowStarts:t}}let f=u.rowStarts??[0],h=u.dashboardCards.length;try{let e=localStorage.getItem(L);if(e){let t=JSON.parse(e);V(t,f,h)&&(u={...u,columnWidths:t})}}catch{}let y=new Set(u.charts.map(e=>e.type)),v=b.charts.filter(e=>!y.has(e.type));if(v.length>0){let e=Math.max(...u.charts.map(e=>e.order),-1),t=[...u.charts,...v.map((t,r)=>({...t,order:e+1+r}))];l(u.columnWidths??[]),a({...u,charts:t,lastUpdated:new Date().toISOString()}),localStorage.setItem(M,JSON.stringify({...u,charts:t,lastUpdated:new Date().toISOString()}))}else a(u);l(u.columnWidths??[])}}catch(e){console.error("載入儀表板配置失敗:",e),a(b),l(null)}},[]),(0,n.useEffect)(()=>{if(!t||0===t.length)return;let e=s.current,r=0===e.indicators.length,n=!r&&function(e,t){if(!Array.isArray(e)||0===e.length||!Array.isArray(t)||0===t.length)return!1;let r=new Map(e.map(e=>[e.indicatorId,e])),a=t.map(e=>r.get(String(e.id))).filter(Boolean);return!(0===a.length||a.some(e=>e.hidden)||a.some(e=>"critical"!==e.priority)||a.some(e=>e?.favorite===!0))}(e.indicators,t);if(r||n){let r={...e,indicators:$(t),lastUpdated:new Date().toISOString()};_(r),s.current=r,a(r);return}let i=new Set(e.indicators.map(e=>e.indicatorId)),o=t.filter(e=>!i.has(String(e.id)));if(0===o.length){let t=e.dashboardCards??[];if(0===t.length){let t=e.indicators.filter(e=>!e.hidden).sort((e,t)=>{let r={critical:0,secondary:1,advanced:2};return r[e.priority]-r[t.priority]}),r=e.charts.filter(e=>e.enabled).sort((e,t)=>e.order-t.order),n=[z],i=1;for(let e of t){if(i>=20)break;n.push({id:`card-migrate-ind-${e.indicatorId}`,type:"indicator",metricKey:e.indicatorId}),i++}for(let e of r){if(i>=20)break;n.push({id:`card-migrate-chart-${e.id}`,type:"chart",metricKey:e.type}),i++}if(n.length>0){let t={...e,dashboardCards:n,rowStarts:[0],lastUpdated:new Date().toISOString()};_(t),s.current=t,a(t)}return}let r=g(t);if((r=D(r)).length!==t.length||r[0]?.id!==t[0]?.id||!t.some(e=>"financialHealth"===e.type)){let t=F(r.length,4),n=t.map((e,a)=>x((a+1<t.length?t[a+1]:r.length)-e)),i={...e,dashboardCards:r,rowStarts:t,columnWidths:n,lastUpdated:new Date().toISOString()};_(i),s.current=i,l(n),a(i);try{localStorage.setItem(L,JSON.stringify(n))}catch{}}return}let d=$(o),c={...e,indicators:[...e.indicators,...d],lastUpdated:new Date().toISOString()};_(c),s.current=c,a(c)},[t]);let d=(0,n.useCallback)(e=>{try{if("function"==typeof e)a(t=>{let r={...e(t),lastUpdated:new Date().toISOString()};return localStorage.setItem(M,JSON.stringify(r)),s.current=r,r});else{let t={...e,lastUpdated:new Date().toISOString()};localStorage.setItem(M,JSON.stringify(t)),s.current=t,a(t)}}catch(e){console.error("儲存儀表板配置失敗:",e)}},[]),m=(0,n.useCallback)(e=>{d({...r,cardStyle:e})},[r,d]),f=(0,n.useCallback)(e=>{d({...r,colorMode:e})},[r,d]),w=(0,n.useCallback)(e=>{let t=r.charts.map(t=>t.id===e?{...t,enabled:!t.enabled}:t);d({...r,charts:t})},[r,d]);(0,n.useCallback)(e=>{let t=r.indicators.map(t=>t.indicatorId===e?{...t,favorite:!t.favorite}:t);d({...r,indicators:t})}
1,[r,d]);let j=(0,n.useCallback)(e=>{let t=r.indicators.map(t=>t.indicatorId===e?{...t,hidden:!t.hidden}:t);d({...r,indicators:t})},[r,d]),S=(0,n.useCallback)((e,t)=>{let a=r.indicators.map(r=>r.indicatorId===e?{...r,priority:t}:r);d({...r,indicators:a})},[r,d]),N=(0,n.useCallback)(e=>{try{let t=D(g(e.dashboardCards)),r={...b,...e,dashboardCards:t},a=p.parse(r);if(a.dashboardCards.length>0&&(!a.rowStarts||0===a.rowStarts.length)&&(a={...a,rowStarts:[0]}),0!==a.dashboardCards.length&&a.dashboardCards.some(e=>"financialHealth"===e.type))a={...a,dashboardCards:D(a.dashboardCards)};else{let e=a.indicators.filter(e=>!e.hidden).sort((e,t)=>{let r={critical:0,secondary:1,advanced:2};return r[e.priority]-r[t.priority]}),t=a.charts.filter(e=>e.enabled).sort((e,t)=>e.order-t.order),r=[z],n=1;for(let t of e){if(n>=20)break;r.push({id:`card-migrate-ind-${t.indicatorId}`,type:"indicator",metricKey:t.indicatorId}),n++}for(let e of t){if(n>=20)break;r.push({id:`card-migrate-chart-${e.id}`,type:"chart",metricKey:e.type}),n++}r.length>0&&(a={...a,dashboardCards:D(r),rowStarts:[0],lastUpdated:new Date().toISOString()})}d(a)}catch(e){throw console.error("匯入配置驗證失敗:",e),e}},[d]),C=(0,n.useCallback)(e=>{let t=e.slice(0,20),a=t.length>4?F(t.length,4):[0];d({...r,dashboardCards:t,rowStarts:a})},[r,d]),k=(0,n.useCallback)((e,t)=>{let a,n;if(r.dashboardCards.length>=20||r.dashboardCards.some(t=>t.type===e.type&&t.metricKey===e.metricKey))return;let i=`card-${Date.now()}-${Math.random().toString(36).slice(2,9)}`,l=h.safeParse({...e,id:i});if(!l.success)return;let o=t?.insertIndex,s=r.rowStarts?.length?[...r.rowStarts]:[0],c=null!=o?(a=Math.max(0,Math.min(o,r.dashboardCards.length)),(n=[...r.dashboardCards]).splice(a,0,l.data),n.slice(0,20)):[...r.dashboardCards,l.data],u=null!=o?[...new Set([...s,o])].sort((e,t)=>e-t):s;d({...r,dashboardCards:c,rowStarts:u})},[r,d]),A=(0,n.useCallback)(e=>{let t=r.dashboardCards.findIndex(t=>t.id===e);if(t<0)return;let a=r.dashboardCards.filter(t=>t.id!==e),n=(r.rowStarts?.length?[...r.rowStarts]:[0]).filter(e=>e!==t).map(e=>e>t?e-1:e).sort((e,t)=>e-t);(0===n.length||0!==n[0])&&(n=[0,...n.filter(e=>e>0)]),d({...r,dashboardCards:a,rowStarts:n})},[r,d]),T=(0,n.useCallback)((e,t,a)=>{let n=[...r.dashboardCards],[i]=n.splice(e,1);if(!i)return;let l=t>e?t-1:t;n.splice(l,0,i);let o=(r.rowStarts?.length?[...r.rowStarts]:[0]).filter(t=>t!==e).map(t=>t>e?t-1:t).sort((e,t)=>e-t);(0===o.length||0!==o[0])&&(o=[0,...o.filter(e=>e>0)]);let s=o.length-1;for(let e=0;e<o.length-1;e++)if(l>=o[e]&&l<o[e+1]){s=e;break}let c=o.map((e,t)=>t>s?e+1:e);a?.startNewRow&&(c=[...new Set([...c,l])].sort((e,t)=>e-t)),d({...r,dashboardCards:n,rowStarts:c})},[r,d]),E=(0,n.useCallback)((e,t)=>{let r=s.current,a=e.filter(e=>e.length>0);if(0===a.length)return;let n=Math.min(Math.max(1,t.maxPerRow),4);if(a.some(e=>e.length>n))return void(0,u.vV)("[applyDashboardDragLayout] 列長度超過上限",{cap:n,lengths:a.map(e=>e.length)});let i=a.flat();if(i.length!==r.dashboardCards.length)return void(0,u.vV)("[applyDashboardDragLayout] 卡片數不符",{expected:r.dashboardCards.length,got:i.length});if([...r.dashboardCards.map(e=>e.id)].sort().join("\0")!==[...i.map(e=>e.id)].sort().join("\0"))return void(0,u.vV)("[applyDashboardDragLayout] 卡片 id 集合不符");let o=c.YO(h).max(20).safeParse(i);if(!o.success)return void(0,u.vV)("[applyDashboardDragLayout] Zod 驗證失敗",o.error);let m=[],f=0;for(let e=0;e<a.length;e++)m.push(f),f+=a[e].length;let p=y(r.rowStarts?.length?[...r.rowStarts]:[0],r.columnWidths??[],m,i.length);V(p,m,i.length)||(p=m.map((e,t)=>x((t+1<m.length?m[t+1]:i.length)-e)));try{localStorage.setItem(L,JSON.stringify(p))}catch{}l(p),d({...r,dashboardCards:o.data,rowStarts:m,columnWidths:p})},[d]),I=(0,n.useCallback)((e,t)=>{let r,a,n=s.current,i=n.rowStarts??[0],o=n.dashboardCards.length,c=e.map(e=>{let t=e.map(e=>Math.max(2,Math.min(8,Math.round(e))));return 8===t.reduce((e,t)=>e+t,0)?t:x(t.length)}),u=t.length===i.length&&t.every((e,t)=>e===i[t]);if(V(c,t,o)?(a=t,r=c):u&&V(c,i,o)?(a=i,r=c):(r=function(e,t,r,a){let n=[];for(let i=0;i<r.length;
1i++){let l=r[i]??0,o=i+1<r.length?r[i+1]:a,s=[];for(let r=0;r<e.length;r++){let n=t[r]??0,i=r+1<t.length?t[r+1]:a;if(n>=l&&i<=o){let t=e[r];Array.isArray(t)&&s.push(...t)}}n.push(s.length>0&&8===s.reduce((e,t)=>e+t,0)?s:x(o-l))}return n}(c,t,i,o),a=i),V(r,a,o)){try{localStorage.setItem(L,JSON.stringify(r))}catch{}l(r),d({...n,rowStarts:a,columnWidths:r})}},[d]),R=(0,n.useCallback)(e=>{if(e<1)return;let t=s.current,r=t.dashboardCards.length,a=t.rowStarts?.length?[...t.rowStarts]:[0],n=t.columnWidths??[];if(r>1&&a.length===r&&a.every((e,t)=>e===t)){a=[0];for(let t=e;t<r;t+=e)a.push(t)}let i=[];for(let t=0;t<a.length;t++){let n=a[t],l=t+1<a.length?a[t+1]:r;if(l-n<=e)i.push(n);else for(let t=n;t<l;t+=e)i.push(t)}let l=[];for(let e=0;e<i.length;e++){let t=i[e],o=e+1<i.length?i[e+1]:r,s=0;for(let e=0;e<a.length;e++)if(t<(e+1<a.length?a[e+1]:r)){s=e;break}let d=a[s]??0,c=n[s],u=o-t;if(Array.isArray(c)&&c.length>=o-d){let e=c.slice(t-d,o-d),r=e.reduce((e,t)=>e+t,0),a=e.every(e=>e>=2&&e<=8&&Number.isInteger(e));l.push(8===r&&a?e:x(u))}else l.push(x(u))}i.length===a.length&&i.every((e,t)=>e===a[t])&&l.length===n.length||d({...t,rowStarts:i,columnWidths:l})},[d]);return{config:(0,n.useMemo)(()=>{let e=r.dashboardCards.length,t=r.rowStarts??[0];if(null!=i){if(V(i,t,e))return{...r,columnWidths:i};if(null!=i&&i.length>0){let t=[],a=0;for(let e of i)t.push(a),a+=e.length;if(a===e&&V(i,t,e))return{...r,rowStarts:t,columnWidths:i}}}try{let a=localStorage.getItem(L);if(a){let n=JSON.parse(a);if(V(n,t,e))return{...r,columnWidths:n}}}catch{}return r},[r,i]),updateCardStyle:m,updateColorMode:f,toggleChart:w,toggleIndicatorHidden:j,updateIndicatorPriority:S,importConfig:N,saveConfig:d,setDashboardCards:C,addDashboardCard:k,removeDashboardCard:A,reorderDashboardCards:T,applyDashboardDragLayout:E,updateRowColumnWidths:I,reflowLayoutByWidth:R}}(),{financialIndicators:I,isLoading:R,updateIndicatorValues:P}=(0,v.rl)(m?.uid),O=!!m&&!f&&!j&&!R&&N.dashboardCards.length>0,[W,H]=(0,n.useState)(!1),G=i?.isEditing??W,U=i?.setIsEditing??H,[B,K]=(0,n.useState)(!1),[q,Y]=(0,n.use
1State)("sameRow"),[J,Q]=(0,n.useState)(null),[Z,X]=(0,n.useState)(null),ee=(0,n.useRef)(null),et=(0,n.useRef)(null),[er,ea]=(0,n.useState)(0),[en,ei]=(0,n.useState)(0),[el,eo]=(0,n.useState)(null);(0,n.useEffect)(()=>{let e=setTimeout(()=>{window.dispatchEvent(new CustomEvent("dashboard-columns-resized"))},350);return()=>clearTimeout(e)},[G]),(0,n.useEffect)(()=>{if(!O)return;let e=et.current;if(!e)return;let t=()=>{ei(window.innerWidth)},r=new ResizeObserver(()=>{requestAnimationFrame(()=>{ea(e.clientWidth)})});return r.observe(e),ea(e.clientWidth),t(),window.addEventListener("resize",t),()=>{r.disconnect(),window.removeEventListener("resize",t)}},[O]);let es=(0,n.useMemo)(()=>tU(er,en),[er,en]),ed=en>0&&en<768;(0,n.useEffect)(()=>{let e=N.dashboardCards.find(e=>"netWorth"===e.type);e&&A(e.id)},[N.dashboardCards,A]);let ec=(0,n.useMemo)(()=>{var e,t,r;let a,n;return e=N.rowStarts??[0],t=N.columnWidths??[],r=N.dashboardCards.length,{rowStarts:n=function(e,t,r){let a=e?.length?[...e]:[0],n=[],i=Math.max(1,r);for(let e=0;e<a.length;e++){let r=a[e],l=e+1<a.length?a[e+1]:t;if(l-r<=i)n.push(r);else for(let e=r;e<l;e+=i)n.push(e)}return n}(a=e?.length?[...e]:[0],r,es),columnWidths:y(a,t,n,r)}},[N.rowStarts,N.columnWidths,N.dashboardCards.length,es]);(0,n.useEffect)(()=>{if(null==el)return;let e=ec.columnWidths;el.length!==e.length||el.every((t,r)=>t.length===e[r]?.length&&t.every((t,a)=>t===e[r]?.[a]))&&eo(null)},[ec.columnWidths,el]);let eu=(0,n.useCallback)(({type:e,metricKey:t})=>{let r=N.dashboardCards.find(r=>r.type===e&&r.metricKey===t);if(r){K(!1),Q(null),X(r.id),null!=ee.current&&(window.clearTimeout(ee.current),ee.current=null),requestAnimationFrame(()=>{let e=document.querySelector(`[data-dashboard-card-id="${r.id}"]`);e instanceof HTMLElement&&e.scrollIntoView({behavior:"smooth",block:"center"})}),ee.current=window.setTimeout(()=>{X(null),ee.current=null},1600);return}let a=N.dashboardCards.length,n=ec.rowStarts?.length?ec.rowStarts:[0],i=a-(n[n.length-1]??0),l=tU(er,en);if(null!=J){k({type:e,metricKey:t},{insertIndex:J}),Q(null);return}"sameRow"===q?i>=l?k({type:e,metricKey:t},{insertIndex:a}):k({type:e,metricKey:t}):k({type:e,metricKey:t},{insertIndex:l*Math.floor(a/l)})},[q,J,N.dashboardCards,ec.rowStarts,er,en,k]);return((0,n.useEffect)(()=>{w&&m?.uid&&(R||P(w))},[w,m?.uid,P,R]),(0,n.useEffect)(()=>{S&&t({title:"財務摘要載入錯誤",description:S.message,variant:"destructive"})},[S,t]),f||j||R)?(0,a.jsx)(tH.default,{className:"min-h-[40vh]",variant:"outline"}):m?(0,a.jsxs)("div",{className:"space-y-6 pb-8",children:[!e&&(0,a.jsx)(tD,{isEditing:G,onEditingChange:U}),0===N.dashboardCards.length?(0,a.jsxs)("div",{className:"w-full min-w-0 rounded-lg border border-dashed p-8",children:[(0,a.jsx)("p",{className:"text-sm text-muted-foreground mb-2",children:"尚未新增卡片,可選擇以下範本快速開始"}),(0,a.jsx)(tR,{currentConfig:N,availableIndicators:I,onApplyPreset:e=>C(e)}),!G&&(0,a.jsx)("p",{className:"text-xs text-muted-foreground mt-4",children:"若要手動新增或調整卡片,請切換至編輯儀表板"})]}):(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)("div",{ref:et,className:"w-full min-w-0 overflow-x-auto",children:(0,a.jsx)(tE,{cards:N.dashboardCards,rowStarts:ec.rowStarts,maxPerRow:es,rowHeightPx:ed?240:void 0,chartRowHeightPx:ed?360:void 0,isEditing:G,highlightCardId:Z,cardStyle:N.cardStyle,colorMode:N.colorMode,indicators:I,charts:N.charts,financialSummary:w,onRemoveCard:A,onApplyDragLayout:T,columnWidths:el??ec.columnWidths,onColumnWidthsChange:(e,t)=>
1{eo(e),E(e,t)},onAddCardToRow:G?e=>{Q(e),Y("sameRow"),K(!0)}:void 0,onBottomAddCard:G&&N.dashboardCards.length<20?()=>{Y("newRow"),K(!0)}:void 0})}),(0,a.jsx)(t_,{open:B,onOpenChange:e=>{K(e),e||Q(null)},indicators:I,charts:N.charts,currentCardCount:N.dashboardCards.length,onSelect:eu})]}),(0,a.jsx)(tB,{})]}):(0,a.jsx)("div",{className:"flex items-center justify-center py-16",children:(0,a.jsx)("p",{className:"text-muted-foreground",children:"請先登入..."})})}},42226:(e,t,r)=>{r.d(t,{PF:()=>i,fb:()=>l}),r(32407).env.NEXT_PUBLIC_DBUI;let a="/dashboard";var n=r(3303);function i(e){return e===n.Ru||"dashboard"===e?a:`${a}/${e}`}function l(e){if(!e||e===a||e===`${a}/`)return n.Ru;let t=`${a}/`;if(!e.startsWith(t))return n.Ru;let r=e.slice(t.length).split("/")[0]||n.Ru;return"dashboard"===r?n.Ru:(0,n.EZ)(r)?r:n.Ru}},46136:(e,t,r)=>{r.d(t,{I5:()=>o,kC:()=>h,a_:()=>f});var a=r(57376),n=r(31615),i=r(30233),l=r(89088);function o(e){let t=(0,n.useMemo)(()=>(0,i.l)(),[]),r=(0,n.useMemo)(()=>[],[]),o=(0,n.useMemo)(()=>[],[]),{data:s,error:d,isLoading:c,mutate:u}=(0,a.Ay)(e?["insurance/policies",e]:null,async([,e])=>{let r=await t.insurance.getPolicies(e);if(!r.ok)throw Error(r.error||"fetch_failed");return r.data||[]}),{data:m,error:f,isLoading:h,mutate:p}=(0,a.Ay)(e?["insurance/documents",e]:null,async([,e])=>{let r=await t.insurance.getDocuments(e);if(!r.ok)throw Error(r.error||"fetch_failed");return r.data||[]}),g=async(r,a)=>{if(!e)throw Error("missing_user");let n=await t.insurance.savePolicy(e,r,a);if(!n.ok)throw Error(n.error||"save_failed");return await u(),await (0,l.BS)(e),n.data},b=async r=>{let a=await t.insurance.deletePolicy(r);if(!a.ok)throw Error(a.error||"delete_failed");await u(),await (0,l.BS)(e)},x=async r=>{if(!e)throw Error("missing_user");let a=await t.insurance.addDocument(e,r);if(!a.ok)throw Error(a.error||"add_doc_failed");return await p(),a.data},y=async e=>{let r=await t.insurance.deleteDocument(e);if(!r.ok)throw Error(r.error||"delete_doc_failed");await p()};return{...{loading:!!(c||h),error:d?.message||f?.message||null,policies:s??r,documents:m??o},savePolicy:g,deletePolicy:b,addDocument:x,deleteDocument:y,mutatePolicies:u,mutateDocuments:p}}var s=r(76458),d=r(24571),c=r(27703);async function u(e,t){let r=t?(0,d.P)((0,d.rJ)(e,c.I.insuranceProducts),(0,d._M)("reviewStatus","==","listed"),(0,d._M)("category","==",t)):(0,d.P)((0,d.rJ)(e,c.I.insuranceProducts),(0,d._M)("reviewStatus","==","listed"));return(await (0,d.GG)(r)).docs.map(e=>{let t=e.data();return{id:e.id,productName:t.productName??"",productCode:t.productCode??"",insurerCode:t.insurerCode??"",category:t.category??"",productType:t.productType??""}})}async function m(e,t){let r,a,n,i=await (0,d.getDoc)((0,d.doc)(e,c.I.insuranceProducts,t));if(!i.exists())return null;let l=i.data(),o=l?.minInsuredAmountWan,s=l?.maxInsuredAmountWan,u=l?.termOption,m=l?.planAmounts;if(m&&"object"==typeof m&&!Array.isArray(m)){for(let[e,t]of(r={},Object.entries(m)))"number"==typeof t&&t>=0&&"string"==typeof e&&(r[e]=t);0===Object.keys(r).length&&(r=void 0)}let f=l?.benefitItems;Array.isArray(f)&&f.length>0&&0===(a=f.filter(e=>null!=e&&"object"==typeof e&&"string"==typeof e.name).map(e=>{let t,r=e.amountByPlan;if(r&&"object"==typeof r&&!Array.isArray(r)){let e={};for(let[t,a]of Object.entries(r)){let r=String(t).trim();if(!r||"string"!=typeof a)continue;let n=a.trim();n&&(e[r]=n)}Object.keys(e).length>0&&(t=e)}return{name:e.name,description:e.description,amount:e.amount,...t?{amountByPlan:t}:{},category:e.category}})).length&&(a=void 0);let h=l?.contributors;return Array.isArray(h)&&(n=h.filter(e=>null!=e&&"object"==typeof e&&"string"==typeof e.uid).map(e=>({uid:e.uid,submissionId:e.submissionId,contributedAt:e.contributedAt}))),{id:i.id,productName:l?.productName,insurerCode:l?.insurerCode,category:l?.category,productType:l?.productType??"",premiumCurrency:"string"==typeof l?.premiumCurrency?l.premiumCurrency:void 0,premiumRateType:"string"==typeof l?.premiumRateType?l.premiumRateType:void 0,rateTable:l?.rateTable??void 0,accidentRateTable:l?.accidentRateTable??void 0,minInsuredAmountWan:"number"==typeof o&&o>=0?o:void 0,maxInsuredAmountWan:"number"==typeof s&&s>=0?s:void 0,termOption:"string"==typeof u&&""!==u.trim()?u.trim():void 0,planAmounts:r,benefitItems:a,contributors:n,coverageSummary:l?.coverageSummary,termsSummary:l?.termsSummary}}function f(e){let{data:t=[],error:r,isLoading:i,mutate:l}=(0,a.Ay)(s.db?e?["insurance-products",e]:["insurance-products"]:null,()=>{if(!s.db)throw Error("Firestore 尚未初始化");return u(s.db,e)},{revalidateOnFocus:!1}),o=(0,n.useMemo)(()=>{let e=new Set;return t.forEach(t=>e.add(t.insurerCode)),Array.from(e).sort()},[t]),d=(0,n.useMemo)(()=>e=>{let r=new Set;return t.filter(t=>
1t.insurerCode===e).forEach(e=>r.add(e.productType)),Array.from(r).sort()},[t]),c=(0,n.useMemo)(()=>(e,r)=>t.filter(t=>t.insurerCode===e&&t.productType===r),[t]);return{products:t,companyOptions:o,getProductTypeOptions:d,getProductNameOptions:c,error:r,isLoading:i,mutate:l}}function h(e){let{data:t,error:r,isLoading:n,mutate:i}=(0,a.Ay)(s.db&&e?["insurance-product-detail",e]:null,()=>s.db&&e?m(s.db,e):Promise.resolve(null),{revalidateOnFocus:!1});return{productDetail:t??null,error:r,isLoading:n,mutate:i}}r(16032)},48019:(e,t,r)=>{r.d(t,{F4:()=>l,Ns:()=>o,Rt:()=>n,Tb:()=>i});let a=["expense-ratio","debt-ratio","housing-expense","loan-to-value","debt-to-income","excess-cash-ratio"],n=e=>a.includes(e),i=(e,t,r)=>(n(r),Math.min(e/t*100,100)),l=(e,t,r)=>n(r)?e<=t:e>=t,o=(e,t)=>"emergency-fund-coverage"===t?`目標: ${e}個月`:"excess-cash-ratio"===t?`目標: ${e}%`:n(t)?`上限: ${e}%`:`目標: ${e}%`},48716:(e,t,r)=>{r.r(t),r.d(t,{cleanupLegacyFlags:()=>b,clearAllAuthFlags:()=>x,clearLoginState:()=>s,clearLogoutState:()=>m,clearOAuthRedirectState:()=>p,getLoginState:()=>o,getOAuthRedirectState:()=>h,hasLoggedInRecently:()=>d,isLogoutState:()=>u,isOAuthRedirectInProgress:()=>g,setLoginState:()=>l,setLogoutState:()=>c,setOAuthRedirectState:()=>f});let a="authState",n="logoutFlag",i="oauthRedirectState";function l(e){try{let t={isLoggedIn:!0,redirectPath:e,timestamp:Date.now()};sessionStorage.setItem(a,JSON.stringify(t))}catch(e){}}function o(){try{let e=sessionStorage.getItem(a);if(!e)return null;let t=JSON.parse(e);if(Date.now()-t.timestamp>3e5)return s(),null;return t}catch(e){return null}}function s(){try{sessionStorage.removeItem(a)}catch(e){}}function d(){let e=o();return e?.isLoggedIn===!0}function c(){try{sessionStorage.setItem(n,"1")}catch(e){}}function u(){try{return"1"===sessionStorage.getItem(n)}catch(e){return!1}}function m(){try{sessionStorage.removeItem(n)}catch(e){}}function f(e){let t=Date.now();try{let r={inProgress:!0,timestamp:t,...e&&{provider:e}}
1;sessionStorage.setItem(i,JSON.stringify(r))}catch(e){console.error("[OAuth] 設置 OAuth redirect 狀態時發生錯誤:",e)}}function h(){try{let e=sessionStorage.getItem(i);if(e){let t=JSON.parse(e);if(Date.now()-t.timestamp>3e4)return p(),null;return t}return null}catch(e){return console.error("[OAuth] 讀取 OAuth redirect 狀態時發生錯誤:",e),null}}function p(){try{sessionStorage.removeItem(i)}catch(e){}}function g(){let e=h();return e?.inProgress===!0}function b(){try{sessionStorage.removeItem("justLoggedIn"),sessionStorage.removeItem("authRedirected"),sessionStorage.removeItem("oauthRedirectInProgress"),sessionStorage.removeItem("oauthRedirectInProgressTimestamp")}catch{}try{localStorage.removeItem("oauthRedirectInProgress"),localStorage.removeItem("oauthRedirectInProgressTimestamp")}catch{}}function x(){s(),m(),p(),b()}b()},56878:(e,t,r)=>{r.d(t,{d:()=>o});var a=r(57376),n=r(31615),i=r(30233),l=r(89088);function o(e){let t=(0,n.useMemo)(()=>(0,i.l)(),[]),r=(0,n.useMemo)(()=>[],[]),o=(0,n.useMemo)(()=>[],[]),s=e?["assets/list",e]:null,d=e?["liabilities/list",e]:null,{data:c,error:u,isLoading:m,mutate:f}=(0,a.Ay)(s,async([,e])=>{let r=await t.assets.getAssets(e);if(!r.ok)throw Error(r.error||"fetch_failed");return r.data||[]}),{data:h,error:p,isLoading:g,mutate:b}=(0,a.Ay)(d,async([,e])=>{let r=await t.assets.getLiabilities(e);if(!r.ok)throw Error(r.error||"fetch_failed");return r.data||[]}),x=async()=>{await Promise.all([f(),b()]),await (0,l.BS)(e)},y=async r=>{if(!e)throw Error("missing_user");let a=await t.assets.addAsset(e,r);if(!a.ok)throw Error(a.error||"add_failed");return await f(),await (0,l.BS)(e),a.data},v=async r=>{if(!e)throw Error("missing_user");let a=await t.assets.addLiability(e,r);if(!a.ok)throw Error(a.error||"add_failed");return await b(),await (0,l.BS)(e),a.data},w=async(r,a)=>{if(!e)throw Error("missing_user");let n=await t.assets.updateAsset(e,r,a);if(!n.ok)throw Error(n.error||"update_failed");await f(),await (0,l.BS)(e)},j=async(r,a)=>{if(!e)throw Error("missing_user");let n=await t.assets.updateLiability(e,r,a);if(!n.ok)throw Error(n.error||"update_failed");await b(),await (0,l.BS)(e)},S=async r=>{if(!e)throw Error("missing_user");let a=await t.assets.deleteAsset(e,r);if(!a.ok)throw Error(a.error||"delete_failed");await f(),await (0,l.BS)(e)},N=async r=>{if(!e)throw Error("missing_user");let a=await t.assets.deleteLiability(e,r);if(!a.ok)throw Error(a.error||"delete_failed");await b(),await (0,l.BS)(e)};return{loading:m||g,error:u?.message||p?.message||null,assets:c??r,liabilities:h??o,refreshAll:x,addAsset:y,addLiability:v,updateAsset:w,updateLiability:j,deleteAsset:S,deleteLiability:N}}r(96258)},63474:(e,t,r)=>{r.d(t,{s:()=>a});function a(e){let t=e.netWorth??0,r=e.totalLiabilities??0;if(t<=0)return 0;let a=e.leverageRatio;return"number"==typeof a&&Number.isFinite(a)?a:r/t*100}},73521:(e,t,r)=>{r.d(t,{A:()=>f,O:()=>m});var a=r(85047),n=r(31615),i=r(30274),l=r(76458),o=r(18654),s=r(3379),d=r(47026),c=r(48716);let u=(0,n.createContext)({user:null,auth:void 0,loading:!0,isGoogleUser:!1,googleUserInfo:null,viewingUserId:null,viewingUserEmail:null,setViewingUser:()=>{},clearViewingUser:()=>{}}),m=({children:e})=>{let[t,m]=(0,n.useState)(null),[f,h]=(0,n.useState)(!0),[p,g]=(0,n.useState)(null),[b,x]=(0,n.useState)(null),y=l.auth,v=(0,n.useRef)(null);(0,n.useEffect)(()=>{try{let e=sessionStorage.getItem("viewingUserId"),t=sessionStorage.getItem("viewingUserEmail");e&&t&&(g(e),x(t))}catch(e){(0,o.vV)("恢復檢視模式狀態失敗:",e)}},[]),(0,n.useEffect)(()=>{let e;if(!y)return void h(!1);e=(0,i.onAuthStateChanged)(y,async e=>{let t=v.current,r=e&&!t;if((0,c.isOAuthRedirectInProgress)(),m(e),v.current=e,h(!1),e){if((0,c.clearLogoutState)(),r)try{await (0,d.ME)()}catch(e){(0,o.vV)("登入時更新匯率失敗:",e)}}else if((0,c.isOAuthRedirectInProgress)())(0,c.clearLogoutState)();else{(0,c.setLogoutState)(),localStorage.removeItem("lineLoginStatus"),localStorage.removeItem("lineUserId"),localStorage.removeItem("lineDisplayName"),localStorage.removeItem("linePictureUrl"),localStorage.removeItem("lineAccessToken"),localStorage.removeItem("lineLoginReturnUrl"),g(null),x(null);try{sessionStorage.removeItem("viewingUserId"),sessionStorage.removeItem("viewingUserEmail"),sessionStorage.removeItem("lineLoginSuccess"),(0,c.clearLoginState)()}catch(e){(0,o.vV)("清除檢視模式狀態失敗:",e)}}});let t=async()=>{try{let e=window.location.pathname;if("/auth"===e||e.startsWith("/auth/"))return;let{googleProvider:t}=await r.e(4982).then(r.bind(r,14982)),{authService:a}=await r.e(392).then(r.bind(r,60392)),n=await t.handleRedirectResult();n?.success&&n.user&&await a.handleAuthSuccess(n.user,n.credential)}catch(e){if(e?.code==="auth/multi-factor-auth-required")return;(0,o.vV)("處理重定向結果失敗:",e)}};return setTimeout(()=>{t()},100),()=>{e&&e()}},[y]);let w=!!t&&(0,s.jR)(t),j=t?(0,s.R7)(t):null;return(0,a.jsx)(u.Provider,{value:{user:t,auth:y,loading:f,isGoogleUser:w,googleUserInfo:j,viewingUserId:p,viewingUserEmail:b,setViewingUser:(e,t)=>{if(!e||"string"!=typeof e||""===e.trim())return void(0,o.vV)("setVie
1wingUser: 無效的 UID",{uid:e});if(!t||"string"!=typeof t||""===t.trim())return void(0,o.vV)("setViewingUser: 無效的 Email",{email:t});g(e.trim()),x(t.trim());try{sessionStorage.setItem("viewingUserId",e.trim()),sessionStorage.setItem("viewingUserEmail",t.trim())}catch(e){(0,o.vV)("保存檢視模式狀態失敗:",e)}},clearViewingUser:()=>{g(null),x(null);try{sessionStorage.removeItem("viewingUserId"),sessionStorage.removeItem("viewingUserEmail")}catch(e){(0,o.vV)("清除檢視模式狀態失敗:",e)}}},children:e})},f=()=>(0,n.useContext)(u)},80221:(e,t,r)=>{r.d(t,{Z$:()=>s,rl:()=>u,v$:()=>c});var a=r(31615),n=r(24571),i=r(21),l=r(18654),o=r(63474);let s=[{id:1,type:"expense-ratio",title:"支出比",target:60},{id:2,type:"debt-ratio",title:"負債比",target:50},{id:3,type:"emergency-fund-coverage",title:"緊急預備金覆蓋",target:6},{id:4,type:"financial-freedom",title:"財務自由度",target:50},{id:5,type:"savings-rate",title:"儲蓄率",target:30},{id:6,type:"investment-ratio",title:"投資比例",target:50},{id:7,type:"debt-to-income",title:"債務收入比",target:35},{id:8,type:"net-worth-growth",title:"淨值增長率",target:10},{id:9,type:"housing-expense",title:"住房支出比",target:30},{id:10,type:"loan-to-value",title:"財務槓桿比率",target:80},{id:11,type:"current-ratio",title:"流動比率",target:200},{id:12,type:"investment-diversification",title:"投資分散度",target:70},{id:13,type:"excess-cash-ratio",title:"超額現金比",target:100}],d=()=>s.map(e=>({...e,value:0})),c=(e,t)=>{switch(e){case"expense-ratio":return t.expenseRatio;case"debt-ratio":return t.debtRatio;case"emergency-fund-coverage":return t.emergencyFundCoverageMonths??0;case"housing-expense":return t.housingExpenseRatio;case"financial-freedom":return t.financialFreedomProgress;case"savings-rate":return t.savingsRate;case"investment-ratio":return t.investmentRatio;case"debt-to-income":return t.debtToIncomeRatio;case"net-worth-growth":return t.netWorthGrowthRate;case"loan-to-value":return(0,o.s)(t);case"current-ratio":return t.currentRatio??0;case"investment-diversification":return t.investmentDiversification??0;case"excess-cash-ratio":return t.excessCashRatio??0;default:return 0}};function u(e){let[t,r]=(0,a.useState)([]),[o,s]=(0,a.useState)([]),[u,m]=(0,a.useState)(!0),[f,h]=(0,a.useState)(null),p=(0,a.useRef)(null),g=(0,a.useRef)(e);g.current=e;let b=(0,a.useCallback)(async(e,t)=>{let r=g.current;if(r)try{let a={financialIndicators:e,availableIndicators:t,lastUpdated:n.Timestamp.now()};await i.s.setPreferences(r,{financialIndicators:a})}catch(e){throw(0,l.vV)("保存財務指標失敗:",e),e}},[]),x=(0,a.useRef)(null),y=(0,a.useRef)(0),v=(0,a.useRef)(null),w=(0,a.useCallback)(async()=>{if(!e)return void m(!1);if(x.current!==e){m(!0),h(null),x.current=e;try{let t=await i.s.getPreferences(e);y.current=0;let a=t?.financialIndicators;if(a){let e=(a.financialIndicators||[]).filter(e=>"quick-ratio"!==e.type),t=(a.availableIndicators||[]).filter(e=>"quick-ratio"!==e.type);if(Array.isArray(e)&&e.length>0){let t=e.map(e=>{let t=Number(e.target)||0,r="emergency-fund-coverage"===e.type&&100===t?6:t;return{id:Number(e.id)||0,type:e.type,title:e.title||"",value:Number(e.value)||0,target:r}});r(t)}else{let e=d();r(e),await b(e,[])}Array.isArray(t)&&t.length>0?s(t.map(e=>{let t=Number(e.target)||0,r="emergency-fund-coverage"===e.type&&100===t?6:t;return{id:Number(e.id)||0,type:e.type,title:e.title||"",value:Number(e.value)||0,target:r}})):s([])}else{let e=d();r(e),s([]),await b(e,[])}}catch(t){if(t?.code==="permission-denied")if(x.current=null,y.current<3){let t=++y.current;(0,l.JE)("載入財務指標暫時無權限(auth 尚未就緒),排程重試",{userId:e,attempt:t}),v.current&&clearTimeout(v.current),v.current=setTimeout(()=>{g.current===e&&w()},800*t)}else(0,l.JE)("載入財務指標多次無權限,停止重試並使用預設值",{userId:e});else(0,l.vV)("載入財務指標失敗:",t),h(t?.message||"載入財務指標失敗");r(d()),s([])}finally{p.current=null,m(!1)}}},[e,b]),j=(0,a.useCallback)(async e=>{if(g.current)try{r(e),s(t=>(b(e,t).catch(e=>{(0,l.vV)("保存財務指標失敗:",e),h(e?.message||"保存財務指標失敗")}),t))}catch(e){throw(0,l.vV)("保存財務指標失敗:",e),h(e?.message||"保存財務指標失敗"),e}},[b]),S=(0,a.useCallback)(async e=>{if(g.current)try{s(e),r(t=>(b(t,e).catch(e=>{(0,l.vV)("保存可用指標失敗:",e),h(e?.message||"保存可用指標失敗")}),t))}catch(e){throw(0,l.vV)("保存可用指標失敗:",e),h(e?.message||"保存可用指標失敗"),e}},[b]),N=(0,a.useCallback)(async e=>{if(!g.current)return;let t=JSON.stringify({expenseRatio:e.expenseRatio,debtRatio:e.debtRatio,emergencyFundCoverageMonths:e.emergencyFundCoverageMonths,housingExpenseRatio:e.housingExpenseRatio,financialFreedomProgress:e.financialFreedomProgress,savingsRate:e.savingsRate,investmentRatio:e.investmentRatio,debtToIncomeRatio:e.debtToIncomeRatio,netWorthGrowthRate:e.netWorthGrowthRate,
1netWorth:e.netWorth,totalLiabilities:e.totalLiabilities,leverageRatio:e.leverageRatio,currentRatio:e.currentRatio,investmentDiversification:e.investmentDiversification,excessCashRatio:e.excessCashRatio});if(p.current!==t)try{r(r=>{if(0===r.length)return r;p.current=t;let a=r.map(t=>({...t,value:parseFloat(c(t.type,e).toFixed(1))}));return s(t=>{let r=t.map(t=>({...t,value:parseFloat(c(t.type,e).toFixed(1))}));return b(a,r).catch(e=>{(0,l.vV)("保存指標值失敗:",e)}),r}),a})}catch(e){(0,l.vV)("更新指標值失敗:",e)}},[b]);return(0,a.useEffect)(()=>(e&&(x.current=null,y.current=0,w()),()=>{v.current&&(clearTimeout(v.current),v.current=null)}),[e,w]),{financialIndicators:t,availableIndicators:o,isLoading:u,error:f,loadIndicators:w,saveIndicators:j,saveAvailableIndicators:S,updateIndicatorValues:N}}},93027:(e,t,r)=>{r.d(t,{A:()=>d});var a=r(31615),n=r(24571),i=r(15418),l=r(18654),o=r(76458),s=r(73521);let d=()=>{let{user:e,loading:t,viewingUserId:r,viewingUserEmail:d}=(0,s.A)(),[c,u]=(0,a.useState)(null),[m,f]=(0,a.useState)(!0),h=e?.uid??null,p=e?.email??null,g=(0,a.useMemo)(()=>r||h,[r,h]),b=(0,a.useMemo)(()=>g?e&&e.uid===g?e:{uid:g,email:d??p??null,emailVerified:e?.emailVerified??!1,displayName:null,photoURL:null,phoneNumber:null,isAnonymous:!1,providerId:"firebase",metadata:{},providerData:[],refreshToken:"",tenantId:null,delete:async()=>{},getIdToken:async()=>"",getIdTokenResult:async()=>({}),reload:async()=>{},toJSON:()=>({})}:null,[g,d,p,e]),x=(0,a.useMemo)(()=>i.Ik({email:i.Yj().email().nullable().optional(),displayName:i.Yj().nullable().optional(),referralCode:i.Yj().optional()}).passthrough(),[]);return(0,a.useEffect)(()=>{if(t)return void f(!0);if(!g){u(null),f(!1);return}if(!o.db)return void f(!0);let e=!1;return(async()=>{f(!0);try{let t=(0,n.doc)(o.db,"users",g),r=await (0,n.getDoc)(t);if(e)return;if(!r.exists()){u({uid:g,email:d??p??null,displayName:null}),e||f(!1);return}let a=r.data(),i=x.parse(a),l=d??i.email??p??null;u({uid:g,email:l,displayName:i.displayName??null,referralCode:i.referralCode,...a})}catch(t){if(e)return;(0,l.vV)("[useUserData] Error fetching user document:",{error:t,meta:{targetUserId:g}}),u(null)}finally{e||f(!1)}})(),()=>{e=!0}},[t,g,d,p,x]),{currentUser:b,userData:c,loading:m}}},94170:(e,t,r)=>{r.d(t,{a:()=>i});var a=r(73521),n=r(41178);function i(e=!1){let{viewingUserId:t,viewingUserEmail:r}=(0,a.A)(),{toast:l}=(0,n.dj)(),o=!!t,s=(t=!0)=>!!o&&!e&&(t&&l({title:"檢視模式",description:"目前為唯讀模式,無法修改資料",variant:"destructive"}),!0);return{isViewMode:o,isEditableViewMode:o&&e,viewingUserId:t,viewingUserEmail:r,checkViewMode:s,preventInViewMode:(e,t=!0)=>{s(t)||e()}}}},97839:(e,t,r)=>{r.d(t,{SQ:()=>m,_2:()=>f,lp:()=>h,mB:()=>p,rI:()=>c,ty:()=>u});var a=r(85047),n=r(31615),i=r(76490),l=r(95513),o=r(68341),s=r(72723),d=r(34961);let c=i.bL,u=i.l9;i.YJ,i.ZL,i.Pb,i.z6,n.forwardRef(({className:e,inset:t,children:r,...n},o)=>(0,a.jsxs)(i.ZP,{ref:o,className:(0,d.cn)("flex cursor-default gap-2 select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",t&&"pl-8",e),...n,children:[r,(0,a.jsx)(l.A,{className:"ml-auto"})]})).displayName=i.ZP.displayName,n.forwardRef(({className:e,...t},r)=>(0,a.jsx)(i.G5,{ref:r,className:(0,d.cn)("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...t})).displayName=i.G5.displayName;let m=n.forwardRef(({className:e,sideOffset:t=4,...r},n)=>(0,a.jsx)(i.ZL,{children:(0,a.jsx)(i.UC,{ref:n,sideOffset:t,className:(0,d.cn)("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:sli
1de-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...r})}));m.displayName=i.UC.displayName;let f=n.forwardRef(({className:e,inset:t,...r},n)=>(0,a.jsx)(i.q7,{ref:n,className:(0,d.cn)("relative flex cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",t&&"pl-8",e),...r}));f.displayName=i.q7.displayName,n.forwardRef(({className:e,children:t,checked:r,...n},l)=>(0,a.jsxs)(i.H_,{ref:l,className:(0,d.cn)("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),checked:r,...n,children:[(0,a.jsx)("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:(0,a.jsx)(i.VF,{children:(0,a.jsx)(o.A,{className:"h-4 w-4"})})}),t]})).displayName=i.H_.displayName,n.forwardRef(({className:e,children:t,...r},n)=>(0,a.jsxs)(i.hN,{ref:n,className:(0,d.cn)("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...r,children:[(0,a.jsx)("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:(0,a.jsx)(i.VF,{children:(0,a.jsx)(s.A,{className:"h-2 w-2 fill-current"})})}),t]})).displayName=i.hN.displayName;let h=n.forwardRef(({className:e,inset:t,...r},n)=>(0,a.jsx)(i.JU,{ref:n,className:(0,d.cn)("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",e),...r}));h.displayName=i.JU.displayName;let p=n.forwardRef(({className:e,...t},r)=>(0,a.jsx)(i.wv,{ref:r,className:(0,d.cn)("-mx-1 my-1 h-px bg-muted",e),...t}));p.displayName=i.wv.displayName},99185:(e,t,r)=>{r.d(t,{C:()=>d,z:()=>s});var a=r(85047),n=r(31615),i=r(34158),l=r(72723),o=r(34961);let s=n.forwardRef(({className:e,...t},r)=>(0,a.jsx)(i.bL,{className:(0,o.cn)("grid gap-2",e),...t,ref:r}));s.displayName=i.bL.displayName;let d=n.forwardRef(({className:e,...t},r)=>(0,a.jsx)(i.q7,{ref:r,className:(0,o.cn)("aspect-square h-4 w-4 rounded-full border border-primary text-primary ring-offset-background focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",e),...t,children:(0,a.jsx)(i.C1,{className:"flex items-center justify-center",children:(0,a.jsx)(l.A,{className:"h-2.5 w-2.5 fill-current text-current"})})}));d.displayName=i.q7.displayName}}]);

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.