PageSourceSearch

https://blue-flow.com/assets/Journaling-Bo5VVOvI.js

js blue-flow.com collected 2026-10-08 07:26:55 UTC 100,655 bytes, 26 lines download raw bytes

1import{c as _e,m as Se,j as e,u as Le,r as o,X as ze,s as rt,F as Ct,n as Tt,f as Ae,T as Dt,b as it,B as Ft}from"./index-BAbn0ab5.js";import{S as Ee}from"./star-BIEYPXfO.js";import{S as we}from"./sparkles-BFuxKIC_.js";import{U as Et}from"./upload-BWEhIMxi.js";import{C as qe}from"./calendar-BTiCifVB.js";import{C as ct}from"./chevron-up-BsxsHUah.js";import{C as xt}from"./chevron-down-DSmgHxsn.js";import{c as at,a as At,g as ke,D as Rt,A as Lt}from"./monthlyScore-BP-pfA4j.js";import{A as nt}from"./activity-DBLJQeeH.js";import{T as Bt}from"./target-DJRkQgwH.js";import{G as Wt}from"./gauge-BMMBvCDn.js";import{S as Ot}from"./shield-alert-BsssUKzV.js";import{G as It}from"./GlobalReportModal-BiuWw8PO.js";import"./ReportSections-BNGnewU7.js";import"./ComposedChart-CU5xVIx-.js";/**
2 * @license lucide-react v0.563.0 - ISC
3 *
4 * This source code is licensed under the ISC license.
5 * See the LICENSE file in the root directory of this source tree.
6 */const zt=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],qt=_e("file-text",zt);/**
7 * @license lucide-react v0.563.0 - ISC
8 *
9 * This source code is licensed under the ISC license.
10 * See the LICENSE file in the root directory of this source tree.
11 */const Ht=[["path",{d:"M10 20a1 1 0 0 0 .553.895l2 1A1 1 0 0 0 14 21v-7a2 2 0 0 1 .517-1.341L21.74 4.67A1 1 0 0 0 21 3H3a1 1 0 0 0-.742 1.67l7.225 7.989A2 2 0 0 1 10 14z",key:"sc7q7i"}]],Gt=_e("funnel",Ht);/**
12 * @license lucide-react v0.563.0 - ISC
13 *
14 * This source code is licensed under the ISC license.
15 * See the LICENSE file in the root directory of this source tree.
16 */const Jt=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}]],He=_e("message-square",Jt);/**
17 * @license lucide-react v0.563.0 - ISC
18 *
19 * This source code is licensed under the ISC license.
20 * See the LICENSE file in the root directory of this source tree.
21 */const Yt=[["path",{d:"M10 14.66v1.626a2 2 0 0 1-.976 1.696A5 5 0 0 0 7 21.978",key:"1n3hpd"}],["path",{d:"M14 14.66v1.626a2 2 0 0 0 .976 1.696A5 5 0 0 1 17 21.978",key:"rfe1zi"}],["path",{d:"M18 9h1.5a1 1 0 0 0 0-5H18",key:"7xy6bh"}],["path",{d:"M4 22h16",key:"57wxv0"}],["path",{d:"M6 9a6 6 0 0 0 12 0V3a1 1 0 0 0-1-1H7a1 1 0 0 0-1 1z",key:"1mhfuq"}],["path",{d:"M6 9H4.5a1 1 0 0 1 0-5H6",key:"tex48p"}]],Zt=_e("trophy",Yt);/**
22 * @license lucide-react v0.563.0 - ISC
23 *
24 * This source code is licensed under the ISC license.
25 * See the LICENSE file in the root directory of this source tree.
26 */const Ut=[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["line",{x1:"21",x2:"16.65",y1:"21",y2:"16.65",key:"13gj7c"}],["line",{x1:"11",x2:"11",y1:"8",y2:"14",key:"1vmskp"}],["line",{x1:"8",x2:"14",y1:"11",y2:"11",key:"durymu"}]],mt=_e("zoom-in",Ut);function Vt(s,r,d){const p=new Date(d,r,1),g=new Date(d,r+1,0).getDate(),N=p.getDay(),h=N===0?6:N-1,c={month:r,year:d,days:[],weeks:[]},b=new Map;s.forEach(u=>{if(!u.close_time)return;const E=new Date(u.close_time);if(E.getMonth()!==r||E.getFullYear()!==d)return;const B=E.getDate();b.has(B)||b.set(B,{date:B,trades:[],dailyPnL:0,tradeCount:0,winningTrades:0,losingTrades:0});const v=b.get(B);v.trades.push(u),v.dailyPnL+=u.net_pnl||0,v.tradeCount++,u.net_pnl>0?v.winningTrades++:u.net_pnl<0&&v.losingTrades++});for(let u=1;u<=g;u++){const E=b.get(u);E?(E.winRate=E.tradeCount>0?E.winningTrades/E.tradeCount*100:0,E.trades.sort((B,v)=>{var $,A;const L=(($=B.close_time)==null?void 0:$.getTime())||0;return(((A=v.close_time)==null?void 0:A.getTime())||0)-L}),c.days.push(E)):c.days.push({date:u,trades:[],dailyPnL:0,tradeCount:0,winRate:0,winningTrades:0,losingTrades:0})}let S=[],y=0,F=0;for(let u=0;u<h;u++)S.push(null);return c.days.forEach((u,E)=>{if(S.push(u),y+=u.dailyPnL,S.length===7||E===c.days.length-1){for(;S.length<7;)S.push(null);c.weeks.push({weekIndex:F++,days:[...S],weekPnL:y}),S=[],y=0}}),c}function Kt(s){return["January","February","March","April","May","June","July","August","September","October","November","December"][s]}function Xt(s){return["Mon","Tue","Wed","Thu","Fri","Sat","Sun"][s]}function Qt(s,r,d){return`${s}.${r+1}.${d}.`}
26function es({dayData:s,onDayClick:r,month:d,year:p,enrichmentData:P,reportsByDate:g,onOpenReport:N,onOpenReportList:h}){const{getJournalEntry:c,toggleSpecialDay:b,isSpecialDay:S}=Se();if(!s)return e.jsx("div",{className:"bg-dark-800 border border-dark-700 p-2 min-h-[100px]"});const{date:y,dailyPnL:F,tradeCount:u,trades:E}=s,B=u>0,v=`${p}-${String(d+1).padStart(2,"0")}-${String(y).padStart(2,"0")}`,L=c(v),j=P==null?void 0:P[v],$=(L==null?void 0:L.notes)&&L.notes.trim().length>0,A=S(v),f=(g==null?void 0:g[v])||[],m=L==null?void 0:L.gwtdd_14day_avg,i=m!=null,M=L==null?void 0:L.stress_level,Z=M!=null&&M!==0,X=()=>{r(y,s)},I=k=>{k.stopPropagation(),b(v)},K=k=>{k.stopPropagation(),f.length>0&&(h==null||h(v))};return e.jsxs("div",{onClick:X,className:"bg-dark-800 border border-dark-700 p-2 min-h-[100px] transition-all cursor-pointer hover:bg-dark-750 hover:border-primary-500 relative",children:[e.jsxs("div",{className:"flex items-start justify-between mb-2",children:[e.jsx("span",{className:"text-sm font-semibold text-gray-400",children:y}),e.jsx("button",{onClick:I,className:"p-0.5 hover:bg-dark-700 rounded transition-colors",title:A?"Unmark special day":"Mark as special day",children:e.jsx(Ee,{className:`w-3.5 h-3.5 transition-colors ${A?"text-yellow-400 fill-yellow-400":"text-dark-600 hover:text-dark-500"}`})})]}),$&&e.jsx("div",{className:"absolute bottom-2 left-1/2 transform -translate-x-1/2",children:e.jsx(qt,{className:"w-3.5 h-3.5 text-blue-400 opacity-60"})}),f.length>0&&e.jsxs("button",{onClick:K,className:"absolute bottom-2 right-2 flex items-center gap-0.5 hover:opacity-100 opacity-70 transition-opacity",title:`${f.length} global report${f.length>1?"s":""} — click to choose one`,children:[e.jsx(we,{className:"w-3.5 h-3.5 text-purple-400"}),f.length>1&&e.jsx("span",{className:"text-[9px] font-bold text-purple-400",children:f.length})]}),B&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:`text-lg font-bold ${F>=0?"text-green-400":"text-red-400"}`,children:["$",F.toFixed(2)]}),e.jsxs("div",{className:"text-xs text-gray-500",children:[u," ",u===1?"trade":"trades"]})]}),(i||Z)&&e.jsx("div",{className:"mt-2 pt-2 border-t border-dark-700",children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[i&&e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"text-xs font-semibold text-blue-400",children:parseFloat(m).toFixed(1)}),e.jsx("div",{className:"text-[10px] text-gray-600",children:"GWTDD"})]}),Z&&e.jsxs("div",{className:"flex-1 text-right",children:[e.jsxs("div",{className:`text-xs font-bold ${M===0?"text-gray-400":M===1?"text-green-400":M===2?"text-yellow-400":M===3?"text-orange-400":M===4?"text-red-400":M===5?"text-red-500":"text-gray-400"}`,children:["L",M]}),e.jsx("div",{className:"text-[10px] text-gray-600",children:(L==null?void 0:L.stress_tactical)!=null?`day L${L.stress_tactical}`:"STRESS"})]})]})}),j&&(j.ng_price_change_pct!=null||j.gwtdd_tail_delta!=null)&&e.jsx("div",{className:"mt-1 pt-1 border-t border-dark-700/50",children:e.jsxs("div",{className:"flex items-center justify-between gap-1",children:[j.ng_price_change_pct!=null&&e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:`text-[10px] font-bold ${j.ng_price_change_pct>0?"text-green-400":j.ng_price_change_pct<0?"text-red-400":"text-gray-500"}`,children:[j.ng_price_change_pct>0?"+":"",j.ng_price_change_pct.toFixed(1),"%"]}),e.jsx("div",{className:"text-[8px] text-gray-600",children:"NG"})]}),j.gwtdd_tail_delta!=null&&e.jsxs("div",{className:"flex-1 text-right",children:[e.jsxs("div",{className:`text-[10px] font-bold ${j.gwtdd_tail_delta>0?"text-green-400":j.gwtdd_tail_delta<0?"text-red-400":"text-gray-500"}`,children:[j.gwtdd_tail_delta>0?"+":"",j.gwtdd_tail_delta.toFixed(2)]}),e.jsx("div",{className:"text-[8px] text-gray-600",children:"ΔTail"})]})]})})]})}function ts({calendarData:s,onDayClick:r,month:d,year:p,enrichmentData:P,reportsByDate:g,onOpenReport:N,onOpenReportList:h}){const{weeks:c}=s;return e.jsxs("div",{className:"bg-dark-800 rounded-lg border border-dark-700 overflow-hidden",children:[e.jsxs("div",{className:"grid grid-cols-8 bg-dark-900",children:[[0,1,2,3,4,5,6].map(b=>e.jsx("div",{className:"px-4 py-3 text-center text-xs font-semibold text-gray-400 uppercase tracking-wider border-r border-dark-700",children:Xt(b)},b)),e.jsx("div",{className:"px-4 py-3 text-center text-xs font-semibold text-gray-400 uppercase tracking-wider",children:"Wk"})]}),c.map((b,S)=>e.jsxs("div",{className:"grid grid-cols-8 border-t border-dark-700",children:[b.days.map((y,F)=>e.jsx("div",{className:"border-r border-dark-700",children:e.jsx(es,{dayData:y,onDayCl
26ick:r,month:d,year:p,enrichmentData:P,reportsByDate:g,onOpenReport:N,onOpenReportList:h})},F)),e.jsxs("div",{className:"bg-dark-900 p-2 min-h-[100px] flex flex-col items-center justify-center",children:[e.jsxs("div",{className:"text-xs text-gray-500 mb-1",children:["Week ",b.weekIndex+1]}),e.jsxs("div",{className:`text-sm font-bold ${b.weekPnL>=0?"text-green-400":"text-red-400"}`,children:["$",b.weekPnL.toFixed(2)]})]})]},S))]})}function ss({isOpen:s,onClose:r,dayData:d,month:p,year:P}){const{saveJournalEntry:g,getJournalEntry:N,getTotalEquity:h,getTotalStats:c,trades:b,cashFlow:S,addGlobalPosition:y,updateGlobalPosition:F,closeGlobalPosition:u,partialCloseGlobalPosition:E,getPositionsForDate:B}=Se(),{getAuthHeader:v}=Le(),[L,j]=o.useState(""),[$,A]=o.useState(""),[f,m]=o.useState("idle"),[i,M]=o.useState(null),[Z,X]=o.useState(!1),[I,K]=o.useState(null),[k,Q]=o.useState(null),[R,ie]=o.useState(null),[w,W]=o.useState(""),[Y,U]=o.useState(""),[se,n]=o.useState([]),[l,a]=o.useState(!1),[C,O]=o.useState("Buy"),[le,H]=o.useState(""),[ee,ae]=o.useState(""),[oe,T]=o.useState(""),[D,V]=o.useState(""),[ce,z]=o.useState(""),[J,he]=o.useState(""),[ue,ge]=o.useState(""),[xe,fe]=o.useState(null),be=(t,x)=>{const _=t.trim(),G=(x||"").trim()||"00:00";if(!_)return new Date().toISOString().slice(0,16);const re=de=>de.length===2?"20"+de:de,ne=_.match(/^(\d{1,2})[./](\d{1,2})[./](\d{2}|\d{4})$/);if(ne){const de=re(ne[3])+"-"+ne[2].padStart(2,"0")+"-"+ne[1].padStart(2,"0")+"T"+G;if(!isNaN(new Date(de).getTime()))return de}const me=_.match(/^(\d{1,2})[./](\d{1,2})[./]?$/)||_.match(/^(\d{2})(\d{2})$/);if(me){const de=new Date,ye=Oe=>String(Oe).padStart(2,"0");let Fe=de.getFullYear();const st=Fe+"-"+ye(me[2])+"-"+ye(me[1]);if(!isNaN(new Date(st).getTime())){const Oe=Fe+"-"+ye(de.getMonth()+1)+"-"+ye(de.getDate());return st>Oe&&(Fe-=1),Fe+"-"+ye(me[2])+"-"+ye(me[1])+"T"+G}}const De=_.match(/^(\d{2})(\d{2})(\d{2}|\d{4})$/);if(De){const de=re(De[3])+"-"+De[2]+"-"+De[1]+"T"+G;if(!isNaN(new Date(de).getTime()))return de}return _.match(/^(\d{4})-(\d{2})-(\d{2})$/)?_+"T"+G:null},$e=t=>{const x=t.replace(/\D/g,"").slice(0,8);let _=x;x.length>=5?_=x.slice(0,2)+"/"+x.slice(2,4)+"/"+x.slice(4):x.length>=3&&(_=x.slice(0,2)+"/"+x.slice(2)),ae(_)},Pe=t=>{const x=t.replace(/\D/g,"").slice(0,8);let _=x;x.length>=5?_=x.slice(0,2)+"/"+x.slice(2,4)+"/"+x.slice(4):x.length>=3&&(_=x.slice(0,2)+"/"+x.slice(2)),V(_)},Me=t=>{const x=t.replace(/\D/g,"").slice(0,4);let _=x;x.length>=3&&(_=x.slice(0,2)+":"+x.slice(2)),T(_)},q=s&&d?String(P)+"-"+String(p+1).padStart(2,"0")+"-"+String(d.date).padStart(2,"0"):null,te=q?N(q):null,Ce=te?te.floating_pnl??te.effective_floating_pnl??null:null;o.useEffect(()=>{if(s&&d){const t=N(q);j((t==null?void 0:t.notes)||""),A((t==null?void 0:t.gwtdd_14day_avg)!==void 0&&t.gwtdd_14day_avg!==null?t.gwtdd_14day_avg.toString():""),M((t==null?void 0:t.image_path)||null),W((t==null?void 0:t.tags)||""),K(t!=null&&t.image_path?`/${t.image_path}`:null),O("Buy"),H(""),ae(""),T(""),he(""),m("idle"),t!=null&&t.gwtdd_14day_avg||ut(q),Ue(q),ft()}},[s,d,p,P]),o.useEffect(()=>{if(!s||!q)return;const t=15*60*1e3,x=setInterval(()=>Ue(q),t);return()=>clearInterval(x)},[s,q]);const ut=async t=>{try{const x=await fetch(`/api/journal/weather/gwtdd/${t}`);if(x.ok){const _=await x.json();_.gwtdd_14day_avg&&A(_.gwtdd_14day_avg.toString())}}catch(x){console.error("Error fetching GWTDD:",x)}},Ue=async t=>{try{const x=localStorage.getItem("blueflow_token"),_=await fetch("/api/journal/daily-enrichment?days=60",{headers:{Authorization:`Bearer ${x}`}});if(_.ok){const G=await _.json();G.success&&G.data[t]?ie(G.data[t]):ie(null)}}catch(x){console.error("Error fetching enrichment:",x)}},ft=async()=>{try{const t=localStorage.getItem("blueflow_token"),x=await fetch("/api/journal/tags",{headers:{Authorization:`Bearer ${t}`}});if(x.ok){const _=await x.json();_.success&&n(_.tags||[])}}catch(t){console.error("Tags fetch error:",t)}},Ve=t=>{const x=t.trim().toLowerCase();if(!x)return;const _=w?w.split(",").map(G=>G.trim()).filter(Boolean):[];if(!_.includes(x)){const G=[..._,x].join(", ");W(G),g(q,{tags:G})}U(""),a(!1)},bt=t=>{const _=w.split(",").map(G=>
26G.trim()).filter(Boolean).filter(G=>G!==t).join(", ");W(_),g(q,{tags:_})},Ke=se.filter(t=>{const x=w?w.split(",").map(_=>_.trim()):[];return t.toLowerCase().includes(Y.toLowerCase())&&!x.includes(t)});if(!s||!d)return null;const{date:yt,dailyPnL:Xe=0,trades:jt=[],tradeCount:Be=0,winRate:Nt=0}=d,Qe=Be>0,je=q?B(q):[],Ne=je.filter(t=>t.direction==="Buy").reduce((t,x)=>t+(x.amount||0),0),ve=je.filter(t=>t.direction==="Sell").reduce((t,x)=>t+(x.amount||0),0),et=Ne+ve,We=()=>{const t=et>0;return{open_contracts:t?et:null,open_contracts_long:t?Ne:null,open_contracts_short:t?ve:null}},tt=()=>{const t=parseFloat(le);if(!le||t<=0)return;const x=be(ee,oe);if(x===null){alert(`Can't read the open date "${ee}" -- use dd/mm/yyyy (e.g. 11/09/2026). Nothing was saved.`);return}let _=null;if(D.trim()!==""){if(_=be(D,ce||"23:59"),_===null){alert(`Can't read the close date "${D}" -- use dd/mm/yyyy. Nothing was saved.`);return}if(_<x){alert("Close date is before the open date. Nothing was saved.");return}}const G=ue.trim()!==""?parseFloat(ue):null;xe?(F(xe,{direction:C,amount:t,open_time:x,close_time:_,entry_price:G,note:J.trim()}),fe(null)):y({direction:C,amount:t,open_time:x,close_time:_,entry_price:G,note:J.trim()}),H(""),ge(""),ae(""),T(""),V(""),z(""),he("")},vt=t=>{if(fe(t.id),O(t.direction),H(String(t.amount)),ge(t.entry_price!=null?String(t.entry_price):""),t.open_time){const[x,_]=t.open_time.replace("T"," ").split(" "),[G,re,ne]=(x||"").split("-");ae(ne&&re&&G?`${ne}/${re}/${G}`:""),T((_||"").slice(0,5))}if(t.close_time){const[x,_]=t.close_time.replace("T"," ").split(" "),[G,re,ne]=(x||"").split("-");V(ne&&re&&G?`${ne}/${re}/${G}`:""),z((_||"").slice(0,5))}else V(""),z("");he(t.note||"")},Te=()=>{fe(null),O("Buy"),H(""),ge(""),ae(""),T(""),V(""),z(""),he("")},kt=t=>{const x=window.prompt("Close date (dd/mm/yyyy) -- leave blank for now:","");if(x===null)return;let _=null;if(x.trim()!==""&&(_=be(x,"23:59"),_===null)){alert(`Can't read the date "${x}" -- use dd/mm/yyyy. Nothing was changed.`);return}u(t,_),xe===t&&Te()},wt=async t=>{const x=window.prompt(`How many contracts did you close? (lot is ${t.amount.toLocaleString()})`,"");if(x===null)return;const _=parseFloat(String(x).replace(",","."));if(!(_>0)||_>=t.amount){alert(`Enter a number between 1 and ${t.amount-1}. To close the whole lot use Close. Nothing was changed.`);return}await E(t.id,_)||alert("Partial close failed -- nothing was changed."),xe===t.id&&Te()},_t=t=>{window.confirm("Permanently delete this position (as if it was never entered)? Use Close instead to keep it in history.")&&(u(t,null,!0),xe===t&&Te())},St=()=>{m("saving"),g(q,{notes:L,...We(),gwtdd_14day_avg:$!==""?parseFloat($):null,image_path:i,tags:w}),setTimeout(()=>{m("saved"),setTimeout(()=>{m("idle")},2e3)},300)},$t=()=>{g(q,{notes:L,...We(),gwtdd_14day_avg:$!==""?parseFloat($):null,image_path:i,tags:w}),m("saved"),setTimeout(()=>{m("idle")},2e3)},Pt=async t=>{var G;const x=(G=t.target.files)==null?void 0:G[0];if(!x)return;if(!["image/png","image/jpeg","image/jpg"].includes(x.type)){alert("Only PNG and JPG images are allowed");return}if(x.size>5*1024*1024){alert("Image size must be less than 5MB");return}X(!0);try{const re=new FormData;re.append("file",x);const ne=await fetch(`/api/journal/upload-image/${q}`,{method:"POST",headers:v(),body:re});if(ne.ok){const me=await ne.json();M(me.image_path),K(`/${me.image_path}`),m("saved"),setTimeout(()=>m("idle"),2e3)}else alert("Failed to upload image")}catch(re){console.error("Error uploading image:",re),alert("Error uploading image")}finally{X(!1)}},Mt=async()=>{if(i)try{await g(q,{notes:L,...We(),gwtdd_14day_avg:$!==""?parseFloat($):null,image_path:null}),M(null),K(null),m("saved"),setTimeout(()=>m("idle"),2e3)}catch(t){console.error("Error removing image:",t),alert("Error removing image")}};return e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/70 backdrop-blur-sm",children:[e.jsxs("div",{className:"bg-dark-800 rounded-lg border border-dark-700 w-full max-w-4xl max-h-[90vh] overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-6 py-4 border-b border-dark-700 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold text-dark-50 mb-2",children:Qt(yt,p,P)}),Qe?e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-dark-400 mb-1",children:"Daily P&L"}),e.jsxs("p",{className:`text-xl font-bold ${Xe>=0?"text-profit":"text-loss"}`,children:["Total P&L: $",Xe.toFixed(2)]}),e.jsx("p",{className:"text-xs text-dark-400 mb-1",children:"Trades"}),e.jsxs("p",{className:"text-sm text-gray-400",children:[Be," ",Be===1?"trade":"trades"]}),e.jsx("p",{className:"text-xs text-dark-400 mb-1",children:"Win Rate"}),e.jsxs("p",{className:"text-xl font-bold text-primary-500",children:[Nt.toFixed(0),"%"]})]}):e.jsx("p",{className:"text-sm text-dark-400 mt-1",children:"No trades for this date"})]}),e.jsx("button",{onClick:r,className:"text-gray-400 hover:text-white transition-colors",children:e.jsx("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-6 space-y-6",children:[Qe&&e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold text-dark-50 mb-3",children:"Trades"}),e.jsx("div",{className:"bg-dark-900 rounded-lg border border-dark-700 overflow-hidden",children:e.jsxs("table",{className:"w-full",children:[e.jsx("thead",{className:"bg-dark-800",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-4 py-3 text-left text-xs font-semibold text-gray-400 uppercase tracking-wider",children:"Time"}),e.jsx("th",{className:"px-4 py-3 text-left text-xs font-semibold text-gray-400 uppercase tracking-wider",children:"ID"}),e.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-dark-400 uppercase tracking-wider",children:"Symbol"}),e.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-dark-400 uppercase tracking-wider",children:"Direction"}),e.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-dark-400 uppercase tracking-wider",children:"Amount"}),e.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-dark-400 uppercase tracking-wider",children:"P&L"})]})}),e.jsx("tbody",{className:"divide-y divide-dark-700",children:jt.map(t=>{var x;return e.jsxs("tr",{className:"hover:bg-dark-750 transition-colors",children:[e.jsx("td",{className:"px-4 py-3 text-sm text-gray-400",children:(x=t.close_time)==null?void 0:x.toLocaleTimeString("hr-HR",{hour:"2-digit",minute:"2-digit"})}),e.jsx("td",{className:"px-4 py-3 text-sm font-mono text-gray-500",children:t.id}),e.jsx("td",{className:"px-4 py-3 text-sm text-dark-50 font-medium",children:t.symbol}),e.jsx("td",{className:"px-4 py-3 text-sm",children:e.jsx("span",{className:`px-2 py-1 rounded text-xs font-semibold ${t.direction==="Buy"?"bg-profit/20 text-profit":"bg-loss/20 text-loss"}`,children:t.direction})}),e.jsx("td",{className:"px-4 py-3 text-sm text-right text-gray-400",children:t.amount.toFixed(1)}),e.jsxs("td",{className:`px-4 py-3 text-sm font-semibold ${t.net_pnl>=0?"text-profit":"text-loss"}`,children:["$",t.net_pnl.toFixed(2)]})]},t.id)})})]})})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4 mb-6",children:e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-dark-50 mb-2",children:"EOD Floating P/L (€)"}),e.jsx("div",{className:"w-full px-4 py-3 bg-dark-900/60 border border-dark-700 rounded-lg tabular",children:Ce==null?e.jsx("span",{className:"text-dark-500",children:"—"}):e.jsxs("span",{className:Ce>=0?"text-profit":"text-loss",children:[Ce>=0?"+":"",Ce.toFixed(2)]})}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Automatic — from the Plus500 quote + P&L you enter in the POSITIONS card (Overview) and Capital.com's moves. Nothing to type here."})]})}),e.jsxs("div",{className:"mb-6",children:[e.jsxs("h3",{className:"text-sm font-semibold text-dark-50 mb-3",children:["Open Positions",je.length>0&&e.jsxs("span",{className:"ml-2 text-xs font-normal text-dark-400",children:["Long: ",Ne.toLocaleStr
26ing()," · Short: ",ve.toLocaleString(),Ne>0&&ve>0&&` · Hedged: ${Math.min(Ne,ve).toLocaleString()}`]})]}),je.length>0?e.jsx("div",{className:"space-y-2 mb-3",children:je.map(t=>e.jsxs("div",{className:`flex items-center gap-2 px-3 py-2 bg-dark-900 border rounded-lg ${xe===t.id?"border-primary-500/60 ring-1 ring-primary-500/40":"border-dark-700"}`,children:[e.jsx("span",{className:`text-xs font-bold px-2 py-0.5 rounded ${t.direction==="Buy"?"bg-green-500/20 text-green-400":"bg-red-500/20 text-red-400"}`,children:t.direction==="Buy"?"LONG":"SHORT"}),e.jsx("span",{className:"text-sm text-dark-50 font-medium",children:t.amount.toLocaleString()}),t.entry_price!=null&&e.jsxs("span",{className:"text-xs text-primary-300 font-mono",children:["@ ",t.entry_price]}),e.jsx("span",{className:"text-xs text-dark-400",children:t.open_time?(()=>{const x=t.open_time.replace("T"," "),[_,G]=x.split(" "),[re,ne,me]=(_||"").split("-");return(me||"")+"/"+(ne||"")+"/"+(re||"")+" "+(G||"").slice(0,5)})():""}),t.matched_trade&&e.jsxs("span",{className:"text-xs text-green-400",title:`Matched to Plus500 position ${t.matched_trade.id}`,children:["Plus500 #",t.matched_trade.id,t.matched_trade.net_pnl!=null?` · ${t.matched_trade.net_pnl>=0?"+":""}${t.matched_trade.net_pnl.toFixed(2)}`:""]}),!t.matched_trade&&t.close_time&&e.jsxs("span",{className:"text-xs text-amber-400",children:["closed ",(()=>{const[x]=t.close_time.split("T"),[_,G,re]=x.split("-");return re+"/"+G+"/"+_})()]}),t.note&&e.jsx("span",{className:"text-xs text-dark-400 italic flex-1 truncate",children:t.note}),e.jsx("button",{onClick:()=>vt(t),className:"text-dark-400 hover:text-primary-400 transition-colors text-xs ml-auto",title:"Edit position",children:"Edit"}),!t.close_time&&t.amount>1&&e.jsx("button",{onClick:()=>wt(t),className:"text-dark-400 hover:text-amber-400 transition-colors text-xs",title:"Partial close -- close part of this lot, the rest stays open",children:"Partial"}),!t.close_time&&e.jsx("button",{onClick:()=>kt(t.id),className:"text-dark-400 hover:text-amber-400 transition-colors text-xs",title:"Close position (keeps it in history until the close date)",children:"Close"}),e.jsx("button",{onClick:()=>_t(t.id),className:"text-dark-400 hover:text-red-400 transition-colors text-lg leading-none",title:"Delete position permanently (entered by mistake)",children:"×"})]},t.id))}):e.jsx("p",{className:"text-xs text-dark-500 mb-3",children:"No active positions for this date."}),e.jsxs("div",{className:"p-3 bg-dark-900/60 border border-dark-700 rounded-lg space-y-2",children:[xe&&e.jsxs("div",{className:"flex items-center justify-between text-xs text-primary-300 -mb-1",children:[e.jsxs("span",{children:["Editing position #",xe]}),e.jsx("button",{onClick:Te,className:"text-dark-400 hover:text-dark-100 underline",children:"Cancel"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{onClick:()=>O("Buy"),className:`flex-1 py-1.5 text-xs font-bold rounded transition-colors ${C==="Buy"?"bg-green-500/30 text-green-400 border border-green-500/50":"bg-dark-800 text-dark-400 border border-dark-700"}`,children:"LONG"}),e.jsx("button",{onClick:()=>O("Sell"),className:`flex-1 py-1.5 text-xs font-bold rounded transition-colors ${C==="Sell"?"bg-red-500/30 text-red-400 border border-red-500/50":"bg-dark-800 text-dark-400 border border-dark-700"}`,children:"SHORT"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{type:"number",min:"1",step:"1",value:le,onChange:t=>H(t.target.value),placeholder:"Amount (e.g. 2000)",className:"flex-1 px-3 py-2 bg-dark-900 border border-dark-700 rounded text-dark-50 text-sm placeholder-dark-400 focus:outline-none focus:ring-1 focus:ring-primary-500"}),e.jsx("input",{type:"number",step:"0.0001",value:ue,onChange:t=>ge(t.target.value),placeholder:"Price (optional)",className:"w-32 px-3 py-2 bg-dark-900 border border-dark-700 rounded text-dark-50 text-sm placeholder-dark-400 focus:outline-none focus:ring-1 focus:ring-primary-500"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{type:"text",value:ee,onChange:t=>$e(t.target.value),placeholder:"ddmmyyyy",maxLength:10,className:"w-28 px-3 py-2 bg-dark-900 border border-dark-700 rounded text-dark-50 text-sm placeholder-dark-400 focus:outline-none focus:ring-1 focus:ring-primary-500"}),e.jsx("input",{type:"text",value:oe,onChange:t=>Me(t.target.value),placeholder:"HH:MM",maxLength:5,className:"w-20 px-3 py-2 bg-dark-900 border border-dark-700 rounded text-dark-50 text-sm placeholder-dark-400 focus:outline-none focus:ring-1 focus:ring-primary-500"}),e.jsx("input",{type:"text",value:D,onChange:t=>Pe(t.target.value),placeholder:"Closed (opt.)",maxLength:10,title:"Close date, only for positions that are already closed",className:"w-28 px-3 py-2 bg-dark-900 border border-dark-700 rounded text-dark-50 text-sm placeholder-dark-400 focus:outline-none focus:ring-1 focus:ring-primary-500"}),e.jsx("input",{type:"text",value:J,onChange:t=>he(t.target.value),placeholder:"Note (optional)",onKeyDown:t=>t.key==="Enter"&&tt(),className:"flex-1 px-3 py-2 bg-dark-900 border border-dark-700 rounded text-dark-50 text-sm placeholder-dark-400 focus:outline-none focus:ring-1 focus:ring-primary-500"})]}),e.jsx("div",{className:"flex gap-2 justify-end",children:e.jsx("button",{onClick:tt,disabled:!le||parseFloat(le)<=0,className:"px-4 py-2 bg-primary-500 hover:bg-primary-600 disabled:opacity-40 text-white text-sm font-medium rounded transition-colors",children:xe?"Save changes":"+ Add"})})]})]}),e.jsxs("div",{className:"mb-6",children:[e.jsx("h3",{className:"text-sm font-semibold text-dark-50 mb-2",children:"Tags"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:w&&w.split(",").map(t=>
26t.trim()).filter(Boolean).map(t=>e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-semibold bg-primary-500/15 text-primary-400 border border-primary-500/30",children:["#",t,e.jsx("button",{onClick:()=>bt(t),className:"ml-0.5 hover:text-red-400 transition-colors",children:"×"})]},t))}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:"text",value:Y,onChange:t=>{U(t.target.value),a(!0)},onKeyDown:t=>{t.key==="Enter"&&Y.trim()&&(t.preventDefault(),Ve(Y))},onFocus:()=>a(!0),onBlur:()=>setTimeout(()=>a(!1),200),placeholder:"Add tag (press Enter to confirm)...",className:"w-full px-3 py-2 bg-dark-900 border border-dark-700 rounded-lg text-dark-50 text-sm placeholder-dark-400 focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent"}),l&&Ke.length>0&&Y.length>0&&e.jsx("div",{className:"absolute z-50 w-full mt-1 bg-dark-800 border border-dark-600 rounded-lg shadow-xl max-h-32 overflow-y-auto",children:Ke.slice(0,8).map(t=>e.jsxs("button",{onMouseDown:x=>{x.preventDefault(),Ve(t)},className:"w-full text-left px-3 py-1.5 text-xs text-gray-300 hover:bg-dark-700 hover:text-primary-400 transition-colors",children:["#",t]},t))})]})]}),R&&e.jsxs("div",{className:"mb-6 p-4 bg-dark-900/50 rounded-lg border border-dark-700",children:[e.jsx("h4",{className:"text-sm font-semibold text-gray-300 mb-3",children:"📊 Daily Market Data (auto)"}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[R.ng_price!=null&&e.jsxs("div",{className:"text-center px-2 py-2 rounded bg-dark-800/60 border border-dark-700",children:[e.jsx("p",{className:"text-[10px] text-gray-500 uppercase",children:"NG Price"}),e.jsxs("p",{className:"text-sm font-bold text-gray-200",children:["$",R.ng_price.toFixed(3)]})]}),R.ng_price_change_pct!=null&&e.jsxs("div",{className:`text-center px-2 py-2 rounded border ${R.ng_price_change_pct>0?"bg-green-500/10 border-green-500/30":R.ng_price_change_pct<0?"bg-red-500/10 border-red-500/30":"bg-dark-800/60 border-dark-700"}`,children:[e.jsx("p",{className:"text-[10px] text-gray-500 uppercase",children:"Δ Price"}),e.jsxs("p",{className:`text-sm font-bold ${R.ng_price_change_pct>0?"text-green-400":R.ng_price_change_pct<0?"text-red-400":"text-gray-400"}`,children:[R.ng_price_change_pct>0?"+":"",R.ng_price_change_pct.toFixed(1),"%"]})]}),R.gwtdd_tail_avg!=null&&e.jsxs("div",{className:"text-center px-2 py-2 rounded bg-dark-800/60 border border-dark-700",children:[e.jsx("p",{className:"text-[10px] text-gray-500 uppercase",children:"GWTDD Tail Avg"}),e.jsx("p",{className:"text-sm font-bold text-gray-200",children:R.gwtdd_tail_avg.toFixed(2)})]}),R.gwtdd_tail_delta!=null&&e.jsxs("div",{className:`text-center px-2 py-2 rounded border ${R.gwtdd_tail_delta>0?"bg-green-500/10 border-green-500/30":R.gwtdd_tail_delta<0?"bg-red-500/10 border-red-500/30":"bg-dark-800/60 border-dark-700"}`,children:[e.jsx("p",{className:"text-[10px] text-gray-500 uppercase",children:"Δ GWTDD Tail"}),e.jsxs("p",{className:`text-sm font-bold ${R.gwtdd_tail_delta>0?"text-green-400":R.gwtdd_tail_delta<0?"text-red-400":"text-gray-400"}`,children:[R.gwtdd_tail_delta>0?"+":"",R.gwtdd_tail_delta.toFixed(3)]})]})]}),R.ng_price_change!=null&&R.gwtdd_tail_delta!=null&&e.jsx("div",{className:`mt-3 px-3 py-1.5 rounded text-xs font-semibold text-center ${R.gwtdd_tail_delta>0&&R.ng_price_change>0||R.gwtdd_tail_delta<0&&R.ng_price_change<0?"bg-green-500/10 text-green-400 border border-green-500/30":"bg-orange-500/10 text-orange-400 border border-orange-500/30"}`,children:R.gwtdd_tail_delta>0&&R.ng_price_change>0||R.gwtdd_tail_delta<0&&R.ng_price_change<0?"✓ CORRELATION — GWTDD and price move in the same direction":"⚠ DIVERGENCE — price move is not weather-driven"})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold text-dark-50 mb-3",children:"Image Upload"}),e.jsx("div",{className:"space-y-4",children:I?e.jsxs("div",{className:"relative inline-block group",children:[e.jsx("img",{src:I,alt:"Journal entry",onClick:()=>
26Q(I),className:"max-w-full max-h-64 rounded-lg border border-dark-700 cursor-pointer hover:opacity-90 transition-opacity"}),e.jsx("button",{onClick:()=>Q(I),className:"absolute bottom-2 left-2 p-2 bg-dark-800/80 hover:bg-dark-700 rounded-lg text-white transition-colors opacity-0 group-hover:opacity-100",title:"View full size",children:e.jsx(mt,{className:"w-4 h-4"})}),e.jsx("button",{onClick:Mt,className:"absolute top-2 right-2 p-1 bg-red-500 hover:bg-red-600 rounded-full text-white transition-colors",title:"Remove image",children:e.jsx(ze,{className:"w-4 h-4"})})]}):e.jsxs("label",{className:"flex flex-col items-center justify-center w-full h-32 border-2 border-dashed border-dark-700 rounded-lg cursor-pointer hover:border-primary-500 transition-colors",children:[e.jsxs("div",{className:"flex flex-col items-center justify-center pt-5 pb-6",children:[e.jsx(Et,{className:"w-8 h-8 text-dark-400 mb-2"}),e.jsx("p",{className:"text-sm text-dark-400",children:Z?"Uploading...":"Click to upload image (PNG/JPG)"})]}),e.jsx("input",{type:"file",className:"hidden",accept:".png,.jpg,.jpeg",onChange:Pt,disabled:Z})]})})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold text-dark-50 mb-3",children:"Daily Notes"}),e.jsx("textarea",{value:L,onChange:t=>j(t.target.value),onBlur:$t,placeholder:"Add your notes, observations, or journal entries for this day...",className:"w-full px-4 py-3 bg-dark-900 border border-dark-700 rounded-lg text-dark-50 placeholder-dark-400 focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent resize-none h-32"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"All fields are automatically saved when you click outside them"})]})]}),e.jsxs("div",{className:"px-6 py-4 border-t border-dark-700 flex justify-end gap-3",children:[e.jsx("button",{onClick:r,className:"px-4 py-2 bg-primary-500 hover:bg-primary-600 text-white rounded-lg transition-colors font-medium",children:"Close"}),e.jsxs("button",{onClick:St,disabled:f==="saving",className:`px-4 py-2 rounded-lg transition-colors font-medium ${f==="saved"?"bg-green-600 text-white":f==="saving"?"bg-gray-600 text-gray-300 cursor-not-allowed":"bg-primary-600 hover:bg-primary-700 text-white"}`,children:[f==="saving"&&"Saving...",f==="saved"&&"Saved! ✓",f==="idle"&&"Save Notes"]})]})]}),k&&e.jsxs("div",{className:"fixed inset-0 z-[60] flex items-center justify-center p-4 bg-black/90 backdrop-blur-sm",onClick:()=>Q(null),children:[e.jsx("button",{onClick:()=>Q(null),className:"absolute top-4 right-4 p-2 bg-dark-800/80 hover:bg-dark-700 rounded-full text-white transition-colors",title:"Close",children:e.jsx(ze,{className:"w-6 h-6"})}),e.jsx("img",{src:k,alt:"Journal entry full size",className:"max-w-full max-h-full object-contain",onClick:t=>t.stopPropagation()})]})]})}function rs({reportsByDate:s,onOpenReport:r}){const{trades:d,journalEntries:p,cashFlow:P,specialDays:g}=Se(),[N,h]=o.useState(!1),[c,b]=o.useState("all"),[S,y]=o.useState("all"),[F,u]=o.useState(""),[E,B]=o.useState({}),[v,L]=o.useState(!1),[j,$]=o.useState(null),[A,f]=o.useState([]),[m,i]=o.useState(null),M=o.useMemo(()=>{const n={};return d.filter(l=>l.close_time).forEach(l=>{const a=new Date(l.close_time),C=`${a.getFullYear()}-${String(a.getMonth()+1).padStart(2,"0")}-${String(a.getDate()).padStart(2,"0")}`;n[C]||(n[C]={date:C,trades:[],pnl:0,wins:0,losses:0}),n[C].trades.push(l),n[C].pnl+=l.net_pnl||0,(l.net_pnl||0)>0?n[C].wins++:n[C].losses++}),Object.entries(p).forEach(([l,a])=>{n[l]||(n[l]={date:l,trades:[],pnl:0,wins:0,losses:0}),n[l].journal=a}),Object.keys(n).forEach(l=>{n[l].isStarred=(g==null?void 0:g[l])===!0}),Object.values(n).sort((l,a)=>a.date.localeCompare(l.date))},[d,p,g]),Z=o.useMemo(()=>{const n=[...M].sort((a,C)=>a.date.localeCompare(C.date));let l=0;return n.map(a=>(l+=a.pnl,{date:a.date,equity:l,pnl:a.pnl}))},[M]),X=o.useMemo(()=>{const n=new Set;return M.forEach(l=>{n.add(l.date.substring(0,7))}),[...n].sort().reverse()},[M]),I=o.useMemo(()=>{let n=M;if(N&&(n=n.filter(l=>l.isStarred)),c==="profit"?n=n.filter(l=>l.pnl>0):c==="loss"&&(n=n.filter(l=>l.pnl<0)),S!=="all"&&(n=n.filter(l=>l.date.startsWith(S))),F!==""){const l=parseFloat(F);isNaN(l)||(n=n.filter(a=>Math.abs(a.pnl)>=l))}return v&&(n=n.filter(l=>{var O;const a=((O=l.journal)==null?void 0:O.notes)&&l.journal.notes.trim().length>0,C=l.trades.length>0;return a||C})),j&&(n=n.filter(l=>{var C;return((C=l.journal)!=null&&C.tags?l.journal.tags.split(",").map(O=>O.trim()):[]).includes(j)})),n},[M,N,c,S,F,v,j]),K=o.useMemo(()=>{const n=[];let l=null;return I.forEach(a=>{const C=a.date.substring(0,7);if(C!==l){l=C;const O=M.filter(z=>z.date.startsWith(C)),le=O.reduce((z,J)=>z+J.pnl,0),H=O.reduce((z,J)=>z+J.trades.length,0),ee=O.reduce((z,J)=>z+J.wins,0);O.reduce((z,J)=>z+J.losses,0);const ae=H>0?ee/H*100:0,oe=O.filter(z=>z.trades.length>0).length,T=O.filter(z=>z.pnl>0).length,D=O.filter(z=>z.pnl<0).length,V=O.length>0?O.reduce((z,J)=>J.pnl>z.pnl?J:z,O[0]):null,ce=O.length>0?O.reduce((z,J)=>J.pnl<z.pnl?J:z,O[0]):null;n.push({type:"month-separator",monthKey:C,stats:{monthPnl:le,monthTrades:H,winRate:ae,tradingDays:oe,profitDays:T,lossDays:D,bestDay:V,worstDay:ce}})}n.push({type:"day",...a})}),n},[I,M]);o.useEffect(()=>{(async()=>{try{const l=localStorage.getItem("blueflow_token"),a=await fetch("/api/journal/tags",{headers:{Authorization:`Bearer ${l}`}});if(a.ok){const C=await a.json();C.success&&f(C.tags||[])}}catch{}})()},[]);const k=o.useMemo(()=>{const n=M.filter(H=>H.isStarred),l=M.filter(H=>!H.isStarred&&H.trades.length>0),a=n.length>0?n.reduce((H,ee)=>H+ee.pnl,0)/n.length:0,C=l.length>0?l.reduce((H,ee)=>H+ee.pnl,0)/l.length:0,O=n.length>0?n.filter(H=>H.pnl>0).length/n.length*100:0,le=l.length>0?l.filter(H=>H.pnl>0).length/l.length*100:0;return{starred:n.length,nonStarred:l.length,starredAvgPnl:a,nonStarredAvgPnl:C,starredWinRate:O,nonStarredWinRate:le}},[M]),Q=({data:n,width:l=120,height:a=32})=>
26{if(!n||n.length<2)return null;const C=n.map(T=>T.equity),O=Math.min(...C),H=Math.max(...C)-O||1,ee=C.map((T,D)=>{const V=D/(C.length-1)*l,ce=a-(T-O)/H*(a-4)-2;return`${V},${ce}`}).join(" "),ae=C[C.length-1],oe=ae>=0?"#34d399":"#f87171";return e.jsxs("svg",{width:l,height:a,className:"inline-block",children:[e.jsx("polyline",{fill:"none",stroke:oe,strokeWidth:"1.5",points:ee}),e.jsx("circle",{cx:l,cy:a-(ae-O)/H*(a-4)-2,r:"2",fill:oe})]})},R=({level:n})=>{if(n==null)return null;const l=["bg-green-500/20 text-green-400 border-green-500/30","bg-green-500/20 text-green-400 border-green-500/30","bg-yellow-500/20 text-yellow-400 border-yellow-500/30","bg-orange-500/20 text-orange-400 border-orange-500/30","bg-red-500/20 text-red-400 border-red-500/30","bg-red-700/20 text-red-300 border-red-700/30"],a=["Flat","Calm","Active","Loaded","Stretched","Danger"],C=Math.min(Math.max(n,0),5);return e.jsxs("span",{className:`text-[10px] font-bold px-1.5 py-0.5 rounded border ${l[C]}`,children:["Stress: ",a[C]]})},ie=n=>new Date(n+"T12:00:00").toLocaleDateString("en-US",{weekday:"long"}),w=n=>new Date(n+"T12:00:00").toLocaleDateString("hr-HR",{day:"2-digit",month:"long",year:"numeric"}),W=n=>{const[l,a]=n.split("-");return new Date(parseInt(l),parseInt(a)-1,1).toLocaleDateString("hr-HR",{month:"long",year:"numeric"})},Y=n=>{B(l=>({...l,[n]:!l[n]}))},U=n=>{const l=Z.find(a=>a.date===n);return(l==null?void 0:l.equity)??null},se=n=>{const l=Z.findIndex(a=>a.date===n);return l<1?null:Z.slice(Math.max(0,l-20),l+1)};return M.length===0?e.jsxs("div",{className:"bg-dark-800 rounded-lg border border-dark-700 p-12 text-center",children:[e.jsx(qe,{className:"w-16 h-16 text-gray-600 mx-auto mb-4"}),e.jsx("h3",{className:"text-xl font-bold text-white mb-2",children:"No Journal Entries Yet"}),e.jsx("p",{className:"text-gray-400",children:"Import trading data or add journal entries to see the blog view."})]}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"bg-gradient-to-r from-amber-900/15 via-dark-800 to-amber-900/15 rounded-lg border border-amber-700/20 p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(Ee,{className:"w-4 h-4 text-amber-400 fill-amber-400"}),e.jsx("span",{className:"text-sm font-bold text-amber-300",children:"Edge Tracker"}),e.jsx("span",{className:"text-[10px] text-gray-500 ml-1",children:"Compare days you starred vs the rest"})]}),k.starred>0?e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3",children:[e.jsxs("div",{className:"bg-dark-900/60 rounded-lg p-3 border border-amber-700/20 text-center",children:[e.jsx("div",{className:"text-[10px] text-gray-500 mb-1",children:"Edge days"}),e.jsx("div",{className:"text-xl font-bold text-amber-400",children:k.starred}),e.jsxs("div",{className:"text-[10px] text-gray-600",children:["of ",k.starred+k.nonStarred]})]}),e.jsxs("div",{className:"bg-dark-900/60 rounded-lg p-3 border border-dark-600 text-center",children:[e.jsx("div",{className:"text-[10px] text-gray-500 mb-1",children:"Avg P&L with edge"}),e.jsxs("div",{className:`text-xl font-bold ${k.starredAvgPnl>=0?"text-green-400":"text-red-400"}`,children:[k.starredAvgPnl>=0?"+":"",k.starredAvgPnl.toFixed(1)]})]}),e.jsxs("div",{className:"bg-dark-900/60 rounded-lg p-3 border border-dark-600 text-center",children:[e.jsx("div",{className:"text-[10px] text-gray-500 mb-1",children:"Avg P&L without edge"}),e.jsxs("div",{className:`text-xl font-bold ${k.nonStarredAvgPnl>=0?"text-green-400":"text-red-400"}`,children:[k.nonStarredAvgPnl>=0?"+":"",k.nonStarredAvgPnl.toFixed(1)]})]}),e.jsxs("div",{className:"bg-dark-900/60 rounded-lg p-3 border border-dark-600 text-center",children:[e.jsx("div",{className:"text-[10px] text-gray-500 mb-1",children:"Win Rate"}),e.jsxs("div",{className:"flex items-center justify-center gap-2",children:[e.jsxs("span",{className:"text-amber-400 font-bold",children:[k.starredWinRate.toFixed(0),"%"]}),e.jsx("span",{className:"text-gray-600",children:"vs"}),e.jsxs("span",{className:"text-gray-400 font-bold",children:[k.nonStarredWinRate.toFixed(0),"%"]})]}),e.jsx("div",{className:"text-[10px] text-gray-600",children:"edge vs normal"})]})]}):e.jsx("div",{className:"text-xs text-gray-500 text-center py-2",children:"Star days on the calendar to see a performance comparison."})]}),A.length>0&&e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-4",children:[e.jsx("span",{className:"text-xs text-gray-500 font-semibold",children:"Tags:"}),e.jsx("button",{onClick:()=>$(null),className:`px-2.5 py-1 rounded-full text-[10px] font-semibold border transition-all ${j?"border-dark-600 text-gray-500 hover:text-gray-300":"bg-primary-500/15 border-primary-500/40 text-primary-400"}`,children:"All"}),A.map(n=>e.jsxs("button",{onClick:()=>$(j===n?null:n),className:`px-2.5 py-1 rounded-full text-[10px] font-semibold border transition-all ${j===n?"bg-primary-500/15 border-primary-500/40 text-primary-400":"border-dark-600 text-gray-500 hover:text-gray-300"}`,children:["#",n]},n))]}),e.jsxs("div",{className:"bg-dark-800 rounded-lg border border-dark-700 p-3 flex items-center gap-3 flex-wrap",children:[e.jsx(Gt,{className:"w-4 h-4 text-gray-500"}),e.jsxs("button",{onClick:()=>h(!N),title:"Show only starred days (edge days)",className:`px-3 py-1.5 rounded-md text-xs font-semibold transition-colors ${N?"bg-amber-500/20 text-amber-300 border border-amber-500/50":"bg-dark-700 text-gray-400 border border-dark-600 hover:text-white"}`,children:[e.jsx(Ee,{className:`w-3 h-3 inline mr-1 ${N?"fill-amber-400":""}`})," Edge Only"]}),e.jsx("div",{className:"flex rounded-md border border-dark-600 overflow-hidden",children:["all","profit","loss"].map(n=>e.jsx("button",{onClick:()=>b(n),className:`px-3 py-1.5 text-xs font-semibold transition-colors ${c===n?n==="profit"?"bg-green-500/20 text-green-400":n==="loss"?"bg-red-500/20 text-red-400":"bg-dark-600 text-white":"bg-dark-700 text-gray-500 hover:text-gray-300"}`,children:n==="all"?"All":n==="profit"?"↑ Profit":"↓ Loss"},n))}),e.jsxs("select",{value:S,onChange:n=>y(n.target.value),className:"px-3 py-1.5 rounded-md text-xs bg-dark-700 border border-dark-600 text-gray-300 focus:outline-none focus:border-primary-500",children:[e.jsx("option",{value:"all",children:"All Months"}),X.map(n=>e.jsx("option",{value:n,children:W(n)},n))]}),e.jsx("input",{type:"number",placeholder:"Min |P&L|",value:F,onChange:n=>u(n.target.value),className:"w-24 px-2 py-1.5 rounded-md text-xs bg-dark-700 border border-dark-600 text-gray-300 focus:outline-none focus:border-primary-500"}),e.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[e.jsx("button",{onClick:()=>L(!v),title:v?"Compact view: only days with entries":"Expanded view: all days",className:`px-3 py-1.5 rounded-md text-xs font-semibold transition-colors ${v?"bg-primary-500/20 text-primary-300 border border-primary-500/50":"bg-dark-700 text-gray-400 border border-dark-600"}`,children:v?"Compact (entries only)":"All Days"}),e.jsxs("span",{className:"text-xs text-gray-600",children:[I.length," entries"]})]})]}),e.jsx("div",{className:"space-y-3",children:K.map((n,l)=>{var V,ce,z,J,he,ue,ge,xe,fe,be,$e,Pe,Me;if(n.type==="month-separator"){const{monthKey:q,stats:te}=n;return e.jsxs("div",{className:"bg-gradient-to-r from-dark-800 via-dark-750 to-dark-800 rounded-lg border border-dark-600 p-5",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("h3",{className:"text-lg font-bold text-white capitalize",children:W(q)}),e.jsxs("div",{className:`text-2xl font-bold ${te.monthPnl>=0?"text-green-400":"text-red-400"}`,children:[te.monthPnl>=0?"+":"","€",te.monthPnl.toFixed(2)]})]}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 lg:grid-cols-6 gap-3 text-xs",children:[e.jsxs("div",{className:"bg-dark-900/50 rounded p-2 text-center",children:[e.jsx("div",{className:"text-gray-500 mb-1",children:"Trades"}),e.jsx("div",{className:"text-white font-bold",children:te.monthTrades})]}),e.jsxs("div",{className:"bg-dark-900/50 rounded p-2 text-center",children:[e.jsx("div",{className:"text-gray-500 mb-1",children:"Win Rate"}),e.jsxs("div",{className:"text-white font-bold",children:[te.winRate.toFixed(0),"%"]})]}),e.jsxs("div",{className:"bg-dark-900/50 rounded p-2 text-center",children:[e.jsx("div",{className:"text-gray-500 mb-1",children:"Trading Days"}),e.jsx("div",{className:"text-white font-bold",children:te.tradingDays})]}),e.jsxs("div",{className:"bg-dark-900/50 rounded p-2 text-center",children:[e.jsx("div",{className:"text-gray-500 mb-1",children:"Profit/Loss Days"}),e.jsxs("div",{className:"font-bold",children:[e.jsx("span",{className:"text-green-400",children:te.profitDays}),e.jsx("span",{className:"text-gray-600",children:" / "}),e.jsx("span",{className:"text-red-400",children:te.lossDays})]})]}),e.jsxs("div",{className:"bg-dark-900/50 rounded p-2 text-center",children:[e.jsx("div",{className:"text-gray-500 mb-1",children:"Best Day"}),e.jsxs("div",{className:"text-green-400 font-bold",children:["+€",((ce=(V=te.bestDay)==null?void 0:V.pnl)==null?void 0:ce.toFixed(1))||"0"]})]}),e.jsxs("div",{className:"bg-dark-900/50 rounded p-2 text-center",children:[e.jsx("div",{className:"text-gray-500 mb-1",children:"Worst Day"}),e.jsxs("div",{className:"text-red-400 font-bold",children:["€",((J=(z=te.worstDay)==null?void 0:z.pnl)==null?void 0:J.toFixed(1))||"0"]})]})]})]},`month-${q}`)}const a=n,C=((he=a.journal)==null?void 0:he.notes)&&a.journal.notes.trim().length>0,O=(ue=a.journal)==null?void 0:ue.image_path,le=(ge=a.journal)==null?void 0:ge.stress_level,H=E[a.date]??!v,ee=se(a.date),ae=U(a.date),oe=a.trades.length>0?a.wins/a.trades.length*100:null,T=(xe=a.journal)==null?void 0:xe.gwtdd_14day_avg,D=(s==null?void 0:s[a.date])||[];return e.jsxs("div",{className:`rounded-lg border transition-all ${a.isStarred?"bg-dark-800 border-amber-500/40 shadow-[0_0_8px_rgba(245,158,11,0.1)]":a.pnl>0?"bg-dark-800 border-l-4 border-l-green-500 border-t-dark-700 border-r-dark-700 border-b-dark-700":a.pnl<0?"bg-dark-800 border-l-4 border-l-red-500 border-t-dark-700 border-r-dark-700 border-b-dark-700":"bg-dark-800 border-dark-700"}`,children:[e.jsxs("div",{className:"p-4 flex items-center justify-between cursor-pointer hover:bg-dark-750/50 transition-colors",onClick:()=>Y(a.date),children:[e.jsxs("div",{className:"flex items-center gap-3",children:[a.isStarred&&e.jsx(Ee,{className:"w-4 h-4 text-amber-400 fill-amber-400 flex-shrink-0"}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-bold text-white",children:ie(a.date)}),e.jsx("span",{className:"text-xs text-gray-500",children:w(a.date)})]}),v&&C&&e.jsxs("p",{className:"text-xs text-gray-500 mt-0.5 truncate max-w-md",children:[a.journal.notes.substring(0,80),a.journal.notes.length>80?"...":""]})]})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[ee&&e.jsx(Q,{data:ee,width:80,height:24}),e.jsxs("div",{className:`text-right min-w-[80px] ${a.pnl>0?"text-green-400":a.pnl<0?"text-red-400":"text-gray-500"}`,children:[e.jsxs("div",{className:"text-lg font-bold",children:[a.pnl>=0?"+":"","€",a.pnl.toFixed(2)]}),a.trades.length>0&&e.jsxs("div",{className:"text-[10px] text-gray-500",children:[a.trades.length," trades • ",oe==null?void 0:oe.toFixed(0),"% WR"]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(R,{level:le}),T&&e.jsxs("span",{className:"text-[10px] font-semibold px-1.5 py-0.5 rounded bg-sky-500/15 text-sky-300 border border-sky-500/30",children:["GWTDD: ",Number(T).toFixed(1)]}),D.length>0&&e.jsxs("button",{onClick:q=>{q.stopPropagation(),r==null||r(D[D.length-1].id)},className:"flex items-center gap-0.5 text-[10px] font-semibold px-1.5 py-0.5 rounded bg-purple-500/15 text-purple-300 border border-purple-500/30 hover:bg-purple-500/25",title:`${D.length} global report${D.length>
261?"s":""} — click to open latest`,children:[e.jsx(we,{className:"w-3 h-3"}),D.length>1&&D.length]})]}),(C||O||a.trades.length>0)&&e.jsx("div",{className:"text-gray-600",children:H?e.jsx(ct,{className:"w-4 h-4"}):e.jsx(xt,{className:"w-4 h-4"})})]})]}),H&&e.jsxs("div",{className:"px-4 pb-4 border-t border-dark-700 pt-3 space-y-3",children:[((fe=a.journal)==null?void 0:fe.tags)&&e.jsx("div",{className:"flex flex-wrap gap-1.5 mb-1",children:a.journal.tags.split(",").map(q=>q.trim()).filter(Boolean).map(q=>e.jsxs("span",{onClick:te=>{te.stopPropagation(),$(q)},className:"px-2 py-0.5 rounded-full text-[10px] font-semibold bg-primary-500/10 text-primary-400 border border-primary-500/20 cursor-pointer hover:bg-primary-500/20 transition-colors",children:["#",q]},q))}),C&&e.jsxs("div",{className:"bg-dark-900/50 rounded-lg p-3 border border-dark-700",children:[e.jsx("div",{className:"text-xs text-gray-500 font-semibold mb-1.5",children:"Journal Notes"}),e.jsx("p",{className:"text-sm text-gray-200 whitespace-pre-wrap leading-relaxed",children:a.journal.notes})]}),O&&e.jsxs("div",{className:"relative inline-block",children:[e.jsx("img",{src:`/${a.journal.image_path}`,alt:"Journal screenshot",className:"max-h-48 rounded-lg border border-dark-600 cursor-pointer hover:opacity-90 transition-opacity",onClick:()=>i(`/${a.journal.image_path}`)}),e.jsx("button",{onClick:()=>i(`/${a.journal.image_path}`),className:"absolute top-2 right-2 p-1 bg-dark-900/80 rounded text-gray-300 hover:text-white",children:e.jsx(mt,{className:"w-4 h-4"})})]}),a.trades.length>0&&e.jsxs("div",{children:[e.jsxs("div",{className:"text-xs text-gray-500 font-semibold mb-2",children:["Trades (",a.trades.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-2",children:[a.trades.slice(0,6).map((q,te)=>e.jsxs("div",{className:"bg-dark-900/50 rounded p-2 border border-dark-700 text-xs flex justify-between items-center",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-300 font-medium",children:q.instrument||q.symbol||"Trade"}),q.amount&&e.jsxs("span",{className:"text-gray-600 ml-1",children:["x",q.amount]})]}),e.jsxs("span",{className:`font-bold ${(q.net_pnl||0)>=0?"text-green-400":"text-red-400"}`,children:[(q.net_pnl||0)>=0?"+":"","€",(q.net_pnl||0).toFixed(2)]})]},te)),a.trades.length>6&&e.jsxs("div",{className:"text-xs text-gray-600 p-2",children:["+",a.trades.length-6," more trades..."]})]})]}),(((be=a.journal)==null?void 0:be.effective_floating_pnl)!=null||(($e=a.journal)==null?void 0:$e.open_contracts)!=null)&&e.jsxs("div",{className:"flex gap-3 text-xs",children:[((Pe=a.journal)==null?void 0:Pe.effective_floating_pnl)!=null&&e.jsxs("span",{className:`px-2 py-1 rounded bg-dark-900/50 border border-dark-700 ${a.journal.effective_floating_pnl>=0?"text-green-400":"text-red-400"}`,children:["Floating: ",a.journal.effective_floating_pnl>=0?"+":"","€",a.journal.effective_floating_pnl.toFixed(2)]}),((Me=a.journal)==null?void 0:Me.open_contracts)!=null&&e.jsxs("span",{className:"px-2 py-1 rounded bg-dark-900/50 border border-dark-700 text-gray-300",children:["Open: ",a.journal.open_contracts," contracts"]})]}),ae!=null&&e.jsxs("div",{className:"text-[10px] text-gray-600",children:["Running equity: ",e.jsxs("span",{className:ae>=0?"text-green-500":"text-red-500",children:["€",ae.toFixed(2)]})]})]})]},a.date)})}),m&&e.jsxs("div",{className:"fixed inset-0 z-50 bg-black/90 flex items-center justify-center p-4",onClick:()=>i(null),children:[e.jsx("button",{onClick:()=>i(null),className:"absolute top-4 right-4 p-2 bg-dark-800 rounded-full text-white hover:bg-dark-700",children:e.jsx(ze,{className:"w-6 h-6"})}),e.jsx("img",{src:m,alt:"Full size",className:"max-w-full max-h-full rounded-lg"})]})]})}const as=20,ns=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function Ge(s,r,d=as){if(s==null||r==null||!(r>s))return[];const p=(r-s)/d;return Array.from({length:d},(P,g)=>({lo:s+g*p,hi:s+(g+1)*p}))}function Je(s,r){return s==null||r.length===0?-1:s<r[0].lo?0:s>=r[r.length-1].hi?r.length-1:r.findIndex(d=>s>=d.lo&&s<d.hi)}function Re(s){return{counts:new Array(s).fill(0),pnlSums:new Array(s).fill(0),total:0,netPnl:0}}function ht(s,r,d,p){const P=new Map,g=Re(r.length);
26return(s||[]).forEach(N=>{if(!N.close_time)return;const h=new Date(N.close_time);if(!d(h))return;const c=p(h);if(c==null)return;P.has(c)||P.set(c,Re(r.length));const b=P.get(c),S=N.net_pnl||0;let y=!1;[N.open_rate,N.close_rate].forEach(F=>{const u=Je(F,r);u!==-1&&(y=!0,b.counts[u]++,b.pnlSums[u]+=S,b.total++,g.counts[u]++,g.pnlSums[u]+=S,g.total++)}),y&&(b.netPnl+=S,g.netPnl+=S)}),{groups:P,overall:g}}function pt(s,r){const d=s.counts.filter(p=>p>0).length;return{touchedBuckets:d,bucketCount:r,coveragePct:r>0?Math.round(d/r*100):null}}function ls(s,r,d){const{groups:p,overall:P}=ht(s,d,N=>N.getFullYear()===r,N=>N.getMonth());return{rows:ns.map((N,h)=>({key:h,label:N,...p.get(h)||Re(d.length)})),total:P,...pt(P,d.length)}}function os(s,r,d){const p=new Set(r),{groups:P,overall:g}=ht(s,d,h=>p.has(h.getFullYear()),h=>h.getFullYear());return{rows:[...r].sort((h,c)=>h-c).map(h=>({key:h,label:String(h),...P.get(h)||Re(d.length)})),total:g,...pt(g,d.length)}}function lt(s){const r=parseInt(s.slice(1),16);return[r>>16&255,r>>8&255,r&255]}function Ye(s,r,d){const[p,P,g]=lt(s),[N,h,c]=lt(r),b=Math.round(p+(N-p)*d),S=Math.round(P+(h-P)*d),y=Math.round(g+(c-g)*d);return`rgb(${b}, ${S}, ${y})`}const Ze="#1A1F2E",Ie="#525A73",ds="#3A76D8",is="#ff7961",cs="#4db6ac",xs="#ff7961";function ms(s,r){if(!s||s<=0||!r||r<=0)return Ze;const d=Math.min(1,s/r);return Ye(ds,is,d)}function hs(s,r,d){if(!d||d<=0)return Ze;if(!r||r<=0||s===0)return Ie;const p=Math.min(1,Math.abs(s)/r)**.6;return s>0?Ye(Ie,cs,p):Ye(Ie,xs,p)}const ps=.02,gs=4,us=12;function gt(s,r,d,p){if(d.length===0||!r||r.length===0||!(p>0))return null;const P=new Array(d.length).fill(0);r.forEach(y=>{const F=Je(y,d);F!==-1&&P[F]++});const g=new Array(d.length).fill(0);(s||[]).forEach(y=>{if(!y.close_time)return;const F=(y.net_pnl||0)/2;[y.open_rate,y.close_rate].forEach(u=>{const E=Je(u,d);E!==-1&&(g[E]+=F)})});let N=0,h=0,c=null,b=null;d.forEach((y,F)=>{const u=P[F];if(u===0)return;const B=g[F]/p*100/u-ps;if(B>0){const v=B*u;N+=v,(!c||v>c.bonus)&&(c={...y,days:u,pnl:g[F],bonus:v})}else{const v=-B*u;h+=v,(!b||v>b.penalty)&&(b={...y,days:u,pnl:g[F],penalty:v})}});const S=Math.max(0,Math.min(100,50+Math.sqrt(N)*gs-Math.sqrt(h)*us));return{score:Math.round(S),bonusTotal:N,penaltyTotal:h,bestZone:c,worstZone:b}}function fs(s){const{getAuthHeader:r}=Le(),d=o.useRef(r);d.current=r;const[p,P]=o.useState([]),[g,N]=o.useState([]),[h,c]=o.useState(!0),[b,S]=o.useState(null),y=o.useMemo(()=>{const u=new Set;return(s||[]).forEach(E=>{E.close_time&&u.add(new Date(E.close_time).getFullYear())}),Array.from(u).sort((E,B)=>B-E)},[s]);o.useEffect(()=>{if(!s||s.length===0)return;let u=!1;async function E(){var A,f;c(!0);const B=new Date().getFullYear(),v=Math.min(...y),L=Math.max(5,B-v+1),[j,$]=await Promise.all([rt(`/api/market/yearly-price-range?years_back=${L}`,{headers:d.current()}),rt(`/api/market/price-history?start_date=${v}-01-01`,{headers:d.current()})]);u||(j.ok&&((A=j.data)!=null&&A.success)?P(j.data.years||[]):S("Failed to fetch yearly price ranges"),$.ok&&((f=$.data)!=null&&f.success)?N($.data.prices||[]):S(m=>m||"Failed to fetch daily price history"),c(!1))}return E(),()=>{u=!0}},[y.join(",")]);const F=o.useMemo(()=>{const u=new Map;return g.forEach(E=>{const B=new Date(E.date),v=`${B.getFullYear()}-${B.getMonth()}`;u.has(v)||u.set(v,[]),u.get(v).push(E.price)}),u},[g]);return{yearRanges:p,dailyPricesByYearMonth:F,tradeYears:y,loading:h,error:b}}const pe="ALL",ot=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function bs({trades:s,yearRanges:r,dailyPricesByYearMonth:d,tradeYears:p,investedAtStartByMonth:P,loading:g,error:N}){const[h,c]=o.useState(null),[b,S]=o.useState("count"),[y,F]=o.useState(null);o.useEffect(()=>{h==null&&p.length>0&&c(p[0])},[p,h]);const u=o.useMemo(()=>{const m=r.filter(i=>p.includes(i.year));return m.length===0?null:{min:Math.min(...m.map(i=>i.min)),max:Math.max(...m.map(i=>i.max))}},[r,p]),E=o.useMemo(()=>typeof h=="number"?r.find(m=>m.year===h):null,[r,h]),B=h===pe?u:E,v=o.useMemo(()=>B?Ge(B.min,B.max):[],[B]),L=o.useMemo(()=>v.length===0?null:h===pe?os(s,p,v):typeof h=="number"?ls(s,h,v):null,[s,h,p,v]),j=o.useMemo(()=>L?L.rows.filter(m=>m.total>0):[],[L]),$=h===pe?"All-Time Total":"Year Total",A=o.useMemo(()=>
26{if(b!=="pnl"||!L)return null;let m=null,i=null;return L.total.pnlSums.forEach((M,Z)=>{L.total.counts[Z]!==0&&((!m||M>m.sum)&&(m={sum:M,...v[Z]}),(!i||M<i.sum)&&(i={sum:M,...v[Z]}))}),m&&i?{best:m,worst:i}:null},[b,L,v]),f=o.useMemo(()=>{const m=[];p.forEach(I=>{const K=r.find(Q=>Q.year===I);if(!K)return;const k=Ge(K.min,K.max);for(let Q=0;Q<12;Q++){const R=P.get(`${I}-${Q+1}`),ie=d.get(`${I}-${Q}`),w=gt(s,ie,k,R);w&&m.push({year:I,month:Q,...w})}});const i=h===pe?m:m.filter(I=>I.year===h);if(i.length===0)return null;const M=Math.round(i.reduce((I,K)=>I+K.score,0)/i.length),Z=i.filter(I=>I.bestZone).sort((I,K)=>K.bestZone.bonus-I.bestZone.bonus)[0],X=i.filter(I=>I.worstZone).sort((I,K)=>K.worstZone.penalty-I.worstZone.penalty)[0];return{avgScore:M,best:Z,worst:X,monthCount:i.length}},[s,p,r,d,P,h]);return g?e.jsx("div",{className:"bg-dark-800 rounded-lg border border-dark-700 p-6",children:e.jsx("div",{className:"h-24 flex items-center justify-center text-dark-400 text-sm",children:"Loading price ranges…"})}):N?e.jsx("div",{className:"bg-dark-800 rounded-lg border border-dark-700 p-6",children:e.jsx("p",{className:"text-loss text-sm text-center",children:N})}):p.length===0||!B||!L?null:e.jsxs("div",{className:"bg-dark-800 rounded-lg border border-dark-700 p-4",children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-2 mb-1",children:[e.jsxs("h3",{className:"text-sm font-bold text-gray-300 flex items-center gap-2",children:[e.jsx(Ct,{className:"w-4 h-4 text-primary-400"}),"Price Range Heatmap"]}),e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsx("div",{className:"flex items-center gap-1 bg-dark-900/60 rounded-lg p-0.5 border border-dark-700",children:[{id:"count",label:"Trades"},{id:"pnl",label:"P/L"}].map(m=>e.jsx("button",{onClick:()=>S(m.id),className:`text-xs font-semibold px-2.5 py-1 rounded-md transition-colors ${b===m.id?"bg-primary-500/20 text-primary-300":"text-dark-400 hover:text-dark-200"}`,children:m.label},m.id))}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[p.map(m=>e.jsx("button",{onClick:()=>c(m),className:`text-xs font-semibold px-2.5 py-1 rounded-lg border transition-colors ${h===m?"bg-primary-500/20 border-primary-500/50 text-primary-300":"border-dark-600 text-dark-400 hover:border-dark-500"}`,children:m},m)),e.jsx("button",{onClick:()=>c(pe),className:`text-xs font-semibold px-2.5 py-1 rounded-lg border transition-colors ${h===pe?"bg-primary-500/20 border-primary-500/50 text-primary-300":"border-dark-600 text-dark-400 hover:border-dark-500"}`,children:"All Time"})]})]})]}),e.jsx("p",{className:"text-[11px] text-dark-500 mb-3",children:b==="count"?"Each row = trade density (entries + exits) across the real market range · redder = more trades that price zone, dark = fewer or none":"Each row = net P/L attributed to entries + exits in that price zone · teal = profit, red = loss, dark = never traded"}),e.jsx("div",{className:"flex items-start gap-2 bg-dark-900/60 border border-dark-700 rounded-lg px-3 py-2 mb-2",children:e.jsxs("p",{className:"text-xs text-dark-300",children:["Touched ",e.jsxs("span",{className:"font-mono font-bold text-primary-300",children:[L.touchedBuckets," of ",L.bucketCount]})," price zones ",h===pe?"across all traded years":`in ${h}`," (",e.jsxs("span",{className:"font-mono font-bold text-primary-300",children:[L.coveragePct,"%"]}),") — market ranged ",e.jsxs("span",{className:"font-mono",children:["$",B.min.toFixed(2),"–$",B.max.toFixed(2)]}),"."]})}),A&&e.jsx("div",{className:"flex items-start gap-2 bg-dark-900/60 border border-dark-700 rounded-lg px-3 py-2 mb-4",children:e.jsxs("p",{className:"text-xs text-dark-300",children:["Most profitable zone ",e.jsxs("span",{className:"font-mono",children:["$",A.best.lo.toFixed(2),"–$",A.best.hi.toFixed(2)]})," (",e.jsxs("span",{className:"font-mono font-bold text-profit",children:["+€",A.best.sum.toFixed(2)]}),")"," ","· least ",e.jsxs("span",{className:"font-mono",children:["$",A.worst.lo.toFixed(2),"–$",A.worst.hi.toFixed(2)]})," (",e.jsxs("span",{className:`font-mono font-bold ${A.worst.sum>=0?"text-profit":"text-loss"}`,children:[A.worst.sum>=0?"+":"","€",A.worst.sum.toFixed(2)]}),")"]})}),!A&&e.jsx("div",{className:"mb-4"}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("div",{className:"min-w-[600px]",children:[e.jsx(dt,{label:$,row:L.total,buckets:v,mode:b,emphasized:!0,onHoverCell:F}),e.jsx("div",{className:"h-2"}),j.map(m=>e.jsx(dt,{label:m.label,row:m,buckets:v,mode:b,onHoverCell:F},m.key)),e.jsx("div",{className:"flex mt-1 pl-[76px]",children:v.map((m,i)=>i===0||i===Math.floor(v.length/2)||i===v.length-1?e.jsxs("div",{className:"flex-1 text-[9px] text-dark-500 text-center",style:{minWidth:0},children:["$",m.lo.toFixed(2)]},i):e.jsx("div",{className:"flex-1"},i))})]})}),y&&e.jsxs("div",{className:"mt-2 text-xs text-dark-300 bg-dark-900/60 border border-dark-700 rounded-lg px-3 py-1.5 inline-block",children:[e.jsx("span",{className:"font-semibold text-white",children:y.rowLabel})," ",e.jsxs("span",{className:"font-mono",children:["$",y.lo.toFixed(3),"–$",y.hi.toFixed(3)]})," ",b==="count"?e.jsxs(e.Fragment,{children:["· ",e.jsx("span",{className:"font-mono font-bold text-primary-300",children:y.count}
26)," ",y.count===1?"endpoint":"endpoints"," (entries+exits)"]}):e.jsxs(e.Fragment,{children:["· ",e.jsxs("span",{className:`font-mono font-bold ${y.pnl>=0?"text-profit":"text-loss"}`,children:[y.pnl>=0?"+":"","€",y.pnl.toFixed(2)]})," across ",e.jsx("span",{className:"font-mono font-bold text-primary-300",children:y.count})," endpoints"]})]}),f&&e.jsxs("div",{className:"mt-4 pt-4 border-t border-dark-700",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(we,{className:"w-4 h-4 text-primary-400"}),e.jsx("h4",{className:"text-sm font-bold text-gray-300",children:"Range Capture Score"}),e.jsxs("span",{className:`font-mono font-bold text-sm ${f.avgScore>=60?"text-profit":f.avgScore<=40?"text-loss":"text-dark-200"}`,children:[f.avgScore,"/100"]})]}),e.jsxs("p",{className:"text-[11px] text-dark-500 mb-2",children:["Did trading actually monetize the time price spent in each zone, ",h===pe?`averaged across ${f.monthCount} months`:`averaged across ${f.monthCount} months of ${h}`," — a zone price flew through quickly and was captured scores higher than a zone price sat range-bound in for weeks with little P/L."]}),e.jsxs("div",{className:"space-y-1.5",children:[f.best&&e.jsxs("p",{className:"text-xs text-dark-300",children:[e.jsx("span",{className:"text-profit font-semibold",children:"Best capture:"})," ",ot[f.best.month]," ",f.best.year," — price passed through"," ",e.jsxs("span",{className:"font-mono",children:["$",f.best.bestZone.lo.toFixed(2),"–$",f.best.bestZone.hi.toFixed(2)]})," in just ",f.best.bestZone.days," ",f.best.bestZone.days===1?"day":"days",", captured"," ",e.jsxs("span",{className:"font-mono font-bold text-profit",children:[f.best.bestZone.pnl>=0?"+":"","€",f.best.bestZone.pnl.toFixed(2)]}),"."]}),f.worst&&e.jsxs("p",{className:"text-xs text-dark-300",children:[e.jsx("span",{className:"text-loss font-semibold",children:"Left on the table:"})," ",ot[f.worst.month]," ",f.worst.year," — price sat in"," ",e.jsxs("span",{className:"font-mono",children:["$",f.worst.worstZone.lo.toFixed(2),"–$",f.worst.worstZone.hi.toFixed(2)]})," for"," ",f.worst.worstZone.days," days, only"," ",e.jsxs("span",{className:`font-mono font-bold ${f.worst.worstZone.pnl>=0?"text-profit":"text-loss"}`,children:[f.worst.worstZone.pnl>=0?"+":"","€",f.worst.worstZone.pnl.toFixed(2)]})," captured."]})]})]})]})}function dt({label:s,row:r,buckets:d,mode:p,emphasized:P=!1,onHoverCell:g}){const N=Math.max(...r.counts,0),h=Math.max(...r.pnlSums.map(b=>Math.abs(b)),0),c=p==="count"?r.total:`${r.netPnl>=0?"+":""}€${r.netPnl.toFixed(0)}`;return e.jsxs("div",{className:`flex items-center gap-0.5 py-0.5 ${P?"bg-dark-900/40 rounded":""}`,children:[e.jsx("div",{className:`w-[70px] shrink-0 text-[11px] pr-1.5 text-right ${P?"text-white font-bold":"text-dark-400"}`,children:s}),e.jsx("div",{className:"flex flex-1 gap-[1px]",children:d.map((b,S)=>{const y=r.counts[S],F=r.pnlSums[S],u=p==="count"?ms(y,N):hs(F,h,y);return e.jsx("div",{className:"flex-1 rounded-sm cursor-default transition-transform hover:scale-y-125",style:{height:P?20:14,backgroundColor:u},onMouseEnter:()=>g({rowLabel:s,lo:b.lo,hi:b.hi,count:y,pnl:F}),onMouseLeave:()=>g(null)},S)})}),e.jsx("div",{className:`w-14 shrink-0 text-[10px] text-right pl-1 ${p==="pnl"?r.netPnl>=0?"text-profit":"text-loss":"text-dark-500"}`,children:c})]})}const ys=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],js=["January","February","March","April","May","June","July","August","September","October","November","December"];function Ns(s){return s==="best"?{band:"bg-emerald-500/15 border-emerald-500/40",txt:"text-emerald-300",tier:"Best"}:{band:"bg-red-500/15 border-red-500/40",txt:"text-red-300",tier:"Worst"}}function vs({monthlyData:s}){const r=s.length;if(r<2)return null;const d=[...s].sort((c,b)=>{const S=c.equityReturnPct??-1/0;return(b.equityReturnPct??-1/0)-S}),p=Math.min(3,Math.ceil(r/2)),P=Math.min(3,r-p),g=d.slice(0,p),N=d.slice(r-P).reverse(),h=[...g.map((c,b)=>({...c,kind:"best",rank:b+1})),...N.map((c,b)=>({...c,kind:"worst",rank:b+1}))];return e.jsxs("div",{className:"bg-dark-800 rounded-lg border border-dark-700 p-4",children:[e.jsxs("h3",{className:"text-sm font-bold text-gray-300 mb-1 flex items-center gap-2",children:[e.jsx(Zt,{className:"w-4 h-4 text-primary-400"}),"Best & Worst Months by Equity Return"]}),e.jsx("p",{className:"text-[11px] text-dark-500 mb-3",children:"Ranked purely by monthly Time-Weighted Return (deposits and withdrawals never distort it) — it already nets out every effect on the account, so nothing else can override the ranking. Score is a separate execution-quality diagnostic (drawdown, Sharpe, avg P&L/trade — see badge tooltip below), shown alongside but not used to rank."}),e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-dark-400 border-b border-dark-700",children:[e.jsx("th",{className:"text-left py-2 pl-2 font-semibold",children:"Tier"}),e.jsx("th",{className:"text-center py-2 font-semibold",children:"Rank"}),e.jsx("th",{className:"text-left py-2 font-semibold",children:"Month"}),e.jsx("th",{className:"text-right py-2 font-semibold",children:"Eq. Return"}),e.jsx("th",{className:"text-right py-2 font-semibold",children:"Score"}),e.jsx("th",{className:"text-right py-2 pr-2 font-semibold",children:"Drawdown"})]})}),e.jsx("tbody",{children:h.map((c,b)=>{const S=Ns(c.kind),y=c.kind==="worst"&&b===g.length;return e.jsxs("tr",{className:`border ${S.band} ${y?"border-t-4":""}`,children:[e.jsx("td",{className:`py-2.5 pl-2 font-bold ${S.txt}`,children:S.tier}),e.jsxs("td",{className:"py-2.5 text-center text-dark-100 font-mono text-lg",children:[c.rank,"."]}
26),e.jsx("td",{className:"py-2.5 text-left text-white font-semibold",children:c.label}),e.jsx("td",{className:`py-2.5 text-right font-bold font-mono text-lg ${c.equityReturnPct==null?"text-dark-500":c.equityReturnPct>=0?"text-green-400":"text-red-400"}`,children:c.equityReturnPct==null?"—":`${c.equityReturnPct>=0?"+":""}${c.equityReturnPct.toFixed(1)}%`}),e.jsxs("td",{className:`py-2.5 text-right font-mono ${ke(c.score).color}`,children:[c.score," ",e.jsx("span",{className:"text-xs opacity-70",children:ke(c.score).grade})]}),e.jsxs("td",{className:"py-2.5 pr-2 text-right font-mono text-dark-200",children:[c.drawdownPct.toFixed(1),"%"]})]},`${c.kind}-${c.year}-${c.month}`)})})]})]})}function ks({onOpenReport:s}){const{trades:r,cashFlow:d,journalEntries:p}=Se(),{liveFloatingPnl:P}=Tt(),{getAuthHeader:g}=Le(),[N,h]=o.useState(null),[c,b]=o.useState({}),[S,y]=o.useState({}),F=fs(r);o.useEffect(()=>{(async()=>{try{const $=await fetch("/api/ai-assistant/monthly-reports",{headers:g()});if($.ok){const A=await $.json();if(A.success){const f={};A.reports.forEach(m=>{f[m.period]=m}),y(f)}}}catch($){console.error("Failed to fetch monthly AI reports:",$)}})()},[g]),o.useEffect(()=>{(async()=>{try{const $=await fetch("/api/journal/monthly-comments",{headers:g()});if($.ok){const A=await $.json();if(A.success){const f={};A.comments.forEach(m=>{f[`${m.year}-${m.month}`]=m.comment}),b(f)}}}catch($){console.error("Failed to fetch monthly comments:",$)}})()},[g]);const u=o.useCallback(async(j,$,A)=>{const f=await fetch("/api/journal/monthly-comments",{method:"POST",headers:{"Content-Type":"application/json",...g()},body:JSON.stringify({year:j,month:$,comment:A})});if(!f.ok){const m=await f.text().catch(()=>f.status);throw new Error(`HTTP ${f.status}: ${m}`)}b(m=>({...m,[`${j}-${$}`]:A}))},[g]),E=o.useMemo(()=>{if(!r||r.length===0)return[];const j=r.filter(i=>i.close_time),$={};j.forEach(i=>{const M=new Date(i.close_time),Z=`${M.getFullYear()}-${M.getMonth()+1}`;$[Z]||($[Z]={year:M.getFullYear(),month:M.getMonth()+1,trades:[],netPnl:0,costs:0,wins:0,losses:0,winPnl:0,lossPnl:0,totalDuration:0});const X=$[Z];X.trades.push(i);const I=i.net_pnl||0,K=i.gross_pnl||I;X.netPnl+=I,X.costs+=Math.abs(K-I),I>0?(X.wins++,X.winPnl+=I):I<0&&(X.losses++,X.lossPnl+=I),i.duration_minutes!=null&&(X.totalDuration+=i.duration_minutes)});const A=at(r,d,p,P),{yearRanges:f,dailyPricesByYearMonth:m}=F;return Object.values($).map(i=>{const M=i.wins+i.losses,Z=i.trades.filter(l=>l.duration_minutes!=null).length,X=Z>0?Math.round(i.totalDuration/Z):null,I=M>0?Math.round(i.wins/M*1e3)/10:0,K=i.lossPnl<0?i.winPnl/Math.abs(i.lossPnl):i.winPnl>0?3:0,k=M>0?Math.round(i.netPnl/M*100)/100:0,Q=`${i.year}-${i.month}`,R=A[Q]||{equityReturnPct:null,drawdownPct:0,sharpe:null,investedAtStart:0},ie=M>0&&R.investedAtStart>0?k/R.investedAtStart*100:null,w=f.find(l=>l.year===i.year),W=w?Ge(w.min,w.max):[],Y=m.get(`${i.year}-${i.month-1}`),U=gt(r,Y,W,R.investedAtStart),{score:se,breakdown:n}=At({drawdownPct:R.drawdownPct,sharpe:R.sharpe,avgPnlPerTradePct:ie,rangeCaptureScore:(U==null?void 0:U.score)??null});return{...i,totalTrades:M,winRate:I,avgPerTrade:k,avgDurationMinutes:X,profitFactor:K,avgPnlPerTradePct:ie,equityReturnPct:R.equityReturnPct,dietzPct:R.dietzPct??null,drawdownPct:R.drawdownPct,sharpe:R.sharpe,score:se,scoreBreakdown:n,label:`${js[i.month-1]} ${i.year}`,shortLabel:`${ys[i.month-1]} '${String(i.year).slice(2)}`}}).sort((i,M)=>i.year!==M.year?i.year-M.year:i.month-M.month)},[r,d,p,F,P]),B=o.useMemo(()=>Math.max(...E.map(j=>Math.abs(j.netPnl)),1),[E]),v=o.useMemo(()=>Math.max(...E.map(j=>j.totalTrades),1),[E]),L=o.useMemo(()=>{const j=at(r,d,p,P),$=new Map;return Object.entries(j).forEach(([A,f])=>$.set(A,f.investedAtStart)),$},[r,d,p,P]);return!r||r.length===0?e.jsxs("div",{className:"bg-dark-800 rounded-lg border border-dark-700 p-12 text-center",children:[e.jsx(Ae,{className:"w-12 h-12 text-gray-600 mx-auto mb-3"}),e.jsx("h3",{className:"text-lg font-bold text-dark-50 mb-1",children:"No Data Available"}),e.jsx("p",{className:"text-sm text-dark-400",children:"Import trading data to view the monthly breakdown"})]}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"bg-dark-800 rounded-lg border border-dark-700 p-4",children:[e.jsxs("h3",{className:"text-sm font-bold text-gray-300 mb-3 flex items-center gap-2",children:[e.jsx(Ae,{className:"w-4 h-4 text-primary-400"}),"Monthly Net P&L"]}),e.jsx("div",{className:"flex items-end gap-1.5",style:{height:"120px"},children:E.map((j,$)=>{const A=Math.abs(j.netPnl)/B*100,f=Math.max(A,5),m=j.netPnl>=0,i=`${j.year}-${j.month}`,M=N===i;return e.jsxs("div",{className:"flex-1 flex flex-col items-center justify-end h-full cursor-pointer group",onClick:()=>h(M?null:i),children:[e.jsxs("div",{className:"relative w-full flex flex-col items-center justify-end h-full",children:[e.jsxs("div",{className:"absolute -top-5 hidden group-hover:block text-[9px] font-bold whitespace-nowrap z-10",style:{color:m?"#4ade80":"#f87171"},children:[m?"+":"",j.netPnl.toFixed(0),"€"]}),e.jsx("div",{className:`w-full rounded-sm transition-all ${M?"ring-2 ring-primary-400":""} ${m?"bg-green-500/80 hover:bg-green-400":"bg-red-500/80 hover:bg-red-400"}`,style:{height:`${f}%`,minHeight:"3px"}})]}),e.jsx("span",{className:`text-[9px] mt-1 ${M?"text-primary-300 font-bold":"text-gray-600"}`,children:j.shortLabel})]},$)})})]}),e.jsx(bs,{trades:r,yearRanges:F.yearRanges,dailyPricesByYearMonth:F.dailyPricesByYearMonth,tradeYears:F.tradeYears,investedAtStartByMonth:L,loading:F.loading,error:F.error}),e.jsx(vs,{monthlyData:E}),e.jsx("div",{className:"bg-dark-800 rounded-lg border border-dark-700 overflow-x-auto",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-dark-900/60 border-b border-dark-700",children:[e.jsx("th",{className:"text-left px-3 py-2 text-gray-500 font-semibold",children:"Month"}),e.jsx("th",{className:"text-center px-2 py-2 text-gray-500 font-semibold",children:"Score"}),e.jsx("th",{className:"text-center px-2 py-2 text-gray-500 font-semibold",children:"Positions"}),e.jsx("th",{className:"text-center px-2 py-2 text-gray-500 font-semibold",children:"Win Rate"}),e.jsx("th",{className:"text-right px-2 py-2 text-gray-500 font-semibold",children:"Eq. Return"}),e.jsx("th",{className:"text-right px-2 py-2 text-gray-500 font-semibold",children:"Drawdown"}),e.jsx("th",{className:"text-right px-2 py-2 text-gray-500 font-semibold",children:"Net P&L"}),e.jsx("th",{className:"text-right px-2 py-2 text-gray-500 font-semibold",children:"Avg/Trade"}),e.jsx("th",{className:"text-right px-3 py-2 text-gray-500 font-semibold",children:"Costs"}),e.jsx("th",{className:"text-center px-2 py-2 text-gray-500 font-semibold w-6"})]})}),e.jsx("tbody",{children:[...E].reverse().map(j=>{const $=`${j.year}-${j.month}`,A=N===$,f=j.netPnl>=0,m=c[$]||"";return e.jsx(_s,{m:j,mKey:$,isExpanded:A,pos:f,comment:m,maxTrades:v,onToggle:()=>h(A?null:$),onSaveComment:i=>u(j.year,j.month,i),aiReport:S[`${j.year}-${String(j.month).padStart(2,"0")}`],onOpenReport:s},$)})})]})})]})}function ws(s){if(s==null)return"—";if(s<60)return`${s}m`;const r=Math.floor(s/60),d=s%60;return d>0?`${r}h ${d}m`:`${r}h`}function _s({m:s,mKey:r,isExpanded:d,pos:p,comment:P,maxTrades:g,onToggle:N,onSaveComment:h,aiReport:c,onOpenReport:b}
26){const[S,y]=o.useState(P),[F,u]=o.useState(!1),[E,B]=o.useState(null);o.useEffect(()=>{y(P)},[P]);const v=S!==P,L=async i=>{if(i.stopPropagation(),!(!v||F)){u(!0),B(null);try{await h(S),B("ok"),setTimeout(()=>B(null),2e3)}catch{B("error")}finally{u(!1)}}},j=Math.min(s.winRate,100),$=s.totalTrades/g*100,{grade:A,color:f,bg:m}=ke(s.score);return e.jsxs(e.Fragment,{children:[e.jsxs("tr",{className:`border-b border-dark-700/50 cursor-pointer transition-colors ${d?"bg-dark-750/50":"hover:bg-dark-750/30"}`,onClick:N,children:[e.jsx("td",{className:"px-3 py-2.5",children:e.jsxs("div",{className:"flex items-center gap-2",children:[P&&e.jsx(He,{className:"w-3 h-3 text-primary-400 flex-shrink-0"}),c&&e.jsx(we,{className:"w-3 h-3 text-purple-400 flex-shrink-0"}),e.jsx("span",{className:"font-semibold text-white text-xs",children:s.label})]})}),e.jsx("td",{className:"px-2 py-2.5 text-center",children:e.jsxs("span",{title:"Execution-quality score (does not rank months — Eq. Return alone does that, see the Best/Worst table): 45% drawdown (real NLV incl. floating P&L), 35% Sharpe, 20% avg P&L/trade. Win rate and profit factor are excluded — not meaningful for a hedged book.",className:`inline-flex items-center gap-1 px-1.5 py-0.5 rounded-md border font-mono font-bold ${m} ${f}`,children:[s.score,e.jsx("span",{className:"opacity-70 text-[9px]",children:A})]})}),e.jsx("td",{className:"px-2 py-2.5 text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1.5",children:[e.jsx("div",{className:"w-12 h-1.5 bg-dark-700 rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-primary-400/60 rounded-full",style:{width:`${$}%`}})}),e.jsx("span",{className:"text-gray-300 font-mono",children:s.totalTrades})]})}),e.jsx("td",{className:"px-2 py-2.5 text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1.5",children:[e.jsx("div",{className:"w-12 h-1.5 bg-dark-700 rounded-full overflow-hidden",children:e.jsx("div",{className:`h-full rounded-full ${s.winRate>=50?"bg-green-500/70":"bg-red-500/70"}`,style:{width:`${j}%`}})}),e.jsxs("span",{className:`font-mono font-bold ${s.winRate>=50?"text-green-400":"text-red-400"}`,children:[s.winRate,"%"]})]})}),e.jsxs("td",{className:`px-2 py-2.5 text-right font-mono ${s.equityReturnPct==null?"text-gray-600":s.equityReturnPct>=0?"text-green-400":"text-red-400"}`,children:[s.equityReturnPct==null?"—":`${s.equityReturnPct>=0?"+":""}${s.equityReturnPct.toFixed(1)}%`,s.dietzPct!=null&&e.jsxs("div",{className:"text-[10px] text-dark-500",title:"Modified Dietz — money-weighted return on average capital",children:["Dietz ",s.dietzPct>=0?"+":"",s.dietzPct.toFixed(1),"%"]})]}),e.jsxs("td",{className:`px-2 py-2.5 text-right font-mono ${s.drawdownPct<0?"text-red-400":"text-gray-500"}`,children:[s.drawdownPct.toFixed(1),"%"]}),e.jsxs("td",{className:`px-2 py-2.5 text-right font-mono font-bold ${p?"text-green-400":"text-red-400"}`,children:[p?"+":"","€",s.netPnl.toFixed(2)]}),e.jsxs("td",{className:`px-2 py-2.5 text-right font-mono ${s.avgPerTrade>=0?"text-green-400/80":"text-red-400/80"}`,children:[s.avgPerTrade>=0?"+":"","€",s.avgPerTrade.toFixed(2)]}),e.jsxs("td",{className:"px-3 py-2.5 text-right font-mono text-orange-400/80",children:["€",s.costs.toFixed(2)]}),e.jsx("td",{className:"px-2 py-2.5 text-center",children:d?e.jsx(ct,{className:"w-3.5 h-3.5 text-gray-500 inline"}):e.jsx(xt,{className:"w-3.5 h-3.5 text-gray-500 inline"})})]}),d&&e.jsx("tr",{className:"bg-dark-850/30",children:e.jsx("td",{colSpan:10,className:"px-4 py-3",onClick:i=>i.stopPropagation(),children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center flex-wrap gap-x-4 gap-y-1 text-[11px] text-gray-400",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Dt,{className:"w-3 h-3 text-green-400"})," ",s.wins,"W"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(it,{className:"w-3 h-3 text-red-400"})," ",s.losses,"L"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(nt,{className:"w-3 h-3 text-primary-400"})," ",s.totalTrades," trades"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ae,{className:"w-3 h-3 text-blue-400"})," avg ",ws(s.avgDurationMinutes)]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Rt,{className:"w-3 h-3 text-orange-400"})," €",s.costs.toFixed(2)," costs"]}),e.jsxs("span",{className:`flex items-center gap-1 ${s.avgPnlPerTradePct==null?"":s.avgPnlPerTradePct>=0?"text-green-400":"text-red-400"}`,children:[e.jsx(Bt,{className:"w-3 h-3 text-cyan-400"})," Avg/Trade ",s.avgPnlPerTradePct==null?"—":`${s.avgPnlPerTradePct>=0?"+":""}${s.avgPnlPerTradePct.toFixed(2)}%`]}),e.jsxs("span",{className:`flex items-center gap-1 ${s.equityReturnPct==null?"":s.equityReturnPct>=0?"text-green-400":"text-red-400"}`,children:[e.jsx(Wt,{className:"w-3 h-3"})," Eq. Return ",s.equityReturnPct==null?"—":`${s.equityReturnPct>=0?"+":""}${s.equityReturnPct.toFixed(1)}%`]}),e.jsxs("span",{className:`flex items-center gap-1 ${s.drawdownPct<0?"text-red-400":""}`,children:[e.jsx(Ot,{className:"w-3 h-3"})," Drawdown ",s.drawdownPct.toFixed(1),"% ",e.jsx("span",{className:"text-dark-600",children:"(incl. floating)"})]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(nt,{className:"w-3 h-3 text-indigo-400"})," Sharpe ",s.sharpe==null?"—":s.sharpe.toFixed(2)]})]}),e.jsxs("div",{className:"flex items-center flex-wrap gap-x-3 gap-y-1 text-[10px] text-gray-500 bg-dark-900/50 rounded-md px-2.5 py-1.5 border border-dark-700/50",children:[e.jsxs("span",{className:`font-mono font-bold text-xs ${ke(s.score).color}`,children:["Score ",s.score,"/100 (",ke(s.score).grade,")"]}),e.jsx("span",{className:"text-dark-600",children:"|"}),e.jsxs("span",{children:["Drawdown ",Math.round(s.scoreBreakdown.drawdownScore)]}),e.jsxs("span",{children:["Sharpe ",Math.round(s.scoreBreakdown.sharpeScore)]}),e.jsxs("span",{children:["Avg/Trade ",Math.round(s.scoreBreakdown.avgPnlScore)]}),e.jsxs("span",{children:["Range Capture ",Math.round(s.scoreBreakdown.rangeScore)]}),e.jsx("span",{className:"text-dark-600 italic",children:"win rate, profit factor & equity return not part of this score"})]}),c&&e.jsxs("button",{onClick:()=>
26b==null?void 0:b(c.id),className:"flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1.5 rounded-lg bg-purple-500/10 text-purple-300 border border-purple-500/30 hover:bg-purple-500/20 transition-colors",children:[e.jsx(we,{className:"w-3.5 h-3.5"}),"Monthly AI Report"]}),e.jsxs("div",{className:"border-t border-dark-700/50 pt-2",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[e.jsxs("span",{className:"text-[10px] text-gray-500 uppercase tracking-wider flex items-center gap-1",children:[e.jsx(He,{className:"w-3 h-3"})," Monthly Review"]}),E==="ok"&&e.jsx("span",{className:"text-[10px] text-green-400",children:"Saved ✓"}),E==="error"&&e.jsx("span",{className:"text-[10px] text-red-400",children:"Failed to save"})]}),e.jsx("textarea",{value:S,onChange:i=>y(i.target.value),placeholder:"Key takeaways of the month, strategy changes...",className:"w-full bg-dark-900/80 text-gray-200 text-xs rounded-md p-2.5 border border-dark-600 focus:border-primary-500 outline-none resize-y min-h-[60px]",rows:3,onClick:i=>i.stopPropagation()}),v&&e.jsx("div",{className:"flex justify-end mt-1.5",children:e.jsx("button",{onClick:L,disabled:F,className:"px-3 py-1 text-[10px] text-white rounded bg-primary-500 hover:bg-primary-600 disabled:opacity-50",children:F?"Saving...":"Save"})})]})]})})})]})}class Ss extends o.Component{constructor(r){super(r),this.state={hasError:!1,error:null}}static getDerivedStateFromError(r){return{hasError:!0,error:r}}render(){var r;return this.state.hasError?e.jsxs("div",{className:"bg-red-900/20 border border-red-500/30 rounded-lg p-6 text-center",children:[e.jsx("p",{className:"text-red-400 font-semibold mb-2",children:"Blog View encountered an error"}),e.jsx("p",{className:"text-xs text-gray-500 mb-3",children:((r=this.state.error)==null?void 0:r.message)||"Unknown error"}),e.jsx("button",{onClick:()=>this.setState({hasError:!1,error:null}),className:"px-4 py-2 bg-dark-700 text-white rounded-lg text-sm hover:bg-dark-600",children:"Try Again"})]}):this.props.children}}function Hs(){const{trades:s,selectedDate:r,isModalOpen:d,openDayDetails:p,closeDayDetails:P}=Se(),g=new Date,[N,h]=o.useState(g.getMonth()),[c,b]=o.useState(g.getFullYear());o.useEffect(()=>{if(!r)return;const[w,W]=r.split("-").map(Number);b(w),h(W-1)},[r]);const[S,y]=o.useState("calendar"),[F,u]=o.useState({}),[E,B]=o.useState({}),[v,L]=o.useState(null),[j,$]=o.useState(null);o.useEffect(()=>{(async()=>{try{const W=localStorage.getItem("blueflow_token"),Y=await fetch("/api/journal/daily-enrichment?days=60",{headers:{Authorization:`Bearer ${W}`}});if(Y.ok){const U=await Y.json();U.success&&u(U.data||{})}}catch(W){console.error("Enrichment fetch failed:",W)}})()},[]),o.useEffect(()=>{(async()=>{try{const W=localStorage.getItem("blueflow_token"),[Y,U,se,n]=await Promise.all([fetch("/api/ai-assistant/global-reports",{headers:{Authorization:`Bearer ${W}`}}),fetch("/api/ai-assistant/daily-reports",{headers:{Authorization:`Bearer ${W}`}}),fetch("/api/ai-assistant/market-close-reports",{headers:{Authorization:`Bearer ${W}`}}),fetch("/api/ai-assistant/week-ahead-reports",{headers:{Authorization:`Bearer ${W}`}})]),l={};for(const a of[Y,U,se,n]){if(!a.ok)continue;const C=await a.json();if(C.success)for(const O of C.reports||[])l[O.report_date]||(l[O.report_date]=[]),l[O.report_date].push(O)}B(l)}catch(W){console.error("Reports fetch failed:",W)}})()},[]);const A=async w=>{try{const W=localStorage.getItem("blueflow_token"),Y=await fetch(`/api/ai-assistant/global-reports/${w}`,{headers:{Authorization:`Bearer ${W}`}});if(Y.ok){const U=await Y.json();U.success&&L(U.report)}}catch(W){console.error("Report fetch failed:",W)}},f=Vt(s,N,c),m=s.filter(w=>w.close_time?w.close_time.getMonth()===N&&w.close_time.getFullYear()===c:!1).reduce((w,W)=>w+(W.net_pnl||0),0),i=()=>{N===0?(h(11),b(c-1)):h(N-1)},M=()=>{N===11?(h(0),b(c+1)):h(N+1)},Z=()=>{h(g.getMonth()),b(g.getFullYear())},X=(w,W)=>{const Y=`${c}-${String(N+1).padStart(2,"0")}-${String(w).padStart(2,"0")}`;p(Y)},I=()=>{P()},k=(()=>{if(s.length===0)return null;const w=s.filter(T=>T.close_time!==null),W=w.reduce((T,D)=>D.net_pnl>T.net_pnl?D:T,w[0]),Y=w.reduce((T,D)=>D.net_pnl<T.net_pnl?D:T,w[0]),U={};
26w.forEach(T=>{const D=new Date(T.close_time),V=D.getFullYear(),ce=String(D.getMonth()+1).padStart(2,"0"),z=String(D.getDate()).padStart(2,"0"),J=`${V}-${ce}-${z}`;U[J]||(U[J]={date:J,pnl:0,trades:[]}),U[J].pnl+=T.net_pnl,U[J].trades.push(T)});const se=Object.values(U),n=se.reduce((T,D)=>D.pnl>T.pnl?D:T,se[0]),l=se.reduce((T,D)=>D.pnl<T.pnl?D:T,se[0]),a={};w.forEach(T=>{const D=new Date(T.close_time),V=D.getDay(),ce=V===0?6:V-1,z=new Date(D);z.setDate(D.getDate()-ce),z.setHours(0,0,0,0);const J=`${z.getFullYear()}-${String(z.getMonth()+1).padStart(2,"0")}-${String(z.getDate()).padStart(2,"0")}`;a[J]||(a[J]={week:J,pnl:0,trades:[]}),a[J].pnl+=T.net_pnl,a[J].trades.push(T)});const C=Object.values(a),O=C.reduce((T,D)=>D.pnl>T.pnl?D:T,C[0]),le=C.reduce((T,D)=>D.pnl<T.pnl?D:T,C[0]),H={};w.forEach(T=>{const D=new Date(T.close_time),V=`${D.getFullYear()}-${String(D.getMonth()+1).padStart(2,"0")}`;H[V]||(H[V]={month:V,pnl:0,trades:[]}),H[V].pnl+=T.net_pnl,H[V].trades.push(T)});const ee=Object.values(H),ae=ee.reduce((T,D)=>D.pnl>T.pnl?D:T,ee[0]),oe=ee.reduce((T,D)=>D.pnl<T.pnl?D:T,ee[0]);return{bestTrade:W,worstTrade:Y,bestDay:n,worstDay:l,bestWeek:O,worstWeek:le,bestMonth:ae,worstMonth:oe}})(),Q=w=>new Date(w).toLocaleDateString("en-GB",{day:"2-digit",month:"2-digit",year:"numeric"}),R=w=>{const W=new Date(w),Y=new Date(W);return Y.setDate(W.getDate()+6),`${W.toLocaleDateString("en-GB",{day:"2-digit",month:"2-digit"})} - ${Y.toLocaleDateString("en-GB",{day:"2-digit",month:"2-digit",year:"numeric"})}`},ie=w=>{const[W,Y]=w.split("-");return new Date(W,parseInt(Y)-1).toLocaleDateString("en-GB",{month:"long",year:"numeric"})};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-1 bg-dark-800 rounded-lg p-1 border border-dark-700 w-fit",children:[e.jsxs("button",{onClick:()=>y("calendar"),className:`flex items-center gap-2 px-4 py-2 rounded-md text-sm font-semibold transition-all ${S==="calendar"?"bg-primary-500/20 text-primary-300 border border-primary-500/50":"text-gray-400 hover:text-white hover:bg-dark-700"}`,children:[e.jsx(qe,{className:"w-4 h-4"}),"Calendar"]}),e.jsxs("button",{onClick:()=>y("blog"),className:`flex items-center gap-2 px-4 py-2 rounded-md text-sm font-semibold transition-all ${S==="blog"?"bg-primary-500/20 text-primary-300 border border-primary-500/50":"text-gray-400 hover:text-white hover:bg-dark-700"}`,children:[e.jsx(Ft,{className:"w-4 h-4"}),"Blog View"]}),e.jsxs("button",{onClick:()=>y("monthly"),className:`flex items-center gap-2 px-4 py-2 rounded-md text-sm font-semibold transition-all ${S==="monthly"?"bg-primary-500/20 text-primary-300 border border-primary-500/50":"text-gray-400 hover:text-white hover:bg-dark-700"}`,children:[e.jsx(Ae,{className:"w-4 h-4"}),"Monthly"]})]}),S==="blog"&&e.jsx(Ss,{children:e.jsx(rs,{reportsByDate:E,onOpenReport:A})}),S==="monthly"&&e.jsx(ks,{onOpenReport:A}),S==="calendar"&&e.jsxs(e.Fragment,{children:[s.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"bg-dark-800 rounded-lg border border-dark-700 p-6",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("h3",{className:"text-xl font-bold text-dark-50",children:[Kt(N)," ",c]}),e.jsxs("span",{className:`text-lg font-bold ${m>=0?"text-green-400":"text-red-400"}`,children:[m>=0?"+":"","€",m.toFixed(2)]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{onClick:i,className:"px-4 py-2 bg-dark-700 hover:bg-dark-600 text-gray-300 rounded-lg transition-colors flex items-center gap-2",children:[e.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})}),"Previous"]}),e.jsx("button",{onClick:Z,className:"px-4 py-2 bg-primary-600 hover:bg-primary-700 text-white rounded-lg transition-colors",children:"Current"}),e.jsxs("button",{onClick:M,className:"px-4 py-2 bg-dark-700 hover:bg-dark-600 text-gray-300 rounded-lg transition-colors flex items-center gap-2",children:["Next",e.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]})]})]}),e.jsx(ts,{calendarData:f,onDayClick:X,month:N,year:c,enrichmentData:F,reportsByDate:E,onOpenReport:A,onOpenReportList:$}),e.jsx($s,{month:N,year:c})]}),k&&e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsxs("div",{className:"bg-gradient-to-br from-green-900/20 to-dark-800 rounded-lg border border-green-700/50 p-6",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-6",children:[e.jsx("div",{className:"p-3 bg-green-600 rounded-lg",children:e.jsx(Lt,{className:"w-6 h-6 text-white"})}),e.jsx("h3",{className:"text-xl font-bold text-green-400",children:"BEST PERFORMANCE"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"bg-dark-800/50 rounded-lg p-4 border border-dark-700",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("span",{className:"text-sm font-semibold text-green-400",children:"Best Trade"}),e.jsxs("span",{className:"text-lg font-bold text-green-400",children:["+€",k.bestTrade.net_pnl.toFixed(2)]})]}),e.jsxs("div",{className:"text-xs text-dark-400",children:[e.jsxs("div",{children:[k.bestTrade.instrument," • ",k.bestTrade.amount," contracts"]}),e.jsx("div",{children:Q(`${k.bestTrade.close_time.getFullYear()}
26-${String(k.bestTrade.close_time.getMonth()+1).padStart(2,"0")}-${String(k.bestTrade.close_time.getDate()).padStart(2,"0")}`)})]})]}),e.jsxs("div",{className:"bg-dark-800/50 rounded-lg p-4 border border-dark-700",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("span",{className:"text-sm font-semibold text-green-400",children:"Best Day"}),e.jsxs("span",{className:"text-lg font-bold text-green-400",children:["+€",k.bestDay.pnl.toFixed(2)]})]}),e.jsxs("div",{className:"text-xs text-dark-400",children:[e.jsx("div",{children:Q(k.bestDay.date)}),e.jsxs("div",{children:[k.bestDay.trades.length," trades"]})]})]}),e.jsxs("div",{className:"bg-dark-800/50 rounded-lg p-4 border border-dark-700",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("span",{className:"text-sm font-semibold text-green-400",children:"Best Week"}),e.jsxs("span",{className:"text-lg font-bold text-green-400",children:["+€",k.bestWeek.pnl.toFixed(2)]})]}),e.jsxs("div",{className:"text-xs text-dark-400",children:[e.jsx("div",{children:R(k.bestWeek.week)}),e.jsxs("div",{children:[k.bestWeek.trades.length," trades"]})]})]}),e.jsxs("div",{className:"bg-dark-800/50 rounded-lg p-4 border border-dark-700",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("span",{className:"text-sm font-semibold text-green-400",children:"Best Month"}),e.jsxs("span",{className:"text-lg font-bold text-green-400",children:["+€",k.bestMonth.pnl.toFixed(2)]})]}),e.jsxs("div",{className:"text-xs text-dark-400",children:[e.jsx("div",{children:ie(k.bestMonth.month)}),e.jsxs("div",{children:[k.bestMonth.trades.length," trades"]})]})]})]})]}),e.jsxs("div",{className:"bg-gradient-to-br from-red-900/20 to-dark-800 rounded-lg border border-red-700/50 p-6",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-6",children:[e.jsx("div",{className:"p-3 bg-red-600 rounded-lg",children:e.jsx(it,{className:"w-6 h-6 text-white"})}),e.jsx("h3",{className:"text-xl font-bold text-red-400",children:"WORST PERFORMANCE"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"bg-dark-800/50 rounded-lg p-4 border border-dark-700",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("span",{className:"text-sm font-semibold text-red-400",children:"Worst Trade"}),e.jsxs("span",{className:"text-lg font-bold text-red-400",children:[k.worstTrade.net_pnl>=0?"+":"","€",k.worstTrade.net_pnl.toFixed(2)]})]}),e.jsxs("div",{className:"text-xs text-dark-400",children:[e.jsxs("div",{children:[k.worstTrade.instrument," • ",k.worstTrade.amount," contracts"]}),e.jsx("div",{children:Q(`${k.worstTrade.close_time.getFullYear()}-${String(k.worstTrade.close_time.getMonth()+1).padStart(2,"0")}-${String(k.worstTrade.close_time.getDate()).padStart(2,"0")}`)})]})]}),e.jsxs("div",{className:"bg-dark-800/50 rounded-lg p-4 border border-dark-700",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("span",{className:"text-sm font-semibold text-red-400",children:"Worst Day"}),e.jsxs("span",{className:"text-lg font-bold text-red-400",children:[k.worstDay.pnl>=0?"+":"","€",k.worstDay.pnl.toFixed(2)]})]}),e.jsxs("div",{className:"text-xs text-dark-400",children:[e.jsx("div",{children:Q(k.worstDay.date)}),e.jsxs("div",{children:[k.worstDay.trades.length," trades"]})]})]}),e.jsxs("div",{className:"bg-dark-800/50 rounded-lg p-4 border border-dark-700",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("span",{className:"text-sm font-semibold text-red-400",children:"Worst Week"}),e.jsxs("span",{className:"text-lg font-bold text-red-400",children:[k.worstWeek.pnl>=0?"+":"","€",k.worstWeek.pnl.toFixed(2)]})]}),e.jsxs("div",{className:"text-xs text-dark-400",children:[e.jsx("div",{children:R(k.worstWeek.week)}),e.jsxs("div",{children:[k.worstWeek.trades.length," trades"]})]})]}),e.jsxs("div",{className:"bg-dark-800/50 rounded-lg p-4 border border-dark-700",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("span",{className:"text-sm font-semibold text-red-400",children:"Worst Month"}),e.jsxs("span",{className:"text-lg font-bold text-red-400",children:[k.worstMonth.pnl>=0?"+":"","€",k.worstMonth.pnl.toFixed(2)]})]}),e.jsxs("div",{className:"text-xs text-dark-400",children:[e.jsx("div",{children:ie(k.worstMonth.month)}),e.jsxs("div",{children:[k.worstMonth.trades.length," trades"]})]})]})]})]})]})]}),s.length===0&&e.jsxs("div",{className:"bg-dark-800 rounded-lg border border-dark-700 p-12 text-center",children:[e.jsx(qe,{className:"w-16 h-16 text-gray-600 mx-auto mb-4"}),e.jsx("h3",{className:"text-xl font-bold text-dark-50 mb-2",children:"No Journal Entries Yet"}),e.jsx("p",{className:"text-dark-400 mb-4",children:"Import your trading data to start journaling"}),e.jsx("a",{href:"/trade/config",className:"inline-block px-6 py-3 bg-primary-500 hover:bg-primary-600 text-white rounded-lg transition-colors font-medium",children:"Go to Data Config"})]}),e.jsx(ss,{isOpen:d,onClose:I,dayData:r?(()=>{const[w,W,Y]=r.split("-").map(Number);return f.weeks.flatMap(se=>se.days).find(se=>se&&se.date===Y)||{date:Y,dailyPnL:0,trades:[],tradeCount:0,winRate:0}})():null,month:r?parseInt(r.split("-")[1])-1:N,year:r?parseInt(r.split("-")[0]):c})]}),j&&e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60",onClick:()=>$(null),children:e.jsxs("div",{className:"bg-dark-800 border border-dark-700 rounded-xl p-4 w-full max-w-md mx-4",onClick:w=>w.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("h3",{className:"text-sm font-semibold text-dark-50",children:["Reports · ",j]}),e.jsx("button",{onClick:()=>$(null),className:"text-dark-400 hover:text-dark-50 text-lg leading-none",children:"×"})]}),e.jsx("div",{className:"space-y-2",children:(E[j]||[]).slice().sort((w,W)=>String(w.created_at).localeCompare(String(W.created_at))).map(w=>e.jsxs("button",{onClick:()=>{$(null),A(w.id)},className:"w-full text-left px-3 py-2 bg-dark-900 border border-dark-700 hover:border-primary-500 rounded-lg transition-colors",children:[e.jsx("div",{className:"text-sm text-dark-50",children:w.title||w.report_type}),e.jsxs("div",{className:"text-[11px] text-dark-400",children:[w.report_type,w.created_at?` · ${String(w.created_at).slice(11,16)}`:""]})]},w.id))})]})}),v&&e.jsx(It,{report:v,onClose:()=>L(null)})]})}function $s({month:s,year:r}){const{getAuthHeader:d}=Le(),[p,P]=o.useState(""),[g,N]=o.useState(""),[h,c]=o.useState(!1);o.useEffect(()=>
26{P(""),N(""),(async()=>{var F;try{const u=await fetch(`/api/journal/monthly-comments/${r}/${s+1}`,{headers:d()});if(u.ok){const B=((F=(await u.json()).comment)==null?void 0:F.comment)||"";P(B),N(B)}}catch(u){console.error("Failed to fetch monthly comment:",u)}})()},[s,r,d]);const b=async()=>{if(p!==g){c(!0);try{(await fetch("/api/journal/monthly-comments",{method:"POST",headers:{"Content-Type":"application/json",...d()},body:JSON.stringify({year:r,month:s+1,comment:p})})).ok&&N(p)}catch(y){console.error("Failed to save monthly comment:",y)}finally{c(!1)}}},S=p!==g;return e.jsxs("div",{className:"mt-4 bg-dark-800/50 rounded-lg border border-dark-700 p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(He,{className:"w-4 h-4 text-primary-400"}),e.jsxs("span",{className:"text-sm font-semibold text-gray-300",children:["Monthly Review — ",new Date(r,s).toLocaleDateString("en-GB",{month:"long",year:"numeric"})]})]}),S&&e.jsx("button",{onClick:b,disabled:h,className:"px-3 py-1 text-xs font-medium text-white bg-primary-500 hover:bg-primary-600 rounded-md disabled:opacity-50 transition-colors",children:h?"Saving...":"Save"}),!S&&g&&e.jsx("span",{className:"text-[10px] text-green-500/60",children:"Saved ✓"})]}),e.jsx("textarea",{value:p,onChange:y=>P(y.target.value),placeholder:"Write your monthly review — key takeaways, strategy changes, notable moments...",className:"w-full bg-dark-900/50 text-gray-200 text-sm rounded-lg p-3 border border-dark-700 focus:border-primary-500 focus:ring-1 focus:ring-primary-500 outline-none resize-y min-h-[80px]",rows:3})]})}export{Hs 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.