PageSourceSearch

https://eisenhowertodoist.netlify.app/assets/index--kdl1ae9.js

js eisenhowertodoist.netlify.app collected 2026-10-03 10:41:18 UTC 551,442 bytes, 32 lines download raw bytes

1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/FeatureTour-BvQZ-bXu.js","assets/vendor-1kUQ7zn2.js","assets/vendor-date-en1IyhsK.js","assets/vendor-supabase-Dh2gyaRa.js","assets/vendor-motion-BX-jsy7E.js","assets/MobileFilterSheet-CD03krW8.js","assets/SettingsDialog-BEGO-5Bn.js","assets/AiConsentDialog-CkXfz-s-.js","assets/slider-D6mh3qnw.js","assets/DeleteAccountDialog-CMaSG8PP.js","assets/GumroadLicenseDialog-CxkArFHj.js","assets/license-C3P8flk1.js","assets/checkoutState-C2DchyvW.js","assets/FeatureRequestDialog-CT2R6KQ8.js","assets/textarea-eVnMW_FJ.js","assets/TaskCommentsDialog-BnBwvN69.js","assets/FocusedTaskOverlay-DZ6qBPtJ.js","assets/focusStats-sBxcroA-.js","assets/focus-adIRnHuT.js","assets/focus-Chh2JnFh.css","assets/ParentHint-C6NcJBXf.js","assets/MobileFocusOverlay-CTuWVBes.js","assets/MobileTaskActionSheet-mqUgU2VK.js","assets/PlanPanel-DyQyrbCZ.js","assets/checkout-DROMBe3d.js","assets/PlanPicker-C8gzQIYq.js","assets/TrialPlansPanel-p_lTinxu.js","assets/Statistics-C6kF8i-x.js","assets/vendor-charts-gGf1aRzE.js","assets/Statistics-C05fa6uA.css","assets/DailyReviewDialog-cTmWj_Jx.js","assets/DailyReviewDialog-BG9FtDFQ.css","assets/MatrixSheets-76SgZskf.js","assets/scroll-area-Domx4w8f.js","assets/MovedHereReviewSheet-CZ3kfDxh.js","assets/UpgradePrompt-CifKKiPm.js","assets/ApiKeyManager-VatIB6Wy.js","assets/LandingPage-BZz1aGrd.js","assets/ResetRequestForm-BGTDKErw.js","assets/NPSSurvey-DNw8ssZI.js","assets/Achievements-DpW-_NoR.js","assets/Checkout-CVNi1jve.js","assets/ResetPassword-0NCm7ytb.js","assets/Admin-BAtFewQU.js","assets/CheckoutStatus-BmBXbUFj.js","assets/CheckoutStatus-B0ZSkDq_.css"])))=>i.map(i=>d[i]);
2import{c as i,D as yp,j as s,T as wp,E as vp,C as kp,F as Xd,P as jp,H as Np,J as Sp,K as Z,L as at,M as Xt,N as it,O as Zd,Q as qn,S as Ti,U as Xn,V as Cp,W as gr,X as Tp,Y as kt,Z as xr,$ as _i,a0 as ln,a1 as br,a2 as dn,a3 as yr,a4 as Ie,a5 as un,a6 as wr,a7 as Ei,a8 as _p,a9 as Ep,aa as Ss,ab as Dp,ac as vr,ad as Cs,ae as eu,af as tu,ag as Rp,ah as su,ai as nu,aj as pt,ak as au,al as Ip,am as ru,an as ou,ao as iu,ap as cu,aq as Oe,ar as lu,as as Di,at as du,au as uu,av as Mp,aw as Lp,ax as Mt,ay as Ri,az as Ap,aA as mt,aB as Kt,aC as mu,aD as Ii,aE as Zn,aF as kr,aG as jr,aH as Mi,aI as Yt,aJ as ea,aK as mn,aL as ta,aM as Pp,R as Ue,aN as Lc,aO as Op,aP as fu,aQ as $p,aR as hu,aS as Is,aT as Li,aU as Ai,aV as pu,aW as os,aX as Zs,aY as Wt,aZ as Pi,a_ as Fp,a$ as qp,b0 as zp,b1 as Up,b2 as Bp,b3 as Hp,b4 as gu,b5 as zn,b6 as Vp,b7 as Un,b8 as Ts,b9 as Kp,ba as _o,bb as fn,bc as Yp,bd as Wp,be as xu,bf as Gp,bg as Qp,bh as bu,bi as Jp,bj as yu,bk as Xp,bl as wu,bm as Zp,bn as eg,bo as vu,bp as tg,bq as sg,br as ku,bs as ng,bt as ju,bu as ag,bv as rg,bw as Nu,bx as Su,by as Cu,bz as Tu,bA as _u,bB as og,bC as Eu,bD as ig,bE as cg,bF as lg,bG as dg,bH as Du,bI as Ru,bJ as ug,bK as mg,bL as Iu,bM as Mu,bN as Lu,bO as Au,bP as Pu,bQ as fg,bR as hg,bS as pg,bT as gg,bU as xg,bV as bg,bW as Ou,bX as $u,bY as yg,bZ as wg,b_ as vg,b$ as kg,c0 as jg,c1 as Ng,c2 as Sg,c3 as Cg,c4 as Tg,c5 as _g,c6 as Eg,c7 as Dg,c8 as Rg,c9 as Ig,ca as Mg,cb as Lg,cc as zt,cd as Ac,ce as Ag,cf as Pg,cg as Og,ch as $g,ci as Fg,cj as qg}from"./vendor-1kUQ7zn2.js";import{c as zg,d as we,F as Ug}from"./vendor-supabase-Dh2gyaRa.js";import{m as te,a as _e,A as Gt,L as Fu,d as qu,M as zu}from"./vendor-motion-BX-jsy7E.js";import{D as Ee,F as Ms,G as Oi,H as Bg,c as Hg,I as _s,g as st,b as Uu,e as Vg,s as Kg,m as Bu,y as Pc,A as Eo,J as Oc,K as Nr,L as Hu,M as Vu,j as ls,a as Bn,N as Yg,f as Wg,O as Gg}from"./vendor-date-en1IyhsK.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))a(r);new MutationObserver(r=>{for(const o of r)if(o.type==="childList")for(const c of o.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&a(c)}).observe(document,{childList:!0,subtree:!0});function n(r){const o={};return r.integrity&&(o.integrity=r.integrity),r.referrerPolicy&&(o.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?o.credentials="include":r.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function a(r){if(r.ep)return;r.ep=!0;const o=n(r);fetch(r.href,o)}})();if(typeof console<"u"){const e=()=>{},t=["log","info","debug","warn","error","trace","table","dir","dirxml","group","groupCollapsed","groupEnd","count","countReset","time","timeEnd","timeLog","assert"];for(const n of t)try{console[n]=e}catch{}}const Qg="https://eisenhowertodoist.com",$c="/reset-password",iT=e=>`${Qg}${e}`,Jg=()=>{const e={type:null,hasAccessToken:!1,tokenHash:null,errorCode:null,errorDescription:null};if(typeof window>"u")return e;try{const t=new URLSearchParams(window.location.search),n=new URLSearchParams(window.location.hash.replace(/^#/,"")),a=l=>n.get(l)??t.get(l),r=a("error"),o=a("error_code"),c=a("error_description");return{type:a("type"),hasAccessToken:n.has("access_token"),tokenHash:t.get("token_hash"),errorCode:o??r??(c?"unspecified":null),errorDescription:c}}catch{return e}},Fc=Jg();if(typeof window<"u"&&Fc.type==="recovery"&&Fc.hasAccessToken&&window.location.pathname!==$c)try{window.history.replaceState(window.history.state,"",`${$c}${window.location.search}${window.location.hash}`)}catch{}const Xg="modulepreload",Zg=function(e){return"/"+e},qc={},Ne=function(t,n,a){let r=Promise.resolve();if(n&&n.length>0){let d=function(m){return Promise.all(m.map(u=>Promise.resolve(u).then(f=>({status:"fulfilled",value:f}),f=>({status:"rejected",reason:f}
2))))};document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),l=c?.nonce||c?.getAttribute("nonce");r=d(n.map(m=>{if(m=Zg(m),m in qc)return;qc[m]=!0;const u=m.endsWith(".css"),f=u?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${m}"]${f}`))return;const p=document.createElement("link");if(p.rel=u?"stylesheet":Xg,u||(p.as="script"),p.crossOrigin="",p.href=m,l&&p.setAttribute("nonce",l),document.head.appendChild(p),u)return new Promise((h,g)=>{p.addEventListener("load",h),p.addEventListener("error",()=>g(new Error(`Unable to preload CSS for ${m}`)))})}))}function o(c){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=c,window.dispatchEvent(l),!l.defaultPrevented)throw c}return r.then(c=>{for(const l of c||[])l.status==="rejected"&&o(l.reason);return t().catch(o)})},ex=768,tx=`(max-width: ${ex-1}px), (max-height: 500px) and (pointer: coarse)`;let Br=null;const Ku=()=>(!Br&&typeof window<"u"&&"matchMedia"in window&&(Br=window.matchMedia(tx)),Br),sx=e=>{const t=Ku();return t?(t.addEventListener("change",e),()=>t.removeEventListener("change",e)):()=>{}},Yu=()=>Ku()?.matches??!1,nx=()=>!1;function Fe(){return i.useSyncExternalStore(sx,Yu,nx)}const nt=()=>Yu(),ax=({...e})=>{const{theme:t="system"}=yp(),n=Fe();return s.jsx(wp,{theme:t,className:"toaster group",position:"bottom-right",expand:!1,closeButton:!0,visibleToasts:n?1:2,toastOptions:{duration:n?3e3:3500},...e})};function S(...e){return vp(kp(e))}const Ls=jp,Ht=Np,Vt=Sp,At=i.forwardRef(({className:e,sideOffset:t=4,...n},a)=>s.jsx(Xd,{ref:a,sideOffset:t,className:S("z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...n}));At.displayName=Xd.displayName;const $i="https://zhowxgsinuyxjfjlepuq.supabase.co",Ga="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Inpob3d4Z3NpbnV5eGpmamxlcHVxIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MzUxMDAwMzMsImV4cCI6MjA1MDY3NjAzM30.fBFJ5x18ykZ9qr-8lX1YaoU37bYPQ0olD3Jar-28Pss",B=zg($i,Ga);function Fi(e){const{title:t,description:n,variant:a="default",duration:r=3e3}=e,o=t||n,c={description:t?n:void 0,duration:r};switch(a){case"destructive":return Z.error(o,c);case"success":return Z.success(o,c);default:return Z(o,c)}}function He(){return{toast:Fi,dismiss:Z.dismiss}}const Bt=({message:e})=>{const[t,n]=i.useState(!1);return i.useEffect(()=>{const a=setTimeout(()=>{n(!0)},1e4);return()=>clearTimeout(a)},[]),s.jsx("div",{className:"min-h-screen bg-background",children:s.jsx("div",{className:"flex flex-col justify-center items-center h-[calc(100vh-64px)]",children:s.jsxs(te.div,{className:"text-center space-y-4",initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{duration:.5,ease:[.4,0,.2,1]},children:[s.jsxs(te.div,{className:"relative mx-auto h-12 w-12 flex items-center justify-center",animate:{scale:[.96,1.04,.96]},transition:{duration:3,repeat:1/0,ease:[.4,0,.6,1]},children:[s.jsx("div",{className:"absolute inset-0",children:s.jsx(te.div,{className:"h-full w-full rounded-full border-2 border-primary/20",animate:{scale:[.8,1.15,.8],opacity:[.3,.5,.3]},transition:{duration:3,repeat:1/0,ease:[.4,0,.6,1]}})}),s.jsx(te.div,{className:"absolute inset-0",animate:{rotate:360},transition:{duration:1.5,repeat:1/0,ease:"linear"},children:s.jsx("div",{className:"h-full w-full border-b-2 border-primary rounded-full"})})]}),s.jsx(te.p,{className:"text-muted-foreground",animate:{opacity:[.7,1,.7]},transition:{duration:2,repeat:1/0,ease:"easeInOut"},children:e}),t&&s.jsxs(te.div,{className:"mt-8 text-sm text-muted-foreground",initial:{opacity:0,height:0},animate:{opacity:1,height:"auto"},transition:{duration:.5},children:[s.jsx("p",{children:"Still loading? Try refreshing the page."}),s.jsx(te.button,{onClick:()=>window.location.reload(),className:"mt-2 px-4 py-2 text-sm rounded-md bg-primary/10 hover:bg-primary/20 text-primary",whileHover:{scale:1.03},whileTap:{scale:.97},transition:{type:"spring",stiffness:400,damping:17},children:"Refresh"})]})]})})})},je=(...e)=>({kind:"enum",values:e}),Do=(e,t)=>({kind:"int",min:e,max:t}),fa={kind:"bool"},ha={kind:"token"},rx=["0","1-5","6-20","21-50","51-100","100+"],ox=["0-1","2-4","5-14","15-24","25-49","50+"],hs=je("desktop","phone"),pa=je(...rx),ix=je("do","schedule","delegate","backlog"),Hr=je("do","schedule","delegate","backlog","unsorted"),Vr=je("lifetime","monthly","yearly","membership"),ga=Do(1,500),cx=["denied","state","expired","no_session","exchange","no_token","save","init","login","unknown"],lx=["consent_required","limit_reached","rate_limited","no_access","no_tasks","ai_unavailable","ai_busy","ai_timeout","bad_output","refused","not_signed_in","invali
2d_request","server_error","network"],Wu={app_opened:{layout:hs},signed_up:{method:je("google","email","todoist"),utm_source:ha,utm_medium:ha,utm_campaign:ha,ref:ha},signed_in:{method:je("google","email","todoist")},connect_todoist_viewed:{layout:hs},connect_todoist_clicked:{via:je("screen","retry")},connect_todoist_result:{result:je("ok","cancelled","error"),code:je(...cx),via:je("connect","login")},matrix_viewed:{tasks:pa,unsorted:pa,layout:hs,view:je("classic","clean","mobile")},categorize_opened:{kind:je("sheet","bulk","starter"),unsorted:pa},task_categorized:{quadrant:ix,via:je("buttons","tap","key","all","row","move","bulk"),sheet:je("categorize","starter","recategorize","matrix"),n:ga},ai_suggest_run:{result:je("ok","error"),code:je(...lx),tasks:pa},ai_consent:{state:je("granted","revoked")},task_added:{quadrant:Hr,via:je("dialog","row"),n:ga},task_completed:{quadrant:Hr,focus:fa,n:ga},task_deleted:{quadrant:Hr,via:je("menu","key","sheet"),recurring:fa},task_delete_undone:{n:ga},follow_up_created:{},focus_started:{layout:hs},focus_ended:{minutes:je(...ox),idle:fa},daily_review_opened:{auto:fa},stats_opened:{},filters_used:{kind:je("date","label","project","priority","todoist_filter","subtasks")},settings_opened:{},tour_started:{kind:je("onboarding","replay"),layout:hs},tour_completed:{kind:je("onboarding","replay")},tour_skipped:{kind:je("onboarding","replay"),step:Do(0,50)},plans_viewed:{layout:hs},checkout_started:{plan:Vr},checkout_result:{result:je("activated","closed","slow","cancelled"),plan:Vr},license_dialog_opened:{},license_activated:{plan:Vr},logged_out:{},session_active:{seconds:Do(5,3600),surface:hs},starter_card:{action:je("shown","started","dismissed")},view_changed:{kind:je("quadrant_tab","layout","density"),to:je("do","schedule","delegate","backlog","clean","classic","compact","default","comfortable")},task_opened:{surface:je("sheet","expand","detail")},due_changed:{via:je("picker","nl","swipe","quick"),kind:je("date","time","cleared")},error_shown:{kind:je("tasks_load","todoist_auth","network","other")}},Gu=e=>typeof e=="string"&&Object.prototype.hasOwnProperty.call(Wu,e),dx=["task_categorized","task_completed","task_added","task_deleted","task_delete_undone","due_changed","follow_up_created","focus_started","filters_used","daily_review_opened","ai_suggest_run"],ux=new Set(dx);function mx(e,t){return!(!ux.has(e)||e==="daily_review_opened"&&t?.auto===!0)}function cT(e,t){if(!mx(e,t))return 0;const n=t?.n;return typeof n=="number"&&n>=1?Math.round(n):1}function Sr(e){return typeof e!="string"?null:e.trim().toLowerCase().replace(/[^a-z0-9_.+-]+/g,"_").replace(/^_+|_+$/g,"").slice(0,40)||null}function fx(e,t){switch(e.kind){case"enum":return typeof t=="string"&&e.values.includes(t)?t:null;case"int":{if(typeof t!="number"||!Number.isFinite(t))return null;const n=Math.round(t);return n>=e.min&&n<=e.max?n:null}case"bool":return typeof t=="boolean"?t:null;case"token":return Sr(t)}}function hx(e,t){if(!Gu(e))return null;const n=Wu[e],a={};if(!t||typeof t!="object")return a;for(const r of Object.keys(n)){if(!Object.prototype.hasOwnProperty.call(t,r))continue;const o=fx(n[r],t[r]);o!==null&&(a[r]=o)}return a}function $a(e){return e>0?e<=5?"1-5":e<=20?"6-20":e<=50?"21-50":e<=100?"51-100":"100+":"0"}function px(e){const t=Number.isFinite(e)?e:0;return t<2?"0-1":t<5?"2-4":t<15?"5-14":t<25?"15-24":t<50?"25-49":"50+"}function sa(e){const t=(e||"").toLowerCase().replace(/[\s_-]+/g,"");return t==="do"||t==="dofirst"||t==="urgentimportant"?"do":t==="schedule"||t==="important"?"schedule":t==="delegate"||t==="urgent"?"delegate":t==="backlog"||t==="eliminate"||t==="neither"?"backlog":"unsorted"}const gx={app_opened:{ms:30*6e4},matrix_viewed:{ms:30*6e4},connect_todoist_viewed:{ms:10*6e4},categorize_opened:{ms:3e4,by:["kind"]},stats_opened:{ms:6e4},settings_opened:{ms:3e4},plans_viewed:{ms:5*6e4},filters_used:{ms:6e4,by:["kind"]},daily_review_opened:{ms:6e4},license_dialog_opened:{ms:3e4},signed_in:{ms:6e4},checkout_result:{ms:6e4,by:["result"]},focus_started:{ms:1e4},tour_started:{ms:6e4,by:["kind"]},connect_todoist_clicked:{ms:5e3},starter_card:{ms:6e4,by:["action"]},view_changed:{ms:6e4,by:["kind"]},task_opened:{ms:3e4,by:["surface"]},error_shown:{ms:5*6e4,by:["kind"]}},xx=new Set(["task_categorized","task_completed","task_added"]),bx=1e4,yx=50,zc=200,Uc=(e,t)=>JSON.stringify(Object.keys(e).filter(n=>n!==t).sort().map(n=>[n,e[n]]));function wx(e={}){let t=e.transport??null;const n=e.now??(()=>Date.now()),a=e.flushMs??bx,r=e.setTimer??((x,y)=>setTimeout(x,y)),o=e.clearTimer??(x=>clearTimeout(x));let c,l=[],d=null,m=null;const u=new Map,f=()=>{d!=null||!l.length||typeof c!="string"||(d=r(()=>{d=null,g()},a))},p=()=>
2{if(d!=null){try{o(d)}catch{}d=null}};function h(x,y){try{if(c===null||c===""||!Gu(x))return!1;const w=hx(x,y);if(!w)return!1;const k=n(),N=gx[x];if(N){const C=x+"|"+(N.by?N.by.map(j=>String(w[j]??"")).join("|"):""),v=u.get(C);if(v!=null&&k-v<N.ms)return!1;u.set(C,k)}if(xx.has(x)){const C=typeof w.n=="number"?w.n:1,v=Uc(w,"n"),j=l.find(T=>T.name===x&&Uc(T.props,"n")===v);if(j){const T=typeof j.props.n=="number"?j.props.n:1;return j.props.n=Math.min(500,T+C),!0}w.n=Math.min(500,C)}return l.push({name:x,props:w,ts:k}),l.length>zc&&(l=l.slice(l.length-zc)),f(),!0}catch{return!1}}async function g(x={}){try{if(p(),!l.length||!t||typeof c!="string")return;m&&!x.keepalive&&await m.catch(()=>{});const y=[];for(;l.length;)y.push(l.splice(0,yx));const w=t,k=(async()=>{for(const N of y)try{await w.send(N,{keepalive:!!x.keepalive})}catch{}})();m=k,await k,m===k&&(m=null)}catch{}}function b(x){try{if(x===c)return;(!x||c&&x!==c)&&(l=[],p());const y=c===void 0;c=x||null,y||u.clear(),f()}catch{}}return{track:h,flush:g,identify:b,setTransport(x){t=x},get userId(){return c??null},pending(){return l.map(x=>({...x,props:{...x.props}}))}}}const tt=wx(),pe=(e,t)=>tt.track(e,t);function Hn(){try{return window.matchMedia("(max-width: 767px), (max-height: 500px) and (pointer: coarse)").matches?"phone":"desktop"}catch{return"desktop"}}function Qu(e,t){try{tt.track(e,t)&&tt.flush()}catch{}}async function vx(){try{if(!tt.track("logged_out"))return;await Promise.race([tt.flush({keepalive:!0}),new Promise(e=>setTimeout(e,1500))])}catch{}}const Kr=new Map,kx=300*1e3,jx=({onProfileUpdate:e,onApiKeyFound:t})=>{const[n,a]=i.useState(!0),[r,o]=i.useState(!1),{session:c}=we.useSessionContext(),{toast:l}=He(),d=i.useRef(!1),m=i.useRef(0),u=i.useCallback(async()=>{if(!c?.user){e(null),a(!1);return}if(d.current)return;const p=c.user.id,h=Date.now();if(h-m.current<1e3){const b=Kr.get(p);b&&(e(b.profile),b.token&&t(b.token),a(!1));return}const g=Kr.get(p);if(g&&h-g.timestamp<kx){e(g.profile),g.token&&t(g.token),a(!1);return}d.current=!0,m.current=h;try{let b=null;for(let x=0;;x++){const{data:y,error:w}=await B.from("profiles").select("*").eq("id",p).maybeSingle();if(!w){b=y;break}if(x>=1)throw w;await new Promise(k=>setTimeout(k,800*(x+1)))}if(b){const x=b.todoist_access_token;Kr.set(p,{profile:b,timestamp:h,token:typeof x=="string"&&x.length>0?x:void 0})}if(o(!1),e(b),b?.todoist_access_token){const x=b.todoist_access_token;typeof x=="string"&&x.length>0&&t(x)}}catch{o(!0),l({title:"Error",description:"Failed to fetch user profile",variant:"destructive"})}finally{d.current=!1,a(!1)}},[c,l,e,t]),f=i.useCallback(()=>{o(!1),a(!0),m.current=0,u()},[u]);return i.useEffect(()=>{c?.user?u():a(!1)},[c,u]),{isLoading:n,hasError:r,retry:f}},Nx=i.lazy(()=>Ne(()=>import("./FeatureTour-BvQZ-bXu.js"),__vite__mapDeps([0,1,2,3,4])).then(e=>({default:e.OnboardingTour}))),Sx=()=>{const[e,t]=i.useState(!1);return i.useEffect(()=>{const n=()=>t(!0);return window.addEventListener("tour:open",n),()=>window.removeEventListener("tour:open",n)},[]),e?s.jsx(i.Suspense,{fallback:null,children:s.jsx(Nx,{onClose:()=>t(!1)})}):null},Ju=!0,Yr={phase:null,queue:[],sorted:[],walkStepId:null,dismissCount:0,firstSeenAt:null,tipsShown:[],lastSurfaceDay:null},Xu=new Map,Zu=e=>`onb:v1:${e}`,Cx=e=>{try{const t=window.localStorage.getItem(e);if(t!==null)return t}catch{}return Xu.get(e)??null},Tx=(e,t)=>{Xu.set(e,t);try{window.localStorage.setItem(e,t)}catch{}},Rt=e=>{const t=Cx(Zu(e));if(!t)return{...Yr};try{return{...Yr,...JSON.parse(t)}}catch{return{...Yr}}},_n=(e,t)=>{const n={...Rt(e),...t};return Tx(Zu(e),JSON.stringify(n)),n},lT=e=>{if(!e)return!1;const{phase:t}=Rt(e);return t==="welcome"||t==="sorting"||t==="walk"},em=(e=new Date)=>Ee(e,"yyyy-MM-dd"),Bc=(e,t=new Date)=>{const n=em(t);return Rt(e).lastSurfaceDay===n?!1:(_n(e,{lastSurfaceDay:n}),!0)},_x=(e,t=new Date)=>Rt(e).lastSurfaceDay===em(t),Cr="onb:just-connected",Ex=()=>{try{return window.sessionStorage.getItem(Cr)==="1"}catch{return!1}},Hc=()=>{try{window.sessionStorage.removeItem(Cr)}catch{}},Dx=/^yigitsonbahar25\+[a-z0-9._-]+@outlook\.com$/i,Rx=e=>!!e&&Dx.test(e),Vc="reset-onboarding",Ix=async(e,t)=>{if(!Rx(t))return!1;const n=new URLSearchParams(window.location.search);if(!n.has(Vc))return!1;await B.from("profiles").update({has_completed_tour:!1,has_seen_category_tour:!1}).eq("id",e);try{[`onb:v1:${e}`,`onb:used-focus:${e}`,`matrix-view-tip-${e}`,`matrix-view-v2-${e}`,`daily-review-intro-seen:${e}`].forEach(o=>localStorage.removeItem(o)),["categorize-nudge-day","quick-category-info-dismissals","nps_submitted"].forEach(o=>localStorage.removeItem(o)),sessionStorage.removeItem("cm-intro-played"),sessionStorage.setItem("onb:just-connected","1")}catch{}n.delete(Vc);const a=n.toString();return window.history.replaceState(null,"",`${window.location.pathname}${a?`?${a}`:""}${window.location.hash}`),!0},tm={DO:"DO",SCHEDULE:"SCHEDULE",DELEGATE:"DELEGATE",BACKLOG:"BACKLOG"},Mx=(e,t={})=>{const{debounceTime:n=500,maxBatchSize:a=10}=t,r=i.useRef(null),o=i.useRef(new Set),c=i.useRef(!1),l=i.useRef(0),d=i.useCallback(()=>{r.current&&(clearTimeout(r.current),r.current=null)},[]),m=i.useCallback((f,p,h=!1)=>{o.current.add(f),d();const g=h||o.current.size>=a;if(c.current)return;const x=Date.now()-l.current,y=200;if(g&&x>y)u(p);else{const w=g?Math.max(0,y-x):n;r.current=setTimeout(()=>{u(p)},w)}}
2,[d,n,a]),u=i.useCallback(async f=>{if(!(o.current.size===0||c.current))try{c.current=!0,l.current=Date.now(),d(),await e(f,!0),o.current.clear()}catch{}finally{c.current=!1}},[d,e]);return i.useEffect(()=>()=>{d()},[d]),{queueTaskUpdate:m,clearProcessingTimeout:d,pendingUpdateCount:o.current.size}},Lx=/^([01]\d|2[0-3]):([0-5]\d)$/,na=e=>!!e&&Lx.test(e);function sm(e){if(!e)return e;const t=e.datetime||(e.date&&e.date.includes("T")?e.date:void 0);if(!t)return e;const n=Ms(t);return Oi(n)?{...e,date:Ee(n,"yyyy-MM-dd"),datetime:t}:e}function Ye(e){if(!e)return null;const t=e.datetime||e.date;if(!t)return null;const n=Ms(t);return Oi(n)?n:null}function gt(e){return!!(e?.datetime||e?.date?.includes("T"))}function nm(e){try{return new Intl.DateTimeFormat(e,{hour:"numeric"}).resolvedOptions().hour12===!0}catch{return!1}}function Tr(e,t){return nm(t)?new Intl.DateTimeFormat(t,{hour:"numeric",...e.getMinutes()?{minute:"2-digit"}:{},hour12:!0}).format(e):`${e.getHours()}:${String(e.getMinutes()).padStart(2,"0")}`}function qi(e,t){const[n,a]=e.split(":").map(Number);return Tr(new Date(2e3,0,1,n,a),t)}function am(e,t){if(!gt(e))return null;const n=Ye(e);return n?Tr(n,t):null}function _r(e){if(!gt(e))return;const t=Ye(e);return t?Ee(t,"HH:mm"):void 0}function Er(e,t=new Date){const n=Ye(e);return n?gt(e)?n.getTime()<=t.getTime():new Date(n.getFullYear(),n.getMonth(),n.getDate()+1).getTime()<=t.getTime():!1}function Ax(e,t){const[n,a]=t.split(":").map(Number);return new Date(e.getFullYear(),e.getMonth(),e.getDate(),n,a,0,0)}function Px(e,t){return Ax(e,t).toISOString().replace(/\.\d{3}Z$/,"Z")}function rm(e){const[t,n]=e.split(":").map(Number),a=t<12?"am":"pm",r=t%12||12;return n?`${r}:${String(n).padStart(2,"0")}${a}`:`${r}${a}`}const Ox=e=>/\bat\b|\d\s*(am|pm)\b|\d:\d\d/i.test(e);function om(e,t,n){const a=n?.trim(),r=na(t)?t:void 0;if(a){const o=r&&!Ox(a)?` at ${rm(r)}`:"";return{due_string:e?`${a}${o} starting ${Ee(e,"MMM d yyyy")}`:`${a}${o}`,due_lang:"en"}}return e?r?{due_datetime:Px(e,r)}:{due_date:Ee(e,"yyyy-MM-dd")}:{}}function $x(e,t,n,a=!1,r={}){return{taskId:e,date:t?Ee(t,"yyyy-MM-dd"):null,time:t&&na(n)?n:null,isRecurring:a,...r.via?{via:r.via}:{},...r.kind?{kind:r.kind}:{}}}function en(e,t,n,a=!1,r={}){window.dispatchEvent(new CustomEvent("task:set-due",{detail:$x(e,t,n,a,r)}))}function Fx(e){return e.date?e.kind==="time"?"time":"date":"cleared"}function qx(e){if(!e.date)return{due_string:"no date"};const t=Ms(e.date);return om(t,e.time??void 0)}function zi(e){if(!e?.date)return null;const t=Ms(e.date);return Oi(t)?t:null}class Vn extends Error{status;constructor(t,n){super(t),this.name="TodoistApiError",this.status=n}get isAuthError(){return this.status===401||this.status===403}}class zx{apiToken;constructor(t){this.apiToken=t}async request(t,n="GET",a,r){const{data:o,error:c}=await B.functions.invoke("todoist-proxy",{body:{path:t,method:n,apiToken:this.apiToken,requestBody:a,bodyFormat:r}});if(c){let l,d=c.message||"Todoist proxy request failed";const m=c.context;if(m){typeof m.status=="number"&&(l=m.status);try{const u=await m.json();u?.error&&(d=typeof u.error=="string"?u.error:u.error?.message||d),typeof u?.status=="number"&&(l=u.status)}catch{}}throw new Vn(d,l)}if(o?.error){const l=typeof o.error=="string"?o.error:o.error?.message||JSON.stringify(o.error);throw new Vn(l,typeof o.status=="number"?o.status:void 0)}return o}async requestList(t){const n=[];let a=null;for(;;){const r=t.includes("?")?"&":"?",o=a?`${t}${r}cursor=${encodeURIComponent(a)}`:t,c=await this.request(o);if(Array.isArray(c))return c;if(c?.results&&n.push(...c.results),c?.next_cursor)a=c.next_cursor;else break}return n}}const vn=e=>{if(!e?.due)return e;const t=sm(e.due);return{...e,due:t.isRecurring===void 0?{...t,isRecurring:!!t.is_recurring}:t}};class Ke{proxy;apiToken;constructor(t){this.apiToken=t,this.proxy=new zx(t)}setUseDirectApiFirst(t){}async getTasks(){return(await this.proxy.requestList("/api/v1/tasks?limit=200")).map(vn)}async getTasksByIds(t){if(!t.length)return[];const n=t.map(encodeURIComponent).join(",");return(await this.proxy.requestList(`/api/v1/tasks?ids=${n}&limit=200`)).map(vn)}async getTask(t){return vn(await this.proxy.request(`/api/v1/tasks/${t}`))}async createTask(t){return vn(await this.proxy.request("/api/v1/tasks","POST",t))}async updateTaskLabels(t,n){return await this.proxy.request(`/api/v1/tasks/${t}`,"POST",{labels:n}),!0}async closeTask(t){return await this.proxy.request(`/api/v1/tasks/${t}/close`,"POST"),!0}async reopenTask(t){return await this.proxy.request(`/api/v1/tasks/${t}/reopen`,"POST"),!0}async deleteTask(t){return await this.proxy.request(`/api/v1/tasks/${encodeURIComponent(t)}`,"DELETE"),!0}async getProjects(){return this.proxy.requestList("/api/v1/projects")}async getLabels(){return this.proxy.requestList("/api/v1/labels")}async getFilters(){const t={sync_token:"*",resource_types:["filters"]},n=`sync_token=*&resource_types=${encodeURIComponent('["filters"]')}`,a=[()=>this.proxy.request("/api/v1/sync","POST",t,"form"),()=>this.proxy.request(`/api/v1/sync?${n}`,"POST",void 0),()=>this.proxy.request("/sync/v9/sync","POST",t,"form"),()=>this.proxy.request(`/sync/v9/sync?${n}`,"POST",void 0)];let r;for(const o of a)try{const c=await o();if(c&&Array.isArray(c.filters))return c.filters.filter(l=>!l?.is_deleted)}catch(c){r=c}throw r??new Error("Todoist sync response did not include filters")}async getTasksByFilter(t){return(await this.proxy.requestList(`/api/v1/tasks/filter?query=${encodeURIComponent(t)}&limit=200`)).map(vn)}async addLabel(t){return this.proxy.request("/api/v1/labels","POST",t)}async updateTask(t,n){return this.proxy.request(`/api/v1/tasks/${t}`,"POST",n)}async addTask(t){return this.createTask(t)}async getComments(t){return this.proxy.requestList(`/api/v1/comments?task_id=${t.taskId}`)}async addComment(t){return this.proxy.request("/api/v1/comments","POST",{task_id:t.taskId,content:t.content})}async updateComment(t){return this.proxy.request(`/api/v1/comments/${t.commentId}`,"POST",{content:t.content})}async deleteComment(t){return await this.proxy.request(`/api/v1/comments/${t.commentId}`,"DELETE"),!0}getApi(){return this}}const Dr=e=>Ee(e,"yyyy-MM-dd"),Ui=()=>Dr(new Date),Ux=()=>new Date().toISOString().slice(0,10),Lt={},Bx=(e,t)=>{const n=Ui();(!Lt[e]||Lt[e].date!==n)&&(Lt[e]={date:n,tasks:new Set}),Lt[e].tasks.add(t)},Hx=(e,t)=>{Lt[e]?.tasks.delete(t)},Vx=(e,t)=>{const n=Ui();return Lt[e]&&Lt[e].date===n&&Lt[e].tasks.has(t)},Kx=()=>
2{if(!(typeof window>"u"))try{const e=Object.entries(Lt).reduce((t,[n,a])=>(t[n]={date:a.date,tasks:Array.from(a.tasks),local:!0},t),{});localStorage.setItem("completed-tasks-cache",JSON.stringify(e))}catch{}},Yx=()=>{if(!(typeof window>"u"))try{const e=localStorage.getItem("completed-tasks-cache");if(e){const t=JSON.parse(e);Object.entries(t).forEach(([n,a])=>{const r=!a.local&&a.date===Ux()?Ui():a.date;Lt[n]={date:r,tasks:new Set(a.tasks)}})}}catch{}};typeof window<"u"&&(Yx(),window.addEventListener("beforeunload",Kx));const Wx=e=>({id:String(e.id),title:e.content,content:e.content,description:e.description||"",labels:(e.labels||[]).filter(t=>typeof t=="string"),due:sm(e.due),deadline:e.deadline,priority:e.priority,project_id:String(e.project_id??e.projectId??""),...(e.section_id??e.sectionId)!=null?{section_id:String(e.section_id??e.sectionId)}:{},parent_id:e.parent_id!=null?String(e.parent_id):e.parentId!=null?String(e.parentId):void 0}),im=6e3,Wr="eis:pending-deletes",Gx=10080*60*1e3,Qx=e=>{const t=e?.status;return t===404||t===410},Jx=()=>{try{return typeof window<"u"&&window.localStorage?window.localStorage:null}catch{return null}},Xx=e=>{const t=e;return!!t&&typeof t.id=="string"&&!!t.id&&typeof t.userId=="string"&&typeof t.at=="number"&&Array.isArray(t.ids)&&t.ids.every(n=>typeof n=="string")};function Zx(e={}){const t={send:e.send,onChange:e.onChange,onSending:e.onSending,onDone:e.onDone,onFailed:e.onFailed},n=e.delayMs??im,a=e.now??(()=>Date.now()),r=e.setTimer??((j,T)=>setTimeout(j,T)),o=e.clearTimer??(j=>clearTimeout(j)),c=e.storage===void 0?Jx():e.storage;let l=[];const d=new Map;let m=null;const u=()=>{if(!c)return[];try{const j=JSON.parse(c.getItem(Wr)||"[]");return Array.isArray(j)?j.filter(Xx):[]}catch{return[]}},f=j=>{if(c)try{j.length?c.setItem(Wr,JSON.stringify(j)):c.removeItem(Wr)}catch{}},p=j=>f([...u().filter(T=>T.id!==j.id),j]),h=j=>{const T=new Set(j),_=u(),I=_.filter(R=>!T.has(R.id));I.length!==_.length&&f(I)};let g=u();const b=()=>{if(m!=null){try{o(m)}catch{}m=null}},x=()=>t.onChange?.(l.slice());async function y(j,T){const _=t.send;if(!j.length)return;if(!_){g=[...g.filter(M=>!j.some(P=>P.id===M.id)),...j];return}j.forEach(M=>d.set(M.id,M));const I=[];let R=null;await Promise.all(j.map(async M=>{try{await _(M,{keepalive:T})}catch(P){Qx(P)||(I.push(M),R=P)}})),j.forEach(M=>d.delete(M.id)),h(j.map(M=>M.id));for(const M of j)I.includes(M)||t.onDone?.(M);I.length&&t.onFailed?.(I,R)}async function w(j={}){if(b(),!l.length)return;const T=l;l=[];const _=!!j.keepalive;t.onSending?.(T.slice(),{keepalive:_}),x(),await y(T,_)}function k(j){const T={...j,ids:j.ids.length?j.ids:[j.id],at:j.at??a()};return l=[...l.filter(_=>_.id!==T.id),T],p(T),b(),m=r(()=>{m=null,w()},n),x(),T}function N(){b();const j=l;return l=[],h(j.map(T=>T.id)),j.length&&x(),j}async function C(j){const T=a()-Gx,_=g.filter(R=>R.at<T);_.length&&h(_.map(R=>R.id));const I=g.filter(R=>R.userId===j&&R.at>=T);return g=g.filter(R=>R.userId!==j&&R.at>=T),await y(I,!1),I}function v(j){const T=_=>_.id===j||_.ids.includes(j);if(l.some(T)||g.some(T))return!0;for(const _ of d.values())if(T(_))return!0;return!1}return{add:k,undo:N,flush:w,resume:C,isPending:v,pending:()=>l.slice(),inflight:()=>[...d.values()],leftovers:()=>g.slice(),configure(j){Object.assign(t,j)}}}const Dt=Zx(),eb=e=>Dt.isPending(e),tb=300*1e3,sb=3,nb=3e3,ab=()=>{const[e,t]=i.useState(!1),[n,a]=i.useState(null),{toast:r}=He(),{session:o}=we.useSessionContext(),c=at(),l=i.useRef(0),d=i.useRef([]),m=i.useRef(0),u=i.useRef(null),f=i.useCallback(()=>{u.current&&(u.current.abort(),u.current=null)},[]),p=i.useCallback(async(h,g=!1,b,x={})=>{const y=!!x.quiet,w=Date.now(),k=!!b;if(!g&&!k&&w-l.current<tb&&d.current.length>0)return d.current;f(),u.current=new AbortController,y||t(!0);try{if(!h){const{data:{user:I}}=await B.auth.getUser();if(I){const{data:R}=await B.from("profiles").select("todoist_access_token, todoist_api_key").eq("id",I.id).single();h=R?.todoist_access_token||R?.todoist_api_key}}if(!h)return y?null:[];const N=new Ke(h),C=k?await N.getTasksByFilter(b):await N.getTasks(),j=(Array.isArray(C)?C:C?.results??[]).map(Wx),T=o?.user?.id,_=j.filter(I=>!eb(I.id)&&(!T||I.due?.isRecurring||!Vx(T,I.id)));return l.current=w,k||(d.current=_),m.current=0,a(null),c.setQueryData(["tasks"],_),_}catch(N){if(y)return null;if(m.current<sb&&!u.current?.signal.aborted)return m.current++,await new Promise(j=>setTimeout(j,nb)),p(h,!0,b);const C=N instanceof Vn&&N.isAuthError,v=d.current.length>0;return a({message:C?"Your Todoist connection expired. Reconnect to load your tasks.":"Couldn't reach Todoist. Check your connection and retry.",isAuthError:C,showingCachedTasks:v}),nt()||r({title:C?"Todoist connection expired":"Couldn't load tasks",description:C?"Reconnect Todoist from the header to keep working.":"Failed to fetch tasks. Please check your connection and retry.",variant:"destructive"}),v?d.current:[]}finally{u.current?.signal.aborted||t(!1)}},[f,c,r,o?.user?.id]);return{isLoading:e,fetchError:n,fetchTasks:p,cleanup:f}},rb=new Set(["do","schedule","delegate","backlog"]),Kn=e=>{for(const t of e.labels||[]){const n=t.toLowerCase();if(rb.has(n))return n}return null},cm={byId:new Map,nestedSubtasksByParent:new Map,nestedChildIds:new Set,displayRootIdById:new Map,nestedDescendantCountByRoot:new Map,parentTitleById:new Map},ob=e=>{if(!e?.length)return cm;const t=new Map;for(const u of e)t.set(u.id,u);const n=new Map,a=new Set,r=u=>{const f=n.get(u.id);if(f)return f;if(a.has(u.id)){const g={rootId:u.id,nested:!1};return n.set(u.id,g),g}a.add(u.id);let p;const h=u.parent_id?t.get(u.parent_id):void 0;if(!h)p={rootId:u.id,nested:!1};else{const g=t.get(r(h).rootId),b=Kn(g),x=Kn(u);p=g.id!==u.id&&b!==null&&(x===null||x===b)?{rootId:g.id,nested:!0}:{rootId:u.id,nested:!1}}return a.delete(u.id),n.set(u.id,p),p},o=new Map,c=new Set,l=new Map,d=new Map,m=new Map;for(const u of e){const f=u.parent_id?t.get(u.parent_id):void 0;if(!f)continue;const p=r(u);if(p.nested){const h=o.get(f.id);h?h.push(u):o.set(f.id,[u]),c.add(u.id),l.set(u.id,p.rootId),d.set(p.rootId,(d.get(p.rootId)??0)+1)}else m.set(u.id,f.title)}return{byId:t,nestedSubtasksByParent:o,nestedChildIds:c,displayRootIdById:l,nestedDescendantCountByRoot:d,parentTitleById:m}},lm=(e,t)=>
2{const n=new Map;for(const c of e){if(!c.parent_id)continue;const l=n.get(c.parent_id);l?l.push(c):n.set(c.parent_id,[c])}const a=[],r=new Set([t]),o=[t];for(;o.length;){const c=o.shift();for(const l of n.get(c)||[])r.has(l.id)||(r.add(l.id),a.push(l.id),o.push(l.id))}return a},ib=()=>{const[e,t]=i.useState([]),[n,a]=i.useState(void 0),[r,o]=i.useState([]),[c,l]=i.useState(!1),{session:d}=we.useSessionContext(),{isLoading:m,fetchError:u,fetchTasks:f,cleanup:p}=ab(),{queueTaskUpdate:h,clearProcessingTimeout:g}=Mx(f),b=i.useMemo(()=>new Map,[]),x=i.useMemo(()=>Object.values(tm).map(C=>C.toLowerCase()),[]),y=i.useCallback((C,v)=>{if(v==="all")return C;const j=`project-${v}`;if(b.has(j))return b.get(j);const T=C.filter(_=>_.project_id===v);return b.set(j,T),T},[b]),w=i.useCallback(async(C,v=!1,j,T={})=>{try{const _=await f(C,v,j,T);if(!_)return[];t(_),a(j||void 0),b.clear();const I=new Set(x),R=_.filter(M=>M.labels?.length?!M.labels.some(P=>I.has(P.toLowerCase())):!0);return o(R),R}catch{return[]}finally{l(!0)}},[f,x,b]),k=i.useCallback(C=>{const v={removed:!1,removedIds:[],rollback:()=>{}},j=e.find(D=>D.id===C),T=r.find(D=>D.id===C),_=j||T;if(!_||_.due?.isRecurring)return v;const I=new Set([C]);for(const D of lm(e,C)){const L=e.find(A=>A.id===D);L&&!L.due?.isRecurring&&I.add(D)}const R=e.filter(D=>I.has(D.id)),M=r.filter(D=>I.has(D.id)),P=setTimeout(()=>{t(D=>D.filter(L=>!I.has(L.id))),o(D=>D.filter(L=>!I.has(L.id))),b.clear()},280),E=()=>{clearTimeout(P);const D=L=>A=>{const H=new Set(A.map(X=>X.id)),K=L.filter(X=>!H.has(X.id));return K.length?[...A,...K]:A};R.length&&t(D(R)),M.length&&o(D(M)),b.clear()};return{removed:!0,removedIds:[...I],rollback:E}},[e,r,b]),N=i.useCallback((C,v=0)=>{const j=new Set(C),T=D=>D.map((L,A)=>({t:L,i:A})).filter(({t:L})=>j.has(L.id)),_=T(e),I=T(r),R=()=>{t(D=>D.some(L=>j.has(L.id))?D.filter(L=>!j.has(L.id)):D),o(D=>D.some(L=>j.has(L.id))?D.filter(L=>!j.has(L.id)):D),b.clear()};let M=null;v>0?M=setTimeout(R,v):R();const P=D=>L=>{const A=new Set(L.map(X=>X.id)),H=D.filter(({t:X})=>!A.has(X.id));if(!H.length)return L;const K=L.slice();for(const{t:X,i:ce}of H)K.splice(Math.min(ce,K.length),0,X);return K};return{restore:()=>{M&&clearTimeout(M),_.length&&t(P(_)),I.length&&o(P(I)),b.clear()}}},[e,r,b]);return i.useEffect(()=>()=>{p(),g(),b.clear()},[p,g,b]),{tasks:e,tasksFilterQuery:n,unlabeledTasks:r,isLoading:m,tasksReady:c,fetchError:u,fetchTasks:i.useCallback((C,v,j)=>w(C,!0,v,j),[w]),queueTaskUpdate:h,filterTasksByProject:y,completeTaskOptimistic:k,removeTasksOptimistic:N}},Ro=new Map,cb=60*1e3;let Kc=Date.now();const Yc=new WeakMap,lb=e=>{if(!e.due?.date&&!e.due?.datetime)return null;const t=Yc.get(e);if(t!==void 0)return t;const n=Ye(e.due);return Yc.set(e,n),n},dm=()=>{const e=Date.now();e-Kc>cb&&(Ro.clear(),Kc=e)},db=e=>{dm();const t=`${e}-${new Date().toDateString()}`;let n=Ro.get(t);if(!n){const a=new Date,r=_s(),o=st(r,1);n=(()=>{switch(e){case"today":return{type:"interval",start:_s(),end:Oc()};case"tomorrow":return{type:"interval",start:o,end:st(o,1)};case"overdue":return{type:"before",date:r};case"today,overdue":return{type:"beforeEnd",end:Oc()};case"this-week":return{type:"interval",start:Eo(a,{weekStartsOn:1}),end:Pc(a,{weekStartsOn:1})};case"next-week":{const c=Bu(a,1);return{type:"interval",start:Eo(c,{weekStartsOn:1}),end:Pc(c,{weekStartsOn:1})}}case"next-month":{const c=Uu(a,1);return{type:"interval",start:Kg(c),end:Vg(c)}}default:return{type:"interval",start:a,end:a}}})(),Ro.set(t,n)}return n},Bi=({tasks:e,dateFilter:t,selectedLabel:n,projectId:a})=>{if(!e?.length||t==="all")return e;dm();const r=db(t);return e.filter(c=>{if(a&&a!=="all"&&c.project_id!==a)return!1;const l=lb(c);if(!l)return!1;switch(r.type){case"before":return Er(c.due);case"beforeEnd":return Hg(l,r.end);case"interval":return Bg(l,{start:r.start,end:r.end});default:return!1}})},ub=["do","schedule","delegate","backlog"],mb=new Set(ub),fb=/̇/g,Qt=e=>String(e??"").normalize("NFC").toLowerCase().replace(fb,""),dT=(e,t)=>Qt(e)===Qt(t),Rr=e=>{const t=Qt(e).trim();return mb.has(t)?t:null},hb=e=>Rr(e)!==null,um=e=>{for(const t of e??[]){const n=Rr(t);if(n)return n}return null},mm=e=>(e??[]).filter(t=>typeof t=="string"&&t!==""&&!hb(t)),Io=(e,t)=>{const n=Array.from(new Set(mm(e)));if(t==null||t==="")return n;const a=Rr(t)??t;return n.includes(a)?n:[...n,a]},Jt=e=>e.startsWith("@")?e:`@${e}`,Ir=e=>mm(e).map(Jt),Wc=new WeakMap,Hs=new Map,pb=50,gb=new Set(["do","schedule","delegate","backlog"]),xb=e=>{let t=Wc.get(e);return t||(t=new Set(e.labels?.map(Qt)||[]),Wc.set(e,t)),t},fm=(e,t)=>
2{if(!e?.length)return[];const n=Array.isArray(t)?t:t==="all"||t.trim()===""?[]:[t];if(n.length===0)return e.filter(m=>!m.completed);const a=[...n].map(Qt).sort().join("&"),r=`label-${a}-${e.length}`,o=Hs.get(r);if(o)return o.tasks;const c=new Set(n.map(Qt)),l=new Map,d=e.filter(m=>{if(m.completed)return!1;const u=`${m.id}-${a}`;if(l.has(u))return l.get(u);const f=xb(m),p=[...c].every(b=>f.has(b)),h=[...f].some(b=>gb.has(b)),g=p&&h;return l.set(u,g),g});if(Hs.size>=pb){let m=null,u=1/0;for(const[f,p]of Hs.entries())p.timestamp<u&&(u=p.timestamp,m=f);m&&Hs.delete(m)}return Hs.set(r,{tasks:d,timestamp:Date.now()}),d},Gr=()=>{Hs.clear()};function ct(e,t){const n=l=>{try{const d=window.localStorage.getItem(l);return d?JSON.parse(d):t}catch{return t}},[a,r]=i.useState(()=>n(e)),o=i.useRef(e);o.current!==e&&(o.current=e,r(n(e)));const c=i.useRef(!1);return i.useEffect(()=>{if(!c.current){c.current=!0;return}try{window.localStorage.setItem(e,JSON.stringify(a))}catch{}},[e,a]),[a,r]}function bb(e,t){let n=null;return function(...a){const r=()=>{n=null,e.apply(this,a)};n!==null&&clearTimeout(n),n=setTimeout(r,t)}}const ps=e=>e(),yb=(e,t)=>bb(e,t),wb=e=>{const[t,n]=i.useState(!1),[a,r]=i.useState([]),[o,c]=i.useState(!1),[l,d]=i.useState(!0),[m,u]=i.useState({checked:!1,eligible:!1,firstName:null}),[f,p]=i.useState(!1),[h,g]=i.useState(null),[b,x]=i.useState("all"),[y,w]=i.useState([]),[k,N]=i.useState([]),[C,v]=i.useState(null),[j,T]=ct("hide-subtasks",!1),_=i.useRef(!1),I=i.useRef(null),R=i.useRef(null),{toast:M}=He(),{tasks:P,tasksFilterQuery:E,isLoading:D,tasksReady:L,fetchError:A,unlabeledTasks:H,fetchTasks:K,completeTaskOptimistic:X,removeTasksOptimistic:ce}=ib(),oe=i.useMemo(()=>yb(async()=>{try{_.current=!0,await K(e||void 0,I.current?.query),Gr()}catch{M({title:"Error",description:"Failed to fetch tasks. Please check your API key.",variant:"destructive"})}},50),[K,M,e]),ve=i.useRef(oe);ve.current=oe;const Ce=i.useCallback(async()=>{ve.current()},[]),ee=i.useCallback(async()=>{e&&(await K(e,I.current?.query,{quiet:!0}),Gr())},[e,K]);i.useEffect(()=>(e&&Ce(),()=>{R.current&&clearTimeout(R.current),Gr()}),[e]),i.useEffect(()=>{if(!e)return;let U=!1;return(async()=>{try{const{data:{user:me}}=await B.auth.getUser();if(U)return;if(!me){d(!1),u({checked:!0,eligible:!1,firstName:null});return}if(await Ix(me.id,me.email),U)return;const{data:q,error:xe}=await B.from("profiles").select("has_completed_tour, todoist_user_name").eq("id",me.id).single();if(U)return;if(xe||q?.has_completed_tour===!0){d(!1),u({checked:!0,eligible:!1,firstName:null});return}if(Ju){d(!1);const ke=(q?.todoist_user_name||"").trim().split(/\s+/)[0]||null;u({checked:!0,eligible:!0,firstName:ke});return}u({checked:!0,eligible:!1,firstName:null}),window.setTimeout(()=>{U||c(!0)},1200)}catch{U||(d(!1),u({checked:!0,eligible:!1,firstName:null}))}})(),()=>{U=!0}},[e]);const Le=i.useCallback(async()=>{try{const{data:{user:U}}=await B.auth.getUser();U&&await B.from("profiles").update({has_completed_tour:!0}).eq("id",U.id)}catch{}finally{c(!1),d(!1)}},[]),he=i.useCallback(async U=>{try{const{data:{user:ne}}=await B.auth.getUser();if(!ne)return;await B.from("profiles").update({has_completed_tour:!0,...U}).eq("id",ne.id)}catch{}},[]),ge=i.useCallback(()=>{p(!f),M({title:f?"Focus Mode Disabled":"Focus Mode Enabled",description:f?"Returning to normal view":"Focusing on urgent tasks"})},[f,M]),Te=i.useCallback(U=>{ps(()=>{r(U),_.current=!0})},[]),De=i.useCallback(U=>{ps(()=>{r(ne=>ne.filter(me=>me!==U)),_.current=!0})},[]),re=i.useCallback(U=>{U!==b&&ps(()=>{x(U),_.current=!0})},[b]),se=i.useCallback(U=>{ps(()=>{w(U),_.current=!0})},[]),ue=i.useCallback(U=>{ps(()=>{w(ne=>ne.filter(me=>me!==U)),_.current=!0})},[]),Qe=i.useCallback(U=>{ps(()=>{N(U),_.current=!0})},[]),$=i.useCallback(()=>N([]),[]),O=i.useCallback(U=>{I.current=U,ps(()=>{v(U),U&&(r([]),w([]),N([]),x("all")),_.current=!0}),oe()},[oe]),F=i.useDeferredValue(y),Q=i.useDeferredValue(a),V=i.useDeferredValue(k),G=i.useDeferredValue(b),Y=i.useDeferredValue(j),J=F!==y||Q!==a||V!==k||G!==b||Y!==j,le=i.useCallback(()=>{const U=F,ne=Q,me=V,q=G,xe=Y;`${U.join(",")}${q}${ne.join(",")}${me.join(",")}`;let ke=P;return U.length>0&&(ke=ke.filter(We=>U.includes(We.project_id))),ke=Bi({tasks:ke,dateFilter:q,selectedLabel:ne.length>0?ne.join(","):"all",projectId:U.length>0?U[0]:"all"}),ne.length>0&&(ke=fm(ke,ne)),me.length>0&&(ke=ke.filter(We=>me.includes(We.priority??4))),xe&&(ke=ke.filter(We=>!We.parent_id)),ke},[P,G,Q,F,V,Y]);return{showLabelingSheet:t,setShowLabelingSheet:n,selectedLabels:a,setSelectedLabels:Te,removeLabel:De,showTour:o,tourPending:l,firstRun:m,markOnboardingComplete:he,isFocusMode:f,tasks:P,tasksAreFiltered:!!E,tasksReady:L,isLoading:D,fetchError:A,unlabeledTasks:H,fetchTasks:Ce,quietRefreshTasks:ee,completeTaskOptimistic:X,removeTasksOptimistic:ce,handleTourClose:Le,toggleFocusMode:ge,profile:h,setProfile:g,dateFilter:b,setDateFilter:re,filteredTasks:le,isPending:J,selectedProjects:y,setSelectedProjects:se,removeProject:ue,selectedPriorities:k,setSelectedPriorities:Qe,clearPriorities:$,selectedTodoistFilter:C,setSelectedTodoistFilter:O,hideSubtasks:j,setHideSubtasks:T,selectedLabel:a.length>0?a[0]:"all",setSelectedLabel:U=>Te(U==="all"?[]:[U]),selectedProject:y.length>0?y[0]:"all",setSelectedProject:U=>se(U==="all"?[]:[U])}},vb=864e5,hm=e=>{if(!e)return null;const t=new Date(e).getTime();return Number.isNaN(t)?null:t},kb=(e,t)=>
2e.getFullYear()===t.getFullYear()&&e.getMonth()===t.getMonth()&&e.getDate()===t.getDate(),pm=(e,t=new Date)=>{const n=hm(e);return n!==null&&n>t.getTime()},jb=(e,t=new Date)=>{const n=hm(e);if(n===null)return;const a=n-t.getTime();return a<=0||kb(new Date(n),t)?0:Math.ceil(a/vb)},uT=e=>e<=0?"Ends today":`${e} ${e===1?"day":"days"} left`,Nb=["cancelled","failed","expired","invalid","ended"],Mr=(e,t=new Date)=>{if(!e||e.is_lifetime_purchase===!0||e.subscription_type!=="monthly"||!e.subscription_expiry_date)return!1;const n=new Date(e.subscription_expiry_date).getTime();if(Number.isNaN(n)||n>=t.getTime())return!1;const a=(e.gumroad_subscription_status??"").toLowerCase();return Nb.includes(a)},Sb=(e,t=new Date)=>e?e.is_lifetime_purchase===!0?!0:e.payment_status==="paid"?!Mr(e,t):e.payment_status==="trial"?pm(e.trial_end_date,t):!1:!1,gm=e=>e?.subscription_type==="monthly"||e?.subscription_type==="yearly"?"plan":"trial",Cb=({onProfileUpdate:e})=>{const{toast:t}=He(),n=Xt(),[a,r]=ct("simulate-expired",!1),o=i.useCallback(()=>{const l=!a;r(l),t({title:l?"Simulation Enabled":"Simulation Disabled",description:l?"Now simulating an expired subscription. The app will behave as if your trial has expired.":"Subscription simulation disabled. The app will use your actual subscription status.",variant:l?"destructive":"default"}),setTimeout(()=>window.location.reload(),1500)},[a,r,t]);i.useEffect(()=>{if(typeof window<"u")return window.__toggleExpiredSimulation=o,window.__simulationStatus=a,()=>{delete window.__toggleExpiredSimulation,delete window.__simulationStatus}},[o,a]);const c=i.useCallback(async()=>{try{const{data:{user:l}}=await B.auth.getUser();if(!l){n("/");return}const{data:d,error:m}=await B.from("profiles").select("id, payment_status, trial_end_date, is_lifetime_purchase, subscription_type, subscription_expiry_date, gumroad_subscription_status, email").eq("id",l.id).maybeSingle();if(m)throw m;if(!d)return;if(a){const u={...d,payment_status:"expired",is_lifetime_purchase:!1,subscription_type:null,subscription_expiry_date:null,trial_end_date:new Date(Date.now()-864e5).toISOString()};e(u),t({title:"Expired User Simulation",description:"You are currently simulating an expired subscription. Use the console and type __toggleExpiredSimulation() to disable.",variant:"destructive"});return}if(d.payment_status==="paid"&&(d.is_lifetime_purchase||d.subscription_type==="lifetime")){e(d);return}if(Mr(d)){e({...d,payment_status:"expired"}),t({title:"Subscription ended",description:"Your monthly subscription has ended. Renew to keep using all features.",variant:"destructive"});return}if(d.subscription_type==="monthly"&&d.subscription_expiry_date){e(d);return}d.payment_status==="trial"&&d.trial_end_date&&!pm(d.trial_end_date)?e({...d,payment_status:"expired"}):e(d)}catch{t({title:"Couldn't check your plan",description:"Please reload the page to try again.",variant:"destructive"})}},[n,e,t,a]);return i.useEffect(()=>{const l=setTimeout(()=>{c()},100);return()=>clearTimeout(l)},[c]),null},xm=[3,7,14,30,50,100,200,365],Gc=e=>xm.includes(e),Tb=e=>xm.find(t=>t>e)??null,Qa=e=>`${e.getFullYear()}-${e.getMonth()}-${e.getDate()}`,xa=e=>`${e.getFullYear()}-${e.getMonth()}-${e.getDate()}`,Qc=(e,t)=>{const n=new Date(e);return n.setDate(n.getDate()+t),n};function _b(e,t=new Date){const n=new Set,a=xa(t);let r=0;for(const h of e){const g=new Date(h);if(Number.isNaN(g.getTime()))continue;const b=xa(g);n.add(b),b===a&&(r+=1)}const o=h=>n.has(xa(Qc(t,-h)));let c=0;const l=o(0)?0:o(1)?1:-1;if(l>=0){let h=l;for(;o(h);)c+=1,h+=1}const d=Array.from(n).map(h=>{const[g,b,x]=h.split("-").map(Number);return new Date(g,b,x).getTime()}).sort((h,g)=>h-g),m=864e5;let u=d.length?1:0,f=u;for(let h=1;h<d.length;h+=1)f=Math.round((d[h]-d[h-1])/m)===1?f+1:1,f>u&&(u=f);const p=Array.from({length:7},(h,g)=>{const b=6-g,x=Qc(t,-b);return{label:x.toLocaleDateString(void 0,{weekday:"narrow"}),active:n.has(xa(x)),isToday:b===0}});return{current:c,longest:u,completedToday:r,activeToday:n.has(a),last7:p}}const Eb=150,Hi=()=>{const{session:e}=we.useSessionContext(),t=e?.user?.id,n=at(),a=it({queryKey:["streak",t],enabled:!!t,staleTime:6e4,queryFn:async()=>{const r=new Date;r.setDate(r.getDate()-Eb);const{data:o,error:c}=await B.from("user_activities").select("created_at").eq("user_id",t).gte("created_at",r.toISOString());if(c)throw c;
2return _b((o??[]).map(l=>l.created_at))}});return i.useEffect(()=>{if(!t)return;const r=()=>n.invalidateQueries({queryKey:["streak",t]});return window.addEventListener("task-completion-finished",r),window.addEventListener("focus-task-completed",r),window.addEventListener("streak-refresh",r),()=>{window.removeEventListener("task-completion-finished",r),window.removeEventListener("focus-task-completed",r),window.removeEventListener("streak-refresh",r)}},[n,t]),a},Db={"first steps":10,"priority pioneer":10,"weekend warrior":15,"focus master":20,"speed demon":20,"matrix minded":25,"marathon runner":30},Rb=10,Ib=e=>(e??"").trim().toLowerCase(),Mb=e=>{const t=Db[Ib(e.achievement_name)];return typeof t=="number"?t:e.points&&e.points>0?e.points:Rb},Es=e=>!!e.earned_at||e.target>0&&(e.progress??0)>=e.target,mT=e=>e.target>0?Math.min(e.progress??0,e.target):Es(e)?1:0,Lb=e=>Es(e)?1:e.target<=0?0:Math.min(1,(e.progress??0)/e.target),Vi=()=>{const{session:e}=we.useSessionContext(),t=e?.user?.id;return it({queryKey:["achievements",t],queryFn:async()=>{if(!t)return{achievements:[],categories:[],totalPoints:0};try{await B.rpc("initialize_user_achievements",{user_id:t});const{data:n,error:a}=await B.from("achievement_categories").select("*").order("display_order");if(a)throw a;const{data:r,error:o}=await B.from("achievement_progress_cache").select("*").eq("user_id",t);if(o)throw o;const{data:c,error:l}=await B.from("user_achievements").select(`
3            *,
4            achievement_categories (
5              name,
6              description,
7              icon_name
8            )
9          `).eq("user_id",t).order("display_order");if(l)throw l;if(!c)return{achievements:[],categories:n||[],totalPoints:0};const d=new Map(r?.map(f=>[f.achievement_type,{progress:f.progress,data:f.data}])||[]),m=c.map(f=>{const p=d.get(f.achievement_type),h=f.achievement_categories?.name,g={...f,category_name:h,progress:p?.progress||f.progress,earned_at:p?.progress>=f.target?f.earned_at||new Date().toISOString():null,prerequisites:f.prerequisites||[]};return{...g,points:Mb(g)}}),u=m.filter(Es).reduce((f,p)=>f+(p.points??0),0);return{achievements:m,categories:n||[],totalPoints:u}}catch{return Z.error("Failed to load achievements"),{achievements:[],categories:[],totalPoints:0}}},enabled:!!t,staleTime:300*1e3,refetchOnMount:!0,refetchOnWindowFocus:!0})},Ki=({value:e})=>{const[t,n]=i.useState(null),a=i.useRef(e),r=i.useRef(0);if(i.useLayoutEffect(()=>{if(e===a.current)return;const m=a.current;a.current=e,r.current+=1,n({prev:m,tick:r.current});const u=Math.max(String(m).length,String(e).length),f=window.setTimeout(()=>n(null),280+40*(u-1)+40);return()=>window.clearTimeout(f)},[e]),!t)return s.jsx("span",{className:"cm-roll",children:e});const o=String(e),c=String(t.prev),l=Math.max(o.length,c.length),d=[];for(let m=0;m<l;m++){const u=o[o.length-l+m],f=c[c.length-l+m],p=l-1-m;if(u===f){d.push(s.jsx("span",{className:"cm-roll-slot",children:s.jsx("span",{children:u})},`s${p}`));continue}d.push(s.jsxs("span",{className:f===void 0?"cm-roll-slot is-grow":u===void 0?"cm-roll-slot is-shrink":"cm-roll-slot",style:{"--d":`${p*40}ms`},children:[f!==void 0&&s.jsx("span",{className:"cm-roll-out","aria-hidden":!0,children:f}),u!==void 0&&s.jsx("span",{className:"cm-roll-in",children:u})]},`s${p}-${t.tick}`))}return s.jsx("span",{className:e<t.prev?"cm-roll is-rolling is-down":"cm-roll is-rolling",children:d})},Jc=5e3,xt=e=>{if(nt())for(const t of Z.getHistory())t.id!==e&&Z.dismiss(t.id)};let Ab=0;const ba=(e,t)=>{if(nt()){const n=t??`quiet-${++Ab}`;return xt(n),n}return Z.loading(e,t!==void 0?{id:t}:void 0)},Xc=()=>!!document.querySelector("[data-sonner-toast]"),Zc=(e,t=12e3)=>{if(!nt()||!Xc()){e();return}const n=Date.now(),a=window.setInterval(()=>{Xc()?Date.now()-n>t&&window.clearInterval(a):(window.clearInterval(a),window.setTimeout(e,250))},400)},Pb=1500,el=(e,t)=>
9{const n=e+Pb-Date.now();n>0?setTimeout(t,n):t()},bm=280,Ob=e=>"#"+e.trim().split(/\s+/).map(t=>Math.round(+t).toString(16).padStart(2,"0")).join(""),tl=(e,t)=>{nt()||setTimeout(()=>{const a=document.querySelector('[data-sonner-toast][data-front="true"] [data-icon]')?.getBoundingClientRect(),r=a&&a.width?{x:(a.left+a.width/2)/window.innerWidth,y:(a.top+a.height/2)/window.innerHeight}:{x:.85,y:.9},o=getComputedStyle(document.documentElement);Ti({particleCount:e,spread:70,startVelocity:22,ticks:120,origin:r,colors:t.map(c=>Ob(o.getPropertyValue(c))),disableForReducedMotion:!0})},bm)},$b=({n:e})=>{const[t,n]=i.useState(Math.max(0,e-1));return i.useEffect(()=>{const a=setTimeout(()=>n(e),bm);return()=>clearTimeout(a)},[e]),s.jsx(Ki,{value:t})},Fb=()=>{const{session:e}=we.useSessionContext(),t=e?.user?.id,n=at(),{data:a}=Hi(),{data:r}=Vi(),o=i.useRef(!1),c=i.useRef(null),l=i.useRef(null),d=i.useRef(null),m=i.useRef(0);return i.useEffect(()=>{if(!t)return;const u=()=>{m.current=Date.now(),o.current=!0,c.current&&clearTimeout(c.current),c.current=setTimeout(()=>{o.current=!1},12e3),l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{n.invalidateQueries({queryKey:["achievements",t]}),n.invalidateQueries({queryKey:["streak",t]})},1200)};return window.addEventListener("task-completion-finished",u),window.addEventListener("focus-task-completed",u),()=>{window.removeEventListener("task-completion-finished",u),window.removeEventListener("focus-task-completed",u),c.current&&clearTimeout(c.current),l.current&&clearTimeout(l.current)}},[n,t]),i.useEffect(()=>{const u=r?.achievements??[];if(!u.length&&d.current===null)return;const f=u.filter(Es).map(h=>h.id);if(d.current===null){d.current=new Set(f);return}if(!o.current){d.current=new Set(f);return}const p=u.filter(h=>Es(h)&&!d.current.has(h.id));d.current=new Set(f),p.length&&p.slice(0,nt()?1:2).forEach((h,g)=>{el(m.current,()=>setTimeout(()=>Zc(()=>{Z.success(`Achievement unlocked: ${h.achievement_name}`,{description:h.points?`${h.description} · +${h.points} pts`:h.description,icon:s.jsx(Zd,{className:"h-4 w-4"}),duration:5e3,className:"is-celebration toast-award"}
9),tl(22,["--q-do","--q-schedule","--q-delegate","--q-focus"])}),g*650))})},[r]),i.useEffect(()=>{if(!t||!o.current||!a?.activeToday)return;const u=`streak-celebrated:${t}:${Qa(new Date)}`;try{if(localStorage.getItem(u))return;localStorage.setItem(u,"1")}catch{return}const f=a.current;nt()&&!Gc(f)||el(m.current,()=>Zc(()=>{const p=[s.jsx($b,{n:f},"n"),"-day streak"];Gc(f)?(Z.success(p,{description:`${f} days running, that's a real habit now.`,icon:s.jsx(qn,{className:"h-4 w-4"}),duration:6e3,className:"is-celebration toast-streak"}),tl(36,["--q-delegate","--q-focus","--q-do"])):Z.success(p,{description:f===1?"Day one. Come back tomorrow to make it two.":"Streak's safe for today.",icon:s.jsx(qn,{className:"h-4 w-4"}),duration:3500,className:"is-celebration toast-streak"})}))},[a,t]),null},Pt=async(e,t,n,a)=>{try{await B.from("user_activities").insert({user_id:e,email:t,activity_type:n,details:a})}catch{}},qb=()=>{const{session:e}=we.useSessionContext(),t=e?.user?.id;i.useEffect(()=>{if(!t)return;const n=`app-open-logged:${t}:${Qa(new Date)}`;try{if(localStorage.getItem(n))return;localStorage.setItem(n,"1")}catch{return}Pt(t,e?.user?.email,"app_open",{at:new Date().toISOString()}).finally(()=>{window.dispatchEvent(new CustomEvent("streak-refresh"))})},[t,e?.user?.email])},zb=Xn("relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground",{variants:{variant:{default:"bg-background text-foreground",destructive:"border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive"}},defaultVariants:{variant:"default"}}),Yi=i.forwardRef(({className:e,variant:t,...n},a)=>s.jsx("div",{ref:a,role:"alert",className:S(zb({variant:t}),e),...n}));Yi.displayName="Alert";const ym=i.forwardRef(({className:e,...t},n)=>s.jsx("h5",{ref:n,className:S("mb-1 font-medium leading-none tracking-tight",e),...t}));ym.displayName="AlertTitle";const Wi=i.forwardRef(({className:e,...t},n)=>s.jsx("div",{ref:n,className:S("text-sm [&_p]:leading-relaxed",e),...t}));Wi.displayName="AlertDescription";const Mo=Xn("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-8",icon:"h-10 w-10"}},defaultVariants:{variant:"default",size:"default"}}),W=i.forwardRef(({className:e,variant:t,size:n,asChild:a=!1,...r},o)=>{const c=a?Cp:"button";return s.jsx(c,{className:S(Mo({variant:t,size:n,className:e})),ref:o,...r})});W.displayName="Button";const Ja=e=>e?.code==="23505"||/duplicate key|unique constraint/i.test(e?.message??"")?"This Todoist account is already connected to another Eisenhower Matrix account. Disconnect it there first, or connect a different Todoist account.":e?.status===401?"Invalid or expired Todoist token. Please reconnect your account.":e?.status===403?"Access denied. Please check your Todoist permissions.":e?.status===429?"Too many requests to Todoist. Please try again later.":e?.status===500?"Todoist service is temporarily unavailable. Please try again in a few moments.":e?.message?.includes("Edge Function")||e?.message?.includes("non-2xx status")?"Couldn't reach the Todoist connection service. Please try again.":e?.message?.includes("Failed to fetch")||e?.message?.includes("CORS")?"Network connection issue. Please check your internet connection.":e?.message?.includes("Internal Server Error")||e?.message?.includes("500")?"Todoist service is temporarily unavailable. Please try again in a few moments.":e?.message||"An unexpected error occurred. Please try again.",Ub=gr()(Tp(e=>({isConnecting:!1,setConnecting:t=>e({isConnecting:t}),lastSync:null,setLastSync:t=>e({lastSync:t}),connectionStatus:null,setConnectionStatus:t=>e({connectionStatus:t})}),{name:"todoist-auth-store"})),wm=()=>{const{session:e}=we.useSessionContext(),{toast:t}=He(),{isConnecting:n,setConnecting:a,setLastSync:r,connectionStatus:o,setConnectionStatus:c}=Ub(),l=i.useCallback(async()=>{try{a(!0),c("pending");const u="https://eisenhowertodoist.com/auth/callback",f="https://eisenhowertodoist.com",{data:p,error:h}=await B.functions.invoke("todoist-oauth-init",{body:{redirectUri:u,origin:f}});if(h)throw c("disconnected"),h;if(!p?.authUrl||!p?.state)throw c("disconnected"),new Error("Invalid OAuth initialization response");const g={state:p.state,timestamp:Date.now(),redirectUri:u,destination:"/matrix",origin:f,userId:e?.user?.id};return localStorage.setItem("todoist_oauth_state",JSON.stringify(g)),p.authUrl}
9catch(u){return c("disconnected"),t({title:"Connection Error",description:u.message||"Failed to initialize Todoist connection. Please try again.",variant:"destructive"}),null}finally{a(!1)}},[e?.user?.id,a,c,t]),d=i.useCallback(async(u,f)=>{try{a(!0),c("pending");const p=localStorage.getItem("todoist_oauth_state");if(!p)throw new Error("Authentication session expired or invalid");const h=JSON.parse(p);if(h.state!==f)throw new Error("Invalid authentication state");if(Date.now()-h.timestamp>1800*1e3)throw new Error("Authentication session expired");let g=null;try{const b=await B.functions.invoke("todoist-oauth-callback",{body:{code:u,state:f,redirectUri:"https://eisenhowertodoist.com/auth/callback"}});if(g=b.data,b.error){c("disconnected");const x=typeof b.error=="object"&&b.error.message?b.error.message:"Todoist connection failed";throw new Error(x)}}catch(b){throw b?.message?.includes("not valid JSON")?(c("disconnected"),new Error("Todoist connection service returned an unexpected response. Please try again.")):b}if(!g?.access_token)throw c("disconnected"),new Error("No access token received");if(e?.user?.id){const{error:b}=await B.from("profiles").update({todoist_access_token:g.access_token,todoist_user_id:String(g.user?.id??""),todoist_user_name:g.user?.full_name??"",todoist_user_email:g.user?.email??e?.user?.email??""}).eq("id",e.user.id);if(b)throw c("disconnected"),b;c("connected"),r(new Date),t({title:"Connected!",description:"Successfully connected to Todoist"})}return g.access_token}catch(p){return c("disconnected"),t({title:"Connection Failed",description:Ja(p)||"Could not complete Todoist connection. Please try again.",variant:"destructive"}),null}finally{localStorage.removeItem("todoist_oauth_state"),a(!1)}},[e?.user?.id,a,r,c,t]),m=i.useCallback(async()=>{if(!e?.user?.id)return c(null),!1;try{const{data:u,error:f}=await B.from("profiles").select("todoist_access_token").eq("id",e.user.id).single();if(f)return c("disconnected"),!1;const p=!!u?.todoist_access_token;return c(p?"connected":"disconnected"),p}catch{return c("disconnected"),!1}},[e?.user?.id,c]);return{isConnecting:n,connectionStatus:o,initializeOAuth:l,handleOAuthCallback:d,checkConnectionStatus:m}},Bb=({onSuccess:e})=>{const{isConnecting:t,initializeOAuth:n,checkConnectionStatus:a}=wm(),{session:r}=we.useSessionContext();i.useEffect(()=>{(async()=>{if(r?.user?.id)try{if(await a()){const{data:d}=await B.from("profiles").select("todoist_access_token").eq("id",r.user.id).single();d?.todoist_access_token&&await e(d.todoist_access_token)}}catch{}})()},[r?.user?.id,a,e]);const o=async()=>{try{const c=await n();c&&setTimeout(()=>{window.location.href=c},100)}catch{}};return s.jsx(_e.div,{initial:{opacity:0,y:-10},animate:{opacity:1,y:0},exit:{opacity:0,y:-10},transition:{duration:.3},children:s.jsx(Yi,{className:"mb-6 bg-white/50 dark:bg-card/50 backdrop-blur-lg border-primary/10 shadow-lg",children:s.jsxs(Wi,{className:"flex items-center justify-between",children:[s.jsxs("span",{className:"text-sm font-medium flex items-center gap-2",children:[t?s.jsx(kt,{className:"h-4 w-4 text-yellow-500 animate-spin"}):s.jsx(xr,{className:"h-4 w-4 text-yellow-500"}),t?"Connecting to Todoist...":"Please connect to Todoist to access your tasks and statistics"]}),s.jsx(W,{onClick:o,disabled:t,variant:"default",className:"relative overflow-hidden group",children:t?s.jsxs(s.Fragment,{children:[s.jsx(kt,{className:"mr-2 h-4 w-4 animate-spin"}),"Connecting..."]}):s.jsxs(s.Fragment,{children:["Connect with Todoist",s.jsx("div",{className:"absolute inset-0 bg-white/10 opacity-0 group-hover:opacity-100 transition-opacity duration-200"})]})})]})})})},Gi=()=>{const e=Xt(),{session:t}=we.useSessionContext(),{toast:n}=He(),[a,r]=i.useState(!1);return{reconnectTodoist:async()=>{try{r(!0);const{error:c}=await B.from("profiles").update({todoist_api_key:null,todoist_access_token:null,todoist_refresh_token:null,todoist_token_expires_at:null,todoist_user_id:null,todoist_user_name:null,todoist_user_email:null}).eq("id",t?.user?.id);if(c)throw c;await Pt(t?.user?.id||"",t?.user?.email,"logout",{action:"todoist_reconnect",timestamp:new Date().toISOString()}),e("/auth/callback")}catch{n({title:"Error",description:"Failed to reconnect Todoist. Please try again.",variant:"destructive"})}finally{r(!1)}},isReconnecting:a}},Hb=({error:e,onRetry:t})=>{const{reconnectTodoist:n,isReconnecting:a}=Gi(),r=e.isAuthError?"todoist_auth":typeof navigator<"u"&&navigator.onLine===!1?"network":"tasks_load";return i.useEffect(()=>{pe("error_shown",{kind:r})},[r]),s.jsxs(Yi,{variant:"destructive",className:"mb-3",children:[s.jsx(xr,{className:"h-4 w-4"}),s.jsx(ym,{children:e.isAuthError?"Todoist connection expired":"Couldn't load tasks"}),s.jsxs(Wi,{className:"flex flex-wrap items-center gap-2",children:[s.jsxs("span",{children:[e.message,e.showingCachedTasks&&" Showing your last loaded tasks meanwhile."]}),s.jsxs("span",{className:"flex items-center gap-2",children:[s.jsxs(W,{variant:"outline",size:"sm",className:"h-7",onClick:t,children:[s.jsx(_i,{className:"mr-1 h-3 w-3"}),"Retry"]}),e.isAuthError&&s.jsx(W,{variant:"outline",size:"sm",className:"h-7",onClick:n,disabled:a,children:a?"Reconnecting…":"Reconnect Todoist"})]})]})]})},Qi=i.createContext(null),Vb=({children:e})=>{const[t,n]=i.useState(null);return s.jsx(Qi.Provider,{value:{slot:t,setSlot:n},children:e})},sl=({className:e})=>{const t=i.useContext(Qi);return s.jsx("div",{ref:t?.setSlot,className:S("cm-filter-slot",e)})},Kb=()=>i.useContext(Qi)?.slot??null,Yn=i.forwardRef(({className:e,type:t,...n},a)=>s.jsx("input",{type:t,className:S("flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",e),ref:a,...n}));Yn.displayName="Input";const Xa=Ei,Yb=_p,Wb=br,vm=i.forwardRef(({className:e,...t},n)=>s.jsx(ln,{ref:n,className:S("fixed inset-0 z-50 bg-black/80  data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t}));vm.displayName=ln.displayName;const Za=i.forwardRef(({className:e,overlayClassName:t,children:n,...a},r)=>s.jsxs(Wb,{children:[s.jsx(vm,{className:t}),s.jsxs(dn,{ref:r,className:S("fixed z-50 grid w-full gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0","max-sm:inset-x-0 max-sm:bottom-0 max-sm:rounded-t-2xl max-sm:border-b-0 max-sm:max-h-[92vh] max-sm:overflow-y-auto max-sm:data-[state=open]:slide-in-from-bottom max-sm:data-[state=closed]:slide-out-to-bottom","sm:left-[50%] sm:top-[50%] sm:max-w-lg sm:translate-x-[-50%] sm:translate-y-[-50%] sm:rou
9nded-lg sm:data-[state=closed]:zoom-out-95 sm:data-[state=open]:zoom-in-95 sm:data-[state=closed]:slide-out-to-left-1/2 sm:data-[state=closed]:slide-out-to-top-[48%] sm:data-[state=open]:slide-in-from-left-1/2 sm:data-[state=open]:slide-in-from-top-[48%]",e),...a,children:[n,s.jsxs(yr,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[s.jsx(Ie,{className:"h-4 w-4"}),s.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Za.displayName=dn.displayName;const Lo=({className:e,...t})=>s.jsx("div",{className:S("flex flex-col space-y-1.5 text-center sm:text-left",e),...t});Lo.displayName="DialogHeader";const km=({className:e,...t})=>s.jsx("div",{className:S("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",e),...t});km.displayName="DialogFooter";const er=i.forwardRef(({className:e,...t},n)=>s.jsx(un,{ref:n,className:S("text-lg font-semibold leading-none tracking-tight",e),...t}));er.displayName=un.displayName;const tr=i.forwardRef(({className:e,...t},n)=>s.jsx(wr,{ref:n,className:S("text-sm text-muted-foreground",e),...t}));tr.displayName=wr.displayName;const Gb=[{id:"builtin:waiting",name:"Waiting",projects:[],labels:["waiting"],priorities:[],date_filter:"all",hide_subtasks:!1,is_default:!1,position:Number.MAX_SAFE_INTEGER,builtIn:!0}],ya=e=>[...e].sort((t,n)=>(t.position??0)-(n.position??0)),Qb=()=>{const{session:e}=we.useSessionContext(),[t,n]=i.useState([]),[a,r]=i.useState(!1);return i.useEffect(()=>{if(!e?.user)return;let u=!1;return(async()=>{r(!0);const{data:f,error:p}=await B.from("filter_presets").select("*").eq("user_id",e.user.id).order("created_at",{ascending:!1});!u&&!p&&f&&n(ya(f)),r(!1)})(),()=>{u=!0}},[e?.user]),{presets:t,loading:a,savePreset:async u=>{if(!e?.user)return null;const f=t.length?Math.min(...t.map(b=>b.position??0)):0,p={user_id:e.user.id,position:f-1,is_default:!1,...u};let{data:h,error:g}=await B.from("filter_presets").insert(p).select().single();if(g&&/hide_subtasks/.test(g.message??"")){const{hide_subtasks:b,...x}=p;({data:h,error:g}=await B.from("filter_presets").insert(x).select().single())}return!g&&h?(n(b=>ya([h,...b])),h):null},deletePreset:async u=>{await B.from("filter_presets").delete().eq("id",u),n(f=>f.filter(p=>p.id!==u))},renamePreset:async(u,f)=>{const p=f.trim();p&&(await B.from("filter_presets").update({name:p}).eq("id",u),n(h=>h.map(g=>g.id===u?{...g,name:p}:g)))},setDefaultPreset:async u=>{if(!e?.user)return;const p=!t.find(h=>h.id===u)?.is_default;p&&await B.from("filter_presets").update({is_default:!1}).eq("user_id",e.user.id),await B.from("filter_presets").update({is_default:p}).eq("id",u),n(h=>h.map(g=>({...g,is_default:g.id===u?p:!1})))},movePreset:async(u,f)=>{const p=ya(t),h=p.findIndex(C=>C.id===u);if(h===-1)return;const g=f==="up"?h-1:h+1;if(g<0||g>=p.length)return;const b=p[h],x=p[g],y=b.position??0,w=x.position??0,k=y===w?f==="up"?w-1:w+1:w,N=y;await Promise.all([B.from("filter_presets").update({position:k}).eq("id",b.id),B.from("filter_presets").update({position:N}).eq("id",x.id)]),n(C=>ya(C.map(v=>v.id===b.id?{...v,position:k}:v.id===x.id?{...v,position:N}:v)))}}},Jb=e=>{const{data:t=[],isLoading:n,isError:a}=it({queryKey:["todoist-filters",e],queryFn:async()=>{if(!e)return[];const r=new Ke(e);try{const o=await r.getFilters();return[...Array.isArray(o)?o:[]].sort((l,d)=>(l.item_order??0)-(d.item_order??0))}catch(o){throw Fi({title:"Error",description:"Failed to fetch your Todoist filters",variant:"destructive"}),o}},enabled:!!e,retry:1,staleTime:3e5,gcTime:18e5});return{filters:t,isLoading:n,isError:a}},Ji=e=>{const{toast:t}=He(),{data:n=[],isLoading:a}=it({queryKey:["projects",e],queryFn:async()=>{if(!e)return[];try{const o=await new Ke(e).getProjects();return(Array.isArray(o)?o:o?.results??[]).map(l=>({id:String(l.id),name:l.name,color:l.color,parent_id:l.parent_id?String(l.parent_id):void 0,order:l.child_order??l.order,is_inbox_project:l.is_inbox_project}))}catch{return t({title:"Error",description:"Failed to fetch projects",variant:"destructive"}),[]}},enabled:!!e});return{projects:n,isLoading:a}},jm=[{value:4,label:"P1",tone:"fb-p1"}
9,{value:3,label:"P2",tone:"fb-p2"},{value:2,label:"P3",tone:"fb-p3"},{value:1,label:"P4",tone:"fb-p4"}],Xb=e=>jm.find(t=>t.value===e)?.label??`P${e}`,Ao=[[{value:"all",label:"All"},{value:"overdue",label:"Overdue"},{value:"today",label:"Today"},{value:"today,overdue",label:"Today & overdue"}],[{value:"tomorrow",label:"Tomorrow"},{value:"this-week",label:"This week"},{value:"next-week",label:"Next week"},{value:"next-month",label:"Next month"}]],sr=e=>Ao.flat().find(t=>t.value===e)?.label??"",Qr=(e,t)=>e.length<=2?e.join(` ${t} `):`${e.slice(0,2).join(` ${t} `)} +${e.length-2}`,Zb=e=>{switch(e){case 4:return"P1";case 3:return"P2";case 2:return"P3";default:return"P4"}},kn=({icon:e,className:t,size:n,children:a})=>s.jsxs("span",{className:S("inline-flex items-center gap-1 rounded-md font-medium leading-none border",n==="sm"?"px-1.5 py-0.5 text-[10px]":"px-2 py-1 text-[11px]",t),children:[s.jsx(e,{className:n==="sm"?"h-2.5 w-2.5 shrink-0":"h-3 w-3 shrink-0"}),s.jsx("span",{className:"truncate max-w-[140px]",children:a})]}),nl=(e,t=2)=>e.length<=t?e.join(", "):`${e.slice(0,t).join(", ")} +${e.length-t}`,Po=({projects:e,labels:t,priorities:n,dateFilter:a,hideSubtasks:r=!1,projectNames:o={},size:c="sm",emptyText:l="Matches everything",className:d})=>{if(!(e.length>0||t.length>0||n.length>0||a!=="all"||r))return s.jsxs("span",{className:S("inline-flex items-center gap-1 text-muted-foreground",c==="sm"?"text-[10px]":"text-[11px]",d),children:[s.jsx(Ep,{className:c==="sm"?"h-2.5 w-2.5":"h-3 w-3"}),l]});const u=e.map(p=>o[p]??p),f=n.slice().sort((p,h)=>h-p).map(Zb);return s.jsxs("div",{className:S("flex flex-wrap items-center gap-1",d),children:[a!=="all"&&s.jsx(kn,{icon:Ss,size:c,className:"bg-green-500/10 text-green-600 dark:text-green-400 border-green-500/20",children:sr(a)}),e.length>0&&s.jsx(kn,{icon:Dp,size:c,className:"bg-blue-500/10 text-blue-600 dark:text-blue-400 border-blue-500/20",children:nl(u)}),t.length>0&&s.jsx(kn,{icon:vr,size:c,className:"bg-violet-500/10 text-violet-600 dark:text-violet-400 border-violet-500/20",children:nl(t.map(Jt))}),n.length>0&&s.jsx(kn,{icon:Cs,size:c,className:"bg-amber-500/10 text-amber-600 dark:text-amber-400 border-amber-500/20",children:f.join(", ")}),r&&s.jsx(kn,{icon:eu,size:c,className:"bg-slate-500/10 text-slate-500 dark:text-slate-400 border-slate-500/20",children:"Subtasks hidden"})]})},Wn=i.forwardRef(({className:e,...t},n)=>s.jsx(tu,{className:S("peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",e),...t,ref:n,children:s.jsx(Rp,{className:S("pointer-events-none block h-5 w-5 rounded-full bg-background dark:bg-white shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0")})}));Wn.displayName=tu.displayName;const ey=Xn("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),aa=i.forwardRef(({className:e,...t},n)=>s.jsx(su,{ref:n,className:S(ey(),e),...t}));aa.displayName=su.displayName;const Fa={projects:[],labels:[]},nr=new Map,Ks=new Map;function Nm(e){if(!e)return null;try{const t=JSON.parse(e);return!t||typeof t!="object"?null:{projects:Array.isArray(t.projects)?t.projects:[],labels:Array.isArray(t.labels)?t.labels:[]}}catch{return null}}function ty(e){if(typeof window>"u")return Fa;try{return Nm(window.localStorage.getItem(e))??Fa}catch{return Fa}}function qa(e){let t=nr.get(e);return t||(t=ty(e),nr.set(e,t)),t}function Sm(e){const t=Ks.get(e);if(t)for(const n of Array.from(t))n()}function wa(e,t){const n=qa(e),a=t(n);if(a!==n){if(nr.set(e,a),typeof window<"u")try{window.localStorage.setItem(e,JSON.stringify(a))}catch{}Sm(e)}}function sy(e,t){let n=Ks.get(e);return n||(n=new Set,Ks.set(e,n)),n.add(t),()=>{const a=Ks.get(e);a&&(a.delete(t),a.size===0&&Ks.delete(e))}}typeof window<"u"&&window.addEventListener("storage",e=>
9{if(!e.key||!Ks.has(e.key))return;const t=Nm(e.newValue);nr.set(e.key,t??Fa),Sm(e.key)});const al="matrix-usage-tracking-anonymous",Jr=e=>`matrix-usage-tracking-${e}`,Xi=()=>{const{session:e}=we.useSessionContext(),t=e?.user?.id,n=t?Jr(t):al,a=i.useCallback(f=>sy(n,f),[n]),r=i.useCallback(()=>qa(n),[n]),o=i.useSyncExternalStore(a,r,r);i.useEffect(()=>{if(!t)return;const f=qa(Jr(t));if(f.labels.length>0||f.projects.length>0)return;const p=qa(al);p.labels.length===0&&p.projects.length===0||wa(Jr(t),()=>p)},[t]);const c=i.useCallback((f,p)=>{wa(n,h=>{const g=[...h.projects],b=g.findIndex(x=>x.id===f);return b>=0?g[b]={...g[b],name:p||g[b].name,count:g[b].count+1,lastUsed:Date.now()}:g.push({id:f,name:p,count:1,lastUsed:Date.now()}),{...h,projects:g}})},[n]),l=i.useCallback(f=>{wa(n,p=>{const h=[...p.labels],g=h.findIndex(b=>b.name===f);return g>=0?h[g]={...h[g],count:h[g].count+1,lastUsed:Date.now()}:h.push({id:f,name:f,count:1,lastUsed:Date.now()}),{...p,labels:h}})},[n]),d=i.useCallback((f=5)=>[...o.projects].sort((p,h)=>h.count-p.count||h.lastUsed-p.lastUsed).slice(0,f),[o.projects]),m=i.useCallback((f=5)=>[...o.labels].sort((p,h)=>h.count-p.count||h.lastUsed-p.lastUsed).slice(0,f),[o.labels]),u=i.useCallback(()=>{wa(n,()=>({projects:[],labels:[]}))},[n]);return{trackProjectUsage:c,trackLabelUsage:l,getTopProjects:d,getTopLabels:m,clearUsageData:u,usageData:o}},ny=Xn("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",destructive:"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",outline:"text-foreground",new:"border-transparent bg-gradient-to-r from-purple-500 to-indigo-600 text-white shadow-sm animate-pulse",filter:"flex items-center gap-1.5 py-1 px-2 text-xs hover:bg-opacity-90 transition-all duration-200 shadow-sm",success:"border-transparent bg-green-100 text-green-800 dark:bg-green-900/20 dark:text-green-400",warning:"border-transparent bg-amber-100 text-amber-800 dark:bg-amber-900/20 dark:text-amber-400",info:"border-transparent bg-blue-100 text-blue-800 dark:bg-blue-900/20 dark:text-blue-400",muted:"border-transparent bg-gray-100 text-gray-800 dark:bg-gray-800/40 dark:text-gray-400",do:"border-transparent bg-red-100 text-red-800 dark:bg-red-900/20 dark:text-red-400",schedule:"border-transparent bg-blue-100 text-blue-800 dark:bg-blue-900/20 dark:text-blue-400",delegate:"border-transparent bg-orange-100 text-orange-800 dark:bg-orange-900/20 dark:text-orange-400",backlog:"border-transparent bg-gray-100 text-gray-800 dark:bg-gray-800/40 dark:text-gray-400","high-priority":"border-transparent bg-red-100 text-red-800 dark:bg-red-900/20 dark:text-red-400","medium-priority":"border-transparent bg-amber-100 text-amber-800 dark:bg-amber-900/20 dark:text-amber-400","low-priority":"border-transparent bg-green-100 text-green-800 dark:bg-green-900/20 dark:text-green-400"},size:{default:"px-2.5 py-0.5 text-xs",sm:"px-2 py-0.5 text-[0.625rem]",lg:"px-3 py-1 text-sm"},animation:{none:"",pulse:"animate-pulse",bounce:"animate-bounce"}},defaultVariants:{variant:"default",size:"default",animation:"none"}});function Ds({className:e,variant:t,size:n,animation:a,...r}){return s.jsx("div",{className:S(ny({variant:t,size:n,animation:a}),e),...r})}const Cm=({type:e,onSelect:t,compact:n=!1})=>{const{getTopLabels:a,getTopProjects:r}=Xi(),o=e==="labels"?a():r();return o.length?s.jsxs("div",{className:`flex gap-1.5 ${n?"mt-2":"mt-1"} items-center flex-wrap`,children:[!n&&s.jsx("span",{className:"text-xs text-muted-foreground mr-1",children:"Frequent:"}),s.jsx("div",{className:"flex gap-1.5 flex-wrap",children:o.map(c=>s.jsx(Ds,{variant:"outline",className:`cursor-pointer bg-[#8B5CF6]/5 hover:bg-[#8B5CF6]/10 border-[#8B5CF6]/20 
10                     text-[#8B5CF6] transition-all duration-200 text-xs py-0.5 px-2 
11                     hover:border-[#8B5CF6]/30 font-medium rounded-full`,onClick:()=>t(c.id,c.name),children:c.name},c.id))})]}):null},hn=Mp,pn=Lp,ay=i.forwardRef(({className:e,inset:t,children:n,...a},r)=>s.jsxs(nu,{ref:r,className:S("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent",t&&"pl-8",e),...a,children:[n,s.jsx(pt,{className:"ml-auto h-4 w-4"})]}));ay.displayName=nu.displayName;const ry=i.forwardRef(({className:e,...t},n)=>s.jsx(au,{ref:n,className:S("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:sli
11de-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...t}));ry.displayName=au.displayName;const As=i.forwardRef(({className:e,sideOffset:t=4,...n},a)=>s.jsx(Ip,{children:s.jsx(ru,{ref:a,sideOffset:t,className:S("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...n})}));As.displayName=ru.displayName;const dt=i.forwardRef(({className:e,inset:t,...n},a)=>s.jsx(ou,{ref:a,className:S("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...n}));dt.displayName=ou.displayName;const Lr=i.forwardRef(({className:e,children:t,checked:n,...a},r)=>s.jsxs(iu,{ref:r,className:S("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),checked:n,...a,children:[s.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:s.jsx(cu,{children:s.jsx(Oe,{className:"h-4 w-4"})})}),t]}));Lr.displayName=iu.displayName;const oy=i.forwardRef(({className:e,children:t,...n},a)=>s.jsxs(lu,{ref:a,className:S("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[s.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:s.jsx(cu,{children:s.jsx(Di,{className:"h-2 w-2 fill-current"})})}),t]}));oy.displayName=lu.displayName;const tn=i.forwardRef(({className:e,inset:t,...n},a)=>s.jsx(du,{ref:a,className:S("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",e),...n}));tn.displayName=du.displayName;const is=i.forwardRef(({className:e,...t},n)=>s.jsx(uu,{ref:n,className:S("-mx-1 my-1 h-px bg-muted",e),...t}));is.displayName=uu.displayName;const iy=/[̀-ͯ]/g,Tm=e=>e.normalize("NFD").replace(iy,"").toLowerCase().replace(/ı/g,"i"),Oo=e=>Tm(e),cy=e=>{let t="";const n=[];for(let a=0;a<e.length;a++){const r=Tm(e[a]);for(let o=0;o<r.length;o++)n.push(a);t+=r}return{out:t,map:n}},_m=(e,t)=>e.localeCompare(t,"tr",{sensitivity:"base"}),Ar=(e,t,n)=>{const a=Oo(t.trim());if(!a)return[];const r=[];for(const o of e){const c=n(o),{out:l,map:d}=cy(c),m=l.indexOf(a);if(m<0)continue;const u=m===0||/[\s\-_/.·]/.test(l[m-1]),f=m===0?0:u?1:2,p=d[m],h=(d[m+a.length-1]??c.length-1)+1;r.push({item:o,range:[p,h],rank:f})}return r.sort((o,c)=>o.rank-c.rank||_m(n(o.item),n(c.item)))},Em=(e,t)=>[...e].sort((n,a)=>_m(t(n),t(a))),ly="cubic-bezier(0.2, 0, 0, 1)",dy=()=>typeof window<"u"&&!!window.matchMedia?.("(prefers-reduced-motion: reduce)").matches,Dm=({facet:e,title:t,mode:n,noun:a,options:r,selected:o,onToggle:c,onReset:l,frequent:d=[],onFrequent:m,autoFocus:u=!1,size:f="popover",emptyText:p})=>{const[h,g]=i.useState(""),b=i.useMemo(()=>new Map(r.map(A=>[A.value,A])),[r]),x=o.map(A=>b.get(A)??{value:A,label:A}),[y]=i.useState(d),w=!h&&m?y.map(A=>d.find(H=>H.id===A.id)??{...A,selected:o.includes(A.id)||o.includes(A.name)}):[],k=i.useRef(new Set(o)),[N,C]=i.useState([]),v=i.useRef(o),j=i.useRef(null),T=i.useRef(null),_=i.useRef(b);_.current=b;const I=i.useRef([]);i.useEffect(()=>()=>I.current.forEach(clearTimeout),[]),i.useEffect(()=>{const A=v.current;v.current=o;const H=A.filter(K=>!o.includes(K));!H.length||dy()||(C(K=>[...K,...H.map(X=>({opt:_.current.get(X)??{value:X,label:X},index:A.indexOf(X)}))]),I.current.push(window.setTimeout(()=>{const K=new Map;j.current?.querySelectorAll("[data-token]").forEach(X=>K.set(X.dataset.token,X.getBoundingClientRect().left)),T.current=K,C(X=>X.filter(ce=>
11!H.includes(ce.opt.value)))},100)))},[o]),i.useLayoutEffect(()=>{const A=T.current;T.current=null,!(!A||!j.current)&&j.current.querySelectorAll("[data-token]").forEach(H=>{const K=A.get(H.dataset.token),X=K==null?0:K-H.getBoundingClientRect().left;Math.abs(X)>.5&&H.animate([{transform:`translateX(${X}px)`},{transform:"none"}],{duration:220,easing:ly})})},[N]),i.useEffect(()=>{o.forEach(A=>k.current.add(A))},[o]);const R=o.length,M=i.useRef(R);i.useEffect(()=>{R>M.current&&j.current&&(j.current.scrollTop=j.current.scrollHeight),M.current=R},[R]);const P=x.map(A=>({opt:A,leaving:!1}));N.forEach(({opt:A,index:H})=>{P.some(K=>K.opt.value===A.value)||P.splice(Math.min(H,P.length),0,{opt:A,leaving:!0})});const E=i.useRef(null);i.useEffect(()=>{E.current&&(E.current.scrollTop=0)},[h]);const[D,L]=i.useState("idle");return s.jsxs("div",{className:S("fb-combo",`fb-${e}`,f==="panel"&&"is-panel"),children:[s.jsxs("div",{className:"fb-phead",children:[f==="panel"?s.jsxs("span",{className:"fb-h",children:[t," ",s.jsxs("span",{children:["· ",n]})]}):s.jsxs("span",{children:[s.jsx("b",{children:t})," · ",n]}),l&&s.jsx("button",{type:"button",className:S("fb-reset",!o.length&&"is-idle"),tabIndex:o.length?void 0:-1,"aria-hidden":!o.length||void 0,onClick:l,children:"Reset"})]}),s.jsxs(Mt,{className:"fb-combo-cmd",label:`${t} filter`,loop:!0,filter:(A,H,K)=>{const X=Ar([(K?.[0]??A).replace(/^@/,"")],H,ce=>ce)[0];return X?1-X.rank*.1:0},onKeyDown:()=>L("kbd"),children:[s.jsxs("div",{className:"fb-combo-field",children:[P.length>0&&s.jsx("div",{ref:j,className:"fb-tokens","aria-label":`Selected ${t.toLowerCase()}`,children:P.map(({opt:A,leaving:H})=>{const K=!H&&!k.current.has(A.value);return s.jsxs("span",{"data-token":A.value,className:S("fb-token",K&&"is-new",H&&"is-leaving"),children:[s.jsx("span",{className:"fb-token-label",children:A.label}),s.jsx("button",{type:"button",tabIndex:H?-1:void 0,"aria-label":`Remove ${A.label}`,onClick:()=>c(A.value,!1),children:s.jsx(Ie,{"aria-hidden":!0})})]},A.value)})}),s.jsxs("div",{className:"fb-combo-input",children:[s.jsx(Ri,{"aria-hidden":!0}
11),s.jsx(Mt.Input,{value:h,onValueChange:g,autoFocus:u,placeholder:`Search ${a}s`,onKeyDown:A=>{A.key==="Backspace"&&!h&&x.length&&c(x[x.length-1].value,!1)}})]})]}),w.length>0&&s.jsxs("div",{className:"fb-freq","aria-label":"Frequently used",children:[s.jsx("span",{className:"fb-freq-label",children:"Frequent"}),w.map(A=>s.jsx("button",{type:"button",className:S(A.selected&&"is-on"),"aria-pressed":A.selected,title:A.name,onClick:()=>m?.(A),children:e==="label"?Jt(A.name):A.name},A.id))]}),s.jsxs(Mt.List,{ref:E,className:"fb-combo-list","data-input":D,onPointerMove:()=>{D!=="ptr"&&L("ptr")},onPointerLeave:()=>{D==="ptr"&&L("idle")},children:[s.jsx(Mt.Empty,{className:"fb-note fb-combo-empty",children:h?`No ${a} matches “${h}”`:p}),r.map(A=>{const H=o.includes(A.value);return s.jsxs(Mt.Item,{value:`${A.label}\0${A.value}`,keywords:[A.label],onSelect:()=>{c(A.value,!H),h&&g("")},className:"fb-combo-item","data-checked":H||void 0,children:[s.jsx("span",{className:"fb-combo-check","aria-hidden":!0,children:H&&s.jsx(Oe,{})}),s.jsx("span",{className:"fb-combo-label",children:A.label}),H&&s.jsx("span",{className:"sr-only",children:"(selected)"})]},A.value)})]})]})]})},Rm=({apiKey:e,selectedProjects:t,onProjectsChange:n,compact:a=!1,variant:r="default"})=>{const{projects:o,isLoading:c}=Ji(e),{trackProjectUsage:l,getTopProjects:d}=Xi(),m=(h,g)=>{let b;if(g){b=[...t,h];const x=o.find(y=>y.id===h);x&&l(h,x.name)}else b=t.filter(x=>x!==h);n(b)},u=(h,g="")=>{if(!t.includes(h)){const b=[...t,h];n(b),l(h,g)}},f=()=>{n([])};if(r!=="default")return s.jsx(Dm,{facet:"project",noun:"project",title:"Projects",mode:"any of",size:r==="list"?"popover":"panel",autoFocus:r==="list",options:o.map(h=>({value:h.id,label:h.is_inbox_project?"Inbox":h.name})),selected:t,onToggle:m,onReset:f,frequent:d().map(h=>({...h,selected:t.includes(h.id)})),onFrequent:h=>h.selected?n(t.filter(g=>g!==h.id)):u(h.id,h.name),emptyText:c?"Loading projects…":"No projects"});const p=t.length===0?"All Projects":`${t.length} project${t.length>1?"s":""} selected`;return s.jsxs("div",{className:`flex flex-col space-y-1.5 max-w-[240px] ${a?"w-full":""}`,children:[s.jsxs("div",{className:"flex items-center gap-2",children:[a&&s.jsx(Ap,{className:"h-3.5 w-3.5 text-primary/70"}),s.jsx(aa,{htmlFor:"project-filter",className:`font-medium ${a?"text-xs":""}`,children:"Projects"})]}),s.jsxs("div",{className:"flex flex-col space-y-1.5 w-full",children:[s.jsxs(hn,{children:[s.jsx(pn,{asChild:!0,children:s.jsxs(W,{variant:"outline",className:"w-full justify-between",id:"project-filter",disabled:c,children:[p,s.jsx(mt,{className:"h-4 w-4 ml-2 opacity-50"})]})}),s.jsxs(As,{className:"z-[70] w-[200px] max-h-[400px] overflow-y-auto",children:[s.jsx(tn,{children:"Select Projects"}),s.jsx(is,{}),o.map(h=>s.jsx(Lr,{checked:t.includes(h.id),onCheckedChange:g=>m(h.id,g),children:h.is_inbox_project?"Inbox":h.name},h.id))]})]}),t.length>0&&s.jsx(W,{variant:"ghost",size:"sm",className:"self-start text-xs text-muted-foreground hover:text-destructive",onClick:f,children:"Reset projects"}),s.jsx(Cm,{type:"projects",onSelect:u,compact:a})]})]})},uy=(e,t=[])=>{const{data:n=[]}=it({queryKey:["labels",e],queryFn:async()=>{if(!e)return[];const c=new Ke(e);try{const l=await c.getLabels();return Array.isArray(l)?l:l?.results??[]}catch{return Fi({title:"Error",description:"Failed to fetch labels",variant:"destructive"}),[]}},enabled:!!e,staleTime:3e5,gcTime:18e5}),a=i.useMemo(()=>Array.from(new Set(t.filter(c=>!c.completed).flatMap(c=>c.labels||[]))),[t]),r=i.useMemo(()=>{const c=new Map;return[...n.map(l=>l.name),...a].forEach(l=>{if(typeof l!="string")return;const d=Qt(l);c.has(d)||c.set(d,l)}),Array.from(c.values()).sort()},[n,a]),o=i.useCallback(c=>{const l=["do","schedule","delegate","backlog"];return c.labels.find(d=>l.includes(d.toLowerCase()))},[]);return{allLabels:r,taskLabels:a,todoistLabels:n,getMatrixLabel:o}},Im=({apiKey:e,selectedLabels:t,onLabelsChange:n,tasks:a=[],variant:r="default"})=>{const{allLabels:o}=uy(e,a),{trackLabelUsage:c,getTopLabels:l}=Xi(),d=(p,h)=>{let g;h?(g=[...t,p],c(p)):g=t.filter(b=>b!==p),n(g)},m=(p,h)=>{if(!t.includes(h)){const g=[...t,h];n(g),c(h)}},u=()=>{n([])};if(r!=="default")return s.jsx(Dm,{facet:"label",noun:"label",title:"Labels",mode:"all of",size:r==="list"?"popover":"panel",autoFocus:r==="list",options:Em(o,p=>p).map(p=>({value:p,label:Jt(p)})),selected:t,onToggle:d,onReset:u,frequent:l().map(p=>({...p,selected:t.includes(p.name)})),onFrequent:p=>p.selected?n(t.filter(h=>h!==p.name)):m(p.id,p.name),emptyText:"No labels"});const f=t.length===0?"All Labels":`${t.length} label${t.length>
111?"s":""} selected`;return s.jsxs("div",{className:"flex flex-col space-y-2 max-w-[240px]",children:[s.jsx(aa,{htmlFor:"label-filter",className:"font-medium",children:"Labels"}),s.jsxs("div",{className:"flex flex-col space-y-1.5",children:[s.jsxs(hn,{children:[s.jsx(pn,{asChild:!0,children:s.jsxs(W,{variant:"outline",className:"w-full justify-between",id:"label-filter",children:[f,s.jsx(mt,{className:"h-4 w-4 ml-2 opacity-50"})]})}),s.jsxs(As,{className:"z-[70] w-[200px] max-h-[400px] overflow-y-auto",children:[s.jsx(tn,{children:"Select Labels"}),s.jsx(is,{}),o.map(p=>s.jsx(Lr,{checked:t.includes(p),onCheckedChange:h=>d(p,h),children:p},p))]})]}),t.length>0&&s.jsx(W,{variant:"ghost",size:"sm",className:"self-start text-xs text-muted-foreground hover:text-destructive",onClick:u,children:"Reset labels"}),s.jsx(Cm,{type:"labels",onSelect:m,compact:!1})]})]})},my=12,Mm=({facet:e,layout:t,title:n,mode:a,options:r,selected:o,onToggle:c,single:l=!1,splitAt:d,onReset:m,frequent:u=[],onFrequent:f,emptyText:p})=>{const h=l?"radio":"checkbox",[g,b]=i.useState(""),x=r.length>my,y=g.trim(),w=y?Ar(r,y,v=>v.label.replace(/^@/,"")).map(v=>v.item):r,k=o.length>0&&!(l&&o[0]==="all"),N=x&&s.jsx("input",{className:"fb-search",type:"search",placeholder:`Find ${n.toLowerCase()}`,"aria-label":`Find ${n.toLowerCase()}`,value:g,onChange:v=>b(v.target.value)}),C=u.length>0&&f&&s.jsxs("div",{className:"fb-freq",children:[s.jsx("span",{className:"fb-freq-label",children:"Frequent"}),u.map(v=>s.jsx("button",{type:"button",className:S(v.selected&&"is-on"),"aria-pressed":v.selected,title:v.name,onClick:()=>f(v),children:e==="label"?Jt(v.name):v.name},v.id))]});return t==="chips"?s.jsxs("div",{className:`fb-${e}`,children:[s.jsxs("div",{className:"fb-phead fb-chips-head",children:[s.jsxs("span",{className:"fb-h",children:[n," ",s.jsxs("span",{children:["· ",a]})]}),m&&s.jsx("button",{type:"button",className:S("fb-reset",!k&&"is-idle"),tabIndex:k?void 0:-1,"aria-hidden":!k||void 0,onClick:m,children:"Reset"})]}),C,N,s.jsxs("div",{className:"fb-chips",role:l?"radiogroup":"group","aria-label":n,children:[w.map(v=>{const j=o.includes(v.value);return s.jsx("button",{type:"button",className:"fb-chip",role:l?"radio":void 0,"aria-checked":l?j:void 0,"aria-pressed":l?void 0:j,title:v.label,onClick:()=>c(v.value,!j),children:s.jsx("span",{className:S(!j&&v.tone),children:v.label})},v.value)}),w.length===0&&(y||p)&&s.jsx("span",{className:"fb-note",children:y?"No match":p})]})]}):s.jsxs("div",{className:`fb-${e}`,children:[s.jsxs("div",{className:"fb-phead",children:[s.jsxs("span",{children:[s.jsx("b",{children:n})," · ",a]}),m&&k&&s.jsx("button",{type:"button",className:"fb-reset",onClick:m,children:"Reset"})]}),C,C&&s.jsx("div",{className:"fb-sep"}),N,s.jsxs("div",{role:l?"radiogroup":"group","aria-label":n,children:[w.map((v,j)=>{const T=o.includes(v.value);return s.jsxs("div",{children:[d!==void 0&&j===d&&!y&&s.jsx("div",{className:"fb-sep"}),s.jsxs("button",{type:"button",role:h,"aria-checked":T,className:"fb-row",onClick:()=>c(v.value,!T),children:[s.jsx("span",{className:S("fb-box",l&&"fb-radio"),"aria-hidden":!0,children:!l&&T&&s.jsx(Oe,{})}),s.jsx("span",{className:v.tone,children:v.label})]})]},v.value)}),w.length===0&&(y||p)&&s.jsx("div",{className:"fb-note",children:y?"No match":p})]})]})},Lm=[{label:"P1",value:4},{label:"P2",value:3},{label:"P3",value:2},{label:"P4",value:1}],fy=e=>{const t=Lm.find(n=>n.value===e);return t?t.label:`P${e}`},Am=({selectedPriorities:e,onPrioritiesChange:t,variant:n="default"})=>{const a=(c,l)=>{let d;l?d=[...e,c]:d=e.filter(m=>m!==c),t(d)},r=()=>t([]);if(n!=="default")return s.jsx(Mm,{facet:"priority",layout:n,title:"Priority",mode:"any of",options:jm.map(c=>({value:String(c.value),label:c.label,tone:c.tone})),selected:e.map(String),onToggle:(c,l)=>a(Number(c),l),onReset:r});const o=e.length===0?"All Priorities":`${e.sort((c,l)=>l-c).map(c=>fy(c)).join(", ")}`;return s.jsxs("div",{className:"flex flex-col space-y-2 max-w-[240px]",children:[s.jsx(aa,{htmlFor:"priority-filter",className:"font-medium",children:"Priority"}),s.jsxs("div",{className:"flex flex-col space-y-1.5",children:[s.jsxs(hn,{children:[s.jsx(pn,{asChild:!0,children:s.jsxs(W,{variant:"outline",className:"w-full justify-between",id:"priority-filter",children:[o,s.jsx(mt,{className:"h-4 w-4 ml-2 opacity-50"})]})}),s.jsxs(As,{className:"z-[70] w-[180px]",children:[s.jsx(tn,{children:"Select Priorities"}),s.jsx(is,{}),Lm.map(({label:c,value:l})=>s.jsx(Lr,{checked:e.includes(l),onCheckedChange:d=>
11a(l,d),children:c},l))]})]}),e.length>0&&s.jsx(W,{variant:"ghost",size:"sm",className:"self-start text-xs text-muted-foreground hover:text-destructive",onClick:r,children:"Reset priority"})]})]})},hy=({onClear:e,label:t})=>{const n=a=>{a.key==="Escape"&&e()};return s.jsx(Ls,{children:s.jsxs(Ht,{children:[s.jsx(Vt,{asChild:!0,children:s.jsx(W,{variant:"ghost",size:"icon",className:"h-8 w-8 p-0 hover:bg-destructive/10 hover:text-destructive transition-colors",onClick:e,onKeyDown:n,"aria-label":`Clear ${t} filter`,children:s.jsx(Ie,{className:"h-4 w-4"})})}),s.jsx(At,{children:s.jsxs("p",{children:["Clear ",t.toLowerCase()," filter"]})})]})})},rl=[{label:"Overdue",value:"overdue",icon:xr,description:"Overdue tasks"},{label:"Today",value:"today",icon:Kt,description:"Tasks due today"},{label:"All",value:"all",icon:Ri,description:"Show all tasks"}],ol=[{label:"Tomorrow",value:"tomorrow",icon:Ss,description:"Tasks due tomorrow"},{label:"This Week",value:"this-week",icon:Kt,description:"Tasks due this week"},{label:"Next Week",value:"next-week",icon:mu,description:"Tasks due next week"},{label:"Next Month",value:"next-month",icon:Ss,description:"Tasks due next month"}],Zi=i.memo(({value:e,onValueChange:t,variant:n="default",onPicked:a})=>{const[r,o]=i.useState(!1),c=i.useCallback(l=>{e!==l&&requestAnimationFrame(()=>{t(l)})},[e,t]);return n!=="default"?s.jsx(Mm,{facet:"date",layout:n,title:"Date",mode:"one of",single:!0,options:Ao.flat(),splitAt:Ao[0].length,selected:[e],onToggle:l=>{l!==e?t(l):n==="chips"&&l!=="all"&&t("all"),a?.()},onReset:()=>t("all")}):([...rl,...ol].find(l=>l.value===e),s.jsx("div",{className:"date-filter flex flex-col gap-2",children:s.jsxs(_e.div,{layout:!0,className:"flex flex-wrap items-center gap-2",children:[s.jsx("div",{className:"flex flex-wrap gap-2",children:rl.map(({label:l,value:d,icon:m,description:u})=>s.jsxs(W,{variant:e===d?"default":"outline",onClick:()=>c(d),className:S("relative gap-2 transition-all duration-75 ease-out","hover:shadow-lg hover:scale-[1.02] active:scale-[0.98]",e===d&&["bg-primary text-primary-foreground","shadow-lg shadow-primary/20","ring-2 ring-primary/20","after:absolute after:inset-0 after:rounded-lg","after:bg-primary/5"],e!==d&&["hover:bg-muted/80","hover:border-primary/20"]),title:u,children:[s.jsx(m,{className:S("h-4 w-4 transition-transform",e===d&&"scale-110")}),s.jsx("span",{className:"font-medium",children:l})]},d))}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs(hn,{open:r,onOpenChange:o,children:[s.jsx(pn,{asChild:!0,children:s.jsxs(W,{variant:"ghost",className:"gap-2",title:r?"Show less filters":"Show more filters",children:[s.jsx(pt,{className:S("h-4 w-4 transition-transform duration-200",r&&"rotate-90")}),s.jsx("span",{className:"font-medium",children:r?"Less filters":"More filters"})]})}),s.jsx(As,{align:"start",className:"z-[70] w-[300px] max-w-[calc(100vw-2rem)] p-2 grid gap-2",children:ol.map(({label:l,value:d,icon:m,description:u})=>s.jsxs(W,{variant:e===d?"default":"outline",onClick:()=>c(d),className:S("relative gap-2 transition-all duration-75 ease-out w-full justify-start","hover:shadow-lg hover:scale-[1.02] active:scale-[0.98]",e===d&&["bg-primary text-primary-foreground","shadow-lg shadow-primary/20","ring-2 ring-primary/20","after:absolute after:inset-0 after:rounded-lg","after:bg-primary/5"],e!==d&&["hover:bg-muted/80","hover:border-primary/20"]),title:u,children:[s.jsx(m,{className:S("h-4 w-4 transition-transform",e===d&&"scale-110")}),s.jsx("span",{className:"font-medium",children:l})]},d))})]}),e!=="all"&&s.jsx(hy,{onClear:()=>c("all"),label:"Date"})]})]})}))});Zi.displayName="TaskDateFilter";const il=".cm-toolbar, .classic-toolbar, .fb-inline",ec=e=>{const t=i.useRef(null),n=i.useRef({dx:0,dy:0,w:0,h:0,base:null}),a=i.useRef(null),r=i.useRef({contextElement:void 0,getBoundingClientRect(){const c=n.current;if(c.base&&!c.base.isConnected){const m=t.current,u=m?.isConnected?m.closest(il):null;if(u&&u.className===c.base.className)c.base=u;else if(a.current)return a.current}if(!c.base)return t.current?.getBoundingClientRect()??new DOMRect;
11const l=c.base.getBoundingClientRect(),d=e==="end"?l.right-c.dx-c.w:l.left+c.dx;return a.current=new DOMRect(d,l.top+c.dy,c.w,c.h),a.current}}),o=i.useCallback(()=>{const c=t.current;if(!c)return;const l=c.closest(il)??c.parentElement;if(!l)return;const d=l.getBoundingClientRect(),m=c.getBoundingClientRect();n.current={dx:e==="end"?d.right-m.right:m.left-d.left,dy:m.top-d.top,w:m.width,h:m.height,base:l},r.current.contextElement=l},[e]);return{triggerRef:t,virtualRef:r,freeze:o}},tc=e=>{const t=i.useRef(null),[n,a]=i.useState(void 0);return i.useLayoutEffect(()=>{if(!e)return;a(void 0);let r=0,o=0;const c=()=>{const l=t.current,d=l&&!l.parentElement?.style.transform.includes("-200%"),m=l?.getAttribute("data-side");if(d&&(m==="top"||m==="bottom")){a(m);return}++o<30&&(r=requestAnimationFrame(c))};return r=requestAnimationFrame(c),()=>cancelAnimationFrame(r)},[e]),{ref:t,side:n}},py="cubic-bezier(0.2, 0, 0, 1)",gy=()=>typeof window<"u"&&!!window.matchMedia?.("(prefers-reduced-motion: reduce)").matches,sc=e=>{const t=i.useRef(null),n=i.useRef(null),a=i.useRef(e),r=i.useRef(null);return a.current!==e&&(a.current=e,r.current=t.current?t.current.getBoundingClientRect().width:null),i.useLayoutEffect(()=>{const o=t.current,c=r.current;if(r.current=null,!o||c==null)return;n.current?.cancel(),n.current=null,o.classList.remove("is-morphing");const l=o.getBoundingClientRect().width;if(Math.abs(c-l)<1||gy())return;o.classList.add("is-morphing");const d=o.animate([{width:`${c}px`},{width:`${l}px`}],{duration:220,easing:py});n.current=d,d.onfinish=()=>{o.classList.remove("is-morphing"),n.current=null},d.oncancel=()=>o.classList.remove("is-morphing")},[e]),t},xy=({text:e,size:t,className:n})=>{const[a,r]=i.useState(null),o=i.useRef({text:e,size:t}),c=i.useRef(0);return i.useEffect(()=>{const l=o.current;if(o.current={text:e,size:t},l.text===e||!l.text)return;c.current+=1,r({text:l.text,dir:t>=l.size?"up":"down",key:c.current});const d=window.setTimeout(()=>r(null),240);return()=>window.clearTimeout(d)},[e,t]),s.jsxs("span",{className:`fb-value-roll ${a?`is-rolling is-${a.dir}`:""} ${n??""}`,children:[a&&s.jsx("span",{className:"fb-roll-out","aria-hidden":!0,children:a.text},`o${a.key}`),s.jsx("span",{className:a?"fb-roll-in":void 0,children:e},`i${e}`)]})};let $o=!1;typeof window<"u"&&(window.addEventListener("pointerdown",()=>{$o=!0},!0),window.addEventListener("keydown",()=>{$o=!1},!0));const Pm=()=>$o,by="Paused while a Todoist filter is on",yy=()=>typeof window<"u"&&!!window.matchMedia?.("(prefers-reduced-motion: reduce)").matches,nc=(e,t)=>({ref:t.ref,side:t.side,sideOffset:6,collisionPadding:16,"data-swap":e||void 0,onCloseAutoFocus:n=>{Pm()&&n.preventDefault()}}),wy=e=>{Pm()&&(e.preventDefault(),e.target?.focus({preventScroll:!0}))},vy=e=>{const{apiKey:t,selectedProjects:n,onProjectsChange:a,selectedLabels:r,onLabelsChange:o,selectedPriorities:c,onPrioritiesChange:l,dateFilter:d,onDateFilterChange:m,hideSubtasks:u,onHideSubtasksChange:f,isPending:p,hasActiveFilters:h,selectedTodoistFilter:g,onClearAll:b,projectNames:x}=e,[y,w]=i.useState(null),k=Kb(),N=i.useRef(null),C=!!g,v=h||C,j=i.useRef(0),[T,_]=i.useState(!1),I=se=>{const ue=performance.now();y&&!se&&(j.current=ue),se&&se!==y&&_(!!y||ue-j.current<150),w(se)},[R,M]=i.useState(v);i.useEffect(()=>{(v||!y)&&M(v)},[v,y]);const[P,E]=i.useState(R),[D,L]=i.useState(!1),[A,H]=i.useState(null);i.useEffect(()=>{if(R===P)return;if(yy()){E(R);return}L(!0);const se=window.setTimeout(()=>{L(!1),E(R),H(R?"B":"A")},R?80:120);return()=>window.clearTimeout(se)},[R,P]),i.useEffect(()=>{if(!A)return;const se=window.setTimeout(()=>H(null),480);return()=>window.clearTimeout(se)},[A]);const K=D?P?"B-out":"A-out":P?"B":"A",X=se=>ue=>I(ue?se:null),ce=se=>{const ue=se.detail===0;b(),I(null),ue&&requestAnimationFrame(()=>N.current?.focus())},oe={project:n.length?Qr(n.map(se=>x[se]??se),"or"):"",projectN:n.length,label:r.length?Qr(r.map(Jt),"and"):"",labelN:r.length,priority:c.length?Qr([...c].sort((se,ue)=>ue-se).map(Xb),"or"):"",priorityN:c.length,date:d!=="all"?sr(d):"",subtasks:u},ve=i.useRef(oe),Ce=P&&!v&&!y;Ce||(ve.current=oe);const ee=Ce?ve.current:oe,Le=s.jsx(ky,{...e,swap:T,open:y==="saved",onOpenChange:X("saved"),close:()=>I(null)},"saved"),he=s.jsx(Sy,{...e,wide:P,triggerRef:N,swap:T,open:y==="all",onOpenChange:X("all"),close:()=>I(null)},"all"),ge=P?[Le,s.jsx("span",{className:"fb-divider","aria-hidden":!0},"divider"),s.jsxs("div",{className:"fb-facets",children:[s.jsx(va,{facet:"project",name:"Project",value:ee.project,count:ee.projectN,paused:C,swap:T,open:y==="project",onOpenChange:X("project"),onReset:()=>a([]),children:s.jsx(Rm,{apiKey:t,selectedProjects:n,onProjectsChange:a,variant:"list"})}),s.jsx(va,{facet:"label",name:"Label",value:ee.label,count:ee.labelN,paused:C,swap:T,open:y==="label",onOpenChange:X("label"),onReset:()=>o([]),children:s.jsx(Im,{apiKey:t,selectedLabels:r,onLabelsChange:o,variant:"list"})}),s.jsx(va,{facet:"priority",name:"Priority",value:ee.priority,count:ee.priorityN,paused:C,swap:T,open:y==="priority",onOpenChange:X("priority"),onReset:()=>l([]),children:s.jsx(Am,{selectedPriorities:c,onPrioritiesChange:l,variant:"list"})}),s.jsx(va,{facet:"date",name:"Date",value:ee.date,count:ee.date?1:0,paused:C,swap:T,open:y==="date",onOpenChange:X("date"),onReset:()=>m("all"),children:s.jsx(Zi,{value:d,onValueChange:m,variant:"list",onPicked:()=>I(null)})}),ee.subtasks&&s.jsxs("div",{className:"fb-pill fb-subtasks is-on",children:[s.jsx("span",{className:"fb-pill-in",children:"Subtasks hidden"}),s.jsx("button",{type:"button",className:"fb-x","aria-label":"Show subtasks",onClick:()=>f(!1),children:s.jsx(Ie,{})})]})]}
11,"facets"),s.jsx("span",{className:"fb-spacer"},"spacer"),s.jsx("button",{type:"button",className:"fb-link fb-clear",onClick:ce,children:"Clear all"},"clear"),he]:[Le,he],Te=s.jsx("div",{className:S("fb-root fb-row-group matrix-filters",P?"fb-bar":"fb-compact"),"data-phase":K,"data-enter":A??void 0,role:"group","aria-label":"Filters","aria-busy":p||void 0,children:ge}),[De]=i.useState(()=>{const se=document.createElement("div");return se.className="fb-host",se}),re=i.useRef(null);return i.useLayoutEffect(()=>{const se=k??re.current;se&&De.parentNode!==se&&se.appendChild(De)},[k,De]),i.useEffect(()=>()=>De.remove(),[De]),s.jsxs(s.Fragment,{children:[Ii.createPortal(Te,De),!k&&s.jsx("div",{ref:re,className:"fb-inline"})]})},va=({facet:e,name:t,value:n,count:a,paused:r,swap:o,open:c,onOpenChange:l,onReset:d,children:m})=>{const u=!!n,f=sc(n),{triggerRef:p,virtualRef:h,freeze:g}=ec("start"),b=tc(c&&!r);return s.jsxs(Zn,{open:c&&!r,onOpenChange:x=>{x&&g(),l(x)},children:[s.jsx(kr,{virtualRef:h}),s.jsxs("div",{ref:f,className:S("fb-pill fb-facet",`fb-${e}`,u&&"is-on",r&&"is-paused"),title:r?by:u?`${t}: ${n}`:void 0,children:[s.jsx(jr,{asChild:!0,children:s.jsxs("button",{ref:p,type:"button",disabled:r,"aria-label":u?`${t} filter: ${n}`:`${t} filter`,children:[s.jsx("span",{className:"fb-name",children:t}),u?s.jsx(xy,{text:n,size:a,className:"fb-value"}):s.jsx(mt,{className:"fb-chev fb-icon-in","aria-hidden":!0})]})}),u&&s.jsx("button",{type:"button",className:"fb-x fb-icon-in",disabled:r,"aria-label":`Remove ${t.toLowerCase()} filter`,onClick:d,children:s.jsx(Ie,{})})]}),s.jsx(ea,{children:s.jsx(mn,{className:S("fb-root fb-pop",`fb-pop-${e}`),align:"start",...nc(o,b),children:m})})]})},ky=e=>{const t=e.presets.find(u=>u.id===e.selectedPresetId)??null,n=e.selectedTodoistFilter,a=!!t||!!n,r=n?n.name:t?t.name:"Saved",o=sc(r),{triggerRef:c,virtualRef:l,freeze:d}=ec("start"),m=tc(e.open);return s.jsxs(Zn,{open:e.open,onOpenChange:u=>{u&&d(),e.onOpenChange(u)},children:[s.jsx(kr,{virtualRef:l}),s.jsxs("div",{ref:o,className:S("fb-pill fb-saved",n&&"fb-project is-on"),title:a?r:void 0,children:[s.jsx(jr,{asChild:!0,children:s.jsxs("button",{ref:c,type:"button","aria-label":a?`Saved filter: ${r}`:"Saved filters",children:[n&&s.jsx(Mi,{"aria-hidden":!0}),t?.is_default&&s.jsx(Yt,{className:"fb-star","aria-hidden":!0}),s.jsx("span",{className:S(a?"fb-value":"fb-name","fb-label-in"),children:r},r),!a&&s.jsx(mt,{className:"fb-chev fb-icon-in","aria-hidden":!0})]})}),a&&s.jsx("button",{type:"button",className:"fb-x fb-icon-in","aria-label":"Clear saved filter",onClick:e.onClearSelection,children:s.jsx(Ie,{})})]}),s.jsx(ea,{children:s.jsx(mn,{className:"fb-root fb-pop fb-pop-saved",align:"start",...nc(!!e.swap,m),children:s.jsx(jy,{...e})})})]})},ar=e=>e.filter(t=>!t.builtIn),jy=e=>{const t=o=>()=>{e.close(),o()},n=ar(e.presets),a=e.presets.filter(o=>o.builtIn),r=o=>{const c=o.id===e.selectedPresetId;return s.jsxs("button",{type:"button",className:S("fb-saved-row",c&&"is-on"),"aria-pressed":c,onClick:t(()=>e.onSelectPreset(o.id)),children:[s.jsxs("div",{className:"fb-saved-name",children:[s.jsxs("span",{children:[o.is_default&&s.jsx(Yt,{className:"fb-star","aria-label":"Default"}),s.jsx("span",{className:"truncate",children:o.name})]}),c&&s.jsx(Oe,{className:"text-primary","aria-hidden":!0})]}),s.jsx("div",{className:"mt-1",children:s.jsx(Po,{projects:o.projects,labels:o.labels,priorities:o.priorities,dateFilter:o.date_filter,hideSubtasks:o.hide_subtasks??!1,projectNames:e.projectNames,size:"sm"})})]},o.id)};return s.jsxs("div",{children:[n.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fb-phead",children:s.jsx("span",{children:"Your presets"})}),n.map(r)]}),a.length>0&&s.jsxs(s.Fragment,{children:[n.length>0&&s.jsx("div",{className:"fb-sep"}),s.jsx("div",{className:"fb-phead",children:s.jsx("span",{children:"Built in"})}),a.map(r)]}),e.todoistFilters.length>0&&s.jsxs(s.Fragment,{children:[e.presets.length>0&&s.jsx("div",{className:"fb-sep"}),s.jsx("div",{className:"fb-phead",children:s.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[s.jsx(Mi,{className:"h-3 w-3","aria-hidden":!0}),"From Todoist"]})}),e.todoistFilters.map(o=>{const c=o.id===e.selectedTodoistFilter?.id;return s.jsxs("button",{type:"button",className:S("fb-saved-row",c&&"is-on"),"aria-pressed":c,onClick:t(()=>e.onSelectTodoistFilter(c?null:o)),children:[s.jsxs("div",{className:"fb-saved-name",children:[s.jsx("span",{className:"truncate",children:o.name}),c&&s.jsx(Oe,{className:"text-primary","aria-hidden":!0})]}),o.query&&s.jsx("div",{className:"fb-query",children:o.query})]},o.id)})]}),n.length===0&&e.todoistFilters.length===0&&!e.todoistFiltersError&&s.jsx("div",{className:"fb-empty",children:"Set some filters, then save them here."}),e.todoistFiltersError&&s.jsx("div",{className:"fb-note",children:"Couldn't load your Todoist filters. They'll be retried automatically."}),s.jsx("div",{className:"fb-sep"}),s.jsx(Ny,{...e})]})},Om=e=>{const t=e.presets.find(a=>a.id===e.selectedPresetId),n=e.selectedTodoistFilter?"Presets save local filters;
11 clear the Todoist filter first":t?`Already saved as “${t.name}”`:e.hasActiveFilters?void 0:"Pick some filters first";return s.jsxs("button",{type:"button",className:S(e.primary?"fb-save":void 0),disabled:!!n,title:n,onClick:()=>{e.close(),e.onSaveCurrent()},children:[s.jsx(Pp,{"aria-hidden":!0}),"Save as preset"]})},Ny=e=>s.jsxs("div",{className:"fb-foot",children:[s.jsx(Om,{...e}),ar(e.presets).length>0&&s.jsx("button",{type:"button",onClick:()=>{e.close(),e.onManage()},children:"Manage"})]}),Sy=e=>{const t=!!e.selectedTodoistFilter,{triggerRef:n,virtualRef:a,freeze:r}=ec("end"),o=tc(e.open),c=e.wide?"All filters":"Filters",l=sc(c);return s.jsxs(Zn,{open:e.open,onOpenChange:d=>{d&&r(),e.onOpenChange(d)},children:[s.jsx(kr,{virtualRef:a}),s.jsx("div",{ref:l,className:"fb-pill fb-all-btn",children:s.jsx(jr,{asChild:!0,children:s.jsxs("button",{ref:d=>{n.current=d,e.triggerRef.current=d},type:"button","aria-label":c,children:[s.jsx(ta,{"aria-hidden":!0}),s.jsx("span",{className:"fb-name fb-label-in",children:c},c)]})})}),s.jsx(ea,{children:s.jsx(mn,{className:"fb-root fb-pop fb-pop-all",align:"end",...nc(!!e.swap,o),onOpenAutoFocus:wy,children:s.jsxs("div",{className:"fb-all",children:[s.jsxs("div",{className:"fb-all-saved",children:[s.jsxs("div",{className:"fb-all-head",children:[s.jsx("span",{className:"fb-h",children:"Saved"}),ar(e.presets).length>0&&s.jsx("button",{type:"button",className:"fb-link fb-link-sm",onClick:()=>{e.close(),e.onManage()},children:"Manage"})]}),e.presets.length>0&&s.jsx("div",{className:"fb-chips fb-project",role:"group","aria-label":"Presets",children:e.presets.map(d=>s.jsxs("button",{type:"button",className:"fb-chip is-preset","aria-pressed":d.id===e.selectedPresetId,onClick:()=>e.onSelectPreset(d.id),children:[d.is_default&&s.jsx(Yt,{className:"fb-star mr-1 inline h-3 w-3 align-[-1px]","aria-label":"Default"}),d.name]},d.id))}),e.todoistFilters.length>0&&s.jsxs("div",{className:"fb-chips fb-project",role:"group","aria-label":"From Todoist",children:[s.jsxs("span",{className:"fb-freq-label inline-flex items-center gap-1",children:[s.jsx(Mi,{className:"h-3 w-3","aria-hidden":!0}),"From Todoist"]}),e.todoistFilters.map(d=>s.jsx("button",{type:"button",className:"fb-chip","aria-pressed":d.id===e.selectedTodoistFilter?.id,title:d.query||d.name,onClick:()=>e.onSelectTodoistFilter(d.id===e.selectedTodoistFilter?.id?null:d),children:d.name},d.id))]}),ar(e.presets).length===0&&e.todoistFilters.length===0&&!e.todoistFiltersError&&s.jsx("div",{className:"fb-note",children:"Pick some filters below, then save them as a preset."}),e.todoistFiltersError&&s.jsx("div",{className:"fb-note",children:"Couldn't load your Todoist filters. They'll be retried automatically."})]}),s.jsx("div",{className:S("fb-notice-wrap",t&&"is-open"),"aria-hidden":!t||void 0,children:s.jsx("div",{className:"fb-notice-clip",children:s.jsxs("div",{className:"fb-notice",children:["Showing tasks from the Todoist filter ",s.jsx("b",{children:e.selectedTodoistFilter?.name}),". Local filters are paused while it's active."]})})}),s.jsxs("div",{className:S(t&&"fb-paused"),"aria-disabled":t||void 0,...t?{inert:""}:{},children:[s.jsx("div",{className:"fb-all-date",children:s.jsx(Zi,{value:e.dateFilter,onValueChange:e.onDateFilterChange,variant:"chips"})}),s.jsxs("div",{className:"fb-cols",children:[s.jsx("div",{className:"fb-col-list",children:s.jsx(Rm,{apiKey:e.apiKey,selectedProjects:e.selectedProjects,onProjectsChange:e.onProjectsChange,variant:"chips"})}),s.jsx("div",{className:"fb-col-list",children:s.jsx(Im,{apiKey:e.apiKey,selectedLabels:e.selectedLabels,onLabelsChange:e.onLabelsChange,variant:"chips"})}),s.jsx("div",{children:s.jsx(Am,{selectedPriorities:e.selectedPriorities,onPrioritiesChange:e.onPrioritiesChange,variant:"chips"})})]})]}),s.jsxs("div",{className:"fb-all-foot",children:[s.jsxs("label",{htmlFor:"fb-hide-subtasks",children:[s.jsx(Wn,{id:"fb-hide-subtasks",checked:e.hideSubtasks,onCheckedChange:e.onHideSubtasksChange}),"Hide subtasks"]}),s.jsxs("div",{className:"fb-all-actions",children:[s.jsx("button",{type:"button",className:S("fb-link fb-clear-panel",!(e.hasActiveFilters||t)&&"is-idle"),tabIndex:e.hasActiveFilters||t?void 0:-1,"aria-hidden":!(e.hasActiveFilters||t)||void 0,onClick:()=>{e.close(),e.onClearAll()},children:"Clear all"}),s.jsx(Om,{...e,primary:!0})]})]})]})})})]})};let rr="All tasks";const Fo=new Set,cl=e=>
11{e!==rr&&(rr=e,Fo.forEach(t=>t()))},Cy=e=>(Fo.add(e),()=>Fo.delete(e)),fT=()=>i.useSyncExternalStore(Cy,()=>rr,()=>rr),Ty=e=>{if(!e.length)return"All tasks";const t=e.slice(0,2).join(", ");return e.length>2?`${t} +${e.length-2}`:t},_y={},Ey="https://ylandon.gumroad.com",Dy=_y??{},ac=Dy.VITE_GUMROAD_YEARLY_ENABLED==="true",ll=e=>e===null?null:`$${(e/100).toFixed(2)}`,lt={lifetime:{plan:"lifetime",permalink:"ujjsu",recurrence:null,priceCents:1990,price:ll(1990)},monthly:{plan:"monthly",permalink:"uxeju",recurrence:null,priceCents:499,price:ll(499)},yearly:{plan:"yearly",permalink:"uxeju",recurrence:"yearly",priceCents:null,price:null}},Ry=(e=ac)=>e?["lifetime","monthly","yearly"]:["lifetime","monthly"],hT=(e=ac)=>Ry(e)[0],Iy="checkout_ticket";function pT(e,t={}){const n=lt[e],a=new URL(`${Ey}/l/${n.permalink}`);return a.searchParams.set("wanted","true"),n.recurrence&&a.searchParams.set("recurrence",n.recurrence),t.ticket&&a.searchParams.set(Iy,t.ticket),t.email&&a.searchParams.set("email",t.email),a.toString()}const My=2,Ly=e=>{if(e)return e.is_lifetime_purchase===!0||e.subscription_type==="lifetime"?"paid":e.payment_status==="paid"&&Mr(e)?"expired":e.payment_status??void 0},Ay=e=>e?e.is_lifetime_purchase===!0||e.subscription_type==="lifetime"?"lifetime":e.payment_status==="paid"&&e.subscription_type==="monthly"&&!Mr(e)?"membership":null:null,$m=e=>e==="trial"||e==="expired",Pr=(e,t)=>e==="trial"&&typeof t=="number"&&t<=My,Fm=e=>e==="lifetime"?"Lifetime":e==="membership"?ac?"Subscription":"Monthly":null,rc="https://app.gumroad.com/library",qm="billing:nudge-dismissed",Py=()=>{try{return window.sessionStorage.getItem(qm)==="1"}catch{return!1}},Oy=()=>{try{window.sessionStorage.setItem(qm,"1")}catch{}},zm=(e,t)=>`billing:activated-shown:${e}:${t}`,gT=(e,t)=>{try{return window.localStorage.getItem(zm(e,t))!==null}catch{return!1}},xT=(e,t)=>{try{window.localStorage.setItem(zm(e,t),String(Date.now()))}catch{}},dl={minimized:!1,nudgeReopened:!1};function $y(e){return e.paymentStatus!=="trial"||e.trialEnded?{view:"hidden",reopen:!1}:e.onboarding?{view:"minimized",reopen:!1}:e.prefs.minimized?Pr(e.paymentStatus,e.daysLeft)&&!e.prefs.nudgeReopened?{view:"expanded",reopen:!0}:{view:"minimized",reopen:!1}:{view:"expanded",reopen:!1}}const Fy=(e,t)=>({minimized:!0,nudgeReopened:e.nudgeReopened||Pr("trial",t)}),ul=(e,t=!1)=>({minimized:!1,nudgeReopened:e.nudgeReopened||t}),Um=e=>`billing:trial-plans:${e||"anon"}`,ml=e=>{try{const t=window.localStorage.getItem(Um(e));if(!t)return{...dl};const n=JSON.parse(t);return{minimized:n?.minimized===!0,nudgeReopened:n?.nudgeReopened===!0}}catch{return{...dl}}},Xr=(e,t)=>{try{window.localStorage.setItem(Um(e),JSON.stringify(t))}catch{}},On=[{id:"do",label:"Do First",meaning:"Urgent and important"},{id:"schedule",label:"Schedule",meaning:"Important, not urgent"},{id:"delegate",label:"Delegate",meaning:"Urgent, not important"},{id:"backlog",label:"Backlog",meaning:"Neither urgent nor important"}],qy=(e,t)=>Pr(e,t),Bm="mobile-quadrant",zy=e=>e==="do"||e==="schedule"||e==="delegate"||e==="backlog",Uy=()=>{try{const e=window.localStorage.getItem(Bm);return zy(e)?e:"do"}catch{return"do"}},By=e=>{try{window.localStorage.setItem(Bm,e)}catch{}},Zr=new Map,Pe=gr((e,t)=>({quadrant:typeof window>"u"?"do":Uy(),counts:{do:0,schedule:0,delegate:0,backlog:0},countsKnown:!1,activeFilterCount:0,clearFilters:null,projectNames:{},filterSheetOpen:!1,accountSheetOpen:!1,accountShowsPlans:!1,setQuadrant:n=>{t().quadrant!==n&&(By(n),e({quadrant:n}))},setCounts:n=>{const a=t().counts;if(!t().countsKnown){e({counts:n,countsKnown:!0});return}a.do===n.do&&a.schedule===n.schedule&&a.delegate===n.delegate&&a.backlog===n.backlog||e({counts:n})},setFilterState:(n,a)=>e({activeFilterCount:n,clearFilters:a}),setProjectNames:n=>e({projectNames:n}),setFilterSheetOpen:n=>e({filterSheetOpen:n}),openAccountSheet:n=>e({accountSheetOpen:!0,accountShowsPlans:!!n?.plans}),closeAccountSheet:()=>e({accountSheetOpen:!1})})),Hy=()=>{try{return window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{return!1}},Gn=e=>{const{quadrant:t,setQuadrant:n}=Pe.getState();if(e===t){window.scrollTo({top:0,behavior:Hy()?"auto":"smooth"}),Zr.set(e,0);return}Zr.set(t,window.scrollY),n(e);const a=Zr.get(e)??0;requestAnimationFrame(()=>window.scrollTo({top:a,behavior:"auto"}))},eo="stale-chunk-reloaded";let Hm=!1;const Vy=()=>Hm,Ky=e=>{const t=e instanceof Error?e.message:String(e??"");return/dynamically imported module|Importing a module script failed|Loading chunk/i.test(t)},Yy=()=>{window.addEventListener("vite:preloadError",e=>{let t=!1;try{t=sessionStorage.getItem(eo)==="1"}catch{}if(!t){e.preventDefault(),Hm=!0;try{sessionStorage.setItem(eo,"1")}catch{}window.location.reload()}});try{sessionStorage.removeItem(eo)}catch{}},Vm=new Set;let fl=!1;function gn(e,t=null){let n,a;const r=()=>a??=e().then(l=>(n=l,{default:l}),l=>{if(a=void 0,Vy())return new Promise(()=>{});throw l}),o=i.lazy(r);function c(l){const[d]=i.useState(()=>n);return d?i.createElement(d,l):s.jsx(i.Suspense,{fallback:t,children:i.createElement(o,l)})}return Vm.add(r),Object.assign(c,{preload:r})}function Km(e){const[t,n]=i.useState(e);return e&&!t&&n(!0),t||e}function Ps(e,t,n=null){const a=gn(e,n);function r(o){return Km(t(o))?i.createElement(a,o):null}return Object.assign(r,{preload:a.preload})}function Wy(){if(fl||typeof window>"u")return;fl=!0;const e=()=>{for(const n of Vm)n().catch(()=>{})},t=()=>{typeof window.requestIdleCallback=="function"?window.requestIdleCallback(e,{timeout:3e3}):window.setTimeout(e,200)};document.readyState==="complete"?t():window.addEventListener("load",t,{once:!0})}const Gy=Ps(()=>Ne(()=>import("./MobileFilterSheet-CD03krW8.js"),__vite__mapDeps([5,1,2,3,4])).then(e=>e.MobileFilterSheet),e=>e.open),Qy=({apiKey:e,selectedLabels:t,onLabelsChange:n,selectedProjects:a,onProjectsChange:r,dateFilter:o,onDateFilterChange:c,selectedPriorities:l,onPrioritiesChange:d,isPending:m,selectedTodoistFilter:u,onSelectTodoistFilter:f,hideSubtasks:p,onHideSubtasksChange:h})=>{const{presets:g,savePreset:b,deletePreset:x,renamePreset:y,setDefaultPreset:w,movePreset:k}=Qb(),N=Ue.useMemo(()=>[...g,...Gb],[g]),{filters:C,isError:v}=Jb(e),{projects:j}=Ji(e),{toast:T}=He(),_=Fe(),[I,R]=i.useState(!1),[M,P]=i.useState(""),[E,D]=i.useState(!1),L=!!u,[A,H]=i.useState(null),[K,X]=i.useState(""),ce=Ue.useMemo(()=>{const q={};
11return j.forEach(xe=>{q[xe.id]=xe.is_inbox_project?"Inbox":xe.name}),q},[j]),oe=Pe(q=>q.filterSheetOpen),ve=Pe(q=>q.setFilterSheetOpen),Ce=Pe(q=>q.setFilterState),ee=Pe(q=>q.setProjectNames),Le=Pe(q=>q.counts.do+q.counts.schedule+q.counts.delegate+q.counts.backlog),[he,ge]=i.useState(null),Te=()=>n([]),De=()=>r([]),re=()=>c("all"),se=()=>{Te(),De(),re(),d([]),ge(null),u&&f(null),h(!1)},ue=q=>{ge(null),f(q)};i.useEffect(()=>{if(!m||_)return;const q=document.documentElement,xe=window.setTimeout(()=>q.classList.add("fb-filtering"),250);return()=>{window.clearTimeout(xe),q.classList.remove("fb-filtering")}},[m,_]);const Qe=t.length>0||a.length>0||o!=="all"||l.length>0||p,$=N.find(q=>q.id===he)??null,O=u?u.name:$?$.name:Ty([...a.map(q=>ce[q]??q),...t.map(Jt),...[...l].sort((q,xe)=>xe-q).map(q=>`P${5-q}`),...o!=="all"?[sr(o)]:[]]);i.useEffect(()=>{cl(O)},[O]);const F=(a.length>0?1:0)+(t.length>0?1:0)+(l.length>0?1:0)+(o!=="all"?1:0)+(p?1:0)+(u?1:0),Q=i.useRef(()=>{});Q.current=se,i.useEffect(()=>{Ce(F,F?()=>Q.current():null)},[F,Ce]),i.useEffect(()=>{_&&ee(ce)},[_,ce,ee]),i.useEffect(()=>()=>cl("All tasks"),[]);const V=i.useRef(null),G=(q,xe)=>{L&&f(null),V.current=q.id,r(q.projects),n(q.labels),d(q.priorities),c(q.date_filter),h(q.hide_subtasks??!1),xe?.silent||T({title:`Preset “${q.name}” applied`})},Y=q=>{if(q===he){se();return}ge(q);const xe=N.find(ke=>ke.id===q);xe&&G(xe)},J=()=>{if(u&&ue(null),he){se();return}ge(null)},le=i.useRef(!1);i.useEffect(()=>{if(le.current||g.length===0)return;le.current=!0;const q=g.find(xe=>xe.is_default);q&&!Qe&&(ge(q.id),G(q,{silent:!0}))},[g]);const U=async()=>{if(!M.trim())return;const q=await b({name:M.trim(),projects:a,labels:t,priorities:l,date_filter:o,hide_subtasks:p});q&&(ge(q.id),T({title:"Preset saved",description:q.name})),P(""),R(!1)};i.useEffect(()=>{if(!he)return;const q=N.find(ke=>ke.id===he);if(!q)return;if(!(JSON.stringify(q.projects)!==JSON.stringify(a)||JSON.stringify(q.labels)!==JSON.stringify(t)||JSON.stringify(q.priorities)!==JSON.stringify(l)||q.date_filter!==o||(q.hide_subtasks??!1)!==p)){V.current===he&&(V.current=null);return}V.current!==he&&ge(null)},[a,t,l,o,p]);const ne=s.jsxs(s.Fragment,{children:[s.jsx(Xa,{open:I,onOpenChange:R,children:s.jsxs(Za,{className:"sm:max-w-[420px]",children:[s.jsxs(Lo,{className:"text-left",children:[s.jsxs(er,{className:"flex items-center gap-2 text-lg",children:[s.jsx(Lc,{className:"h-5 w-5 text-primary"}),"Save as preset"]}),s.jsx(tr,{children:"Give this combination a name so you can reapply it any time."})]}),s.jsxs("div",{className:"space-y-4 py-2",children:[s.jsx(Yn,{autoFocus:!0,placeholder:"e.g. Urgent work this week",value:M,onChange:q=>P(q.target.value),onKeyDown:q=>{q.key==="Enter"&&M.trim()&&U()}}),s.jsxs("div",{className:"rounded-xl border border-border/60 bg-muted/30 p-3",children:[s.jsx("div",{className:"mb-2 text-[11px] font-medium uppercase tracking-wide text-muted-foreground",children:"This preset will capture"}),s.jsx(Po,{projects:a,labels:t,priorities:l,dateFilter:o,hideSubtasks:p,projectNames:ce,size:"md",emptyText:"No filters yet, this preset would match everything"})]})]}),s.jsxs(km,{children:[s.jsx(W,{variant:"ghost",onClick:()=>R(!1),children:"Cancel"}),s.jsx(W,{onClick:U,disabled:!M.trim(),children:"Save preset"})]})]})}),s.jsx(Xa,{open:E,onOpenChange:D,children:s.jsxs(Za,{className:"sm:max-w-[460px]",children:[s.jsxs(Lo,{children:[s.jsxs(er,{className:"flex items-center gap-2 text-lg",children:[s.jsx(Op,{className:"h-5 w-5 text-muted-foreground"}),"Your presets"]}),s.jsx(tr,{children:"Apply, rename, reorder, set a default, or remove your presets. The default is applied automatically when you open the app."})]}),s.jsxs("div",{className:"space-y-2 max-h-[360px] overflow-y-auto pr-1",children:[g.length===0&&s.jsxs("div",{className:"flex flex-col items-center gap-2 rounded-xl border border-dashed border-border/60 py-8 text-center",children:[s.jsx("span",{className:"flex h-10 w-10 items-center justify-center rounded-full bg-muted",children:s.jsx(Lc,{className:"h-5 w-5 text-muted-foreground"})}),s.jsx("p",{className:"text-sm font-medium",children:"No presets yet"}),s.jsx("p",{className:"text-xs text-muted-foreground px-6",children:"Set up some filters and choose “Save as preset” to create your first preset."})]}),g.map((q,xe)=>{const ke=q.id===he,We=A===q.id,Ze=()=>{K.trim()&&y(q.id,K),H(null)};return s.jsxs("div",{className:S("flex items-start gap-2 rounded-xl border px-2.5 py-2.5 transition-colors",ke?"border-primary/30 bg-primary/5":"border-border/60 hover:bg-muted/40"),children:[s.jsxs("div",{className:"flex flex-col -my-1 shrink-0",children:[s.jsx(W,{variant:"ghost",size:"icon",className:"h-5 w-5 text-muted-foreground disabled:opacity-30",disabled:xe===0,title:"Move up",onClick:()=>k(q.id,"up"),children:s.jsx(fu,{className:"h-3.5 w-3.5"})}),s.jsx(W,{variant:"ghost",size:"icon",className:"h-5 w-5 text-muted-foreground disabled:opacity-30",disabled:xe===g.length-1,title:"Move down",onClick:()=>k(q.id,"down"),children:s.jsx($p,{className:"h-3.5 w-3.5"})})]}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"flex items-center gap-1.5",children:We?s.jsx(Yn,{autoFocus:!0,value:K,onChange:de=>X(de.target.value),onBlur:Ze,onKeyDown:de=>{de.key==="Enter"&&Ze(),de.key==="Escape"&&H(null)},className:"h-7 text-sm"}):s.jsxs(s.Fragment,{children:[q.is_default&&s.jsx(Yt,{className:"h-3.5 w-3.5 shrink-0 fill-amber-400 text-amber-400"}),s.jsx("span",{className:"text-sm font-medium truncate",children:q.name}),ke&&s.jsx("span",{className:"text-[10px] font-semibold text-primary bg-primary/10 rounded-full px-1.5 py-0.5",children:"Active"})]})}),!We&&s.jsx("div",{className:"mt-1.5",children:s.jsx(Po,{projects:q.projects,labels:q.labels,priorities:q.priorities,dateFilter:q.date_filter,hideSubtasks:q.hide_subtasks??!1,projectNames:ce,size:"sm"})})]}),s.jsxs("div",{className:"flex items-center gap-0.5 shrink-0",children:[s.jsx(W,{variant:"ghost",size:"icon",className:S("h-8 w-8",q.is_default?"text-amber-500":"text-muted-foreground hover:text-amber-500"),title:q.is_default?"Remove as default":"Set as default",onClick:()=>w(q.id),children:s.jsx(Yt,{className:S("h-4 w-4",q.is_default&&"fill-amber-400")})}),s.jsx(W,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground hover:text-foreground",title:"Rename",onClick:()=>{H(q.id),X(q.name)}
11,children:s.jsx(hu,{className:"h-3.5 w-3.5"})}),s.jsx(W,{variant:"ghost",size:"sm",className:"h-8 text-xs",onClick:()=>{Y(q.id),D(!1)},children:"Apply"}),s.jsx(W,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground hover:text-destructive",title:`Delete “${q.name}”`,onClick:()=>{he===q.id&&ge(null),x(q.id)},children:s.jsx(Is,{className:"h-4 w-4"})})]})]},q.id)})]})]})})]});if(!_)return s.jsxs(s.Fragment,{children:[s.jsx(vy,{apiKey:e,selectedProjects:a,onProjectsChange:r,selectedLabels:t,onLabelsChange:n,selectedPriorities:l,onPrioritiesChange:d,dateFilter:o,onDateFilterChange:c,hideSubtasks:p,onHideSubtasksChange:h,isPending:m,hasActiveFilters:Qe,presets:N,selectedPresetId:he,onSelectPreset:Y,todoistFilters:C,todoistFiltersError:v,selectedTodoistFilter:u,onSelectTodoistFilter:ue,onClearSelection:J,onClearAll:se,onSaveCurrent:()=>R(!0),onManage:()=>D(!0),projectNames:ce}),ne]});const me=[u?.name,$&&!u?$.name:null,a.map(q=>ce[q]??q).join(", "),t.map(Jt).join(", "),[...l].sort((q,xe)=>xe-q).map(q=>`P${5-q}`).join(", "),o!=="all"?sr(o):null,p?"No subtasks":null].filter(Boolean).join(" · ");return s.jsxs("div",{className:"matrix-filters",children:[F>0&&s.jsxs("div",{className:"mx-active-filters",children:[s.jsxs("button",{type:"button",className:"mx-active-filters-line",onClick:()=>ve(!0),children:[s.jsx(ta,{className:"h-4 w-4 shrink-0 text-muted-foreground","aria-hidden":!0}),s.jsx("span",{className:"truncate",children:me})]}),s.jsx("button",{type:"button",className:"mx-active-filters-clear",onClick:se,children:"Clear"})]}),s.jsx(Gy,{open:oe,onOpenChange:ve,apiKey:e,isPending:m,selectedProjects:a,onProjectsChange:r,selectedLabels:t,onLabelsChange:n,selectedPriorities:l,onPrioritiesChange:d,dateFilter:o,onDateFilterChange:c,hideSubtasks:p,onHideSubtasksChange:h,presets:N,selectedPresetId:he,onSelectPreset:Y,todoistFilters:C,todoistFiltersError:v,selectedTodoistFilter:u,onSelectTodoistFilter:ue,onClearSaved:J,activeFacetCount:F,onClearAll:se,onSaveCurrent:()=>R(!0),onManage:()=>{ve(!1),D(!0)},projectNames:ce,resultCount:Le}),ne]})},Jy=(e,t,n,a)=>({quadrants:i.useMemo(()=>[{title:"Do First",description:"Urgent and Important - Complete these tasks immediately",tasks:e,type:"urgent-important",droppableId:"do",isMainQuadrant:!0},{title:"Schedule",description:"Important, Not Urgent - Plan and schedule these tasks",tasks:t,type:"important",droppableId:"schedule"},{title:"Delegate",description:"Urgent, Not Important - Find someone to handle these tasks",tasks:n,type:"urgent",droppableId:"delegate"},{title:"Backlog",description:"Neither Urgent nor Important - Review these tasks periodically",tasks:a,type:"neither",droppableId:"backlog"}],[e,t,n,a])}),Ym=async(e,t)=>{},Wm=e=>{const{session:t}=we.useSessionContext(),{toast:n}=He(),[a,r]=i.useState(()=>{const c=localStorage.getItem("focus-session-state");
11return c?JSON.parse(c):{sessionId:null,startTime:null,completedTasks:0}});i.useEffect(()=>{localStorage.setItem("focus-session-state",JSON.stringify(a))},[a]),i.useEffect(()=>{(async()=>{if(!t?.user?.id||!a.sessionId)return;const{error:l,count:d}=await B.from("task_completions").select("id",{count:"exact",head:!0}).eq("user_id",t.user.id).eq("focus_session_id",a.sessionId);if(l)return;const m=d||0;r(u=>({...u,completedTasks:m}))})()},[a.sessionId,t?.user?.id]),i.useEffect(()=>{(async()=>{if(t?.user?.id)try{if(e&&!a.sessionId){const l=new Date,{data:d,error:m}=await B.from("focus_sessions").insert({user_id:t.user.id,started_at:l.toISOString()}).select().single();if(m)throw m;r({sessionId:d.id,startTime:l.toISOString(),completedTasks:0})}else if(!e&&a.sessionId){const l=new Date;if(a.startTime){const d=new Date(a.startTime),m=Math.round((l.getTime()-d.getTime())/6e4),{error:u}=await B.from("focus_sessions").update({ended_at:l.toISOString(),duration_minutes:m}).eq("id",a.sessionId);if(u)throw u;const{data:f}=await B.from("user_goals").select("*").eq("user_id",t.user.id).eq("goal_type","daily_focus_time");if(f&&f.length>0){const p=new Date;p.setHours(0,0,0,0);const{data:h}=await B.from("focus_sessions").select("duration_minutes").eq("user_id",t.user.id).gte("started_at",p.toISOString()).lt("started_at",new Date(p.getTime()+1440*60*1e3).toISOString()),g=(h||[]).reduce((b,x)=>b+(x.duration_minutes||0),0);for(const b of f)g>=b.target_value&&await Ym(B,[b])}}
11r({sessionId:null,startTime:null,completedTasks:0})}}catch{n({title:"Error",description:"Failed to manage focus session",variant:"destructive"})}})()},[e,t?.user?.id,a.sessionId,a.startTime,a.completedTasks,n]);const o=()=>{r(c=>({...c,completedTasks:c.completedTasks+1}))};return{focusStartTime:a.startTime?new Date(a.startTime):null,completedTasksInSession:a.completedTasks,incrementCompletedTasks:o}},oc="focus-session-start-time",or="focus-timer-paused",ir="focus-timer-paused-at",ic="focus-timer-total-paused",Xy=12*36e5;function to(){try{const e=localStorage.getItem(oc);if(e){const t=new Date(e);if(!isNaN(t.getTime())&&Date.now()-t.getTime()<Xy)return t}}catch{}return null}function hl(e){try{localStorage.setItem(oc,e.toISOString())}catch{}}function sn(){try{localStorage.removeItem(oc),localStorage.removeItem(or),localStorage.removeItem(ir),localStorage.removeItem(ic),localStorage.removeItem("focus-cycle")}catch{}}function Zy(){try{const e=localStorage.getItem(or)==="true",t=parseInt(localStorage.getItem(ir)||"0",10),n=parseInt(localStorage.getItem(ic)||"0",10);return{isPaused:e,pausedAt:t,totalPaused:n}}catch{return{isPaused:!1,pausedAt:0,totalPaused:0}}}const bT=({isTaskFocus:e})=>{const t=i.useRef(to()),n=i.useRef(Zy()),[a,r]=i.useState(()=>to()),[o,c]=i.useState(n.current.isPaused),[l,d]=i.useState(n.current.pausedAt),[m,u]=i.useState(n.current.totalPaused);i.useEffect(()=>{{const b=to();if(b)(!t.current||t.current.getTime()!==b.getTime())&&(t.current=b,r(b));else if(t.current)hl(t.current),r(t.current);else{const x=new Date;t.current=x,hl(x),r(x),c(!1),d(0),u(0)}}},[e]);const f=i.useRef({isPaused:o,pausedTime:l,totalPausedTime:m});f.current={isPaused:o,pausedTime:l,totalPausedTime:m};const p=i.useCallback(b=>{if(f.current.isPaused||!t.current)return;const x=b??Date.now();f.current={...f.current,isPaused:!0,pausedTime:x},c(!0),d(x);try{localStorage.setItem(or,"true"),localStorage.setItem(ir,x.toString())}catch{}},[]),h=i.useCallback(b=>{const{isPaused:x,pausedTime:y,totalPausedTime:w}=f.current;if(!x||y<=0)return;const k=w+Math.max(0,(b??Date.now())-y);f.current={isPaused:!1,pausedTime:0,totalPausedTime:k},u(k),c(!1),d(0);try{localStorage.setItem(or,"false"),localStorage.setItem(ir,"0"),localStorage.setItem(ic,k.toString())}catch{}},[]),g=i.useCallback((b=Date.now())=>{const x=t.current;if(!x)return 0;const{isPaused:y,pausedTime:w,totalPausedTime:k}=f.current,N=y&&w?Math.min(w,b):b;return Math.max(0,(N-x.getTime()-k)/1e3)},[]);return{sessionStartTime:a,setSessionStartTime:r,isPaused:o,pausedTime:l,pauseTimer:p,resumeTimer:h,totalPausedTime:m,focusAt:g,liveState:()=>f.current}},ka="focus-owner",so="focus-tab-id",pl="focus-owner-ping",e0="focus-owner",t0=5e3,cc=15e3,s0=500,En=(e,t,n=cc)=>!!e&&e.heartbeatAt>0&&t-e.heartbeatAt<n,gl=(e,t,n,a=cc)=>!En(e,n,a)||e.instance===t.instance||e.tabId===t.tabId?"free":"check",xl=e=>{if(!e)return null;try{const t=JSON.parse(e);if(t&&typeof t.tabId=="string"&&typeof t.instance=="string"&&typeof t.heartbeatAt=="number")return t}catch{}return null},n0=()=>{try{if(typeof crypto<"u"&&"randomUUID"in crypto)return crypto.randomUUID()}catch{}return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`};function a0(e){const t=e.newId??n0,n=t();let a=(()=>{try{const y=e.session?.getItem(so);if(y)return y;const w=t();return e.session?.setItem(so,w),w}catch{return t()}})(),r=!1,o=null;const c=new Set,l=y=>c.forEach(w=>{try{w(y)}catch{}}),d=()=>{try{return xl(e.local?.getItem(ka)??null)}catch{return null}},m=y=>{try{e.local?.setItem(ka,JSON.stringify(y))}catch{}},u=y=>{try{e.channel?.postMessage(y)}catch{}},f=()=>{o!=null&&e.clearInterval(o),o=null},p=y=>{if(r){if(r=!1,f(),y.tabId===a){a=t();try{e.session?.setItem(so,a)}catch{}}l("taken")}},h=()=>{if(!r)return;const y=d();if(y&&y.instance!==n&&En(y,e.now(),e.timing().staleMs)){p(y);return}m({tabId:a,instance:n,heartbeatAt:e.now()})},g=y=>{!y||y.instance===n||(y.type==="claimed"?r?p(y):l("claimed"):y.type==="released"?l("released"):y.type==="ping"&&r&&(h(),u({type:"alive",instance:n})))};return e.channel&&(e.channel.onmessage=y=>g(y.data)),{get tabId(){return a},instance:n,read:d,isOwner:()=>r,ownedElsewhere:()=>{if(r)return!1;const y=d();return En(y,e.now(),e.timing().staleMs)&&y.tabId!==a&&y.instance!==n},decide:()=>r?"free":gl(d(),{tabId:a,instance:n},e.now(),e.timing().staleMs),check:()=>
11{if(r)return Promise.resolve(!1);const y=d();return gl(y,{tabId:a,instance:n},e.now(),e.timing().staleMs)==="free"?Promise.resolve(!1):new Promise(w=>{let k=!1;const N=C=>{k||(k=!0,e.channel&&(e.channel.onmessage=v=>g(v.data)),w(C))};e.channel&&(e.channel.onmessage=C=>{C.data?.type==="alive"&&C.data.instance===y?.instance?N(!0):g(C.data)}),u({type:"ping",instance:n});try{e.local?.setItem(pl,`${n}:${e.now()}`)}catch{}e.setTimeout(()=>{const C=d();N(!!C&&C.instance!==n&&C.tabId!==a&&C.heartbeatAt>(y?.heartbeatAt??0)&&En(C,e.now(),e.timing().staleMs))},e.timing().pingMs)})},claim:()=>{const y=r;r=!0,m({tabId:a,instance:n,heartbeatAt:e.now()}),y||u({type:"claimed",tabId:a,instance:n}),f(),o=e.setInterval(h,e.timing().heartbeatMs)},release:()=>{if(!r)return;r=!1,f();const y=d();if(!y||y.instance===n)try{e.local?.removeItem(ka)}catch{}u({type:"released",tabId:a,instance:n})},pageHide:()=>{if(!r)return;const y=d();y&&y.instance===n&&m({...y,heartbeatAt:0})},resume:()=>{if(!r)return;const y=d();y&&y.instance!==n&&En(y,e.now(),e.timing().staleMs)?p(y):m({tabId:a,instance:n,heartbeatAt:e.now()})},onStorage:(y,w)=>{if(y===pl){r&&h();return}if(y!==ka)return;const k=xl(w);r&&k&&k.instance!==n&&k.heartbeatAt>0&&p(k)},onMessage:g,subscribe:y=>(c.add(y),()=>{c.delete(y)})}}const r0=()=>{const e=(typeof window<"u"?window.__focusOwnerTiming:void 0)??{};return{heartbeatMs:e.heartbeatMs??t0,staleMs:e.staleMs??cc,pingMs:e.pingMs??s0}},bl=e=>{try{return typeof window<"u"?window[e]:null}catch{return null}};let no=null;const Dn=()=>{if(no)return no;let e=null;try{typeof BroadcastChannel<"u"&&(e=new BroadcastChannel(e0))}catch{e=null}const t=a0({local:bl("localStorage"),session:bl("sessionStorage"),channel:e,now:()=>Date.now(),setInterval:(n,a)=>window.setInterval(n,a),clearInterval:n=>window.clearInterval(n),setTimeout:(n,a)=>window.setTimeout(n,a),timing:r0});return typeof window<"u"&&(window.addEventListener("storage",n=>t.onStorage(n.key,n.newValue)),window.addEventListener("pagehide",()=>t.pageHide()),window.addEventListener("pageshow",n=>{n.persisted&&t.resume()}),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&t.resume()})),no=t,t},jt=()=>{try{return Dn().ownedElsewhere()}catch{return!1}};let nn=null;const qo=new Set,lc=()=>qo.forEach(e=>e()),o0=e=>{nn=e,lc()},i0=()=>{nn&&(nn=null,lc())},ao=e=>{const t=nn;t&&(nn=null,lc(),e?t.onMove():t.onKeep())},c0=e=>(qo.add(e),()=>{qo.delete(e)}),l0=()=>i.useSyncExternalStore(c0,()=>nn,()=>null),yl="focus-moved",d0="Focus moved to another tab",u0=()=>{const e=()=>{xt(yl),Z(d0,{id:yl,duration:4e3})};if(document.visibilityState==="visible"){e();return}const t=()=>{document.visibilityState==="visible"&&(document.removeEventListener("visibilitychange",t),e())};document.addEventListener("visibilitychange",t)},m0=()=>{const[e,t]=i.useState(!1),[n,a]=i.useState(void 0),[r,o]=ct("has-seen-focus-instructions",!1),[c,l]=i.useState(null),[d,m]=i.useState(!1),[u,f]=i.useState(null),[p,h]=i.useState(null),g=i.useRef(!1),b=i.useRef(!1),x=i.useCallback((C,v="user")=>{const j=Dn();if(!C){j.release(),t(!1);return}if(j.isOwner()){t(!0);return}if(v==="restore"&&g.current)return;const T=()=>{g.current=!1,j.claim(),t(!0)},_=()=>o0({onMove:()=>{if(v==="restore")try{const I=JSON.parse(localStorage.getItem("task-focus-state")||"null");I?.focusedTaskId&&a(I.focusedTaskId)}catch{}T()},onKeep:()=>{g.current=!0}});if(j.decide()==="free"){T();return}b.current||(b.current=!0,j.check().then(I=>{b.current=!1,I?_():T()}))},[]);i.useEffect(()=>()=>Dn().release(),[]),i.useEffect(()=>Dn().subscribe(C=>{C==="taken"?(g.current=!0,t(!1),u0()):C==="released"&&i0()}),[]);const y=i.useRef(!1),w=i.useRef(!1),k=i.useRef(null);i.useEffect(()=>{e?y.current=!0:y.current&&!w.current&&(w.current=!0,requestAnimationFrame(()=>{const v=document.querySelectorAll(".matrix-grid");v.length>0&&(v.forEach(j=>{const T=j;document.body.contains(T)&&(T.style.transition="none",T.offsetWidth,T.style.opacity="1",T.style.filter="none",T.style.transform="none",requestAnimationFrame(()=>{T.style.transition=""}))}),y.current=!1),w.current=!1}))},[e]);const N=i.useCallback(()=>
11{if(w.current)return;w.current=!0;const C=document.querySelectorAll(".matrix-grid");C.length>0&&C.forEach(v=>{const j=v;document.body.contains(j)&&requestAnimationFrame(()=>{j.style.transition="none",j.style.opacity="1",j.style.filter="none",j.style.transform="none",j.offsetWidth,requestAnimationFrame(()=>{j.style.transition=""})})}),y.current=!1,sn(),k.current&&clearTimeout(k.current),k.current=setTimeout(()=>{Dn().release(),t(!1),a(void 0),l(null),typeof window<"u"&&(localStorage.removeItem("task-focus-state"),localStorage.removeItem("focus-timer-state"),localStorage.removeItem("focus-timer-visible")),Z.info("Focus Mode Disabled",{description:"Returning to normal view",duration:2e3}),w.current=!1},50)},[]);return{isTaskFocus:e,setIsTaskFocus:x,focusedTaskId:n,setFocusedTaskId:a,hasSeenFocusInstructions:r,setHasSeenFocusInstructions:o,focusSessionStartTime:c,setFocusSessionStartTime:l,isProcessingTaskCompletion:d,setIsProcessingTaskCompletion:m,lastCompletedTaskId:u,setLastCompletedTaskId:f,taskCompletionTimestamp:p,setTaskCompletionTimestamp:h,disableFocusMode:N}},f0=25,h0=10800*1e3,p0=e=>Math.round(e*10)/10,Gm=(e,t)=>e.map(n=>({type:n.type,start:new Date(n.start).toISOString(),minutes:p0(((n.end??t)-n.start)/6e4)})).filter(n=>n.minutes>0),Qm=e=>{let t=0,n=0,a=0,r=0;return e.forEach(o=>{o.type==="focus"?(t+=o.minutes,o.minutes>=f0&&(n+=o.minutes)):(a+=o.minutes,r+=1)}),{focus:t,deep:n,paused:a,pauses:r}},g0=(e,t)=>e.filter(n=>n.start<t).map(n=>({...n,end:n.end==null?t:Math.min(n.end,t)})),x0=(e,t,n)=>{const a=Math.max(t??e,e);return n-a>=h0?a:null},b0=(e,t,n)=>{const a=Math.max(n,t),r=Gm(g0(e,a),a);return{endedAt:a,segments:r,totals:Qm(r)}},y0=2,zo="focus-rec",w0=12*36e5,v0=3e4,Or=()=>{try{return JSON.parse(localStorage.getItem(zo)||"null")}catch{return null}},k0=()=>{const e=Or();return e&&Date.now()-Math.max(e.lastActive??0,e.startedAt)<w0?e:null},j0=e=>{try{e?localStorage.setItem(zo,JSON.stringify(e)):localStorage.removeItem(zo)}catch{}},an=()=>k0(),rs=e=>j0(e);let It=0,Qn=0;const N0=e=>Math.max(e.lastActive??e.startedAt,Qn===e.startedAt?It:0,e.startedAt),S0=()=>{const e=an();return e?{id:e.id,startedAt:e.startedAt,...Qm(Gm(e.segs,Date.now()))}:null};let wl=!0;const C0=e=>!!e&&(e.code==="PGRST204"||e.code==="42703"||/column .* does not exist|Could not find the .* column/i.test(e.message??"")),T0=async(e,t,n)=>{if(wl){const{error:r}=await B.from("focus_sessions").update({...t,...n}).eq("id",e);if(!r)return;if(!C0(r))throw r;wl=!1}const{error:a}=await B.from("focus_sessions").update(t).eq("id",e);if(a)throw a};let cr=null;const Uo=new Map,yT=e=>{if(uc(),jt())return;const t=an();if(t){e&&rs({...t,filter:e});return}const n=Date.now();pe("focus_started",{layout:Hn()});const a={id:null,userId:null,startedAt:n,segs:[{type:"focus",start:n,end:null}],filter:e??null,lastActive:n};It=n,Qn=n,rs(a),cr=(async()=>{try{const{data:{user:r}}=await B.auth.getUser();if(!r)return;const{data:o,error:c}=await B.from("focus_sessions").insert({user_id:r.id,started_at:new Date(n).toISOString()}).select("id").single();if(c)throw c;Uo.set(n,{id:o.id,userId:r.id});const l=an();l&&l.startedAt===n&&rs({...l,id:o.id,userId:r.id})}catch{}finally{cr=null}})()},Jm=(e,t)=>e.map(n=>n.end==null?{...n,end:t}:n),wT=e=>{if(jt())return;const t=an();if(!t)return;const n=t.segs[t.segs.length-1];if(n?.type==="pause"&&n.end==null)return;const a=Math.max(e??Date.now(),n?.start??0);rs({...t,segs:[...Jm(t.segs,a),{type:"pause",start:a,end:null}]})},vT=e=>{if(jt())return;const t=an();if(!t)return;const n=t.segs[t.segs.length-1];if(n?.type==="focus"&&n.end==null)return;const a=Math.max(e??Date.now(),n?.start??0);rs({...t,segs:[...Jm(t.segs,a),{type:"focus",start:a,end:null}]})},vl=(e=Date.now(),t=!1)=>{const n=Or();!n||jt()||(Qn!==n.startedAt&&(Qn=n.startedAt,It=0),It=Math.max(It,e),(t?It>(n.lastActive??0):It-(n.lastActive??n.startedAt)>=v0)&&rs({...n,lastActive:It}))},ro=()=>{const e=Or();e&&Qn===e.startedAt&&It>(e.lastActive??0)&&!jt()&&rs({...e,lastActive:It})},dc=(e=Date.now())=>{const t=Or();if(!t||jt())return null;const n=x0(t.startedAt,N0(t),e);if(n==null)return null;const a=Xm(t,n,t.filter,!0);return{endedAt:n,totals:a}},_0=e=>{if(uc(),jt())return null;const t=an();return t?Xm(t,Date.now(),e??t.filter):null},E0=1500;let $n=null;function uc(){$n!=null&&clearTimeout($n),$n=null}const kT=e=>{uc(),$n=setTimeout(()=>{$n=null,_0(e)},E0)},Xm=(e,t,n,a=!1)=>{rs(null);const{endedAt:r,segments:o,totals:c}=b0(e.segs,e.startedAt,t);return pe("focus_ended",{minutes:px(c.focus),idle:a}),(async()=>{try{cr&&await cr;const l=e.id?{id:e.id,userId:e.userId}:Uo.get(e.startedAt);Uo.delete(e.startedAt);const d=l?.id,m=l?.userId;if(!d)return;if(c.focus<y0){await B.from("task_completions").update({focus_session_id:null}).eq("focus_session_id",d),await B.from("focus_sessions").delete().eq("id",d);return}await T0(d,{ended_at:new Date(r).toISOString(),duration_minutes:Math.round(c.focus)},{paused_minutes:Math.round(c.paused),deep_minutes:Math.round(c.deep),segments:o,queue_filter:n}),m&&await D0(m),window.dispatchEvent(new CustomEvent("focus-session-saved",{detail:{id:d}}))}catch{}})(),c},D0=async e=>{const{data:t}=await B.from("user_goals").select("*").eq("user_id",e).eq("goal_type","daily_focu
11s_time");if(!t?.length)return;const n=new Date;n.setHours(0,0,0,0);const{data:a}=await B.from("focus_sessions").select("duration_minutes").eq("user_id",e).gte("started_at",n.toISOString()).lt("started_at",new Date(n.getTime()+864e5).toISOString()),r=(a??[]).reduce((c,l)=>c+(l.duration_minutes||0),0);t.filter(c=>r>=c.target_value).length&&await Ym()},R0=3e4,I0=1e3,lr="focus-idle-notice",dr=["pointerdown","pointermove","keydown","touchstart","wheel","scroll"],M0=e=>`Focus ended after 3 hours without activity · counted until ${Ee(e,"HH:mm")}`,kl=e=>{try{sessionStorage.removeItem(lr)}catch{}const t="focus-idle";if(nt()){xt(t),Z(`Focus ended · 3 h idle · until ${Ee(e,"HH:mm")}`,{id:t,duration:8e3});return}Z(M0(e),{id:t,duration:12e3})},mc=(e,t=!1)=>{try{sessionStorage.setItem(lr,String(e))}catch{}if(t&&document.visibilityState==="visible"){kl(e);return}const n=()=>{document.visibilityState==="visible"&&(dr.forEach(a=>window.removeEventListener(a,n,!0)),document.removeEventListener("visibilitychange",n),kl(e))};dr.forEach(a=>window.addEventListener(a,n,{capture:!0,passive:!0})),document.addEventListener("visibilitychange",n)},L0=()=>{const e=dc();e&&sn();let t=e?.endedAt??null;if(t==null)try{const n=sessionStorage.getItem(lr);t=n&&Number(n)||null}catch{}if(t!=null){const n=t;
11try{sessionStorage.setItem(lr,String(n))}catch{}window.setTimeout(()=>mc(n,!0),600)}return!!e},jT=()=>{const[e]=i.useState(()=>{const t=dc();return t&&sn(),t});i.useEffect(()=>{e&&mc(e.endedAt,!0)},[e])},NT=e=>{const t=i.useRef(e);t.current=e,i.useEffect(()=>{let n=!1,a=0;const r=f=>{if(n)return!0;const p=dc();return p?(n=!0,mc(p.endedAt,f),t.current(p),!0):!1};let o=NaN,c=NaN;const l=f=>{const p=Date.now();if(f.type==="pointermove"){const{screenX:g,screenY:b}=f;if(g===o&&b===c)return;o=g,c=b}(f.type==="pointermove"||f.type==="scroll"||f.type==="wheel")&&p-a<I0||(a=p,!r(!0)&&vl(p))},d=()=>{document.visibilityState==="visible"?r(!0)||vl(Date.now()):ro()},m=()=>ro();r(document.visibilityState==="visible"),dr.forEach(f=>window.addEventListener(f,l,{capture:!0,passive:!0})),document.addEventListener("visibilitychange",d),window.addEventListener("pagehide",m);const u=window.setInterval(()=>r(!1),R0);return()=>{dr.forEach(f=>window.removeEventListener(f,l,!0)),document.removeEventListener("visibilitychange",d),window.removeEventListener("pagehide",m),window.clearInterval(u),ro()}},[])},A0=({isTaskFocus:e,focusedTaskId:t,focusSessionStartTime:n,setFocusSessionStartTime:a,isProcessingTaskCompletion:r,lastCompletedTaskId:o,setIsTaskFocus:c,setFocusedTaskId:l})=>{const d=i.useRef(null),m=i.useRef(!1),u=i.useRef(!1);i.useEffect(()=>{if(u.current)return;if(L0()){localStorage.removeItem("task-focus-state"),u.current=!0;return}const f=localStorage.getItem("task-focus-state");if(f)try{const{isTaskFocus:p,focusedTaskId:h,timestamp:g,focusSessionStartTime:b,processingCompletion:x}=JSON.parse(f);g&&Date.now()-g<7200*1e3||!!S0()?(c(p,"restore"),l(h),b&&p&&a(new Date),d.current=f):jt()||(sn(),requestAnimationFrame(()=>{localStorage.removeItem("task-focus-state"),localStorage.removeItem("focus-timer-state"),localStorage.removeItem("focus-timer-visible")}))}catch{localStorage.removeItem("task-focus-state"),localStorage.removeItem("focus-timer-state"),localStorage.removeItem("focus-timer-visible")}u.current=!0},[c,l,a]),i.useEffect(()=>{if(u.current&&!m.current)if(e){const f=n||new Date;n||a(f),m.current=!0,requestAnimationFrame(()=>{const p={isTaskFocus:e,focusedTaskId:t,timestamp:Date.now(),focusSessionStartTime:f.toISOString(),isProcessingCompletion:r,lastCompletedTaskId:o,inTransition:r},h=JSON.stringify(p);h!==d.current&&(d.current=h,localStorage.setItem("task-focus-state",h)),m.current=!1})}else d.current!==null&&jt()?d.current=null:d.current!==null&&requestAnimationFrame(()=>{localStorage.removeItem("task-focus-state"),localStorage.removeItem("focus-timer-state"),localStorage.removeItem("focus-timer-visible"),a(null),d.current=null,m.current=!1})},[e,t,r,o,n,a])},P0=({isProcessingTaskCompletion:e,setIsProcessingTaskCompletion:t,isTaskFocus:n})=>{i.useEffect(()=>{if(e){if(n){const r=localStorage.getItem("task-focus-state");if(r)try{const o=JSON.parse(r);localStorage.setItem("task-focus-state",JSON.stringify({...o,isProcessingCompletion:!0,processingTimestamp:Date.now(),inTransition:!0}))}catch{}}const a=setTimeout(()=>{if(e){t(!1);try{const r=localStorage.getItem("task-focus-state");if(r){const o=JSON.parse(r);localStorage.setItem("task-focus-state",JSON.stringify({...o,isProcessingCompletion:!1,inTransition:!1}))}}catch{}}},1e4);return()=>clearTimeout(a)}},[e,n,t])},O0=({isProcessingTaskCompletion:e,setIsProcessingTaskCompletion:t,setLastCompletedTaskId:n,setTaskCompletionTimestamp:a})=>{i.useEffect(()=>{const r=o=>{const c=o.detail;c&&c.taskId&&(n(c.taskId),a(c.timestamp||Date.now()),e&&setTimeout(()=>{t(!1)},1e3))};return window.addEventListener("focus-task-completed",r),()=>window.removeEventListener("focus-task-completed",r)},[e,t,n,a])},$0=()=>{const{isTaskFocus:e,setIsTaskFocus:t,focusedTaskId:n,setFocusedTaskId:a,hasSeenFocusInstructions:r,setHasSeenFocusInstructions:o,focusSessionStartTime:c,setFocusSessionStartTime:l,isProcessingTaskCompletion:d,setIsProcessingTaskCompletion:m,lastCompletedTaskId:u,setLastCompletedTaskId:f,taskCompletionTimestamp:p,setTaskCompletionTimestamp:h,disableFocusMode:g}=m0();A0({isTaskFocus:e,focusedTaskId:n,focusSessionStartTime:c,setFocusSessionStartTime:l,isProcessingTaskCompletion:d,lastCompletedTaskId:u,setIsTaskFocus:t,setFocusedTaskId:a}),P0({isProcessingTaskCompletion:d,setIsProcessingTaskCompletion:m,isTask
11Focus:e}),O0({isProcessingTaskCompletion:d,setIsProcessingTaskCompletion:m,setLastCompletedTaskId:f,setTaskCompletionTimestamp:h});const b=i.useRef(!1);i.useEffect(()=>(e?(document.body.classList.add("focus-mode-active"),b.current=!0):(document.body.classList.remove("focus-mode-active"),b.current&&(document.querySelectorAll(".matrix-grid").forEach(w=>{const k=w;requestAnimationFrame(()=>{k.style.transition="none",k.offsetWidth,k.style.opacity="1",k.style.filter="none",k.style.transform="none",requestAnimationFrame(()=>{k.style.transition=""})})}),b.current=!1)),()=>{document.body.classList.remove("focus-mode-active")}),[e]);const x=i.useCallback(()=>{b.current&&(document.querySelectorAll(".matrix-grid").forEach(y=>{const w=y;requestAnimationFrame(()=>{w.style.transition="none",w.style.opacity="1",w.style.filter="none",w.style.transform="none",w.offsetWidth,requestAnimationFrame(()=>{w.style.transition=""})})}),b.current=!1),g()},[g]);return{isTaskFocus:e,setIsTaskFocus:t,focusedTaskId:n,setFocusedTaskId:a,hasSeenFocusInstructions:r,setHasSeenFocusInstructions:o,isProcessingTaskCompletion:d,setIsProcessingTaskCompletion:m,lastCompletedTaskId:u,setLastCompletedTaskId:f,taskCompletionTimestamp:p,setTaskCompletionTimestamp:h,focusSessionStartTime:c,disableFocusMode:x}},F0=(e,t)=>{const n=Fe();return{showFocusToast:i.useCallback(()=>{n||e||(Z.dismiss(),Z.message("Focus mode on · ← → to move · Esc to exit",{duration:4e3}),t(!0))},[n,e,t])}},jl="focus-empty",q0=e=>e==="filters"?{title:"No tasks to focus on",description:"Your filters hide every task.",action:"Clear filters"}:{title:"No tasks to focus on",description:"Add a task to start a focus session.",action:"Add task"},z0=(e,t)=>e>0&&t?"filters":"empty",U0=()=>{document.getElementById("add-task-btn")?.click()},fc=()=>{const{activeFilterCount:e,clearFilters:t}=Pe.getState(),n=z0(e,!!t),a=q0(n),r=nt();xt(jl),Z(a.title,{id:jl,description:r?void 0:a.description,duration:5e3,action:{label:a.action,onClick:()=>{n==="filters"?t?.():U0()}}})},B0=({isTaskFocus:e,setIsTaskFocus:t,setFocusedTaskId:n,showFocusToast:a})=>{const r=i.useCallback(l=>{e&&n(l)},[e,n]),o=i.useCallback(l=>{if(e){n(void 0),sn(),localStorage.removeItem("task-focus-state"),localStorage.removeItem("focus-timer-state"),localStorage.removeItem("focus-timer-visible"),t(!1);return}if(l){let d;const m=[...l.urgentImportant,...l.important,...l.urgent,...l.neither];l.startId&&m.some(u=>u.id===l.startId)?d=m.find(u=>u.id===l.startId):l.urgentImportant.length>0?d=l.urgentImportant[0]:l.important.length>0?d=l.important[0]:l.urgent.length>0?d=l.urgent[0]:l.neither.length>0&&(d=l.neither[0]),d?(n(d.id),t(!0),a()):fc()}},[e,t,n,a]),c=i.useCallback(()=>{sn(),localStorage.removeItem("task-focus-state"),localStorage.removeItem("focus-timer-state"),localStorage.removeItem("focus-timer-visible"),t(!1),n(void 0)},[t,n]);return{handleTaskFocus:r,handleToggleTaskFocus:o,handleExitTaskFocus:c}},H0=({isTaskFocus:e,focusedTaskId:t,isProcessingTaskCompletion:n,setIsProcessingTaskCompletion:a,setLastCompletedTaskId:r,setTaskCompletionTimestamp:o,setFocusedTaskId:c})=>{const l=at();return{handleTaskComplete:i.useCallback((m,u)=>{if(!n){a(!0),r(m),o(Date.now());try{if(e&&t===m){const f=u.filter(h=>h!==m),p={isTaskFocus:!0,focusedTaskId:f.length>0?f[0]:null,timestamp:Date.now(),lastCompletedTaskId:m,processingState:!0,remainingTasksCount:f.length,inTransition:!0,transitionStart:Date.now()};localStorage.setItem("task-focus-state",JSON.stringify(p)),f.length>0&&(c(f[0]),setTimeout(()=>{l.setQueryData(["focused-tasks"],h=>h?h.filter(g=>g!==m):[]),l.invalidateQueries({queryKey:["statistics"],refetchType:"inactive"})},0))}}catch{}finally{setTimeout(()=>{try{const f=localStorage.getItem("task-focus-state");if(f){const p=JSON.parse(f);localStorage.setItem("task-focus-state",JSON.stringify({...p,processingState:!1,inTransition:!1}))}}catch{}a(!1)},800)}}},[e,t,n,a,r,o,c,l])}},V0=({lastCompletedTaskId:e,taskCompletionTimestamp:t,isTaskFocus:n,setIsTaskFocus:a,setFocusedTaskId:r})=>{i.useEffect(()=>{const o=t&&Date.now()-t<15e3;if(e&&o&&!n)try{const c=localStorage.getItem("task-focus-state");if(c){const l=JSON.parse(c);if(l&&typeof l=="object"){const{isTaskFocus:d,focusedTaskId:m,timestamp:u,inTransition:f}=l;if(u&&Date.now()-u<1800*1e3){if(a(!0,"restore"),jt())return;m&&r(m),localStorage.setItem("task-focus-state",JSON.stringify({...l,timestamp:Date.now(),recovered:!0,inTransition:!1})),setTimeout(()=>{try{Z.info("Focus Mode Restored",{description:"Your focus session has been recovered",duration:2e3,position:"bottom-right",className:"bg-background/80 backdrop-blur-sm op
11acity-80"})}catch{}},500)}}}}catch{a(!0,"restore")}},[e,t,n,a,r]),i.useEffect(()=>{if(!n)try{const o=localStorage.getItem("task-focus-state");if(o){const c=JSON.parse(o);if(c&&typeof c=="object"){const{isTaskFocus:l,focusedTaskId:d,timestamp:m,inTransition:u}=c;m&&Date.now()-m<7200*1e3&&l&&setTimeout(()=>{a(!0,"restore"),d&&r(d),!jt()&&localStorage.setItem("task-focus-state",JSON.stringify({...c,inTransition:!1,timestamp:Date.now()}))},u?500:0)}}}catch{}},[n,a,r]),i.useEffect(()=>{try{const o=localStorage.getItem("task-focus-state");if(o){const c=JSON.parse(o);c&&c.timestamp&&Date.now()-c.timestamp>720*60*1e3&&localStorage.removeItem("task-focus-state")}}catch{}},[])},K0=()=>{const{isTaskFocus:e,setIsTaskFocus:t,focusedTaskId:n,setFocusedTaskId:a,hasSeenFocusInstructions:r,setHasSeenFocusInstructions:o,isProcessingTaskCompletion:c,setIsProcessingTaskCompletion:l,lastCompletedTaskId:d,setLastCompletedTaskId:m,taskCompletionTimestamp:u,setTaskCompletionTimestamp:f,disableFocusMode:p}=$0(),{showFocusToast:h}=F0(r,o),{handleTaskFocus:g,handleToggleTaskFocus:b,handleExitTaskFocus:x}=B0({isTaskFocus:e,setIsTaskFocus:t,setFocusedTaskId:a,showFocusToast:h}),{handleTaskComplete:y}=H0({isTaskFocus:e,focusedTaskId:n,isProcessingTaskCompletion:c,setIsProcessingTaskCompletion:l,setLastCompletedTaskId:m,setTaskCompletionTimestamp:f,setFocusedTaskId:a});return V0({lastCompletedTaskId:d,taskCompletionTimestamp:u,isTaskFocus:e,setIsTaskFocus:t,setFocusedTaskId:a}),i.useMemo(()=>({isTaskFocus:e,focusedTaskId:n,handleTaskFocus:g,handleToggleTaskFocus:b,handleTaskComplete:y,handleExitTaskFocus:x,disableFocusMode:p,setIsTaskFocus:t,setFocusedTaskId:a,isProcessingTaskCompletion:c,lastCompletedTaskId:d}),[e,n,g,b,y,x,p,c,d])},Y0=({isFocusMode:e})=>{const{focusStartTime:t,incrementCompletedTasks:n}=Wm(e),{isTaskFocus:a,focusedTaskId:r,handleTaskFocus:o,handleToggleTaskFocus:c,handleExitTaskFocus:l,setIsTaskFocus:d,setFocusedTaskId:m}=K0(),u=i.useCallback(h=>{m(h),d(!0)},[m,d]),f=i.useCallback((h,g,b,x)=>({urgentImportant:h,important:g,urgent:b,neither:x}),[]),p=i.useCallback(h=>{c(h)},[c]);return i.useMemo(()=>({focusStartTime:t,incrementCompletedTasks:n,isTaskFocus:a,focusedTaskId:r,handleTaskFocus:o,handleToggleTaskFocus:p,handleExitTaskFocus:l,prepareQuadrantTasks:f,setIsTaskFocus:d,openTaskFocus:u}),[t,n,a,r,o,p,l,f,d,u])},ut=(e=10)=>{if(typeof navigator<"u"&&typeof navigator.vibrate=="function")try{navigator.vibrate(e)}catch{}},W0=()=>{const[e,t]=i.useState(!1);i.useEffect(()=>{const a=()=>{const r=document.getElementById("matrix-top"),o=r?r.getBoundingClientRect().top<-300:window.scrollY>300;t(o)};return a(),window.addEventListener("scroll",a,{passive:!0}),document.addEventListener("scroll",a,{passive:!0,capture:!0}),()=>{window.removeEventListener("scroll",a),document.removeEventListener("scroll",a,{capture:!0})}},[]);const n=i.useCallback(a=>{a.preventDefault(),a.stopPropagation(),ut(8);const r=document.getElementById("matrix-top");if(r){const c=Math.abs(r.getBoundingClientRect().top)>(window.innerHeight||1)*1.5?"auto":"smooth";try{r.scrollIntoView({behavior:c,block:"start"})}catch{r.scrollIntoView()}}else window.scrollTo({top:0,behavior:"smooth"})},[]);return s.jsx(_e.div,{initial:{opacity:0,scale:.8},animate:{opacity:e?1:0,scale:e?1:.8,y:e?0:20},transition:{duration:.2},className:"fixed right-4 bottom-8 max-sm:bottom-[calc(env(safe-area-inset-bottom,0px)+76px)] z-40",style:{pointerEvents:e?"auto":"none"},children:s.jsx(W,{variant:"secondary",size:"icon","aria-label":"Scroll to top",className:"rounded-full shadow-lg bg-primary text-primary-foreground hover:bg-primary/90 active:scale-90 transition-transform",onClick:n,style:{opacity:e?1:0,visibility:e?"visible":"hidden",pointerEvents:e?"auto":"none"},children:s.jsx(fu,{className:"h-4 w-4"})})})},G0=({urgentImportant:e,important:t,urgent:n,neither:a,dateFilter:r="all",children:o})=>{const{toast:c}=He(),l=i.useCallback(m=>{try{let u=m;return r!=="all"&&(u=Bi({tasks:u,dateFilter:r,selectedLabel:"all"})),u}catch{return c({title:"Error",description:"Failed to filter tasks",variant:"destructive"}),m}},[r,c]),d=i.useMemo(()=>({filteredUrgentImportant:l(e),filteredImportant:l(t),filteredUrgent:l(n),filteredNeither:l(a)}),[l,e,t,n,a]);return s.jsx(s.Fragment,{children:o(d)})},Q0=new Map,J0=new Map,X0=new Map,Z0=new Map,ew=new Map,tw=new Map,sw=()=>{Q0.clear(),J0.clear(),X0.clear(),Z0.clear(),ew.clear(),tw.clear()},ST=(e,t,n,a,r)=>`${e}-${t}-${n}-${a}-${r}
11`,nw=({isFocusMode:e,isTaskFocus:t,onTaskComplete:n,onTaskUpdate:a,hasPendingUpdates:r=!1,children:o})=>{const c=at(),[l,d]=i.useState(Date.now()),[m,u]=i.useState(r),f=i.useCallback(async()=>{try{await n(),d(Date.now()),e||t?(u(!0),await c.invalidateQueries({queryKey:["statistics"],refetchType:"inactive",exact:!1})):await c.invalidateQueries({queryKey:["tasks","statistics"],refetchType:"active",exact:!1})}catch{Z.error("Failed to complete task",{description:"Please try again later",className:"border border-red-200 bg-gradient-to-r from-red-50 to-rose-50 text-red-800 dark:from-red-950/50 dark:to-rose-950/50 dark:border-red-800/40 dark:text-red-300"})}},[n,c,e,t]);return s.jsx(s.Fragment,{children:o({handleTaskComplete:f,lastUpdatedTimestamp:l,hasPendingUpdates:m})})},Zm=e=>{const t=typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():Math.random().toString(36).slice(2);return`${e}:${t}`},ur={focus_do_first:!0,focus_schedule:!0,auto_prioritize_enabled:!1,days_before_due:3,include_today:!0,include_overdue:!0},oo=e=>["focus-mode-preferences",e],Bo=e=>({focus_do_first:e.focus_do_first,focus_schedule:e.focus_schedule,auto_prioritize_enabled:e.auto_prioritize_enabled||!1,days_before_due:e.days_before_due||3,include_today:e.include_today??!0,include_overdue:e.include_overdue??!0}),aw=async e=>{const{data:t,error:n}=await B.from("focus_mode_preferences").select("*").eq("user_id",e).maybeSingle();if(n)throw n;if(t)return Bo(t);const{data:a,error:r}=await B.from("focus_mode_preferences").insert({user_id:e,...ur}).select().single();if(r)throw r;return a?Bo(a):ur},mr=new Map,rw=(e,t)=>{const n=mr.get(e);if(n){n.count+=1;return}const a=B.channel(Zm("focus_mode_preferences_changes")).on("postgres_changes",{event:"*",schema:"public",table:"focus_mode_preferences",filter:`user_id=eq.${e}`},r=>{r.new&&t(Bo(r.new))}).subscribe();mr.set(e,{channel:a,count:1})},ow=e=>{const t=mr.get(e);t&&(t.count-=1,t.count<=0&&(mr.delete(e),B.removeChannel(t.channel)))},iw=()=>{const{session:e}=we.useSessionContext(),t=e?.user?.id,n=e?.user?.email,a=at(),{toast:r}=He(),o=it({queryKey:oo(t),enabled:!!t,staleTime:5*6e4,queryFn:()=>aw(t)});i.useEffect(()=>{if(t)return rw(t,d=>{a.setQueryData(oo(t),d)}),()=>ow(t)},[t,a]);const c=o.data??ur,l=i.useCallback(async d=>{if(!t)return;const m=oo(t),u=a.getQueryData(m)??ur,f={...u,...d};try{await Pt(t,n,"auto_prioritize_settings_update",{enabled:f.auto_prioritize_enabled,days_before_due:f.days_before_due,include_today:f.include_today,include_overdue:f.include_overdue}),a.setQueryData(m,f);const{error:p}=await B.from("focus_mode_preferences").update(f).eq("user_id",t);if(p)throw p}catch(p){throw a.setQueryData(m,u),r({title:"Error",description:"Failed to update focus mode preferences.",variant:"destructive"}),p}},[t,n,a,r]);return{preferences:c,isLoading:!!t&&o.isLoading,updatePreferences:l}},cw=3600*1e3;function lw(e,t=new Date){const n=t.getTime();let a=new Date(t.getFullYear(),t.getMonth(),t.getDate()+1).getTime();for(const r of e){if(!gt(r.due))continue;const o=Ye(r.due)?.getTime();o!==void 0&&o>n&&o<a&&(a=o)}return Math.min(a-n,cw)+250}function ra(e){const[t,n]=i.useState(0);return i.useEffect(()=>{const a=window.setTimeout(()=>n(r=>r+1),lw(e));return()=>window.clearTimeout(a)},[e,t]),t}const hc=i.forwardRef(({className:e,...t},n)=>s.jsx("div",{ref:n,className:S("rounded-xl border bg-card text-card-foreground shadow-sm transition-all duration-300","hover:shadow-md hover:border-border/50","backdrop-blur-sm",e),...t}));hc.displayName="Card";const ef=i.forwardRef(({className:e,...t},n)=>s.jsx("div",{ref:n,className:S("flex flex-col space-y-1.5 p-6",e),...t}));ef.displayName="CardHeader";const tf=i.forwardRef(({className:e,...t},n)=>s.jsx("h3",{ref:n,className:S("text-2xl font-semibold leading-none tracking-tight",e),...t}));tf.displayName="CardTitle";const sf=i.forwardRef(({className:e,...t},n)=>s.jsx("p",{ref:n,className:S("text-sm text-muted-foreground",e),...t}));sf.displayName="CardDescription";const pc=i.forwardRef(({className:e,...t},n)=>s.jsx("div",{ref:n,className:S("p-6 pt-0",e),...t}));
11pc.displayName="CardContent";const dw=i.forwardRef(({className:e,...t},n)=>s.jsx("div",{ref:n,className:S("flex items-center p-6 pt-0",e),...t}));dw.displayName="CardFooter";const uw="Subtask",nf=e=>{const t=new Set;if(e.length<2)return t;const n=new Map;for(const r of e)n.set(r.id,r.parent_id||void 0);const a=(r,o)=>{const c=new Set;let l=n.get(r);for(;l&&!c.has(l);){if(l===o)return!0;c.add(l),l=n.get(l)}return!1};return e.forEach((r,o)=>{const c=r.parent_id;if(c)for(let l=o-1;l>=0;l--){const d=e[l];if(d.id===c){t.add(r.id);return}if(!a(d.id,c))return}}),t},mw=(e,{nested:t=!1,parentAbove:n=!1}={})=>!!e?.parent_id&&!t&&!n,fw=e=>{const t=e?.trim()||null;return{text:t??uw,aria:t?`subtask of ${t}`:"subtask",known:!!t}},hw=(e,{loaded:t,visibleIds:n,hierarchy:a,nestSubtasks:r})=>{const o=t.get(e),c=o?Kn(o):null;if(!o||!c)return{kind:"todoist",parentId:e};if(!n.has(e))return{kind:"hidden",parentId:e,quadrant:c};const l=a.displayRootIdById.get(e);if(r&&a.nestedChildIds.has(e)&&l&&n.has(l)){const d=t.get(l);return{kind:"row",parentId:e,rowId:l,quadrant:d&&Kn(d)||c}}return{kind:"row",parentId:e,rowId:e,quadrant:c}},af={compact:{cardPadding:"p-2 sm:p-2.5",gridGap:"gap-2 sm:gap-3",gridGapMobile:"gap-1",quadrantMinHeight:"min-h-[60
11px]",quadrantPadding:"p-2",quadrantHeaderPy:"py-2",quadrantTitleSize:"text-base md:text-lg",quadrantDescSize:"text-xs",quadrantIconSize:"h-4 w-4",taskSpacing:"space-y-1",textSize:"text-xs",titleSize:"text-[13px]",cardRadius:"rounded-lg",cardMaxWidth:"sm:max-w-5xl sm:mx-auto",rowHeight:32},default:{cardPadding:"p-3.5 sm:p-4",gridGap:"gap-5 sm:gap-6",gridGapMobile:"gap-2",quadrantMinHeight:"min-h-[140px]",quadrantPadding:"p-4",quadrantHeaderPy:"py-4",quadrantTitleSize:"text-xl md:text-2xl",quadrantDescSize:"text-sm",quadrantIconSize:"h-5 w-5",taskSpacing:"space-y-2",textSize:"text-sm",titleSize:"text-base",cardRadius:"rounded-2xl",cardMaxWidth:"sm:max-w-3xl sm:mx-auto",rowHeight:38},comfortable:{cardPadding:"p-6 sm:p-8",gridGap:"gap-8 sm:gap-10",gridGapMobile:"gap-4",quadrantMinHeight:"min-h-[240px]",quadrantPadding:"p-6",quadrantHeaderPy:"py-6",quadrantTitleSize:"text-2xl md:text-3xl",quadrantDescSize:"text-base",quadrantIconSize:"h-6 w-6",taskSpacing:"space-y-4",textSize:"text-base",titleSize:"text-lg sm:text-xl",cardRadius:"rounded-3xl",cardMaxWidth:"sm:max-w-xl sm:mx-auto",rowHeight:56}},rf=i.createContext(null),pw=({children:e})=>{const{session:t}=we.useSessionContext(),n=t?.user?.id,a=n?`matrix-density-${n}`:"matrix-density-anonymous",[r,o]=ct(a,"default"),c=i.useCallback(u=>{u!==r&&pe("view_changed",{kind:"density",to:u}),o(u)},[r,o]),l=i.useMemo(()=>af[r],[r]),d=i.useCallback(()=>{const u=["compact","default","comfortable"],f=(u.indexOf(r)+1)%u.length;c(u[f])},[r,c]),m=i.useMemo(()=>({density:r,setDensity:c,config:l,cycleDensity:d}),[r,c,l,d]);return s.jsx(rf.Provider,{value:m,children:e})},Zt=()=>{const e=i.useContext(rf);return e||{density:"default",setDensity:()=>{},config:af.default,cycleDensity:()=>{}}},of=(e,t)=>{const[n,a]=i.useState(!1),[r,o]=i.useState(null),c=i.useRef(t);c.current=t,i.useEffect(()=>{r&&t!==r.base&&o(null)},[t,r]),i.useEffect(()=>{if(!e)return;const f=h=>{const g=h.detail;g?.taskId===e&&o({title:g.title,base:c.current})},p=h=>{h.detail?.taskId===e&&o(null)};return window.addEventListener("task:rename",f),window.addEventListener("task:rename-failed",p),()=>{window.removeEventListener("task:rename",f),window.removeEventListener("task:rename-failed",p)}},[e]);const l=r?.title??t,d=i.useCallback(()=>{e&&a(!0)},[e]),m=i.useCallback(()=>a(!1),[]),u=i.useCallback(f=>{a(!1);const p=f.replace(/\s+/g," ").trim();!e||!p||p===l||window.dispatchEvent(new CustomEvent("task:rename",{detail:{taskId:e,title:p,previous:l}}))},[e,l]);return{title:l,editing:n,start:d,cancel:m,commit:u}},cf=({value:e,onCommit:t,onCancel:n,className:a})=>{const[r,o]=i.useState(e),c=i.useRef(null),l=i.useRef(!1);i.useEffect(()=>{const m=c.current;m&&(m.focus({preventScroll:!0}),m.select())},[]);const d=m=>{l.current||(l.current=!0,m?t(r):n())};return s.jsx("input",{ref:c,className:S("task-title-input",a),value:r,"aria-label":"Task name",maxLength:500,onChange:m=>o(m.target.value),onKeyDown:m=>{m.stopPropagation(),m.key==="Enter"&&(m.preventDefault(),d(!0)),m.key==="Escape"&&(m.preventDefault(),d(!1))},onBlur:()=>d(!0),onClick:m=>m.stopPropagation(),onPointerDown:m=>m.stopPropagation(),onDoubleClick:m=>m.stopPropagation()})},lf=i.memo(({title:e,isFocused:t,taskId:n})=>{const{config:a}=Zt(),r=of(n,e);return s.jsx("h3",{className:S("font-medium leading-tight line-clamp-3 max-sm:line-clamp-2 tracking-tight subpixel-antialiased",a.titleSize,t?"text-foreground mb-2":"text-foreground/90 mb-0.5","group-hover:text-foreground transition-colors duration-200"),title:n&&!r.editing?"Double-click to rename":void 0,onDoubleClick:n?o=>{o.stopPropagation(),r.start()}:void 0,children:r.editing?s.jsx(cf,{value:r.title,onCommit:r.commit,onCancel:r.cancel}):r.title})});lf.displayName="TaskTitle";const df=i.memo(({title:e,isFocused:t,taskId:n})=>s.jsx(te.div,{className:"flex items-start gap-2 flex-1",initial:{opacity:.9},animate:{opacity:1},transition:{duration:.2},children:s.jsx(lf,{title:e,isFocused:t,taskId:n})}));df.displayName="TaskHeaderContent";const Nt=Zn,St=jr,Ct=i.forwardRef(({className:e,align:t="center",sideOffset:n=4,...a},r)=>s.jsx(ea,{children:s.jsx(mn,{ref:r,align:t,sideOffset:n,className:S("z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:sli
11de-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...a})}));Ct.displayName=mn.displayName;const uf=i.memo(({onComplete:e,isFocused:t})=>{const[n,a]=i.useState(!1),[r,o]=i.useState(!1),c=i.useCallback(async l=>{if(l.stopPropagation(),!n){a(!0);try{await e(l)}catch{}finally{setTimeout(()=>a(!1),150)}}},[e,n]);return s.jsxs("button",{onClick:c,onMouseEnter:()=>o(!0),onMouseLeave:()=>o(!1),"aria-label":"Mark task as complete",className:S("relative flex items-center justify-center h-8 w-8 max-sm:h-11 max-sm:w-11 rounded-full","transition-all duration-200 ease-[cubic-bezier(0.25,0.1,0.25,1)]","hover:bg-green-500/8 active:scale-90 active:duration-100","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-green-400/40",n&&"pointer-events-none scale-90 opacity-60"),children:[s.jsx(Di,{className:S("h-[22px] w-[22px] transition-all duration-200","text-slate-300 dark:text-slate-400",r&&"text-green-500 scale-110",t&&"text-green-400",n&&"opacity-0 scale-75"),strokeWidth:2}),s.jsx(Li,{className:S("h-[22px] w-[22px] absolute transition-all duration-200","text-green-500 opacity-0 scale-75",r&&"opacity-100 scale-110",n&&"opacity-100 scale-100"),strokeWidth:1.8})]})});uf.displayName="TaskCompleteButton";const mf=Ps(()=>Ne(()=>import("./SettingsDialog-BEGO-5Bn.js"),__vite__mapDeps([6,1,2,7,3,8,4])).then(e=>e.SettingsDialog),e=>e.isOpen),ff=Ps(()=>Ne(()=>import("./DeleteAccountDialog-CMaSG8PP.js"),__vite__mapDeps([9,1,2,3,4])).then(e=>e.DeleteAccountDialog),e=>e.open),hf=Ps(()=>Ne(()=>import("./GumroadLicenseDialog-CxkArFHj.js"),__vite__mapDeps([10,1,2,3,11,12,4])).then(e=>e.GumroadLicenseDialog),e=>e.isOpen),pf=Ps(()=>Ne(()=>import("./FeatureRequestDialog-CT2R6KQ8.js"),__vite__mapDeps([13,1,2,14,3,4])).then(e=>e.FeatureRequestDialog),e=>e.open),gf=Ps(()=>Ne(()=>import("./TaskCommentsDialog-BnBwvN69.js"),__vite__mapDeps([15,1,2,14,4,3])).then(e=>e.default),e=>e.isOpen),rn=gn(()=>Ne(()=>Promise.resolve().then(()=>Hj),void 0).then(e=>e.DateSelectorPopover)),xf=gn(()=>Ne(()=>Promise.resolve().then(()=>Kj),void 0).then(e=>e.DeadlinePicker)),bf=i.memo(({isFocusMode:e,isFocused:t,showCommentSection:n,onCommentClick:a,onFocusClick:r,onComplete:o,onToggleFocusMode:c,taskId:l,deadline:d})=>{const[m,u]=i.useState(!1),f=d?.date?Ms(d.date):void 0,p=h=>{h.stopPropagation(),h.preventDefault();const g=h.currentTarget.closest("[data-task-id]");if(g){const b=g.getAttribute("data-task-id");if(b){const x=`https://todoist.com/app/task/${b}`,y=window.open(x,"_blank");!y||y.closed||typeof y.closed>"u"}}};return s.jsx("div",{className:"flex items-center gap-2",children:s.jsxs(Ls,{delayDuration:100,children:[s.jsxs(Ht,{children:[s.jsx(Vt,{asChild:!0,children:s.jsx(W,{variant:"ghost",size:"icon",className:S("h-9 w-9 rounded-full transition-all duration-200 max-sm:hidden",n?"bg-primary/10 hover:bg-primary/20 shadow-sm":"hover:bg-primary/10"),onClick:a,children:s.jsx(Ai,{className:S("h-5 w-5 transition-all duration-200",n?"text-primary scale-110":"text-muted-foreground hover:text-primary/80")})})}),s.jsx(At,{side:"left",className:"bg-card/95 backdrop-blur-sm border-border/70 shadow-lg",children:s.jsx("p",{children:"Add a comment"})})]}),s.jsxs(Ht,{children:[s.jsx(Vt,{asChild:!0,children:s.jsx(W,{variant:"ghost",size:"icon",className:"h-9 w-9 rounded-full transition-all duration-200 hover:bg-primary/10 max-sm:hidden",onClick:p,children:s.jsx(pu,{className:"h-5 w-5 text-muted-foreground hover:text-primary/80 transition-all duration-200"})})}),s.jsx(At,{side:"left",className:"bg-card/95 backdrop-blur-sm border-border/70 shadow-lg",children:s.jsx("p",{children:"Open in Todoist"})})]}),s.jsxs(Nt,{open:m,onOpenChange:u,children:[s.jsxs(Ht,{children:[s.jsx(Vt,{asChild:!0,children:s.jsx(St,{asChild:!0,children:s.jsx(W,{variant:"ghost",size:"icon",className:S("h-9 w-9 rounded-full transition-all duration-200 max-sm:hidden",d?"bg-amber-500/10 hover:bg-amber-500/20":"hover:bg-primary/10"),onClick:h=>h.stopPropagation(),children:s.jsx(os,{className:S("h-5 w-5 transition-all duration-200",d?"text-amber-600 dark:text-amber-400":"text-muted-foreground hover:text-primary/80")})})})}),s.jsx(At,{side:"left",className:"bg-card/95 backdrop-blur-sm border-border/70 shadow-lg",children:s.jsx("p",{children:d?`Deadline · ${Ee(f,"MMM d")}`:"Set deadline"})})]}),s.jsx(Ct,{className:"w-auto p-0 rounded-xl shadow-xl border-border/40",align:"end",onClick:h=>
11h.stopPropagation(),children:s.jsx(xf,{taskId:l,deadline:d,onDone:()=>u(!1)})})]}),s.jsx(uf,{onComplete:o,isFocused:t})]})})});bf.displayName="TaskActionButtons";const yf=i.memo(({isFocusMode:e,isFocused:t,showCommentSection:n,onCommentClick:a,onFocusClick:r,onComplete:o,onToggleFocusMode:c,taskId:l,deadline:d})=>s.jsx(bf,{isFocusMode:e,isFocused:t,showCommentSection:n,onCommentClick:a,onFocusClick:r,onComplete:o,onToggleFocusMode:c,taskId:l,deadline:d}));yf.displayName="TaskActions";const gw=(e,t)=>t?"overdue":Nr(e)?"today":Hu(e)?"overdue":Vu(e)?"upcoming":"none",xw=e=>{switch(e){case"today":return"text-blue-500 dark:text-blue-400 font-medium";case"overdue":return"text-red-500 dark:text-red-400 font-medium";case"upcoming":return"text-gray-600 dark:text-gray-400";default:return"text-gray-500"}},Ho=({due:e})=>{const t=Fe(),n=e?.date,a=e?.datetime,r=i.useMemo(()=>{const m=Ye(e);if(!m)return null;const u=gw(m,gt(e)&&Er(e));return{dateStatus:u,dateStyles:xw(u),formattedDate:Ee(m,t?"MMM d":"MMM dd, yyyy"),formattedTime:am(e)}},[n,a,t]);if(!r)return null;const{dateStatus:o,dateStyles:c,formattedDate:l,formattedTime:d}=r;return t?s.jsxs("div",{className:S("flex items-center gap-1 text-xs mt-0.5 flex-nowrap",c),children:[s.jsx(Zs,{className:"h-3.5 w-3.5 mr-1 shrink-0"}),s.jsx("span",{className:"font-medium whitespace-nowrap",children:l}),d&&s.jsxs("span",{className:"whitespace-nowrap opacity-80",children:["· ",d]}),o==="today"&&s.jsxs("span",{className:"ml-1 text-[10px] bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300 px-1.5 rounded-full flex items-center shrink-0",children:[s.jsx(Kt,{className:"h-3 w-3 mr-0.5"}),"Today"]}),o==="overdue"&&s.jsxs("span",{className:"ml-1 text-[10px] bg-red-100 dark:bg-red-900/30 text-red-700 dark:text-red-300 px-1.5 rounded-full flex items-center shrink-0",children:[s.jsx(Wt,{className:"h-3 w-3 mr-0.5"}),"Overdue"]})]}):s.jsxs(te.div,{className:S("flex items-center gap-1.5 text-sm mt-2",c),initial:{opacity:0,y:2},animate:{opacity:1,y:0},transition:{duration:.2},children:[s.jsx(Zs,{className:"h-4 w-4 mr-1 shrink-0"}),s.jsx("span",{className:"font-medium whitespace-nowrap",children:l}),d&&s.jsxs("span",{className:"whitespace-nowrap opacity-80",children:["· ",d]}),o==="today"&&s.jsxs(te.span,{className:"ml-1 text-xs bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300 px-2 py-0.5 rounded-full flex items-center shrink-0",initial:{scale:.9},animate:{scale:1},transition:{type:"spring",stiffness:300,damping:20},children:[s.jsx(Kt,{className:"h-3 w-3 mr-1"}),"Today"]}),o==="overdue"&&s.jsxs(te.span,{className:"ml-1 text-xs bg-red-100 dark:bg-red-900/30 text-red-700 dark:text-red-300 px-2 py-0.5 rounded-full flex items-center shrink-0",initial:{scale:.9},animate:{scale:1},transition:{type:"spring",stiffness:300,damping:20},children:[s.jsx(Wt,{className:"h-3 w-3 mr-1"}),"Overdue"]})]})},bw=({due:e,taskId:t,isFocused:n})=>{const[a,r]=i.useState(!1),o=Ye(e)??void 0,c=_r(e),l=u=>{t&&(en(t,u,c,!!e?.isRecurring),r(!1))},d=u=>{t&&en(t,o??_s(),u,!!e?.isRecurring,{kind:"time"})};if(e?.isRecurring)return s.jsx(Ho,{due:e});const m=s.jsx(Ct,{className:"w-auto max-h-[var(--radix-popover-content-available-height)] overflow-y-auto p-0 rounded-xl shadow-xl border-border/40",align:"start",onClick:u=>u.stopPropagation(),children:s.jsx(rn,{title:"Due date",value:o,onChange:l,time:{value:c,onChange:d},setActivePopover:()=>r(!1)})});return e?.date?s.jsxs(Nt,{open:a,onOpenChange:r,children:[s.jsx(St,{asChild:!0,children:s.jsx("button",{type:"button",onClick:u=>u.stopPropagation(),className:"block w-full text-left rounded-md -mx-1 px-1 hover:bg-muted/40 transition-colors cursor-pointer",children:s.jsx(Ho,{due:e})})}),m]}):s.jsx("div",{className:S("overflow-hidden transition-[max-height,opacity] duration-300 ease-[cubic-bezier(0.2,0.8,0.2,1)]",n?"":"max-h-0 opacity-0 group-hover:max-h-10 group-hover:opacity-100"),children:s.jsxs(Nt,{open:a,onOpenChange:r,children:[s.jsx(St,{asChild:!0,children:s.jsxs("button",{type:"button",onClick:u=>u.stopPropagation(),className:"flex items-center gap-1.5 text-sm mt-2 rounded-md -mx-1 px-1 py-0.5 text-muted-foreground
11/60 hover:text-foreground hover:bg-muted/40 transition-colors cursor-pointer",children:[s.jsx(Pi,{className:"h-4 w-4 mr-1 shrink-0"}),s.jsx("span",{className:"font-medium",children:"Due date"})]})}),m]})})},yw=e=>Nr(e)?"today":Hu(e)?"overdue":Vu(e)?"upcoming":"none",ww=e=>{switch(e){case"today":return"text-amber-600 dark:text-amber-400 font-medium";case"overdue":return"text-red-600 dark:text-red-400 font-semibold";case"upcoming":return"text-gray-600 dark:text-gray-400";default:return"text-gray-500"}},Nl=({deadline:e})=>{const t=Fe(),n=e?.date,a=i.useMemo(()=>{const l=zi(e);if(!l)return null;const d=yw(l);return{status:d,styles:ww(d),formattedDate:Ee(l,t?"MMM d":"MMM dd, yyyy")}},[n,t]);if(!a)return null;const{status:r,styles:o,formattedDate:c}=a;return t?s.jsxs("div",{className:S("flex items-center gap-1 text-xs mt-0.5 flex-nowrap",o),children:[s.jsx(os,{className:"h-3.5 w-3.5 mr-1 shrink-0"}),s.jsx("span",{className:"font-medium opacity-80 whitespace-nowrap",children:"Deadline"}),s.jsxs("span",{className:"whitespace-nowrap",children:["· ",c]}),r==="today"&&s.jsx("span",{className:"ml-1 text-[10px] bg-amber-100 dark:bg-amber-900/30 text-amber-700 dark:text-amber-300 px-1.5 rounded-full flex items-center shrink-0",children:"Due today"}),r==="overdue"&&s.jsxs("span",{className:"ml-1 text-[10px] bg-red-100 dark:bg-red-900/30 text-red-700 dark:text-red-300 px-1.5 rounded-full flex items-center shrink-0",children:[s.jsx(Wt,{className:"h-3 w-3 mr-0.5"}),"Overdue"]})]}):s.jsxs(te.div,{className:S("flex items-center gap-1.5 text-sm mt-2",o),initial:{opacity:0,y:2},animate:{opacity:1,y:0},transition:{duration:.2},children:[s.jsx(os,{className:"h-4 w-4 mr-1 shrink-0"}),s.jsx("span",{className:"font-medium opacity-80 whitespace-nowrap",children:"Deadline"}),s.jsxs("span",{className:"whitespace-nowrap",children:["· ",c]}),r==="today"&&s.jsx(te.span,{className:"ml-1 text-xs bg-amber-100 dark:bg-amber-900/30 text-amber-700 dark:text-amber-300 px-2 py-0.5 rounded-full flex items-center shrink-0",initial:{scale:.9},animate:{scale:1},transition:{type:"spring",stiffness:300,damping:20},children:"Due today"}),r==="overdue"&&s.jsxs(te.span,{className:"ml-1 text-xs bg-red-100 dark:bg-red-900/30 text-red-700 dark:text-red-300 px-2 py-0.5 rounded-full flex items-center shrink-0",initial:{scale:.9},animate:{scale:1},transition:{type:"spring",stiffness:300,damping:20},children:[s.jsx(Wt,{className:"h-3 w-3 mr-1"}),"Overdue"]})]})},vw=()=>({bg:"bg-purple-100 dark:bg-purple-900/30",text:"text-purple-700 dark:text-purple-200",border:"border-purple-200 dark:border-purple-800/40"}),kw=({labels:e})=>{const t=Ir(e.filter(o=>o&&o.trim().length>0));if(t.length===0)return null;const n={hidden:{opacity:0},show:{opacity:1,transition:{staggerChildren:.03,delayChildren:.02}}},a={hidden:{opacity:0,scale:.92,y:3},show:{opacity:1,scale:1,y:0}},r=vw();return s.jsx(te.div,{className:"flex flex-wrap gap-1.5 mt-2",variants:n,initial:"hidden",animate:"show",children:t.map((o,c)=>s.jsx(te.div,{variants:a,transition:{type:"spring",stiffness:320,damping:24,mass:.8},children:s.jsxs(Ds,{className:`
12                font-medium text-xs tracking-tight px-2.5 py-0.5 rounded-full
13                ${r.bg} ${r.text} border ${r.border}
14                flex items-center gap-1.5 whitespace-nowrap
15                transition-all duration-300 will-change-transform
16                shadow-[0_0.5px_2px_rgba(0,0,0,0.02)]
17                hover:bg-purple-200 dark:hover:bg-purple-800/40 hover:shadow-[0_1px_3px_rgba(0,0,0,0.04)]
18                hover:scale-[1.02] active:scale-[0.98]
19              `,children:[s.jsx(vr,{className:"h-2.5 w-2.5 opacity-80",strokeWidth:2.5}),s.jsx("span",{className:"relative top-px",children:o})]})},o))})},Sl=(e,t)=>{try{if(typeof window>"u")return t;const n=window.localStorage.getItem(e);return n?JSON.parse(n):t}catch{return t}},Cl=(e,t)=>{try{window.localStorage.setItem(e,JSON.stringify(t))}catch{}},wf="show-task-tags",vf="nest-subtasks-v2",jw=gr(e=>({showTags:Sl(wf,!0),setShowTags:t=>e({showTags:t}),nestSubtasks:Sl(vf,!0),setNestSubtasks:t=>e({nestSubtasks:t})})),ds=()=>{const{showTags:e,setShowTags:t,nestSubtasks:n,setNestSubtasks:a}=jw();return{showTags:e,toggleShowTags:c=>{t(c),Cl(wf,c)},nestSubtasks:n,toggleNestSubtasks:c=>{a(c),Cl(vf,c)}}},kf=i.createContext(cm),Nw=kf.Provider,oa=()=>i.useContext(kf),Sw=({storage:e=null,storageKey:t="subtask-parent-titles-v1",chunkSize:n=50,maxSingle:a=5,maxIds:r=200}={})=>{const o=new Map,c=new Set;let l=0,d=0;try{const f=e?.getItem(t);if(f){const p=JSON.parse(f);for(const[h,g]of Object.entries(p))(typeof g=="string"||g===null)&&o.set(h,g)}}catch{}const m=()=>{try{e?.setItem(t,JSON.stringify(Object.fromEntries(o)))}catch{}},u=f=>(f.content??f.title??"").trim()||null;return{peek:f=>o.get(f),pending:f=>[...new Set(f)].filter(p=>
19!o.has(p)&&!c.has(p)),async load(f,p){let h=[...new Set(f)].filter(x=>x&&!o.has(x)&&!c.has(x));if(!h.length)return!1;const g=Math.max(0,r-d),b=h.slice(g);if(h=h.slice(0,g),b.forEach(x=>o.set(x,null)),!h.length)return m(),b.length>0;d+=h.length,h.forEach(x=>c.add(x));try{const x=new Map;for(let y=0;y<h.length;y+=n){const w=h.slice(y,y+n);try{const k=await p.byIds(w),N=new Set(w);for(const C of k||[])C&&N.has(String(C.id))&&x.set(String(C.id),u(C))}catch{}}for(const y of h)if(!x.has(y)){if(l>=a){x.set(y,null);continue}l++;try{const w=await p.one(y);x.set(y,w?u(w):null)}catch{x.set(y,null)}}return x.forEach((y,w)=>o.set(w,y)),m(),!0}finally{h.forEach(x=>c.delete(x))}}}},Cw=()=>{try{return typeof window>"u"?null:window.sessionStorage}catch{return null}},za=Sw({storage:Cw()}),Ua=new Map,jf={DO:"do",SCHEDULE:"schedule",DELEGATE:"delegate",BACKLOG:"backlog"},Tw=600*1e3;setInterval(()=>Ua.clear(),Tw);const _w=e=>{if(Ua.has(e.id))return Ua.get(e.id);const t=new Set(e.labels.map(Qt));return Ua.set(e.id,t),t},CT=e=>{const t=_w(e);return Object.values(jf).find(n=>t.has(n))},Rn="waiting",Ew=(e,t=new Date)=>({id:e.id,title:e.content||e.title||"",projectId:e.project_id||null,sectionId:e.section_id||null,completedAt:t}),gc=[{id:"tomorrow",label:"Tomorrow"},{id:"in3days",label:"In 3 days"},{id:"nextweek",label:"Next week"}],Tl="in3days",Dw=e=>gc.some(t=>t.id===e),Rw=e=>`Follow up: ${e.trim()}`,Iw=(e,t)=>{const n=e.trim(),a=(t??"").trim();return a?`${n} (${a})`:n},xc=(e,t=new Date)=>{const n=Bn(t);switch(e){case"tomorrow":return st(n,1);case"in3days":return st(n,3);case"nextweek":{const a=(8-n.getDay())%7||7;return st(n,a)}}},Mw=(e,t=new Date)=>gc.find(n=>ls(xc(n.id,t),e)===0)?.id??null,Nf="followup-last-chip",Lw=()=>{try{const e=window.localStorage.getItem(Nf);return Dw(e)?e:Tl}catch{return Tl}},Aw=e=>{try{window.localStorage.setItem(Nf,e)}catch{}},bc=e=>`https://todoist.com/app/task/${e}`,Pw=e=>`[Original task](${bc(e.id)})
20Completed ${Ee(e.completedAt??new Date,"MMM d, yyyy")}`,Ow=({title:e,waitingOn:t,date:n,source:a})=>({content:Iw(e,t),description:Pw(a),due_date:Dr(n),labels:[Rn,jf.DELEGATE],...a.projectId?{project_id:a.projectId}:{},...a.sectionId?{section_id:a.sectionId}:{}}),$w=(e,t=new Date)=>ls(e,t)===1?"tomorrow":Ee(e,"EEE, MMM d"),Fw=new Set,Sf=i.createContext({titleOf:e=>za.peek(e),reveal:e=>{e.parent_id&&window.open(bc(e.parent_id),"_blank","noopener")},revealedIds:Fw}),Cf=()=>i.useContext(Sf),yc=(e,t={})=>{const{titleOf:n,reveal:a}=Cf(),r=mw(e,t),o=e?.parent_id,c=r&&o?n(o):void 0;return i.useMemo(()=>{if(!r||!o)return null;const{text:l,aria:d,known:m}=fw(c);return{parentId:o,text:l,aria:d,known:m,activate:u=>{u?.stopPropagation(),u?.preventDefault(),a({parent_id:o})}}},[r,o,c,a])},_l={transform:{willChange:"transform",backfaceVisibility:"hidden",transformStyle:"preserve-3d",transform:"translateZ(0)"},opacity:{willChange:"opacity",backfaceVisibility:"hidden"}},In={naturalOut:[.2,.8,.2,1],snapOut:[.4,0,.6,1]},Tf={taskCard:{type:"spring",stiffness:280,damping:28,mass:.6,restDelta:.001,restSpeed:.001},modal:{}},Ut={instant:.08,quickHover:.12,standard:.2,smooth:.3},Ys={supportsSmooth:()=>CSS.supports("will-change","transform")&&CSS.supports("backface-visibility","hidden"),isMobile:()=>/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),getOptimizedConfig:()=>{const e=Ys.isMobile();return{reducedStiffness:e,simplifiedShadows:e,reducedParallax:e,fasterDurations:e}},getCPUCores:()=>navigator.hardwareConcurrency||4,getBatteryInfo:async()=>{if("getBattery"in navigator)try{const e=await navigator.getBattery();return{level:e.level,charging:e.charging,chargingTime:e.chargingTime,dischargingTime:e.dischargingTime}}catch{return null}return null},shouldOptimizeForBattery:async()=>{const e=await Ys.getBatteryInfo();return e?!e.charging&&e.level<.2:!1},measureFrameBudget:()=>{performance.now();const e=()=>{performance.now(),requestAnimationFrame(e)};requestAnimationFrame(e)},getDeviceOptimizations:()=>{const e=Ys.isMobile(),t=Ys.getCPUCores(),n=Vo.monitorConnectionQuality();return{reducedAnimations:e&&t<=4,useVirtualization:e,reduceImageQuality:n?.effectiveType==="2g"||n?.s
20aveData,aggressiveBatching:e,useWebWorkers:t>=4&&!e,preloadStrategy:n?.effectiveType==="4g"?"aggressive":"conservative"}}},Vo={monitorMemoryPressure:()=>{if("memory"in performance){const e=performance.memory,t=e.usedJSHeapSize,n=e.totalJSHeapSize,a=e.jsHeapSizeLimit,r=t/a;return r>.9&&Vo.performCleanup(),{usage:r,used:t,total:n,limit:a}}return null},performCleanup:()=>{window.gc&&window.gc(),"caches"in window&&caches.keys().then(e=>{e.forEach(t=>{(t.includes("old")||t.includes("temp"))&&caches.delete(t)})}),Object.keys(localStorage).forEach(e=>{if(e.includes("temp-")||e.includes("cache-")){const t=localStorage.getItem(e);if(t)try{const n=JSON.parse(t);n.expires&&Date.now()>n.expires&&localStorage.removeItem(e)}catch{localStorage.removeItem(e)}}})},monitorConnectionQuality:()=>{if("connection"in navigator){const e=navigator.connection;return{effectiveType:e.effectiveType,downlink:e.downlink,rtt:e.rtt,saveData:e.saveData}}return null},shouldReduceQuality:()=>{const e=Vo.monitorConnectionQuality();return e?e.effectiveType==="slow-2g"||e.effectiveType==="2g"||e.saveData||e.downlink<1:!1}},_f=({description:e,due:t,deadline:n,labels:a,isFocused:r,quadrant:o,priority:c,taskId:l,parentId:d,parentAbove:m=!1})=>{const{showTags:u}=ds(),{byId:f}=oa(),{config:p}=Zt(),g=Fe()&&!r,b=yc(d?{parent_id:d}:null,{parentAbove:m}),x=b?.text,y=b?f.get(b.parentId):void 0,w=i.useMemo(()=>{switch(y?Kn(y):null){case"do":return"bg-red-400";case"schedule":return"bg-blue-400";case"delegate":return"bg-orange-400";case"backlog":return"bg-gray-400";default:return null}},[y]),k=b?s.jsxs("button",{type:"button",onClick:b.activate,"data-qa":"parent-crumb",title:b.known?`Subtask of ${x}`:"Subtask","aria-label":b.known?`Subtask of ${x}. Go to parent task`:"Subtask. Go to parent task",className:S("inline-flex items-center gap-1.5 text-[11px] text-muted-foreground","bg-muted/50 border border-border/40 rounded-full px-2 py-0.5 max-w-[260px]","transition-colors hover:bg-muted hover:text-foreground hover:border-border/80","focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"),children:[s.jsx(Fp,{className:"h-3 w-3 shrink-0"}),w&&s.jsx("span",{className:S("h-1.5 w-1.5 rounded-full shrink-0",w),"aria-hidden":!0}),s.jsx("span",{className:"truncate",children:x})]}):null,N=i.useMemo(()=>{const T=e&&e.trim().length>0,_=a.filter(M=>!M.startsWith("@")),I=a.filter(M=>M.startsWith("@")),R=T||t?.date||n?.date||r;return{hasDescription:T,displayLabels:_,gtdContexts:I,hasContent:R,hasMetadata:_.length>0||I.length>0||t?.date||n?.date}},[e,a,t?.date,n?.date,r]),C=i.useMemo(()=>{const T={4:{label:"P1",color:"text-red-500"},3:{label:"P2",color:"text-orange-500"},2:{label:"P3",color:"text-blue-500"}},_=c&&c>=2?T[c]??null:null;let I=null;if(t?.date){const R=ls(Ms(t.date),new Date);R>0&&(I=R===1?"in 1 day":R<=14?`in ${R} days`:`in ${Math.round(R/7)} weeks`)}return{priorityMeta:_,dueCountdown:I}},[c,t?.date]),v=i.useMemo(()=>Ys.getOptimizedConfig(),[]),j=i.useMemo(()=>({container:{initial:r?{opacity:0,y:3}:!1,animate:r?{opacity:1,y:0}:{},transition:{duration:v.fasterDurations?Ut.instant:Ut.smooth,ease:In.naturalOut}},description:{initial:r?{opacity:0,y:2}:!1,animate:r?{opacity:1,y:0}:{},transition:{delay:v.fasterDurations?.05:.1,duration:v.fasterDurations?Ut.instant:Ut.smooth,ease:In.naturalOut}},badge:{initial:{opacity:0,scale:.9},animate:{opacity:1,scale:1},transition:{duration:Ut.quickHover,ease:In.naturalOut}}}),[r,v]);return!N.hasContent&&!r&&N.displayLabels.length===0&&N.gtdContexts.length===0?k?s.jsx("div",{className:"task-content mt-1",children:k}):null:g?!t?.date&&!n?.date&&!k?null:s.jsxs("div",{className:"task-content",style:{contain:"layout style"},children:[k&&s.jsx("div",{className:"mt-0.5",children:k}),t?.date&&s.jsx(Ho,{due:t}),n?.date&&s.jsx(Nl,{deadline:n})]}):s.jsxs(_e.div,{...j.container,className:"task-content hardware-accelerated",style:{..._l.opacity,contain:"layout style"},children:[k&&s.jsx("div",{className:"mb-1.5",children:k}),N.hasDescription?s.jsx(_e.div,{...j.description,className:S("transition-all duration-300 ease-[cubic-bezier(0.2,0.8,0.2,1)]",r?"text-foreground
20/90 text-base leading-relaxed mb-6 prose prose-sm max-w-none":S("text-foreground/70 line-clamp-2 max-sm:hidden mb-2 leading-relaxed",p.textSize)),children:s.jsx("p",{className:S("tracking-tight subpixel-antialiased will-change-opacity",r?"text-foreground/85 font-normal":"text-foreground/70 font-light"),children:e})}):null,N.hasMetadata&&s.jsxs("div",{className:S("space-y-3 transition-all duration-300 ease-[cubic-bezier(0.2,0.8,0.2,1)]",r?"opacity-100":"opacity-90","hardware-accelerated"),children:[s.jsx("div",{className:"hardware-accelerated",children:s.jsx(bw,{due:t,taskId:l,isFocused:r})}),n?.date&&s.jsx("div",{className:"hardware-accelerated",children:s.jsx(Nl,{deadline:n})}),N.gtdContexts.length>0&&s.jsx("div",{className:S("flex flex-wrap gap-1.5 mt-2 overflow-hidden","transition-[max-height,opacity] duration-300 ease-[cubic-bezier(0.2,0.8,0.2,1)]",r?"":"max-h-0 opacity-0 group-hover:max-h-20 group-hover:opacity-100 max-sm:hidden","hardware-accelerated"),children:N.gtdContexts.map(T=>s.jsx(_e.span,{...j.badge,className:S("text-xs px-3 py-1.5 rounded-full border shadow-sm","bg-primary/10 text-primary/90 dark:text-primary/80 border-primary/20","backdrop-blur-sm font-medium","premium-hover cursor-default","focus-ring"),style:_l.transform,children:T},T))}),u&&N.displayLabels.length>0&&s.jsx("div",{className:S("overflow-hidden hardware-accelerated","transition-[max-height,opacity] duration-300 ease-[cubic-bezier(0.2,0.8,0.2,1)]",r?"":"max-h-0 opacity-0 group-hover:max-h-20 group-hover:opacity-100 max-sm:hidden"),children:s.jsx("div",{className:"pt-1",children:s.jsx(kw,{labels:N.displayLabels})})}),r&&(C.priorityMeta||C.dueCountdown)&&s.jsx(_e.div,{initial:{opacity:0,y:5},animate:{opacity:1,y:0},transition:{delay:.2,duration:Ut.smooth,ease:In.naturalOut},className:"pt-2 border-t border-border/30 mt-4",children:s.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[s.jsx("div",{className:"flex items-center gap-3",children:C.priorityMeta&&s.jsxs("span",{className:S("flex items-center gap-1 font-semibold",C.priorityMeta.color),children:[s.jsx(Cs,{className:"h-3 w-3",strokeWidth:2.5}),C.priorityMeta.label]})}),C.dueCountdown&&s.jsx("span",{className:"opacity-80 font-medium tabular-nums",children:C.dueCountdown})]})})]})]})},qw=({isOpen:e,title:t,description:n,due:a,labels:r,onClose:o,onComplete:c})=>{const l=t.length>50;return e?s.jsx(te.div,{initial:{opacity:0}
20,animate:{opacity:1},exit:{opacity:0},className:"fixed inset-0 bg-background/95 backdrop-blur-sm z-50 flex items-center justify-center p-4",children:s.jsxs(te.div,{initial:{scale:.9,opacity:0},animate:{scale:1,opacity:1},exit:{scale:.9,opacity:0},className:"relative w-full max-w-2xl bg-card rounded-lg shadow-xl p-6",children:[s.jsx(W,{variant:"ghost",size:"icon",className:"absolute top-4 right-4",onClick:o,children:s.jsx(Ie,{className:"h-5 w-5"})}),s.jsxs("div",{className:"flex flex-col gap-6",children:[s.jsxs(te.div,{initial:{y:20,opacity:0},animate:{y:0,opacity:1},transition:{delay:.1},children:[s.jsx("h2",{className:S("mb-2",l?"text-xl leading-snug":"text-2xl font-semibold"),children:t}),s.jsx(_f,{description:n,due:a,labels:r,isFocused:!0,quadrant:"none"})]}),s.jsxs(te.div,{initial:{y:20,opacity:0},animate:{y:0,opacity:1},transition:{delay:.3},className:"flex justify-end gap-2",children:[s.jsx(W,{variant:"outline",onClick:o,children:"Close"}),s.jsx(W,{variant:"default",onClick:c,children:"Complete Task"})]})]})]})}):null},Ef=i.memo(({isFullScreen:e,showCommentsDialog:t,title:n,description:a,due:r,labels:o,taskId:c,apiKey:l,onCloseFullscreen:d,onCloseComments:m,onComplete:u})=>s.jsxs(s.Fragment,{children:[s.jsx(gf,{isOpen:t,onClose:m,taskId:c,apiKey:l,taskTitle:n}),s.jsx(Gt,{children:e&&s.jsx(qw,{isOpen:e,title:n,description:a,due:r,labels:o,onClose:d,onComplete:u})})]}));Ef.displayName="TaskDialogs";const Df=Ue.memo(({id:e,title:t,description:n,due:a,deadline:r,labels:o,isFocused:c,isFocusMode:l,onComplete:d,onFocus:m,onToggleFocusMode:u,quadrant:f,apiKey:p})=>{const[h,g]=Ue.useState(!1),[b,x]=Ue.useState(!1),y=i.useCallback(async N=>{N.stopPropagation();try{await d(N),g(!1)}catch{}},[d]),w=i.useCallback(N=>{N.stopPropagation(),x(!0)},[]),k=i.useCallback(N=>{N.stopPropagation(),m?.()},[m]);return s.jsxs(s.Fragment,{children:[s.jsxs(_e.div,{className:"flex items-start justify-between gap-2 mb-1.5",initial:!1,animate:c?{scale:1,opacity:1}:{scale:.98,opacity:.95},transition:{duration:.2,ease:"easeOut"},children:[s.jsx(df,{title:t,isFocused:c,taskId:e}),s.jsx(yf,{isFocusMode:l,isFocused:c,showCommentSection:b,onCommentClick:w,onFocusClick:k,onComplete:y,onToggleFocusMode:u,taskId:e,deadline:r})]}),s.jsx(Ef,{isFullScreen:h,showCommentsDialog:b,title:t,description:n,due:a,labels:o,taskId:e||"",apiKey:p,onCloseFullscreen:()=>g(!1),onCloseComments:()=>x(!1),onComplete:y})]})});Df.displayName="TaskHeader";const El={1:"bg-slate-100 text-slate-800 dark:bg-muted dark:text-slate-100 border-slate-300 dark:border-border",2:"bg-blue-100 text-blue-900 dark:bg-blue-900 dark:text-blue-100 border-blue-300 dark:border-blue-800",3:"bg-amber-100 text-amber-900 dark:bg-amber-900 dark:text-amber-100 border-amber-300 dark:border-amber-800",4:"bg-red-100 text-red-900 dark:bg-red-900 dark:text-red-100 border-red-300 dark:border-red-800"},Dl={1:"P4",2:"P3",3:"P2",4:"P1"},zw=e=>El[e||1]||El[1],Uw=e=>Dl[e||1]||Dl[1],Rf=i.memo(({priority:e,className:t})=>s.jsx(Ds,{className:S("text-xs font-medium px-2.5 py-0.5 rounded-full","transition-all duration-300 hardware-accelerated","border","shadow-sm","hover:shadow-md","active:scale-95",zw(e),t),children:Uw(e)}));Rf.displayName="PriorityBadge";const ja={quadrant:{urgentImportant:{bg:"quadrant-urgent-important",text:"text-red-600 dark:text-red-400",border:"border-red-200 dark:border-red-800",badge:"bg-red-100 text-red-800 dark:bg-red-900/20 dark:text-red-400"},important:{bg:"quadrant-important",text:"text-blue-600 dark:text-blue-400",border:"border-blue-200 dark:border-blue-800",badge:"bg-blue-100 text-blue-800 dark:bg-blue-900/20 dark:text-blue-400"},urgent:{bg:"quadrant-urgent",text:"text-orange-600 dark:text-orange-400",border:"border-orange-200 dark:border-orange-800",badge:"bg-orange-100 text-orange-800 dark:bg-orange-900/20 dark:text-orange-400"},neither:{bg:"quadrant-neither",text:"text-gray-600 dark:text-gray-400",border:"border-gray-200 dark:border-gray-700",badge:"bg-gray-100 text-gray-800 dark:bg-gray-800/40 dark:text-gray-400"}}},Bw=e=>{switch(e.toLowerCase()){case"do":case"do_first":case"urgent_important":return ja.quadrant.urgentImportant;case"schedule":case"important":return ja.quadrant.important;case"delegate":case"urgent":return ja.quadrant.urgent;default:return ja.quadrant.neither}},Hw=({quadrant:e,size:t="md",variant:n="outline",showLabel:a=!0,className:r})=>{const o=Bw(e),c=t==="sm"?"sm":t==="lg"?"lg":"default",d=(m=>{switch(m.toLowerCase()){case"do":case"do_first":case"urgent_important":return"Do First";case"schedule":case"important":return"Schedule";case"delegate":case"urgent":return"Delegate";default:return"Backlog"}})(e);return s.jsxs(Ds,{variant:n==="solid"?e.toLowerCase():"outline",size:c,className:S("transition-all rounded-md font-medium flex items-center gap-1.5",n!=="solid"&&o.text,n!=="solid"&&o.border,t==="sm"?"text-xs":"text-sm",r),children:[s.jsx(qp,{className:S("fill-current opacity-70",t==="sm"?"h-2.5 w-2.5":t==="lg"?"h-3.5 w-3.5":"h-3 w-3")}),a&&d]})},If=i.memo(({priority:e,quadrant:t,isFocused:n,showQuadrant:a=!0})=>!e&&!a?null:s.jsxs("div",{className:S("flex items-center gap-2 mt-3 pt-3 overflow-hidden transition-[max-height,opacity] duration-300",n?"border-t border-border/30":"max-h-0 opacity-0 group-hover:max-h-10 group-hover:opacity-100 max-sm:hidden"),children:[e&&s.jsx(Rf,{priority:e}),a&&n&&s.jsx(Hw,{quadrant:t,size:"sm",showLabel:!0})]}));If.displayName="TaskMetadata";const Vw={background:["radial-gradient(circle at 50% 50%, rgba(var(--primary), 0.4) 0%, transparent 75%)","radial-gradient(circle at 50% 50%, rgba(var(--primary), 0.7) 5%, transparent 85%)","radial-gradient(circle at 50% 50%, rgba(var(--primary), 0.4) 0%, transparent 75%)"],boxShadow:["0 0 20px 0 rgba(var(--primary), 0.3)","0 0 25px 0 rgba(var(--primary), 0.5)","0 0 20px 0 rgba(var(--primary), 0.3)"]},Kw={duration:5,repeat:1/0,repeatType:"reverse",ease:"easeInOut"},Yw=({isFocused:e})=>e?s.jsx(te.div,{className:"absolute inset-0 -z-10 overflow-hidden rounded-lg hardware-accelerated",initial:{opacity:0}
20,animate:{opacity:.5},exit:{opacity:0},transition:{duration:.3,ease:"easeOut"},children:s.jsx(te.div,{className:"w-full h-full",style:{willChange:"background, box-shadow"},animate:Vw,transition:Kw})}):null,Ww=["0 0 4px 0 rgba(var(--primary), 0.3)","0 0 8px 0 rgba(var(--primary), 0.5)","0 0 4px 0 rgba(var(--primary), 0.3)"],Gw=({isFocused:e})=>e?s.jsx(_e.div,{className:"absolute bottom-0 left-0 right-0 h-1 bg-gradient-to-r from-primary/20 via-primary/40 to-primary/20",initial:{scaleX:0,opacity:0},animate:{scaleX:1,opacity:1,boxShadow:Ww},exit:{scaleX:0,opacity:0},transition:{type:"spring",stiffness:300,damping:35,boxShadow:{duration:2,repeat:1/0,repeatType:"reverse",ease:"easeInOut"}},style:{originX:0,willChange:"transform, opacity, box-shadow"}}):null,Mf=i.createContext(void 0);function Qw({children:e}){const[t,n]=i.useState(new Set),a=i.useCallback(d=>{n(m=>{const u=new Set(m);return u.has(d)?u.delete(d):u.add(d),u})},[]),r=i.useCallback(()=>{n(new Set)},[]),o=i.useCallback(d=>t.has(d),[t]),c=i.useCallback(()=>t.size>0,[t]),l=i.useMemo(()=>({selectedTasks:t,toggleTaskSelection:a,clearSelection:r,isSelected:o,hasSelectedTasks:c}),[t,a,r,o,c]);return s.jsx(Mf.Provider,{value:l,children:e})}const $r=()=>{const e=i.useContext(Mf);if(!e)throw new Error("useTaskSelection must be used within a TaskSelectionProvider");return e},Lf=i.memo(({children:e,isFocused:t=!1,isFocusMode:n=!1,onFocus:a,className:r="",taskId:o,quadrant:c="neither",style:l})=>{const{isSelected:d,toggleTaskSelection:m,hasSelectedTasks:u}=$r(),{config:f}=Zt(),p=Fe(),h=i.useCallback(x=>{o&&(u()||x.ctrlKey||x.metaKey?(x.preventDefault(),x.stopPropagation(),m(o)):a&&n&&a())},[o,a,m,u,n]),g=o?d(o):!1,b=i.useMemo(()=>({...l,backfaceVisibility:"hidden",contain:"layout paint style"}),[l]);return s.jsxs("div",{onClick:h,style:b,className:S("relative w-full overflow-hidden bg-card border border-border/60 group",f.cardPadding,"max-sm:!p-2.5","max-sm:min-h-[64px]",f.cardRadius,"select-none cursor-pointer","density-resize","hover:-translate-y-[2px]",p?"shadow-sm dark:shadow-[0_1px_2px_rgba(0,0,0,0.3)]":"shadow-[0_1px_2px_rgba(0,0,0,0.04),0_6px_16px_-8px_rgba(0,0,0,0.10)] dark:shadow-[0_1px_2px_rgba(0,0,0,0.3),0_8px_20px_-10px_rgba(0,0,0,0.45)]","active:translate-y-0 active:scale-[0.985] active:shadow-sm active:duration-100",t&&"ring-1 ring-primary/25 border-primary/30 shadow-md -translate-y-[1px]",g&&["ring-2 ring-[#9b87f5]/70 border-[#9b87f5]/40","bg-[#9b87f5]/[0.05]","shadow-[0_4px_16px_-4px_rgba(155,135,245,0.35)]","hover:bg-[#9b87f5]/[0.08]"],r),children:[s.jsx("div",{"aria-hidden":!0,className:"quadrant-accent"}),s.jsx("div",{"aria-hidden":!0,className:`absolute inset-x-0 top-0 h-px pointer-events-none rounded-t-2xl
21                   bg-gradient-to-r from-transparent via-white/50 to-transparent
22                   dark:via-white/10`}),g&&s.jsx("div",{className:"absolute top-2.5 right-2.5 z-20",children:s.jsx("span",{className:`flex h-5 w-5 items-center justify-center rounded-full
23                       bg-[#9b87f5] text-white shadow-sm ring-2 ring-background
24                       animate-in zoom-in-50 duration-150`,children:s.jsx(Oe,{className:"w-3 h-3",strokeWidth:3})})}),!p&&s.jsx(Gt,{children:t&&s.jsx(Yw,{isFocused:t})}),s.jsx("div",{className:"relative z-10",children:e}),!p&&s.jsx(Gt,{children:t&&s.jsx(Gw,{isFocused:t})})]})});Lf.displayName="TaskWrapper";const Jw=({enabled:e})=>{if(!e)return{trigger:()=>{}};const t={particleCount:100,spread:120,origin:{y:.6},colors:["#FF69B4","#4CAF50","#FFD700","#00BCD4","#FF4081"],startVelocity:45,gravity:.7,ticks:300,shapes:["circle","square"],scalar:1.4,drift:.5,decay:.9};return{trigger:()=>{requestAnimationFrame(()=>{Ti(t)})}}},Af={smooth:[.25,.46,.45,.94]},Xw={initial:{scale:0,opacity:.6},animate:{scale:2.5,opacity:0,transition:{duration:.6,ease:Af.smooth}}},Zw={initial:{y:0},animate:{y:[-2,2,-2],transition:{duration:2,repeat:1/0,ease:Af.smooth}}},ev=({trigger:e,color:t="rgba(59, 130, 246, 0.5)",duration:n=.6,onComplete:a})=>{const[r,o]=i.useState([]);return i.useEffect(()=>{if(e){const c={id:Date.now(),x:50,y:50};o(l=>[...l,c]),setTimeout(()=>{o(l=>l.filter(d=>d.id!==c.id)),a?.()},n*1e3)}},[e,n,a]),s.jsx("div",{className:"absolute inset-0 pointer-events-none overflow-hidden rounded-lg",children:s.jsx(Gt,{children:r.map(c=>s.jsx(te.div,{className:"absolute rounded-full",style:{left:`${c.x}%`,top:`${c.y}%`,width:"20px",height:"20px",marginLeft:"-10px",marginTop:"-10px",backgroundColor:t},variants:Xw,initial:"initial",animate:"animate",exit:"initial"},c.id))})})},tv=zp,sv=Up,nv=Bp,av=["late","today","week","later","someday"],rv={late:"Late",today:"Today",week:"This week",later:"Later",someday:"Someday"},on=(e,t)=>ls(Bn(e),Bn(t));function ia(e,t=new Date){const n=Ye(e.due);if(!n)return"someday";const a=on(n,t);return a<0?"late":a===0?gt(e.due)&&n.getTime()<=t.getTime()?"late":"today":a<7?"week":"later"}function wc(e,t=new Set,n=new Date){const a=e.map((r,o)=>{const c=ia(r,n),l=Ye(r.due);return{task:r,index:o,bucket:av.indexOf(c),focus:t.has(r.id)?0:1,time:l?c==="today"&&!gt(r.due)?Number.MAX_SAFE_INTEGER:l.getTime():0,priority:r.priority||1}});return a.sort((r,o)=>r.focus-o.focus||r.bucket-o.bucket||r.time-o.time||o.priority-r.priority||r.index-o.index),a.map(r=>r.task)}function ov(e,t=new Date,n=new Set){const a=[];for(const r of e){const o=n.has(r.id)?"focus":ia(r,t),c=a[a.length-1];c&&c.bucket===o?c.tasks.push(r):a.push({bucket:o,label:o==="focus"?"":rv[o],tasks:[r]})}return a}function as(e,t){const n=on(e,t);return n===0?"Today":n===1?"Tomorrow":n>1&&n<7?Ee(e,"EEE"):e.getFullYear()===t.getFullYear()?Ee(e,"MMM d"):Ee(e,"MMM d, yyyy")}function Fr(e,t,n,a){if(!n)return e;const r=Tr(t,a);return/\d$/.test(e)?`${e} · ${r}`:`${e} ${r}`}function TT(e,t=new Date,n){const a=Ye(e.due);return a?Fr(as(a,t),a,gt(e.due),n):""}function Pf(e,t=new Date,n){const a=Ye(e.due);if(!a)return{text:"",late:!1};const r=on(a,t),o=gt(e.due),c=e.due?.isRecurring?" ↻":"";if(r<0)return{text:`${-r}d late${c}`,late:!0,lateDays:-r};if(r===0){if(!o)return{text:c.trim(),late:!1};const l=a.getTime()<=t.getTime();return{text:`${Tr(a,n)}${c}`,late:l,timed:!0,...l?{lateDays:0}:{}}}return{text:`${Fr(as(a,t),a,o,n)}${c}`,late:!1,timed:o}}function iv(e,t=new Date){const n=zi(e.deadline);if(!n)return null;const a=on(n,t);if(a<0)return{text:`deadline ${-a}d late`,late:!0};const r=as(n,t);return{text:`deadline ${a<=1?r.toLowerCase():r}`,late:!1}}function Of(e,t=new Date){let n=0,a=0,r=null;for(const o of e){const c=ia(o,t);
24if(c==="late")n++;else if(c==="today")a++;else if(c!=="someday"){const l=Ye(o.due);(!r||l<r)&&(r=l)}}return{late:n,today:a,next:!n&&!a&&r?as(r,t):void 0}}const cv={4:{label:"Priority 1",className:"text-red-500 dark:text-red-400"},3:{label:"Priority 2",className:"text-orange-500 dark:text-orange-400"},2:{label:"Priority 3",className:"text-blue-500 dark:text-blue-400"}},lv=e=>{switch(e?.toLowerCase()){case"do":case"do_first":return"border-l-red-400/70";case"schedule":case"important":return"border-l-blue-400/70";case"delegate":case"urgent":return"border-l-orange-400/70";case"backlog":case"neither":return"border-l-gray-400/70";default:return"border-l-border"}},dv=({subtask:e,quadrant:t,onComplete:n,childCount:a=0,childrenExpanded:r=!0,onToggleChildren:o})=>{const[c,l]=i.useState(!1),[d,m]=i.useState(!1),u=i.useRef();i.useEffect(()=>()=>window.clearTimeout(u.current),[]);const f=e.priority?cv[e.priority]??null:null,p=i.useMemo(()=>{const j=Ye(e.due);if(!j)return null;const T=Nr(j),_=Er(e.due);return{date:j,text:Fr(T?"Today":Ee(j,"MMM d"),j,gt(e.due)),isOverdue:_,isToday:T&&!_}},[e.due]),h=i.useMemo(()=>Ir((e.labels||[]).filter(j=>!j.startsWith("@"))).slice(0,3),[e.labels]),g=!!e.description?.trim(),b=a>0&&!!o,x=b||!!f||!!p||h.length>0||g,y=j=>{j.stopPropagation(),!c&&(l(!0),ut(15),u.current=window.setTimeout(()=>l(!1),5e3),n?n(e.id):window.dispatchEvent(new CustomEvent("task:complete",{detail:{taskId:e.id}})))},w=_r(e.due),k=j=>{en(e.id,j,w,!!e.due?.isRecurring),m(!1)},N=j=>{en(e.id,p?.date??_s(),j,!!e.due?.isRecurring,{kind:"time"})},C=p?.isOverdue?"text-red-500 dark:text-red-400 font-medium":p?.isToday?"text-blue-500 dark:text-blue-400 font-medium":"text-muted-foreground",v=j=>s.jsxs(Nt,{open:d,onOpenChange:m,children:[s.jsx(St,{asChild:!0,children:j}),s.jsx(Ct,{className:"w-auto max-h-[var(--radix-popover-content-available-height)] overflow-y-auto p-0 rounded-xl shadow-xl border-border/40",align:"start",onClick:T=>T.stopPropagation(),children:s.jsx(rn,{title:"Due date",value:p?.date,onChange:k,time:{value:w,onChange:N},setActivePopover:()=>m(!1)})})]});return s.jsxs("div",{className:S("group/subtask flex items-center gap-2 rounded-lg","border border-border/30 border-l-2",lv(t),"bg-background/50 dark:bg-background/30 px-2.5 py-1.5","transition-all duration-200 hover:bg-background/80 hover:border-border/60 hover:shadow-sm",c&&"opacity-40"),onClick:j=>j.stopPropagation(),children:[s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("span",{className:S("block truncate text-[13px] font-medium text-foreground/90 leading-snug",c&&"line-through"),title:e.title,children:e.title}),x&&s.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-x-2.5 gap-y-1",children:[b&&s.jsxs("button",{type:"button",onClick:j=>{j.stopPropagation(),o()},"aria-expanded":r,"aria-label":`${r?"Hide":"Show"} ${a} nested ${a===1?"subtask":"subtasks"}`,className:S("flex items-center gap-0.5 text-[10px] font-medium rounded px-1 -mx-1","text-muted-foreground/70 transition-colors hover:bg-muted/50 hover:text-foreground cursor-pointer"),children:[s.jsx(pt,{className:S("h-2.5 w-2.5 transition-transform duration-200",r&&"rotate-90")}),!r&&a]}),f&&s.jsx("span",{title:f.label,"aria-label":f.label,children:s.jsx(Cs,{className:S("h-2.5 w-2.5",f.className),strokeWidth:2.5})}),p&&(e.due?.isRecurring?s.jsxs("span",{className:S("flex items-center gap-1 text-[10px] whitespace-nowrap",C),children:[s.jsx(Zs,{className:"h-2.5 w-2.5 shrink-0"}),p.text]}):v(s.jsxs("button",{type:"button",onClick:j=>j.stopPropagation(),"aria-label":"Change due date",className:S("flex items-center gap-1 text-[10px] whitespace-nowrap rounded px-1 -mx-1","transition-colors hover:bg-muted/50 cursor-pointer",C),children:[s.jsx(Zs,{className:"h-2.5 w-2.5 shrink-0"}),p.text]}))),h.map(j=>s.jsxs("span",{className:"flex items-center gap-1 text-[10px] text-muted-foreground/80 bg-muted/40 rounded-full px-1.5 py-px",children:[s.jsx(vr,{className:"h-2 w-2"}),j]},j)),g&&s.jsx("span",{title:"Has description","aria-label":"Has description",children:s.jsx(Hp,{className:"h-3 w-3 text-muted-foreground/60"})})]})]}),!p&&v(s.jsx("button",{type:"button",onClick:j=>j.stopPropagation(),"aria-label":"Add due date",className:S("flex h-6 w-6 shrink-0 items-center justify-center rounded-full text-muted-foreground
24/70","opacity-0 transition-all duration-200 hover:bg-muted/60 hover:text-foreground","group-hover/subtask:opacity-100 focus-visible:opacity-100 [@media(pointer:coarse)]:opacity-60",d&&"opacity-100"),children:s.jsx(Pi,{className:"h-3.5 w-3.5"})})),s.jsxs("button",{type:"button",onClick:y,"aria-label":`Complete subtask: ${e.title}`,className:S("relative flex h-6 w-6 shrink-0 items-center justify-center rounded-full","transition-all duration-200 hover:bg-green-500/10 active:scale-90","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-green-400/40",c&&"pointer-events-none"),children:[s.jsx(Di,{className:S("h-[16px] w-[16px] transition-all duration-200 text-slate-300 dark:text-slate-400","group-hover/subtask:text-green-500",c&&"opacity-0 scale-75"),strokeWidth:2}),s.jsx(Li,{className:S("absolute h-[16px] w-[16px] text-green-500 opacity-0 scale-75 transition-all duration-200",c&&"opacity-100 scale-100"),strokeWidth:1.8})]})]})},uv=(e,t)=>{const n=(t.priority||1)-(e.priority||1);return n!==0?n:!e.due?.date&&!t.due?.date?0:e.due?.date?t.due?.date?(Ye(e.due)?.getTime()??0)-(Ye(t.due)?.getTime()??0):-1:1},mv=({subtask:e,depth:t,quadrant:n,childrenByParent:a,onComplete:r})=>{const[o,c]=i.useState(!0),l=a.get(e.id)?.length??0;return s.jsxs("div",{className:S("relative pl-3 pb-1.5 last:pb-0","before:absolute before:left-0 before:top-0 before:bottom-0 before:border-l before:border-border/50 last:before:hidden","after:absolute after:left-0 after:top-0 after:h-[15px] after:w-2.5 after:rounded-bl-lg after:border-b after:border-l after:border-border/50"),children:[s.jsx(dv,{subtask:e,quadrant:n,onComplete:r,childCount:l,childrenExpanded:o,onToggleChildren:()=>c(d=>!d)}),l>0&&o&&s.jsx($f,{parentId:e.id,depth:t+1,quadrant:n,childrenByParent:a,onComplete:r})]})},$f=({parentId:e,depth:t,quadrant:n,childrenByParent:a,onComplete:r})=>{const o=a.get(e);if(!o?.length)return null;const c=[...o].sort(uv);return s.jsx("div",{className:S("mt-1.5",t===1&&"ml-2",t>1&&"animate-in fade-in-0 slide-in-from-top-1 duration-200"),children:c.map(l=>s.jsx(mv,{subtask:l,depth:t,quadrant:n,childrenByParent:a,onComplete:r},l.id))})},fv=({parentTaskId:e,quadrant:t,variant:n="card",defaultOpen:a=!0,onCompleteSubtask:r,className:o})=>{const{nestedSubtasksByParent:c,nestedDescendantCountByRoot:l}=oa(),{nestSubtasks:d}=ds(),[m,u]=i.useState(a),f=l.get(e)??0;if(!d||f===0)return null;const p=`${f} ${f===1?"subtask":"subtasks"}`;return s.jsxs(tv,{open:m,onOpenChange:u,className:S(n==="card"?"mt-1.5":"mt-3",o),children:[s.jsxs(sv,{onClick:h=>h.stopPropagation(),"aria-label":`${m?"Hide":"Show"} ${p}`,className:S("group flex items-center gap-1.5 rounded-full border border-border/40 bg-muted/40","text-muted-foreground transition-colors hover:bg-muted/70 hover:text-foreground",n==="card"?"px-2 py-0.5 text-[11px]":"px-2.5 py-1 text-xs"),children:[s.jsx(eu,{className:n==="card"?"h-3 w-3":"h-3.5 w-3.5"}),s.jsx("span",{className:"font-medium",children:p}),s.jsx(pt,{className:S("transition-transform duration-200",n==="card"?"h-3 w-3":"h-3.5 w-3.5",m&&"rotate-90")})]}),s.jsx(nv,{children:s.jsx($f,{parentId:e,depth:1,quadrant:t,childrenByParent:c,onComplete:r})})]})};function hv(e){const t=e.toLowerCase();if(t.includes("overdue"))return"Overdue";if(t.includes("due today"))return"Due today";const n=t.match(/due within (\d+) day/);if(n){const a=Number(n[1]);return a===1?"Due tomorrow":`Due within ${a} days`}return"Due soon"}const pv={do:"Do First",schedule:"Schedule",delegate:"Delegate",backlog:"Backlog"};function Ff(e){return pv[e?.toLowerCase()]??"its old spot"}function qf(e){const t=e?.toLowerCase();return t==="do"||t==="schedule"||t==="delegate"||t==="backlog"?t:null}function gv(e){return e<=0?"":e===1?"1 moved here · Review":`${e} moved here · Review`}function xv(e){return qf(e)?`Move to ${Ff(e)}`:"Remove label"}function _T(e){const t=e.toLowerCase();if(t.includes("overdue"))return"overdue";if(t.includes("due today"))return"today";const n=t.match(/due within (\d+) day/);return n&&Number(n[1])===1?"tomorrow":"soon"}const ET=["overdue","today","tomorrow","soon"],DT={overdue:"Overdue",today:"Due today",tomorrow:"Due tomorrow",soon:"Coming up"},zf=i.createContext(null),bv=7;function yv({apiKey:e,doFirstTaskIds:t,children:n}){const{session:a}=we.useSessionContext(),r=at(),[o,c]=i.useState(new Map),[l,d]=i.useState(!1),m=i.useRef(o);m.current=o;const u=i.useMemo(()=>
24{if(o.size===0)return o;const v=new Map;for(const[j,T]of o)t.has(j)&&v.set(j,T);return v},[o,t]),f=i.useRef(u);f.current=u;const p=a?.user?.id,h=i.useCallback(async()=>{if(!p){c(new Map);return}const v=new Date(Date.now()-bv*24*60*60*1e3).toISOString(),{data:j,error:T}=await B.from("auto_prioritization_logs").select("id, task_id, original_quadrant, reason, prioritized_at").eq("user_id",p).is("dismissed_at",null).gt("prioritized_at",v).order("prioritized_at",{ascending:!1});if(T)return;const _=new Map;for(const I of j??[])!I.task_id||_.has(I.task_id)||_.set(I.task_id,{id:I.id,task_id:I.task_id,original_quadrant:I.original_quadrant??"unassigned",reason:I.reason??"",prioritized_at:I.prioritized_at??new Date().toISOString()});c(_)},[p]);i.useEffect(()=>{h()},[h]),i.useEffect(()=>{if(!p)return;const v=B.channel(Zm(`auto_prioritization_logs:${p}`)).on("postgres_changes",{event:"*",schema:"public",table:"auto_prioritization_logs",filter:`user_id=eq.${p}`},()=>{h()}).subscribe();return()=>{B.removeChannel(v)}},[p,h]);const g=i.useCallback(v=>{c(j=>{if(!j.has(v))return j;const T=new Map(j);return T.delete(v),T})},[]),b=i.useCallback(v=>{c(j=>{const T=new Map(j);return T.set(v.task_id,v),T})},[]),x=i.useCallback(async v=>{const{data:j,error:T}=await B.from("auto_prioritization_logs").update({dismissed_at:new Date().toISOString()}).eq("id",v.id).is("dismissed_at",null).select("id");return!(T||!j||j.length===0)},[]),y=i.useCallback(async v=>{const j=m.current.get(v);if(!j)return;g(v),await x(j)||b(j)},[x,g,b]),w=i.useCallback(async v=>{const j=m.current.get(v);if(!j||!e)return;g(v);const T=qf(j.original_quadrant);let _;r.setQueryData(["tasks"],I=>Array.isArray(I)?I.map(R=>R.id!==v?R:(_=R.labels??[],{...R,labels:Io(R.labels,T||null)})):I);try{const I=new Ke(e),R=await I.getTask(v),M=Array.isArray(R?.labels)?R.labels:[],P=Io(M,T||null);await I.updateTaskLabels(v,P),await x(j),r.invalidateQueries({queryKey:["tasks"]})}catch{if(_){const R=_;r.setQueryData(["tasks"],M=>Array.isArray(M)?M.map(P=>P.id===v?{...P,labels:R}:P):M)}b(j)}},[e,x,r,g,b]),k=i.useCallback(async()=>{const v=Array.from(f.current.values());if(v.length===0)return;c(new Map);const j=[];await Promise.all(v.map(async T=>{await x(T)||j.push(T)})),j.length>0&&c(T=>{const _=new Map(T);for(const I of j)_.set(I.task_id,I);return _})},[x]),N=i.useCallback(async()=>{const v=Array.from(f.current.values());if(v.length!==0)for(const j of v)await w(j.task_id)},[w]),C=i.useMemo(()=>({entries:u,count:u.size,reviewOpen:l,openReview:()=>d(!0),closeReview:()=>d(!1),keep:y,revert:w,keepAll:k,revertAll:N}),[u,l,y,w,k,N]);return s.jsx(zf.Provider,{value:C,children:n})}function xn(){const e=i.useContext(zf);return e||{entries:new Map,count:0,reviewOpen:!1,openReview:()=>{},closeReview:()=>{},keep:async()=>{},revert:async()=>{},keepAll:async()=>{},revertAll:async()=>{}}}function vc(e){const{entries:t}=xn();return t.get(e)}const ca=Ei,wv=br,Uf=i.forwardRef(({className:e,...t},n)=>s.jsx(ln,{className:S("fixed inset-0 z-[60] bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t,ref:n}));Uf.displayName=ln.displayName;const vv=Xn("fixed z-[60] gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:duration-500",{variants:{side:{top:"inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",bottom:"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",left:"inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",right:"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm"}},defaultVariants:{side:"right"}}),bn=i.forwardRef(({side:e="right",className:t,overlayClassName:n,children:a,...r},o)=>s.jsxs(wv,{children:[s.jsx(Uf,{className:n}),s.jsxs(dn,{ref:o,className:S(vv({side:e}),t),...r,children:[a,s.jsxs(yr,{className:"absolute right-4 top-4 roun
24ded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-secondary",children:[s.jsx(Ie,{className:"h-4 w-4"}),s.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));bn.displayName=dn.displayName;const Bf=({className:e,...t})=>s.jsx("div",{className:S("flex flex-col space-y-2 text-center sm:text-left",e),...t});Bf.displayName="SheetHeader";const Rs=i.forwardRef(({className:e,...t},n)=>s.jsx(un,{ref:n,className:S("text-lg font-semibold text-foreground",e),...t}));Rs.displayName=un.displayName;const qr=i.forwardRef(({className:e,...t},n)=>s.jsx(wr,{ref:n,className:S("text-sm text-muted-foreground",e),...t}));qr.displayName=wr.displayName;const ts=e=>{e.stopPropagation()};function kc({entry:e,onKeep:t,onRevert:n}){const[a,r]=i.useState(!1),[o,c]=i.useState(!1),l=Fe(),d=async h=>{if(ts(h),!o){c(!0);try{await t(),r(!1)}finally{c(!1)}}},m=async h=>{if(ts(h),!o){c(!0);try{await n(),r(!1)}finally{c(!1)}}},u=s.jsxs("div",{className:"space-y-3.5",children:[s.jsxs("div",{className:"space-y-1",children:[s.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] font-medium uppercase tracking-wider text-muted-foreground",children:[s.jsx("span",{"aria-hidden":!0,className:"block h-1 w-1 rounded-full bg-amber-500 dark:bg-amber-300"}),"Auto-prioritize"]}),s.jsx("div",{className:"text-base font-semibold leading-tight",children:hv(e.reason)}),e.original_quadrant&&e.original_quadrant!=="unassigned"&&s.jsxs("div",{className:"text-sm text-muted-foreground",children:["From ",Ff(e.original_quadrant)]})]}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx(W,{type:"button",size:"sm",variant:"ghost",className:"flex-1",onClick:d,disabled:o,children:"Keep here"}),s.jsx(W,{type:"button",size:"sm",variant:"secondary",className:"flex-1",onClick:m,disabled:o,children:xv(e.original_quadrant)})]})]}),f=S("absolute bottom-2 right-2 z-20","grid h-7 w-7 place-items-center rounded-full","transition-[background-color,transform] duration-200","hover:bg-foreground
24/[0.06] focus-visible:bg-foreground/[0.08]","focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-foreground/20",a&&"bg-foreground/[0.06]"),p=s.jsx("span",{"aria-hidden":!0,className:S("block h-1.5 w-1.5 rounded-full","bg-amber-500 dark:bg-amber-300","shadow-[0_0_0_3px_rgba(245,158,11,0.12)] dark:shadow-[0_0_0_3px_rgba(252,211,77,0.10)]")});return l?s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button","aria-label":"Review why this task is in Do First",className:f,onPointerDown:ts,onClick:h=>{ts(h),r(!0)},children:p}),s.jsx(ca,{open:a,onOpenChange:r,children:s.jsxs(bn,{side:"bottom",className:"rounded-t-2xl pb-[max(env(safe-area-inset-bottom),1rem)]",onClick:ts,children:[s.jsx(Bf,{className:"text-left",children:s.jsx(Rs,{className:"sr-only",children:"Moved to Do First"})}),s.jsx("div",{className:"pt-2",children:u})]})})]}):s.jsxs(Nt,{open:a,onOpenChange:r,children:[s.jsx(St,{asChild:!0,children:s.jsx("button",{type:"button","aria-label":"Review why this task is in Do First",className:f,onPointerDown:ts,onClick:ts,children:p})}),s.jsx(Ct,{side:"top",align:"end",sideOffset:6,className:"w-72 p-3.5",onClick:ts,children:u})]})}const jc=i.createContext(new Set),Hf=i.createContext(void 0),kv=({focusTaskIds:e,firstOpenId:t,children:n})=>s.jsx(jc.Provider,{value:e,children:s.jsx(Hf.Provider,{value:t,children:n})}),Nc=e=>i.useContext(jc).has(e),la=()=>i.useContext(jc),jv=()=>i.useContext(Hf),Vf=i.memo(({id:e,title:t,description:n,index:a,due:r,deadline:o,labels:c,priority:l,onComplete:d,isFocused:m,onFocus:u,isFocusMode:f,quadrant:p,className:h="",apiKey:g,parent_id:b,parentAbove:x=!1})=>{const[y]=ct("show-confetti",!0),w=i.useMemo(()=>Jw({enabled:y}),[y]),k=i.useRef(null),[N,C]=i.useState(!1),v=i.useMemo(()=>{const L=p.toLowerCase();return L==="do"||L==="do_first"},[p]),j=vc(e),{keep:T,revert:_}=xn(),I=Nc(e),R=i.useMemo(()=>{switch(p.toLowerCase()){case"do":case"do_first":return"hover:border-red-300/60 focus:border-red-400/70 hover:bg-red-50/20 hover:shadow-[0_4px_14px_-2px_rgba(248,113,113,0.25)]";case"schedule":case"important":return"hover:border-blue-300/60 focus:border-blue-400/70 hover:bg-blue-50/20 hover:shadow-[0_4px_14px_-2px_rgba(147,197,253,0.25)]";case"delegate":case"urgent":return"hover:border-orange-300/60 focus:border-orange-400/70 hover:bg-orange-50/20 hover:shadow-[0_4px_14px_-2px_rgba(251,146,60,0.25)]";default:return"hover:border-stone-300/60 focus:border-stone-400/70 hover:bg-stone-50/20 hover:shadow-[0_4px_14px_-2px_rgba(138,133,128,0.25)]"}},[p]),M=i.useMemo(()=>{switch(p.toLowerCase()){case"do":case"do_first":return"239 68 68";case"schedule":case"important":return"59 130 246";case"delegate":case"urgent":return"251 146 60";default:return"138 133 128"}},[p]),P=i.useMemo(()=>({"--quadrant-rgb":I?"251 191 36":M}),[M,I]),E=i.useMemo(()=>{switch(p.toLowerCase()){case"do":case"do_first":return"rgba(248, 113, 113, 0.4)";case"schedule":case"important":return"rgba(59, 130, 246, 0.4)";case"delegate":case"urgent":return"rgba(251, 146, 60, 0.4)";default:return"rgba(138, 133, 128, 0.4)"}},[p]),D=i.useCallback(async L=>{L.stopPropagation(),C(!0),setTimeout(()=>C(!1),600),y&&requestAnimationFrame(()=>{w.trigger()}),await d()},[y,d,w]);return s.jsx("div",{ref:k,className:"hardware-accelerated","data-task-id":e,children:s.jsxs(Lf,{isFocused:m,isFocusMode:f,onFocus:u,className:S(h,R,I&&["border-amber-400/40","bg-gradient-to-r from-amber-400/[0.10] via-amber-400/[0.03] to-transparent"]),style:P,taskId:e,quadrant:p,children:[s.jsx(ev,{trigger:N,color:E,duration:.6}),I&&s.jsxs("span",{className:"mb-1 inline-flex items-center gap-1 text-[10px] font-medium uppercase tracking-wide text-amber-600 dark:text-amber-400",children:[s.jsx(Yt,{className:"h-2.5 w-2.5 fill-current"}),"Focus"]}),s.jsxs("div",{className:"flex flex-col space-y-1.5",children:[s.jsx(Df,{id:e,title:t,description:n,due:r,deadline:o,labels:c,priority:l,isFocused:!!m,isFocusMode:!!f,onComplete:D,onFocus:u,quadrant:p,apiKey:g}),s.jsx(_f,{description:n,due:r,deadline:o,labels:c,isFocused:!!m,quadrant:p,taskId:e,parentId:b,parentAbove:x}),s.jsx(fv,{parentTaskId:e,quadrant:p}),(l||m)&&s.jsx(If,{priority:l,quadrant:p,isFocused:!!m,showQuadrant:!!m})]}),v&&j&&s.jsx(kc,{entry:j,onKeep:()=>T(e),onRevert:()=>_(e)})]})})});Vf.displayName="TaskCard";const cn=Ys.getOptimizedConfig();cn.fasterDurations?Ut.instant:Ut.standard;const Nv=cn.reducedStiffness?{type:"tween",duration:Ut.instant,ease:In.snapOut}:Tf.taskCard;cn.fasterDurations,cn.fasterDurations;cn.reducedStiffness;cn.fasterDurations||Tf.modal;const fr=new Set,Rl=new Set,Ko=new Set,Sv=e=>{fr.add(e)},Il=e=>{fr.delete(e)},Cv=e=>{e&&typeof e.disconnect=="function"&&e.disconnect(),Ko.delete(e)},Tv=()=>
24{fr.forEach(e=>{clearTimeout(e)}),fr.clear(),Rl.forEach(e=>{cancelAnimationFrame(e)}),Rl.clear(),Ko.forEach(e=>{e&&typeof e.disconnect=="function"&&e.disconnect()}),Ko.clear()};typeof window<"u"&&window.addEventListener("beforeunload",Tv);const _v=760,Ev=({isVisible:e,onComplete:t,size:n="md"})=>{const[a,r]=i.useState(!1),o=i.useRef(null);i.useEffect(()=>{if(e&&!a){r(!0),o.current&&(clearTimeout(o.current),Il(o.current));const m=setTimeout(()=>{r(!1),t?.(),o.current=null},_v);Sv(m),o.current=m}return()=>{o.current&&(clearTimeout(o.current),Il(o.current),o.current=null)}},[e,t,a]);const c={sm:40,md:56,lg:72}[n],l={sm:18,md:26,lg:34}[n],d={type:"spring",stiffness:420,damping:17,mass:.7};return s.jsx(Gt,{mode:"wait",children:a&&s.jsxs(_e.div,{className:"absolute inset-0 z-50 flex items-center justify-center pointer-events-none",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.14},children:[s.jsx(_e.div,{"aria-hidden":!0,className:"absolute rounded-full",style:{width:c*2.4,height:c*2.4,background:"radial-gradient(circle, rgba(16,185,129,0.30) 0%, rgba(16,185,129,0) 70%)"},initial:{scale:.5,opacity:0},animate:{scale:1.15,opacity:[0,.9,0]},transition:{duration:.62,ease:"easeOut"}}),s.jsx(_e.div,{"aria-hidden":!0,className:"absolute rounded-full border-2 border-emerald-400/70",style:{width:c,height:c},initial:{scale:.7,opacity:.85},animate:{scale:2,opacity:0},transition:{duration:.6,ease:[.22,1,.36,1]}}),s.jsx(_e.div,{className:`relative flex items-center justify-center rounded-full
25                       bg-gradient-to-br from-emerald-400 to-emerald-500
26                       shadow-[0_8px_24px_-6px_rgba(16,185,129,0.55)]
27                       ring-1 ring-white/25`,style:{width:c,height:c},initial:{scale:0,opacity:0},animate:{scale:1,opacity:1},exit:{scale:1.12,opacity:0},transition:d,children:s.jsx(_e.div,{initial:{scale:.2,opacity:0},animate:{scale:1,opacity:1},transition:{...d,delay:.09},children:s.jsx(Oe,{width:l,height:l,className:"text-white",strokeWidth:3,strokeLinecap:"round",strokeLinejoin:"round"})})})]})})},jn=96,Ml=10,Dv=450,Rv=220,Kf=({children:e,onComplete:t,onSnooze:n,onLongPress:a,disabled:r=!1,style:o})=>{const[c,l]=i.useState(0),[d,m]=i.useState(!1),[u,f]=i.useState(!1),p=i.useRef(null),h=i.useRef(!1),g=i.useRef(!1),b=i.useRef(null),x=i.useRef(null),y=i.useRef(!1),w=typeof n=="function",k=typeof a=="function",N=i.useCallback(()=>{b.current!==null&&(window.clearTimeout(b.current),b.current=null),x.current!==null&&(window.clearTimeout(x.current),x.current=null),f(!1)},[]),C=i.useCallback(()=>{p.current=null,h.current=!1,g.current=!1,N()},[N]),v=i.useCallback(R=>{if(r||d)return;const M=R.touches[0];p.current={x:M.clientX,y:M.clientY},h.current=!1,g.current=!1,y.current=!1,k&&(N(),x.current=window.setTimeout(()=>{x.current=null,f(!0)},Rv),b.current=window.setTimeout(()=>{b.current=null,y.current=!0,f(!1),ut([10,20,10]),a?.()},Dv))},[r,d,k,N,a]),j=i.useCallback(R=>{if(!p.current||r||d)return;const M=R.touches[0],P=M.clientX-p.current.x,E=M.clientY-p.current.y;if((Math.abs(P)>8||Math.abs(E)>8)&&N(),!h.current){if(Math.abs(E)>Math.abs(P)&&Math.abs(E)>Ml){C();return}Math.abs(P)>Ml&&Math.abs(P)>Math.abs(E)&&(h.current=!0)}if(h.current){const D=w?P:Math.max(0,P);l(D);const L=Math.abs(D)>=jn;!g.current&&L?(g.current=!0,ut(15)):g.current&&!L&&(g.current=!1)}},[r,d,C,w,N]),T=i.useCallback(R=>{if(N(),y.current){R.cancelable&&R.preventDefault(),y.current=!1,C();return}if(!h.current){C();return}m(!0),c>=jn?(l(window.innerWidth),t(),window.setTimeout(()=>{l(0),m(!1)},180)):w&&c<=-jn?(l(-window.innerWidth),n?.(),window.setTimeout(()=>{l(0),m(!1)},180)):(l(0),window.setTimeout(()=>m(!1),180)),C()},[c,t,n,w,C,N]),_=Math.min(1,Math.max(0,c)/jn),I=Math.min(1,Math.max(0,-c)/jn);return s.jsxs("div",{style:{...o,position:"relative",overflow:"hidden"},children:[s.jsx("div",{className:"absolute inset-0 flex items-center pl-6 rounded-xl bg-emerald-600",style:{opacity:_},"aria-hidden":!0,children:s.jsx("span",{className:"flex items-center justify-center rounded-full bg-white/20 text-white",style:{height:36,width:36,transform:`scale(${.6+_*.4})`},children:s.jsx(Oe,{className:"h-5 w-5",strokeWidth:3})})}),w&&s.jsx("div",{className:"absolute inset-0 flex items-center justify-end pr-6 rounded-xl bg-amber-500",style:{opacity:I}
27,"aria-hidden":!0,children:s.jsxs("span",{className:"flex items-center gap-1.5 text-white font-semibold text-sm",style:{transform:`scale(${.7+I*.3})`},children:[s.jsx(os,{className:"h-5 w-5",strokeWidth:2.5}),"Tomorrow"]})}),s.jsx("div",{onTouchStart:v,onTouchMove:j,onTouchEnd:T,onTouchCancel:T,style:{transform:u?`translateX(${c}px) scale(1.02)`:`translateX(${c}px)`,transition:d?"transform 180ms ease-out":u?"transform 220ms cubic-bezier(0.32, 0.72, 0, 1), box-shadow 220ms ease-out":"transform 180ms ease-out, box-shadow 180ms ease-out",boxShadow:u?"0 14px 32px -10px rgba(0, 0, 0, 0.28)":void 0,borderRadius:u?"12px":void 0,touchAction:"pan-y",position:"relative",zIndex:u?5:void 0},children:e})]})};Kf.displayName="SwipeToCompleteRow";let Na=null,ys=null;const Iv=()=>(Na&&ys?.isConnected||(ys=document.createElement("canvas"),ys.className="mx-burst",ys.setAttribute("aria-hidden","true"),document.body.appendChild(ys),Na=Ti.create(ys,{resize:!0})),Na),Mv=()=>{try{return window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{return!0}},Lv=e=>"#"+e.trim().split(/\s+/).map(t=>Math.round(+t).toString(16).padStart(2,"0")).join(""),Av=(e,t)=>{if(Mv())return;const n=e.getBoundingClientRect();if(!n.width)return;const a=Iv(),r=ys,o=Math.max(0,Math.round(document.querySelector(".mx-header")?.getBoundingClientRect().bottom??0)),c=window.innerHeight-o;r.style.top=`${o}px`,r.style.height=`${c}px`;const l=getComputedStyle(document.documentElement),d=u=>{const f=l.getPropertyValue(u);return f.trim()?Lv(f):null},m=[d(`--q-${t}`),d("--q-done"),d("--q-focus")].filter(Boolean);a({particleCount:14,spread:70,startVelocity:13,gravity:1.1,decay:.88,ticks:55,scalar:.65,angle:60,origin:{x:(n.left+n.width/2)/window.innerWidth,y:(n.top+n.height/2-o)/c},colors:m.length?m:void 0,shapes:["circle","square"],disableForReducedMotion:!0})},Ll={4:"P1",3:"P2",2:"P3"},Al=10,Yf=i.memo(({task:e,quadrant:t,completing:n,onComplete:a,parentAbove:r=!1})=>{const{id:o,title:c,due:l,deadline:d,labels:m,priority:u,project_id:f}=e,p=Nc(o),{showTags:h,nestSubtasks:g}=ds(),{nestedDescendantCountByRoot:b}=oa(),x=g?b.get(o)??0:0,y=Pe(D=>D.projectNames[f]),[w]=ct("show-confetti",!0),k=vc(o),N=yc(e,{parentAbove:r}),{keep:C,revert:v}=xn(),j=ra(i.useMemo(()=>[e],[e])),T=i.useMemo(()=>{const D=new Date,L=[];u&&Ll[u]&&L.push({key:"p",className:"mx-meta-priority",node:s.jsxs(s.Fragment,{children:[s.jsx(Cs,{className:"mx-meta-icon","aria-hidden":!0}),Ll[u]]})});const A=Ye(l);if(A){const K=on(A,D),X=K<0||gt(l)&&A.getTime()<=D.getTime();L.push({key:"due",className:X?"mx-meta-late":void 0,node:K<0?`${as(A,D)} · ${-K}d late`:Fr(as(A,D),A,gt(l))})}l?.isRecurring&&L.push({key:"rec",node:s.jsx("span",{"aria-label":"Recurring",children:"↻"})});const H=zi(d);if(H&&L.push({key:"dl",className:on(H,D)<0?"mx-meta-late":void 0,node:s.jsxs("span",{"aria-label":`Deadline ${as(H,D)}`,children:[s.jsx(os,{className:"mx-meta-icon","aria-hidden":!0,"data-qa":"deadline-icon"}),as(H,D)]})}),y&&y!=="Inbox"&&L.push({key:"proj",node:y}),h){const K=Ir(m);K.length&&L.push({key:"tags",node:K.join(" ")})}return x>0&&L.push({key:"sub",node:s.jsxs("span",{"aria-label":`${x} ${x===1?"subtask":"subtasks"}`,children:[s.jsx(gu,{className:"mx-meta-icon","aria-hidden":!0}),x]})}),L},[u,l,d,y,h,m,x,j]),_=i.useRef(null),I=i.useCallback(D=>{const L=D.touches[0];_.current={x:L.clientX,y:L.clientY,moved:!1}},[]),R=i.useCallback(D=>{const L=_.current;if(!L)return;const A=D.touches[0];(Math.abs(A.clientX-L.x)>Al||Math.abs(A.clientY-L.y)>Al)&&(L.moved=!0)},[]),M=i.useCallback(()=>{_.current?.moved||window.dispatchEvent(new CustomEvent("task:peek",{detail:{task:e,quadrant:t}}))},[e,t]),P=i.useCallback(async D=>{if(D.stopPropagation(),n)return;const L=D.currentTarget;w&&requestAnimationFrame(()=>Av(L,t)),await a()},[n,w,t,a]),E=t==="do";return s.jsxs("div",{className:S("mx-row",T.length===0&&!N&&"is-single",n&&"is-completing"),"data-task-id":o,onClick:M,onTouchStart:I,onTouchMove:R,children:[s.jsx("button",{type:"button",className:"mx-ring","aria-label":"Mark task as complete",onClick:P,children:s.jsx("span",{className:"mx-ring-circle","aria-hidden":!0,
27children:s.jsx(Oe,{className:"mx-ring-check",strokeWidth:3})})}),s.jsxs("div",{className:"mx-row-body",children:[s.jsxs("button",{type:"button",className:"mx-row-open","aria-haspopup":"dialog",children:[s.jsxs("span",{className:"mx-row-title",children:[p&&s.jsx(Yt,{className:"mx-row-star","aria-label":"Today's focus"}),c]}),N&&s.jsxs("span",{className:"mx-row-parent","data-qa":"parent-crumb",title:N.known?`Subtask of ${N.text}`:"Subtask",onClick:N.activate,children:[s.jsx("span",{"aria-hidden":!0,children:"↳ "}),N.known&&s.jsx("span",{className:"sr-only",children:"Subtask of "}),N.text]}),T.length>0&&s.jsx("span",{className:"mx-row-meta",children:T.map((D,L)=>s.jsxs(Ue.Fragment,{children:[L>0&&s.jsx("span",{className:"mx-meta-sep","aria-hidden":!0,children:" · "}),s.jsx("span",{className:D.className,children:D.node})]},D.key))})]}),E&&k&&s.jsx("div",{onClick:D=>D.stopPropagation(),children:s.jsx(kc,{entry:k,onKeep:()=>C(o),onRevert:()=>v(o)})})]})]})});Yf.displayName="MobileTaskRow";const Mn=new Map,Yo=new Set,Sa=new Map,Pl=()=>Yo.forEach(e=>e());function io(e,t,n){for(const a of e){const r=Sa.get(a);r&&(clearTimeout(r),Sa.delete(a)),t?Mn.set(a,t):Mn.delete(a),t&&n&&Sa.set(a,window.setTimeout(()=>{Sa.delete(a),Mn.get(a)===t&&(Mn.delete(a),Pl())},n))}Pl()}const Pv=e=>(Yo.add(e),()=>Yo.delete(e));function Wf(e){const t=i.useCallback(()=>Mn.get(e)??null,[e]);return i.useSyncExternalStore(Pv,t,t)}const Gf=i.memo(({task:e,index:t,droppableId:n,onTaskComplete:a,isFocusMode:r,isTaskFocus:o,focusedTaskId:c,onTaskFocus:l,parentAbove:d=!1})=>{const m=Fe(),u=o&&c===e.id,[f,p]=i.useState(!1),[h,g]=i.useState(!1),b=Wf(e.id),x=f&&!e.due?.isRecurring||b==="leaving",y=i.useCallback(async()=>{try{p(!0),g(!0),ut(20),await a(e.id,n),setTimeout(()=>{g(!1),p(!1)},300)}catch{g(!1),p(!1)}},[e.id,n,a]),w=s.jsxs(s.Fragment,{children:[s.jsx(Vf,{index:t,...e,onComplete:y,isFocused:u,onFocus:()=>l?.(e.id),isFocusMode:r,quadrant:n,parentAbove:d,className:S(f&&"opacity-50 scale-[0.98] transition-all duration-150")}),h&&s.jsx(Ev,{isVisible:h,variant:"success",size:"md",onComplete:()=>g(!1)})]}),k={marginBottom:m?"0.5rem":"0.75rem",position:"relative",zIndex:u?10:t,contain:"content"};if(m){const N=()=>{ut(15),window.dispatchEvent(new CustomEvent("task:snooze",{detail:{taskId:e.id,isRecurring:!!e.due?.isRecurring,time:_r(e.due)}}))},C=()=>{window.dispatchEvent(new CustomEvent("task:peek",{detail:{task:e,quadrant:n}}))};return s.jsx("div",{className:S("task-virtualize mx-item",b==="leaving"&&"is-deleting",b==="restored"&&"is-restored"),style:{display:"grid",gridTemplateRows:x?"0fr":"1fr",opacity:x?0:1,zIndex:k.zIndex,...b==="restored"?{"--q":`var(--q-${n})`}:{}},children:s.jsx("div",{style:{overflow:"hidden",minHeight:0},children:s.jsx(Kf,{style:{position:"relative",contain:"content"},onComplete:y,onSnooze:N,onLongPress:C,disabled:f||u,children:s.jsx(Yf,{task:e,quadrant:n,completing:f,onComplete:y,parentAbove:d})})})})}return s.jsx(_e.div,{className:"task-virtualize",initial:{opacity:0,y:5},animate:{opacity:1,y:0},exit:{opacity:0,y:2,transition:{duration:.28,ease:[.33,0,.2,1]}},transition:{...Nv,layout:{duration:.32,ease:[.33,0,.2,1]}},style:{...k,transformOrigin:"center top"},layout:"position",children:w},e.id)});Gf.displayName="TaskListItem";const Ov={do:{title:"Ready for Action",subtitle:"Do First Quadrant",description:"This is your command center for urgent and important tasks that need immediate attention.",icon:Ts,color:"text-red-600 dark:text-red-400",bgGradient:"from-red-50/50 to-orange-50/50 dark:from-red-950/10 dark:to-orange-950/10",tips:["Start with tasks due today or overdue","Focus on high-impact activities","Limit to 3-5 tasks for mental clarity"],actionText:"Add Urgent Task",motivationalText:"A clear mind starts with clear priorities",illustration:s.jsxs("div",{className:"relative",children:[s.jsx("div",{className:"w-14 h-14 rounded-full bg-gradient-to-br from-red-100 to-red-200 dark:from-red-900/40 dark:to-red-800/40 flex items-center justify-center",children:s.jsx(Ts,{className:"w-7 h-7 text-red-600 dark:text-red-400"})}),s.jsx(te.div,{className:"absolute -top-1 -right-1 w-5 h-5 rounded-full bg-red-500 flex items-center justify-center",animate:{scale:[1,1.2,1]},transition:{duration:2,repeat:1/0},children:s.jsx(Kp,{className:"w-2.5 h-2.5 text-white"})})]})},schedule:{title:"Plan for Success",subtitle:"Schedule Quadrant",description:"Important tasks that deserve your attention but don't require immediate action.",icon:Ss,color:"text-blue-600 dar
27k:text-blue-400",bgGradient:"from-blue-50/50 to-indigo-50/50 dark:from-blue-950/10 dark:to-indigo-950/10",tips:["Block dedicated time for these tasks","Break large projects into smaller steps","Set realistic deadlines"],actionText:"Schedule Important Task",motivationalText:"Progress happens when intention meets planning",illustration:s.jsxs("div",{className:"relative",children:[s.jsx("div",{className:"w-14 h-14 rounded-full bg-gradient-to-br from-blue-100 to-blue-200 dark:from-blue-900/40 dark:to-blue-800/40 flex items-center justify-center",children:s.jsx(Ss,{className:"w-7 h-7 text-blue-600 dark:text-blue-400"})}),s.jsx(te.div,{className:"absolute -top-1 -right-1 w-5 h-5 rounded-full bg-blue-500 flex items-center justify-center",animate:{rotate:[0,360]},transition:{duration:8,repeat:1/0,ease:"linear"},children:s.jsx(Kt,{className:"w-2.5 h-2.5 text-white"})})]})},delegate:{title:"Share the Load",subtitle:"Delegate Quadrant",description:"Urgent tasks that others can handle, freeing you to focus on what matters most.",icon:Un,color:"text-orange-700 dark:text-orange-300",bgGradient:"from-orange-50/40 to-amber-50/40 dark:from-orange-950/10 dark:to-amber-950/10",tips:["Identify who can best handle each task","Provide clear instructions and deadlines","Set up check-in points for important items"],actionText:"Add Task to Delegate",motivationalText:"Leadership is knowing when to let others shine",illustration:s.jsxs("div",{className:"relative",children:[s.jsx("div",{className:"w-14 h-14 rounded-full bg-gradient-to-br from-orange-100 to-amber-100 dark:from-orange-900/40 dark:to-amber-800/40 flex items-center justify-center",children:s.jsx(Un,{className:"w-7 h-7 text-orange-700 dark:text-orange-300"})}),s.jsx(te.div,{className:"absolute -top-1 -right-1 w-5 h-5 rounded-full bg-orange-600 flex items-center justify-center",animate:{y:[-2,2,-2]},transition:{duration:3,repeat:1/0,ease:"easeInOut"},children:s.jsx(mu,{className:"w-2.5 h-2.5 text-white"})})]})},backlog:{title:"Future Possibilities",subtitle:"Backlog Quadrant",description:"Ideas and tasks to revisit when you have time, or to eliminate if they're no longer relevant.",icon:zn,color:"text-gray-600 dark:text-gray-400",bgGradient:"from-gray-50/50 to-slate-50/50 dark:from-card/10 dark:to-card/10",tips:["Review monthly to keep relevant items","Perfect for someday/maybe lists","Consider if tasks still align with your goals"],actionText:"Add Future Task",motivationalText:"Keep what serves your goals, release what doesn't",illustration:s.jsxs("div",{className:"relative",children:[s.jsx("div",{className:"w-14 h-14 rounded-full bg-gradient-to-br from-gray-100 to-gray-200 dark:from-card/40 dark:to-muted/40 flex items-center justify-center",children:s.jsx(zn,{className:"w-7 h-7 text-gray-600 dark:text-gray-400"})}),s.jsx(te.div,{className:"absolute -top-1 -right-1 w-5 h-5 rounded-full bg-gray-500 flex items-center justify-center",animate:{opacity:[.5,1,.5]},transition:{duration:4,repeat:1/0},children:s.jsx(Vp,{className:"w-2.5 h-2.5 text-white"})})]})}},$v={title:"Ready to Organize",subtitle:"Task Quadrant",description:"Add tasks here to keep your work organized and prioritized.",icon:_o,color:"text-primary",bgGradient:"from-muted/30 to-muted/10",tips:["Ctrl (⌘ on Mac) + click tasks to move them between quadrants","Use labels and due dates for better organization","Focus on one quadrant at a time"],actionText:"Add Task",motivationalText:"Every journey begins with a single step",illustration:s.jsx("div",{className:"w-14 h-14 rounded-full bg-gradient-to-br from-primary/20 to-primary/30 flex items-center justify-center",children:s.jsx(_o,{className:"w-7 h-7 text-primary"})})},Fv=({droppableId:e="default",onCreateTask:t,className:n})=>{const a=i.useMemo(()=>Ov[e]||$v,[e]),r={initial:{opacity:0,y:20},animate:{opacity:1,y:0,transition:{duration:.6,ease:[.2,.8,.2,1],staggerChildren:.1}}},o={initial:{opacity:0,y:10},animate:{opacity:1,y:0,transition:{duration:.4,ease:[.2,.8,.2,1]}}};return s.jsxs(te.div,{variants:r,initial:"initial",animate:"animate",className:S("flex flex-col items-center justify-center py-8 px-4 min-h-[160px] rounded-lg",`bg-gradient-to-br ${a.bgGradient}`,"border border-border/20 backdrop-blur-sm relative overflow-hidden",n),children:[s.jsx("div",{className:"absolute inset-0 opacity-[0.02] pointer-events-none",style:{backgroundImage:"radial-gradient(circle, currentColor 1px, transparent 1px)",backgroundSize:"20px 20px"}}),s.jsx(te.div,{variants:o,className:"mb-4",children:a.illustration}),s.jsxs(te.div,{variants:o,className:"text-center mb-4",children:[s.jsx("h3",{className:S("text-lg font-semibold mb-1",a.color),children:a.title}),s.jsx("p",{className:"text-xs text-muted-foreground max-w-xs leading-relaxed",children:a.description})]}),s.jsx(te.div,{variants:o,className:"mb-4 w-full max-w-xs",children:s.jsx("div",{className:"space-y-1.5",children:a.tips.slice(0,2).map((c,l)=>s.jsxs(te.div,{initial:{opacity:0,x:-10}
27,animate:{opacity:1,x:0},transition:{delay:.3+l*.1},className:"flex items-start gap-2 text-xs text-muted-foreground",children:[s.jsx("div",{className:S("w-1 h-1 rounded-full mt-1.5 flex-shrink-0",e==="do"?"bg-red-400":e==="schedule"?"bg-blue-400":e==="delegate"?"bg-orange-400":e==="backlog"?"bg-gray-400":"bg-primary")}),s.jsx("span",{className:"leading-relaxed",children:c})]},l))})}),t&&s.jsx(te.div,{variants:o,className:"mb-3",children:s.jsxs(W,{onClick:()=>t(e),size:"sm",className:S("group transition-all duration-300 shadow-lg hover:shadow-xl",e==="do"?"bg-red-500 hover:bg-red-600 text-white":e==="schedule"?"bg-blue-500 hover:bg-blue-600 text-white":e==="delegate"?"bg-orange-600 hover:bg-orange-700 text-white":e==="backlog"?"bg-gray-500 hover:bg-gray-600 text-white":"bg-primary hover:bg-primary/90"),children:[s.jsx(fn,{className:"w-3 h-3 mr-1.5 group-hover:rotate-90 transition-transform duration-300"}),a.actionText]})}),s.jsxs(te.div,{variants:o,className:"flex flex-col items-center gap-2 text-center",children:[s.jsx("span",{"aria-hidden":!0,className:"h-px w-10 rounded-full bg-gradient-to-r from-transparent via-border to-transparent"}),s.jsx("p",{className:"max-w-[44ch] text-xs italic leading-relaxed text-muted-foreground/70",children:a.motivationalText})]}),s.jsx(te.div,{className:"absolute inset-0 pointer-events-none overflow-hidden rounded-lg",initial:{opacity:0}
27,animate:{opacity:1},transition:{delay:1},children:[...Array(2)].map((c,l)=>s.jsx(te.div,{className:S("absolute w-0.5 h-0.5 rounded-full opacity-20",e==="do"?"bg-red-400":e==="schedule"?"bg-blue-400":e==="delegate"?"bg-orange-400":e==="backlog"?"bg-gray-400":"bg-primary"),style:{left:`${30+l*40}%`,top:`${15+l*30}%`},animate:{y:[-5,5,-5],opacity:[.1,.3,.1]},transition:{duration:3+l,repeat:1/0,delay:l*.5}},l))})]})},Ol={do:{line:"Nothing urgent and important. Nice.",icon:Ts},schedule:{line:"Nothing planned yet.",icon:Ss},delegate:{line:"Nothing to hand off.",icon:Un},backlog:{line:"Backlog is clear.",icon:zn}},qv=({droppableId:e,onCreateTask:t})=>{const n=Pe(c=>c.activeFilterCount>0),a=Pe(c=>c.clearFilters),r=Ol[e]??Ol.backlog,o=n?ta:r.icon;return s.jsxs("div",{className:"mx-empty",style:{"--q":`var(--q-${e})`},children:[s.jsx(o,{className:"mx-empty-icon","aria-hidden":!0}),s.jsx("p",{className:"mx-empty-line",children:n?"No tasks match these filters.":r.line}),n&&a?s.jsx("button",{type:"button",className:"mx-empty-btn",onClick:a,children:"Clear filters"}):t?s.jsxs("button",{type:"button",className:"mx-empty-btn",onClick:()=>t(e),children:[s.jsx(fn,{className:"h-4 w-4","aria-hidden":!0}),"Add task"]}):null]})},zv=e=>{const[t,n]=i.useState(!1),a=i.useRef(null);return{isTaskCompleting:t,setIsTaskCompleting:n,containerRef:a}},Uv=({onCompleteTask:e,isTaskFocus:t,setIsTaskCompleting:n})=>({handleTaskComplete:i.useCallback(async(r,o)=>{try{n(!0),await e(r,o),setTimeout(()=>{n(!1)},t?700:500)}catch{n(!1)}},[e,t,n])}),Wo="task:open-add",Sc=(e={})=>{window.dispatchEvent(new CustomEvent(Wo,{detail:e}))},hr=e=>e==="do"||e==="schedule"||e==="delegate"||e==="backlog",$l=e=>{hr(e)&&Sc({quadrant:e})},Go=i.memo(({tasks:e,droppableId:t,isCollapsed:n,onCompleteTask:a,isTaskFocus:r,focusedTaskId:o,onTaskFocus:c,onCreateTask:l})=>{const{config:d,density:m}=Zt(),u=Fe(),{setIsTaskCompleting:f,containerRef:p}=zv(),{handleTaskComplete:h}=Uv({onCompleteTask:a,isTaskFocus:r,setIsTaskCompleting:f}),g=i.useMemo(()=>nf(e),[e]);if(n)return s.jsx("div",{className:"collapsed-droppable"});const b=e.map((y,w)=>s.jsx(Gf,{task:y,index:w,droppableId:t,onTaskComplete:h,isFocusMode:!!r,isTaskFocus:r,focusedTaskId:o,onTaskFocus:c,parentAbove:g.has(y.id)},y.id));if(u)return s.jsxs("div",{className:"mx-list","data-density":m,ref:p,children:[b,e.length===0&&s.jsx(qv,{droppableId:t,onCreateTask:l??(hr(t)?$l:void 0)})]});const x=e.length===0&&s.jsx(Fv,{droppableId:t,onCreateTask:l??(hr(t)?$l:void 0)});return s.jsxs(_e.div,{initial:!1,animate:{opacity:1,height:"auto",transition:{duration:.2,ease:[.2,0,.2,1]}},className:S("bg-transparent min-h-[100px] relative",d.quadrantPadding),ref:p,children:[s.jsx("div",{"aria-hidden":!0,className:"absolute inset-0 pointer-events-none",style:{backgroundImage:"radial-gradient(circle, currentColor 1px, transparent 1.5px)",backgroundSize:"28px 28px",color:"rgb(148 163 184)",opacity:.06,maskImage:"radial-gradient(ellipse 80% 80% at 50% 45%, black 30%, transparent 100%)",WebkitMaskImage:"radial-gradient(ellipse 80% 80% at 50% 45%, black 30%, transparent 100%)"}}),s.jsxs("div",{className:S("overflow-y-auto max-h-[calc(100vh-300px)] scrollbar-none","sm:transition-[max-width] sm:duration-500 sm:ease-[cubic-bezier(0.22,1,0.36,1)]",d.taskSpacing,d.cardMaxWidth),children:[s.jsx(Gt,{mode:"popLayout",initial:!1,children:b}),x]})]})});Go.displayName="TaskList";const Qf=Ue.memo(({isTaskFocus:e})=>s.jsx(te.div,{initial:!1,animate:{rotate:180,scale:e?1.1:1},transition:{type:"spring",stiffness:200,damping:20},children:s.jsx(mt,{className:S("h-4 w-4 transition-colors duration-300",e?"text-primary":"text-muted-foreground")})}));Qf.displayName="ChevronMotion";const Jf=Ue.memo(({isTaskFocus:e,taskCountLabel:t})=>{const[n,...a]=t.split(" "),r=a.join(" ");return s.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[s.jsxs(te.div,{className:"relative",animate:e?{scale:[1,1.02,1],transition:{duration:3,repeat:1/0,repeatType:"reverse",ease:"easeInOut"}}:{},children:[s.jsxs(te.span,{className:S("px-3 max-sm:px-2.5 py-1 text-sm font-medium rounded-full transition-all whitespace-nowrap",e?"bg-primary/20 text-primary shadow-sm backdrop-blur-sm":"bg-black/20 text-white"),layout:!0,children:[n,r&&s.jsxs("span",{className:"max-sm:hidden",children:[" ",r]})]}),e&&s.jsx(te.div,{className:"absolute inset-0 rounded-full",initial:{boxShadow:"0 0 0 0 rgba(var(--primary), 0)"},animate:{boxShadow:["0 0 0 0 rgba(var(--primary), 0)","0 0 0 4px rgba(var(--primary), 0.1)","0 0 0 0 rgba(var(--primary), 0)"]},transition:{duration:2,repeat:1/0,repeatType:"loop",ease:"easeInOut"}})]}),s.jsx(Qf,{isTaskFocus:e})]})});Jf.displayName="QuadrantCounter";function Xf(){const{count:e,openReview:t}=xn();return e<=0?null:s.jsxs("button",{type:"button",onClick:n=>{n.stopPropagation(),t()},onPointerDown:n=>n.stopPropagation(),className:S("group/pill inline-flex items-center gap-1.5","mt-1 max-w-full self
27-start","rounded-full px-2.5 py-1","text-[11px] font-medium tracking-wide","text-amber-900/80 dark:text-amber-200/85","bg-amber-400/12 dark:bg-amber-300/10","ring-1 ring-inset ring-amber-500/15 dark:ring-amber-300/15","hover:bg-amber-400/20 hover:text-amber-900 dark:hover:bg-amber-300/15","transition-colors","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-amber-500/40"),children:[s.jsx("span",{"aria-hidden":!0,className:"block h-1 w-1 rounded-full bg-amber-500 dark:bg-amber-300"}),s.jsx("span",{className:"truncate",children:gv(e)})]})}const Bv=e=>{switch(e.toLowerCase()){case"do first":return"#ef4444";case"schedule":return"#3b82f6";case"delegate":return"#fb923c";case"backlog":return"#8a8580";default:return}},Hv=(e,t)=>{switch(e.toLowerCase()){case"do first":return s.jsx(Wt,{className:S(t,"text-red-500 shrink-0")});case"schedule":return s.jsx(Kt,{className:S(t,"text-blue-500 shrink-0")});case"delegate":return s.jsx(Un,{className:S(t,"text-orange-400 shrink-0")});case"backlog":return s.jsx(zn,{className:S(t,"text-[#8a8580] shrink-0")});default:return null}},Zf=Ue.memo(({title:e,description:t,isCollapsed:n,isTaskFocus:a,taskCountLabel:r,onToggle:o})=>{const[c,l]=i.useState(!1),{config:d}=Zt(),m=Bv(e);return s.jsx(ef,{className:S("quadrant-header flex flex-row items-center justify-between cursor-pointer text-left select-none",d.quadrantHeaderPy,"max-sm:py-3 max-sm:px-3","max-sm:sticky max-sm:top-0 max-sm:z-10 max-sm:bg-background/95 max-sm:backdrop-blur-sm","max-sm:border-l-[3px] max-sm:rounded-l-md","hover:bg-black/5 dark:hover:bg-white/5 rounded-lg transition-colors","group"),style:m?{borderLeftColor:m}:void 0,onClick:o,onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),children:s.jsx("div",{className:"flex-1",children:s.jsxs("div",{className:"flex items-center justify-between space-x-2 sm:space-x-4",children:[s.jsxs("div",{className:"space-y-1.5 text-left flex-1 min-w-0",children:[s.jsxs(te.div,{animate:a?{color:"rgb(var(--primary))",transition:{duration:.5}}:{},className:"flex items-center gap-2 sm:gap-3 min-w-0",children:[s.jsx(te.div,{className:"quadrant-header-icon",variants:Zw,initial:"initial",animate:c?"animate":"initial",children:Hv(e,d.quadrantIconSize)}),s.jsx(tf,{className:S(d.quadrantTitleSize,"max-sm:text-base truncate min-w-0","text-left font-bold tracking-tight text-foreground"),children:e})]}),s.jsx(sf,{className:S("quadrant-header-desc",d.quadrantDescSize,"max-sm:hidden","text-left break-words","line-clamp-2 overflow-hidden","sm:min-h-[2lh]","font-medium opacity-80","text-muted-foreground"),children:t}),e.toLowerCase()==="do first"&&s.jsx(Xf,{})]}),s.jsx(Jf,{isTaskFocus:a,taskCountLabel:r})]})})})});Zf.displayName="QuadrantHeader";const Vv=({title:e,description:t,tasks:n,className:a,type:r,onCompleteTask:o,droppableId:c,isTaskFocus:l=!1,focusedTaskId:d,onTaskFocus:m,onCollapseChange:u,index:f=0})=>{const[p,h]=i.useState(!1),g=i.useRef(null),b=Fe();i.useEffect(()=>{const C=v=>{h(v.detail.collapsed),u?.(v.detail.collapsed)};return window.addEventListener("toggle-all-quadrants",C),()=>{window.removeEventListener("toggle-all-quadrants",C)}},[u]);const x=la(),y=ra(n),w=Ue.useMemo(()=>wc(n,x),[n,x,y]),k=Ue.useCallback(C=>{C.preventDefault();const v=!p;h(v),u?.(v)},[p,u]),N=Ue.useMemo(()=>{const C=n.length;return`${C} ${C===1?"task":"tasks"}`},[n.length]);return b?s.jsx(Go,{tasks:w,droppableId:c,isCollapsed:!1,onCompleteTask:o,isTaskFocus:l,focusedTaskId:d,onTaskFocus:m}):s.jsx("div",{className:"h-full",children:s.jsxs(hc,{className:S("w-full transition-shadow duration-200 ease-out border-0 shadow-none bg-transparent","font-sans tracking-tight relative hover:shadow-lg","max-sm:overflow-visible sm:overflow-hidden",a,l&&"focus-mode-active relative",l&&!n.some(C=>C.id===d)&&"opacity-30"),children:[s.jsx(Zf,{title:e,description:t,isCollapsed:p,isTaskFocus:l||!1,taskCountLabel:N,onToggle:k}),s.jsx("div",{ref:g,className:S("overflow-hidden transition-all duration-200 ease-out",p?"max-h-0 opacity-0":"max-h-[2000px] opacity-100"),children:s.jsx(pc,{className:"p-0",children:s.jsx(Go,{tasks:w,droppableId:c,isCollapsed:p,onCompleteTask:o,isTaskFocus:l,focusedTaskId:d,onTaskFocus:m})})})]})})},Kv=i.memo(Vv),Yv=({shouldFocus:e,isCollapsed:t,isHovering:n=!1})=>{if(t)return null;const o=n?e?.25:.12:e?.15:0;
27return s.jsxs("div",{"aria-hidden":!0,className:"pointer-events-none absolute inset-0 -z-10 overflow-hidden rounded-xl transition-opacity duration-500",style:{opacity:o,transitionTimingFunction:"cubic-bezier(0.19, 1, 0.22, 1)"},children:[s.jsx("div",{className:S("h-full w-full quadrant-highlight-glow",e&&"quadrant-breathe")}),s.jsx("div",{className:"absolute inset-0 rounded-xl transition-opacity duration-300",style:{opacity:n?.6:0,boxShadow:"inset 0 0 0 1px rgba(var(--primary), 0.12)"}})]})},Wv=({isCollapsed:e})=>e?null:s.jsx(te.div,{initial:{opacity:0},animate:{opacity:.7},exit:{opacity:0},transition:{duration:.3,ease:"easeOut"},className:"absolute bottom-0 left-0 w-full h-1/4 bg-gradient-to-t from-black/5 to-transparent pointer-events-none"}),Gv=({isActive:e})=>s.jsx("div",{"aria-hidden":!0,className:S("pointer-events-none absolute inset-0 -z-10 rounded-xl transition-[opacity,transform] duration-700 ease-out",e?"opacity-80 scale-100":"opacity-0 scale-95"),children:s.jsx("div",{className:S("absolute inset-0 rounded-xl quadrant-ambient-glow",e&&"quadrant-breathe")})}),Qv=({tasks:e,focusedTaskId:t,isTaskFocus:n,shouldFocus:a})=>{const r=i.useMemo(()=>t?e.some(d=>d.id===t):!1,[e,t]),o=i.useMemo(()=>!n||r?1:a?.8:.15,[n,a,r]),c="blur(0px)",l=i.useMemo(()=>`
28    relative rounded-lg overflow-hidden group
29    transition-all duration-300 transform-gpu
30    ${a?"shadow-lg ring-1 ring-primary/20":"hover:shadow-md"}
31    ${r?"ring-1 ring-primary/30 shadow-md":""}
32  `,[a,r]);return{hasCurrentFocusedTask:r,quadrantOpacity:o,quadrantBlur:c,quadrantClassName:l}},Jv={type:"tween",duration:.4,ease:[.22,1,.36,1]},Xv={type:"spring",stiffness:250,damping:25,mass:.8},Qo=i.memo(({title:e,description:t,tasks:n,type:a,droppableId:r,isTaskFocus:o,focusedTaskId:c,onTaskFocus:l,onCompleteTask:d,index:m=0})=>{const{preferences:u}=iw(),[f,p]=i.useState(!1),[h,g]=i.useState(!1),b=Fe(),x=r==="do",y=r==="schedule",w=o&&(x&&u?.focus_do_first||y&&u?.focus_schedule),{hasCurrentFocusedTask:k,quadrantOpacity:N,quadrantBlur:C,quadrantClassName:v}=Qv({tasks:n,focusedTaskId:c,isTaskFocus:o,shouldFocus:w}),j=R=>{p(R)},T=i.useMemo(()=>`${v} ${f?"h-[96px]":"h-full"} focus-transition`,[v,f]),_=k||w||h,I=s.jsxs(s.Fragment,{children:[s.jsx(Kv,{title:e,description:t,tasks:n,className:`quadrant-${a} h-full ${_?"quadrant-active":""}`,type:a,onCompleteTask:d,droppableId:r,isTaskFocus:o,focusedTaskId:c,onTaskFocus:l,onCollapseChange:j,index:m}),!b&&s.jsxs(s.Fragment,{children:[s.jsx(Yv,{shouldFocus:w,isCollapsed:f,isHovering:h}),s.jsx(Wv,{isCollapsed:f}),o&&s.jsx(Gv,{isActive:_})]})]});return b?s.jsx("div",{className:T,children:I}):s.jsx(te.div,{initial:{opacity:.9,y:5},animate:{opacity:N,scale:o?w||k?1.01:.99:1,filter:C,y:0,boxShadow:h?"0 8px 24px rgba(0, 0, 0, 0.08), 0 2px 8px rgba(0, 0, 0, 0.06)":"0 2px 8px rgba(0, 0, 0, 0.04), 0 1px 4px rgba(0, 0, 0, 0.02)"},transition:h?Xv:Jv,className:T,onMouseEnter:()=>g(!0),onMouseLeave:()=>g(!1),children:I})},(e,t)=>{const n=e.isTaskFocus===t.isTaskFocus,a=e.focusedTaskId===t.focusedTaskId,r=e.title===t.title,o=e.type===t.type,c=e.droppableId===t.droppableId;if(!n||!a||!r||!o||!c)return!1;const l=e.tasks,d=t.tasks;if(l.length!==d.length)return!1;for(let m=0;m<l.length;m++){const u=l[m],f=d[m];if(u.id!==f.id||u.title!==f.title||u.description!==f.description||u.priority!==f.priority||u.completed!==f.completed||u.due?.date!==f.due?.date||u.due?.datetime!==f.due?.datetime||u.deadline?.date!==f.deadline?.date||u.labels.length!==f.labels.length||u.labels.some((p,h)=>p!==f.labels[h]))return!1}return!0});Qo.displayName="QuadrantWrapper";const eh=()=>{const e=i.useRef(null),t=i.useRef(null),n=Pe(l=>l.quadrant),a=Pe(l=>l.counts);i.useEffect(()=>{const l=()=>{const m=e.current;m&&(m.style.display="none",m.offsetHeight,m.style.display="")},d=()=>{document.visibilityState==="visible"&&l()};return window.addEventListener("pageshow",l),document.addEventListener("visibilitychange",d),()=>{window.removeEventListener("pageshow",l),document.removeEventListener("visibilitychange",d)}},[]),i.useEffect(()=>{let l=window.scrollY,d=0;const m=()=>{d=0;const f=t.current;if(!f)return;const p=window.scrollY,h=p-l,g=window.innerHeight+p>=document.documentElement.scrollHeight-24;p<64||g||h<-6?f.removeAttribute("data-away"):h>6&&f.setAttribute("data-away",""),(Math.abs(h)>6||p<64)&&(l=p)},u=()=>{d||(d=requestAnimationFrame(m))};return window.addEventListener("scroll",u,{passive:!0}),()=>{window.removeEventListener("scroll",u),d&&cancelAnimationFrame(d)}},[]);const r=i.useCallback(l=>{ut(8),l!==Pe.getState().quadrant&&pe("view_changed",{kind:"quadrant_tab",to:l}),Gn(l)},[]),o=i.useCallback(l=>{if(l.key!=="ArrowLeft"&&l.key!=="ArrowRight")return;const d=On.findIndex(u=>u.id===n),m=On[(d+(l.key==="ArrowRight"?1:3))%4];l.preventDefault(),pe("view_changed",{kind:"quadrant_tab",to:m.id}),Gn(m.id),document.getElementById(`mx-tab-${m.id}`)?.focus()},[n]),c=i.useCallback(()=>{ut(12),document.getElementById("add-task-btn")?.click()},[]);return s.jsxs(s.Fragment,{children:[s.jsx("button",{ref:t,type:"button",className:"mx-fab",onClick:c,"aria-label":"Add task",children:s.jsx(fn,{className:"h-6 w-6",strokeWidth:2.25,"aria-hidden":!0})}),s.jsx("div",{ref:e,id:"mx-tabbar",className:"mx-tabbar",children:s.jsx("div",{role:"tablist","aria-label":"Quadrants",className:"mx-tabs",onKeyDown:o,children:On.map(l
32=>{const d=l.id===n,m=a[l.id];return s.jsx("button",{id:`mx-tab-${l.id}`,type:"button",role:"tab","aria-selected":d,"aria-controls":"mx-panel","aria-label":`${l.label}, ${m} ${m===1?"task":"tasks"}`,tabIndex:d?0:-1,onClick:()=>r(l.id),className:S("mx-tab",d&&"is-active"),style:{"--q":`var(--q-${l.id})`},children:s.jsxs("span",{className:"mx-tab-pill","aria-hidden":!0,children:[s.jsxs("span",{className:"mx-tab-name",children:[s.jsx("span",{className:"mx-dot"}),l.label]}),s.jsx("span",{className:"mx-tab-count",children:s.jsx(Ki,{value:m})})]})},l.id)})})})]})};eh.displayName="MobileActionBar";const Zv=[{icon:Oe,tint:"#10b981",bg:"rgba(16, 185, 129, 0.16)",action:"Swipe right",result:"complete it"},{icon:os,tint:"#f59e0b",bg:"rgba(245, 158, 11, 0.16)",action:"Swipe left",result:"snooze to tomorrow"},{icon:Yp,tint:"#94a3b8",bg:"rgba(148, 163, 184, 0.18)",action:"Tap or hold",result:"see more options"}],th=()=>{const[e,t]=ct("mobile-gesture-hint-dismissed",!1);return i.useEffect(()=>{if(e)return;const n=()=>t(!0);return window.addEventListener("task-completion-finished",n),window.addEventListener("task:snooze",n),()=>{window.removeEventListener("task-completion-finished",n),window.removeEventListener("task:snooze",n)}},[e,t]),e?null:s.jsxs("div",{className:"mx-hint mb-3 rounded-2xl border border-border/60 bg-card px-3.5 py-3 shadow-sm animate-in fade-in slide-in-from-top-2 duration-300",children:[s.jsxs("div",{className:"mb-2.5 flex items-center justify-between",children:[s.jsx("span",{className:"text-[13px] font-semibold text-foreground/90",children:"Quick gestures"}),s.jsx("button",{type:"button",onClick:()=>{ut(8),t(!0)},"aria-label":"Dismiss",className:"flex h-7 w-7 items-center justify-center rounded-full text-muted-foreground transition active:scale-90 hover:bg-foreground
32/10",children:s.jsx(Ie,{className:"h-4 w-4"})})]}),s.jsx("div",{className:"flex flex-col gap-2",children:Zv.map(n=>{const a=n.icon;return s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg",style:{backgroundColor:n.bg,color:n.tint},children:s.jsx(a,{className:"h-4 w-4",strokeWidth:2.5})}),s.jsxs("span",{className:"text-[13px] leading-tight",children:[s.jsx("span",{className:"font-semibold text-foreground/90",children:n.action}),s.jsxs("span",{className:"text-muted-foreground",children:[" to ",n.result]})]})]},n.action)})})]})};th.displayName="MobileGestureHint";const Jo=new Set,ek=()=>Jo.forEach(e=>e()),Fl=e=>(Jo.add(e),window.addEventListener("storage",e),()=>{Jo.delete(e),window.removeEventListener("storage",e)}),co=e=>{try{return window.localStorage.getItem(e)}catch{return null}},Ba=(e,t)=>{try{window.localStorage.setItem(e,t)}catch{}Ha.set(e,t),ek()},Ha=new Map,tk=e=>`matrix-view-v2-${e}`,sh=e=>`matrix-view-tip-${e}`,ql=e=>Ba(sh(e),"1");function da(){const{session:e}=we.useSessionContext(),t=e?.user?.id??"anonymous",n=tk(t),a=sh(t),r=i.useSyncExternalStore(Fl,()=>Ha.get(n)??co(n),()=>null),o=i.useSyncExternalStore(Fl,()=>Ha.get(a)??co(a),()=>"1"),c=r==="classic"?"classic":"clean",l=i.useCallback(f=>{const p=(Ha.get(n)??co(n))==="classic"?"classic":"clean";Ba(n,f),p!==f&&pe("view_changed",{kind:"layout",to:f}),Ba(a,"1")},[n,a]),d=i.useCallback(()=>{l(c==="clean"?"classic":"clean")},[l,c]),m=i.useCallback(()=>Ba(a,"1"),[a]);return{view:c,setView:l,toggleView:d,showTip:o===null,dismissTip:m,userId:t}}function sk(e){const{toggleView:t}=da();i.useEffect(()=>{if(!e)return;const n=a=>{if(a.key!=="v"&&a.key!=="V"||a.defaultPrevented||a.altKey||a.ctrlKey||a.metaKey)return;const r=a.target;r&&(r.tagName==="INPUT"||r.tagName==="TEXTAREA"||r.tagName==="SELECT"||r.isContentEditable)||document.querySelector('[role="dialog"], [data-radix-popper-content-wrapper]')||(a.preventDefault(),t())};return window.addEventListener("keydown",n),()=>window.removeEventListener("keydown",n)},[e,t])}const zl=e=>Ee(e,"yyyy-MM-dd"),nh=(e,t=new Date)=>!!e&&zl(new Date(e))===zl(t),nk=(e,t=new Date)=>
32e?ls(t,new Date(e)):Number.POSITIVE_INFINITY,Ul=e=>Ee(e,"yyyy-MM-dd"),ah=e=>{const t=[e.due?.date,e.deadline?.date].filter(n=>!!n).map(n=>n.slice(0,10));return t.length?t.sort()[0]:null},ak=(e,t=new Date)=>{const n=ah(e),a=Ul(t);if(n){if(n<a)return 0;if(n===a)return 1;if(n<=Ul(st(t,7)))return 2}return(e.priority??1)>=2?3:4},Ca=(e,t=5,n=new Date)=>{if(t<=0)return[];const a=e.filter(u=>!u.parent_id),o=(a.length>=t?a:e).map((u,f)=>({task:u,index:f,bucket:ak(u,n),date:ah(u)})).sort((u,f)=>u.bucket-f.bucket||(f.task.priority??1)-(u.task.priority??1)||(u.date&&f.date?u.date.localeCompare(f.date):u.date?-1:f.date?1:0)||u.index-f.index),c=o.filter(u=>u.bucket<=2).slice(0,3),l=o.filter(u=>u.bucket>=3).slice(0,2),d=[...c,...l],m=new Set(d.map(u=>u.task.id));for(const u of o){if(d.length>=t)break;m.has(u.task.id)||(d.push(u),m.add(u.task.id))}return d.slice(0,t).sort((u,f)=>o.indexOf(u)-o.indexOf(f)).map(u=>u.task.id)},Bl=(e,t,n)=>e===1?t:n,rk=({surface:e,variant:t,justConnected:n,doCount:a,unsorted:r,touch:o=!1,short:c=!1})=>{const l=t==="presorted"?n?"Todoist connected. Your matrix is ready.":"Your matrix is ready":"Your matrix is live",d=e==="clean"?"Start here, and tick a task's circle when it's done.":e==="classic"?"Start here, and complete a task when it's done.":"Start here. Swipe right on a task when it's done.",m=a>=1?`${a} ${Bl(a,"task","tasks")} landed in Do First: urgent and important. ${d}`:"Do First is empty, so nothing is on fire. Anything urgent and important will show up here first.",u=[{id:"start",anchor:e==="clean"?".cm-cell-do .cm-qhead":e==="mobile"?c?"#mx-tab-do":"#q-do, #mx-tab-do":"#q-do",title:l,body:m}];return r>0&&u.push({id:"rest",anchor:"#categorize-btn",title:`${r} ${Bl(r,"task","tasks")} still unsorted`,body:"They wait here, out of your way. Sort a few whenever you have a minute. Five at a time is plenty."}),e==="mobile"?u.push({id:"bar",anchor:"#mx-tabbar",title:"Everything's one tap away",body:"Tap a quadrant to switch lists. Add a task with +."}):u.push({id:"view",anchor:".cm-switch",title:"Two ways to see your matrix",body:o?"Switch between Clean and Classic here anytime.":"Switch between Clean and Classic here anytime, or press V."}),u},lo={focus:e=>({id:"focus",anchor:e?"#mx-focus-btn":"#single-task-focus",title:"One task at a time",body:"Single Task Focus hides everything except your next task, with a timer to keep you on it.",primaryLabel:"Got it"}),stats:()=>({id:"stats",anchor:"#stats-button",title:"Your week at a glance",body:"See what you finished, how long you focused, and how your streak is going.",primaryLabel:"Got it"}),recat:()=>({id:"recat",anchor:"#recategorize-btn",title:"Priorities shift",body:"Recategorize moves many tasks between quadrants at once. Handy for a weekly reset.",primaryLabel:"Got it"})},ns=e=>{const t=document.querySelectorAll(e);for(const n of Array.from(t)){const a=n.getBoundingClientRect();if(a.width>0&&a.height>0)return n}return null},rh=()=>{try{return window.matchMedia("(max-height: 500px)").matches}catch{return!1}},ok=()=>{try{return window.matchMedia("(pointer: coarse)").matches}catch{return!1}},Hl=(e,t)=>e.left<t.left+t.width&&t.left<e.left+e.width&&e.top<t.top+t.height&&t.top<e.top+e.height,ik=({rect:e,card:t,viewport:n,gap:a=10,margin:r=16,bottomInset:o=0,obstacles:c=[]})=>{const l=e.height>240?{...e,height:64}:e,d=n.h-o,m=c.filter(C=>C.width>0&&C.height>0),u=l.left+l.width/2,f=Math.max(r,n.w-t.w-r),p=Math.min(Math.max(r,u-t.w/2),f),h=(C,v)=>({top:C,left:v,width:t.w,height:t.h}),g=(C,v)=>!m.some(j=>Hl(h(C,v),j)),b=C=>Math.min(Math.max(16,u-C),t.w-16),x=(C,v)=>{if(g(v,p))return{top:v,left:p,side:C,arrowX:b(p)};const j=m.find(I=>Hl(h(v,p),I)),T=j.left-a-t.w;if(T>=r&&g(v,T)&&u-T>=16&&u-T<=t.w-16)return{top:v,left:T,side:C,arrowX:b(T)};const _=j.left+j.width+a;if(_<=f&&g(v,_)&&u-_>=16)return{top:v,left:_,side:C,arrowX:b(_)};if(C==="above"){const I=j.top-a-t.h;if(I>=r&&g(I,p))return{top:I,left:p,side:C,arrowX:null}}else{const I=j.top+j.height+a;if(I+t.h+r<=d&&g(I,p))return{top:I,left:p,side:C,arrowX:null}}return null};if(l.top+l.height+a+t.h+r<=d){const C=x("below",l.top+l.height+a);if(C)return C}if(l.top-a-t.h>=r){const C=x("above",l.top-a-t.h);if(C)return C}const y=Math.min(Math.max(r,l.top+l.height/2-t.h/2),Math.max(r,d-t.h-r)),w=l.left+l.width+a;if(w+t.w+r<=n.w&&g(y,w))return{top:y,left:w,side:"right",arrowX:null};const k=l.left-a-t.w;return k>=r&&g(y,k)?{top:y,left:k,side:"left",arrowX:null}:{top:Math.min(Math.max(r,l.top+12),d-t.h-r),left:p,side:"inside",arrowX:null}},Vl=()=>{try{return window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{return!1}},ck=e=>{if(!e)return 0;const n=document.getElementById("mx-tabbar")?.getBoundingClientRect();return!n||n.height<=0||n.top>=window.innerHeight?e:Math.max(0,window.innerHeight-n.top)},lk=e=>Array.from(document.querySelectorAll(".mx-fab")).filter(t=>!t.contains(e)&&!e.contains(t)).map(t=>t.getBoundingClientRect()).filter(t=>t.width>0&&t.height>0&&t.bottom>0&&t.top<window.innerHeight).map(t=>
32({top:t.top,left:t.left,width:t.width,height:t.height}));let ss=null;const dk=e=>!!e&&(e.tagName==="INPUT"||e.tagName==="TEXTAREA"||e.tagName==="SELECT"||e.isContentEditable),Kl=({anchor:e,title:t,body:n,step:a,primaryLabel:r,onPrimary:o,onClose:c,onAnchorClick:l,bottomInset:d=0,returnFocusOnPrimary:m=!1})=>{const u=i.useRef(null),f=i.useRef(null),[p,h]=i.useState(null),[g,b]=i.useState(!1),[x,y]=i.useState(()=>ss&&(ss.alive||Date.now()-ss.at<150)&&!Vl()?ss:null),[w,k]=i.useState(!1),N=i.useCallback(()=>{const P=ns(e),E=u.current;if(!P||!E){h(null);return}const D=P.getBoundingClientRect();h(ik({rect:{top:D.top,left:D.left,width:D.width,height:D.height},card:{w:E.offsetWidth,h:E.offsetHeight},viewport:{w:window.innerWidth,h:window.innerHeight},bottomInset:ck(d),obstacles:d?lk(P):[]}))},[e,d]);i.useEffect(()=>{b(!1);const P=ns(e);let E=0;if(P){const D=P.getBoundingClientRect();D.bottom<0||D.top>window.innerHeight-d?(y(null),P.scrollIntoView({block:"center",behavior:Vl()?"auto":"smooth"}),E=window.setTimeout(()=>b(!0),380)):b(!0)}return()=>window.clearTimeout(E)},[e,d]),i.useLayoutEffect(()=>{g&&N()},[g,N,t,n]),i.useEffect(()=>{if(!g)return;let P=0;const E=()=>{cancelAnimationFrame(P),P=requestAnimationFrame(N)};window.addEventListener("scroll",E,!0),window.addEventListener("resize",E);const D=ns(e),L=typeof ResizeObserver<"u"&&D?new ResizeObserver(E):null;return D&&L&&L.observe(D),()=>{cancelAnimationFrame(P),window.removeEventListener("scroll",E,!0),window.removeEventListener("resize",E),L?.disconnect()}},[g,e,N]),i.useEffect(()=>{if(!g)return;const P=ns(e);if(!P)return;P.setAttribute("data-coach-target","");const E=()=>l?.();return P.addEventListener("click",E,!0),()=>{P.removeAttribute("data-coach-target"),P.removeEventListener("click",E,!0)}},[g,e,l]);const C=g?p:null;i.useLayoutEffect(()=>{C&&(ss={top:C.top,left:C.left,arrowX:C.arrowX,alive:!0,at:Date.now()})},[C]),i.useEffect(()=>()=>{ss&&(ss={...ss,alive:!1,at:Date.now()})},[]);const v=!!C&&!!x&&w;i.useEffect(()=>{if(!C||!x||w)return;const P=requestAnimationFrame(()=>k(!0));return()=>cancelAnimationFrame(P)},[C,x,w]),i.useEffect(()=>{if(!v)return;const P=window.setTimeout(()=>y(null),300);return()=>window.clearTimeout(P)},[v]);const j=x&&p&&!w?x:p,T=i.useRef(!1),_=g&&!!p;i.useEffect(()=>{if(!_||T.current)return;T.current=!0;try{sessionStorage.setItem("onb:coach-shown","1")}catch{}const P=document.activeElement;(!P||P===document.body||u.current?.contains(P))&&f.current?.focus({preventScroll:!0})},[_]);const I=i.useCallback(()=>{const P=document.activeElement;if(!P||!u.current?.contains(P))return;const E=ns(e);E&&(E.tabIndex>=0||E.matches("button, a[href], input, [tabindex]"))?E.focus({preventScroll:!0}):P.blur()},[e]),R=i.useCallback(()=>{I(),c()},[I,c]),M=i.useCallback(()=>{m&&I(),o()},[m,I,o]);return i.useEffect(()=>{const P=E=>{if(E.key!=="Escape"||E.defaultPrevented)return;const D=document.activeElement;if(dk(D)||document.querySelector('[role="dialog"]'))return;const L=!!D&&!!u.current?.contains(D),A=!!document.querySelector(".cm-row.is-kbd, .cm-row.is-selected")||!!D?.closest?.('.cm-root, [role="listbox"], [role="option"]');!L&&A||R()};return window.addEventListener("keydown",P),()=>window.removeEventListener("keydown",P)},[R]),Ii.createPortal(s.jsxs("div",{ref:u,className:["cm-coach",(x||w)&&"is-stepped",x&&w&&"is-gliding"].filter(Boolean).join(" "),role:"region","aria-roledescription":"tip","aria-labelledby":"cm-coach-title","aria-describedby":"cm-coach-body","data-testid":"onb-coachmark","data-side":p?.side,style:{top:j?.top??-9999,left:j?.left??-9999,visibility:g&&p?"visible":"hidden"},children:[j?.arrowX!=null&&s.jsx("span",{className:"cm-coach-arrow","aria-hidden":!0,style:{left:j.arrowX-5}}),s.jsxs("div",{"aria-live":"polite",className:"cm-coach-content",children:[s.jsxs("div",{className:"cm-coach-head",children:[a&&a.total>1?s.jsxs("span",{className:"cm-coach-step",children:[a.index," of ",a.total]}):s.jsx("span",{}),s.jsx("button",{type:"button",className:"cm-coach-x","aria-label":"Skip tips","data-testid":"onb-coachmark-close",onClick:R,children:s.jsx(Ie,{className:"h-3.5 w-3.5"})})]}),s.jsx("p",{id:"cm-coach-title",className:"cm-coach-title",children:t}),s.jsx("p",{id:"cm-coach-body",className:"cm-coach-body",children:n}),s.jsx("button",{ref:f,type:"button",className:"cm-coach-ok","data-testid":"onb-coachmark-next",onClick:M,children:r})]},t)]}),document.body)},gs=5,uk=["do","schedule","delegate","backlog"],Yl=e=>(e.labels||[]).some(t=>uk.includes(t.toLowerCase())),mk=()=>{try{return window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{return!1}},oh=()=>!!document.querySelector('[role="dialog"]')||document.documentElement.classList.contains("task-focus-active"),fk=()=>oh()||!!document.querySelector("[data-radix-popper-content-wrapper]"),Wl=360,Gl={start:0,rest:1,view:2,bar:2},hk={phase:"off",quiet:!1,signupDay:!1,card:null,startSorting:()=>{},dismissCard:()=>{},starterSheet:null,recordSorted:()=>{},unrecordSorted:()=>{},holdsDailyReview:!1,allowCtrlBanner:!0,allowGestureHint:!0,compactPricing:!1,plansHold:"none",nudgeAllowed:!0,viewTipAllowed:!0},ih=i.createContext(hk),Ot=()=>i.useContext(ih),pk=({children:e,firstRun:t,tasks:n,unlabeledTasks:a,tasksReady:r,fetchFailed:o,paymentStatus:c,categorizeSheetOpen:l,markOnboardingComplete:d})=>{const{session:m}=we.useSessionContext(),u=m?.user?.id??null,f=m?.user?.email,p=m?.user?.created_at??null,h=nh(p),g=nk(p),b=Fe(),{view:x,showTip:y}=da(),w=b?"mobile":x==="clean"?"clean":"classic",[k,N]=i.useState("off"),[C,v]=i.useState("sort"),[j,T]=i.useState("sort"),[_,I]=i.useState([]),[R,M]=i.useState([]),[P,E]=i.useState(!1),[D,L]=i.useState(!1),[A,H]=i.useState(!1),[K,X]=i.useState(!1),[ce,oe]=i.useState(null),[ve,Ce]=i.useState(!1),[ee,Le]=i.useState(null),he=i.useRef(!1),ge=i.useRef(k);ge.current=k;const Te=i.useRef(!1);Te.current=D;const De=i.useRef(new Set),re=i.useCallback((z,ie)=>{const fe=window.setTimeout(()=>{De.current.delete(fe),z()},ie);De.current.add(fe)},[]),se=i.useCallback(()=>{De.current.forEach(z=>window.clearTimeout(z)),De.current.clear()},[]);i.useEffect(()=>se,[se]);const ue=i.useRef([]),Qe=i.useRef(0),$=i.useRef(n);$.current=n;const O=i.useRef(null),F=i.useCallback((z,ie={})=>{u&&Pt(u,f,"onboarding",{event:z,...ie}),z==="sort_started"?pe("categorize_opened",{kind:"starter",unsorted:$a(Number(ie.total)||0)}):z==="walk_started"?pe("tour_started",{kind:"onboarding",layout:Hn()}):z==="walk_ended"&&ie.reason==="done"?pe("tour_completed",{kind:"onboarding"}):z==="walk_ended"&&pe("tour_skipped",{kind:"onboarding",step:Number(ie.atIndex)||0}),z==="welcome_shown"?pe("starter_card",{action:"shown"}):z==="sort_started"||z==="add_started"?pe("starter_card",{action:"started"}):z==="welcome_dismissed"&&pe("starter_card",{action:"dismissed"})},[u,f]),Q=i.useMemo(()=>n.filter(Yl),[n]),V=Q.length,G=a.length,Y=i.useMemo(()=>n.filter(z=>(z.labels||[]).some(ie=>ie.toLowerCase()==="do")).length,[n]);i.useEffect(()=>{r&&O.current===null&&(O.current=Date.now())},[r]),i.useEffect(()=>{if(he.current||!u||!t.checked)return;he.current=!0;const z=Rt(u);if(z.phase==="done"||z.phase==="skipped"){t.eligible&&d();return}if(!t.eligible){(z.phase==="welcome"||z.phase==="sorting"||z.phase==="walk")&&_n(u,{phase:"done",walkStepId:null});return}H(Ex()),X(!0),Bc(u),I(z.queue),M(z.sorted),ue.current=z.sorted,oe(z.walkStepId),N("pending")},[u,t,d]);const J=i.useCallback(z=>{u&&_n(u,z)},[u]),le=i.useCallback((z,ie)=>{T(z),N("reveal"),re(()=>{ge.current==="reveal"&&(N("walk"),J({phase:"walk"}))},ie)},[J,re]),U=i.useCallback((z,{scroll:ie=!0}={})=>{N("reveal"),L(!0),Hc(),F("sort_closed",{sorted:z.length,total:_.length}),re(()=>{if(L(!1),window.dispatchEvent(new Event("resize")),ie){const qe=d
32ocument.querySelector(".cm-root")??document.querySelector(".matrix-grid");qe&&qe.getBoundingClientRect().top>window.innerHeight*.6&&qe.scrollIntoView({block:"start",behavior:mk()?"auto":"smooth"})}const fe=Date.now(),$e=()=>{const qe=new Map($.current.map(_t=>[_t.id,_t]));if(!z.every(_t=>{const Fs=qe.get(_t);return!Fs||Yl(Fs)})&&Date.now()-fe<3e3){re($e,100);return}re(()=>{ge.current==="reveal"&&(window.dispatchEvent(new CustomEvent("onboarding:reveal",{detail:{ids:z}})),le("sort",1400))},350)};$e()},Wl)},[F,_.length,le,re]);i.useEffect(()=>{if(k!=="pending"||!u||!r||o)return;const z=Rt(u);if(z.phase==="walk"){le(V>=gs&&!z.sorted.length?"presorted":"sort",1500);return}if(z.phase==="sorting"&&z.queue.length){const fe=new Set(a.map(qe=>qe.id)),$e=z.queue.filter(qe=>fe.has(qe)&&!z.sorted.includes(qe));if(!$e.length&&z.sorted.length){U(z.sorted,{scroll:!1});return}if($e.length){v("resume"),N("welcome");return}I([]),J({queue:[]})}if(z.phase==="welcome"&&z.queue.length){const fe=new Set(a.map($e=>$e.id));if(z.queue.some($e=>fe.has($e))){v("sort"),N("welcome");return}I([]),J({queue:[]})}if(n.length===0){v("empty"),N("welcome"),J({phase:"welcome",queue:[],firstSeenAt:new Date().toISOString()}),F("welcome_shown",{variant:"empty",unlabeled:0,categorized:0});return}if(V>=gs||G===0){le("presorted",1500);return}const ie=Ca(a,gs);I(ie),v("sort"),N("welcome"),J({phase:"welcome",queue:ie,firstSeenAt:new Date().toISOString()}),F("welcome_shown",{variant:"sort",unlabeled:G,categorized:V})},[k,u,r,o,n.length,V,a,G,J,F,U,le]),i.useEffect(()=>{if(!(k!=="welcome"||C==="empty"||G>0||n.length===0)){if(C==="second"){N("skipped");return}if(ue.current.length>=1){U(ue.current,{scroll:!1});return}J({queue:[]}),le("presorted",600)}},[k,C,G,n.length,U,le,J,F]),i.useEffect(()=>{if(k!=="welcome"||C!=="empty"||V>0||G===0)return;const z=Ca(a,gs);I(z),v("sort"),J({queue:z})},[k,C,V,G,a,J]),i.useEffect(()=>{k!=="welcome"||C!=="empty"||V<1||U(Q.map(z=>z.id).slice(0,8))},[k,C,V,Q,U]);const ne=i.useCallback((z,ie,fe)=>{if(!u||ge.current!=="welcome"&&ge.current!=="sorting")return;const $e=Array.from(new Set([...ue.current,...z]));z.forEach((qe,ms)=>F("task_sorted",{index:ue.current.length+ms,quadrant:ie.toLowerCase(),source:fe})),ue.current=$e,M($e),J({sorted:$e})},[u,F,J]),me=i.useCallback(z=>{if(!u||!z.length)return;const ie=new Set(z),fe=ue.current.filter($e=>!ie.has($e));fe.length!==ue.current.length&&(ue.current=fe,M(fe),J({sorted:fe}))},[u,J]),q=i.useCallback(()=>{if(C==="empty"){F("add_started"),document.getElementById("add-task-btn")?.click();return}let z=_;const ie=new Set(a.map(fe=>fe.id));z.some(fe=>ie.has(fe)&&!ue.current.includes(fe))||(z=Ca(a.filter(fe=>!ue.current.includes(fe.id)),gs),I(z),J({queue:z})),Qe.current=z.filter(fe=>ue.current.includes(fe)).length,N("sorting"),xe.current=!0,E(!0),J({phase:"sorting"}),F("sort_started",{total:z.length,resumed:C==="resume"})},[C,_,a,J,F]),xe=i.useRef(!1),ke=i.useCallback(z=>{!z&&!xe.current||(xe.current=z,E(z),!z&&(ue.current.length>=1?U(ue.current):(N("welcome"),J({phase:"welcome"}))))},[U,J]),We=i.useRef(l);i.useEffect(()=>{const z=We.current;We.current=l,z&&!l&&k==="welcome"&&ue.current.length>=1&&U(ue.current)},[l,k,U]);const Ze=i.useCallback(()=>{if(!u||Te.current||ge.current!=="welcome"&&ge.current!=="sorting")return;Te.current=!0,se();const ie=Rt(u).dismissCount+1;L(!0),re(()=>{L(!1),N("skipped"),window.dispatchEvent(new Event("resize"))},Wl),J({phase:"skipped",dismissCount:ie}),d(),Hc(),F("welcome_dismissed",{count:ie});const fe=document.getElementById("add-task-btn");fe&&fe.getBoundingClientRect().width>0?fe.focus():document.activeElement?.blur?.()},[u,J,d,F,se,re]),de=i.useMemo(()=>k==="walk"?rk({surface:w,variant:j,justConnected:A,doCount:Y,unsorted:G,touch:ok(),short:rh()}):[],[k,w,j,A,Y,G]),[be,Se]=i.useState([]);i.useEffect(()=>{if(k!=="walk"){Se([]);return}w==="mobile"&&window.dispatchEvent(new Event("mobile-bar:show"));const z=window.setTimeout(()=>{Se(de.filter(ie=>ns(ie.anchor)))},60);return()=>window.clearTimeout(z)},[k,de,w]);const Me=i.useMemo(()=>{if(!be.length)return-1;const z=ce?be.findIndex($e=>$e.id===ce):0;
32if(z>=0)return z;const ie=Gl[ce??"start"]??0,fe=be.findIndex($e=>(Gl[$e.id]??0)>=ie);return fe>=0?fe:be.length-1},[be,ce]),Je=i.useRef(!1);i.useEffect(()=>{k!=="walk"||!be.length||Je.current||(Je.current=!0,F("walk_started",{view:w,steps:be.length,variant:j}))},[k,be.length,w,j,F]);const ft=i.useRef(new Set);i.useEffect(()=>{const z=be[Me];k!=="walk"||!z||(ft.current.has(z.id)||(ft.current.add(z.id),F("walk_step",{index:Me,id:z.id})),z.id==="bar"&&window.dispatchEvent(new Event("mobile-bar:show")))},[k,be,Me,F]);const rt=i.useCallback(z=>{if(!u||ge.current!=="walk")return;ge.current="done",N("done"),J({phase:"done",walkStepId:null});const ie=ft.current;ie.has("view")&&ql(u),d(ie.has("rest")?{has_seen_category_tour:!0}:void 0),F("walk_ended",{reason:z,atIndex:Me})},[u,J,d,F,Me]),$t=i.useCallback(()=>{const z=be[Me+1];if(!z){rt("done");return}oe(z.id),J({walkStepId:z.id})},[be,Me,rt,J]);i.useEffect(()=>{if(k!=="walk"||!de.length)return;const z=window.setTimeout(()=>{const ie=de.filter(fe=>ns(fe.anchor));ie.length?Se(fe=>fe.length?fe:ie):rt("done")},1500);return()=>window.clearTimeout(z)},[k,de,rt]),i.useEffect(()=>{if(k!=="walk"&&!ee)return;let z=null;const ie=window.setInterval(()=>{oh()?(z=null,Ce(!0)):(z??=Date.now(),Date.now()-z>=600&&Ce(!1))},250);return()=>window.clearInterval(ie)},[k,ee]);const Ft=i.useRef(!1);i.useEffect(()=>{if(Ft.current||!u||!Ju||!t.checked||!r||K||k!=="off"||(Ft.current=!0,_x(u)))return;const z=Rt(u);let ie=!1;try{ie=!!localStorage.getItem(`onb:used-focus:${u}`)}catch{}let fe=!1;try{const wn=localStorage.getItem("categorize-nudge-day"),[qt,Et,fs]=(wn||"").split("-").map(Number);wn&&!Number.isNaN(qt+Et+fs)&&(fe=ls(new Date,new Date(qt,Et,fs))<3)}catch{}const $e=!!z.firstSeenAt||z.phase==="done"||z.phase==="skipped",qe=[];z.phase==="skipped"&&z.dismissCount===1&&V<3&&!h&&G>0&&qe.push("second"),g>=2&&G>=5&&!fe&&qe.push("nudge");const ms=wn=>!h&&!z.tipsShown.includes(wn);if($e&&Y>=1&&!ie&&ms("focus")&&qe.push("focus"),$e&&g>=2&&ms("stats")&&qe.push("stats"),!b&&y&&ms("view")&&qe.push("view"),$e&&g>=5&&V>=10&&ms("recat")&&qe.push("recat"),!qe.length)return;let _t=0,Fs=null;const Mc=window.setInterval(()=>{if(document.querySelector(".daily-review")&&(Fs=Date.now()),Date.now()-(O.current??Date.now())<1e4||fk()||Fs!==null&&Date.now()-Fs<8e3)return;for(;_t<qe.length;){const Et=qe[_t];if((Et==="focus"||Et==="stats"||Et==="recat")&&!ns(lo[Et](b).anchor)){_t++;continue}if(Et==="view"&&!document.querySelector(".cm-switch")){_t++;continue}break}window.clearInterval(Mc);const qt=qe[_t];if(!(!qt||!Bc(u))){if(qt==="second"){const Et=new Set(a.map(Ur=>Ur.id));let fs=z.queue.filter(Ur=>Et.has(Ur));fs.length||(fs=Ca(a,gs)),v("second"),I(fs),_n(u,{queue:fs}),N("welcome"),F("welcome_shown",{variant:"second",unlabeled:G,categorized:V});return}qt!=="nudge"&&(_n(u,{tipsShown:[...Rt(u).tipsShown,qt]}),F("tip_shown",{id:qt})),b&&window.dispatchEvent(new Event("mobile-bar:show")),Le(qt)}},2e3);return()=>window.clearInterval(Mc)},[u,t.checked,r,K,k]);const et=i.useCallback(()=>{ee==="view"&&u&&ql(u),Le(null)},[ee,u]),bt=k==="pending"||k==="welcome"||k==="sorting"||k==="reveal"||k==="walk",Tt=bt&&K,us=i.useMemo(()=>{if(!u||!t.checked)return!1;const z=Rt(u).phase;return z==="done"||z==="skipped"},[u,t.checked]),es=!c||c==="trial",Os=!!u&&(!t.checked||t.eligible&&!us&&!K&&k==="off"),$s=bt?"onboarding":Os?"deciding":"none",ae=i.useMemo(()=>{const z=new Map(a.map(ie=>[ie.id,ie]));return _.filter(ie=>!R.includes(ie)).map(ie=>z.get(ie)).filter(ie=>!!ie)},[_,R,a]),ye=k==="welcome"||k==="sorting"||k==="reveal"&&D||k==="skipped"&&D,ze=C==="second"||C==="resume"?Math.max(_.length,1):Math.min(gs,Math.max(G,_.length)),Re=i.useMemo(()=>({phase:k,quiet:bt,signupDay:h,card:ye?{variant:C,unsorted:G,k:_.length||ze,sortedOfQueue:_.filter(z=>R.includes(z)).length,firstName:t.firstName,justConnected:A,closing:D}:null,startSorting:q,dismissCard:Ze,starterSheet:_.length>0?{open:P,tasks:ae,total:_.length,alreadySorted:Qe.current,onOpenChange:ke}:null,recordSorted:ne,holdsDailyReview:K||t.checked&&t.eligible&&!us,allowCtrlBanner:!Tt&&!h&&V>=1,allowGestureHint:!Tt&&!h,compactPricing:(h||Tt)&&es,plansHold:$s,nudgeAllowed:ee==="nudge",viewTipAllowed:ee==="view",unrecordSorted:me}),[k,bt,h,ye,C,G,_,ze,R,t.firstName,A,D,q,Ze,P,ae,ke,ne,K,t.checked,t.eligible,V,es,ee,Tt,us,me,$s]),Ae=k==="walk"?be[Me]:void 0,Xe=ee&&ee in lo?lo[ee](b):void 0,ma=b?84:0;return s.jsxs(ih.Provider,{value:Re,children:[e,Ae&&!ve&&s.jsx(Kl,{anchor:Ae.anchor,title:Ae.title,body:Ae.body,step:{index:Me+1,total:be.length},primaryLabel:Me===be.length-1?"Done":"Next",onPrimary:$t,onClose:()=>rt("skipped"),onAnchorClick:$t,returnFocusOnPrimary:Me===be.length-1,bottomInset:ma},Ae.id),Xe&&!ve&&s.jsx(Kl,{anchor:Xe.anchor,title:Xe.title,body:Xe.body,primaryLabel:"Got it",onPrimary:et,onClose:et,onAnchorClick:et,returnFocusOnPrimary:!0,bottomInset:ma},Xe.id)]})},gk=[{id:"do",label:"Do First"},{id:"schedule",label:"Schedule"},{id:"delegate",label:"Delegate"},{id:"backlog",label:"Backlog"}],qs="min-h-[44px] gap-3 px-3 text-[15px] rounded-lg",xk=({at:e,title:t,count:n,current:a,selected:r,onClose:o,onMove:c,onComplete:l,onCompleteFollowUp:d,onFocus:m,onToggleSelect:u,onDelete:f})=>s.jsxs(hn,{open:!0,onOpenChange:p=>{p||o()},children:[s.jsx(pn,{asChild:!0,children:s.jsx("span",{className:"cm-menu-anchor",style:{left:e.x,top:e.y},"aria-hidden":!0,tabIndex:-1})}
32),s.jsxs(As,{className:"cm-touch-menu w-64 rounded-xl p-1.5",side:"bottom",align:"start",sideOffset:10,collisionPadding:12,onCloseAutoFocus:p=>p.preventDefault(),onClick:p=>p.stopPropagation(),children:[s.jsx(tn,{className:"truncate px-3 pb-1 pt-2 text-[13px] font-medium text-muted-foreground",children:n>1?`${n} selected`:t}),s.jsx(tn,{className:"px-3 pb-1 pt-1 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Move to"}),gk.map(p=>{const h=p.id===a&&n===1;return s.jsxs(dt,{className:qs,"aria-current":h||void 0,"data-quadrant-choice":p.id,onSelect:()=>{h||c(p.id)},children:[s.jsx("span",{className:"h-2.5 w-2.5 shrink-0 rounded-full",style:{background:`rgb(var(--q-${p.id}))`},"aria-hidden":!0}),s.jsx("span",{className:S("flex-1",h&&"font-medium"),children:p.label}),h&&s.jsx(Oe,{className:"h-4 w-4 text-muted-foreground","aria-label":"current quadrant"})]},p.id)}),s.jsx(is,{className:"my-1.5"}),s.jsxs(dt,{className:qs,onSelect:l,children:[s.jsx(Li,{className:"h-4 w-4 text-muted-foreground","aria-hidden":!0}),"Complete"]}),s.jsxs(dt,{className:qs,onSelect:d,children:[s.jsx(Wp,{className:"h-4 w-4 text-muted-foreground","aria-hidden":!0}),"Complete & follow up"]}),s.jsxs(dt,{className:qs,onSelect:m,children:[s.jsx(xu,{className:"h-4 w-4 text-muted-foreground","aria-hidden":!0}),"Focus"]}),s.jsxs(dt,{className:qs,onSelect:u,children:[s.jsx(gu,{className:"h-4 w-4 text-muted-foreground","aria-hidden":!0}),r?"Deselect":"Select"]}),s.jsx(is,{className:"my-1.5"}),s.jsxs(dt,{className:S(qs,"cm-menu-danger"),"data-action":"delete",onSelect:f,children:[s.jsx(Is,{className:"h-4 w-4","aria-hidden":!0}),"Delete task"]})]})]}),Xo="task:follow-up",Zo=e=>{window.dispatchEvent(new CustomEvent(Xo,{detail:e}))},ch="toast-follow-up",bk=()=>document.querySelector(`[data-sonner-toast][data-visible="true"][data-removed="false"] .${ch}`),ei=new Set,yk=e=>{ei.add(e),window.setTimeout(()=>ei.delete(e),3e4)},wk=e=>ei.delete(e),vk=(e,t,n=0)=>{const a=Ew(e);yk(e.id),t(),n?window.setTimeout(()=>Zo(a),n):Zo(a)},ti="task:delete",si=e=>{window.dispatchEvent(new CustomEvent(ti,{detail:e}))},kk=e=>{window.open(`https://todoist.com/app/task/${e}`,"_blank","noopener")},Ql=e=>{window.dispatchEvent(new CustomEvent("task:open-focus",{detail:{taskId:e}}))},jk=450,Nk=8,Sk=e=>document.querySelector(`[role="option"][data-task-id="${CSS.escape(e)}"]`)?.closest("[data-quadrant]")?.dataset.quadrant,lh=i.memo(({task:e,quadrant:t,onComplete:n,isFocusMode:a=!1,isFocusedTask:r=!1,onFocus:o,isKeyboardFocused:c=!1,onPointerFocus:l,request:d,onRequestHandled:m,wide:u=!1,introIndex:f,parentAbove:p=!1})=>{const{id:h,title:g,description:b,due:x,deadline:y,priority:w,labels:k}=e,N=of(h,g),C=N.title,{isSelected:v,toggleTaskSelection:j,hasSelectedTasks:T,selectedTasks:_,clearSelection:I}=$r(),R=Nc(h),{density:M,config:P}=Zt(),{nestSubtasks:E}=ds(),{nestedDescendantCountByRoot:D,nestedSubtasksByParent:L}=oa(),[A,H]=ct("matrix-subtasks-open",[]),K=vc(h),{keep:X,revert:ce}=xn(),[oe,ve]=i.useState("idle"),Ce=Wf(h),ee=oe!=="idle",Le=i.useRef(null),he=i.useRef([]);i.useEffect(()=>()=>he.current.forEach(clearTimeout),[]);const[ge,Te]=i.useState(!1),[De,re]=i.useState(!1),[se,ue]=i.useState(!1),Qe=i.useRef(null),[$,O]=i.useState(null),F=i.useRef(null),Q=i.useRef(!1),V=i.useRef("mouse"),G=i.useCallback(()=>{F.current&&window.clearTimeout(F.current.timer),F.current=null,Le.current?.classList.remove("is-pressing")},[]);i.useEffect(()=>G,[G]);const Y=i.useCallback((ae,ye)=>{const ze=Qe.current?.getBoundingClientRect();ze&&(O({x:ae-ze.left,y:ye-ze.top}),pe("task_opened",{surface:"detail"}))},[]),J=v(h);ra(i.useMemo(()=>[e],[e]));const le=Pf(e),U=iv(e),ne=E?D.get(h)??0:0,me=ne>0&&A.includes(h),q=yc(e,{parentAbove:p}),xe=i.useMemo(()=>Ir(k),[k]);i.useEffect(()=>{d&&(d==="due"&&Te(!0),d==="deadline"&&re(!0),d==="comments"&&ue(!0),d==="rename"&&N.start(),m?.())},[d,m]);const ke=i.useCallback(async ae=>{if(ae?.stopPropagation(),ae&&V.current!=="mouse"&&T()){j(h);return}if(ee)return;const ye=!!x?.isRecurring,ze=Re=>new Promise(Ae=>{he.current.push(window.setTimeout(Ae,Re))});ve("check"),window.matchMedia?.("(prefers-reduced-motion: reduce)").matches?(ye||he.current.push(window.setTimeout(()=>ve("close"),120)),await ze(ye?240:260)):(he.current.push(window.setTimeout(()=>ve("dim"),320)),ye||he.current.push(window.setTimeout(()=>ve("close"),480)),await ze(ye?480:700));try{await n(h),ye&&ve("idle")}catch{ve("idle")}},[ee,n,h,x?.isRecurring,T,j]);i.useEffect(()=>{const ae=ye=>{ye.detail?.taskId===h&&(Le.current?.closest("[inert]")||ke())};return window.addEventListener("matrix:complete-row",ae),()=>window.removeEventListener("matrix:complete-row",ae)},[h,ke]);const We=i.useCallback(ae=>{if(Q.current){Q.current=!1;return}
32l?.(),T()||ae.ctrlKey||ae.metaKey?(ae.preventDefault(),j(h)):a&&o?.(h)},[l,T,j,h,a,o]),Ze=ae=>{ae.stopPropagation(),H(ye=>ye.includes(h)?ye.filter(ze=>ze!==h):[...ye,h]),me||pe("task_opened",{surface:"expand"})},de=Ye(x)??void 0,be=_r(x),Se=ae=>{en(h,ae,be,!!x?.isRecurring),Te(!1)},Me=ae=>{en(h,de??_s(),ae,!!x?.isRecurring,{kind:"time"})},Je=ae=>{if(V.current=ae.pointerType,Q.current=!1,ae.pointerType==="mouse"||!ae.isPrimary||ee||N.editing){G();return}if(ae.target.closest("input, textarea, .cm-row-more"))return;G();const{clientX:ye,clientY:ze,pointerId:Re}=ae;Le.current?.classList.add("is-pressing"),F.current={x:ye,y:ze,id:Re,timer:window.setTimeout(()=>{F.current=null,Le.current?.classList.remove("is-pressing"),Q.current=!0,ut(10),Y(ye,ze)},jk)}},ft=ae=>{const ye=F.current;ye&&ae.pointerId===ye.id&&Math.hypot(ae.clientX-ye.x,ae.clientY-ye.y)>Nk&&G()},rt=ae=>{if(F.current||Q.current||V.current!=="mouse"){ae.preventDefault();return}ee||N.editing||ae.target.closest("input, textarea")||(ae.preventDefault(),Y(ae.clientX,ae.clientY))},$t=ae=>{ae.stopPropagation();const ye=ae.currentTarget.getBoundingClientRect();Y(ye.left,ye.bottom-4)},Ft=ae=>{const ye=J&&_.size>1,ze=ye?Array.from(_):[h],Re={};ze.forEach(Ae=>{const Xe=Ae===h?t:Sk(Ae);Xe&&(Re[Ae]=Xe)}),!ze.every(Ae=>Re[Ae]===ae)&&(window.dispatchEvent(new CustomEvent("matrix:move-tasks",{detail:{ids:ze,to:ae,from:Re}})),ye&&I())},et=ae=>ae.stopPropagation(),bt=ge||De||!!$,Tt=M==="comfortable"||u,us=s.jsxs(s.Fragment,{children:[ne>0&&s.jsxs("button",{type:"button",className:"cm-suffix cm-suffix-btn",onClick:Ze,"aria-expanded":me,children:["· ",ne," ",ne===1?"subtask":"subtasks",s.jsx(mt,{className:S("cm-chev",me&&"rotate-180"),"aria-hidden":!0})]}),U&&!u&&s.jsxs("span",{className:S("cm-suffix",U.late&&"cm-late"),children:[" · ",U.text]}),q&&s.jsx(Jl,{crumb:q})]}),es=le.lateDays??0,Os=!le.late&&!!le.timed&&ia(e)==="today",$s=[C,le.late?es?`${es} ${es===1?"day":"days"} late`:`late, due ${le.text.replace(" ↻","")}`:le.text.replace(" ↻",""),x?.isRecurring?"recurring":"",w===4?"priority 1":"",R?"today's focus":"",q?.aria??""].filter(Boolean).join(", ");return s.jsxs("div",{ref:Qe,className:S("cm-row-wrap",oe==="close"&&"is-closing",Ce==="leaving"&&"is-closing is-deleting",f!==void 0&&"cm-intro-row"),style:f!==void 0?{"--intro-i":f}:void 0,children:[s.jsxs("div",{className:"cm-row-clip",children:[s.jsxs("div",{ref:Le,role:"option","aria-selected":J,"aria-label":$s,"data-task-id":h,className:S("cm-row group/row",Tt&&"cm-row-two",J&&"is-selected",ee&&"is-completing",oe==="dim"||oe==="close"?"is-dimmed":"",c&&"is-kbd",r&&"is-focused",le.late&&"is-late",bt&&"is-pinned",Ce==="restored"&&"cm-restored"),style:{minHeight:P.rowHeight,"--row-pad":`${(P.rowHeight-20)/2}px`},onClick:We,onPointerDown:Je,onPointerMove:ft,onPointerUp:G,onPointerCancel:G,onPointerLeave:G,onContextMenu:rt,children:[s.jsx("button",{type:"button",className:S("cm-ring",R&&"is-focus"),"aria-label":"Mark task as complete",onClick:ke,children:ee?s.jsx("svg",{className:"cm-check",width:"8",height:"8",viewBox:"0 0 8 8","aria-hidden":!0,children:s.jsx("path",{d:"M1 4.2 3.1 6.2 7 1.8"})}):J?s.jsx(Oe,{className:"h-2.5 w-2.5",strokeWidth:3.5}):null}),s.jsxs("div",{className:"cm-main",children:[s.jsxs("div",{className:"cm-line",children:[w===4&&s.jsx("span",{className:"cm-pri",children:"P1"}),N.editing?s.jsx(cf,{value:C,onCommit:N.commit,onCancel:N.cancel,className:"cm-title-input"}):s.jsxs(Ht,{delayDuration:500,children:[s.jsx(Vt,{asChild:!0,children:s.jsx("span",{className:"cm-title",onDoubleClick:ae=>{ae.stopPropagation(),N.start()},children:C})}),s.jsxs(At,{side:"bottom",align:"start",className:"max-w-sm space-y-1",children:[s.jsx("p",{className:"font-medium leading-snug",children:C}),b&&s.jsx("p",{className:"text-xs text-muted-foreground line-clamp-4",children:b}),xe.length>0&&s.jsx("p",{className:"text-xs text-muted-foreground",children:xe.join("  ")}),w&&w>1?s.jsxs("p",{className:"text-xs text-muted-foreground",children:["P",5-w]}):null,s.jsx("p",{className:"kbd-hint text-[11px] text-muted-foreground/80",children:"Double-click or R to rename"})]})]}),!u&&us]}),Tt&&b&&s.jsx("div",{className:"cm-desc truncate",children:b})]}),u&&s.jsxs("div",{className:"cm-meta truncate",children:[[ne?`${ne}
32 subtasks`:"",U?.text??""].filter(Boolean).join(" · "),q&&s.jsx(Jl,{crumb:q,lead:!!(ne||U)})]}),s.jsxs("div",{className:"cm-end",children:[s.jsx("span",{className:S("cm-date",le.late&&"cm-late",Os&&"cm-time"),children:ee?"Done":le.text}),s.jsx("button",{type:"button",className:"cm-row-more","aria-label":"Task actions","aria-haspopup":"menu","aria-expanded":!!$,onClick:$t,children:s.jsx(Gp,{})}),s.jsxs("div",{className:"cm-actions",onClick:et,children:[s.jsx("button",{type:"button",className:"cm-act","aria-label":"Comments",title:"Comments",onClick:()=>ue(!0),children:s.jsx(Ai,{})}),s.jsx("button",{type:"button",className:"cm-act","aria-label":"Open in Todoist",title:"Open in Todoist",onClick:()=>kk(h),children:s.jsx(pu,{})}),s.jsxs(Nt,{open:ge,onOpenChange:Te,children:[s.jsx(St,{asChild:!0,children:s.jsx("button",{type:"button",className:"cm-act","aria-label":x?.date?"Due date":"Add due date",title:x?.date?"Due date":"Add due date",children:s.jsx(Pi,{})})}),s.jsx(Ct,{className:"w-auto max-h-[var(--radix-popover-content-available-height)] overflow-y-auto p-0 rounded-xl shadow-xl border-border/40",align:"end",onClick:et,children:x?.isRecurring?s.jsx("p",{className:"p-3 text-sm text-muted-foreground max-w-[220px]",children:"Recurring task, open it in Todoist to reschedule."}):s.jsx(rn,{title:"Due date",value:de,onChange:Se,time:{value:be,onChange:Me},setActivePopover:()=>Te(!1)})})]}),s.jsxs(Nt,{open:De,onOpenChange:re,children:[s.jsx(St,{asChild:!0,children:s.jsx("button",{type:"button",className:S("cm-act",y&&"is-on"),"aria-label":"Deadline",title:"Deadline",children:s.jsx(os,{})})}),s.jsx(Ct,{className:"w-auto p-0 rounded-xl shadow-xl border-border/40",align:"end",onClick:et,children:s.jsx(xf,{taskId:h,deadline:y,onDone:()=>re(!1)})})]}),s.jsx("button",{type:"button",className:"cm-act","aria-label":"Focus on this task",title:"Focus",onClick:()=>Ql(h),children:s.jsx(xu,{})}),s.jsx("button",{type:"button",className:"cm-act","aria-label":"Rename",title:"Rename (R)",onClick:N.start,children:s.jsx(hu,{})}),s.jsx("button",{type:"button",className:"cm-act cm-act-danger","aria-label":"Delete task",title:"Delete (Del)","data-action":"delete",onClick:()=>si({taskId:h,via:"menu",quadrant:t,task:e}),children:s.jsx(Is,{})})]})]})]}),me&&s.jsx("div",{className:"cm-subtasks",role:"group","aria-label":`Subtasks of ${C}`,children:(L.get(h)??[]).map(ae=>s.jsx(Ck,{task:ae},ae.id))}),K&&s.jsx("div",{className:"cm-marker",children:s.jsx(kc,{entry:K,onKeep:()=>X(h),onRevert:()=>ce(h)})})]}),$&&s.jsx(xk,{at:$,title:C,count:J&&_.size>1?_.size:1,current:t,selected:J,onClose:()=>O(null),onMove:Ft,onComplete:()=>{ke()},onCompleteFollowUp:()=>vk(e,()=>{ke()}),onFocus:()=>Ql(h),onToggleSelect:()=>j(h),onDelete:()=>si({taskId:h,via:"menu",quadrant:t,task:e})}),se&&s.jsx(gf,{isOpen:se,onClose:()=>ue(!1),taskId:h,taskTitle:C})]})});lh.displayName="TaskRow";const Jl=({crumb:e,lead:t=!0})=>s.jsxs("button",{type:"button",className:"cm-suffix cm-suffix-btn cm-parent","data-qa":"parent-crumb",title:e.known?`Subtask of ${e.text}`:"Subtask","aria-label":e.known?`Go to parent task: ${e.text}`:"Go to parent task",onClick:e.activate,children:[t?"· ":"","↳ ",s.jsx("span",{className:"cm-parent-text",children:e.text})]}),Ck=({task:e})=>{const[t,n]=i.useState(!1),a=Pf(e),r=o=>{o.stopPropagation(),n(!0),window.dispatchEvent(new CustomEvent("task:complete",{detail:{taskId:e.id}}))};return s.jsxs("div",{className:S("cm-row cm-sub",t&&"is-completing"),"data-task-id":e.id,children:[s.jsx("button",{type:"button",className:"cm-ring cm-ring-sm","aria-label":"Mark subtask as complete",onClick:r,children:t&&s.jsx(Oe,{className:"h-2 w-2",strokeWidth:3.5})}),s.jsx("div",{className:"cm-main",children:s.jsx("div",{className:"cm-line",children:s.jsx("span",{className:"cm-title",children:e.title})})}),s.jsx("div",{className:"cm-end",children:s.jsx("span",{className:S("cm-date",a.late&&"cm-late"),children:a.text})})]})},Tk={do:"Urgent · Important",schedule:"Not urgent · Important",delegate:"Urgent · Not important",backlog:"Not urgent · N
32ot important"},_k=e=>`var(--q-${e})`,Xl=(e,t)=>{const n=Array.from(e.querySelectorAll(`[data-bucket="${t}"]`));n.length&&(n[0].scrollIntoView({behavior:"smooth",block:"nearest"}),n.forEach(a=>{a.classList.remove("parent-task-flash"),a.offsetWidth,a.classList.add("parent-task-flash"),window.setTimeout(()=>a.classList.remove("parent-task-flash"),1900)}))},Zl=({quadrant:e,onComplete:t,isFocusMode:n,focusedTaskId:a,onTaskFocus:r,collapsed:o=!1,onToggleCollapse:c,expanded:l=!1,onExpand:d,onCollapseExpanded:m,keyboardIndex:u=null,onRowPointerFocus:f,request:p,onRequestHandled:h,adding:g=!1,onAddingChange:b,sideLabel:x,scrollStore:y,intro:w=!1,heldCount:k})=>{const{phase:N}=Ot(),C=N==="welcome"||N==="sorting",{title:v,description:j,droppableId:T,tasks:_}=e,I=i.useRef(null),[R,M]=i.useState(0),[P,E]=i.useState(""),D=i.useRef(new Set),L=i.useCallback(O=>(D.current.add(O),t(O).catch(F=>{throw D.current.delete(O),F})),[t]),[A,H]=i.useState(!1),[K,X]=i.useState(_);K!==_&&(X(_),_.length===0&&K.length>0&&K.every(O=>D.current.has(O.id))?H(!0):_.length>0&&A&&H(!1),D.current.forEach(O=>{_.some(F=>F.id===O)||D.current.delete(O)}));const ce=ra(_),oe=i.useMemo(()=>Of(_),[_,ce]),ve=la(),Ce=i.useMemo(()=>ov(_,new Date,ve),[_,ve,ce]),ee=i.useMemo(()=>l?[{bucket:"all",label:"",tasks:_}]:Ce,[l,_,Ce]),Le=i.useMemo(()=>{const O=new Set;return ee.forEach(F=>nf(F.tasks).forEach(Q=>O.add(Q))),O},[ee]),he=Ce.length>=2&&!l,ge=l?`${T}:expanded`:T,Te=i.useCallback(()=>{const O=I.current;if(!O)return;const F=O.getBoundingClientRect().bottom;let Q=0;O.querySelectorAll('.cm-row-wrap:not(.is-closing) > .cm-row-clip > [role="option"]').forEach(V=>{const G=parseFloat(getComputedStyle(V).paddingTop)||0;V.getBoundingClientRect().top+G+10>F&&Q++}),M(Q),y&&(y[ge]=O.scrollTop)},[y,ge]);i.useLayoutEffect(()=>{const O=I.current,F=y?.[ge];O&&F&&(O.scrollTop=F)},[o,ge]),i.useLayoutEffect(()=>{Te()},[Te,_,o,l]),i.useEffect(()=>{const O=I.current;if(!O)return;const F=new ResizeObserver(Te);return F.observe(O),()=>F.disconnect()},[Te,o]),i.useEffect(()=>{if(u==null)return;const O=_[u]?.id;O&&I.current?.querySelector(`[data-task-id="${O}"]`)?.scrollIntoView({block:"nearest"})},[u,_]);const De=()=>{const O=P.trim();O&&window.dispatchEvent(new CustomEvent("task:create-in-quadrant",{detail:{content:O,quadrant:T}})),E(""),b?.(!1)},re=()=>{hr(T)&&Sc({title:P,quadrant:T}),E(""),b?.(!1)},se=i.useRef();i.useEffect(()=>()=>window.clearTimeout(se.current),[]);const ue=O=>{if(!(l||O.target.closest("button"))){if(window.clearTimeout(se.current),O.detail>=2){d?.();return}se.current=window.setTimeout(()=>c?.(),200)}},Qe=[v,`${_.length} ${_.length===1?"task":"tasks"}`,oe.late?`${oe.late} late`:"",oe.today?`${oe.today} today`:""].filter(Boolean).join(", ");let $=-1;return s.jsxs("section",{className:S("cm-quad",o&&"is-collapsed",l&&"is-expanded",A&&_.length===0&&"is-cleared"),style:{"--acc":_k(T)},"aria-label":Qe,"data-quadrant":T,children:[x&&s.jsx("span",{className:"cm-side-label","aria-hidden":!0,children:x}),s.jsxs("header",{className:S("cm-qhead group/head",!l&&"is-clickable"),onClick:ue,children:[s.jsx("span",{className:S("cm-count",T==="do"&&"is-lead"),children:s.jsx(Ki,{value:k??_.length})}),s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"cm-qtitle",children:[s.jsx("span",{className:"cm-dot","aria-hidden":!0}),v,s.jsx("span",{className:"cm-axis-tag",children:Tk[T]})]}),s.jsx("div",{className:"cm-status",children:oe.late>0||oe.today>0?s.jsxs(s.Fragment,{children:[oe.late>0&&s.jsxs("button",{type:"button",className:"cm-late",onClick:()=>I.current&&Xl(I.current,"late"),children:[oe.late," late"]}),oe.late>0&&oe.today>0&&s.jsx("span",{"aria-hidden":!0,children:" · "}),oe.today>0&&s.jsxs("button",{type:"button",onClick:()=>I.current&&Xl(I.current,"today"),children:[oe.today," today"]})]}):oe.next?s.jsxs("span",{children:["Next: ",oe.next]}):s.jsx("span",{className:"truncate",children:_.length?"No dates":j.split(" - ")[0]})}),T==="do"&&s.jsx(Xf,{})]}),s.jsx("div",{className:"cm-qtools",children:l?s.jsxs("button",{type:"button",className:"cm-tool is-labelled",onClick:m,children:[s.jsx(Qp,{"aria-hidden":!0})," Back to matrix"]}):s.jsxs(s.Fragment,{children:[s.jsxs("button",{type:"button",className:"cm-tool","aria-label":`Expand ${v}`,title:"Expand (E)",onClick:d,children:[s.jsx(bu,{"aria-hidden":!0}
32),s.jsx("kbd",{className:"cm-kbd-inline","aria-hidden":!0,children:"E"})]}),s.jsx("button",{type:"button",className:"cm-tool","aria-label":o?`Show ${v}`:`Collapse ${v}`,"aria-expanded":!o,onClick:c,children:s.jsx(mt,{"aria-hidden":!0,className:S("cm-chevron",o&&"-rotate-90")})})]})})]}),s.jsxs("div",{className:"cm-list-wrap","aria-hidden":o||void 0,...o?{inert:""}:{},children:[s.jsxs("div",{ref:I,className:S("cm-list",R>0&&"has-more"),onScroll:Te,children:[_.length===0&&s.jsx("p",{className:"cm-empty",children:C?"Nothing sorted here yet":A?"All clear":"Nothing here"}),s.jsx("div",{role:"listbox","aria-label":`${v} tasks`,"aria-multiselectable":!0,children:ee.map(O=>s.jsxs("div",{role:"presentation",className:"cm-gblock",children:[he&&O.label&&s.jsxs("div",{className:S("cm-group",O.bucket==="late"&&"cm-late"),role:"presentation",children:[O.label,s.jsx("span",{children:O.tasks.length})]}),O.tasks.map(F=>{$++;const Q=$;return s.jsx("div",{"data-bucket":ia(F),className:S(l&&"cm-divided"),children:s.jsx(lh,{task:F,quadrant:T,onComplete:L,isFocusMode:n,isFocusedTask:a===F.id,onFocus:r,isKeyboardFocused:u===Q,onPointerFocus:()=>f?.(Q),request:p?.taskId===F.id?p.kind:null,onRequestHandled:h,wide:l,parentAbove:Le.has(F.id),introIndex:w&&Q<6?Q:void 0})},F.id)})]},O.bucket))}),g?s.jsxs("div",{className:"cm-row cm-add is-editing",children:[s.jsx("span",{className:"cm-ring","aria-hidden":!0}),s.jsx("input",{autoFocus:!0,className:"cm-add-input",placeholder:`Add to ${v}`,value:P,onChange:O=>E(O.target.value),onBlur:()=>{P.trim()||b?.(!1)},onKeyDown:O=>{if(O.key==="Enter"&&O.shiftKey){O.preventDefault(),re();return}O.key==="Enter"&&De(),O.key==="Escape"&&(E(""),b?.(!1))}}),s.jsx("button",{type:"button",className:"cm-add-more","aria-label":"More options",title:"More options (⇧Enter)",onMouseDown:O=>O.preventDefault(),onClick:re,children:s.jsx(ta,{"aria-hidden":!0})})]}):s.jsxs("button",{type:"button",className:S("cm-row cm-add",_.length===0&&"is-visible"),onClick:()=>b?.(!0),children:[s.jsx(fn,{className:"h-3.5 w-3.5","aria-hidden":!0}),"Add to ",v,s.jsx("kbd",{className:"cm-kbd-inline","aria-hidden":!0,children:"N"})]})]}),R>0&&!o&&s.jsxs("button",{type:"button",className:"cm-more",onClick:()=>I.current?.scrollBy({top:I.current.clientHeight*.85,behavior:"smooth"}),children:["↓ ",R," more"]})]})]})},xs=["do","schedule","delegate","backlog"],Ek={do:"schedule",schedule:"do",delegate:"backlog",backlog:"delegate"},Dk={do:"delegate",schedule:"backlog"},Rk={delegate:"do",backlog:"schedule"},ed={1:"do",2:"schedule",3:"delegate",4:"backlog"},bs="cubic-bezier(0.2, 0, 0, 1)",uo="cubic-bezier(0.05, 0.7, 0.1, 1)",Ik="cubic-bezier(0.3, 0, 0.8, 0.15)",Mk="cubic-bezier(0.35, 0, 0.1, 1)",Ta=(e,t)=>Math.min(e,5)*t,zs=()=>typeof window<"u"&&window.matchMedia?.("(prefers-reduced-motion: reduce)").matches,Ln=(e,t)=>{const n=new Map;return e&&e.querySelectorAll('[role="option"][data-task-id]').forEach(a=>{if(a.closest("[inert]"))return;const r=a.closest(".cm-list"),o=a.closest("[data-quadrant]"),c=a.dataset.taskId;if(!r||!o||!c)return;const l=a.getBoundingClientRect(),d=r.getBoundingClientRect();n.set(c,{el:a,q:o.dataset.quadrant??"",top:l.top,left:l.left,w:l.width,h:l.height,inList:l.top-d.top+r.scrollTop,visible:l.height>0&&l.bottom>d.top&&l.top<d.bottom,focus:t.has(c)})}),n},ni=new Set,td=e=>{if(!e)return null;const t=Ln(e,ni);return t.forEach((n,a)=>{n.visible||t.delete(a)}),{head:e.querySelector(".cm-qhead")?.getBoundingClientRect()??null,rows:t}},dh=(e,t)=>{e.classList.remove(t),e.offsetWidth,e.classList.add(t),e.addEventListener("animationend",()=>e.classList.remove(t),{once:!0})},mo=e=>dh(e,"cm-landing"),Lk=e=>{const t=e;return t?t.tagName==="INPUT"||t.tagName==="TEXTAREA"||t.tagName==="SELECT"||t.isContentEditable:!1},Ak=({quadrants:e,onCompleteTask:t,isTaskFocus:n,focusedTaskId:a,onTaskFocus:r})=>{const o=la(),{toggleTaskSelection:c,selectedTasks:l,isSelected:d}=$r(),m=i.useRef(null),[u,f]=i.useState(640),[p,h]=i.useState({do:!1,schedule:!1,delegate:!1,backlog:!1}),[g,b]=i.useState(null),[x,y]=i.useState(!1),[w,k]=i.useState(()=>{try{return!zs()&&!sessionStorage.getItem("cm-intro-played")}catch{return!1}}),[N,C]=i.useState(null),[v,j]=i.useState(null),[T,_]=i.useState(null),I=i.useRef(null),R=i.useRef({}),M=i.useMemo(()=>e.flatMap($=>$.tasks),[e]),P=ra(M),E=i.useMemo(()=>{const $={};return e.forEach(O=>
32{$[O.droppableId]={title:O.title,description:O.description,droppableId:O.droppableId,tasks:wc(O.tasks,o)}}),$},[e,o,P]);i.useEffect(()=>{const $=O=>{if(window.matchMedia?.("(prefers-reduced-motion: reduce)").matches)return;(O.detail?.ids??[]).map(V=>m.current?.querySelector(`[role="option"][data-task-id="${CSS.escape(V)}"]`)).filter(V=>!!V&&!V.closest("[inert]")).map(V=>({el:V,q:xs.indexOf(V.closest("[data-quadrant]")?.dataset.quadrant),top:V.getBoundingClientRect().top})).sort((V,G)=>V.q-G.q||V.top-G.top).slice(0,8).forEach(({el:V},G)=>{window.setTimeout(()=>{V.isConnected&&mo(V)},G*90)})};return window.addEventListener("onboarding:reveal",$),()=>window.removeEventListener("onboarding:reveal",$)},[]),i.useEffect(()=>{if(!w)return;try{sessionStorage.setItem("cm-intro-played","1")}catch{}const $=window.setTimeout(()=>k(!1),1100);return()=>window.clearTimeout($)},[w]);const D=i.useRef([]),L=i.useRef(E),A=i.useRef(o),H=i.useRef(null),[K,X]=i.useState(null),ce=i.useRef(0);if(L.current!==E){D.current.forEach(Y=>Y.finish()),D.current=[];const $=Ln(m.current,A.current);H.current=$;const O=L.current,F=new Map;xs.forEach(Y=>O[Y]?.tasks.forEach(J=>F.set(J.id,Y)));const Q={};let V=0;zs()||xs.forEach(Y=>E[Y]?.tasks.forEach(J=>{const le=F.get(J.id);!le||le===Y||!$.get(J.id)?.visible||(V++,Q[le]=O[le]?.tasks.length??0,Q[Y]=O[Y]?.tasks.length??0)})),ce.current++;const G=V>0&&V<=8?Q:null;(G||K)&&X(G),L.current=E,A.current=o}i.useLayoutEffect(()=>{const $=m.current,O=H.current;H.current=null;const F=ce.current,Q=()=>{ce.current===F&&X(null)};if(!O)return;if(!$||zs()){Q();return}const V=Ln($,o),G=[],Y=[];
32V.forEach((de,be)=>{const Se=O.get(be);if(!Se)return;if(Se.q!==de.q){G.push({from:Se,to:de});return}const Me=Se.inList-de.inList,Je=de.focus&&!Se.focus;Je&&dh(de.el,"cm-focus-arrive"),!(Math.abs(Me)<.5)&&Y.push({from:Se,to:de,dy:Me,rising:Je})});const J=G.length<=8,le=new Set(J?G.map(de=>de.from.q):[]),U=new Set(J?G.map(de=>de.to.q):[]),ne={};Y.sort((de,be)=>de.to.inList-be.to.inList).forEach(({to:de,dy:be,rising:Se})=>{const Me=ne[de.q]=(ne[de.q]??-1)+1,Je=U.has(de.q)&&!le.has(de.q),ft=Se?{duration:320,easing:bs}:Je?{duration:260,delay:120+Ta(Me,30),easing:uo,fill:"backwards"}:le.has(de.q)?{duration:220,delay:Ta(Me,30),easing:bs,fill:"backwards"}:{duration:220,easing:bs};D.current.push(de.el.animate([{transform:`translateY(${be}px)`},{transform:"translateY(0)"}],ft))});const me=$.getBoundingClientRect(),q=document.documentElement.classList.contains("dark"),xe=`hsl(${getComputedStyle($).getPropertyValue("--border").trim()||"0 0% 50%"})`,ke=`0 0 0 1px ${xe}, 0 3px 8px -2px rgb(0 0 0 / ${q?.5:.16})`,We=`0 0 0 1px ${xe}, 0 18px 32px -12px rgb(0 0 0 / ${q?.85:.3})`;let Ze=0;G.forEach(({from:de,to:be})=>{if(!J||!de.visible||!be.visible){mo(be.el);return}const Se=be.el.cloneNode(!0);Se.classList.add("cm-ghost"),Se.classList.remove("is-kbd","is-selected","cm-landing","cm-focus-arrive"),Se.removeAttribute("role"),Se.removeAttribute("data-task-id"),Se.setAttribute("aria-hidden","true"),Object.assign(Se.style,{left:`${de.left-me.left}px`,top:`${de.top-me.top}px`,width:`${de.w}px`,height:`${de.h}px`}),Se.style.setProperty("--acc",`var(--q-${de.q})`),$.appendChild(Se),be.el.style.visibility="hidden";const Me=be.left-de.left,Je=be.top-de.top,ft=Math.min(420,Math.max(280,240+.25*Math.hypot(Me,Je))),rt=Se.animate([{transform:"translate(0, 0)",boxShadow:ke},{offset:.5,transform:`translate(${Me/2}px, ${Je/2-12}px)`,boxShadow:We},{transform:`translate(${Me}px, ${Je}px)`,boxShadow:ke}],{duration:ft,delay:120,easing:Mk,fill:"both"});Ze++;let $t=!1;const Ft=et=>{$t||($t=!0,be.el.style.visibility="",mo(be.el),et?Se.animate([{opacity:1},{opacity:0}],{duration:120,easing:"ease-out",fill:"forwards"}).onfinish=()=>Se.remove():Se.remove(),--Ze===0&&Q())};rt.onfinish=()=>Ft(!0),rt.oncancel=()=>Ft(!1),D.current.push(rt)}),Ze===0&&Q()},[E,o]);const oe=i.useRef(null),ve=i.useCallback($=>{const O=m.current,F=O?.querySelector(`.cm-cell-${$}`);if(!O||!F)return null;const Q=O.getBoundingClientRect(),V=F.getBoundingClientRect();return`inset(${V.top-Q.top}px ${Q.right-V.right}px ${Q.bottom-V.bottom}px ${V.left-Q.left}px round 14px)`},[]),Ce=i.useRef(null),ee=$=>m.current?.querySelector(`.cm-cell-${$}`)??null,Le=i.useCallback($=>{y(!1),Ce.current=zs()?null:td(m.current?.querySelector(`.cm-cell-${$}`)??null),b($)},[]),he=i.useCallback(()=>{if(g){if(zs()){b(null);return}y(!0)}},[g]),ge=i.useRef(null);i.useLayoutEffect(()=>{const $=oe.current,O=g&&!ge.current;ge.current=g;const F=Ce.current;if(Ce.current=null,!$||!g||zs()||!O)return;const Q=ve(g);Q&&$.animate([{clipPath:Q},{clipPath:"inset(0px 0px 0px 0px round 14px)"}],{duration:300,easing:bs});const V=$.querySelector(".cm-expanded-main");if(!F||!V)return;const G=!V.querySelector(".cm-list")?.scrollTop;G&&$.classList.add("is-travelling");const Y=V.querySelector(".cm-qhead");if(Y&&F.head){const U=Y.getBoundingClientRect();Y.animate([{transform:`translate(${F.head.left-U.left}px, ${F.head.top-U.top}px)`},{transform:"none"}],{duration:300,easing:bs}),Y.querySelector(".cm-qtools")?.animate([{opacity:0},{opacity:1}],{duration:200,delay:220,easing:"ease-out",fill:"backwards"})}let J=0;Ln(V,ni).forEach((U,ne)=>{const me=G?F.rows.get(ne):void 0;if(me)U.el.animate([{transform:`translate(${me.left-U.left}px, ${me.top-U.top}px)`},{transform:"none"}],{duration:300,easing:bs});else if(U.visible){const q=240+Ta(J++,25);U.el.animate([{opacity:0},{opacity:1}],{duration:200,delay:q,easing:"ease-out",fill:"backwards"}),U.el.animate([{transform:"translateY(6px)"},{transform:"none"}],{duration:260,delay:q,easing:uo,fill:"backwards"})}}),$.querySelectorAll(".cm-rail > *").forEach((U,ne)=>{const me=150+Ta(ne,30);U.animate([{opacity:0}
32,{opacity:1}],{duration:200,delay:me,easing:"ease-out",fill:"backwards"}),U.animate([{transform:"translateX(-6px)"},{transform:"none"}],{duration:260,delay:me,easing:uo,fill:"backwards"})}),$.classList.add("is-entering");const le=window.setTimeout(()=>$.classList.remove("is-entering","is-travelling"),450);return()=>window.clearTimeout(le)},[g,ve]),i.useLayoutEffect(()=>{const $=oe.current;if(!x||!g)return;const O=ve(g);if(!$||!O){b(null),y(!1);return}const F=[],Q={duration:260,delay:60,easing:bs,fill:"forwards"},V={duration:80,easing:Ik,fill:"forwards"},G=$.querySelector(".cm-expanded-main"),Y=td(ee(g)),J=!G?.querySelector(".cm-list")?.scrollTop;if(J&&$.classList.add("is-travelling"),G&&Y){const U=G.querySelector(".cm-qhead");if(U&&Y.head){const ne=U.getBoundingClientRect();F.push(U.animate([{transform:"none"},{transform:`translate(${Y.head.left-ne.left}px, ${Y.head.top-ne.top}px)`}],Q));const me=U.querySelector(".cm-qtools");me&&F.push(me.animate([{opacity:1},{opacity:0}],V))}Ln(G,ni).forEach((ne,me)=>{const q=J?Y.rows.get(me):void 0;F.push(q?ne.el.animate([{transform:"none"},{transform:`translate(${q.left-ne.left}px, ${q.top-ne.top}px)`}],Q):ne.el.animate([{opacity:1},{opacity:0}],V))}),$.querySelectorAll(".cm-rail > *").forEach(ne=>F.push(ne.animate([{opacity:1},{opacity:0}],V)))}const le=$.animate([{clipPath:"inset(0px 0px 0px 0px round 14px)"},{clipPath:O}],Q);return le.onfinish=()=>{b(null),y(!1)},()=>{le.cancel(),F.forEach(U=>U.cancel())}},[x,g,ve]),i.useLayoutEffect(()=>{const $=()=>{const F=m.current;if(!F)return;document.documentElement.style.setProperty("--sbw",`${Math.max(0,window.innerWidth-document.documentElement.clientWidth)}px`);const Q=F.getBoundingClientRect().top+window.scrollY,V=Math.max(640,window.innerHeight-Q-24);f(V),requestAnimationFrame(()=>{const G=document.documentElement.scrollHeight-window.innerHeight;G>0&&V>640&&f(Math.max(640,V-G))})};$();const O=window.setTimeout($,400);return window.addEventListener("resize",$),()=>{window.clearTimeout(O),window.removeEventListener("resize",$)}},[]),i.useEffect(()=>{const $=O=>{const F=O.detail?.quadrant;!F||!xs.includes(F)||(h(Q=>Q[F]?{...Q,[F]:!1}:Q),b(Q=>Q&&Q!==F?null:Q),y(!1))};return window.addEventListener("matrix:reveal-task",$),()=>window.removeEventListener("matrix:reveal-task",$)},[]),i.useEffect(()=>{const $=O=>{const F=!!O.detail?.collapsed;h({do:F,schedule:F,delegate:F,backlog:F})};return window.addEventListener("toggle-all-quadrants",$),()=>window.removeEventListener("toggle-all-quadrants",$)},[]),i.useEffect(()=>{if(!N)return;const $=E[N.q]?.tasks.length??0;$===0?C(null):N.i>=$&&C({...N,i:$-1})},[E,N]);const Te=i.useCallback($=>{if(n||$.defaultPrevented||$.altKey||$.ctrlKey||$.metaKey||Lk($.target)||document.querySelector('[role="dialog"], [role="alertdialog"], [data-radix-popper-content-wrapper]'))return;const O=$.key;if((O===" "||O==="Enter")&&$.target?.closest?.('button, a, [role="button"], [role="radio"]'))return;const F=N??{q:g??"do",i:-1},Q=E[F.q]?.tasks??[],V=N?Q[N.i]:void 0,G=(Y,J)=>{const le=E[Y]?.tasks.length??0;!le||Y!==F.q&&p[Y]&&!g||C({q:Y,i:Math.max(0,Math.min(le-1,J)),visible:!0})};switch(O){case"ArrowDown":case"j":case"J":{$.preventDefault();const Y=!g&&Dk[F.q];Y&&F.i>=Q.length-1&&E[Y]?.tasks.length&&!p[Y]?G(Y,0):G(F.q,F.i+1);return}case"ArrowUp":case"k":case"K":{$.preventDefault();const Y=!g&&Rk[F.q];Y&&F.i===0&&E[Y]?.tasks.length&&!p[Y]?G(Y,E[Y].tasks.length-1):G(F.q,F.i<0?0:F.i-1);return}case"ArrowLeft":case"ArrowRight":case"h":case"H":case"l":case"L":{if(g)return;$.preventDefault();const Y=Ek[F.q];G(Y,Math.max(0,F.i));return}case"Escape":if(g){he(),$.preventDefault();return}N&&C(null);return;case"e":case"E":$.preventDefault(),g?he():Le(F.q);return;case"n":case"N":$.preventDefault(),h(Y=>({...Y,[F.q]:!1})),_(F.q);return}if(!V){O==="Enter"&&xs.every(Y=>!E[Y]?.tasks.length)&&($.preventDefault(),fc());return}if(O===" ")$.preventDefault(),window.dispatchEvent(new CustomEvent("matrix:complete-row",{detail:{taskId:V.id}}));else if(ed[O]){$.preventDefault();const Y=ed[O],J=l.size&&d(V.id)?Array.from(l):[V.id],le={};if(xs.forEach(U=>E[U]?.tasks.forEach(ne=>{J.includes(ne.id)&&(le[ne.id]=U)})),J.every(U=>le[U]===Y))return;window.dispatchEvent(new CustomEvent("matrix:move-tasks",{detail:{ids:J,to:Y,from:le}}))}else if(O==="Delete"||O==="Backspace"){if($.preventDefault(),$.repeat)return;si({taskId:V.id,via:"key",quadrant:F.q,task:V})}else if(O==="Enter")$.preventDefault(),window.dispatchEvent(new CustomEvent("task:open-focus",{detail:{taskId:V.id}}));else if(O==="d"||O==="D")$.preventDefault(),j({taskId:V.id,kind:$.shiftKey?"deadline":"due"});else if(O==="r"||O==="R"||O==="F2")$.preventDefault(),j({taskId:V.id,kind:"rename"});else if(O==="c"||O==="C")$.preventDefault(),j({taskId:V.id,kind:"comments"});else if(O==="x"||O==="X"){$.preventDefault();const Y=I.current;if($.shiftKey&&Y&&Y.q===F.q){const[J,le]=[Y.i,F.i].sort((U,ne)=>U-ne);
32Q.slice(J,le+1).forEach(U=>{d(U.id)||c(U.id)})}else c(V.id),I.current={q:F.q,i:F.i}}},[n,N,g,E,l,d,c,p,he,Le]);i.useEffect(()=>(window.addEventListener("keydown",Te),()=>window.removeEventListener("keydown",Te)),[Te]);const De=($,O=!1)=>({quadrant:E[$],onComplete:t,isFocusMode:n,focusedTaskId:a,onTaskFocus:r,keyboardIndex:!O&&N?.q===$&&N.visible?N.i:null,onRowPointerFocus:F=>C({q:$,i:F,visible:!1}),request:O?null:v,onRequestHandled:()=>j(null),adding:!O&&T===$,onAddingChange:F=>_(F?$:null),scrollStore:R.current,intro:w,heldCount:K?.[$]}),re=!!g,se=($,O)=>s.jsx("div",{className:S("cm-cell",`cm-cell-${$}`,p[$]&&"is-collapsed"),children:s.jsx(Zl,{...De($,re),sideLabel:O,collapsed:p[$],onToggleCollapse:()=>h(F=>({...F,[$]:!F[$]})),onExpand:()=>Le($)})}),ue=!p.do&&!p.schedule&&!p.delegate&&!p.backlog,Qe=re&&!x?{inert:""}:{};return s.jsxs("div",{ref:m,className:S("cm-root",w&&"is-intro",re&&"is-expanded"),style:{height:u},children:[s.jsxs("div",{className:S("cm-cross",re&&!x&&"is-under"),...Qe,children:[s.jsxs("div",{className:"cm-axis-top","aria-hidden":!0,children:[s.jsx("span",{children:"Urgent"}),s.jsx("span",{children:"Not urgent"})]}),s.jsxs("div",{className:"cm-cols",children:[s.jsxs("div",{className:"cm-col cm-col-left",children:[se("do","Important"),se("delegate","Not important")]}),s.jsxs("div",{className:"cm-col cm-col-right",children:[se("schedule"),se("backlog")]}),ue&&s.jsx("span",{className:"cm-origin","aria-hidden":!0})]})]}),g&&s.jsxs("div",{ref:oe,className:"cm-expanded",children:[s.jsxs("nav",{className:"cm-rail","aria-label":"Quadrants",children:[s.jsx("span",{className:"cm-rail-title",children:"Matrix"}),xs.map($=>{const O=Of(E[$].tasks);return s.jsxs("button",{type:"button",className:S("cm-rail-item",$===g&&"is-on"),style:{"--acc":`var(--q-${$})`},"aria-current":$===g,onClick:()=>{b($),C(null)},children:[s.jsx("span",{className:"cm-dot","aria-hidden":!0}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"cm-rail-name",children:E[$].title}),s.jsxs("span",{className:"cm-rail-status",children:[O.late?s.jsxs("span",{className:"cm-late",children:[O.late," late"]}):null,O.late&&O.today?" · ":"",O.today?`${O.today} today`:"",!O.late&&!O.today?O.next?`Next: ${O.next}`:"No dates":""]})]}),s.jsx("span",{className:"cm-rail-count",children:E[$].tasks.length})]},$)}),s.jsxs("span",{className:"cm-rail-foot kbd-hint",children:[s.jsx("kbd",{children:"Esc"})," back to the matrix"]})]}),s.jsx("div",{className:"cm-expanded-main",children:s.jsx(Zl,{...De(g),expanded:!0,onCollapseExpanded:he},g)})]})]})},Pk=[{value:"clean",label:"Clean"},{value:"classic",label:"Classic"}],Ok=1200,sd=({className:e})=>{const{view:t,setView:n,showTip:a,dismissTip:r}=da(),{viewTipAllowed:o}=Ot(),c=a&&o,[l,d]=i.useState(!1);i.useEffect(()=>{if(!c)return;const u=window.setTimeout(()=>d(!0),Ok);return()=>window.clearTimeout(u)},[c]);const m=c&&l;return s.jsx("div",{className:S("flex items-center justify-end",e),children:s.jsxs("div",{className:"cm-switch-wrap",children:[s.jsx("div",{className:"cm-switch",role:"radiogroup","aria-label":"Matrix view","aria-describedby":m?"cm-viewtip":void 0,children:Pk.map(u=>s.jsx("button",{type:"button",role:"radio","aria-checked":t===u.value,title:`${u.label} view (V)`,className:S("cm-switch-opt",t===u.value&&"is-on"),onClick:()=>n(u.value),children:u.label},u.value))}),m&&s.jsxs("div",{id:"cm-viewtip",className:"cm-viewtip",role:"status",children:[s.jsx("p",{className:"cm-viewtip-title",children:"Two ways to see your matrix"}),s.jsxs("p",{className:"cm-viewtip-body",children:["Switch between Clean and Classic here anytime",s.jsxs("span",{className:"kbd-hint",children:[", or press ",s.jsx("kbd",{children:"V"})]}),"."]}),s.jsx("button",{type:"button",className:"cm-viewtip-ok",onClick:r,children:"Got it"})]})]})})},$k=[{title:"Move around",keys:[{k:["↑","↓"],d:"Move within a quadrant (also J / K)"},{k:["←","→"],d:"Jump to the quadrant beside (also H / L)"},{k:["E"],d:"Expand the quadrant; Esc returns"},{k:["V"],d:"Switch Clean / Classic"},{k:["Q"],d:"New task (full form)"}]},{title:"Act on the row",keys:[{k:["Space"],d:"Complete"},{k:["1","4"],d:"Move to Do First … Backlog, with Undo"},{k:["Enter"],d:"Open in Single Task Focus"},{k:["D"],d:"Due date"},{k:["⇧","D"],d:"Deadline"},{k:["C"],d:"Comments"},{k:["R"],d:"Rename (or double-click the title)"},{k:["X"],d:"Select; ⇧X selects a range"},{k:["N"],d:"Add a task to this quadrant"},{k:["Delete"],d:"Delete, with Undo (also Backspace)"},{k:["F"],d:"Follow up, while the Completed toast shows"}]},{title:"Mouse",keys:[{k:["Ctrl","Click"],d:"Select tasks (⌘ on Mac), then move them with 1–4 or the bar at the bottom"},{k:["Click"],d:"A quadrant header folds or opens it"},{k:["Double-click"],d:"A quadrant header expands it"}]}],Fk=[{k:"↑↓",d:"Navigate"},{k:"←→",d:"Quadrant"},{k:"E",d:"Expand"},{k:"N",d:"Add"}],qk=e=>{const t=e;return!!t&&(t.tagName==="INPUT"||t.tagName==="TEXTAREA"||t.tagName==="SELECT"||t.isContentEditable)},zk=()=>{const[e,t]=i.useState(!1),[n,a]=ct("matrix-shortcuts-hidden",!1);return i.useEffect(()=>{const r=o=>{!(o.key==="?"||o.key==="/"&&o.shiftKey)||o.ctrlKey||o.metaKey||o.altKey||qk(o.target)||!e&&document.querySelector('[role="dialog"], [role="alertdialog"]')||(o.preventDefault(),t(l=>!l))};return window.addEventListener("keydown",r),()=>window.removeEventListener("keydown",r)},[e]),s.jsxs("div",{className:n?"cm-keys is-hidden":"cm-keys","aria-label":"Keyboard shortcuts",children:[!n&&Fk.map(r=>s.jsxs("span",{className:"cm-keys-item",children:[s.jsx("kbd",{children:r.k}),r.d]}
32,r.k)),s.jsxs(Nt,{open:e,onOpenChange:t,children:[s.jsx(St,{asChild:!0,children:s.jsxs("button",{type:"button",className:"cm-keys-all","aria-haspopup":"dialog","aria-label":n?"Keyboard shortcuts (?)":void 0,title:n?"Keyboard shortcuts (?)":void 0,children:[s.jsx(Jp,{className:"h-3.5 w-3.5","aria-hidden":!0}),!n&&s.jsxs(s.Fragment,{children:["All shortcuts",s.jsx("kbd",{children:"?"})]})]})}),s.jsxs(Ct,{align:"start",avoidCollisions:!0,collisionPadding:8,className:"cm-keys-panel w-[380px] p-0",children:[s.jsx("div",{className:"cm-keys-panel-head",children:"Keyboard shortcuts"}),s.jsx("div",{className:"cm-keys-body",children:$k.map(r=>s.jsxs("div",{className:"cm-keys-group",children:[s.jsx("div",{className:"cm-keys-group-title",children:r.title}),r.keys.map(o=>s.jsxs("div",{className:"cm-keys-row",children:[s.jsx("span",{className:"cm-keys-combo",children:o.k.map(c=>s.jsx("kbd",{children:c},c))}),s.jsx("span",{children:o.d})]},o.d))]},r.title))}),s.jsxs("div",{className:"cm-keys-foot",children:[s.jsx("span",{children:"Shortcuts pause while you type. Click a row first, or press ↓ to start."}),s.jsx("button",{type:"button",className:"cm-keys-toggle",onClick:()=>a(!n),children:n?"Show hints above the matrix":"Hide hints above the matrix"})]})]})]}),!n&&s.jsx("button",{type:"button",className:"cm-keys-hide","aria-label":"Hide shortcut hints",title:"Hide hints",onClick:()=>a(!0),children:s.jsx(Ie,{className:"h-3 w-3","aria-hidden":!0})})]})},Uk=["do","schedule","delegate","backlog"];function uh(e,t=new Set,n=new Date){return Uk.flatMap(a=>wc(e[a]??[],t,n).map(r=>({task:r,q:a})))}function Bk(e,t,n={}){const{completedToday:a=new Set,tasksAreFiltered:r=!1}=n;for(const o of e)if(!(a.has(o)||!t.has(o)&&!r))return o}function Hk(e,t={}){const{focusOneId:n,openTab:a}=t;if(n&&e.some(r=>r.task.id===n))return n;if(a){const r=e.find(o=>o.q===a);if(r)return r.task.id}return e[0]?.task.id}const Va=gr(e=>({task:null,pin:t=>e({task:t}),clear:()=>e({task:null})})),Vk=gn(()=>Ne(()=>import("./FocusedTaskOverlay-DZ6qBPtJ.js"),__vite__mapDeps([16,1,2,8,17,18,19,20,3,4])).then(e=>e.FocusedTaskOverlay)),Kk=gn(()=>Ne(()=>import("./MobileFocusOverlay-CTuWVBes.js"),__vite__mapDeps([21,1,2,18,19,3,4])).then(e=>e.MobileFocusOverlay)),Yk=["do","schedule","delegate","backlog"],Wk={hidden:{opacity:0},visible:{opacity:1,transition:{duration:.12}}},Gk={hidden:{opacity:0},visible:{opacity:1,transition:{duration:.1}}},mh=Ue.memo(({quadrants:e,isTaskFocus:t,focusedTaskId:n,onTaskFocus:a,onCompleteTask:r,onExitTaskFocus:o})=>{const c=Fe(),{toast:l}=He(),{config:d}=Zt(),{view:m}=da(),u=!c&&m==="clean";sk(!c&&!t);const{allowGestureHint:f}=Ot(),p=Pe(D=>D.quadrant),h=Pe(D=>D.setCounts);i.useEffect(()=>{if(!c)return;const D=L=>e.find(A=>A.droppableId===L)?.tasks.length??0;h({do:D("do"),schedule:D("schedule"),delegate:D("delegate"),backlog:D("backlog")})},[c,e,h]);const g=i.useRef(e);g.current=e,i.useEffect(()=>{if(u)return;const D=L=>{const A=new Set(L.detail?.ids??[]),H=g.current.filter(K=>K.tasks.some(X=>A.has(X.id)));c&&H.length&&Yk.includes(H[0].droppableId)&&Gn(H[0].droppableId),(c?H.slice(1):H).forEach((K,X)=>{window.setTimeout(()=>{const ce=document.getElementById(c?`mx-tab-${K.droppableId}`:`q-${K.droppableId}`);ce&&(ce.style.setProperty("--onb-q",`var(--q-${K.droppableId})`),ce.classList.add("onb-glow"),window.setTimeout(()=>ce.classList.remove("onb-glow"),700))},X*120)})};return window.addEventListener("onboarding:reveal",D),()=>window.removeEventListener("onboarding:reveal",D)},[u,c]);const b=i.useRef(t),x=i.useRef(null),y=i.useRef(null),w=i.useRef(null),k=la(),N=Va(D=>D.task),C=i.useMemo(()=>{const D=uh(Object.fromEntries(e.map(A=>[A.droppableId,A.tasks])),k);if(!N||D.some(A=>A.task.id===N.id))return D;const L=um(N.labels)??"do";return[{task:N,q:L},...D]},[e,k,N]),v=i.useRef(t);i.useEffect(()=>{v.current&&!t&&Va.getState().clear(),v.current=t},[t]),i.useEffect(()=>{if(!N)return;const D=L=>{L.detail?.taskId===N.id&&Va.getState().clear()};return window.addEventListener("task-completion-finished",D),window.addEventListener("focus-task-completed",D),()=>{window.removeEventListener("task-completion-finished",D),window.removeEventListener("focus-task-completed",D)}},[N]);const j=i.useMemo(()=>C.map(D=>D.task),[C]);i.useEffect(()=>(t&&!n&&j.length>0&&(y.current=requestAnimationFrame(()=>{a(j[0].id)})),()=>{y.current!==null&&cancelAnimationFrame(y.current)}),[t,n,j,a]);const T=i.useCallback(D=>{if(!x.current)return;const L=x.current;L.style.transition="var(--focus-transition)",D?(L.style.setProperty("--grid-opacity","0.05"),L.style.setProperty("--grid-scale","0.988")):(L.style.setProperty("--grid-opacity","1"),L.style.setProperty("--grid-scale","1")),w.current&&clearTimeout(w.current),w.current=setTimeout(()=>{L&&document.body.contains(L)&&(L.style.transition="")},200)},[]);i.useEffect(()=>(b.current!==t&&x.current&&(x.current.style.getPropertyValue("--focus-transition")||x.current.style.setProperty("--focus-transition","opacity 180ms cubic-bezier(0.2, 0, 0.2, 1), transform 180ms cubic-bezier(0.2, 0, 0.2, 1)"),y.current=requestAnimationFrame(()=>{T(t)})),b.current=t,()=>{y.current!==null&&cancelAnimationFrame(y.current),w.current&&clearTimeout(w.current)}),[t,T]);const _=i.useCallback(async D=>{try{await r(D)}catch{l({title:"Error",description:"Failed to complete task",variant:"destructive"})}},[r,l]),I=i.useCallback(()=>{o&&o()},[o]),R=S("grid relative isolate matrix-grid","auto-rows-fr","will-change-transform","grid-cols-1 px-2 pb-4 max-sm:pb-24 sm:grid-cols-2 sm:px-4 sm:pb-8 md:px-0",d.gridGap),M=e.findIndex(D=>D.droppableId===p),P=e[M],E=c?[]:e.map((D,L)=>s.jsx(_e.div,{id:`q-${D.droppableId}`,variants:Gk,className:S("relative grid grid-item","scroll-mt-2","h-full will-change-transform",d.quadrantMinHeight),children:s.jsx(Qo,{...D,index:L,isTaskFocus:t,focusedTaskId:n,onTaskFocus:a,onCompleteTask:_})},D.droppableId));return s.jsxs(s.Fragment,{children:[c?s.jsxs(s.Fragment,{children:[j.length>0&&f&&s.jsx(th,{}),s.jsx("div",{id:"mx-panel",role:"tabpanel","aria-labelledby":`mx-tab-${p}`,className:"mx-panel",ref:x,onClick:D=>D.stopPropagation(),children:P&&s.jsx("div",{id:`q-${P.droppableId}`,className:"mx-panel-inner",children:s.jsx(Qo,{...P,index:M,isTaskFocus:t,focusedTaskId:n,onTaskFocus:a,onCompleteTask:_})},P.droppableId)})]}):u?s.jsx("div",{className:"cm-bleed cm-fade-in",onClick:D=>D.stopPropagation(),children:s.jsxs("div",{className:"cm-bleed-inner",children:[s.jsxs("div",{className:"cm-toolbar",children:[s.jsx(zk,{}),s.jsx(sl,{}),s.jsx(sd,{})]}),s.jsx("div",{className:"pb-24",children:s.jsx(Ak,{quadrants:e,onCompleteTask:_,isTask
32Focus:t,focusedTaskId:n,onTaskFocus:a})})]})}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"classic-toolbar mt-4 mb-3 px-2 sm:px-4 md:px-0",children:[s.jsx(sl,{}),s.jsx(sd,{})]}),s.jsx(Gt,{children:s.jsx(_e.div,{variants:Wk,initial:"hidden",animate:"visible",className:R,ref:x,style:{willChange:"transform, opacity",opacity:"var(--grid-opacity, 1)",transform:"translateZ(0) scale(var(--grid-scale, 1))",backfaceVisibility:"hidden"},onClick:D=>D.stopPropagation(),children:E})})]}),c&&!t&&s.jsx(eh,{}),t&&s.jsx(s.Fragment,{children:c?s.jsx(Kk,{focusedTaskId:n,queue:C,onTaskFocus:a,onCompleteTask:_,onExitFocusMode:I}):s.jsx(Vk,{focusedTaskId:n,queue:C,onTaskFocus:a,onCompleteTask:_,onExitFocusMode:I})})]})});mh.displayName="QuadrantList";const fh=Ue.memo(({quadrants:e,isFocusMode:t,isTaskFocus:n,focusedTaskId:a,onTaskFocus:r,onCompleteTask:o,onToggleFocusMode:c,onExitTaskFocus:l,onToggleTaskFocus:d})=>{i.useEffect(()=>{if(n)return document.documentElement.classList.add("task-focus-active"),()=>{document.documentElement.classList.remove("task-focus-active")}},[n]);const m=i.useCallback(()=>{l?l():c()},[l,c]),u=i.useCallback(async f=>{try{window.dispatchEvent(new CustomEvent("task-completion-started",{detail:{taskId:f,timestamp:Date.now()}})),await o(f),window.dispatchEvent(new CustomEvent("task-completion-finished",{detail:{taskId:f,timestamp:Date.now(),success:!0}}))}catch(p){throw window.dispatchEvent(new CustomEvent("task-completion-failed",{detail:{taskId:f,timestamp:Date.now(),error:p}})),p}},[o]);return s.jsx("div",{className:"relative",children:s.jsx(mh,{quadrants:e,isTaskFocus:n,focusedTaskId:a,onTaskFocus:r,onCompleteTask:u,onExitTaskFocus:m})})});fh.displayName="MatrixContent";const Qk=({id:e,checked:t,onCheckedChange:n,label:a,description:r})=>s.jsxs("div",{className:"flex items-center gap-4 max-sm:gap-2.5",children:[s.jsx(Wn,{id:e,checked:t,onCheckedChange:n,className:S("data-[state=checked]:bg-primary","transition-all duration-300","hover:scale-105","data-[state=checked]:shadow-lg data-[state=checked]:shadow-primary/10","cursor-pointer")}),s.jsxs("div",{className:"flex flex-col",children:[s.jsx(aa,{htmlFor:e,className:S("text-base max-sm:text-sm font-semibold cursor-pointer select-none","transition-colors duration-300",t?"text-primary":"text-muted-foreground","hover:text-primary/90"),children:a}),s.jsx("span",{className:"text-xs text-muted-foreground/70 transition-colors duration-300 max-sm:hidden",children:r})]})]}),Jk=({isActive:e})=>s.jsx(te.div,{whileHover:{scale:1.1},whileTap:{scale:.95},animate:{scale:e?[1,1.1,1]:1,rotate:e?[0,15,0]:0},transition:{duration:.3,ease:"easeInOut"},children:s.jsx(Ts,{className:S("h-5 w-5 transition-colors duration-300",e?"text-primary filter drop-shadow-lg":"text-muted-foreground/50","hover:text-primary/70")})}),Xk=({isActive:e,content:t="Click to enable single task focus mode",children:n})=>n?s.jsx(Ls,{children:s.jsxs(Ht,{delayDuration:300,children:[s.jsx(Vt,{asChild:!0,children:n}),s.jsx(At,{className:"bg-primary/95 text-primary-foreground border-primary/20",children:e?"Single task focus mode is enabled":t})]})}):null,Zk=({isTaskFocus:e,onToggleTaskFocus:t,hasTasks:n=!0})=>{const[a,r]=i.useState(!1),{session:o}=we.useSessionContext(),c=()=>{if(!e&&!n){t();return}if(!e&&o?.user?.id)try{localStorage.setItem(`onb:used-focus:${o.user.id}`,"1")}catch{}r(!0),t(),setTimeout(()=>{r(!1)},600)};return s.jsx(Ls,{delayDuration:100,children:s.jsx("div",{className:"flex items-center justify-between mb-4 bg-background/95 backdrop-blur-sm p-4 rounded-xl shadow-sm border border-border/40 max-sm:p-1.5 max-sm:mb-2 max-sm:border-0 max-sm:bg-transparent max-sm:shadow-none",children:s.jsx("div",{className:"flex items-center gap-6 max-sm:gap-2 max-sm:w-full",children:s.jsxs(_e.div,{initial:{opacity:0,y:-20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},className:S("relative group flex items-center gap-4 px-6 py-3.5 rounded-xl transition-all duration-300","max-sm:gap-2 max-sm:px-3 max-sm:py-2 max-sm:shadow-none","bg-gradient-to-r from-primary/10 via-primary/5 to-transparent","hover:from-primary/15 hover:via-primary/10 hover:to-transparent","border border-primary/10 hover:border-primary/20","shadow-lg hover:shadow-xl shadow-primary/5",e&&"ring-2 ring-primary/30"),children:[s.jsx(Qk,{id:"single-task-focus",checked:e,onCheckedChange:c,label:"Single Task Focus",description:n||e?"Concentrate on one task at a time":"No tasks to focus on"}),s.jsx("div",{className:"relative",children:a?s.jsx("div",{className:"flex items-center justify-center w-8 h-8",children:s.jsx(kt,{className:"h-5 w-5 text-primary animate-spin"})}):s.jsx(Xk,{isActive:e,content:"Toggle single task focus mode",children:s.jsx(Jk,{isActive:e})})}),e&&s.jsx(_e.div,{className:"absolute inset-0 -z-10 rounded-xl opacity-20",initial:!1,animate:{background:["radial-gradient(circle at 50% 50%, rgba(var(--primary), 0.1) 0%, transparent 50%)","radial-gradient(circle at 50% 50%, rgba(var(--primary), 0.2) 0%, transparent 70%)","radial-gradient(circle at 50% 50%, rgba(var(--primary), 0.1) 0%, transparent 50%)"]},transition:{duration:4,repeat:1/0,repeatType:"reverse"}})]})})})})},hh=e=>({kb:Math.max(0,Math.round(window.innerHeight-e.height-e.offsetTop)),vvh:Math.round(e.height)}),ph=(e,t,n)=>{e.style.setProperty("--kb",`${t}px`),e.style.setProperty("--vvh",`${n}px`),e.toggleAttribute("data-kb",t>0)},Cc=e=>{i.useEffect(()=>
32{const t=window.visualViewport;if(!t)return;let n=0;const a=()=>{const r=e.current;if(!r)return;const{kb:o,vvh:c}=hh(t);ph(r,o,c)};return a(),n=requestAnimationFrame(a),t.addEventListener("resize",a),t.addEventListener("scroll",a),()=>{cancelAnimationFrame(n),t.removeEventListener("resize",a),t.removeEventListener("scroll",a)}},[e])},ej=()=>{i.useEffect(()=>{const e=window.visualViewport;if(!e)return;const t=document.documentElement;let n=!1,a=0;const r=()=>{const{kb:o,vvh:c}=hh(e);ph(t,o,c),o>0&&!n&&(cancelAnimationFrame(a),a=requestAnimationFrame(()=>{const l=document.activeElement;l instanceof HTMLElement&&l.closest('[role="dialog"]')&&l.scrollIntoView({block:"nearest"})})),n=o>0};return r(),e.addEventListener("resize",r),e.addEventListener("scroll",r),()=>{cancelAnimationFrame(a),e.removeEventListener("resize",r),e.removeEventListener("scroll",r),t.style.removeProperty("--kb"),t.style.removeProperty("--vvh"),t.removeAttribute("data-kb")}},[])},gh="recent-labels",tj=8,xh=()=>{try{const e=localStorage.getItem(gh);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}catch{return[]}},sj=e=>{const t=e.trim();if(t)try{const n=xh().filter(r=>r.toLowerCase()!==t.toLowerCase()),a=[t,...n].slice(0,tj);localStorage.setItem(gh,JSON.stringify(a))}catch{}},bh=({label:e,tone:t,query:n,onQueryChange:a,placeholder:r,groups:o,chips:c,onBackspaceEmpty:l,empty:d,inputRef:m})=>{const u=o.flatMap(w=>w.rows),f=u.find(w=>!w.disabled)?.id??"",[p,h]=i.useState(f);i.useEffect(()=>{h(f)},[n,f]);const g=u.some(w=>w.id===p&&!w.disabled),b=i.useRef(null);i.useEffect(()=>{b.current&&(b.current.scrollTop=0)},[n]);const[x,y]=i.useState("ptr");return s.jsxs(Mt,{label:e,className:S("pk",t),shouldFilter:!1,loop:!0,vimBindings:!1,value:g?p:f,onValueChange:h,onPointerMove:()=>{x!=="ptr"&&y("ptr")},onKeyDown:w=>{y("kbd"),w.key==="Enter"&&(w.metaKey||w.ctrlKey)&&w.preventDefault()},children:[s.jsxs("div",{className:"fb-combo-field pk-field",children:[c,s.jsxs("div",{className:"fb-combo-input",children:[s.jsx(Ri,{"aria-hidden":!0}),s.jsx(Mt.Input,{ref:m,value:n,onValueChange:a,placeholder:r,"data-autofocus":"",autoComplete:"off",autoCapitalize:"off",spellCheck:!1,enterKeyHint:"done",onKeyDown:w=>{w.key==="Backspace"&&!n&&l&&l()}})]})]}),s.jsxs(Mt.List,{ref:b,className:"pk-list","data-input":x,onWheel:w=>w.stopPropagation(),onTouchMove:w=>w.stopPropagation(),children:[u.length===0&&d,o.map((w,k)=>w.rows.length>0&&s.jsx(Mt.Group,{heading:w.heading,className:"pk-group",children:w.rows.map(N=>s.jsxs(Mt.Item,{value:N.id,disabled:N.disabled,onSelect:N.onSelect,className:S("pk-row",N.className),style:N.style,"data-checked":N.checked||void 0,children:[N.content,N.checked&&s.jsx(Oe,{className:"pk-check","aria-hidden":!0}),N.checked&&s.jsx("span",{className:"sr-only",children:"(selected)"})]},N.id))},w.heading??k))]})]})},ai=({text:e,range:t})=>{if(!t)return s.jsx(s.Fragment,{children:e});const[n,a]=t;return s.jsxs(s.Fragment,{children:[e.slice(0,n),s.jsx("mark",{className:"pk-hit",children:e.slice(n,a)}),e.slice(a)]})},ri=({color:e})=>s.jsx("span",{className:"pk-dot",style:e?{"--dot":e}:void 0,"aria-hidden":!0}),nj={berry_red:"#b8255f",red:"#db4035",orange:"#ff9933",yellow:"#fad000",olive_green:"#afb83b",lime_green:"#7ecc49",green:"#299438",mint_green:"#6accbc",teal:"#158fad",sky_blue:"#14aaf5",light_blue:"#96c3eb",blue:"#4073ff",grape:"#884dff",violet:"#af38eb",lavender:"#eb96eb",magenta:"#e05194",salmon:"#ff8d85",charcoal:"#808080",grey:"#b8b8b8",taupe:"#ccac93"},oi=e=>e?nj[e]:void 0,nd=["do","schedule","delegate","backlog"],aj=9,rj=3,ad=128,oj=/[@"()|&!,]/,ij=e=>e.trim().replace(/^@+/,"").replace(/\s+/g," ").trim(),cj=({isLoading:e=!1,availableLabels:t=[],selectedLabels:n=[],onToggleLabel:a,apiKey:r})=>{const o=at(),[c,l]=i.useState(""),[d,m]=i.useState(!1),[u,f]=i.useState(null),[p]=i.useState(xh),h=i.useRef(null),g=Array.isArray(n)?n:[],b=E=>g.includes(E),x=i.useMemo(()=>(Array.isArray(t)?t:[]).filter(E=>!nd.includes(E.name.toLowerCase())),[t]),y=i.useMemo(()=>new Map(x.map(E=>[E.name,E])),[x]),w=E=>{b(E)||sj(E),a(E),l(""),f(null)},k=ij(c),N=Oo(k),C=!!k&&x.some(E=>Oo(E.name)===N),v=nd.includes(N),j=oj.test(k)?`Labels can't contain @ " ( ) | & ! ,`:k.length>ad?`Keep it under ${ad} characters`:null,T=async()=>
32{if(!(!k||j||d||!r)){m(!0),f(null);try{const D=await new Ke(r).addLabel({name:k}),L=D?.name??k;o.setQueryData(["labels",r],A=>Array.isArray(A)?[...A,D??{id:`new-${L}`,name:L}]:A),w(L),h.current?.focus()}catch(E){f(E instanceof Error&&E.message?E.message:"Couldn't create the label")}finally{m(!1)}}},_=(E,D)=>({id:`l:${E.id}`,checked:b(E.name),onSelect:()=>w(E.name),content:s.jsxs(s.Fragment,{children:[s.jsx(ri,{color:oi(E.color)}),s.jsx("span",{className:"pk-name",children:s.jsx(ai,{text:E.name,range:D})})]})}),I=k&&!C&&!v?{id:"create",className:"pk-create",disabled:!!j||d,onSelect:()=>{T()},content:s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"pk-plus","aria-hidden":!0,children:d?s.jsx(kt,{className:"animate-spin"}):s.jsx(fn,{})}),s.jsx("span",{className:"pk-name",children:j??u??s.jsxs(s.Fragment,{children:["Create ",s.jsxs("b",{children:["“",k,"”"]})]})})]})}:null,R=[];if(c.trim()){const E=Ar(x,k,L=>L.name),D=E.map(L=>_(L.item,L.range));v&&D.push({id:"quadrant",disabled:!0,className:"pk-muted",onSelect:()=>{},content:s.jsx("span",{className:"pk-name",children:"Set by the Quadrant row"})}),I&&(E.length?D.push(I):D.unshift(I)),R.push({rows:D})}else{const E=x.length>=aj?p.map(A=>x.find(H=>H.name.toLowerCase()===A.toLowerCase())).filter(A=>!!A).slice(0,rj):[],D=new Set(E.map(A=>A.id)),L=Em(x.filter(A=>!D.has(A.id)),A=>A.name);E.length&&R.push({heading:"Recent",rows:E.map(A=>_(A))}),R.push({heading:E.length?"All labels":void 0,rows:L.map(A=>_(A))})}const M=g.length>0&&s.jsx("div",{className:"fb-tokens","aria-label":"Selected labels",children:g.map(E=>s.jsxs("span",{className:"fb-token pk-chip",children:[s.jsx(ri,{color:oi(y.get(E)?.color)}),s.jsx("span",{className:"fb-token-label",children:E}),s.jsx("button",{type:"button","aria-label":`Remove ${E}`,onClick:()=>{a(E),h.current?.focus()},children:s.jsx(Ie,{"aria-hidden":!0})})]},E))}),P=e?s.jsxs("div",{className:"pk-skeleton","aria-label":"Loading labels",children:[s.jsx("span",{}),s.jsx("span",{}),s.jsx("span",{})]}):s.jsx("div",{className:"pk-note",children:"No labels yet. Type a name to create one."});return s.jsx(bh,{label:"Labels",tone:"fb-label",query:c,onQueryChange:E=>{l(E),f(null)},placeholder:g.length?"Add more…":"Search or create labels",groups:R,chips:M,onBackspaceEmpty:g.length?()=>a(g[g.length-1]):void 0,empty:P,inputRef:h})},lj=({projects:e,isLoading:t,projectId:n,onSelect:a})=>{const[r,o]=i.useState(""),c=e.find(b=>b.is_inbox_project)??e.find(b=>b.name?.toLowerCase()==="inbox"),l=i.useMemo(()=>new Map(e.map(b=>[b.id,b])),[e]),d=i.useMemo(()=>{const b=new Map;for(const w of e){if(w.id===c?.id)continue;const k=w.parent_id&&l.has(w.parent_id)?w.parent_id:"";b.set(k,[...b.get(k)??[],w])}const x=[],y=(w,k)=>{const N=[...b.get(w)??[]].sort((C,v)=>(C.order??0)-(v.order??0));for(const C of N)x.push({project:C,depth:k}),k<8&&y(C.id,k+1)};return y("",0),x},[e,c?.id,l]),m=n&&n!==c?.id?n:void 0,u=b=>a(b===c?.id?void 0:b),f=b=>({id:"inbox",checked:!m,onSelect:()=>u(void 0),content:s.jsxs(s.Fragment,{children:[s.jsx(yu,{className:"pk-icon","aria-hidden":!0}),s.jsx("span",{className:"pk-name",children:s.jsx(ai,{text:"Inbox",range:b})})]})}),p=(b,x,y,w)=>({id:`p:${b.id}`,checked:m===b.id,onSelect:()=>u(b.id),style:x?{"--depth":x}:void 0,className:x?"pk-nested":void 0,content:s.jsxs(s.Fragment,{children:[s.jsx(ri,{color:oi(b.color)}),s.jsxs("span",{className:"pk-name",children:[s.jsx(ai,{text:b.name,range:y}),w&&s.jsxs("span",{className:"pk-hint",children:["· ",w]})]})]})});let h;if(r.trim()){const b=[null,...d.map(({project:x})=>x)];h=Ar(b,r,x=>x?.name??"Inbox").map(({item:x,range:y})=>x?p(x,0,y,x.parent_id?l.get(x.parent_id)?.name:void 0):f(y))}else h=[f(),...d.map(({project:b,depth:x})=>p(b,x))];const g=t?s.jsxs("div",{className:"pk-skeleton","aria-label":"Loading projects",children:[s.jsx("span",{}),s.jsx("span",{}),s.jsx("span",{})]}):s.jsxs("div",{className:"pk-note",children:["No project matches “",r.trim(),"”"]});return s.jsx(bh,{label:"Project",tone:"fb-project",query:r,onQueryChange:o,placeholder:"Search projects",groups:[{rows:t&&!r.trim()?[]:h}],empty:g})};function ii({className:e,classNames:t,showOutsideDays:n=!0,...a}){return s.jsx(Xp,{showOutsideDays:n,className:S("p-3",e),classNames:{months:"flex flex-col sm:flex-row space-y-4 sm:sp
32ace-x-4 sm:space-y-0",month:"space-y-4",caption:"flex justify-center pt-1 relative items-center",caption_label:"text-sm font-medium",nav:"space-x-1 flex items-center",nav_button:S(Mo({variant:"outline"}),"h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100"),nav_button_previous:"absolute left-1",nav_button_next:"absolute right-1",table:"w-full border-collapse space-y-1",head_row:"flex",head_cell:"text-muted-foreground rounded-md w-9 font-normal text-[0.8rem]",row:"flex w-full mt-2",cell:"h-9 w-9 text-center text-sm p-0 relative [&:has([aria-selected].day-range-end)]:rounded-r-md [&:has([aria-selected].day-outside)]:bg-accent/50 [&:has([aria-selected])]:bg-accent first:[&:has([aria-selected])]:rounded-l-md last:[&:has([aria-selected])]:rounded-r-md focus-within:relative focus-within:z-20",day:S(Mo({variant:"ghost"}),"h-9 w-9 p-0 font-normal aria-selected:opacity-100"),day_range_end:"day-range-end",day_selected:"bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground focus:bg-primary focus:text-primary-foreground",day_today:"bg-accent text-accent-foreground",day_outside:"day-outside text-muted-foreground opacity-50 aria-selected:bg-accent/50 aria-selected:text-muted-foreground aria-selected:opacity-30",day_disabled:"text-muted-foreground opacity-50",day_range_middle:"aria-selected:bg-accent aria-selected:text-accent-foreground",day_hidden:"invisible",...t},components:{IconLeft:({...r})=>s.jsx(wu,{className:"h-4 w-4"}),IconRight:({...r})=>s.jsx(pt,{className:"h-4 w-4"})},...a})}ii.displayName="Calendar";const dj=Zp,uj=eg,yh=i.forwardRef(({className:e,children:t,...n},a)=>s.jsxs(vu,{ref:a,className:S("flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm r
32ing-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",e),...n,children:[t,s.jsx(tg,{asChild:!0,children:s.jsx(mt,{className:"h-4 w-4 opacity-50"})})]}));yh.displayName=vu.displayName;const wh=i.forwardRef(({className:e,...t},n)=>s.jsx(Nu,{ref:n,className:S("flex cursor-default items-center justify-center py-1",e),...t,children:s.jsx(Su,{className:"h-4 w-4"})}));wh.displayName=Nu.displayName;const vh=i.forwardRef(({className:e,...t},n)=>s.jsx(Cu,{ref:n,className:S("flex cursor-default items-center justify-center py-1",e),...t,children:s.jsx(mt,{className:"h-4 w-4"})}));vh.displayName=Cu.displayName;const kh=i.forwardRef(({className:e,children:t,position:n="popper",...a},r)=>s.jsx(sg,{children:s.jsxs(ku,{ref:r,className:S("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",n==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:n,...a,children:[s.jsx(wh,{}),s.jsx(ng,{className:S("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),s.jsx(vh,{})]})}));kh.displayName=ku.displayName;const mj=i.forwardRef(({className:e,...t},n)=>s.jsx(Tu,{ref:n,className:S("py-1.5 pl-8 pr-2 text-sm font-semibold",e),...t}));mj.displayName=Tu.displayName;const Ka=i.forwardRef(({className:e,children:t,...n},a)=>s.jsxs(ju,{ref:a,className:S("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[s.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:s.jsx(ag,{children:s.jsx(Oe,{className:"h-4 w-4"})})}),s.jsx(rg,{children:t})]}));Ka.displayName=ju.displayName;const fj=i.forwardRef(({className:e,...t},n)=>s.jsx(_u,{ref:n,className:S("-mx-1 my-1 h-px bg-muted",e),...t}));fj.displayName=_u.displayName;const Ya={sunday:0,sun:0,monday:1,mon:1,tuesday:2,tues:2,tue:2,wednesday:3,wed:3,thursday:4,thurs:4,thur:4,thu:4,friday:5,fri:5,saturday:6,sat:6},hj=new Set(["sun","sat"]),An={pazartesi:1,sali:2,carsamba:3,persembe:4,cuma:5,cumartesi:6,pazar:0},pj=new Set(["pazar"]),ci={january:0,jan:0,february:1,feb:1,march:2,mar:2,april:3,apr:3,may:4,june:5,jun:5,july:6,jul:6,august:7,aug:7,september:8,sept:8,sep:8,october:9,oct:9,november:10,nov:10,december:11,dec:11},jh={ocak:0,subat:1,mart:2,nisan:3,mayis:4,haziran:5,temmuz:6,agustos:7,eylul:8,ekim:9,kasim:10,aralik:11,aralig:11},Nh={a:1,an:1,one:1,two:2,three:3,four:4,five:5,six:6,seven:7,eight:8,nine:9,ten:10},li={bir:1,iki:2,uc:3,dort:4,bes:5,alti:6,yedi:7,sekiz:8,dokuz:9,on:10},gj={morning:"09:00",noon:"12:00",afternoon:"15:00",evening:"19:00",night:"21:00"},rd=["sunday","monday","tuesday","wednesday","thursday","friday","saturday"],yn=e=>`(?:${[...e].sort((t,n)=>n.length-t.length).map(t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|")})`,xj={ı:"i",İ:"i",ç:"c",Ç:"c",ğ:"g",Ğ:"g",ö:"o",Ö:"o",ş:"s",Ş:"s",ü:"u",Ü:"u","’":"'","‘":"'"};function bj(e){let t="";for(let n=0;n<e.length;n++){const a=e[n],r=xj[a]??a.toLowerCase();t+=r.length===1?r:a}return t}const Pn=(e,t)=>n=>{const a=(e-n.getDay()+7)%7;return st(n,a===0&&!t?7:a)},pr=e=>st(Eo(e,{weekStartsOn:1}),7),fo=e=>t=>st(pr(t),(e+6)%7),yt=e=>t=>st(t,e),od=(e,t)=>n=>/^(day|gun)/.test(t)?st(n,e):/^(week|hafta)/.test(t)?Bu(n,e):Uu(n,e),id=e=>new Date(e.getFullYear(),e.getMonth()+1,1),cd=e=>t=>e?st(pr(t),5):t.getDay()===6||t.getDay()===0?t:Pn(6,!1)(t),Us=(e,t,n)=>a=>{const r=c=>{const l=new Date(c,e,t);return l.getMonth()===e&&l.getDate()===t?l:null};if(n!=null)return r(n);const o=r(a.getFullYear());if(o&&o<a)return r(a.getFullYear()+1);if(!o)for(let c=a.getFullYear()+1;c<=a.getFullYear()+4;c++){const l=r(c);if(l)return l}return o},ho=(e,t)=>e==null?NaN:/^\d+$/.test(e)?Number(e):t[e]??NaN,_a=e=>e==null?void 0:e.length===2?2e3+Number(e):Number(e),po=yn(Object.keys(Ya)),Ea=yn(Object.keys(An)),ld=yn(Object.keys(ci)),yj=yn(Object.keys(jh)),wj=`(?:\\d{1,3}
32|${yn(Object.keys(Nh))})`,dd=`(?:\\d{1,3}|${yn(Object.keys(li))})`,Da="(?:'(?:d[ae]|t[ae]|y[ae]|[ae]))?",vj="(?:'?(?:d[ae]n?|t[ae]n?|y[ae]|[ae]))?",go="(?!\\s+(?:yeme|kahvalt))",ud={morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},xo=e=>e.startsWith("sabah")?"morning":e.startsWith("ogleden")||e.startsWith("aksamustu")?"afternoon":e.startsWith("ogle")?"noon":e.startsWith("aksam")?"evening":"night",kj=[["(?:the\\s+)?day\\s+after\\s+tomorrow",()=>({strong:!0,lang:"en",date:yt(2)})],["today",()=>({strong:!0,lang:"en",date:yt(0)})],["tonight",()=>({strong:!0,lang:"en",date:yt(0),period:"evening"})],["(?:tomorrow|tmrw|tmr)",()=>({strong:!0,lang:"en",date:yt(1)})],["this\\s+(?<p>morning|afternoon|evening)",e=>({strong:!0,lang:"en",date:yt(0),period:ud[e.p]})],["(?:in\\s+the\\s+)?(?<p>morning|afternoon|evening|night)",e=>({strong:!1,lang:"en",period:ud[e.p]})],[`in\\s+(?<n>${wj})\\s+(?<u>days?|weeks?|months?)`,e=>{const t=ho(e.n,Nh);return t>0?{strong:!0,lang:"en",date:od(t,e.u)}:null}],["next\\s+week",()=>({strong:!0,lang:"en",date:pr})],["next\\s+month",()=>({strong:!0,lang:"en",date:id})],["(?<k>this\\s+|next\\s+)?weekend",e=>({strong:!!e.k,lang:"en",date:cd(!!e.k?.startsWith("next"))})],[`(?<k>this|next|coming)\\s+(?<d>${po})`,e=>{const t=Ya[e.d];return{strong:!0,lang:"en",date:e.k==="next"?fo(t):Pn(t,e.k==="this")}}],[`every\\s+(?<d>${po})`,e=>({strong:!0,lang:"en",rule:`every ${rd[Ya[e.d]]}`})],[`(?<d>${po})`,(e,{orig:t})=>e.d.length<=4&&t===t.toUpperCase()?null:{strong:!1,needsCue:hj.has(e.d),lang:"en",date:Pn(Ya[e.d],!1)}],["every\\s+(?:(?<n>\\d{1,2}|other)\\s+)?(?<u>day|weekday|week|month|year)s?",e=>e.u==="weekday"&&e.n?null:{strong:!0,lang:"en",rule:e.n==="other"?`every other ${e.u}`:e.n?`every ${e.n} ${e.u}s`:`every ${e.u}`}],[`(?<mon>${ld})\\.?\\s+(?<day>\\d{1,2})(?:st|nd|rd|th)?(?:,?\\s+(?<y>\\d{4}))?`,(e,{orig:t})=>e.mon==="may"&&t[0]!=="M"?null:{strong:!0,lang:"en",date:Us(ci[e.mon],Number(e.day),_a(e.y))}],[`(?<day>\\d{1,2})(?:st|nd|rd|th)?\\s+(?:of\\s+)?(?<mon>${ld})\\.?(?:,?\\s+(?<y>\\d{4}))?`,(e,{orig:t})=>e.mon==="may"&&!/May/.test(t)?null:{strong:!0,lang:"en",date:Us(ci[e.mon],Number(e.day),_a(e.y))}],["(?<a>\\d{1,2})\\/(?<b>\\d{1,2})(?:\\/(?<y>\\d{4}|\\d{2}))?",(e,{opts:t})=>{const[n,a]=t.dayFirst?[e.a,e.b]:[e.b,e.a];return{strong:!!e.y,lang:null,date:Us(Number(a)-1,Number(n),_a(e.y))}}],["(?<d>\\d{1,2})\\.(?<m>\\d{1,2})\\.(?<y>\\d{4})",e=>({strong:!0,lang:null,date:Us(Number(e.m)-1,Number(e.d),Number(e.y))})],["(?<y>\\d{4})-(?<m>\\d{2})-(?<d>\\d{2})",e=>({strong:!0,lang:null,date:Us(Number(e.m)-1,Number(e.d),Number(e.y))})],["(?:(?<at>at|@)\\s*)?(?<h>\\d{1,2})(?::(?<m>[0-5]\\d))?\\s?(?<ap>am|pm|a\\.m\\.|p\\.m\\.)",e=>{const t=Number(e.h);return t<1||t>12?null:{strong:!!e.at,lang:"en",clock:{h:t,m:Number(e.m??0),ap:e.ap.startsWith("a")?"am":"pm",loose:!1}}}],[`(?:(?<at>at|@)\\s*)?(?<h>[01]?\\d|2[0-3]):(?<m>[0-5]\\d)${Da}`,(e,{opts:t})=>{const n=t.hour12&&e.h.length===1;return{strong:!!e.at,lang:null,clock:{h:Number(e.h),m:Number(e.m),loose:n}}}],["(?<at>at|@)\\s*(?<h>\\d{1,2})",e=>{const t=Number(e.h);return t<=23?{strong:!1,lang:"en",clock:{h:t,m:0,loose:!0}}:null}],["(?:(?<at>at)\\s+)?(?:noon|midday)",e=>({strong:!!e.at,lang:"en",clock:{h:12,m:0,loose:!1}})],["bugun",()=>({strong:!0,lang:"tr",date:yt(0)})],[`bu\\s+(?<p>sabah|ogleden\\s+sonra|aksam|gece)${go}`,e=>({strong:!0,lang:"tr",date:yt(0),period:xo(e.p)})],["yarindan\\s+sonra(?:ki\\s+gun)?",()=>({strong:!0,lang:"tr",date:yt(2)})],["yarin(?:a)?",()=>({strong:!0,lang:"tr",date:yt(1)})],["obur\\s?gun(?:e)?",()=>({strong:!0,lang:"tr",date:yt(2)})],["ertesi\\s+gun(?:e)?",()=>({strong:!0,lang:"tr",date:yt(1)})],[`(?<n>${dd})\\s+(?<u>gun|hafta|ay)\\s+(?:sonra|icinde)`,e=>{const t=ho(e.n,li);return t>0?{strong:!0,lang:"tr",date:od(t,e.u)}:null}],["(?:haftaya|(?:gelecek|onumuzdeki)\\s+hafta(?:ya)?)",()=>({strong:!0,lang:"tr",date:pr})],["(?:gelecek|onumuzdeki)\\s+ay(?:a)?",()=>({strong:!0,lang:"tr",date:id})],["(?<k>bu\\s+|gelecek\\s+|haftaya\\s+)?hafta\\s?sonu(?:na)?",e=>({strong:!!e.k,lang:"tr",date:cd(!!e.k&&!e.k.startsWith("bu"))})],[`(?<k>haftaya|(?:gelecek|onumuzdeki)\\s+hafta)\\s+(?<d>${Ea})(?:'?y[ae])?(?:\\s+gunu(?:ne)?)?`,e=>({strong:!0,lang:"tr",date:fo(An[e.d])})],[`(?<k>bu|gelecek|onumuzdeki)\\s+(?<d>${Ea})(?:'?y[ae])?(?:\\s+gunu(?:ne)?)?`,e=>{const t=An[e.d];return{strong:!0,lang:"tr",date:e.k==="gelecek"?fo(t):Pn(t,e.k==="bu")}}],[`her\\s+(?<d>${Ea})(?:\\s+gunu)?`,e=>({strong:!0,lang:"tr",rule:`every ${rd[An[e.d]]}`})],[`(?<d>${Ea})(?<s>'?y[ae]|\\s+gunu(?:ne)?)?`,e=>!!e.s&&!e.s.includes("gunu")&&pj.has(e.d)?null:{strong:!!e.s,lang:"tr",date:Pn(An[e.d],!1)}],["(?:hafta\\s+ici\\s+her\\s+gun|her\\s+hafta\\s+ici)",()=>({strong:!0,lang:"tr",rule:"every weekday"})],["her\\s+(?<u>gun|hafta|ay|yil|sene)",e=>({strong:!0,lang:"tr",rule:`every ${{gun:"day",hafta:"week",ay:"month",yil:"year",sene:"year"}[e.u]}`})],[`(?<n>${dd})\\s+(?<u>gunde|haftada|ayda)\\s+bir`,e=>{const t=ho(e.n,li),n={gunde:"day",haftada:"week",ayda:"month"}[e.u];return t>0?{strong:!0,lang:"tr",rule:t===1?`every ${n}`:`every ${t} ${n}s`}:null}],[`(?<day>\\d{1,2})\\s+(?<mon>${yj})${vj}(?:\\s+(?<y>\\d{4})${Da})?`,e=>({strong:!0,lang:"tr",date:Us(jh[e.mon],Number(e.day),_a(e.y))})],[`saat\\s*(?<h>\\d{1,2})(?:[:.](?<m>[0-5]\\d))?${Da}`,e=>{const t=Number(e.h);
32return t<=23?{strong:!0,lang:"tr",clock:{h:t,m:Number(e.m??0),loose:e.m==null}}:null}],[`(?<p>sabah|ogleden\\s+sonra|aksam|gece|ogle|oglen)\\s+(?:saat\\s*)?(?<h>\\d{1,2})(?:[:.](?<m>[0-5]\\d))?${Da}`,e=>{const t=Number(e.h);return t<=23?{strong:!0,lang:"tr",clock:{h:t,m:Number(e.m??0),loose:!0,period:xo(e.p)}}:null}],[`(?:oglen|ogleyin|ogle)(?:'?e)?${go}`,()=>({strong:!1,lang:"tr",clock:{h:12,m:0,loose:!1}})],[`(?<p>sabahi?|ogleden\\s+sonra|aksamustu|aksami?|gecesi|gece)${go}`,e=>({strong:!1,lang:"tr",period:xo(e.p)})]],jj=`(^|[\\s(\\["'“])`,Nj=`(?=$|\\s|[,.!?;:)\\]"'”]+(?:$|\\s))`,Sj=kj.map(([e,t])=>({re:new RegExp(`${jj}(?:${e})${Nj}`,"g"),build:t})),Cj=/\S*(?:[a-z][a-z0-9+.-]*:\/\/|www\.)\S*|\S+@\S+/gi,Tj=/(?:^|\s)(?:on|by|due|until)\s+$/,_j=/^\s+kadar(?=$|\s|[,.!?;:])/,Ej=/^[\s,.!?;:)\]"'”]*$/,md=e=>String(e).padStart(2,"0");function Dj(e,t){let n=e.h;if(e.ap)n=n%12+(e.ap==="pm"?12:0);else if(e.loose&&n<=12){const a=e.period??t;a==="morning"?n=n%12:a==="noon"?n=n<6?n+12:n:a==="afternoon"||a==="evening"?n=n<12?n+12:n:a==="night"?n=n===12?0:n>=6?n+12:n:n>=1&&n<=7&&(n+=12)}return n<=23&&e.m<=59?`${md(n)}:${md(e.m)}`:null}function Rj(e,t,n){const a=[];for(const c of t.matchAll(Cj))a.push([c.index,c.index+c[0].length]);const r=[];for(const{re:c,build:l}of Sj){c.lastIndex=0;let d;for(;d=c.exec(t);){const m=d.index+d[1].length,u=d.index+d[0].length;if(u===m){c.lastIndex++;continue}if(c.lastIndex=u,a.some(([p,h])=>m<h&&u>p))continue;const f=l(d.groups??{},{orig:e.slice(m,u),opts:n});f&&r.push({...f,start:m,end:u})}}r.sort((c,l)=>l.end-l.start-(c.end-c.start)||c.start-l.start);const o=[];for(const c of r)o.some(l=>c.start<l.end&&c.end>l.start)||o.push(c);return o.sort((c,l)=>c.start-l.start)}const Ij=(e,t)=>{const n=a=>e.some(r=>r[a]);return!(t.date&&(n("date")||n("rule"))||t.rule&&(n("rule")||n("date"))||t.clock&&n("clock")||t.period&&n("period"))};function Mj(e,t){const n=[];for(const a of e){const r=n[n.length-1],o=r?.[r.length-1];r&&/^[\s,]*$/.test(t.slice(o.end,a.start))&&Ij(r,a)?r.push(a):n.push([a])}return n}function Sh(e,t){const n=e.slice(0,t.start).replace(/[\s,;:–—-]+$/,""),a=e.slice(t.end).replace(/^[\s,;:]+/,"");return n?a?/^[.!?)\]]/.test(a)?`${n}${a}`.trim():`${n} ${a}`.trim():n.trim():a.replace(/^[.!?)\]]+\s*/,"").trim()}function Lj(e){try{const t=new Intl.DateTimeFormat(e,{day:"numeric",month:"numeric"}).formatToParts(new Date(2e3,10,22));return t.findIndex(n=>n.type==="day")<t.findIndex(n=>n.type==="month")}catch{return!0}}function Aj(e,t={}){if(!e.trim())return null;const n=t.now??new Date,a={dayFirst:t.dayFirst??!0,hour12:t.hour12??!1},r=new Date(n.getFullYear(),n.getMonth(),n.getDate()),o=bj(e),c=Mj(Rj(e,o,a),o);for(let l=c.length-1;l>=0;l--){const d=c[l];let m=d[0].start,u=d[d.length-1].end;const f=Tj.exec(o.slice(0,m));if(d.every(j=>j.period&&!j.date&&!j.clock)||d.length===1&&d[0].needsCue&&!f)continue;const p=d.some(j=>j.strong)||d.some(j=>j.date)&&d.some(j=>j.clock),h=Ej.test(o.slice(u));if(!p&&!h&&!f)continue;f&&(m-=f[0].replace(/^\s/,"").length);const g=d.some(j=>j.lang==="tr")?"tr":"en",b=g==="tr"?_j.exec(o.slice(u)):null;b&&(u+=b[0].length);const x=d.find(j=>j.date),y=d.find(j=>j.clock),w=d.find(j=>j.period)?.period,k=d.find(j=>j.rule)?.rule;let N;if(y){const j=Dj(y.clock,w);if(!j)continue;N=j}else w&&(N=gj[w]);let C;if(x){const j=x.date(r);if(!j)continue;C=j}else if(!k){if(!N)continue;const[j,T]=N.split(":").map(Number);C=j*60+T>n.getHours()*60+n.getMinutes()?r:st(r,1)}const v={start:m,end:u,text:e.slice(m,u),date:C,time:N,recurrence:k,lang:g};return/[\p{L}\p{N}]/u.test(Sh(e,v))?v:null}return null}const Wa=()=>({title:"",description:"",quadrant:"",labels:[]}),Pj=e=>({...Wa(),quadrant:e.quadrant,labels:e.labels,projectId:e.projectId}),ws=[{id:"do",name:"Do First",helper:"Urgent and important. Do it first."},{id:"schedule",name:"Schedule",helper:"Important, not urgent. Plan time for it."},{id:"delegate",name:"Delegate",helper:"Urgent, not important. Hand it off if you can."},{id:"backlog",name:"Backlog",helper:"Neither. Park it and review later."}],Oj="Skip it for now. It waits in Categorize.",Tc=[{value:"every day",label:"Every day",short:"Daily"},{value:"every weekday",label:"Every weekday",short:"Weekdays"},{value:"every week",label:"Every week",short:"Weekly"},{value:"every 2 weeks",label:"Every 2 weeks",short:"Biweekly"},{value:"every month",label:"Every month",short:"Monthly"},{value:"every 3 months",label:"Every 3 months",short:"Quarterly"},{value:"every year",label:"Every year",short:"Yearly"}],fd=e=>Tc.some(t=>t.value===e),hd=e=>Tc.find(t=>t.value===e)?.short??e,di=e=>{if(Nr(e))return"Today";if(Yg(e))return"Tomorrow";const t=ls(e,new Date);return t>1&&t<7?Ee(e,"EEE"):Ee(e,"MMM d")},pd=(e,t,n)=>{const a=di(e);if(!na(t))return a;const r=qi(t,n);return/\d$/.test(a)?`${a} · ${r}`:`${a} ${r}`},Ch=e=>!!(e.dueDate||e.dueTime||e.recurrence?.trim()),$j=(e,t)=>!t||Ch(e)?e:{...e,title:Sh(e.title,t),dueDate:t.date,dueTime:t.time,recurrence:t.recurrence},Fj=e=>{const t=e.description.trim();return{content:e.title.trim(),...t?{description:t}:{}
32,labels:[...e.labels.filter(Boolean),...e.quadrant?[e.quadrant]:[]],...om(e.dueDate,e.dueTime,e.recurrence),...e.deadline?{deadline_date:Dr(e.deadline)}:{},...e.priority!=null?{priority:e.priority}:{},...e.projectId?{project_id:e.projectId}:{}}},qj=(e,t)=>e.length>t?`${e.slice(0,t-1).trimEnd()}…`:e,zj=e=>{const t=ws.find(r=>r.id===e.quadrant),n=e.recurrence?.trim(),a=t?qj(e.title.trim(),60):"Waiting in Categorize";return{title:t?`Added to ${t.name}`:"Task added",description:n?`${a} · Repeats ${n}`:a}},Uj=(e=new Date)=>[{label:"Today",value:e},{label:"Tomorrow",value:st(e,1)},{label:"Next week",value:st(e,7)}],gd=({value:e,onPick:t,accentClass:n,variant:a="column"})=>{const r=a==="sheet";return s.jsx("div",{className:r?"grid grid-cols-3 gap-2":"flex flex-col gap-1.5",role:"group","aria-label":"Quick dates","data-qa":"date-quick-picks","data-variant":a,children:Uj().map(o=>{const c=!!e&&Wg(e,o.value);return s.jsxs(W,{type:"button",variant:"outline",size:r?void 0:"sm","aria-pressed":c,className:S(r?"h-auto min-h-11 flex-col gap-0 px-1 py-1.5 text-[15px] leading-tight":"h-8 justify-between px-2.5 text-xs",c&&n),onClick:()=>
32t(o.value),children:[o.label,s.jsx("span",{className:S("font-normal opacity-60",r&&"text-[12px]"),"aria-hidden":!0,"data-qa":"quick-weekday",children:Ee(o.value,"EEE")})]},o.label)})})},Bj={months:"flex flex-col",month:"space-y-3 w-full",caption:"flex justify-center relative items-center h-11",caption_label:"text-[15px] font-semibold",nav_button:"inline-flex h-11 w-11 items-center justify-center rounded-lg text-foreground/80 active:bg-muted",nav_button_previous:"absolute left-0",nav_button_next:"absolute right-0",head_row:"flex w-full",head_cell:"flex-1 text-muted-foreground font-normal text-[12px]",row:"flex w-full mt-1",cell:"flex-1 h-11 text-center p-0 relative flex items-center justify-center focus-within:relative focus-within:z-20",day:"h-11 w-11 max-w-full rounded-full text-[15px] font-normal inline-flex items-center justify-center aria-selected:opacity-100 active:bg-muted"},ui=({title:e,subtitle:t,value:n,onChange:a,setActivePopover:r,accentClass:o="border-blue-500/40 bg-blue-500/10 text-blue-600 dark:text-blue-400",repeat:c,inSheet:l=!1,minDate:d,clearable:m=!0,clearLabel:u="Clear date",time:f})=>{const p=d?{before:d}:void 0,h=x=>{a(x),x&&r(null)},g=()=>{c?.onChange(void 0),h(void 0)},b=m&&!!(n||c?.value);return l?s.jsxs("div",{className:"atd-datesheet",children:[s.jsx(gd,{value:n,onPick:h,accentClass:o,variant:"sheet"}),s.jsx(ii,{mode:"single",selected:n,onSelect:x=>h(x??void 0),disabled:p,className:"p-0",classNames:Bj}),f&&s.jsx(mi,{value:f.value,onChange:f.onChange,accentClass:o,inSheet:!0}),c&&s.jsx(bd,{value:c.value,onChange:c.onChange,inSheet:!0}),b&&s.jsxs(W,{variant:"ghost",className:"w-full h-11 text-[15px] text-muted-foreground hover:text-destructive",onClick:g,children:[s.jsx(Ie,{className:"mr-1.5 h-4 w-4"}),u]})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"px-3 py-2.5 border-b flex items-start justify-between gap-2",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h3",{className:"text-sm font-semibold",children:e}),t&&s.jsx("p",{className:"text-[11px] text-muted-foreground mt-0.5",children:t})]}),s.jsx(W,{variant:"ghost",size:"icon",className:"h-6 w-6 rounded-full shrink-0",onClick:()=>r(null),children:s.jsx(Ie,{className:"h-3.5 w-3.5"})})]}),s.jsxs("div",{className:"flex items-start gap-3 p-2","data-qa":"date-picker-wide",children:[s.jsx(ii,{mode:"single",selected:n,onSelect:x=>h(x??void 0),disabled:p,initialFocus:!0,className:"rounded-md p-0"}),s.jsxs("div",{className:"flex w-[212px] shrink-0 flex-col gap-2 self-stretch",children:[s.jsx(gd,{value:n,onPick:h,accentClass:o}),f&&s.jsx(mi,{value:f.value,onChange:f.onChange,accentClass:o,onPicked:()=>{n&&r(null)}}),c&&s.jsx(bd,{value:c.value,onChange:c.onChange}),b&&s.jsx("div",{className:"mt-auto",children:s.jsxs(W,{variant:"ghost",size:"sm",className:"w-full h-8 text-xs text-muted-foreground hover:text-destructive",onClick:g,children:[s.jsx(Ie,{className:"mr-1.5 h-3.5 w-3.5"}),u]})})]})]})]})},Th=["09:00","12:00","15:00","18:00"],mi=({value:e,onChange:t,accentClass:n,onPicked:a,inSheet:r=!1})=>{const[o,c]=i.useState(e??""),l=i.useRef(null),d=i.useRef({draft:o,value:e,onChange:t});d.current={draft:o,value:e,onChange:t};const m=i.useRef(null);i.useEffect(()=>{m.current=null,c(e??"")},[e]);const u=g=>{const b=m.current?m.current.time:d.current.value;g!==b&&(m.current={time:g},d.current.onChange(g))},f=()=>{const g=d.current.draft;return na(g)?(u(g),!0):(!g&&!l.current?.validity.badInput&&u(void 0),!1)};i.useEffect(()=>()=>{f()},[]);const p=g=>{c(g),d.current.draft=g,u(g),a?.()},h=g=>{g.key!=="Enter"||g.metaKey||g.ctrlKey||(g.preventDefault(),g.stopPropagation(),f()&&a?.())};return s.jsxs("div",{className:S("border-t border-border/60 px-1",r?"pt-3 space-y-2.5":"pt-2 space-y-2"),"data-qa":"time-section",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("span",{className:S("font-medium text-muted-foreground",r?"text-[15px]":"text-xs"),children:"Time"}),s.jsxs("div",{className:"relative flex-1 min-w-0",children:[s.jsx("input",{ref:l,type:"time",value:o,onChange:g=>c(g.target.value),onBlur:f,onKeyDown:h,"aria-label":"Time",className:S("block w-full min-w-0 rounded-md border border-input bg-transparent tabular-nums outline-none focus-visible:ring-2 focus-visible:ring-ring dark:[color-scheme:dark]",r?"h-11 pl-2.5 pr-11 text-base":"h-8 pl-2.5 pr-8 text-base sm:text-xs",!o&&"text-muted-foreground")}),e&&s.jsx("button",{type:"button","aria-label":"Remove time",title:"Remove time",className:r?"absolute right-0 top-0 inline-flex h-11 w-11 items-center justify-center rounded text-muted-foreground hover:bg-muted hover:text-foreground":"absolute right-1 top-1 inline-flex h-6 w-6 items-center justify-center rounded text-muted-foreground hover:bg-muted hover:text-foreground",onMouseDown:g=>g.preventDefault(),onClick:()=>{c(""),d.current.draft="",u(void 0)},children:s.jsx(Ie,{className:"h-3.5 w-3.5"})})]})]}),s.jsx("div",{className:S("grid grid-cols-4",r?"gap-2":"gap-1.5"),role:"group","aria-label":"Quick times",children:Th.map(g=>s.jsx(W,{type:"button",variant:"outline",size:r?void 0:"sm","aria-pressed":e===g,className:S(r?"h-11 px-1 text-[15px]":"h-8 px-1 text-xs","tabular-nums",e===g&&n),onClick:()=>p(g),children:qi(g)},g))})]})}
32,bo="none",xd="custom",bd=({value:e,onChange:t,inSheet:n=!1})=>{const[a,r]=i.useState(()=>!!e&&!fd(e));return s.jsxs("div",{className:S("flex items-center gap-3 border-t border-border/60 px-1",n?"pt-3":"pt-2"),children:[s.jsx("span",{className:S("font-medium text-muted-foreground",n?"text-[15px]":"text-xs"),children:"Repeat"}),a?s.jsxs("div",{className:"relative flex-1",children:[s.jsx("input",{autoFocus:!0,value:e??"",onChange:o=>t(o.target.value||void 0),placeholder:"e.g. every mon, fri","aria-label":"Custom repeat",className:n?"h-11 w-full rounded-md border border-input bg-transparent pl-2.5 pr-11 text-base outline-none focus-visible:ring-2 focus-visible:ring-ring":"h-8 w-full rounded-md border border-input bg-transparent pl-2.5 pr-8 text-base sm:text-xs outline-none focus-visible:ring-2 focus-visible:ring-ring"}),s.jsx("button",{type:"button","aria-label":"Back to repeat options",className:n?"absolute right-0 top-0 inline-flex h-11 w-11 items-center justify-center rounded text-muted-foreground hover:bg-muted hover:text-foreground":"absolute right-1 top-1 inline-flex h-6 w-6 items-center justify-center rounded text-muted-foreground hover:bg-muted hover:text-foreground",onClick:()=>{r(!1),t(void 0)},children:s.jsx(Ie,{className:"h-3.5 w-3.5"})})]}):s.jsxs(dj,{value:e&&fd(e)?e:bo,onValueChange:o=>{o===xd?(r(!0),t(void 0)):t(o===bo?void 0:o)},children:[s.jsx(yh,{className:n?"h-11 flex-1 text-[15px]":"h-8 flex-1 text-xs","aria-label":"Repeat",children:s.jsx(uj,{})}),s.jsxs(kh,{className:n?"rounded-xl z-[70]":"rounded-xl",children:[s.jsx(Ka,{value:bo,className:n?"min-h-11 text-[15px]":"text-xs",children:"Doesn't repeat"}),Tc.map(o=>s.jsx(Ka,{value:o.value,className:n?"min-h-11 text-[15px]":"text-xs",children:o.label},o.value)),s.jsx(Ka,{value:xd,className:n?"min-h-11 text-[15px]":"text-xs",children:"Custom…"})]})]})]})},Hj=Object.freeze(Object.defineProperty({__proto__:null,DateSelectorPopover:ui,TIME_CHIPS:Th,TimeSection:mi,default:ui},Symbol.toStringTag,{value:"Module"})),_c="border-amber-500/40 bg-amber-500/10 text-amber-600 dark:text-amber-400",Vj=({taskId:e,deadline:t,onDone:n})=>{const a=t?.date?Ms(t.date):void 0,r=o=>{e&&window.dispatchEvent(new CustomEvent("task:set-deadline",{detail:{taskId:e,date:o?Ee(o,"yyyy-MM-dd"):null}})),o||n()};return s.jsx(ui,{title:"Deadline",value:a,onChange:r,setActivePopover:()=>n(),accentClass:_c,clearable:!!t,clearLabel:"Clear deadline"})},Kj=Object.freeze(Object.defineProperty({__proto__:null,DEADLINE_ACCENT:_c,DeadlinePicker:Vj},Symbol.toStringTag,{value:"Module"})),yd=e=>e.preventDefault(),Jn={onPointerDown:yd,onMouseDown:yd},fi=[{value:4,label:"P1",desc:"Urgent",tone:"fb-p1"},{value:3,label:"P2",desc:"High",tone:"fb-p2"},{value:2,label:"P3",desc:"Medium",tone:"fb-p3"},{value:1,label:"P4",desc:"No flag",tone:"fb-p4"}],Ec="atd-root atd-pop p-0 rounded-xl shadow-xl border-border/60",wd=S(Ec,"atd-pop-calendar w-[min(320px,calc(100vw-32px))]"),vd=S(Ec,"atd-pop-calendar w-auto max-w-[calc(100vw-24px)]"),kd="atd-root atd-pop pk-pop",_h="(max-width: 639px), (max-height: 500px) and (pointer: coarse)",Yj=e=>{const t=window.matchMedia?.(_h);return t?.addEventListener("change",e),()=>t?.removeEventListener("change",e)},Eh=()=>i.useSyncExternalStore(Yj,()=>!!window.matchMedia?.(_h).matches,()=>!1),Nn=({name:e,tone:t,icon:n,label:a,suffix:r,on:o,open:c,onOpenChange:l,onClear:d,children:m,contentClassName:u,onReturnFocus:f,sheet:p,sheetSubtitle:h,sheetFit:g,clearLabel:b,className:x})=>{const y=Eh(),w=i.useRef(null),k=i.useRef(!1),N=s.jsxs(s.Fragment,{children:[s.jsx(n,{"aria-hidden":!0}),s.jsx("span",{className:"atd-value",children:a}),r&&s.jsx("span",{className:"atd-suffix",children:r})]}),C={type:"button","aria-label":o?`${e}: ${a}${r?` ${r}`:""}`:void 0,title:o?`${a}${r?` ${r}`:""}`:void 0},v=o&&s.jsx("button",{type:"button",className:"fb-x","aria-label":b??`Clear ${e.toLowerCase()}`,onClick:d,...Jn,children:s.jsx(Ie,{"aria-hidden":!0})});return p&&y?s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:S("fb-pill atd-pill",o&&"is-on",t,x),children:[s.jsx("button",{...C,"aria-haspopup":"dialog","data-state":c?"open":"closed",onClick:()=>l(!0),children:N}),v]}),s.jsx(Ei,{open:c,onOpenChange:l,children:s.jsxs(br,{children:[s.jsx(ln,{className:"pk-sheet-overlay"}),s.jsx(Wj,{title:p,subtitle:h,fit:g,children:m})]})})]}):s.jsxs(Nt,{open:c,onOpenChange:l,children:[s.jsxs("span",{className:S("fb-pill atd-pill",o&&"is-on",t,x),children:[s.jsx(St,{asChild:!0,children:s.jsx("button",{...C,children:N})}),v]}),s.jsx(Ct,{ref:w,className:u,align:"start",side:"bottom",collisionPadding:12,onOpenAutoFocus:j=>{k.current=!1;const T=w.current?.querySelector("input[data-autofocus]");T&&(j.preventDefault(),T.focus())},onInteractOutside:()=>{k.current=!0},onCloseAutoFocus:j=>{const T=!k.current;k.current=!1,!y&&(j.preventDefault(),T&&f())},children:m})]})}
32,Wj=({title:e,subtitle:t,fit:n,children:a})=>{const r=i.useRef(null);return Cc(r),s.jsxs(dn,{ref:r,"aria-describedby":void 0,className:S("atd-root pk-sheet",n&&"is-fit"),onOpenAutoFocus:o=>o.preventDefault(),onCloseAutoFocus:o=>o.preventDefault(),children:[s.jsx("div",{className:"atd-grab","aria-hidden":!0}),s.jsxs("div",{className:"pk-sheet-head",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx(un,{className:"pk-sheet-title",children:e}),t&&s.jsx("p",{className:"pk-sheet-sub",children:t})]}),s.jsx(yr,{className:"pk-done",children:"Done"})]}),n?s.jsx("div",{className:"pk-sheet-body",children:a}):a]})},Gj=({projectId:e,selectedProject:t,dueDate:n,dueTime:a,recurrence:r,fromTitle:o,onIgnoreTitleDate:c,deadline:l,priority:d,selectedLabels:m,activePopover:u,setActivePopover:f,onProjectSelect:p,onDateChange:h,onTimeChange:g,onRecurrenceChange:b,onDeadlineChange:x,onPrioritySelect:y,onToggleLabel:w,onClearLabels:k,projects:N,isLoadingProjects:C,availableLabels:v,isLoadingLabels:j,apiKey:T,onReturnFocus:_})=>{const I=H=>({open:u===H,onOpenChange:K=>f(K?H:null),onReturnFocus:_}),R=N.find(H=>H.id===e),M=!R||R.is_inbox_project||R.name?.toLowerCase()==="inbox",P=r?.trim(),E=n&&P?`${pd(n,a)} · ↻ ${hd(P)}`:n?di(n):P?`↻ ${hd(P)}${a?` ${qi(a)}`:""}`:"Date",D=n&&!P&&a?pd(n,a).slice(di(n).length).trim():void 0,L=fi.find(H=>H.value===d),A=Eh();return s.jsxs("div",{className:"atd-props",children:[s.jsx(Nn,{name:"Project",tone:"fb-project atd-project",icon:M?yu:og,label:M?"Inbox":t,on:!M,...I("project"),onClear:()=>p(void 0),contentClassName:kd,sheet:"Project",children:s.jsx(lj,{projects:N,isLoading:C,projectId:e,onSelect:p})}),s.jsx(Nn,{name:"Date",tone:S("fb-date",n&&a&&"has-time"),icon:Zs,label:E,suffix:D,on:!!n||!!P,...I("date"),onClear:o&&c?c:()=>{h(void 0),b(void 0)},clearLabel:o?"Ignore the date in the title":void 0,className:o?"is-nl":void 0,contentClassName:A?wd:vd,sheet:"Date",sheetSubtitle:"When you plan to work on it",sheetFit:!0,children:s.jsx(rn,{title:"Date",subtitle:"When you plan to work on it",value:n,onChange:h,setActivePopover:f,time:{value:a,onChange:g},repeat:{value:r,onChange:b},inSheet:A})}),s.jsx(Nn,{name:"Deadline",tone:"atd-deadline",icon:os,label:l?Ee(l,"MMM d"):"Deadline",on:!!l,...I("deadline"),onClear:()=>x(void 0),contentClassName:A?wd:vd,sheet:"Deadline",sheetSubtitle:"The hard date it must be done by",sheetFit:!0,children:s.jsx(rn,{title:"Deadline",subtitle:"The hard date it must be done by",value:l,onChange:x,setActivePopover:f,accentClass:_c,clearLabel:"Clear deadline",inSheet:A})}),s.jsx(Nn,{name:"Priority",tone:"fb-priority",icon:Cs,label:L?L.label:"Priority",on:!!L,...I("priority"),onClear:()=>y(void 0),contentClassName:S(Ec,"w-52"),sheet:"Priority",sheetFit:!0,children:s.jsx(Qj,{priority:d,onSelect:y,setActivePopover:f,inSheet:A})}),s.jsx(Nn,{name:"Labels",tone:"fb-label",icon:vr,label:m.length?Jt(m[0]):"Labels",suffix:m.length>1?`+${m.length-1}`:void 0,on:m.length>0,...I("labels"),onClear:k,contentClassName:kd,sheet:"Labels",children:s.jsx(cj,{isLoading:j,availableLabels:v,selectedLabels:m,onToggleLabel:w,apiKey:T})})]})},Qj=({priority:e,onSelect:t,setActivePopover:n,inSheet:a})=>a?s.jsxs("div",{className:"atd-prio-list",children:[fi.map(r=>s.jsxs("button",{type:"button",onClick:()=>{t(r.value),n(null)},className:S("atd-prio-row",e===r.value&&"is-on"),children:[s.jsx(Cs,{className:S("h-5 w-5 shrink-0",r.tone),"aria-hidden":!0}),s.jsxs("span",{className:"flex-1 text-left",children:[r.label,s.jsx("span",{className:"ml-2 text-muted-foreground",children:r.desc})]}),e===r.value&&s.jsx(Oe,{className:"h-5 w-5 shrink-0 text-primary","aria-hidden":!0})]},r.value)),e!=null&&s.jsxs("button",{type:"button",onClick:()=>{t(void 0),n(null)},className:"atd-prio-row text-muted-foreground",children:[s.jsx(Ie,{className:"h-5 w-5 shrink-0","aria-hidden":!0}),s.jsx("span",{className:"flex-1 text-left",children:"No priority"})]})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"px-3 py-2.5 border-b flex items-center justify-between",children:[s.jsx("h3",{className:"text-sm font-semibold",children:"Priority"}),s.jsx(W,{variant:"ghost",size:"icon",className:"h-6 w-6 rounded-full",onClick:()=>n(null),children:s.jsx(Ie,{className:"h-3.5 w-3.5"})})]}),s.jsxs("div",{className:"p-1.5 space-y-0.5",children:[fi.map(r=>s.jsxs("button",{type:"button",onClick:()=>{t(r.value),n(null)},className:S("flex w-full items-center gap-2.5 rounded-lg px-3 py-2 text-sm transition-colors",e===r.value?"bg-primary/10":"hover:bg-muted/60"),
32children:[s.jsx(Cs,{className:S("h-4 w-4 shrink-0",r.tone)}),s.jsxs("span",{className:"flex-1 text-left",children:[r.label,s.jsx("span",{className:"ml-1.5 text-xs text-muted-foreground",children:r.desc})]}),e===r.value&&s.jsx(Oe,{className:"h-4 w-4 shrink-0 text-primary"})]},r.value)),e!=null&&s.jsxs("button",{type:"button",onClick:()=>{t(void 0),n(null)},className:"flex w-full items-center gap-2.5 rounded-lg px-3 py-2 text-sm text-muted-foreground hover:bg-muted/60 transition-colors",children:[s.jsx(Ie,{className:"h-4 w-4 shrink-0"}),s.jsx("span",{className:"flex-1 text-left",children:"No priority"})]})]})]}),Jj=6,Xj=({title:e,description:t,onTitleChange:n,onDescriptionChange:a,onSubmit:r,titleRef:o,noteRef:c,highlight:l})=>{const d=i.useRef(null),m=()=>{d.current&&o.current&&(d.current.scrollLeft=o.current.scrollLeft)};i.useLayoutEffect(m),i.useLayoutEffect(()=>{const f=c.current;if(!f)return;const p=parseFloat(getComputedStyle(f).lineHeight)||20;f.style.height="auto",f.style.height=`${Math.min(f.scrollHeight,p*Jj)}px`},[t,c]);const u=f=>{f.metaKey||f.ctrlKey||f.altKey||f.nativeEvent.isComposing||(f.key==="Enter"?(f.preventDefault(),r(f.shiftKey?!0:void 0)):f.key==="ArrowDown"&&(f.preventDefault(),c.current?.focus()))};return s.jsxs("div",{className:"atd-head",children:[s.jsxs("div",{className:"atd-title-wrap",children:[l&&s.jsxs("div",{ref:d,className:"atd-title atd-title-mirror","aria-hidden":!0,children:[e.slice(0,l.start),s.jsx("mark",{"data-qa":"nl-mark",children:e.slice(l.start,l.end)}),e.slice(l.end)]}),s.jsx("input",{ref:o,placeholder:"What needs to be done?","aria-label":"Task title",value:e,onChange:f=>n(f.target.value),onKeyDown:u,onScroll:m,onSelect:m,className:"atd-title",enterKeyHint:"done"})]}),s.jsx("textarea",{ref:c,placeholder:"Add a note","aria-label":"Note",value:t,onChange:f=>a(f.target.value),rows:1,className:"atd-note"})]})},Zj=({value:e,onChange:t})=>{const n=i.useRef([]),a=Math.max(0,ws.findIndex(c=>c.id===e)),r=c=>t(e===c?"":c),o=c=>{if(!(c.altKey||c.ctrlKey||c.metaKey))if(c.key==="ArrowRight"||c.key==="ArrowLeft"){c.preventDefault();const l=n.current.findIndex(m=>m===document.activeElement),d=(Math.max(0,l)+(c.key==="ArrowRight"?1:-1)+ws.length)%ws.length;n.current[d]?.focus()}else(c.key==="0"||c.key==="Backspace")&&(c.preventDefault(),t(""))};return s.jsxs("div",{className:"atd-quadrant",children:[s.jsxs("div",{className:"atd-q-head",children:[s.jsx("span",{className:"atd-q-title",children:"Quadrant"}),e?s.jsx("button",{type:"button",className:"atd-q-clear",onClick:()=>t(""),...Jn,children:"Clear"}):s.jsx("span",{className:"atd-q-later",children:"Sort later"})]}),s.jsx("div",{role:"radiogroup","aria-label":"Quadrant",className:"atd-chips",onKeyDown:o,children:ws.map((c,l)=>s.jsxs("button",{ref:d=>{n.current[l]=d},type:"button",role:"radio","aria-checked":e===c.id,tabIndex:l===a?0:-1,className:"atd-chip",style:{"--qc":`var(--q-${c.id})`},onClick:()=>r(c.id),...Jn,children:[s.jsx("span",{className:"atd-dot","aria-hidden":!0}),s.jsx("span",{className:"atd-chip-name",children:c.name}),s.jsx("kbd",{className:"atd-chip-key","aria-hidden":!0,children:l+1})]},c.id))}),s.jsx("p",{className:"atd-help",children:[{id:"",helper:Oj},...ws].map(c=>s.jsx("span",{className:c.id===e?"is-on":void 0,"aria-hidden":c.id!==e,children:c.helper},c.id||"none"))})]})},Dh=i.forwardRef(({className:e,...t},n)=>s.jsx(Eu,{ref:n,className:S("peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",e),...t,children:s.jsx(ig,{className:S("flex items-center justify-center text-current"),children:s.jsx(Oe,{className:"h-4 w-4"})})}));Dh.displayName=Eu.displayName;const eN=({onSubmit:e,isDisabled:t,isSubmitting:n,keepOpen:a,onKeepOpenChange:r})=>s.jsxs("div",{className:"atd-footer",children:[s.jsxs("label",{className:"atd-another",htmlFor:"atd-keep-open",...Jn,onClick:o=>{o.target.closest("#atd-keep-open")||(o.preventDefault(),r(!a))},children:[s.jsx(Dh,{id:"atd-keep-open",checked:a,onCheckedChange:o=>r(o===!0)}),"Add another"]}),s.jsx(W,{type:"button",onClick:e,...Jn,disabled:t,"aria-busy":n||void 0,className:S("atd-submit h-9 min-w-[112px] rounded-lg px-4 text-[13.5px] font-semibold","disabled:pointer-events-auto disabled:cursor-not-allowed disabled:hover:bg-primary"),children:s.jsxs("span",{className:"atd-submit-label",children:[s.jsxs("span",{className:S(!n&&"is-on"),"aria-hidden":n,children:["Add task",
32s.jsx("kbd",{className:"atd-enter","aria-hidden":!0,children:"↵"})]}),s.jsxs("span",{className:S(n&&"is-on"),"aria-hidden":!n,children:[s.jsx(kt,{className:"animate-spin","aria-hidden":!0}),"Adding…"]})]})})]}),tN=(e,t,n)=>{const{toast:a}=He(),[r,o]=i.useState(!1),[c,l]=i.useState(null),{projects:d,isLoading:m}=Ji(e),{data:u=[],isLoading:f}=it({queryKey:["labels",e],queryFn:async()=>{if(!e)return[];const x=new Ke(e);try{return await x.getLabels()}catch{return a({title:"Error",description:"Failed to fetch labels",variant:"destructive"}),[]}},enabled:!!e}),p=u.filter(x=>!["do","schedule","delegate","backlog"].includes(x.name.toLowerCase())).map(x=>({id:x.id.toString(),name:x.name,color:x.color,count:0})),h=x=>{n(y=>({...y,labels:y.labels.includes(x)?y.labels.filter(w=>w!==x):[...y.labels,x]}))},g=x=>{n(y=>({...y,projectId:x})),l(null)},b=i.useCallback(()=>{if(!t.projectId)return"Inbox";const x=d.find(y=>y.id===t.projectId);return x?x.name:"Inbox"},[t.projectId,d]);return{isSubmitting:r,setIsSubmitting:o,activePopover:c,setActivePopover:l,projects:d,isLoadingProjects:m,availableLabels:p,isLoadingLabels:f,handleToggleLabel:h,handleProjectSelect:g,getSelectedProjectName:b}},sN=(e,t,n)=>{for(let a=e.indexOf(t);a>=0;a=e.indexOf(t,a+1))if(a<n.end&&a+t.length>n.start)return!0;return!1};function nN(e){const[t,n]=i.useState(null),a=typeof navigator<"u"?navigator.language:void 0,r=i.useMemo(()=>({dayFirst:Lj(a),hour12:nm(a)}),[a]),o=Ch(e),c=i.useMemo(()=>{if(o)return null;const d=Aj(e.title,r);return!d||t&&sN(e.title,t,d)?null:d},[e.title,o,t,r]);i.useEffect(()=>{e.title.trim()||n(null)},[e.title]);const l=i.useCallback(()=>{c&&n(c.text)},[c]);return{match:c,ignore:l}}const Rh="add-task-keep-open",aN=()=>{try{return localStorage.getItem(Rh)==="1"}catch{return!1}},rN=e=>e.tagName==="INPUT"||e.tagName==="TEXTAREA"||e.tagName==="SELECT"||e.isContentEditable,Ih=i.memo(({formData:e,setFormData:t,onSubmit:n,apiKey:a})=>{const{isSubmitting:r,setIsSubmitting:o,activePopover:c,setActivePopover:l,projects:d,isLoadingProjects:m,availableLabels:u,isLoadingLabels:f,handleToggleLabel:p,handleProjectSelect:h,getSelectedProjectName:g}=tN(a,e,t),b=i.useRef(null),x=i.useRef(null),y=i.useRef(null);Cc(b);const{match:w,ignore:k}=nN(e),N=()=>{const R=x.current;R&&(R.focus(),R.setSelectionRange(R.value.length,R.value.length))},[C,v]=i.useState(aN),j=R=>{v(R);try{localStorage.setItem(Rh,R?"1":"0")}catch{}},T=R=>t(M=>({...M,...R})),_=async R=>{if(!e.title.trim()||r)return;const M=$j(e,w);if(M!==e&&(t(M),(M.dueDate||M.dueTime||M.recurrence)&&pe("due_changed",{via:"nl",kind:M.dueTime?"time":"date"})),!(R||C)){n(M,!1);return}o(!0);const E=await n(M,!0);o(!1),E&&x.current?.focus()},I=R=>{if(R.key==="Enter"&&(R.metaKey||R.ctrlKey)){if(R.nativeEvent.isComposing)return;R.preventDefault(),l(null),_(R.shiftKey||void 0);return}const M=R.target;if(R.altKey||R.ctrlKey||R.metaKey||rN(M)||!b.current?.contains(M))return;const P=ws[Number(R.key)-1];/^[1-4]$/.test(R.key)&&P&&(R.preventDefault(),T({quadrant:e.quadrant===P.id?"":P.id}))};return s.jsxs(br,{children:[s.jsx(ln,{className:"atd-overlay fixed inset-0 z-50 bg-black/50"}),s.jsxs(dn,{ref:b,"aria-describedby":void 0,className:"atd-root atd-dialog bg-popover text-popover-foreground shadow-2xl",onKeyDown:I,onOpenAutoFocus:R=>{R.preventDefault(),N()},children:[s.jsx(un,{className:"sr-only",children:"New task"}),s.jsx("div",{className:"atd-grab","aria-hidden":!0}),s.jsx(Xj,{title:e.title,description:e.description,onTitleChange:R=>T({title:R}),onDescriptionChange:R=>T({description:R}),onSubmit:_,highlight:w?{start:w.start,end:w.end}:void 0,titleRef:x,noteRef:y}),s.jsxs("div",{className:"atd-body",children:[s.jsx(Gj,{projectId:e.projectId,selectedProject:g(),dueDate:e.dueDate??w?.date,dueTime:e.dueTime??w?.time,recurrence:e.recurrence??w?.recurrence,fromTitle:!!w,onIgnoreTitleDate:k,deadline:e.deadline,priority:e.priority,selectedLabels:e.labels,activePopover:c,setActivePopover:l,onProjectSelect:h,onDateChange:R=>{k(),T(R?{dueDate:R,dueTime:e.dueTime??w?.time}:{dueDate:void 0,dueTime:void 0})},onTimeChange:R=>{k(),t(M=>({...M,dueTime:R,dueDate:M.dueDate??(R?w?.date??_s():void 0)}))},onRecurrenceChange:R=>{k(),T({recurrence:R})},onDeadlineChange:R=>T({deadline:R}),onPrioritySelect:R=>T({priority:R}),onToggleLabel:p,onClearLabels:()=>T({labels:[]}),projects:d,isLoadingProjects:m,availableLabels:u,isLoadingLabels:f,apiKey:a,onReturnFocus:N}
32),s.jsx("div",{className:"atd-divider"}),s.jsx(Zj,{value:e.quadrant,onChange:R=>T({quadrant:R})})]}),s.jsx(eN,{onSubmit:()=>{_()},isDisabled:!e.title.trim(),isSubmitting:r,keepOpen:C,onKeepOpenChange:j}),s.jsxs(yr,{className:"atd-close",children:[s.jsx(Ie,{"aria-hidden":!0}),s.jsx("span",{className:"sr-only",children:"Close"})]})]})]})});Ih.displayName="AddTaskDialogContent";const Be=e=>[s.jsx("span",{className:"toast-roll",children:e},e)],Sn="add-task",oN=e=>{const t=e;return!!t&&(t.tagName==="INPUT"||t.tagName==="TEXTAREA"||t.tagName==="SELECT"||t.isContentEditable)},Mh=i.memo(({onTaskUpdate:e,apiKey:t})=>{const[n,a]=i.useState(!1),[r,o]=i.useState(Wa),c=i.useRef(null),{session:l}=we.useSessionContext(),d=i.useCallback((u={})=>{o(f=>({...f===c.current?Wa():f,...u.title?.trim()?{title:u.title}:{},...u.quadrant?{quadrant:u.quadrant}:{}})),a(!0)},[]);i.useEffect(()=>{const u=p=>d(p.detail??{}),f=p=>{p.key.toLowerCase()!=="q"||p.repeat||p.ctrlKey||p.metaKey||p.altKey||p.shiftKey||oN(p.target)||document.querySelector('[role="dialog"]')||(p.preventDefault(),d())};return window.addEventListener(Wo,u),window.addEventListener("keydown",f),()=>{window.removeEventListener(Wo,u),window.removeEventListener("keydown",f)}},[d]);const m=i.useCallback(async(u,f)=>{if(!u.title.trim())return!1;if(!t)return Z.error("Connect Todoist to add tasks",{id:Sn}),!1;f||(c.current=u,a(!1)),nt()||Z.loading(Be("Adding task…"),{id:Sn,description:void 0,action:void 0});try{const p=new Ke(t);p.setUseDirectApiFirst(!0);const h=await p.createTask(Fj(u));pe("task_added",{quadrant:sa(u.quadrant),via:"dialog"}),l?.user?.id&&setTimeout(()=>{B.from("task_creation_log").insert({user_id:l.user.id,task_id:h.id,quadrant:u.quadrant||"unsorted",created_at:new Date().toISOString()})},0);const g=zj(u),b=nt()&&!u.quadrant?"Added to tasks to sort":g.title;return xt(Sn),Z.success(Be(b),{id:Sn,description:g.description,action:void 0}),ut(20),c.current===u&&(c.current=null),o(x=>x===u?f?Pj(u):Wa():x),e().catch(x=>{}),!0}catch{return c.current===u&&(c.current=null),Z.error(Be("Couldn't add the task"),{id:Sn,description:"Your draft is saved.",action:{label:"Edit",onClick:()=>{o(u),a(!0)}}}),!1}},[t,e,l]);return s.jsxs(Xa,{open:n,onOpenChange:u=>u?d():a(!1),children:[s.jsx(Yb,{asChild:!0,children:s.jsxs(W,{id:"add-task-btn",className:"h-9 gap-2 rounded-lg px-4 text-sm font-semibold",children:[s.jsx(fn,{className:"h-4 w-4",strokeWidth:2.5}),"Add Task"]})}),s.jsx(Ih,{formData:r,setFormData:o,onSubmit:m,apiKey:t})]})});Mh.displayName="AddTaskDialog";const iN=({totalTasks:e,isTaskFocus:t,onTaskUpdate:n,onToggleTaskFocus:a,apiKey:r,urgentImportant:o,important:c,urgent:l,neither:d})=>{const[m,u]=i.useState(!1),f=()=>{const p=new CustomEvent("toggle-all-quadrants",{detail:{collapsed:!m}});window.dispatchEvent(p),u(!m)};return s.jsx("div",{className:"mb-6 max-md:mb-0 space-y-4 max-md:space-y-0",children:s.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 max-md:gap-0",children:[s.jsx("div",{className:"max-md:hidden",children:s.jsx(Zk,{isTaskFocus:t,onToggleTaskFocus:a,hasTasks:e>0})}),s.jsxs("div",{className:"flex items-center gap-2 max-md:hidden",children:[s.jsx(W,{variant:"outline",size:"icon",onClick:f,className:"flex-shrink-0","aria-label":m?"Expand all quadrants":"Collapse all quadrants",title:m?"Expand all quadrants":"Collapse all quadrants",children:m?s.jsx(mt,{size:16}):s.jsx(Su,{size:16})}),s.jsx(Mh,{onTaskUpdate:n,apiKey:r})]})]})})},cN=({totalTasks:e,isTaskFocus:t,onTaskUpdate:n,onToggleTaskFocus:a,apiKey:r,filteredQuadrants:o,quadrants:c,isFocusMode:l,onToggleFocusMode:d,onExitTaskFocus:m,focusedTaskId:u,onTaskFocus:f,onCompleteTask:p,onTaskComplete:h})=>{const{filteredUrgentImportant:g,filteredImportant:b,filteredUrgent:x,filteredNeither:y}=o,w=i.useMemo(()=>({hidden:{opacity:0},visible:{opacity:1,transition:{staggerChildren:.1,duration:.3}}}),[]);return s.jsxs(_e.div,{className:"space-y-6 max-md:space-y-0",variants:w,initial:"hidden",animate:"visible",children:[s.jsx(iN,{totalTasks:e,isTaskFocus:t,onTaskUpdate:n,onToggleTaskFocus:a,apiKey:r,urgentImportant:g,important:b,urgent:x,neither:y}),s.jsx("div",{children:s.jsx(fh,{quadrants:c,isFocusMode:l,isTask
32Focus:t,focusedTaskId:u,onTaskFocus:f,onCompleteTask:p,onToggleFocusMode:d,onExitTaskFocus:m,onToggleTaskFocus:a})})]})},lN=({hasPendingUpdates:e,isFocusMode:t,isTaskFocus:n,onTaskUpdate:a})=>{const r=at(),o=i.useRef(!0),c=i.useRef(!1);return i.useEffect(()=>(o.current=!0,()=>{o.current=!1}),[]),i.useEffect(()=>{e&&!t&&!n&&!c.current&&(async()=>{try{c.current=!0,o.current&&Z.success("Applying task updates",{description:"Syncing your changes with Todoist"}),await r.invalidateQueries({queryKey:["tasks"],refetchType:"active",exact:!1}),o.current&&await a(),requestAnimationFrame(()=>{sw(),typeof window<"u"&&o.current&&window.dispatchEvent(new CustomEvent("matrix:clear-similarity-cache"))})}catch{o.current&&Z.error("Update failed",{description:"There was a problem syncing your changes"})}finally{c.current=!1}})()},[e,t,n,r,a]),null},Lh=Ue.memo(({totalTasks:e,isFocusMode:t,isTaskFocus:n,onTaskUpdate:a,onToggleFocusMode:r,onToggleTaskFocus:o,onExitTaskFocus:c,apiKey:l,urgentImportant:d,important:m,urgent:u,neither:f,quadrants:p,focusedTaskId:h,onTaskFocus:g,onCompleteTask:b,focusStartTime:x,onTaskComplete:y})=>{const w=Fe();return s.jsx(G0,{urgentImportant:d,important:m,urgent:u,neither:f,dateFilter:"all",children:k=>s.jsx(nw,{isFocusMode:t,isTaskFocus:n,onTaskComplete:y,onTaskUpdate:a,children:({handleTaskComplete:N,hasPendingUpdates:C})=>s.jsxs(s.Fragment,{children:[s.jsx(cN,{totalTasks:e,isTaskFocus:n,onTaskUpdate:a,onToggleTaskFocus:o,apiKey:l,filteredQuadrants:k,quadrants:p,isFocusMode:t,onToggleFocusMode:r,onExitTaskFocus:c,focusedTaskId:h,onTaskFocus:g,onCompleteTask:b,onTaskComplete:N}),s.jsx(lN,{hasPendingUpdates:C,isFocusMode:t,isTaskFocus:n,onTaskUpdate:a}),!w&&s.jsx(W0,{})]})})})});Lh.displayName="MatrixView";const dN=({children:e})=>s.jsx(_e.div,{initial:{opacity:0}
32,animate:{opacity:1},transition:{duration:.3},children:e}),uN=e=>(i.useMemo(()=>({...e,urgentImportantCount:e.urgentImportant.length,importantCount:e.important.length,urgentCount:e.urgent.length,neitherCount:e.neither.length}),[e.totalTasks,e.isFocusMode,e.isTaskFocus,e.quadrants,e.focusedTaskId,e.focusStartTime,e.urgentImportant.length,e.important.length,e.urgent.length,e.neither.length,e.apiKey,e.onToggleFocusMode,e.onExitTaskFocus]),e),Ah=e=>{if(!e||!Array.isArray(e)||e.length===0)return"Backlog";const t=e.filter(n=>n!=null).map(n=>String(n).toLowerCase());return t.some(n=>["do","do_first","dofirst","do first"].includes(n))?"Do First":t.some(n=>["schedule","important"].includes(n))?"Schedule":t.some(n=>["delegate","urgent"].includes(n))?"Delegate":(t.some(n=>["backlog","neither"].includes(n)),"Backlog")},mN=e=>{if(!e)return"BACKLOG";const t=e.toUpperCase().trim();return t==="DO"||t==="DO_FIRST"||t==="DOFIRST"||t==="DO FIRST"?"DO_FIRST":t==="SCHEDULE"?"SCHEDULE":t==="DELEGATE"?"DELEGATE":"BACKLOG"},RT=e=>{if(!e)return"Backlog";const t=e.toLowerCase().trim();return["do","do_first","dofirst","do first"].includes(t)?"Do First":t==="schedule"?"Schedule":t==="delegate"?"Delegate":"Backlog"},fN=e=>{if(typeof window>"u")return!1;const t=document.documentElement.classList.contains("task-focus-active");return e||t},jd=(e,t,n,a,r,o=!1)=>{if(!(typeof window>"u"))try{const c={taskId:e,quadrant:t,isRecurring:n,labels:a,isFocusMode:r,timestamp:Date.now(),success:o};localStorage.setItem("last-completed-task",JSON.stringify(c))}catch{}},hN=(e,t)=>{typeof window>"u"||window.dispatchEvent(new CustomEvent("focus-task-completed",{detail:{taskId:e,isRecurring:t,timestamp:Date.now()}}))},pN=async(e,t,n,a,r,o,c=null,l=!1,d)=>{try{const{data:m,error:u}=await B.from("task_completions").insert({user_id:e,task_id:n,quadrant:a,completion_grid:a,original_quadrant:a,completed_at:new Date().toISOString(),is_recurring:r,task_labels:o||[],completion_source:"web_app",focus_session_id:c,task_content:d??null,completion_metadata:{focus_mode:l},validation_status:"validated"}).select("id").maybeSingle();if(u)throw u;return await Pt(e,t,"task_complete",{taskId:n,quadrant:a,isRecurring:r,labels:o||[],isFocusMode:l,focusSessionId:c}),m?.id??null}catch(m){throw m}},gN=async e=>{const{error:t}=await B.from("task_completions").delete().eq("id",e)},xN=async e=>{const t=await bN(e);if(t)return t;try{const n=new Date().toISOString(),{data:a,error:r}=await B.from("focus_sessions").insert({user_id:e,started_at:n,ended_at:n,duration_minutes:0}).select("id").single();return r?null:a?.id??null}catch{return null}},bN=async e=>{try{const t=new Date;t.setHours(0,0,0,0);const{data:n}=await B.from("focus_sessions").select("id").eq("user_id",e).gte("started_at",t.toISOString()).is("ended_at",null).order("started_at",{ascending:!1}).limit(1);return n&&n.length>0?n[0].id:null}catch{return null}},yN=e=>`relative overflow-hidden border px-4 py-3 rounded-xl shadow-lg backdrop-blur-[2px] transition-all duration-200 ${{success:"border-green-200 bg-gradient-to-r from-green-50 to-emerald-50 text-green-800 dark:from-green-950/50 dark:to-emerald-950/50 dark:border-green-800/40 dark:text-green-300",error:"border-red-200 bg-gradient-to-r from-red-50 to-rose-50 text-red-800 dark:from-red-950/50 dark:to-rose-950/50 dark:border-red-800/40 dark:text-red-300",info:"border-blue-200 bg-gradient-to-r from-blue-50 to-sky-50 text-blue-800 dark:from-blue-950/50 dark:to-sky-950/50 dark:border-blue-800/40 dark:text-blue-300",warning:"border-amber-200 bg-gradient-to-r from-amber-50 to-orange-50 text-amber-800 dark:from-amber-950/50 dark:to-orange-950/50 dark:border-amber-800/40 dark:text-amber-300",celebration:"border-violet-200 bg-gradient-to-r from-violet-50 to-purple-50 text-violet-800 dark:from-violet-950/50 dark:to-purple-950/50 dark:border-violet-800/40 dark:text-violet-300"}[e]}`,wN=[{text:"Nice, that's done",category:"achievement",weight:10},{text:"One down 👍",category:"achievement",weight:10},{text:"That's off your plate",category:"achievement",weight:10},{text:"Done, feels good",category:"achievement",weight:9},{text:"Checked off, nice",category:"achievement",weight:9},{text:"That's sorted",category:"achievement",weight:8},{text:"Taken care of",category:"achievement",weight:8},{text:"One less to think about",category:"achievement",weight:9},{text:"Out of the way",category:"achievement",weight:8},{text:"Wrapped that one up",category:"achievement",weight:7},{text:"Good, done",category:"achievement",weight:8},{text:"Off the list 👍",category:"achievement",weight:9},{text:"Handled",category:"achievement",weight:7},{text:"Nicely done",category:"achievement",weight:8},{text:"Done. See you next time",category:"achievement",weight:8,contexts:{isRecurring:!0}},{text:"Done, and the next one's set",category:"achievement",weight:7,contexts:{isRecurring:!0}},{text:"Big one, nicely done",category:"achievement",weight:8,contexts:{quadrant:"DO"}},{text:"That important one? Handled",category:"achievement",weight:7,contexts:{quadrant:"DO"}},{text:"Urgent one, sorted",category:"achievement",weight:8,contexts:{quadrant:"URGENT"}},{text:"Ahead of schedule, nice",category:"achievement",weight:7,contexts:{quadrant:"SCHEDULE"}}],vN=[{text:"Nice pace today",category:"motivation",weight:9},{text:"You're in a good rhythm",category:"motivation",weight:9},{text:"Rolling along nicely",category:"motivation",weight:8},{text:"Smooth, keep going",category:"motivation",weight:8},{text:"Good momentum",category:"motivation",weight:8},{text:"You're on it today",category:"motivation",weight:8},{text:"Nice run going",category:"motivation",weight:8},{text:"Steady and smooth",category:"motivation",weight:7},{text:"Good flow today",category:"motivation",weight:8},{text:"Keep it rolling",category:"motivation",weight:7},{text:"You're getting through it",category:"motivation",weight:7},{text:"Bit by bit, it's working",category:"motivation",weight:7},{text:"First of the day, nice start",category:"motivation",weight:9,contexts:{isFirstOfDay:!0}},{text:"Good way to kick things off",category:"motivation",weight:9,contexts:{isFirstOfDay:!0}},{text:"Off to a good start ☀️",category:"motivation",weight:8,contexts:{isFirstOfDay:!0}},{text:"Straight to what matters 💪",category:"motivation",weight:8,contexts:{quadrant:"DO"}},{text:"Planning ahead, smart move",category:"motivation",weight:8,contexts:{quadrant:"SCHEDULE"}},{text:"Future you will thank you",category:"motivation",weight:7,contexts:{quadrant:"SCHEDULE"}},{text:"Handed off nicely",category:"motivation",weight:7,contexts:{quadrant:"DELEGATE"}},{text:"Chipping at the backlog",category:"motivation",weight:7,contexts:{quadrant:"BACKLOG"}}],kN=[{text:"A step closer, nice",category:"progress",weight:8},{text:"Coming along nicely",category:"progress",weight:8},{text:"It's adding up",category:"progress",weight:8},{text:"Good forward motion",category:"progress",weight:7},{text:"Chipping away nicely",category:"progress",weight:7},{text:"Steady progress 👍",category:"progress",weight:8},{text:"Getting there",category:"progress",weight:7},{text:"Three in, good start",category:"progress",weight:8,contexts:{tasksCompleted:[3]}},{text:"Five done, nice going",category:"progress",weight:9,contexts:{tasksCompleted:[5]}},{text:"Seven in, good momentum",category:"progress",weight:8,contexts:{tasksCompleted:[7]}},{text:"Ten in the bag",category:"progress",weight:10,contexts:{tasksCompleted:[10]}},{text:"A dozen done, great going",category:"progress",weight:9,contexts:{tasksCompleted:[12]}},{text:"Twenty today, big day",category:"progress",weight:10,contexts:{tasksCompleted:[20]}}],jN=[{text:"Nice one 🙌",category:"celebration",weight:7},{text:"There it is",category:"celebration",weight:7},{text:"That felt good, right?",category:"celebration",weight:6},{text:"Good work",category:"celebration",weight:7},{text:"That's the one",category:"celebration",weight:6},{text:"Well handled",category:"celebration",weight:6},{text:"Three down, nice run",category:"celebration",weight:8,contexts:{tasksCompleted:[3]}},{text:"Five done, you're rolling 🙌",category:"celebration",weight:9,contexts:{tasksCompleted:[5]}},{text:"Ten today, that's a solid day",category:"celebration",weight:10,contexts:{tasksCompleted:[10]}},{text:"Fifteen done. Great day.",category:"celebration",weight:10,contexts:{tasksCompleted:[15]}},{text:"Twenty today 🔥 that's huge",category:"celebration",weight:10,contexts:{tasksCompleted:[20]}}],NN=[{text:"List's looking lighter",category:"productivity",weight:7},{text:"Matrix is clearing up nicely",category:"productivity",weight:7},{text:"Making good space",category:"productivity",weight:7},{text:"Nice dent in the backlog",category:"productivity",weight:6},{text:"Future you says thanks",category:"productivity",weight:6},{text:"Less on your plate now",category:"productivity",weight:7},{text:"Things are moving today",category:"productivity",weight:7}],SN=[...wN,...vN,...kN,...jN,...NN],Ra=new Set,Ia={},CN=1e3*60*30,Ph=e=>{const n=Date.now();for(const l in Ia)n-Ia[l]>CN&&(delete Ia[l],Ra.delete(l));const a=SN.filter(l=>!(Ra.has(l.text)||l.contexts&&(l.contexts.isRecurring!==void 0&&l.contexts.isRecurring!==e.isRecurring||l.contexts.isFirstOfDay!==void 0&&l.contexts.isFirstOfDay!==e.isFirstOfDay||l.contexts.quadrant!==void 0&&l.contexts.quadrant!==e.quadrant||l.contexts.tasksCompleted!==void 0&&e.tasksCompletedToday!==void 0&&!l.contexts.tasksCompleted.includes(e.tasksCompletedToday))));if(a.length===0)return Ra.clear(),Ph(e);const r=a.reduce((l,d)=>l+d.weight,0);let o=Math.random()*r,c=null;for(const l of a)if(o-=l.weight,o<=0){c=l;break}if(!c&&a.length>0)c=a[0];else if(!c)return"Task completed!";return Ra.add(c.text),Ia[c.text]=n,c.text},Oh=1500,yo=6e3;let Vs=0;const TN=()=>{const t=new Date().toDateString();localStorage.getItem("last-reset-day")!==t&&(Vs=0,localStorage.setItem("last-reset-day",t))},$h={lastToastTime:0,minInterval:800,canShowToast(){const e=Date.now();return e-this.lastToastTime>this.minInterval?(this.lastToastTime=e,!0):!1}},_N=(e=!1,t=!1,n="DO",a,r)=>{const o=r?{cancel:{label:"Follow up",onClick:r},classNames:{cancelButton:ch}}:{cancel:void 0,classNames:void 0};if(nt()){if(!a&&!r)return;xt("task-completion"),Z.success("Completed",{description:void 0,id:"task-completion",duration:Jc,className:"has-undo",style:{"--toast-dur":`${Jc}ms`},action:a?{label:"Undo",onClick:a}:void 0,...o});return}if(!$h.canShowToast())return;TN(),Vs++;const c=Ph({isRecurring:e,isFirstOfDay:Vs===1,quadrant:n,tasksCompletedToday:Vs}),l=e?"Back on your schedule":Vs>=4?`${Vs} done today`:void 0;Z.success(c,a?{description:l,id:"task-completion",duration:yo,className:"has-undo",style:{"--toast-dur":`${yo}ms`},action:{label:"Undo",onClick:a},...o}:{description:l,id:"task-completion",duration:r?yo:Oh,className:"",style:{},action:void 0,...o})},EN=()=>{$h.canShowToast()&&Z.error("Couldn't complete that one",{description:"Your progress is safe. Give it another go.",duration:Oh,className:yN("error")})},Nd=(e,t)=>{e.setQueryData(["tasks"],n=>n&&n.filter(a=>a.id!==t))},wo=async(e,t)=>
32{await Promise.all([e.invalidateQueries({queryKey:["tasks"],refetchType:"active",exact:!1}),t?e.invalidateQueries({queryKey:["task",t],exact:!0}):Promise.resolve()])},Sd=async(e,t=100)=>{t>0&&await new Promise(a=>setTimeout(a,t));const n={cancelRefetch:!1};await Promise.all([e.invalidateQueries({queryKey:["statistics"],refetchType:"inactive",exact:!1},n),e.invalidateQueries({queryKey:["streak"]},n),e.invalidateQueries({queryKey:["achievements"]},n),e.invalidateQueries({queryKey:["matrix-minded-progress"]},n),e.invalidateQueries({queryKey:["focus-master-progress"]},n)])},DN=(e,t)=>{e.setQueryData(["tasks"],t)},vs=new Map,Ws=new Map,RN=(e,t)=>{vs.set(e,t),Ws.get(e)?.forEach(n=>n(t)),Ws.delete(e),window.setTimeout(()=>{vs.get(e)===t&&vs.delete(e)},6e4)},IT=(e,t=8e3)=>{if(vs.has(e)){const n=vs.get(e)??null;return vs.delete(e),Promise.resolve(n)}return new Promise(n=>{const a=o=>{window.clearTimeout(r),vs.delete(e),n(o)},r=window.setTimeout(()=>{Ws.set(e,(Ws.get(e)??[]).filter(o=>o!==a)),n(null)},t);Ws.set(e,[...Ws.get(e)??[],a])})},IN={completeTaskOptimistic:()=>({removed:!1,removedIds:[],rollback:()=>{}})},Fh=i.createContext(IN),MN=Fh.Provider,LN=()=>i.useContext(Fh),qh=({apiKey:e,onTaskUpdate:t,isFocusMode:n,onTaskComplete:a})=>{const{session:r}=we.useSessionContext(),o=at(),{completeTaskOptimistic:c}=LN(),l=i.useRef(new Set),{incrementCompletedTasks:d}=Wm(n),m=async(h,g="DO")=>{if(l.current.has(h))return!1;const b=new AbortController;l.current.add(h);const x=fN(n);let y={removed:!1,removedIds:[],rollback:()=>{}};try{if(!r?.user?.id)throw new Error("No authenticated user found");x||(y=c(h)),Nd(o,h);const w=new Ke(e),[k,N]=await Promise.all([w.getTask(h),w.closeTask(h)]);if(!N||b.signal.aborted)throw new Error("Failed to close task or request was aborted");const C=k.due?.isRecurring||!1,v=Ah(k.labels),j=mN(v),T=y.removedIds.length?y.removedIds:[h];for(const M of T)Bx(r.user.id,M);jd(h,v,C,k.labels||[],x);const _=x?await xN(r.user.id):null,I=await pN(r.user.id,r.user.email||void 0,h,j,C,k.labels||[],_,x,k.content);pe("task_completed",{quadrant:sa(v),focus:!!x}),a&&a(),d();const R=r.user.id;if(x)RN(h,C?null:()=>u(R,T,I,!0));else{const M=C?void 0:()=>{u(R,T,I)},P={id:h,title:k.content??"",projectId:k.project_id??k.projectId??null,sectionId:k.section_id??k.sectionId??null,completedAt:new Date},E=wk(h)?void 0:()=>Zo(P);_N(C,x,v,M,E)}return x?(w.getApi().getTasks().then(M=>{if(!b.signal.aborted){const P=M.map(E=>({id:E.id,title:E.content,content:E.content,description:E.description||"",project_id:E.projectId,parent_id:E.parentId??void 0,labels:E.labels||[],priority:E.priority,due:E.due?{date:E.due.date,datetime:E.due.datetime,timezone:E.due.timezone,isRecurring:E.due.isRecurring,string:E.due.string,lang:E.due.lang}:void 0}));DN(o,P)}}).catch(M=>{}),hN(h,C)):y.removed||(await wo(o),requestAnimationFrame(async()=>{b.signal.aborted||await t()})),jd(h,v,C,k.labels||[],x,!0),!x&&y.removed}catch{return b.signal.aborted||(y.rollback(),EN(),wo(o,h)),!1}finally{b.signal.aborted||(l.current.delete(h),Sd(o,0))}},u=async(h,g,b,x=!1)=>{const y="task-completion";x||Z.loading("Restoring task…",{id:y,action:void 0,cancel:void 0,classNames:void 0,className:"",style:{},description:void 0});try{const w=new Ke(e);for(const k of g)Hx(h,k),await w.reopenTask(k);b&&await gN(b),window.dispatchEvent(new CustomEvent("task-completion-undone",{detail:{taskIds:g}})),await wo(o),await t(),x||Z.success("Task restored",{id:y,duration:2e3})}catch(w){if(Z.error("Couldn't restore the task",{id:y,description:"It is still completed in Todoist."}),x)throw w}finally{Sd(o,0)}},f=i.useRef(m);return f.current=m,{handleCompleteTask:i.useCallback((h,g)=>f.current(h,g),[])}},AN=({apiKey:e,onTaskUpdate:t,isFocusMode:n,onTaskComplete:a})=>{const r=i.useRef(!1),o=i.useRef(0),c=500,l=i.useRef(!1),{handleCompleteTask:d}=qh({apiKey:e,onTaskUpdate:t,isFocusMode:n,onTaskComplete:a}),m=i.useCallback(()=>n?!0:typeof document<"u"?document.documentElement.classList.contains("task-focus-active"):!1,[n]);return{handleTaskComplete:i.useCallback(async f=>{try{r.current=!0;const p=m();p&&(l.current=!0);const h=await d(f),g=Date.now(),b=g-o.current;return p?(setTimeout(async()=>{r.current&&(r.current=!1,o.current=Date.now(),await t(),setTimeout(()=>{l.current=!1},200))},1200),Promise.resolve()):h?(r.current=!1,Promise.resolve()):(b>c?(o.current=g,r.current=!1,await t()):setTimeout(async()=>{r.current&&(r.current=!1,o.current=Date.now(),await t())},c-b),Promise.resolve())}catch(p){return Promise.reject(p)}},[d,m,t]),isModalInteractionInProgress:()=>l.current}};class PN{logHistory=new Map;enabled=!0;debugMode=!1;maxHistorySize=50;lastCleanupTime=Date.now();cleanupInterval=3e4;nextAllowedLog={};disableNonCriticalInProduction=!0;constructor(){this.debugMode=!1,typeof window<"u"&&setInterval(()=>this.pruneLogHistory(),this.cleanupInterval)}log(t,n={}){const{level:a="info",module:r="app",throttle:o=0}=n;if(a==="debug"&&!this.debugMode||this.disableNonCriticalInProduction&&a!=="error"||!this.enabled&&a!=="error")return;const c=`${a}:${r}:${t}`,l=Date.now();if(l-this.lastCleanupTime>this.cleanupInterval&&(this.pruneLogHistory(),this.lastCleanupTime=l),o>0){if(this.nextAllowedLog[c]&&l<this.nextAllowedLog[c]){const m=this.logHistory.get(c);m&&m.count++;return}this.nextAllowedLog[c]=l+o;const d=this.logHistory.get(c);if(d&&(d.count++,d.count>5)){const m=`(+${d.count-1} similar logs suppressed)`;this.writeToConsole(a,`${t} ${m}`,r),d.count=1,d.timestamp=l;return}}this.logHistory.set(c,{message:t,timestamp:l,count:1}),this.logHistory.size>this.maxHistorySize&&this.pruneLogHistory(),this.writeToConsole(a,t,r)}writeToConsole(t,n,a){}pruneLogHistory(){const t=Date.now(),n=18e5;for(const[a,r]of this.logHistory.entries())t-r.timestamp>n&&this.logHistory.delete(a);for(const a in this.nextAllowedLog)t>this.nextAllowedLog[a]&&delete this.nextAllowedLog[a]}setEnabled(t){this.enabled=t}setDebugMode(t){this.debugMode=t}clearHistory(){this.logHistory.clear(),this.nextAllowedLog={}}}const ua=new PN,Ma=(e,t,n)=>ua.log(e,{level:"debug",module:t,throttle:n}
32),ht=(e,t,n)=>ua.log(e,{level:"info",module:t,throttle:n}),Qs=(e,t,n)=>ua.log(e,{level:"warn",module:t,throttle:n}),ON=(e,t,n)=>ua.log(e,{level:"error",module:t,throttle:n}),$N=(e,t={})=>{const{logSlowRenders:n=!1,renderThreshold:a=16,enableDebug:r=!1,maxLogEntries:o=3,sampleRate:c=10}=t,l=i.useRef(0),d=i.useRef(performance.now()),m=i.useRef(performance.now()),u=i.useRef(0),f=i.useRef([]),p=i.useRef(null),h=3e4,g=i.useCallback(()=>!1,[r,n]),b=i.useCallback(()=>{f.current=[],p.current&&(Cv(p.current),p.current=null)},[]);return i.useEffect(()=>{const x=performance.now()-m.current;return g()&&x>a*5&&performance.now()-u.current>h&&(u.current=performance.now(),Qs(`${e} mounted in ${x.toFixed(1)}ms`,"performance",h)),()=>{g()&&l.current>30&&Qs(`${e} unmounted after ${l.current} renders`,"performance",h),b()}},[e,a,g,b]),i.useEffect(()=>{if(l.current++,(l.current%c===0||l.current<=2)&&g()){const y=performance.now(),w=y-d.current;w>a*5&&y-u.current>h&&(u.current=y,f.current.push({time:y,duration:w}),f.current.length>o&&f.current.shift(),Qs(`Slow render in ${e}: ${w.toFixed(1)}ms (render #${l.current})`,"performance",h))}d.current=performance.now()}),i.useEffect(()=>{!window.PerformanceObserver||g()},[e,g,b]),{renderCount:l.current,getLastRenderTime:()=>performance.now()-d.current,getLogEntries:()=>[...f.current]}},vo="fu-date",FN=({draft:e,onChange:t,onSubmit:n,inSheet:a=!1})=>{const[r,o]=i.useState(!1),c=i.useRef(null),l=g=>t({...e,...g}),d=g=>{g&&(l({date:g,chip:Mw(g)}),o(!1))},m=g=>{if(g.key!=="Enter"||g.shiftKey||g.nativeEvent.isComposing)return;const b=g.target;b.closest(`.${vo}`)||b.closest('[type="submit"]')||(g.preventDefault(),n())},u=e.chip===null,f=g=>S("fu-chip inline-flex items-center justify-center gap-1.5 whitespace-nowrap rounded-lg border font-medium transition-colors",a?"h-11 px-2.5 text-[14px]":"h-8 flex-auto px-2 text-[13px]",g?"border-primary/50 bg-primary/10 text-foreground":"border-border/70 text-muted-foreground hover:bg-muted/60 hover:text-foreground"),p=s.jsx(rn,{title:"Check back",value:e.date,onChange:d,setActivePopover:()=>o(!1),inSheet:a,minDate:_s(),clearable:!1}),h=s.jsxs("button",{type:"button",role:"radio","aria-checked":u,"aria-expanded":r,className:f(u),onClick:()=>o(g=>!g),children:[s.jsx(Zs,{className:"h-3.5 w-3.5 shrink-0","aria-hidden":!0}),u?Ee(e.date,"MMM d"):"Pick date"]});return s.jsxs("form",{ref:c,className:"fu-form space-y-3","aria-label":"Follow up",onKeyDown:m,onSubmit:g=>{g.preventDefault(),n()},children:[s.jsxs("div",{className:"space-y-1.5",children:[s.jsx("label",{htmlFor:"fu-title",className:"text-[12px] font-medium text-muted-foreground",children:"Title"}),s.jsx(Yn,{id:"fu-title",value:e.title,onChange:g=>l({title:g.target.value}),className:S(a?"h-11":"h-9"),autoComplete:"off"})]}),s.jsxs("div",{className:"space-y-1.5",children:[s.jsx("label",{htmlFor:"fu-waiting",className:"text-[12px] font-medium text-muted-foreground",children:"Waiting on"}),s.jsx(Yn,{id:"fu-waiting",value:e.waitingOn,onChange:g=>l({waitingOn:g.target.value}),placeholder:"Name (optional)",className:S(a?"h-11":"h-9"),autoComplete:"off"})]}),s.jsxs("div",{className:"space-y-1.5",children:[s.jsx("div",{id:"fu-when",className:"text-[12px] font-medium text-muted-foreground",children:"Check back"}),s.jsxs("div",{role:"radiogroup","aria-labelledby":"fu-when",className:S("fu-chips gap-1.5",a?"grid grid-cols-2":"flex"),children:[gc.map(g=>s.jsx("button",{type:"button",role:"radio","aria-checked":e.chip===g.id,"data-chip":g.id,className:f(e.chip===g.id),onClick:()=>{l({chip:g.id,date:xc(g.id)}),o(!1)},children:g.label},g.id)),a?h:s.jsxs(Nt,{open:r,onOpenChange:o,children:[s.jsx(St,{asChild:!0,children:h}),s.jsx(Ct,{className:S(vo,"w-auto p-0 rounded-xl shadow-xl border-border/40"),align:"end",side:"top",children:p})]})]}),a&&r&&s.jsx("div",{className:S(vo,"pt-1"),children:p}),s.jsxs("p",{className:"fu-due text-[12px] text-muted-foreground",children:["Due ",Ee(e.date,"EEE, MMM d")," · Delegate · @waiting"]})]}),s.jsx(W,{type:"submit",className:S("w-full font-semibold",a?"h-11":"h-9"),disabled:!e.title.trim(),children:"Add follow-up"})]})},Bs="follow-up",qN=e=>{const t=e;return!!t&&(t.tagName==="INPUT"||t.tagName==="TEXTAREA"||t.tagName==="SELECT"||t.isContentEditable)},zN=e=>{const t=Lw();return{title:Rw(e.title),waitingOn:"",chip:t,date:xc(t)}},UN=({apiKey:e,onTaskUpdate:t})=>
32{const n=Fe(),a=at(),{session:r}=we.useSessionContext(),[o,c]=i.useState(null),[l,d]=i.useState(null),m=!!o&&!!l,[u,f]=i.useState(null),p=i.useMemo(()=>({current:u}),[u]);Cc(p);const h=i.useCallback(()=>{c(null),d(null)},[]);i.useEffect(()=>{const y=k=>{const N=k.detail;N?.id&&(c(N),d(zN(N)))},w=k=>{if(k.key!=="f"&&k.key!=="F"||k.repeat||k.defaultPrevented||k.ctrlKey||k.metaKey||k.altKey||k.shiftKey||qN(k.target)||document.querySelector('[role="dialog"], [data-radix-popper-content-wrapper]'))return;const N=bk();N&&(k.preventDefault(),N.click())};return window.addEventListener(Xo,y),window.addEventListener("keydown",w),()=>{window.removeEventListener(Xo,y),window.removeEventListener("keydown",w)}},[]);const g=i.useCallback(async y=>{const w=a.getQueryData(["labels",e]);if(!(Array.isArray(w)&&w.some(k=>typeof k?.name=="string"&&Qt(k.name)===Rn)))try{const k=await y.addLabel({name:Rn});a.setQueryData(["labels",e],N=>Array.isArray(N)?[...N,k??{id:`new-${Rn}`,name:Rn}]:N)}catch{}},[e,a]),b=i.useCallback(async()=>{if(!o||!l||!l.title.trim())return;if(!e){Z.error("Connect Todoist to add tasks",{id:Bs});return}const y={source:o,draft:l};l.chip&&Aw(l.chip),h(),nt()||Z.loading(Be("Adding follow-up…"),{id:Bs,description:void 0,action:void 0});try{const w=new Ke(e);await g(w);const k=await w.createTask(Ow({...l,source:o}));pe("follow_up_created"),r?.user?.id&&k?.id&&setTimeout(()=>{B.from("task_creation_log").insert({user_id:r.user.id,task_id:k.id,quadrant:"delegate",created_at:new Date().toISOString()})},0),xt(Bs),Z.success(Be(`Follow-up set for ${$w(l.date)}`),{id:Bs,description:void 0,action:void 0}),ut(20),t().catch(N=>{})}catch{xt(Bs),Z.error(Be("Couldn't add the follow-up"),{id:Bs,description:"Nothing was added to Todoist.",action:{label:"Edit",onClick:()=>{c(y.source),d(y.draft)}}})}},[o,l,e,h,g,r,t]),x=l&&s.jsx(FN,{draft:l,onChange:d,onSubmit:()=>{b()},inSheet:n});return n?s.jsx(ca,{open:m,onOpenChange:y=>{y||h()},children:s.jsxs(bn,{ref:f,side:"bottom",onOpenAutoFocus:y=>{y.preventDefault(),y.target?.focus()},className:S("fu-sheet mx-sheet p-0 rounded-t-2xl border-t border-border/60","overflow-y-auto overscroll-contain","data-[state=open]:duration-200 data-[state=closed]:duration-150","[&>button]:hidden"),children:[s.jsx("div",{className:"fu-handle flex justify-center pt-2",children:s.jsx("span",{className:"h-1 w-10 rounded-full bg-muted-foreground/30","aria-hidden":!0})}),s.jsxs("div",{className:"fu-body px-5 pt-3 pb-[max(1rem,env(safe-area-inset-bottom))]",children:[s.jsx(Rs,{className:"text-[17px] font-semibold leading-snug",children:"Follow up"}),s.jsxs(qr,{className:"fu-desc mt-0.5 mb-3 truncate text-[13px] text-muted-foreground",children:["Done: ",o?.title]}),x]})]})}):s.jsxs(Zn,{open:m,onOpenChange:y=>{y||h()},children:[s.jsx(kr,{className:"fu-anchor","aria-hidden":!0}),s.jsx(ea,{children:s.jsxs(mn,{side:"top",align:"end",sideOffset:0,collisionPadding:16,className:"fu-pop z-50 w-[400px] max-w-[calc(100vw-32px)] rounded-xl border border-border/60 bg-popover p-4 text-popover-foreground shadow-xl outline-none data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:slide-in-from-bottom-2",onOpenAutoFocus:y=>{y.preventDefault(),y.currentTarget.querySelector("#fu-waiting")?.focus()},children:[s.jsxs("div",{className:"mb-3 min-w-0",children:[s.jsx("div",{className:"text-[15px] font-semibold leading-snug",children:"Follow up"}),s.jsxs("div",{className:"truncate text-[12px] text-muted-foreground",children:["Done: ",o?.title]})]}),x]})})]})},BN=Ps(()=>Ne(()=>import("./MobileTaskActionSheet-mqUgU2VK.js"),__vite__mapDeps([22,1,2,15,14,4,3])).then(e=>e.MobileTaskActionSheet),e=>e.open),zh=Ue.memo(({urgentImportant:e,important:t,urgent:n,neither:a,apiKey:r,onTaskUpdate:o,isFocusMode:c,onToggleFocusMode:l,quadrants:d,focusStartTime:m,isTaskFocus:u,focusedTaskId:f,onTaskFocus:p,onToggleTaskFocus:h,onExitTaskFocus:g,incrementCompletedTasks:b})=>{$N("MatrixGridContent",{logSlowRenders:!1,renderThreshold:20});const x=i.useMemo(()=>e.length+t.length+n.length+a.length,[e.length,t.length,n.length,a.length]),{handleTaskComplete:y}=AN({apiKey:r,onTaskUpdate:o,isFocusMode:c,onTaskComplete:b});i.useEffect(()=>{const M=P=>{const E=P.detail?.taskId;E&&y(E)};return window.addEventListener("task:complete",M),()=>window.removeEventListener("task:complete",M)},[y]),i.useEffect(()=>{const M=async P=>{const E=P.detail;if(!E?.taskId)return;if(!r){Z.error("Connect Todoist to reschedule tasks");return}if(E.isRecurring){Z.info("Recurring task, open in Todoist to reschedule");return}const D=E.when??"tomorrow",L=ba(`Snoozing to ${D}…`);try{const A=new Ke(r);A.setUseDirectApiFirst(!0);const H=D==="tomorrow"&&na(E.time)?` at ${rm(E.time)}`:"";await A.updateTask(E.taskId,{due_string:`${D}${H}`,...H?{due_lang:"en"}:{}}),pe("due_changed",{via:E.via??"swipe",kind:"date"}),Z.success(Be(`Snoozed to ${D}`),{id:L}),await o()}catch{Z.error(Be("Failed to snooze task"),{id:L})}};return window.addEventListener("task:snooze",M),()=>window.removeEventListener("task:snooze",M)},[r,o]),i.useEffect(()=>{const M=async P=>{const E=P.detail;if(!E?.taskId)return;if(!r){Z.error("Connect Todoist to set deadlines");return}const D=ba(E.date?"Setting deadline…":"Clearing deadline…");try{const L=new Ke(r);L.setUseDirectApiFirst(!0),await L.updateTask(E.taskId,{deadline_date:E.date??null}),Z.success(Be(E.date?"Deadline set":"Deadline cleared"),{id:D}),await o()}catch{Z.error(Be("Failed to update deadline"),{id:D})}};return window.addEventListener("task:set-deadline",M),()=>window.removeEventListener("task:set-deadline",M)},[r,o]),i.useEffect(()=>{const M=async P=>{const E=P.detail;if(!E?.taskId)return;if(!r){Z.error("Connect Todoist to reschedule tasks");return}if(E.isRecurring){Z.info("Recurring task, open in Todoist to reschedule");return}const D=E.date??null,L=ba(D?"Setting due date…":"Clearing due date…");try{const A=new Ke(r);A.setUseDirectApiFirst(!0),await A.updateTask(E.taskId,qx({date:D,time:E.time??null})),pe("due_changed",{via:E.via??"picker",kind:Fx({date:D,kind:E.kind})}),Z.success(Be(D?"Due date set":"Due date cleared"),{id:L}),await o()}catch{Z.error(Be("Failed to update due date"),{id:L})}};return window.addEventListener("task:set-due",M),()=>window.removeEventListener("task:set-due",M)},[r,o]),i.useEffect(()=>{const M=async P=>{const E=P.detail;if(!E?.taskId||!E.title)return;const D=()=>window.dispatchEvent(new CustomEvent("task:rename-failed",{detail:{taskId:E.taskId}}));if(!r){Z.error("Connect Todoist to rename tasks"),D();return}const L=`rename-${E.taskId}`;try{const A=new Ke(r);A.setUseDirectApiFirst(!0),await A.updateTask(E.taskId,{content:E.title}),Z.success(Be(E.undo?"Name restored":"Task renamed"),E.undo?{id:L,duration:2500,action:void 0,className:"",style:{}}:{id:L,duration:6e3,className:"has-undo",style:{"--toast-dur":"6000ms"},action:{label:"Undo",onClick:()=>window.dispatchEvent(new CustomEvent("task:rename",{detail:{taskId:E.taskId,title:E.previous,previous:E.title,undo:!0}}))}}),await o()}catch{Z.error(Be("Couldn't rename the task"),{id:L,description:"The old name is back."}),D()}};return window.addEventListener("task:rename",M),()=>window.removeEventListener("task:rename",M)},[r,o]),i.useEffect(()=>{const M=async P=>{const E=P.detail;if(!E?.content||!E.quadrant)return;if(!r){Z.error("Connect Todoist to add tasks");return}const D=ba("Adding task…");try{await new Ke(r).createTask({content:E.content,labels:[E.quadrant]}),pe("task_added",{quadrant:sa(E.quadrant),via:"row"}),Z.success(Be("Task added"),{id:D}),await o()}catch{Z.error(Be("Failed to add task"),{id:D})}};return window.addEventListener("task:create-in-quadrant",M),()=>window.removeEventListener("task:create-in-quadrant",M)},[r,o]);const[w,k]=i.useState(null);i.useEffect(()=>{const M=P=>{const E=P.detail;E?.task&&(k({task:E.task,quadrant:E.quadrant}),pe("task_opened",{surface:"sheet"}))};return window.addEventListener("task:peek",M),()=>window.removeEventListener("task:peek",M)},[]);const N=i.useCallback(M=>y(M),[y]),C=uN({totalTasks:x,isFocusMode:c,isTaskFocus:u,quadrants:d,focusedTaskId:f,focusStartTime:m,urgentImportant:e,important:t,urgent:n,neither:a,apiKey:r,onToggleFocusMode:l,onExitTaskFocus:g}),v=i.useMemo(()=>({urgentImportant:e,important:t,urgent:n,neither:a}),[e,t,n,a]),j=la(),T=jv(),_=Fe(),I=i.useCallback(()=>{const M=uh({do:e,schedule:t,delegate:n,backlog:a},j),P=Hk(M,{focusOneId:T,openTab:_?Pe.getState().quadrant:null});h({...v,startId:P})},[h,v,e,t,n,a,j,T,_]),R=i.useCallback(M=>{p(M)},[p]);return s.jsx(Ls,{children:s.jsx(Fu,{features:qu,children:s.jsxs(zu,{reducedMotion:"always",children:[s.jsx(dN,{children:s.jsx(Lh,{...C,onTaskUpdate:o,onToggleTaskFocus:I,onTaskFocus:R,onCompleteTask:y,onTaskComplete:b,onExitTaskFocus:g})}),s.jsx(BN,{open:!!w,task:w?.task??null,quadrant:w?.quadrant,apiKey:r,onTaskUpdate:o,onComplete:N,onClose:()=>k(null)}),s.jsx(UN,{apiKey:r,onTaskUpdate:o})]})})})});zh.displayName="MatrixGridContent";function HN({onRecategorize:e}){const{selectedTasks:t,clearSelection:n}=$r(),[a,r]=i.useState(!1),o=async c=>{if(t.size!==0){r(!0);try{await e(Array.from(t),c),n()}catch{}finally{r(!1)}}};return t.size===0?null:s.jsxs("div",{className:"fixed bottom-6 left-1/2 transform -translate-x-1/2 z-50 bg-card/95 border rounded-lg shadow-lg backdrop-blur-sm p-3 flex gap-2 animate-in slide-in-from-bottom",children:[s.jsxs("div",{className:"px-3 py-2 text-sm font-medium whitespace-nowrap",children:[t.size," selected"]}),s.jsx(W,{variant:"secondary",size:"sm",onClick:()=>o("do"),disabled:a,className:"bg-red-500/10 text-red-700 hover:bg-red-500/20 dark:text-red-400",children:"Do First"}),s.jsx(W,{variant:"secondary",size:"sm",onClick:()=>o("schedule"),disabled:a,className:"bg-blue-500/10 text-blue-700 hover:bg-blue-500/20 dark:text-blue-400",children:"Schedule"}),s.jsx(W,{variant:"secondary",size:"sm",onClick:()=>o("delegate"),disabled:a,className:"bg-orange-500/10 text-orange-700 hover:bg-orange-500/20 dark:text-orange-400",children:"Delegate"}),s.jsx(W,{variant:"secondary",size:"sm",onClick:()=>o("backlog"),disabled:a,className:"bg-slate-500/10 text-slate-700 hover:bg-slate-500/20 dark:text-slate-400",children:"Backlog"}),s.jsx(W,{variant:"ghost",size:"sm",onClick:n,disabled:a,children:"Clear"})]})}const Cd="Focus is open in another tab",Td="Keep focusing there, or move it here. Your timer and progress carry over.",VN=()=>
32{const e=l0(),t=Fe(),n=!!e,a=l=>{l||ao(!1)},r=s.jsx(W,{className:S(t&&"h-11 w-full"),onClick:()=>ao(!0),"data-qa":"focus-move-here",children:"Move Focus here"},"move"),o=s.jsx(W,{variant:"ghost",className:S(t&&"h-11 w-full"),onClick:()=>ao(!1),"data-qa":"focus-keep-there",children:"Keep it there"},"keep"),c=s.jsx("div",{className:S("fe-actions flex gap-2",t?"flex-col":"flex-row justify-end"),children:t?[r,o]:[o,r]});return t?s.jsx(ca,{open:n,onOpenChange:a,children:s.jsxs(bn,{side:"bottom","data-qa":"focus-elsewhere",onOpenAutoFocus:l=>{l.preventDefault(),l.target?.focus()},className:S("fe-sheet mx-sheet p-0 rounded-t-2xl border-t border-border/60","data-[state=open]:duration-200 data-[state=closed]:duration-150","[&>button]:hidden"),children:[s.jsx("div",{className:"flex justify-center pt-2",children:s.jsx("span",{className:"h-1 w-10 rounded-full bg-muted-foreground/30","aria-hidden":!0})}),s.jsxs("div",{className:"px-5 pt-3 pb-[max(1rem,env(safe-area-inset-bottom))]",children:[s.jsx(Rs,{className:"text-[17px] font-semibold leading-snug",children:Cd}),s.jsx(qr,{className:"mt-1 mb-4 text-[14px] leading-relaxed text-muted-foreground",children:Td}),c]})]})}):s.jsx(Xa,{open:n,onOpenChange:a,children:s.jsxs(Za,{"data-qa":"focus-elsewhere",overlayClassName:"bg-black/40",onOpenAutoFocus:l=>{l.preventDefault(),l.currentTarget?.querySelector('[data-qa="focus-move-here"]')?.focus()},className:"fe-dialog sm:max-w-[400px] gap-0 p-6 [&>button]:hidden",children:[s.jsx(er,{className:"text-[17px] font-semibold leading-snug",children:Cd}),s.jsx(tr,{className:"mt-2 mb-5 text-sm leading-relaxed text-muted-foreground",children:Td}),c]})})},_d=6e3,KN={do:"Do First",schedule:"Schedule",delegate:"Delegate",backlog:"Backlog"};async function YN(e,t,n){let a=0,r=0;const o=async()=>{for(;a<e.length;){const c=a++;try{await n(e[c])}catch{r++}}};return await Promise.all(Array.from({length:Math.min(t,e.length)},o)),r}const Uh=Ue.memo(({urgentImportant:e,important:t,urgent:n,neither:a,apiKey:r,onTaskUpdate:o,isFocusMode:c,onToggleFocusMode:l})=>{const{quadrants:d}=Jy(e,t,n,a),{focusStartTime:m,incrementCompletedTasks:u,isTaskFocus:f,focusedTaskId:p,handleTaskFocus:h,handleToggleTaskFocus:g,handleExitTaskFocus:b,prepareQuadrantTasks:x,openTaskFocus:y}=Y0({isFocusMode:c});i.useMemo(()=>x(e,t,n,a),[x,e,t,n,a]);const w=i.useMemo(()=>{const v=new Map;return[...e,...t,...n,...a].forEach(j=>{v.set(String(j.id),j)}),v},[e,t,n,a]),k=Ue.useRef(w);k.current=w;const N=i.useCallback(async(v,j,T)=>{if(!v.length)return;const _=T??Object.fromEntries(v.map(H=>[H,um(w.get(String(H))?.labels)]).filter(H=>!!H[1])),I=j.toLowerCase(),R=KN[I]??j,M=v.length,P=`bulk-move-${I}`;nt()?xt(P):Z.loading(`Moving ${M} ${M===1?"task":"tasks"} to ${R}…`,{id:P,action:void 0,className:"",style:{}});const E=new Ke(r),D=await YN(v,6,async H=>{const K=w.get(String(H)),X=Array.isArray(K?.labels)?K.labels:(await E.getTask(H)).labels??[];await E.updateTaskLabels(H,Io(X,I))});await o();const L=M-D,A=sa(I);if(L>0&&A!=="unsorted"&&!(T&&Object.keys(T).length===0)&&pe("task_categorized",{quadrant:A,via:"move",sheet:"matrix",n:L}),D===0){const H={};v.forEach(ce=>{const oe=_[ce];oe&&oe!==I&&(H[oe]??=[]).push(ce)});const K=Object.keys(H).length>0,X=`${L} ${L===1?"task":"tasks"} moved to ${R}`;Z.success(Be(X),K?{id:P,duration:_d,className:"has-undo",style:{"--toast-dur":`${_d}ms`},action:{label:"Undo",onClick:()=>{Object.entries(H).forEach(([ce,oe])=>{C.current?.(oe,ce,{})})}}}:{id:P,action:void 0,className:"",style:{}})}else{const H=L>0?`Moved ${L} of ${M} to ${R} · ${D} failed`:`Couldn't move ${M===1?"task":"tasks"} to ${R}`;Z.error(Be(H),{id:P,action:void 0,className:"",style:{}})}},[r,o,w]),C=Ue.useRef();return C.current=N,i.useEffect(()=>{const v=T=>{const _=T.detail;!_?.ids?.length||!_.to||N(_.ids,_.to,_.from)},j=T=>{const _=T.detail,I=_?.taskId;if(!I)return;if(!k.current.has(String(I))&&_?.task&&String(_.task.id)===String(I)){Va.getState().pin(_.task),y(I);return}if(k.current.size===0){fc();return}y(I)};return window.addEventListener("matrix:move-tasks",v),window.addEventListener("task:open-focus",j),()=>{window.removeEventListener("matrix:move-tasks",v),window.removeEventListener("task:open-focus",j)}},[N,y]),s.jsxs(Qw,{children:[s.jsx(zh,{urgentImportant:e,important:t,urgent:n,neither:a,apiKey:r,onTaskUpdate:o,isFocusMode:c,onToggleFocusMode:l,quadrants:d,focusStartTime:m,isTask
32Focus:f,focusedTaskId:p,onTaskFocus:h,onToggleTaskFocus:g,onExitTaskFocus:b,incrementCompletedTasks:u}),s.jsx(HN,{onRecategorize:N}),s.jsx(VN,{})]})});Uh.displayName="MatrixGrid";const ko=({width:e="100%",height:t="1.25rem",rounded:n="0.5rem",shimmer:a=!0,staggerDelay:r=null,animate:o="shimmer",intensity:c="normal",withShadow:l=!1,className:d,style:m,...u})=>{const p=(typeof window<"u"?window.matchMedia("(prefers-reduced-motion: reduce)").matches:!1)?"pulse":o,g={subtle:{opacity:"opacity-40 hover:opacity-60",shadow:"shadow-sm"},normal:{opacity:"opacity-50 hover:opacity-70",shadow:"shadow"},strong:{opacity:"opacity-60 hover:opacity-80",shadow:"shadow-md"}}[c],b=p==="none"?"":p==="breathe"?"skeleton-breathe":p==="pulse"?"animate-skeleton":"skeleton-shimmer",x=r?`skeleton-stagger-${r}`:"";return s.jsx("div",{className:S("relative overflow-hidden bg-muted",b,x,l&&g.shadow,g.opacity,"transition-all duration-300 ease-in-out","hardware-accelerated will-change-transform",d),style:{width:e,height:t,borderRadius:n,...m},"aria-busy":"true","aria-hidden":"true",...u})},Ed=()=>s.jsx("div",{className:"w-16 h-16 mx-auto flex items-center justify-center relative",children:s.jsx(te.div,{className:"rounded-full p-3 bg-primary/10 shadow-lg",initial:{rotate:0,opacity:.88,scale:.93},animate:{rotate:360,opacity:[.88,1,.88],scale:[.97,1.04,.97]},transition:{repeat:1/0,repeatType:"loop",ease:"linear",duration:2.5},style:{display:"flex",alignItems:"center",justifyContent:"center",willChange:"transform, opacity"},children:s.jsx(cg,{size:36,strokeWidth:2.4,className:"text-primary animate-[pulse_2s_ease-in-out_infinite]"})})}),WN=()=>s.jsx("div",{className:"flex items-center justify-center h-[400px] bg-background/80 backdrop-blur-[2px] transition-all duration-500",children:s.jsxs("div",{className:"text-center space-y-6 w-full max-w-xs mx-auto",children:[s.jsxs(i.Suspense,{fallback:s.jsx("div",{className:"mt-8",children:s.jsx(Ed,{})}),children:[s.jsx(ko,{width:"70%",height:"2rem",className:"mx-auto mb-1",animate:"breathe",withShadow:!0}),s.jsx(ko,{width:"90%",height:"1.2rem",className:"mx-auto",staggerDelay:1,animate:"shimmer"}),s.jsx(ko,{width:"60%",height:"1.2rem",className:"mx-auto",staggerDelay:2,animate:"shimmer"}),s.jsx("div",{className:"mt-4 transform transition-transform hover:scale-105 duration-300",children:s.jsx(Ed,{})})]}),s.jsx(te.p,{className:"text-muted-foreground text-xs transition-all animate-skeleton skeleton-breathe flex items-center gap-1 justify-center",style:{willChange:"opacity, transform",animationDelay:"0.3s"},initial:{opacity:.7},animate:{opacity:[.7,1,.7]},transition:{repeat:1/0,duration:3,ease:[.4,0,.6,1]},children:"Loading your tasks…"})]})}),Dd="categorize-nudge-day",GN=({hasAnyTasks:e,unlabeledTasks:t,onCreateTask:n,children:a})=>{const[r,o]=i.useState(!1),{nudgeAllowed:c,quiet:l}=Ot();i.useEffect(()=>{if(!c||l){o(!1);return}if(e&&t.length>0){try{if(localStorage.getItem(Dd)===Qa(new Date))return}catch{}const u=window.setTimeout(()=>{o(!0);try{localStorage.setItem(Dd,Qa(new Date))}catch{}},800);return()=>window.clearTimeout(u)}o(!1)},[e,t.length,c,l]);const d=()=>o(!1),m=s.jsx(te.div,{initial:{opacity:0,x:20,scale:.9},animate:{opacity:1,x:0,scale:1},exit:{opacity:0,x:20,scale:.9},className:"fixed bottom-6 right-6 z-[70] max-md:bottom-[calc(env(safe-area-inset-bottom,0px)+148px)] max-md:right-4",children:s.jsxs("div",{className:"bg-background/95 backdrop-blur-md border border-primary/20 rounded-lg shadow-xl p-4 max-w-xs",children:[s.jsxs("div",{className:"flex items-start justify-between mb-2",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("div",{className:"w-5 h-5 rounded-full bg-primary/20 flex items-center justify-center",children:s.jsx(Ts,{className:"w-3 h-3 text-primary"})}),s.jsx("h3",{className:"font-medium text-sm",children:"Organize your tasks"})]}),s.jsx(W,{variant:"ghost",size:"icon",className:"h-4 w-4 text-muted-foreground hover:text-foreground -mt-1 -mr-1",onClick:d,"aria-label":"Dismiss",children:s.jsx(Ie,{className:"w-3 h-3"})})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"text-xs text-foreground",children:["You have ",s.jsx("span",{className:"font-semibold text-primary",children:t.length})," ",t.length===1?"task":"tasks"," waiting to be organized."]}),n&&s.jsx(W,{onClick:()=>{n(),d()},size:"sm",className:"w-full text-xs h-7 mt-3",children:"Open Categorize"})]})]})});return s.jsxs(s.Fragment,{children:[a,r&&typeof document<"u"&&Ii.createPortal(m,document.body)]})},Bh=Ue.memo(({isLoading:e,tasks:t,selectedLabels:n,apiKey:a,onTaskUpdate:r,isFocusMode:o,onToggleFocusMode:c,unlabeledTasks:l,onCreateTask:d})=>
32{const{nestedChildIds:m,displayRootIdById:u}=oa(),{nestSubtasks:f}=ds(),{revealedIds:p}=Cf(),{urgentImportant:h,important:g,urgent:b,neither:x,hasAnyTasks:y}=i.useMemo(()=>{let w=fm(t,n);if(n.length===1&&["today","overdue","today,overdue"].includes(n[0])&&(w=Bi({tasks:w,dateFilter:n[0],selectedLabel:n[0]})),p.size){const j=new Set(w.map(_=>_.id)),T=t.filter(_=>p.has(_.id)&&!j.has(_.id));T.length&&(w=[...w,...T])}const N=new Set(w.map(j=>j.id)),C=j=>f&&m.has(j.id)&&N.has(u.get(j.id)),v=j=>w.filter(T=>(T.labels||[]).some(_=>Rr(_)===j)&&!C(T));return{urgentImportant:v("do"),important:v("schedule"),urgent:v("delegate"),neither:v("backlog"),hasAnyTasks:t.length>0}},[t,n,f,m,u,p]);return e&&t.length===0?s.jsx(WN,{}):s.jsx(GN,{hasAnyTasks:y,unlabeledTasks:l,onCreateTask:d,children:s.jsx(Uh,{urgentImportant:h,important:g,urgent:b,neither:x,apiKey:a,onTaskUpdate:r,isFocusMode:o,onToggleFocusMode:c})})});Bh.displayName="MatrixContent";const QN=()=>{try{return window.matchMedia("(hover: hover) and (pointer: fine)").matches}catch{return!0}},JN=({allowed:e=!0})=>{const[t,n]=ct("quick-category-info-dismissals",0),[a,r]=i.useState(t<2),[o]=i.useState(QN),c=()=>{n(l=>l+1),r(!1)};return!a||!e||!o?null:s.jsxs("div",{className:S("relative flex items-center gap-2 p-2 mb-2 text-xs","bg-soft-purple dark:bg-card/50 rounded-lg border border-primary/20","text-muted-foreground shadow-sm"),children:[s.jsx(lg,{className:"h-4 w-4 flex-shrink-0 text-primary"}),s.jsxs("p",{className:"flex-grow text-xs pr-6",children:["Use ",s.jsx("kbd",{className:"mx-1 px-1 py-0.5 text-[0.6rem] rounded-md bg-slate-200 dark:bg-muted",children:"Ctrl"})," (or ",s.jsx("kbd",{className:"mx-1 px-1 py-0.5 text-[0.6rem] rounded-md bg-slate-200 dark:bg-muted",children:"⌘"}),") + Click to select and move tasks"]}),s.jsx(W,{variant:"ghost",size:"icon",className:"absolute top-0 right-0 h-6 w-6",onClick:c,children:s.jsx(Ie,{className:"h-4 w-4"})})]})},XN=({isLoading:e,tasks:t,selectedLabels:n,apiKey:a,onTaskUpdate:r,isFocusMode:o,onToggleFocusMode:c,unlabeledTasks:l,onCreateTask:d})=>{const{allowCtrlBanner:m}=Ot();return s.jsxs(_e.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:.2},children:[s.jsx(JN,{allowed:m}),s.jsx(Bh,{isLoading:e,tasks:t,selectedLabels:n,apiKey:a,onTaskUpdate:r,isFocusMode:o,onToggleFocusMode:c,unlabeledTasks:l,onCreateTask:d})]})},ZN=["[email protected]"],Hh=e=>!!e&&ZN.includes(e.toLowerCase().trim()),Ve={planName:{yearly:"Yearly",lifetime:"Lifetime",monthly:"Monthly"},planTag:{yearly:"Yearly",lifetime:"Pay once",monthly:"Flexible"},planLine(e){return e==="lifetime"?`One-time ${lt.lifetime.price}, yours forever.`:e==="monthly"?`${lt.monthly.price} a month. Cancel anytime.`:lt.yearly.price?`${lt.yearly.price} a year. Cancel anytime.`:"Billed yearly, price shown at checkout. Cancel anytime."},priceMain(e){return e==="lifetime"?{amount:lt.lifetime.price??"",unit:"once"}:e==="monthly"?{amount:lt.monthly.price??"",unit:"/ month"}:{amount:lt.yearly.price??"Yearly",unit:lt.yearly.price?"/ year":""}},priceSub(e){return e==="lifetime"?"Pay once, yours forever":e==="monthly"?"Cancel anytime":lt.yearly.price?"Billed yearly, cancel anytime":"Price shown at checkout"},cta:"Keep your matrix",landingCta:{yearly:"Start yearly",lifetime:"Get lifetime access",monthly:"Start monthly"},gateTitle:"Your free trial has ended",gateBody:"Your tasks are safe in Todoist. Pick a plan to keep sorting them in your matrix.",planEndedTitle:"Your plan has ended",planEndedBody:"Your tasks are safe in Todoist. Pick a plan to keep sorting them in your matrix.",trialEndingTitle:e=>e<=0?"Your free trial ends today":`Your free trial ends in ${e} ${e===1?"day":"days"}`,socialProof:"Used by people who plan their week in Todoist.",trust:"Secure checkout on Gumroad. We never see your card details.",trustShort:"Secure checkout on Gumroad",reassurance(e){return e==="lifetime"?["Instant activation","No subscription"]:["Instant activation","Cancel anytime"]},features:["Your Todoist tasks sorted into the four quadrants","Auto-prioritize, Daily review and Focus mode","Statistics and streaks","Every future update"],featuresShort:["Todoist tasks in four quadrants","Auto-prioritize and Daily review","Focus mode, stats and streaks","Every future update"],trialPlansTitle(e,t){return typeof e!="number"?"Your free trial":t?Ve.trialEndingTitle(e):`Free trial · ${e} ${e===1?"day":"days"} left`},trialLine(e,t){return typeof e!="number"?"Free trial active":t?Ve.trialEndingTitle(e):e===1?"1 day left in your trial":`${e} days left in your trial`},minimize:"Minimize",licenseLink:"Already bought? Enter license key",licenseQuestion:"Already bought?",licenseAction:"Enter license key",seePlans:"See plans",notNow:"Not now",opening:"Opening secure checkout on Gumroad…",waitingTitle:"Complete your payment in the Gumroad tab",waitingBody:"This page will unlock automatically.",returnTitle:"Welcome back",returnBody:"If you completed your payment, this page unlocks automatically.",closedTitle:"Did you finish paying?",closedBody:"No worries. If you finished paying, we'll unlock your account as soon as Gumroad confirms.",reopen:"Open Gumroad again",paid:"I've completed payment",cancel:"Cancel checkout",activatingTitle:"Payment received, activating…",checkingTitle:"Checking your payment…",activatingBody:"This usually takes a few seconds.",activatedTitle:"You're all set",activatedBody:"Everything is unlocked.",continue:"Continue",slowTitle:"Gumroad is taking a little longer",slowBody:"Your payment is safe. You can keep waiting, or unlock now with the license key from your Gumroad receipt email.",keepWaiting:"Keep waiting",enterKey:"Enter license key",help:"Need help?",steps:["Pay on Gumroad","Confirming","Unlocked"],switchReminderLabel:"One last step",manage:"Manage"},MT=e=>e==="plan"?{title:Ve.planEndedTitle,body:Ve.planEndedBody}:{title:Ve.gateTitle,body:Ve.gateBody},eS="product, status, period_end, subscription_id, created_at",tS=3,sS=864e5,Js=e=>{if(!e)return null;const t=new Date(e);return Number.isNaN(t.getTime())?null:t},Vh=e=>e.product==="monthly"||e.product==="yearly",hi=e=>{const t=typeof e=="string"?e.trim():"";return t?`https://app.gumroad.com/subscriptions/${encodeURIComponent(t).replace(/%3D/g,"=")}/manage`:rc},nS=(e,t=new Date)=>{if(!Vh(e)||e.status!=="active"&&e.status!=="failed")return!1;const n=Js(e.period_end);
32return!n||n.getTime()+tS*sS>t.getTime()};function Kh(e,t=new Date){if(!e?.length)return null;const n=e.filter(a=>nS(a,t));return n.length?[...n].sort((a,r)=>(r.created_at??"").localeCompare(a.created_at??""))[0]:null}function LT(e,t=new Date){if(e==null)return{manageUrl:rc};const n=Kh(e,t);return n?{manageUrl:hi(n.subscription_id)}:null}const aS=["active","cancelled","failed"];function rS(e){let t=null;for(const n of e){if(!Vh(n)||!aS.includes(n.status))continue;if(!t){t=n;continue}const a=Js(t.period_end)?.getTime()??1/0,r=Js(n.period_end)?.getTime()??1/0;(r>a||r===a&&t.status!=="active"&&n.status==="active")&&(t=n)}return t}function oS(e,t=new Date){const n=e.purchases??[];if(e.billingPlan==="lifetime"){const a=Kh(n,t);return{kind:"lifetime",oldMembership:a?{manageUrl:hi(a.subscription_id),periodEnd:Js(a.period_end)}:null}}if(e.billingPlan==="membership"){const a=rS(n);if(a)return{kind:"membership",product:a.product==="yearly"?"yearly":"monthly",status:a.status,periodEnd:Js(a.period_end),manageUrl:hi(a.subscription_id)};const r=(e.profile?.gumroad_subscription_status??"").toLowerCase(),o=r==="cancelled"?"cancelled":r==="failed"?"failed":"active";return{kind:"membership",product:"monthly",status:o,periodEnd:o==="cancelled"?Js(e.profile?.subscription_expiry_date):null,manageUrl:rc}}return{kind:"none"}}const iS=(e,t="en-US")=>e.toLocaleDateString(t,{month:"long",day:"numeric",year:"numeric"}),Yh={title:"Plan",membershipName:e=>e==="yearly"?"Yearly plan":`Monthly plan · ${lt.monthly.price} / month`,statusLine(e,t){const n=e.periodEnd?iS(e.periodEnd,t):null;return e.status==="cancelled"?n?`Cancelled · access until ${n}`:"Cancelled · access until the end of the paid period":e.status==="failed"?"Payment failed · update your card to keep access":n?`Renews on ${n} · Active`:"Active"},switchCta:`Switch to Lifetime · ${lt.lifetime.price} once`,switchLine:"Pay once, keep it forever. No more monthly charges.",manage:"Update card or cancel",manageCancelled:"Manage on Gumroad",footnote:"Billing is handled securely by Gumroad.",lifetimeName:"Lifetime · yours forever",receipts:"Receipts in your Gumroad library",oldMonthlyTitle:"Your old monthly plan is still active",oldMonthlyBody:"Gumroad keeps charging it until it's cancelled. Cancel it so you're not charged again.",oldMonthlyCta:"Cancel monthly on Gumroad",oldMonthlyLag:"Already cancelled? It can take a little while to show here.",switchedTitle:"Lifetime is active",switchedBody:"Cancel your monthly plan on Gumroad so you're not charged again.",rowCancelOld:"Cancel old monthly"};function cS(e,t){if(!e)return null;const n=Fm(e)??"";return e==="lifetime"?t?.kind==="lifetime"&&t.oldMembership?{text:`${n} · ${Yh.rowCancelOld}`,attention:!0}:{text:n,attention:!1}:{text:`${n} · ${Ve.manage}`,attention:!1}}const Wh=e=>{const{session:t}=we.useSessionContext(),n=t?.user?.id??null,a=it({queryKey:["billing-plan-details",n],enabled:!!n&&!!e,staleTime:6e4,refetchOnWindowFocus:!0,queryFn:async()=>{const[o,c]=await Promise.all([B.from("purchases").select(eS).eq("user_id",n),B.from("profiles").select("gumroad_subscription_status, subscription_expiry_date").eq("id",n).maybeSingle()]);if(o.error)throw o.error;return{purchases:o.data??[],profile:c.data??null}}});return{state:i.useMemo(()=>e?oS({billingPlan:e,purchases:a.data?.purchases??null,profile:a.data?.profile??null}):null,[e,a.data]),isLoading:a.isLoading,isError:a.isError}},lS=i.lazy(()=>Ne(()=>import("./PlanPanel-DyQyrbCZ.js"),__vite__mapDeps([23,1,2,24,12,3,4])).then(e=>({default:e.PlanPanel}))),Gh=e=>{const[t,n]=i.useState(e.open);return i.useEffect(()=>{e.open&&n(!0)},[e.open]),!t&&!e.open?null:s.jsx(i.Suspense,{fallback:null,children:s.jsx(lS,{...e})})},Qh=i.memo(({email:e,paymentStatus:t,billingPlan:n,daysLeft:a,onReconnectTodoist:r,isReconnecting:o=!1})=>{const[c]=ct("simulate-expired",!1),l=Xt(),d=Hh(e),[m,u]=i.useState(!1),[f,p]=i.useState(!1),[h,g]=i.useState(!1),{state:b}=Wh(n),x=cS(n,b);e&&e.split("@")[0];const y=()=>c?s.jsx(te.div,{initial:{scale:.9,opacity:0},animate:{scale:1,opacity:1},transition:{duration:.3},className:"relative",children:s.jsxs(Ds,{variant:"destructive",className:"shadow-lg hover:shadow-red-200/50 transition-all duration-300 animate-pulse group",children:[s.jsx(xr,{className:"w-4 h-4 mr-1.5 group-hover:animate-bounce"}),"Simulation Mode"]})}):n||t==="paid"||t==="lifetime"||t!=="expired"?null:s.jsx(te.div,{initial:{scale:.9,opacity:0}
32,animate:{scale:1,opacity:1},transition:{duration:.3},children:s.jsxs(Ds,{variant:"destructive",className:"shadow-lg hover:shadow-red-200/50 transition-all duration-300 animate-pulse group",children:[s.jsx(Wt,{className:"w-4 h-4 mr-1.5 group-hover:animate-bounce"}),"Trial expired"]})});return s.jsxs(te.div,{initial:{opacity:0,y:-10},animate:{opacity:1,y:0},transition:{duration:.5},className:S("flex flex-col items-end space-y-2.5 p-3 min-w-0 max-w-full","rounded-lg transition-all duration-300","hover:bg-accent/5 hover:backdrop-blur-sm","border border-transparent hover:border-accent/10"),children:[s.jsxs(hn,{children:[s.jsx(pn,{asChild:!0,children:s.jsxs(te.div,{id:"account-menu-btn",className:S("flex items-center gap-3 px-4 py-2 rounded-xl min-w-0 max-w-full","bg-gradient-to-r from-background via-accent/5 to-background","backdrop-blur-sm","border border-accent/20","shadow-md hover:shadow-lg","transition-all duration-300","hover:bg-accent/10 hover:border-accent/30","group cursor-pointer"),whileHover:{scale:1.03},whileTap:{scale:.98},initial:{x:-20,opacity:0},animate:{x:0,opacity:1},transition:{type:"spring",stiffness:400,damping:15,delay:.1},children:[s.jsxs("div",{className:"relative",children:[s.jsx(te.div,{className:S("absolute inset-0 rounded-full","bg-gradient-to-r from-primary/20 to-primary/30","blur-md"),animate:{scale:[1,1.15,1],opacity:[.7,.9,.7]},transition:{duration:3,repeat:1/0,repeatType:"reverse"}}),s.jsx("div",{className:S("relative flex items-center justify-center","w-8 h-8 rounded-full","bg-gradient-to-br from-primary/30 to-primary/10","border border-primary/20","group-hover:from-primary/40 group-hover:to-primary/20","transition-all duration-300"),children:s.jsx(dg,{className:S("w-4 h-4","text-primary","group-hover:scale-110","transition-all duration-300")})})]}),s.jsxs("div",{className:"flex flex-col min-w-0",children:[s.jsx("span",{className:S("text-xs font-medium text-muted-foreground","group-hover:text-foreground","transition-colors duration-300"),children:"Signed in as"}),s.jsx("span",{className:S("text-sm font-semibold","bg-gradient-to-r from-primary/90 via-primary/80 to-primary/70","text-transparent bg-clip-text","group-hover:from-primary group-hover:via-primary/90 group-hover:to-primary/80","transition-all duration-300","truncate max-w-[160px] sm:max-w-none"),children:e})]}),s.jsx(mt,{className:"w-4 h-4 opacity-50 group-hover:opacity-70 transition-opacity ml-1"})]})}),s.jsxs(As,{align:"end",className:"w-[240px]",children:[x&&s.jsxs(s.Fragment,{children:[s.jsxs(dt,{onSelect:()=>g(!0),className:"flex items-center gap-2","data-testid":"account-plan","data-attention":x.attention||void 0,children:[x.attention&&s.jsx("span",{className:"h-2 w-2 shrink-0 rounded-full bg-amber-500","aria-hidden":!0}),s.jsx("span",{className:S(x.attention?"text-foreground":"text-muted-foreground"),children:x.text}),s.jsx(pt,{className:"ml-auto h-3.5 w-3.5 text-muted-foreground","aria-hidden":!0})]}),s.jsx(is,{})]}),s.jsxs(dt,{onClick:r,disabled:o,className:"flex items-center gap-2",children:[s.jsx(_i,{className:S("w-4 h-4",o&&"animate-spin")}),o?"Reconnecting…":"Reconnect Todoist"]}),d&&s.jsxs(dt,{onClick:()=>l("/admin"),className:"flex items-center gap-2",children:[s.jsx(Du,{className:"w-4 h-4"}),"Admin panel"]}),s.jsxs(dt,{onSelect:()=>window.dispatchEvent(new Event("tour:open")),className:"flex items-center gap-2",children:[s.jsx(Ru,{className:"w-4 h-4"}),"Product tour"]}),s.jsxs(dt,{onSelect:()=>p(!0),className:"flex items-center gap-2",children:[s.jsx(Ai,{className:"w-4 h-4"}),"Send feedback"]}),s.jsx(is,{}),s.jsxs(dt,{onSelect:()=>u(!0),className:"flex items-center gap-2 text-destructive focus:bg-destructive/10 focus:text-destructive",children:[s.jsx(Is,{className:"w-4 h-4"}),"Delete account"]})]})]}),y(),s.jsx(pf,{open:f,onOpenChange:p}),n&&s.jsx(Gh,{open:h,onOpenChange:g,state:b}),s.jsx(ff,{open:m,onOpenChange:u,email:e})]})});Qh.displayName="UserInfo";const dS=i.lazy(()=>Ne(()=>import("./PlanPicker-C8gzQIYq.js"),__vite__mapDeps([25,1,2,24,12,3,4])).then(e=>({default:e.PlanPicker}))),Jh=e=>s.jsx(i.Suspense,{fallback:s.jsx("div",{className:"h-40 w-full","aria-hidden":!0}),children:s.jsx(dS,{...e})}),uS=i.lazy(()=>Ne(()=>import("./TrialPlansPanel-p_lTinxu.js"),__vite__mapDeps([26,1,2,25,24,12,3,4])).then(e=>({default:e.TrialPlansPanel}))),Xh=e=>s.jsx(i.Suspense,{fallback:s.jsx("div",{className:e.layout==="phone"?"h-64 w-full":"h-[5.75rem] w-full","aria-hidden":!0}),children:s.jsx(uS,{...e})}),Zh=({onClick:e,size:t="default",className:n,id:a,...r})=>{const o=t==="large";return s.jsxs("button",{type:"button",id:a,onClick:e,"data-testid":r["data-testid"]??"enter-license-link",className:S("group inline-flex max-w-full items-center justify-center gap-1.5 rounded-full text-muted-foreground transition-colors","hover:bg-primary/5 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",o?"min-h-11 px-3 text-[15px]":"min-h-7 px-2.5 text-[13px]",n),children:[s.jsx(ug,{className:S("shrink-0 text-primary",o?"h-4 w-4":"h-3.5 w-3.5"),"aria-hidden":!0}),s.jsxs("span",{className:"min-w-0 text-balance text-left",children:[Ve.licenseQuestion," ",s.jsx("span",{className:"font-medium text-primary underline-offset-4 group-hover:underline",children:Ve.licenseAction})]})]})};function ep(e,t){const{session:n}=we.useSessionContext(),a=n?.user?.id??null,{plansHold:r}=Ot(),[o,c]=i.useState(()=>ml(a)),[l,d]=i.useState(!1);i.useEffect(()=>{c(ml(a))},[a]);const{view:m,reopen:u}=$y({paymentStatus:e,daysLeft:t,onboarding:r!=="none"&&!l,prefs:o});i.useEffect(()=>{if(!u)return;const h=ul(o,!0);Xr(a,h),c(h)},[u,o,a]);const f=i.useCallback(()=>{d(!1),c(h=>{const g=Fy(h,t);return Xr(a,g),g})},[t,a]),p=i.useCallback(()=>{d(!0),c(h=>{const g=ul(h);return Xr(a,g),g})},[a]);return{view:r==="deciding"&&!l&&m!=="hidden"?"hidden":m,nudgeDue:Pr(e,t),onboarding:r==="onboarding"&&!l,minimize:f,expand:p}}const mS=({paymentStatus:e,daysLeft:t,plansOnly:n=!1})=>{const[a,r]=i.useState(!1),[o,c]=i.useState(Py),{compactPricing:l}=Ot(),d=ep(e,t),m=$m(e),u=m&&!n&&e==="trial",f=u&&d.view==="expanded",p=u&&d.view==="minimized",h=m&&(n||e==="expired"&&!o&&!l);return s.jsxs("div",{className:"flex flex-col items-center gap-1 sm:gap-4",children:[!n&&s.jsx("h1",{className:S("max-sm:hidden text-2xl sm:text-3xl font-bold tracking-tight text-foreground mb-0",f?"sm:mb-0":"sm:mb-2"),children:"Eisenhower Matrix"}),f&&s.jsx(Xh,{layout:"desktop",daysLeft:t,nudgeDue:d.nudgeDue,onMinimize:d.minimize,onEnterLicense:()=>r(!0)}),p&&s.jsxs("div",{className:"flex max-w-full flex-wrap items-center justify-center gap-x-3 gap-y-1.5 rounded-full border border-border/70 bg-card py-1 pl-4 pr-1 shadow-sm","data-testid":"pricing-compact",children:[s.jsx("span",{className:"text-sm text-muted-foreground",children:Ve.trialLine(t,d.nudgeDue)}),s.jsx(W,{type:"button",size:"sm",className:"h-8 rounded-full px-4 font-semibold","data-testid":"pricing-see-plans","aria-expanded":!1,onClick:d.expand,children:Ve.seePlans})]}),p&&s.jsx(Zh,{className:"-mt-0.5 sm:-mt-2.5","data-testid":"header-license-link",onClick:()=>r(!0)}),h&&s.jsxs("div",{className:"relative flex w-full max-w-md flex-col items-center gap-2 rounded-xl border bg-card p-4 shadow-sm","data-testid":"pricing-card",children:[!n&&s.jsx("button",{type:"button","aria-label":Ve.notNow,title:Ve.n
32otNow,"data-testid":"pricing-dismiss",className:"absolute right-2 top-2 rounded-md p-1 text-muted-foreground hover:bg-muted hover:text-foreground",onClick:()=>{Oy(),c(!0)},children:s.jsx(Ie,{className:"h-4 w-4","aria-hidden":!0})}),!n&&s.jsxs("div",{className:"px-6 text-center",children:[s.jsx("p",{className:"text-sm font-semibold text-foreground",children:Ve.gateTitle}),s.jsx("p",{className:"text-xs text-muted-foreground",children:Ve.socialProof})]}),s.jsx(Jh,{size:n?"large":"default",onEnterLicense:()=>r(!0)})]}),s.jsx(hf,{isOpen:a,onClose:()=>r(!1)})]})},tp=()=>{const[e,t]=i.useState(()=>typeof window<"u"&&localStorage.getItem("theme")||"dark");return i.useEffect(()=>{const a=window.document.documentElement,r=a.classList.contains(e==="dark"?"light":"dark");r&&a.classList.add("theme-switching"),a.classList.remove("light","dark"),a.classList.add(e),r&&(a.offsetHeight,requestAnimationFrame(()=>requestAnimationFrame(()=>a.classList.remove("theme-switching")))),localStorage.setItem("theme",e);const o=document.querySelector('meta[name="theme-color"]'),c=getComputedStyle(a).getPropertyValue("--background").trim();o&&c&&o.setAttribute("content",`hsl(${c.replace(/\s+/g,", ")})`)},[e]),{theme:e,toggleTheme:()=>{t(a=>a==="light"?"dark":"light")}}},fS=()=>{const{theme:e,toggleTheme:t}=tp();return s.jsx(W,{variant:"ghost",size:"icon",onClick:t,className:"h-8 w-8",title:e==="dark"?"Switch to light mode":"Switch to dark mode",children:e==="dark"?s.jsx(mg,{className:"h-4 w-4"}):s.jsx(Iu,{className:"h-4 w-4"})})},hS=()=>{const[e,t]=i.useState(!1),[n,a]=i.useState(!1),[r,o]=ct("has-seen-categorize-tooltip",!1),[c,l]=i.useState(!1),[d,m]=i.useState(null),{session:u}=we.useSessionContext(),[f,p]=i.useState(!1);return i.useEffect(()=>{(async()=>{if(u?.user?.id)try{const{data:g,error:b}=await B.from("profiles").select("todoist_user_name, email, todoist_access_token, created_at").eq("id",u.user.id).single();if(!b&&g){g.todoist_user_name?m(g.todoist_user_name.split(" ")[0]):g.email&&m(g.email.split("@")[0].replace(/[._-]/g," "));const x=!!g.todoist_access_token;p(x);const y=g.created_at&&Gg(new Date,new Date(g.created_at))<=10;x&&!r&&y&&(l(!0),setTimeout(()=>{l(!1),o(!0)},12e3))}}catch{}})()},[u,r,o]),{showPing:e,setShowPing:t,showTooltip:n,setShowTooltip:a,hasSeenCategorizeTooltip:r,setHasSeenCategorizeTooltip:o,showNewUserTooltip:c,setShowNewUserTooltip:l,userName:d,hasTodoistConnection:f}},pS=({unlabeledTasksCount:e,showPing:t,showNewUserTooltip:n,onCategorize:a,setShowNewUserTooltip:r,setHasSeenCategorizeTooltip:o})=>{const c=()=>{n&&(r(!1),o(!0)),a()};return s.jsxs(Ht,{children:[s.jsx(Vt,{asChild:!0,children:s.jsxs(W,{id:"categorize-btn",variant:"ghost",size:"sm",onClick:c,className:"h-8 relative bg-gradient-to-r from-[#8a73eb] to-[#9b87f5] hover:from-[#7E69AB] hover:to-[#8a73eb] text-white transition-all duration-300 max-sm:h-8 max-sm:w-8 max-sm:p-0 max-sm:rounded-full max-sm:justify-center",children:[s.jsx(Mu,{className:"h-4 w-4 sm:mr-1.5"}),s.jsx("span",{className:"max-sm:sr-only",children:"Categorize"}),s.jsx(Ds,{variant:"secondary",className:`ml-1.5 max-sm:ml-0 max-sm:absolute max-sm:-top-1 max-sm:-right-1 max-sm:h-4 max-sm:min-w-4 max-sm:px-1 max-sm:py-0 max-sm:text-[10px] max-sm:leading-none max-sm:flex max-sm:items-center max-sm:justify-center max-sm:rounded-full max-sm:shadow-sm ${t?"bg-white text-[#9b87f5] animate-pulse":"bg-white/90 text-[#9b87f5]"}`,children:e}),t&&s.jsx("span",{className:"absolute -top-1 -right-1 h-2 w-2 bg-white rounded-full animate-ping max-sm:hidden"})]})}),s.jsx(At,{side:"bottom",align:"center",sideOffset:5,className:"z-[100] max-w-[280px]",children:s.jsx("p",{children:t?"🎯 Time to organize your tasks!":"✨ Organize your tasks in the Eisenhower Matrix"})})]})},gS=({onClick:e})=>s.jsxs(Ht,{children:[s.jsx(Vt,{asChild:!0,children:s.jsxs(W,{id:"recategorize-btn",variant:"ghost",size:"sm",onClick:e,className:"h-8 hover:bg-accent",children:[s.jsx(Lu,{className:"h-4 w-4 sm:mr-1.5"}),s.jsx("span",{className:"max-sm:sr-only",children:"Recategorize"})]})}),s.jsx(At,{side:"bottom",align:"center",sideOffset:5,className:"z-[60] max-w-[220px]",children:s.jsx("p",{children:"Review and update your existing task categorizations"})})]}),xS=({onLogout:e,onRecategorize:t,onBulkRecategorize:n,unlabeledTasksCount:a})=>{const{showPing:r,showTooltip:o,hasSeenCategorizeTooltip:c,setHasSeenCategorizeTooltip:l,showNewUserTooltip:d,setShowNewUserTooltip:m,userName:u}=hS();return s.jsx(Ls,{delayDuration:100,children:s.jsxs(s.Fragment,{children:[a>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"h-4 w-px bg-border mx-1 max-sm:hidden"}),s.jsx(pS,{unlabeledTasksCount:a,showPing:r,showNewUserTooltip:d,showTooltip:o,userName:u,onCategorize:t,hasSeenCategorizeTooltip:c,setShowNewUserTooltip:m,setHasSeenCategorizeTooltip:l})]}),s.jsx("div",{className:"h-4 w-px bg-border mx-1 max-sm:hidden"}),s.jsx(gS,{onClick:n}),s.jsx("div",{className:"h-4 w-px bg-border mx-1 max-sm:hidden"}),s.jsxs(W,{variant:"ghost",size:"sm",onClick:e,className:"h-8",title:"Log out",children:[s.jsx(Au,{className:"h-4 w-4 sm:mr-1.5"}),s.jsx("span",{className:"max-sm:sr-only",children:"Log out"})]})]})})},bS=({showConfetti:e,onToggleConfetti:t,showTags:n,onToggleTags:a})=>{const[r,o]=i.useState(!1);return s.jsxs(s.Fragment,{children:[s.jsx(W,{variant:"ghost",size:"sm",onClick:()=>o(!0),title:"Settings",className:"flex items-center gap-2 w-9 h-9 p-0 justify-center rounded-full hover:bg-accent/80",children:s.jsx(Pu,{className:"h-4 w-4"})}),s.jsx(mf,{isOpen:r,onClose:()=>o(!1),showConfetti:e,onToggleConfetti:t,showTags:n,onToggleTags:a})]})},yS={compact:{icon:hg,label:"Compact"},default:{icon:fg,label:"Default"},comfortable:{icon:bu,label:"Comfortable"}},wS=()=>{const{density:e,cycleDensity:t}=Zt(),{icon:n,label:a}=yS[e];return s.jsxs(Ht,{children:[s.jsx(Vt,{asChild:!0,children:s.jsx(W,{variant:"ghost",size:"icon",onClick:t,className:S("h-8 w-8 rounded-lg transition-colors duration-150","text-muted-foreground hover:text-foreground"),"aria-label":`Display density: ${a}`,children:s.jsx(n,{className:"h-4 w-4"})})}),s.jsx(At,{side:"bottom",children:s.jsxs("p",{className:"text-xs",children:["Density: ",a]})})]})},vS=({onLogout:e,onRecategorize:t,onBulkRecategorize:n,unlabeledTasksCount:a,isFocusMode:r=!1,onToggleFocusMode:o,showConfetti:c,onToggleConfetti:l,showTags:d,onToggleTags:m})=>s.jsx("div",{className:"flex justify-center items-center mt-4 max-sm:mt-1 max-w-full",children:s.jsxs("div",{className:"flex flex-wrap items-center justify-center gap-2 p-2 bg-card/60 rounded-lg border shadow-sm max-w-full max-sm:flex-nowrap max-sm:gap-1 max-sm:p-0 max-sm:border-0 max-sm:bg-transparent max-sm:shadow-none",children:[s.jsx(fS,{}),s.jsx(wS,{}),s.jsx("div",{className:"h-4 w-px bg-border mx-1 max-sm:hidden"}),s.jsx(bS,{showConfetti:c,onToggleConfetti:l,showTags:d,onToggleTags:m}),s.jsx(xS,{onLogout:e,onRecategorize:t,onBulkRecategorize:n,unlabeledTasksCount:a})]})}),Cn=100,Rd={DO_FIRST:10,SCHEDULE:6,DELEGATE:4,BACKLOG:2},kS=5,jS=["login","app_open"],NS=e=>{const t=Math.max(0,Math.floor(e||0)),n=Math.floor(t/Cn)+1,a=t%Cn;
32return{level:n,intoLevel:a,toNext:Cn-a,pointsPerLevel:Cn,levelProgressPct:Math.min(100,a/Cn*100)}},SS=async(e,t)=>{const{count:n}=await t(CS(e));return n??0},CS=e=>B.from("task_completions").select("*",{count:"exact",head:!0}).eq("user_id",e),TS=()=>{const{session:e}=we.useSessionContext(),t=e?.user?.id,n=at(),{data:a}=Vi(),r=a?.totalPoints??0,o=it({queryKey:["level-activity-points",t],enabled:!!t,staleTime:6e4,queryFn:async()=>{const f=t,p=Object.keys(Rd),[h,g]=await Promise.all([Promise.all(p.map(y=>SS(f,w=>w.eq("quadrant",y)))),(async()=>{const{count:y}=await B.from("user_activities").select("*",{count:"exact",head:!0}).eq("user_id",f).in("activity_type",jS);return y??0})()]),b=p.reduce((y,w,k)=>y+h[k]*Rd[w],0),x=g*kS;return{tasks:b,logins:x}}});i.useEffect(()=>{if(!t)return;const f=()=>n.invalidateQueries({queryKey:["level-activity-points",t]});return window.addEventListener("task-completion-finished",f),window.addEventListener("focus-task-completed",f),window.addEventListener("streak-refresh",f),()=>{window.removeEventListener("task-completion-finished",f),window.removeEventListener("focus-task-completed",f),window.removeEventListener("streak-refresh",f)}},[n,t]);const c=o.data?.tasks??0,l=o.data?.logins??0,d=r+c+l,m={achievements:r,tasks:c,logins:l,total:d},u=NS(d);return{total:d,breakdown:m,...u,isLoading:o.isLoading}},_S=e=>it({queryKey:["matrix-minded-progress",e],queryFn:async()=>{if(!e)return 0;try{const{data:t,error:n}=await B.rpc("get_unique_quadrants_count",{p_user_id:e});if(n)throw n;return t}catch{return 0}},enabled:!!e}),ES=e=>it({queryKey:["focus-master-progress",e],enabled:!!e,staleTime:6e4,queryFn:async()=>{const{count:t,error:n}=await B.from("task_completions").select("id",{count:"exact",head:!0}).eq("user_id",e).or("focus_session_id.not.is.null,completion_metadata->>focus_mode.eq.true");return n?0:t??0}}),sp=e=>(e.achievement_type||"").toLowerCase().replace(/[\s-]/g,"_"),DS=e=>sp(e)==="matrix_minded"||e.achievement_name?.trim().toLowerCase()==="matrix minded",RS=e=>sp(e)==="focus_master"||e.achievement_name?.trim().toLowerCase()==="focus master",IS=(e,t)=>e.map(n=>t.matrixMinded!=null&&DS(n)?{...n,progress:Math.max(n.progress??0,t.matrixMinded)}:t.focusMaster!=null&&RS(n)?{...n,progress:Math.max(n.progress??0,t.focusMaster)}:n),MS=({iconName:e})=>{switch(e){case"clock":return s.jsx(Kt,{className:"w-5 h-5"});case"timer":return s.jsx(bg,{className:"w-5 h-5"});case"badge":return s.jsx(xg,{className:"w-5 h-5"});case"check":return s.jsx(Oe,{className:"w-5 h-5"});case"calendar":return s.jsx(Ss,{className:"w-5 h-5"});case"star":return s.jsx(Yt,{className:"w-5 h-5"});case"grid":return s.jsx(gg,{className:"w-5 h-5"});case"target":return s.jsx(Ts,{className:"w-5 h-5"});default:return s.jsx(pg,{className:"w-5 h-5"})}},np=()=>{const{session:e}=we.useSessionContext(),{data:t}=Hi(),{data:n}=Vi(),{total:a,level:r}=TS(),{data:o}=_S(e?.user?.id),{data:c}=ES(e?.user?.id),l=t?.current??0,d=t?.activeToday??!1,m=Tb(l),{totalCount:u,nextUp:f,justEarned:p}=i.useMemo(()=>{const g=IS(n?.achievements??[],{matrixMinded:typeof o=="number"?o:void 0,focusMaster:typeof c=="number"?c:void 0}),b=g.filter(Es),x=g.filter(w=>!Es(w)&&!w.is_hidden&&w.target>0).map(w=>({...w,ratio:Lb(w)})).sort((w,k)=>k.ratio-w.ratio).slice(0,3),y=b.filter(w=>w.earned_at).sort((w,k)=>new Date(k.earned_at).getTime()-new Date(w.earned_at).getTime()).slice(0,2);return{earnedCount:b.length,totalCount:g.length,nextUp:x,justEarned:y}},[n,o,c]),h=d?"text-orange-500":l>0?"text-amber-500/70":"text-muted-foreground";return{streak:t,current:l,activeToday:d,nextMilestone:m,totalCount:u,nextUp:f,justEarned:p,level:r,points:a,flameTone:h}},ap=()=>{const e=Xt(),{streak:t,current:n,activeToday:a,nextMilestone:r,totalCount:o,nextUp:c,justEarned:l,level:d,points:m,flameTone:u}=np();return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"p-4 bg-gradient-to-br from-orange-500/10 to-transparent",children:[s.jsxs("div",{className:"flex items-end justify-between",children:[s.jsxs("div",{className:"flex items-end gap-2",children:[s.jsx(qn,{className:S("h-7 w-7",u),strokeWidth:2.2}),s.jsxs("div",{className:"leading-none",children:[s.jsx("div",{className:"text-2xl font-bold tabular-nums",children:n}),s.jsx("div",{className:"text-xs text-muted-foreground mt-1",children:"day streak"})]})]}),s.jsxs("div",{className:"text-right text-xs text-muted-foreground",children:["Best",s.jsx("div",{className:"text-sm font-semibold text-foreground tabular-nums",children:t?.longest??0})]})]}),s.jsx("div",{className:"mt-3 flex items-center justify-between",children:(t?.last7??[]).map((f,p)=>s.jsxs("div",{className:"flex flex-col items-center gap-1",children:[s.jsx("span",{className:S("h-6 w-6 rounded-full flex items-center justify-center text-[10px] font-semibold",f.active?"bg-
32orange-500 text-white":"bg-muted text-muted-foreground/60",f.isToday&&!f.active&&"ring-2 ring-orange-500/40"),children:f.active?"✓":""}),s.jsx("span",{className:"text-[10px] text-muted-foreground",children:f.label})]},p))}),s.jsx("p",{className:S("mt-3 text-xs font-medium",a?"text-emerald-600 dark:text-emerald-400":"text-amber-600 dark:text-amber-400"),children:a?"You're back today, streak secured.":n>0?`Drop in today to keep your ${n}-day streak alive.`:"Show up today to start a streak."}),r&&s.jsxs("div",{className:"mt-2.5",children:[s.jsxs("div",{className:"flex items-center justify-between text-[10px] text-muted-foreground mb-1",children:[s.jsx("span",{children:"Next milestone"}),s.jsxs("span",{className:"tabular-nums",children:[n,"/",r," days"]})]}),s.jsx("div",{className:"h-1.5 rounded-full bg-muted overflow-hidden",children:s.jsx("div",{className:"h-full rounded-full bg-gradient-to-r from-amber-400 to-orange-500 transition-[width] duration-500",style:{width:`${Math.min(100,n/r*100)}%`}})})]})]}),s.jsxs("div",{className:"p-4 border-t border-border/60",children:[s.jsxs("div",{className:"flex items-center justify-between mb-2.5",children:[s.jsxs("span",{className:"text-xs font-semibold flex items-center gap-1.5",children:[s.jsx(_o,{className:"h-3.5 w-3.5 text-violet-500"}),"Next achievements"]}),s.jsxs("span",{className:"text-[11px] text-muted-foreground tabular-nums",children:["Lv ",d," · ",m," pts"]})]}),c.length>0?s.jsx("div",{className:"space-y-2.5",children:c.map(f=>{const p=Math.round(f.ratio*100),h=Math.max(0,f.target-(f.progress||0));return s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("span",{className:"flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-lg bg-violet-500/10 text-violet-600 dark:text-violet-400",children:s.jsx(MS,{iconName:f.icon_name})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-xs font-medium truncate",children:f.achievement_name}),s.jsxs("span",{className:"text-[10px] text-muted-foreground tabular-nums flex-shrink-0",children:[h," to go"]})]}),s.jsx("div",{className:"mt-1 h-1.5 rounded-full bg-muted overflow-hidden",children:s.jsx("div",{className:"h-full rounded-full bg-gradient-to-r from-violet-500 to-fuchsia-500 transition-[width] duration-500",style:{width:`${p}%`}})})]})]},f.id)})}):s.jsx("p",{className:"text-xs text-muted-foreground py-1",children:o>0?"Everything unlocked, legend. 🎉":"Complete tasks to start unlocking achievements."}),l.length>0&&s.jsxs("div",{className:"mt-3 pt-3 border-t border-border/40",children:[s.jsx("span",{className:"text-[11px] text-muted-foreground",children:"Recently earned"}),s.jsx("div",{className:"mt-1.5 flex flex-wrap gap-1.5",children:l.map(f=>s.jsxs("span",{className:"inline-flex items-center gap-1 text-[11px] font-medium px-2 py-0.5 rounded-full bg-emerald-500/10 text-emerald-600 dark:text-emerald-400",children:[s.jsx(Zd,{className:"h-3 w-3"}),f.achievement_name]},f.id))})]}),s.jsxs(W,{variant:"ghost",size:"sm",onClick:()=>e("/achievements"),className:"mt-3 w-full justify-between h-8 text-xs",children:["View all achievements",s.jsx(pt,{className:"h-3.5 w-3.5"})]})]})]})},LS=()=>{const{current:e,activeToday:t,flameTone:n}=np();return s.jsxs(Nt,{children:[s.jsx(St,{asChild:!0,children:s.jsxs(W,{variant:"outline",size:"sm",className:S("h-9 gap-2 rounded-full pl-2.5 pr-3 border-border/70","transition-colors",t&&"border-orange-500/40 bg-orange-500/[0.06]"),"aria-label":`Streak: ${e} days. Open progress`,children:[s.jsxs("span",{className:"relative flex items-center justify-center",children:[s.jsx(qn,{className:S("h-4 w-4",n),strokeWidth:2.4}),t&&s.jsx(te.span,{"aria-hidden":!0,className:"absolute inset-0 rounded-full",animate:{opacity:[.5,0,.5],scale:[1,1.7,1]},transition:{duration:2.2,repeat:1/0,ease:"easeInOut"},style:{boxShadow:"0 0 6px 2px rgba(249,115,22,0.45)"}})]}),s.jsx("span",{className:"text-sm font-semibold tabular-nums",children:e}),s.jsxs("span",{className:"hidden sm:inline text-xs text-muted-foreground",children:["day",e===1?"":"s"]})]})}),s.jsx(Ct,{align:"end",className:"w-[340px] p-0 overflow-hidden rounded-2xl",children:s.jsx(ap,{})})]})},AS=({email:e,onLogout:t,onRecategorize:n,onBulkRecategorize:a,onOpenDailyReview:r,unlabeledTasksCount:o,paymentStatus:c,billingPlan:l,daysLeft:d})=>{const{showTags:m,toggleShowTags:u}=ds(),[f,p]=ct("show-confetti",!0),h=Xt(),{session:g}=we.useSessionContext(),{reconnectTodoist:b,isReconnecting:x}=Gi(),y=()=>{Ne(()=>import("./Statistics-C6kF8i-x.js"),__vite__mapDeps([27,1,2,3,4,17,28,29])).catch(()=>{})};return s.jsx("header",{className:"py-2 sm:py-6 mb-2 sm:mb-8 border-b bg-background/95 backdrop-blur-sm",children:s.jsxs("div",{className:"flex w-full flex-col gap-2 sm:gap-4",children:[s.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[s.jsx(Qh,{email:e,paymentStatus:c,billingPlan:l,daysLeft:d,onReconnectTodoist:b,isReconnecting:x}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[g?.user?.id&&s.jsx(LS,{}),r&&s.jsxs(W,{id:"daily-review-btn",variant:"outline",size:"sm",onClick:r,className:"flex items-center gap-2 bg-card",children:[s.jsx(Ou,{className:"w-4 h-4 text-amber-500"}),s.jsx("span",{className:"hidden sm:inline",children:"Daily review"})]}),s.jsxs(W,{id:"stats-button",variant:"outline",size:"sm",onMouseEnter:y,onTouchStart:y,onClick:()=>h("/statistics"),className:"flex items-center gap-2 bg-card",children:[s.jsx($u,{className:"w-4 h-4 text-muted-foreground"}),"Statistics"]})]})]}),s.jsx(mS,{paymentStatus:c,daysLeft:d}),s.jsx(vS,{onLogout:t,onRecategorize:n,onBulkRecategorize:a,unlabeledTasksCount:o,showConfetti:f,onToggleConfetti:()=>p(!f),showTags:m,onToggleTags:()=>u(!m)})]})})},PS=({email:e,onLogout:t,onRecategorize:n,onBulkRecategorize:a,onOpenDailyReview:r,unlabeledTasksCount:o,paymentStatus:c,billingPlan:l,daysLeft:d})=>s.jsx(AS,{email:e,onLogout:t,onRecategorize:n,onBulkRecategorize:a,onOpenDailyReview:r,unlabeledTasksCount:o,paymentStatus:c,billingPlan:l,daysLeft:d}),OS=()=>{const{session:e}=we.useSessionContext(),{toast:t}=He();return{handleRecategorize:c=>{c(!0),e?.user&&Pt(e.user.id,e.user.email,"task_move",{action:"recategorize_start"})},handleBulkRecategorize:c=>{c(!0),e?.user&&Pt(e.user.id,e.user.email,"task_move",{action:"bulk_recategorize_start"})},handleFocusModeToggle:(c,l)=>{e?.user&&Pt(e.user.id,e.user.email,c?"focus_session_end":"focus_session_start"),l()},handleOAuthSuccess:async c=>{try{if(e?.user){const{error:l}=await B.from("profiles").update({todoist_access_token:c}).eq("id",e.user.id);if(l)throw l;t({title:"Todoist connected",description:"Your tasks are syncing."}),window.location.reload()}}catch{t({title:"Error",description:"Failed to save Todoist connection",variant:"destructive"})}}}},Id=new WeakMap,$S=e=>{if(!e?.length)return[];const t=Id.get(e);if(t)return t;const n=Object.values(tm).map(o=>o.toLowerCase()),a=new Set(n),r=e.filter(o=>o.labels?.length?o.labels.some(c=>a.has(c.toLowerCase())):!1);return Id.set(e,r),r},FS=`${$i}/functions/v1/todoist-proxy`,qS=e=>`/api/v1/tasks/${encodeURIComponent(e)}`;function zS(e){return async(t,{keepalive:n})=>{const{apiKey:a,accessToken:r}=e();if(!a)throw new Vn("Todoist is not connected",401);if(!n){await new Ke(a).deleteTask(t.id);return}const o=await fetch(FS,{method:"POST",keepalive:!0,headers:{"Content-Type":"application/json",apikey:Ga,Authorization:`Bearer ${r||Ga}`},body:JSON.stringify({path:qS(t.id),method:"DELETE",apiToken:a})});if(!o.ok){let c=o.status;try{const l=await o.json();typeof l?.status=="number"&&(c=l.status)}catch{}throw new Vn(`Todoist delete failed (${c})`,c)}}}const US=e=>!!e?.due?.isRecurring,BS=(e,t)=>lm(e,t);function HS(e,t){const n=BS(t,e.id),a=US(e);
32return{ids:[e.id,...n],subtaskCount:n.length,recurring:a,confirm:a?"recurring":n.length>0?"subtasks":"none"}}const Md=e=>`${e} ${e===1?"subtask":"subtasks"}`;function VS(e){return e.recurring?{title:"Delete all occurrences?",body:"This recurring task and all its future dates will be deleted from Todoist."+(e.subtaskCount>0?` Its ${Md(e.subtaskCount)} go too.`:""),note:"To finish only this one, complete it instead.",confirm:"Delete all"}:{title:`Delete task and ${Md(e.subtaskCount)}?`,body:e.subtaskCount===1?"The subtask is deleted from Todoist with it.":"The subtasks are deleted from Todoist with it.",confirm:"Delete"}}const KS=e=>e>1?`${e} tasks deleted`:"Task deleted",YS=e=>e>1?`Couldn't delete ${e} tasks`:"Couldn't delete the task",WS=({open:e,copy:t,taskTitle:n,recurring:a,isPhone:r,onConfirm:o,onCancel:c})=>{const l=s.jsxs("p",{className:"del-task","data-testid":"delete-confirm-task",children:[a?s.jsx(Tg,{className:"del-task-icon","aria-hidden":!0}):s.jsx(Is,{className:"del-task-icon","aria-hidden":!0}),s.jsx("span",{className:"truncate",children:n})]});return r?s.jsx(ca,{open:e,onOpenChange:d=>{d||c()},children:s.jsxs(bn,{side:"bottom",className:S("del-sheet mx-sheet p-0 rounded-t-2xl border-t border-border/60","data-[state=open]:duration-200 data-[state=closed]:duration-150","[&>button]:hidden"),onOpenAutoFocus:d=>{d.preventDefault(),d.currentTarget.querySelector("[data-del-cancel]")?.focus({preventScroll:!0})},children:[s.jsx("div",{className:"flex justify-center pt-2",children:s.jsx("span",{className:"h-1 w-10 rounded-full bg-muted-foreground/30","aria-hidden":!0})}),s.jsxs("div",{className:"px-5 pt-3 pb-[max(1rem,env(safe-area-inset-bottom))]",children:[l,s.jsx(Rs,{className:"mt-2 text-[17px] font-semibold leading-snug",children:t?.title}),s.jsxs(qr,{className:"mt-1 text-[14px] leading-relaxed text-muted-foreground",children:[t?.body,t?.note&&s.jsx("span",{className:"del-note",children:t.note})]}),s.jsxs("div",{className:"mt-5 flex flex-col gap-2",children:[s.jsx("button",{type:"button",className:"del-btn del-btn-danger h-12 w-full",onClick:o,children:t?.confirm}),s.jsx("button",{type:"button","data-del-cancel":!0,className:"del-btn del-btn-quiet h-12 w-full",onClick:c,children:"Cancel"})]})]})]})}):s.jsx(yg,{open:e,onOpenChange:d=>{d||c()},children:s.jsxs(wg,{children:[s.jsx(vg,{className:"del-overlay fixed inset-0 z-50 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=closed]:animate-out data-[state=closed]:fade-out-0"}),s.jsxs(kg,{className:"del-dialog fixed left-1/2 top-1/2 z-50 w-[400px] max-w-[calc(100vw-32px)] -translate-x-1/2 -translate-y-1/2 rounded-xl border border-border/60 bg-popover p-5 text-popover-foreground shadow-xl outline-none data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-[0.98] data-[state=closed]:animate-out data-[state=closed]:fade-out-0",children:[l,s.jsx(jg,{className:"mt-2 text-[16px] font-semibold leading-snug",children:t?.title}),s.jsxs(Ng,{className:"mt-1.5 text-[14px] leading-relaxed text-muted-foreground",children:[t?.body,t?.note&&s.jsx("span",{className:"del-note",children:t.note})]}),s.jsxs("div",{className:"mt-5 flex justify-end gap-2",children:[s.jsx(Sg,{"data-del-cancel":!0,className:"del-btn del-btn-quiet h-9 px-4",children:"Cancel"}),s.jsx(Cg,{className:"del-btn del-btn-danger h-9 px-4",onClick:o,children:t?.confirm})]})]})]})})},GS=240,QS=1400,La="task-delete",Ld="task-delete-error",Ad=()=>{try{return window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{return!1}},JS=({tasks:e,unlabeledTasks:t,apiKey:n,removeTasksOptimistic:a,onTaskUpdate:r})=>{const{session:o}=we.useSessionContext(),c=Fe(),[l,d]=i.useState(null),m=i.useRef({tasks:e,unlabeledTasks:t,apiKey:n,removeTasksOptimistic:a,onTaskUpdate:r,token:o?.access_token??null,userId:o?.user?.id??""});m.current={tasks:e,unlabeledTasks:t,apiKey:n,removeTasksOptimistic:a,onTaskUpdate:r,token:o?.access_token??null,userId:o?.user?.id??""};const u=i.useRef(new Map),f=i.useRef(!1),p=i.useCallback(k=>{let N=!1;
32for(const C of k){const v=u.current.get(C.id);u.current.delete(C.id),v?v():N=!0,Ad()?io(C.ids,null):io(C.ids,"restored",QS)}N&&m.current.onTaskUpdate()},[]),h=i.useCallback(()=>{const k=Dt.undo();Z.dismiss(La),k.length&&(p(k),pe("task_delete_undone",{n:k.length}))},[p]),g=i.useCallback(k=>{f.current=!f.current,c&&xt(La),Z(Be(KS(k)),{id:La,duration:1/0,icon:s.jsx(Is,{className:"toast-delete-icon","aria-hidden":!0}),description:void 0,className:S("has-undo toast-delete",f.current&&"is-redrain"),style:{"--toast-dur":`${im}ms`},action:{label:"Undo",onClick:h},cancel:void 0})},[c,h]);i.useEffect(()=>{Dt.configure({send:zS(()=>({apiKey:m.current.apiKey,accessToken:m.current.token})),onChange:k=>{k.length&&g(k.length)},onSending:()=>Z.dismiss(La),onDone:k=>{u.current.delete(k.id)},onFailed:k=>{p(k),c&&xt(Ld),Z.error(Be(YS(k.length)),{id:Ld,description:"It's back where it was."})}})},[g,p,c]),i.useEffect(()=>{const k=()=>{Dt.pending().length&&Dt.flush({keepalive:!0})},N=()=>{document.visibilityState==="hidden"&&k()};return window.addEventListener("pagehide",k),document.addEventListener("visibilitychange",N),()=>{window.removeEventListener("pagehide",k),document.removeEventListener("visibilitychange",N),Dt.flush()}},[]);const b=o?.user?.id;i.useEffect(()=>{!b||!n||Dt.leftovers().some(k=>k.userId===b)&&Dt.resume(b)},[b,n]);const x=i.useCallback(({task:k,plan:N,via:C,quadrant:v})=>{const{removeTasksOptimistic:j,userId:T}=m.current,_=Ad(),I=_?0:GS;_||io(N.ids,"leaving",I+400);const{restore:R}=j(N.ids,I);u.current.set(k.id,R),pe("task_deleted",{quadrant:sa(v||Ah(k.labels)),via:C,recurring:N.recurring}),Dt.add({id:k.id,ids:N.ids,userId:T})},[]);i.useEffect(()=>{const k=N=>{const C=N.detail;if(!C?.taskId||Dt.isPending(C.taskId))return;const{tasks:v,unlabeledTasks:j}=m.current,T=v.find(R=>R.id===C.taskId)??j.find(R=>R.id===C.taskId)??C.task;if(!T)return;const _=HS(T,v),I={task:T,plan:_,via:C.via,quadrant:C.quadrant};_.confirm==="none"?x(I):d(I)};return window.addEventListener(ti,k),()=>window.removeEventListener(ti,k)},[x]);const y=i.useRef(null);l&&(y.current=l);const w=y.current;return s.jsx(WS,{open:!!l,copy:w?VS(w.plan):null,taskTitle:w?.task.content||w?.task.title||"",recurring:!!w?.plan.recurring,isPhone:c,onConfirm:()=>{const k=l;d(null),k&&x(k)},onCancel:()=>d(null)})},jo="subtask-reveal-flash",XS=1700,ZS=1500,eC=e=>e==="do"||e==="schedule"||e==="delegate"||e==="backlog",tC=()=>{try{return window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{return!1}},sC=e=>{const t=`[data-task-id="${CSS.escape(e)}"]`;for(const n of document.querySelectorAll(t))if(!n.closest('[inert], [role="dialog"], .cm-subtasks, [aria-hidden="true"]')&&n.getClientRects().length)return n;return null},Pd=(e,t)=>{window.dispatchEvent(new CustomEvent("matrix:reveal-task",{detail:{taskId:e,quadrant:t}})),t&&eC(t)&&nt()&&Gn(t);const n=performance.now();return new Promise(a=>{const r=()=>{const o=sC(e);if(!o){performance.now()-n<ZS?requestAnimationFrame(r):a(!1);return}o.scrollIntoView({block:"center",behavior:tC()?"auto":"smooth"}),o.classList.remove(jo),o.offsetWidth,o.classList.add(jo),window.setTimeout(()=>o.classList.remove(jo),XS),a(!0)};requestAnimationFrame(()=>requestAnimationFrame(r))})},Od="subtask-parent-hidden",nC=400,aC=({apiKey:e,hierarchy:t,visibleTasks:n,revealedIds:a,onRevealHidden:r,children:o})=>{const{nestSubtasks:c}=ds(),[l,d]=i.useReducer(x=>x+1,0),m=i.useMemo(()=>{const x=new Set;for(const y of n)y.parent_id&&!t.byId.has(y.parent_id)&&x.add(y.parent_id);return[...x].sort().join(",")},[n,t]),u=i.useRef(!0);i.useEffect(()=>()=>{u.current=!1},[]),i.useEffect(()=>{if(!e||!m)return;const x=za.pending(m.split(","));if(!x.length)return;const y=window.setTimeout(()=>{const w=new Ke(e);za.load(x,{byIds:k=>w.getTasksByIds(k),one:k=>w.getTask(k)}).then(k=>{k&&u.current&&d()})},nC);return()=>window.clearTimeout(y)},[e,m]);const f=i.useRef({hierarchy:t,visibleTasks:n,nestSubtasks:c});f.current={hierarchy:t,visibleTasks:n,nestSubtasks:c};const p=i.useCallback(x=>{const{hierarchy:y,visibleTasks:w,nestSubtasks:k}=f.current;return hw(x,{loaded:y.byId,visibleIds:new Set(w.map(N=>N.id)),hierarchy:y,nestSubtasks:k})},[]),h=i.useCallback(x=>{const y=x.parent_id;if(!y)return;const w=p(y);if(w.kind==="todoist"){window.open(bc(y),"_blank","noopener");return}if(w.kind==="row"){Pd(w.rowId,w.quadrant);return}xt(Od),Z("Parent is hidden by your filters",{id:Od,action:{label:"Show",onClick:()=>{r(y),window.setTimeout(()=>{const k=p(y);k.kind==="row"&&Pd(k.rowId,k.quadrant)},80)}}})},[p,r]),g=i.useCallback(x=>t.byId.get(x)?.title??za.peek(x),[t,l]),b=i.useMemo(()=>({titleOf:g,reveal:h,revealedIds:a}),[g,h,a]);return s.jsx(Sf.Provider,{value:b,children:o})},rC=[{label:"DO",title:"Do First",subtitle:"Urgent & Important",color:"#ef4444",tint:"rgba(239,68,68,0.12)",icon:Wt}
32,{label:"SCHEDULE",title:"Schedule",subtitle:"Important, Not Urgent",color:"#3b82f6",tint:"rgba(59,130,246,0.12)",icon:Kt},{label:"DELEGATE",title:"Delegate",subtitle:"Urgent, Not Important",color:"#fb923c",tint:"rgba(251,146,60,0.14)",icon:Un},{label:"BACKLOG",title:"Backlog",subtitle:"Neither Urgent nor Important",color:"#8a8580",tint:"rgba(138,133,128,0.16)",icon:zn}],oC=e=>rC.find(t=>t.label===e.toUpperCase()),rp=e=>{const{session:t}=we.useSessionContext(),n=t?.user?.id,a=at(),{data:r}=it({queryKey:["daily-focus-completions",n,e],enabled:!!n&&e.length>0,staleTime:6e4,queryFn:async()=>{const{data:o,error:c}=await B.from("task_completions").select("task_id").eq("user_id",n).gte("completed_at",Bn(new Date).toISOString()).in("task_id",e);if(c)throw c;return(o??[]).map(l=>l.task_id)}});return i.useEffect(()=>{const o=()=>a.invalidateQueries({queryKey:["daily-focus-completions"]});return window.addEventListener("task-completion-finished",o),()=>window.removeEventListener("task-completion-finished",o)},[a]),r},op=["do","schedule","delegate","backlog"],$d={4:"P1",3:"P2",2:"P3"},iC={4:"text-red-500",3:"text-amber-500",2:"text-blue-500"},vt=36,pi=3.5,gi=(vt-pi)/2,Fd=2*Math.PI*gi,cC=e=>{if(!e)return null;const t=Ye(e.due);if(!t)return null;const n=ls(t,Bn(new Date));if(n<0)return{text:n===-1?"Yesterday":`${-n}d overdue`,tone:"overdue"};if(n===0){const a=am(e.due);return{text:a?`Today · ${a}`:"Today",tone:a&&Er(e.due)?"overdue":"today"}}return n===1?{text:"Tomorrow",tone:"later"}:{text:`In ${n} days`,tone:"later"}},lC=e=>{if(!e)return;const t=(e.labels??[]).map(a=>a.toLowerCase()),n=op.find(a=>t.includes(a));return n?oC(n):void 0},dC=(e,t,n)=>{if(t===0)return"";if(e===t)return"All done for today.";if(e===0)return`Start with #${n+1}.`;const a=t-e;return a===1?"One left.":`${a} left.`},uC=({focusTasks:e,tasks:t,tasksAreFiltered:n=!1,isLoadingTasks:a,apiKey:r,onTaskUpdate:o,onClearFocus:c,onEditFocus:l})=>{const{handleCompleteTask:d}=qh({apiKey:r,onTaskUpdate:o,isFocusMode:!1}),m=Fe(),[u,f]=i.useState(new Set),p=i.useMemo(()=>e.map(v=>v.id),[e]),h=rp(p),g=i.useRef(new Map),b=i.useMemo(()=>{const v=new Map(t.map(T=>[T.id,T])),j=new Set(h??[]);return e.map(T=>{const _=v.get(T.id);_&&g.current.set(T.id,_);const I=j.has(T.id)||u.has(T.id)||!_&&!n,R=!_&&!I,M=_??(R?g.current.get(T.id):void 0);return{...T,title:M?.title??T.title,live:M,quadrant:lC(M),due:cC(M),priority:M?.priority&&$d[M.priority]?M.priority:void 0,open:!I,hidden:R}})},[e,t,n,h,u]),x=b.filter(v=>!v.open).length,y=b.length>0&&x===b.length,w=b.findIndex(v=>v.open),k=b.length>0?x/b.length:0,N=async v=>{f(j=>new Set(j).add(v)),await d(v),window.dispatchEvent(new CustomEvent("task-completion-finished",{detail:{taskId:v,timestamp:Date.now(),success:!0}}))};if(b.length===0||a&&t.length===0)return null;const C=v=>{document.querySelector(`[data-task-id="${v}"]`)?.scrollIntoView({behavior:"smooth",block:"center"})};return m?s.jsx(pC,{items:b,doneCount:x,allDone:y,firstOpenIndex:w,progress:k,onComplete:N,onEditFocus:l,onClearFocus:c}):s.jsxs(_e.section,{layout:!0,initial:{opacity:0,y:-6},animate:{opacity:1,y:0},transition:{duration:.25},"aria-label":"Today's focus",className:S("relative mb-4 overflow-hidden rounded-2xl border p-3 sm:p-4","bg-gradient-to-br backdrop-blur-sm transition-colors duration-500",y?"border-emerald-400/30 from-emerald-500/[0.08] via-emerald-400/[0.03] to-transparent":"border-amber-400/30 from-amber-500/[0.09] via-amber-400/[0.03] to-transparent"),children:[s.jsxs("div",{className:"mb-3 flex items-center gap-3",children:[s.jsxs("div",{className:"relative shrink-0",style:{width:vt,height:vt},children:[s.jsxs("svg",{width:vt,height:vt,viewBox:`0 0 ${vt} ${vt}`,className:"-rotate-90","aria-hidden":!0,children:[s.jsx("circle",{cx:vt/2,cy:vt/2,r:gi,fill:"none",strokeWidth:pi,className:S("stroke-current",y?"text-emerald-500/20":"text-amber-400/25")}),s.jsx(_e.circle,{cx:vt/2,cy:vt/2,r:gi,fill:"none",strokeWidth:pi,strokeLinecap:"round",strokeDasharray:Fd,initial:!1,animate:{strokeDashoffset:Fd*(1-k)},transition:{type:"spring",stiffness:120,damping:20}
32,className:S("stroke-current",y?"text-emerald-500":"text-amber-400")})]}),s.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:s.jsx(Gt,{mode:"wait",initial:!1,children:y?s.jsx(_e.span,{initial:{scale:.4,opacity:0},animate:{scale:1,opacity:1},exit:{scale:.4,opacity:0},transition:{type:"spring",stiffness:300,damping:18},className:"text-emerald-500",children:s.jsx(Oe,{className:"h-4 w-4",strokeWidth:3})},"done"):s.jsxs(_e.span,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"text-[11px] font-semibold tabular-nums text-amber-700 dark:text-amber-300",children:[x,"/",b.length]},"count")})})]}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx(Yt,{className:S("h-3.5 w-3.5",y?"fill-emerald-500 text-emerald-500":"fill-amber-400 text-amber-400")}),s.jsx("h2",{className:"text-sm font-semibold leading-none",children:"Today's focus"})]}),s.jsx("p",{className:"mt-1 truncate text-xs text-muted-foreground",children:dC(x,b.length,w)})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-0.5",children:[l&&s.jsx("button",{type:"button",onClick:l,"aria-label":"Change today's focus",className:"h-8 rounded-[9px] bg-muted/60 px-3 text-[13px] font-medium text-foreground transition-colors hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-amber-400 focus-visible:ring-offset-2 focus-visible:ring-offset-background",children:"Edit"}),s.jsx("button",{type:"button",onClick:()=>c(),title:"Clear today's focus","aria-label":"Clear today's focus",className:"flex h-7 w-7 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:s.jsx(Ie,{className:"h-3.5 w-3.5"})})]})]}),s.jsx("div",{className:S("grid gap-2",b.length===1&&"grid-cols-1",b.length===2&&"grid-cols-1 sm:grid-cols-2",b.length>=3&&"grid-cols-1 sm:grid-cols-3"),children:b.map((v,j)=>{const T=j===w;return s.jsxs(_e.div,{layout:!0,animate:{opacity:v.open?v.hidden?.75:1:.7},transition:{duration:.3},className:S("group relative flex items-center gap-3 rounded-xl border px-3 py-2.5 transition-colors",v.open?S("border-border/60 bg-background/70 hover:border-amber-400/50",T&&"border-amber-400/50 shadow-sm shadow-amber-500/10"):"border-transparent bg-muted/40"),children:[s.jsx("button",{type:"button",onClick:()=>v.open&&N(v.id),disabled:!v.open,"aria-label":v.open?`Complete ${v.title}`:`${v.title} completed`,title:v.open?"Complete":"Completed",className:S("relative flex h-6 w-6 shrink-0 items-center justify-center rounded-full border transition-all duration-200",v.open?"border-muted-foreground/40 text-transparent hover:scale-105 hover:border-emerald-500 hover:bg-emerald-500 hover:text-white":"border-emerald-500 bg-emerald-500 text-white"),children:s.jsx(Oe,{className:"h-3.5 w-3.5",strokeWidth:3})}),s.jsxs("button",{type:"button",onClick:()=>v.open&&!v.hidden&&C(v.id),disabled:!v.open||v.hidden,title:v.hidden?"Hidden by the active filter":v.open?"Show in matrix":void 0,className:"min-w-0 flex-1 text-left",children:[s.jsx("p",{className:S("truncate text-sm leading-tight",v.open?S("font-medium",!v.hidden&&"group-hover:underline"):"text-muted-foreground line-through"),children:v.title}),s.jsxs("div",{className:"mt-1 flex items-center gap-1.5 text-[11px] text-muted-foreground",children:[v.quadrant&&s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx("span",{className:"h-1.5 w-1.5 rounded-full",style:{backgroundColor:v.quadrant.color},"aria-hidden":!0}),v.quadrant.title]}),v.due&&v.open&&s.jsxs(s.Fragment,{children:[v.quadrant&&s.jsx("span",{"aria-hidden":!0,children:"·"}),s.jsx("span",{className:S(v.due.tone==="overdue"&&"text-red-500 dark:text-red-400",v.due.tone==="today"&&"text-amber-600 dark:text-amber-400"),children:v.due.text})]}),v.priority&&v.open&&s.jsxs(s.Fragment,{children:[s.jsx("span",{"aria-hidden":!0,children:"·"}),s.jsx("span",{className:S("font-medium",iC[v.priority]),children:$d[v.priority]})]}),v.hidden&&s.jsxs(s.Fragment,{children:[(v.quadrant||v.due||v.priority)&&s.jsx("span",{"aria-hidden":!0,
32children:"·"}),s.jsx("span",{className:"italic",children:"Hidden by filter"})]}),!v.open&&s.jsx("span",{children:"Done"})]})]}),s.jsx("span",{className:S("flex h-5 w-5 shrink-0 items-center justify-center rounded-full text-[10px] font-semibold tabular-nums",v.open?"bg-amber-400/20 text-amber-700 dark:text-amber-300":"bg-muted text-muted-foreground"),"aria-hidden":!0,children:j+1})]},v.id)})})]})},xi="daily-focus-open",ip=()=>Ee(new Date,"yyyy-MM-dd"),mC=()=>{try{return window.localStorage.getItem(xi)===ip()}catch{return!1}},fC=e=>{try{e?window.localStorage.setItem(xi,ip()):window.localStorage.removeItem(xi)}catch{}},hC=({progress:e,allDone:t,label:n})=>{const c=2*Math.PI*15.5;return s.jsxs("span",{className:"relative flex shrink-0 items-center justify-center",style:{width:34,height:34},"aria-hidden":!0,children:[s.jsxs("svg",{width:34,height:34,viewBox:"0 0 34 34",className:"-rotate-90",children:[s.jsx("circle",{cx:34/2,cy:34/2,r:15.5,fill:"none",strokeWidth:3,className:S("stroke-current",t?"text-emerald-500/20":"text-amber-400/25")}),s.jsx("circle",{cx:34/2,cy:34/2,r:15.5,fill:"none",strokeWidth:3,strokeLinecap:"round",strokeDasharray:c,strokeDashoffset:c*(1-e),className:S("stroke-current transition-[stroke-dashoffset] duration-500",t?"text-emerald-500":"text-amber-400")})]}),s.jsx("span",{className:"absolute text-[12px] font-semibold tabular-nums tracking-tight text-foreground",children:t?s.jsx(Oe,{className:"h-3 w-3 text-emerald-500",strokeWidth:3}):n})]})},pC=({items:e,doneCount:t,allDone:n,firstOpenIndex:a,progress:r,onComplete:o,onEditFocus:c,onClearFocus:l})=>{const[d,m]=i.useState(mC),u=()=>{m(h=>(fC(!h),!h))},f=e[a],p=h=>{const g=(h.live?.labels??[]).map(x=>x.toLowerCase()),b=op.find(x=>g.includes(x));b&&Gn(b),window.setTimeout(()=>{document.querySelector(`[data-task-id="${h.id}"]`)?.scrollIntoView({behavior:"smooth",block:"center"})},60)};return s.jsxs("section",{"aria-label":"Today's focus",className:S("mx-focus",d&&"is-open",n&&"is-done"),children:[s.jsxs("button",{type:"button",className:"mx-focus-head","aria-expanded":d,onClick:u,children:[s.jsx(hC,{progress:r,allDone:n,label:`${t}/${e.length}`}),s.jsxs("span",{className:"min-w-0 flex-1 truncate text-left",children:[s.jsx("span",{className:"font-semibold",children:"Today's focus"}),!d&&s.jsxs("span",{className:"text-muted-foreground",children:[" · ",n?"All done":f?.title]})]}),s.jsx(mt,{className:S("h-4 w-4 shrink-0 text-muted-foreground transition-transform",d&&"rotate-180"),"aria-hidden":!0})]}),d&&s.jsxs("div",{className:"mx-focus-body",children:[e.map(h=>s.jsxs("div",{className:S("mx-focus-row",!h.open&&"is-done"),children:[s.jsx("button",{type:"button",className:"mx-ring",onClick:()=>h.open&&o(h.id),disabled:!h.open,"aria-label":h.open?`Complete ${h.title}`:`${h.title} completed`,children:s.jsx("span",{className:S("mx-ring-circle",!h.open&&"is-checked"),"aria-hidden":!0,children:s.jsx(Oe,{className:"mx-ring-check",strokeWidth:3})})}),s.jsxs("button",{type:"button",className:"mx-focus-title",onClick:()=>h.open&&!h.hidden&&p(h),disabled:!h.open||h.hidden,children:[s.jsx("span",{className:S("block truncate",!h.open&&"line-through text-muted-foreground"),children:h.title}),s.jsxs("span",{className:"mx-row-meta",children:[h.quadrant&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-dot",style:{"--q":`var(--q-${h.quadrant.label.toLowerCase()})`},"aria-hidden":!0}),h.quadrant.title]}),h.due&&h.open&&s.jsxs(s.Fragment,{children:[h.quadrant&&" · ",h.due.text]}),h.hidden&&" · Hidden by filter",!h.open&&" · Done"]})]})]},h.id)),s.jsxs("div",{className:"mx-focus-actions",children:[c&&s.jsx("button",{type:"button",onClick:c,"aria-label":"Change today's focus",children:"Edit"}),s.jsx("button",{type:"button",onClick:()=>l(),"aria-label":"Hide today's focus for today",children:"Hide for today"})]})]})]})},gC=(e=new Date)=>Ee(e,"yyyy-MM-dd"),qd=(e,t)=>`daily-review-prompted:${e}:${t}`,xC=()=>{const{session:e}=we.useSessionContext(),t=at(),n=e?.user?.id,a=e?.user?.email,r=gC(),o=it({queryKey:["daily-review",n,r],enabled:!!n,staleTime:6e4,queryFn:async()=>{const{data:x,error:y}=await B.from("daily_reviews").select("*").eq("user_id",n).eq("review_date",r).maybeSingle();if(y)throw y;return x}}),c=i.useMemo(()=>new Set(o.data?.status==="completed"?o.data.focus_task_ids:[]),[o.data]),l=i.useMemo(()=>o.data?.status!=="completed"||!Array.isArray(o.data.focus_tasks)?[]:o.data.focus_tasks.filter(x=>!!x&&typeof x=="object"&&typeof x.id=="string"&&typeof x.title=="string"),[o.data]),d=i.useMemo(()=>
32{if(!n)return!0;try{return!!localStorage.getItem(qd(n,r))}catch{return!0}},[n,r]),m=i.useCallback(()=>{if(n)try{localStorage.setItem(qd(n,r),"1")}catch{}},[n,r]),u=nh(e?.user?.created_at),f=!!n&&!u&&o.isSuccess&&o.data===null&&!d,p=i.useCallback(async(x,y)=>{if(!n)return;m();const{error:w}=await B.from("daily_reviews").upsert({user_id:n,review_date:r,status:x,focus_task_ids:y.map(k=>k.id),focus_tasks:y,updated_at:new Date().toISOString()},{onConflict:"user_id,review_date"});if(w)throw w;await t.invalidateQueries({queryKey:["daily-review",n,r]})},[n,r,m,t]),h=i.useCallback(async x=>{await p("completed",x),n&&(await Pt(n,a??void 0,"daily_review",{focus_task_count:x.length,review_date:r}),window.dispatchEvent(new CustomEvent("focus-task-completed")))},[p,n,a,r]),g=i.useCallback(()=>p("skipped",[]),[p]),b=i.useCallback(()=>p("completed",[]),[p]);return{todaysReview:o.data??null,isLoading:o.isLoading,focusTaskIds:c,focusTasks:l,shouldPrompt:f,markPrompted:m,completeReview:h,skipReview:g,clearFocus:b}},bC=6e4,yC=6e4;function wC(e){return e.pending||e.hiddenForMs>=bC?e.focusOpen||e.overlayOpen?"hold":e.now-e.lastRefreshAt<yC?"skip":"refresh":"skip"}function vC(e=document){return e.body.classList.contains("focus-mode-active")||e.documentElement.classList.contains("task-focus-active")||!!e.querySelector(".fv-root, .fvm-root")}function kC(e=document){return!!e.querySelector('[role="dialog"][data-state="open"], [role="alertdialog"][data-state="open"], [vaul-drawer][data-state="open"]')}const jC=1e3;function NC(e,t){const n=i.useRef(e);n.current=e,i.useEffect(()=>{if(!t)return;let a=document.visibilityState==="hidden"?Date.now():null,r=!1,o=Date.now(),c=null;const l=()=>{c!==null&&window.clearInterval(c),c=null},d=h=>{const g=wC({hiddenForMs:h,pending:r,now:Date.now(),lastRefreshAt:o,overlayOpen:kC(),focusOpen:vC()});g==="refresh"?(r=!1,l(),o=Date.now(),n.current()):g==="hold"?(r=!0,c===null&&(c=window.setInterval(()=>{document.visibilityState==="visible"&&d(0)},jC))):(r=!1,l())},m=()=>{a===null&&(a=Date.now()),l()},u=()=>{const h=a===null?0:Date.now()-a;a=null,d(h)},f=()=>{document.visibilityState==="hidden"?m():u()},p=h=>{h.persisted&&u()};return document.addEventListener("visibilitychange",f),window.addEventListener("pagehide",m),window.addEventListener("pageshow",p),()=>{document.removeEventListener("visibilitychange",f),window.removeEventListener("pagehide",m),window.removeEventListener("pageshow",p),l()}},[t])}const No=(e,t,n)=>e===1?t:n,SC=()=>{const{card:e,startSorting:t,dismissCard:n}=Ot();if(!e)return null;const{variant:a,unsorted:r,k:o,sortedOfQueue:c,firstName:l,justConnected:d,closing:m}=e;if(a!=="empty"&&(r===0||o===0)&&!m)return null;let u,f,p,h="Not now";if(a==="empty")u="Your Todoist is empty. Fresh start.",f="Add the first thing on your mind and choose its quadrant as you add it. Urgent and important goes to Do First.",p="Add a task";else if(a==="resume")u=`You've sorted ${c} of ${o}. Pick up where you left off?`,f=`The rest of your first ${o} are ready when you are.`,p="Continue sorting";else if(a==="second")u=`Ready to sort your first ${o} ${No(o,"task","tasks")}?`,f="It takes about a minute, and your matrix fills in as you go.",p=o===1?"Sort my first task":`Sort my first ${o} tasks`,h="Dismiss";else{u=l?`Welcome, ${l}. Let's put your tasks in order.`:"Welcome. Let's put your tasks in order.";const g="The matrix asks two questions about every task: is it urgent, and is it important?";f=r>o?`${g} Your ${r} Todoist tasks don't have a quadrant yet. Start with the ${o} most pressing. It takes about a minute.`:`${g} Your ${r} Todoist ${No(r,"task","tasks")} ${r===1?"doesn't":"don't"} have a quadrant yet. Sort ${No(r,"it","them")} and watch the matrix fill in.`,p=o===1?"Sort my first task":r<=o?`Sort my ${r} tasks`:`Sort my first ${o} tasks`}return s.jsx("div",{className:S("cm-starter-wrap",m&&"is-closing"),children:s.jsx("div",{className:"cm-starter-clip",children:s.jsxs("section",{className:"cm-starter","aria-labelledby":"onb-starter-title","data-testid":"onb-starter",children:[s.jsxs("span",{className:"cm-starter-glyph","aria-hidden":!0,
32children:[s.jsx("i",{}),s.jsx("i",{}),s.jsx("i",{}),s.jsx("i",{})]}),s.jsxs("div",{className:"min-w-0",children:[d&&s.jsxs("p",{className:"cm-starter-eyebrow",children:[s.jsx(Oe,{className:"h-3 w-3","aria-hidden":!0})," Todoist connected"]}),s.jsx("h2",{id:"onb-starter-title",className:"cm-starter-title",children:u}),s.jsx("p",{className:"cm-starter-body",children:f})]}),s.jsxs("div",{className:"cm-starter-actions",children:[s.jsx(W,{size:"sm",className:"text-[13px]","data-testid":"onb-starter-primary",onClick:t,children:p}),s.jsx(W,{size:"sm",variant:"ghost",className:"text-[13px] text-muted-foreground","data-testid":"onb-starter-dismiss",onClick:n,children:h})]})]})})})},Aa="tasks-completed-today",cp=(e=new Date)=>Dr(e),bi=(e,t=new Date)=>e.local?e.date===cp(t):e.date===t.toISOString().slice(0,10),CC=(e,t=new Date)=>{if(!e)return 0;try{const n=JSON.parse(e);return bi(n,t)?n.count:0}catch{return 0}},TC=()=>{const[e,t]=i.useState(()=>{try{return CC(localStorage.getItem(Aa))}catch{return 0}});return i.useEffect(()=>{const n=c=>{try{localStorage.setItem(Aa,JSON.stringify({date:cp(),count:c,local:!0}))}catch{}},a=()=>{t(c=>{let l=c;try{const m=localStorage.getItem(Aa);if(m){const u=JSON.parse(m);bi(u)||(l=0)}}catch{}const d=l+1;return n(d),d})},r=()=>{try{const c=localStorage.getItem(Aa);if(!c)return;const l=JSON.parse(c);bi(l)||(n(0),t(0))}catch{}},o=()=>{t(c=>{const l=Math.max(0,c-1);return n(l),l})};return window.addEventListener("task-completion-finished",a),window.addEventListener("task-completion-undone",o),document.addEventListener("visibilitychange",r),()=>{window.removeEventListener("task-completion-finished",a),window.removeEventListener("task-completion-undone",o),document.removeEventListener("visibilitychange",r)}},[]),e},_C=(e,t,n)=>n?Fm(n):e==="paid"||e==="lifetime"?"Premium":e==="trial"&&typeof t=="number"?t<=0?"Trial · ends today":`Trial · ${t} ${t===1?"day":"days"} left`:e==="expired"||e==="trial"?"Trial expired":null,EC=({email:e,onLogout:t,onCategorize:n,onBulkRecategorize:a,onOpenDailyReview:r,unlabeledTasksCount:o,paymentStatus:c,billingPlan:l,daysLeft:d,theme:m,onToggleTheme:u})=>{const f=Pe(re=>re.accountSheetOpen),p=Pe(re=>re.accountShowsPlans),h=Pe(re=>re.closeAccountSheet),g=Xt(),{data:b}=Hi(),x=TC(),{density:y,setDensity:w}=Zt(),{showTags:k,toggleShowTags:N}=ds(),[C,v]=ct("show-confetti",!0),{reconnectTodoist:j,isReconnecting:T}=Gi(),[_,I]=i.useState("main"),[R,M]=i.useState(!1),[P,E]=i.useState(!1),[D,L]=i.useState(!1),[A,H]=i.useState(!1),[K,X]=i.useState(!1),[ce,oe]=i.useState(!1),{state:ve}=Wh(l),Ce=ve?.kind==="lifetime"&&!!ve.oldMembership;i.useEffect(()=>{f&&(I("main"),M(p))},[f,p]);const ee=re=>()=>{h(),window.setTimeout(re,180)},Le=_C(c,d,l),he=$m(c),ge=c==="expired"||c==="trial"&&(d??99)<=3,De=[`${b?.current??0}-day streak`,x>0?`${x} today`:null].filter(Boolean).join(" · ");return s.jsxs(s.Fragment,{children:[s.jsx(ca,{open:f,onOpenChange:re=>!re&&h(),children:s.jsxs(bn,{side:"bottom",onOpenAutoFocus:re=>{re.preventDefault(),re.target?.focus()},className:S("mx-sheet p-0 rounded-t-2xl border-t border-border/60","max-h-[calc(100dvh-env(safe-area-inset-top)-24px)] overflow-y-auto overscroll-contain","data-[state=open]:duration-200 data-[state=closed]:duration-150","[&>button]:hidden"),children:[s.jsx("div",{className:"flex justify-center pt-2",children:s.jsx("span",{className:"h-1 w-10 rounded-full bg-muted-foreground/30","aria-hidden":!0})}),_==="progress"?s.jsxs("div",{className:"pb-[max(1rem,env(safe-area-inset-bottom))]",children:[s.jsxs("div",{className:"flex items-center gap-1 px-2 pt-1",children:[s.jsx("button",{type:"button",className:"mx-icon-btn",onClick:()=>I("main"),"aria-label":"Back to account",children:s.jsx(wu,{className:"h-5 w-5","aria-hidden":!0})}),s.jsx(Rs,{className:"flex-1 text-[17px] font-semibold",children:"Progress"}),s.jsx("button",{type:"button",className:"mx-sheet-close is-inline is-flush",onClick:h,"aria-label":"Close",children:s.jsx(Ie,{"aria-hidden":!0})})]}),s.jsx(ap,{})]}):s.jsxs("div",{className:"pb-[max(0.75rem,env(safe-area-inset-bottom))]",children:[s.jsxs("div",{className:"px-5 pt-3 pb-3",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx(Rs,{className:"min-w-0 flex-1 truncate text-[15px] font-semibold",children:e??"Account"}),Le&&s.jsx("span",{className:S("shrink-0 rounded-full px-2.5 py-1 text-[12px] font-medium",ge?"bg-amber-500/15 text-amber-700 dark:text-amber-300":"bg-muted text-muted-foreground"),children:Le}),s.jsx("button",{type:"button",className:"mx-sheet-close is-inline",onClick:h,"aria-label":"Close",children:s.jsx(Ie,{"aria-hidden":!0})})]}),l&&s.jsxs("button",{type:"button","data-testid":"manage-membership","data-attention":Ce||void 0,onClick:ee(()=>oe(!0)),className:S("-ml-2 mt-1 inline-flex min-h-[44px] items-center gap-1.5 rounded-lg px-2 text-[15px] font-medium",Ce?"text-foreground":"text-muted-foreground"),children:[Ce&&s.jsx("span",{className:"h-2 w-2 shrink-0 rounded-full bg-amber-500","aria-hidden":!0}
32),Ce?Yh.rowCancelOld:l==="membership"?`${Ve.manage} plan`:"Plan & receipts",s.jsx(pt,{className:"h-4 w-4","aria-hidden":!0})]}),he&&s.jsxs("button",{type:"button","data-testid":"sheet-see-plans",className:"mt-2 inline-flex min-h-[44px] items-center gap-1 rounded-full bg-primary px-5 text-[15px] font-semibold text-primary-foreground shadow-sm active:opacity-90","aria-expanded":R,onClick:()=>M(re=>!re),children:[Ve.seePlans,s.jsx(pt,{className:S("h-4 w-4 transition-transform",R&&"rotate-90"),"aria-hidden":!0})]}),he&&R&&s.jsx("div",{className:"mt-2",children:s.jsx(Jh,{size:"large",onStarted:h})}),he&&s.jsx(Zh,{size:"large",className:S("flex w-fit mt-1",R?"mx-auto":"-ml-3"),"data-testid":"sheet-license-link",onClick:ee(()=>H(!0))})]}),s.jsx(zd,{}),s.jsxs("div",{className:"px-2 py-1",children:[r&&s.jsx(ot,{id:"daily-review-btn",icon:s.jsx(Ou,{}),tint:"var(--q-focus)",label:"Daily review",chevron:!0,onClick:ee(r)}),s.jsx(ot,{icon:s.jsx(qn,{}),tint:"var(--q-delegate)",label:"Progress",value:De,chevron:!0,onClick:()=>I("progress")}),s.jsx(ot,{id:"stats-button",icon:s.jsx($u,{}),tint:"var(--q-schedule)",label:"Statistics",chevron:!0,onTouchStart:()=>Ne(()=>import("./Statistics-C6kF8i-x.js"),__vite__mapDeps([27,1,2,3,4,17,28,29])).catch(()=>{}),onClick:ee(()=>g("/statistics"))}),o>0&&s.jsx(ot,{icon:s.jsx(_g,{}),tint:"var(--q-focus)",label:"Sort tasks",value:String(o),chevron:!0,onClick:ee(n)}),s.jsx(ot,{id:"recategorize-btn",icon:s.jsx(Lu,{}),label:"Recategorize all",chevron:!0,onClick:ee(a)}),s.jsx(ot,{icon:s.jsx(Pu,{}),label:"Settings",chevron:!0,onClick:ee(()=>E(!0))}),s.jsx(ot,{icon:s.jsx(Iu,{}),label:"Dark mode",control:s.jsx(Wn,{checked:m==="dark",onCheckedChange:u,"aria-label":"Dark mode"}),onClick:u}),s.jsx(ot,{icon:s.jsx(Eg,{}),label:"Compact cards",control:s.jsx(Wn,{checked:y==="compact",onCheckedChange:re=>w(re?"compact":"default"),"aria-label":"Compact cards"}),onClick:()=>w(y==="compact"?"default":"compact")})]}),s.jsx(zd,{}),s.jsxs("div",{className:"px-2 py-1",children:[s.jsx(ot,{icon:s.jsx(Dg,{}),label:"Send feedback",onClick:ee(()=>X(!0))}),s.jsx(ot,{icon:s.jsx(Ru,{}),label:"Product tour",onClick:ee(()=>window.dispatchEvent(new Event("tour:open")))}),s.jsx(ot,{icon:s.jsx(_i,{className:S(T&&"animate-spin")}),label:T?"Reconnecting…":"Reconnect Todoist",disabled:T,onClick:()=>{j()}}),Hh(e)&&s.jsx(ot,{icon:s.jsx(Du,{}),label:"Admin panel",chevron:!0,onClick:ee(()=>g("/admin"))}),s.jsx(ot,{icon:s.jsx(Au,{}),label:"Log out",onClick:ee(t)}),s.jsx(ot,{icon:s.jsx(Is,{}),label:"Delete account",danger:!0,onClick:ee(()=>L(!0))})]})]})]})}),s.jsx(pf,{open:K,onOpenChange:X}),s.jsx(mf,{isOpen:P,onClose:()=>E(!1),showConfetti:C,onToggleConfetti:()=>v(!C),showTags:k,onToggleTags:()=>N(!k)}),s.jsx(ff,{open:D,onOpenChange:L,email:e}),s.jsx(hf,{isOpen:A,onClose:()=>H(!1)}),l&&s.jsx(Gh,{open:ce,onOpenChange:oe,state:ve})]})},zd=()=>s.jsx("div",{className:"mx-5 h-px bg-border/60"}),ot=({id:e,icon:t,tint:n,label:a,value:r,chevron:o,control:c,danger:l,disabled:d,onClick:m,onTouchStart:u})=>{const f=s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-row-tile",style:l?{background:"hsl(var(--destructive) / 0.12)",color:"hsl(var(--destructive))"}:n?{background:`rgb(${n} / 0.14)`,color:`rgb(${n})`}:void 0,"aria-hidden":!0,children:t}),s.jsx("span",{className:S("min-w-0 flex-1 truncate",l&&"text-destructive"),children:a}),r&&s.jsx("span",{className:"shrink-0 text-[13px] text-muted-foreground tabular-nums",children:r}),o&&s.jsx(pt,{className:"h-4 w-4 shrink-0 text-muted-foreground/70","aria-hidden":!0})]});return c?s.jsxs("div",{className:"mx-sheet-row",onClick:m,children:[f,s.jsx("span",{onClick:p=>p.stopPropagation(),children:c})]}):s.jsx("button",{id:e,type:"button",className:"mx-sheet-row",onClick:m,onTouchStart:u,disabled:d,children:f})},DC=({email:e,onLogout:t,onRecategorize:n,onBulkRecategorize:a,onOpenDailyReview:r,unlabeledTasksCount:o,paymentStatus:c,billingPlan:l,daysLeft:d})=>{const m=Pe(v=>v.quadrant),u=Pe(v=>v.counts[v.quadrant]),f=Pe(v=>v.activeFilterCount),p=Pe(v=>v.countsKnown&&v.counts.do+v.counts.schedule+v.counts.delegate+v.counts.backlog===0),h=Pe(v=>v.setFilterSheetOpen),g=Pe(v=>v.openAccountSheet),{theme:b,toggleTheme:x}=tp(),y=On.find(v=>v.id===m)??On[0];ej();const[w,k]=i.useState(!1);i.useEffect(()=>{let v=0;const j=()=>{v=0,k(window.scrollY>4)},T=()=>{v||(v=requestAnimationFrame(j))};return j(),window.addEventListener("scroll",T,{passive:!0}),()=>{window.removeEventListener("scroll",T),v&&cancelAnimationFrame(v)}},[]);const N=()=>{ut(12),document.getElementById("single-task-focus")?.click()},C=(e?.trim()[0]??"?").toUpperCase();return s.jsxs("header",{className:"mx-header","data-scrolled":w||void 0,children:[s.jsxs("div",{className:"mx-header-title",style:{"--q":`var(--q-${m})`},children:[s.jsx("span",{className:"mx-dot","aria-hidden":!0}),s.jsx("h1",{className:"mx-header-name","aria-description":y.meaning,children:y.label}),s.jsx("span",{className:"mx-header-count","aria-label":`${u} ${u===1?"task":"tasks"}`,children:u})]}),s.jsxs("div",{className:"mx-header-actions",children:[s.jsx("button",{id:"mx-focus-btn",type:"button",className:"mx-icon-btn",onClick:N,"aria-label":p?"Single task focus, no tasks":"Single task focus","data-empty":p||void 0,children:s.jsx(Ts,{className:"h-5 w-5","aria-hidden":!0})}),s.jsxs("button",{id:"mx-filter-btn",type:"button",className:"mx-icon-btn",onClick:()=>h(!0),"aria-label":f?`Filters, ${f} active`:"Filters","aria-haspopup":"dialog",children:[s.jsx(ta,{className:"h-5 w-5","aria-hidden":!0}),f>
320&&s.jsx("span",{className:"mx-badge","aria-hidden":!0,children:f})]}),s.jsx("button",{id:"mx-account-btn",type:"button",className:"mx-icon-btn",onClick:()=>g(),"aria-label":"Account","aria-haspopup":"dialog",children:s.jsx("span",{className:S("mx-avatar",qy(c,d)&&"has-dot"),"aria-hidden":!0,children:C})})]}),s.jsx(EC,{email:e,onLogout:t,onCategorize:n,onBulkRecategorize:a,onOpenDailyReview:r,unlabeledTasksCount:o,paymentStatus:c,billingPlan:l,daysLeft:d,theme:b,onToggleTheme:x})]})},RC=({unlabeledTasksCount:e,onSort:t,paymentStatus:n,daysLeft:a})=>{const r=ep(n,a),o=rh(),c=r.view==="expanded"&&!o,l=r.view==="minimized"&&!r.onboarding&&!o;return!c&&!l&&e===0?null:s.jsxs("div",{className:"mx-intro",children:[c&&s.jsx(Xh,{layout:"phone",daysLeft:a,nudgeDue:r.nudgeDue,onMinimize:r.minimize}),l&&s.jsxs("button",{type:"button",className:"mx-trial","data-testid":"trial-plans-row","aria-expanded":!1,onClick:r.expand,children:[s.jsx(Kt,{className:"h-4 w-4 shrink-0","aria-hidden":!0}),s.jsx("span",{className:"min-w-0 flex-1 truncate text-left",children:Ve.trialLine(a,r.nudgeDue)}),s.jsxs("span",{className:"mx-intro-cta",children:[Ve.seePlans,s.jsx(pt,{className:"h-4 w-4","aria-hidden":!0})]})]}),e>0&&s.jsxs("button",{id:"categorize-btn",type:"button",className:"mx-tosort",onClick:t,children:[s.jsx(Mu,{className:"h-[18px] w-[18px] shrink-0","aria-hidden":!0}),s.jsxs("span",{className:"min-w-0 flex-1 truncate text-left",children:[e," ",e===1?"task":"tasks"," to sort"]}),s.jsxs("span",{className:"mx-intro-cta",children:["Sort",s.jsx(pt,{className:"h-4 w-4","aria-hidden":!0})]})]})]})},IC=i.lazy(()=>Ne(()=>import("./FeatureTour-BvQZ-bXu.js"),__vite__mapDeps([0,1,2,3,4])).then(e=>({default:e.OnboardingTour}))),MC=i.lazy(()=>Ne(()=>import("./DailyReviewDialog-cTmWj_Jx.js"),__vite__mapDeps([30,1,2,3,20,4,31])).then(e=>({default:e.DailyReviewDialog}))),LC=i.lazy(()=>Ne(()=>import("./MatrixSheets-76SgZskf.js"),__vite__mapDeps([32,1,2,4,7,3,33])).then(e=>({default:e.MatrixSheets}))),AC=gn(()=>Ne(()=>import("./MovedHereReviewSheet-CZ3kfDxh.js"),__vite__mapDeps([34,1,2,33,4,3])).then(e=>e.MovedHereReviewSheet)),PC=({tasks:e})=>{const{reviewOpen:t}=xn();return Km(t)?s.jsx(AC,{tasks:e}):null},OC=({apiKey:e,email:t,onLogout:n})=>{const[a,r]=i.useState(null),o=Fe(),[c,l]=i.useState(!1),{showLabelingSheet:d,setShowLabelingSheet:m,selectedLabels:u,setSelectedLabels:f,removeLabel:p,showTour:h,tourPending:g,firstRun:b,markOnboardingComplete:x,isFocusMode:y,tasks:w,tasksAreFiltered:k,tasksReady:N,isLoading:C,fetchError:v,unlabeledTasks:j,fetchTasks:T,quietRefreshTasks:_,handleTourClose:I,toggleFocusMode:R,dateFilter:M,setDateFilter:P,filteredTasks:E,isPending:D,selectedProjects:L,setSelectedProjects:A,removeProject:H,selectedPriorities:K,setSelectedPriorities:X,selectedTodoistFilter:ce,setSelectedTodoistFilter:oe,hideSubtasks:ve,setHideSubtasks:Ce,completeTaskOptimistic:ee,removeTasksOptimistic:Le}=wb(e),he=i.useMemo(()=>({completeTaskOptimistic:ee}),[ee]),ge=i.useMemo(()=>$S(w),[w]),{view:Te}=da(),De=i.useRef(!1);i.useEffect(()=>{!N||De.current||(De.current=!0,pe("matrix_viewed",{tasks:$a(w.length),unsorted:$a(j?.length??0),layout:o?"phone":"desktop",view:o?"mobile":Te==="clean"?"clean":"classic"}))},[N,w.length,j?.length,o,Te]),i.useEffect(()=>{N&&Wy()},[N]),i.useEffect(()=>{d&&pe("categorize_opened",{kind:"sheet",unsorted:$a(j?.length??0)})},[d]),i.useEffect(()=>{c&&pe("categorize_opened",{kind:"bulk"})},[c]);const re=(Re,Ae)=>Xe=>{pe("filters_used",{kind:Re}),Ae(Xe)},[se,ue]=i.useState(!1),Qe=b.eligible||se,$=d||c||Qe,[O,F]=i.useState(!1);i.useEffect(()=>{$&&F(!0)},[$]);const Q=i.useMemo(()=>ob(w),[w]),V=i.useMemo(()=>{const Re=new Set;for(const Ae of w)(Ae.labels??[]).map(ma=>ma.toLowerCase()).includes("do")&&Re.add(Ae.id);return Re},[w]),{handleRecategorize:G,handleBulkRecategorize:Y,handleFocusModeToggle:J,handleOAuthSuccess:le}=OS();qb();const{focusTaskIds:U,focusTasks:ne,shouldPrompt:me,markPrompted:q,completeReview:xe,ski
32pReview:ke,clearFocus:We}=xC(),Ze=i.useMemo(()=>[...U],[U]),de=rp(Ze),be=i.useMemo(()=>Bk(Ze,new Set(w.map(Re=>Re.id)),{completedToday:new Set(de??[]),tasksAreFiltered:k}),[Ze,w,de,k]);NC(()=>{_()},!!e&&N);const[Se,Me]=i.useState(!1),[Je,ft]=i.useState(!1),rt=(Re=!1)=>{pe("daily_review_opened",{auto:!1}),ft(Re),Me(!0)},[$t,Ft]=i.useState(!1);i.useEffect(()=>{Se&&Ft(!0)},[Se]);const et=i.useMemo(()=>E(),[E]),[bt,Tt]=i.useState(()=>new Set),us=JSON.stringify([u,L,K,M,ve,ce?.id??null]);i.useEffect(()=>{Tt(Re=>Re.size?new Set:Re)},[us]);const es=i.useCallback(Re=>{Tt(Ae=>Ae.has(Re)?Ae:new Set([...Ae,Re]))},[]),Os=i.useMemo(()=>{if(!bt.size)return et;const Re=new Set(et.map(Xe=>Xe.id)),Ae=w.filter(Xe=>bt.has(Xe.id)&&!Re.has(Xe.id));return Ae.length?[...et,...Ae]:et},[et,bt,w]),$s=()=>Sc(),ae=jb(a?.trial_end_date),ye={email:t,onLogout:n,onRecategorize:()=>G(m),onBulkRecategorize:()=>Y(l),onOpenDailyReview:e?()=>rt(!1):void 0,unlabeledTasksCount:j?.length||0,paymentStatus:Ly(a),billingPlan:Ay(a),daysLeft:ae},ze=s.jsx(Qy,{apiKey:e,selectedLabels:u,onLabelsChange:re("label",f),selectedProjects:L,onProjectsChange:re("project",A),dateFilter:M,onDateFilterChange:re("date",P),selectedPriorities:K,onPrioritiesChange:re("priority",X),isPending:D,onRemoveLabel:p,onRemoveProject:H,selectedTodoistFilter:ce,onSelectTodoistFilter:re("todoist_filter",oe),hideSubtasks:ve,onHideSubtasksChange:re("subtasks",Ce)});return s.jsxs(pk,{firstRun:b,tasks:w,unlabeledTasks:j||[],tasksReady:N,fetchFailed:!!v,paymentStatus:a?.payment_status,categorizeSheetOpen:d,markOnboardingComplete:x,children:[s.jsx($C,{onNeeded:()=>ue(!0)}),s.jsx(FC,{shouldPrompt:me,ready:!!e&&!C&&N&&!g&&b.checked,markPrompted:q,open:()=>{pe("daily_review_opened",{auto:!0}),ft(!1),Me(!0)}}),s.jsx(Fu,{features:qu,children:s.jsxs("div",{className:o?"min-h-screen":"min-h-screen bg-gradient-to-b from-background to-accent/5 max-md:bg-none",children:[s.jsx(Cb,{onProfileUpdate:r}),s.jsx(Fb,{}),s.jsxs("div",{className:o?"mx-auto w-full max-w-[1760px] px-0 py-0":"mx-auto w-full max-w-[2480px] px-0 py-0 md:px-6 md:py-4 xl:px-10",children:[s.jsx("div",{id:"matrix-top","aria-hidden":!0}),o?s.jsx(DC,{...ye}):s.jsx(_e.div,{initial:{opacity:0,y:-10},animate:{opacity:1,y:0},transition:{duration:.3},className:"relative z-30",children:s.jsx(PS,{...ye})}),s.jsxs("div",{className:"mx-gutter",children:[s.jsx(Gt,{children:!e&&s.jsx(Bb,{onSuccess:le})}),e&&s.jsx(SC,{})]}),e&&s.jsx(Nw,{value:Q,children:s.jsx(aC,{apiKey:e,hierarchy:Q,visibleTasks:Os,revealedIds:bt,onRevealHidden:es,children:s.jsx(MN,{value:he,children:s.jsx(kv,{focusTaskIds:U,firstOpenId:be,children:s.jsx(yv,{apiKey:e,doFirstTaskIds:V,children:s.jsxs(Vb,{children:[!o&&ze,v&&s.jsx("div",{className:"mx-gutter",children:s.jsx(Hb,{error:v,onRetry:T})}),o&&s.jsx(RC,{unlabeledTasksCount:ye.unlabeledTasksCount,onSort:ye.onRecategorize,paymentStatus:ye.paymentStatus,daysLeft:ae}),s.jsx(uC,{focusTasks:ne,tasks:w,tasksAreFiltered:k,isLoadingTasks:C,apiKey:e,onTaskUpdate:T,onClearFocus:We,onEditFocus:()=>rt(!0)}),o&&ze,s.jsx(XN,{isLoading:!N&&(C||o&&!!e),tasks:Os,selectedLabels:u,apiKey:e,onTaskUpdate:T,isFocusMode:y,onToggleFocusMode:()=>J(y,R),unlabeledTasks:j||[],onCreateTask:$s}),($||O)&&s.jsx(i.Suspense,{fallback:null,children:s.jsx(LC,{showLabelingSheet:d,setShowLabelingSheet:m,unlabeledTasks:j||[],apiKey:e,fetchTasks:T,showBulkRecategorySheet:c,setShowBulkRecategorySheet:l,categorizedTasks:ge})}),s.jsx(PC,{tasks:w}),s.jsx(JS,{tasks:w,unlabeledTasks:j||[],apiKey:e,removeTasksOptimistic:Le,onTaskUpdate:T}),(Se||$t)&&s.jsx(i.Suspense,{fallback:null,children:s.jsx(MC,{open:Se,onOpenChange:Me,tasks:w,apiKey:e,onTaskUpdate:T,completeReview:xe,ski
32pReview:ke,initialStep:Je?"pick":"triage",initialSelectedIds:Je?ne.map(Re=>Re.id):void 0})})]})})})})})}),h&&s.jsx(i.Suspense,{fallback:null,children:s.jsx(IC,{onClose:I})}),s.jsx(Sx,{})]})]})})]})},$C=({onNeeded:e})=>{const{starterSheet:t}=Ot(),n=!!t,a=i.useRef(e);return a.current=e,i.useEffect(()=>{n&&a.current()},[n]),null},FC=({shouldPrompt:e,ready:t,markPrompted:n,open:a})=>{const{holdsDailyReview:r}=Ot(),o=i.useRef(!1),c=i.useRef(a);return c.current=a,i.useEffect(()=>{!e||o.current||!t||r||(o.current=!0,n(),c.current())},[e,t,r,n]),null};class qC extends i.Component{state={hasError:!1,error:null};static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,n){pe("error_shown",{kind:"other"}),this.props.onError&&this.props.onError(t),setTimeout(()=>{this.setState({hasError:!1,error:null})},2e3)}render(){return this.state.hasError?s.jsx(hc,{className:"m-8",children:s.jsxs(pc,{className:"p-6 text-center",children:[s.jsx("h2",{className:"text-lg font-semibold text-destructive mb-2",children:"Something went wrong"}),s.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:this.state.error?.message||"An error occurred while loading"}),s.jsx("button",{onClick:()=>Ky(this.state.error)?window.location.reload():this.setState({hasError:!1,error:null}),className:"px-4 py-2 text-sm font-medium rounded-md bg-primary text-primary-foreground hover:bg-primary/90",children:"Try Again"})]})}):this.props.children}}const lp=({apiKey:e,email:t,onLogout:n})=>{const{toast:a}=He(),r=o=>{a({title:"Error",description:"An error occurred in the matrix view. Please try refreshing.",variant:"destructive"})};return s.jsx(qC,{onError:r,children:s.jsx(OC,{apiKey:e,email:t,onLogout:n})})};lp.displayName="MatrixLayout";const zC=Ue.memo(lp),UC=i.lazy(()=>Ne(()=>import("./UpgradePrompt-CifKKiPm.js"),__vite__mapDeps([35,1,2,3,25,24,12,4])).then(e=>({default:e.UpgradePrompt}))),dp=({apiKey:e,email:t,onLogout:n})=>{He();const a=at(),r=i.useCallback(()=>{a.invalidateQueries(),n()},[n,a]),{data:o,isLoading:c}=it({queryKey:["profile"],queryFn:async()=>{const{data:{user:l}}=await B.auth.getUser();if(!l)return null;const{data:d,error:m}=await B.from("profiles").select("*").eq("id",l.id).single();if(m)throw m;return d},retry:1,staleTime:300*1e3,refetchOnWindowFocus:!1});return c?s.jsx(Bt,{message:"Loading matrix view..."}):o?.payment_status==="expired"?s.jsx(i.Suspense,{fallback:s.jsx(Bt,{message:"Loading..."}),children:s.jsx(UC,{kind:gm(o)})}):s.jsx(te.div,{initial:{opacity:0}
32,animate:{opacity:1},transition:{duration:.15,ease:"easeOut"},children:s.jsx(zC,{apiKey:e,email:t,onLogout:r})})};dp.displayName="Matrix";const BC=i.memo(dp),HC=i.lazy(()=>Ne(()=>import("./ApiKeyManager-VatIB6Wy.js"),__vite__mapDeps([36,1,2,4,3]))),VC=({apiKey:e,user:t,onLogout:n})=>{const a=Fe();return e?s.jsx("div",{className:"min-h-screen bg-background",children:s.jsx("div",{className:a?"max-w-7xl mx-auto p-0":"mx-auto py-6",children:s.jsx(BC,{apiKey:e,email:t.email,onLogout:n})})}):s.jsx("div",{className:"min-h-screen bg-background",children:s.jsx("div",{className:"max-w-7xl mx-auto p-6",children:s.jsx(i.Suspense,{fallback:null,children:s.jsx(HC,{onApiKeySubmit:()=>{}})})})})},KC=i.lazy(()=>Ne(()=>import("./LandingPage-BZz1aGrd.js"),__vite__mapDeps([37,1,2,4,38,3,33,24,12])).then(e=>({default:e.LandingPage}))),YC=i.lazy(()=>Ne(()=>import("./UpgradePrompt-CifKKiPm.js"),__vite__mapDeps([35,1,2,3,25,24,12,4])).then(e=>({default:e.UpgradePrompt}))),WC=i.lazy(()=>Ne(()=>import("./ApiKeyManager-VatIB6Wy.js"),__vite__mapDeps([36,1,2,4,3]))),GC=i.lazy(()=>Ne(()=>import("./NPSSurvey-DNw8ssZI.js"),__vite__mapDeps([39,1,2,14,3,4]))),QC=()=>{const[e,t]=i.useState(null),[n,a]=i.useState(null),{session:r,isLoading:o}=we.useSessionContext(),{connectionStatus:c,checkConnectionStatus:l}=wm(),{toast:d}=He(),m=Fe(),u=i.useRef(!1),f=async()=>{try{await vx(),await B.auth.signOut(),a(null),t(null)}catch{ht("Logout error","auth",1e4),d({title:"Couldn't log out",description:"Please try again.",variant:"destructive"})}},p=i.useCallback(N=>{a(N),N?.todoist_access_token&&t(N.todoist_access_token)},[]),h=i.useCallback(N=>{N&&t(N)},[]),{isLoading:g,hasError:b,retry:x}=jx({onProfileUpdate:p,onApiKeyFound:h});i.useEffect(()=>{if(!r?.user||u.current||!l)return;(async()=>{try{await l()}catch{ht("Todoist connection verification failed","auth",6e4),d({title:"Connection check failed",description:"Couldn't verify your Todoist connection — tasks may not load. Use 'Reconnect Todoist' in the header if they don't.",variant:"destructive"})}finally{u.current=!0}})()},[r,l,d]);const[,y]=i.useState(0),w=i.useCallback(()=>Sb(n),[n]);i.useEffect(()=>{if(n?.payment_status!=="trial"||!n.trial_end_date)return;
32const N=new Date(n.trial_end_date).getTime()-Date.now();if(!(N>0)||N>2**31-1)return;const C=window.setTimeout(()=>y(v=>v+1),N+1e3);return()=>window.clearTimeout(C)},[n?.payment_status,n?.trial_end_date]);const k=o||g;if(i.useEffect(()=>{c==="connected"&&n?.todoist_access_token&&!e&&t(n.todoist_access_token)},[c,n,e]),k)return s.jsx(Bt,{message:"Loading profile..."});if(!r)return s.jsx(i.Suspense,{fallback:s.jsx(Bt,{message:"Loading..."}),children:s.jsx(KC,{price:lt.lifetime.price??void 0})});if(!e&&b)return s.jsxs("div",{className:"min-h-screen flex flex-col items-center justify-center gap-4 bg-background p-6 text-center",children:[s.jsx("p",{className:"text-muted-foreground",children:"Couldn't load your account. Check your connection and try again."}),s.jsx("button",{type:"button",onClick:x,className:"rounded-md border border-border px-4 py-2 text-sm font-medium hover:bg-muted",children:"Try again"})]});if(!e&&(!n||w()))return s.jsx(i.Suspense,{fallback:s.jsx(Bt,{message:"Loading..."}),children:s.jsx(WC,{onApiKeySubmit:t})});if(!w()){const N=new URLSearchParams;n?.trial_end_date&&N.set("trialEndDate",n.trial_end_date);const C=N.toString()?`?${N.toString()}`:"";return window.history.replaceState(null,"",`${window.location.pathname}${C}`),s.jsx(i.Suspense,{fallback:s.jsx(Bt,{message:"Loading..."}),children:s.jsx(YC,{kind:gm(n)})})}return s.jsx("div",{className:`min-h-screen bg-background safe-padding ${m?"touch-gap":""}`,children:s.jsxs("div",{className:"mobile-vh",children:[s.jsx(VC,{apiKey:e||"",user:r.user,onLogout:f}),s.jsx(i.Suspense,{fallback:null,children:s.jsx(GC,{})})]})})},yi="eis:attribution",JC=/(^|\.)(accounts\.google\.com|todoist\.com|gumroad\.com|supabase\.co)$/;function XC(e,t){try{if(!e)return null;const n=new URL(e).hostname.toLowerCase().replace(/^www\./,""),a=t.toLowerCase().replace(/^www\./,"");return!n||n===a||JC.test(n)?null:Sr(n)}catch{return null}}function ZC(e,t,n){const a={};try{const o=new URLSearchParams(e);for(const c of["utm_source","utm_medium","utm_campaign"]){const l=Sr(o.get(c));l&&(a[c]=l)}}catch{}const r=XC(t,n);return r&&(a.ref=r),a}const wi=e=>!!e&&Object.keys(e).length>0;function e1(e,t){return wi(e)?e:t}function vi(){try{const e=localStorage.getItem(yi);if(!e)return{};const t=JSON.parse(e),n={};for(const a of["utm_source","utm_medium","utm_campaign","ref"]){const r=Sr(t?.[a]);r&&(n[a]=r)}return n}catch{return{}}}function t1(){try{const e=localStorage.getItem(yi),t=ZC(window.location.search,document.referrer,window.location.hostname),n=e1(e?vi():null,t);(!e||!wi(vi())&&wi(n))&&localStorage.setItem(yi,JSON.stringify({...n,at:new Date().toISOString().slice(0,10)}))}catch{}}const Ud=24*36e5,s1=10*6e4;function n1(e){const t=e.hint??(e.provider==="google"?"google":"email"),n=e.createdAt?Date.parse(e.createdAt):NaN;if(Number.isFinite(n)&&e.now-n<Ud&&e.now-n>-Ud&&!e.signedUpReported)return{signedUp:t,signedIn:null};const r=e.authAt==null||e.now-e.authAt<s1;return e.event==="SIGNED_IN"&&!e.sessionSeen&&r?{signedUp:null,signedIn:t}:{signedUp:null,signedIn:null}}function up(e){try{const t=e?.split(".")[1];if(!t)return null;const n=JSON.parse(atob(t.replace(/-/g,"+").replace(/_/g,"/")));return n&&typeof n=="object"?n:null}catch{return null}}function a1(e){const t=up(e);return typeof t?.session_id=="string"?t.session_id:null}function r1(e){const t=up(e)?.amr;if(!Array.isArray(t))return null;const n=t.map(a=>Number(a?.timestamp)).filter(a=>Number.isFinite(a)&&a>0);return n.length?Math.max(...n)*1e3:null}const Dc="eis:auth-method",o1="eis:signed-up:",mp="eis:seen-sessions",Bd="eis:app-opened";function i1(e){try{sessionStorage.setItem(Dc,e)}catch{}}const c1=()=>{try{const e=sessionStorage.getItem(Dc);return e==="google"||e==="email"||e==="todoist"?e:null}catch{return null}},fp=()=>{try{const e=JSON.parse(localStorage.getItem(mp)||"[]");return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}catch{return[]}},l1=e=>{try{const t=fp().filter(n=>n!==e);t.push(e),localStorage.setItem(mp,JSON.stringify(t.slice(-20)))}catch{}},d1=e=>{try{return localStorage.getItem(e)==="1"}catch{return!1}},u1=e=>{try{localStorage.setItem(e,"1")}catch{}};let ki=null;const m1={async send(e,{keepalive:t}){if(!ki)return;if(t){await fetch(`${$i}/rest/v1/rpc/track_events`,{method:"POST",keepalive:!0,headers:{"Content-Type":"application/json",apikey:Ga,Authorization:`Bearer ${ki}`},body:JSON.stringify({p:e})});return}const{error:n}=await B.rpc("track_events",{p:e});if(n)throw n}};function f1(e,t){ki=t?.access_token??null;const n=t?.user??null;if(tt.identify(n?.id??null),!n)return;const a=a1(t?.access_token),r=!!a&&fp().includes(a),o=o1+n.id,c=n1({event:e,createdAt:n.created_at,provider:n.app_metadata?.provider??null,now:Date.now(),signedUpReported:d1(o),sessionSeen:r,authAt:r1(t?.access_token),hint:c1()});if(c.signedUp?(u1(o),tt.track("signed_up",{method:c.signedUp,...vi()})):c.signedIn&&tt.track("signed_in",{method:c.signedIn}),a&&l1(a),c.signedUp||c.signedIn)try{sessionStorage.removeItem(Dc)}catch{}try{sessionStorage.getItem(Bd)!==n.id&&(sessionStorage.setItem(Bd,n.id),tt.track("app_opened",{layout:Hn()}))}catch{tt.track("app_opened",{layout:Hn()})}}let Hd=!1;function h1(){if(!Hd){Hd=!0;try{t1(),tt.setTransport(m1),B.auth.onAuthStateChange((e,t)=>{try{f1(e,t)}catch{}}),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&tt.flush({keepalive:!0})}),window.addEventListener("pagehide",()=>{tt.flush({keepalive:!0})})}catch{}}}const ji="https://eisenhowertodoist.com/auth/callback",zr="todoist_login_state",ks="todoist_oauth_state",p1=1800*1e3,hp=e=>{if(!e)return null;try{return JSON.parse(e)}catch{return null}},pp=e=>{const t=hp(e);return!t||typeof t.state!="string"||!t.state||typeof t.timestamp!="number"?null:{state:t.state,timestamp:t.timestamp,redirectUri:typeof t.redirectUri=="string"?t.redirectUri:ji}},g1=(e,t,n)=>{if(!pp(t))return!1;const a=new URLSearchParams(e);if(!a.has("code")&&!a.has("state")&&!a.has("error"))return!1;const r=a.get("state"),o=hp(n);return!(r&&o&&o.state===r)},x1=(e,t,n)=>{const a=new URLSearchParams(e),r=a.get("error");
32if(r)return{ok:!1,code:r==="access_denied"?"cancelled":"todoist_error"};const o=a.get("code"),c=a.get("state");return!t||!o||!c||c!==t.state?{ok:!1,code:"state_mismatch"}:n-t.timestamp>p1?{ok:!1,code:"expired"}:{ok:!0,code:o,redirectUri:t.redirectUri}},Vd={cancelled:{title:"Sign-in cancelled",message:"You didn't approve access in Todoist. You can try again any time.",retryable:!0,offerSignIn:!1},state_mismatch:{title:"This sign-in didn't match",message:"For your safety we stopped here. Try again.",retryable:!0,offerSignIn:!1},expired:{title:"Sign-in timed out",message:"That took a little too long. Try again.",retryable:!0,offerSignIn:!1},invalid_code:{title:"Sign-in timed out",message:"That Todoist sign-in expired. Try again.",retryable:!0,offerSignIn:!1},todoist_error:{title:"Todoist couldn't sign you in",message:"Todoist returned an error. Try again in a minute.",retryable:!0,offerSignIn:!1},todoist_unavailable:{title:"We couldn't reach Todoist",message:"Todoist didn't answer. Try again in a minute.",retryable:!0,offerSignIn:!1},email_exists:{title:"You already have an account",message:"An account with this email already exists. Sign in with your usual method, then connect Todoist.",retryable:!1,offerSignIn:!0},link_unverified:{title:"Sign in with your usual method",message:"We couldn't confirm the account this Todoist is linked to. Sign in with your usual method, then reconnect Todoist.",retryable:!1,offerSignIn:!0},ambiguous_link:{title:"Sign in with your usual method",message:"This Todoist is linked to more than one account. Sign in with your usual method.",retryable:!1,offerSignIn:!0},todoist_in_use:{title:"This Todoist is already in use",message:"It is connected to another account. Sign in to that account with your usual method.",retryable:!1,offerSignIn:!0},email_unverified:{title:"Verify your email in Todoist",message:"Please verify your email in Todoist first, then try again. Or sign in with Google or email instead.",retryable:!0,offerSignIn:!0},no_email:{title:"No email on your Todoist account",message:"Sign in with Google or email, then connect Todoist.",retryable:!1,offerSignIn:!0},rate_limited:{title:"Too many attempts",message:"Wait an hour, then try again.",retryable:!1,offerSignIn:!0},network:{title:"No connection",message:"Check your internet connection and try again.",retryable:!0,offerSignIn:!1},session_failed:{title:"We couldn't finish signing you in",message:"Your account is fine. Try again.",retryable:!0,offerSignIn:!1},server_error:{title:"Something went wrong",message:"Something went wrong on our side. Try again.",retryable:!0,offerSignIn:!1}},Xs=e=>({ok:!1,code:e,...Vd[e]??Vd.server_error}),Pa=(e,t=!1)=>{if(t)return Xs("network");if(!e||typeof e!="object")return Xs("server_error");const n=e;return n.ok===!0&&typeof n.token_hash=="string"&&n.token_hash?{ok:!0,tokenHash:n.token_hash,newAccount:n.new_account===!0}:Xs(typeof n.code=="string"?n.code:"server_error")},b1=()=>Array.from(crypto.getRandomValues(new Uint8Array(32)),e=>e.toString(16).padStart(2,"0")).join(""),y1=(e,t)=>{const n=new URL(e);return n.searchParams.set("state",t),n.toString()},w1=e=>{try{const t=new URL(e);return t.protocol==="https:"&&(t.hostname==="todoist.com"||t.hostname==="app.todoist.com")&&t.pathname==="/oauth/authorize"}catch{return!1}};async function gp(){const{data:e,error:t}=await B.functions.invoke("todoist-oauth-init",{body:{redirectUri:ji}});if(t||typeof e?.authUrl!="string"||!w1(e.authUrl))throw new Error("We couldn't reach Todoist. Try again in a minute.");const n=b1(),a={state:n,timestamp:Date.now(),redirectUri:ji};try{sessionStorage.setItem(zr,JSON.stringify(a))}catch{throw new Error("Your browser blocked storage this sign-in needs. Try Google or email instead.")}window.location.assign(y1(e.authUrl,n))}const v1=({className:e})=>s.jsxs("svg",{viewBox:"0 0 24 24","aria-hidden":"true",className:e,children:[s.jsx("rect",{width:"24",height:"24",rx:"5",fill:"#fff"}),s.jsx("path",{d:"M5 8.2l1.4-.8 5.6 3.2 5.6-3.2 1.4.8-7 4zM5 12.2l1.4-.8 5.6 3.2 5.6-3.2 1.4.8-7 4zM5 16.2l1.4-.8 5.6 3.2 5.6-3.2 1.4.8-7 4z",fill:"#E44332"})]}),AT=({onError:e})=>{const[t,n]=i.useState(!1);i.useEffect(()=>{const r=o=>{o.persisted&&n(!1)};return window.addEventListener("pageshow",r),()=>window.removeEventListener("pageshow",r)},[]);const a=async()=>{n(!0);try{await gp()}catch(r){n(!1),e(r instanceof Error?r.message:"We couldn't reach Todoist. Try again in a minute.")}};return s.jsxs("button",{type:"button",onClick:a,disabled:t,"data-testid":"todoist-signin",className:"mx-auto flex h-10 w-full max-w-[400px] items-center justify-center gap-2.5 rounded-[4px] bg-[#E44332] px-3 text-sm font-medium text-white transition-colors hover:bg-[#CF3520] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:opacity-80",children:[t?s.jsx(kt,{className:"h-[18px] w-[18px] animate-spin","aria-hidden":!0}):s.jsx(v1,{className:"h-[18px] w-[18px]"}),t?"Opening Todoist…":"Continue with Todoist"]})},k1=()=>{try{return pp(sessionStorage.getItem(zr))}catch{return null}},j1=()=>{try{sessionStorage.removeItem(zr)}catch{}},N1=()=>{const e=Xt(),{toast:t}=He(),[n,a]=i.useState(null),[r,o]=i.useState(!1),c=i.useRef(!1);i.useEffect(()=>{c.current||(c.current=!0,(async()=>{const d=x1(window.location.search,k1(),Date.now());if(j1(),window.history.replaceState(null,"",window.location.pathname),!d.ok){a(Xs(d.code));return}let m;try{const{data:h,error:g}=await B.functions.invoke("todoist-login",{body:{code:d.code,redirectUri:d.redirectUri}});g?m=g instanceof Ug?Pa(await g.context.json().catch(()=>null)):Pa(null,!0):m=Pa(h)}catch{m=Pa(null,!0)}if(!m.ok){a(m);return}i1("todoist");const{data:u,error:f}=await B.auth.verifyOtp({token_hash:m.tokenHash,type:"magiclink"});if(f||!u.session){a(Xs("session_failed"));return}const p=u.session.user;if(Pt(p.id,p.email,"login",{method:"todoist",new_account:m.newAccount,at:new Date().toISOString()}).catch(()=>{}),m.newAccount)try{sessionStorage.setItem(Cr,"1")}catch{}else t({title:"Signed in",description:"Welcome back."});e("/",{replace:!0})})())},[e,t]);const l=async()=>{o(!0);try{await gp()}catch{o(!1),a(Xs("todoist_unavailable"))}};return n?s.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background px-4 py-8",children:s.jsxs("div",{role:"alert","data-testid":"todoist-login-error","data-code":n.code,className:"w-full max-w-md 
32space-y-5 rounded-2xl border bg-card p-6 shadow-sm",children:[s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx(Wt,{className:"mt-0.5 h-5 w-5 shrink-0 text-muted-foreground","aria-hidden":!0}),s.jsxs("div",{className:"space-y-1.5",children:[s.jsx("h1",{className:"text-lg font-semibold text-foreground",children:n.title}),s.jsx("p",{className:"text-sm text-muted-foreground",children:n.message})]})]}),s.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row-reverse",children:[n.retryable&&s.jsxs(W,{onClick:l,disabled:r,className:"h-11 sm:h-10 sm:flex-1",children:[r?s.jsx(kt,{className:"mr-2 h-4 w-4 animate-spin","aria-hidden":!0}):null,"Try again"]}),s.jsx(W,{variant:n.retryable?"outline":"default",onClick:()=>e(n.offerSignIn?"/?signin=1":"/",{replace:!0}),className:"h-11 sm:h-10 sm:flex-1",children:n.offerSignIn?"Sign in another way":"Back"})]})]})}):s.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background p-6","data-testid":"todoist-login-pending",children:s.jsxs("div",{className:"space-y-4 text-center",children:[s.jsx(kt,{className:"mx-auto h-8 w-8 animate-spin text-primary","aria-hidden":!0}),s.jsx("h1",{className:"text-xl font-semibold text-foreground",children:"Signing you in with Todoist"}),s.jsx("p",{className:"text-sm text-muted-foreground",children:"This takes a few seconds."})]})})};class xp extends Error{}const bp=async()=>{const{data:{session:e},error:t}=await B.auth.getSession();if(!e||t)throw new xp("Not signed in");localStorage.removeItem(ks);const n="https://eisenhowertodoist.com/auth/callback",{data:a,error:r}=await B.functions.invoke("todoist-oauth-init",{body:{redirectUri:n}});if(r)throw r;if(!a?.authUrl||!a?.state)throw new Error("Invalid response from OAuth initialization");const o={state:a.state,timestamp:Date.now(),redirectUri:n,destination:"/matrix",origin:"https://eisenhowertodoist.com",userId:e.user.id};localStorage.setItem(ks,JSON.stringify(o)),window.location.href=a.authUrl},PT=({onSuccess:e})=>{const[t,n]=i.useState(!1),{toast:a}=He(),r=Xt();i.useEffect(()=>{if(window.location.hostname==="eisenhowertodoist.netlify.app"){const m=`https://eisenhowertodoist.com${window.location.pathname}${window.location.search}`;window.location.replace(m);return}const c=new URLSearchParams(window.location.search),l=c.get("error"),d=c.get("error_description");l&&(a({title:"Couldn't connect Todoist",description:d||"Please try again.",variant:"destructive"}),window.history.replaceState({},document.title,window.location.pathname))},[a]);const o=async()=>{n(!0),Qu("connect_todoist_clicked",{via:"screen"});try{await bp()}catch(c){if(pe("connect_todoist_result",{result:"error",code:"init",via:"connect"}),c instanceof xp){a({title:"Please sign in first",description:"Sign in before connecting your Todoist account.",variant:"destructive"}),r("/");return}a({title:"Couldn't connect Todoist",description:Ja(c),variant:"destructive"})}finally{n(!1)}};return s.jsx(W,{onClick:o,disabled:t,className:"w-full",children:t?s.jsxs(s.Fragment,{children:[s.jsx(kt,{className:"mr-2 h-4 w-4 animate-spin"}),"Connecting…"]}):"Connect with Todoist"})},Rc="todoist:connect-notice",Kd=e=>{try{sessionStorage.setItem(Rc,JSON.stringify(e))}catch{}},OT=()=>{try{const e=sessionStorage.getItem(Rc);if(!e)return null;const t=JSON.parse(e);return t?.kind==="cancelled"?{kind:"cancelled"}:t?.kind==="failed"&&typeof t.message=="string"?{kind:"failed",message:t.message}:null}catch{return null}},$T=()=>{try{sessionStorage.removeItem(Rc)}catch{}},FT=e=>e.kind==="cancelled"?"Todoist wasn't connected. You can try again anytime.":`Todoist wasn't connected. ${e.message}`,Yd=(e,t)=>{try{return e().getItem(t)}catch{return null}},S1=()=>{const[e]=i.useState(()=>g1(window.location.search,Yd(()=>sessionStorage,zr),Yd(()=>localStorage,ks)));return e?s.jsx(N1,{}):s.jsx(T1,{})},C1=6e3,T1=()=>{const e=Xt(),{toast:t}=He(),[n,a]=i.useState(null),[r,o]=i.useState(!1),c=i.useRef(!1);i.useEffect(()=>{if(c.current)return;c.current=!0,(async()=>{const m=new URLSearchParams(window.location.search),u=m.get("code"),f=m.get("state"),p=m.get("error");
32if(window.history.replaceState(null,"",window.location.pathname),p==="access_denied"){pe("connect_todoist_result",{result:"cancelled",code:"denied",via:"connect"}),localStorage.removeItem(ks),Kd({kind:"cancelled"}),e("/",{replace:!0});return}if(!p&&!u&&!f){e("/",{replace:!0});return}let h="denied";try{if(p)throw new Error(m.get("error_description")||"Todoist didn't allow the connection. Please try again.");if(h="state",!u||!f)throw new Error("Todoist didn't send the connection back. Please try again.");const g=localStorage.getItem(ks);if(!g)throw new Error("No stored state found");const b=JSON.parse(g);if(b.state!==f)throw new Error("State mismatch - possible security issue");if(h="expired",Date.now()-b.timestamp>1800*1e3)throw new Error("Authentication session expired");h="no_session";const{data:{session:x},error:y}=await B.auth.getSession();if(y||!x)throw new Error("Authentication session not found");h="exchange";let w=null,k=null;try{const v=await B.functions.invoke("todoist-oauth-callback",{body:{code:u,state:f,redirectUri:b.redirectUri}});w=v.data,k=v.error}catch(v){throw new Error(v?.message?.includes("not valid JSON")?"Todoist connection service returned an unexpected response. Please try again.":v?.message||"Failed to connect to Todoist service")}if(k){const v=typeof k=="object"&&k.message?k.message:"Todoist connection failed";throw new Error(v)}if(h="no_token",!w?.access_token)throw new Error("No access token received");h="save";const{data:N,error:C}=await B.from("profiles").update({todoist_access_token:w.access_token,todoist_user_id:String(w.user?.id??""),todoist_user_name:w.user?.full_name??"",todoist_user_email:w.user?.email??x.user.email??""}).eq("id",x.user.id).select("has_completed_tour").maybeSingle();if(C)throw C;if(localStorage.removeItem(ks),pe("connect_todoist_result",{result:"ok",via:"connect"}),N?.has_completed_tour!==!0)try{sessionStorage.setItem(Cr,"1")}catch{}else t({title:"Todoist connected",description:"Your tasks are syncing."});e("/",{replace:!0})}catch(g){pe("connect_todoist_result",{result:"error",code:h,via:"connect"});const b=Ja(g);localStorage.removeItem(ks),Kd({kind:"failed",message:b}),a(b)}})()},[e,t]),i.useEffect(()=>{if(!n||r)return;const d=window.setTimeout(()=>e("/",{replace:!0}),C1);return()=>window.clearTimeout(d)},[n,r,e]);const l=async()=>{o(!0),Qu("connect_todoist_clicked",{via:"retry"});try{await bp()}catch(d){o(!1),a(Ja(d))}};return n?s.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background px-4 py-8",children:s.jsxs("div",{role:"alert","data-testid":"todoist-connect-error",className:"w-full max-w-md 
32space-y-5 rounded-2xl border bg-card p-6 shadow-sm",children:[s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx(Wt,{className:"mt-0.5 h-5 w-5 shrink-0 text-muted-foreground","aria-hidden":!0}),s.jsxs("div",{className:"space-y-1.5",children:[s.jsx("h1",{className:"text-lg font-semibold text-foreground",children:"Couldn't connect Todoist"}),s.jsx("p",{className:"text-sm text-muted-foreground",children:n}),!r&&s.jsx("p",{className:"text-xs text-muted-foreground",children:"Taking you back in a few seconds…"})]})]}),s.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row-reverse",children:[s.jsxs(W,{onClick:l,disabled:r,className:"h-11 sm:h-10 sm:flex-1",children:[r?s.jsx(kt,{className:"mr-2 h-4 w-4 animate-spin","aria-hidden":!0}):null,"Try again"]}),s.jsx(W,{variant:"outline",onClick:()=>e("/",{replace:!0}),className:"h-11 sm:h-10 sm:flex-1",children:"Back"})]})]})}):s.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background p-6","data-testid":"todoist-connect-pending",children:s.jsxs("div",{className:"space-y-4 text-center",children:[s.jsx(kt,{className:"mx-auto h-8 w-8 animate-spin text-primary","aria-hidden":!0}),s.jsx("h1",{className:"text-xl font-semibold text-foreground",children:"Connecting Todoist…"}),s.jsx("p",{className:"text-sm text-muted-foreground",children:"This takes a few seconds."})]})})},Ge="session",wt=1e4,Oa=3e4,Wd=6e4,Ns={init:{start:()=>ht("Session initialization started",Ge,wt),complete:e=>ht(`Session initialized: ${e?"User logged in":"No user"}`,Ge,wt),timeout:()=>Qs("Session initialization timed out, proceeding without session",Ge,wt),retry:(e,t)=>ht(`Retrying session initialization (${e}/${t})`,Ge,wt),error:e=>ON(`Session initialization error: ${e?.message||e}`,Ge,wt)},state:{change:(e,t)=>
32ht(`Auth state change: ${e} - ${t?"User present":"No user"}`,Ge,Wd),signIn:e=>ht(`User signed in${e?": "+e:""}`,Ge,wt),signOut:()=>ht("User signed out",Ge,wt)},refresh:{attempt:()=>Ma("Attempting session refresh",Ge,Oa),success:()=>Ma("Session refreshed successfully",Ge,Oa),error:e=>Qs(`Session refresh error: ${e?.message||e}`,Ge,wt)},tracking:{update:()=>Ma("Updating session activity",Ge,Oa),createSession:()=>ht("Creating new user session",Ge,wt),updateSession:()=>Ma("Updating existing user session",Ge,Oa),cleanup:()=>ht("Cleaning up user session",Ge,wt),error:(e,t)=>Qs(`Session tracking error (${e}): ${t?.message||t}`,Ge,wt)},activity:{userActive:e=>ht(`User session active${e?": "+e:""}`,Ge,Wd)}},Gd=2*6e4,_1=5*6e4,E1=6e4,D1=15e3,R1=10*6e4,I1=3e4,So=5,M1=3600;function L1(e){const t=e.now??(()=>Date.now());let n=!1,a=-1/0,r=-1/0,o=0,c=0,l=0,d=!1;const m=N=>{try{N()}catch{}};function u(N){if(n&&Number.isFinite(a)){const C=Math.min(N,a+E1);l+=Math.max(0,C-Math.max(o,a))}o=Math.max(o,N)}const f=N=>n&&N-a<_1;function p(N){r=N,m(e.heartbeat)}function h(N,C){const v=Math.min(M1,Math.floor(l/1e3/So)*So);v<So||(l=Math.max(0,l-v*1e3),c=N,m(()=>e.report(v,C)))}function g(N=!1){if(!d)return;const C=t(),v=!N&&f(C);u(C),a=C,n&&(!v&&C-r>=I1||C-r>=Gd)&&p(C)}function b(){if(!d)return;const N=t(),C=e.isVisible();C!==n&&(u(N),C?(n=!0,g(!0)):(n=!1,h(N,"hide")))}function x(){if(!d)return;const N=t();u(N),h(N,"hide")}function y(){if(!d)return;const N=t();u(N),f(N)&&N-r>=Gd&&p(N),N-c>=R1&&h(N,"interval")}function w(){if(d)return;d=!0;const N=t();o=N,c=N,l=0,a=-1/0,r=-1/0,n=e.isVisible(),n&&g(!0)}function k(){if(!d)return;const N=t();u(N),h(N,"stop"),d=!1}return{start:w,stop:k,input:()=>g(),visibilityChanged:b,leave:x,tick:y,state(){return{visible:n,lastInput:a,lastHeartbeat:r,activeMs:l,running:d}}}}const A1=2,Ni="eis:presence-row:",Qd=["pointerdown","pointermove","keydown","touchstart","wheel","scroll"],P1=1e3,Fn=e=>!!e&&(e.code==="PGRST301"||e.code==="42501"||e.message?.includes("403")||e.message?.includes("permission denied")||e.message?.includes("row-level security")||e.status===403||e.statusCode===403);let cs=null,js=null,Gs=null,Co=0,To=null,Si=null;const O1=e=>{try{return sessionStorage.getItem(Ni+e)}catch{return null}},Ci=(e,t)=>{try{t?sessionStorage.setItem(Ni+e,t):sessionStorage.removeItem(Ni+e)}catch{}};async function $1(){const e=cs;if(e)try{if(js){const{data:r,error:o}=await B.from("user_sessions").update({last_active:new Date().toISOString()}).eq("id",js).select("id");if(o){if(Fn(o))return;throw o}if(Array.isArray(r)&&r.length>0){Ns.tracking.updateSession();return}js=null,Ci(e.id,null)}const t={userAgent:navigator.userAgent,language:navigator.language,platform:navigator.platform,screenWidth:window.screen.width,screenHeight:window.screen.height,timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone,presence:A1},{data:n,error:a}=await B.from("user_sessions").insert({user_id:e.id,email:e.email,client_info:t}).select("id").single();if(a){if(Fn(a))return;throw a}n?.id&&cs?.id===e.id&&(Ns.tracking.createSession(),js=n.id,Ci(e.id,n.id))}catch(t){Fn(t)||Ns.tracking.error("updateSession",t)}}function F1(){To||(To=$1().finally(()=>{To=null}))}function q1(e,t){tt.track("session_active",{seconds:e,surface:Hn()})&&t!=="interval"&&tt.flush({keepalive:!0})}function z1(e){let t=0;const n=()=>{const l=Date.now();l-t<P1||(t=l,e.input())},a=()=>e.visibilityChanged(),r=()=>e.leave(),o={passive:!0,capture:!0};for(const l of Qd)document.addEventListener(l,n,o);document.addEventListener("visibilitychange",a),window.addEventListener("pagehide",r);const c=window.setInterval(()=>e.tick(),D1);return()=>{for(const l of Qd)document.removeEventListener(l,n,o);document.removeEventListener("visibilitychange",a),window.removeEventListener("pagehide",r),window.clearInterval(c)}}function U1(e){cs?.id===e.id&&Gs||(Ic(),cs=e,js=O1(e.id),Gs=L1({isVisible:()=>document.visibilityState==="visible",heartbeat:F1,report:q1}),Si=z1(Gs),Gs.start())}function Ic(){Gs?.stop(),Si?.(),Si=null,Gs=null}async function Jd(){const e=js,t=cs?.id;if(Ic(),cs=null,js=null,t&&Ci(t,null),!!e)try{Ns.tracking.cleanup();const{error:n}=await B.from("user_sessions").delete().eq("id",e);n&&!Fn(n)&&Ns.tracking.error("cleanupSession",n)}catch(n){Fn(n)||Ns.tracking.error("cleanupSession",n)}}function B1(){const{session:e}
32=we.useSessionContext(),t=e?.user?.id??null,n=e?.user?.email??null;return i.useEffect(()=>(Co++,()=>{Co--,Co===0&&(Ic(),cs=null)}),[]),i.useEffect(()=>{t?U1({id:t,email:n}):cs&&Jd()},[t,n]),{cleanup:Jd}}const H1=()=>{const{session:e}=we.useSessionContext();return B1(),i.useEffect(()=>{if(e?.user)try{Ns.activity.userActive(e.user.email)}catch{}},[e]),null},V1=2e3,K1=()=>{const[e,t]=i.useState(!0),[n,a]=i.useState(null),[r,o]=i.useState(!1);return i.useEffect(()=>{let c=!0;const l=(f=null)=>{c&&(a(f),t(!1),o(!0))},d=setTimeout(()=>l(),V1);(async()=>{try{const{data:{session:f}}=await B.auth.getSession();if(!c)return;clearTimeout(d),l(f)}catch{if(!c)return;clearTimeout(d),l()}})();const{data:{subscription:u}}=B.auth.onAuthStateChange((f,p)=>{c&&(f==="SIGNED_OUT"?a(null):(f==="SIGNED_IN"||f==="USER_UPDATED"||f==="INITIAL_SESSION")&&a(p),t(!1),o(!0))});return()=>{c=!1,clearTimeout(d),u.unsubscribe()}},[]),{isLoading:e,loadingMessage:"Loading...",session:n,isInitialized:r}},Y1=i.lazy(()=>Ne(()=>import("./Statistics-C6kF8i-x.js"),__vite__mapDeps([27,1,2,3,4,17,28,29]))),W1=i.lazy(()=>Ne(()=>import("./Achievements-DpW-_NoR.js"),__vite__mapDeps([40,1,2,3,4]))),G1=i.lazy(()=>Ne(()=>import("./Checkout-CVNi1jve.js"),__vite__mapDeps([41,1,2,25,24,12,3,4,11]))),Q1=i.lazy(()=>Ne(()=>import("./ResetPassword-0NCm7ytb.js"),__vite__mapDeps([42,1,2,38,4,3]))),J1=i.lazy(()=>Ne(()=>import("./Admin-BAtFewQU.js"),__vite__mapDeps([43,1,2,3,4]))),X1=i.lazy(()=>Ne(()=>import("./CheckoutStatus-BmBXbUFj.js"),__vite__mapDeps([44,1,2,3,11,24,12,4,45])).then(e=>({default:e.CheckoutStatus}))),Z1=new Rg({defaultOptions:{queries:{retry:1,refetchOnWindowFocus:!1,staleTime:300*1e3,gcTime:1800*1e3}}});ua.setEnabled(!1);const eT=()=>{const{isLoading:e,loadingMessage:t,session:n,isInitialized:a}=K1();return i.useEffect(()=>{ht("Application initialized","app",36e5)},[]),i.useEffect(()=>{const r=l=>{if(!l)return!1;const d=l.tagName;return d==="INPUT"||d==="TEXTAREA"||l.isContentEditable===!0},o=()=>{const l=document.activeElement;r(l)&&l.blur();const d=document.body,m=d.style;m.position==="fixed"&&(m.position=""),m.overflow==="hidden"&&(m.overflow=""),m.top&&(m.top=""),m.width==="100%"&&(m.width=""),m.pointerEvents==="none"&&(m.pointerEvents=""),m.paddingRight&&(m.paddingRight=""),d.removeAttribute("data-scroll-locked"),d.removeAttribute("data-rrul-scroll-blocked"),d.removeAttribute("inert"),d.removeAttribute("aria-hidden"),document.documentElement.classList.remove("task-focus-active")},c=l=>{l.persisted&&o()};return window.addEventListener("pageshow",c),()=>window.removeEventListener("pageshow",c)},[]),e?s.jsx(Bt,{message:t}):s.jsx(we.SessionContextProvider,{supabaseClient:B,initialSession:n,children:s.jsx(zu,{reducedMotion:"user",children:s.jsx(pw,{children:s.jsx(Ig,{client:Z1,children:s.jsxs(Ls,{children:[s.jsx(Mg,{children:a?s.jsxs(s.Fragment,{children:[s.jsx(H1,{}),s.jsx(i.Suspense,{fallback:null,children:s.jsx(X1,{})}),s.jsx(i.Suspense,{fallback:s.jsx(Bt,{message:"Loading…"}),children:s.jsxs(Lg,{children:[s.jsx(zt,{path:"/",element:s.jsx(QC,{})}),s.jsx(zt,{path:"/matrix",element:s.jsx(Ac,{to:"/",replace:!0})}),s.jsx(zt,{path:"/statistics",element:s.jsx(Y1,{})}),s.jsx(zt,{path:"/achievements",element:s.jsx(W1,{})}),s.jsx(zt,{path:"/auth/callback",element:s.jsx(S1,{})}),s.jsx(zt,{path:"/checkout",element:s.jsx(G1,{})}),s.jsx(zt,{path:"/reset-password",element:s.jsx(Q1,{})}),s.jsx(zt,{path:"/admin",element:s.jsx(J1,{})}),s.jsx(zt,{path:"*",element:s.jsx(Ac,{to:"/",replace:!0})})]})})]}):s.jsx(Bt,{message:"Initializing application..."})}),s.jsx(ax,{})]})})})})})};function Tn(e){}function tT(){try{Ag(Tn),Pg(Tn),Og(Tn),$g(Tn),Fg(Tn)}catch{}}function sT(){if(typeof window>"u")return;let e=!1;const t=()=>{e=!1,window.scrollX!==0&&window.scrollTo({left:0,top:window.scrollY,behavior:"instant"}),document.body&&document.body.scrollLeft!==0&&(document.body.scrollLeft=0)},n=()=>{e||window.scrollX===0&&(!document.body||document.body.scrollLeft===0)||(e=!0,requestAnimationFrame(t))};window.addEventListener("scroll",n,{passive:!0}),document.addEventListener("scroll",n,{passive:!0,capture:!0})}Yy();sT();h1();try{const e=localStorage.getItem("theme");(e==="light"||e==="dark")&&(document.documentElement.classList.remove("light","dark"),document.documentElement.classList.add(e))}catch{}qg.createRoot(document.getElementById("root")).render(s.jsx(eT,{}));tT();export{hf as $,ES as A,W as B,hc as C,Xa as D,qC as E,IS as F,Es as G,MS as H,Lb as I,mT as J,Ve as K,ko as L,Yn as M,aa as N,Fc as O,cT as P,bn as Q,Rs as R,ca as S,qr as T,Hh as U,eS as V,xT as W,LT as X,gT as Y,Yh as Z,Ne as _,Za as a,dj as a$,ct as a0,Ds as a1,pm as a2,uT as a3,jb as a4,lt as a5,rC as a6,Pt as a7,iT as a8,AT as a9,ok as aA,ql as aB,ns as aC,qh as aD,Ye as aE,Wb as aF,vm as aG,tn as aH,is as aI,Io as aJ,Ke as aK,am as aL,Fr as aM,gt as aN,nt as aO,On as aP,ut as aQ,Sb as aR,Ji as aS,$m as aT,Ly as aU,Jh as aV,Pe as aW,Hw as aX,ah as aY,uy as aZ,Xi as a_,Yi as aa,Wi as ab,ds as ac,iw as ad,Wn as ae,Ls as af,Ht as ag,Vt as ah,At as ai,B1 as aj,vx as ak,Yb as al,sf as am,dw as an,Ry as ao,hT as ap,$c as aq,ff as ar,MT as as,OT as at,Hn as au,$T as av,FT as aw,PT as ax,nk as ay,lT as az,Lo as b,_0 as b$,yh as b0,uj as b1,kh as b2,Ka as b3,Cm as b4,tv as b5,sv as b6,nv as b7,oC as b8,CT as b9,rc as bA,Qu as bB,pT as bC,Mr as bD,yc as bE,vk as bF,_r as bG,en as bH,ba as bI,Gn as bJ,Jc as bK,si as bL,TT as bM,fv as bN,gd as bO,ii as bP,mi as bQ,_c as bR,Nt as bS,St as bT,Ct as bU,fT as bV,jT as bW,bT as bX,yT as bY,kT as bZ,IT as b_,dT as ba,tm as bb,sa as bc,xt as bd,Be as be,Bf as bf,Ot as bg,xn as bh,_T as bi,ET as bj,DT as bk,Ff as bl,hv as bm,xv as bn,Jt as bo,jm as bp,Ar as bq,Em as br,ri as bs,oi as bt,bh as bu,ai as bv,Zh as bw,hb as bx,$a as by,Mo as bz,S as c,sn as c0,NT as c1,of as c2,Ir as c3,cf as c4,oa as c5,y0 as c6,Qm as c7,ew as c8,J0 as c9,Z0 as ca,ST as cb,Q0 as cc,zi as cd,wT as ce,vT as cf,er as d,tr as e,km as f,Fe as g,hn as h,pn as i,As as j,dt as k,ef as l,pc as m,RT as n,tf as o,Hi as p,S0 as q,f0 as r,B as s,Ki as t,He as u,Zm as v,pe as w,Vi as x,TS as y,_S as z};

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.