1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/SmartAgentCard-BJ3BFpRm.js","assets/rolldown-runtime-ChpBd9eV.js","assets/chat-page-C-flp553.js","assets/chartjs-vendor-CJ58C3gX.js","assets/chat-page-BXqTKTIP.css","assets/community-page-dub7UFXa.js","assets/community-page-zj3fMWjX.css","assets/EquityCurve-Dmi-OkPp.js","assets/dashboard-page-BSnUBMUY.js","assets/recharts-vendor-DalH_QXM.js","assets/market-core-B8Bfud51.js","assets/firebase-messaging-CsDg6nnc.js","assets/firebase-core-BBMsJHd4.js","assets/education-page-Buqr-MLV.js","assets/markdown-vendor-BgBZRf5M.js","assets/market-core-15RKgApK.css","assets/lodash-vendor-CQ1T4J8E.js","assets/XPLevelSystem-BK3hNdvz.js","assets/ExportReporting-BxRSQss9.js","assets/AICopilotTab-D4hWH7m8.js","assets/icons-vendor-DpKLKbbD.js","assets/ViolationSummaryCard-CB5K6x99.js","assets/WeeklyReviewTab-DrR-Hxte.js","assets/trading-charts-uBzRtfFs.js","assets/BehaviorTab-DESe4vL3.js","assets/DecisionsTab-DdVkpYvL.js","assets/InsightCard-CbSYsRiV.js","assets/LabTab-DMNbLGaj.js","assets/playbook-kDJJosU-.js","assets/CouncilChatPanel-BrbnSO-e.js","assets/ClearanceProgressCard-DCZyvfF9.js","assets/PerformanceKPIGrid-CslBl5R9.js","assets/InteractiveChart-TJOKQiVj.js"])))=>i.map(i=>d[i]); 2import{o as Ct}from"./rolldown-runtime-ChpBd9eV.js";import{A as Mt,Ba as Dt,H as ht,In as Me,It as Pt,Ka as Ot,Pa as Ft,Tr as Ze,Ua as zt,Un as et,Va as Vt,Wa as b,Y as $t,ba as Wt,ga as ft,n as Bt}from"./chat-page-C-flp553.js";import{$ as Ut,J as qt,Q as tt,Qs as Ht,X as Kt,Xs as Gt,Z as Yt,Zs as De,au as Pe,et as Xt,mo as Jt,nt as Qt,sa as Zt,su as es,tt as ts,yl as ss}from"./market-core-B8Bfud51.js";import{B as at,En as rs,J as xe,Mt as as,N as ns,Pr as re,X as bt,an as is,at as ls,fr as we,ht as yt,j as os,ln as cs,n as ds,sr as de,xt as vt,z as ms}from"./community-page-dub7UFXa.js";import{a as us,c as xs,g as ps,i as hs,l as gs,m as fs,p as bs,r as ys,t as vs,u as js}from"./chartjs-vendor-CJ58C3gX.js";import{k as st,w as ws}from"./dashboard-page-BSnUBMUY.js";import{S as Ns,n as ks,p as rt,v as Ts}from"./index-DeISjUgD.js";import{a as As,c as Is,f as _s,i as Ss,n as Rs,p as Es,r as Ls,s as Cs}from"./recharts-vendor-DalH_QXM.js";import{i as Ms,r as Ds,t as Ps}from"./EmptyStateCard-5omhNgM0.js";var s=Ct(Ot(),1),gt={free:0,pro:1,elite:2,mentor:3},jt=[{id:"overview",label:"Overview",icon:bt,color:"from-blue-500 to-cyan-500",description:"Key performance metrics & summary",requiredTier:"free",enforcementImmune:!0},{id:"playbook",label:"Playbook",icon:at,color:"from-indigo-500 to-blue-500",description:"Personal strategy library & trading rules",isNew:!0,requiredTier:"pro"},{id:"weekly",label:"Weekly Review",icon:xe,color:"from-indigo-500 to-violet-500",description:"Weekly performance snapshots & trends",requiredTier:"pro"},{id:"xp",label:"XP & Levels",icon:rs,color:"from-amber-500 to-orange-500",description:"Experience points & skill levels",requiredTier:"pro"},{id:"decisions",label:"Decisions",icon:ms,color:"from-blue-500 to-violet-500",description:"Action-oriented insights with concrete fixes",isNew:!0,requiredTier:"pro",enforcementImmune:!0,tradeCountGate:10},{id:"lab",label:"Lab",icon:as,color:"from-orange-500 to-pink-500",description:"Counterfactual replays & power-user tools",level:"advanced",requiredTier:"pro",lockedWhenRestricted:!0,tradeCountGate:10},{id:"behavior",label:"Behavior",icon:xe,color:"from-cyan-500 to-blue-500",description:"Discipline command center â violations & patterns",level:"intermediate",requiredTier:"free",enforcementImmune:!0},{id:"export",label:"Export",icon:yt,color:"from-stone-500 to-neutral-500",description:"Export data & generate reports",level:"intermediate",requiredTier:"pro"},{id:"ai",label:"AI Copilot",icon:is,color:"from-purple-500 to-pink-500",description:"Advanced AI trading assistant",requiredTier:"pro"}],fr=jt.map(o=>o.id),Os=(o,c,d=!1)=>d?!0:(gt[(o||"free").toLowerCase()]??-1)>=(gt[c]??1),Fs=(o,c,d,u=!1,y=0)=>{const i=d?.state||"NORMAL",p=i==="LOCKED",$=i==="COOLDOWN"||i==="RESTRICTED"||i==="LOCKED",L=i==="WARN"||i==="AT_RISK"||$;return jt.map(C=>{const H=u?!1:!Os(o||null,C.requiredTier||"pro",c);let k=!1,W,K=!1;!c&&!C.enforcementImmune&&(p?(k=!0,W=d?.primaryReason?.description||"Complete remediation to unlock"):$&&C.lockedWhenRestricted?(k=!0,W=d?.primaryReason?.description||"Address issues to unlock"):L&&C.lockedWhenRestricted&&(K=!0));const G=!c&&C.tradeCountGate!=null&&y<C.tradeCountGate;return{...C,isSubscriptionLocked:H||k,isTradeCountLocked:G,isLocked:H||k||G,lockedReason:k?W:void 0,hasWarning:K}})},e=Ft();(0,s.lazy)(()=>b(()=>import("./SmartAgentCard-BJ3BFpRm.js"),__vite__mapDeps([0,1,2,3,4,5,6])));var zs=(0,s.lazy)(()=>b(()=>import("./EquityCurve-Dmi-OkPp.js"),__vite__mapDeps([7,1,2,3,4,5,6,8,9,10,11,12,13,14,15,16]))),Vs=(0,s.lazy)(()=>b(()=>import("./XPLevelSystem-BK3hNdvz.js"),__vite__mapDeps([17,1,2,3,4,5,6,9,10,11,12,13,8,14,15,16]))),$s=(0,s.lazy)(()=>b(()=>import("./ExportReporting-BxRSQss9.js"),__vite__mapDeps([18,1,2,3,4,5,6,8]))),Ws=(0,s.lazy)(()=>b(()=>import("./AICopilotTab-D4hWH7m8.js"),__vite__mapDeps([19,1,2,3,4,20,13,5,6,8]))),Bs=(0,s.lazy)(()=>b(()=>import("./ViolationSummaryCard-CB5K6x99.js"),__vite__mapDeps([21,10,3,1,2,4,11,12,13,5,6,8,14,15]))),Us=(0,s.lazy)(()=>b(()=>import("./WeeklyReviewTab-DrR-Hxte.js"),__vite__mapDeps([22,10,3,1,2,4,11,12,13,5,6,8,14,15,20,23]))),qs=(0,s.lazy)(()=>b(()=>import("./BehaviorTab-DESe4vL3.js"),__vite__mapDeps([24,10,3,1,2,4,11,12,13,5,6,8,14,15]))),Hs=(0,s.lazy)(()=>b(()=>import("./DecisionsTab-DdVkpYvL.js"),__vite__mapDeps([25,10,3,1,2,4,11,12,13,5,6,8,14,15,26]))),Ks=(0,s.lazy)(()=>b(()=>import("./LabTab-DMNbLGaj.js"),__vite__mapDeps([27,10,3,1,2,4,11,12,13,5,6,8,14,15]))),Gs=(0,s.lazy)(()=>b(()=>import("./playbook-kDJJosU-.js").then(o=>({default:o.PlaybookTab})),__vite__mapDeps([28,10,3,1,2,4,11,12,13,5,6,8,14,15,23,20,29]))),Ys=(0,s.lazy)(()=>b(()=>import("./ClearanceProgressCard-DCZyvfF9.js"),__vite__mapDeps([30,10,3,1,2,4,11,12,13,5,6,8,14,15]))),Xs=(0,s.lazy)(()=>b(()=>import("./PerformanceKPIGrid-CslBl5R9.js"),__vite__mapDeps([31,1,2,3,4,5,6])));(0,s.lazy)(()=>b(()=>import("./InteractiveChart-TJOKQiVj.js"),__vite__mapDeps([32,1,2,3,4,5,6,23,10,11,12,13,8,14,15,20])));us.register(xs,ys,js,gs,hs,ps,fs,vs,bs);var Js=()=>(0,e.jsxs)("div",{className:"flex items-center justify-center p-8",children:[(0,e.jsx)("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500"}),(0,e.jsx)("span",{className:"ml-3 text-slate-400",children:"Loading..."})]}),Qs=o=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}
2).format(o||0),Zs=o=>{if(o.marketType!=="options"||!o.entryTime||!o.optionExpiry)return"N/A";const c=re(o.entryTime),d=re(o.optionExpiry);if(!c||!d)return"N/A";const u=Math.abs(d-c),y=Math.ceil(u/(1e3*60*60*24));return y<=1?"0DTE":y<=7?"Weekly":"Monthly"},er=o=>{if(!o||o.length===0)return"beginner";const c=o.length,d=o.filter(u=>we(u)>0).length/c*100;return c>=300&&d>=60?"expert":c>=150&&d>=50?"advanced":c>=50&&d>=40?"intermediate":"beginner"},tr=({text:o,children:c})=>{const[d,u]=s.useState(null),y=s.useRef(),i=()=>{const p=y.current?.getBoundingClientRect();p&&u({top:p.top-8,left:p.left+p.width/2})};return(0,e.jsxs)("div",{ref:y,style:{position:"relative",display:"inline-flex"},onMouseEnter:i,onMouseLeave:()=>u(null),children:[c,d&&(0,e.jsxs)("div",{style:{position:"fixed",top:d.top,left:d.left,transform:"translate(-50%, -100%)",background:"#111827",color:"white",fontSize:11,padding:"6px 10px",borderRadius:6,whiteSpace:"nowrap",border:"1px solid rgba(255,255,255,0.12)",zIndex:9999,pointerEvents:"none",boxShadow:"0 4px 16px rgba(0,0,0,0.5)"},children:[o,(0,e.jsx)("div",{style:{position:"absolute",top:"100%",left:"50%",transform:"translateX(-50%)",width:0,height:0,borderLeft:"5px solid transparent",borderRight:"5px solid transparent",borderTop:"5px solid #111827"}})]})]})},sr=()=>{const{t:o}=ft(),c=Vt(),d=Dt(),[u,y]=zt(),i=Ze(t=>t.user),p=Ze(t=>t.activeTradingAccount),$=Ze(t=>t.setActiveTradingAccount),{isIOS:L,isPWA:C}=Kt((0,s.useRef)(null),{enableMemoryCheck:!0,throttleMs:100}),H=Me(t=>t.isMentor),k=Me(t=>t.isAdmin),W=Me(t=>t.tier),K=Me(t=>t.loading),{accountState:G,isLocked:_,isRestricted:wt,isAtRisk:Nt}=Mt(),Oe=$t(t=>t.activeViolations().length),[Fe,ze]=(0,s.useState)(!1),nt=(0,s.useCallback)(async()=>{ze(!0);try{const{getFunctions:t,httpsCallable:r}=await b(async()=>{const{getFunctions:n,httpsCallable:l}=await import("./chat-page-C-flp553.js").then(m=>m.Ir);return{getFunctions:n,httpsCallable:l}},__vite__mapDeps([2,3,1,4]));await r(t(),"clearStaleViolationsV2")({reason:"analytics_gate_recheck"})}catch(t){console.warn("[TradeAnalytics] account state recheck failed:",t?.message||t)}finally{ze(!1)}},[]),Ne=st(t=>t.risk.baseAccountSize)||2e3;st(t=>t.risk.accountSize),(0,s.useEffect)(()=>{if(i?.uid){const t=setTimeout(()=>{st.getState().loadFromFirestore(i.uid)},1e3);return()=>clearTimeout(t)}},[i?.uid]);const{isAdmin:it,loading:Ve}=ss(),M=k===!0||it===!0||typeof k=="function"&&k(),{currentUserId:Y,inMentorMode:$e,isReadOnly:kt}=Yt();(0,s.useEffect)(()=>{window.scrollTo(0,0)},[]);const We=de(t=>t.trades),ae=(0,s.useMemo)(()=>qt(We),[We]);de(t=>t.loading);const Be=de(t=>t.error),ke=de(t=>t.initializeTradeLogs),Ue=de(t=>t.setError),D=Pe(t=>t.currentOrg),pe=Pe(t=>t.currentMembership),qe=Pe(t=>t.allMemberships),lt=Pe(t=>t.fetchAllMemberships),[P,He]=(0,s.useState)(null),[S,he]=(0,s.useState)(null),[Te,ge]=(0,s.useState)([]),[h,X]=(0,s.useState)(null),[ne,F]=(0,s.useState)(null),[j,T]=(0,s.useState)([]),Ae=(0,s.useRef)(null),B=(0,s.useRef)(new Map),Ie=(0,s.useRef)(!1);(0,s.useEffect)(()=>{i?.uid&&!Ie.current&&(!qe||qe.length===0)&&(Ie.current=!0,lt(i.uid))},[i?.uid]);const w=(0,s.useMemo)(()=>pe?.role?Jt(pe.role):!1,[pe?.role]),A=P&&w,[z,ie]=(0,s.useState)(null),[O,J]=(0,s.useState)([]),[Ke,_e]=(0,s.useState)(!1),Q=(0,s.useMemo)(()=>new URLSearchParams(d.search).get("viewUserId"),[d.search]);(0,s.useEffect)(()=>{Q?ie(Q):i?.uid&&ie(i.uid)},[Q,i?.uid]);const le=(0,s.useMemo)(()=>P&&w?{userId:P,mode:"org_member",displayName:S?.displayName||S?.email||"Team Member",isReadOnly:!0,source:"org"}:$e&&Y&&Y!==i?.uid?{userId:Y,mode:"mentor",displayName:O.find(t=>t.id===Y)?.displayName||"Mentee",isReadOnly:!0,source:"mentor"}:z&&z!==i?.uid?{userId:z,mode:"legacy_view",displayName:O.find(t=>t.id===z)?.displayName||"Trader",isReadOnly:!0,source:"url"}:{userId:i?.uid||null,mode:"self",displayName:"You",isReadOnly:!1,source:"auth"},[P,w,S,$e,Y,i?.uid,z,O]),x=le.userId,{trades:Z,loading:fe,error:Ge}=Qt(x,ae),Se=(0,s.useMemo)(()=>new Set(Z.map(t=>t.id||t.tradeId)),[Z]),oe=(0,s.useMemo)(()=>le.mode==="self"?ae.filter(t=>!Se.has(t.id||t.tradeId)):[],[ae,Se,le.mode]),v=(0,s.useMemo)(()=>[...Z,...oe.map(t=>({...t,financialEvidence:{eligible:!1,authoritative:!1,type:"self_reported",confidence:"self_reported"},_analyticsProvenance:"self_reported"}))],[Z,oe]),R=(0,s.useMemo)(()=>v.filter(ws).length,[v]),g=(0,s.useMemo)(()=>Fs(W,M,G,K||Ve||fe,M?999:R),[W,M,G,K,Ve,fe,R]),N=k||(typeof H=="function"?H():!1);(0,s.useEffect)(()=>
2{if(!x)return;const t=Zt.getState();return t.subscribe(x),()=>{try{t.unsubscribe()}catch{}}},[x]);const U=async(t,r,n)=>{He(t),he(r);const l=n||D?.id;if(l&&t){const m=`${t}_${l}`;if(B.current.has(m)){const f=B.current.get(m);console.log("[TradeAnalytics] Using cached org-linked account IDs for member:",f),ge(f);return}try{const{collection:f,query:V,where:Je,getDocs:ve}=await b(async()=>{const{collection:se,query:je,where:Qe,getDocs:Et}=await import("./chat-page-C-flp553.js").then(Lt=>Lt.bi);return{collection:se,query:je,where:Qe,getDocs:Et}},__vite__mapDeps([2,3,1,4])),{db:ee}=await b(async()=>{const{db:se}=await import("./chat-page-C-flp553.js").then(je=>je.jr);return{db:se}},__vite__mapDeps([2,3,1,4])),te=(await ve(V(f(ee,"users",t,"tradingAccounts"),Je("organizationId","==",l)))).docs.map(se=>se.id);B.current.set(m,te),ge(te),console.log("[TradeAnalytics] Fetched and cached org-linked account IDs for member:",te)}catch(f){console.error("[TradeAnalytics] Failed to fetch org-linked accounts:",f),ge([])}}},Re=()=>{He(null),he(null),ge([]),X(null),F(null);const t=new URLSearchParams(u);t.delete("viewOrgMember"),y(t,{replace:!0})},ot=async t=>{if(console.log("[TradeAnalytics] Trade view filter changed to:",t),X(t),t===null)F(null),console.log("[TradeAnalytics] All trades mode - no filtering");else if(t==="personal")F("personal"),console.log("[TradeAnalytics] Personal trades mode");else{const r=P||Y||z||i?.uid;if(!r){F([]);return}const n=`${r}_${t}`;if(B.current.has(n)){const l=B.current.get(n);console.log("[TradeAnalytics] Using cached org-linked accounts for",t,":",l),F(l);return}try{const{collection:l,query:m,where:f,getDocs:V}=await b(async()=>{const{collection:ee,query:te,where:se,getDocs:je}=await import("./chat-page-C-flp553.js").then(Qe=>Qe.bi);return{collection:ee,query:te,where:se,getDocs:je}},__vite__mapDeps([2,3,1,4])),{db:Je}=await b(async()=>{const{db:ee}=await import("./chat-page-C-flp553.js").then(te=>te.jr);return{db:ee}},__vite__mapDeps([2,3,1,4])),ve=(await V(m(l(Je,"users",r,"tradingAccounts"),f("organizationId","==",t)))).docs.map(ee=>ee.id);B.current.set(n,ve),console.log("[TradeAnalytics] Fetched and cached org-linked accounts for",t,"(user:",r,"):",ve),F(ve)}catch(l){console.error("[TradeAnalytics] Failed to fetch org-linked accounts:",l),F([])}}};(0,s.useEffect)(()=>{if(!N||!i?.uid){J([]);return}let t=!1;return _e(!0),Bt(i.uid).then(r=>{t||J(Array.isArray(r)?r:[])}).catch(r=>{console.warn("â ï¸ TradeAnalytics: failed to load mentees",r),t||J([])}).finally(()=>{t||_e(!1)}),()=>{t=!0}},[N,i?.uid]),(0,s.useMemo)(()=>x?x===i?.uid?{id:x,displayName:"You",email:i?.email}:O.find(t=>t.id===x)||null:null,[x,i?.uid,i?.email,O]),(0,s.useEffect)(()=>{if(x){const{_lastUserId:t}=de.getState();t!==x&&ke(x)}},[x]);const ct=(0,s.useRef)(null),ce=(0,s.useCallback)(()=>{},[]);(0,s.useEffect)(()=>()=>{ct.current&&clearTimeout(ct.current)},[]),et("trade.created",ce,[ce]),et("trade.updated",ce,[ce]),et("trade.deleted",ce,[ce]);const dt=(0,s.useCallback)(()=>{Ue?.(null)},[Ue]),Tt=(0,s.useCallback)(()=>{dt(),x&&ke(x,{forceRefresh:!0})},[dt,x,ke]);(0,s.useEffect)(()=>{const t=u.get("viewOrgMember"),r=u.get("orgId"),n=u.get("memberName");if(t&&i?.uid){r&&ot(r),U(t,{id:t,displayName:n||"Trader",email:""},r);const l=new URLSearchParams(u);l.delete("viewOrgMember"),l.delete("orgId"),l.delete("memberName"),y(l,{replace:!0})}},[i?.uid]);const[E,Ee]=(0,s.useState)(()=>{try{return new URLSearchParams(window.location.search).get("tab")||"overview"}catch{return"overview"}}),mt=(0,s.useRef)(!0),[be,At]=(0,s.useState)(!1);(0,s.useEffect)(()=>{const t=u.get("tab");t&&t!==E&&Ee(t)},[u]);const{agentConfig:It}=ds("performance-analyst"),ut=It;(0,s.useEffect)(()=>{mt.current=!0},[]),(0,s.useEffect)(()=>{if(!be){const t=setTimeout(()=>{mt.current&&At(!0)},100);return()=>clearTimeout(t)}},[be]);const[a,ye]=(0,s.useState)({searchTerm:"",market:"",timeRange:"",setup:"",sort:"date-desc",tag:"",accountId:p||"",marketType:"all",expiration:"all",contractType:"all",strategy:"all"});(0,s.useEffect)(()=>{d.state?.filterTag&&(ye(t=>({...t,tag:d.state.filterTag})),(0,s.startTransition)(()=>{Ee("overview")}),c(d.pathname,{replace:!0,state:{}}))},[d.state,d.pathname,c]),(0,s.useEffect)(()=>
2{if(!x){T([]),ye(r=>r.accountId?{...r,accountId:""}:r);return}let t=!1;return es.getConnectedAccounts(x).then(r=>{if(t)return;const n=r||[];T(n),ye(l=>{const m=`${x}:${p||""}`;if(Ae.current!==m){const f=n.find(V=>V.id===p||V.brokerAccountId===p);return Ae.current=m,{...l,accountId:f?.id||""}}return l.accountId?n.some(f=>f.id===l.accountId||f.brokerAccountId===l.accountId)?l:{...l,accountId:""}:l})}).catch(()=>{t||T([])}),()=>{t=!0}},[x,p]);const _t=(0,s.useCallback)(t=>{ye(r=>({...r,accountId:t})),t&&$(t)},[$]),Ye=(0,s.useMemo)(()=>Ut(a.timeRange),[a.timeRange]);(0,s.useMemo)(()=>er(v),[v]);const I=(0,s.useMemo)(()=>{try{let t=[...v];if(A&&Te.length>0&&(t=t.filter(r=>Te.includes(r.accountId)||r.organizationId===D?.id)),ne==="personal")t=t.filter(r=>!r.organizationId&&!r.accountOrganizationId);else if(h&&h!=="personal"){const r=Array.isArray(ne)?ne:[],n=h;t=t.filter(l=>!!(l.organizationId===n||l.accountOrganizationId===n||l.accountId&&r.length>0&&r.includes(l.accountId)))}if(t=tt(t,a.accountId,j),a.searchTerm){const r=a.searchTerm.toLowerCase();t=t.filter(n=>{try{return!!((n.symbol?.toLowerCase()||"").includes(r)||(n.notes?.toLowerCase()||"").includes(r)||(n.setup?.toLowerCase()||"").includes(r)||(Array.isArray(n.tags)?n.tags:typeof n.tags=="string"?n.tags.split(",").map(l=>l.trim()):[]).some(l=>typeof l=="string"&&l.toLowerCase().includes(r)))}catch(l){return console.warn("[TradeAnalytics] Search filter error for trade:",n.id,l),!1}})}if(a.market&&(t=t.filter(r=>r.marketType===a.market)),a.setup&&(t=t.filter(r=>r.setup===a.setup)),a.tag&&(t=t.filter(r=>r.tags&&Array.isArray(r.tags)&&r.tags.includes(a.tag))),a.timeRange){const r=new Date;let n=new Date;switch(a.timeRange){case"today":n.setHours(0,0,0,0);break;case"last5days":n.setDate(r.getDate()-5);break;case"currentWeek":{const l=r.getDay(),m=r.getDate()-l+(l===0?-6:1);n=new Date(r.setDate(m)),n.setHours(0,0,0,0);break}case"currentMonth":n=new Date(r.getFullYear(),r.getMonth(),1);break;case"last30days":n.setDate(r.getDate()-30);break;default:n=null}n&&(t=t.filter(l=>{const m=re(l.entryTime);return m&&m>=n}))}if(a.marketType&&a.marketType!=="all"&&(t=t.filter(r=>r.marketType===a.marketType)),a.expiration&&a.expiration!=="all"&&a.marketType==="options"&&(t=t.filter(r=>Zs(r).toLowerCase()===a.expiration)),a.contractType&&a.contractType!=="all"&&a.marketType==="options"&&(t=t.filter(r=>r.optionType?.toLowerCase()===a.contractType)),a.strategy&&a.strategy!=="all"&&a.marketType==="options"){const r=a.strategy==="premium_sell"?"sell":"buy";t=t.filter(n=>n.tradeType===r)}return a.sort&&t.sort((r,n)=>{switch(a.sort){case"date-desc":return(re(n.entryTime)||0)-(re(r.entryTime)||0);case"date-asc":return(re(r.entryTime)||0)-(re(n.entryTime)||0);case"pl-desc":return(we(n)||0)-(we(r)||0);case"pl-asc":return(we(r)||0)-(we(n)||0);case"ticker-asc":return(r.symbol||"").localeCompare(n.symbol||"");default:return 0}}),t}catch(t){return console.error("[TradeAnalytics] Filter pipeline error:",t),a.accountId?[]:v}},[v,a,j,A,Te,D?.id,ne,h]),xt=(0,s.useMemo)(()=>tt(ae,a.accountId,j),[ae,a.accountId,j]),Xe=(0,s.useMemo)(()=>{if(!a.accountId)return"All Accounts";const t=j.find(r=>r.id===a.accountId||r.brokerAccountId===a.accountId);return t?.displayName||t?.name||t?.provider||a.accountId},[a.accountId,j]),pt=(0,s.useMemo)(()=>tt(oe,a.accountId,j).some(t=>{if(!(t.isActive===!1||t.status==="closed"||typeof t.exitPrice=="number"&&t.exitPrice>0))return!1;const r=String(t.source||"").toLowerCase(),n=String(t.accountProvider||"").toLowerCase();return t.isPaperTrade!==!0&&n!=="paper"&&r!=="paper"&&r!=="agent_pipeline"}),[oe,a.accountId,j]),Le=(0,s.useRef)(v);(0,s.useEffect)(()=>{(v.length!==Le.current.length||v.some((t,r)=>{const n=Le.current[r];return t.id!==n?.id?!0:(t.updatedAt?.seconds??(typeof t.updatedAt=="number"?t.updatedAt:null))!==(n.updatedAt?.seconds??(typeof n.updatedAt=="number"?n.updatedAt:null))}))&&(Le.current=v)},[v]);const Ce=!!(a.searchTerm||a.market||a.timeRange||a.setup||a.tag||a.accountId||a.marketType&&a.marketType!=="all"||a.expiration&&a.expiration!=="all"||a.contractType&&a.contractType!=="all"||a.strategy&&a.strategy!=="all"||h!==null),q=(0,s.useMemo)(()=>
2{if(!be)return null;try{const t=a.accountId?(()=>{const l=j.find(f=>f.id===a.accountId||f.brokerAccountId===a.accountId),m=l?.startingCapital||l?.balance||0;return m>0?m:Ne})():Ne,r=l=>{const m=ts(l,{startingBalance:t,config:Xt});return A?{...m,clientsInRisk:0,ruleBreachesLast7Days:0,ruleBreachesLast30Days:0}:m};if(A)return r(I);const n=Ce||I.length>0?I:v;return!n||n.length===0?Ce?r([]):null:r(n)}catch(t){return console.error("[TradeAnalytics] Analytics computation error:",t),null}},[be,I,Le.current.length,Ce,A,h,Ne,a.accountId,j.length]),St=Be&&(!v||v.length===0),Rt=(0,s.useMemo)(()=>{const t=I;try{switch(E){case"overview":return(0,e.jsx)(lr,{analytics:q,trades:t,user:i,agentConfig:ut,orgTradeFilter:h,inOrgViewMode:A,currentOrg:D,canViewOrgMembers:w,timeRangeLabel:Ye,financialLedgerLoading:fe,financialLedgerError:Ge,journalTradeCount:xt.length,usingJournalAnalytics:pt});case"decisions":return!M&&R<10?(0,e.jsx)(rt,{featureKey:"analytics_decisions",title:"Decisions",description:"Action-oriented insights with concrete fixes â built from your own trade history.",count:R}):(0,e.jsx)(Hs,{trades:t,user:i});case"lab":return!M&&R<10?(0,e.jsx)(rt,{featureKey:"analytics_lab",title:"Lab",description:"Counterfactual replays and power-user tools that need real trade history to work with.",count:R}):(0,e.jsx)(Ks,{trades:t,user:i});case"export":return(0,e.jsx)($s,{trades:t,user:i});case"behavior":return!M&&R<10?(0,e.jsx)(rt,{featureKey:"analytics_behavior",title:"Behavior",description:"Your discipline command center â violation patterns emerge once there's history to read.",count:R}):(0,e.jsx)(qs,{trades:t,user:i});case"xp":return(0,e.jsx)(Vs,{user:i,trades:t});case"weekly":return(0,e.jsx)(Us,{user:i,trades:t});case"ai":return M||t.length>=2?(0,e.jsx)(Ws,{trades:t,user:i,accountId:a.accountId||null,accountLabel:Xe,timeRangeLabel:Ye}):(0,e.jsx)(Ps,{tradeCount:t.length});case"playbook":return(0,e.jsx)(Gs,{trades:t,user:i,accountId:a.accountId||null,accountLabel:Xe});default:return(0,e.jsxs)("div",{className:"p-8 text-center",children:[(0,e.jsx)("h3",{className:"text-xl font-semibold text-white mb-2",children:"Tab Not Found"}),(0,e.jsxs)("p",{className:"text-slate-400",children:['The selected tab "',E,'" is not available.']})]})}}catch(r){return console.error("[TradeAnalytics] Tab render error:",E,r),(0,e.jsxs)("div",{className:"p-8 text-center",children:[(0,e.jsx)("h3",{className:"text-xl font-semibold text-red-400 mb-2",children:"Something went wrong"}),(0,e.jsxs)("p",{className:"text-slate-400 mb-4",children:['The "',E,'" tab encountered an error. Try refreshing the page.']}),(0,e.jsx)("button",{onClick:()=>window.location.reload(),className:"px-4 py-2 bg-blue-600 hover:bg-blue-500 text-white rounded-lg text-sm",children:"Refresh Page"})]})}},[E,I,(0,s.useMemo)(()=>I.reduce((t,r)=>t+(r.updatedAt?.seconds??(typeof r.updatedAt=="number"?r.updatedAt:0)),0),[I]),i?.uid,q,ut,h,A,D?.id,w,Ye,M,R,fe,Ge,xt.length,pt,a.accountId,Xe]);if(St)return(0,e.jsx)("div",{className:"analytics-page-wrapper",children:(0,e.jsx)("div",{className:"analytics-main-content",children:(0,e.jsx)("div",{className:"analytics-content-wrapper",children:(0,e.jsxs)("div",{className:"analytics-card text-center space-y-4 py-10",children:[(0,e.jsx)("h3",{className:"text-xl font-semibold",children:"Unable to load analytics"}),(0,e.jsx)("p",{className:"text-gray-500",children:Be}),(0,e.jsx)(Ts,{onClick:Tt,variant:"primary",children:"Retry Sync"})]})})})});if((!q||v.length===0)&&A&&S)return(0,e.jsxs)("div",{className:"analytics-page-wrapper min-h-screen pt-0 relative theme-page bg-[var(--bg-primary)]",children:[(0,e.jsx)("div",{className:"px-4 pt-4 bg-[var(--bg-primary)]",children:(0,e.jsx)(ht,{variant:"compact"})}),(0,e.jsx)("div",{className:"px-4 pt-2 bg-[var(--bg-primary)]",children:(0,e.jsx)(s.Suspense,{fallback:null,children:(0,e.jsx)(De,{selectedMemberId:P,selectedMemberData:S,onMemberSelect:U,onExit:Re,orgIdOverride:h&&h!=="personal"?h:D?.id})})}),(0,e.jsx)("div",{className:"analytics-main-content",children:(0,e.jsx)("div",{className:"analytics-content-wrapper",children:(0,e.jsxs)("div",{className:"analytics-card text-center py-12",children:[(0,e.jsx)("div",{className:"w-16 h-16 bg-slate-800 rounded-2xl flex items-center justify-center mx-auto mb-4",children:(0,e.jsx)(xe,{className:"w-8 h-8 text-slate-600"})}),(0,e.jsx)("h3",{className:"text-xl font-semibold text-white mb-2",children:"No Trades Yet"}),(0,e.jsxs)("p",{className:"text-slate-400 max-w-md mx-auto",children:[(0,e.jsx)("span",{className:"font-medium text-orange-300",children:S.displayName||S.email||"This member"})," ","hasn't logged any trades yet. Their analytics will appear here once they start trading."]})]})})})]});if([a.searchTerm,a.market,a.timeRange,a.setup,a.tag,a.accountId,a.marketType!=="all"&&a.marketType,a.expiration!=="all"&&a.expiration,a.contractType!=="all"&&a.contractType,a.strategy!=="all"&&a.strategy].filter(
2Boolean).length,I.length===0&&Ce){const t=()=>ye({searchTerm:"",market:"",timeRange:"",setup:"",tag:"",accountId:"",sort:"date-desc",marketType:"all",expiration:"all",contractType:"all",strategy:"all"});return(0,e.jsx)("div",{className:"analytics-page-wrapper",children:(0,e.jsx)("div",{className:"analytics-main-content",children:(0,e.jsx)("div",{className:"analytics-content-wrapper",children:(0,e.jsx)("div",{className:"analytics-card",children:(0,e.jsx)(Ds,{onClearFilters:t,currentFiltersCount:4})})})})})}return(0,e.jsxs)("div",{className:"analytics-page-wrapper min-h-screen overflow-y-auto pt-0 relative theme-page bg-[var(--bg-primary)]",children:[(0,e.jsx)("div",{className:"px-4 pt-4 bg-[var(--bg-primary)]",children:(0,e.jsx)(ht,{variant:"compact",accountId:a.accountId||null})}),_&&!M&&(0,e.jsx)("div",{className:"px-4 py-6 bg-[var(--bg-primary)]",children:(0,e.jsxs)(Wt.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},className:"bg-gradient-to-br from-red-900/20 to-orange-900/20 border border-red-500/30 rounded-xl p-6",children:[(0,e.jsxs)("div",{className:"flex items-start gap-4",children:[(0,e.jsx)("div",{className:"w-12 h-12 bg-red-500/20 rounded-xl flex items-center justify-center flex-shrink-0",children:(0,e.jsx)(vt,{className:"w-6 h-6 text-red-400"})}),(0,e.jsxs)("div",{className:"flex-1",children:[(0,e.jsx)("h3",{className:"text-xl font-bold text-white mb-2",children:"Analytics Access Limited"}),(0,e.jsx)("p",{className:"text-white/70 mb-4",children:Oe===0?"Your record is clean, but the account is still marked restricted. This restriction looks stale â recheck to clear it.":G.restrictionReason||"A reset timer or required acknowledgment is still active."}),Oe===0?(0,e.jsx)("button",{onClick:nt,disabled:Fe,className:"inline-flex items-center gap-2 px-4 py-2 bg-orange-600 hover:bg-orange-500 disabled:opacity-50 text-white rounded-lg font-medium transition-colors",children:Fe?"Recheckingâ¦":"Recheck account state"}):(0,e.jsxs)("button",{onClick:()=>c("/education"),className:"inline-flex items-center gap-2 px-4 py-2 bg-orange-600 hover:bg-orange-500 text-white rounded-lg font-medium transition-colors",children:[(0,e.jsx)(at,{className:"w-4 h-4"}),"Start Remediation"]})]})]}),(0,e.jsx)("div",{className:"mt-6 pt-6 border-t border-red-500/20",children:(0,e.jsx)(Bs,{showActions:!0,maxViolations:5})})]})}),(0,e.jsx)("div",{className:"px-4 pt-4 bg-[var(--bg-primary)]",children:(0,e.jsx)(s.Suspense,{fallback:(0,e.jsx)("div",{className:"h-10 bg-slate-800/50 rounded-lg animate-pulse border border-slate-700/30"}),children:(0,e.jsx)(Gt,{})})}),!A&&h&&h!=="personal"&&(0,e.jsx)("div",{className:"px-4 pt-2 bg-[var(--bg-primary)]",children:(0,e.jsx)(s.Suspense,{fallback:(0,e.jsx)("div",{className:"h-10 bg-slate-800/50 rounded-lg animate-pulse border border-slate-700/30"}),children:(0,e.jsx)(De,{selectedMemberId:P,selectedMemberData:S,onMemberSelect:U,onExit:Re,orgIdOverride:h})})}),!A&&!h&&D&&(0,e.jsx)("div",{className:"px-4 pt-2 bg-[var(--bg-primary)]",children:(0,e.jsx)(s.Suspense,{fallback:(0,e.jsx)("div",{className:"h-10 bg-slate-800/50 rounded-lg animate-pulse border border-slate-700/30"}),children:w?(0,e.jsx)(De,{selectedMemberId:P,selectedMemberData:S,onMemberSelect:U,onExit:Re}):(0,e.jsxs)("div",{className:"flex items-center gap-2 p-2 bg-slate-800/50 rounded-lg border border-slate-700/50",children:[(0,e.jsxs)("span",{className:"text-xs text-slate-400",children:["Viewing: ",(0,e.jsx)("span",{className:"text-blue-400 font-medium",children:D?.name||"Organization"})]}),(0,e.jsxs)("span",{className:"text-xs text-slate-500",children:["⢠Role: ",pe?.role||"member"]})]})})}),A&&(0,e.jsx)("div",{className:"px-4 pt-2 bg-[var(--bg-primary)]",children:(0,e.jsx)(s.Suspense,{fallback:(0,e.jsx)("div",{className:"h-10 bg-slate-800/50 rounded-lg animate-pulse border border-slate-700/30"}),children:(0,e.jsx)(De,{selectedMemberId:P,selectedMemberData:S,onMemberSelect:U,onExit:Re,orgIdOverride:h&&h!=="personal"?h:D?.id})})}),E==="overview"&&(0,e.jsx)("div",{className:"sticky top-0 z-20 bg-[var(--bg-primary)]/95 backdrop-blur-sm border-b border-[var(--border-primary)]/50 px-3 sm:px-4 py-2 sm:py-3",children:(0,e.jsxs)("div",{className:"flex items-center justify-between gap-2 sm:gap-4 overflow-x-auto",children:[(0,e.jsxs)("div",{className:"flex items-center gap-3 sm:gap-6 min-w-0",children:[(0,e.jsxs)("div",{className:"flex flex-col min-w-0",children:[(0,e.jsx)("span",{className:"text-[10px] sm:text-xs text-slate-400 whitespace-nowrap",children:o("analytics.kpis.trades","Trades")}),(0,e.jsx)("span",{className:"text-sm sm:text-lg font-bold text-slate-200",children:q?.totalTrades||0})]}),(0,e.jsxs)("div",{className:"hidden xs:flex flex-col min-w-0",children:[(0,e.jsx)("span",{className:"text-[10px] sm:text-xs text-slate-400 whitespace-nowrap",children:o("analytics.kpis.profitFactor","Profit Factor")}),(0,e.jsx)("span",{className:`text-sm sm:text-lg font-bold ${_?"text-slate-400":(q?.profitFactor||0)>=1.5?"text-emerald-400":(q?.profitFactor||0)>=1?"text-amber-400":"text-red-400"}`,children:Number.isFinite(q?.profitFactor??0)?(q?.profitFactor||0).toFixed(2):"â"})]})]}),(0,e.jsxs)("button",{onClick:()=>(0,s.startTransition)(()=>Ee("export")),className:"flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-slate-700/50 hover:bg-slate-600/50 border border-slate-600/50 text-xs text-slate-300 hover:text-white transition-colors flex-shrink-0",children:[(0,e.jsx)(yt,{className:"w-3 h-3"}),(0,e.jsx)("span",{className:"hidden xs:inline",children:"Export"})]})]})}),(0,e.jsx)("div",{className:"analytics-main-content",children:(0,e.jsxs)("div",{className:"analytics-content-wrapper",children:[(0,e.jsx)("div",{className:"mb-2 relative z-10","data-tour":"analytics-tabs",children:(0,e.jsx)("div",{className:"relative",children:(0,e.jsxs)("div",{className:"relative bg-gradient-to-r from-sky-500 via-sky-600 to-blue-600 rounded-none sm:rounded-2xl p-4 sm:p-6 shadow-xl -mx-4 sm:mx-0",children:[(0,e.jsxs)("div",{className:"flex items-center justify-between mb-3",children:[(0,e.jsxs)("div",{className:"flex items-center gap-3",children:[(0,e.jsx)("div",{className:"w-10 h-10 sm:w-12 sm:h-12 bg-white/20 backdrop-blur-sm rounded-xl flex items-center justify-center flex-shrink-0",children:(0,e.jsx)(xe,{className:"w-5 h-5 sm:w-6 sm:h-6 text-white"})}),(0,e.jsx)(Ns,{accountId:a.accountId||null,variant:"pill",className:"border-white/30 bg-white/10"})]}),(0,e.jsxs)("div",{className:"text-right hidden sm:block",children:[(0,e.jsx)("div",{className:"text-sm font-semibold text-white",children:o("analytics.tradeDna","Trade DNA")}),(0,e.jsx)("div",{className:"text-[10px] text-white/60",children:o("analytics.deterministicProfile","Your deterministic trading profile")})]})]}),(0,e.jsxs)("div",{className:"flex flex-wrap items-center gap-2 mb-3",children:[i?.uid&&(0,e.jsx)(s.Suspense,{fallback:(0,e.jsx)("div",{className:"h-8 w-24 bg-white/10 rounded-lg animate-pulse"}),children:(0,e.jsx)(Ht,{currentView:h,onViewChange:ot})}),j.length>0&&(0,e.jsxs)("select",{value:a.accountId,onChange:t=>_t(t.target.value),className:"bg-white/10 border border-white/20 text-white text-[10px] sm:text-xs rounded-lg px-2 py-1.5 focus:outline-none focus:ring-2 focus:ring-white/40 backdrop-blur-sm",children:[(0,e.jsx)("option",{value:"",className:"bg-slate-800 text-white",children:"All Accounts"}),j.map(t=>(0,e.jsx)("option",{value:t.id,className:"bg-slate-800 text-white",children:t.displayName||t.name||t.provider||t.id},t.id))]}),N&&(0,e.jsxs)("select",{value:x||"",onChange:t=>ie(t.target.value),className:"bg-white/10 border border-white/20 text-white text-[10px] sm:text-xs rounded-lg px-2 py-1.5 focus:outline-none focus:ring-2 focus:ring-white/40 backdrop-blur-sm",children:[i?.uid&&(0,e.jsx)("option",{value:i.uid,className:"bg-slate-800 text-white",children:"My trades (You)"}),O.map(t=>(0,e.jsxs)("option",{value:t.id,className:"bg-slate-800 text-white",children:["Mentee: ",t.displayName||t.email||t.id]},t.id))]}),Ke&&(0,e.jsx)("span",{className:"text-[10px] text-white/70",children:"Loadingâ¦"}),(h||a.accountId)&&(0,e.jsxs)("div",{className:"px-2 py-1 rounded-full text-[10px] sm:text-xs font-medium bg-sky-500/20 text-sky-200 border border-sky-400/30",children:[I.length," trade",I.length!==1?"s":""]})]}),(0,e.jsx)("div",{className:"analytics-tab-scroll pb-3 -mx-4 px-4",style:{overflowX:"scroll",WebkitOverflowScrolling:"touch",scrollbarWidth:"thin",scrollbarColor:"rgba(148, 163,
2184, 0.6) rgba(30, 41, 59, 0.5)"},children:(0,e.jsx)("div",{className:"flex gap-2 min-w-max",children:g.map(t=>{const r=t.isSubscriptionLocked,n=t.isTradeCountLocked,l=r||n,m=E===t.id,f=n?`Unlocks after 10 closed trades â you have ${R} so far`:r?"Pro feature â upgrade to unlock":null,V=(0,e.jsxs)("button",{onClick:()=>{r||(0,s.startTransition)(()=>Ee(t.id))},style:r?{opacity:.45,cursor:"not-allowed"}:n?{opacity:.6,cursor:"pointer"}:void 0,className:` 3 flex items-center gap-2 px-4 py-3 rounded-xl 4 transition-all duration-200 whitespace-nowrap 5 ${l?"bg-white/30 dark:bg-slate-800/30 border border-gray-200/40 dark:border-slate-700/30":m?"bg-gradient-to-r from-blue-500/20 to-cyan-500/20 border-2 border-blue-500/50 shadow-lg cursor-pointer":"bg-white/60 dark:bg-slate-800/50 border border-gray-200/60 dark:border-slate-700/50 hover:bg-gray-100 dark:hover:bg-slate-700/50 cursor-pointer"} 6 `,children:[(0,e.jsx)("div",{className:`w-8 h-8 rounded-lg flex items-center justify-center bg-gradient-to-br ${t.color} ${m&&!l?"shadow-md":""}`,children:t.icon&&(0,e.jsx)(t.icon,{className:"text-sm text-white"})}),(0,e.jsx)("div",{className:"text-left",children:(0,e.jsxs)("div",{className:`text-xs font-semibold flex items-center gap-1.5 ${m&&!l?"text-white":"text-gray-600 dark:text-slate-300"}`,children:[o(`analytics.tabs.${t.id}`,t.label),n&&(0,e.jsx)("span",{className:"text-[10px] opacity-70",children:"ð"}),r&&!n&&(0,e.jsx)("span",{className:"text-[8px] bg-amber-500/90 px-1 py-0.5 rounded font-semibold",children:"PRO"})]})})]});return f?(0,e.jsx)(tr,{text:f,children:V},t.id):(0,e.jsx)(s.Fragment,{children:V},t.id)})})})]})})}),(0,e.jsx)("main",{className:"analytics-main-area",children:be&&(0,e.jsx)(ks,{componentName:`AnalyticsTab-${E}`,children:(0,e.jsx)(s.Suspense,{fallback:(0,e.jsx)(Js,{}),children:Rt},E)},`eb-${E}`)})]})})]})},rr={blue:"hover:border-blue-500/30",emerald:"hover:border-emerald-500/30",purple:"hover:border-purple-500/30",cyan:"hover:border-cyan-500/30",red:"hover:border-red-500/30",yellow:"hover:border-yellow-500/30",indigo:"hover:border-indigo-500/30",orange:"hover:border-orange-500/30"},ar={blue:"text-blue-400",emerald:"text-emerald-400",purple:"text-purple-400",cyan:"text-cyan-400",red:"text-red-400",yellow:"text-yellow-400",indigo:"text-indigo-400",orange:"text-orange-400"},nr={blue:"text-blue-400",emerald:"text-emerald-400",purple:"text-purple-400",cyan:"text-cyan-400",red:"text-red-400",yellow:"text-yellow-400",indigo:"text-indigo-400",orange:"text-orange-400"},ir={blue:"from-blue-500 to-blue-400",emerald:"from-emerald-500 to-emerald-400",purple:"from-purple-500 to-purple-400",cyan:"from-cyan-500 to-cyan-400",red:"from-red-500 to-red-400",yellow:"from-yellow-500 to-yellow-400",indigo:"from-indigo-500 to-indigo-400",orange:"from-orange-500 to-orange-400"},me=s.memo(({text:o})=>(0,e.jsxs)("div",{className:"group relative inline-flex items-center ml-1 shrink-0",children:[(0,e.jsx)(Pt,{className:"w-3 h-3 flex-shrink-0 text-slate-600 hover:text-slate-400 cursor-help transition-colors",tabIndex:0,role:"button","aria-label":"More information",onKeyDown:c=>{(c.key==="Enter"||c.key===" ")&&c.currentTarget.closest("[role=button]")?.click()}}),(0,e.jsx)("div",{role:"tooltip",className:"pointer-events-none absolute z-[1000] hidden group-hover:block group-focus-within:block bottom-full right-0 mb-1.5 w-52 max-w-[calc(100vw-2rem)] rounded-lg border border-slate-700 bg-slate-900/98 p-2.5 shadow-xl text-[10px] text-slate-300 leading-relaxed",children:o})]}));s.memo(({title:o,value:c,subValue:d,icon:u,color:y="blue",trend:i=null,tooltip:p=null})=>(0,e.jsxs)("div",{className:`relative p-4 bg-white dark:bg-gradient-to-br dark:from-slate-800/80 dark:to-slate-900/60 rounded-xl border border-gray-200 dark:border-slate-700/50 ${rr[y]??"hover:border-blue-500/30"} transition-all duration-300 shadow-sm dark:shadow-none`,children:[p&&(0,e.jsxs)("div",{className:"absolute top-2 right-2 group",children:[(0,e.jsx)("span",{className:"text-slate-500 text-xs cursor-help",tabIndex:0,role:"button","aria-label":"More information",children:"â"}),(0,e.jsx)("div",{role:"tooltip",className:"hidden group-hover:block group-focus-within:block absolute right-0 top-5 w-48 p-2 bg-white dark:bg-slate-800 rounded-lg shadow-xl text-xs text-gray-600 dark:text-slate-300 z-[1000] border border-gray-200 dark:border-slate-600",children:p})]}),(0,e.jsxs)("div",{className:"flex items-center gap-2 mb-2",children:[(0,e.jsx)("span",{className:ar[y]??"text-blue-400",children:u}),(0,e.jsx)("span",{className:"text-xs font-medium text-gray-500 dark:text-slate-400 uppercase tracking-wide",children:o})]}),(0,e.jsxs)("div",{className:"flex items-end justify-between",children:[(0,e.jsxs)("div",{children:[(0,e.jsx)("p",{className:`text-2xl font-bold ${i==="positive"?"text-emerald-400":i==="negative"?"text-red-400":"text-gray-900 dark:text-white"}`,children:c}),d&&(0,e.jsx)("p",{className:"text-xs text-gray-400 dark:text-slate-500 mt-0.5",children:d})]}),i&&(0,e.jsx)("span",{className:`text-xs px-2 py-0.5 rounded-full ${i==="positive"?"bg-emerald-500/20 text-emerald-400":"bg-red-500/20 text-red-400"}`,children:i==="positive"?(0,e.jsx)(ns,{className:"inline","aria-hidden":"true"}):(0,e.jsx)(os,{className:"inline","aria-hidden":"true"})})]})]}));var ue=s.memo(({value:o,max:c=100,color:d="blue",label:u,showPercent:y=!0}
6)=>{const i=Math.min((o||0)/(c>0?c:1)*100,100),p=Number.isFinite(i)?i:0;return(0,e.jsxs)("div",{className:"space-y-1",children:[(0,e.jsxs)("div",{className:"flex justify-between items-center text-xs",children:[(0,e.jsx)("span",{className:"text-gray-500 dark:text-slate-400",children:u}),y&&(0,e.jsxs)("span",{className:`${nr[d]??"text-blue-400"} font-medium`,children:[p.toFixed(0),"%"]})]}),(0,e.jsx)("div",{className:"h-1.5 bg-gray-200 dark:bg-slate-700 rounded-full overflow-hidden",children:(0,e.jsx)("div",{className:`h-full bg-gradient-to-r ${ir[d]??"from-blue-500 to-blue-400"} rounded-full transition-all duration-500`,style:{width:`${p}%`},role:"progressbar","aria-valuenow":Math.round(p),"aria-valuemin":0,"aria-valuemax":100,"aria-label":u})})]})}),lr=s.memo(({analytics:o,trades:c,user:d,agentConfig:u,orgTradeFilter:y,inOrgViewMode:i,currentOrg:p,canViewOrgMembers:$,timeRangeLabel:L="All time (no date filter)",financialLedgerLoading:C=!1,financialLedgerError:H=null,journalTradeCount:k=0,usingJournalAnalytics:W=!1})=>{const{t:K}=ft(),{winRate:G=0,totalTrades:_=0,winningTrades:wt=0,losingTrades:Nt=0,avgWin:Oe=0,avgLoss:Fe=0,totalPL:ze=0,profitFactor:nt=0,bestTrade:Ne=0,worstTrade:it=0,maxDrawdown:Ve=0,maxDrawdownPercent:M=0,recoveryFactor:Y=0,avgRiskPerTrade:$e=0,maxSingleDayLoss:kt=0,maxSingleTradeLoss:We=0,dailyLossLimitHits:ae=0,riskRewardRatio:Be=0,expectedValue:ke=0,largestRisk:Ue=0,riskEfficiency:D=0,winRateAtRisk:pe=0,riskDataCoverage:qe=0,greenDays:lt=0,redDays:P=0,breakEvenDays:He=0,longestGreenStreak:S=0,longestRedStreak:he=0,tradesPerDay:Te=0,tradesPerWeek:ge=0,avgR:h=0,journalingCompleteness:X=0,tradesWithNotes:ne=0,tradesWithTags:F=0,tradesWithScreenshot:j=0,processAdherenceScore:T=0,tradesWithStopLoss:Ae=0,tradesWithinPlanSize:B=0,tradesWithSetup:Ie=0,violationCount:w=0,violationTypes:A=[],revengeTradeCount:z=0,overtradingDays:ie=0,sessionPL:O={premarket:0,regular:0,afterHours:0},sessionCounts:J={premarket:0,regular:0,afterHours:0},bestSession:Ke="",worstSession:_e="",emotionalTags:Q=[],topSetups:le=[],equitySeries:x=[],drawdownSeries:Z=[],tradingDays:fe=0,startingBalance:Ge=2e3}=o||{},Se=i||y&&y!=="personal",oe=p?.name||"Organization",[v,R]=(0,s.use
6State)(null);return o?_===0?(0,e.jsx)(Ms,{}):(0,e.jsxs)("div",{className:"space-y-0 sm:space-y-4 md:space-y-6 pb-20 md:pb-6",children:[W&&(0,e.jsx)("div",{className:"mx-3 sm:mx-0 rounded-xl border border-amber-300/70 bg-amber-50 px-4 py-3 text-sm text-amber-900 dark:border-amber-500/30 dark:bg-amber-500/10 dark:text-amber-200",children:"Showing self-reported journal analytics. Connect a broker to upgrade profitability metrics to verified evidence; your private process analysis remains available now."}),(0,e.jsx)("div",{className:"mb-0 sm:mb-4",children:(0,e.jsx)(Ys,{})}),(0,e.jsxs)("div",{className:"flex flex-wrap items-center gap-2 text-xs text-gray-600 dark:text-slate-300 bg-gray-100 dark:bg-slate-800/60 border-y sm:border border-gray-200 dark:border-slate-700/60 sm:rounded-lg px-4 sm:px-3 py-3 sm:py-2 -mx-0 sm:mx-0",children:[(0,e.jsxs)("span",{className:"font-semibold text-gray-900 dark:text-white",children:[K("analytics.analysisWindow","Analysis window"),":"]}),(0,e.jsx)("span",{className:"text-gray-700 dark:text-white/90",children:L}),(0,e.jsx)(me,{text:`All metrics in Overview use your current filters and this time window (${L}). Adjust the date filter to change the scope.`})]}),Se&&(0,e.jsx)("div",{className:"px-4 py-4 border-b border-gray-200 dark:border-slate-700/50 sm:border sm:rounded-xl sm:mx-0 sm:mb-4 sm:bg-gradient-to-r sm:from-sky-900/30 sm:to-blue-900/30 sm:border-sky-500/30",children:(0,e.jsxs)("div",{className:"flex items-center justify-between",children:[(0,e.jsxs)("div",{className:"flex items-center gap-3",children:[(0,e.jsx)("div",{className:"w-10 h-10 rounded-xl bg-gradient-to-br from-sky-500 to-blue-500 flex items-center justify-center",children:(0,e.jsx)(bt,{className:"text-white"})}),(0,e.jsxs)("div",{children:[(0,e.jsxs)("h3",{className:"text-white font-semibold",children:["Org View: ",oe]}),(0,e.jsxs)("p",{className:"text-sky-300 text-xs",children:[$?"Manager Dashboard":"Member Analytics"," ⢠",_," trades tracked"]})]})]}),$&&(0,e.jsxs)("div",{className:"flex items-center gap-4 text-xs",children:[(0,e.jsxs)("div",{className:"text-center",children:[(0,e.jsx)("p",{className:"text-slate-400",children:"Violations"}),(0,e.jsx)("p",{className:`font-bold ${w>0?"text-red-400":"text-emerald-400"}`,children:w})]}),(0,e.jsxs)("div",{className:"text-center",children:[(0,e.jsx)("p",{className:"text-slate-400",children:"Rule Compliance"}),(0,e.jsxs)("p",{className:`font-bold ${(T||0)>=80?"text-emerald-400":(T||0)>=60?"text-yellow-400":"text-red-400"}`,children:[Number.isFinite(T)?T.toFixed(0):"0","%"]})]})]})]})}),(0,e.jsx)("div",{"data-tour":"analytics-key-metrics",children:(0,e.jsx)(s.Suspense,{fallback:(0,e.jsx)("div",{className:"h-40 rounded-xl bg-gray-100 dark:bg-slate-800/50 animate-pulse","aria-label":"Loading performance metrics"}),children:(0,e.jsx)(Xs,{analytics:o,trades:c,timeRangeLabel:L})})}),(0,e.jsxs)("div",{className:"space-y-4",children:[(0,e.jsx)("div",{"data-tour":"analytics-charts",children:(0,e.jsx)(s.Suspense,{fallback:(0,e.jsx)("div",{className:"h-64 rounded-xl bg-gray-100 dark:bg-slate-800/50 animate-pulse","aria-label":"Loading equity curve"}),children:(0,e.jsx)(zs,{trades:c,showAllTrades:!0,embedded:!1})})}),Z.length>1&&(0,e.jsxs)("div",{className:"analytics-card rounded-xl p-4",children:[(0,e.jsxs)("div",{className:"flex items-center gap-2 mb-3",children:[(0,e.jsx)(xe,{className:"text-red-400 text-sm","aria-hidden":"true"}),(0,e.jsx)("h4",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"Drawdown"}),(0,e.jsx)(me,{text:"Percentage drawdown from peak equity over time. Deeper troughs indicate larger losing runs relative to your starting balance."})]}),(0,e.jsx)(_s,{width:"100%",height:120,children:(0,e.jsxs)(Rs,{data:Z,margin:{top:4,right:4,left:0,bottom:0},children:[(0,e.jsx)("defs",{children:(0,e.jsxs)("linearGradient",{id:"ddGradient",x1:"0",y1:"0",x2:"0",y2:"1",children:[(0,e.jsx)("stop",{offset:"5%",stopColor:"#EF4444",stopOpacity:.3}),(0,e.jsx)("stop",{offset:"95%",stopColor:"#EF4444",stopOpacity:.02})]})}),(0,e.jsx)(Cs,{strokeDasharray:"3 3",stroke:"rgba(100,116,139,0.15)"}),(0,e.jsx)(Ss,{dataKey:"date",tick:{fontSize:10,fill:"#64748b"},interval:"preserveStartEnd"}),(0,e.jsx)(Ls,{tick:{fontSize:10,fill:"#64748b"},tickFormatter:g=>`${g.toFixed(1)}%`,domain:["auto",0],width:45}),(0,e.jsx)(Es,{contentStyle:{backgroundColor:"#0f172a",border:"1px solid #334155",borderRadius:8,fontSize:12},formatter:g=>[`${g.toFixed(2)}%`,"Drawdown"],labelFormatter:g=>`Trade: ${g}`}),(0,e.jsx)(Is,{y:0,stroke:"#475569",strokeDasharray:"3 3"}),(0,e.jsx)(As,{type:"monotone",dataKey:"drawdown",stroke:"#EF4444",strokeWidth:1.5,fill:"url(#ddGradient)",dot:!1})]})})]})]}),(0,e.jsx)("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-3 md:gap-6",children:(0,e.jsxs)("div",{className:"analytics-card rounded-2xl md:rounded-xl",children:[(0,e.jsxs)("div",{className:"flex items-center justify-between mb-3 md:mb-4 gap-2",children:[(0,e.jsx)("h3",{className:"text-sm md:text-base font-semibold text-gray-900 dark:text-white",children:"Highlights"}),(0,e.jsx)(me,{text:`High-signal overview for ${L}: best setups and key behavior risks. This avoids repeating core performance metrics already shown above.`})]}),(0,e.jsxs)("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[(0,e.jsxs)("div",{className:"p-3 bg-gray-50 dark:bg-gradient-to-br dark:from-slate-800/50 dark:to-slate-900/50 rounded-xl border border-gray-200 dark:border-slate-700/50",children:[(0,e.jsxs)("div",{className:"flex items-center justify-between mb-2",children:[(0,e.jsx)("p",{className:"text-gray-700 dark:text-slate-300 text-sm font-semibold",children:"Top Setups"}),(0,e.jsx)("span",{className:"text-[10px] text-gray-400 dark:text-slate-500",children:"Edge leaders"})]}),le.length>
60?(0,e.jsx)("div",{className:"space-y-2",children:le.slice(0,4).map((g,N)=>(0,e.jsxs)("div",{className:"flex items-center justify-between p-2 bg-gray-100 dark:bg-slate-800/40 rounded-lg",children:[(0,e.jsxs)("div",{className:"flex items-center gap-2 min-w-0",children:[(0,e.jsx)("span",{className:`w-6 h-6 rounded-full flex items-center justify-center text-xs font-bold flex-shrink-0 ${N===0?"bg-yellow-500/20 text-yellow-400":N===1?"bg-slate-400/20 text-slate-300":N===2?"bg-orange-500/20 text-orange-400":"bg-emerald-500/15 text-emerald-300"}`,children:N+1}),(0,e.jsx)("span",{className:"text-sm text-gray-900 dark:text-white truncate",children:g.setup})]}),(0,e.jsxs)("div",{className:"flex items-center gap-3 text-xs flex-shrink-0",children:[(0,e.jsxs)("span",{className:`${(g.winRate||0)>=50?"text-emerald-400":"text-yellow-400"}`,children:[Number.isFinite(g.winRate)?g.winRate.toFixed(0):"0","% WR"]}),(0,e.jsx)("span",{className:"text-slate-500",children:g.count||0})]})]},g.setup))}):(0,e.jsx)("div",{className:"text-gray-400 dark:text-slate-500 text-sm py-2",children:"No setups logged yet"})]}),(0,e.jsxs)("div",{className:"p-3 bg-gray-50 dark:bg-gradient-to-br dark:from-slate-800/50 dark:to-slate-900/50 rounded-xl border border-gray-200 dark:border-slate-700/50",children:[(0,e.jsxs)("div",{className:"flex items-center justify-between mb-2",children:[(0,e.jsx)("p",{className:"text-gray-700 dark:text-slate-300 text-sm font-semibold",children:"Behavior Risks"}),(0,e.jsx)("span",{className:"text-[10px] text-gray-400 dark:text-slate-500",children:"Watch list"})]}),(0,e.jsxs)("div",{className:"space-y-2",children:[(0,e.jsxs)("div",{className:"flex items-center justify-between p-2 bg-gray-100 dark:bg-slate-800/40 rounded-lg",children:[(0,e.jsxs)("div",{className:"flex items-center gap-2",children:[(0,e.jsx)("span",{className:"text-red-400",role:"img","aria-label":"Revenge trades indicator",children:"ð¥"}),(0,e.jsx)("span",{className:"text-sm text-gray-600 dark:text-slate-300",children:"Revenge Trades"})]}),(0,e.jsx)("span",{className:`text-sm font-semibold ${z>0?"text-red-400":"text-emerald-400"}`,children:z})]}),(0,e.jsxs)("div",{className:"flex items-center justify-between p-2 bg-gray-100 dark:bg-slate-800/40 rounded-lg",children:[(0,e.jsxs)("div",{className:"flex items-center gap-2",children:[(0,e.jsx)("span",{className:"text-orange-400",role:"img","aria-label":"Overtrading indicator",children:"â¡"}),(0,e.jsx)("span",{className:"text-sm text-gray-600 dark:text-slate-300",children:"Overtrading Days"})]}),(0,e.jsx)("span",{className:`text-sm font-semibold ${ie>0?"text-orange-400":"text-emerald-400"}`,children:ie})]}),(0,e.jsxs)("div",{className:"flex items-center justify-between p-2 bg-gray-100 dark:bg-slate-800/40 rounded-lg",children:[(0,e.jsxs)("div",{className:"flex items-center gap-2",children:[(0,e.jsx)("span",{className:"text-yellow-400",role:"img","aria-label":"Red streak indicator",children:"ð"}),(0,e.jsx)("span",{className:"text-sm text-gray-600 dark:text-slate-300",children:"Max Red Streak"})]}),(0,e.jsxs)("span",{className:`text-sm font-semibold ${he>3?"text-red-400":"text-yellow-400"}`,children:[he," days"]})]})]}),(Q.length>0||w>0)&&(0,e.jsxs)("div",{className:"mt-3 pt-3 border-t border-slate-700/60",children:[w>0&&(0,e.jsxs)("div",{className:"flex items-center justify-between text-xs mb-2",children:[(0,e.jsx)("span",{className:"text-slate-400",children:"Violations"}),(0,e.jsx)("span",{className:"text-red-400 font-semibold",children:w})]}),Q.length>0&&(0,e.jsxs)("div",{children:[(0,e.jsx)("p",{className:"text-xs text-slate-400 mb-2",children:"Top Emotions"}),(0,e.jsx)("div",{className:"flex flex-wrap gap-1",children:Q.slice(0,3).map(({emotion:g,count:N})=>(0,e.jsxs)("span",{className:"text-xs px-2 py-1 bg-gray-200 dark:bg-slate-700 rounded-full text-gray-600 dark:text-slate-300",children:[g," (",N,")"]},g))})]})]})]})]})]})}),(0,e.jsxs)("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-3 md:gap-6",children:[(0,e.jsxs)("div",{className:"analytics-card rounded-xl p-4",children:[(0,e.jsxs)("div",{className:"flex items-center justify-between mb-4",children:[(0,e.jsxs)("div",{className:"flex items-center gap-2",children:[(0,e.jsx)("div",{className:"w-8 h-8 rounded-lg bg-blue-500/20 flex items-center justify-center",children:(0,e.jsx)(cs,{className:"text-blue-400 text-sm","aria-hidden":"true"})}),(0,e.jsxs)("div",{children:[(0,e.jsxs)("h4",{className:"text-sm font-semibold text-gray-900 dark:text-white flex items-center gap-1",children:["Process Adherence",(0,e.jsx)(me,{text:`Per-trade habit completion across ${L}. Score = fraction of trades with stop loss set, setup tagged, and size within plan. Higher = more disciplined execution.`})]}),(0,e.jsx)("p",{className:"text-[10px] text-gray-400 dark:text-slate-500",children:"Per-trade habit completion rate"})]})]}),(0,e.jsxs)("div",{className:`text-2xl font-bold ${(T||0)>=80?"text-emerald-400":(T||0)>=60?"text-yellow-400":"text-red-400"}`,children:[Number.isFinite(T)?T.toFixed(0):"0",(0,e.jsx)("span",{className:"text-sm text-gray-400 dark:text-slate-500",children:"/100"})]})]}),(0,e.jsxs)("div",{className:"space-y-3",children:[(0,e.jsx)(ue,{value:Ae,max:_,color:"emerald",label:"Stop Loss Set"}),(0,e.jsx)(ue,{value:Ie,max:_,color:"blue",label:"Setup Logged"}),(0,e.jsx)(ue,{value:B,max:_,color:"purple",label:"Within Plan Size"})]}),w>0&&(0,e.jsx)("div",{className:"mt-3 pt-3 border-t border-gray-200 dark:border-slate-700",children:(0,e.jsxs)("div",{className:"flex items-center gap-2 text-red-400 text-xs",children:[(0,e.jsx)(vt,{}),(0,e.jsxs)("span",{children:[w," violations detected"]})]})})]}),(0,e.jsxs)("div",{className:"analytics-card rounded-xl p-4",children:[(0,e.jsxs)("div",{className:"flex items-center justify-between mb-4",children:[(0,e.jsxs)("div",{className:"flex items-center gap-2",children:[(0,e.jsx)("div",{className:"w-8 h-8 rounded-lg bg-purple-500/20 flex items-center justify-center",children:(0,e.jsx)(at,{className:"text-purple-400 text-sm"})}),(0,e.jsxs)("div",{children:[(0,e.jsxs)("h4",{className:"text-sm font-semibold text-gray-900 dark:text-white flex items-center gap-1",children:["Journaling Quality",(0,e.jsx)(me,{text:`Documentation habits for ${L}. Percentages show how many filtered trades had notes, tags, and screenshots.`})]}),(0,e.jsx)("p",{className:"text-[10px] text-gray-400 dark:text-slate-500",children:"Trade documentation rate"})]})]}
6),(0,e.jsxs)("div",{className:`text-2xl font-bold ${(X||0)>=70?"text-emerald-400":(X||0)>=40?"text-yellow-400":"text-red-400"}`,children:[Number.isFinite(X)?X.toFixed(0):"0",(0,e.jsx)("span",{className:"text-sm text-gray-400 dark:text-slate-500",children:"%"})]})]}),(0,e.jsxs)("div",{className:"space-y-3",children:[(0,e.jsx)(ue,{value:ne,max:_,color:"purple",label:"With Notes"}),(0,e.jsx)(ue,{value:F,max:_,color:"blue",label:"With Tags"}),(0,e.jsx)(ue,{value:j,max:_,color:"cyan",label:"With Charts"})]})]})]}),(0,e.jsxs)("div",{className:"analytics-card rounded-xl p-4",children:[(0,e.jsxs)("div",{className:"flex items-center justify-between mb-4",children:[(0,e.jsxs)("div",{className:"flex items-center gap-2",children:[(0,e.jsx)("div",{className:"w-8 h-8 rounded-lg bg-indigo-500/20 flex items-center justify-center",children:(0,e.jsx)(ls,{className:"text-indigo-400 text-sm"})}),(0,e.jsxs)("div",{children:[(0,e.jsxs)("h4",{className:"text-sm font-semibold text-white flex items-center gap-1",children:["Session Performance",(0,e.jsx)(me,{text:`P/L by session across ${L}. Trades are bucketed into pre-market, regular, and after-hours based on entry time.`})]}),(0,e.jsx)("p",{className:"text-[10px] text-slate-500",children:"P/L by market session"})]})]}),(0,e.jsxs)("div",{className:"text-right",children:[(0,e.jsxs)("p",{className:"text-xs text-slate-400",children:["Best: ",(0,e.jsx)("span",{className:"text-emerald-400",children:Ke})]}),(0,e.jsxs)("p",{className:"text-xs text-slate-400",children:["Worst: ",(0,e.jsx)("span",{className:"text-red-400",children:_e})]})]})]}),(0,e.jsx)("div",{className:"grid grid-cols-3 gap-3",children:[{label:"Pre-Market",pl:O.premarket,count:J.premarket},{label:"Regular",pl:O.regular,count:J.regular},{label:"After-Hours",pl:O.afterHours,count:J.afterHours}].map(({label:g,pl:N,count:U})=>(0,e.jsxs)("div",{className:`p-3 rounded-lg text-center ${N>=0?"bg-emerald-900/20 border border-emerald-500/30":"bg-red-900/20 border border-red-500/30"}`,children:[(0,e.jsx)("p",{className:"text-xs text-slate-400 mb-1",children:g}),(0,e.jsx)("p",{className:`text-lg font-bold ${N>=0?"text-emerald-400":"text-red-400"}`,children:Qs(N)}),(0,e.jsxs)("p",{className:"text-[10px] text-slate-500 mt-0.5",children:[U," trade",U!==1?"s":""]})]},g))})]})]}):(0,e.jsxs)("div",{className:"flex flex-col items-center justify-center py-24 text-center space-y-4",children:[(0,e.jsx)("div",{className:"w-16 h-16 rounded-full bg-gray-100 dark:bg-slate-700/50 flex items-center justify-center",children:(0,e.jsx)(xe,{className:"text-gray-400 dark:text-slate-500 text-2xl"})}),(0,e.jsxs)("div",{children:[(0,e.jsx)("p",{className:"font-semibold text-gray-900 dark:text-white",children:C?"Verifying executionsâ¦":"No verified analytics yet"}),(0,e.jsx)("p",{className:"text-gray-500 dark:text-slate-400 text-sm mt-1",children:k>0?H?"Verified execution evidence is unavailable for this account.":"Existing trades remain in your journal, but profitability metrics wait for verified broker or execution evidence.":"Log your first trade to see your performance dashboard."})]})]})}),br=s.memo(sr);export{br as default};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.