1import{S as oe,o as Se,aa as jn,N as me,u as Me,p as ae,O as He,t as ne,r as P,s as Fe,U as Tt,e as De,R as wn,j as e,at as Xn,al as It,c1 as Rt,cj as Dn,ax as Zn,am as ke,c5 as Nn,bV as et,c6 as nt,d as tt,ai as $n,aN as at,eE as st,an as kn,e5 as Mt,bG as rt,bh as ot,eb as it,dU as Bt,as as ct,aG as At,ah as Lt,Z as Pn,eF as On,cs as $t,bj as Pt,ap as Ot,b as qt,Y as Ut,bo as zt}from"./vendor-Gb9OPHf3.js";import{H as Ft}from"./Helmet-BDSbmKca.js";import{c7 as We,bh as Ht,c8 as Wt,b$ as lt,c2 as Et,c3 as dt,au as cn,d as ln,l as Sn,u as Tn,c4 as Vt,aw as Yt,e as Kt,S as z,I as gn,v as Gt,w as Qt,y as qn,B as Z,dk as ut,co as Jt,c as E,bV as Xt,ak as Zt,b6 as ea,b7 as na,b8 as ta,h as aa,j as sa,k as ra,dl as oa,O as ia,i as ca,b5 as la,N as da,cM as ua,dm as ma,ab as pa,m as ha,o as ga,p as _a,q as xa,G as Un,H as zn,J as Fn,K as Hn}from"./index-BLnxNZb-.js";import{u as _n}from"./emptyStateConfig-5q_1Pymx.js";import{a as mt,P as ya,T as fa}from"./TransactionEditDialog-c0PWnoGS.js";import{U as In}from"./useUpcomingBills-oAakcjiY.js";import{i as dn,r as rn,a as va,b as sn,m as ja}from"./recurringMonthlyCost-NV-1Oish.js";import{u as pt}from"./useCategories-KORxwAhB.js";import{u as wa}from"./useDefaultView-C0oXOePq.js";import{u as Na,P as Ca}from"./PullToRefresh-D4R-XSwc.js";import{F as ba}from"./FabButton-BfxIhgNQ.js";import{V as Wn}from"./ViewToggle-DC_3nlAw.js";import{u as Da,R as ka,a as ht}from"./TransactionHistoryDialog-DULtFjVT.js";import{E as Sa}from"./EmptyState-yvCzo-eM.js";import{L as Ta}from"./LoadFailedState-m32y_G9t.js";import{I as Ia}from"./InfoTooltip-BzZ3i8EG.js";import{u as Ra,s as Ma,C as Ce}from"./zod-D_WKioNR.js";import{s as Ba}from"./showErrorToast-DozajVof.js";import{C as Aa}from"./currencySymbol-ywlRW0sp.js";import{S as Je,a as Xe,b as Ze,c as en,d as ze}from"./Select-B0sF2S7p.js";import{T as La,a as En}from"./ToggleGroup-DiipVVa-.js";import{G as $a}from"./GroupedCategorySelect-B6kJ9S8G.js";import{R as Pa}from"./ResponsiveDatePicker-CrVtcPQN.js";import{f as pe}from"./formatDate-cZNCMbUJ.js";import{C as Oa}from"./ConfirmationDialog-BaGTXnt3.js";import{M as qa}from"./MutationError-BJVUOOJ4.js";import{C as gt,a as _t,b as Cn}from"./Chart-D1M91Xy-.js";import{L as xt}from"./LineChart-QtBk8UO6.js";import{C as yt}from"./CartesianGrid-DzbdQnDH.js";import{X as ft,Y as vt}from"./YAxis-CFRrTDtQ.js";import{L as bn}from"./Line-C4yGYJq4.js";import{R as Ua,C as za,X as Fa}
1from"./generateCategoricalChart-4zyNxVr5.js";import{P as Ha,a as Wa}from"./PieChart-D7Yv8Uia.js";import{C as Ea}from"./ChartLoadError-Dsr-v3xk.js";import{i as Va,a as Ya}from"./reportableTransactions-C-feOhIo.js";import{S as Ka}from"./SubscriptionReviewBanner-Cd8FySea.js";import{T as jt}from"./TransactionIcon-YhOgpSPQ.js";import{g as Ee,i as Ga}from"./getMerchantDisplayName-5cEwyAQe.js";import{T as Qa}from"./TransactionBadge-BHE9xK8A.js";import{t as Vn,a as Ja}from"./recurrenceMath-MTgf-4fT.js";import{S as xn}from"./SwipeableItem-DXbjnITn.js";import"./index-Ci6LE_sB.js";import"./tagColors-BqF1f0N3.js";import"./useRules-BlN1snsN.js";import"./RuleSuggestionDialog-uYtOcCW9.js";import"./matchesRulePattern-DbeAHWdF.js";import"./TagBadge-zACA1ieo.js";import"./capitalize-6tlP4022.js";import"./Switch--U_-_r8V.js";import"./Collapsible-D3O7xbQi.js";import"./index-Dt_OFcSI.js";import"./AppleLogo-DgkOuGUJ.js";import"./bankLogos-4Yd93Q0E.js";import"./useIsPhoneSize-N0wWOWwD.js";import"./transactionCategories-CtUVXEyp.js";import"./normalizeMerchantName-DHqvcevH.js";import"./Textarea-Cp5u-X5r.js";import"./categoryIcons-BjgN4Om3.js";import"./normalizeCategory-DfLQp-B_.js";import"./EditRuleDialog-C3Jmyyl6.js";import"./parseLocalDate-BCu5k5-Y.js";import"./FormattedCurrencyInput-_NFu3OOu.js";import"./convert_POST.schema-B0lFgEqo.js";import"./Slider-__78gh6p.js";import"./index-B8--ZtTf.js";import"./useSplitOverrides-SiedCtQB.js";import"./Avatar-CxqAHtI4.js";import"./BarChart-BZKmRYb6.js";import"./index-BC1H005C.js";import"./AddCustomCategoryForm-DfjcK1ZV.js";import"./Calendar-B2pIkTsd.js";import"./sql-DMDdMHEE.js";import"./p2pPaymentPatterns-BZioFmpF.js";import"./useSubscriptions-DFdoS0nP.js";import"./DashboardBanner-C-Ua8dO1.js";import"./Badge-BLDRlnDv.js";import"./SwipeableItem.module-aGToWfSg.js";Se({patternId:jn.number().int().positive()});const Xa=async(n,t)=>{const a=new URLSearchParams;a.append("patternId",n.patternId.toString());const o=await fetch(`/_api/recurring/latest-transaction?${a.toString()}`,{method:"GET",...t,headers:{"Content-Type":"application/json"}});if(!o.ok){const p=oe.parse(await o.text());throw new Error(p.error)}return oe.parse(await o.text())},Za=Se({id:me()}),es=async(n,t)=>{const a=Za.parse(n),o=await fetch("/_api/recurring/delete",{method:"POST",body:oe.stringify(a),...t,headers:{"Content-Type":"application/json"}});if(!o.ok){const p=oe.parse(await o.text());throw new Error(p.error)}return oe.parse(await o.text())},wt=()=>{const n=Me(),{t}=ae();return He({mutationFn:a=>es(a),onSuccess:()=>{n.invalidateQueries({queryKey:[We]}),n.invalidateQueries({queryKey:[Ht]}),n.invalidateQueries({queryKey:In}),n.invalidateQueries({queryKey:["dashboard"]}),n.invalidateQueries({queryKey:["dashboardBudgets"]}),n.invalidateQueries({queryKey:Wt}),n.invalidateQueries({queryKey:["budgets"]}),n.invalidateQueries({queryKey:["reports"]})},onError:a=>{ne.error(t("recurring.deleteError","Failed to delete subscription: {{message}}",{message:a.message}))}})},ns=(n,t)=>P.useMemo(()=>{if(!t)return n;const a=2026,o=0,p=[{description:"Monthly Rent",amount:"1850.00",category:{id:101,slug:"housing",displayName:"Housing",icon:"home"},splitType:"shared",merchantLogoUrl:null,dayOfMonth:1},{description:"Netflix",amount:"15.99",category:{id:102,slug:"streaming",displayName:"Streaming",icon:"tv"},splitType:"personal",merchantLogoUrl:"https://pub-9191c1ede9c74f98988a8e0b80c0c46b.r2.dev/migrated/edf57b2c-92a7-41e4-a15f-c9f4d3755aa4.webp",dayOfMonth:5},{description:"Electric Bill",amount:"120.00",category:{id:105,slug:"utilities",displayName:"Utilities",icon:"zap"},splitType:"shared",merchantLogoUrl:null,dayOfMonth:8},{description:"Spotify Premium",amount:"10.99",category:{id:104,slug:"music",displayName:"Music",icon:"music"},splitType:"personal",merchantLogoUrl:null,dayOfMonth:12}],s=p.map((c,u)=>{const l=new Date(a,o,c.dayOfMonth);return{...n[u]||{id:9e4+u,householdId:1,userId:1,payerUserId:1,amount:"0",categoryId:c.category.id,description:"",transactionDate:new Date(a,o-1,c.dayOfMonth),transactionType:"expense",transferType:"none",splitType:"personal",splitMethod:null,customSplitRatio:null,user1Amount:null,user2Amount:null,plaidTransactionId:null,plaidAccountId:null,merchantLogoUrl:null,categoryIconUrl:null,isSynced:!1,isPending:!1,isRecurring:!0,recurringPatternId:null,isVoided:!1,recurrence:"monthly",dueDay:c.dayOfMonth,nextDueDate:l,notes:null,needsReview:!1,autoSplit:null,excludeFromReports:!1,cancelledAt:null,isPaused:null,pausedUntil:null,trialEndsAt:null,originalAmount:null,merchantEntityId:null,merchantWebsite:null,originalDescription:null,createdAt:new Date,updatedAt:new Date,categoryInfo:null,institutionInfo:null,tags:[],matchedTransferInfo:null,accountName:null,accountMask:null},description:c.description,amount:c.amount,transactionType:"expense",transferType:"none",isRecurring:!0,recurrence:"monthly",splitType:c.splitType,nextDueDate:l,dueDay:l.getDate(),merchantLogoUrl:c.merchantLogoUrl,needsReview:!1,excludeFromReports:!1,isVoided:!1,isSynced:!1,autoSplit:c.splitType==="shared",splitMethod:c.splitType==="shared"?"equal":null,categoryInfo:{slug:c.category.slug,displayName:c.category.displayName,icon:c.category.icon},categoryId:c.category.id}});return n.length>p.length?[...s,...n.slice(p.length)]:s},[n,t]),ts=Se({id:me(),merchantName:Fe().min(1,"Merchant name is required").optional(),amount:me().positive("Amount must be positive").optional(),recurrence:De(lt).optional(),isShared:Tt().optional(),ownerUserId:me().optional(),categoryId:me().positive("Category ID must be positive").optional(),notes:Fe().nullable().optional(),dayOfMonth:me().min(1).max(31).optional(),dayOfMonth2:me().min(1).max(31).optional()}),as=async(n,t)=>{const a=ts.parse(n),o=await fetch("/_api/recurring/update",{method:"POST",body:oe.stringify(a),...t,headers:{"Content-Type":"application/json"}});if(!o.ok){const p=oe.parse(await o.text());throw new Error(p.error)}return oe.parse(await o.text())},ss=()=>{const n=Me(),{t}=ae();return He({mutationFn:a=>as(a),onSuccess:()=>{n.invalidateQueries({queryKey:["recurringBills"]}),n.invalidateQueries({queryKey:["transactions","list"]}),n.invalidateQueries({queryKey:In}),n.invalidateQueries({queryKey:["dashboard"]}),n.invalidateQueries({queryKey:["dashboardBudgets"]})},onError:a=>{ne.error(t("recurring.updateError","Failed to update recurring bill: {{message}}",{message:a.message}))}})},rs=({subscription:n,onSuccess:t,setMutationError:a,transactionType:o="expense"})=>{const p=Et(),s=dt(),c=ss(),u=wt();return{handleSubmit:v=>{a(null);const i=v.nextDueDate.getDate(),r={description:v.description,amount:v.amount,categoryId:v.categoryId,recurrence:v.recurrence,nextDueDate:v.nextDueDate,splitType:v.splitType,payerUserId:v.payerUserId,notes:v.paymentMethod||void 0,transactionType:o,transferType:"none",isRecurring:!0,transactionDate:cn(v.nextDueDate),dueDay:i,excludeFromReports:!1};if(n){const _=n._billSource,d=n._billOriginalId,L=o==="income"?"Income updated successfully":"Subscription updated successfully";_==="pattern"&&d?c.mutate({id:d,merchantName:r.description,amount:r.amount,recurrence:r.recurrence,categoryId:r.categoryId,notes:r.notes,dayOfMonth:r.dueDay,dayOfMonth2:v.dayOfMonth2,isShared:r.splitType==="shared",ownerUserId:r.payerUserId},{onSuccess:()=>{ne.success(L),t()},onError:N=>{a(N.message)}}):s.mutate({id:n.id,description:r.description,amount:r.amount,categoryId:r.categoryId,recurrence:r.recurrence,nextDueDate:r.nextDueDate,splitType:r.splitType,payerUserId:r.payerUserId,notes:r.notes||void 0,transactionDate:r.transactionDate,dueDay:r.dueDay,isRecurring:!0},{onSuccess:()=>{ne.success(L),t()},onError:N=>{a(N.message)}})}else{const _=o==="income"?"Income saved successfully":"Subscription saved successfully";p.mutate(r,{onSuccess:()=>{ne.success(_),t()},onError:d=>{a(d.message)}})}},handleDelete:async()=>
1{if(n)try{const v=n._billSource,i=n._billOriginalId;v==="pattern"&&i?await u.mutateAsync({id:i}):await s.mutateAsync({id:n.id,isRecurring:!1}),t()}catch(v){throw v}},isSubmitting:p.isPending||s.isPending&&s.variables?.isRecurring!==!1||c.isPending,isDeleting:u.isPending||s.isPending&&s.variables?.isRecurring===!1}},os="_form_1s8ay_1",is="_infoBanner_1s8ay_9",cs="_infoIcon_1s8ay_19",ls="_field_1s8ay_33",ds="_error_1s8ay_45",us="_twoColumnRow_1s8ay_51",ms="_twoColumnRowCompact_1s8ay_57",ps="_amountInputWrapper_1s8ay_73",hs="_dollarIcon_1s8ay_79",gs="_amountInput_1s8ay_73",_s="_accountContainer_1s8ay_91",xs="_accountIconWrapper_1s8ay_103",ys="_accountContent_1s8ay_115",fs="_accountLabel_1s8ay_124",vs="_accountValue_1s8ay_133",js="_accountMask_1s8ay_138",ws="_datePickerTrigger_1s8ay_143",Ns="_budgetTypeToggle_1s8ay_198",Cs="_budgetTypeItem_1s8ay_207",bs="_footer_1s8ay_235",Ds="_destructiveActions_1s8ay_245",ks="_actionButtons_1s8ay_252",Ss="_cancelButton_1s8ay_259",Ts="_saveButton_1s8ay_260",Is="_deleteButton_1s8ay_281",Rs="_skeletonBanner_1s8ay_334",Ms="_skeletonInput_1s8ay_339",Bs="_historyRow_1s8ay_343",w={form:os,infoBanner:is,infoIcon:cs,field:ls,error:ds,twoColumnRow:us,twoColumnRowCompact:ms,amountInputWrapper:ps,dollarIcon:hs,amountInput:gs,accountContainer:_s,accountIconWrapper:xs,accountContent:ys,accountLabel:fs,accountValue:vs,accountMask:js,datePickerTrigger:ws,budgetTypeToggle:Ns,budgetTypeItem:Cs,footer:bs,destructiveActions:Ds,actionButtons:ks,cancelButton:Ss,saveButton:Ts,deleteButton:Is,skeletonBanner:Rs,skeletonInput:Ms,historyRow:Bs},As=n=>Se({description:Fe().trim().min(1,n("recurring.form.nameRequired","Add a name.")),amount:jn.number().positive(n("recurring.form.amountRequired","Add an amount above zero.")),categoryId:me().positive(n("recurring.form.categoryRequired","Pick a category.")),recurrence:De(lt),nextDueDate:jn.date().optional(),dayOfMonth:me().min(1).max(31).optional(),dayOfMonth2:me().min(1).max(31).optional(),splitType:De(["shared","personal"]),payerUserId:me().positive(n("recurring.form.payerRequired","Pick who pays.")),paymentMethod:Fe().optional()}),Yn=(n,t)=>{if(!t.startsWith("en"))return"";if(n>3&&n<21)return"th";switch(n%10){case 1:return"st";case 2:return"nd";case 3:return"rd";default:return"th"}},yn=n=>{const t=new Date;switch(n){case"weekly":t.setDate(t.getDate()+7);break;case"biweekly":t.setDate(t.getDate()+14);break;case"semimonthly":t.setDate(t.getDate()+15);break;case"quarterly":t.setMonth(t.getMonth()+3);break;case"yearly":t.setFullYear(t.getFullYear()+1);break;case"monthly":default:t.setMonth(t.getMonth()+1);break}return t},Kn=({subscription:n,onSuccess:t,onCancel:a,className:o,mode:p="expense"})=>{const{t:s,i18n:c}=ae(),u=c.language||"en",l=P.useMemo(()=>As(s),[s]),f=p==="income",[v,i]=P.useState(!1),[r,_]=P.useState(!1),[d,L]=P.useState(null),[N,x]=P.useState(!1),[H,R]=P.useState(null),M=ln(),{currency:h}=Sn(),{authState:B}=Tn(),{data:O,isFetching:D}=Vt(),{data:k,isFetching:y}=pt(),{data:m,isFetching:j}=Yt(),b=B.type==="authenticated"?B.user.id:null,U=P.useMemo(()=>{if(!m?.members||!b)return null;const T=m.members.find($=>$.userId!==b);return T?{id:T.userId,firstName:T.firstName}:null},[m,b]),Y=P.useMemo(()=>k?.categories?f?k.categories.filter(T=>T.categoryGroup==="Income"):k.categories:[],[k,f]),{handleSubmit:ie,handleDelete:G,isSubmitting:xe,isDeleting:te}=rs({subscription:n,onSuccess:t,setMutationError:L,transactionType:f?"income":"expense"}),se=P.useMemo(()=>{if(n){const T=n.splitType==="unclassified"?"shared":n.splitType,$=n.nextDueDate?new Date(n.nextDueDate):new Date;return{description:n.description,amount:parseFloat(n.amount),categoryId:n.categoryId??void 0,recurrence:n.recurrence||"monthly",nextDueDate:$,dayOfMonth:$.getDate(),dayOfMonth2:n.dayOfMonth2||15,splitType:T,payerUserId:n.payerUserId||b||0,paymentMethod:n.notes||""}}return{description:"",amount:void 0,categoryId:void 0,recurrence:"monthly",nextDueDate:yn("monthly"),dayOfMonth:new Date().getDate(),dayOfMonth2:15,splitType:f?"personal":"shared",payerUserId:b||0,paymentMethod:""}},[]),{register:V,handleSubmit:le,control:ee,reset:ye,watch:he,setValue:fe,formState:{errors:J}}=Ra({resolver:Ma(l),defaultValues:se});P.useEffect(()=>{if(n){const T=n.splitType==="unclassified"?"shared":n.splitType,$=n.recurrence||"monthly",de=n.nextDueDate?new Date(n.nextDueDate):new Date;ye({description:n.description,amount:parseFloat(n.amount),categoryId:n.categoryId??void 0,recurrence:$,nextDueDate:de,dayOfMonth:de.getDate(),dayOfMonth2:n.dayOfMonth2||15,splitType:T,payerUserId:n.payerUserId||b||void 0,paymentMethod:n.notes||""})}},[n,ye,b]),P.useEffect(()=>{if(!(!k?.categories||Y.length===0))if(n)n.categoryId&&fe("categoryId",n.categoryId);else{const T=f?Y[0]:Y.find($=>$.slug==="streaming")||Y[0];ye({description:"",amount:void 0,categoryId:T.id,recurrence:"monthly",nextDueDate:yn("monthly"),dayOfMonth:new Date().getDate(),dayOfMonth2:15,splitType:f?"personal":"shared",payerUserId:b||void 0,paymentMethod:""})}},[k,Y,n,f,b,ye,fe]);const Be=()=>{_(!0)},Ve=async()=>{try{await G(),_(!1),ne.success(f?s("recurring.form.removedIncome","Removed from recurring income"):s("recurring.form.removedExpense","Removed from recurring expenses"))}catch(T){Ba(T,{title:s("recurring.form.deleteFailed","Couldn't remove it")})}},Ye=T=>{let $=T.nextDueDate||new Date;if(T.recurrence==="semimonthly"){const de=new Date;$=new Date(de.getFullYear(),de.getMonth(),T.dayOfMonth||1)}ie({...T,nextDueDate:$,dayOfMonth2:T.dayOfMonth2})}
1,Ke=he("categoryId"),un=P.useMemo(()=>k?.categories?.find(T=>T.id===Ke)?.slug||"",[k,Ke]),mn=T=>{const $=k?.categories.find(de=>de.slug===T);$&&fe("categoryId",$.id)},ce=he("description"),pn=Kt(ce,500),{transactions:Ae}=Da(pn),Ge=Ae.length,Le=he("splitType");wn.useEffect(()=>{!n&&f&&Le!=="personal"&&fe("splitType","personal")},[f,n,Le,fe]);const _e=he("recurrence");wn.useEffect(()=>{n||!_e||fe("nextDueDate",yn(_e))},[_e,n,fe]);const $e=n?.accountName,Qe=n?.accountMask,Pe=!!$e;return D||y||j||!b?e.jsxs("div",{className:`${w.form} ${o||""}`,children:[e.jsx(z,{className:w.skeletonBanner}),e.jsx(z,{className:w.skeletonInput}),e.jsxs("div",{className:w.twoColumnRow,children:[e.jsx(z,{className:w.skeletonInput}),e.jsx(z,{className:w.skeletonInput})]}),e.jsxs("div",{className:w.twoColumnRow,children:[e.jsx(z,{className:w.skeletonInput}),e.jsx(z,{className:w.skeletonInput})]}),e.jsxs("div",{className:w.twoColumnRow,children:[e.jsx(z,{className:w.skeletonInput}),e.jsx(z,{className:w.skeletonInput})]}),e.jsx(z,{className:w.skeletonInput})]}):e.jsxs("form",{onSubmit:le(Ye),className:`${w.form} ${o||""}`,children:[e.jsxs("div",{className:w.infoBanner,children:[e.jsx(Xn,{size:18,className:w.infoIcon}),e.jsx("p",{children:f?s("recurring.form.bannerIncome","Halfway will track this recurring income and include it in your reports."):Pe?s("recurring.form.bannerSynced","This recurring expense is synced with your bank. Halfway will send you a reminder 3 days before each renewal date."):s("recurring.form.bannerManual","Halfway will automatically create a transaction on each renewal date and send you a reminder 3 days before.")})]}),!f&&e.jsxs("div",{className:w.field,children:[e.jsx("label",{children:s("recurring.form.expenseType","Expense type")}),e.jsx(Ce,{name:"splitType",control:ee,render:({field:T})=>e.jsxs(La,{type:"single",value:T.value,onValueChange:$=>$&&T.onChange($),className:w.budgetTypeToggle,children:[e.jsx(En,{value:"shared",className:w.budgetTypeItem,children:s("common.shared","Shared")}),e.jsx(En,{value:"personal",className:w.budgetTypeItem,children:s("common.personal","Personal")})]})}),J.splitType&&e.jsx("p",{className:w.error,children:J.splitType.message})]}),e.jsxs("div",{className:w.field,children:[e.jsx("label",{htmlFor:"description",children:s("recurring.form.name","Name")}),e.jsx(gn,{id:"description",placeholder:s("recurring.form.namePlaceholder","e.g., Netflix, Rent"),...V("description")}),J.description&&e.jsx("p",{className:w.error,children:J.description.message})]}),e.jsxs("div",{className:f?w.field:w.twoColumnRowCompact,children:[e.jsxs("div",{className:w.field,children:[e.jsx("label",{htmlFor:"amount",children:s("recurring.form.amount","Amount")}),e.jsx(Ce,{name:"amount",control:ee,render:({field:T})=>e.jsxs("div",{className:w.amountInputWrapper,children:[e.jsx(Aa,{currency:h,size:18,className:w.dollarIcon}),e.jsx(gn,{id:"amount",type:"text",inputMode:"decimal",placeholder:"0.00",className:w.amountInput,value:H!==null?qn(H):qn(T.value),onChange:$=>{const de=Gt($.target.value);let je=Qt(de);const Oe=je.indexOf(".");Oe!==-1&&(je=je.slice(0,Oe+1)+je.slice(Oe+1).replace(/\./g,"").slice(0,2)),R(je),T.onChange(je===""||je==="."?void 0:Number(je))},onBlur:()=>{R(null),T.onBlur()}})]})}),J.amount&&e.jsx("p",{className:w.error,children:J.amount.message})]}),!f&&e.jsxs("div",{className:w.field,children:[e.jsx("label",{htmlFor:"payerUserId",children:s("recurring.form.whoPays","Who pays")}),e.jsx(Ce,{name:"payerUserId",control:ee,render:({field:T})=>e.jsxs(Je,{onValueChange:$=>T.onChange(parseInt($,10)),value:T.value?.toString()??"",children:[e.jsx(Xe,{id:"payerUserId",children:e.jsx(Ze,{placeholder:s("recurring.form.selectWhoPays","Select who pays")})}),e.jsxs(en,{children:[b&&e.jsx(ze,{value:b.toString(),children:s("recurring.form.me","Me")}),U&&e.jsx(ze,{value:U.id.toString(),children:U.firstName})]})]},n?.id??"new")}),J.payerUserId&&e.jsx("p",{className:w.error,children:J.payerUserId.message})]})]}),Pe&&e.jsxs("div",{className:w.accountContainer,children:[e.jsx("div",{className:w.accountIconWrapper,children:e.jsx(It,{size:14})}),e.jsxs("div",{className:w.accountContent,children:[e.jsx("span",{className:w.accountLabel,children:s("recurring.form.account","Account")}
1),e.jsxs("span",{className:w.accountValue,children:[$e,Qe&&e.jsxs("span",{className:w.accountMask,children:[" â¢â¢",Qe]})]})]})]}),e.jsxs("div",{className:w.field,children:[e.jsx("label",{children:s("recurring.form.category","Category")}),e.jsx($a,{value:un,onValueChange:mn,transactionType:f?"income":"expense",categories:k?.categories||[],showAddCustom:!f}),J.categoryId&&e.jsx("p",{className:w.error,children:J.categoryId.message})]}),e.jsxs("div",{className:w.twoColumnRow,children:[e.jsxs("div",{className:w.field,children:[e.jsx("label",{htmlFor:"recurrence",children:s("recurring.form.frequency","Frequency")}),e.jsx(Ce,{name:"recurrence",control:ee,render:({field:T})=>e.jsxs(Je,{onValueChange:T.onChange,value:T.value,children:[e.jsx(Xe,{id:"recurrence",children:e.jsx(Ze,{placeholder:s("recurring.form.selectFrequency","Select frequency")})}),e.jsx(en,{children:ka.map($=>e.jsx(ze,{value:$.value,children:s($.labelKey,$.defaultLabel)},$.value))})]},n?.id??"new")}),J.recurrence&&e.jsx("p",{className:w.error,children:J.recurrence.message})]}),he("recurrence")==="semimonthly"?e.jsxs("div",{className:w.field,children:[e.jsx("label",{children:s("recurring.form.dueDates","Due dates")}),e.jsxs("div",{className:w.twoColumnRowCompact,children:[e.jsx(Ce,{name:"dayOfMonth",control:ee,render:({field:T})=>e.jsxs(Je,{onValueChange:$=>T.onChange(parseInt($,10)),value:T.value?.toString()||"1",children:[e.jsx(Xe,{children:e.jsx(Ze,{placeholder:"1st"})}),e.jsx(en,{children:Array.from({length:31},($,de)=>de+1).map($=>e.jsxs(ze,{value:$.toString(),children:[$,Yn($,u)]},$))})]})}),e.jsx(Ce,{name:"dayOfMonth2",control:ee,render:({field:T})=>e.jsxs(Je,{onValueChange:$=>T.onChange(parseInt($,10)),value:T.value?.toString()||"15",children:[e.jsx(Xe,{children:e.jsx(Ze,{placeholder:"15th"})}),e.jsx(en,{children:Array.from({length:31},($,de)=>de+1).map($=>e.jsxs(ze,{value:$.toString(),children:[$,Yn($,u)]},$))})]})})]}),(J.dayOfMonth||J.dayOfMonth2)&&e.jsx("p",{className:w.error,children:J.dayOfMonth?.message||J.dayOfMonth2?.message})]}):e.jsxs("div",{className:w.field,children:[e.jsx("label",{children:s("recurring.form.renewalDate","Renewal date")}),e.jsx(Ce,{name:"nextDueDate",control:ee,render:({field:T})=>e.jsx(Pa,{selected:T.value,onSelect:T.onChange,open:v,onOpenChange:i,trigger:e.jsxs(Z,{variant:"outline",className:w.datePickerTrigger,children:[e.jsx("span",{children:T.value?pe(T.value):s("recurring.form.selectDate","Select a date")}),e.jsx(Rt,{size:16})]})})}),J.nextDueDate&&e.jsx("p",{className:w.error,children:J.nextDueDate.message})]})]}),e.jsxs("div",{className:w.field,children:[e.jsx("label",{htmlFor:"paymentMethod",children:s("recurring.form.paymentMethod","Payment method (optional)")}),e.jsx(gn,{id:"paymentMethod",placeholder:s("recurring.form.paymentMethodPlaceholder","e.g. Chase Sapphire, Joint Checking"),...V("paymentMethod")}),J.paymentMethod&&e.jsx("p",{className:w.error,children:J.paymentMethod.message})]}),ce&&Ge>0&&e.jsxs("button",{type:"button",onClick:()=>x(!0),className:w.historyRow,children:[e.jsx(Dn,{size:20}),e.jsx("span",{children:s("recurring.form.seeHistory","See history ({{count}})",{count:Ge})})]}),d&&e.jsx(qa,{error:d}),e.jsxs("div",{className:w.footer,children:[n&&e.jsx("div",{className:w.destructiveActions,children:e.jsxs(Z,{type:"button",variant:"outline",onClick:Be,disabled:te,className:w.deleteButton,children:[e.jsx(Zn,{size:16}),f?s("recurring.form.stopTracking","Stop tracking"):s("common.delete","Delete")]})}),e.jsxs("div",{className:w.actionButtons,children:[e.jsx(Z,{type:"button",variant:"outline",onClick:a||t,className:w.cancelButton,children:s("common.cancel","Cancel")}),e.jsx(Z,{type:"submit",disabled:xe,"aria-busy":xe,className:w.saveButton,children:xe?n?s("common.updating","Updating..."):s("common.adding","Adding..."):n?s("recurring.form.update","Update"):s("recurring.form.add","Add")})]})]}),n&&e.jsx(Oa,{open:r,onOpenChange:_,title:f?s("recurring.form.stopIncomeTitle","Stop tracking this income?"):s("recurring.form.deleteTitle","Delete this recurring expense?"),description:f?s("recurring.form.stopIncomeBody","It comes off your recurring income. Past transactions stay as they are."):s("recurring.form.deleteBody","It comes off your recurring expenses for good. Past transactions stay as they are."),confirmLabel:f?s("recurring.form.stopTracking","Stop tracking"):s("common.delete","Delete"),onConfirm:Ve,isLoading:te}),N&&ce&&(M?e.jsx(mt,{open:N,onOpenChange:x,merchantName:ce,merchantIcon:n?.merchantLogoUrl||void 0,onTransactionClick:()=>x(!1)}):e.jsx(ht,{open:N,onOpenChange:x,merchantName:ce,merchantIcon:n?.merchantLogoUrl||void 0,onTransactionClick:()=>x(!1)}))]})},Ls="_card_1p6gf_2",$s="_chartWrapper_1p6gf_11",Ps="_emptyState_1p6gf_16",Os="_skeletonContainer_1p6gf_28",qs="_skeletonChart_1p6gf_33",be={card:Ls,chartWrapper:$s,emptyState:Ps,skeletonContainer:Os,skeletonChart:qs},Us=({transactions:n=[],history:t,isLoading:a=!1,billTypeFilter:o="all",className:p})=>{const{t:s,i18n:c}=ae(),u=P.useMemo(()=>
1{if(a||n.length===0||!t)return[];const f=o==="all"?n:n.filter(_=>_.billType===o);if(f.length===0)return[];const v=new Set(f.map(_=>ut(_)).filter(_=>_!=null)),i=new Map;for(const _ of t.rows)v.has(_.key)&&i.set(_.month,(i.get(_.month)??0)+_.amount);const r=new Intl.DateTimeFormat(c.language||"en",{month:"short",timeZone:"UTC"});return t.months.map(_=>({monthLabel:r.format(new Date(`${_}-01T00:00:00Z`)),amount:Math.round((i.get(_)??0)*100)/100}))},[n,t,a,o,c.language]);if(a)return e.jsx("div",{className:`${be.card} ${p??""}`,children:e.jsx("div",{className:be.skeletonContainer,children:e.jsx(z,{className:be.skeletonChart})})});if(u.length===0)return e.jsx("div",{className:`${be.card} ${p??""}`,children:e.jsx("div",{className:be.emptyState,children:e.jsx("p",{children:o==="subscription"?s("recurring.trends.emptySubs","No active subscriptions to show trends."):o==="bill"?s("recurring.trends.emptyBills","No active bills to show trends."):o==="savings"?s("recurring.trends.emptySavings","No active savings to show trends."):o==="other"?s("recurring.trends.emptyOther","No other active items to show trends."):s("recurring.trends.emptyAll","No active items to show trends.")})})});const l={amount:{label:s("recurring.trends.paid","Paid"),color:"var(--primary)"}};return e.jsx("div",{className:`${be.card} ${p??""}`,children:e.jsx("div",{className:be.chartWrapper,children:e.jsx(gt,{config:l,children:e.jsxs(xt,{data:u,margin:{top:10,right:10,left:0,bottom:0},children:[e.jsx(yt,{strokeDasharray:"3 3",vertical:!1}),e.jsx(ft,{dataKey:"monthLabel",tickLine:!1,axisLine:!1,tickMargin:10,minTickGap:0,interval:0}),e.jsx(vt,{tickLine:!1,axisLine:!1,tickFormatter:f=>`${f}`,width:40}),e.jsx(_t,{content:e.jsx(Cn,{})}),e.jsx(bn,{type:"monotone",dataKey:"amount",stroke:"var(--color-amount)",strokeWidth:2,dot:{r:4,fill:"var(--color-amount)"},activeDot:{r:6}})]})})})})},zs="_card_vsrlx_2",Fs="_chartSection_vsrlx_21",Hs="_chartWrapper_vsrlx_29",Ws="_centerLabel_vsrlx_35",Es="_centerLabelText_vsrlx_48",Vs="_centerLabelTextActive_vsrlx_60",Ys="_centerLabelAmount_vsrlx_66",Ks="_listSection_vsrlx_74",Gs="_row_vsrlx_79",Qs="_rowSelected_vsrlx_95",Js="_rowContent_vsrlx_101",Xs="_colorDot_vsrlx_108",Zs="_rowInfo_vsrlx_116",er="_rowName_vsrlx_124",nr="_rowAmount_vsrlx_130",tr="_emptyState_vsrlx_138",ar="_skeletonContainer_vsrlx_152",sr="_skeletonCircle_vsrlx_161",rr="_skeletonLegend_vsrlx_167",or="_skeletonLegendItem_vsrlx_174",X={card:zs,chartSection:Fs,chartWrapper:Hs,centerLabel:Ws,centerLabelText:Es,centerLabelTextActive:Vs,centerLabelAmount:Ys,listSection:Ks,row:Gs,rowSelected:Qs,rowContent:Js,colorDot:Xs,rowInfo:Zs,rowName:er,rowAmount:nr,emptyState:tr,skeletonContainer:ar,skeletonCircle:sr,skeletonLegend:rr,skeletonLegendItem:or},nn=["hsl(35, 45%, 45%)","hsl(350, 65%, 60%)","hsl(320, 50%, 70%)","hsl(260, 50%, 65%)","hsl(160, 50%, 55%)","hsl(200, 60%, 55%)","hsl(45, 70%, 55%)","hsl(140, 45%, 40%)","hsl(20, 65%, 55%)","hsl(280, 40%, 55%)"],ir=n=>{const{cx:t,cy:a,innerRadius:o,outerRadius:p,startAngle:s,endAngle:c,fill:u}=n,l=Math.PI/180,f=(s+c)/2,v=6,i=t+v*Math.cos(-f*l),r=a+v*Math.sin(-f*l);return e.jsx("g",{children:e.jsx(Fa,{cx:i,cy:r,innerRadius:o,outerRadius:p+6,startAngle:s,endAngle:c,fill:u,style:{filter:"drop-shadow(0px 2px 4px rgba(0,0,0,0.15))"}})})},cr=({subscriptions:n=[],currency:t,isLoading:a=!1,view:o="all",className:p,billTypeFilter:s="all"})=>{const[c,u]=P.useState(null),{t:l}=ae(),f={"Home & Utilities":"homeUtilities","Health & Wellness":"healthWellness","Entertainment & Digital":"entertainmentDigital",Transportation:"transportation","Food & Dining":"foodDining","Financial & Insurance":"financialInsurance","Shopping & Lifestyle":"shoppingLifestyle",Other:"other"},v=R=>f[R]?l(`recurring.breakdown.groups.${f[R]}`,R):R,i=ln(),r=Jt("(min-width: 1024px) and (max-width: 1023px)"),{chartData:_,totalAmount:d}=P.useMemo(()=>{if(a||n.length===0)return{chartData:[],totalAmount:0};const R={rent:"Home & Utilities",mortgage:"Home & Utilities",utilities:"Home & Utilities",internet:"Home & Utilities",phone_bill:"Home & Utilities",home_insurance:"Home & Utilities",hoa_fees:"Home & Utilities",property_taxes:"Home & Utilities",home_maintenance:"Home & Utilities",healthcare:"Health & Wellness",gym_fitness:"Health & Wellness",personal_care:"Health & Wellness",streaming:"Entertainment & Digital",music:"Entertainment & Digital",apps_software:"Entertainment & Digital",entertainment:"Entertainment & Digital",hobbies:"Entertainment & Digital",electronics:"Entertainment & Digital",gas_fuel:"Trans
1portation",car_payment:"Transportation",car_insurance:"Transportation",car_maintenance:"Transportation",public_transit:"Transportation",parking:"Transportation",ride_share:"Transportation",groceries:"Food & Dining",dining_out:"Food & Dining",coffee_shops:"Food & Dining",food_delivery:"Food & Dining",alcohol:"Food & Dining",insurance:"Financial & Insurance",bank_fees:"Financial & Insurance",taxes:"Financial & Insurance",student_loan:"Financial & Insurance",government:"Financial & Insurance",professional_services:"Financial & Insurance",credit_card_payment:"Financial & Insurance",investment:"Financial & Insurance",shopping:"Shopping & Lifestyle",gifts:"Shopping & Lifestyle",pets:"Shopping & Lifestyle",childcare:"Shopping & Lifestyle",travel:"Shopping & Lifestyle",education:"Shopping & Lifestyle",donations:"Shopping & Lifestyle",internal_transfer:"Other",savings_transfer:"Other",reimbursement:"Other",refund:"Other",other:"Other",salary:"Other",business_income:"Other",freelance:"Other",investment_income:"Other",rental_income:"Other",interest_income:"Other",retirement_income:"Other",tax_refund:"Other",income_other:"Other",cash_and_checks:"Other"},M=D=>R[D]||"Other",h={};n.forEach(D=>{if(s!=="all"&&D.billType!==s||!dn(D))return;const k=D.categoryInfo?.slug??"other",y=M(k),m=y,j=rn(D);h[y]||(h[y]={name:m,amount:0}),h[y].amount+=j});const B=Object.values(h).reduce((D,k)=>D+k.amount,0);return{chartData:Object.entries(h).map(([D,{name:k,amount:y}],m)=>({id:D,name:k,value:y,color:nn[m%nn.length],percentage:B>0?y/B*100:0})).filter(D=>D.value>0).sort((D,k)=>k.value-D.value).map((D,k)=>({...D,color:nn[k%nn.length]})),totalAmount:B}},[n,a,s]),L=(R,M)=>{u(h=>h===M?null:M)},N=P.useMemo(()=>{if(c!==null&&_[c]){const M=_[c];return{label:v(M.name),amount:M.value,isTotal:!1}}let R=l("recurring.breakdown.totalAll","Total/mo");return s==="subscription"?R=l("recurring.breakdown.totalSubs","Total Subs/mo"):s==="bill"?R=l("recurring.breakdown.totalBills","Total Bills/mo"):s==="savings"?R=l("recurring.breakdown.totalSavings","Total Savings/mo"):s==="other"&&(R=l("recurring.breakdown.totalOther","Total Other/mo")),{label:R,amount:d,isTotal:!0}},[c,_,d,s,l]);if(a)return e.jsx("div",{className:`${X.card} ${p??""}`,children:e.jsxs("div",{className:X.skeletonContainer,children:[e.jsx(z,{className:X.skeletonCircle}),e.jsx("div",{className:X.skeletonLegend,children:[1,2,3,4].map(R=>e.jsx(z,{className:X.skeletonLegendItem},R))})]})});if(_.length===0)return e.jsx("div",{className:`${X.card} ${p??""}`,children:e.jsx("div",{className:X.emptyState,children:e.jsx("p",{children:s==="subscription"?l("recurring.breakdown.emptySubs","No active subscriptions to analyze."):s==="bill"?l("recurring.breakdown.emptyBills","No active bills to analyze."):s==="savings"?l("recurring.breakdown.emptySavings","No active savings to analyze."):s==="other"?l("recurring.breakdown.emptyOther","No other active items to analyze."):l("recurring.breakdown.emptyAll","No active items to analyze.")})})});const x=r?110:i?80:"68%",H=r?125:i?90:"78%";return e.jsxs("div",{className:`${X.card} ${p??""}`,children:[e.jsx("div",{className:X.chartSection,children:e.jsxs("div",{className:X.chartWrapper,children:[e.jsx(Ua,{width:"100%",height:"100%",children:e.jsx(Ha,{children:e.jsx(Wa,{data:_,dataKey:"value",nameKey:"name",cx:"50%",cy:"50%",innerRadius:x,outerRadius:H,paddingAngle:4,cornerRadius:8,stroke:"none",activeIndex:c??-1,activeShape:ir,onClick:L,isAnimationActive:!0,animationDuration:1800,animationBegin:100,animationEasing:"ease-out",children:_.map((R,M)=>e.jsx(za,{fill:R.color,style:{cursor:"pointer",outline:"none"}},`cell-${M}`))})})}),e.jsxs("div",{className:X.centerLabel,children:[e.jsx("span",{className:`${X.centerLabelText} ${N.isTotal?"":X.centerLabelTextActive}`,children:N.label}),e.jsx("span",{className:X.centerLabelAmount,children:E(N.amount,t,{hideDecimals:!0,compact:!0})})]})]})}),e.jsx("div",{className:X.listSection,children:_.map((R,M)=>{const h=c===M;return e.jsx("div",{className:`${X.row} ${h?X.rowSelected:""}`,onClick:()=>L(null,M),children:e.jsxs("div",{className:X.rowContent,children:[e.jsx("div",{className:X.colorDot,style:{backgroundColor:R.color}}),e.jsxs("div",{className:X.rowInfo,children:[e.jsx("span",{className:X.rowName,children:v(R.name)}),e.jsxs("span",{className:X.rowAmount,children:[E(R.value,t,{}),l("recurring.perMonth","/mo")," · ",R.percentage.toFixed(1),"%"]})]})]})},R.id)})})]})},lr="_card_1wm7n_2",dr="_chartWrapper_1wm7n_14",ur="_emptyState_1wm7n_19",mr="_skeletonContainer_1wm7n_31",pr="_skeletonChart_1wm7n_36",hr="_summaryContainer_1wm7n_42",gr="_summary_1wm7n_42",we={card:lr,chartWrapper:dr,emptyState:ur,skeletonContainer:mr,skeletonChart:pr,summaryContainer:hr,summary:gr},_r=n=>{const{cx:t,cy:a,index:o}=n;return o===5?e.jsx("circle",{cx:t,cy:a,r:4,fill:"var(--background)",stroke:"var(--color-currentAmount)",strokeWidth:2},`dot-${o}`):e.jsx("circle",{cx:t,cy:a,r:0,fill:"none",stroke:"none"},`dot-${o}`)},xr=n=>{const{cx:t,cy:a,index:o}=n;return o===5?e.jsx("circle",{cx:t,cy:a,r:6,fill:"var(--background)",stroke:"var(--color-currentAmount)",strokeWidth:2},`active-dot-${o}`):e.jsx("circle",{cx:t,cy:a,r:0,fill:"none",stroke:"none"},`active-dot-${o}`)},yr=n=>{const{x:t,y:a,payload:o,soFarLabel:p}=n,s=o.index===5;return e.jsxs("g",{transform:`translate(${t},${a})`,children:[e.jsx("text",{x:0,y:0,dy:16,textAnchor:"middle",children:o.value}),s&&e.jsx("text",{x:0,y:0,dy:30,textAnchor:"middle",style:{fontSize:"0.65rem"},children:p})]})},fr=({currency:n="USD",isLoading:t=!1,className:a})=>{const{t:o,i18n:p}=ae(),{startDate:s,endDate:c,monthsList:u}=P.useMemo(()=>{const x=new Date,H=new Date(x.getFullYear(),x.getMonth()-5,1),R=new Date(x.getFullYear(),x.getMonth()+1,0,23,59,59,999),M=[];for(let h=5;h>=0;h--)M.push(new Date(x.getFullYear(),x.getMonth()-h,1));return{startDate:H,endDate:R,monthsList:M}},[]),{data:l,isLoading:f,isError:v,refetch:i}=Xt({startDate:s.toISOString(),endDate:c.toISOString(),transactionType:"income",paidBy:"me",limit:5e3}),r=t||f,{chartData:_,totalIncome:d}=P.useMemo(()=>
1{if(!l||l.transactions.length===0)return{chartData:[],totalIncome:0};let x=0;return{chartData:u.map(M=>{const h=new Intl.DateTimeFormat(p.language||"en-US",{month:"short"}).format(M),O=l.transactions.filter(D=>{const k=new Date(D.transactionDate);return k.getFullYear()===M.getFullYear()&&k.getMonth()===M.getMonth()&&Va(D)&&!Ya(D)}).reduce((D,k)=>D+parseFloat(k.amount),0);return x+=O,{monthLabel:h,rawAmount:parseFloat(O.toFixed(2))}}).map((M,h,B)=>{let O=null,D=null;return h<B.length-1&&(O=M.rawAmount),h>=B.length-2&&(D=M.rawAmount),{monthLabel:M.monthLabel,amount:O,currentAmount:D}}),totalIncome:x}},[l,u,p.language]);if(v)return e.jsx("div",{className:`${we.card} ${a??""}`,children:e.jsx(Ea,{onRetry:()=>i()})});if(r)return e.jsx("div",{className:`${we.card} ${a??""}`,children:e.jsx("div",{className:we.skeletonContainer,children:e.jsx(z,{className:we.skeletonChart})})});if(!l||l.transactions.length===0)return e.jsx("div",{className:`${we.card} ${a??""}`,children:e.jsx("div",{className:we.emptyState,children:e.jsx("p",{children:o("recurring.noIncomeTransactions","No income transactions found.")})})});const L={amount:{label:o("common.income","Income"),color:"var(--success)"},currentAmount:{label:o("common.income","Income"),color:"var(--success)"}},N=x=>x>=1e6?`${Math.round(x/1e6)}M`:x>=1e3?`${Math.round(x/1e3)}K`:`${Math.round(x)}`;return e.jsxs("div",{className:`${we.card} ${a??""}`,children:[e.jsx("div",{className:we.chartWrapper,children:e.jsx(gt,{config:L,children:e.jsxs(xt,{data:_,margin:{top:10,right:30,left:0,bottom:35},children:[e.jsx(yt,{strokeDasharray:"3 3",vertical:!1}),e.jsx(ft,{dataKey:"monthLabel",tickLine:!1,axisLine:!1,tickMargin:10,minTickGap:0,interval:0,tick:e.jsx(yr,{soFarLabel:o("recurring.soFar","(so far)")})}),e.jsx(vt,{tickLine:!1,axisLine:!1,tickFormatter:N,width:65}),e.jsx(_t,{cursor:!1,content:x=>{if(x.payload&&x.payload.length>1){const H=x.payload.filter(R=>R.dataKey==="amount");return e.jsx(Cn,{...x,payload:H})}return e.jsx(Cn,{...x})}}),e.jsx(bn,{type:"monotone",dataKey:"amount",stroke:"var(--color-amount)",strokeWidth:2,dot:{r:4,fill:"var(--color-amount)"},activeDot:{r:6}}),e.jsx(bn,{type:"monotone",dataKey:"currentAmount",stroke:"var(--color-currentAmount)",strokeWidth:2,strokeDasharray:"5 5",dot:_r,activeDot:xr})]})})}),e.jsx("div",{className:we.summaryContainer,children:e.jsxs("p",{className:we.summary,children:[o("recurring.totalIncomeOverMonths","Total income over 6 months:")," ",e.jsx("strong",{children:E(d,n)})]})})]})},vr=Se({patternId:me(),action:De(["accept","dismiss","add_new"])}),jr=async(n,t)=>{const a=vr.parse(n),o=await fetch("/_api/recurring/review-amount",{method:"POST",body:oe.stringify(a),...t,headers:{"Content-Type":"application/json"}});if(!o.ok){const p=oe.parse(await o.text());throw new Error(p.error)}return oe.parse(await o.text())},wr=()=>{const n=Me();return He({mutationFn:async t=>jr(t),onSuccess:(t,a)=>{n.invalidateQueries({queryKey:[We]}),ne.success(a.action==="accept"?"Income amount updated.":a.action==="add_new"?"New income stream added.":"Change dismissed.")},onError:t=>{ne.error(t.message||"Failed to update recurring amount")}})},Nr="_container_tmpvs_1",Cr="_card_tmpvs_9",br="_infoSection_tmpvs_22",Dr="_header_tmpvs_28",kr="_labelWrapper_tmpvs_35",Sr="_labelIconIncrease_tmpvs_41",Tr="_labelIconDecrease_tmpvs_45",Ir="_label_tmpvs_35",Rr="_merchant_tmpvs_55",Mr="_amountFlow_tmpvs_61",Br="_oldAmount_tmpvs_71",Ar="_arrow_tmpvs_77",Lr="_newAmount_tmpvs_81",$r="_percentBadge_tmpvs_87",Pr="_positive_tmpvs_98",Or="_negative_tmpvs_103",qr="_actionsSection_tmpvs_108",Ur="_primaryActions_tmpvs_114",zr="_actionBtn_tmpvs_120",Fr="_addNewBtn_tmpvs_120",Hr="_secondaryAction_tmpvs_128",Wr="_plusIcon_tmpvs_135",Er="_helperText_tmpvs_139",Q={container:Nr,card:Cr,infoSection:br,header:Dr,labelWrapper:kr,labelIconIncrease:Sr,labelIconDecrease:Tr,label:Ir,merchant:Rr,amountFlow:Mr,oldAmount:Br,arrow:Ar,newAmount:Lr,percentBadge:$r,positive:Pr,negative:Or,actionsSection:qr,primaryActions:Ur,actionBtn:zr,addNewBtn:Fr,secondaryAction:Hr,plusIcon:Wr,helperText:Er},Gn=({bills:n,currency:t,className:a})=>{const{t:o}=ae(),{mutate:p,isPending:s}=wr(),c=n.filter(u=>u.amountChangeNeedsReview&&u.patternType==="income"&&u.source==="pattern"&&u.pendingAmount!==null);return c.length===0?null:e.jsx("div",{className:`${Q.container} ${a||""}`,children:c.map(u=>{const l=u.amount,f=u.pendingAmount,v=f-l,i=l!==0?Math.round(Math.abs(v/l)*100):0,r=v>0;return e.jsxs("div",{className:Q.card,children:[e.jsxs("div",{className:Q.infoSection,children:[e.jsxs("div",{className:Q.header,children:[e.jsxs("div",{className:Q.labelWrapper,children:[r?e.jsx(ke,{size:14,className:Q.labelIconIncrease}):e.jsx(Nn,{size:14,className:Q.labelIconDecrease}),e.jsx("span",{className:Q.label,children:o("recurring.incomeReview","Income Review")})]}),e.jsx("span",{className:Q.merchant,children:u.merchantName})]}),e.jsxs("div",{className:Q.amountFlow,children:[e.jsx("span",{className:Q.oldAmount,children:E(l,t)}),e.jsx(et,{size:14,className:Q.arrow}),e.jsx("span",{className:Q.newAmount,children:E(f,t)}),i>0&&e.jsxs("div",{className:`${Q.percentBadge} ${r?Q.positive:Q.negative}`,children:[r?e.jsx(ke,{size:12}):e.jsx(Nn,{size:12}),e.jsxs("span",{children:[i,"%"]})]})]})]}),e.jsxs("div",{className:Q.actionsSection,children:[e.jsxs("div",{className:Q.primaryActions,children:[e.jsx(Z,{variant:"outline",className:Q.actionBtn,onClick:()=>p({patternId:u.originalId,action:"dismiss"}),disabled:s,children:o("common.ignore","Ignore")}),e.jsx(Z,{variant:"primary",className:Q.actionBtn,onClick:()=>p({patternId:u.originalId,action:"accept"}),disabled:s,children:o("recurring.updateAmount","Update Amount")})]}),e.jsxs("div",{className:Q.secondaryAction,children:[e.jsxs(Z,{variant:"outline",className:Q.addNewBtn,onClick:()=>p({patternId:u.originalId,action:"add_new"}),disabled:s,children:[e.jsx(nt,{size:14,className:Q.plusIcon}),o("recurring.addAsNewIncome","Add as New Income")]}),e.jsx("span",{className:Q.helperText,children:o("recurring.trackAsSeparateIncome","Track as a separate recurring income")})]})]})]},u.id)})})},Nt=(n,t)=>{if(!n)return{status:"upcoming",label:"Next renewal"};const a=typeof n=="string"?new Date(n):n;if(isNaN(a.getTime()))return{status:"upcoming",label:"Next renewal"};const o=Ee(n,new Date);return o<0?{status:"overdue",label:"Overdue since"}:o===0?{status:"today",label:"Renews today"}:{status:"upcoming",label:"Next renewal"}};function Vr(n){return(cn(n)??"").slice(0,7)}function Rn(n=new Date){return`${n.getFullYear()}
1-${String(n.getMonth()+1).padStart(2,"0")}`}function Yr(n){return`${Rn(n)}-${String(n.getDate()).padStart(2,"0")}`}const Kr={paid:"paid",possible_payment:"possible",upcoming:"upcoming",unpaid:"unpaid",missed:"missed",no_charge_yet:"nocharge",stale:"stale",bank_not_connected:"bank",planned:"planned",awaiting_first:"awaiting",not_logged:"notlogged"};function on(n,t=new Date){const a=n;return a._cycleStatus?Kr[a._cycleStatus]:a._isStale?"stale":a._billStatus==="missed_payment"?"missed":a._isUnpaid?"unpaid":a.lastPaidDate&&Vr(a.lastPaidDate)===Rn(t)&&(cn(a.lastPaidDate)??"")<=Yr(t)?"paid":"upcoming"}const Gr=Se({patternId:me().int().positive(),action:De(["confirm","reject","mark_paid"]),transactionId:me().int().positive().optional(),cycleDate:Fe().regex(/^\d{4}-\d{2}-\d{2}$/).optional()}),Qr=async(n,t)=>{const a=Gr.parse(n),o=await fetch("/_api/recurring/payment-decision",{method:"POST",body:oe.stringify(a),...t,headers:{"Content-Type":"application/json"}});if(!o.ok){const p=oe.parse(await o.text());throw new Error(p.error)}return oe.parse(await o.text())};function Jr(){const n=Me(),{t}=ae();return He({mutationFn:a=>Qr(a),onSuccess:(a,o)=>{n.invalidateQueries({queryKey:[We]}),n.invalidateQueries({queryKey:In}),n.invalidateQueries({queryKey:["dashboard"]}),o.action==="confirm"&&ne.success(t("recurring.cycle.confirmedToast","Got it. That payment now counts for this bill.")),o.action==="reject"&&ne.success(t("recurring.cycle.rejectedToast","Got it. We won't suggest that payment again.")),o.action==="mark_paid"&&ne.success(t("recurring.cycle.markedToast","Marked as paid."))},onError:a=>{ne.error(a.message||t("recurring.cycle.saveFailed","We couldn't save that. Please try again."))}})}const Xr="_line_6aoqt_6",Zr="_table_6aoqt_13",eo="_card_6aoqt_17",no="_question_6aoqt_21",to="_quiet_6aoqt_27",ao="_sub_6aoqt_44",so="_actions_6aoqt_61",ro="_yesNo_6aoqt_71",oo="_actionButton_6aoqt_76",io="_planBadge_6aoqt_95",co="_textAction_6aoqt_101",re={line:Xr,table:Zr,card:eo,question:no,quiet:to,sub:ao,actions:so,yesNo:ro,actionButton:oo,planBadge:io,textAction:co},Mn=new Set(["possible","bank","nocharge","planned","awaiting","notlogged"]),Re=n=>n.stopPropagation(),Ct=({bill:n,status:t,currency:a,isIncome:o,layout:p})=>{const{t:s}=ae(),c=tt(),u=Jr(),{entitlements:l,isResolved:f}=Zt();if(!Mn.has(t))return null;const v=n.recurringPatternId??null,i=d=>pe(d,{month:"short",day:"numeric"}),r=`${re.line} ${p==="card"?re.card:re.table}`;if(t==="possible"&&n._suggestion){const d=n._suggestion;return e.jsxs("div",{className:r,onClick:Re,children:[e.jsx("span",{className:re.question,children:s("recurring.cycle.isThisIt","Is this it?")}),e.jsx("span",{className:re.sub,children:s("recurring.cycle.possibleDetail","{{amount}} on {{date}}",{amount:E(d.amount,a,{}),date:i(d.date)})}),v!=null&&e.jsxs("span",{className:`${re.actions} ${re.yesNo}`,children:[e.jsx(Z,{size:"sm",variant:"primary",className:re.actionButton,disabled:u.isPending,onClick:L=>{Re(L),u.mutate({patternId:v,action:"confirm",transactionId:d.transactionId})},children:s("common.yes","Yes")}),e.jsx(Z,{size:"sm",variant:"outline",className:re.actionButton,disabled:u.isPending,onClick:L=>{Re(L),u.mutate({patternId:v,action:"reject",transactionId:d.transactionId})}
1,children:s("common.no","No")})]})]})}if(t==="bank"){const d=l?.canBankSync===!0,L=l?.canBuyPremium===!0,N=n._cycleDueDate?cn(n._cycleDueDate):null;return e.jsxs("div",{className:r,onClick:Re,children:[e.jsx("span",{className:re.quiet,title:p==="table"?s("recurring.cycle.bankHelp","We can't check this until your bank is connected."):void 0,children:s("recurring.cycle.bankNotConnected","Bank not connected")}),p==="card"&&e.jsx("span",{className:re.sub,children:s("recurring.cycle.bankHelp","We can't check this until your bank is connected.")}),e.jsxs("span",{className:re.actions,children:[f&&(d||L)&&e.jsxs(Z,{size:"sm",variant:"primary",className:re.actionButton,onClick:x=>{Re(x),c(d?"/accounts":"/premium")},children:[d?s("recurring.cycle.reconnect","Reconnect"):s("recurring.cycle.reconnectWith","Reconnect with"),!d&&e.jsx(ya,{className:re.planBadge})]}),v!=null&&N&&e.jsx("button",{type:"button",className:re.textAction,disabled:u.isPending,onClick:x=>{Re(x),u.mutate({patternId:v,action:"mark_paid",cycleDate:N})},children:o?s("recurring.cycle.markReceived","Mark as received"):s("recurring.cycle.markPaid","Mark as paid")})]})]})}const _=(d,L)=>e.jsxs("div",{className:r,children:[e.jsx("span",{className:re.quiet,children:d}),L&&e.jsx("span",{className:re.sub,children:L})]});return t==="nocharge"?_(o?s("recurring.cycle.notReceivedYet","Nothing received yet"):s("recurring.cycle.noChargeYet","No charge yet this month"),s("recurring.cycle.variesHelp","This one varies, so it's never marked missed.")):t==="planned"?_(s("recurring.cycle.planned","Planned"),n.nextDueDate?s("recurring.cycle.firstOne","First one {{date}}",{date:pe(n.nextDueDate)}):null):t==="awaiting"?_(o?s("recurring.cycle.awaitingIncome","Waiting for the first deposit"):s("recurring.cycle.awaitingFirst","Waiting for first charge")):t==="notlogged"?_(s("recurring.cycle.notLogged","Not logged yet"),n.nextDueDate?s("recurring.cycle.wasDue","Due {{date}}",{date:i(n.nextDueDate)}):null):null},lo="_tableContainer_1n2ds_1",uo="_caption_1n2ds_10",mo="_table_1n2ds_1",po="_subscriptionRow_1n2ds_75",ho="_inactiveRow_1n2ds_89",go="_nameCellContent_1n2ds_98",_o="_iconContainer_1n2ds_104",xo="_recentlyPaidBadge_1n2ds_109",yo="_nameInfo_1n2ds_126",fo="_name_1n2ds_98",vo="_categoryCell_1n2ds_139",jo="_amountWrapper_1n2ds_143",wo="_amount_1n2ds_143",No="_avgText_1n2ds_157",Co="_priceChange_1n2ds_164",bo="_priceChangeText_1n2ds_175",Do="_priceBad_1n2ds_179",ko="_priceGood_1n2ds_184",So="_frequency_1n2ds_189",To="_dateCell_1n2ds_194",Io="_renewalDateWrapper_1n2ds_200",Ro="_renewalDate_1n2ds_200",Mo="_overdue_1n2ds_206",Bo="_overdueBadge_1n2ds_211",Ao="_paidBadge_1n2ds_222",Lo="_missedBadge_1n2ds_232",$o="_staleBadge_1n2ds_242",Po="_statusSub_1n2ds_248",Oo="_accountCell_1n2ds_254",qo="_accountName_1n2ds_259",Uo="_accountMask_1n2ds_263",zo="_manualBadge_1n2ds_269",Fo="_actionsHeader_1n2ds_282",Ho="_actionsCell_1n2ds_286",Wo="_actionsCellContent_1n2ds_291",Eo="_emptyState_1n2ds_326",Vo="_errorState_1n2ds_344",Yo="_skeletonName_1n2ds_359",Ko="_skeletonIcon_1n2ds_365",Go="_skeletonText_1n2ds_371",Qo="_splitCell_1n2ds_377",Jo="_splitContent_1n2ds_382",Xo="_splitIcon_1n2ds_390",Zo="_splitIconPersonal_1n2ds_396",ei="_splitIconShared_1n2ds_400",ni="_staleRow_1n2ds_419",g={tableContainer:lo,caption:uo,table:mo,subscriptionRow:po,inactiveRow:ho,nameCellContent:go,iconContainer:_o,recentlyPaidBadge:xo,nameInfo:yo,name:fo,categoryCell:vo,amountWrapper:jo,amount:wo,avgText:No,priceChange:Co,priceChangeText:bo,priceBad:Do,priceGood:ko,frequency:So,dateCell:To,renewalDateWrapper:Io,renewalDate:Ro,overdue:Mo,overdueBadge:Bo,paidBadge:Ao,missedBadge:Lo,staleBadge:$o,statusSub:Po,accountCell:Oo,accountName:qo,accountMask:Uo,manualBadge:zo,actionsHeader:Fo,actionsCell:Ho,actionsCellContent:Wo,emptyState:Eo,errorState:Vo,skeletonName:Yo,skeletonIcon:Ko,skeletonText:Go,splitCell:Qo,splitContent:Jo,splitIcon:Xo,splitIconPersonal:Zo,splitIconShared:ei,staleRow:ni},ti=(n,t)=>{const a=-Ee(n);return a<=0?t("recurring.paidToday","today"):a===1?t("recurring.paidYesterday","yesterday"):t("recurring.paidDaysAgo","{{count}} days ago",{count:a})},tn=({subscriptions:n,currency:t,isFetching:a,error:o,onEdit:p,onDelete:s,onViewHistory:c,showCancelledDate:u=!1,view:l="all",isMarketing:f=!1,isRecentlyPaid:v=!1})=>{const{t:i}=ae();if(a&&n.length===0)return e.jsx(ai,{showCancelledDate:u,view:l});if(o)return e.jsxs("div",{className:g.errorState,children:[e.jsx($n,{size:24}),e.jsx("p",{children:i("recurring.failedToLoad","Failed to load subscriptions")})]});if(n.length===0){let r=i("recurring.noSubscriptions","No subscriptions foun
1d");return l==="shared"?r=i("recurring.noSharedSubscriptions","No shared subscriptions yet. Add shared recurring expenses like streaming services or rent."):l==="personal"?r=i("recurring.noPersonalSubscriptions","No personal subscriptions yet. Add your individual recurring expenses like gym memberships."):l==="income"&&(r=i("recurring.noIncomeSources","No income sources found yet. Add your salary, freelance income, or any other recurring income.")),e.jsx("div",{className:g.emptyState,children:e.jsx("p",{children:r})})}return e.jsx("div",{className:g.tableContainer,children:e.jsxs("table",{className:g.table,children:[e.jsx("caption",{className:g.caption,children:u?i("recurring.listCancelled","List of cancelled subscriptions"):i("recurring.listActive","List of active subscriptions")}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:i("recurring.columnName","Name")}),e.jsx("th",{children:i("common.category","Category")}),e.jsx("th",{children:i("common.amount","Amount")}),e.jsx("th",{children:i("recurring.frequency","Frequency")}),e.jsx("th",{children:v?i("recurring.lastPaid","Last Paid"):l==="income"?i("recurring.nextPayment","Next Payment"):i("recurring.nextRenewal","Next Renewal")}),u&&e.jsx("th",{children:i("recurring.cancelledDate","Cancelled Date")}),e.jsx("th",{children:i("common.account","Account")}),e.jsx("th",{children:i("common.split","Split")}),e.jsx("th",{className:g.actionsHeader,children:i("common.actions","Actions")})]})}),e.jsx("tbody",{children:n.map(r=>{const _=!!r.cancelledAt,d=r,L=parseFloat(r.amount),N=d.previousAmount,x=d.amountType==="variable"&&d.averageAmount!==null&&d.averageAmount!==void 0,H=x?d.averageAmount:L,R=l==="income"||r.transactionType==="income"||d.patternType==="income",M=N!=null?L-N:0,h=N?Math.abs(M)/N*100:0,B=N!=null&&Math.abs(M)>=1&&h>=1,O=B&&d.amountType!=="variable",D=B?M:0,k=D>0,m=Math.round(B?h:0).toString(),j=R?k:!k,b=f?"upcoming":on(r),U=v||b==="paid",ie=f&&r.description.toLowerCase().includes("spotify")?"https://pub-9191c1ede9c74f98988a8e0b80c0c46b.r2.dev/migrated/bf77a7a4-618e-42bc-8995-c68a15929d4a.webp":r.merchantLogoUrl;return e.jsxs("tr",{"data-recurring-id":r.id,className:`${g.subscriptionRow} ${_?g.inactiveRow:""} ${b==="stale"?g.staleRow:""}`,onClick:()=>p(r),children:[e.jsx("td",{className:g.nameCell,children:e.jsxs("div",{className:g.nameCellContent,children:[e.jsxs("div",{className:g.iconContainer,children:[e.jsx(jt,{merchantLogoUrl:ie,categorySlug:r.categoryInfo?.slug,customCategoryIcon:r.categoryInfo?.icon,description:r.description,size:36}),U&&e.jsx("div",{className:g.recentlyPaidBadge,children:e.jsx(at,{size:8,strokeWidth:3})})]}),e.jsx("div",{className:g.nameInfo,children:e.jsx("span",{className:g.name,children:r.description})})]})}),e.jsx("td",{className:g.categoryCell,children:e.jsx(Qa,{transaction:r})}),e.jsx("td",{className:g.amountCell,children:e.jsxs("div",{className:g.amountWrapper,children:[e.jsxs("span",{className:g.amount,children:[E(H,t,{}),x&&e.jsx("span",{className:g.avgText,children:" avg"})]}),O&&e.jsxs("span",{className:`${g.priceChange} ${j?g.priceGood:g.priceBad}`,title:`Was ${E(N,t,{})}`,"aria-label":`Price ${k?"increased":"decreased"} from ${E(N,t,{})} to ${E(r.amount,t,{})}`,children:[k?e.jsx(ke,{size:12,"aria-hidden":"true"}):e.jsx(Nn,{size:12,"aria-hidden":"true"}),e.jsxs("span",{className:g.priceChangeText,children:[E(Math.round(Math.abs(D)),t,{})," (",m,"%)"]})]})]})}),e.jsx("td",{className:g.frequencyCell,children:x&&(r.recurrence==="weekly"||r.recurrence==="biweekly")?e.jsx("span",{className:g.frequency,children:i("recurring.frequencyVaries","Varies")}):r.recurrence?e.jsx("span",{className:g.frequency,children:r.recurrence==="semimonthly"?i("recurring.twiceAMonth","Twice a month"):r.recurrence==="biweekly"?i("recurring.biWeekly","Bi-weekly"):i(`recurring.${r.recurrence}`,r.recurrence.charAt(0).toUpperCase()+r.recurrence.slice(1))}):e.jsx("span",{className:g.frequency,children:i("recurring.monthly","Monthly")})}),e.jsx("td",{className:g.dateCell,children:x&&(r.recurrence==="weekly"||r.recurrence==="biweekly")?"-":f?e.jsx("div",{className:g.renew
1alDateWrapper,children:e.jsx("span",{className:g.renewalDate,children:"Jan 1, 2026"})}):v&&d.lastPaidDate?e.jsxs("div",{className:g.renewalDateWrapper,children:[e.jsx("span",{className:g.renewalDate,children:pe(d.lastPaidDate)}),e.jsxs("span",{className:g.paidBadge,children:[i("recurring.paid","Paid")," ",ti(d.lastPaidDate,i)]})]}):Mn.has(b)?e.jsxs("div",{className:g.renewalDateWrapper,children:[b!=="awaiting"&&b!=="planned"&&r.nextDueDate&&e.jsx("span",{className:g.renewalDate,children:pe(r.nextDueDate)}),e.jsx(Ct,{bill:d,status:b,currency:t,isIncome:R,layout:"table"})]}):b==="stale"?e.jsxs("div",{className:g.renewalDateWrapper,children:[e.jsx("span",{className:g.staleBadge,children:i("recurring.status.noChargeRecently","No charge in 2 cycles")}),d.lastPaidDate&&e.jsx("span",{className:g.statusSub,children:i("recurring.status.lastChargeOn","Last {{date}}",{date:pe(d.lastPaidDate,{month:"short",day:"numeric"})})})]}):r.nextDueDate?e.jsx("div",{className:g.renewalDateWrapper,children:(()=>{const{status:G,label:xe}=Nt(r.nextDueDate);return e.jsxs(e.Fragment,{children:[e.jsx("span",{className:`${g.renewalDate} ${G==="overdue"?g.overdue:""}`,children:pe(r.nextDueDate)}),b==="missed"?e.jsxs("span",{className:g.missedBadge,children:[e.jsx(st,{size:10}),i("recurring.status.missed","Last one missed")]}):b==="unpaid"?e.jsxs("span",{className:g.missedBadge,children:[e.jsx($n,{size:10}),R?i("recurring.status.notReceived","Not received yet"):i("recurring.status.unpaid","Unpaid")]}):b==="paid"&&d.lastPaidDate?e.jsx("span",{className:g.paidBadge,children:R?i("recurring.status.receivedOn","Received {{date}}",{date:pe(d.lastPaidDate,{month:"short",day:"numeric"})}):i("recurring.status.paidOn","Paid {{date}}",{date:pe(d.lastPaidDate,{month:"short",day:"numeric"})})}):G==="overdue"&&e.jsxs("span",{className:g.overdueBadge,title:xe,children:[e.jsx(kn,{size:10}),i("recurring.overdue","Overdue")]})]})})()}):"-"}),u&&e.jsx("td",{className:g.dateCell,children:r.cancelledAt?pe(r.cancelledAt):"-"}),e.jsx("td",{className:g.accountCell,children:d._accountHidden?e.jsx("span",{className:g.accountName,children:d._accountHiddenOwnerFirstName?i("transactions.partnerAccount","{{name}}'s account",{name:d._accountHiddenOwnerFirstName}):i("transactions.partnerAccountGeneric","Partner's account")}):!r.accountName&&d._hasBankCharges?e.jsx("span",{className:g.accountName,children:i("recurring.cycle.bankAccount","Bank account")}
1):r.accountName?e.jsxs("span",{className:g.accountName,children:[r.accountName,r.accountMask&&e.jsxs("span",{className:g.accountMask,children:[" â¢â¢",r.accountMask]})]}):e.jsxs("span",{className:g.manualBadge,children:[e.jsx(Mt,{size:12}),i("common.manual","Manual")]})}),e.jsx("td",{className:g.splitCell,children:e.jsxs(ea,{delayDuration:100,children:[e.jsx(na,{asChild:!0,children:e.jsx("div",{className:g.splitContent,children:r.splitType==="personal"?e.jsx(rt,{size:14,className:`${g.splitIcon} ${g.splitIconPersonal}`}):r.splitType==="shared"?e.jsx(ot,{size:14,className:`${g.splitIcon} ${g.splitIconShared}`}):e.jsx(it,{size:14,className:g.splitIcon})})}),e.jsx(ta,{children:r.splitType==="personal"?l==="income"?i("recurring.personalIncome","Personal income"):i("recurring.personalExpense","Personal expense"):r.splitType==="shared"?l==="income"?i("recurring.sharedIncome","Shared income"):i("recurring.sharedExpense","Shared expense"):i("recurring.unclassified","Unclassified")})]})}),e.jsx("td",{className:g.actionsCell,onClick:G=>G.stopPropagation(),children:e.jsxs("div",{className:g.actionsCellContent,children:[e.jsx(Z,{variant:"ghost",size:"icon-sm",onClick:G=>{G.stopPropagation(),c(r)},"aria-label":`${i("recurring.viewHistory","View history")} ${r.description}`,title:i("recurring.viewHistory","View history"),children:e.jsx(Dn,{size:14})}),e.jsx(Z,{variant:"ghost",size:"icon-sm",onClick:G=>{G.stopPropagation(),p(r)},"aria-label":`${i("common.edit","Edit")} ${r.description}`,children:e.jsx(Bt,{size:14})}),e.jsx(Z,{variant:"ghost",size:"icon-sm",onClick:G=>{G.stopPropagation(),s(r)},"aria-label":`${i("recurring.stopTrackingButton","Stop Tracking")} ${r.description}`,title:i("recurring.stopTrackingButton","Stop Tracking"),children:e.jsx(Zn,{size:14})})]})})]},r.id)})})]})})},ai=({showCancelledDate:n=!1,view:t="all"})=>{const{t:a}=ae();return e.jsx("div",{className:g.tableContainer,children:e.jsxs("table",{className:g.table,children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:a("recurring.columnName","Name")}),e.jsx("th",{children:a("common.category","Category")}),e.jsx("th",{children:a("common.amount","Amount")}),e.jsx("th",{children:a("recurring.frequency","Frequency")}),e.jsx("th",{children:t==="income"?a("recurring.nextPayment","Next Payment"):a("recurring.nextRenewal","Next Renewal")}),n&&e.jsx("th",{children:a("recurring.cancelledDate","Cancelled Date")}),e.jsx("th",{children:a("common.account","Account")}),e.jsx("th",{})]})}),e.jsx("tbody",{children:[1,2,3,4,5].map(o=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("div",{className:g.skeletonName,children:[e.jsx(z,{className:g.skeletonIcon}),e.jsx("div",{className:g.skeletonText,children:e.jsx(z,{style:{width:"140px",height:"1rem"}})})]})}),e.jsx("td",{children:e.jsx(z,{style:{width:"100px",height:"1rem"}})}),e.jsx("td",{children:e.jsx(z,{style:{width:"60px",height:"1rem"}})}),e.jsx("td",{children:e.jsx(z,{style:{width:"80px",height:"1rem"}})}),e.jsx("td",{children:e.jsx(z,{style:{width:"100px",height:"1rem"}})}),n&&e.jsx("td",{children:e.jsx(z,{style:{width:"100px",height:"1rem"}})}),e.jsx("td",{children:e.jsx(z,{style:{width:"120px",height:"1rem"}})}),e.jsx("td",{children:e.jsx(z,{style:{width:"30px",height:"1rem"}})}),e.jsx("td",{children:e.jsx(z,{style:{width:"32px",height:"32px"}})})]},o))})]})})},si="_card_1wzs0_1",ri="_marketingCard_1wzs0_23",oi="_mainRow_1wzs0_40",ii="_iconCircle_1wzs0_47",ci="_recentlyPaidBadge_1wzs0_53",li="_headerContent_1wzs0_70",di="_nameGroup_1wzs0_79",ui="_name_1wzs0_79",mi="_badgeWrapper_1wzs0_96",pi="_incomeIcon_1wzs0_104",hi="_sharedIcon_1wzs0_104",gi="_personalIcon_1wzs0_108",_i="_paidText_1wzs0_122",xi="_missedText_1wzs0_128",yi="_staleText_1wzs0_142",fi="_amountContent_1wzs0_162",vi="_amount_1wzs0_162",ji="_frequency_1wzs0_178",wi="_renewalRow_1wzs0_191",Ni="_renewalTextWrapper_1wzs0_198",Ci="_comingUpText_1wzs0_207",bi="_renewalLabel_1wzs0_207",Di="_comingUpAmount_1wzs0_221",ki="_renewalDate_1wzs0_221",Si="_renewalDot_1wzs0_229",Ti="_overdueLabel_1wzs0_236",Ii="_overdueDate_1wzs0_236",Ri="_priceChangeIndicator_1wzs0_240",Mi="_priceBad_1wzs0_250",Bi="_priceGood_1wzs0_25
15",Ai="_viewHistoryLink_1wzs0_260",A={card:si,marketingCard:ri,mainRow:oi,iconCircle:ii,recentlyPaidBadge:ci,headerContent:li,nameGroup:di,name:ui,badgeWrapper:mi,incomeIcon:pi,sharedIcon:hi,personalIcon:gi,paidText:_i,missedText:xi,staleText:yi,amountContent:fi,amount:vi,frequency:ji,renewalRow:wi,renewalTextWrapper:Ni,comingUpText:Ci,renewalLabel:bi,comingUpAmount:Di,renewalDate:ki,renewalDot:Si,overdueLabel:Ti,overdueDate:Ii,priceChangeIndicator:Ri,priceBad:Mi,priceGood:Bi,viewHistoryLink:Ai},Li=(n,t)=>{const a=-Ee(n);return a<=0?t("recurring.paidToday","today"):a===1?t("recurring.paidYesterday","yesterday"):t("recurring.paidDaysAgo",{count:a,defaultValue:`${a} days ago`})},fn=({subscription:n,onClick:t,className:a,isMarketing:o=!1,onViewHistory:p,isRecentlyPaid:s=!1})=>{const{t:c,i18n:u}=ae(),{currency:l}=Sn(),f=parseFloat(n.amount),v=n.splitType==="shared",i=n,r=n.transactionType==="income"||i.patternType==="income",_=i.previousAmount!=null?f-i.previousAmount:0,d=i.previousAmount?Math.abs(_)/i.previousAmount*100:0,L=i.previousAmount!=null&&Math.abs(_)>=1&&d>=1,N=L&&i.amountType!=="variable",x=L?_:0,R=Math.round(L?d:0).toString(),M=i.amountType==="variable",h=M&&i.minAmount!=null&&i.maxAmount!=null,O=!(M&&(n.recurrence==="weekly"||n.recurrence==="biweekly"))&&n.nextDueDate!=null,D=x>0,k=r?D:!D,y=o?"upcoming":on(n),m=!s&&Mn.has(y),j=m||O||h||i._isStale===!0,b=s||y==="paid",U=te=>pe(te,{month:"short",day:"numeric"},u.language),ie=o&&n.description.toLowerCase().includes("spotify")?"https://pub-9191c1ede9c74f98988a8e0b80c0c46b.r2.dev/migrated/bf77a7a4-618e-42bc-8995-c68a15929d4a.webp":n.merchantLogoUrl,G=()=>{if(i.amountType==="variable"&&(n.recurrence==="weekly"||n.recurrence==="biweekly"))return c("recurring.frequencyVaries","Varies");switch(n.recurrence){case"weekly":return c("recurring.frequencyWeekly","Weekly");case"biweekly":return c("recurring.frequencyBiweekly","Bi-weekly");case"semimonthly":return c("recurring.frequencySemimonthly","Twice a month");case"monthly":return c("recurring.frequencyMonthly","Monthly");case"quarterly":return c("recurring.frequencyQuarterly","Quarterly");case"yearly":return c("recurring.frequencyYearly","Yearly");default:return""}},xe=te=>{const se=Ee(te);if(se<=0)return c("recurring.upcomingToday","today");if(se===1)return c("recurring.upcomingTomorrow","tomorrow");if(se<14)return c("recurring.upcomingInDays",{count:se,defaultValue:`in ${se} days`});if(se<30){const le=Math.round(se/7);return le===1?c("recurring.upcomingInWeeks",{count:le,defaultValue:"in 1 week"}):c("recurring.upcomingInWeeksPlural",{count:le,defaultValue:`in ${le} weeks`})}if(se<60)return c("recurring.upcomingNextMonth","next month");const V=pe(te,void 0,u.language);return c("recurring.upcomingOnDate",{date:V,defaultValue:`on ${V}`})};return e.jsxs("div",{className:`${A.card} ${o?A.marketingCard:""} ${a||""}`,onClick:t,role:t?"button":void 0,tabIndex:t?0:void 0,onKeyDown:t?te=>{(te.key==="Enter"||te.key===" ")&&(te.preventDefault(),t())}:void 0,children:[e.jsxs("div",{className:A.mainRow,children:[e.jsxs("div",{className:A.iconCircle,children:[e.jsx(jt,{merchantLogoUrl:ie,categorySlug:n.categoryInfo?.slug,customCategoryIcon:n.categoryInfo?.icon,description:n.description,size:40}),b&&e.jsx("div",{className:A.recentlyPaidBadge,children:e.jsx(at,{size:8,strokeWidth:3})})]}),e.jsxs("div",{className:A.headerContent,children:[e.jsxs("div",{className:A.nameGroup,children:[e.jsx("span",{className:A.name,children:n.description}),e.jsx("div",{className:A.badgeWrapper,children:r?e.jsx(ke,{size:16,className:A.incomeIcon}):v?e.jsx(ot,{size:16,className:A.sharedIcon}):e.jsx(rt,{size:16,className:A.personalIcon})}),p&&e.jsx("button",{className:A.viewHistoryLink,onClick:te=>{te.stopPropagation(),p()},"aria-label":"View history",title:"View history",children:e.jsx(Dn,{size:14})})]}),e.jsx("div",{className:A.amountContent,children:M&&i.averageAmount!=null?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:A.amount,children:E(i.averageAmount,l,{})}),G()&&e.jsx("span",{className:A.frequency,children:G()===c("recurring.frequencyVaries","Varies")?c("recurring.frequencyVaries","Varies"):`${G()} ${c("recurring.avg","avg")}`})]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:A.amount,children:E(f,l,{})}),G()&&e.jsx("span",{className:A.frequency,children:G()})]})})]})]}),m&&e.jsx("div",{className:A.renewalRow,children:e.jsx(Ct,{bill:i,status:y,currency:l,isIncome:r,layout:"card"})}),j&&!m&&e.jsx("div",{className:A.renewalRow,children:e.jsxs("div",{className:A.renewalTextWrapper,children:[y==="stale"&&e.jsxs("span",{className:A.staleText,children:[c("recurring.status.noChargeRecently","No charge in 2 cycles"),i.lastPaidDate?` · ${c("recurring.status.lastChargeOn","Last {{date}}",{date:U(i.lastPaidDate)})}`:""]}),y==="missed"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:A.missedText,children:c("recurring.status.missed","Last one missed")}),e.jsx("span",{className:A.renewalDot,children:"·"})]}),y==="unpaid"&&n.nextDueDate&&e.jsx("span",{className:A.missedText,children:r?c("recurring.status.notReceivedDue","Not received yet · due {{date}}",{date:U(n.nextDueDate)}):c("recurring.status.unpaidDue","Unpaid · due {{date}}",{date:U(n.nextDueDate)})}),y==="paid"&&i.lastPaidDate&&!s&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:A.paidText,children:r?c("recurring.status.receivedOn","Received {{date}}",{date:U(i.lastPaidDate)}):c("recurring.status.paidOn","Paid {{date}}",{date:U(i.lastPaidDate)})}),O&&e.jsx("span",{className:A.renewalDot,children:"·"})]}),y!=="stale"&&y!=="unpaid"&&h&&e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:A.comingUpText,children:[E(i.minAmount,l,{hideDecimals:!0})," - ",E(i.maxAmount,l,{hideDecimals:!0})]}),O&&e.jsx("span",{className:A.renewalDot,children:"·"})]}),y!=="stale"&&y!=="unpaid"&&O&&(()=>{if(o)return e.jsxs(e.Fragment,{children:[e.jsx("span",{className:A.renewalLabel,children:"Renews:"}),e.jsx("span",{className:A.renewalDate,children:"Jan 1, 2026"})]});if(s&&i.lastPaidDate){const V=Li(i.lastPaidDate,c),ee=c("recurring.paidTimeAgo",{timeAgo:V,defaultValue:`Paid ${V}`}).split(V);return e.jsx("span",{className:A.comingUpText,children:ee.length===2?e.jsxs(e.Fragment,{children:[ee[0],e.jsx("span",{className:A.comingUpAmount,children:V}),ee[1]]}):e.jsxs(e.Fragment,{children:[c("recurring.paid","Paid")," ",e.jsx("span",{className:A.comingUpAmount,children:V})]})})}const{status:te,label:se}=Nt(n.nextDueDate);if(te==="upcoming"){const V=xe(n.nextDueDate),le=pe(n.nextDueDate,{month:"short",day:"numeric"},u.language),ee=`(${le})`,he=c("recurring.comingUpDate",{relativeText:V,date:le,defaultValue:`Coming up ${V} (${le})`}).split(ee);return e.jsx("span",{className:A.comingUpText,children:he.length===2?e.jsxs(e.Fragment,{children:[he[0],e.jsx("span",{className:A.comingUpAmount,children:ee}),he[1]]}):e.jsxs(e.Fragment,{children:[c("recurring.comingUp",{defaultValue:"Coming up"})," ",V," ",e.jsx("span",{className:A.comingUpAmount,children:ee})]})})}return e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:`${A.renewalLabel} ${te==="overdue"?A.overdueLabel:""}`,children:[se,":"]}),e.jsx("span",{className:`${A.renewalDate} ${te==="overdue"?A.overdueDate:""}`,children:pe(n.nextDueDate)})]})})(),y!=="stale"&&O&&N&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:A.renewalDot,children:"·"}),e.jsxs("span",{className:`${A.priceChangeIndicator} ${k?A.priceGood:A.priceBad}`,children:[x>0?"â":"â"," ",E(Math.abs(x),l,{hideDecimals:!0})," (",R,"%)"]})]})]})})]})},$i="_container_1pl8k_2",Pi="_header_1pl8k_8",Oi="_dateRange_1pl8k_24",qi="_stripContent_1pl8k_32",Ui="_navButton_1pl8k_38",zi="_grid_1pl8k_50",Fi="_dayColumn_1pl8k_59",Hi="_mobileDayCell_1pl8k_75",Wi="_dayLabel_1pl8k_104",Ei="_dateNumberRow_1pl8k_127",Vi="_dateNumberWrapper_1pl8k_142",Yi="_dateNumber_1pl8k_127",Ki="_hasBillsText_1pl8k_159",Gi="_todayCircle_1pl8k_164",Qi="_indicatorRow_1pl8k_174",Ji="_indicator_1pl8k_174",Xi="_dotsContainer_1pl8k_192",Zi="_dot_1pl8k_192",e
1c="_todayDot_1pl8k_207",nc="_countBadge_1pl8k_212",tc="_spacer_1pl8k_227",ac="_dayContentInner_1pl8k_232",sc="_mobileContainer_1pl8k_242",rc="_mobileGrid_1pl8k_249",oc="_mobileHeaderCell_1pl8k_256",ic="_popoverContent_1pl8k_281",cc="_popoverHeader_1pl8k_286",lc="_billList_1pl8k_295",dc="_billItem_1pl8k_301",uc="_billName_1pl8k_309",mc="_billAmount_1pl8k_318",pc="_popoverTotal_1pl8k_325",q={container:$i,header:Pi,dateRange:Oi,stripContent:qi,navButton:Ui,grid:zi,dayColumn:Fi,mobileDayCell:Hi,dayLabel:Wi,dateNumberRow:Ei,dateNumberWrapper:Vi,dateNumber:Yi,hasBillsText:Ki,todayCircle:Gi,indicatorRow:Qi,indicator:Ji,dotsContainer:Xi,dot:Zi,todayDot:ec,countBadge:nc,spacer:tc,dayContentInner:ac,mobileContainer:sc,mobileGrid:rc,mobileHeaderCell:oc,popoverContent:ic,popoverHeader:cc,billList:lc,billItem:dc,billName:uc,billAmount:mc,popoverTotal:pc},hc=(n,t)=>n.getFullYear()===t.getFullYear()&&n.getMonth()===t.getMonth()&&n.getDate()===t.getDate(),Qn=({bills:n,currency:t,days:a=14,className:o,isMarketing:p=!1})=>{const{i18n:s}=ae(),c=s.language||"en-US",l=ln()&&a>=14,[f,v]=P.useState(0),[i,r]=P.useState(null),_=new Date,d=new Date;_.setFullYear(d.getFullYear(),d.getMonth(),d.getDate()),_.setHours(0,0,0,0);const L=p?new Date(2025,11,25):_;let N;if(l){N=new Date(L);const y=N.getDay();N.setDate(L.getDate()-y)}else N=new Date(L),N.setDate(L.getDate()+f);const x=new Date(N);x.setDate(N.getDate()+a-1);const H=y=>y.toLocaleDateString(c,{month:"short",day:"numeric"}),R=`${H(N)} - ${H(x)}`,M=[],h=l?14:a;for(let y=0;y<h;y++){const m=new Date(N);m.setDate(N.getDate()+y);const j=hc(m,L),b=n.filter(Y=>Y.nextDueDate?Ga(Y.nextDueDate,m):!1),U=b.reduce((Y,ie)=>{const G=typeof ie.amount=="string"?parseFloat(ie.amount):ie.amount;return Y+(isNaN(G)?0:G)},0);M.push({date:m,dayLabel:m.toLocaleDateString(c,{weekday:"short"}),dateNumber:m.getDate(),isToday:j,bills:b,totalAmount:U})}const B=()=>{v(y=>y-a)},O=()=>{v(y=>y+a)},D=(y,m)=>y===0?null:y>=4?e.jsx("div",{className:q.indicator,children:e.jsx("div",{className:`${q.countBadge} ${m&&l?q.todayIndicator:""}`,children:y})}):e.jsx("div",{className:q.indicator,children:e.jsx("div",{className:q.dotsContainer,children:Array.from({length:y}).map((j,b)=>e.jsx("div",{className:`${q.dot} ${m&&l?q.todayDot:""}`},b))})}),k=(y,m)=>{const j=y.bills.length>0,b=y.bills.length,U=e.jsxs("div",{className:q.dayContentInner,children:[!l&&e.jsx("div",{className:q.dayLabel,children:y.date.toLocaleDateString(c,{weekday:"short"})}),e.jsx("div",{className:q.dateNumberRow,children:e.jsx("div",{className:`${q.dateNumberWrapper} ${y.isToday?q.todayCircle:""} ${j?q.hasBillsText:""}`,children:e.jsx("span",{className:q.dateNumber,children:y.dateNumber})})}),e.jsx("div",{className:q.indicatorRow,children:j?D(b,y.isToday):e.jsx("div",{className:q.spacer})})]}),Y=`${l?q.mobileDayCell:q.dayColumn} ${j?q.interactive:""}`;return j?e.jsxs(aa,{children:[e.jsx(sa,{asChild:!0,children:e.jsx("button",{className:Y,onMouseEnter:()=>r(m),onMouseLeave:()=>r(null),children:U})}),e.jsxs(ra,{className:q.popoverContent,children:[e.jsx("div",{className:q.popoverHeader,children:y.date.toLocaleDateString(void 0,{weekday:"long",month:"short",day:"numeric"})}),e.jsx("div",{className:q.billList,children:y.bills.map(ie=>e.jsxs("div",{className:q.billItem,children:[e.jsx("span",{className:q.billName,children:ie.description}),e.jsx("span",{className:q.billAmount,children:E(ie.amount,t,{})})]},ie.id))}),e.jsxs("div",{className:q.popoverTotal,children:[e.jsx("span",{children:"Total"}),e.jsx("span",{children:E(y.totalAmount,t,{})})]})]})]},m):e.jsx("div",{className:Y,onMouseEnter:()=>r(m),onMouseLeave:()=>r(null),children:U},m)};if(l){const y=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];return e.jsx("div",{className:`${q.mobileContainer} ${o||""}`,children:e.jsxs("div",{className:q.mobileGrid,children:[y.map(m=>e.jsx("div",{className:q.mobileHeaderCell,children:m},m)),M.map((m,j)=>k(m,j))]})})}return e.jsxs("div",{className:`${q.container} ${o||""}`,children:[e.jsx("div",{className:q.header,children:e.jsx("span",{className:q.dateRange,children:R})}),e.jsxs("div",{className:q.stripContent,children:[e.jsx(Z,{variant:"ghost",size:"icon-sm",onClick:B,className:q.navButton,"aria-label":"Previous period",children:e.jsx(ct,{size:20})}),e.jsx("div",{className:q.grid,style:{"--days":a},children:M.map((y,m)=>k(y,m))}),e.jsx(Z,{variant:"ghost",size:"icon-sm",onClick:O,className:q.navButton,"aria-label":"Next period",children:e.jsx(At,{size:20})})]})]})},gc="_header_3ruer_6",_c="_left_3ruer_15",xc="_icon_3ruer_22",yc="_title_3ruer_29",fc="_count_3ruer_42",vc="_right_3ruer_52",jc="_value_3ruer_59",wc="_period_3ruer_68",Nc="_titleSkeleton_3ruer_75",Cc="_valueSkeleton_3ruer_81",ve={header:gc,left
1:_c,icon:xc,title:yc,count:fc,right:vc,value:jc,period:wc,titleSkeleton:Nc,valueSkeleton:Cc},an=({title:n,icon:t,items:a,currency:o,isLoading:p=!1,view:s="all",accentColor:c="var(--primary)",className:u=""})=>{const{t:l}=ae(),{authState:f}=Tn(),i=(f.type==="authenticated"?f.user:null)?.email==="[email protected]",r=P.useMemo(()=>p?null:{totalMonthly:a.filter(x=>dn(x)).reduce((x,H)=>x+rn(H),0),count:a.length},[a,p]),_=L=>i?E(Math.round(L),o).replace(/(\.00|\.0)$/,"").split(".")[0]:E(L,o,{}),d={"--local-accent":c};return p||!r?e.jsxs("div",{className:`${ve.header} ${u}`,style:d,children:[e.jsx(z,{className:ve.titleSkeleton}),e.jsx(z,{className:ve.valueSkeleton})]}):e.jsxs("div",{className:`${ve.header} ${u}`,style:d,children:[e.jsxs("div",{className:ve.left,children:[e.jsx("span",{className:ve.icon,"aria-hidden":"true",children:t}),e.jsx("span",{className:ve.title,children:n}),e.jsx("span",{className:ve.count,children:r.count})]}),e.jsx("div",{className:ve.right,children:e.jsxs("span",{className:ve.value,children:[_(r.totalMonthly),e.jsx("span",{className:ve.period,children:l("recurring.perMonth","/mo")})]})})]})};function bc(n,t){const a=t-n;return a>=1&&n>0&&a/n*100>=1}function Dc(n,t,a=new Date,o=90){const p=n.filter(h=>dn(h,a)),s=p.reduce((h,B)=>h+rn(B),0),c=p.reduce((h,B)=>h+va(B),0),u=n.filter(h=>h._isStale).length,l=Vn(a),f=Rn(a),[v,i]=f.split("-").map(Number),r=new Date(Date.UTC(v,i,0)).toISOString().slice(0,10);let _=0,d=0;if(t){const h=new Set(n.map(O=>ut(O)).filter(Boolean)),B=new Set;for(const O of t.rows)O.month!==f||!h.has(O.key)||(_+=O.amount,O.count>0&&B.add(O.key));d=B.size}else for(const h of n)on(h,a)==="paid"&&(_+=sn(h),d+=1);let L=0,N=0;for(const h of p){if(!h.nextDueDate)continue;let B;try{B=Vn(h.nextDueDate)}catch{continue}let O=0;const D=h._isUnpaid===!0;for(let k=0;k<40&&B<=r;k++)(B>=l||D&&k===0)&&(O+=1),B=Ja(B,h.recurrence);O>0&&(L+=O*sn(h),N+=1)}let x=0,H=0;for(const h of n)on(h,a)==="missed"&&(x+=1,H+=sn(h));const R=a.getTime()-o*864e5,M=p.map(h=>{const B=h,O=Math.abs(parseFloat(h.amount)),D=B.previousAmount!=null?Math.abs(B.previousAmount):null;if(D==null||B.amountType==="variable"||!B.priceChangeDetectedAt||new Date(B.priceChangeDetectedAt).getTime()<R||!bc(D,O))return null;const k=O>0?rn(h)/O:1;return{id:h.id,name:h.description,from:D,to:O,monthlyIncrease:(O-D)*k}}).filter(h=>h!=null).sort((h,B)=>B.monthlyIncrease-h.monthlyIncrease);return{monthly:s,yearly:s*12,myShareMonthly:c,activeCount:p.length,staleCount:u,paidThisMonth:Math.round(_*100)/100,paidCount:d,upcomingThisMonth:L,upcomingCount:N,missedCount:x,missedAmount:H,priceIncreases:M}}const kc="_card_11znn_1",Sc="_columns_11znn_13",Tc="_monthBlock_11znn_28",Ic="_quad_11znn_43",Rc="_cell_11znn_51",Mc="_cellValue_11znn_58",Bc="_eyebrow_11znn_68",Ac="_total_11znn_74",Lc="_period_11znn_85",$c="_monthRow_11znn_107",Pc="_monthLabel_11znn_118",Oc="_monthValue_11znn_125",qc="_monthCount_11znn_133",Uc="_paidIcon_11znn_140",zc="_upcomingIcon_11znn_144",Fc="_missedIcon_11znn_148",Hc="_missedValue_11znn_152",Wc="_priceBlock_11znn_156",Ec="_priceHeader_11znn_164",Vc="_priceTitle_11znn_170",Yc="_priceImpact_11znn_176",Kc="_priceList_11znn_183",Gc="_priceRow_11znn_191",Qc="_priceName_11znn_209",Jc="_priceChange_11znn_218",Xc="_staleNote_11znn_225",Zc="_skeletonLine_11znn_231",el="_skeletonBig_11znn_237",S={card:kc,columns:Sc,monthBlock:Tc,quad:Ic,cell:Rc,cellValue:Mc,eyebrow:Bc,total:Ac,period:Lc,monthRow:$c,monthLabel:Pc,monthValue:Oc,monthCount:qc,paidIcon:Uc,upcomingIcon:zc,missedIcon:Fc,missedValue:Hc,priceBlock:Wc,priceHeader:Ec,priceTitle:Vc,priceImpact:Yc,priceList:Kc,priceRow:Gc,priceName:Qc,priceChange:Jc,staleNote:Xc,skeletonLine:Zc,skeletonBig:el},nl=({items:n,history:t,currency:a,view:o,isLoading:p=!1,onSelectBill:s})=>{const{t:c}=ae(),u=P.useMemo(()=>Dc(n,t),[n,t]),l=r=>E(r,a,{}),f=r=>E(Math.round(r),a,{hideDecimals:!0});if(p&&n.length===0)return e.jsxs("div",{className:S.card,children:[e.jsx(z,{className:S.skeletonLine}),e.jsx(z,{className:S.skeletonBig}),e.jsx(z,{className:S.skeletonLine})]});const v=o!=="personal"&&Math.abs(u.myShareMonthly-u.monthly)>=.5,i=u.priceIncreases.reduce((r,_)=>r+_.monthlyIncrease,0)*12;return e.jsxs("section",{className:S.card,"aria-label":c("recurring.overview.title","Recurring spending"),children:[e.jsxs("div",{className:S.columns,children:[e.jsxs("div",{className:S.quad,children:[e.jsxs("div",{className:S.cell,children:[e.jsx("span",{className:S.eyebrow,children:c("recurring.overview.title","Recurring spending")}),e.jsxs("span",{className:S.total,children:[l(u.monthly),e.jsx("span",{className:S.period,children:c("recurring.perMonth","/mo")})]})]}),e.jsxs("div",{className:`${S.cell} ${S.cellEnd}`,children:[e.jsx("span",{className:S.eyebrow,children:c("recurring.overview.active","Active")}
1),e.jsx("span",{className:S.cellValue,children:u.activeCount})]}),e.jsxs("div",{className:S.cell,children:[e.jsx("span",{className:S.eyebrow,children:c("recurring.overview.perYear","Per year")}),e.jsx("span",{className:S.cellValue,children:f(u.yearly)})]}),v&&e.jsxs("div",{className:`${S.cell} ${S.cellEnd}`,children:[e.jsx("span",{className:S.eyebrow,children:c("recurring.overview.yourShare","Your share")}),e.jsxs("span",{className:S.cellValue,children:[l(u.myShareMonthly),e.jsx("span",{className:S.period,children:c("recurring.perMonth","/mo")})]})]})]}),e.jsxs("div",{className:S.monthBlock,children:[e.jsxs("div",{className:S.monthRow,children:[e.jsx(Lt,{size:16,className:S.paidIcon,"aria-hidden":"true"}),e.jsxs("span",{className:S.monthLabel,children:[c("recurring.overview.paidThisMonth","Paid this month"),e.jsx("span",{className:S.monthCount,children:c("recurring.overview.billCount","{{count}} bills",{count:u.paidCount})})]}),e.jsx("span",{className:S.monthValue,children:l(u.paidThisMonth)})]}),e.jsxs("div",{className:S.monthRow,children:[e.jsx(kn,{size:16,className:S.upcomingIcon,"aria-hidden":"true"}),e.jsxs("span",{className:S.monthLabel,children:[c("recurring.overview.stillToCome","Still to come"),e.jsx("span",{className:S.monthCount,children:c("recurring.overview.billCount","{{count}} bills",{count:u.upcomingCount})})]}),e.jsx("span",{className:S.monthValue,children:l(u.upcomingThisMonth)})]}),u.missedCount>0&&e.jsxs("div",{className:S.monthRow,children:[e.jsx(st,{size:16,className:S.missedIcon,"aria-hidden":"true"}),e.jsxs("span",{className:S.monthLabel,children:[c("recurring.overview.missed","Missed"),e.jsx("span",{className:S.monthCount,children:c("recurring.overview.billCount","{{count}} bills",{count:u.missedCount})})]}),e.jsx("span",{className:`${S.monthValue} ${S.missedValue}`,children:l(u.missedAmount)})]})]})]}),u.priceIncreases.length>0&&e.jsxs("div",{className:S.priceBlock,children:[e.jsxs("div",{className:S.priceHeader,children:[e.jsx(ke,{size:14,className:S.missedIcon,"aria-hidden":"true"}),e.jsx("span",{className:S.priceTitle,children:c("recurring.overview.priceIncreases","Price increases")}),e.jsx("span",{className:S.priceImpact,children:c("recurring.overview.priceImpact","+{{amount}} a year",{amount:f(i)})})]}),e.jsx("ul",{className:S.priceList,children:u.priceIncreases.slice(0,3).map(r=>e.jsx("li",{children:e.jsxs("button",{type:"button",className:S.priceRow,onClick:()=>s?.(r.id),disabled:!s,children:[e.jsx("span",{className:S.priceName,children:r.name}),e.jsxs("span",{className:S.priceChange,children:[l(r.from)," â ",l(r.to)]})]})},r.id))})]}),u.staleCount>0&&e.jsx("p",{className:S.staleNote,children:c("recurring.overview.staleNote","{{count}} bills have had no charge in 2 cycles, so they are left out of these totals.",{count:u.staleCount})})]})},tl=Se({patternId:me(),action:De(["accept","dismiss"]),recurrence:De(oa).optional()}),al=async(n,t)=>{const a=tl.parse(n),o=await fetch("/_api/recurring/review-frequency",{method:"POST",body:oe.stringify(a),...t,headers:{"Content-Type":"application/json"}});if(!o.ok){const p=oe.parse(await o.text());throw new Error(p.error)}return oe.parse(await o.text())},sl=()=>{const n=Me(),{t}=ae();return He({mutationFn:a=>al(a),onSuccess:(a,o)=>{n.invalidateQueries({queryKey:[We]}),ne.success(o.action==="accept"?t("recurring.frequencyReview.updated","Frequency updated."):t("recurring.frequencyReview.kept","Kept as it was."))},onError:a=>{ne.error(a.message||t("recurring.frequencyReview.failed","We couldn't save that. Please try again."))}})},rl="_container_1nb3x_1",ol="_card_1nb3x_8",il="_info_1nb3x_20",cl="_header_1nb3x_27",ll="_icon_1nb3x_34",dl="_label_1nb3x_38",ul="_merchant_1nb3x_44",ml="_flow_1nb3x_50",pl="_old_1nb3x_56",hl="_arrow_1nb3x_62",gl="_helper_1nb3x_72",_l="_actions_1nb3x_77",xl="_btn_1nb3x_83",ue={container:rl,card:ol,info:il,header:cl,icon:ll,label:dl,merchant:ul,flow:ml,old:pl,arrow:hl,new:"_new_1nb3x_66",helper:gl,actions:_l,btn:xl},Jn=({bills:n,patternType:t,className:a})=>{const{t:o}=ae(),{mutate:p,isPending:s}=sl(),c=l=>{switch(l){case"weekly":return o("recurring.frequencyWeekly","Weekly");case"biweekly":return o("recurring.frequencyBiweekly","Bi-weekly");case"semimonthly":return o("recurring.frequencySemimonthly","Twice a month");case"monthly":return o("recurring.frequencyMonthly","Monthly");case"quarterly":return o("recurring.frequencyQuarterly","Quarterly");case"yearly":return o("recurring.frequencyYearly","Yearly");default:return l??""}},u=n.filter(l=>l.frequencyChangeNeedsReview&&l.pendingRecurrenceType&&l.source==="pattern"&&l.patternType===t);return u.length===0?null:e.jsx("div",{className:`${ue.container} ${a??""}`,children:u.map(l=>e.jsxs("div",{className:ue.card,children:[e.jsxs("div",{className:ue.info,children:[e.jsxs("div",{className:ue.header,children:[e.jsx(kn,{size:14,className:ue.icon,"aria-hidden":"true"}),e.jsx("span",{className:ue.label,children:o("recurring.frequencyReview.label","Schedule changed?")}),e.jsx("span",{className:ue.merchant,children:l.merchantName})]}),e.jsxs("div",{className:ue.flow,children:[e.jsx("span",{className:ue.old,children:c(l.recurrence)}),e.jsx(et,{size:14,className:ue.arrow,"aria-hidden":"true"}),e.jsx("span",{className:ue.new,children:c(l.pendingRecurrenceType)})]}),e.jsx("span",{className:ue.helper,children:o("recurring.frequencyReview.helper","The last 3 charges came on this new schedule.")})]}),e.jsxs("div",{className:ue.actions,children:[e.jsx(Z,{variant:"outline",className:ue.btn,disabled:s,onClick:()=>p({patternId:l.originalId,action:"dismiss"}),children:o("recurring.frequencyReview.keep","Keep {{frequency}}",{frequency:c(l.recurrence)})}),e.jsx(Z,{variant:"primary",className:ue.btn,disabled:s,onClick:()=>p({patternId:l.originalId,action:"accept"}),children:o("recurring.frequencyReview.switch","Switch to {{frequency}}",{frequency:c(l.pendingRecurrenceType)})})]})]},l.id))})},yl="_wrapper_1tqv6_1",fl="_cardContainer_1tqv6_26",vl="_sectionHeaderRow_1tqv6_41",jl="_expandButton_1tqv6_48",wl="_sectionHeader_1tqv6_41",Nl="_sectionSubtext_1tqv6_66",Cl="_titleNote_1tqv6_75",bl="_mobileSubtext_1tqv6_86",Dl="_c
1omingUpTitle_1tqv6_89",kl="_cardList_1tqv6_97",Sl="_cardSkeleton_1tqv6_103",Tl="_sectionContainer_1tqv6_111",Il="_unifiedSection_1tqv6_149",Rl="_unifiedSummary_1tqv6_171",Ml="_desktopUnifiedSection_1tqv6_191",Bl="_desktopUnifiedSummary_1tqv6_201",Al="_desktopUnifiedTableWrapper_1tqv6_220",Ll="_unifiedList_1tqv6_235",$l="_swipeWrapper_1tqv6_240",I={wrapper:yl,cardContainer:fl,sectionHeaderRow:vl,expandButton:jl,sectionHeader:wl,sectionSubtext:Nl,titleNote:Cl,mobileSubtext:bl,comingUpTitle:Dl,cardList:kl,cardSkeleton:Sl,sectionContainer:Tl,unifiedSection:Il,unifiedSummary:Rl,desktopUnifiedSection:Ml,desktopUnifiedSummary:Bl,desktopUnifiedTableWrapper:Al,unifiedList:Ll,swipeWrapper:$l},Pl=({subscriptions:n,currency:t,isFetching:a,error:o,isMobile:p,isMarketing:s,view:c,categoryMap:u,rawBills:l,history:f,onEdit:v,onViewHistory:i,onDelete:r,highlightId:_})=>{const{t:d}=ae();if(P.useEffect(()=>{if(!_)return;const m=setTimeout(()=>{let j=null;for(const b of n){const U=b;if(_.startsWith("tx_")){if(b.id.toString()===_.replace("tx_","")){j=b.id.toString();break}}else if(U._billOriginalId?.toString()===_||b.id.toString()===_){j=b.id.toString();break}}if(j){const b=document.querySelector(`[data-recurring-id="${j}"]`);b&&(b.scrollIntoView({behavior:"smooth",block:"center"}),b.classList.add("highlight-pulse"),setTimeout(()=>b.classList.remove("highlight-pulse"),2e3))}},500);return()=>clearTimeout(m)},[_,n]),a&&n.length===0)return e.jsxs("div",{className:I.wrapper,children:[c!=="income"&&e.jsxs("div",{className:I.cardContainer,children:[e.jsx("div",{className:I.sectionHeaderRow,children:e.jsxs("div",{className:I.comingUpTitle,children:[e.jsx("h2",{className:I.sectionHeader,children:d("recurring.comingUp","Coming up")}),e.jsx("p",{className:I.sectionSubtext,children:d("recurring.loadingUpcoming","Loading upcoming charges...")})]})}),e.jsx(z,{className:I.cardSkeleton,style:{height:"60px"}})]}),p?e.jsx("div",{className:I.cardList,children:Array.from({length:5}).map((m,j)=>e.jsx(z,{className:I.cardSkeleton},j))}):e.jsx(tn,{subscriptions:[],categoryMap:u,currency:t,isFetching:!0,error:o,onEdit:v,onViewHistory:i,onDelete:r,view:c})]});if(s)return e.jsxs("div",{className:I.wrapper,children:[c!=="income"&&e.jsxs("div",{className:I.cardContainer,children:[e.jsxs("div",{className:I.sectionHeaderRow,children:[e.jsxs("div",{className:I.comingUpTitle,children:[e.jsxs("h2",{className:I.sectionHeader,children:[d("recurring.comingUp","Coming up"),e.jsx("span",{className:I.titleNote,children:d("recurring.upcomingCompactFallback","(4 charges, {{amount}}, next 14 days)",{amount:E(1997,t,{})})})]}),e.jsx("p",{className:`${I.sectionSubtext} ${I.mobileSubtext}`,children:d("recurring.upcomingSummaryFallback","You have 4 charges for {{amount}} in the next 14 days.",{amount:E(1997,t,{})})})]}),e.jsx(Z,{asChild:!0,variant:"ghost",size:"icon-sm",className:I.expandButton,"aria-label":"View full calendar",children:e.jsx(Pn,{to:"/recurring/calendar",children:e.jsx(On,{size:16})})})]}),e.jsx(Qn,{bills:n,currency:t,days:14,className:I.calendarStrip,isMarketing:s})]}),p?e.jsx("div",{className:I.unifiedSection,children:e.jsx("div",{className:I.unifiedList,children:n.map(m=>e.jsx("div",{"data-recurring-id":m.id,className:I.swipeWrapper,children:e.jsx(xn,{onDelete:()=>r(m),children:e.jsx(fn,{subscription:m,onClick:()=>v(m),onViewHistory:()=>i(m),isMarketing:s})})},m.id))})}):e.jsx(tn,{subscriptions:n,categoryMap:u,currency:t,isFetching:a,error:o,onEdit:v,onViewHistory:i,onDelete:r,showCancelledDate:!1,view:c,isMarketing:s})]});const L=(m,j)=>{const b=m.nextDueDate?.getTime()||1/0,U=j.nextDueDate?.getTime()||1/0;return b-U},N=[...n].sort(L);if(c==="income")return e.jsxs("div",{className:I.wrapper,children:[e.jsx(Gn,{bills:l||[],currency:t}),e.jsx(Jn,{bills:l||[],patternType:"income"}),p?e.jsxs("div",{className:I.unifiedSection,children:[e.jsx(an,{title:d("common.income","Income"),icon:e.jsx(ke,{size:16}),items:N,currency:t,isLoading:a,view:"income",accentColor:"var(--success)",className:I.unifiedSummary}),e.jsx("div",{className:I.unifiedList,children:N.map(m=>e.jsx("div",{"data-recurring-id":m.id,className:I.swipeWrapper,children:e.jsx(xn,{onDelete:()=>r(m),children:e.jsx(fn,{subscription:m,onClick:()=>v(m),onViewHistory:()=>i(m)})})},m.id))})]}):e.jsx("div",{className:I.sectionContainer,children:e.jsxs("div",{className:I.desktopUnifiedSection,children:[e.jsx(an,{title:d("common.income","Income"),icon:e.jsx(ke,{size:16}),items:N,currency:t,isLoading:a,view:"income",accentColor:"var(--success)",className:I.desktopUnifiedSummary}),e.jsx("div",{className:I.desktopUnifiedTableWrapper,children:e.jsx(tn,{subscriptions:N,categoryMap:u,currency:t,isFetching:a,error:o,onEdit:v,onViewHistory:i,onDelete:r,view:c})})]})})]});const x=N.filter(m=>m.billType==="subscription"),H=N.filter(m=>m.billType==="bill"),R=N.filter(m=>m.billType==="savings"),M=N.filter(m=>{const j=m.billType;return j==="other"||!j}),h=(m,j,b,U)=>j.length===0?null:e.jsx("div",{className:I.sectionContainer,children:p?e.jsxs("div",{className:I.unifiedSection,children:[e.jsx(an,{title:m,icon:b,items:j,currency:t,view:c,accentColor:U,className:I.unifiedSummary}),e.jsx("div",{className:I.unifiedList,children:j.map(Y=>e.jsx("div",{"data-recurring-id":Y.id,className:I.swipeWrapper,children:e.jsx(xn,{onDelete:()=>r(Y),children:e.jsx(fn,{subscription:Y,onClick:()=>v(Y),onViewHistory:()=>i(Y)})})},Y.id))})]}):e.jsxs("div",{className:I.desktopUnifiedSection,children:[e.jsx(an,{title:m,icon:b,items:j,currency:t,view:c,accentColor:U,className:I.desktopUnifiedSummary}),e.jsx("div",{className:I.desktopUnifiedTableWrapper,children:e.jsx(tn,{subscriptions:j,categoryMap:u,currency:t,isFetching:a,error:o,onEdit:v,onViewHistory:i,onDelete:r,view:c})})]})},m),B=n.filter(m=>dn(m)),O=B.filter(m=>{if(!m.nextDueDate)return!1;if(m._isUnpaid)return!0;const j=Ee(m.nextDueDate);return j>=0&&j<14}),D=O.length,k=O.reduce((m,j)=>m+sn(j),0),y=m=>{const j=document.querySelector(`[data-recurring-id="${m}"]`);j&&(j.scrollIntoView({behavior:"smooth",block:"center"}),j.classList.add("highlight-pulse"),setTimeout(()=>j.classList.remove("highlight-pulse"),2e3))};return e.jsxs("div",{className:I.wrapper,children:[c==="all"&&e.jsx(Gn,{bills:l||[],currency:t}),c==="all"&&e.jsx(Jn,{bills:l||[],patternType:"expense"}),e.jsx(nl,{items:n,history:f,currency:t,view:c,isLoading:a,onSelectBill:y}),e.jsxs("div",{className:I.cardContainer,children:[e.jsxs("div",{className:I.sectionHeaderRow,children:[e.jsxs("div",{className:I.comingUpTitle,children:[e.jsxs("h2",{className:I.sectionHeader,children:[d("recurring.comingUp","Coming up"),e.jsx("span",{className:I.titleNote,children:D===1?d("recurring.upcomingCompactOne","(1 charge, {{amount}}, next 14 days)",{amount:E(k,t,{})}):d("recurring.upcomingCompactMany","({{count}} charges, {{amount}}, next 14 days)",{count:D,amount:E(k,t,{})})})]}),e.jsx("p",{className:`${I.sectionSubtext} ${I.mobileSubtext}`,children:D===1?d("recurring.upcomingSummaryOne","You have 1 charge for {{amount}} in the next 14 days.",{amount:E(k,t,{})}):d("recurring.upcomingSummaryMany","You have {{count}} charges for {{amount}} in the next 14 days.",{count:D,amount:E(k,t,{})})})]}),e.jsx(Z,{asChild:!0,variant:"ghost",size:"icon-sm",className:I.expandButton,"aria-label":"View full calendar",children:e.jsx(Pn,{to:"/recurring/calendar",children:e.jsx(On,{size:16})})})]}),e.jsx(Qn,{bills:B,currency:t,days:14,className:I.calendarStrip})]}),h(d("recurring.subscriptions","Subscriptions"),x,e.jsx($t,{size:16,fill:"currentColor"}),"var(--muted-foreground)"),h(d("categories.bills","Bills"),H,e.jsx(Pt,{size:16}),"var(--muted-foreground)"),h(d("recurring.savings","Savings"),R,e.jsx(Ot,{size:16}),"var(--muted-foreground)"),h(d("categories.other","Other"),M,e.jsx(it,{size:16}),"var(--muted-foreground)")]})},Ol="_pageHeader_ly0wa_3",ql="_titleRow_ly0wa_25",Ul="_pageTitle_ly0wa_31",zl="_backButton_ly0wa_40",Fl="_aiIconButton_ly0wa_66",Hl="_mobileViewToggleContainer_ly0wa_103",Wl="_chartSectionFirst_ly0wa_107",El="_chartHeaderRow_ly0wa_112",Vl="_chartCardWrapper_ly0wa_119",Yl="_chartInnerNoCard_ly0wa_132",Kl="_filterPills_ly0wa_187",Gl="_filterPill_ly0wa_187",Ql="_filterPillActive_ly0wa_237",Jl="_stickyHeader_ly0wa_13",Xl="_chartSection_ly0wa_107",Zl="_sectionHeader_ly0wa_284",ed="_fullScreenSheet_ly0wa_298",nd="_sheetHeader_ly0wa_312",td="_sheetBody_ly0wa_322",W={pageHeader:Ol,titleRow:ql,pageTitle:Ul,backButton:zl,aiIconButton:Fl,mobileViewToggleContainer:Hl,chartSectionFirst:Wl,chartHeaderRow:El,chartCardWrapper:Vl,chartInnerNoCard:Yl,filterPills:Kl,filterPill:Gl,filterPillActive:Ql,stickyHeader:Jl,chartSection:Xl,sectionHeader:Zl,fullScreenSheet:ed,sheetHeader:nd,sheetBody:td};function vn(n){const a=new URLSearchParams(n).get("view");return a==="all"||a==="shared"||a==="personal"||a==="income"?a:null}const Du=()=>{const{t:n}=ae(),t=P.useMemo(()=>[{value:"all",label:n("common.all","All"),ariaLabel:"View all recurring expenses"},{value:"shared",label:n("common.shared","Shared"),ariaLabel:"View shared recurring expenses"},{value:"personal",label:n("common.personal","Personal"),ariaLabel:"View personal recurring expenses"},{value:"income",label:n("common.income","Income"),ariaLabel:"View income sources"}],[n]),{authState:a}=Tn(),{data:o}=wa(),{currency:p}=Sn(),s=ln(),c=ia();ca();const u=Me(),{impactMedium:l}
1=la(),f=tt(),v=da(),i=qt(),r=new URLSearchParams(i.search).get("highlight"),[_,d]=P.useState(!1),[L,N]=P.useState(null),[x,H]=P.useState(null),[R,M]=P.useState(null),[h,B]=P.useState(!1),[O,D]=P.useState(null),[k,y]=P.useState("subscription"),m=P.useRef(!1),[j,b]=P.useState(()=>{const C=vn(i.search);if(C)return C;const F=o?.defaultView;return F==="shared"||F==="personal"?F:"all"}),U=j==="income",Y=_n("recurring"),ie=_n("recurringShared"),G=_n("recurringPersonal"),xe=P.useMemo(()=>j==="shared"?ie:j==="personal"?G:j==="income"?{illustrationUrl:Y.illustrationUrl,title:"No income sources found yet.",description:"Add your salary, freelance income, or any other recurring income to track it here."}:Y,[j,Y,ie,G]),[te,se]=P.useState(!1),[V,le]=P.useState(null);P.useEffect(()=>{const C=vn(i.search);C&&b(C)},[i.search]),P.useEffect(()=>{if(o?.defaultView){if(vn(i.search))return;const F=o.defaultView;b(F==="shared"||F==="personal"?F:"all")}},[o]);const{data:ee,isFetching:ye,error:he,refetch:fe}=ua({}),{data:J}=ma(),{data:Be}=pt(),Ve=wt(),Ye=dt(),Ke=wn.useCallback(async()=>{l();
1const C=Promise.allSettled([fe(),u.invalidateQueries({queryKey:["categories","list"]})]),F=new Promise(K=>setTimeout(K,15e3));await Promise.race([C,F])},[fe,l,u]),{isRefreshing:un,handleRefresh:mn}=Na(Ke),ce=a.type==="authenticated"&&pa(a.user.email),pn=P.useMemo(()=>ee?.bills?ee.bills.map(ja):[],[ee?.bills]),Ae=ns(pn,ce),Ge=P.useMemo(()=>Be?.categories?new Map(Be.categories.map(C=>[C.id,C])):new Map,[Be]),Le=P.useMemo(()=>Ae?Ae.sort((C,F)=>C.nextDueDate?F.nextDueDate?new Date(C.nextDueDate).getTime()-new Date(F.nextDueDate).getTime():-1:1):[],[Ae]),_e=P.useMemo(()=>{let C=Le;ce||(j==="income"?C=C.filter(K=>K.patternType==="income"):j==="shared"?C=C.filter(K=>K.splitType==="shared"&&K.patternType!=="income"):j==="personal"?C=C.filter(K=>K.splitType!=="shared"&&K.patternType!=="income"):C=C.filter(K=>K.patternType!=="income"));const F=C.filter(K=>!K.cancelledAt);return ce?F.sort((K,ge)=>{const qe=K.description.toLowerCase(),Ue=ge.description.toLowerCase(),Ne=qe.includes("spotify"),Te=Ue.includes("spotify"),Ie=qe.includes("netflix"),hn=Ue.includes("netflix");return Ne&&!Te?-1:!Ne&&Te?1:Ie&&!hn?-1:!Ie&&hn?1:0}):F},[Le,j,ce]),$e=!ye&&_e.length===0;P.useEffect(()=>{if(U||m.current||_e.length===0)return;const C=new Set(_e.map(F=>F.billType));C.has("subscription")?y("subscription"):C.has("bill")?y("bill"):C.has("savings")?y("savings"):C.has("other")&&y("other"),m.current=!0},[_e,U]);const Qe=()=>{N(null),d(!0)},Pe=L?U?n("recurring.editIncome","Edit Income"):n("recurring.editExpense","Edit Expense"):U?n("recurring.newIncome","New recurring income"):n("recurring.newExpense","New recurring expense"),T=async C=>{const F=C;if(F._billSource==="pattern"&&F._billOriginalId&&F.patternType!=="income"){let K=null;const ge=setTimeout(()=>{K=ne.loading(n("common.loading","Loading transaction..."),{closeButton:!0})},300);let qe;const Ue=()=>{clearTimeout(ge),clearTimeout(qe),K!==null&&ne.dismiss(K)};try{const Ne=u.fetchQuery({queryKey:["recurring","latest-transaction",F._billOriginalId],queryFn:()=>Xa({patternId:F._billOriginalId}),staleTime:3e5}),Te=new Promise((hn,St)=>{qe=setTimeout(()=>St(new Error("Request timed out")),1e4)}),Ie=await Promise.race([Ne,Te]);Ue(),Ie&&Ie.transaction?(M(Ie.transaction),D(F),B(!0)):(ne(n("recurring.noLinkedTransactions","No linked transactions found. Opening subscription editor instead.")),N(C),d(!0))}catch(Ne){Ue();const Te=Ne instanceof Error&&Ne.message==="Request timed out"?n("recurring.linkedTransactionTimeout","Request timed out. Opening subscription editor instead."):n("recurring.linkedTransactionError","Failed to fetch linked transaction. Opening subscription editor instead.");ne(Te),N(C),d(!0)}}else N(C),d(!0)},$=C=>{H(C)},de=C=>{B(C),C||(M(null),D(null))},je=()=>{B(!1),M(null),D(null),u.invalidateQueries({queryKey:[We]})},Oe=()=>{const C=O;B(!1),M(null),D(null),C&&Bn(C)},Bn=C=>{le(C),se(!0)},bt=()=>{if(!V)return;const C=V.patternType==="income",F=()=>{ne.success(C?n("recurring.incomeTrackingStopped","Removed from recurring income tracking"):n("recurring.subscriptionTrackingStopped","Subscription removed from recurring tracking")),se(!1),le(null)},K=ge=>{ne.error(ge instanceof Error?ge.message:C?n("recurring.stopTrackingIncomeError","Failed to stop tracking income"):n("recurring.stopTrackingSubscriptionError","Failed to stop tracking subscription"))};V._billSource==="pattern"?Ve.mutate({id:V.id},{onSuccess:F,onError:K}):Ye.mutate({id:V.id,isRecurring:!1},{onSuccess:F,onError:K})},Dt=C=>{Bn(C)},kt=()=>{se(!1),le(null)},An=()=>{d(!1),N(null)},Ln=()=>{const C=_e.some(ge=>ge.billType==="other"),F={subscription:n("recurring.subscriptions","Subscriptions"),bill:n("categories.bills","Bills"),savings:n("recurring.savings","Savings"),other:n("categories.other","Other")},K=["subscription","bill","savings"];return C&&K.push("other"),e.jsx("div",{className:W.filterPills,children:K.map(ge=>e.jsx("button",{type:"button",className:`${W.filterPill} ${k===ge?W.filterPillActive:""}`,onClick:()=>y(ge),children:F[ge]},ge))})};return e.jsxs(e.Fragment,{children:[e.jsxs(Ft,{children:[e.jsx("title",{children:"Track Recurring Expenses & Bills | Halfway Couples Budgeting"}),e.jsx("meta",{name:"description",content:"Manage recurring expenses like Netflix, rent, or childcare. Halfway automatically tracks renew
1als and splits shared costs fairly between partners."}),e.jsx("link",{rel:"icon",type:"image/webp",href:"https://pub-9191c1ede9c74f98988a8e0b80c0c46b.r2.dev/migrated/7a266cb4-5a34-48b3-b08e-5491102ad78a.webp"}),e.jsx("link",{rel:"apple-touch-icon",href:"https://pub-9191c1ede9c74f98988a8e0b80c0c46b.r2.dev/migrated/7a266cb4-5a34-48b3-b08e-5491102ad78a.webp"})]}),e.jsxs(Ca,{onRefresh:mn,isRefreshing:un,children:[e.jsxs("div",{className:W.stickyHeader,children:[e.jsxs("div",{className:W.pageHeader,children:[e.jsxs("div",{className:W.titleRow,children:[s&&e.jsx("button",{onClick:()=>f("/dashboard"),className:W.backButton,"aria-label":"Go back",type:"button",children:e.jsx(ct,{size:20})}),e.jsx("h1",{className:W.pageTitle,children:n("recurring.recurring","Recurring")}),e.jsx("button",{type:"button",onClick:()=>v("recurring"),className:W.aiIconButton,"aria-label":n("recurring.askPenny","Ask Penny about your bills"),title:n("recurring.askPenny","Ask Penny about your bills"),children:e.jsx(Ut,{size:16})})]}),!s&&!ce&&e.jsx(Wn,{value:j,onValueChange:b,options:t,size:"sm","aria-label":"Toggle recurring view"})]}),s&&!ce&&e.jsx("div",{className:W.mobileViewToggleContainer,children:e.jsx(Wn,{value:j,onValueChange:b,options:t,size:"sm","aria-label":"Toggle recurring view"})})]}),!ce&&e.jsx(Ka,{}),he?e.jsx(Ta,{error:he,onRetry:()=>{fe()},entity:n("common.errors.entities.recurring","your recurring expenses")}):$e?e.jsx(Sa,{icon:e.jsx(zt,{size:32}),illustration:xe.illustrationUrl,title:xe.title,description:xe.description}):e.jsx(Pl,{highlightId:r,subscriptions:_e,currency:p,isFetching:ye,error:he,isMobile:s,isMarketing:ce,view:j,categoryMap:Ge,rawBills:ee?.bills,history:ce?void 0:J,onEdit:T,onViewHistory:$,onDelete:Dt}),U&&e.jsx("div",{className:W.chartSectionFirst,children:e.jsxs("div",{className:W.chartCardWrapper,children:[e.jsx("div",{className:W.chartHeaderRow,children:e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"var(--spacing-2)"},children:[e.jsx("h2",{className:W.sectionHeader,children:n("recurring.overallIncomeTrends","Overall Income Trends")}),e.jsx(Ia,{content:n("recurring.incomeTrendsTooltip","This chart covers ALL your income, not just the recurring sources listed above â paychecks, bonuses, side income and other deposits. Transfers between your own accounts and investment movements are excluded."),children:e.jsx(Xn,{size:15,color:"var(--muted-foreground)"})})]})}),e.jsx(fr,{currency:p,isLoading:ye,className:W.chartInnerNoCard})]})}),!U&&!$e&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:W.chartSectionFirst,children:e.jsxs("div",{className:W.chartCardWrapper,children:[e.jsxs("div",{className:W.chartHeaderRow,children:[e.jsx("h2",{className:W.sectionHeader,children:n("reports.spendingBreakdown","Spending Breakdown")}),Ln()]}),e.jsx(cr,{subscriptions:_e,currency:p,isLoading:ye,billTypeFilter:k,className:W.chartInnerNoCard})]})}),e.jsx("div",{className:W.chartSection,children:e.jsxs("div",{className:W.chartCardWrapper,children:[e.jsxs("div",{className:W.chartHeaderRow,children:[e.jsx("h2",{className:W.sectionHeader,children:n("recurring.paidEachMonth","Paid each month")}),Ln()]}),e.jsx(Us,{transactions:_e,history:J,isLoading:ye,billTypeFilter:k,className:W.chartInnerNoCard})]})})]})]}),!ce&&e.jsx(ba,{onClick:Qe,icon:e.jsx(nt,{size:20}),ariaLabel:"Add recurring expense"}),s?e.jsxs(e.Fragment,{children:[e.jsx(ha,{open:_,onOpenChange:d,children:e.jsxs(ga,{side:"bottom",className:W.fullScreenSheet,fullHeight:!0,hideCloseButton:!0,hideDragHandle:!0,children:[e.jsx(_a,{className:W.sheetHeader,showCloseButton:!0,children:e.jsx(xa,{children:Pe})}),e.jsx("div",{className:W.sheetBody,style:{paddingBottom:c>0?c:void 0},children:e.jsx(Kn,{subscription:L,onSuccess:An,mode:U?"income":"expense"})})]})}),e.jsx(mt,{open:!!x,onOpenChange:C=>!C&&H(null),merchantName:x?.description,merchantIcon:x?.merchantLogoUrl||void 0,isIncome:x?.patternType==="income",onTransactionClick:()=>H(null)})]}):e.jsxs(e.Fragment,{children:[e.jsx(Un,{open:_,onOpenChange:d,children:e.jsxs(zn,{children:[e.jsx(Fn,{children:e.jsx(Hn,{children:Pe})}),e.jsx(Kn,{subscription:L,onSuccess:An,mode:U?"income":"expense"})]})}),e.jsx(ht,{open:!!x,onOpenChange:C=>!C&&H(null),merchantName:x?.description,merchantIcon:x?.merchantLogoUrl||void 0,isIncome:x?.patternType==="income",onTransactionClick:()=>H(null)})]}),e.jsx(fa,{open:h,onOpenChange:de,transaction:R,onSuccess:je,onDelete:Oe,deleteLabel:n("recurring.stopTrackingButton","Stop Tracking")}),e.jsx(Un,{open:te,onOpenChange:se,children:e.jsxs(zn,{children:[e.jsx(Fn,{children:e.jsx(Hn,{children:V?.patternType==="income"?n("recurring.stopTrackingIncomeTitle","Stop Tracking This Income?"):n("recurring.stopTrackingSubscriptionTitle","Stop Tracking This Subscription?")})}),e.jsx("p",{style:{marginBottom:"var(--spacing-4)",color:"var(--foreground)"},children:V?.patternType==="income"?n("recurring.deleteIncomeDesc","This will remove {{name}} from your recurring income tracking. Your past transactions won't be affected.",{name:V.description}):V?._billSource==="pattern"?n("recurring.deletePatternDesc","This will remove {{name}} from your recurring bills. Your past transactions will be kept but will no longer be linked to this subscription.",{name:V.description}):n("recurring.deleteTransactionDesc","This will stop tracking {{name}} as a recurring expense. The transaction will remain in your history.",{name:V?.description})}),e.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:"var(--spacing-2)"},children:[e.jsx(Z,{variant:"outline",onClick:kt,children:n("common.cancel","Cancel")}),e.jsx(Z,{variant:"destructive",onClick:bt,disabled:Ve.isPending||Ye.isPending,children:n("recurring.stopTrackingButton","Stop Tracking")})]})]})})]})};export{Du as default};
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.