PageSourceSearch

https://chartmentor.io/assets/Account-BcXbn6Hk.js

js chartmentor.io collected 2026-09-24 15:03:42 UTC 102,331 bytes, 265 lines download raw bytes

1import{r as i,j as e,L as ce,n as dt,m as Yt}from"./react-vendor-CdbEkvHB.js";import{u as Pe,f as ee,a as zt,B as w,L as R,n as C,A as Gt,b as ae,c as ne,d as ie,q as xe,r as Kt,v as Qt,w as Xt,x as Zt,y as Jt,z as es,E as ts,G as ss,t as pe,N as ut,C as mt,H as oe,I as rs,h as as,s as ns,J as is,K as os}from"./index-JLjMfWcU.js";import{C as ls}from"./checkbox-BVNP93ES.js";import{C as H,a as G,b as K,c as Q,d as Y}from"./card-D-_Bsl1M.js";import{m as cs,s as ds,t as ht,u as pt,A as us,v as ft,w as ms,x as hs,E as ps,P as fs,R as J,y as Re,c as xs,l as Ve,z as gs,F as bs,G as ys,H as He,k as vs,I as je,e as ws,J as js,K as Ns,N as Ae,O as ks,Z as xt,Q as _s,V as Cs,f as gt,_ as Ye}from"./icons-L2uz_W8N.js";import{L as X}from"./label-DFAgYZ0S.js";import{S as bt,a as yt,b as vt,c as wt,d as le}from"./select-DXLgYjsM.js";import{T as Me}from"./textarea-BScTIVPV.js";import{c as de,T as As}from"./tabs-DNNZW8nN.js";import{F as Ss}from"./FirstReviewWalkthrough-CBXfDMZH.js";import{D as Ts,a as Es,b as ze,c as Ge,d as Ke,e as Ps}from"./dialog-CP-Yg244.js";import{A as Rs}from"./AccountSectionNav-De0VKNW_.js";import{I as Z}from"./input-DyZ3sHv6.js";import{y as Ms,z as Is,B as Fs}from"./radix-ui-CSxGpBRr.js";import{P as Ls}from"./progress-DFN4Cbko.js";import{B as Qe}from"./badge-CqxdFDoy.js";import{T as Ds,a as Os,b as Xe,c as $,d as qs,e as V}from"./table-qpHXHNUG.js";import{a as Us}from"./authDestination-Dn0rvoAS.js";import"./supabase-CxM-nLeM.js";const Ws=({onAccepted:t})=>{const{user:s}=Pe(),{toast:r}=ee(),[a,n]=i.useState(!1),[l,o]=i.useState(!1),c=async()=>{if(!s||!a)return;o(!0);const{error:d}=await C.from("profiles").update({disclaimer_accepted:!0,disclaimer_accepted_at:new Date().toISOString()}).eq("id",s.id);o(!1),d?r({title:"Error",description:"Failed to save acceptance. Please try again.",variant:"destructive"}):t()};return e.jsx("div",{className:"fixed inset-0 z-50 bg-background flex items-center justify-center px-4",children:e.jsxs(H,{className:"w-full max-w-lg border-border bg-card",children:[e.jsxs(G,{className:"text-center",children:[e.jsx("div",{className:"flex justify-center mb-4",children:e.jsx("div",{className:"p-3 bg-accent/10 rounded-xl",children:e.jsx(zt,{className:"h-10 w-10"})})}),e.jsx(K,{className:"text-2xl",children:"Legal Agreement Required"}),e.jsx(Q,{className:"mt-2",children:"Before using ChartMentor, please review and accept our legal terms."})]}),e.jsxs(Y,{className:"space-y-6",children:[e.jsx("div",{className:"bg-destructive/10 border border-destructive/30 rounded-lg p-4",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(cs,{className:"h-5 w-5 text-destructive mt-0.5 shrink-0"}),e.jsx("p",{className:"text-sm text-destructive font-medium",children:"ChartMentor does NOT provide financial advice. All AI-generated analyses are for educational and informational purposes only. Trading involves substantial risk of loss."})]})}),e.jsxs("div",{className:"flex items-start space-x-3",children:[e.jsx(ls,{id:"disclaimer-accept",checked:a,onCheckedChange:d=>n(d===!0),className:"mt-1"}),e.jsxs("label",{htmlFor:"disclaimer-accept",className:"text-sm text-muted-foreground leading-relaxed cursor-pointer",children:["I have read and agree to the"," ",e.jsx("a",{href:"/terms",target:"_blank",className:"text-accent hover:underline",children:"Terms of Service"}),","," ",e.jsx("a",{href:"/privacy",target:"_blank",className:"text-accent hover:underline",children:"Privacy Policy"}),", and"," ",e.jsx("a",{href:"/disclaimer",target:"_blank",className:"text-accent hover:underline",children:"Disclaimer"}),". I understand that ChartMentor does ",e.jsx("strong",{children:"NOT"})," provide financial advice and all AI analyses are for educational purposes only."]})]}),e.jsx(w,{className:"w-full",disabled:!a||l,onClick:c,children:l?e.jsxs(e.Fragment,{children:[e.jsx(R,{className:"mr-2 h-4 w-4"}),"Saving..."]}):"Continue to ChartMentor"})]})]})})},Bs=["starter","pro","elite"];function jt(t){return Bs.includes(t||"")}function $s(t){return t==="free"||t===null}function Vs(t){const{planTier:s,subscriptionStatus:r,scansThisMonth:a,monthlyLimit:n,firstAnalysisCompleted:l}=t;return jt(s)&&r==="active"?"paid":a>
1=n?"free_limit_reached":$s(s)?l?"first_value":"activated":"signup"}function Hs(t){switch(t){case"signup":return"Try free";case"activated":return"Get started with your first analysis";case"first_value":return"Keep exploring";case"free_limit_reached":return"Upgrade to continue";case"paid":return"Enjoy full access"}}function Ys({profile:t}){const{toast:s}=ee(),[r,a]=i.useState("bug"),[n,l]=i.useState(""),[o,c]=i.useState(!1),d=async()=>{c(!0);try{const p=crypto.randomUUID(),m=r,f=n.trim(),{error:h}=await C.from("bug_reports").insert({id:p,user_id:t.id,user_email:t.email,category:m,description:f});if(h){s({title:"Error",description:"Failed to submit report",variant:"destructive"});return}s({title:"Report submitted",description:"Thanks. We will review it from the admin panel."}),l(""),a("bug"),C.functions.invoke("send-email",{body:{type:"report-received",userId:t.id,reportId:p,reportCategory:m,reportDescription:f,reportUserEmail:t.email}}).catch(x=>console.warn("[bug-report] auto-ack email failed",x))}catch(p){s({title:"Error",description:p instanceof Error?p.message:"Failed to submit report",variant:"destructive"})}finally{c(!1)}};return e.jsxs(H,{id:"report-problem",className:"border-border bg-card scroll-mt-24",children:[e.jsx(G,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"rounded-md bg-primary/10 p-2",children:e.jsx(ds,{className:"h-5 w-5 text-primary","aria-hidden":"true"})}),e.jsxs("div",{children:[e.jsx(K,{children:"Report a problem"}),e.jsx(Q,{children:"Send a concrete issue or product suggestion."})]})]})}),e.jsxs(Y,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(X,{htmlFor:"bugCategory",children:"Category"}),e.jsxs(bt,{value:r,onValueChange:a,children:[e.jsx(yt,{id:"bugCategory",children:e.jsx(vt,{})}),e.jsxs(wt,{children:[e.jsx(le,{value:"bug",children:"Bug"}),e.jsx(le,{value:"performance",children:"Performance"}),e.jsx(le,{value:"feature",children:"Feature request"}),e.jsx(le,{value:"other",children:"Other"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(X,{htmlFor:"bugDesc",children:"Description"}),e.jsx(Me,{id:"bugDesc",placeholder:"What happened, and what did you expect?",value:n,onChange:p=>l(p.target.value.slice(0,2e3)),rows:4}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[n.length," / 2000 characters"]})]}),e.jsxs(w,{className:"w-full",disabled:o||n.trim().length<10,onClick:()=>{d()},children:[o?e.jsx(R,{className:"mr-2 h-4 w-4"}):e.jsx(ht,{className:"mr-2 h-4 w-4"}),o?"Submitting...":"Submit report"]})]})]})}function zs({profile:t}){return e.jsxs(de,{value:"help",className:"mt-0 space-y-4",children:[e.jsxs("section",{className:"rounded-md border border-border bg-card",children:[e.jsxs("div",{className:"border-b border-border px-4 py-3",children:[e.jsx("h2",{className:"text-base font-semibold tracking-tight",children:"How to use ChartMentor"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-muted-foreground",children:"Practices that make each plan review sharper."})]}),e.jsx("div",{className:"px-4 py-3",children:e.jsxs(Gt,{type:"multiple",className:"w-full",children:[e.jsxs(ae,{value:"prompts",children:[e.jsx(ne,{children:"How Your Strategy Lens Works"}),e.jsxs(ie,{className:"text-muted-foreground space-y-2",children:[e.jsx("p",{children:"ChartMentor auto-selects a Strategy Lens (ICC, breakout, mean reversion, and more) calibrated to your market and setup. When you converse with your mentor on the TradingView chart, it learns your preferred style and confirms your trading rules."}),e.jsx("p",{children:"How your mentor calibrates to you:"}),e.jsxs("ul",{className:"list-disc list-inside ml-4 space-y-1",children:[e.jsx("li",{children:"Your declared market, session, and typical timeframe"}),e.jsx("li",{children:"Your confirmed strategy and playbook rules"}),e.jsx("li",{children:"Your recurring mistakes, seeded in the Setup tab or learned over time"})]}),e.jsx("p",{children:"You can review and update your seeded rules and recurring mistakes anytime from the Setup tab."})]})]}),e.jsxs(ae,{value:"review-plan",children:[e.jsx(ne,{children:"How Plan Review Works"}),e.jsxs(ie,{className:"text-muted-foreground space-y-2",children:[e.jsx("p",{children:"Mark a TradingView Long or Short Position, or enter direction, entry, stop, and target manually. ChartMentor then reviews the declared thesis through your Strategy Lens."}),e.jsxs("ul",{className:"list-disc list-inside ml-4 space-y-1",children:[e.jsxs("li",{children:[e.jsx("strong",{children:"Observed facts:"})," what is actually visible in the chart and in the plan you stated"]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Questions and conflicts:"})," what is missing or breaks a rule in your saved playbook"]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Your decision:"})," take it, change it, or skip it; the mentor never chooses long or short for you"]})]}),e.jsx("p",{children:"After the trade is due, record the outcome so the mentor can connect future reviews to the mistakes you actually repeat."})]})]}),e.jsxs(ae,{value:"chart",children:[e.jsx(ne,{children:"Chart Best Practices"}),e.jsxs(ie,{className:"text-muted-foreground space-y-2",children:[e.jsx("p",{children:"For the best results:"}),e.jsxs("ul",{className:"list-disc list-inside ml-4 space-y-1",children:[e.jsxs("li",{children:[e.jsx("strong",{children:"Make sure the chart is fully loaded"})," - partially rendered candles, broker panels, or popups can degrade the screenshot analysis"]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Zoom appropriately"})," - too zoomed in or too compressed can hide the structure behind the plan"]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Indicators are helpful but optional"})," - if RSI, MACD, moving averages, volume, or custom indicators are visible, ChartMentor will read them"]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Keep the right TradingView chart active"}
1)," - ChartMentor receives symbol and timeframe context from TradingView, but price action, levels, and annotations still need to be visible on screen"]})]})]})]}),e.jsxs(ae,{value:"trades",children:[e.jsx(ne,{children:"Trade Plans & Drawing Tools"}),e.jsxs(ie,{className:"text-muted-foreground space-y-2",children:[e.jsx("p",{children:"ChartMentor recognizes TradingView's visual elements, but separates your planned trade from indicator output:"}),e.jsxs("ul",{className:"list-disc list-inside ml-4 space-y-1",children:[e.jsxs("li",{children:[e.jsx("strong",{children:"Trade boxes:"})," TradingView position tools and manual trade boxes declare the plan ChartMentor should review; a toolbar label alone is not treated as a plan"]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Position markers:"})," Entry, take-profit, and stop-loss lines are recognized when clearly visible and manually marked"]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Drawing tools:"})," Trendlines, channels, Fibonacci levels, and other drawings are visible to the AI"]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Alerts and annotations:"})," If you have price alerts or text notes on the chart, the AI will read them"]})]}),e.jsx("p",{children:"If you want open-position management, say the trade is already open. Otherwise ChartMentor treats visible levels as pre-entry context."})]})]}),e.jsxs(ae,{value:"indicators",children:[e.jsx(ne,{children:"Custom Indicators"}),e.jsxs(ie,{className:"text-muted-foreground space-y-2",children:[e.jsxs("p",{children:["You can use ",e.jsx("strong",{children:"any indicator"})," on your chart - the AI reads whatever is visually displayed, but indicator-generated trade labels are context, not your marked trade plan. This includes:"]}),e.jsxs("ul",{className:"list-disc list-inside ml-4 space-y-1",children:[e.jsx("li",{children:"Standard indicators (MA, EMA, RSI, MACD, Bollinger Bands, etc.)"}),e.jsx("li",{children:"Custom/community TradingView indicators"}),e.jsx("li",{children:"Volume profiles and market profiles"}),e.jsx("li",{children:"Any overlay or oscillator visible on the chart"})]}),e.jsx("p",{children:"Keep the chart readable. A few well-chosen indicators plus clean structure usually outperform a chart overloaded with overlapping overlays."})]})]})]})})]}),e.jsx(Ys,{profile:t})]})}function Gs({profile:t,onSignOut:s}){return e.jsx(de,{value:"options",className:"mt-0 space-y-4",children:e.jsxs("section",{className:"rounded-md border border-border bg-card",children:[e.jsxs("div",{className:"border-b border-border px-4 py-3",children:[e.jsx("h2",{className:"text-base font-semibold tracking-tight",children:"Account"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-muted-foreground",children:"Identity, billing, settings, and your session."})]}),e.jsxs("dl",{className:"grid grid-cols-1 gap-px bg-border sm:grid-cols-2",children:[e.jsxs("div",{className:"bg-card px-4 py-3",children:[e.jsx("dt",{className:"text-xs text-muted-foreground",children:"Name"}),e.jsx("dd",{className:"mt-1 text-sm font-medium",children:t.full_name||"Not set"})]}),e.jsxs("div",{className:"bg-card px-4 py-3",children:[e.jsx("dt",{className:"text-xs text-muted-foreground",children:"Email"}),e.jsx("dd",{className:"mt-1 truncate text-sm font-medium",children:t.email})]})]}),e.jsxs("div",{className:"flex flex-col gap-2 border-t border-border px-4 py-3 sm:flex-row sm:items-center",children:[e.jsx(w,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs(ce,{to:"/account/billing",children:[e.jsx(pt,{className:"mr-2 h-4 w-4","aria-hidden":"true"}),"Billing",e.jsx(us,{className:"ml-2 h-4 w-4","aria-hidden":"true"})]})}),e.jsx(w,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs(ce,{to:"/settings",children:[e.jsx(ft,{className:"mr-2 h-4 w-4","aria-hidden":"true"}),"Settings"]})}),e.jsx(w,{variant:"ghost",size:"sm",className:"sm:ml-auto text-destructive hover:bg-destructive/10 hover:text-destructive",onClick:()=>{s()},children:"Sign out"})]})]})})}function Ks({isPreview:t,onDismissForever:s,onContinue:r,onExitPreview:a}){return e.jsx("div",{role:"dialog","aria-modal":"true","aria-labelledby":"account-onboarding-title",className:"fixed inset-0 z-[80] flex items-start justify-center overflow-y-auto bg-background/95 px-4 py-10",children:e.jsx("div",{className:"w-full max-w-4xl rounded-md border border-border bg-card",children:e.jsxs("div",{className:"space-y-5 p-5 md:p-6",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:t?"Onboarding preview":"Onboarding"}),e.jsx("h2",{id:"account-onboarding-title",className:"text-xl font-semibold tracking-tight",children:"From your chart to your first review."}),e.jsx("p",{className:"max-w-2xl text-sm text-muted-foreground",children:"Bring a plan, talk it through, then make your decision. You can follow these steps at your own pace."})]}),e.jsx(Ss,{}),e.jsxs("div",{className:"flex flex-col-reverse gap-3 border-t border-border pt-4 md:flex-row md:items-center md:justify-between",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Your AI mentor is ready on TradingView. The mentor learns your rules and strategy in conversation on your chart."}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row",children:[t?e.jsx(w,{variant:"outline",asChild:!0,children:e.jsx(ce,{to:"/account",onClick:a,children:"Exit preview"})}):e.jsx(w,{variant:"outline",onClick:s,children:"Don't show this again"}),e.jsx(w,{onClick:r,children:"Continue to workspace"})]})]})]})})})}const Ze=2e3,Qs=10;function Xs({shouldShowBanner:t,open:s,step:r,feedback:a,submitting:n,onOpenChange:l,onOpenBanner:o,onStepChange:c,onFeedbackChange:d,onHappyReviewClick:p,onSubmitFeedback:m}){return e.jsxs(e.Fragment,{children:[t&&e.jsxs("div",{className:"flex flex-col gap-2 rounded-md border border-border bg-card px-4 py-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:"How is ChartMentor holding up?"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"A short answer helps us improve the plan-review w
1orkflow."})]}),e.jsx(w,{size:"sm",variant:"outline",className:"shrink-0",onClick:o,children:"Share opinion"})]}),e.jsx(Ts,{open:s,onOpenChange:l,children:e.jsx(Es,{className:"sm:max-w-md",children:r==="question"?e.jsxs(e.Fragment,{children:[e.jsxs(ze,{children:[e.jsx(Ge,{children:"Are you happy with ChartMentor?"}),e.jsx(Ke,{children:"If it is helping your pre-trade review workflow, a Chrome Web Store review helps other traders find it. If it is not, tell us what to fix privately."})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs(w,{onClick:p,className:"h-auto justify-start gap-3 py-4",children:[e.jsx(ms,{className:"h-4 w-4 shrink-0","aria-hidden":"true"}),e.jsxs("span",{className:"text-left",children:[e.jsx("span",{className:"block font-semibold",children:"Yes"}),e.jsx("span",{className:"block text-xs font-normal opacity-80",children:"Leave a public review"})]})]}),e.jsxs(w,{variant:"outline",onClick:()=>c("feedback"),className:"h-auto justify-start gap-3 py-4",children:[e.jsx(hs,{className:"h-4 w-4 shrink-0","aria-hidden":"true"}),e.jsxs("span",{className:"text-left",children:[e.jsx("span",{className:"block font-semibold",children:"Not yet"}),e.jsx("span",{className:"block text-xs font-normal text-muted-foreground",children:"Send private feedback"})]})]})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(ze,{children:[e.jsx(Ge,{children:"What should we improve?"}),e.jsx(Ke,{children:"This stays private and appears in the admin panel as review feedback."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(X,{htmlFor:"reviewFeedback",children:"Feedback"}),e.jsx(Me,{id:"reviewFeedback",value:a,onChange:f=>d(f.target.value.slice(0,Ze)),placeholder:"What felt weak, confusing, missing, or not useful?",rows:5}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[a.length," / ",Ze," characters"]})]}),e.jsxs(Ps,{className:"gap-2 sm:justify-between",children:[e.jsx(w,{type:"button",variant:"ghost",onClick:()=>c("question"),disabled:n,children:"Back"}),e.jsxs(w,{type:"button",onClick:()=>{m()},disabled:n||a.trim().length<Qs,children:[n?e.jsx(R,{className:"mr-2 h-4 w-4","aria-hidden":"true"}):e.jsx(ht,{className:"mr-2 h-4 w-4","aria-hidden":"true"}),"Send feedback"]})]})]})})})]})}function Zs({mentorSeedSection:t}){return e.jsx(de,{value:"setup",className:"mt-0 space-y-3 sm:space-y-4",children:t})}function Js({extensionPresent:t,hasUsedFreeReview:s,planName:r,isPaidAccount:a,nextAction:n,onAnchorClick:l}){const o=n.href.startsWith("#")?e.jsx(w,{size:"sm",variant:"outline",className:"min-h-10 w-full whitespace-nowrap sm:w-auto",onClick:()=>l(n.href),children:n.cta}):e.jsx(w,{size:"sm",asChild:!0,className:"min-h-10 w-full whitespace-nowrap sm:w-auto",children:e.jsxs("a",{href:n.href,target:n.external?"_blank":void 0,rel:n.external?"noreferrer":void 0,children:[n.cta,n.external&&e.jsx(ps,{className:"ml-2 h-3.5 w-3.5","aria-hidden":"true"})]})});return e.jsxs("section",{"aria-label":"Mentor profile status",className:"rounded-md border border-border bg-card",children:[e.jsxs("dl",{className:"grid grid-cols-2 gap-px bg-border lg:grid-cols-3",children:[e.jsx(Ne,{label:"Extension",value:t?"Connected":"Not detected",ok:t}),e.jsx(Ne,{label:a?"Access":"Mentor session",value:a?"Unlimited":s?"Active":"Ready",ok:a||!s}),e.jsx(Ne,{label:"Plan",value:a?`${r} · active`:r,ok:a})]}),e.jsxs("div",{className:"flex flex-col gap-3 border-t border-border px-4 py-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:n.title}),e.jsx("p",{className:"mt-0.5 text-xs leading-relaxed text-muted-foreground",children:n.description})]}),e.jsx("div",{className:"shrink-0",children:o})]})]})}function Ne({label:t,value:s,ok:r}){return e.jsxs("div",{className:"bg-card px-4 py-3",children:[e.jsx("dt",{className:"text-xs text-muted-foreground",children:t}),e.jsxs("dd",{className:"mt-1 flex items-center gap-2 text-sm font-medium text-foreground",children:[r!==void 0&&e.jsx("span",{"aria-hidden":"true",className:xe("h-1.5 w-1.5 shrink-0 rounded-full",r?"bg-success":"bg-muted-foreground")}),e.jsx("span",{className:"truncate",children:s})]})]})}const B=20,ge=64,be=160,Nt=[{value:"1m",label:"1 minute"},{value:"5m",label:"5 minutes"},{value:"15m",label:"15 minutes"},{value:"1h",label:"1 hour"},{value:"4h",label:"4 hours"},{value:"1D",label:"1 day"},{value:"1W",label:"1 week"},{value:"1M",label:"1 month"}],er=/^[A-Z0-9][A-Z0-9._:!/-]{0,63}$/,tr=/^[1-9][0-9]*(m|h|D|W|M)$/,sr=t=>t.trim().toUpperCase();function rr(t){const s=t.trim().replace(/\s+/g,"");if(!s)return null;if(/^\d+$/.test(s)){const o=Number(s);return!Number.isSafeInteger(o)||o<=0?null:o>=60&&o%60===0?`${o/60}h`:`${o}m`}const r=s.match(/^(\d+)?([MmdDwWhH])$/);if(r){const o=Number(r[1]||"1");if(!Number.isSafeInteger(o)||o<=0)return null;const c=r[2];return c==="M"?`${o}M`:c==="m"?`${o}m`:c==="D"||c==="d"?`${o}D`:c==="W"||c==="w"?`${o}W`:`${o}h`}const a=s.toLowerCase().match(/^(\d+)?(min|mins|minute|minutes|hr|hrs|hour|hours|hourly|day|days|daily|wk|wks|week|weeks|weekly|mo|mon|month|months|monthly)$/);if(!a)return null;const n=Number(a[1]||"1");if(!Number.isSafeInteger(n)||n<=0)return null;const l=a[2];return["min","mins","minute","minutes"].includes(l)?`${n}m`:["hr","hrs","hour","hours","hourly"].includes(l)?`${n}h`:["day","days","daily"].includes(l)?`${n}D`:["wk","wks","week","weeks","weekly"].includes(l)?`${n}W`:`${n}M`}function kt(t){const s=sr(t.symbol);if(!s)return{ok:!1,message:"Symbol is required."};if(s.length>ge)return{ok:!1,message:`Symbol must be ${ge} characters or fewer.`};if(!er.test(s))return{ok:!1,message:"Enter a valid TradingView symbol."};const r=rr(t.timeframe);if(!r||r.length>8||!tr.test(r))return{ok:!1,message:"Enter a valid timeframe."};const a=t.note?.trim()||"";return a.length>be?{ok:!1,message:`Note must be ${be} characters or fewer.`}:{ok:!0,value:{symbol:s,timeframe:r,note:a}}}const ar="1h";function nr({status:t,canAddMore:s,isMutating:r,actionError:a,onAdd:n}){const[l,o]=i.useState(""),[c,d]=i.useState(ar),[p,m]=i.useState(""),[f,h]=i.useState(null),x=t==="ready",j=x&&!s,u=!x||j||r,y=f??a,S=x?r?"Saving your watchlist change…":j?`Watchlist is full at ${B} items. Remove one to add another.`:null:t==="loading"?"Loading your watchlist before new items can be added.":"Adding is unavailable until your watchlist loads.",v=async b=>{if(b.preventDefault(),u)return;const N=kt({symbol:l,timeframe:c,note:p});if(N.ok===!1){h(N.message);return}h(null),await n(N.value)&&(o(""),m(""))};return e.jsxs("form",{onSubmit:b=>{v(b)},className:"border-b border-border px-4 py-3",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-[minmax(0,13rem)_9rem_minmax(0,1fr)_auto] lg:items-start",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(X,{htmlFor:"watchlist-symbol",children:"Symbol"}
1),e.jsx(Z,{id:"watchlist-symbol",value:l,onChange:b=>o(b.target.value.toUpperCase()),maxLength:ge,disabled:u,spellCheck:!1,autoComplete:"off","aria-invalid":!!f||void 0,"aria-describedby":"watchlist-symbol-hint",placeholder:"NASDAQ:AAPL",className:"font-mono"}),e.jsxs("p",{id:"watchlist-symbol-hint",className:"text-xs text-muted-foreground",children:["TradingView format, up to ",ge," ","characters."]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(X,{htmlFor:"watchlist-timeframe",children:"Timeframe"}),e.jsxs(bt,{value:c,onValueChange:d,disabled:u,children:[e.jsx(yt,{id:"watchlist-timeframe",children:e.jsx(vt,{placeholder:"Select"})}),e.jsx(wt,{children:Nt.map(b=>e.jsx(le,{value:b.value,children:b.label},b.value))})]})]}),e.jsxs("div",{className:"space-y-1.5 sm:col-span-2 lg:col-span-1",children:[e.jsx(X,{htmlFor:"watchlist-note",children:"Note (optional)"}),e.jsx(Z,{id:"watchlist-note",value:p,onChange:b=>m(b.target.value),maxLength:be,disabled:u,"aria-describedby":"watchlist-note-hint",placeholder:"What you are waiting for"}),e.jsxs("p",{id:"watchlist-note-hint",className:"text-xs text-muted-foreground",children:["Note"," ",e.jsxs("span",{className:"font-mono",children:[p.length," / ",be]})," ","characters."]})]}),e.jsxs(w,{type:"submit",disabled:u,className:"w-full sm:col-span-2 lg:col-span-1 lg:mt-6 lg:w-auto",children:[r?e.jsx(R,{className:"mr-2 h-4 w-4","aria-hidden":"true"}):e.jsx(fs,{className:"mr-2 h-4 w-4","aria-hidden":"true"}),"Add"]})]}),e.jsx("p",{role:"status",className:xe("text-xs text-muted-foreground",S&&"mt-2"),children:S}),y&&e.jsx("p",{role:"alert",className:"mt-1 text-xs text-destructive",children:y})]})}function ke(t,s){if(!t||typeof t!="object")return null;const r=t;let a;if(r.note===null)a=null;else if(typeof r.note=="string")a=r.note;else return null;return typeof r.id!="string"||r.user_id!==s||typeof r.symbol!="string"||typeof r.timeframe!="string"||typeof r.created_at!="string"||typeof r.updated_at!="string"?null:{id:r.id,user_id:s,symbol:r.symbol,timeframe:r.timeframe,note:a,created_at:r.created_at,updated_at:r.updated_at}}async function fe(t,s){const r=t?.context;if(r instanceof Response)try{const a=await r.clone().json();if(typeof a.error=="string"&&a.error.trim())return a.error.trim()}catch{}return s}function ir(t){const{userId:s,initialItems:r=[]}=t,a=i.useRef(r);a.current=r;const n=i.useRef(0),[l,o]=i.useState([]),[c,d]=i.useState("idle"),[p,m]=i.useState(null),[f,h]=i.useState(!1),[x,j]=i.useState(null),u=i.useCallback(async()=>{if(!s){o([]),d("idle"),m(null);return}const v=n.current;d("loading"),m(null);const{data:b,error:N}=await C.functions.invoke("mentor-watchlist",{method:"GET"});if(v!==n.current)return;if(N){const _=await fe(N,"Unable to load your watchlist right now.");if(v!==n.current)return;m(_),d("error");return}const A=(Array.isArray(b?.items)?b.items:[]).map(_=>ke(_,s)).filter(_=>_!==null).slice(0,B);o(A),d("ready")},[s]);i.useEffect(()=>{if(n.current+=1,h(!1),j(null),m(null),!s){o([]),d("idle");return}const v=a.current.map(b=>ke(b,s)).filter(b=>b!==null).slice(0,B);if(v.length>0){o(v),d("ready");return}u()},[u,s]);const y=i.useCallback(async v=>{if(!s)return m("Please log in to update your watchlist."),!1;const b=kt(v);if(b.ok===!1)return m(b.message),!1;if(l.length>=B)return m(`Watchlist limit reached (${B} items).`),!1;const N=n.current;h(!0),m(null);const{data:A,error:_}=await C.functions.invoke("mentor-watchlist",{method:"POST",body:b.value});if(N!==n.current)return!1;if(h(!1),_){const M=await fe(_,"Unable to add that watchlist item right now.");return N!==n.current||m(M),!1}const T=ke(A?.item,s);return T?(o(M=>[T,...M.filter(I=>I.id!==T.id)].slice(0,B)),!0):(m("The watchlist returned an invalid item. Please refresh and try again."),!1)},[l.length,s]),S=i.useCallback(async v=>{if(!s||!v.trim())return m("Select a watchlist item to remove."),!1;const b=n.current;h(!0),j(v),m(null);const{data:N,error:A}=await C.functions.invoke("mentor-watchlist",{method:"DELETE",body:{id:v}});if(b!==n.current)return!1;if(h(!1),j(null),A){const _=await fe(A,"Unable to remove that watchlist item right now.");return b!==n.current||m(_),!1}return N?.success!==!0||N.id!==v?(m("The watchlist returned an invali
1d response. Please refresh and try again."),!1):(o(_=>_.filter(T=>T.id!==v)),!0)},[s]);return{items:l,status:c,error:p,isMutating:f,pendingRemovalId:x,canAddMore:l.length<B,refresh:u,addItem:y,removeItem:S}}function _t(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function or(t){const s=_t(t);return!s||typeof s.id!="string"||typeof s.symbol!="string"||typeof s.setup!="string"||typeof s.status!="string"||typeof s.expires_at!="string"||s.status==="removed"?null:{id:s.id,symbol:s.symbol,setup:s.setup,session:typeof s.session=="string"?s.session:null,direction:typeof s.direction=="string"?s.direction:null,status:s.status,expiresAt:s.expires_at}}function lr(t){const s=_t(t);return!s||typeof s.id!="string"||typeof s.condition_id!="string"||typeof s.symbol!="string"||typeof s.setup!="string"||typeof s.event_type!="string"||typeof s.trigger_reason!="string"||typeof s.created_at!="string"?null:{id:s.id,conditionId:s.condition_id,symbol:s.symbol,setup:s.setup,eventType:s.event_type,triggerReason:s.trigger_reason,marketPrice:typeof s.market_price=="number"&&Number.isFinite(s.market_price)?s.market_price:null,createdAt:s.created_at}}function cr(t){const s=i.useRef(0),r=i.useRef(0),[a,n]=i.useState({conditions:[],events:[],status:"idle",error:null,pendingId:null}),l=i.useCallback(async()=>{if(!t){n({conditions:[],events:[],status:"idle",error:null,pendingId:null});return}const c=s.current,d=++r.current;n(h=>({...h,status:"loading",error:null}));const[p,m]=await Promise.all([C.functions.invoke("mentor-watchlist?resource=conditions",{method:"GET"}),C.functions.invoke("mentor-watchlist?resource=events",{method:"GET"})]);if(c!==s.current||d!==r.current)return;if(p.error||m.error){n(h=>({...h,status:"error",error:"Unable to load your watches right now."}));return}n(h=>({...h,conditions:(Array.isArray(p.data?.conditions)?p.data.conditions:[]).map(or).filter(x=>x!==null),events:(Array.isArray(m.data?.events)?m.data.events:[]).map(lr).filter(x=>x!==null),status:"ready",error:null}))},[t]);i.useEffect(()=>(s.current++,r.current++,n({conditions:[],events:[],status:t?"loading":"idle",error:null,pendingId:null}),t&&l(),()=>{s.current++,r.current++}),[t,l]);const o=i.useCallback(async(c,d)=>{if(!t||!a.conditions.some(h=>h.id===c))return!1;const p=s.current;n(h=>({...h,pendingId:c,error:null}));const{data:m,error:f}=await C.functions.invoke("mentor-watchlist?resource=conditions",d==="disable"?{method:"PATCH",body:{id:c,action:d}}:{method:"DELETE",body:{id:c,type:"condition"}});if(p!==s.current)return!1;if(f||m?.success!==!0||m.id!==c){const h=f?await fe(f,"Unable to update that watch."):"Unable to update that watch.";return p===s.current&&n(x=>({...x,pendingId:null,error:h})),!1}return n(h=>({...h,pendingId:null,conditions:h.conditions.map(x=>x.id===c?{...x,status:d==="disable"?"disabled":"removed"}:x).filter(x=>x.status!=="removed")})),!0},[a.conditions,t]);return{...a,refresh:l,disable:c=>o(c,"disable"),remove:c=>o(c,"remove")}}const Ct=new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric"}),dr=new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"});function ur(t){return Nt.find(s=>s.value===t)?.label??t}function mr({watchlist:t,userId:s}){const r=cr(s),{items:a,status:n,error:l,isMutating:o,pendingRemovalId:c,canAddMore:d}=t,p=n==="error",[m]=dt(),f=(m.get("watchEvent")??"").trim(),h=i.useRef(null),x=!!f&&r.events.some(u=>u.id===f),j=!!f&&r.status==="ready"&&!x;return i.useEffect(()=>{x&&h.current?.scrollIntoView({behavior:"smooth",block:"center"})},[x,f,r.events]),e.jsxs(de,{value:"watchlist",className:"mt-0 space-y-4",children:[e.jsxs("section",{id:"watchlist",className:"scroll-mt-24 rounded-md border border-border bg-card",children:[e.jsxs("div",{className:"flex flex-wrap items-baseline justify-between gap-2 border-b border-border px-4 py-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("h2",{className:"text-base font-semibold tracking-tight",children:"Watchlist"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-muted-foreground",children:"Charts you want to review later. Saved items sync to the ChartMentor extension, which opens the chart on TradingView before anything is analysed."})]}),e.jsxs("p",{className:"shrink-0 font-mono text-xs text-muted-foreground",children:[a.length," / ",B]})]}),e.jsx(nr,{status:n,canAddMore:d,isMutating:o,actionError:p?null:l,onAdd:t.addItem}),n==="loading"&&e.jsxs("p",{className:"flex items-center gap-2 px-4 py-6 text-sm text-muted-foreground","aria-busy":"true",children:[e.jsx(R,{className:"h-4 w-4","aria-hidden":"true"}),"Loading your watchlist…"]}),p&&e.jsxs("div",{className:"flex flex-wrap items-center gap-3 px-4 py-6",children:[e.jsx("p",{role:"alert",className:"text-sm text-destructive",children:l??"Unable to load your watchlist right now."}),e.jsxs(w,{type:"button",size:"sm",variant:"outline",onClick:()=>{t.refresh()},children:[e.jsx(J,{className:"mr-2 h-3.5 w-3.5","aria-hidden":"true"}),"Try again"]})]}),n==="ready"&&a.length===0&&e.jsx("p",{className:"px-4 py-6 text-sm text-muted-foreground",children:"Nothing saved yet. Add the symbol and timeframe you are waiting on, and it will be waiting for you in the extension."}),a.length>0&&e.jsx("ul",{className:"divide-y divide-border",children:a.map(u=>e.jsx(hr,{item:u,removing:c===u.id,disabled:o,onRemove:()=>{t.removeItem(u.id)}},u.id))})]}),e.jsxs("section",{className:"rounded-md border border-border bg-card",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 border-b border-border px-4 py-3",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-base font-semibold tracking-tight",children:"Internal watches"}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Your conditional setups and recent changes appear here. A watch never places a trade. If you have opted in by linking Telegram in your account settings, ChartMentor sends you a mentor-style alert when a condition triggers — nothing is sent until you connect Telegram yourself."})]}),e.jsxs(w,{type:"button",size:"sm",variant:"outline",onClick:()=>{r.refresh()},disabled:r.status==="loading",children:[e.jsx(J,{className:"mr-2 h-3.5 w-3.5","aria-hidden":"true"}),"Refresh"]})]}),r.status==="loading"&&e.jsx("p",{className:"px-4 py-5 text-sm text-muted-foreground","aria-busy":"true",children:"Loading watches…"}),r.error&&e.jsx("p",{role:"alert",className:"px-4 py-3 text-sm text-destructive",children:r.error}),r.status==="ready"&&r.conditions.length===0&&e.jsx("p",{className:"px-4 py-5 text-sm text-muted-foreground",children:"No conditions yet. Ask Mentor to watch a specific symbol and setup."}),r.conditions.length>0&&e.jsx("ul",{className:"divide-y divide-border",children:r.conditions.map(u=>e.jsxs("li",{className:"flex flex-wrap items-center gap-2 px-4 py-3",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"text-sm font-medium",children:[e.jsx("span",{className:"font-mono",children:u.symbol})," · ",u.setup]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[u.status,u.session?` · ${u.session.replace(/_/g," ")}`:"",u.direction?` · ${u.direction.toLowerCase()}`:""," · expires ",Number.isNaN(Date.parse(u.expiresAt))?"unknown":Ct.format(new Date(u.expiresAt))]})]}),u.status==="active"&&e.jsx(w,{type:"button",size:"sm",variant:"outline",disabled:!!r.pen
1dingId,"aria-label":`Disable watch for ${u.symbol} ${u.setup}`,onClick:()=>{r.disable(u.id)},children:"Disable"}),e.jsx(w,{type:"button",size:"sm",variant:"ghost",disabled:!!r.pendingId,"aria-label":`Remove watch for ${u.symbol} ${u.setup}`,onClick:()=>{r.remove(u.id)},children:e.jsx(Re,{className:"h-4 w-4","aria-hidden":"true"})})]},u.id))})]}),e.jsxs("section",{className:"rounded-md border border-border bg-card",children:[e.jsxs("div",{className:"border-b border-border px-4 py-3",children:[e.jsx("h2",{className:"text-base font-semibold tracking-tight",children:"Recent watch events"}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Changes detected in the past 48 hours. Open the chart to review the current setup. Telegram alerts link back to this list."})]}),j&&e.jsx("p",{className:"border-b border-border px-4 py-3 text-sm text-muted-foreground",children:"That alert is not in the last 48 hours of watch events."}),r.status==="ready"&&r.events.length===0&&e.jsx("p",{className:"px-4 py-5 text-sm text-muted-foreground",children:"No recent changes."}),r.events.length>0&&e.jsx("ul",{className:"divide-y divide-border",children:r.events.map(u=>{const y=!!f&&u.id===f;return e.jsxs("li",{ref:y?h:void 0,"data-watch-event-focused":y?"true":void 0,className:y?"bg-muted/60 px-4 py-3 ring-1 ring-inset ring-primary/40":"px-4 py-3",children:[e.jsxs("div",{className:"flex flex-wrap items-baseline justify-between gap-2",children:[e.jsxs("p",{className:"text-sm font-medium",children:[e.jsx("span",{className:"font-mono",children:u.symbol})," · ",u.setup]}),e.jsx("time",{dateTime:u.createdAt,className:"text-xs text-muted-foreground",children:Number.isNaN(Date.parse(u.createdAt))?"Time unavailable":dr.format(new Date(u.createdAt))})]}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:u.triggerReason}),y&&e.jsx("p",{className:"mt-1 text-xs font-medium text-primary",children:"From your Telegram alert"})]},u.id)})})]})]})}function hr({item:t,removing:s,disabled:r,onRemove:a}){const n=new Date(t.created_at),l=Number.isNaN(n.getTime())?null:Ct.format(n);return e.jsxs("li",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 px-4 py-2.5",children:[e.jsx("span",{className:"font-mono text-sm font-medium",children:t.symbol}),e.jsx("span",{className:"shrink-0 border border-border px-1.5 py-0.5 text-xs text-muted-foreground",children:ur(t.timeframe)}),t.note&&e.jsx("span",{className:"min-w-0 basis-full text-sm text-muted-foreground sm:basis-auto",children:t.note}),e.jsx("span",{className:"ml-auto shrink-0 text-xs text-muted-foreground",children:l?`Added ${l}`:""}),e.jsx(w,{type:"button",size:"sm",variant:"ghost",disabled:r,"aria-label":`Remove ${t.symbol} from watchlist`,className:"h-8 shrink-0 px-2 text-muted-foreground hover:text-destructive",onClick:a,children:s?e.jsx(R,{className:"h-4 w-4","aria-hidden":"true"}):e.jsx(Re,{className:"h-4 w-4","aria-hidden":"true"})})]})}const pr=Ms,fr=Is,xr=Fs,_e=768;function gr(){const[t,s]=i.useState(void 0);return i.useEffect(()=>{const r=window.matchMedia(`(max-width: ${_e-1}px)`),a=()=>{s(window.innerWidth<_e)};return r.addEventListener("change",a),s(window.innerWidth<_e),()=>r.removeEventListener("change",a)},[]),!!t}function At({id:t,eyebrow:s,title:r,description:a,summary:n,actions:l,nested:o=!1,children:c}){const d=gr(),[p,m]=i.useState(!1),f=d?p:!0;i.useEffect(()=>{if(!t)return;const j=()=>{window.location.hash===`#${t}`&&m(!0)};return j(),window.addEventListener("hashchange",j),()=>window.removeEventListener("hashchange",j)},[t]);const h=o?"h3":"h2",x=o?"text-sm font-semibold":"text-base font-semibold tracking-tight";return e.jsx("section",{id:t,className:xe("scroll-mt-24",o?"border-t border-border":"rounded-md border border-border bg-card"),children:e.jsxs(pr,{open:f,onOpenChange:m,children:[d?e.jsx(h,{className:x,children:e.jsxs(fr,{className:"flex w-full items-center justify-between gap-3 px-4 py-3 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",children:[e.jsxs("span",{className:"min-w-0",children:[s&&e.jsx("span",{className:"block text-xs font-normal uppercase tracking-wide text-muted-foreground",children:s}),e.jsx("span",{className:"block",children:r}),n&&e.jsx("span",{className:"mt-0.5 block truncate text-xs font-normal text-muted-foreground",children:n})]}),e.jsx(xs,{"aria-hidden":"true",className:xe("h-4 w-4 shrink-0 text-muted-foreground transition-transform",f&&"rotate-180")}
1)]})}):e.jsxs("div",{className:"flex flex-col gap-2 px-4 py-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[s&&e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:s}),e.jsx(h,{className:x,children:r}),a&&e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-muted-foreground",children:a})]}),l]}),e.jsxs(xr,{className:"border-t border-border",children:[d&&(a||l)&&e.jsxs("div",{className:"space-y-3 border-b border-border px-4 py-3",children:[a&&e.jsx("p",{className:"text-sm text-muted-foreground",children:a}),l]}),c]})]})})}const Se=3,br=6,Je={countertrend_without_confirmation:"Countertrend entry without confirmation",entry_chasing_extension:"Entry chases an extended move",stop_inside_normal_noise:"Stop sits inside normal chart noise",target_into_nearby_structure:"Target runs into nearby structure",poor_reward_to_risk:"Planned reward does not justify the risk",timeframe_plan_mismatch:"Plan conflicts with the selected timeframe",invalidation_not_structural:"Invalidation is not tied to chart structure"};function yr(t){if(typeof t!="string")return"";const s=t.trim();return s?Je[s]??Je[s.toLowerCase().replace(/\s+/g,"_")]??s:""}function vr(t){const s=Math.max(0,Math.trunc(t||0));return s===1?"1 observation":`${s} observations`}const Te=2e3,St=160,ye=3;function Ie(t){const s=t?.code;return s==="42P01"||s==="PGRST205"}async function wr(t){const{data:s,error:r}=await C.from("mentor_seeded_profile").select("rules_playbook, recurring_mistakes").eq("user_id",t).maybeSingle();return r?Ie(r)?{status:"unavailable"}:{status:"error",message:r.message||"Failed to load."}:{status:"ok",profile:{rulesPlaybook:typeof s?.rules_playbook=="string"?s.rules_playbook:"",recurringMistakes:Array.isArray(s?.recurring_mistakes)?s.recurring_mistakes.filter(a=>typeof a=="string"):[]}}}async function jr(t,s){const r=s.rulesPlaybook.trim().slice(0,Te),a=s.recurringMistakes.map(l=>l.trim().slice(0,St)).filter(Boolean).slice(0,ye),{error:n}=await C.from("mentor_seeded_profile").upsert({user_id:t,rules_playbook:r||null,recurring_mistakes:a,updated_at:new Date().toISOString()},{onConflict:"user_id"});return n?Ie(n)?{status:"unavailable"}:{status:"error",message:n.message||"Failed to save."}:{status:"ok"}}async function Nr(t){const{data:s,error:r}=await C.from("mentor_observed_patterns").select("label, evidence_count, first_observed_at, last_observed_at").eq("user_id",t).gte("evidence_count",Se).order("evidence_count",{ascending:!1}).order("last_observed_at",{ascending:!1}).limit(br);return r?Ie(r)?{status:"unavailable"}:{status:"error",message:r.message||"Failed to load."}:{status:"ok",patterns:(s??[]).map(a=>({label:yr(a.label),evidenceCount:typeof a.evidence_count=="number"?a.evidence_count:0,firstObservedAt:a.first_observed_at??null,lastObservedAt:a.last_observed_at??null})).filter(a=>a.label.length>0&&a.evidenceCount>=Se)}}const kr=new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric"});function _r(t){if(!t)return null;const s=new Date(t);return Number.isNaN(s.getTime())?null:kr.format(s)}function Cr({userId:t}){const[s,r]=i.useState({status:"loading"}),[a,n]=i.useState(0);i.useEffect(()=>{if(!t)return;let o=!1;return r({status:"loading"}),(async()=>{const c=await Nr(t);o||(c.status==="ok"?r({status:"ready",patterns:c.patterns}):c.status==="unavailable"?r({status:"unavailable"}):r({status:"error",message:c.message}))})(),()=>{o=!0}},[t,a]);const l=s.status==="ready"?s.patterns.length===0?"Nothing evidenced yet":`${s.patterns.length} evidenced`:s.status==="loading"?"Loading…":"Unavailable";return e.jsx(At,{nested:!0,title:"Observed patterns",summary:l,description:`Written by ChartMentor, not editable. A behaviour is only listed after it was evidenced in ${Se} separate reviews of different plans. Below that, nothing is claimed and nothing is recalled.`,children:e.jsxs("div",{className:"px-4 py-3",children:[s.status==="loading"&&e.jsxs("p",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(R,{className:"h-3.5 w-3.5","aria-hidden":"true"}),"Loading observed patterns…"]}),s.status==="unavailable"&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Observed patterns are not available on this account yet."}),s.status==="error"&&e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("p",{className:"text-xs text-destructive",children:["Could not load observed patterns. ",s.message]}),e.jsxs(w,{type:"button",size:"sm",variant:"outline",className:"h-7 px-2 text-xs",onClick:()=>n(o=>o+1),children:[e.jsx(J,{className:"mr-1.5 h-3 w-3","aria-hidden":"true"}),"Try again"]})]}),s.status==="ready"&&s.patterns.length===0&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"No pattern has enough evidence yet. Keep reviewing plans and recording outcomes; anything repeated will show up here with its evidence count."}),s.status==="ready"&&s.patterns.length>0&&e.jsx("ul",{className:"divide-y divide-border border border-border",children:s.patterns.map(o=>{const c=_r(o.lastObservedAt);return e.jsxs("li",{className:"flex flex-wrap items-baseline justify-between gap-x-4 gap-y-1 px-3 py-2",children:[e.jsx("span",{className:"text-sm",children:o.label}),e.jsxs("span",{className:"shrink-0 font-mono text-xs text-muted-foreground",children:[vr(o.evidenceCount),c?` · last ${c}`:""]})]},o.label)})})]})})}const Ar=["preferred_symbol","trading_style","preferred_session","preferred_timeframe","has_strategy","strategy_name","strategy_summary","wants_fundamental_briefs"],et={preferred_symbol:"Preferred market",trading_style:"Trading style",preferred_session:"Trading session",preferred_timeframe:"Preferred timeframe",has_strategy:"Strategy status",strategy_name:"Strategy name",strategy_summary:"Strategy summary",wants_fundamental_briefs:"Fundamental briefs"},Sr=new Set(Ar);function Tr(t){if(!t||typeof t!="object"||Array.isArray(t))return null;const s=t,r=s.sourceQuote;return typeof s.id!="string"||typeof s.key!="string"||!Sr.has(s.key)||typeof s.value!="string"||!s.value.trim()||s.sourceType!=="user_stated"&&s.sourceType!=="user_confirmed"&&s.sourceType!=="system_observed"||r!==null&&typeof r!="string"||typeof s.learnedAt!="string"?null:{id:s.id,key:s.key,value:s.value.trim().slice(0,500),sourceType:s.sourceType,sourceQuote:typeof r=="string"&&r.trim()?r.trim().slice(0,500):null,learnedAt:s.learnedAt}}async function Tt(t,s){if(t?.context instanceof Response)try{const r=await t.context.clone().json();if(typeof r.error=="string"&&r.error.trim())return r.error.trim().slice(0,240)}catch{}return s}function tt(t){return t.key==="has_strategy"?t.value.toLowerCase()==="true"?"Uses a defined strategy":"No defined strategy yet":t.key==="wants_fundamental_briefs"?t.value.toLowerCase()==="true"?"Wanted":"Not wanted":t.key==="preferred_session"||t.key==="trading_style"?t.value.replace(/_/g," ").replace(/\b\w/g,s=>s.toUpperCase()):t.value}async function Er(){const{data:t,error:s}=await C.functions.invoke("mentor-memory",{method:"GET"});return s?{status:"error",message:await Tt(s,"Unable to load what ChartMentor learned right now.")}:{status:"ok",preferences:(Array.isArray(t?.preferences)?t.preferences:[]).map(Tr).filter(a=>a!==null).slice(0,16)}}async function Pr(t){const{data:s,error:r}=await C.functions.invoke("mentor-memory",{method:"DELETE",body:{id:t}});return r?{status:"error",message:await Tt(r,"Unable to forget that memory right now.")}:s?.success===!0&&s.id===t?{status:"ok"}
1:{status:"error",message:"Mentor memory returned an invalid response."}}const Rr=new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",year:"numeric"});function Mr(t){const s=new Date(t);return Number.isNaN(s.getTime())?null:Rr.format(s)}function Ir({userId:t}){const{toast:s}=ee(),[r,a]=i.useState({status:"loading"}),[n,l]=i.useState(0),[o,c]=i.useState(null),[d,p]=i.useState(null);i.useEffect(()=>{if(a({status:"loading"}),c(null),p(null),!t)return;let f=!1;return Er().then(h=>{f||a(h.status==="ok"?{status:"ready",preferences:h.preferences}:{status:"error",message:h.message})}),()=>{f=!0}},[n,t]);const m=async()=>{if(!o||d)return;const f=o.id;p(f);const h=await Pr(f);if(p(null),h.status==="error"){s({title:"Could not forget memory",description:h.message,variant:"destructive"});return}a(x=>x.status==="ready"?{status:"ready",preferences:x.preferences.filter(j=>j.id!==f)}:x),c(null),s({title:"Memory forgotten",description:"ChartMentor will not use it in future mentor sessions."})};return e.jsx(Fr,{state:r,selected:o,pendingForgetId:d,onRetry:()=>l(f=>f+1),onSelect:c,onCancel:()=>c(null),onConfirm:()=>{m()}})}function Fr({state:t,selected:s,pendingForgetId:r,onRetry:a,onSelect:n,onCancel:l,onConfirm:o}){const c=t.status==="ready"?t.preferences.length===0?"Nothing learned yet":`${t.preferences.length} remembered`:t.status==="loading"?"Loading...":"Unavailable";return e.jsxs(e.Fragment,{children:[e.jsx(At,{nested:!0,id:"learned-memory",title:"What ChartMentor learned",summary:c,description:"Facts ChartMentor saved from your mentor sessions. Review the source and forget anything that is wrong or outdated.",children:e.jsxs("div",{className:"px-4 py-3",children:[t.status==="loading"&&e.jsxs("div",{className:"space-y-3","aria-busy":"true",children:[e.jsxs("p",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(R,{className:"h-3.5 w-3.5","aria-hidden":"true"}),"Loading learned memory..."]}),e.jsx("div",{className:"h-12 animate-pulse rounded bg-muted"})]}),t.status==="error"&&e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("p",{role:"alert",className:"text-xs text-destructive",children:["Could not load what ChartMentor learned. ",t.message]}),e.jsxs(w,{type:"button",size:"sm",variant:"outline",className:"h-7 px-2 text-xs",onClick:a,children:[e.jsx(J,{className:"mr-1.5 h-3 w-3","aria-hidden":"true"}),"Try again"]})]}),t.status==="ready"&&t.preferences.length===0&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Nothing learned yet. When you explicitly tell ChartMentor your market, session, timeframe, style, or strategy, it will appear here."}),t.status==="ready"&&t.preferences.length>0&&e.jsx("ul",{className:"divide-y divide-border",children:t.preferences.map(d=>{const p=Mr(d.learnedAt),m=et[d.key];return e.jsxs("li",{className:"grid gap-2 py-3 first:pt-0 last:pb-0 sm:grid-cols-[minmax(0,1fr)_auto] sm:items-start",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:m}),e.jsx("p",{className:"mt-0.5 text-sm font-medium text-foreground",children:tt(d)}),d.sourceQuote&&e.jsxs("blockquote",{className:"mt-1 border-l-2 border-border pl-2 text-xs text-muted-foreground",children:[d.sourceType==="user_stated"?"You said":"Evidence",': "',d.sourceQuote,'"']}),e.jsxs("p",{className:"mt-1 text-[11px] text-muted-foreground",children:[d.sourceType==="user_stated"?"Learned from your mentor conversation":d.sourceType==="user_confirmed"?"Confirmed by you in mentor chat":"Learned from repeated account evidence",p?` on ${p}`:""]})]}),e.jsxs(w,{type:"button",size:"sm",variant:"ghost",className:"h-8 justify-self-start px-2 text-xs text-muted-foreground hover:text-destructive sm:justify-self-end",onClick:()=>n(d),"aria-label":`Forget ${m.toLowerCase()}`,children:[e.jsx(Re,{className:"mr-1.5 h-3.5 w-3.5","aria-hidden":"true"}),"Forget"]})]},d.id)})})]})}),e.jsx(Kt,{open:s!==null,onOpenChange:d=>{!d&&!r&&l()},children:e.jsxs(Qt,{children:[e.jsxs(Xt,{children:[e.jsx(Zt,{children:"Forget this memory?"}),e.jsx(Jt,{children:"ChartMentor will stop using this in future mentor sessions. Your past conversation messages will not be deleted."})]}),s&&e.jsxs("div",{className:"border-l-2 border-border pl-3 text-sm",children:[e.jsx("p",{className:"font-medium",children:et[s.key]}),e.jsx("p",{className:"text-muted-foreground",children:tt(s)})]}),e.jsxs(es,{children:[e.jsx(ts,{disabled:!!r,children:"Keep memory"}),e.jsxs(ss,{disabled:!!r,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",onClick:d=>{d.preventDefault(),o()},children:[r&&e.jsx(R,{className:"mr-2 h-4 w-4","aria-hidden":"true"}),"Forget memory"]})]})]})})]})}const Ce=Array.from({length:ye},()=>"");function Lr({userId:t}){const{toast:s}=ee(),[r,a]=i.useState("loading"),[n,l]=i.useState(null),[o,c]=i.useState(""),[d,p]=i.useState([...Ce]),[m,f]=i.useState(!1),[h,x]=i.useState(0);i.useEffect(()=>{if(a("loading"),l(null),c(""),p([...Ce]),f(!1),!t)return;let u=!1;return(async()=>{const y=await wr(t);if(!u){if(y.status==="ok"){c(y.profile.rulesPlaybook),p(Ce.map((S,v)=>y.profile.recurringMistakes[v]||"")),a("ready");return}if(y.status==="unavailable"){a("unavailable");return}l(y.message),a("error")}})(),()=>{u=!0}},[t,h]);const j=async()=>
1{if(!t||r!=="ready")return;f(!0);const u=await jr(t,{rulesPlaybook:o,recurringMistakes:d.map(y=>y.trim()).filter(Boolean).slice(0,ye)});if(f(!1),u.status==="ok"){s({title:"Saved",description:"Your mentor memory is updated."});return}if(u.status==="unavailable"){a("unavailable");return}s({title:"Couldn't save",description:u.message,variant:"destructive"})};return e.jsx(Dr,{status:r,errorMessage:n,rulesPlaybook:o,mistakes:d,saving:m,onRulesChange:c,onMistakeChange:(u,y)=>p(S=>S.map((v,b)=>b===u?y:v)),onRetry:()=>x(u=>u+1),onSave:()=>{j()},observedPatterns:t?e.jsxs(e.Fragment,{children:[e.jsx(Ir,{userId:t}),e.jsx(Cr,{userId:t})]}):null})}function Dr({status:t,errorMessage:s,rulesPlaybook:r,mistakes:a,saving:n,onRulesChange:l,onMistakeChange:o,onRetry:c,onSave:d,observedPatterns:p}){return e.jsxs("section",{id:"mentor-memory",className:"scroll-mt-24 rounded-md border border-border bg-card",children:[e.jsxs("div",{className:"border-b border-border px-4 py-3",children:[e.jsx("h2",{className:"text-base font-semibold tracking-tight",children:"Mentor memory"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-muted-foreground",children:"What ChartMentor knows about how you trade. Your rules and repeated mistakes are yours to edit; observed patterns are earned from evidence."})]}),t==="loading"&&e.jsxs("div",{className:"space-y-3 px-4 py-4","aria-busy":"true",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading your mentor memory…"}),e.jsx("div",{className:"h-24 animate-pulse rounded bg-muted"}),e.jsx("div",{className:"h-9 w-40 animate-pulse rounded bg-muted"})]}),t==="error"&&e.jsxs("div",{className:"flex flex-wrap items-center gap-3 px-4 py-4",children:[e.jsxs("p",{role:"alert",className:"text-sm text-destructive",children:["Could not load your mentor memory",s?`: ${s}`:"."," Editing stays locked so nothing already saved is overwritten."]}),e.jsxs(w,{type:"button",size:"sm",variant:"outline",onClick:c,children:[e.jsx(J,{className:"mr-2 h-3.5 w-3.5","aria-hidden":"true"}),"Try again"]})]}),t==="unavailable"&&e.jsx("p",{role:"status",className:"px-4 py-4 text-sm text-muted-foreground",children:"Mentor memory is not available on this account yet. Your reviews still run; saved rules will start applying once it is enabled."}),t==="ready"&&e.jsxs("div",{className:"space-y-4 px-4 py-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-sm font-medium",htmlFor:"mentor-seed-rules",children:"Your trading rules"}),e.jsx(Me,{id:"mentor-seed-rules",value:r,onChange:m=>l(m.target.value),maxLength:Te,rows:5,"aria-describedby":"mentor-seed-rules-hint",placeholder:"e.g. Never risk more than 1% per trade. Only take setups aligned with the daily trend. No trades in the first 15 minutes of the session."}),e.jsxs("p",{id:"mentor-seed-rules-hint",className:"text-xs text-muted-foreground",children:["Every review is checked against these rules."," ",e.jsxs("span",{className:"font-mono",children:[r.length," / ",Te]})]})]}),e.jsxs("fieldset",{className:"space-y-1.5",children:[e.jsx("legend",{className:"text-sm font-medium",children:"Mistakes you keep repeating"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Up to ",ye,". The mentor challenges these first when a plan drifts towards one."]}),e.jsx("div",{className:"space-y-2 pt-1",children:a.map((m,f)=>e.jsx(Z,{value:m,onChange:h=>o(f,h.target.value),maxLength:St,"aria-label":`Recurring mistake ${f+1}`,placeholder:`Mistake ${f+1} (e.g. "I move my stop when it gets close")`},f))})]}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(w,{onClick:d,disabled:n,size:"sm",children:[n&&e.jsx(R,{className:"mr-2 h-4 w-4","aria-hidden":"true"}),"Save mentor memory"]})})]}),p]})}const st={referralCode:"",referralUrl:"",referredSignups:0,activatedReferrals:0,commissionRatePercent:30,commissionWindowMonths:12,refundHoldDays:30,minimumPayoutCents:5e3,paidReferrals:0,grossRevenueCents:0,pendingCommissionCents:0,eligibleCommissionCents:0,requestedCommissionCents:0,nextEligibleCommissionAt:null,nextEligibleCommissionCents:0,paidCommissionCents:0,currency:"usd",affiliateTermsAccepted:!1,affiliateTermsVersion:null,affiliateTermsAcceptedAt:null,affiliatePaypalEmail:"",affiliatePayoutName:"",payoutRequests:[]},rt="2026-07-01";function F(t){return t===void 0?"$0.00":`$${(t/100).toFixed(2)}`}function at(t){if(!t)return"—";try{return new Date(t).toLocaleDateString()}catch{return t}}function Or(t,s){const r=Math.min(100,Math.round(t.eligibleCommissionCents/Math.max(1,t.minimumPayoutCents)*100)),a=!t.affiliatePaypalEmail,n=!t.affiliateTermsAccepted,l=t.affiliateTermsAccepted||s,o=t.eligibleCommissionCents>
1=t.minimumPayoutCents&&!a&&l;return{payoutProgress:r,needsPaypal:a,needsTerms:n,canRequestPayout:o}}const qr=()=>{const{toast:t}=ee(),{user:s}=Pe(),[r,a]=i.useState(st),[n,l]=i.useState(!0),[o,c]=i.useState(!1),[d,p]=i.useState(!1),[m,f]=i.useState(!1),[h,x]=i.useState(""),[j,u]=i.useState(""),[y,S]=i.useState(!1),[v,b]=i.useState(!1),N=i.useCallback(async()=>{l(!0);try{const{data:g,error:L}=await C.functions.invoke("get-referral-dashboard");if(L){console.debug("[ReferralCard] get-referral-dashboard failed:",L.message),t({title:"Affiliate stats unavailable",description:"Try refreshing this section in a moment.",variant:"destructive"});return}const D={...st,...g};a(D),x(D.affiliatePaypalEmail),u(D.affiliatePayoutName),p(D.affiliateTermsAccepted)}catch(g){console.debug("[ReferralCard] get-referral-dashboard exception:",g),t({title:"Affiliate stats unavailable",description:"Try refreshing this section in a moment.",variant:"destructive"})}finally{l(!1)}},[t]);i.useEffect(()=>{s&&N()},[s,N]);const A=async()=>{if(!(!r.referralUrl||o)){c(!0);try{await navigator.clipboard.writeText(r.referralUrl),t({title:"Affiliate link copied",description:"You'll earn 30% recurring commission on subscription revenue for 12 months."}),pe("affiliate_link_copied",{referralCode:r.referralCode})}catch{t({title:"Copy failed",description:"Select the link and copy it manually.",variant:"destructive"})}finally{c(!1)}}},_=async()=>{if(!d||!s)return!1;f(!0);const{error:g}=await C.from("profiles").update({affiliate_terms_accepted:!0,affiliate_terms_version:rt,affiliate_terms_accepted_at:new Date().toISOString()}).eq("id",s.id);return f(!1),g?(t({title:"Enrollment failed",description:g.message,variant:"destructive"}),!1):(pe("affiliate_terms_accepted",{termsVersion:rt}),t({title:"Affiliate terms accepted",description:"You can now request eligible payouts."}),N(),!0)},T=async()=>{if(!s)return;if(!h||!h.includes("@")){t({title:"Invalid Email",description:"Please enter a valid email address.",variant:"destructive"});return}S(!0);const{error:g}=await C.from("profiles").update({affiliate_paypal_email:h.trim().toLowerCase(),affiliate_payout_name:j.trim()||null}).eq("id",s.id);if(S(!1),g){t({title:"Save failed",description:g.message,variant:"destructive"});return}t({title:"Payout profile updated",description:"Your PayPal address has been saved."}),pe("affiliate_payout_profile_saved",{hasPayoutName:!!j.trim()}),N()},M=async()=>{if(!s)return;if(!r.affiliatePaypalEmail){t({title:"PayPal email required",description:"Please configure and save your PayPal email in the payout profile section first.",variant:"destructive"});return}if(!r.affiliateTermsAccepted){if(!d){t({title:"Affiliate terms required",description:"Accept the affiliate terms before requesting a payout.",variant:"destructive"});return}if(!await _())return}b(!0);const{error:g}=await C.rpc("request_affiliate_payout",{p_paypal_email:r.affiliatePaypalEmail,p_payout_name:r.affiliatePayoutName||null});if(b(!1),g){t({title:"Payout request failed",description:g.message,variant:"destructive"});return}t({title:"Payout request submitted",description:"Our team will review and process your request shortly."}),pe("affiliate_payout_requested",{amountCents:r.eligibleCommissionCents,minimumPayoutCents:r.minimumPayoutCents}),N()},{payoutProgress:I,needsTerms:W,canRequestPayout:U}=Or(r,d);return n&&!r.referralUrl?e.jsx(H,{className:"border-border bg-card",children:e.jsx(Y,{className:"flex items-center justify-center py-12",children:e.jsx(R,{className:"h-6 w-6 text-primary"})})}
1):e.jsxs("div",{className:"space-y-6",children:[e.jsxs(H,{className:"border-border bg-card",children:[e.jsx(G,{children:e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(K,{className:"flex items-center gap-2 text-xl font-bold tracking-tight",children:[e.jsx(Ve,{className:"h-5 w-5 text-primary"}),"Affiliate Partner Program"]}),e.jsx(Qe,{variant:"outline",className:r.affiliateTermsAccepted?"text-emerald-500 border-emerald-500/20 bg-emerald-500/5":"text-amber-500 border-amber-500/20 bg-amber-500/5",children:r.affiliateTermsAccepted?"Payout Ready":"Link Ready"})]}),e.jsxs(Q,{className:"text-muted-foreground text-sm",children:["Earn"," ",e.jsxs("strong",{children:[r.commissionRatePercent,"% recurring commission"]})," ","for ",e.jsxs("strong",{children:[r.commissionWindowMonths," months"]})," on referred subscription revenue. Share your link now; payout setup and terms are only required once you request eligible commission."]})]})}),e.jsxs(Y,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wider",children:"Your Affiliate Link"}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row",children:[e.jsx(Z,{value:n?"Loading affiliate link...":r.referralUrl,readOnly:!0,className:"font-mono text-xs bg-muted/40 border-border select-all focus-visible:ring-primary","aria-label":"Affiliate link"}),e.jsxs(w,{type:"button",onClick:A,disabled:n||o||!r.referralUrl,children:[o?e.jsx(R,{className:"mr-2 h-4 w-4"}):e.jsx(gs,{className:"mr-2 h-4 w-4"}),"Copy Link"]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 md:grid-cols-4",children:[e.jsxs("div",{className:"rounded-lg border border-border p-4 bg-muted/10",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs font-semibold uppercase tracking-wider text-muted-foreground mb-1",children:[e.jsx("span",{children:"Signups"}),e.jsx(bs,{className:"h-4 w-4 text-muted-foreground/60"})]}),e.jsx("p",{className:"text-2xl font-bold text-foreground",children:r.referredSignups}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:"Total registered users"})]}),e.jsxs("div",{className:"rounded-lg border border-border p-4 bg-muted/10",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs font-semibold uppercase tracking-wider text-muted-foreground mb-1",children:[e.jsx("span",{children:"Paid Referrals"}),e.jsx(ys,{className:"h-4 w-4 text-muted-foreground/60"})]}),e.jsx("p",{className:"text-2xl font-bold text-foreground",children:r.paidReferrals}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:"Paying customers referred"})]}),e.jsxs("div",{className:"rounded-lg border border-border p-4 bg-muted/10",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs font-semibold uppercase tracking-wider text-muted-foreground mb-1",children:[e.jsx("span",{children:"Pending"}),e.jsx(He,{className:"h-4 w-4 text-muted-foreground/60"})]}),e.jsx("p",{className:"text-2xl font-bold text-foreground",children:F(r.pendingCommissionCents)}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:"Inside 30-day hold window"})]}),e.jsxs("div",{className:"rounded-lg border border-border p-4 bg-muted/10",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs font-semibold uppercase tracking-wider text-muted-foreground mb-1",children:[e.jsx("span",{children:"Eligible Balance"}),e.jsx(Ve,{className:"h-4 w-4 text-emerald-500"})]}),e.jsx("p",{className:"text-2xl font-bold text-emerald-500",children:F(r.eligibleCommissionCents)}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:"Eligible for manual payout"})]})]}),e.jsxs("div",{className:"flex flex-col gap-3 border-t border-border pt-4 text-xs text-muted-foreground sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("p",{className:"max-w-xl",children:["Commissions are calculated automatically upon payment verification. Payments are subject to our"," ",e.jsx(ce,{to:"/affiliate-terms",className:"text-primary hover:underline",children:"terms of service"}),"."]}),e.jsxs(w,{type:"button",variant:"ghost",size:"sm",onClick:()=>{N()},disabled:n,className:"hover:bg-muted/30",children:[n?e.jsx(R,{className:"mr-2 h-4 w-4"}):e.jsx(J,{className:"mr-2 h-4 w-4"}),"Refresh Stats"]})]})]})]}),e.jsxs("div",{className:"grid gap-6 md:grid-cols-2",children:[e.jsxs(H,{
1className:"border-border bg-card",children:[e.jsxs(G,{children:[e.jsxs(K,{className:"text-lg font-bold flex items-center gap-2",children:[e.jsx(vs,{className:"h-4 w-4 text-primary"}),"Payout Profile"]}),e.jsx(Q,{className:"text-xs",children:"Configure where you would like your payouts to be processed."})]}),e.jsx(Y,{className:"space-y-4",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-xs font-semibold text-muted-foreground",children:"PayPal Account Email"}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row",children:[e.jsx(Z,{type:"email",placeholder:"[email protected]",value:h,onChange:g=>x(g.target.value),className:"bg-muted/10 border-border focus-visible:ring-primary"}),e.jsx(Z,{type:"text",placeholder:"Payout name",value:j,onChange:g=>u(g.target.value),className:"bg-muted/10 border-border focus-visible:ring-primary sm:max-w-[180px]"}),e.jsx(w,{type:"button",variant:"secondary",disabled:y||h.trim().toLowerCase()===r.affiliatePaypalEmail&&j.trim()===r.affiliatePayoutName,onClick:T,children:y?e.jsx(R,{className:"h-4 w-4"}):"Save"})]}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"We support PayPal email addresses only. Ensure this is correct to avoid payment issues."})]})})]}
1),e.jsxs(H,{className:"border-border bg-card",children:[e.jsxs(G,{children:[e.jsxs(K,{className:"text-lg font-bold flex items-center gap-2",children:[e.jsx(He,{className:"h-4 w-4 text-primary"}),"Request Payout"]}),e.jsx(Q,{className:"text-xs",children:"Request a payout once you meet the threshold and have set up your PayPal email."})]}),e.jsxs(Y,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between rounded-lg border border-border p-3 bg-muted/5",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Eligible Balance"}),e.jsx("p",{className:"text-lg font-bold text-foreground",children:F(r.eligibleCommissionCents)})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Pending Payout Request"}),e.jsx("p",{className:"text-lg font-bold text-muted-foreground",children:F(r.requestedCommissionCents)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"font-semibold text-muted-foreground",children:"Payout progress"}),e.jsxs("span",{className:"font-mono text-muted-foreground",children:[F(r.eligibleCommissionCents)," /"," ",F(r.minimumPayoutCents)]})]}),e.jsx(Ls,{value:I,className:"h-2"}),r.nextEligibleCommissionAt&&r.nextEligibleCommissionCents>0&&e.jsxs("p",{className:"text-[10px] text-muted-foreground",children:["Next hold release:"," ",e.jsx("strong",{children:F(r.nextEligibleCommissionCents)})," ","on"," ",e.jsx("strong",{children:at(r.nextEligibleCommissionAt)}),"."]})]}),r.eligibleCommissionCents<r.minimumPayoutCents?e.jsxs("div",{className:"flex items-start gap-2 text-xs text-muted-foreground bg-muted/10 p-3 rounded-lg border border-border",children:[e.jsx(je,{className:"h-4 w-4 text-amber-500 shrink-0 mt-0.5"}),e.jsxs("p",{children:["You need at least"," ",e.jsx("strong",{children:F(r.minimumPayoutCents)})," ","of eligible commissions to request a payout. You currently need"," ",e.jsx("strong",{children:F(r.minimumPayoutCents-r.eligibleCommissionCents)})," ","more."]})]}):r.affiliatePaypalEmail?W?e.jsxs("div",{className:"space-y-3 rounded-lg border border-border bg-muted/10 p-3",children:[e.jsxs("div",{className:"flex items-start gap-2 text-xs text-muted-foreground",children:[e.jsx(je,{className:"h-4 w-4 text-amber-500 shrink-0 mt-0.5"}),e.jsx("p",{children:"Accept the affiliate terms before requesting this payout."})]}),e.jsxs("div",{className:"flex items-start space-x-3",children:[e.jsx("input",{type:"checkbox",id:"accept-affiliate-terms-payout",checked:d,onChange:g=>p(g.target.checked),className:"mt-1 h-4 w-4 rounded border-border bg-background text-primary focus:ring-primary"}),e.jsxs("label",{htmlFor:"accept-affiliate-terms-payout",className:"text-xs leading-normal text-muted-foreground",children:["I agree to the"," ",e.jsx(ce,{to:"/affiliate-terms",target:"_blank",className:"font-medium text-primary hover:underline",children:"Affiliate Program Terms"}),", including disclosure requirements and no self-referrals."]})]})]}):e.jsxs("div",{className:"flex items-start gap-2 text-xs text-emerald-600 bg-emerald-500/5 p-3 rounded-lg border border-emerald-500/10",children:[e.jsx(ws,{className:"h-4 w-4 text-emerald-500 shrink-0 mt-0.5"}),e.jsxs("p",{children:["You have met the"," ",e.jsxs("strong",{children:[F(r.minimumPayoutCents)," minimum"]})," ","and are ready to request your manual payout of"," ",e.jsx("strong",{children:F(r.eligibleCommissionCents)}),"!"]})]}):e.jsxs("div",{className:"flex items-start gap-2 text-xs text-muted-foreground bg-muted/10 p-3 rounded-lg border border-border",children:[e.jsx(je,{className:"h-4 w-4 text-amber-500 shrink-0 mt-0.5"}),e.jsxs("p",{children:["You have met the payout threshold, but you need to save your"," ",e.jsx("strong",{children:"PayPal email address"})," before requesting a payout."]})]}),e.jsxs(w,{type:"button",className:"w-full",disabled:!U||v||m,onClick:M,children:[v||m?e.jsx(R,{className:"mr-2 h-4 w-4"}):null,"Request Payout"]})]})]})]}
1),e.jsxs(H,{className:"border-border bg-card",children:[e.jsxs(G,{children:[e.jsxs(K,{className:"text-lg font-bold flex items-center gap-2",children:[e.jsx(js,{className:"h-4 w-4 text-primary"}),"Payout Request History"]}),e.jsx(Q,{className:"text-xs",children:"Review your past manual payout requests and their status."})]}),e.jsx(Y,{children:r.payoutRequests.length===0?e.jsxs("div",{className:"text-center py-6 text-xs text-muted-foreground",children:[e.jsx(Ns,{className:"h-8 w-8 mx-auto text-muted-foreground/30 mb-2"}),"No payout requests yet."]}):e.jsxs(Ds,{children:[e.jsx(Os,{children:e.jsxs(Xe,{children:[e.jsx($,{children:"Requested Date"}),e.jsx($,{children:"PayPal Email"}),e.jsx($,{children:"Payout Name"}),e.jsx($,{className:"text-right font-mono",children:"Amount"}),e.jsx($,{children:"Status"}),e.jsx($,{children:"Reference"}),e.jsx($,{children:"Notes"})]})}),e.jsx(qs,{children:r.payoutRequests.map(g=>e.jsxs(Xe,{children:[e.jsx(V,{className:"text-xs",children:at(g.created_at)}),e.jsx(V,{className:"text-xs font-mono",children:g.paypal_email}),e.jsx(V,{className:"text-xs",children:g.payout_name||"—"}),e.jsx(V,{className:"text-right font-mono text-xs font-semibold",children:F(g.amount_cents)}),e.jsx(V,{children:e.jsx(Qe,{variant:g.status==="paid"?"default":g.status==="rejected"?"destructive":"secondary",className:"text-[10px]",children:g.status})}),e.jsx(V,{className:"text-xs text-muted-foreground max-w-[160px] truncate",title:g.payout_reference||"",children:g.payout_reference||"—"}),e.jsx(V,{className:"text-xs text-muted-foreground max-w-[200px] truncate",title:g.admin_notes||"",children:g.admin_notes||"—"})]},g.id))})]})})]})]})},Et=["setup","watchlist","affiliate","help","options"],nt={setup:{title:"Mentor profile",description:"Your trading style, rules and the patterns you want to improve."},watchlist:{title:"Watchlist",description:"Keep the charts you want to review in one place."},help:{title:"Help",description:"Find setup guidance or report a problem with your review."},options:{title:"Account",description:"Manage your profile, preferences and sign-in."},affiliate:{title:"Affiliate program",description:"Your referral link, commissions and payouts."}},Ee={advanced:"setup",review:"setup"},Pt={setup:["mentor-memory"],watchlist:["watchlist"],affiliate:[],help:["report-problem"],options:[]};function Ur(t,s){return t==="options"&&s==="#report-problem"?"help":Ee[t]?Ee[t]:Et.includes(t)?t:null}function Wr(t){return t in Ee}function Br(t,s){return Pt[t]?.includes(s)?s:null}function $r(t){for(const s of Et)if(Pt[s].includes(t))return s;return null}function Vr({account:t,watchlist:s,view:r}){const{profile:a,reviewPromptOpen:n,setReviewPromptOpen:l,reviewPromptStep:o,setReviewPromptStep:c,reviewFeedback:d,setReviewFeedback:p,submittingReviewFeedback:m,setIsPromptOnboardingModalDismissed:f,setShowTutorialModal:h,accountTab:x,setAccountTab:j,updateProfileFlags:u,handleSignOut:y,handleReviewPromptOpenChange:S,handleHappyReviewClick:v,handleSubmitReviewFeedback:b}=t,{shouldRenderPromptOnboardingModal:N,isPromptOnboardingPreview:A,nextAction:_,shouldShowAccountReviewPrompt:T,plan:M,isPaidAccount:I,hasUsedFreeReview:W,onAccountAnchorClick:U}=r,g=()=>{h(!1),f(!0)},L=nt[x]??nt.setup;return e.jsxs("div",{className:"min-h-screen bg-background text-foreground",children:[N&&e.jsx(Ks,{isPreview:A,onContinue:()=>{g(),u({account_prompt_onboarding_seen:!0,account_prompt_onboarding_completed:!0})},onExitPreview:()=>h(!1),onDismissForever:()=>{g(),u({account_prompt_onboarding_seen:!0,account_prompt_onboarding_dismissed:!0})}}),e.jsx(ut,{}),e.jsx("main",{id:"main-content",tabIndex:-1,className:"mx-auto max-w-[1400px] px-4 pb-12 pt-8 sm:px-6 lg:px-8",children:e.jsxs("div",{className:"space-y-4 sm:space-y-5",children:[e.jsx("header",{className:"flex flex-col gap-4 border-b border-border pb-3 sm:pb-4 md:flex-row md:items-end md:justify-between",children:e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"hidden text-xs uppercase tracking-wide text-muted-foreground sm:block",children:"Workspace"}),e.jsx("h1",{className:"text-xl font-semibold tracking-tight sm:text-2xl",children:L.title}),e.jsx("p",{className:"max-w-2xl text-sm text-muted-foreground",children:L.description})]})}),e.jsx(Js,{extensionPresent:t.extensionPresent,hasUsedFreeReview:W,planName:M.name,isPaidAccount:I,nextAction:_,onAnchorClick:U}),e.jsx(Xs,{shouldShowBanner:T,open:n,step:o,feedback:d,submitting:m,onOpenChange:S,onOpenBanner:()=>l(!0),onStepChange:c,onFeedbackChange:p,onHappyReviewClick:v,onSubmitFeedback:b}
1),e.jsx(As,{value:x,onValueChange:j,className:"space-y-4 sm:space-y-5",children:e.jsxs("div",{className:"grid gap-4 sm:gap-5 lg:grid-cols-[220px_minmax(0,1fr)] lg:items-start",children:[e.jsx(Rs,{accountTab:x,onAccountTabChange:j}),e.jsxs("div",{className:"min-w-0 space-y-4 sm:space-y-5",children:[e.jsx(Zs,{mentorSeedSection:e.jsx(Lr,{userId:a?.id})}),e.jsx(mr,{watchlist:s,userId:t.user?.id??null}),e.jsx(de,{value:"affiliate",className:"mt-0 space-y-5",children:e.jsx(qr,{})}),e.jsx(zs,{profile:a}),e.jsx(Gs,{profile:a,onSignOut:y})]})]})})]})})]})}const Hr="165916";function it(t,s){const r=new URL(t,"https://www.tradingview.com");return r.searchParams.set("aff_id",Hr),r.toString()}function Yr({planTier:t,subscriptionStatus:s,scansThisMonth:r,monthlyLimit:a,extensionPresent:n,isPaidAccount:l}){const o=Math.max(a-r,0),c=r>0,d=t==="free"||!t;if(d&&o<=0)return{title:"Ready to upgrade to Unlimited?",description:"You've completed your initial mentor sessions. Upgrade to Unlimited for continuous daily reviews and mentor feedback.",cta:"Upgrade to Unlimited",href:"/account/billing",external:!1};if(!n)return{title:"Install the Chrome extension",description:"Install the Chrome extension, then open TradingView for current market briefs and plan reviews on the chart.",cta:"Install extension",href:mt,external:!0};if(!c)return{title:"Start your mentor session on TradingView",description:"Open a chart, mark your plan or chat with your AI mentor to pressure-test your setup before entry.",cta:"Open TradingView",href:it("/chart/"),external:!0};const p=Vs({planTier:t,subscriptionStatus:s,scansThisMonth:r,monthlyLimit:a,firstAnalysisCompleted:c}),m=d?"Free session is active":"Unlimited is active";return{title:l?"Your AI mentor is ready":Hs(p),description:`${m}. Open the extension to begin a mentor session, then mark or enter a plan when you want the thesis challenged against your Strategy Lens.`,cta:"Open TradingView",href:it("/chart/"),external:!0}}const zr=[{key:"icc",name:"ICC Beginner",description:"Indication, Correction, Continuation",prompt:`Use an ICC continuation lens only when the visible chart contains all three phases (Indication, Correction, Continuation).
2
3Scope:
4- A readable timeframe with a directional impulse, a pullback, and a possible continuation location.
5
6Required evidence:
7- Indication: a visible impulse that closes beyond a prior swing or the boundary of a defined consolidation.
8- Correction: a retracement that stays on the correct side of the impulse origin and has a visible corrective swing.
9- Continuation: the proposed entry has a visible level and an unobstructed path to the next opposing structure.
10
11Activation:
12- A candle close through the last corrective swing in the impulse direction, or a visible rejection of the correction level followed by that close.
13- A wick alone is not activation.
14
15Invalidation:
16- A close that accepts beyond the impulse origin, or a break of the correction swing that supports the thesis.
17- If the chart cannot locate either level, return no trigger.
18
19False-break rule:
20- A close beyond the decision level that immediately returns inside the prior structure is a failed continuation. Do not chase it.
21
22Skip conditions:
23- Flat chop.
24- A single-candle spike without follow-through.
25- An already completed extension.
26- A gap whose open leaves no defensible structural stop.
27- Conflicting visible timeframe evidence - report the conflict and require the higher visible structure to resolve before a directional signal.
28
29Do not infer:
30- Unseen higher/lower timeframe structure, volume, session, liquidity, news, or indicators.
31
32Examples:
33- Correct: an impulse closes above a prior swing, the pullback holds above the impulse origin, then a candle's body closes back through the correction swing -> ICC activation confirmed.
34- Reject: the pullback wicks below the impulse origin but closes back above it -> correction is intact; wait for an actual close-through, not the wick.`},{key:"scalp",name:"Scalping",description:"Short-term, fast-paced setups",prompt:`Use a scalp lens only for a liquid-looking intraday chart where the visible timeframe and execution location are readable.
35
36Required evidence:
37- A defined micro range or recent swing.
38- A visible sweep-and-reclaim or break-and-retest.
39- A specific decision price.
40- A structural stop beyond the sweep extreme or micro swing.
41
42Activation:
43- Sweep: a close back through the swept level.
44- Break: a close outside the micro range and a retest that holds.
45- Never activate on a wick, a mid-range print, or a moving price with no close.
46
47Invalidation:
48- Acceptance beyond the sweep extreme.
49- A close back inside the broken range.
50- A stop that cannot be placed beyond visible structure.
51
52False-break / liquidity-trap rule:
53- A quick breach followed by immediate close back inside is a failed break. Do not reverse direction unless a separate visible structure shift confirms it.
54
55Skip conditions:
56- Session-open spikes.
57- Gapped opens.
58- Low-volume drift.
59- Spread/slippage conditions not visible or supplied.
60- Broad stops.
61- Late extension.
62- Charts where the next level is too close to support a defensible path.
63- A visible higher timeframe that conflicts with the micro setup - downgrade to watch/no trigger instead of averaging the biases.
64
65Do not infer:
66- Order flow, volume, liquidity, session phase, or news.
67
68Examples:
69- Correct activation: a micro range low is swept, the very next candle's body closes back above the swept level -> sweep-and-reclaim confirmed, use that close as the entry reference.
70- Reject, not activation: price dips through the micro low on a lower wick but the candle's body closes above it, and no separate candle ever closed below the level -> the level was never accepted through; there is nothing to reclaim.`},{key:"swing",name:"Swing Trading",description:"Multi-day trend setups",prompt:`Use a swing lens for a readable broader chart with room between the proposed trigger, structural invalidation, and the next major opposing level.
71
72Required evidence (either):
73- A visible sequence of higher-highs/higher-lows or lower-highs/lower-lows plus a controlled pullback into a prior swing/broken level.
74- A defined base breakout followed by acceptance outside the base and a held retest.
75
76Activation:
77- A close through the corrective swing in the trend direction, or a close outside the base followed by a retest that remains outside it.
78- A wick is never confirmation.
79
80Invalidation:
81- Acceptance beyond the swing defining the thesis.
82- A close back inside a failed breakout base.
83- A gap that leaves no visible stop anchor.
84
85False-break rule:
86- A breakout that closes outside then closes back inside the base before entry marks the thesis failed - wait for a new structure.
87
88Skip conditions:
89- Late extension.
90- Compressed chop.
91- Low-volume drift.
92- Nearby opposing structure.
93- Earnings/news windows, unless trusted context supplies them.
94- A conflict between the visible higher timeframe and entry timeframe - unresolved conflict is watch/no trigger.
95
96Do not infer:
97- Unseen higher timeframe bias, overnight behavior, volume, catalysts, correlations, or future sessions.
98
99Examples:
100- Correct activation: an uptrend pulls back into a prior swing low, the next candle's body closes back above the swing high that started the pullback -> continuation confirmed.
101- Reject, not activation: the pullback candle's wick dips into the prior swing low but the candle's body closes well above it -> price never accepted at that level; wait for an actual retest-and-close, not a wick tag.`},{key:"crypto",name:"Crypto Analysis",description:"Crypto-specific context",prompt:`Use a crypto lens only when the visible symbol, timeframe, price scale, and structure are readable, and the chart does not show disorderly thin trading.
102
103Required evidence:
104- A defined swing/range.
105- Plus one of: a sweep-and-reclaim, compression followed by multi-candle expansion, or a breakout that closes outside and holds on retest.
106
107Activation:
108- A close back above/below the swept level, a close beyond the range followed by acceptance, or a held retest.
109- A liquidation-style wick alone is not confirmation.
110
111Invalidation:
112- Acceptance beyond the sweep extreme.
113- A close back inside the breakout range.
114- A break of the swing that anchors the thesis.
115
116False-break / liquidity-trap rule:
117- A fast breach with immediate return inside is failed. Do not assume the opposite trade is valid without a new structure shift.
118
119Skip conditions:
120- Thin/erratic candles.
121- Low-volume drift when volume is visible.
122- Funding/open-interest/liquidation claims without trusted data.
123- Gapped or exchange-transition opens.
124- Mid-range entries.
125- Already extended moves.
126- A visible benchmark or higher-timeframe structure that conflicts with the setup - state the conflict and downgrade to watch/no trigger.
127
128Do not infer:
129- Funding, open interest, liquidation clusters, exchange order flow, market sentiment, or hidden liquidity.
130
131Read the exact ticker/pair and exchange label before applying crypto-specific assumptions; crypto markets trade continuously with no session close, so do not import forex/equity session logic.
132
133Examples:
134- Correct: a swing low is swept, the next candle's body closes back above the swept level with visible follow-through -> sweep-and-reclaim confirmed.
135- Reject: a long lower wick touches below the swing low but the candle's body closes above it, and price never traded a confirmed close below the level ->
135 nothing was swept; this is normal range noise.`},{key:"forex",name:"Forex Majors",description:"Macro-aware forex analysis",prompt:`Use a forex-major lens only for a readable major pair chart with a visible range, swing structure, round-number reference, or labeled session level.
136
137Required evidence:
138- A range edge rejection, failed break, or break-and-retest with a visible decision price and room to the next opposing level.
139
140Activation:
141- A candle close through the decision level plus a held retest, or a close back inside the range after a failed break.
142- A wick beyond a level is not enough.
143
144Invalidation:
145- Acceptance beyond the range/swing extreme.
146- A close back inside a breakout that has not yet retested.
147- A stop that cannot be anchored structurally.
148
149False-break rule:
150- A break that returns inside and holds is a failed break. Do not chase the original direction.
151
152Skip conditions:
153- Mid-range entries.
154- Late expansion.
155- Thin/low-volume drift where visible.
156- Session-open volatility.
157- Gapped opens.
158- Trusted event-risk windows - if event timing is unavailable, do not claim it is clear.
159- Visible pair structure that conflicts with supplied macro context - chart structure stays primary, but disclose the conflict and reduce confidence.
160
161Do not infer:
162- Spread, session, news, yields, central-bank policy, or currency correlation, unless visible or trusted server context supplies it.
163
164Read the exact pair and exchange/session label before applying round-number or session logic; only reference a session if the chart or trusted context names it.
165
166Examples:
167- Correct: price rejects a labeled round-number level, closes back inside the range, then a later candle's body closes through the level with a held retest -> break-and-retest confirmed.
168- Reject: price wicks through the round number but the candle's body closes back on the original side -> the level was tested, not broken; wait for an actual close through it.`},{key:"ict",name:"ICT / Smart Money",description:"Order blocks, FVGs, liquidity",prompt:`Use an ICT/smart-money lens only when the complete visible sequence supports the label. Never label a zone from one candle or narrative vocabulary.
169
170Required evidence:
171- A visible liquidity pool at equal highs/lows or a prior swing.
172- A sweep/raid beyond that pool.
173- Displacement that closes through a meaningful structure point.
174- An FVG only if visible: a three-candle gap where candle 1's high (bullish) or low (bearish) does not overlap candle 3's low or high.
175- An order block only if visible: the last opposite-colored candle before a strong displacement move, with its originating base, the displacement, and invalidation all visible.
176
177Activation:
178- Retracement into the still-unmitigated FVG/order-block area, rejection there, and a close through the intended corrective swing.
179- Entry on zone touch alone is not activation.
180
181Invalidation:
182- Beyond the swept swing or defining block.
183- Full mitigation/acceptance through the zone.
184- The supposed structure shift is reversed.
185
186Liquidity-trap rule:
187- A sweep without displacement and a hold is a liquidity event, not a trade.
188
189Skip conditions:
190- Narrative-only labels.
191- Weak displacement.
192- Already mitigated zones.
193- Undefined dealing ranges.
194- Session assumptions.
195- Gapped opens with no stop anchor.
196- Conflicting visible timeframe structure - unresolved conflict is no trigger.
197
198Do not infer:
199- Hidden liquidity, order flow, session bias, institutional intent, or unseen higher-timeframe dealing ranges.
200
201Examples:
202- Correct: liquidity rests at equal highs, price sweeps above them, displaces down through a swing low, retraces into the unmitigated FVG left by that move, then closes through the next corrective swing -> activation.
203- Reject: price touches the FVG zone and immediately reverses on the same candle's wick without a follow-through close -> zone touch alone is not activation; wait for the close.`},{key:"volume_profile",name:"Volume Profile",description:"Value, acceptance, and imbalance",prompt:`Use an auction-market lens only when a trustworthy volume profile, VWAP, volume series, or clearly labeled value area is visible/supplied.
204
205Required evidence:
206- Value high, value low, point of control, or prior balance - only when the level is actually shown.
207
208Activation:
209- Continuation: a close outside value followed by acceptance or a held retest.
210- Reversion: rejection at an extreme and re-entry into value.
211- Never based on distance from an unseen mean.
212
213Invalidation:
214- Acceptance beyond the failed value edge.
215- A break of the balance boundary supporting the thesis.
216- A return into value after an unconfirmed breakout.
217
218Structure note:
219- Treat low-volume nodes as travel zones, not guaranteed support/resistance.
220
221Skip conditions:
222- Volume data is absent.
223- Profile session boundaries are unknown.
224- The open is gapped outside value with no acceptance.
225- Price is drifting on low participation.
226
227Do not infer:
228- Volume, VWAP, auction intent, or institutional positioning from candle shape alone.
229
230Output rule:
231- If no volume profile, VWAP, or labeled value area is visible or supplied, return watch/no trigger immediately. Do not approximate a value area from candle shape or price clustering alone.
232
233Examples:
234- Correct: price closes below the shown value area low, then holds a retest against the underside of the value area -> continuation-from-value activation.
235- Reject: price is simply near a round price level with no plotted profile or VWAP shown -> there is no visible value reference here; this lens does not apply.`},{key:"wyckoff",name:"Wyckoff",description:"Cause, test, and range resolution",prompt:`Use a Wyckoff lens only when a visible trading range has enough bars to show repeated tests and a meaningful range boundary.
236
237Required evidence:
238- A clearly bounded accumulation/distribution hypothesis.
239- An observable stopping action or failed break.
240- A test that holds relative to the range.
241- Spring/upthrust label: a break beyond the range followed by a close back inside.
242- SOS/SOW label: displacement and a break of an internal swing, not a single large candle.
243
244Activation:
245- A close beyond the relevant test/swing and a held retest.
246- A schematic label alone is not activation.
247
248Invalidation:
249- Acceptance beyond the range boundary against the thesis, or failure of the test low/high.
250
251Skip conditions:
252- Ranges too short to establish cause.
253- Low-volume drift without visible volume.
254- Gaps.
255- Session-open spikes.
256- Cases where accumulation and distribution are equally plausible.
257
258Do not infer:
259- Composite-operator intent, hidden volume, or an exact Wyckoff phase not visible on the chart.
260
261Examples:
262- Correct: price breaks below the range low (spring), the very next candle's body closes back inside the range -> spring confirmed, watch for a held retest before continuation.
263- Reject: price closes below the range low and stays there for several candles -> that is a breakdown, not a spring; the range has failed, not been tested.`}];function Fe(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Rt(t){const s=Fe(t);return{account_prompt_onboarding_seen:s.account_prompt_onboarding_seen===!0,account_prompt_onboarding_completed:s.account_prompt_onboarding_completed===!0,account_prompt_onboarding_dismissed:s.account_prompt_onboarding_dismissed===!0}}function Gr(t){const s=Fe(t);return{account_review_prompt_shown:s.account_review_prompt_shown===!0,account_review_prompt_public_clicked:s.account_review_prompt_public_clicked===!0,account_review_prompt_private_submitted:s.account_review_prompt_private_submitted===!0}}function Kr(t){return t==="short"||t==="detailed"?t:"standard"}const ot={free:{name:"Free",icon:xt,color:"bg-muted",textColor:"text-muted-foreground",credits:oe("free"),description:"Generous first session, no card required"},starter:{name:"Starter",icon:ks,color:"bg-accent/20",textColor:"text-accent",credits:oe("starter"),description:"Unlimited"},pro:{name:"Unlimited",icon:Ae,color:"bg-primary/20",textColor:"text-primary",credits:oe("pro"),description:"Unlimited mentor chat and chart reviews"},elite:{name:"Elite",icon:Ae,color:"bg-primary/20",textColor:"text-primary",credits:oe("elite"),description:"Unlimited"}},Qr={icc:Ye,scalp:xt,swing:Ye,crypto:gt,forex:pt,ict:Ae,volume_profile:Cs,wyckoff:_s};[...zr.map(t=>({name:t.name,icon:Qr[t.key]??gt,description:t.description,prompt:t.prompt})),ft];const Mt="sharp_mentor",Xr=[{value:"sharp_mentor",label:"Sharp mentor",description:"Leads with the trigger and invalidation. Second-person, no filler, no hedging."}
263,{value:"strict_coach",label:"Strict coach",description:"Zero comfort padding. Names late entries, soft stops, and risk you haven't earned."},{value:"calm_pro",label:"Calm pro",description:"Flat desk-terminal tone. States the condition and the level, nothing else."}];function Zr(t){return t==="protective_bro"?"sharp_mentor":Xr.some(s=>s.value===t)?t:Mt}const lt="cm_referral_claimed_code",Jr=new Set(["claimed","activated","already_claimed","invalid_code","self_referral","signup_window_closed","already_active"]),It=()=>typeof window<"u";function ea(t){if(!It())return null;try{return window.localStorage.getItem(t)}catch{return null}}function ta(t,s){if(It())try{window.localStorage.setItem(t,s)}catch{}}async function sa(){const t=rs();if(!t||ea(lt)===t)return null;const{data:s,error:r}=await C.functions.invoke("claim-referral",{body:{code:t}});if(r)return console.debug("[Referrals] claim-referral failed:",r.message),null;const a=String(s?.status||"unknown");return Jr.has(a)&&ta(lt,t),{status:a}}const ct=`${mt}/reviews`;function ra(){const t=Yt(),[s,r]=dt(),{user:a,loading:n,signOut:l}=Pe(),{toast:o}=ee(),[c,d]=i.useState(null),[p,m]=i.useState(!0),[f,h]=i.useState(""),[x,j]=i.useState(!1),[u,y]=i.useState(!1),[S,v]=i.useState("question"),[b,N]=i.useState(""),[A,_]=i.useState(!1),[T,M]=i.useState(!1),[I,W]=i.useState(!1),[U,g]=i.useState(!1),[L,D]=i.useState(!1),[te,ue]=i.useState(!1),[se,z]=i.useState("setup"),[,re]=i.useState("signal_generator"),[Ft,Le]=i.useState("standard"),[Lt,De]=i.useState(Mt),[Dt,Ot]=i.useState("idle"),[qt,Oe]=i.useState(!1),Ut=i.useRef(null),me=i.useRef({}),ve=i.useRef(null),Wt=i.useRef(0),qe=Us(s.get("coachingWeek"),s.get("coachingReview"));i.useEffect(()=>{if(!n&&!a){const k=qe?.split("?")[1]?.split("#")[0];t(`/auth?mode=login${k?`&${k}`:""}`)}},[a,n,t,qe]),i.useEffect(()=>{a&&Ue()},[a,n,t]),i.useEffect(()=>{n||!a||sa().then(k=>{(k?.status==="claimed"||k?.status==="activated")&&Ue()})},[a,n]),i.useEffect(()=>(Oe(as()),ns(()=>Oe(!0))),[]),i.useEffect(()=>{s.get("success")==="true"&&t(`/account/billing?${s.toString()}`,{replace:!0})},[t,s]),i.useEffect(()=>{n||!a||s.get("checkout")!=="resume"||t("/account/billing?checkout=resume",{replace:!0})},[n,t,s,a]),i.useEffect(()=>{const k=s.get("tab");if(!k)return;const E=Ur(k,window.location.hash);if(E){if(z(E),Wr(k)){const P=new URLSearchParams(s);P.set("tab","setup"),t(`/account?${P.toString()}`,{replace:!0});return}if(E!==k){const P=new URLSearchParams(s);P.set("tab",E),r(P,{replace:!0})}}},[t,s,r]),i.useEffect(()=>{const k=window.location.hash.slice(1),E=Br(se,k);E&&window.setTimeout(()=>{document.getElementById(E)?.scrollIntoView({behavior:"auto",block:"start"})},0)},[se]),i.useEffect(()=>()=>{ve.current!==null&&window.clearTimeout(ve.current)},[]);const Ue=async()=>{if(!a)return;const[{data:k,error:E},P,we]=await Promise.all([C.from("profiles").select("id, email, full_name, system_prompt, flags_json, disclaimer_accepted, signal_rules, plan_tier, subscription_status, credits_remaining, scans_this_month, monthly_limit").eq("id",a.id).single(),C.functions.invoke("get-profile"),C.from("bug_reports").select("id",{count:"exact",head:!0}).eq("user_id",a.id).eq("category","review_feedback")]);if(E){console.error("Error fetching profile:",E),m(!1);return}const O=P?.data??{},q=k,We=O.planTier??q.plan_tier??"free",Be=O.monthlyLimit??oe(We),$e=typeof O.creditsRemaining=="number"?O.creditsRemaining:q.credits_remaining??0,Vt=typeof O.creditsRemaining=="number"?Math.max(0,Be-$e):q.scans_this_month??0,Ht={...q,plan_tier:We,subscription_status:O.subscriptionStatus??q.subscription_status??"free",credits_remaining:$e,scans_this_month:Vt,monthly_limit:Be,referral_bonus_scans_remaining:O.referralBonusScans??0,has_completed_review:!!O.hasCompletedReview};d(Ht),h(q.system_prompt||""),me.current=Fe(q.flags_json),Le(Kr(q.flags_json?.response_length??O.defaultResponseLength)),De(Zr(q.flags_json?.mentor_voice??O.mentorVoice)),q.disclaimer_accepted||g(!0),we?.error?console.warn("[account] review feedback dismissal lookup failed",we.error):W((we?.count??0)>0),re("signal_generator"),m(!1)},Bt=async()=>{await l(),t("/")},$t=async()=>{ue(!0),D(!1),c&&(Rt(c.flags_json).account_prompt_onboarding_seen||await he({account_prompt_onboarding_seen:!0})),window.scrollTo({top:0,behavior:"smooth"})},he=async k=>
263{if(!a||!c)return;const E={...me.current,...k};me.current=E,d(P=>P&&{...P,flags_json:E});try{const{error:P}=await C.from("profiles").update({flags_json:E}).eq("id",a.id);P&&console.error("[AccountProfile] updateProfileFlags failed:",P.message)}catch(P){console.error("[AccountProfile] updateProfileFlags exception:",P)}};return{searchParams:s,user:a,authLoading:n,profile:c,setProfile:d,loading:p,systemPrompt:f,setSystemPrompt:h,saving:x,setSaving:j,reviewPromptOpen:u,setReviewPromptOpen:y,reviewPromptStep:S,setReviewPromptStep:v,reviewFeedback:b,setReviewFeedback:N,submittingReviewFeedback:A,hasClickedPublicReviewPrompt:T,hasSubmittedReviewFeedbackReport:I,disclaimerNeeded:U,setDisclaimerNeeded:g,isPromptOnboardingModalDismissed:L,setIsPromptOnboardingModalDismissed:D,showTutorialModal:te,setShowTutorialModal:ue,accountTab:se,setAccountTab:z,responseLength:Ft,setResponseLength:Le,mentorVoice:Lt,setMentorVoice:De,preferencesSaveStatus:Dt,setPreferencesSaveStatus:Ot,extensionPresent:qt,onboardingSeenRef:Ut,latestFlagsRef:me,preferencesSaveTimerRef:ve,flagsMutationIdRef:Wt,toast:o,updateProfileFlags:he,handleSignOut:Bt,handleWatchTutorial:$t,handleReviewPromptOpenChange:k=>{y(k),k||(v("question"),N(""))},handleHappyReviewClick:()=>{if(!a)return;const k=window.open(ct,"_blank");k&&(k.opener=null),k||window.location.assign(ct),y(!1),M(!0),is(a.id),he({account_review_prompt_public_clicked:!0})},handleSubmitReviewFeedback:async()=>{if(!a||!c)return;const k=b.trim();if(k.length<10){o({title:"Feedback too short",description:"Add a few more words so it is useful.",variant:"destructive"});return}_(!0);const{error:E}=await C.from("bug_reports").insert({user_id:a.id,user_email:c.email,category:"review_feedback",description:`Account review prompt feedback:
264
265${k}`});if(_(!1),E){o({title:"Feedback not sent",description:"Please try again.",variant:"destructive"});return}W(!0),await he({account_review_prompt_private_submitted:!0}),N(""),y(!1),o({title:"Feedback sent",description:"I will review it from the admin panel."})}}}const aa=3,na=()=>e.jsxs("div",{className:"min-h-screen bg-background",children:[e.jsx(ut,{}),e.jsx("main",{id:"main-content",tabIndex:-1,className:"mx-auto max-w-[1400px] px-4 pb-12 pt-8 sm:px-6 lg:px-8",children:e.jsxs("div",{className:"animate-pulse space-y-5",children:[e.jsxs("div",{className:"space-y-2 border-b border-border pb-4",children:[e.jsx("div",{className:"h-6 w-48 rounded bg-muted"}),e.jsx("div",{className:"h-4 w-72 rounded bg-muted"})]}),e.jsx("div",{className:"h-28 rounded-md border border-border bg-muted/40"}),e.jsxs("div",{className:"grid gap-5 lg:grid-cols-[220px_minmax(0,1fr)]",children:[e.jsx("div",{className:"h-56 rounded-md border border-border bg-muted/40"}),e.jsx("div",{className:"h-96 rounded-md border border-border bg-muted/40"})]})]})})]}),Sa=()=>{const t=ra(),s=ir({userId:t.user?.id??null}),{searchParams:r,user:a,authLoading:n,profile:l,loading:o,hasClickedPublicReviewPrompt:c,hasSubmittedReviewFeedbackReport:d,disclaimerNeeded:p,setDisclaimerNeeded:m,isPromptOnboardingModalDismissed:f,setIsPromptOnboardingModalDismissed:h,showTutorialModal:x,setAccountTab:j,extensionPresent:u,onboardingSeenRef:y,updateProfileFlags:S}=t,v=l?.plan_tier||"free",b=ot[v]||ot.free,N=!0,A=Rt(l?.flags_json),_=Gr(l?.flags_json),T=r.get("previewPromptOnboarding")==="1",M=!!l?.system_prompt?.trim(),I=l?.scans_this_month??0,W=I>0,U=!!l&&N&&!p&&(T||W&&!M&&!A.account_prompt_onboarding_completed&&!A.account_prompt_onboarding_dismissed),g=(U||x)&&!f,L=l?.monthly_limit??b.credits,D=jt(v)&&["active","trialing","past_due"].includes(l?.subscription_status||""),te=!!l&&!g&&M&&u&&I>=aa&&!c&&!d&&!_.account_review_prompt_public_clicked&&!_.account_review_prompt_private_submitted,ue=Yr({planTier:v,subscriptionStatus:l?.subscription_status||"free",scansThisMonth:I,monthlyLimit:L,extensionPresent:u,isPaidAccount:D}),se=z=>{const re=z.slice(1);j($r(re)??"setup"),window.history.replaceState(null,"",`#${re}`),window.dispatchEvent(new Event("hashchange")),window.setTimeout(()=>{document.getElementById(re)?.scrollIntoView({behavior:"smooth",block:"start"})},0)};return i.useEffect(()=>{!a||!l||!te||_.account_review_prompt_shown||(os(a.id),S({account_review_prompt_shown:!0}))},[a?.id,l?.id,te,_.account_review_prompt_shown]),i.useEffect(()=>{T||!l||!U||A.account_prompt_onboarding_seen||y.current!==l.id&&(y.current=l.id,S({account_prompt_onboarding_seen:!0}))},[T,l,A.account_prompt_onboarding_seen,U]),i.useEffect(()=>{h(!1)},[l?.id,T]),i.useEffect(()=>{if(!g)return;const z=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=z}},[g]),n||o?e.jsx(na,{}
265):l?p?e.jsx(Ws,{onAccepted:()=>m(!1)}):e.jsx(Vr,{account:t,watchlist:s,view:{shouldRenderPromptOnboardingModal:g,isPromptOnboardingPreview:T,nextAction:ue,shouldShowAccountReviewPrompt:te,plan:b,isPaidAccount:D,hasUsedFreeReview:I>0,canCustomizePrompt:N,onAccountAnchorClick:se}}):e.jsx("div",{className:"min-h-screen bg-background flex items-center justify-center",children:e.jsx("p",{className:"text-muted-foreground",children:"Unable to load profile"})})};export{Sa 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.