← back to Bertha
snapshot: 11 file(s) changed, +3 new, ~2 modified, -6 removed
1b701674d7a119b969152de2db62aa268a24f5a2 · 2026-05-13 08:57:46 -0700 · Steve
Files touched
D kalshi-dash/dist/assets/index-BXhqt972.cssD kalshi-dash/dist/assets/index-_K_ynK5-.jsD kalshi-dash/dist/index.htmlA kalshi-dash/server.js.bak-20260422-160936A kalshi-dash/server.js.pre-scrub-2026-05-07.bakA public/favicon.svgD react-dash/dist/assets/index-X3aldCwL.cssD react-dash/dist/assets/index-qtNisuCe.jsD react-dash/dist/index.htmlM react-dash/server.jsM src/lib/auth.js
Diff
commit 1b701674d7a119b969152de2db62aa268a24f5a2
Author: Steve <steve@designerwallcoverings.com>
Date: Wed May 13 08:57:46 2026 -0700
snapshot: 11 file(s) changed, +3 new, ~2 modified, -6 removed
---
kalshi-dash/dist/assets/index-BXhqt972.css | 1 -
kalshi-dash/dist/assets/index-_K_ynK5-.js | 157 -
kalshi-dash/dist/index.html | 16 -
kalshi-dash/server.js.bak-20260422-160936 | 9128 +++++++++++++++++++++++
kalshi-dash/server.js.pre-scrub-2026-05-07.bak | 9138 ++++++++++++++++++++++++
public/favicon.svg | 4 +
react-dash/dist/assets/index-X3aldCwL.css | 1 -
react-dash/dist/assets/index-qtNisuCe.js | 139 -
react-dash/dist/index.html | 14 -
react-dash/server.js | 9 +-
src/lib/auth.js | 14 +-
11 files changed, 18288 insertions(+), 333 deletions(-)
diff --git a/kalshi-dash/dist/assets/index-BXhqt972.css b/kalshi-dash/dist/assets/index-BXhqt972.css
deleted file mode 100644
index 054d04f..0000000
--- a/kalshi-dash/dist/assets/index-BXhqt972.css
+++ /dev/null
@@ -1 +0,0 @@
-*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji";font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}.pointer-events-none{pointer-events:none}.collapse{visibility:collapse}.absolute{position:absolute}.relative{position:relative}.sticky{position:sticky}.inset-0{top:0;right:0;bottom:0;left:0}.-top-2{top:-.5rem}.bottom-0{bottom:0}.bottom-3{bottom:.75rem}.left-0{left:0}.left-1{left:.25rem}.left-3{left:.75rem}.left-6{left:1.5rem}.right-0{right:0}.right-2{right:.5rem}.right-3{right:.75rem}.top-0{top:0}.top-1{top:.25rem}.top-1\/2{top:50%}.top-3{top:.75rem}.z-10{z-index:10}.z-20{z-index:20}.mx-0\.5{margin-left:.125rem;margin-right:.125rem}.mx-auto{margin-left:auto;margin-right:auto}.mb-0\.5{margin-bottom:.125rem}.mb-1{margin-bottom:.25rem}.mb-1\.5{margin-bottom:.375rem}.mb-2{margin-bottom:.5rem}.mb-3{margin-bottom:.75rem}.mb-4{margin-bottom:1rem}.mb-5{margin-bottom:1.25rem}.mb-7{margin-bottom:1.75rem}.ml-1{margin-left:.25rem}.ml-2{margin-left:.5rem}.ml-3{margin-left:.75rem}.ml-6{margin-left:1.5rem}.ml-auto{margin-left:auto}.mr-1{margin-right:.25rem}.mr-4{margin-right:1rem}.mt-0\.5{margin-top:.125rem}.mt-1{margin-top:.25rem}.mt-2{margin-top:.5rem}.mt-3{margin-top:.75rem}.mt-auto{margin-top:auto}.block{display:block}.inline-block{display:inline-block}.inline{display:inline}.flex{display:flex}.inline-flex{display:inline-flex}.table{display:table}.grid{display:grid}.contents{display:contents}.hidden{display:none}.h-0\.5{height:.125rem}.h-1\.5{height:.375rem}.h-10{height:2.5rem}.h-12{height:3rem}.h-16{height:4rem}.h-2{height:.5rem}.h-2\.5{height:.625rem}.h-3{height:.75rem}.h-4{height:1rem}.h-5{height:1.25rem}.h-6{height:1.5rem}.h-64{height:16rem}.h-8{height:2rem}.h-9{height:2.25rem}.h-full{height:100%}.max-h-48{max-height:12rem}.min-h-screen{min-height:100vh}.w-1\.5{width:.375rem}.w-10{width:2.5rem}.w-11{width:2.75rem}.w-12{width:3rem}.w-2{width:.5rem}.w-2\.5{width:.625rem}.w-20{width:5rem}.w-3{width:.75rem}.w-4{width:1rem}.w-5{width:1.25rem}.w-6{width:1.5rem}.w-8{width:2rem}.w-9{width:2.25rem}.w-fit{width:-moz-fit-content;width:fit-content}.w-full{width:100%}.min-w-0{min-width:0px}.max-w-2xl{max-width:42rem}.max-w-3xl{max-width:48rem}.max-w-\[180px\]{max-width:180px}.max-w-\[192px\]{max-width:192px}.max-w-\[200px\]{max-width:200px}.max-w-\[250px\]{max-width:250px}.max-w-\[280px\]{max-width:280px}.max-w-\[300px\]{max-width:300px}.max-w-\[400px\]{max-width:400px}.max-w-lg{max-width:32rem}.flex-1{flex:1 1 0%}.flex-shrink-0{flex-shrink:0}.-translate-y-1\/2{--tw-translate-y: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.transform{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes ping{75%,to{transform:scale(2);opacity:0}}.animate-ping{animation:ping 1s cubic-bezier(0,0,.2,1) infinite}@keyframes pulse{50%{opacity:.5}}.animate-pulse{animation:pulse 2s cubic-bezier(.4,0,.6,1) infinite}@keyframes spin{to{transform:rotate(360deg)}}.animate-spin{animation:spin 1s linear infinite}.cursor-default{cursor:default}.cursor-not-allowed{cursor:not-allowed}.cursor-pointer{cursor:pointer}.select-none{-webkit-user-select:none;-moz-user-select:none;user-select:none}.resize{resize:both}.list-inside{list-style-position:inside}.list-decimal{list-style-type:decimal}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.grid-cols-5{grid-template-columns:repeat(5,minmax(0,1fr))}.grid-cols-6{grid-template-columns:repeat(6,minmax(0,1fr))}.grid-cols-7{grid-template-columns:repeat(7,minmax(0,1fr))}.grid-cols-8{grid-template-columns:repeat(8,minmax(0,1fr))}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-start{align-items:flex-start}.items-end{align-items:flex-end}.items-center{align-items:center}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.gap-0\.5{gap:.125rem}.gap-1{gap:.25rem}.gap-1\.5{gap:.375rem}.gap-2{gap:.5rem}.gap-3{gap:.75rem}.gap-4{gap:1rem}.gap-6{gap:1.5rem}.gap-px{gap:1px}.gap-x-3{-moz-column-gap:.75rem;column-gap:.75rem}.gap-y-1{row-gap:.25rem}.space-y-1>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.25rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.25rem * var(--tw-space-y-reverse))}.space-y-1\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.375rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.375rem * var(--tw-space-y-reverse))}.space-y-2>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.5rem * var(--tw-space-y-reverse))}.space-y-3>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.75rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.75rem * var(--tw-space-y-reverse))}.space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1rem * var(--tw-space-y-reverse))}.space-y-5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1.25rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1.25rem * var(--tw-space-y-reverse))}.space-y-6>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1.5rem * var(--tw-space-y-reverse))}.space-y-8>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(2rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(2rem * var(--tw-space-y-reverse))}.overflow-hidden{overflow:hidden}.overflow-x-auto{overflow-x:auto}.overflow-y-auto{overflow-y:auto}.truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.whitespace-nowrap{white-space:nowrap}.rounded{border-radius:.25rem}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:.5rem}.rounded-md{border-radius:.375rem}.rounded-sm{border-radius:.125rem}.rounded-xl{border-radius:.75rem}.border{border-width:1px}.border-2{border-width:2px}.border-b{border-bottom-width:1px}.border-t{border-top-width:1px}.border-amber-500{--tw-border-opacity: 1;border-color:rgb(245 158 11 / var(--tw-border-opacity, 1))}.border-blue-500{--tw-border-opacity: 1;border-color:rgb(59 130 246 / var(--tw-border-opacity, 1))}.border-gray-700{--tw-border-opacity: 1;border-color:rgb(55 65 81 / var(--tw-border-opacity, 1))}.border-gray-800{--tw-border-opacity: 1;border-color:rgb(31 41 55 / var(--tw-border-opacity, 1))}.border-green-500{--tw-border-opacity: 1;border-color:rgb(34 197 94 / var(--tw-border-opacity, 1))}.border-green-500\/20{border-color:#22c55e33}.border-green-500\/30{border-color:#22c55e4d}.border-red-500\/20{border-color:#ef444433}.border-yellow-500\/30{border-color:#eab3084d}.border-t-transparent{border-top-color:transparent}.bg-amber-500{--tw-bg-opacity: 1;background-color:rgb(245 158 11 / var(--tw-bg-opacity, 1))}.bg-amber-500\/10{background-color:#f59e0b1a}.bg-amber-500\/15{background-color:#f59e0b26}.bg-gray-600{--tw-bg-opacity: 1;background-color:rgb(75 85 99 / var(--tw-bg-opacity, 1))}.bg-gray-700{--tw-bg-opacity: 1;background-color:rgb(55 65 81 / var(--tw-bg-opacity, 1))}.bg-gray-800{--tw-bg-opacity: 1;background-color:rgb(31 41 55 / var(--tw-bg-opacity, 1))}.bg-gray-800\/30{background-color:#1f29374d}.bg-gray-800\/50{background-color:#1f293780}.bg-green-400{--tw-bg-opacity: 1;background-color:rgb(74 222 128 / var(--tw-bg-opacity, 1))}.bg-green-500{--tw-bg-opacity: 1;background-color:rgb(34 197 94 / var(--tw-bg-opacity, 1))}.bg-green-500\/10{background-color:#22c55e1a}.bg-green-500\/15{background-color:#22c55e26}.bg-green-500\/30{background-color:#22c55e4d}.bg-green-500\/5{background-color:#22c55e0d}.bg-red-500{--tw-bg-opacity: 1;background-color:rgb(239 68 68 / var(--tw-bg-opacity, 1))}.bg-red-500\/10{background-color:#ef44441a}.bg-yellow-400{--tw-bg-opacity: 1;background-color:rgb(250 204 21 / var(--tw-bg-opacity, 1))}.bg-yellow-500{--tw-bg-opacity: 1;background-color:rgb(234 179 8 / var(--tw-bg-opacity, 1))}.bg-yellow-500\/15{background-color:#eab30826}.bg-yellow-500\/30{background-color:#eab3084d}.p-0{padding:0}.p-0\.5{padding:.125rem}.p-1{padding:.25rem}.p-1\.5{padding:.375rem}.p-2{padding:.5rem}.p-2\.5{padding:.625rem}.p-3{padding:.75rem}.p-4{padding:1rem}.px-1\.5{padding-left:.375rem;padding-right:.375rem}.px-2{padding-left:.5rem;padding-right:.5rem}.px-2\.5{padding-left:.625rem;padding-right:.625rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.px-5{padding-left:1.25rem;padding-right:1.25rem}.px-6{padding-left:1.5rem;padding-right:1.5rem}.px-8{padding-left:2rem;padding-right:2rem}.py-0\.5{padding-top:.125rem;padding-bottom:.125rem}.py-1{padding-top:.25rem;padding-bottom:.25rem}.py-1\.5{padding-top:.375rem;padding-bottom:.375rem}.py-10{padding-top:2.5rem;padding-bottom:2.5rem}.py-12{padding-top:3rem;padding-bottom:3rem}.py-16{padding-top:4rem;padding-bottom:4rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-3{padding-top:.75rem;padding-bottom:.75rem}.py-4{padding-top:1rem;padding-bottom:1rem}.py-5{padding-top:1.25rem;padding-bottom:1.25rem}.py-8{padding-top:2rem;padding-bottom:2rem}.pb-1{padding-bottom:.25rem}.pb-10{padding-bottom:2.5rem}.pb-3{padding-bottom:.75rem}.pl-5{padding-left:1.25rem}.pl-8{padding-left:2rem}.pt-2{padding-top:.5rem}.pt-3{padding-top:.75rem}.text-left{text-align:left}.text-center{text-align:center}.text-right{text-align:right}.align-middle{vertical-align:middle}.font-mono{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace}.text-2xl{font-size:1.5rem;line-height:2rem}.text-3xl{font-size:1.875rem;line-height:2.25rem}.text-4xl{font-size:2.25rem;line-height:2.5rem}.text-\[10px\]{font-size:10px}.text-\[11px\]{font-size:11px}.text-\[9px\]{font-size:9px}.text-base{font-size:1rem;line-height:1.5rem}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xl{font-size:1.25rem;line-height:1.75rem}.text-xs{font-size:.75rem;line-height:1rem}.font-bold{font-weight:700}.font-medium{font-weight:500}.font-semibold{font-weight:600}.uppercase{text-transform:uppercase}.italic{font-style:italic}.leading-none{line-height:1}.leading-relaxed{line-height:1.625}.leading-tight{line-height:1.25}.tracking-wide{letter-spacing:.025em}.tracking-wider{letter-spacing:.05em}.text-amber-400{--tw-text-opacity: 1;color:rgb(251 191 36 / var(--tw-text-opacity, 1))}.text-black{--tw-text-opacity: 1;color:rgb(0 0 0 / var(--tw-text-opacity, 1))}.text-blue-400{--tw-text-opacity: 1;color:rgb(96 165 250 / var(--tw-text-opacity, 1))}.text-gray-200{--tw-text-opacity: 1;color:rgb(229 231 235 / var(--tw-text-opacity, 1))}.text-gray-300{--tw-text-opacity: 1;color:rgb(209 213 219 / var(--tw-text-opacity, 1))}.text-gray-400{--tw-text-opacity: 1;color:rgb(156 163 175 / var(--tw-text-opacity, 1))}.text-gray-500{--tw-text-opacity: 1;color:rgb(107 114 128 / var(--tw-text-opacity, 1))}.text-gray-600{--tw-text-opacity: 1;color:rgb(75 85 99 / var(--tw-text-opacity, 1))}.text-green-400{--tw-text-opacity: 1;color:rgb(74 222 128 / var(--tw-text-opacity, 1))}.text-red-400{--tw-text-opacity: 1;color:rgb(248 113 113 / var(--tw-text-opacity, 1))}.text-white{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.text-yellow-400{--tw-text-opacity: 1;color:rgb(250 204 21 / var(--tw-text-opacity, 1))}.opacity-0{opacity:0}.opacity-10{opacity:.1}.opacity-30{opacity:.3}.opacity-50{opacity:.5}.ring{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(3px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.blur{--tw-blur: blur(8px);filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.drop-shadow{--tw-drop-shadow: drop-shadow(0 1px 2px rgb(0 0 0 / .1)) drop-shadow(0 1px 1px rgb(0 0 0 / .06));filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.\!filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)!important}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.transition{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-all{transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-colors{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-transform{transition-property:transform;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.duration-1000{transition-duration:1s}.duration-300{transition-duration:.3s}.ease-out{transition-timing-function:cubic-bezier(0,0,.2,1)}:root{--bg: #0E0E10;--surface: #141419;--surface-el: #1C1C24;--border: #2A2A35;--border-light: #3A3A48;--cyan: #00F0FF;--cyan-dim: rgba(0, 240, 255, .15);--cyan-glow: rgba(0, 240, 255, .08);--orange: #F7931A;--orange-dim: rgba(247, 147, 26, .15);--green: #00C389;--green-dim: rgba(0, 195, 137, .15);--red: #FF5C5C;--red-dim: rgba(255, 92, 92, .15);--blue: #3B82F6;--blue-dim: rgba(59, 130, 246, .15);--purple: #A855F7;--purple-dim: rgba(168, 85, 247, .15);--text: #E0E0E0;--text-dim: #A8A8A8;--text-muted: #6B7280;--radius-sm: 6px;--radius-md: 10px;--radius-lg: 14px;--radius-xl: 20px;--transition: .15s ease;--font-heading: "Space Grotesk", sans-serif;--font-body: "Inter", sans-serif;--font-mono: "JetBrains Mono", monospace}body{background:var(--bg);color:var(--text);font-family:var(--font-body);margin:0;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}h1,h2,h3,h4,h5,h6{font-family:var(--font-heading);font-weight:700;letter-spacing:-.02em}::-webkit-scrollbar{width:6px;height:6px}::-webkit-scrollbar-track{background:var(--bg)}::-webkit-scrollbar-thumb{background:#374151;border-radius:3px}::-webkit-scrollbar-thumb:hover{background:#4b5563}.card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius-lg);padding:1.25rem;transition:all var(--transition)}.card:hover{border-color:#00f0ff40;box-shadow:0 0 0 1px #00f0ff14,0 0 24px #00f0ff1f,0 4px 16px #0000004d}.card-elevated{background:var(--surface-el);border:1px solid var(--border);border-radius:var(--radius-lg);padding:1.25rem}.card-glow{background:var(--surface);border:1px solid rgba(0,240,255,.2);border-radius:var(--radius-lg);padding:1.25rem;box-shadow:0 0 30px var(--cyan-glow),inset 0 1px #00f0ff0d}.stat-v{font-family:var(--font-mono);font-size:1.75rem;font-weight:600;line-height:1;letter-spacing:-.02em}.stat-label{font-size:.7rem;font-weight:600;text-transform:uppercase;letter-spacing:.08em;color:var(--text-muted);font-family:var(--font-body)}.badge{display:inline-flex;align-items:center;gap:4px;padding:3px 10px;border-radius:9999px;font-size:.7rem;font-weight:600;font-family:var(--font-body);letter-spacing:.02em}.bg-cyan{background:var(--cyan-dim);color:var(--cyan)}.bg-green{background:var(--green-dim);color:var(--green)}.bg-red{background:var(--red-dim);color:var(--red)}.bg-yellow,.bg-orange{background:var(--orange-dim);color:var(--orange)}.bg-blue{background:var(--blue-dim);color:var(--blue)}.bg-purple{background:var(--purple-dim);color:var(--purple)}.btn{display:inline-flex;align-items:center;justify-content:center;gap:6px;padding:.5rem 1rem;border-radius:var(--radius-md);font-weight:600;font-size:.85rem;font-family:var(--font-body);cursor:pointer;border:none;transition:all var(--transition)}.btn-p{background:var(--cyan);color:#0e0e10}.btn-p:hover{background:#00d4e0;transform:translateY(-1px);box-shadow:0 4px 12px #00f0ff40}.btn-orange{background:var(--orange);color:#0e0e10}.btn-orange:hover{background:#e5850f}.btn-d{background:var(--red);color:#fff}.btn-d:hover{background:#e04a4a}.btn-s{background:var(--green);color:#0e0e10}.btn-s:hover{background:#00a875}.btn-o{background:transparent;border:1px solid var(--border);color:var(--text-dim)}.btn-o:hover{border-color:var(--cyan);color:var(--cyan)}.btn-ghost{background:transparent;color:var(--text-dim);border:none}.btn-ghost:hover{color:var(--cyan);background:var(--cyan-glow)}.btn-sm{padding:.35rem .75rem;font-size:.75rem}.btn-lg{padding:.75rem 1.5rem;font-size:1rem}table{width:100%;border-collapse:collapse}th{text-align:left;padding:.75rem;font-size:.65rem;text-transform:uppercase;letter-spacing:.08em;color:var(--text-muted);font-family:var(--font-body);font-weight:600;border-bottom:1px solid var(--border)}td{padding:.75rem;border-bottom:1px solid rgba(42,42,53,.5);font-size:.85rem}.input{width:100%;padding:.6rem .85rem;background:var(--surface-el);border:1px solid var(--border);border-radius:var(--radius-md);color:var(--text);font-family:var(--font-body);font-size:.85rem;transition:all var(--transition);outline:none}.input:focus{border-color:var(--cyan);box-shadow:0 0 0 3px #00f0ff1a}.input::-moz-placeholder{color:var(--text-muted)}.input::placeholder{color:var(--text-muted)}.kalshi-gradient{background:linear-gradient(135deg,var(--cyan),var(--orange));-webkit-background-clip:text;-webkit-text-fill-color:transparent;background-clip:text}.gradient-cyan{background:linear-gradient(135deg,var(--cyan),#0088FF);-webkit-background-clip:text;-webkit-text-fill-color:transparent;background-clip:text}.pulse-cyan{animation:pulse-c 2s infinite}@keyframes pulse-c{0%,to{box-shadow:0 0 #00f0ff66}50%{box-shadow:0 0 0 6px #00f0ff00}}.pulse-g{animation:pg 2s infinite}@keyframes pg{0%,to{box-shadow:0 0 #00c38966}50%{box-shadow:0 0 0 6px #00c38900}}.glow-cyan{box-shadow:0 0 20px #00f0ff26,0 0 60px #00f0ff0d}.fade-in{animation:fadeIn .3s ease-out}@keyframes fadeIn{0%{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}.section-title{font-family:var(--font-heading);font-size:1.25rem;font-weight:700;color:var(--text);display:flex;align-items:center;gap:10px}.section-subtitle{font-size:.8rem;color:var(--text-muted);margin-top:2px}.toggle{position:relative;width:40px;height:22px;background:var(--border);border-radius:11px;cursor:pointer;transition:background var(--transition)}.toggle.active{background:var(--cyan)}.toggle:after{content:"";position:absolute;top:2px;left:2px;width:18px;height:18px;background:#fff;border-radius:50%;transition:transform var(--transition)}.toggle.active:after{transform:translate(18px)}.progress-bar{height:4px;background:var(--border);border-radius:2px;overflow:hidden}.progress-fill{height:100%;border-radius:2px;background:linear-gradient(90deg,var(--cyan),#0088FF);transition:width .5s ease}.mono{font-family:var(--font-mono)}.heading{font-family:var(--font-heading)}.text-cyan{color:var(--cyan)}.text-orange{color:var(--orange)}.text-green{color:var(--green)}.text-red{color:var(--red)}.text-dim{color:var(--text-dim)}.text-muted{color:var(--text-muted)}.border-cyan{border-color:var(--cyan)!important}.card-glass{background:#141419cc;backdrop-filter:blur(12px);-webkit-backdrop-filter:blur(12px);border:1px solid rgba(0,240,255,.1);border-radius:var(--radius-lg)}.text-glow{text-shadow:0 0 10px rgba(0,240,255,.5)}.text-glow-green{text-shadow:0 0 10px rgba(0,195,137,.4)}.text-glow-red{text-shadow:0 0 10px rgba(255,92,92,.4)}.divider-glow{height:1px;background:linear-gradient(90deg,transparent,var(--cyan),transparent);border:none;margin:0}.skeleton{background:linear-gradient(90deg,var(--surface-el) 25%,var(--border) 50%,var(--surface-el) 75%);background-size:200% 100%;animation:shimmer 1.5s ease-in-out infinite;border-radius:var(--radius-sm)}@keyframes shimmer{0%{background-position:200% 0}to{background-position:-200% 0}}@keyframes ticker{0%{transform:translate(0)}to{transform:translate(-50%)}}.btn:active:not(:disabled){transform:scale(.97)}.neon-focus:focus-visible{outline:none;box-shadow:0 0 0 2px var(--bg),0 0 0 4px var(--cyan),0 0 12px #00f0ff4d}.card-accent-cyan{border-top:2px solid var(--cyan)}.card-accent-green{border-top:2px solid var(--green)}.card-accent-red{border-top:2px solid var(--red)}.card-accent-orange{border-top:2px solid var(--orange)}.card-accent-blue{border-top:2px solid var(--blue)}.card-accent-purple{border-top:2px solid var(--purple)}tr:hover td{background:var(--cyan-glow)}tbody tr:hover td:first-child{box-shadow:inset 3px 0 0 var(--cyan)}tbody tr:nth-child(2n) td{background:#1c1c2466}tbody tr:nth-child(2n):hover td{background:var(--cyan-glow)}.card-lift{transition:transform .15s ease,box-shadow .15s ease,border-color .15s ease}.card-lift:hover{transform:translateY(-2px);box-shadow:0 8px 24px #0006,0 0 20px #00f0ff1a}.pnl-positive{color:var(--green);text-shadow:0 0 8px rgba(0,195,137,.35)}.pnl-negative{color:var(--red);text-shadow:0 0 8px rgba(255,92,92,.35)}.section-accent-green{border-left:3px solid var(--green);padding-left:10px}.section-accent-red{border-left:3px solid var(--red);padding-left:10px}.section-accent-cyan{border-left:3px solid var(--cyan);padding-left:10px}.nav-active-glow{box-shadow:inset 0 0 12px #00f0ff14}.bar-win-glow{box-shadow:0 0 8px #00c38980}.bar-loss-glow{box-shadow:0 0 8px #ff5c5c80}.live-indicator{display:inline-flex;align-items:center;gap:6px;font-family:var(--font-mono);font-size:.7rem;font-weight:700;text-transform:uppercase;letter-spacing:.1em;color:var(--green)}.live-dot{width:6px;height:6px;border-radius:50%;background:var(--green);animation:live-blink 1.5s ease-in-out infinite;flex-shrink:0}@keyframes live-blink{0%,to{opacity:1;box-shadow:0 0 #00c38999}50%{opacity:.4;box-shadow:0 0 0 4px #00c38900}}@keyframes scan-line{0%{top:-5%}to{top:105%}}.scan-overlay{pointer-events:none;position:fixed;top:0;left:0;width:100%;height:100%;z-index:9999;overflow:hidden}.scan-overlay:before{content:"";position:absolute;width:100%;height:2px;background:linear-gradient(90deg,transparent,rgba(0,240,255,.06),transparent);animation:scan-line 8s linear infinite}.scan-overlay:after{content:"";position:absolute;top:0;left:0;width:100%;height:100%;background:repeating-linear-gradient(0deg,transparent,transparent 2px,rgba(0,0,0,.03) 2px,rgba(0,0,0,.03) 4px)}.sidebar-mesh{background:radial-gradient(ellipse at 20% 80%,rgba(0,240,255,.04) 0%,transparent 50%),radial-gradient(ellipse at 80% 20%,rgba(247,147,26,.03) 0%,transparent 50%),var(--surface)}.market-status-bar{display:flex;align-items:center;gap:16px;padding:6px 16px;background:linear-gradient(90deg,rgba(0,240,255,.03),transparent,rgba(247,147,26,.03));border-bottom:1px solid var(--border);font-size:.7rem;color:var(--text-muted);font-family:var(--font-mono)}@property --neon-angle{syntax: "<angle>"; initial-value: 0deg; inherits: false;}@keyframes neon-rotate{0%{--neon-angle: 0deg}to{--neon-angle: 360deg}}.border-neon-animated{position:relative;border:none!important;isolation:isolate}.border-neon-animated:before{content:"";position:absolute;top:-2px;right:-2px;bottom:-2px;left:-2px;border-radius:calc(var(--radius-lg) + 2px);background:conic-gradient(from var(--neon-angle),var(--cyan),var(--orange),var(--green),var(--cyan));animation:neon-rotate 3s linear infinite;z-index:-1}.border-neon-animated:after{content:"";position:absolute;top:0;right:0;bottom:0;left:0;border-radius:var(--radius-lg);background:var(--surface);z-index:-1}.notification-bell{position:relative;cursor:pointer;padding:6px;border-radius:var(--radius-sm);transition:background .15s ease}.notification-bell:hover{background:var(--cyan-glow)}.notification-bell svg{width:18px;height:18px;color:var(--text-dim);transition:color .15s ease}.notification-bell:hover svg{color:var(--cyan)}.notification-count{position:absolute;top:2px;right:2px;min-width:14px;height:14px;border-radius:7px;background:var(--red);color:#fff;font-size:.55rem;font-weight:700;display:flex;align-items:center;justify-content:center;padding:0 3px;border:2px solid var(--bg);animation:notification-pop .3s ease-out}@keyframes notification-pop{0%{transform:scale(0)}50%{transform:scale(1.3)}to{transform:scale(1)}}@keyframes breathe-neon{0%,to{box-shadow:0 0 #00f0ff1a,0 0 #00f0ff0d}50%{box-shadow:0 0 15px 2px #00f0ff1f,0 0 40px 4px #00f0ff0a}}@keyframes breathe-orange{0%,to{box-shadow:0 0 #f7931a1a}50%{box-shadow:0 0 15px 2px #f7931a1f}}.breathe-neon{animation:breathe-neon 4s ease-in-out infinite}.breathe-orange{animation:breathe-orange 3.5s ease-in-out infinite}@keyframes logo-pulse{0%,to{filter:drop-shadow(0 0 4px rgba(247,147,26,.3))}50%{filter:drop-shadow(0 0 12px rgba(247,147,26,.6))}}.logo-animated{animation:logo-pulse 3s ease-in-out infinite}.position-winning{border-left:3px solid var(--green);position:relative}.position-winning:before{content:"";position:absolute;left:-7px;top:50%;transform:translateY(-50%);width:8px;height:8px;border-radius:50%;background:var(--green);box-shadow:0 0 8px #00c38980}.position-losing{border-left:3px solid var(--red);position:relative}.position-losing:before{content:"";position:absolute;left:-7px;top:50%;transform:translateY(-50%);width:8px;height:8px;border-radius:50%;background:var(--red);box-shadow:0 0 8px #ff5c5c80}.chart-tooltip{background:var(--surface-el);border:1px solid var(--border);border-radius:8px;padding:10px 14px;font-family:var(--font-body);font-size:12px;color:var(--text);min-width:140px}.chart-tooltip-label{font-family:var(--font-body);font-size:11px;font-weight:600;color:var(--text-muted);text-transform:uppercase;letter-spacing:.05em;margin-bottom:6px}.chart-tooltip-row{display:flex;justify-content:space-between;gap:12px;margin-bottom:3px}.chart-tooltip-key{color:var(--text-muted)}.chart-tooltip-val{font-family:var(--font-mono);font-weight:700}.chart-stat-pill{display:inline-flex;align-items:center;gap:6px;padding:4px 12px;border-radius:20px;font-size:11px;font-family:var(--font-body)}.chart-stat-pill .pill-label{font-size:10px;font-weight:600;text-transform:uppercase;letter-spacing:.06em;color:var(--text-muted)}.chart-stat-pill .pill-value{font-family:var(--font-mono);font-weight:700;font-size:12px}.chart-stat-pill-positive{background:#00c3891a;border:1px solid rgba(0,195,137,.25)}.chart-stat-pill-negative{background:#ff5c5c1a;border:1px solid rgba(255,92,92,.25)}.chart-stat-pill-neutral{background:#6b72801a;border:1px solid rgba(107,114,128,.25)}.strategy-deep-dive{display:flex;flex-direction:column;gap:20px}.sdd-header{display:flex;align-items:center;gap:16px;padding:8px 0}.sdd-header-line{flex:1;height:1px;background:linear-gradient(90deg,transparent,var(--cyan),transparent);opacity:.4}.sdd-header-content{display:flex;align-items:center;gap:12px;flex-shrink:0}.sdd-section-card{animation:sdd-fadeUp .4s ease-out both}.sdd-section-card:nth-child(2){animation-delay:.05s}.sdd-section-card:nth-child(3){animation-delay:.1s}.sdd-section-card:nth-child(4){animation-delay:.15s}@keyframes sdd-fadeUp{0%{opacity:0;transform:translateY(12px)}to{opacity:1;transform:translateY(0)}}.sdd-stat-glow{position:relative}.sdd-stat-glow:after{content:"";position:absolute;top:-1px;right:-1px;bottom:-1px;left:-1px;border-radius:11px;background:conic-gradient(from 0deg,#00f0ff14,#00c38914,#00f0ff14);z-index:-1;opacity:0;transition:opacity .3s ease}.sdd-stat-glow:hover:after{opacity:1}.sdd-flow-row{display:flex;align-items:center;gap:6px;justify-content:center}.sdd-flow-step{flex:1;max-width:180px;padding:12px 10px;border-radius:10px;display:flex;align-items:center;justify-content:center;transition:transform .15s ease,box-shadow .15s ease}.sdd-flow-step:hover{transform:translateY(-2px);box-shadow:0 4px 16px #0000004d}.sdd-flow-arrow{display:flex;align-items:center;justify-content:center;flex-shrink:0;animation:sdd-arrow-pulse 2s ease-in-out infinite}@keyframes sdd-arrow-pulse{0%,to{opacity:.4;transform:translate(0)}50%{opacity:.8;transform:translate(2px)}}.sdd-trades-table{width:100%;border-collapse:collapse}.sdd-trades-table th{text-align:center;padding:8px 10px;font-size:.62rem;text-transform:uppercase;letter-spacing:.08em;color:var(--text-muted);font-family:var(--font-body);font-weight:600;border-bottom:1px solid var(--border);white-space:nowrap}.sdd-trades-table td{padding:10px;border-bottom:1px solid rgba(42,42,53,.5);font-size:.85rem;white-space:nowrap}.sdd-trades-table tbody tr{transition:background .15s ease}.sdd-trades-table tbody tr:hover td{background:#00f0ff0a}.sdd-trades-table tbody tr:nth-child(2n) td{background:#1c1c2466}.sdd-trades-table tbody tr:nth-child(2n):hover td{background:#00f0ff0a}.sdd-insights-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:14px}.sdd-insight-card{border-radius:12px;padding:18px 16px;transition:transform .15s ease,box-shadow .15s ease,border-color .15s ease}.sdd-insight-card:hover{transform:translateY(-2px);box-shadow:0 8px 24px #00000059,0 0 16px #00f0ff0f}@media (max-width: 1200px){.sdd-insights-grid{grid-template-columns:repeat(2,1fr)}.sdd-flow-row{flex-wrap:wrap}.sdd-flow-step{max-width:none}}@media (max-width: 768px){.sdd-insights-grid{grid-template-columns:1fr}}.hover\:text-gray-300:hover{--tw-text-opacity: 1;color:rgb(209 213 219 / var(--tw-text-opacity, 1))}.hover\:underline:hover{text-decoration-line:underline}.focus\:border-amber-500:focus{--tw-border-opacity: 1;border-color:rgb(245 158 11 / var(--tw-border-opacity, 1))}.focus\:outline-none:focus{outline:2px solid transparent;outline-offset:2px}.group:hover .group-hover\:opacity-100{opacity:1}@media (min-width: 640px){.sm\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}}@media (min-width: 768px){.md\:col-span-2{grid-column:span 2 / span 2}.md\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.md\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.md\:grid-cols-5{grid-template-columns:repeat(5,minmax(0,1fr))}.md\:grid-cols-6{grid-template-columns:repeat(6,minmax(0,1fr))}}@media (min-width: 1024px){.lg\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}}@media (min-width: 1280px){.xl\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}}
diff --git a/kalshi-dash/dist/assets/index-_K_ynK5-.js b/kalshi-dash/dist/assets/index-_K_ynK5-.js
deleted file mode 100644
index a2ae682..0000000
--- a/kalshi-dash/dist/assets/index-_K_ynK5-.js
+++ /dev/null
@@ -1,157 +0,0 @@
-function rN(e,t){for(var r=0;r<t.length;r++){const n=t[r];if(typeof n!="string"&&!Array.isArray(n)){for(const a in n)if(a!=="default"&&!(a in e)){const i=Object.getOwnPropertyDescriptor(n,a);i&&Object.defineProperty(e,a,i.get?i:{enumerable:!0,get:()=>n[a]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))n(a);new MutationObserver(a=>{for(const i of a)if(i.type==="childList")for(const s of i.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&n(s)}).observe(document,{childList:!0,subtree:!0});function r(a){const i={};return a.integrity&&(i.integrity=a.integrity),a.referrerPolicy&&(i.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?i.credentials="include":a.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function n(a){if(a.ep)return;a.ep=!0;const i=r(a);fetch(a.href,i)}})();var Ol=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function de(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Rj={exports:{}},rd={},Bj={exports:{}},ae={};/**
- * @license React
- * react.production.min.js
- *
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- */var ll=Symbol.for("react.element"),nN=Symbol.for("react.portal"),aN=Symbol.for("react.fragment"),iN=Symbol.for("react.strict_mode"),oN=Symbol.for("react.profiler"),sN=Symbol.for("react.provider"),lN=Symbol.for("react.context"),cN=Symbol.for("react.forward_ref"),uN=Symbol.for("react.suspense"),dN=Symbol.for("react.memo"),fN=Symbol.for("react.lazy"),rg=Symbol.iterator;function hN(e){return e===null||typeof e!="object"?null:(e=rg&&e[rg]||e["@@iterator"],typeof e=="function"?e:null)}var Fj={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},zj=Object.assign,Wj={};function eo(e,t,r){this.props=e,this.context=t,this.refs=Wj,this.updater=r||Fj}eo.prototype.isReactComponent={};eo.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")};eo.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function Uj(){}Uj.prototype=eo.prototype;function Km(e,t,r){this.props=e,this.context=t,this.refs=Wj,this.updater=r||Fj}var Vm=Km.prototype=new Uj;Vm.constructor=Km;zj(Vm,eo.prototype);Vm.isPureReactComponent=!0;var ng=Array.isArray,Hj=Object.prototype.hasOwnProperty,Gm={current:null},Kj={key:!0,ref:!0,__self:!0,__source:!0};function Vj(e,t,r){var n,a={},i=null,s=null;if(t!=null)for(n in t.ref!==void 0&&(s=t.ref),t.key!==void 0&&(i=""+t.key),t)Hj.call(t,n)&&!Kj.hasOwnProperty(n)&&(a[n]=t[n]);var l=arguments.length-2;if(l===1)a.children=r;else if(1<l){for(var c=Array(l),u=0;u<l;u++)c[u]=arguments[u+2];a.children=c}if(e&&e.defaultProps)for(n in l=e.defaultProps,l)a[n]===void 0&&(a[n]=l[n]);return{$$typeof:ll,type:e,key:i,ref:s,props:a,_owner:Gm.current}}function pN(e,t){return{$$typeof:ll,type:e.type,key:t,ref:e.ref,props:e.props,_owner:e._owner}}function Ym(e){return typeof e=="object"&&e!==null&&e.$$typeof===ll}function mN(e){var t={"=":"=0",":":"=2"};return"$"+e.replace(/[=:]/g,function(r){return t[r]})}var ag=/\/+/g;function hf(e,t){return typeof e=="object"&&e!==null&&e.key!=null?mN(""+e.key):t.toString(36)}function dc(e,t,r,n,a){var i=typeof e;(i==="undefined"||i==="boolean")&&(e=null);var s=!1;if(e===null)s=!0;else switch(i){case"string":case"number":s=!0;break;case"object":switch(e.$$typeof){case ll:case nN:s=!0}}if(s)return s=e,a=a(s),e=n===""?"."+hf(s,0):n,ng(a)?(r="",e!=null&&(r=e.replace(ag,"$&/")+"/"),dc(a,t,r,"",function(u){return u})):a!=null&&(Ym(a)&&(a=pN(a,r+(!a.key||s&&s.key===a.key?"":(""+a.key).replace(ag,"$&/")+"/")+e)),t.push(a)),1;if(s=0,n=n===""?".":n+":",ng(e))for(var l=0;l<e.length;l++){i=e[l];var c=n+hf(i,l);s+=dc(i,t,r,c,a)}else if(c=hN(e),typeof c=="function")for(e=c.call(e),l=0;!(i=e.next()).done;)i=i.value,c=n+hf(i,l++),s+=dc(i,t,r,c,a);else if(i==="object")throw t=String(e),Error("Objects are not valid as a React child (found: "+(t==="[object Object]"?"object with keys {"+Object.keys(e).join(", ")+"}":t)+"). If you meant to render a collection of children, use an array instead.");return s}function Nl(e,t,r){if(e==null)return e;var n=[],a=0;return dc(e,n,"","",function(i){return t.call(r,i,a++)}),n}function vN(e){if(e._status===-1){var t=e._result;t=t(),t.then(function(r){(e._status===0||e._status===-1)&&(e._status=1,e._result=r)},function(r){(e._status===0||e._status===-1)&&(e._status=2,e._result=r)}),e._status===-1&&(e._status=0,e._result=t)}if(e._status===1)return e._result.default;throw e._result}var wt={current:null},fc={transition:null},yN={ReactCurrentDispatcher:wt,ReactCurrentBatchConfig:fc,ReactCurrentOwner:Gm};function Gj(){throw Error("act(...) is not supported in production builds of React.")}ae.Children={map:Nl,forEach:function(e,t,r){Nl(e,function(){t.apply(this,arguments)},r)},count:function(e){var t=0;return Nl(e,function(){t++}),t},toArray:function(e){return Nl(e,function(t){return t})||[]},only:function(e){if(!Ym(e))throw Error("React.Children.only expected to receive a single React element child.");return e}};ae.Component=eo;ae.Fragment=aN;ae.Profiler=oN;ae.PureComponent=Km;ae.StrictMode=iN;ae.Suspense=uN;ae.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=yN;ae.act=Gj;ae.cloneElement=function(e,t,r){if(e==null)throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+e+".");var n=zj({},e.props),a=e.key,i=e.ref,s=e._owner;if(t!=null){if(t.ref!==void 0&&(i=t.ref,s=Gm.current),t.key!==void 0&&(a=""+t.key),e.type&&e.type.defaultProps)var l=e.type.defaultProps;for(c in t)Hj.call(t,c)&&!Kj.hasOwnProperty(c)&&(n[c]=t[c]===void 0&&l!==void 0?l[c]:t[c])}var c=arguments.length-2;if(c===1)n.children=r;else if(1<c){l=Array(c);for(var u=0;u<c;u++)l[u]=arguments[u+2];n.children=l}return{$$typeof:ll,type:e.type,key:a,ref:i,props:n,_owner:s}};ae.createContext=function(e){return e={$$typeof:lN,_currentValue:e,_currentValue2:e,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null},e.Provider={$$typeof:sN,_context:e},e.Consumer=e};ae.createElement=Vj;ae.createFactory=function(e){var t=Vj.bind(null,e);return t.type=e,t};ae.createRef=function(){return{current:null}};ae.forwardRef=function(e){return{$$typeof:cN,render:e}};ae.isValidElement=Ym;ae.lazy=function(e){return{$$typeof:fN,_payload:{_status:-1,_result:e},_init:vN}};ae.memo=function(e,t){return{$$typeof:dN,type:e,compare:t===void 0?null:t}};ae.startTransition=function(e){var t=fc.transition;fc.transition={};try{e()}finally{fc.transition=t}};ae.unstable_act=Gj;ae.useCallback=function(e,t){return wt.current.useCallback(e,t)};ae.useContext=function(e){return wt.current.useContext(e)};ae.useDebugValue=function(){};ae.useDeferredValue=function(e){return wt.current.useDeferredValue(e)};ae.useEffect=function(e,t){return wt.current.useEffect(e,t)};ae.useId=function(){return wt.current.useId()};ae.useImperativeHandle=function(e,t,r){return wt.current.useImperativeHandle(e,t,r)};ae.useInsertionEffect=function(e,t){return wt.current.useInsertionEffect(e,t)};ae.useLayoutEffect=function(e,t){return wt.current.useLayoutEffect(e,t)};ae.useMemo=function(e,t){return wt.current.useMemo(e,t)};ae.useReducer=function(e,t,r){return wt.current.useReducer(e,t,r)};ae.useRef=function(e){return wt.current.useRef(e)};ae.useState=function(e){return wt.current.useState(e)};ae.useSyncExternalStore=function(e,t,r){return wt.current.useSyncExternalStore(e,t,r)};ae.useTransition=function(){return wt.current.useTransition()};ae.version="18.3.1";Bj.exports=ae;var P=Bj.exports;const $=de(P),gN=rN({__proto__:null,default:$},[P]);/**
- * @license React
- * react-jsx-runtime.production.min.js
- *
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- */var xN=P,bN=Symbol.for("react.element"),jN=Symbol.for("react.fragment"),wN=Object.prototype.hasOwnProperty,SN=xN.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,_N={key:!0,ref:!0,__self:!0,__source:!0};function Yj(e,t,r){var n,a={},i=null,s=null;r!==void 0&&(i=""+r),t.key!==void 0&&(i=""+t.key),t.ref!==void 0&&(s=t.ref);for(n in t)wN.call(t,n)&&!_N.hasOwnProperty(n)&&(a[n]=t[n]);if(e&&e.defaultProps)for(n in t=e.defaultProps,t)a[n]===void 0&&(a[n]=t[n]);return{$$typeof:bN,type:e,key:i,ref:s,props:a,_owner:SN.current}}rd.Fragment=jN;rd.jsx=Yj;rd.jsxs=Yj;Rj.exports=rd;var o=Rj.exports,xh={},qj={exports:{}},Wt={},Xj={exports:{}},Qj={};/**
- * @license React
- * scheduler.production.min.js
- *
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- */(function(e){function t(I,R){var F=I.length;I.push(R);e:for(;0<F;){var K=F-1>>>1,z=I[K];if(0<a(z,R))I[K]=R,I[F]=z,F=K;else break e}}function r(I){return I.length===0?null:I[0]}function n(I){if(I.length===0)return null;var R=I[0],F=I.pop();if(F!==R){I[0]=F;e:for(var K=0,z=I.length,q=z>>>1;K<q;){var ie=2*(K+1)-1,he=I[ie],ge=ie+1,Qe=I[ge];if(0>a(he,F))ge<z&&0>a(Qe,he)?(I[K]=Qe,I[ge]=F,K=ge):(I[K]=he,I[ie]=F,K=ie);else if(ge<z&&0>a(Qe,F))I[K]=Qe,I[ge]=F,K=ge;else break e}}return R}function a(I,R){var F=I.sortIndex-R.sortIndex;return F!==0?F:I.id-R.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;e.unstable_now=function(){return i.now()}}else{var s=Date,l=s.now();e.unstable_now=function(){return s.now()-l}}var c=[],u=[],f=1,d=null,h=3,p=!1,g=!1,y=!1,b=typeof setTimeout=="function"?setTimeout:null,v=typeof clearTimeout=="function"?clearTimeout:null,m=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function x(I){for(var R=r(u);R!==null;){if(R.callback===null)n(u);else if(R.startTime<=I)n(u),R.sortIndex=R.expirationTime,t(c,R);else break;R=r(u)}}function S(I){if(y=!1,x(I),!g)if(r(c)!==null)g=!0,C(j);else{var R=r(u);R!==null&&M(S,R.startTime-I)}}function j(I,R){g=!1,y&&(y=!1,v(O),O=-1),p=!0;var F=h;try{for(x(R),d=r(c);d!==null&&(!(d.expirationTime>R)||I&&!E());){var K=d.callback;if(typeof K=="function"){d.callback=null,h=d.priorityLevel;var z=K(d.expirationTime<=R);R=e.unstable_now(),typeof z=="function"?d.callback=z:d===r(c)&&n(c),x(R)}else n(c);d=r(c)}if(d!==null)var q=!0;else{var ie=r(u);ie!==null&&M(S,ie.startTime-R),q=!1}return q}finally{d=null,h=F,p=!1}}var w=!1,_=null,O=-1,N=5,k=-1;function E(){return!(e.unstable_now()-k<N)}function T(){if(_!==null){var I=e.unstable_now();k=I;var R=!0;try{R=_(!0,I)}finally{R?D():(w=!1,_=null)}}else w=!1}var D;if(typeof m=="function")D=function(){m(T)};else if(typeof MessageChannel<"u"){var A=new MessageChannel,L=A.port2;A.port1.onmessage=T,D=function(){L.postMessage(null)}}else D=function(){b(T,0)};function C(I){_=I,w||(w=!0,D())}function M(I,R){O=b(function(){I(e.unstable_now())},R)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(I){I.callback=null},e.unstable_continueExecution=function(){g||p||(g=!0,C(j))},e.unstable_forceFrameRate=function(I){0>I||125<I?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):N=0<I?Math.floor(1e3/I):5},e.unstable_getCurrentPriorityLevel=function(){return h},e.unstable_getFirstCallbackNode=function(){return r(c)},e.unstable_next=function(I){switch(h){case 1:case 2:case 3:var R=3;break;default:R=h}var F=h;h=R;try{return I()}finally{h=F}},e.unstable_pauseExecution=function(){},e.unstable_requestPaint=function(){},e.unstable_runWithPriority=function(I,R){switch(I){case 1:case 2:case 3:case 4:case 5:break;default:I=3}var F=h;h=I;try{return R()}finally{h=F}},e.unstable_scheduleCallback=function(I,R,F){var K=e.unstable_now();switch(typeof F=="object"&&F!==null?(F=F.delay,F=typeof F=="number"&&0<F?K+F:K):F=K,I){case 1:var z=-1;break;case 2:z=250;break;case 5:z=1073741823;break;case 4:z=1e4;break;default:z=5e3}return z=F+z,I={id:f++,callback:R,priorityLevel:I,startTime:F,expirationTime:z,sortIndex:-1},F>K?(I.sortIndex=F,t(u,I),r(c)===null&&I===r(u)&&(y?(v(O),O=-1):y=!0,M(S,F-K))):(I.sortIndex=z,t(c,I),g||p||(g=!0,C(j))),I},e.unstable_shouldYield=E,e.unstable_wrapCallback=function(I){var R=h;return function(){var F=h;h=R;try{return I.apply(this,arguments)}finally{h=F}}}})(Qj);Xj.exports=Qj;var kN=Xj.exports;/**
- * @license React
- * react-dom.production.min.js
- *
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- */var ON=P,zt=kN;function H(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,r=1;r<arguments.length;r++)t+="&args[]="+encodeURIComponent(arguments[r]);return"Minified React error #"+e+"; visit "+t+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var Jj=new Set,ss={};function Pa(e,t){bi(e,t),bi(e+"Capture",t)}function bi(e,t){for(ss[e]=t,e=0;e<t.length;e++)Jj.add(t[e])}var Xr=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),bh=Object.prototype.hasOwnProperty,NN=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,ig={},og={};function PN(e){return bh.call(og,e)?!0:bh.call(ig,e)?!1:NN.test(e)?og[e]=!0:(ig[e]=!0,!1)}function AN(e,t,r,n){if(r!==null&&r.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return n?!1:r!==null?!r.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function CN(e,t,r,n){if(t===null||typeof t>"u"||AN(e,t,r,n))return!0;if(n)return!1;if(r!==null)switch(r.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function St(e,t,r,n,a,i,s){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=n,this.attributeNamespace=a,this.mustUseProperty=r,this.propertyName=e,this.type=t,this.sanitizeURL=i,this.removeEmptyString=s}var ut={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){ut[e]=new St(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];ut[t]=new St(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){ut[e]=new St(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){ut[e]=new St(e,2,!1,e,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){ut[e]=new St(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){ut[e]=new St(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){ut[e]=new St(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){ut[e]=new St(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){ut[e]=new St(e,5,!1,e.toLowerCase(),null,!1,!1)});var qm=/[\-:]([a-z])/g;function Xm(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(qm,Xm);ut[t]=new St(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(qm,Xm);ut[t]=new St(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(qm,Xm);ut[t]=new St(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){ut[e]=new St(e,1,!1,e.toLowerCase(),null,!1,!1)});ut.xlinkHref=new St("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){ut[e]=new St(e,1,!1,e.toLowerCase(),null,!0,!0)});function Qm(e,t,r,n){var a=ut.hasOwnProperty(t)?ut[t]:null;(a!==null?a.type!==0:n||!(2<t.length)||t[0]!=="o"&&t[0]!=="O"||t[1]!=="n"&&t[1]!=="N")&&(CN(t,r,a,n)&&(r=null),n||a===null?PN(t)&&(r===null?e.removeAttribute(t):e.setAttribute(t,""+r)):a.mustUseProperty?e[a.propertyName]=r===null?a.type===3?!1:"":r:(t=a.attributeName,n=a.attributeNamespace,r===null?e.removeAttribute(t):(a=a.type,r=a===3||a===4&&r===!0?"":""+r,n?e.setAttributeNS(n,t,r):e.setAttribute(t,r))))}var an=ON.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,Pl=Symbol.for("react.element"),Va=Symbol.for("react.portal"),Ga=Symbol.for("react.fragment"),Jm=Symbol.for("react.strict_mode"),jh=Symbol.for("react.profiler"),Zj=Symbol.for("react.provider"),ew=Symbol.for("react.context"),Zm=Symbol.for("react.forward_ref"),wh=Symbol.for("react.suspense"),Sh=Symbol.for("react.suspense_list"),ev=Symbol.for("react.memo"),hn=Symbol.for("react.lazy"),tw=Symbol.for("react.offscreen"),sg=Symbol.iterator;function xo(e){return e===null||typeof e!="object"?null:(e=sg&&e[sg]||e["@@iterator"],typeof e=="function"?e:null)}var $e=Object.assign,pf;function Bo(e){if(pf===void 0)try{throw Error()}catch(r){var t=r.stack.trim().match(/\n( *(at )?)/);pf=t&&t[1]||""}return`
-`+pf+e}var mf=!1;function vf(e,t){if(!e||mf)return"";mf=!0;var r=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(t)if(t=function(){throw Error()},Object.defineProperty(t.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(t,[])}catch(u){var n=u}Reflect.construct(e,[],t)}else{try{t.call()}catch(u){n=u}e.call(t.prototype)}else{try{throw Error()}catch(u){n=u}e()}}catch(u){if(u&&n&&typeof u.stack=="string"){for(var a=u.stack.split(`
-`),i=n.stack.split(`
-`),s=a.length-1,l=i.length-1;1<=s&&0<=l&&a[s]!==i[l];)l--;for(;1<=s&&0<=l;s--,l--)if(a[s]!==i[l]){if(s!==1||l!==1)do if(s--,l--,0>l||a[s]!==i[l]){var c=`
-`+a[s].replace(" at new "," at ");return e.displayName&&c.includes("<anonymous>")&&(c=c.replace("<anonymous>",e.displayName)),c}while(1<=s&&0<=l);break}}}finally{mf=!1,Error.prepareStackTrace=r}return(e=e?e.displayName||e.name:"")?Bo(e):""}function EN(e){switch(e.tag){case 5:return Bo(e.type);case 16:return Bo("Lazy");case 13:return Bo("Suspense");case 19:return Bo("SuspenseList");case 0:case 2:case 15:return e=vf(e.type,!1),e;case 11:return e=vf(e.type.render,!1),e;case 1:return e=vf(e.type,!0),e;default:return""}}function _h(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case Ga:return"Fragment";case Va:return"Portal";case jh:return"Profiler";case Jm:return"StrictMode";case wh:return"Suspense";case Sh:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case ew:return(e.displayName||"Context")+".Consumer";case Zj:return(e._context.displayName||"Context")+".Provider";case Zm:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case ev:return t=e.displayName||null,t!==null?t:_h(e.type)||"Memo";case hn:t=e._payload,e=e._init;try{return _h(e(t))}catch{}}return null}function $N(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return _h(t);case 8:return t===Jm?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function In(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function rw(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function TN(e){var t=rw(e)?"checked":"value",r=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),n=""+e[t];if(!e.hasOwnProperty(t)&&typeof r<"u"&&typeof r.get=="function"&&typeof r.set=="function"){var a=r.get,i=r.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return a.call(this)},set:function(s){n=""+s,i.call(this,s)}}),Object.defineProperty(e,t,{enumerable:r.enumerable}),{getValue:function(){return n},setValue:function(s){n=""+s},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function Al(e){e._valueTracker||(e._valueTracker=TN(e))}function nw(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var r=t.getValue(),n="";return e&&(n=rw(e)?e.checked?"true":"false":e.value),e=n,e!==r?(t.setValue(e),!0):!1}function Oc(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function kh(e,t){var r=t.checked;return $e({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:r??e._wrapperState.initialChecked})}function lg(e,t){var r=t.defaultValue==null?"":t.defaultValue,n=t.checked!=null?t.checked:t.defaultChecked;r=In(t.value!=null?t.value:r),e._wrapperState={initialChecked:n,initialValue:r,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function aw(e,t){t=t.checked,t!=null&&Qm(e,"checked",t,!1)}function Oh(e,t){aw(e,t);var r=In(t.value),n=t.type;if(r!=null)n==="number"?(r===0&&e.value===""||e.value!=r)&&(e.value=""+r):e.value!==""+r&&(e.value=""+r);else if(n==="submit"||n==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?Nh(e,t.type,r):t.hasOwnProperty("defaultValue")&&Nh(e,t.type,In(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function cg(e,t,r){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var n=t.type;if(!(n!=="submit"&&n!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,r||t===e.value||(e.value=t),e.defaultValue=t}r=e.name,r!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,r!==""&&(e.name=r)}function Nh(e,t,r){(t!=="number"||Oc(e.ownerDocument)!==e)&&(r==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+r&&(e.defaultValue=""+r))}var Fo=Array.isArray;function ci(e,t,r,n){if(e=e.options,t){t={};for(var a=0;a<r.length;a++)t["$"+r[a]]=!0;for(r=0;r<e.length;r++)a=t.hasOwnProperty("$"+e[r].value),e[r].selected!==a&&(e[r].selected=a),a&&n&&(e[r].defaultSelected=!0)}else{for(r=""+In(r),t=null,a=0;a<e.length;a++){if(e[a].value===r){e[a].selected=!0,n&&(e[a].defaultSelected=!0);return}t!==null||e[a].disabled||(t=e[a])}t!==null&&(t.selected=!0)}}function Ph(e,t){if(t.dangerouslySetInnerHTML!=null)throw Error(H(91));return $e({},t,{value:void 0,defaultValue:void 0,children:""+e._wrapperState.initialValue})}function ug(e,t){var r=t.value;if(r==null){if(r=t.children,t=t.defaultValue,r!=null){if(t!=null)throw Error(H(92));if(Fo(r)){if(1<r.length)throw Error(H(93));r=r[0]}t=r}t==null&&(t=""),r=t}e._wrapperState={initialValue:In(r)}}function iw(e,t){var r=In(t.value),n=In(t.defaultValue);r!=null&&(r=""+r,r!==e.value&&(e.value=r),t.defaultValue==null&&e.defaultValue!==r&&(e.defaultValue=r)),n!=null&&(e.defaultValue=""+n)}function dg(e){var t=e.textContent;t===e._wrapperState.initialValue&&t!==""&&t!==null&&(e.value=t)}function ow(e){switch(e){case"svg":return"http://www.w3.org/2000/svg";case"math":return"http://www.w3.org/1998/Math/MathML";default:return"http://www.w3.org/1999/xhtml"}}function Ah(e,t){return e==null||e==="http://www.w3.org/1999/xhtml"?ow(t):e==="http://www.w3.org/2000/svg"&&t==="foreignObject"?"http://www.w3.org/1999/xhtml":e}var Cl,sw=function(e){return typeof MSApp<"u"&&MSApp.execUnsafeLocalFunction?function(t,r,n,a){MSApp.execUnsafeLocalFunction(function(){return e(t,r,n,a)})}:e}(function(e,t){if(e.namespaceURI!=="http://www.w3.org/2000/svg"||"innerHTML"in e)e.innerHTML=t;else{for(Cl=Cl||document.createElement("div"),Cl.innerHTML="<svg>"+t.valueOf().toString()+"</svg>",t=Cl.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function ls(e,t){if(t){var r=e.firstChild;if(r&&r===e.lastChild&&r.nodeType===3){r.nodeValue=t;return}}e.textContent=t}var Vo={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},MN=["Webkit","ms","Moz","O"];Object.keys(Vo).forEach(function(e){MN.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),Vo[t]=Vo[e]})});function lw(e,t,r){return t==null||typeof t=="boolean"||t===""?"":r||typeof t!="number"||t===0||Vo.hasOwnProperty(e)&&Vo[e]?(""+t).trim():t+"px"}function cw(e,t){e=e.style;for(var r in t)if(t.hasOwnProperty(r)){var n=r.indexOf("--")===0,a=lw(r,t[r],n);r==="float"&&(r="cssFloat"),n?e.setProperty(r,a):e[r]=a}}var IN=$e({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function Ch(e,t){if(t){if(IN[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(H(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(H(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(H(61))}if(t.style!=null&&typeof t.style!="object")throw Error(H(62))}}function Eh(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var $h=null;function tv(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var Th=null,ui=null,di=null;function fg(e){if(e=dl(e)){if(typeof Th!="function")throw Error(H(280));var t=e.stateNode;t&&(t=sd(t),Th(e.stateNode,e.type,t))}}function uw(e){ui?di?di.push(e):di=[e]:ui=e}function dw(){if(ui){var e=ui,t=di;if(di=ui=null,fg(e),t)for(e=0;e<t.length;e++)fg(t[e])}}function fw(e,t){return e(t)}function hw(){}var yf=!1;function pw(e,t,r){if(yf)return e(t,r);yf=!0;try{return fw(e,t,r)}finally{yf=!1,(ui!==null||di!==null)&&(hw(),dw())}}function cs(e,t){var r=e.stateNode;if(r===null)return null;var n=sd(r);if(n===null)return null;r=n[t];e:switch(t){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(n=!n.disabled)||(e=e.type,n=!(e==="button"||e==="input"||e==="select"||e==="textarea")),e=!n;break e;default:e=!1}if(e)return null;if(r&&typeof r!="function")throw Error(H(231,t,typeof r));return r}var Mh=!1;if(Xr)try{var bo={};Object.defineProperty(bo,"passive",{get:function(){Mh=!0}}),window.addEventListener("test",bo,bo),window.removeEventListener("test",bo,bo)}catch{Mh=!1}function LN(e,t,r,n,a,i,s,l,c){var u=Array.prototype.slice.call(arguments,3);try{t.apply(r,u)}catch(f){this.onError(f)}}var Go=!1,Nc=null,Pc=!1,Ih=null,DN={onError:function(e){Go=!0,Nc=e}};function RN(e,t,r,n,a,i,s,l,c){Go=!1,Nc=null,LN.apply(DN,arguments)}function BN(e,t,r,n,a,i,s,l,c){if(RN.apply(this,arguments),Go){if(Go){var u=Nc;Go=!1,Nc=null}else throw Error(H(198));Pc||(Pc=!0,Ih=u)}}function Aa(e){var t=e,r=e;if(e.alternate)for(;t.return;)t=t.return;else{e=t;do t=e,t.flags&4098&&(r=t.return),e=t.return;while(e)}return t.tag===3?r:null}function mw(e){if(e.tag===13){var t=e.memoizedState;if(t===null&&(e=e.alternate,e!==null&&(t=e.memoizedState)),t!==null)return t.dehydrated}return null}function hg(e){if(Aa(e)!==e)throw Error(H(188))}function FN(e){var t=e.alternate;if(!t){if(t=Aa(e),t===null)throw Error(H(188));return t!==e?null:e}for(var r=e,n=t;;){var a=r.return;if(a===null)break;var i=a.alternate;if(i===null){if(n=a.return,n!==null){r=n;continue}break}if(a.child===i.child){for(i=a.child;i;){if(i===r)return hg(a),e;if(i===n)return hg(a),t;i=i.sibling}throw Error(H(188))}if(r.return!==n.return)r=a,n=i;else{for(var s=!1,l=a.child;l;){if(l===r){s=!0,r=a,n=i;break}if(l===n){s=!0,n=a,r=i;break}l=l.sibling}if(!s){for(l=i.child;l;){if(l===r){s=!0,r=i,n=a;break}if(l===n){s=!0,n=i,r=a;break}l=l.sibling}if(!s)throw Error(H(189))}}if(r.alternate!==n)throw Error(H(190))}if(r.tag!==3)throw Error(H(188));return r.stateNode.current===r?e:t}function vw(e){return e=FN(e),e!==null?yw(e):null}function yw(e){if(e.tag===5||e.tag===6)return e;for(e=e.child;e!==null;){var t=yw(e);if(t!==null)return t;e=e.sibling}return null}var gw=zt.unstable_scheduleCallback,pg=zt.unstable_cancelCallback,zN=zt.unstable_shouldYield,WN=zt.unstable_requestPaint,Le=zt.unstable_now,UN=zt.unstable_getCurrentPriorityLevel,rv=zt.unstable_ImmediatePriority,xw=zt.unstable_UserBlockingPriority,Ac=zt.unstable_NormalPriority,HN=zt.unstable_LowPriority,bw=zt.unstable_IdlePriority,nd=null,Pr=null;function KN(e){if(Pr&&typeof Pr.onCommitFiberRoot=="function")try{Pr.onCommitFiberRoot(nd,e,void 0,(e.current.flags&128)===128)}catch{}}var mr=Math.clz32?Math.clz32:YN,VN=Math.log,GN=Math.LN2;function YN(e){return e>>>=0,e===0?32:31-(VN(e)/GN|0)|0}var El=64,$l=4194304;function zo(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function Cc(e,t){var r=e.pendingLanes;if(r===0)return 0;var n=0,a=e.suspendedLanes,i=e.pingedLanes,s=r&268435455;if(s!==0){var l=s&~a;l!==0?n=zo(l):(i&=s,i!==0&&(n=zo(i)))}else s=r&~a,s!==0?n=zo(s):i!==0&&(n=zo(i));if(n===0)return 0;if(t!==0&&t!==n&&!(t&a)&&(a=n&-n,i=t&-t,a>=i||a===16&&(i&4194240)!==0))return t;if(n&4&&(n|=r&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=n;0<t;)r=31-mr(t),a=1<<r,n|=e[r],t&=~a;return n}function qN(e,t){switch(e){case 1:case 2:case 4:return t+250;case 8:case 16:case 32:case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return t+5e3;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return-1;case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function XN(e,t){for(var r=e.suspendedLanes,n=e.pingedLanes,a=e.expirationTimes,i=e.pendingLanes;0<i;){var s=31-mr(i),l=1<<s,c=a[s];c===-1?(!(l&r)||l&n)&&(a[s]=qN(l,t)):c<=t&&(e.expiredLanes|=l),i&=~l}}function Lh(e){return e=e.pendingLanes&-1073741825,e!==0?e:e&1073741824?1073741824:0}function jw(){var e=El;return El<<=1,!(El&4194240)&&(El=64),e}function gf(e){for(var t=[],r=0;31>r;r++)t.push(e);return t}function cl(e,t,r){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-mr(t),e[t]=r}function QN(e,t){var r=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var n=e.eventTimes;for(e=e.expirationTimes;0<r;){var a=31-mr(r),i=1<<a;t[a]=0,n[a]=-1,e[a]=-1,r&=~i}}function nv(e,t){var r=e.entangledLanes|=t;for(e=e.entanglements;r;){var n=31-mr(r),a=1<<n;a&t|e[n]&t&&(e[n]|=t),r&=~a}}var ue=0;function ww(e){return e&=-e,1<e?4<e?e&268435455?16:536870912:4:1}var Sw,av,_w,kw,Ow,Dh=!1,Tl=[],kn=null,On=null,Nn=null,us=new Map,ds=new Map,vn=[],JN="mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset submit".split(" ");function mg(e,t){switch(e){case"focusin":case"focusout":kn=null;break;case"dragenter":case"dragleave":On=null;break;case"mouseover":case"mouseout":Nn=null;break;case"pointerover":case"pointerout":us.delete(t.pointerId);break;case"gotpointercapture":case"lostpointercapture":ds.delete(t.pointerId)}}function jo(e,t,r,n,a,i){return e===null||e.nativeEvent!==i?(e={blockedOn:t,domEventName:r,eventSystemFlags:n,nativeEvent:i,targetContainers:[a]},t!==null&&(t=dl(t),t!==null&&av(t)),e):(e.eventSystemFlags|=n,t=e.targetContainers,a!==null&&t.indexOf(a)===-1&&t.push(a),e)}function ZN(e,t,r,n,a){switch(t){case"focusin":return kn=jo(kn,e,t,r,n,a),!0;case"dragenter":return On=jo(On,e,t,r,n,a),!0;case"mouseover":return Nn=jo(Nn,e,t,r,n,a),!0;case"pointerover":var i=a.pointerId;return us.set(i,jo(us.get(i)||null,e,t,r,n,a)),!0;case"gotpointercapture":return i=a.pointerId,ds.set(i,jo(ds.get(i)||null,e,t,r,n,a)),!0}return!1}function Nw(e){var t=na(e.target);if(t!==null){var r=Aa(t);if(r!==null){if(t=r.tag,t===13){if(t=mw(r),t!==null){e.blockedOn=t,Ow(e.priority,function(){_w(r)});return}}else if(t===3&&r.stateNode.current.memoizedState.isDehydrated){e.blockedOn=r.tag===3?r.stateNode.containerInfo:null;return}}}e.blockedOn=null}function hc(e){if(e.blockedOn!==null)return!1;for(var t=e.targetContainers;0<t.length;){var r=Rh(e.domEventName,e.eventSystemFlags,t[0],e.nativeEvent);if(r===null){r=e.nativeEvent;var n=new r.constructor(r.type,r);$h=n,r.target.dispatchEvent(n),$h=null}else return t=dl(r),t!==null&&av(t),e.blockedOn=r,!1;t.shift()}return!0}function vg(e,t,r){hc(e)&&r.delete(t)}function eP(){Dh=!1,kn!==null&&hc(kn)&&(kn=null),On!==null&&hc(On)&&(On=null),Nn!==null&&hc(Nn)&&(Nn=null),us.forEach(vg),ds.forEach(vg)}function wo(e,t){e.blockedOn===t&&(e.blockedOn=null,Dh||(Dh=!0,zt.unstable_scheduleCallback(zt.unstable_NormalPriority,eP)))}function fs(e){function t(a){return wo(a,e)}if(0<Tl.length){wo(Tl[0],e);for(var r=1;r<Tl.length;r++){var n=Tl[r];n.blockedOn===e&&(n.blockedOn=null)}}for(kn!==null&&wo(kn,e),On!==null&&wo(On,e),Nn!==null&&wo(Nn,e),us.forEach(t),ds.forEach(t),r=0;r<vn.length;r++)n=vn[r],n.blockedOn===e&&(n.blockedOn=null);for(;0<vn.length&&(r=vn[0],r.blockedOn===null);)Nw(r),r.blockedOn===null&&vn.shift()}var fi=an.ReactCurrentBatchConfig,Ec=!0;function tP(e,t,r,n){var a=ue,i=fi.transition;fi.transition=null;try{ue=1,iv(e,t,r,n)}finally{ue=a,fi.transition=i}}function rP(e,t,r,n){var a=ue,i=fi.transition;fi.transition=null;try{ue=4,iv(e,t,r,n)}finally{ue=a,fi.transition=i}}function iv(e,t,r,n){if(Ec){var a=Rh(e,t,r,n);if(a===null)Pf(e,t,n,$c,r),mg(e,n);else if(ZN(a,e,t,r,n))n.stopPropagation();else if(mg(e,n),t&4&&-1<JN.indexOf(e)){for(;a!==null;){var i=dl(a);if(i!==null&&Sw(i),i=Rh(e,t,r,n),i===null&&Pf(e,t,n,$c,r),i===a)break;a=i}a!==null&&n.stopPropagation()}else Pf(e,t,n,null,r)}}var $c=null;function Rh(e,t,r,n){if($c=null,e=tv(n),e=na(e),e!==null)if(t=Aa(e),t===null)e=null;else if(r=t.tag,r===13){if(e=mw(t),e!==null)return e;e=null}else if(r===3){if(t.stateNode.current.memoizedState.isDehydrated)return t.tag===3?t.stateNode.containerInfo:null;e=null}else t!==e&&(e=null);return $c=e,null}function Pw(e){switch(e){case"cancel":case"click":case"close":case"contextmenu":case"copy":case"cut":case"auxclick":case"dblclick":case"dragend":case"dragstart":case"drop":case"focusin":case"focusout":case"input":case"invalid":case"keydown":case"keypress":case"keyup":case"mousedown":case"mouseup":case"paste":case"pause":case"play":case"pointercancel":case"pointerdown":case"pointerup":case"ratechange":case"reset":case"resize":case"seeked":case"submit":case"touchcancel":case"touchend":case"touchstart":case"volumechange":case"change":case"selectionchange":case"textInput":case"compositionstart":case"compositionend":case"compositionupdate":case"beforeblur":case"afterblur":case"beforeinput":case"blur":case"fullscreenchange":case"focus":case"hashchange":case"popstate":case"select":case"selectstart":return 1;case"drag":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"mousemove":case"mouseout":case"mouseover":case"pointermove":case"pointerout":case"pointerover":case"scroll":case"toggle":case"touchmove":case"wheel":case"mouseenter":case"mouseleave":case"pointerenter":case"pointerleave":return 4;case"message":switch(UN()){case rv:return 1;case xw:return 4;case Ac:case HN:return 16;case bw:return 536870912;default:return 16}default:return 16}}var xn=null,ov=null,pc=null;function Aw(){if(pc)return pc;var e,t=ov,r=t.length,n,a="value"in xn?xn.value:xn.textContent,i=a.length;for(e=0;e<r&&t[e]===a[e];e++);var s=r-e;for(n=1;n<=s&&t[r-n]===a[i-n];n++);return pc=a.slice(e,1<n?1-n:void 0)}function mc(e){var t=e.keyCode;return"charCode"in e?(e=e.charCode,e===0&&t===13&&(e=13)):e=t,e===10&&(e=13),32<=e||e===13?e:0}function Ml(){return!0}function yg(){return!1}function Ut(e){function t(r,n,a,i,s){this._reactName=r,this._targetInst=a,this.type=n,this.nativeEvent=i,this.target=s,this.currentTarget=null;for(var l in e)e.hasOwnProperty(l)&&(r=e[l],this[l]=r?r(i):i[l]);return this.isDefaultPrevented=(i.defaultPrevented!=null?i.defaultPrevented:i.returnValue===!1)?Ml:yg,this.isPropagationStopped=yg,this}return $e(t.prototype,{preventDefault:function(){this.defaultPrevented=!0;var r=this.nativeEvent;r&&(r.preventDefault?r.preventDefault():typeof r.returnValue!="unknown"&&(r.returnValue=!1),this.isDefaultPrevented=Ml)},stopPropagation:function(){var r=this.nativeEvent;r&&(r.stopPropagation?r.stopPropagation():typeof r.cancelBubble!="unknown"&&(r.cancelBubble=!0),this.isPropagationStopped=Ml)},persist:function(){},isPersistent:Ml}),t}var to={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},sv=Ut(to),ul=$e({},to,{view:0,detail:0}),nP=Ut(ul),xf,bf,So,ad=$e({},ul,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:lv,button:0,buttons:0,relatedTarget:function(e){return e.relatedTarget===void 0?e.fromElement===e.srcElement?e.toElement:e.fromElement:e.relatedTarget},movementX:function(e){return"movementX"in e?e.movementX:(e!==So&&(So&&e.type==="mousemove"?(xf=e.screenX-So.screenX,bf=e.screenY-So.screenY):bf=xf=0,So=e),xf)},movementY:function(e){return"movementY"in e?e.movementY:bf}}),gg=Ut(ad),aP=$e({},ad,{dataTransfer:0}),iP=Ut(aP),oP=$e({},ul,{relatedTarget:0}),jf=Ut(oP),sP=$e({},to,{animationName:0,elapsedTime:0,pseudoElement:0}),lP=Ut(sP),cP=$e({},to,{clipboardData:function(e){return"clipboardData"in e?e.clipboardData:window.clipboardData}}),uP=Ut(cP),dP=$e({},to,{data:0}),xg=Ut(dP),fP={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},hP={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},pP={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function mP(e){var t=this.nativeEvent;return t.getModifierState?t.getModifierState(e):(e=pP[e])?!!t[e]:!1}function lv(){return mP}var vP=$e({},ul,{key:function(e){if(e.key){var t=fP[e.key]||e.key;if(t!=="Unidentified")return t}return e.type==="keypress"?(e=mc(e),e===13?"Enter":String.fromCharCode(e)):e.type==="keydown"||e.type==="keyup"?hP[e.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:lv,charCode:function(e){return e.type==="keypress"?mc(e):0},keyCode:function(e){return e.type==="keydown"||e.type==="keyup"?e.keyCode:0},which:function(e){return e.type==="keypress"?mc(e):e.type==="keydown"||e.type==="keyup"?e.keyCode:0}}),yP=Ut(vP),gP=$e({},ad,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),bg=Ut(gP),xP=$e({},ul,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:lv}),bP=Ut(xP),jP=$e({},to,{propertyName:0,elapsedTime:0,pseudoElement:0}),wP=Ut(jP),SP=$e({},ad,{deltaX:function(e){return"deltaX"in e?e.deltaX:"wheelDeltaX"in e?-e.wheelDeltaX:0},deltaY:function(e){return"deltaY"in e?e.deltaY:"wheelDeltaY"in e?-e.wheelDeltaY:"wheelDelta"in e?-e.wheelDelta:0},deltaZ:0,deltaMode:0}),_P=Ut(SP),kP=[9,13,27,32],cv=Xr&&"CompositionEvent"in window,Yo=null;Xr&&"documentMode"in document&&(Yo=document.documentMode);var OP=Xr&&"TextEvent"in window&&!Yo,Cw=Xr&&(!cv||Yo&&8<Yo&&11>=Yo),jg=" ",wg=!1;function Ew(e,t){switch(e){case"keyup":return kP.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function $w(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var Ya=!1;function NP(e,t){switch(e){case"compositionend":return $w(t);case"keypress":return t.which!==32?null:(wg=!0,jg);case"textInput":return e=t.data,e===jg&&wg?null:e;default:return null}}function PP(e,t){if(Ya)return e==="compositionend"||!cv&&Ew(e,t)?(e=Aw(),pc=ov=xn=null,Ya=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1<t.char.length)return t.char;if(t.which)return String.fromCharCode(t.which)}return null;case"compositionend":return Cw&&t.locale!=="ko"?null:t.data;default:return null}}var AP={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function Sg(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t==="input"?!!AP[e.type]:t==="textarea"}function Tw(e,t,r,n){uw(n),t=Tc(t,"onChange"),0<t.length&&(r=new sv("onChange","change",null,r,n),e.push({event:r,listeners:t}))}var qo=null,hs=null;function CP(e){Hw(e,0)}function id(e){var t=Qa(e);if(nw(t))return e}function EP(e,t){if(e==="change")return t}var Mw=!1;if(Xr){var wf;if(Xr){var Sf="oninput"in document;if(!Sf){var _g=document.createElement("div");_g.setAttribute("oninput","return;"),Sf=typeof _g.oninput=="function"}wf=Sf}else wf=!1;Mw=wf&&(!document.documentMode||9<document.documentMode)}function kg(){qo&&(qo.detachEvent("onpropertychange",Iw),hs=qo=null)}function Iw(e){if(e.propertyName==="value"&&id(hs)){var t=[];Tw(t,hs,e,tv(e)),pw(CP,t)}}function $P(e,t,r){e==="focusin"?(kg(),qo=t,hs=r,qo.attachEvent("onpropertychange",Iw)):e==="focusout"&&kg()}function TP(e){if(e==="selectionchange"||e==="keyup"||e==="keydown")return id(hs)}function MP(e,t){if(e==="click")return id(t)}function IP(e,t){if(e==="input"||e==="change")return id(t)}function LP(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var gr=typeof Object.is=="function"?Object.is:LP;function ps(e,t){if(gr(e,t))return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;var r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(n=0;n<r.length;n++){var a=r[n];if(!bh.call(t,a)||!gr(e[a],t[a]))return!1}return!0}function Og(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function Ng(e,t){var r=Og(e);e=0;for(var n;r;){if(r.nodeType===3){if(n=e+r.textContent.length,e<=t&&n>=t)return{node:r,offset:t-e};e=n}e:{for(;r;){if(r.nextSibling){r=r.nextSibling;break e}r=r.parentNode}r=void 0}r=Og(r)}}function Lw(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?Lw(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function Dw(){for(var e=window,t=Oc();t instanceof e.HTMLIFrameElement;){try{var r=typeof t.contentWindow.location.href=="string"}catch{r=!1}if(r)e=t.contentWindow;else break;t=Oc(e.document)}return t}function uv(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function DP(e){var t=Dw(),r=e.focusedElem,n=e.selectionRange;if(t!==r&&r&&r.ownerDocument&&Lw(r.ownerDocument.documentElement,r)){if(n!==null&&uv(r)){if(t=n.start,e=n.end,e===void 0&&(e=t),"selectionStart"in r)r.selectionStart=t,r.selectionEnd=Math.min(e,r.value.length);else if(e=(t=r.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var a=r.textContent.length,i=Math.min(n.start,a);n=n.end===void 0?i:Math.min(n.end,a),!e.extend&&i>n&&(a=n,n=i,i=a),a=Ng(r,i);var s=Ng(r,n);a&&s&&(e.rangeCount!==1||e.anchorNode!==a.node||e.anchorOffset!==a.offset||e.focusNode!==s.node||e.focusOffset!==s.offset)&&(t=t.createRange(),t.setStart(a.node,a.offset),e.removeAllRanges(),i>n?(e.addRange(t),e.extend(s.node,s.offset)):(t.setEnd(s.node,s.offset),e.addRange(t)))}}for(t=[],e=r;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof r.focus=="function"&&r.focus(),r=0;r<t.length;r++)e=t[r],e.element.scrollLeft=e.left,e.element.scrollTop=e.top}}var RP=Xr&&"documentMode"in document&&11>=document.documentMode,qa=null,Bh=null,Xo=null,Fh=!1;function Pg(e,t,r){var n=r.window===r?r.document:r.nodeType===9?r:r.ownerDocument;Fh||qa==null||qa!==Oc(n)||(n=qa,"selectionStart"in n&&uv(n)?n={start:n.selectionStart,end:n.selectionEnd}:(n=(n.ownerDocument&&n.ownerDocument.defaultView||window).getSelection(),n={anchorNode:n.anchorNode,anchorOffset:n.anchorOffset,focusNode:n.focusNode,focusOffset:n.focusOffset}),Xo&&ps(Xo,n)||(Xo=n,n=Tc(Bh,"onSelect"),0<n.length&&(t=new sv("onSelect","select",null,t,r),e.push({event:t,listeners:n}),t.target=qa)))}function Il(e,t){var r={};return r[e.toLowerCase()]=t.toLowerCase(),r["Webkit"+e]="webkit"+t,r["Moz"+e]="moz"+t,r}var Xa={animationend:Il("Animation","AnimationEnd"),animationiteration:Il("Animation","AnimationIteration"),animationstart:Il("Animation","AnimationStart"),transitionend:Il("Transition","TransitionEnd")},_f={},Rw={};Xr&&(Rw=document.createElement("div").style,"AnimationEvent"in window||(delete Xa.animationend.animation,delete Xa.animationiteration.animation,delete Xa.animationstart.animation),"TransitionEvent"in window||delete Xa.transitionend.transition);function od(e){if(_f[e])return _f[e];if(!Xa[e])return e;var t=Xa[e],r;for(r in t)if(t.hasOwnProperty(r)&&r in Rw)return _f[e]=t[r];return e}var Bw=od("animationend"),Fw=od("animationiteration"),zw=od("animationstart"),Ww=od("transitionend"),Uw=new Map,Ag="abort auxClick cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(" ");function Dn(e,t){Uw.set(e,t),Pa(t,[e])}for(var kf=0;kf<Ag.length;kf++){var Of=Ag[kf],BP=Of.toLowerCase(),FP=Of[0].toUpperCase()+Of.slice(1);Dn(BP,"on"+FP)}Dn(Bw,"onAnimationEnd");Dn(Fw,"onAnimationIteration");Dn(zw,"onAnimationStart");Dn("dblclick","onDoubleClick");Dn("focusin","onFocus");Dn("focusout","onBlur");Dn(Ww,"onTransitionEnd");bi("onMouseEnter",["mouseout","mouseover"]);bi("onMouseLeave",["mouseout","mouseover"]);bi("onPointerEnter",["pointerout","pointerover"]);bi("onPointerLeave",["pointerout","pointerover"]);Pa("onChange","change click focusin focusout input keydown keyup selectionchange".split(" "));Pa("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" "));Pa("onBeforeInput",["compositionend","keypress","textInput","paste"]);Pa("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" "));Pa("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" "));Pa("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var Wo="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),zP=new Set("cancel close invalid load scroll toggle".split(" ").concat(Wo));function Cg(e,t,r){var n=e.type||"unknown-event";e.currentTarget=r,BN(n,t,void 0,e),e.currentTarget=null}function Hw(e,t){t=(t&4)!==0;for(var r=0;r<e.length;r++){var n=e[r],a=n.event;n=n.listeners;e:{var i=void 0;if(t)for(var s=n.length-1;0<=s;s--){var l=n[s],c=l.instance,u=l.currentTarget;if(l=l.listener,c!==i&&a.isPropagationStopped())break e;Cg(a,l,u),i=c}else for(s=0;s<n.length;s++){if(l=n[s],c=l.instance,u=l.currentTarget,l=l.listener,c!==i&&a.isPropagationStopped())break e;Cg(a,l,u),i=c}}}if(Pc)throw e=Ih,Pc=!1,Ih=null,e}function we(e,t){var r=t[Kh];r===void 0&&(r=t[Kh]=new Set);var n=e+"__bubble";r.has(n)||(Kw(t,e,2,!1),r.add(n))}function Nf(e,t,r){var n=0;t&&(n|=4),Kw(r,e,n,t)}var Ll="_reactListening"+Math.random().toString(36).slice(2);function ms(e){if(!e[Ll]){e[Ll]=!0,Jj.forEach(function(r){r!=="selectionchange"&&(zP.has(r)||Nf(r,!1,e),Nf(r,!0,e))});var t=e.nodeType===9?e:e.ownerDocument;t===null||t[Ll]||(t[Ll]=!0,Nf("selectionchange",!1,t))}}function Kw(e,t,r,n){switch(Pw(t)){case 1:var a=tP;break;case 4:a=rP;break;default:a=iv}r=a.bind(null,t,r,e),a=void 0,!Mh||t!=="touchstart"&&t!=="touchmove"&&t!=="wheel"||(a=!0),n?a!==void 0?e.addEventListener(t,r,{capture:!0,passive:a}):e.addEventListener(t,r,!0):a!==void 0?e.addEventListener(t,r,{passive:a}):e.addEventListener(t,r,!1)}function Pf(e,t,r,n,a){var i=n;if(!(t&1)&&!(t&2)&&n!==null)e:for(;;){if(n===null)return;var s=n.tag;if(s===3||s===4){var l=n.stateNode.containerInfo;if(l===a||l.nodeType===8&&l.parentNode===a)break;if(s===4)for(s=n.return;s!==null;){var c=s.tag;if((c===3||c===4)&&(c=s.stateNode.containerInfo,c===a||c.nodeType===8&&c.parentNode===a))return;s=s.return}for(;l!==null;){if(s=na(l),s===null)return;if(c=s.tag,c===5||c===6){n=i=s;continue e}l=l.parentNode}}n=n.return}pw(function(){var u=i,f=tv(r),d=[];e:{var h=Uw.get(e);if(h!==void 0){var p=sv,g=e;switch(e){case"keypress":if(mc(r)===0)break e;case"keydown":case"keyup":p=yP;break;case"focusin":g="focus",p=jf;break;case"focusout":g="blur",p=jf;break;case"beforeblur":case"afterblur":p=jf;break;case"click":if(r.button===2)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":p=gg;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":p=iP;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":p=bP;break;case Bw:case Fw:case zw:p=lP;break;case Ww:p=wP;break;case"scroll":p=nP;break;case"wheel":p=_P;break;case"copy":case"cut":case"paste":p=uP;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":p=bg}var y=(t&4)!==0,b=!y&&e==="scroll",v=y?h!==null?h+"Capture":null:h;y=[];for(var m=u,x;m!==null;){x=m;var S=x.stateNode;if(x.tag===5&&S!==null&&(x=S,v!==null&&(S=cs(m,v),S!=null&&y.push(vs(m,S,x)))),b)break;m=m.return}0<y.length&&(h=new p(h,g,null,r,f),d.push({event:h,listeners:y}))}}if(!(t&7)){e:{if(h=e==="mouseover"||e==="pointerover",p=e==="mouseout"||e==="pointerout",h&&r!==$h&&(g=r.relatedTarget||r.fromElement)&&(na(g)||g[Qr]))break e;if((p||h)&&(h=f.window===f?f:(h=f.ownerDocument)?h.defaultView||h.parentWindow:window,p?(g=r.relatedTarget||r.toElement,p=u,g=g?na(g):null,g!==null&&(b=Aa(g),g!==b||g.tag!==5&&g.tag!==6)&&(g=null)):(p=null,g=u),p!==g)){if(y=gg,S="onMouseLeave",v="onMouseEnter",m="mouse",(e==="pointerout"||e==="pointerover")&&(y=bg,S="onPointerLeave",v="onPointerEnter",m="pointer"),b=p==null?h:Qa(p),x=g==null?h:Qa(g),h=new y(S,m+"leave",p,r,f),h.target=b,h.relatedTarget=x,S=null,na(f)===u&&(y=new y(v,m+"enter",g,r,f),y.target=x,y.relatedTarget=b,S=y),b=S,p&&g)t:{for(y=p,v=g,m=0,x=y;x;x=Da(x))m++;for(x=0,S=v;S;S=Da(S))x++;for(;0<m-x;)y=Da(y),m--;for(;0<x-m;)v=Da(v),x--;for(;m--;){if(y===v||v!==null&&y===v.alternate)break t;y=Da(y),v=Da(v)}y=null}else y=null;p!==null&&Eg(d,h,p,y,!1),g!==null&&b!==null&&Eg(d,b,g,y,!0)}}e:{if(h=u?Qa(u):window,p=h.nodeName&&h.nodeName.toLowerCase(),p==="select"||p==="input"&&h.type==="file")var j=EP;else if(Sg(h))if(Mw)j=IP;else{j=TP;var w=$P}else(p=h.nodeName)&&p.toLowerCase()==="input"&&(h.type==="checkbox"||h.type==="radio")&&(j=MP);if(j&&(j=j(e,u))){Tw(d,j,r,f);break e}w&&w(e,h,u),e==="focusout"&&(w=h._wrapperState)&&w.controlled&&h.type==="number"&&Nh(h,"number",h.value)}switch(w=u?Qa(u):window,e){case"focusin":(Sg(w)||w.contentEditable==="true")&&(qa=w,Bh=u,Xo=null);break;case"focusout":Xo=Bh=qa=null;break;case"mousedown":Fh=!0;break;case"contextmenu":case"mouseup":case"dragend":Fh=!1,Pg(d,r,f);break;case"selectionchange":if(RP)break;case"keydown":case"keyup":Pg(d,r,f)}var _;if(cv)e:{switch(e){case"compositionstart":var O="onCompositionStart";break e;case"compositionend":O="onCompositionEnd";break e;case"compositionupdate":O="onCompositionUpdate";break e}O=void 0}else Ya?Ew(e,r)&&(O="onCompositionEnd"):e==="keydown"&&r.keyCode===229&&(O="onCompositionStart");O&&(Cw&&r.locale!=="ko"&&(Ya||O!=="onCompositionStart"?O==="onCompositionEnd"&&Ya&&(_=Aw()):(xn=f,ov="value"in xn?xn.value:xn.textContent,Ya=!0)),w=Tc(u,O),0<w.length&&(O=new xg(O,e,null,r,f),d.push({event:O,listeners:w}),_?O.data=_:(_=$w(r),_!==null&&(O.data=_)))),(_=OP?NP(e,r):PP(e,r))&&(u=Tc(u,"onBeforeInput"),0<u.length&&(f=new xg("onBeforeInput","beforeinput",null,r,f),d.push({event:f,listeners:u}),f.data=_))}Hw(d,t)})}function vs(e,t,r){return{instance:e,listener:t,currentTarget:r}}function Tc(e,t){for(var r=t+"Capture",n=[];e!==null;){var a=e,i=a.stateNode;a.tag===5&&i!==null&&(a=i,i=cs(e,r),i!=null&&n.unshift(vs(e,i,a)),i=cs(e,t),i!=null&&n.push(vs(e,i,a))),e=e.return}return n}function Da(e){if(e===null)return null;do e=e.return;while(e&&e.tag!==5);return e||null}function Eg(e,t,r,n,a){for(var i=t._reactName,s=[];r!==null&&r!==n;){var l=r,c=l.alternate,u=l.stateNode;if(c!==null&&c===n)break;l.tag===5&&u!==null&&(l=u,a?(c=cs(r,i),c!=null&&s.unshift(vs(r,c,l))):a||(c=cs(r,i),c!=null&&s.push(vs(r,c,l)))),r=r.return}s.length!==0&&e.push({event:t,listeners:s})}var WP=/\r\n?/g,UP=/\u0000|\uFFFD/g;function $g(e){return(typeof e=="string"?e:""+e).replace(WP,`
-`).replace(UP,"")}function Dl(e,t,r){if(t=$g(t),$g(e)!==t&&r)throw Error(H(425))}function Mc(){}var zh=null,Wh=null;function Uh(e,t){return e==="textarea"||e==="noscript"||typeof t.children=="string"||typeof t.children=="number"||typeof t.dangerouslySetInnerHTML=="object"&&t.dangerouslySetInnerHTML!==null&&t.dangerouslySetInnerHTML.__html!=null}var Hh=typeof setTimeout=="function"?setTimeout:void 0,HP=typeof clearTimeout=="function"?clearTimeout:void 0,Tg=typeof Promise=="function"?Promise:void 0,KP=typeof queueMicrotask=="function"?queueMicrotask:typeof Tg<"u"?function(e){return Tg.resolve(null).then(e).catch(VP)}:Hh;function VP(e){setTimeout(function(){throw e})}function Af(e,t){var r=t,n=0;do{var a=r.nextSibling;if(e.removeChild(r),a&&a.nodeType===8)if(r=a.data,r==="/$"){if(n===0){e.removeChild(a),fs(t);return}n--}else r!=="$"&&r!=="$?"&&r!=="$!"||n++;r=a}while(r);fs(t)}function Pn(e){for(;e!=null;e=e.nextSibling){var t=e.nodeType;if(t===1||t===3)break;if(t===8){if(t=e.data,t==="$"||t==="$!"||t==="$?")break;if(t==="/$")return null}}return e}function Mg(e){e=e.previousSibling;for(var t=0;e;){if(e.nodeType===8){var r=e.data;if(r==="$"||r==="$!"||r==="$?"){if(t===0)return e;t--}else r==="/$"&&t++}e=e.previousSibling}return null}var ro=Math.random().toString(36).slice(2),kr="__reactFiber$"+ro,ys="__reactProps$"+ro,Qr="__reactContainer$"+ro,Kh="__reactEvents$"+ro,GP="__reactListeners$"+ro,YP="__reactHandles$"+ro;function na(e){var t=e[kr];if(t)return t;for(var r=e.parentNode;r;){if(t=r[Qr]||r[kr]){if(r=t.alternate,t.child!==null||r!==null&&r.child!==null)for(e=Mg(e);e!==null;){if(r=e[kr])return r;e=Mg(e)}return t}e=r,r=e.parentNode}return null}function dl(e){return e=e[kr]||e[Qr],!e||e.tag!==5&&e.tag!==6&&e.tag!==13&&e.tag!==3?null:e}function Qa(e){if(e.tag===5||e.tag===6)return e.stateNode;throw Error(H(33))}function sd(e){return e[ys]||null}var Vh=[],Ja=-1;function Rn(e){return{current:e}}function ke(e){0>Ja||(e.current=Vh[Ja],Vh[Ja]=null,Ja--)}function je(e,t){Ja++,Vh[Ja]=e.current,e.current=t}var Ln={},vt=Rn(Ln),At=Rn(!1),ya=Ln;function ji(e,t){var r=e.type.contextTypes;if(!r)return Ln;var n=e.stateNode;if(n&&n.__reactInternalMemoizedUnmaskedChildContext===t)return n.__reactInternalMemoizedMaskedChildContext;var a={},i;for(i in r)a[i]=t[i];return n&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=a),a}function Ct(e){return e=e.childContextTypes,e!=null}function Ic(){ke(At),ke(vt)}function Ig(e,t,r){if(vt.current!==Ln)throw Error(H(168));je(vt,t),je(At,r)}function Vw(e,t,r){var n=e.stateNode;if(t=t.childContextTypes,typeof n.getChildContext!="function")return r;n=n.getChildContext();for(var a in n)if(!(a in t))throw Error(H(108,$N(e)||"Unknown",a));return $e({},r,n)}function Lc(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||Ln,ya=vt.current,je(vt,e),je(At,At.current),!0}function Lg(e,t,r){var n=e.stateNode;if(!n)throw Error(H(169));r?(e=Vw(e,t,ya),n.__reactInternalMemoizedMergedChildContext=e,ke(At),ke(vt),je(vt,e)):ke(At),je(At,r)}var zr=null,ld=!1,Cf=!1;function Gw(e){zr===null?zr=[e]:zr.push(e)}function qP(e){ld=!0,Gw(e)}function Bn(){if(!Cf&&zr!==null){Cf=!0;var e=0,t=ue;try{var r=zr;for(ue=1;e<r.length;e++){var n=r[e];do n=n(!0);while(n!==null)}zr=null,ld=!1}catch(a){throw zr!==null&&(zr=zr.slice(e+1)),gw(rv,Bn),a}finally{ue=t,Cf=!1}}return null}var Za=[],ei=0,Dc=null,Rc=0,Gt=[],Yt=0,ga=null,Wr=1,Ur="";function Qn(e,t){Za[ei++]=Rc,Za[ei++]=Dc,Dc=e,Rc=t}function Yw(e,t,r){Gt[Yt++]=Wr,Gt[Yt++]=Ur,Gt[Yt++]=ga,ga=e;var n=Wr;e=Ur;var a=32-mr(n)-1;n&=~(1<<a),r+=1;var i=32-mr(t)+a;if(30<i){var s=a-a%5;i=(n&(1<<s)-1).toString(32),n>>=s,a-=s,Wr=1<<32-mr(t)+a|r<<a|n,Ur=i+e}else Wr=1<<i|r<<a|n,Ur=e}function dv(e){e.return!==null&&(Qn(e,1),Yw(e,1,0))}function fv(e){for(;e===Dc;)Dc=Za[--ei],Za[ei]=null,Rc=Za[--ei],Za[ei]=null;for(;e===ga;)ga=Gt[--Yt],Gt[Yt]=null,Ur=Gt[--Yt],Gt[Yt]=null,Wr=Gt[--Yt],Gt[Yt]=null}var Rt=null,Dt=null,Ne=!1,hr=null;function qw(e,t){var r=Xt(5,null,null,0);r.elementType="DELETED",r.stateNode=t,r.return=e,t=e.deletions,t===null?(e.deletions=[r],e.flags|=16):t.push(r)}function Dg(e,t){switch(e.tag){case 5:var r=e.type;return t=t.nodeType!==1||r.toLowerCase()!==t.nodeName.toLowerCase()?null:t,t!==null?(e.stateNode=t,Rt=e,Dt=Pn(t.firstChild),!0):!1;case 6:return t=e.pendingProps===""||t.nodeType!==3?null:t,t!==null?(e.stateNode=t,Rt=e,Dt=null,!0):!1;case 13:return t=t.nodeType!==8?null:t,t!==null?(r=ga!==null?{id:Wr,overflow:Ur}:null,e.memoizedState={dehydrated:t,treeContext:r,retryLane:1073741824},r=Xt(18,null,null,0),r.stateNode=t,r.return=e,e.child=r,Rt=e,Dt=null,!0):!1;default:return!1}}function Gh(e){return(e.mode&1)!==0&&(e.flags&128)===0}function Yh(e){if(Ne){var t=Dt;if(t){var r=t;if(!Dg(e,t)){if(Gh(e))throw Error(H(418));t=Pn(r.nextSibling);var n=Rt;t&&Dg(e,t)?qw(n,r):(e.flags=e.flags&-4097|2,Ne=!1,Rt=e)}}else{if(Gh(e))throw Error(H(418));e.flags=e.flags&-4097|2,Ne=!1,Rt=e}}}function Rg(e){for(e=e.return;e!==null&&e.tag!==5&&e.tag!==3&&e.tag!==13;)e=e.return;Rt=e}function Rl(e){if(e!==Rt)return!1;if(!Ne)return Rg(e),Ne=!0,!1;var t;if((t=e.tag!==3)&&!(t=e.tag!==5)&&(t=e.type,t=t!=="head"&&t!=="body"&&!Uh(e.type,e.memoizedProps)),t&&(t=Dt)){if(Gh(e))throw Xw(),Error(H(418));for(;t;)qw(e,t),t=Pn(t.nextSibling)}if(Rg(e),e.tag===13){if(e=e.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(H(317));e:{for(e=e.nextSibling,t=0;e;){if(e.nodeType===8){var r=e.data;if(r==="/$"){if(t===0){Dt=Pn(e.nextSibling);break e}t--}else r!=="$"&&r!=="$!"&&r!=="$?"||t++}e=e.nextSibling}Dt=null}}else Dt=Rt?Pn(e.stateNode.nextSibling):null;return!0}function Xw(){for(var e=Dt;e;)e=Pn(e.nextSibling)}function wi(){Dt=Rt=null,Ne=!1}function hv(e){hr===null?hr=[e]:hr.push(e)}var XP=an.ReactCurrentBatchConfig;function _o(e,t,r){if(e=r.ref,e!==null&&typeof e!="function"&&typeof e!="object"){if(r._owner){if(r=r._owner,r){if(r.tag!==1)throw Error(H(309));var n=r.stateNode}if(!n)throw Error(H(147,e));var a=n,i=""+e;return t!==null&&t.ref!==null&&typeof t.ref=="function"&&t.ref._stringRef===i?t.ref:(t=function(s){var l=a.refs;s===null?delete l[i]:l[i]=s},t._stringRef=i,t)}if(typeof e!="string")throw Error(H(284));if(!r._owner)throw Error(H(290,e))}return e}function Bl(e,t){throw e=Object.prototype.toString.call(t),Error(H(31,e==="[object Object]"?"object with keys {"+Object.keys(t).join(", ")+"}":e))}function Bg(e){var t=e._init;return t(e._payload)}function Qw(e){function t(v,m){if(e){var x=v.deletions;x===null?(v.deletions=[m],v.flags|=16):x.push(m)}}function r(v,m){if(!e)return null;for(;m!==null;)t(v,m),m=m.sibling;return null}function n(v,m){for(v=new Map;m!==null;)m.key!==null?v.set(m.key,m):v.set(m.index,m),m=m.sibling;return v}function a(v,m){return v=$n(v,m),v.index=0,v.sibling=null,v}function i(v,m,x){return v.index=x,e?(x=v.alternate,x!==null?(x=x.index,x<m?(v.flags|=2,m):x):(v.flags|=2,m)):(v.flags|=1048576,m)}function s(v){return e&&v.alternate===null&&(v.flags|=2),v}function l(v,m,x,S){return m===null||m.tag!==6?(m=Df(x,v.mode,S),m.return=v,m):(m=a(m,x),m.return=v,m)}function c(v,m,x,S){var j=x.type;return j===Ga?f(v,m,x.props.children,S,x.key):m!==null&&(m.elementType===j||typeof j=="object"&&j!==null&&j.$$typeof===hn&&Bg(j)===m.type)?(S=a(m,x.props),S.ref=_o(v,m,x),S.return=v,S):(S=wc(x.type,x.key,x.props,null,v.mode,S),S.ref=_o(v,m,x),S.return=v,S)}function u(v,m,x,S){return m===null||m.tag!==4||m.stateNode.containerInfo!==x.containerInfo||m.stateNode.implementation!==x.implementation?(m=Rf(x,v.mode,S),m.return=v,m):(m=a(m,x.children||[]),m.return=v,m)}function f(v,m,x,S,j){return m===null||m.tag!==7?(m=ha(x,v.mode,S,j),m.return=v,m):(m=a(m,x),m.return=v,m)}function d(v,m,x){if(typeof m=="string"&&m!==""||typeof m=="number")return m=Df(""+m,v.mode,x),m.return=v,m;if(typeof m=="object"&&m!==null){switch(m.$$typeof){case Pl:return x=wc(m.type,m.key,m.props,null,v.mode,x),x.ref=_o(v,null,m),x.return=v,x;case Va:return m=Rf(m,v.mode,x),m.return=v,m;case hn:var S=m._init;return d(v,S(m._payload),x)}if(Fo(m)||xo(m))return m=ha(m,v.mode,x,null),m.return=v,m;Bl(v,m)}return null}function h(v,m,x,S){var j=m!==null?m.key:null;if(typeof x=="string"&&x!==""||typeof x=="number")return j!==null?null:l(v,m,""+x,S);if(typeof x=="object"&&x!==null){switch(x.$$typeof){case Pl:return x.key===j?c(v,m,x,S):null;case Va:return x.key===j?u(v,m,x,S):null;case hn:return j=x._init,h(v,m,j(x._payload),S)}if(Fo(x)||xo(x))return j!==null?null:f(v,m,x,S,null);Bl(v,x)}return null}function p(v,m,x,S,j){if(typeof S=="string"&&S!==""||typeof S=="number")return v=v.get(x)||null,l(m,v,""+S,j);if(typeof S=="object"&&S!==null){switch(S.$$typeof){case Pl:return v=v.get(S.key===null?x:S.key)||null,c(m,v,S,j);case Va:return v=v.get(S.key===null?x:S.key)||null,u(m,v,S,j);case hn:var w=S._init;return p(v,m,x,w(S._payload),j)}if(Fo(S)||xo(S))return v=v.get(x)||null,f(m,v,S,j,null);Bl(m,S)}return null}function g(v,m,x,S){for(var j=null,w=null,_=m,O=m=0,N=null;_!==null&&O<x.length;O++){_.index>O?(N=_,_=null):N=_.sibling;var k=h(v,_,x[O],S);if(k===null){_===null&&(_=N);break}e&&_&&k.alternate===null&&t(v,_),m=i(k,m,O),w===null?j=k:w.sibling=k,w=k,_=N}if(O===x.length)return r(v,_),Ne&&Qn(v,O),j;if(_===null){for(;O<x.length;O++)_=d(v,x[O],S),_!==null&&(m=i(_,m,O),w===null?j=_:w.sibling=_,w=_);return Ne&&Qn(v,O),j}for(_=n(v,_);O<x.length;O++)N=p(_,v,O,x[O],S),N!==null&&(e&&N.alternate!==null&&_.delete(N.key===null?O:N.key),m=i(N,m,O),w===null?j=N:w.sibling=N,w=N);return e&&_.forEach(function(E){return t(v,E)}),Ne&&Qn(v,O),j}function y(v,m,x,S){var j=xo(x);if(typeof j!="function")throw Error(H(150));if(x=j.call(x),x==null)throw Error(H(151));for(var w=j=null,_=m,O=m=0,N=null,k=x.next();_!==null&&!k.done;O++,k=x.next()){_.index>O?(N=_,_=null):N=_.sibling;var E=h(v,_,k.value,S);if(E===null){_===null&&(_=N);break}e&&_&&E.alternate===null&&t(v,_),m=i(E,m,O),w===null?j=E:w.sibling=E,w=E,_=N}if(k.done)return r(v,_),Ne&&Qn(v,O),j;if(_===null){for(;!k.done;O++,k=x.next())k=d(v,k.value,S),k!==null&&(m=i(k,m,O),w===null?j=k:w.sibling=k,w=k);return Ne&&Qn(v,O),j}for(_=n(v,_);!k.done;O++,k=x.next())k=p(_,v,O,k.value,S),k!==null&&(e&&k.alternate!==null&&_.delete(k.key===null?O:k.key),m=i(k,m,O),w===null?j=k:w.sibling=k,w=k);return e&&_.forEach(function(T){return t(v,T)}),Ne&&Qn(v,O),j}function b(v,m,x,S){if(typeof x=="object"&&x!==null&&x.type===Ga&&x.key===null&&(x=x.props.children),typeof x=="object"&&x!==null){switch(x.$$typeof){case Pl:e:{for(var j=x.key,w=m;w!==null;){if(w.key===j){if(j=x.type,j===Ga){if(w.tag===7){r(v,w.sibling),m=a(w,x.props.children),m.return=v,v=m;break e}}else if(w.elementType===j||typeof j=="object"&&j!==null&&j.$$typeof===hn&&Bg(j)===w.type){r(v,w.sibling),m=a(w,x.props),m.ref=_o(v,w,x),m.return=v,v=m;break e}r(v,w);break}else t(v,w);w=w.sibling}x.type===Ga?(m=ha(x.props.children,v.mode,S,x.key),m.return=v,v=m):(S=wc(x.type,x.key,x.props,null,v.mode,S),S.ref=_o(v,m,x),S.return=v,v=S)}return s(v);case Va:e:{for(w=x.key;m!==null;){if(m.key===w)if(m.tag===4&&m.stateNode.containerInfo===x.containerInfo&&m.stateNode.implementation===x.implementation){r(v,m.sibling),m=a(m,x.children||[]),m.return=v,v=m;break e}else{r(v,m);break}else t(v,m);m=m.sibling}m=Rf(x,v.mode,S),m.return=v,v=m}return s(v);case hn:return w=x._init,b(v,m,w(x._payload),S)}if(Fo(x))return g(v,m,x,S);if(xo(x))return y(v,m,x,S);Bl(v,x)}return typeof x=="string"&&x!==""||typeof x=="number"?(x=""+x,m!==null&&m.tag===6?(r(v,m.sibling),m=a(m,x),m.return=v,v=m):(r(v,m),m=Df(x,v.mode,S),m.return=v,v=m),s(v)):r(v,m)}return b}var Si=Qw(!0),Jw=Qw(!1),Bc=Rn(null),Fc=null,ti=null,pv=null;function mv(){pv=ti=Fc=null}function vv(e){var t=Bc.current;ke(Bc),e._currentValue=t}function qh(e,t,r){for(;e!==null;){var n=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,n!==null&&(n.childLanes|=t)):n!==null&&(n.childLanes&t)!==t&&(n.childLanes|=t),e===r)break;e=e.return}}function hi(e,t){Fc=e,pv=ti=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(Nt=!0),e.firstContext=null)}function Zt(e){var t=e._currentValue;if(pv!==e)if(e={context:e,memoizedValue:t,next:null},ti===null){if(Fc===null)throw Error(H(308));ti=e,Fc.dependencies={lanes:0,firstContext:e}}else ti=ti.next=e;return t}var aa=null;function yv(e){aa===null?aa=[e]:aa.push(e)}function Zw(e,t,r,n){var a=t.interleaved;return a===null?(r.next=r,yv(t)):(r.next=a.next,a.next=r),t.interleaved=r,Jr(e,n)}function Jr(e,t){e.lanes|=t;var r=e.alternate;for(r!==null&&(r.lanes|=t),r=e,e=e.return;e!==null;)e.childLanes|=t,r=e.alternate,r!==null&&(r.childLanes|=t),r=e,e=e.return;return r.tag===3?r.stateNode:null}var pn=!1;function gv(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function e2(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function Gr(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function An(e,t,r){var n=e.updateQueue;if(n===null)return null;if(n=n.shared,se&2){var a=n.pending;return a===null?t.next=t:(t.next=a.next,a.next=t),n.pending=t,Jr(e,r)}return a=n.interleaved,a===null?(t.next=t,yv(n)):(t.next=a.next,a.next=t),n.interleaved=t,Jr(e,r)}function vc(e,t,r){if(t=t.updateQueue,t!==null&&(t=t.shared,(r&4194240)!==0)){var n=t.lanes;n&=e.pendingLanes,r|=n,t.lanes=r,nv(e,r)}}function Fg(e,t){var r=e.updateQueue,n=e.alternate;if(n!==null&&(n=n.updateQueue,r===n)){var a=null,i=null;if(r=r.firstBaseUpdate,r!==null){do{var s={eventTime:r.eventTime,lane:r.lane,tag:r.tag,payload:r.payload,callback:r.callback,next:null};i===null?a=i=s:i=i.next=s,r=r.next}while(r!==null);i===null?a=i=t:i=i.next=t}else a=i=t;r={baseState:n.baseState,firstBaseUpdate:a,lastBaseUpdate:i,shared:n.shared,effects:n.effects},e.updateQueue=r;return}e=r.lastBaseUpdate,e===null?r.firstBaseUpdate=t:e.next=t,r.lastBaseUpdate=t}function zc(e,t,r,n){var a=e.updateQueue;pn=!1;var i=a.firstBaseUpdate,s=a.lastBaseUpdate,l=a.shared.pending;if(l!==null){a.shared.pending=null;var c=l,u=c.next;c.next=null,s===null?i=u:s.next=u,s=c;var f=e.alternate;f!==null&&(f=f.updateQueue,l=f.lastBaseUpdate,l!==s&&(l===null?f.firstBaseUpdate=u:l.next=u,f.lastBaseUpdate=c))}if(i!==null){var d=a.baseState;s=0,f=u=c=null,l=i;do{var h=l.lane,p=l.eventTime;if((n&h)===h){f!==null&&(f=f.next={eventTime:p,lane:0,tag:l.tag,payload:l.payload,callback:l.callback,next:null});e:{var g=e,y=l;switch(h=t,p=r,y.tag){case 1:if(g=y.payload,typeof g=="function"){d=g.call(p,d,h);break e}d=g;break e;case 3:g.flags=g.flags&-65537|128;case 0:if(g=y.payload,h=typeof g=="function"?g.call(p,d,h):g,h==null)break e;d=$e({},d,h);break e;case 2:pn=!0}}l.callback!==null&&l.lane!==0&&(e.flags|=64,h=a.effects,h===null?a.effects=[l]:h.push(l))}else p={eventTime:p,lane:h,tag:l.tag,payload:l.payload,callback:l.callback,next:null},f===null?(u=f=p,c=d):f=f.next=p,s|=h;if(l=l.next,l===null){if(l=a.shared.pending,l===null)break;h=l,l=h.next,h.next=null,a.lastBaseUpdate=h,a.shared.pending=null}}while(!0);if(f===null&&(c=d),a.baseState=c,a.firstBaseUpdate=u,a.lastBaseUpdate=f,t=a.shared.interleaved,t!==null){a=t;do s|=a.lane,a=a.next;while(a!==t)}else i===null&&(a.shared.lanes=0);ba|=s,e.lanes=s,e.memoizedState=d}}function zg(e,t,r){if(e=t.effects,t.effects=null,e!==null)for(t=0;t<e.length;t++){var n=e[t],a=n.callback;if(a!==null){if(n.callback=null,n=r,typeof a!="function")throw Error(H(191,a));a.call(n)}}}var fl={},Ar=Rn(fl),gs=Rn(fl),xs=Rn(fl);function ia(e){if(e===fl)throw Error(H(174));return e}function xv(e,t){switch(je(xs,t),je(gs,e),je(Ar,fl),e=t.nodeType,e){case 9:case 11:t=(t=t.documentElement)?t.namespaceURI:Ah(null,"");break;default:e=e===8?t.parentNode:t,t=e.namespaceURI||null,e=e.tagName,t=Ah(t,e)}ke(Ar),je(Ar,t)}function _i(){ke(Ar),ke(gs),ke(xs)}function t2(e){ia(xs.current);var t=ia(Ar.current),r=Ah(t,e.type);t!==r&&(je(gs,e),je(Ar,r))}function bv(e){gs.current===e&&(ke(Ar),ke(gs))}var Ce=Rn(0);function Wc(e){for(var t=e;t!==null;){if(t.tag===13){var r=t.memoizedState;if(r!==null&&(r=r.dehydrated,r===null||r.data==="$?"||r.data==="$!"))return t}else if(t.tag===19&&t.memoizedProps.revealOrder!==void 0){if(t.flags&128)return t}else if(t.child!==null){t.child.return=t,t=t.child;continue}if(t===e)break;for(;t.sibling===null;){if(t.return===null||t.return===e)return null;t=t.return}t.sibling.return=t.return,t=t.sibling}return null}var Ef=[];function jv(){for(var e=0;e<Ef.length;e++)Ef[e]._workInProgressVersionPrimary=null;Ef.length=0}var yc=an.ReactCurrentDispatcher,$f=an.ReactCurrentBatchConfig,xa=0,Ee=null,Ve=null,et=null,Uc=!1,Qo=!1,bs=0,QP=0;function dt(){throw Error(H(321))}function wv(e,t){if(t===null)return!1;for(var r=0;r<t.length&&r<e.length;r++)if(!gr(e[r],t[r]))return!1;return!0}function Sv(e,t,r,n,a,i){if(xa=i,Ee=t,t.memoizedState=null,t.updateQueue=null,t.lanes=0,yc.current=e===null||e.memoizedState===null?tA:rA,e=r(n,a),Qo){i=0;do{if(Qo=!1,bs=0,25<=i)throw Error(H(301));i+=1,et=Ve=null,t.updateQueue=null,yc.current=nA,e=r(n,a)}while(Qo)}if(yc.current=Hc,t=Ve!==null&&Ve.next!==null,xa=0,et=Ve=Ee=null,Uc=!1,t)throw Error(H(300));return e}function _v(){var e=bs!==0;return bs=0,e}function _r(){var e={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return et===null?Ee.memoizedState=et=e:et=et.next=e,et}function er(){if(Ve===null){var e=Ee.alternate;e=e!==null?e.memoizedState:null}else e=Ve.next;var t=et===null?Ee.memoizedState:et.next;if(t!==null)et=t,Ve=e;else{if(e===null)throw Error(H(310));Ve=e,e={memoizedState:Ve.memoizedState,baseState:Ve.baseState,baseQueue:Ve.baseQueue,queue:Ve.queue,next:null},et===null?Ee.memoizedState=et=e:et=et.next=e}return et}function js(e,t){return typeof t=="function"?t(e):t}function Tf(e){var t=er(),r=t.queue;if(r===null)throw Error(H(311));r.lastRenderedReducer=e;var n=Ve,a=n.baseQueue,i=r.pending;if(i!==null){if(a!==null){var s=a.next;a.next=i.next,i.next=s}n.baseQueue=a=i,r.pending=null}if(a!==null){i=a.next,n=n.baseState;var l=s=null,c=null,u=i;do{var f=u.lane;if((xa&f)===f)c!==null&&(c=c.next={lane:0,action:u.action,hasEagerState:u.hasEagerState,eagerState:u.eagerState,next:null}),n=u.hasEagerState?u.eagerState:e(n,u.action);else{var d={lane:f,action:u.action,hasEagerState:u.hasEagerState,eagerState:u.eagerState,next:null};c===null?(l=c=d,s=n):c=c.next=d,Ee.lanes|=f,ba|=f}u=u.next}while(u!==null&&u!==i);c===null?s=n:c.next=l,gr(n,t.memoizedState)||(Nt=!0),t.memoizedState=n,t.baseState=s,t.baseQueue=c,r.lastRenderedState=n}if(e=r.interleaved,e!==null){a=e;do i=a.lane,Ee.lanes|=i,ba|=i,a=a.next;while(a!==e)}else a===null&&(r.lanes=0);return[t.memoizedState,r.dispatch]}function Mf(e){var t=er(),r=t.queue;if(r===null)throw Error(H(311));r.lastRenderedReducer=e;var n=r.dispatch,a=r.pending,i=t.memoizedState;if(a!==null){r.pending=null;var s=a=a.next;do i=e(i,s.action),s=s.next;while(s!==a);gr(i,t.memoizedState)||(Nt=!0),t.memoizedState=i,t.baseQueue===null&&(t.baseState=i),r.lastRenderedState=i}return[i,n]}function r2(){}function n2(e,t){var r=Ee,n=er(),a=t(),i=!gr(n.memoizedState,a);if(i&&(n.memoizedState=a,Nt=!0),n=n.queue,kv(o2.bind(null,r,n,e),[e]),n.getSnapshot!==t||i||et!==null&&et.memoizedState.tag&1){if(r.flags|=2048,ws(9,i2.bind(null,r,n,a,t),void 0,null),nt===null)throw Error(H(349));xa&30||a2(r,t,a)}return a}function a2(e,t,r){e.flags|=16384,e={getSnapshot:t,value:r},t=Ee.updateQueue,t===null?(t={lastEffect:null,stores:null},Ee.updateQueue=t,t.stores=[e]):(r=t.stores,r===null?t.stores=[e]:r.push(e))}function i2(e,t,r,n){t.value=r,t.getSnapshot=n,s2(t)&&l2(e)}function o2(e,t,r){return r(function(){s2(t)&&l2(e)})}function s2(e){var t=e.getSnapshot;e=e.value;try{var r=t();return!gr(e,r)}catch{return!0}}function l2(e){var t=Jr(e,1);t!==null&&vr(t,e,1,-1)}function Wg(e){var t=_r();return typeof e=="function"&&(e=e()),t.memoizedState=t.baseState=e,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:js,lastRenderedState:e},t.queue=e,e=e.dispatch=eA.bind(null,Ee,e),[t.memoizedState,e]}function ws(e,t,r,n){return e={tag:e,create:t,destroy:r,deps:n,next:null},t=Ee.updateQueue,t===null?(t={lastEffect:null,stores:null},Ee.updateQueue=t,t.lastEffect=e.next=e):(r=t.lastEffect,r===null?t.lastEffect=e.next=e:(n=r.next,r.next=e,e.next=n,t.lastEffect=e)),e}function c2(){return er().memoizedState}function gc(e,t,r,n){var a=_r();Ee.flags|=e,a.memoizedState=ws(1|t,r,void 0,n===void 0?null:n)}function cd(e,t,r,n){var a=er();n=n===void 0?null:n;var i=void 0;if(Ve!==null){var s=Ve.memoizedState;if(i=s.destroy,n!==null&&wv(n,s.deps)){a.memoizedState=ws(t,r,i,n);return}}Ee.flags|=e,a.memoizedState=ws(1|t,r,i,n)}function Ug(e,t){return gc(8390656,8,e,t)}function kv(e,t){return cd(2048,8,e,t)}function u2(e,t){return cd(4,2,e,t)}function d2(e,t){return cd(4,4,e,t)}function f2(e,t){if(typeof t=="function")return e=e(),t(e),function(){t(null)};if(t!=null)return e=e(),t.current=e,function(){t.current=null}}function h2(e,t,r){return r=r!=null?r.concat([e]):null,cd(4,4,f2.bind(null,t,e),r)}function Ov(){}function p2(e,t){var r=er();t=t===void 0?null:t;var n=r.memoizedState;return n!==null&&t!==null&&wv(t,n[1])?n[0]:(r.memoizedState=[e,t],e)}function m2(e,t){var r=er();t=t===void 0?null:t;var n=r.memoizedState;return n!==null&&t!==null&&wv(t,n[1])?n[0]:(e=e(),r.memoizedState=[e,t],e)}function v2(e,t,r){return xa&21?(gr(r,t)||(r=jw(),Ee.lanes|=r,ba|=r,e.baseState=!0),t):(e.baseState&&(e.baseState=!1,Nt=!0),e.memoizedState=r)}function JP(e,t){var r=ue;ue=r!==0&&4>r?r:4,e(!0);var n=$f.transition;$f.transition={};try{e(!1),t()}finally{ue=r,$f.transition=n}}function y2(){return er().memoizedState}function ZP(e,t,r){var n=En(e);if(r={lane:n,action:r,hasEagerState:!1,eagerState:null,next:null},g2(e))x2(t,r);else if(r=Zw(e,t,r,n),r!==null){var a=jt();vr(r,e,n,a),b2(r,t,n)}}function eA(e,t,r){var n=En(e),a={lane:n,action:r,hasEagerState:!1,eagerState:null,next:null};if(g2(e))x2(t,a);else{var i=e.alternate;if(e.lanes===0&&(i===null||i.lanes===0)&&(i=t.lastRenderedReducer,i!==null))try{var s=t.lastRenderedState,l=i(s,r);if(a.hasEagerState=!0,a.eagerState=l,gr(l,s)){var c=t.interleaved;c===null?(a.next=a,yv(t)):(a.next=c.next,c.next=a),t.interleaved=a;return}}catch{}finally{}r=Zw(e,t,a,n),r!==null&&(a=jt(),vr(r,e,n,a),b2(r,t,n))}}function g2(e){var t=e.alternate;return e===Ee||t!==null&&t===Ee}function x2(e,t){Qo=Uc=!0;var r=e.pending;r===null?t.next=t:(t.next=r.next,r.next=t),e.pending=t}function b2(e,t,r){if(r&4194240){var n=t.lanes;n&=e.pendingLanes,r|=n,t.lanes=r,nv(e,r)}}var Hc={readContext:Zt,useCallback:dt,useContext:dt,useEffect:dt,useImperativeHandle:dt,useInsertionEffect:dt,useLayoutEffect:dt,useMemo:dt,useReducer:dt,useRef:dt,useState:dt,useDebugValue:dt,useDeferredValue:dt,useTransition:dt,useMutableSource:dt,useSyncExternalStore:dt,useId:dt,unstable_isNewReconciler:!1},tA={readContext:Zt,useCallback:function(e,t){return _r().memoizedState=[e,t===void 0?null:t],e},useContext:Zt,useEffect:Ug,useImperativeHandle:function(e,t,r){return r=r!=null?r.concat([e]):null,gc(4194308,4,f2.bind(null,t,e),r)},useLayoutEffect:function(e,t){return gc(4194308,4,e,t)},useInsertionEffect:function(e,t){return gc(4,2,e,t)},useMemo:function(e,t){var r=_r();return t=t===void 0?null:t,e=e(),r.memoizedState=[e,t],e},useReducer:function(e,t,r){var n=_r();return t=r!==void 0?r(t):t,n.memoizedState=n.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},n.queue=e,e=e.dispatch=ZP.bind(null,Ee,e),[n.memoizedState,e]},useRef:function(e){var t=_r();return e={current:e},t.memoizedState=e},useState:Wg,useDebugValue:Ov,useDeferredValue:function(e){return _r().memoizedState=e},useTransition:function(){var e=Wg(!1),t=e[0];return e=JP.bind(null,e[1]),_r().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,r){var n=Ee,a=_r();if(Ne){if(r===void 0)throw Error(H(407));r=r()}else{if(r=t(),nt===null)throw Error(H(349));xa&30||a2(n,t,r)}a.memoizedState=r;var i={value:r,getSnapshot:t};return a.queue=i,Ug(o2.bind(null,n,i,e),[e]),n.flags|=2048,ws(9,i2.bind(null,n,i,r,t),void 0,null),r},useId:function(){var e=_r(),t=nt.identifierPrefix;if(Ne){var r=Ur,n=Wr;r=(n&~(1<<32-mr(n)-1)).toString(32)+r,t=":"+t+"R"+r,r=bs++,0<r&&(t+="H"+r.toString(32)),t+=":"}else r=QP++,t=":"+t+"r"+r.toString(32)+":";return e.memoizedState=t},unstable_isNewReconciler:!1},rA={readContext:Zt,useCallback:p2,useContext:Zt,useEffect:kv,useImperativeHandle:h2,useInsertionEffect:u2,useLayoutEffect:d2,useMemo:m2,useReducer:Tf,useRef:c2,useState:function(){return Tf(js)},useDebugValue:Ov,useDeferredValue:function(e){var t=er();return v2(t,Ve.memoizedState,e)},useTransition:function(){var e=Tf(js)[0],t=er().memoizedState;return[e,t]},useMutableSource:r2,useSyncExternalStore:n2,useId:y2,unstable_isNewReconciler:!1},nA={readContext:Zt,useCallback:p2,useContext:Zt,useEffect:kv,useImperativeHandle:h2,useInsertionEffect:u2,useLayoutEffect:d2,useMemo:m2,useReducer:Mf,useRef:c2,useState:function(){return Mf(js)},useDebugValue:Ov,useDeferredValue:function(e){var t=er();return Ve===null?t.memoizedState=e:v2(t,Ve.memoizedState,e)},useTransition:function(){var e=Mf(js)[0],t=er().memoizedState;return[e,t]},useMutableSource:r2,useSyncExternalStore:n2,useId:y2,unstable_isNewReconciler:!1};function ur(e,t){if(e&&e.defaultProps){t=$e({},t),e=e.defaultProps;for(var r in e)t[r]===void 0&&(t[r]=e[r]);return t}return t}function Xh(e,t,r,n){t=e.memoizedState,r=r(n,t),r=r==null?t:$e({},t,r),e.memoizedState=r,e.lanes===0&&(e.updateQueue.baseState=r)}var ud={isMounted:function(e){return(e=e._reactInternals)?Aa(e)===e:!1},enqueueSetState:function(e,t,r){e=e._reactInternals;var n=jt(),a=En(e),i=Gr(n,a);i.payload=t,r!=null&&(i.callback=r),t=An(e,i,a),t!==null&&(vr(t,e,a,n),vc(t,e,a))},enqueueReplaceState:function(e,t,r){e=e._reactInternals;var n=jt(),a=En(e),i=Gr(n,a);i.tag=1,i.payload=t,r!=null&&(i.callback=r),t=An(e,i,a),t!==null&&(vr(t,e,a,n),vc(t,e,a))},enqueueForceUpdate:function(e,t){e=e._reactInternals;var r=jt(),n=En(e),a=Gr(r,n);a.tag=2,t!=null&&(a.callback=t),t=An(e,a,n),t!==null&&(vr(t,e,n,r),vc(t,e,n))}};function Hg(e,t,r,n,a,i,s){return e=e.stateNode,typeof e.shouldComponentUpdate=="function"?e.shouldComponentUpdate(n,i,s):t.prototype&&t.prototype.isPureReactComponent?!ps(r,n)||!ps(a,i):!0}function j2(e,t,r){var n=!1,a=Ln,i=t.contextType;return typeof i=="object"&&i!==null?i=Zt(i):(a=Ct(t)?ya:vt.current,n=t.contextTypes,i=(n=n!=null)?ji(e,a):Ln),t=new t(r,i),e.memoizedState=t.state!==null&&t.state!==void 0?t.state:null,t.updater=ud,e.stateNode=t,t._reactInternals=e,n&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=a,e.__reactInternalMemoizedMaskedChildContext=i),t}function Kg(e,t,r,n){e=t.state,typeof t.componentWillReceiveProps=="function"&&t.componentWillReceiveProps(r,n),typeof t.UNSAFE_componentWillReceiveProps=="function"&&t.UNSAFE_componentWillReceiveProps(r,n),t.state!==e&&ud.enqueueReplaceState(t,t.state,null)}function Qh(e,t,r,n){var a=e.stateNode;a.props=r,a.state=e.memoizedState,a.refs={},gv(e);var i=t.contextType;typeof i=="object"&&i!==null?a.context=Zt(i):(i=Ct(t)?ya:vt.current,a.context=ji(e,i)),a.state=e.memoizedState,i=t.getDerivedStateFromProps,typeof i=="function"&&(Xh(e,t,i,r),a.state=e.memoizedState),typeof t.getDerivedStateFromProps=="function"||typeof a.getSnapshotBeforeUpdate=="function"||typeof a.UNSAFE_componentWillMount!="function"&&typeof a.componentWillMount!="function"||(t=a.state,typeof a.componentWillMount=="function"&&a.componentWillMount(),typeof a.UNSAFE_componentWillMount=="function"&&a.UNSAFE_componentWillMount(),t!==a.state&&ud.enqueueReplaceState(a,a.state,null),zc(e,r,a,n),a.state=e.memoizedState),typeof a.componentDidMount=="function"&&(e.flags|=4194308)}function ki(e,t){try{var r="",n=t;do r+=EN(n),n=n.return;while(n);var a=r}catch(i){a=`
-Error generating stack: `+i.message+`
-`+i.stack}return{value:e,source:t,stack:a,digest:null}}function If(e,t,r){return{value:e,source:null,stack:r??null,digest:t??null}}function Jh(e,t){try{console.error(t.value)}catch(r){setTimeout(function(){throw r})}}var aA=typeof WeakMap=="function"?WeakMap:Map;function w2(e,t,r){r=Gr(-1,r),r.tag=3,r.payload={element:null};var n=t.value;return r.callback=function(){Vc||(Vc=!0,lp=n),Jh(e,t)},r}function S2(e,t,r){r=Gr(-1,r),r.tag=3;var n=e.type.getDerivedStateFromError;if(typeof n=="function"){var a=t.value;r.payload=function(){return n(a)},r.callback=function(){Jh(e,t)}}var i=e.stateNode;return i!==null&&typeof i.componentDidCatch=="function"&&(r.callback=function(){Jh(e,t),typeof n!="function"&&(Cn===null?Cn=new Set([this]):Cn.add(this));var s=t.stack;this.componentDidCatch(t.value,{componentStack:s!==null?s:""})}),r}function Vg(e,t,r){var n=e.pingCache;if(n===null){n=e.pingCache=new aA;var a=new Set;n.set(t,a)}else a=n.get(t),a===void 0&&(a=new Set,n.set(t,a));a.has(r)||(a.add(r),e=gA.bind(null,e,t,r),t.then(e,e))}function Gg(e){do{var t;if((t=e.tag===13)&&(t=e.memoizedState,t=t!==null?t.dehydrated!==null:!0),t)return e;e=e.return}while(e!==null);return null}function Yg(e,t,r,n,a){return e.mode&1?(e.flags|=65536,e.lanes=a,e):(e===t?e.flags|=65536:(e.flags|=128,r.flags|=131072,r.flags&=-52805,r.tag===1&&(r.alternate===null?r.tag=17:(t=Gr(-1,1),t.tag=2,An(r,t,1))),r.lanes|=1),e)}var iA=an.ReactCurrentOwner,Nt=!1;function gt(e,t,r,n){t.child=e===null?Jw(t,null,r,n):Si(t,e.child,r,n)}function qg(e,t,r,n,a){r=r.render;var i=t.ref;return hi(t,a),n=Sv(e,t,r,n,i,a),r=_v(),e!==null&&!Nt?(t.updateQueue=e.updateQueue,t.flags&=-2053,e.lanes&=~a,Zr(e,t,a)):(Ne&&r&&dv(t),t.flags|=1,gt(e,t,n,a),t.child)}function Xg(e,t,r,n,a){if(e===null){var i=r.type;return typeof i=="function"&&!Mv(i)&&i.defaultProps===void 0&&r.compare===null&&r.defaultProps===void 0?(t.tag=15,t.type=i,_2(e,t,i,n,a)):(e=wc(r.type,null,n,t,t.mode,a),e.ref=t.ref,e.return=t,t.child=e)}if(i=e.child,!(e.lanes&a)){var s=i.memoizedProps;if(r=r.compare,r=r!==null?r:ps,r(s,n)&&e.ref===t.ref)return Zr(e,t,a)}return t.flags|=1,e=$n(i,n),e.ref=t.ref,e.return=t,t.child=e}function _2(e,t,r,n,a){if(e!==null){var i=e.memoizedProps;if(ps(i,n)&&e.ref===t.ref)if(Nt=!1,t.pendingProps=n=i,(e.lanes&a)!==0)e.flags&131072&&(Nt=!0);else return t.lanes=e.lanes,Zr(e,t,a)}return Zh(e,t,r,n,a)}function k2(e,t,r){var n=t.pendingProps,a=n.children,i=e!==null?e.memoizedState:null;if(n.mode==="hidden")if(!(t.mode&1))t.memoizedState={baseLanes:0,cachePool:null,transitions:null},je(ni,Mt),Mt|=r;else{if(!(r&1073741824))return e=i!==null?i.baseLanes|r:r,t.lanes=t.childLanes=1073741824,t.memoizedState={baseLanes:e,cachePool:null,transitions:null},t.updateQueue=null,je(ni,Mt),Mt|=e,null;t.memoizedState={baseLanes:0,cachePool:null,transitions:null},n=i!==null?i.baseLanes:r,je(ni,Mt),Mt|=n}else i!==null?(n=i.baseLanes|r,t.memoizedState=null):n=r,je(ni,Mt),Mt|=n;return gt(e,t,a,r),t.child}function O2(e,t){var r=t.ref;(e===null&&r!==null||e!==null&&e.ref!==r)&&(t.flags|=512,t.flags|=2097152)}function Zh(e,t,r,n,a){var i=Ct(r)?ya:vt.current;return i=ji(t,i),hi(t,a),r=Sv(e,t,r,n,i,a),n=_v(),e!==null&&!Nt?(t.updateQueue=e.updateQueue,t.flags&=-2053,e.lanes&=~a,Zr(e,t,a)):(Ne&&n&&dv(t),t.flags|=1,gt(e,t,r,a),t.child)}function Qg(e,t,r,n,a){if(Ct(r)){var i=!0;Lc(t)}else i=!1;if(hi(t,a),t.stateNode===null)xc(e,t),j2(t,r,n),Qh(t,r,n,a),n=!0;else if(e===null){var s=t.stateNode,l=t.memoizedProps;s.props=l;var c=s.context,u=r.contextType;typeof u=="object"&&u!==null?u=Zt(u):(u=Ct(r)?ya:vt.current,u=ji(t,u));var f=r.getDerivedStateFromProps,d=typeof f=="function"||typeof s.getSnapshotBeforeUpdate=="function";d||typeof s.UNSAFE_componentWillReceiveProps!="function"&&typeof s.componentWillReceiveProps!="function"||(l!==n||c!==u)&&Kg(t,s,n,u),pn=!1;var h=t.memoizedState;s.state=h,zc(t,n,s,a),c=t.memoizedState,l!==n||h!==c||At.current||pn?(typeof f=="function"&&(Xh(t,r,f,n),c=t.memoizedState),(l=pn||Hg(t,r,l,n,h,c,u))?(d||typeof s.UNSAFE_componentWillMount!="function"&&typeof s.componentWillMount!="function"||(typeof s.componentWillMount=="function"&&s.componentWillMount(),typeof s.UNSAFE_componentWillMount=="function"&&s.UNSAFE_componentWillMount()),typeof s.componentDidMount=="function"&&(t.flags|=4194308)):(typeof s.componentDidMount=="function"&&(t.flags|=4194308),t.memoizedProps=n,t.memoizedState=c),s.props=n,s.state=c,s.context=u,n=l):(typeof s.componentDidMount=="function"&&(t.flags|=4194308),n=!1)}else{s=t.stateNode,e2(e,t),l=t.memoizedProps,u=t.type===t.elementType?l:ur(t.type,l),s.props=u,d=t.pendingProps,h=s.context,c=r.contextType,typeof c=="object"&&c!==null?c=Zt(c):(c=Ct(r)?ya:vt.current,c=ji(t,c));var p=r.getDerivedStateFromProps;(f=typeof p=="function"||typeof s.getSnapshotBeforeUpdate=="function")||typeof s.UNSAFE_componentWillReceiveProps!="function"&&typeof s.componentWillReceiveProps!="function"||(l!==d||h!==c)&&Kg(t,s,n,c),pn=!1,h=t.memoizedState,s.state=h,zc(t,n,s,a);var g=t.memoizedState;l!==d||h!==g||At.current||pn?(typeof p=="function"&&(Xh(t,r,p,n),g=t.memoizedState),(u=pn||Hg(t,r,u,n,h,g,c)||!1)?(f||typeof s.UNSAFE_componentWillUpdate!="function"&&typeof s.componentWillUpdate!="function"||(typeof s.componentWillUpdate=="function"&&s.componentWillUpdate(n,g,c),typeof s.UNSAFE_componentWillUpdate=="function"&&s.UNSAFE_componentWillUpdate(n,g,c)),typeof s.componentDidUpdate=="function"&&(t.flags|=4),typeof s.getSnapshotBeforeUpdate=="function"&&(t.flags|=1024)):(typeof s.componentDidUpdate!="function"||l===e.memoizedProps&&h===e.memoizedState||(t.flags|=4),typeof s.getSnapshotBeforeUpdate!="function"||l===e.memoizedProps&&h===e.memoizedState||(t.flags|=1024),t.memoizedProps=n,t.memoizedState=g),s.props=n,s.state=g,s.context=c,n=u):(typeof s.componentDidUpdate!="function"||l===e.memoizedProps&&h===e.memoizedState||(t.flags|=4),typeof s.getSnapshotBeforeUpdate!="function"||l===e.memoizedProps&&h===e.memoizedState||(t.flags|=1024),n=!1)}return ep(e,t,r,n,i,a)}function ep(e,t,r,n,a,i){O2(e,t);var s=(t.flags&128)!==0;if(!n&&!s)return a&&Lg(t,r,!1),Zr(e,t,i);n=t.stateNode,iA.current=t;var l=s&&typeof r.getDerivedStateFromError!="function"?null:n.render();return t.flags|=1,e!==null&&s?(t.child=Si(t,e.child,null,i),t.child=Si(t,null,l,i)):gt(e,t,l,i),t.memoizedState=n.state,a&&Lg(t,r,!0),t.child}function N2(e){var t=e.stateNode;t.pendingContext?Ig(e,t.pendingContext,t.pendingContext!==t.context):t.context&&Ig(e,t.context,!1),xv(e,t.containerInfo)}function Jg(e,t,r,n,a){return wi(),hv(a),t.flags|=256,gt(e,t,r,n),t.child}var tp={dehydrated:null,treeContext:null,retryLane:0};function rp(e){return{baseLanes:e,cachePool:null,transitions:null}}function P2(e,t,r){var n=t.pendingProps,a=Ce.current,i=!1,s=(t.flags&128)!==0,l;if((l=s)||(l=e!==null&&e.memoizedState===null?!1:(a&2)!==0),l?(i=!0,t.flags&=-129):(e===null||e.memoizedState!==null)&&(a|=1),je(Ce,a&1),e===null)return Yh(t),e=t.memoizedState,e!==null&&(e=e.dehydrated,e!==null)?(t.mode&1?e.data==="$!"?t.lanes=8:t.lanes=1073741824:t.lanes=1,null):(s=n.children,e=n.fallback,i?(n=t.mode,i=t.child,s={mode:"hidden",children:s},!(n&1)&&i!==null?(i.childLanes=0,i.pendingProps=s):i=hd(s,n,0,null),e=ha(e,n,r,null),i.return=t,e.return=t,i.sibling=e,t.child=i,t.child.memoizedState=rp(r),t.memoizedState=tp,e):Nv(t,s));if(a=e.memoizedState,a!==null&&(l=a.dehydrated,l!==null))return oA(e,t,s,n,l,a,r);if(i){i=n.fallback,s=t.mode,a=e.child,l=a.sibling;var c={mode:"hidden",children:n.children};return!(s&1)&&t.child!==a?(n=t.child,n.childLanes=0,n.pendingProps=c,t.deletions=null):(n=$n(a,c),n.subtreeFlags=a.subtreeFlags&14680064),l!==null?i=$n(l,i):(i=ha(i,s,r,null),i.flags|=2),i.return=t,n.return=t,n.sibling=i,t.child=n,n=i,i=t.child,s=e.child.memoizedState,s=s===null?rp(r):{baseLanes:s.baseLanes|r,cachePool:null,transitions:s.transitions},i.memoizedState=s,i.childLanes=e.childLanes&~r,t.memoizedState=tp,n}return i=e.child,e=i.sibling,n=$n(i,{mode:"visible",children:n.children}),!(t.mode&1)&&(n.lanes=r),n.return=t,n.sibling=null,e!==null&&(r=t.deletions,r===null?(t.deletions=[e],t.flags|=16):r.push(e)),t.child=n,t.memoizedState=null,n}function Nv(e,t){return t=hd({mode:"visible",children:t},e.mode,0,null),t.return=e,e.child=t}function Fl(e,t,r,n){return n!==null&&hv(n),Si(t,e.child,null,r),e=Nv(t,t.pendingProps.children),e.flags|=2,t.memoizedState=null,e}function oA(e,t,r,n,a,i,s){if(r)return t.flags&256?(t.flags&=-257,n=If(Error(H(422))),Fl(e,t,s,n)):t.memoizedState!==null?(t.child=e.child,t.flags|=128,null):(i=n.fallback,a=t.mode,n=hd({mode:"visible",children:n.children},a,0,null),i=ha(i,a,s,null),i.flags|=2,n.return=t,i.return=t,n.sibling=i,t.child=n,t.mode&1&&Si(t,e.child,null,s),t.child.memoizedState=rp(s),t.memoizedState=tp,i);if(!(t.mode&1))return Fl(e,t,s,null);if(a.data==="$!"){if(n=a.nextSibling&&a.nextSibling.dataset,n)var l=n.dgst;return n=l,i=Error(H(419)),n=If(i,n,void 0),Fl(e,t,s,n)}if(l=(s&e.childLanes)!==0,Nt||l){if(n=nt,n!==null){switch(s&-s){case 4:a=2;break;case 16:a=8;break;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:a=32;break;case 536870912:a=268435456;break;default:a=0}a=a&(n.suspendedLanes|s)?0:a,a!==0&&a!==i.retryLane&&(i.retryLane=a,Jr(e,a),vr(n,e,a,-1))}return Tv(),n=If(Error(H(421))),Fl(e,t,s,n)}return a.data==="$?"?(t.flags|=128,t.child=e.child,t=xA.bind(null,e),a._reactRetry=t,null):(e=i.treeContext,Dt=Pn(a.nextSibling),Rt=t,Ne=!0,hr=null,e!==null&&(Gt[Yt++]=Wr,Gt[Yt++]=Ur,Gt[Yt++]=ga,Wr=e.id,Ur=e.overflow,ga=t),t=Nv(t,n.children),t.flags|=4096,t)}function Zg(e,t,r){e.lanes|=t;var n=e.alternate;n!==null&&(n.lanes|=t),qh(e.return,t,r)}function Lf(e,t,r,n,a){var i=e.memoizedState;i===null?e.memoizedState={isBackwards:t,rendering:null,renderingStartTime:0,last:n,tail:r,tailMode:a}:(i.isBackwards=t,i.rendering=null,i.renderingStartTime=0,i.last=n,i.tail=r,i.tailMode=a)}function A2(e,t,r){var n=t.pendingProps,a=n.revealOrder,i=n.tail;if(gt(e,t,n.children,r),n=Ce.current,n&2)n=n&1|2,t.flags|=128;else{if(e!==null&&e.flags&128)e:for(e=t.child;e!==null;){if(e.tag===13)e.memoizedState!==null&&Zg(e,r,t);else if(e.tag===19)Zg(e,r,t);else if(e.child!==null){e.child.return=e,e=e.child;continue}if(e===t)break e;for(;e.sibling===null;){if(e.return===null||e.return===t)break e;e=e.return}e.sibling.return=e.return,e=e.sibling}n&=1}if(je(Ce,n),!(t.mode&1))t.memoizedState=null;else switch(a){case"forwards":for(r=t.child,a=null;r!==null;)e=r.alternate,e!==null&&Wc(e)===null&&(a=r),r=r.sibling;r=a,r===null?(a=t.child,t.child=null):(a=r.sibling,r.sibling=null),Lf(t,!1,a,r,i);break;case"backwards":for(r=null,a=t.child,t.child=null;a!==null;){if(e=a.alternate,e!==null&&Wc(e)===null){t.child=a;break}e=a.sibling,a.sibling=r,r=a,a=e}Lf(t,!0,r,null,i);break;case"together":Lf(t,!1,null,null,void 0);break;default:t.memoizedState=null}return t.child}function xc(e,t){!(t.mode&1)&&e!==null&&(e.alternate=null,t.alternate=null,t.flags|=2)}function Zr(e,t,r){if(e!==null&&(t.dependencies=e.dependencies),ba|=t.lanes,!(r&t.childLanes))return null;if(e!==null&&t.child!==e.child)throw Error(H(153));if(t.child!==null){for(e=t.child,r=$n(e,e.pendingProps),t.child=r,r.return=t;e.sibling!==null;)e=e.sibling,r=r.sibling=$n(e,e.pendingProps),r.return=t;r.sibling=null}return t.child}function sA(e,t,r){switch(t.tag){case 3:N2(t),wi();break;case 5:t2(t);break;case 1:Ct(t.type)&&Lc(t);break;case 4:xv(t,t.stateNode.containerInfo);break;case 10:var n=t.type._context,a=t.memoizedProps.value;je(Bc,n._currentValue),n._currentValue=a;break;case 13:if(n=t.memoizedState,n!==null)return n.dehydrated!==null?(je(Ce,Ce.current&1),t.flags|=128,null):r&t.child.childLanes?P2(e,t,r):(je(Ce,Ce.current&1),e=Zr(e,t,r),e!==null?e.sibling:null);je(Ce,Ce.current&1);break;case 19:if(n=(r&t.childLanes)!==0,e.flags&128){if(n)return A2(e,t,r);t.flags|=128}if(a=t.memoizedState,a!==null&&(a.rendering=null,a.tail=null,a.lastEffect=null),je(Ce,Ce.current),n)break;return null;case 22:case 23:return t.lanes=0,k2(e,t,r)}return Zr(e,t,r)}var C2,np,E2,$2;C2=function(e,t){for(var r=t.child;r!==null;){if(r.tag===5||r.tag===6)e.appendChild(r.stateNode);else if(r.tag!==4&&r.child!==null){r.child.return=r,r=r.child;continue}if(r===t)break;for(;r.sibling===null;){if(r.return===null||r.return===t)return;r=r.return}r.sibling.return=r.return,r=r.sibling}};np=function(){};E2=function(e,t,r,n){var a=e.memoizedProps;if(a!==n){e=t.stateNode,ia(Ar.current);var i=null;switch(r){case"input":a=kh(e,a),n=kh(e,n),i=[];break;case"select":a=$e({},a,{value:void 0}),n=$e({},n,{value:void 0}),i=[];break;case"textarea":a=Ph(e,a),n=Ph(e,n),i=[];break;default:typeof a.onClick!="function"&&typeof n.onClick=="function"&&(e.onclick=Mc)}Ch(r,n);var s;r=null;for(u in a)if(!n.hasOwnProperty(u)&&a.hasOwnProperty(u)&&a[u]!=null)if(u==="style"){var l=a[u];for(s in l)l.hasOwnProperty(s)&&(r||(r={}),r[s]="")}else u!=="dangerouslySetInnerHTML"&&u!=="children"&&u!=="suppressContentEditableWarning"&&u!=="suppressHydrationWarning"&&u!=="autoFocus"&&(ss.hasOwnProperty(u)?i||(i=[]):(i=i||[]).push(u,null));for(u in n){var c=n[u];if(l=a!=null?a[u]:void 0,n.hasOwnProperty(u)&&c!==l&&(c!=null||l!=null))if(u==="style")if(l){for(s in l)!l.hasOwnProperty(s)||c&&c.hasOwnProperty(s)||(r||(r={}),r[s]="");for(s in c)c.hasOwnProperty(s)&&l[s]!==c[s]&&(r||(r={}),r[s]=c[s])}else r||(i||(i=[]),i.push(u,r)),r=c;else u==="dangerouslySetInnerHTML"?(c=c?c.__html:void 0,l=l?l.__html:void 0,c!=null&&l!==c&&(i=i||[]).push(u,c)):u==="children"?typeof c!="string"&&typeof c!="number"||(i=i||[]).push(u,""+c):u!=="suppressContentEditableWarning"&&u!=="suppressHydrationWarning"&&(ss.hasOwnProperty(u)?(c!=null&&u==="onScroll"&&we("scroll",e),i||l===c||(i=[])):(i=i||[]).push(u,c))}r&&(i=i||[]).push("style",r);var u=i;(t.updateQueue=u)&&(t.flags|=4)}};$2=function(e,t,r,n){r!==n&&(t.flags|=4)};function ko(e,t){if(!Ne)switch(e.tailMode){case"hidden":t=e.tail;for(var r=null;t!==null;)t.alternate!==null&&(r=t),t=t.sibling;r===null?e.tail=null:r.sibling=null;break;case"collapsed":r=e.tail;for(var n=null;r!==null;)r.alternate!==null&&(n=r),r=r.sibling;n===null?t||e.tail===null?e.tail=null:e.tail.sibling=null:n.sibling=null}}function ft(e){var t=e.alternate!==null&&e.alternate.child===e.child,r=0,n=0;if(t)for(var a=e.child;a!==null;)r|=a.lanes|a.childLanes,n|=a.subtreeFlags&14680064,n|=a.flags&14680064,a.return=e,a=a.sibling;else for(a=e.child;a!==null;)r|=a.lanes|a.childLanes,n|=a.subtreeFlags,n|=a.flags,a.return=e,a=a.sibling;return e.subtreeFlags|=n,e.childLanes=r,t}function lA(e,t,r){var n=t.pendingProps;switch(fv(t),t.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return ft(t),null;case 1:return Ct(t.type)&&Ic(),ft(t),null;case 3:return n=t.stateNode,_i(),ke(At),ke(vt),jv(),n.pendingContext&&(n.context=n.pendingContext,n.pendingContext=null),(e===null||e.child===null)&&(Rl(t)?t.flags|=4:e===null||e.memoizedState.isDehydrated&&!(t.flags&256)||(t.flags|=1024,hr!==null&&(dp(hr),hr=null))),np(e,t),ft(t),null;case 5:bv(t);var a=ia(xs.current);if(r=t.type,e!==null&&t.stateNode!=null)E2(e,t,r,n,a),e.ref!==t.ref&&(t.flags|=512,t.flags|=2097152);else{if(!n){if(t.stateNode===null)throw Error(H(166));return ft(t),null}if(e=ia(Ar.current),Rl(t)){n=t.stateNode,r=t.type;var i=t.memoizedProps;switch(n[kr]=t,n[ys]=i,e=(t.mode&1)!==0,r){case"dialog":we("cancel",n),we("close",n);break;case"iframe":case"object":case"embed":we("load",n);break;case"video":case"audio":for(a=0;a<Wo.length;a++)we(Wo[a],n);break;case"source":we("error",n);break;case"img":case"image":case"link":we("error",n),we("load",n);break;case"details":we("toggle",n);break;case"input":lg(n,i),we("invalid",n);break;case"select":n._wrapperState={wasMultiple:!!i.multiple},we("invalid",n);break;case"textarea":ug(n,i),we("invalid",n)}Ch(r,i),a=null;for(var s in i)if(i.hasOwnProperty(s)){var l=i[s];s==="children"?typeof l=="string"?n.textContent!==l&&(i.suppressHydrationWarning!==!0&&Dl(n.textContent,l,e),a=["children",l]):typeof l=="number"&&n.textContent!==""+l&&(i.suppressHydrationWarning!==!0&&Dl(n.textContent,l,e),a=["children",""+l]):ss.hasOwnProperty(s)&&l!=null&&s==="onScroll"&&we("scroll",n)}switch(r){case"input":Al(n),cg(n,i,!0);break;case"textarea":Al(n),dg(n);break;case"select":case"option":break;default:typeof i.onClick=="function"&&(n.onclick=Mc)}n=a,t.updateQueue=n,n!==null&&(t.flags|=4)}else{s=a.nodeType===9?a:a.ownerDocument,e==="http://www.w3.org/1999/xhtml"&&(e=ow(r)),e==="http://www.w3.org/1999/xhtml"?r==="script"?(e=s.createElement("div"),e.innerHTML="<script><\/script>",e=e.removeChild(e.firstChild)):typeof n.is=="string"?e=s.createElement(r,{is:n.is}):(e=s.createElement(r),r==="select"&&(s=e,n.multiple?s.multiple=!0:n.size&&(s.size=n.size))):e=s.createElementNS(e,r),e[kr]=t,e[ys]=n,C2(e,t,!1,!1),t.stateNode=e;e:{switch(s=Eh(r,n),r){case"dialog":we("cancel",e),we("close",e),a=n;break;case"iframe":case"object":case"embed":we("load",e),a=n;break;case"video":case"audio":for(a=0;a<Wo.length;a++)we(Wo[a],e);a=n;break;case"source":we("error",e),a=n;break;case"img":case"image":case"link":we("error",e),we("load",e),a=n;break;case"details":we("toggle",e),a=n;break;case"input":lg(e,n),a=kh(e,n),we("invalid",e);break;case"option":a=n;break;case"select":e._wrapperState={wasMultiple:!!n.multiple},a=$e({},n,{value:void 0}),we("invalid",e);break;case"textarea":ug(e,n),a=Ph(e,n),we("invalid",e);break;default:a=n}Ch(r,a),l=a;for(i in l)if(l.hasOwnProperty(i)){var c=l[i];i==="style"?cw(e,c):i==="dangerouslySetInnerHTML"?(c=c?c.__html:void 0,c!=null&&sw(e,c)):i==="children"?typeof c=="string"?(r!=="textarea"||c!=="")&&ls(e,c):typeof c=="number"&&ls(e,""+c):i!=="suppressContentEditableWarning"&&i!=="suppressHydrationWarning"&&i!=="autoFocus"&&(ss.hasOwnProperty(i)?c!=null&&i==="onScroll"&&we("scroll",e):c!=null&&Qm(e,i,c,s))}switch(r){case"input":Al(e),cg(e,n,!1);break;case"textarea":Al(e),dg(e);break;case"option":n.value!=null&&e.setAttribute("value",""+In(n.value));break;case"select":e.multiple=!!n.multiple,i=n.value,i!=null?ci(e,!!n.multiple,i,!1):n.defaultValue!=null&&ci(e,!!n.multiple,n.defaultValue,!0);break;default:typeof a.onClick=="function"&&(e.onclick=Mc)}switch(r){case"button":case"input":case"select":case"textarea":n=!!n.autoFocus;break e;case"img":n=!0;break e;default:n=!1}}n&&(t.flags|=4)}t.ref!==null&&(t.flags|=512,t.flags|=2097152)}return ft(t),null;case 6:if(e&&t.stateNode!=null)$2(e,t,e.memoizedProps,n);else{if(typeof n!="string"&&t.stateNode===null)throw Error(H(166));if(r=ia(xs.current),ia(Ar.current),Rl(t)){if(n=t.stateNode,r=t.memoizedProps,n[kr]=t,(i=n.nodeValue!==r)&&(e=Rt,e!==null))switch(e.tag){case 3:Dl(n.nodeValue,r,(e.mode&1)!==0);break;case 5:e.memoizedProps.suppressHydrationWarning!==!0&&Dl(n.nodeValue,r,(e.mode&1)!==0)}i&&(t.flags|=4)}else n=(r.nodeType===9?r:r.ownerDocument).createTextNode(n),n[kr]=t,t.stateNode=n}return ft(t),null;case 13:if(ke(Ce),n=t.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(Ne&&Dt!==null&&t.mode&1&&!(t.flags&128))Xw(),wi(),t.flags|=98560,i=!1;else if(i=Rl(t),n!==null&&n.dehydrated!==null){if(e===null){if(!i)throw Error(H(318));if(i=t.memoizedState,i=i!==null?i.dehydrated:null,!i)throw Error(H(317));i[kr]=t}else wi(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;ft(t),i=!1}else hr!==null&&(dp(hr),hr=null),i=!0;if(!i)return t.flags&65536?t:null}return t.flags&128?(t.lanes=r,t):(n=n!==null,n!==(e!==null&&e.memoizedState!==null)&&n&&(t.child.flags|=8192,t.mode&1&&(e===null||Ce.current&1?Ye===0&&(Ye=3):Tv())),t.updateQueue!==null&&(t.flags|=4),ft(t),null);case 4:return _i(),np(e,t),e===null&&ms(t.stateNode.containerInfo),ft(t),null;case 10:return vv(t.type._context),ft(t),null;case 17:return Ct(t.type)&&Ic(),ft(t),null;case 19:if(ke(Ce),i=t.memoizedState,i===null)return ft(t),null;if(n=(t.flags&128)!==0,s=i.rendering,s===null)if(n)ko(i,!1);else{if(Ye!==0||e!==null&&e.flags&128)for(e=t.child;e!==null;){if(s=Wc(e),s!==null){for(t.flags|=128,ko(i,!1),n=s.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),t.subtreeFlags=0,n=r,r=t.child;r!==null;)i=r,e=n,i.flags&=14680066,s=i.alternate,s===null?(i.childLanes=0,i.lanes=e,i.child=null,i.subtreeFlags=0,i.memoizedProps=null,i.memoizedState=null,i.updateQueue=null,i.dependencies=null,i.stateNode=null):(i.childLanes=s.childLanes,i.lanes=s.lanes,i.child=s.child,i.subtreeFlags=0,i.deletions=null,i.memoizedProps=s.memoizedProps,i.memoizedState=s.memoizedState,i.updateQueue=s.updateQueue,i.type=s.type,e=s.dependencies,i.dependencies=e===null?null:{lanes:e.lanes,firstContext:e.firstContext}),r=r.sibling;return je(Ce,Ce.current&1|2),t.child}e=e.sibling}i.tail!==null&&Le()>Oi&&(t.flags|=128,n=!0,ko(i,!1),t.lanes=4194304)}else{if(!n)if(e=Wc(s),e!==null){if(t.flags|=128,n=!0,r=e.updateQueue,r!==null&&(t.updateQueue=r,t.flags|=4),ko(i,!0),i.tail===null&&i.tailMode==="hidden"&&!s.alternate&&!Ne)return ft(t),null}else 2*Le()-i.renderingStartTime>Oi&&r!==1073741824&&(t.flags|=128,n=!0,ko(i,!1),t.lanes=4194304);i.isBackwards?(s.sibling=t.child,t.child=s):(r=i.last,r!==null?r.sibling=s:t.child=s,i.last=s)}return i.tail!==null?(t=i.tail,i.rendering=t,i.tail=t.sibling,i.renderingStartTime=Le(),t.sibling=null,r=Ce.current,je(Ce,n?r&1|2:r&1),t):(ft(t),null);case 22:case 23:return $v(),n=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==n&&(t.flags|=8192),n&&t.mode&1?Mt&1073741824&&(ft(t),t.subtreeFlags&6&&(t.flags|=8192)):ft(t),null;case 24:return null;case 25:return null}throw Error(H(156,t.tag))}function cA(e,t){switch(fv(t),t.tag){case 1:return Ct(t.type)&&Ic(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return _i(),ke(At),ke(vt),jv(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return bv(t),null;case 13:if(ke(Ce),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(H(340));wi()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return ke(Ce),null;case 4:return _i(),null;case 10:return vv(t.type._context),null;case 22:case 23:return $v(),null;case 24:return null;default:return null}}var zl=!1,pt=!1,uA=typeof WeakSet=="function"?WeakSet:Set,G=null;function ri(e,t){var r=e.ref;if(r!==null)if(typeof r=="function")try{r(null)}catch(n){Me(e,t,n)}else r.current=null}function ap(e,t,r){try{r()}catch(n){Me(e,t,n)}}var e0=!1;function dA(e,t){if(zh=Ec,e=Dw(),uv(e)){if("selectionStart"in e)var r={start:e.selectionStart,end:e.selectionEnd};else e:{r=(r=e.ownerDocument)&&r.defaultView||window;var n=r.getSelection&&r.getSelection();if(n&&n.rangeCount!==0){r=n.anchorNode;var a=n.anchorOffset,i=n.focusNode;n=n.focusOffset;try{r.nodeType,i.nodeType}catch{r=null;break e}var s=0,l=-1,c=-1,u=0,f=0,d=e,h=null;t:for(;;){for(var p;d!==r||a!==0&&d.nodeType!==3||(l=s+a),d!==i||n!==0&&d.nodeType!==3||(c=s+n),d.nodeType===3&&(s+=d.nodeValue.length),(p=d.firstChild)!==null;)h=d,d=p;for(;;){if(d===e)break t;if(h===r&&++u===a&&(l=s),h===i&&++f===n&&(c=s),(p=d.nextSibling)!==null)break;d=h,h=d.parentNode}d=p}r=l===-1||c===-1?null:{start:l,end:c}}else r=null}r=r||{start:0,end:0}}else r=null;for(Wh={focusedElem:e,selectionRange:r},Ec=!1,G=t;G!==null;)if(t=G,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,G=e;else for(;G!==null;){t=G;try{var g=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(g!==null){var y=g.memoizedProps,b=g.memoizedState,v=t.stateNode,m=v.getSnapshotBeforeUpdate(t.elementType===t.type?y:ur(t.type,y),b);v.__reactInternalSnapshotBeforeUpdate=m}break;case 3:var x=t.stateNode.containerInfo;x.nodeType===1?x.textContent="":x.nodeType===9&&x.documentElement&&x.removeChild(x.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(H(163))}}catch(S){Me(t,t.return,S)}if(e=t.sibling,e!==null){e.return=t.return,G=e;break}G=t.return}return g=e0,e0=!1,g}function Jo(e,t,r){var n=t.updateQueue;if(n=n!==null?n.lastEffect:null,n!==null){var a=n=n.next;do{if((a.tag&e)===e){var i=a.destroy;a.destroy=void 0,i!==void 0&&ap(t,r,i)}a=a.next}while(a!==n)}}function dd(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var r=t=t.next;do{if((r.tag&e)===e){var n=r.create;r.destroy=n()}r=r.next}while(r!==t)}}function ip(e){var t=e.ref;if(t!==null){var r=e.stateNode;switch(e.tag){case 5:e=r;break;default:e=r}typeof t=="function"?t(e):t.current=e}}function T2(e){var t=e.alternate;t!==null&&(e.alternate=null,T2(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[kr],delete t[ys],delete t[Kh],delete t[GP],delete t[YP])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function M2(e){return e.tag===5||e.tag===3||e.tag===4}function t0(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||M2(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function op(e,t,r){var n=e.tag;if(n===5||n===6)e=e.stateNode,t?r.nodeType===8?r.parentNode.insertBefore(e,t):r.insertBefore(e,t):(r.nodeType===8?(t=r.parentNode,t.insertBefore(e,r)):(t=r,t.appendChild(e)),r=r._reactRootContainer,r!=null||t.onclick!==null||(t.onclick=Mc));else if(n!==4&&(e=e.child,e!==null))for(op(e,t,r),e=e.sibling;e!==null;)op(e,t,r),e=e.sibling}function sp(e,t,r){var n=e.tag;if(n===5||n===6)e=e.stateNode,t?r.insertBefore(e,t):r.appendChild(e);else if(n!==4&&(e=e.child,e!==null))for(sp(e,t,r),e=e.sibling;e!==null;)sp(e,t,r),e=e.sibling}var st=null,dr=!1;function un(e,t,r){for(r=r.child;r!==null;)I2(e,t,r),r=r.sibling}function I2(e,t,r){if(Pr&&typeof Pr.onCommitFiberUnmount=="function")try{Pr.onCommitFiberUnmount(nd,r)}catch{}switch(r.tag){case 5:pt||ri(r,t);case 6:var n=st,a=dr;st=null,un(e,t,r),st=n,dr=a,st!==null&&(dr?(e=st,r=r.stateNode,e.nodeType===8?e.parentNode.removeChild(r):e.removeChild(r)):st.removeChild(r.stateNode));break;case 18:st!==null&&(dr?(e=st,r=r.stateNode,e.nodeType===8?Af(e.parentNode,r):e.nodeType===1&&Af(e,r),fs(e)):Af(st,r.stateNode));break;case 4:n=st,a=dr,st=r.stateNode.containerInfo,dr=!0,un(e,t,r),st=n,dr=a;break;case 0:case 11:case 14:case 15:if(!pt&&(n=r.updateQueue,n!==null&&(n=n.lastEffect,n!==null))){a=n=n.next;do{var i=a,s=i.destroy;i=i.tag,s!==void 0&&(i&2||i&4)&&ap(r,t,s),a=a.next}while(a!==n)}un(e,t,r);break;case 1:if(!pt&&(ri(r,t),n=r.stateNode,typeof n.componentWillUnmount=="function"))try{n.props=r.memoizedProps,n.state=r.memoizedState,n.componentWillUnmount()}catch(l){Me(r,t,l)}un(e,t,r);break;case 21:un(e,t,r);break;case 22:r.mode&1?(pt=(n=pt)||r.memoizedState!==null,un(e,t,r),pt=n):un(e,t,r);break;default:un(e,t,r)}}function r0(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var r=e.stateNode;r===null&&(r=e.stateNode=new uA),t.forEach(function(n){var a=bA.bind(null,e,n);r.has(n)||(r.add(n),n.then(a,a))})}}function lr(e,t){var r=t.deletions;if(r!==null)for(var n=0;n<r.length;n++){var a=r[n];try{var i=e,s=t,l=s;e:for(;l!==null;){switch(l.tag){case 5:st=l.stateNode,dr=!1;break e;case 3:st=l.stateNode.containerInfo,dr=!0;break e;case 4:st=l.stateNode.containerInfo,dr=!0;break e}l=l.return}if(st===null)throw Error(H(160));I2(i,s,a),st=null,dr=!1;var c=a.alternate;c!==null&&(c.return=null),a.return=null}catch(u){Me(a,t,u)}}if(t.subtreeFlags&12854)for(t=t.child;t!==null;)L2(t,e),t=t.sibling}function L2(e,t){var r=e.alternate,n=e.flags;switch(e.tag){case 0:case 11:case 14:case 15:if(lr(t,e),Sr(e),n&4){try{Jo(3,e,e.return),dd(3,e)}catch(y){Me(e,e.return,y)}try{Jo(5,e,e.return)}catch(y){Me(e,e.return,y)}}break;case 1:lr(t,e),Sr(e),n&512&&r!==null&&ri(r,r.return);break;case 5:if(lr(t,e),Sr(e),n&512&&r!==null&&ri(r,r.return),e.flags&32){var a=e.stateNode;try{ls(a,"")}catch(y){Me(e,e.return,y)}}if(n&4&&(a=e.stateNode,a!=null)){var i=e.memoizedProps,s=r!==null?r.memoizedProps:i,l=e.type,c=e.updateQueue;if(e.updateQueue=null,c!==null)try{l==="input"&&i.type==="radio"&&i.name!=null&&aw(a,i),Eh(l,s);var u=Eh(l,i);for(s=0;s<c.length;s+=2){var f=c[s],d=c[s+1];f==="style"?cw(a,d):f==="dangerouslySetInnerHTML"?sw(a,d):f==="children"?ls(a,d):Qm(a,f,d,u)}switch(l){case"input":Oh(a,i);break;case"textarea":iw(a,i);break;case"select":var h=a._wrapperState.wasMultiple;a._wrapperState.wasMultiple=!!i.multiple;var p=i.value;p!=null?ci(a,!!i.multiple,p,!1):h!==!!i.multiple&&(i.defaultValue!=null?ci(a,!!i.multiple,i.defaultValue,!0):ci(a,!!i.multiple,i.multiple?[]:"",!1))}a[ys]=i}catch(y){Me(e,e.return,y)}}break;case 6:if(lr(t,e),Sr(e),n&4){if(e.stateNode===null)throw Error(H(162));a=e.stateNode,i=e.memoizedProps;try{a.nodeValue=i}catch(y){Me(e,e.return,y)}}break;case 3:if(lr(t,e),Sr(e),n&4&&r!==null&&r.memoizedState.isDehydrated)try{fs(t.containerInfo)}catch(y){Me(e,e.return,y)}break;case 4:lr(t,e),Sr(e);break;case 13:lr(t,e),Sr(e),a=e.child,a.flags&8192&&(i=a.memoizedState!==null,a.stateNode.isHidden=i,!i||a.alternate!==null&&a.alternate.memoizedState!==null||(Cv=Le())),n&4&&r0(e);break;case 22:if(f=r!==null&&r.memoizedState!==null,e.mode&1?(pt=(u=pt)||f,lr(t,e),pt=u):lr(t,e),Sr(e),n&8192){if(u=e.memoizedState!==null,(e.stateNode.isHidden=u)&&!f&&e.mode&1)for(G=e,f=e.child;f!==null;){for(d=G=f;G!==null;){switch(h=G,p=h.child,h.tag){case 0:case 11:case 14:case 15:Jo(4,h,h.return);break;case 1:ri(h,h.return);var g=h.stateNode;if(typeof g.componentWillUnmount=="function"){n=h,r=h.return;try{t=n,g.props=t.memoizedProps,g.state=t.memoizedState,g.componentWillUnmount()}catch(y){Me(n,r,y)}}break;case 5:ri(h,h.return);break;case 22:if(h.memoizedState!==null){a0(d);continue}}p!==null?(p.return=h,G=p):a0(d)}f=f.sibling}e:for(f=null,d=e;;){if(d.tag===5){if(f===null){f=d;try{a=d.stateNode,u?(i=a.style,typeof i.setProperty=="function"?i.setProperty("display","none","important"):i.display="none"):(l=d.stateNode,c=d.memoizedProps.style,s=c!=null&&c.hasOwnProperty("display")?c.display:null,l.style.display=lw("display",s))}catch(y){Me(e,e.return,y)}}}else if(d.tag===6){if(f===null)try{d.stateNode.nodeValue=u?"":d.memoizedProps}catch(y){Me(e,e.return,y)}}else if((d.tag!==22&&d.tag!==23||d.memoizedState===null||d===e)&&d.child!==null){d.child.return=d,d=d.child;continue}if(d===e)break e;for(;d.sibling===null;){if(d.return===null||d.return===e)break e;f===d&&(f=null),d=d.return}f===d&&(f=null),d.sibling.return=d.return,d=d.sibling}}break;case 19:lr(t,e),Sr(e),n&4&&r0(e);break;case 21:break;default:lr(t,e),Sr(e)}}function Sr(e){var t=e.flags;if(t&2){try{e:{for(var r=e.return;r!==null;){if(M2(r)){var n=r;break e}r=r.return}throw Error(H(160))}switch(n.tag){case 5:var a=n.stateNode;n.flags&32&&(ls(a,""),n.flags&=-33);var i=t0(e);sp(e,i,a);break;case 3:case 4:var s=n.stateNode.containerInfo,l=t0(e);op(e,l,s);break;default:throw Error(H(161))}}catch(c){Me(e,e.return,c)}e.flags&=-3}t&4096&&(e.flags&=-4097)}function fA(e,t,r){G=e,D2(e)}function D2(e,t,r){for(var n=(e.mode&1)!==0;G!==null;){var a=G,i=a.child;if(a.tag===22&&n){var s=a.memoizedState!==null||zl;if(!s){var l=a.alternate,c=l!==null&&l.memoizedState!==null||pt;l=zl;var u=pt;if(zl=s,(pt=c)&&!u)for(G=a;G!==null;)s=G,c=s.child,s.tag===22&&s.memoizedState!==null?i0(a):c!==null?(c.return=s,G=c):i0(a);for(;i!==null;)G=i,D2(i),i=i.sibling;G=a,zl=l,pt=u}n0(e)}else a.subtreeFlags&8772&&i!==null?(i.return=a,G=i):n0(e)}}function n0(e){for(;G!==null;){var t=G;if(t.flags&8772){var r=t.alternate;try{if(t.flags&8772)switch(t.tag){case 0:case 11:case 15:pt||dd(5,t);break;case 1:var n=t.stateNode;if(t.flags&4&&!pt)if(r===null)n.componentDidMount();else{var a=t.elementType===t.type?r.memoizedProps:ur(t.type,r.memoizedProps);n.componentDidUpdate(a,r.memoizedState,n.__reactInternalSnapshotBeforeUpdate)}var i=t.updateQueue;i!==null&&zg(t,i,n);break;case 3:var s=t.updateQueue;if(s!==null){if(r=null,t.child!==null)switch(t.child.tag){case 5:r=t.child.stateNode;break;case 1:r=t.child.stateNode}zg(t,s,r)}break;case 5:var l=t.stateNode;if(r===null&&t.flags&4){r=l;var c=t.memoizedProps;switch(t.type){case"button":case"input":case"select":case"textarea":c.autoFocus&&r.focus();break;case"img":c.src&&(r.src=c.src)}}break;case 6:break;case 4:break;case 12:break;case 13:if(t.memoizedState===null){var u=t.alternate;if(u!==null){var f=u.memoizedState;if(f!==null){var d=f.dehydrated;d!==null&&fs(d)}}}break;case 19:case 17:case 21:case 22:case 23:case 25:break;default:throw Error(H(163))}pt||t.flags&512&&ip(t)}catch(h){Me(t,t.return,h)}}if(t===e){G=null;break}if(r=t.sibling,r!==null){r.return=t.return,G=r;break}G=t.return}}function a0(e){for(;G!==null;){var t=G;if(t===e){G=null;break}var r=t.sibling;if(r!==null){r.return=t.return,G=r;break}G=t.return}}function i0(e){for(;G!==null;){var t=G;try{switch(t.tag){case 0:case 11:case 15:var r=t.return;try{dd(4,t)}catch(c){Me(t,r,c)}break;case 1:var n=t.stateNode;if(typeof n.componentDidMount=="function"){var a=t.return;try{n.componentDidMount()}catch(c){Me(t,a,c)}}var i=t.return;try{ip(t)}catch(c){Me(t,i,c)}break;case 5:var s=t.return;try{ip(t)}catch(c){Me(t,s,c)}}}catch(c){Me(t,t.return,c)}if(t===e){G=null;break}var l=t.sibling;if(l!==null){l.return=t.return,G=l;break}G=t.return}}var hA=Math.ceil,Kc=an.ReactCurrentDispatcher,Pv=an.ReactCurrentOwner,Jt=an.ReactCurrentBatchConfig,se=0,nt=null,Re=null,ct=0,Mt=0,ni=Rn(0),Ye=0,Ss=null,ba=0,fd=0,Av=0,Zo=null,Ot=null,Cv=0,Oi=1/0,Br=null,Vc=!1,lp=null,Cn=null,Wl=!1,bn=null,Gc=0,es=0,cp=null,bc=-1,jc=0;function jt(){return se&6?Le():bc!==-1?bc:bc=Le()}function En(e){return e.mode&1?se&2&&ct!==0?ct&-ct:XP.transition!==null?(jc===0&&(jc=jw()),jc):(e=ue,e!==0||(e=window.event,e=e===void 0?16:Pw(e.type)),e):1}function vr(e,t,r,n){if(50<es)throw es=0,cp=null,Error(H(185));cl(e,r,n),(!(se&2)||e!==nt)&&(e===nt&&(!(se&2)&&(fd|=r),Ye===4&&yn(e,ct)),Et(e,n),r===1&&se===0&&!(t.mode&1)&&(Oi=Le()+500,ld&&Bn()))}function Et(e,t){var r=e.callbackNode;XN(e,t);var n=Cc(e,e===nt?ct:0);if(n===0)r!==null&&pg(r),e.callbackNode=null,e.callbackPriority=0;else if(t=n&-n,e.callbackPriority!==t){if(r!=null&&pg(r),t===1)e.tag===0?qP(o0.bind(null,e)):Gw(o0.bind(null,e)),KP(function(){!(se&6)&&Bn()}),r=null;else{switch(ww(n)){case 1:r=rv;break;case 4:r=xw;break;case 16:r=Ac;break;case 536870912:r=bw;break;default:r=Ac}r=K2(r,R2.bind(null,e))}e.callbackPriority=t,e.callbackNode=r}}function R2(e,t){if(bc=-1,jc=0,se&6)throw Error(H(327));var r=e.callbackNode;if(pi()&&e.callbackNode!==r)return null;var n=Cc(e,e===nt?ct:0);if(n===0)return null;if(n&30||n&e.expiredLanes||t)t=Yc(e,n);else{t=n;var a=se;se|=2;var i=F2();(nt!==e||ct!==t)&&(Br=null,Oi=Le()+500,fa(e,t));do try{vA();break}catch(l){B2(e,l)}while(!0);mv(),Kc.current=i,se=a,Re!==null?t=0:(nt=null,ct=0,t=Ye)}if(t!==0){if(t===2&&(a=Lh(e),a!==0&&(n=a,t=up(e,a))),t===1)throw r=Ss,fa(e,0),yn(e,n),Et(e,Le()),r;if(t===6)yn(e,n);else{if(a=e.current.alternate,!(n&30)&&!pA(a)&&(t=Yc(e,n),t===2&&(i=Lh(e),i!==0&&(n=i,t=up(e,i))),t===1))throw r=Ss,fa(e,0),yn(e,n),Et(e,Le()),r;switch(e.finishedWork=a,e.finishedLanes=n,t){case 0:case 1:throw Error(H(345));case 2:Jn(e,Ot,Br);break;case 3:if(yn(e,n),(n&130023424)===n&&(t=Cv+500-Le(),10<t)){if(Cc(e,0)!==0)break;if(a=e.suspendedLanes,(a&n)!==n){jt(),e.pingedLanes|=e.suspendedLanes&a;break}e.timeoutHandle=Hh(Jn.bind(null,e,Ot,Br),t);break}Jn(e,Ot,Br);break;case 4:if(yn(e,n),(n&4194240)===n)break;for(t=e.eventTimes,a=-1;0<n;){var s=31-mr(n);i=1<<s,s=t[s],s>a&&(a=s),n&=~i}if(n=a,n=Le()-n,n=(120>n?120:480>n?480:1080>n?1080:1920>n?1920:3e3>n?3e3:4320>n?4320:1960*hA(n/1960))-n,10<n){e.timeoutHandle=Hh(Jn.bind(null,e,Ot,Br),n);break}Jn(e,Ot,Br);break;case 5:Jn(e,Ot,Br);break;default:throw Error(H(329))}}}return Et(e,Le()),e.callbackNode===r?R2.bind(null,e):null}function up(e,t){var r=Zo;return e.current.memoizedState.isDehydrated&&(fa(e,t).flags|=256),e=Yc(e,t),e!==2&&(t=Ot,Ot=r,t!==null&&dp(t)),e}function dp(e){Ot===null?Ot=e:Ot.push.apply(Ot,e)}function pA(e){for(var t=e;;){if(t.flags&16384){var r=t.updateQueue;if(r!==null&&(r=r.stores,r!==null))for(var n=0;n<r.length;n++){var a=r[n],i=a.getSnapshot;a=a.value;try{if(!gr(i(),a))return!1}catch{return!1}}}if(r=t.child,t.subtreeFlags&16384&&r!==null)r.return=t,t=r;else{if(t===e)break;for(;t.sibling===null;){if(t.return===null||t.return===e)return!0;t=t.return}t.sibling.return=t.return,t=t.sibling}}return!0}function yn(e,t){for(t&=~Av,t&=~fd,e.suspendedLanes|=t,e.pingedLanes&=~t,e=e.expirationTimes;0<t;){var r=31-mr(t),n=1<<r;e[r]=-1,t&=~n}}function o0(e){if(se&6)throw Error(H(327));pi();var t=Cc(e,0);if(!(t&1))return Et(e,Le()),null;var r=Yc(e,t);if(e.tag!==0&&r===2){var n=Lh(e);n!==0&&(t=n,r=up(e,n))}if(r===1)throw r=Ss,fa(e,0),yn(e,t),Et(e,Le()),r;if(r===6)throw Error(H(345));return e.finishedWork=e.current.alternate,e.finishedLanes=t,Jn(e,Ot,Br),Et(e,Le()),null}function Ev(e,t){var r=se;se|=1;try{return e(t)}finally{se=r,se===0&&(Oi=Le()+500,ld&&Bn())}}function ja(e){bn!==null&&bn.tag===0&&!(se&6)&&pi();var t=se;se|=1;var r=Jt.transition,n=ue;try{if(Jt.transition=null,ue=1,e)return e()}finally{ue=n,Jt.transition=r,se=t,!(se&6)&&Bn()}}function $v(){Mt=ni.current,ke(ni)}function fa(e,t){e.finishedWork=null,e.finishedLanes=0;var r=e.timeoutHandle;if(r!==-1&&(e.timeoutHandle=-1,HP(r)),Re!==null)for(r=Re.return;r!==null;){var n=r;switch(fv(n),n.tag){case 1:n=n.type.childContextTypes,n!=null&&Ic();break;case 3:_i(),ke(At),ke(vt),jv();break;case 5:bv(n);break;case 4:_i();break;case 13:ke(Ce);break;case 19:ke(Ce);break;case 10:vv(n.type._context);break;case 22:case 23:$v()}r=r.return}if(nt=e,Re=e=$n(e.current,null),ct=Mt=t,Ye=0,Ss=null,Av=fd=ba=0,Ot=Zo=null,aa!==null){for(t=0;t<aa.length;t++)if(r=aa[t],n=r.interleaved,n!==null){r.interleaved=null;var a=n.next,i=r.pending;if(i!==null){var s=i.next;i.next=a,n.next=s}r.pending=n}aa=null}return e}function B2(e,t){do{var r=Re;try{if(mv(),yc.current=Hc,Uc){for(var n=Ee.memoizedState;n!==null;){var a=n.queue;a!==null&&(a.pending=null),n=n.next}Uc=!1}if(xa=0,et=Ve=Ee=null,Qo=!1,bs=0,Pv.current=null,r===null||r.return===null){Ye=1,Ss=t,Re=null;break}e:{var i=e,s=r.return,l=r,c=t;if(t=ct,l.flags|=32768,c!==null&&typeof c=="object"&&typeof c.then=="function"){var u=c,f=l,d=f.tag;if(!(f.mode&1)&&(d===0||d===11||d===15)){var h=f.alternate;h?(f.updateQueue=h.updateQueue,f.memoizedState=h.memoizedState,f.lanes=h.lanes):(f.updateQueue=null,f.memoizedState=null)}var p=Gg(s);if(p!==null){p.flags&=-257,Yg(p,s,l,i,t),p.mode&1&&Vg(i,u,t),t=p,c=u;var g=t.updateQueue;if(g===null){var y=new Set;y.add(c),t.updateQueue=y}else g.add(c);break e}else{if(!(t&1)){Vg(i,u,t),Tv();break e}c=Error(H(426))}}else if(Ne&&l.mode&1){var b=Gg(s);if(b!==null){!(b.flags&65536)&&(b.flags|=256),Yg(b,s,l,i,t),hv(ki(c,l));break e}}i=c=ki(c,l),Ye!==4&&(Ye=2),Zo===null?Zo=[i]:Zo.push(i),i=s;do{switch(i.tag){case 3:i.flags|=65536,t&=-t,i.lanes|=t;var v=w2(i,c,t);Fg(i,v);break e;case 1:l=c;var m=i.type,x=i.stateNode;if(!(i.flags&128)&&(typeof m.getDerivedStateFromError=="function"||x!==null&&typeof x.componentDidCatch=="function"&&(Cn===null||!Cn.has(x)))){i.flags|=65536,t&=-t,i.lanes|=t;var S=S2(i,l,t);Fg(i,S);break e}}i=i.return}while(i!==null)}W2(r)}catch(j){t=j,Re===r&&r!==null&&(Re=r=r.return);continue}break}while(!0)}function F2(){var e=Kc.current;return Kc.current=Hc,e===null?Hc:e}function Tv(){(Ye===0||Ye===3||Ye===2)&&(Ye=4),nt===null||!(ba&268435455)&&!(fd&268435455)||yn(nt,ct)}function Yc(e,t){var r=se;se|=2;var n=F2();(nt!==e||ct!==t)&&(Br=null,fa(e,t));do try{mA();break}catch(a){B2(e,a)}while(!0);if(mv(),se=r,Kc.current=n,Re!==null)throw Error(H(261));return nt=null,ct=0,Ye}function mA(){for(;Re!==null;)z2(Re)}function vA(){for(;Re!==null&&!zN();)z2(Re)}function z2(e){var t=H2(e.alternate,e,Mt);e.memoizedProps=e.pendingProps,t===null?W2(e):Re=t,Pv.current=null}function W2(e){var t=e;do{var r=t.alternate;if(e=t.return,t.flags&32768){if(r=cA(r,t),r!==null){r.flags&=32767,Re=r;return}if(e!==null)e.flags|=32768,e.subtreeFlags=0,e.deletions=null;else{Ye=6,Re=null;return}}else if(r=lA(r,t,Mt),r!==null){Re=r;return}if(t=t.sibling,t!==null){Re=t;return}Re=t=e}while(t!==null);Ye===0&&(Ye=5)}function Jn(e,t,r){var n=ue,a=Jt.transition;try{Jt.transition=null,ue=1,yA(e,t,r,n)}finally{Jt.transition=a,ue=n}return null}function yA(e,t,r,n){do pi();while(bn!==null);if(se&6)throw Error(H(327));r=e.finishedWork;var a=e.finishedLanes;if(r===null)return null;if(e.finishedWork=null,e.finishedLanes=0,r===e.current)throw Error(H(177));e.callbackNode=null,e.callbackPriority=0;var i=r.lanes|r.childLanes;if(QN(e,i),e===nt&&(Re=nt=null,ct=0),!(r.subtreeFlags&2064)&&!(r.flags&2064)||Wl||(Wl=!0,K2(Ac,function(){return pi(),null})),i=(r.flags&15990)!==0,r.subtreeFlags&15990||i){i=Jt.transition,Jt.transition=null;var s=ue;ue=1;var l=se;se|=4,Pv.current=null,dA(e,r),L2(r,e),DP(Wh),Ec=!!zh,Wh=zh=null,e.current=r,fA(r),WN(),se=l,ue=s,Jt.transition=i}else e.current=r;if(Wl&&(Wl=!1,bn=e,Gc=a),i=e.pendingLanes,i===0&&(Cn=null),KN(r.stateNode),Et(e,Le()),t!==null)for(n=e.onRecoverableError,r=0;r<t.length;r++)a=t[r],n(a.value,{componentStack:a.stack,digest:a.digest});if(Vc)throw Vc=!1,e=lp,lp=null,e;return Gc&1&&e.tag!==0&&pi(),i=e.pendingLanes,i&1?e===cp?es++:(es=0,cp=e):es=0,Bn(),null}function pi(){if(bn!==null){var e=ww(Gc),t=Jt.transition,r=ue;try{if(Jt.transition=null,ue=16>e?16:e,bn===null)var n=!1;else{if(e=bn,bn=null,Gc=0,se&6)throw Error(H(331));var a=se;for(se|=4,G=e.current;G!==null;){var i=G,s=i.child;if(G.flags&16){var l=i.deletions;if(l!==null){for(var c=0;c<l.length;c++){var u=l[c];for(G=u;G!==null;){var f=G;switch(f.tag){case 0:case 11:case 15:Jo(8,f,i)}var d=f.child;if(d!==null)d.return=f,G=d;else for(;G!==null;){f=G;var h=f.sibling,p=f.return;if(T2(f),f===u){G=null;break}if(h!==null){h.return=p,G=h;break}G=p}}}var g=i.alternate;if(g!==null){var y=g.child;if(y!==null){g.child=null;do{var b=y.sibling;y.sibling=null,y=b}while(y!==null)}}G=i}}if(i.subtreeFlags&2064&&s!==null)s.return=i,G=s;else e:for(;G!==null;){if(i=G,i.flags&2048)switch(i.tag){case 0:case 11:case 15:Jo(9,i,i.return)}var v=i.sibling;if(v!==null){v.return=i.return,G=v;break e}G=i.return}}var m=e.current;for(G=m;G!==null;){s=G;var x=s.child;if(s.subtreeFlags&2064&&x!==null)x.return=s,G=x;else e:for(s=m;G!==null;){if(l=G,l.flags&2048)try{switch(l.tag){case 0:case 11:case 15:dd(9,l)}}catch(j){Me(l,l.return,j)}if(l===s){G=null;break e}var S=l.sibling;if(S!==null){S.return=l.return,G=S;break e}G=l.return}}if(se=a,Bn(),Pr&&typeof Pr.onPostCommitFiberRoot=="function")try{Pr.onPostCommitFiberRoot(nd,e)}catch{}n=!0}return n}finally{ue=r,Jt.transition=t}}return!1}function s0(e,t,r){t=ki(r,t),t=w2(e,t,1),e=An(e,t,1),t=jt(),e!==null&&(cl(e,1,t),Et(e,t))}function Me(e,t,r){if(e.tag===3)s0(e,e,r);else for(;t!==null;){if(t.tag===3){s0(t,e,r);break}else if(t.tag===1){var n=t.stateNode;if(typeof t.type.getDerivedStateFromError=="function"||typeof n.componentDidCatch=="function"&&(Cn===null||!Cn.has(n))){e=ki(r,e),e=S2(t,e,1),t=An(t,e,1),e=jt(),t!==null&&(cl(t,1,e),Et(t,e));break}}t=t.return}}function gA(e,t,r){var n=e.pingCache;n!==null&&n.delete(t),t=jt(),e.pingedLanes|=e.suspendedLanes&r,nt===e&&(ct&r)===r&&(Ye===4||Ye===3&&(ct&130023424)===ct&&500>Le()-Cv?fa(e,0):Av|=r),Et(e,t)}function U2(e,t){t===0&&(e.mode&1?(t=$l,$l<<=1,!($l&130023424)&&($l=4194304)):t=1);var r=jt();e=Jr(e,t),e!==null&&(cl(e,t,r),Et(e,r))}function xA(e){var t=e.memoizedState,r=0;t!==null&&(r=t.retryLane),U2(e,r)}function bA(e,t){var r=0;switch(e.tag){case 13:var n=e.stateNode,a=e.memoizedState;a!==null&&(r=a.retryLane);break;case 19:n=e.stateNode;break;default:throw Error(H(314))}n!==null&&n.delete(t),U2(e,r)}var H2;H2=function(e,t,r){if(e!==null)if(e.memoizedProps!==t.pendingProps||At.current)Nt=!0;else{if(!(e.lanes&r)&&!(t.flags&128))return Nt=!1,sA(e,t,r);Nt=!!(e.flags&131072)}else Nt=!1,Ne&&t.flags&1048576&&Yw(t,Rc,t.index);switch(t.lanes=0,t.tag){case 2:var n=t.type;xc(e,t),e=t.pendingProps;var a=ji(t,vt.current);hi(t,r),a=Sv(null,t,n,e,a,r);var i=_v();return t.flags|=1,typeof a=="object"&&a!==null&&typeof a.render=="function"&&a.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,Ct(n)?(i=!0,Lc(t)):i=!1,t.memoizedState=a.state!==null&&a.state!==void 0?a.state:null,gv(t),a.updater=ud,t.stateNode=a,a._reactInternals=t,Qh(t,n,e,r),t=ep(null,t,n,!0,i,r)):(t.tag=0,Ne&&i&&dv(t),gt(null,t,a,r),t=t.child),t;case 16:n=t.elementType;e:{switch(xc(e,t),e=t.pendingProps,a=n._init,n=a(n._payload),t.type=n,a=t.tag=wA(n),e=ur(n,e),a){case 0:t=Zh(null,t,n,e,r);break e;case 1:t=Qg(null,t,n,e,r);break e;case 11:t=qg(null,t,n,e,r);break e;case 14:t=Xg(null,t,n,ur(n.type,e),r);break e}throw Error(H(306,n,""))}return t;case 0:return n=t.type,a=t.pendingProps,a=t.elementType===n?a:ur(n,a),Zh(e,t,n,a,r);case 1:return n=t.type,a=t.pendingProps,a=t.elementType===n?a:ur(n,a),Qg(e,t,n,a,r);case 3:e:{if(N2(t),e===null)throw Error(H(387));n=t.pendingProps,i=t.memoizedState,a=i.element,e2(e,t),zc(t,n,null,r);var s=t.memoizedState;if(n=s.element,i.isDehydrated)if(i={element:n,isDehydrated:!1,cache:s.cache,pendingSuspenseBoundaries:s.pendingSuspenseBoundaries,transitions:s.transitions},t.updateQueue.baseState=i,t.memoizedState=i,t.flags&256){a=ki(Error(H(423)),t),t=Jg(e,t,n,r,a);break e}else if(n!==a){a=ki(Error(H(424)),t),t=Jg(e,t,n,r,a);break e}else for(Dt=Pn(t.stateNode.containerInfo.firstChild),Rt=t,Ne=!0,hr=null,r=Jw(t,null,n,r),t.child=r;r;)r.flags=r.flags&-3|4096,r=r.sibling;else{if(wi(),n===a){t=Zr(e,t,r);break e}gt(e,t,n,r)}t=t.child}return t;case 5:return t2(t),e===null&&Yh(t),n=t.type,a=t.pendingProps,i=e!==null?e.memoizedProps:null,s=a.children,Uh(n,a)?s=null:i!==null&&Uh(n,i)&&(t.flags|=32),O2(e,t),gt(e,t,s,r),t.child;case 6:return e===null&&Yh(t),null;case 13:return P2(e,t,r);case 4:return xv(t,t.stateNode.containerInfo),n=t.pendingProps,e===null?t.child=Si(t,null,n,r):gt(e,t,n,r),t.child;case 11:return n=t.type,a=t.pendingProps,a=t.elementType===n?a:ur(n,a),qg(e,t,n,a,r);case 7:return gt(e,t,t.pendingProps,r),t.child;case 8:return gt(e,t,t.pendingProps.children,r),t.child;case 12:return gt(e,t,t.pendingProps.children,r),t.child;case 10:e:{if(n=t.type._context,a=t.pendingProps,i=t.memoizedProps,s=a.value,je(Bc,n._currentValue),n._currentValue=s,i!==null)if(gr(i.value,s)){if(i.children===a.children&&!At.current){t=Zr(e,t,r);break e}}else for(i=t.child,i!==null&&(i.return=t);i!==null;){var l=i.dependencies;if(l!==null){s=i.child;for(var c=l.firstContext;c!==null;){if(c.context===n){if(i.tag===1){c=Gr(-1,r&-r),c.tag=2;var u=i.updateQueue;if(u!==null){u=u.shared;var f=u.pending;f===null?c.next=c:(c.next=f.next,f.next=c),u.pending=c}}i.lanes|=r,c=i.alternate,c!==null&&(c.lanes|=r),qh(i.return,r,t),l.lanes|=r;break}c=c.next}}else if(i.tag===10)s=i.type===t.type?null:i.child;else if(i.tag===18){if(s=i.return,s===null)throw Error(H(341));s.lanes|=r,l=s.alternate,l!==null&&(l.lanes|=r),qh(s,r,t),s=i.sibling}else s=i.child;if(s!==null)s.return=i;else for(s=i;s!==null;){if(s===t){s=null;break}if(i=s.sibling,i!==null){i.return=s.return,s=i;break}s=s.return}i=s}gt(e,t,a.children,r),t=t.child}return t;case 9:return a=t.type,n=t.pendingProps.children,hi(t,r),a=Zt(a),n=n(a),t.flags|=1,gt(e,t,n,r),t.child;case 14:return n=t.type,a=ur(n,t.pendingProps),a=ur(n.type,a),Xg(e,t,n,a,r);case 15:return _2(e,t,t.type,t.pendingProps,r);case 17:return n=t.type,a=t.pendingProps,a=t.elementType===n?a:ur(n,a),xc(e,t),t.tag=1,Ct(n)?(e=!0,Lc(t)):e=!1,hi(t,r),j2(t,n,a),Qh(t,n,a,r),ep(null,t,n,!0,e,r);case 19:return A2(e,t,r);case 22:return k2(e,t,r)}throw Error(H(156,t.tag))};function K2(e,t){return gw(e,t)}function jA(e,t,r,n){this.tag=e,this.key=r,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=n,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Xt(e,t,r,n){return new jA(e,t,r,n)}function Mv(e){return e=e.prototype,!(!e||!e.isReactComponent)}function wA(e){if(typeof e=="function")return Mv(e)?1:0;if(e!=null){if(e=e.$$typeof,e===Zm)return 11;if(e===ev)return 14}return 2}function $n(e,t){var r=e.alternate;return r===null?(r=Xt(e.tag,t,e.key,e.mode),r.elementType=e.elementType,r.type=e.type,r.stateNode=e.stateNode,r.alternate=e,e.alternate=r):(r.pendingProps=t,r.type=e.type,r.flags=0,r.subtreeFlags=0,r.deletions=null),r.flags=e.flags&14680064,r.childLanes=e.childLanes,r.lanes=e.lanes,r.child=e.child,r.memoizedProps=e.memoizedProps,r.memoizedState=e.memoizedState,r.updateQueue=e.updateQueue,t=e.dependencies,r.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},r.sibling=e.sibling,r.index=e.index,r.ref=e.ref,r}function wc(e,t,r,n,a,i){var s=2;if(n=e,typeof e=="function")Mv(e)&&(s=1);else if(typeof e=="string")s=5;else e:switch(e){case Ga:return ha(r.children,a,i,t);case Jm:s=8,a|=8;break;case jh:return e=Xt(12,r,t,a|2),e.elementType=jh,e.lanes=i,e;case wh:return e=Xt(13,r,t,a),e.elementType=wh,e.lanes=i,e;case Sh:return e=Xt(19,r,t,a),e.elementType=Sh,e.lanes=i,e;case tw:return hd(r,a,i,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case Zj:s=10;break e;case ew:s=9;break e;case Zm:s=11;break e;case ev:s=14;break e;case hn:s=16,n=null;break e}throw Error(H(130,e==null?e:typeof e,""))}return t=Xt(s,r,t,a),t.elementType=e,t.type=n,t.lanes=i,t}function ha(e,t,r,n){return e=Xt(7,e,n,t),e.lanes=r,e}function hd(e,t,r,n){return e=Xt(22,e,n,t),e.elementType=tw,e.lanes=r,e.stateNode={isHidden:!1},e}function Df(e,t,r){return e=Xt(6,e,null,t),e.lanes=r,e}function Rf(e,t,r){return t=Xt(4,e.children!==null?e.children:[],e.key,t),t.lanes=r,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function SA(e,t,r,n,a){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=gf(0),this.expirationTimes=gf(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=gf(0),this.identifierPrefix=n,this.onRecoverableError=a,this.mutableSourceEagerHydrationData=null}function Iv(e,t,r,n,a,i,s,l,c){return e=new SA(e,t,r,l,c),t===1?(t=1,i===!0&&(t|=8)):t=0,i=Xt(3,null,null,t),e.current=i,i.stateNode=e,i.memoizedState={element:n,isDehydrated:r,cache:null,transitions:null,pendingSuspenseBoundaries:null},gv(i),e}function _A(e,t,r){var n=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:Va,key:n==null?null:""+n,children:e,containerInfo:t,implementation:r}}function V2(e){if(!e)return Ln;e=e._reactInternals;e:{if(Aa(e)!==e||e.tag!==1)throw Error(H(170));var t=e;do{switch(t.tag){case 3:t=t.stateNode.context;break e;case 1:if(Ct(t.type)){t=t.stateNode.__reactInternalMemoizedMergedChildContext;break e}}t=t.return}while(t!==null);throw Error(H(171))}if(e.tag===1){var r=e.type;if(Ct(r))return Vw(e,r,t)}return t}function G2(e,t,r,n,a,i,s,l,c){return e=Iv(r,n,!0,e,a,i,s,l,c),e.context=V2(null),r=e.current,n=jt(),a=En(r),i=Gr(n,a),i.callback=t??null,An(r,i,a),e.current.lanes=a,cl(e,a,n),Et(e,n),e}function pd(e,t,r,n){var a=t.current,i=jt(),s=En(a);return r=V2(r),t.context===null?t.context=r:t.pendingContext=r,t=Gr(i,s),t.payload={element:e},n=n===void 0?null:n,n!==null&&(t.callback=n),e=An(a,t,s),e!==null&&(vr(e,a,s,i),vc(e,a,s)),s}function qc(e){if(e=e.current,!e.child)return null;switch(e.child.tag){case 5:return e.child.stateNode;default:return e.child.stateNode}}function l0(e,t){if(e=e.memoizedState,e!==null&&e.dehydrated!==null){var r=e.retryLane;e.retryLane=r!==0&&r<t?r:t}}function Lv(e,t){l0(e,t),(e=e.alternate)&&l0(e,t)}function kA(){return null}var Y2=typeof reportError=="function"?reportError:function(e){console.error(e)};function Dv(e){this._internalRoot=e}md.prototype.render=Dv.prototype.render=function(e){var t=this._internalRoot;if(t===null)throw Error(H(409));pd(e,t,null,null)};md.prototype.unmount=Dv.prototype.unmount=function(){var e=this._internalRoot;if(e!==null){this._internalRoot=null;var t=e.containerInfo;ja(function(){pd(null,e,null,null)}),t[Qr]=null}};function md(e){this._internalRoot=e}md.prototype.unstable_scheduleHydration=function(e){if(e){var t=kw();e={blockedOn:null,target:e,priority:t};for(var r=0;r<vn.length&&t!==0&&t<vn[r].priority;r++);vn.splice(r,0,e),r===0&&Nw(e)}};function Rv(e){return!(!e||e.nodeType!==1&&e.nodeType!==9&&e.nodeType!==11)}function vd(e){return!(!e||e.nodeType!==1&&e.nodeType!==9&&e.nodeType!==11&&(e.nodeType!==8||e.nodeValue!==" react-mount-point-unstable "))}function c0(){}function OA(e,t,r,n,a){if(a){if(typeof n=="function"){var i=n;n=function(){var u=qc(s);i.call(u)}}var s=G2(t,n,e,0,null,!1,!1,"",c0);return e._reactRootContainer=s,e[Qr]=s.current,ms(e.nodeType===8?e.parentNode:e),ja(),s}for(;a=e.lastChild;)e.removeChild(a);if(typeof n=="function"){var l=n;n=function(){var u=qc(c);l.call(u)}}var c=Iv(e,0,!1,null,null,!1,!1,"",c0);return e._reactRootContainer=c,e[Qr]=c.current,ms(e.nodeType===8?e.parentNode:e),ja(function(){pd(t,c,r,n)}),c}function yd(e,t,r,n,a){var i=r._reactRootContainer;if(i){var s=i;if(typeof a=="function"){var l=a;a=function(){var c=qc(s);l.call(c)}}pd(t,s,e,a)}else s=OA(r,t,e,a,n);return qc(s)}Sw=function(e){switch(e.tag){case 3:var t=e.stateNode;if(t.current.memoizedState.isDehydrated){var r=zo(t.pendingLanes);r!==0&&(nv(t,r|1),Et(t,Le()),!(se&6)&&(Oi=Le()+500,Bn()))}break;case 13:ja(function(){var n=Jr(e,1);if(n!==null){var a=jt();vr(n,e,1,a)}}),Lv(e,1)}};av=function(e){if(e.tag===13){var t=Jr(e,134217728);if(t!==null){var r=jt();vr(t,e,134217728,r)}Lv(e,134217728)}};_w=function(e){if(e.tag===13){var t=En(e),r=Jr(e,t);if(r!==null){var n=jt();vr(r,e,t,n)}Lv(e,t)}};kw=function(){return ue};Ow=function(e,t){var r=ue;try{return ue=e,t()}finally{ue=r}};Th=function(e,t,r){switch(t){case"input":if(Oh(e,r),t=r.name,r.type==="radio"&&t!=null){for(r=e;r.parentNode;)r=r.parentNode;for(r=r.querySelectorAll("input[name="+JSON.stringify(""+t)+'][type="radio"]'),t=0;t<r.length;t++){var n=r[t];if(n!==e&&n.form===e.form){var a=sd(n);if(!a)throw Error(H(90));nw(n),Oh(n,a)}}}break;case"textarea":iw(e,r);break;case"select":t=r.value,t!=null&&ci(e,!!r.multiple,t,!1)}};fw=Ev;hw=ja;var NA={usingClientEntryPoint:!1,Events:[dl,Qa,sd,uw,dw,Ev]},Oo={findFiberByHostInstance:na,bundleType:0,version:"18.3.1",rendererPackageName:"react-dom"},PA={bundleType:Oo.bundleType,version:Oo.version,rendererPackageName:Oo.rendererPackageName,rendererConfig:Oo.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:an.ReactCurrentDispatcher,findHostInstanceByFiber:function(e){return e=vw(e),e===null?null:e.stateNode},findFiberByHostInstance:Oo.findFiberByHostInstance||kA,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.3.1-next-f1338f8080-20240426"};if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"){var Ul=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!Ul.isDisabled&&Ul.supportsFiber)try{nd=Ul.inject(PA),Pr=Ul}catch{}}Wt.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=NA;Wt.createPortal=function(e,t){var r=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!Rv(t))throw Error(H(200));return _A(e,t,null,r)};Wt.createRoot=function(e,t){if(!Rv(e))throw Error(H(299));var r=!1,n="",a=Y2;return t!=null&&(t.unstable_strictMode===!0&&(r=!0),t.identifierPrefix!==void 0&&(n=t.identifierPrefix),t.onRecoverableError!==void 0&&(a=t.onRecoverableError)),t=Iv(e,1,!1,null,null,r,!1,n,a),e[Qr]=t.current,ms(e.nodeType===8?e.parentNode:e),new Dv(t)};Wt.findDOMNode=function(e){if(e==null)return null;if(e.nodeType===1)return e;var t=e._reactInternals;if(t===void 0)throw typeof e.render=="function"?Error(H(188)):(e=Object.keys(e).join(","),Error(H(268,e)));return e=vw(t),e=e===null?null:e.stateNode,e};Wt.flushSync=function(e){return ja(e)};Wt.hydrate=function(e,t,r){if(!vd(t))throw Error(H(200));return yd(null,e,t,!0,r)};Wt.hydrateRoot=function(e,t,r){if(!Rv(e))throw Error(H(405));var n=r!=null&&r.hydratedSources||null,a=!1,i="",s=Y2;if(r!=null&&(r.unstable_strictMode===!0&&(a=!0),r.identifierPrefix!==void 0&&(i=r.identifierPrefix),r.onRecoverableError!==void 0&&(s=r.onRecoverableError)),t=G2(t,null,e,1,r??null,a,!1,i,s),e[Qr]=t.current,ms(e),n)for(e=0;e<n.length;e++)r=n[e],a=r._getVersion,a=a(r._source),t.mutableSourceEagerHydrationData==null?t.mutableSourceEagerHydrationData=[r,a]:t.mutableSourceEagerHydrationData.push(r,a);return new md(t)};Wt.render=function(e,t,r){if(!vd(t))throw Error(H(200));return yd(null,e,t,!1,r)};Wt.unmountComponentAtNode=function(e){if(!vd(e))throw Error(H(40));return e._reactRootContainer?(ja(function(){yd(null,null,e,!1,function(){e._reactRootContainer=null,e[Qr]=null})}),!0):!1};Wt.unstable_batchedUpdates=Ev;Wt.unstable_renderSubtreeIntoContainer=function(e,t,r,n){if(!vd(r))throw Error(H(200));if(e==null||e._reactInternals===void 0)throw Error(H(38));return yd(e,t,r,!1,n)};Wt.version="18.3.1-next-f1338f8080-20240426";function q2(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(q2)}catch(e){console.error(e)}}q2(),qj.exports=Wt;var AA=qj.exports,u0=AA;xh.createRoot=u0.createRoot,xh.hydrateRoot=u0.hydrateRoot;/**
- * @remix-run/router v1.23.2
- *
- * Copyright (c) Remix Software Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE.md file in the root directory of this source tree.
- *
- * @license MIT
- */function _s(){return _s=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},_s.apply(this,arguments)}var jn;(function(e){e.Pop="POP",e.Push="PUSH",e.Replace="REPLACE"})(jn||(jn={}));const d0="popstate";function CA(e){e===void 0&&(e={});function t(n,a){let{pathname:i,search:s,hash:l}=n.location;return fp("",{pathname:i,search:s,hash:l},a.state&&a.state.usr||null,a.state&&a.state.key||"default")}function r(n,a){return typeof a=="string"?a:Xc(a)}return $A(t,r,null,e)}function Fe(e,t){if(e===!1||e===null||typeof e>"u")throw new Error(t)}function Bv(e,t){if(!e){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function EA(){return Math.random().toString(36).substr(2,8)}function f0(e,t){return{usr:e.state,key:e.key,idx:t}}function fp(e,t,r,n){return r===void 0&&(r=null),_s({pathname:typeof e=="string"?e:e.pathname,search:"",hash:""},typeof t=="string"?no(t):t,{state:r,key:t&&t.key||n||EA()})}function Xc(e){let{pathname:t="/",search:r="",hash:n=""}=e;return r&&r!=="?"&&(t+=r.charAt(0)==="?"?r:"?"+r),n&&n!=="#"&&(t+=n.charAt(0)==="#"?n:"#"+n),t}function no(e){let t={};if(e){let r=e.indexOf("#");r>=0&&(t.hash=e.substr(r),e=e.substr(0,r));let n=e.indexOf("?");n>=0&&(t.search=e.substr(n),e=e.substr(0,n)),e&&(t.pathname=e)}return t}function $A(e,t,r,n){n===void 0&&(n={});let{window:a=document.defaultView,v5Compat:i=!1}=n,s=a.history,l=jn.Pop,c=null,u=f();u==null&&(u=0,s.replaceState(_s({},s.state,{idx:u}),""));function f(){return(s.state||{idx:null}).idx}function d(){l=jn.Pop;let b=f(),v=b==null?null:b-u;u=b,c&&c({action:l,location:y.location,delta:v})}function h(b,v){l=jn.Push;let m=fp(y.location,b,v);u=f()+1;let x=f0(m,u),S=y.createHref(m);try{s.pushState(x,"",S)}catch(j){if(j instanceof DOMException&&j.name==="DataCloneError")throw j;a.location.assign(S)}i&&c&&c({action:l,location:y.location,delta:1})}function p(b,v){l=jn.Replace;let m=fp(y.location,b,v);u=f();let x=f0(m,u),S=y.createHref(m);s.replaceState(x,"",S),i&&c&&c({action:l,location:y.location,delta:0})}function g(b){let v=a.location.origin!=="null"?a.location.origin:a.location.href,m=typeof b=="string"?b:Xc(b);return m=m.replace(/ $/,"%20"),Fe(v,"No window.location.(origin|href) available to create URL for href: "+m),new URL(m,v)}let y={get action(){return l},get location(){return e(a,s)},listen(b){if(c)throw new Error("A history only accepts one active listener");return a.addEventListener(d0,d),c=b,()=>{a.removeEventListener(d0,d),c=null}},createHref(b){return t(a,b)},createURL:g,encodeLocation(b){let v=g(b);return{pathname:v.pathname,search:v.search,hash:v.hash}},push:h,replace:p,go(b){return s.go(b)}};return y}var h0;(function(e){e.data="data",e.deferred="deferred",e.redirect="redirect",e.error="error"})(h0||(h0={}));function TA(e,t,r){return r===void 0&&(r="/"),MA(e,t,r)}function MA(e,t,r,n){let a=typeof t=="string"?no(t):t,i=Fv(a.pathname||"/",r);if(i==null)return null;let s=X2(e);IA(s);let l=null;for(let c=0;l==null&&c<s.length;++c){let u=GA(i);l=HA(s[c],u)}return l}function X2(e,t,r,n){t===void 0&&(t=[]),r===void 0&&(r=[]),n===void 0&&(n="");let a=(i,s,l)=>{let c={relativePath:l===void 0?i.path||"":l,caseSensitive:i.caseSensitive===!0,childrenIndex:s,route:i};c.relativePath.startsWith("/")&&(Fe(c.relativePath.startsWith(n),'Absolute route path "'+c.relativePath+'" nested under path '+('"'+n+'" is not valid. An absolute child route path ')+"must start with the combined path of all its parent routes."),c.relativePath=c.relativePath.slice(n.length));let u=Tn([n,c.relativePath]),f=r.concat(c);i.children&&i.children.length>0&&(Fe(i.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+u+'".')),X2(i.children,t,f,u)),!(i.path==null&&!i.index)&&t.push({path:u,score:WA(u,i.index),routesMeta:f})};return e.forEach((i,s)=>{var l;if(i.path===""||!((l=i.path)!=null&&l.includes("?")))a(i,s);else for(let c of Q2(i.path))a(i,s,c)}),t}function Q2(e){let t=e.split("/");if(t.length===0)return[];let[r,...n]=t,a=r.endsWith("?"),i=r.replace(/\?$/,"");if(n.length===0)return a?[i,""]:[i];let s=Q2(n.join("/")),l=[];return l.push(...s.map(c=>c===""?i:[i,c].join("/"))),a&&l.push(...s),l.map(c=>e.startsWith("/")&&c===""?"/":c)}function IA(e){e.sort((t,r)=>t.score!==r.score?r.score-t.score:UA(t.routesMeta.map(n=>n.childrenIndex),r.routesMeta.map(n=>n.childrenIndex)))}const LA=/^:[\w-]+$/,DA=3,RA=2,BA=1,FA=10,zA=-2,p0=e=>e==="*";function WA(e,t){let r=e.split("/"),n=r.length;return r.some(p0)&&(n+=zA),t&&(n+=RA),r.filter(a=>!p0(a)).reduce((a,i)=>a+(LA.test(i)?DA:i===""?BA:FA),n)}function UA(e,t){return e.length===t.length&&e.slice(0,-1).every((n,a)=>n===t[a])?e[e.length-1]-t[t.length-1]:0}function HA(e,t,r){let{routesMeta:n}=e,a={},i="/",s=[];for(let l=0;l<n.length;++l){let c=n[l],u=l===n.length-1,f=i==="/"?t:t.slice(i.length)||"/",d=KA({path:c.relativePath,caseSensitive:c.caseSensitive,end:u},f),h=c.route;if(!d)return null;Object.assign(a,d.params),s.push({params:a,pathname:Tn([i,d.pathname]),pathnameBase:JA(Tn([i,d.pathnameBase])),route:h}),d.pathnameBase!=="/"&&(i=Tn([i,d.pathnameBase]))}return s}function KA(e,t){typeof e=="string"&&(e={path:e,caseSensitive:!1,end:!0});let[r,n]=VA(e.path,e.caseSensitive,e.end),a=t.match(r);if(!a)return null;let i=a[0],s=i.replace(/(.)\/+$/,"$1"),l=a.slice(1);return{params:n.reduce((u,f,d)=>{let{paramName:h,isOptional:p}=f;if(h==="*"){let y=l[d]||"";s=i.slice(0,i.length-y.length).replace(/(.)\/+$/,"$1")}const g=l[d];return p&&!g?u[h]=void 0:u[h]=(g||"").replace(/%2F/g,"/"),u},{}),pathname:i,pathnameBase:s,pattern:e}}function VA(e,t,r){t===void 0&&(t=!1),r===void 0&&(r=!0),Bv(e==="*"||!e.endsWith("*")||e.endsWith("/*"),'Route path "'+e+'" will be treated as if it were '+('"'+e.replace(/\*$/,"/*")+'" because the `*` character must ')+"always follow a `/` in the pattern. To get rid of this warning, "+('please change the route path to "'+e.replace(/\*$/,"/*")+'".'));let n=[],a="^"+e.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(s,l,c)=>(n.push({paramName:l,isOptional:c!=null}),c?"/?([^\\/]+)?":"/([^\\/]+)"));return e.endsWith("*")?(n.push({paramName:"*"}),a+=e==="*"||e==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):r?a+="\\/*$":e!==""&&e!=="/"&&(a+="(?:(?=\\/|$))"),[new RegExp(a,t?void 0:"i"),n]}function GA(e){try{return e.split("/").map(t=>decodeURIComponent(t).replace(/\//g,"%2F")).join("/")}catch(t){return Bv(!1,'The URL path "'+e+'" could not be decoded because it is is a malformed URL segment. This is probably due to a bad percent '+("encoding ("+t+").")),e}}function Fv(e,t){if(t==="/")return e;if(!e.toLowerCase().startsWith(t.toLowerCase()))return null;let r=t.endsWith("/")?t.length-1:t.length,n=e.charAt(r);return n&&n!=="/"?null:e.slice(r)||"/"}const YA=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,qA=e=>YA.test(e);function XA(e,t){t===void 0&&(t="/");let{pathname:r,search:n="",hash:a=""}=typeof e=="string"?no(e):e,i;if(r)if(qA(r))i=r;else{if(r.includes("//")){let s=r;r=r.replace(/\/\/+/g,"/"),Bv(!1,"Pathnames cannot have embedded double slashes - normalizing "+(s+" -> "+r))}r.startsWith("/")?i=m0(r.substring(1),"/"):i=m0(r,t)}else i=t;return{pathname:i,search:ZA(n),hash:eC(a)}}function m0(e,t){let r=t.replace(/\/+$/,"").split("/");return e.split("/").forEach(a=>{a===".."?r.length>1&&r.pop():a!=="."&&r.push(a)}),r.length>1?r.join("/"):"/"}function Bf(e,t,r,n){return"Cannot include a '"+e+"' character in a manually specified "+("`to."+t+"` field ["+JSON.stringify(n)+"]. Please separate it out to the ")+("`to."+r+"` field. Alternatively you may provide the full path as ")+'a string in <Link to="..."> and the router will parse it for you.'}function QA(e){return e.filter((t,r)=>r===0||t.route.path&&t.route.path.length>0)}function J2(e,t){let r=QA(e);return t?r.map((n,a)=>a===r.length-1?n.pathname:n.pathnameBase):r.map(n=>n.pathnameBase)}function Z2(e,t,r,n){n===void 0&&(n=!1);let a;typeof e=="string"?a=no(e):(a=_s({},e),Fe(!a.pathname||!a.pathname.includes("?"),Bf("?","pathname","search",a)),Fe(!a.pathname||!a.pathname.includes("#"),Bf("#","pathname","hash",a)),Fe(!a.search||!a.search.includes("#"),Bf("#","search","hash",a)));let i=e===""||a.pathname==="",s=i?"/":a.pathname,l;if(s==null)l=r;else{let d=t.length-1;if(!n&&s.startsWith("..")){let h=s.split("/");for(;h[0]==="..";)h.shift(),d-=1;a.pathname=h.join("/")}l=d>=0?t[d]:"/"}let c=XA(a,l),u=s&&s!=="/"&&s.endsWith("/"),f=(i||s===".")&&r.endsWith("/");return!c.pathname.endsWith("/")&&(u||f)&&(c.pathname+="/"),c}const Tn=e=>e.join("/").replace(/\/\/+/g,"/"),JA=e=>e.replace(/\/+$/,"").replace(/^\/*/,"/"),ZA=e=>!e||e==="?"?"":e.startsWith("?")?e:"?"+e,eC=e=>!e||e==="#"?"":e.startsWith("#")?e:"#"+e;function tC(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.internal=="boolean"&&"data"in e}const eS=["post","put","patch","delete"];new Set(eS);const rC=["get",...eS];new Set(rC);/**
- * React Router v6.30.3
- *
- * Copyright (c) Remix Software Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE.md file in the root directory of this source tree.
- *
- * @license MIT
- */function ks(){return ks=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},ks.apply(this,arguments)}const zv=P.createContext(null),nC=P.createContext(null),Ca=P.createContext(null),gd=P.createContext(null),Fn=P.createContext({outlet:null,matches:[],isDataRoute:!1}),tS=P.createContext(null);function aC(e,t){let{relative:r}=t===void 0?{}:t;hl()||Fe(!1);let{basename:n,navigator:a}=P.useContext(Ca),{hash:i,pathname:s,search:l}=nS(e,{relative:r}),c=s;return n!=="/"&&(c=s==="/"?n:Tn([n,s])),a.createHref({pathname:c,search:l,hash:i})}function hl(){return P.useContext(gd)!=null}function pl(){return hl()||Fe(!1),P.useContext(gd).location}function rS(e){P.useContext(Ca).static||P.useLayoutEffect(e)}function xd(){let{isDataRoute:e}=P.useContext(Fn);return e?xC():iC()}function iC(){hl()||Fe(!1);let e=P.useContext(zv),{basename:t,future:r,navigator:n}=P.useContext(Ca),{matches:a}=P.useContext(Fn),{pathname:i}=pl(),s=JSON.stringify(J2(a,r.v7_relativeSplatPath)),l=P.useRef(!1);return rS(()=>{l.current=!0}),P.useCallback(function(u,f){if(f===void 0&&(f={}),!l.current)return;if(typeof u=="number"){n.go(u);return}let d=Z2(u,JSON.parse(s),i,f.relative==="path");e==null&&t!=="/"&&(d.pathname=d.pathname==="/"?t:Tn([t,d.pathname])),(f.replace?n.replace:n.push)(d,f.state,f)},[t,n,s,i,e])}const oC=P.createContext(null);function sC(e){let t=P.useContext(Fn).outlet;return t&&P.createElement(oC.Provider,{value:e},t)}function nS(e,t){let{relative:r}=t===void 0?{}:t,{future:n}=P.useContext(Ca),{matches:a}=P.useContext(Fn),{pathname:i}=pl(),s=JSON.stringify(J2(a,n.v7_relativeSplatPath));return P.useMemo(()=>Z2(e,JSON.parse(s),i,r==="path"),[e,s,i,r])}function lC(e,t){return cC(e,t)}function cC(e,t,r,n){hl()||Fe(!1);let{navigator:a}=P.useContext(Ca),{matches:i}=P.useContext(Fn),s=i[i.length-1],l=s?s.params:{};s&&s.pathname;let c=s?s.pathnameBase:"/";s&&s.route;let u=pl(),f;if(t){var d;let b=typeof t=="string"?no(t):t;c==="/"||(d=b.pathname)!=null&&d.startsWith(c)||Fe(!1),f=b}else f=u;let h=f.pathname||"/",p=h;if(c!=="/"){let b=c.replace(/^\//,"").split("/");p="/"+h.replace(/^\//,"").split("/").slice(b.length).join("/")}let g=TA(e,{pathname:p}),y=pC(g&&g.map(b=>Object.assign({},b,{params:Object.assign({},l,b.params),pathname:Tn([c,a.encodeLocation?a.encodeLocation(b.pathname).pathname:b.pathname]),pathnameBase:b.pathnameBase==="/"?c:Tn([c,a.encodeLocation?a.encodeLocation(b.pathnameBase).pathname:b.pathnameBase])})),i,r,n);return t&&y?P.createElement(gd.Provider,{value:{location:ks({pathname:"/",search:"",hash:"",state:null,key:"default"},f),navigationType:jn.Pop}},y):y}function uC(){let e=gC(),t=tC(e)?e.status+" "+e.statusText:e instanceof Error?e.message:JSON.stringify(e),r=e instanceof Error?e.stack:null,a={padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"};return P.createElement(P.Fragment,null,P.createElement("h2",null,"Unexpected Application Error!"),P.createElement("h3",{style:{fontStyle:"italic"}},t),r?P.createElement("pre",{style:a},r):null,null)}const dC=P.createElement(uC,null);class fC extends P.Component{constructor(t){super(t),this.state={location:t.location,revalidation:t.revalidation,error:t.error}}static getDerivedStateFromError(t){return{error:t}}static getDerivedStateFromProps(t,r){return r.location!==t.location||r.revalidation!=="idle"&&t.revalidation==="idle"?{error:t.error,location:t.location,revalidation:t.revalidation}:{error:t.error!==void 0?t.error:r.error,location:r.location,revalidation:t.revalidation||r.revalidation}}componentDidCatch(t,r){console.error("React Router caught the following error during render",t,r)}render(){return this.state.error!==void 0?P.createElement(Fn.Provider,{value:this.props.routeContext},P.createElement(tS.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function hC(e){let{routeContext:t,match:r,children:n}=e,a=P.useContext(zv);return a&&a.static&&a.staticContext&&(r.route.errorElement||r.route.ErrorBoundary)&&(a.staticContext._deepestRenderedBoundaryId=r.route.id),P.createElement(Fn.Provider,{value:t},n)}function pC(e,t,r,n){var a;if(t===void 0&&(t=[]),r===void 0&&(r=null),n===void 0&&(n=null),e==null){var i;if(!r)return null;if(r.errors)e=r.matches;else if((i=n)!=null&&i.v7_partialHydration&&t.length===0&&!r.initialized&&r.matches.length>0)e=r.matches;else return null}let s=e,l=(a=r)==null?void 0:a.errors;if(l!=null){let f=s.findIndex(d=>d.route.id&&(l==null?void 0:l[d.route.id])!==void 0);f>=0||Fe(!1),s=s.slice(0,Math.min(s.length,f+1))}let c=!1,u=-1;if(r&&n&&n.v7_partialHydration)for(let f=0;f<s.length;f++){let d=s[f];if((d.route.HydrateFallback||d.route.hydrateFallbackElement)&&(u=f),d.route.id){let{loaderData:h,errors:p}=r,g=d.route.loader&&h[d.route.id]===void 0&&(!p||p[d.route.id]===void 0);if(d.route.lazy||g){c=!0,u>=0?s=s.slice(0,u+1):s=[s[0]];break}}}return s.reduceRight((f,d,h)=>{let p,g=!1,y=null,b=null;r&&(p=l&&d.route.id?l[d.route.id]:void 0,y=d.route.errorElement||dC,c&&(u<0&&h===0?(bC("route-fallback"),g=!0,b=null):u===h&&(g=!0,b=d.route.hydrateFallbackElement||null)));let v=t.concat(s.slice(0,h+1)),m=()=>{let x;return p?x=y:g?x=b:d.route.Component?x=P.createElement(d.route.Component,null):d.route.element?x=d.route.element:x=f,P.createElement(hC,{match:d,routeContext:{outlet:f,matches:v,isDataRoute:r!=null},children:x})};return r&&(d.route.ErrorBoundary||d.route.errorElement||h===0)?P.createElement(fC,{location:r.location,revalidation:r.revalidation,component:y,error:p,children:m(),routeContext:{outlet:null,matches:v,isDataRoute:!0}}):m()},null)}var aS=function(e){return e.UseBlocker="useBlocker",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e}(aS||{}),iS=function(e){return e.UseBlocker="useBlocker",e.UseLoaderData="useLoaderData",e.UseActionData="useActionData",e.UseRouteError="useRouteError",e.UseNavigation="useNavigation",e.UseRouteLoaderData="useRouteLoaderData",e.UseMatches="useMatches",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e.UseRouteId="useRouteId",e}(iS||{});function mC(e){let t=P.useContext(zv);return t||Fe(!1),t}function vC(e){let t=P.useContext(nC);return t||Fe(!1),t}function yC(e){let t=P.useContext(Fn);return t||Fe(!1),t}function oS(e){let t=yC(),r=t.matches[t.matches.length-1];return r.route.id||Fe(!1),r.route.id}function gC(){var e;let t=P.useContext(tS),r=vC(),n=oS();return t!==void 0?t:(e=r.errors)==null?void 0:e[n]}function xC(){let{router:e}=mC(aS.UseNavigateStable),t=oS(iS.UseNavigateStable),r=P.useRef(!1);return rS(()=>{r.current=!0}),P.useCallback(function(a,i){i===void 0&&(i={}),r.current&&(typeof a=="number"?e.navigate(a):e.navigate(a,ks({fromRouteId:t},i)))},[e,t])}const v0={};function bC(e,t,r){v0[e]||(v0[e]=!0)}function jC(e,t){e==null||e.v7_startTransition,e==null||e.v7_relativeSplatPath}function wC(e){return sC(e.context)}function it(e){Fe(!1)}function SC(e){let{basename:t="/",children:r=null,location:n,navigationType:a=jn.Pop,navigator:i,static:s=!1,future:l}=e;hl()&&Fe(!1);let c=t.replace(/^\/*/,"/"),u=P.useMemo(()=>({basename:c,navigator:i,static:s,future:ks({v7_relativeSplatPath:!1},l)}),[c,l,i,s]);typeof n=="string"&&(n=no(n));let{pathname:f="/",search:d="",hash:h="",state:p=null,key:g="default"}=n,y=P.useMemo(()=>{let b=Fv(f,c);return b==null?null:{location:{pathname:b,search:d,hash:h,state:p,key:g},navigationType:a}},[c,f,d,h,p,g,a]);return y==null?null:P.createElement(Ca.Provider,{value:u},P.createElement(gd.Provider,{children:r,value:y}))}function _C(e){let{children:t,location:r}=e;return lC(hp(t),r)}new Promise(()=>{});function hp(e,t){t===void 0&&(t=[]);let r=[];return P.Children.forEach(e,(n,a)=>{if(!P.isValidElement(n))return;let i=[...t,a];if(n.type===P.Fragment){r.push.apply(r,hp(n.props.children,i));return}n.type!==it&&Fe(!1),!n.props.index||!n.props.children||Fe(!1);let s={id:n.props.id||i.join("-"),caseSensitive:n.props.caseSensitive,element:n.props.element,Component:n.props.Component,index:n.props.index,path:n.props.path,loader:n.props.loader,action:n.props.action,errorElement:n.props.errorElement,ErrorBoundary:n.props.ErrorBoundary,hasErrorBoundary:n.props.ErrorBoundary!=null||n.props.errorElement!=null,shouldRevalidate:n.props.shouldRevalidate,handle:n.props.handle,lazy:n.props.lazy};n.props.children&&(s.children=hp(n.props.children,i)),r.push(s)}),r}/**
- * React Router DOM v6.30.3
- *
- * Copyright (c) Remix Software Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE.md file in the root directory of this source tree.
- *
- * @license MIT
- */function pp(){return pp=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},pp.apply(this,arguments)}function kC(e,t){if(e==null)return{};var r={},n=Object.keys(e),a,i;for(i=0;i<n.length;i++)a=n[i],!(t.indexOf(a)>=0)&&(r[a]=e[a]);return r}function OC(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function NC(e,t){return e.button===0&&(!t||t==="_self")&&!OC(e)}const PC=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset","viewTransition"],AC="6";try{window.__reactRouterVersion=AC}catch{}const CC="startTransition",y0=gN[CC];function EC(e){let{basename:t,children:r,future:n,window:a}=e,i=P.useRef();i.current==null&&(i.current=CA({window:a,v5Compat:!0}));let s=i.current,[l,c]=P.useState({action:s.action,location:s.location}),{v7_startTransition:u}=n||{},f=P.useCallback(d=>{u&&y0?y0(()=>c(d)):c(d)},[c,u]);return P.useLayoutEffect(()=>s.listen(f),[s,f]),P.useEffect(()=>jC(n),[n]),P.createElement(SC,{basename:t,children:r,location:l.location,navigationType:l.action,navigator:s,future:n})}const $C=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",TC=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,Sc=P.forwardRef(function(t,r){let{onClick:n,relative:a,reloadDocument:i,replace:s,state:l,target:c,to:u,preventScrollReset:f,viewTransition:d}=t,h=kC(t,PC),{basename:p}=P.useContext(Ca),g,y=!1;if(typeof u=="string"&&TC.test(u)&&(g=u,$C))try{let x=new URL(window.location.href),S=u.startsWith("//")?new URL(x.protocol+u):new URL(u),j=Fv(S.pathname,p);S.origin===x.origin&&j!=null?u=j+S.search+S.hash:y=!0}catch{}let b=aC(u,{relative:a}),v=MC(u,{replace:s,state:l,target:c,preventScrollReset:f,relative:a,viewTransition:d});function m(x){n&&n(x),x.defaultPrevented||v(x)}return P.createElement("a",pp({},h,{href:g||b,onClick:y||i?n:m,ref:r,target:c}))});var g0;(function(e){e.UseScrollRestoration="useScrollRestoration",e.UseSubmit="useSubmit",e.UseSubmitFetcher="useSubmitFetcher",e.UseFetcher="useFetcher",e.useViewTransitionState="useViewTransitionState"})(g0||(g0={}));var x0;(function(e){e.UseFetcher="useFetcher",e.UseFetchers="useFetchers",e.UseScrollRestoration="useScrollRestoration"})(x0||(x0={}));function MC(e,t){let{target:r,replace:n,state:a,preventScrollReset:i,relative:s,viewTransition:l}=t===void 0?{}:t,c=xd(),u=pl(),f=nS(e,{relative:s});return P.useCallback(d=>{if(NC(d,r)){d.preventDefault();let h=n!==void 0?n:Xc(u)===Xc(f);c(e,{replace:h,state:a,preventScrollReset:i,relative:s,viewTransition:l})}},[u,c,f,n,a,r,e,i,s,l])}const IC="/api";async function Oe(e,t={}){const r=await fetch(`${IC}${e}`,{...t,credentials:"same-origin",headers:{"Content-Type":"application/json",...t.headers}});return r.status===401&&!e.startsWith("/auth/")?(window.location.href="/login",{}):r.json()}async function me(e,t){return Oe(e,{method:"POST",body:JSON.stringify(t)})}async function Wv(){try{return(await Oe("/auth/session")).authenticated===!0}catch{return!1}}async function LC(e,t){return(await me("/auth/login",{username:e,password:t})).success===!0}async function DC(e){return await me("/auth/google",{credential:e})}async function RC(){try{return await Oe("/auth/google-config")}catch{return{configured:!1}}}async function BC(){await me("/auth/logout",{}),window.location.href="/login"}const FC=`
-@keyframes floatDot {
- 0%, 100% { transform: translateY(0px) scale(1); opacity: 0.18; }
- 50% { transform: translateY(-18px) scale(1.1); opacity: 0.35; }
-}
-.login-dot {
- position: absolute;
- border-radius: 50%;
- background: var(--cyan);
- animation: floatDot linear infinite;
- pointer-events: none;
-}
-`,zC=Array.from({length:22},(e,t)=>({size:2+Math.random()*4,top:Math.random()*100,left:Math.random()*100,duration:4+Math.random()*6,delay:-(Math.random()*8)}));function WC(){const[e,t]=P.useState(""),[r,n]=P.useState(""),[a,i]=P.useState(!1),[s,l]=P.useState(""),[c,u]=P.useState(!1),[f,d]=P.useState(!0),[h,p]=P.useState(!1),[g,y]=P.useState(null),b=P.useRef(null),v=xd();P.useEffect(()=>{Wv().then(w=>{w?v("/"):d(!1)}),RC().then(w=>{w.configured&&w.client_id&&(y(w.client_id),m(w.client_id))})},[]);function m(w){if(document.getElementById("google-gsi")){x(w);return}const _=document.createElement("script");_.id="google-gsi",_.src="https://accounts.google.com/gsi/client",_.async=!0,_.defer=!0,_.onload=()=>x(w),document.head.appendChild(_)}function x(w){var _,O;(O=(_=window.google)==null?void 0:_.accounts)!=null&&O.id&&(window.google.accounts.id.initialize({client_id:w,callback:S,auto_select:!1}),p(!0))}P.useEffect(()=>{var w,_;h&&b.current&&((_=(w=window.google)==null?void 0:w.accounts)!=null&&_.id)&&window.google.accounts.id.renderButton(b.current,{type:"standard",theme:"filled_black",size:"large",text:"signin_with",shape:"pill",width:360})},[h]);async function S(w){l(""),u(!0);try{const _=await DC(w.credential);_.success?v("/"):l(_.error||"Google login failed")}catch{l("Connection error")}u(!1)}async function j(w){w.preventDefault(),l(""),u(!0);try{await LC(e,r)?v("/"):l("Invalid credentials")}catch{l("Connection error")}u(!1)}return f?o.jsx("div",{className:"flex items-center justify-center min-h-screen",style:{background:"var(--bg)"},children:o.jsx("div",{className:"w-8 h-8 rounded-full border-2 border-t-transparent animate-spin",style:{borderColor:"var(--cyan)",borderTopColor:"transparent"}})}):o.jsxs("div",{className:"min-h-screen flex items-center justify-center p-4",style:{background:"var(--bg)",position:"relative",overflow:"hidden"},children:[o.jsx("style",{children:FC}),zC.map((w,_)=>o.jsx("span",{className:"login-dot",style:{width:w.size,height:w.size,top:`${w.top}%`,left:`${w.left}%`,animationDuration:`${w.duration}s`,animationDelay:`${w.delay}s`}},_)),o.jsx("div",{style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",width:600,height:600,borderRadius:"50%",background:"radial-gradient(ellipse, rgba(0,240,255,0.04) 0%, transparent 70%)",pointerEvents:"none"}}),o.jsxs("div",{className:"card-glow fade-in w-full",style:{maxWidth:400,position:"relative",zIndex:1},children:[o.jsxs("div",{className:"flex flex-col items-center mb-7",children:[o.jsx("div",{style:{width:72,height:72,borderRadius:18,background:"linear-gradient(135deg, var(--orange), #C45A08)",display:"flex",alignItems:"center",justifyContent:"center",marginBottom:16,boxShadow:"0 4px 24px rgba(247,147,26,0.35)"},children:o.jsx("span",{style:{color:"#0E0E10",fontWeight:900,fontSize:32,fontFamily:"var(--font-heading)",lineHeight:1},children:"K"})}),o.jsx("h1",{className:"kalshi-gradient heading",style:{fontSize:26,fontWeight:800,letterSpacing:"-0.02em",marginBottom:6},children:"KEN TRADER"}),o.jsx("p",{style:{fontSize:13,color:"var(--text-muted)",marginBottom:4},children:"Event Contracts Trading Platform"}),o.jsx("span",{className:"badge bg-green",style:{fontSize:10},children:"CFTC-Regulated DCM"})]}),s&&o.jsxs("div",{className:"fade-in",style:{display:"flex",alignItems:"center",gap:8,background:"var(--red-dim)",border:"1px solid rgba(255,92,92,0.25)",borderRadius:8,padding:"10px 12px",marginBottom:16,color:"var(--red)",fontSize:13},children:[o.jsx("svg",{style:{width:15,height:15,flexShrink:0},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})}),s]}),g&&o.jsxs("div",{style:{marginBottom:4},children:[o.jsx("div",{ref:b,style:{display:"flex",justifyContent:"center",marginBottom:16}}),o.jsxs("div",{style:{position:"relative",display:"flex",alignItems:"center",marginBottom:20},children:[o.jsx("div",{style:{flex:1,height:1,background:"var(--border)"}}),o.jsx("span",{style:{padding:"0 12px",fontSize:11,color:"var(--text-muted)",background:"var(--surface)",whiteSpace:"nowrap"},children:"or sign in with password"}),o.jsx("div",{style:{flex:1,height:1,background:"var(--border)"}})]})]}),o.jsxs("form",{onSubmit:j,children:[o.jsxs("div",{style:{marginBottom:14},children:[o.jsx("label",{style:{display:"block",fontSize:11,fontWeight:600,color:"var(--text-dim)",marginBottom:6,textTransform:"uppercase",letterSpacing:"0.06em"},children:"Username"}),o.jsx("input",{type:"text",value:e,onChange:w=>t(w.target.value),required:!0,autoComplete:"username",placeholder:"admin",className:"input"})]}),o.jsxs("div",{style:{marginBottom:20},children:[o.jsx("label",{style:{display:"block",fontSize:11,fontWeight:600,color:"var(--text-dim)",marginBottom:6,textTransform:"uppercase",letterSpacing:"0.06em"},children:"Password"}),o.jsxs("div",{style:{position:"relative"},children:[o.jsx("input",{type:a?"text":"password",value:r,onChange:w=>n(w.target.value),required:!0,autoComplete:"current-password",placeholder:"Enter password",className:"input",style:{paddingRight:"2.5rem"}}),o.jsx("button",{type:"button",onClick:()=>i(!a),style:{position:"absolute",right:12,top:"50%",transform:"translateY(-50%)",background:"none",border:"none",cursor:"pointer",color:"var(--text-muted)",padding:0,display:"flex"},children:o.jsx("svg",{style:{width:16,height:16},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:a?"M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.878 9.878L3 3m6.878 6.879L21 21":"M15 12a3 3 0 11-6 0 3 3 0 016 0z M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"})})})]})]}),o.jsxs("button",{type:"submit",disabled:c,className:"btn btn-p btn-lg",style:{width:"100%",opacity:c?.6:1},children:[c&&o.jsx("span",{className:"w-4 h-4 rounded-full border-2 border-t-transparent animate-spin",style:{borderColor:"#0E0E10",borderTopColor:"transparent"}}),c?"Signing in...":"Sign In"]})]}),o.jsx("p",{style:{textAlign:"center",marginTop:20,fontSize:10,color:"var(--text-muted)",letterSpacing:"0.02em"},children:"Ken operates as a CFTC-regulated Designated Contract Market"})]})]})}const b0=[{sym:"POTUS-2028",price:"52c",chg:"+3.1%",up:!0},{sym:"FED-RATE-CUT",price:"78c",chg:"-1.2%",up:!1},{sym:"BTC-100K",price:"34c",chg:"+5.8%",up:!0},{sym:"NVIDIA-BEAT",price:"91c",chg:"+0.4%",up:!0},{sym:"SP-5500",price:"67c",chg:"-2.3%",up:!1},{sym:"INFLATION-4PCT",price:"21c",chg:"+1.7%",up:!0},{sym:"RECESSION-2025",price:"18c",chg:"-0.9%",up:!1},{sym:"ETH-5K",price:"45c",chg:"+2.2%",up:!0},{sym:"APPLE-3T",price:"83c",chg:"+0.6%",up:!0},{sym:"FED-HOLD-JUN",price:"62c",chg:"-1.5%",up:!1},{sym:"JOBS-200K",price:"55c",chg:"+0.8%",up:!0},{sym:"OIL-90",price:"29c",chg:"-3.1%",up:!1},{sym:"OPENAI-IPO",price:"41c",chg:"+4.4%",up:!0},{sym:"GOLD-3K",price:"71c",chg:"+1.9%",up:!0},{sym:"TESLA-SPLIT",price:"37c",chg:"-0.7%",up:!1},{sym:"CPI-3PCT",price:"48c",chg:"+2.6%",up:!0},{sym:"TRUMP-TARIFF",price:"86c",chg:"+0.3%",up:!0},{sym:"VIX-SPIKE",price:"16c",chg:"-4.2%",up:!1},{sym:"SPACEX-LAUNCH",price:"94c",chg:"+0.1%",up:!0},{sym:"SENATE-FLIP",price:"33c",chg:"+3.7%",up:!0}];function UC(){return o.jsx("span",{style:{display:"inline-block",width:3,height:3,borderRadius:"50%",background:"var(--cyan)",opacity:.4,margin:"0 14px",verticalAlign:"middle",flexShrink:0}})}function HC({sym:e,price:t,chg:r,up:n}){return o.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:6,whiteSpace:"nowrap",fontFamily:"var(--font-mono)",fontSize:"0.68rem"},children:[o.jsx("span",{style:{color:"var(--text-dim)",fontWeight:600,letterSpacing:"0.04em"},children:e}),o.jsx("span",{style:{color:"var(--text)",fontWeight:700},children:t}),o.jsx("span",{style:{color:n?"var(--green)":"var(--red)",fontWeight:700,fontSize:"0.62rem"},children:r})]})}function KC(){const e=P.useMemo(()=>[...b0,...b0],[]);return o.jsxs("div",{style:{width:"100%",overflow:"hidden",background:"var(--surface)",borderBottom:"1px solid var(--border)",borderTop:"1px solid var(--border)",height:32,display:"flex",alignItems:"center",position:"relative"},"aria-label":"Live market ticker",role:"marquee",children:[o.jsx("div",{style:{position:"absolute",left:0,top:0,bottom:0,width:48,background:"linear-gradient(90deg, var(--surface), transparent)",zIndex:2,pointerEvents:"none"}}),o.jsx("div",{style:{position:"absolute",right:0,top:0,bottom:0,width:48,background:"linear-gradient(270deg, var(--surface), transparent)",zIndex:2,pointerEvents:"none"}}),o.jsx("div",{style:{display:"inline-flex",alignItems:"center",animation:"ticker 60s linear infinite",willChange:"transform",paddingLeft:24},children:e.map((t,r)=>o.jsxs($.Fragment,{children:[o.jsx(HC,{...t}),o.jsx(UC,{})]},r))})]})}const VC=[{to:"/",label:"Dashboard",d:"M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6"},{to:"/markets",label:"Markets",d:"M13 7h8m0 0v8m0-8l-8 8-4-4-6 6"},{to:"/signals",label:"Signals",d:"M13 10V3L4 14h7v7l9-11h-7z"},{to:"/intelligence",label:"Intel Feed",d:"M19.428 15.428a2 2 0 00-1.022-.547l-2.387-.477a6 6 0 00-3.86.517l-.318.158a6 6 0 01-3.86.517L6.05 15.21a2 2 0 00-1.806.547M8 4h8l-1 1v5.172a2 2 0 00.586 1.414l5 5c1.26 1.26.367 3.414-1.415 3.414H4.828c-1.782 0-2.674-2.154-1.414-3.414l5-5A2 2 0 009 10.172V5L8 4z"},{to:"/trading",label:"Trading",d:"M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z"},{to:"/positions",label:"Positions",d:"M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"},{to:"/orders",label:"Orders",d:"M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4"},{to:"/heatmap",label:"Heatmap",d:"M4 5a1 1 0 011-1h4a1 1 0 011 1v4a1 1 0 01-1 1H5a1 1 0 01-1-1V5zm10 0a1 1 0 011-1h4a1 1 0 011 1v4a1 1 0 01-1 1h-4a1 1 0 01-1-1V5zM4 15a1 1 0 011-1h4a1 1 0 011 1v4a1 1 0 01-1 1H5a1 1 0 01-1-1v-4zm10 0a1 1 0 011-1h4a1 1 0 011 1v4a1 1 0 01-1 1h-4a1 1 0 01-1-1v-4z"},{to:"/orbit",label:"Orbit",d:"M21 12a9 9 0 01-9 9m9-9a9 9 0 00-9-9m9 9H3m9 9a9 9 0 01-9-9m9 9c1.657 0 3-4.03 3-9s-1.343-9-3-9m0 18c-1.657 0-3-4.03-3-9s1.343-9 3-9m-9 9a9 9 0 019-9"},{to:"/pulse",label:"Pulse",d:"M3.055 11H5a2 2 0 012 2v1a2 2 0 002 2 2 2 0 012 2v2.945M8 3.935V5.5A2.5 2.5 0 0010.5 8h.5a2 2 0 012 2 2 2 0 104 0 2 2 0 012-2h1.064M15 20.488V18a2 2 0 012-2h3.064M21 12a9 9 0 11-18 0 9 9 0 0118 0z"},{to:"/weather",label:"Weather",d:"M3 15a4 4 0 004 4h9a5 5 0 10-.1-9.999 5.002 5.002 0 10-9.78 2.096A4.001 4.001 0 003 15z"},{to:"/risk",label:"Portfauxlios",d:"M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4"},{to:"/settings",label:"Settings",d:"M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.066 2.573c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.573 1.066c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.066-2.573c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z M15 12a3 3 0 11-6 0 3 3 0 016 0z"}];function GC({active:e,warn:t}){const r=t?"var(--orange)":e?"var(--green)":"var(--red)";return o.jsx("span",{style:{display:"inline-block",width:6,height:6,borderRadius:"50%",background:r,flexShrink:0,boxShadow:`0 0 4px ${r}`}})}function YC(){const e=pl(),t=xd(),[r,n]=P.useState(null),[a,i]=P.useState(!1),[s,l]=P.useState(!1);if(P.useEffect(()=>{Wv().then(u=>{if(!u){t("/login");return}l(!0);const f=()=>Oe("/health").then(n).catch(()=>{});f();const d=setInterval(f,15e3);return()=>clearInterval(d)})},[]),!s)return o.jsx("div",{className:"flex items-center justify-center min-h-screen",style:{background:"var(--bg)"},children:o.jsx("div",{className:"w-8 h-8 rounded-full border-2 border-t-transparent animate-spin",style:{borderColor:"var(--cyan)",borderTopColor:"transparent"}})});const c=a?64:220;return o.jsxs("div",{className:"flex min-h-screen",style:{background:"var(--bg)"},children:[o.jsx("div",{className:"scan-overlay","aria-hidden":"true"}),o.jsxs("aside",{className:"sidebar-mesh",style:{width:c,minWidth:c,borderRight:"1px solid var(--border)",display:"flex",flexDirection:"column",transition:"width 200ms ease, min-width 200ms ease",overflow:"hidden",position:"sticky",top:0,height:"100vh"},children:[o.jsxs("div",{style:{padding:a?"16px 12px":"16px 18px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",gap:12,minHeight:64,flexShrink:0},children:[o.jsx("div",{className:"logo-animated",style:{width:34,height:34,borderRadius:8,background:"linear-gradient(135deg, var(--orange), #E5690D)",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,boxShadow:"0 2px 10px rgba(247,147,26,0.3)"},children:o.jsx("span",{style:{color:"#0E0E10",fontWeight:900,fontSize:16,fontFamily:"var(--font-heading)"},children:"K"})}),!a&&o.jsx("span",{className:"kalshi-gradient heading",style:{fontSize:13,fontWeight:700,letterSpacing:"0.06em",whiteSpace:"nowrap",filter:"drop-shadow(0 0 8px rgba(0,240,255,0.3))"},children:"KEN TRADER"})]}),o.jsx("nav",{style:{flex:1,padding:"10px 8px",overflowY:"auto",overflowX:"hidden"},children:VC.map((u,f)=>{const d=e.pathname===u.to||u.to!=="/"&&e.pathname.startsWith(u.to),h=u.to==="/settings";return o.jsxs($.Fragment,{children:[h&&o.jsx("div",{style:{margin:"8px 4px",height:1,background:"linear-gradient(90deg, transparent, var(--border), transparent)"}}),o.jsxs(Sc,{to:u.to,title:a?u.label:void 0,style:{display:"flex",alignItems:"center",gap:a?0:10,padding:a?"9px 0":"9px 10px",justifyContent:a?"center":"flex-start",borderRadius:8,marginBottom:2,textDecoration:"none",fontSize:13,fontWeight:d?600:400,color:d?"var(--cyan)":"var(--text-dim)",background:d?"rgba(0,240,255,0.08)":"transparent",borderLeft:d?"3px solid var(--cyan)":"3px solid transparent",boxShadow:d?"inset 0 0 16px rgba(0,240,255,0.06), inset 3px 0 8px rgba(0,240,255,0.1)":void 0,textShadow:d?"0 0 8px rgba(0,240,255,0.4)":void 0,transition:"all 150ms ease",whiteSpace:"nowrap",overflow:"hidden"},onMouseEnter:p=>{d||(p.currentTarget.style.color="var(--text)",p.currentTarget.style.background="rgba(0,240,255,0.04)",p.currentTarget.style.borderLeftColor="rgba(0,240,255,0.3)")},onMouseLeave:p=>{d||(p.currentTarget.style.color="var(--text-dim)",p.currentTarget.style.background="transparent",p.currentTarget.style.borderLeftColor="transparent")},children:[o.jsx("svg",{style:{width:17,height:17,flexShrink:0,opacity:d?1:.7},fill:"none",stroke:"currentColor",strokeWidth:"1.6",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:u.d})}),!a&&o.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis"},children:u.label})]})]},u.to)})}),o.jsxs("div",{style:{borderTop:"1px solid var(--border)",padding:a?"12px 8px":"12px 14px",flexShrink:0},children:[!a&&r&&o.jsx("div",{style:{marginBottom:10,display:"flex",flexDirection:"column",gap:6},children:[{label:"Env",value:(r.env||"demo").toUpperCase(),warn:r.env==="demo",active:r.env==="prod"},{label:"API",value:r.kalshi_connected?"CONNECTED":"OFF",active:r.kalshi_connected},{label:"DB",value:r.db_connected?"OK":"DOWN",active:r.db_connected},{label:"Safe Mode",value:r.safe_mode?"ON":"OFF",warn:r.safe_mode,active:!r.safe_mode}].map(u=>o.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[o.jsx("span",{style:{fontSize:10,color:"var(--text-muted)",fontFamily:"var(--font-body)"},children:u.label}),o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:5},children:[o.jsx(GC,{active:u.active,warn:u.warn}),o.jsx("span",{style:{fontSize:10,fontFamily:"var(--font-mono)",fontWeight:600,color:u.warn?"var(--orange)":u.active?"var(--green)":"var(--red)"},children:u.value})]})]},u.label))}),o.jsxs("div",{style:{display:"flex",gap:6,alignItems:"center"},children:[o.jsx("button",{onClick:()=>i(!a),title:a?"Expand sidebar":"Collapse sidebar",style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",padding:"7px 0",background:"transparent",border:"1px solid var(--border)",borderRadius:7,cursor:"pointer",color:"var(--text-muted)",transition:"all 150ms ease"},onMouseEnter:u=>{u.currentTarget.style.borderColor="var(--cyan)",u.currentTarget.style.color="var(--cyan)"},onMouseLeave:u=>{u.currentTarget.style.borderColor="var(--border)",u.currentTarget.style.color="var(--text-muted)"},children:o.jsx("svg",{style:{width:14,height:14,transition:"transform 200ms ease",transform:a?"rotate(180deg)":"none"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M11 19l-7-7 7-7m8 14l-7-7 7-7"})})}),!a&&o.jsx("button",{onClick:BC,style:{padding:"7px 10px",background:"transparent",border:"1px solid var(--border)",borderRadius:7,cursor:"pointer",color:"var(--text-muted)",fontSize:11,fontFamily:"var(--font-body)",fontWeight:500,transition:"all 150ms ease",whiteSpace:"nowrap"},onMouseEnter:u=>{u.currentTarget.style.borderColor="var(--red)",u.currentTarget.style.color="var(--red)"},onMouseLeave:u=>{u.currentTarget.style.borderColor="var(--border)",u.currentTarget.style.color="var(--text-muted)"},children:"Logout"})]})]})]}),o.jsxs("main",{style:{flex:1,overflowY:"auto",overflowX:"hidden",display:"flex",flexDirection:"column"},children:[o.jsx(KC,{}),o.jsxs("div",{className:"market-status-bar",children:[o.jsx("span",{style:{color:"var(--cyan)",fontWeight:700,letterSpacing:"0.06em"},children:"KEN TRADER"}),o.jsx("span",{style:{color:"var(--border-light)"},children:"|"}),o.jsxs("span",{children:["KALSHI"," ",o.jsx("span",{style:{color:r!=null&&r.kalshi_connected?"var(--green)":"var(--red)",fontWeight:700},children:r!=null&&r.kalshi_connected?"LIVE":"OFFLINE"})]}),o.jsx("span",{style:{color:"var(--border-light)"},children:"|"}),o.jsxs("span",{children:["DB"," ",o.jsx("span",{style:{color:r!=null&&r.db_connected?"var(--green)":"var(--red)",fontWeight:700},children:r!=null&&r.db_connected?"OK":"DOWN"})]}),o.jsx("span",{style:{color:"var(--border-light)"},children:"|"}),o.jsxs("span",{children:["ENV"," ",o.jsx("span",{style:{color:(r==null?void 0:r.env)==="prod"?"var(--green)":"var(--orange)",fontWeight:700},children:((r==null?void 0:r.env)||"DEMO").toUpperCase()})]}),(r==null?void 0:r.safe_mode)&&o.jsxs(o.Fragment,{children:[o.jsx("span",{style:{color:"var(--border-light)"},children:"|"}),o.jsx("span",{style:{color:"var(--orange)",fontWeight:700},children:"SAFE MODE ON"})]}),o.jsxs("span",{style:{marginLeft:"auto",display:"flex",alignItems:"center",gap:12},children:[o.jsxs("span",{style:{color:"var(--border-light)"},children:[new Date().toLocaleTimeString("en-US",{timeZone:"America/Los_Angeles",hour:"2-digit",minute:"2-digit",second:"2-digit"})," PT"]}),o.jsxs("button",{className:"notification-bell","aria-label":"Alerts (7 unread)",title:"7 unread alerts",style:{background:"none",border:"none",display:"flex",alignItems:"center"},children:[o.jsx("svg",{fill:"none",stroke:"currentColor",strokeWidth:"1.8",viewBox:"0 0 24 24","aria-hidden":"true",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9"})}),o.jsx("span",{className:"notification-count","aria-label":"7 alerts",children:"7"})]})]})]}),o.jsx("div",{style:{maxWidth:1600,margin:"0 auto",padding:"24px 28px",flex:1,width:"100%"},children:o.jsx(wC,{})})]})]})}const qC=[{title:"Event Contracts",desc:"Betting on weather like a person who never learned to just look outside. CFTC-regulated, at least.",icon:"M13 7h8m0 0v8m0-8l-8 8-4-4-6 6"},{title:"Weather Intelligence",desc:"We schlepp forecast data from the government so you don't have to read the almanac yourself.",icon:"M3 15a4 4 0 004 4h9a5 5 0 10-.1-9.999 5.002 5.002 0 10-9.78 2.096A4.001 4.001 0 003 15z"},{title:"Automated Execution",desc:"The machine places your bets so your hands stay clean. Safe mode included, because I worry.",icon:"M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"}],XC=["Hook up to Ken (demo first, like a sensible person)","Snoop around the weather contracts","Schlep in the NWS settlement data","Let the computer do the math you were too lazy to learn","Set some limits so you don't lose your shirt","Place the bets (on paper first, God willing)"];function QC({next:e}){return o.jsxs("div",{className:"space-y-8",children:[o.jsxs("div",{className:"text-center",children:[o.jsx("h1",{className:"text-4xl font-bold kalshi-gradient mb-3",children:"Oy, Look Who Finally Showed Up"}),o.jsx("p",{className:"text-gray-400 text-lg",children:"So you want to bet on the weather? Your mother would be so proud."})]}),o.jsx("div",{className:"grid grid-cols-3 gap-4",children:qC.map(t=>o.jsxs("div",{className:"card text-center",children:[o.jsx("div",{className:"w-10 h-10 rounded-lg bg-amber-500/10 flex items-center justify-center mx-auto mb-3",children:o.jsx("svg",{className:"w-5 h-5 text-amber-400",fill:"none",stroke:"currentColor",strokeWidth:"1.5",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:t.icon})})}),o.jsx("h3",{className:"font-semibold text-sm mb-1",children:t.title}),o.jsx("p",{className:"text-xs text-gray-500 leading-relaxed",children:t.desc})]},t.title))}),o.jsxs("div",{className:"card",children:[o.jsx("h3",{className:"font-semibold text-sm mb-3",children:"Listen, this is how it works"}),o.jsx("div",{className:"grid grid-cols-2 gap-2",children:XC.map((t,r)=>o.jsxs("div",{className:"flex items-center gap-3 py-1.5",children:[o.jsx("span",{className:"w-6 h-6 rounded-full bg-amber-500/15 text-amber-400 flex items-center justify-center text-xs font-bold flex-shrink-0",children:r+1}),o.jsx("span",{className:"text-sm text-gray-300",children:t})]},r))})]}),o.jsx("div",{className:"card bg-green-500/5 border-green-500/20",children:o.jsxs("div",{className:"flex items-start gap-3",children:[o.jsx("svg",{className:"w-5 h-5 text-green-400 mt-0.5 flex-shrink-0",fill:"none",stroke:"currentColor",strokeWidth:"1.5",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"})}),o.jsxs("div",{children:[o.jsx("p",{className:"text-sm font-medium text-green-400",children:"At least it's legal, thank God"}),o.jsx("p",{className:"text-xs text-gray-400 mt-1",children:"Ken is a real CFTC-regulated exchange, not some offshore mishegoss. You'll need an account with API access. Go make one already, I'll wait."})]})]})}),o.jsx("div",{className:"flex justify-center",children:o.jsx("button",{onClick:e,className:"btn btn-p px-8 py-3 text-base font-bold rounded-xl",children:"Nu, Let's Go Already"})})]})}function JC({data:e,update:t,next:r,back:n}){var b,v,m;const[a,i]=P.useState(((b=e.keys)==null?void 0:b.api_key)||""),[s,l]=P.useState(((v=e.keys)==null?void 0:v.private_key)||""),[c,u]=P.useState(((m=e.keys)==null?void 0:m.env)||"demo"),[f,d]=P.useState(!1),[h,p]=P.useState(null);async function g(){d(!0),p(null);try{const x=await me("/kalshi",{action:"save_keys",api_key:a,private_key:s,env:c});x.success?(t({keys:{api_key:a,private_key:"***",env:c}}),r()):p(x.error||"Failed to save")}catch{p("Connection error")}d(!1)}function y(){t({keys:null,skippedConnect:!0}),r()}return o.jsxs("div",{className:"space-y-6",children:[o.jsxs("div",{className:"text-center",children:[o.jsx("h2",{className:"text-2xl font-bold mb-2",children:"Give Me the Keys"}),o.jsx("p",{className:"text-gray-400 text-sm",children:"Your API credentials, darling. I don't have all day."})]}),o.jsxs("div",{className:"card space-y-4",children:[o.jsxs("div",{children:[o.jsx("label",{className:"block text-xs text-gray-400 mb-1.5 font-medium",children:"Which playground are we using?"}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx("button",{onClick:()=>u("demo"),className:`flex-1 py-2 rounded-lg text-sm font-medium transition ${c==="demo"?"bg-yellow-500/15 text-yellow-400 border border-yellow-500/30":"bg-gray-800/50 text-gray-500 border border-gray-700"}`,children:"Demo (Smart)"}),o.jsx("button",{onClick:()=>u("prod"),className:`flex-1 py-2 rounded-lg text-sm font-medium transition ${c==="prod"?"bg-green-500/15 text-green-400 border border-green-500/30":"bg-gray-800/50 text-gray-500 border border-gray-700"}`,children:"Production (Brave)"})]})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-xs text-gray-400 mb-1.5 font-medium",children:"API Key ID (the one they gave you)"}),o.jsx("input",{type:"text",value:a,onChange:x=>i(x.target.value),placeholder:"Paste it here, bubeleh",className:"w-full px-3 py-2 bg-gray-800/50 border border-gray-700 rounded-lg text-sm focus:border-amber-500 focus:outline-none font-mono"})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-xs text-gray-400 mb-1.5 font-medium",children:"Private Key (the whole megillah, PEM format)"}),o.jsx("textarea",{value:s,onChange:x=>l(x.target.value),placeholder:`-----BEGIN RSA PRIVATE KEY-----
-...
------END RSA PRIVATE KEY-----`,rows:6,className:"w-full px-3 py-2 bg-gray-800/50 border border-gray-700 rounded-lg text-sm focus:border-amber-500 focus:outline-none font-mono text-xs leading-relaxed"}),o.jsx("p",{className:"text-[10px] text-gray-600 mt-1",children:"Don't worry, I keep it locked up tighter than your grandmother's jewelry box"})]}),h&&o.jsx("p",{className:"text-red-400 text-xs",children:h})]}),o.jsxs("div",{className:"card bg-gray-800/30",children:[o.jsx("h3",{className:"text-sm font-medium mb-2",children:"What, you don't have keys yet? Oy vey."}),o.jsxs("ol",{className:"text-xs text-gray-400 space-y-1.5 list-decimal list-inside",children:[o.jsxs("li",{children:["Go log into ",o.jsx("span",{className:"text-amber-400 font-mono",children:"ken.com"})," like a mensch"]}),o.jsx("li",{children:"Find Settings → API Keys (it's not that hard, look around)"}),o.jsxs("li",{children:['Click "Create API Key" and ',o.jsx("strong",{children:"download that private key file immediately"})]}),o.jsx("li",{children:"Copy the Key ID and paste the PEM contents up there. Simple."})]}),o.jsx("p",{className:"text-[10px] text-red-400 mt-2",children:"Listen to me — that private key file? You can only download it ONCE. Lose it and you start over. Don't say I didn't warn you."})]}),o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("button",{onClick:n,className:"text-sm text-gray-500 hover:text-gray-300",children:"Back"}),o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("button",{onClick:y,className:"text-sm text-gray-500 hover:text-gray-300",children:"Skip (play pretend)"}),o.jsx("button",{onClick:g,disabled:f||!a||!s,className:"btn btn-p",children:f?"Saving, patience...":"Save & Continue"})]})]})]})}function ZC({data:e,update:t,next:r,back:n}){const[a,i]=P.useState(null),[s,l]=P.useState(null),[c,u]=P.useState(!0),[f,d]=P.useState(!1);P.useEffect(()=>{h()},[]);async function h(){u(!0);try{const b=await me("/kalshi",{action:"test_connection"});i(b),b.success&&e.keys&&!e.skippedConnect&&p()}catch{i({error:!0})}u(!1)}async function p(){d(!0);try{const b=await me("/kalshi",{action:"get_balance"});l(b),b.success&&t({connectionOk:!0})}catch{l({error:!0})}d(!1)}const g=e.skippedConnect,y=({title:b,loading:v,result:m,skippedMsg:x})=>o.jsxs("div",{className:"card",children:[o.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[x?o.jsx("div",{className:"w-5 h-5 rounded-full bg-yellow-500 flex items-center justify-center",children:o.jsx("span",{className:"text-white text-xs font-bold",children:"—"})}):v?o.jsx("div",{className:"animate-spin w-5 h-5 border-2 border-amber-500 border-t-transparent rounded-full"}):m!=null&&m.success?o.jsx("div",{className:"w-5 h-5 rounded-full bg-green-500 flex items-center justify-center",children:o.jsx("svg",{className:"w-3 h-3 text-white",fill:"none",stroke:"currentColor",strokeWidth:"3",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5 13l4 4L19 7"})})}):m!=null&&m.error?o.jsx("div",{className:"w-5 h-5 rounded-full bg-red-500 flex items-center justify-center",children:o.jsx("svg",{className:"w-3 h-3 text-white",fill:"none",stroke:"currentColor",strokeWidth:"3",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})})}):o.jsx("div",{className:"w-5 h-5 rounded-full bg-gray-600"}),o.jsx("h3",{className:"font-semibold text-sm",children:b})]}),x?o.jsx("p",{className:"text-xs text-yellow-400",children:x}):m!=null&&m.success?o.jsxs("div",{className:"space-y-1 text-xs text-gray-400",children:[m.exchange_status&&o.jsxs("p",{children:["Exchange: ",o.jsx("span",{className:"text-green-400 font-mono",children:m.exchange_status})]}),m.balance!==void 0&&o.jsxs("p",{children:["Balance: ",o.jsxs("span",{className:"text-green-400 font-mono",children:["$",(m.balance/100).toFixed(2)]})]}),m.env&&o.jsxs("p",{children:["Env: ",o.jsx("span",{className:"text-amber-400 font-mono",children:m.env.toUpperCase()})]})]}):m!=null&&m.error?o.jsx("p",{className:"text-xs text-red-400",children:typeof m.error=="string"?m.error:"Connection failed"}):null]});return o.jsxs("div",{className:"space-y-6",children:[o.jsxs("div",{className:"text-center",children:[o.jsx("h2",{className:"text-2xl font-bold mb-2",children:"Let's See If This Thing Works"}),o.jsx("p",{className:"text-gray-400 text-sm",children:"I'm checking your wiring. Hold your horses."})]}),o.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[o.jsx(y,{title:"Is Ken Even Open?",loading:c,result:a}),o.jsx(y,{title:"Do They Know Who You Are?",loading:f,result:s,skippedMsg:g?"You skipped this — playing pretend, remember?":e.keys?null:"No keys, no entry. What did you expect?"})]}),!c&&!f&&o.jsx("div",{className:"flex justify-center",children:o.jsx("button",{onClick:h,className:"text-xs text-gray-500 hover:text-gray-300",children:"Try again, maybe this time it'll listen"})}),o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("button",{onClick:n,className:"text-sm text-gray-500 hover:text-gray-300",children:"Back"}),o.jsx("button",{onClick:r,className:"btn btn-p",children:"Continue"})]})]})}function eE({data:e,update:t,next:r,back:n}){var h,p;const[a,i]=P.useState(!0),[s,l]=P.useState(null),[c,u]=P.useState(null);P.useEffect(()=>{f()},[]);async function f(){var g;i(!0),u(null);try{const y=await me("/kalshi",{action:"get_events",params:{status:"open",limit:50}});l(y);const b=((g=y.events)==null?void 0:g.length)||0;t({marketsLoaded:b})}catch{u("Failed to load markets")}i(!1)}const d=((s==null?void 0:s.events)||[]).filter(g=>(g.category||"").toLowerCase().includes("climate")||(g.category||"").toLowerCase().includes("weather")||(g.title||"").toLowerCase().includes("temperature")||(g.title||"").toLowerCase().includes("rain")||(g.title||"").toLowerCase().includes("snow")||(g.title||"").toLowerCase().includes("precipitation"));return o.jsxs("div",{className:"space-y-6",children:[o.jsxs("div",{className:"text-center",children:[o.jsx("h2",{className:"text-2xl font-bold mb-2",children:"Let's See What They're Selling"}),o.jsx("p",{className:"text-gray-400 text-sm",children:"I'm snooping through the markets. You're welcome."})]}),o.jsx("div",{className:"card",children:a?o.jsxs("div",{className:"flex flex-col items-center justify-center py-12 gap-4",children:[o.jsx("div",{className:"animate-spin w-10 h-10 border-3 border-amber-500 border-t-transparent rounded-full"}),o.jsx("p",{className:"text-sm text-gray-400",children:"Schlepping markets from Ken... patience is a virtue"})]}):c?o.jsxs("div",{className:"text-center py-8",children:[o.jsx("p",{className:"text-red-400 text-sm mb-3",children:c}),o.jsx("button",{onClick:f,className:"btn btn-s text-sm",children:"Retry"})]}):o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[o.jsxs("div",{className:"text-center",children:[o.jsx("p",{className:"stat-v text-amber-400",children:((h=s==null?void 0:s.events)==null?void 0:h.length)||0}),o.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Things to Bet On"})]}),o.jsxs("div",{className:"text-center",children:[o.jsx("p",{className:"stat-v text-blue-400",children:d.length}),o.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Weather Bets (Our Thing)"})]}),o.jsxs("div",{className:"text-center",children:[o.jsx("p",{className:"stat-v text-green-400",children:((p=s==null?void 0:s.markets)==null?void 0:p.length)||"—"}),o.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Individual Contracts"})]})]}),d.length>0&&o.jsxs("div",{className:"border-t border-gray-800 pt-3",children:[o.jsx("p",{className:"text-xs text-gray-500 mb-2 uppercase font-medium",children:"Weather Bets I Found For You"}),o.jsx("div",{className:"space-y-1.5 max-h-48 overflow-y-auto",children:d.slice(0,12).map((g,y)=>o.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[o.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-amber-500 flex-shrink-0"}),o.jsx("span",{className:"text-gray-300 truncate",children:g.title}),o.jsx("span",{className:"text-gray-600 ml-auto font-mono text-[10px]",children:g.event_ticker})]},y))})]}),d.length===0&&o.jsx("p",{className:"text-center text-gray-500 text-sm py-4",children:"No weather bets right now. What, the weather took a day off? Other markets are there at least."})]})}),o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("button",{onClick:n,className:"text-sm text-gray-500 hover:text-gray-300",children:"Back"}),o.jsx("button",{onClick:r,disabled:a,className:"btn btn-p",children:a?"Loading...":"Continue"})]})]})}function tE({data:e,update:t,next:r,back:n}){var d;const[a,i]=P.useState(!0),[s,l]=P.useState(null),[c,u]=P.useState(null);P.useEffect(()=>{f()},[]);async function f(){i(!0),u(null);try{const h=await me("/weather",{action:"fetch_all"});l(h),t({weatherFetched:!0})}catch{u("Failed to fetch weather data")}i(!1)}return o.jsxs("div",{className:"space-y-6",children:[o.jsxs("div",{className:"text-center",children:[o.jsx("h2",{className:"text-2xl font-bold mb-2",children:"Checking the Weather, Darling"}),o.jsx("p",{className:"text-gray-400 text-sm",children:"I'm schlepping in the government weather reports. In my day we just looked outside."})]}),o.jsx("div",{className:"card",children:a?o.jsxs("div",{className:"flex flex-col items-center justify-center py-12 gap-4",children:[o.jsx("div",{className:"animate-spin w-10 h-10 border-3 border-blue-500 border-t-transparent rounded-full"}),o.jsx("p",{className:"text-sm text-gray-400",children:"Fetching from the National Weather Service... they take their sweet time"})]}):c?o.jsxs("div",{className:"text-center py-8",children:[o.jsx("p",{className:"text-red-400 text-sm mb-3",children:c}),o.jsx("button",{onClick:f,className:"btn btn-s text-sm",children:"Retry"})]}):o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"flex items-center justify-center gap-3 py-4",children:[o.jsx("div",{className:"w-12 h-12 rounded-full bg-green-500/10 flex items-center justify-center",children:o.jsx("svg",{className:"w-6 h-6 text-green-400",fill:"none",stroke:"currentColor",strokeWidth:"2",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5 13l4 4L19 7"})})}),o.jsxs("div",{children:[o.jsx("p",{className:"font-semibold text-green-400",children:"Got the Weather, Finally"}),o.jsx("p",{className:"text-xs text-gray-400",children:"All the fancy government data, right here in your tuchas seat"})]})]}),o.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[o.jsxs("div",{className:"text-center p-3 bg-gray-800/30 rounded-lg",children:[o.jsx("p",{className:"stat-v text-blue-400",children:(s==null?void 0:s.stations)||"—"}),o.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Stations"})]}),o.jsxs("div",{className:"text-center p-3 bg-gray-800/30 rounded-lg",children:[o.jsx("p",{className:"stat-v text-amber-400",children:(s==null?void 0:s.data_points)||"—"}),o.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Data Points"})]}),o.jsxs("div",{className:"text-center p-3 bg-gray-800/30 rounded-lg",children:[o.jsx("p",{className:"stat-v text-green-400",children:((d=s==null?void 0:s.metrics)==null?void 0:d.length)||"—"}),o.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Metrics"})]})]})]})}),o.jsxs("div",{className:"card bg-gray-800/30",children:[o.jsx("p",{className:"text-xs text-gray-500 mb-1 font-medium",children:"How They Settle (Pay Attention)"}),o.jsxs("p",{className:"text-xs text-gray-400",children:["Ken settles on the ",o.jsx("span",{className:"text-amber-400",children:"final NWS Daily Climate Report"}),". A trace of rain? That's zero. Missing data? Also zero. And listen — the first report is the last word. They don't go back and change it, even if the weatherman was wrong. Such is life."]})]}),o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("button",{onClick:n,className:"text-sm text-gray-500 hover:text-gray-300",children:"Back"}),o.jsx("button",{onClick:r,disabled:a,className:"btn btn-p",children:a?"Fetching...":"Continue"})]})]})}function rE({data:e,update:t,next:r,back:n}){const[a,i]=P.useState(!0),[s,l]=P.useState(null),[c,u]=P.useState(null);P.useEffect(()=>{f()},[]);async function f(){i(!0),u(null);try{const p=await me("/kalshi",{action:"run_predictions"});l(p),t({predictionsRun:!0})}catch{u("Failed to generate predictions")}i(!1)}const d=(s==null?void 0:s.predictions)||[],h=d.filter(p=>(p.edge_bps||0)>0);return o.jsxs("div",{className:"space-y-6",children:[o.jsxs("div",{className:"text-center",children:[o.jsx("h2",{className:"text-2xl font-bold mb-2",children:"The Machine Is Thinking"}),o.jsx("p",{className:"text-gray-400 text-sm",children:"Running the numbers so you don't have to use that head of yours"})]}),o.jsx("div",{className:"card",children:a?o.jsxs("div",{className:"flex flex-col items-center justify-center py-12 gap-4",children:[o.jsx("div",{className:"animate-spin w-10 h-10 border-3 border-green-500 border-t-transparent rounded-full"}),o.jsx("p",{className:"text-sm text-gray-400",children:"Crunching numbers... in my day we did this with an abacus"})]}):c?o.jsxs("div",{className:"text-center py-8",children:[o.jsx("p",{className:"text-red-400 text-sm mb-3",children:c}),o.jsx("button",{onClick:f,className:"btn btn-s text-sm",children:"Retry"})]}):o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[o.jsxs("div",{className:"text-center",children:[o.jsx("p",{className:"stat-v text-amber-400",children:d.length}),o.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Opinions"})]}),o.jsxs("div",{className:"text-center",children:[o.jsx("p",{className:"stat-v text-green-400",children:h.length}),o.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Worth a Look"})]}),o.jsxs("div",{className:"text-center",children:[o.jsxs("p",{className:"stat-v text-blue-400",children:[(s==null?void 0:s.avg_edge_bps)||0,"bps"]}),o.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Your Edge (God Willing)"})]})]}),d.length>0&&o.jsx("div",{className:"border-t border-gray-800 pt-3",children:o.jsxs("table",{children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"Contract"}),o.jsx("th",{children:"Side"}),o.jsx("th",{children:"Price"}),o.jsx("th",{children:"Edge"}),o.jsx("th",{children:"Signal"})]})}),o.jsx("tbody",{children:d.slice(0,6).map((p,g)=>o.jsxs("tr",{children:[o.jsx("td",{className:"max-w-[180px]",children:o.jsx("span",{className:"truncate block text-xs",children:p.ticker||p.market})}),o.jsx("td",{children:o.jsx("span",{className:`badge ${p.side==="yes"?"bg-green":"bg-red"}`,children:(p.side||"yes").toUpperCase()})}),o.jsxs("td",{className:"font-mono text-sm",children:[p.price_cents||"—","c"]}),o.jsxs("td",{className:`font-mono text-sm ${(p.edge_bps||0)>0?"text-green-400":"text-gray-500"}`,children:[p.edge_bps||0,"bps"]}),o.jsx("td",{children:o.jsx("span",{className:`badge ${(p.edge_bps||0)>0?"bg-green":"bg-yellow"}`,children:(p.edge_bps||0)>0?"BUY":"HOLD"})})]},g))})]})})]})}),o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("button",{onClick:n,className:"text-sm text-gray-500 hover:text-gray-300",children:"Back"}),o.jsx("button",{onClick:r,disabled:a,className:"btn btn-p",children:a?"Processing...":"Continue"})]})]})}const j0=[{name:"Conservative",maxContracts:5,maxDollars:25,dailyLoss:10,color:"blue",desc:"Like your bubbe taught you — small bets, tight grip on the purse strings."},{name:"Moderate",maxContracts:20,maxDollars:100,dailyLoss:50,color:"amber",desc:"Not too much, not too little. Like Goldilocks, but with money.",recommended:!0},{name:"Aggressive",maxContracts:50,maxDollars:500,dailyLoss:200,color:"red",desc:"What are you, a big shot? Don't come crying to me when it goes sideways."}];function nE({data:e,update:t,next:r,back:n}){const[a,i]=P.useState(e.riskProfile||"Moderate"),[s,l]=P.useState(!1);async function c(){l(!0);const u=j0.find(f=>f.name===a);try{await me("/risk",{action:"update_config",max_contracts_per_market:u.maxContracts,max_dollars_at_risk:u.maxDollars,daily_loss_cap:u.dailyLoss,risk_profile:u.name}),t({riskProfile:a}),r()}catch{}l(!1)}return o.jsxs("div",{className:"space-y-6",children:[o.jsxs("div",{className:"text-center",children:[o.jsx("h2",{className:"text-2xl font-bold mb-2",children:"How Much Are You Willing to Lose?"}),o.jsx("p",{className:"text-gray-400 text-sm",children:'Pick one. And no, "all of it" is not an option.'})]}),o.jsx("div",{className:"grid grid-cols-3 gap-4",children:j0.map(u=>{const d={blue:{ring:"#3b82f6",text:"text-blue-400"},amber:{ring:"#f59e0b",text:"text-amber-400"},red:{ring:"#ef4444",text:"text-red-400"}}[u.color];return o.jsxs("button",{onClick:()=>i(u.name),className:"card text-left transition-all relative",style:a===u.name?{boxShadow:`0 0 0 2px ${d.ring}`}:{},children:[u.recommended&&o.jsx("span",{className:"absolute -top-2 right-3 text-[9px] font-bold uppercase px-2 py-0.5 rounded-full bg-amber-500 text-black",children:"Recommended"}),o.jsx("h3",{className:`font-bold text-lg mb-1 ${d.text}`,children:u.name}),o.jsx("p",{className:"text-xs text-gray-500 mb-3",children:u.desc}),o.jsxs("div",{className:"space-y-1.5 text-xs",children:[o.jsxs("div",{className:"flex justify-between",children:[o.jsx("span",{className:"text-gray-500",children:"Max Contracts"}),o.jsx("span",{className:"font-mono text-gray-300",children:u.maxContracts})]}),o.jsxs("div",{className:"flex justify-between",children:[o.jsx("span",{className:"text-gray-500",children:"Max $ at Risk"}),o.jsxs("span",{className:"font-mono text-gray-300",children:["$",u.maxDollars]})]}),o.jsxs("div",{className:"flex justify-between",children:[o.jsx("span",{className:"text-gray-500",children:"Daily Loss Cap"}),o.jsxs("span",{className:"font-mono text-gray-300",children:["$",u.dailyLoss]})]})]})]},u.name)})}),o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("button",{onClick:n,className:"text-sm text-gray-500 hover:text-gray-300",children:"Back"}),o.jsx("button",{onClick:c,disabled:s,className:"btn btn-p",children:s?"Saving...":"Save & Continue"})]})]})}const Ff=[{key:"keys",label:"Gave me the API keys (good)",check:e=>!!e.keys},{key:"conn",label:"Connection actually works (miracle)",check:e=>!!e.connectionOk},{key:"markets",label:"Found some markets to bet on",check:e=>e.marketsLoaded>0},{key:"weather",label:"Got the weather data (finally)",check:e=>!!e.weatherFetched},{key:"preds",label:"The machine made its predictions",check:e=>!!e.predictionsRun},{key:"risk",label:"Set some limits (smart)",check:e=>!!e.riskProfile}];function aE({data:e,complete:t,back:r}){const[n,a]=P.useState(!0),[i,s]=P.useState(!1),l=Ff.filter(f=>f.check(e)).length,c=e.skippedConnect;async function u(){s(!0),await t()}return o.jsxs("div",{className:"space-y-6",children:[o.jsxs("div",{className:"text-center",children:[o.jsx("h2",{className:"text-2xl font-bold mb-2",children:"Alright, Mazel Tov"}),o.jsx("p",{className:"text-gray-400 text-sm",children:"Let's see if you actually did everything right. I have my doubts."})]}),o.jsxs("div",{className:"card",children:[o.jsx("h3",{className:"font-semibold text-sm mb-3",children:"Your Report Card"}),o.jsx("div",{className:"space-y-2",children:Ff.map(f=>{const d=f.check(e),h=f.key==="keys"&&c;return o.jsxs("div",{className:"flex items-center gap-3",children:[d?o.jsx("div",{className:"w-5 h-5 rounded-full bg-green-500 flex items-center justify-center flex-shrink-0",children:o.jsx("svg",{className:"w-3 h-3 text-white",fill:"none",stroke:"currentColor",strokeWidth:"3",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5 13l4 4L19 7"})})}):h?o.jsx("div",{className:"w-5 h-5 rounded-full bg-yellow-500 flex items-center justify-center flex-shrink-0",children:o.jsx("span",{className:"text-white text-[10px] font-bold",children:"—"})}):o.jsx("div",{className:"w-5 h-5 rounded-full bg-gray-700 flex-shrink-0"}),o.jsxs("span",{className:`text-sm ${d?"text-gray-200":h?"text-yellow-400":"text-gray-500"}`,children:[f.label,h?" (skipped)":""]})]},f.key)})}),o.jsxs("p",{className:"text-xs text-gray-500 mt-3 pt-3 border-t border-gray-800",children:[l,"/",Ff.length," steps completed"]})]}),o.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[o.jsxs("div",{className:"card text-center",children:[o.jsx("p",{className:"stat-v text-amber-400",children:e.marketsLoaded||0}),o.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Markets"})]}),o.jsxs("div",{className:"card text-center",children:[o.jsx("p",{className:"stat-v text-blue-400",children:e.riskProfile||"—"}),o.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Risk Profile"})]}),o.jsxs("div",{className:"card text-center",children:[o.jsx("p",{className:"stat-v text-green-400",children:e.keys?(e.keys.env||"demo").toUpperCase():"PAPER"}),o.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Mode"})]})]}),o.jsxs("div",{className:"card",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{children:[o.jsx("h3",{className:"font-semibold text-sm",children:"Safe Mode (I Recommend It)"}),o.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:n?"Paper trading — playing pretend, like a sensible person":"Live orders! With real money! Oy gevalt."})]}),o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("span",{className:`text-xs font-medium ${n?"text-yellow-400":"text-gray-500"}`,children:"Safe"}),o.jsx("button",{onClick:()=>a(!n),disabled:!e.keys,className:`w-11 h-6 rounded-full transition-colors relative ${n?"bg-yellow-500/30":"bg-green-500/30"} ${e.keys?"":"opacity-50 cursor-not-allowed"}`,children:o.jsx("div",{className:`w-4 h-4 rounded-full absolute top-1 transition-all ${n?"left-1 bg-yellow-400":"left-6 bg-green-400"}`})}),o.jsx("span",{className:`text-xs font-medium ${n?"text-gray-500":"text-green-400"}`,children:"Live"})]})]}),!n&&o.jsx("div",{className:"mt-3 p-2 bg-red-500/10 border border-red-500/20 rounded-lg",children:o.jsx("p",{className:"text-xs text-red-400",children:"Live mode means real money, bubeleh. Real. Money. Don't say I didn't warn you. Make sure you've got funds and your limits are set, or so help me."})})]}),o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("button",{onClick:r,className:"text-sm text-gray-500 hover:text-gray-300",children:"Back"}),o.jsx("button",{onClick:u,disabled:i,className:"btn btn-p text-lg px-8 py-3 rounded-xl font-bold",children:i?"Starting up, hold your horses...":"Go Make Some Gelt Already"})]})]})}const Hl=[{label:"Shalom",icon:"1"},{label:"Keys",icon:"2"},{label:"Test It",icon:"3"},{label:"Snoop",icon:"4"},{label:"Weather",icon:"5"},{label:"Predict",icon:"6"},{label:"Limits",icon:"7"},{label:"Mazel Tov",icon:"8"}],iE=[QC,JC,ZC,eE,tE,rE,nE,aE];function oE(){const e=xd(),[t,r]=P.useState(!1),[n,a]=P.useState(0),[i,s]=P.useState({keys:null,connectionOk:!1,marketsLoaded:0,weatherFetched:!1,predictionsRun:!1,riskProfile:null});P.useEffect(()=>{Wv().then(p=>{if(!p){e("/login");return}r(!0),Oe("/setup").then(g=>{if(g.setup_complete){e("/");return}g.setup_progress&&(a(g.setup_progress.step||0),s(y=>({...y,...g.setup_progress.data})))}).catch(()=>{})})},[]),P.useEffect(()=>{t&&n>0&&me("/setup",{action:"save_progress",progress:{step:n,data:i}}).catch(()=>{})},[n]);function l(){n<Hl.length-1&&a(p=>p+1)}function c(){n>0&&a(p=>p-1)}function u(p){p<=n&&a(p)}function f(p){s(g=>({...g,...p}))}async function d(){await me("/setup",{action:"complete",progress:{step:Hl.length-1,data:i}}),e("/")}if(!t)return o.jsx("div",{className:"flex items-center justify-center min-h-screen",children:o.jsx("div",{className:"animate-spin w-8 h-8 border-2 border-amber-500 border-t-transparent rounded-full"})});const h=iE[n];return o.jsxs("div",{className:"min-h-screen flex flex-col",style:{background:"var(--bg)"},children:[o.jsxs("div",{className:"flex items-center gap-3 px-6 py-4 border-b border-gray-800",children:[o.jsx("div",{className:"w-8 h-8 rounded-lg flex items-center justify-center flex-shrink-0",style:{background:"linear-gradient(135deg,#f59e0b,#f97316)"},children:o.jsx("span",{className:"text-black font-bold text-sm",children:"K"})}),o.jsx("span",{className:"font-bold text-sm kalshi-gradient",children:"KEN SETUP — SIT, WE'LL TALK"})]}),o.jsx("div",{className:"px-6 py-5",children:o.jsx("div",{className:"max-w-3xl mx-auto flex items-center",children:Hl.map((p,g)=>o.jsxs($.Fragment,{children:[o.jsxs("button",{onClick:()=>u(g),disabled:g>n,className:"flex flex-col items-center gap-1.5 group",style:{minWidth:56},children:[o.jsx("div",{className:`w-8 h-8 rounded-full flex items-center justify-center text-xs font-bold transition-all ${g<n?"bg-green-500 text-white":g===n?"bg-amber-500 text-black":"bg-gray-800 text-gray-500"} ${g<=n?"cursor-pointer":"cursor-default"}`,style:g===n?{animation:"pg 2s infinite"}:{},children:g<n?o.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",strokeWidth:"2.5",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5 13l4 4L19 7"})}):p.icon}),o.jsx("span",{className:`text-[10px] font-medium ${g<n?"text-green-400":g===n?"text-amber-400":"text-gray-600"}`,children:p.label})]}),g<Hl.length-1&&o.jsx("div",{className:`h-0.5 flex-1 transition-colors ${g<n?"bg-green-500":"bg-gray-800"}`})]},g))})}),o.jsx("div",{className:"flex-1 flex items-start justify-center px-6 pb-10",children:o.jsx("div",{className:"w-full max-w-2xl",children:o.jsx(h,{data:i,update:f,next:l,back:c,complete:d,step:n})},n)})]})}function sS(e){var t,r,n="";if(typeof e=="string"||typeof e=="number")n+=e;else if(typeof e=="object")if(Array.isArray(e)){var a=e.length;for(t=0;t<a;t++)e[t]&&(r=sS(e[t]))&&(n&&(n+=" "),n+=r)}else for(r in e)e[r]&&(n&&(n+=" "),n+=r);return n}function ee(){for(var e,t,r=0,n="",a=arguments.length;r<a;r++)(e=arguments[r])&&(t=sS(e))&&(n&&(n+=" "),n+=t);return n}var sE=Array.isArray,$t=sE,lE=typeof Ol=="object"&&Ol&&Ol.Object===Object&&Ol,lS=lE,cE=lS,uE=typeof self=="object"&&self&&self.Object===Object&&self,dE=cE||uE||Function("return this")(),Mr=dE,fE=Mr,hE=fE.Symbol,ml=hE,w0=ml,cS=Object.prototype,pE=cS.hasOwnProperty,mE=cS.toString,No=w0?w0.toStringTag:void 0;function vE(e){var t=pE.call(e,No),r=e[No];try{e[No]=void 0;var n=!0}catch{}var a=mE.call(e);return n&&(t?e[No]=r:delete e[No]),a}var yE=vE,gE=Object.prototype,xE=gE.toString;function bE(e){return xE.call(e)}var jE=bE,S0=ml,wE=yE,SE=jE,_E="[object Null]",kE="[object Undefined]",_0=S0?S0.toStringTag:void 0;function OE(e){return e==null?e===void 0?kE:_E:_0&&_0 in Object(e)?wE(e):SE(e)}var on=OE;function NE(e){return e!=null&&typeof e=="object"}var sn=NE,PE=on,AE=sn,CE="[object Symbol]";function EE(e){return typeof e=="symbol"||AE(e)&&PE(e)==CE}var ao=EE,$E=$t,TE=ao,ME=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,IE=/^\w*$/;function LE(e,t){if($E(e))return!1;var r=typeof e;return r=="number"||r=="symbol"||r=="boolean"||e==null||TE(e)?!0:IE.test(e)||!ME.test(e)||t!=null&&e in Object(t)}var Uv=LE;function DE(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}var zn=DE;const io=de(zn);var RE=on,BE=zn,FE="[object AsyncFunction]",zE="[object Function]",WE="[object GeneratorFunction]",UE="[object Proxy]";function HE(e){if(!BE(e))return!1;var t=RE(e);return t==zE||t==WE||t==FE||t==UE}var Hv=HE;const Q=de(Hv);var KE=Mr,VE=KE["__core-js_shared__"],GE=VE,zf=GE,k0=function(){var e=/[^.]+$/.exec(zf&&zf.keys&&zf.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}();function YE(e){return!!k0&&k0 in e}var qE=YE,XE=Function.prototype,QE=XE.toString;function JE(e){if(e!=null){try{return QE.call(e)}catch{}try{return e+""}catch{}}return""}var uS=JE,ZE=Hv,e$=qE,t$=zn,r$=uS,n$=/[\\^$.*+?()[\]{}|]/g,a$=/^\[object .+?Constructor\]$/,i$=Function.prototype,o$=Object.prototype,s$=i$.toString,l$=o$.hasOwnProperty,c$=RegExp("^"+s$.call(l$).replace(n$,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function u$(e){if(!t$(e)||e$(e))return!1;var t=ZE(e)?c$:a$;return t.test(r$(e))}var d$=u$;function f$(e,t){return e==null?void 0:e[t]}var h$=f$,p$=d$,m$=h$;function v$(e,t){var r=m$(e,t);return p$(r)?r:void 0}var Ea=v$,y$=Ea,g$=y$(Object,"create"),bd=g$,O0=bd;function x$(){this.__data__=O0?O0(null):{},this.size=0}var b$=x$;function j$(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}var w$=j$,S$=bd,_$="__lodash_hash_undefined__",k$=Object.prototype,O$=k$.hasOwnProperty;function N$(e){var t=this.__data__;if(S$){var r=t[e];return r===_$?void 0:r}return O$.call(t,e)?t[e]:void 0}var P$=N$,A$=bd,C$=Object.prototype,E$=C$.hasOwnProperty;function $$(e){var t=this.__data__;return A$?t[e]!==void 0:E$.call(t,e)}var T$=$$,M$=bd,I$="__lodash_hash_undefined__";function L$(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=M$&&t===void 0?I$:t,this}var D$=L$,R$=b$,B$=w$,F$=P$,z$=T$,W$=D$;function oo(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}oo.prototype.clear=R$;oo.prototype.delete=B$;oo.prototype.get=F$;oo.prototype.has=z$;oo.prototype.set=W$;var U$=oo;function H$(){this.__data__=[],this.size=0}var K$=H$;function V$(e,t){return e===t||e!==e&&t!==t}var Kv=V$,G$=Kv;function Y$(e,t){for(var r=e.length;r--;)if(G$(e[r][0],t))return r;return-1}var jd=Y$,q$=jd,X$=Array.prototype,Q$=X$.splice;function J$(e){var t=this.__data__,r=q$(t,e);if(r<0)return!1;var n=t.length-1;return r==n?t.pop():Q$.call(t,r,1),--this.size,!0}var Z$=J$,eT=jd;function tT(e){var t=this.__data__,r=eT(t,e);return r<0?void 0:t[r][1]}var rT=tT,nT=jd;function aT(e){return nT(this.__data__,e)>-1}var iT=aT,oT=jd;function sT(e,t){var r=this.__data__,n=oT(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this}var lT=sT,cT=K$,uT=Z$,dT=rT,fT=iT,hT=lT;function so(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}so.prototype.clear=cT;so.prototype.delete=uT;so.prototype.get=dT;so.prototype.has=fT;so.prototype.set=hT;var wd=so,pT=Ea,mT=Mr,vT=pT(mT,"Map"),Vv=vT,N0=U$,yT=wd,gT=Vv;function xT(){this.size=0,this.__data__={hash:new N0,map:new(gT||yT),string:new N0}}var bT=xT;function jT(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}var wT=jT,ST=wT;function _T(e,t){var r=e.__data__;return ST(t)?r[typeof t=="string"?"string":"hash"]:r.map}var Sd=_T,kT=Sd;function OT(e){var t=kT(this,e).delete(e);return this.size-=t?1:0,t}var NT=OT,PT=Sd;function AT(e){return PT(this,e).get(e)}var CT=AT,ET=Sd;function $T(e){return ET(this,e).has(e)}var TT=$T,MT=Sd;function IT(e,t){var r=MT(this,e),n=r.size;return r.set(e,t),this.size+=r.size==n?0:1,this}var LT=IT,DT=bT,RT=NT,BT=CT,FT=TT,zT=LT;function lo(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}lo.prototype.clear=DT;lo.prototype.delete=RT;lo.prototype.get=BT;lo.prototype.has=FT;lo.prototype.set=zT;var Gv=lo,dS=Gv,WT="Expected a function";function Yv(e,t){if(typeof e!="function"||t!=null&&typeof t!="function")throw new TypeError(WT);var r=function(){var n=arguments,a=t?t.apply(this,n):n[0],i=r.cache;if(i.has(a))return i.get(a);var s=e.apply(this,n);return r.cache=i.set(a,s)||i,s};return r.cache=new(Yv.Cache||dS),r}Yv.Cache=dS;var fS=Yv;const UT=de(fS);var HT=fS,KT=500;function VT(e){var t=HT(e,function(n){return r.size===KT&&r.clear(),n}),r=t.cache;return t}var GT=VT,YT=GT,qT=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,XT=/\\(\\)?/g,QT=YT(function(e){var t=[];return e.charCodeAt(0)===46&&t.push(""),e.replace(qT,function(r,n,a,i){t.push(a?i.replace(XT,"$1"):n||r)}),t}),JT=QT;function ZT(e,t){for(var r=-1,n=e==null?0:e.length,a=Array(n);++r<n;)a[r]=t(e[r],r,e);return a}var qv=ZT,P0=ml,e3=qv,t3=$t,r3=ao,A0=P0?P0.prototype:void 0,C0=A0?A0.toString:void 0;function hS(e){if(typeof e=="string")return e;if(t3(e))return e3(e,hS)+"";if(r3(e))return C0?C0.call(e):"";var t=e+"";return t=="0"&&1/e==-1/0?"-0":t}var n3=hS,a3=n3;function i3(e){return e==null?"":a3(e)}var pS=i3,o3=$t,s3=Uv,l3=JT,c3=pS;function u3(e,t){return o3(e)?e:s3(e,t)?[e]:l3(c3(e))}var mS=u3,d3=ao;function f3(e){if(typeof e=="string"||d3(e))return e;var t=e+"";return t=="0"&&1/e==-1/0?"-0":t}var _d=f3,h3=mS,p3=_d;function m3(e,t){t=h3(t,e);for(var r=0,n=t.length;e!=null&&r<n;)e=e[p3(t[r++])];return r&&r==n?e:void 0}var Xv=m3,v3=Xv;function y3(e,t,r){var n=e==null?void 0:v3(e,t);return n===void 0?r:n}var vS=y3;const Bt=de(vS);function g3(e){return e==null}var x3=g3;const te=de(x3);var b3=on,j3=$t,w3=sn,S3="[object String]";function _3(e){return typeof e=="string"||!j3(e)&&w3(e)&&b3(e)==S3}var k3=_3;const wa=de(k3);var yS={exports:{}},fe={};/**
- * @license React
- * react-is.production.min.js
- *
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- */var Qv=Symbol.for("react.element"),Jv=Symbol.for("react.portal"),kd=Symbol.for("react.fragment"),Od=Symbol.for("react.strict_mode"),Nd=Symbol.for("react.profiler"),Pd=Symbol.for("react.provider"),Ad=Symbol.for("react.context"),O3=Symbol.for("react.server_context"),Cd=Symbol.for("react.forward_ref"),Ed=Symbol.for("react.suspense"),$d=Symbol.for("react.suspense_list"),Td=Symbol.for("react.memo"),Md=Symbol.for("react.lazy"),N3=Symbol.for("react.offscreen"),gS;gS=Symbol.for("react.module.reference");function ar(e){if(typeof e=="object"&&e!==null){var t=e.$$typeof;switch(t){case Qv:switch(e=e.type,e){case kd:case Nd:case Od:case Ed:case $d:return e;default:switch(e=e&&e.$$typeof,e){case O3:case Ad:case Cd:case Md:case Td:case Pd:return e;default:return t}}case Jv:return t}}}fe.ContextConsumer=Ad;fe.ContextProvider=Pd;fe.Element=Qv;fe.ForwardRef=Cd;fe.Fragment=kd;fe.Lazy=Md;fe.Memo=Td;fe.Portal=Jv;fe.Profiler=Nd;fe.StrictMode=Od;fe.Suspense=Ed;fe.SuspenseList=$d;fe.isAsyncMode=function(){return!1};fe.isConcurrentMode=function(){return!1};fe.isContextConsumer=function(e){return ar(e)===Ad};fe.isContextProvider=function(e){return ar(e)===Pd};fe.isElement=function(e){return typeof e=="object"&&e!==null&&e.$$typeof===Qv};fe.isForwardRef=function(e){return ar(e)===Cd};fe.isFragment=function(e){return ar(e)===kd};fe.isLazy=function(e){return ar(e)===Md};fe.isMemo=function(e){return ar(e)===Td};fe.isPortal=function(e){return ar(e)===Jv};fe.isProfiler=function(e){return ar(e)===Nd};fe.isStrictMode=function(e){return ar(e)===Od};fe.isSuspense=function(e){return ar(e)===Ed};fe.isSuspenseList=function(e){return ar(e)===$d};fe.isValidElementType=function(e){return typeof e=="string"||typeof e=="function"||e===kd||e===Nd||e===Od||e===Ed||e===$d||e===N3||typeof e=="object"&&e!==null&&(e.$$typeof===Md||e.$$typeof===Td||e.$$typeof===Pd||e.$$typeof===Ad||e.$$typeof===Cd||e.$$typeof===gS||e.getModuleId!==void 0)};fe.typeOf=ar;yS.exports=fe;var P3=yS.exports,A3=on,C3=sn,E3="[object Number]";function $3(e){return typeof e=="number"||C3(e)&&A3(e)==E3}var xS=$3;const T3=de(xS);var M3=xS;function I3(e){return M3(e)&&e!=+e}var L3=I3;const co=de(L3);var rt=function(t){return t===0?0:t>0?1:-1},oa=function(t){return wa(t)&&t.indexOf("%")===t.length-1},U=function(t){return T3(t)&&!co(t)},D3=function(t){return te(t)},qe=function(t){return U(t)||wa(t)},R3=0,uo=function(t){var r=++R3;return"".concat(t||"").concat(r)},xt=function(t,r){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:0,a=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;if(!U(t)&&!wa(t))return n;var i;if(oa(t)){var s=t.indexOf("%");i=r*parseFloat(t.slice(0,s))/100}else i=+t;return co(i)&&(i=n),a&&i>r&&(i=r),i},gn=function(t){if(!t)return null;var r=Object.keys(t);return r&&r.length?t[r[0]]:null},B3=function(t){if(!Array.isArray(t))return!1;for(var r=t.length,n={},a=0;a<r;a++)if(!n[t[a]])n[t[a]]=!0;else return!0;return!1},lt=function(t,r){return U(t)&&U(r)?function(n){return t+n*(r-t)}:function(){return r}};function Qc(e,t,r){return!e||!e.length?null:e.find(function(n){return n&&(typeof t=="function"?t(n):Bt(n,t))===r})}var F3=function(t,r){return U(t)&&U(r)?t-r:wa(t)&&wa(r)?t.localeCompare(r):t instanceof Date&&r instanceof Date?t.getTime()-r.getTime():String(t).localeCompare(String(r))};function mi(e,t){for(var r in e)if({}.hasOwnProperty.call(e,r)&&(!{}.hasOwnProperty.call(t,r)||e[r]!==t[r]))return!1;for(var n in t)if({}.hasOwnProperty.call(t,n)&&!{}.hasOwnProperty.call(e,n))return!1;return!0}function mp(e){"@babel/helpers - typeof";return mp=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},mp(e)}var z3=["viewBox","children"],W3=["aria-activedescendant","aria-atomic","aria-autocomplete","aria-busy","aria-checked","aria-colcount","aria-colindex","aria-colspan","aria-controls","aria-current","aria-describedby","aria-details","aria-disabled","aria-errormessage","aria-expanded","aria-flowto","aria-haspopup","aria-hidden","aria-invalid","aria-keyshortcuts","aria-label","aria-labelledby","aria-level","aria-live","aria-modal","aria-multiline","aria-multiselectable","aria-orientation","aria-owns","aria-placeholder","aria-posinset","aria-pressed","aria-readonly","aria-relevant","aria-required","aria-roledescription","aria-rowcount","aria-rowindex","aria-rowspan","aria-selected","aria-setsize","aria-sort","aria-valuemax","aria-valuemin","aria-valuenow","aria-valuetext","className","color","height","id","lang","max","media","method","min","name","style","target","width","role","tabIndex","accentHeight","accumulate","additive","alignmentBaseline","allowReorder","alphabetic","amplitude","arabicForm","ascent","attributeName","attributeType","autoReverse","azimuth","baseFrequency","baselineShift","baseProfile","bbox","begin","bias","by","calcMode","capHeight","clip","clipPath","clipPathUnits","clipRule","colorInterpolation","colorInterpolationFilters","colorProfile","colorRendering","contentScriptType","contentStyleType","cursor","cx","cy","d","decelerate","descent","diffuseConstant","direction","display","divisor","dominantBaseline","dur","dx","dy","edgeMode","elevation","enableBackground","end","exponent","externalResourcesRequired","fill","fillOpacity","fillRule","filter","filterRes","filterUnits","floodColor","floodOpacity","focusable","fontFamily","fontSize","fontSizeAdjust","fontStretch","fontStyle","fontVariant","fontWeight","format","from","fx","fy","g1","g2","glyphName","glyphOrientationHorizontal","glyphOrientationVertical","glyphRef","gradientTransform","gradientUnits","hanging","horizAdvX","horizOriginX","href","ideographic","imageRendering","in2","in","intercept","k1","k2","k3","k4","k","kernelMatrix","kernelUnitLength","kerning","keyPoints","keySplines","keyTimes","lengthAdjust","letterSpacing","lightingColor","limitingConeAngle","local","markerEnd","markerHeight","markerMid","markerStart","markerUnits","markerWidth","mask","maskContentUnits","maskUnits","mathematical","mode","numOctaves","offset","opacity","operator","order","orient","orientation","origin","overflow","overlinePosition","overlineThickness","paintOrder","panose1","pathLength","patternContentUnits","patternTransform","patternUnits","pointerEvents","pointsAtX","pointsAtY","pointsAtZ","preserveAlpha","preserveAspectRatio","primitiveUnits","r","radius","refX","refY","renderingIntent","repeatCount","repeatDur","requiredExtensions","requiredFeatures","restart","result","rotate","rx","ry","seed","shapeRendering","slope","spacing","specularConstant","specularExponent","speed","spreadMethod","startOffset","stdDeviation","stemh","stemv","stitchTiles","stopColor","stopOpacity","strikethroughPosition","strikethroughThickness","string","stroke","strokeDasharray","strokeDashoffset","strokeLinecap","strokeLinejoin","strokeMiterlimit","strokeOpacity","strokeWidth","surfaceScale","systemLanguage","tableValues","targetX","targetY","textAnchor","textDecoration","textLength","textRendering","to","transform","u1","u2","underlinePosition","underlineThickness","unicode","unicodeBidi","unicodeRange","unitsPerEm","vAlphabetic","values","vectorEffect","version","vertAdvY","vertOriginX","vertOriginY","vHanging","vIdeographic","viewTarget","visibility","vMathematical","widths","wordSpacing","writingMode","x1","x2","x","xChannelSelector","xHeight","xlinkActuate","xlinkArcrole","xlinkHref","xlinkRole","xlinkShow","xlinkTitle","xlinkType","xmlBase","xmlLang","xmlns","xmlnsXlink","xmlSpace","y1","y2","y","yChannelSelector","z","zoomAndPan","ref","key","angle"],E0=["points","pathLength"],Wf={svg:z3,polygon:E0,polyline:E0},Zv=["dangerouslySetInnerHTML","onCopy","onCopyCapture","onCut","onCutCapture","onPaste","onPasteCapture","onCompositionEnd","onCompositionEndCapture","onCompositionStart","onCompositionStartCapture","onCompositionUpdate","onCompositionUpdateCapture","onFocus","onFocusCapture","onBlur","onBlurCapture","onChange","onChangeCapture","onBeforeInput","onBeforeInputCapture","onInput","onInputCapture","onReset","onResetCapture","onSubmit","onSubmitCapture","onInvalid","onInvalidCapture","onLoad","onLoadCapture","onError","onErrorCapture","onKeyDown","onKeyDownCapture","onKeyPress","onKeyPressCapture","onKeyUp","onKeyUpCapture","onAbort","onAbortCapture","onCanPlay","onCanPlayCapture","onCanPlayThrough","onCanPlayThroughCapture","onDurationChange","onDurationChangeCapture","onEmptied","onEmptiedCapture","onEncrypted","onEncryptedCapture","onEnded","onEndedCapture","onLoadedData","onLoadedDataCapture","onLoadedMetadata","onLoadedMetadataCapture","onLoadStart","onLoadStartCapture","onPause","onPauseCapture","onPlay","onPlayCapture","onPlaying","onPlayingCapture","onProgress","onProgressCapture","onRateChange","onRateChangeCapture","onSeeked","onSeekedCapture","onSeeking","onSeekingCapture","onStalled","onStalledCapture","onSuspend","onSuspendCapture","onTimeUpdate","onTimeUpdateCapture","onVolumeChange","onVolumeChangeCapture","onWaiting","onWaitingCapture","onAuxClick","onAuxClickCapture","onClick","onClickCapture","onContextMenu","onContextMenuCapture","onDoubleClick","onDoubleClickCapture","onDrag","onDragCapture","onDragEnd","onDragEndCapture","onDragEnter","onDragEnterCapture","onDragExit","onDragExitCapture","onDragLeave","onDragLeaveCapture","onDragOver","onDragOverCapture","onDragStart","onDragStartCapture","onDrop","onDropCapture","onMouseDown","onMouseDownCapture","onMouseEnter","onMouseLeave","onMouseMove","onMouseMoveCapture","onMouseOut","onMouseOutCapture","onMouseOver","onMouseOverCapture","onMouseUp","onMouseUpCapture","onSelect","onSelectCapture","onTouchCancel","onTouchCancelCapture","onTouchEnd","onTouchEndCapture","onTouchMove","onTouchMoveCapture","onTouchStart","onTouchStartCapture","onPointerDown","onPointerDownCapture","onPointerMove","onPointerMoveCapture","onPointerUp","onPointerUpCapture","onPointerCancel","onPointerCancelCapture","onPointerEnter","onPointerEnterCapture","onPointerLeave","onPointerLeaveCapture","onPointerOver","onPointerOverCapture","onPointerOut","onPointerOutCapture","onGotPointerCapture","onGotPointerCaptureCapture","onLostPointerCapture","onLostPointerCaptureCapture","onScroll","onScrollCapture","onWheel","onWheelCapture","onAnimationStart","onAnimationStartCapture","onAnimationEnd","onAnimationEndCapture","onAnimationIteration","onAnimationIterationCapture","onTransitionEnd","onTransitionEndCapture"],Jc=function(t,r){if(!t||typeof t=="function"||typeof t=="boolean")return null;var n=t;if(P.isValidElement(t)&&(n=t.props),!io(n))return null;var a={};return Object.keys(n).forEach(function(i){Zv.includes(i)&&(a[i]=r||function(s){return n[i](n,s)})}),a},U3=function(t,r,n){return function(a){return t(r,n,a),null}},en=function(t,r,n){if(!io(t)||mp(t)!=="object")return null;var a=null;return Object.keys(t).forEach(function(i){var s=t[i];Zv.includes(i)&&typeof s=="function"&&(a||(a={}),a[i]=U3(s,r,n))}),a},H3=["children"],K3=["children"];function $0(e,t){if(e==null)return{};var r=V3(e,t),n,a;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(a=0;a<i.length;a++)n=i[a],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function V3(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function vp(e){"@babel/helpers - typeof";return vp=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},vp(e)}var T0={click:"onClick",mousedown:"onMouseDown",mouseup:"onMouseUp",mouseover:"onMouseOver",mousemove:"onMouseMove",mouseout:"onMouseOut",mouseenter:"onMouseEnter",mouseleave:"onMouseLeave",touchcancel:"onTouchCancel",touchend:"onTouchEnd",touchmove:"onTouchMove",touchstart:"onTouchStart",contextmenu:"onContextMenu",dblclick:"onDoubleClick"},Yr=function(t){return typeof t=="string"?t:t?t.displayName||t.name||"Component":""},M0=null,Uf=null,ey=function e(t){if(t===M0&&Array.isArray(Uf))return Uf;var r=[];return P.Children.forEach(t,function(n){te(n)||(P3.isFragment(n)?r=r.concat(e(n.props.children)):r.push(n))}),Uf=r,M0=t,r};function Ft(e,t){var r=[],n=[];return Array.isArray(t)?n=t.map(function(a){return Yr(a)}):n=[Yr(t)],ey(e).forEach(function(a){var i=Bt(a,"type.displayName")||Bt(a,"type.name");n.indexOf(i)!==-1&&r.push(a)}),r}function It(e,t){var r=Ft(e,t);return r&&r[0]}var I0=function(t){if(!t||!t.props)return!1;var r=t.props,n=r.width,a=r.height;return!(!U(n)||n<=0||!U(a)||a<=0)},G3=["a","altGlyph","altGlyphDef","altGlyphItem","animate","animateColor","animateMotion","animateTransform","circle","clipPath","color-profile","cursor","defs","desc","ellipse","feBlend","feColormatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence","filter","font","font-face","font-face-format","font-face-name","font-face-url","foreignObject","g","glyph","glyphRef","hkern","image","line","lineGradient","marker","mask","metadata","missing-glyph","mpath","path","pattern","polygon","polyline","radialGradient","rect","script","set","stop","style","svg","switch","symbol","text","textPath","title","tref","tspan","use","view","vkern"],Y3=function(t){return t&&t.type&&wa(t.type)&&G3.indexOf(t.type)>=0},q3=function(t){return t&&vp(t)==="object"&&"clipDot"in t},X3=function(t,r,n,a){var i,s=(i=Wf==null?void 0:Wf[a])!==null&&i!==void 0?i:[];return r.startsWith("data-")||!Q(t)&&(a&&s.includes(r)||W3.includes(r))||n&&Zv.includes(r)},X=function(t,r,n){if(!t||typeof t=="function"||typeof t=="boolean")return null;var a=t;if(P.isValidElement(t)&&(a=t.props),!io(a))return null;var i={};return Object.keys(a).forEach(function(s){var l;X3((l=a)===null||l===void 0?void 0:l[s],s,r,n)&&(i[s]=a[s])}),i},yp=function e(t,r){if(t===r)return!0;var n=P.Children.count(t);if(n!==P.Children.count(r))return!1;if(n===0)return!0;if(n===1)return L0(Array.isArray(t)?t[0]:t,Array.isArray(r)?r[0]:r);for(var a=0;a<n;a++){var i=t[a],s=r[a];if(Array.isArray(i)||Array.isArray(s)){if(!e(i,s))return!1}else if(!L0(i,s))return!1}return!0},L0=function(t,r){if(te(t)&&te(r))return!0;if(!te(t)&&!te(r)){var n=t.props||{},a=n.children,i=$0(n,H3),s=r.props||{},l=s.children,c=$0(s,K3);return a&&l?mi(i,c)&&yp(a,l):!a&&!l?mi(i,c):!1}return!1},D0=function(t,r){var n=[],a={};return ey(t).forEach(function(i,s){if(Y3(i))n.push(i);else if(i){var l=Yr(i.type),c=r[l]||{},u=c.handler,f=c.once;if(u&&(!f||!a[l])){var d=u(i,l,s);n.push(d),a[l]=!0}}}),n},Q3=function(t){var r=t&&t.type;return r&&T0[r]?T0[r]:null},J3=function(t,r){return ey(r).indexOf(t)},Z3=["children","width","height","viewBox","className","style","title","desc"];function gp(){return gp=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},gp.apply(this,arguments)}function e5(e,t){if(e==null)return{};var r=t5(e,t),n,a;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(a=0;a<i.length;a++)n=i[a],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function t5(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function xp(e){var t=e.children,r=e.width,n=e.height,a=e.viewBox,i=e.className,s=e.style,l=e.title,c=e.desc,u=e5(e,Z3),f=a||{width:r,height:n,x:0,y:0},d=ee("recharts-surface",i);return $.createElement("svg",gp({},X(u,!0,"svg"),{className:d,width:r,height:n,style:s,viewBox:"".concat(f.x," ").concat(f.y," ").concat(f.width," ").concat(f.height)}),$.createElement("title",null,l),$.createElement("desc",null,c),t)}var r5=["children","className"];function bp(){return bp=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},bp.apply(this,arguments)}function n5(e,t){if(e==null)return{};var r=a5(e,t),n,a;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(a=0;a<i.length;a++)n=i[a],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function a5(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}var ne=$.forwardRef(function(e,t){var r=e.children,n=e.className,a=n5(e,r5),i=ee("recharts-layer",n);return $.createElement("g",bp({className:i},X(a,!0),{ref:t}),r)}),yr=function(t,r){for(var n=arguments.length,a=new Array(n>2?n-2:0),i=2;i<n;i++)a[i-2]=arguments[i]};function i5(e,t,r){var n=-1,a=e.length;t<0&&(t=-t>a?0:a+t),r=r>a?a:r,r<0&&(r+=a),a=t>r?0:r-t>>>0,t>>>=0;for(var i=Array(a);++n<a;)i[n]=e[n+t];return i}var o5=i5,s5=o5;function l5(e,t,r){var n=e.length;return r=r===void 0?n:r,!t&&r>=n?e:s5(e,t,r)}var c5=l5,u5="\\ud800-\\udfff",d5="\\u0300-\\u036f",f5="\\ufe20-\\ufe2f",h5="\\u20d0-\\u20ff",p5=d5+f5+h5,m5="\\ufe0e\\ufe0f",v5="\\u200d",y5=RegExp("["+v5+u5+p5+m5+"]");function g5(e){return y5.test(e)}var bS=g5;function x5(e){return e.split("")}var b5=x5,jS="\\ud800-\\udfff",j5="\\u0300-\\u036f",w5="\\ufe20-\\ufe2f",S5="\\u20d0-\\u20ff",_5=j5+w5+S5,k5="\\ufe0e\\ufe0f",O5="["+jS+"]",jp="["+_5+"]",wp="\\ud83c[\\udffb-\\udfff]",N5="(?:"+jp+"|"+wp+")",wS="[^"+jS+"]",SS="(?:\\ud83c[\\udde6-\\uddff]){2}",_S="[\\ud800-\\udbff][\\udc00-\\udfff]",P5="\\u200d",kS=N5+"?",OS="["+k5+"]?",A5="(?:"+P5+"(?:"+[wS,SS,_S].join("|")+")"+OS+kS+")*",C5=OS+kS+A5,E5="(?:"+[wS+jp+"?",jp,SS,_S,O5].join("|")+")",$5=RegExp(wp+"(?="+wp+")|"+E5+C5,"g");function T5(e){return e.match($5)||[]}var M5=T5,I5=b5,L5=bS,D5=M5;function R5(e){return L5(e)?D5(e):I5(e)}var B5=R5,F5=c5,z5=bS,W5=B5,U5=pS;function H5(e){return function(t){t=U5(t);var r=z5(t)?W5(t):void 0,n=r?r[0]:t.charAt(0),a=r?F5(r,1).join(""):t.slice(1);return n[e]()+a}}var K5=H5,V5=K5,G5=V5("toUpperCase"),Y5=G5;const Id=de(Y5);function be(e){return function(){return e}}const NS=Math.cos,Zc=Math.sin,jr=Math.sqrt,eu=Math.PI,Ld=2*eu,Sp=Math.PI,_p=2*Sp,Zn=1e-6,q5=_p-Zn;function PS(e){this._+=e[0];for(let t=1,r=e.length;t<r;++t)this._+=arguments[t]+e[t]}function X5(e){let t=Math.floor(e);if(!(t>=0))throw new Error(`invalid digits: ${e}`);if(t>15)return PS;const r=10**t;return function(n){this._+=n[0];for(let a=1,i=n.length;a<i;++a)this._+=Math.round(arguments[a]*r)/r+n[a]}}class Q5{constructor(t){this._x0=this._y0=this._x1=this._y1=null,this._="",this._append=t==null?PS:X5(t)}moveTo(t,r){this._append`M${this._x0=this._x1=+t},${this._y0=this._y1=+r}`}closePath(){this._x1!==null&&(this._x1=this._x0,this._y1=this._y0,this._append`Z`)}lineTo(t,r){this._append`L${this._x1=+t},${this._y1=+r}`}quadraticCurveTo(t,r,n,a){this._append`Q${+t},${+r},${this._x1=+n},${this._y1=+a}`}bezierCurveTo(t,r,n,a,i,s){this._append`C${+t},${+r},${+n},${+a},${this._x1=+i},${this._y1=+s}`}arcTo(t,r,n,a,i){if(t=+t,r=+r,n=+n,a=+a,i=+i,i<0)throw new Error(`negative radius: ${i}`);let s=this._x1,l=this._y1,c=n-t,u=a-r,f=s-t,d=l-r,h=f*f+d*d;if(this._x1===null)this._append`M${this._x1=t},${this._y1=r}`;else if(h>Zn)if(!(Math.abs(d*c-u*f)>Zn)||!i)this._append`L${this._x1=t},${this._y1=r}`;else{let p=n-s,g=a-l,y=c*c+u*u,b=p*p+g*g,v=Math.sqrt(y),m=Math.sqrt(h),x=i*Math.tan((Sp-Math.acos((y+h-b)/(2*v*m)))/2),S=x/m,j=x/v;Math.abs(S-1)>Zn&&this._append`L${t+S*f},${r+S*d}`,this._append`A${i},${i},0,0,${+(d*p>f*g)},${this._x1=t+j*c},${this._y1=r+j*u}`}}arc(t,r,n,a,i,s){if(t=+t,r=+r,n=+n,s=!!s,n<0)throw new Error(`negative radius: ${n}`);let l=n*Math.cos(a),c=n*Math.sin(a),u=t+l,f=r+c,d=1^s,h=s?a-i:i-a;this._x1===null?this._append`M${u},${f}`:(Math.abs(this._x1-u)>Zn||Math.abs(this._y1-f)>Zn)&&this._append`L${u},${f}`,n&&(h<0&&(h=h%_p+_p),h>q5?this._append`A${n},${n},0,1,${d},${t-l},${r-c}A${n},${n},0,1,${d},${this._x1=u},${this._y1=f}`:h>Zn&&this._append`A${n},${n},0,${+(h>=Sp)},${d},${this._x1=t+n*Math.cos(i)},${this._y1=r+n*Math.sin(i)}`)}rect(t,r,n,a){this._append`M${this._x0=this._x1=+t},${this._y0=this._y1=+r}h${n=+n}v${+a}h${-n}Z`}toString(){return this._}}function ty(e){let t=3;return e.digits=function(r){if(!arguments.length)return t;if(r==null)t=null;else{const n=Math.floor(r);if(!(n>=0))throw new RangeError(`invalid digits: ${r}`);t=n}return e},()=>new Q5(t)}function ry(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}function AS(e){this._context=e}AS.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;default:this._context.lineTo(e,t);break}}};function Dd(e){return new AS(e)}function CS(e){return e[0]}function ES(e){return e[1]}function $S(e,t){var r=be(!0),n=null,a=Dd,i=null,s=ty(l);e=typeof e=="function"?e:e===void 0?CS:be(e),t=typeof t=="function"?t:t===void 0?ES:be(t);function l(c){var u,f=(c=ry(c)).length,d,h=!1,p;for(n==null&&(i=a(p=s())),u=0;u<=f;++u)!(u<f&&r(d=c[u],u,c))===h&&((h=!h)?i.lineStart():i.lineEnd()),h&&i.point(+e(d,u,c),+t(d,u,c));if(p)return i=null,p+""||null}return l.x=function(c){return arguments.length?(e=typeof c=="function"?c:be(+c),l):e},l.y=function(c){return arguments.length?(t=typeof c=="function"?c:be(+c),l):t},l.defined=function(c){return arguments.length?(r=typeof c=="function"?c:be(!!c),l):r},l.curve=function(c){return arguments.length?(a=c,n!=null&&(i=a(n)),l):a},l.context=function(c){return arguments.length?(c==null?n=i=null:i=a(n=c),l):n},l}function Kl(e,t,r){var n=null,a=be(!0),i=null,s=Dd,l=null,c=ty(u);e=typeof e=="function"?e:e===void 0?CS:be(+e),t=typeof t=="function"?t:be(t===void 0?0:+t),r=typeof r=="function"?r:r===void 0?ES:be(+r);function u(d){var h,p,g,y=(d=ry(d)).length,b,v=!1,m,x=new Array(y),S=new Array(y);for(i==null&&(l=s(m=c())),h=0;h<=y;++h){if(!(h<y&&a(b=d[h],h,d))===v)if(v=!v)p=h,l.areaStart(),l.lineStart();else{for(l.lineEnd(),l.lineStart(),g=h-1;g>=p;--g)l.point(x[g],S[g]);l.lineEnd(),l.areaEnd()}v&&(x[h]=+e(b,h,d),S[h]=+t(b,h,d),l.point(n?+n(b,h,d):x[h],r?+r(b,h,d):S[h]))}if(m)return l=null,m+""||null}function f(){return $S().defined(a).curve(s).context(i)}return u.x=function(d){return arguments.length?(e=typeof d=="function"?d:be(+d),n=null,u):e},u.x0=function(d){return arguments.length?(e=typeof d=="function"?d:be(+d),u):e},u.x1=function(d){return arguments.length?(n=d==null?null:typeof d=="function"?d:be(+d),u):n},u.y=function(d){return arguments.length?(t=typeof d=="function"?d:be(+d),r=null,u):t},u.y0=function(d){return arguments.length?(t=typeof d=="function"?d:be(+d),u):t},u.y1=function(d){return arguments.length?(r=d==null?null:typeof d=="function"?d:be(+d),u):r},u.lineX0=u.lineY0=function(){return f().x(e).y(t)},u.lineY1=function(){return f().x(e).y(r)},u.lineX1=function(){return f().x(n).y(t)},u.defined=function(d){return arguments.length?(a=typeof d=="function"?d:be(!!d),u):a},u.curve=function(d){return arguments.length?(s=d,i!=null&&(l=s(i)),u):s},u.context=function(d){return arguments.length?(d==null?i=l=null:l=s(i=d),u):i},u}class TS{constructor(t,r){this._context=t,this._x=r}areaStart(){this._line=0}areaEnd(){this._line=NaN}lineStart(){this._point=0}lineEnd(){(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line}point(t,r){switch(t=+t,r=+r,this._point){case 0:{this._point=1,this._line?this._context.lineTo(t,r):this._context.moveTo(t,r);break}case 1:this._point=2;default:{this._x?this._context.bezierCurveTo(this._x0=(this._x0+t)/2,this._y0,this._x0,r,t,r):this._context.bezierCurveTo(this._x0,this._y0=(this._y0+r)/2,t,this._y0,t,r);break}}this._x0=t,this._y0=r}}function J5(e){return new TS(e,!0)}function Z5(e){return new TS(e,!1)}const ny={draw(e,t){const r=jr(t/eu);e.moveTo(r,0),e.arc(0,0,r,0,Ld)}},e4={draw(e,t){const r=jr(t/5)/2;e.moveTo(-3*r,-r),e.lineTo(-r,-r),e.lineTo(-r,-3*r),e.lineTo(r,-3*r),e.lineTo(r,-r),e.lineTo(3*r,-r),e.lineTo(3*r,r),e.lineTo(r,r),e.lineTo(r,3*r),e.lineTo(-r,3*r),e.lineTo(-r,r),e.lineTo(-3*r,r),e.closePath()}},MS=jr(1/3),t4=MS*2,r4={draw(e,t){const r=jr(t/t4),n=r*MS;e.moveTo(0,-r),e.lineTo(n,0),e.lineTo(0,r),e.lineTo(-n,0),e.closePath()}},n4={draw(e,t){const r=jr(t),n=-r/2;e.rect(n,n,r,r)}},a4=.8908130915292852,IS=Zc(eu/10)/Zc(7*eu/10),i4=Zc(Ld/10)*IS,o4=-NS(Ld/10)*IS,s4={draw(e,t){const r=jr(t*a4),n=i4*r,a=o4*r;e.moveTo(0,-r),e.lineTo(n,a);for(let i=1;i<5;++i){const s=Ld*i/5,l=NS(s),c=Zc(s);e.lineTo(c*r,-l*r),e.lineTo(l*n-c*a,c*n+l*a)}e.closePath()}},Hf=jr(3),l4={draw(e,t){const r=-jr(t/(Hf*3));e.moveTo(0,r*2),e.lineTo(-Hf*r,-r),e.lineTo(Hf*r,-r),e.closePath()}},Ht=-.5,Kt=jr(3)/2,kp=1/jr(12),c4=(kp/2+1)*3,u4={draw(e,t){const r=jr(t/c4),n=r/2,a=r*kp,i=n,s=r*kp+r,l=-i,c=s;e.moveTo(n,a),e.lineTo(i,s),e.lineTo(l,c),e.lineTo(Ht*n-Kt*a,Kt*n+Ht*a),e.lineTo(Ht*i-Kt*s,Kt*i+Ht*s),e.lineTo(Ht*l-Kt*c,Kt*l+Ht*c),e.lineTo(Ht*n+Kt*a,Ht*a-Kt*n),e.lineTo(Ht*i+Kt*s,Ht*s-Kt*i),e.lineTo(Ht*l+Kt*c,Ht*c-Kt*l),e.closePath()}};function d4(e,t){let r=null,n=ty(a);e=typeof e=="function"?e:be(e||ny),t=typeof t=="function"?t:be(t===void 0?64:+t);function a(){let i;if(r||(r=i=n()),e.apply(this,arguments).draw(r,+t.apply(this,arguments)),i)return r=null,i+""||null}return a.type=function(i){return arguments.length?(e=typeof i=="function"?i:be(i),a):e},a.size=function(i){return arguments.length?(t=typeof i=="function"?i:be(+i),a):t},a.context=function(i){return arguments.length?(r=i??null,a):r},a}function tu(){}function ru(e,t,r){e._context.bezierCurveTo((2*e._x0+e._x1)/3,(2*e._y0+e._y1)/3,(e._x0+2*e._x1)/3,(e._y0+2*e._y1)/3,(e._x0+4*e._x1+t)/6,(e._y0+4*e._y1+r)/6)}function LS(e){this._context=e}LS.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){switch(this._point){case 3:ru(this,this._x1,this._y1);case 2:this._context.lineTo(this._x1,this._y1);break}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;break;case 2:this._point=3,this._context.lineTo((5*this._x0+this._x1)/6,(5*this._y0+this._y1)/6);default:ru(this,e,t);break}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t}};function f4(e){return new LS(e)}function DS(e){this._context=e}DS.prototype={areaStart:tu,areaEnd:tu,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._y0=this._y1=this._y2=this._y3=this._y4=NaN,this._point=0},lineEnd:function(){switch(this._point){case 1:{this._context.moveTo(this._x2,this._y2),this._context.closePath();break}case 2:{this._context.moveTo((this._x2+2*this._x3)/3,(this._y2+2*this._y3)/3),this._context.lineTo((this._x3+2*this._x2)/3,(this._y3+2*this._y2)/3),this._context.closePath();break}case 3:{this.point(this._x2,this._y2),this.point(this._x3,this._y3),this.point(this._x4,this._y4);break}}},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._x2=e,this._y2=t;break;case 1:this._point=2,this._x3=e,this._y3=t;break;case 2:this._point=3,this._x4=e,this._y4=t,this._context.moveTo((this._x0+4*this._x1+e)/6,(this._y0+4*this._y1+t)/6);break;default:ru(this,e,t);break}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t}};function h4(e){return new DS(e)}function RS(e){this._context=e}RS.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){(this._line||this._line!==0&&this._point===3)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3;var r=(this._x0+4*this._x1+e)/6,n=(this._y0+4*this._y1+t)/6;this._line?this._context.lineTo(r,n):this._context.moveTo(r,n);break;case 3:this._point=4;default:ru(this,e,t);break}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t}};function p4(e){return new RS(e)}function BS(e){this._context=e}BS.prototype={areaStart:tu,areaEnd:tu,lineStart:function(){this._point=0},lineEnd:function(){this._point&&this._context.closePath()},point:function(e,t){e=+e,t=+t,this._point?this._context.lineTo(e,t):(this._point=1,this._context.moveTo(e,t))}};function m4(e){return new BS(e)}function R0(e){return e<0?-1:1}function B0(e,t,r){var n=e._x1-e._x0,a=t-e._x1,i=(e._y1-e._y0)/(n||a<0&&-0),s=(r-e._y1)/(a||n<0&&-0),l=(i*a+s*n)/(n+a);return(R0(i)+R0(s))*Math.min(Math.abs(i),Math.abs(s),.5*Math.abs(l))||0}function F0(e,t){var r=e._x1-e._x0;return r?(3*(e._y1-e._y0)/r-t)/2:t}function Kf(e,t,r){var n=e._x0,a=e._y0,i=e._x1,s=e._y1,l=(i-n)/3;e._context.bezierCurveTo(n+l,a+l*t,i-l,s-l*r,i,s)}function nu(e){this._context=e}nu.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=this._t0=NaN,this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x1,this._y1);break;case 3:Kf(this,this._t0,F0(this,this._t0));break}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){var r=NaN;if(e=+e,t=+t,!(e===this._x1&&t===this._y1)){switch(this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;break;case 2:this._point=3,Kf(this,F0(this,r=B0(this,e,t)),r);break;default:Kf(this,this._t0,r=B0(this,e,t));break}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t,this._t0=r}}};function FS(e){this._context=new zS(e)}(FS.prototype=Object.create(nu.prototype)).point=function(e,t){nu.prototype.point.call(this,t,e)};function zS(e){this._context=e}zS.prototype={moveTo:function(e,t){this._context.moveTo(t,e)},closePath:function(){this._context.closePath()},lineTo:function(e,t){this._context.lineTo(t,e)},bezierCurveTo:function(e,t,r,n,a,i){this._context.bezierCurveTo(t,e,n,r,i,a)}};function v4(e){return new nu(e)}function y4(e){return new FS(e)}function WS(e){this._context=e}WS.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x=[],this._y=[]},lineEnd:function(){var e=this._x,t=this._y,r=e.length;if(r)if(this._line?this._context.lineTo(e[0],t[0]):this._context.moveTo(e[0],t[0]),r===2)this._context.lineTo(e[1],t[1]);else for(var n=z0(e),a=z0(t),i=0,s=1;s<r;++i,++s)this._context.bezierCurveTo(n[0][i],a[0][i],n[1][i],a[1][i],e[s],t[s]);(this._line||this._line!==0&&r===1)&&this._context.closePath(),this._line=1-this._line,this._x=this._y=null},point:function(e,t){this._x.push(+e),this._y.push(+t)}};function z0(e){var t,r=e.length-1,n,a=new Array(r),i=new Array(r),s=new Array(r);for(a[0]=0,i[0]=2,s[0]=e[0]+2*e[1],t=1;t<r-1;++t)a[t]=1,i[t]=4,s[t]=4*e[t]+2*e[t+1];for(a[r-1]=2,i[r-1]=7,s[r-1]=8*e[r-1]+e[r],t=1;t<r;++t)n=a[t]/i[t-1],i[t]-=n,s[t]-=n*s[t-1];for(a[r-1]=s[r-1]/i[r-1],t=r-2;t>=0;--t)a[t]=(s[t]-a[t+1])/i[t];for(i[r-1]=(e[r]+a[r-1])/2,t=0;t<r-1;++t)i[t]=2*e[t+1]-a[t+1];return[a,i]}function g4(e){return new WS(e)}function Rd(e,t){this._context=e,this._t=t}Rd.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x=this._y=NaN,this._point=0},lineEnd:function(){0<this._t&&this._t<1&&this._point===2&&this._context.lineTo(this._x,this._y),(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line>=0&&(this._t=1-this._t,this._line=1-this._line)},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;default:{if(this._t<=0)this._context.lineTo(this._x,t),this._context.lineTo(e,t);else{var r=this._x*(1-this._t)+e*this._t;this._context.lineTo(r,this._y),this._context.lineTo(r,t)}break}}this._x=e,this._y=t}};function x4(e){return new Rd(e,.5)}function b4(e){return new Rd(e,0)}function j4(e){return new Rd(e,1)}function Ni(e,t){if((s=e.length)>1)for(var r=1,n,a,i=e[t[0]],s,l=i.length;r<s;++r)for(a=i,i=e[t[r]],n=0;n<l;++n)i[n][1]+=i[n][0]=isNaN(a[n][1])?a[n][0]:a[n][1]}function Op(e){for(var t=e.length,r=new Array(t);--t>=0;)r[t]=t;return r}function w4(e,t){return e[t]}function S4(e){const t=[];return t.key=e,t}function _4(){var e=be([]),t=Op,r=Ni,n=w4;function a(i){var s=Array.from(e.apply(this,arguments),S4),l,c=s.length,u=-1,f;for(const d of i)for(l=0,++u;l<c;++l)(s[l][u]=[0,+n(d,s[l].key,u,i)]).data=d;for(l=0,f=ry(t(s));l<c;++l)s[f[l]].index=l;return r(s,f),s}return a.keys=function(i){return arguments.length?(e=typeof i=="function"?i:be(Array.from(i)),a):e},a.value=function(i){return arguments.length?(n=typeof i=="function"?i:be(+i),a):n},a.order=function(i){return arguments.length?(t=i==null?Op:typeof i=="function"?i:be(Array.from(i)),a):t},a.offset=function(i){return arguments.length?(r=i??Ni,a):r},a}function k4(e,t){if((n=e.length)>0){for(var r,n,a=0,i=e[0].length,s;a<i;++a){for(s=r=0;r<n;++r)s+=e[r][a][1]||0;if(s)for(r=0;r<n;++r)e[r][a][1]/=s}Ni(e,t)}}function O4(e,t){if((a=e.length)>0){for(var r=0,n=e[t[0]],a,i=n.length;r<i;++r){for(var s=0,l=0;s<a;++s)l+=e[s][r][1]||0;n[r][1]+=n[r][0]=-l/2}Ni(e,t)}}function N4(e,t){if(!(!((s=e.length)>0)||!((i=(a=e[t[0]]).length)>0))){for(var r=0,n=1,a,i,s;n<i;++n){for(var l=0,c=0,u=0;l<s;++l){for(var f=e[t[l]],d=f[n][1]||0,h=f[n-1][1]||0,p=(d-h)/2,g=0;g<l;++g){var y=e[t[g]],b=y[n][1]||0,v=y[n-1][1]||0;p+=b-v}c+=d,u+=p*d}a[n-1][1]+=a[n-1][0]=r,c&&(r-=u/c)}a[n-1][1]+=a[n-1][0]=r,Ni(e,t)}}function Os(e){"@babel/helpers - typeof";return Os=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Os(e)}var P4=["type","size","sizeType"];function Np(){return Np=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},Np.apply(this,arguments)}function W0(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function U0(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?W0(Object(r),!0).forEach(function(n){A4(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):W0(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function A4(e,t,r){return t=C4(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function C4(e){var t=E4(e,"string");return Os(t)=="symbol"?t:t+""}function E4(e,t){if(Os(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(Os(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function $4(e,t){if(e==null)return{};var r=T4(e,t),n,a;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(a=0;a<i.length;a++)n=i[a],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function T4(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}var US={symbolCircle:ny,symbolCross:e4,symbolDiamond:r4,symbolSquare:n4,symbolStar:s4,symbolTriangle:l4,symbolWye:u4},M4=Math.PI/180,I4=function(t){var r="symbol".concat(Id(t));return US[r]||ny},L4=function(t,r,n){if(r==="area")return t;switch(n){case"cross":return 5*t*t/9;case"diamond":return .5*t*t/Math.sqrt(3);case"square":return t*t;case"star":{var a=18*M4;return 1.25*t*t*(Math.tan(a)-Math.tan(a*2)*Math.pow(Math.tan(a),2))}case"triangle":return Math.sqrt(3)*t*t/4;case"wye":return(21-10*Math.sqrt(3))*t*t/8;default:return Math.PI*t*t/4}},D4=function(t,r){US["symbol".concat(Id(t))]=r},ay=function(t){var r=t.type,n=r===void 0?"circle":r,a=t.size,i=a===void 0?64:a,s=t.sizeType,l=s===void 0?"area":s,c=$4(t,P4),u=U0(U0({},c),{},{type:n,size:i,sizeType:l}),f=function(){var b=I4(n),v=d4().type(b).size(L4(i,l,n));return v()},d=u.className,h=u.cx,p=u.cy,g=X(u,!0);return h===+h&&p===+p&&i===+i?$.createElement("path",Np({},g,{className:ee("recharts-symbols",d),transform:"translate(".concat(h,", ").concat(p,")"),d:f()})):null};ay.registerSymbol=D4;function Pi(e){"@babel/helpers - typeof";return Pi=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Pi(e)}function Pp(){return Pp=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},Pp.apply(this,arguments)}function H0(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function R4(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?H0(Object(r),!0).forEach(function(n){Ns(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):H0(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function B4(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function F4(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,KS(n.key),n)}}function z4(e,t,r){return t&&F4(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function W4(e,t,r){return t=au(t),U4(e,HS()?Reflect.construct(t,r||[],au(e).constructor):t.apply(e,r))}function U4(e,t){if(t&&(Pi(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return H4(e)}function H4(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function HS(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(HS=function(){return!!e})()}function au(e){return au=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},au(e)}function K4(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Ap(e,t)}function Ap(e,t){return Ap=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,a){return n.__proto__=a,n},Ap(e,t)}function Ns(e,t,r){return t=KS(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function KS(e){var t=V4(e,"string");return Pi(t)=="symbol"?t:t+""}function V4(e,t){if(Pi(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(Pi(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}var Vt=32,iy=function(e){function t(){return B4(this,t),W4(this,t,arguments)}return K4(t,e),z4(t,[{key:"renderIcon",value:function(n){var a=this.props.inactiveColor,i=Vt/2,s=Vt/6,l=Vt/3,c=n.inactive?a:n.color;if(n.type==="plainline")return $.createElement("line",{strokeWidth:4,fill:"none",stroke:c,strokeDasharray:n.payload.strokeDasharray,x1:0,y1:i,x2:Vt,y2:i,className:"recharts-legend-icon"});if(n.type==="line")return $.createElement("path",{strokeWidth:4,fill:"none",stroke:c,d:"M0,".concat(i,"h").concat(l,`
- A`).concat(s,",").concat(s,",0,1,1,").concat(2*l,",").concat(i,`
- H`).concat(Vt,"M").concat(2*l,",").concat(i,`
- A`).concat(s,",").concat(s,",0,1,1,").concat(l,",").concat(i),className:"recharts-legend-icon"});if(n.type==="rect")return $.createElement("path",{stroke:"none",fill:c,d:"M0,".concat(Vt/8,"h").concat(Vt,"v").concat(Vt*3/4,"h").concat(-Vt,"z"),className:"recharts-legend-icon"});if($.isValidElement(n.legendIcon)){var u=R4({},n);return delete u.legendIcon,$.cloneElement(n.legendIcon,u)}return $.createElement(ay,{fill:c,cx:i,cy:i,size:Vt,sizeType:"diameter",type:n.type})}},{key:"renderItems",value:function(){var n=this,a=this.props,i=a.payload,s=a.iconSize,l=a.layout,c=a.formatter,u=a.inactiveColor,f={x:0,y:0,width:Vt,height:Vt},d={display:l==="horizontal"?"inline-block":"block",marginRight:10},h={display:"inline-block",verticalAlign:"middle",marginRight:4};return i.map(function(p,g){var y=p.formatter||c,b=ee(Ns(Ns({"recharts-legend-item":!0},"legend-item-".concat(g),!0),"inactive",p.inactive));if(p.type==="none")return null;var v=Q(p.value)?null:p.value;yr(!Q(p.value),`The name property is also required when using a function for the dataKey of a chart's cartesian components. Ex: <Bar name="Name of my Data"/>`);var m=p.inactive?u:p.color;return $.createElement("li",Pp({className:b,style:d,key:"legend-item-".concat(g)},en(n.props,p,g)),$.createElement(xp,{width:s,height:s,viewBox:f,style:h},n.renderIcon(p)),$.createElement("span",{className:"recharts-legend-item-text",style:{color:m}},y?y(v,p,g):v))})}},{key:"render",value:function(){var n=this.props,a=n.payload,i=n.layout,s=n.align;if(!a||!a.length)return null;var l={padding:0,margin:0,textAlign:i==="horizontal"?s:"left"};return $.createElement("ul",{className:"recharts-default-legend",style:l},this.renderItems())}}])}(P.PureComponent);Ns(iy,"displayName","Legend");Ns(iy,"defaultProps",{iconSize:14,layout:"horizontal",align:"center",verticalAlign:"middle",inactiveColor:"#ccc"});var G4=wd;function Y4(){this.__data__=new G4,this.size=0}var q4=Y4;function X4(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r}var Q4=X4;function J4(e){return this.__data__.get(e)}var Z4=J4;function eM(e){return this.__data__.has(e)}var tM=eM,rM=wd,nM=Vv,aM=Gv,iM=200;function oM(e,t){var r=this.__data__;if(r instanceof rM){var n=r.__data__;if(!nM||n.length<iM-1)return n.push([e,t]),this.size=++r.size,this;r=this.__data__=new aM(n)}return r.set(e,t),this.size=r.size,this}var sM=oM,lM=wd,cM=q4,uM=Q4,dM=Z4,fM=tM,hM=sM;function fo(e){var t=this.__data__=new lM(e);this.size=t.size}fo.prototype.clear=cM;fo.prototype.delete=uM;fo.prototype.get=dM;fo.prototype.has=fM;fo.prototype.set=hM;var VS=fo,pM="__lodash_hash_undefined__";function mM(e){return this.__data__.set(e,pM),this}var vM=mM;function yM(e){return this.__data__.has(e)}var gM=yM,xM=Gv,bM=vM,jM=gM;function iu(e){var t=-1,r=e==null?0:e.length;for(this.__data__=new xM;++t<r;)this.add(e[t])}iu.prototype.add=iu.prototype.push=bM;iu.prototype.has=jM;var GS=iu;function wM(e,t){for(var r=-1,n=e==null?0:e.length;++r<n;)if(t(e[r],r,e))return!0;return!1}var YS=wM;function SM(e,t){return e.has(t)}var qS=SM,_M=GS,kM=YS,OM=qS,NM=1,PM=2;function AM(e,t,r,n,a,i){var s=r&NM,l=e.length,c=t.length;if(l!=c&&!(s&&c>l))return!1;var u=i.get(e),f=i.get(t);if(u&&f)return u==t&&f==e;var d=-1,h=!0,p=r&PM?new _M:void 0;for(i.set(e,t),i.set(t,e);++d<l;){var g=e[d],y=t[d];if(n)var b=s?n(y,g,d,t,e,i):n(g,y,d,e,t,i);if(b!==void 0){if(b)continue;h=!1;break}if(p){if(!kM(t,function(v,m){if(!OM(p,m)&&(g===v||a(g,v,r,n,i)))return p.push(m)})){h=!1;break}}else if(!(g===y||a(g,y,r,n,i))){h=!1;break}}return i.delete(e),i.delete(t),h}var XS=AM,CM=Mr,EM=CM.Uint8Array,$M=EM;function TM(e){var t=-1,r=Array(e.size);return e.forEach(function(n,a){r[++t]=[a,n]}),r}var MM=TM;function IM(e){var t=-1,r=Array(e.size);return e.forEach(function(n){r[++t]=n}),r}var oy=IM,K0=ml,V0=$M,LM=Kv,DM=XS,RM=MM,BM=oy,FM=1,zM=2,WM="[object Boolean]",UM="[object Date]",HM="[object Error]",KM="[object Map]",VM="[object Number]",GM="[object RegExp]",YM="[object Set]",qM="[object String]",XM="[object Symbol]",QM="[object ArrayBuffer]",JM="[object DataView]",G0=K0?K0.prototype:void 0,Vf=G0?G0.valueOf:void 0;function ZM(e,t,r,n,a,i,s){switch(r){case JM:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case QM:return!(e.byteLength!=t.byteLength||!i(new V0(e),new V0(t)));case WM:case UM:case VM:return LM(+e,+t);case HM:return e.name==t.name&&e.message==t.message;case GM:case qM:return e==t+"";case KM:var l=RM;case YM:var c=n&FM;if(l||(l=BM),e.size!=t.size&&!c)return!1;var u=s.get(e);if(u)return u==t;n|=zM,s.set(e,t);var f=DM(l(e),l(t),n,a,i,s);return s.delete(e),f;case XM:if(Vf)return Vf.call(e)==Vf.call(t)}return!1}var eI=ZM;function tI(e,t){for(var r=-1,n=t.length,a=e.length;++r<n;)e[a+r]=t[r];return e}var QS=tI,rI=QS,nI=$t;function aI(e,t,r){var n=t(e);return nI(e)?n:rI(n,r(e))}var iI=aI;function oI(e,t){for(var r=-1,n=e==null?0:e.length,a=0,i=[];++r<n;){var s=e[r];t(s,r,e)&&(i[a++]=s)}return i}var sI=oI;function lI(){return[]}var cI=lI,uI=sI,dI=cI,fI=Object.prototype,hI=fI.propertyIsEnumerable,Y0=Object.getOwnPropertySymbols,pI=Y0?function(e){return e==null?[]:(e=Object(e),uI(Y0(e),function(t){return hI.call(e,t)}))}:dI,mI=pI;function vI(e,t){for(var r=-1,n=Array(e);++r<e;)n[r]=t(r);return n}var yI=vI,gI=on,xI=sn,bI="[object Arguments]";function jI(e){return xI(e)&&gI(e)==bI}var wI=jI,q0=wI,SI=sn,JS=Object.prototype,_I=JS.hasOwnProperty,kI=JS.propertyIsEnumerable,OI=q0(function(){return arguments}())?q0:function(e){return SI(e)&&_I.call(e,"callee")&&!kI.call(e,"callee")},sy=OI,ou={exports:{}};function NI(){return!1}var PI=NI;ou.exports;(function(e,t){var r=Mr,n=PI,a=t&&!t.nodeType&&t,i=a&&!0&&e&&!e.nodeType&&e,s=i&&i.exports===a,l=s?r.Buffer:void 0,c=l?l.isBuffer:void 0,u=c||n;e.exports=u})(ou,ou.exports);var ZS=ou.exports,AI=9007199254740991,CI=/^(?:0|[1-9]\d*)$/;function EI(e,t){var r=typeof e;return t=t??AI,!!t&&(r=="number"||r!="symbol"&&CI.test(e))&&e>-1&&e%1==0&&e<t}var ly=EI,$I=9007199254740991;function TI(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=$I}var cy=TI,MI=on,II=cy,LI=sn,DI="[object Arguments]",RI="[object Array]",BI="[object Boolean]",FI="[object Date]",zI="[object Error]",WI="[object Function]",UI="[object Map]",HI="[object Number]",KI="[object Object]",VI="[object RegExp]",GI="[object Set]",YI="[object String]",qI="[object WeakMap]",XI="[object ArrayBuffer]",QI="[object DataView]",JI="[object Float32Array]",ZI="[object Float64Array]",eL="[object Int8Array]",tL="[object Int16Array]",rL="[object Int32Array]",nL="[object Uint8Array]",aL="[object Uint8ClampedArray]",iL="[object Uint16Array]",oL="[object Uint32Array]",Se={};Se[JI]=Se[ZI]=Se[eL]=Se[tL]=Se[rL]=Se[nL]=Se[aL]=Se[iL]=Se[oL]=!0;Se[DI]=Se[RI]=Se[XI]=Se[BI]=Se[QI]=Se[FI]=Se[zI]=Se[WI]=Se[UI]=Se[HI]=Se[KI]=Se[VI]=Se[GI]=Se[YI]=Se[qI]=!1;function sL(e){return LI(e)&&II(e.length)&&!!Se[MI(e)]}var lL=sL;function cL(e){return function(t){return e(t)}}var e_=cL,su={exports:{}};su.exports;(function(e,t){var r=lS,n=t&&!t.nodeType&&t,a=n&&!0&&e&&!e.nodeType&&e,i=a&&a.exports===n,s=i&&r.process,l=function(){try{var c=a&&a.require&&a.require("util").types;return c||s&&s.binding&&s.binding("util")}catch{}}();e.exports=l})(su,su.exports);var uL=su.exports,dL=lL,fL=e_,X0=uL,Q0=X0&&X0.isTypedArray,hL=Q0?fL(Q0):dL,t_=hL,pL=yI,mL=sy,vL=$t,yL=ZS,gL=ly,xL=t_,bL=Object.prototype,jL=bL.hasOwnProperty;function wL(e,t){var r=vL(e),n=!r&&mL(e),a=!r&&!n&&yL(e),i=!r&&!n&&!a&&xL(e),s=r||n||a||i,l=s?pL(e.length,String):[],c=l.length;for(var u in e)(t||jL.call(e,u))&&!(s&&(u=="length"||a&&(u=="offset"||u=="parent")||i&&(u=="buffer"||u=="byteLength"||u=="byteOffset")||gL(u,c)))&&l.push(u);return l}var SL=wL,_L=Object.prototype;function kL(e){var t=e&&e.constructor,r=typeof t=="function"&&t.prototype||_L;return e===r}var OL=kL;function NL(e,t){return function(r){return e(t(r))}}var r_=NL,PL=r_,AL=PL(Object.keys,Object),CL=AL,EL=OL,$L=CL,TL=Object.prototype,ML=TL.hasOwnProperty;function IL(e){if(!EL(e))return $L(e);var t=[];for(var r in Object(e))ML.call(e,r)&&r!="constructor"&&t.push(r);return t}var LL=IL,DL=Hv,RL=cy;function BL(e){return e!=null&&RL(e.length)&&!DL(e)}var vl=BL,FL=SL,zL=LL,WL=vl;function UL(e){return WL(e)?FL(e):zL(e)}var Bd=UL,HL=iI,KL=mI,VL=Bd;function GL(e){return HL(e,VL,KL)}var YL=GL,J0=YL,qL=1,XL=Object.prototype,QL=XL.hasOwnProperty;function JL(e,t,r,n,a,i){var s=r&qL,l=J0(e),c=l.length,u=J0(t),f=u.length;if(c!=f&&!s)return!1;for(var d=c;d--;){var h=l[d];if(!(s?h in t:QL.call(t,h)))return!1}var p=i.get(e),g=i.get(t);if(p&&g)return p==t&&g==e;var y=!0;i.set(e,t),i.set(t,e);for(var b=s;++d<c;){h=l[d];var v=e[h],m=t[h];if(n)var x=s?n(m,v,h,t,e,i):n(v,m,h,e,t,i);if(!(x===void 0?v===m||a(v,m,r,n,i):x)){y=!1;break}b||(b=h=="constructor")}if(y&&!b){var S=e.constructor,j=t.constructor;S!=j&&"constructor"in e&&"constructor"in t&&!(typeof S=="function"&&S instanceof S&&typeof j=="function"&&j instanceof j)&&(y=!1)}return i.delete(e),i.delete(t),y}var ZL=JL,e6=Ea,t6=Mr,r6=e6(t6,"DataView"),n6=r6,a6=Ea,i6=Mr,o6=a6(i6,"Promise"),s6=o6,l6=Ea,c6=Mr,u6=l6(c6,"Set"),n_=u6,d6=Ea,f6=Mr,h6=d6(f6,"WeakMap"),p6=h6,Cp=n6,Ep=Vv,$p=s6,Tp=n_,Mp=p6,a_=on,ho=uS,Z0="[object Map]",m6="[object Object]",ex="[object Promise]",tx="[object Set]",rx="[object WeakMap]",nx="[object DataView]",v6=ho(Cp),y6=ho(Ep),g6=ho($p),x6=ho(Tp),b6=ho(Mp),ea=a_;(Cp&&ea(new Cp(new ArrayBuffer(1)))!=nx||Ep&&ea(new Ep)!=Z0||$p&&ea($p.resolve())!=ex||Tp&&ea(new Tp)!=tx||Mp&&ea(new Mp)!=rx)&&(ea=function(e){var t=a_(e),r=t==m6?e.constructor:void 0,n=r?ho(r):"";if(n)switch(n){case v6:return nx;case y6:return Z0;case g6:return ex;case x6:return tx;case b6:return rx}return t});var j6=ea,Gf=VS,w6=XS,S6=eI,_6=ZL,ax=j6,ix=$t,ox=ZS,k6=t_,O6=1,sx="[object Arguments]",lx="[object Array]",Vl="[object Object]",N6=Object.prototype,cx=N6.hasOwnProperty;function P6(e,t,r,n,a,i){var s=ix(e),l=ix(t),c=s?lx:ax(e),u=l?lx:ax(t);c=c==sx?Vl:c,u=u==sx?Vl:u;var f=c==Vl,d=u==Vl,h=c==u;if(h&&ox(e)){if(!ox(t))return!1;s=!0,f=!1}if(h&&!f)return i||(i=new Gf),s||k6(e)?w6(e,t,r,n,a,i):S6(e,t,c,r,n,a,i);if(!(r&O6)){var p=f&&cx.call(e,"__wrapped__"),g=d&&cx.call(t,"__wrapped__");if(p||g){var y=p?e.value():e,b=g?t.value():t;return i||(i=new Gf),a(y,b,r,n,i)}}return h?(i||(i=new Gf),_6(e,t,r,n,a,i)):!1}var A6=P6,C6=A6,ux=sn;function i_(e,t,r,n,a){return e===t?!0:e==null||t==null||!ux(e)&&!ux(t)?e!==e&&t!==t:C6(e,t,r,n,i_,a)}var uy=i_,E6=VS,$6=uy,T6=1,M6=2;function I6(e,t,r,n){var a=r.length,i=a,s=!n;if(e==null)return!i;for(e=Object(e);a--;){var l=r[a];if(s&&l[2]?l[1]!==e[l[0]]:!(l[0]in e))return!1}for(;++a<i;){l=r[a];var c=l[0],u=e[c],f=l[1];if(s&&l[2]){if(u===void 0&&!(c in e))return!1}else{var d=new E6;if(n)var h=n(u,f,c,e,t,d);if(!(h===void 0?$6(f,u,T6|M6,n,d):h))return!1}}return!0}var L6=I6,D6=zn;function R6(e){return e===e&&!D6(e)}var o_=R6,B6=o_,F6=Bd;function z6(e){for(var t=F6(e),r=t.length;r--;){var n=t[r],a=e[n];t[r]=[n,a,B6(a)]}return t}var W6=z6;function U6(e,t){return function(r){return r==null?!1:r[e]===t&&(t!==void 0||e in Object(r))}}var s_=U6,H6=L6,K6=W6,V6=s_;function G6(e){var t=K6(e);return t.length==1&&t[0][2]?V6(t[0][0],t[0][1]):function(r){return r===e||H6(r,e,t)}}var Y6=G6;function q6(e,t){return e!=null&&t in Object(e)}var X6=q6,Q6=mS,J6=sy,Z6=$t,e8=ly,t8=cy,r8=_d;function n8(e,t,r){t=Q6(t,e);for(var n=-1,a=t.length,i=!1;++n<a;){var s=r8(t[n]);if(!(i=e!=null&&r(e,s)))break;e=e[s]}return i||++n!=a?i:(a=e==null?0:e.length,!!a&&t8(a)&&e8(s,a)&&(Z6(e)||J6(e)))}var a8=n8,i8=X6,o8=a8;function s8(e,t){return e!=null&&o8(e,t,i8)}var l8=s8,c8=uy,u8=vS,d8=l8,f8=Uv,h8=o_,p8=s_,m8=_d,v8=1,y8=2;function g8(e,t){return f8(e)&&h8(t)?p8(m8(e),t):function(r){var n=u8(r,e);return n===void 0&&n===t?d8(r,e):c8(t,n,v8|y8)}}var x8=g8;function b8(e){return e}var po=b8;function j8(e){return function(t){return t==null?void 0:t[e]}}var w8=j8,S8=Xv;function _8(e){return function(t){return S8(t,e)}}var k8=_8,O8=w8,N8=k8,P8=Uv,A8=_d;function C8(e){return P8(e)?O8(A8(e)):N8(e)}var E8=C8,$8=Y6,T8=x8,M8=po,I8=$t,L8=E8;function D8(e){return typeof e=="function"?e:e==null?M8:typeof e=="object"?I8(e)?T8(e[0],e[1]):$8(e):L8(e)}var Ir=D8;function R8(e,t,r,n){for(var a=e.length,i=r+(n?1:-1);n?i--:++i<a;)if(t(e[i],i,e))return i;return-1}var l_=R8;function B8(e){return e!==e}var F8=B8;function z8(e,t,r){for(var n=r-1,a=e.length;++n<a;)if(e[n]===t)return n;return-1}var W8=z8,U8=l_,H8=F8,K8=W8;function V8(e,t,r){return t===t?K8(e,t,r):U8(e,H8,r)}var G8=V8,Y8=G8;function q8(e,t){var r=e==null?0:e.length;return!!r&&Y8(e,t,0)>-1}var X8=q8;function Q8(e,t,r){for(var n=-1,a=e==null?0:e.length;++n<a;)if(r(t,e[n]))return!0;return!1}var J8=Q8;function Z8(){}var eD=Z8,Yf=n_,tD=eD,rD=oy,nD=1/0,aD=Yf&&1/rD(new Yf([,-0]))[1]==nD?function(e){return new Yf(e)}:tD,iD=aD,oD=GS,sD=X8,lD=J8,cD=qS,uD=iD,dD=oy,fD=200;function hD(e,t,r){var n=-1,a=sD,i=e.length,s=!0,l=[],c=l;if(r)s=!1,a=lD;else if(i>=fD){var u=t?null:uD(e);if(u)return dD(u);s=!1,a=cD,c=new oD}else c=t?[]:l;e:for(;++n<i;){var f=e[n],d=t?t(f):f;if(f=r||f!==0?f:0,s&&d===d){for(var h=c.length;h--;)if(c[h]===d)continue e;t&&c.push(d),l.push(f)}else a(c,d,r)||(c!==l&&c.push(d),l.push(f))}return l}var pD=hD,mD=Ir,vD=pD;function yD(e,t){return e&&e.length?vD(e,mD(t)):[]}var gD=yD;const dx=de(gD);function c_(e,t,r){return t===!0?dx(e,r):Q(t)?dx(e,t):e}function Ai(e){"@babel/helpers - typeof";return Ai=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Ai(e)}var xD=["ref"];function fx(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function Dr(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?fx(Object(r),!0).forEach(function(n){Fd(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):fx(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function bD(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function hx(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,d_(n.key),n)}}function jD(e,t,r){return t&&hx(e.prototype,t),r&&hx(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function wD(e,t,r){return t=lu(t),SD(e,u_()?Reflect.construct(t,r||[],lu(e).constructor):t.apply(e,r))}function SD(e,t){if(t&&(Ai(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return _D(e)}function _D(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function u_(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(u_=function(){return!!e})()}function lu(e){return lu=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},lu(e)}function kD(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Ip(e,t)}function Ip(e,t){return Ip=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,a){return n.__proto__=a,n},Ip(e,t)}function Fd(e,t,r){return t=d_(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function d_(e){var t=OD(e,"string");return Ai(t)=="symbol"?t:t+""}function OD(e,t){if(Ai(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(Ai(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}function ND(e,t){if(e==null)return{};var r=PD(e,t),n,a;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(a=0;a<i.length;a++)n=i[a],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function PD(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function AD(e){return e.value}function CD(e,t){if($.isValidElement(e))return $.cloneElement(e,t);if(typeof e=="function")return $.createElement(e,t);t.ref;var r=ND(t,xD);return $.createElement(iy,r)}var px=1,vi=function(e){function t(){var r;bD(this,t);for(var n=arguments.length,a=new Array(n),i=0;i<n;i++)a[i]=arguments[i];return r=wD(this,t,[].concat(a)),Fd(r,"lastBoundingBox",{width:-1,height:-1}),r}return kD(t,e),jD(t,[{key:"componentDidMount",value:function(){this.updateBBox()}},{key:"componentDidUpdate",value:function(){this.updateBBox()}},{key:"getBBox",value:function(){if(this.wrapperNode&&this.wrapperNode.getBoundingClientRect){var n=this.wrapperNode.getBoundingClientRect();return n.height=this.wrapperNode.offsetHeight,n.width=this.wrapperNode.offsetWidth,n}return null}},{key:"updateBBox",value:function(){var n=this.props.onBBoxUpdate,a=this.getBBox();a?(Math.abs(a.width-this.lastBoundingBox.width)>px||Math.abs(a.height-this.lastBoundingBox.height)>px)&&(this.lastBoundingBox.width=a.width,this.lastBoundingBox.height=a.height,n&&n(a)):(this.lastBoundingBox.width!==-1||this.lastBoundingBox.height!==-1)&&(this.lastBoundingBox.width=-1,this.lastBoundingBox.height=-1,n&&n(null))}},{key:"getBBoxSnapshot",value:function(){return this.lastBoundingBox.width>=0&&this.lastBoundingBox.height>=0?Dr({},this.lastBoundingBox):{width:0,height:0}}},{key:"getDefaultPosition",value:function(n){var a=this.props,i=a.layout,s=a.align,l=a.verticalAlign,c=a.margin,u=a.chartWidth,f=a.chartHeight,d,h;if(!n||(n.left===void 0||n.left===null)&&(n.right===void 0||n.right===null))if(s==="center"&&i==="vertical"){var p=this.getBBoxSnapshot();d={left:((u||0)-p.width)/2}}else d=s==="right"?{right:c&&c.right||0}:{left:c&&c.left||0};if(!n||(n.top===void 0||n.top===null)&&(n.bottom===void 0||n.bottom===null))if(l==="middle"){var g=this.getBBoxSnapshot();h={top:((f||0)-g.height)/2}}else h=l==="bottom"?{bottom:c&&c.bottom||0}:{top:c&&c.top||0};return Dr(Dr({},d),h)}},{key:"render",value:function(){var n=this,a=this.props,i=a.content,s=a.width,l=a.height,c=a.wrapperStyle,u=a.payloadUniqBy,f=a.payload,d=Dr(Dr({position:"absolute",width:s||"auto",height:l||"auto"},this.getDefaultPosition(c)),c);return $.createElement("div",{className:"recharts-legend-wrapper",style:d,ref:function(p){n.wrapperNode=p}},CD(i,Dr(Dr({},this.props),{},{payload:c_(f,u,AD)})))}}],[{key:"getWithHeight",value:function(n,a){var i=Dr(Dr({},this.defaultProps),n.props),s=i.layout;return s==="vertical"&&U(n.props.height)?{height:n.props.height}:s==="horizontal"?{width:n.props.width||a}:null}}])}(P.PureComponent);Fd(vi,"displayName","Legend");Fd(vi,"defaultProps",{iconSize:14,layout:"horizontal",align:"center",verticalAlign:"bottom"});var mx=ml,ED=sy,$D=$t,vx=mx?mx.isConcatSpreadable:void 0;function TD(e){return $D(e)||ED(e)||!!(vx&&e&&e[vx])}var MD=TD,ID=QS,LD=MD;function f_(e,t,r,n,a){var i=-1,s=e.length;for(r||(r=LD),a||(a=[]);++i<s;){var l=e[i];t>0&&r(l)?t>1?f_(l,t-1,r,n,a):ID(a,l):n||(a[a.length]=l)}return a}var h_=f_;function DD(e){return function(t,r,n){for(var a=-1,i=Object(t),s=n(t),l=s.length;l--;){var c=s[e?l:++a];if(r(i[c],c,i)===!1)break}return t}}var RD=DD,BD=RD,FD=BD(),zD=FD,WD=zD,UD=Bd;function HD(e,t){return e&&WD(e,t,UD)}var p_=HD,KD=vl;function VD(e,t){return function(r,n){if(r==null)return r;if(!KD(r))return e(r,n);for(var a=r.length,i=t?a:-1,s=Object(r);(t?i--:++i<a)&&n(s[i],i,s)!==!1;);return r}}var GD=VD,YD=p_,qD=GD,XD=qD(YD),dy=XD,QD=dy,JD=vl;function ZD(e,t){var r=-1,n=JD(e)?Array(e.length):[];return QD(e,function(a,i,s){n[++r]=t(a,i,s)}),n}var m_=ZD;function eR(e,t){var r=e.length;for(e.sort(t);r--;)e[r]=e[r].value;return e}var tR=eR,yx=ao;function rR(e,t){if(e!==t){var r=e!==void 0,n=e===null,a=e===e,i=yx(e),s=t!==void 0,l=t===null,c=t===t,u=yx(t);if(!l&&!u&&!i&&e>t||i&&s&&c&&!l&&!u||n&&s&&c||!r&&c||!a)return 1;if(!n&&!i&&!u&&e<t||u&&r&&a&&!n&&!i||l&&r&&a||!s&&a||!c)return-1}return 0}var nR=rR,aR=nR;function iR(e,t,r){for(var n=-1,a=e.criteria,i=t.criteria,s=a.length,l=r.length;++n<s;){var c=aR(a[n],i[n]);if(c){if(n>=l)return c;var u=r[n];return c*(u=="desc"?-1:1)}}return e.index-t.index}var oR=iR,qf=qv,sR=Xv,lR=Ir,cR=m_,uR=tR,dR=e_,fR=oR,hR=po,pR=$t;function mR(e,t,r){t.length?t=qf(t,function(i){return pR(i)?function(s){return sR(s,i.length===1?i[0]:i)}:i}):t=[hR];var n=-1;t=qf(t,dR(lR));var a=cR(e,function(i,s,l){var c=qf(t,function(u){return u(i)});return{criteria:c,index:++n,value:i}});return uR(a,function(i,s){return fR(i,s,r)})}var vR=mR;function yR(e,t,r){switch(r.length){case 0:return e.call(t);case 1:return e.call(t,r[0]);case 2:return e.call(t,r[0],r[1]);case 3:return e.call(t,r[0],r[1],r[2])}return e.apply(t,r)}var gR=yR,xR=gR,gx=Math.max;function bR(e,t,r){return t=gx(t===void 0?e.length-1:t,0),function(){for(var n=arguments,a=-1,i=gx(n.length-t,0),s=Array(i);++a<i;)s[a]=n[t+a];a=-1;for(var l=Array(t+1);++a<t;)l[a]=n[a];return l[t]=r(s),xR(e,this,l)}}var jR=bR;function wR(e){return function(){return e}}var SR=wR,_R=Ea,kR=function(){try{var e=_R(Object,"defineProperty");return e({},"",{}),e}catch{}}(),v_=kR,OR=SR,xx=v_,NR=po,PR=xx?function(e,t){return xx(e,"toString",{configurable:!0,enumerable:!1,value:OR(t),writable:!0})}:NR,AR=PR,CR=800,ER=16,$R=Date.now;function TR(e){var t=0,r=0;return function(){var n=$R(),a=ER-(n-r);if(r=n,a>0){if(++t>=CR)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}var MR=TR,IR=AR,LR=MR,DR=LR(IR),RR=DR,BR=po,FR=jR,zR=RR;function WR(e,t){return zR(FR(e,t,BR),e+"")}var UR=WR,HR=Kv,KR=vl,VR=ly,GR=zn;function YR(e,t,r){if(!GR(r))return!1;var n=typeof t;return(n=="number"?KR(r)&&VR(t,r.length):n=="string"&&t in r)?HR(r[t],e):!1}var zd=YR,qR=h_,XR=vR,QR=UR,bx=zd,JR=QR(function(e,t){if(e==null)return[];var r=t.length;return r>1&&bx(e,t[0],t[1])?t=[]:r>2&&bx(t[0],t[1],t[2])&&(t=[t[0]]),XR(e,qR(t,1),[])}),ZR=JR;const fy=de(ZR);function Ps(e){"@babel/helpers - typeof";return Ps=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Ps(e)}function Lp(){return Lp=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},Lp.apply(this,arguments)}function eB(e,t){return aB(e)||nB(e,t)||rB(e,t)||tB()}function tB(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
-In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function rB(e,t){if(e){if(typeof e=="string")return jx(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return jx(e,t)}}function jx(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function nB(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,a,i,s,l=[],c=!0,u=!1;try{if(i=(r=r.call(e)).next,t!==0)for(;!(c=(n=i.call(r)).done)&&(l.push(n.value),l.length!==t);c=!0);}catch(f){u=!0,a=f}finally{try{if(!c&&r.return!=null&&(s=r.return(),Object(s)!==s))return}finally{if(u)throw a}}return l}}function aB(e){if(Array.isArray(e))return e}function wx(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function Xf(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?wx(Object(r),!0).forEach(function(n){iB(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):wx(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function iB(e,t,r){return t=oB(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function oB(e){var t=sB(e,"string");return Ps(t)=="symbol"?t:t+""}function sB(e,t){if(Ps(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(Ps(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function lB(e){return Array.isArray(e)&&qe(e[0])&&qe(e[1])?e.join(" ~ "):e}var cB=function(t){var r=t.separator,n=r===void 0?" : ":r,a=t.contentStyle,i=a===void 0?{}:a,s=t.itemStyle,l=s===void 0?{}:s,c=t.labelStyle,u=c===void 0?{}:c,f=t.payload,d=t.formatter,h=t.itemSorter,p=t.wrapperClassName,g=t.labelClassName,y=t.label,b=t.labelFormatter,v=t.accessibilityLayer,m=v===void 0?!1:v,x=function(){if(f&&f.length){var T={padding:0,margin:0},D=(h?fy(f,h):f).map(function(A,L){if(A.type==="none")return null;var C=Xf({display:"block",paddingTop:4,paddingBottom:4,color:A.color||"#000"},l),M=A.formatter||d||lB,I=A.value,R=A.name,F=I,K=R;if(M&&F!=null&&K!=null){var z=M(I,R,A,L,f);if(Array.isArray(z)){var q=eB(z,2);F=q[0],K=q[1]}else F=z}return $.createElement("li",{className:"recharts-tooltip-item",key:"tooltip-item-".concat(L),style:C},qe(K)?$.createElement("span",{className:"recharts-tooltip-item-name"},K):null,qe(K)?$.createElement("span",{className:"recharts-tooltip-item-separator"},n):null,$.createElement("span",{className:"recharts-tooltip-item-value"},F),$.createElement("span",{className:"recharts-tooltip-item-unit"},A.unit||""))});return $.createElement("ul",{className:"recharts-tooltip-item-list",style:T},D)}return null},S=Xf({margin:0,padding:10,backgroundColor:"#fff",border:"1px solid #ccc",whiteSpace:"nowrap"},i),j=Xf({margin:0},u),w=!te(y),_=w?y:"",O=ee("recharts-default-tooltip",p),N=ee("recharts-tooltip-label",g);w&&b&&f!==void 0&&f!==null&&(_=b(y,f));var k=m?{role:"status","aria-live":"assertive"}:{};return $.createElement("div",Lp({className:O,style:S},k),$.createElement("p",{className:N,style:j},$.isValidElement(_)?_:"".concat(_)),x())};function As(e){"@babel/helpers - typeof";return As=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},As(e)}function Gl(e,t,r){return t=uB(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function uB(e){var t=dB(e,"string");return As(t)=="symbol"?t:t+""}function dB(e,t){if(As(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(As(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var Po="recharts-tooltip-wrapper",fB={visibility:"hidden"};function hB(e){var t=e.coordinate,r=e.translateX,n=e.translateY;return ee(Po,Gl(Gl(Gl(Gl({},"".concat(Po,"-right"),U(r)&&t&&U(t.x)&&r>=t.x),"".concat(Po,"-left"),U(r)&&t&&U(t.x)&&r<t.x),"".concat(Po,"-bottom"),U(n)&&t&&U(t.y)&&n>=t.y),"".concat(Po,"-top"),U(n)&&t&&U(t.y)&&n<t.y))}function Sx(e){var t=e.allowEscapeViewBox,r=e.coordinate,n=e.key,a=e.offsetTopLeft,i=e.position,s=e.reverseDirection,l=e.tooltipDimension,c=e.viewBox,u=e.viewBoxDimension;if(i&&U(i[n]))return i[n];var f=r[n]-l-a,d=r[n]+a;if(t[n])return s[n]?f:d;if(s[n]){var h=f,p=c[n];return h<p?Math.max(d,c[n]):Math.max(f,c[n])}var g=d+l,y=c[n]+u;return g>y?Math.max(f,c[n]):Math.max(d,c[n])}function pB(e){var t=e.translateX,r=e.translateY,n=e.useTranslate3d;return{transform:n?"translate3d(".concat(t,"px, ").concat(r,"px, 0)"):"translate(".concat(t,"px, ").concat(r,"px)")}}function mB(e){var t=e.allowEscapeViewBox,r=e.coordinate,n=e.offsetTopLeft,a=e.position,i=e.reverseDirection,s=e.tooltipBox,l=e.useTranslate3d,c=e.viewBox,u,f,d;return s.height>0&&s.width>0&&r?(f=Sx({allowEscapeViewBox:t,coordinate:r,key:"x",offsetTopLeft:n,position:a,reverseDirection:i,tooltipDimension:s.width,viewBox:c,viewBoxDimension:c.width}),d=Sx({allowEscapeViewBox:t,coordinate:r,key:"y",offsetTopLeft:n,position:a,reverseDirection:i,tooltipDimension:s.height,viewBox:c,viewBoxDimension:c.height}),u=pB({translateX:f,translateY:d,useTranslate3d:l})):u=fB,{cssProperties:u,cssClasses:hB({translateX:f,translateY:d,coordinate:r})}}function Ci(e){"@babel/helpers - typeof";return Ci=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Ci(e)}function _x(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function kx(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?_x(Object(r),!0).forEach(function(n){Rp(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):_x(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function vB(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function yB(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,g_(n.key),n)}}function gB(e,t,r){return t&&yB(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function xB(e,t,r){return t=cu(t),bB(e,y_()?Reflect.construct(t,r||[],cu(e).constructor):t.apply(e,r))}function bB(e,t){if(t&&(Ci(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return jB(e)}function jB(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function y_(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(y_=function(){return!!e})()}function cu(e){return cu=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},cu(e)}function wB(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Dp(e,t)}function Dp(e,t){return Dp=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,a){return n.__proto__=a,n},Dp(e,t)}function Rp(e,t,r){return t=g_(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function g_(e){var t=SB(e,"string");return Ci(t)=="symbol"?t:t+""}function SB(e,t){if(Ci(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(Ci(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}var Ox=1,_B=function(e){function t(){var r;vB(this,t);for(var n=arguments.length,a=new Array(n),i=0;i<n;i++)a[i]=arguments[i];return r=xB(this,t,[].concat(a)),Rp(r,"state",{dismissed:!1,dismissedAtCoordinate:{x:0,y:0},lastBoundingBox:{width:-1,height:-1}}),Rp(r,"handleKeyDown",function(s){if(s.key==="Escape"){var l,c,u,f;r.setState({dismissed:!0,dismissedAtCoordinate:{x:(l=(c=r.props.coordinate)===null||c===void 0?void 0:c.x)!==null&&l!==void 0?l:0,y:(u=(f=r.props.coordinate)===null||f===void 0?void 0:f.y)!==null&&u!==void 0?u:0}})}}),r}return wB(t,e),gB(t,[{key:"updateBBox",value:function(){if(this.wrapperNode&&this.wrapperNode.getBoundingClientRect){var n=this.wrapperNode.getBoundingClientRect();(Math.abs(n.width-this.state.lastBoundingBox.width)>Ox||Math.abs(n.height-this.state.lastBoundingBox.height)>Ox)&&this.setState({lastBoundingBox:{width:n.width,height:n.height}})}else(this.state.lastBoundingBox.width!==-1||this.state.lastBoundingBox.height!==-1)&&this.setState({lastBoundingBox:{width:-1,height:-1}})}},{key:"componentDidMount",value:function(){document.addEventListener("keydown",this.handleKeyDown),this.updateBBox()}},{key:"componentWillUnmount",value:function(){document.removeEventListener("keydown",this.handleKeyDown)}},{key:"componentDidUpdate",value:function(){var n,a;this.props.active&&this.updateBBox(),this.state.dismissed&&(((n=this.props.coordinate)===null||n===void 0?void 0:n.x)!==this.state.dismissedAtCoordinate.x||((a=this.props.coordinate)===null||a===void 0?void 0:a.y)!==this.state.dismissedAtCoordinate.y)&&(this.state.dismissed=!1)}},{key:"render",value:function(){var n=this,a=this.props,i=a.active,s=a.allowEscapeViewBox,l=a.animationDuration,c=a.animationEasing,u=a.children,f=a.coordinate,d=a.hasPayload,h=a.isAnimationActive,p=a.offset,g=a.position,y=a.reverseDirection,b=a.useTranslate3d,v=a.viewBox,m=a.wrapperStyle,x=mB({allowEscapeViewBox:s,coordinate:f,offsetTopLeft:p,position:g,reverseDirection:y,tooltipBox:this.state.lastBoundingBox,useTranslate3d:b,viewBox:v}),S=x.cssClasses,j=x.cssProperties,w=kx(kx({transition:h&&i?"transform ".concat(l,"ms ").concat(c):void 0},j),{},{pointerEvents:"none",visibility:!this.state.dismissed&&i&&d?"visible":"hidden",position:"absolute",top:0,left:0},m);return $.createElement("div",{tabIndex:-1,className:S,style:w,ref:function(O){n.wrapperNode=O}},u)}}])}(P.PureComponent),kB=function(){return!(typeof window<"u"&&window.document&&window.document.createElement&&window.setTimeout)},Wn={isSsr:kB()};function Ei(e){"@babel/helpers - typeof";return Ei=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Ei(e)}function Nx(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function Px(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Nx(Object(r),!0).forEach(function(n){hy(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Nx(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function OB(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function NB(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,b_(n.key),n)}}function PB(e,t,r){return t&&NB(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function AB(e,t,r){return t=uu(t),CB(e,x_()?Reflect.construct(t,r||[],uu(e).constructor):t.apply(e,r))}function CB(e,t){if(t&&(Ei(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return EB(e)}function EB(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function x_(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(x_=function(){return!!e})()}function uu(e){return uu=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},uu(e)}function $B(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Bp(e,t)}function Bp(e,t){return Bp=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,a){return n.__proto__=a,n},Bp(e,t)}function hy(e,t,r){return t=b_(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function b_(e){var t=TB(e,"string");return Ei(t)=="symbol"?t:t+""}function TB(e,t){if(Ei(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(Ei(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}function MB(e){return e.dataKey}function IB(e,t){return $.isValidElement(e)?$.cloneElement(e,t):typeof e=="function"?$.createElement(e,t):$.createElement(cB,t)}var Ge=function(e){function t(){return OB(this,t),AB(this,t,arguments)}return $B(t,e),PB(t,[{key:"render",value:function(){var n=this,a=this.props,i=a.active,s=a.allowEscapeViewBox,l=a.animationDuration,c=a.animationEasing,u=a.content,f=a.coordinate,d=a.filterNull,h=a.isAnimationActive,p=a.offset,g=a.payload,y=a.payloadUniqBy,b=a.position,v=a.reverseDirection,m=a.useTranslate3d,x=a.viewBox,S=a.wrapperStyle,j=g??[];d&&j.length&&(j=c_(g.filter(function(_){return _.value!=null&&(_.hide!==!0||n.props.includeHidden)}),y,MB));var w=j.length>0;return $.createElement(_B,{allowEscapeViewBox:s,animationDuration:l,animationEasing:c,isAnimationActive:h,active:i,coordinate:f,hasPayload:w,offset:p,position:b,reverseDirection:v,useTranslate3d:m,viewBox:x,wrapperStyle:S},IB(u,Px(Px({},this.props),{},{payload:j})))}}])}(P.PureComponent);hy(Ge,"displayName","Tooltip");hy(Ge,"defaultProps",{accessibilityLayer:!1,allowEscapeViewBox:{x:!1,y:!1},animationDuration:400,animationEasing:"ease",contentStyle:{},coordinate:{x:0,y:0},cursor:!0,cursorStyle:{},filterNull:!0,isAnimationActive:!Wn.isSsr,itemStyle:{},labelStyle:{},offset:10,reverseDirection:{x:!1,y:!1},separator:" : ",trigger:"hover",useTranslate3d:!1,viewBox:{x:0,y:0,height:0,width:0},wrapperStyle:{}});var LB=Mr,DB=function(){return LB.Date.now()},RB=DB,BB=/\s/;function FB(e){for(var t=e.length;t--&&BB.test(e.charAt(t)););return t}var zB=FB,WB=zB,UB=/^\s+/;function HB(e){return e&&e.slice(0,WB(e)+1).replace(UB,"")}var KB=HB,VB=KB,Ax=zn,GB=ao,Cx=NaN,YB=/^[-+]0x[0-9a-f]+$/i,qB=/^0b[01]+$/i,XB=/^0o[0-7]+$/i,QB=parseInt;function JB(e){if(typeof e=="number")return e;if(GB(e))return Cx;if(Ax(e)){var t=typeof e.valueOf=="function"?e.valueOf():e;e=Ax(t)?t+"":t}if(typeof e!="string")return e===0?e:+e;e=VB(e);var r=qB.test(e);return r||XB.test(e)?QB(e.slice(2),r?2:8):YB.test(e)?Cx:+e}var j_=JB,ZB=zn,Qf=RB,Ex=j_,eF="Expected a function",tF=Math.max,rF=Math.min;function nF(e,t,r){var n,a,i,s,l,c,u=0,f=!1,d=!1,h=!0;if(typeof e!="function")throw new TypeError(eF);t=Ex(t)||0,ZB(r)&&(f=!!r.leading,d="maxWait"in r,i=d?tF(Ex(r.maxWait)||0,t):i,h="trailing"in r?!!r.trailing:h);function p(w){var _=n,O=a;return n=a=void 0,u=w,s=e.apply(O,_),s}function g(w){return u=w,l=setTimeout(v,t),f?p(w):s}function y(w){var _=w-c,O=w-u,N=t-_;return d?rF(N,i-O):N}function b(w){var _=w-c,O=w-u;return c===void 0||_>=t||_<0||d&&O>=i}function v(){var w=Qf();if(b(w))return m(w);l=setTimeout(v,y(w))}function m(w){return l=void 0,h&&n?p(w):(n=a=void 0,s)}function x(){l!==void 0&&clearTimeout(l),u=0,n=c=a=l=void 0}function S(){return l===void 0?s:m(Qf())}function j(){var w=Qf(),_=b(w);if(n=arguments,a=this,c=w,_){if(l===void 0)return g(c);if(d)return clearTimeout(l),l=setTimeout(v,t),p(c)}return l===void 0&&(l=setTimeout(v,t)),s}return j.cancel=x,j.flush=S,j}var aF=nF,iF=aF,oF=zn,sF="Expected a function";function lF(e,t,r){var n=!0,a=!0;if(typeof e!="function")throw new TypeError(sF);return oF(r)&&(n="leading"in r?!!r.leading:n,a="trailing"in r?!!r.trailing:a),iF(e,t,{leading:n,maxWait:t,trailing:a})}var cF=lF;const w_=de(cF);function Cs(e){"@babel/helpers - typeof";return Cs=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Cs(e)}function $x(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function Yl(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?$x(Object(r),!0).forEach(function(n){uF(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):$x(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function uF(e,t,r){return t=dF(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function dF(e){var t=fF(e,"string");return Cs(t)=="symbol"?t:t+""}function fF(e,t){if(Cs(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(Cs(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function hF(e,t){return yF(e)||vF(e,t)||mF(e,t)||pF()}function pF(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
-In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function mF(e,t){if(e){if(typeof e=="string")return Tx(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return Tx(e,t)}}function Tx(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function vF(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,a,i,s,l=[],c=!0,u=!1;try{if(i=(r=r.call(e)).next,t!==0)for(;!(c=(n=i.call(r)).done)&&(l.push(n.value),l.length!==t);c=!0);}catch(f){u=!0,a=f}finally{try{if(!c&&r.return!=null&&(s=r.return(),Object(s)!==s))return}finally{if(u)throw a}}return l}}function yF(e){if(Array.isArray(e))return e}var tr=P.forwardRef(function(e,t){var r=e.aspect,n=e.initialDimension,a=n===void 0?{width:-1,height:-1}:n,i=e.width,s=i===void 0?"100%":i,l=e.height,c=l===void 0?"100%":l,u=e.minWidth,f=u===void 0?0:u,d=e.minHeight,h=e.maxHeight,p=e.children,g=e.debounce,y=g===void 0?0:g,b=e.id,v=e.className,m=e.onResize,x=e.style,S=x===void 0?{}:x,j=P.useRef(null),w=P.useRef();w.current=m,P.useImperativeHandle(t,function(){return Object.defineProperty(j.current,"current",{get:function(){return console.warn("The usage of ref.current.current is deprecated and will no longer be supported."),j.current},configurable:!0})});var _=P.useState({containerWidth:a.width,containerHeight:a.height}),O=hF(_,2),N=O[0],k=O[1],E=P.useCallback(function(D,A){k(function(L){var C=Math.round(D),M=Math.round(A);return L.containerWidth===C&&L.containerHeight===M?L:{containerWidth:C,containerHeight:M}})},[]);P.useEffect(function(){var D=function(R){var F,K=R[0].contentRect,z=K.width,q=K.height;E(z,q),(F=w.current)===null||F===void 0||F.call(w,z,q)};y>0&&(D=w_(D,y,{trailing:!0,leading:!1}));var A=new ResizeObserver(D),L=j.current.getBoundingClientRect(),C=L.width,M=L.height;return E(C,M),A.observe(j.current),function(){A.disconnect()}},[E,y]);var T=P.useMemo(function(){var D=N.containerWidth,A=N.containerHeight;if(D<0||A<0)return null;yr(oa(s)||oa(c),`The width(%s) and height(%s) are both fixed numbers,
- maybe you don't need to use a ResponsiveContainer.`,s,c),yr(!r||r>0,"The aspect(%s) must be greater than zero.",r);var L=oa(s)?D:s,C=oa(c)?A:c;r&&r>0&&(L?C=L/r:C&&(L=C*r),h&&C>h&&(C=h)),yr(L>0||C>0,`The width(%s) and height(%s) of chart should be greater than 0,
- please check the style of container, or the props width(%s) and height(%s),
- or add a minWidth(%s) or minHeight(%s) or use aspect(%s) to control the
- height and width.`,L,C,s,c,f,d,r);var M=!Array.isArray(p)&&Yr(p.type).endsWith("Chart");return $.Children.map(p,function(I){return $.isValidElement(I)?P.cloneElement(I,Yl({width:L,height:C},M?{style:Yl({height:"100%",width:"100%",maxHeight:C,maxWidth:L},I.props.style)}:{})):I})},[r,p,c,h,d,f,N,s]);return $.createElement("div",{id:b?"".concat(b):void 0,className:ee("recharts-responsive-container",v),style:Yl(Yl({},S),{},{width:s,height:c,minWidth:f,minHeight:d,maxHeight:h}),ref:j},T)}),xr=function(t){return null};xr.displayName="Cell";function Es(e){"@babel/helpers - typeof";return Es=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Es(e)}function Mx(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function Fp(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Mx(Object(r),!0).forEach(function(n){gF(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Mx(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function gF(e,t,r){return t=xF(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function xF(e){var t=bF(e,"string");return Es(t)=="symbol"?t:t+""}function bF(e,t){if(Es(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(Es(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var Ra={widthCache:{},cacheCount:0},jF=2e3,wF={position:"absolute",top:"-20000px",left:0,padding:0,margin:0,border:"none",whiteSpace:"pre"},Ix="recharts_measurement_span";function SF(e){var t=Fp({},e);return Object.keys(t).forEach(function(r){t[r]||delete t[r]}),t}var ts=function(t){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(t==null||Wn.isSsr)return{width:0,height:0};var n=SF(r),a=JSON.stringify({text:t,copyStyle:n});if(Ra.widthCache[a])return Ra.widthCache[a];try{var i=document.getElementById(Ix);i||(i=document.createElement("span"),i.setAttribute("id",Ix),i.setAttribute("aria-hidden","true"),document.body.appendChild(i));var s=Fp(Fp({},wF),n);Object.assign(i.style,s),i.textContent="".concat(t);var l=i.getBoundingClientRect(),c={width:l.width,height:l.height};return Ra.widthCache[a]=c,++Ra.cacheCount>jF&&(Ra.cacheCount=0,Ra.widthCache={}),c}catch{return{width:0,height:0}}},_F=function(t){return{top:t.top+window.scrollY-document.documentElement.clientTop,left:t.left+window.scrollX-document.documentElement.clientLeft}};function $s(e){"@babel/helpers - typeof";return $s=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},$s(e)}function du(e,t){return PF(e)||NF(e,t)||OF(e,t)||kF()}function kF(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
-In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function OF(e,t){if(e){if(typeof e=="string")return Lx(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return Lx(e,t)}}function Lx(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function NF(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,a,i,s,l=[],c=!0,u=!1;try{if(i=(r=r.call(e)).next,t===0){if(Object(r)!==r)return;c=!1}else for(;!(c=(n=i.call(r)).done)&&(l.push(n.value),l.length!==t);c=!0);}catch(f){u=!0,a=f}finally{try{if(!c&&r.return!=null&&(s=r.return(),Object(s)!==s))return}finally{if(u)throw a}}return l}}function PF(e){if(Array.isArray(e))return e}function AF(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function Dx(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,EF(n.key),n)}}function CF(e,t,r){return t&&Dx(e.prototype,t),r&&Dx(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function EF(e){var t=$F(e,"string");return $s(t)=="symbol"?t:t+""}function $F(e,t){if($s(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if($s(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}var Rx=/(-?\d+(?:\.\d+)?[a-zA-Z%]*)([*/])(-?\d+(?:\.\d+)?[a-zA-Z%]*)/,Bx=/(-?\d+(?:\.\d+)?[a-zA-Z%]*)([+-])(-?\d+(?:\.\d+)?[a-zA-Z%]*)/,TF=/^px|cm|vh|vw|em|rem|%|mm|in|pt|pc|ex|ch|vmin|vmax|Q$/,MF=/(-?\d+(?:\.\d+)?)([a-zA-Z%]+)?/,S_={cm:96/2.54,mm:96/25.4,pt:96/72,pc:96/6,in:96,Q:96/(2.54*40),px:1},IF=Object.keys(S_),ai="NaN";function LF(e,t){return e*S_[t]}var ql=function(){function e(t,r){AF(this,e),this.num=t,this.unit=r,this.num=t,this.unit=r,Number.isNaN(t)&&(this.unit=""),r!==""&&!TF.test(r)&&(this.num=NaN,this.unit=""),IF.includes(r)&&(this.num=LF(t,r),this.unit="px")}return CF(e,[{key:"add",value:function(r){return this.unit!==r.unit?new e(NaN,""):new e(this.num+r.num,this.unit)}},{key:"subtract",value:function(r){return this.unit!==r.unit?new e(NaN,""):new e(this.num-r.num,this.unit)}},{key:"multiply",value:function(r){return this.unit!==""&&r.unit!==""&&this.unit!==r.unit?new e(NaN,""):new e(this.num*r.num,this.unit||r.unit)}},{key:"divide",value:function(r){return this.unit!==""&&r.unit!==""&&this.unit!==r.unit?new e(NaN,""):new e(this.num/r.num,this.unit||r.unit)}},{key:"toString",value:function(){return"".concat(this.num).concat(this.unit)}},{key:"isNaN",value:function(){return Number.isNaN(this.num)}}],[{key:"parse",value:function(r){var n,a=(n=MF.exec(r))!==null&&n!==void 0?n:[],i=du(a,3),s=i[1],l=i[2];return new e(parseFloat(s),l??"")}}])}();function __(e){if(e.includes(ai))return ai;for(var t=e;t.includes("*")||t.includes("/");){var r,n=(r=Rx.exec(t))!==null&&r!==void 0?r:[],a=du(n,4),i=a[1],s=a[2],l=a[3],c=ql.parse(i??""),u=ql.parse(l??""),f=s==="*"?c.multiply(u):c.divide(u);if(f.isNaN())return ai;t=t.replace(Rx,f.toString())}for(;t.includes("+")||/.-\d+(?:\.\d+)?/.test(t);){var d,h=(d=Bx.exec(t))!==null&&d!==void 0?d:[],p=du(h,4),g=p[1],y=p[2],b=p[3],v=ql.parse(g??""),m=ql.parse(b??""),x=y==="+"?v.add(m):v.subtract(m);if(x.isNaN())return ai;t=t.replace(Bx,x.toString())}return t}var Fx=/\(([^()]*)\)/;function DF(e){for(var t=e;t.includes("(");){var r=Fx.exec(t),n=du(r,2),a=n[1];t=t.replace(Fx,__(a))}return t}function RF(e){var t=e.replace(/\s+/g,"");return t=DF(t),t=__(t),t}function BF(e){try{return RF(e)}catch{return ai}}function Jf(e){var t=BF(e.slice(5,-1));return t===ai?"":t}var FF=["x","y","lineHeight","capHeight","scaleToFit","textAnchor","verticalAnchor","fill"],zF=["dx","dy","angle","className","breakAll"];function zp(){return zp=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},zp.apply(this,arguments)}function zx(e,t){if(e==null)return{};var r=WF(e,t),n,a;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(a=0;a<i.length;a++)n=i[a],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function WF(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function Wx(e,t){return VF(e)||KF(e,t)||HF(e,t)||UF()}function UF(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
-In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function HF(e,t){if(e){if(typeof e=="string")return Ux(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return Ux(e,t)}}function Ux(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function KF(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,a,i,s,l=[],c=!0,u=!1;try{if(i=(r=r.call(e)).next,t===0){if(Object(r)!==r)return;c=!1}else for(;!(c=(n=i.call(r)).done)&&(l.push(n.value),l.length!==t);c=!0);}catch(f){u=!0,a=f}finally{try{if(!c&&r.return!=null&&(s=r.return(),Object(s)!==s))return}finally{if(u)throw a}}return l}}function VF(e){if(Array.isArray(e))return e}var k_=/[ \f\n\r\t\v\u2028\u2029]+/,O_=function(t){var r=t.children,n=t.breakAll,a=t.style;try{var i=[];te(r)||(n?i=r.toString().split(""):i=r.toString().split(k_));var s=i.map(function(c){return{word:c,width:ts(c,a).width}}),l=n?0:ts(" ",a).width;return{wordsWithComputedWidth:s,spaceWidth:l}}catch{return null}},GF=function(t,r,n,a,i){var s=t.maxLines,l=t.children,c=t.style,u=t.breakAll,f=U(s),d=l,h=function(){var L=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return L.reduce(function(C,M){var I=M.word,R=M.width,F=C[C.length-1];if(F&&(a==null||i||F.width+R+n<Number(a)))F.words.push(I),F.width+=R+n;else{var K={words:[I],width:R};C.push(K)}return C},[])},p=h(r),g=function(L){return L.reduce(function(C,M){return C.width>M.width?C:M})};if(!f)return p;for(var y="…",b=function(L){var C=d.slice(0,L),M=O_({breakAll:u,style:c,children:C+y}).wordsWithComputedWidth,I=h(M),R=I.length>s||g(I).width>Number(a);return[R,I]},v=0,m=d.length-1,x=0,S;v<=m&&x<=d.length-1;){var j=Math.floor((v+m)/2),w=j-1,_=b(w),O=Wx(_,2),N=O[0],k=O[1],E=b(j),T=Wx(E,1),D=T[0];if(!N&&!D&&(v=j+1),N&&D&&(m=j-1),!N&&D){S=k;break}x++}return S||p},Hx=function(t){var r=te(t)?[]:t.toString().split(k_);return[{words:r}]},YF=function(t){var r=t.width,n=t.scaleToFit,a=t.children,i=t.style,s=t.breakAll,l=t.maxLines;if((r||n)&&!Wn.isSsr){var c,u,f=O_({breakAll:s,children:a,style:i});if(f){var d=f.wordsWithComputedWidth,h=f.spaceWidth;c=d,u=h}else return Hx(a);return GF({breakAll:s,children:a,maxLines:l,style:i},c,u,r,n)}return Hx(a)},Kx="#808080",Sa=function(t){var r=t.x,n=r===void 0?0:r,a=t.y,i=a===void 0?0:a,s=t.lineHeight,l=s===void 0?"1em":s,c=t.capHeight,u=c===void 0?"0.71em":c,f=t.scaleToFit,d=f===void 0?!1:f,h=t.textAnchor,p=h===void 0?"start":h,g=t.verticalAnchor,y=g===void 0?"end":g,b=t.fill,v=b===void 0?Kx:b,m=zx(t,FF),x=P.useMemo(function(){return YF({breakAll:m.breakAll,children:m.children,maxLines:m.maxLines,scaleToFit:d,style:m.style,width:m.width})},[m.breakAll,m.children,m.maxLines,d,m.style,m.width]),S=m.dx,j=m.dy,w=m.angle,_=m.className,O=m.breakAll,N=zx(m,zF);if(!qe(n)||!qe(i))return null;var k=n+(U(S)?S:0),E=i+(U(j)?j:0),T;switch(y){case"start":T=Jf("calc(".concat(u,")"));break;case"middle":T=Jf("calc(".concat((x.length-1)/2," * -").concat(l," + (").concat(u," / 2))"));break;default:T=Jf("calc(".concat(x.length-1," * -").concat(l,")"));break}var D=[];if(d){var A=x[0].width,L=m.width;D.push("scale(".concat((U(L)?L/A:1)/A,")"))}return w&&D.push("rotate(".concat(w,", ").concat(k,", ").concat(E,")")),D.length&&(N.transform=D.join(" ")),$.createElement("text",zp({},X(N,!0),{x:k,y:E,className:ee("recharts-text",_),textAnchor:p,fill:v.includes("url")?Kx:v}),x.map(function(C,M){var I=C.words.join(O?"":" ");return $.createElement("tspan",{x:k,dy:M===0?T:l,key:"".concat(I,"-").concat(M)},I)}))};function Mn(e,t){return e==null||t==null?NaN:e<t?-1:e>t?1:e>=t?0:NaN}function qF(e,t){return e==null||t==null?NaN:t<e?-1:t>e?1:t>=e?0:NaN}function py(e){let t,r,n;e.length!==2?(t=Mn,r=(l,c)=>Mn(e(l),c),n=(l,c)=>e(l)-c):(t=e===Mn||e===qF?e:XF,r=e,n=e);function a(l,c,u=0,f=l.length){if(u<f){if(t(c,c)!==0)return f;do{const d=u+f>>>1;r(l[d],c)<0?u=d+1:f=d}while(u<f)}return u}function i(l,c,u=0,f=l.length){if(u<f){if(t(c,c)!==0)return f;do{const d=u+f>>>1;r(l[d],c)<=0?u=d+1:f=d}while(u<f)}return u}function s(l,c,u=0,f=l.length){const d=a(l,c,u,f-1);return d>u&&n(l[d-1],c)>-n(l[d],c)?d-1:d}return{left:a,center:s,right:i}}function XF(){return 0}function N_(e){return e===null?NaN:+e}function*QF(e,t){for(let r of e)r!=null&&(r=+r)>=r&&(yield r)}const JF=py(Mn),yl=JF.right;py(N_).center;class Vx extends Map{constructor(t,r=t9){if(super(),Object.defineProperties(this,{_intern:{value:new Map},_key:{value:r}}),t!=null)for(const[n,a]of t)this.set(n,a)}get(t){return super.get(Gx(this,t))}has(t){return super.has(Gx(this,t))}set(t,r){return super.set(ZF(this,t),r)}delete(t){return super.delete(e9(this,t))}}function Gx({_intern:e,_key:t},r){const n=t(r);return e.has(n)?e.get(n):r}function ZF({_intern:e,_key:t},r){const n=t(r);return e.has(n)?e.get(n):(e.set(n,r),r)}function e9({_intern:e,_key:t},r){const n=t(r);return e.has(n)&&(r=e.get(n),e.delete(n)),r}function t9(e){return e!==null&&typeof e=="object"?e.valueOf():e}function r9(e=Mn){if(e===Mn)return P_;if(typeof e!="function")throw new TypeError("compare is not a function");return(t,r)=>{const n=e(t,r);return n||n===0?n:(e(r,r)===0)-(e(t,t)===0)}}function P_(e,t){return(e==null||!(e>=e))-(t==null||!(t>=t))||(e<t?-1:e>t?1:0)}const n9=Math.sqrt(50),a9=Math.sqrt(10),i9=Math.sqrt(2);function fu(e,t,r){const n=(t-e)/Math.max(0,r),a=Math.floor(Math.log10(n)),i=n/Math.pow(10,a),s=i>=n9?10:i>=a9?5:i>=i9?2:1;let l,c,u;return a<0?(u=Math.pow(10,-a)/s,l=Math.round(e*u),c=Math.round(t*u),l/u<e&&++l,c/u>t&&--c,u=-u):(u=Math.pow(10,a)*s,l=Math.round(e/u),c=Math.round(t/u),l*u<e&&++l,c*u>t&&--c),c<l&&.5<=r&&r<2?fu(e,t,r*2):[l,c,u]}function Wp(e,t,r){if(t=+t,e=+e,r=+r,!(r>0))return[];if(e===t)return[e];const n=t<e,[a,i,s]=n?fu(t,e,r):fu(e,t,r);if(!(i>=a))return[];const l=i-a+1,c=new Array(l);if(n)if(s<0)for(let u=0;u<l;++u)c[u]=(i-u)/-s;else for(let u=0;u<l;++u)c[u]=(i-u)*s;else if(s<0)for(let u=0;u<l;++u)c[u]=(a+u)/-s;else for(let u=0;u<l;++u)c[u]=(a+u)*s;return c}function Up(e,t,r){return t=+t,e=+e,r=+r,fu(e,t,r)[2]}function Hp(e,t,r){t=+t,e=+e,r=+r;const n=t<e,a=n?Up(t,e,r):Up(e,t,r);return(n?-1:1)*(a<0?1/-a:a)}function Yx(e,t){let r;for(const n of e)n!=null&&(r<n||r===void 0&&n>=n)&&(r=n);return r}function qx(e,t){let r;for(const n of e)n!=null&&(r>n||r===void 0&&n>=n)&&(r=n);return r}function A_(e,t,r=0,n=1/0,a){if(t=Math.floor(t),r=Math.floor(Math.max(0,r)),n=Math.floor(Math.min(e.length-1,n)),!(r<=t&&t<=n))return e;for(a=a===void 0?P_:r9(a);n>r;){if(n-r>600){const c=n-r+1,u=t-r+1,f=Math.log(c),d=.5*Math.exp(2*f/3),h=.5*Math.sqrt(f*d*(c-d)/c)*(u-c/2<0?-1:1),p=Math.max(r,Math.floor(t-u*d/c+h)),g=Math.min(n,Math.floor(t+(c-u)*d/c+h));A_(e,t,p,g,a)}const i=e[t];let s=r,l=n;for(Ao(e,r,t),a(e[n],i)>0&&Ao(e,r,n);s<l;){for(Ao(e,s,l),++s,--l;a(e[s],i)<0;)++s;for(;a(e[l],i)>0;)--l}a(e[r],i)===0?Ao(e,r,l):(++l,Ao(e,l,n)),l<=t&&(r=l+1),t<=l&&(n=l-1)}return e}function Ao(e,t,r){const n=e[t];e[t]=e[r],e[r]=n}function o9(e,t,r){if(e=Float64Array.from(QF(e)),!(!(n=e.length)||isNaN(t=+t))){if(t<=0||n<2)return qx(e);if(t>=1)return Yx(e);var n,a=(n-1)*t,i=Math.floor(a),s=Yx(A_(e,i).subarray(0,i+1)),l=qx(e.subarray(i+1));return s+(l-s)*(a-i)}}function s9(e,t,r=N_){if(!(!(n=e.length)||isNaN(t=+t))){if(t<=0||n<2)return+r(e[0],0,e);if(t>=1)return+r(e[n-1],n-1,e);var n,a=(n-1)*t,i=Math.floor(a),s=+r(e[i],i,e),l=+r(e[i+1],i+1,e);return s+(l-s)*(a-i)}}function l9(e,t,r){e=+e,t=+t,r=(a=arguments.length)<2?(t=e,e=0,1):a<3?1:+r;for(var n=-1,a=Math.max(0,Math.ceil((t-e)/r))|0,i=new Array(a);++n<a;)i[n]=e+n*r;return i}function ir(e,t){switch(arguments.length){case 0:break;case 1:this.range(e);break;default:this.range(t).domain(e);break}return this}function ln(e,t){switch(arguments.length){case 0:break;case 1:{typeof e=="function"?this.interpolator(e):this.range(e);break}default:{this.domain(e),typeof t=="function"?this.interpolator(t):this.range(t);break}}return this}const Kp=Symbol("implicit");function my(){var e=new Vx,t=[],r=[],n=Kp;function a(i){let s=e.get(i);if(s===void 0){if(n!==Kp)return n;e.set(i,s=t.push(i)-1)}return r[s%r.length]}return a.domain=function(i){if(!arguments.length)return t.slice();t=[],e=new Vx;for(const s of i)e.has(s)||e.set(s,t.push(s)-1);return a},a.range=function(i){return arguments.length?(r=Array.from(i),a):r.slice()},a.unknown=function(i){return arguments.length?(n=i,a):n},a.copy=function(){return my(t,r).unknown(n)},ir.apply(a,arguments),a}function Ts(){var e=my().unknown(void 0),t=e.domain,r=e.range,n=0,a=1,i,s,l=!1,c=0,u=0,f=.5;delete e.unknown;function d(){var h=t().length,p=a<n,g=p?a:n,y=p?n:a;i=(y-g)/Math.max(1,h-c+u*2),l&&(i=Math.floor(i)),g+=(y-g-i*(h-c))*f,s=i*(1-c),l&&(g=Math.round(g),s=Math.round(s));var b=l9(h).map(function(v){return g+i*v});return r(p?b.reverse():b)}return e.domain=function(h){return arguments.length?(t(h),d()):t()},e.range=function(h){return arguments.length?([n,a]=h,n=+n,a=+a,d()):[n,a]},e.rangeRound=function(h){return[n,a]=h,n=+n,a=+a,l=!0,d()},e.bandwidth=function(){return s},e.step=function(){return i},e.round=function(h){return arguments.length?(l=!!h,d()):l},e.padding=function(h){return arguments.length?(c=Math.min(1,u=+h),d()):c},e.paddingInner=function(h){return arguments.length?(c=Math.min(1,h),d()):c},e.paddingOuter=function(h){return arguments.length?(u=+h,d()):u},e.align=function(h){return arguments.length?(f=Math.max(0,Math.min(1,h)),d()):f},e.copy=function(){return Ts(t(),[n,a]).round(l).paddingInner(c).paddingOuter(u).align(f)},ir.apply(d(),arguments)}function C_(e){var t=e.copy;return e.padding=e.paddingOuter,delete e.paddingInner,delete e.paddingOuter,e.copy=function(){return C_(t())},e}function rs(){return C_(Ts.apply(null,arguments).paddingInner(1))}function vy(e,t,r){e.prototype=t.prototype=r,r.constructor=e}function E_(e,t){var r=Object.create(e.prototype);for(var n in t)r[n]=t[n];return r}function gl(){}var Ms=.7,hu=1/Ms,yi="\\s*([+-]?\\d+)\\s*",Is="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",Cr="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",c9=/^#([0-9a-f]{3,8})$/,u9=new RegExp(`^rgb\\(${yi},${yi},${yi}\\)$`),d9=new RegExp(`^rgb\\(${Cr},${Cr},${Cr}\\)$`),f9=new RegExp(`^rgba\\(${yi},${yi},${yi},${Is}\\)$`),h9=new RegExp(`^rgba\\(${Cr},${Cr},${Cr},${Is}\\)$`),p9=new RegExp(`^hsl\\(${Is},${Cr},${Cr}\\)$`),m9=new RegExp(`^hsla\\(${Is},${Cr},${Cr},${Is}\\)$`),Xx={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074};vy(gl,Ls,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:Qx,formatHex:Qx,formatHex8:v9,formatHsl:y9,formatRgb:Jx,toString:Jx});function Qx(){return this.rgb().formatHex()}function v9(){return this.rgb().formatHex8()}function y9(){return $_(this).formatHsl()}function Jx(){return this.rgb().formatRgb()}function Ls(e){var t,r;return e=(e+"").trim().toLowerCase(),(t=c9.exec(e))?(r=t[1].length,t=parseInt(t[1],16),r===6?Zx(t):r===3?new Pt(t>>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):r===8?Xl(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):r===4?Xl(t>>12&15|t>>8&240,t>>8&15|t>>4&240,t>>4&15|t&240,((t&15)<<4|t&15)/255):null):(t=u9.exec(e))?new Pt(t[1],t[2],t[3],1):(t=d9.exec(e))?new Pt(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=f9.exec(e))?Xl(t[1],t[2],t[3],t[4]):(t=h9.exec(e))?Xl(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=p9.exec(e))?rb(t[1],t[2]/100,t[3]/100,1):(t=m9.exec(e))?rb(t[1],t[2]/100,t[3]/100,t[4]):Xx.hasOwnProperty(e)?Zx(Xx[e]):e==="transparent"?new Pt(NaN,NaN,NaN,0):null}function Zx(e){return new Pt(e>>16&255,e>>8&255,e&255,1)}function Xl(e,t,r,n){return n<=0&&(e=t=r=NaN),new Pt(e,t,r,n)}function g9(e){return e instanceof gl||(e=Ls(e)),e?(e=e.rgb(),new Pt(e.r,e.g,e.b,e.opacity)):new Pt}function Vp(e,t,r,n){return arguments.length===1?g9(e):new Pt(e,t,r,n??1)}function Pt(e,t,r,n){this.r=+e,this.g=+t,this.b=+r,this.opacity=+n}vy(Pt,Vp,E_(gl,{brighter(e){return e=e==null?hu:Math.pow(hu,e),new Pt(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?Ms:Math.pow(Ms,e),new Pt(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new Pt(pa(this.r),pa(this.g),pa(this.b),pu(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:eb,formatHex:eb,formatHex8:x9,formatRgb:tb,toString:tb}));function eb(){return`#${sa(this.r)}${sa(this.g)}${sa(this.b)}`}function x9(){return`#${sa(this.r)}${sa(this.g)}${sa(this.b)}${sa((isNaN(this.opacity)?1:this.opacity)*255)}`}function tb(){const e=pu(this.opacity);return`${e===1?"rgb(":"rgba("}${pa(this.r)}, ${pa(this.g)}, ${pa(this.b)}${e===1?")":`, ${e})`}`}function pu(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function pa(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function sa(e){return e=pa(e),(e<16?"0":"")+e.toString(16)}function rb(e,t,r,n){return n<=0?e=t=r=NaN:r<=0||r>=1?e=t=NaN:t<=0&&(e=NaN),new pr(e,t,r,n)}function $_(e){if(e instanceof pr)return new pr(e.h,e.s,e.l,e.opacity);if(e instanceof gl||(e=Ls(e)),!e)return new pr;if(e instanceof pr)return e;e=e.rgb();var t=e.r/255,r=e.g/255,n=e.b/255,a=Math.min(t,r,n),i=Math.max(t,r,n),s=NaN,l=i-a,c=(i+a)/2;return l?(t===i?s=(r-n)/l+(r<n)*6:r===i?s=(n-t)/l+2:s=(t-r)/l+4,l/=c<.5?i+a:2-i-a,s*=60):l=c>0&&c<1?0:s,new pr(s,l,c,e.opacity)}function b9(e,t,r,n){return arguments.length===1?$_(e):new pr(e,t,r,n??1)}function pr(e,t,r,n){this.h=+e,this.s=+t,this.l=+r,this.opacity=+n}vy(pr,b9,E_(gl,{brighter(e){return e=e==null?hu:Math.pow(hu,e),new pr(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?Ms:Math.pow(Ms,e),new pr(this.h,this.s,this.l*e,this.opacity)},rgb(){var e=this.h%360+(this.h<0)*360,t=isNaN(e)||isNaN(this.s)?0:this.s,r=this.l,n=r+(r<.5?r:1-r)*t,a=2*r-n;return new Pt(Zf(e>=240?e-240:e+120,a,n),Zf(e,a,n),Zf(e<120?e+240:e-120,a,n),this.opacity)},clamp(){return new pr(nb(this.h),Ql(this.s),Ql(this.l),pu(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){const e=pu(this.opacity);return`${e===1?"hsl(":"hsla("}${nb(this.h)}, ${Ql(this.s)*100}%, ${Ql(this.l)*100}%${e===1?")":`, ${e})`}`}}));function nb(e){return e=(e||0)%360,e<0?e+360:e}function Ql(e){return Math.max(0,Math.min(1,e||0))}function Zf(e,t,r){return(e<60?t+(r-t)*e/60:e<180?r:e<240?t+(r-t)*(240-e)/60:t)*255}const yy=e=>()=>e;function j9(e,t){return function(r){return e+r*t}}function w9(e,t,r){return e=Math.pow(e,r),t=Math.pow(t,r)-e,r=1/r,function(n){return Math.pow(e+n*t,r)}}function S9(e){return(e=+e)==1?T_:function(t,r){return r-t?w9(t,r,e):yy(isNaN(t)?r:t)}}function T_(e,t){var r=t-e;return r?j9(e,r):yy(isNaN(e)?t:e)}const ab=function e(t){var r=S9(t);function n(a,i){var s=r((a=Vp(a)).r,(i=Vp(i)).r),l=r(a.g,i.g),c=r(a.b,i.b),u=T_(a.opacity,i.opacity);return function(f){return a.r=s(f),a.g=l(f),a.b=c(f),a.opacity=u(f),a+""}}return n.gamma=e,n}(1);function _9(e,t){t||(t=[]);var r=e?Math.min(t.length,e.length):0,n=t.slice(),a;return function(i){for(a=0;a<r;++a)n[a]=e[a]*(1-i)+t[a]*i;return n}}function k9(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function O9(e,t){var r=t?t.length:0,n=e?Math.min(r,e.length):0,a=new Array(n),i=new Array(r),s;for(s=0;s<n;++s)a[s]=mo(e[s],t[s]);for(;s<r;++s)i[s]=t[s];return function(l){for(s=0;s<n;++s)i[s]=a[s](l);return i}}function N9(e,t){var r=new Date;return e=+e,t=+t,function(n){return r.setTime(e*(1-n)+t*n),r}}function mu(e,t){return e=+e,t=+t,function(r){return e*(1-r)+t*r}}function P9(e,t){var r={},n={},a;(e===null||typeof e!="object")&&(e={}),(t===null||typeof t!="object")&&(t={});for(a in t)a in e?r[a]=mo(e[a],t[a]):n[a]=t[a];return function(i){for(a in r)n[a]=r[a](i);return n}}var Gp=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,eh=new RegExp(Gp.source,"g");function A9(e){return function(){return e}}function C9(e){return function(t){return e(t)+""}}function E9(e,t){var r=Gp.lastIndex=eh.lastIndex=0,n,a,i,s=-1,l=[],c=[];for(e=e+"",t=t+"";(n=Gp.exec(e))&&(a=eh.exec(t));)(i=a.index)>r&&(i=t.slice(r,i),l[s]?l[s]+=i:l[++s]=i),(n=n[0])===(a=a[0])?l[s]?l[s]+=a:l[++s]=a:(l[++s]=null,c.push({i:s,x:mu(n,a)})),r=eh.lastIndex;return r<t.length&&(i=t.slice(r),l[s]?l[s]+=i:l[++s]=i),l.length<2?c[0]?C9(c[0].x):A9(t):(t=c.length,function(u){for(var f=0,d;f<t;++f)l[(d=c[f]).i]=d.x(u);return l.join("")})}function mo(e,t){var r=typeof t,n;return t==null||r==="boolean"?yy(t):(r==="number"?mu:r==="string"?(n=Ls(t))?(t=n,ab):E9:t instanceof Ls?ab:t instanceof Date?N9:k9(t)?_9:Array.isArray(t)?O9:typeof t.valueOf!="function"&&typeof t.toString!="function"||isNaN(t)?P9:mu)(e,t)}function gy(e,t){return e=+e,t=+t,function(r){return Math.round(e*(1-r)+t*r)}}function $9(e,t){t===void 0&&(t=e,e=mo);for(var r=0,n=t.length-1,a=t[0],i=new Array(n<0?0:n);r<n;)i[r]=e(a,a=t[++r]);return function(s){var l=Math.max(0,Math.min(n-1,Math.floor(s*=n)));return i[l](s-l)}}function T9(e){return function(){return e}}function vu(e){return+e}var ib=[0,1];function bt(e){return e}function Yp(e,t){return(t-=e=+e)?function(r){return(r-e)/t}:T9(isNaN(t)?NaN:.5)}function M9(e,t){var r;return e>t&&(r=e,e=t,t=r),function(n){return Math.max(e,Math.min(t,n))}}function I9(e,t,r){var n=e[0],a=e[1],i=t[0],s=t[1];return a<n?(n=Yp(a,n),i=r(s,i)):(n=Yp(n,a),i=r(i,s)),function(l){return i(n(l))}}function L9(e,t,r){var n=Math.min(e.length,t.length)-1,a=new Array(n),i=new Array(n),s=-1;for(e[n]<e[0]&&(e=e.slice().reverse(),t=t.slice().reverse());++s<n;)a[s]=Yp(e[s],e[s+1]),i[s]=r(t[s],t[s+1]);return function(l){var c=yl(e,l,1,n)-1;return i[c](a[c](l))}}function xl(e,t){return t.domain(e.domain()).range(e.range()).interpolate(e.interpolate()).clamp(e.clamp()).unknown(e.unknown())}function Wd(){var e=ib,t=ib,r=mo,n,a,i,s=bt,l,c,u;function f(){var h=Math.min(e.length,t.length);return s!==bt&&(s=M9(e[0],e[h-1])),l=h>2?L9:I9,c=u=null,d}function d(h){return h==null||isNaN(h=+h)?i:(c||(c=l(e.map(n),t,r)))(n(s(h)))}return d.invert=function(h){return s(a((u||(u=l(t,e.map(n),mu)))(h)))},d.domain=function(h){return arguments.length?(e=Array.from(h,vu),f()):e.slice()},d.range=function(h){return arguments.length?(t=Array.from(h),f()):t.slice()},d.rangeRound=function(h){return t=Array.from(h),r=gy,f()},d.clamp=function(h){return arguments.length?(s=h?!0:bt,f()):s!==bt},d.interpolate=function(h){return arguments.length?(r=h,f()):r},d.unknown=function(h){return arguments.length?(i=h,d):i},function(h,p){return n=h,a=p,f()}}function xy(){return Wd()(bt,bt)}function D9(e){return Math.abs(e=Math.round(e))>=1e21?e.toLocaleString("en").replace(/,/g,""):e.toString(10)}function yu(e,t){if(!isFinite(e)||e===0)return null;var r=(e=t?e.toExponential(t-1):e.toExponential()).indexOf("e"),n=e.slice(0,r);return[n.length>1?n[0]+n.slice(2):n,+e.slice(r+1)]}function $i(e){return e=yu(Math.abs(e)),e?e[1]:NaN}function R9(e,t){return function(r,n){for(var a=r.length,i=[],s=0,l=e[0],c=0;a>0&&l>0&&(c+l+1>n&&(l=Math.max(1,n-c)),i.push(r.substring(a-=l,a+l)),!((c+=l+1)>n));)l=e[s=(s+1)%e.length];return i.reverse().join(t)}}function B9(e){return function(t){return t.replace(/[0-9]/g,function(r){return e[+r]})}}var F9=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function Ds(e){if(!(t=F9.exec(e)))throw new Error("invalid format: "+e);var t;return new by({fill:t[1],align:t[2],sign:t[3],symbol:t[4],zero:t[5],width:t[6],comma:t[7],precision:t[8]&&t[8].slice(1),trim:t[9],type:t[10]})}Ds.prototype=by.prototype;function by(e){this.fill=e.fill===void 0?" ":e.fill+"",this.align=e.align===void 0?">":e.align+"",this.sign=e.sign===void 0?"-":e.sign+"",this.symbol=e.symbol===void 0?"":e.symbol+"",this.zero=!!e.zero,this.width=e.width===void 0?void 0:+e.width,this.comma=!!e.comma,this.precision=e.precision===void 0?void 0:+e.precision,this.trim=!!e.trim,this.type=e.type===void 0?"":e.type+""}by.prototype.toString=function(){return this.fill+this.align+this.sign+this.symbol+(this.zero?"0":"")+(this.width===void 0?"":Math.max(1,this.width|0))+(this.comma?",":"")+(this.precision===void 0?"":"."+Math.max(0,this.precision|0))+(this.trim?"~":"")+this.type};function z9(e){e:for(var t=e.length,r=1,n=-1,a;r<t;++r)switch(e[r]){case".":n=a=r;break;case"0":n===0&&(n=r),a=r;break;default:if(!+e[r])break e;n>0&&(n=0);break}return n>0?e.slice(0,n)+e.slice(a+1):e}var gu;function W9(e,t){var r=yu(e,t);if(!r)return gu=void 0,e.toPrecision(t);var n=r[0],a=r[1],i=a-(gu=Math.max(-8,Math.min(8,Math.floor(a/3)))*3)+1,s=n.length;return i===s?n:i>s?n+new Array(i-s+1).join("0"):i>0?n.slice(0,i)+"."+n.slice(i):"0."+new Array(1-i).join("0")+yu(e,Math.max(0,t+i-1))[0]}function ob(e,t){var r=yu(e,t);if(!r)return e+"";var n=r[0],a=r[1];return a<0?"0."+new Array(-a).join("0")+n:n.length>a+1?n.slice(0,a+1)+"."+n.slice(a+1):n+new Array(a-n.length+2).join("0")}const sb={"%":(e,t)=>(e*100).toFixed(t),b:e=>Math.round(e).toString(2),c:e=>e+"",d:D9,e:(e,t)=>e.toExponential(t),f:(e,t)=>e.toFixed(t),g:(e,t)=>e.toPrecision(t),o:e=>Math.round(e).toString(8),p:(e,t)=>ob(e*100,t),r:ob,s:W9,X:e=>Math.round(e).toString(16).toUpperCase(),x:e=>Math.round(e).toString(16)};function lb(e){return e}var cb=Array.prototype.map,ub=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];function U9(e){var t=e.grouping===void 0||e.thousands===void 0?lb:R9(cb.call(e.grouping,Number),e.thousands+""),r=e.currency===void 0?"":e.currency[0]+"",n=e.currency===void 0?"":e.currency[1]+"",a=e.decimal===void 0?".":e.decimal+"",i=e.numerals===void 0?lb:B9(cb.call(e.numerals,String)),s=e.percent===void 0?"%":e.percent+"",l=e.minus===void 0?"−":e.minus+"",c=e.nan===void 0?"NaN":e.nan+"";function u(d,h){d=Ds(d);var p=d.fill,g=d.align,y=d.sign,b=d.symbol,v=d.zero,m=d.width,x=d.comma,S=d.precision,j=d.trim,w=d.type;w==="n"?(x=!0,w="g"):sb[w]||(S===void 0&&(S=12),j=!0,w="g"),(v||p==="0"&&g==="=")&&(v=!0,p="0",g="=");var _=(h&&h.prefix!==void 0?h.prefix:"")+(b==="$"?r:b==="#"&&/[boxX]/.test(w)?"0"+w.toLowerCase():""),O=(b==="$"?n:/[%p]/.test(w)?s:"")+(h&&h.suffix!==void 0?h.suffix:""),N=sb[w],k=/[defgprs%]/.test(w);S=S===void 0?6:/[gprs]/.test(w)?Math.max(1,Math.min(21,S)):Math.max(0,Math.min(20,S));function E(T){var D=_,A=O,L,C,M;if(w==="c")A=N(T)+A,T="";else{T=+T;var I=T<0||1/T<0;if(T=isNaN(T)?c:N(Math.abs(T),S),j&&(T=z9(T)),I&&+T==0&&y!=="+"&&(I=!1),D=(I?y==="("?y:l:y==="-"||y==="("?"":y)+D,A=(w==="s"&&!isNaN(T)&&gu!==void 0?ub[8+gu/3]:"")+A+(I&&y==="("?")":""),k){for(L=-1,C=T.length;++L<C;)if(M=T.charCodeAt(L),48>M||M>57){A=(M===46?a+T.slice(L+1):T.slice(L))+A,T=T.slice(0,L);break}}}x&&!v&&(T=t(T,1/0));var R=D.length+T.length+A.length,F=R<m?new Array(m-R+1).join(p):"";switch(x&&v&&(T=t(F+T,F.length?m-A.length:1/0),F=""),g){case"<":T=D+T+A+F;break;case"=":T=D+F+T+A;break;case"^":T=F.slice(0,R=F.length>>1)+D+T+A+F.slice(R);break;default:T=F+D+T+A;break}return i(T)}return E.toString=function(){return d+""},E}function f(d,h){var p=Math.max(-8,Math.min(8,Math.floor($i(h)/3)))*3,g=Math.pow(10,-p),y=u((d=Ds(d),d.type="f",d),{suffix:ub[8+p/3]});return function(b){return y(g*b)}}return{format:u,formatPrefix:f}}var Jl,jy,M_;H9({thousands:",",grouping:[3],currency:["$",""]});function H9(e){return Jl=U9(e),jy=Jl.format,M_=Jl.formatPrefix,Jl}function K9(e){return Math.max(0,-$i(Math.abs(e)))}function V9(e,t){return Math.max(0,Math.max(-8,Math.min(8,Math.floor($i(t)/3)))*3-$i(Math.abs(e)))}function G9(e,t){return e=Math.abs(e),t=Math.abs(t)-e,Math.max(0,$i(t)-$i(e))+1}function I_(e,t,r,n){var a=Hp(e,t,r),i;switch(n=Ds(n??",f"),n.type){case"s":{var s=Math.max(Math.abs(e),Math.abs(t));return n.precision==null&&!isNaN(i=V9(a,s))&&(n.precision=i),M_(n,s)}case"":case"e":case"g":case"p":case"r":{n.precision==null&&!isNaN(i=G9(a,Math.max(Math.abs(e),Math.abs(t))))&&(n.precision=i-(n.type==="e"));break}case"f":case"%":{n.precision==null&&!isNaN(i=K9(a))&&(n.precision=i-(n.type==="%")*2);break}}return jy(n)}function Un(e){var t=e.domain;return e.ticks=function(r){var n=t();return Wp(n[0],n[n.length-1],r??10)},e.tickFormat=function(r,n){var a=t();return I_(a[0],a[a.length-1],r??10,n)},e.nice=function(r){r==null&&(r=10);var n=t(),a=0,i=n.length-1,s=n[a],l=n[i],c,u,f=10;for(l<s&&(u=s,s=l,l=u,u=a,a=i,i=u);f-- >0;){if(u=Up(s,l,r),u===c)return n[a]=s,n[i]=l,t(n);if(u>0)s=Math.floor(s/u)*u,l=Math.ceil(l/u)*u;else if(u<0)s=Math.ceil(s*u)/u,l=Math.floor(l*u)/u;else break;c=u}return e},e}function xu(){var e=xy();return e.copy=function(){return xl(e,xu())},ir.apply(e,arguments),Un(e)}function L_(e){var t;function r(n){return n==null||isNaN(n=+n)?t:n}return r.invert=r,r.domain=r.range=function(n){return arguments.length?(e=Array.from(n,vu),r):e.slice()},r.unknown=function(n){return arguments.length?(t=n,r):t},r.copy=function(){return L_(e).unknown(t)},e=arguments.length?Array.from(e,vu):[0,1],Un(r)}function D_(e,t){e=e.slice();var r=0,n=e.length-1,a=e[r],i=e[n],s;return i<a&&(s=r,r=n,n=s,s=a,a=i,i=s),e[r]=t.floor(a),e[n]=t.ceil(i),e}function db(e){return Math.log(e)}function fb(e){return Math.exp(e)}function Y9(e){return-Math.log(-e)}function q9(e){return-Math.exp(-e)}function X9(e){return isFinite(e)?+("1e"+e):e<0?0:e}function Q9(e){return e===10?X9:e===Math.E?Math.exp:t=>Math.pow(e,t)}function J9(e){return e===Math.E?Math.log:e===10&&Math.log10||e===2&&Math.log2||(e=Math.log(e),t=>Math.log(t)/e)}function hb(e){return(t,r)=>-e(-t,r)}function wy(e){const t=e(db,fb),r=t.domain;let n=10,a,i;function s(){return a=J9(n),i=Q9(n),r()[0]<0?(a=hb(a),i=hb(i),e(Y9,q9)):e(db,fb),t}return t.base=function(l){return arguments.length?(n=+l,s()):n},t.domain=function(l){return arguments.length?(r(l),s()):r()},t.ticks=l=>{const c=r();let u=c[0],f=c[c.length-1];const d=f<u;d&&([u,f]=[f,u]);let h=a(u),p=a(f),g,y;const b=l==null?10:+l;let v=[];if(!(n%1)&&p-h<b){if(h=Math.floor(h),p=Math.ceil(p),u>0){for(;h<=p;++h)for(g=1;g<n;++g)if(y=h<0?g/i(-h):g*i(h),!(y<u)){if(y>f)break;v.push(y)}}else for(;h<=p;++h)for(g=n-1;g>=1;--g)if(y=h>0?g/i(-h):g*i(h),!(y<u)){if(y>f)break;v.push(y)}v.length*2<b&&(v=Wp(u,f,b))}else v=Wp(h,p,Math.min(p-h,b)).map(i);return d?v.reverse():v},t.tickFormat=(l,c)=>{if(l==null&&(l=10),c==null&&(c=n===10?"s":","),typeof c!="function"&&(!(n%1)&&(c=Ds(c)).precision==null&&(c.trim=!0),c=jy(c)),l===1/0)return c;const u=Math.max(1,n*l/t.ticks().length);return f=>{let d=f/i(Math.round(a(f)));return d*n<n-.5&&(d*=n),d<=u?c(f):""}},t.nice=()=>r(D_(r(),{floor:l=>i(Math.floor(a(l))),ceil:l=>i(Math.ceil(a(l)))})),t}function R_(){const e=wy(Wd()).domain([1,10]);return e.copy=()=>xl(e,R_()).base(e.base()),ir.apply(e,arguments),e}function pb(e){return function(t){return Math.sign(t)*Math.log1p(Math.abs(t/e))}}function mb(e){return function(t){return Math.sign(t)*Math.expm1(Math.abs(t))*e}}function Sy(e){var t=1,r=e(pb(t),mb(t));return r.constant=function(n){return arguments.length?e(pb(t=+n),mb(t)):t},Un(r)}function B_(){var e=Sy(Wd());return e.copy=function(){return xl(e,B_()).constant(e.constant())},ir.apply(e,arguments)}function vb(e){return function(t){return t<0?-Math.pow(-t,e):Math.pow(t,e)}}function Z9(e){return e<0?-Math.sqrt(-e):Math.sqrt(e)}function e7(e){return e<0?-e*e:e*e}function _y(e){var t=e(bt,bt),r=1;function n(){return r===1?e(bt,bt):r===.5?e(Z9,e7):e(vb(r),vb(1/r))}return t.exponent=function(a){return arguments.length?(r=+a,n()):r},Un(t)}function ky(){var e=_y(Wd());return e.copy=function(){return xl(e,ky()).exponent(e.exponent())},ir.apply(e,arguments),e}function t7(){return ky.apply(null,arguments).exponent(.5)}function yb(e){return Math.sign(e)*e*e}function r7(e){return Math.sign(e)*Math.sqrt(Math.abs(e))}function F_(){var e=xy(),t=[0,1],r=!1,n;function a(i){var s=r7(e(i));return isNaN(s)?n:r?Math.round(s):s}return a.invert=function(i){return e.invert(yb(i))},a.domain=function(i){return arguments.length?(e.domain(i),a):e.domain()},a.range=function(i){return arguments.length?(e.range((t=Array.from(i,vu)).map(yb)),a):t.slice()},a.rangeRound=function(i){return a.range(i).round(!0)},a.round=function(i){return arguments.length?(r=!!i,a):r},a.clamp=function(i){return arguments.length?(e.clamp(i),a):e.clamp()},a.unknown=function(i){return arguments.length?(n=i,a):n},a.copy=function(){return F_(e.domain(),t).round(r).clamp(e.clamp()).unknown(n)},ir.apply(a,arguments),Un(a)}function z_(){var e=[],t=[],r=[],n;function a(){var s=0,l=Math.max(1,t.length);for(r=new Array(l-1);++s<l;)r[s-1]=s9(e,s/l);return i}function i(s){return s==null||isNaN(s=+s)?n:t[yl(r,s)]}return i.invertExtent=function(s){var l=t.indexOf(s);return l<0?[NaN,NaN]:[l>0?r[l-1]:e[0],l<r.length?r[l]:e[e.length-1]]},i.domain=function(s){if(!arguments.length)return e.slice();e=[];for(let l of s)l!=null&&!isNaN(l=+l)&&e.push(l);return e.sort(Mn),a()},i.range=function(s){return arguments.length?(t=Array.from(s),a()):t.slice()},i.unknown=function(s){return arguments.length?(n=s,i):n},i.quantiles=function(){return r.slice()},i.copy=function(){return z_().domain(e).range(t).unknown(n)},ir.apply(i,arguments)}function W_(){var e=0,t=1,r=1,n=[.5],a=[0,1],i;function s(c){return c!=null&&c<=c?a[yl(n,c,0,r)]:i}function l(){var c=-1;for(n=new Array(r);++c<r;)n[c]=((c+1)*t-(c-r)*e)/(r+1);return s}return s.domain=function(c){return arguments.length?([e,t]=c,e=+e,t=+t,l()):[e,t]},s.range=function(c){return arguments.length?(r=(a=Array.from(c)).length-1,l()):a.slice()},s.invertExtent=function(c){var u=a.indexOf(c);return u<0?[NaN,NaN]:u<1?[e,n[0]]:u>=r?[n[r-1],t]:[n[u-1],n[u]]},s.unknown=function(c){return arguments.length&&(i=c),s},s.thresholds=function(){return n.slice()},s.copy=function(){return W_().domain([e,t]).range(a).unknown(i)},ir.apply(Un(s),arguments)}function U_(){var e=[.5],t=[0,1],r,n=1;function a(i){return i!=null&&i<=i?t[yl(e,i,0,n)]:r}return a.domain=function(i){return arguments.length?(e=Array.from(i),n=Math.min(e.length,t.length-1),a):e.slice()},a.range=function(i){return arguments.length?(t=Array.from(i),n=Math.min(e.length,t.length-1),a):t.slice()},a.invertExtent=function(i){var s=t.indexOf(i);return[e[s-1],e[s]]},a.unknown=function(i){return arguments.length?(r=i,a):r},a.copy=function(){return U_().domain(e).range(t).unknown(r)},ir.apply(a,arguments)}const th=new Date,rh=new Date;function Xe(e,t,r,n){function a(i){return e(i=arguments.length===0?new Date:new Date(+i)),i}return a.floor=i=>(e(i=new Date(+i)),i),a.ceil=i=>(e(i=new Date(i-1)),t(i,1),e(i),i),a.round=i=>{const s=a(i),l=a.ceil(i);return i-s<l-i?s:l},a.offset=(i,s)=>(t(i=new Date(+i),s==null?1:Math.floor(s)),i),a.range=(i,s,l)=>{const c=[];if(i=a.ceil(i),l=l==null?1:Math.floor(l),!(i<s)||!(l>0))return c;let u;do c.push(u=new Date(+i)),t(i,l),e(i);while(u<i&&i<s);return c},a.filter=i=>Xe(s=>{if(s>=s)for(;e(s),!i(s);)s.setTime(s-1)},(s,l)=>{if(s>=s)if(l<0)for(;++l<=0;)for(;t(s,-1),!i(s););else for(;--l>=0;)for(;t(s,1),!i(s););}),r&&(a.count=(i,s)=>(th.setTime(+i),rh.setTime(+s),e(th),e(rh),Math.floor(r(th,rh))),a.every=i=>(i=Math.floor(i),!isFinite(i)||!(i>0)?null:i>1?a.filter(n?s=>n(s)%i===0:s=>a.count(0,s)%i===0):a)),a}const bu=Xe(()=>{},(e,t)=>{e.setTime(+e+t)},(e,t)=>t-e);bu.every=e=>(e=Math.floor(e),!isFinite(e)||!(e>0)?null:e>1?Xe(t=>{t.setTime(Math.floor(t/e)*e)},(t,r)=>{t.setTime(+t+r*e)},(t,r)=>(r-t)/e):bu);bu.range;const Hr=1e3,Qt=Hr*60,Kr=Qt*60,tn=Kr*24,Oy=tn*7,gb=tn*30,nh=tn*365,la=Xe(e=>{e.setTime(e-e.getMilliseconds())},(e,t)=>{e.setTime(+e+t*Hr)},(e,t)=>(t-e)/Hr,e=>e.getUTCSeconds());la.range;const Ny=Xe(e=>{e.setTime(e-e.getMilliseconds()-e.getSeconds()*Hr)},(e,t)=>{e.setTime(+e+t*Qt)},(e,t)=>(t-e)/Qt,e=>e.getMinutes());Ny.range;const Py=Xe(e=>{e.setUTCSeconds(0,0)},(e,t)=>{e.setTime(+e+t*Qt)},(e,t)=>(t-e)/Qt,e=>e.getUTCMinutes());Py.range;const Ay=Xe(e=>{e.setTime(e-e.getMilliseconds()-e.getSeconds()*Hr-e.getMinutes()*Qt)},(e,t)=>{e.setTime(+e+t*Kr)},(e,t)=>(t-e)/Kr,e=>e.getHours());Ay.range;const Cy=Xe(e=>{e.setUTCMinutes(0,0,0)},(e,t)=>{e.setTime(+e+t*Kr)},(e,t)=>(t-e)/Kr,e=>e.getUTCHours());Cy.range;const bl=Xe(e=>e.setHours(0,0,0,0),(e,t)=>e.setDate(e.getDate()+t),(e,t)=>(t-e-(t.getTimezoneOffset()-e.getTimezoneOffset())*Qt)/tn,e=>e.getDate()-1);bl.range;const Ud=Xe(e=>{e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCDate(e.getUTCDate()+t)},(e,t)=>(t-e)/tn,e=>e.getUTCDate()-1);Ud.range;const H_=Xe(e=>{e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCDate(e.getUTCDate()+t)},(e,t)=>(t-e)/tn,e=>Math.floor(e/tn));H_.range;function $a(e){return Xe(t=>{t.setDate(t.getDate()-(t.getDay()+7-e)%7),t.setHours(0,0,0,0)},(t,r)=>{t.setDate(t.getDate()+r*7)},(t,r)=>(r-t-(r.getTimezoneOffset()-t.getTimezoneOffset())*Qt)/Oy)}const Hd=$a(0),ju=$a(1),n7=$a(2),a7=$a(3),Ti=$a(4),i7=$a(5),o7=$a(6);Hd.range;ju.range;n7.range;a7.range;Ti.range;i7.range;o7.range;function Ta(e){return Xe(t=>{t.setUTCDate(t.getUTCDate()-(t.getUTCDay()+7-e)%7),t.setUTCHours(0,0,0,0)},(t,r)=>{t.setUTCDate(t.getUTCDate()+r*7)},(t,r)=>(r-t)/Oy)}const Kd=Ta(0),wu=Ta(1),s7=Ta(2),l7=Ta(3),Mi=Ta(4),c7=Ta(5),u7=Ta(6);Kd.range;wu.range;s7.range;l7.range;Mi.range;c7.range;u7.range;const Ey=Xe(e=>{e.setDate(1),e.setHours(0,0,0,0)},(e,t)=>{e.setMonth(e.getMonth()+t)},(e,t)=>t.getMonth()-e.getMonth()+(t.getFullYear()-e.getFullYear())*12,e=>e.getMonth());Ey.range;const $y=Xe(e=>{e.setUTCDate(1),e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCMonth(e.getUTCMonth()+t)},(e,t)=>t.getUTCMonth()-e.getUTCMonth()+(t.getUTCFullYear()-e.getUTCFullYear())*12,e=>e.getUTCMonth());$y.range;const rn=Xe(e=>{e.setMonth(0,1),e.setHours(0,0,0,0)},(e,t)=>{e.setFullYear(e.getFullYear()+t)},(e,t)=>t.getFullYear()-e.getFullYear(),e=>e.getFullYear());rn.every=e=>!isFinite(e=Math.floor(e))||!(e>0)?null:Xe(t=>{t.setFullYear(Math.floor(t.getFullYear()/e)*e),t.setMonth(0,1),t.setHours(0,0,0,0)},(t,r)=>{t.setFullYear(t.getFullYear()+r*e)});rn.range;const nn=Xe(e=>{e.setUTCMonth(0,1),e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCFullYear(e.getUTCFullYear()+t)},(e,t)=>t.getUTCFullYear()-e.getUTCFullYear(),e=>e.getUTCFullYear());nn.every=e=>!isFinite(e=Math.floor(e))||!(e>0)?null:Xe(t=>{t.setUTCFullYear(Math.floor(t.getUTCFullYear()/e)*e),t.setUTCMonth(0,1),t.setUTCHours(0,0,0,0)},(t,r)=>{t.setUTCFullYear(t.getUTCFullYear()+r*e)});nn.range;function K_(e,t,r,n,a,i){const s=[[la,1,Hr],[la,5,5*Hr],[la,15,15*Hr],[la,30,30*Hr],[i,1,Qt],[i,5,5*Qt],[i,15,15*Qt],[i,30,30*Qt],[a,1,Kr],[a,3,3*Kr],[a,6,6*Kr],[a,12,12*Kr],[n,1,tn],[n,2,2*tn],[r,1,Oy],[t,1,gb],[t,3,3*gb],[e,1,nh]];function l(u,f,d){const h=f<u;h&&([u,f]=[f,u]);const p=d&&typeof d.range=="function"?d:c(u,f,d),g=p?p.range(u,+f+1):[];return h?g.reverse():g}function c(u,f,d){const h=Math.abs(f-u)/d,p=py(([,,b])=>b).right(s,h);if(p===s.length)return e.every(Hp(u/nh,f/nh,d));if(p===0)return bu.every(Math.max(Hp(u,f,d),1));const[g,y]=s[h/s[p-1][2]<s[p][2]/h?p-1:p];return g.every(y)}return[l,c]}const[d7,f7]=K_(nn,$y,Kd,H_,Cy,Py),[h7,p7]=K_(rn,Ey,Hd,bl,Ay,Ny);function ah(e){if(0<=e.y&&e.y<100){var t=new Date(-1,e.m,e.d,e.H,e.M,e.S,e.L);return t.setFullYear(e.y),t}return new Date(e.y,e.m,e.d,e.H,e.M,e.S,e.L)}function ih(e){if(0<=e.y&&e.y<100){var t=new Date(Date.UTC(-1,e.m,e.d,e.H,e.M,e.S,e.L));return t.setUTCFullYear(e.y),t}return new Date(Date.UTC(e.y,e.m,e.d,e.H,e.M,e.S,e.L))}function Co(e,t,r){return{y:e,m:t,d:r,H:0,M:0,S:0,L:0}}function m7(e){var t=e.dateTime,r=e.date,n=e.time,a=e.periods,i=e.days,s=e.shortDays,l=e.months,c=e.shortMonths,u=Eo(a),f=$o(a),d=Eo(i),h=$o(i),p=Eo(s),g=$o(s),y=Eo(l),b=$o(l),v=Eo(c),m=$o(c),x={a:M,A:I,b:R,B:F,c:null,d:_b,e:_b,f:R7,g:Y7,G:X7,H:I7,I:L7,j:D7,L:V_,m:B7,M:F7,p:K,q:z,Q:Nb,s:Pb,S:z7,u:W7,U:U7,V:H7,w:K7,W:V7,x:null,X:null,y:G7,Y:q7,Z:Q7,"%":Ob},S={a:q,A:ie,b:he,B:ge,c:null,d:kb,e:kb,f:tz,g:dz,G:hz,H:J7,I:Z7,j:ez,L:Y_,m:rz,M:nz,p:Qe,q:Ae,Q:Nb,s:Pb,S:az,u:iz,U:oz,V:sz,w:lz,W:cz,x:null,X:null,y:uz,Y:fz,Z:pz,"%":Ob},j={a:k,A:E,b:T,B:D,c:A,d:wb,e:wb,f:E7,g:jb,G:bb,H:Sb,I:Sb,j:N7,L:C7,m:O7,M:P7,p:N,q:k7,Q:T7,s:M7,S:A7,u:b7,U:j7,V:w7,w:x7,W:S7,x:L,X:C,y:jb,Y:bb,Z:_7,"%":$7};x.x=w(r,x),x.X=w(n,x),x.c=w(t,x),S.x=w(r,S),S.X=w(n,S),S.c=w(t,S);function w(V,Z){return function(re){var W=[],Te=-1,oe=0,We=V.length,Ue,_t,cn;for(re instanceof Date||(re=new Date(+re));++Te<We;)V.charCodeAt(Te)===37&&(W.push(V.slice(oe,Te)),(_t=xb[Ue=V.charAt(++Te)])!=null?Ue=V.charAt(++Te):_t=Ue==="e"?" ":"0",(cn=Z[Ue])&&(Ue=cn(re,_t)),W.push(Ue),oe=Te+1);return W.push(V.slice(oe,Te)),W.join("")}}function _(V,Z){return function(re){var W=Co(1900,void 0,1),Te=O(W,V,re+="",0),oe,We;if(Te!=re.length)return null;if("Q"in W)return new Date(W.Q);if("s"in W)return new Date(W.s*1e3+("L"in W?W.L:0));if(Z&&!("Z"in W)&&(W.Z=0),"p"in W&&(W.H=W.H%12+W.p*12),W.m===void 0&&(W.m="q"in W?W.q:0),"V"in W){if(W.V<1||W.V>53)return null;"w"in W||(W.w=1),"Z"in W?(oe=ih(Co(W.y,0,1)),We=oe.getUTCDay(),oe=We>4||We===0?wu.ceil(oe):wu(oe),oe=Ud.offset(oe,(W.V-1)*7),W.y=oe.getUTCFullYear(),W.m=oe.getUTCMonth(),W.d=oe.getUTCDate()+(W.w+6)%7):(oe=ah(Co(W.y,0,1)),We=oe.getDay(),oe=We>4||We===0?ju.ceil(oe):ju(oe),oe=bl.offset(oe,(W.V-1)*7),W.y=oe.getFullYear(),W.m=oe.getMonth(),W.d=oe.getDate()+(W.w+6)%7)}else("W"in W||"U"in W)&&("w"in W||(W.w="u"in W?W.u%7:"W"in W?1:0),We="Z"in W?ih(Co(W.y,0,1)).getUTCDay():ah(Co(W.y,0,1)).getDay(),W.m=0,W.d="W"in W?(W.w+6)%7+W.W*7-(We+5)%7:W.w+W.U*7-(We+6)%7);return"Z"in W?(W.H+=W.Z/100|0,W.M+=W.Z%100,ih(W)):ah(W)}}function O(V,Z,re,W){for(var Te=0,oe=Z.length,We=re.length,Ue,_t;Te<oe;){if(W>=We)return-1;if(Ue=Z.charCodeAt(Te++),Ue===37){if(Ue=Z.charAt(Te++),_t=j[Ue in xb?Z.charAt(Te++):Ue],!_t||(W=_t(V,re,W))<0)return-1}else if(Ue!=re.charCodeAt(W++))return-1}return W}function N(V,Z,re){var W=u.exec(Z.slice(re));return W?(V.p=f.get(W[0].toLowerCase()),re+W[0].length):-1}function k(V,Z,re){var W=p.exec(Z.slice(re));return W?(V.w=g.get(W[0].toLowerCase()),re+W[0].length):-1}function E(V,Z,re){var W=d.exec(Z.slice(re));return W?(V.w=h.get(W[0].toLowerCase()),re+W[0].length):-1}function T(V,Z,re){var W=v.exec(Z.slice(re));return W?(V.m=m.get(W[0].toLowerCase()),re+W[0].length):-1}function D(V,Z,re){var W=y.exec(Z.slice(re));return W?(V.m=b.get(W[0].toLowerCase()),re+W[0].length):-1}function A(V,Z,re){return O(V,t,Z,re)}function L(V,Z,re){return O(V,r,Z,re)}function C(V,Z,re){return O(V,n,Z,re)}function M(V){return s[V.getDay()]}function I(V){return i[V.getDay()]}function R(V){return c[V.getMonth()]}function F(V){return l[V.getMonth()]}function K(V){return a[+(V.getHours()>=12)]}function z(V){return 1+~~(V.getMonth()/3)}function q(V){return s[V.getUTCDay()]}function ie(V){return i[V.getUTCDay()]}function he(V){return c[V.getUTCMonth()]}function ge(V){return l[V.getUTCMonth()]}function Qe(V){return a[+(V.getUTCHours()>=12)]}function Ae(V){return 1+~~(V.getUTCMonth()/3)}return{format:function(V){var Z=w(V+="",x);return Z.toString=function(){return V},Z},parse:function(V){var Z=_(V+="",!1);return Z.toString=function(){return V},Z},utcFormat:function(V){var Z=w(V+="",S);return Z.toString=function(){return V},Z},utcParse:function(V){var Z=_(V+="",!0);return Z.toString=function(){return V},Z}}}var xb={"-":"",_:" ",0:"0"},at=/^\s*\d+/,v7=/^%/,y7=/[\\^$*+?|[\]().{}]/g;function le(e,t,r){var n=e<0?"-":"",a=(n?-e:e)+"",i=a.length;return n+(i<r?new Array(r-i+1).join(t)+a:a)}function g7(e){return e.replace(y7,"\\$&")}function Eo(e){return new RegExp("^(?:"+e.map(g7).join("|")+")","i")}function $o(e){return new Map(e.map((t,r)=>[t.toLowerCase(),r]))}function x7(e,t,r){var n=at.exec(t.slice(r,r+1));return n?(e.w=+n[0],r+n[0].length):-1}function b7(e,t,r){var n=at.exec(t.slice(r,r+1));return n?(e.u=+n[0],r+n[0].length):-1}function j7(e,t,r){var n=at.exec(t.slice(r,r+2));return n?(e.U=+n[0],r+n[0].length):-1}function w7(e,t,r){var n=at.exec(t.slice(r,r+2));return n?(e.V=+n[0],r+n[0].length):-1}function S7(e,t,r){var n=at.exec(t.slice(r,r+2));return n?(e.W=+n[0],r+n[0].length):-1}function bb(e,t,r){var n=at.exec(t.slice(r,r+4));return n?(e.y=+n[0],r+n[0].length):-1}function jb(e,t,r){var n=at.exec(t.slice(r,r+2));return n?(e.y=+n[0]+(+n[0]>68?1900:2e3),r+n[0].length):-1}function _7(e,t,r){var n=/^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(t.slice(r,r+6));return n?(e.Z=n[1]?0:-(n[2]+(n[3]||"00")),r+n[0].length):-1}function k7(e,t,r){var n=at.exec(t.slice(r,r+1));return n?(e.q=n[0]*3-3,r+n[0].length):-1}function O7(e,t,r){var n=at.exec(t.slice(r,r+2));return n?(e.m=n[0]-1,r+n[0].length):-1}function wb(e,t,r){var n=at.exec(t.slice(r,r+2));return n?(e.d=+n[0],r+n[0].length):-1}function N7(e,t,r){var n=at.exec(t.slice(r,r+3));return n?(e.m=0,e.d=+n[0],r+n[0].length):-1}function Sb(e,t,r){var n=at.exec(t.slice(r,r+2));return n?(e.H=+n[0],r+n[0].length):-1}function P7(e,t,r){var n=at.exec(t.slice(r,r+2));return n?(e.M=+n[0],r+n[0].length):-1}function A7(e,t,r){var n=at.exec(t.slice(r,r+2));return n?(e.S=+n[0],r+n[0].length):-1}function C7(e,t,r){var n=at.exec(t.slice(r,r+3));return n?(e.L=+n[0],r+n[0].length):-1}function E7(e,t,r){var n=at.exec(t.slice(r,r+6));return n?(e.L=Math.floor(n[0]/1e3),r+n[0].length):-1}function $7(e,t,r){var n=v7.exec(t.slice(r,r+1));return n?r+n[0].length:-1}function T7(e,t,r){var n=at.exec(t.slice(r));return n?(e.Q=+n[0],r+n[0].length):-1}function M7(e,t,r){var n=at.exec(t.slice(r));return n?(e.s=+n[0],r+n[0].length):-1}function _b(e,t){return le(e.getDate(),t,2)}function I7(e,t){return le(e.getHours(),t,2)}function L7(e,t){return le(e.getHours()%12||12,t,2)}function D7(e,t){return le(1+bl.count(rn(e),e),t,3)}function V_(e,t){return le(e.getMilliseconds(),t,3)}function R7(e,t){return V_(e,t)+"000"}function B7(e,t){return le(e.getMonth()+1,t,2)}function F7(e,t){return le(e.getMinutes(),t,2)}function z7(e,t){return le(e.getSeconds(),t,2)}function W7(e){var t=e.getDay();return t===0?7:t}function U7(e,t){return le(Hd.count(rn(e)-1,e),t,2)}function G_(e){var t=e.getDay();return t>=4||t===0?Ti(e):Ti.ceil(e)}function H7(e,t){return e=G_(e),le(Ti.count(rn(e),e)+(rn(e).getDay()===4),t,2)}function K7(e){return e.getDay()}function V7(e,t){return le(ju.count(rn(e)-1,e),t,2)}function G7(e,t){return le(e.getFullYear()%100,t,2)}function Y7(e,t){return e=G_(e),le(e.getFullYear()%100,t,2)}function q7(e,t){return le(e.getFullYear()%1e4,t,4)}function X7(e,t){var r=e.getDay();return e=r>=4||r===0?Ti(e):Ti.ceil(e),le(e.getFullYear()%1e4,t,4)}function Q7(e){var t=e.getTimezoneOffset();return(t>0?"-":(t*=-1,"+"))+le(t/60|0,"0",2)+le(t%60,"0",2)}function kb(e,t){return le(e.getUTCDate(),t,2)}function J7(e,t){return le(e.getUTCHours(),t,2)}function Z7(e,t){return le(e.getUTCHours()%12||12,t,2)}function ez(e,t){return le(1+Ud.count(nn(e),e),t,3)}function Y_(e,t){return le(e.getUTCMilliseconds(),t,3)}function tz(e,t){return Y_(e,t)+"000"}function rz(e,t){return le(e.getUTCMonth()+1,t,2)}function nz(e,t){return le(e.getUTCMinutes(),t,2)}function az(e,t){return le(e.getUTCSeconds(),t,2)}function iz(e){var t=e.getUTCDay();return t===0?7:t}function oz(e,t){return le(Kd.count(nn(e)-1,e),t,2)}function q_(e){var t=e.getUTCDay();return t>=4||t===0?Mi(e):Mi.ceil(e)}function sz(e,t){return e=q_(e),le(Mi.count(nn(e),e)+(nn(e).getUTCDay()===4),t,2)}function lz(e){return e.getUTCDay()}function cz(e,t){return le(wu.count(nn(e)-1,e),t,2)}function uz(e,t){return le(e.getUTCFullYear()%100,t,2)}function dz(e,t){return e=q_(e),le(e.getUTCFullYear()%100,t,2)}function fz(e,t){return le(e.getUTCFullYear()%1e4,t,4)}function hz(e,t){var r=e.getUTCDay();return e=r>=4||r===0?Mi(e):Mi.ceil(e),le(e.getUTCFullYear()%1e4,t,4)}function pz(){return"+0000"}function Ob(){return"%"}function Nb(e){return+e}function Pb(e){return Math.floor(+e/1e3)}var Ba,X_,Q_;mz({dateTime:"%x, %X",date:"%-m/%-d/%Y",time:"%-I:%M:%S %p",periods:["AM","PM"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]});function mz(e){return Ba=m7(e),X_=Ba.format,Ba.parse,Q_=Ba.utcFormat,Ba.utcParse,Ba}function vz(e){return new Date(e)}function yz(e){return e instanceof Date?+e:+new Date(+e)}function Ty(e,t,r,n,a,i,s,l,c,u){var f=xy(),d=f.invert,h=f.domain,p=u(".%L"),g=u(":%S"),y=u("%I:%M"),b=u("%I %p"),v=u("%a %d"),m=u("%b %d"),x=u("%B"),S=u("%Y");function j(w){return(c(w)<w?p:l(w)<w?g:s(w)<w?y:i(w)<w?b:n(w)<w?a(w)<w?v:m:r(w)<w?x:S)(w)}return f.invert=function(w){return new Date(d(w))},f.domain=function(w){return arguments.length?h(Array.from(w,yz)):h().map(vz)},f.ticks=function(w){var _=h();return e(_[0],_[_.length-1],w??10)},f.tickFormat=function(w,_){return _==null?j:u(_)},f.nice=function(w){var _=h();return(!w||typeof w.range!="function")&&(w=t(_[0],_[_.length-1],w??10)),w?h(D_(_,w)):f},f.copy=function(){return xl(f,Ty(e,t,r,n,a,i,s,l,c,u))},f}function gz(){return ir.apply(Ty(h7,p7,rn,Ey,Hd,bl,Ay,Ny,la,X_).domain([new Date(2e3,0,1),new Date(2e3,0,2)]),arguments)}function xz(){return ir.apply(Ty(d7,f7,nn,$y,Kd,Ud,Cy,Py,la,Q_).domain([Date.UTC(2e3,0,1),Date.UTC(2e3,0,2)]),arguments)}function Vd(){var e=0,t=1,r,n,a,i,s=bt,l=!1,c;function u(d){return d==null||isNaN(d=+d)?c:s(a===0?.5:(d=(i(d)-r)*a,l?Math.max(0,Math.min(1,d)):d))}u.domain=function(d){return arguments.length?([e,t]=d,r=i(e=+e),n=i(t=+t),a=r===n?0:1/(n-r),u):[e,t]},u.clamp=function(d){return arguments.length?(l=!!d,u):l},u.interpolator=function(d){return arguments.length?(s=d,u):s};function f(d){return function(h){var p,g;return arguments.length?([p,g]=h,s=d(p,g),u):[s(0),s(1)]}}return u.range=f(mo),u.rangeRound=f(gy),u.unknown=function(d){return arguments.length?(c=d,u):c},function(d){return i=d,r=d(e),n=d(t),a=r===n?0:1/(n-r),u}}function Hn(e,t){return t.domain(e.domain()).interpolator(e.interpolator()).clamp(e.clamp()).unknown(e.unknown())}function J_(){var e=Un(Vd()(bt));return e.copy=function(){return Hn(e,J_())},ln.apply(e,arguments)}function Z_(){var e=wy(Vd()).domain([1,10]);return e.copy=function(){return Hn(e,Z_()).base(e.base())},ln.apply(e,arguments)}function ek(){var e=Sy(Vd());return e.copy=function(){return Hn(e,ek()).constant(e.constant())},ln.apply(e,arguments)}function My(){var e=_y(Vd());return e.copy=function(){return Hn(e,My()).exponent(e.exponent())},ln.apply(e,arguments)}function bz(){return My.apply(null,arguments).exponent(.5)}function tk(){var e=[],t=bt;function r(n){if(n!=null&&!isNaN(n=+n))return t((yl(e,n,1)-1)/(e.length-1))}return r.domain=function(n){if(!arguments.length)return e.slice();e=[];for(let a of n)a!=null&&!isNaN(a=+a)&&e.push(a);return e.sort(Mn),r},r.interpolator=function(n){return arguments.length?(t=n,r):t},r.range=function(){return e.map((n,a)=>t(a/(e.length-1)))},r.quantiles=function(n){return Array.from({length:n+1},(a,i)=>o9(e,i/n))},r.copy=function(){return tk(t).domain(e)},ln.apply(r,arguments)}function Gd(){var e=0,t=.5,r=1,n=1,a,i,s,l,c,u=bt,f,d=!1,h;function p(y){return isNaN(y=+y)?h:(y=.5+((y=+f(y))-i)*(n*y<n*i?l:c),u(d?Math.max(0,Math.min(1,y)):y))}p.domain=function(y){return arguments.length?([e,t,r]=y,a=f(e=+e),i=f(t=+t),s=f(r=+r),l=a===i?0:.5/(i-a),c=i===s?0:.5/(s-i),n=i<a?-1:1,p):[e,t,r]},p.clamp=function(y){return arguments.length?(d=!!y,p):d},p.interpolator=function(y){return arguments.length?(u=y,p):u};function g(y){return function(b){var v,m,x;return arguments.length?([v,m,x]=b,u=$9(y,[v,m,x]),p):[u(0),u(.5),u(1)]}}return p.range=g(mo),p.rangeRound=g(gy),p.unknown=function(y){return arguments.length?(h=y,p):h},function(y){return f=y,a=y(e),i=y(t),s=y(r),l=a===i?0:.5/(i-a),c=i===s?0:.5/(s-i),n=i<a?-1:1,p}}function rk(){var e=Un(Gd()(bt));return e.copy=function(){return Hn(e,rk())},ln.apply(e,arguments)}function nk(){var e=wy(Gd()).domain([.1,1,10]);return e.copy=function(){return Hn(e,nk()).base(e.base())},ln.apply(e,arguments)}function ak(){var e=Sy(Gd());return e.copy=function(){return Hn(e,ak()).constant(e.constant())},ln.apply(e,arguments)}function Iy(){var e=_y(Gd());return e.copy=function(){return Hn(e,Iy()).exponent(e.exponent())},ln.apply(e,arguments)}function jz(){return Iy.apply(null,arguments).exponent(.5)}const Ab=Object.freeze(Object.defineProperty({__proto__:null,scaleBand:Ts,scaleDiverging:rk,scaleDivergingLog:nk,scaleDivergingPow:Iy,scaleDivergingSqrt:jz,scaleDivergingSymlog:ak,scaleIdentity:L_,scaleImplicit:Kp,scaleLinear:xu,scaleLog:R_,scaleOrdinal:my,scalePoint:rs,scalePow:ky,scaleQuantile:z_,scaleQuantize:W_,scaleRadial:F_,scaleSequential:J_,scaleSequentialLog:Z_,scaleSequentialPow:My,scaleSequentialQuantile:tk,scaleSequentialSqrt:bz,scaleSequentialSymlog:ek,scaleSqrt:t7,scaleSymlog:B_,scaleThreshold:U_,scaleTime:gz,scaleUtc:xz,tickFormat:I_},Symbol.toStringTag,{value:"Module"}));var wz=ao;function Sz(e,t,r){for(var n=-1,a=e.length;++n<a;){var i=e[n],s=t(i);if(s!=null&&(l===void 0?s===s&&!wz(s):r(s,l)))var l=s,c=i}return c}var Yd=Sz;function _z(e,t){return e>t}var ik=_z,kz=Yd,Oz=ik,Nz=po;function Pz(e){return e&&e.length?kz(e,Nz,Oz):void 0}var Az=Pz;const wn=de(Az);function Cz(e,t){return e<t}var ok=Cz,Ez=Yd,$z=ok,Tz=po;function Mz(e){return e&&e.length?Ez(e,Tz,$z):void 0}var Iz=Mz;const qd=de(Iz);var Lz=qv,Dz=Ir,Rz=m_,Bz=$t;function Fz(e,t){var r=Bz(e)?Lz:Rz;return r(e,Dz(t))}var zz=Fz,Wz=h_,Uz=zz;function Hz(e,t){return Wz(Uz(e,t),1)}var Kz=Hz;const Vz=de(Kz);var Gz=uy;function Yz(e,t){return Gz(e,t)}var qz=Yz;const _a=de(qz);var vo=1e9,Xz={precision:20,rounding:4,toExpNeg:-7,toExpPos:21,LN10:"2.302585092994045684017991454684364207601101488628772976033327900967572609677352480235997205089598298341967784042286"},Dy,Pe=!0,rr="[DecimalError] ",ma=rr+"Invalid argument: ",Ly=rr+"Exponent out of range: ",yo=Math.floor,ta=Math.pow,Qz=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,Lt,Ze=1e7,_e=7,sk=9007199254740991,Su=yo(sk/_e),Y={};Y.absoluteValue=Y.abs=function(){var e=new this.constructor(this);return e.s&&(e.s=1),e};Y.comparedTo=Y.cmp=function(e){var t,r,n,a,i=this;if(e=new i.constructor(e),i.s!==e.s)return i.s||-e.s;if(i.e!==e.e)return i.e>e.e^i.s<0?1:-1;for(n=i.d.length,a=e.d.length,t=0,r=n<a?n:a;t<r;++t)if(i.d[t]!==e.d[t])return i.d[t]>e.d[t]^i.s<0?1:-1;return n===a?0:n>a^i.s<0?1:-1};Y.decimalPlaces=Y.dp=function(){var e=this,t=e.d.length-1,r=(t-e.e)*_e;if(t=e.d[t],t)for(;t%10==0;t/=10)r--;return r<0?0:r};Y.dividedBy=Y.div=function(e){return qr(this,new this.constructor(e))};Y.dividedToIntegerBy=Y.idiv=function(e){var t=this,r=t.constructor;return ve(qr(t,new r(e),0,1),r.precision)};Y.equals=Y.eq=function(e){return!this.cmp(e)};Y.exponent=function(){return ze(this)};Y.greaterThan=Y.gt=function(e){return this.cmp(e)>0};Y.greaterThanOrEqualTo=Y.gte=function(e){return this.cmp(e)>=0};Y.isInteger=Y.isint=function(){return this.e>this.d.length-2};Y.isNegative=Y.isneg=function(){return this.s<0};Y.isPositive=Y.ispos=function(){return this.s>0};Y.isZero=function(){return this.s===0};Y.lessThan=Y.lt=function(e){return this.cmp(e)<0};Y.lessThanOrEqualTo=Y.lte=function(e){return this.cmp(e)<1};Y.logarithm=Y.log=function(e){var t,r=this,n=r.constructor,a=n.precision,i=a+5;if(e===void 0)e=new n(10);else if(e=new n(e),e.s<1||e.eq(Lt))throw Error(rr+"NaN");if(r.s<1)throw Error(rr+(r.s?"NaN":"-Infinity"));return r.eq(Lt)?new n(0):(Pe=!1,t=qr(Rs(r,i),Rs(e,i),i),Pe=!0,ve(t,a))};Y.minus=Y.sub=function(e){var t=this;return e=new t.constructor(e),t.s==e.s?uk(t,e):lk(t,(e.s=-e.s,e))};Y.modulo=Y.mod=function(e){var t,r=this,n=r.constructor,a=n.precision;if(e=new n(e),!e.s)throw Error(rr+"NaN");return r.s?(Pe=!1,t=qr(r,e,0,1).times(e),Pe=!0,r.minus(t)):ve(new n(r),a)};Y.naturalExponential=Y.exp=function(){return ck(this)};Y.naturalLogarithm=Y.ln=function(){return Rs(this)};Y.negated=Y.neg=function(){var e=new this.constructor(this);return e.s=-e.s||0,e};Y.plus=Y.add=function(e){var t=this;return e=new t.constructor(e),t.s==e.s?lk(t,e):uk(t,(e.s=-e.s,e))};Y.precision=Y.sd=function(e){var t,r,n,a=this;if(e!==void 0&&e!==!!e&&e!==1&&e!==0)throw Error(ma+e);if(t=ze(a)+1,n=a.d.length-1,r=n*_e+1,n=a.d[n],n){for(;n%10==0;n/=10)r--;for(n=a.d[0];n>=10;n/=10)r++}return e&&t>r?t:r};Y.squareRoot=Y.sqrt=function(){var e,t,r,n,a,i,s,l=this,c=l.constructor;if(l.s<1){if(!l.s)return new c(0);throw Error(rr+"NaN")}for(e=ze(l),Pe=!1,a=Math.sqrt(+l),a==0||a==1/0?(t=Or(l.d),(t.length+e)%2==0&&(t+="0"),a=Math.sqrt(t),e=yo((e+1)/2)-(e<0||e%2),a==1/0?t="5e"+e:(t=a.toExponential(),t=t.slice(0,t.indexOf("e")+1)+e),n=new c(t)):n=new c(a.toString()),r=c.precision,a=s=r+3;;)if(i=n,n=i.plus(qr(l,i,s+2)).times(.5),Or(i.d).slice(0,s)===(t=Or(n.d)).slice(0,s)){if(t=t.slice(s-3,s+1),a==s&&t=="4999"){if(ve(i,r+1,0),i.times(i).eq(l)){n=i;break}}else if(t!="9999")break;s+=4}return Pe=!0,ve(n,r)};Y.times=Y.mul=function(e){var t,r,n,a,i,s,l,c,u,f=this,d=f.constructor,h=f.d,p=(e=new d(e)).d;if(!f.s||!e.s)return new d(0);for(e.s*=f.s,r=f.e+e.e,c=h.length,u=p.length,c<u&&(i=h,h=p,p=i,s=c,c=u,u=s),i=[],s=c+u,n=s;n--;)i.push(0);for(n=u;--n>=0;){for(t=0,a=c+n;a>n;)l=i[a]+p[n]*h[a-n-1]+t,i[a--]=l%Ze|0,t=l/Ze|0;i[a]=(i[a]+t)%Ze|0}for(;!i[--s];)i.pop();return t?++r:i.shift(),e.d=i,e.e=r,Pe?ve(e,d.precision):e};Y.toDecimalPlaces=Y.todp=function(e,t){var r=this,n=r.constructor;return r=new n(r),e===void 0?r:(Tr(e,0,vo),t===void 0?t=n.rounding:Tr(t,0,8),ve(r,e+ze(r)+1,t))};Y.toExponential=function(e,t){var r,n=this,a=n.constructor;return e===void 0?r=ka(n,!0):(Tr(e,0,vo),t===void 0?t=a.rounding:Tr(t,0,8),n=ve(new a(n),e+1,t),r=ka(n,!0,e+1)),r};Y.toFixed=function(e,t){var r,n,a=this,i=a.constructor;return e===void 0?ka(a):(Tr(e,0,vo),t===void 0?t=i.rounding:Tr(t,0,8),n=ve(new i(a),e+ze(a)+1,t),r=ka(n.abs(),!1,e+ze(n)+1),a.isneg()&&!a.isZero()?"-"+r:r)};Y.toInteger=Y.toint=function(){var e=this,t=e.constructor;return ve(new t(e),ze(e)+1,t.rounding)};Y.toNumber=function(){return+this};Y.toPower=Y.pow=function(e){var t,r,n,a,i,s,l=this,c=l.constructor,u=12,f=+(e=new c(e));if(!e.s)return new c(Lt);if(l=new c(l),!l.s){if(e.s<1)throw Error(rr+"Infinity");return l}if(l.eq(Lt))return l;if(n=c.precision,e.eq(Lt))return ve(l,n);if(t=e.e,r=e.d.length-1,s=t>=r,i=l.s,s){if((r=f<0?-f:f)<=sk){for(a=new c(Lt),t=Math.ceil(n/_e+4),Pe=!1;r%2&&(a=a.times(l),Eb(a.d,t)),r=yo(r/2),r!==0;)l=l.times(l),Eb(l.d,t);return Pe=!0,e.s<0?new c(Lt).div(a):ve(a,n)}}else if(i<0)throw Error(rr+"NaN");return i=i<0&&e.d[Math.max(t,r)]&1?-1:1,l.s=1,Pe=!1,a=e.times(Rs(l,n+u)),Pe=!0,a=ck(a),a.s=i,a};Y.toPrecision=function(e,t){var r,n,a=this,i=a.constructor;return e===void 0?(r=ze(a),n=ka(a,r<=i.toExpNeg||r>=i.toExpPos)):(Tr(e,1,vo),t===void 0?t=i.rounding:Tr(t,0,8),a=ve(new i(a),e,t),r=ze(a),n=ka(a,e<=r||r<=i.toExpNeg,e)),n};Y.toSignificantDigits=Y.tosd=function(e,t){var r=this,n=r.constructor;return e===void 0?(e=n.precision,t=n.rounding):(Tr(e,1,vo),t===void 0?t=n.rounding:Tr(t,0,8)),ve(new n(r),e,t)};Y.toString=Y.valueOf=Y.val=Y.toJSON=Y[Symbol.for("nodejs.util.inspect.custom")]=function(){var e=this,t=ze(e),r=e.constructor;return ka(e,t<=r.toExpNeg||t>=r.toExpPos)};function lk(e,t){var r,n,a,i,s,l,c,u,f=e.constructor,d=f.precision;if(!e.s||!t.s)return t.s||(t=new f(e)),Pe?ve(t,d):t;if(c=e.d,u=t.d,s=e.e,a=t.e,c=c.slice(),i=s-a,i){for(i<0?(n=c,i=-i,l=u.length):(n=u,a=s,l=c.length),s=Math.ceil(d/_e),l=s>l?s+1:l+1,i>l&&(i=l,n.length=1),n.reverse();i--;)n.push(0);n.reverse()}for(l=c.length,i=u.length,l-i<0&&(i=l,n=u,u=c,c=n),r=0;i;)r=(c[--i]=c[i]+u[i]+r)/Ze|0,c[i]%=Ze;for(r&&(c.unshift(r),++a),l=c.length;c[--l]==0;)c.pop();return t.d=c,t.e=a,Pe?ve(t,d):t}function Tr(e,t,r){if(e!==~~e||e<t||e>r)throw Error(ma+e)}function Or(e){var t,r,n,a=e.length-1,i="",s=e[0];if(a>0){for(i+=s,t=1;t<a;t++)n=e[t]+"",r=_e-n.length,r&&(i+=mn(r)),i+=n;s=e[t],n=s+"",r=_e-n.length,r&&(i+=mn(r))}else if(s===0)return"0";for(;s%10===0;)s/=10;return i+s}var qr=function(){function e(n,a){var i,s=0,l=n.length;for(n=n.slice();l--;)i=n[l]*a+s,n[l]=i%Ze|0,s=i/Ze|0;return s&&n.unshift(s),n}function t(n,a,i,s){var l,c;if(i!=s)c=i>s?1:-1;else for(l=c=0;l<i;l++)if(n[l]!=a[l]){c=n[l]>a[l]?1:-1;break}return c}function r(n,a,i){for(var s=0;i--;)n[i]-=s,s=n[i]<a[i]?1:0,n[i]=s*Ze+n[i]-a[i];for(;!n[0]&&n.length>1;)n.shift()}return function(n,a,i,s){var l,c,u,f,d,h,p,g,y,b,v,m,x,S,j,w,_,O,N=n.constructor,k=n.s==a.s?1:-1,E=n.d,T=a.d;if(!n.s)return new N(n);if(!a.s)throw Error(rr+"Division by zero");for(c=n.e-a.e,_=T.length,j=E.length,p=new N(k),g=p.d=[],u=0;T[u]==(E[u]||0);)++u;if(T[u]>(E[u]||0)&&--c,i==null?m=i=N.precision:s?m=i+(ze(n)-ze(a))+1:m=i,m<0)return new N(0);if(m=m/_e+2|0,u=0,_==1)for(f=0,T=T[0],m++;(u<j||f)&&m--;u++)x=f*Ze+(E[u]||0),g[u]=x/T|0,f=x%T|0;else{for(f=Ze/(T[0]+1)|0,f>1&&(T=e(T,f),E=e(E,f),_=T.length,j=E.length),S=_,y=E.slice(0,_),b=y.length;b<_;)y[b++]=0;O=T.slice(),O.unshift(0),w=T[0],T[1]>=Ze/2&&++w;do f=0,l=t(T,y,_,b),l<0?(v=y[0],_!=b&&(v=v*Ze+(y[1]||0)),f=v/w|0,f>1?(f>=Ze&&(f=Ze-1),d=e(T,f),h=d.length,b=y.length,l=t(d,y,h,b),l==1&&(f--,r(d,_<h?O:T,h))):(f==0&&(l=f=1),d=T.slice()),h=d.length,h<b&&d.unshift(0),r(y,d,b),l==-1&&(b=y.length,l=t(T,y,_,b),l<1&&(f++,r(y,_<b?O:T,b))),b=y.length):l===0&&(f++,y=[0]),g[u++]=f,l&&y[0]?y[b++]=E[S]||0:(y=[E[S]],b=1);while((S++<j||y[0]!==void 0)&&m--)}return g[0]||g.shift(),p.e=c,ve(p,s?i+ze(p)+1:i)}}();function ck(e,t){var r,n,a,i,s,l,c=0,u=0,f=e.constructor,d=f.precision;if(ze(e)>16)throw Error(Ly+ze(e));if(!e.s)return new f(Lt);for(Pe=!1,l=d,s=new f(.03125);e.abs().gte(.1);)e=e.times(s),u+=5;for(n=Math.log(ta(2,u))/Math.LN10*2+5|0,l+=n,r=a=i=new f(Lt),f.precision=l;;){if(a=ve(a.times(e),l),r=r.times(++c),s=i.plus(qr(a,r,l)),Or(s.d).slice(0,l)===Or(i.d).slice(0,l)){for(;u--;)i=ve(i.times(i),l);return f.precision=d,t==null?(Pe=!0,ve(i,d)):i}i=s}}function ze(e){for(var t=e.e*_e,r=e.d[0];r>=10;r/=10)t++;return t}function oh(e,t,r){if(t>e.LN10.sd())throw Pe=!0,r&&(e.precision=r),Error(rr+"LN10 precision limit exceeded");return ve(new e(e.LN10),t)}function mn(e){for(var t="";e--;)t+="0";return t}function Rs(e,t){var r,n,a,i,s,l,c,u,f,d=1,h=10,p=e,g=p.d,y=p.constructor,b=y.precision;if(p.s<1)throw Error(rr+(p.s?"NaN":"-Infinity"));if(p.eq(Lt))return new y(0);if(t==null?(Pe=!1,u=b):u=t,p.eq(10))return t==null&&(Pe=!0),oh(y,u);if(u+=h,y.precision=u,r=Or(g),n=r.charAt(0),i=ze(p),Math.abs(i)<15e14){for(;n<7&&n!=1||n==1&&r.charAt(1)>3;)p=p.times(e),r=Or(p.d),n=r.charAt(0),d++;i=ze(p),n>1?(p=new y("0."+r),i++):p=new y(n+"."+r.slice(1))}else return c=oh(y,u+2,b).times(i+""),p=Rs(new y(n+"."+r.slice(1)),u-h).plus(c),y.precision=b,t==null?(Pe=!0,ve(p,b)):p;for(l=s=p=qr(p.minus(Lt),p.plus(Lt),u),f=ve(p.times(p),u),a=3;;){if(s=ve(s.times(f),u),c=l.plus(qr(s,new y(a),u)),Or(c.d).slice(0,u)===Or(l.d).slice(0,u))return l=l.times(2),i!==0&&(l=l.plus(oh(y,u+2,b).times(i+""))),l=qr(l,new y(d),u),y.precision=b,t==null?(Pe=!0,ve(l,b)):l;l=c,a+=2}}function Cb(e,t){var r,n,a;for((r=t.indexOf("."))>-1&&(t=t.replace(".","")),(n=t.search(/e/i))>0?(r<0&&(r=n),r+=+t.slice(n+1),t=t.substring(0,n)):r<0&&(r=t.length),n=0;t.charCodeAt(n)===48;)++n;for(a=t.length;t.charCodeAt(a-1)===48;)--a;if(t=t.slice(n,a),t){if(a-=n,r=r-n-1,e.e=yo(r/_e),e.d=[],n=(r+1)%_e,r<0&&(n+=_e),n<a){for(n&&e.d.push(+t.slice(0,n)),a-=_e;n<a;)e.d.push(+t.slice(n,n+=_e));t=t.slice(n),n=_e-t.length}else n-=a;for(;n--;)t+="0";if(e.d.push(+t),Pe&&(e.e>Su||e.e<-Su))throw Error(Ly+r)}else e.s=0,e.e=0,e.d=[0];return e}function ve(e,t,r){var n,a,i,s,l,c,u,f,d=e.d;for(s=1,i=d[0];i>=10;i/=10)s++;if(n=t-s,n<0)n+=_e,a=t,u=d[f=0];else{if(f=Math.ceil((n+1)/_e),i=d.length,f>=i)return e;for(u=i=d[f],s=1;i>=10;i/=10)s++;n%=_e,a=n-_e+s}if(r!==void 0&&(i=ta(10,s-a-1),l=u/i%10|0,c=t<0||d[f+1]!==void 0||u%i,c=r<4?(l||c)&&(r==0||r==(e.s<0?3:2)):l>5||l==5&&(r==4||c||r==6&&(n>0?a>0?u/ta(10,s-a):0:d[f-1])%10&1||r==(e.s<0?8:7))),t<1||!d[0])return c?(i=ze(e),d.length=1,t=t-i-1,d[0]=ta(10,(_e-t%_e)%_e),e.e=yo(-t/_e)||0):(d.length=1,d[0]=e.e=e.s=0),e;if(n==0?(d.length=f,i=1,f--):(d.length=f+1,i=ta(10,_e-n),d[f]=a>0?(u/ta(10,s-a)%ta(10,a)|0)*i:0),c)for(;;)if(f==0){(d[0]+=i)==Ze&&(d[0]=1,++e.e);break}else{if(d[f]+=i,d[f]!=Ze)break;d[f--]=0,i=1}for(n=d.length;d[--n]===0;)d.pop();if(Pe&&(e.e>Su||e.e<-Su))throw Error(Ly+ze(e));return e}function uk(e,t){var r,n,a,i,s,l,c,u,f,d,h=e.constructor,p=h.precision;if(!e.s||!t.s)return t.s?t.s=-t.s:t=new h(e),Pe?ve(t,p):t;if(c=e.d,d=t.d,n=t.e,u=e.e,c=c.slice(),s=u-n,s){for(f=s<0,f?(r=c,s=-s,l=d.length):(r=d,n=u,l=c.length),a=Math.max(Math.ceil(p/_e),l)+2,s>a&&(s=a,r.length=1),r.reverse(),a=s;a--;)r.push(0);r.reverse()}else{for(a=c.length,l=d.length,f=a<l,f&&(l=a),a=0;a<l;a++)if(c[a]!=d[a]){f=c[a]<d[a];break}s=0}for(f&&(r=c,c=d,d=r,t.s=-t.s),l=c.length,a=d.length-l;a>0;--a)c[l++]=0;for(a=d.length;a>s;){if(c[--a]<d[a]){for(i=a;i&&c[--i]===0;)c[i]=Ze-1;--c[i],c[a]+=Ze}c[a]-=d[a]}for(;c[--l]===0;)c.pop();for(;c[0]===0;c.shift())--n;return c[0]?(t.d=c,t.e=n,Pe?ve(t,p):t):new h(0)}function ka(e,t,r){var n,a=ze(e),i=Or(e.d),s=i.length;return t?(r&&(n=r-s)>0?i=i.charAt(0)+"."+i.slice(1)+mn(n):s>1&&(i=i.charAt(0)+"."+i.slice(1)),i=i+(a<0?"e":"e+")+a):a<0?(i="0."+mn(-a-1)+i,r&&(n=r-s)>0&&(i+=mn(n))):a>=s?(i+=mn(a+1-s),r&&(n=r-a-1)>0&&(i=i+"."+mn(n))):((n=a+1)<s&&(i=i.slice(0,n)+"."+i.slice(n)),r&&(n=r-s)>0&&(a+1===s&&(i+="."),i+=mn(n))),e.s<0?"-"+i:i}function Eb(e,t){if(e.length>t)return e.length=t,!0}function dk(e){var t,r,n;function a(i){var s=this;if(!(s instanceof a))return new a(i);if(s.constructor=a,i instanceof a){s.s=i.s,s.e=i.e,s.d=(i=i.d)?i.slice():i;return}if(typeof i=="number"){if(i*0!==0)throw Error(ma+i);if(i>0)s.s=1;else if(i<0)i=-i,s.s=-1;else{s.s=0,s.e=0,s.d=[0];return}if(i===~~i&&i<1e7){s.e=0,s.d=[i];return}return Cb(s,i.toString())}else if(typeof i!="string")throw Error(ma+i);if(i.charCodeAt(0)===45?(i=i.slice(1),s.s=-1):s.s=1,Qz.test(i))Cb(s,i);else throw Error(ma+i)}if(a.prototype=Y,a.ROUND_UP=0,a.ROUND_DOWN=1,a.ROUND_CEIL=2,a.ROUND_FLOOR=3,a.ROUND_HALF_UP=4,a.ROUND_HALF_DOWN=5,a.ROUND_HALF_EVEN=6,a.ROUND_HALF_CEIL=7,a.ROUND_HALF_FLOOR=8,a.clone=dk,a.config=a.set=Jz,e===void 0&&(e={}),e)for(n=["precision","rounding","toExpNeg","toExpPos","LN10"],t=0;t<n.length;)e.hasOwnProperty(r=n[t++])||(e[r]=this[r]);return a.config(e),a}function Jz(e){if(!e||typeof e!="object")throw Error(rr+"Object expected");var t,r,n,a=["precision",1,vo,"rounding",0,8,"toExpNeg",-1/0,0,"toExpPos",0,1/0];for(t=0;t<a.length;t+=3)if((n=e[r=a[t]])!==void 0)if(yo(n)===n&&n>=a[t+1]&&n<=a[t+2])this[r]=n;else throw Error(ma+r+": "+n);if((n=e[r="LN10"])!==void 0)if(n==Math.LN10)this[r]=new this(n);else throw Error(ma+r+": "+n);return this}var Dy=dk(Xz);Lt=new Dy(1);const pe=Dy;function Zz(e){return nW(e)||rW(e)||tW(e)||eW()}function eW(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
-In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function tW(e,t){if(e){if(typeof e=="string")return qp(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return qp(e,t)}}function rW(e){if(typeof Symbol<"u"&&Symbol.iterator in Object(e))return Array.from(e)}function nW(e){if(Array.isArray(e))return qp(e)}function qp(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}var aW=function(t){return t},fk={},hk=function(t){return t===fk},$b=function(t){return function r(){return arguments.length===0||arguments.length===1&&hk(arguments.length<=0?void 0:arguments[0])?r:t.apply(void 0,arguments)}},iW=function e(t,r){return t===1?r:$b(function(){for(var n=arguments.length,a=new Array(n),i=0;i<n;i++)a[i]=arguments[i];var s=a.filter(function(l){return l!==fk}).length;return s>=t?r.apply(void 0,a):e(t-s,$b(function(){for(var l=arguments.length,c=new Array(l),u=0;u<l;u++)c[u]=arguments[u];var f=a.map(function(d){return hk(d)?c.shift():d});return r.apply(void 0,Zz(f).concat(c))}))})},Xd=function(t){return iW(t.length,t)},Xp=function(t,r){for(var n=[],a=t;a<r;++a)n[a-t]=a;return n},oW=Xd(function(e,t){return Array.isArray(t)?t.map(e):Object.keys(t).map(function(r){return t[r]}).map(e)}),sW=function(){for(var t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];if(!r.length)return aW;var a=r.reverse(),i=a[0],s=a.slice(1);return function(){return s.reduce(function(l,c){return c(l)},i.apply(void 0,arguments))}},Qp=function(t){return Array.isArray(t)?t.reverse():t.split("").reverse.join("")},pk=function(t){var r=null,n=null;return function(){for(var a=arguments.length,i=new Array(a),s=0;s<a;s++)i[s]=arguments[s];return r&&i.every(function(l,c){return l===r[c]})||(r=i,n=t.apply(void 0,i)),n}};function lW(e){var t;return e===0?t=1:t=Math.floor(new pe(e).abs().log(10).toNumber())+1,t}function cW(e,t,r){for(var n=new pe(e),a=0,i=[];n.lt(t)&&a<1e5;)i.push(n.toNumber()),n=n.add(r),a++;return i}var uW=Xd(function(e,t,r){var n=+e,a=+t;return n+r*(a-n)}),dW=Xd(function(e,t,r){var n=t-+e;return n=n||1/0,(r-e)/n}),fW=Xd(function(e,t,r){var n=t-+e;return n=n||1/0,Math.max(0,Math.min(1,(r-e)/n))});const Qd={rangeStep:cW,getDigitCount:lW,interpolateNumber:uW,uninterpolateNumber:dW,uninterpolateTruncation:fW};function Jp(e){return mW(e)||pW(e)||mk(e)||hW()}function hW(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
-In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function pW(e){if(typeof Symbol<"u"&&Symbol.iterator in Object(e))return Array.from(e)}function mW(e){if(Array.isArray(e))return Zp(e)}function Bs(e,t){return gW(e)||yW(e,t)||mk(e,t)||vW()}function vW(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
-In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function mk(e,t){if(e){if(typeof e=="string")return Zp(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return Zp(e,t)}}function Zp(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function yW(e,t){if(!(typeof Symbol>"u"||!(Symbol.iterator in Object(e)))){var r=[],n=!0,a=!1,i=void 0;try{for(var s=e[Symbol.iterator](),l;!(n=(l=s.next()).done)&&(r.push(l.value),!(t&&r.length===t));n=!0);}catch(c){a=!0,i=c}finally{try{!n&&s.return!=null&&s.return()}finally{if(a)throw i}}return r}}function gW(e){if(Array.isArray(e))return e}function vk(e){var t=Bs(e,2),r=t[0],n=t[1],a=r,i=n;return r>n&&(a=n,i=r),[a,i]}function yk(e,t,r){if(e.lte(0))return new pe(0);var n=Qd.getDigitCount(e.toNumber()),a=new pe(10).pow(n),i=e.div(a),s=n!==1?.05:.1,l=new pe(Math.ceil(i.div(s).toNumber())).add(r).mul(s),c=l.mul(a);return t?c:new pe(Math.ceil(c))}function xW(e,t,r){var n=1,a=new pe(e);if(!a.isint()&&r){var i=Math.abs(e);i<1?(n=new pe(10).pow(Qd.getDigitCount(e)-1),a=new pe(Math.floor(a.div(n).toNumber())).mul(n)):i>1&&(a=new pe(Math.floor(e)))}else e===0?a=new pe(Math.floor((t-1)/2)):r||(a=new pe(Math.floor(e)));var s=Math.floor((t-1)/2),l=sW(oW(function(c){return a.add(new pe(c-s).mul(n)).toNumber()}),Xp);return l(0,t)}function gk(e,t,r,n){var a=arguments.length>4&&arguments[4]!==void 0?arguments[4]:0;if(!Number.isFinite((t-e)/(r-1)))return{step:new pe(0),tickMin:new pe(0),tickMax:new pe(0)};var i=yk(new pe(t).sub(e).div(r-1),n,a),s;e<=0&&t>=0?s=new pe(0):(s=new pe(e).add(t).div(2),s=s.sub(new pe(s).mod(i)));var l=Math.ceil(s.sub(e).div(i).toNumber()),c=Math.ceil(new pe(t).sub(s).div(i).toNumber()),u=l+c+1;return u>r?gk(e,t,r,n,a+1):(u<r&&(c=t>0?c+(r-u):c,l=t>0?l:l+(r-u)),{step:i,tickMin:s.sub(new pe(l).mul(i)),tickMax:s.add(new pe(c).mul(i))})}function bW(e){var t=Bs(e,2),r=t[0],n=t[1],a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:6,i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,s=Math.max(a,2),l=vk([r,n]),c=Bs(l,2),u=c[0],f=c[1];if(u===-1/0||f===1/0){var d=f===1/0?[u].concat(Jp(Xp(0,a-1).map(function(){return 1/0}))):[].concat(Jp(Xp(0,a-1).map(function(){return-1/0})),[f]);return r>n?Qp(d):d}if(u===f)return xW(u,a,i);var h=gk(u,f,s,i),p=h.step,g=h.tickMin,y=h.tickMax,b=Qd.rangeStep(g,y.add(new pe(.1).mul(p)),p);return r>n?Qp(b):b}function jW(e,t){var r=Bs(e,2),n=r[0],a=r[1],i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,s=vk([n,a]),l=Bs(s,2),c=l[0],u=l[1];if(c===-1/0||u===1/0)return[n,a];if(c===u)return[c];var f=Math.max(t,2),d=yk(new pe(u).sub(c).div(f-1),i,0),h=[].concat(Jp(Qd.rangeStep(new pe(c),new pe(u).sub(new pe(.99).mul(d)),d)),[u]);return n>a?Qp(h):h}var wW=pk(bW),SW=pk(jW),_W="Invariant failed";function Oa(e,t){throw new Error(_W)}var kW=["offset","layout","width","dataKey","data","dataPointFormatter","xAxis","yAxis"];function Ii(e){"@babel/helpers - typeof";return Ii=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Ii(e)}function _u(){return _u=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},_u.apply(this,arguments)}function OW(e,t){return CW(e)||AW(e,t)||PW(e,t)||NW()}function NW(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
-In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function PW(e,t){if(e){if(typeof e=="string")return Tb(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return Tb(e,t)}}function Tb(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function AW(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,a,i,s,l=[],c=!0,u=!1;try{if(i=(r=r.call(e)).next,t!==0)for(;!(c=(n=i.call(r)).done)&&(l.push(n.value),l.length!==t);c=!0);}catch(f){u=!0,a=f}finally{try{if(!c&&r.return!=null&&(s=r.return(),Object(s)!==s))return}finally{if(u)throw a}}return l}}function CW(e){if(Array.isArray(e))return e}function EW(e,t){if(e==null)return{};var r=$W(e,t),n,a;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(a=0;a<i.length;a++)n=i[a],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function $W(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function TW(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function MW(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,jk(n.key),n)}}function IW(e,t,r){return t&&MW(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function LW(e,t,r){return t=ku(t),DW(e,xk()?Reflect.construct(t,r||[],ku(e).constructor):t.apply(e,r))}function DW(e,t){if(t&&(Ii(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return RW(e)}function RW(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function xk(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(xk=function(){return!!e})()}function ku(e){return ku=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},ku(e)}function BW(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&em(e,t)}function em(e,t){return em=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,a){return n.__proto__=a,n},em(e,t)}function bk(e,t,r){return t=jk(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function jk(e){var t=FW(e,"string");return Ii(t)=="symbol"?t:t+""}function FW(e,t){if(Ii(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(Ii(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}var Jd=function(e){function t(){return TW(this,t),LW(this,t,arguments)}return BW(t,e),IW(t,[{key:"render",value:function(){var n=this.props,a=n.offset,i=n.layout,s=n.width,l=n.dataKey,c=n.data,u=n.dataPointFormatter,f=n.xAxis,d=n.yAxis,h=EW(n,kW),p=X(h,!1);this.props.direction==="x"&&f.type!=="number"&&Oa();var g=c.map(function(y){var b=u(y,l),v=b.x,m=b.y,x=b.value,S=b.errorVal;if(!S)return null;var j=[],w,_;if(Array.isArray(S)){var O=OW(S,2);w=O[0],_=O[1]}else w=_=S;if(i==="vertical"){var N=f.scale,k=m+a,E=k+s,T=k-s,D=N(x-w),A=N(x+_);j.push({x1:A,y1:E,x2:A,y2:T}),j.push({x1:D,y1:k,x2:A,y2:k}),j.push({x1:D,y1:E,x2:D,y2:T})}else if(i==="horizontal"){var L=d.scale,C=v+a,M=C-s,I=C+s,R=L(x-w),F=L(x+_);j.push({x1:M,y1:F,x2:I,y2:F}),j.push({x1:C,y1:R,x2:C,y2:F}),j.push({x1:M,y1:R,x2:I,y2:R})}return $.createElement(ne,_u({className:"recharts-errorBar",key:"bar-".concat(j.map(function(K){return"".concat(K.x1,"-").concat(K.x2,"-").concat(K.y1,"-").concat(K.y2)}))},p),j.map(function(K){return $.createElement("line",_u({},K,{key:"line-".concat(K.x1,"-").concat(K.x2,"-").concat(K.y1,"-").concat(K.y2)}))}))});return $.createElement(ne,{className:"recharts-errorBars"},g)}}])}($.Component);bk(Jd,"defaultProps",{stroke:"black",strokeWidth:1.5,width:5,offset:0,layout:"horizontal"});bk(Jd,"displayName","ErrorBar");function Fs(e){"@babel/helpers - typeof";return Fs=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Fs(e)}function Mb(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function Yn(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Mb(Object(r),!0).forEach(function(n){zW(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Mb(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function zW(e,t,r){return t=WW(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function WW(e){var t=UW(e,"string");return Fs(t)=="symbol"?t:t+""}function UW(e,t){if(Fs(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(Fs(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var wk=function(t){var r=t.children,n=t.formattedGraphicalItems,a=t.legendWidth,i=t.legendContent,s=It(r,vi);if(!s)return null;var l=vi.defaultProps,c=l!==void 0?Yn(Yn({},l),s.props):{},u;return s.props&&s.props.payload?u=s.props&&s.props.payload:i==="children"?u=(n||[]).reduce(function(f,d){var h=d.item,p=d.props,g=p.sectors||p.data||[];return f.concat(g.map(function(y){return{type:s.props.iconType||h.props.legendType,value:y.name,color:y.fill,payload:y}}))},[]):u=(n||[]).map(function(f){var d=f.item,h=d.type.defaultProps,p=h!==void 0?Yn(Yn({},h),d.props):{},g=p.dataKey,y=p.name,b=p.legendType,v=p.hide;return{inactive:v,dataKey:g,type:c.iconType||b||"square",color:Ry(d),value:y||g,payload:p}}),Yn(Yn(Yn({},c),vi.getWithHeight(s,a)),{},{payload:u,item:s})};function zs(e){"@babel/helpers - typeof";return zs=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},zs(e)}function Ib(e){return GW(e)||VW(e)||KW(e)||HW()}function HW(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
-In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function KW(e,t){if(e){if(typeof e=="string")return tm(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return tm(e,t)}}function VW(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function GW(e){if(Array.isArray(e))return tm(e)}function tm(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function Lb(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function Ie(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Lb(Object(r),!0).forEach(function(n){gi(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Lb(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function gi(e,t,r){return t=YW(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function YW(e){var t=qW(e,"string");return zs(t)=="symbol"?t:t+""}function qW(e,t){if(zs(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(zs(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Be(e,t,r){return te(e)||te(t)?r:qe(t)?Bt(e,t,r):Q(t)?t(e):r}function ns(e,t,r,n){var a=Vz(e,function(l){return Be(l,t)});if(r==="number"){var i=a.filter(function(l){return U(l)||parseFloat(l)});return i.length?[qd(i),wn(i)]:[1/0,-1/0]}var s=n?a.filter(function(l){return!te(l)}):a;return s.map(function(l){return qe(l)||l instanceof Date?l:""})}var XW=function(t){var r,n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[],a=arguments.length>2?arguments[2]:void 0,i=arguments.length>3?arguments[3]:void 0,s=-1,l=(r=n==null?void 0:n.length)!==null&&r!==void 0?r:0;if(l<=1)return 0;if(i&&i.axisType==="angleAxis"&&Math.abs(Math.abs(i.range[1]-i.range[0])-360)<=1e-6)for(var c=i.range,u=0;u<l;u++){var f=u>0?a[u-1].coordinate:a[l-1].coordinate,d=a[u].coordinate,h=u>=l-1?a[0].coordinate:a[u+1].coordinate,p=void 0;if(rt(d-f)!==rt(h-d)){var g=[];if(rt(h-d)===rt(c[1]-c[0])){p=h;var y=d+c[1]-c[0];g[0]=Math.min(y,(y+f)/2),g[1]=Math.max(y,(y+f)/2)}else{p=f;var b=h+c[1]-c[0];g[0]=Math.min(d,(b+d)/2),g[1]=Math.max(d,(b+d)/2)}var v=[Math.min(d,(p+d)/2),Math.max(d,(p+d)/2)];if(t>v[0]&&t<=v[1]||t>=g[0]&&t<=g[1]){s=a[u].index;break}}else{var m=Math.min(f,h),x=Math.max(f,h);if(t>(m+d)/2&&t<=(x+d)/2){s=a[u].index;break}}}else for(var S=0;S<l;S++)if(S===0&&t<=(n[S].coordinate+n[S+1].coordinate)/2||S>0&&S<l-1&&t>(n[S].coordinate+n[S-1].coordinate)/2&&t<=(n[S].coordinate+n[S+1].coordinate)/2||S===l-1&&t>(n[S].coordinate+n[S-1].coordinate)/2){s=n[S].index;break}return s},Ry=function(t){var r,n=t,a=n.type.displayName,i=(r=t.type)!==null&&r!==void 0&&r.defaultProps?Ie(Ie({},t.type.defaultProps),t.props):t.props,s=i.stroke,l=i.fill,c;switch(a){case"Line":c=s;break;case"Area":case"Radar":c=s&&s!=="none"?s:l;break;default:c=l;break}return c},QW=function(t){var r=t.barSize,n=t.totalSize,a=t.stackGroups,i=a===void 0?{}:a;if(!i)return{};for(var s={},l=Object.keys(i),c=0,u=l.length;c<u;c++)for(var f=i[l[c]].stackGroups,d=Object.keys(f),h=0,p=d.length;h<p;h++){var g=f[d[h]],y=g.items,b=g.cateAxisId,v=y.filter(function(_){return Yr(_.type).indexOf("Bar")>=0});if(v&&v.length){var m=v[0].type.defaultProps,x=m!==void 0?Ie(Ie({},m),v[0].props):v[0].props,S=x.barSize,j=x[b];s[j]||(s[j]=[]);var w=te(S)?r:S;s[j].push({item:v[0],stackList:v.slice(1),barSize:te(w)?void 0:xt(w,n,0)})}}return s},JW=function(t){var r=t.barGap,n=t.barCategoryGap,a=t.bandSize,i=t.sizeList,s=i===void 0?[]:i,l=t.maxBarSize,c=s.length;if(c<1)return null;var u=xt(r,a,0,!0),f,d=[];if(s[0].barSize===+s[0].barSize){var h=!1,p=a/c,g=s.reduce(function(S,j){return S+j.barSize||0},0);g+=(c-1)*u,g>=a&&(g-=(c-1)*u,u=0),g>=a&&p>0&&(h=!0,p*=.9,g=c*p);var y=(a-g)/2>>0,b={offset:y-u,size:0};f=s.reduce(function(S,j){var w={item:j.item,position:{offset:b.offset+b.size+u,size:h?p:j.barSize}},_=[].concat(Ib(S),[w]);return b=_[_.length-1].position,j.stackList&&j.stackList.length&&j.stackList.forEach(function(O){_.push({item:O,position:b})}),_},d)}else{var v=xt(n,a,0,!0);a-2*v-(c-1)*u<=0&&(u=0);var m=(a-2*v-(c-1)*u)/c;m>1&&(m>>=0);var x=l===+l?Math.min(m,l):m;f=s.reduce(function(S,j,w){var _=[].concat(Ib(S),[{item:j.item,position:{offset:v+(m+u)*w+(m-x)/2,size:x}}]);return j.stackList&&j.stackList.length&&j.stackList.forEach(function(O){_.push({item:O,position:_[_.length-1].position})}),_},d)}return f},ZW=function(t,r,n,a){var i=n.children,s=n.width,l=n.margin,c=s-(l.left||0)-(l.right||0),u=wk({children:i,legendWidth:c});if(u){var f=a||{},d=f.width,h=f.height,p=u.align,g=u.verticalAlign,y=u.layout;if((y==="vertical"||y==="horizontal"&&g==="middle")&&p!=="center"&&U(t[p]))return Ie(Ie({},t),{},gi({},p,t[p]+(d||0)));if((y==="horizontal"||y==="vertical"&&p==="center")&&g!=="middle"&&U(t[g]))return Ie(Ie({},t),{},gi({},g,t[g]+(h||0)))}return t},eU=function(t,r,n){return te(r)?!0:t==="horizontal"?r==="yAxis":t==="vertical"||n==="x"?r==="xAxis":n==="y"?r==="yAxis":!0},Sk=function(t,r,n,a,i){var s=r.props.children,l=Ft(s,Jd).filter(function(u){return eU(a,i,u.props.direction)});if(l&&l.length){var c=l.map(function(u){return u.props.dataKey});return t.reduce(function(u,f){var d=Be(f,n);if(te(d))return u;var h=Array.isArray(d)?[qd(d),wn(d)]:[d,d],p=c.reduce(function(g,y){var b=Be(f,y,0),v=h[0]-Math.abs(Array.isArray(b)?b[0]:b),m=h[1]+Math.abs(Array.isArray(b)?b[1]:b);return[Math.min(v,g[0]),Math.max(m,g[1])]},[1/0,-1/0]);return[Math.min(p[0],u[0]),Math.max(p[1],u[1])]},[1/0,-1/0])}return null},tU=function(t,r,n,a,i){var s=r.map(function(l){return Sk(t,l,n,i,a)}).filter(function(l){return!te(l)});return s&&s.length?s.reduce(function(l,c){return[Math.min(l[0],c[0]),Math.max(l[1],c[1])]},[1/0,-1/0]):null},_k=function(t,r,n,a,i){var s=r.map(function(c){var u=c.props.dataKey;return n==="number"&&u&&Sk(t,c,u,a)||ns(t,u,n,i)});if(n==="number")return s.reduce(function(c,u){return[Math.min(c[0],u[0]),Math.max(c[1],u[1])]},[1/0,-1/0]);var l={};return s.reduce(function(c,u){for(var f=0,d=u.length;f<d;f++)l[u[f]]||(l[u[f]]=!0,c.push(u[f]));return c},[])},kk=function(t,r){return t==="horizontal"&&r==="xAxis"||t==="vertical"&&r==="yAxis"||t==="centric"&&r==="angleAxis"||t==="radial"&&r==="radiusAxis"},Ok=function(t,r,n,a){if(a)return t.map(function(c){return c.coordinate});var i,s,l=t.map(function(c){return c.coordinate===r&&(i=!0),c.coordinate===n&&(s=!0),c.coordinate});return i||l.push(r),s||l.push(n),l},Vr=function(t,r,n){if(!t)return null;var a=t.scale,i=t.duplicateDomain,s=t.type,l=t.range,c=t.realScaleType==="scaleBand"?a.bandwidth()/2:2,u=(r||n)&&s==="category"&&a.bandwidth?a.bandwidth()/c:0;if(u=t.axisType==="angleAxis"&&(l==null?void 0:l.length)>=2?rt(l[0]-l[1])*2*u:u,r&&(t.ticks||t.niceTicks)){var f=(t.ticks||t.niceTicks).map(function(d){var h=i?i.indexOf(d):d;return{coordinate:a(h)+u,value:d,offset:u}});return f.filter(function(d){return!co(d.coordinate)})}return t.isCategorical&&t.categoricalDomain?t.categoricalDomain.map(function(d,h){return{coordinate:a(d)+u,value:d,index:h,offset:u}}):a.ticks&&!n?a.ticks(t.tickCount).map(function(d){return{coordinate:a(d)+u,value:d,offset:u}}):a.domain().map(function(d,h){return{coordinate:a(d)+u,value:i?i[d]:d,index:h,offset:u}})},sh=new WeakMap,Zl=function(t,r){if(typeof r!="function")return t;sh.has(t)||sh.set(t,new WeakMap);var n=sh.get(t);if(n.has(r))return n.get(r);var a=function(){t.apply(void 0,arguments),r.apply(void 0,arguments)};return n.set(r,a),a},Nk=function(t,r,n){var a=t.scale,i=t.type,s=t.layout,l=t.axisType;if(a==="auto")return s==="radial"&&l==="radiusAxis"?{scale:Ts(),realScaleType:"band"}:s==="radial"&&l==="angleAxis"?{scale:xu(),realScaleType:"linear"}:i==="category"&&r&&(r.indexOf("LineChart")>=0||r.indexOf("AreaChart")>=0||r.indexOf("ComposedChart")>=0&&!n)?{scale:rs(),realScaleType:"point"}:i==="category"?{scale:Ts(),realScaleType:"band"}:{scale:xu(),realScaleType:"linear"};if(wa(a)){var c="scale".concat(Id(a));return{scale:(Ab[c]||rs)(),realScaleType:Ab[c]?c:"point"}}return Q(a)?{scale:a}:{scale:rs(),realScaleType:"point"}},Db=1e-4,Pk=function(t){var r=t.domain();if(!(!r||r.length<=2)){var n=r.length,a=t.range(),i=Math.min(a[0],a[1])-Db,s=Math.max(a[0],a[1])+Db,l=t(r[0]),c=t(r[n-1]);(l<i||l>s||c<i||c>s)&&t.domain([r[0],r[n-1]])}},Ak=function(t,r){if(!t)return null;for(var n=0,a=t.length;n<a;n++)if(t[n].item===r)return t[n].position;return null},Ck=function(t,r){if(!r||r.length!==2||!U(r[0])||!U(r[1]))return t;var n=Math.min(r[0],r[1]),a=Math.max(r[0],r[1]),i=[t[0],t[1]];return(!U(t[0])||t[0]<n)&&(i[0]=n),(!U(t[1])||t[1]>a)&&(i[1]=a),i[0]>a&&(i[0]=a),i[1]<n&&(i[1]=n),i},rU=function(t){var r=t.length;if(!(r<=0))for(var n=0,a=t[0].length;n<a;++n)for(var i=0,s=0,l=0;l<r;++l){var c=co(t[l][n][1])?t[l][n][0]:t[l][n][1];c>=0?(t[l][n][0]=i,t[l][n][1]=i+c,i=t[l][n][1]):(t[l][n][0]=s,t[l][n][1]=s+c,s=t[l][n][1])}},nU=function(t){var r=t.length;if(!(r<=0))for(var n=0,a=t[0].length;n<a;++n)for(var i=0,s=0;s<r;++s){var l=co(t[s][n][1])?t[s][n][0]:t[s][n][1];l>=0?(t[s][n][0]=i,t[s][n][1]=i+l,i=t[s][n][1]):(t[s][n][0]=0,t[s][n][1]=0)}},aU={sign:rU,expand:k4,none:Ni,silhouette:O4,wiggle:N4,positive:nU},iU=function(t,r,n){var a=r.map(function(l){return l.props.dataKey}),i=aU[n],s=_4().keys(a).value(function(l,c){return+Be(l,c,0)}).order(Op).offset(i);return s(t)},oU=function(t,r,n,a,i,s){if(!t)return null;var l=s?r.reverse():r,c={},u=l.reduce(function(d,h){var p,g=(p=h.type)!==null&&p!==void 0&&p.defaultProps?Ie(Ie({},h.type.defaultProps),h.props):h.props,y=g.stackId,b=g.hide;if(b)return d;var v=g[n],m=d[v]||{hasStack:!1,stackGroups:{}};if(qe(y)){var x=m.stackGroups[y]||{numericAxisId:n,cateAxisId:a,items:[]};x.items.push(h),m.hasStack=!0,m.stackGroups[y]=x}else m.stackGroups[uo("_stackId_")]={numericAxisId:n,cateAxisId:a,items:[h]};return Ie(Ie({},d),{},gi({},v,m))},c),f={};return Object.keys(u).reduce(function(d,h){var p=u[h];if(p.hasStack){var g={};p.stackGroups=Object.keys(p.stackGroups).reduce(function(y,b){var v=p.stackGroups[b];return Ie(Ie({},y),{},gi({},b,{numericAxisId:n,cateAxisId:a,items:v.items,stackedData:iU(t,v.items,i)}))},g)}return Ie(Ie({},d),{},gi({},h,p))},f)},Ek=function(t,r){var n=r.realScaleType,a=r.type,i=r.tickCount,s=r.originalDomain,l=r.allowDecimals,c=n||r.scale;if(c!=="auto"&&c!=="linear")return null;if(i&&a==="number"&&s&&(s[0]==="auto"||s[1]==="auto")){var u=t.domain();if(!u.length)return null;var f=wW(u,i,l);return t.domain([qd(f),wn(f)]),{niceTicks:f}}if(i&&a==="number"){var d=t.domain(),h=SW(d,i,l);return{niceTicks:h}}return null};function Rb(e){var t=e.axis,r=e.ticks,n=e.bandSize,a=e.entry,i=e.index,s=e.dataKey;if(t.type==="category"){if(!t.allowDuplicatedCategory&&t.dataKey&&!te(a[t.dataKey])){var l=Qc(r,"value",a[t.dataKey]);if(l)return l.coordinate+n/2}return r[i]?r[i].coordinate+n/2:null}var c=Be(a,te(s)?t.dataKey:s);return te(c)?null:t.scale(c)}var Ou=function(t){var r=t.axis,n=t.ticks,a=t.offset,i=t.bandSize,s=t.entry,l=t.index;if(r.type==="category")return n[l]?n[l].coordinate+a:null;var c=Be(s,r.dataKey,r.domain[l]);return te(c)?null:r.scale(c)-i/2+a},$k=function(t){var r=t.numericAxis,n=r.scale.domain();if(r.type==="number"){var a=Math.min(n[0],n[1]),i=Math.max(n[0],n[1]);return a<=0&&i>=0?0:i<0?i:a}return n[0]},sU=function(t,r){var n,a=(n=t.type)!==null&&n!==void 0&&n.defaultProps?Ie(Ie({},t.type.defaultProps),t.props):t.props,i=a.stackId;if(qe(i)){var s=r[i];if(s){var l=s.items.indexOf(t);return l>=0?s.stackedData[l]:null}}return null},lU=function(t){return t.reduce(function(r,n){return[qd(n.concat([r[0]]).filter(U)),wn(n.concat([r[1]]).filter(U))]},[1/0,-1/0])},Tk=function(t,r,n){return Object.keys(t).reduce(function(a,i){var s=t[i],l=s.stackedData,c=l.reduce(function(u,f){var d=lU(f.slice(r,n+1));return[Math.min(u[0],d[0]),Math.max(u[1],d[1])]},[1/0,-1/0]);return[Math.min(c[0],a[0]),Math.max(c[1],a[1])]},[1/0,-1/0]).map(function(a){return a===1/0||a===-1/0?0:a})},Bb=/^dataMin[\s]*-[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,Fb=/^dataMax[\s]*\+[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,rm=function(t,r,n){if(Q(t))return t(r,n);if(!Array.isArray(t))return r;var a=[];if(U(t[0]))a[0]=n?t[0]:Math.min(t[0],r[0]);else if(Bb.test(t[0])){var i=+Bb.exec(t[0])[1];a[0]=r[0]-i}else Q(t[0])?a[0]=t[0](r[0]):a[0]=r[0];if(U(t[1]))a[1]=n?t[1]:Math.max(t[1],r[1]);else if(Fb.test(t[1])){var s=+Fb.exec(t[1])[1];a[1]=r[1]+s}else Q(t[1])?a[1]=t[1](r[1]):a[1]=r[1];return a},Nu=function(t,r,n){if(t&&t.scale&&t.scale.bandwidth){var a=t.scale.bandwidth();if(!n||a>0)return a}if(t&&r&&r.length>=2){for(var i=fy(r,function(d){return d.coordinate}),s=1/0,l=1,c=i.length;l<c;l++){var u=i[l],f=i[l-1];s=Math.min((u.coordinate||0)-(f.coordinate||0),s)}return s===1/0?0:s}return n?void 0:0},zb=function(t,r,n){return!t||!t.length||_a(t,Bt(n,"type.defaultProps.domain"))?r:t},By=function(t,r){var n=t.type.defaultProps?Ie(Ie({},t.type.defaultProps),t.props):t.props,a=n.dataKey,i=n.name,s=n.unit,l=n.formatter,c=n.tooltipType,u=n.chartType,f=n.hide;return Ie(Ie({},X(t,!1)),{},{dataKey:a,unit:s,formatter:l,name:i||a,color:Ry(t),value:Be(r,a),type:c,payload:r,chartType:u,hide:f})};function Ws(e){"@babel/helpers - typeof";return Ws=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Ws(e)}function Wb(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function Fr(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Wb(Object(r),!0).forEach(function(n){Mk(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Wb(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function Mk(e,t,r){return t=cU(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function cU(e){var t=uU(e,"string");return Ws(t)=="symbol"?t:t+""}function uU(e,t){if(Ws(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(Ws(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function dU(e,t){return mU(e)||pU(e,t)||hU(e,t)||fU()}function fU(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
-In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function hU(e,t){if(e){if(typeof e=="string")return Ub(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return Ub(e,t)}}function Ub(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function pU(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,a,i,s,l=[],c=!0,u=!1;try{if(i=(r=r.call(e)).next,t!==0)for(;!(c=(n=i.call(r)).done)&&(l.push(n.value),l.length!==t);c=!0);}catch(f){u=!0,a=f}finally{try{if(!c&&r.return!=null&&(s=r.return(),Object(s)!==s))return}finally{if(u)throw a}}return l}}function mU(e){if(Array.isArray(e))return e}var Pu=Math.PI/180,vU=function(t){return t*180/Math.PI},ye=function(t,r,n,a){return{x:t+Math.cos(-Pu*a)*n,y:r+Math.sin(-Pu*a)*n}},Ik=function(t,r){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{top:0,right:0,bottom:0,left:0};return Math.min(Math.abs(t-(n.left||0)-(n.right||0)),Math.abs(r-(n.top||0)-(n.bottom||0)))/2},Lk=function(t,r,n,a,i){var s=t.width,l=t.height,c=t.startAngle,u=t.endAngle,f=xt(t.cx,s,s/2),d=xt(t.cy,l,l/2),h=Ik(s,l,n),p=xt(t.innerRadius,h,0),g=xt(t.outerRadius,h,h*.8),y=Object.keys(r);return y.reduce(function(b,v){var m=r[v],x=m.domain,S=m.reversed,j;if(te(m.range))a==="angleAxis"?j=[c,u]:a==="radiusAxis"&&(j=[p,g]),S&&(j=[j[1],j[0]]);else{j=m.range;var w=j,_=dU(w,2);c=_[0],u=_[1]}var O=Nk(m,i),N=O.realScaleType,k=O.scale;k.domain(x).range(j),Pk(k);var E=Ek(k,Fr(Fr({},m),{},{realScaleType:N})),T=Fr(Fr(Fr({},m),E),{},{range:j,radius:g,realScaleType:N,scale:k,cx:f,cy:d,innerRadius:p,outerRadius:g,startAngle:c,endAngle:u});return Fr(Fr({},b),{},Mk({},v,T))},{})},yU=function(t,r){var n=t.x,a=t.y,i=r.x,s=r.y;return Math.sqrt(Math.pow(n-i,2)+Math.pow(a-s,2))},gU=function(t,r){var n=t.x,a=t.y,i=r.cx,s=r.cy,l=yU({x:n,y:a},{x:i,y:s});if(l<=0)return{radius:l};var c=(n-i)/l,u=Math.acos(c);return a>s&&(u=2*Math.PI-u),{radius:l,angle:vU(u),angleInRadian:u}},xU=function(t){var r=t.startAngle,n=t.endAngle,a=Math.floor(r/360),i=Math.floor(n/360),s=Math.min(a,i);return{startAngle:r-s*360,endAngle:n-s*360}},bU=function(t,r){var n=r.startAngle,a=r.endAngle,i=Math.floor(n/360),s=Math.floor(a/360),l=Math.min(i,s);return t+l*360},Hb=function(t,r){var n=t.x,a=t.y,i=gU({x:n,y:a},r),s=i.radius,l=i.angle,c=r.innerRadius,u=r.outerRadius;if(s<c||s>u)return!1;if(s===0)return!0;var f=xU(r),d=f.startAngle,h=f.endAngle,p=l,g;if(d<=h){for(;p>h;)p-=360;for(;p<d;)p+=360;g=p>=d&&p<=h}else{for(;p>d;)p-=360;for(;p<h;)p+=360;g=p>=h&&p<=d}return g?Fr(Fr({},r),{},{radius:s,angle:bU(p,r)}):null},Dk=function(t){return!P.isValidElement(t)&&!Q(t)&&typeof t!="boolean"?t.className:""};function Us(e){"@babel/helpers - typeof";return Us=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Us(e)}var jU=["offset"];function wU(e){return OU(e)||kU(e)||_U(e)||SU()}function SU(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
-In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function _U(e,t){if(e){if(typeof e=="string")return nm(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return nm(e,t)}}function kU(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function OU(e){if(Array.isArray(e))return nm(e)}function nm(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function NU(e,t){if(e==null)return{};var r=PU(e,t),n,a;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(a=0;a<i.length;a++)n=i[a],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function PU(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function Kb(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function Ke(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Kb(Object(r),!0).forEach(function(n){AU(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Kb(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function AU(e,t,r){return t=CU(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function CU(e){var t=EU(e,"string");return Us(t)=="symbol"?t:t+""}function EU(e,t){if(Us(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(Us(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Hs(){return Hs=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},Hs.apply(this,arguments)}var $U=function(t){var r=t.value,n=t.formatter,a=te(t.children)?r:t.children;return Q(n)?n(a):a},TU=function(t,r){var n=rt(r-t),a=Math.min(Math.abs(r-t),360);return n*a},MU=function(t,r,n){var a=t.position,i=t.viewBox,s=t.offset,l=t.className,c=i,u=c.cx,f=c.cy,d=c.innerRadius,h=c.outerRadius,p=c.startAngle,g=c.endAngle,y=c.clockWise,b=(d+h)/2,v=TU(p,g),m=v>=0?1:-1,x,S;a==="insideStart"?(x=p+m*s,S=y):a==="insideEnd"?(x=g-m*s,S=!y):a==="end"&&(x=g+m*s,S=y),S=v<=0?S:!S;var j=ye(u,f,b,x),w=ye(u,f,b,x+(S?1:-1)*359),_="M".concat(j.x,",").concat(j.y,`
- A`).concat(b,",").concat(b,",0,1,").concat(S?0:1,`,
- `).concat(w.x,",").concat(w.y),O=te(t.id)?uo("recharts-radial-line-"):t.id;return $.createElement("text",Hs({},n,{dominantBaseline:"central",className:ee("recharts-radial-bar-label",l)}),$.createElement("defs",null,$.createElement("path",{id:O,d:_})),$.createElement("textPath",{xlinkHref:"#".concat(O)},r))},IU=function(t){var r=t.viewBox,n=t.offset,a=t.position,i=r,s=i.cx,l=i.cy,c=i.innerRadius,u=i.outerRadius,f=i.startAngle,d=i.endAngle,h=(f+d)/2;if(a==="outside"){var p=ye(s,l,u+n,h),g=p.x,y=p.y;return{x:g,y,textAnchor:g>=s?"start":"end",verticalAnchor:"middle"}}if(a==="center")return{x:s,y:l,textAnchor:"middle",verticalAnchor:"middle"};if(a==="centerTop")return{x:s,y:l,textAnchor:"middle",verticalAnchor:"start"};if(a==="centerBottom")return{x:s,y:l,textAnchor:"middle",verticalAnchor:"end"};var b=(c+u)/2,v=ye(s,l,b,h),m=v.x,x=v.y;return{x:m,y:x,textAnchor:"middle",verticalAnchor:"middle"}},LU=function(t){var r=t.viewBox,n=t.parentViewBox,a=t.offset,i=t.position,s=r,l=s.x,c=s.y,u=s.width,f=s.height,d=f>=0?1:-1,h=d*a,p=d>0?"end":"start",g=d>0?"start":"end",y=u>=0?1:-1,b=y*a,v=y>0?"end":"start",m=y>0?"start":"end";if(i==="top"){var x={x:l+u/2,y:c-d*a,textAnchor:"middle",verticalAnchor:p};return Ke(Ke({},x),n?{height:Math.max(c-n.y,0),width:u}:{})}if(i==="bottom"){var S={x:l+u/2,y:c+f+h,textAnchor:"middle",verticalAnchor:g};return Ke(Ke({},S),n?{height:Math.max(n.y+n.height-(c+f),0),width:u}:{})}if(i==="left"){var j={x:l-b,y:c+f/2,textAnchor:v,verticalAnchor:"middle"};return Ke(Ke({},j),n?{width:Math.max(j.x-n.x,0),height:f}:{})}if(i==="right"){var w={x:l+u+b,y:c+f/2,textAnchor:m,verticalAnchor:"middle"};return Ke(Ke({},w),n?{width:Math.max(n.x+n.width-w.x,0),height:f}:{})}var _=n?{width:u,height:f}:{};return i==="insideLeft"?Ke({x:l+b,y:c+f/2,textAnchor:m,verticalAnchor:"middle"},_):i==="insideRight"?Ke({x:l+u-b,y:c+f/2,textAnchor:v,verticalAnchor:"middle"},_):i==="insideTop"?Ke({x:l+u/2,y:c+h,textAnchor:"middle",verticalAnchor:g},_):i==="insideBottom"?Ke({x:l+u/2,y:c+f-h,textAnchor:"middle",verticalAnchor:p},_):i==="insideTopLeft"?Ke({x:l+b,y:c+h,textAnchor:m,verticalAnchor:g},_):i==="insideTopRight"?Ke({x:l+u-b,y:c+h,textAnchor:v,verticalAnchor:g},_):i==="insideBottomLeft"?Ke({x:l+b,y:c+f-h,textAnchor:m,verticalAnchor:p},_):i==="insideBottomRight"?Ke({x:l+u-b,y:c+f-h,textAnchor:v,verticalAnchor:p},_):io(i)&&(U(i.x)||oa(i.x))&&(U(i.y)||oa(i.y))?Ke({x:l+xt(i.x,u),y:c+xt(i.y,f),textAnchor:"end",verticalAnchor:"end"},_):Ke({x:l+u/2,y:c+f/2,textAnchor:"middle",verticalAnchor:"middle"},_)},DU=function(t){return"cx"in t&&U(t.cx)};function tt(e){var t=e.offset,r=t===void 0?5:t,n=NU(e,jU),a=Ke({offset:r},n),i=a.viewBox,s=a.position,l=a.value,c=a.children,u=a.content,f=a.className,d=f===void 0?"":f,h=a.textBreakAll;if(!i||te(l)&&te(c)&&!P.isValidElement(u)&&!Q(u))return null;if(P.isValidElement(u))return P.cloneElement(u,a);var p;if(Q(u)){if(p=P.createElement(u,a),P.isValidElement(p))return p}else p=$U(a);var g=DU(i),y=X(a,!0);if(g&&(s==="insideStart"||s==="insideEnd"||s==="end"))return MU(a,p,y);var b=g?IU(a):LU(a);return $.createElement(Sa,Hs({className:ee("recharts-label",d)},y,b,{breakAll:h}),p)}tt.displayName="Label";var Rk=function(t){var r=t.cx,n=t.cy,a=t.angle,i=t.startAngle,s=t.endAngle,l=t.r,c=t.radius,u=t.innerRadius,f=t.outerRadius,d=t.x,h=t.y,p=t.top,g=t.left,y=t.width,b=t.height,v=t.clockWise,m=t.labelViewBox;if(m)return m;if(U(y)&&U(b)){if(U(d)&&U(h))return{x:d,y:h,width:y,height:b};if(U(p)&&U(g))return{x:p,y:g,width:y,height:b}}return U(d)&&U(h)?{x:d,y:h,width:0,height:0}:U(r)&&U(n)?{cx:r,cy:n,startAngle:i||a||0,endAngle:s||a||0,innerRadius:u||0,outerRadius:f||c||l||0,clockWise:v}:t.viewBox?t.viewBox:{}},RU=function(t,r){return t?t===!0?$.createElement(tt,{key:"label-implicit",viewBox:r}):qe(t)?$.createElement(tt,{key:"label-implicit",viewBox:r,value:t}):P.isValidElement(t)?t.type===tt?P.cloneElement(t,{key:"label-implicit",viewBox:r}):$.createElement(tt,{key:"label-implicit",content:t,viewBox:r}):Q(t)?$.createElement(tt,{key:"label-implicit",content:t,viewBox:r}):io(t)?$.createElement(tt,Hs({viewBox:r},t,{key:"label-implicit"})):null:null},BU=function(t,r){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;if(!t||!t.children&&n&&!t.label)return null;var a=t.children,i=Rk(t),s=Ft(a,tt).map(function(c,u){return P.cloneElement(c,{viewBox:r||i,key:"label-".concat(u)})});if(!n)return s;var l=RU(t.label,r||i);return[l].concat(wU(s))};tt.parseViewBox=Rk;tt.renderCallByParent=BU;function FU(e){var t=e==null?0:e.length;return t?e[t-1]:void 0}var zU=FU;const WU=de(zU);function Ks(e){"@babel/helpers - typeof";return Ks=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Ks(e)}var UU=["valueAccessor"],HU=["data","dataKey","clockWise","id","textBreakAll"];function KU(e){return qU(e)||YU(e)||GU(e)||VU()}function VU(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
-In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function GU(e,t){if(e){if(typeof e=="string")return am(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return am(e,t)}}function YU(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function qU(e){if(Array.isArray(e))return am(e)}function am(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function Au(){return Au=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},Au.apply(this,arguments)}function Vb(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function Gb(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Vb(Object(r),!0).forEach(function(n){XU(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Vb(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function XU(e,t,r){return t=QU(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function QU(e){var t=JU(e,"string");return Ks(t)=="symbol"?t:t+""}function JU(e,t){if(Ks(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(Ks(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Yb(e,t){if(e==null)return{};var r=ZU(e,t),n,a;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(a=0;a<i.length;a++)n=i[a],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function ZU(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}var eH=function(t){return Array.isArray(t.value)?WU(t.value):t.value};function Er(e){var t=e.valueAccessor,r=t===void 0?eH:t,n=Yb(e,UU),a=n.data,i=n.dataKey,s=n.clockWise,l=n.id,c=n.textBreakAll,u=Yb(n,HU);return!a||!a.length?null:$.createElement(ne,{className:"recharts-label-list"},a.map(function(f,d){var h=te(i)?r(f,d):Be(f&&f.payload,i),p=te(l)?{}:{id:"".concat(l,"-").concat(d)};return $.createElement(tt,Au({},X(f,!0),u,p,{parentViewBox:f.parentViewBox,value:h,textBreakAll:c,viewBox:tt.parseViewBox(te(s)?f:Gb(Gb({},f),{},{clockWise:s})),key:"label-".concat(d),index:d}))}))}Er.displayName="LabelList";function tH(e,t){return e?e===!0?$.createElement(Er,{key:"labelList-implicit",data:t}):$.isValidElement(e)||Q(e)?$.createElement(Er,{key:"labelList-implicit",data:t,content:e}):io(e)?$.createElement(Er,Au({data:t},e,{key:"labelList-implicit"})):null:null}function rH(e,t){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;if(!e||!e.children&&r&&!e.label)return null;var n=e.children,a=Ft(n,Er).map(function(s,l){return P.cloneElement(s,{data:t,key:"labelList-".concat(l)})});if(!r)return a;var i=tH(e.label,t);return[i].concat(KU(a))}Er.renderCallByParent=rH;function Vs(e){"@babel/helpers - typeof";return Vs=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Vs(e)}function im(){return im=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},im.apply(this,arguments)}function qb(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function Xb(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?qb(Object(r),!0).forEach(function(n){nH(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):qb(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function nH(e,t,r){return t=aH(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function aH(e){var t=iH(e,"string");return Vs(t)=="symbol"?t:t+""}function iH(e,t){if(Vs(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(Vs(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var oH=function(t,r){var n=rt(r-t),a=Math.min(Math.abs(r-t),359.999);return n*a},ec=function(t){var r=t.cx,n=t.cy,a=t.radius,i=t.angle,s=t.sign,l=t.isExternal,c=t.cornerRadius,u=t.cornerIsExternal,f=c*(l?1:-1)+a,d=Math.asin(c/f)/Pu,h=u?i:i+s*d,p=ye(r,n,f,h),g=ye(r,n,a,h),y=u?i-s*d:i,b=ye(r,n,f*Math.cos(d*Pu),y);return{center:p,circleTangency:g,lineTangency:b,theta:d}},Bk=function(t){var r=t.cx,n=t.cy,a=t.innerRadius,i=t.outerRadius,s=t.startAngle,l=t.endAngle,c=oH(s,l),u=s+c,f=ye(r,n,i,s),d=ye(r,n,i,u),h="M ".concat(f.x,",").concat(f.y,`
- A `).concat(i,",").concat(i,`,0,
- `).concat(+(Math.abs(c)>180),",").concat(+(s>u),`,
- `).concat(d.x,",").concat(d.y,`
- `);if(a>0){var p=ye(r,n,a,s),g=ye(r,n,a,u);h+="L ".concat(g.x,",").concat(g.y,`
- A `).concat(a,",").concat(a,`,0,
- `).concat(+(Math.abs(c)>180),",").concat(+(s<=u),`,
- `).concat(p.x,",").concat(p.y," Z")}else h+="L ".concat(r,",").concat(n," Z");return h},sH=function(t){var r=t.cx,n=t.cy,a=t.innerRadius,i=t.outerRadius,s=t.cornerRadius,l=t.forceCornerRadius,c=t.cornerIsExternal,u=t.startAngle,f=t.endAngle,d=rt(f-u),h=ec({cx:r,cy:n,radius:i,angle:u,sign:d,cornerRadius:s,cornerIsExternal:c}),p=h.circleTangency,g=h.lineTangency,y=h.theta,b=ec({cx:r,cy:n,radius:i,angle:f,sign:-d,cornerRadius:s,cornerIsExternal:c}),v=b.circleTangency,m=b.lineTangency,x=b.theta,S=c?Math.abs(u-f):Math.abs(u-f)-y-x;if(S<0)return l?"M ".concat(g.x,",").concat(g.y,`
- a`).concat(s,",").concat(s,",0,0,1,").concat(s*2,`,0
- a`).concat(s,",").concat(s,",0,0,1,").concat(-s*2,`,0
- `):Bk({cx:r,cy:n,innerRadius:a,outerRadius:i,startAngle:u,endAngle:f});var j="M ".concat(g.x,",").concat(g.y,`
- A`).concat(s,",").concat(s,",0,0,").concat(+(d<0),",").concat(p.x,",").concat(p.y,`
- A`).concat(i,",").concat(i,",0,").concat(+(S>180),",").concat(+(d<0),",").concat(v.x,",").concat(v.y,`
- A`).concat(s,",").concat(s,",0,0,").concat(+(d<0),",").concat(m.x,",").concat(m.y,`
- `);if(a>0){var w=ec({cx:r,cy:n,radius:a,angle:u,sign:d,isExternal:!0,cornerRadius:s,cornerIsExternal:c}),_=w.circleTangency,O=w.lineTangency,N=w.theta,k=ec({cx:r,cy:n,radius:a,angle:f,sign:-d,isExternal:!0,cornerRadius:s,cornerIsExternal:c}),E=k.circleTangency,T=k.lineTangency,D=k.theta,A=c?Math.abs(u-f):Math.abs(u-f)-N-D;if(A<0&&s===0)return"".concat(j,"L").concat(r,",").concat(n,"Z");j+="L".concat(T.x,",").concat(T.y,`
- A`).concat(s,",").concat(s,",0,0,").concat(+(d<0),",").concat(E.x,",").concat(E.y,`
- A`).concat(a,",").concat(a,",0,").concat(+(A>180),",").concat(+(d>0),",").concat(_.x,",").concat(_.y,`
- A`).concat(s,",").concat(s,",0,0,").concat(+(d<0),",").concat(O.x,",").concat(O.y,"Z")}else j+="L".concat(r,",").concat(n,"Z");return j},lH={cx:0,cy:0,innerRadius:0,outerRadius:0,startAngle:0,endAngle:0,cornerRadius:0,forceCornerRadius:!1,cornerIsExternal:!1},Fk=function(t){var r=Xb(Xb({},lH),t),n=r.cx,a=r.cy,i=r.innerRadius,s=r.outerRadius,l=r.cornerRadius,c=r.forceCornerRadius,u=r.cornerIsExternal,f=r.startAngle,d=r.endAngle,h=r.className;if(s<i||f===d)return null;var p=ee("recharts-sector",h),g=s-i,y=xt(l,g,0,!0),b;return y>0&&Math.abs(f-d)<360?b=sH({cx:n,cy:a,innerRadius:i,outerRadius:s,cornerRadius:Math.min(y,g/2),forceCornerRadius:c,cornerIsExternal:u,startAngle:f,endAngle:d}):b=Bk({cx:n,cy:a,innerRadius:i,outerRadius:s,startAngle:f,endAngle:d}),$.createElement("path",im({},X(r,!0),{className:p,d:b,role:"img"}))};function Gs(e){"@babel/helpers - typeof";return Gs=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Gs(e)}function om(){return om=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},om.apply(this,arguments)}function Qb(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function Jb(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Qb(Object(r),!0).forEach(function(n){cH(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Qb(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function cH(e,t,r){return t=uH(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function uH(e){var t=dH(e,"string");return Gs(t)=="symbol"?t:t+""}function dH(e,t){if(Gs(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(Gs(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var Zb={curveBasisClosed:h4,curveBasisOpen:p4,curveBasis:f4,curveBumpX:J5,curveBumpY:Z5,curveLinearClosed:m4,curveLinear:Dd,curveMonotoneX:v4,curveMonotoneY:y4,curveNatural:g4,curveStep:x4,curveStepAfter:j4,curveStepBefore:b4},tc=function(t){return t.x===+t.x&&t.y===+t.y},To=function(t){return t.x},Mo=function(t){return t.y},fH=function(t,r){if(Q(t))return t;var n="curve".concat(Id(t));return(n==="curveMonotone"||n==="curveBump")&&r?Zb["".concat(n).concat(r==="vertical"?"Y":"X")]:Zb[n]||Dd},hH=function(t){var r=t.type,n=r===void 0?"linear":r,a=t.points,i=a===void 0?[]:a,s=t.baseLine,l=t.layout,c=t.connectNulls,u=c===void 0?!1:c,f=fH(n,l),d=u?i.filter(function(y){return tc(y)}):i,h;if(Array.isArray(s)){var p=u?s.filter(function(y){return tc(y)}):s,g=d.map(function(y,b){return Jb(Jb({},y),{},{base:p[b]})});return l==="vertical"?h=Kl().y(Mo).x1(To).x0(function(y){return y.base.x}):h=Kl().x(To).y1(Mo).y0(function(y){return y.base.y}),h.defined(tc).curve(f),h(g)}return l==="vertical"&&U(s)?h=Kl().y(Mo).x1(To).x0(s):U(s)?h=Kl().x(To).y1(Mo).y0(s):h=$S().x(To).y(Mo),h.defined(tc).curve(f),h(d)},xi=function(t){var r=t.className,n=t.points,a=t.path,i=t.pathRef;if((!n||!n.length)&&!a)return null;var s=n&&n.length?hH(t):a;return P.createElement("path",om({},X(t,!1),Jc(t),{className:ee("recharts-curve",r),d:s,ref:i}))},zk={exports:{}},pH="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED",mH=pH,vH=mH;function Wk(){}function Uk(){}Uk.resetWarningCache=Wk;var yH=function(){function e(n,a,i,s,l,c){if(c!==vH){var u=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types");throw u.name="Invariant Violation",u}}e.isRequired=e;function t(){return e}var r={array:e,bigint:e,bool:e,func:e,number:e,object:e,string:e,symbol:e,any:e,arrayOf:t,element:e,elementType:e,instanceOf:t,node:e,objectOf:t,oneOf:t,oneOfType:t,shape:t,exact:t,checkPropTypes:Uk,resetWarningCache:Wk};return r.PropTypes=r,r};zk.exports=yH();var gH=zk.exports;const ce=de(gH),{getOwnPropertyNames:xH,getOwnPropertySymbols:bH}=Object,{hasOwnProperty:jH}=Object.prototype;function lh(e,t){return function(n,a,i){return e(n,a,i)&&t(n,a,i)}}function rc(e){return function(r,n,a){if(!r||!n||typeof r!="object"||typeof n!="object")return e(r,n,a);const{cache:i}=a,s=i.get(r),l=i.get(n);if(s&&l)return s===n&&l===r;i.set(r,n),i.set(n,r);const c=e(r,n,a);return i.delete(r),i.delete(n),c}}function wH(e){return e!=null?e[Symbol.toStringTag]:void 0}function e1(e){return xH(e).concat(bH(e))}const SH=Object.hasOwn||((e,t)=>jH.call(e,t));function Ma(e,t){return e===t||!e&&!t&&e!==e&&t!==t}const _H="__v",kH="__o",OH="_owner",{getOwnPropertyDescriptor:t1,keys:r1}=Object;function NH(e,t){return e.byteLength===t.byteLength&&Cu(new Uint8Array(e),new Uint8Array(t))}function PH(e,t,r){let n=e.length;if(t.length!==n)return!1;for(;n-- >0;)if(!r.equals(e[n],t[n],n,n,e,t,r))return!1;return!0}function AH(e,t){return e.byteLength===t.byteLength&&Cu(new Uint8Array(e.buffer,e.byteOffset,e.byteLength),new Uint8Array(t.buffer,t.byteOffset,t.byteLength))}function CH(e,t){return Ma(e.getTime(),t.getTime())}function EH(e,t){return e.name===t.name&&e.message===t.message&&e.cause===t.cause&&e.stack===t.stack}function $H(e,t){return e===t}function n1(e,t,r){const n=e.size;if(n!==t.size)return!1;if(!n)return!0;const a=new Array(n),i=e.entries();let s,l,c=0;for(;(s=i.next())&&!s.done;){const u=t.entries();let f=!1,d=0;for(;(l=u.next())&&!l.done;){if(a[d]){d++;continue}const h=s.value,p=l.value;if(r.equals(h[0],p[0],c,d,e,t,r)&&r.equals(h[1],p[1],h[0],p[0],e,t,r)){f=a[d]=!0;break}d++}if(!f)return!1;c++}return!0}const TH=Ma;function MH(e,t,r){const n=r1(e);let a=n.length;if(r1(t).length!==a)return!1;for(;a-- >0;)if(!Hk(e,t,r,n[a]))return!1;return!0}function Io(e,t,r){const n=e1(e);let a=n.length;if(e1(t).length!==a)return!1;let i,s,l;for(;a-- >0;)if(i=n[a],!Hk(e,t,r,i)||(s=t1(e,i),l=t1(t,i),(s||l)&&(!s||!l||s.configurable!==l.configurable||s.enumerable!==l.enumerable||s.writable!==l.writable)))return!1;return!0}function IH(e,t){return Ma(e.valueOf(),t.valueOf())}function LH(e,t){return e.source===t.source&&e.flags===t.flags}function a1(e,t,r){const n=e.size;if(n!==t.size)return!1;if(!n)return!0;const a=new Array(n),i=e.values();let s,l;for(;(s=i.next())&&!s.done;){const c=t.values();let u=!1,f=0;for(;(l=c.next())&&!l.done;){if(!a[f]&&r.equals(s.value,l.value,s.value,l.value,e,t,r)){u=a[f]=!0;break}f++}if(!u)return!1}return!0}function Cu(e,t){let r=e.byteLength;if(t.byteLength!==r||e.byteOffset!==t.byteOffset)return!1;for(;r-- >0;)if(e[r]!==t[r])return!1;return!0}function DH(e,t){return e.hostname===t.hostname&&e.pathname===t.pathname&&e.protocol===t.protocol&&e.port===t.port&&e.hash===t.hash&&e.username===t.username&&e.password===t.password}function Hk(e,t,r,n){return(n===OH||n===kH||n===_H)&&(e.$$typeof||t.$$typeof)?!0:SH(t,n)&&r.equals(e[n],t[n],n,n,e,t,r)}const RH="[object ArrayBuffer]",BH="[object Arguments]",FH="[object Boolean]",zH="[object DataView]",WH="[object Date]",UH="[object Error]",HH="[object Map]",KH="[object Number]",VH="[object Object]",GH="[object RegExp]",YH="[object Set]",qH="[object String]",XH={"[object Int8Array]":!0,"[object Uint8Array]":!0,"[object Uint8ClampedArray]":!0,"[object Int16Array]":!0,"[object Uint16Array]":!0,"[object Int32Array]":!0,"[object Uint32Array]":!0,"[object Float16Array]":!0,"[object Float32Array]":!0,"[object Float64Array]":!0,"[object BigInt64Array]":!0,"[object BigUint64Array]":!0},QH="[object URL]",JH=Object.prototype.toString;function ZH({areArrayBuffersEqual:e,areArraysEqual:t,areDataViewsEqual:r,areDatesEqual:n,areErrorsEqual:a,areFunctionsEqual:i,areMapsEqual:s,areNumbersEqual:l,areObjectsEqual:c,arePrimitiveWrappersEqual:u,areRegExpsEqual:f,areSetsEqual:d,areTypedArraysEqual:h,areUrlsEqual:p,unknownTagComparators:g}){return function(b,v,m){if(b===v)return!0;if(b==null||v==null)return!1;const x=typeof b;if(x!==typeof v)return!1;if(x!=="object")return x==="number"?l(b,v,m):x==="function"?i(b,v,m):!1;const S=b.constructor;if(S!==v.constructor)return!1;if(S===Object)return c(b,v,m);if(Array.isArray(b))return t(b,v,m);if(S===Date)return n(b,v,m);if(S===RegExp)return f(b,v,m);if(S===Map)return s(b,v,m);if(S===Set)return d(b,v,m);const j=JH.call(b);if(j===WH)return n(b,v,m);if(j===GH)return f(b,v,m);if(j===HH)return s(b,v,m);if(j===YH)return d(b,v,m);if(j===VH)return typeof b.then!="function"&&typeof v.then!="function"&&c(b,v,m);if(j===QH)return p(b,v,m);if(j===UH)return a(b,v,m);if(j===BH)return c(b,v,m);if(XH[j])return h(b,v,m);if(j===RH)return e(b,v,m);if(j===zH)return r(b,v,m);if(j===FH||j===KH||j===qH)return u(b,v,m);if(g){let w=g[j];if(!w){const _=wH(b);_&&(w=g[_])}if(w)return w(b,v,m)}return!1}}function eK({circular:e,createCustomConfig:t,strict:r}){let n={areArrayBuffersEqual:NH,areArraysEqual:r?Io:PH,areDataViewsEqual:AH,areDatesEqual:CH,areErrorsEqual:EH,areFunctionsEqual:$H,areMapsEqual:r?lh(n1,Io):n1,areNumbersEqual:TH,areObjectsEqual:r?Io:MH,arePrimitiveWrappersEqual:IH,areRegExpsEqual:LH,areSetsEqual:r?lh(a1,Io):a1,areTypedArraysEqual:r?lh(Cu,Io):Cu,areUrlsEqual:DH,unknownTagComparators:void 0};if(t&&(n=Object.assign({},n,t(n))),e){const a=rc(n.areArraysEqual),i=rc(n.areMapsEqual),s=rc(n.areObjectsEqual),l=rc(n.areSetsEqual);n=Object.assign({},n,{areArraysEqual:a,areMapsEqual:i,areObjectsEqual:s,areSetsEqual:l})}return n}function tK(e){return function(t,r,n,a,i,s,l){return e(t,r,l)}}function rK({circular:e,comparator:t,createState:r,equals:n,strict:a}){if(r)return function(l,c){const{cache:u=e?new WeakMap:void 0,meta:f}=r();return t(l,c,{cache:u,equals:n,meta:f,strict:a})};if(e)return function(l,c){return t(l,c,{cache:new WeakMap,equals:n,meta:void 0,strict:a})};const i={cache:void 0,equals:n,meta:void 0,strict:a};return function(l,c){return t(l,c,i)}}const nK=Kn();Kn({strict:!0});Kn({circular:!0});Kn({circular:!0,strict:!0});Kn({createInternalComparator:()=>Ma});Kn({strict:!0,createInternalComparator:()=>Ma});Kn({circular:!0,createInternalComparator:()=>Ma});Kn({circular:!0,createInternalComparator:()=>Ma,strict:!0});function Kn(e={}){const{circular:t=!1,createInternalComparator:r,createState:n,strict:a=!1}=e,i=eK(e),s=ZH(i),l=r?r(s):tK(s);return rK({circular:t,comparator:s,createState:n,equals:l,strict:a})}function aK(e){typeof requestAnimationFrame<"u"&&requestAnimationFrame(e)}function i1(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,r=-1,n=function a(i){r<0&&(r=i),i-r>t?(e(i),r=-1):aK(a)};requestAnimationFrame(n)}function sm(e){"@babel/helpers - typeof";return sm=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},sm(e)}function iK(e){return cK(e)||lK(e)||sK(e)||oK()}function oK(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
-In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function sK(e,t){if(e){if(typeof e=="string")return o1(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return o1(e,t)}}function o1(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function lK(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function cK(e){if(Array.isArray(e))return e}function uK(){var e={},t=function(){return null},r=!1,n=function a(i){if(!r){if(Array.isArray(i)){if(!i.length)return;var s=i,l=iK(s),c=l[0],u=l.slice(1);if(typeof c=="number"){i1(a.bind(null,u),c);return}a(c),i1(a.bind(null,u));return}sm(i)==="object"&&(e=i,t(e)),typeof i=="function"&&i()}};return{stop:function(){r=!0},start:function(i){r=!1,n(i)},subscribe:function(i){return t=i,function(){t=function(){return null}}}}}function Ys(e){"@babel/helpers - typeof";return Ys=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Ys(e)}function s1(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function l1(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?s1(Object(r),!0).forEach(function(n){Kk(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):s1(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function Kk(e,t,r){return t=dK(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function dK(e){var t=fK(e,"string");return Ys(t)==="symbol"?t:String(t)}function fK(e,t){if(Ys(e)!=="object"||e===null)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(Ys(n)!=="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var hK=function(t,r){return[Object.keys(t),Object.keys(r)].reduce(function(n,a){return n.filter(function(i){return a.includes(i)})})},pK=function(t){return t},mK=function(t){return t.replace(/([A-Z])/g,function(r){return"-".concat(r.toLowerCase())})},as=function(t,r){return Object.keys(r).reduce(function(n,a){return l1(l1({},n),{},Kk({},a,t(a,r[a])))},{})},c1=function(t,r,n){return t.map(function(a){return"".concat(mK(a)," ").concat(r,"ms ").concat(n)}).join(",")};function vK(e,t){return xK(e)||gK(e,t)||Vk(e,t)||yK()}function yK(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
-In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function gK(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,a,i,s,l=[],c=!0,u=!1;try{if(i=(r=r.call(e)).next,t!==0)for(;!(c=(n=i.call(r)).done)&&(l.push(n.value),l.length!==t);c=!0);}catch(f){u=!0,a=f}finally{try{if(!c&&r.return!=null&&(s=r.return(),Object(s)!==s))return}finally{if(u)throw a}}return l}}function xK(e){if(Array.isArray(e))return e}function bK(e){return SK(e)||wK(e)||Vk(e)||jK()}function jK(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
-In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Vk(e,t){if(e){if(typeof e=="string")return lm(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return lm(e,t)}}function wK(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function SK(e){if(Array.isArray(e))return lm(e)}function lm(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}var Eu=1e-4,Gk=function(t,r){return[0,3*t,3*r-6*t,3*t-3*r+1]},Yk=function(t,r){return t.map(function(n,a){return n*Math.pow(r,a)}).reduce(function(n,a){return n+a})},u1=function(t,r){return function(n){var a=Gk(t,r);return Yk(a,n)}},_K=function(t,r){return function(n){var a=Gk(t,r),i=[].concat(bK(a.map(function(s,l){return s*l}).slice(1)),[0]);return Yk(i,n)}},d1=function(){for(var t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];var a=r[0],i=r[1],s=r[2],l=r[3];if(r.length===1)switch(r[0]){case"linear":a=0,i=0,s=1,l=1;break;case"ease":a=.25,i=.1,s=.25,l=1;break;case"ease-in":a=.42,i=0,s=1,l=1;break;case"ease-out":a=.42,i=0,s=.58,l=1;break;case"ease-in-out":a=0,i=0,s=.58,l=1;break;default:{var c=r[0].split("(");if(c[0]==="cubic-bezier"&&c[1].split(")")[0].split(",").length===4){var u=c[1].split(")")[0].split(",").map(function(b){return parseFloat(b)}),f=vK(u,4);a=f[0],i=f[1],s=f[2],l=f[3]}}}var d=u1(a,s),h=u1(i,l),p=_K(a,s),g=function(v){return v>1?1:v<0?0:v},y=function(v){for(var m=v>1?1:v,x=m,S=0;S<8;++S){var j=d(x)-m,w=p(x);if(Math.abs(j-m)<Eu||w<Eu)return h(x);x=g(x-j/w)}return h(x)};return y.isStepper=!1,y},kK=function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},r=t.stiff,n=r===void 0?100:r,a=t.damping,i=a===void 0?8:a,s=t.dt,l=s===void 0?17:s,c=function(f,d,h){var p=-(f-d)*n,g=h*i,y=h+(p-g)*l/1e3,b=h*l/1e3+f;return Math.abs(b-d)<Eu&&Math.abs(y)<Eu?[d,0]:[b,y]};return c.isStepper=!0,c.dt=l,c},OK=function(){for(var t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];var a=r[0];if(typeof a=="string")switch(a){case"ease":case"ease-in-out":case"ease-out":case"ease-in":case"linear":return d1(a);case"spring":return kK();default:if(a.split("(")[0]==="cubic-bezier")return d1(a)}return typeof a=="function"?a:null};function qs(e){"@babel/helpers - typeof";return qs=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},qs(e)}function f1(e){return AK(e)||PK(e)||qk(e)||NK()}function NK(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
-In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function PK(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function AK(e){if(Array.isArray(e))return um(e)}function h1(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function ot(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?h1(Object(r),!0).forEach(function(n){cm(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):h1(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function cm(e,t,r){return t=CK(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function CK(e){var t=EK(e,"string");return qs(t)==="symbol"?t:String(t)}function EK(e,t){if(qs(e)!=="object"||e===null)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(qs(n)!=="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function $K(e,t){return IK(e)||MK(e,t)||qk(e,t)||TK()}function TK(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
-In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function qk(e,t){if(e){if(typeof e=="string")return um(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return um(e,t)}}function um(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function MK(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,a,i,s,l=[],c=!0,u=!1;try{if(i=(r=r.call(e)).next,t!==0)for(;!(c=(n=i.call(r)).done)&&(l.push(n.value),l.length!==t);c=!0);}catch(f){u=!0,a=f}finally{try{if(!c&&r.return!=null&&(s=r.return(),Object(s)!==s))return}finally{if(u)throw a}}return l}}function IK(e){if(Array.isArray(e))return e}var $u=function(t,r,n){return t+(r-t)*n},dm=function(t){var r=t.from,n=t.to;return r!==n},LK=function e(t,r,n){var a=as(function(i,s){if(dm(s)){var l=t(s.from,s.to,s.velocity),c=$K(l,2),u=c[0],f=c[1];return ot(ot({},s),{},{from:u,velocity:f})}return s},r);return n<1?as(function(i,s){return dm(s)?ot(ot({},s),{},{velocity:$u(s.velocity,a[i].velocity,n),from:$u(s.from,a[i].from,n)}):s},r):e(t,a,n-1)};const DK=function(e,t,r,n,a){var i=hK(e,t),s=i.reduce(function(b,v){return ot(ot({},b),{},cm({},v,[e[v],t[v]]))},{}),l=i.reduce(function(b,v){return ot(ot({},b),{},cm({},v,{from:e[v],velocity:0,to:t[v]}))},{}),c=-1,u,f,d=function(){return null},h=function(){return as(function(v,m){return m.from},l)},p=function(){return!Object.values(l).filter(dm).length},g=function(v){u||(u=v);var m=v-u,x=m/r.dt;l=LK(r,l,x),a(ot(ot(ot({},e),t),h())),u=v,p()||(c=requestAnimationFrame(d))},y=function(v){f||(f=v);var m=(v-f)/n,x=as(function(j,w){return $u.apply(void 0,f1(w).concat([r(m)]))},s);if(a(ot(ot(ot({},e),t),x)),m<1)c=requestAnimationFrame(d);else{var S=as(function(j,w){return $u.apply(void 0,f1(w).concat([r(1)]))},s);a(ot(ot(ot({},e),t),S))}};return d=r.isStepper?g:y,function(){return requestAnimationFrame(d),function(){cancelAnimationFrame(c)}}};function Li(e){"@babel/helpers - typeof";return Li=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Li(e)}var RK=["children","begin","duration","attributeName","easing","isActive","steps","from","to","canBegin","onAnimationEnd","shouldReAnimate","onAnimationReStart"];function BK(e,t){if(e==null)return{};var r=FK(e,t),n,a;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(a=0;a<i.length;a++)n=i[a],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function FK(e,t){if(e==null)return{};var r={},n=Object.keys(e),a,i;for(i=0;i<n.length;i++)a=n[i],!(t.indexOf(a)>=0)&&(r[a]=e[a]);return r}function ch(e){return HK(e)||UK(e)||WK(e)||zK()}function zK(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
-In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function WK(e,t){if(e){if(typeof e=="string")return fm(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return fm(e,t)}}function UK(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function HK(e){if(Array.isArray(e))return fm(e)}function fm(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function p1(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function cr(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?p1(Object(r),!0).forEach(function(n){Uo(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):p1(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function Uo(e,t,r){return t=Xk(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function KK(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function VK(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,Xk(n.key),n)}}function GK(e,t,r){return t&&VK(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function Xk(e){var t=YK(e,"string");return Li(t)==="symbol"?t:String(t)}function YK(e,t){if(Li(e)!=="object"||e===null)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(Li(n)!=="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function qK(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&hm(e,t)}function hm(e,t){return hm=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,a){return n.__proto__=a,n},hm(e,t)}function XK(e){var t=QK();return function(){var n=Tu(e),a;if(t){var i=Tu(this).constructor;a=Reflect.construct(n,arguments,i)}else a=n.apply(this,arguments);return pm(this,a)}}function pm(e,t){if(t&&(Li(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return mm(e)}function mm(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function QK(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function Tu(e){return Tu=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},Tu(e)}var br=function(e){qK(r,e);var t=XK(r);function r(n,a){var i;KK(this,r),i=t.call(this,n,a);var s=i.props,l=s.isActive,c=s.attributeName,u=s.from,f=s.to,d=s.steps,h=s.children,p=s.duration;if(i.handleStyleChange=i.handleStyleChange.bind(mm(i)),i.changeStyle=i.changeStyle.bind(mm(i)),!l||p<=0)return i.state={style:{}},typeof h=="function"&&(i.state={style:f}),pm(i);if(d&&d.length)i.state={style:d[0].style};else if(u){if(typeof h=="function")return i.state={style:u},pm(i);i.state={style:c?Uo({},c,u):u}}else i.state={style:{}};return i}return GK(r,[{key:"componentDidMount",value:function(){var a=this.props,i=a.isActive,s=a.canBegin;this.mounted=!0,!(!i||!s)&&this.runAnimation(this.props)}},{key:"componentDidUpdate",value:function(a){var i=this.props,s=i.isActive,l=i.canBegin,c=i.attributeName,u=i.shouldReAnimate,f=i.to,d=i.from,h=this.state.style;if(l){if(!s){var p={style:c?Uo({},c,f):f};this.state&&h&&(c&&h[c]!==f||!c&&h!==f)&&this.setState(p);return}if(!(nK(a.to,f)&&a.canBegin&&a.isActive)){var g=!a.canBegin||!a.isActive;this.manager&&this.manager.stop(),this.stopJSAnimation&&this.stopJSAnimation();var y=g||u?d:a.to;if(this.state&&h){var b={style:c?Uo({},c,y):y};(c&&h[c]!==y||!c&&h!==y)&&this.setState(b)}this.runAnimation(cr(cr({},this.props),{},{from:y,begin:0}))}}}},{key:"componentWillUnmount",value:function(){this.mounted=!1;var a=this.props.onAnimationEnd;this.unSubscribe&&this.unSubscribe(),this.manager&&(this.manager.stop(),this.manager=null),this.stopJSAnimation&&this.stopJSAnimation(),a&&a()}},{key:"handleStyleChange",value:function(a){this.changeStyle(a)}},{key:"changeStyle",value:function(a){this.mounted&&this.setState({style:a})}},{key:"runJSAnimation",value:function(a){var i=this,s=a.from,l=a.to,c=a.duration,u=a.easing,f=a.begin,d=a.onAnimationEnd,h=a.onAnimationStart,p=DK(s,l,OK(u),c,this.changeStyle),g=function(){i.stopJSAnimation=p()};this.manager.start([h,f,g,c,d])}},{key:"runStepAnimation",value:function(a){var i=this,s=a.steps,l=a.begin,c=a.onAnimationStart,u=s[0],f=u.style,d=u.duration,h=d===void 0?0:d,p=function(y,b,v){if(v===0)return y;var m=b.duration,x=b.easing,S=x===void 0?"ease":x,j=b.style,w=b.properties,_=b.onAnimationEnd,O=v>0?s[v-1]:b,N=w||Object.keys(j);if(typeof S=="function"||S==="spring")return[].concat(ch(y),[i.runJSAnimation.bind(i,{from:O.style,to:j,duration:m,easing:S}),m]);var k=c1(N,m,S),E=cr(cr(cr({},O.style),j),{},{transition:k});return[].concat(ch(y),[E,m,_]).filter(pK)};return this.manager.start([c].concat(ch(s.reduce(p,[f,Math.max(h,l)])),[a.onAnimationEnd]))}},{key:"runAnimation",value:function(a){this.manager||(this.manager=uK());var i=a.begin,s=a.duration,l=a.attributeName,c=a.to,u=a.easing,f=a.onAnimationStart,d=a.onAnimationEnd,h=a.steps,p=a.children,g=this.manager;if(this.unSubscribe=g.subscribe(this.handleStyleChange),typeof u=="function"||typeof p=="function"||u==="spring"){this.runJSAnimation(a);return}if(h.length>1){this.runStepAnimation(a);return}var y=l?Uo({},l,c):c,b=c1(Object.keys(y),s,u);g.start([f,i,cr(cr({},y),{},{transition:b}),s,d])}},{key:"render",value:function(){var a=this.props,i=a.children;a.begin;var s=a.duration;a.attributeName,a.easing;var l=a.isActive;a.steps,a.from,a.to,a.canBegin,a.onAnimationEnd,a.shouldReAnimate,a.onAnimationReStart;var c=BK(a,RK),u=P.Children.count(i),f=this.state.style;if(typeof i=="function")return i(f);if(!l||u===0||s<=0)return i;var d=function(p){var g=p.props,y=g.style,b=y===void 0?{}:y,v=g.className,m=P.cloneElement(p,cr(cr({},c),{},{style:cr(cr({},b),f),className:v}));return m};return u===1?d(P.Children.only(i)):$.createElement("div",null,P.Children.map(i,function(h){return d(h)}))}}]),r}(P.PureComponent);br.displayName="Animate";br.defaultProps={begin:0,duration:1e3,from:"",to:"",attributeName:"",easing:"ease",isActive:!0,canBegin:!0,steps:[],onAnimationEnd:function(){},onAnimationStart:function(){}};br.propTypes={from:ce.oneOfType([ce.object,ce.string]),to:ce.oneOfType([ce.object,ce.string]),attributeName:ce.string,duration:ce.number,begin:ce.number,easing:ce.oneOfType([ce.string,ce.func]),steps:ce.arrayOf(ce.shape({duration:ce.number.isRequired,style:ce.object.isRequired,easing:ce.oneOfType([ce.oneOf(["ease","ease-in","ease-out","ease-in-out","linear"]),ce.func]),properties:ce.arrayOf("string"),onAnimationEnd:ce.func})),children:ce.oneOfType([ce.node,ce.func]),isActive:ce.bool,canBegin:ce.bool,onAnimationEnd:ce.func,shouldReAnimate:ce.bool,onAnimationStart:ce.func,onAnimationReStart:ce.func};function Xs(e){"@babel/helpers - typeof";return Xs=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Xs(e)}function Mu(){return Mu=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},Mu.apply(this,arguments)}function JK(e,t){return rV(e)||tV(e,t)||eV(e,t)||ZK()}function ZK(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
-In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function eV(e,t){if(e){if(typeof e=="string")return m1(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return m1(e,t)}}function m1(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function tV(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,a,i,s,l=[],c=!0,u=!1;try{if(i=(r=r.call(e)).next,t!==0)for(;!(c=(n=i.call(r)).done)&&(l.push(n.value),l.length!==t);c=!0);}catch(f){u=!0,a=f}finally{try{if(!c&&r.return!=null&&(s=r.return(),Object(s)!==s))return}finally{if(u)throw a}}return l}}function rV(e){if(Array.isArray(e))return e}function v1(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function y1(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?v1(Object(r),!0).forEach(function(n){nV(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):v1(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function nV(e,t,r){return t=aV(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function aV(e){var t=iV(e,"string");return Xs(t)=="symbol"?t:t+""}function iV(e,t){if(Xs(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(Xs(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var g1=function(t,r,n,a,i){var s=Math.min(Math.abs(n)/2,Math.abs(a)/2),l=a>=0?1:-1,c=n>=0?1:-1,u=a>=0&&n>=0||a<0&&n<0?1:0,f;if(s>0&&i instanceof Array){for(var d=[0,0,0,0],h=0,p=4;h<p;h++)d[h]=i[h]>s?s:i[h];f="M".concat(t,",").concat(r+l*d[0]),d[0]>0&&(f+="A ".concat(d[0],",").concat(d[0],",0,0,").concat(u,",").concat(t+c*d[0],",").concat(r)),f+="L ".concat(t+n-c*d[1],",").concat(r),d[1]>0&&(f+="A ".concat(d[1],",").concat(d[1],",0,0,").concat(u,`,
- `).concat(t+n,",").concat(r+l*d[1])),f+="L ".concat(t+n,",").concat(r+a-l*d[2]),d[2]>0&&(f+="A ".concat(d[2],",").concat(d[2],",0,0,").concat(u,`,
- `).concat(t+n-c*d[2],",").concat(r+a)),f+="L ".concat(t+c*d[3],",").concat(r+a),d[3]>0&&(f+="A ".concat(d[3],",").concat(d[3],",0,0,").concat(u,`,
- `).concat(t,",").concat(r+a-l*d[3])),f+="Z"}else if(s>0&&i===+i&&i>0){var g=Math.min(s,i);f="M ".concat(t,",").concat(r+l*g,`
- A `).concat(g,",").concat(g,",0,0,").concat(u,",").concat(t+c*g,",").concat(r,`
- L `).concat(t+n-c*g,",").concat(r,`
- A `).concat(g,",").concat(g,",0,0,").concat(u,",").concat(t+n,",").concat(r+l*g,`
- L `).concat(t+n,",").concat(r+a-l*g,`
- A `).concat(g,",").concat(g,",0,0,").concat(u,",").concat(t+n-c*g,",").concat(r+a,`
- L `).concat(t+c*g,",").concat(r+a,`
- A `).concat(g,",").concat(g,",0,0,").concat(u,",").concat(t,",").concat(r+a-l*g," Z")}else f="M ".concat(t,",").concat(r," h ").concat(n," v ").concat(a," h ").concat(-n," Z");return f},oV=function(t,r){if(!t||!r)return!1;var n=t.x,a=t.y,i=r.x,s=r.y,l=r.width,c=r.height;if(Math.abs(l)>0&&Math.abs(c)>0){var u=Math.min(i,i+l),f=Math.max(i,i+l),d=Math.min(s,s+c),h=Math.max(s,s+c);return n>=u&&n<=f&&a>=d&&a<=h}return!1},sV={x:0,y:0,width:0,height:0,radius:0,isAnimationActive:!1,isUpdateAnimationActive:!1,animationBegin:0,animationDuration:1500,animationEasing:"ease"},Fy=function(t){var r=y1(y1({},sV),t),n=P.useRef(),a=P.useState(-1),i=JK(a,2),s=i[0],l=i[1];P.useEffect(function(){if(n.current&&n.current.getTotalLength)try{var S=n.current.getTotalLength();S&&l(S)}catch{}},[]);var c=r.x,u=r.y,f=r.width,d=r.height,h=r.radius,p=r.className,g=r.animationEasing,y=r.animationDuration,b=r.animationBegin,v=r.isAnimationActive,m=r.isUpdateAnimationActive;if(c!==+c||u!==+u||f!==+f||d!==+d||f===0||d===0)return null;var x=ee("recharts-rectangle",p);return m?$.createElement(br,{canBegin:s>0,from:{width:f,height:d,x:c,y:u},to:{width:f,height:d,x:c,y:u},duration:y,animationEasing:g,isActive:m},function(S){var j=S.width,w=S.height,_=S.x,O=S.y;return $.createElement(br,{canBegin:s>0,from:"0px ".concat(s===-1?1:s,"px"),to:"".concat(s,"px 0px"),attributeName:"strokeDasharray",begin:b,duration:y,isActive:v,easing:g},$.createElement("path",Mu({},X(r,!0),{className:x,d:g1(_,O,j,w,h),ref:n})))}):$.createElement("path",Mu({},X(r,!0),{className:x,d:g1(c,u,f,d,h)}))},lV=["points","className","baseLinePoints","connectNulls"];function ii(){return ii=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},ii.apply(this,arguments)}function cV(e,t){if(e==null)return{};var r=uV(e,t),n,a;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(a=0;a<i.length;a++)n=i[a],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function uV(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function x1(e){return pV(e)||hV(e)||fV(e)||dV()}function dV(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
-In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function fV(e,t){if(e){if(typeof e=="string")return vm(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return vm(e,t)}}function hV(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function pV(e){if(Array.isArray(e))return vm(e)}function vm(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}var b1=function(t){return t&&t.x===+t.x&&t.y===+t.y},mV=function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],r=[[]];return t.forEach(function(n){b1(n)?r[r.length-1].push(n):r[r.length-1].length>0&&r.push([])}),b1(t[0])&&r[r.length-1].push(t[0]),r[r.length-1].length<=0&&(r=r.slice(0,-1)),r},is=function(t,r){var n=mV(t);r&&(n=[n.reduce(function(i,s){return[].concat(x1(i),x1(s))},[])]);var a=n.map(function(i){return i.reduce(function(s,l,c){return"".concat(s).concat(c===0?"M":"L").concat(l.x,",").concat(l.y)},"")}).join("");return n.length===1?"".concat(a,"Z"):a},vV=function(t,r,n){var a=is(t,n);return"".concat(a.slice(-1)==="Z"?a.slice(0,-1):a,"L").concat(is(r.reverse(),n).slice(1))},yV=function(t){var r=t.points,n=t.className,a=t.baseLinePoints,i=t.connectNulls,s=cV(t,lV);if(!r||!r.length)return null;var l=ee("recharts-polygon",n);if(a&&a.length){var c=s.stroke&&s.stroke!=="none",u=vV(r,a,i);return $.createElement("g",{className:l},$.createElement("path",ii({},X(s,!0),{fill:u.slice(-1)==="Z"?s.fill:"none",stroke:"none",d:u})),c?$.createElement("path",ii({},X(s,!0),{fill:"none",d:is(r,i)})):null,c?$.createElement("path",ii({},X(s,!0),{fill:"none",d:is(a,i)})):null)}var f=is(r,i);return $.createElement("path",ii({},X(s,!0),{fill:f.slice(-1)==="Z"?s.fill:"none",className:l,d:f}))};function ym(){return ym=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},ym.apply(this,arguments)}var Zd=function(t){var r=t.cx,n=t.cy,a=t.r,i=t.className,s=ee("recharts-dot",i);return r===+r&&n===+n&&a===+a?P.createElement("circle",ym({},X(t,!1),Jc(t),{className:s,cx:r,cy:n,r:a})):null};function Qs(e){"@babel/helpers - typeof";return Qs=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Qs(e)}var gV=["x","y","top","left","width","height","className"];function gm(){return gm=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},gm.apply(this,arguments)}function j1(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function xV(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?j1(Object(r),!0).forEach(function(n){bV(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):j1(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function bV(e,t,r){return t=jV(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function jV(e){var t=wV(e,"string");return Qs(t)=="symbol"?t:t+""}function wV(e,t){if(Qs(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(Qs(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function SV(e,t){if(e==null)return{};var r=_V(e,t),n,a;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(a=0;a<i.length;a++)n=i[a],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function _V(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}var kV=function(t,r,n,a,i,s){return"M".concat(t,",").concat(i,"v").concat(a,"M").concat(s,",").concat(r,"h").concat(n)},OV=function(t){var r=t.x,n=r===void 0?0:r,a=t.y,i=a===void 0?0:a,s=t.top,l=s===void 0?0:s,c=t.left,u=c===void 0?0:c,f=t.width,d=f===void 0?0:f,h=t.height,p=h===void 0?0:h,g=t.className,y=SV(t,gV),b=xV({x:n,y:i,top:l,left:u,width:d,height:p},y);return!U(n)||!U(i)||!U(d)||!U(p)||!U(l)||!U(u)?null:$.createElement("path",gm({},X(b,!0),{className:ee("recharts-cross",g),d:kV(n,i,d,p,l,u)}))},NV=Yd,PV=ik,AV=Ir;function CV(e,t){return e&&e.length?NV(e,AV(t),PV):void 0}var EV=CV;const $V=de(EV);var TV=Yd,MV=Ir,IV=ok;function LV(e,t){return e&&e.length?TV(e,MV(t),IV):void 0}var DV=LV;const RV=de(DV);var BV=["cx","cy","angle","ticks","axisLine"],FV=["ticks","tick","angle","tickFormatter","stroke"];function Di(e){"@babel/helpers - typeof";return Di=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Di(e)}function os(){return os=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},os.apply(this,arguments)}function w1(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function qn(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?w1(Object(r),!0).forEach(function(n){ef(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):w1(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function S1(e,t){if(e==null)return{};var r=zV(e,t),n,a;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(a=0;a<i.length;a++)n=i[a],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function zV(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function WV(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _1(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,Jk(n.key),n)}}function UV(e,t,r){return t&&_1(e.prototype,t),r&&_1(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function HV(e,t,r){return t=Iu(t),KV(e,Qk()?Reflect.construct(t,r||[],Iu(e).constructor):t.apply(e,r))}function KV(e,t){if(t&&(Di(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return VV(e)}function VV(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function Qk(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(Qk=function(){return!!e})()}function Iu(e){return Iu=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},Iu(e)}function GV(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&xm(e,t)}function xm(e,t){return xm=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,a){return n.__proto__=a,n},xm(e,t)}function ef(e,t,r){return t=Jk(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function Jk(e){var t=YV(e,"string");return Di(t)=="symbol"?t:t+""}function YV(e,t){if(Di(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(Di(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var jl=function(e){function t(){return WV(this,t),HV(this,t,arguments)}return GV(t,e),UV(t,[{key:"getTickValueCoord",value:function(n){var a=n.coordinate,i=this.props,s=i.angle,l=i.cx,c=i.cy;return ye(l,c,a,s)}},{key:"getTickTextAnchor",value:function(){var n=this.props.orientation,a;switch(n){case"left":a="end";break;case"right":a="start";break;default:a="middle";break}return a}},{key:"getViewBox",value:function(){var n=this.props,a=n.cx,i=n.cy,s=n.angle,l=n.ticks,c=$V(l,function(f){return f.coordinate||0}),u=RV(l,function(f){return f.coordinate||0});return{cx:a,cy:i,startAngle:s,endAngle:s,innerRadius:u.coordinate||0,outerRadius:c.coordinate||0}}},{key:"renderAxisLine",value:function(){var n=this.props,a=n.cx,i=n.cy,s=n.angle,l=n.ticks,c=n.axisLine,u=S1(n,BV),f=l.reduce(function(g,y){return[Math.min(g[0],y.coordinate),Math.max(g[1],y.coordinate)]},[1/0,-1/0]),d=ye(a,i,f[0],s),h=ye(a,i,f[1],s),p=qn(qn(qn({},X(u,!1)),{},{fill:"none"},X(c,!1)),{},{x1:d.x,y1:d.y,x2:h.x,y2:h.y});return $.createElement("line",os({className:"recharts-polar-radius-axis-line"},p))}},{key:"renderTicks",value:function(){var n=this,a=this.props,i=a.ticks,s=a.tick,l=a.angle,c=a.tickFormatter,u=a.stroke,f=S1(a,FV),d=this.getTickTextAnchor(),h=X(f,!1),p=X(s,!1),g=i.map(function(y,b){var v=n.getTickValueCoord(y),m=qn(qn(qn(qn({textAnchor:d,transform:"rotate(".concat(90-l,", ").concat(v.x,", ").concat(v.y,")")},h),{},{stroke:"none",fill:u},p),{},{index:b},v),{},{payload:y});return $.createElement(ne,os({className:ee("recharts-polar-radius-axis-tick",Dk(s)),key:"tick-".concat(y.coordinate)},en(n.props,y,b)),t.renderTickItem(s,m,c?c(y.value,b):y.value))});return $.createElement(ne,{className:"recharts-polar-radius-axis-ticks"},g)}},{key:"render",value:function(){var n=this.props,a=n.ticks,i=n.axisLine,s=n.tick;return!a||!a.length?null:$.createElement(ne,{className:ee("recharts-polar-radius-axis",this.props.className)},i&&this.renderAxisLine(),s&&this.renderTicks(),tt.renderCallByParent(this.props,this.getViewBox()))}}],[{key:"renderTickItem",value:function(n,a,i){var s;return $.isValidElement(n)?s=$.cloneElement(n,a):Q(n)?s=n(a):s=$.createElement(Sa,os({},a,{className:"recharts-polar-radius-axis-tick-value"}),i),s}}])}(P.PureComponent);ef(jl,"displayName","PolarRadiusAxis");ef(jl,"axisType","radiusAxis");ef(jl,"defaultProps",{type:"number",radiusAxisId:0,cx:0,cy:0,angle:0,orientation:"right",stroke:"#ccc",axisLine:!0,tick:!0,tickCount:5,allowDataOverflow:!1,scale:"auto",allowDuplicatedCategory:!0});function Ri(e){"@babel/helpers - typeof";return Ri=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Ri(e)}function ra(){return ra=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},ra.apply(this,arguments)}function k1(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function Xn(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?k1(Object(r),!0).forEach(function(n){tf(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):k1(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function qV(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function O1(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,eO(n.key),n)}}function XV(e,t,r){return t&&O1(e.prototype,t),r&&O1(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function QV(e,t,r){return t=Lu(t),JV(e,Zk()?Reflect.construct(t,r||[],Lu(e).constructor):t.apply(e,r))}function JV(e,t){if(t&&(Ri(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return ZV(e)}function ZV(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function Zk(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(Zk=function(){return!!e})()}function Lu(e){return Lu=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},Lu(e)}function eG(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&bm(e,t)}function bm(e,t){return bm=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,a){return n.__proto__=a,n},bm(e,t)}function tf(e,t,r){return t=eO(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function eO(e){var t=tG(e,"string");return Ri(t)=="symbol"?t:t+""}function tG(e,t){if(Ri(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(Ri(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var rG=Math.PI/180,N1=1e-5,wl=function(e){function t(){return qV(this,t),QV(this,t,arguments)}return eG(t,e),XV(t,[{key:"getTickLineCoord",value:function(n){var a=this.props,i=a.cx,s=a.cy,l=a.radius,c=a.orientation,u=a.tickSize,f=u||8,d=ye(i,s,l,n.coordinate),h=ye(i,s,l+(c==="inner"?-1:1)*f,n.coordinate);return{x1:d.x,y1:d.y,x2:h.x,y2:h.y}}},{key:"getTickTextAnchor",value:function(n){var a=this.props.orientation,i=Math.cos(-n.coordinate*rG),s;return i>N1?s=a==="outer"?"start":"end":i<-N1?s=a==="outer"?"end":"start":s="middle",s}},{key:"renderAxisLine",value:function(){var n=this.props,a=n.cx,i=n.cy,s=n.radius,l=n.axisLine,c=n.axisLineType,u=Xn(Xn({},X(this.props,!1)),{},{fill:"none"},X(l,!1));if(c==="circle")return $.createElement(Zd,ra({className:"recharts-polar-angle-axis-line"},u,{cx:a,cy:i,r:s}));var f=this.props.ticks,d=f.map(function(h){return ye(a,i,s,h.coordinate)});return $.createElement(yV,ra({className:"recharts-polar-angle-axis-line"},u,{points:d}))}},{key:"renderTicks",value:function(){var n=this,a=this.props,i=a.ticks,s=a.tick,l=a.tickLine,c=a.tickFormatter,u=a.stroke,f=X(this.props,!1),d=X(s,!1),h=Xn(Xn({},f),{},{fill:"none"},X(l,!1)),p=i.map(function(g,y){var b=n.getTickLineCoord(g),v=n.getTickTextAnchor(g),m=Xn(Xn(Xn({textAnchor:v},f),{},{stroke:"none",fill:u},d),{},{index:y,payload:g,x:b.x2,y:b.y2});return $.createElement(ne,ra({className:ee("recharts-polar-angle-axis-tick",Dk(s)),key:"tick-".concat(g.coordinate)},en(n.props,g,y)),l&&$.createElement("line",ra({className:"recharts-polar-angle-axis-tick-line"},h,b)),s&&t.renderTickItem(s,m,c?c(g.value,y):g.value))});return $.createElement(ne,{className:"recharts-polar-angle-axis-ticks"},p)}},{key:"render",value:function(){var n=this.props,a=n.ticks,i=n.radius,s=n.axisLine;return i<=0||!a||!a.length?null:$.createElement(ne,{className:ee("recharts-polar-angle-axis",this.props.className)},s&&this.renderAxisLine(),this.renderTicks())}}],[{key:"renderTickItem",value:function(n,a,i){var s;return $.isValidElement(n)?s=$.cloneElement(n,a):Q(n)?s=n(a):s=$.createElement(Sa,ra({},a,{className:"recharts-polar-angle-axis-tick-value"}),i),s}}])}(P.PureComponent);tf(wl,"displayName","PolarAngleAxis");tf(wl,"axisType","angleAxis");tf(wl,"defaultProps",{type:"category",angleAxisId:0,scale:"auto",cx:0,cy:0,orientation:"outer",axisLine:!0,tickLine:!0,tickSize:8,tick:!0,hide:!1,allowDuplicatedCategory:!0});var nG=r_,aG=nG(Object.getPrototypeOf,Object),iG=aG,oG=on,sG=iG,lG=sn,cG="[object Object]",uG=Function.prototype,dG=Object.prototype,tO=uG.toString,fG=dG.hasOwnProperty,hG=tO.call(Object);function pG(e){if(!lG(e)||oG(e)!=cG)return!1;var t=sG(e);if(t===null)return!0;var r=fG.call(t,"constructor")&&t.constructor;return typeof r=="function"&&r instanceof r&&tO.call(r)==hG}var mG=pG;const vG=de(mG);var yG=on,gG=sn,xG="[object Boolean]";function bG(e){return e===!0||e===!1||gG(e)&&yG(e)==xG}var jG=bG;const wG=de(jG);function Js(e){"@babel/helpers - typeof";return Js=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Js(e)}function Du(){return Du=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},Du.apply(this,arguments)}function SG(e,t){return NG(e)||OG(e,t)||kG(e,t)||_G()}function _G(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
-In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function kG(e,t){if(e){if(typeof e=="string")return P1(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return P1(e,t)}}function P1(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function OG(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,a,i,s,l=[],c=!0,u=!1;try{if(i=(r=r.call(e)).next,t!==0)for(;!(c=(n=i.call(r)).done)&&(l.push(n.value),l.length!==t);c=!0);}catch(f){u=!0,a=f}finally{try{if(!c&&r.return!=null&&(s=r.return(),Object(s)!==s))return}finally{if(u)throw a}}return l}}function NG(e){if(Array.isArray(e))return e}function A1(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function C1(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?A1(Object(r),!0).forEach(function(n){PG(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):A1(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function PG(e,t,r){return t=AG(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function AG(e){var t=CG(e,"string");return Js(t)=="symbol"?t:t+""}function CG(e,t){if(Js(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(Js(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var E1=function(t,r,n,a,i){var s=n-a,l;return l="M ".concat(t,",").concat(r),l+="L ".concat(t+n,",").concat(r),l+="L ".concat(t+n-s/2,",").concat(r+i),l+="L ".concat(t+n-s/2-a,",").concat(r+i),l+="L ".concat(t,",").concat(r," Z"),l},EG={x:0,y:0,upperWidth:0,lowerWidth:0,height:0,isUpdateAnimationActive:!1,animationBegin:0,animationDuration:1500,animationEasing:"ease"},$G=function(t){var r=C1(C1({},EG),t),n=P.useRef(),a=P.useState(-1),i=SG(a,2),s=i[0],l=i[1];P.useEffect(function(){if(n.current&&n.current.getTotalLength)try{var x=n.current.getTotalLength();x&&l(x)}catch{}},[]);var c=r.x,u=r.y,f=r.upperWidth,d=r.lowerWidth,h=r.height,p=r.className,g=r.animationEasing,y=r.animationDuration,b=r.animationBegin,v=r.isUpdateAnimationActive;if(c!==+c||u!==+u||f!==+f||d!==+d||h!==+h||f===0&&d===0||h===0)return null;var m=ee("recharts-trapezoid",p);return v?$.createElement(br,{canBegin:s>0,from:{upperWidth:0,lowerWidth:0,height:h,x:c,y:u},to:{upperWidth:f,lowerWidth:d,height:h,x:c,y:u},duration:y,animationEasing:g,isActive:v},function(x){var S=x.upperWidth,j=x.lowerWidth,w=x.height,_=x.x,O=x.y;return $.createElement(br,{canBegin:s>0,from:"0px ".concat(s===-1?1:s,"px"),to:"".concat(s,"px 0px"),attributeName:"strokeDasharray",begin:b,duration:y,easing:g},$.createElement("path",Du({},X(r,!0),{className:m,d:E1(_,O,S,j,w),ref:n})))}):$.createElement("g",null,$.createElement("path",Du({},X(r,!0),{className:m,d:E1(c,u,f,d,h)})))},TG=["option","shapeType","propTransformer","activeClassName","isActive"];function Zs(e){"@babel/helpers - typeof";return Zs=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Zs(e)}function MG(e,t){if(e==null)return{};var r=IG(e,t),n,a;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(a=0;a<i.length;a++)n=i[a],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function IG(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function $1(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function Ru(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?$1(Object(r),!0).forEach(function(n){LG(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):$1(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function LG(e,t,r){return t=DG(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function DG(e){var t=RG(e,"string");return Zs(t)=="symbol"?t:t+""}function RG(e,t){if(Zs(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(Zs(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function BG(e,t){return Ru(Ru({},t),e)}function FG(e,t){return e==="symbols"}function T1(e){var t=e.shapeType,r=e.elementProps;switch(t){case"rectangle":return $.createElement(Fy,r);case"trapezoid":return $.createElement($G,r);case"sector":return $.createElement(Fk,r);case"symbols":if(FG(t))return $.createElement(ay,r);break;default:return null}}function zG(e){return P.isValidElement(e)?e.props:e}function zy(e){var t=e.option,r=e.shapeType,n=e.propTransformer,a=n===void 0?BG:n,i=e.activeClassName,s=i===void 0?"recharts-active-shape":i,l=e.isActive,c=MG(e,TG),u;if(P.isValidElement(t))u=P.cloneElement(t,Ru(Ru({},c),zG(t)));else if(Q(t))u=t(c);else if(vG(t)&&!wG(t)){var f=a(t,c);u=$.createElement(T1,{shapeType:r,elementProps:f})}else{var d=c;u=$.createElement(T1,{shapeType:r,elementProps:d})}return l?$.createElement(ne,{className:s},u):u}function rf(e,t){return t!=null&&"trapezoids"in e.props}function nf(e,t){return t!=null&&"sectors"in e.props}function el(e,t){return t!=null&&"points"in e.props}function WG(e,t){var r,n,a=e.x===(t==null||(r=t.labelViewBox)===null||r===void 0?void 0:r.x)||e.x===t.x,i=e.y===(t==null||(n=t.labelViewBox)===null||n===void 0?void 0:n.y)||e.y===t.y;return a&&i}function UG(e,t){var r=e.endAngle===t.endAngle,n=e.startAngle===t.startAngle;return r&&n}function HG(e,t){var r=e.x===t.x,n=e.y===t.y,a=e.z===t.z;return r&&n&&a}function KG(e,t){var r;return rf(e,t)?r=WG:nf(e,t)?r=UG:el(e,t)&&(r=HG),r}function VG(e,t){var r;return rf(e,t)?r="trapezoids":nf(e,t)?r="sectors":el(e,t)&&(r="points"),r}function GG(e,t){if(rf(e,t)){var r;return(r=t.tooltipPayload)===null||r===void 0||(r=r[0])===null||r===void 0||(r=r.payload)===null||r===void 0?void 0:r.payload}if(nf(e,t)){var n;return(n=t.tooltipPayload)===null||n===void 0||(n=n[0])===null||n===void 0||(n=n.payload)===null||n===void 0?void 0:n.payload}return el(e,t)?t.payload:{}}function YG(e){var t=e.activeTooltipItem,r=e.graphicalItem,n=e.itemData,a=VG(r,t),i=GG(r,t),s=n.filter(function(c,u){var f=_a(i,c),d=r.props[a].filter(function(g){var y=KG(r,t);return y(g,t)}),h=r.props[a].indexOf(d[d.length-1]),p=u===h;return f&&p}),l=n.indexOf(s[s.length-1]);return l}var _c;function Bi(e){"@babel/helpers - typeof";return Bi=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Bi(e)}function oi(){return oi=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},oi.apply(this,arguments)}function M1(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function xe(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?M1(Object(r),!0).forEach(function(n){qt(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):M1(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function qG(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function I1(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,nO(n.key),n)}}function XG(e,t,r){return t&&I1(e.prototype,t),r&&I1(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function QG(e,t,r){return t=Bu(t),JG(e,rO()?Reflect.construct(t,r||[],Bu(e).constructor):t.apply(e,r))}function JG(e,t){if(t&&(Bi(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return ZG(e)}function ZG(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function rO(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(rO=function(){return!!e})()}function Bu(e){return Bu=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},Bu(e)}function eY(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&jm(e,t)}function jm(e,t){return jm=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,a){return n.__proto__=a,n},jm(e,t)}function qt(e,t,r){return t=nO(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function nO(e){var t=tY(e,"string");return Bi(t)=="symbol"?t:t+""}function tY(e,t){if(Bi(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(Bi(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}var wr=function(e){function t(r){var n;return qG(this,t),n=QG(this,t,[r]),qt(n,"pieRef",null),qt(n,"sectorRefs",[]),qt(n,"id",uo("recharts-pie-")),qt(n,"handleAnimationEnd",function(){var a=n.props.onAnimationEnd;n.setState({isAnimationFinished:!0}),Q(a)&&a()}),qt(n,"handleAnimationStart",function(){var a=n.props.onAnimationStart;n.setState({isAnimationFinished:!1}),Q(a)&&a()}),n.state={isAnimationFinished:!r.isAnimationActive,prevIsAnimationActive:r.isAnimationActive,prevAnimationId:r.animationId,sectorToFocus:0},n}return eY(t,e),XG(t,[{key:"isActiveIndex",value:function(n){var a=this.props.activeIndex;return Array.isArray(a)?a.indexOf(n)!==-1:n===a}},{key:"hasActiveIndex",value:function(){var n=this.props.activeIndex;return Array.isArray(n)?n.length!==0:n||n===0}},{key:"renderLabels",value:function(n){var a=this.props.isAnimationActive;if(a&&!this.state.isAnimationFinished)return null;var i=this.props,s=i.label,l=i.labelLine,c=i.dataKey,u=i.valueKey,f=X(this.props,!1),d=X(s,!1),h=X(l,!1),p=s&&s.offsetRadius||20,g=n.map(function(y,b){var v=(y.startAngle+y.endAngle)/2,m=ye(y.cx,y.cy,y.outerRadius+p,v),x=xe(xe(xe(xe({},f),y),{},{stroke:"none"},d),{},{index:b,textAnchor:t.getTextAnchor(m.x,y.cx)},m),S=xe(xe(xe(xe({},f),y),{},{fill:"none",stroke:y.fill},h),{},{index:b,points:[ye(y.cx,y.cy,y.outerRadius,v),m]}),j=c;return te(c)&&te(u)?j="value":te(c)&&(j=u),$.createElement(ne,{key:"label-".concat(y.startAngle,"-").concat(y.endAngle,"-").concat(y.midAngle,"-").concat(b)},l&&t.renderLabelLineItem(l,S,"line"),t.renderLabelItem(s,x,Be(y,j)))});return $.createElement(ne,{className:"recharts-pie-labels"},g)}},{key:"renderSectorsStatically",value:function(n){var a=this,i=this.props,s=i.activeShape,l=i.blendStroke,c=i.inactiveShape;return n.map(function(u,f){if((u==null?void 0:u.startAngle)===0&&(u==null?void 0:u.endAngle)===0&&n.length!==1)return null;var d=a.isActiveIndex(f),h=c&&a.hasActiveIndex()?c:null,p=d?s:h,g=xe(xe({},u),{},{stroke:l?u.fill:u.stroke,tabIndex:-1});return $.createElement(ne,oi({ref:function(b){b&&!a.sectorRefs.includes(b)&&a.sectorRefs.push(b)},tabIndex:-1,className:"recharts-pie-sector"},en(a.props,u,f),{key:"sector-".concat(u==null?void 0:u.startAngle,"-").concat(u==null?void 0:u.endAngle,"-").concat(u.midAngle,"-").concat(f)}),$.createElement(zy,oi({option:p,isActive:d,shapeType:"sector"},g)))})}},{key:"renderSectorsWithAnimation",value:function(){var n=this,a=this.props,i=a.sectors,s=a.isAnimationActive,l=a.animationBegin,c=a.animationDuration,u=a.animationEasing,f=a.animationId,d=this.state,h=d.prevSectors,p=d.prevIsAnimationActive;return $.createElement(br,{begin:l,duration:c,isActive:s,easing:u,from:{t:0},to:{t:1},key:"pie-".concat(f,"-").concat(p),onAnimationStart:this.handleAnimationStart,onAnimationEnd:this.handleAnimationEnd},function(g){var y=g.t,b=[],v=i&&i[0],m=v.startAngle;return i.forEach(function(x,S){var j=h&&h[S],w=S>0?Bt(x,"paddingAngle",0):0;if(j){var _=lt(j.endAngle-j.startAngle,x.endAngle-x.startAngle),O=xe(xe({},x),{},{startAngle:m+w,endAngle:m+_(y)+w});b.push(O),m=O.endAngle}else{var N=x.endAngle,k=x.startAngle,E=lt(0,N-k),T=E(y),D=xe(xe({},x),{},{startAngle:m+w,endAngle:m+T+w});b.push(D),m=D.endAngle}}),$.createElement(ne,null,n.renderSectorsStatically(b))})}},{key:"attachKeyboardHandlers",value:function(n){var a=this;n.onkeydown=function(i){if(!i.altKey)switch(i.key){case"ArrowLeft":{var s=++a.state.sectorToFocus%a.sectorRefs.length;a.sectorRefs[s].focus(),a.setState({sectorToFocus:s});break}case"ArrowRight":{var l=--a.state.sectorToFocus<0?a.sectorRefs.length-1:a.state.sectorToFocus%a.sectorRefs.length;a.sectorRefs[l].focus(),a.setState({sectorToFocus:l});break}case"Escape":{a.sectorRefs[a.state.sectorToFocus].blur(),a.setState({sectorToFocus:0});break}}}}},{key:"renderSectors",value:function(){var n=this.props,a=n.sectors,i=n.isAnimationActive,s=this.state.prevSectors;return i&&a&&a.length&&(!s||!_a(s,a))?this.renderSectorsWithAnimation():this.renderSectorsStatically(a)}},{key:"componentDidMount",value:function(){this.pieRef&&this.attachKeyboardHandlers(this.pieRef)}},{key:"render",value:function(){var n=this,a=this.props,i=a.hide,s=a.sectors,l=a.className,c=a.label,u=a.cx,f=a.cy,d=a.innerRadius,h=a.outerRadius,p=a.isAnimationActive,g=this.state.isAnimationFinished;if(i||!s||!s.length||!U(u)||!U(f)||!U(d)||!U(h))return null;var y=ee("recharts-pie",l);return $.createElement(ne,{tabIndex:this.props.rootTabIndex,className:y,ref:function(v){n.pieRef=v}},this.renderSectors(),c&&this.renderLabels(s),tt.renderCallByParent(this.props,null,!1),(!p||g)&&Er.renderCallByParent(this.props,s,!1))}}],[{key:"getDerivedStateFromProps",value:function(n,a){return a.prevIsAnimationActive!==n.isAnimationActive?{prevIsAnimationActive:n.isAnimationActive,prevAnimationId:n.animationId,curSectors:n.sectors,prevSectors:[],isAnimationFinished:!0}:n.isAnimationActive&&n.animationId!==a.prevAnimationId?{prevAnimationId:n.animationId,curSectors:n.sectors,prevSectors:a.curSectors,isAnimationFinished:!0}:n.sectors!==a.curSectors?{curSectors:n.sectors,isAnimationFinished:!0}:null}},{key:"getTextAnchor",value:function(n,a){return n>a?"start":n<a?"end":"middle"}},{key:"renderLabelLineItem",value:function(n,a,i){if($.isValidElement(n))return $.cloneElement(n,a);if(Q(n))return n(a);var s=ee("recharts-pie-label-line",typeof n!="boolean"?n.className:"");return $.createElement(xi,oi({},a,{key:i,type:"linear",className:s}))}},{key:"renderLabelItem",value:function(n,a,i){if($.isValidElement(n))return $.cloneElement(n,a);var s=i;if(Q(n)&&(s=n(a),$.isValidElement(s)))return s;var l=ee("recharts-pie-label-text",typeof n!="boolean"&&!Q(n)?n.className:"");return $.createElement(Sa,oi({},a,{alignmentBaseline:"middle",className:l}),s)}}])}(P.PureComponent);_c=wr;qt(wr,"displayName","Pie");qt(wr,"defaultProps",{stroke:"#fff",fill:"#808080",legendType:"rect",cx:"50%",cy:"50%",startAngle:0,endAngle:360,innerRadius:0,outerRadius:"80%",paddingAngle:0,labelLine:!0,hide:!1,minAngle:0,isAnimationActive:!Wn.isSsr,animationBegin:400,animationDuration:1500,animationEasing:"ease",nameKey:"name",blendStroke:!1,rootTabIndex:0});qt(wr,"parseDeltaAngle",function(e,t){var r=rt(t-e),n=Math.min(Math.abs(t-e),360);return r*n});qt(wr,"getRealPieData",function(e){var t=e.data,r=e.children,n=X(e,!1),a=Ft(r,xr);return t&&t.length?t.map(function(i,s){return xe(xe(xe({payload:i},n),i),a&&a[s]&&a[s].props)}):a&&a.length?a.map(function(i){return xe(xe({},n),i.props)}):[]});qt(wr,"parseCoordinateOfPie",function(e,t){var r=t.top,n=t.left,a=t.width,i=t.height,s=Ik(a,i),l=n+xt(e.cx,a,a/2),c=r+xt(e.cy,i,i/2),u=xt(e.innerRadius,s,0),f=xt(e.outerRadius,s,s*.8),d=e.maxRadius||Math.sqrt(a*a+i*i)/2;return{cx:l,cy:c,innerRadius:u,outerRadius:f,maxRadius:d}});qt(wr,"getComposedData",function(e){var t=e.item,r=e.offset,n=t.type.defaultProps!==void 0?xe(xe({},t.type.defaultProps),t.props):t.props,a=_c.getRealPieData(n);if(!a||!a.length)return null;var i=n.cornerRadius,s=n.startAngle,l=n.endAngle,c=n.paddingAngle,u=n.dataKey,f=n.nameKey,d=n.valueKey,h=n.tooltipType,p=Math.abs(n.minAngle),g=_c.parseCoordinateOfPie(n,r),y=_c.parseDeltaAngle(s,l),b=Math.abs(y),v=u;te(u)&&te(d)?(yr(!1,`Use "dataKey" to specify the value of pie,
- the props "valueKey" will be deprecated in 1.1.0`),v="value"):te(u)&&(yr(!1,`Use "dataKey" to specify the value of pie,
- the props "valueKey" will be deprecated in 1.1.0`),v=d);var m=a.filter(function(O){return Be(O,v,0)!==0}).length,x=(b>=360?m:m-1)*c,S=b-m*p-x,j=a.reduce(function(O,N){var k=Be(N,v,0);return O+(U(k)?k:0)},0),w;if(j>0){var _;w=a.map(function(O,N){var k=Be(O,v,0),E=Be(O,f,N),T=(U(k)?k:0)/j,D;N?D=_.endAngle+rt(y)*c*(k!==0?1:0):D=s;var A=D+rt(y)*((k!==0?p:0)+T*S),L=(D+A)/2,C=(g.innerRadius+g.outerRadius)/2,M=[{name:E,value:k,payload:O,dataKey:v,type:h}],I=ye(g.cx,g.cy,C,L);return _=xe(xe(xe({percent:T,cornerRadius:i,name:E,tooltipPayload:M,midAngle:L,middleRadius:C,tooltipPosition:I},O),g),{},{value:Be(O,v),startAngle:D,endAngle:A,payload:O,paddingAngle:rt(y)*c}),_})}return xe(xe({},g),{},{sectors:w,data:a})});function tl(e){"@babel/helpers - typeof";return tl=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},tl(e)}function wm(){return wm=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},wm.apply(this,arguments)}function L1(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function uh(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?L1(Object(r),!0).forEach(function(n){rY(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):L1(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function rY(e,t,r){return t=nY(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function nY(e){var t=aY(e,"string");return tl(t)=="symbol"?t:t+""}function aY(e,t){if(tl(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(tl(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function D1(e){return typeof e=="string"?parseInt(e,10):e}function iY(e,t){var r="".concat(t.cx||e.cx),n=Number(r),a="".concat(t.cy||e.cy),i=Number(a);return uh(uh(uh({},t),e),{},{cx:n,cy:i})}function R1(e){return $.createElement(zy,wm({shapeType:"sector",propTransformer:iY},e))}var oY=["shape","activeShape","activeIndex","cornerRadius"],sY=["value","background"];function Fi(e){"@babel/helpers - typeof";return Fi=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Fi(e)}function Fu(){return Fu=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},Fu.apply(this,arguments)}function B1(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function Je(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?B1(Object(r),!0).forEach(function(n){va(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):B1(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function F1(e,t){if(e==null)return{};var r=lY(e,t),n,a;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(a=0;a<i.length;a++)n=i[a],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function lY(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function cY(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function z1(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,iO(n.key),n)}}function uY(e,t,r){return t&&z1(e.prototype,t),r&&z1(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function dY(e,t,r){return t=zu(t),fY(e,aO()?Reflect.construct(t,r||[],zu(e).constructor):t.apply(e,r))}function fY(e,t){if(t&&(Fi(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return hY(e)}function hY(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function aO(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(aO=function(){return!!e})()}function zu(e){return zu=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},zu(e)}function pY(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Sm(e,t)}function Sm(e,t){return Sm=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,a){return n.__proto__=a,n},Sm(e,t)}function va(e,t,r){return t=iO(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function iO(e){var t=mY(e,"string");return Fi(t)=="symbol"?t:t+""}function mY(e,t){if(Fi(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(Fi(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}var Sl=function(e){function t(){var r;cY(this,t);for(var n=arguments.length,a=new Array(n),i=0;i<n;i++)a[i]=arguments[i];return r=dY(this,t,[].concat(a)),va(r,"state",{isAnimationFinished:!1}),va(r,"handleAnimationEnd",function(){var s=r.props.onAnimationEnd;r.setState({isAnimationFinished:!0}),Q(s)&&s()}),va(r,"handleAnimationStart",function(){var s=r.props.onAnimationStart;r.setState({isAnimationFinished:!1}),Q(s)&&s()}),r}return pY(t,e),uY(t,[{key:"getDeltaAngle",value:function(){var n=this.props,a=n.startAngle,i=n.endAngle,s=rt(i-a),l=Math.min(Math.abs(i-a),360);return s*l}},{key:"renderSectorsStatically",value:function(n){var a=this,i=this.props,s=i.shape,l=i.activeShape,c=i.activeIndex,u=i.cornerRadius,f=F1(i,oY),d=X(f,!1);return n.map(function(h,p){var g=p===c,y=Je(Je(Je(Je({},d),{},{cornerRadius:D1(u)},h),en(a.props,h,p)),{},{className:"recharts-radial-bar-sector ".concat(h.className),forceCornerRadius:f.forceCornerRadius,cornerIsExternal:f.cornerIsExternal,isActive:g,option:g?l:s});return $.createElement(R1,Fu({},y,{key:"sector-".concat(p)}))})}},{key:"renderSectorsWithAnimation",value:function(){var n=this,a=this.props,i=a.data,s=a.isAnimationActive,l=a.animationBegin,c=a.animationDuration,u=a.animationEasing,f=a.animationId,d=this.state.prevData;return $.createElement(br,{begin:l,duration:c,isActive:s,easing:u,from:{t:0},to:{t:1},key:"radialBar-".concat(f),onAnimationStart:this.handleAnimationStart,onAnimationEnd:this.handleAnimationEnd},function(h){var p=h.t,g=i.map(function(y,b){var v=d&&d[b];if(v){var m=lt(v.startAngle,y.startAngle),x=lt(v.endAngle,y.endAngle);return Je(Je({},y),{},{startAngle:m(p),endAngle:x(p)})}var S=y.endAngle,j=y.startAngle,w=lt(j,S);return Je(Je({},y),{},{endAngle:w(p)})});return $.createElement(ne,null,n.renderSectorsStatically(g))})}},{key:"renderSectors",value:function(){var n=this.props,a=n.data,i=n.isAnimationActive,s=this.state.prevData;return i&&a&&a.length&&(!s||!_a(s,a))?this.renderSectorsWithAnimation():this.renderSectorsStatically(a)}},{key:"renderBackground",value:function(n){var a=this,i=this.props.cornerRadius,s=X(this.props.background,!1);return n.map(function(l,c){l.value;var u=l.background,f=F1(l,sY);if(!u)return null;var d=Je(Je(Je(Je(Je({cornerRadius:D1(i)},f),{},{fill:"#eee"},u),s),en(a.props,l,c)),{},{index:c,className:ee("recharts-radial-bar-background-sector",s==null?void 0:s.className),option:u,isActive:!1});return $.createElement(R1,Fu({},d,{key:"sector-".concat(c)}))})}},{key:"render",value:function(){var n=this.props,a=n.hide,i=n.data,s=n.className,l=n.background,c=n.isAnimationActive;if(a||!i||!i.length)return null;var u=this.state.isAnimationFinished,f=ee("recharts-area",s);return $.createElement(ne,{className:f},l&&$.createElement(ne,{className:"recharts-radial-bar-background"},this.renderBackground(i)),$.createElement(ne,{className:"recharts-radial-bar-sectors"},this.renderSectors()),(!c||u)&&Er.renderCallByParent(Je({},this.props),i))}}],[{key:"getDerivedStateFromProps",value:function(n,a){return n.animationId!==a.prevAnimationId?{prevAnimationId:n.animationId,curData:n.data,prevData:a.curData}:n.data!==a.curData?{curData:n.data}:null}}])}(P.PureComponent);va(Sl,"displayName","RadialBar");va(Sl,"defaultProps",{angleAxisId:0,radiusAxisId:0,minPointSize:0,hide:!1,legendType:"rect",data:[],isAnimationActive:!Wn.isSsr,animationBegin:0,animationDuration:1500,animationEasing:"ease",forceCornerRadius:!1,cornerIsExternal:!1});va(Sl,"getComposedData",function(e){var t=e.item,r=e.props,n=e.radiusAxis,a=e.radiusAxisTicks,i=e.angleAxis,s=e.angleAxisTicks,l=e.displayedData,c=e.dataKey,u=e.stackedData,f=e.barPosition,d=e.bandSize,h=e.dataStartIndex,p=Ak(f,t);if(!p)return null;var g=i.cx,y=i.cy,b=r.layout,v=t.props,m=v.children,x=v.minPointSize,S=b==="radial"?i:n,j=u?S.scale.domain():null,w=$k({numericAxis:S}),_=Ft(m,xr),O=l.map(function(N,k){var E,T,D,A,L,C;if(u?E=Ck(u[h+k],j):(E=Be(N,c),Array.isArray(E)||(E=[w,E])),b==="radial"){T=Ou({axis:n,ticks:a,bandSize:d,offset:p.offset,entry:N,index:k}),L=i.scale(E[1]),A=i.scale(E[0]),D=T+p.size;var M=L-A;if(Math.abs(x)>0&&Math.abs(M)<Math.abs(x)){var I=rt(M||x)*(Math.abs(x)-Math.abs(M));L+=I}C={background:{cx:g,cy:y,innerRadius:T,outerRadius:D,startAngle:r.startAngle,endAngle:r.endAngle}}}else{T=n.scale(E[0]),D=n.scale(E[1]),A=Ou({axis:i,ticks:s,bandSize:d,offset:p.offset,entry:N,index:k}),L=A+p.size;var R=D-T;if(Math.abs(x)>0&&Math.abs(R)<Math.abs(x)){var F=rt(R||x)*(Math.abs(x)-Math.abs(R));D+=F}}return Je(Je(Je(Je({},N),C),{},{payload:N,value:u?E:E[1],cx:g,cy:y,innerRadius:T,outerRadius:D,startAngle:A,endAngle:L},_&&_[k]&&_[k].props),{},{tooltipPayload:[By(t,N)],tooltipPosition:ye(g,y,(T+D)/2,(A+L)/2)})});return{data:O,layout:b}});var vY=Math.ceil,yY=Math.max;function gY(e,t,r,n){for(var a=-1,i=yY(vY((t-e)/(r||1)),0),s=Array(i);i--;)s[n?i:++a]=e,e+=r;return s}var xY=gY,bY=j_,W1=1/0,jY=17976931348623157e292;function wY(e){if(!e)return e===0?e:0;if(e=bY(e),e===W1||e===-W1){var t=e<0?-1:1;return t*jY}return e===e?e:0}var oO=wY,SY=xY,_Y=zd,dh=oO;function kY(e){return function(t,r,n){return n&&typeof n!="number"&&_Y(t,r,n)&&(r=n=void 0),t=dh(t),r===void 0?(r=t,t=0):r=dh(r),n=n===void 0?t<r?1:-1:dh(n),SY(t,r,n,e)}}var OY=kY,NY=OY,PY=NY(),AY=PY;const Wu=de(AY);function rl(e){"@babel/helpers - typeof";return rl=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},rl(e)}function U1(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function H1(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?U1(Object(r),!0).forEach(function(n){sO(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):U1(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function sO(e,t,r){return t=CY(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function CY(e){var t=EY(e,"string");return rl(t)=="symbol"?t:t+""}function EY(e,t){if(rl(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(rl(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var $Y=["Webkit","Moz","O","ms"],TY=function(t,r){var n=t.replace(/(\w)/,function(i){return i.toUpperCase()}),a=$Y.reduce(function(i,s){return H1(H1({},i),{},sO({},s+n,r))},{});return a[t]=r,a};function zi(e){"@babel/helpers - typeof";return zi=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},zi(e)}function Uu(){return Uu=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},Uu.apply(this,arguments)}function K1(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function fh(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?K1(Object(r),!0).forEach(function(n){Tt(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):K1(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function MY(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function V1(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,cO(n.key),n)}}function IY(e,t,r){return t&&V1(e.prototype,t),r&&V1(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function LY(e,t,r){return t=Hu(t),DY(e,lO()?Reflect.construct(t,r||[],Hu(e).constructor):t.apply(e,r))}function DY(e,t){if(t&&(zi(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return RY(e)}function RY(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function lO(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(lO=function(){return!!e})()}function Hu(e){return Hu=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},Hu(e)}function BY(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&_m(e,t)}function _m(e,t){return _m=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,a){return n.__proto__=a,n},_m(e,t)}function Tt(e,t,r){return t=cO(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function cO(e){var t=FY(e,"string");return zi(t)=="symbol"?t:t+""}function FY(e,t){if(zi(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(zi(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}var zY=function(t){var r=t.data,n=t.startIndex,a=t.endIndex,i=t.x,s=t.width,l=t.travellerWidth;if(!r||!r.length)return{};var c=r.length,u=rs().domain(Wu(0,c)).range([i,i+s-l]),f=u.domain().map(function(d){return u(d)});return{isTextActive:!1,isSlideMoving:!1,isTravellerMoving:!1,isTravellerFocused:!1,startX:u(n),endX:u(a),scale:u,scaleValues:f}},G1=function(t){return t.changedTouches&&!!t.changedTouches.length},Wi=function(e){function t(r){var n;return MY(this,t),n=LY(this,t,[r]),Tt(n,"handleDrag",function(a){n.leaveTimer&&(clearTimeout(n.leaveTimer),n.leaveTimer=null),n.state.isTravellerMoving?n.handleTravellerMove(a):n.state.isSlideMoving&&n.handleSlideDrag(a)}),Tt(n,"handleTouchMove",function(a){a.changedTouches!=null&&a.changedTouches.length>0&&n.handleDrag(a.changedTouches[0])}),Tt(n,"handleDragEnd",function(){n.setState({isTravellerMoving:!1,isSlideMoving:!1},function(){var a=n.props,i=a.endIndex,s=a.onDragEnd,l=a.startIndex;s==null||s({endIndex:i,startIndex:l})}),n.detachDragEndListener()}),Tt(n,"handleLeaveWrapper",function(){(n.state.isTravellerMoving||n.state.isSlideMoving)&&(n.leaveTimer=window.setTimeout(n.handleDragEnd,n.props.leaveTimeOut))}),Tt(n,"handleEnterSlideOrTraveller",function(){n.setState({isTextActive:!0})}),Tt(n,"handleLeaveSlideOrTraveller",function(){n.setState({isTextActive:!1})}),Tt(n,"handleSlideDragStart",function(a){var i=G1(a)?a.changedTouches[0]:a;n.setState({isTravellerMoving:!1,isSlideMoving:!0,slideMoveStartX:i.pageX}),n.attachDragEndListener()}),n.travellerDragStartHandlers={startX:n.handleTravellerDragStart.bind(n,"startX"),endX:n.handleTravellerDragStart.bind(n,"endX")},n.state={},n}return BY(t,e),IY(t,[{key:"componentWillUnmount",value:function(){this.leaveTimer&&(clearTimeout(this.leaveTimer),this.leaveTimer=null),this.detachDragEndListener()}},{key:"getIndex",value:function(n){var a=n.startX,i=n.endX,s=this.state.scaleValues,l=this.props,c=l.gap,u=l.data,f=u.length-1,d=Math.min(a,i),h=Math.max(a,i),p=t.getIndexInRange(s,d),g=t.getIndexInRange(s,h);return{startIndex:p-p%c,endIndex:g===f?f:g-g%c}}},{key:"getTextOfTick",value:function(n){var a=this.props,i=a.data,s=a.tickFormatter,l=a.dataKey,c=Be(i[n],l,n);return Q(s)?s(c,n):c}},{key:"attachDragEndListener",value:function(){window.addEventListener("mouseup",this.handleDragEnd,!0),window.addEventListener("touchend",this.handleDragEnd,!0),window.addEventListener("mousemove",this.handleDrag,!0)}},{key:"detachDragEndListener",value:function(){window.removeEventListener("mouseup",this.handleDragEnd,!0),window.removeEventListener("touchend",this.handleDragEnd,!0),window.removeEventListener("mousemove",this.handleDrag,!0)}},{key:"handleSlideDrag",value:function(n){var a=this.state,i=a.slideMoveStartX,s=a.startX,l=a.endX,c=this.props,u=c.x,f=c.width,d=c.travellerWidth,h=c.startIndex,p=c.endIndex,g=c.onChange,y=n.pageX-i;y>0?y=Math.min(y,u+f-d-l,u+f-d-s):y<0&&(y=Math.max(y,u-s,u-l));var b=this.getIndex({startX:s+y,endX:l+y});(b.startIndex!==h||b.endIndex!==p)&&g&&g(b),this.setState({startX:s+y,endX:l+y,slideMoveStartX:n.pageX})}},{key:"handleTravellerDragStart",value:function(n,a){var i=G1(a)?a.changedTouches[0]:a;this.setState({isSlideMoving:!1,isTravellerMoving:!0,movingTravellerId:n,brushMoveStartX:i.pageX}),this.attachDragEndListener()}},{key:"handleTravellerMove",value:function(n){var a=this.state,i=a.brushMoveStartX,s=a.movingTravellerId,l=a.endX,c=a.startX,u=this.state[s],f=this.props,d=f.x,h=f.width,p=f.travellerWidth,g=f.onChange,y=f.gap,b=f.data,v={startX:this.state.startX,endX:this.state.endX},m=n.pageX-i;m>0?m=Math.min(m,d+h-p-u):m<0&&(m=Math.max(m,d-u)),v[s]=u+m;var x=this.getIndex(v),S=x.startIndex,j=x.endIndex,w=function(){var O=b.length-1;return s==="startX"&&(l>c?S%y===0:j%y===0)||l<c&&j===O||s==="endX"&&(l>c?j%y===0:S%y===0)||l>c&&j===O};this.setState(Tt(Tt({},s,u+m),"brushMoveStartX",n.pageX),function(){g&&w()&&g(x)})}},{key:"handleTravellerMoveKeyboard",value:function(n,a){var i=this,s=this.state,l=s.scaleValues,c=s.startX,u=s.endX,f=this.state[a],d=l.indexOf(f);if(d!==-1){var h=d+n;if(!(h===-1||h>=l.length)){var p=l[h];a==="startX"&&p>=u||a==="endX"&&p<=c||this.setState(Tt({},a,p),function(){i.props.onChange(i.getIndex({startX:i.state.startX,endX:i.state.endX}))})}}}},{key:"renderBackground",value:function(){var n=this.props,a=n.x,i=n.y,s=n.width,l=n.height,c=n.fill,u=n.stroke;return $.createElement("rect",{stroke:u,fill:c,x:a,y:i,width:s,height:l})}},{key:"renderPanorama",value:function(){var n=this.props,a=n.x,i=n.y,s=n.width,l=n.height,c=n.data,u=n.children,f=n.padding,d=P.Children.only(u);return d?$.cloneElement(d,{x:a,y:i,width:s,height:l,margin:f,compact:!0,data:c}):null}},{key:"renderTravellerLayer",value:function(n,a){var i,s,l=this,c=this.props,u=c.y,f=c.travellerWidth,d=c.height,h=c.traveller,p=c.ariaLabel,g=c.data,y=c.startIndex,b=c.endIndex,v=Math.max(n,this.props.x),m=fh(fh({},X(this.props,!1)),{},{x:v,y:u,width:f,height:d}),x=p||"Min value: ".concat((i=g[y])===null||i===void 0?void 0:i.name,", Max value: ").concat((s=g[b])===null||s===void 0?void 0:s.name);return $.createElement(ne,{tabIndex:0,role:"slider","aria-label":x,"aria-valuenow":n,className:"recharts-brush-traveller",onMouseEnter:this.handleEnterSlideOrTraveller,onMouseLeave:this.handleLeaveSlideOrTraveller,onMouseDown:this.travellerDragStartHandlers[a],onTouchStart:this.travellerDragStartHandlers[a],onKeyDown:function(j){["ArrowLeft","ArrowRight"].includes(j.key)&&(j.preventDefault(),j.stopPropagation(),l.handleTravellerMoveKeyboard(j.key==="ArrowRight"?1:-1,a))},onFocus:function(){l.setState({isTravellerFocused:!0})},onBlur:function(){l.setState({isTravellerFocused:!1})},style:{cursor:"col-resize"}},t.renderTraveller(h,m))}},{key:"renderSlide",value:function(n,a){var i=this.props,s=i.y,l=i.height,c=i.stroke,u=i.travellerWidth,f=Math.min(n,a)+u,d=Math.max(Math.abs(a-n)-u,0);return $.createElement("rect",{className:"recharts-brush-slide",onMouseEnter:this.handleEnterSlideOrTraveller,onMouseLeave:this.handleLeaveSlideOrTraveller,onMouseDown:this.handleSlideDragStart,onTouchStart:this.handleSlideDragStart,style:{cursor:"move"},stroke:"none",fill:c,fillOpacity:.2,x:f,y:s,width:d,height:l})}},{key:"renderText",value:function(){var n=this.props,a=n.startIndex,i=n.endIndex,s=n.y,l=n.height,c=n.travellerWidth,u=n.stroke,f=this.state,d=f.startX,h=f.endX,p=5,g={pointerEvents:"none",fill:u};return $.createElement(ne,{className:"recharts-brush-texts"},$.createElement(Sa,Uu({textAnchor:"end",verticalAnchor:"middle",x:Math.min(d,h)-p,y:s+l/2},g),this.getTextOfTick(a)),$.createElement(Sa,Uu({textAnchor:"start",verticalAnchor:"middle",x:Math.max(d,h)+c+p,y:s+l/2},g),this.getTextOfTick(i)))}},{key:"render",value:function(){var n=this.props,a=n.data,i=n.className,s=n.children,l=n.x,c=n.y,u=n.width,f=n.height,d=n.alwaysShowText,h=this.state,p=h.startX,g=h.endX,y=h.isTextActive,b=h.isSlideMoving,v=h.isTravellerMoving,m=h.isTravellerFocused;if(!a||!a.length||!U(l)||!U(c)||!U(u)||!U(f)||u<=0||f<=0)return null;var x=ee("recharts-brush",i),S=$.Children.count(s)===1,j=TY("userSelect","none");return $.createElement(ne,{className:x,onMouseLeave:this.handleLeaveWrapper,onTouchMove:this.handleTouchMove,style:j},this.renderBackground(),S&&this.renderPanorama(),this.renderSlide(p,g),this.renderTravellerLayer(p,"startX"),this.renderTravellerLayer(g,"endX"),(y||b||v||m||d)&&this.renderText())}}],[{key:"renderDefaultTraveller",value:function(n){var a=n.x,i=n.y,s=n.width,l=n.height,c=n.stroke,u=Math.floor(i+l/2)-1;return $.createElement($.Fragment,null,$.createElement("rect",{x:a,y:i,width:s,height:l,fill:c,stroke:"none"}),$.createElement("line",{x1:a+1,y1:u,x2:a+s-1,y2:u,fill:"none",stroke:"#fff"}),$.createElement("line",{x1:a+1,y1:u+2,x2:a+s-1,y2:u+2,fill:"none",stroke:"#fff"}))}},{key:"renderTraveller",value:function(n,a){var i;return $.isValidElement(n)?i=$.cloneElement(n,a):Q(n)?i=n(a):i=t.renderDefaultTraveller(a),i}},{key:"getDerivedStateFromProps",value:function(n,a){var i=n.data,s=n.width,l=n.x,c=n.travellerWidth,u=n.updateId,f=n.startIndex,d=n.endIndex;if(i!==a.prevData||u!==a.prevUpdateId)return fh({prevData:i,prevTravellerWidth:c,prevUpdateId:u,prevX:l,prevWidth:s},i&&i.length?zY({data:i,width:s,x:l,travellerWidth:c,startIndex:f,endIndex:d}):{scale:null,scaleValues:null});if(a.scale&&(s!==a.prevWidth||l!==a.prevX||c!==a.prevTravellerWidth)){a.scale.range([l,l+s-c]);var h=a.scale.domain().map(function(p){return a.scale(p)});return{prevData:i,prevTravellerWidth:c,prevUpdateId:u,prevX:l,prevWidth:s,startX:a.scale(n.startIndex),endX:a.scale(n.endIndex),scaleValues:h}}return null}},{key:"getIndexInRange",value:function(n,a){for(var i=n.length,s=0,l=i-1;l-s>1;){var c=Math.floor((s+l)/2);n[c]>a?l=c:s=c}return a>=n[l]?l:s}}])}(P.PureComponent);Tt(Wi,"displayName","Brush");Tt(Wi,"defaultProps",{height:40,travellerWidth:5,gap:1,fill:"#fff",stroke:"#666",padding:{top:1,right:1,bottom:1,left:1},leaveTimeOut:1e3,alwaysShowText:!1});var WY=dy;function UY(e,t){var r;return WY(e,function(n,a,i){return r=t(n,a,i),!r}),!!r}var HY=UY,KY=YS,VY=Ir,GY=HY,YY=$t,qY=zd;function XY(e,t,r){var n=YY(e)?KY:GY;return r&&qY(e,t,r)&&(t=void 0),n(e,VY(t))}var QY=XY;const JY=de(QY);var $r=function(t,r){var n=t.alwaysShow,a=t.ifOverflow;return n&&(a="extendDomain"),a===r},Y1=v_;function ZY(e,t,r){t=="__proto__"&&Y1?Y1(e,t,{configurable:!0,enumerable:!0,value:r,writable:!0}):e[t]=r}var eq=ZY,tq=eq,rq=p_,nq=Ir;function aq(e,t){var r={};return t=nq(t),rq(e,function(n,a,i){tq(r,a,t(n,a,i))}),r}var iq=aq;const oq=de(iq);function sq(e,t){for(var r=-1,n=e==null?0:e.length;++r<n;)if(!t(e[r],r,e))return!1;return!0}var lq=sq,cq=dy;function uq(e,t){var r=!0;return cq(e,function(n,a,i){return r=!!t(n,a,i),r}),r}var dq=uq,fq=lq,hq=dq,pq=Ir,mq=$t,vq=zd;function yq(e,t,r){var n=mq(e)?fq:hq;return r&&vq(e,t,r)&&(t=void 0),n(e,pq(t))}var gq=yq;const uO=de(gq);var xq=["x","y"];function nl(e){"@babel/helpers - typeof";return nl=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},nl(e)}function km(){return km=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},km.apply(this,arguments)}function q1(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function Lo(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?q1(Object(r),!0).forEach(function(n){bq(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):q1(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function bq(e,t,r){return t=jq(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function jq(e){var t=wq(e,"string");return nl(t)=="symbol"?t:t+""}function wq(e,t){if(nl(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(nl(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Sq(e,t){if(e==null)return{};var r=_q(e,t),n,a;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(a=0;a<i.length;a++)n=i[a],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function _q(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function kq(e,t){var r=e.x,n=e.y,a=Sq(e,xq),i="".concat(r),s=parseInt(i,10),l="".concat(n),c=parseInt(l,10),u="".concat(t.height||a.height),f=parseInt(u,10),d="".concat(t.width||a.width),h=parseInt(d,10);return Lo(Lo(Lo(Lo(Lo({},t),a),s?{x:s}:{}),c?{y:c}:{}),{},{height:f,width:h,name:t.name,radius:t.radius})}function X1(e){return $.createElement(zy,km({shapeType:"rectangle",propTransformer:kq,activeClassName:"recharts-active-bar"},e))}var Oq=function(t){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;return function(n,a){if(typeof t=="number")return t;var i=U(n)||D3(n);return i?t(n,a):(i||Oa(),r)}},Nq=["value","background"],dO;function Ui(e){"@babel/helpers - typeof";return Ui=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Ui(e)}function Pq(e,t){if(e==null)return{};var r=Aq(e,t),n,a;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(a=0;a<i.length;a++)n=i[a],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function Aq(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function Ku(){return Ku=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},Ku.apply(this,arguments)}function Q1(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function De(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Q1(Object(r),!0).forEach(function(n){Sn(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Q1(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function Cq(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function J1(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,hO(n.key),n)}}function Eq(e,t,r){return t&&J1(e.prototype,t),r&&J1(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function $q(e,t,r){return t=Vu(t),Tq(e,fO()?Reflect.construct(t,r||[],Vu(e).constructor):t.apply(e,r))}function Tq(e,t){if(t&&(Ui(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return Mq(e)}function Mq(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function fO(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(fO=function(){return!!e})()}function Vu(e){return Vu=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},Vu(e)}function Iq(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Om(e,t)}function Om(e,t){return Om=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,a){return n.__proto__=a,n},Om(e,t)}function Sn(e,t,r){return t=hO(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function hO(e){var t=Lq(e,"string");return Ui(t)=="symbol"?t:t+""}function Lq(e,t){if(Ui(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(Ui(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}var nr=function(e){function t(){var r;Cq(this,t);for(var n=arguments.length,a=new Array(n),i=0;i<n;i++)a[i]=arguments[i];return r=$q(this,t,[].concat(a)),Sn(r,"state",{isAnimationFinished:!1}),Sn(r,"id",uo("recharts-bar-")),Sn(r,"handleAnimationEnd",function(){var s=r.props.onAnimationEnd;r.setState({isAnimationFinished:!0}),s&&s()}),Sn(r,"handleAnimationStart",function(){var s=r.props.onAnimationStart;r.setState({isAnimationFinished:!1}),s&&s()}),r}return Iq(t,e),Eq(t,[{key:"renderRectanglesStatically",value:function(n){var a=this,i=this.props,s=i.shape,l=i.dataKey,c=i.activeIndex,u=i.activeBar,f=X(this.props,!1);return n&&n.map(function(d,h){var p=h===c,g=p?u:s,y=De(De(De({},f),d),{},{isActive:p,option:g,index:h,dataKey:l,onAnimationStart:a.handleAnimationStart,onAnimationEnd:a.handleAnimationEnd});return $.createElement(ne,Ku({className:"recharts-bar-rectangle"},en(a.props,d,h),{key:"rectangle-".concat(d==null?void 0:d.x,"-").concat(d==null?void 0:d.y,"-").concat(d==null?void 0:d.value,"-").concat(h)}),$.createElement(X1,y))})}},{key:"renderRectanglesWithAnimation",value:function(){var n=this,a=this.props,i=a.data,s=a.layout,l=a.isAnimationActive,c=a.animationBegin,u=a.animationDuration,f=a.animationEasing,d=a.animationId,h=this.state.prevData;return $.createElement(br,{begin:c,duration:u,isActive:l,easing:f,from:{t:0},to:{t:1},key:"bar-".concat(d),onAnimationEnd:this.handleAnimationEnd,onAnimationStart:this.handleAnimationStart},function(p){var g=p.t,y=i.map(function(b,v){var m=h&&h[v];if(m){var x=lt(m.x,b.x),S=lt(m.y,b.y),j=lt(m.width,b.width),w=lt(m.height,b.height);return De(De({},b),{},{x:x(g),y:S(g),width:j(g),height:w(g)})}if(s==="horizontal"){var _=lt(0,b.height),O=_(g);return De(De({},b),{},{y:b.y+b.height-O,height:O})}var N=lt(0,b.width),k=N(g);return De(De({},b),{},{width:k})});return $.createElement(ne,null,n.renderRectanglesStatically(y))})}},{key:"renderRectangles",value:function(){var n=this.props,a=n.data,i=n.isAnimationActive,s=this.state.prevData;return i&&a&&a.length&&(!s||!_a(s,a))?this.renderRectanglesWithAnimation():this.renderRectanglesStatically(a)}},{key:"renderBackground",value:function(){var n=this,a=this.props,i=a.data,s=a.dataKey,l=a.activeIndex,c=X(this.props.background,!1);return i.map(function(u,f){u.value;var d=u.background,h=Pq(u,Nq);if(!d)return null;var p=De(De(De(De(De({},h),{},{fill:"#eee"},d),c),en(n.props,u,f)),{},{onAnimationStart:n.handleAnimationStart,onAnimationEnd:n.handleAnimationEnd,dataKey:s,index:f,className:"recharts-bar-background-rectangle"});return $.createElement(X1,Ku({key:"background-bar-".concat(f),option:n.props.background,isActive:f===l},p))})}},{key:"renderErrorBar",value:function(n,a){if(this.props.isAnimationActive&&!this.state.isAnimationFinished)return null;var i=this.props,s=i.data,l=i.xAxis,c=i.yAxis,u=i.layout,f=i.children,d=Ft(f,Jd);if(!d)return null;var h=u==="vertical"?s[0].height/2:s[0].width/2,p=function(b,v){var m=Array.isArray(b.value)?b.value[1]:b.value;return{x:b.x,y:b.y,value:m,errorVal:Be(b,v)}},g={clipPath:n?"url(#clipPath-".concat(a,")"):null};return $.createElement(ne,g,d.map(function(y){return $.cloneElement(y,{key:"error-bar-".concat(a,"-").concat(y.props.dataKey),data:s,xAxis:l,yAxis:c,layout:u,offset:h,dataPointFormatter:p})}))}},{key:"render",value:function(){var n=this.props,a=n.hide,i=n.data,s=n.className,l=n.xAxis,c=n.yAxis,u=n.left,f=n.top,d=n.width,h=n.height,p=n.isAnimationActive,g=n.background,y=n.id;if(a||!i||!i.length)return null;var b=this.state.isAnimationFinished,v=ee("recharts-bar",s),m=l&&l.allowDataOverflow,x=c&&c.allowDataOverflow,S=m||x,j=te(y)?this.id:y;return $.createElement(ne,{className:v},m||x?$.createElement("defs",null,$.createElement("clipPath",{id:"clipPath-".concat(j)},$.createElement("rect",{x:m?u:u-d/2,y:x?f:f-h/2,width:m?d:d*2,height:x?h:h*2}))):null,$.createElement(ne,{className:"recharts-bar-rectangles",clipPath:S?"url(#clipPath-".concat(j,")"):null},g?this.renderBackground():null,this.renderRectangles()),this.renderErrorBar(S,j),(!p||b)&&Er.renderCallByParent(this.props,i))}}],[{key:"getDerivedStateFromProps",value:function(n,a){return n.animationId!==a.prevAnimationId?{prevAnimationId:n.animationId,curData:n.data,prevData:a.curData}:n.data!==a.curData?{curData:n.data}:null}}])}(P.PureComponent);dO=nr;Sn(nr,"displayName","Bar");Sn(nr,"defaultProps",{xAxisId:0,yAxisId:0,legendType:"rect",minPointSize:0,hide:!1,data:[],layout:"vertical",activeBar:!1,isAnimationActive:!Wn.isSsr,animationBegin:0,animationDuration:400,animationEasing:"ease"});Sn(nr,"getComposedData",function(e){var t=e.props,r=e.item,n=e.barPosition,a=e.bandSize,i=e.xAxis,s=e.yAxis,l=e.xAxisTicks,c=e.yAxisTicks,u=e.stackedData,f=e.dataStartIndex,d=e.displayedData,h=e.offset,p=Ak(n,r);if(!p)return null;var g=t.layout,y=r.type.defaultProps,b=y!==void 0?De(De({},y),r.props):r.props,v=b.dataKey,m=b.children,x=b.minPointSize,S=g==="horizontal"?s:i,j=u?S.scale.domain():null,w=$k({numericAxis:S}),_=Ft(m,xr),O=d.map(function(N,k){var E,T,D,A,L,C;u?E=Ck(u[f+k],j):(E=Be(N,v),Array.isArray(E)||(E=[w,E]));var M=Oq(x,dO.defaultProps.minPointSize)(E[1],k);if(g==="horizontal"){var I,R=[s.scale(E[0]),s.scale(E[1])],F=R[0],K=R[1];T=Ou({axis:i,ticks:l,bandSize:a,offset:p.offset,entry:N,index:k}),D=(I=K??F)!==null&&I!==void 0?I:void 0,A=p.size;var z=F-K;if(L=Number.isNaN(z)?0:z,C={x:T,y:s.y,width:A,height:s.height},Math.abs(M)>0&&Math.abs(L)<Math.abs(M)){var q=rt(L||M)*(Math.abs(M)-Math.abs(L));D-=q,L+=q}}else{var ie=[i.scale(E[0]),i.scale(E[1])],he=ie[0],ge=ie[1];if(T=he,D=Ou({axis:s,ticks:c,bandSize:a,offset:p.offset,entry:N,index:k}),A=ge-he,L=p.size,C={x:i.x,y:D,width:i.width,height:L},Math.abs(M)>0&&Math.abs(A)<Math.abs(M)){var Qe=rt(A||M)*(Math.abs(M)-Math.abs(A));A+=Qe}}return De(De(De({},N),{},{x:T,y:D,width:A,height:L,value:u?E:E[1],payload:N,background:C},_&&_[k]&&_[k].props),{},{tooltipPayload:[By(r,N)],tooltipPosition:{x:T+A/2,y:D+L/2}})});return De({data:O,layout:g},h)});function al(e){"@babel/helpers - typeof";return al=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},al(e)}function Dq(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function Z1(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,pO(n.key),n)}}function Rq(e,t,r){return t&&Z1(e.prototype,t),r&&Z1(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function ej(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function fr(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?ej(Object(r),!0).forEach(function(n){af(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ej(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function af(e,t,r){return t=pO(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function pO(e){var t=Bq(e,"string");return al(t)=="symbol"?t:t+""}function Bq(e,t){if(al(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(al(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var mO=function(t,r,n,a,i){var s=t.width,l=t.height,c=t.layout,u=t.children,f=Object.keys(r),d={left:n.left,leftMirror:n.left,right:s-n.right,rightMirror:s-n.right,top:n.top,topMirror:n.top,bottom:l-n.bottom,bottomMirror:l-n.bottom},h=!!It(u,nr);return f.reduce(function(p,g){var y=r[g],b=y.orientation,v=y.domain,m=y.padding,x=m===void 0?{}:m,S=y.mirror,j=y.reversed,w="".concat(b).concat(S?"Mirror":""),_,O,N,k,E;if(y.type==="number"&&(y.padding==="gap"||y.padding==="no-gap")){var T=v[1]-v[0],D=1/0,A=y.categoricalDomain.sort(F3);if(A.forEach(function(ie,he){he>0&&(D=Math.min((ie||0)-(A[he-1]||0),D))}),Number.isFinite(D)){var L=D/T,C=y.layout==="vertical"?n.height:n.width;if(y.padding==="gap"&&(_=L*C/2),y.padding==="no-gap"){var M=xt(t.barCategoryGap,L*C),I=L*C/2;_=I-M-(I-M)/C*M}}}a==="xAxis"?O=[n.left+(x.left||0)+(_||0),n.left+n.width-(x.right||0)-(_||0)]:a==="yAxis"?O=c==="horizontal"?[n.top+n.height-(x.bottom||0),n.top+(x.top||0)]:[n.top+(x.top||0)+(_||0),n.top+n.height-(x.bottom||0)-(_||0)]:O=y.range,j&&(O=[O[1],O[0]]);var R=Nk(y,i,h),F=R.scale,K=R.realScaleType;F.domain(v).range(O),Pk(F);var z=Ek(F,fr(fr({},y),{},{realScaleType:K}));a==="xAxis"?(E=b==="top"&&!S||b==="bottom"&&S,N=n.left,k=d[w]-E*y.height):a==="yAxis"&&(E=b==="left"&&!S||b==="right"&&S,N=d[w]-E*y.width,k=n.top);var q=fr(fr(fr({},y),z),{},{realScaleType:K,x:N,y:k,scale:F,width:a==="xAxis"?n.width:y.width,height:a==="yAxis"?n.height:y.height});return q.bandSize=Nu(q,z),!y.hide&&a==="xAxis"?d[w]+=(E?-1:1)*q.height:y.hide||(d[w]+=(E?-1:1)*q.width),fr(fr({},p),{},af({},g,q))},{})},vO=function(t,r){var n=t.x,a=t.y,i=r.x,s=r.y;return{x:Math.min(n,i),y:Math.min(a,s),width:Math.abs(i-n),height:Math.abs(s-a)}},Fq=function(t){var r=t.x1,n=t.y1,a=t.x2,i=t.y2;return vO({x:r,y:n},{x:a,y:i})},yO=function(){function e(t){Dq(this,e),this.scale=t}return Rq(e,[{key:"domain",get:function(){return this.scale.domain}},{key:"range",get:function(){return this.scale.range}},{key:"rangeMin",get:function(){return this.range()[0]}},{key:"rangeMax",get:function(){return this.range()[1]}},{key:"bandwidth",get:function(){return this.scale.bandwidth}},{key:"apply",value:function(r){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},a=n.bandAware,i=n.position;if(r!==void 0){if(i)switch(i){case"start":return this.scale(r);case"middle":{var s=this.bandwidth?this.bandwidth()/2:0;return this.scale(r)+s}case"end":{var l=this.bandwidth?this.bandwidth():0;return this.scale(r)+l}default:return this.scale(r)}if(a){var c=this.bandwidth?this.bandwidth()/2:0;return this.scale(r)+c}return this.scale(r)}}},{key:"isInRange",value:function(r){var n=this.range(),a=n[0],i=n[n.length-1];return a<=i?r>=a&&r<=i:r>=i&&r<=a}}],[{key:"create",value:function(r){return new e(r)}}])}();af(yO,"EPS",1e-4);var Wy=function(t){var r=Object.keys(t).reduce(function(n,a){return fr(fr({},n),{},af({},a,yO.create(t[a])))},{});return fr(fr({},r),{},{apply:function(a){var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},s=i.bandAware,l=i.position;return oq(a,function(c,u){return r[u].apply(c,{bandAware:s,position:l})})},isInRange:function(a){return uO(a,function(i,s){return r[s].isInRange(i)})}})};function zq(e){return(e%180+180)%180}var Wq=function(t){var r=t.width,n=t.height,a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,i=zq(a),s=i*Math.PI/180,l=Math.atan(n/r),c=s>l&&s<Math.PI-l?n/Math.sin(s):r/Math.cos(s);return Math.abs(c)},Uq=Ir,Hq=vl,Kq=Bd;function Vq(e){return function(t,r,n){var a=Object(t);if(!Hq(t)){var i=Uq(r);t=Kq(t),r=function(l){return i(a[l],l,a)}}var s=e(t,r,n);return s>-1?a[i?t[s]:s]:void 0}}var Gq=Vq,Yq=oO;function qq(e){var t=Yq(e),r=t%1;return t===t?r?t-r:t:0}var Xq=qq,Qq=l_,Jq=Ir,Zq=Xq,eX=Math.max;function tX(e,t,r){var n=e==null?0:e.length;if(!n)return-1;var a=r==null?0:Zq(r);return a<0&&(a=eX(n+a,0)),Qq(e,Jq(t),a)}var rX=tX,nX=Gq,aX=rX,iX=nX(aX),oX=iX;const sX=de(oX);var lX=UT(function(e){return{x:e.left,y:e.top,width:e.width,height:e.height}},function(e){return["l",e.left,"t",e.top,"w",e.width,"h",e.height].join("")}),Uy=P.createContext(void 0),Hy=P.createContext(void 0),gO=P.createContext(void 0),xO=P.createContext({}),bO=P.createContext(void 0),jO=P.createContext(0),wO=P.createContext(0),tj=function(t){var r=t.state,n=r.xAxisMap,a=r.yAxisMap,i=r.offset,s=t.clipPathId,l=t.children,c=t.width,u=t.height,f=lX(i);return $.createElement(Uy.Provider,{value:n},$.createElement(Hy.Provider,{value:a},$.createElement(xO.Provider,{value:i},$.createElement(gO.Provider,{value:f},$.createElement(bO.Provider,{value:s},$.createElement(jO.Provider,{value:u},$.createElement(wO.Provider,{value:c},l)))))))},cX=function(){return P.useContext(bO)},SO=function(t){var r=P.useContext(Uy);r==null&&Oa();var n=r[t];return n==null&&Oa(),n},uX=function(){var t=P.useContext(Uy);return gn(t)},dX=function(){var t=P.useContext(Hy),r=sX(t,function(n){return uO(n.domain,Number.isFinite)});return r||gn(t)},_O=function(t){var r=P.useContext(Hy);r==null&&Oa();var n=r[t];return n==null&&Oa(),n},fX=function(){var t=P.useContext(gO);return t},hX=function(){return P.useContext(xO)},Ky=function(){return P.useContext(wO)},Vy=function(){return P.useContext(jO)};function Hi(e){"@babel/helpers - typeof";return Hi=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Hi(e)}function pX(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function mX(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,OO(n.key),n)}}function vX(e,t,r){return t&&mX(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function yX(e,t,r){return t=Gu(t),gX(e,kO()?Reflect.construct(t,r||[],Gu(e).constructor):t.apply(e,r))}function gX(e,t){if(t&&(Hi(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return xX(e)}function xX(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function kO(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(kO=function(){return!!e})()}function Gu(e){return Gu=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},Gu(e)}function bX(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Nm(e,t)}function Nm(e,t){return Nm=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,a){return n.__proto__=a,n},Nm(e,t)}function rj(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function nj(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?rj(Object(r),!0).forEach(function(n){Gy(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):rj(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function Gy(e,t,r){return t=OO(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function OO(e){var t=jX(e,"string");return Hi(t)=="symbol"?t:t+""}function jX(e,t){if(Hi(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(Hi(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}function wX(e,t){return OX(e)||kX(e,t)||_X(e,t)||SX()}function SX(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
-In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function _X(e,t){if(e){if(typeof e=="string")return aj(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return aj(e,t)}}function aj(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function kX(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,a,i,s,l=[],c=!0,u=!1;try{if(i=(r=r.call(e)).next,t!==0)for(;!(c=(n=i.call(r)).done)&&(l.push(n.value),l.length!==t);c=!0);}catch(f){u=!0,a=f}finally{try{if(!c&&r.return!=null&&(s=r.return(),Object(s)!==s))return}finally{if(u)throw a}}return l}}function OX(e){if(Array.isArray(e))return e}function Pm(){return Pm=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},Pm.apply(this,arguments)}var NX=function(t,r){var n;return $.isValidElement(t)?n=$.cloneElement(t,r):Q(t)?n=t(r):n=$.createElement("line",Pm({},r,{className:"recharts-reference-line-line"})),n},PX=function(t,r,n,a,i,s,l,c,u){var f=i.x,d=i.y,h=i.width,p=i.height;if(n){var g=u.y,y=t.y.apply(g,{position:s});if($r(u,"discard")&&!t.y.isInRange(y))return null;var b=[{x:f+h,y},{x:f,y}];return c==="left"?b.reverse():b}if(r){var v=u.x,m=t.x.apply(v,{position:s});if($r(u,"discard")&&!t.x.isInRange(m))return null;var x=[{x:m,y:d+p},{x:m,y:d}];return l==="top"?x.reverse():x}if(a){var S=u.segment,j=S.map(function(w){return t.apply(w,{position:s})});return $r(u,"discard")&&JY(j,function(w){return!t.isInRange(w)})?null:j}return null};function AX(e){var t=e.x,r=e.y,n=e.segment,a=e.xAxisId,i=e.yAxisId,s=e.shape,l=e.className,c=e.alwaysShow,u=cX(),f=SO(a),d=_O(i),h=fX();if(!u||!h)return null;yr(c===void 0,'The alwaysShow prop is deprecated. Please use ifOverflow="extendDomain" instead.');var p=Wy({x:f.scale,y:d.scale}),g=qe(t),y=qe(r),b=n&&n.length===2,v=PX(p,g,y,b,h,e.position,f.orientation,d.orientation,e);if(!v)return null;var m=wX(v,2),x=m[0],S=x.x,j=x.y,w=m[1],_=w.x,O=w.y,N=$r(e,"hidden")?"url(#".concat(u,")"):void 0,k=nj(nj({clipPath:N},X(e,!0)),{},{x1:S,y1:j,x2:_,y2:O});return $.createElement(ne,{className:ee("recharts-reference-line",l)},NX(s,k),tt.renderCallByParent(e,Fq({x1:S,y1:j,x2:_,y2:O})))}var Yy=function(e){function t(){return pX(this,t),yX(this,t,arguments)}return bX(t,e),vX(t,[{key:"render",value:function(){return $.createElement(AX,this.props)}}])}($.Component);Gy(Yy,"displayName","ReferenceLine");Gy(Yy,"defaultProps",{isFront:!1,ifOverflow:"discard",xAxisId:0,yAxisId:0,fill:"none",stroke:"#ccc",fillOpacity:1,strokeWidth:1,position:"middle"});function Am(){return Am=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},Am.apply(this,arguments)}function Ki(e){"@babel/helpers - typeof";return Ki=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Ki(e)}function ij(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function oj(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?ij(Object(r),!0).forEach(function(n){of(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ij(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function CX(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function EX(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,PO(n.key),n)}}function $X(e,t,r){return t&&EX(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function TX(e,t,r){return t=Yu(t),MX(e,NO()?Reflect.construct(t,r||[],Yu(e).constructor):t.apply(e,r))}function MX(e,t){if(t&&(Ki(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return IX(e)}function IX(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function NO(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(NO=function(){return!!e})()}function Yu(e){return Yu=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},Yu(e)}function LX(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Cm(e,t)}function Cm(e,t){return Cm=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,a){return n.__proto__=a,n},Cm(e,t)}function of(e,t,r){return t=PO(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function PO(e){var t=DX(e,"string");return Ki(t)=="symbol"?t:t+""}function DX(e,t){if(Ki(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(Ki(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}var RX=function(t){var r=t.x,n=t.y,a=t.xAxis,i=t.yAxis,s=Wy({x:a.scale,y:i.scale}),l=s.apply({x:r,y:n},{bandAware:!0});return $r(t,"discard")&&!s.isInRange(l)?null:l},sf=function(e){function t(){return CX(this,t),TX(this,t,arguments)}return LX(t,e),$X(t,[{key:"render",value:function(){var n=this.props,a=n.x,i=n.y,s=n.r,l=n.alwaysShow,c=n.clipPathId,u=qe(a),f=qe(i);if(yr(l===void 0,'The alwaysShow prop is deprecated. Please use ifOverflow="extendDomain" instead.'),!u||!f)return null;var d=RX(this.props);if(!d)return null;var h=d.x,p=d.y,g=this.props,y=g.shape,b=g.className,v=$r(this.props,"hidden")?"url(#".concat(c,")"):void 0,m=oj(oj({clipPath:v},X(this.props,!0)),{},{cx:h,cy:p});return $.createElement(ne,{className:ee("recharts-reference-dot",b)},t.renderDot(y,m),tt.renderCallByParent(this.props,{x:h-s,y:p-s,width:2*s,height:2*s}))}}])}($.Component);of(sf,"displayName","ReferenceDot");of(sf,"defaultProps",{isFront:!1,ifOverflow:"discard",xAxisId:0,yAxisId:0,r:10,fill:"#fff",stroke:"#ccc",fillOpacity:1,strokeWidth:1});of(sf,"renderDot",function(e,t){var r;return $.isValidElement(e)?r=$.cloneElement(e,t):Q(e)?r=e(t):r=$.createElement(Zd,Am({},t,{cx:t.cx,cy:t.cy,className:"recharts-reference-dot-dot"})),r});function Em(){return Em=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},Em.apply(this,arguments)}function Vi(e){"@babel/helpers - typeof";return Vi=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Vi(e)}function sj(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function lj(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?sj(Object(r),!0).forEach(function(n){lf(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):sj(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function BX(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function FX(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,CO(n.key),n)}}function zX(e,t,r){return t&&FX(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function WX(e,t,r){return t=qu(t),UX(e,AO()?Reflect.construct(t,r||[],qu(e).constructor):t.apply(e,r))}function UX(e,t){if(t&&(Vi(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return HX(e)}function HX(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function AO(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(AO=function(){return!!e})()}function qu(e){return qu=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},qu(e)}function KX(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&$m(e,t)}function $m(e,t){return $m=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,a){return n.__proto__=a,n},$m(e,t)}function lf(e,t,r){return t=CO(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function CO(e){var t=VX(e,"string");return Vi(t)=="symbol"?t:t+""}function VX(e,t){if(Vi(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(Vi(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}var GX=function(t,r,n,a,i){var s=i.x1,l=i.x2,c=i.y1,u=i.y2,f=i.xAxis,d=i.yAxis;if(!f||!d)return null;var h=Wy({x:f.scale,y:d.scale}),p={x:t?h.x.apply(s,{position:"start"}):h.x.rangeMin,y:n?h.y.apply(c,{position:"start"}):h.y.rangeMin},g={x:r?h.x.apply(l,{position:"end"}):h.x.rangeMax,y:a?h.y.apply(u,{position:"end"}):h.y.rangeMax};return $r(i,"discard")&&(!h.isInRange(p)||!h.isInRange(g))?null:vO(p,g)},cf=function(e){function t(){return BX(this,t),WX(this,t,arguments)}return KX(t,e),zX(t,[{key:"render",value:function(){var n=this.props,a=n.x1,i=n.x2,s=n.y1,l=n.y2,c=n.className,u=n.alwaysShow,f=n.clipPathId;yr(u===void 0,'The alwaysShow prop is deprecated. Please use ifOverflow="extendDomain" instead.');var d=qe(a),h=qe(i),p=qe(s),g=qe(l),y=this.props.shape;if(!d&&!h&&!p&&!g&&!y)return null;var b=GX(d,h,p,g,this.props);if(!b&&!y)return null;var v=$r(this.props,"hidden")?"url(#".concat(f,")"):void 0;return $.createElement(ne,{className:ee("recharts-reference-area",c)},t.renderRect(y,lj(lj({clipPath:v},X(this.props,!0)),b)),tt.renderCallByParent(this.props,b))}}])}($.Component);lf(cf,"displayName","ReferenceArea");lf(cf,"defaultProps",{isFront:!1,ifOverflow:"discard",xAxisId:0,yAxisId:0,r:10,fill:"#ccc",fillOpacity:.5,stroke:"none",strokeWidth:1});lf(cf,"renderRect",function(e,t){var r;return $.isValidElement(e)?r=$.cloneElement(e,t):Q(e)?r=e(t):r=$.createElement(Fy,Em({},t,{className:"recharts-reference-area-rect"})),r});function EO(e,t,r){if(t<1)return[];if(t===1&&r===void 0)return e;for(var n=[],a=0;a<e.length;a+=t)n.push(e[a]);return n}function YX(e,t,r){var n={width:e.width+t.width,height:e.height+t.height};return Wq(n,r)}function qX(e,t,r){var n=r==="width",a=e.x,i=e.y,s=e.width,l=e.height;return t===1?{start:n?a:i,end:n?a+s:i+l}:{start:n?a+s:i+l,end:n?a:i}}function Xu(e,t,r,n,a){if(e*t<e*n||e*t>e*a)return!1;var i=r();return e*(t-e*i/2-n)>=0&&e*(t+e*i/2-a)<=0}function XX(e,t){return EO(e,t+1)}function QX(e,t,r,n,a){for(var i=(n||[]).slice(),s=t.start,l=t.end,c=0,u=1,f=s,d=function(){var g=n==null?void 0:n[c];if(g===void 0)return{v:EO(n,u)};var y=c,b,v=function(){return b===void 0&&(b=r(g,y)),b},m=g.coordinate,x=c===0||Xu(e,m,v,f,l);x||(c=0,f=s,u+=1),x&&(f=m+e*(v()/2+a),c+=u)},h;u<=i.length;)if(h=d(),h)return h.v;return[]}function il(e){"@babel/helpers - typeof";return il=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},il(e)}function cj(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function ht(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?cj(Object(r),!0).forEach(function(n){JX(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):cj(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function JX(e,t,r){return t=ZX(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function ZX(e){var t=eQ(e,"string");return il(t)=="symbol"?t:t+""}function eQ(e,t){if(il(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(il(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function tQ(e,t,r,n,a){for(var i=(n||[]).slice(),s=i.length,l=t.start,c=t.end,u=function(h){var p=i[h],g,y=function(){return g===void 0&&(g=r(p,h)),g};if(h===s-1){var b=e*(p.coordinate+e*y()/2-c);i[h]=p=ht(ht({},p),{},{tickCoord:b>0?p.coordinate-b*e:p.coordinate})}else i[h]=p=ht(ht({},p),{},{tickCoord:p.coordinate});var v=Xu(e,p.tickCoord,y,l,c);v&&(c=p.tickCoord-e*(y()/2+a),i[h]=ht(ht({},p),{},{isShow:!0}))},f=s-1;f>=0;f--)u(f);return i}function rQ(e,t,r,n,a,i){var s=(n||[]).slice(),l=s.length,c=t.start,u=t.end;if(i){var f=n[l-1],d=r(f,l-1),h=e*(f.coordinate+e*d/2-u);s[l-1]=f=ht(ht({},f),{},{tickCoord:h>0?f.coordinate-h*e:f.coordinate});var p=Xu(e,f.tickCoord,function(){return d},c,u);p&&(u=f.tickCoord-e*(d/2+a),s[l-1]=ht(ht({},f),{},{isShow:!0}))}for(var g=i?l-1:l,y=function(m){var x=s[m],S,j=function(){return S===void 0&&(S=r(x,m)),S};if(m===0){var w=e*(x.coordinate-e*j()/2-c);s[m]=x=ht(ht({},x),{},{tickCoord:w<0?x.coordinate-w*e:x.coordinate})}else s[m]=x=ht(ht({},x),{},{tickCoord:x.coordinate});var _=Xu(e,x.tickCoord,j,c,u);_&&(c=x.tickCoord+e*(j()/2+a),s[m]=ht(ht({},x),{},{isShow:!0}))},b=0;b<g;b++)y(b);return s}function qy(e,t,r){var n=e.tick,a=e.ticks,i=e.viewBox,s=e.minTickGap,l=e.orientation,c=e.interval,u=e.tickFormatter,f=e.unit,d=e.angle;if(!a||!a.length||!n)return[];if(U(c)||Wn.isSsr)return XX(a,typeof c=="number"&&U(c)?c:0);var h=[],p=l==="top"||l==="bottom"?"width":"height",g=f&&p==="width"?ts(f,{fontSize:t,letterSpacing:r}):{width:0,height:0},y=function(x,S){var j=Q(u)?u(x.value,S):x.value;return p==="width"?YX(ts(j,{fontSize:t,letterSpacing:r}),g,d):ts(j,{fontSize:t,letterSpacing:r})[p]},b=a.length>=2?rt(a[1].coordinate-a[0].coordinate):1,v=qX(i,b,p);return c==="equidistantPreserveStart"?QX(b,v,y,a,s):(c==="preserveStart"||c==="preserveStartEnd"?h=rQ(b,v,y,a,s,c==="preserveStartEnd"):h=tQ(b,v,y,a,s),h.filter(function(m){return m.isShow}))}var nQ=["viewBox"],aQ=["viewBox"],iQ=["ticks"];function Gi(e){"@babel/helpers - typeof";return Gi=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Gi(e)}function si(){return si=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},si.apply(this,arguments)}function uj(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function He(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?uj(Object(r),!0).forEach(function(n){Xy(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):uj(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function hh(e,t){if(e==null)return{};var r=oQ(e,t),n,a;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(a=0;a<i.length;a++)n=i[a],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function oQ(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function sQ(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function dj(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,TO(n.key),n)}}function lQ(e,t,r){return t&&dj(e.prototype,t),r&&dj(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function cQ(e,t,r){return t=Qu(t),uQ(e,$O()?Reflect.construct(t,r||[],Qu(e).constructor):t.apply(e,r))}function uQ(e,t){if(t&&(Gi(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return dQ(e)}function dQ(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function $O(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return($O=function(){return!!e})()}function Qu(e){return Qu=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},Qu(e)}function fQ(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Tm(e,t)}function Tm(e,t){return Tm=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,a){return n.__proto__=a,n},Tm(e,t)}function Xy(e,t,r){return t=TO(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function TO(e){var t=hQ(e,"string");return Gi(t)=="symbol"?t:t+""}function hQ(e,t){if(Gi(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(Gi(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}var go=function(e){function t(r){var n;return sQ(this,t),n=cQ(this,t,[r]),n.state={fontSize:"",letterSpacing:""},n}return fQ(t,e),lQ(t,[{key:"shouldComponentUpdate",value:function(n,a){var i=n.viewBox,s=hh(n,nQ),l=this.props,c=l.viewBox,u=hh(l,aQ);return!mi(i,c)||!mi(s,u)||!mi(a,this.state)}},{key:"componentDidMount",value:function(){var n=this.layerReference;if(n){var a=n.getElementsByClassName("recharts-cartesian-axis-tick-value")[0];a&&this.setState({fontSize:window.getComputedStyle(a).fontSize,letterSpacing:window.getComputedStyle(a).letterSpacing})}}},{key:"getTickLineCoord",value:function(n){var a=this.props,i=a.x,s=a.y,l=a.width,c=a.height,u=a.orientation,f=a.tickSize,d=a.mirror,h=a.tickMargin,p,g,y,b,v,m,x=d?-1:1,S=n.tickSize||f,j=U(n.tickCoord)?n.tickCoord:n.coordinate;switch(u){case"top":p=g=n.coordinate,b=s+ +!d*c,y=b-x*S,m=y-x*h,v=j;break;case"left":y=b=n.coordinate,g=i+ +!d*l,p=g-x*S,v=p-x*h,m=j;break;case"right":y=b=n.coordinate,g=i+ +d*l,p=g+x*S,v=p+x*h,m=j;break;default:p=g=n.coordinate,b=s+ +d*c,y=b+x*S,m=y+x*h,v=j;break}return{line:{x1:p,y1:y,x2:g,y2:b},tick:{x:v,y:m}}}},{key:"getTickTextAnchor",value:function(){var n=this.props,a=n.orientation,i=n.mirror,s;switch(a){case"left":s=i?"start":"end";break;case"right":s=i?"end":"start";break;default:s="middle";break}return s}},{key:"getTickVerticalAnchor",value:function(){var n=this.props,a=n.orientation,i=n.mirror,s="end";switch(a){case"left":case"right":s="middle";break;case"top":s=i?"start":"end";break;default:s=i?"end":"start";break}return s}},{key:"renderAxisLine",value:function(){var n=this.props,a=n.x,i=n.y,s=n.width,l=n.height,c=n.orientation,u=n.mirror,f=n.axisLine,d=He(He(He({},X(this.props,!1)),X(f,!1)),{},{fill:"none"});if(c==="top"||c==="bottom"){var h=+(c==="top"&&!u||c==="bottom"&&u);d=He(He({},d),{},{x1:a,y1:i+h*l,x2:a+s,y2:i+h*l})}else{var p=+(c==="left"&&!u||c==="right"&&u);d=He(He({},d),{},{x1:a+p*s,y1:i,x2:a+p*s,y2:i+l})}return $.createElement("line",si({},d,{className:ee("recharts-cartesian-axis-line",Bt(f,"className"))}))}},{key:"renderTicks",value:function(n,a,i){var s=this,l=this.props,c=l.tickLine,u=l.stroke,f=l.tick,d=l.tickFormatter,h=l.unit,p=qy(He(He({},this.props),{},{ticks:n}),a,i),g=this.getTickTextAnchor(),y=this.getTickVerticalAnchor(),b=X(this.props,!1),v=X(f,!1),m=He(He({},b),{},{fill:"none"},X(c,!1)),x=p.map(function(S,j){var w=s.getTickLineCoord(S),_=w.line,O=w.tick,N=He(He(He(He({textAnchor:g,verticalAnchor:y},b),{},{stroke:"none",fill:u},v),O),{},{index:j,payload:S,visibleTicksCount:p.length,tickFormatter:d});return $.createElement(ne,si({className:"recharts-cartesian-axis-tick",key:"tick-".concat(S.value,"-").concat(S.coordinate,"-").concat(S.tickCoord)},en(s.props,S,j)),c&&$.createElement("line",si({},m,_,{className:ee("recharts-cartesian-axis-tick-line",Bt(c,"className"))})),f&&t.renderTickItem(f,N,"".concat(Q(d)?d(S.value,j):S.value).concat(h||"")))});return $.createElement("g",{className:"recharts-cartesian-axis-ticks"},x)}},{key:"render",value:function(){var n=this,a=this.props,i=a.axisLine,s=a.width,l=a.height,c=a.ticksGenerator,u=a.className,f=a.hide;if(f)return null;var d=this.props,h=d.ticks,p=hh(d,iQ),g=h;return Q(c)&&(g=h&&h.length>0?c(this.props):c(p)),s<=0||l<=0||!g||!g.length?null:$.createElement(ne,{className:ee("recharts-cartesian-axis",u),ref:function(b){n.layerReference=b}},i&&this.renderAxisLine(),this.renderTicks(g,this.state.fontSize,this.state.letterSpacing),tt.renderCallByParent(this.props))}}],[{key:"renderTickItem",value:function(n,a,i){var s,l=ee(a.className,"recharts-cartesian-axis-tick-value");return $.isValidElement(n)?s=$.cloneElement(n,He(He({},a),{},{className:l})):Q(n)?s=n(He(He({},a),{},{className:l})):s=$.createElement(Sa,si({},a,{className:"recharts-cartesian-axis-tick-value"}),i),s}}])}(P.Component);Xy(go,"displayName","CartesianAxis");Xy(go,"defaultProps",{x:0,y:0,width:0,height:0,viewBox:{x:0,y:0,width:0,height:0},orientation:"bottom",ticks:[],stroke:"#666",tickLine:!0,axisLine:!0,tick:!0,mirror:!1,minTickGap:5,tickSize:6,tickMargin:2,interval:"preserveEnd"});var pQ=["x1","y1","x2","y2","key"],mQ=["offset"];function Na(e){"@babel/helpers - typeof";return Na=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Na(e)}function fj(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function mt(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?fj(Object(r),!0).forEach(function(n){vQ(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):fj(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function vQ(e,t,r){return t=yQ(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function yQ(e){var t=gQ(e,"string");return Na(t)=="symbol"?t:t+""}function gQ(e,t){if(Na(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(Na(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function ca(){return ca=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},ca.apply(this,arguments)}function hj(e,t){if(e==null)return{};var r=xQ(e,t),n,a;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(a=0;a<i.length;a++)n=i[a],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function xQ(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}var bQ=function(t){var r=t.fill;if(!r||r==="none")return null;var n=t.fillOpacity,a=t.x,i=t.y,s=t.width,l=t.height,c=t.ry;return $.createElement("rect",{x:a,y:i,ry:c,width:s,height:l,stroke:"none",fill:r,fillOpacity:n,className:"recharts-cartesian-grid-bg"})};function MO(e,t){var r;if($.isValidElement(e))r=$.cloneElement(e,t);else if(Q(e))r=e(t);else{var n=t.x1,a=t.y1,i=t.x2,s=t.y2,l=t.key,c=hj(t,pQ),u=X(c,!1);u.offset;var f=hj(u,mQ);r=$.createElement("line",ca({},f,{x1:n,y1:a,x2:i,y2:s,fill:"none",key:l}))}return r}function jQ(e){var t=e.x,r=e.width,n=e.horizontal,a=n===void 0?!0:n,i=e.horizontalPoints;if(!a||!i||!i.length)return null;var s=i.map(function(l,c){var u=mt(mt({},e),{},{x1:t,y1:l,x2:t+r,y2:l,key:"line-".concat(c),index:c});return MO(a,u)});return $.createElement("g",{className:"recharts-cartesian-grid-horizontal"},s)}function wQ(e){var t=e.y,r=e.height,n=e.vertical,a=n===void 0?!0:n,i=e.verticalPoints;if(!a||!i||!i.length)return null;var s=i.map(function(l,c){var u=mt(mt({},e),{},{x1:l,y1:t,x2:l,y2:t+r,key:"line-".concat(c),index:c});return MO(a,u)});return $.createElement("g",{className:"recharts-cartesian-grid-vertical"},s)}function SQ(e){var t=e.horizontalFill,r=e.fillOpacity,n=e.x,a=e.y,i=e.width,s=e.height,l=e.horizontalPoints,c=e.horizontal,u=c===void 0?!0:c;if(!u||!t||!t.length)return null;var f=l.map(function(h){return Math.round(h+a-a)}).sort(function(h,p){return h-p});a!==f[0]&&f.unshift(0);var d=f.map(function(h,p){var g=!f[p+1],y=g?a+s-h:f[p+1]-h;if(y<=0)return null;var b=p%t.length;return $.createElement("rect",{key:"react-".concat(p),y:h,x:n,height:y,width:i,stroke:"none",fill:t[b],fillOpacity:r,className:"recharts-cartesian-grid-bg"})});return $.createElement("g",{className:"recharts-cartesian-gridstripes-horizontal"},d)}function _Q(e){var t=e.vertical,r=t===void 0?!0:t,n=e.verticalFill,a=e.fillOpacity,i=e.x,s=e.y,l=e.width,c=e.height,u=e.verticalPoints;if(!r||!n||!n.length)return null;var f=u.map(function(h){return Math.round(h+i-i)}).sort(function(h,p){return h-p});i!==f[0]&&f.unshift(0);var d=f.map(function(h,p){var g=!f[p+1],y=g?i+l-h:f[p+1]-h;if(y<=0)return null;var b=p%n.length;return $.createElement("rect",{key:"react-".concat(p),x:h,y:s,width:y,height:c,stroke:"none",fill:n[b],fillOpacity:a,className:"recharts-cartesian-grid-bg"})});return $.createElement("g",{className:"recharts-cartesian-gridstripes-vertical"},d)}var kQ=function(t,r){var n=t.xAxis,a=t.width,i=t.height,s=t.offset;return Ok(qy(mt(mt(mt({},go.defaultProps),n),{},{ticks:Vr(n,!0),viewBox:{x:0,y:0,width:a,height:i}})),s.left,s.left+s.width,r)},OQ=function(t,r){var n=t.yAxis,a=t.width,i=t.height,s=t.offset;return Ok(qy(mt(mt(mt({},go.defaultProps),n),{},{ticks:Vr(n,!0),viewBox:{x:0,y:0,width:a,height:i}})),s.top,s.top+s.height,r)},Fa={horizontal:!0,vertical:!0,stroke:"#ccc",fill:"none",verticalFill:[],horizontalFill:[]};function Ia(e){var t,r,n,a,i,s,l=Ky(),c=Vy(),u=hX(),f=mt(mt({},e),{},{stroke:(t=e.stroke)!==null&&t!==void 0?t:Fa.stroke,fill:(r=e.fill)!==null&&r!==void 0?r:Fa.fill,horizontal:(n=e.horizontal)!==null&&n!==void 0?n:Fa.horizontal,horizontalFill:(a=e.horizontalFill)!==null&&a!==void 0?a:Fa.horizontalFill,vertical:(i=e.vertical)!==null&&i!==void 0?i:Fa.vertical,verticalFill:(s=e.verticalFill)!==null&&s!==void 0?s:Fa.verticalFill,x:U(e.x)?e.x:u.left,y:U(e.y)?e.y:u.top,width:U(e.width)?e.width:u.width,height:U(e.height)?e.height:u.height}),d=f.x,h=f.y,p=f.width,g=f.height,y=f.syncWithTicks,b=f.horizontalValues,v=f.verticalValues,m=uX(),x=dX();if(!U(p)||p<=0||!U(g)||g<=0||!U(d)||d!==+d||!U(h)||h!==+h)return null;var S=f.verticalCoordinatesGenerator||kQ,j=f.horizontalCoordinatesGenerator||OQ,w=f.horizontalPoints,_=f.verticalPoints;if((!w||!w.length)&&Q(j)){var O=b&&b.length,N=j({yAxis:x?mt(mt({},x),{},{ticks:O?b:x.ticks}):void 0,width:l,height:c,offset:u},O?!0:y);yr(Array.isArray(N),"horizontalCoordinatesGenerator should return Array but instead it returned [".concat(Na(N),"]")),Array.isArray(N)&&(w=N)}if((!_||!_.length)&&Q(S)){var k=v&&v.length,E=S({xAxis:m?mt(mt({},m),{},{ticks:k?v:m.ticks}):void 0,width:l,height:c,offset:u},k?!0:y);yr(Array.isArray(E),"verticalCoordinatesGenerator should return Array but instead it returned [".concat(Na(E),"]")),Array.isArray(E)&&(_=E)}return $.createElement("g",{className:"recharts-cartesian-grid"},$.createElement(bQ,{fill:f.fill,fillOpacity:f.fillOpacity,x:f.x,y:f.y,width:f.width,height:f.height,ry:f.ry}),$.createElement(jQ,ca({},f,{offset:u,horizontalPoints:w,xAxis:m,yAxis:x})),$.createElement(wQ,ca({},f,{offset:u,verticalPoints:_,xAxis:m,yAxis:x})),$.createElement(SQ,ca({},f,{horizontalPoints:w})),$.createElement(_Q,ca({},f,{verticalPoints:_})))}Ia.displayName="CartesianGrid";var NQ=["layout","type","stroke","connectNulls","isRange","ref"],PQ=["key"],IO;function Yi(e){"@babel/helpers - typeof";return Yi=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Yi(e)}function LO(e,t){if(e==null)return{};var r=AQ(e,t),n,a;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(a=0;a<i.length;a++)n=i[a],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function AQ(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function ua(){return ua=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},ua.apply(this,arguments)}function pj(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function dn(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?pj(Object(r),!0).forEach(function(n){Nr(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):pj(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function CQ(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function mj(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,RO(n.key),n)}}function EQ(e,t,r){return t&&mj(e.prototype,t),r&&mj(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function $Q(e,t,r){return t=Ju(t),TQ(e,DO()?Reflect.construct(t,r||[],Ju(e).constructor):t.apply(e,r))}function TQ(e,t){if(t&&(Yi(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return MQ(e)}function MQ(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function DO(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(DO=function(){return!!e})()}function Ju(e){return Ju=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},Ju(e)}function IQ(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Mm(e,t)}function Mm(e,t){return Mm=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,a){return n.__proto__=a,n},Mm(e,t)}function Nr(e,t,r){return t=RO(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function RO(e){var t=LQ(e,"string");return Yi(t)=="symbol"?t:t+""}function LQ(e,t){if(Yi(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(Yi(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}var Lr=function(e){function t(){var r;CQ(this,t);for(var n=arguments.length,a=new Array(n),i=0;i<n;i++)a[i]=arguments[i];return r=$Q(this,t,[].concat(a)),Nr(r,"state",{isAnimationFinished:!0}),Nr(r,"id",uo("recharts-area-")),Nr(r,"handleAnimationEnd",function(){var s=r.props.onAnimationEnd;r.setState({isAnimationFinished:!0}),Q(s)&&s()}),Nr(r,"handleAnimationStart",function(){var s=r.props.onAnimationStart;r.setState({isAnimationFinished:!1}),Q(s)&&s()}),r}return IQ(t,e),EQ(t,[{key:"renderDots",value:function(n,a,i){var s=this.props.isAnimationActive,l=this.state.isAnimationFinished;if(s&&!l)return null;var c=this.props,u=c.dot,f=c.points,d=c.dataKey,h=X(this.props,!1),p=X(u,!0),g=f.map(function(b,v){var m=dn(dn(dn({key:"dot-".concat(v),r:3},h),p),{},{index:v,cx:b.x,cy:b.y,dataKey:d,value:b.value,payload:b.payload,points:f});return t.renderDotItem(u,m)}),y={clipPath:n?"url(#clipPath-".concat(a?"":"dots-").concat(i,")"):null};return $.createElement(ne,ua({className:"recharts-area-dots"},y),g)}},{key:"renderHorizontalRect",value:function(n){var a=this.props,i=a.baseLine,s=a.points,l=a.strokeWidth,c=s[0].x,u=s[s.length-1].x,f=n*Math.abs(c-u),d=wn(s.map(function(h){return h.y||0}));return U(i)&&typeof i=="number"?d=Math.max(i,d):i&&Array.isArray(i)&&i.length&&(d=Math.max(wn(i.map(function(h){return h.y||0})),d)),U(d)?$.createElement("rect",{x:c<u?c:c-f,y:0,width:f,height:Math.floor(d+(l?parseInt("".concat(l),10):1))}):null}},{key:"renderVerticalRect",value:function(n){var a=this.props,i=a.baseLine,s=a.points,l=a.strokeWidth,c=s[0].y,u=s[s.length-1].y,f=n*Math.abs(c-u),d=wn(s.map(function(h){return h.x||0}));return U(i)&&typeof i=="number"?d=Math.max(i,d):i&&Array.isArray(i)&&i.length&&(d=Math.max(wn(i.map(function(h){return h.x||0})),d)),U(d)?$.createElement("rect",{x:0,y:c<u?c:c-f,width:d+(l?parseInt("".concat(l),10):1),height:Math.floor(f)}):null}},{key:"renderClipRect",value:function(n){var a=this.props.layout;return a==="vertical"?this.renderVerticalRect(n):this.renderHorizontalRect(n)}},{key:"renderAreaStatically",value:function(n,a,i,s){var l=this.props,c=l.layout,u=l.type,f=l.stroke,d=l.connectNulls,h=l.isRange;l.ref;var p=LO(l,NQ);return $.createElement(ne,{clipPath:i?"url(#clipPath-".concat(s,")"):null},$.createElement(xi,ua({},X(p,!0),{points:n,connectNulls:d,type:u,baseLine:a,layout:c,stroke:"none",className:"recharts-area-area"})),f!=="none"&&$.createElement(xi,ua({},X(this.props,!1),{className:"recharts-area-curve",layout:c,type:u,connectNulls:d,fill:"none",points:n})),f!=="none"&&h&&$.createElement(xi,ua({},X(this.props,!1),{className:"recharts-area-curve",layout:c,type:u,connectNulls:d,fill:"none",points:a})))}},{key:"renderAreaWithAnimation",value:function(n,a){var i=this,s=this.props,l=s.points,c=s.baseLine,u=s.isAnimationActive,f=s.animationBegin,d=s.animationDuration,h=s.animationEasing,p=s.animationId,g=this.state,y=g.prevPoints,b=g.prevBaseLine;return $.createElement(br,{begin:f,duration:d,isActive:u,easing:h,from:{t:0},to:{t:1},key:"area-".concat(p),onAnimationEnd:this.handleAnimationEnd,onAnimationStart:this.handleAnimationStart},function(v){var m=v.t;if(y){var x=y.length/l.length,S=l.map(function(O,N){var k=Math.floor(N*x);if(y[k]){var E=y[k],T=lt(E.x,O.x),D=lt(E.y,O.y);return dn(dn({},O),{},{x:T(m),y:D(m)})}return O}),j;if(U(c)&&typeof c=="number"){var w=lt(b,c);j=w(m)}else if(te(c)||co(c)){var _=lt(b,0);j=_(m)}else j=c.map(function(O,N){var k=Math.floor(N*x);if(b[k]){var E=b[k],T=lt(E.x,O.x),D=lt(E.y,O.y);return dn(dn({},O),{},{x:T(m),y:D(m)})}return O});return i.renderAreaStatically(S,j,n,a)}return $.createElement(ne,null,$.createElement("defs",null,$.createElement("clipPath",{id:"animationClipPath-".concat(a)},i.renderClipRect(m))),$.createElement(ne,{clipPath:"url(#animationClipPath-".concat(a,")")},i.renderAreaStatically(l,c,n,a)))})}},{key:"renderArea",value:function(n,a){var i=this.props,s=i.points,l=i.baseLine,c=i.isAnimationActive,u=this.state,f=u.prevPoints,d=u.prevBaseLine,h=u.totalLength;return c&&s&&s.length&&(!f&&h>0||!_a(f,s)||!_a(d,l))?this.renderAreaWithAnimation(n,a):this.renderAreaStatically(s,l,n,a)}},{key:"render",value:function(){var n,a=this.props,i=a.hide,s=a.dot,l=a.points,c=a.className,u=a.top,f=a.left,d=a.xAxis,h=a.yAxis,p=a.width,g=a.height,y=a.isAnimationActive,b=a.id;if(i||!l||!l.length)return null;var v=this.state.isAnimationFinished,m=l.length===1,x=ee("recharts-area",c),S=d&&d.allowDataOverflow,j=h&&h.allowDataOverflow,w=S||j,_=te(b)?this.id:b,O=(n=X(s,!1))!==null&&n!==void 0?n:{r:3,strokeWidth:2},N=O.r,k=N===void 0?3:N,E=O.strokeWidth,T=E===void 0?2:E,D=q3(s)?s:{},A=D.clipDot,L=A===void 0?!0:A,C=k*2+T;return $.createElement(ne,{className:x},S||j?$.createElement("defs",null,$.createElement("clipPath",{id:"clipPath-".concat(_)},$.createElement("rect",{x:S?f:f-p/2,y:j?u:u-g/2,width:S?p:p*2,height:j?g:g*2})),!L&&$.createElement("clipPath",{id:"clipPath-dots-".concat(_)},$.createElement("rect",{x:f-C/2,y:u-C/2,width:p+C,height:g+C}))):null,m?null:this.renderArea(w,_),(s||m)&&this.renderDots(w,L,_),(!y||v)&&Er.renderCallByParent(this.props,l))}}],[{key:"getDerivedStateFromProps",value:function(n,a){return n.animationId!==a.prevAnimationId?{prevAnimationId:n.animationId,curPoints:n.points,curBaseLine:n.baseLine,prevPoints:a.curPoints,prevBaseLine:a.curBaseLine}:n.points!==a.curPoints||n.baseLine!==a.curBaseLine?{curPoints:n.points,curBaseLine:n.baseLine}:null}}])}(P.PureComponent);IO=Lr;Nr(Lr,"displayName","Area");Nr(Lr,"defaultProps",{stroke:"#3182bd",fill:"#3182bd",fillOpacity:.6,xAxisId:0,yAxisId:0,legendType:"line",connectNulls:!1,points:[],dot:!1,activeDot:!0,hide:!1,isAnimationActive:!Wn.isSsr,animationBegin:0,animationDuration:1500,animationEasing:"ease"});Nr(Lr,"getBaseValue",function(e,t,r,n){var a=e.layout,i=e.baseValue,s=t.props.baseValue,l=s??i;if(U(l)&&typeof l=="number")return l;var c=a==="horizontal"?n:r,u=c.scale.domain();if(c.type==="number"){var f=Math.max(u[0],u[1]),d=Math.min(u[0],u[1]);return l==="dataMin"?d:l==="dataMax"||f<0?f:Math.max(Math.min(u[0],u[1]),0)}return l==="dataMin"?u[0]:l==="dataMax"?u[1]:u[0]});Nr(Lr,"getComposedData",function(e){var t=e.props,r=e.item,n=e.xAxis,a=e.yAxis,i=e.xAxisTicks,s=e.yAxisTicks,l=e.bandSize,c=e.dataKey,u=e.stackedData,f=e.dataStartIndex,d=e.displayedData,h=e.offset,p=t.layout,g=u&&u.length,y=IO.getBaseValue(t,r,n,a),b=p==="horizontal",v=!1,m=d.map(function(S,j){var w;g?w=u[f+j]:(w=Be(S,c),Array.isArray(w)?v=!0:w=[y,w]);var _=w[1]==null||g&&Be(S,c)==null;return b?{x:Rb({axis:n,ticks:i,bandSize:l,entry:S,index:j}),y:_?null:a.scale(w[1]),value:w,payload:S}:{x:_?null:n.scale(w[1]),y:Rb({axis:a,ticks:s,bandSize:l,entry:S,index:j}),value:w,payload:S}}),x;return g||v?x=m.map(function(S){var j=Array.isArray(S.value)?S.value[0]:null;return b?{x:S.x,y:j!=null&&S.y!=null?a.scale(j):null}:{x:j!=null?n.scale(j):null,y:S.y}}):x=b?a.scale(y):n.scale(y),dn({points:m,baseLine:x,layout:p,isRange:v},h)});Nr(Lr,"renderDotItem",function(e,t){var r;if($.isValidElement(e))r=$.cloneElement(e,t);else if(Q(e))r=e(t);else{var n=ee("recharts-area-dot",typeof e!="boolean"?e.className:""),a=t.key,i=LO(t,PQ);r=$.createElement(Zd,ua({},i,{key:a,className:n}))}return r});function qi(e){"@babel/helpers - typeof";return qi=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},qi(e)}function DQ(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function RQ(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,zO(n.key),n)}}function BQ(e,t,r){return t&&RQ(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function FQ(e,t,r){return t=Zu(t),zQ(e,BO()?Reflect.construct(t,r||[],Zu(e).constructor):t.apply(e,r))}function zQ(e,t){if(t&&(qi(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return WQ(e)}function WQ(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function BO(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(BO=function(){return!!e})()}function Zu(e){return Zu=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},Zu(e)}function UQ(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Im(e,t)}function Im(e,t){return Im=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,a){return n.__proto__=a,n},Im(e,t)}function FO(e,t,r){return t=zO(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function zO(e){var t=HQ(e,"string");return qi(t)=="symbol"?t:t+""}function HQ(e,t){if(qi(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(qi(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}function Lm(){return Lm=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},Lm.apply(this,arguments)}function KQ(e){var t=e.xAxisId,r=Ky(),n=Vy(),a=SO(t);return a==null?null:P.createElement(go,Lm({},a,{className:ee("recharts-".concat(a.axisType," ").concat(a.axisType),a.className),viewBox:{x:0,y:0,width:r,height:n},ticksGenerator:function(s){return Vr(s,!0)}}))}var or=function(e){function t(){return DQ(this,t),FQ(this,t,arguments)}return UQ(t,e),BQ(t,[{key:"render",value:function(){return P.createElement(KQ,this.props)}}])}(P.Component);FO(or,"displayName","XAxis");FO(or,"defaultProps",{allowDecimals:!0,hide:!1,orientation:"bottom",width:0,height:30,mirror:!1,xAxisId:0,tickCount:5,type:"category",padding:{left:0,right:0},allowDataOverflow:!1,scale:"auto",reversed:!1,allowDuplicatedCategory:!0});function Xi(e){"@babel/helpers - typeof";return Xi=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Xi(e)}function VQ(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function GQ(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,HO(n.key),n)}}function YQ(e,t,r){return t&&GQ(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function qQ(e,t,r){return t=ed(t),XQ(e,WO()?Reflect.construct(t,r||[],ed(e).constructor):t.apply(e,r))}function XQ(e,t){if(t&&(Xi(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return QQ(e)}function QQ(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function WO(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(WO=function(){return!!e})()}function ed(e){return ed=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},ed(e)}function JQ(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Dm(e,t)}function Dm(e,t){return Dm=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,a){return n.__proto__=a,n},Dm(e,t)}function UO(e,t,r){return t=HO(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function HO(e){var t=ZQ(e,"string");return Xi(t)=="symbol"?t:t+""}function ZQ(e,t){if(Xi(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(Xi(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}function Rm(){return Rm=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},Rm.apply(this,arguments)}var eJ=function(t){var r=t.yAxisId,n=Ky(),a=Vy(),i=_O(r);return i==null?null:P.createElement(go,Rm({},i,{className:ee("recharts-".concat(i.axisType," ").concat(i.axisType),i.className),viewBox:{x:0,y:0,width:n,height:a},ticksGenerator:function(l){return Vr(l,!0)}}))},sr=function(e){function t(){return VQ(this,t),qQ(this,t,arguments)}return JQ(t,e),YQ(t,[{key:"render",value:function(){return P.createElement(eJ,this.props)}}])}(P.Component);UO(sr,"displayName","YAxis");UO(sr,"defaultProps",{allowDuplicatedCategory:!0,allowDecimals:!0,hide:!1,orientation:"left",width:60,height:0,mirror:!1,yAxisId:0,tickCount:5,type:"number",padding:{top:0,bottom:0},allowDataOverflow:!1,scale:"auto",reversed:!1});function vj(e){return aJ(e)||nJ(e)||rJ(e)||tJ()}function tJ(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
-In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function rJ(e,t){if(e){if(typeof e=="string")return Bm(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return Bm(e,t)}}function nJ(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function aJ(e){if(Array.isArray(e))return Bm(e)}function Bm(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}var Fm=function(t,r,n,a,i){var s=Ft(t,Yy),l=Ft(t,sf),c=[].concat(vj(s),vj(l)),u=Ft(t,cf),f="".concat(a,"Id"),d=a[0],h=r;if(c.length&&(h=c.reduce(function(y,b){if(b.props[f]===n&&$r(b.props,"extendDomain")&&U(b.props[d])){var v=b.props[d];return[Math.min(y[0],v),Math.max(y[1],v)]}return y},h)),u.length){var p="".concat(d,"1"),g="".concat(d,"2");h=u.reduce(function(y,b){if(b.props[f]===n&&$r(b.props,"extendDomain")&&U(b.props[p])&&U(b.props[g])){var v=b.props[p],m=b.props[g];return[Math.min(y[0],v,m),Math.max(y[1],v,m)]}return y},h)}return i&&i.length&&(h=i.reduce(function(y,b){return U(b)?[Math.min(y[0],b),Math.max(y[1],b)]:y},h)),h},KO={exports:{}};(function(e){var t=Object.prototype.hasOwnProperty,r="~";function n(){}Object.create&&(n.prototype=Object.create(null),new n().__proto__||(r=!1));function a(c,u,f){this.fn=c,this.context=u,this.once=f||!1}function i(c,u,f,d,h){if(typeof f!="function")throw new TypeError("The listener must be a function");var p=new a(f,d||c,h),g=r?r+u:u;return c._events[g]?c._events[g].fn?c._events[g]=[c._events[g],p]:c._events[g].push(p):(c._events[g]=p,c._eventsCount++),c}function s(c,u){--c._eventsCount===0?c._events=new n:delete c._events[u]}function l(){this._events=new n,this._eventsCount=0}l.prototype.eventNames=function(){var u=[],f,d;if(this._eventsCount===0)return u;for(d in f=this._events)t.call(f,d)&&u.push(r?d.slice(1):d);return Object.getOwnPropertySymbols?u.concat(Object.getOwnPropertySymbols(f)):u},l.prototype.listeners=function(u){var f=r?r+u:u,d=this._events[f];if(!d)return[];if(d.fn)return[d.fn];for(var h=0,p=d.length,g=new Array(p);h<p;h++)g[h]=d[h].fn;return g},l.prototype.listenerCount=function(u){var f=r?r+u:u,d=this._events[f];return d?d.fn?1:d.length:0},l.prototype.emit=function(u,f,d,h,p,g){var y=r?r+u:u;if(!this._events[y])return!1;var b=this._events[y],v=arguments.length,m,x;if(b.fn){switch(b.once&&this.removeListener(u,b.fn,void 0,!0),v){case 1:return b.fn.call(b.context),!0;case 2:return b.fn.call(b.context,f),!0;case 3:return b.fn.call(b.context,f,d),!0;case 4:return b.fn.call(b.context,f,d,h),!0;case 5:return b.fn.call(b.context,f,d,h,p),!0;case 6:return b.fn.call(b.context,f,d,h,p,g),!0}for(x=1,m=new Array(v-1);x<v;x++)m[x-1]=arguments[x];b.fn.apply(b.context,m)}else{var S=b.length,j;for(x=0;x<S;x++)switch(b[x].once&&this.removeListener(u,b[x].fn,void 0,!0),v){case 1:b[x].fn.call(b[x].context);break;case 2:b[x].fn.call(b[x].context,f);break;case 3:b[x].fn.call(b[x].context,f,d);break;case 4:b[x].fn.call(b[x].context,f,d,h);break;default:if(!m)for(j=1,m=new Array(v-1);j<v;j++)m[j-1]=arguments[j];b[x].fn.apply(b[x].context,m)}}return!0},l.prototype.on=function(u,f,d){return i(this,u,f,d,!1)},l.prototype.once=function(u,f,d){return i(this,u,f,d,!0)},l.prototype.removeListener=function(u,f,d,h){var p=r?r+u:u;if(!this._events[p])return this;if(!f)return s(this,p),this;var g=this._events[p];if(g.fn)g.fn===f&&(!h||g.once)&&(!d||g.context===d)&&s(this,p);else{for(var y=0,b=[],v=g.length;y<v;y++)(g[y].fn!==f||h&&!g[y].once||d&&g[y].context!==d)&&b.push(g[y]);b.length?this._events[p]=b.length===1?b[0]:b:s(this,p)}return this},l.prototype.removeAllListeners=function(u){var f;return u?(f=r?r+u:u,this._events[f]&&s(this,f)):(this._events=new n,this._eventsCount=0),this},l.prototype.off=l.prototype.removeListener,l.prototype.addListener=l.prototype.on,l.prefixed=r,l.EventEmitter=l,e.exports=l})(KO);var iJ=KO.exports;const oJ=de(iJ);var ph=new oJ,mh="recharts.syncMouseEvents";function ol(e){"@babel/helpers - typeof";return ol=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},ol(e)}function sJ(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function lJ(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,VO(n.key),n)}}function cJ(e,t,r){return t&&lJ(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function vh(e,t,r){return t=VO(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function VO(e){var t=uJ(e,"string");return ol(t)=="symbol"?t:t+""}function uJ(e,t){if(ol(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(ol(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}var dJ=function(){function e(){sJ(this,e),vh(this,"activeIndex",0),vh(this,"coordinateList",[]),vh(this,"layout","horizontal")}return cJ(e,[{key:"setDetails",value:function(r){var n,a=r.coordinateList,i=a===void 0?null:a,s=r.container,l=s===void 0?null:s,c=r.layout,u=c===void 0?null:c,f=r.offset,d=f===void 0?null:f,h=r.mouseHandlerCallback,p=h===void 0?null:h;this.coordinateList=(n=i??this.coordinateList)!==null&&n!==void 0?n:[],this.container=l??this.container,this.layout=u??this.layout,this.offset=d??this.offset,this.mouseHandlerCallback=p??this.mouseHandlerCallback,this.activeIndex=Math.min(Math.max(this.activeIndex,0),this.coordinateList.length-1)}},{key:"focus",value:function(){this.spoofMouse()}},{key:"keyboardEvent",value:function(r){if(this.coordinateList.length!==0)switch(r.key){case"ArrowRight":{if(this.layout!=="horizontal")return;this.activeIndex=Math.min(this.activeIndex+1,this.coordinateList.length-1),this.spoofMouse();break}case"ArrowLeft":{if(this.layout!=="horizontal")return;this.activeIndex=Math.max(this.activeIndex-1,0),this.spoofMouse();break}}}},{key:"setIndex",value:function(r){this.activeIndex=r}},{key:"spoofMouse",value:function(){var r,n;if(this.layout==="horizontal"&&this.coordinateList.length!==0){var a=this.container.getBoundingClientRect(),i=a.x,s=a.y,l=a.height,c=this.coordinateList[this.activeIndex].coordinate,u=((r=window)===null||r===void 0?void 0:r.scrollX)||0,f=((n=window)===null||n===void 0?void 0:n.scrollY)||0,d=i+c+u,h=s+this.offset.top+l/2+f;this.mouseHandlerCallback({pageX:d,pageY:h})}}}])}();function fJ(e,t,r){if(r==="number"&&t===!0&&Array.isArray(e)){var n=e==null?void 0:e[0],a=e==null?void 0:e[1];if(n&&a&&U(n)&&U(a))return!0}return!1}function hJ(e,t,r,n){var a=n/2;return{stroke:"none",fill:"#ccc",x:e==="horizontal"?t.x-a:r.left+.5,y:e==="horizontal"?r.top+.5:t.y-a,width:e==="horizontal"?n:r.width-1,height:e==="horizontal"?r.height-1:n}}function GO(e){var t=e.cx,r=e.cy,n=e.radius,a=e.startAngle,i=e.endAngle,s=ye(t,r,n,a),l=ye(t,r,n,i);return{points:[s,l],cx:t,cy:r,radius:n,startAngle:a,endAngle:i}}function pJ(e,t,r){var n,a,i,s;if(e==="horizontal")n=t.x,i=n,a=r.top,s=r.top+r.height;else if(e==="vertical")a=t.y,s=a,n=r.left,i=r.left+r.width;else if(t.cx!=null&&t.cy!=null)if(e==="centric"){var l=t.cx,c=t.cy,u=t.innerRadius,f=t.outerRadius,d=t.angle,h=ye(l,c,u,d),p=ye(l,c,f,d);n=h.x,a=h.y,i=p.x,s=p.y}else return GO(t);return[{x:n,y:a},{x:i,y:s}]}function sl(e){"@babel/helpers - typeof";return sl=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},sl(e)}function yj(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function nc(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?yj(Object(r),!0).forEach(function(n){mJ(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):yj(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function mJ(e,t,r){return t=vJ(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function vJ(e){var t=yJ(e,"string");return sl(t)=="symbol"?t:t+""}function yJ(e,t){if(sl(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(sl(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function gJ(e){var t,r,n=e.element,a=e.tooltipEventType,i=e.isActive,s=e.activeCoordinate,l=e.activePayload,c=e.offset,u=e.activeTooltipIndex,f=e.tooltipAxisBandSize,d=e.layout,h=e.chartName,p=(t=n.props.cursor)!==null&&t!==void 0?t:(r=n.type.defaultProps)===null||r===void 0?void 0:r.cursor;if(!n||!p||!i||!s||h!=="ScatterChart"&&a!=="axis")return null;var g,y=xi;if(h==="ScatterChart")g=s,y=OV;else if(h==="BarChart")g=hJ(d,s,c,f),y=Fy;else if(d==="radial"){var b=GO(s),v=b.cx,m=b.cy,x=b.radius,S=b.startAngle,j=b.endAngle;g={cx:v,cy:m,startAngle:S,endAngle:j,innerRadius:x,outerRadius:x},y=Fk}else g={points:pJ(d,s,c)},y=xi;var w=nc(nc(nc(nc({stroke:"#ccc",pointerEvents:"none"},c),g),X(p,!1)),{},{payload:l,payloadIndex:u,className:ee("recharts-tooltip-cursor",p.className)});return P.isValidElement(p)?P.cloneElement(p,w):P.createElement(y,w)}var xJ=["item"],bJ=["children","className","width","height","style","compact","title","desc"];function Qi(e){"@babel/helpers - typeof";return Qi=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Qi(e)}function li(){return li=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},li.apply(this,arguments)}function gj(e,t){return SJ(e)||wJ(e,t)||qO(e,t)||jJ()}function jJ(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
-In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function wJ(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,a,i,s,l=[],c=!0,u=!1;try{if(i=(r=r.call(e)).next,t!==0)for(;!(c=(n=i.call(r)).done)&&(l.push(n.value),l.length!==t);c=!0);}catch(f){u=!0,a=f}finally{try{if(!c&&r.return!=null&&(s=r.return(),Object(s)!==s))return}finally{if(u)throw a}}return l}}function SJ(e){if(Array.isArray(e))return e}function xj(e,t){if(e==null)return{};var r=_J(e,t),n,a;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(a=0;a<i.length;a++)n=i[a],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function _J(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function kJ(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function OJ(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,XO(n.key),n)}}function NJ(e,t,r){return t&&OJ(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function PJ(e,t,r){return t=td(t),AJ(e,YO()?Reflect.construct(t,r||[],td(e).constructor):t.apply(e,r))}function AJ(e,t){if(t&&(Qi(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return CJ(e)}function CJ(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function YO(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(YO=function(){return!!e})()}function td(e){return td=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},td(e)}function EJ(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&zm(e,t)}function zm(e,t){return zm=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,a){return n.__proto__=a,n},zm(e,t)}function Ji(e){return MJ(e)||TJ(e)||qO(e)||$J()}function $J(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
-In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function qO(e,t){if(e){if(typeof e=="string")return Wm(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return Wm(e,t)}}function TJ(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function MJ(e){if(Array.isArray(e))return Wm(e)}function Wm(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function bj(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function B(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?bj(Object(r),!0).forEach(function(n){J(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):bj(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function J(e,t,r){return t=XO(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function XO(e){var t=IJ(e,"string");return Qi(t)=="symbol"?t:t+""}function IJ(e,t){if(Qi(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(Qi(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var LJ={xAxis:["bottom","top"],yAxis:["left","right"]},DJ={width:"100%",height:"100%"},QO={x:0,y:0};function ac(e){return e}var RJ=function(t,r){return r==="horizontal"?t.x:r==="vertical"?t.y:r==="centric"?t.angle:t.radius},BJ=function(t,r,n,a){var i=r.find(function(f){return f&&f.index===n});if(i){if(t==="horizontal")return{x:i.coordinate,y:a.y};if(t==="vertical")return{x:a.x,y:i.coordinate};if(t==="centric"){var s=i.coordinate,l=a.radius;return B(B(B({},a),ye(a.cx,a.cy,l,s)),{},{angle:s,radius:l})}var c=i.coordinate,u=a.angle;return B(B(B({},a),ye(a.cx,a.cy,c,u)),{},{angle:u,radius:c})}return QO},uf=function(t,r){var n=r.graphicalItems,a=r.dataStartIndex,i=r.dataEndIndex,s=(n??[]).reduce(function(l,c){var u=c.props.data;return u&&u.length?[].concat(Ji(l),Ji(u)):l},[]);return s.length>0?s:t&&t.length&&U(a)&&U(i)?t.slice(a,i+1):[]};function JO(e){return e==="number"?[0,"auto"]:void 0}var Um=function(t,r,n,a){var i=t.graphicalItems,s=t.tooltipAxis,l=uf(r,t);return n<0||!i||!i.length||n>=l.length?null:i.reduce(function(c,u){var f,d=(f=u.props.data)!==null&&f!==void 0?f:r;d&&t.dataStartIndex+t.dataEndIndex!==0&&t.dataEndIndex-t.dataStartIndex>=n&&(d=d.slice(t.dataStartIndex,t.dataEndIndex+1));var h;if(s.dataKey&&!s.allowDuplicatedCategory){var p=d===void 0?l:d;h=Qc(p,s.dataKey,a)}else h=d&&d[n]||l[n];return h?[].concat(Ji(c),[By(u,h)]):c},[])},jj=function(t,r,n,a){var i=a||{x:t.chartX,y:t.chartY},s=RJ(i,n),l=t.orderedTooltipTicks,c=t.tooltipAxis,u=t.tooltipTicks,f=XW(s,l,u,c);if(f>=0&&u){var d=u[f]&&u[f].value,h=Um(t,r,f,d),p=BJ(n,l,f,i);return{activeTooltipIndex:f,activeLabel:d,activePayload:h,activeCoordinate:p}}return null},FJ=function(t,r){var n=r.axes,a=r.graphicalItems,i=r.axisType,s=r.axisIdKey,l=r.stackGroups,c=r.dataStartIndex,u=r.dataEndIndex,f=t.layout,d=t.children,h=t.stackOffset,p=kk(f,i);return n.reduce(function(g,y){var b,v=y.type.defaultProps!==void 0?B(B({},y.type.defaultProps),y.props):y.props,m=v.type,x=v.dataKey,S=v.allowDataOverflow,j=v.allowDuplicatedCategory,w=v.scale,_=v.ticks,O=v.includeHidden,N=v[s];if(g[N])return g;var k=uf(t.data,{graphicalItems:a.filter(function(z){var q,ie=s in z.props?z.props[s]:(q=z.type.defaultProps)===null||q===void 0?void 0:q[s];return ie===N}),dataStartIndex:c,dataEndIndex:u}),E=k.length,T,D,A;fJ(v.domain,S,m)&&(T=rm(v.domain,null,S),p&&(m==="number"||w!=="auto")&&(A=ns(k,x,"category")));var L=JO(m);if(!T||T.length===0){var C,M=(C=v.domain)!==null&&C!==void 0?C:L;if(x){if(T=ns(k,x,m),m==="category"&&p){var I=B3(T);j&&I?(D=T,T=Wu(0,E)):j||(T=zb(M,T,y).reduce(function(z,q){return z.indexOf(q)>=0?z:[].concat(Ji(z),[q])},[]))}else if(m==="category")j?T=T.filter(function(z){return z!==""&&!te(z)}):T=zb(M,T,y).reduce(function(z,q){return z.indexOf(q)>=0||q===""||te(q)?z:[].concat(Ji(z),[q])},[]);else if(m==="number"){var R=tU(k,a.filter(function(z){var q,ie,he=s in z.props?z.props[s]:(q=z.type.defaultProps)===null||q===void 0?void 0:q[s],ge="hide"in z.props?z.props.hide:(ie=z.type.defaultProps)===null||ie===void 0?void 0:ie.hide;return he===N&&(O||!ge)}),x,i,f);R&&(T=R)}p&&(m==="number"||w!=="auto")&&(A=ns(k,x,"category"))}else p?T=Wu(0,E):l&&l[N]&&l[N].hasStack&&m==="number"?T=h==="expand"?[0,1]:Tk(l[N].stackGroups,c,u):T=_k(k,a.filter(function(z){var q=s in z.props?z.props[s]:z.type.defaultProps[s],ie="hide"in z.props?z.props.hide:z.type.defaultProps.hide;return q===N&&(O||!ie)}),m,f,!0);if(m==="number")T=Fm(d,T,N,i,_),M&&(T=rm(M,T,S));else if(m==="category"&&M){var F=M,K=T.every(function(z){return F.indexOf(z)>=0});K&&(T=F)}}return B(B({},g),{},J({},N,B(B({},v),{},{axisType:i,domain:T,categoricalDomain:A,duplicateDomain:D,originalDomain:(b=v.domain)!==null&&b!==void 0?b:L,isCategorical:p,layout:f})))},{})},zJ=function(t,r){var n=r.graphicalItems,a=r.Axis,i=r.axisType,s=r.axisIdKey,l=r.stackGroups,c=r.dataStartIndex,u=r.dataEndIndex,f=t.layout,d=t.children,h=uf(t.data,{graphicalItems:n,dataStartIndex:c,dataEndIndex:u}),p=h.length,g=kk(f,i),y=-1;return n.reduce(function(b,v){var m=v.type.defaultProps!==void 0?B(B({},v.type.defaultProps),v.props):v.props,x=m[s],S=JO("number");if(!b[x]){y++;var j;return g?j=Wu(0,p):l&&l[x]&&l[x].hasStack?(j=Tk(l[x].stackGroups,c,u),j=Fm(d,j,x,i)):(j=rm(S,_k(h,n.filter(function(w){var _,O,N=s in w.props?w.props[s]:(_=w.type.defaultProps)===null||_===void 0?void 0:_[s],k="hide"in w.props?w.props.hide:(O=w.type.defaultProps)===null||O===void 0?void 0:O.hide;return N===x&&!k}),"number",f),a.defaultProps.allowDataOverflow),j=Fm(d,j,x,i)),B(B({},b),{},J({},x,B(B({axisType:i},a.defaultProps),{},{hide:!0,orientation:Bt(LJ,"".concat(i,".").concat(y%2),null),domain:j,originalDomain:S,isCategorical:g,layout:f})))}return b},{})},WJ=function(t,r){var n=r.axisType,a=n===void 0?"xAxis":n,i=r.AxisComp,s=r.graphicalItems,l=r.stackGroups,c=r.dataStartIndex,u=r.dataEndIndex,f=t.children,d="".concat(a,"Id"),h=Ft(f,i),p={};return h&&h.length?p=FJ(t,{axes:h,graphicalItems:s,axisType:a,axisIdKey:d,stackGroups:l,dataStartIndex:c,dataEndIndex:u}):s&&s.length&&(p=zJ(t,{Axis:i,graphicalItems:s,axisType:a,axisIdKey:d,stackGroups:l,dataStartIndex:c,dataEndIndex:u})),p},UJ=function(t){var r=gn(t),n=Vr(r,!1,!0);return{tooltipTicks:n,orderedTooltipTicks:fy(n,function(a){return a.coordinate}),tooltipAxis:r,tooltipAxisBandSize:Nu(r,n)}},wj=function(t){var r=t.children,n=t.defaultShowTooltip,a=It(r,Wi),i=0,s=0;return t.data&&t.data.length!==0&&(s=t.data.length-1),a&&a.props&&(a.props.startIndex>=0&&(i=a.props.startIndex),a.props.endIndex>=0&&(s=a.props.endIndex)),{chartX:0,chartY:0,dataStartIndex:i,dataEndIndex:s,activeTooltipIndex:-1,isTooltipActive:!!n}},HJ=function(t){return!t||!t.length?!1:t.some(function(r){var n=Yr(r&&r.type);return n&&n.indexOf("Bar")>=0})},Sj=function(t){return t==="horizontal"?{numericAxisName:"yAxis",cateAxisName:"xAxis"}:t==="vertical"?{numericAxisName:"xAxis",cateAxisName:"yAxis"}:t==="centric"?{numericAxisName:"radiusAxis",cateAxisName:"angleAxis"}:{numericAxisName:"angleAxis",cateAxisName:"radiusAxis"}},KJ=function(t,r){var n=t.props,a=t.graphicalItems,i=t.xAxisMap,s=i===void 0?{}:i,l=t.yAxisMap,c=l===void 0?{}:l,u=n.width,f=n.height,d=n.children,h=n.margin||{},p=It(d,Wi),g=It(d,vi),y=Object.keys(c).reduce(function(j,w){var _=c[w],O=_.orientation;return!_.mirror&&!_.hide?B(B({},j),{},J({},O,j[O]+_.width)):j},{left:h.left||0,right:h.right||0}),b=Object.keys(s).reduce(function(j,w){var _=s[w],O=_.orientation;return!_.mirror&&!_.hide?B(B({},j),{},J({},O,Bt(j,"".concat(O))+_.height)):j},{top:h.top||0,bottom:h.bottom||0}),v=B(B({},b),y),m=v.bottom;p&&(v.bottom+=p.props.height||Wi.defaultProps.height),g&&r&&(v=ZW(v,a,n,r));var x=u-v.left-v.right,S=f-v.top-v.bottom;return B(B({brushBottom:m},v),{},{width:Math.max(x,0),height:Math.max(S,0)})},VJ=function(t,r){if(r==="xAxis")return t[r].width;if(r==="yAxis")return t[r].height},df=function(t){var r=t.chartName,n=t.GraphicalChild,a=t.defaultTooltipEventType,i=a===void 0?"axis":a,s=t.validateTooltipEventTypes,l=s===void 0?["axis"]:s,c=t.axisComponents,u=t.legendContent,f=t.formatAxisMap,d=t.defaultProps,h=function(v,m){var x=m.graphicalItems,S=m.stackGroups,j=m.offset,w=m.updateId,_=m.dataStartIndex,O=m.dataEndIndex,N=v.barSize,k=v.layout,E=v.barGap,T=v.barCategoryGap,D=v.maxBarSize,A=Sj(k),L=A.numericAxisName,C=A.cateAxisName,M=HJ(x),I=[];return x.forEach(function(R,F){var K=uf(v.data,{graphicalItems:[R],dataStartIndex:_,dataEndIndex:O}),z=R.type.defaultProps!==void 0?B(B({},R.type.defaultProps),R.props):R.props,q=z.dataKey,ie=z.maxBarSize,he=z["".concat(L,"Id")],ge=z["".concat(C,"Id")],Qe={},Ae=c.reduce(function(Vn,Gn){var ff=m["".concat(Gn.axisType,"Map")],eg=z["".concat(Gn.axisType,"Id")];ff&&ff[eg]||Gn.axisType==="zAxis"||Oa();var tg=ff[eg];return B(B({},Vn),{},J(J({},Gn.axisType,tg),"".concat(Gn.axisType,"Ticks"),Vr(tg)))},Qe),V=Ae[C],Z=Ae["".concat(C,"Ticks")],re=S&&S[he]&&S[he].hasStack&&sU(R,S[he].stackGroups),W=Yr(R.type).indexOf("Bar")>=0,Te=Nu(V,Z),oe=[],We=M&&QW({barSize:N,stackGroups:S,totalSize:VJ(Ae,C)});if(W){var Ue,_t,cn=te(ie)?D:ie,La=(Ue=(_t=Nu(V,Z,!0))!==null&&_t!==void 0?_t:cn)!==null&&Ue!==void 0?Ue:0;oe=JW({barGap:E,barCategoryGap:T,bandSize:La!==Te?La:Te,sizeList:We[ge],maxBarSize:cn}),La!==Te&&(oe=oe.map(function(Vn){return B(B({},Vn),{},{position:B(B({},Vn.position),{},{offset:Vn.position.offset-La/2})})}))}var kl=R&&R.type&&R.type.getComposedData;kl&&I.push({props:B(B({},kl(B(B({},Ae),{},{displayedData:K,props:v,dataKey:q,item:R,bandSize:Te,barPosition:oe,offset:j,stackedData:re,layout:k,dataStartIndex:_,dataEndIndex:O}))),{},J(J(J({key:R.key||"item-".concat(F)},L,Ae[L]),C,Ae[C]),"animationId",w)),childIndex:J3(R,v.children),item:R})}),I},p=function(v,m){var x=v.props,S=v.dataStartIndex,j=v.dataEndIndex,w=v.updateId;if(!I0({props:x}))return null;var _=x.children,O=x.layout,N=x.stackOffset,k=x.data,E=x.reverseStackOrder,T=Sj(O),D=T.numericAxisName,A=T.cateAxisName,L=Ft(_,n),C=oU(k,L,"".concat(D,"Id"),"".concat(A,"Id"),N,E),M=c.reduce(function(z,q){var ie="".concat(q.axisType,"Map");return B(B({},z),{},J({},ie,WJ(x,B(B({},q),{},{graphicalItems:L,stackGroups:q.axisType===D&&C,dataStartIndex:S,dataEndIndex:j}))))},{}),I=KJ(B(B({},M),{},{props:x,graphicalItems:L}),m==null?void 0:m.legendBBox);Object.keys(M).forEach(function(z){M[z]=f(x,M[z],I,z.replace("Map",""),r)});var R=M["".concat(A,"Map")],F=UJ(R),K=h(x,B(B({},M),{},{dataStartIndex:S,dataEndIndex:j,updateId:w,graphicalItems:L,stackGroups:C,offset:I}));return B(B({formattedGraphicalItems:K,graphicalItems:L,offset:I,stackGroups:C},F),M)},g=function(b){function v(m){var x,S,j;return kJ(this,v),j=PJ(this,v,[m]),J(j,"eventEmitterSymbol",Symbol("rechartsEventEmitter")),J(j,"accessibilityManager",new dJ),J(j,"handleLegendBBoxUpdate",function(w){if(w){var _=j.state,O=_.dataStartIndex,N=_.dataEndIndex,k=_.updateId;j.setState(B({legendBBox:w},p({props:j.props,dataStartIndex:O,dataEndIndex:N,updateId:k},B(B({},j.state),{},{legendBBox:w}))))}}),J(j,"handleReceiveSyncEvent",function(w,_,O){if(j.props.syncId===w){if(O===j.eventEmitterSymbol&&typeof j.props.syncMethod!="function")return;j.applySyncEvent(_)}}),J(j,"handleBrushChange",function(w){var _=w.startIndex,O=w.endIndex;if(_!==j.state.dataStartIndex||O!==j.state.dataEndIndex){var N=j.state.updateId;j.setState(function(){return B({dataStartIndex:_,dataEndIndex:O},p({props:j.props,dataStartIndex:_,dataEndIndex:O,updateId:N},j.state))}),j.triggerSyncEvent({dataStartIndex:_,dataEndIndex:O})}}),J(j,"handleMouseEnter",function(w){var _=j.getMouseInfo(w);if(_){var O=B(B({},_),{},{isTooltipActive:!0});j.setState(O),j.triggerSyncEvent(O);var N=j.props.onMouseEnter;Q(N)&&N(O,w)}}),J(j,"triggeredAfterMouseMove",function(w){var _=j.getMouseInfo(w),O=_?B(B({},_),{},{isTooltipActive:!0}):{isTooltipActive:!1};j.setState(O),j.triggerSyncEvent(O);var N=j.props.onMouseMove;Q(N)&&N(O,w)}),J(j,"handleItemMouseEnter",function(w){j.setState(function(){return{isTooltipActive:!0,activeItem:w,activePayload:w.tooltipPayload,activeCoordinate:w.tooltipPosition||{x:w.cx,y:w.cy}}})}),J(j,"handleItemMouseLeave",function(){j.setState(function(){return{isTooltipActive:!1}})}),J(j,"handleMouseMove",function(w){w.persist(),j.throttleTriggeredAfterMouseMove(w)}),J(j,"handleMouseLeave",function(w){j.throttleTriggeredAfterMouseMove.cancel();var _={isTooltipActive:!1};j.setState(_),j.triggerSyncEvent(_);var O=j.props.onMouseLeave;Q(O)&&O(_,w)}),J(j,"handleOuterEvent",function(w){var _=Q3(w),O=Bt(j.props,"".concat(_));if(_&&Q(O)){var N,k;/.*touch.*/i.test(_)?k=j.getMouseInfo(w.changedTouches[0]):k=j.getMouseInfo(w),O((N=k)!==null&&N!==void 0?N:{},w)}}),J(j,"handleClick",function(w){var _=j.getMouseInfo(w);if(_){var O=B(B({},_),{},{isTooltipActive:!0});j.setState(O),j.triggerSyncEvent(O);var N=j.props.onClick;Q(N)&&N(O,w)}}),J(j,"handleMouseDown",function(w){var _=j.props.onMouseDown;if(Q(_)){var O=j.getMouseInfo(w);_(O,w)}}),J(j,"handleMouseUp",function(w){var _=j.props.onMouseUp;if(Q(_)){var O=j.getMouseInfo(w);_(O,w)}}),J(j,"handleTouchMove",function(w){w.changedTouches!=null&&w.changedTouches.length>0&&j.throttleTriggeredAfterMouseMove(w.changedTouches[0])}),J(j,"handleTouchStart",function(w){w.changedTouches!=null&&w.changedTouches.length>0&&j.handleMouseDown(w.changedTouches[0])}),J(j,"handleTouchEnd",function(w){w.changedTouches!=null&&w.changedTouches.length>0&&j.handleMouseUp(w.changedTouches[0])}),J(j,"handleDoubleClick",function(w){var _=j.props.onDoubleClick;if(Q(_)){var O=j.getMouseInfo(w);_(O,w)}}),J(j,"handleContextMenu",function(w){var _=j.props.onContextMenu;if(Q(_)){var O=j.getMouseInfo(w);_(O,w)}}),J(j,"triggerSyncEvent",function(w){j.props.syncId!==void 0&&ph.emit(mh,j.props.syncId,w,j.eventEmitterSymbol)}),J(j,"applySyncEvent",function(w){var _=j.props,O=_.layout,N=_.syncMethod,k=j.state.updateId,E=w.dataStartIndex,T=w.dataEndIndex;if(w.dataStartIndex!==void 0||w.dataEndIndex!==void 0)j.setState(B({dataStartIndex:E,dataEndIndex:T},p({props:j.props,dataStartIndex:E,dataEndIndex:T,updateId:k},j.state)));else if(w.activeTooltipIndex!==void 0){var D=w.chartX,A=w.chartY,L=w.activeTooltipIndex,C=j.state,M=C.offset,I=C.tooltipTicks;if(!M)return;if(typeof N=="function")L=N(I,w);else if(N==="value"){L=-1;for(var R=0;R<I.length;R++)if(I[R].value===w.activeLabel){L=R;break}}var F=B(B({},M),{},{x:M.left,y:M.top}),K=Math.min(D,F.x+F.width),z=Math.min(A,F.y+F.height),q=I[L]&&I[L].value,ie=Um(j.state,j.props.data,L),he=I[L]?{x:O==="horizontal"?I[L].coordinate:K,y:O==="horizontal"?z:I[L].coordinate}:QO;j.setState(B(B({},w),{},{activeLabel:q,activeCoordinate:he,activePayload:ie,activeTooltipIndex:L}))}else j.setState(w)}),J(j,"renderCursor",function(w){var _,O=j.state,N=O.isTooltipActive,k=O.activeCoordinate,E=O.activePayload,T=O.offset,D=O.activeTooltipIndex,A=O.tooltipAxisBandSize,L=j.getTooltipEventType(),C=(_=w.props.active)!==null&&_!==void 0?_:N,M=j.props.layout,I=w.key||"_recharts-cursor";return $.createElement(gJ,{key:I,activeCoordinate:k,activePayload:E,activeTooltipIndex:D,chartName:r,element:w,isActive:C,layout:M,offset:T,tooltipAxisBandSize:A,tooltipEventType:L})}),J(j,"renderPolarAxis",function(w,_,O){var N=Bt(w,"type.axisType"),k=Bt(j.state,"".concat(N,"Map")),E=w.type.defaultProps,T=E!==void 0?B(B({},E),w.props):w.props,D=k&&k[T["".concat(N,"Id")]];return P.cloneElement(w,B(B({},D),{},{className:ee(N,D.className),key:w.key||"".concat(_,"-").concat(O),ticks:Vr(D,!0)}))}),J(j,"renderPolarGrid",function(w){var _=w.props,O=_.radialLines,N=_.polarAngles,k=_.polarRadius,E=j.state,T=E.radiusAxisMap,D=E.angleAxisMap,A=gn(T),L=gn(D),C=L.cx,M=L.cy,I=L.innerRadius,R=L.outerRadius;return P.cloneElement(w,{polarAngles:Array.isArray(N)?N:Vr(L,!0).map(function(F){return F.coordinate}),polarRadius:Array.isArray(k)?k:Vr(A,!0).map(function(F){return F.coordinate}),cx:C,cy:M,innerRadius:I,outerRadius:R,key:w.key||"polar-grid",radialLines:O})}),J(j,"renderLegend",function(){var w=j.state.formattedGraphicalItems,_=j.props,O=_.children,N=_.width,k=_.height,E=j.props.margin||{},T=N-(E.left||0)-(E.right||0),D=wk({children:O,formattedGraphicalItems:w,legendWidth:T,legendContent:u});if(!D)return null;var A=D.item,L=xj(D,xJ);return P.cloneElement(A,B(B({},L),{},{chartWidth:N,chartHeight:k,margin:E,onBBoxUpdate:j.handleLegendBBoxUpdate}))}),J(j,"renderTooltip",function(){var w,_=j.props,O=_.children,N=_.accessibilityLayer,k=It(O,Ge);if(!k)return null;var E=j.state,T=E.isTooltipActive,D=E.activeCoordinate,A=E.activePayload,L=E.activeLabel,C=E.offset,M=(w=k.props.active)!==null&&w!==void 0?w:T;return P.cloneElement(k,{viewBox:B(B({},C),{},{x:C.left,y:C.top}),active:M,label:L,payload:M?A:[],coordinate:D,accessibilityLayer:N})}),J(j,"renderBrush",function(w){var _=j.props,O=_.margin,N=_.data,k=j.state,E=k.offset,T=k.dataStartIndex,D=k.dataEndIndex,A=k.updateId;return P.cloneElement(w,{key:w.key||"_recharts-brush",onChange:Zl(j.handleBrushChange,w.props.onChange),data:N,x:U(w.props.x)?w.props.x:E.left,y:U(w.props.y)?w.props.y:E.top+E.height+E.brushBottom-(O.bottom||0),width:U(w.props.width)?w.props.width:E.width,startIndex:T,endIndex:D,updateId:"brush-".concat(A)})}),J(j,"renderReferenceElement",function(w,_,O){if(!w)return null;var N=j,k=N.clipPathId,E=j.state,T=E.xAxisMap,D=E.yAxisMap,A=E.offset,L=w.type.defaultProps||{},C=w.props,M=C.xAxisId,I=M===void 0?L.xAxisId:M,R=C.yAxisId,F=R===void 0?L.yAxisId:R;return P.cloneElement(w,{key:w.key||"".concat(_,"-").concat(O),xAxis:T[I],yAxis:D[F],viewBox:{x:A.left,y:A.top,width:A.width,height:A.height},clipPathId:k})}),J(j,"renderActivePoints",function(w){var _=w.item,O=w.activePoint,N=w.basePoint,k=w.childIndex,E=w.isRange,T=[],D=_.props.key,A=_.item.type.defaultProps!==void 0?B(B({},_.item.type.defaultProps),_.item.props):_.item.props,L=A.activeDot,C=A.dataKey,M=B(B({index:k,dataKey:C,cx:O.x,cy:O.y,r:4,fill:Ry(_.item),strokeWidth:2,stroke:"#fff",payload:O.payload,value:O.value},X(L,!1)),Jc(L));return T.push(v.renderActiveDot(L,M,"".concat(D,"-activePoint-").concat(k))),N?T.push(v.renderActiveDot(L,B(B({},M),{},{cx:N.x,cy:N.y}),"".concat(D,"-basePoint-").concat(k))):E&&T.push(null),T}),J(j,"renderGraphicChild",function(w,_,O){var N=j.filterFormatItem(w,_,O);if(!N)return null;var k=j.getTooltipEventType(),E=j.state,T=E.isTooltipActive,D=E.tooltipAxis,A=E.activeTooltipIndex,L=E.activeLabel,C=j.props.children,M=It(C,Ge),I=N.props,R=I.points,F=I.isRange,K=I.baseLine,z=N.item.type.defaultProps!==void 0?B(B({},N.item.type.defaultProps),N.item.props):N.item.props,q=z.activeDot,ie=z.hide,he=z.activeBar,ge=z.activeShape,Qe=!!(!ie&&T&&M&&(q||he||ge)),Ae={};k!=="axis"&&M&&M.props.trigger==="click"?Ae={onClick:Zl(j.handleItemMouseEnter,w.props.onClick)}:k!=="axis"&&(Ae={onMouseLeave:Zl(j.handleItemMouseLeave,w.props.onMouseLeave),onMouseEnter:Zl(j.handleItemMouseEnter,w.props.onMouseEnter)});var V=P.cloneElement(w,B(B({},N.props),Ae));function Z(Gn){return typeof D.dataKey=="function"?D.dataKey(Gn.payload):null}if(Qe)if(A>=0){var re,W;if(D.dataKey&&!D.allowDuplicatedCategory){var Te=typeof D.dataKey=="function"?Z:"payload.".concat(D.dataKey.toString());re=Qc(R,Te,L),W=F&&K&&Qc(K,Te,L)}else re=R==null?void 0:R[A],W=F&&K&&K[A];if(ge||he){var oe=w.props.activeIndex!==void 0?w.props.activeIndex:A;return[P.cloneElement(w,B(B(B({},N.props),Ae),{},{activeIndex:oe})),null,null]}if(!te(re))return[V].concat(Ji(j.renderActivePoints({item:N,activePoint:re,basePoint:W,childIndex:A,isRange:F})))}else{var We,Ue=(We=j.getItemByXY(j.state.activeCoordinate))!==null&&We!==void 0?We:{graphicalItem:V},_t=Ue.graphicalItem,cn=_t.item,La=cn===void 0?w:cn,kl=_t.childIndex,Vn=B(B(B({},N.props),Ae),{},{activeIndex:kl});return[P.cloneElement(La,Vn),null,null]}return F?[V,null,null]:[V,null]}),J(j,"renderCustomized",function(w,_,O){return P.cloneElement(w,B(B({key:"recharts-customized-".concat(O)},j.props),j.state))}),J(j,"renderMap",{CartesianGrid:{handler:ac,once:!0},ReferenceArea:{handler:j.renderReferenceElement},ReferenceLine:{handler:ac},ReferenceDot:{handler:j.renderReferenceElement},XAxis:{handler:ac},YAxis:{handler:ac},Brush:{handler:j.renderBrush,once:!0},Bar:{handler:j.renderGraphicChild},Line:{handler:j.renderGraphicChild},Area:{handler:j.renderGraphicChild},Radar:{handler:j.renderGraphicChild},RadialBar:{handler:j.renderGraphicChild},Scatter:{handler:j.renderGraphicChild},Pie:{handler:j.renderGraphicChild},Funnel:{handler:j.renderGraphicChild},Tooltip:{handler:j.renderCursor,once:!0},PolarGrid:{handler:j.renderPolarGrid,once:!0},PolarAngleAxis:{handler:j.renderPolarAxis},PolarRadiusAxis:{handler:j.renderPolarAxis},Customized:{handler:j.renderCustomized}}),j.clipPathId="".concat((x=m.id)!==null&&x!==void 0?x:uo("recharts"),"-clip"),j.throttleTriggeredAfterMouseMove=w_(j.triggeredAfterMouseMove,(S=m.throttleDelay)!==null&&S!==void 0?S:1e3/60),j.state={},j}return EJ(v,b),NJ(v,[{key:"componentDidMount",value:function(){var x,S;this.addListener(),this.accessibilityManager.setDetails({container:this.container,offset:{left:(x=this.props.margin.left)!==null&&x!==void 0?x:0,top:(S=this.props.margin.top)!==null&&S!==void 0?S:0},coordinateList:this.state.tooltipTicks,mouseHandlerCallback:this.triggeredAfterMouseMove,layout:this.props.layout}),this.displayDefaultTooltip()}},{key:"displayDefaultTooltip",value:function(){var x=this.props,S=x.children,j=x.data,w=x.height,_=x.layout,O=It(S,Ge);if(O){var N=O.props.defaultIndex;if(!(typeof N!="number"||N<0||N>this.state.tooltipTicks.length-1)){var k=this.state.tooltipTicks[N]&&this.state.tooltipTicks[N].value,E=Um(this.state,j,N,k),T=this.state.tooltipTicks[N].coordinate,D=(this.state.offset.top+w)/2,A=_==="horizontal",L=A?{x:T,y:D}:{y:T,x:D},C=this.state.formattedGraphicalItems.find(function(I){var R=I.item;return R.type.name==="Scatter"});C&&(L=B(B({},L),C.props.points[N].tooltipPosition),E=C.props.points[N].tooltipPayload);var M={activeTooltipIndex:N,isTooltipActive:!0,activeLabel:k,activePayload:E,activeCoordinate:L};this.setState(M),this.renderCursor(O),this.accessibilityManager.setIndex(N)}}}},{key:"getSnapshotBeforeUpdate",value:function(x,S){if(!this.props.accessibilityLayer)return null;if(this.state.tooltipTicks!==S.tooltipTicks&&this.accessibilityManager.setDetails({coordinateList:this.state.tooltipTicks}),this.props.layout!==x.layout&&this.accessibilityManager.setDetails({layout:this.props.layout}),this.props.margin!==x.margin){var j,w;this.accessibilityManager.setDetails({offset:{left:(j=this.props.margin.left)!==null&&j!==void 0?j:0,top:(w=this.props.margin.top)!==null&&w!==void 0?w:0}})}return null}},{key:"componentDidUpdate",value:function(x){yp([It(x.children,Ge)],[It(this.props.children,Ge)])||this.displayDefaultTooltip()}},{key:"componentWillUnmount",value:function(){this.removeListener(),this.throttleTriggeredAfterMouseMove.cancel()}},{key:"getTooltipEventType",value:function(){var x=It(this.props.children,Ge);if(x&&typeof x.props.shared=="boolean"){var S=x.props.shared?"axis":"item";return l.indexOf(S)>=0?S:i}return i}},{key:"getMouseInfo",value:function(x){if(!this.container)return null;var S=this.container,j=S.getBoundingClientRect(),w=_F(j),_={chartX:Math.round(x.pageX-w.left),chartY:Math.round(x.pageY-w.top)},O=j.width/S.offsetWidth||1,N=this.inRange(_.chartX,_.chartY,O);if(!N)return null;var k=this.state,E=k.xAxisMap,T=k.yAxisMap,D=this.getTooltipEventType(),A=jj(this.state,this.props.data,this.props.layout,N);if(D!=="axis"&&E&&T){var L=gn(E).scale,C=gn(T).scale,M=L&&L.invert?L.invert(_.chartX):null,I=C&&C.invert?C.invert(_.chartY):null;return B(B({},_),{},{xValue:M,yValue:I},A)}return A?B(B({},_),A):null}},{key:"inRange",value:function(x,S){var j=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1,w=this.props.layout,_=x/j,O=S/j;if(w==="horizontal"||w==="vertical"){var N=this.state.offset,k=_>=N.left&&_<=N.left+N.width&&O>=N.top&&O<=N.top+N.height;return k?{x:_,y:O}:null}var E=this.state,T=E.angleAxisMap,D=E.radiusAxisMap;if(T&&D){var A=gn(T);return Hb({x:_,y:O},A)}return null}},{key:"parseEventsOfWrapper",value:function(){var x=this.props.children,S=this.getTooltipEventType(),j=It(x,Ge),w={};j&&S==="axis"&&(j.props.trigger==="click"?w={onClick:this.handleClick}:w={onMouseEnter:this.handleMouseEnter,onDoubleClick:this.handleDoubleClick,onMouseMove:this.handleMouseMove,onMouseLeave:this.handleMouseLeave,onTouchMove:this.handleTouchMove,onTouchStart:this.handleTouchStart,onTouchEnd:this.handleTouchEnd,onContextMenu:this.handleContextMenu});var _=Jc(this.props,this.handleOuterEvent);return B(B({},_),w)}},{key:"addListener",value:function(){ph.on(mh,this.handleReceiveSyncEvent)}},{key:"removeListener",value:function(){ph.removeListener(mh,this.handleReceiveSyncEvent)}},{key:"filterFormatItem",value:function(x,S,j){for(var w=this.state.formattedGraphicalItems,_=0,O=w.length;_<O;_++){var N=w[_];if(N.item===x||N.props.key===x.key||S===Yr(N.item.type)&&j===N.childIndex)return N}return null}},{key:"renderClipPath",value:function(){var x=this.clipPathId,S=this.state.offset,j=S.left,w=S.top,_=S.height,O=S.width;return $.createElement("defs",null,$.createElement("clipPath",{id:x},$.createElement("rect",{x:j,y:w,height:_,width:O})))}},{key:"getXScales",value:function(){var x=this.state.xAxisMap;return x?Object.entries(x).reduce(function(S,j){var w=gj(j,2),_=w[0],O=w[1];return B(B({},S),{},J({},_,O.scale))},{}):null}},{key:"getYScales",value:function(){var x=this.state.yAxisMap;return x?Object.entries(x).reduce(function(S,j){var w=gj(j,2),_=w[0],O=w[1];return B(B({},S),{},J({},_,O.scale))},{}):null}},{key:"getXScaleByAxisId",value:function(x){var S;return(S=this.state.xAxisMap)===null||S===void 0||(S=S[x])===null||S===void 0?void 0:S.scale}},{key:"getYScaleByAxisId",value:function(x){var S;return(S=this.state.yAxisMap)===null||S===void 0||(S=S[x])===null||S===void 0?void 0:S.scale}},{key:"getItemByXY",value:function(x){var S=this.state,j=S.formattedGraphicalItems,w=S.activeItem;if(j&&j.length)for(var _=0,O=j.length;_<O;_++){var N=j[_],k=N.props,E=N.item,T=E.type.defaultProps!==void 0?B(B({},E.type.defaultProps),E.props):E.props,D=Yr(E.type);if(D==="Bar"){var A=(k.data||[]).find(function(I){return oV(x,I)});if(A)return{graphicalItem:N,payload:A}}else if(D==="RadialBar"){var L=(k.data||[]).find(function(I){return Hb(x,I)});if(L)return{graphicalItem:N,payload:L}}else if(rf(N,w)||nf(N,w)||el(N,w)){var C=YG({graphicalItem:N,activeTooltipItem:w,itemData:T.data}),M=T.activeIndex===void 0?C:T.activeIndex;return{graphicalItem:B(B({},N),{},{childIndex:M}),payload:el(N,w)?T.data[C]:N.props.data[C]}}}return null}},{key:"render",value:function(){var x=this;if(!I0(this))return null;var S=this.props,j=S.children,w=S.className,_=S.width,O=S.height,N=S.style,k=S.compact,E=S.title,T=S.desc,D=xj(S,bJ),A=X(D,!1);if(k)return $.createElement(tj,{state:this.state,width:this.props.width,height:this.props.height,clipPathId:this.clipPathId},$.createElement(xp,li({},A,{width:_,height:O,title:E,desc:T}),this.renderClipPath(),D0(j,this.renderMap)));if(this.props.accessibilityLayer){var L,C;A.tabIndex=(L=this.props.tabIndex)!==null&&L!==void 0?L:0,A.role=(C=this.props.role)!==null&&C!==void 0?C:"application",A.onKeyDown=function(I){x.accessibilityManager.keyboardEvent(I)},A.onFocus=function(){x.accessibilityManager.focus()}}var M=this.parseEventsOfWrapper();return $.createElement(tj,{state:this.state,width:this.props.width,height:this.props.height,clipPathId:this.clipPathId},$.createElement("div",li({className:ee("recharts-wrapper",w),style:B({position:"relative",cursor:"default",width:_,height:O},N)},M,{ref:function(R){x.container=R}}),$.createElement(xp,li({},A,{width:_,height:O,title:E,desc:T,style:DJ}),this.renderClipPath(),D0(j,this.renderMap)),this.renderLegend(),this.renderTooltip()))}}])}(P.Component);J(g,"displayName",r),J(g,"defaultProps",B({layout:"horizontal",stackOffset:"none",barCategoryGap:"10%",barGap:4,margin:{top:5,right:5,bottom:5,left:5},reverseStackOrder:!1,syncMethod:"index"},d)),J(g,"getDerivedStateFromProps",function(b,v){var m=b.dataKey,x=b.data,S=b.children,j=b.width,w=b.height,_=b.layout,O=b.stackOffset,N=b.margin,k=v.dataStartIndex,E=v.dataEndIndex;if(v.updateId===void 0){var T=wj(b);return B(B(B({},T),{},{updateId:0},p(B(B({props:b},T),{},{updateId:0}),v)),{},{prevDataKey:m,prevData:x,prevWidth:j,prevHeight:w,prevLayout:_,prevStackOffset:O,prevMargin:N,prevChildren:S})}if(m!==v.prevDataKey||x!==v.prevData||j!==v.prevWidth||w!==v.prevHeight||_!==v.prevLayout||O!==v.prevStackOffset||!mi(N,v.prevMargin)){var D=wj(b),A={chartX:v.chartX,chartY:v.chartY,isTooltipActive:v.isTooltipActive},L=B(B({},jj(v,x,_)),{},{updateId:v.updateId+1}),C=B(B(B({},D),A),L);return B(B(B({},C),p(B({props:b},C),v)),{},{prevDataKey:m,prevData:x,prevWidth:j,prevHeight:w,prevLayout:_,prevStackOffset:O,prevMargin:N,prevChildren:S})}if(!yp(S,v.prevChildren)){var M,I,R,F,K=It(S,Wi),z=K&&(M=(I=K.props)===null||I===void 0?void 0:I.startIndex)!==null&&M!==void 0?M:k,q=K&&(R=(F=K.props)===null||F===void 0?void 0:F.endIndex)!==null&&R!==void 0?R:E,ie=z!==k||q!==E,he=!te(x),ge=he&&!ie?v.updateId:v.updateId+1;return B(B({updateId:ge},p(B(B({props:b},v),{},{updateId:ge,dataStartIndex:z,dataEndIndex:q}),v)),{},{prevChildren:S,dataStartIndex:z,dataEndIndex:q})}return null}),J(g,"renderActiveDot",function(b,v,m){var x;return P.isValidElement(b)?x=P.cloneElement(b,v):Q(b)?x=b(v):x=$.createElement(Zd,v),$.createElement(ne,{className:"recharts-active-dot",key:m},x)});var y=P.forwardRef(function(v,m){return $.createElement(g,li({},v,{ref:m}))});return y.displayName=g.displayName,y},_l=df({chartName:"BarChart",GraphicalChild:nr,defaultTooltipEventType:"axis",validateTooltipEventTypes:["axis","item"],axisComponents:[{axisType:"xAxis",AxisComp:or},{axisType:"yAxis",AxisComp:sr}],formatAxisMap:mO}),Qy=df({chartName:"PieChart",GraphicalChild:wr,validateTooltipEventTypes:["item"],defaultTooltipEventType:"item",legendContent:"children",axisComponents:[{axisType:"angleAxis",AxisComp:wl},{axisType:"radiusAxis",AxisComp:jl}],formatAxisMap:Lk,defaultProps:{layout:"centric",startAngle:0,endAngle:360,cx:"50%",cy:"50%",innerRadius:0,outerRadius:"80%"}}),Jy=df({chartName:"AreaChart",GraphicalChild:Lr,axisComponents:[{axisType:"xAxis",AxisComp:or},{axisType:"yAxis",AxisComp:sr}],formatAxisMap:mO}),GJ=df({chartName:"RadialBarChart",GraphicalChild:Sl,legendContent:"children",defaultTooltipEventType:"axis",validateTooltipEventTypes:["axis","item"],axisComponents:[{axisType:"angleAxis",AxisComp:wl},{axisType:"radiusAxis",AxisComp:jl}],formatAxisMap:Lk,defaultProps:{layout:"radial",startAngle:0,endAngle:360,cx:"50%",cy:"50%",innerRadius:0,outerRadius:"80%"}});function YJ({data:e=[],color:t="var(--cyan)",width:r=60,height:n=20,id:a="spark"}){const i=P.useMemo(()=>{if(!e||e.length<2)return null;const l=Math.min(...e),u=Math.max(...e)-l||1,f=2,d=e.map((y,b)=>b/(e.length-1)*r),h=e.map(y=>n-f-(y-l)/u*(n-f*2)),p=d.map((y,b)=>`${y},${h[b]}`).join(" "),g=`M ${d[0]},${h[0]} `+d.slice(1).map((y,b)=>`L ${y},${h[b+1]}`).join(" ")+` L ${d[d.length-1]},${n} L ${d[0]},${n} Z`;return{polyline:p,fillPath:g}},[e,r,n]);if(!i)return o.jsx("svg",{width:r,height:n});const s=`spark-grad-${a}`;return o.jsxs("svg",{width:r,height:n,viewBox:`0 0 ${r} ${n}`,style:{display:"inline-block",verticalAlign:"middle",flexShrink:0},"aria-hidden":"true",children:[o.jsx("defs",{children:o.jsxs("linearGradient",{id:s,x1:"0",y1:"0",x2:"0",y2:"1",children:[o.jsx("stop",{offset:"0%",stopColor:t,stopOpacity:"0.25"}),o.jsx("stop",{offset:"100%",stopColor:t,stopOpacity:"0.01"})]})}),o.jsx("path",{d:i.fillPath,fill:`url(#${s})`}),o.jsx("polyline",{points:i.polyline,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinejoin:"round",strokeLinecap:"round"}),(()=>{const l=(e.length-1)/(e.length-1)*r,c=Math.min(...e),f=Math.max(...e)-c||1,d=2,h=n-d-(e[e.length-1]-c)/f*(n-d*2);return o.jsx("circle",{cx:l,cy:h,r:"2",fill:t})})()]})}function qJ(e,t=800){const[r,n]=P.useState(e),a=P.useRef(e),i=P.useRef(null),s=P.useRef(null),l=P.useRef(e);return P.useEffect(()=>{l.current=e,a.current=r,i.current=null;const c=u=>{i.current||(i.current=u);const f=u-i.current,d=Math.min(1,f/t),h=d===1?1:1-Math.pow(2,-10*d),p=a.current+(l.current-a.current)*h;n(p),d<1&&(s.current=requestAnimationFrame(c))};return s.current=requestAnimationFrame(c),()=>cancelAnimationFrame(s.current)},[e]),r}const _j=["#00F0FF","#F7931A","#00C389","#3B82F6","#A855F7","#FF5C5C"];function XJ(e){return e?new Date(e+"T00:00:00").toLocaleDateString("en-US",{month:"short",day:"numeric"}):""}function Do(e,t=8){let r=e;return Array.from({length:t},()=>(r=r*1664525+1013904223&4294967295,Math.abs(r)%100+10))}const kj={Balance:Do(42,9),Positions:Do(17,9),"Open Markets":Do(93,9),"Today P&L":Do(55,9),"Markets Tracked":Do(71,9)};function ic({cents:e}){const t=Number(e||0),r=(t/100).toFixed(2);return t>0?o.jsxs("span",{className:"mono",style:{color:"var(--green)",fontWeight:700},children:["+$",r]}):t<0?o.jsxs("span",{className:"mono",style:{color:"var(--red)",fontWeight:700},children:["-$",Math.abs(t/100).toFixed(2)]}):o.jsx("span",{className:"mono",style:{color:"var(--text-muted)"},children:"$0.00"})}function Oj({wins:e,losses:t}){const r=e+t;if(!r)return o.jsx("span",{style:{color:"var(--text-muted)"},children:"—"});const n=(e/r*100).toFixed(0),a=n>=80?"var(--green)":n>=50?"var(--orange)":"var(--red)";return o.jsxs("span",{style:{color:a},children:[e,"/",r," (",n,"%)"]})}function Nj({wins:e,losses:t,pnl:r}){const n=e+t,a=n>0?e/n:0,i={padding:"2px 8px",borderRadius:4,fontSize:10,fontWeight:700,fontFamily:"var(--font-body)"};return a>=.9&&r>0?o.jsx("span",{style:{...i,background:"var(--green-dim)",color:"var(--green)",border:"1px solid rgba(0,195,137,0.25)"},children:"ADD MORE"}):a>=.65&&r>0?o.jsx("span",{style:{...i,background:"var(--orange-dim)",color:"var(--orange)",border:"1px solid rgba(247,147,26,0.25)"},children:"HOLD"}):r<0?o.jsx("span",{style:{...i,background:"var(--red-dim)",color:"var(--red)",border:"1px solid rgba(255,92,92,0.25)"},children:"REDUCE"}):o.jsx("span",{style:{...i,background:"rgba(107,114,128,0.15)",color:"var(--text-muted)",border:"1px solid var(--border)"},children:"WATCH"})}function QJ({opportunities:e}){const t=e||[];if(!t.length)return o.jsxs("div",{className:"card",children:[o.jsxs("div",{className:"section-title",style:{marginBottom:8},children:[o.jsx("svg",{style:{width:18,height:18,color:"var(--cyan)"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.8",d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"})}),"Best Opportunities Right Now"]}),o.jsx("p",{style:{color:"var(--text-muted)",fontSize:13,textAlign:"center",padding:"24px 0"},children:"No fresh signals — waiting for next pipeline cycle..."})]});const r=[{borderColor:"rgba(247,147,26,0.35)",background:"rgba(247,147,26,0.06)",rankColor:"var(--orange)",rankLabel:"#1"},{borderColor:"rgba(160,160,160,0.25)",background:"rgba(160,160,160,0.04)",rankColor:"var(--text-dim)",rankLabel:"#2"},{borderColor:"rgba(180,100,50,0.25)",background:"rgba(180,100,50,0.04)",rankColor:"#CD7F32",rankLabel:"#3"}];return o.jsxs("div",{className:"card",style:{border:"1px solid rgba(0,240,255,0.15)",background:"linear-gradient(135deg, rgba(0,240,255,0.03), var(--surface), rgba(0,195,137,0.03))"},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,marginBottom:16},children:[o.jsxs("div",{className:"section-title",children:[o.jsx("svg",{style:{width:18,height:18,color:"var(--cyan)"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.8",d:"M9 12l2 2 4-4M7.835 4.697a3.42 3.42 0 001.946-.806 3.42 3.42 0 014.438 0 3.42 3.42 0 001.946.806 3.42 3.42 0 013.138 3.138 3.42 3.42 0 00.806 1.946 3.42 3.42 0 010 4.438 3.42 3.42 0 00-.806 1.946 3.42 3.42 0 01-3.138 3.138 3.42 3.42 0 00-1.946.806 3.42 3.42 0 01-4.438 0 3.42 3.42 0 00-1.946-.806 3.42 3.42 0 01-3.138-3.138 3.42 3.42 0 00-.806-1.946 3.42 3.42 0 010-4.438 3.42 3.42 0 00.806-1.946 3.42 3.42 0 013.138-3.138z"})}),"Best Opportunities Right Now"]}),o.jsx("span",{style:{marginLeft:"auto",fontSize:10,color:"var(--text-muted)",textTransform:"uppercase",fontWeight:600,letterSpacing:"0.08em"},children:"Live Signals"})]}),o.jsx("div",{style:{display:"flex",flexDirection:"column",gap:10},children:t.map((n,a)=>{const i=r[a]||r[2],s=n.hist_trades>0,l=parseFloat(n.hist_wr)>=80?"var(--green)":parseFloat(n.hist_wr)>=50?"var(--orange)":"var(--red)";return o.jsxs("div",{className:a===0?"breathe-neon":"",style:{borderRadius:10,padding:"14px 16px",background:i.background,border:`1px solid ${i.borderColor}`,display:"flex",gap:14,alignItems:"flex-start"},children:[o.jsx("div",{style:{width:28,height:28,borderRadius:7,background:`${i.rankColor}22`,border:`1px solid ${i.borderColor}`,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:2},children:o.jsx("span",{style:{fontSize:11,fontWeight:800,color:i.rankColor,fontFamily:"var(--font-mono)"},children:i.rankLabel})}),o.jsxs("div",{style:{flex:1,minWidth:0},children:[o.jsx("a",{href:n.url,target:"_blank",rel:"noopener noreferrer",style:{fontSize:13,fontWeight:600,color:"var(--text)",textDecoration:"none",display:"block",marginBottom:8,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},onMouseEnter:c=>{c.currentTarget.style.color="var(--cyan)"},onMouseLeave:c=>{c.currentTarget.style.color="var(--text)"},children:n.title}),o.jsxs("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:8,marginBottom:8},children:[o.jsxs("span",{className:"badge",style:n.direction==="NO"?{background:"var(--red-dim)",color:"var(--red)",border:"1px solid rgba(255,92,92,0.25)"}:{background:"var(--green-dim)",color:"var(--green)",border:"1px solid rgba(0,195,137,0.25)"},children:["BUY ",n.direction]}),o.jsxs("span",{style:{fontSize:12,color:"var(--text-muted)"},children:["Edge: ",o.jsxs("span",{className:"mono",style:{color:"var(--cyan)",fontWeight:700},children:[n.edge_pct,"%"]})]}),o.jsxs("span",{style:{fontSize:12,color:"var(--text-muted)"},children:["Conf: ",o.jsxs("span",{style:{color:"var(--blue)",fontWeight:700},children:[n.confidence,"%"]})]}),n.price_cents>0&&o.jsxs("span",{style:{fontSize:12,color:"var(--text-muted)"},children:["Price: ",o.jsxs("span",{className:"mono",style:{color:"var(--text)"},children:[n.price_cents,"c"]})]}),s&&o.jsxs("span",{style:{fontSize:12,color:"var(--text-muted)"},children:["History: ",o.jsxs("span",{style:{fontWeight:700,color:l},children:[n.hist_wr,"% WR"]}),o.jsxs("span",{style:{color:"var(--text-muted)",marginLeft:4},children:["(",n.hist_trades," trades, ",n.hist_pnl/100>=0?"+":"","$",(n.hist_pnl/100).toFixed(0),")"]})]}),!s&&o.jsx("span",{style:{fontSize:11,color:"var(--text-muted)",fontStyle:"italic"},children:"New market"})]}),o.jsx("p",{style:{fontSize:11,color:"var(--text-dim)",lineHeight:1.5},children:n.why})]})]},n.ticker)})})]})}function JJ({topMarkets:e,seedMoney:t,balance:r}){const n=(e||[]).slice(0,3);if(!n.length)return null;const a=n.reduce((f,d)=>f+d.wins/(d.wins+d.losses),0)/n.length*100,i=n.length>0?Math.round(n.reduce((f,d)=>{const h=d.wins/(d.wins+d.losses||1);return f+(h>=.9?95:80)},0)/n.length):95,s=t?t/100:5e4,l=r?r/100:s,c=s>0?(l-s)/s*100:0,u=[{icon:o.jsx("svg",{style:{width:20,height:20},fill:"none",stroke:"var(--cyan)",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.8",d:"M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z"})}),label:`Start: $${s.toLocaleString()}`,sub:`$${l.toLocaleString()} (${c>=0?"+":""}${c.toFixed(1)}%)`,borderColor:"rgba(0,240,255,0.25)",subColor:c>=0?"var(--green)":"var(--red)"},{icon:o.jsx("svg",{style:{width:20,height:20},fill:"none",stroke:"var(--blue)",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.8",d:"M8.111 16.404a5.5 5.5 0 017.778 0M12 20h.01m-7.08-7.071c3.904-3.905 10.236-3.905 14.141 0M1.394 9.393c5.857-5.857 15.355-5.857 21.213 0"})}),label:"Signal Found",sub:"AI scans 135 markets",borderColor:"rgba(59,130,246,0.25)",subColor:"var(--text-muted)"},{icon:o.jsx("svg",{style:{width:20,height:20},fill:"none",stroke:"var(--orange)",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.8",d:"M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"})}),label:`Buy NO at ${i}c`,sub:"High-prob event",borderColor:"rgba(247,147,26,0.25)",subColor:"var(--text-muted)"},{icon:o.jsx("svg",{style:{width:20,height:20},fill:"none",stroke:"var(--purple)",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.8",d:"M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"})}),label:"Hold 5min-2hr",sub:"TP +3c / SL -5c",borderColor:"rgba(168,85,247,0.25)",subColor:"var(--text-muted)"},{icon:o.jsx("svg",{style:{width:20,height:20},fill:"none",stroke:"var(--green)",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.8",d:"M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),label:`Collect ${100-i}c`,sub:`${a.toFixed(0)}% of the time`,borderColor:"rgba(0,195,137,0.25)",subColor:"var(--text-muted)"}];return o.jsxs("div",{className:"card",style:{border:"1px solid rgba(0,195,137,0.12)",background:"linear-gradient(135deg, rgba(0,195,137,0.04), var(--surface), rgba(247,147,26,0.04))"},children:[o.jsxs("div",{className:"section-title",style:{marginBottom:16},children:[o.jsx("svg",{style:{width:18,height:18,color:"var(--cyan)"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.8",d:"M13 10V3L4 14h7v7l9-11h-7z"})}),"Winning Strategy — Live Flow"]}),o.jsx("div",{style:{display:"flex",alignItems:"center",gap:6,marginBottom:18},children:u.map((f,d)=>o.jsxs($.Fragment,{children:[o.jsxs("div",{style:{flex:1,borderRadius:10,padding:"12px 10px",background:"rgba(255,255,255,0.02)",border:`1px solid ${f.borderColor}`,textAlign:"center"},children:[o.jsx("div",{style:{display:"flex",justifyContent:"center",marginBottom:6},children:f.icon}),o.jsx("p",{style:{fontSize:11,fontWeight:600,color:"var(--text)",marginBottom:2},children:f.label}),o.jsx("p",{style:{fontSize:10,color:f.subColor},children:f.sub})]}),d<u.length-1&&o.jsx("svg",{style:{width:14,height:14,color:"var(--border-light)",flexShrink:0},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M9 5l7 7-7 7"})})]},d))}),o.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(3,1fr)",gap:10},children:[{label:"Cost Per Trade",value:`${i}c`,sub:"buying NO side",color:"var(--orange)"},{label:"Profit on Win",value:`${100-i}c`,sub:"per contract",color:"var(--green)"},{label:"Return Multiple",value:`${((100-i)/i*100).toFixed(0)}%`,sub:"per winning trade",color:"var(--green)"}].map(f=>o.jsxs("div",{style:{borderRadius:8,padding:"12px",background:"var(--surface-el)",border:"1px solid var(--border)",textAlign:"center"},children:[o.jsx("p",{className:"stat-label",style:{marginBottom:4},children:f.label}),o.jsx("p",{className:"mono",style:{fontSize:20,fontWeight:700,color:f.color},children:f.value}),o.jsx("p",{style:{fontSize:10,color:"var(--text-muted)",marginTop:2},children:f.sub})]},f.label))})]})}function ZJ({topMarkets:e,worstMarkets:t,strategies:r}){const n=(e||[]).filter(c=>c.wins/(c.wins+c.losses||1)>=.9&&c.pnl>0),a=(t||[]).filter(c=>c.pnl<-5e3),i=(r||[]).filter(c=>c.pnl<-1e4&&c.win_rate<20).slice(0,3),s=[];n.length>0&&s.push({priority:"HIGH",color:"green",iconPath:"M13 7h8m0 0v8m0-8l-8 8-4-4-6 6",title:`Double down on ${n.length} near-certain markets`,detail:n.slice(0,2).map(c=>{var u;return((u=c.title)==null?void 0:u.split("?")[0])||c.ticker}).join(", "),reason:`${n.length} markets have 90%+ win rate — the edge is proven`}),a.length>0&&s.push({priority:"HIGH",color:"red",iconPath:"M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636",title:`Exit ${a.length} bleeding market(s)`,detail:a.slice(0,2).map(c=>{var u;return((u=c.title)==null?void 0:u.split("?")[0])||c.ticker}).join(", "),reason:`0% win rate, losing $${Math.abs(a.reduce((c,u)=>c+u.pnl,0)/100).toFixed(0)} total`}),i.length>0&&s.push({priority:"MED",color:"orange",iconPath:"M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.066 2.573c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.573 1.066c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.066-2.573c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z M15 12a3 3 0 11-6 0 3 3 0 016 0z",title:`Consider disabling ${i.length} strategy(ies)`,detail:i.map(c=>c.name).join(", "),reason:"Sub-20% win rate — these are coin flips minus fees"}),s.push({priority:"INFO",color:"cyan",iconPath:"M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z",title:"Keep hyper-trading high-prob NO markets",detail:"The 95c+ NO strategy is the #1 edge — scale it up",reason:"Compounding small spreads at 99%+ win rate = consistent returns"});const l={green:{bg:"var(--green-dim)",border:"rgba(0,195,137,0.2)",text:"var(--green)",badge:"rgba(0,195,137,0.2)"},red:{bg:"var(--red-dim)",border:"rgba(255,92,92,0.2)",text:"var(--red)",badge:"rgba(255,92,92,0.2)"},orange:{bg:"var(--orange-dim)",border:"rgba(247,147,26,0.2)",text:"var(--orange)",badge:"rgba(247,147,26,0.2)"},cyan:{bg:"var(--cyan-dim)",border:"rgba(0,240,255,0.2)",text:"var(--cyan)",badge:"rgba(0,240,255,0.2)"}};return o.jsxs("div",{className:"card",style:{border:"1px solid rgba(247,147,26,0.12)"},children:[o.jsxs("div",{className:"section-title",style:{marginBottom:14},children:[o.jsx("svg",{style:{width:18,height:18,color:"var(--orange)"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.8",d:"M9 12l2 2 4-4M7.835 4.697a3.42 3.42 0 001.946-.806 3.42 3.42 0 014.438 0 3.42 3.42 0 001.946.806 3.42 3.42 0 013.138 3.138 3.42 3.42 0 00.806 1.946 3.42 3.42 0 010 4.438 3.42 3.42 0 00-.806 1.946 3.42 3.42 0 01-3.138 3.138 3.42 3.42 0 00-1.946.806 3.42 3.42 0 01-4.438 0 3.42 3.42 0 00-1.946-.806 3.42 3.42 0 01-3.138-3.138 3.42 3.42 0 00-.806-1.946 3.42 3.42 0 010-4.438 3.42 3.42 0 00.806-1.946 3.42 3.42 0 013.138-3.138z"})}),"What To Do Next"]}),o.jsx("div",{style:{display:"flex",flexDirection:"column",gap:10},children:s.map((c,u)=>{const f=l[c.color];return o.jsxs("div",{style:{borderRadius:10,padding:"12px 14px",background:f.bg,border:`1px solid ${f.border}`,display:"flex",gap:12,alignItems:"flex-start"},children:[o.jsx("div",{style:{width:30,height:30,borderRadius:8,background:f.badge,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:1},children:o.jsx("svg",{style:{width:15,height:15,color:f.text},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.8",d:c.iconPath})})}),o.jsxs("div",{style:{flex:1},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:3},children:[o.jsx("span",{className:"badge",style:{background:f.badge,color:f.text,fontSize:9,padding:"2px 6px"},children:c.priority}),o.jsx("span",{style:{fontSize:13,fontWeight:600,color:f.text},children:c.title})]}),o.jsx("p",{style:{fontSize:12,color:"var(--text-dim)",marginBottom:2},children:c.detail}),o.jsx("p",{style:{fontSize:11,color:"var(--text-muted)"},children:c.reason})]})]},u)})})]})}function eZ({strategies:e}){const t=[...e||[]].sort((n,a)=>a.pnl-n.pnl).slice(0,10);if(!t.length)return null;const r=t.map(n=>({name:n.name,pnl:n.pnl/100,fill:n.pnl>=0?"#00C389":"#FF5C5C"}));return o.jsxs("div",{className:"card",children:[o.jsxs("div",{className:"section-title",style:{marginBottom:14},children:[o.jsx("svg",{style:{width:18,height:18,color:"var(--cyan)"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.8",d:"M13 7h8m0 0v8m0-8l-8 8-4-4-6 6"})}),"Strategy P&L — Top 10"]}),o.jsx(tr,{width:"100%",height:250,children:o.jsxs(_l,{data:r,layout:"vertical",margin:{left:70,right:20},children:[o.jsx(Ia,{strokeDasharray:"3 3",stroke:"var(--border)",horizontal:!1}),o.jsx(or,{type:"number",stroke:"var(--text-muted)",tick:{fill:"var(--text-muted)",fontSize:11},tickFormatter:n=>`$${n}`}),o.jsx(sr,{type:"category",dataKey:"name",stroke:"var(--text-muted)",tick:{fill:"var(--text-muted)",fontSize:11},width:65}),o.jsx(Ge,{contentStyle:{background:"var(--surface-el)",border:"1px solid var(--border)",borderRadius:8,color:"var(--text)"},formatter:n=>[`$${n.toFixed(2)}`,"P&L"]}),o.jsx(nr,{dataKey:"pnl",radius:[0,4,4,0],children:r.map((n,a)=>o.jsx(xr,{fill:n.fill},a))})]})})]})}function tZ({todayWins:e,todayLosses:t}){const r=(e||0)+(t||0);if(!r)return null;const n=(e/r*100).toFixed(1),a=[{name:"Wins",value:e,fill:"#00C389"},{name:"Losses",value:t,fill:"#FF5C5C"}];return o.jsxs("div",{className:"card",style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center"},children:[o.jsx("p",{className:"stat-label",style:{marginBottom:12},children:"Today's Win Rate"}),o.jsxs("div",{style:{position:"relative",width:140,height:140},children:[o.jsx(tr,{width:"100%",height:"100%",children:o.jsx(Qy,{children:o.jsx(wr,{data:a,innerRadius:45,outerRadius:65,paddingAngle:2,dataKey:"value",startAngle:90,endAngle:-270,children:a.map((i,s)=>o.jsx(xr,{fill:i.fill},s))})})}),o.jsxs("div",{style:{position:"absolute",inset:0,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center"},children:[o.jsxs("span",{className:"mono",style:{fontSize:22,fontWeight:700,color:Number(n)>=50?"var(--green)":"var(--red)"},children:[n,"%"]}),o.jsxs("span",{style:{fontSize:10,color:"var(--text-muted)",marginTop:2},children:[r.toLocaleString()," trades"]})]})]}),o.jsxs("div",{style:{display:"flex",gap:16,marginTop:10},children:[o.jsxs("span",{style:{fontSize:12,color:"var(--green)",fontWeight:600},children:[e==null?void 0:e.toLocaleString()," W"]}),o.jsxs("span",{style:{fontSize:12,color:"var(--red)",fontWeight:600},children:[t==null?void 0:t.toLocaleString()," L"]})]})]})}function rZ({active:e,payload:t,label:r}){var a;if(!e||!t||!t.length)return null;const n=((a=t[0])==null?void 0:a.payload)||{};return o.jsxs("div",{style:{background:"#1C1C24",border:"1px solid #2A2A35",borderRadius:8,padding:"10px 14px",fontFamily:"'Inter', sans-serif",fontSize:12,minWidth:160},children:[o.jsx("p",{style:{color:"#6B7280",fontWeight:600,marginBottom:6,fontSize:11},children:r}),o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",gap:16},children:[o.jsx("span",{style:{color:"#6B7280"},children:"Daily P&L"}),o.jsxs("span",{className:"mono",style:{color:(n.pnl||0)>=0?"#00C389":"#FF5C5C",fontWeight:700},children:[(n.pnl||0)>=0?"+":"","$",((n.pnl||0)/100).toFixed(2)]})]}),o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",gap:16},children:[o.jsx("span",{style:{color:"#6B7280"},children:"Cumulative"}),o.jsxs("span",{className:"mono",style:{color:"#00F0FF",fontWeight:700},children:[(n.cumulative_pnl||0)>=0?"+":"","$",((n.cumulative_pnl||0)/100).toFixed(2)]})]}),n.trades!=null&&o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",gap:16},children:[o.jsx("span",{style:{color:"#6B7280"},children:"Trades"}),o.jsxs("span",{className:"mono",style:{color:"#E0E0E0"},children:[n.wins||0,"W / ",(n.trades||0)-(n.wins||0),"L"]})]})]})]})}function nZ({dailyPnl:e}){var f,d;const t=e||[];if(!t.length)return o.jsxs("div",{className:"card",style:{borderLeft:"3px solid #00F0FF",paddingLeft:16},children:[o.jsx("div",{style:{display:"flex",alignItems:"center",gap:10,marginBottom:12},children:o.jsx("h2",{className:"section-title section-accent-cyan",style:{borderLeft:"none",paddingLeft:0},children:"Portfolio Performance"})}),o.jsx("p",{style:{color:"#6B7280",fontSize:13,textAlign:"center",padding:"48px 0"},children:"No daily P&L data yet — will appear after trading activity is recorded"})]});const r=t.reduce((h,p)=>p.pnl>((h==null?void 0:h.pnl)||-1/0)?p:h,t[0]),n=t.reduce((h,p)=>p.pnl<((h==null?void 0:h.pnl)||1/0)?p:h,t[0]),a=((f=t[t.length-1])==null?void 0:f.cumulative_pnl)||0,i=((d=t[0])==null?void 0:d.cumulative_pnl)||0,s=a-i,l=s>=0,c=l?"#00C389":"#FF5C5C",u=t.map(h=>({...h,label:XJ(h.date),cumDisplay:h.cumulative_pnl/100}));return o.jsxs("div",{className:"card",style:{borderLeft:"3px solid #00F0FF",paddingLeft:20},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:16},children:[o.jsx("h2",{className:"section-title",style:{fontSize:"1.1rem"},children:"Portfolio Performance"}),o.jsxs("div",{style:{display:"flex",gap:10},children:[o.jsxs("div",{style:{padding:"4px 12px",borderRadius:20,background:l?"rgba(0,195,137,0.12)":"rgba(255,92,92,0.12)",border:`1px solid ${l?"rgba(0,195,137,0.3)":"rgba(255,92,92,0.3)"}`},children:[o.jsx("span",{style:{fontSize:10,color:"#6B7280",marginRight:6,fontWeight:600},children:"30d RETURN"}),o.jsxs("span",{className:"mono",style:{fontSize:12,fontWeight:700,color:l?"#00C389":"#FF5C5C"},children:[l?"+":"","$",(s/100).toFixed(2)]})]}),o.jsxs("div",{style:{padding:"4px 12px",borderRadius:20,background:"rgba(0,195,137,0.08)",border:"1px solid rgba(0,195,137,0.2)"},children:[o.jsx("span",{style:{fontSize:10,color:"#6B7280",marginRight:6,fontWeight:600},children:"BEST DAY"}),o.jsxs("span",{className:"mono",style:{fontSize:12,fontWeight:700,color:"#00C389"},children:["+$",(((r==null?void 0:r.pnl)||0)/100).toFixed(2)]})]}),o.jsxs("div",{style:{padding:"4px 12px",borderRadius:20,background:"rgba(255,92,92,0.08)",border:"1px solid rgba(255,92,92,0.2)"},children:[o.jsx("span",{style:{fontSize:10,color:"#6B7280",marginRight:6,fontWeight:600},children:"WORST DAY"}),o.jsxs("span",{className:"mono",style:{fontSize:12,fontWeight:700,color:"#FF5C5C"},children:["$",(((n==null?void 0:n.pnl)||0)/100).toFixed(2)]})]})]})]}),o.jsx(tr,{width:"100%",height:280,children:o.jsxs(Jy,{data:u,margin:{top:8,right:12,left:0,bottom:0},children:[o.jsxs("defs",{children:[o.jsxs("linearGradient",{id:"dailyPnlGradPos",x1:"0",y1:"0",x2:"0",y2:"1",children:[o.jsx("stop",{offset:"5%",stopColor:"#00C389",stopOpacity:.25}),o.jsx("stop",{offset:"95%",stopColor:"#00C389",stopOpacity:.01})]}),o.jsxs("linearGradient",{id:"dailyPnlGradNeg",x1:"0",y1:"0",x2:"0",y2:"1",children:[o.jsx("stop",{offset:"5%",stopColor:"#FF5C5C",stopOpacity:.22}),o.jsx("stop",{offset:"95%",stopColor:"#FF5C5C",stopOpacity:.01})]})]}),o.jsx(Ia,{strokeDasharray:"3 3",stroke:"#2A2A35",strokeOpacity:.6,horizontal:!0,vertical:!1}),o.jsx(or,{dataKey:"label",stroke:"#2A2A35",tick:{fill:"#6B7280",fontSize:11,fontFamily:"'Inter', sans-serif"},tickLine:!1,axisLine:{stroke:"#2A2A35"}}),o.jsx(sr,{stroke:"#2A2A35",tick:{fill:"#6B7280",fontSize:11,fontFamily:"'Inter', sans-serif"},tickLine:!1,axisLine:!1,tickFormatter:h=>`$${h>=0,""}${h.toFixed(0)}`,width:55}),o.jsx(Ge,{content:o.jsx(rZ,{})}),o.jsx(Lr,{type:"monotone",dataKey:"cumDisplay",name:"Cumulative P&L",stroke:c,strokeWidth:2,fill:`url(#${l?"dailyPnlGradPos":"dailyPnlGradNeg"})`,dot:!1,activeDot:{r:5,fill:"#00F0FF",stroke:"#1C1C24",strokeWidth:2,filter:"drop-shadow(0 0 6px rgba(0,240,255,0.8))"}})]})})]})}function aZ({active:e,payload:t,label:r}){var a;if(!e||!t||!t.length)return null;const n=((a=t[0])==null?void 0:a.payload)||{};return o.jsxs("div",{style:{background:"#1C1C24",border:"1px solid #2A2A35",borderRadius:8,padding:"10px 14px",fontFamily:"'Inter', sans-serif",fontSize:12,minWidth:180},children:[o.jsx("p",{style:{color:"#E0E0E0",fontWeight:600,marginBottom:6,fontSize:12},children:n.name}),o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",gap:16},children:[o.jsx("span",{style:{color:"#6B7280"},children:"P&L"}),o.jsxs("span",{className:"mono",style:{color:n.pnlRaw>=0?"#00C389":"#FF5C5C",fontWeight:700},children:[n.pnlRaw>=0?"+":"","$",Math.abs(n.pnlRaw).toFixed(2)]})]}),n.trades!=null&&o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",gap:16},children:[o.jsx("span",{style:{color:"#6B7280"},children:"Trades"}),o.jsx("span",{className:"mono",style:{color:"#E0E0E0"},children:n.trades})]}),n.win_rate!=null&&o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",gap:16},children:[o.jsx("span",{style:{color:"#6B7280"},children:"Win Rate"}),o.jsxs("span",{className:"mono",style:{color:n.win_rate>=50?"#00C389":"#FF5C5C"},children:[n.win_rate,"%"]})]}),n.avg_edge!=null&&o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",gap:16},children:[o.jsx("span",{style:{color:"#6B7280"},children:"Avg Edge"}),o.jsxs("span",{className:"mono",style:{color:"#00F0FF"},children:[n.avg_edge,"%"]})]})]})]})}function iZ({strategies:e}){const t=[...e||[]].sort((a,i)=>i.pnl-a.pnl).slice(0,10);if(!t.length)return o.jsxs("div",{className:"card",children:[o.jsx("h2",{className:"section-title",style:{marginBottom:12,fontSize:"1.1rem"},children:"Strategy Breakdown"}),o.jsx("p",{style:{color:"#6B7280",fontSize:13,textAlign:"center",padding:"32px 0"},children:"No strategy data yet"})]});const r=t.map(a=>({name:(a.name||a.strategy||"Unknown").slice(0,22),pnl:Math.abs(a.pnl/100),pnlRaw:a.pnl/100,fill:a.pnl>=0?"#00C389":"#FF5C5C",trades:a.trades,win_rate:a.win_rate,avg_edge:a.avg_edge})),n=Math.max(220,r.length*36);return o.jsxs("div",{className:"card",children:[o.jsx("h2",{className:"section-title",style:{marginBottom:16,fontSize:"1.1rem"},children:"Strategy Breakdown"}),o.jsx(tr,{width:"100%",height:n,children:o.jsxs(_l,{data:r,layout:"vertical",margin:{left:10,right:24,top:4,bottom:4},children:[o.jsx(Ia,{strokeDasharray:"3 3",stroke:"#2A2A35",strokeOpacity:.6,horizontal:!1}),o.jsx(or,{type:"number",stroke:"#2A2A35",tick:{fill:"#6B7280",fontSize:11,fontFamily:"'Inter', sans-serif"},tickLine:!1,axisLine:{stroke:"#2A2A35"},tickFormatter:a=>`$${a.toFixed(0)}`}),o.jsx(sr,{type:"category",dataKey:"name",stroke:"#2A2A35",tick:{fill:"#A8A8A8",fontSize:11,fontFamily:"'Inter', sans-serif"},tickLine:!1,axisLine:!1,width:130}),o.jsx(Ge,{content:o.jsx(aZ,{}),cursor:{fill:"rgba(0,240,255,0.04)"}}),o.jsx(nr,{dataKey:"pnl",radius:[0,4,4,0],maxBarSize:22,children:r.map((a,i)=>o.jsx(xr,{fill:a.fill,fillOpacity:.85},i))})]})})]})}function oZ({winRate:e}){const t=Math.round((e||0)*100),r=t>=80?"#00C389":t>=50?"#F7931A":"#FF5C5C",n=[{name:"Win Rate",value:t,fill:r}];return o.jsxs("div",{className:"card",style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",minHeight:200},children:[o.jsx("p",{className:"stat-label",style:{marginBottom:8},children:"Overall Win Rate"}),o.jsxs("div",{style:{position:"relative",width:160,height:160},children:[o.jsx(tr,{width:"100%",height:"100%",children:o.jsx(GJ,{cx:"50%",cy:"50%",innerRadius:"60%",outerRadius:"85%",startAngle:90,endAngle:-270,data:n,children:o.jsx(Sl,{background:{fill:"#2A2A35"},dataKey:"value",cornerRadius:6,fill:r})})}),o.jsxs("div",{style:{position:"absolute",inset:0,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",pointerEvents:"none"},children:[o.jsxs("span",{className:"mono",style:{fontSize:28,fontWeight:700,color:r,textShadow:`0 0 12px ${r}60`,lineHeight:1},children:[t,"%"]}),o.jsx("span",{style:{fontSize:10,color:"#6B7280",marginTop:4,fontFamily:"'Inter', sans-serif"},children:"win rate"})]})]})]})}function sZ(){const e=[{id:1,market:"NVDA closes above $50 on Mar 2",direction:"NO @ 95c",entry:"95c",exit:"$1.00",contracts:200,cost:190,profit:10,roi:"5.26%",holdTime:"47min"},{id:2,market:"S&P 500 above 4000 on Mar 2",direction:"NO @ 96c",entry:"96c",exit:"$1.00",contracts:150,cost:144,profit:6,roi:"4.17%",holdTime:"1h 12min"},{id:3,market:"BTC above $10K on Mar 2",direction:"NO @ 97c",entry:"97c",exit:"$1.00",contracts:300,cost:291,profit:9,roi:"3.09%",holdTime:"23min"},{id:4,market:"Fed rate cut Mar 2",direction:"NO @ 94c",entry:"94c",exit:"$1.00",contracts:250,cost:235,profit:15,roi:"6.38%",holdTime:"1h 45min"},{id:5,market:"Tesla below $50 on Mar 2",direction:"NO @ 93c",entry:"93c",exit:"$1.00",contracts:100,cost:93,profit:7,roi:"7.53%",holdTime:"55min"}],t=[{title:"Mathematical Edge",icon:"M9 7h6m0 10v-3m-3 3h.01M9 17h.01M9 14h.01M12 14h.01M15 11h.01M12 11h.01M9 11h.01M7 21h10a2 2 0 002-2V5a2 2 0 00-2-2H7a2 2 0 00-2 2v14a2 2 0 002 2z",color:"var(--cyan)",borderColor:"rgba(0,240,255,0.2)",bgColor:"rgba(0,240,255,0.05)",text:"Even with occasional losses, a 95% win rate with 5% gains per trade generates massive compound returns. One loss costs 5c, but 19 consecutive wins cover that loss and then some."},{title:"Market Inefficiency",icon:"M13 10V3L4 14h7v7l9-11h-7z",color:"var(--orange)",borderColor:"rgba(247,147,26,0.2)",bgColor:"rgba(247,147,26,0.05)",text:"Prediction markets still underprice certainty. Events priced at 95% probability should often be 99%+. This gap between market price and true probability is our edge."},{title:"AI Advantage",icon:"M9.75 17L9 20l-1 1h8l-1-1-.75-3M3 13h18M5 17h14a2 2 0 002-2V5a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z",color:"var(--green)",borderColor:"rgba(0,195,137,0.2)",bgColor:"rgba(0,195,137,0.05)",text:"Our AI scans 135+ markets in real-time, finding opportunities humans miss. It evaluates probability, liquidity, and time-to-expiry simultaneously across every active contract."},{title:"Time Decay Works For Us",icon:"M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z",color:"var(--purple)",borderColor:"rgba(168,85,247,0.2)",bgColor:"rgba(168,85,247,0.05)",text:"As events approach expiry, NO contracts on events that will not happen converge toward $1.00. Time is our ally. The closer to expiry, the more certain the outcome, the safer the trade."},{title:"Scalability",icon:"M13 7h8m0 0v8m0-8l-8 8-4-4-6 6",color:"var(--blue)",borderColor:"rgba(59,130,246,0.2)",bgColor:"rgba(59,130,246,0.05)",text:"Strategy works whether trading $100 or $100,000. Kalshi liquidity is sufficient for large positions on high-volume markets. Scale capital, not complexity."}],r=[{label:"AI Scans 135 Markets",color:"var(--cyan)",bgColor:"rgba(0,240,255,0.08)"},{label:"Finds High-Prob NO",color:"var(--orange)",bgColor:"rgba(247,147,26,0.08)"},{label:"Buy at 95c",color:"var(--green)",bgColor:"rgba(0,195,137,0.08)"},{label:"Hold 5min-2hr",color:"var(--purple)",bgColor:"rgba(168,85,247,0.08)"},{label:"Collect 5c Profit",color:"var(--green)",bgColor:"rgba(0,195,137,0.12)"}];return o.jsxs("div",{className:"strategy-deep-dive",children:[o.jsxs("div",{className:"sdd-header",children:[o.jsx("div",{className:"sdd-header-line"}),o.jsxs("div",{className:"sdd-header-content",children:[o.jsx("svg",{style:{width:22,height:22,color:"var(--cyan)"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.8",d:"M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z"})}),o.jsx("h2",{className:"heading",style:{fontSize:22,fontWeight:800,color:"var(--text)"},children:"Strategy Deep Dive"}),o.jsx("svg",{style:{width:22,height:22,color:"var(--cyan)"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.8",d:"M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z"})})]}),o.jsx("div",{className:"sdd-header-line"})]}),o.jsxs("div",{className:"card sdd-section-card",style:{border:"1px solid rgba(0,240,255,0.15)",background:"linear-gradient(135deg, rgba(0,240,255,0.03), var(--surface), rgba(0,195,137,0.03))"},children:[o.jsxs("div",{className:"section-title",style:{marginBottom:20},children:[o.jsx("svg",{style:{width:18,height:18,color:"var(--cyan)"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.8",d:"M13 10V3L4 14h7v7l9-11h-7z"})}),"Winning Strategy — How It Works"]}),o.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(5,1fr)",gap:12,marginBottom:24},children:[{label:"The Edge",value:"Buy NO at 95c",sub:"on near-certain events",color:"var(--cyan)",glow:!0},{label:"The Math",value:"95c in, $1 out",sub:"= 5c profit per contract",color:"var(--green)",glow:!1},{label:"Per-Trade Return",value:"5.26%",sub:"per winning trade",color:"var(--green)",glow:!0},{label:"Risk Mgmt",value:"TP +3c / SL -5c",sub:"early exit if favorable",color:"var(--orange)",glow:!1},{label:"Win Rate",value:"95%+",sub:"on high-prob events",color:"var(--cyan)",glow:!0}].map(n=>o.jsxs("div",{className:n.glow?"sdd-stat-glow":"",style:{borderRadius:10,padding:"16px 12px",background:"var(--surface-el)",border:`1px solid ${n.color}33`,textAlign:"center"},children:[o.jsx("p",{className:"stat-label",style:{marginBottom:6},children:n.label}),o.jsx("p",{className:"mono",style:{fontSize:16,fontWeight:700,color:n.color,lineHeight:1.2},children:n.value}),o.jsx("p",{style:{fontSize:10,color:"var(--text-muted)",marginTop:4},children:n.sub})]},n.label))}),o.jsxs("div",{style:{marginBottom:16},children:[o.jsx("p",{className:"stat-label",style:{marginBottom:12,textAlign:"center"},children:"Trade Flow"}),o.jsx("div",{className:"sdd-flow-row",children:r.map((n,a)=>o.jsxs($.Fragment,{children:[o.jsx("div",{className:"sdd-flow-step",style:{background:n.bgColor,border:`1px solid ${n.color}33`},children:o.jsx("span",{className:"mono",style:{fontSize:12,fontWeight:700,color:n.color,textAlign:"center"},children:n.label})}),a<r.length-1&&o.jsx("div",{className:"sdd-flow-arrow",children:o.jsx("svg",{style:{width:16,height:16,color:"var(--border-light)"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2.5",d:"M9 5l7 7-7 7"})})})]},a))})]}),o.jsxs("div",{style:{borderRadius:10,padding:"14px 18px",background:"linear-gradient(90deg, rgba(0,195,137,0.08), rgba(0,240,255,0.06))",border:"1px solid rgba(0,195,137,0.18)",display:"flex",alignItems:"center",gap:14},children:[o.jsx("div",{style:{width:36,height:36,borderRadius:10,background:"rgba(0,195,137,0.15)",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:o.jsx("svg",{style:{width:18,height:18,color:"var(--green)"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.8",d:"M13 7h8m0 0v8m0-8l-8 8-4-4-6 6"})})}),o.jsxs("div",{children:[o.jsx("p",{style:{fontSize:13,fontWeight:600,color:"var(--green)",marginBottom:2},children:"Compound Effect"}),o.jsx("p",{style:{fontSize:12,color:"var(--text-dim)",lineHeight:1.5},children:"5% per trade x multiple trades per day = exponential growth. At just 3 trades/day with 95% win rate, capital compounds at roughly 14% per week. This is how $60K becomes $221K."})]})]})]}),o.jsxs("div",{className:"card sdd-section-card",style:{border:"1px solid rgba(247,147,26,0.15)",background:"linear-gradient(135deg, rgba(247,147,26,0.03), var(--surface))"},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:16},children:[o.jsxs("div",{className:"section-title",children:[o.jsx("svg",{style:{width:18,height:18,color:"var(--orange)"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.8",d:"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"})}),"Example Trades"]}),o.jsx("span",{className:"badge",style:{background:"var(--orange-dim)",color:"var(--orange)",fontSize:10},children:"ILLUSTRATIVE"})]}),o.jsx("div",{style:{overflowX:"auto"},children:o.jsxs("table",{className:"sdd-trades-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{style:{width:32},children:"#"}),o.jsx("th",{style:{textAlign:"left"},children:"Market"}),o.jsx("th",{children:"Direction"}),o.jsx("th",{style:{textAlign:"right"},children:"Entry"}),o.jsx("th",{style:{textAlign:"right"},children:"Exit"}),o.jsx("th",{style:{textAlign:"right"},children:"Contracts"}),o.jsx("th",{style:{textAlign:"right"},children:"Cost"}),o.jsx("th",{style:{textAlign:"right"},children:"Profit"}),o.jsx("th",{style:{textAlign:"right"},children:"ROI"}),o.jsx("th",{style:{textAlign:"right"},children:"Hold Time"})]})}),o.jsx("tbody",{children:e.map(n=>o.jsxs("tr",{children:[o.jsx("td",{style:{textAlign:"center"},children:o.jsx("span",{className:"mono",style:{fontSize:12,color:"var(--text-muted)"},children:n.id})}),o.jsx("td",{style:{textAlign:"left",maxWidth:240},children:o.jsx("span",{style:{fontSize:13,color:"var(--text)",fontWeight:500},children:n.market})}),o.jsx("td",{style:{textAlign:"center"},children:o.jsx("span",{className:"badge",style:{background:"var(--red-dim)",color:"var(--red)",fontSize:10,border:"1px solid rgba(255,92,92,0.25)"},children:n.direction})}),o.jsx("td",{style:{textAlign:"right"},children:o.jsx("span",{className:"mono",style:{fontSize:13,color:"var(--text-dim)"},children:n.entry})}),o.jsx("td",{style:{textAlign:"right"},children:o.jsx("span",{className:"mono",style:{fontSize:13,color:"var(--green)"},children:n.exit})}),o.jsx("td",{style:{textAlign:"right"},children:o.jsx("span",{className:"mono",style:{fontSize:13,color:"var(--text)"},children:n.contracts})}),o.jsx("td",{style:{textAlign:"right"},children:o.jsxs("span",{className:"mono",style:{fontSize:13,color:"var(--orange)"},children:["$",n.cost.toFixed(2)]})}),o.jsx("td",{style:{textAlign:"right"},children:o.jsxs("span",{className:"mono",style:{fontSize:13,fontWeight:700,color:"var(--green)"},children:["+$",n.profit.toFixed(2)]})}),o.jsx("td",{style:{textAlign:"right"},children:o.jsx("span",{className:"mono",style:{fontSize:12,color:"var(--cyan)",fontWeight:600},children:n.roi})}),o.jsx("td",{style:{textAlign:"right"},children:o.jsx("span",{style:{fontSize:12,color:"var(--text-muted)"},children:n.holdTime})})]},n.id))})]})}),o.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(4,1fr)",gap:12,marginTop:16,paddingTop:14,borderTop:"1px solid var(--border)"},children:[{label:"Total Cost",value:"$953.00",color:"var(--orange)"},{label:"Total Profit",value:"+$47.00",color:"var(--green)"},{label:"Avg ROI",value:"5.29%",color:"var(--cyan)"},{label:"Avg Hold",value:"52min",color:"var(--purple)"}].map(n=>o.jsxs("div",{style:{textAlign:"center"},children:[o.jsx("p",{className:"stat-label",style:{marginBottom:4},children:n.label}),o.jsx("p",{className:"mono",style:{fontSize:18,fontWeight:700,color:n.color},children:n.value})]},n.label))})]}),o.jsxs("div",{className:"card sdd-section-card",style:{border:"1px solid rgba(0,195,137,0.15)",background:"linear-gradient(135deg, rgba(0,195,137,0.03), var(--surface), rgba(168,85,247,0.03))"},children:[o.jsxs("div",{className:"section-title",style:{marginBottom:20},children:[o.jsx("svg",{style:{width:18,height:18,color:"var(--green)"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.8",d:"M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"})}),"Why This Works Long-Term"]}),o.jsx("div",{className:"sdd-insights-grid",children:t.map((n,a)=>o.jsxs("div",{className:"sdd-insight-card",style:{border:`1px solid ${n.borderColor}`,background:n.bgColor},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,marginBottom:10},children:[o.jsx("div",{style:{width:32,height:32,borderRadius:8,background:`${n.color}1A`,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:o.jsx("svg",{style:{width:16,height:16,color:n.color},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.8",d:n.icon})})}),o.jsx("h4",{style:{fontSize:14,fontWeight:700,color:n.color,fontFamily:"var(--font-heading)"},children:n.title})]}),o.jsx("p",{style:{fontSize:12,color:"var(--text-dim)",lineHeight:1.6},children:n.text})]},a))}),o.jsxs("div",{style:{marginTop:20,borderRadius:10,padding:"16px 20px",background:"linear-gradient(90deg, rgba(0,240,255,0.06), rgba(247,147,26,0.06))",border:"1px solid rgba(0,240,255,0.12)",textAlign:"center"},children:[o.jsx("p",{style:{fontSize:14,fontWeight:600,color:"var(--text)",marginBottom:4},children:"The Bottom Line"}),o.jsx("p",{style:{fontSize:13,color:"var(--text-dim)",lineHeight:1.6,maxWidth:700,margin:"0 auto"},children:"This is not gambling. It is systematic, AI-driven arbitrage on prediction market inefficiencies. Small, consistent profits compounded over hundreds of trades per week create exponential portfolio growth. The math is on our side, and the AI never sleeps."})]})]})]})}function lZ({label:e,rawValue:t,displayValue:r,color:n,accent:a,icon:i,sparkColor:s,hero:l}){const c=qJ(typeof t=="number"?t:0),u=kj[e]||kj.Balance,f=typeof t=="number"&&t!==0?e==="Balance"||e==="Today P&L"?`$${(c/100).toLocaleString(void 0,{minimumFractionDigits:2,maximumFractionDigits:2})}`:Math.round(c).toLocaleString():r;return o.jsxs("div",{className:`card ${a}${l?" border-neon-animated":""}`,style:{display:"flex",flexDirection:"column",gap:8},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[o.jsx("span",{className:"stat-label",children:e}),o.jsx("div",{style:{width:28,height:28,borderRadius:7,background:`${n}1A`,display:"flex",alignItems:"center",justifyContent:"center"},children:o.jsx("svg",{style:{width:14,height:14,color:n},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.8",d:i})})})]}),o.jsxs("div",{style:{display:"flex",alignItems:"flex-end",justifyContent:"space-between",gap:8},children:[o.jsx("p",{className:"stat-v mono",style:{color:n},children:f}),o.jsx(YJ,{data:u,color:s||n,width:60,height:22,id:e.replace(/\s+/g,"-").toLowerCase()})]})]})}function yt({title:e,defaultOpen:t=!0,children:r}){const n=`ken-sec-${e.toLowerCase().replace(/[^a-z0-9]/g,"-")}`,[a,i]=P.useState(()=>{try{return localStorage.getItem(n)!=="false"}catch{return t}}),s=()=>i(l=>{const c=!l;try{localStorage.setItem(n,String(c))}catch{}return c});return o.jsxs("div",{children:[o.jsxs("button",{onClick:s,style:{display:"flex",alignItems:"center",gap:8,padding:"2px 0 8px",width:"100%",background:"transparent",border:"none",cursor:"pointer"},onMouseEnter:l=>{l.currentTarget.style.opacity="0.7"},onMouseLeave:l=>{l.currentTarget.style.opacity="1"},children:[o.jsx("svg",{style:{width:12,height:12,color:"var(--text-muted)",flexShrink:0,transition:"transform 220ms ease",transform:a?"rotate(0deg)":"rotate(-90deg)"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M19 9l-7 7-7-7"})}),o.jsx("span",{style:{fontSize:10,fontWeight:700,fontFamily:"var(--font-body)",color:"var(--text-muted)",textTransform:"uppercase",letterSpacing:"0.1em"},children:e})]}),o.jsx("div",{style:{maxHeight:a?"3500px":0,overflow:"hidden",opacity:a?1:0,transition:"max-height 0.4s cubic-bezier(0.4,0,0.2,1), opacity 0.3s ease"},children:r})]})}function cZ(){var d;const[e,t]=P.useState(null),[r,n]=P.useState(!0);P.useEffect(()=>{a();const h=setInterval(a,3e4);return()=>clearInterval(h)},[]);async function a(){try{const h=await Oe("/dashboard");t(h)}catch{}n(!1)}if(r)return o.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:256},children:o.jsx("div",{className:"w-8 h-8 rounded-full border-2 border-t-transparent animate-spin",style:{borderColor:"var(--cyan)",borderTopColor:"transparent"}})});const i=e||{},s=(i.pnl_history||[]).map((h,p)=>({day:p+1,pnl:h})),l=i.today_trades>0?(i.today_wins/i.today_trades*100).toFixed(1):"0",c=(i.strategies||[]).filter(h=>h.pnl>0).slice(0,5),u=(i.strategies||[]).filter(h=>h.pnl<0).slice(-5).reverse(),f=[{label:"Balance",rawValue:i.balance||0,displayValue:i.balance?`$${(i.balance/100).toLocaleString(void 0,{minimumFractionDigits:2})}`:"—",color:"var(--green)",sparkColor:"var(--green)",accent:"card-accent-green",icon:"M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z"},{label:"Positions",rawValue:i.position_count||0,displayValue:i.position_count??"—",color:"var(--orange)",sparkColor:"var(--orange)",accent:"card-accent-orange",icon:"M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"},{label:"Open Markets",rawValue:i.open_orders||0,displayValue:i.open_orders??"—",color:"var(--blue)",sparkColor:"var(--cyan)",accent:"card-accent-blue",icon:"M13 7h8m0 0v8m0-8l-8 8-4-4-6 6"},{label:"Today P&L",rawValue:i.daily_pnl||0,displayValue:i.daily_pnl?`$${(i.daily_pnl/100).toLocaleString(void 0,{minimumFractionDigits:2})}`:"$0.00",color:(i.daily_pnl||0)>=0?"var(--green)":"var(--red)",sparkColor:(i.daily_pnl||0)>=0?"var(--green)":"var(--red)",accent:(i.daily_pnl||0)>=0?"card-accent-green":"card-accent-red",icon:"M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z"},{label:"Markets Tracked",rawValue:i.markets_tracked||0,displayValue:i.markets_tracked??"—",color:"var(--purple)",sparkColor:"var(--purple)",accent:"card-accent-purple",icon:"M21 12a9 9 0 01-9 9m9-9a9 9 0 00-9-9m9 9H3m9 9a9 9 0 01-9-9m9 9c1.657 0 3-4.03 3-9s-1.343-9-3-9m0 18c-1.657 0-3-4.03-3-9s1.343-9 3-9m-9 9a9 9 0 019-9"}];return o.jsxs("div",{className:"fade-in",style:{display:"flex",flexDirection:"column",gap:24},children:[o.jsxs("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between"},children:[o.jsxs("div",{children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,marginBottom:4},children:[o.jsx("h1",{className:"heading",style:{fontSize:26,fontWeight:800,color:"var(--text)",letterSpacing:"-0.025em"},children:"Dashboard"}),o.jsxs("span",{className:"live-indicator",children:[o.jsx("span",{className:"live-dot"}),"LIVE"]})]}),o.jsx("p",{className:"section-subtitle",children:"Ken event contracts overview"})]}),o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[o.jsx("span",{className:"badge",style:i.env==="prod"?{background:"var(--green-dim)",color:"var(--green)"}:{background:"var(--orange-dim)",color:"var(--orange)"},children:(i.env||"DEMO").toUpperCase()}),i.safe_mode&&o.jsx("span",{className:"badge",style:{background:"var(--orange-dim)",color:"var(--orange)"},children:"SAFE MODE"})]})]}),o.jsx(yt,{title:"Overview",children:o.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(5,1fr)",gap:14},children:f.map((h,p)=>o.jsx(lZ,{...h,hero:p===0},h.label))})}),o.jsx(yt,{title:"Portfolio Performance",children:o.jsx(nZ,{dailyPnl:i.daily_pnl_history||i.dailyPnl||[]})}),o.jsx(yt,{title:"Strategy Breakdown",children:o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"2fr 1fr",gap:16},children:[o.jsx(iZ,{strategies:i.strategies}),o.jsx(oZ,{winRate:i.win_rate||(i.today_trades>0?i.today_wins/i.today_trades:0)})]})}),i.seed_money>0&&o.jsx(yt,{title:"Capital & Economics",children:o.jsxs("div",{className:"card",style:{border:"1px solid rgba(59,130,246,0.18)",background:"linear-gradient(135deg, rgba(59,130,246,0.04), var(--surface), rgba(0,195,137,0.04))"},children:[o.jsxs("div",{className:"section-title",style:{marginBottom:16},children:[o.jsx("svg",{style:{width:18,height:18,color:"var(--cyan)"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.8",d:"M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),"Capital & Economics"]}),o.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(6,1fr)",gap:12,textAlign:"center"},children:[{label:"Seed Money",value:`$${(i.seed_money/100).toLocaleString(void 0,{minimumFractionDigits:0})}`,sub:`${i.num_portfolios} portfolios`,color:"var(--blue)"},{label:"Current Balance",value:`$${(i.balance/100).toLocaleString(void 0,{minimumFractionDigits:0})}`,sub:"all portfolios",color:"var(--green)"},{label:"Net P&L",value:`${i.net_pnl_from_seed>=0?"+":""}$${(i.net_pnl_from_seed/100).toLocaleString(void 0,{minimumFractionDigits:0})}`,sub:`${i.roi_pct>=0?"+":""}${i.roi_pct}% ROI`,color:i.net_pnl_from_seed>=0?"var(--green)":"var(--red)",subColor:i.roi_pct>=0?"var(--green)":"var(--red)"},{label:"Capital Deployed",value:`$${(i.total_invested/100).toLocaleString(void 0,{minimumFractionDigits:0})}`,sub:"total traded",color:"var(--orange)"},{label:"Capital at Risk",value:`$${(i.capital_at_risk/100).toLocaleString(void 0,{minimumFractionDigits:0})}`,sub:"open positions",color:"var(--red)"},{label:"Daily Budget",value:`$${(i.daily_budget/100).toLocaleString(void 0,{minimumFractionDigits:0})}`,sub:"across strategies",color:"var(--purple)"}].map(h=>o.jsxs("div",{children:[o.jsx("p",{className:"stat-label",style:{marginBottom:6},children:h.label}),o.jsx("p",{className:"mono",style:{fontSize:18,fontWeight:700,color:h.color},children:h.value}),o.jsx("p",{style:{fontSize:10,color:h.subColor||"var(--text-muted)",marginTop:2},children:h.sub})]},h.label))}),((d=i.daily_economics)==null?void 0:d.length)>0&&o.jsxs("div",{style:{marginTop:18,paddingTop:14,borderTop:"1px solid var(--border)"},children:[o.jsx("p",{className:"stat-label",style:{marginBottom:10},children:"Daily Breakdown (Last 7 Days)"}),o.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(7,1fr)",gap:8},children:(i.daily_economics||[]).slice(0,7).reverse().map((h,p)=>{const g=new Date(h.day).toLocaleDateString("en-US",{weekday:"short",month:"numeric",day:"numeric",timeZone:"America/Los_Angeles"}),y=h.net_pnl>=0;return o.jsxs("div",{style:{borderRadius:8,padding:"10px 8px",background:y?"rgba(0,195,137,0.06)":"rgba(255,92,92,0.06)",border:`1px solid ${y?"rgba(0,195,137,0.18)":"rgba(255,92,92,0.18)"}`,textAlign:"center"},children:[o.jsx("p",{style:{fontSize:10,color:"var(--text-muted)",fontWeight:600,marginBottom:4},children:g}),o.jsxs("p",{className:"mono",style:{fontSize:13,fontWeight:700,color:y?"var(--green)":"var(--red)",marginBottom:3},children:[y?"+":"","$",(h.net_pnl/100).toFixed(0)]}),o.jsxs("p",{style:{fontSize:10,color:"var(--text-muted)",marginBottom:2},children:[h.trades," trades"]}),o.jsxs("p",{style:{fontSize:10,color:"var(--text-muted)"},children:[o.jsxs("span",{style:{color:"var(--green)"},children:[h.wins,"W"]})," / ",o.jsxs("span",{style:{color:"var(--red)"},children:[h.losses,"L"]})]})]},p)})})]})]})}),o.jsx(yt,{title:"Best Opportunities",children:o.jsx(QJ,{opportunities:i.top_opportunities})}),o.jsx(yt,{title:"Today's Performance",children:o.jsxs("div",{className:"card",style:{border:"1px solid rgba(247,147,26,0.18)",background:"linear-gradient(135deg, rgba(247,147,26,0.04), var(--surface))"},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",marginBottom:14},children:[o.jsxs("div",{className:"section-title",children:[o.jsx("svg",{style:{width:18,height:18,color:"var(--orange)"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.8",d:"M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"})}),"Today's Lessons"]}),o.jsx("span",{style:{marginLeft:"auto",fontSize:12,color:"var(--text-muted)"},children:new Date().toLocaleDateString("en-US",{weekday:"long",month:"short",day:"numeric"})})]}),o.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(4,1fr)",gap:16,textAlign:"center"},children:[{label:"Trades Resolved",value:(i.today_trades||0).toLocaleString(),color:"var(--orange)"},{label:"Wins / Losses",value:o.jsxs("span",{children:[o.jsx("span",{style:{color:"var(--green)"},children:i.today_wins||0}),o.jsx("span",{style:{color:"var(--border-light)",margin:"0 4px"},children:"/"}),o.jsx("span",{style:{color:"var(--red)"},children:i.today_losses||0})]}),color:null},{label:"Win Rate",value:`${l}%`,color:Number(l)>=50?"var(--green)":"var(--red)"},{label:"Day P&L",value:`${(i.daily_pnl||0)>=0?"+":""}$${((i.daily_pnl||0)/100).toLocaleString(void 0,{minimumFractionDigits:2})}`,color:(i.daily_pnl||0)>=0?"var(--green)":"var(--red)"}].map((h,p)=>o.jsxs("div",{children:[o.jsx("p",{className:"stat-label",style:{marginBottom:6},children:h.label}),typeof h.value=="string"?o.jsx("p",{className:"mono",style:{fontSize:22,fontWeight:700,color:h.color},children:h.value}):o.jsx("p",{className:"mono",style:{fontSize:22,fontWeight:700},children:h.value})]},p))})]})}),o.jsx(yt,{title:"Strategy Flow",children:o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"2fr 1fr",gap:16},children:[o.jsx(JJ,{topMarkets:i.top_markets,seedMoney:i.seed_money,balance:i.balance}),o.jsx(tZ,{todayWins:i.today_wins,todayLosses:i.today_losses})]})}),o.jsx(yt,{title:"Action Plan",children:o.jsx(ZJ,{topMarkets:i.top_markets,worstMarkets:i.worst_markets,strategies:i.strategies})}),(i.top_markets||[]).length>0&&o.jsx(yt,{title:"Top Markets",children:o.jsxs("div",{className:"card",children:[o.jsxs("div",{className:"section-title",style:{marginBottom:14},children:[o.jsx("svg",{style:{width:18,height:18,color:"var(--green)"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.8",d:"M5 3l14 9-14 9V3z"})}),"Top Markets — Money Makers"]}),o.jsx("div",{style:{overflowX:"auto"},children:o.jsxs("table",{children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{style:{textAlign:"left"},children:"Market"}),o.jsx("th",{style:{textAlign:"right"},children:"Trades"}),o.jsx("th",{style:{textAlign:"right"},children:"Wins"}),o.jsx("th",{style:{textAlign:"right"},children:"P&L"}),o.jsx("th",{children:"Edge"}),o.jsx("th",{children:"Signal"})]})}),o.jsx("tbody",{children:(i.top_markets||[]).map((h,p)=>{var g;return o.jsxs("tr",{children:[o.jsxs("td",{style:{maxWidth:300},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[o.jsx(Sc,{to:`/positions?market=${encodeURIComponent(h.ticker)}`,style:{fontSize:13,color:"var(--text)",textDecoration:"none",display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",transition:"color 150ms"},onMouseEnter:y=>{y.currentTarget.style.color="var(--cyan)"},onMouseLeave:y=>{y.currentTarget.style.color="var(--text)"},children:h.title}),o.jsx("a",{href:`https://kalshi.com/search?query=${encodeURIComponent(((g=h.title)==null?void 0:g.split("?")[0])||h.ticker)}`,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--text-muted)",flexShrink:0,textDecoration:"none",fontSize:13},onMouseEnter:y=>{y.currentTarget.style.color="var(--cyan)"},onMouseLeave:y=>{y.currentTarget.style.color="var(--text-muted)"},title:"View on Kalshi",children:"↗"})]}),o.jsx("span",{className:"mono",style:{fontSize:10,color:"var(--text-muted)"},children:h.ticker})]}),o.jsx("td",{style:{textAlign:"right"},className:"mono",children:o.jsx("span",{style:{fontSize:13,color:"var(--text-dim)"},children:h.trades})}),o.jsx("td",{style:{textAlign:"right",fontSize:13},children:o.jsx(Oj,{wins:h.wins,losses:h.losses})}),o.jsx("td",{style:{textAlign:"right",fontSize:13},children:o.jsx(ic,{cents:h.pnl})}),o.jsx("td",{style:{fontSize:12,color:"var(--text-muted)",whiteSpace:"nowrap"},children:h.edge}),o.jsx("td",{style:{textAlign:"center"},children:o.jsx(Nj,{wins:h.wins,losses:h.losses,pnl:h.pnl})})]},p)})})]})})]})}),(i.worst_markets||[]).length>0&&o.jsx(yt,{title:"Bleeding Markets",children:o.jsxs("div",{className:"card",style:{border:"1px solid rgba(255,92,92,0.12)"},children:[o.jsxs("div",{className:"section-title",style:{marginBottom:14,color:"var(--red)"},children:[o.jsx("svg",{style:{width:18,height:18},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.8",d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})}),"Bleeding Markets — Consider Exiting"]}),o.jsx("div",{style:{overflowX:"auto"},children:o.jsxs("table",{children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{style:{textAlign:"left"},children:"Market"}),o.jsx("th",{style:{textAlign:"right"},children:"Trades"}),o.jsx("th",{style:{textAlign:"right"},children:"Wins"}),o.jsx("th",{style:{textAlign:"right"},children:"P&L"}),o.jsx("th",{children:"Edge"}),o.jsx("th",{children:"Signal"})]})}),o.jsx("tbody",{children:(i.worst_markets||[]).map((h,p)=>{var g;return o.jsxs("tr",{children:[o.jsxs("td",{style:{maxWidth:300},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[o.jsx(Sc,{to:`/positions?market=${encodeURIComponent(h.ticker)}`,style:{fontSize:13,color:"var(--text)",textDecoration:"none",display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",transition:"color 150ms"},onMouseEnter:y=>{y.currentTarget.style.color="var(--red)"},onMouseLeave:y=>{y.currentTarget.style.color="var(--text)"},children:h.title}),o.jsx("a",{href:`https://kalshi.com/search?query=${encodeURIComponent(((g=h.title)==null?void 0:g.split("?")[0])||h.ticker)}`,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--text-muted)",flexShrink:0,textDecoration:"none",fontSize:13},onMouseEnter:y=>{y.currentTarget.style.color="var(--red)"},onMouseLeave:y=>{y.currentTarget.style.color="var(--text-muted)"},title:"View on Kalshi",children:"↗"})]}),o.jsx("span",{className:"mono",style:{fontSize:10,color:"var(--text-muted)"},children:h.ticker})]}),o.jsx("td",{style:{textAlign:"right"},className:"mono",children:o.jsx("span",{style:{fontSize:13,color:"var(--text-dim)"},children:h.trades})}),o.jsx("td",{style:{textAlign:"right",fontSize:13},children:o.jsx(Oj,{wins:h.wins,losses:h.losses})}),o.jsx("td",{style:{textAlign:"right",fontSize:13},children:o.jsx(ic,{cents:h.pnl})}),o.jsx("td",{style:{fontSize:12,color:"var(--text-muted)",whiteSpace:"nowrap"},children:h.edge}),o.jsx("td",{style:{textAlign:"center"},children:o.jsx(Nj,{wins:h.wins,losses:h.losses,pnl:h.pnl})})]},p)})})]})})]})}),s.length>0&&o.jsx(yt,{title:"P&L History",children:o.jsxs("div",{className:"card",children:[o.jsxs("div",{className:"section-title",style:{marginBottom:14},children:[o.jsx("svg",{style:{width:18,height:18,color:"var(--cyan)"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.8",d:"M7 12l3-3 3 3 4-4M8 21l4-4 4 4M3 4h18M4 4h16v12a1 1 0 01-1 1H5a1 1 0 01-1-1V4z"})}),"P&L History (Daily)"]}),o.jsx(tr,{width:"100%",height:200,children:o.jsxs(Jy,{data:s,children:[o.jsx("defs",{children:o.jsxs("linearGradient",{id:"pnlGrad",x1:"0",y1:"0",x2:"0",y2:"1",children:[o.jsx("stop",{offset:"5%",stopColor:"#00F0FF",stopOpacity:.2}),o.jsx("stop",{offset:"95%",stopColor:"#00F0FF",stopOpacity:0})]})}),o.jsx(Ia,{strokeDasharray:"3 3",stroke:"var(--border)"}),o.jsx(or,{dataKey:"day",stroke:"var(--text-muted)",tick:{fill:"var(--text-muted)",fontSize:11}}),o.jsx(sr,{stroke:"var(--text-muted)",tick:{fill:"var(--text-muted)",fontSize:11},tickFormatter:h=>`$${h}`}),o.jsx(Ge,{contentStyle:{background:"var(--surface-el)",border:"1px solid var(--border)",borderRadius:8,color:"var(--text)"}}),o.jsx(Lr,{type:"monotone",dataKey:"pnl",stroke:"var(--cyan)",strokeWidth:2,fill:"url(#pnlGrad)"})]})})]})}),o.jsx(yt,{title:"Strategy P&L",children:o.jsx(eZ,{strategies:i.strategies})}),o.jsx(yt,{title:"Strategy Leaderboard",children:o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:16},children:[o.jsxs("div",{className:"card",children:[o.jsxs("div",{className:"section-title",style:{marginBottom:12},children:[o.jsx("svg",{style:{width:18,height:18,color:"var(--green)"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.8",d:"M5 3l14 9-14 9V3z"})}),"Top Strategies"]}),o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[c.map((h,p)=>o.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"8px 0",borderBottom:p<c.length-1?"1px solid var(--border)":"none"},children:[o.jsxs("div",{children:[o.jsx("span",{style:{fontSize:13,fontWeight:500,color:"var(--text)"},children:h.name}),o.jsx("span",{style:{marginLeft:8,fontSize:10,color:"var(--text-muted)"},children:h.strategy})]}),o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12},children:[o.jsxs("span",{style:{fontSize:11,color:"var(--text-muted)"},children:[h.win_rate,"% WR"]}),o.jsx(ic,{cents:h.pnl})]})]},p)),c.length===0&&o.jsx("p",{style:{color:"var(--text-muted)",fontSize:13,textAlign:"center",padding:"16px 0"},children:"No profitable strategies yet"})]})]}),o.jsxs("div",{className:"card",children:[o.jsxs("div",{className:"section-title",style:{marginBottom:12},children:[o.jsx("svg",{style:{width:18,height:18,color:"var(--red)"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.8",d:"M13 17h8m0 0V9m0 8l-8-8-4 4-6-6"})}),"Losing Strategies"]}),o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[u.map((h,p)=>o.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"8px 0",borderBottom:p<u.length-1?"1px solid var(--border)":"none"},children:[o.jsxs("div",{children:[o.jsx("span",{style:{fontSize:13,fontWeight:500,color:"var(--text-dim)"},children:h.name}),o.jsx("span",{style:{marginLeft:8,fontSize:10,color:"var(--text-muted)"},children:h.strategy})]}),o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12},children:[o.jsxs("span",{style:{fontSize:11,color:"var(--text-muted)"},children:[h.win_rate,"% WR"]}),o.jsx(ic,{cents:h.pnl})]})]},p)),u.length===0&&o.jsx("p",{style:{color:"var(--text-muted)",fontSize:13,textAlign:"center",padding:"16px 0"},children:"No losing strategies"})]})]})]})}),o.jsx(yt,{title:"Strategy Deep Dive",defaultOpen:!1,children:o.jsx(sZ,{})}),o.jsx(yt,{title:"Recent Activity",children:o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:16},children:[o.jsxs("div",{className:"card",children:[o.jsxs("div",{className:"section-title",style:{marginBottom:12},children:[o.jsx("svg",{style:{width:18,height:18,color:"var(--cyan)"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.8",d:"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"})}),"Recent Fills"]}),(i.recent_fills||[]).length>0?o.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:(i.recent_fills||[]).slice(0,5).map((h,p)=>{var g;return o.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",fontSize:13},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[o.jsx("span",{className:"mono",style:{fontSize:11,color:"var(--text-muted)"},children:h.ticker}),o.jsx("span",{className:"badge",style:h.side==="yes"?{background:"var(--green-dim)",color:"var(--green)"}:{background:"var(--red-dim)",color:"var(--red)"},children:(g=h.side)==null?void 0:g.toUpperCase()})]}),o.jsxs("span",{className:"mono",style:{color:"var(--text-dim)",fontSize:12},children:[h.count,"@",h.yes_price,"c"]})]},p)})}):o.jsx("p",{style:{color:"var(--text-muted)",fontSize:13,textAlign:"center",padding:"24px 0"},children:"No recent fills"})]}),o.jsxs("div",{className:"card",children:[o.jsxs("div",{className:"section-title",style:{marginBottom:12},children:[o.jsx("svg",{style:{width:18,height:18,color:"var(--cyan)"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.8",d:"M13 10V3L4 14h7v7l9-11h-7z"})}),"Quick Actions"]}),o.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[{to:"/markets",icon:"M13 7h8m0 0v8m0-8l-8 8-4-4-6 6",iconColor:"var(--orange)",label:"Browse Markets",sub:"Find weather contracts"},{to:"/positions",icon:"M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z",iconColor:"var(--green)",label:"View Positions",sub:"Current portfolio"},{to:"/settings",icon:"M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.066 2.573c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.573 1.066c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.066-2.573c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z M15 12a3 3 0 11-6 0 3 3 0 016 0z",iconColor:"var(--blue)",label:"Scan Config",sub:"Intervals & risk params"}].map(h=>o.jsxs(Sc,{to:h.to,style:{display:"flex",alignItems:"center",gap:12,padding:"10px 12px",borderRadius:8,background:"var(--surface-el)",border:"1px solid var(--border)",textDecoration:"none",transition:"all 150ms ease"},onMouseEnter:p=>{p.currentTarget.style.borderColor="var(--cyan)",p.currentTarget.style.background="rgba(0,240,255,0.04)"},onMouseLeave:p=>{p.currentTarget.style.borderColor="var(--border)",p.currentTarget.style.background="var(--surface-el)"},children:[o.jsx("div",{style:{width:32,height:32,borderRadius:8,background:`${h.iconColor}1A`,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:o.jsx("svg",{style:{width:15,height:15,color:h.iconColor},fill:"none",stroke:"currentColor",strokeWidth:"1.8",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:h.icon})})}),o.jsxs("div",{children:[o.jsx("p",{style:{fontSize:13,fontWeight:500,color:"var(--text)",marginBottom:1},children:h.label}),o.jsx("p",{style:{fontSize:11,color:"var(--text-muted)"},children:h.sub})]})]},h.to))})]})]})})]})}function uZ({m:e}){const[t,r]=P.useState(null),[n,a]=P.useState(!1),[i,s]=P.useState(!1);async function l(){if(n){a(!1);return}a(!0),s(!0);try{const c=await me("/kalshi",{action:"get_orderbook",ticker:e.ticker});c.success&&r(c.orderbook)}catch{}s(!1)}return o.jsxs(o.Fragment,{children:[o.jsxs("tr",{style:{background:"rgba(0,240,255,0.02)"},children:[o.jsx("td",{className:"pl-8 max-w-[250px]",children:o.jsx("span",{className:"truncate block text-sm",style:{color:"var(--text-dim)"},children:e.title||e.subtitle||e.ticker})}),o.jsx("td",{children:o.jsx("a",{href:`https://kalshi.com/search?query=${encodeURIComponent((e.ticker||"").split("-")[0])}`,target:"_blank",rel:"noopener noreferrer",className:"mono text-xs hover:underline transition",style:{color:"var(--cyan)"},children:e.ticker})}),o.jsx("td",{children:o.jsxs("span",{className:"mono text-sm",style:{color:"var(--green)"},children:[e.yes_bid??"—","¢"]})}),o.jsx("td",{children:o.jsxs("span",{className:"mono text-sm",style:{color:"var(--red)"},children:[e.yes_ask??"—","¢"]})}),o.jsx("td",{children:o.jsx("span",{className:"mono text-xs",style:{color:"var(--text-dim)"},children:(e.volume||0).toLocaleString()})}),o.jsx("td",{children:o.jsx("span",{className:"mono text-xs",style:{color:"var(--text-muted)"},children:e.open_interest?e.open_interest.toLocaleString():"—"})}),o.jsx("td",{children:o.jsx("button",{onClick:l,className:"btn btn-ghost btn-sm",style:{color:n?"var(--cyan)":"var(--text-muted)"},children:n?"▾ Book":"▸ Book"})})]}),n&&o.jsx("tr",{style:{background:"rgba(0,240,255,0.01)"},children:o.jsx("td",{colSpan:7,className:"p-4",children:i?o.jsx("div",{className:"flex items-center justify-center h-16",children:o.jsx("div",{className:"animate-spin w-5 h-5 border-2 border-t-transparent rounded-full",style:{borderColor:"var(--cyan)",borderTopColor:"transparent"}})}):t?o.jsxs("div",{className:"grid grid-cols-2 gap-6 max-w-lg",children:[o.jsxs("div",{children:[o.jsx("p",{className:"stat-label mb-2",style:{color:"var(--green)"},children:"YES Bids"}),o.jsxs("div",{className:"space-y-1",children:[(t.yes||[]).slice(0,8).map((c,u)=>o.jsxs("div",{className:"relative flex justify-between text-xs px-2 py-1 rounded overflow-hidden",style:{background:"var(--surface-el)"},children:[o.jsx("div",{className:"absolute inset-0 rounded",style:{width:`${Math.min((c[1]||0)*2,100)}%`,background:"rgba(0,195,137,0.08)"}}),o.jsxs("span",{className:"mono relative z-10",style:{color:"var(--green)"},children:[c[0],"¢"]}),o.jsx("span",{className:"mono relative z-10",style:{color:"var(--text-muted)"},children:c[1]})]},u)),(!t.yes||t.yes.length===0)&&o.jsx("p",{className:"text-xs text-center py-2",style:{color:"var(--text-muted)"},children:"Empty"})]})]}),o.jsxs("div",{children:[o.jsx("p",{className:"stat-label mb-2",style:{color:"var(--red)"},children:"NO Bids"}),o.jsxs("div",{className:"space-y-1",children:[(t.no||[]).slice(0,8).map((c,u)=>o.jsxs("div",{className:"relative flex justify-between text-xs px-2 py-1 rounded overflow-hidden",style:{background:"var(--surface-el)"},children:[o.jsx("div",{className:"absolute inset-0 rounded",style:{width:`${Math.min((c[1]||0)*2,100)}%`,background:"rgba(255,92,92,0.08)"}}),o.jsxs("span",{className:"mono relative z-10",style:{color:"var(--red)"},children:[c[0],"¢"]}),o.jsx("span",{className:"mono relative z-10",style:{color:"var(--text-muted)"},children:c[1]})]},u)),(!t.no||t.no.length===0)&&o.jsx("p",{className:"text-xs text-center py-2",style:{color:"var(--text-muted)"},children:"Empty"})]})]})]}):o.jsx("p",{className:"text-xs text-center py-2",style:{color:"var(--text-muted)"},children:"No orderbook data"})})})]})}function dZ({e}){const[t,r]=P.useState(!1),[n,a]=P.useState([]),[i,s]=P.useState(!1);async function l(){if(t){r(!1);return}if(r(!0),!(n.length>0)){s(!0);try{const c=await me("/kalshi",{action:"get_markets",params:{event_ticker:e.event_ticker}});a(c.markets||[])}catch{}s(!1)}}return o.jsxs(o.Fragment,{children:[o.jsxs("tr",{className:"cursor-pointer transition",onClick:l,style:{background:t?"rgba(0,240,255,0.04)":void 0},onMouseEnter:c=>{t||(c.currentTarget.style.background="var(--cyan-glow)")},onMouseLeave:c=>{t||(c.currentTarget.style.background="")},children:[o.jsx("td",{className:"max-w-[300px]",children:o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-xs transition-transform inline-block",style:{color:"var(--text-muted)",transform:t?"rotate(90deg)":"rotate(0deg)"},children:"▶"}),o.jsx("span",{className:"truncate block font-medium heading",style:{color:"var(--text)"},children:e.title})]})}),o.jsx("td",{children:o.jsx("span",{className:"badge bg-orange",children:e.category||"—"})}),o.jsx("td",{children:o.jsx("a",{href:`https://kalshi.com/search?query=${encodeURIComponent((e.event_ticker||"").split("-")[0])}`,target:"_blank",rel:"noopener noreferrer",className:"mono text-xs hover:underline transition",style:{color:"var(--cyan)"},onClick:c=>c.stopPropagation(),children:e.event_ticker})}),o.jsx("td",{children:o.jsx("span",{className:"text-xs",style:{color:"var(--text-muted)"},children:e.mutually_exclusive?o.jsx("span",{className:"badge bg-blue",children:"ME"}):"—"})}),o.jsx("td",{onClick:c=>c.stopPropagation(),children:t?o.jsxs("span",{className:"text-xs mono",style:{color:"var(--cyan)"},children:[n.length||"..."," contracts"]}):o.jsx("span",{className:"text-xs transition",style:{color:"var(--text-muted)"},children:"View Contracts"})})]}),t&&o.jsx("tr",{children:o.jsx("td",{colSpan:5,className:"p-0",children:o.jsx("div",{className:"ml-6 fade-in",style:{borderLeft:"2px solid rgba(0,240,255,0.2)",background:"rgba(0,240,255,0.015)"},children:i?o.jsx("div",{className:"flex items-center justify-center py-8",children:o.jsx("div",{className:"animate-spin w-5 h-5 border-2 border-t-transparent rounded-full",style:{borderColor:"var(--cyan)",borderTopColor:"transparent"}})}):n.length===0?o.jsx("div",{className:"text-xs text-center py-4",style:{color:"var(--text-muted)"},children:"No contracts found"}):o.jsxs("table",{className:"w-full",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{className:"pl-8",children:"Contract"}),o.jsx("th",{children:"Ticker"}),o.jsx("th",{children:"Yes Bid"}),o.jsx("th",{children:"Yes Ask"}),o.jsx("th",{children:"Volume"}),o.jsx("th",{children:"Open Int."}),o.jsx("th",{children:"Book"})]})}),o.jsx("tbody",{children:n.map(c=>o.jsx(uZ,{m:c},c.ticker))})]})})})})]})}function fZ(){const[e,t]=P.useState([]),[r,n]=P.useState(!0),[a,i]=P.useState(""),[s,l]=P.useState("");P.useEffect(()=>{c()},[]);async function c(){n(!0);try{const d=await me("/kalshi",{action:"get_events",params:{status:"open",limit:100}});t(d.events||[])}catch{}n(!1)}const u=[...new Set(e.map(d=>d.category).filter(Boolean))].sort(),f=e.filter(d=>{const h=!a||(d.title||"").toLowerCase().includes(a.toLowerCase())||(d.category||"").toLowerCase().includes(a.toLowerCase()),p=!s||d.category===s;return h&&p});return r?o.jsx("div",{className:"flex items-center justify-center h-64",children:o.jsx("div",{className:"animate-spin w-8 h-8 border-2 border-t-transparent rounded-full pulse-cyan",style:{borderColor:"var(--cyan)",borderTopColor:"transparent"}})}):o.jsxs("div",{className:"space-y-6 fade-in",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("h1",{className:"heading text-3xl font-bold",style:{color:"var(--text)"},children:"Markets"}),o.jsxs("span",{className:"badge bg-cyan",children:[e.length," events"]}),f.length!==e.length&&o.jsxs("span",{className:"badge bg-orange",children:[f.length," filtered"]})]}),o.jsx("p",{className:"section-subtitle mt-1",children:"Live Kalshi prediction markets"})]}),o.jsx("button",{onClick:c,className:"btn btn-o btn-sm",children:"↻ Refresh"})]}),o.jsxs("div",{className:"relative",children:[o.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-sm pointer-events-none",style:{color:"var(--text-muted)"},children:"⌕"}),o.jsx("input",{type:"text",value:a,onChange:d=>i(d.target.value),placeholder:"Search markets by name or category...",className:"input pl-8"})]}),u.length>0&&o.jsxs("div",{className:"flex flex-wrap gap-2",children:[o.jsx("button",{onClick:()=>l(""),className:"badge transition cursor-pointer",style:{background:s?"rgba(42,42,53,0.6)":"var(--cyan-dim)",color:s?"var(--text-muted)":"var(--cyan)",border:s?"1px solid var(--border)":"1px solid rgba(0,240,255,0.3)"},children:"All"}),u.map(d=>o.jsx("button",{onClick:()=>l(d===s?"":d),className:"badge transition cursor-pointer",style:{background:s===d?"var(--orange-dim)":"rgba(42,42,53,0.6)",color:s===d?"var(--orange)":"var(--text-muted)",border:s===d?"1px solid rgba(247,147,26,0.3)":"1px solid var(--border)"},children:d},d))]}),o.jsx("div",{className:"card overflow-x-auto",style:{padding:0},children:o.jsxs("table",{children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{className:"pl-5",children:"Event"}),o.jsx("th",{children:"Category"}),o.jsx("th",{children:"Ticker"}),o.jsx("th",{children:"Type"}),o.jsx("th",{children:"Contracts"})]})}),o.jsx("tbody",{children:f.length===0?o.jsx("tr",{children:o.jsx("td",{colSpan:5,className:"text-center py-12",style:{color:"var(--text-muted)"},children:o.jsxs("div",{className:"flex flex-col items-center gap-2",children:[o.jsx("span",{className:"text-2xl",children:"⌕"}),o.jsx("span",{className:"text-sm",children:"No markets match your filter"})]})})}):f.map(d=>o.jsx(dZ,{e:d},d.event_ticker))})]})})]})}function oc(e,t=9,r="flat"){let n=e;const a=()=>(n=n*1664525+1013904223&4294967295,Math.abs(n)%1e3/1e3),i=r==="up"?.8:r==="down"?-.8:0;let s=45+a()*10;const l=[];for(let c=0;c<t;c++){const u=(a()-.45+i*.1)*6,f=s,d=Math.max(5,Math.min(95,s+u)),h=a()*3,p=a()*3,g=Math.max(f,d)+h,y=Math.min(f,d)-p;l.push({o:f,h:g,l:y,c:d}),s=d}return l}function sc({data:e,width:t=80,height:r=32,bullColor:n="var(--green)",bearColor:a="var(--red)"}){if(!e||e.length===0)return null;const i=e.map(m=>m.l),s=e.map(m=>m.h),l=Math.min(...i),u=Math.max(...s)-l||1,f=2,d=r-f*2,h=t-f*2,p=m=>f+d-(m-l)/u*d,g=e.length,y=h/g,b=Math.max(2,y*.55),v=1;return o.jsx("svg",{width:t,height:r,viewBox:`0 0 ${t} ${r}`,style:{display:"block",flexShrink:0},"aria-hidden":"true",children:e.map((m,x)=>{const S=m.c>=m.o,j=S?n:a,w=f+x*y+y/2,_=p(Math.max(m.o,m.c)),O=p(Math.min(m.o,m.c)),N=Math.max(1,O-_);return o.jsxs("g",{children:[o.jsx("line",{x1:w,y1:p(m.h),x2:w,y2:p(m.l),stroke:j,strokeWidth:v,strokeOpacity:.7}),o.jsx("rect",{x:w-b/2,y:_,width:b,height:N,fill:j,fillOpacity:S?.85:.75,rx:.5})]},x)})})}const fn=e=>`$${(e/100).toFixed(2)}`,Rr=e=>{const t=e/100;return`${t>=0?"+":""}$${t.toFixed(2)}`},hZ=e=>e>=0?"text-green":"text-red",Ha=e=>e==="BUY_YES"?"bg-green":"bg-red",Ka=e=>e==="BUY_YES"?"YES":"NO",Ho=(e,t,r)=>!r||r===0?null:Math.round(e+t/r),Ro=e=>`https://kalshi.com/search?query=${encodeURIComponent((e||"").split("-")[0])}`,Pj=e=>{if(!e)return"";const t=Date.now()-new Date(e).getTime();return t<6e4?"just now":t<36e5?`${Math.floor(t/6e4)}m ago`:t<864e5?`${Math.floor(t/36e5)}h ago`:`${Math.floor(t/864e5)}d ago`};function pZ({positions:e}){if(!e||!e.length)return null;const r=[{label:"<-$50",min:-1/0,max:-5e3,color:"#FF5C5C"},{label:"-$20-50",min:-5e3,max:-2e3,color:"#FF7A7A"},{label:"-$1-20",min:-2e3,max:-100,color:"#FF9999"},{label:"$0",min:-100,max:100,color:"#6B7280"},{label:"$1-20",min:100,max:2e3,color:"#88DDBB"},{label:"$20-50",min:2e3,max:5e3,color:"#44CC99"},{label:">$50",min:5e3,max:1/0,color:"#00C389"}].map(a=>{const i=e.filter(s=>{const l=s.realized_pnl_cents||0;return l>a.min&&l<=a.max}).length;return{...a,count:i}}).filter(a=>a.count>0);if(!r.length)return null;const n=({active:a,payload:i,label:s})=>{var c;if(!a||!(i!=null&&i.length))return null;const l=((c=i[0])==null?void 0:c.payload)||{};return o.jsxs("div",{style:{background:"#1C1C24",border:"1px solid #2A2A35",borderRadius:8,padding:"8px 12px",fontSize:12,fontFamily:"'Inter', sans-serif"},children:[o.jsx("p",{style:{color:"#E0E0E0",fontWeight:700,marginBottom:4},children:s}),o.jsxs("p",{style:{color:l.color,fontFamily:"'JetBrains Mono', monospace",fontWeight:700},children:[l.count," position",l.count!==1?"s":""]})]})};return o.jsxs("div",{className:"card",children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:14},children:[o.jsx("h2",{className:"section-title",style:{fontSize:"1.05rem"},children:"P&L Distribution"}),o.jsxs("span",{style:{fontSize:11,color:"#6B7280"},children:[e.length," positions total"]})]}),o.jsx(tr,{width:"100%",height:180,children:o.jsxs(_l,{data:r,margin:{top:4,right:12,left:0,bottom:4},children:[o.jsx(Ia,{strokeDasharray:"3 3",stroke:"#2A2A35",strokeOpacity:.6,vertical:!1}),o.jsx(or,{dataKey:"label",stroke:"#2A2A35",tick:{fill:"#6B7280",fontSize:10,fontFamily:"'Inter', sans-serif"},tickLine:!1,axisLine:{stroke:"#2A2A35"}}),o.jsx(sr,{stroke:"#2A2A35",tick:{fill:"#6B7280",fontSize:11,fontFamily:"'Inter', sans-serif"},tickLine:!1,axisLine:!1,allowDecimals:!1,width:30}),o.jsx(Ge,{content:o.jsx(n,{}),cursor:{fill:"rgba(0,240,255,0.04)"}}),o.jsx(nr,{dataKey:"count",radius:[4,4,0,0],maxBarSize:48,children:r.map((a,i)=>o.jsx(xr,{fill:a.color,fillOpacity:.85},i))})]})})]})}function mZ(){return o.jsx("div",{className:"flex items-center justify-center h-64",children:o.jsx("div",{className:"w-9 h-9 rounded-full border-2 animate-spin",style:{borderColor:"var(--border)",borderTopColor:"var(--cyan)"}})})}function Aj({p:e,trades:t,loading:r}){return o.jsxs("div",{style:{background:"var(--bg)",borderTop:"1px solid var(--border)",borderBottom:"1px solid var(--border)"},className:"px-4 py-3",children:[o.jsxs("div",{className:"flex items-center justify-between mb-3",children:[o.jsxs("span",{className:"mono text-xs font-bold",style:{color:"var(--cyan)"},children:["Trade History — ",e.ticker]}),o.jsxs("div",{className:"flex gap-4 text-xs",style:{color:"var(--text-muted)"},children:[o.jsxs("span",{children:["Open: ",o.jsx("b",{style:{color:"var(--blue)"},children:e.open_trades})]}),o.jsxs("span",{children:["Closed: ",o.jsx("b",{style:{color:"var(--text-dim)"},children:e.closed_trades})]}),o.jsxs("span",{children:["Entry Range:"," ",o.jsxs("b",{style:{color:"var(--orange)"},children:[e.min_entry,"¢ – ",e.max_entry,"¢"]})]}),o.jsxs("span",{children:["First: ",o.jsx("b",{children:new Date(e.first_trade_at).toLocaleDateString()})]})]})]}),r?o.jsx("div",{className:"flex justify-center py-4",children:o.jsx("div",{className:"w-5 h-5 rounded-full border-2 animate-spin",style:{borderColor:"var(--border)",borderTopColor:"var(--cyan)"}})}):t.length>0?o.jsx("div",{className:"overflow-x-auto",style:{maxHeight:200,overflowY:"auto"},children:o.jsxs("table",{className:"text-xs",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"Time"}),o.jsx("th",{children:"Direction"}),o.jsx("th",{children:"Contracts"}),o.jsx("th",{children:"Entry"}),o.jsx("th",{children:"Exit"}),o.jsx("th",{children:"Cost"}),o.jsx("th",{children:"Profit"}),o.jsx("th",{children:"Status"})]})}),o.jsx("tbody",{children:t.map((n,a)=>{const i=parseInt(n.entry_price_cents)||0,s=parseInt(n.pnl_cents)||0,l=parseInt(n.contracts)||0,c=n.status==="closed"||n.status==="expired",u=c&&l>0?Ho(i,s,l):null;return o.jsxs("tr",{children:[o.jsx("td",{className:"mono",style:{color:"var(--text-muted)"},children:new Date(n.created_at).toLocaleString()}),o.jsx("td",{children:o.jsx("span",{className:`badge ${Ha(n.direction)}`,children:Ka(n.direction)})}),o.jsx("td",{className:"mono",children:n.contracts}),o.jsxs("td",{className:"mono",style:{color:"var(--orange)",fontFamily:"'JetBrains Mono', monospace"},children:[i,"¢"]}),o.jsx("td",{className:"mono",style:{fontFamily:"'JetBrains Mono', monospace",color:u!=null?"var(--text-dim)":"var(--text-muted)"},children:u!=null?`${u}¢`:"—"}),o.jsx("td",{className:"mono",style:{color:"var(--text-dim)"},children:fn(n.cost_cents||0)}),o.jsx("td",{className:"mono",style:{fontFamily:"'JetBrains Mono', monospace",fontWeight:700,color:s>0?"var(--green)":s<0?"var(--red)":"var(--text-muted)"},children:n.pnl_cents!=null&&c?Rr(s):"—"}),o.jsx("td",{children:o.jsx("span",{className:`badge ${n.status==="open"?"bg-blue":n.status==="closed"?"bg-green":"bg-orange"}`,children:n.status})})]},a)})})]})}):o.jsx("p",{className:"text-center py-3 text-xs",style:{color:"var(--text-muted)"},children:"No trade details available"})]})}function vZ(){var D;const[e,t]=P.useState([]),[r,n]=P.useState([]),[a,i]=P.useState({}),[s,l]=P.useState(!0),[c,u]=P.useState(null),[f,d]=P.useState(null),[h,p]=P.useState({}),[g,y]=P.useState(null),[b,v]=P.useState("grouped"),[m,x]=P.useState("cost"),S=P.useCallback(async()=>{try{const A=await Oe("/positions");A.success&&(t(A.positions||[]),n(A.grouped||[]),i(A.summary||{}))}catch{}l(!1)},[]);P.useEffect(()=>{S();const A=setInterval(S,3e4);return()=>clearInterval(A)},[S]);async function j(A,L){const C=`${A}_${L}`;if(!h[C]){y(C);try{const M=await me("/positions/trades",{ticker:A,direction:L,limit:50});M.success&&p(I=>({...I,[C]:M.trades||[]}))}catch{}y(null)}}function w(A){u(L=>L===A?null:A),d(null)}function _(A,L){const C=`${A}_${L}`;f===C?d(null):(d(C),j(A,L))}const O=[...e].sort((A,L)=>m==="pnl"?L.realized_pnl_cents-A.realized_pnl_cents:m==="contracts"?L.open_contracts-A.open_contracts:L.open_cost_cents-A.open_cost_cents),N=e.filter(A=>A.realized_pnl_cents>0).sort((A,L)=>L.realized_pnl_cents-A.realized_pnl_cents),k=e.filter(A=>A.realized_pnl_cents<0).sort((A,L)=>A.realized_pnl_cents-L.realized_pnl_cents),E=e.filter(A=>A.realized_pnl_cents===0),T=e.length>0&&N.length+k.length>0?`${Math.round(N.length/(N.length+k.length)*100)}%`:"—";return s?o.jsx(mZ,{}):o.jsxs("div",{className:"space-y-6 fade-in",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{children:[o.jsxs("h1",{className:"heading text-3xl",style:{color:"var(--text)"},children:["Positions",o.jsx("span",{className:"badge bg-cyan ml-3 align-middle text-base",children:a.positionCount||0})]}),o.jsxs("p",{className:"section-subtitle mt-1",children:[a.positionCount||0," active positions •"," ",((D=a.totalTrades)==null?void 0:D.toLocaleString())||0," total trades"]})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("div",{className:"flex rounded-lg p-0.5 gap-0.5",style:{background:"var(--surface-el)",border:"1px solid var(--border)"},children:[["grouped","Grouped"],["flat","All"],["pnl","P&L"]].map(([A,L])=>o.jsx("button",{onClick:()=>v(A),className:"px-3 py-1 text-xs font-semibold rounded-md transition",style:b===A?{background:"var(--cyan)",color:"var(--bg)",fontFamily:"var(--font-body)"}:{color:"var(--text-muted)",fontFamily:"var(--font-body)"},children:L},A))}),o.jsx("button",{onClick:S,className:"btn btn-o btn-sm",children:"Refresh"})]})]}),o.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:[o.jsxs("div",{className:"card card-accent-cyan",children:[o.jsx("p",{className:"stat-label",children:"Positions"}),o.jsx("p",{className:"stat-v mono mt-2",style:{color:"var(--cyan)"},children:a.positionCount||0})]}),o.jsxs("div",{className:"card card-accent-orange",children:[o.jsx("p",{className:"stat-label",children:"Total Cost"}),o.jsx("p",{className:"stat-v mono mt-2",style:{color:"var(--text)"},children:fn(a.totalCost||0)})]}),o.jsxs("div",{className:`card ${(a.totalPnl||0)>=0?"card-accent-green":"card-accent-red"}`,children:[o.jsx("p",{className:"stat-label",children:"Realized P&L"}),o.jsx("p",{className:`stat-v mono mt-2 ${(a.totalPnl||0)>=0?"pnl-positive":"pnl-negative"}`,children:Rr(a.totalPnl||0)})]}),o.jsxs("div",{className:"card card-accent-blue",children:[o.jsx("p",{className:"stat-label",children:"Contracts"}),o.jsx("p",{className:"stat-v mono mt-2",style:{color:"var(--blue)"},children:(a.totalContracts||0).toLocaleString()})]}),o.jsxs("div",{className:"card card-accent-green",children:[o.jsx("p",{className:"stat-label",children:"Win Rate"}),o.jsx("p",{className:"stat-v mono mt-2 text-green",children:T})]})]}),a.totalPnl!==0&&o.jsxs("div",{className:"card py-3",children:[o.jsxs("div",{className:"flex items-center justify-between text-xs mb-2",children:[o.jsxs("span",{className:"font-semibold text-green",children:[N.length," winners"]}),o.jsxs("span",{style:{color:"var(--text-muted)"},children:[E.length," flat"]}),o.jsxs("span",{className:"font-semibold text-red",children:[k.length," losers"]})]}),o.jsx("div",{className:"progress-bar",style:{height:8},children:(()=>{const A=N.reduce((C,M)=>C+M.realized_pnl_cents,0)+Math.abs(k.reduce((C,M)=>C+M.realized_pnl_cents,0));if(!A)return null;const L=N.reduce((C,M)=>C+M.realized_pnl_cents,0)/A*100;return o.jsxs("div",{className:"flex h-full w-full",children:[o.jsx("div",{className:"bar-win-glow",style:{width:`${L}%`,background:"var(--green)",borderRadius:"2px 0 0 2px"}}),o.jsx("div",{className:"bar-loss-glow",style:{width:`${100-L}%`,background:"var(--red)",borderRadius:"0 2px 2px 0"}})]})})()})]}),o.jsx(pZ,{positions:e}),b==="grouped"&&o.jsx("div",{className:"space-y-3",children:r.map(A=>{const L=c===A.event;return o.jsxs("div",{className:"card p-0 overflow-hidden",style:{padding:0},children:[o.jsxs("button",{onClick:()=>w(A.event),className:"w-full flex items-center gap-3 p-4 text-left transition",style:{background:"transparent"},onMouseEnter:C=>C.currentTarget.style.background="var(--cyan-glow)",onMouseLeave:C=>C.currentTarget.style.background="transparent",children:[o.jsx("span",{className:"text-xs inline-block transition-transform",style:{color:"var(--cyan)",transform:L?"rotate(90deg)":"rotate(0deg)"},children:"▶"}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"mono text-sm font-bold",style:{color:"var(--orange)"},children:A.event}),o.jsx("span",{className:"badge bg-cyan",children:A.positions.length})]}),o.jsx("p",{className:"text-xs truncate mt-0.5",style:{color:"var(--text-muted)"},children:A.title})]}),o.jsxs("div",{className:"flex items-center gap-6 text-right flex-shrink-0",children:[o.jsxs("div",{children:[o.jsx("p",{className:"text-xs",style:{color:"var(--text-muted)"},children:"Cost"}),o.jsx("p",{className:"mono text-sm",style:{color:"var(--text)"},children:fn(A.totalCost)})]}),o.jsxs("div",{children:[o.jsx("p",{className:"text-xs",style:{color:"var(--text-muted)"},children:"Contracts"}),o.jsx("p",{className:"mono text-sm",style:{color:"var(--blue)"},children:A.totalContracts.toLocaleString()})]}),o.jsxs("div",{children:[o.jsx("p",{className:"text-xs",style:{color:"var(--text-muted)"},children:"Realized P&L"}),o.jsx("p",{className:`mono text-sm font-bold ${hZ(A.totalPnl)}`,children:Rr(A.totalPnl)})]})]})]}),L&&o.jsx("div",{style:{borderTop:"1px solid var(--border)"},children:o.jsxs("table",{children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{}),o.jsx("th",{children:"Ticker"}),o.jsx("th",{children:"Side"}),o.jsx("th",{children:"Contracts"}),o.jsx("th",{children:"Bought At"}),o.jsx("th",{children:"Sold At"}),o.jsx("th",{children:"Cost"}),o.jsx("th",{children:"Profit"}),o.jsx("th",{children:"Trades"}),o.jsx("th",{children:"Last Trade"})]})}),o.jsx("tbody",{children:A.positions.map(C=>{var Qe,Ae;const M=`${C.ticker}_${C.direction}`,I=f===M,R=h[M]||[],F=g===M,K=(C.realized_pnl_cents||0)>0,z=(C.realized_pnl_cents||0)<0,q=C.ticker.split("").reduce((V,Z)=>V+Z.charCodeAt(0),0),he=oc(q,9,K?"up":z?"down":"flat"),ge=K?"cursor-pointer position-winning":z?"cursor-pointer position-losing":"cursor-pointer";return o.jsxs($.Fragment,{children:[o.jsxs("tr",{className:ge,onClick:()=>_(C.ticker,C.direction),style:{position:"relative"},children:[o.jsx("td",{style:{width:24},children:o.jsx("span",{className:"text-xs inline-block transition-transform",style:{color:"var(--cyan)",transform:I?"rotate(90deg)":"rotate(0deg)"},children:"▶"})}),o.jsx("td",{children:o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[o.jsx("a",{href:Ro(C.ticker),target:"_blank",rel:"noopener noreferrer",className:"mono text-sm hover:underline",style:{color:"var(--orange)"},onClick:V=>V.stopPropagation(),children:C.ticker}),o.jsx(sc,{data:he,width:72,height:28})]})}),o.jsx("td",{children:o.jsx("span",{className:`badge ${Ha(C.direction)}`,children:Ka(C.direction)})}),o.jsx("td",{className:"mono",children:(Qe=C.open_contracts)==null?void 0:Qe.toLocaleString()}),o.jsxs("td",{className:"mono",style:{color:"var(--orange)",fontFamily:"'JetBrains Mono', monospace"},children:[C.avg_entry_price,"¢"]}),o.jsx("td",{className:"mono",style:{fontFamily:"'JetBrains Mono', monospace"},children:(()=>{const V=parseInt(C.closed_trades)||0,Z=parseInt(C.open_trades)||0;if(V>0&&Z===0){const re=Ho(C.avg_entry_price,C.realized_pnl_cents,parseInt(C.open_contracts)||parseInt(C.total_trades)||1);return o.jsxs("span",{style:{color:"var(--text-dim)"},children:[re,"¢"]})}return o.jsx("span",{className:"badge bg-blue",style:{fontSize:"0.65rem"},children:"Open"})})()}),o.jsx("td",{className:"mono",style:{color:"var(--text)"},children:fn(C.open_cost_cents)}),o.jsx("td",{className:"mono",style:{fontFamily:"'JetBrains Mono', monospace",fontWeight:700,color:C.realized_pnl_cents>0?"var(--green)":C.realized_pnl_cents<0?"var(--red)":"var(--text-muted)"},children:C.realized_pnl_cents!==0?Rr(C.realized_pnl_cents):"—"}),o.jsx("td",{className:"mono",style:{color:"var(--text-muted)"},children:(Ae=C.total_trades)==null?void 0:Ae.toLocaleString()}),o.jsx("td",{className:"text-xs",style:{color:"var(--text-muted)"},children:Pj(C.last_trade_at)})]}),I&&o.jsx("tr",{children:o.jsx("td",{colSpan:10,style:{padding:0},children:o.jsx(Aj,{p:C,trades:R,loading:F})})})]},M)})})]})})]},A.event)})}),b==="flat"&&o.jsxs("div",{className:"card overflow-x-auto",style:{padding:0},children:[o.jsxs("div",{className:"flex items-center gap-3 px-4 py-3",style:{borderBottom:"1px solid var(--border)"},children:[o.jsx("span",{className:"text-xs",style:{color:"var(--text-muted)"},children:"Sort by:"}),[["cost","Cost"],["pnl","P&L"],["contracts","Contracts"]].map(([A,L])=>o.jsx("button",{onClick:()=>x(A),className:"text-xs font-semibold px-2.5 py-1 rounded-md transition",style:m===A?{background:"var(--cyan-dim)",color:"var(--cyan)"}:{color:"var(--text-muted)"},children:L},A))]}),o.jsxs("table",{children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"#"}),o.jsx("th",{children:"Ticker"}),o.jsx("th",{children:"Market"}),o.jsx("th",{children:"Side"}),o.jsx("th",{children:"Contracts"}),o.jsx("th",{children:"Bought At"}),o.jsx("th",{children:"Sold At"}),o.jsx("th",{children:"Cost"}),o.jsx("th",{children:"Profit"}),o.jsx("th",{children:"Trades"}),o.jsx("th",{children:"Last Trade"})]})}),o.jsx("tbody",{children:O.length===0?o.jsx("tr",{children:o.jsx("td",{colSpan:11,className:"text-center py-12",style:{color:"var(--text-muted)"},children:"No open positions"})}):O.map((A,L)=>{var ge,Qe;const C=`${A.ticker}_${A.direction}`,M=f===C,I=h[C]||[],R=g===C,F=(A.realized_pnl_cents||0)>0,K=(A.realized_pnl_cents||0)<0,z=A.ticker.split("").reduce((Ae,V)=>Ae+V.charCodeAt(0),0),q=F?"up":K?"down":"flat",ie=oc(z+100,9,q),he=F?"cursor-pointer position-winning":K?"cursor-pointer position-losing":"cursor-pointer";return o.jsxs($.Fragment,{children:[o.jsxs("tr",{className:he,onClick:()=>_(A.ticker,A.direction),style:{position:"relative"},children:[o.jsx("td",{style:{color:"var(--text-muted)"},children:L+1}),o.jsx("td",{children:o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[o.jsx("a",{href:Ro(A.ticker),target:"_blank",rel:"noopener noreferrer",className:"mono text-sm hover:underline",style:{color:"var(--orange)"},onClick:Ae=>Ae.stopPropagation(),children:A.ticker}),o.jsx(sc,{data:ie,width:72,height:28})]})}),o.jsx("td",{className:"text-xs max-w-[192px] truncate",style:{color:"var(--text-dim)"},children:A.title}),o.jsx("td",{children:o.jsx("span",{className:`badge ${Ha(A.direction)}`,children:Ka(A.direction)})}),o.jsx("td",{className:"mono",children:(ge=A.open_contracts)==null?void 0:ge.toLocaleString()}),o.jsxs("td",{className:"mono",style:{color:"var(--orange)",fontFamily:"'JetBrains Mono', monospace"},children:[A.avg_entry_price,"¢"]}),o.jsx("td",{className:"mono",style:{fontFamily:"'JetBrains Mono', monospace"},children:(()=>{const Ae=parseInt(A.closed_trades)||0,V=parseInt(A.open_trades)||0;if(Ae>0&&V===0){const Z=Ho(A.avg_entry_price,A.realized_pnl_cents,parseInt(A.open_contracts)||parseInt(A.total_trades)||1);return o.jsxs("span",{style:{color:"var(--text-dim)"},children:[Z,"¢"]})}return o.jsx("span",{className:"badge bg-blue",style:{fontSize:"0.65rem"},children:"Open"})})()}),o.jsx("td",{className:"mono",style:{color:"var(--text)"},children:fn(A.open_cost_cents)}),o.jsx("td",{className:"mono",style:{fontFamily:"'JetBrains Mono', monospace",fontWeight:700,color:A.realized_pnl_cents>0?"var(--green)":A.realized_pnl_cents<0?"var(--red)":"var(--text-muted)"},children:A.realized_pnl_cents!==0?Rr(A.realized_pnl_cents):"—"}),o.jsx("td",{className:"mono",style:{color:"var(--text-muted)"},children:(Qe=A.total_trades)==null?void 0:Qe.toLocaleString()}),o.jsx("td",{className:"text-xs",style:{color:"var(--text-muted)"},children:Pj(A.last_trade_at)})]}),M&&o.jsx("tr",{children:o.jsx("td",{colSpan:11,style:{padding:0},children:o.jsx(Aj,{p:A,trades:I,loading:R})})})]},C)})})]})]}),b==="pnl"&&o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"card overflow-hidden",style:{padding:0},children:[o.jsxs("div",{className:"flex items-center gap-3 px-4 py-3",style:{background:"rgba(0,195,137,0.06)",borderBottom:"1px solid rgba(0,195,137,0.2)",borderLeft:"4px solid var(--green)"},children:[o.jsx("span",{className:"text-sm font-bold text-green",style:{textShadow:"0 0 10px rgba(0,195,137,0.4)"},children:"Winners"}),o.jsx("span",{className:"badge bg-green",children:N.length}),o.jsx("div",{className:"flex-1"}),o.jsx("span",{className:"mono font-bold pnl-positive",children:Rr(N.reduce((A,L)=>A+L.realized_pnl_cents,0))})]}),o.jsxs("table",{children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"Ticker"}),o.jsx("th",{children:"Market"}),o.jsx("th",{children:"Side"}),o.jsx("th",{children:"Contracts"}),o.jsx("th",{children:"Bought At"}),o.jsx("th",{children:"Sold At"}),o.jsx("th",{children:"Cost"}),o.jsx("th",{children:"Profit"}),o.jsx("th",{children:"ROI"})]})}),o.jsx("tbody",{children:N.map(A=>{var K;const L=A.open_cost_cents>0?`${(A.realized_pnl_cents/A.open_cost_cents*100).toFixed(0)}%`:"∞",C=A.ticker.split("").reduce((z,q)=>z+q.charCodeAt(0),0),M=oc(C+200,9,"up"),I=parseInt(A.closed_trades)||0,R=parseInt(A.open_trades)||0,F=I>0&&R===0?Ho(A.avg_entry_price,A.realized_pnl_cents,parseInt(A.open_contracts)||parseInt(A.total_trades)||1):null;return o.jsxs("tr",{className:"position-winning",style:{position:"relative"},children:[o.jsx("td",{children:o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[o.jsx("a",{href:Ro(A.ticker),target:"_blank",rel:"noopener",className:"mono text-sm hover:underline",style:{color:"var(--orange)"},children:A.ticker}),o.jsx(sc,{data:M,width:64,height:26})]})}),o.jsx("td",{className:"text-xs max-w-[192px] truncate",style:{color:"var(--text-dim)"},children:A.title}),o.jsx("td",{children:o.jsx("span",{className:`badge ${Ha(A.direction)}`,children:Ka(A.direction)})}),o.jsx("td",{className:"mono",children:(K=A.open_contracts)==null?void 0:K.toLocaleString()}),o.jsxs("td",{className:"mono",style:{color:"var(--orange)",fontFamily:"'JetBrains Mono', monospace"},children:[A.avg_entry_price,"¢"]}),o.jsx("td",{className:"mono",style:{fontFamily:"'JetBrains Mono', monospace",color:F!=null?"var(--text-dim)":"var(--text-muted)"},children:F!=null?`${F}¢`:o.jsx("span",{className:"badge bg-blue",style:{fontSize:"0.65rem"},children:"Open"})}),o.jsx("td",{className:"mono",style:{color:"var(--text-dim)"},children:fn(A.open_cost_cents)}),o.jsx("td",{className:"mono font-bold pnl-positive",style:{fontFamily:"'JetBrains Mono', monospace"},children:Rr(A.realized_pnl_cents)}),o.jsx("td",{className:"mono pnl-positive",children:L})]},`${A.ticker}_${A.direction}`)})})]})]}),o.jsxs("div",{className:"card overflow-hidden",style:{padding:0},children:[o.jsxs("div",{className:"flex items-center gap-3 px-4 py-3",style:{background:"rgba(255,92,92,0.06)",borderBottom:"1px solid rgba(255,92,92,0.2)",borderLeft:"4px solid var(--red)"},children:[o.jsx("span",{className:"text-sm font-bold text-red",style:{textShadow:"0 0 10px rgba(255,92,92,0.4)"},children:"Losers"}),o.jsx("span",{className:"badge bg-red",children:k.length}),o.jsx("div",{className:"flex-1"}),o.jsx("span",{className:"mono font-bold pnl-negative",children:Rr(k.reduce((A,L)=>A+L.realized_pnl_cents,0))})]}),o.jsxs("table",{children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"Ticker"}),o.jsx("th",{children:"Market"}),o.jsx("th",{children:"Side"}),o.jsx("th",{children:"Contracts"}),o.jsx("th",{children:"Bought At"}),o.jsx("th",{children:"Sold At"}),o.jsx("th",{children:"Cost"}),o.jsx("th",{children:"Profit"}),o.jsx("th",{children:"ROI"})]})}),o.jsx("tbody",{children:k.map(A=>{var K;const L=A.open_cost_cents>0?`${(A.realized_pnl_cents/A.open_cost_cents*100).toFixed(0)}%`:"—",C=A.ticker.split("").reduce((z,q)=>z+q.charCodeAt(0),0),M=oc(C+300,9,"down"),I=parseInt(A.closed_trades)||0,R=parseInt(A.open_trades)||0,F=I>0&&R===0?Ho(A.avg_entry_price,A.realized_pnl_cents,parseInt(A.open_contracts)||parseInt(A.total_trades)||1):null;return o.jsxs("tr",{className:"position-losing",style:{position:"relative"},children:[o.jsx("td",{children:o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[o.jsx("a",{href:Ro(A.ticker),target:"_blank",rel:"noopener",className:"mono text-sm hover:underline",style:{color:"var(--orange)"},children:A.ticker}),o.jsx(sc,{data:M,width:64,height:26})]})}),o.jsx("td",{className:"text-xs max-w-[192px] truncate",style:{color:"var(--text-dim)"},children:A.title}),o.jsx("td",{children:o.jsx("span",{className:`badge ${Ha(A.direction)}`,children:Ka(A.direction)})}),o.jsx("td",{className:"mono",children:(K=A.open_contracts)==null?void 0:K.toLocaleString()}),o.jsxs("td",{className:"mono",style:{color:"var(--orange)",fontFamily:"'JetBrains Mono', monospace"},children:[A.avg_entry_price,"¢"]}),o.jsx("td",{className:"mono",style:{fontFamily:"'JetBrains Mono', monospace",color:F!=null?"var(--text-dim)":"var(--text-muted)"},children:F!=null?`${F}¢`:o.jsx("span",{className:"badge bg-blue",style:{fontSize:"0.65rem"},children:"Open"})}),o.jsx("td",{className:"mono",style:{color:"var(--text-dim)"},children:fn(A.open_cost_cents)}),o.jsx("td",{className:"mono font-bold pnl-negative",style:{fontFamily:"'JetBrains Mono', monospace"},children:Rr(A.realized_pnl_cents)}),o.jsx("td",{className:"mono pnl-negative",children:L})]},`${A.ticker}_${A.direction}`)})})]})]}),E.length>0&&o.jsxs("div",{className:"card overflow-hidden",style:{padding:0},children:[o.jsxs("div",{className:"flex items-center gap-3 px-4 py-3",style:{background:"var(--surface-el)",borderBottom:"1px solid var(--border)"},children:[o.jsx("span",{className:"text-sm font-bold",style:{color:"var(--text-dim)"},children:"Flat (No Realized P&L)"}),o.jsx("span",{className:"badge bg-orange",children:E.length})]}),o.jsxs("table",{children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"Ticker"}),o.jsx("th",{children:"Market"}),o.jsx("th",{children:"Side"}),o.jsx("th",{children:"Contracts"}),o.jsx("th",{children:"Cost"})]})}),o.jsx("tbody",{children:E.map(A=>{var L;return o.jsxs("tr",{children:[o.jsx("td",{children:o.jsx("a",{href:Ro(A.ticker),target:"_blank",rel:"noopener",className:"mono text-sm hover:underline",style:{color:"var(--orange)"},children:A.ticker})}),o.jsx("td",{className:"text-xs max-w-[192px] truncate",style:{color:"var(--text-dim)"},children:A.title}),o.jsx("td",{children:o.jsx("span",{className:`badge ${Ha(A.direction)}`,children:Ka(A.direction)})}),o.jsx("td",{className:"mono",children:(L=A.open_contracts)==null?void 0:L.toLocaleString()}),o.jsx("td",{className:"mono",style:{color:"var(--text-dim)"},children:fn(A.open_cost_cents)})]},`${A.ticker}_${A.direction}`)})})]})]})]})]})}function yZ(e){return e==="filled"?"bg-green":e==="resting"?"bg-orange":e==="canceled"?"bg-red":"bg-blue"}function Cj({label:e}){return o.jsx("tr",{children:o.jsx("td",{colSpan:20,children:o.jsxs("div",{className:"flex flex-col items-center justify-center py-16 gap-3",children:[o.jsxs("svg",{width:"40",height:"40",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-muted)"},children:[o.jsx("path",{d:"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2"}),o.jsx("rect",{x:"9",y:"3",width:"6",height:"4",rx:"1"}),o.jsx("path",{d:"M9 12h6M9 16h4"})]}),o.jsx("p",{style:{color:"var(--text-muted)",fontFamily:"var(--font-body)",fontSize:"0.875rem"},children:e})]})})})}function gZ(){return o.jsx("div",{className:"flex items-center justify-center h-64",children:o.jsx("div",{className:"w-9 h-9 rounded-full border-2 animate-spin",style:{borderColor:"var(--border)",borderTopColor:"var(--cyan)"}})})}function xZ(){const[e,t]=P.useState([]),[r,n]=P.useState([]),[a,i]=P.useState(!0),[s,l]=P.useState("orders");P.useEffect(()=>{c()},[]);async function c(){i(!0);try{const[f,d]=await Promise.all([me("/kalshi",{action:"get_orders"}),me("/kalshi",{action:"get_fills"})]);t(f.orders||[]),n(d.fills||[])}catch{}i(!1)}async function u(f){try{await me("/kalshi",{action:"cancel_order",order_id:f}),c()}catch{}}return a?o.jsx(gZ,{}):o.jsxs("div",{className:"space-y-6 fade-in",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("div",{className:"flex items-center justify-center w-10 h-10 rounded-xl",style:{background:"var(--cyan-dim)",color:"var(--cyan)"},children:o.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[o.jsx("path",{d:"M7 16V4m0 0L3 8m4-4l4 4"}),o.jsx("path",{d:"M17 8v12m0 0l4-4m-4 4l-4-4"})]})}),o.jsxs("div",{children:[o.jsx("h1",{className:"heading text-3xl",style:{color:"var(--text)"},children:"Orders"}),o.jsxs("p",{className:"section-subtitle mt-0.5",children:[e.length," orders • ",r.length," fills"]})]})]}),o.jsx("button",{onClick:c,className:"btn btn-o btn-sm",children:"Refresh"})]}),o.jsxs("div",{className:"flex rounded-xl p-1 gap-1 w-fit",style:{background:"var(--surface-el)",border:"1px solid var(--border)"},children:[o.jsxs("button",{onClick:()=>l("orders"),className:"btn btn-sm",style:s==="orders"?{background:"var(--cyan)",color:"var(--bg)"}:{background:"transparent",color:"var(--text-muted)",border:"none"},children:["Orders",o.jsx("span",{className:"badge ml-1",style:s==="orders"?{background:"rgba(0,0,0,0.2)",color:"var(--bg)",fontSize:"0.65rem"}:{background:"var(--surface)",color:"var(--text-muted)",fontSize:"0.65rem"},children:e.length})]}),o.jsxs("button",{onClick:()=>l("fills"),className:"btn btn-sm",style:s==="fills"?{background:"var(--cyan)",color:"var(--bg)"}:{background:"transparent",color:"var(--text-muted)",border:"none"},children:["Fills",o.jsx("span",{className:"badge ml-1",style:s==="fills"?{background:"rgba(0,0,0,0.2)",color:"var(--bg)",fontSize:"0.65rem"}:{background:"var(--surface)",color:"var(--text-muted)",fontSize:"0.65rem"},children:r.length})]})]}),s==="orders"&&o.jsx("div",{className:"card overflow-x-auto",style:{padding:0},children:o.jsxs("table",{children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"Ticker"}),o.jsx("th",{children:"Side"}),o.jsx("th",{children:"Action"}),o.jsx("th",{children:"Type"}),o.jsx("th",{children:"Price"}),o.jsx("th",{children:"Qty"}),o.jsx("th",{children:"Filled"}),o.jsx("th",{children:"Status"}),o.jsx("th",{children:"Action"})]})}),o.jsx("tbody",{children:e.length===0?o.jsx(Cj,{label:"No orders yet"}):e.map((f,d)=>o.jsxs("tr",{children:[o.jsx("td",{children:o.jsx("a",{href:`https://kalshi.com/search?query=${encodeURIComponent((f.ticker||"").split("-")[0])}`,target:"_blank",rel:"noopener noreferrer",className:"mono text-xs hover:underline transition",style:{color:"var(--orange)"},children:f.ticker})}),o.jsx("td",{children:o.jsx("span",{className:`badge ${f.side==="yes"?"bg-green":"bg-red"}`,children:(f.side||"").toUpperCase()})}),o.jsx("td",{className:"text-xs",style:{color:"var(--text-dim)"},children:(f.action||"").toUpperCase()}),o.jsx("td",{className:"text-xs",style:{color:"var(--text-muted)"},children:f.type}),o.jsxs("td",{className:"mono",style:{color:"var(--cyan)"},children:[f.yes_price||f.no_price||"—","¢"]}),o.jsx("td",{className:"mono",children:f.count||f.remaining_count||0}),o.jsx("td",{className:"mono text-green",children:f.count-(f.remaining_count||0)}),o.jsx("td",{children:o.jsx("span",{className:`badge ${yZ(f.status)}`,children:f.status})}),o.jsx("td",{children:f.status==="resting"&&o.jsx("button",{onClick:()=>u(f.order_id),className:"btn btn-d btn-sm",children:"Cancel"})})]},d))})]})}),s==="fills"&&o.jsx("div",{className:"card overflow-x-auto",style:{padding:0},children:o.jsxs("table",{children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"Ticker"}),o.jsx("th",{children:"Side"}),o.jsx("th",{children:"Action"}),o.jsx("th",{children:"Price"}),o.jsx("th",{children:"Qty"}),o.jsx("th",{children:"Maker/Taker"}),o.jsx("th",{children:"Time"})]})}),o.jsx("tbody",{children:r.length===0?o.jsx(Cj,{label:"No fills yet"}):r.map((f,d)=>o.jsxs("tr",{children:[o.jsx("td",{children:o.jsx("a",{href:`https://kalshi.com/search?query=${encodeURIComponent((f.ticker||"").split("-")[0])}`,target:"_blank",rel:"noopener noreferrer",className:"mono text-xs hover:underline transition",style:{color:"var(--orange)"},children:f.ticker})}),o.jsx("td",{children:o.jsx("span",{className:`badge ${f.side==="yes"?"bg-green":"bg-red"}`,children:(f.side||"").toUpperCase()})}),o.jsx("td",{className:"text-xs",style:{color:"var(--text-dim)"},children:(f.action||"").toUpperCase()}),o.jsxs("td",{className:"mono",style:{color:"var(--cyan)"},children:[f.yes_price||f.no_price||"—","¢"]}),o.jsx("td",{className:"mono",children:f.count}),o.jsx("td",{children:f.is_taker?o.jsx("span",{className:"badge bg-orange",children:"TAKER"}):o.jsx("span",{className:"badge bg-green",children:"MAKER"})}),o.jsx("td",{className:"mono text-xs",style:{color:"var(--text-muted)"},children:f.created_time?new Date(f.created_time).toLocaleString():"—"})]},d))})]})})]})}function bZ(){const[e,t]=P.useState(null),[r,n]=P.useState(!0);P.useEffect(()=>{a()},[]);async function a(){n(!0);try{const l=await me("/weather",{action:"get_data"});t(l)}catch{}n(!1)}async function i(){n(!0);try{const l=await me("/weather",{action:"fetch_all"});t(l)}catch{}n(!1)}if(r)return o.jsx("div",{className:"flex items-center justify-center h-64",children:o.jsx("div",{className:"w-8 h-8 rounded-full border-2 border-t-transparent animate-spin",style:{borderColor:"var(--cyan)",borderTopColor:"transparent"}})});const s=[{label:"Stations",key:"stations",icon:"📍",color:"var(--cyan)"},{label:"Forecasts",key:"forecasts",icon:"🔮",color:"var(--blue)"},{label:"Observations",key:"observations",icon:"📊",color:"var(--green)"},{label:"Metrics",key:"metrics",icon:"📏",color:"var(--purple)"}];return o.jsxs("div",{className:"space-y-6",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{children:[o.jsxs("h1",{className:"heading text-2xl font-bold flex items-center gap-2",children:[o.jsx("span",{style:{color:"var(--cyan)"},children:"☁"}),o.jsx("span",{className:"gradient-cyan",children:"Weather Markets"})]}),o.jsx("p",{className:"section-subtitle mt-1",children:"NWS settlement data for Ken weather contracts"})]}),o.jsxs("button",{onClick:i,className:"btn btn-p",children:["↻"," Fetch Latest"]})]}),o.jsx("div",{className:"grid grid-cols-4 gap-4",children:s.map(({label:l,key:c,icon:u,color:f})=>o.jsxs("div",{className:"card",children:[o.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[o.jsx("span",{className:"text-lg",children:u}),o.jsx("p",{className:"stat-label",children:l})]}),o.jsx("p",{className:"stat-v",style:{color:f},children:(e==null?void 0:e[c])??"—"})]},l))}),o.jsxs("div",{className:"card",children:[o.jsx("h2",{className:"section-title mb-4",children:"Settlement Rule Reference"}),o.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[o.jsxs("div",{className:"rounded-lg p-4",style:{background:"var(--surface-el)",border:"1px solid var(--border)"},children:[o.jsx("p",{className:"stat-label mb-3",children:"Temperature Contracts"}),o.jsx("ul",{className:"space-y-2",children:["Source: NWS Daily Climate Report (final)","Station: Market-specified (e.g. KORD, KLGA)","Values: Tmax/Tmin in degrees F","Missing data: treated as 0"].map((l,c)=>o.jsxs("li",{className:"flex items-start gap-2 text-xs",style:{color:"var(--text-dim)"},children:[o.jsx("span",{style:{color:"var(--cyan)",flexShrink:0},children:"‣"}),l]},c))})]}),o.jsxs("div",{className:"rounded-lg p-4",style:{background:"var(--surface-el)",border:"1px solid var(--border)"},children:[o.jsx("p",{className:"stat-label mb-3",children:"Precipitation Contracts"}),o.jsx("ul",{className:"space-y-2",children:["Source: NWS Daily Climate Report (first complete)","Trace: counted as 0.00 inches","Missing: counted as 0.00 inches","Revisions: do NOT change settlement"].map((l,c)=>o.jsxs("li",{className:"flex items-start gap-2 text-xs",style:{color:"var(--text-dim)"},children:[o.jsx("span",{style:{color:"var(--blue)",flexShrink:0},children:"‣"}),l]},c))})]})]})]}),((e==null?void 0:e.outcomes)||[]).length>0&&o.jsxs("div",{className:"card overflow-x-auto",children:[o.jsx("h2",{className:"section-title mb-4",children:"Recent Observations"}),o.jsxs("table",{children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"Station"}),o.jsx("th",{children:"Metric"}),o.jsx("th",{children:"Value"}),o.jsx("th",{children:"Source"}),o.jsx("th",{children:"Date"})]})}),o.jsx("tbody",{children:e.outcomes.map((l,c)=>o.jsxs("tr",{className:"fade-in",children:[o.jsx("td",{className:"mono text-sm",style:{color:"var(--cyan)"},children:l.station_id}),o.jsx("td",{children:o.jsx("span",{className:"badge bg-blue",children:l.metric})}),o.jsxs("td",{className:"mono font-bold",style:{color:"var(--text)"},children:[l.value,l.units]}),o.jsx("td",{className:"text-xs",style:{color:"var(--text-muted)"},children:l.source}),o.jsx("td",{className:"text-xs mono",style:{color:"var(--text-muted)"},children:l.period_end})]},c))})]})]}),((e==null?void 0:e.outcomes)||[]).length===0&&o.jsxs("div",{className:"card text-center py-12",style:{border:"1px dashed var(--border)"},children:[o.jsx("p",{className:"text-4xl mb-3",children:"⛅"}),o.jsx("p",{className:"heading text-sm font-semibold mb-1",style:{color:"var(--text-dim)"},children:"No observations loaded"}),o.jsx("p",{className:"text-xs mb-4",style:{color:"var(--text-muted)"},children:'Click "Fetch Latest" to pull current NWS settlement data'}),o.jsx("button",{onClick:i,className:"btn btn-p btn-sm",children:"Fetch Latest"})]})]})}const jZ={aggressive:"#ef4444",conservative:"#3b82f6",weather:"#06b6d4",momentum:"#f59e0b",contrarian:"#a855f7",ai_enhanced:"#ec4899",mc_validated:"#8b5cf6",scalper:"#10b981",patient:"#6366f1",random:"#f97316",penny_pincher:"#84cc16",spray_pray:"#14b8a6",nickel_slots:"#eab308",degen_lite:"#e11d48",politics_junkie:"#7c3aed",double_down:"#dc2626",volatility_rider:"#0ea5e9",whale:"#1d4ed8",yolo:"#be123c",full_send:"#ea580c",kelly_criterion:"#4f46e5",sharpe_sniper:"#059669",bayesian_blend:"#7c3aed",ensemble_lock:"#0891b2",mean_revert:"#4338ca",info_ratio:"#b45309",anti_fomo:"#64748b",nightcrawler:"#334155",heatseeker:"#dc2626",quant_core:"#2563eb"},wZ="#F7931A";function ZO(e){return e.startsWith("etf_")?wZ:jZ[e]||"#6b7280"}function SZ({won:e,lost:t,total:r}){if(!r)return o.jsx("span",{className:"text-xs",style:{color:"var(--text-muted)"},children:"no trades"});const n=e/r*100,a=t/r*100;return o.jsxs("div",{className:"flex h-1.5 rounded-full overflow-hidden w-full",style:{background:"var(--border)"},children:[e>0&&o.jsx("div",{style:{width:`${n}%`,background:"var(--green)"}}),t>0&&o.jsx("div",{style:{width:`${a}%`,background:"var(--red)"}})]})}function _Z({streak:e}){if(e===0)return o.jsx("span",{style:{color:"var(--text-muted)",fontSize:"0.7rem"},children:"—"});const t=e>0;return o.jsxs("span",{className:"mono font-bold text-xs",style:{color:t?"var(--green)":"var(--red)"},children:[t?"+":"",e]})}const kZ=e=>e==="BUY_YES"?"YES":"NO",OZ=e=>e==="BUY_YES"?"bg-green":"bg-red",NZ=e=>e>=0?"var(--green)":"var(--red)";function Ej({trades:e,loading:t}){return t?o.jsx("div",{className:"flex justify-center py-4",children:o.jsx("div",{className:"w-5 h-5 rounded-full border-2 animate-spin",style:{borderColor:"var(--border)",borderTopColor:"var(--cyan)"}})}):!e||e.length===0?o.jsx("p",{className:"text-xs text-center py-3",style:{color:"var(--text-muted)"},children:"No trades found for this portfolio"}):o.jsx("div",{className:"overflow-x-auto",style:{maxHeight:240,overflowY:"auto"},children:o.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:"0.7rem"},children:[o.jsx("thead",{children:o.jsx("tr",{style:{borderBottom:"1px solid var(--border)"},children:["Market","Dir","Entry","Qty","Cost","P&L","Status"].map(r=>o.jsx("th",{style:{padding:"4px 6px",textAlign:"left",color:"var(--text-muted)",fontWeight:600,fontFamily:"var(--font-body)",fontSize:"0.65rem",whiteSpace:"nowrap"},children:r},r))})}),o.jsx("tbody",{children:e.map((r,n)=>{const a=parseInt(r.pnl_cents)||0,i=parseInt(r.cost_cents)||0,s=parseInt(r.entry_price_cents)||0,l=parseInt(r.contracts)||0,c=r.status||"open";return o.jsxs("tr",{style:{borderBottom:"1px solid var(--border)",background:n%2===0?"transparent":"rgba(255,255,255,0.01)"},children:[o.jsxs("td",{style:{padding:"4px 6px",maxWidth:140,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontFamily:"var(--font-body)"},title:r.market_title||r.market_id,children:[(r.market_title||r.market_id||"").substring(0,28),(r.market_title||r.market_id||"").length>28?"...":""]}),o.jsx("td",{style:{padding:"4px 6px"},children:o.jsx("span",{className:`badge ${OZ(r.direction)}`,style:{fontSize:"0.6rem",padding:"1px 5px"},children:kZ(r.direction)})}),o.jsxs("td",{style:{padding:"4px 6px",fontFamily:"'JetBrains Mono', monospace",color:"var(--orange)"},children:[s,"¢"]}),o.jsx("td",{style:{padding:"4px 6px",fontFamily:"'JetBrains Mono', monospace",color:"var(--text-dim)"},children:l}),o.jsxs("td",{style:{padding:"4px 6px",fontFamily:"'JetBrains Mono', monospace",color:"var(--text-dim)"},children:["$",(i/100).toFixed(2)]}),o.jsx("td",{style:{padding:"4px 6px",fontFamily:"'JetBrains Mono', monospace",fontWeight:700,color:NZ(a)},children:a!==0?`${a>=0?"+":""}$${(a/100).toFixed(2)}`:"—"}),o.jsx("td",{style:{padding:"4px 6px"},children:o.jsx("span",{className:`badge ${c==="open"?"bg-blue":c==="closed"?"bg-green":"bg-orange"}`,style:{fontSize:"0.6rem",padding:"1px 5px"},children:c})})]},r.id||n)})})]})})}function PZ({p:e,dailyPnl:t,expanded:r,onToggle:n,pfTrades:a,pfTradesLoading:i}){const s=(e.total_returned_cents-e.total_invested_cents)/100,l=e.trades_won+e.trades_lost+e.trades_expired,c=e.total_invested_cents/100,u=e.total_returned_cents/100,f=l>0,d=ZO(e.strategy),h=Math.min(100,e.daily_budget_cents/Math.max(1,1e5)*100);return o.jsxs("div",{className:"card cursor-pointer transition-all",style:r?{borderColor:"var(--cyan)",boxShadow:"0 0 20px var(--cyan-glow)",opacity:1}:f?{opacity:1}:{opacity:.5},onClick:n,children:[o.jsxs("div",{className:"flex items-center justify-between mb-2",children:[o.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[o.jsx("div",{className:"w-2.5 h-2.5 rounded-full flex-shrink-0",style:{background:d}}),o.jsx("span",{className:"heading font-semibold text-sm truncate",style:{color:"var(--text)"},children:e.name}),o.jsxs("span",{className:"mono text-xs flex-shrink-0",style:{color:"var(--text-muted)"},children:["#",e.id]}),l>0&&o.jsxs("span",{className:"text-xs flex-shrink-0 px-1.5 py-0.5 rounded",style:{background:"var(--surface-el)",color:"var(--text-muted)",fontSize:"0.65rem"},children:[l," trade",l!==1?"s":""]})]}),o.jsxs("span",{className:"mono text-sm font-bold flex-shrink-0 ml-2",style:{color:s>=0?"var(--green)":"var(--red)"},children:[s>=0?"+":"","$",s.toFixed(2)]})]}),o.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[o.jsx("span",{className:"mono px-1.5 py-0.5 rounded text-xs flex-shrink-0",style:{background:`${d}15`,color:d,border:`1px solid ${d}30`},children:e.strategy}),o.jsx(_Z,{streak:e.streak}),o.jsx("div",{className:"flex-1"}),o.jsx("span",{className:"badge flex-shrink-0",style:f?{background:"var(--green-dim)",color:"var(--green)"}:{background:"var(--border)",color:"var(--text-muted)"},children:f?"Active":"Dormant"})]}),o.jsxs("div",{className:"mb-3",children:[o.jsx(SZ,{won:e.trades_won,lost:e.trades_lost,total:l}),o.jsxs("div",{className:"flex justify-between mt-1",children:[o.jsxs("span",{className:"text-xs",style:{color:"var(--text-muted)"},children:[e.trades_won,"W / ",e.trades_lost,"L"]}),o.jsxs("span",{className:"mono text-xs",style:{color:"var(--text-dim)"},children:[e.win_rate||0,"%"]})]})]}),o.jsxs("div",{className:"mb-3",children:[o.jsxs("div",{className:"flex justify-between text-xs mb-1",style:{color:"var(--text-muted)"},children:[o.jsx("span",{children:"Daily Budget"}),o.jsxs("span",{className:"mono",style:{color:"var(--text-dim)"},children:["$",(e.daily_budget_cents/100).toFixed(2)]})]}),o.jsx("div",{className:"progress-bar",children:o.jsx("div",{className:"progress-fill",style:{width:`${h}%`,background:`linear-gradient(90deg, ${d}, ${d}99)`}})})]}),o.jsxs("div",{className:"grid grid-cols-2 gap-x-3 gap-y-1",style:{fontSize:"0.7rem"},children:[o.jsxs("div",{className:"flex justify-between",children:[o.jsx("span",{style:{color:"var(--text-muted)"},children:"Invested"}),o.jsxs("span",{className:"mono",style:{color:"var(--text-dim)"},children:["$",c.toFixed(2)]})]}),o.jsxs("div",{className:"flex justify-between",children:[o.jsx("span",{style:{color:"var(--text-muted)"},children:"Returned"}),o.jsxs("span",{className:"mono",style:{color:"var(--text-dim)"},children:["$",u.toFixed(2)]})]}),o.jsxs("div",{className:"flex justify-between",children:[o.jsx("span",{style:{color:"var(--text-muted)"},children:"Trades Today"}),o.jsx("span",{className:"mono",style:{color:"var(--cyan)"},children:e.trades_today})]}),o.jsxs("div",{className:"flex justify-between",children:[o.jsx("span",{style:{color:"var(--text-muted)"},children:"Total"}),o.jsx("span",{className:"mono",style:{color:"var(--text-dim)"},children:l})]})]}),r&&t&&t.length>0&&o.jsxs("div",{className:"mt-3 pt-3",style:{borderTop:"1px solid var(--border)"},children:[o.jsx("p",{className:"text-xs mb-1",style:{color:"var(--text-muted)"},children:"Cumulative P&L"}),o.jsx(tr,{width:"100%",height:80,children:o.jsxs(Jy,{data:t,children:[o.jsx(or,{dataKey:"date",hide:!0}),o.jsx(sr,{hide:!0,domain:["dataMin","dataMax"]}),o.jsx(Ge,{contentStyle:{background:"var(--surface-el)",border:"1px solid var(--border)",borderRadius:8,fontSize:11,fontFamily:"var(--font-mono)"},formatter:p=>[`$${(p/100).toFixed(2)}`,"P&L"],labelFormatter:p=>p}),o.jsx(Lr,{type:"monotone",dataKey:"cumulative",stroke:d,fill:d,fillOpacity:.1,strokeWidth:1.5,dot:!1})]})}),e.description&&o.jsx("p",{className:"text-xs mt-1",style:{color:"var(--text-muted)"},children:e.description}),o.jsxs("div",{className:"mt-3 pt-3",style:{borderTop:"1px solid var(--border)"},children:[o.jsx("p",{className:"text-xs mb-2 font-semibold",style:{color:"var(--cyan)"},children:"Individual Trades"}),o.jsx(Ej,{trades:a,loading:i})]})]}),r&&(!t||t.length===0)&&o.jsxs("div",{className:"mt-3 pt-3",style:{borderTop:"1px solid var(--border)"},children:[o.jsx("p",{className:"text-xs mb-2 font-semibold",style:{color:"var(--cyan)"},children:"Individual Trades"}),o.jsx(Ej,{trades:a,loading:i})]})]})}function AZ(){return o.jsx("div",{className:"flex items-center justify-center h-64",children:o.jsx("div",{className:"w-9 h-9 rounded-full border-2 animate-spin",style:{borderColor:"var(--border)",borderTopColor:"var(--cyan)"}})})}function CZ(){const[e,t]=P.useState([]),[r,n]=P.useState({}),[a,i]=P.useState(!0),[s,l]=P.useState("all"),[c,u]=P.useState("pnl"),[f,d]=P.useState(null),[h,p]=P.useState({}),[g,y]=P.useState(null);P.useEffect(()=>{b()},[]);async function b(){try{const[N,k]=await Promise.all([Oe("/portfolios"),Oe("/portfolio-trades?include_history=true").catch(()=>({}))]);t(N||[]),k!=null&&k.byPortfolio&&n(k.byPortfolio)}catch{}i(!1)}async function v(N){if(!h[N]){y(N);try{const k=await Oe(`/portfolio-trades?portfolio_id=${N}`);p(E=>({...E,[N]:Array.isArray(k)?k:[]}))}catch{p(k=>({...k,[N]:[]}))}y(null)}}function m(N){f===N?d(null):(d(N),v(N))}const x=P.useMemo(()=>{let N=[...e];return s==="active"&&(N=N.filter(k=>k.trades_won+k.trades_lost>0)),s==="dormant"&&(N=N.filter(k=>k.trades_won+k.trades_lost===0)),s==="etf"&&(N=N.filter(k=>k.strategy.startsWith("etf_"))),s==="core"&&(N=N.filter(k=>!k.strategy.startsWith("etf_"))),c==="pnl"&&N.sort((k,E)=>E.total_returned_cents-E.total_invested_cents-(k.total_returned_cents-k.total_invested_cents)),c==="winrate"&&N.sort((k,E)=>(E.win_rate||0)-(k.win_rate||0)),c==="invested"&&N.sort((k,E)=>E.total_invested_cents-k.total_invested_cents),c==="name"&&N.sort((k,E)=>k.name.localeCompare(E.name)),c==="id"&&N.sort((k,E)=>k.id-E.id),N},[e,s,c]),S=P.useMemo(()=>{const N=e.reduce((M,I)=>M+I.total_invested_cents,0),k=e.reduce((M,I)=>M+I.total_returned_cents,0),E=e.reduce((M,I)=>M+I.trades_won,0),T=e.reduce((M,I)=>M+I.trades_lost,0),D=e.filter(M=>M.trades_won+M.trades_lost>0).length,A=e.length-D,L=[...e].sort((M,I)=>I.total_returned_cents-I.total_invested_cents-(M.total_returned_cents-M.total_invested_cents))[0],C=[...e].sort((M,I)=>M.total_returned_cents-M.total_invested_cents-(I.total_returned_cents-I.total_invested_cents))[0];return{totalInvested:N,totalReturned:k,totalWins:E,totalLosses:T,active:D,dormant:A,bestPf:L,worstPf:C}},[e]),j=P.useMemo(()=>[...e].map(N=>({name:N.name,pnl:(N.total_returned_cents-N.total_invested_cents)/100,strategy:N.strategy})).filter(N=>N.pnl!==0).sort((N,k)=>k.pnl-N.pnl).slice(0,20),[e]),w=P.useMemo(()=>{const N={};return e.forEach(k=>{const E=k.strategy.startsWith("etf_")?"ETF Baskets":k.strategy;N[E]||(N[E]={name:E,value:0}),N[E].value+=k.total_invested_cents}),Object.values(N).filter(k=>k.value>0).sort((k,E)=>E.value-k.value)},[e]);if(a)return o.jsx(AZ,{});const _=(S.totalReturned-S.totalInvested)/100,O=S.totalWins+S.totalLosses;return o.jsxs("div",{className:"space-y-6 fade-in",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{children:[o.jsxs("h1",{className:"heading text-3xl",style:{color:"var(--text)"},children:["Portfauxlios",o.jsx("span",{className:"badge bg-cyan ml-3 align-middle text-base",children:e.length})]}),o.jsxs("p",{className:"section-subtitle mt-1",children:["All ",e.length," portfolios — performance, P&L, and strategy breakdown"]})]}),o.jsx("button",{onClick:b,className:"btn btn-o btn-sm",children:"Refresh"})]}),o.jsx("div",{className:"grid grid-cols-3 md:grid-cols-6 gap-3",children:[{label:"Total P&L",value:`${_>=0?"+":""}$${_.toFixed(2)}`,color:_>=0?"var(--green)":"var(--red)"},{label:"Invested",value:`$${(S.totalInvested/100).toFixed(2)}`,color:"var(--orange)"},{label:"Returned",value:`$${(S.totalReturned/100).toFixed(2)}`,color:"var(--blue)"},{label:"Win Rate",value:O?`${(S.totalWins/O*100).toFixed(1)}%`:"0%",color:"var(--purple)"},{label:"Active",value:S.active,color:"var(--green)"},{label:"Dormant",value:S.dormant,color:"var(--text-muted)"}].map(N=>o.jsxs("div",{className:"card text-center",style:{padding:"1rem"},children:[o.jsx("div",{className:"stat-v",style:{color:N.color,fontSize:"1.4rem"},children:N.value}),o.jsx("div",{className:"stat-label mt-1",children:N.label})]},N.label))}),o.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[o.jsxs("div",{className:"card md:col-span-2",children:[o.jsx("h2",{className:"heading text-sm mb-3",style:{color:"var(--text-dim)"},children:"P&L by Portfolio"}),j.length>0?o.jsx(tr,{width:"100%",height:220,children:o.jsxs(_l,{data:j,margin:{left:10,right:10},children:[o.jsx(or,{dataKey:"name",tick:{fill:"var(--text-muted)",fontSize:9,fontFamily:"var(--font-mono)"},angle:-45,textAnchor:"end",height:60}),o.jsx(sr,{tick:{fill:"var(--text-muted)",fontSize:10,fontFamily:"var(--font-mono)"},tickFormatter:N=>`$${N}`}),o.jsx(Ge,{contentStyle:{background:"var(--surface-el)",border:"1px solid var(--border)",borderRadius:8,fontSize:11,fontFamily:"var(--font-mono)"},formatter:N=>[`$${N.toFixed(2)}`,"P&L"]}),o.jsx(nr,{dataKey:"pnl",radius:[4,4,0,0],children:j.map((N,k)=>o.jsx(xr,{fill:N.pnl>=0?"var(--green)":"var(--red)",fillOpacity:.8},k))})]})}):o.jsx("div",{className:"text-center py-10 text-sm",style:{color:"var(--text-muted)"},children:"No P&L data yet"})]}),o.jsxs("div",{className:"card",children:[o.jsx("h2",{className:"heading text-sm mb-3",style:{color:"var(--text-dim)"},children:"Capital Allocation"}),w.length>0?o.jsx(tr,{width:"100%",height:220,children:o.jsxs(Qy,{children:[o.jsx(wr,{data:w,dataKey:"value",nameKey:"name",cx:"50%",cy:"50%",innerRadius:40,outerRadius:75,paddingAngle:2,strokeWidth:0,children:w.map((N,k)=>o.jsx(xr,{fill:ZO(N.name==="ETF Baskets"?"etf_":N.name),fillOpacity:.85},k))}),o.jsx(Ge,{contentStyle:{background:"var(--surface-el)",border:"1px solid var(--border)",borderRadius:8,fontSize:11,fontFamily:"var(--font-mono)"},formatter:N=>[`$${(N/100).toFixed(2)}`,"Invested"]})]})}):o.jsx("div",{className:"text-center py-10 text-sm",style:{color:"var(--text-muted)"},children:"No allocations yet"})]})]}),o.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[S.bestPf&&o.jsxs("div",{className:"card",style:{borderColor:"rgba(0,195,137,0.25)",background:"var(--green-dim)"},children:[o.jsx("div",{className:"flex items-center gap-2 mb-2",children:o.jsx("span",{className:"badge",style:{background:"var(--green-dim)",color:"var(--green)"},children:"Best Performer"})}),o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("span",{className:"heading font-bold",style:{color:"var(--text)"},children:S.bestPf.name}),o.jsxs("span",{className:"mono font-bold text-green",children:["+$",((S.bestPf.total_returned_cents-S.bestPf.total_invested_cents)/100).toFixed(2)]})]}),o.jsxs("span",{className:"text-xs",style:{color:"var(--text-muted)"},children:[S.bestPf.strategy," — ",S.bestPf.win_rate||0,"% win rate"]})]}),S.worstPf&&o.jsxs("div",{className:"card",style:{borderColor:"rgba(255,92,92,0.25)",background:"var(--red-dim)"},children:[o.jsx("div",{className:"flex items-center gap-2 mb-2",children:o.jsx("span",{className:"badge",style:{background:"var(--red-dim)",color:"var(--red)"},children:"Worst Performer"})}),o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("span",{className:"heading font-bold",style:{color:"var(--text)"},children:S.worstPf.name}),o.jsxs("span",{className:"mono font-bold text-red",children:["$",((S.worstPf.total_returned_cents-S.worstPf.total_invested_cents)/100).toFixed(2)]})]}),o.jsxs("span",{className:"text-xs",style:{color:"var(--text-muted)"},children:[S.worstPf.strategy," — ",S.worstPf.win_rate||0,"% win rate"]})]})]}),o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[o.jsx("div",{className:"flex flex-wrap gap-2",children:["all","active","dormant","etf","core"].map(N=>o.jsx("button",{onClick:()=>l(N),className:"px-3 py-1.5 rounded-lg text-xs font-semibold transition",style:s===N?{background:"var(--cyan-dim)",color:"var(--cyan)",border:"1px solid rgba(0,240,255,0.3)"}:{background:"var(--surface-el)",color:"var(--text-muted)",border:"1px solid var(--border)"},children:N==="all"?`All (${e.length})`:N==="active"?`Active (${S.active})`:N==="dormant"?`Dormant (${S.dormant})`:N==="etf"?"ETF Baskets":"Core Strategies"},N))}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-xs",style:{color:"var(--text-muted)"},children:"Sort:"}),["pnl","winrate","invested","name","id"].map(N=>o.jsx("button",{onClick:()=>u(N),className:"px-2 py-1 rounded text-xs font-medium transition",style:c===N?{color:"var(--cyan)",background:"var(--cyan-dim)"}:{color:"var(--text-muted)"},children:N==="pnl"?"P&L":N==="winrate"?"Win%":N.charAt(0).toUpperCase()+N.slice(1)},N))]})]}),x.length===0?o.jsx("div",{className:"text-center py-16 text-sm",style:{color:"var(--text-muted)"},children:"No portfolios match this filter"}):o.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3",children:x.map(N=>{var k;return o.jsx(PZ,{p:N,dailyPnl:((k=r[N.id])==null?void 0:k.daily)||[],expanded:f===N.id,onToggle:()=>m(N.id),pfTrades:h[N.id]||null,pfTradesLoading:g===N.id},N.id)})})]})}const EZ=[{label:"30s",ms:3e4},{label:"1m",ms:6e4},{label:"2m",ms:12e4},{label:"5m",ms:3e5},{label:"8m",ms:48e4},{label:"10m",ms:6e5},{label:"15m",ms:9e5},{label:"30m",ms:18e5},{label:"60m",ms:36e5}];function $Z(e){return e>=36e5?`${e/36e5}h`:e>=6e4?`${e/6e4}m`:`${e/1e3}s`}function TZ(){return o.jsxs("svg",{width:"22",height:"22",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[o.jsx("circle",{cx:"12",cy:"12",r:"3"}),o.jsx("path",{d:"M19.4 15a1.65 1.65 0 00.33 1.82l.06.06a2 2 0 010 2.83 2 2 0 01-2.83 0l-.06-.06a1.65 1.65 0 00-1.82-.33 1.65 1.65 0 00-1 1.51V21a2 2 0 01-4 0v-.09A1.65 1.65 0 009 19.4a1.65 1.65 0 00-1.82.33l-.06.06a2 2 0 01-2.83-2.83l.06-.06A1.65 1.65 0 004.68 15a1.65 1.65 0 00-1.51-1H3a2 2 0 010-4h.09A1.65 1.65 0 004.6 9a1.65 1.65 0 00-.33-1.82l-.06-.06a2 2 0 012.83-2.83l.06.06A1.65 1.65 0 009 4.68a1.65 1.65 0 001-1.51V3a2 2 0 014 0v.09a1.65 1.65 0 001 1.51 1.65 1.65 0 001.82-.33l.06-.06a2 2 0 012.83 2.83l-.06.06A1.65 1.65 0 0019.4 9a1.65 1.65 0 001.51 1H21a2 2 0 010 4h-.09a1.65 1.65 0 00-1.51 1z"})]})}function yh({title:e,children:t}){return o.jsxs("div",{className:"card space-y-4",children:[o.jsx("h2",{className:"heading font-semibold text-base pb-3",style:{color:"var(--text)",borderBottom:"1px solid var(--border)"},children:e}),t]})}function Hm({label:e,description:t,children:r}){return o.jsxs("div",{className:"flex items-start justify-between gap-4",children:[o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsx("p",{className:"text-sm font-medium",style:{color:"var(--text)"},children:e}),t&&o.jsx("p",{className:"text-xs mt-0.5",style:{color:"var(--text-muted)"},children:t})]}),o.jsx("div",{className:"flex-shrink-0",children:r})]})}function lc({label:e,value:t,onChange:r,description:n}){return o.jsxs("div",{className:"space-y-2",children:[o.jsx(Hm,{label:e,description:n,children:o.jsx("span",{className:"mono font-bold text-lg",style:{color:"var(--cyan)"},children:$Z(t)})}),o.jsx("div",{className:"flex flex-wrap gap-1.5",children:EZ.map(a=>o.jsx("button",{onClick:()=>r(a.ms),className:"px-2.5 py-1 rounded text-xs font-medium transition",style:t===a.ms?{background:"var(--cyan-dim)",color:"var(--cyan)",border:"1px solid rgba(0,240,255,0.4)"}:{background:"var(--surface-el)",color:"var(--text-muted)",border:"1px solid var(--border)"},children:a.label},a.ms))})]})}function $j({msg:e}){return e?o.jsx("p",{className:"text-xs px-3 py-2 rounded-lg",style:e.type==="ok"?{background:"var(--green-dim)",color:"var(--green)"}:{background:"var(--red-dim)",color:"var(--red)"},children:e.text}):null}function MZ(){return o.jsx("div",{className:"flex items-center justify-center h-64",children:o.jsx("div",{className:"w-9 h-9 rounded-full border-2 animate-spin",style:{borderColor:"var(--border)",borderTopColor:"var(--cyan)"}})})}function IZ(){const[e,t]=P.useState(null),[r,n]=P.useState(!0),[a,i]=P.useState(""),[s,l]=P.useState(""),[c,u]=P.useState("demo"),[f,d]=P.useState(!1),[h,p]=P.useState(null),[g,y]=P.useState(null),[b,v]=P.useState(null),[m,x]=P.useState(!1);P.useEffect(()=>{S(),j();const k=setInterval(j,3e4);return()=>clearInterval(k)},[]);async function S(){try{const k=await me("/kalshi",{action:"status"});t(k),k.env&&u(k.env)}catch{}n(!1)}async function j(){try{const k=await Oe("/scan-config");y(k)}catch{}}async function w(k,E){x(!0),v(null);try{const T=await Oe("/scan-config",{method:"POST",body:JSON.stringify({[k]:E})});T.success?(y(T),v({type:"ok",text:`Updated ${k.replace(/_/g," ")}`})):v({type:"err",text:T.error||"Failed"})}catch{v({type:"err",text:"Connection error"})}x(!1),setTimeout(()=>v(null),3e3)}async function _(){d(!0),p(null);try{const k=await me("/kalshi",{action:"save_keys",api_key:a,private_key:s,env:c});k.success?(p({type:"ok",text:"Keys saved and connected"}),S(),i(""),l("")):p({type:"err",text:k.error||"Failed"})}catch{p({type:"err",text:"Connection error"})}d(!1)}async function O(){try{await me("/kalshi",{action:"disconnect"}),S()}catch{}}async function N(){p(null);try{const k=await me("/kalshi",{action:"test_connection"});p({type:k.success?"ok":"err",text:k.success?`Connected. Exchange: ${k.exchange_status}`:"Connection failed"})}catch{p({type:"err",text:"Connection error"})}}return r?o.jsx(MZ,{}):o.jsxs("div",{className:"space-y-6 fade-in",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("div",{className:"flex items-center justify-center w-10 h-10 rounded-xl",style:{background:"var(--cyan-dim)",color:"var(--cyan)"},children:o.jsx(TZ,{})}),o.jsxs("div",{children:[o.jsx("h1",{className:"heading text-3xl",style:{color:"var(--text)"},children:"Settings"}),o.jsx("p",{className:"section-subtitle mt-0.5",children:"Configure scan pipeline, API keys, and risk parameters"})]})]}),g&&o.jsxs(yh,{title:"Scan & Pipeline Configuration",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("p",{className:"text-xs",style:{color:"var(--text-muted)"},children:"Adjust intervals, thresholds, and risk parameters in real-time"}),m&&o.jsx("span",{className:"text-xs animate-pulse",style:{color:"var(--orange)"},children:"Saving..."})]}),o.jsx($j,{msg:b}),o.jsxs("div",{className:"flex items-center gap-3 px-4 py-3 rounded-xl",style:{background:"var(--surface-el)",border:"1px solid var(--border)"},children:[o.jsx("span",{className:"stat-label",children:"Cached Markets"}),o.jsx("span",{className:"mono font-bold text-xl",style:{color:"var(--cyan)"},children:g.cached_markets||0}),o.jsx("div",{className:"w-2 h-2 rounded-full pulse-cyan ml-auto",style:{background:"var(--cyan)"}})]}),o.jsxs("div",{className:"space-y-5 pt-2 pb-1",style:{borderTop:"1px solid var(--border)"},children:[o.jsx("h3",{className:"text-sm font-semibold pt-3",style:{color:"var(--text-dim)"},children:"Pipeline Intervals"}),o.jsx(lc,{label:"Market Scan",description:"How often to fetch and analyze all active Kalshi markets",value:g.scan_interval_ms,onChange:k=>w("scan_interval_ms",k)}),o.jsx(lc,{label:"Signal Pipeline",description:"News sentiment + probability + Monte Carlo signal generation",value:g.signal_pipeline_ms,onChange:k=>w("signal_pipeline_ms",k)}),o.jsx(lc,{label:"Intelligence Sweep",description:"Reddit, news feeds, Bluesky, Mastodon, Lemmy + 20 more sources",value:g.reddit_interval_ms,onChange:k=>w("reddit_interval_ms",k)}),o.jsx(lc,{label:"Trade Resolution",description:"Take-profit / stop-loss check on open portfolio positions",value:g.resolve_interval_ms,onChange:k=>w("resolve_interval_ms",k)})]}),o.jsxs("div",{className:"space-y-5",style:{borderTop:"1px solid var(--border)",paddingTop:"1rem"},children:[o.jsx("h3",{className:"text-sm font-semibold",style:{color:"var(--text-dim)"},children:"Risk Parameters"}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Hm,{label:"Min Edge Threshold",description:"Minimum statistical edge required to approve a signal",children:o.jsxs("span",{className:"mono font-bold text-lg",style:{color:"var(--cyan)"},children:[(g.min_edge_threshold*100).toFixed(1),"%"]})}),o.jsx("div",{className:"flex flex-wrap gap-1.5",children:[.01,.02,.03,.05,.08,.1,.15,.2].map(k=>o.jsxs("button",{onClick:()=>w("min_edge_threshold",k),className:"px-2.5 py-1 rounded text-xs font-medium transition",style:Math.abs(g.min_edge_threshold-k)<.001?{background:"var(--cyan-dim)",color:"var(--cyan)",border:"1px solid rgba(0,240,255,0.4)"}:{background:"var(--surface-el)",color:"var(--text-muted)",border:"1px solid var(--border)"},children:[(k*100).toFixed(0),"%"]},k))})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Hm,{label:"Min Liquidity (24h Vol)",description:"Minimum 24-hour trading volume to consider a market",children:o.jsx("span",{className:"mono font-bold text-lg",style:{color:"var(--cyan)"},children:g.min_liquidity})}),o.jsx("div",{className:"flex flex-wrap gap-1.5",children:[0,10,25,50,100,250,500,1e3].map(k=>o.jsx("button",{onClick:()=>w("min_liquidity",k),className:"px-2.5 py-1 rounded text-xs font-medium transition",style:g.min_liquidity===k?{background:"var(--cyan-dim)",color:"var(--cyan)",border:"1px solid rgba(0,240,255,0.4)"}:{background:"var(--surface-el)",color:"var(--text-muted)",border:"1px solid var(--border)"},children:k===0?"None":k},k))})]})]})]}),o.jsxs(yh,{title:"API Configuration",children:[o.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[o.jsx("div",{className:`w-2.5 h-2.5 rounded-full ${e!=null&&e.connected?"pulse-cyan":""}`,style:{background:e!=null&&e.connected?"var(--cyan)":"var(--text-muted)"}}),o.jsx("span",{className:"text-sm font-semibold",style:{color:e!=null&&e.connected?"var(--cyan)":"var(--text-muted)"},children:e!=null&&e.connected?"Connected":"Not Connected"})]}),e!=null&&e.connected?o.jsxs("div",{className:"space-y-3",children:[o.jsxs("div",{className:"rounded-xl px-4 py-3 space-y-2",style:{background:"var(--surface-el)",border:"1px solid var(--border)"},children:[o.jsxs("div",{className:"flex justify-between text-sm",children:[o.jsx("span",{style:{color:"var(--text-muted)"},children:"API Key"}),o.jsx("span",{className:"mono",style:{color:"var(--text)"},children:e.api_key_masked||"•••••"})]}),o.jsxs("div",{className:"flex justify-between text-sm",children:[o.jsx("span",{style:{color:"var(--text-muted)"},children:"Environment"}),o.jsx("span",{className:"mono font-bold",style:{color:e.env==="prod"?"var(--green)":"var(--orange)"},children:(e.env||"demo").toUpperCase()})]})]}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx("button",{onClick:N,className:"btn btn-o btn-sm",children:"Test Connection"}),o.jsx("button",{onClick:O,className:"btn btn-d btn-sm",children:"Disconnect"})]})]}):o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"flex gap-2",children:[o.jsx("button",{onClick:()=>u("demo"),className:"flex-1 py-2 rounded-xl text-sm font-semibold transition",style:c==="demo"?{background:"var(--orange-dim)",color:"var(--orange)",border:"1px solid rgba(247,147,26,0.4)"}:{background:"var(--surface-el)",color:"var(--text-muted)",border:"1px solid var(--border)"},children:"Demo"}),o.jsx("button",{onClick:()=>u("prod"),className:"flex-1 py-2 rounded-xl text-sm font-semibold transition",style:c==="prod"?{background:"var(--green-dim)",color:"var(--green)",border:"1px solid rgba(0,195,137,0.4)"}:{background:"var(--surface-el)",color:"var(--text-muted)",border:"1px solid var(--border)"},children:"Production"})]}),o.jsxs("div",{children:[o.jsx("label",{className:"stat-label block mb-1.5",children:"API Key ID"}),o.jsx("input",{type:"text",value:a,onChange:k=>i(k.target.value),placeholder:"Your API key",className:"input mono"})]}),o.jsxs("div",{children:[o.jsx("label",{className:"stat-label block mb-1.5",children:"Private Key (PEM)"}),o.jsx("textarea",{value:s,onChange:k=>l(k.target.value),placeholder:"-----BEGIN RSA PRIVATE KEY-----",rows:4,className:"input mono text-xs",style:{resize:"vertical"}})]}),o.jsx("button",{onClick:_,disabled:f||!a,className:"btn btn-p w-full",style:f||!a?{opacity:.5,cursor:"not-allowed"}:{},children:f?"Saving...":"Save & Connect"})]}),o.jsx($j,{msg:h})]}),o.jsx(yh,{title:"Ken API Reference",children:o.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6 text-xs",style:{color:"var(--text-muted)"},children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx("p",{className:"stat-label mb-2",children:"Environments"}),o.jsxs("div",{className:"space-y-1",children:[o.jsxs("div",{className:"flex gap-2",children:[o.jsx("span",{children:"Demo:"}),o.jsx("span",{className:"mono",style:{color:"var(--orange)"},children:"demo-api.kalshi.co"})]}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx("span",{children:"Prod:"}),o.jsx("span",{className:"mono",style:{color:"var(--green)"},children:"api.elections.kalshi.com"})]})]})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("p",{className:"stat-label mb-2",children:"Authentication"}),o.jsxs("div",{className:"space-y-1",children:[o.jsxs("div",{className:"flex gap-2",children:[o.jsx("span",{children:"Method:"}),o.jsx("span",{className:"mono",style:{color:"var(--text-dim)"},children:"RSA-PSS + SHA-256"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Headers: "}),o.jsx("span",{className:"mono",style:{color:"var(--text-dim)"},children:"KALSHI-ACCESS-KEY, TIMESTAMP, SIGNATURE"})]})]})]})]})})]})}const LZ={BUY_YES:"bg-green",BUY_NO:"bg-red"};function DZ(e){if(!e)return null;const t=e.match(/on\s+"([^"]+)"/);return t?t[1]:null}function RZ({value:e}){const t=Math.max(0,Math.min(100,e*100)),r=e>.7?"var(--green)":e>.5?"var(--orange)":"var(--red)";return o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("div",{className:"progress-bar flex-1",style:{minWidth:64},children:o.jsx("div",{className:"progress-fill",style:{width:`${t}%`,background:`linear-gradient(90deg, ${r}, ${r}cc)`}})}),o.jsxs("span",{className:"mono text-xs",style:{color:"var(--text-dim)"},children:[t.toFixed(0),"%"]})]})}function BZ({s:e}){const[t,r]=P.useState(!1),n=DZ(e.reasoning)||e.market_id,a=parseFloat(e.expected_edge)||0,i=parseFloat(e.confidence)||0;return o.jsxs(o.Fragment,{children:[o.jsxs("tr",{className:"cursor-pointer transition",onClick:()=>r(!t),style:{background:t?"rgba(0,240,255,0.04)":void 0},children:[o.jsx("td",{className:"whitespace-nowrap",children:o.jsx("span",{className:"mono text-xs",style:{color:"var(--text-muted)"},children:new Date(e.created_at).toLocaleTimeString()})}),o.jsxs("td",{className:"max-w-[280px]",children:[o.jsx("a",{href:e.kalshi_url||`https://kalshi.com/search?query=${encodeURIComponent((e.market_id||"").split("-")[0])}`,target:"_blank",rel:"noopener noreferrer",className:"text-sm truncate block hover:underline transition heading",style:{color:"var(--cyan)"},onClick:s=>s.stopPropagation(),children:n}),o.jsx("span",{className:"mono text-[10px]",style:{color:"var(--text-muted)"},children:e.market_id})]}),o.jsx("td",{children:o.jsx("span",{className:`badge ${LZ[e.direction]||"bg-yellow"}`,children:e.direction})}),o.jsx("td",{children:o.jsxs("span",{className:"mono font-bold text-base",style:{color:a>0?"var(--cyan)":"var(--red)"},children:[a>0?"+":"",(a*100).toFixed(1),"%"]})}),o.jsx("td",{children:o.jsx("span",{className:"mono text-sm",style:{color:"var(--text-dim)"},children:e.size_recommendation||"—"})}),o.jsx("td",{style:{minWidth:140},children:o.jsx(RZ,{value:i})}),o.jsx("td",{children:o.jsx("span",{className:`badge ${e.risk_approved?"bg-green":"bg-red"}`,children:e.risk_approved?"APPROVED":"BLOCKED"})}),o.jsx("td",{children:o.jsx("span",{style:{color:"var(--text-muted)"},children:t?"▾":"▸"})})]}),t&&o.jsx("tr",{style:{background:"rgba(0,240,255,0.02)"},children:o.jsxs("td",{colSpan:8,className:"px-4 py-3",children:[o.jsx("p",{className:"text-xs leading-relaxed fade-in",style:{color:"var(--text-dim)"},children:e.reasoning}),e.sources&&o.jsx("div",{className:"mt-2 flex flex-wrap gap-1",children:(typeof e.sources=="string"?e.sources.split(","):Array.isArray(e.sources)?e.sources:[]).map((s,l)=>o.jsx("span",{className:"badge bg-blue text-[10px]",children:s.trim()},l))})]})})]})}function FZ({s:e}){const t=parseFloat(e.edge)||0,r=parseFloat(e.sentiment_impact)||0,n=e.market_title||e.market_id;return o.jsxs("tr",{children:[o.jsx("td",{className:"whitespace-nowrap",children:o.jsx("span",{className:"mono text-xs",style:{color:"var(--text-muted)"},children:new Date(e.created_at).toLocaleTimeString()})}),o.jsxs("td",{className:"max-w-[250px]",children:[o.jsx("a",{href:e.kalshi_url||`https://kalshi.com/search?query=${encodeURIComponent((e.market_id||"").split("-")[0])}`,target:"_blank",rel:"noopener noreferrer",className:"text-sm truncate block hover:underline transition heading",style:{color:"var(--cyan)"},children:n}),o.jsx("span",{className:"mono text-[10px]",style:{color:"var(--text-muted)"},children:e.market_id})]}),o.jsx("td",{children:o.jsxs("span",{className:"mono text-sm",style:{color:"var(--text-dim)"},children:[(parseFloat(e.prior_probability)*100).toFixed(1),"%"]})}),o.jsx("td",{children:o.jsxs("span",{className:"mono text-sm font-semibold",style:{color:r>0?"var(--green)":"var(--red)"},children:[r>0?"+":"",(r*100).toFixed(2),"%"]})}),o.jsx("td",{children:o.jsxs("span",{className:"mono text-sm",style:{color:"var(--orange)"},children:[(parseFloat(e.adjusted_probability)*100).toFixed(1),"%"]})}),o.jsx("td",{children:o.jsxs("span",{className:"mono text-sm",style:{color:"var(--text-dim)"},children:[(parseFloat(e.market_probability)*100).toFixed(1),"%"]})}),o.jsx("td",{children:o.jsxs("span",{className:"mono text-sm font-bold",style:{color:t>0?"var(--green)":t<0?"var(--red)":"var(--text-muted)"},children:[t>0?"+":"",(t*100).toFixed(1),"%"]})}),o.jsx("td",{children:o.jsx("span",{className:"mono text-xs",style:{color:"var(--text-muted)"},children:e.num_articles})})]})}function zZ({s:e}){const t=parseFloat(e.avg_sent)||0;return o.jsxs("div",{className:"card flex items-center justify-between",style:{padding:"0.75rem 1rem"},children:[o.jsx("span",{className:"text-sm font-medium heading",children:e.source}),o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsxs("span",{className:"mono text-xs",style:{color:"var(--text-muted)"},children:[e.cnt," items"]}),o.jsxs("span",{className:"mono text-xs font-bold",style:{color:t>.05?"var(--green)":t<-.05?"var(--red)":"var(--text-muted)"},children:[t>0?"+":"",(t*100).toFixed(0),"%"]})]})]})}function za({label:e,value:t,color:r}){return o.jsxs("div",{className:"card",children:[o.jsx("p",{className:"stat-label mb-2",children:e}),o.jsx("p",{className:"stat-v",style:{color:r},children:t})]})}function gh({active:e,onClick:t,children:r}){return o.jsx("button",{onClick:t,className:"btn btn-sm transition",style:{background:e?"var(--cyan-dim)":"transparent",color:e?"var(--cyan)":"var(--text-muted)",border:e?"1px solid rgba(0,240,255,0.3)":"1px solid transparent",borderRadius:"var(--radius-md)"},children:r})}function WZ(){var p,g,y,b,v,m;const[e,t]=P.useState(null),[r,n]=P.useState(null),[a,i]=P.useState(!0),[s,l]=P.useState("signals");P.useEffect(()=>{c();const x=setInterval(c,3e4);return()=>clearInterval(x)},[]);async function c(){try{const[x,S]=await Promise.all([Oe("/signals"),Oe("/signals/dashboard")]);t(x),n(S)}catch{}i(!1)}if(a)return o.jsx("div",{className:"flex items-center justify-center h-64",children:o.jsx("div",{className:"animate-spin w-8 h-8 border-2 border-t-transparent rounded-full pulse-cyan",style:{borderColor:"var(--cyan)",borderTopColor:"transparent"}})});const u=(r==null?void 0:r.stats)||{},f=(e==null?void 0:e.signals)||[],d=(e==null?void 0:e.probabilityShifts)||[],h=(r==null?void 0:r.sourceBreakdown)||[];return o.jsxs("div",{className:"space-y-6 fade-in",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("span",{className:"text-2xl",style:{color:"var(--cyan)"},children:"⚡"}),o.jsx("h1",{className:"heading text-3xl font-bold",style:{color:"var(--text)"},children:"Signals"}),o.jsxs("span",{className:"flex items-center gap-1.5",children:[o.jsx("span",{className:"inline-block w-2 h-2 rounded-full pulse-cyan",style:{background:"var(--cyan)"}}),o.jsx("span",{className:"text-xs",style:{color:"var(--cyan)"},children:"LIVE"})]})]}),o.jsxs("p",{className:"section-subtitle mt-1",children:["News → Sentiment → Probability → Signals → Risk · ",((p=e==null?void 0:e.pipeline)==null?void 0:p.cachedMarkets)||0," markets tracked"]})]}),o.jsx("button",{onClick:c,className:"btn btn-o btn-sm",children:"↻ Refresh"})]}),o.jsxs("div",{className:"grid grid-cols-6 gap-3",children:[o.jsx(za,{label:"Signals 24h",value:u.total_signals||0,color:"var(--orange)"}),o.jsx(za,{label:"Approved",value:u.approved_signals||0,color:"var(--green)"}),o.jsx(za,{label:"BUY YES",value:u.buy_yes||0,color:"var(--green)"}),o.jsx(za,{label:"BUY NO",value:u.buy_no||0,color:"var(--red)"}),o.jsx(za,{label:"Avg Edge",value:u.avg_edge?`${(u.avg_edge*100).toFixed(1)}%`:"—",color:"var(--cyan)"}),o.jsx(za,{label:"Avg Confidence",value:u.avg_confidence?`${(u.avg_confidence*100).toFixed(0)}%`:"—",color:"var(--blue)"})]}),o.jsxs("div",{className:"flex gap-2 pb-3",style:{borderBottom:"1px solid var(--border)"},children:[o.jsxs(gh,{active:s==="signals",onClick:()=>l("signals"),children:["Strategy Signals (",f.length,")"]}),o.jsxs(gh,{active:s==="shifts",onClick:()=>l("shifts"),children:["Probability Shifts (",d.length,")"]}),o.jsxs(gh,{active:s==="sources",onClick:()=>l("sources"),children:["Source Breakdown (",h.length,")"]})]}),s==="signals"&&o.jsx("div",{className:"card overflow-x-auto fade-in",style:{padding:0},children:o.jsxs("table",{children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"Time"}),o.jsx("th",{children:"Market"}),o.jsx("th",{children:"Direction"}),o.jsx("th",{children:"Edge"}),o.jsx("th",{children:"Size"}),o.jsx("th",{children:"Confidence"}),o.jsx("th",{children:"Risk"}),o.jsx("th",{})]})}),o.jsx("tbody",{children:f.length===0?o.jsx("tr",{children:o.jsx("td",{colSpan:8,className:"text-center py-12",style:{color:"var(--text-muted)"},children:o.jsxs("div",{className:"flex flex-col items-center gap-2",children:[o.jsx("span",{className:"text-2xl",children:"⚡"}),o.jsx("span",{className:"text-sm",children:"No signals generated yet"})]})})}):f.map(x=>o.jsx(BZ,{s:x},x.id))})]})}),s==="shifts"&&o.jsx("div",{className:"card overflow-x-auto fade-in",style:{padding:0},children:o.jsxs("table",{children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"Time"}),o.jsx("th",{children:"Market"}),o.jsx("th",{children:"Prior"}),o.jsx("th",{children:"Impact"}),o.jsx("th",{children:"Adjusted"}),o.jsx("th",{children:"Market Price"}),o.jsx("th",{children:"Edge"}),o.jsx("th",{children:"Articles"})]})}),o.jsx("tbody",{children:d.length===0?o.jsx("tr",{children:o.jsx("td",{colSpan:8,className:"text-center py-12",style:{color:"var(--text-muted)"},children:o.jsxs("div",{className:"flex flex-col items-center gap-2",children:[o.jsx("span",{className:"text-2xl",children:"📊"}),o.jsx("span",{className:"text-sm",children:"No probability shifts yet"})]})})}):d.map((x,S)=>o.jsx(FZ,{s:x},S))})]})}),s==="sources"&&o.jsxs("div",{className:"grid grid-cols-2 gap-4 fade-in",children:[o.jsxs("div",{children:[o.jsxs("p",{className:"section-title mb-3",style:{fontSize:"1rem"},children:["Active Sources",o.jsx("span",{className:"badge bg-cyan ml-2",children:h.length})]}),o.jsx("div",{className:"space-y-2",children:h.length===0?o.jsx("p",{className:"text-sm",style:{color:"var(--text-muted)"},children:"No recent source data"}):h.map((x,S)=>o.jsx(zZ,{s:x},S))})]}),o.jsxs("div",{children:[o.jsx("p",{className:"section-title mb-3",style:{fontSize:"1rem"},children:"Pipeline Config"}),o.jsx("div",{className:"card space-y-2",children:[{label:"Market Scan",value:"Every 15 min"},{label:"Signal Pipeline",value:"Every 5 min"},{label:"Intelligence Sweep",value:"Every 30 min"},{label:"Min Edge Threshold",value:`${((((y=(g=e==null?void 0:e.pipeline)==null?void 0:g.riskLimits)==null?void 0:y.minEdgeThreshold)||.05)*100).toFixed(0)}%`,highlight:!0},{label:"Min Liquidity",value:`${((v=(b=e==null?void 0:e.pipeline)==null?void 0:b.riskLimits)==null?void 0:v.minLiquidity)||100} vol`,highlight:!0},{label:"Cached Markets",value:((m=e==null?void 0:e.pipeline)==null?void 0:m.cachedMarkets)||0,highlight:!0}].map(x=>o.jsxs("div",{className:"flex justify-between items-center p-2 rounded",style:{background:"var(--surface-el)"},children:[o.jsx("span",{className:"text-sm",style:{color:"var(--text-muted)"},children:x.label}),o.jsx("span",{className:"mono text-sm font-semibold",style:{color:x.highlight?"var(--cyan)":"var(--text)"},children:x.value})]},x.label))})]})]})]})}const Tj={reddit_hot:"🔴",reddit:"📋",google_news:"📰",hackernews:"🟠",metaculus:"🔮",manifold:"📊",gdelt_tv:"📺",youtube:"▶️",lemmy:"🟢",lobsters:"🦞",tildes:"~",bluesky:"🦋",mastodon:"🐘",predictit:"💰",fred:"📈",nws:"⛈️",govtrack:"🏛️",discord:"💬"};function UZ(e){return["reddit_hot","reddit","lemmy"].includes(e)?"bg-red":["google_news","govtrack","nws"].includes(e)?"bg-blue":["metaculus","manifold","predictit"].includes(e)?"bg-purple":["hackernews","lobsters","tildes"].includes(e)?"bg-orange":["fred"].includes(e)?"bg-green":["bluesky","mastodon","discord"].includes(e)?"bg-cyan":"bg-blue"}function HZ({value:e}){const t=parseFloat(e)||0;return t>.1?o.jsxs("span",{className:"badge bg-cyan",children:["+",(t*100).toFixed(0),"%"]}):t<-.1?o.jsxs("span",{className:"badge bg-red",children:[(t*100).toFixed(0),"%"]}):o.jsxs("span",{className:"badge bg-orange",children:[(t*100).toFixed(0),"%"]})}function Wa({col:e,label:t,sortCol:r,sortDir:n,onSort:a}){const i=r===e;return o.jsx("th",{onClick:()=>a(e),className:"cursor-pointer select-none transition",style:{color:i?"var(--cyan)":void 0},children:o.jsxs("span",{className:"flex items-center gap-1",children:[t,i?o.jsx("span",{style:{color:"var(--cyan)"},children:n==="asc"?"▲":"▼"}):o.jsx("span",{style:{color:"var(--border-light)"},children:"⇅"})]})})}function cc({label:e,value:t,color:r}){return o.jsxs("div",{className:"card",children:[o.jsx("p",{className:"stat-label mb-2",children:e}),o.jsx("p",{className:"stat-v",style:{color:r},children:t})]})}function KZ(){const[e,t]=P.useState(null),[r,n]=P.useState(!0),[a,i]=P.useState(""),[s,l]=P.useState("captured_at"),[c,u]=P.useState("desc");P.useEffect(()=>{f();const S=setInterval(f,6e4);return()=>clearInterval(S)},[]);async function f(){try{const S=await Oe("/intelligence");t(S)}catch{}n(!1)}function d(S){s===S?u(j=>j==="asc"?"desc":"asc"):(l(S),u(S==="captured_at"?"desc":"asc"))}if(r)return o.jsx("div",{className:"flex items-center justify-center h-64",children:o.jsx("div",{className:"animate-spin w-8 h-8 border-2 border-t-transparent rounded-full pulse-cyan",style:{borderColor:"var(--cyan)",borderTopColor:"transparent"}})});const h=(e==null?void 0:e.totals)||{},p=(e==null?void 0:e.sourceCounts)||[],g=((e==null?void 0:e.recent)||[]).filter(S=>!a||S.source.toLowerCase().includes(a.toLowerCase())||(S.post_title||"").toLowerCase().includes(a.toLowerCase())||(S.keyword||"").toLowerCase().includes(a.toLowerCase()));function y(S,j){let w,_;switch(s){case"captured_at":w=new Date(S.captured_at),_=new Date(j.captured_at);break;case"source":w=S.source||"",_=j.source||"";break;case"keyword":w=S.keyword||S.subreddit||"",_=j.keyword||j.subreddit||"";break;case"post_title":w=(S.post_title||"").toLowerCase(),_=(j.post_title||"").toLowerCase();break;case"score":w=Number(S.score||0),_=Number(j.score||0);break;case"sentiment":w=parseFloat(S.sentiment_score||0),_=parseFloat(j.sentiment_score||0);break;default:return 0}return w<_?c==="asc"?-1:1:w>_?c==="asc"?1:-1:0}const b=[...g].sort(y),v=parseFloat(h.avg_sentiment_1h)||0,m=v>0?"var(--green)":v<0?"var(--red)":"var(--text-muted)",x={sortCol:s,sortDir:c,onSort:d};return o.jsxs("div",{className:"space-y-6 fade-in",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("span",{className:"text-2xl",style:{color:"var(--cyan)"},children:"⚗"}),o.jsx("h1",{className:"heading text-3xl font-bold",style:{color:"var(--text)"},children:"Intel Feed"}),o.jsxs("span",{className:"flex items-center gap-1.5",children:[o.jsx("span",{className:"inline-block w-2 h-2 rounded-full pulse-cyan",style:{background:"var(--cyan)"}}),o.jsx("span",{className:"text-xs",style:{color:"var(--cyan)"},children:"LIVE"})]})]}),o.jsx("p",{className:"section-subtitle mt-1",children:"Real-time data from 20+ sources"})]}),o.jsx("button",{onClick:f,className:"btn btn-o btn-sm",children:"↻ Refresh"})]}),o.jsxs("div",{className:"grid grid-cols-4 gap-4",children:[o.jsx(cc,{label:"Total Items",value:Number(h.total_items||0).toLocaleString(),color:"var(--orange)"}),o.jsx(cc,{label:"Last Hour",value:h.last_hour||0,color:"var(--green)"}),o.jsx(cc,{label:"Last 4 Hours",value:h.last_4h||0,color:"var(--blue)"}),o.jsx(cc,{label:"Avg Sentiment 1h",value:h.avg_sentiment_1h?`${(v*100).toFixed(1)}%`:"—",color:m})]}),o.jsxs("div",{className:"card",style:{padding:"1rem"},children:[o.jsx("p",{className:"section-title mb-3",style:{fontSize:"0.9rem"},children:"Active Sources"}),o.jsxs("div",{className:"flex flex-wrap gap-2",children:[o.jsx("button",{onClick:()=>i(""),className:"badge transition cursor-pointer",style:{background:a?"rgba(42,42,53,0.6)":"var(--cyan-dim)",color:a?"var(--text-muted)":"var(--cyan)",border:a?"1px solid var(--border)":"1px solid rgba(0,240,255,0.3)"},children:"All"}),p.map((S,j)=>{const w=a===S.source,_=parseFloat(S.avg_sent)||0;return o.jsxs("button",{onClick:()=>i(w?"":S.source),className:"badge transition cursor-pointer",style:{background:w?"var(--cyan-dim)":"rgba(42,42,53,0.6)",color:w?"var(--cyan)":"var(--text-muted)",border:w?"1px solid rgba(0,240,255,0.3)":"1px solid var(--border)"},children:[o.jsx("span",{children:Tj[S.source]||"📡"}),o.jsx("span",{className:"font-medium",children:S.source}),o.jsx("span",{style:{color:"var(--text-muted)",opacity:.7},children:S.cnt}),o.jsxs("span",{className:"mono",style:{color:_>.05?"var(--green)":_<-.05?"var(--red)":"var(--text-muted)"},children:[_>0?"+":"",(_*100).toFixed(0),"%"]})]},j)})]})]}),o.jsxs("div",{className:"relative",children:[o.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-sm pointer-events-none",style:{color:"var(--text-muted)"},children:"⌕"}),o.jsx("input",{type:"text",value:a,onChange:S=>i(S.target.value),placeholder:"Filter by source, keyword, or title...",className:"input pl-8"})]}),o.jsxs("div",{className:"card overflow-x-auto",style:{padding:0},children:[o.jsxs("table",{children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx(Wa,{col:"captured_at",label:"Time",...x}),o.jsx(Wa,{col:"source",label:"Source",...x}),o.jsx(Wa,{col:"keyword",label:"Topic",...x}),o.jsx(Wa,{col:"post_title",label:"Headline",...x}),o.jsx(Wa,{col:"score",label:"Score",...x}),o.jsx(Wa,{col:"sentiment",label:"Sentiment",...x})]})}),o.jsx("tbody",{children:b.length===0?o.jsx("tr",{children:o.jsx("td",{colSpan:6,className:"text-center py-12",style:{color:"var(--text-muted)"},children:o.jsxs("div",{className:"flex flex-col items-center gap-2",children:[o.jsx("span",{className:"text-2xl",children:"⚗"}),o.jsx("span",{className:"text-sm",children:"No items match your filter"})]})})}):b.slice(0,50).map((S,j)=>(parseFloat(S.sentiment_score),o.jsxs("tr",{children:[o.jsx("td",{className:"whitespace-nowrap",children:o.jsx("span",{className:"mono text-xs",style:{color:"var(--text-muted)"},children:new Date(S.captured_at).toLocaleTimeString()})}),o.jsx("td",{children:o.jsxs("span",{className:`badge ${UZ(S.source)}`,children:[Tj[S.source]||"📡"," ",S.source]})}),o.jsx("td",{children:o.jsx("span",{className:"text-xs",style:{color:"var(--text-dim)"},children:S.keyword||S.subreddit||"—"})}),o.jsx("td",{className:"max-w-[400px]",children:S.post_url?o.jsx("a",{href:S.post_url,target:"_blank",rel:"noopener noreferrer",className:"text-sm truncate block hover:underline transition heading",style:{color:"var(--text)"},children:S.post_title}):o.jsx("span",{className:"text-sm truncate block heading",style:{color:"var(--text)"},children:S.post_title})}),o.jsx("td",{children:o.jsxs("span",{className:"mono text-xs",style:{color:"var(--text-dim)"},children:[S.score||0,S.num_comments?o.jsxs("span",{style:{color:"var(--text-muted)"},children:[" / ",S.num_comments,"c"]}):null]})}),o.jsx("td",{children:o.jsx(HZ,{value:S.sentiment_score})})]},j)))})]}),b.length>0&&o.jsxs("div",{className:"px-4 py-3 text-xs",style:{color:"var(--text-muted)",borderTop:"1px solid var(--border)"},children:["Showing ",Math.min(50,b.length)," of ",b.length," items",a&&` matching "${a}"`]})]})]})}function Ua({label:e,value:t,color:r}){return o.jsxs("div",{className:"card",children:[o.jsx("p",{className:"stat-label mb-2",children:e}),o.jsx("p",{className:"stat-v",style:{color:r},children:t})]})}function kt({label:e,value:t,highlight:r}){return o.jsxs("div",{className:"flex justify-between items-center px-3 py-2 rounded",style:{background:"var(--surface-el)"},children:[o.jsx("span",{className:"text-sm",style:{color:"var(--text-muted)"},children:e}),o.jsx("span",{className:"mono text-sm font-semibold",style:{color:r||"var(--text)"},children:t})]})}function Mj({label:e,active:t,color:r,onClick:n,disabled:a}){return o.jsx("button",{onClick:n,disabled:a,className:"flex-1 py-2 rounded-lg text-sm font-bold transition",style:{background:t?`${r}22`:"var(--surface-el)",color:t?r:"var(--text-muted)",border:`1px solid ${t?r+"55":"var(--border)"}`},children:e})}function VZ(){const[e,t]=P.useState(null),[r,n]=P.useState(null),[a,i]=P.useState(null),[s,l]=P.useState(!0),[c,u]=P.useState("");P.useEffect(()=>{f();const x=setInterval(f,15e3);return()=>clearInterval(x)},[]);async function f(){try{const[x,S,j]=await Promise.all([me("/trading/mode",{action:"get"}),Oe("/trading/history"),Oe("/system")]);t(x),n(S),i(j)}catch{}l(!1)}async function d(x,S={}){u(x);try{await me("/trading/mode",{action:x,...S}),await f()}catch{}u("")}if(s)return o.jsx("div",{className:"flex items-center justify-center h-64",children:o.jsx("div",{className:"animate-spin w-8 h-8 border-2 border-t-transparent rounded-full pulse-cyan",style:{borderColor:"var(--cyan)",borderTopColor:"transparent"}})});const h=(e==null?void 0:e.trade_config)||{},p=(e==null?void 0:e.trader_state)||{},g=(r==null?void 0:r.summary)||{},y=(r==null?void 0:r.trades)||[],b=(a==null?void 0:a.memory)||{},v=parseInt(g.total_pnl||0),m=v>0?"var(--green)":v<0?"var(--red)":"var(--text-muted)";return o.jsxs("div",{className:"space-y-6 fade-in",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("span",{className:"text-2xl",style:{color:"var(--green)"},children:"$"}),o.jsx("h1",{className:"heading text-3xl font-bold",style:{color:"var(--text)"},children:"Trading"}),o.jsx("span",{className:`badge ${(e==null?void 0:e.env)==="prod"?"bg-green":"bg-orange"}`,children:((e==null?void 0:e.env)||"demo").toUpperCase()}),(e==null?void 0:e.safe_mode)&&o.jsx("span",{className:"badge bg-orange",children:"SAFE MODE"}),(e==null?void 0:e.auto_trader_enabled)&&o.jsx("span",{className:"badge bg-green",children:"AUTO ON"})]}),o.jsx("p",{className:"section-subtitle mt-1",children:"Mode control, execution, and P&L"})]}),o.jsx("button",{onClick:f,className:"btn btn-o btn-sm",children:"↻ Refresh"})]}),o.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[o.jsxs("div",{className:"card-glow",children:[o.jsx("p",{className:"stat-label mb-3",children:"Environment"}),o.jsxs("div",{className:"flex gap-2 mb-3",children:[o.jsx(Mj,{label:"DEMO",active:(e==null?void 0:e.env)==="demo",color:"var(--orange)",onClick:()=>d("switch_env",{env:"demo"}),disabled:c==="switch_env"}),o.jsx(Mj,{label:"PROD",active:(e==null?void 0:e.env)==="prod",color:"var(--green)",onClick:()=>d("switch_env",{env:"prod"}),disabled:c==="switch_env"})]}),o.jsxs("p",{className:"text-xs",style:{color:"var(--text-muted)"},children:["API keys: ",e!=null&&e.kalshi_connected?o.jsx("span",{style:{color:"var(--green)"},children:"Configured"}):o.jsx("span",{style:{color:"var(--red)"},children:"Not set"})]})]}),o.jsxs("div",{className:"card-glow",children:[o.jsx("p",{className:"stat-label mb-3",children:"Safe Mode"}),o.jsx("button",{onClick:()=>d("toggle_safe_mode"),disabled:c==="toggle_safe_mode",className:"btn w-full btn-lg font-bold transition",style:{background:e!=null&&e.safe_mode?"rgba(247,147,26,0.15)":"var(--red-dim)",color:e!=null&&e.safe_mode?"var(--orange)":"var(--red)",border:`1px solid ${e!=null&&e.safe_mode?"rgba(247,147,26,0.4)":"rgba(255,92,92,0.4)"}`},children:c==="toggle_safe_mode"?"...":e!=null&&e.safe_mode?"SAFE MODE — ON":"SAFE MODE — OFF"}),o.jsx("p",{className:"text-xs mt-2",style:{color:"var(--text-muted)"},children:e!=null&&e.safe_mode?"No real orders will be placed":o.jsx("span",{style:{color:"var(--red)"},children:"Real orders will be executed!"})})]}),o.jsxs("div",{className:"card-glow",children:[o.jsx("p",{className:"stat-label mb-3",children:"Auto Trader"}),o.jsx("button",{onClick:()=>d("toggle_auto_trader"),disabled:c==="toggle_auto_trader",className:"btn w-full btn-lg font-bold transition",style:{background:e!=null&&e.auto_trader_enabled?"var(--green-dim)":"var(--surface-el)",color:e!=null&&e.auto_trader_enabled?"var(--green)":"var(--text-muted)",border:`1px solid ${e!=null&&e.auto_trader_enabled?"rgba(0,195,137,0.4)":"var(--border)"}`},children:c==="toggle_auto_trader"?"...":e!=null&&e.auto_trader_enabled?"AUTO TRADER: ON":"AUTO TRADER: OFF"}),o.jsxs("p",{className:"text-xs mt-2",style:{color:"var(--text-muted)"},children:["Min confidence: ",o.jsxs("span",{className:"mono",children:[h.min_confidence,"%"]})," · Budget: ",o.jsxs("span",{className:"mono",children:["$",(h.budget_cents/100).toFixed(0)]})]})]})]}),o.jsxs("div",{className:"grid grid-cols-6 gap-3",children:[o.jsx(Ua,{label:"Total Trades",value:g.total_trades||0,color:"var(--orange)"}),o.jsx(Ua,{label:"Open",value:g.open_trades||0,color:"var(--blue)"}),o.jsx(Ua,{label:"Wins",value:g.winning_trades||0,color:"var(--green)"}),o.jsx(Ua,{label:"Losses",value:g.losing_trades||0,color:"var(--red)"}),o.jsx(Ua,{label:"Total P&L",value:g.total_pnl?`$${(v/100).toFixed(2)}`:"$0.00",color:m}),o.jsx(Ua,{label:"Exposure",value:`$${(parseInt(g.open_exposure||0)/100).toFixed(2)}`,color:"var(--purple)"})]}),o.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[o.jsxs("div",{className:"card",children:[o.jsxs("p",{className:"section-title mb-3",style:{fontSize:"1rem"},children:[o.jsx("span",{style:{color:"var(--cyan)"},children:"⚙"})," Trade Config"]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(kt,{label:"Budget",value:`$${(h.budget_cents/100).toFixed(0)}`,highlight:"var(--cyan)"}),o.jsx(kt,{label:"Max per trade",value:`$${(h.max_position_cents/100).toFixed(0)}`}),o.jsx(kt,{label:"Max positions",value:h.max_open_positions}),o.jsx(kt,{label:"Daily loss limit",value:`$${(h.daily_loss_limit_cents/100).toFixed(0)}`,highlight:"var(--red)"}),o.jsx(kt,{label:"Min confidence",value:`${h.min_confidence}%`,highlight:"var(--orange)"}),o.jsx(kt,{label:"Take profit",value:`${h.take_profit_pct}%`,highlight:"var(--green)"}),o.jsx(kt,{label:"Stop loss",value:`${h.stop_loss_pct}%`,highlight:"var(--red)"})]})]}),o.jsxs("div",{className:"card",children:[o.jsxs("p",{className:"section-title mb-3",style:{fontSize:"1rem"},children:[o.jsx("span",{style:{color:"var(--cyan)"},children:"♥"})," System Health"]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(kt,{label:"Memory (RSS)",value:`${b.rss_mb||"?"} MB`}),o.jsx(kt,{label:"Heap Used",value:`${b.heapUsed_mb||"?"} MB`}),o.jsx(kt,{label:"Heap Total",value:`${b.heapTotal_mb||"?"} MB`}),o.jsx(kt,{label:"Uptime",value:`${(a==null?void 0:a.uptime_hours)||"?"}h`,highlight:"var(--blue)"}),o.jsx(kt,{label:"Cached Markets",value:(a==null?void 0:a.cachedMarkets)||0,highlight:"var(--cyan)"}),o.jsx(kt,{label:"PID",value:(a==null?void 0:a.pid)||"?"}),o.jsx(kt,{label:"Available Budget",value:`$${((p.available||0)/100).toFixed(2)}`,highlight:"var(--green)"})]})]})]}),o.jsxs("div",{className:"card overflow-x-auto",style:{padding:0},children:[o.jsxs("div",{className:"flex items-center justify-between px-5 py-4",style:{borderBottom:"1px solid var(--border)"},children:[o.jsxs("p",{className:"section-title",style:{fontSize:"1rem"},children:[o.jsx("span",{style:{color:"var(--orange)"},children:"◈"})," Trade History"]}),y.length>0&&o.jsxs("span",{className:"badge bg-orange",children:[y.length," trades"]})]}),o.jsxs("table",{children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"Time"}),o.jsx("th",{children:"Market"}),o.jsx("th",{children:"Side"}),o.jsx("th",{children:"Qty"}),o.jsx("th",{children:"Entry"}),o.jsx("th",{children:"Exit"}),o.jsx("th",{children:"P&L"}),o.jsx("th",{children:"Type"}),o.jsx("th",{children:"Status"})]})}),o.jsx("tbody",{children:y.length===0?o.jsx("tr",{children:o.jsx("td",{colSpan:9,className:"text-center py-12",style:{color:"var(--text-muted)"},children:o.jsxs("div",{className:"flex flex-col items-center gap-2",children:[o.jsx("span",{className:"text-2xl",style:{color:"var(--text-muted)"},children:"$"}),o.jsx("span",{className:"text-sm",children:"No trades yet — signals are generating, waiting for execution"})]})})}):y.map((x,S)=>{const j=parseInt(x.pnl_cents)||0,w=j>0?"var(--green)":j<0?"var(--red)":"var(--text-muted)",_=x.status==="open"?"bg-blue":x.status==="profit"?"bg-green":x.status==="stopped"?"bg-red":"bg-orange";return o.jsxs("tr",{children:[o.jsx("td",{className:"whitespace-nowrap",children:o.jsxs("span",{className:"mono text-xs",style:{color:"var(--text-muted)"},children:[new Date(x.created_at).toLocaleDateString()," ",new Date(x.created_at).toLocaleTimeString()]})}),o.jsx("td",{className:"max-w-[200px]",children:o.jsx("a",{href:`https://kalshi.com/search?query=${encodeURIComponent((x.ticker||"").split("-")[0])}`,target:"_blank",rel:"noopener noreferrer",className:"text-sm truncate block hover:underline transition heading",style:{color:"var(--cyan)"},children:x.title||x.ticker})}),o.jsx("td",{children:o.jsx("span",{className:`badge ${x.side==="yes"?"bg-green":"bg-red"}`,children:(x.side||"").toUpperCase()})}),o.jsx("td",{children:o.jsx("span",{className:"mono text-sm",style:{color:"var(--text-dim)"},children:x.count})}),o.jsx("td",{children:o.jsxs("span",{className:"mono text-sm",style:{color:"var(--text-dim)"},children:[x.price_cents,"c"]})}),o.jsx("td",{children:o.jsx("span",{className:"mono text-sm",style:{color:x.exit_price?"var(--text-dim)":"var(--text-muted)"},children:x.exit_price?`${x.exit_price}c`:"—"})}),o.jsx("td",{children:o.jsx("span",{className:"mono text-sm font-bold",style:{color:w},children:j!==0?`${j>0?"+":""}$${(j/100).toFixed(2)}`:"—"})}),o.jsx("td",{children:o.jsx("span",{className:"text-xs",style:{color:"var(--text-muted)"},children:x.signal_type})}),o.jsx("td",{children:o.jsx("span",{className:`badge ${_}`,children:x.status})})]},S)})})]})]})]})}function Ij({value:e=0,size:t=48,strokeWidth:r=4,color:n="var(--cyan)",label:a,showValue:i=!0}){const[s,l]=P.useState(0),c=P.useRef(null),u=P.useRef(null),f=900;P.useEffect(()=>{const b=Math.min(100,Math.max(0,e)),v=s,m=x=>{u.current||(u.current=x);const S=x-u.current,j=Math.min(1,S/f),w=1-Math.pow(1-j,3);l(v+(b-v)*w),j<1&&(c.current=requestAnimationFrame(m))};return u.current=null,c.current=requestAnimationFrame(m),()=>cancelAnimationFrame(c.current)},[e]);const d=(t-r)/2,h=2*Math.PI*d,p=h-s/100*h,g=t/2,y=t<=40?t*.22:t*.2;return o.jsxs("div",{style:{display:"inline-flex",flexDirection:"column",alignItems:"center",gap:4},children:[o.jsxs("div",{style:{position:"relative",width:t,height:t},children:[o.jsxs("svg",{width:t,height:t,viewBox:`0 0 ${t} ${t}`,style:{display:"block"},children:[o.jsx("circle",{cx:g,cy:g,r:d,fill:"none",stroke:"var(--border)",strokeWidth:r}),o.jsx("circle",{cx:g,cy:g,r:d,fill:"none",stroke:n,strokeWidth:r,strokeLinecap:"round",strokeDasharray:h,strokeDashoffset:p,style:{transformOrigin:`${g}px ${g}px`,transform:"rotate(-90deg)",filter:`drop-shadow(0 0 3px ${n}80)`}})]}),i&&o.jsx("div",{style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center"},children:o.jsxs("span",{style:{fontFamily:"var(--font-mono)",fontWeight:700,fontSize:y,color:n,lineHeight:1,letterSpacing:"-0.03em"},children:[Math.round(s),"%"]})})]}),a&&o.jsx("span",{style:{fontFamily:"var(--font-body)",fontSize:"0.6rem",fontWeight:600,textTransform:"uppercase",letterSpacing:"0.08em",color:"var(--text-muted)"},children:a})]})}function GZ({categories:e}){const t=Object.entries(e||{});if(!t.length)return null;const r=t.map(([s,l],c)=>{const f=(Array.isArray(l)?l:[]).reduce((d,h)=>d+(h.pnl||0),0);return{name:s,value:Math.max(Math.abs(f),1),rawPnl:f,color:_j[c%_j.length]}}).filter(s=>Math.abs(s.rawPnl)>0).sort((s,l)=>l.value-s.value),n=t.reduce((s,[,l])=>{const c=Array.isArray(l)?l:[];return s+c.reduce((u,f)=>u+(f.pnl||0),0)},0),a=({active:s,payload:l})=>{var u;if(!s||!(l!=null&&l.length))return null;const c=((u=l[0])==null?void 0:u.payload)||{};return o.jsxs("div",{style:{background:"#1C1C24",border:"1px solid #2A2A35",borderRadius:8,padding:"8px 12px",fontSize:12,fontFamily:"'Inter', sans-serif"},children:[o.jsx("p",{style:{color:c.color,fontWeight:700,marginBottom:4},children:c.name}),o.jsxs("p",{className:"mono",style:{color:c.rawPnl>=0?"#00C389":"#FF5C5C",fontWeight:700},children:[c.rawPnl>=0?"+":"","$",(c.rawPnl/100).toFixed(2)]})]})},i=()=>o.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"6px 14px",justifyContent:"center",marginTop:8},children:r.map(s=>o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:5},children:[o.jsx("div",{style:{width:8,height:8,borderRadius:"50%",background:s.color,flexShrink:0}}),o.jsx("span",{style:{fontSize:11,color:"#A8A8A8",fontFamily:"'Inter', sans-serif"},children:s.name})]},s.name))});return o.jsxs("div",{className:"card",style:{display:"flex",flexDirection:"column",alignItems:"center"},children:[o.jsx("h3",{className:"section-title",style:{fontSize:"1rem",marginBottom:4,alignSelf:"flex-start"},children:"P&L by Category"}),o.jsxs("div",{style:{position:"relative",width:"100%",height:220},children:[o.jsx(tr,{width:"100%",height:"100%",children:o.jsxs(Qy,{children:[o.jsx("defs",{children:r.map(s=>o.jsxs("radialGradient",{id:`donut-grad-${s.name}`,cx:"50%",cy:"50%",r:"50%",children:[o.jsx("stop",{offset:"0%",stopColor:s.color,stopOpacity:.9}),o.jsx("stop",{offset:"100%",stopColor:s.color,stopOpacity:.6})]},s.name))}),o.jsx(wr,{data:r,cx:"50%",cy:"50%",innerRadius:65,outerRadius:95,paddingAngle:2,dataKey:"value",startAngle:90,endAngle:-270,children:r.map((s,l)=>o.jsx(xr,{fill:s.color,fillOpacity:.85,stroke:"transparent"},s.name))}),o.jsx(Ge,{content:o.jsx(a,{})})]})}),o.jsxs("div",{style:{position:"absolute",inset:0,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",pointerEvents:"none"},children:[o.jsx("span",{style:{fontSize:10,color:"#6B7280",fontWeight:600,textTransform:"uppercase",letterSpacing:"0.06em"},children:"Total P&L"}),o.jsxs("span",{className:"mono",style:{fontSize:20,fontWeight:700,lineHeight:1.2,color:n>=0?"#00C389":"#FF5C5C",textShadow:`0 0 10px ${n>=0?"rgba(0,195,137,0.4)":"rgba(255,92,92,0.4)"}`},children:[n>=0?"+":"","$",Math.abs(n/100).toFixed(0)]})]})]}),o.jsx(i,{})]})}function YZ({categories:e}){const t=Object.entries(e||{});if(!t.length)return null;const r=t.map(([a,i])=>{const s=Array.isArray(i)?i:[],l=s.reduce((d,h)=>d+(h.wins||0),0),c=s.reduce((d,h)=>d+(h.losses||0),0),u=l+c,f=u>0?(l/u*100).toFixed(1):0;return{name:a,wins:l,losses:c,total:u,wr:Number(f)}}).filter(a=>a.total>0).sort((a,i)=>i.total-a.total),n=({active:a,payload:i,label:s})=>{var c;if(!a||!(i!=null&&i.length))return null;const l=((c=i[0])==null?void 0:c.payload)||{};return o.jsxs("div",{style:{background:"#1C1C24",border:"1px solid #2A2A35",borderRadius:8,padding:"10px 14px",fontSize:12,fontFamily:"'Inter', sans-serif",minWidth:150},children:[o.jsx("p",{style:{color:"#E0E0E0",fontWeight:700,marginBottom:6},children:s}),o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",gap:12},children:[o.jsx("span",{style:{color:"#6B7280"},children:"Wins"}),o.jsx("span",{className:"mono",style:{color:"#00C389",fontWeight:700},children:l.wins})]}),o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",gap:12},children:[o.jsx("span",{style:{color:"#6B7280"},children:"Losses"}),o.jsx("span",{className:"mono",style:{color:"#FF5C5C",fontWeight:700},children:l.losses})]}),o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",gap:12},children:[o.jsx("span",{style:{color:"#6B7280"},children:"Win Rate"}),o.jsxs("span",{className:"mono",style:{color:l.wr>=50?"#00C389":"#FF5C5C",fontWeight:700},children:[l.wr,"%"]})]})]})]})};return o.jsxs("div",{className:"card",children:[o.jsx("h3",{className:"section-title",style:{fontSize:"1rem",marginBottom:16},children:"Category Win / Loss"}),o.jsx(tr,{width:"100%",height:220,children:o.jsxs(_l,{data:r,margin:{top:4,right:16,left:0,bottom:4},children:[o.jsx(Ia,{strokeDasharray:"3 3",stroke:"#2A2A35",strokeOpacity:.6,vertical:!1}),o.jsx(or,{dataKey:"name",stroke:"#2A2A35",tick:{fill:"#6B7280",fontSize:10,fontFamily:"'Inter', sans-serif"},tickLine:!1,axisLine:{stroke:"#2A2A35"}}),o.jsx(sr,{stroke:"#2A2A35",tick:{fill:"#6B7280",fontSize:11,fontFamily:"'Inter', sans-serif"},tickLine:!1,axisLine:!1,allowDecimals:!1}),o.jsx(Ge,{content:o.jsx(n,{}),cursor:{fill:"rgba(0,240,255,0.04)"}}),o.jsx(nr,{dataKey:"wins",stackId:"a",fill:"#00C389",fillOpacity:.85,radius:[0,0,0,0],maxBarSize:40,name:"Wins"}),o.jsx(nr,{dataKey:"losses",stackId:"a",fill:"#FF5C5C",fillOpacity:.85,radius:[4,4,0,0],maxBarSize:40,name:"Losses"})]})}),o.jsxs("div",{style:{display:"flex",justifyContent:"center",gap:20,marginTop:8},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[o.jsx("div",{style:{width:10,height:10,borderRadius:2,background:"#00C389"}}),o.jsx("span",{style:{fontSize:11,color:"#A8A8A8"},children:"Wins"})]}),o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[o.jsx("div",{style:{width:10,height:10,borderRadius:2,background:"#FF5C5C"}}),o.jsx("span",{style:{fontSize:11,color:"#A8A8A8"},children:"Losses"})]})]})]})}const qZ={trump:"Politics",president:"Politics",impeach:"Politics",congress:"Politics",senate:"Politics",house:"Politics",governor:"Politics",election:"Politics",democrat:"Politics",republican:"Politics",vote:"Politics",biden:"Politics",vance:"Politics",cabinet:"Politics",scotus:"Politics",supreme:"Politics",pardon:"Politics",approval:"Politics",poll:"Politics",secretary:"Politics",defense:"Politics",attorney:"Politics",gdp:"Economy",inflation:"Economy",cpi:"Economy",fed:"Economy","interest rate":"Economy",unemployment:"Economy",jobs:"Economy",payroll:"Economy",recession:"Economy",stock:"Economy",sp500:"Economy","s&p":"Economy",nasdaq:"Economy",dow:"Economy",treasury:"Economy",bond:"Economy",debt:"Economy",trade:"Economy",tariff:"Economy",deficit:"Economy",temperature:"Weather",rain:"Weather",snow:"Weather",hurricane:"Weather",weather:"Weather",tornado:"Weather",flood:"Weather",heat:"Weather",cold:"Weather",storm:"Weather",wind:"Weather",precipitation:"Weather",climate:"Weather",bitcoin:"Crypto",btc:"Crypto",ethereum:"Crypto",eth:"Crypto",crypto:"Crypto",token:"Crypto",blockchain:"Crypto",defi:"Crypto",nfl:"Sports",nba:"Sports",mlb:"Sports",nhl:"Sports",soccer:"Sports",tennis:"Sports","super bowl":"Sports",championship:"Sports",game:"Sports",match:"Sports",playoff:"Sports","world series":"Sports",ai:"Tech",spacex:"Tech",tesla:"Tech",apple:"Tech",google:"Tech",meta:"Tech",openai:"Tech",chatgpt:"Tech",tech:"Tech",rocket:"Tech",launch:"Tech",oscar:"Culture",movie:"Culture",tv:"Culture",celebrity:"Culture",grammy:"Culture",award:"Culture",music:"Culture",entertainment:"Culture",oil:"Energy",gas:"Energy",energy:"Energy",solar:"Energy",opec:"Energy",crude:"Energy",coal:"Energy",renewable:"Energy"},_n={Politics:{bg:"var(--blue)",glow:"rgba(59,130,246,0.3)",hex:"#3B82F6"},Economy:{bg:"var(--green)",glow:"rgba(0,195,137,0.3)",hex:"#00C389"},Weather:{bg:"var(--cyan)",glow:"rgba(0,240,255,0.3)",hex:"#00F0FF"},Crypto:{bg:"var(--orange)",glow:"rgba(247,147,26,0.3)",hex:"#F7931A"},Sports:{bg:"var(--purple)",glow:"rgba(168,85,247,0.3)",hex:"#A855F7"},Tech:{bg:"var(--cyan)",glow:"rgba(0,240,255,0.3)",hex:"#00F0FF"},Culture:{bg:"var(--orange)",glow:"rgba(247,147,26,0.3)",hex:"#F7931A"},Energy:{bg:"var(--orange)",glow:"rgba(247,147,26,0.3)",hex:"#F7931A"},Other:{bg:"var(--text-muted)",glow:"rgba(107,114,128,0.3)",hex:"#6B7280"}};function Lj(e){const t=(e||"").toLowerCase();for(const[r,n]of Object.entries(qZ))if(t.includes(r))return n;return"Other"}function Dj(e){return e>5e4?"var(--green)":e>1e4?"#4ade80":e>1e3?"#86efac":e>0?"#bbf7d0":e===0?"var(--text-muted)":e>-1e3?"#fecaca":e>-1e4?"#f87171":"var(--red)"}function uc(e){return e>5e4?"rgba(0,195,137,0.35)":e>1e4?"rgba(0,195,137,0.25)":e>1e3?"rgba(0,195,137,0.15)":e>0?"rgba(0,195,137,0.08)":e===0?"rgba(107,114,128,0.15)":e>-1e3?"rgba(255,92,92,0.08)":e>-1e4?"rgba(255,92,92,0.15)":"rgba(255,92,92,0.30)"}function da(e,t,r,n,a){if(!e.length)return[];if(e.length===1)return[{...e[0],x:t,y:r,w:n,h:a}];const i=e.reduce((p,g)=>p+g.size,0);if(i===0)return e.map(p=>({...p,x:t,y:r,w:0,h:0}));let s=0,l=0;const c=i*.5;for(let p=0;p<e.length;p++)if(s+=e[p].size,s>=c){l=p+1;break}l===0&&(l=1),l>=e.length&&(l=e.length-1);const u=e.slice(0,l),f=e.slice(l),h=u.reduce((p,g)=>p+g.size,0)/i;if(n>=a){const p=n*h;return[...da(u,t,r,p,a),...da(f,t+p,r,n-p,a)]}else{const p=a*h;return[...da(u,t,r,n,p),...da(f,t,r+p,n,a-p)]}}function eN({item:e,onClick:t,isSelected:r}){const n=(e.pnl/100).toFixed(2),a=e.trades>0?(e.wins/e.trades*100).toFixed(0):"0",i=e.w<120||e.h<80,s=e.w<80||e.h<50;return o.jsxs("div",{onClick:()=>t(e),className:"absolute cursor-pointer overflow-hidden group",style:{left:e.x,top:e.y,width:e.w,height:e.h,backgroundColor:uc(e.pnl),border:r?"2px solid var(--cyan)":"1px solid var(--border)",borderRadius:6,zIndex:r?10:1,transition:"all 150ms ease",boxShadow:r?"0 0 16px rgba(0,240,255,0.4)":void 0},children:[o.jsx("div",{className:"absolute inset-0 opacity-0 group-hover:opacity-100 pointer-events-none",style:{background:`radial-gradient(circle at center, ${uc(e.pnl).replace(")",", transparent)").replace("rgba","radial-gradient").includes("radial"),uc(e.pnl)}, transparent)`,boxShadow:`inset 0 0 12px ${e.pnl>=0?"rgba(0,195,137,0.3)":"rgba(255,92,92,0.3)"}`,transition:"opacity 200ms ease"}}),o.jsxs("div",{className:"relative h-full p-1.5 flex flex-col justify-between z-10",children:[!s&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"truncate text-[10px] font-medium leading-tight",style:{color:"var(--text-dim)"},children:e.shortTitle}),o.jsxs("div",{className:"flex items-end justify-between mt-auto",children:[o.jsxs("span",{className:"mono font-bold text-xs",style:{color:Dj(e.pnl)},children:[e.pnl>=0?"+":"",n>999?`$${(e.pnl/100/1e3).toFixed(1)}k`:`$${n}`]}),!i&&o.jsxs("span",{className:"text-[9px] font-bold mono",style:{color:Number(a)>=80?"var(--green)":Number(a)>=50?"var(--orange)":"var(--red)"},children:[a,"%"]})]})]}),s&&o.jsx("div",{className:"flex items-center justify-center h-full",children:o.jsxs("span",{className:"mono font-bold text-[10px]",style:{color:Dj(e.pnl)},children:[e.pnl>=0?"+":"",(e.pnl/100).toFixed(0)]})})]})]})}function XZ({category:e,items:t,x:r,y:n,w:a,h:i,onTileClick:s,selectedTicker:l}){const c=_n[e]||_n.Other,u=t.reduce((p,g)=>p+g.pnl,0),f=t.reduce((p,g)=>p+g.trades,0),d=Math.min(28,i*.15),h=da(t,0,0,a,i-d);return o.jsxs("div",{className:"absolute overflow-hidden",style:{left:r,top:n,width:a,height:i,borderRadius:8,border:`1px solid ${c.hex}40`},children:[o.jsxs("div",{className:"flex items-center justify-between px-2 relative z-20",style:{height:d,background:`linear-gradient(135deg, ${c.hex}25, ${c.hex}0D)`,borderBottom:`1px solid ${c.hex}40`},children:[o.jsx("span",{className:"text-xs font-bold tracking-wide heading",style:{color:c.hex},children:e}),o.jsxs("span",{className:"text-[10px] mono",style:{color:u>=0?"var(--green)":"var(--red)"},children:[u>=0?"+":"","$",(u/100).toFixed(0)," | ",f," trades"]})]}),o.jsx("div",{className:"relative",style:{height:i-d},children:h.map(p=>o.jsx(eN,{item:{...p,y:p.y},onClick:s,isSelected:l===p.ticker},p.ticker))})]})}function QZ({market:e,onClose:t}){if(!e)return null;const r=(e.pnl/100).toFixed(2),n=e.trades>0?(e.wins/e.trades*100).toFixed(1):"0",a=_n[e.category]||_n.Other;return o.jsxs("div",{className:"card-glow fade-in",children:[o.jsxs("div",{className:"flex items-start justify-between mb-4",children:[o.jsxs("div",{className:"flex-1 min-w-0 mr-4",children:[o.jsx("h3",{className:"heading text-sm font-bold truncate",style:{color:"var(--text)"},children:e.title}),o.jsx("p",{className:"mono text-xs mt-1",style:{color:"var(--text-muted)"},children:e.ticker})]}),o.jsx("button",{onClick:t,className:"btn btn-ghost text-lg leading-none",style:{padding:"0 6px"},children:"×"})]}),o.jsx("div",{className:"grid grid-cols-4 gap-3 text-center",children:[{label:"P&L",value:`${e.pnl>=0?"+":""}$${r}`,color:e.pnl>=0?"var(--green)":"var(--red)"},{label:"Win Rate",value:`${n}%`,color:Number(n)>=80?"var(--green)":Number(n)>=50?"var(--orange)":"var(--red)"},{label:"Trades",value:e.trades.toLocaleString(),color:"var(--orange)"},{label:"Record",valueEl:o.jsxs("p",{className:"text-lg font-bold",children:[o.jsx("span",{style:{color:"var(--green)"},children:e.wins}),o.jsx("span",{style:{color:"var(--border-light)"},className:"mx-0.5",children:"-"}),o.jsx("span",{style:{color:"var(--red)"},children:e.losses})]})}].map(i=>o.jsxs("div",{className:"rounded-lg p-2.5 text-center",style:{background:"var(--surface-el)",border:"1px solid var(--border)"},children:[o.jsx("p",{className:"stat-label mb-1",children:i.label}),i.valueEl||o.jsx("p",{className:"stat-v text-lg",style:{color:i.color},children:i.value})]},i.label))}),o.jsxs("div",{className:"mt-3 flex items-center justify-between text-xs",children:[o.jsxs("span",{style:{color:"var(--text-muted)"},children:["Category:"," ",o.jsx("span",{style:{color:a.hex},className:"font-semibold",children:e.category})]}),e.url&&o.jsx("a",{href:e.url,target:"_blank",rel:"noopener noreferrer",className:"text-cyan transition-colors",style:{color:"var(--cyan)"},children:"View on Kalshi →"})]}),e.edge&&o.jsx("div",{className:"mt-2 text-[11px] rounded-lg px-3 py-2",style:{color:"var(--text-dim)",background:"var(--surface-el)",border:"1px solid var(--border)"},children:e.edge})]})}function JZ(){const e=[{label:"> $500",bg:"rgba(0,195,137,0.35)"},{label:"$100-500",bg:"rgba(0,195,137,0.25)"},{label:"$10-100",bg:"rgba(0,195,137,0.15)"},{label:"$0-10",bg:"rgba(0,195,137,0.08)"},{label:"$0",bg:"rgba(107,114,128,0.15)"},{label:"-$10",bg:"rgba(255,92,92,0.08)"},{label:"-$100",bg:"rgba(255,92,92,0.15)"},{label:"< -$100",bg:"rgba(255,92,92,0.30)"}];return o.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[o.jsx("span",{className:"stat-label mr-1",children:"P&L Scale:"}),e.map(t=>o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx("div",{className:"w-3 h-3 rounded-sm",style:{backgroundColor:t.bg,border:"1px solid var(--border)"}}),o.jsx("span",{className:"text-[9px]",style:{color:"var(--text-muted)"},children:t.label})]},t.label))]})}function ZZ(){var _;const[e,t]=P.useState(null),[r,n]=P.useState(null),[a,i]=P.useState(!0),[s,l]=P.useState(null),[c,u]=P.useState("category"),[f,d]=P.useState("pnl");P.useEffect(()=>{h();const O=setInterval(h,3e4);return()=>clearInterval(O)},[]);async function h(){try{const[O,N]=await Promise.all([Oe("/dashboard"),Oe("/signals")]);t(O),n(N)}catch{}i(!1)}const{categories:p,allMarkets:g,summary:y}=P.useMemo(()=>{if(!e)return{categories:{},allMarkets:[],summary:{}};const O=[],N=new Set;for(const C of e.top_markets||[])if(!N.has(C.ticker)){N.add(C.ticker);const M=Lj(C.title);O.push({...C,category:M,trades:(C.wins||0)+(C.losses||0),shortTitle:(C.title||C.ticker).split("?")[0].substring(0,40),size:Math.max(Math.abs(C.pnl||1),100)})}for(const C of e.worst_markets||[])if(!N.has(C.ticker)){N.add(C.ticker);const M=Lj(C.title);O.push({...C,category:M,trades:(C.wins||0)+(C.losses||0),shortTitle:(C.title||C.ticker).split("?")[0].substring(0,40),size:Math.max(Math.abs(C.pnl||1),100)})}for(const C of e.strategies||[]){const M=`strategy-${C.strategy||C.name}`;N.has(M)||(N.add(M),O.push({ticker:M,title:`Strategy: ${C.name}`,shortTitle:C.name,category:"Other",wins:C.wins||0,losses:C.losses||0,trades:(C.wins||0)+(C.losses||0),pnl:C.pnl||0,edge:`Win Rate: ${C.win_rate||0}%`,size:Math.max(Math.abs(C.pnl||1),100)}))}f==="pnl"?O.sort((C,M)=>M.pnl-C.pnl):f==="trades"?O.sort((C,M)=>M.trades-C.trades):f==="winrate"&&O.sort((C,M)=>{const I=C.trades>0?C.wins/C.trades:0;return(M.trades>0?M.wins/M.trades:0)-I});const k={};for(const C of O)k[C.category]||(k[C.category]=[]),k[C.category].push(C);const E=O.reduce((C,M)=>C+M.pnl,0),T=O.reduce((C,M)=>C+M.trades,0),D=O.reduce((C,M)=>C+M.wins,0),A=O.reduce((C,M)=>C+M.losses,0),L=O.filter(C=>C.pnl>0).length;return{categories:k,allMarkets:O,summary:{totalPnl:E,totalTrades:T,totalWins:D,totalLosses:A,profitableCount:L,totalMarkets:O.length}}},[e,f]),b=g.find(O=>O.ticker===s);if(a)return o.jsx("div",{className:"flex items-center justify-center h-64",children:o.jsx("div",{className:"w-8 h-8 rounded-full border-2 border-t-transparent animate-spin",style:{borderColor:"var(--cyan)",borderTopColor:"transparent"}})});const v=1200,m=700,x=Object.entries(p).sort((O,N)=>{const k=O[1].reduce((T,D)=>T+Math.abs(D.pnl),0);return N[1].reduce((T,D)=>T+Math.abs(D.pnl),0)-k}),S=da(x.map(([O,N])=>({name:O,size:N.reduce((k,E)=>k+Math.abs(E.pnl||1),0)+N.length*100,items:N})),0,0,v,m),j=c==="flat"?da(g.map(O=>({...O,size:Math.max(Math.abs(O.pnl||1),200)})),0,0,v,m):[],w=[{label:"Total P&L",value:`${y.totalPnl>=0?"+":""}$${(y.totalPnl/100).toLocaleString(void 0,{minimumFractionDigits:0})}`,color:y.totalPnl>=0?"var(--green)":"var(--red)"},{label:"Total Trades",value:((_=y.totalTrades)==null?void 0:_.toLocaleString())||"0",color:"var(--orange)"},{label:"Win Rate",value:y.totalTrades>0?`${(y.totalWins/y.totalTrades*100).toFixed(1)}%`:"0%",color:"var(--blue)"},{label:"Markets",value:y.totalMarkets||0,color:"var(--purple)"},{label:"Profitable",value:y.profitableCount||0,color:"var(--green)"},{label:"Categories",value:Object.keys(p).length,color:"var(--cyan)"}];return o.jsxs("div",{className:"space-y-6",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{children:[o.jsx("h1",{className:"heading text-2xl font-bold kalshi-gradient",children:"Market Heatmap"}),o.jsx("p",{className:"section-subtitle mt-1",children:"Treemap visualization of trading activity and P&L by market category"})]}),o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("div",{className:"flex items-center gap-0.5 rounded-lg p-0.5",style:{background:"var(--surface-el)",border:"1px solid var(--border)"},children:["category","flat"].map(O=>o.jsx("button",{onClick:()=>u(O),className:"btn btn-sm",style:c===O?{background:"var(--cyan)",color:"var(--bg)",fontWeight:700}:{background:"transparent",color:"var(--text-muted)"},children:O==="category"?"By Category":"All Markets"},O))}),o.jsxs("select",{value:f,onChange:O=>d(O.target.value),className:"input",style:{width:"auto",paddingRight:"1.5rem"},children:[o.jsx("option",{value:"pnl",children:"Sort by P&L"}),o.jsx("option",{value:"trades",children:"Sort by Trades"}),o.jsx("option",{value:"winrate",children:"Sort by Win Rate"})]}),o.jsx("button",{onClick:h,className:"btn btn-o btn-sm",children:"Refresh"})]})]}),o.jsx("div",{className:"grid grid-cols-6 gap-3",children:w.map((O,N)=>{var E;const k=["card-accent-green","card-accent-orange","card-accent-blue","card-accent-purple","card-accent-green","card-accent-cyan"];if(O.label==="Win Rate"){const T=parseFloat(O.value)||0;return o.jsxs("div",{className:`card ${k[N]||"card-accent-cyan"}`,style:{display:"flex",alignItems:"center",gap:12},children:[o.jsx(Ij,{value:T,size:52,strokeWidth:4,color:T>=80?"var(--green)":T>=50?"var(--orange)":"var(--red)"}),o.jsxs("div",{children:[o.jsx("p",{className:"stat-label mb-0.5",children:O.label}),o.jsx("p",{className:"stat-v mono text-lg",style:{color:O.color},children:O.value})]})]},O.label)}if(O.label==="Profitable"){const T=((E=w.find(A=>A.label==="Markets"))==null?void 0:E.value)||1,D=T>0?Math.round(Number(O.value)/Number(T)*100):0;return o.jsxs("div",{className:`card ${k[N]||"card-accent-cyan"}`,style:{display:"flex",alignItems:"center",gap:12},children:[o.jsx(Ij,{value:D,size:52,strokeWidth:4,color:"var(--green)"}),o.jsxs("div",{children:[o.jsx("p",{className:"stat-label mb-0.5",children:O.label}),o.jsx("p",{className:"stat-v mono text-lg",style:{color:O.color},children:O.value})]})]},O.label)}return o.jsxs("div",{className:`card ${k[N]||"card-accent-cyan"}`,children:[o.jsx("p",{className:"stat-label mb-1",children:O.label}),o.jsx("p",{className:"stat-v mono text-xl",style:{color:O.color},children:O.value})]},O.label)})}),Object.keys(p).length>0&&o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 2fr",gap:16},children:[o.jsx(GZ,{categories:p}),o.jsx(YZ,{categories:p})]}),o.jsx("div",{className:"flex items-center gap-2 flex-wrap",children:Object.entries(p).map(([O,N])=>{const k=_n[O]||_n.Other,E=N.reduce((T,D)=>T+D.pnl,0);return o.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-1.5 rounded-full",style:{backgroundColor:`${k.hex}18`,border:`1px solid ${k.hex}40`},children:[o.jsx("div",{className:"w-2 h-2 rounded-full",style:{backgroundColor:k.hex}}),o.jsx("span",{className:"text-xs font-semibold heading",style:{color:k.hex},children:O}),o.jsx("span",{className:"text-[10px]",style:{color:"var(--text-muted)"},children:N.length}),o.jsxs("span",{className:"text-[10px] mono font-bold",style:{color:E>=0?"var(--green)":"var(--red)"},children:[E>=0?"+":"","$",(E/100).toFixed(0)]})]},O)})}),o.jsxs("div",{className:"card p-2 relative overflow-hidden",style:{minHeight:m+20},children:[o.jsx("div",{className:"relative",style:{width:v,height:m,margin:"0 auto",maxWidth:"100%"},children:c==="category"?S.map(O=>o.jsx(XZ,{category:O.name,items:O.items,x:O.x,y:O.y,w:O.w,h:O.h,onTileClick:N=>l(N.ticker===s?null:N.ticker),selectedTicker:s},O.name)):j.map(O=>o.jsx(eN,{item:O,onClick:N=>l(N.ticker===s?null:N.ticker),isSelected:s===O.ticker},O.ticker))}),o.jsx("div",{className:"mt-3 px-2",children:o.jsx(JZ,{})})]}),b&&o.jsx(QZ,{market:b,onClose:()=>l(null)}),o.jsxs("div",{className:"card",children:[o.jsx("div",{className:"flex items-center gap-2 mb-4",children:o.jsx("h2",{className:"section-title",children:"Category Breakdown"})}),o.jsxs("table",{children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"Category"}),o.jsx("th",{children:"Markets"}),o.jsx("th",{children:"Total Trades"}),o.jsx("th",{children:"Win Rate"}),o.jsx("th",{children:"P&L"}),o.jsx("th",{children:"Best Market"})]})}),o.jsx("tbody",{children:x.map(([O,N])=>{const k=_n[O]||_n.Other,E=N.reduce((C,M)=>C+M.pnl,0),T=N.reduce((C,M)=>C+M.trades,0),D=N.reduce((C,M)=>C+M.wins,0),A=T>0?(D/T*100).toFixed(1):"0",L=N.reduce((C,M)=>M.pnl>((C==null?void 0:C.pnl)||-1/0)?M:C,N[0]);return o.jsxs("tr",{children:[o.jsx("td",{children:o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:k.hex}}),o.jsx("span",{className:"font-semibold heading",style:{color:k.hex},children:O})]})}),o.jsx("td",{style:{color:"var(--text-dim)"},children:N.length}),o.jsx("td",{className:"mono",style:{color:"var(--text-dim)"},children:T.toLocaleString()}),o.jsxs("td",{className:"mono font-bold",style:{color:Number(A)>=80?"var(--green)":Number(A)>=50?"var(--orange)":"var(--red)"},children:[A,"%"]}),o.jsxs("td",{className:"mono font-bold",style:{color:E>=0?"var(--green)":"var(--red)"},children:[E>=0?"+":"","$",(E/100).toFixed(2)]}),o.jsx("td",{className:"text-xs truncate max-w-[200px]",style:{color:"var(--text-muted)"},children:(L==null?void 0:L.shortTitle)||"--"})]},O)})})]})]})]})}const Ko=[{radius:80,label:"Core",color:"#00F0FF",opacity:.5,description:"Highest confidence"},{radius:160,label:"Inner",color:"#00C389",opacity:.35,description:"Strong signals"},{radius:240,label:"Mid",color:"#3B82F6",opacity:.25,description:"Moderate signals"},{radius:320,label:"Outer",color:"#A855F7",opacity:.18,description:"Weak signals"},{radius:400,label:"Edge",color:"#FF5C5C",opacity:.12,description:"Speculative"}],Zi={BUY_YES:{fill:"#00C389",stroke:"#009E6F",glow:"rgba(0,195,137,0.5)"},BUY_NO:{fill:"#FF5C5C",stroke:"#CC4A4A",glow:"rgba(255,92,92,0.5)"},YES:{fill:"#00C389",stroke:"#009E6F",glow:"rgba(0,195,137,0.5)"},NO:{fill:"#FF5C5C",stroke:"#CC4A4A",glow:"rgba(255,92,92,0.5)"}};function Zy(e){return e>=.9?"#00C389":e>=.7?"#F7931A":e>=.5?"#3B82F6":e>=.3?"#A855F7":"#FF5C5C"}function tN(e){return e>=.9?0:e>=.75?1:e>=.6?2:e>=.4?3:4}function eee({width:e,height:t}){const r=P.useMemo(()=>{const n=[];for(let a=0;a<80;a++)n.push({x:Math.random()*e,y:Math.random()*t,r:Math.random()*1.2+.3,opacity:Math.random()*.4+.05,delay:Math.random()*3});return n},[e,t]);return o.jsx(o.Fragment,{children:r.map((n,a)=>o.jsx("circle",{cx:n.x,cy:n.y,r:n.r,fill:"white",opacity:n.opacity,className:"animate-pulse",style:{animationDelay:`${n.delay}s`,animationDuration:`${2+Math.random()*3}s`}},a))})}function tee({market:e,cx:t,cy:r,size:n,isSelected:a,onSelect:i,animate:s}){var h;const l=Zi[e.direction]||Zi.BUY_YES,c=parseFloat(e.confidence)||0,u=Zy(c),f=n+4,d=`gradient-${(h=e.ticker)==null?void 0:h.replace(/[^a-zA-Z0-9]/g,"")}`;return o.jsxs("g",{onClick:()=>i(e),className:"cursor-pointer",style:{transition:"all 0.5s ease-out"},children:[o.jsx("circle",{cx:t,cy:r,r:f,fill:"none",stroke:l.glow,strokeWidth:1.5,opacity:a?.9:.3,className:s?"animate-ping":"",style:{animationDuration:"2s",transformOrigin:`${t}px ${r}px`}}),o.jsx("circle",{cx:t,cy:r,r:n+2,fill:"none",stroke:u,strokeWidth:2,opacity:.65,strokeDasharray:`${c*20} ${(1-c)*20}`}),o.jsx("circle",{cx:t,cy:r,r:n,fill:`url(#${d})`,stroke:a?"#00F0FF":l.stroke,strokeWidth:a?2.5:1,className:"transition-all duration-300"}),o.jsx("defs",{children:o.jsxs("radialGradient",{id:d,children:[o.jsx("stop",{offset:"0%",stopColor:l.fill,stopOpacity:"0.9"}),o.jsx("stop",{offset:"70%",stopColor:l.fill,stopOpacity:"0.6"}),o.jsx("stop",{offset:"100%",stopColor:l.stroke,stopOpacity:"0.4"})]})}),n>=8&&o.jsx("text",{x:t,y:r+1,textAnchor:"middle",dominantBaseline:"middle",fill:"white",fontSize:Math.max(7,n*.6),fontWeight:"bold",fontFamily:"'JetBrains Mono', monospace",style:{pointerEvents:"none"},children:e.edge_display||""}),n>=10&&o.jsx("text",{x:t,y:r+n+12,textAnchor:"middle",fill:"#A8A8A8",fontSize:8,fontFamily:"'JetBrains Mono', monospace",style:{pointerEvents:"none"},children:(e.shortTitle||"").substring(0,18)})]})}function ree({market:e,onClose:t}){var s;if(!e)return null;const r=parseFloat(e.confidence)||0,n=parseFloat(e.expected_edge)||0,a=Zi[e.direction]||Zi.BUY_YES,i=((s=Ko[tN(r)])==null?void 0:s.label)||"Edge";return o.jsxs("div",{className:"card-glow fade-in",children:[o.jsxs("div",{className:"flex items-start justify-between mb-4",children:[o.jsxs("div",{className:"flex-1 min-w-0 mr-4",children:[o.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[o.jsx("span",{className:"inline-block w-3 h-3 rounded-full",style:{backgroundColor:a.fill}}),o.jsx("span",{className:"badge",style:e.direction==="BUY_YES"||e.direction==="YES"?{background:"var(--green-dim)",color:"var(--green)"}:{background:"var(--red-dim)",color:"var(--red)"},children:e.direction}),e.risk_approved?o.jsx("span",{className:"badge bg-green",children:"APPROVED"}):o.jsx("span",{className:"badge bg-red",children:"BLOCKED"})]}),o.jsx("h3",{className:"heading text-sm font-bold",style:{color:"var(--text)"},children:e.title||e.ticker}),o.jsx("p",{className:"mono text-xs mt-1",style:{color:"var(--text-muted)"},children:e.ticker})]}),o.jsx("button",{onClick:t,className:"btn btn-ghost text-lg leading-none",style:{padding:"0 6px"},children:"×"})]}),o.jsx("div",{className:"grid grid-cols-3 gap-3 mb-4",children:[{label:"Edge",value:`${(n*100).toFixed(1)}%`,color:"var(--orange)"},{label:"Confidence",value:`${(r*100).toFixed(0)}%`,color:Zy(r)},{label:"Orbit Ring",value:i,color:"var(--purple)"}].map(l=>o.jsxs("div",{className:"rounded-lg p-2.5 text-center",style:{background:"var(--surface-el)",border:"1px solid var(--border)"},children:[o.jsx("p",{className:"stat-label mb-1",children:l.label}),o.jsx("p",{className:"stat-v text-lg",style:{color:l.color},children:l.value})]},l.label))}),e.reasoning&&o.jsx("div",{className:"text-[11px] rounded-lg px-3 py-2 mb-3 leading-relaxed",style:{color:"var(--text-dim)",background:"var(--surface-el)",border:"1px solid var(--border)"},children:e.reasoning}),e.sources&&e.sources.length>0&&o.jsxs("div",{className:"space-y-1.5",children:[o.jsx("p",{className:"stat-label mb-1",children:"Signal Sources"}),e.sources.map((l,c)=>{var u;return o.jsxs("div",{className:"flex items-center gap-2 text-xs rounded-lg px-3 py-2",style:{background:"var(--surface-el)",border:"1px solid var(--border)"},children:[o.jsx("span",{className:"badge bg-blue",children:l.source}),o.jsx("span",{className:"truncate flex-1",style:{color:"var(--text-dim)"},children:l.headline}),o.jsxs("span",{className:"mono text-[10px]",style:{color:l.sentiment>0?"var(--green)":l.sentiment<0?"var(--red)":"var(--text-muted)"},children:[l.sentiment>0?"+":"",(u=l.sentiment)==null?void 0:u.toFixed(2)]})]},c)})]}),o.jsxs("div",{className:"mt-3 text-[10px]",style:{color:"var(--text-muted)"},children:["Signal created:"," ",e.created_at?new Date(e.created_at).toLocaleString("en-US",{timeZone:"America/Los_Angeles",hour:"2-digit",minute:"2-digit",month:"short",day:"numeric"}):"Unknown"]})]})}function nee(){const[e,t]=P.useState(null),[r,n]=P.useState(null),[a,i]=P.useState(!0),[s,l]=P.useState(null),[c,u]=P.useState("all"),[f,d]=P.useState(!0),h=P.useRef(null);P.useEffect(()=>{p();const k=setInterval(p,3e4);return()=>clearInterval(k)},[]);async function p(){try{const[k,E,T]=await Promise.all([Oe("/dashboard"),Oe("/signals"),Oe("/signals/dashboard")]);t(k),n({signals:(E==null?void 0:E.signals)||[],dashboard:T})}catch{}i(!1)}const{orbitalMarkets:g,stats:y}=P.useMemo(()=>{if(!(r!=null&&r.signals))return{orbitalMarkets:[],stats:{}};let k=r.signals.map(C=>{var z,q;const M=parseFloat(C.confidence)||0,I=parseFloat(C.expected_edge)||0,R=tN(M),K=((z=(C.ticker||"").split("-")[0])==null?void 0:z.replace("KX","").substring(0,12))||C.ticker;return{...C,shortTitle:K,title:((q=C.reasoning)==null?void 0:q.split('"')[1])||C.ticker,ring:R,conf:M,edge:I,edge_display:`${(I*100).toFixed(0)}%`,size:Math.max(6,Math.min(22,I*120+6))}});c==="approved"&&(k=k.filter(C=>C.risk_approved)),c==="yes"&&(k=k.filter(C=>C.direction==="BUY_YES")),c==="no"&&(k=k.filter(C=>C.direction==="BUY_NO")),k.sort((C,M)=>M.edge-C.edge),k=k.slice(0,60);const E=k.filter(C=>C.risk_approved).length,T=k.filter(C=>C.direction==="BUY_YES").length,D=k.filter(C=>C.direction==="BUY_NO").length,A=k.length>0?k.reduce((C,M)=>C+M.conf,0)/k.length:0,L=k.length>0?k.reduce((C,M)=>C+M.edge,0)/k.length:0;return{orbitalMarkets:k,stats:{total:k.length,approved:E,buyYes:T,buyNo:D,avgConf:A,avgEdge:L}}},[r,c]),b=g.find(k=>k.ticker===s);if(a)return o.jsx("div",{className:"flex items-center justify-center h-64",children:o.jsx("div",{className:"w-8 h-8 rounded-full border-2 border-t-transparent animate-spin",style:{borderColor:"var(--cyan)",borderTopColor:"transparent"}})});const v=450,m=430,x=900,S=860,j={};g.forEach(k=>{j[k.ring]=(j[k.ring]||0)+1});const w={},_=g.map(k=>{const E=Ko[k.ring];w[k.ring]||(w[k.ring]=0);const T=w[k.ring]++,D=j[k.ring],L=2*Math.PI/D*T+k.ring*.4,C=Math.sin(T*7.3)*.15,M=L+C,I=E.radius+Math.cos(T*3.7)*15;return{...k,cx:v+I*Math.cos(M),cy:m+I*Math.sin(M)}}),O=[{key:"all",label:"All"},{key:"approved",label:"Approved"},{key:"yes",label:"BUY YES"},{key:"no",label:"BUY NO"}],N=[{label:"Active Signals",value:y.total||0,color:"var(--cyan)"},{label:"Risk Approved",value:y.approved||0,color:"var(--green)"},{label:"BUY YES",value:y.buyYes||0,color:"var(--green)"},{label:"BUY NO",value:y.buyNo||0,color:"var(--red)"},{label:"Avg Confidence",value:`${((y.avgConf||0)*100).toFixed(0)}%`,color:"var(--blue)"},{label:"Avg Edge",value:`${((y.avgEdge||0)*100).toFixed(1)}%`,color:"var(--purple)"}];return o.jsxs("div",{className:"space-y-6",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{children:[o.jsxs("h1",{className:"heading text-2xl font-bold flex items-center gap-2",children:[o.jsx("span",{style:{color:"var(--cyan)"},children:"◐"}),o.jsx("span",{className:"gradient-cyan",children:"Signal Orbit"})]}),o.jsx("p",{className:"section-subtitle mt-1",children:"Radial visualization — distance from center = confidence, size = edge strength"})]}),o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("div",{className:"flex items-center gap-0.5 rounded-lg p-0.5",style:{background:"var(--surface-el)",border:"1px solid var(--border)"},children:O.map(k=>o.jsx("button",{onClick:()=>u(k.key),className:"btn btn-sm",style:c===k.key?{background:"var(--cyan)",color:"var(--bg)",fontWeight:700}:{background:"transparent",color:"var(--text-muted)"},children:k.label},k.key))}),o.jsxs("label",{className:"flex items-center gap-2 text-xs cursor-pointer",style:{color:"var(--text-dim)"},children:[o.jsx("input",{type:"checkbox",checked:f,onChange:k=>d(k.target.checked),className:"rounded",style:{accentColor:"var(--cyan)"}}),"Animate"]}),o.jsx("button",{onClick:p,className:"btn btn-o btn-sm",children:"Refresh"})]})]}),o.jsx("div",{className:"grid grid-cols-6 gap-3",children:N.map(k=>o.jsxs("div",{className:"card",children:[o.jsx("p",{className:"stat-label mb-1",children:k.label}),o.jsx("p",{className:"stat-v",style:{color:k.color},children:k.value})]},k.label))}),o.jsxs("div",{className:"card p-0 overflow-hidden relative",style:{background:"radial-gradient(ellipse at center, #0D1B2E 0%, #080D14 60%, var(--bg) 100%)"},children:[o.jsxs("svg",{ref:h,viewBox:`0 0 ${x} ${S}`,className:"w-full",style:{maxHeight:"75vh"},children:[o.jsx(eee,{width:x,height:S}),Ko.map((k,E)=>o.jsxs("g",{children:[o.jsx("circle",{cx:v,cy:m,r:k.radius,fill:"none",stroke:k.color,strokeWidth:.8,opacity:k.opacity,strokeDasharray:"4 4"}),o.jsx("text",{x:v+k.radius+6,y:m-4,fill:k.color,fontSize:9,opacity:k.opacity+.2,fontFamily:"'JetBrains Mono', monospace",children:k.label})]},E)),o.jsxs("defs",{children:[o.jsxs("radialGradient",{id:"sun-gradient",children:[o.jsx("stop",{offset:"0%",stopColor:"#00F0FF",stopOpacity:"1"}),o.jsx("stop",{offset:"50%",stopColor:"#00B8C8",stopOpacity:"0.8"}),o.jsx("stop",{offset:"100%",stopColor:"#006070",stopOpacity:"0.4"})]}),o.jsxs("filter",{id:"sun-glow",children:[o.jsx("feGaussianBlur",{stdDeviation:"10",result:"blur"}),o.jsxs("feMerge",{children:[o.jsx("feMergeNode",{in:"blur"}),o.jsx("feMergeNode",{in:"SourceGraphic"})]})]})]}),o.jsx("circle",{cx:v,cy:m,r:40,fill:"url(#sun-gradient)",filter:"url(#sun-glow)",opacity:.55}),o.jsx("circle",{cx:v,cy:m,r:25,fill:"url(#sun-gradient)"}),o.jsx("text",{x:v,y:m-4,textAnchor:"middle",fill:"#0E0E10",fontSize:12,fontWeight:"bold",fontFamily:"'JetBrains Mono', monospace",children:"KEN"}),o.jsx("text",{x:v,y:m+10,textAnchor:"middle",fill:"#0E0E10",fontSize:7,fontFamily:"'JetBrains Mono', monospace",opacity:.7,children:"TRADER"}),_.map(k=>{const E=Zi[k.direction]||Zi.BUY_YES;return o.jsx("line",{x1:v,y1:m,x2:k.cx,y2:k.cy,stroke:E.fill,strokeWidth:.4,opacity:s===k.ticker?.6:.1},`line-${k.ticker}`)}),_.map(k=>o.jsx(tee,{market:k,cx:k.cx,cy:k.cy,size:k.size,isSelected:s===k.ticker,onSelect:E=>l(E.ticker===s?null:E.ticker),animate:f&&k.risk_approved},k.ticker))]}),o.jsx("div",{className:"absolute bottom-3 left-3 rounded-lg p-3",style:{background:"rgba(14,14,16,0.85)",backdropFilter:"blur(8px)",border:"1px solid var(--border)"},children:o.jsxs("div",{className:"flex items-center gap-4 text-[10px]",children:[o.jsxs("div",{className:"flex items-center gap-1.5",children:[o.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:"var(--green)"}}),o.jsx("span",{style:{color:"var(--text-dim)"},children:"BUY YES"})]}),o.jsxs("div",{className:"flex items-center gap-1.5",children:[o.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:"var(--red)"}}),o.jsx("span",{style:{color:"var(--text-dim)"},children:"BUY NO"})]}),o.jsx("span",{style:{color:"var(--border-light)"},children:"|"}),o.jsx("span",{style:{color:"var(--text-muted)"},children:"Closer to center = higher confidence"}),o.jsx("span",{style:{color:"var(--text-muted)"},children:"Larger = bigger edge"})]})}),o.jsxs("div",{className:"absolute top-3 right-3 rounded-lg p-2.5",style:{background:"rgba(14,14,16,0.85)",backdropFilter:"blur(8px)",border:"1px solid var(--border)"},children:[o.jsx("p",{className:"stat-label mb-1.5",children:"Orbit Rings"}),o.jsx("div",{className:"space-y-1",children:Ko.map((k,E)=>o.jsxs("div",{className:"flex items-center gap-2 text-[10px]",children:[o.jsx("div",{className:"w-2 h-2 rounded-full",style:{backgroundColor:k.color,opacity:k.opacity+.3}}),o.jsx("span",{style:{color:k.color},children:k.label}),o.jsx("span",{style:{color:"var(--text-muted)"},children:k.description})]},E))})]})]}),b&&o.jsx(ree,{market:b,onClose:()=>l(null)}),o.jsxs("div",{className:"card",children:[o.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[o.jsx("h2",{className:"section-title",children:"Orbital Signal Registry"}),o.jsxs("span",{className:"text-xs",style:{color:"var(--text-muted)"},children:[g.length," signals in orbit"]})]}),o.jsx("div",{className:"overflow-x-auto",children:o.jsxs("table",{children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"Ring"}),o.jsx("th",{children:"Ticker"}),o.jsx("th",{children:"Direction"}),o.jsx("th",{children:"Edge"}),o.jsx("th",{children:"Confidence"}),o.jsx("th",{children:"Risk"}),o.jsx("th",{children:"Sources"})]})}),o.jsx("tbody",{children:g.slice(0,20).map(k=>{var T;const E=Ko[k.ring];return o.jsxs("tr",{onClick:()=>l(k.ticker===s?null:k.ticker),className:"cursor-pointer",style:s===k.ticker?{background:"var(--cyan-glow)"}:{},children:[o.jsx("td",{children:o.jsx("span",{className:"text-xs font-bold heading",style:{color:E.color},children:E.label})}),o.jsx("td",{className:"mono text-xs",style:{color:"var(--text-dim)"},children:k.ticker}),o.jsx("td",{children:o.jsx("span",{className:"badge",style:k.direction==="BUY_YES"?{background:"var(--green-dim)",color:"var(--green)"}:{background:"var(--red-dim)",color:"var(--red)"},children:k.direction})}),o.jsxs("td",{className:"mono font-bold text-sm",style:{color:"var(--orange)"},children:[(k.edge*100).toFixed(1),"%"]}),o.jsxs("td",{className:"mono text-sm",style:{color:Zy(k.conf)},children:[(k.conf*100).toFixed(0),"%"]}),o.jsx("td",{children:k.risk_approved?o.jsx("span",{className:"text-xs font-bold",style:{color:"var(--green)"},children:"OK"}):o.jsx("span",{className:"text-xs font-bold",style:{color:"var(--red)"},children:"BLOCKED"})}),o.jsx("td",{className:"text-xs",style:{color:"var(--text-muted)"},children:((T=k.sources)==null?void 0:T.length)||0})]},k.ticker)})})]})})]})]})}const kc=[{name:"Economy",icon:"💰",subcategories:["GDP","Inflation","Jobs","Fed Rate","Recession","Trade","Debt","Markets"],keywords:["gdp","inflation","cpi","unemployment","jobs","payroll","fed","interest rate","recession","stock","sp500","nasdaq","dow","treasury","bond","debt","trade","tariff","deficit"],cssColor:"var(--green)",dimColor:"var(--green-dim)",rgbColor:[0,195,137]},{name:"Politics",icon:"🏛",subcategories:["White House","Congress","Elections","SCOTUS","Cabinet","Polls","Policy","Foreign"],keywords:["trump","president","impeach","congress","senate","house","governor","election","democrat","republican","vote","biden","vance","cabinet","scotus","supreme","pardon","approval","poll","secretary","defense","attorney"],cssColor:"var(--blue)",dimColor:"var(--blue-dim)",rgbColor:[59,130,246]},{name:"Weather",icon:"⛈",subcategories:["Temperature","Storms","Snow","Rain","Hurricanes","Heat","Wind","Climate"],keywords:["temperature","rain","snow","hurricane","weather","tornado","flood","heat","cold","storm","wind","precipitation","climate"],cssColor:"var(--cyan)",dimColor:"var(--cyan-dim)",rgbColor:[0,240,255]},{name:"Technology",icon:"💻",subcategories:["AI","SpaceX","Tesla","Big Tech","Startups","Chips","Cyber","Social"],keywords:["ai","spacex","tesla","apple","google","meta","openai","chatgpt","tech","rocket","launch"],cssColor:"var(--cyan)",dimColor:"var(--cyan-dim)",rgbColor:[0,240,255]},{name:"Crypto",icon:"🪙",subcategories:["Bitcoin","Ethereum","DeFi","NFTs","Regulation","Mining","Stablecoins","Altcoins"],keywords:["bitcoin","btc","ethereum","eth","crypto","token","blockchain","defi"],cssColor:"var(--orange)",dimColor:"var(--orange-dim)",rgbColor:[247,147,26]},{name:"Sports",icon:"🏈",subcategories:["NFL","NBA","MLB","Soccer","Tennis","UFC","Olympics","Playoffs"],keywords:["nfl","nba","mlb","nhl","soccer","tennis","super bowl","championship","game","match","playoff","world series"],cssColor:"var(--purple)",dimColor:"var(--purple-dim)",rgbColor:[168,85,247]},{name:"Energy",icon:"⚡",subcategories:["Oil","Gas","Solar","Nuclear","OPEC","EVs","Grid","Coal"],keywords:["oil","gas","energy","solar","opec","crude","coal","renewable"],cssColor:"var(--orange)",dimColor:"var(--orange-dim)",rgbColor:[247,147,26]},{name:"Culture",icon:"🎬",subcategories:["Movies","Music","Awards","TV","Social Media","Trends","Celebrity","Gaming"],keywords:["oscar","movie","tv","celebrity","grammy","award","music","entertainment"],cssColor:"var(--orange)",dimColor:"var(--orange-dim)",rgbColor:[247,147,26]}];kc.forEach((e,t)=>{e.baseColor=e.rgbColor});function aee(e,t){const[r,n,a]=t,i=Math.max(.05,Math.min(.9,e));return`rgba(${r},${n},${a},${i})`}function iee(e,t){const[r,n,a]=t,i=Math.max(.1,Math.min(.6,e*.8));return`rgba(${r},${n},${a},${i})`}function oee(e,t){const[r,n,a]=t;return e>.5?`rgb(${Math.min(255,r+60)},${Math.min(255,n+60)},${Math.min(255,a+60)})`:e>.2?`rgb(${r},${n},${a})`:"var(--text-muted)"}function see({subcategory:e,intensity:t,signalCount:r,sentiment:n,baseColor:a,onClick:i,isSelected:s}){const l=aee(t,a),c=iee(t,a),u=oee(t,a),f=t>.3;return o.jsxs("div",{onClick:i,className:`relative overflow-hidden rounded-lg cursor-pointer group ${s?"z-10":""}`,style:{backgroundColor:l,border:s?"2px solid var(--cyan)":`1px solid ${c}`,minHeight:70,transform:s?"scale(1.05)":void 0,transition:"all 200ms ease",boxShadow:s?"0 0 16px rgba(0,240,255,0.2)":void 0},children:[f&&o.jsx("div",{className:"absolute inset-0 opacity-10 pointer-events-none",style:{backgroundImage:"repeating-linear-gradient(0deg, transparent, transparent 2px, rgba(255,255,255,0.03) 2px, rgba(255,255,255,0.03) 4px)"}}),t>.6&&o.jsx("div",{className:"absolute inset-0 animate-pulse opacity-30 pointer-events-none",style:{background:`radial-gradient(circle at center, rgba(${a.join(",")},0.4), transparent 70%)`,animationDuration:`${3-t*2}s`}}),o.jsx("div",{className:"absolute inset-0 opacity-0 group-hover:opacity-100 pointer-events-none",style:{background:`radial-gradient(circle at center, rgba(${a.join(",")},0.08), transparent)`,transition:"opacity 150ms ease"}}),o.jsxs("div",{className:"relative p-2.5 h-full flex flex-col justify-between z-10",children:[o.jsx("div",{children:o.jsx("p",{className:"text-[10px] font-bold uppercase tracking-wider",style:{color:u},children:e})}),o.jsxs("div",{className:"flex items-end justify-between mt-1",children:[o.jsx("div",{children:r>0?o.jsx("p",{className:"text-lg font-bold mono",style:{color:u},children:r}):o.jsx("p",{className:"text-sm",style:{color:"var(--text-muted)"},children:"--"})}),n!==0&&o.jsxs("div",{className:"text-[9px] mono font-bold px-1.5 py-0.5 rounded",style:n>0?{background:"var(--green-dim)",color:"var(--green)"}:{background:"var(--red-dim)",color:"var(--red)"},children:[n>0?"+":"",n.toFixed(2)]})]})]}),o.jsx("div",{className:"absolute bottom-0 left-0 right-0 h-0.5",style:{background:`linear-gradient(90deg, transparent, rgba(${a.join(",")},${t}), transparent)`}})]})}function lee({category:e,subcategoryData:t,onCellClick:r,selectedCell:n}){const a=t.reduce((l,c)=>l+c.signalCount,0),i=Math.max(...t.map(l=>l.intensity),0),s=t.reduce((l,c)=>l+c.sentiment,0)/t.length;return o.jsxs("div",{className:"space-y-2",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-lg",children:e.icon}),o.jsx("h3",{className:"text-sm font-bold heading",style:{color:e.cssColor},children:e.name}),o.jsxs("span",{className:"text-[10px]",style:{color:"var(--text-muted)"},children:[a," signals"]})]}),o.jsxs("div",{className:"flex items-center gap-3 text-[10px]",children:[o.jsxs("span",{style:{color:"var(--text-muted)"},children:["Peak:"," ",o.jsxs("span",{className:"font-bold",style:{color:e.cssColor},children:[(i*100).toFixed(0),"%"]})]}),o.jsxs("span",{className:"mono",style:{color:s>0?"var(--green)":s<0?"var(--red)":"var(--text-muted)"},children:["Sentiment: ",s>0?"+":"",s.toFixed(3)]})]})]}),o.jsx("div",{className:"grid grid-cols-8 gap-2",children:t.map(l=>o.jsx(see,{subcategory:l.name,intensity:l.intensity,signalCount:l.signalCount,sentiment:l.sentiment,baseColor:e.baseColor,onClick:()=>r({category:e.name,subcategory:l.name,...l}),isSelected:(n==null?void 0:n.category)===e.name&&(n==null?void 0:n.subcategory)===l.name},l.name))})]})}function cee(){return o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"stat-label",children:"Low"}),o.jsx("div",{className:"flex gap-px",children:Array.from({length:10}).map((t,r)=>o.jsx("div",{className:"w-5 h-3 rounded-sm",style:{backgroundColor:`rgba(0,240,255,${(r+1)/10*.7+.05})`}},r))}),o.jsx("span",{className:"stat-label",children:"High"})]})}function uee({cell:e,signals:t,onClose:r}){if(!e)return null;const n=t.filter(a=>{var s;const i=(a.reasoning||a.ticker||"").toLowerCase();return(s=e.matchingKeywords)==null?void 0:s.some(l=>i.includes(l))}).slice(0,10);return o.jsxs("div",{className:"card-glow fade-in",children:[o.jsxs("div",{className:"flex items-start justify-between mb-3",children:[o.jsxs("div",{children:[o.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[o.jsx("span",{className:"text-lg",children:e.categoryIcon}),o.jsxs("h3",{className:"heading text-sm font-bold",style:{color:"var(--text)"},children:[e.category," / ",e.subcategory]})]}),o.jsxs("p",{className:"text-xs",style:{color:"var(--text-muted)"},children:[e.signalCount," signals | Intensity: ",(e.intensity*100).toFixed(0),"% | Sentiment:"," ",o.jsxs("span",{style:{color:e.sentiment>0?"var(--green)":e.sentiment<0?"var(--red)":"var(--text-dim)"},children:[e.sentiment>0?"+":"",e.sentiment.toFixed(3)]})]})]}),o.jsx("button",{onClick:r,className:"btn btn-ghost text-lg leading-none",style:{padding:"0 6px"},children:"×"})]}),n.length>0?o.jsxs("div",{className:"space-y-2",children:[o.jsx("p",{className:"stat-label mb-1",children:"Related Signals"}),n.map((a,i)=>o.jsxs("div",{className:"flex items-center gap-3 text-xs rounded-lg px-3 py-2",style:{background:"var(--surface-el)",border:"1px solid var(--border)"},children:[o.jsx("span",{className:"badge",style:a.direction==="BUY_YES"?{background:"var(--green-dim)",color:"var(--green)"}:{background:"var(--red-dim)",color:"var(--red)"},children:a.direction}),o.jsx("span",{className:"mono truncate flex-1",style:{color:"var(--text-dim)"},children:a.ticker}),o.jsxs("span",{className:"mono font-bold",style:{color:"var(--orange)"},children:[(parseFloat(a.expected_edge)*100).toFixed(1),"%"]}),o.jsxs("span",{className:"mono",style:{color:"var(--blue)"},children:[(parseFloat(a.confidence)*100).toFixed(0),"%"]}),a.risk_approved?o.jsx("span",{className:"text-[9px] font-bold",style:{color:"var(--green)"},children:"OK"}):o.jsx("span",{className:"text-[9px] font-bold",style:{color:"var(--red)"},children:"BLOCKED"})]},i))]}):o.jsx("p",{className:"text-sm text-center py-4",style:{color:"var(--text-muted)"},children:"No matching signals for this subcategory"})]})}function dee({categoryStats:e}){const t=Math.max(...e.map(r=>r.totalSignals),1);return o.jsxs("div",{className:"card",children:[o.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[o.jsx("h2",{className:"section-title",children:"National Activity Overview"}),o.jsx("span",{className:"section-subtitle",children:"Signal density across categories"})]}),o.jsx("div",{className:"space-y-2",children:e.sort((r,n)=>n.totalSignals-r.totalSignals).map(r=>{const n=r.totalSignals/t*100;return o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("span",{className:"text-sm w-5",children:r.icon}),o.jsx("span",{className:"text-xs font-medium w-20 heading",style:{color:r.cssColor||`rgb(${r.baseColor.join(",")})`},children:r.name}),o.jsxs("div",{className:"flex-1 h-5 rounded-full overflow-hidden relative",style:{background:"var(--surface-el)"},children:[o.jsx("div",{className:"h-full rounded-full transition-all duration-1000 relative overflow-hidden",style:{width:`${Math.max(n,2)}%`,background:`linear-gradient(90deg, rgba(${r.baseColor.join(",")},0.3), rgba(${r.baseColor.join(",")},0.6))`},children:o.jsx("div",{className:"absolute inset-0",style:{background:"linear-gradient(90deg, transparent 0%, rgba(255,255,255,0.1) 50%, transparent 100%)",animation:"shimmer 2s infinite"}})}),o.jsx("span",{className:"absolute right-2 top-0 bottom-0 flex items-center text-[10px] mono",style:{color:"var(--text-dim)"},children:r.totalSignals})]}),o.jsxs("span",{className:"text-[10px] mono w-12 text-right",style:{color:r.avgSentiment>0?"var(--green)":r.avgSentiment<0?"var(--red)":"var(--text-muted)"},children:[r.avgSentiment>0?"+":"",r.avgSentiment.toFixed(2)]})]},r.name)})})]})}function fee(){const[e,t]=P.useState(null),[r,n]=P.useState(null),[a,i]=P.useState(null),[s,l]=P.useState(!0),[c,u]=P.useState(null),[f,d]=P.useState("24h");P.useEffect(()=>{h();const v=setInterval(h,3e4);return()=>clearInterval(v)},[]);async function h(){try{const[v,m,x]=await Promise.all([Oe("/dashboard"),Oe("/signals"),Oe("/signals/dashboard")]);t(v),n((m==null?void 0:m.signals)||[]),i(x)}catch{}l(!1)}const{categoryData:p,categoryStats:g,overallStats:y}=P.useMemo(()=>{var w;if(!r)return{categoryData:[],categoryStats:[],overallStats:{}};const v=r||[],m=Math.max(...kc.flatMap(_=>_.subcategories.map(O=>(_.keywords.filter(k=>O.toLowerCase().includes(k.split(" ")[0])||k.includes(O.toLowerCase())),v.filter(k=>{const E=(k.reasoning||k.ticker||"").toLowerCase();return _.keywords.some(T=>E.includes(T))}).length))),1),x=kc.map(_=>{const O=v.filter(k=>{const E=(k.reasoning||k.ticker||"").toLowerCase();return _.keywords.some(T=>E.includes(T))});O.length,O.length>0&&O.reduce((k,E)=>{const T=(E.sources||[]).reduce((D,A)=>D+(A.sentiment||0),0);return k+T},0)/Math.max(O.length,1);const N=_.subcategories.map(k=>{const E=_.keywords.filter(C=>{const M=k.toLowerCase();return C.includes(M)||M.includes(C.split(" ")[0])});let T;if(E.length>0)T=v.filter(C=>{const M=(C.reasoning||C.ticker||"").toLowerCase();return E.some(I=>M.includes(I))});else{const C=k.split("").reduce((M,I)=>(M<<5)-M+I.charCodeAt(0)|0,0);T=O.filter((M,I)=>I%_.subcategories.length===Math.abs(C)%_.subcategories.length)}const D=T.length,A=T.reduce((C,M)=>{const I=(M.sources||[]).reduce((R,F)=>R+(F.sentiment||0),0);return C+I},0)/Math.max(T.length,1),L=Math.min(1,D/Math.max(m*.5,1));return{name:k,signalCount:D,sentiment:A,intensity:L,matchingKeywords:E.length>0?E:_.keywords,categoryIcon:_.icon}});return{category:_,subcategoryData:N}}),S=kc.map(_=>{const O=v.filter(N=>{const k=(N.reasoning||N.ticker||"").toLowerCase();return _.keywords.some(E=>k.includes(E))});return{name:_.name,icon:_.icon,baseColor:_.baseColor,cssColor:_.cssColor,totalSignals:O.length,avgSentiment:O.length>0?O.reduce((N,k)=>N+(k.sources||[]).reduce((E,T)=>E+(T.sentiment||0),0),0)/O.length:0}}),j={totalSignals:v.length,buyYes:v.filter(_=>_.direction==="BUY_YES").length,buyNo:v.filter(_=>_.direction==="BUY_NO").length,approved:v.filter(_=>_.risk_approved).length,avgEdge:v.length>0?v.reduce((_,O)=>_+parseFloat(O.expected_edge||0),0)/v.length:0,avgConf:v.length>0?v.reduce((_,O)=>_+parseFloat(O.confidence||0),0)/v.length:0,hottest:((w=[...S].sort((_,O)=>O.totalSignals-_.totalSignals)[0])==null?void 0:w.name)||"None"};return{categoryData:x,categoryStats:S,overallStats:j}},[r]);if(s)return o.jsx("div",{className:"flex items-center justify-center h-64",children:o.jsx("div",{className:"w-8 h-8 rounded-full border-2 border-t-transparent animate-spin",style:{borderColor:"var(--cyan)",borderTopColor:"transparent"}})});const b=[{label:"Total Signals",value:y.totalSignals||0,color:"var(--cyan)"},{label:"BUY YES",value:y.buyYes||0,color:"var(--green)"},{label:"BUY NO",value:y.buyNo||0,color:"var(--red)"},{label:"Approved",value:y.approved||0,color:"var(--green)"},{label:"Avg Edge",value:`${((y.avgEdge||0)*100).toFixed(1)}%`,color:"var(--orange)"},{label:"Avg Confidence",value:`${((y.avgConf||0)*100).toFixed(0)}%`,color:"var(--blue)"},{label:"Hottest Sector",value:y.hottest,color:"var(--red)"}];return o.jsxs("div",{className:"space-y-6",children:[o.jsx("style",{children:`
- @keyframes shimmer {
- 0% { transform: translateX(-100%); }
- 100% { transform: translateX(200%); }
- }
- `}),o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{children:[o.jsxs("h1",{className:"heading text-2xl font-bold flex items-center gap-3",children:[o.jsx("span",{className:"inline-flex items-center justify-center w-3 h-3 rounded-full pulse-cyan",style:{backgroundColor:"var(--cyan)",flexShrink:0}}),o.jsx("span",{className:"gradient-cyan",children:"Pulse of America"})]}),o.jsx("p",{className:"section-subtitle mt-1",children:"Sentiment and activity heatmap across American prediction markets"})]}),o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("div",{className:"flex items-center gap-0.5 rounded-lg p-0.5",style:{background:"var(--surface-el)",border:"1px solid var(--border)"},children:["24h","7d","30d"].map(v=>o.jsx("button",{onClick:()=>d(v),className:"btn btn-sm",style:f===v?{background:"var(--cyan)",color:"var(--bg)",fontWeight:700}:{background:"transparent",color:"var(--text-muted)"},children:v},v))}),o.jsx("button",{onClick:h,className:"btn btn-o btn-sm",children:"Refresh"})]})]}),o.jsx("div",{className:"grid grid-cols-7 gap-3",children:b.map(v=>o.jsxs("div",{className:"card",children:[o.jsx("p",{className:"stat-label mb-1",children:v.label}),o.jsx("p",{className:"stat-v text-lg",style:{color:v.color},children:v.value})]},v.label))}),o.jsx(dee,{categoryStats:g}),o.jsxs("div",{className:"card p-4",children:[o.jsxs("div",{className:"flex items-center justify-between mb-5",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("div",{className:"w-2 h-2 rounded-full animate-pulse",style:{backgroundColor:"var(--red)"}}),o.jsx("h2",{className:"section-title",children:"Live Signal Heatmap"})]}),o.jsx(cee,{})]}),o.jsx("div",{className:"space-y-5",children:p.map(({category:v,subcategoryData:m})=>o.jsx(lee,{category:v,subcategoryData:m,onCellClick:x=>u((c==null?void 0:c.category)===x.category&&(c==null?void 0:c.subcategory)===x.subcategory?null:x),selectedCell:c},v.name))})]}),c&&o.jsx(uee,{cell:c,signals:r||[],onClose:()=>u(null)}),o.jsxs("div",{className:"card",children:[o.jsx("div",{className:"flex items-center gap-2 mb-4",children:o.jsx("h2",{className:"section-title",children:"Signal Source Breakdown"})}),o.jsx("div",{className:"grid grid-cols-4 gap-3",children:((a==null?void 0:a.sourceBreakdown)||[]).slice(0,8).map(v=>{const m=parseFloat(v.avg_sent)||0,x=parseInt(v.cnt)||0;return o.jsxs("div",{className:"rounded-lg p-3",style:{background:"var(--surface-el)",border:"1px solid var(--border)"},children:[o.jsxs("div",{className:"flex items-center justify-between mb-2",children:[o.jsx("span",{className:"text-xs font-bold heading",style:{color:"var(--text-dim)"},children:v.source.replace("_"," ").toUpperCase()}),o.jsx("span",{className:"mono text-xs font-bold",style:{color:"var(--orange)"},children:x})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("div",{className:"progress-bar flex-1",children:o.jsx("div",{className:"progress-fill",style:{width:`${Math.min(100,Math.abs(m)*5e3+10)}%`,background:m>0?"var(--green)":m<0?"var(--red)":"var(--text-muted)"}})}),o.jsxs("span",{className:"text-[10px] mono",style:{color:m>0?"var(--green)":m<0?"var(--red)":"var(--text-muted)"},children:[m>0?"+":"",m.toFixed(3)]})]})]},v.source)})})]}),e&&o.jsxs("div",{className:"card",children:[o.jsx("div",{className:"flex items-center gap-2 mb-4",children:o.jsx("h2",{className:"section-title",children:"Market Pulse Metrics"})}),o.jsx("div",{className:"grid grid-cols-5 gap-3 text-center",children:[{label:"Balance",value:`$${e.balance?(e.balance/100).toLocaleString(void 0,{minimumFractionDigits:0}):"0"}`,color:"var(--green)"},{label:"Today's P&L",value:`${(e.daily_pnl||0)>=0?"+":""}$${((e.daily_pnl||0)/100).toFixed(2)}`,color:(e.daily_pnl||0)>=0?"var(--green)":"var(--red)"},{label:"Today's Trades",value:(e.today_trades||0).toLocaleString(),color:"var(--orange)"},{label:"Win Rate",value:`${e.today_trades>0?(e.today_wins/e.today_trades*100).toFixed(1):"0"}%`,color:e.today_trades>0&&e.today_wins/e.today_trades*100>=50?"var(--green)":"var(--red)"},{label:"Markets Tracked",value:e.markets_tracked||0,color:"var(--purple)"}].map(v=>o.jsxs("div",{className:"rounded-lg p-3",style:{background:"var(--surface-el)",border:"1px solid var(--border)"},children:[o.jsx("p",{className:"stat-label mb-1",children:v.label}),o.jsx("p",{className:"stat-v text-lg",style:{color:v.color},children:v.value})]},v.label))})]})]})}function hee(){return o.jsx(EC,{children:o.jsxs(_C,{children:[o.jsx(it,{path:"/login",element:o.jsx(WC,{})}),o.jsx(it,{path:"/setup",element:o.jsx(oE,{})}),o.jsxs(it,{path:"/",element:o.jsx(YC,{}),children:[o.jsx(it,{index:!0,element:o.jsx(cZ,{})}),o.jsx(it,{path:"markets",element:o.jsx(fZ,{})}),o.jsx(it,{path:"positions",element:o.jsx(vZ,{})}),o.jsx(it,{path:"orders",element:o.jsx(xZ,{})}),o.jsx(it,{path:"signals",element:o.jsx(WZ,{})}),o.jsx(it,{path:"intelligence",element:o.jsx(KZ,{})}),o.jsx(it,{path:"trading",element:o.jsx(VZ,{})}),o.jsx(it,{path:"heatmap",element:o.jsx(ZZ,{})}),o.jsx(it,{path:"orbit",element:o.jsx(nee,{})}),o.jsx(it,{path:"pulse",element:o.jsx(fee,{})}),o.jsx(it,{path:"weather",element:o.jsx(bZ,{})}),o.jsx(it,{path:"risk",element:o.jsx(CZ,{})}),o.jsx(it,{path:"settings",element:o.jsx(IZ,{})})]})]})})}xh.createRoot(document.getElementById("root")).render(o.jsx(hee,{}));
diff --git a/kalshi-dash/dist/index.html b/kalshi-dash/dist/index.html
deleted file mode 100644
index f507deb..0000000
--- a/kalshi-dash/dist/index.html
+++ /dev/null
@@ -1,16 +0,0 @@
-<!DOCTYPE html>
-<html lang="en">
-<head>
- <meta charset="UTF-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
- <title>Ken - Event Contracts Trading</title>
- <link rel="preconnect" href="https://fonts.googleapis.com" />
- <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
- <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&family=Space+Grotesk:wght@500;600;700&family=JetBrains+Mono:wght@400;500;600&display=swap" rel="stylesheet" />
- <script type="module" crossorigin src="/assets/index-_K_ynK5-.js"></script>
- <link rel="stylesheet" crossorigin href="/assets/index-BXhqt972.css">
-</head>
-<body>
- <div id="root"></div>
-</body>
-</html>
diff --git a/kalshi-dash/server.js.bak-20260422-160936 b/kalshi-dash/server.js.bak-20260422-160936
new file mode 100644
index 0000000..88fc2dd
--- /dev/null
+++ b/kalshi-dash/server.js.bak-20260422-160936
@@ -0,0 +1,9128 @@
+import http from 'http';
+import fs from 'fs';
+import path from 'path';
+import { fileURLToPath } from 'url';
+import pg from 'pg';
+import crypto from 'crypto';
+import { OAuth2Client } from 'google-auth-library';
+import { Worker, isMainThread, parentPort, workerData } from 'worker_threads';
+import os from 'os';
+
+const __filename = fileURLToPath(import.meta.url);
+const __dirname = path.dirname(__filename);
+
+const PORT = 7810;
+const DIST = path.join(__dirname, 'dist');
+
+// ── Unified DW Auth Config ──
+const AUTH_USER = 'admin';
+const AUTH_PASS = 'DWSecure2024!';
+const SESSION_COOKIE = 'kalshi_session';
+const SESSION_MAX_AGE = 30 * 24 * 60 * 60; // 30 days in seconds
+const WHITELISTED_IPS = ['127.0.0.1', '::1', '45.61.58.125', 'localhost'];
+
+// ── Slack Alerts ──
+const SLACK_WEBHOOK = 'https://hooks.slack.com/services/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';
+
+async function sendSlack(text) {
+ // Slack notifications disabled per Steve
+ return;
+}
+
+// ── Google OAuth Config ──
+const GOOGLE_CLIENT_ID = process.env.GOOGLE_CLIENT_ID || '';
+const ALLOWED_EMAILS = (process.env.ALLOWED_EMAILS || '').split(',').filter(Boolean);
+const googleClient = GOOGLE_CLIENT_ID ? new OAuth2Client(GOOGLE_CLIENT_ID) : null;
+
+// ── NWS Weather Config ──
+const NWS_BASE = 'https://api.weather.gov';
+const NWS_USER_AGENT = 'Ken-Bot/1.0 (steve@designerwallcoverings.com)';
+
+const CITY_COORDS = {
+ 'New York': { lat: 40.7128, lon: -74.0060 },
+ 'Los Angeles': { lat: 34.0522, lon: -118.2437 },
+ 'Chicago': { lat: 41.8781, lon: -87.6298 },
+ 'Houston': { lat: 29.7604, lon: -95.3698 },
+ 'Phoenix': { lat: 33.4484, lon: -112.0740 },
+ 'Philadelphia': { lat: 39.9526, lon: -75.1652 },
+ 'Dallas': { lat: 32.7767, lon: -96.7970 },
+ 'San Francisco': { lat: 37.7749, lon: -122.4194 },
+ 'Seattle': { lat: 47.6062, lon: -122.3321 },
+ 'Denver': { lat: 39.7392, lon: -104.9903 },
+ 'Boston': { lat: 42.3601, lon: -71.0589 },
+ 'Miami': { lat: 25.7617, lon: -80.1918 },
+ 'Atlanta': { lat: 33.7490, lon: -84.3880 },
+ 'Minneapolis': { lat: 44.9778, lon: -93.2650 },
+ 'Washington': { lat: 38.9072, lon: -77.0369 },
+ 'Las Vegas': { lat: 36.1699, lon: -115.1398 },
+};
+
+async function nwsFetch(url) {
+ const controller = new AbortController();
+ // Hard Promise.race timeout — AbortController alone can't kill DNS-level hangs
+ const hardTimeout = new Promise((_, reject) =>
+ setTimeout(() => { controller.abort(); reject(new Error('NWS timeout (5s)')); }, 5000)
+ );
+ const doFetch = async () => {
+ const res = await fetch(url, {
+ headers: { 'User-Agent': NWS_USER_AGENT, 'Accept': 'application/geo+json' },
+ signal: controller.signal,
+ });
+ if (!res.ok) throw new Error(`NWS ${res.status}: ${res.statusText}`);
+ return res.json();
+ };
+ return Promise.race([doFetch(), hardTimeout]);
+}
+
+function extractForecastFeatures(forecastData, variable) {
+ const periods = forecastData?.properties?.periods || [];
+ if (!periods.length) return null;
+ const features = { variable, values: [], timestamps: [] };
+ for (const p of periods) {
+ let value = null;
+ if (variable === 'temperature') { value = p.temperature; features.unit = p.temperatureUnit; }
+ else if (variable === 'wind') { const m = p.windSpeed?.match(/(\d+)/); if (m) value = parseInt(m[1]); features.unit = 'mph'; }
+ else if (variable === 'precipitation') { value = p.probabilityOfPrecipitation?.value ?? 0; features.unit = 'percent'; }
+ if (value !== null) { features.values.push(value); features.timestamps.push(p.startTime); }
+ }
+ if (features.values.length) {
+ features.mean = features.values.reduce((a, b) => a + b, 0) / features.values.length;
+ features.min = Math.min(...features.values);
+ features.max = Math.max(...features.values);
+ features.latest = features.values[0];
+ }
+ return features;
+}
+
+// ── Prediction Model ──
+function ensembleExceedance(features, threshold, operator = '>=') {
+ const vals = features?.values || [];
+ if (!vals.length) return null;
+ let ct = 0;
+ for (const v of vals) {
+ if (operator === '>=' && v >= threshold) ct++;
+ else if (operator === '<=' && v <= threshold) ct++;
+ else if (operator === '>' && v > threshold) ct++;
+ else if (operator === '<' && v < threshold) ct++;
+ }
+ return ct / vals.length;
+}
+
+function climatologicalPrior(variable, threshold, month) {
+ const season = month >= 6 && month <= 8 ? 'summer' : month >= 12 || month <= 2 ? 'winter' : month >= 3 && month <= 5 ? 'spring' : 'fall';
+ const priors = {
+ temperature: { summer: t => t > 100 ? 0.05 : t > 90 ? 0.35 : t > 80 ? 0.65 : 0.85, winter: t => t > 60 ? 0.15 : t > 40 ? 0.50 : t > 20 ? 0.75 : 0.90, spring: t => t > 80 ? 0.20 : t > 60 ? 0.55 : t > 40 ? 0.80 : 0.95, fall: t => t > 80 ? 0.25 : t > 60 ? 0.50 : t > 40 ? 0.75 : 0.90 },
+ precipitation: { any: t => t > 2 ? 0.10 : t > 1 ? 0.20 : t > 0.5 ? 0.35 : 0.50 },
+ snow: { winter: t => t > 12 ? 0.05 : t > 6 ? 0.15 : t > 3 ? 0.25 : 0.40, any: () => 0.10 },
+ };
+ const vp = priors[variable]; if (!vp) return 0.50;
+ const fn = vp[season] || vp.any; if (!fn) return 0.50;
+ return fn(threshold);
+}
+
+function bayesianUpdate(prior, forecastProb, weight = 0.7) {
+ return prior * (1 - weight) + forecastProb * weight;
+}
+
+// ══════════════════════════════════════════════════════
+// GEMINI AI PREDICTION ENGINE — uses CPU + AI for better signals
+// ══════════════════════════════════════════════════════
+const GEMINI_API_KEY = 'AIzaSyAO0rLKwtJUKcf3zVmKstBS4udct4QejMo';
+const GEMINI_MODEL = 'gemini-2.0-flash';
+
+async function geminiAnalyze(prompt, maxTokens = 1024) {
+ try {
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), 25000);
+ const res = await fetch(
+ `https://generativelanguage.googleapis.com/v1beta/models/${GEMINI_MODEL}:generateContent?key=${GEMINI_API_KEY}`,
+ {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ signal: controller.signal,
+ body: JSON.stringify({
+ contents: [{ parts: [{ text: prompt }] }],
+ generationConfig: { temperature: 0.3, maxOutputTokens: maxTokens },
+ }),
+ }
+ );
+ clearTimeout(timeout);
+ if (!res.ok) return null;
+ const data = await res.json();
+ return data?.candidates?.[0]?.content?.parts?.[0]?.text || null;
+ } catch (e) {
+ console.log(`[Ken/Gemini] Error: ${e.message}`);
+ return null;
+ }
+}
+
+// AI-Enhanced Signal Scoring — Gemini analyzes top signals for smarter predictions
+let geminiCallCount = 0;
+const GEMINI_DAILY_LIMIT = 200; // budget: ~200 calls/day
+const geminiCallReset = setInterval(() => { geminiCallCount = 0; }, 24 * 60 * 60 * 1000);
+
+async function aiEnhanceSignal(signal, articles, market) {
+ if (geminiCallCount >= GEMINI_DAILY_LIMIT) return signal;
+ geminiCallCount++;
+
+ const articleSummary = articles.slice(0, 8).map((a, i) =>
+ `${i + 1}. [${a.source}] ${a.headline?.substring(0, 150)}`
+ ).join('\n');
+
+ const prompt = `You are Ken, an expert prediction market analyst. Analyze this trading signal and provide a calibrated probability estimate.
+
+MARKET: "${market.title}" ${market.subtitle ? '- ' + market.subtitle : ''}
+CURRENT PRICE: YES at ${market.yes_ask}¢, NO at ${100 - market.yes_ask}¢
+24H VOLUME: ${market.volume_24h?.toLocaleString() || '?'}
+OUR SIGNAL: ${signal.direction} with ${(Math.abs(signal.expectedEdge) * 100).toFixed(1)}% edge
+
+RECENT NEWS (${articles.length} articles):
+${articleSummary}
+
+SENTIMENT ANALYSIS: category=${articles[0]?.category || '?'}, direction=${articles[0]?.direction || '?'}, agreement=${((signal.agreement || 0) * 100).toFixed(0)}%
+
+Respond with ONLY a JSON object (no markdown):
+{"probability": 0.XX, "confidence": 0.XX, "reasoning": "one sentence", "adjustedEdge": X.XX, "riskFlag": "none|caution|high_risk"}`;
+
+ const response = await geminiAnalyze(prompt, 256);
+ if (!response) return signal;
+
+ try {
+ // Parse JSON from response (handle markdown wrapping)
+ const jsonStr = response.replace(/```json\n?/g, '').replace(/```\n?/g, '').trim();
+ const ai = JSON.parse(jsonStr);
+
+ // Blend AI probability with our statistical model
+ const blendedEdge = signal.expectedEdge * 0.6 + (ai.adjustedEdge || signal.expectedEdge) * 0.4;
+ const blendedConf = signal.confidence * 0.5 + (ai.confidence || signal.confidence) * 0.5;
+
+ return {
+ ...signal,
+ expectedEdge: blendedEdge,
+ confidence: Math.min(0.95, blendedConf),
+ aiProbability: ai.probability,
+ aiReasoning: ai.reasoning,
+ aiRiskFlag: ai.riskFlag || 'none',
+ aiEnhanced: true,
+ };
+ } catch (e) {
+ console.log(`[Ken/Gemini] Parse error: ${e.message}`);
+ return signal;
+ }
+}
+
+// ══════════════════════════════════════════════════════
+// MONTE CARLO SIMULATION — CPU-intensive probability estimation
+// ══════════════════════════════════════════════════════
+function monteCarloSimulation(params, iterations = 10000) {
+ const { priorProb, sentimentImpact, momentum2h, momentum6h, volume24h, spread, articleCount, agreement } = params;
+
+ let successCount = 0;
+ const edgeDistribution = [];
+
+ for (let i = 0; i < iterations; i++) {
+ // Add noise to each factor (simulating uncertainty)
+ const sentimentNoise = sentimentImpact + (Math.random() - 0.5) * 0.15;
+ const momentumNoise = (momentum2h || 0) / 100 + (Math.random() - 0.5) * 0.08;
+ const volumeSignal = Math.min(1, (volume24h || 0) / 10000) * (Math.random() * 0.1);
+ const spreadPenalty = Math.max(0, (spread || 0) - 3) * -0.005 * Math.random();
+ const articleBoost = Math.min(0.1, (articleCount || 0) * 0.01) * Math.random();
+ const agreementBoost = ((agreement || 0.5) - 0.5) * 0.15 * Math.random();
+
+ // Simulate probability with all factors
+ const simProb = Math.max(0.01, Math.min(0.99,
+ priorProb + sentimentNoise + momentumNoise + volumeSignal + spreadPenalty + articleBoost + agreementBoost
+ ));
+
+ // Compare to market price — is there an edge?
+ const marketProb = priorProb;
+ const simEdge = simProb - marketProb;
+
+ if (Math.abs(simEdge) >= 0.05) successCount++;
+ edgeDistribution.push(simEdge);
+ }
+
+ // Calculate statistics from simulation
+ edgeDistribution.sort((a, b) => a - b);
+ const mean = edgeDistribution.reduce((a, b) => a + b, 0) / iterations;
+ const p5 = edgeDistribution[Math.floor(iterations * 0.05)];
+ const p25 = edgeDistribution[Math.floor(iterations * 0.25)];
+ const p50 = edgeDistribution[Math.floor(iterations * 0.50)];
+ const p75 = edgeDistribution[Math.floor(iterations * 0.75)];
+ const p95 = edgeDistribution[Math.floor(iterations * 0.95)];
+ const stdDev = Math.sqrt(edgeDistribution.reduce((sum, e) => sum + Math.pow(e - mean, 2), 0) / iterations);
+
+ return {
+ meanEdge: mean,
+ medianEdge: p50,
+ stdDev,
+ confidence: successCount / iterations,
+ percentiles: { p5, p25, p50, p75, p95 },
+ iterations,
+ edgeConsistent: Math.sign(p25) === Math.sign(p75), // Is edge direction consistent?
+ };
+}
+
+// ══════════════════════════════════════════════════════
+// PARALLEL PROCESSING — run CPU-heavy tasks across cores
+// ══════════════════════════════════════════════════════
+const CPU_CORES = Math.max(2, os.cpus().length);
+const WORKER_POOL_SIZE = Math.min(12, CPU_CORES - 2); // Use up to 14 cores, leave 2 for OS + other services
+
+function runInParallel(tasks, workerFn) {
+ return Promise.all(tasks.map(task => {
+ return new Promise(resolve => {
+ try {
+ resolve(workerFn(task));
+ } catch (e) {
+ resolve({ error: e.message, task });
+ }
+ });
+ }));
+}
+
+// Batch process markets in parallel chunks
+async function parallelMarketAnalysis(markets, analysisFunc, batchSize = 50) {
+ const results = [];
+ const batches = [];
+ for (let i = 0; i < markets.length; i += batchSize) {
+ batches.push(markets.slice(i, i + batchSize));
+ }
+
+ // Process batches concurrently (up to WORKER_POOL_SIZE at once)
+ for (let i = 0; i < batches.length; i += WORKER_POOL_SIZE) {
+ const concurrent = batches.slice(i, i + WORKER_POOL_SIZE);
+ const batchResults = await Promise.all(concurrent.map(batch =>
+ Promise.all(batch.map(m => analysisFunc(m).catch(e => ({ error: e.message, ticker: m.ticker }))))
+ ));
+ results.push(...batchResults.flat());
+ }
+ return results;
+}
+
+// Parse Kalshi weather market title into event spec
+function parseWeatherEvent(title) {
+ const t = (title || '').toLowerCase();
+ let variable = 'unknown', threshold = 80, operator = '>=';
+ const tempMatch = t.match(/(\d+)\s*°?\s*f/);
+ // Detect temperature events
+ if (t.includes('temperature') || t.includes('temp') || t.includes('°f') || t.includes('degrees') || t.includes('high') || t.includes('low') || t.includes('cold') || t.includes('hot') || t.includes('warm') || t.includes('heat')) {
+ variable = 'temperature';
+ if (tempMatch) threshold = parseInt(tempMatch[1]);
+ }
+ if (t.includes('rain') || t.includes('precipitation') || t.includes('inch')) { variable = 'precipitation'; threshold = tempMatch ? parseInt(tempMatch[1]) : 0.1; }
+ if (t.includes('snow')) { variable = 'snow'; threshold = tempMatch ? parseInt(tempMatch[1]) : 1; }
+ if (t.includes('wind') || t.includes('gust')) { variable = 'wind'; threshold = tempMatch ? parseInt(tempMatch[1]) : 40; }
+ if (t.includes('below') || t.includes('under') || t.includes('less')) operator = '<=';
+ if (t.includes('above') || t.includes('over') || t.includes('exceed') || t.includes('at least')) operator = '>=';
+ return { variable, threshold, operator };
+}
+
+// Extract city from market title
+function extractCity(title) {
+ for (const city of Object.keys(CITY_COORDS)) {
+ if (title.toLowerCase().includes(city.toLowerCase())) return city;
+ }
+ return null;
+}
+
+// ── Kalshi API Config ──
+let KALSHI_ENV = (process.env.KALSHI_ENV || 'demo').toLowerCase();
+const KALSHI_BASE_URLS = {
+ demo: 'https://demo-api.kalshi.co/trade-api/v2',
+ prod: 'https://api.elections.kalshi.com/trade-api/v2',
+};
+let KALSHI_BASE_URL = KALSHI_BASE_URLS[KALSHI_ENV] || KALSHI_BASE_URLS.demo;
+
+// Refresh env from DB config (called on startup and mode changes)
+async function refreshKalshiEnv() {
+ try {
+ const result = await pool.query('SELECT config FROM risk_state ORDER BY updated_at DESC LIMIT 1');
+ const cfg = result.rows[0]?.config || {};
+ if (cfg.kalshi_env && KALSHI_BASE_URLS[cfg.kalshi_env]) {
+ KALSHI_ENV = cfg.kalshi_env;
+ KALSHI_BASE_URL = KALSHI_BASE_URLS[KALSHI_ENV];
+ }
+ } catch {}
+}
+
+// ── Database ──
+const pool = new pg.Pool({
+ connectionString: 'postgresql://dw_admin:DW2024SecurePass@127.0.0.1:5432/bertha_betting',
+ max: 10,
+ idleTimeoutMillis: 30000,
+});
+
+const MIME = {
+ '.html': 'text/html', '.js': 'application/javascript', '.css': 'text/css',
+ '.json': 'application/json', '.png': 'image/png', '.svg': 'image/svg+xml',
+ '.ico': 'image/x-icon', '.woff2': 'font/woff2', '.woff': 'font/woff',
+ '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif',
+ '.webp': 'image/webp', '.map': 'application/json', '.txt': 'text/plain',
+};
+
+// ── DB Helper ──
+async function q(text, params) {
+ return pool.query(text, params);
+}
+
+// ── Response Helper ──
+function json(res, data, status = 200, extraHeaders = {}) {
+ res.writeHead(status, {
+ 'Content-Type': 'application/json',
+ 'Access-Control-Allow-Origin': '*',
+ 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
+ 'Access-Control-Allow-Headers': 'Content-Type, Authorization',
+ ...extraHeaders,
+ });
+ res.end(JSON.stringify(data));
+}
+
+// ── Body Parser ──
+async function readBody(req) {
+ return new Promise(resolve => {
+ let d = '';
+ req.on('data', c => d += c);
+ req.on('end', () => { try { resolve(JSON.parse(d)); } catch { resolve({}); } });
+ });
+}
+
+// ── Cookie / Session Helpers ──
+function parseCookies(req) {
+ const obj = {};
+ (req.headers.cookie || '').split(';').forEach(c => {
+ const [k, ...v] = c.trim().split('=');
+ if (k) obj[k] = v.join('=');
+ });
+ return obj;
+}
+
+function getSession(req) {
+ const cookies = parseCookies(req);
+ const token = cookies[SESSION_COOKIE];
+ if (!token) return null;
+ try {
+ const data = JSON.parse(Buffer.from(decodeURIComponent(token), 'base64').toString());
+ if (!data.authenticated) return null;
+ const age = Date.now() - data.loginTime;
+ if (age > SESSION_MAX_AGE * 1000) return null;
+ return data;
+ } catch { return null; }
+}
+
+function getClientIP(req) {
+ return req.headers['x-forwarded-for']?.split(',')[0]?.trim() || req.socket.remoteAddress || '';
+}
+
+function isWhitelistedIP(req) {
+ const ip = getClientIP(req);
+ return WHITELISTED_IPS.some(w => ip.includes(w));
+}
+
+function hasBasicAuth(req) {
+ const auth = req.headers.authorization;
+ if (!auth || !auth.startsWith('Basic ')) return false;
+ const [user, pass] = Buffer.from(auth.split(' ')[1], 'base64').toString().split(':');
+ return user === AUTH_USER && pass === AUTH_PASS;
+}
+
+function isAuthenticated(req) {
+ if (isWhitelistedIP(req)) return true;
+ if (hasBasicAuth(req)) return true;
+ if (getSession(req)) return true;
+ return false;
+}
+
+function setSessionCookie(res, sessionToken) {
+ return `${SESSION_COOKIE}=${encodeURIComponent(sessionToken)}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${SESSION_MAX_AGE}`;
+}
+
+function clearSessionCookie() {
+ return `${SESSION_COOKIE}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0`;
+}
+
+// ── Kalshi API Signing ──
+// RSA-PSS with SHA-256, salt length 32
+// Signs: timestamp_ms_string + method_uppercase + path
+function signKalshiRequest(privateKeyPem, timestampMs, method, requestPath) {
+ const message = timestampMs + method.toUpperCase() + requestPath;
+ const signature = crypto.sign('sha256', Buffer.from(message), {
+ key: privateKeyPem,
+ padding: crypto.constants.RSA_PKCS1_PSS_PADDING,
+ saltLength: 32,
+ });
+ return signature.toString('base64');
+}
+
+// ── Kalshi Authenticated Fetch ──
+async function kalshiFetch(method, apiPath, body = null) {
+ // Load keys from DB
+ const result = await q('SELECT config FROM risk_state ORDER BY updated_at DESC LIMIT 1');
+ const cfg = result.rows[0]?.config || {};
+
+ const apiKey = cfg.kalshi_api_key;
+ const privateKeyPem = cfg.kalshi_private_key;
+
+ if (!apiKey || !privateKeyPem) {
+ throw new Error('Kalshi API keys not configured. Please save your API key and private key first.');
+ }
+
+ const timestampMs = Date.now().toString();
+ // The path for signing is everything after the base domain, starting with /trade-api/v2
+ const basePath = KALSHI_ENV === 'prod' ? '/trade-api/v2' : '/trade-api/v2';
+ const fullSignPath = basePath + apiPath;
+ const signature = signKalshiRequest(privateKeyPem, timestampMs, method, fullSignPath);
+
+ const url = KALSHI_BASE_URL + apiPath;
+ const headers = {
+ 'KALSHI-ACCESS-KEY': apiKey,
+ 'KALSHI-ACCESS-TIMESTAMP': timestampMs,
+ 'KALSHI-ACCESS-SIGNATURE': signature,
+ 'Content-Type': 'application/json',
+ 'Accept': 'application/json',
+ };
+
+ const fetchOpts = { method, headers };
+ if (body && method !== 'GET' && method !== 'DELETE') {
+ fetchOpts.body = JSON.stringify(body);
+ }
+
+ const response = await fetch(url, fetchOpts);
+ const text = await response.text();
+
+ let data;
+ try {
+ data = JSON.parse(text);
+ } catch {
+ data = { raw: text };
+ }
+
+ if (!response.ok) {
+ const errMsg = data?.message || data?.error || data?.raw || `HTTP ${response.status}`;
+ throw new Error(`Kalshi API error (${response.status}): ${errMsg}`);
+ }
+
+ return data;
+}
+
+// ── Kalshi Unauthenticated Fetch (for public endpoints) ──
+async function kalshiPublicFetch(method, apiPath) {
+ const url = KALSHI_BASE_URL + apiPath;
+ const response = await fetch(url, {
+ method,
+ headers: { 'Accept': 'application/json' },
+ });
+ const text = await response.text();
+
+ let data;
+ try {
+ data = JSON.parse(text);
+ } catch {
+ data = { raw: text };
+ }
+
+ if (!response.ok) {
+ const errMsg = data?.message || data?.error || data?.raw || `HTTP ${response.status}`;
+ throw new Error(`Kalshi API error (${response.status}): ${errMsg}`);
+ }
+
+ return data;
+}
+
+// ── Build query string from params object ──
+function buildQueryString(params) {
+ if (!params || Object.keys(params).length === 0) return '';
+ const qs = Object.entries(params)
+ .filter(([, v]) => v !== undefined && v !== null && v !== '')
+ .map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)
+ .join('&');
+ return qs ? `?${qs}` : '';
+}
+
+// ── API Route Handlers ──
+const routes = {
+
+ // ════════════════════════════════════════
+ // AUTH ENDPOINTS (same DW pattern)
+ // ════════════════════════════════════════
+
+ 'POST /api/auth/login': async (req, res) => {
+ const body = await readBody(req);
+ if (body.username === AUTH_USER && body.password === AUTH_PASS) {
+ const sessionData = { authenticated: true, username: AUTH_USER, loginTime: Date.now() };
+ const token = Buffer.from(JSON.stringify(sessionData)).toString('base64');
+ json(res, { success: true, message: 'Login successful', username: AUTH_USER }, 200, {
+ 'Set-Cookie': setSessionCookie(res, token),
+ });
+ } else {
+ json(res, { error: 'Invalid credentials' }, 401);
+ }
+ },
+
+ 'POST /api/auth/logout': async (req, res) => {
+ json(res, { success: true, message: 'Logged out successfully' }, 200, {
+ 'Set-Cookie': clearSessionCookie(),
+ });
+ },
+
+ 'GET /api/auth/session': async (req, res) => {
+ if (isWhitelistedIP(req)) {
+ return json(res, { authenticated: true, username: AUTH_USER, bypassReason: 'whitelisted_ip' });
+ }
+ if (hasBasicAuth(req)) {
+ return json(res, { authenticated: true, username: AUTH_USER, bypassReason: 'basic_auth' });
+ }
+ const session = getSession(req);
+ if (session) {
+ return json(res, {
+ authenticated: true,
+ username: session.username,
+ email: session.email,
+ picture: session.picture,
+ provider: session.provider,
+ loginTime: session.loginTime,
+ });
+ }
+ json(res, { authenticated: false }, 401);
+ },
+
+ 'POST /api/auth/google': async (req, res) => {
+ if (!googleClient) return json(res, { error: 'Google OAuth not configured' }, 400);
+ const body = await readBody(req);
+ if (!body.credential) return json(res, { error: 'Missing credential' }, 400);
+ try {
+ const ticket = await googleClient.verifyIdToken({ idToken: body.credential, audience: GOOGLE_CLIENT_ID });
+ const payload = ticket.getPayload();
+ const email = payload.email;
+ if (!payload.email_verified) return json(res, { error: 'Email not verified' }, 401);
+ if (ALLOWED_EMAILS.length > 0 && !ALLOWED_EMAILS.includes(email)) {
+ return json(res, { error: 'Email not authorized' }, 403);
+ }
+ const sessionData = {
+ authenticated: true,
+ username: payload.name || email,
+ email,
+ picture: payload.picture,
+ provider: 'google',
+ loginTime: Date.now(),
+ };
+ const token = Buffer.from(JSON.stringify(sessionData)).toString('base64');
+ json(res, { success: true, username: payload.name || email, email, picture: payload.picture }, 200, {
+ 'Set-Cookie': setSessionCookie(res, token),
+ });
+ } catch (err) {
+ json(res, { error: 'Invalid Google token', details: err.message }, 401);
+ }
+ },
+
+ 'GET /api/auth/google-config': async (req, res) => {
+ json(res, { client_id: GOOGLE_CLIENT_ID || null, configured: !!GOOGLE_CLIENT_ID });
+ },
+
+ // ════════════════════════════════════════
+ // SETUP WIZARD (save/load progress)
+ // ════════════════════════════════════════
+
+ 'GET /api/setup': async (req, res) => {
+ try {
+ const result = await q('SELECT config FROM risk_state ORDER BY updated_at DESC LIMIT 1');
+ const cfg = result.rows[0]?.config || {};
+ json(res, {
+ setup_complete: !!cfg.setup_complete,
+ setup_progress: cfg.setup_progress || null,
+ });
+ } catch (err) {
+ json(res, { error: err.message }, 500);
+ }
+ },
+
+ 'POST /api/setup': async (req, res) => {
+ const body = await readBody(req);
+ try {
+ const current = await q('SELECT * FROM risk_state ORDER BY updated_at DESC LIMIT 1');
+ const row = current.rows[0] || {};
+ const cfg = row.config || {};
+
+ if (body.action === 'save_progress') {
+ const newConfig = { ...cfg, setup_progress: body.progress };
+ await q('UPDATE risk_state SET config = $1, updated_at = NOW() WHERE id = $2', [JSON.stringify(newConfig), row.id]);
+ json(res, { success: true });
+ } else if (body.action === 'complete') {
+ const newConfig = { ...cfg, setup_complete: true, setup_progress: body.progress };
+ await q('UPDATE risk_state SET config = $1, updated_at = NOW() WHERE id = $2', [JSON.stringify(newConfig), row.id]);
+ json(res, { success: true, message: 'Setup complete!' });
+ } else {
+ json(res, { error: `Unknown setup action: ${body.action}` }, 400);
+ }
+ } catch (err) {
+ json(res, { error: err.message }, 500);
+ }
+ },
+
+ // ════════════════════════════════════════
+ // HEALTH
+ // ════════════════════════════════════════
+
+ 'GET /api/health': async (req, res) => {
+ try {
+ const dbCheck = await q('SELECT 1');
+ const risk = await q('SELECT * FROM risk_state ORDER BY updated_at DESC LIMIT 1');
+ const cfg = risk.rows[0]?.config || {};
+
+ // Test Kalshi connection
+ let kalshiConnected = false;
+ let balance = null;
+ if (cfg.kalshi_api_key && cfg.kalshi_private_key) {
+ try {
+ const balData = await kalshiFetch('GET', '/portfolio/balance');
+ kalshiConnected = true;
+ balance = balData.balance ?? balData;
+ } catch {
+ // Keys exist but connection failed
+ kalshiConnected = false;
+ }
+ }
+
+ json(res, {
+ status: 'ok',
+ db_connected: !!dbCheck,
+ kalshi_connected: kalshiConnected,
+ env: KALSHI_ENV,
+ safe_mode: cfg.safe_mode ?? true,
+ balance,
+ });
+ } catch (err) {
+ json(res, { status: 'error', error: err.message }, 500);
+ }
+ },
+
+ // ════════════════════════════════════════
+ // KALSHI PROXY (all actions via POST)
+ // ════════════════════════════════════════
+
+ 'POST /api/kalshi': async (req, res) => {
+ const body = await readBody(req);
+ const { action } = body;
+
+ if (!action) {
+ return json(res, { error: 'Missing action field' }, 400);
+ }
+
+ try {
+ switch (action) {
+
+ // ── Save API Keys ──
+ case 'save_keys': {
+ if (!body.api_key || !body.private_key) {
+ return json(res, { error: 'api_key and private_key (PEM) required' }, 400);
+ }
+ const current = await q('SELECT * FROM risk_state ORDER BY updated_at DESC LIMIT 1');
+ const row = current.rows[0] || {};
+ const newConfig = {
+ ...row.config,
+ kalshi_api_key: body.api_key,
+ kalshi_private_key: body.private_key,
+ kalshi_connected: true,
+ kalshi_connected_at: new Date().toISOString(),
+ kalshi_env: KALSHI_ENV,
+ };
+ await q('UPDATE risk_state SET config = $1, updated_at = NOW() WHERE id = $2', [
+ JSON.stringify(newConfig), row.id,
+ ]);
+ json(res, {
+ success: true,
+ api_key: body.api_key.substring(0, 12) + '...',
+ env: KALSHI_ENV,
+ message: 'Kalshi API keys saved',
+ });
+ break;
+ }
+
+ // ── Test Connection ──
+ case 'test_connection': {
+ try {
+ const data = await kalshiPublicFetch('GET', '/exchange/status');
+ json(res, { success: true, exchange_status: data, env: KALSHI_ENV });
+ } catch (err) {
+ json(res, { success: false, error: err.message }, 500);
+ }
+ break;
+ }
+
+ // ── Get Balance ──
+ case 'get_balance': {
+ const data = await kalshiFetch('GET', '/portfolio/balance');
+ json(res, { success: true, balance: data });
+ break;
+ }
+
+ // ── Get Markets (public) ──
+ case 'get_markets': {
+ const params = {};
+ if (body.category) params.category = body.category;
+ if (body.status) params.status = body.status;
+ if (body.limit) params.limit = body.limit;
+ if (body.cursor) params.cursor = body.cursor;
+ if (body.series_ticker) params.series_ticker = body.series_ticker;
+ if (body.event_ticker) params.event_ticker = body.event_ticker;
+ const qs = buildQueryString(params);
+ const data = await kalshiPublicFetch('GET', `/markets${qs}`);
+ json(res, { success: true, ...data });
+ break;
+ }
+
+ // ── Get Single Market ──
+ case 'get_market': {
+ if (!body.ticker) return json(res, { error: 'ticker required' }, 400);
+ const data = await kalshiPublicFetch('GET', `/markets/${encodeURIComponent(body.ticker)}`);
+ json(res, { success: true, market: data });
+ break;
+ }
+
+ // ── Get Orderbook ──
+ case 'get_orderbook': {
+ if (!body.ticker) return json(res, { error: 'ticker required' }, 400);
+ const qs = body.depth ? `?depth=${body.depth}` : '';
+ const data = await kalshiPublicFetch('GET', `/markets/${encodeURIComponent(body.ticker)}/orderbook${qs}`);
+ json(res, { success: true, orderbook: data });
+ break;
+ }
+
+ // ── Get Trades (public market trades) ──
+ case 'get_trades': {
+ if (!body.ticker) return json(res, { error: 'ticker required' }, 400);
+ const params = {};
+ if (body.limit) params.limit = body.limit;
+ if (body.cursor) params.cursor = body.cursor;
+ const qs = buildQueryString(params);
+ const data = await kalshiPublicFetch('GET', `/markets/${encodeURIComponent(body.ticker)}/trades${qs}`);
+ json(res, { success: true, ...data });
+ break;
+ }
+
+ // ── Get Events ──
+ case 'get_events': {
+ // Accept flat fields or nested in body.params (BrowseMarkets sends params wrapper)
+ const src = body.params || body;
+ const params = {};
+ if (src.status) params.status = src.status;
+ if (src.limit) params.limit = src.limit;
+ if (src.cursor) params.cursor = src.cursor;
+ if (src.series_ticker) params.series_ticker = src.series_ticker;
+ if (src.with_nested_markets !== undefined) params.with_nested_markets = src.with_nested_markets;
+ const qs = buildQueryString(params);
+ const data = await kalshiPublicFetch('GET', `/events${qs}`);
+ json(res, { success: true, ...data });
+ break;
+ }
+
+ // ── Get Single Event ──
+ case 'get_event': {
+ if (!body.event_ticker) return json(res, { error: 'event_ticker required' }, 400);
+ const qs = body.with_nested_markets ? '?with_nested_markets=true' : '';
+ const data = await kalshiPublicFetch('GET', `/events/${encodeURIComponent(body.event_ticker)}${qs}`);
+ json(res, { success: true, event: data });
+ break;
+ }
+
+ // ── Get Series ──
+ case 'get_series': {
+ if (!body.series_ticker) return json(res, { error: 'series_ticker required' }, 400);
+ const data = await kalshiPublicFetch('GET', `/series/${encodeURIComponent(body.series_ticker)}`);
+ json(res, { success: true, series: data });
+ break;
+ }
+
+ // ── Get Positions (from portfolio trades DB, or real Kalshi API if keys configured) ──
+ case 'get_positions': {
+ {
+ // No API keys — return portfolio trades from DB
+ const { rows: posRows } = await kenQ(`
+ SELECT pt.market_id as ticker, pt.market_title, pt.direction,
+ COUNT(*) FILTER (WHERE pt.status = 'open') as open_count,
+ SUM(pt.contracts) FILTER (WHERE pt.status = 'open') as open_contracts,
+ SUM(pt.cost_cents) FILTER (WHERE pt.status = 'open') as open_cost,
+ ROUND(AVG(pt.entry_price_cents) FILTER (WHERE pt.status = 'open')) as avg_price,
+ COUNT(*) as total_trades,
+ SUM(COALESCE(pt.pnl_cents, 0)) FILTER (WHERE pt.status != 'open') as realized_pnl
+ FROM ken_portfolio_trades pt
+ WHERE pt.created_at > NOW() - INTERVAL '24 hours'
+ GROUP BY pt.market_id, pt.market_title, pt.direction
+ HAVING COUNT(*) FILTER (WHERE pt.status = 'open') > 0
+ ORDER BY SUM(pt.cost_cents) FILTER (WHERE pt.status = 'open') DESC NULLS LAST
+ `);
+ const positions = posRows.map(r => ({
+ ticker: r.ticker,
+ market_ticker: r.ticker,
+ title: r.market_title || r.ticker,
+ market_exposure: r.direction === 'BUY_YES' ? parseInt(r.open_contracts || 0) : -parseInt(r.open_contracts || 0),
+ position: r.direction === 'BUY_YES' ? parseInt(r.open_contracts || 0) : -parseInt(r.open_contracts || 0),
+ position_cost: parseInt(r.open_cost || 0) * 100,
+ realized_pnl: parseInt(r.realized_pnl || 0) * 100,
+ fees_paid: 0,
+ avg_price_cents: parseInt(r.avg_price || 0),
+ open_trades: parseInt(r.open_count || 0),
+ total_trades: parseInt(r.total_trades || 0),
+ }));
+ json(res, { success: true, positions, market_positions: positions, is_paper: true });
+ }
+ break;
+ }
+
+ // ── Get Fills (auth required) ──
+ case 'get_fills': {
+ const params = {};
+ if (body.limit) params.limit = body.limit;
+ if (body.cursor) params.cursor = body.cursor;
+ if (body.ticker) params.ticker = body.ticker;
+ if (body.order_id) params.order_id = body.order_id;
+ const qs = buildQueryString(params);
+ const data = await kalshiFetch('GET', `/portfolio/fills${qs}`);
+ json(res, { success: true, ...data });
+ break;
+ }
+
+ // ── Get Orders (auth required) ──
+ case 'get_orders': {
+ const params = {};
+ if (body.limit) params.limit = body.limit;
+ if (body.cursor) params.cursor = body.cursor;
+ if (body.ticker) params.ticker = body.ticker;
+ if (body.status) params.status = body.status;
+ const qs = buildQueryString(params);
+ const data = await kalshiFetch('GET', `/portfolio/orders${qs}`);
+ json(res, { success: true, ...data });
+ break;
+ }
+
+ // ── Create Order (auth required) ──
+ case 'create_order': {
+ if (!body.ticker || !body.side || !body.action || !body.type || !body.count) {
+ return json(res, { error: 'ticker, side, action, type, and count are required' }, 400);
+ }
+ const orderPayload = {
+ ticker: body.ticker,
+ side: body.side, // 'yes' or 'no'
+ action: body.action, // 'buy' or 'sell'
+ type: body.type, // 'limit' or 'market'
+ count: body.count,
+ };
+ if (body.yes_price !== undefined) orderPayload.yes_price = body.yes_price;
+ if (body.no_price !== undefined) orderPayload.no_price = body.no_price;
+ if (body.client_order_id) orderPayload.client_order_id = body.client_order_id;
+ if (body.time_in_force) orderPayload.time_in_force = body.time_in_force;
+ if (body.expiration_ts) orderPayload.expiration_ts = body.expiration_ts;
+
+ const data = await kalshiFetch('POST', '/portfolio/orders', orderPayload);
+ json(res, { success: true, order: data });
+ break;
+ }
+
+ // ── Cancel Order (auth required) ──
+ case 'cancel_order': {
+ if (!body.order_id) return json(res, { error: 'order_id required' }, 400);
+ const data = await kalshiFetch('DELETE', `/portfolio/orders/${encodeURIComponent(body.order_id)}`);
+ json(res, { success: true, result: data });
+ break;
+ }
+
+ // ── Get Single Order (auth required) ──
+ case 'get_order': {
+ if (!body.order_id) return json(res, { error: 'order_id required' }, 400);
+ const data = await kalshiFetch('GET', `/portfolio/orders/${encodeURIComponent(body.order_id)}`);
+ json(res, { success: true, order: data });
+ break;
+ }
+
+ // ── Auto-Trader Status ──
+ case 'trader_status': {
+ const state = await getTraderState();
+ const allTrades = await kenQ('SELECT * FROM ken_trades ORDER BY created_at DESC LIMIT 50');
+ const closedTrades = (allTrades.rows || []).filter(t => t.status !== 'open');
+ const totalPnL = closedTrades.reduce((sum, t) => sum + (t.pnl_cents || 0), 0);
+ const wins = closedTrades.filter(t => (t.pnl_cents || 0) > 0).length;
+ const losses = closedTrades.filter(t => (t.pnl_cents || 0) < 0).length;
+ json(res, {
+ success: true,
+ config: TRADE_CONFIG,
+ state: {
+ open_positions: state.openCount,
+ total_invested: state.totalInvested,
+ available_budget: state.available,
+ daily_loss: state.dailyLoss,
+ },
+ positions: state.openPositions,
+ stats: {
+ total_trades: closedTrades.length,
+ wins, losses,
+ win_rate: closedTrades.length > 0 ? Math.round(wins / closedTrades.length * 100) : 0,
+ total_pnl_cents: totalPnL,
+ total_pnl_dollars: (totalPnL / 100).toFixed(2),
+ },
+ recent_trades: (allTrades.rows || []).slice(0, 20),
+ });
+ break;
+ }
+
+ // ── Toggle Auto-Trader ──
+ case 'trader_toggle': {
+ TRADE_CONFIG.enabled = !TRADE_CONFIG.enabled;
+ saveTradeConfig();
+ json(res, { success: true, enabled: TRADE_CONFIG.enabled, message: `Auto-trader ${TRADE_CONFIG.enabled ? 'ENABLED' : 'DISABLED'}` });
+ console.log(`[Ken] Auto-trader ${TRADE_CONFIG.enabled ? 'ENABLED' : 'DISABLED'} via API`);
+ break;
+ }
+
+ // ── Run Predictions (weather model pipeline) ──
+ case 'run_predictions': {
+ // Step 1: Get weather events from Kalshi
+ let events = [];
+ try {
+ const evData = await kalshiPublicFetch('GET', '/events?status=open&limit=100');
+ events = (evData.events || []).filter(e => {
+ const t = ((e.category || '') + ' ' + (e.title || '')).toLowerCase();
+ return t.includes('weather') || t.includes('temperature') || t.includes('temp ') ||
+ t.includes('rain') || t.includes('snow') || t.includes('precipitation') ||
+ t.includes('hurricane') || t.includes('wind') || t.includes('°f');
+ });
+ } catch { /* no events available - use weather cache */ }
+
+ // Step 2: Load cached weather data
+ const riskRow = await q('SELECT config FROM risk_state ORDER BY updated_at DESC LIMIT 1');
+ const rCfg = riskRow.rows[0]?.config || {};
+ const weatherCache = rCfg.weather_cache?.results || [];
+ const month = new Date().getMonth() + 1;
+
+ // Step 3: Generate predictions (only for real weather events with a city match)
+ const predictions = [];
+ for (const evt of events) {
+ const city = extractCity(evt.title);
+ if (!city) continue; // Skip non-geographic events (climate policy, earthquakes, etc.)
+ const spec = parseWeatherEvent(evt.title);
+ if (!spec || spec.variable === 'unknown') continue; // Skip if we can't parse a weather variable
+ const cityWeather = weatherCache.find(w => w.city === city);
+ if (!cityWeather) continue; // Skip if no weather data for this city
+ const features = cityWeather[spec.variable === 'snow' ? 'precipitation' : spec.variable] || cityWeather.temperature;
+
+ if (features && features.values?.length) {
+ const rawProb = ensembleExceedance(features, spec.threshold, spec.operator);
+ const prior = climatologicalPrior(spec.variable, spec.threshold, month);
+ const combined = bayesianUpdate(prior, rawProb ?? 0.5);
+ const pYes = Math.max(0.01, Math.min(0.99, combined));
+
+ // Get market price for edge calc
+ let marketPrice = 50;
+ try {
+ const mkts = await kalshiPublicFetch('GET', `/events/${encodeURIComponent(evt.event_ticker)}?with_nested_markets=true`);
+ const mkt = mkts.event?.markets?.[0] || mkts.markets?.[0];
+ if (mkt) {
+ const p = mkt.yes_ask || mkt.last_price || 50;
+ if (p > 0 && p < 100) marketPrice = p; // Skip fully priced markets
+ }
+ } catch {}
+
+ const edgeBps = Math.round((pYes * 100 - marketPrice) * 100);
+ predictions.push({
+ event_ticker: evt.event_ticker,
+ ticker: evt.title?.substring(0, 60),
+ market: evt.title,
+ city,
+ side: edgeBps > 0 ? 'yes' : 'no',
+ p_yes: Math.round(pYes * 1000) / 10,
+ price_cents: marketPrice,
+ edge_bps: edgeBps,
+ method: 'ensemble_bayesian_v1',
+ variable: spec.variable,
+ threshold: spec.threshold,
+ data_points: features.values.length,
+ });
+ }
+ }
+
+ // If no Kalshi events but we have weather data, generate synthetic predictions
+ if (predictions.length === 0 && weatherCache.length > 0) {
+ for (const wd of weatherCache.filter(w => !w.error)) {
+ if (wd.temperature?.values?.length) {
+ const maxT = wd.temperature.max;
+ const threshold = Math.round(maxT / 5) * 5;
+ const rawProb = ensembleExceedance(wd.temperature, threshold, '>=');
+ const prior = climatologicalPrior('temperature', threshold, month);
+ const combined = bayesianUpdate(prior, rawProb ?? 0.5);
+ const pYes = Math.max(0.01, Math.min(0.99, combined));
+ predictions.push({
+ ticker: `${wd.city} temp >= ${threshold}°F`,
+ market: `Will the high temperature in ${wd.city} reach ${threshold}°F?`,
+ city: wd.city,
+ side: pYes > 0.5 ? 'yes' : 'no',
+ p_yes: Math.round(pYes * 1000) / 10,
+ price_cents: 50,
+ edge_bps: Math.round((pYes * 100 - 50) * 100),
+ method: 'synthetic_forecast',
+ variable: 'temperature',
+ threshold,
+ data_points: wd.temperature.values.length,
+ });
+ }
+ }
+ }
+
+ predictions.sort((a, b) => Math.abs(b.edge_bps) - Math.abs(a.edge_bps));
+ const buySignals = predictions.filter(p => p.edge_bps > 0);
+ const avgEdge = predictions.length ? Math.round(predictions.reduce((s, p) => s + p.edge_bps, 0) / predictions.length) : 0;
+
+ json(res, {
+ success: true,
+ predictions,
+ buy_signals: buySignals.length,
+ avg_edge_bps: avgEdge,
+ total_events_scanned: events.length,
+ weather_cities: weatherCache.filter(w => !w.error).length,
+ });
+ break;
+ }
+
+ // ── Disconnect: remove keys from config ──
+ case 'disconnect': {
+ const current = await q('SELECT * FROM risk_state ORDER BY updated_at DESC LIMIT 1');
+ const row = current.rows[0] || {};
+ const newConfig = {
+ ...row.config,
+ kalshi_api_key: null,
+ kalshi_private_key: null,
+ kalshi_connected: false,
+ kalshi_connected_at: null,
+ };
+ await q('UPDATE risk_state SET config = $1, updated_at = NOW() WHERE id = $2', [
+ JSON.stringify(newConfig), row.id,
+ ]);
+ json(res, { success: true, message: 'Kalshi keys removed, disconnected' });
+ break;
+ }
+
+ // ── Status: show current connection config (masked) ──
+ case 'status': {
+ const current = await q('SELECT config FROM risk_state ORDER BY updated_at DESC LIMIT 1');
+ const cfg = current.rows[0]?.config || {};
+ json(res, {
+ connected: !!cfg.kalshi_connected,
+ api_key: cfg.kalshi_api_key ? cfg.kalshi_api_key.substring(0, 12) + '...' : null,
+ has_private_key: !!cfg.kalshi_private_key,
+ connected_at: cfg.kalshi_connected_at || null,
+ env: KALSHI_ENV,
+ });
+ break;
+ }
+
+ default:
+ json(res, {
+ error: `Unknown action: ${action}`,
+ available_actions: [
+ 'save_keys', 'test_connection', 'get_balance',
+ 'get_markets', 'get_market', 'get_orderbook', 'get_trades',
+ 'get_events', 'get_event', 'get_series',
+ 'get_positions', 'get_fills', 'get_orders',
+ 'create_order', 'cancel_order', 'get_order',
+ 'run_predictions', 'disconnect', 'status',
+ ],
+ }, 400);
+ }
+ } catch (err) {
+ json(res, { success: false, error: err.message }, 500);
+ }
+ },
+
+ // ════════════════════════════════════════
+ // WEATHER ENDPOINTS
+ // ════════════════════════════════════════
+
+ 'POST /api/weather': async (req, res) => {
+ const body = await readBody(req);
+
+ if (body.action === 'fetch_all') {
+ try {
+ const cities = body.cities || ['New York', 'Chicago', 'Miami', 'Denver', 'Los Angeles', 'Seattle'];
+ const useNws = body.force_nws === true; // opt-in to real NWS (flaky from this server)
+
+ // ── Generate synthetic seasonal forecast data (fast, reliable) ──
+ function generateSyntheticCities(cityList) {
+ const month = new Date().getMonth();
+ const results = [];
+ let totalDP = 0;
+ for (const city of cityList) {
+ const coords = CITY_COORDS[city]; if (!coords) continue;
+ const baseTemp = [35,38,48,58,68,78,85,83,75,62,48,38][month] + (coords.lat < 35 ? 15 : coords.lat > 42 ? -8 : 0);
+ const temps = Array.from({length: 14}, (_, i) => baseTemp + Math.round((Math.random() - 0.5) * 12) + (i < 7 ? 3 : -2));
+ const precips = Array.from({length: 14}, () => Math.round(Math.random() * 60));
+ const winds = Array.from({length: 14}, () => 5 + Math.round(Math.random() * 15));
+ const mkStat = (arr) => ({ mean: arr.reduce((a,b)=>a+b)/arr.length, min: Math.min(...arr), max: Math.max(...arr), latest: arr[0] });
+ results.push({
+ city, synthetic: true,
+ temperature: { variable: 'temperature', unit: 'F', values: temps, ...mkStat(temps) },
+ precipitation: { variable: 'precipitation', unit: 'percent', values: precips, ...mkStat(precips) },
+ wind: { variable: 'wind', unit: 'mph', values: winds, ...mkStat(winds) },
+ data_points: 42,
+ });
+ totalDP += 42;
+ }
+ return { results, totalDP };
+ }
+
+ let responseData;
+
+ if (useNws) {
+ // Real NWS path — wrapped in 15s global timeout, falls back to synthetic
+ const nwsResult = await Promise.race([
+ (async () => {
+ const results = [];
+ let dp = 0;
+ const mets = new Set();
+ for (const city of cities) {
+ const coords = CITY_COORDS[city]; if (!coords) continue;
+ try {
+ const grid = await nwsFetch(`${NWS_BASE}/points/${coords.lat},${coords.lon}`);
+ const forecast = await nwsFetch(`${NWS_BASE}/gridpoints/${grid.properties.gridId}/${grid.properties.gridX},${grid.properties.gridY}/forecast`);
+ const tempF = extractForecastFeatures(forecast, 'temperature');
+ const precip = extractForecastFeatures(forecast, 'precipitation');
+ const wind = extractForecastFeatures(forecast, 'wind');
+ const cdp = (tempF?.values?.length||0) + (precip?.values?.length||0) + (wind?.values?.length||0);
+ dp += cdp;
+ if (tempF) mets.add('temperature'); if (precip) mets.add('precipitation'); if (wind) mets.add('wind');
+ results.push({ city, temperature: tempF, precipitation: precip, wind, data_points: cdp });
+ } catch (e) { results.push({ city, error: e.message }); }
+ }
+ return { results, totalDP: dp, metrics: [...mets], synthetic: false };
+ })(),
+ new Promise(resolve => setTimeout(() => resolve(null), 15000)),
+ ]);
+
+ if (nwsResult && nwsResult.results.some(r => !r.error)) {
+ responseData = nwsResult;
+ } else {
+ const syn = generateSyntheticCities(cities);
+ responseData = { ...syn, metrics: ['temperature','precipitation','wind'], synthetic: true, note: 'NWS timed out — using synthetic' };
+ }
+ } else {
+ // Default: synthetic data (instant, always works)
+ const syn = generateSyntheticCities(cities);
+ responseData = { ...syn, metrics: ['temperature','precipitation','wind'], synthetic: true, note: 'Using seasonal synthetic forecasts (pass force_nws:true for real NWS data)' };
+ }
+
+ // Cache in DB
+ const row = (await q('SELECT id, config FROM risk_state ORDER BY updated_at DESC LIMIT 1')).rows[0];
+ if (row) {
+ const newCfg = { ...(row.config || {}), weather_cache: { results: responseData.results, fetched_at: new Date().toISOString(), synthetic: responseData.synthetic } };
+ await q('UPDATE risk_state SET config = $1, updated_at = NOW() WHERE id = $2', [JSON.stringify(newCfg), row.id]);
+ }
+
+ json(res, {
+ success: true,
+ synthetic: responseData.synthetic,
+ stations: responseData.results.length,
+ data_points: responseData.totalDP,
+ metrics: responseData.metrics,
+ cities: responseData.results,
+ fetched_at: new Date().toISOString(),
+ note: responseData.note || undefined,
+ });
+ } catch (err) {
+ json(res, { success: false, error: err.message }, 500);
+ }
+ } else {
+ json(res, { error: `Unknown weather action: ${body.action}` }, 400);
+ }
+ },
+
+ // ════════════════════════════════════════
+ // RISK ENDPOINTS
+ // ════════════════════════════════════════
+
+ 'POST /api/risk': async (req, res) => {
+ const body = await readBody(req);
+
+ try {
+ const current = await q('SELECT * FROM risk_state ORDER BY updated_at DESC LIMIT 1');
+ const row = current.rows[0] || {};
+ const cfg = row.config || {};
+
+ if (body.action === 'get_config') {
+ json(res, {
+ success: true,
+ config: {
+ safe_mode: cfg.safe_mode ?? true,
+ risk_profile: cfg.risk_profile ?? 'conservative',
+ max_position_size: cfg.max_position_size ?? 100,
+ max_contracts_per_market: cfg.max_contracts_per_market ?? 25,
+ max_dollars_at_risk: cfg.max_dollars_at_risk ?? 250,
+ max_daily_loss: cfg.max_daily_loss ?? cfg.daily_loss_cap ?? 50,
+ daily_loss_cap: cfg.daily_loss_cap ?? 50,
+ max_open_orders: cfg.max_open_orders ?? 10,
+ max_exposure: cfg.max_exposure ?? 500,
+ stop_loss_pct: cfg.stop_loss_pct ?? 20,
+ auto_hedge: cfg.auto_hedge ?? false,
+ allowed_categories: cfg.allowed_categories ?? [],
+ kill_switch_active: row.kill_switch_active || false,
+ kill_reason: row.kill_reason || null,
+ bankroll: parseFloat(row.bankroll || 0),
+ daily_pnl: parseFloat(row.daily_pnl || 0),
+ open_exposure: parseFloat(row.open_exposure || 0),
+ },
+ });
+ } else if (body.action === 'update_config') {
+ // Accept flat fields (from RiskProfile step) or wrapped in config object
+ const updates = body.config || {};
+ if (body.max_contracts_per_market !== undefined) updates.max_contracts_per_market = body.max_contracts_per_market;
+ if (body.max_dollars_at_risk !== undefined) updates.max_dollars_at_risk = body.max_dollars_at_risk;
+ if (body.daily_loss_cap !== undefined) updates.daily_loss_cap = body.daily_loss_cap;
+ if (body.risk_profile !== undefined) updates.risk_profile = body.risk_profile;
+ if (body.safe_mode !== undefined) updates.safe_mode = body.safe_mode;
+ const newConfig = { ...cfg, ...updates };
+ await q('UPDATE risk_state SET config = $1, updated_at = NOW() WHERE id = $2', [
+ JSON.stringify(newConfig), row.id,
+ ]);
+
+ // Also update top-level risk fields if provided
+ if (body.config?.kill_switch_active !== undefined) {
+ await q('UPDATE risk_state SET kill_switch_active = $1, kill_reason = $2, updated_at = NOW() WHERE id = $3', [
+ body.config.kill_switch_active,
+ body.config.kill_reason || null,
+ row.id,
+ ]);
+ }
+
+ const updated = await q('SELECT * FROM risk_state ORDER BY updated_at DESC LIMIT 1');
+ const u = updated.rows[0] || {};
+ json(res, {
+ success: true,
+ message: 'Risk config updated',
+ config: u.config || {},
+ });
+ } else {
+ json(res, { error: `Unknown risk action: ${body.action}` }, 400);
+ }
+ } catch (err) {
+ json(res, { success: false, error: err.message }, 500);
+ }
+ },
+
+ // ════════════════════════════════════════
+ // TRADING MODE CONTROL
+ // ════════════════════════════════════════
+
+ 'POST /api/trading/mode': async (req, res) => {
+ const body = await readBody(req);
+ try {
+ const current = await q('SELECT * FROM risk_state ORDER BY updated_at DESC LIMIT 1');
+ const row = current.rows[0] || {};
+ const cfg = row.config || {};
+
+ if (body.action === 'get') {
+ // Get current trading mode
+ const traderState = await getTraderState().catch(() => ({ openPositions: [], openCount: 0, totalInvested: 0, dailyLoss: 0, available: 0 }));
+ return json(res, {
+ env: KALSHI_ENV,
+ safe_mode: cfg.safe_mode ?? true,
+ kalshi_connected: !!(cfg.kalshi_api_key && cfg.kalshi_private_key),
+ trade_config: TRADE_CONFIG,
+ trader_state: traderState,
+ auto_trader_enabled: TRADE_CONFIG.enabled,
+ });
+ }
+
+ if (body.action === 'switch_env') {
+ const newEnv = body.env === 'prod' ? 'prod' : 'demo';
+ const newConfig = { ...cfg, kalshi_env: newEnv };
+ await q('UPDATE risk_state SET config = $1, updated_at = NOW() WHERE id = $2', [JSON.stringify(newConfig), row.id]);
+ KALSHI_ENV = newEnv;
+ KALSHI_BASE_URL = KALSHI_BASE_URLS[newEnv];
+ console.log(`[Ken] Environment switched to ${newEnv.toUpperCase()} (${KALSHI_BASE_URL})`);
+ return json(res, { success: true, env: newEnv, base_url: KALSHI_BASE_URL });
+ }
+
+ if (body.action === 'toggle_safe_mode') {
+ const newSafe = !(cfg.safe_mode ?? true);
+ const newConfig = { ...cfg, safe_mode: newSafe };
+ await q('UPDATE risk_state SET config = $1, updated_at = NOW() WHERE id = $2', [JSON.stringify(newConfig), row.id]);
+ console.log(`[Ken] Safe mode ${newSafe ? 'ENABLED' : 'DISABLED'}`);
+ return json(res, { success: true, safe_mode: newSafe });
+ }
+
+ if (body.action === 'toggle_auto_trader') {
+ TRADE_CONFIG.enabled = !TRADE_CONFIG.enabled;
+ saveTradeConfig();
+ console.log(`[Ken] Auto-trader ${TRADE_CONFIG.enabled ? 'ENABLED' : 'DISABLED'}`);
+ return json(res, { success: true, auto_trader_enabled: TRADE_CONFIG.enabled });
+ }
+
+ if (body.action === 'update_trade_config') {
+ if (body.budget_cents !== undefined) TRADE_CONFIG.budget_cents = Math.max(100, Math.min(100000, body.budget_cents));
+ if (body.max_position_cents !== undefined) TRADE_CONFIG.max_position_cents = Math.max(50, Math.min(10000, body.max_position_cents));
+ if (body.max_open_positions !== undefined) TRADE_CONFIG.max_open_positions = Math.max(1, Math.min(20, body.max_open_positions));
+ if (body.min_confidence !== undefined) TRADE_CONFIG.min_confidence = Math.max(50, Math.min(99, body.min_confidence));
+ if (body.daily_loss_limit_cents !== undefined) TRADE_CONFIG.daily_loss_limit_cents = Math.max(100, Math.min(50000, body.daily_loss_limit_cents));
+ saveTradeConfig();
+ return json(res, { success: true, trade_config: TRADE_CONFIG });
+ }
+
+ json(res, { error: `Unknown trading mode action: ${body.action}` }, 400);
+ } catch (err) {
+ json(res, { error: err.message }, 500);
+ }
+ },
+
+ // ════════════════════════════════════════
+ // TRADING HISTORY & P&L
+ // ════════════════════════════════════════
+
+ 'GET /api/trading/history': async (req, res) => {
+ try {
+ const { rows: trades } = await kenQ('SELECT * FROM ken_trades ORDER BY created_at DESC LIMIT 100');
+ const { rows: [summary] } = await kenQ(`
+ SELECT
+ COUNT(*) as total_trades,
+ COUNT(*) FILTER (WHERE status = 'open') as open_trades,
+ COUNT(*) FILTER (WHERE pnl_cents > 0) as winning_trades,
+ COUNT(*) FILTER (WHERE pnl_cents < 0) as losing_trades,
+ COALESCE(SUM(pnl_cents), 0) as total_pnl,
+ COALESCE(SUM(cost_cents) FILTER (WHERE status = 'open'), 0) as open_exposure
+ FROM ken_trades
+ `);
+ json(res, { trades, summary });
+ } catch (err) {
+ json(res, { error: err.message }, 500);
+ }
+ },
+
+ // ════════════════════════════════════════
+ // PAPER TRADING
+ // ════════════════════════════════════════
+
+ 'POST /api/paper': async (req, res) => {
+ const body = await readBody(req);
+
+ try {
+ const current = await q('SELECT * FROM risk_state ORDER BY updated_at DESC LIMIT 1');
+ const row = current.rows[0] || {};
+ const cfg = row.config || {};
+ const paperTrades = cfg.paper_trades || [];
+
+ if (body.action === 'submit_order') {
+ if (!body.ticker || !body.side || !body.count) {
+ return json(res, { error: 'ticker, side, and count required' }, 400);
+ }
+
+ const orderId = `paper_${Date.now()}_${Math.random().toString(36).substring(2, 8)}`;
+ const fillPrice = body.yes_price || body.no_price || body.price || 50; // cents
+
+ const paperOrder = {
+ order_id: orderId,
+ ticker: body.ticker,
+ side: body.side, // 'yes' or 'no'
+ action: body.action_type || 'buy',
+ type: body.type || 'market',
+ count: body.count,
+ price: fillPrice,
+ cost: fillPrice * body.count, // in cents
+ status: 'filled',
+ created_at: new Date().toISOString(),
+ filled_at: new Date().toISOString(),
+ is_paper: true,
+ };
+
+ paperTrades.push(paperOrder);
+
+ const newConfig = { ...cfg, paper_trades: paperTrades };
+ await q('UPDATE risk_state SET config = $1, updated_at = NOW() WHERE id = $2', [
+ JSON.stringify(newConfig), row.id,
+ ]);
+
+ json(res, { success: true, order: paperOrder, message: 'Paper order filled' });
+
+ } else if (body.action === 'get_positions') {
+ // Aggregate from ken_portfolio_trades (live hyper-trading data)
+ try {
+ const { rows } = await kenQ(`
+ SELECT pt.market_id as ticker, pt.market_title, pt.direction,
+ SUM(pt.contracts) as total_contracts,
+ SUM(pt.cost_cents) as position_cost,
+ ROUND(AVG(pt.entry_price_cents)) as avg_price,
+ COUNT(*) as trades,
+ SUM(CASE WHEN pt.status != 'open' THEN pt.pnl_cents ELSE 0 END) as realized_pnl
+ FROM ken_portfolio_trades pt
+ WHERE pt.created_at > NOW() - INTERVAL '24 hours'
+ GROUP BY pt.market_id, pt.market_title, pt.direction
+ ORDER BY SUM(pt.cost_cents) DESC
+ `);
+ const positions = rows.map(r => ({
+ ticker: r.ticker,
+ market_ticker: r.ticker,
+ title: r.market_title,
+ side: r.direction === 'BUY_YES' ? 'yes' : 'no',
+ market_exposure: r.direction === 'BUY_YES' ? parseInt(r.total_contracts) : -parseInt(r.total_contracts),
+ position: r.direction === 'BUY_YES' ? parseInt(r.total_contracts) : -parseInt(r.total_contracts),
+ position_cost: parseInt(r.position_cost) * 100,
+ avg_price_cents: parseInt(r.avg_price),
+ realized_pnl: parseInt(r.realized_pnl || 0) * 100,
+ fees_paid: 0,
+ trades: parseInt(r.trades),
+ }));
+ json(res, { success: true, positions, is_paper: true });
+ } catch (e) {
+ // Fallback to old paper trades
+ const positionMap = {};
+ for (const trade of paperTrades) {
+ const key = `${trade.ticker}_${trade.side}`;
+ if (!positionMap[key]) positionMap[key] = { ticker: trade.ticker, side: trade.side, total_contracts: 0, avg_price: 0, total_cost: 0, trades: 0 };
+ const pos = positionMap[key];
+ if (trade.action === 'buy') { pos.total_cost += trade.price * trade.count; pos.total_contracts += trade.count; }
+ else { pos.total_cost -= trade.price * trade.count; pos.total_contracts -= trade.count; }
+ pos.trades++;
+ pos.avg_price = pos.total_contracts > 0 ? Math.round(pos.total_cost / pos.total_contracts) : 0;
+ }
+ const positions = Object.values(positionMap).filter(p => p.total_contracts !== 0);
+ json(res, { success: true, positions, is_paper: true });
+ }
+
+ } else if (body.action === 'get_fills') {
+ // Return paper trade history
+ const limit = body.limit || 50;
+ const fills = paperTrades.slice(-limit).reverse();
+ json(res, { success: true, fills, total: paperTrades.length, is_paper: true });
+
+ } else if (body.action === 'clear') {
+ // Clear all paper trades
+ const newConfig = { ...cfg, paper_trades: [] };
+ await q('UPDATE risk_state SET config = $1, updated_at = NOW() WHERE id = $2', [
+ JSON.stringify(newConfig), row.id,
+ ]);
+ json(res, { success: true, message: 'Paper trades cleared' });
+
+ } else {
+ json(res, { error: `Unknown paper action: ${body.action}` }, 400);
+ }
+ } catch (err) {
+ json(res, { success: false, error: err.message }, 500);
+ }
+ },
+
+ // ── Positions Detail API (collapsible tables) ──
+ 'GET /api/positions': async (req, res) => {
+ try {
+ // All positions with full stats
+ const { rows: positions } = await kenQ(`
+ SELECT
+ pt.market_id AS ticker,
+ pt.direction,
+ pt.market_title AS title,
+ COUNT(*) FILTER (WHERE pt.status = 'open') AS open_trades,
+ SUM(pt.contracts) FILTER (WHERE pt.status = 'open') AS open_contracts,
+ SUM(pt.cost_cents) FILTER (WHERE pt.status = 'open') AS open_cost_cents,
+ ROUND(AVG(pt.entry_price_cents) FILTER (WHERE pt.status = 'open')) AS avg_entry_price,
+ SUM(COALESCE(pt.pnl_cents, 0)) FILTER (WHERE pt.status != 'open') AS realized_pnl_cents,
+ COUNT(*) AS total_trades,
+ COUNT(*) FILTER (WHERE pt.status != 'open') AS closed_trades,
+ MIN(pt.created_at) AS first_trade_at,
+ MAX(pt.created_at) AS last_trade_at,
+ MIN(pt.entry_price_cents) FILTER (WHERE pt.status = 'open') AS min_entry,
+ MAX(pt.entry_price_cents) FILTER (WHERE pt.status = 'open') AS max_entry
+ FROM ken_portfolio_trades pt
+ GROUP BY pt.market_id, pt.direction, pt.market_title
+ HAVING COUNT(*) FILTER (WHERE pt.status = 'open') > 0
+ ORDER BY SUM(pt.cost_cents) FILTER (WHERE pt.status = 'open') DESC NULLS LAST
+ `);
+
+ // Category grouping by market event prefix
+ const grouped = {};
+ for (const p of positions) {
+ const prefix = (p.ticker || '').split('-')[0];
+ if (!grouped[prefix]) grouped[prefix] = { event: prefix, title: p.title, positions: [], totalCost: 0, totalPnl: 0, totalContracts: 0 };
+ grouped[prefix].positions.push(p);
+ grouped[prefix].totalCost += parseInt(p.open_cost_cents || 0);
+ grouped[prefix].totalPnl += parseInt(p.realized_pnl_cents || 0);
+ grouped[prefix].totalContracts += parseInt(p.open_contracts || 0);
+ }
+
+ // Summary stats
+ const totalCost = positions.reduce((s, p) => s + parseInt(p.open_cost_cents || 0), 0);
+ const totalPnl = positions.reduce((s, p) => s + parseInt(p.realized_pnl_cents || 0), 0);
+ const totalContracts = positions.reduce((s, p) => s + parseInt(p.open_contracts || 0), 0);
+ const totalTrades = positions.reduce((s, p) => s + parseInt(p.total_trades || 0), 0);
+
+ json(res, {
+ success: true,
+ positions: positions.map(p => ({
+ ...p,
+ open_trades: parseInt(p.open_trades || 0),
+ open_contracts: parseInt(p.open_contracts || 0),
+ open_cost_cents: parseInt(p.open_cost_cents || 0),
+ avg_entry_price: parseInt(p.avg_entry_price || 0),
+ realized_pnl_cents: parseInt(p.realized_pnl_cents || 0),
+ total_trades: parseInt(p.total_trades || 0),
+ closed_trades: parseInt(p.closed_trades || 0),
+ min_entry: parseInt(p.min_entry || 0),
+ max_entry: parseInt(p.max_entry || 0),
+ })),
+ grouped: Object.values(grouped).sort((a, b) => b.totalCost - a.totalCost),
+ summary: { totalCost, totalPnl, totalContracts, totalTrades, positionCount: positions.length },
+ });
+ } catch (err) {
+ json(res, { success: false, error: err.message }, 500);
+ }
+ },
+
+ // Get trade history for a specific position
+ 'POST /api/positions/trades': async (req, res) => {
+ try {
+ const body = await readBody(req);
+ const { ticker, direction, limit: lim } = body;
+ if (!ticker) return json(res, { error: 'ticker required' }, 400);
+
+ let sql = `SELECT * FROM ken_portfolio_trades WHERE market_id = $1`;
+ const params = [ticker];
+ if (direction) { sql += ` AND direction = $2`; params.push(direction); }
+ sql += ` ORDER BY created_at DESC LIMIT ${Math.min(parseInt(lim) || 100, 500)}`;
+
+ const { rows } = await kenQ(sql, params);
+ json(res, { success: true, trades: rows });
+ } catch (err) {
+ json(res, { success: false, error: err.message }, 500);
+ }
+ },
+
+ // ── Signal Pipeline API ──
+ 'GET /api/signals': async (req, res) => {
+ try {
+ const { rows: signals } = await kenQ(`
+ SELECT id, market_id, direction, expected_edge, size_recommendation, confidence, reasoning, sources, risk_approved, executed, created_at
+ FROM ken_strategy_signals
+ ORDER BY created_at DESC
+ LIMIT 50
+ `);
+ const { rows: shifts } = await kenQ(`
+ SELECT market_id, prior_probability, sentiment_impact, adjusted_probability, market_probability, edge, num_articles, created_at
+ FROM ken_probability_shifts
+ ORDER BY created_at DESC
+ LIMIT 50
+ `);
+ const { rows: recentSentiment } = await kenQ(`
+ SELECT event_tag, market_ticker, AVG(sentiment) as avg_sentiment, AVG(confidence) as avg_confidence, COUNT(*) as count
+ FROM ken_event_sentiment
+ WHERE created_at > NOW() - INTERVAL '1 hour'
+ GROUP BY event_tag, market_ticker
+ ORDER BY count DESC
+ LIMIT 30
+ `);
+ // Enrich with Kalshi URLs
+ const enrichWithUrl = (rows) => rows.map(r => {
+ const ticker = r.market_id || '';
+ const eventTicker = ticker.replace(/-[^-]+$/, '') || ticker;
+ const seriesTicker = eventTicker.replace(/-[^-]+$/, '') || eventTicker;
+ return { ...r, event_ticker: eventTicker, kalshi_url: `https://kalshi.com/markets/${seriesTicker.toLowerCase()}/${eventTicker.toLowerCase()}` };
+ });
+ json(res, {
+ signals: enrichWithUrl(signals),
+ probabilityShifts: enrichWithUrl(shifts),
+ eventSentiment: recentSentiment,
+ pipeline: {
+ scanInterval: '15 min',
+ signalInterval: '5 min',
+ intelligenceInterval: '30 min',
+ cachedMarkets: cachedActiveMarkets.length,
+ riskLimits: RISK_LIMITS,
+ },
+ });
+ } catch (err) {
+ json(res, { error: err.message }, 500);
+ }
+ },
+
+ 'GET /api/signals/dashboard': async (req, res) => {
+ try {
+ // Summary stats for the signal pipeline
+ const { rows: [stats] } = await kenQ(`
+ SELECT
+ COUNT(*) as total_signals,
+ COUNT(CASE WHEN risk_approved THEN 1 END) as approved_signals,
+ COUNT(CASE WHEN direction = 'BUY_YES' THEN 1 END) as buy_yes,
+ COUNT(CASE WHEN direction = 'BUY_NO' THEN 1 END) as buy_no,
+ AVG(expected_edge) as avg_edge,
+ AVG(confidence) as avg_confidence,
+ MAX(created_at) as latest_signal
+ FROM ken_strategy_signals
+ WHERE created_at > NOW() - INTERVAL '24 hours'
+ `);
+ const { rows: topSignals } = await kenQ(`
+ SELECT market_id, direction, expected_edge, confidence, reasoning, risk_approved, created_at
+ FROM ken_strategy_signals
+ WHERE created_at > NOW() - INTERVAL '4 hours' AND risk_approved = true
+ ORDER BY ABS(expected_edge) DESC
+ LIMIT 10
+ `);
+ const { rows: sourceBreakdown } = await kenQ(`
+ SELECT source, COUNT(*) as cnt, AVG(sentiment_score) as avg_sent
+ FROM ken_sentiment
+ WHERE captured_at > NOW() - INTERVAL '1 hour'
+ GROUP BY source
+ ORDER BY cnt DESC
+ LIMIT 20
+ `);
+ json(res, { stats, topSignals, sourceBreakdown, cachedMarkets: cachedActiveMarkets.length });
+ } catch (err) {
+ json(res, { error: err.message }, 500);
+ }
+ },
+
+ // ════════════════════════════════════════
+ // INTELLIGENCE FEED
+ // ════════════════════════════════════════
+
+ 'GET /api/intelligence': async (req, res) => {
+ try {
+ const { rows: recent } = await kenQ(`
+ SELECT source, subreddit, keyword, post_title, post_url, score, num_comments, sentiment_score, captured_at
+ FROM ken_sentiment
+ ORDER BY captured_at DESC
+ LIMIT 100
+ `);
+ const { rows: sourceCounts } = await kenQ(`
+ SELECT source, COUNT(*) as cnt, AVG(sentiment_score) as avg_sent,
+ MAX(captured_at) as latest
+ FROM ken_sentiment
+ WHERE captured_at > NOW() - INTERVAL '4 hours'
+ GROUP BY source ORDER BY cnt DESC
+ `);
+ const { rows: [totals] } = await kenQ(`
+ SELECT
+ COUNT(*) as total_items,
+ COUNT(*) FILTER (WHERE captured_at > NOW() - INTERVAL '1 hour') as last_hour,
+ COUNT(*) FILTER (WHERE captured_at > NOW() - INTERVAL '4 hours') as last_4h,
+ AVG(sentiment_score) FILTER (WHERE captured_at > NOW() - INTERVAL '1 hour') as avg_sentiment_1h
+ FROM ken_sentiment
+ `);
+ json(res, { recent, sourceCounts, totals });
+ } catch (err) {
+ json(res, { error: err.message }, 500);
+ }
+ },
+
+ // ════════════════════════════════════════
+ // PREDICTIONS FEED
+ // ════════════════════════════════════════
+
+ 'GET /api/predictions': async (req, res) => {
+ try {
+ const { rows } = await kenQ(`
+ SELECT ticker, event_ticker, title, signal_type, side, confidence, entry_price, edge_bps, reasoning, sources, created_at
+ FROM ken_predictions
+ ORDER BY created_at DESC
+ LIMIT 100
+ `);
+ json(res, { predictions: rows });
+ } catch (err) {
+ json(res, { error: err.message }, 500);
+ }
+ },
+
+ // ── Live Markets (all active with snapshots) ──
+ 'GET /api/markets': async (req, res) => {
+ try {
+ const { rows } = await kenQ(`
+ SELECT DISTINCT ON (ticker) ticker, event_ticker, title, subtitle, category,
+ yes_bid, yes_ask, no_bid, no_ask, last_price, volume, volume_24h, open_interest, spread,
+ captured_at
+ FROM ken_market_snapshots
+ WHERE captured_at > NOW() - INTERVAL '1 hour'
+ ORDER BY ticker, captured_at DESC
+ `);
+ json(res, { markets: rows, count: rows.length, cached: cachedActiveMarkets.length });
+ } catch (err) {
+ json(res, { error: err.message }, 500);
+ }
+ },
+
+ // ── Energy/LNG Arbitrage Opportunities ──
+ 'GET /api/energy-arb': async (req, res) => {
+ try {
+ const arbs = await energyArbitrageScan(cachedActiveMarkets);
+ // Also get recent energy-related signals
+ const { rows: energySignals } = await kenQ(`
+ SELECT ticker, title, signal_type, side, confidence, entry_price, edge_bps, reasoning, sources, created_at
+ FROM ken_predictions
+ WHERE signal_type IN ('energy_arb', 'polymarket_arb')
+ OR reasoning ILIKE '%energy%' OR reasoning ILIKE '%oil%' OR reasoning ILIKE '%gas%' OR reasoning ILIKE '%lng%'
+ ORDER BY created_at DESC LIMIT 50
+ `);
+ json(res, {
+ arbitrage_opportunities: arbs,
+ energy_signals: energySignals,
+ scan_time: new Date().toISOString(),
+ markets_scanned: cachedActiveMarkets.length,
+ });
+ } catch (err) {
+ json(res, { error: err.message }, 500);
+ }
+ },
+
+ // ── All Active Signals (for trading) ──
+ 'GET /api/signals': async (req, res) => {
+ try {
+ const { rows } = await kenQ(`
+ SELECT market_id as ticker, direction, expected_edge, confidence, reasoning, sources, risk_approved, created_at
+ FROM ken_strategy_signals
+ WHERE created_at > NOW() - INTERVAL '2 hours'
+ ORDER BY created_at DESC LIMIT 200
+ `);
+ json(res, { signals: rows, count: rows.length });
+ } catch (err) {
+ json(res, { error: err.message }, 500);
+ }
+ },
+
+ // ════════════════════════════════════════
+ // DASHBOARD — aggregated paper portfolio stats
+ // ════════════════════════════════════════
+
+ 'GET /api/dashboard': async (req, res) => {
+ try {
+ // Aggregate balance across all portfolios
+ const { rows: [balRow] } = await kenQ(`
+ SELECT SUM(balance_cents) as total_balance,
+ SUM(total_invested_cents) as total_invested,
+ SUM(total_returned_cents) as total_returned
+ FROM ken_portfolios
+ `);
+
+ // Seed money + economics
+ const totalBalance = Number(balRow?.total_balance || 0);
+ const totalInvested = Number(balRow?.total_invested || 0);
+ const totalReturned = Number(balRow?.total_returned || 0);
+ const seedMoney = totalBalance + totalInvested - totalReturned; // always 5000000 cents ($50K)
+ const netPnl = totalBalance - seedMoney; // how much above/below seed
+ const roi = seedMoney > 0 ? ((totalBalance - seedMoney) / seedMoney * 100) : 0;
+
+ // Daily spend breakdown (last 7 days)
+ const { rows: spendRows } = await kenQ(`
+ SELECT resolved_at::date as day,
+ COUNT(*) as trades,
+ SUM(CASE WHEN pnl_cents > 0 THEN 1 ELSE 0 END) as wins,
+ SUM(CASE WHEN pnl_cents < 0 THEN 1 ELSE 0 END) as losses,
+ SUM(pnl_cents) as net_pnl,
+ SUM(CASE WHEN pnl_cents < 0 THEN ABS(pnl_cents) ELSE 0 END) as gross_losses,
+ SUM(CASE WHEN pnl_cents > 0 THEN pnl_cents ELSE 0 END) as gross_wins,
+ SUM(cost_cents) as capital_deployed
+ FROM ken_portfolio_trades
+ WHERE status != 'open' AND resolved_at IS NOT NULL
+ GROUP BY resolved_at::date ORDER BY day DESC LIMIT 7
+ `);
+
+ // Daily budget across all portfolios
+ const { rows: [budgetRow] } = await kenQ(`
+ SELECT SUM(daily_budget_cents) as total_daily_budget,
+ COUNT(*) as num_portfolios
+ FROM ken_portfolios
+ `);
+
+ // Open position cost (capital currently at risk)
+ const { rows: [riskRow] } = await kenQ(`
+ SELECT COALESCE(SUM(cost_cents), 0) as capital_at_risk,
+ COUNT(*) as open_positions
+ FROM ken_portfolio_trades WHERE status = 'open'
+ `);
+
+ // Open position count + today's P&L
+ const { rows: [posRow] } = await kenQ(`
+ SELECT
+ COUNT(*) FILTER (WHERE status = 'open') as open_count,
+ COUNT(DISTINCT market_id) FILTER (WHERE status = 'open') as unique_markets,
+ COALESCE(SUM(pnl_cents) FILTER (WHERE status != 'open' AND resolved_at::date = CURRENT_DATE), 0) as daily_pnl,
+ COALESCE(SUM(pnl_cents) FILTER (WHERE status != 'open'), 0) as total_pnl
+ FROM ken_portfolio_trades
+ `);
+
+ // Recent fills (last 10 resolved trades)
+ const { rows: fills } = await kenQ(`
+ SELECT market_id as ticker, market_title, direction,
+ contracts, entry_price_cents, pnl_cents, status, resolved_at
+ FROM ken_portfolio_trades
+ WHERE status != 'open'
+ ORDER BY resolved_at DESC LIMIT 10
+ `);
+
+ // P&L history — daily totals for last 14 days
+ const { rows: pnlHistory } = await kenQ(`
+ SELECT resolved_at::date as day, SUM(pnl_cents) as daily_pnl
+ FROM ken_portfolio_trades
+ WHERE status != 'open' AND resolved_at > NOW() - INTERVAL '14 days'
+ GROUP BY resolved_at::date
+ ORDER BY day ASC
+ `);
+
+ // Top winning markets
+ const { rows: topMarkets } = await kenQ(`
+ SELECT market_id, market_title,
+ COUNT(*) as total_trades,
+ SUM(CASE WHEN pnl_cents > 0 THEN 1 ELSE 0 END) as wins,
+ SUM(CASE WHEN pnl_cents < 0 THEN 1 ELSE 0 END) as losses,
+ SUM(pnl_cents) as pnl_cents,
+ MODE() WITHIN GROUP (ORDER BY direction) as primary_direction,
+ ROUND(AVG(entry_price_cents)) as avg_entry
+ FROM ken_portfolio_trades
+ WHERE status != 'open'
+ GROUP BY market_id, market_title
+ ORDER BY SUM(pnl_cents) DESC
+ LIMIT 10
+ `);
+
+ // Bottom losing markets
+ const { rows: worstMarkets } = await kenQ(`
+ SELECT market_id, market_title,
+ COUNT(*) as total_trades,
+ SUM(CASE WHEN pnl_cents > 0 THEN 1 ELSE 0 END) as wins,
+ SUM(CASE WHEN pnl_cents < 0 THEN 1 ELSE 0 END) as losses,
+ SUM(pnl_cents) as pnl_cents,
+ MODE() WITHIN GROUP (ORDER BY direction) as primary_direction,
+ ROUND(AVG(entry_price_cents)) as avg_entry
+ FROM ken_portfolio_trades
+ WHERE status != 'open'
+ GROUP BY market_id, market_title
+ HAVING SUM(pnl_cents) < 0
+ ORDER BY SUM(pnl_cents) ASC
+ LIMIT 5
+ `);
+
+ // Top/bottom strategies
+ const { rows: strategies } = await kenQ(`
+ SELECT p.strategy, p.name,
+ p.trades_won, p.trades_lost,
+ (p.total_returned_cents - p.total_invested_cents) as net_pnl_cents,
+ p.balance_cents,
+ ROUND(100.0 * p.trades_won / NULLIF(p.trades_won + p.trades_lost, 0), 1) as win_rate
+ FROM ken_portfolios p
+ WHERE p.total_invested_cents > 0
+ ORDER BY (p.total_returned_cents - p.total_invested_cents) DESC
+ `);
+
+ // Today's stats
+ const { rows: [todayRow] } = await kenQ(`
+ SELECT COUNT(*) as trades,
+ SUM(CASE WHEN pnl_cents > 0 THEN 1 ELSE 0 END) as wins,
+ SUM(CASE WHEN pnl_cents < 0 THEN 1 ELSE 0 END) as losses
+ FROM ken_portfolio_trades
+ WHERE status != 'open' AND resolved_at::date = CURRENT_DATE
+ `);
+
+ // ── Top 3 Best Opportunities Right Now ──
+ // Combine recent high-confidence signals with historical win rates and current market prices
+ const { rows: opportunities } = await kenQ(`
+ WITH recent_signals AS (
+ SELECT DISTINCT ON (market_id)
+ market_id, direction, expected_edge, confidence, reasoning, risk_approved, created_at
+ FROM ken_strategy_signals
+ WHERE created_at > NOW() - INTERVAL '6 hours'
+ ORDER BY market_id, expected_edge DESC
+ ),
+ historical AS (
+ SELECT market_id,
+ COUNT(*) as total_trades,
+ COUNT(*) FILTER (WHERE pnl_cents > 0) as wins,
+ SUM(pnl_cents) as pnl_cents,
+ MODE() WITHIN GROUP (ORDER BY direction) as primary_direction,
+ ROUND(AVG(entry_price_cents)) as avg_entry
+ FROM ken_portfolio_trades
+ WHERE resolved_at IS NOT NULL
+ GROUP BY market_id
+ ),
+ snapshots AS (
+ SELECT DISTINCT ON (ticker)
+ ticker, title, yes_bid, no_bid, volume_24h, last_price
+ FROM ken_market_snapshots
+ WHERE captured_at > NOW() - INTERVAL '2 hours'
+ ORDER BY ticker, captured_at DESC
+ )
+ SELECT
+ s.market_id, COALESCE(snap.title, s.market_id) as title,
+ s.direction, s.expected_edge, s.confidence, s.risk_approved,
+ COALESCE(h.total_trades, 0) as hist_trades,
+ COALESCE(h.wins, 0) as hist_wins,
+ COALESCE(h.pnl_cents, 0) as hist_pnl,
+ COALESCE(h.avg_entry, 0) as avg_entry,
+ snap.yes_bid, snap.no_bid, snap.volume_24h,
+ LEFT(s.reasoning, 200) as reasoning
+ FROM recent_signals s
+ LEFT JOIN historical h ON h.market_id = s.market_id
+ LEFT JOIN snapshots snap ON snap.ticker = s.market_id
+ WHERE s.confidence >= 0.5
+ ORDER BY
+ (s.expected_edge * s.confidence * (1 + COALESCE(h.wins::float / NULLIF(h.total_trades, 0), 0))) DESC
+ LIMIT 3
+ `);
+
+ function edgeDescription(m) {
+ const wr = Number(m.wins) / (Number(m.wins) + Number(m.losses) || 1);
+ const dir = m.primary_direction === 'BUY_NO' ? 'NO' : 'YES';
+ const avg = Number(m.avg_entry);
+ if (wr >= 0.99 && avg >= 90) return `${dir} at ${avg}¢ = near-certain`;
+ if (wr >= 0.95 && avg >= 85) return `${dir} at ${avg}¢, market overprices`;
+ if (wr >= 0.80) return `${dir} side, ${(wr*100).toFixed(0)}% win rate`;
+ if (Number(m.total_trades) >= 150) return `High volume, clear direction`;
+ if (avg >= 80) return `${dir} at ${avg}¢, steady edge`;
+ return `${dir} side, avg ${avg}¢ entry`;
+ }
+
+ json(res, {
+ env: KALSHI_ENV,
+ safe_mode: true,
+ balance: totalBalance,
+ seed_money: seedMoney,
+ net_pnl_from_seed: totalBalance - seedMoney,
+ roi_pct: parseFloat(roi.toFixed(2)),
+ total_invested: totalInvested,
+ total_returned: totalReturned,
+ daily_budget: Number(budgetRow?.total_daily_budget || 0),
+ num_portfolios: Number(budgetRow?.num_portfolios || 0),
+ capital_at_risk: Number(riskRow?.capital_at_risk || 0),
+ open_positions_cost: Number(riskRow?.open_positions || 0),
+ daily_economics: spendRows.map(r => ({
+ day: r.day,
+ trades: Number(r.trades),
+ wins: Number(r.wins),
+ losses: Number(r.losses),
+ net_pnl: Number(r.net_pnl),
+ gross_wins: Number(r.gross_wins),
+ gross_losses: Number(r.gross_losses),
+ capital_deployed: Number(r.capital_deployed),
+ })),
+ position_count: Number(posRow?.open_count || 0),
+ open_orders: Number(posRow?.unique_markets || 0),
+ daily_pnl: Number(posRow?.daily_pnl || 0),
+ total_pnl: Number(posRow?.total_pnl || 0),
+ markets_tracked: cachedActiveMarkets.length,
+ today_trades: Number(todayRow?.trades || 0),
+ today_wins: Number(todayRow?.wins || 0),
+ today_losses: Number(todayRow?.losses || 0),
+ recent_fills: fills.map(f => ({
+ ticker: f.ticker,
+ title: f.market_title,
+ side: f.direction === 'BUY_YES' ? 'yes' : 'no',
+ count: f.contracts,
+ yes_price: f.entry_price_cents,
+ pnl: f.pnl_cents,
+ status: f.status,
+ })),
+ pnl_history: pnlHistory.map(p => Number(p.daily_pnl) / 100),
+ top_markets: topMarkets.map(m => {
+ const t = m.market_id || '';
+ const et = t.replace(/-[^-]+$/, '') || t;
+ const st = et.replace(/-[^-]+$/, '') || et;
+ return {
+ ticker: m.market_id,
+ title: m.market_title,
+ trades: Number(m.total_trades),
+ wins: Number(m.wins),
+ losses: Number(m.losses),
+ pnl: Number(m.pnl_cents),
+ edge: edgeDescription(m),
+ url: `https://kalshi.com/markets/${st.toLowerCase()}/${et.toLowerCase()}`,
+ }; }),
+ worst_markets: worstMarkets.map(m => {
+ const t = m.market_id || '';
+ const et = t.replace(/-[^-]+$/, '') || t;
+ const st = et.replace(/-[^-]+$/, '') || et;
+ return {
+ ticker: m.market_id,
+ title: m.market_title,
+ trades: Number(m.total_trades),
+ wins: Number(m.wins),
+ losses: Number(m.losses),
+ pnl: Number(m.pnl_cents),
+ edge: edgeDescription(m),
+ url: `https://kalshi.com/markets/${st.toLowerCase()}/${et.toLowerCase()}`,
+ }; }),
+ strategies: strategies.map(s => ({
+ name: s.name,
+ strategy: s.strategy,
+ wins: Number(s.trades_won),
+ losses: Number(s.trades_lost),
+ pnl: Number(s.net_pnl_cents),
+ balance: Number(s.balance_cents),
+ win_rate: Number(s.win_rate || 0),
+ })),
+ top_opportunities: opportunities.map(o => {
+ const wr = Number(o.hist_trades) > 0 ? Number(o.hist_wins) / Number(o.hist_trades) : null;
+ const dir = o.direction === 'BUY_NO' ? 'NO' : 'YES';
+ const edge = (parseFloat(o.expected_edge) * 100).toFixed(1);
+ const conf = (parseFloat(o.confidence) * 100).toFixed(0);
+ const yesBid = Number(o.yes_bid || 0);
+ const noBid = Number(o.no_bid || 0);
+ const price = o.direction === 'BUY_NO' ? noBid : yesBid;
+ // Build human-readable "why" from signal reasoning
+ const rawReasoning = o.reasoning || '';
+ const reasoningClean = rawReasoning.replace(/^BUY_(YES|NO) on "[^"]*"\s*—\s*/, '');
+ return {
+ ticker: o.market_id,
+ title: o.title,
+ direction: dir,
+ edge_pct: edge,
+ confidence: conf,
+ price_cents: price,
+ hist_trades: Number(o.hist_trades),
+ hist_wins: Number(o.hist_wins),
+ hist_wr: wr !== null ? (wr * 100).toFixed(1) : null,
+ hist_pnl: Number(o.hist_pnl),
+ volume_24h: Number(o.volume_24h || 0),
+ risk_approved: o.risk_approved,
+ why: reasoningClean,
+ url: (() => { const t = o.market_id || ''; const et = t.replace(/-[^-]+$/, '') || t; const st = et.replace(/-[^-]+$/, '') || et; return `https://kalshi.com/markets/${st.toLowerCase()}/${et.toLowerCase()}`; })(),
+ };
+ }),
+ });
+ } catch (err) {
+ json(res, { error: err.message }, 500);
+ }
+ },
+
+ // ════════════════════════════════════════
+ // SCAN CONFIG (User-adjustable intervals + risk params)
+ // ════════════════════════════════════════
+
+ 'GET /api/scan-config': async (req, res) => {
+ json(res, {
+ scan_interval_ms: SCAN_INTERVAL_MS,
+ signal_pipeline_ms: SIGNAL_PIPELINE_MS,
+ reddit_interval_ms: REDDIT_INTERVAL_MS,
+ resolve_interval_ms: RESOLVE_INTERVAL_MS,
+ min_edge_threshold: RISK_LIMITS.minEdgeThreshold,
+ min_liquidity: RISK_LIMITS.minLiquidity,
+ cached_markets: cachedActiveMarkets.length,
+ });
+ },
+
+ 'POST /api/scan-config': async (req, res) => {
+ try {
+ const body = await readBody(req);
+ let changed = false;
+ if (body.scan_interval_ms !== undefined) { SCAN_INTERVAL_MS = Math.max(60000, Math.min(3600000, Number(body.scan_interval_ms))); changed = true; }
+ if (body.signal_pipeline_ms !== undefined) { SIGNAL_PIPELINE_MS = Math.max(30000, Math.min(1800000, Number(body.signal_pipeline_ms))); changed = true; }
+ if (body.reddit_interval_ms !== undefined) { REDDIT_INTERVAL_MS = Math.max(60000, Math.min(3600000, Number(body.reddit_interval_ms))); changed = true; }
+ if (body.resolve_interval_ms !== undefined) { RESOLVE_INTERVAL_MS = Math.max(30000, Math.min(1800000, Number(body.resolve_interval_ms))); changed = true; }
+ if (body.min_edge_threshold !== undefined) { RISK_LIMITS.minEdgeThreshold = Math.max(0.005, Math.min(0.50, Number(body.min_edge_threshold))); changed = true; }
+ if (body.min_liquidity !== undefined) { RISK_LIMITS.minLiquidity = Math.max(0, Math.min(10000, Number(body.min_liquidity))); changed = true; }
+ if (changed) {
+ await saveScanConfig();
+ restartIntervals();
+ }
+ json(res, {
+ success: true,
+ scan_interval_ms: SCAN_INTERVAL_MS,
+ signal_pipeline_ms: SIGNAL_PIPELINE_MS,
+ reddit_interval_ms: REDDIT_INTERVAL_MS,
+ resolve_interval_ms: RESOLVE_INTERVAL_MS,
+ min_edge_threshold: RISK_LIMITS.minEdgeThreshold,
+ min_liquidity: RISK_LIMITS.minLiquidity,
+ cached_markets: cachedActiveMarkets.length,
+ });
+ } catch (err) {
+ json(res, { error: err.message }, 500);
+ }
+ },
+
+ // ════════════════════════════════════════
+ // MEMORY / SYSTEM STATUS
+ // ════════════════════════════════════════
+
+ 'GET /api/system': async (req, res) => {
+ const mem = process.memoryUsage();
+ json(res, {
+ memory: {
+ rss_mb: Math.round(mem.rss / 1024 / 1024),
+ heapUsed_mb: Math.round(mem.heapUsed / 1024 / 1024),
+ heapTotal_mb: Math.round(mem.heapTotal / 1024 / 1024),
+ external_mb: Math.round(mem.external / 1024 / 1024),
+ },
+ uptime_hours: Math.round(process.uptime() / 3600 * 10) / 10,
+ env: KALSHI_ENV,
+ cachedMarkets: cachedActiveMarkets.length,
+ pid: process.pid,
+ cpuCores: os.cpus().length,
+ enhancements: {
+ monteCarloIterations: 15000,
+ geminiModel: GEMINI_MODEL,
+ geminiCallsToday: geminiCallCount,
+ geminiDailyLimit: GEMINI_DAILY_LIMIT,
+ scanInterval: '8m',
+ signalPipeline: '2m',
+ redditInterval: '15m',
+ momentumCacheSize: Object.keys(cachedMomentumMap).length,
+ },
+ });
+ },
+
+ // ── Portfolios API ──
+ 'GET /api/portfolios': async (req, res) => {
+ try {
+ const { rows: portfolios } = await kenQ(`SELECT * FROM ken_portfolios ORDER BY id`);
+ // Get today's trade counts per portfolio
+ for (const pf of portfolios) {
+ const { rows: today } = await kenQ(`
+ SELECT COUNT(*) as trades_today, COALESCE(SUM(cost_cents),0) as spent_today
+ FROM ken_portfolio_trades WHERE portfolio_id = $1 AND created_at::date = CURRENT_DATE
+ `, [pf.id]);
+ pf.trades_today = parseInt(today[0]?.trades_today) || 0;
+ pf.spent_today = parseInt(today[0]?.spent_today) || 0;
+ pf.budget_remaining = Math.max(0, pf.balance_cents); // Remaining = whatever balance is left
+
+ // Win rate
+ const totalResolved = pf.trades_won + pf.trades_lost + pf.trades_expired;
+ pf.win_rate = totalResolved > 0 ? Math.round(pf.trades_won / totalResolved * 100) : 0;
+ pf.total_resolved = totalResolved;
+ pf.is_bankrupt = pf.balance_cents <= 0;
+ }
+ // Sort: active portfolios by ROI (best first), bankrupt portfolios at bottom
+ portfolios.sort((a, b) => {
+ if (a.is_bankrupt !== b.is_bankrupt) return a.is_bankrupt ? 1 : -1;
+ const aROI = a.total_invested_cents > 0 ? (a.total_returned_cents - a.total_invested_cents) / a.total_invested_cents : 0;
+ const bROI = b.total_invested_cents > 0 ? (b.total_returned_cents - b.total_invested_cents) / b.total_invested_cents : 0;
+ return bROI - aROI;
+ });
+ json(res, portfolios);
+ } catch(e) { json(res, { error: e.message }, 500); }
+ },
+
+ 'GET /api/portfolio-trades': async (req, res) => {
+ try {
+ const url = new URL(req.url, 'http://x');
+ const pfId = url.searchParams.get('portfolio_id');
+ const status = url.searchParams.get('status');
+ let q = `SELECT * FROM ken_portfolio_trades`;
+ const params = [];
+ const conds = [];
+ if (pfId) { conds.push(`portfolio_id = $${params.length+1}`); params.push(pfId); }
+ if (status) { conds.push(`status = $${params.length+1}`); params.push(status); }
+ if (conds.length) q += ' WHERE ' + conds.join(' AND ');
+ q += ' ORDER BY created_at DESC LIMIT 200';
+ const { rows } = await kenQ(q, params);
+ json(res, rows);
+ } catch(e) { json(res, { error: e.message }, 500); }
+ },
+
+ // ── PortFAUXlio Charts API — time-series NAV data ──
+ 'GET /api/portfauxlio/charts': async (req, res) => {
+ try {
+ const url = new URL(req.url, 'http://x');
+ const period = url.searchParams.get('period') || '7d';
+ const intervals = { '1d': '1 day', '3d': '3 days', '7d': '7 days', '14d': '14 days', '30d': '30 days' };
+ const interval = intervals[period] || '7 days';
+
+ // Snapshots (intraday)
+ const { rows: snapRows } = await kenQ(`
+ SELECT s.portfolio_id, s.nav_cents, s.open_positions, s.snapshot_at, p.name, p.strategy
+ FROM ken_portfolio_snapshots s JOIN ken_portfolios p ON p.id = s.portfolio_id
+ WHERE s.snapshot_at > NOW() - INTERVAL '${interval}' ORDER BY s.portfolio_id, s.snapshot_at ASC
+ `);
+
+ // Daily P&L (longer-term)
+ const { rows: dailyRows } = await kenQ(`
+ SELECT dp.portfolio_id, dp.date, dp.daily_pnl_cents, dp.cumulative_pnl_cents,
+ dp.wins, dp.losses, dp.closed_trades, p.name, p.strategy
+ FROM ken_daily_pnl dp JOIN ken_portfolios p ON p.id = dp.portfolio_id
+ WHERE dp.date > CURRENT_DATE - INTERVAL '${interval}' ORDER BY dp.portfolio_id, dp.date ASC
+ `);
+
+ const byPortfolio = {};
+ for (const r of snapRows) {
+ if (!byPortfolio[r.portfolio_id]) byPortfolio[r.portfolio_id] = { id: r.portfolio_id, name: r.name, strategy: r.strategy, snapshots: [], daily: [] };
+ byPortfolio[r.portfolio_id].snapshots.push({ nav: r.nav_cents, openPositions: r.open_positions, time: r.snapshot_at });
+ }
+ for (const r of dailyRows) {
+ if (!byPortfolio[r.portfolio_id]) byPortfolio[r.portfolio_id] = { id: r.portfolio_id, name: r.name, strategy: r.strategy, snapshots: [], daily: [] };
+ byPortfolio[r.portfolio_id].daily.push({ date: r.date, pnl: r.daily_pnl_cents, cumulative: r.cumulative_pnl_cents, wins: r.wins, losses: r.losses, trades: r.closed_trades });
+ }
+
+ json(res, { portfolios: Object.values(byPortfolio), period });
+ } catch (e) { json(res, { error: e.message }, 500); }
+ },
+
+ // ── PortFAUXlio SWOT — trades with strengths/weaknesses/opportunities/threats ──
+ 'GET /api/portfauxlio/swot': async (req, res) => {
+ try {
+ const { rows: trades } = await kenQ(`
+ SELECT t.id, t.market_id, t.market_title, t.direction, t.entry_price_cents,
+ t.contracts, t.cost_cents, t.status, t.pnl_cents, t.reasoning,
+ t.confidence, t.ai_enhanced, t.mc_consistent, t.created_at, t.resolved_at,
+ p.name AS portfolio_name, p.strategy, p.id AS portfolio_id
+ FROM ken_portfolio_trades t JOIN ken_portfolios p ON p.id = t.portfolio_id
+ WHERE t.created_at > NOW() - INTERVAL '7 days'
+ ORDER BY t.created_at DESC LIMIT 200
+ `);
+
+ // Group by market
+ const byMarket = {};
+ for (const t of trades) {
+ if (!byMarket[t.market_id]) byMarket[t.market_id] = { market_id: t.market_id, title: t.market_title || t.market_id, trades: [], totalCost: 0, totalPnl: 0, models: new Set() };
+ const m = byMarket[t.market_id];
+ m.trades.push(t);
+ m.totalCost += parseInt(t.cost_cents) || 0;
+ m.totalPnl += parseInt(t.pnl_cents) || 0;
+ m.models.add(t.portfolio_name);
+ }
+
+ // Generate SWOT for each market group
+ const swotMarkets = Object.values(byMarket).map(m => {
+ const t0 = m.trades[0];
+ const conf = parseFloat(t0.confidence) || 0;
+ const aiCount = m.trades.filter(t => t.ai_enhanced).length;
+ const mcCount = m.trades.filter(t => t.mc_consistent).length;
+ const totalT = m.trades.length;
+ const openCount = m.trades.filter(t => t.status === 'open').length;
+ const reasoning = t0.reasoning || '';
+
+ // Parse edge from reasoning
+ const edgeMatch = reasoning.match(/edge\s*([\d.]+)%/i);
+ const edge = edgeMatch ? parseFloat(edgeMatch[1]) : 0;
+ const mcMatch = reasoning.match(/MC:\s*\u03bc=([\d.]+)%\s*\u00b1\s*([\d.]+)%/);
+ const mcMean = mcMatch ? parseFloat(mcMatch[1]) : 0;
+ const mcStd = mcMatch ? parseFloat(mcMatch[2]) : 0;
+ const artMatch = reasoning.match(/(\d+)\s*articles?/i);
+ const articles = artMatch ? parseInt(artMatch[1]) : 0;
+ const agreeMatch = reasoning.match(/Agreement:\s*([\d.]+)%/i);
+ const agreement = agreeMatch ? parseFloat(agreeMatch[1]) : 0;
+
+ // SWOT generation
+ const strengths = [];
+ const weaknesses = [];
+ const opportunities = [];
+ const threats = [];
+
+ // Strengths
+ if (conf >= 0.6) strengths.push('High confidence (' + Math.round(conf * 100) + '%)');
+ if (mcCount > totalT * 0.5) strengths.push('Monte Carlo validated (' + mcCount + '/' + totalT + ' models)');
+ if (aiCount > 0) strengths.push('AI enhanced signals');
+ if (totalT >= 3) strengths.push('Multi-model consensus (' + totalT + ' models agree)');
+ if (agreement >= 80) strengths.push('Strong news agreement (' + agreement + '%)');
+ if (articles >= 3) strengths.push('Strong news coverage (' + articles + ' articles)');
+ if (edge >= 15) strengths.push('Large statistical edge (' + edge.toFixed(1) + '%)');
+ if (strengths.length === 0) strengths.push('Active position in play');
+
+ // Weaknesses
+ if (conf < 0.4) weaknesses.push('Low confidence (' + Math.round(conf * 100) + '%)');
+ if (mcCount === 0) weaknesses.push('No Monte Carlo validation');
+ if (aiCount === 0) weaknesses.push('No AI enhancement');
+ if (articles <= 1) weaknesses.push('Limited news coverage (' + articles + ' article' + (articles === 1 ? '' : 's') + ')');
+ if (edge < 5 && edge > 0) weaknesses.push('Narrow edge (' + edge.toFixed(1) + '%)');
+ if (mcStd > 10) weaknesses.push('High MC uncertainty (\u00b1' + mcStd.toFixed(1) + '%)');
+ if (weaknesses.length === 0) weaknesses.push('No significant weaknesses identified');
+
+ // Opportunities
+ if (edge >= 8) opportunities.push('Exploitable edge of ' + edge.toFixed(1) + '%');
+ if (m.models.size >= 5) opportunities.push(m.models.size + ' models see opportunity');
+ if (mcMean > edge) opportunities.push('MC mean (' + mcMean.toFixed(1) + '%) exceeds raw edge');
+ if (openCount > 0) opportunities.push(openCount + ' open position' + (openCount > 1 ? 's' : '') + ' tracking');
+ if (opportunities.length === 0) opportunities.push('Market exposure maintained');
+
+ // Threats
+ if (mcStd > 8) threats.push('High volatility (MC \u00b1' + mcStd.toFixed(1) + '%)');
+ if (agreement < 60 && agreement > 0) threats.push('Mixed news sentiment (' + agreement + '% agreement)');
+ if (m.totalPnl < 0) threats.push('Currently underwater ($' + (Math.abs(m.totalPnl) / 100).toFixed(2) + ' loss)');
+ const direction = t0.direction;
+ if (direction === 'BUY_YES' && edge < 10) threats.push('Thin YES margin — small price move could flip');
+ if (direction === 'BUY_NO' && conf < 0.5) threats.push('NO position with uncertain conviction');
+ if (threats.length === 0) threats.push('Standard market risk');
+
+ return {
+ market_id: m.market_id,
+ title: m.title,
+ direction: t0.direction,
+ edge,
+ confidence: conf,
+ articles,
+ agreement,
+ mc_mean: mcMean,
+ mc_std: mcStd,
+ model_count: totalT,
+ models: [...m.models],
+ open_count: openCount,
+ total_cost: m.totalCost,
+ total_pnl: m.totalPnl,
+ entry_price: parseInt(t0.entry_price_cents) || 0,
+ first_trade: m.trades[m.trades.length - 1]?.created_at,
+ reasoning: reasoning.substring(0, 200),
+ swot: { strengths, weaknesses, opportunities, threats },
+ trades: m.trades.map(t => ({
+ id: t.id, portfolio: t.portfolio_name, strategy: t.strategy,
+ direction: t.direction, contracts: t.contracts,
+ cost: parseInt(t.cost_cents) || 0, pnl: parseInt(t.pnl_cents) || 0,
+ status: t.status, created_at: t.created_at
+ }))
+ };
+ });
+
+ // Sort by model count desc (most consensus first)
+ swotMarkets.sort((a, b) => b.model_count - a.model_count);
+
+ json(res, { markets: swotMarkets, total_trades: trades.length });
+ } catch (e) { json(res, { error: e.message }, 500); }
+ },
+
+ // ── Weekly Tournament System — survive or die ──
+ 'GET /api/tournament/current': async (req, res) => {
+ try {
+ const { rows: [tourney] } = await kenQ(`SELECT * FROM ken_weekly_tournaments WHERE status = 'active' ORDER BY id DESC LIMIT 1`);
+ if (!tourney) return json(res, { active: false, message: 'No active tournament' });
+ const { rows: entries } = await kenQ(`
+ SELECT e.*, p.name, p.strategy, p.balance_cents, p.total_invested_cents, p.total_returned_cents,
+ p.trades_won, p.trades_lost, p.daily_budget_cents
+ FROM ken_tournament_entries e JOIN ken_portfolios p ON p.id = e.portfolio_id
+ WHERE e.tournament_id = $1 ORDER BY e.pnl_cents DESC NULLS LAST
+ `, [tourney.id]);
+ // Compute live P&L for each entry
+ for (const e of entries) {
+ const { rows: [stats] } = await kenQ(`
+ SELECT COUNT(*) as trades, COALESCE(SUM(cost_cents),0) as total_cost,
+ COALESCE(SUM(CASE WHEN status IN ('won','lost','closed') THEN pnl_cents ELSE 0 END),0) as realized_pnl
+ FROM ken_portfolio_trades WHERE portfolio_id = $1 AND created_at >= $2
+ `, [e.portfolio_id, tourney.week_start]);
+ e.live_trades = parseInt(stats.trades) || 0;
+ e.live_invested = parseInt(stats.total_cost) || 0;
+ e.live_pnl = parseInt(stats.realized_pnl) || 0;
+ }
+ json(res, { active: true, tournament: tourney, entries });
+ } catch (e) { json(res, { error: e.message }, 500); }
+ },
+
+ 'POST /api/tournament/start': async (req, res) => {
+ try {
+ const body = await readBody(req);
+ const portfolioIds = body.portfolio_ids || [];
+ const budgetCents = body.budget_cents || 2000; // $20 default
+ const notes = body.notes || '';
+ const weeks = body.weeks || 1;
+ if (portfolioIds.length < 1 || portfolioIds.length > 10) return json(res, { error: 'Pick 1-10 portfolios' }, 400);
+ // Check no active tournament
+ const { rows: active } = await kenQ(`SELECT id FROM ken_weekly_tournaments WHERE status = 'active'`);
+ if (active.length > 0) return json(res, { error: 'Tournament already active. Evaluate or cancel it first.', active_id: active[0].id }, 400);
+ const weekStart = new Date(); weekStart.setHours(0,0,0,0);
+ const weekEnd = new Date(weekStart); weekEnd.setDate(weekEnd.getDate() + 7 * weeks);
+ const { rows: [tourney] } = await kenQ(`
+ INSERT INTO ken_weekly_tournaments (week_start, week_end, budget_per_portfolio_cents, notes)
+ VALUES ($1, $2, $3, $4) RETURNING *
+ `, [weekStart.toISOString().split('T')[0], weekEnd.toISOString().split('T')[0], budgetCents, notes]);
+ const entries = [];
+ for (const pid of portfolioIds) {
+ const { rows: [pf] } = await kenQ(`SELECT * FROM ken_portfolios WHERE id = $1`, [pid]);
+ if (!pf) continue;
+ // Set portfolio budget for the tournament
+ await kenQ(`UPDATE ken_portfolios SET daily_budget_cents = $1, balance_cents = $2 WHERE id = $3`, [Math.round(budgetCents / 7), budgetCents, pid]);
+ const { rows: [entry] } = await kenQ(`
+ INSERT INTO ken_tournament_entries (tournament_id, portfolio_id, start_balance_cents, status)
+ VALUES ($1, $2, $3, 'alive') RETURNING *
+ `, [tourney.id, pid, budgetCents]);
+ entries.push({ ...entry, name: pf.name, strategy: pf.strategy });
+ }
+ json(res, { tournament: tourney, entries, message: `Tournament started with ${entries.length} portfolios at $${(budgetCents/100).toFixed(2)} each` });
+ } catch (e) { json(res, { error: e.message }, 500); }
+ },
+
+ 'POST /api/tournament/evaluate': async (req, res) => {
+ try {
+ const { rows: [tourney] } = await kenQ(`SELECT * FROM ken_weekly_tournaments WHERE status = 'active' ORDER BY id DESC LIMIT 1`);
+ if (!tourney) return json(res, { error: 'No active tournament' }, 400);
+ const { rows: entries } = await kenQ(`
+ SELECT e.*, p.name, p.strategy FROM ken_tournament_entries e
+ JOIN ken_portfolios p ON p.id = e.portfolio_id WHERE e.tournament_id = $1
+ `, [tourney.id]);
+ const results = [];
+ for (const e of entries) {
+ const { rows: [stats] } = await kenQ(`
+ SELECT COUNT(*) as trades,
+ COALESCE(SUM(CASE WHEN status='won' THEN payout_cents - cost_cents WHEN status='lost' THEN -cost_cents ELSE 0 END),0) as pnl
+ FROM ken_portfolio_trades WHERE portfolio_id = $1 AND created_at >= $2
+ `, [e.portfolio_id, tourney.week_start]);
+ const pnl = parseInt(stats.pnl) || 0;
+ const trades = parseInt(stats.trades) || 0;
+ const survived = pnl >= 0;
+ await kenQ(`UPDATE ken_tournament_entries SET end_balance_cents = $1, pnl_cents = $2, trades_count = $3, status = $4, elimination_reason = $5 WHERE id = $6`,
+ [e.start_balance_cents + pnl, pnl, trades, survived ? 'survived' : 'eliminated', survived ? null : `Lost $${(Math.abs(pnl)/100).toFixed(2)}`, e.id]);
+ if (!survived) await kenQ(`UPDATE ken_portfolios SET daily_budget_cents = 0 WHERE id = $1`, [e.portfolio_id]);
+ results.push({ name: e.name, strategy: e.strategy, pnl_cents: pnl, trades, status: survived ? 'SURVIVED' : 'ELIMINATED' });
+ }
+ await kenQ(`UPDATE ken_weekly_tournaments SET status = 'completed' WHERE id = $1`, [tourney.id]);
+ const survivors = results.filter(r => r.status === 'SURVIVED');
+ const eliminated = results.filter(r => r.status === 'ELIMINATED');
+ json(res, { tournament_id: tourney.id, results, survivors: survivors.length, eliminated: eliminated.length, message: `${survivors.length} survived, ${eliminated.length} eliminated` });
+ } catch (e) { json(res, { error: e.message }, 500); }
+ },
+
+ 'POST /api/tournament/cancel': async (req, res) => {
+ try {
+ const { rows: [tourney] } = await kenQ(`SELECT * FROM ken_weekly_tournaments WHERE status = 'active' ORDER BY id DESC LIMIT 1`);
+ if (!tourney) return json(res, { error: 'No active tournament' }, 400);
+ await kenQ(`UPDATE ken_weekly_tournaments SET status = 'cancelled' WHERE id = $1`, [tourney.id]);
+ await kenQ(`UPDATE ken_tournament_entries SET status = 'cancelled' WHERE tournament_id = $1`, [tourney.id]);
+ json(res, { message: 'Tournament cancelled', id: tourney.id });
+ } catch (e) { json(res, { error: e.message }, 500); }
+ },
+
+ 'GET /api/tournament/history': async (req, res) => {
+ try {
+ const { rows: tournaments } = await kenQ(`SELECT * FROM ken_weekly_tournaments ORDER BY id DESC LIMIT 20`);
+ for (const t of tournaments) {
+ const { rows: entries } = await kenQ(`
+ SELECT e.*, p.name, p.strategy FROM ken_tournament_entries e
+ JOIN ken_portfolios p ON p.id = e.portfolio_id WHERE e.tournament_id = $1 ORDER BY e.pnl_cents DESC NULLS LAST
+ `, [t.id]);
+ t.entries = entries;
+ }
+ json(res, tournaments);
+ } catch (e) { json(res, { error: e.message }, 500); }
+ },
+
+ // ── PortFAUXlio Dashboard API — full simulated trading view ──
+ 'GET /api/portfauxlio': async (req, res) => {
+ try {
+ // 1. All portfolios with computed stats
+ const { rows: portfolios } = await kenQ(`
+ SELECT p.*,
+ (p.total_returned_cents - p.total_invested_cents) AS pnl_cents,
+ CASE WHEN p.total_invested_cents > 0
+ THEN ROUND((p.total_returned_cents - p.total_invested_cents)::numeric / p.total_invested_cents * 100, 1)
+ ELSE 0 END AS roi_pct,
+ (p.trades_won + p.trades_lost + p.trades_expired) AS resolved_trades,
+ CASE WHEN (p.trades_won + p.trades_lost) > 0
+ THEN ROUND(p.trades_won::numeric / (p.trades_won + p.trades_lost) * 100, 0)
+ ELSE 0 END AS win_rate
+ FROM ken_portfolios p ORDER BY (p.total_returned_cents - p.total_invested_cents) DESC
+ `);
+
+ // 2. All active (open) trades across all portfolios
+ const { rows: activeTrades } = await kenQ(`
+ SELECT t.id, t.portfolio_id, t.market_id, t.market_title, t.direction,
+ t.contracts, t.entry_price_cents, t.cost_cents, t.confidence, t.created_at,
+ p.name AS portfolio_name, p.strategy
+ FROM ken_portfolio_trades t
+ JOIN ken_portfolios p ON p.id = t.portfolio_id
+ WHERE t.status = 'open'
+ ORDER BY t.created_at DESC
+ `);
+
+ // 3. Trade history (all trades, most recent first)
+ const { rows: tradeHistory } = await kenQ(`
+ SELECT t.id, t.portfolio_id, t.market_id, t.market_title, t.direction,
+ t.contracts, t.entry_price_cents, t.cost_cents, t.pnl_cents, t.status,
+ t.confidence, t.created_at, t.resolved_at,
+ p.name AS portfolio_name, p.strategy
+ FROM ken_portfolio_trades t
+ JOIN ken_portfolios p ON p.id = t.portfolio_id
+ ORDER BY t.created_at DESC LIMIT 200
+ `);
+
+ // 4. Per-model trade distribution: which markets each strategy traded
+ const { rows: modelMarkets } = await kenQ(`
+ SELECT p.strategy, t.market_id,
+ COUNT(*) AS trade_count,
+ SUM(t.cost_cents) AS total_cost,
+ MAX(t.created_at) AS last_trade
+ FROM ken_portfolio_trades t
+ JOIN ken_portfolios p ON p.id = t.portfolio_id
+ GROUP BY p.strategy, t.market_id
+ ORDER BY p.strategy, trade_count DESC
+ `);
+
+ // 5. Overlap analysis: markets traded by 3+ strategies
+ const { rows: overlaps } = await kenQ(`
+ SELECT t.market_id,
+ COUNT(DISTINCT p.strategy) AS num_strategies,
+ ARRAY_AGG(DISTINCT p.name ORDER BY p.name) AS portfolios,
+ SUM(t.cost_cents) AS total_exposure
+ FROM ken_portfolio_trades t
+ JOIN ken_portfolios p ON p.id = t.portfolio_id
+ GROUP BY t.market_id
+ HAVING COUNT(DISTINCT p.strategy) >= 2
+ ORDER BY num_strategies DESC
+ `);
+
+ // 6. Summary stats
+ const totalInvested = portfolios.reduce((s, p) => s + (parseInt(p.total_invested_cents) || 0), 0);
+ const totalReturned = portfolios.reduce((s, p) => s + (parseInt(p.total_returned_cents) || 0), 0);
+ const totalTrades = tradeHistory.length;
+ const openTrades = activeTrades.length;
+ const uniqueMarkets = [...new Set(tradeHistory.map(t => t.market_id))].length;
+
+ json(res, {
+ portfolios,
+ activeTrades,
+ tradeHistory,
+ modelMarkets,
+ overlaps,
+ summary: {
+ totalInvested, totalReturned,
+ totalPnl: totalReturned - totalInvested,
+ totalTrades, openTrades, uniqueMarkets,
+ activeModels: portfolios.filter(p => parseInt(p.total_invested_cents) > 0).length,
+ }
+ });
+ } catch(e) { json(res, { error: e.message }, 500); }
+ },
+
+ 'GET /api/predictions-history': async (req, res) => {
+ try {
+ const { rows } = await kenQ(`
+ SELECT id, ticker, title, signal_type, side, confidence, entry_price, exit_price,
+ edge_bps, outcome, pnl_cents, reasoning, created_at, resolved_at
+ FROM ken_predictions
+ WHERE outcome != 'pending'
+ ORDER BY resolved_at DESC NULLS LAST
+ LIMIT 100
+ `);
+ // Also get stats
+ const { rows: stats } = await kenQ(`
+ SELECT outcome, COUNT(*) as cnt, ROUND(AVG(pnl_cents),1) as avg_pnl,
+ ROUND(AVG(confidence),1) as avg_conf
+ FROM ken_predictions WHERE outcome != 'pending'
+ GROUP BY outcome
+ `);
+ json(res, { predictions: rows, stats });
+ } catch(e) { json(res, { error: e.message }, 500); }
+ },
+
+ 'GET /api/daily-pnl': async (req, res) => {
+ try {
+ const { rows } = await kenQ(`
+ SELECT dp.*, p.name as portfolio_name
+ FROM ken_daily_pnl dp
+ JOIN ken_portfolios p ON p.id = dp.portfolio_id
+ ORDER BY dp.date DESC, dp.portfolio_id
+ LIMIT 200
+ `);
+ json(res, rows);
+ } catch(e) { json(res, { error: e.message }, 500); }
+ },
+
+ // ── Heating & Weather Intelligence API ──
+ 'GET /api/heating-intel': async (req, res) => {
+ try {
+ const { rows: posts } = await kenQ(`
+ SELECT source, subreddit as area, keyword, post_title as title, post_url as url,
+ score, sentiment_score, raw_text, captured_at
+ FROM ken_sentiment
+ WHERE source IN ('heating_intel', 'noaa_alert', 'noaa_forecast')
+ ORDER BY captured_at DESC
+ LIMIT 50
+ `);
+ const { rows: stats } = await kenQ(`
+ SELECT source, COUNT(*) as cnt,
+ ROUND(AVG(sentiment_score)::numeric, 2) as avg_sentiment,
+ ROUND(AVG(score)::numeric, 0) as avg_score
+ FROM ken_sentiment
+ WHERE source IN ('heating_intel', 'noaa_alert', 'noaa_forecast')
+ AND captured_at > NOW() - INTERVAL '7 days'
+ GROUP BY source
+ `);
+ json(res, { posts, stats, keywords: HEATING_KEYWORDS });
+ } catch(e) { json(res, { error: e.message }, 500); }
+ },
+
+ // ── Ken Inc Command Center API ──
+ 'GET /api/inc': async (req, res) => {
+ const mem = process.memoryUsage();
+ // Get recent signals
+ let recentSignals = [];
+ try {
+ const { rows } = await kenQ(`SELECT market_id, direction, expected_edge, confidence, reasoning, risk_approved, created_at
+ FROM ken_strategy_signals ORDER BY created_at DESC LIMIT 20`);
+ recentSignals = rows;
+ } catch(e) {}
+
+ // Get pipeline stats
+ let pipelineStats = {};
+ try {
+ const { rows } = await kenQ(`SELECT COUNT(*) as total_signals,
+ COUNT(*) FILTER (WHERE risk_approved = true) as approved,
+ COUNT(*) FILTER (WHERE created_at > NOW() - INTERVAL '1 hour') as last_hour,
+ AVG(ABS(expected_edge::numeric)) as avg_edge,
+ MAX(confidence::numeric) as max_confidence
+ FROM ken_strategy_signals WHERE created_at > NOW() - INTERVAL '24 hours'`);
+ pipelineStats = rows[0] || {};
+ } catch(e) {}
+
+ // Sentiment stats
+ let sentimentStats = {};
+ try {
+ const { rows } = await kenQ(`SELECT COUNT(*) as total_articles,
+ COUNT(DISTINCT source) as unique_sources,
+ AVG(sentiment_score) as avg_sentiment
+ FROM ken_sentiment WHERE captured_at > NOW() - INTERVAL '24 hours'`);
+ sentimentStats = rows[0] || {};
+ } catch(e) {}
+
+ // Market snapshot stats
+ let marketStats = {};
+ try {
+ const { rows } = await kenQ(`SELECT COUNT(DISTINCT ticker) as tracked_markets
+ FROM ken_market_snapshots WHERE captured_at > NOW() - INTERVAL '24 hours'`);
+ marketStats = rows[0] || {};
+ } catch(e) {}
+
+ // Build sub-agent status
+ const subAgents = [
+ {
+ id: 'scout', name: 'Scout', role: 'Intelligence Gatherer', emoji: '🔍',
+ color: '#3B82F6', status: 'active',
+ desc: 'Sweeps 77 subreddits, 71 RSS feeds, HN, YouTube, Bluesky, Mastodon, Discord',
+ stats: { articles24h: parseInt(sentimentStats.total_articles) || 0, sources: parseInt(sentimentStats.unique_sources) || 0 },
+ skills: ['Reddit Scraping', 'RSS Feeds', 'Social Media', 'GDELT TV', 'YouTube', 'Lemmy', 'Lobsters'],
+ },
+ {
+ id: 'oracle', name: 'Oracle', role: 'Monte Carlo Engine', emoji: '🎲',
+ color: '#8B5CF6', status: 'active',
+ desc: 'Runs 15,000 iteration Monte Carlo simulations on every signal for probability validation',
+ stats: { iterations: 15000, cores: os.cpus().length, momentumTracked: Object.keys(cachedMomentumMap).length },
+ skills: ['Monte Carlo Simulation', 'Bayesian Inference', 'Ensemble Probability', 'Confidence Intervals'],
+ },
+ {
+ id: 'gemini', name: 'Nova', role: 'AI Analyst', emoji: '🧠',
+ color: '#EC4899', status: geminiCallCount < GEMINI_DAILY_LIMIT ? 'active' : 'rate_limited',
+ desc: 'Gemini 2.0 Flash analyzes high-edge signals with natural language reasoning',
+ stats: { callsToday: geminiCallCount, dailyBudget: GEMINI_DAILY_LIMIT, model: GEMINI_MODEL },
+ skills: ['Signal Analysis', 'News Interpretation', 'Risk Assessment', 'Market Reasoning'],
+ },
+ {
+ id: 'pulse', name: 'Pulse', role: 'Sentiment Analyst', emoji: '💓',
+ color: '#EF4444', status: 'active',
+ desc: '75 event-specific rules across 7 categories with certainty modifiers and source diversity scoring',
+ stats: { rules: 75, categories: 7, avgSentiment: parseFloat(sentimentStats.avg_sentiment || 0).toFixed(3) },
+ skills: ['Event Sentiment', 'Certainty Detection', 'Multi-source Agreement', 'Category Weighting'],
+ },
+ {
+ id: 'hawk', name: 'Hawk', role: 'Market Watcher', emoji: '🦅',
+ color: '#F59E0B', status: 'active',
+ desc: 'Tracks momentum, volume spikes, spreads, and price action across all active markets',
+ stats: { activeMarkets: cachedActiveMarkets.length, trackedMarkets: parseInt(marketStats.tracked_markets) || 0 },
+ skills: ['Momentum Tracking', 'Volume Analysis', 'Spread Detection', 'Price Action'],
+ },
+ {
+ id: 'arbiter', name: 'Arbiter', role: 'Cross-Market Arbitrage', emoji: '⚖️',
+ color: '#14B8A6', status: 'active',
+ desc: 'Compares Kalshi prices vs Polymarket, PredictIt, Manifold, Metaculus for arbitrage',
+ stats: { platforms: 5 },
+ skills: ['Polymarket', 'PredictIt', 'Manifold', 'Metaculus', 'Fuzzy Matching'],
+ },
+ {
+ id: 'shield', name: 'Shield', role: 'Risk Manager', emoji: '🛡️',
+ color: '#22C55E', status: 'active',
+ desc: 'Enforces exposure limits, edge thresholds, time decay, and liquidity requirements',
+ stats: {
+ signalsApproved: parseInt(pipelineStats.approved) || 0,
+ totalSignals: parseInt(pipelineStats.total_signals) || 0,
+ maxConf: parseFloat(pipelineStats.max_confidence || 0).toFixed(2),
+ },
+ skills: ['Position Sizing', 'Exposure Limits', 'Edge Threshold', 'Time Decay', 'Liquidity Check'],
+ },
+ {
+ id: 'storm', name: 'Storm', role: 'Weather Predictor', emoji: '⛈️',
+ color: '#06B6D4', status: 'active',
+ desc: 'NWS forecast data + Bayesian model for 11 US cities, climatological priors by season',
+ stats: { cities: 11 },
+ skills: ['NWS Forecasts', 'Bayesian Weather', 'Climatological Priors', 'Temperature/Precip/Wind'],
+ },
+ ];
+
+ json(res, {
+ ceo: { name: 'Ken', title: 'CEO, Ken Inc.', tagline: 'Trading Intelligence Corporation', color: '#FF69B4' },
+ agents: subAgents,
+ pipeline: {
+ signalsLast24h: parseInt(pipelineStats.total_signals) || 0,
+ approvedLast24h: parseInt(pipelineStats.approved) || 0,
+ lastHour: parseInt(pipelineStats.last_hour) || 0,
+ avgEdge: parseFloat(pipelineStats.avg_edge || 0).toFixed(3),
+ },
+ system: {
+ memory_mb: Math.round(mem.rss / 1024 / 1024),
+ uptime_hours: Math.round(process.uptime() / 3600 * 10) / 10,
+ cpuCores: os.cpus().length,
+ pid: process.pid,
+ },
+ recentSignals: recentSignals.map(s => ({
+ market: s.market_id,
+ direction: s.direction,
+ edge: parseFloat(s.expected_edge || 0),
+ confidence: parseFloat(s.confidence || 0),
+ approved: s.risk_approved,
+ reasoning: s.reasoning?.substring(0, 200),
+ time: s.created_at,
+ })),
+ });
+ },
+
+ // ── Market Data — stock-market style data points ──
+ 'GET /api/inc/market-data': async (req, res) => {
+ const out = {};
+
+ // 1. Hourly signal volume — last 24h in 1-hour buckets
+ try {
+ const { rows } = await kenQ(`SELECT date_trunc('hour', created_at) AS hour,
+ COUNT(*) AS signals, COUNT(*) FILTER (WHERE risk_approved) AS approved,
+ AVG(ABS(expected_edge::numeric)) AS avg_edge,
+ AVG(confidence::numeric) AS avg_confidence
+ FROM ken_strategy_signals
+ WHERE created_at > NOW() - INTERVAL '24 hours'
+ GROUP BY 1 ORDER BY 1`);
+ out.signalTrend = rows.map(r => ({
+ hour: r.hour, signals: parseInt(r.signals), approved: parseInt(r.approved),
+ avgEdge: parseFloat(parseFloat(r.avg_edge || 0).toFixed(4)),
+ avgConf: parseFloat(parseFloat(r.avg_confidence || 0).toFixed(3)),
+ }));
+ } catch { out.signalTrend = []; }
+
+ // 2. Sentiment volume by hour — last 24h
+ try {
+ const { rows } = await kenQ(`SELECT date_trunc('hour', captured_at) AS hour,
+ COUNT(*) AS articles, AVG(sentiment_score) AS avg_sentiment,
+ COUNT(DISTINCT source) AS sources
+ FROM ken_sentiment
+ WHERE captured_at > NOW() - INTERVAL '24 hours'
+ GROUP BY 1 ORDER BY 1`);
+ out.sentimentTrend = rows.map(r => ({
+ hour: r.hour, articles: parseInt(r.articles),
+ avgSentiment: parseFloat(parseFloat(r.avg_sentiment || 0).toFixed(3)),
+ sources: parseInt(r.sources),
+ }));
+ } catch { out.sentimentTrend = []; }
+
+ // 3. Top sentiment sources with counts
+ try {
+ const { rows } = await kenQ(`SELECT source, COUNT(*) AS cnt,
+ AVG(sentiment_score) AS avg_sent
+ FROM ken_sentiment WHERE captured_at > NOW() - INTERVAL '24 hours'
+ GROUP BY source ORDER BY cnt DESC LIMIT 15`);
+ out.sourceMix = rows.map(r => ({
+ source: r.source, count: parseInt(r.cnt),
+ avgSentiment: parseFloat(parseFloat(r.avg_sent || 0).toFixed(3)),
+ }));
+ } catch { out.sourceMix = []; }
+
+ // 4. Top tickers / categories from sentiment
+ try {
+ const { rows } = await kenQ(`SELECT
+ COALESCE(relevance_ticker, 'general') AS category, COUNT(*) AS cnt
+ FROM ken_sentiment WHERE captured_at > NOW() - INTERVAL '24 hours'
+ AND relevance_ticker IS NOT NULL AND relevance_ticker != ''
+ GROUP BY relevance_ticker ORDER BY cnt DESC LIMIT 12`);
+ out.categories = rows.map(r => ({ category: r.category, count: parseInt(r.cnt) }));
+ } catch { out.categories = []; }
+
+ // 5. Portfolio P&L (current state) — compute actual PnL from invested vs returned
+ try {
+ const { rows } = await kenQ(`SELECT p.id, p.name, p.strategy, p.trades_won, p.trades_lost, p.trades_expired,
+ p.total_invested_cents, p.total_returned_cents, p.daily_budget_cents, p.streak,
+ p.best_trade_cents, p.worst_trade_cents, p.last_trade_at,
+ (p.total_returned_cents - p.total_invested_cents) AS pnl_cents,
+ CASE WHEN (p.trades_won + p.trades_lost) > 0
+ THEN ROUND(p.trades_won * 100.0 / (p.trades_won + p.trades_lost))
+ ELSE 0 END AS win_rate,
+ (SELECT COUNT(*) FROM ken_portfolio_trades t WHERE t.portfolio_id = p.id) AS total_trades
+ FROM ken_portfolios p ORDER BY (p.total_returned_cents - p.total_invested_cents) DESC`);
+ out.portfolios = rows.map(r => ({
+ ...r,
+ pnl_cents: parseInt(r.pnl_cents) || 0,
+ win_rate: parseInt(r.win_rate) || 0,
+ total_trades: parseInt(r.total_trades) || 0,
+ total_invested_cents: parseInt(r.total_invested_cents) || 0,
+ total_returned_cents: parseInt(r.total_returned_cents) || 0,
+ }));
+ } catch { out.portfolios = []; }
+
+ // 6. Active markets count and top movers
+ out.activeMarkets = cachedActiveMarkets.length;
+ out.momentumKeys = Object.keys(cachedMomentumMap).length;
+
+ // 7. Signal approval rate over last 6 hours vs prior 6
+ try {
+ const { rows } = await kenQ(`SELECT
+ COUNT(*) FILTER (WHERE created_at > NOW() - INTERVAL '6 hours') AS recent_total,
+ COUNT(*) FILTER (WHERE created_at > NOW() - INTERVAL '6 hours' AND risk_approved) AS recent_approved,
+ COUNT(*) FILTER (WHERE created_at BETWEEN NOW() - INTERVAL '12 hours' AND NOW() - INTERVAL '6 hours') AS prior_total,
+ COUNT(*) FILTER (WHERE created_at BETWEEN NOW() - INTERVAL '12 hours' AND NOW() - INTERVAL '6 hours' AND risk_approved) AS prior_approved
+ FROM ken_strategy_signals WHERE created_at > NOW() - INTERVAL '12 hours'`);
+ const r = rows[0] || {};
+ const recentRate = r.recent_total > 0 ? (r.recent_approved / r.recent_total * 100) : 0;
+ const priorRate = r.prior_total > 0 ? (r.prior_approved / r.prior_total * 100) : 0;
+ out.approvalTrend = {
+ current: Math.round(recentRate), prior: Math.round(priorRate),
+ change: Math.round(recentRate - priorRate),
+ recentSignals: parseInt(r.recent_total), priorSignals: parseInt(r.prior_total),
+ };
+ } catch { out.approvalTrend = { current: 0, prior: 0, change: 0 }; }
+
+ // 8. Gemini usage
+ out.gemini = { callsToday: geminiCallCount, dailyLimit: GEMINI_DAILY_LIMIT, pctUsed: Math.round(geminiCallCount / GEMINI_DAILY_LIMIT * 100) };
+
+ // 9. Latest signals feed — most recent 15 signals for live ticker
+ try {
+ const { rows } = await kenQ(`SELECT market_id, direction, expected_edge, confidence, risk_approved, created_at,
+ SUBSTRING(reasoning FROM 1 FOR 80) AS reason_short
+ FROM ken_strategy_signals ORDER BY created_at DESC LIMIT 15`);
+ out.latestSignals = rows.map(r => ({
+ market: r.market_id, direction: r.direction,
+ edge: parseFloat(parseFloat(r.expected_edge || 0).toFixed(4)),
+ confidence: parseFloat(parseFloat(r.confidence || 0).toFixed(3)),
+ approved: r.risk_approved, reason: r.reason_short,
+ time: r.created_at,
+ }));
+ } catch { out.latestSignals = []; }
+
+ // 10. Per-market signal stats — heatmap data
+ try {
+ const { rows } = await kenQ(`SELECT market_id,
+ COUNT(*) AS total_signals,
+ AVG(expected_edge::numeric) AS avg_edge,
+ AVG(confidence::numeric) AS avg_conf,
+ COUNT(*) FILTER (WHERE risk_approved) AS approved,
+ MAX(created_at) AS last_signal
+ FROM ken_strategy_signals WHERE created_at > NOW() - INTERVAL '24 hours'
+ GROUP BY market_id ORDER BY total_signals DESC LIMIT 20`);
+ out.marketStats = rows.map(r => ({
+ market: r.market_id, signals: parseInt(r.total_signals),
+ avgEdge: parseFloat(parseFloat(r.avg_edge || 0).toFixed(4)),
+ avgConf: parseFloat(parseFloat(r.avg_conf || 0).toFixed(3)),
+ approved: parseInt(r.approved), lastSignal: r.last_signal,
+ }));
+ } catch { out.marketStats = []; }
+
+ // 11. Recent trades with details
+ try {
+ const { rows } = await kenQ(`SELECT t.id, t.portfolio_id, t.market_id, t.market_title, t.direction, t.contracts,
+ t.entry_price_cents, t.pnl_cents, t.status, t.cost_cents, t.confidence, t.created_at,
+ p.name AS portfolio_name, p.strategy
+ FROM ken_portfolio_trades t
+ JOIN ken_portfolios p ON p.id = t.portfolio_id
+ ORDER BY t.created_at DESC LIMIT 20`);
+ out.recentTrades = rows.map(r => ({
+ ...r, entry_price_cents: parseInt(r.entry_price_cents) || 0, pnl_cents: parseInt(r.pnl_cents) || 0,
+ contracts: parseInt(r.contracts) || 0, cost_cents: parseInt(r.cost_cents) || 0,
+ }));
+ } catch { out.recentTrades = []; }
+
+ // 12. Confidence distribution histogram (10 buckets from 0-1)
+ try {
+ const { rows } = await kenQ(`SELECT
+ WIDTH_BUCKET(confidence::numeric, 0, 1, 10) AS bucket,
+ COUNT(*) AS cnt
+ FROM ken_strategy_signals WHERE created_at > NOW() - INTERVAL '24 hours'
+ GROUP BY bucket ORDER BY bucket`);
+ out.confDistribution = Array.from({length: 10}, (_, i) => {
+ const found = rows.find(r => parseInt(r.bucket) === i + 1);
+ return { range: (i * 10) + '-' + ((i + 1) * 10) + '%', count: found ? parseInt(found.cnt) : 0 };
+ });
+ } catch { out.confDistribution = []; }
+
+ json(res, out);
+ },
+};
+
+// ════════════════════════════════════════
+// TOURNAMENT ARENA — 3D TEAM COMPETITION
+// ════════════════════════════════════════
+const ARENA_HTML = `<!DOCTYPE html>
+<html lang="en">
+<head>
+<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
+<title>Tournament Arena | Ken Trading</title>
+<style>
+*{margin:0;padding:0;box-sizing:border-box}
+body{background:#000;overflow:hidden;font-family:'Segoe UI',system-ui,sans-serif;color:#fff}
+#c{position:fixed;top:0;left:0;z-index:0}
+#hud{position:fixed;top:0;left:0;right:0;z-index:10;pointer-events:none}
+.top-bar{display:flex;justify-content:center;align-items:center;padding:20px 40px;gap:30px}
+.team-badge{display:flex;align-items:center;gap:12px;padding:10px 24px;border-radius:12px;pointer-events:auto;cursor:default}
+.team-badge.alpha{background:rgba(99,102,241,.15);border:1px solid rgba(99,102,241,.4)}
+.team-badge.beta{background:rgba(244,63,94,.15);border:1px solid rgba(244,63,94,.4)}
+.team-badge h2{font-size:16px;letter-spacing:2px;text-transform:uppercase}
+.team-badge.alpha h2{color:#818cf8}
+.team-badge.beta h2{color:#fb7185}
+.vs{font-size:32px;font-weight:900;background:linear-gradient(135deg,#818cf8,#fb7185);-webkit-background-clip:text;-webkit-text-fill-color:transparent;text-shadow:none;filter:drop-shadow(0 0 20px rgba(168,85,247,.5))}
+.scoreboard{position:fixed;bottom:20px;left:50%;transform:translateX(-50%);z-index:10;display:flex;gap:8px;background:rgba(0,0,0,.7);backdrop-filter:blur(10px);border:1px solid rgba(255,255,255,.08);border-radius:16px;padding:12px 20px}
+.score-card{text-align:center;padding:6px 16px;border-radius:10px;min-width:100px}
+.score-card.alpha{background:rgba(99,102,241,.1);border:1px solid rgba(99,102,241,.2)}
+.score-card.beta{background:rgba(244,63,94,.1);border:1px solid rgba(244,63,94,.2)}
+.score-card .name{font-size:11px;font-weight:700;letter-spacing:1px;text-transform:uppercase;margin-bottom:4px}
+.score-card.alpha .name{color:#818cf8}
+.score-card.beta .name{color:#fb7185}
+.score-card .strat{font-size:9px;color:#666;margin-bottom:6px}
+.score-card .pnl{font-size:18px;font-weight:800;font-family:'Courier New',monospace}
+.score-card .pnl.pos{color:#4ade80}
+.score-card .pnl.neg{color:#f87171}
+.score-card .pnl.zero{color:#666}
+.score-card .trades{font-size:9px;color:#888;margin-top:2px}
+.score-card .bar{height:3px;border-radius:2px;margin-top:6px;background:#1a1a2e;overflow:hidden}
+.score-card .bar-fill{height:100%;border-radius:2px;transition:width .5s ease}
+.week-info{position:fixed;top:80px;left:50%;transform:translateX(-50%);z-index:10;font-size:11px;color:#555;letter-spacing:2px;text-transform:uppercase}
+.team-total{font-size:11px;font-weight:700;margin-top:4px;letter-spacing:1px}
+.back-link{position:fixed;top:20px;left:20px;z-index:20;color:#666;text-decoration:none;font-size:12px;pointer-events:auto}
+.back-link:hover{color:#fff}
+.refresh-note{position:fixed;bottom:4px;left:50%;transform:translateX(-50%);z-index:10;font-size:9px;color:#333}
+</style>
+</head>
+<body>
+<canvas id="c"></canvas>
+<a href="/inc" class="back-link">← Command Center</a>
+<div id="hud">
+ <div class="top-bar">
+ <div class="team-badge alpha"><div style="width:12px;height:12px;border-radius:50%;background:#818cf8;box-shadow:0 0 12px #818cf8"></div><h2>Team Alpha</h2></div>
+ <div class="vs">VS</div>
+ <div class="team-badge beta"><div style="width:12px;height:12px;border-radius:50%;background:#fb7185;box-shadow:0 0 12px #fb7185"></div><h2>Team Beta</h2></div>
+ </div>
+</div>
+<div id="week-info" class="week-info">Loading tournament...</div>
+<div id="scoreboard" class="scoreboard"></div>
+<div class="refresh-note">Auto-refreshes every 15s</div>
+
+<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"><\/script>
+<script>
+const scene = new THREE.Scene();
+const camera = new THREE.PerspectiveCamera(60, innerWidth/innerHeight, 0.1, 1000);
+const renderer = new THREE.WebGLRenderer({ canvas: document.getElementById('c'), antialias: true, alpha: true });
+renderer.setSize(innerWidth, innerHeight);
+renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
+camera.position.set(0, 4, 12);
+camera.lookAt(0, 0, 0);
+
+// Lighting
+scene.add(new THREE.AmbientLight(0x222244, 0.5));
+const spotA = new THREE.SpotLight(0x6366f1, 2, 30, Math.PI/4);
+spotA.position.set(-6, 10, 5);
+scene.add(spotA);
+const spotB = new THREE.SpotLight(0xf43f5e, 2, 30, Math.PI/4);
+spotB.position.set(6, 10, 5);
+scene.add(spotB);
+const rimLight = new THREE.PointLight(0xa855f7, 1, 20);
+rimLight.position.set(0, 8, -5);
+scene.add(rimLight);
+
+// Arena floor
+const floorGeo = new THREE.CircleGeometry(8, 64);
+const floorMat = new THREE.MeshStandardMaterial({ color: 0x0a0a1a, metalness: 0.8, roughness: 0.3 });
+const floor = new THREE.Mesh(floorGeo, floorMat);
+floor.rotation.x = -Math.PI / 2;
+floor.position.y = -0.5;
+scene.add(floor);
+
+// Arena ring
+const ringGeo = new THREE.TorusGeometry(8, 0.05, 8, 128);
+const ringMat = new THREE.MeshStandardMaterial({ color: 0xa855f7, emissive: 0xa855f7, emissiveIntensity: 0.5 });
+const ring = new THREE.Mesh(ringGeo, ringMat);
+ring.rotation.x = -Math.PI / 2;
+ring.position.y = -0.48;
+scene.add(ring);
+
+// Center divider line
+const divGeo = new THREE.PlaneGeometry(0.02, 14);
+const divMat = new THREE.MeshBasicMaterial({ color: 0x333355, transparent: true, opacity: 0.3 });
+const divider = new THREE.Mesh(divGeo, divMat);
+divider.rotation.x = -Math.PI / 2;
+divider.position.y = -0.47;
+scene.add(divider);
+
+// Particle system for arena atmosphere
+const pCount = 500;
+const pGeo = new THREE.BufferGeometry();
+const pPos = new Float32Array(pCount * 3);
+const pCol = new Float32Array(pCount * 3);
+for (let i = 0; i < pCount; i++) {
+ const r = Math.random() * 10;
+ const a = Math.random() * Math.PI * 2;
+ pPos[i*3] = Math.cos(a) * r;
+ pPos[i*3+1] = Math.random() * 8 - 0.5;
+ pPos[i*3+2] = Math.sin(a) * r;
+ const isAlpha = pPos[i*3] < 0;
+ pCol[i*3] = isAlpha ? 0.38 : 0.96;
+ pCol[i*3+1] = isAlpha ? 0.39 : 0.24;
+ pCol[i*3+2] = isAlpha ? 0.95 : 0.37;
+}
+pGeo.setAttribute('position', new THREE.BufferAttribute(pPos, 3));
+pGeo.setAttribute('color', new THREE.BufferAttribute(pCol, 3));
+const pMat = new THREE.PointsMaterial({ size: 0.04, vertexColors: true, transparent: true, opacity: 0.4, blending: THREE.AdditiveBlending });
+const particles = new THREE.Points(pGeo, pMat);
+scene.add(particles);
+
+// Team node storage
+const teamNodes = [];
+const ALPHA_COLOR = 0x6366f1;
+const BETA_COLOR = 0xf43f5e;
+const TEAM_POSITIONS = {
+ alpha: [[-3.5, 1, -1.5], [-2, 1, 2], [-4.5, 1, 1]],
+ beta: [[3.5, 1, -1.5], [2, 1, 2], [4.5, 1, 1]]
+};
+
+function createTeamNode(pos, color, name, strategy) {
+ const group = new THREE.Group();
+ // Main sphere
+ const geo = new THREE.IcosahedronGeometry(0.6, 2);
+ const mat = new THREE.MeshStandardMaterial({ color, emissive: color, emissiveIntensity: 0.3, metalness: 0.7, roughness: 0.2, wireframe: false });
+ const sphere = new THREE.Mesh(geo, mat);
+ group.add(sphere);
+ // Glow ring
+ const glowGeo = new THREE.TorusGeometry(0.9, 0.03, 8, 64);
+ const glowMat = new THREE.MeshBasicMaterial({ color, transparent: true, opacity: 0.5 });
+ const glowRing = new THREE.Mesh(glowGeo, glowMat);
+ glowRing.rotation.x = Math.PI / 2;
+ group.add(glowRing);
+ // Outer shell wireframe
+ const shellGeo = new THREE.IcosahedronGeometry(0.75, 1);
+ const shellMat = new THREE.MeshBasicMaterial({ color, wireframe: true, transparent: true, opacity: 0.15 });
+ const shell = new THREE.Mesh(shellGeo, shellMat);
+ group.add(shell);
+ // Name label (canvas texture)
+ const canvas = document.createElement('canvas');
+ canvas.width = 256; canvas.height = 80;
+ const ctx = canvas.getContext('2d');
+ ctx.fillStyle = '#fff';
+ ctx.font = 'bold 28px Segoe UI';
+ ctx.textAlign = 'center';
+ ctx.fillText(name, 128, 30);
+ ctx.font = '16px Segoe UI';
+ ctx.fillStyle = '#888';
+ ctx.fillText(strategy, 128, 58);
+ const tex = new THREE.CanvasTexture(canvas);
+ const labelGeo = new THREE.PlaneGeometry(2, 0.6);
+ const labelMat = new THREE.MeshBasicMaterial({ map: tex, transparent: true, depthTest: false });
+ const label = new THREE.Mesh(labelGeo, labelMat);
+ label.position.y = 1.5;
+ group.add(label);
+ // P&L indicator bar (will be updated)
+ const barBgGeo = new THREE.PlaneGeometry(1.2, 0.08);
+ const barBgMat = new THREE.MeshBasicMaterial({ color: 0x1a1a2e, transparent: true, opacity: 0.8 });
+ const barBg = new THREE.Mesh(barBgGeo, barBgMat);
+ barBg.position.y = 1.1;
+ group.add(barBg);
+ const barGeo = new THREE.PlaneGeometry(0.01, 0.06);
+ const barMat = new THREE.MeshBasicMaterial({ color: 0x4ade80, transparent: true, opacity: 0.9 });
+ const bar = new THREE.Mesh(barGeo, barMat);
+ bar.position.y = 1.1;
+ bar.position.x = -0.58;
+ group.add(bar);
+ group.position.set(...pos);
+ scene.add(group);
+ return { group, sphere, shell, glowRing, bar, barMat, mat, name, pnl: 0, trades: 0 };
+}
+
+// Energy beams connecting team members
+function createTeamBeam(nodeA, nodeB, color) {
+ const geo = new THREE.BufferGeometry();
+ const positions = new Float32Array(6);
+ geo.setAttribute('position', new THREE.BufferAttribute(positions, 3));
+ const mat = new THREE.LineBasicMaterial({ color, transparent: true, opacity: 0.15, blending: THREE.AdditiveBlending });
+ const line = new THREE.Line(geo, mat);
+ scene.add(line);
+ return { line, nodeA, nodeB, geo };
+}
+const beams = [];
+
+// Data fetching
+let tournamentData = null;
+async function fetchData() {
+ try {
+ const r = await fetch('/api/tournament/current');
+ const d = await r.json();
+ if (!d.active) return;
+ tournamentData = d;
+ updateScene(d);
+ updateHUD(d);
+ } catch(e) { console.error('Fetch error:', e); }
+}
+
+function updateScene(d) {
+ const entries = d.entries || [];
+ // First 3 = alpha, next 3 = beta (sorted by entry id)
+ const sorted = [...entries].sort((a,b) => a.id - b.id);
+ const alphaEntries = sorted.slice(0, 3);
+ const betaEntries = sorted.slice(3, 6);
+ // Create nodes if not yet created
+ if (teamNodes.length === 0) {
+ alphaEntries.forEach((e, i) => {
+ const n = createTeamNode(TEAM_POSITIONS.alpha[i], ALPHA_COLOR, e.name, e.strategy);
+ n.entry = e;
+ n.team = 'alpha';
+ teamNodes.push(n);
+ });
+ betaEntries.forEach((e, i) => {
+ const n = createTeamNode(TEAM_POSITIONS.beta[i], BETA_COLOR, e.name, e.strategy);
+ n.entry = e;
+ n.team = 'beta';
+ teamNodes.push(n);
+ });
+ // Create beams within each team
+ for (let i = 0; i < 3; i++) for (let j = i+1; j < 3; j++) {
+ beams.push(createTeamBeam(teamNodes[i], teamNodes[j], ALPHA_COLOR));
+ }
+ for (let i = 3; i < 6; i++) for (let j = i+1; j < 6; j++) {
+ beams.push(createTeamBeam(teamNodes[i], teamNodes[j], BETA_COLOR));
+ }
+ }
+ // Update node data
+ const allEntries = [...alphaEntries, ...betaEntries];
+ allEntries.forEach((e, i) => {
+ if (!teamNodes[i]) return;
+ const n = teamNodes[i];
+ n.pnl = e.live_pnl || 0;
+ n.trades = e.live_trades || 0;
+ n.entry = e;
+ // Update emissive based on P&L
+ const intensity = Math.min(0.8, 0.3 + Math.abs(n.pnl) / 500);
+ n.mat.emissiveIntensity = intensity;
+ // Update P&L bar
+ const pnlPct = Math.max(0.01, Math.min(1, (n.pnl + 2000) / 4000));
+ n.bar.scale.x = pnlPct * 116;
+ n.bar.position.x = -0.58 + (pnlPct * 1.16) / 2;
+ n.barMat.color.setHex(n.pnl >= 0 ? 0x4ade80 : 0xf87171);
+ });
+}
+
+function updateHUD(d) {
+ const entries = d.entries || [];
+ const sorted = [...entries].sort((a,b) => a.id - b.id);
+ const t = d.tournament;
+ const wStart = new Date(t.week_start).toLocaleDateString('en-US', {month:'short',day:'numeric'});
+ const wEnd = new Date(t.week_end).toLocaleDateString('en-US', {month:'short',day:'numeric'});
+ document.getElementById('week-info').textContent = 'Week ' + t.id + ' • ' + wStart + ' - ' + wEnd + ' • $' + (t.budget_per_portfolio_cents/100).toFixed(0) + ' per portfolio';
+ let html = '';
+ let alphaTotal = 0, betaTotal = 0;
+ sorted.forEach((e, i) => {
+ const isAlpha = i < 3;
+ const pnl = e.live_pnl || 0;
+ if (isAlpha) alphaTotal += pnl; else betaTotal += pnl;
+ const pnlClass = pnl > 0 ? 'pos' : pnl < 0 ? 'neg' : 'zero';
+ const pnlStr = (pnl >= 0 ? '+' : '') + '$' + (pnl/100).toFixed(2);
+ const budgetUsed = Math.min(100, (e.live_invested || 0) / e.start_balance_cents * 100);
+ const barColor = isAlpha ? '#818cf8' : '#fb7185';
+ html += '<div class="score-card ' + (isAlpha?'alpha':'beta') + '">';
+ html += '<div class="name">' + e.name + '</div>';
+ html += '<div class="strat">' + e.strategy + '</div>';
+ html += '<div class="pnl ' + pnlClass + '">' + pnlStr + '</div>';
+ html += '<div class="trades">' + (e.live_trades||0) + ' trades • $' + ((e.live_invested||0)/100).toFixed(2) + ' deployed</div>';
+ html += '<div class="bar"><div class="bar-fill" style="width:' + budgetUsed + '%;background:' + barColor + '"></div></div>';
+ html += '</div>';
+ if (i === 2) {
+ html += '<div style="display:flex;flex-direction:column;justify-content:center;align-items:center;padding:0 8px">';
+ html += '<div style="font-size:20px;font-weight:900;background:linear-gradient(135deg,#818cf8,#fb7185);-webkit-background-clip:text;-webkit-text-fill-color:transparent">VS</div>';
+ html += '</div>';
+ }
+ });
+ document.getElementById('scoreboard').innerHTML = html;
+}
+
+// Animation
+let time = 0;
+function animate() {
+ requestAnimationFrame(animate);
+ time += 0.01;
+ // Rotate camera slowly
+ camera.position.x = Math.sin(time * 0.15) * 12;
+ camera.position.z = Math.cos(time * 0.15) * 12;
+ camera.position.y = 4 + Math.sin(time * 0.3) * 0.5;
+ camera.lookAt(0, 0.5, 0);
+ // Animate nodes
+ teamNodes.forEach((n, i) => {
+ const base = n.group.position.y;
+ n.sphere.position.y = Math.sin(time * 2 + i) * 0.15;
+ n.sphere.rotation.y = time + i;
+ n.shell.rotation.y = -time * 0.5 + i;
+ n.shell.rotation.x = time * 0.3;
+ n.glowRing.rotation.z = time * (i % 2 === 0 ? 1 : -1);
+ // Pulse based on trades
+ const pulse = 1 + Math.sin(time * 3 + i * 2) * 0.05 * (n.trades > 0 ? 1 : 0.2);
+ n.sphere.scale.setScalar(pulse);
+ });
+ // Update beams
+ beams.forEach(b => {
+ const pa = b.nodeA.group.position;
+ const pb = b.nodeB.group.position;
+ const pos = b.geo.attributes.position.array;
+ pos[0] = pa.x; pos[1] = pa.y + 1; pos[2] = pa.z;
+ pos[3] = pb.x; pos[4] = pb.y + 1; pos[5] = pb.z;
+ b.geo.attributes.position.needsUpdate = true;
+ b.line.material.opacity = 0.1 + Math.sin(time * 2) * 0.05;
+ });
+ // Animate particles
+ const pp = particles.geometry.attributes.position.array;
+ for (let i = 0; i < pCount; i++) {
+ pp[i*3+1] += Math.sin(time + i) * 0.002;
+ if (pp[i*3+1] > 8) pp[i*3+1] = -0.5;
+ }
+ particles.geometry.attributes.position.needsUpdate = true;
+ particles.rotation.y = time * 0.02;
+ // Ring pulse
+ ring.material.emissiveIntensity = 0.3 + Math.sin(time * 2) * 0.2;
+ renderer.render(scene, camera);
+}
+
+// Resize
+addEventListener('resize', () => {
+ camera.aspect = innerWidth / innerHeight;
+ camera.updateProjectionMatrix();
+ renderer.setSize(innerWidth, innerHeight);
+});
+
+// Init
+fetchData();
+setInterval(fetchData, 15000);
+animate();
+<\/script>
+</body>
+</html>`;
+
+// KEN INC COMMAND CENTER PAGE
+// ════════════════════════════════════════
+const KEN_INC_HTML = `<!DOCTYPE html>
+<html lang="en">
+<head>
+<meta charset="UTF-8">
+<meta name="viewport" content="width=device-width, initial-scale=1.0">
+<title>Ken Inc. | Trading Intelligence Command Center</title>
+<script src="https://unpkg.com/react@18/umd/react.production.min.js" crossorigin></script>
+<script src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js" crossorigin></script>
+<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
+<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.4/dist/chart.umd.min.js"></script>
+<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns@3.0.0/dist/chartjs-adapter-date-fns.bundle.min.js"></script>
+<style>
+*{margin:0;padding:0;box-sizing:border-box}
+:root{--bg:#050510;--card:rgba(15,15,35,0.85);--border:rgba(255,255,255,0.06);--text:#e2e8f0;--muted:#64748b;--pink:#ff69b4;--blue:#3b82f6;--purple:#8b5cf6;--green:#22c55e;--red:#ef4444;--yellow:#f59e0b;--cyan:#06b6d4;--teal:#14b8a6}
+body{font-family:'SF Pro Display',-apple-system,BlinkMacSystemFont,sans-serif;background:var(--bg);color:var(--text);min-height:100vh;overflow-x:hidden}
+
+/* Animated gradient background */
+body::before{content:'';position:fixed;top:0;left:0;right:0;bottom:0;background:radial-gradient(ellipse at 20% 50%,rgba(139,92,246,0.08) 0%,transparent 50%),radial-gradient(ellipse at 80% 20%,rgba(255,105,180,0.06) 0%,transparent 50%),radial-gradient(ellipse at 50% 80%,rgba(59,130,246,0.06) 0%,transparent 50%);z-index:-1;animation:bgPulse 8s ease-in-out infinite alternate}
+@keyframes bgPulse{0%{opacity:0.6}100%{opacity:1}}
+
+/* Grid lines overlay */
+body::after{content:'';position:fixed;top:0;left:0;right:0;bottom:0;background-image:linear-gradient(rgba(255,255,255,0.015) 1px,transparent 1px),linear-gradient(90deg,rgba(255,255,255,0.015) 1px,transparent 1px);background-size:60px 60px;z-index:-1;animation:gridScroll 20s linear infinite}
+@keyframes gridScroll{to{background-position:60px 60px}}
+
+.container{max-width:1400px;margin:0 auto;padding:20px}
+
+/* Header */
+.header{text-align:center;padding:30px 20px;position:relative}
+.header-glow{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);width:400px;height:400px;background:radial-gradient(circle,rgba(255,105,180,0.15) 0%,transparent 70%);border-radius:50%;filter:blur(60px);animation:glowPulse 4s ease-in-out infinite alternate;pointer-events:none}
+@keyframes glowPulse{0%{opacity:0.5;transform:translate(-50%,-50%) scale(0.9)}100%{opacity:1;transform:translate(-50%,-50%) scale(1.1)}}
+.ceo-avatar{width:80px;height:80px;border-radius:50%;background:linear-gradient(135deg,#ff69b4,#8b5cf6);display:flex;align-items:center;justify-content:center;font-size:36px;margin:0 auto 12px;box-shadow:0 0 30px rgba(255,105,180,0.4),0 0 60px rgba(139,92,246,0.2);animation:avatarFloat 3s ease-in-out infinite;position:relative;z-index:2}
+@keyframes avatarFloat{0%,100%{transform:translateY(0)}50%{transform:translateY(-8px)}}
+.ceo-name{font-size:32px;font-weight:800;background:linear-gradient(135deg,#ff69b4,#c084fc,#818cf8);-webkit-background-clip:text;-webkit-text-fill-color:transparent;position:relative;z-index:2}
+.ceo-title{color:var(--muted);font-size:14px;letter-spacing:2px;text-transform:uppercase;margin-top:4px;position:relative;z-index:2}
+.ceo-tagline{color:rgba(255,105,180,0.6);font-size:11px;letter-spacing:4px;text-transform:uppercase;margin-top:8px;position:relative;z-index:2}
+
+/* Stats bar */
+.stats-bar{display:flex;justify-content:center;gap:30px;margin:24px 0;flex-wrap:wrap}
+.stat-item{text-align:center;padding:12px 24px;background:var(--card);border:1px solid var(--border);border-radius:12px;backdrop-filter:blur(10px);min-width:120px}
+.stat-val{font-size:24px;font-weight:700;font-variant-numeric:tabular-nums}
+.stat-label{font-size:10px;color:var(--muted);text-transform:uppercase;letter-spacing:1px;margin-top:2px}
+
+/* Agent Network */
+.network{position:relative;margin:30px auto;max-width:1200px}
+.agents-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:16px}
+@media(max-width:1024px){.agents-grid{grid-template-columns:repeat(2,1fr)}}
+@media(max-width:600px){.agents-grid{grid-template-columns:1fr}}
+
+/* Agent Card */
+.agent-card{background:var(--card);border:1px solid var(--border);border-radius:16px;padding:20px;backdrop-filter:blur(10px);transition:all 0.3s cubic-bezier(0.4,0,0.2,1);position:relative;overflow:hidden;cursor:pointer}
+.agent-card::before{content:'';position:absolute;top:0;left:0;right:0;height:3px;border-radius:16px 16px 0 0;opacity:0;transition:opacity 0.3s}
+.agent-card:hover{transform:translateY(-4px);border-color:rgba(255,255,255,0.12);box-shadow:0 20px 40px rgba(0,0,0,0.3)}
+.agent-card:hover::before{opacity:1}
+.agent-card.expanded{grid-column:span 2}
+.agent-header{display:flex;align-items:center;gap:12px}
+.agent-emoji{font-size:28px;width:48px;height:48px;display:flex;align-items:center;justify-content:center;border-radius:12px;flex-shrink:0}
+.agent-name{font-size:16px;font-weight:700}
+.agent-role{font-size:11px;color:var(--muted);text-transform:uppercase;letter-spacing:0.5px}
+.status-indicator{width:8px;height:8px;border-radius:50%;position:absolute;top:16px;right:16px;animation:statusPulse 2s ease-in-out infinite}
+@keyframes statusPulse{0%,100%{opacity:1;box-shadow:0 0 4px currentColor}50%{opacity:0.6;box-shadow:0 0 12px currentColor}}
+.agent-desc{font-size:12px;color:var(--muted);line-height:1.5;margin-top:10px}
+.agent-stats{display:flex;flex-wrap:wrap;gap:6px;margin-top:12px}
+.agent-stat{padding:3px 10px;background:rgba(255,255,255,0.04);border:1px solid var(--border);border-radius:6px;font-size:11px;font-variant-numeric:tabular-nums}
+.agent-stat strong{color:var(--text);margin-right:3px}
+.skills-wrap{margin-top:12px;display:flex;flex-wrap:wrap;gap:4px}
+.skill-tag{padding:2px 8px;border-radius:4px;font-size:10px;font-weight:600;letter-spacing:0.3px}
+
+/* Signal Feed */
+.signal-feed{margin-top:30px}
+.signal-feed h2{font-size:16px;font-weight:600;margin-bottom:12px;display:flex;align-items:center;gap:8px}
+.signal-feed h2 .live-dot{width:8px;height:8px;border-radius:50%;background:var(--red);animation:livePulse 1s ease-in-out infinite}
+@keyframes livePulse{0%,100%{opacity:1;transform:scale(1)}50%{opacity:0.5;transform:scale(0.8)}}
+.signal-list{display:flex;flex-direction:column;gap:6px}
+.signal-item{display:flex;align-items:center;gap:12px;padding:10px 16px;background:var(--card);border:1px solid var(--border);border-radius:10px;font-size:12px;backdrop-filter:blur(10px);transition:border-color 0.2s}
+.signal-item:hover{border-color:rgba(255,255,255,0.12)}
+.signal-dir{padding:3px 8px;border-radius:4px;font-weight:700;font-size:11px;min-width:60px;text-align:center}
+.signal-dir.buy-yes{background:rgba(34,197,94,0.15);color:var(--green)}
+.signal-dir.buy-no{background:rgba(239,68,68,0.15);color:var(--red)}
+.signal-market{flex:1;font-weight:500;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
+.signal-edge{font-weight:700;font-variant-numeric:tabular-nums;min-width:50px;text-align:right}
+.signal-conf{color:var(--muted);font-variant-numeric:tabular-nums;min-width:40px;text-align:right}
+.signal-time{color:var(--muted);font-size:11px;min-width:65px;text-align:right}
+.signal-approved{width:18px;height:18px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:10px;flex-shrink:0}
+
+/* Connection Lines Animation */
+.connections-svg{position:absolute;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:0}
+.data-flow{stroke-dasharray:8 4;animation:flowDash 1s linear infinite}
+@keyframes flowDash{to{stroke-dashoffset:-12}}
+
+/* Particle effect */
+.particles{position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:0}
+.particle{position:absolute;width:2px;height:2px;border-radius:50%;opacity:0;animation:particleFloat linear infinite}
+@keyframes particleFloat{0%{opacity:0;transform:translateY(0)}10%{opacity:0.6}90%{opacity:0.6}100%{opacity:0;transform:translateY(-100vh)}}
+
+/* Clock */
+.clock{position:fixed;top:16px;right:20px;text-align:right;z-index:10}
+.clock-time{font-size:14px;font-weight:600;font-variant-numeric:tabular-nums;color:var(--text)}
+.clock-date{font-size:11px;color:var(--muted)}
+
+/* Sparkline */
+.sparkline-wrap{display:inline-block;vertical-align:middle}
+.sparkline-svg{display:block}
+
+/* ─── Market Data Terminal ─── */
+.mkt-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(340px,1fr));gap:14px;margin-top:16px}
+.mkt-card{background:var(--card);border:1px solid var(--border);border-radius:14px;padding:18px 20px;backdrop-filter:blur(10px);transition:all .3s;position:relative;overflow:hidden}
+.mkt-card::after{content:'';position:absolute;top:0;left:0;right:0;height:2px;background:linear-gradient(90deg,transparent,var(--border),transparent);opacity:0;transition:opacity .3s}
+.mkt-card:hover{border-color:rgba(255,255,255,.12);transform:translateY(-2px);box-shadow:0 12px 40px rgba(0,0,0,.3)}
+.mkt-card:hover::after{opacity:1}
+.mkt-card-header{display:flex;align-items:center;justify-content:space-between;margin-bottom:12px}
+.mkt-card-title{font-size:13px;font-weight:700;text-transform:uppercase;letter-spacing:.5px}
+.mkt-card-badge{padding:3px 8px;border-radius:6px;font-size:10px;font-weight:700;font-variant-numeric:tabular-nums}
+.mkt-bar-chart{display:flex;align-items:flex-end;gap:3px;height:80px;padding-top:4px}
+.mkt-bar{flex:1;border-radius:3px 3px 0 0;min-width:4px;transition:height .5s ease;position:relative}
+.mkt-bar:hover{opacity:1!important;filter:brightness(1.3)}
+.mkt-bar-label{position:absolute;top:-16px;left:50%;transform:translateX(-50%);font-size:8px;color:var(--muted);white-space:nowrap;display:none;background:var(--card);padding:1px 4px;border-radius:3px;border:1px solid var(--border)}
+.mkt-bar:hover .mkt-bar-label{display:block}
+.mkt-source-list{display:flex;flex-direction:column;gap:5px}
+.mkt-source-row{display:flex;align-items:center;gap:8px;font-size:11px;padding:2px 0;transition:background .2s;border-radius:4px}
+.mkt-source-row:hover{background:rgba(255,255,255,.03)}
+.mkt-source-bar{height:7px;border-radius:4px;transition:width .6s cubic-bezier(.4,0,.2,1)}
+.mkt-source-name{min-width:85px;font-weight:500;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
+.mkt-source-val{font-variant-numeric:tabular-nums;color:var(--muted);min-width:45px;text-align:right;font-weight:600}
+.mkt-gauge{position:relative;width:100%;height:14px;background:rgba(255,255,255,.05);border-radius:7px;overflow:hidden;margin-top:8px}
+.mkt-gauge-fill{height:100%;border-radius:7px;transition:width .6s cubic-bezier(.4,0,.2,1)}
+.mkt-gauge-label{position:absolute;top:50%;right:8px;transform:translateY(-50%);font-size:9px;font-weight:700;color:var(--text);text-shadow:0 1px 2px rgba(0,0,0,.5)}
+/* Scrolling ticker */
+.mkt-ticker-strip{overflow:hidden;padding:12px 0;border-top:1px solid rgba(255,255,255,.06);border-bottom:1px solid rgba(255,255,255,.06);margin:16px 0;background:linear-gradient(90deg,rgba(5,5,16,.8),transparent 5%,transparent 95%,rgba(5,5,16,.8))}
+.mkt-ticker-track{display:flex;gap:24px;animation:tickerScroll 40s linear infinite;width:max-content}
+.mkt-ticker-track:hover{animation-play-state:paused}
+@keyframes tickerScroll{0%{transform:translateX(0)}100%{transform:translateX(-50%)}}
+.mkt-ticker-item{display:flex;align-items:center;gap:8px;font-size:12px;font-weight:600;white-space:nowrap;font-variant-numeric:tabular-nums;padding:4px 12px;border-radius:6px;background:rgba(255,255,255,.02);border:1px solid rgba(255,255,255,.04)}
+.mkt-change{font-size:11px;font-weight:700}
+.mkt-change.up{color:var(--green)}
+.mkt-change.down{color:var(--red)}
+.mkt-change.flat{color:var(--muted)}
+/* Signal feed */
+.signal-feed{display:flex;flex-direction:column;gap:4px;max-height:300px;overflow-y:auto}
+.signal-feed::-webkit-scrollbar{width:4px}
+.signal-feed::-webkit-scrollbar-thumb{background:var(--border);border-radius:2px}
+.signal-row{display:flex;align-items:center;gap:8px;padding:6px 10px;border-radius:8px;font-size:11px;transition:all .2s;border:1px solid transparent;animation:signalIn .3s ease}
+.signal-row:hover{background:rgba(255,255,255,.04);border-color:var(--border)}
+@keyframes signalIn{from{opacity:0;transform:translateX(-8px)}to{opacity:1;transform:none}}
+.signal-dir{padding:2px 8px;border-radius:4px;font-weight:800;font-size:10px;text-transform:uppercase;letter-spacing:.5px}
+.signal-dir.yes{background:rgba(34,197,94,.15);color:var(--green)}
+.signal-dir.no{background:rgba(239,68,68,.15);color:var(--red)}
+.signal-market{font-weight:600;min-width:160px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
+.signal-edge{font-variant-numeric:tabular-nums;font-weight:700;min-width:50px;text-align:right}
+.signal-conf{font-variant-numeric:tabular-nums;min-width:40px;text-align:right;color:var(--muted)}
+.signal-time{font-size:9px;color:var(--muted);margin-left:auto;white-space:nowrap}
+.signal-approved{width:6px;height:6px;border-radius:50%;flex-shrink:0}
+/* Heatmap grid */
+.heatmap-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(140px,1fr));gap:6px}
+.heatmap-cell{padding:8px 10px;border-radius:8px;border:1px solid var(--border);transition:all .2s;cursor:default;text-align:center}
+.heatmap-cell:hover{transform:scale(1.03);z-index:1;box-shadow:0 4px 16px rgba(0,0,0,.4)}
+.heatmap-market{font-size:10px;font-weight:700;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;margin-bottom:2px}
+.heatmap-edge{font-size:16px;font-weight:800;font-variant-numeric:tabular-nums}
+.heatmap-meta{font-size:8px;color:var(--muted);margin-top:2px}
+/* Histogram */
+.histogram{display:flex;align-items:flex-end;gap:2px;height:80px}
+.hist-bar{flex:1;border-radius:3px 3px 0 0;transition:height .5s;position:relative;min-width:0}
+.hist-bar:hover{filter:brightness(1.3)}
+.hist-label{position:absolute;bottom:-16px;left:50%;transform:translateX(-50%);font-size:7px;color:var(--muted);white-space:nowrap}
+/* Trade log */
+.trade-log{display:flex;flex-direction:column;gap:3px;max-height:260px;overflow-y:auto}
+.trade-log::-webkit-scrollbar{width:4px}
+.trade-log::-webkit-scrollbar-thumb{background:var(--border);border-radius:2px}
+.trade-row{display:flex;align-items:center;gap:6px;padding:5px 10px;border-radius:6px;font-size:10px;border:1px solid transparent;transition:all .2s}
+.trade-row:hover{background:rgba(255,255,255,.03);border-color:var(--border)}
+.trade-portfolio{font-weight:600;min-width:70px}
+.trade-pnl{font-weight:800;font-variant-numeric:tabular-nums;min-width:55px;text-align:right}
+/* P&L big number */
+.pnl-hero{font-size:48px;font-weight:900;font-variant-numeric:tabular-nums;letter-spacing:-1px;line-height:1}
+@keyframes pnlPulse{0%,100%{text-shadow:0 0 8px currentColor}50%{text-shadow:0 0 20px currentColor}}
+
+/* ─── PortFAUXlio Dashboard ─── */
+.pf-banner{text-align:center;padding:14px;margin-bottom:20px;background:linear-gradient(135deg,rgba(139,92,246,.08),rgba(255,105,180,.06));border:1px solid rgba(139,92,246,.2);border-radius:14px;position:relative;overflow:hidden}
+.pf-banner::before{content:'SIMULATED';position:absolute;top:-2px;right:20px;font-size:8px;letter-spacing:3px;color:var(--purple);background:var(--bg);padding:0 8px;border-radius:0 0 4px 4px;border:1px solid rgba(139,92,246,.2);border-top:none;font-weight:800}
+.pf-banner-title{font-size:22px;font-weight:900;background:linear-gradient(135deg,#8b5cf6,#ec4899);-webkit-background-clip:text;-webkit-text-fill-color:transparent;letter-spacing:1px}
+.pf-banner-sub{font-size:10px;color:var(--muted);letter-spacing:2px;text-transform:uppercase;margin-top:4px}
+
+.pf-summary-row{display:flex;gap:10px;margin-bottom:18px;flex-wrap:wrap}
+.pf-summary-card{flex:1;min-width:100px;background:var(--card);border:1px solid var(--border);border-radius:12px;padding:14px;text-align:center}
+.pf-summary-val{font-size:22px;font-weight:800;font-variant-numeric:tabular-nums}
+.pf-summary-lbl{font-size:9px;color:var(--muted);text-transform:uppercase;letter-spacing:1px;margin-top:2px}
+
+/* Active Trades Strip */
+.pf-active-strip{margin-bottom:20px}
+.pf-active-header{display:flex;align-items:center;gap:8px;margin-bottom:10px;font-size:12px;font-weight:700;text-transform:uppercase;letter-spacing:.5px;color:var(--green)}
+.pf-active-header .dot{width:8px;height:8px;border-radius:50%;background:var(--green);animation:statusPulse 2s ease infinite}
+.pf-active-scroll{display:flex;gap:8px;overflow-x:auto;padding-bottom:8px;scroll-behavior:smooth}
+.pf-active-scroll::-webkit-scrollbar{height:4px}
+.pf-active-scroll::-webkit-scrollbar-thumb{background:var(--border);border-radius:2px}
+.pf-active-card{flex-shrink:0;min-width:200px;max-width:260px;background:var(--card);border:1px solid var(--border);border-radius:10px;padding:10px 14px;transition:all .2s;border-top:2px solid var(--border)}
+.pf-active-card:hover{border-color:rgba(255,255,255,.15);transform:translateY(-2px);box-shadow:0 8px 24px rgba(0,0,0,.3)}
+
+/* Model Leaderboard Table */
+.pf-leaderboard{margin-bottom:20px;border:1px solid var(--border);border-radius:14px;overflow:hidden;background:var(--card);max-height:800px;overflow-y:auto}
+.pf-leaderboard::-webkit-scrollbar{width:4px}
+.pf-leaderboard::-webkit-scrollbar-thumb{background:var(--border);border-radius:2px}
+.pf-lb-header{display:grid;grid-template-columns:32px 100px 90px 80px 70px 40px 40px 55px 80px 150px;gap:0;padding:10px 14px;background:rgba(255,255,255,.03);border-bottom:1px solid var(--border);font-size:9px;font-weight:700;text-transform:uppercase;letter-spacing:.5px;color:var(--muted)}
+.pf-lb-header span[style*="cursor"]:hover{color:var(--cyan)}
+.pf-lb-row{display:grid;grid-template-columns:32px 100px 90px 80px 70px 40px 40px 55px 80px 150px;gap:0;padding:10px 14px;border-bottom:1px solid rgba(255,255,255,.03);font-size:11px;transition:all .2s;cursor:pointer;align-items:center}
+/* Chart Modal */
+.chart-modal{position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,.7);z-index:1000;display:flex;align-items:center;justify-content:center;backdrop-filter:blur(4px);animation:modalFadeIn .3s ease}
+.chart-modal-content{background:var(--card);border:1px solid var(--border);border-radius:16px;padding:24px;width:92%;max-width:900px}
+@keyframes modalFadeIn{from{opacity:0;transform:scale(.95)}to{opacity:1;transform:scale(1)}}
+.chart-modal-header{display:flex;align-items:center;gap:10px;margin-bottom:16px}
+.chart-close{margin-left:auto;background:none;border:1px solid var(--border);color:var(--muted);border-radius:8px;padding:4px 12px;cursor:pointer;font-size:12px}
+.chart-close:hover{color:var(--text);border-color:var(--muted)}
+.chart-period-btns{display:flex;gap:4px;margin-left:auto}
+.chart-period,.chart-period-active{padding:3px 10px;border-radius:6px;font-size:10px;font-weight:600;cursor:pointer;border:1px solid var(--border);background:transparent;color:var(--muted);transition:all .2s}
+.chart-period-active{border-color:var(--cyan);background:rgba(6,182,212,.1);color:var(--cyan)}
+.pf-lb-chart{display:flex;align-items:center;cursor:pointer;opacity:.85;transition:opacity .2s}
+.pf-lb-chart:hover{opacity:1}
+/* SWOT Trade Analysis */
+.swot-section{margin-bottom:20px}
+.swot-card{background:var(--card);border:1px solid var(--border);border-radius:14px;overflow:hidden;margin-bottom:12px;transition:all .2s}
+.swot-card:hover{border-color:rgba(255,255,255,.1)}
+.swot-card-header{display:flex;align-items:center;gap:10px;padding:14px 16px;cursor:pointer;border-bottom:1px solid rgba(255,255,255,.03)}
+.swot-grid{display:grid;grid-template-columns:1fr 1fr;gap:10px;padding:12px 16px}
+.swot-quadrant{padding:10px;border-radius:10px;font-size:10px}
+.swot-quadrant-s{background:rgba(34,197,94,.06);border:1px solid rgba(34,197,94,.15)}
+.swot-quadrant-w{background:rgba(239,68,68,.06);border:1px solid rgba(239,68,68,.15)}
+.swot-quadrant-o{background:rgba(59,130,246,.06);border:1px solid rgba(59,130,246,.15)}
+.swot-quadrant-t{background:rgba(245,158,11,.06);border:1px solid rgba(245,158,11,.15)}
+.swot-q-title{font-weight:800;font-size:9px;text-transform:uppercase;letter-spacing:.5px;margin-bottom:6px}
+.swot-q-item{padding:2px 0;color:var(--muted);line-height:1.4}
+.swot-q-item::before{content:'• '}
+.swot-models{display:flex;flex-wrap:wrap;gap:4px;padding:8px 16px 14px}
+.swot-model-tag{padding:2px 8px;border-radius:4px;font-size:9px;font-weight:600;background:rgba(255,255,255,.04);border:1px solid rgba(255,255,255,.06)}
+.pf-lb-row:hover{background:rgba(255,255,255,.03)}
+.pf-lb-row:last-child{border-bottom:none}
+.pf-lb-rank{font-size:14px;font-weight:900;color:var(--muted)}
+.pf-lb-name{font-weight:700;display:flex;align-items:center;gap:6px;overflow:hidden}
+.pf-lb-pnl{font-weight:800;font-variant-numeric:tabular-nums}
+.pf-lb-invested{font-variant-numeric:tabular-nums;color:var(--muted)}
+.pf-lb-wr{font-weight:700;font-variant-numeric:tabular-nums}
+.pf-lb-wl{font-variant-numeric:tabular-nums;color:var(--muted)}
+.pf-lb-roi{font-weight:800;font-variant-numeric:tabular-nums;padding:2px 8px;border-radius:4px;text-align:center}
+.pf-lb-bar{height:4px;border-radius:2px;background:rgba(255,255,255,.05);overflow:hidden;margin-top:2px}
+.pf-lb-bar-fill{height:100%;border-radius:2px;transition:width .6s ease}
+
+/* Overlap Warning */
+.pf-overlap{margin-bottom:18px;background:rgba(245,158,11,.04);border:1px solid rgba(245,158,11,.15);border-radius:12px;padding:14px}
+.pf-overlap-title{font-size:11px;font-weight:700;color:var(--yellow);text-transform:uppercase;letter-spacing:.5px;margin-bottom:8px;display:flex;align-items:center;gap:6px}
+
+/* Trade History */
+.pf-history{border:1px solid var(--border);border-radius:14px;overflow:hidden;background:var(--card)}
+.pf-history-header{padding:14px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid var(--border)}
+.pf-history-list{max-height:400px;overflow-y:auto}
+.pf-history-list::-webkit-scrollbar{width:4px}
+.pf-history-list::-webkit-scrollbar-thumb{background:var(--border);border-radius:2px}
+.pf-history-row{display:flex;align-items:center;gap:8px;padding:8px 14px;font-size:11px;border-bottom:1px solid rgba(255,255,255,.02);transition:all .15s}
+.pf-history-row:hover{background:rgba(255,255,255,.03)}
+.pf-history-row:last-child{border-bottom:none}
+
+@media(max-width:900px){
+.pf-lb-header,.pf-lb-row{grid-template-columns:28px 80px 70px 70px 50px 40px 40px 50px 70px;font-size:10px;padding:8px 10px}
+.pf-active-card{min-width:180px}
+}
+
+/* Footer */
+.footer{text-align:center;padding:30px;color:var(--muted);font-size:11px;letter-spacing:1px}
+.footer a{color:var(--pink);text-decoration:none}
+</style>
+</head>
+<body>
+<div id="root"></div>
+<script type="text/babel">
+const { useState, useEffect, useRef } = React;
+
+const AUTH = btoa('admin:DWSecure2024!');
+const api = (url) => fetch(url, { headers: { 'Authorization': 'Basic ' + AUTH } }).then(r => r.json());
+
+function Particles() {
+ const particles = Array.from({ length: 30 }, (_, i) => ({
+ id: i,
+ left: Math.random() * 100 + '%',
+ delay: Math.random() * 10 + 's',
+ duration: 8 + Math.random() * 12 + 's',
+ color: ['#ff69b4','#8b5cf6','#3b82f6','#22c55e','#f59e0b','#06b6d4'][Math.floor(Math.random()*6)],
+ size: 1 + Math.random() * 2 + 'px',
+ }));
+ return (
+ <div className="particles">
+ {particles.map(p => (
+ <div key={p.id} className="particle" style={{
+ left: p.left, bottom: 0, animationDelay: p.delay, animationDuration: p.duration,
+ background: p.color, width: p.size, height: p.size, boxShadow: '0 0 6px ' + p.color,
+ }} />
+ ))}
+ </div>
+ );
+}
+
+function Clock() {
+ const [now, setNow] = useState(new Date());
+ useEffect(() => { const iv = setInterval(() => setNow(new Date()), 1000); return () => clearInterval(iv); }, []);
+ const pt = now.toLocaleString('en-US', { timeZone: 'America/Los_Angeles', hour: 'numeric', minute: '2-digit', second: '2-digit', hour12: true });
+ const dateStr = now.toLocaleDateString('en-US', { timeZone: 'America/Los_Angeles', weekday: 'short', month: 'short', day: 'numeric' });
+ return <div className="clock"><div className="clock-time">{pt} PT</div><div className="clock-date">{dateStr}</div></div>;
+}
+
+function AgentCard({ agent, expanded, onToggle }) {
+ const bgColor = agent.color + '15';
+ return (
+ <div className={'agent-card' + (expanded ? ' expanded' : '')} onClick={onToggle}
+ style={{ '--agent-color': agent.color }}>
+ <div className="status-indicator" style={{ background: agent.status === 'active' ? 'var(--green)' : 'var(--yellow)', color: agent.status === 'active' ? 'var(--green)' : 'var(--yellow)' }} />
+ <div style={{ position: 'absolute', top: 0, left: 0, right: 0, height: 3, borderRadius: '16px 16px 0 0', background: agent.color, opacity: 0.7 }} />
+ <div className="agent-header">
+ <div className="agent-emoji" style={{ background: bgColor }}>{agent.emoji}</div>
+ <div>
+ <div className="agent-name" style={{ color: agent.color }}>{agent.name}</div>
+ <div className="agent-role">{agent.role}</div>
+ </div>
+ </div>
+ <div className="agent-desc">{agent.desc}</div>
+ <div className="agent-stats">
+ {Object.entries(agent.stats || {}).map(([k, v]) => (
+ <div key={k} className="agent-stat"><strong>{typeof v === 'number' ? v.toLocaleString() : v}</strong> {k.replace(/([A-Z])/g, ' $1').toLowerCase()}</div>
+ ))}
+ </div>
+ {expanded && (
+ <div className="skills-wrap">
+ {(agent.skills || []).map(s => (
+ <span key={s} className="skill-tag" style={{ background: agent.color + '20', color: agent.color, border: '1px solid ' + agent.color + '30' }}>{s}</span>
+ ))}
+ </div>
+ )}
+ </div>
+ );
+}
+
+function SignalFeed({ signals }) {
+ if (!signals?.length) return <div style={{ textAlign: 'center', color: 'var(--muted)', padding: 30, fontSize: 13 }}>Waiting for signals...</div>;
+
+ function timeAgo(ts) {
+ const ms = Date.now() - new Date(ts).getTime();
+ if (ms < 60000) return Math.floor(ms/1000) + 's ago';
+ if (ms < 3600000) return Math.floor(ms/60000) + 'm ago';
+ return Math.floor(ms/3600000) + 'h ago';
+ }
+
+ return (
+ <div className="signal-list">
+ {signals.slice(0, 12).map((s, i) => (
+ <div key={i} className="signal-item">
+ <div className={'signal-dir ' + (s.direction === 'BUY_YES' ? 'buy-yes' : 'buy-no')}>
+ {s.direction === 'BUY_YES' ? 'BUY YES' : 'BUY NO'}
+ </div>
+ <div className="signal-market" title={s.market}>{s.market}</div>
+ <div className="signal-edge" style={{ color: Math.abs(s.edge) > 0.1 ? 'var(--green)' : 'var(--muted)' }}>
+ {(s.edge * 100).toFixed(1)}%
+ </div>
+ <div className="signal-conf">{(s.confidence * 100).toFixed(0)}%</div>
+ <div className="signal-approved" style={{ background: s.approved ? 'rgba(34,197,94,0.15)' : 'rgba(239,68,68,0.1)', color: s.approved ? 'var(--green)' : 'var(--red)' }}>
+ {s.approved ? '✓' : '✗'}
+ </div>
+ <div className="signal-time">{timeAgo(s.time)}</div>
+ </div>
+ ))}
+ </div>
+ );
+}
+
+// ── PORTFOLIOS TAB ──
+function PortfoliosTab() {
+ const [data, setData] = useState(null);
+ const [histFilter, setHistFilter] = useState('all');
+ const [chartData, setChartData] = useState({});
+ const [selectedChart, setSelectedChart] = useState(null);
+ const [compareMode, setCompareMode] = useState(false);
+ const [compareIds, setCompareIds] = useState([]);
+ const [sortBy, setSortBy] = useState('pnl');
+ const [sortDir, setSortDir] = useState('desc');
+ useEffect(() => {
+ const load = () => api('/api/portfauxlio').then(setData).catch(e => console.error(e));
+ load();
+ const iv = setInterval(load, 15000);
+ return () => clearInterval(iv);
+ }, []);
+ useEffect(() => {
+ const loadCharts = () => api('/api/portfauxlio/charts?period=7d').then(d => {
+ const byId = {};
+ (d.portfolios || []).forEach(p => { byId[p.id] = p; });
+ setChartData(byId);
+ }).catch(() => {});
+ loadCharts();
+ const cv = setInterval(loadCharts, 120000);
+ return () => clearInterval(cv);
+ }, []);
+ const [swotData, setSwotData] = useState(null);
+ const [swotExpanded, setSwotExpanded] = useState({});
+ useEffect(() => {
+ const loadSwot = () => api('/api/portfauxlio/swot').then(setSwotData).catch(() => {});
+ loadSwot();
+ const sv = setInterval(loadSwot, 60000);
+ return () => clearInterval(sv);
+ }, []);
+
+ const stratColors = {aggressive:'#ef4444',conservative:'#3b82f6',weather:'#06b6d4',momentum:'#f59e0b',contrarian:'#8b5cf6',ai_enhanced:'#ec4899',mc_validated:'#a855f7',scalper:'#eab308',patient:'#22c55e',random:'#64748b',penny_pincher:'#94a3b8',spray_pray:'#fb923c',nickel_slots:'#a78bfa',degen_lite:'#f43f5e',politics_junkie:'#0ea5e9',double_down:'#dc2626',volatility_rider:'#14b8a6',whale:'#1d4ed8',yolo:'#e11d48',full_send:'#b91c1c',kelly_criterion:'#059669',sharpe_sniper:'#7c3aed',bayesian_blend:'#0891b2',ensemble_lock:'#c026d3',mean_revert:'#d97706',info_ratio:'#2563eb',anti_fomo:'#16a34a',nightcrawler:'#4c1d95',heatseeker:'#ea580c',quant_core:'#0d9488',etf_presidential:'#dc143c',etf_cabinet:'#ff6347',etf_congress:'#4169e1',etf_scotus:'#2f4f4f',etf_fed:'#228b22',etf_economy:'#daa520',etf_geopolitics:'#8b0000',etf_territory:'#006400',etf_climate:'#00bfff',etf_energy:'#ff8c00',etf_tech:'#7b68ee',etf_space:'#191970',etf_crypto:'#ffd700',etf_sports:'#32cd32',etf_entertainment:'#ff1493',etf_legal:'#708090',etf_financials:'#4682b4',etf_govreform:'#b22222',etf_global_social:'#9370db',etf_broad_market:'#c0a050'};
+ const stratEmojis = {aggressive:'🔥',conservative:'🏛️',weather:'⛈️',momentum:'🚀',contrarian:'🔄',ai_enhanced:'🧠',mc_validated:'🎲',scalper:'⚡',patient:'🐢',random:'🎰',penny_pincher:'🪙',spray_pray:'💦',nickel_slots:'🎰',degen_lite:'😈',politics_junkie:'🏛️',double_down:'⬆️',volatility_rider:'🏄',whale:'🐳',yolo:'🧨',full_send:'💣',kelly_criterion:'🎰',sharpe_sniper:'🎯',bayesian_blend:'🧮',ensemble_lock:'🔐',mean_revert:'↩️',info_ratio:'📊',anti_fomo:'🧘',nightcrawler:'🦇',heatseeker:'🔬',quant_core:'∑',etf_presidential:'🏛️',etf_cabinet:'💼',etf_congress:'🗳️',etf_scotus:'⚖️',etf_fed:'🏦',etf_economy:'📈',etf_geopolitics:'🌍',etf_territory:'🗺️',etf_climate:'🌡️',etf_energy:'⛽',etf_tech:'🤖',etf_space:'🚀',etf_crypto:'₿',etf_sports:'⚽',etf_entertainment:'🎬',etf_legal:'🔨',etf_financials:'💹',etf_govreform:'✂️',etf_global_social:'⛪',etf_broad_market:'🌐'};
+ const stratNames = {aggressive:'Alpha',conservative:'Beta',weather:'Storm',momentum:'Momentum',contrarian:'Contrarian',ai_enhanced:'Nova',mc_validated:'Oracle',scalper:'Shark',patient:'Turtle',random:'Wildcard',penny_pincher:'Penny',spray_pray:'Spray',nickel_slots:'Nickel',degen_lite:'Degen',politics_junkie:'Capitol',double_down:'Doubler',volatility_rider:'Rider',whale:'Moby',yolo:'YOLO',full_send:'Cannon',kelly_criterion:'Kelly',sharpe_sniper:'Sniper',bayesian_blend:'Bayes',ensemble_lock:'Voltron',mean_revert:'Revert',info_ratio:'Signal',anti_fomo:'Zen',nightcrawler:'Shadow',heatseeker:'Heatseek',quant_core:'Quant',etf_presidential:'PRES',etf_cabinet:'Cabinet',etf_congress:'Congress',etf_scotus:'SCOTUS',etf_fed:'Fed',etf_economy:'Economy',etf_geopolitics:'Geo',etf_territory:'Territory',etf_climate:'Climate',etf_energy:'Energy',etf_tech:'Tech',etf_space:'Space',etf_crypto:'Crypto',etf_sports:'Sports',etf_entertainment:'Showbiz',etf_legal:'Legal',etf_financials:'Finance',etf_govreform:'GovReform',etf_global_social:'Global',etf_broad_market:'Broad Mkt'};
+ const stratDesc = {aggressive:'High edge (>15%), low confidence — speculative swings',conservative:'High confidence (>70%) — quality over quantity',weather:'Weather/climate markets only',momentum:'High agreement + articles — follows the trend',contrarian:'BUY_NO only — bets against the crowd',ai_enhanced:'Gemini AI enhanced signals only',mc_validated:'Monte Carlo validated, tight spread',scalper:'Small edges (3-10%) — quantity plays',patient:'Needs everything: conf>80%, MC, 5+ articles',random:'20% random — control group for luck testing',penny_pincher:'Any edge >=1% — micro bets, max volume',spray_pray:'Random 50% of all signals — luck vs skill',nickel_slots:'Edge >=2% + conf >=20% — low bar catcher',degen_lite:'Edge >=5%, ignores confidence — pure edge',politics_junkie:'Political markets only — elections/congress',double_down:'Edge >=20% — goes big on massive edges',volatility_rider:'High MC stddev + edge — volatile markets',whale:'Edge >=25% + conf >=60% — rare massive sniper',yolo:'Edge >=30% — max degen, no filters',full_send:'Takes EVERY signal — pipeline profitability test',kelly_criterion:'Kelly fraction: edge/(1+edge) — bankroll math',sharpe_sniper:'Signal-to-noise ratio >2.0 — edge/stddev',bayesian_blend:'Bayesian posterior: conf * evidence * edge',ensemble_lock:'ALL must align: AI + MC + conf + edge + articles',mean_revert:'High volatility + moderate edge — reversion play',info_ratio:'(articles * agreement) / noise — quality intel',anti_fomo:'Small edge + high conf — calm, certain plays',nightcrawler:'BUY_NO + AI + MC — sophisticated shorts',heatseeker:'Multi-factor composite: 40e + 30c + 20a + 10n',quant_core:'Geometric mean sqrt(edge*conf) — pure math',etf_presidential:'Presidential election & 2028 race markets',etf_cabinet:'Cabinet confirmations & departures',etf_congress:'House, Senate & legislative markets',etf_scotus:'Supreme Court rulings & retirements',etf_fed:'Federal Reserve, rates & monetary policy',etf_economy:'GDP, jobs & economic indicators',etf_geopolitics:'Wars, treaties, sanctions & foreign affairs',etf_territory:'Greenland, statehood & territorial expansion',etf_climate:'Weather, warming & climate events',etf_energy:'LNG, oil, power grid & energy commodities',etf_tech:'AI, fusion, tech companies & semiconductors',etf_space:'SpaceX, NASA, Mars & Moon missions',etf_crypto:'Bitcoin, Ethereum & digital assets',etf_sports:'NBA, NFL, MLB & sports outcomes',etf_entertainment:'Celebrity, media, awards & pop culture',etf_legal:'Pardons, impeachment & legal proceedings',etf_financials:'Bonds, yields & financial markets',etf_govreform:'DOGE, agency cuts & government reform',etf_global_social:'Pope, referendums & global social movements',etf_broad_market:'Index fund — high-quality signals all sectors'};
+
+ if (!data) return <div style={{textAlign:'center',padding:60,color:'var(--muted)'}}>Loading portFAUXlio data...</div>;
+
+ const { portfolios: rawPortfolios, activeTrades, tradeHistory, overlaps, summary } = data;
+ const maxInvested = Math.max(...rawPortfolios.map(p => parseInt(p.total_invested_cents) || 0), 1);
+ const filteredHistory = histFilter === 'all' ? tradeHistory : tradeHistory.filter(t => t.strategy === histFilter);
+
+ const sortFns = {
+ pnl: p => parseInt(p.pnl_cents) || 0,
+ roi: p => parseFloat(p.roi_pct) || 0,
+ invested: p => parseInt(p.total_invested_cents) || 0,
+ trades: p => (parseInt(p.trades_won)||0) + (parseInt(p.trades_lost)||0) + (parseInt(p.trades_expired)||0),
+ wins: p => parseInt(p.trades_won) || 0,
+ name: p => (p.name || '').toLowerCase(),
+ strategy: p => (p.strategy || '').toLowerCase(),
+ };
+ const getSortVal = sortFns[sortBy] || sortFns.pnl;
+ const portfolios = [...rawPortfolios].sort((a, b) => {
+ const av = getSortVal(a), bv = getSortVal(b);
+ if (typeof av === 'string') return sortDir === 'asc' ? av.localeCompare(bv) : bv.localeCompare(av);
+ return sortDir === 'desc' ? bv - av : av - bv;
+ });
+ const toggleSort = (col) => { if (sortBy === col) setSortDir(d => d === 'desc' ? 'asc' : 'desc'); else { setSortBy(col); setSortDir('desc'); } };
+
+ return (<div>
+ {/* ═══ Banner ═══ */}
+ <div className="pf-banner">
+ <div className="pf-banner-title">portFAUXlio</div>
+ <div className="pf-banner-sub">50 Strategy Models • Paper Trading • Real Signals • Zero Real Money</div>
+ </div>
+
+ {/* ═══ Summary Stats ═══ */}
+ <div className="pf-summary-row">
+ <div className="pf-summary-card">
+ <div className="pf-summary-val" style={{color: summary.totalPnl >= 0 ? 'var(--green)' : 'var(--red)'}}>
+ {summary.totalPnl >= 0 ? '+' : ''}{'$'}{(summary.totalPnl / 100).toFixed(2)}
+ </div>
+ <div className="pf-summary-lbl">Total P&L</div>
+ </div>
+ <div className="pf-summary-card">
+ <div className="pf-summary-val" style={{color:'var(--blue)'}}>{'$'}{(summary.totalInvested / 100).toFixed(2)}</div>
+ <div className="pf-summary-lbl">Invested</div>
+ </div>
+ <div className="pf-summary-card">
+ <div className="pf-summary-val" style={{color:'var(--purple)'}}>{summary.totalTrades}</div>
+ <div className="pf-summary-lbl">Total Trades</div>
+ </div>
+ <div className="pf-summary-card">
+ <div className="pf-summary-val" style={{color:'var(--green)'}}>{summary.openTrades}</div>
+ <div className="pf-summary-lbl">Open Positions</div>
+ </div>
+ <div className="pf-summary-card">
+ <div className="pf-summary-val" style={{color:'var(--cyan)'}}>{summary.uniqueMarkets}</div>
+ <div className="pf-summary-lbl">Markets</div>
+ </div>
+ <div className="pf-summary-card">
+ <div className="pf-summary-val" style={{color:'var(--yellow)'}}>{summary.activeModels}/{portfolios ? portfolios.length : 50}</div>
+ <div className="pf-summary-lbl">Active Models</div>
+ </div>
+ </div>
+
+ {/* ═══ Active Trades Strip ═══ */}
+ {activeTrades.length > 0 && <div className="pf-active-strip">
+ <div className="pf-active-header">
+ <span className="dot" />
+ {activeTrades.length} Open Positions
+ </div>
+ <div className="pf-active-scroll">
+ {activeTrades.map((t, i) => {
+ const c = stratColors[t.strategy] || 'var(--muted)';
+ return (<div key={i} className="pf-active-card" style={{borderTopColor: c}}>
+ <div style={{display:'flex',alignItems:'center',gap:6,marginBottom:4}}>
+ <span style={{fontSize:14}}>{stratEmojis[t.strategy] || ''}</span>
+ <span style={{fontSize:11,fontWeight:700,color:c}}>{t.portfolio_name}</span>
+ <span style={{marginLeft:'auto',padding:'1px 6px',borderRadius:4,fontSize:9,fontWeight:700,
+ background: t.direction === 'BUY_YES' ? 'rgba(34,197,94,.15)' : 'rgba(239,68,68,.15)',
+ color: t.direction === 'BUY_YES' ? 'var(--green)' : 'var(--red)'
+ }}>{t.direction === 'BUY_YES' ? 'YES' : 'NO'}</span>
+ </div>
+ <div style={{fontSize:10,fontWeight:600,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap',marginBottom:3}} title={t.market_title || t.market_id}>
+ {t.market_title || t.market_id}
+ </div>
+ <div style={{display:'flex',justifyContent:'space-between',fontSize:10,color:'var(--muted)'}}>
+ <span>{t.contracts}x @ {t.entry_price_cents}¢</span>
+ <span>{'$'}{(t.cost_cents / 100).toFixed(2)}</span>
+ <span>{timeAgo(t.created_at)}</span>
+ </div>
+ </div>);
+ })}
+ </div>
+ </div>}
+
+ {/* ═══ Model Leaderboard ═══ */}
+ <div style={{marginBottom:18}}>
+ <div style={{fontSize:13,fontWeight:700,textTransform:'uppercase',letterSpacing:.5,marginBottom:10,color:'var(--pink)',display:'flex',alignItems:'center',gap:8}}>
+ Model Leaderboard
+ <span style={{fontSize:9,fontWeight:400,color:'var(--muted)',textTransform:'none',letterSpacing:0}}>ranked by {sortBy}</span>
+ <div style={{marginLeft:'auto',display:'flex',gap:6}}>
+ {compareMode && compareIds.length >= 2 && <button onClick={() => setCompareMode('show')} style={{padding:'3px 10px',borderRadius:6,fontSize:9,fontWeight:700,background:'rgba(6,182,212,.15)',border:'1px solid var(--cyan)',color:'var(--cyan)',cursor:'pointer'}}>
+ Compare {compareIds.length} →
+ </button>}
+ <button onClick={() => { if (compareMode) { setCompareMode(false); setCompareIds([]); } else setCompareMode(true); }} style={{padding:'3px 10px',borderRadius:6,fontSize:9,fontWeight:700,background:compareMode?'rgba(168,85,247,.15)':'transparent',border:'1px solid '+(compareMode?'var(--purple)':'var(--border)'),color:compareMode?'var(--purple)':'var(--muted)',cursor:'pointer'}}>
+ {compareMode ? '✕ Cancel' : '📊 Compare'}
+ </button>
+ </div>
+ </div>
+ <div className="pf-leaderboard">
+ <div className="pf-lb-header">
+ <span>#</span>
+ <span style={{cursor:'pointer'}} onClick={() => toggleSort('name')}>Model {sortBy==='name' ? (sortDir==='asc'?'▲':'▼') : ''}</span>
+ <span style={{cursor:'pointer'}} onClick={() => toggleSort('pnl')}>P&L {sortBy==='pnl' ? (sortDir==='asc'?'▲':'▼') : ''}</span>
+ <span style={{cursor:'pointer'}} onClick={() => toggleSort('invested')}>Invested {sortBy==='invested' ? (sortDir==='asc'?'▲':'▼') : ''}</span>
+ <span style={{cursor:'pointer'}} onClick={() => toggleSort('roi')}>ROI {sortBy==='roi' ? (sortDir==='asc'?'▲':'▼') : ''}</span>
+ <span style={{cursor:'pointer'}} onClick={() => toggleSort('wins')}>W {sortBy==='wins' ? (sortDir==='asc'?'▲':'▼') : ''}</span>
+ <span>L</span>
+ <span style={{cursor:'pointer'}} onClick={() => toggleSort('trades')}>Trades {sortBy==='trades' ? (sortDir==='asc'?'▲':'▼') : ''}</span>
+ <span style={{cursor:'pointer'}} onClick={() => toggleSort('strategy')}>Strategy {sortBy==='strategy' ? (sortDir==='asc'?'▲':'▼') : ''}</span>
+ <span>Chart</span>
+ </div>
+ {portfolios.map((p, i) => {
+ const c = stratColors[p.strategy] || 'var(--muted)';
+ const pnl = parseInt(p.pnl_cents) || 0;
+ const invested = parseInt(p.total_invested_cents) || 0;
+ const resolved = parseInt(p.resolved_trades) || 0;
+ const roi = parseFloat(p.roi_pct) || 0;
+ const totalT = (parseInt(p.trades_won) || 0) + (parseInt(p.trades_lost) || 0) + (parseInt(p.trades_expired) || 0);
+ const openCount = activeTrades.filter(t => t.portfolio_id === p.id).length;
+ const medals = ['🥇','🥈','🥉'];
+ const cd = chartData[p.id];
+ const miniPts = cd ? (cd.snapshots || []).map(s => s.nav / 100) : (cd?.daily || []).map(d => d.cumulative / 100);
+ return (<div key={p.id} className="pf-lb-row" style={compareMode && compareIds.includes(p.id) ? {background:'rgba(168,85,247,.08)',borderLeft:'3px solid var(--purple)'} : {}} onClick={() => {
+ if (compareMode) { setCompareIds(prev => prev.includes(p.id) ? prev.filter(x => x !== p.id) : [...prev, p.id]); }
+ else if (cd) setSelectedChart({id:p.id,strategy:p.strategy,name:p.name,color:c});
+ }}>
+ <span className="pf-lb-rank">{i < 3 ? medals[i] : (i+1)}</span>
+ <span className="pf-lb-name" style={{color:c}}>
+ <span style={{fontSize:16}}>{stratEmojis[p.strategy]||''}</span>
+ {p.name}
+ </span>
+ <span className="pf-lb-pnl" style={{color: pnl >= 0 ? 'var(--green)' : 'var(--red)'}}>
+ {pnl >= 0 ? '+' : ''}{'$'}{(pnl / 100).toFixed(2)}
+ </span>
+ <span className="pf-lb-invested">{'$'}{(invested / 100).toFixed(2)}</span>
+ <span className="pf-lb-roi" style={{
+ background: roi > 0 ? 'rgba(34,197,94,.12)' : roi < 0 ? 'rgba(239,68,68,.12)' : 'rgba(255,255,255,.04)',
+ color: roi > 0 ? 'var(--green)' : roi < 0 ? 'var(--red)' : 'var(--muted)'
+ }}>{roi > 0 ? '+' : ''}{roi}%</span>
+ <span className="pf-lb-wl" style={{color:'var(--green)'}}>{p.trades_won}</span>
+ <span className="pf-lb-wl" style={{color:'var(--red)'}}>{p.trades_lost}</span>
+ <span style={{fontVariantNumeric:'tabular-nums',color:'var(--muted)'}}>
+ {openCount > 0 ? <span>{openCount} <span style={{fontSize:8,color:'var(--green)'}}>OPEN</span></span> : <span style={{color:'var(--muted)'}}>0</span>}
+ {resolved > 0 && <span style={{marginLeft:4,fontSize:9}}>+{resolved}</span>}
+ </span>
+ <span style={{fontSize:9,color:'var(--muted)',overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}} title={stratDesc[p.strategy]}>
+ {p.strategy}
+ </span>
+ <span style={{display:'flex',alignItems:'center',justifyContent:'center'}}>
+ {miniPts && miniPts.length >= 2 ? <MiniChart data={miniPts} color={c} /> : <span style={{fontSize:9,color:'var(--muted)'}}>--</span>}
+ </span>
+ </div>);
+ })}
+ </div>
+ </div>
+
+ {/* ═══ Overlap Analysis ═══ */}
+ {overlaps.length > 0 && <div className="pf-overlap">
+ <div className="pf-overlap-title">
+ ⚠️ Strategy Overlap — Markets with 2+ models
+ </div>
+ <div style={{display:'flex',flexDirection:'column',gap:4}}>
+ {overlaps.slice(0, 8).map((o, i) => (
+ <div key={i} style={{display:'flex',alignItems:'center',gap:8,fontSize:10,padding:'4px 0'}}>
+ <span style={{fontWeight:700,color:'var(--yellow)',minWidth:20}}>{o.num_strategies}x</span>
+ <span style={{fontWeight:600,minWidth:180,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>{o.market_id}</span>
+ <span style={{color:'var(--muted)',flex:1,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>
+ {(o.portfolios || []).join(', ')}
+ </span>
+ <span style={{fontVariantNumeric:'tabular-nums',color:'var(--muted)'}}>{'$'}{((o.total_exposure || 0) / 100).toFixed(2)}</span>
+ </div>
+ ))}
+ </div>
+ </div>}
+
+ {/* ═══ SWOT Trade Intelligence ═══ */}
+ {swotData && swotData.markets && swotData.markets.length > 0 && <div className="swot-section">
+ <div style={{fontSize:13,fontWeight:700,textTransform:'uppercase',letterSpacing:.5,marginBottom:12,color:'var(--purple)',display:'flex',alignItems:'center',gap:8}}>
+ Trade Intelligence & SWOT
+ <span style={{fontSize:9,fontWeight:400,color:'var(--muted)',textTransform:'none',letterSpacing:0}}>{swotData.markets.length} active markets • {swotData.total_trades} trades this week</span>
+ </div>
+ {swotData.markets.map((m, idx) => {
+ const isOpen = swotExpanded[m.market_id];
+ return (<div key={m.market_id} className="swot-card">
+ <div className="swot-card-header" onClick={() => setSwotExpanded(prev => ({...prev, [m.market_id]: !prev[m.market_id]}))}>
+ <span style={{fontSize:16,fontWeight:900,color:'var(--muted)',minWidth:24}}>{idx+1}</span>
+ <span style={{padding:'2px 8px',borderRadius:4,fontSize:9,fontWeight:800,
+ background: m.direction === 'BUY_YES' ? 'rgba(34,197,94,.15)' : 'rgba(239,68,68,.15)',
+ color: m.direction === 'BUY_YES' ? 'var(--green)' : 'var(--red)'
+ }}>{m.direction === 'BUY_YES' ? 'YES' : 'NO'}</span>
+ <span style={{flex:1,fontWeight:700,fontSize:11,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}} title={m.title}>{m.title}</span>
+ <span style={{fontSize:10,color:'var(--cyan)',fontWeight:700}}>{m.model_count} models</span>
+ <span style={{fontSize:10,fontWeight:700,color:m.edge >= 10 ? 'var(--green)' : 'var(--yellow)'}}>{m.edge.toFixed(1)}% edge</span>
+ <span style={{fontSize:10,fontVariantNumeric:'tabular-nums',color:'var(--muted)'}}>{'$'}{(m.total_cost / 100).toFixed(2)}</span>
+ <span style={{fontSize:10,fontWeight:700,color: m.open_count > 0 ? 'var(--green)' : 'var(--muted)'}}>{m.open_count > 0 ? m.open_count + ' OPEN' : 'CLOSED'}</span>
+ <span style={{fontSize:14,color:'var(--muted)',transform:isOpen?'rotate(180deg)':'rotate(0)',transition:'transform .2s'}}>▼</span>
+ </div>
+ {isOpen && <div>
+ <div className="swot-grid">
+ <div className="swot-quadrant swot-quadrant-s">
+ <div className="swot-q-title" style={{color:'var(--green)'}}>Strengths</div>
+ {m.swot.strengths.map((s, i) => <div key={i} className="swot-q-item">{s}</div>)}
+ </div>
+ <div className="swot-quadrant swot-quadrant-w">
+ <div className="swot-q-title" style={{color:'var(--red)'}}>Weaknesses</div>
+ {m.swot.weaknesses.map((w, i) => <div key={i} className="swot-q-item">{w}</div>)}
+ </div>
+ <div className="swot-quadrant swot-quadrant-o">
+ <div className="swot-q-title" style={{color:'var(--blue)'}}>Opportunities</div>
+ {m.swot.opportunities.map((o, i) => <div key={i} className="swot-q-item">{o}</div>)}
+ </div>
+ <div className="swot-quadrant swot-quadrant-t">
+ <div className="swot-q-title" style={{color:'var(--yellow)'}}>Threats</div>
+ {m.swot.threats.map((t, i) => <div key={i} className="swot-q-item">{t}</div>)}
+ </div>
+ </div>
+ <div style={{padding:'8px 16px',fontSize:10,color:'var(--muted)',lineHeight:1.5,borderTop:'1px solid rgba(255,255,255,.03)'}}>
+ <strong style={{color:'var(--text)'}}>Signal:</strong> {m.reasoning}
+ </div>
+ <div style={{padding:'4px 16px 6px',fontSize:10,color:'var(--muted)',display:'flex',gap:16,flexWrap:'wrap'}}>
+ <span>Conf: <strong style={{color:'var(--cyan)'}}>{Math.round(m.confidence * 100)}%</strong></span>
+ <span>Entry: <strong>{m.entry_price}¢</strong></span>
+ {m.mc_mean > 0 && <span>MC: <strong>{m.mc_mean.toFixed(1)}% ±{m.mc_std.toFixed(1)}%</strong></span>}
+ {m.articles > 0 && <span>News: <strong>{m.articles} articles</strong></span>}
+ {m.agreement > 0 && <span>Agree: <strong>{m.agreement}%</strong></span>}
+ </div>
+ <div className="swot-models">
+ {m.trades.map((t, i) => (
+ <span key={i} className="swot-model-tag" style={{color:stratColors[t.strategy]||'var(--muted)',borderColor:(stratColors[t.strategy]||'var(--border)')+'40'}}>
+ {stratEmojis[t.strategy]||''} {t.portfolio} • {t.contracts}x • {t.status === 'open' ? 'OPEN' : (t.pnl >= 0 ? '+' : '') + '$' + (t.pnl / 100).toFixed(2)}
+ </span>
+ ))}
+ </div>
+ </div>}
+ </div>);
+ })}
+ </div>}
+
+ {/* ═══ Trade History ═══ */}
+ <div className="pf-history">
+ <div className="pf-history-header">
+ <span style={{fontSize:13,fontWeight:700,textTransform:'uppercase',letterSpacing:.5,color:'var(--cyan)'}}>Trade History</span>
+ <div style={{display:'flex',gap:4}}>
+ <button onClick={() => setHistFilter('all')} style={{padding:'3px 10px',borderRadius:6,border:'1px solid '+(histFilter==='all'?'var(--cyan)':'var(--border)'),background:histFilter==='all'?'rgba(6,182,212,.1)':'transparent',color:histFilter==='all'?'var(--cyan)':'var(--muted)',fontSize:10,fontWeight:600,cursor:'pointer'}}>All</button>
+ {portfolios.filter(p => parseInt(p.total_invested_cents) > 0).map(p => (
+ <button key={p.strategy} onClick={() => setHistFilter(p.strategy)} style={{padding:'3px 10px',borderRadius:6,border:'1px solid '+(histFilter===p.strategy?stratColors[p.strategy]:'var(--border)'),background:histFilter===p.strategy?stratColors[p.strategy]+'18':'transparent',color:histFilter===p.strategy?stratColors[p.strategy]:'var(--muted)',fontSize:10,fontWeight:600,cursor:'pointer'}}>
+ {stratEmojis[p.strategy] || ''} {p.name}
+ </button>
+ ))}
+ </div>
+ </div>
+ <div className="pf-history-list">
+ {filteredHistory.length === 0 && <div style={{textAlign:'center',padding:30,color:'var(--muted)',fontSize:12}}>No trades for this filter</div>}
+ {filteredHistory.slice(0, 100).map((t, i) => {
+ const c = stratColors[t.strategy] || 'var(--muted)';
+ const pnl = parseInt(t.pnl_cents) || 0;
+ return (<div key={i} className="pf-history-row">
+ <span style={{width:6,height:6,borderRadius:'50%',flexShrink:0,background:
+ t.status === 'open' ? 'var(--green)' : t.status === 'won' ? 'var(--blue)' : t.status === 'lost' ? 'var(--red)' : 'var(--muted)'
+ }} />
+ <span style={{minWidth:60,fontWeight:700,color:c,fontSize:10}}>{t.portfolio_name}</span>
+ <span style={{padding:'1px 6px',borderRadius:3,fontSize:9,fontWeight:700,
+ background: t.direction === 'BUY_YES' ? 'rgba(34,197,94,.12)' : 'rgba(239,68,68,.12)',
+ color: t.direction === 'BUY_YES' ? 'var(--green)' : 'var(--red)'
+ }}>{t.direction === 'BUY_YES' ? 'YES' : 'NO'}</span>
+ <span style={{flex:1,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap',color:'var(--text)'}} title={t.market_title || t.market_id}>
+ {t.market_title || t.market_id}
+ </span>
+ <span style={{fontVariantNumeric:'tabular-nums',color:'var(--muted)',fontSize:10}}>
+ {t.contracts}x @ {t.entry_price_cents}¢
+ </span>
+ <span style={{fontVariantNumeric:'tabular-nums',color:'var(--muted)',fontSize:10,minWidth:45,textAlign:'right'}}>
+ {'$'}{(t.cost_cents / 100).toFixed(2)}
+ </span>
+ <span style={{fontWeight:800,fontVariantNumeric:'tabular-nums',minWidth:55,textAlign:'right',fontSize:10,
+ color: t.status === 'open' ? 'var(--yellow)' : pnl >= 0 ? 'var(--green)' : 'var(--red)'
+ }}>
+ {t.status === 'open' ? 'OPEN' : (pnl >= 0 ? '+' : '') + (pnl / 100).toFixed(2)}
+ </span>
+ <span style={{fontSize:9,color:'var(--muted)',minWidth:55,textAlign:'right'}}>{timeAgo(t.created_at)}</span>
+ </div>);
+ })}
+ </div>
+ </div>
+
+ {/* ═══ FullChart Modal ═══ */}
+ {selectedChart && chartData[selectedChart.id] && <FullChart
+ chartData={chartData[selectedChart.id]}
+ portfolioId={selectedChart.id}
+ strategy={selectedChart.strategy}
+ name={selectedChart.name}
+ color={selectedChart.color || stratColors[selectedChart.strategy] || '#8b5cf6'}
+ emoji={stratEmojis[selectedChart.strategy] || ''}
+ desc={stratDesc[selectedChart.strategy] || ''}
+ onClose={() => setSelectedChart(null)}
+ />}
+
+ {/* ═══ Comparison Chart Modal ═══ */}
+ {compareMode === 'show' && compareIds.length >= 2 && <ComparisonChart
+ portfolioIds={compareIds}
+ allChartData={chartData}
+ stratColors={stratColors}
+ stratNames={stratNames}
+ stratEmojis={stratEmojis}
+ onClose={() => { setCompareMode(false); setCompareIds([]); }}
+ />}
+
+ {/* ═══ Strategy Guide ═══ */}
+ <div style={{marginTop:18,padding:16,background:'var(--card)',border:'1px solid var(--border)',borderRadius:14}}>
+ <div style={{fontSize:11,fontWeight:700,color:'var(--muted)',textTransform:'uppercase',letterSpacing:.5,marginBottom:10}}>Strategy Guide</div>
+ <div style={{display:'grid',gridTemplateColumns:'repeat(auto-fill,minmax(280px,1fr))',gap:6}}>
+ {Object.entries(stratDesc).map(([strat, desc]) => (
+ <div key={strat} style={{display:'flex',alignItems:'flex-start',gap:8,fontSize:10,padding:'4px 0',color:'var(--muted)'}}>
+ <span style={{fontSize:14,flexShrink:0}}>{stratEmojis[strat]||''}</span>
+ <div>
+ <span style={{fontWeight:700,color:stratColors[strat]}}>{stratNames[strat]}</span>
+ <span style={{margin:'0 4px'}}>—</span>
+ {desc}
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+ </div>);
+}
+
+// ── PREDICTIONS TAB ──
+function PredictionsTab() {
+ const [data, setData] = useState(null);
+ useEffect(() => {
+ api('/api/predictions-history').then(setData).catch(()=>{});
+ const iv = setInterval(() => api('/api/predictions-history').then(setData).catch(()=>{}), 30000);
+ return () => clearInterval(iv);
+ }, []);
+ if (!data) return <div style={{textAlign:'center',padding:40,color:'var(--muted)'}}>Loading predictions...</div>;
+
+ const statsMap = {};
+ (data.stats||[]).forEach(s => { statsMap[s.outcome] = s; });
+
+ return (<div>
+ <div style={{display:'flex',gap:12,marginBottom:20,flexWrap:'wrap'}}>
+ {['win','loss','expired'].map(o => {
+ const s = statsMap[o]||{cnt:0,avg_pnl:0,avg_conf:0};
+ const c = o==='win'?'var(--green)':o==='loss'?'var(--red)':'var(--muted)';
+ return (<div key={o} style={{background:'var(--card)',border:'1px solid var(--border)',borderRadius:12,padding:16,flex:1,minWidth:140,textAlign:'center'}}>
+ <div style={{fontSize:28,fontWeight:700,color:c}}>{s.cnt}</div>
+ <div style={{fontSize:10,color:'var(--muted)',textTransform:'uppercase',letterSpacing:1,marginTop:2}}>{o==='win'?'Wins':o==='loss'?'Losses':'Expired'}</div>
+ <div style={{fontSize:11,color:'var(--muted)',marginTop:4}}>Avg P&L: <strong style={{color:c}}>{parseFloat(s.avg_pnl||0)>0?'+':''}{s.avg_pnl||0}¢</strong></div>
+ <div style={{fontSize:11,color:'var(--muted)'}}>Avg Conf: {s.avg_conf||0}%</div>
+ </div>);
+ })}
+ <div style={{background:'var(--card)',border:'1px solid var(--border)',borderRadius:12,padding:16,flex:1,minWidth:140,textAlign:'center'}}>
+ <div style={{fontSize:28,fontWeight:700,color:'var(--blue)'}}>{statsMap.win?Math.round(parseInt(statsMap.win.cnt)/(parseInt(statsMap.win.cnt)+parseInt(statsMap.loss?.cnt||0))*100):0}%</div>
+ <div style={{fontSize:10,color:'var(--muted)',textTransform:'uppercase',letterSpacing:1,marginTop:2}}>Win Rate</div>
+ <div style={{fontSize:11,color:'var(--muted)',marginTop:4}}>W/L only (excl. expired)</div>
+ </div>
+ </div>
+
+ <h3 style={{fontSize:14,fontWeight:600,marginBottom:10,display:'flex',alignItems:'center',gap:8}}>Resolved Predictions <span style={{fontSize:11,color:'var(--muted)',fontWeight:400}}>— what actually happened</span></h3>
+ <div style={{display:'flex',flexDirection:'column',gap:4}}>
+ {(data.predictions||[]).slice(0,30).map((p,i) => {
+ const oc = p.outcome==='win'?'var(--green)':p.outcome==='loss'?'var(--red)':'var(--muted)';
+ return (<div key={i} style={{display:'flex',alignItems:'center',gap:10,padding:'8px 14px',background:'var(--card)',border:'1px solid var(--border)',borderRadius:8,fontSize:12}}>
+ <span style={{padding:'2px 8px',borderRadius:4,fontWeight:700,fontSize:10,background:p.outcome==='win'?'rgba(34,197,94,.15)':p.outcome==='loss'?'rgba(239,68,68,.15)':'rgba(255,255,255,.05)',color:oc,minWidth:48,textAlign:'center',textTransform:'uppercase'}}>{p.outcome}</span>
+ <span style={{padding:'2px 8px',borderRadius:4,fontSize:10,fontWeight:600,background:p.side==='YES'||p.side==='yes'?'rgba(34,197,94,.1)':'rgba(239,68,68,.1)',color:p.side==='YES'||p.side==='yes'?'var(--green)':'var(--red)'}}>{p.side}</span>
+ <span style={{flex:1,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}} title={p.title}>{p.title||p.ticker}</span>
+ <span style={{fontVariantNumeric:'tabular-nums',color:'var(--muted)',fontSize:11}}>Conf:{p.confidence}%</span>
+ <span style={{fontVariantNumeric:'tabular-nums',color:'var(--muted)',fontSize:11}}>{p.entry_price}¢→{p.exit_price||'?'}¢</span>
+ <span style={{fontWeight:700,fontVariantNumeric:'tabular-nums',color:oc,minWidth:45,textAlign:'right'}}>{p.pnl_cents>0?'+':''}{p.pnl_cents||0}¢</span>
+ <span style={{fontSize:10,color:'var(--muted)',minWidth:70,textAlign:'right'}}>{p.resolved_at?new Date(p.resolved_at).toLocaleDateString('en-US',{month:'short',day:'numeric'}):''}</span>
+ </div>);
+ })}
+ </div>
+ </div>);
+}
+
+// ── Sparkline SVG Component ──
+function Sparkline({ data, width = 120, height = 30, color = '#8b5cf6', showDots = false, showArea = true, label }) {
+ if (!data || data.length < 2) return null;
+ const max = Math.max(...data);
+ const min = Math.min(...data);
+ const range = max - min || 1;
+ const gradId = 'grad-' + color.replace('#','') + '-' + width;
+ const points = data.map((v, i) => {
+ const x = (i / (data.length - 1)) * width;
+ const y = height - ((v - min) / range) * (height - 6) - 3;
+ return x + ',' + y;
+ }).join(' ');
+ const areaPoints = points + ' ' + width + ',' + height + ' 0,' + height;
+ const lastVal = data[data.length - 1];
+ const prevVal = data[data.length - 2];
+ const trending = lastVal >= prevVal;
+ return (
+ <div style={{position:'relative'}}>
+ <svg className="sparkline-svg" width={width} height={height} viewBox={'0 0 ' + width + ' ' + height}>
+ <defs><linearGradient id={gradId} x1="0" y1="0" x2="0" y2="1">
+ <stop offset="0%" stopColor={color} stopOpacity="0.25"/><stop offset="100%" stopColor={color} stopOpacity="0.01"/>
+ </linearGradient></defs>
+ {showArea && <polygon points={areaPoints} fill={'url(#' + gradId + ')'} />}
+ <polyline points={points} fill="none" stroke={color} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
+ {showDots && data.map((v, i) => {
+ const x = (i / (data.length - 1)) * width;
+ const y = height - ((v - min) / range) * (height - 6) - 3;
+ return <circle key={i} cx={x} cy={y} r={i === data.length - 1 ? 3 : 1.5} fill={i === data.length - 1 ? color : 'transparent'} stroke={color} strokeWidth={i === data.length - 1 ? 0 : 0.5} opacity={i === data.length - 1 ? 1 : 0.5} />;
+ })}
+ </svg>
+ {label && <div style={{position:'absolute',top:2,right:4,fontSize:9,color:trending?'var(--green)':'var(--red)',fontWeight:700}}>
+ {trending?'▲':'▼'} {lastVal.toLocaleString()}
+ </div>}
+ </div>
+ );
+}
+
+// ── MiniChart: Canvas-based sparkline for leaderboard rows ──
+function MiniChart({ data, color, width = 140, height = 36 }) {
+ const canvasRef = React.useRef(null);
+ const chartRef = React.useRef(null);
+ React.useEffect(() => {
+ if (!data || data.length < 2 || !canvasRef.current) return;
+ if (chartRef.current) chartRef.current.destroy();
+ const ctx = canvasRef.current.getContext('2d');
+ const gradient = ctx.createLinearGradient(0, 0, 0, height);
+ gradient.addColorStop(0, color + '40');
+ gradient.addColorStop(1, color + '05');
+ chartRef.current = new Chart(ctx, {
+ type: 'line',
+ data: { labels: data.map((_, i) => i), datasets: [{ data, borderColor: color, borderWidth: 1.5, backgroundColor: gradient, fill: true, pointRadius: 0, tension: 0.4 }] },
+ options: { responsive: false, animation: { duration: 800, easing: 'easeOutQuart' }, plugins: { legend: { display: false }, tooltip: { enabled: false } }, scales: { x: { display: false }, y: { display: false } } }
+ });
+ return () => { if (chartRef.current) chartRef.current.destroy(); };
+ }, [data, color]);
+ return <canvas ref={canvasRef} width={width} height={height} style={{borderRadius:4}} />;
+}
+
+// ── FullChart: Modal chart for a single portfolio with period selector ──
+function FullChart({ chartData: initialData, portfolioId, strategy, name, color, emoji, desc, onClose }) {
+ const canvasRef = React.useRef(null);
+ const chartRef = React.useRef(null);
+ const clr = color || '#8b5cf6';
+ const [period, setPeriod] = React.useState('7d');
+ const [liveData, setLiveData] = React.useState(initialData);
+ const periods = ['1d','3d','7d','14d','30d'];
+
+ React.useEffect(() => {
+ if (period === '7d') { setLiveData(initialData); return; }
+ api('/api/portfauxlio/charts?period=' + period).then(d => {
+ const match = (d.portfolios || []).find(p => p.id === portfolioId);
+ if (match) setLiveData(match);
+ }).catch(() => {});
+ }, [period, portfolioId]);
+
+ React.useEffect(() => {
+ const cd = liveData || initialData;
+ const snaps = cd?.snapshots || [];
+ const daily = cd?.daily || [];
+ const dataPoints = snaps.length > 1 ? snaps.map(s => ({ x: new Date(s.time), y: s.nav / 100 }))
+ : daily.length > 1 ? daily.map(d => ({ x: new Date(d.date), y: d.cumulative / 100 })) : [];
+ if (!dataPoints.length || !canvasRef.current) return;
+ if (chartRef.current) chartRef.current.destroy();
+ const ctx = canvasRef.current.getContext('2d');
+ const gradient = ctx.createLinearGradient(0, 0, 0, 300);
+ gradient.addColorStop(0, clr + '30');
+ gradient.addColorStop(1, clr + '02');
+ const zeroLine = { id: 'zeroLine', beforeDraw(chart) {
+ const yScale = chart.scales.y;
+ if (!yScale) return;
+ const y0 = yScale.getPixelForValue(0);
+ if (y0 < yScale.top || y0 > yScale.bottom) return;
+ const cctx = chart.ctx;
+ cctx.save();
+ cctx.strokeStyle = 'rgba(255,255,255,0.15)';
+ cctx.lineWidth = 1;
+ cctx.setLineDash([4, 4]);
+ cctx.beginPath();
+ cctx.moveTo(chart.chartArea.left, y0);
+ cctx.lineTo(chart.chartArea.right, y0);
+ cctx.stroke();
+ cctx.restore();
+ }};
+ chartRef.current = new Chart(ctx, {
+ type: 'line',
+ data: { datasets: [{ label: 'NAV', data: dataPoints, borderColor: clr, borderWidth: 2, backgroundColor: gradient, fill: true, pointRadius: dataPoints.length > 50 ? 0 : 2, pointHoverRadius: 6, pointBackgroundColor: clr, tension: 0.3 }] },
+ plugins: [zeroLine],
+ options: {
+ responsive: true, maintainAspectRatio: false,
+ animation: { duration: 1200, easing: 'easeInOutQuart' },
+ interaction: { intersect: false, mode: 'index' },
+ plugins: {
+ legend: { display: false },
+ tooltip: { backgroundColor: 'rgba(15,15,35,0.95)', borderColor: clr + '60', borderWidth: 1, titleColor: '#e2e8f0', bodyColor: '#e2e8f0', padding: 12, displayColors: false,
+ callbacks: { label: (tipCtx) => 'NAV: ' + (tipCtx.parsed.y >= 0 ? '+' : '') + '$' + tipCtx.parsed.y.toFixed(2) }
+ }
+ },
+ scales: {
+ x: { type: 'time', time: { unit: snaps.length > 1 ? 'hour' : 'day' }, ticks: { color: '#64748b', maxRotation: 45, font: { size: 9 } }, grid: { color: 'rgba(255,255,255,.03)' } },
+ y: { ticks: { color: '#64748b', callback: (v) => '$' + v.toFixed(0), font: { size: 10 } }, grid: { color: 'rgba(255,255,255,.05)' } }
+ }
+ }
+ });
+ return () => { if (chartRef.current) chartRef.current.destroy(); };
+ }, [liveData, strategy, clr]);
+ return (
+ <div className="chart-modal" onClick={onClose}>
+ <div className="chart-modal-content" onClick={e => e.stopPropagation()}>
+ <div className="chart-modal-header">
+ <span style={{fontSize:18}}>{emoji||''}</span>
+ <span style={{fontWeight:800,color:clr}}>{name || strategy}</span>
+ <span style={{fontSize:10,color:'var(--muted)',flex:1}}>{desc||''}</span>
+ <div className="chart-period-btns">
+ {periods.map(p => (
+ <button key={p} className={period === p ? 'chart-period-active' : 'chart-period'} onClick={() => setPeriod(p)}>{p}</button>
+ ))}
+ </div>
+ <button className="chart-close" onClick={onClose}>✕</button>
+ </div>
+ <div style={{height:340,position:'relative'}}><canvas ref={canvasRef} /></div>
+ </div>
+ </div>
+ );
+}
+
+// ── ComparisonChart: Overlay multiple portfolios on one chart ──
+function ComparisonChart({ portfolioIds, allChartData, stratColors, stratNames, stratEmojis, onClose }) {
+ const canvasRef = React.useRef(null);
+ const chartRef = React.useRef(null);
+ const [period, setPeriod] = React.useState('7d');
+ const [compareData, setCompareData] = React.useState(allChartData);
+ const periods = ['1d','3d','7d','14d','30d'];
+
+ React.useEffect(() => {
+ if (period === '7d') { setCompareData(allChartData); return; }
+ api('/api/portfauxlio/charts?period=' + period).then(d => {
+ const byId = {};
+ (d.portfolios || []).forEach(p => { byId[p.id] = p; });
+ setCompareData(byId);
+ }).catch(() => {});
+ }, [period]);
+
+ React.useEffect(() => {
+ if (!canvasRef.current) return;
+ if (chartRef.current) chartRef.current.destroy();
+ const datasets = portfolioIds.map(id => {
+ const cd = compareData[id];
+ if (!cd) return null;
+ const strat = cd.strategy || '';
+ const clr = stratColors[strat] || '#8b5cf6';
+ const snaps = cd.snapshots || [];
+ const daily = cd.daily || [];
+ const pts = snaps.length > 1 ? snaps.map(s => ({ x: new Date(s.time), y: s.nav / 100 }))
+ : daily.length > 1 ? daily.map(d => ({ x: new Date(d.date), y: d.cumulative / 100 })) : [];
+ if (pts.length < 2) return null;
+ return { label: (stratEmojis[strat]||'') + ' ' + (cd.name || strat), data: pts, borderColor: clr, borderWidth: 2, backgroundColor: 'transparent', fill: false, pointRadius: 0, pointHoverRadius: 5, tension: 0.3 };
+ }).filter(Boolean);
+ if (!datasets.length) return;
+ const ctx = canvasRef.current.getContext('2d');
+ chartRef.current = new Chart(ctx, {
+ type: 'line', data: { datasets },
+ options: {
+ responsive: true, maintainAspectRatio: false,
+ animation: { duration: 1000, easing: 'easeOutQuart' },
+ interaction: { intersect: false, mode: 'index' },
+ plugins: {
+ legend: { display: true, position: 'bottom', labels: { color: '#94a3b8', font: { size: 10 }, boxWidth: 12, padding: 8 } },
+ tooltip: { backgroundColor: 'rgba(15,15,35,0.95)', borderWidth: 1, titleColor: '#e2e8f0', bodyColor: '#e2e8f0', padding: 12 }
+ },
+ scales: {
+ x: { type: 'time', ticks: { color: '#64748b', maxRotation: 45, font: { size: 9 } }, grid: { color: 'rgba(255,255,255,.03)' } },
+ y: { ticks: { color: '#64748b', callback: (v) => '$' + v.toFixed(0), font: { size: 10 } }, grid: { color: 'rgba(255,255,255,.05)' } }
+ }
+ }
+ });
+ return () => { if (chartRef.current) chartRef.current.destroy(); };
+ }, [compareData, portfolioIds]);
+
+ return (
+ <div className="chart-modal" onClick={onClose}>
+ <div className="chart-modal-content" onClick={e => e.stopPropagation()} style={{maxWidth:1100}}>
+ <div className="chart-modal-header">
+ <span style={{fontSize:16}}>📊</span>
+ <span style={{fontWeight:800,color:'var(--cyan)'}}>Compare {portfolioIds.length} Portfolios</span>
+ <div className="chart-period-btns" style={{marginLeft:'auto'}}>
+ {periods.map(p => (
+ <button key={p} className={period === p ? 'chart-period-active' : 'chart-period'} onClick={() => setPeriod(p)}>{p}</button>
+ ))}
+ </div>
+ <button className="chart-close" onClick={onClose}>✕</button>
+ </div>
+ <div style={{height:400,position:'relative'}}><canvas ref={canvasRef} /></div>
+ </div>
+ </div>
+ );
+}
+
+// ── Vertical Bar Chart ──
+function BarChart({ data, maxVal, height = 80, color = '#8b5cf6' }) {
+ if (!data || data.length === 0) return null;
+ const mx = maxVal || Math.max(...data.map(d => d.value)) || 1;
+ return (
+ <div className="mkt-bar-chart" style={{ height }}>
+ {data.map((d, i) => (
+ <div key={i} className="mkt-bar" style={{ height: Math.max(2, (d.value / mx) * height) + 'px', background: d.color || color, opacity: 0.7 + (d.value / mx) * 0.3 }}>
+ <div className="mkt-bar-label">{d.label}: {d.value}</div>
+ </div>
+ ))}
+ </div>
+ );
+}
+
+// ── Confidence Histogram ──
+function ConfHistogram({ data }) {
+ if (!data || data.length === 0) return null;
+ const max = Math.max(...data.map(d => d.count)) || 1;
+ const colors = ['#ef4444','#f97316','#f59e0b','#eab308','#84cc16','#22c55e','#14b8a6','#06b6d4','#3b82f6','#8b5cf6'];
+ return (
+ <div className="histogram">
+ {data.map((d, i) => (
+ <div key={i} className="hist-bar" style={{
+ height: Math.max(2, (d.count / max) * 70) + 'px',
+ background: colors[i] || 'var(--muted)',
+ opacity: d.count > 0 ? 0.8 : 0.2,
+ }}>
+ <div className="hist-label">{d.range}</div>
+ </div>
+ ))}
+ </div>
+ );
+}
+
+// ── Time ago helper ──
+function timeAgo(ts) {
+ if (!ts) return '';
+ const diff = Date.now() - new Date(ts).getTime();
+ if (diff < 60000) return Math.floor(diff / 1000) + 's ago';
+ if (diff < 3600000) return Math.floor(diff / 60000) + 'm ago';
+ if (diff < 86400000) return Math.floor(diff / 3600000) + 'h ago';
+ return Math.floor(diff / 86400000) + 'd ago';
+}
+
+// ── Market Data Tab — Bloomberg-style terminal ──
+function MarketDataTab() {
+ const [mkt, setMkt] = useState(null);
+ const [tick, setTick] = useState(0);
+
+ useEffect(() => {
+ const load = () => api('/api/inc/market-data').then(setMkt).catch(e => console.error(e));
+ load();
+ const iv = setInterval(load, 8000);
+ return () => clearInterval(iv);
+ }, []);
+ useEffect(() => { const iv = setInterval(() => setTick(t => t + 1), 1000); return () => clearInterval(iv); }, []);
+
+ if (!mkt) return <div style={{textAlign:'center',padding:60,color:'var(--muted)'}}>
+ <div style={{fontSize:24,marginBottom:8,animation:'avatarFloat 2s ease-in-out infinite'}}>Loading market data...</div>
+ </div>;
+
+ const signalVals = (mkt.signalTrend || []).map(s => s.signals);
+ const edgeVals = (mkt.signalTrend || []).map(s => s.avgEdge * 100);
+ const sentVals = (mkt.sentimentTrend || []).map(s => s.articles);
+ const sentScoreVals = (mkt.sentimentTrend || []).map(s => s.avgSentiment);
+ const totalSent24h = sentVals.reduce((a, b) => a + b, 0);
+ const totalSignals = signalVals.reduce((a, b) => a + b, 0);
+ const at = mkt.approvalTrend || {};
+ const changeArrow = at.change > 0 ? '▲' : at.change < 0 ? '▼' : '—';
+ const changeClass = at.change > 0 ? 'up' : at.change < 0 ? 'down' : 'flat';
+ const totalPnl = (mkt.portfolios || []).reduce((s, p) => s + (p.pnl_cents || 0), 0);
+ const totalTrades = (mkt.portfolios || []).reduce((s, p) => s + (p.total_trades || 0), 0);
+ const avgEdge = edgeVals.length > 0 ? (edgeVals.reduce((a,b)=>a+b,0) / edgeVals.length) : 0;
+
+ // Ticker items
+ const tickerItems = [
+ { label: 'P&L', value: (totalPnl >= 0 ? '+' : '') + (totalPnl / 100).toFixed(2), color: totalPnl >= 0 ? 'var(--green)' : 'var(--red)' },
+ { label: 'SIGNALS', value: totalSignals, color: 'var(--blue)' },
+ { label: 'APPROVAL', value: at.current + '%', change: at.change, color: 'var(--green)' },
+ { label: 'SENTIMENT', value: totalSent24h.toLocaleString(), color: 'var(--pink)' },
+ { label: 'AVG EDGE', value: avgEdge.toFixed(1) + '%', color: 'var(--purple)' },
+ { label: 'TRADES', value: totalTrades, color: 'var(--yellow)' },
+ { label: 'MARKETS', value: mkt.activeMarkets, color: 'var(--cyan)' },
+ { label: 'GEMINI', value: mkt.gemini.callsToday + '/' + mkt.gemini.dailyLimit, color: 'var(--teal)' },
+ ];
+ const doubledTicker = tickerItems.concat(tickerItems);
+
+ const stratColors = {aggressive:'#ef4444',conservative:'#3b82f6',weather:'#06b6d4',momentum:'#f59e0b',contrarian:'#8b5cf6',ai_enhanced:'#ec4899',mc_validated:'#a855f7',scalper:'#eab308',patient:'#22c55e',random:'#64748b',penny_pincher:'#94a3b8',spray_pray:'#fb923c',nickel_slots:'#a78bfa',degen_lite:'#f43f5e',politics_junkie:'#0ea5e9',double_down:'#dc2626',volatility_rider:'#14b8a6',whale:'#1d4ed8',yolo:'#e11d48',full_send:'#b91c1c',kelly_criterion:'#059669',sharpe_sniper:'#7c3aed',bayesian_blend:'#0891b2',ensemble_lock:'#c026d3',mean_revert:'#d97706',info_ratio:'#2563eb',anti_fomo:'#16a34a',nightcrawler:'#4c1d95',heatseeker:'#ea580c',quant_core:'#0d9488',etf_presidential:'#dc143c',etf_cabinet:'#ff6347',etf_congress:'#4169e1',etf_scotus:'#2f4f4f',etf_fed:'#228b22',etf_economy:'#daa520',etf_geopolitics:'#8b0000',etf_territory:'#006400',etf_climate:'#00bfff',etf_energy:'#ff8c00',etf_tech:'#7b68ee',etf_space:'#191970',etf_crypto:'#ffd700',etf_sports:'#32cd32',etf_entertainment:'#ff1493',etf_legal:'#708090',etf_financials:'#4682b4',etf_govreform:'#b22222',etf_global_social:'#9370db',etf_broad_market:'#c0a050'};
+ const stratEmojis = {aggressive:'🔥',conservative:'🏛️',weather:'⛈️',momentum:'🚀',contrarian:'🔄',ai_enhanced:'🧠',mc_validated:'🎲',scalper:'⚡',patient:'🐢',random:'🎰',penny_pincher:'🪙',spray_pray:'💦',nickel_slots:'🎰',degen_lite:'😈',politics_junkie:'🏛️',double_down:'⬆️',volatility_rider:'🏄',whale:'🐳',yolo:'🧨',full_send:'💣',kelly_criterion:'🎰',sharpe_sniper:'🎯',bayesian_blend:'🧮',ensemble_lock:'🔐',mean_revert:'↩️',info_ratio:'📊',anti_fomo:'🧘',nightcrawler:'🦇',heatseeker:'🔬',quant_core:'∑',etf_presidential:'🏛️',etf_cabinet:'💼',etf_congress:'🗳️',etf_scotus:'⚖️',etf_fed:'🏦',etf_economy:'📈',etf_geopolitics:'🌍',etf_territory:'🗺️',etf_climate:'🌡️',etf_energy:'⛽',etf_tech:'🤖',etf_space:'🚀',etf_crypto:'₿',etf_sports:'⚽',etf_entertainment:'🎬',etf_legal:'🔨',etf_financials:'💹',etf_govreform:'✂️',etf_global_social:'⛪',etf_broad_market:'🌐'};
+
+ return (<div>
+ {/* ═══ Hero P&L Banner ═══ */}
+ <div style={{textAlign:'center',padding:'20px 0 8px',borderBottom:'1px solid var(--border)'}}>
+ <div style={{fontSize:10,color:'var(--muted)',textTransform:'uppercase',letterSpacing:2,marginBottom:4}}>Total Portfolio P&L</div>
+ <div className="pnl-hero" style={{color: totalPnl >= 0 ? 'var(--green)' : 'var(--red)', animation: totalPnl !== 0 ? 'pnlPulse 3s ease-in-out infinite' : 'none'}}>
+ {totalPnl >= 0 ? '+' : ''}{(totalPnl / 100).toFixed(2)}
+ </div>
+ <div style={{display:'flex',justifyContent:'center',gap:24,marginTop:8,fontSize:11,color:'var(--muted)'}}>
+ <span>{totalTrades} trades</span>
+ <span>{(mkt.portfolios||[]).filter(p => p.pnl_cents > 0).length} winning</span>
+ <span>{(mkt.portfolios||[]).filter(p => p.pnl_cents < 0).length} losing</span>
+ <span>{avgEdge.toFixed(1)}% avg edge</span>
+ </div>
+ </div>
+
+ {/* ═══ Scrolling Ticker ═══ */}
+ <div className="mkt-ticker-strip">
+ <div className="mkt-ticker-track">
+ {doubledTicker.map((t, i) => (
+ <div key={i} className="mkt-ticker-item">
+ <span style={{color:'var(--muted)',fontSize:9,textTransform:'uppercase',letterSpacing:.5}}>{t.label}</span>
+ <span style={{color:t.color,fontWeight:800}}>{t.value}</span>
+ {t.change !== undefined && <span className={'mkt-change ' + (t.change > 0 ? 'up' : t.change < 0 ? 'down' : 'flat')}>
+ {t.change > 0 ? '▲' : t.change < 0 ? '▼' : ''}{Math.abs(t.change)}%
+ </span>}
+ </div>
+ ))}
+ </div>
+ </div>
+
+ <div className="mkt-grid">
+ {/* ═══ Live Signal Feed ═══ */}
+ <div className="mkt-card" style={{gridColumn:'span 2'}}>
+ <div className="mkt-card-header">
+ <span className="mkt-card-title" style={{color:'var(--blue)'}}>
+ <span style={{display:'inline-block',width:6,height:6,borderRadius:'50%',background:'var(--green)',marginRight:6,animation:'statusPulse 2s ease infinite'}}></span>
+ Live Signal Feed
+ </span>
+ <span className="mkt-card-badge" style={{background:'rgba(59,130,246,.15)',color:'var(--blue)'}}>{(mkt.latestSignals||[]).length} latest</span>
+ </div>
+ <div className="signal-feed">
+ {(mkt.latestSignals || []).map((sig, i) => (
+ <div key={i} className="signal-row">
+ <div className="signal-approved" style={{background: sig.approved ? 'var(--green)' : 'var(--red)'}} title={sig.approved ? 'Approved' : 'Rejected'} />
+ <span className={'signal-dir ' + sig.direction}>{sig.direction}</span>
+ <span className="signal-market" title={sig.market}>{sig.market}</span>
+ <span className="signal-edge" style={{color: sig.edge > 0 ? 'var(--green)' : 'var(--red)'}}>
+ {sig.edge > 0 ? '+' : ''}{(sig.edge * 100).toFixed(1)}%
+ </span>
+ <span className="signal-conf" title="Confidence">{(sig.confidence * 100).toFixed(0)}%</span>
+ <span className="signal-time">{timeAgo(sig.time)}</span>
+ </div>
+ ))}
+ {(!mkt.latestSignals || mkt.latestSignals.length === 0) && <div style={{padding:20,textAlign:'center',color:'var(--muted)',fontSize:12}}>No recent signals</div>}
+ </div>
+ </div>
+
+ {/* ═══ Signal Volume Sparkline ═══ */}
+ <div className="mkt-card">
+ <div className="mkt-card-header">
+ <span className="mkt-card-title" style={{color:'var(--blue)'}}>Signal Volume</span>
+ <span className="mkt-card-badge" style={{background:'rgba(59,130,246,.15)',color:'var(--blue)'}}>{totalSignals}</span>
+ </div>
+ <Sparkline data={signalVals} width={300} height={50} color="#3b82f6" showDots={true} label={true} />
+ <BarChart data={(mkt.signalTrend || []).map((s) => ({
+ value: s.signals,
+ label: new Date(s.hour).toLocaleTimeString('en-US', {hour:'numeric',hour12:true}),
+ color: s.approved > s.signals * 0.5 ? 'rgba(34,197,94,.6)' : 'rgba(239,68,68,.4)',
+ }))} height={45} />
+ </div>
+
+ {/* ═══ Sentiment Flow ═══ */}
+ <div className="mkt-card">
+ <div className="mkt-card-header">
+ <span className="mkt-card-title" style={{color:'var(--pink)'}}>Sentiment Flow</span>
+ <span className="mkt-card-badge" style={{background:'rgba(236,72,153,.15)',color:'var(--pink)'}}>{totalSent24h.toLocaleString()}</span>
+ </div>
+ <Sparkline data={sentVals} width={300} height={50} color="#ec4899" label={true} />
+ <div style={{display:'flex',justifyContent:'space-between',marginTop:8,fontSize:10,color:'var(--muted)'}}>
+ <span>Avg: <strong style={{color: sentScoreVals.length > 0 && sentScoreVals.reduce((a,b)=>a+b,0)/sentScoreVals.length > 0 ? 'var(--green)' : 'var(--red)'}}>
+ {sentScoreVals.length > 0 ? (sentScoreVals.reduce((a,b)=>a+b,0)/sentScoreVals.length).toFixed(3) : '—'}
+ </strong></span>
+ <span>{(mkt.sourceMix||[]).length} sources</span>
+ </div>
+ </div>
+
+ {/* ═══ Approval Rate ═══ */}
+ <div className="mkt-card">
+ <div className="mkt-card-header">
+ <span className="mkt-card-title" style={{color:'var(--green)'}}>Approval Rate</span>
+ <span className={'mkt-change ' + changeClass} style={{fontSize:14}}>{changeArrow} {Math.abs(at.change)}%</span>
+ </div>
+ <div style={{display:'flex',alignItems:'baseline',gap:12,marginBottom:8}}>
+ <span style={{fontSize:42,fontWeight:800,color:'var(--green)',fontVariantNumeric:'tabular-nums'}}>{at.current}%</span>
+ <span style={{fontSize:12,color:'var(--muted)'}}>vs {at.prior}% prior</span>
+ </div>
+ <div className="mkt-gauge">
+ <div className="mkt-gauge-fill" style={{width: at.current + '%', background:'linear-gradient(90deg,var(--green),var(--teal))'}} />
+ <div className="mkt-gauge-label">{at.recentSignals} signals</div>
+ </div>
+ </div>
+
+ {/* ═══ Edge Trend ═══ */}
+ <div className="mkt-card">
+ <div className="mkt-card-header">
+ <span className="mkt-card-title" style={{color:'var(--purple)'}}>Edge Trend</span>
+ <span className="mkt-card-badge" style={{background:'rgba(139,92,246,.15)',color:'var(--purple)'}}>
+ {avgEdge.toFixed(1)}% avg
+ </span>
+ </div>
+ <Sparkline data={edgeVals} width={300} height={50} color="#8b5cf6" showDots={true} label={true} />
+ </div>
+
+ {/* ═══ Market Heatmap ═══ */}
+ {(mkt.marketStats || []).length > 0 && <div className="mkt-card" style={{gridColumn:'span 2'}}>
+ <div className="mkt-card-header">
+ <span className="mkt-card-title" style={{color:'var(--yellow)'}}>Market Heatmap (24h)</span>
+ <span className="mkt-card-badge" style={{background:'rgba(245,158,11,.15)',color:'var(--yellow)'}}>{(mkt.marketStats||[]).length} markets</span>
+ </div>
+ <div className="heatmap-grid">
+ {(mkt.marketStats || []).map((m, i) => {
+ const edge = m.avgEdge * 100;
+ const intensity = Math.min(1, Math.abs(edge) / 25);
+ const bg = edge >= 0
+ ? 'rgba(34,197,94,' + (0.08 + intensity * 0.2) + ')'
+ : 'rgba(239,68,68,' + (0.08 + intensity * 0.2) + ')';
+ const borderC = edge >= 0 ? 'rgba(34,197,94,' + (0.2 + intensity * 0.3) + ')' : 'rgba(239,68,68,' + (0.2 + intensity * 0.3) + ')';
+ return (<div key={i} className="heatmap-cell" style={{background: bg, borderColor: borderC}}>
+ <div className="heatmap-market">{m.market}</div>
+ <div className="heatmap-edge" style={{color: edge >= 0 ? 'var(--green)' : 'var(--red)'}}>
+ {edge >= 0 ? '+' : ''}{edge.toFixed(1)}%
+ </div>
+ <div className="heatmap-meta">{m.signals} sig | {m.approved} appr | {(m.avgConf * 100).toFixed(0)}% conf</div>
+ </div>);
+ })}
+ </div>
+ </div>}
+
+ {/* ═══ Confidence Distribution ═══ */}
+ {(mkt.confDistribution || []).length > 0 && <div className="mkt-card">
+ <div className="mkt-card-header">
+ <span className="mkt-card-title" style={{color:'var(--cyan)'}}>Confidence Distribution</span>
+ </div>
+ <ConfHistogram data={mkt.confDistribution} />
+ <div style={{marginTop:18,display:'flex',justifyContent:'space-between',fontSize:9,color:'var(--muted)'}}>
+ <span>Low conf</span><span>High conf</span>
+ </div>
+ </div>}
+
+ {/* ═══ Intelligence Sources ═══ */}
+ <div className="mkt-card">
+ <div className="mkt-card-header">
+ <span className="mkt-card-title" style={{color:'var(--cyan)'}}>Intelligence Sources</span>
+ <span className="mkt-card-badge" style={{background:'rgba(6,182,212,.15)',color:'var(--cyan)'}}>{(mkt.sourceMix||[]).length}</span>
+ </div>
+ <div className="mkt-source-list">
+ {(mkt.sourceMix || []).slice(0, 12).map((s, i) => {
+ const maxC = (mkt.sourceMix || [])[0]?.count || 1;
+ const colors = ['#3b82f6','#8b5cf6','#ec4899','#ef4444','#f59e0b','#22c55e','#06b6d4','#14b8a6','#6366f1','#d946ef','#f97316','#a855f7'];
+ return (<div key={i} className="mkt-source-row">
+ <span className="mkt-source-name">{s.source}</span>
+ <div style={{flex:1,display:'flex',alignItems:'center',gap:4}}>
+ <div className="mkt-source-bar" style={{width: (s.count / maxC * 100) + '%', background: colors[i % colors.length]}} />
+ </div>
+ <span className="mkt-source-val">{s.count.toLocaleString()}</span>
+ <span style={{fontSize:9,color: s.avgSentiment > 0 ? 'var(--green)' : s.avgSentiment < 0 ? 'var(--red)' : 'var(--muted)', minWidth:35, textAlign:'right'}}>
+ {s.avgSentiment > 0 ? '+' : ''}{s.avgSentiment.toFixed(2)}
+ </span>
+ </div>);
+ })}
+ </div>
+ </div>
+
+ {/* ═══ Gemini + Categories row ═══ */}
+ <div className="mkt-card">
+ <div className="mkt-card-header">
+ <span className="mkt-card-title" style={{color:'var(--teal)'}}>Gemini AI</span>
+ <span className="mkt-card-badge" style={{background: mkt.gemini.pctUsed > 80 ? 'rgba(239,68,68,.15)' : 'rgba(20,184,166,.15)', color: mkt.gemini.pctUsed > 80 ? 'var(--red)' : 'var(--teal)'}}>
+ {mkt.gemini.pctUsed}%
+ </span>
+ </div>
+ <div style={{display:'flex',alignItems:'baseline',gap:8,marginBottom:8}}>
+ <span style={{fontSize:32,fontWeight:800,color:'var(--teal)',fontVariantNumeric:'tabular-nums'}}>{mkt.gemini.callsToday}</span>
+ <span style={{fontSize:11,color:'var(--muted)'}}>/ {mkt.gemini.dailyLimit}</span>
+ </div>
+ <div className="mkt-gauge">
+ <div className="mkt-gauge-fill" style={{width: mkt.gemini.pctUsed + '%', background: mkt.gemini.pctUsed > 80 ? 'linear-gradient(90deg,var(--yellow),var(--red))' : 'linear-gradient(90deg,var(--teal),var(--cyan))'}} />
+ <div className="mkt-gauge-label">{mkt.gemini.pctUsed}%</div>
+ </div>
+ {/* Categories inline */}
+ <div style={{marginTop:14,display:'flex',flexWrap:'wrap',gap:4}}>
+ {(mkt.categories || []).slice(0, 8).map((c, i) => {
+ const colors = ['#f59e0b','#3b82f6','#ec4899','#22c55e','#8b5cf6','#ef4444','#06b6d4','#14b8a6'];
+ return (<div key={i} style={{padding:'3px 10px',borderRadius:6,background:'rgba(255,255,255,.03)',border:'1px solid var(--border)',fontSize:9,display:'flex',alignItems:'center',gap:4}}>
+ <div style={{width:4,height:4,borderRadius:'50%',background:colors[i % colors.length]}} />
+ <span style={{fontWeight:600}}>{c.category}</span>
+ <span style={{color:'var(--muted)'}}>{c.count}</span>
+ </div>);
+ })}
+ </div>
+ </div>
+
+ {/* ═══ Recent Trades ═══ */}
+ {(mkt.recentTrades || []).length > 0 && <div className="mkt-card" style={{gridColumn:'span 2'}}>
+ <div className="mkt-card-header">
+ <span className="mkt-card-title" style={{color:'var(--yellow)'}}>Recent Trades</span>
+ <span className="mkt-card-badge" style={{background:'rgba(245,158,11,.15)',color:'var(--yellow)'}}>{totalTrades} total</span>
+ </div>
+ <div className="trade-log">
+ {(mkt.recentTrades || []).map((t, i) => {
+ const c = stratColors[t.strategy] || 'var(--muted)';
+ return (<div key={i} className="trade-row">
+ <span className="trade-portfolio" style={{color:c}}>{t.portfolio_name}</span>
+ <span className={'signal-dir ' + t.direction} style={{fontSize:9}}>{t.direction}</span>
+ <span style={{flex:1,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap',color:'var(--muted)'}}>{t.market_id}</span>
+ <span style={{fontSize:10,color:'var(--muted)'}}>{t.contracts}x @ {t.entry_price_cents}¢</span>
+ <span className="trade-pnl" style={{color: t.pnl_cents >= 0 ? 'var(--green)' : 'var(--red)'}}>
+ {t.pnl_cents >= 0 ? '+' : ''}{(t.pnl_cents / 100).toFixed(2)}
+ </span>
+ <span className="signal-time">{timeAgo(t.created_at)}</span>
+ </div>);
+ })}
+ </div>
+ </div>}
+
+ {/* ═══ Portfolio Leaderboard ═══ */}
+ {(mkt.portfolios || []).length > 0 && <div className="mkt-card" style={{gridColumn:'span 2'}}>
+ <div className="mkt-card-header">
+ <span className="mkt-card-title" style={{color:'var(--pink)'}}>Portfolio Leaderboard</span>
+ <span className="mkt-card-badge" style={{background:'rgba(255,105,180,.15)',color:'var(--pink)'}}>{totalTrades} trades</span>
+ </div>
+ <div style={{display:'grid',gridTemplateColumns:'repeat(auto-fill,minmax(220px,1fr))',gap:8}}>
+ {(mkt.portfolios || []).map((p, i) => {
+ const c = stratColors[p.strategy] || 'var(--muted)';
+ const emoji = stratEmojis[p.strategy] || '';
+ const pnl = p.pnl_cents || 0;
+ const invested = p.total_invested_cents || 0;
+ const roi = invested > 0 ? ((pnl / invested) * 100).toFixed(1) : '0.0';
+ return (<div key={i} style={{padding:'12px 14px',background:'rgba(255,255,255,.02)',border:'1px solid var(--border)',borderRadius:10,transition:'all .3s',borderLeftColor:c,borderLeftWidth:3,position:'relative',overflow:'hidden'}}>
+ {/* Rank badge */}
+ <div style={{position:'absolute',top:6,right:8,fontSize:8,color:'var(--muted)',fontWeight:800}}>#{i+1}</div>
+ <div style={{display:'flex',alignItems:'center',gap:8,marginBottom:6}}>
+ <span style={{fontSize:20}}>{emoji}</span>
+ <div style={{flex:1}}>
+ <div style={{fontSize:13,fontWeight:700,color:c}}>{p.name}</div>
+ <div style={{fontSize:9,color:'var(--muted)',textTransform:'uppercase',letterSpacing:.3}}>{p.strategy}</div>
+ </div>
+ <div style={{textAlign:'right'}}>
+ <div style={{fontSize:18,fontWeight:900,color: pnl >= 0 ? 'var(--green)' : 'var(--red)',fontVariantNumeric:'tabular-nums'}}>
+ {pnl >= 0 ? '+' : ''}{(pnl / 100).toFixed(2)}
+ </div>
+ <div style={{fontSize:9,color:'var(--muted)'}}>ROI: {roi}%</div>
+ </div>
+ </div>
+ <div style={{display:'flex',gap:4,fontSize:9,flexWrap:'wrap'}}>
+ <span style={{padding:'2px 7px',borderRadius:4,background:'rgba(34,197,94,.1)',color:'var(--green)'}}>W:{p.trades_won}</span>
+ <span style={{padding:'2px 7px',borderRadius:4,background:'rgba(239,68,68,.1)',color:'var(--red)'}}>L:{p.trades_lost}</span>
+ <span style={{padding:'2px 7px',borderRadius:4,background:'rgba(255,255,255,.04)',color:'var(--muted)'}}>WR:{p.win_rate}%</span>
+ <span style={{padding:'2px 7px',borderRadius:4,background:'rgba(255,255,255,.04)',color:'var(--muted)'}}>{p.total_trades} trades</span>
+ {p.streak !== 0 && <span style={{padding:'2px 7px',borderRadius:4,background: p.streak > 0 ? 'rgba(34,197,94,.1)' : 'rgba(239,68,68,.1)',color: p.streak > 0 ? 'var(--green)' : 'var(--red)'}}>{p.streak > 0 ? '+' : ''}{p.streak} streak</span>}
+ </div>
+ {invested > 0 && <div style={{marginTop:6}}>
+ <div style={{height:3,borderRadius:2,background:'rgba(255,255,255,.05)',overflow:'hidden'}}>
+ <div style={{height:'100%',borderRadius:2,width: Math.min(100, Math.abs(parseFloat(roi))) + '%',background: pnl >= 0 ? 'var(--green)' : 'var(--red)',transition:'width .5s'}} />
+ </div>
+ </div>}
+ </div>);
+ })}
+ </div>
+ </div>}
+ </div>
+ </div>);
+}
+
+function App() {
+ const [data, setData] = useState(null);
+ const [expandedAgent, setExpandedAgent] = useState(null);
+ const [tab, setTab] = useState('command');
+ const [loading, setLoading] = useState(true);
+
+ useEffect(() => {
+ const load = async () => {
+ try {
+ const d = await api('/api/inc');
+ setData(d);
+ setLoading(false);
+ } catch(e) { console.error(e); setLoading(false); }
+ };
+ load();
+ const iv = setInterval(load, 15000);
+ return () => clearInterval(iv);
+ }, []);
+
+ if (loading || !data) return (
+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: '100vh', flexDirection: 'column', gap: 16 }}>
+ <div style={{ width: 60, height: 60, borderRadius: '50%', background: 'linear-gradient(135deg,#ff69b4,#8b5cf6)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 28, animation: 'avatarFloat 2s ease-in-out infinite' }}>K</div>
+ <div style={{ color: 'var(--muted)', fontSize: 14, letterSpacing: 2 }}>INITIALIZING KEN INC...</div>
+ </div>
+ );
+
+ const d = data;
+ const approvalRate = d.pipeline.signalsLast24h > 0
+ ? Math.round(d.pipeline.approvedLast24h / d.pipeline.signalsLast24h * 100) : 0;
+
+ const tabStyle = (t) => ({
+ padding: '10px 24px', fontSize: 13, fontWeight: 600, border: '1px solid ' + (tab===t?'rgba(255,255,255,.2)':'var(--border)'),
+ borderRadius: 10, background: tab===t?'rgba(255,255,255,.08)':'transparent', color: tab===t?'var(--text)':'var(--muted)',
+ cursor: 'pointer', transition: 'all .2s', letterSpacing: .3,
+ });
+
+ return (
+ <div className="container">
+ <Particles />
+ <Clock />
+
+ <div className="header">
+ <div className="header-glow" />
+ <div className="ceo-avatar">K</div>
+ <div className="ceo-name">Ken</div>
+ <div className="ceo-title">Chief Executive Officer</div>
+ <div className="ceo-tagline">Trading Intelligence Corporation</div>
+ </div>
+
+ <div style={{display:'flex',justifyContent:'center',gap:8,marginBottom:24,flexWrap:'wrap'}}>
+ <button style={tabStyle('command')} onClick={()=>setTab('command')}>Command Center</button>
+ <button style={tabStyle('market')} onClick={()=>setTab('market')}>Market Data</button>
+ <button style={tabStyle('portfolios')} onClick={()=>setTab('portfolios')}>portFAUXlio</button>
+ <button style={tabStyle('predictions')} onClick={()=>setTab('predictions')}>Predictions</button>
+ <button style={tabStyle('signals')} onClick={()=>setTab('signals')}>Live Signals</button>
+ </div>
+
+ {tab === 'command' && <>
+ <div className="stats-bar">
+ <div className="stat-item"><div className="stat-val" style={{color:'var(--pink)'}}>{d.agents.length}</div><div className="stat-label">Sub-Agents</div></div>
+ <div className="stat-item"><div className="stat-val" style={{color:'var(--blue)'}}>{d.pipeline.signalsLast24h}</div><div className="stat-label">Signals / 24h</div></div>
+ <div className="stat-item"><div className="stat-val" style={{color:'var(--green)'}}>{approvalRate}%</div><div className="stat-label">Approval Rate</div></div>
+ <div className="stat-item"><div className="stat-val" style={{color:'var(--purple)'}}>{d.pipeline.lastHour}</div><div className="stat-label">Last Hour</div></div>
+ <div className="stat-item"><div className="stat-val" style={{color:'var(--cyan)'}}>{(parseFloat(d.pipeline.avgEdge)*100).toFixed(1)}%</div><div className="stat-label">Avg Edge</div></div>
+ <div className="stat-item"><div className="stat-val" style={{color:'var(--yellow)'}}>{d.system.memory_mb}MB</div><div className="stat-label">Memory</div></div>
+ <div className="stat-item"><div className="stat-val">{d.system.cpuCores}</div><div className="stat-label">CPU Cores</div></div>
+ </div>
+ <div className="network">
+ <div className="agents-grid">
+ {d.agents.map(a => (
+ <AgentCard key={a.id} agent={a} expanded={expandedAgent===a.id} onToggle={()=>setExpandedAgent(expandedAgent===a.id?null:a.id)} />
+ ))}
+ </div>
+ </div>
+ </>}
+
+ {tab === 'market' && <MarketDataTab />}
+ {tab === 'portfolios' && <PortfoliosTab />}
+ {tab === 'predictions' && <PredictionsTab />}
+
+ {tab === 'signals' && <div className="signal-feed">
+ <h2><span className="live-dot" /> Live Signal Feed</h2>
+ <SignalFeed signals={d.recentSignals} />
+ </div>}
+
+ <div className="footer">
+ Ken Inc. Trading Intelligence • {d.system.cpuCores} cores • {d.system.uptime_hours}h uptime • 50 paper portfolios •
+ <a href="/"> Back to Dashboard</a>
+ </div>
+ </div>
+ );
+}
+
+ReactDOM.createRoot(document.getElementById('root')).render(<App />);
+</script>
+</body>
+</html>`;
+
+// ════════════════════════════════════════
+// HTTP SERVER
+// ════════════════════════════════════════
+
+const server = http.createServer(async (req, res) => {
+ // CORS preflight
+ if (req.method === 'OPTIONS') {
+ res.writeHead(200, {
+ 'Access-Control-Allow-Origin': '*',
+ 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
+ 'Access-Control-Allow-Headers': 'Content-Type, Authorization',
+ });
+ res.end();
+ return;
+ }
+
+ // Route key for matching
+ const urlPath = req.url.split('?')[0];
+ const routeKey = `${req.method} ${urlPath}`;
+
+ // Public endpoints (no auth required)
+ const publicPaths = [
+ '/api/auth/login',
+ '/api/auth/logout',
+ '/api/auth/session',
+ '/api/auth/google',
+ '/api/auth/google-config',
+ '/api/health',
+ '/api/portfauxlio',
+ '/api/portfauxlio/charts',
+ '/api/portfauxlio/swot',
+ '/api/markets',
+ '/api/signals',
+ '/api/energy-arb',
+ '/api/predictions',
+ '/api/portfolios',
+ '/api/scan-config',
+ '/api/dashboard',
+ ];
+ const isPublic = publicPaths.includes(urlPath);
+
+ // Enforce auth on all other API routes
+ if (!isPublic && urlPath.startsWith('/api/') && !isAuthenticated(req)) {
+ return json(res, { error: 'Authentication required' }, 401);
+ }
+
+ // Check route handlers
+ if (routes[routeKey]) {
+ try {
+ await routes[routeKey](req, res);
+ } catch (err) {
+ console.error(`[ERROR] ${routeKey}:`, err.message);
+ json(res, { error: err.message }, 500);
+ }
+ return;
+ }
+
+ // Unknown API route
+ if (urlPath.startsWith('/api/')) {
+ return json(res, { error: `Unknown API endpoint: ${req.method} ${urlPath}` }, 404);
+ }
+
+ // ── Ken Inc. Command Center ──
+ if (urlPath === '/inc' || urlPath === '/inc/') {
+ res.writeHead(200, { 'Content-Type': 'text/html', 'Cache-Control': 'no-cache' });
+ res.end(KEN_INC_HTML);
+ return;
+ }
+
+ // ── Tournament Arena — 3D Team Competition ──
+ if (urlPath === '/arena' || urlPath === '/arena/') {
+ res.writeHead(200, { 'Content-Type': 'text/html', 'Cache-Control': 'no-cache' });
+ res.end(ARENA_HTML);
+ return;
+ }
+
+ // ── PortFAUXlios Dashboard ──
+ if (urlPath === '/portfauxlios' || urlPath === '/portfauxlios/') {
+ try {
+ const dashHtml = fs.readFileSync('/root/DW-Agents/ken-portfauxlios-dashboard.html', 'utf8');
+ res.writeHead(200, { 'Content-Type': 'text/html', 'Cache-Control': 'no-cache' });
+ res.end(dashHtml);
+ } catch (e) {
+ res.writeHead(500);
+ res.end('Dashboard not found: ' + e.message);
+ }
+ return;
+ }
+
+ // ── Serve Static Files / SPA Routing ──
+ let filePath = path.join(DIST, urlPath === '/' ? 'index.html' : urlPath);
+
+ // Security: prevent directory traversal
+ if (!filePath.startsWith(DIST)) {
+ res.writeHead(403);
+ res.end('Forbidden');
+ return;
+ }
+
+ // Check if file exists; if not, serve index.html for SPA routing
+ if (!fs.existsSync(filePath) || fs.statSync(filePath).isDirectory()) {
+ filePath = path.join(DIST, 'index.html');
+ }
+
+ try {
+ const content = fs.readFileSync(filePath);
+ const ext = path.extname(filePath);
+ const contentType = MIME[ext] || 'application/octet-stream';
+
+ // Cache static assets (hashed filenames from Vite)
+ const cacheHeader = ext === '.html'
+ ? 'no-cache, no-store, must-revalidate'
+ : 'public, max-age=31536000, immutable';
+
+ res.writeHead(200, {
+ 'Content-Type': contentType,
+ 'Cache-Control': cacheHeader,
+ });
+ res.end(content);
+ } catch {
+ res.writeHead(404);
+ res.end('Not found');
+ }
+});
+
+// ══════════════════════════════════════════════════════════════
+// KEN AUTONOMOUS TRADING BRAIN — 24/7 MARKET INTELLIGENCE
+// Scans every 15 min: Kalshi markets, Reddit, news, Polymarket
+// Stores everything in PostgreSQL, tracks own performance
+// ══════════════════════════════════════════════════════════════
+
+const KEN_DB = 'postgresql://dw_admin:DW2024SecurePass@127.0.0.1:5432/dw_unified';
+const kenPool = new pg.Pool({ connectionString: KEN_DB, max: 20, idleTimeoutMillis: 30000 });
+async function kenQ(text, params) { return kenPool.query(text, params); }
+
+// ── Mutable scan/pipeline intervals (adjustable via Settings UI) ──
+let SCAN_INTERVAL_MS = 8 * 60 * 1000; // 8 minutes — market scans
+let REDDIT_INTERVAL_MS = 15 * 60 * 1000; // 15 minutes — intelligence sweep
+let SIGNAL_PIPELINE_MS = 2 * 60 * 1000; // 2 minutes — signal pipeline
+let RESOLVE_INTERVAL_MS = 5 * 60 * 1000; // 5 minutes — trade resolution
+const SLACK_COOLDOWN_MS = 4 * 60 * 60 * 1000;
+let lastSlackTime = 0;
+let cachedActiveMarkets = [];
+let cachedMomentumMap = {};
+
+// Interval handles (stored so we can clear + reset when config changes)
+let scanIntervalId = null;
+let redditIntervalId = null;
+let signalIntervalId = null;
+let resolveIntervalId = null;
+
+// Load scan config from DB on startup
+async function loadScanConfig() {
+ try {
+ await initConfigTable();
+ const { rows } = await kenQ("SELECT value FROM ken_config WHERE key = 'scan_config'");
+ if (rows.length > 0) {
+ const cfg = rows[0].value;
+ if (cfg.scan_interval_ms) SCAN_INTERVAL_MS = cfg.scan_interval_ms;
+ if (cfg.reddit_interval_ms) REDDIT_INTERVAL_MS = cfg.reddit_interval_ms;
+ if (cfg.signal_pipeline_ms) SIGNAL_PIPELINE_MS = cfg.signal_pipeline_ms;
+ if (cfg.resolve_interval_ms) RESOLVE_INTERVAL_MS = cfg.resolve_interval_ms;
+ if (cfg.min_edge_threshold !== undefined) RISK_LIMITS.minEdgeThreshold = cfg.min_edge_threshold;
+ if (cfg.min_liquidity !== undefined) RISK_LIMITS.minLiquidity = cfg.min_liquidity;
+ console.log(`[Ken] Loaded scan_config: scan=${SCAN_INTERVAL_MS/1000}s, signal=${SIGNAL_PIPELINE_MS/1000}s, sweep=${REDDIT_INTERVAL_MS/1000}s, resolve=${RESOLVE_INTERVAL_MS/1000}s, edge=${RISK_LIMITS.minEdgeThreshold}, liq=${RISK_LIMITS.minLiquidity}`);
+ }
+ } catch (e) {
+ console.log(`[Ken] Failed to load scan config: ${e.message}`);
+ }
+}
+
+async function saveScanConfig() {
+ try {
+ await kenQ(`
+ INSERT INTO ken_config (key, value, updated_at) VALUES ('scan_config', $1, NOW())
+ ON CONFLICT (key) DO UPDATE SET value = $1, updated_at = NOW()
+ `, [JSON.stringify({
+ scan_interval_ms: SCAN_INTERVAL_MS,
+ reddit_interval_ms: REDDIT_INTERVAL_MS,
+ signal_pipeline_ms: SIGNAL_PIPELINE_MS,
+ resolve_interval_ms: RESOLVE_INTERVAL_MS,
+ min_edge_threshold: RISK_LIMITS.minEdgeThreshold,
+ min_liquidity: RISK_LIMITS.minLiquidity,
+ })]);
+ } catch (e) {
+ console.log(`[Ken] Failed to save scan config: ${e.message}`);
+ }
+}
+
+function restartIntervals() {
+ if (scanIntervalId) clearInterval(scanIntervalId);
+ if (redditIntervalId) clearInterval(redditIntervalId);
+ if (signalIntervalId) clearInterval(signalIntervalId);
+ if (resolveIntervalId) clearInterval(resolveIntervalId);
+
+ scanIntervalId = setInterval(() => runScanSafe(autonomousScan), SCAN_INTERVAL_MS);
+ redditIntervalId = setInterval(() => runSweepSafe('Reddit', redditIntelligenceLoop), REDDIT_INTERVAL_MS);
+ signalIntervalId = setInterval(async () => {
+ if (cachedActiveMarkets.length > 0) {
+ try { await signalPipeline(cachedActiveMarkets); } catch (e) { console.log(`[Ken] Fast pipeline error: ${e.message}`); }
+ }
+ }, SIGNAL_PIPELINE_MS);
+ resolveIntervalId = setInterval(() => {
+ resolvePortfolioTrades().catch(e => console.error('[Ken] Portfolio resolution error:', e.message));
+ }, RESOLVE_INTERVAL_MS);
+
+ console.log(`[Ken] Intervals restarted: scan=${SCAN_INTERVAL_MS/60000}m, signal=${SIGNAL_PIPELINE_MS/60000}m, sweep=${REDDIT_INTERVAL_MS/60000}m, resolve=${RESOLVE_INTERVAL_MS/60000}m`);
+}
+
+// ── Reddit Scraper (no auth needed — uses .json API) ──
+async function scrapeReddit(subreddit, searchTerm, limit = 25) {
+ try {
+ const encoded = encodeURIComponent(searchTerm);
+ const url = `https://www.reddit.com/r/${subreddit}/search.json?q=${encoded}&sort=new&restrict_sr=on&limit=${limit}&t=week`;
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), 10000);
+ const res = await fetch(url, {
+ headers: { 'User-Agent': 'Ken-Bot/2.0 (trading intelligence)' },
+ signal: controller.signal,
+ });
+ clearTimeout(timeout);
+ if (!res.ok) return [];
+ const data = await res.json();
+ const posts = (data?.data?.children || []).map(c => ({
+ title: c.data.title,
+ selftext: (c.data.selftext || '').substring(0, 500),
+ score: c.data.score || 0,
+ num_comments: c.data.num_comments || 0,
+ url: `https://reddit.com${c.data.permalink}`,
+ created: new Date(c.data.created_utc * 1000),
+ subreddit: c.data.subreddit,
+ }));
+ return posts;
+ } catch (e) {
+ console.log(`[Ken] Reddit scrape failed r/${subreddit} "${searchTerm}": ${e.message}`);
+ return [];
+ }
+}
+
+// ── Scrape Reddit hot/top posts for general sentiment ──
+async function scrapeSubredditHot(subreddit, limit = 15) {
+ try {
+ const url = `https://www.reddit.com/r/${subreddit}/hot.json?limit=${limit}`;
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), 10000);
+ const res = await fetch(url, {
+ headers: { 'User-Agent': 'Ken-Bot/2.0 (trading intelligence)' },
+ signal: controller.signal,
+ });
+ clearTimeout(timeout);
+ if (!res.ok) return [];
+ const data = await res.json();
+ return (data?.data?.children || []).map(c => ({
+ title: c.data.title,
+ selftext: (c.data.selftext || '').substring(0, 500),
+ score: c.data.score || 0,
+ num_comments: c.data.num_comments || 0,
+ url: `https://reddit.com${c.data.permalink}`,
+ created: new Date(c.data.created_utc * 1000),
+ subreddit: c.data.subreddit,
+ }));
+ } catch (e) {
+ return [];
+ }
+}
+
+// ── Google News RSS scraper ──
+async function scrapeGoogleNews(query, limit = 10) {
+ try {
+ const encoded = encodeURIComponent(query);
+ const url = `https://news.google.com/rss/search?q=${encoded}&hl=en-US&gl=US&ceid=US:en`;
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), 10000);
+ const res = await fetch(url, { signal: controller.signal });
+ clearTimeout(timeout);
+ if (!res.ok) return [];
+ const xml = await res.text();
+ // Simple XML parse for RSS items
+ const items = [];
+ const itemRegex = /<item>([\s\S]*?)<\/item>/g;
+ let match;
+ while ((match = itemRegex.exec(xml)) && items.length < limit) {
+ const block = match[1];
+ const title = (block.match(/<title>([\s\S]*?)<\/title>/) || [])[1] || '';
+ const link = (block.match(/<link>([\s\S]*?)<\/link>/) || [])[1] || '';
+ const pubDate = (block.match(/<pubDate>([\s\S]*?)<\/pubDate>/) || [])[1] || '';
+ const source = (block.match(/<source[^>]*>([\s\S]*?)<\/source>/) || [])[1] || '';
+ items.push({
+ title: title.replace(/<!\[CDATA\[|\]\]>/g, '').trim(),
+ url: link.trim(),
+ source: source.replace(/<!\[CDATA\[|\]\]>/g, '').trim(),
+ published: pubDate ? new Date(pubDate) : new Date(),
+ });
+ }
+ return items;
+ } catch (e) {
+ console.log(`[Ken] News scrape failed "${query}": ${e.message}`);
+ return [];
+ }
+}
+
+// ── Polymarket cross-reference (public events API) ──
+async function scrapePolymarketEvents(limit = 100) {
+ try {
+ const url = `https://gamma-api.polymarket.com/events?closed=false&limit=${limit}&order=volume&ascending=false`;
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), 15000);
+ const res = await fetch(url, { signal: controller.signal });
+ clearTimeout(timeout);
+ if (!res.ok) return [];
+ const events = await res.json();
+ const results = [];
+ for (const evt of (events || [])) {
+ const mkts = (evt.markets || []).sort((a, b) => (b.volume || 0) - (a.volume || 0));
+ for (const m of mkts.slice(0, 3)) {
+ let price = null;
+ try { price = Math.round(parseFloat(JSON.parse(m.outcomePrices)[0]) * 100); } catch {}
+ if (price !== null && price > 0 && price < 100) {
+ results.push({
+ event_title: evt.title || '',
+ question: m.question || '',
+ price,
+ volume: Math.round(m.volume || 0),
+ slug: evt.slug || m.slug || '',
+ });
+ }
+ }
+ }
+ return results;
+ } catch (e) {
+ console.log(`[Ken] Polymarket scrape failed: ${e.message}`);
+ return [];
+ }
+}
+
+// ── Simple keyword sentiment scorer ──
+function scoreSentiment(text) {
+ const t = (text || '').toLowerCase();
+ const bullish = ['confirmed', 'likely', 'expected', 'approved', 'passed', 'agreed', 'winning', 'surge', 'soaring', 'breaking', 'imminent', 'certain', 'guarantee', 'official', 'announced', 'done deal'];
+ const bearish = ['unlikely', 'denied', 'rejected', 'failed', 'blocked', 'withdrawn', 'canceled', 'impossible', 'no chance', 'not going', 'walked back', 'reversed', 'postponed', 'delayed', 'collapse'];
+ const uncertain = ['maybe', 'could', 'might', 'rumor', 'speculation', 'sources say', 'unconfirmed', 'developing', 'unclear'];
+
+ let score = 0;
+ for (const w of bullish) if (t.includes(w)) score += 0.15;
+ for (const w of bearish) if (t.includes(w)) score -= 0.15;
+ for (const w of uncertain) if (t.includes(w)) score *= 0.7;
+ return Math.max(-1, Math.min(1, score));
+}
+
+// ── Map keywords in text to Kalshi event tickers ──
+function matchTextToMarkets(text, activeMarkets) {
+ const t = (text || '').toLowerCase();
+ const matches = [];
+ const keywords = {
+ 'fed chair': 'KXFEDCHAIRNOM',
+ 'federal reserve': 'KXFEDCHAIRNOM',
+ 'kevin warsh': 'KXFEDCHAIRNOM',
+ 'greenland': 'KXGREEN',
+ 'cabinet': 'KXCABOUT',
+ 'gabbard': 'KXCABOUT',
+ 'tulsi': 'KXCABOUT',
+ 'hegseth': 'KXCABOUT',
+ 'defense secretary': 'KXTRUMPDEFCOUNT',
+ 'insurrection act': 'KXINSURRECTION',
+ 'supreme court': 'KXSCOTUS',
+ 'seattle basketball': 'KXNBASEATTLE',
+ 'seattle nba': 'KXNBASEATTLE',
+ '2028 election': 'KXPRESPERSON',
+ 'presidential': 'KXPRESPERSON',
+ };
+ for (const [kw, prefix] of Object.entries(keywords)) {
+ if (t.includes(kw)) {
+ const related = activeMarkets.filter(m => m.event_ticker?.startsWith(prefix) || m.ticker?.startsWith(prefix));
+ for (const m of related) {
+ if (!matches.find(x => x.ticker === m.ticker)) matches.push(m);
+ }
+ }
+ }
+ return matches;
+}
+
+function generateSyntheticWeather(cities) {
+ const month = new Date().getMonth();
+ const results = [];
+ for (const city of cities) {
+ const coords = CITY_COORDS[city]; if (!coords) continue;
+ const baseTemp = [35,38,48,58,68,78,85,83,75,62,48,38][month] + (coords.lat < 35 ? 15 : coords.lat > 42 ? -8 : 0);
+ const temps = Array.from({length: 14}, (_, i) => baseTemp + Math.round((Math.random() - 0.5) * 12) + (i < 7 ? 3 : -2));
+ const precips = Array.from({length: 14}, () => Math.round(Math.random() * 60));
+ const winds = Array.from({length: 14}, () => 5 + Math.round(Math.random() * 15));
+ const mkStat = (arr) => ({ mean: arr.reduce((a,b)=>a+b)/arr.length, min: Math.min(...arr), max: Math.max(...arr), latest: arr[0] });
+ results.push({
+ city, synthetic: true,
+ temperature: { variable: 'temperature', unit: 'F', values: temps, ...mkStat(temps) },
+ precipitation: { variable: 'precipitation', unit: 'percent', values: precips, ...mkStat(precips) },
+ wind: { variable: 'wind', unit: 'mph', values: winds, ...mkStat(winds) },
+ });
+ }
+ return results;
+}
+
+// ── Hacker News scraper (top stories + search) ──
+// ── GDELT TV News mentions (covers CNN, MSNBC, Fox News, BBC captions) ──
+async function scrapeGDELTtv(query, station = 'CNN', limit = 15) {
+ try {
+ const url = `https://api.gdeltproject.org/api/v2/tv/tv?query=${encodeURIComponent(query)}%20station:${station}&mode=clipgallery&format=json&maxrecords=${limit}&last24hours=yes`;
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), 15000);
+ const res = await fetch(url, { signal: controller.signal, headers: { 'User-Agent': 'Ken-Bot/2.0' } });
+ clearTimeout(timeout);
+ if (!res.ok) return [];
+ const text = await res.text();
+ if (!text.startsWith('{')) return []; // API returns error text, not JSON
+ const data = JSON.parse(text);
+ return (data.clips || []).map(c => ({
+ title: c.snippet || '',
+ url: c.preview_url || c.url || '',
+ source: c.station || 'TV News',
+ show: c.show || '',
+ date: c.date || '',
+ }));
+ } catch (e) {
+ return [];
+ }
+}
+
+// ── YouTube RSS search (public API, no key needed) ──
+async function scrapeYouTubeRSS(query) {
+ try {
+ const url = `https://www.youtube.com/results?search_query=${encodeURIComponent(query)}&sp=CAISBAgBEAE%253D`; // last hour filter
+ // YouTube doesn't have direct RSS search, use channel feeds for major news channels
+ const channels = [
+ { id: 'UCupvZG-5ko_eiXAupbDfxWw', name: 'CNN' },
+ { id: 'UCaXkIU1QidjPwiAYu6GcHjg', name: 'MSNBC' },
+ { id: 'UCXIJgqnII2ZOINSWNOGFThA', name: 'Fox News' },
+ { id: 'UC16niRr50-MSBwiO3YDb3RA', name: 'Bloomberg TV' },
+ { id: 'UCvJJ_dzjViJCoLf5uKUTwoA', name: 'CNBC' },
+ { id: 'UCknLrEdhRCp1aegoMqRaCZg', name: 'NBC News' },
+ { id: 'UCBi2mrWuNuyYy4gbM6fU18Q', name: 'ABC News' },
+ { id: 'UC8p1vwvWtl6T73JiExfWs1g', name: 'CBS News' },
+ { id: 'UC52X5wxOL_s5yw0dQk7NtgA', name: 'PBS NewsHour' },
+ ];
+ const results = [];
+ for (const ch of channels) {
+ try {
+ const feedUrl = `https://www.youtube.com/feeds/videos.xml?channel_id=${ch.id}`;
+ const items = await scrapeRSSFeed(feedUrl, `YT ${ch.name}`, 5);
+ results.push(...items);
+ } catch {}
+ }
+ return results;
+ } catch { return []; }
+}
+
+// ── Lemmy (federated Reddit) — public JSON API, no auth needed ──
+async function scrapeLemmy(sort = 'Hot', limit = 20) {
+ const instances = ['lemmy.world', 'lemmy.ml', 'sh.itjust.works'];
+ const results = [];
+ for (const inst of instances) {
+ try {
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), 10000);
+ const res = await fetch(`https://${inst}/api/v3/post/list?sort=${sort}&limit=${limit}&type_=All`, {
+ signal: controller.signal,
+ headers: { 'Accept': 'application/json' },
+ });
+ clearTimeout(timeout);
+ if (!res.ok) continue;
+ const data = await res.json();
+ for (const p of (data.posts || [])) {
+ const post = p.post || {};
+ const counts = p.counts || {};
+ if (post.name && post.name.length > 10) {
+ results.push({
+ title: post.name.substring(0, 500),
+ url: post.ap_id || `https://${inst}/post/${post.id}`,
+ source: `Lemmy ${inst}`,
+ score: counts.score || 0,
+ num_comments: counts.comments || 0,
+ });
+ }
+ }
+ if (results.length > 0) break; // got data from one instance
+ } catch {}
+ }
+ return results;
+}
+
+// ── Lobsters (tech/politics news) — public JSON API ──
+async function scrapeLobsters(limit = 25) {
+ try {
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), 10000);
+ const res = await fetch('https://lobste.rs/hottest.json', { signal: controller.signal });
+ clearTimeout(timeout);
+ if (!res.ok) return [];
+ const stories = await res.json();
+ return stories.slice(0, limit).map(s => ({
+ title: s.title || '',
+ url: s.url || s.short_id_url || '',
+ source: 'Lobsters',
+ score: s.score || 0,
+ num_comments: s.comment_count || 0,
+ author: s.submitter_user?.username || '',
+ tags: (s.tags || []).join(', '),
+ }));
+ } catch { return []; }
+}
+
+// ── Tildes (curated discussion) — RSS feed ──
+async function scrapeTildes() {
+ try {
+ return await scrapeRSSFeed('https://tildes.net/topics.rss', 'Tildes', 20);
+ } catch { return []; }
+}
+
+// ── Manifold Markets (open prediction market — public API) ──
+async function scrapeManifold(queries) {
+ const results = [];
+ for (const q of queries) {
+ try {
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), 8000);
+ const res = await fetch(`https://manifold.markets/api/v0/search-markets?term=${encodeURIComponent(q)}&sort=liquidity&limit=10`, {
+ signal: controller.signal, headers: { 'Accept': 'application/json' },
+ });
+ clearTimeout(timeout);
+ if (!res.ok) continue;
+ const markets = await res.json();
+ for (const m of (markets || [])) {
+ if (m.question && m.probability != null && (m.volume || 0) > 100) {
+ results.push({
+ title: m.question,
+ url: m.url || `https://manifold.markets/${m.creatorUsername}/${m.slug}`,
+ source: 'Manifold',
+ probability: Math.round((m.probability || 0) * 100),
+ volume: Math.round(m.volume || 0),
+ liquidity: Math.round(m.totalLiquidity || 0),
+ });
+ }
+ }
+ } catch {}
+ await new Promise(r => setTimeout(r, 500));
+ }
+ return results;
+}
+
+// ── Mastodon/Fediverse trending (public API, no auth) ──
+async function scrapeMastodon() {
+ const instances = ['mastodon.social', 'mas.to'];
+ const results = [];
+ for (const inst of instances) {
+ try {
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), 8000);
+ const res = await fetch(`https://${inst}/api/v1/trends/statuses?limit=10`, {
+ signal: controller.signal,
+ });
+ clearTimeout(timeout);
+ if (!res.ok) continue;
+ const statuses = await res.json();
+ for (const s of statuses) {
+ const text = (s.content || '').replace(/<[^>]+>/g, '').trim();
+ if (text.length > 20) {
+ results.push({
+ title: text.substring(0, 500),
+ url: s.url || s.uri || '',
+ source: `Mastodon ${inst}`,
+ score: s.favourites_count || 0,
+ num_comments: s.replies_count || 0,
+ });
+ }
+ }
+ } catch {}
+ }
+ return results;
+}
+
+// ── Bluesky trending (public API — using feed generators, not searchPosts which is 403) ──
+async function scrapeBluesky() {
+ const feeds = [
+ { uri: 'at://did:plc:z72i7hdynmk6r22z27h6tvur/app.bsky.feed.generator/whats-hot', name: 'whats-hot' },
+ { uri: 'at://did:plc:z72i7hdynmk6r22z27h6tvur/app.bsky.feed.generator/hot-classic', name: 'hot-classic' },
+ ];
+ const results = [];
+ for (const feed of feeds) {
+ try {
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), 10000);
+ const url = `https://public.api.bsky.app/xrpc/app.bsky.feed.getFeed?feed=${encodeURIComponent(feed.uri)}&limit=20`;
+ const res = await fetch(url, { signal: controller.signal, headers: { 'Accept': 'application/json' } });
+ clearTimeout(timeout);
+ if (!res.ok) continue;
+ const data = await res.json();
+ for (const item of (data.feed || [])) {
+ const p = item.post || {};
+ const text = (p.record?.text || '').trim();
+ if (text.length > 20) {
+ results.push({
+ title: text.substring(0, 500),
+ url: `https://bsky.app/profile/${p.author?.handle}/post/${p.uri?.split('/').pop()}`,
+ source: `Bluesky ${feed.name}`,
+ author: p.author?.handle || '',
+ score: (p.likeCount || 0) + (p.repostCount || 0),
+ num_comments: p.replyCount || 0,
+ });
+ }
+ }
+ } catch {}
+ }
+ return results;
+}
+
+async function scrapeHackerNews(query, limit = 15) {
+ try {
+ const url = query
+ ? `https://hn.algolia.com/api/v1/search_by_date?query=${encodeURIComponent(query)}&tags=story&hitsPerPage=${limit}`
+ : `https://hn.algolia.com/api/v1/search?tags=front_page&hitsPerPage=${limit}`;
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), 10000);
+ const res = await fetch(url, { signal: controller.signal });
+ clearTimeout(timeout);
+ if (!res.ok) return [];
+ const data = await res.json();
+ return (data.hits || []).map(h => ({
+ title: h.title || '',
+ url: h.url || `https://news.ycombinator.com/item?id=${h.objectID}`,
+ score: h.points || 0,
+ num_comments: h.num_comments || 0,
+ created: new Date(h.created_at),
+ source: 'hackernews',
+ }));
+ } catch (e) {
+ console.log(`[Ken] HN scrape failed: ${e.message}`);
+ return [];
+ }
+}
+
+// ── AP News RSS scraper ──
+// ── Generic RSS feed scraper ──
+async function scrapeRSSFeed(url, source, limit = 15) {
+ try {
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), 10000);
+ const res = await fetch(url, {
+ signal: controller.signal,
+ headers: { 'User-Agent': 'Ken-Bot/2.0 (RSS Reader)' },
+ });
+ clearTimeout(timeout);
+ if (!res.ok) return [];
+ const xml = await res.text();
+ const items = [];
+ // Handle both <item> (RSS) and <entry> (Atom) formats
+ const itemRegex = /<(?:item|entry)>([\s\S]*?)<\/(?:item|entry)>/g;
+ let match;
+ while ((match = itemRegex.exec(xml)) && items.length < limit) {
+ const block = match[1];
+ const title = (block.match(/<title[^>]*>([\s\S]*?)<\/title>/) || [])[1] || '';
+ const link = (block.match(/<link[^>]*href="([^"]+)"/) || block.match(/<link>([\s\S]*?)<\/link>/) || [])[1] || '';
+ const cleanTitle = title.replace(/<!\[CDATA\[|\]\]>/g, '').replace(/<[^>]+>/g, '').trim();
+ if (cleanTitle && cleanTitle.length > 10) {
+ items.push({ title: cleanTitle, url: link.trim(), source });
+ }
+ }
+ return items;
+ } catch { return []; }
+}
+
+// ── All news channel feeds ──
+const NEWS_FEEDS = [
+ // ═══ POLITICS & POLICY (Kalshi political markets) ═══
+ { url: 'https://feeds.bbci.co.uk/news/world/rss.xml', source: 'BBC World' },
+ { url: 'https://feeds.bbci.co.uk/news/politics/rss.xml', source: 'BBC Politics' },
+ { url: 'https://feeds.bbci.co.uk/news/us_and_canada/rss.xml', source: 'BBC US' },
+ { url: 'https://rss.nytimes.com/services/xml/rss/nyt/Politics.xml', source: 'NYT Politics' },
+ { url: 'https://rss.nytimes.com/services/xml/rss/nyt/World.xml', source: 'NYT World' },
+ { url: 'https://rss.nytimes.com/services/xml/rss/nyt/US.xml', source: 'NYT US' },
+ { url: 'https://feeds.washingtonpost.com/rss/politics', source: 'WaPo Politics' },
+ { url: 'https://feeds.washingtonpost.com/rss/world', source: 'WaPo World' },
+ { url: 'https://www.politico.com/rss/politicopicks.xml', source: 'Politico' },
+ { url: 'https://www.politico.com/rss/congress.xml', source: 'Politico Congress' },
+ { url: 'https://thehill.com/feed/', source: 'The Hill' },
+ { url: 'https://feeds.npr.org/1001/rss.xml', source: 'NPR News' },
+ { url: 'https://feeds.npr.org/1014/rss.xml', source: 'NPR Politics' },
+ { url: 'https://www.aljazeera.com/xml/rss/all.xml', source: 'Al Jazeera' },
+ { url: 'https://rss.dw.com/xml/rss-en-all', source: 'DW News' },
+ { url: 'https://feeds.skynews.com/feeds/rss/world.xml', source: 'Sky News World' },
+ { url: 'https://feeds.skynews.com/feeds/rss/us.xml', source: 'Sky News US' },
+ { url: 'https://www.theguardian.com/us-news/rss', source: 'Guardian US' },
+ { url: 'https://www.theguardian.com/world/rss', source: 'Guardian World' },
+ { url: 'https://rss.cbc.ca/lineup/world.xml', source: 'CBC World' },
+ { url: 'https://feeds.abcnews.com/abcnews/politicsheadlines', source: 'ABC Politics' },
+ { url: 'http://feeds.foxnews.com/foxnews/politics', source: 'Fox Politics' },
+ { url: 'https://www.axios.com/feeds/feed.rss', source: 'Axios' },
+ { url: 'https://www.vox.com/rss/index.xml', source: 'Vox' },
+
+ // ═══ ECONOMICS & FINANCIAL MARKETS (Kalshi econ/rate markets) ═══
+ { url: 'https://feeds.bloomberg.com/politics/news.rss', source: 'Bloomberg Politics' },
+ { url: 'https://feeds.bloomberg.com/markets/news.rss', source: 'Bloomberg Markets' },
+ { url: 'https://www.cnbc.com/id/10000664/device/rss/rss.html', source: 'CNBC Top' },
+ { url: 'https://www.cnbc.com/id/10001147/device/rss/rss.html', source: 'CNBC Economy' },
+ { url: 'https://search.cnbc.com/rs/search/combinedcms/view.xml?partnerId=wrss01&id=15839069', source: 'CNBC Politics' },
+ { url: 'https://www.cnbc.com/id/20910258/device/rss/rss.html', source: 'CNBC Finance' },
+ { url: 'https://feeds.marketwatch.com/marketwatch/topstories/', source: 'MarketWatch' },
+ { url: 'https://feeds.marketwatch.com/marketwatch/marketpulse/', source: 'MarketWatch Pulse' },
+ { url: 'https://rss.nytimes.com/services/xml/rss/nyt/Business.xml', source: 'NYT Business' },
+ { url: 'https://rss.nytimes.com/services/xml/rss/nyt/Economy.xml', source: 'NYT Economy' },
+ { url: 'https://www.ft.com/rss/home/us', source: 'FT US' },
+ { url: 'https://www.investing.com/rss/news.rss', source: 'Investing.com' },
+ { url: 'https://www.federalreserve.gov/feeds/press_all.xml', source: 'Fed Reserve' },
+ { url: 'https://www.bis.org/doclist/bis_fsi_publs.rss', source: 'BIS' },
+ { url: 'https://seekingalpha.com/feed.xml', source: 'Seeking Alpha' },
+ { url: 'https://finance.yahoo.com/news/rssindex', source: 'Yahoo Finance' },
+
+ // ═══ CRYPTO & PREDICTION MARKETS (cross-ref with Polymarket) ═══
+ { url: 'https://cointelegraph.com/rss', source: 'CoinTelegraph' },
+ { url: 'https://www.coindesk.com/arc/outboundfeeds/rss/', source: 'CoinDesk' },
+ { url: 'https://decrypt.co/feed', source: 'Decrypt' },
+ { url: 'https://thedefiant.io/feed', source: 'The Defiant' },
+
+ // ═══ PREDICTION & POLLING ANALYSIS ═══
+ { url: 'https://fivethirtyeight.com/features/feed/', source: 'FiveThirtyEight' },
+ { url: 'https://www.realclearpolitics.com/index.xml', source: 'RealClearPolitics' },
+ { url: 'https://electionbettingodds.com/feed', source: 'ElectionBettingOdds' },
+ { url: 'https://www.predictit.org/feed', source: 'PredictIt' },
+
+ // ═══ TECH & AI POLICY (Kalshi tech markets) ═══
+ { url: 'https://www.theverge.com/rss/index.xml', source: 'The Verge' },
+ { url: 'https://techcrunch.com/feed/', source: 'TechCrunch' },
+ { url: 'https://arstechnica.com/feed/', source: 'Ars Technica' },
+ { url: 'https://www.wired.com/feed/rss', source: 'WIRED' },
+ { url: 'https://feeds.feedburner.com/venturebeat/SZYF', source: 'VentureBeat' },
+
+ // ═══ WEATHER & CLIMATE (Kalshi weather markets - temps, snow, etc.) ═══
+ { url: 'https://www.weather.gov/rss_page.php?site_name=nws', source: 'NWS' },
+ { url: 'https://weather.com/feeds/enhancedconditions/rss', source: 'Weather.com' },
+ { url: 'https://www.accuweather.com/en/us/national/current-weather/rss', source: 'AccuWeather' },
+ { url: 'https://www.climate.gov/rss.xml', source: 'NOAA Climate' },
+
+ // ═══ SPORTS (Kalshi has sports-adjacent markets) ═══
+ { url: 'https://www.espn.com/espn/rss/news', source: 'ESPN' },
+ { url: 'https://rss.nytimes.com/services/xml/rss/nyt/Sports.xml', source: 'NYT Sports' },
+
+ // ═══ ENTERTAINMENT & CULTURE (Kalshi awards/culture markets) ═══
+ { url: 'https://variety.com/feed/', source: 'Variety' },
+ { url: 'https://deadline.com/feed/', source: 'Deadline' },
+ { url: 'https://www.hollywoodreporter.com/feed/', source: 'Hollywood Reporter' },
+
+ // ═══ ENERGY & COMMODITIES (Kalshi gas/oil markets) ═══
+ { url: 'https://oilprice.com/rss/main', source: 'OilPrice' },
+ { url: 'https://www.eia.gov/rss/todayinenergy.xml', source: 'EIA Energy' },
+
+ // ═══ DEFENSE & GEOPOLITICS (conflict/territory markets) ═══
+ { url: 'https://www.defensenews.com/arc/outboundfeeds/rss/category/global/?outputType=xml', source: 'Defense News' },
+ { url: 'https://foreignpolicy.com/feed/', source: 'Foreign Policy' },
+ { url: 'https://warontherocks.com/feed/', source: 'War On The Rocks' },
+
+ // ═══ SCIENCE & SPACE (Kalshi space markets) ═══
+ { url: 'https://www.nasa.gov/rss/dyn/breaking_news.rss', source: 'NASA' },
+ { url: 'https://www.space.com/feeds/all', source: 'Space.com' },
+ { url: 'https://www.nature.com/nature.rss', source: 'Nature' },
+ { url: 'https://www.science.org/rss/news_current.xml', source: 'Science' },
+];
+
+async function scrapeAllNewsFeeds() {
+ const allArticles = [];
+ // Process feeds in batches of 15 concurrently for speed (maxed for 16 cores)
+ const batchSize = 15;
+ for (let i = 0; i < NEWS_FEEDS.length; i += batchSize) {
+ const batch = NEWS_FEEDS.slice(i, i + batchSize);
+ const results = await Promise.allSettled(
+ batch.map(feed => scrapeRSSFeed(feed.url, feed.source, 8))
+ );
+ for (const result of results) {
+ if (result.status === 'fulfilled') allArticles.push(...result.value);
+ }
+ await new Promise(r => setTimeout(r, 100)); // minimal pause between batches
+ }
+ return allArticles;
+}
+
+// ── Metaculus predictions scraper (prediction market cross-ref) ──
+async function scrapeMetaculus() {
+ try {
+ const url = 'https://www.metaculus.com/api2/questions/?limit=20&order_by=-activity&status=open&type=forecast';
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), 10000);
+ const res = await fetch(url, { headers: { 'Accept': 'application/json' }, signal: controller.signal });
+ clearTimeout(timeout);
+ if (!res.ok) return [];
+ const data = await res.json();
+ return (data.results || []).map(q => ({
+ title: q.title || '',
+ url: `https://www.metaculus.com/questions/${q.id}`,
+ community_prediction: q.community_prediction?.full?.q2,
+ num_predictions: q.number_of_predictions || 0,
+ source: 'metaculus',
+ }));
+ } catch (e) {
+ console.log(`[Ken] Metaculus scrape failed: ${e.message}`);
+ return [];
+ }
+}
+
+// ── PredictIt API (another prediction market for cross-reference) ──
+async function scrapePredictIt() {
+ try {
+ const controller = new AbortController();
+ setTimeout(() => controller.abort(), 8000);
+ const res = await fetch('https://www.predictit.org/api/marketdata/all/', {
+ signal: controller.signal,
+ headers: { 'User-Agent': 'Ken-Bot/1.0' }
+ });
+ if (!res.ok) return [];
+ const data = await res.json();
+ return (data.markets || []).slice(0, 100).map(m => ({
+ title: m.name,
+ url: m.url || `https://www.predictit.org/markets/detail/${m.id}`,
+ score: Math.round((m.contracts?.[0]?.lastTradePrice || 0) * 100),
+ num_comments: m.contracts?.length || 0,
+ source: 'predictit',
+ extra: JSON.stringify({
+ contracts: (m.contracts || []).slice(0, 5).map(c => ({
+ name: c.name, lastPrice: c.lastTradePrice, bestBuy: c.bestBuyYesCost, bestSell: c.bestSellYesCost
+ }))
+ })
+ }));
+ } catch (e) {
+ console.log(`[Ken] PredictIt scrape failed: ${e.message}`);
+ return [];
+ }
+}
+
+// ── FRED Economic Data API (real economic indicators — no key needed for some endpoints) ──
+async function scrapeFredIndicators() {
+ const indicators = [
+ { series: 'CPIAUCSL', name: 'CPI Inflation' },
+ { series: 'UNRATE', name: 'Unemployment Rate' },
+ { series: 'GDP', name: 'GDP Growth' },
+ { series: 'FEDFUNDS', name: 'Federal Funds Rate' },
+ { series: 'T10Y2Y', name: '10Y-2Y Treasury Spread' },
+ { series: 'VIXCLS', name: 'VIX Volatility Index' },
+ { series: 'DGS10', name: '10-Year Treasury Yield' },
+ { series: 'DCOILWTICO', name: 'WTI Crude Oil Price' },
+ ];
+ const results = [];
+ for (const ind of indicators) {
+ try {
+ const controller = new AbortController();
+ setTimeout(() => controller.abort(), 5000);
+ const res = await fetch(`https://fred.stlouisfed.org/graph/fredgraph.csv?id=${ind.series}&cosd=${new Date(Date.now() - 90*86400000).toISOString().split('T')[0]}`, {
+ signal: controller.signal,
+ headers: { 'User-Agent': 'Ken-Bot/1.0' }
+ });
+ if (!res.ok) continue;
+ const csv = await res.text();
+ const lines = csv.trim().split('\n');
+ if (lines.length < 2) continue;
+ const lastLine = lines[lines.length - 1];
+ const [date, value] = lastLine.split(',');
+ if (value && value !== '.') {
+ results.push({
+ title: `${ind.name}: ${value} (${date})`,
+ url: `https://fred.stlouisfed.org/series/${ind.series}`,
+ score: Math.round(parseFloat(value) * 100) || 0,
+ source: 'fred_economic',
+ keyword: ind.series,
+ });
+ }
+ } catch {}
+ }
+ return results;
+}
+
+// ── NWS Active Weather Alerts (real severe weather data for weather markets) ──
+async function scrapeNWSAlerts() {
+ try {
+ const controller = new AbortController();
+ setTimeout(() => controller.abort(), 8000);
+ const res = await fetch('https://api.weather.gov/alerts/active?status=actual&message_type=alert&limit=50', {
+ signal: controller.signal,
+ headers: { 'User-Agent': 'Ken-Bot/1.0 (ken@designerwallcoverings.com)', 'Accept': 'application/geo+json' }
+ });
+ if (!res.ok) return [];
+ const data = await res.json();
+ return (data.features || []).map(f => ({
+ title: `${f.properties.event}: ${f.properties.headline || f.properties.description?.substring(0, 200) || ''}`.substring(0, 500),
+ url: f.properties['@id'] || 'https://alerts.weather.gov',
+ score: f.properties.severity === 'Extreme' ? 100 : f.properties.severity === 'Severe' ? 75 : f.properties.severity === 'Moderate' ? 50 : 25,
+ num_comments: 0,
+ source: 'nws_alerts',
+ keyword: f.properties.event || 'weather',
+ }));
+ } catch (e) {
+ console.log(`[Ken] NWS Alerts failed: ${e.message}`);
+ return [];
+ }
+}
+
+// ── Congressional/Government Activity (GovTrack API) ──
+async function scrapeGovTrack() {
+ try {
+ const controller = new AbortController();
+ setTimeout(() => controller.abort(), 8000);
+ const res = await fetch('https://www.govtrack.us/api/v2/vote?order_by=-created&limit=20', {
+ signal: controller.signal,
+ headers: { 'User-Agent': 'Ken-Bot/1.0' }
+ });
+ if (!res.ok) return [];
+ const data = await res.json();
+ return (data.objects || []).map(v => ({
+ title: `${v.chamber === 'senate' ? 'Senate' : 'House'} Vote: ${v.question || v.result || 'Unknown'}`.substring(0, 500),
+ url: `https://www.govtrack.us${v.link || ''}`,
+ score: v.total_plus || 0,
+ num_comments: v.total_minus || 0,
+ source: 'govtrack',
+ keyword: v.category || 'legislation',
+ }));
+ } catch (e) {
+ console.log(`[Ken] GovTrack failed: ${e.message}`);
+ return [];
+ }
+}
+
+// ── X/Twitter via Nitter instances (public, no auth needed) ──
+async function scrapeNitterTrending() {
+ const nitterInstances = [
+ 'https://nitter.poast.org',
+ 'https://nitter.privacydev.net',
+ 'https://nitter.cz',
+ ];
+ const searchTerms = ['kalshi', 'polymarket', 'prediction market', 'fed rate decision', 'hurricane season'];
+ const results = [];
+ for (const term of searchTerms) {
+ for (const instance of nitterInstances) {
+ try {
+ const controller = new AbortController();
+ setTimeout(() => controller.abort(), 6000);
+ const url = `${instance}/search?f=tweets&q=${encodeURIComponent(term)}&since=`;
+ const res = await fetch(url, { signal: controller.signal, headers: { 'User-Agent': 'Mozilla/5.0' } });
+ if (!res.ok) continue;
+ const html = await res.text();
+ // Extract tweet text from Nitter HTML
+ const tweetMatches = html.match(/<div class="tweet-content[^"]*"[^>]*>([\s\S]*?)<\/div>/g) || [];
+ for (const match of tweetMatches.slice(0, 5)) {
+ const text = match.replace(/<[^>]+>/g, '').trim().substring(0, 500);
+ if (text.length > 10) {
+ results.push({
+ title: text,
+ url: `${instance}/search?q=${encodeURIComponent(term)}`,
+ score: 0,
+ num_comments: 0,
+ source: 'twitter_nitter',
+ keyword: term,
+ });
+ }
+ }
+ break; // One working instance per term is enough
+ } catch {} // Nitter instances are unreliable, fail silently
+ }
+ await new Promise(r => setTimeout(r, 2000));
+ }
+ return results;
+}
+
+// ── Discord Bot Intelligence (reads messages from joined servers) ──
+const DISCORD_BOT_TOKEN = 'MTQ3MjYyNDg2OTk3NDg2ODA2Mg.GifeyF.C5l9KqQUia-Ex54Ldg23fuxislxwf2QtmkXYII';
+const DISCORD_API = 'https://discord.com/api/v10';
+
+// Channel names to monitor (matched case-insensitive) — covers all Kalshi/Polymarket categories
+const DISCORD_CHANNEL_KEYWORDS = [
+ // Core
+ 'general', 'chat', 'discussion', 'lounge', 'main',
+ // Trading & Markets
+ 'trading', 'markets', 'predictions', 'analysis', 'strategy', 'signals', 'alerts',
+ 'arbitrage', 'polymarket', 'kalshi', 'bets', 'picks', 'plays', 'odds',
+ // News & Facts
+ 'news', 'breaking', 'headlines', 'updates', 'osint', 'intel', 'events',
+ // Weather
+ 'weather', 'hurricane', 'tropical', 'storm', 'forecast', 'severe', 'climate',
+ // Politics & Elections
+ 'politics', 'election', 'polling', 'congress', 'senate', 'trump', 'biden',
+ 'policy', 'legislation', 'vote', 'debate',
+ // Economics & Finance
+ 'economics', 'economy', 'finance', 'stocks', 'fed', 'inflation', 'rates',
+ 'macro', 'earnings', 'options', 'futures', 'bonds',
+ // Sports
+ 'sports', 'nfl', 'nba', 'mlb', 'nhl', 'soccer', 'football', 'basketball',
+ 'baseball', 'ufc', 'mma', 'boxing', 'f1', 'golf', 'tennis',
+ // Crypto
+ 'crypto', 'bitcoin', 'btc', 'ethereum', 'eth', 'defi', 'altcoin', 'solana',
+ // Geopolitics
+ 'geopolitics', 'ukraine', 'russia', 'china', 'military', 'conflict', 'war', 'nato',
+ // Entertainment
+ 'entertainment', 'movies', 'film', 'oscars', 'grammys', 'awards', 'box-office',
+ 'music', 'tv', 'streaming', 'celebrity',
+ // Science & Space
+ 'space', 'spacex', 'nasa', 'launch', 'science', 'rocket',
+ // Tech & AI
+ 'tech', 'ai', 'artificial', 'openai', 'gpt', 'machine-learning', 'nvidia',
+];
+
+async function discordFetch(endpoint) {
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), 10000);
+ const res = await fetch(`${DISCORD_API}${endpoint}`, {
+ headers: { Authorization: `Bot ${DISCORD_BOT_TOKEN}`, 'Content-Type': 'application/json' },
+ signal: controller.signal,
+ });
+ clearTimeout(timeout);
+ if (!res.ok) {
+ if (res.status === 429) {
+ const retry = await res.json().catch(() => ({}));
+ const wait = (retry.retry_after || 5) * 1000;
+ console.log(`[Ken] Discord rate limited, waiting ${wait}ms`);
+ await new Promise(r => setTimeout(r, wait));
+ return null;
+ }
+ return null;
+ }
+ return res.json();
+}
+
+async function scrapeDiscord(limit = 50) {
+ const results = [];
+ try {
+ // 1. Get all guilds the bot is in
+ const guilds = await discordFetch('/users/@me/guilds');
+ if (!guilds || !Array.isArray(guilds)) {
+ console.log('[Ken] Discord: no guilds found (bot may not have joined any servers yet)');
+ return [];
+ }
+ console.log(`[Ken] Discord: bot is in ${guilds.length} server(s): ${guilds.map(g => g.name).join(', ')}`);
+
+ for (const guild of guilds) {
+ // 2. Get channels for this guild
+ const channels = await discordFetch(`/guilds/${guild.id}/channels`);
+ if (!channels || !Array.isArray(channels)) continue;
+
+ // 3. Filter to text channels matching keywords
+ const textChannels = channels.filter(ch => {
+ if (ch.type !== 0) return false; // type 0 = text channel
+ const name = (ch.name || '').toLowerCase();
+ return DISCORD_CHANNEL_KEYWORDS.some(kw => name.includes(kw));
+ });
+
+ console.log(`[Ken] Discord [${guild.name}]: monitoring ${textChannels.length}/${channels.filter(c => c.type === 0).length} text channels`);
+
+ for (const channel of textChannels.slice(0, 15)) { // cap at 15 channels per guild
+ try {
+ const messages = await discordFetch(`/channels/${channel.id}/messages?limit=${Math.min(limit, 50)}`);
+ if (!messages || !Array.isArray(messages)) continue;
+
+ // Only messages from last 2 hours (fresh intel)
+ const cutoff = Date.now() - (2 * 60 * 60 * 1000);
+ for (const msg of messages) {
+ const msgTime = new Date(msg.timestamp).getTime();
+ if (msgTime < cutoff) continue;
+ if (!msg.content || msg.content.length < 20) continue;
+ if (msg.author?.bot) continue; // skip bot messages
+
+ results.push({
+ title: msg.content.substring(0, 500),
+ url: `https://discord.com/channels/${guild.id}/${channel.id}/${msg.id}`,
+ source: `Discord ${guild.name}`,
+ channel: channel.name,
+ author: msg.author?.username || 'unknown',
+ score: (msg.reactions || []).reduce((sum, r) => sum + (r.count || 0), 0),
+ num_comments: msg.referenced_message ? 1 : 0, // thread indicator
+ created: new Date(msg.timestamp),
+ });
+ }
+ // Rate limit: 500ms between channel reads
+ await new Promise(r => setTimeout(r, 500));
+ } catch (e) {
+ console.log(`[Ken] Discord channel ${channel.name} error: ${e.message}`);
+ }
+ }
+ await new Promise(r => setTimeout(r, 1000)); // between guilds
+ }
+ console.log(`[Ken] Discord: ${results.length} messages from ${guilds.length} server(s)`);
+ } catch (e) {
+ console.log(`[Ken] Discord scrape failed: ${e.message}`);
+ }
+ return results;
+}
+
+// ══════════════════════════════════════════════
+// INTELLIGENCE LOOP (every 30 min) — Reddit, HN, News, Metaculus, Discord
+// ══════════════════════════════════════════════
+function logMemory(label) {
+ const mem = process.memoryUsage();
+ const rss = Math.round(mem.rss / 1024 / 1024);
+ const heap = Math.round(mem.heapUsed / 1024 / 1024);
+ if (rss > 500) console.log(`[Ken] MEM ${label}: RSS=${rss}MB Heap=${heap}MB`);
+}
+
+async function redditIntelligenceLoop() {
+ console.log('[Ken] Running Reddit intelligence sweep...');
+ logMemory('sweep-start');
+ let totalPosts = 0;
+ try {
+ // Get tracking config from DB
+ const { rows: trackers } = await kenQ('SELECT * FROM ken_reddit_tracking WHERE enabled = true');
+
+ // Process tracked subreddits in parallel batches of 12 (maxed for 16 cores)
+ const TRACKER_BATCH = 12;
+ for (let i = 0; i < trackers.length; i += TRACKER_BATCH) {
+ const batch = trackers.slice(i, i + TRACKER_BATCH);
+ const results = await Promise.allSettled(
+ batch.map(tracker => scrapeReddit(tracker.subreddit, tracker.search_term, 20)
+ .then(posts => ({ tracker, posts })))
+ );
+ for (const result of results) {
+ if (result.status !== 'fulfilled') continue;
+ const { tracker, posts } = result.value;
+ for (const post of posts) {
+ const sentiment = scoreSentiment(post.title + ' ' + post.selftext);
+ if (post.score > 2 || post.num_comments > 1) {
+ await kenQ(`
+ INSERT INTO ken_sentiment (source, subreddit, keyword, post_title, post_url, score, num_comments, sentiment_score, relevance_ticker, raw_text)
+ VALUES ('reddit', $1, $2, $3, $4, $5, $6, $7, $8, $9)
+ ON CONFLICT DO NOTHING
+ `, [
+ tracker.subreddit, tracker.search_term, post.title, post.url,
+ post.score, post.num_comments, sentiment,
+ (tracker.related_tickers || [])[0] || null,
+ (post.selftext || '').substring(0, 1000),
+ ]);
+ totalPosts++;
+ }
+ }
+ }
+ await new Promise(r => setTimeout(r, 500)); // 0.5s between batches (was 1.5s)
+ }
+
+ // Also scrape hot posts from key subreddits for general intelligence
+ // Categories: Weather | Politics | Economics | Sports | Crypto | Geopolitics | Entertainment | Science/Space | Tech/AI | General Sentiment
+ const hotSubs = [
+ // ── Core prediction markets ──
+ 'Kalshi', 'Polymarket', 'PredictionMarket', 'sportsbook',
+ // ── Weather (hurricane/temp/storm markets) ──
+ 'TropicalWeather', 'weather', 'tornado', 'hurricane', 'climate',
+ 'NaturalGas', 'energy', 'propane', 'HomeImprovement',
+ // ── Heating Bills & Utility Costs ──
+ 'personalfinance', 'Frugal', 'povertyfinance', 'homeowners',
+ 'HVAC', 'utilities', 'electricvehicles',
+ // ── Politics & Elections ──
+ 'politics', 'Conservative', 'Liberal', 'NeutralPolitics', 'PoliticalDiscussion',
+ 'fivethirtyeight', 'elections', 'supremecourt', 'moderatepolitics', 'law',
+ // ── Economics & Finance ──
+ 'economics', 'wallstreetbets', 'economy', 'inflation', 'FederalReserve',
+ 'StockMarket', 'investing', 'RealEstate', 'finance', 'commodities',
+ // ── Sports ──
+ 'nfl', 'nba', 'baseball', 'soccer', 'MMA', 'CFB', 'CollegeBasketball',
+ 'formula1', 'golf', 'hockey', 'tennis', 'boxing',
+ // ── Crypto ──
+ 'CryptoMarkets', 'Bitcoin', 'ethereum', 'CryptoCurrency', 'BitcoinMarkets', 'solana',
+ // ── Geopolitics ──
+ 'worldnews', 'geopolitics', 'UkrainianConflict', 'ukraine', 'China',
+ 'MiddleEastNews', 'foreignpolicy', 'military',
+ // ── Entertainment (awards/box office markets) ──
+ 'movies', 'boxoffice', 'television', 'Oscars', 'Music', 'entertainment',
+ // ── Science & Space (launch/milestone markets) ──
+ 'SpaceX', 'space', 'nasa', 'science', 'Futurology',
+ // ── Tech & AI ──
+ 'technology', 'artificial', 'MachineLearning', 'OpenAI', 'singularity', 'Nvidia',
+ // ── General sentiment ──
+ 'news', 'OutOfTheLoop', 'AskReddit', 'TrueReddit', 'dataisbeautiful',
+ ];
+ // Process subreddits in parallel batches of 12 (maxed for 16 cores)
+ const REDDIT_BATCH = 12;
+ for (let i = 0; i < hotSubs.length; i += REDDIT_BATCH) {
+ const batch = hotSubs.slice(i, i + REDDIT_BATCH);
+ const results = await Promise.allSettled(batch.map(sub => scrapeSubredditHot(sub, 8)));
+ for (let j = 0; j < results.length; j++) {
+ if (results[j].status !== 'fulfilled') continue;
+ const sub = batch[j];
+ for (const post of results[j].value) {
+ if (post.score > 30) { // lower threshold to catch more sentiment signals
+ const sentiment = scoreSentiment(post.title);
+ await kenQ(`
+ INSERT INTO ken_sentiment (source, subreddit, keyword, post_title, post_url, score, num_comments, sentiment_score, raw_text)
+ VALUES ('reddit_hot', $1, 'hot', $2, $3, $4, $5, $6, $7)
+ ON CONFLICT DO NOTHING
+ `, [sub, post.title, post.url, post.score, post.num_comments, sentiment, '']);
+ totalPosts++;
+ }
+ }
+ }
+ await new Promise(r => setTimeout(r, 500)); // 0.5s between batches (was 1.5s)
+ }
+ console.log(`[Ken] Reddit hot: ${hotSubs.length} subreddits across 10 categories`);
+ logMemory('after-reddit');
+ if (global.gc) global.gc();
+
+ // Scrape Google News for top market topics (covers all Kalshi categories)
+ const newsQueries = [
+ // Politics & elections
+ 'trump cabinet resign', 'federal reserve chair nomination', '2028 presidential election',
+ 'trump executive order', 'government shutdown', 'supreme court ruling',
+ // Economics
+ 'CPI inflation report', 'federal reserve rate decision', 'jobs report unemployment',
+ 'GDP growth', 'recession forecast',
+ // Weather
+ 'hurricane forecast atlantic', 'severe weather outbreak', 'temperature record',
+ // Geopolitics
+ 'ukraine russia ceasefire', 'china taiwan', 'middle east conflict',
+ // Crypto
+ 'bitcoin price prediction', 'SEC crypto regulation',
+ // Entertainment
+ 'oscar nominations', 'box office weekend',
+ // Space
+ 'SpaceX launch', 'NASA artemis',
+ ];
+ // Process Google News in batches of 5 (21 serial × 1s = too slow)
+ const NEWS_QUERY_BATCH = 5;
+ for (let i = 0; i < newsQueries.length; i += NEWS_QUERY_BATCH) {
+ const batch = newsQueries.slice(i, i + NEWS_QUERY_BATCH);
+ const results = await Promise.allSettled(
+ batch.map(nq => scrapeGoogleNews(nq, 5).then(articles => ({ nq, articles })))
+ );
+ for (const result of results) {
+ if (result.status !== 'fulfilled') continue;
+ const { nq, articles } = result.value;
+ for (const article of articles) {
+ const sentiment = scoreSentiment(article.title);
+ await kenQ(`
+ INSERT INTO ken_sentiment (source, subreddit, keyword, post_title, post_url, score, sentiment_score)
+ VALUES ('google_news', $1, $2, $3, $4, 0, $5)
+ ON CONFLICT DO NOTHING
+ `, [article.source || 'news', nq, article.title, article.url, sentiment]);
+ totalPosts++;
+ }
+ }
+ await new Promise(r => setTimeout(r, 1000));
+ }
+
+ // ── Hacker News (tech/policy sentiment) ──
+ const hnQueries = ['trump policy', 'federal reserve', 'tariff', 'ukraine russia', null]; // null = front page
+ for (const hq of hnQueries) {
+ try {
+ const stories = await scrapeHackerNews(hq, 10);
+ for (const story of stories) {
+ if (story.score > 5 || story.num_comments > 3) {
+ const sentiment = scoreSentiment(story.title);
+ await kenQ(`
+ INSERT INTO ken_sentiment (source, subreddit, keyword, post_title, post_url, score, num_comments, sentiment_score, raw_text)
+ VALUES ('hackernews', 'hackernews', $1, $2, $3, $4, $5, $6, '')
+ ON CONFLICT DO NOTHING
+ `, [hq || 'front_page', story.title, story.url, story.score, story.num_comments, sentiment]);
+ totalPosts++;
+ }
+ }
+ } catch {}
+ await new Promise(r => setTimeout(r, 1500));
+ }
+
+ // ── All News Channels (BBC, NYT, WaPo, Politico, CNBC, Bloomberg, etc.) ──
+ try {
+ let newsStored = 0;
+ // Process feeds in small batches to limit memory — don't hold all articles at once
+ const batchSize = 5;
+ for (let i = 0; i < NEWS_FEEDS.length; i += batchSize) {
+ const batch = NEWS_FEEDS.slice(i, i + batchSize);
+ const results = await Promise.allSettled(
+ batch.map(feed => scrapeRSSFeed(feed.url, feed.source, 6))
+ );
+ for (const result of results) {
+ if (result.status !== 'fulfilled') continue;
+ for (const article of result.value) {
+ const sentiment = scoreSentiment(article.title);
+ await kenQ(`
+ INSERT INTO ken_sentiment (source, subreddit, keyword, post_title, post_url, score, sentiment_score, raw_text)
+ VALUES ($1, $2, 'news', $3, $4, 0, $5, '')
+ ON CONFLICT DO NOTHING
+ `, [article.source.toLowerCase().replace(/\s+/g, '_'), article.source, article.title, article.url, sentiment]);
+ newsStored++;
+ }
+ }
+ await new Promise(r => setTimeout(r, 300));
+ }
+ totalPosts += newsStored;
+ console.log(`[Ken] News channels: ${newsStored} articles from ${NEWS_FEEDS.length} feeds`);
+ } catch (e) {
+ console.log(`[Ken] News channels failed: ${e.message}`);
+ }
+ logMemory('after-news');
+ if (global.gc) global.gc();
+
+ // ── Metaculus (prediction market community consensus) ──
+ try {
+ const metaQuestions = await scrapeMetaculus();
+ for (const mq of metaQuestions) {
+ const sentiment = scoreSentiment(mq.title);
+ const predText = mq.community_prediction ? `Community: ${Math.round(mq.community_prediction * 100)}%` : '';
+ await kenQ(`
+ INSERT INTO ken_sentiment (source, subreddit, keyword, post_title, post_url, score, num_comments, sentiment_score, raw_text)
+ VALUES ('metaculus', 'metaculus', 'predictions', $1, $2, $3, $4, $5, $6)
+ ON CONFLICT DO NOTHING
+ `, [mq.title, mq.url, mq.num_predictions || 0, 0, sentiment, predText]);
+ totalPosts++;
+ }
+ console.log(`[Ken] Metaculus: ${metaQuestions.length} predictions`);
+ } catch (e) {
+ console.log(`[Ken] Metaculus failed: ${e.message}`);
+ }
+
+ // ── Manifold Markets (cross-reference prediction probabilities) ──
+ let manifoldTotal = 0;
+ try {
+ const manifoldQueries = ['trump', 'fed rate', 'election 2028', 'ukraine', 'tariff'];
+ const manifoldMkts = await scrapeManifold(manifoldQueries);
+ for (const m of manifoldMkts) {
+ const sentiment = scoreSentiment(m.title);
+ await kenQ(`
+ INSERT INTO ken_sentiment (source, subreddit, keyword, post_title, post_url, score, num_comments, sentiment_score, raw_text)
+ VALUES ('manifold', 'manifold', $1, $2, $3, $4, 0, $5, $6)
+ ON CONFLICT DO NOTHING
+ `, [m.source, m.title, m.url, m.volume || 0, sentiment, `prob:${m.probability}% vol:${m.volume}`]);
+ manifoldTotal++;
+ }
+ } catch {}
+ console.log(`[Ken] Manifold Markets: ${manifoldTotal} prediction markets`);
+
+ // ── Kalshi & Polymarket Reddit search (community sentiment on specific trades) ──
+ let predMarketRedditTotal = 0;
+ const pmSearchTerms = ['arbitrage', 'free money', 'mispriced', 'edge'];
+ for (const term of pmSearchTerms) {
+ for (const sub of ['Kalshi', 'Polymarket']) {
+ try {
+ const posts = await scrapeReddit(sub, term, 5);
+ for (const post of posts) {
+ const sentiment = scoreSentiment(post.title);
+ await kenQ(`
+ INSERT INTO ken_sentiment (source, subreddit, keyword, post_title, post_url, score, num_comments, sentiment_score, raw_text)
+ VALUES ('reddit_predmkt', $1, $2, $3, $4, $5, $6, $7, '')
+ ON CONFLICT DO NOTHING
+ `, [sub, term, post.title, post.url, post.score || 0, post.num_comments || 0, sentiment]);
+ predMarketRedditTotal++;
+ }
+ } catch {}
+ }
+ await new Promise(r => setTimeout(r, 2000));
+ }
+ console.log(`[Ken] Prediction market Reddit: ${predMarketRedditTotal} posts from r/Kalshi + r/Polymarket`);
+ if (global.gc) global.gc();
+
+ // ── GDELT TV News (CNN, Fox closed captions) ──
+ const tvStations = ['CNN', 'FOXNEWS'];
+ const tvQueries = ['trump', 'tariff', 'ukraine', 'election'];
+ let tvTotal = 0;
+ for (const station of tvStations) {
+ for (const tq of tvQueries) {
+ try {
+ const clips = await scrapeGDELTtv(tq, station, 5);
+ for (const clip of clips) {
+ if (clip.title && clip.title.length > 15) {
+ const sentiment = scoreSentiment(clip.title);
+ await kenQ(`
+ INSERT INTO ken_sentiment (source, subreddit, keyword, post_title, post_url, score, sentiment_score, raw_text)
+ VALUES ('tv_news', $1, $2, $3, $4, 0, $5, $6)
+ ON CONFLICT DO NOTHING
+ `, [clip.source || station, tq, clip.title.substring(0, 500), clip.url, sentiment, clip.show || '']);
+ tvTotal++;
+ }
+ }
+ } catch {}
+ await new Promise(r => setTimeout(r, 500));
+ }
+ }
+ console.log(`[Ken] GDELT TV: ${tvTotal} clips from ${tvStations.length} stations`);
+
+ // ── YouTube News Channels (CNN, MSNBC, Fox, Bloomberg, CNBC, etc.) ──
+ try {
+ const ytVideos = await scrapeYouTubeRSS();
+ let ytStored = 0;
+ for (const video of ytVideos) {
+ const sentiment = scoreSentiment(video.title);
+ await kenQ(`
+ INSERT INTO ken_sentiment (source, subreddit, keyword, post_title, post_url, score, sentiment_score, raw_text)
+ VALUES ('youtube_news', $1, 'video', $2, $3, 0, $4, '')
+ ON CONFLICT DO NOTHING
+ `, [video.source, video.title, video.url, sentiment]);
+ ytStored++;
+ }
+ totalPosts += ytStored;
+ console.log(`[Ken] YouTube News: ${ytStored} videos from 9 channels`);
+ } catch (e) {
+ console.log(`[Ken] YouTube News failed: ${e.message}`);
+ }
+ if (global.gc) global.gc();
+
+ // ── Lemmy (federated Reddit — public API, no auth) ──
+ let lemmyTotal = 0;
+ try {
+ const lemmyPosts = await scrapeLemmy('Hot', 25);
+ for (const p of lemmyPosts) {
+ const sentiment = scoreSentiment(p.title);
+ await kenQ(`
+ INSERT INTO ken_sentiment (source, subreddit, keyword, post_title, post_url, score, num_comments, sentiment_score, raw_text)
+ VALUES ('lemmy', $1, 'hot', $2, $3, $4, $5, $6, '')
+ ON CONFLICT DO NOTHING
+ `, [p.source, p.title, p.url, p.score || 0, p.num_comments || 0, sentiment]);
+ lemmyTotal++;
+ }
+ } catch {}
+ console.log(`[Ken] Lemmy: ${lemmyTotal} posts`);
+
+ // ── Lobsters (tech/policy news — public JSON API) ──
+ let lobstersTotal = 0;
+ try {
+ const stories = await scrapeLobsters(25);
+ for (const s of stories) {
+ const sentiment = scoreSentiment(s.title);
+ await kenQ(`
+ INSERT INTO ken_sentiment (source, subreddit, keyword, post_title, post_url, score, num_comments, sentiment_score, raw_text)
+ VALUES ('lobsters', $1, $2, $3, $4, $5, $6, $7, '')
+ ON CONFLICT DO NOTHING
+ `, [s.author || 'lobsters', s.tags || 'tech', s.title, s.url, s.score || 0, s.num_comments || 0, sentiment]);
+ lobstersTotal++;
+ }
+ } catch {}
+ console.log(`[Ken] Lobsters: ${lobstersTotal} stories`);
+
+ // ── Tildes (curated discussion — RSS) ──
+ let tildesTotal = 0;
+ try {
+ const tildesPosts = await scrapeTildes();
+ for (const p of tildesPosts) {
+ const sentiment = scoreSentiment(p.title);
+ await kenQ(`
+ INSERT INTO ken_sentiment (source, subreddit, keyword, post_title, post_url, score, sentiment_score, raw_text)
+ VALUES ('tildes', 'tildes', 'discussion', $1, $2, 0, $3, '')
+ ON CONFLICT DO NOTHING
+ `, [p.title, p.url, sentiment]);
+ tildesTotal++;
+ }
+ } catch {}
+ console.log(`[Ken] Tildes: ${tildesTotal} discussions`);
+
+ // ── Bluesky (trending feeds — getFeed API) ──
+ let bskyTotal = 0;
+ try {
+ const posts = await scrapeBluesky();
+ for (const p of posts) {
+ if ((p.score || 0) > 2 || (p.num_comments || 0) > 1 || p.title.length > 30) {
+ const sentiment = scoreSentiment(p.title);
+ await kenQ(`
+ INSERT INTO ken_sentiment (source, subreddit, keyword, post_title, post_url, score, num_comments, sentiment_score, raw_text)
+ VALUES ('bluesky', $1, $2, $3, $4, $5, $6, $7, '')
+ ON CONFLICT DO NOTHING
+ `, [p.author || 'bluesky', p.source || 'trending', p.title, p.url, p.score || 0, p.num_comments || 0, sentiment]);
+ bskyTotal++;
+ }
+ }
+ } catch {}
+ console.log(`[Ken] Bluesky: ${bskyTotal} posts`);
+
+ // ── Mastodon/Fediverse trending ──
+ try {
+ const mastodonPosts = await scrapeMastodon();
+ let mastoTotal = 0;
+ for (const p of mastodonPosts) {
+ const sentiment = scoreSentiment(p.title);
+ await kenQ(`
+ INSERT INTO ken_sentiment (source, subreddit, keyword, post_title, post_url, score, num_comments, sentiment_score, raw_text)
+ VALUES ('mastodon', $1, 'trending', $2, $3, $4, $5, $6, '')
+ ON CONFLICT DO NOTHING
+ `, [p.source, p.title, p.url, p.score || 0, p.num_comments || 0, sentiment]);
+ mastoTotal++;
+ }
+ totalPosts += mastoTotal;
+ console.log(`[Ken] Mastodon: ${mastoTotal} trending`);
+ } catch (e) {
+ console.log(`[Ken] Mastodon failed: ${e.message}`);
+ }
+
+ totalPosts += tvTotal + lemmyTotal + lobstersTotal + tildesTotal + bskyTotal;
+ totalPosts += manifoldTotal + predMarketRedditTotal;
+
+ // ── PredictIt (cross-reference prediction market) ──
+ let predictItTotal = 0;
+ try {
+ const piMarkets = await scrapePredictIt();
+ for (const m of piMarkets) {
+ const sentiment = scoreSentiment(m.title);
+ await kenQ(`
+ INSERT INTO ken_sentiment (source, subreddit, keyword, post_title, post_url, score, num_comments, sentiment_score, raw_text)
+ VALUES ('predictit', 'predictit', 'market', $1, $2, $3, $4, $5, $6)
+ ON CONFLICT DO NOTHING
+ `, [m.title, m.url, m.score, m.num_comments || 0, sentiment, m.extra || '']);
+ predictItTotal++;
+ }
+ totalPosts += predictItTotal;
+ console.log(`[Ken] PredictIt: ${predictItTotal} markets`);
+ } catch (e) {
+ console.log(`[Ken] PredictIt failed: ${e.message}`);
+ }
+
+ // ── FRED Economic Indicators (real data for economic markets) ──
+ let fredTotal = 0;
+ try {
+ const fredData = await scrapeFredIndicators();
+ for (const ind of fredData) {
+ await kenQ(`
+ INSERT INTO ken_sentiment (source, subreddit, keyword, post_title, post_url, score, sentiment_score, raw_text)
+ VALUES ('fred_economic', 'fred', $1, $2, $3, $4, 0, '')
+ ON CONFLICT DO NOTHING
+ `, [ind.keyword, ind.title, ind.url, ind.score]);
+ fredTotal++;
+ }
+ totalPosts += fredTotal;
+ console.log(`[Ken] FRED Economic: ${fredTotal} indicators`);
+ } catch (e) {
+ console.log(`[Ken] FRED failed: ${e.message}`);
+ }
+
+ // ── NWS Active Weather Alerts (severe weather data for weather markets) ──
+ let nwsAlertTotal = 0;
+ try {
+ const alerts = await scrapeNWSAlerts();
+ for (const alert of alerts) {
+ const sentiment = scoreSentiment(alert.title);
+ await kenQ(`
+ INSERT INTO ken_sentiment (source, subreddit, keyword, post_title, post_url, score, num_comments, sentiment_score, raw_text)
+ VALUES ('nws_alerts', 'weather', $1, $2, $3, $4, 0, $5, '')
+ ON CONFLICT DO NOTHING
+ `, [alert.keyword, alert.title, alert.url, alert.score, sentiment]);
+ nwsAlertTotal++;
+ }
+ totalPosts += nwsAlertTotal;
+ console.log(`[Ken] NWS Alerts: ${nwsAlertTotal} active alerts`);
+ } catch (e) {
+ console.log(`[Ken] NWS Alerts failed: ${e.message}`);
+ }
+
+ // ── GovTrack Congressional Votes (legislation for political markets) ──
+ let govTrackTotal = 0;
+ try {
+ const votes = await scrapeGovTrack();
+ for (const v of votes) {
+ const sentiment = scoreSentiment(v.title);
+ await kenQ(`
+ INSERT INTO ken_sentiment (source, subreddit, keyword, post_title, post_url, score, num_comments, sentiment_score, raw_text)
+ VALUES ('govtrack', 'congress', $1, $2, $3, $4, $5, $6, '')
+ ON CONFLICT DO NOTHING
+ `, [v.keyword, v.title, v.url, v.score, v.num_comments || 0, sentiment]);
+ govTrackTotal++;
+ }
+ totalPosts += govTrackTotal;
+ console.log(`[Ken] GovTrack: ${govTrackTotal} congressional votes`);
+ } catch (e) {
+ console.log(`[Ken] GovTrack failed: ${e.message}`);
+ }
+
+ // ── Twitter/X via Nitter (public sentiment, no auth needed) ──
+ let nitterTotal = 0;
+ try {
+ const tweets = await scrapeNitterTrending();
+ for (const t of tweets) {
+ const sentiment = scoreSentiment(t.title);
+ await kenQ(`
+ INSERT INTO ken_sentiment (source, subreddit, keyword, post_title, post_url, score, num_comments, sentiment_score, raw_text)
+ VALUES ('twitter_nitter', 'twitter', $1, $2, $3, 0, 0, $4, '')
+ ON CONFLICT DO NOTHING
+ `, [t.keyword, t.title, t.url, sentiment]);
+ nitterTotal++;
+ }
+ totalPosts += nitterTotal;
+ console.log(`[Ken] Twitter/Nitter: ${nitterTotal} tweets`);
+ } catch (e) {
+ console.log(`[Ken] Twitter/Nitter failed: ${e.message}`);
+ }
+
+ // ── Discord (Kalshi, Polymarket, Prediction Markets servers) ──
+ let discordTotal = 0;
+ try {
+ const discordMessages = await scrapeDiscord(30);
+ for (const msg of discordMessages) {
+ const sentiment = scoreSentiment(msg.title);
+ await kenQ(`
+ INSERT INTO ken_sentiment (source, subreddit, keyword, post_title, post_url, score, num_comments, sentiment_score, raw_text)
+ VALUES ('discord', $1, $2, $3, $4, $5, $6, $7, $8)
+ ON CONFLICT DO NOTHING
+ `, [
+ msg.source, msg.channel || 'general', msg.title.substring(0, 500),
+ msg.url, msg.score || 0, msg.num_comments || 0, sentiment,
+ (msg.author || '').substring(0, 200),
+ ]);
+ discordTotal++;
+ }
+ totalPosts += discordTotal;
+ console.log(`[Ken] Discord: ${discordTotal} messages`);
+ } catch (e) {
+ console.log(`[Ken] Discord failed: ${e.message}`);
+ }
+ if (global.gc) global.gc();
+
+ logMemory('sweep-end');
+ if (global.gc) global.gc();
+ console.log(`[Ken] ═══ FULL SWEEP: ${totalPosts} items (Reddit, HN, ${NEWS_FEEDS.length} feeds, TV, YT, Manifold, r/Kalshi, r/Polymarket, Lemmy, Lobsters, Tildes, Bluesky, Mastodon, Metaculus, PredictIt, FRED, NWS Alerts, GovTrack, Twitter, Discord) ═══`);
+ return totalPosts;
+ } catch (e) {
+ console.error('[Ken] Intelligence sweep error:', e.message);
+ logMemory('sweep-error');
+ return 0;
+ }
+}
+
+// ══════════════════════════════════════════════════════════════════════════════
+// SIGNAL PIPELINE: News → Sentiment → Event Map → Probability → Signals → Risk
+// Pipeline: narrative shifts → probability inference → edge detection
+// ══════════════════════════════════════════════════════════════════════════════
+
+// ── Enhanced Event-Specific Sentiment Engine ──
+// Unlike scoreSentiment() which is general, this maps headlines to specific market directions
+const EVENT_SENTIMENT_RULES = [
+ // Weather markets
+ { pattern: /hurricane|tropical storm|cyclone/i, category: 'weather', direction: 'severity', boost: 0.3 },
+ { pattern: /category\s*[3-5]|major hurricane|extreme/i, category: 'weather', direction: 'severity', boost: 0.5 },
+ { pattern: /weakens|dissipates|downgrade/i, category: 'weather', direction: 'severity', boost: -0.4 },
+ { pattern: /record heat|heat wave|above normal/i, category: 'weather', direction: 'temperature_high', boost: 0.4 },
+ { pattern: /cold snap|polar vortex|below normal|freeze/i, category: 'weather', direction: 'temperature_low', boost: 0.4 },
+ { pattern: /heavy rain|flood|rainfall record/i, category: 'weather', direction: 'precipitation_high', boost: 0.4 },
+ { pattern: /drought|dry spell|no rain/i, category: 'weather', direction: 'precipitation_low', boost: 0.4 },
+ // Political markets
+ { pattern: /resign|step down|quit|fired/i, category: 'politics', direction: 'negative', boost: 0.5 },
+ { pattern: /appointed|confirmed|sworn in|nominated/i, category: 'politics', direction: 'positive', boost: 0.4 },
+ { pattern: /impeach|investigation|scandal|indicted/i, category: 'politics', direction: 'negative', boost: 0.4 },
+ { pattern: /leading|ahead|polling|surge in polls/i, category: 'politics', direction: 'positive', boost: 0.3 },
+ { pattern: /trailing|behind|falling|losing ground/i, category: 'politics', direction: 'negative', boost: 0.3 },
+ { pattern: /shutdown|deadlock|stalemate/i, category: 'politics', direction: 'shutdown_yes', boost: 0.5 },
+ { pattern: /deal reached|agreement|bipartisan|passed/i, category: 'politics', direction: 'shutdown_no', boost: -0.4 },
+ // Economic markets
+ { pattern: /rate cut|dovish|easing/i, category: 'economics', direction: 'rate_down', boost: 0.4 },
+ { pattern: /rate hike|hawkish|tightening/i, category: 'economics', direction: 'rate_up', boost: 0.4 },
+ { pattern: /inflation.*(?:hot|higher|above|surge|accelerat)/i, category: 'economics', direction: 'inflation_up', boost: 0.4 },
+ { pattern: /inflation.*(?:cool|lower|below|slow|deceler)/i, category: 'economics', direction: 'inflation_down', boost: 0.4 },
+ { pattern: /recession|contraction|GDP.*(?:negative|shrink)/i, category: 'economics', direction: 'recession_yes', boost: 0.5 },
+ { pattern: /growth|expansion|GDP.*(?:beat|strong|positive)/i, category: 'economics', direction: 'recession_no', boost: -0.4 },
+ { pattern: /jobs.*(?:beat|strong|added more)/i, category: 'economics', direction: 'jobs_strong', boost: 0.3 },
+ { pattern: /jobs.*(?:miss|weak|fewer)/i, category: 'economics', direction: 'jobs_weak', boost: 0.3 },
+ // Crypto markets
+ { pattern: /bitcoin.*(?:new high|surge|rally|breakout|100k|150k)/i, category: 'crypto', direction: 'btc_up', boost: 0.4 },
+ { pattern: /bitcoin.*(?:crash|plunge|selloff|bear)/i, category: 'crypto', direction: 'btc_down', boost: 0.4 },
+ { pattern: /SEC.*(?:approve|green light)/i, category: 'crypto', direction: 'btc_up', boost: 0.3 },
+ { pattern: /SEC.*(?:reject|deny|sue)/i, category: 'crypto', direction: 'btc_down', boost: 0.3 },
+ // Sports/entertainment
+ { pattern: /favou?rite|odds.*increase|bet.*heavy/i, category: 'sports', direction: 'favourite_stronger', boost: 0.3 },
+ { pattern: /upset|underdog|surprise/i, category: 'sports', direction: 'favourite_weaker', boost: 0.3 },
+ { pattern: /injured|out for|suspended|DNP/i, category: 'sports', direction: 'team_weaker', boost: 0.4 },
+ // Space/tech
+ { pattern: /launch.*(?:success|orbit|nominal)/i, category: 'space', direction: 'launch_success', boost: 0.5 },
+ { pattern: /launch.*(?:scrub|delay|abort|fail)/i, category: 'space', direction: 'launch_fail', boost: 0.5 },
+ // Geopolitics
+ { pattern: /ceasefire|peace.*(?:deal|talks|agreement)/i, category: 'geopolitics', direction: 'de_escalation', boost: 0.5 },
+ { pattern: /escalat|offensive|invasion|attack|strike/i, category: 'geopolitics', direction: 'escalation', boost: 0.4 },
+];
+
+function scoreEventSentiment(headline, marketTitle = '') {
+ const text = `${headline} ${marketTitle}`.toLowerCase();
+ const result = {
+ sentiment: 0,
+ confidence: 0,
+ magnitude: 0,
+ category: 'general',
+ direction: 'neutral',
+ matchedRules: [],
+ };
+
+ // Apply rule-based event-specific scoring
+ for (const rule of EVENT_SENTIMENT_RULES) {
+ if (rule.pattern.test(text)) {
+ result.sentiment += rule.boost;
+ result.magnitude += Math.abs(rule.boost);
+ result.category = rule.category;
+ result.direction = rule.direction;
+ result.matchedRules.push(rule.direction);
+ }
+ }
+
+ // Certainty language modifiers
+ const certainWords = /confirm|official|announce|breaking|just.*happen/i;
+ const uncertainWords = /may|might|could|rumor|unconfirm|speculat|sources say/i;
+ if (certainWords.test(text)) { result.confidence += 0.3; result.magnitude *= 1.2; }
+ if (uncertainWords.test(text)) { result.confidence -= 0.2; result.magnitude *= 0.7; }
+
+ // Multiple source agreement boosts confidence
+ if (result.matchedRules.length > 1) result.confidence += 0.15;
+
+ // Normalize
+ result.sentiment = Math.max(-1, Math.min(1, result.sentiment));
+ result.confidence = Math.max(0, Math.min(1, 0.5 + result.confidence)); // base confidence 0.5
+ result.magnitude = Math.min(1, result.magnitude);
+
+ return result;
+}
+
+// ── Event Mapper: Map news entities → Kalshi market tickers ──
+// Uses keyword-based + fuzzy matching to connect news to specific contracts
+const MARKET_CATEGORY_KEYWORDS = {
+ // Weather
+ 'temperature': ['temperature', 'temp', 'heat', 'cold', 'warm', 'degree', 'fahrenheit', 'celsius'],
+ 'hurricane': ['hurricane', 'tropical', 'cyclone', 'storm', 'named storm'],
+ 'rainfall': ['rain', 'rainfall', 'precipitation', 'flood', 'drought', 'inches'],
+ // Politics
+ 'election': ['election', 'vote', 'ballot', 'primary', 'nominee', 'candidate', 'poll'],
+ 'government': ['resign', 'cabinet', 'secretary', 'appointment', 'nomination', 'impeach'],
+ 'legislation': ['bill', 'act', 'congress', 'senate', 'house', 'passed', 'shutdown'],
+ // Economics
+ 'fed_rate': ['federal reserve', 'fed rate', 'interest rate', 'fomc', 'rate cut', 'rate hike', 'powell'],
+ 'inflation': ['cpi', 'inflation', 'consumer price', 'pce', 'core inflation'],
+ 'gdp': ['gdp', 'gross domestic', 'economic growth', 'recession', 'expansion'],
+ 'jobs': ['jobs report', 'unemployment', 'nonfarm', 'payroll', 'jobless claims'],
+ // Crypto
+ 'bitcoin': ['bitcoin', 'btc', 'cryptocurrency', 'crypto'],
+ 'ethereum': ['ethereum', 'eth', 'ether'],
+ // Space
+ 'spacex': ['spacex', 'falcon', 'starship', 'rocket launch', 'orbit'],
+ 'nasa': ['nasa', 'artemis', 'moon', 'mars mission'],
+};
+
+// Map ticker suffixes to searchable names for multi-outcome events
+const TICKER_ENTITY_MAP = {
+ // KXCABOUT - Cabinet members
+ 'RFK': ['rfk', 'kennedy', 'robert kennedy', 'rfk jr', 'health and human'],
+ 'KNOE': ['noem', 'kristi noem', 'homeland security'],
+ 'SDUF': ['duffy', 'sean duffy', 'transportation'],
+ 'BROL': ['rollins', 'brooke rollins', 'agriculture'],
+ 'JRAT': ['ratcliffe', 'john ratcliffe', 'cia director'],
+ 'SBES': ['bessent', 'scott bessent', 'treasury secretary'],
+ 'MRUB': ['rubio', 'marco rubio', 'state department', 'secretary of state'],
+ 'PHEG': ['hegseth', 'pete hegseth', 'defense secretary'],
+ 'TGAB': ['gabbard', 'tulsi gabbard', 'intelligence director'],
+ 'MWAL': ['waltz', 'mike waltz', 'national security'],
+ 'HLUT': ['lutnick', 'howard lutnick', 'commerce secretary'],
+ 'DBUR': ['burgum', 'doug burgum', 'interior secretary'],
+ 'CWRI': ['chris wright', 'energy secretary'],
+ 'LZEL': ['zeldin', 'lee zeldin', 'epa administrator'],
+ 'DCOL': ['collins', 'doug collins', 'veterans affairs'],
+ 'LMCM': ['mcmahon', 'linda mcmahon', 'education secretary'],
+ 'PBON': ['bondi', 'pam bondi', 'attorney general'],
+ 'RVOU': ['vought', 'russell vought', 'omb director'],
+ 'STUR': ['turner', 'scott turner', 'hud secretary'],
+ 'LCDR': ['cruz', 'linda cruz', 'sba administrator'],
+ 'MKRA': ['kratsios', 'michael kratsios'],
+ 'SWIL': ['wilson', 'sean wilson'],
+ // KXPRESPERSON - 2028 Presidential election
+ 'DTRU': ['trump', 'donald trump', 'president trump', 'former president trump'],
+ 'DTRUJR': ['trump jr', 'donald trump jr', 'don jr', 'trump junior'],
+ 'RDES': ['desantis', 'ron desantis', 'florida governor'],
+ 'JVAN': ['vance', 'jd vance', 'vice president vance', 'j.d. vance'],
+ 'GYOU': ['youngkin', 'glenn youngkin', 'virginia governor'],
+ // KXFEDCHAIRNOM - Fed Chair nominees
+ 'JS': ['dimon', 'jamie dimon'],
+ 'KW': ['warsh', 'kevin warsh'],
+ 'KH': ['hassett', 'kevin hassett'],
+ 'CWAL': ['waller', 'chris waller', 'christopher waller'],
+ 'MBOW': ['bowman', 'michelle bowman'],
+};
+
+function extractMarketEntity(market) {
+ // Extract ticker suffix for entity lookup first (most reliable)
+ const parts = market.ticker.split('-');
+ const suffix = parts[parts.length - 1];
+ if (TICKER_ENTITY_MAP[suffix]) return TICKER_ENTITY_MAP[suffix];
+ // Try subtitle only if it's a real description (not just the ticker repeated)
+ if (market.subtitle && market.subtitle !== market.ticker && !market.subtitle.startsWith('KX')) {
+ return market.subtitle.toLowerCase().split(/[\s\-]+/).filter(w => w.length > 2);
+ }
+ // Try the yes_sub_title field
+ if (market.yes_sub_title && market.yes_sub_title !== market.ticker) {
+ return market.yes_sub_title.toLowerCase().split(/[\s\-]+/).filter(w => w.length > 2);
+ }
+ return [];
+}
+
+function isMultiOutcomeEvent(ticker) {
+ // Multi-outcome events have a common prefix followed by person/answer suffix
+ // e.g., KXCABOUT-29JAN-RFK, KXCABOUT-29JAN-KNOE all share KXCABOUT-29JAN
+ const parts = ticker.split('-');
+ return parts.length >= 3; // Event prefix + date + answer
+}
+
+function getEventPrefix(ticker) {
+ const parts = ticker.split('-');
+ if (parts.length >= 3) return parts.slice(0, -1).join('-');
+ return ticker;
+}
+
+function mapNewsToMarkets(headline, activeMarkets) {
+ const headlineLower = headline.toLowerCase();
+ const matches = [];
+
+ // Step 1: Identify which categories the headline relates to
+ const relevantCategories = [];
+ for (const [category, keywords] of Object.entries(MARKET_CATEGORY_KEYWORDS)) {
+ for (const kw of keywords) {
+ if (headlineLower.includes(kw)) {
+ relevantCategories.push(category);
+ break;
+ }
+ }
+ }
+
+ // Step 2: Group markets by event to detect multi-outcome events
+ const eventGroups = {};
+ for (const market of activeMarkets) {
+ const prefix = getEventPrefix(market.ticker);
+ if (!eventGroups[prefix]) eventGroups[prefix] = [];
+ eventGroups[prefix].push(market);
+ }
+
+ // Step 3: Find matching Kalshi markets by title/subtitle keywords
+ for (const market of activeMarkets) {
+ const marketText = `${market.title} ${market.subtitle || ''} ${market.yes_sub_title || ''}`.toLowerCase();
+ let matchScore = 0;
+
+ // Direct keyword overlap
+ const headlineWords = headlineLower.split(/\s+/).filter(w => w.length > 3);
+ for (const word of headlineWords) {
+ if (marketText.includes(word)) matchScore += 1;
+ }
+
+ // Category match bonus
+ for (const cat of relevantCategories) {
+ const catKws = MARKET_CATEGORY_KEYWORDS[cat];
+ if (catKws.some(kw => marketText.includes(kw))) matchScore += 2;
+ }
+
+ // Entity matching (city names, person names, etc.)
+ const cities = ['phoenix', 'houston', 'miami', 'chicago', 'new york', 'los angeles', 'atlanta', 'dallas', 'denver', 'seattle', 'boston', 'detroit', 'minneapolis', 'philadelphia'];
+ for (const city of cities) {
+ if (headlineLower.includes(city) && marketText.includes(city)) matchScore += 5;
+ }
+
+ // Political figure matching
+ const figures = ['trump', 'biden', 'harris', 'desantis', 'newsom', 'vance', 'powell', 'yellen'];
+ for (const fig of figures) {
+ if (headlineLower.includes(fig) && marketText.includes(fig)) matchScore += 5;
+ }
+
+ // MULTI-OUTCOME EVENT HANDLING: For events with multiple answer markets,
+ // require headline to mention the specific answer entity, not just the general topic
+ const eventPrefix = getEventPrefix(market.ticker);
+ const siblings = eventGroups[eventPrefix] || [];
+ if (siblings.length > 1 && isMultiOutcomeEvent(market.ticker)) {
+ const entityTerms = extractMarketEntity(market);
+ const entityMatch = entityTerms.some(term => headlineLower.includes(term));
+ if (entityMatch) {
+ matchScore += 8; // Strong boost for specific entity match
+ } else {
+ // Headline mentions the topic but NOT this specific answer — reject entirely
+ // With 20+ siblings, even small scores cause massive clustering
+ matchScore = 0;
+ }
+ }
+
+ if (matchScore >= 3) {
+ matches.push({ market, matchScore });
+ }
+ }
+
+ // Sort by match score descending
+ matches.sort((a, b) => b.matchScore - a.matchScore);
+ return matches.slice(0, 5); // Top 5 matches
+}
+
+// ── Probability Shift Model (Bayesian Update) ──
+// adjustedProb = priorProb + (sentiment * weight * confidence)
+// With decay for older signals, source diversity bonus, and category-specific weights
+const CATEGORY_SENTIMENT_WEIGHTS = {
+ politics: 0.18, // Political events move markets fast
+ economics: 0.16, // Economic data is highly impactful
+ crypto: 0.22, // Crypto is volatile, sentiment-driven
+ weather: 0.10, // Weather has model data, less sentiment-dependent
+ geopolitics: 0.20, // Geopolitical events create large moves
+ sports: 0.12, // Sports have existing odds infrastructure
+ space: 0.14, // Launch outcomes are binary
+ general: 0.12, // Default
+};
+
+function calculateProbabilityShift(priorProb, sentimentSignals) {
+ if (!sentimentSignals.length) return { adjustedProb: priorProb, impact: 0, numArticles: 0, agreement: 0, sourceDiversity: 0 };
+
+ const RECENCY_DECAY = 0.85; // Faster decay — old news matters less
+ const AGREEMENT_BONUS = 1.5; // Stronger bonus for agreement
+ const DISAGREEMENT_PENALTY = 0.3; // Stronger penalty for mixed signals
+
+ let totalImpact = 0;
+ let totalWeight = 0;
+ const now = Date.now();
+
+ // Sort by recency
+ const sorted = [...sentimentSignals].sort((a, b) => (b.timestamp || 0) - (a.timestamp || 0));
+
+ // Calculate source diversity (unique sources boost signal)
+ const uniqueSources = new Set(sorted.map(s => s.source));
+ const sourceDiversity = Math.min(1, uniqueSources.size / 4); // 4+ unique sources = max diversity
+
+ for (const sig of sorted) {
+ const hoursAgo = Math.max(0, (now - (sig.timestamp || now)) / 3600000);
+ const recencyWeight = Math.pow(RECENCY_DECAY, hoursAgo);
+ // Use category-specific weight instead of flat 0.08
+ const catWeight = CATEGORY_SENTIMENT_WEIGHTS[sig.category] || CATEGORY_SENTIMENT_WEIGHTS.general;
+ // Magnitude amplifier: strong signals (|sentiment| > 0.3) get more weight
+ const magnitudeBoost = 1 + Math.min(0.5, (sig.magnitude || 0) * 0.8);
+ const impact = sig.sentiment * catWeight * sig.confidence * recencyWeight * magnitudeBoost;
+ totalImpact += impact;
+ totalWeight += recencyWeight * sig.confidence;
+ }
+
+ // Source diversity bonus: multiple independent sources confirming = stronger signal
+ totalImpact *= (1 + sourceDiversity * 0.4);
+
+ // Check agreement: if most signals agree on direction, boost; if mixed, penalize
+ const posSignals = sorted.filter(s => s.sentiment > 0).length;
+ const negSignals = sorted.filter(s => s.sentiment < 0).length;
+ const total = posSignals + negSignals;
+ if (total >= 2) {
+ const agreementRatio = Math.max(posSignals, negSignals) / total;
+ if (agreementRatio > 0.8) totalImpact *= AGREEMENT_BONUS; // Strong agreement
+ else if (agreementRatio > 0.6) totalImpact *= 1.1; // Mild agreement
+ else totalImpact *= DISAGREEMENT_PENALTY; // Mixed signals — dampen hard
+ }
+
+ // Diminishing returns: each additional article adds less new information
+ // 1 article = 100%, 4 = 50%, 9 = 33%, 16 = 25%
+ const articleDiminishing = Math.sqrt(sorted.length) / sorted.length;
+ totalImpact *= articleDiminishing;
+
+ // Prior-anchored capping: prevent unrealistic shifts on low-probability markets
+ // A 4% market shouldn't jump to 60% from sentiment alone; cap shift at 5x prior or 15%, whichever is higher
+ const maxShift = Math.max(0.15, priorProb * 5);
+ totalImpact = Math.sign(totalImpact) * Math.min(Math.abs(totalImpact), maxShift);
+
+ // Clamp adjusted probability to [0.01, 0.99]
+ const adjustedProb = Math.max(0.01, Math.min(0.99, priorProb + totalImpact));
+
+ return {
+ adjustedProb,
+ impact: totalImpact,
+ numArticles: sorted.length,
+ agreement: total > 0 ? Math.max(posSignals, negSignals) / total : 0,
+ sourceDiversity,
+ };
+}
+
+// ── Risk Engine ──
+const RISK_LIMITS = {
+ maxExposurePerMarket: 5000, // cents ($50)
+ maxExposurePerTheme: 15000, // cents ($150)
+ maxTotalExposure: 50000, // cents ($500)
+ maxContractsPerMarket: 25,
+ minEdgeThreshold: 0.03, // 3% edge minimum (lowered from 5% — entity-specific matching yields smaller edges)
+ maxDailyLoss: 5000, // cents ($50)
+ cooldownAfterLoss: 30, // minutes
+ timeDecayPenalty: 0.02, // Reduce edge by 2% per hour of signal age
+ minLiquidity: 100, // Minimum 24h volume
+};
+
+function riskCheck(signal, currentExposure = {}) {
+ const reasons = [];
+ let approved = true;
+
+ // Edge threshold
+ if (Math.abs(signal.expectedEdge) < RISK_LIMITS.minEdgeThreshold) {
+ approved = false;
+ reasons.push(`Edge ${(signal.expectedEdge * 100).toFixed(1)}% below ${(RISK_LIMITS.minEdgeThreshold * 100)}% threshold`);
+ }
+
+ // Market exposure
+ const marketExposure = currentExposure[signal.marketId] || 0;
+ if (marketExposure >= RISK_LIMITS.maxExposurePerMarket) {
+ approved = false;
+ reasons.push(`Market exposure $${(marketExposure / 100).toFixed(2)} at limit`);
+ }
+
+ // Liquidity check
+ if ((signal.volume24h || 0) < RISK_LIMITS.minLiquidity) {
+ approved = false;
+ reasons.push(`Low liquidity: ${signal.volume24h || 0} < ${RISK_LIMITS.minLiquidity} volume`);
+ }
+
+ // Time decay — use absolute edge values so BUY_NO signals aren't unfairly penalized
+ const signalAgeHours = (Date.now() - (signal.timestamp || Date.now())) / 3600000;
+ const absEdge = Math.abs(signal.expectedEdge);
+ const decayedAbsEdge = absEdge - (RISK_LIMITS.timeDecayPenalty * signalAgeHours);
+ if (decayedAbsEdge < RISK_LIMITS.minEdgeThreshold) {
+ approved = false;
+ reasons.push(`Edge decayed from ${(absEdge * 100).toFixed(1)}% to ${(decayedAbsEdge * 100).toFixed(1)}%`);
+ }
+
+ // Size recommendation based on edge and confidence
+ let sizeRecommendation = 1;
+ if (approved) {
+ const edgeFactor = Math.min(3, Math.abs(signal.expectedEdge) / RISK_LIMITS.minEdgeThreshold);
+ const confFactor = signal.confidence || 0.5;
+ sizeRecommendation = Math.max(1, Math.min(RISK_LIMITS.maxContractsPerMarket, Math.floor(edgeFactor * confFactor * 10)));
+ }
+
+ return { approved, reasons, sizeRecommendation, decayedEdge: decayedAbsEdge };
+}
+
+// ── Fast Signal Pipeline (runs every 5 minutes) ──
+async function signalPipeline(activeMarkets) {
+ const pipelineStart = Date.now();
+ let signalsGenerated = 0;
+
+ try {
+ // Step 1: Fetch recent news/sentiment from last 30 minutes
+ const { rows: recentArticles } = await kenQ(`
+ SELECT id, source, keyword, post_title as headline, post_url as url, sentiment_score, captured_at
+ FROM ken_sentiment
+ WHERE captured_at > NOW() - INTERVAL '30 minutes'
+ ORDER BY captured_at DESC
+ LIMIT 500
+ `);
+
+ if (recentArticles.length === 0) {
+ console.log('[Ken] Signal Pipeline: no new articles in last 30 min');
+ return 0;
+ }
+
+ // Step 2: Score each article with event-specific sentiment
+ const eventScores = [];
+ for (const article of recentArticles) {
+ const evtScore = scoreEventSentiment(article.headline);
+ if (evtScore.magnitude > 0.1) { // Only process articles with detectable event signal
+ // Step 3: Map to relevant markets
+ const mappedMarkets = mapNewsToMarkets(article.headline, activeMarkets);
+
+ for (const { market, matchScore } of mappedMarkets) {
+ eventScores.push({
+ articleId: String(article.id),
+ headline: article.headline,
+ source: article.source,
+ marketTicker: market.ticker,
+ marketTitle: market.title,
+ sentiment: evtScore.sentiment,
+ confidence: evtScore.confidence * (matchScore / 10), // Scale confidence by match quality
+ magnitude: evtScore.magnitude,
+ category: evtScore.category,
+ direction: evtScore.direction,
+ timestamp: new Date(article.captured_at).getTime(),
+ });
+
+ // Store event-specific sentiment
+ await kenQ(`
+ INSERT INTO ken_event_sentiment (article_id, event_tag, market_ticker, sentiment, confidence, magnitude, headline, source)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
+ `, [String(article.id), evtScore.direction, market.ticker, evtScore.sentiment,
+ evtScore.confidence, evtScore.magnitude, article.headline?.substring(0, 500), article.source]);
+ }
+ }
+ }
+
+ console.log(`[Ken] Signal Pipeline: ${eventScores.length} event-specific scores from ${recentArticles.length} articles`);
+
+ // Step 4: Group by market and calculate probability shifts
+ const marketSignals = {};
+ for (const score of eventScores) {
+ if (!marketSignals[score.marketTicker]) marketSignals[score.marketTicker] = [];
+ marketSignals[score.marketTicker].push(score);
+ }
+
+ // Step 5: For each market with signals, compute probability shift
+ for (const [ticker, signals] of Object.entries(marketSignals)) {
+ const market = activeMarkets.find(m => m.ticker === ticker);
+ if (!market) continue;
+
+ const priorProb = (market.yes_bid + market.yes_ask) / 200; // Convert cents to probability
+ const { adjustedProb, impact, numArticles, agreement, sourceDiversity } = calculateProbabilityShift(priorProb, signals);
+ const marketProb = market.last_price / 100;
+ const edge = adjustedProb - marketProb;
+
+ // Store probability shift
+ await kenQ(`
+ INSERT INTO ken_probability_shifts (market_id, prior_probability, sentiment_impact, adjusted_probability, market_probability, edge, num_articles)
+ VALUES ($1, $2, $3, $4, $5, $6, $7)
+ `, [ticker, priorProb, impact, adjustedProb, marketProb, edge, numArticles]);
+
+ // Step 6: Generate signal if edge exceeds threshold
+ if (Math.abs(edge) >= RISK_LIMITS.minEdgeThreshold) {
+ const direction = edge > 0 ? 'BUY_YES' : 'BUY_NO';
+
+ // Step 6b: Monte Carlo simulation for probability validation (CPU-intensive)
+ const momentum = cachedMomentumMap?.[ticker] || { delta_2h: 0, delta_6h: 0 };
+ const mcResult = monteCarloSimulation({
+ priorProb,
+ sentimentImpact: impact,
+ momentum2h: momentum.delta_2h,
+ momentum6h: momentum.delta_6h,
+ volume24h: market.volume_24h || 0,
+ spread: (market.yes_ask || 0) - (market.yes_bid || 0),
+ articleCount: numArticles,
+ agreement: agreement || 0.5,
+ }, 15000); // 15k iterations for higher accuracy
+
+ // Blend Monte Carlo with statistical model
+ const mcEdge = mcResult.edgeConsistent ? (edge * 0.65 + mcResult.medianEdge * 0.35) : edge * 0.8;
+
+ // Dedup: skip if we already generated a signal for this market+direction in last 30 min
+ // Compare MC-blended edge (mcEdge) against stored MC-blended edge to avoid false positives
+ const recentDup = await kenQ(`
+ SELECT id, expected_edge, confidence FROM ken_strategy_signals
+ WHERE market_id = $1 AND direction = $2 AND created_at > NOW() - INTERVAL '30 minutes'
+ ORDER BY created_at DESC LIMIT 1
+ `, [ticker, direction]);
+ if (recentDup.rows.length > 0) {
+ const prevEdge = parseFloat(recentDup.rows[0].expected_edge);
+ if (Math.abs(Math.abs(mcEdge) - Math.abs(prevEdge)) < 0.02) continue;
+ }
+
+ // Improved confidence using MC validation
+ const edgeScore = Math.min(1, Math.pow(Math.abs(mcEdge) / 0.15, 1.5));
+ const volumeScore = Math.min(1, numArticles / 8);
+ const agreementScore = Math.pow(agreement || 0.5, 0.7);
+ const diversityScore = sourceDiversity || 0;
+ const mcConfBoost = mcResult.confidence > 0.6 ? 0.08 : mcResult.confidence > 0.4 ? 0.04 : 0;
+ const consistencyBoost = mcResult.edgeConsistent ? 0.05 : -0.05;
+ const confidence = Math.min(0.95, Math.max(0.15,
+ edgeScore * 0.30 +
+ agreementScore * 0.18 +
+ volumeScore * 0.18 +
+ diversityScore * 0.12 +
+ mcConfBoost +
+ consistencyBoost +
+ (numArticles >= 5 ? 0.10 : numArticles >= 3 ? 0.05 : 0)
+ ));
+
+ let signal = {
+ marketId: ticker,
+ direction,
+ expectedEdge: mcEdge,
+ confidence,
+ volume24h: market.volume_24h || 0,
+ timestamp: Date.now(),
+ agreement,
+ mcSimulation: {
+ meanEdge: mcResult.meanEdge,
+ stdDev: mcResult.stdDev,
+ percentiles: mcResult.percentiles,
+ consistent: mcResult.edgeConsistent,
+ },
+ };
+
+ // Step 6c: AI Enhancement for high-edge signals (Gemini)
+ if (Math.abs(mcEdge) >= 0.08 && confidence >= 0.4 && numArticles >= 3) {
+ signal = await aiEnhanceSignal(signal, signals, market);
+ }
+
+ // Step 7: Risk check
+ const risk = riskCheck(signal);
+
+ const mcInfo = `MC: μ=${(mcResult.meanEdge * 100).toFixed(1)}%±${(mcResult.stdDev * 100).toFixed(1)}%, p5-p95=[${(mcResult.percentiles.p5 * 100).toFixed(1)}%,${(mcResult.percentiles.p95 * 100).toFixed(1)}%]`;
+ const aiInfo = signal.aiEnhanced ? ` | AI: ${signal.aiReasoning || 'enhanced'}` : '';
+ const reasoning = `${direction} on "${market.title}" — edge ${(mcEdge * 100).toFixed(1)}% from ${numArticles} articles (${signals[0]?.category}/${signals[0]?.direction}). Agreement: ${((agreement || 0) * 100).toFixed(0)}%. ${mcInfo}${aiInfo}. ${risk.approved ? 'RISK APPROVED' : `RISK BLOCKED: ${risk.reasons.join('; ')}`}`;
+
+ await kenQ(`
+ INSERT INTO ken_strategy_signals (market_id, direction, expected_edge, size_recommendation, confidence, reasoning, sources, risk_approved)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
+ `, [ticker, direction, mcEdge, risk.sizeRecommendation, confidence, reasoning,
+ JSON.stringify(signals.slice(0, 5).map(s => ({ headline: s.headline?.substring(0, 200), source: s.source, sentiment: s.sentiment }))),
+ risk.approved]);
+
+ signalsGenerated++;
+
+ if (risk.approved && confidence > 0.7) {
+ console.log(`[Ken] SIGNAL: ${direction} ${ticker} — edge ${(mcEdge * 100).toFixed(1)}%, conf ${(confidence * 100).toFixed(0)}%, MC:${mcResult.edgeConsistent ? 'consistent' : 'mixed'}${signal.aiEnhanced ? ', AI-enhanced' : ''}, size ${risk.sizeRecommendation}`);
+ }
+
+ // Auto-trade across all 50 paper portfolios
+ if (risk.approved) {
+ autoPortfolioTrade({
+ ...signal, marketId: ticker, market_title: market.title,
+ num_articles: numArticles, signal_type: signals[0]?.category,
+ reasoning, expected_edge: mcEdge,
+ }).catch(e => console.error('[Ken/Portfolio] Error:', e.message));
+ }
+ }
+ }
+
+ const duration = Date.now() - pipelineStart;
+ console.log(`[Ken] Signal Pipeline: ${signalsGenerated} signals from ${Object.keys(marketSignals).length} markets | ${duration}ms`);
+ return signalsGenerated;
+
+ } catch (e) {
+ console.error('[Ken] Signal Pipeline error:', e.message);
+ return 0;
+ }
+}
+
+// ── Auto-mapping: Build market mappings from active Kalshi markets ──
+async function updateMarketMappings(activeMarkets) {
+ try {
+ let mapped = 0;
+ for (const m of activeMarkets) {
+ const titleLower = `${m.title} ${m.subtitle || ''}`.toLowerCase();
+ let category = 'other';
+ const keywords = [];
+
+ for (const [cat, kws] of Object.entries(MARKET_CATEGORY_KEYWORDS)) {
+ for (const kw of kws) {
+ if (titleLower.includes(kw)) {
+ category = cat;
+ keywords.push(kw);
+ }
+ }
+ }
+
+ if (keywords.length > 0) {
+ await kenQ(`
+ INSERT INTO ken_market_mappings (market_id, keywords, category, contract_type)
+ VALUES ($1, $2, $3, 'binary')
+ ON CONFLICT (id) DO NOTHING
+ `, [m.ticker, keywords, category]);
+ mapped++;
+ }
+ }
+ return mapped;
+ } catch (e) {
+ console.log(`[Ken] Market mapping update failed: ${e.message}`);
+ return 0;
+ }
+}
+
+// ══════════════════════════════════════════════
+// POLYMARKET CROSS-REFERENCE (fuzzy matching)
+// ══════════════════════════════════════════════
+const STOP_WORDS = new Set(['will', 'the', 'this', 'that', 'what', 'when', 'where', 'which', 'with', 'from', 'have', 'been', 'before', 'after', 'than', 'more', 'less', 'next', 'last', 'does', 'would', 'could', 'should', 'about', 'into', 'over', 'under', 'between', 'through', 'during', 'each', 'every', 'other', 'some', 'most', 'many', 'much', 'also', 'just', 'only', 'very', 'still', 'even', 'back', 'first', 'year', 'years']);
+
+function extractKeywords(text) {
+ return (text || '').toLowerCase()
+ .replace(/[^a-z0-9\s]/g, ' ')
+ .split(/\s+/)
+ .filter(w => w.length > 2 && !STOP_WORDS.has(w));
+}
+
+function fuzzyMatchScore(textA, textB) {
+ const wordsA = extractKeywords(textA);
+ const wordsB = new Set(extractKeywords(textB));
+ if (wordsA.length === 0 || wordsB.size === 0) return 0;
+ let matches = 0;
+ for (const w of wordsA) {
+ if (wordsB.has(w)) matches++;
+ // Partial match for longer words (e.g. "greenland" matches "greenlands")
+ else if (w.length > 5) {
+ for (const wb of wordsB) {
+ if (wb.length > 5 && (wb.startsWith(w.slice(0, 5)) || w.startsWith(wb.slice(0, 5)))) { matches += 0.5; break; }
+ }
+ }
+ }
+ return matches / Math.min(wordsA.length, wordsB.size);
+}
+
+async function polymarketCrossRef(kalshiMarkets) {
+ const crossRefs = [];
+ try {
+ const polyEvents = await scrapePolymarketEvents(100);
+ if (polyEvents.length === 0) return [];
+ console.log(`[Ken] Polymarket: ${polyEvents.length} markets from top events`);
+
+ // Build index of Kalshi market text for faster matching
+ const kalshiIndex = kalshiMarkets.map(km => ({
+ ...km,
+ searchText: ((km.title || '') + ' ' + (km.subtitle || '')).toLowerCase(),
+ }));
+
+ for (const pm of polyEvents) {
+ const pmText = pm.event_title + ' ' + pm.question;
+ let bestMatch = null;
+ let bestScore = 0;
+
+ for (const km of kalshiIndex) {
+ const score = fuzzyMatchScore(pmText, km.searchText);
+ if (score > bestScore) {
+ bestScore = score;
+ bestMatch = km;
+ }
+ }
+
+ // Require at least 30% keyword overlap for a match
+ if (bestScore >= 0.3 && bestMatch && bestMatch.yes_ask > 0) {
+ const priceDiff = pm.price - bestMatch.yes_ask;
+ if (Math.abs(priceDiff) >= 3) { // 3¢+ divergence
+ crossRefs.push({
+ kalshi_ticker: bestMatch.ticker,
+ event_ticker: bestMatch.event_ticker,
+ kalshi_title: bestMatch.title,
+ kalshi_subtitle: bestMatch.subtitle,
+ kalshi_price: bestMatch.yes_ask,
+ poly_question: pm.question,
+ poly_event: pm.event_title,
+ poly_price: pm.price,
+ poly_volume: pm.volume,
+ poly_slug: pm.slug,
+ price_diff: priceDiff,
+ match_score: Math.round(bestScore * 100),
+ arb_side: priceDiff > 0 ? 'BUY on Kalshi (cheaper)' : 'SHORT on Kalshi (overpriced)',
+ });
+ }
+ }
+ }
+ // Dedupe: keep best match per Kalshi ticker
+ const seen = new Map();
+ for (const ref of crossRefs) {
+ const key = ref.kalshi_ticker;
+ if (!seen.has(key) || Math.abs(ref.price_diff) > Math.abs(seen.get(key).price_diff)) {
+ seen.set(key, ref);
+ }
+ }
+ return [...seen.values()].sort((a, b) => Math.abs(b.price_diff) - Math.abs(a.price_diff));
+ } catch (e) {
+ console.log(`[Ken] Polymarket cross-ref error: ${e.message}`);
+ return [];
+ }
+}
+
+// ══════════════════════════════════════════════
+// LNG / ENERGY CROSS-MARKET ARBITRAGE
+// Compares energy-related predictions across Kalshi, Polymarket, and Manifold
+// ══════════════════════════════════════════════
+const ENERGY_SEARCH_TERMS = [
+ 'oil price', 'crude oil', 'natural gas', 'LNG', 'OPEC',
+ 'energy price', 'gas price', 'heating oil', 'petroleum',
+ 'electricity price', 'EIA', 'oil production', 'pipeline',
+ 'renewable energy', 'solar', 'wind energy', 'nuclear',
+ 'carbon price', 'emissions', 'electric vehicle', 'EV',
+ 'barrel', 'WTI', 'Brent', 'refinery',
+];
+
+async function energyArbitrageScan(kalshiMarkets) {
+ const arbs = [];
+ try {
+ // 1. Get energy markets from Manifold
+ const manifoldEnergy = await scrapeManifold(ENERGY_SEARCH_TERMS.slice(0, 8));
+ console.log(`[Ken/Energy] Manifold: ${manifoldEnergy.length} energy-related markets`);
+
+ // 2. Get energy events from Polymarket
+ let polyEnergy = [];
+ try {
+ const polyAll = await scrapePolymarketEvents(200);
+ polyEnergy = polyAll.filter(p => {
+ const t = (p.event_title + ' ' + p.question).toLowerCase();
+ return /oil|gas|lng|opec|energy|crude|barrel|petroleum|electric|solar|wind|nuclear|carbon|emission|ev market|renewable/i.test(t);
+ });
+ console.log(`[Ken/Energy] Polymarket: ${polyEnergy.length} energy-related markets`);
+ } catch {}
+
+ // 3. Filter Kalshi markets for energy/commodities
+ const kalshiEnergy = kalshiMarkets.filter(m => {
+ const t = ((m.title || '') + ' ' + (m.subtitle || '') + ' ' + (m.category || '')).toLowerCase();
+ return /oil|gas|lng|opec|energy|crude|barrel|petroleum|electric|solar|wind|nuclear|carbon|emission|ev |renewable|consumption|climate/i.test(t);
+ });
+ console.log(`[Ken/Energy] Kalshi: ${kalshiEnergy.length} energy-related markets`);
+
+ // 4. Cross-reference Manifold vs Kalshi
+ for (const mf of manifoldEnergy) {
+ for (const km of kalshiEnergy) {
+ const score = fuzzyMatchScore(mf.title, (km.title + ' ' + (km.subtitle || '')).toLowerCase());
+ if (score >= 0.25) {
+ const priceDiff = mf.probability - km.yes_ask;
+ if (Math.abs(priceDiff) >= 3) {
+ arbs.push({
+ type: 'manifold_kalshi',
+ kalshi_ticker: km.ticker,
+ event_ticker: km.event_ticker,
+ kalshi_title: km.title,
+ kalshi_price: km.yes_ask,
+ other_title: mf.title,
+ other_price: mf.probability,
+ other_source: 'Manifold',
+ other_url: mf.url,
+ other_volume: mf.volume,
+ price_diff: priceDiff,
+ match_score: Math.round(score * 100),
+ category: 'energy',
+ });
+ }
+ }
+ }
+ }
+
+ // 5. Cross-reference Polymarket vs Kalshi (energy-specific)
+ for (const pm of polyEnergy) {
+ for (const km of kalshiEnergy) {
+ const score = fuzzyMatchScore(pm.event_title + ' ' + pm.question, (km.title + ' ' + (km.subtitle || '')).toLowerCase());
+ if (score >= 0.25) {
+ const priceDiff = pm.price - km.yes_ask;
+ if (Math.abs(priceDiff) >= 3) {
+ arbs.push({
+ type: 'poly_kalshi_energy',
+ kalshi_ticker: km.ticker,
+ event_ticker: km.event_ticker,
+ kalshi_title: km.title,
+ kalshi_price: km.yes_ask,
+ other_title: pm.question,
+ other_price: pm.price,
+ other_source: 'Polymarket',
+ other_url: `https://polymarket.com/event/${pm.slug}`,
+ other_volume: pm.volume,
+ price_diff: priceDiff,
+ match_score: Math.round(score * 100),
+ category: 'energy',
+ });
+ }
+ }
+ }
+ }
+
+ // 6. Cross-reference Manifold vs Polymarket (energy only, no Kalshi needed)
+ for (const mf of manifoldEnergy) {
+ for (const pm of polyEnergy) {
+ const score = fuzzyMatchScore(mf.title, pm.event_title + ' ' + pm.question);
+ if (score >= 0.3) {
+ const priceDiff = mf.probability - pm.price;
+ if (Math.abs(priceDiff) >= 5) {
+ arbs.push({
+ type: 'manifold_poly_energy',
+ kalshi_ticker: null,
+ event_ticker: null,
+ kalshi_title: `${mf.title} (cross-platform)`,
+ kalshi_price: mf.probability,
+ other_title: pm.question,
+ other_price: pm.price,
+ other_source: 'Manifold↔Polymarket',
+ other_url: mf.url,
+ other_volume: Math.max(mf.volume, pm.volume),
+ price_diff: priceDiff,
+ match_score: Math.round(score * 100),
+ category: 'energy',
+ });
+ }
+ }
+ }
+ }
+
+ // Dedupe by best price diff per Kalshi ticker
+ const seen = new Map();
+ for (const arb of arbs) {
+ const key = arb.kalshi_ticker || arb.other_title;
+ if (!seen.has(key) || Math.abs(arb.price_diff) > Math.abs(seen.get(key).price_diff)) {
+ seen.set(key, arb);
+ }
+ }
+ const result = [...seen.values()].sort((a, b) => Math.abs(b.price_diff) - Math.abs(a.price_diff));
+ if (result.length > 0) {
+ console.log(`[Ken/Energy] Found ${result.length} energy arbitrage opportunities (top: ${result[0].kalshi_title} ${result[0].price_diff > 0 ? '+' : ''}${result[0].price_diff}¢)`);
+ }
+ return result;
+ } catch (e) {
+ console.log(`[Ken/Energy] Arbitrage scan error: ${e.message}`);
+ return [];
+ }
+}
+
+// ══════════════════════════════════════════════
+// AUTO-TRADER ($20 budget, risk-managed)
+// ══════════════════════════════════════════════
+const TRADE_CONFIG = {
+ enabled: true, // Master kill switch
+ budget_cents: 2000, // $20 total budget
+ max_position_cents: 200, // $2 max per trade
+ max_open_positions: 5, // Max concurrent positions
+ daily_loss_limit_cents: 400, // $4 daily stop-loss
+ min_confidence: 80, // Only trade 80%+ confidence signals
+ min_sources: 2, // Must have 2+ corroborating sources
+ take_profit_pct: 80, // Take profit at 80% of max (e.g. sell YES at 90+ if bought at 50)
+ stop_loss_pct: 50, // Stop loss: exit if position loses 50% of cost
+ fee_rate: 0.07, // Kalshi ~7% fee on winnings
+ cooldown_minutes: 30, // Don't re-trade same ticker within 30 min
+};
+
+// ── TRADE_CONFIG Persistence ──
+async function initConfigTable() {
+ try {
+ await kenQ(`
+ CREATE TABLE IF NOT EXISTS ken_config (
+ key TEXT PRIMARY KEY,
+ value JSONB NOT NULL,
+ updated_at TIMESTAMPTZ DEFAULT NOW()
+ )
+ `);
+ } catch (e) {
+ console.log(`[Ken] Config table init error: ${e.message}`);
+ }
+}
+
+async function loadTradeConfig() {
+ try {
+ await initConfigTable();
+ const { rows } = await kenQ("SELECT value FROM ken_config WHERE key = 'trade_config'");
+ if (rows.length > 0) {
+ const saved = rows[0].value;
+ // Merge saved values into TRADE_CONFIG (preserves new keys added in code)
+ for (const [k, v] of Object.entries(saved)) {
+ if (k in TRADE_CONFIG) TRADE_CONFIG[k] = v;
+ }
+ console.log(`[Ken] Loaded TRADE_CONFIG from DB: budget=$${(TRADE_CONFIG.budget_cents/100).toFixed(0)}, conf=${TRADE_CONFIG.min_confidence}%, enabled=${TRADE_CONFIG.enabled}`);
+ }
+ } catch (e) {
+ console.log(`[Ken] Failed to load trade config: ${e.message}`);
+ }
+}
+
+async function saveTradeConfig() {
+ try {
+ await kenQ(`
+ INSERT INTO ken_config (key, value, updated_at) VALUES ('trade_config', $1, NOW())
+ ON CONFLICT (key) DO UPDATE SET value = $1, updated_at = NOW()
+ `, [JSON.stringify(TRADE_CONFIG)]);
+ } catch (e) {
+ console.log(`[Ken] Failed to save trade config: ${e.message}`);
+ }
+}
+
+async function getTraderState() {
+ try {
+ const openTrades = await kenQ('SELECT * FROM ken_trades WHERE status = $1 ORDER BY created_at DESC', ['open']);
+ const today = new Date().toISOString().split('T')[0];
+ const todayPnL = await kenQ("SELECT COALESCE(SUM(pnl_cents), 0) as total FROM ken_trades WHERE closed_at::date = $1::date", [today]);
+ const totalInvested = (openTrades.rows || []).reduce((sum, t) => sum + (t.cost_cents || 0), 0);
+ const dailyLoss = Math.abs(Math.min(0, todayPnL.rows[0]?.total || 0));
+ return {
+ openPositions: openTrades.rows || [],
+ openCount: (openTrades.rows || []).length,
+ totalInvested,
+ dailyLoss,
+ available: TRADE_CONFIG.budget_cents - totalInvested,
+ };
+ } catch (e) {
+ console.log(`[Ken] Trader state error: ${e.message}`);
+ return { openPositions: [], openCount: 0, totalInvested: 0, dailyLoss: 0, available: 0 };
+ }
+}
+
+async function autoTrader(signals) {
+ if (!TRADE_CONFIG.enabled) return;
+
+ try {
+ // Check if API keys are configured
+ const cfgRow = await q('SELECT config FROM risk_state ORDER BY updated_at DESC LIMIT 1');
+ const cfg = cfgRow.rows[0]?.config || {};
+ if (!cfg.kalshi_api_key || !cfg.kalshi_private_key) {
+ return; // Silent - no keys configured yet
+ }
+
+ const state = await getTraderState();
+
+ // Daily loss limit check
+ if (state.dailyLoss >= TRADE_CONFIG.daily_loss_limit_cents) {
+ console.log(`[Ken] TRADER: Daily loss limit hit ($${(state.dailyLoss/100).toFixed(2)}). No new trades today.`);
+ return;
+ }
+
+ // ── 1. CHECK EXISTING POSITIONS FOR EXIT ──
+ for (const trade of state.openPositions) {
+ try {
+ // Get current market price
+ const mktData = await kalshiPublicFetch('GET', `/markets/${encodeURIComponent(trade.ticker)}`);
+ const mkt = mktData.market || mktData;
+ const currentPrice = trade.side === 'yes' ? (mkt.yes_ask || mkt.last_price || 0) : (mkt.no_ask || mkt.last_price || 0);
+
+ // Market resolved?
+ if (mkt.status === 'settled' || mkt.result) {
+ const won = (mkt.result === trade.side);
+ const pnl = won ? (100 - trade.price_cents) * trade.count : -(trade.cost_cents);
+ const feeAdjusted = won ? Math.round(pnl * (1 - TRADE_CONFIG.fee_rate)) : pnl;
+ await kenQ('UPDATE ken_trades SET status=$1, exit_price=$2, pnl_cents=$3, closed_at=NOW() WHERE id=$4',
+ ['resolved', won ? 100 : 0, feeAdjusted, trade.id]);
+ const emoji = feeAdjusted > 0 ? ':moneybag:' : ':chart_with_downwards_trend:';
+ await sendSlack(`${emoji} *Ken Trade Resolved*\n*${trade.title}* (${trade.ticker})\nSide: ${trade.side.toUpperCase()} @ ${trade.price_cents}¢ → Result: ${mkt.result?.toUpperCase()}\nP&L: *${feeAdjusted > 0 ? '+' : ''}${(feeAdjusted/100).toFixed(2)}* (after fees)`);
+ continue;
+ }
+
+ // Take profit check
+ if (currentPrice >= TRADE_CONFIG.take_profit_pct) {
+ try {
+ const sellOrder = await kalshiFetch('POST', '/portfolio/orders', {
+ ticker: trade.ticker, side: trade.side, action: 'sell', type: 'market', count: trade.count,
+ });
+ const sellPrice = currentPrice;
+ const pnl = Math.round((sellPrice - trade.price_cents) * trade.count * (1 - TRADE_CONFIG.fee_rate));
+ await kenQ('UPDATE ken_trades SET status=$1, exit_price=$2, pnl_cents=$3, closed_at=NOW(), order_id=$4 WHERE id=$5',
+ ['profit', sellPrice, pnl, sellOrder.order?.order_id || trade.order_id, trade.id]);
+ await sendSlack(`:rocket: *Ken Take Profit!*\n*${trade.title}* (${trade.ticker})\nBought ${trade.side.toUpperCase()} @ ${trade.price_cents}¢ → Sold @ ${sellPrice}¢\nP&L: *+$${(pnl/100).toFixed(2)}* :moneybag:`);
+ } catch (e) {
+ console.log(`[Ken] TRADER: Take profit failed for ${trade.ticker}: ${e.message}`);
+ }
+ continue;
+ }
+
+ // Stop loss check
+ const unrealizedLoss = (trade.price_cents - currentPrice) * trade.count;
+ if (unrealizedLoss > trade.cost_cents * (TRADE_CONFIG.stop_loss_pct / 100)) {
+ try {
+ const sellOrder = await kalshiFetch('POST', '/portfolio/orders', {
+ ticker: trade.ticker, side: trade.side, action: 'sell', type: 'market', count: trade.count,
+ });
+ const sellPrice = currentPrice;
+ const pnl = (sellPrice - trade.price_cents) * trade.count;
+ await kenQ('UPDATE ken_trades SET status=$1, exit_price=$2, pnl_cents=$3, closed_at=NOW() WHERE id=$4',
+ ['stopped', sellPrice, pnl, trade.id]);
+ await sendSlack(`:stop_sign: *Ken Stop Loss*\n*${trade.title}* (${trade.ticker})\nBought ${trade.side.toUpperCase()} @ ${trade.price_cents}¢ → Stopped @ ${sellPrice}¢\nP&L: *-$${(Math.abs(pnl)/100).toFixed(2)}*`);
+ } catch (e) {
+ console.log(`[Ken] TRADER: Stop loss failed for ${trade.ticker}: ${e.message}`);
+ }
+ continue;
+ }
+ } catch (e) {
+ console.log(`[Ken] TRADER: Position check failed for ${trade.ticker}: ${e.message}`);
+ }
+ }
+
+ // ── 2. LOOK FOR NEW TRADES ──
+ // Refresh state after exits
+ const freshState = await getTraderState();
+ if (freshState.openCount >= TRADE_CONFIG.max_open_positions) {
+ console.log(`[Ken] TRADER: Max positions (${freshState.openCount}/${TRADE_CONFIG.max_open_positions}). Waiting for exits.`);
+ return;
+ }
+
+ // Filter signals: high confidence, multiple sources, tradeable price
+ const tradeable = signals.filter(s =>
+ s.confidence >= TRADE_CONFIG.min_confidence &&
+ (s.sources?.length || 0) >= TRADE_CONFIG.min_sources &&
+ s.entry_price > 5 && s.entry_price < 90 && // Don't trade near extremes
+ s.ticker
+ ).sort((a, b) => b.confidence - a.confidence);
+
+ // Check cooldown: don't re-trade same ticker
+ const recentTickers = new Set();
+ try {
+ const recent = await kenQ("SELECT ticker FROM ken_trades WHERE created_at > NOW() - INTERVAL '" + TRADE_CONFIG.cooldown_minutes + " minutes'");
+ for (const r of (recent.rows || [])) recentTickers.add(r.ticker);
+ } catch {}
+ // Also skip tickers we already have open positions on
+ for (const t of freshState.openPositions) recentTickers.add(t.ticker);
+
+ let tradesPlaced = 0;
+ for (const sig of tradeable) {
+ if (freshState.openCount + tradesPlaced >= TRADE_CONFIG.max_open_positions) break;
+ if (recentTickers.has(sig.ticker)) continue;
+
+ // Calculate position size: max $2, but respect available budget
+ const priceCents = sig.entry_price;
+ const costPerContract = priceCents; // Cost = price in cents for YES; (100 - price) for NO
+ const maxContracts = Math.floor(Math.min(TRADE_CONFIG.max_position_cents, freshState.available) / costPerContract);
+ if (maxContracts < 1) continue;
+ const count = Math.min(maxContracts, 3); // Max 3 contracts per trade
+ const totalCost = count * costPerContract;
+
+ try {
+ const side = sig.side === 'NO' ? 'no' : 'yes';
+ const order = await kalshiFetch('POST', '/portfolio/orders', {
+ ticker: sig.ticker,
+ side: side,
+ action: 'buy',
+ type: 'limit',
+ count: count,
+ yes_price: side === 'yes' ? priceCents : undefined,
+ no_price: side === 'no' ? (100 - priceCents) : undefined,
+ time_in_force: 'gtc',
+ });
+
+ const orderId = order.order?.order_id || `ken_${Date.now()}`;
+ await kenQ(`INSERT INTO ken_trades (ticker, event_ticker, title, side, action, price_cents, count, cost_cents, order_id, signal_type, confidence, reasoning, status)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, 'open')`,
+ [sig.ticker, sig.event_ticker || '', sig.market || '', side, 'buy', priceCents, count, totalCost,
+ orderId, sig.signal_type || '', sig.confidence, sig.reason || '']);
+
+ recentTickers.add(sig.ticker);
+ tradesPlaced++;
+ freshState.available -= totalCost;
+
+ const kLink = kalshiLink(sig.ticker, sig.event_ticker);
+ await sendSlack(`:chart_with_upwards_trend: *Ken Auto-Trade Placed!*\n${confBadge(sig.confidence)} *${sig.market}*\n${side.toUpperCase()} x${count} @ ${priceCents}¢ = $${(totalCost/100).toFixed(2)}\nSignal: ${sig.signal_type} | ${sig.reason}\n${kLink}\n_Budget remaining: $${(freshState.available/100).toFixed(2)}_`);
+ console.log(`[Ken] TRADER: ${side.toUpperCase()} x${count} ${sig.ticker} @ ${priceCents}¢ ($${(totalCost/100).toFixed(2)}) — ${sig.signal_type} ${sig.confidence}%`);
+
+ } catch (e) {
+ console.log(`[Ken] TRADER: Order failed for ${sig.ticker}: ${e.message}`);
+ }
+ }
+
+ if (tradesPlaced > 0) {
+ console.log(`[Ken] TRADER: ${tradesPlaced} new trades placed. Open: ${freshState.openCount + tradesPlaced}/${TRADE_CONFIG.max_open_positions}`);
+ }
+ } catch (e) {
+ console.log(`[Ken] TRADER ERROR: ${e.message}`);
+ }
+}
+
+// ══════════════════════════════════════════════
+// MAIN AUTONOMOUS SCAN (every 15 min, 24/7)
+// ══════════════════════════════════════════════
+async function autonomousScan() {
+ const scanStart = Date.now();
+ console.log('[Ken] ═══ AUTONOMOUS SCAN STARTING ═══');
+ try {
+ // 1. Refresh weather data
+ const cities = ['New York', 'Chicago', 'Miami', 'Denver', 'Los Angeles', 'Seattle', 'Houston', 'Phoenix', 'Minneapolis', 'Boston'];
+ const weatherData = generateSyntheticWeather(cities);
+
+ // Cache in DB
+ const row = (await q('SELECT id, config FROM risk_state ORDER BY updated_at DESC LIMIT 1')).rows[0];
+ if (row) {
+ const newCfg = { ...(row.config || {}), weather_cache: { results: weatherData, fetched_at: new Date().toISOString(), synthetic: true } };
+ await q('UPDATE risk_state SET config = $1, updated_at = NOW() WHERE id = $2', [JSON.stringify(newCfg), row.id]);
+ }
+
+ // 2. Fetch ALL live Kalshi events with nested markets (retry + fallback to prod)
+ let allEvents = [];
+ let weatherEvents = [];
+ let allMarkets = [];
+ const apiUrls = [KALSHI_BASE_URL, 'https://api.elections.kalshi.com/trade-api/v2', 'https://demo-api.kalshi.co/trade-api/v2'];
+ for (let attempt = 0; attempt < apiUrls.length; attempt++) {
+ try {
+ const url = apiUrls[attempt] + '/events?status=open&limit=200&with_nested_markets=true';
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), 15000);
+ const res = await fetch(url, { headers: { 'Accept': 'application/json' }, signal: controller.signal });
+ clearTimeout(timeout);
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ const evData = await res.json();
+ allEvents = evData.events || [];
+ if (allEvents.length > 0) {
+ if (attempt > 0) console.log(`[Ken] Fallback API ${attempt + 1} worked`);
+ break;
+ }
+ } catch (e) {
+ console.log(`[Ken] API ${attempt + 1}/${apiUrls.length} failed: ${e.message}`);
+ if (attempt < apiUrls.length - 1) await new Promise(r => setTimeout(r, 3000));
+ }
+ }
+ // Build market list from events
+ for (const evt of allEvents) {
+ if (evt.markets) {
+ for (const m of evt.markets) {
+ allMarkets.push({
+ ticker: m.ticker,
+ event_ticker: evt.event_ticker,
+ title: evt.title,
+ subtitle: m.subtitle || m.ticker,
+ volume: m.volume || 0,
+ volume_24h: m.volume_24h || 0,
+ open_interest: m.open_interest || 0,
+ yes_bid: m.yes_bid || 0,
+ yes_ask: m.yes_ask || 0,
+ no_bid: m.no_bid || 0,
+ no_ask: m.no_ask || 0,
+ last_price: m.last_price || 0,
+ prev_price: m.previous_price || m.last_price || 0,
+ status: m.status,
+ category: evt.category || '',
+ });
+ }
+ }
+ }
+ // Filter weather events for model-based predictions
+ weatherEvents = allEvents.filter(e => {
+ const t = ((e.category || '') + ' ' + (e.title || '')).toLowerCase();
+ return t.includes('weather') || t.includes('temperature') || t.includes('temp ') ||
+ t.includes('rain') || t.includes('snow') || t.includes('precipitation') ||
+ t.includes('hurricane') || t.includes('wind') || t.includes('°f');
+ });
+ console.log(`[Ken] Kalshi: ${allEvents.length} events, ${allMarkets.length} markets, ${weatherEvents.length} weather`);
+
+ const month = new Date().getMonth() + 1;
+ const predictions = [];
+
+ // 3. Score weather events against our weather model
+ for (const evt of weatherEvents) {
+ const city = extractCity(evt.title);
+ if (!city) continue;
+ const spec = parseWeatherEvent(evt.title);
+ if (!spec || spec.variable === 'unknown') continue;
+ const cityWeather = weatherData.find(w => w.city === city);
+ if (!cityWeather) continue;
+ const features = cityWeather[spec.variable === 'snow' ? 'precipitation' : spec.variable] || cityWeather.temperature;
+ if (!features?.values?.length) continue;
+
+ const rawProb = ensembleExceedance(features, spec.threshold, spec.operator);
+ const prior = climatologicalPrior(spec.variable, spec.threshold, month);
+ const combined = bayesianUpdate(prior, rawProb ?? 0.5);
+ const pYes = Math.max(0.01, Math.min(0.99, combined));
+
+ let marketPrice = 50;
+ const mkt = (evt.markets || [])[0];
+ if (mkt) {
+ const p = mkt.yes_ask || mkt.last_price || 50;
+ if (p > 0 && p < 100) marketPrice = p;
+ }
+
+ const edgeBps = Math.round((pYes * 100 - marketPrice) * 100);
+ predictions.push({
+ market: evt.title,
+ city,
+ side: edgeBps > 0 ? 'yes' : 'no',
+ p_yes: Math.round(pYes * 1000) / 10,
+ price_cents: marketPrice,
+ edge_bps: edgeBps,
+ variable: spec.variable,
+ threshold: spec.threshold,
+ type: 'weather_model',
+ });
+ }
+
+ // 4. Scan ALL high-volume markets for volume-based signals
+ const volumeIdeas = [];
+
+ // Sort by 24h volume to find what's hot
+ const activeMarkets = allMarkets
+ .filter(m => m.yes_bid > 0 && m.yes_ask > 0 && m.yes_ask < 100 && m.last_price > 0)
+ .sort((a, b) => b.volume_24h - a.volume_24h);
+
+ // Cache for 5-minute signal pipeline
+ cachedActiveMarkets = activeMarkets;
+
+ // Load price momentum from DB (compare current vs 2h ago and 6h ago)
+ let momentumMap = {};
+ // Also update cached version for signal pipeline MC simulations
+ try {
+ const { rows: momentumRows } = await kenQ(`
+ WITH latest AS (
+ SELECT DISTINCT ON (ticker) ticker, last_price as current_price, yes_bid, yes_ask, captured_at
+ FROM ken_market_snapshots ORDER BY ticker, captured_at DESC
+ ),
+ two_hours AS (
+ SELECT DISTINCT ON (ticker) ticker, last_price as price_2h
+ FROM ken_market_snapshots WHERE captured_at < NOW() - INTERVAL '2 hours'
+ ORDER BY ticker, captured_at DESC
+ ),
+ six_hours AS (
+ SELECT DISTINCT ON (ticker) ticker, last_price as price_6h
+ FROM ken_market_snapshots WHERE captured_at < NOW() - INTERVAL '6 hours'
+ ORDER BY ticker, captured_at DESC
+ )
+ SELECT l.ticker, l.current_price, t.price_2h, s.price_6h,
+ l.current_price - COALESCE(t.price_2h, l.current_price) as delta_2h,
+ l.current_price - COALESCE(s.price_6h, l.current_price) as delta_6h
+ FROM latest l LEFT JOIN two_hours t ON l.ticker = t.ticker LEFT JOIN six_hours s ON l.ticker = s.ticker
+ `);
+ for (const r of momentumRows) {
+ momentumMap[r.ticker] = { delta_2h: parseInt(r.delta_2h) || 0, delta_6h: parseInt(r.delta_6h) || 0, price_2h: r.price_2h, price_6h: r.price_6h };
+ }
+ } catch (e) { console.log('[Ken] Momentum query error:', e.message); }
+ cachedMomentumMap = momentumMap; // Update shared cache for signal pipeline
+
+ // ═══ INSTANT SLACK ALERT: Major Price Movements (>=10¢ in 2h or >=15¢ in 6h) ═══
+ try {
+ const bigMovers = Object.entries(momentumMap)
+ .filter(([, m]) => Math.abs(m.delta_2h) >= 10 || Math.abs(m.delta_6h) >= 15)
+ .sort((a, b) => Math.abs(b[1].delta_2h) - Math.abs(a[1].delta_2h));
+ if (bigMovers.length > 0) {
+ const moverLines = bigMovers.slice(0, 8).map(([ticker, m]) => {
+ const mkt = activeMarkets.find(am => am.ticker === ticker);
+ const title = mkt ? mkt.title : ticker;
+ const d2 = m.delta_2h > 0 ? `+${m.delta_2h}` : `${m.delta_2h}`;
+ const d6 = m.delta_6h > 0 ? `+${m.delta_6h}` : `${m.delta_6h}`;
+ const icon = Math.abs(m.delta_2h) >= 10 ? (m.delta_2h > 0 ? ':chart_with_upwards_trend:' : ':chart_with_downwards_trend:') : ':left_right_arrow:';
+ const et = mkt?.event_ticker || ticker?.replace(/-[^-]+$/, '') || ticker;
+ const link = `<https://kalshi.com/markets/${et}/${ticker}|View>`;
+ return ` ${icon} *${title}*\n 2h: *${d2}¢* | 6h: *${d6}¢* | Now: ${mkt?.last_price || '?'}¢ | ${link}`;
+ }).join('\n');
+ const timeStr = new Date().toLocaleString('en-US', { timeZone: 'America/Los_Angeles', hour: 'numeric', minute: '2-digit', hour12: true });
+ await sendSlack(`:rotating_light: *Major Price Movements* (${timeStr} PT)\n_${bigMovers.length} market(s) moved 10+¢ in 2h or 15+¢ in 6h_\n\n${moverLines}\n\nDashboard: http://45.61.58.125:7810`);
+ console.log(`[Ken] SLACK ALERT: ${bigMovers.length} major price movement(s) sent`);
+ }
+ } catch (e) { console.log('[Ken] Price movement alert error:', e.message); }
+
+ for (const m of activeMarkets.slice(0, 200)) {
+ const spread = m.yes_ask - m.yes_bid;
+ const noPrice = 100 - m.yes_ask;
+ const momentum = momentumMap[m.ticker] || { delta_2h: 0, delta_6h: 0 };
+
+ // ── SHORT: YES >= 75¢ (buy NO cheap, wider net than before) ──
+ if (m.yes_bid >= 75 && noPrice <= 25) {
+ let shortConf = 40;
+ if (noPrice <= 5) shortConf += 15; // dirt cheap NO
+ else if (noPrice <= 10) shortConf += 10;
+ else if (noPrice <= 15) shortConf += 5;
+ if (momentum.delta_2h < 0) shortConf += 10; // price dropping = good short
+ if (momentum.delta_6h < -3) shortConf += 10; // strong downtrend
+ if (m.volume_24h > 5000) shortConf += 5;
+ if (m.open_interest > 100000) shortConf += 5;
+ volumeIdeas.push({
+ market: m.title, subtitle: m.subtitle, ticker: m.ticker, event_ticker: m.event_ticker, side: 'NO',
+ reason: `YES at ${m.yes_bid}¢ → NO at ${noPrice}¢${momentum.delta_2h ? ` (${momentum.delta_2h > 0 ? '+' : ''}${momentum.delta_2h}¢/2h)` : ''}`,
+ volume_24h: m.volume_24h, open_interest: m.open_interest,
+ yes_price: m.yes_ask, no_price: noPrice, spread,
+ type: 'short_high_price', confidence: Math.min(90, shortConf),
+ });
+ }
+
+ // ── MOMENTUM SHORT: price dropping fast (was 50+, fell 5+ in 2h) ──
+ if (momentum.delta_2h <= -5 && m.last_price >= 30 && m.last_price <= 80) {
+ volumeIdeas.push({
+ market: m.title, subtitle: m.subtitle, ticker: m.ticker, event_ticker: m.event_ticker, side: 'NO',
+ reason: `Dropping ${momentum.delta_2h}¢/2h (${momentum.delta_6h || '?'}¢/6h) — momentum sell`,
+ volume_24h: m.volume_24h, open_interest: m.open_interest,
+ yes_price: m.yes_ask, no_price: noPrice, spread,
+ type: 'momentum_short', confidence: Math.min(80, 50 + Math.abs(momentum.delta_2h) * 2),
+ });
+ }
+
+ // ── MOMENTUM LONG: price rising fast (was low, jumped 5+ in 2h) ──
+ if (momentum.delta_2h >= 5 && m.last_price <= 70 && m.last_price >= 10) {
+ volumeIdeas.push({
+ market: m.title, subtitle: m.subtitle, ticker: m.ticker, event_ticker: m.event_ticker, side: 'YES',
+ reason: `Rising +${momentum.delta_2h}¢/2h (+${momentum.delta_6h || '?'}¢/6h) — momentum buy`,
+ volume_24h: m.volume_24h, open_interest: m.open_interest,
+ yes_price: m.yes_ask, no_price: noPrice, spread,
+ type: 'momentum_long', confidence: Math.min(80, 50 + momentum.delta_2h * 2),
+ });
+ }
+
+ // ── LONG CHEAP: YES <= 20¢ with volume (wider net) ──
+ if (m.yes_ask <= 20 && m.volume_24h > 100) {
+ let longConf = 35;
+ if (m.yes_ask <= 5) longConf += 5; // lottery ticket
+ if (m.volume_24h > 1000) longConf += 10; // lots of interest
+ if (m.volume_24h > 5000) longConf += 10;
+ if (momentum.delta_2h > 0) longConf += 10; // price rising
+ if (momentum.delta_6h > 2) longConf += 10;
+ volumeIdeas.push({
+ market: m.title, subtitle: m.subtitle, ticker: m.ticker, event_ticker: m.event_ticker, side: 'YES',
+ reason: `YES at ${m.yes_ask}¢, vol ${m.volume_24h.toLocaleString()}${momentum.delta_2h ? ` (${momentum.delta_2h > 0 ? '+' : ''}${momentum.delta_2h}¢/2h)` : ''}`,
+ volume_24h: m.volume_24h, open_interest: m.open_interest,
+ yes_price: m.yes_ask, no_price: noPrice, spread,
+ type: 'long_cheap', confidence: Math.min(80, longConf),
+ });
+ }
+
+ // ── CONTRARIAN SHORT: YES at 60-84¢ with negative momentum ──
+ if (m.yes_bid >= 60 && m.yes_bid < 85 && momentum.delta_2h < -2 && m.volume_24h > 200) {
+ volumeIdeas.push({
+ market: m.title, subtitle: m.subtitle, ticker: m.ticker, event_ticker: m.event_ticker, side: 'NO',
+ reason: `YES fading from ${(m.last_price + Math.abs(momentum.delta_2h))}¢→${m.last_price}¢, NO at ${noPrice}¢`,
+ volume_24h: m.volume_24h, open_interest: m.open_interest,
+ yes_price: m.yes_ask, no_price: noPrice, spread,
+ type: 'contrarian_short', confidence: Math.min(75, 45 + Math.abs(momentum.delta_2h) * 3),
+ });
+ }
+
+ // ── VOLUME SPIKE (kept but enhanced with momentum) ──
+ if (m.volume > 0 && m.volume_24h / m.volume > 0.05 && m.volume_24h > 500) {
+ volumeIdeas.push({
+ market: m.title,
+ subtitle: m.subtitle,
+ ticker: m.ticker,
+ event_ticker: m.event_ticker,
+ side: m.last_price > m.prev_price ? 'YES momentum' : 'NO momentum',
+ reason: `24h vol ${m.volume_24h.toLocaleString()} = ${Math.round(m.volume_24h / m.volume * 100)}% of all-time`,
+ volume_24h: m.volume_24h,
+ open_interest: m.open_interest,
+ yes_price: m.yes_ask,
+ no_price: noPrice,
+ spread,
+ type: 'volume_spike',
+ });
+ }
+
+ // Spread opportunity: wide spread with volume = market-making opportunity
+ if (spread >= 5 && m.volume_24h > 100 && m.open_interest > 1000) {
+ volumeIdeas.push({
+ market: m.title,
+ subtitle: m.subtitle,
+ ticker: m.ticker,
+ event_ticker: m.event_ticker,
+ side: 'SPREAD',
+ reason: `${spread}¢ spread, bid ${m.yes_bid}¢ / ask ${m.yes_ask}¢`,
+ volume_24h: m.volume_24h,
+ open_interest: m.open_interest,
+ yes_price: m.yes_ask,
+ no_price: noPrice,
+ spread,
+ type: 'wide_spread',
+ });
+ }
+ }
+
+ // Deduplicate volume ideas by ticker (keep highest confidence)
+ const deduped = new Map();
+ for (const idea of volumeIdeas) {
+ const existing = deduped.get(idea.ticker);
+ if (!existing || (idea.confidence || 50) > (existing.confidence || 50)) {
+ deduped.set(idea.ticker, idea);
+ }
+ }
+ const uniqueVolumeIdeas = [...deduped.values()];
+
+ logMemory('scan-after-signals');
+
+ // 5. Store market snapshots in DB (batch of 150 to capture more markets)
+ for (const m of activeMarkets.slice(0, 150)) {
+ try {
+ await kenQ(`
+ INSERT INTO ken_market_snapshots (ticker, event_ticker, title, subtitle, category, yes_bid, yes_ask, no_bid, no_ask, last_price, volume, volume_24h, open_interest, spread)
+ VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14)
+ `, [m.ticker, m.event_ticker, m.title, m.subtitle, m.category, m.yes_bid, m.yes_ask, m.no_bid, m.no_ask, m.last_price, m.volume, m.volume_24h, m.open_interest, m.yes_ask - m.yes_bid]);
+ } catch {}
+ }
+
+ // 6. Get sentiment data from last 2 hours for signal boosting
+ let sentimentBoosts = {};
+ try {
+ const { rows: recentSentiment } = await kenQ(`
+ SELECT relevance_ticker, AVG(sentiment_score) as avg_sent, COUNT(*) as post_count, SUM(score) as total_score
+ FROM ken_sentiment
+ WHERE captured_at > NOW() - INTERVAL '2 hours' AND relevance_ticker IS NOT NULL
+ GROUP BY relevance_ticker
+ `);
+ for (const s of recentSentiment) {
+ sentimentBoosts[s.relevance_ticker] = {
+ avgSentiment: parseFloat(s.avg_sent) || 0,
+ postCount: parseInt(s.post_count) || 0,
+ totalScore: parseInt(s.total_score) || 0,
+ };
+ }
+ } catch {}
+
+ // Get recent news sentiment (non-ticker-specific)
+ let newsSentiment = {};
+ try {
+ const { rows: newsRows } = await kenQ(`
+ SELECT keyword, AVG(sentiment_score) as avg_sent, COUNT(*) as cnt
+ FROM ken_sentiment
+ WHERE source = 'google_news' AND captured_at > NOW() - INTERVAL '4 hours'
+ GROUP BY keyword
+ `);
+ for (const n of newsRows) {
+ newsSentiment[n.keyword] = { avg: parseFloat(n.avg_sent) || 0, count: parseInt(n.cnt) || 0 };
+ }
+ } catch {}
+
+ // 7. Polymarket cross-reference for arbitrage
+ let polyArbs = [];
+ try {
+ polyArbs = await polymarketCrossRef(activeMarkets);
+ } catch (e) {
+ console.log('[Ken] Polymarket cross-ref failed:', e.message);
+ }
+
+ // 7b. Energy/LNG cross-market arbitrage scan
+ let energyArbs = [];
+ try {
+ energyArbs = await energyArbitrageScan(activeMarkets);
+ } catch (e) {
+ console.log('[Ken] Energy arb scan failed:', e.message);
+ }
+
+ // 8. Combine ALL signals with confidence scoring
+ const buySignals = predictions.filter(p => p.edge_bps > 200);
+ const shortSignals = predictions.filter(p => p.edge_bps < -200);
+ const longIdeas = uniqueVolumeIdeas.filter(v => v.side === 'YES' || v.side === 'YES momentum');
+ const shortIdeas = uniqueVolumeIdeas.filter(v => ['short_high_price', 'momentum_short', 'contrarian_short'].includes(v.type));
+ const spikeIdeas = uniqueVolumeIdeas.filter(v => v.type === 'volume_spike');
+ const momentumIdeas = uniqueVolumeIdeas.filter(v => v.type === 'momentum_long' || v.type === 'momentum_short');
+ const spreadIdeas = uniqueVolumeIdeas.filter(v => v.type === 'wide_spread');
+
+ // 9. Composite confidence with sentiment + momentum
+ const allSignals = [];
+ for (const p of [...buySignals, ...shortSignals]) {
+ let confidence = 50 + Math.min(30, Math.abs(p.edge_bps) / 50);
+ const sentBoost = sentimentBoosts[p.market] || {};
+ if (sentBoost.postCount > 3) confidence += sentBoost.avgSentiment > 0 ? 10 : -5;
+ const mom = momentumMap[p.ticker] || {};
+ if (p.edge_bps > 0 && mom.delta_2h > 0) confidence += 8; // momentum confirms long
+ if (p.edge_bps < 0 && mom.delta_2h < 0) confidence += 8; // momentum confirms short
+ const sources = ['weather_model'];
+ if (sentBoost.postCount) sources.push('reddit');
+ if (mom.delta_2h) sources.push('momentum');
+ allSignals.push({ ...p, confidence: Math.min(95, Math.round(confidence)), sources, signal_type: p.edge_bps > 0 ? 'long' : 'short' });
+ }
+ for (const v of uniqueVolumeIdeas) {
+ let confidence = v.confidence || 45; // Use pre-calculated confidence from signal detection
+ // Boost with sentiment
+ const sentKey = Object.keys(sentimentBoosts).find(k => v.ticker?.startsWith(k));
+ const sentBoost = sentKey ? sentimentBoosts[sentKey] : null;
+ if (sentBoost && sentBoost.postCount > 3) {
+ if (v.side === 'YES' && sentBoost.avgSentiment > 0.05) confidence += 10;
+ if (v.side === 'NO' && sentBoost.avgSentiment < -0.05) confidence += 10;
+ }
+ // Boost with news
+ for (const [nk, nv] of Object.entries(newsSentiment)) {
+ const titleLower = (v.market || '').toLowerCase();
+ if (nk.split(' ').some(w => w.length > 4 && titleLower.includes(w))) {
+ if (v.side === 'YES' && nv.avg > 0.05) confidence += 5;
+ if (v.side === 'NO' && nv.avg < -0.05) confidence += 5;
+ break;
+ }
+ }
+ const sources = ['volume_analysis'];
+ if (v.type?.includes('momentum')) sources.push('momentum');
+ if (sentBoost) sources.push('reddit');
+ const isShort = v.side === 'NO' || ['short_high_price', 'momentum_short', 'contrarian_short'].includes(v.type);
+ allSignals.push({
+ market: v.market, ticker: v.ticker, event_ticker: v.event_ticker, subtitle: v.subtitle,
+ side: isShort ? 'NO' : v.side === 'SPREAD' ? 'YES' : 'YES',
+ confidence: Math.min(95, Math.round(confidence)),
+ entry_price: isShort ? v.no_price : v.yes_price,
+ edge_bps: isShort ? Math.round((100 - (v.yes_price || 50)) * 100) : 0,
+ signal_type: v.type || 'volume',
+ reason: v.reason, sources, volume_24h: v.volume_24h,
+ });
+ }
+ for (const arb of polyArbs) {
+ allSignals.push({
+ market: arb.kalshi_title, ticker: arb.kalshi_ticker, event_ticker: arb.event_ticker,
+ side: arb.price_diff > 0 ? 'YES' : 'NO',
+ confidence: Math.min(90, 55 + Math.abs(arb.price_diff) * 2),
+ entry_price: arb.kalshi_price,
+ edge_bps: arb.price_diff * 100,
+ signal_type: 'polymarket_arb',
+ reason: `Kalshi ${arb.kalshi_price}¢ vs Poly ${arb.poly_price}¢ (${arb.price_diff > 0 ? '+' : ''}${arb.price_diff}¢ gap | ${arb.match_score}% match)`,
+ sources: ['polymarket_crossref'],
+ });
+ }
+ // Energy/LNG cross-market arb signals
+ for (const arb of energyArbs) {
+ if (arb.kalshi_ticker) {
+ allSignals.push({
+ market: arb.kalshi_title, ticker: arb.kalshi_ticker, event_ticker: arb.event_ticker,
+ side: arb.price_diff > 0 ? 'YES' : 'NO',
+ confidence: Math.min(92, 60 + Math.abs(arb.price_diff) * 2),
+ entry_price: arb.kalshi_price,
+ edge_bps: arb.price_diff * 100,
+ signal_type: 'energy_arb',
+ reason: `ENERGY ARB: Kalshi ${arb.kalshi_price}¢ vs ${arb.other_source} ${arb.other_price}¢ (${arb.price_diff > 0 ? '+' : ''}${arb.price_diff}¢ gap) — BUY ${arb.price_diff > 0 ? 'Kalshi' : arb.other_source}, SELL ${arb.price_diff > 0 ? arb.other_source : 'Kalshi'}`,
+ sources: ['energy_crossmarket_arb', arb.other_source.toLowerCase()],
+ });
+ }
+ }
+
+ // 10. Store predictions in DB
+ for (const sig of allSignals) {
+ try {
+ await kenQ(`
+ INSERT INTO ken_predictions (ticker, event_ticker, title, signal_type, side, confidence, entry_price, edge_bps, reasoning, sources)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
+ `, [
+ sig.ticker || '', sig.event_ticker || '', sig.market || '', sig.signal_type,
+ sig.side, sig.confidence, sig.entry_price || sig.price_cents || 0, sig.edge_bps || 0,
+ sig.reason || sig.reasoning || `${sig.signal_type} signal`, JSON.stringify(sig.sources || []),
+ ]);
+ } catch {}
+ }
+
+ // 10b. AUTO-TRADER: Execute trades on high-confidence signals
+ try {
+ await autoTrader(allSignals);
+ } catch (e) {
+ console.log(`[Ken] Auto-trader error: ${e.message}`);
+ }
+
+ // 10c. PORTFOLIO TRADER: Feed scan signals into paper portfolios
+ let portfolioTradesPlaced = 0;
+ for (const sig of allSignals.filter(s => s.confidence >= 40 && s.ticker)) {
+ try {
+ await autoPortfolioTrade({
+ marketId: sig.ticker,
+ market_title: sig.market || sig.ticker,
+ direction: sig.side === 'YES' ? 'BUY_YES' : 'BUY_NO',
+ expectedEdge: (sig.edge_bps || 0) / 10000,
+ confidence: (sig.confidence || 50) / 100,
+ reasoning: sig.reason || sig.reasoning || sig.signal_type,
+ signal_type: sig.signal_type,
+ aiEnhanced: (sig.sources || []).includes('gemini'),
+ mcSimulation: { consistent: true, stdDev: 0.05 },
+ num_articles: (sig.sources || []).length,
+ agreement: (sig.confidence || 50) / 100,
+ });
+ portfolioTradesPlaced++;
+ } catch {}
+ }
+ if (portfolioTradesPlaced > 0) console.log(`[Ken] Portfolio trades: ${portfolioTradesPlaced} signals fed to paper portfolios`);
+
+ const scanDuration = Date.now() - scanStart;
+
+ // 11. Log performance
+ try {
+ await kenQ(`
+ INSERT INTO ken_performance (total_markets, active_markets, predictions_made, long_signals, short_signals, sentiment_items, scan_duration_ms, slack_sent)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
+ `, [
+ allMarkets.length, activeMarkets.length, allSignals.length,
+ allSignals.filter(s => s.side === 'YES').length,
+ allSignals.filter(s => s.side === 'NO').length,
+ Object.keys(sentimentBoosts).length,
+ scanDuration, false,
+ ]);
+ } catch {}
+
+ console.log(`[Ken] Scan complete: ${allMarkets.length} markets, ${activeMarkets.length} active, ${allSignals.length} signals (${allSignals.filter(s=>s.side==='YES').length} long, ${allSignals.filter(s=>s.side==='NO').length} short), ${polyArbs.length} arbs, ${Object.keys(sentimentBoosts).length} sentiment boosts | ${scanDuration}ms`);
+
+ // 12a. Run Signal Pipeline (News → Sentiment → Probability → Signals → Risk)
+ try {
+ const pipelineSignals = await signalPipeline(activeMarkets);
+ if (pipelineSignals > 0) {
+ console.log(`[Ken] Signal Pipeline produced ${pipelineSignals} risk-assessed signals`);
+ }
+ } catch (e) {
+ console.log(`[Ken] Signal Pipeline error: ${e.message}`);
+ }
+
+ // 12b. Update market mappings
+ try {
+ await updateMarketMappings(activeMarkets);
+ } catch {}
+
+ // 12. Build and send Slack alert (max once per hour to not spam)
+ const now = Date.now();
+ const shouldSlack = (now - lastSlackTime > SLACK_COOLDOWN_MS) || allSignals.some(s => s.confidence >= 75);
+
+ if (shouldSlack && allSignals.length > 0) {
+ lastSlackTime = now;
+ const timeStr = new Date().toLocaleString('en-US', { timeZone: 'America/New_York', hour: 'numeric', minute: '2-digit', hour12: true });
+ const parts = [];
+
+ parts.push(`:dog: *Ken — Autonomous Scan* (${timeStr} ET)`);
+ parts.push(`_${allMarkets.length} markets | ${activeMarkets.length} active | ${allSignals.length} signals | ${KALSHI_ENV}_\n`);
+
+ // Helper: build Kalshi market link
+ const kalshiLink = (ticker, eventTicker) => {
+ const et = eventTicker || ticker?.replace(/-[^-]+$/, '') || ticker;
+ return `<https://kalshi.com/markets/${et}/${ticker}|Trade on Kalshi>`;
+ };
+
+ // Helper: confidence badge with color (green→yellow→orange→red)
+ const confBadge = (conf) => {
+ if (conf >= 80) return `:large_green_circle: *${conf}%*`;
+ if (conf >= 65) return `:large_yellow_circle: *${conf}%*`;
+ if (conf >= 50) return `:large_orange_circle: *${conf}%*`;
+ return `:red_circle: *${conf}%*`;
+ };
+
+ // Confidence legend
+ parts.push(`_:large_green_circle: 80%+ Strong :large_yellow_circle: 65-79% Good :large_orange_circle: 50-64% Moderate :red_circle: <50% Speculative_`);
+
+ // High-confidence signals first (>= 70)
+ const highConf = allSignals.filter(s => s.confidence >= 70).sort((a, b) => b.confidence - a.confidence);
+ if (highConf.length > 0) {
+ const lines = highConf.slice(0, 5).map((s, i) => {
+ const icon = s.side === 'YES' ? ':chart_with_upwards_trend:' : ':small_red_triangle_down:';
+ const link = kalshiLink(s.ticker, s.event_ticker);
+ return ` ${icon} ${confBadge(s.confidence)} *${s.market}*\n ${s.side} | ${s.reason || `Edge ${s.edge_bps}bps`}\n :link: ${link}`;
+ }).join('\n');
+ parts.push(`:rotating_light: *High Confidence Signals*\n${lines}`);
+ }
+
+ // Short ideas
+ const shorts = allSignals.filter(s => s.side === 'NO' && s.confidence >= 50).sort((a, b) => b.confidence - a.confidence);
+ if (shorts.length > 0 && highConf.filter(s => s.side === 'NO').length === 0) {
+ const lines = shorts.slice(0, 3).map((s, i) => {
+ const link = kalshiLink(s.ticker, s.event_ticker);
+ return ` ${confBadge(s.confidence)} *${s.market}* — BUY NO\n ${s.reason || ''}\n :link: ${link}`;
+ }).join('\n');
+ parts.push(`:moneybag: *Short Ideas (Buy NO)*\n${lines}`);
+ }
+
+ // Volume spikes
+ if (spikeIdeas.length > 0) {
+ const lines = spikeIdeas.sort((a, b) => b.volume_24h - a.volume_24h).slice(0, 3)
+ .map((p, i) => {
+ const link = kalshiLink(p.ticker, p.event_ticker);
+ const conf = p.confidence || 45;
+ return ` ${confBadge(conf)} *${p.market}*\n ${p.reason}\n :link: ${link}`;
+ }).join('\n');
+ parts.push(`:fire: *Volume Spikes*\n${lines}`);
+ }
+
+ // Momentum moves
+ if (momentumIdeas.length > 0) {
+ const lines = momentumIdeas.sort((a, b) => (b.confidence || 0) - (a.confidence || 0)).slice(0, 4)
+ .map((p, i) => {
+ const icon = p.type === 'momentum_long' ? ':arrow_up:' : ':arrow_down:';
+ const link = kalshiLink(p.ticker, p.event_ticker);
+ const conf = p.confidence || 50;
+ return ` ${icon} ${confBadge(conf)} *${p.market}*\n ${p.subtitle || ''} — ${p.reason}\n :link: ${link}`;
+ }).join('\n');
+ parts.push(`:rocket: *Momentum Moves*\n${lines}`);
+ }
+
+ // Polymarket arbitrage
+ if (polyArbs.length > 0) {
+ const lines = polyArbs.slice(0, 5)
+ .map(a => {
+ const conf = Math.min(90, 55 + Math.abs(a.price_diff) * 2);
+ const kLink = kalshiLink(a.kalshi_ticker, a.event_ticker);
+ const pLink = `<https://polymarket.com/event/${a.poly_slug}|Polymarket>`;
+ return ` ${confBadge(conf)} *${a.kalshi_title}* (${a.kalshi_subtitle || ''})\n Kalshi: ${a.kalshi_price}¢ vs Poly: ${a.poly_price}¢ → *${a.arb_side}*\n ${kLink} | ${pLink} | Match: ${a.match_score}%`;
+ }).join('\n');
+ parts.push(`:scales: *Polymarket Arbitrage (${polyArbs.length} found)*\n${lines}`);
+ }
+
+ // Reddit buzz
+ const buzzKeys = Object.entries(sentimentBoosts).filter(([, v]) => v.postCount >= 3).sort((a, b) => b[1].totalScore - a[1].totalScore);
+ if (buzzKeys.length > 0) {
+ const lines = buzzKeys.slice(0, 3).map(([ticker, v]) => {
+ const sentIcon = v.avgSentiment > 0.1 ? ':large_green_circle:' : v.avgSentiment < -0.1 ? ':red_circle:' : ':large_yellow_circle:';
+ return ` ${sentIcon} ${ticker}: ${v.postCount} posts, sentiment ${v.avgSentiment > 0 ? '+' : ''}${v.avgSentiment.toFixed(2)}, karma ${v.totalScore}`;
+ }).join('\n');
+ parts.push(`:speech_balloon: *Reddit Buzz*\n${lines}`);
+ }
+
+ // Auto-trader portfolio summary
+ try {
+ const traderState = await getTraderState();
+ const closed = await kenQ("SELECT COUNT(*) as total, SUM(CASE WHEN pnl_cents > 0 THEN 1 ELSE 0 END) as wins, SUM(CASE WHEN pnl_cents <= 0 THEN 1 ELSE 0 END) as losses, COALESCE(SUM(pnl_cents), 0) as pnl FROM ken_trades WHERE status != 'open'");
+ const cs = closed.rows[0] || {};
+ const pnl = parseInt(cs.pnl || 0);
+ const pnlStr = `${pnl >= 0 ? '+' : ''}$${(pnl/100).toFixed(2)}`;
+ const pnlEmoji = pnl > 0 ? ':moneybag:' : pnl < 0 ? ':chart_with_downwards_trend:' : ':neutral_face:';
+ const openLines = traderState.openPositions.map(t =>
+ ` • ${t.side.toUpperCase()} ${t.ticker} x${t.count} @ ${t.price_cents}¢ ($${(t.cost_cents/100).toFixed(2)})`
+ ).join('\n');
+ parts.push(`:bank: *Auto-Trader Portfolio*\n` +
+ `Budget: $${(TRADE_CONFIG.budget_cents/100).toFixed(2)} | Invested: $${(traderState.totalInvested/100).toFixed(2)} | Available: $${(traderState.available/100).toFixed(2)}\n` +
+ `Open: ${traderState.openCount}/${TRADE_CONFIG.max_open_positions} positions` +
+ (openLines ? `\n${openLines}` : '') + `\n` +
+ `${pnlEmoji} P&L: *${pnlStr}* (${cs.wins || 0}W/${cs.losses || 0}L) | Today loss: $${(traderState.dailyLoss/100).toFixed(2)}/$${(TRADE_CONFIG.daily_loss_limit_cents/100).toFixed(2)}`);
+ } catch {}
+
+ // Performance stats
+ try {
+ const { rows: perfRows } = await kenQ(`
+ SELECT COUNT(*) as total_preds,
+ SUM(CASE WHEN outcome='win' THEN 1 ELSE 0 END) as wins,
+ SUM(CASE WHEN outcome='loss' THEN 1 ELSE 0 END) as losses
+ FROM ken_predictions WHERE created_at > NOW() - INTERVAL '24 hours'
+ `);
+ const perf = perfRows[0];
+ if (perf && parseInt(perf.total_preds) > 0) {
+ parts.push(`_24h stats: ${perf.total_preds} predictions, ${perf.wins || 0}W/${perf.losses || 0}L_`);
+ }
+ } catch {}
+
+ parts.push(`\nDashboard: http://45.61.58.125:7810`);
+
+ await sendSlack(parts.join('\n\n'));
+
+ // Update performance row
+ try {
+ await kenQ(`UPDATE ken_performance SET slack_sent = true WHERE id = (SELECT MAX(id) FROM ken_performance)`);
+ } catch {}
+ } else if (allSignals.length > 0) {
+ const cooldownLeft = Math.max(0, Math.round((SLACK_COOLDOWN_MS - (now - lastSlackTime)) / 60000));
+ console.log(`[Ken] ${allSignals.length} signals found, Slack cooldown: ${cooldownLeft}min left`);
+ } else {
+ console.log(`[Ken] No signals this cycle (${allMarkets.length} markets scanned)`);
+ }
+
+ } catch (err) {
+ console.error('[Ken] Autonomous scan error:', err.message);
+ try { await sendSlack(`:warning: *Ken Error* — Scan failed: ${err.message}`); } catch {}
+ }
+}
+
+// ══════════════════════════════════════════════
+// AUTO-PORTFOLIO TRADING ENGINE — 10 personalities, $20/day each
+// ══════════════════════════════════════════════
+
+// Portfolio strategy filters — each personality decides differently
+// ═══ Portfolio Strategy Filters ═══
+// Each strategy is deliberately exclusive — a signal should match 1-3 portfolios, not all 10.
+// Strategies use edge/confidence/direction/article count/MC/AI to create real diversification.
+const PORTFOLIO_STRATEGIES = {
+ // Alpha: High edge (>15%) with LOWER confidence (<70%). Big edges, less certainty — speculative.
+ aggressive: (sig) => Math.abs(sig.edge) >= 0.15 && sig.confidence < 0.70,
+
+ // Beta: High confidence (>70%) with ANY edge. The "safe" bet — trusts confidence over edge size.
+ conservative: (sig) => sig.confidence >= 0.70 && Math.abs(sig.edge) >= 0.05,
+
+ // Storm: Weather/climate markets identified by market_id patterns or reasoning keywords
+ weather: (sig) => /weather|temp|rain|snow|wind|hurricane|precip|storm|°f|heat|cold|frost|drought|flood|tornado|KXTEMP|KXRAIN|KXSNOW|KXHURR/i.test((sig.reasoning || '') + ' ' + (sig.market_id || '')),
+
+ // Momentum: Only trades when edge increased (high agreement = many articles agree).
+ // Needs 3+ articles with >65% agreement — evidence of growing consensus.
+ momentum: (sig) => (sig.agreement || 0) >= 0.65 && (sig.num_articles || 0) >= 3 && Math.abs(sig.edge) >= 0.05,
+
+ // Contrarian: ONLY BUY_NO trades. Bets against the crowd. Never buys YES.
+ contrarian: (sig) => sig.direction === 'BUY_NO',
+
+ // Nova: Only Gemini AI-enhanced signals. If AI didn't weigh in, skip.
+ ai_enhanced: (sig) => sig.ai_enhanced === true,
+
+ // Oracle: MC-validated WITH tight spread (stdDev < 8%) AND moderate edge. The "careful" bot.
+ mc_validated: (sig) => sig.mc_consistent === true && (sig.mc_stddev || 99) < 0.08 && Math.abs(sig.edge) >= 0.05 && Math.abs(sig.edge) < 0.20,
+
+ // Shark: Small edges (3-10%), rapid fire. Takes quantity over quality. Rejects big edges.
+ scalper: (sig) => Math.abs(sig.edge) >= 0.03 && Math.abs(sig.edge) < 0.10 && sig.confidence >= 0.30,
+
+ // Turtle: Ultra-patient. Needs EVERYTHING: 5+ articles, MC consistent, confidence >80%, moderate edge.
+ patient: (sig) => sig.confidence >= 0.80 && sig.mc_consistent === true && (sig.num_articles || 0) >= 5 && Math.abs(sig.edge) >= 0.05,
+
+ // Wildcard: Random 20% of signals — true control group. Lower chance than before to create separation.
+ random: (sig) => Math.random() < 0.20,
+
+ // ═══ RISKY PORTFAUXLIOS: Micro → Macro ═══
+
+ // Penny: Any edge >= 1%. Catches everything. Micro bets, max volume.
+ penny_pincher: (sig) => Math.abs(sig.edge) >= 0.01,
+
+ // Spray: Random 50% of ALL signals. Shotgun approach — tests luck vs skill.
+ spray_pray: (sig) => Math.random() < 0.50,
+
+ // Nickel: Low bar (edge >= 2%, conf >= 20%). Catches most signals.
+ nickel_slots: (sig) => Math.abs(sig.edge) >= 0.02 && sig.confidence >= 0.20,
+
+ // Degen: Edge >= 5%, ignores confidence entirely. Pure edge chaser.
+ degen_lite: (sig) => Math.abs(sig.edge) >= 0.05,
+
+ // Politics: Only political markets. KXPRES, KXSEN, KXGOV, KXCONGRESS, KXPRESPERSON, etc.
+ politics_junkie: (sig) => /KXPRES|KXSEN|KXGOV|KXCONG|KXHOUSE|KXELEC|KXPARTY|KXPRESPERSON|political|election|congress|senate|president|governor/i.test((sig.market_id || '') + ' ' + (sig.reasoning || '')),
+
+ // Double: Only high-edge signals (>20%). Goes big when edge is massive.
+ double_down: (sig) => Math.abs(sig.edge) >= 0.20,
+
+ // Night: Only signals with high MC stddev (>8%) — volatile markets others reject.
+ volatility_rider: (sig) => (sig.mc_stddev || 0) >= 0.08 && Math.abs(sig.edge) >= 0.05,
+
+ // Whale: Edge >25% AND confidence >60%. Rare but massive. The sniper.
+ whale: (sig) => Math.abs(sig.edge) >= 0.25 && sig.confidence >= 0.60,
+
+ // YOLO: Edge >30%. Doesn't care about anything else. Max degen.
+ yolo: (sig) => Math.abs(sig.edge) >= 0.30,
+
+ // Full Send: Takes EVERY signal. Max exposure. Tests whether the signal pipeline itself is profitable.
+ full_send: (sig) => true,
+
+ // ═══ CPU-POWERED: Computational / Multi-Factor Strategies ═══
+
+ // Kelly: Only trades when Kelly fraction (edge / odds) > 0.10. Classic bankroll math.
+ // Kelly f* = (bp - q) / b where b=odds, p=prob_win, q=prob_lose. Simplified: edge/(1+edge).
+ kelly_criterion: (sig) => {
+ const e = Math.abs(sig.edge);
+ const kelly = e / (1 + e); // simplified Kelly fraction
+ return kelly >= 0.10 && sig.confidence >= 0.40;
+ },
+
+ // Sharpe: Signal-to-noise ratio. edge / mc_stddev > 2.0. High SNR = clean signal, low noise.
+ sharpe_sniper: (sig) => {
+ const snr = Math.abs(sig.edge) / Math.max(sig.mc_stddev, 0.01);
+ return snr >= 2.0 && sig.mc_consistent;
+ },
+
+ // Bayesian: Combines confidence with article count as evidence weight.
+ // More articles = stronger prior. posterior = conf * (1 - 1/(1+articles)) * edge_factor.
+ bayesian_blend: (sig) => {
+ const evidenceWeight = 1 - 1 / (1 + (sig.num_articles || 0));
+ const posterior = sig.confidence * evidenceWeight * (1 + Math.abs(sig.edge));
+ return posterior >= 0.55;
+ },
+
+ // Ensemble: ALL factors must align — AI + MC + confidence + edge. Maximum consensus required.
+ ensemble_lock: (sig) => sig.ai_enhanced && sig.mc_consistent && sig.confidence >= 0.60 && Math.abs(sig.edge) >= 0.10 && (sig.num_articles || 0) >= 2,
+
+ // Mean Revert: High MC volatility (stddev > 10%) + moderate edge. Bets on reversion to mean.
+ mean_revert: (sig) => (sig.mc_stddev || 0) >= 0.10 && Math.abs(sig.edge) >= 0.08 && Math.abs(sig.edge) <= 0.25,
+
+ // Info Ratio: (articles * agreement) / max(mc_stddev, 0.01). Quality of information per unit noise.
+ info_ratio: (sig) => {
+ const ir = ((sig.num_articles || 0) * (sig.agreement || 0)) / Math.max(sig.mc_stddev, 0.01);
+ return ir >= 15 && Math.abs(sig.edge) >= 0.05;
+ },
+
+ // Anti-FOMO: Small edge (<12%) but HIGH confidence (>75%). Calm, certain, steady plays.
+ anti_fomo: (sig) => Math.abs(sig.edge) >= 0.03 && Math.abs(sig.edge) <= 0.12 && sig.confidence >= 0.75,
+
+ // Nightcrawler: BUY_NO only + AI enhanced + MC consistent. Sophisticated short-bias strategy.
+ nightcrawler: (sig) => sig.direction === 'BUY_NO' && sig.ai_enhanced && sig.mc_consistent,
+
+ // Heatseeker: Composite multi-factor score. Weighted blend of all signal dimensions.
+ // score = edge*40 + conf*30 + agreement*20 + min(articles/10,1)*10. Trade when score > 35.
+ heatseeker: (sig) => {
+ const score = Math.abs(sig.edge) * 40 + sig.confidence * 30 + (sig.agreement || 0) * 20 + Math.min((sig.num_articles || 0) / 10, 1) * 10;
+ return score >= 35;
+ },
+
+ // Quant: Geometric mean of edge and confidence, weighted by MC consistency. Pure math bot.
+ // geoMean = sqrt(edge * conf). Trade when geoMean > 0.15 and MC agrees.
+ quant_core: (sig) => {
+ const geo = Math.sqrt(Math.abs(sig.edge) * Math.max(sig.confidence, 0.001));
+ return geo >= 0.15 && (sig.mc_consistent || sig.confidence >= 0.80);
+ },
+
+ // ═══ ETF CATEGORY SPECIALISTS: Sector-Focused Portfolios ═══
+
+ etf_presidential: (sig) => /KXPRESPERSON|KXPRESPARTY/i.test(sig.market_id) ||
+ /president|2028 election|presidential race|white house|oval office|nominee/i.test(sig.reasoning + ' ' + sig.market_title),
+
+ etf_cabinet: (sig) => /KXCABOUT|KXCABLEAVE/i.test(sig.market_id) ||
+ /cabinet|secretary of|confirmation hearing|appointee|gabbard|hegseth|rubio|noem|rfk|bessent|lutnick/i.test(sig.reasoning + ' ' + sig.market_title),
+
+ etf_congress: (sig) => /KXCONG|KXHOUSE|SENATE|KXNEXTSPEAKER|KXCAPCONTROL|KXVETOOVERRIDE/i.test(sig.market_id) ||
+ /congress|senate|house of rep|speaker|legislation|bill pass|shutdown|filibuster|debt ceiling/i.test(sig.reasoning + ' ' + sig.market_title),
+
+ etf_scotus: (sig) => /KXSCOURT/i.test(sig.market_id) ||
+ /supreme court|scotus|justice|ruling|overturn|constitutional|judicial review/i.test(sig.reasoning + ' ' + sig.market_title),
+
+ etf_fed: (sig) => /KXFEDCHAIRNOM|KXBALANCE/i.test(sig.market_id) ||
+ /federal reserve|fed chair|interest rate|fomc|rate cut|rate hike|powell|warsh|monetary policy|quantitative/i.test(sig.reasoning + ' ' + sig.market_title),
+
+ etf_economy: (sig) => /KXGDP/i.test(sig.market_id) ||
+ /\bgdp\b|recession|economic growth|jobs report|unemployment|nonfarm payroll|consumer spending|retail sales|pce\b|cpi\b/i.test(sig.reasoning + ' ' + sig.market_title),
+
+ etf_geopolitics: (sig) => /KXZELENSKYPUTIN|KXNEXTUKPM|KXNEXTIRANLEADER|KXEUEXIT|KXTAIWANLVL|KXFTA/i.test(sig.market_id) ||
+ /geopolit|war\b|invasion|sanction|nato|treaty|ceasefire|diplomat|putin|zelensky|china|taiwan|iran|tariff|trade war/i.test(sig.reasoning + ' ' + sig.market_title),
+
+ etf_territory: (sig) => /KXGREENLAND|KXGREENTERRITORY|KXGREENLANDPRICE|KXGTAPRICE|KXSTATE51|KXUSAEXPANDTERRITORY/i.test(sig.market_id) ||
+ /greenland|statehood|territory|annex|state 51|panama canal|territorial/i.test(sig.reasoning + ' ' + sig.market_title),
+
+ etf_climate: (sig) => /KXWARMING|KXTEMP|KXRAIN|KXSNOW|KXHURR/i.test(sig.market_id) ||
+ /warming|climate|temperature|hurricane|tornado|flood|drought|polar vortex|heat wave|cold snap|freeze|precipitation|storm/i.test(sig.reasoning + ' ' + sig.market_title),
+
+ etf_energy: (sig) => /KXPRIMEENGCONSUMPTION|KXENERG/i.test(sig.market_id) ||
+ /\benergy\b|lng\b|natural gas|oil price|petroleum|electricity|power grid|blackout|eia\b|opec|crude|pipeline|refinery|utility|heating bill/i.test(sig.reasoning + ' ' + sig.market_title),
+
+ etf_tech: (sig) => /KXOAIANTH|KXMUSKTRILLION|KXFUSION/i.test(sig.market_id) ||
+ /artificial intelligence|\bai\b|openai|anthropic|chatgpt|gpt-5|machine learning|musk.*trillion|tesla|nvidia|semiconductor|quantum computing|fusion/i.test(sig.reasoning + ' ' + sig.market_title),
+
+ etf_space: (sig) => /KXMOONMAN|KXCOLONIZEMARS|KXSPACEX/i.test(sig.market_id) ||
+ /spacex|nasa|rocket|orbit|mars|moon|starship|falcon|launch|artemis|blue origin|astronaut|satellite/i.test(sig.reasoning + ' ' + sig.market_title),
+
+ etf_crypto: (sig) => /KXCRYPTO|KXBTC|KXETH/i.test(sig.market_id) ||
+ /bitcoin|btc|ethereum|eth|crypto|blockchain|defi|stablecoin|sec.*crypto|digital asset|web3|binance|coinbase/i.test(sig.reasoning + ' ' + sig.market_title),
+
+ etf_sports: (sig) => /KXNBA|KXNFL|KXNBASEATTLE|KXCANADACUP/i.test(sig.market_id) ||
+ /\bnba\b|\bnfl\b|\bmlb\b|\bnhl\b|sports|playoff|championship|super bowl|world series|draft|mvp|coach/i.test(sig.reasoning + ' ' + sig.market_title),
+
+ etf_entertainment: (sig) => /KXSWIFTKELCE|KXTAYLORSWIFT|KXACTORSONNYCROCKETT|KXLIVENATION/i.test(sig.market_id) ||
+ /taylor swift|celebrity|movie|oscar|grammy|concert|entertainment|viral|streaming|netflix|album|tour/i.test(sig.reasoning + ' ' + sig.market_title),
+
+ etf_legal: (sig) => /KXTRUMPPARDONS|KXINSURRECTION|KXIMPEACH|KXTRUMPREMOVE|KXTRUMPRESIGN/i.test(sig.market_id) ||
+ /pardon|impeach|indictment|trial|guilty|conviction|sentencing|insurrection|special counsel|subpoena|contempt/i.test(sig.reasoning + ' ' + sig.market_title),
+
+ etf_financials: (sig) => /KXBOND/i.test(sig.market_id) ||
+ /bond yield|treasury|10-year|yield curve|s&p|nasdaq|dow jones|stock market|bear market|bull market|correction|ipo|banking/i.test(sig.reasoning + ' ' + sig.market_title),
+
+ etf_govreform: (sig) => /KXAGENCYELIM|KXGOVTCUTS|KXWITHDRAW/i.test(sig.market_id) ||
+ /\bdoge\b|government efficiency|agency.*elim|department.*cut|federal workforce|deregulat|budget cut|spending cut|executive order/i.test(sig.reasoning + ' ' + sig.market_title),
+
+ etf_global_social: (sig) => /KXNEWPOPE|KXALBERTAREFYES/i.test(sig.market_id) ||
+ /pope|vatican|catholic|referendum|independence|separatist|social movement|protest|migration|refugee/i.test(sig.reasoning + ' ' + sig.market_title),
+
+ etf_broad_market: (sig) => Math.abs(sig.edge) >= 0.08 && sig.confidence >= 0.50 && (sig.mc_consistent || sig.ai_enhanced),
+
+ // ═══ SECTOR-BASED PORTFOLIOS (IDs 51-100): Granular sub-sector filters ═══
+
+ // — Energy & Commodities (51-55) —
+ lng_exports: (sig) => /lng|liquefied natural gas|natural gas export|gas terminal|lng shipment|henry hub/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ oil_price_band: (sig) => /\boil\b|crude|brent|wti|petroleum|barrel|oil price|oil production/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ natgas_seasonal: (sig) => /natural gas|natgas|gas price|gas storage|heating season|gas futures/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ opec_decisions: (sig) => /opec|oil cartel|production cut|oil output|saudi.*oil|oil supply/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ power_grid: (sig) => /power grid|blackout|electricity|energy grid|brownout|utility|power outage|grid fail/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+
+ // — AI & Tech Stocks (56-60) —
+ semiconductor: (sig) => /semiconductor|chip|nvidia|tsmc|intel|amd|chip act|wafer|fab\b|gpu shortage/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ ai_regulation: (sig) => /ai regulation|ai safety|ai executive order|ai bill|regulate.*ai|ai governance|ai act/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ tech_earnings: (sig) => /tech.*earning|earning.*tech|apple.*revenue|google.*revenue|meta.*revenue|amazon.*revenue|magnificent seven|big tech.*report/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ autonomous_vehicles: (sig) => /autonomous|self.driving|robotaxi|waymo|cruise|lidar|adas|driverless/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ cloud_market: (sig) => /cloud computing|aws|azure|google cloud|cloud revenue|saas|cloud market|cloud spend/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+
+ // — Crypto & Digital (61-65) —
+ btc_price_bands: (sig) => /bitcoin|btc|bitcoin price|btc.*\$|bitcoin.*\$|bitcoin.*above|bitcoin.*below/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ eth_upgrades: (sig) => /ethereum|eth\b|eth.*upgrade|ethereum.*upgrade|ethereum.*merge|eth.*fork|ether.*price/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ crypto_regulation: (sig) => /crypto.*regulat|sec.*crypto|crypto.*ban|crypto.*bill|digital asset.*law|crypto.*legal|stablecoin.*act/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ stablecoin_policy: (sig) => /stablecoin|usdt|usdc|tether|circle|stablecoin.*regulat|stablecoin.*bill|cbdc/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ defi_events: (sig) => /defi|decentralized finance|dex|uniswap|aave|compound|liquidity pool|yield farm|tvl/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+
+ // — Macro Economics (66-70) —
+ cpi_monthly: (sig) => /\bcpi\b|consumer price|inflation.*rate|inflation.*report|core inflation|price index/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ nfp_monthly: (sig) => /nonfarm|non.farm|payroll|jobs report|jobs.*added|employment.*report|unemployment.*rate|jobless.*claim/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ housing_data: (sig) => /housing|home.*sale|home.*price|mortgage|existing home|housing start|case.shiller|real estate.*data/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ gdp_quarterly: (sig) => /\bgdp\b|gross domestic|economic growth|gdp.*quarter|gdp.*annual|recession.*gdp/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ yield_spread: (sig) => /yield curve|yield spread|inverted yield|2.year.*10.year|treasury spread|curve inversion/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+
+ // — Finance & Markets (71-75) —
+ sp500_levels: (sig) => /s&p|s&p 500|sp500|spx|s&p.*above|s&p.*below|stock market.*level/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ fed_rate_path: (sig) => /fed.*rate|interest rate|fomc|rate cut|rate hike|federal funds|fed.*meeting|monetary policy|powell.*rate/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ bank_stress: (sig) => /bank.*stress|bank.*fail|banking crisis|bank run|fdic|bank.*collapse|regional bank|svb|silicon valley bank/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ bond_yields: (sig) => /bond.*yield|treasury.*yield|10.year.*yield|bond.*market|treasury.*rate|bond.*price/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ volatility_index: (sig) => /\bvix\b|volatility index|volatility.*spike|cboe|fear.*index|market.*volatility/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+
+ // — Politics & Policy (76-80) —
+ state_elections: (sig) => /KXSEN|KXGOV|state election|governor.*race|senate.*race|state house|state legislature|primary.*election/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ congress_votes: (sig) => /KXCONG|KXHOUSE|congress.*vote|house.*vote|senate.*vote|bill.*pass|legislation.*vote|floor vote/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ tariff_policy: (sig) => /tariff|trade war|import duty|trade deficit|trade policy|customs duty|trade agreement|wto/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ immigration_policy: (sig) => /immigration|border|migrant|asylum|deportation|visa|daca|immigration.*reform|border.*wall/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ tax_legislation: (sig) => /tax.*bill|tax.*reform|tax.*cut|tax.*hike|tax.*code|irs|estate tax|capital gains.*tax|corporate tax/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+
+ // — Sports (81-85) —
+ nba_outcomes: (sig) => /KXNBA|\bnba\b|basketball|nba.*final|nba.*champion|nba.*mvp|nba.*draft/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ nfl_outcomes: (sig) => /KXNFL|\bnfl\b|football|super bowl|nfl.*draft|nfl.*champion|quarterback|touchdown/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ soccer_global: (sig) => /soccer|football.*world|world cup|premier league|champions league|mls|fifa|la liga|bundesliga/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ mlb_outcomes: (sig) => /KXMLB|\bmlb\b|baseball|world series|mlb.*draft|home run|batting|pitcher/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ combat_sports: (sig) => /\bufc\b|\bmma\b|boxing|fight.*night|ufc.*champion|knockout|title fight|heavyweight/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+
+ // — Health & Science (86-90) —
+ fda_approvals: (sig) => /fda.*approv|fda.*reject|drug.*approv|new drug|biologic.*approv|fda.*review|pdufa/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ disease_tracking: (sig) => /outbreak|pandemic|epidemic|covid|h5n1|bird flu|mpox|disease.*spread|cdc.*alert|who.*emergency/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ biotech_catalysts: (sig) => /biotech|clinical trial|phase 3|gene therapy|mrna|crispr|drug.*trial|biotech.*stock/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ health_metrics: (sig) => /life expectancy|obesity|opioid|drug overdose|health.*metric|public health|mortality rate|vaccination rate/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ space_milestones: (sig) => /spacex|nasa|rocket.*launch|mars|moon.*landing|starship|artemis|blue origin|orbit|satellite.*launch/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+
+ // — Media & Culture (91-95) —
+ box_office: (sig) => /box office|movie.*gross|film.*revenue|opening weekend|blockbuster|cinema.*sales/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ awards_shows: (sig) => /oscar|grammy|emmy|golden globe|academy award|best picture|best actor|awards.*ceremony/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ streaming_subs: (sig) => /netflix.*subscriber|disney.*subscriber|streaming.*war|subscriber.*count|streaming.*growth|hulu|paramount/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ social_trends: (sig) => /viral|tiktok|social media.*trend|influencer|twitter.*trend|internet.*culture|meme/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ reality_outcomes: (sig) => /reality tv|bachelor|survivor|big brother|reality.*show|dancing.*stars|masked singer/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+
+ // — Global & Geopolitics (96-100) —
+ global_conflicts: (sig) => /war\b|invasion|ceasefire|military.*conflict|armed conflict|escalation|airstrike|troops.*deploy/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ sanctions_policy: (sig) => /sanction|embargo|trade restriction|asset freeze|sanctions.*russia|sanctions.*china|sanctions.*iran/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ climate_extremes: (sig) => /climate.*extreme|extreme weather|heat.*record|cold.*record|flood|wildfire|hurricane.*category|tornado|drought/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ forex_events: (sig) => /forex|currency.*crisis|dollar.*index|yen|euro.*dollar|fx.*rate|currency.*devaluation|exchange rate/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ geopolitical_shock: (sig) => /black swan|geopolitical.*shock|coup|assassination|regime.*change|emergency.*declaration|martial law|unexpected.*event/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+};
+
+// Position sizing per strategy — differentiated risk profiles
+const PORTFOLIO_SIZING = {
+ aggressive: (edge, conf) => Math.max(2, Math.min(5, Math.round(Math.abs(edge) * 30))), // 2-5 contracts, edge-weighted
+ conservative: (edge, conf) => Math.max(1, Math.min(3, Math.round(conf * 4))), // 1-3 contracts, confidence-weighted
+ weather: (edge, conf) => 2, // Fixed 2 contracts
+ momentum: (edge, conf) => Math.max(1, Math.min(4, Math.round((conf + Math.abs(edge)) * 5))),// 1-4, blended
+ contrarian: (edge, conf) => 1, // Always 1 contract (high risk)
+ ai_enhanced: (edge, conf) => Math.max(1, Math.min(3, Math.round(conf * 3))), // 1-3, conservative
+ mc_validated: (edge, conf) => Math.max(2, Math.min(4, Math.round(conf * 5))), // 2-4, confidence-driven
+ scalper: (edge, conf) => 1, // Always 1 (high volume, small bets)
+ patient: (edge, conf) => Math.max(3, Math.min(5, Math.round(conf * 6))), // 3-5, big when confident
+ random: (edge, conf) => Math.max(1, Math.min(3, Math.ceil(Math.random() * 3))), // 1-3 random
+
+ // ═══ RISKY SIZING: Micro → Macro ═══
+ penny_pincher: () => 1, // Always 1 — micro
+ spray_pray: () => Math.ceil(Math.random() * 2), // 1-2 random
+ nickel_slots: () => 1, // Fixed 1
+ degen_lite: (edge) => Math.max(1, Math.min(3, Math.round(Math.abs(edge) * 20))), // 1-3, edge-scaled
+ politics_junkie: (edge, conf) => Math.max(2, Math.min(3, Math.round(conf * 4))), // 2-3, confidence
+ double_down: (edge) => Math.max(4, Math.min(8, Math.round(Math.abs(edge) * 30))), // 4-8, big edge bets
+ volatility_rider: (edge) => Math.max(2, Math.min(4, Math.round(Math.abs(edge) * 25))), // 2-4, edge-weighted
+ whale: (edge, conf) => Math.max(5, Math.min(10, Math.round(conf * 12))), // 5-10, confidence-heavy
+ yolo: (edge) => Math.max(8, Math.min(15, Math.round(Math.abs(edge) * 40))), // 8-15, MAX edge scale
+ full_send: (edge, conf) => Math.max(1, Math.min(25, Math.round(Math.abs(edge) * conf * 50))),// 1-25, edge*conf scaled
+
+ // ═══ CPU-POWERED SIZING: Computational approaches ═══
+ kelly_criterion: (edge, conf) => Math.max(1, Math.min(8, Math.round((edge / (1 + edge)) * 20))), // Kelly fraction scaled to 1-8
+ sharpe_sniper: (edge, conf) => Math.max(2, Math.min(6, Math.round(conf * 8))), // 2-6, conf-weighted (high SNR = trust it)
+ bayesian_blend: (edge, conf) => Math.max(1, Math.min(5, Math.round(Math.sqrt(edge * conf) * 15))), // 1-5, geometric scaling
+ ensemble_lock: (edge, conf) => Math.max(3, Math.min(7, Math.round((edge + conf) * 5))), // 3-7, sum-scaled (all factors aligned)
+ mean_revert: (edge, conf) => Math.max(1, Math.min(4, Math.round(edge * 15))), // 1-4, moderate sizing for reversion plays
+ info_ratio: (edge, conf) => Math.max(2, Math.min(5, Math.round(conf * 6))), // 2-5, confidence-driven
+ anti_fomo: (edge, conf) => Math.max(2, Math.min(4, Math.round(conf * 5))), // 2-4, steady sizing for calm plays
+ nightcrawler: (edge, conf) => Math.max(1, Math.min(3, Math.round(conf * 4))), // 1-3, conservative shorts
+ heatseeker: (edge, conf) => Math.max(2, Math.min(6, Math.round((edge * 20 + conf * 3) / 2))), // 2-6, composite score-driven
+ quant_core: (edge, conf) => Math.max(2, Math.min(8, Math.round(Math.sqrt(edge * conf) * 25))), // 2-8, geometric mean heavy
+
+ // ═══ ETF CATEGORY SIZING ═══
+ etf_presidential: (edge, conf) => Math.max(1, Math.min(4, Math.round(conf * 5))),
+ etf_cabinet: (edge, conf) => Math.max(1, Math.min(3, Math.round(conf * 4))),
+ etf_congress: (edge, conf) => Math.max(1, Math.min(3, Math.round(conf * 4))),
+ etf_scotus: (edge, conf) => Math.max(1, Math.min(3, Math.round(conf * 3))),
+ etf_fed: (edge, conf) => Math.max(2, Math.min(5, Math.round(edge * 20 + conf * 2))),
+ etf_economy: (edge, conf) => Math.max(1, Math.min(4, Math.round(edge * 15))),
+ etf_geopolitics: (edge, conf) => Math.max(1, Math.min(3, Math.round(conf * 4))),
+ etf_territory: (edge, conf) => Math.max(1, Math.min(3, Math.round(conf * 3))),
+ etf_climate: () => 2,
+ etf_energy: (edge, conf) => Math.max(1, Math.min(4, Math.round(edge * 18))),
+ etf_tech: (edge, conf) => Math.max(2, Math.min(5, Math.round(conf * 6))),
+ etf_space: (edge, conf) => Math.max(1, Math.min(3, Math.round(conf * 3))),
+ etf_crypto: (edge, conf) => Math.max(1, Math.min(4, Math.round(edge * 20))),
+ etf_sports: (edge, conf) => Math.max(1, Math.min(3, Math.round(conf * 4))),
+ etf_entertainment: (edge, conf) => Math.max(1, Math.min(2, Math.round(conf * 3))),
+ etf_legal: (edge, conf) => Math.max(1, Math.min(3, Math.round(conf * 4))),
+ etf_financials: (edge, conf) => Math.max(2, Math.min(5, Math.round(conf * 6))),
+ etf_govreform: (edge, conf) => Math.max(1, Math.min(3, Math.round(conf * 3))),
+ etf_global_social: (edge, conf) => Math.max(1, Math.min(2, Math.round(conf * 2))),
+ etf_broad_market: (edge, conf) => Math.max(2, Math.min(6, Math.round(edge * 15 + conf * 3))),
+
+ // ═══ SECTOR-BASED SIZING (IDs 51-100): Conservative niche bets ═══
+
+ // — Energy & Commodities (51-55) — Moderate sizing, energy can be volatile
+ lng_exports: (edge, conf) => Math.max(1, Math.min(3, Math.round(conf * 4))),
+ oil_price_band: (edge, conf) => Math.max(1, Math.min(4, Math.round(edge * 15))),
+ natgas_seasonal: (edge, conf) => Math.max(1, Math.min(3, Math.round(conf * 3))),
+ opec_decisions: (edge, conf) => Math.max(1, Math.min(3, Math.round(edge * 12))),
+ power_grid: (edge, conf) => Math.max(1, Math.min(2, Math.round(conf * 3))),
+
+ // — AI & Tech Stocks (56-60) — Slightly larger, higher conviction sector
+ semiconductor: (edge, conf) => Math.max(1, Math.min(4, Math.round(conf * 5))),
+ ai_regulation: (edge, conf) => Math.max(1, Math.min(3, Math.round(conf * 4))),
+ tech_earnings: (edge, conf) => Math.max(2, Math.min(5, Math.round(edge * 18))),
+ autonomous_vehicles: (edge, conf) => Math.max(1, Math.min(3, Math.round(conf * 3))),
+ cloud_market: (edge, conf) => Math.max(1, Math.min(3, Math.round(conf * 4))),
+
+ // — Crypto & Digital (61-65) — Volatile, keep positions smaller
+ btc_price_bands: (edge, conf) => Math.max(1, Math.min(4, Math.round(edge * 16))),
+ eth_upgrades: (edge, conf) => Math.max(1, Math.min(3, Math.round(conf * 3))),
+ crypto_regulation: (edge, conf) => Math.max(1, Math.min(3, Math.round(conf * 4))),
+ stablecoin_policy: (edge, conf) => Math.max(1, Math.min(2, Math.round(conf * 3))),
+ defi_events: (edge, conf) => Math.max(1, Math.min(2, Math.round(edge * 10))),
+
+ // — Macro Economics (66-70) — Data-driven, moderate confidence sizing
+ cpi_monthly: (edge, conf) => Math.max(1, Math.min(4, Math.round(conf * 5))),
+ nfp_monthly: (edge, conf) => Math.max(1, Math.min(4, Math.round(conf * 5))),
+ housing_data: (edge, conf) => Math.max(1, Math.min(3, Math.round(conf * 4))),
+ gdp_quarterly: (edge, conf) => Math.max(1, Math.min(4, Math.round(edge * 15))),
+ yield_spread: (edge, conf) => Math.max(1, Math.min(3, Math.round(conf * 4))),
+
+ // — Finance & Markets (71-75) — Established signals, moderate-to-large
+ sp500_levels: (edge, conf) => Math.max(2, Math.min(5, Math.round(edge * 20))),
+ fed_rate_path: (edge, conf) => Math.max(2, Math.min(5, Math.round(conf * 6))),
+ bank_stress: (edge, conf) => Math.max(1, Math.min(3, Math.round(edge * 12))),
+ bond_yields: (edge, conf) => Math.max(1, Math.min(4, Math.round(conf * 5))),
+ volatility_index: (edge, conf) => Math.max(1, Math.min(4, Math.round(edge * 18))),
+
+ // — Politics & Policy (76-80) — Binary outcomes, confidence-weighted
+ state_elections: (edge, conf) => Math.max(1, Math.min(3, Math.round(conf * 4))),
+ congress_votes: (edge, conf) => Math.max(1, Math.min(3, Math.round(conf * 4))),
+ tariff_policy: (edge, conf) => Math.max(1, Math.min(3, Math.round(edge * 12))),
+ immigration_policy: (edge, conf) => Math.max(1, Math.min(2, Math.round(conf * 3))),
+ tax_legislation: (edge, conf) => Math.max(1, Math.min(3, Math.round(conf * 3))),
+
+ // — Sports (81-85) — Event-driven, fixed small sizing
+ nba_outcomes: (edge, conf) => Math.max(1, Math.min(3, Math.round(conf * 4))),
+ nfl_outcomes: (edge, conf) => Math.max(1, Math.min(3, Math.round(conf * 4))),
+ soccer_global: (edge, conf) => Math.max(1, Math.min(2, Math.round(conf * 3))),
+ mlb_outcomes: (edge, conf) => Math.max(1, Math.min(3, Math.round(conf * 3))),
+ combat_sports: (edge, conf) => Math.max(1, Math.min(2, Math.round(conf * 3))),
+
+ // — Health & Science (86-90) — High-impact but rare, small positions
+ fda_approvals: (edge, conf) => Math.max(1, Math.min(3, Math.round(conf * 4))),
+ disease_tracking: (edge, conf) => Math.max(1, Math.min(3, Math.round(edge * 12))),
+ biotech_catalysts: (edge, conf) => Math.max(1, Math.min(3, Math.round(edge * 10))),
+ health_metrics: (edge, conf) => Math.max(1, Math.min(2, Math.round(conf * 2))),
+ space_milestones: (edge, conf) => Math.max(1, Math.min(2, Math.round(conf * 3))),
+
+ // — Media & Culture (91-95) — Fun bets, keep small
+ box_office: (edge, conf) => Math.max(1, Math.min(2, Math.round(conf * 3))),
+ awards_shows: (edge, conf) => Math.max(1, Math.min(2, Math.round(conf * 3))),
+ streaming_subs: (edge, conf) => Math.max(1, Math.min(2, Math.round(conf * 2))),
+ social_trends: (edge, conf) => Math.max(1, Math.min(2, Math.round(edge * 8))),
+ reality_outcomes: (edge, conf) => Math.max(1, Math.min(2, Math.round(conf * 2))),
+
+ // — Global & Geopolitics (96-100) — High uncertainty, conservative
+ global_conflicts: (edge, conf) => Math.max(1, Math.min(3, Math.round(edge * 12))),
+ sanctions_policy: (edge, conf) => Math.max(1, Math.min(2, Math.round(conf * 3))),
+ climate_extremes: (edge, conf) => Math.max(1, Math.min(3, Math.round(edge * 10))),
+ forex_events: (edge, conf) => Math.max(1, Math.min(3, Math.round(conf * 4))),
+ geopolitical_shock: (edge, conf) => Math.max(1, Math.min(2, Math.round(edge * 8))),
+};
+
+let tradeCounter = 0; // For wildcard portfolio
+
+async function autoPortfolioTrade(signal) {
+ try {
+ const { rows: portfolios } = await kenQ('SELECT * FROM ken_portfolios');
+ const today = new Date().toISOString().split('T')[0];
+
+ for (const pf of portfolios) {
+ const strategy = PORTFOLIO_STRATEGIES[pf.strategy];
+ if (!strategy) continue;
+
+ // Check balance: bankrupt portfolios can't trade (balance = 0 → move to bottom)
+ if (pf.balance_cents <= 0) continue; // BANKRUPT — no more trades
+
+ // Check if strategy accepts this signal
+ const sigData = {
+ edge: signal.expectedEdge || signal.expected_edge || 0,
+ confidence: signal.confidence || 0,
+ direction: signal.direction,
+ reasoning: signal.reasoning || '',
+ signal_type: signal.signal_type || '',
+ market_id: signal.marketId || signal.market_id || '',
+ ai_enhanced: signal.aiEnhanced || signal.ai_enhanced || false,
+ mc_consistent: signal.mcSimulation?.consistent || signal.mc_consistent || false,
+ mc_stddev: signal.mcSimulation?.stdDev || 0.99,
+ volume24h: signal.volume24h || signal.volume_24h || 0,
+ num_articles: signal.num_articles || 0,
+ agreement: signal.agreement || 0,
+ market_title: signal.market_title || signal.marketTitle || '',
+ };
+
+ if (!strategy(sigData)) continue;
+
+ // Hyper-trade: max 10 OPEN positions per market per portfolio (no daily cap)
+ const { rows: dupes } = await kenQ(`
+ SELECT id FROM ken_portfolio_trades
+ WHERE portfolio_id = $1 AND market_id = $2 AND status = 'open'
+ `, [pf.id, signal.marketId || signal.market_id]);
+ if (dupes.length >= 10) continue;
+
+ // Per-strategy position sizing
+ const absEdge = Math.abs(parseFloat(sigData.edge));
+ const conf = parseFloat(sigData.confidence);
+ const sizeFn = PORTFOLIO_SIZING[pf.strategy] || ((e, c) => Math.max(1, Math.min(3, Math.round(e * c * 15))));
+ const contracts = sizeFn(absEdge, conf);
+ const entryPrice = sigData.direction === 'BUY_YES'
+ ? Math.round((0.5 - absEdge / 2) * 100) // rough market mid
+ : Math.round((0.5 + absEdge / 2) * 100);
+ const clampedPrice = Math.max(5, Math.min(95, entryPrice));
+ const cost = clampedPrice * contracts;
+
+ if (cost > pf.balance_cents) continue; // Not enough balance for this trade
+
+ await kenQ(`
+ INSERT INTO ken_portfolio_trades (portfolio_id, signal_id, market_id, market_title, direction, entry_price_cents, contracts, cost_cents, reasoning, confidence, ai_enhanced, mc_consistent)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)
+ `, [pf.id, signal.id || null, signal.marketId || signal.market_id, signal.market_title || signal.marketTitle || '',
+ sigData.direction, clampedPrice, contracts, cost, (sigData.reasoning || '').substring(0, 500),
+ conf, sigData.ai_enhanced, sigData.mc_consistent]);
+
+ // Deduct from balance + update stats
+ await kenQ(`UPDATE ken_portfolios SET balance_cents = balance_cents - $1, total_invested_cents = total_invested_cents + $1, last_trade_at = NOW() WHERE id = $2`, [cost, pf.id]);
+ pf.balance_cents -= cost; // Update in-memory too for subsequent iterations
+
+ console.log(`[Ken/Portfolio] ${pf.name} (${pf.strategy}): ${sigData.direction} ${(signal.marketId || signal.market_id || '').substring(0, 30)} @ ${clampedPrice}¢ x${contracts} = $${(cost/100).toFixed(2)}`);
+ }
+ } catch (e) {
+ console.error('[Ken/Portfolio] Auto-trade error:', e.message);
+ }
+}
+
+// Capture NAV snapshots for charting — runs every 30 minutes
+async function capturePortfolioSnapshots() {
+ try {
+ const { rows: portfolios } = await kenQ('SELECT * FROM ken_portfolios');
+ for (const pf of portfolios) {
+ const { rows: openTrades } = await kenQ(`
+ SELECT entry_price_cents, contracts, direction, market_id
+ FROM ken_portfolio_trades WHERE portfolio_id = $1 AND status = 'open'
+ `, [pf.id]);
+
+ let openValue = 0;
+ for (const t of openTrades) {
+ const { rows: snaps } = await kenQ(`
+ SELECT last_price FROM ken_market_snapshots WHERE ticker = $1 ORDER BY captured_at DESC LIMIT 1
+ `, [t.market_id]);
+ if (snaps.length > 0) {
+ const curr = parseInt(snaps[0].last_price);
+ openValue += t.direction === 'BUY_YES'
+ ? (curr - t.entry_price_cents) * t.contracts
+ : (t.entry_price_cents - curr) * t.contracts;
+ }
+ }
+
+ const nav = (parseInt(pf.total_returned_cents) || 0) - (parseInt(pf.total_invested_cents) || 0) + openValue;
+ await kenQ(`
+ INSERT INTO ken_portfolio_snapshots (portfolio_id, nav_cents, open_positions) VALUES ($1, $2, $3)
+ `, [pf.id, nav, openTrades.length]);
+ }
+ console.log(`[Ken/Charts] NAV snapshots captured for ${portfolios.length} portfolios`);
+ } catch (e) {
+ console.error('[Ken/Charts] Snapshot error:', e.message);
+ }
+}
+
+// Resolve portfolio trades — HYPER MODE: quick take-profit/stop-loss + aging out
+async function resolvePortfolioTrades() {
+ try {
+ // Check ALL open trades (no minimum age for hyper-trading)
+ const { rows: openTrades } = await kenQ(`
+ SELECT pt.*, p.name as portfolio_name, p.strategy as portfolio_strategy
+ FROM ken_portfolio_trades pt
+ JOIN ken_portfolios p ON p.id = pt.portfolio_id
+ WHERE pt.status = 'open'
+ ORDER BY pt.created_at ASC
+ LIMIT 500
+ `);
+
+ for (const trade of openTrades) {
+ // Get latest price from snapshots
+ const { rows: snaps } = await kenQ(`
+ SELECT last_price FROM ken_market_snapshots
+ WHERE ticker = $1 ORDER BY captured_at DESC LIMIT 1
+ `, [trade.market_id]);
+
+ if (snaps.length === 0) continue;
+ const currentPrice = parseInt(snaps[0].last_price);
+ const ageMinutes = (Date.now() - new Date(trade.created_at).getTime()) / 60000;
+
+ let pnl = 0;
+ if (trade.direction === 'BUY_YES') {
+ pnl = (currentPrice - trade.entry_price_cents) * trade.contracts;
+ } else {
+ pnl = (trade.entry_price_cents - currentPrice) * trade.contracts;
+ }
+
+ // Hyper-trade exit rules:
+ // 1. Take profit: +3¢ per contract (minimum 5 min hold)
+ // 2. Stop loss: -5¢ per contract (minimum 5 min hold)
+ // 3. Age out: close after 2 hours regardless
+ let status = null;
+ const profitPerContract = pnl / Math.max(1, trade.contracts);
+
+ if (ageMinutes >= 5 && profitPerContract >= 3) {
+ status = 'won'; // Take profit
+ } else if (ageMinutes >= 5 && profitPerContract <= -5) {
+ status = 'lost'; // Stop loss
+ } else if (ageMinutes >= 120) {
+ // Age out after 2 hours — mark based on current P&L
+ status = pnl > 0 ? 'won' : pnl < 0 ? 'lost' : 'expired';
+ }
+
+ if (!status) continue; // Hold position
+
+ await kenQ(`
+ UPDATE ken_portfolio_trades SET status = $1, exit_price_cents = $2, pnl_cents = $3, resolved_at = NOW()
+ WHERE id = $4
+ `, [status, currentPrice, pnl, trade.id]);
+
+ // Update portfolio running totals
+ const streakVal = status === 'won' ? 1 : status === 'lost' ? -1 : 0;
+ // total_returned = cost_cents + pnl for winning trades (you get your money back + profit)
+ const returned = pnl > 0 ? trade.cost_cents + pnl : (pnl === 0 ? trade.cost_cents : 0);
+ const wonInc = status === 'won' ? 1 : 0;
+ const lostInc = status === 'lost' ? 1 : 0;
+ const expInc = status === 'expired' ? 1 : 0;
+ await kenQ(`
+ UPDATE ken_portfolios SET
+ balance_cents = balance_cents + $1,
+ total_returned_cents = total_returned_cents + $1,
+ trades_won = trades_won + $2,
+ trades_lost = trades_lost + $3,
+ trades_expired = trades_expired + $4,
+ streak = CASE WHEN $5 > 0 AND streak > 0 THEN streak + 1 WHEN $5 < 0 AND streak < 0 THEN streak - 1 ELSE $5 END,
+ best_trade_cents = GREATEST(best_trade_cents, $6),
+ worst_trade_cents = LEAST(worst_trade_cents, $6)
+ WHERE id = $7
+ `, [returned, wonInc, lostInc, expInc, streakVal, pnl, trade.portfolio_id]);
+
+ // Update daily P&L
+ const tradeDate = new Date(trade.created_at).toISOString().split('T')[0];
+ await kenQ(`
+ INSERT INTO ken_daily_pnl (portfolio_id, date, closed_trades, wins, losses, daily_pnl_cents, cumulative_pnl_cents)
+ VALUES ($1, $2, 1, $3, $4, $5, $5)
+ ON CONFLICT (portfolio_id, date) DO UPDATE SET
+ closed_trades = ken_daily_pnl.closed_trades + 1,
+ wins = ken_daily_pnl.wins + $3,
+ losses = ken_daily_pnl.losses + $4,
+ daily_pnl_cents = ken_daily_pnl.daily_pnl_cents + $5
+ `, [trade.portfolio_id, tradeDate, status === 'won' ? 1 : 0, status === 'lost' ? 1 : 0, pnl]);
+
+ // Update learning table
+ const category = extractSignalCategory(trade.reasoning || '');
+ await kenQ(`
+ INSERT INTO ken_learning (category, signal_type, win_rate, avg_pnl_cents, total_trades, last_updated)
+ VALUES ($1, $2, $3, $4, 1, NOW())
+ ON CONFLICT DO NOTHING
+ `, [category, trade.direction, status === 'won' ? 1 : 0, pnl]);
+ }
+
+ if (openTrades.length > 0) console.log(`[Ken/Portfolio] Resolved ${openTrades.length} trades across portfolios`);
+ } catch (e) {
+ console.error('[Ken/Portfolio] Resolution error:', e.message);
+ }
+}
+
+function extractSignalCategory(reasoning) {
+ const r = reasoning.toLowerCase();
+ if (/heating|gas bill|utility bill|electric bill|energy cost|propane|furnace|hvac/.test(r)) return 'heating_energy';
+ if (/weather|temp|rain|snow|wind|hurricane|polar vortex|cold snap|freeze|frost/.test(r)) return 'weather';
+ if (/crypto|bitcoin|btc|eth/.test(r)) return 'crypto';
+ if (/politic|elect|congress|senate|trump|biden/.test(r)) return 'politics';
+ if (/econom|rate|inflation|fed|gdp|job/.test(r)) return 'economics';
+ if (/momentum|volume|spike|spread/.test(r)) return 'momentum';
+ if (/sport|game|nfl|nba|mlb/.test(r)) return 'sports';
+ if (/lng|natural gas|oil|commodity|corn|wheat|soy|cattle|crop/.test(r)) return 'commodities';
+ return 'general';
+}
+
+// ══════════════════════════════════════════════
+// LNG & AGRICULTURAL COMMODITY INTELLIGENCE
+// ══════════════════════════════════════════════
+const COMMODITY_FEEDS = [
+ // ── LNG & Natural Gas (Government) ──
+ { url: 'https://www.eia.gov/rss/naturalgas_rss.xml', source: 'EIA Natural Gas', category: 'lng' },
+ { url: 'https://www.eia.gov/rss/petroleum_rss.xml', source: 'EIA Petroleum', category: 'oil' },
+ { url: 'https://www.eia.gov/rss/todayinenergy_rss.xml', source: 'EIA Today in Energy', category: 'energy' },
+ { url: 'https://www.eia.gov/rss/electricity_rss.xml', source: 'EIA Electricity', category: 'electricity' },
+ // ── Agriculture (Government) ──
+ { url: 'https://www.usda.gov/rss/home.xml', source: 'USDA', category: 'agriculture' },
+ { url: 'https://www.nass.usda.gov/rss/index.php', source: 'USDA NASS', category: 'agriculture' },
+ // ── NOAA Weather (Government) ──
+ { url: 'https://alerts.weather.gov/cap/us.php?x=0', source: 'NWS National Alerts', category: 'weather' },
+ { url: 'https://www.weather.gov/rss_page.php?site_name=nws', source: 'NWS News', category: 'weather' },
+ { url: 'https://www.cpc.ncep.noaa.gov/products/stratosphere/strat-trop/rss.xml', source: 'NOAA CPC', category: 'weather' },
+ // ── FERC & Energy Regulation (Government) ──
+ { url: 'https://www.ferc.gov/rss/news-releases.xml', source: 'FERC News', category: 'energy_regulation' },
+ // ── Weather Risk ──
+ { url: 'https://rfrx.rfrz.io/weatherrisk', source: 'Weather Risk', category: 'weather_commodity' },
+];
+
+// Government Open APIs for Energy & Weather Data
+const GOV_API_ENDPOINTS = {
+ // EIA Open Data API (no key needed for RSS, key for JSON)
+ eia_ng_spot: 'https://api.eia.gov/v2/natural-gas/pri/fut/data/?frequency=daily&data[0]=value&sort[0][column]=period&sort[0][direction]=desc&length=5&api_key=',
+ eia_elec_price: 'https://api.eia.gov/v2/electricity/retail-sales/data/?frequency=monthly&data[0]=price&sort[0][column]=period&sort[0][direction]=desc&length=10&api_key=',
+ // NOAA Weather API (free, no key)
+ noaa_alerts: 'https://api.weather.gov/alerts/active?status=actual&message_type=alert',
+ noaa_forecast_nyc: 'https://api.weather.gov/gridpoints/OKX/33,37/forecast',
+ noaa_forecast_chi: 'https://api.weather.gov/gridpoints/LOT/75,72/forecast',
+ noaa_forecast_dal: 'https://api.weather.gov/gridpoints/FWD/87,108/forecast',
+ noaa_forecast_den: 'https://api.weather.gov/gridpoints/BOU/62,60/forecast',
+ noaa_forecast_msp: 'https://api.weather.gov/gridpoints/MPX/107,71/forecast',
+ // FRED Economic Data (key needed but some RSS free)
+ fred_natgas: 'https://fred.stlouisfed.org/graph/fredgraph.csv?id=DHHNGSP',
+};
+
+// Fetch NOAA weather alerts for extreme cold/heat events
+async function fetchNOAAWeatherIntel() {
+ let found = 0;
+ try {
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), 10000);
+ const res = await fetch(GOV_API_ENDPOINTS.noaa_alerts, {
+ signal: controller.signal,
+ headers: { 'User-Agent': 'KenInc/1.0 Weather Intelligence', Accept: 'application/geo+json' },
+ });
+ clearTimeout(timeout);
+ if (!res.ok) return found;
+ const data = await res.json();
+
+ const heatingKeywords = /cold|freeze|frost|ice|blizzard|winter storm|wind chill|extreme cold|heating|arctic|polar vortex|below zero|record low|dangerous cold/i;
+ const energyKeywords = /power outage|grid|electricity|utility|energy emergency|rolling blackout|brownout|load shed/i;
+
+ for (const feature of (data.features || []).slice(0, 50)) {
+ const props = feature.properties || {};
+ const headline = props.headline || props.event || '';
+ const desc = props.description || '';
+ const combined = headline + ' ' + desc;
+
+ if (heatingKeywords.test(combined) || energyKeywords.test(combined)) {
+ const areas = (props.areaDesc || '').substring(0, 200);
+ const severity = props.severity || 'Unknown';
+ const certainty = props.certainty || 'Unknown';
+
+ await kenQ(`
+ INSERT INTO ken_sentiment (source, subreddit, keyword, post_title, post_url, score, num_comments, sentiment_score, raw_text)
+ VALUES ('noaa_alert', $1, 'weather_energy', $2, $3, $4, 0, $5, $6)
+ ON CONFLICT DO NOTHING
+ `, [
+ areas,
+ headline.substring(0, 500),
+ props.id || `noaa-${Date.now()}`,
+ severity === 'Extreme' ? 100 : severity === 'Severe' ? 80 : severity === 'Moderate' ? 50 : 20,
+ severity === 'Extreme' ? -0.9 : severity === 'Severe' ? -0.7 : -0.4,
+ `[${severity}/${certainty}] ${areas}: ${desc.substring(0, 400)}`
+ ]);
+ found++;
+ }
+ }
+ } catch (e) {
+ // NOAA API can be slow, don't log every failure
+ }
+
+ // Fetch regional forecasts for major metro areas (heating demand proxy)
+ const metros = [
+ { name: 'NYC', url: GOV_API_ENDPOINTS.noaa_forecast_nyc },
+ { name: 'Chicago', url: GOV_API_ENDPOINTS.noaa_forecast_chi },
+ { name: 'Dallas', url: GOV_API_ENDPOINTS.noaa_forecast_dal },
+ { name: 'Denver', url: GOV_API_ENDPOINTS.noaa_forecast_den },
+ { name: 'Minneapolis', url: GOV_API_ENDPOINTS.noaa_forecast_msp },
+ ];
+
+ for (const metro of metros) {
+ try {
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), 8000);
+ const res = await fetch(metro.url, {
+ signal: controller.signal,
+ headers: { 'User-Agent': 'KenInc/1.0', Accept: 'application/geo+json' },
+ });
+ clearTimeout(timeout);
+ if (!res.ok) continue;
+ const data = await res.json();
+
+ for (const period of (data.properties?.periods || []).slice(0, 4)) {
+ const tempF = period.temperature;
+ const wind = period.windSpeed || '';
+ const forecast = period.detailedForecast || period.shortForecast || '';
+
+ // Flag extreme cold (below 20F) or heat waves (above 100F) — heating demand signals
+ if (tempF <= 20 || tempF >= 100) {
+ await kenQ(`
+ INSERT INTO ken_sentiment (source, subreddit, keyword, post_title, post_url, score, num_comments, sentiment_score, raw_text)
+ VALUES ('noaa_forecast', $1, 'extreme_temp', $2, $3, $4, 0, $5, $6)
+ ON CONFLICT DO NOTHING
+ `, [
+ metro.name,
+ `${metro.name}: ${tempF}°F ${period.name} — ${period.shortForecast}`,
+ `noaa-forecast-${metro.name}-${period.number}-${new Date().toISOString().split('T')[0]}`,
+ Math.abs(tempF <= 20 ? (20 - tempF) * 5 : (tempF - 100) * 5),
+ tempF <= 20 ? -0.8 : -0.6,
+ `${metro.name} ${period.name}: ${tempF}°F, Wind ${wind}. ${forecast.substring(0, 300)}`
+ ]);
+ found++;
+ }
+ }
+ await new Promise(r => setTimeout(r, 500));
+ } catch (e) { /* NOAA timeout */ }
+ }
+
+ if (found > 0) console.log(`[Ken/NOAA] ${found} weather/energy alerts from government APIs`);
+ return found;
+}
+
+// Additional weather-impacted commodity keywords for market scanning
+const COMMODITY_KEYWORDS = [
+ 'natural gas', 'lng', 'henry hub', 'gas price', 'heating degree',
+ 'corn', 'wheat', 'soybeans', 'soybean', 'cotton', 'cattle', 'hogs',
+ 'crop', 'harvest', 'drought', 'frost', 'freeze', 'growing season',
+ 'el nino', 'la nina', 'commodity', 'futures', 'agriculture',
+ 'ethanol', 'fertilizer', 'grain', 'livestock', 'usda', 'crop report',
+];
+
+// ── HEATING BILL & ENERGY COST INTELLIGENCE ──
+const HEATING_KEYWORDS = [
+ 'heating bill', 'gas bill', 'electric bill', 'utility bill', 'energy bill',
+ 'heating cost', 'energy cost', 'propane', 'furnace', 'thermostat',
+ 'polar vortex', 'cold snap', 'wind chill', 'below zero', 'record cold',
+ 'heating oil', 'natural gas price', 'electricity price', 'rate hike',
+ 'winter storm', 'power outage', 'grid strain', 'rolling blackout',
+ 'hvac', 'insulation', 'heat pump', 'space heater', 'energy assistance',
+];
+
+const HEATING_SUBS = [
+ 'personalfinance', 'Frugal', 'povertyfinance', 'homeowners',
+ 'HVAC', 'energy', 'NaturalGas', 'HomeImprovement', 'utilities',
+ 'weather', 'climate', 'TropicalWeather', 'preppers',
+];
+
+async function fetchHeatingBillIntel() {
+ let found = 0;
+ const heatingRegex = new RegExp(HEATING_KEYWORDS.join('|'), 'i');
+
+ for (let i = 0; i < HEATING_SUBS.length; i += 3) {
+ const batch = HEATING_SUBS.slice(i, i + 3);
+ const results = await Promise.allSettled(batch.map(sub => scrapeSubredditHot(sub, 15)));
+ for (let j = 0; j < results.length; j++) {
+ if (results[j].status !== 'fulfilled') continue;
+ const sub = batch[j];
+ for (const post of results[j].value) {
+ const text = (post.title + ' ' + (post.selftext || '')).toLowerCase();
+ if (heatingRegex.test(text) && post.score > 10) {
+ const sentiment = scoreSentiment(post.title);
+ await kenQ(`
+ INSERT INTO ken_sentiment (source, subreddit, keyword, post_title, post_url, score, num_comments, sentiment_score, raw_text)
+ VALUES ('heating_intel', $1, 'heating', $2, $3, $4, $5, $6, $7)
+ ON CONFLICT DO NOTHING
+ `, [sub, post.title, post.url, post.score, post.num_comments, sentiment, text.substring(0, 500)]);
+ found++;
+ }
+ }
+ }
+ await new Promise(r => setTimeout(r, 2000));
+ }
+
+ if (found > 0) console.log(`[Ken/Heating] Found ${found} heating bill/energy cost discussions`);
+ return found;
+}
+
+async function fetchCommodityIntel() {
+ let total = 0;
+ for (const feed of COMMODITY_FEEDS) {
+ try {
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), 8000);
+ const res = await fetch(feed.url, {
+ signal: controller.signal,
+ headers: { 'User-Agent': 'KenInc/1.0 Commodity Intelligence' },
+ });
+ clearTimeout(timeout);
+ if (!res.ok) continue;
+ const text = await res.text();
+
+ // Extract items from RSS
+ const items = text.match(/<item>[\s\S]*?<\/item>/gi) || [];
+ for (const item of items.slice(0, 15)) {
+ const title = (item.match(/<title><!\[CDATA\[(.*?)\]\]>|<title>(.*?)<\/title>/)?.[1] || item.match(/<title>(.*?)<\/title>/)?.[1] || '').trim();
+ const link = (item.match(/<link>(.*?)<\/link>/)?.[1] || '').trim();
+ if (!title) continue;
+
+ // Score commodity relevance
+ const score = scoreEventSentiment(title);
+
+ try {
+ await kenQ(`
+ INSERT INTO ken_sentiment (source, keyword, post_title, post_url, sentiment_score, captured_at)
+ VALUES ($1, $2, $3, $4, $5, NOW())
+ ON CONFLICT DO NOTHING
+ `, [feed.source, feed.category, title.substring(0, 500), link.substring(0, 500), score.sentiment || 0]);
+ total++;
+ } catch(e) {} // skip dupes
+ }
+ } catch(e) {}
+ }
+ if (total > 0) console.log(`[Ken/Commodities] ${total} articles from ${COMMODITY_FEEDS.length} commodity feeds`);
+ return total;
+}
+
+// ══════════════════════════════════════════════
+// PERFORMANCE TRACKER — resolve old predictions
+// ══════════════════════════════════════════════
+async function resolveOldPredictions() {
+ try {
+ // Get pending predictions older than 6 hours
+ const { rows } = await kenQ(`
+ SELECT id, ticker, side, entry_price FROM ken_predictions
+ WHERE outcome = 'pending' AND created_at < NOW() - INTERVAL '6 hours'
+ LIMIT 50
+ `);
+ for (const pred of rows) {
+ // Get latest snapshot for this ticker
+ const { rows: snaps } = await kenQ(`
+ SELECT last_price FROM ken_market_snapshots
+ WHERE ticker = $1 ORDER BY captured_at DESC LIMIT 1
+ `, [pred.ticker]);
+ if (snaps.length > 0) {
+ const currentPrice = snaps[0].last_price;
+ const entryPrice = pred.entry_price || 50;
+ let outcome = 'expired';
+ let pnl = 0;
+ if (pred.side === 'YES') {
+ pnl = currentPrice - entryPrice;
+ outcome = pnl > 0 ? 'win' : pnl < 0 ? 'loss' : 'expired';
+ } else {
+ pnl = entryPrice - currentPrice; // NO side profits when price drops
+ outcome = pnl > 0 ? 'win' : pnl < 0 ? 'loss' : 'expired';
+ }
+ await kenQ(`
+ UPDATE ken_predictions SET outcome = $1, exit_price = $2, pnl_cents = $3, resolved_at = NOW()
+ WHERE id = $4
+ `, [outcome, currentPrice, pnl, pred.id]);
+ }
+ }
+ if (rows.length > 0) console.log(`[Ken] Resolved ${rows.length} old predictions`);
+ } catch (e) {
+ console.error('[Ken] Prediction resolution error:', e.message);
+ }
+}
+
+// ══════════════════════════════════════════════
+// CLEANUP — prune old data (daily)
+// ══════════════════════════════════════════════
+async function cleanupOldData() {
+ try {
+ await kenQ(`DELETE FROM ken_market_snapshots WHERE captured_at < NOW() - INTERVAL '7 days'`);
+ await kenQ(`DELETE FROM ken_sentiment WHERE captured_at < NOW() - INTERVAL '14 days'`);
+ await kenQ(`DELETE FROM ken_performance WHERE scan_time < NOW() - INTERVAL '30 days'`);
+ await kenQ(`DELETE FROM ken_portfolio_snapshots WHERE snapshot_at < NOW() - INTERVAL '60 days'`);
+ console.log('[Ken] Old data cleaned up (including portfolio snapshots 60d retention)');
+ } catch (e) {
+ console.error('[Ken] Cleanup error:', e.message);
+ }
+}
+
+// ── Start Server ──
+server.listen(PORT, '0.0.0.0', () => {
+ console.log(`[Ken] Server running on http://0.0.0.0:${PORT}`);
+ console.log(`[Ken] Kalshi environment: ${KALSHI_ENV.toUpperCase()} (${KALSHI_BASE_URL})`);
+ console.log(`[Ken] Static files: ${DIST}`);
+ console.log(`[Ken] Auth: session cookie + IP whitelist + basic auth`);
+ console.log(`[Ken] ═══════════════════════════════════════`);
+ console.log(`[Ken] AUTONOMOUS MODE: 24/7 MARKET INTELLIGENCE`);
+ console.log(`[Ken] Market scan: every 8 minutes (CPU-boosted, was 15m)`);
+ console.log(`[Ken] Signal pipeline: every 2 minutes (MC simulation + Gemini AI enhanced)`);
+ console.log(`[Ken] Reddit/news: every 15 minutes (doubled, was 30m)`);
+ console.log(`[Ken] CPU cores: ${os.cpus().length} | MC iterations: 15,000 per signal`);
+ console.log(`[Ken] Gemini AI: ${GEMINI_MODEL} (daily budget: ${GEMINI_DAILY_LIMIT} calls)`);
+ console.log(`[Ken] Slack alerts: every 4 hours (high-conf bypass)`);
+ console.log(`[Ken] Data sources: Kalshi | Reddit (80+) | ${NEWS_FEEDS.length} news feeds | HN | GDELT TV | YouTube | Manifold | r/Kalshi | r/Polymarket | Lemmy | Lobsters | Tildes | Bluesky | Mastodon | Metaculus | Polymarket | PredictIt | FRED Economic | NWS Alerts | NOAA Forecasts | EIA Energy | FERC | GovTrack | USDA | Twitter/Nitter | Discord`);
+ console.log(`[Ken] Heating intel: ${HEATING_SUBS.length} subreddits | ${HEATING_KEYWORDS.length} keywords | NOAA 5 metro forecasts | EIA electricity/gas prices`);
+ console.log(`[Ken] ═══════════════════════════════════════`);
+
+ // Separate mutexes: sweep (heavy Reddit/news) and scan (light Kalshi API) can run concurrently
+ let sweepRunning = false;
+ let scanRunning = false;
+
+ async function runSweepSafe(name, fn) {
+ if (sweepRunning) { console.log(`[Ken] Skipping ${name} — another sweep in progress`); return; }
+ sweepRunning = true;
+ try { await fn(); } catch (e) { console.error(`[Ken] ${name} error:`, e.message); }
+ sweepRunning = false;
+ if (global.gc) global.gc();
+ }
+
+ async function runScanSafe(fn) {
+ if (scanRunning) { console.log('[Ken] Skipping Scan — another scan in progress'); return; }
+ scanRunning = true;
+ try { await fn(); } catch (e) { console.error(`[Ken] Scan error:`, e.message); }
+ scanRunning = false;
+ if (global.gc) global.gc();
+ }
+
+ // Load stored Kalshi env preference, trade config, and scan config from DB
+ refreshKalshiEnv().then(() => {
+ console.log(`[Ken] Kalshi environment: ${KALSHI_ENV.toUpperCase()} (${KALSHI_BASE_URL})`);
+ });
+ loadTradeConfig();
+ loadScanConfig();
+
+ // Initial: run reddit sweep and market scan (scan uses separate mutex, can overlap)
+ setTimeout(async () => {
+ runSweepSafe('Reddit init', redditIntelligenceLoop);
+ setTimeout(() => runScanSafe(autonomousScan), 10000);
+ }, 5000);
+
+ // Start all recurring intervals via stored handles (restartIntervals can update later)
+ scanIntervalId = setInterval(() => runScanSafe(autonomousScan), SCAN_INTERVAL_MS);
+ redditIntervalId = setInterval(() => runSweepSafe('Reddit', redditIntelligenceLoop), REDDIT_INTERVAL_MS);
+ signalIntervalId = setInterval(async () => {
+ if (cachedActiveMarkets.length > 0) {
+ try { await signalPipeline(cachedActiveMarkets); } catch (e) { console.log(`[Ken] Fast pipeline error: ${e.message}`); }
+ }
+ }, SIGNAL_PIPELINE_MS);
+
+ // Resolve old predictions every hour
+ setInterval(() => {
+ resolveOldPredictions().catch(e => console.error('[Ken] Resolution error:', e.message));
+ }, 60 * 60 * 1000);
+
+ // HYPER-TRADE: Resolve portfolio trades (interval stored in handle for UI control)
+ resolveIntervalId = setInterval(() => {
+ resolvePortfolioTrades().catch(e => console.error('[Ken] Portfolio resolution error:', e.message));
+ }, RESOLVE_INTERVAL_MS);
+ setTimeout(() => resolvePortfolioTrades().catch(() => {}), 30000);
+
+ // Portfolio NAV snapshots every 30 minutes for charting
+ setInterval(() => capturePortfolioSnapshots().catch(e => console.error('[Ken/Charts] Error:', e.message)), 30 * 60 * 1000);
+ setTimeout(() => capturePortfolioSnapshots().catch(() => {}), 25000); // Initial after startup
+
+ // Commodity + heating bill + NOAA intelligence every 20 minutes
+ setInterval(() => {
+ fetchCommodityIntel().catch(e => console.error('[Ken] Commodity error:', e.message));
+ fetchHeatingBillIntel().catch(e => console.error('[Ken] Heating intel error:', e.message));
+ fetchNOAAWeatherIntel().catch(e => console.error('[Ken] NOAA intel error:', e.message));
+ }, 20 * 60 * 1000);
+ // Initial commodity + heating + NOAA fetch
+ setTimeout(() => {
+ fetchCommodityIntel().catch(() => {});
+ fetchHeatingBillIntel().catch(() => {});
+ fetchNOAAWeatherIntel().catch(() => {});
+ }, 15000);
+
+ // Weekly portfolio auto-refill: $100/portfolio every Monday (4-week trial)
+ // Checks every hour, only refills on Mondays between 0:00-0:59 UTC
+ const WEEKLY_REFILL_CENTS = 10000; // $100
+ const REFILL_WEEKS_REMAINING_KEY = 'ken_refill_weeks';
+ setInterval(async () => {
+ try {
+ const now = new Date();
+ if (now.getUTCDay() !== 1 || now.getUTCHours() !== 0) return; // Monday 0:00 UTC only
+ // Check if we already refilled this week
+ const { rows: [config] } = await kenQ(
+ `SELECT value FROM ken_config WHERE key = 'last_refill_date'`
+ ).catch(() => ({ rows: [] }));
+ const today = now.toISOString().split('T')[0];
+ if (config && config.value === today) return; // Already refilled today
+ // Check weeks remaining
+ const { rows: [weeksRow] } = await kenQ(
+ `SELECT value FROM ken_config WHERE key = $1`, [REFILL_WEEKS_REMAINING_KEY]
+ ).catch(() => ({ rows: [] }));
+ const weeksLeft = weeksRow ? parseInt(weeksRow.value) : 4;
+ if (weeksLeft <= 0) { console.log('[Ken] Weekly refill: 0 weeks remaining, skipping'); return; }
+ // Refill all portfolios
+ const { rowCount } = await kenQ(
+ `UPDATE ken_portfolios SET balance_cents = balance_cents + $1`, [WEEKLY_REFILL_CENTS]
+ );
+ // Update tracking (value column is jsonb, so wrap in JSON.stringify)
+ await kenQ(`INSERT INTO ken_config (key, value) VALUES ('last_refill_date', $1::jsonb)
+ ON CONFLICT (key) DO UPDATE SET value = $1::jsonb, updated_at = NOW()`, [JSON.stringify(today)]);
+ await kenQ(`INSERT INTO ken_config (key, value) VALUES ($1, $2::jsonb)
+ ON CONFLICT (key) DO UPDATE SET value = $2::jsonb, updated_at = NOW()`, [REFILL_WEEKS_REMAINING_KEY, JSON.stringify(String(weeksLeft - 1))]);
+ console.log(`[Ken] Weekly refill: +$${WEEKLY_REFILL_CENTS/100} to ${rowCount} portfolios. ${weeksLeft - 1} weeks remaining.`);
+ } catch (e) { console.error('[Ken] Weekly refill error:', e.message); }
+ }, 60 * 60 * 1000); // Check every hour
+
+ // Cleanup old data every 24 hours
+ setInterval(() => {
+ cleanupOldData().catch(e => console.error('[Ken] Cleanup error:', e.message));
+ }, 24 * 60 * 60 * 1000);
+});
diff --git a/kalshi-dash/server.js.pre-scrub-2026-05-07.bak b/kalshi-dash/server.js.pre-scrub-2026-05-07.bak
new file mode 100644
index 0000000..f516b41
--- /dev/null
+++ b/kalshi-dash/server.js.pre-scrub-2026-05-07.bak
@@ -0,0 +1,9138 @@
+import http from 'http';
+import fs from 'fs';
+import path from 'path';
+import { fileURLToPath } from 'url';
+import pg from 'pg';
+import crypto from 'crypto';
+import { OAuth2Client } from 'google-auth-library';
+import { Worker, isMainThread, parentPort, workerData } from 'worker_threads';
+import os from 'os';
+
+const __filename = fileURLToPath(import.meta.url);
+const __dirname = path.dirname(__filename);
+
+const PORT = 7810;
+const DIST = path.join(__dirname, 'dist');
+
+// ── Unified DW Auth Config ──
+// Audit 2026-05-04: fail-closed on missing env. Old literal `DWSecure2024!`
+// is now in source-control history and must be rotated.
+const AUTH_USER = process.env.AUTH_USERNAME || 'admin';
+const AUTH_PASS = process.env.AUTH_PASSWORD;
+if (!AUTH_PASS) {
+ throw new Error('AUTH_PASSWORD env var required (no fallback for production safety)');
+}
+const SESSION_COOKIE = 'kalshi_session';
+const SESSION_MAX_AGE = 30 * 24 * 60 * 60; // 30 days in seconds
+const WHITELISTED_IPS = ['127.0.0.1', '::1', '45.61.58.125', 'localhost'];
+
+// ── Slack Alerts ──
+const SLACK_WEBHOOK = 'https://hooks.slack.com/services/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';
+
+async function sendSlack(text) {
+ // Slack notifications disabled per Steve
+ return;
+}
+
+// ── Google OAuth Config ──
+const GOOGLE_CLIENT_ID = process.env.GOOGLE_CLIENT_ID || '';
+const ALLOWED_EMAILS = (process.env.ALLOWED_EMAILS || '').split(',').filter(Boolean);
+const googleClient = GOOGLE_CLIENT_ID ? new OAuth2Client(GOOGLE_CLIENT_ID) : null;
+
+// ── NWS Weather Config ──
+const NWS_BASE = 'https://api.weather.gov';
+const NWS_USER_AGENT = 'Ken-Bot/1.0 (steve@designerwallcoverings.com)';
+
+const CITY_COORDS = {
+ 'New York': { lat: 40.7128, lon: -74.0060 },
+ 'Los Angeles': { lat: 34.0522, lon: -118.2437 },
+ 'Chicago': { lat: 41.8781, lon: -87.6298 },
+ 'Houston': { lat: 29.7604, lon: -95.3698 },
+ 'Phoenix': { lat: 33.4484, lon: -112.0740 },
+ 'Philadelphia': { lat: 39.9526, lon: -75.1652 },
+ 'Dallas': { lat: 32.7767, lon: -96.7970 },
+ 'San Francisco': { lat: 37.7749, lon: -122.4194 },
+ 'Seattle': { lat: 47.6062, lon: -122.3321 },
+ 'Denver': { lat: 39.7392, lon: -104.9903 },
+ 'Boston': { lat: 42.3601, lon: -71.0589 },
+ 'Miami': { lat: 25.7617, lon: -80.1918 },
+ 'Atlanta': { lat: 33.7490, lon: -84.3880 },
+ 'Minneapolis': { lat: 44.9778, lon: -93.2650 },
+ 'Washington': { lat: 38.9072, lon: -77.0369 },
+ 'Las Vegas': { lat: 36.1699, lon: -115.1398 },
+};
+
+async function nwsFetch(url) {
+ const controller = new AbortController();
+ // Hard Promise.race timeout — AbortController alone can't kill DNS-level hangs
+ const hardTimeout = new Promise((_, reject) =>
+ setTimeout(() => { controller.abort(); reject(new Error('NWS timeout (5s)')); }, 5000)
+ );
+ const doFetch = async () => {
+ const res = await fetch(url, {
+ headers: { 'User-Agent': NWS_USER_AGENT, 'Accept': 'application/geo+json' },
+ signal: controller.signal,
+ });
+ if (!res.ok) throw new Error(`NWS ${res.status}: ${res.statusText}`);
+ return res.json();
+ };
+ return Promise.race([doFetch(), hardTimeout]);
+}
+
+function extractForecastFeatures(forecastData, variable) {
+ const periods = forecastData?.properties?.periods || [];
+ if (!periods.length) return null;
+ const features = { variable, values: [], timestamps: [] };
+ for (const p of periods) {
+ let value = null;
+ if (variable === 'temperature') { value = p.temperature; features.unit = p.temperatureUnit; }
+ else if (variable === 'wind') { const m = p.windSpeed?.match(/(\d+)/); if (m) value = parseInt(m[1]); features.unit = 'mph'; }
+ else if (variable === 'precipitation') { value = p.probabilityOfPrecipitation?.value ?? 0; features.unit = 'percent'; }
+ if (value !== null) { features.values.push(value); features.timestamps.push(p.startTime); }
+ }
+ if (features.values.length) {
+ features.mean = features.values.reduce((a, b) => a + b, 0) / features.values.length;
+ features.min = Math.min(...features.values);
+ features.max = Math.max(...features.values);
+ features.latest = features.values[0];
+ }
+ return features;
+}
+
+// ── Prediction Model ──
+function ensembleExceedance(features, threshold, operator = '>=') {
+ const vals = features?.values || [];
+ if (!vals.length) return null;
+ let ct = 0;
+ for (const v of vals) {
+ if (operator === '>=' && v >= threshold) ct++;
+ else if (operator === '<=' && v <= threshold) ct++;
+ else if (operator === '>' && v > threshold) ct++;
+ else if (operator === '<' && v < threshold) ct++;
+ }
+ return ct / vals.length;
+}
+
+function climatologicalPrior(variable, threshold, month) {
+ const season = month >= 6 && month <= 8 ? 'summer' : month >= 12 || month <= 2 ? 'winter' : month >= 3 && month <= 5 ? 'spring' : 'fall';
+ const priors = {
+ temperature: { summer: t => t > 100 ? 0.05 : t > 90 ? 0.35 : t > 80 ? 0.65 : 0.85, winter: t => t > 60 ? 0.15 : t > 40 ? 0.50 : t > 20 ? 0.75 : 0.90, spring: t => t > 80 ? 0.20 : t > 60 ? 0.55 : t > 40 ? 0.80 : 0.95, fall: t => t > 80 ? 0.25 : t > 60 ? 0.50 : t > 40 ? 0.75 : 0.90 },
+ precipitation: { any: t => t > 2 ? 0.10 : t > 1 ? 0.20 : t > 0.5 ? 0.35 : 0.50 },
+ snow: { winter: t => t > 12 ? 0.05 : t > 6 ? 0.15 : t > 3 ? 0.25 : 0.40, any: () => 0.10 },
+ };
+ const vp = priors[variable]; if (!vp) return 0.50;
+ const fn = vp[season] || vp.any; if (!fn) return 0.50;
+ return fn(threshold);
+}
+
+function bayesianUpdate(prior, forecastProb, weight = 0.7) {
+ return prior * (1 - weight) + forecastProb * weight;
+}
+
+// ══════════════════════════════════════════════════════
+// GEMINI AI PREDICTION ENGINE — uses CPU + AI for better signals
+// ══════════════════════════════════════════════════════
+const GEMINI_API_KEY = 'AIzaSyAO0rLKwtJUKcf3zVmKstBS4udct4QejMo';
+const GEMINI_MODEL = 'gemini-2.0-flash';
+
+async function geminiAnalyze(prompt, maxTokens = 1024) {
+ try {
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), 25000);
+ const res = await fetch(
+ `https://generativelanguage.googleapis.com/v1beta/models/${GEMINI_MODEL}:generateContent?key=${GEMINI_API_KEY}`,
+ {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ signal: controller.signal,
+ body: JSON.stringify({
+ contents: [{ parts: [{ text: prompt }] }],
+ generationConfig: { temperature: 0.3, maxOutputTokens: maxTokens },
+ }),
+ }
+ );
+ clearTimeout(timeout);
+ if (!res.ok) return null;
+ const data = await res.json();
+ return data?.candidates?.[0]?.content?.parts?.[0]?.text || null;
+ } catch (e) {
+ console.log(`[Ken/Gemini] Error: ${e.message}`);
+ return null;
+ }
+}
+
+// AI-Enhanced Signal Scoring — Gemini analyzes top signals for smarter predictions
+let geminiCallCount = 0;
+const GEMINI_DAILY_LIMIT = 200; // budget: ~200 calls/day
+const geminiCallReset = setInterval(() => { geminiCallCount = 0; }, 24 * 60 * 60 * 1000);
+
+async function aiEnhanceSignal(signal, articles, market) {
+ if (geminiCallCount >= GEMINI_DAILY_LIMIT) return signal;
+ geminiCallCount++;
+
+ const articleSummary = articles.slice(0, 8).map((a, i) =>
+ `${i + 1}. [${a.source}] ${a.headline?.substring(0, 150)}`
+ ).join('\n');
+
+ const prompt = `You are Ken, an expert prediction market analyst. Analyze this trading signal and provide a calibrated probability estimate.
+
+MARKET: "${market.title}" ${market.subtitle ? '- ' + market.subtitle : ''}
+CURRENT PRICE: YES at ${market.yes_ask}¢, NO at ${100 - market.yes_ask}¢
+24H VOLUME: ${market.volume_24h?.toLocaleString() || '?'}
+OUR SIGNAL: ${signal.direction} with ${(Math.abs(signal.expectedEdge) * 100).toFixed(1)}% edge
+
+RECENT NEWS (${articles.length} articles):
+${articleSummary}
+
+SENTIMENT ANALYSIS: category=${articles[0]?.category || '?'}, direction=${articles[0]?.direction || '?'}, agreement=${((signal.agreement || 0) * 100).toFixed(0)}%
+
+Respond with ONLY a JSON object (no markdown):
+{"probability": 0.XX, "confidence": 0.XX, "reasoning": "one sentence", "adjustedEdge": X.XX, "riskFlag": "none|caution|high_risk"}`;
+
+ const response = await geminiAnalyze(prompt, 256);
+ if (!response) return signal;
+
+ try {
+ // Parse JSON from response (handle markdown wrapping)
+ const jsonStr = response.replace(/```json\n?/g, '').replace(/```\n?/g, '').trim();
+ const ai = JSON.parse(jsonStr);
+
+ // Blend AI probability with our statistical model
+ const blendedEdge = signal.expectedEdge * 0.6 + (ai.adjustedEdge || signal.expectedEdge) * 0.4;
+ const blendedConf = signal.confidence * 0.5 + (ai.confidence || signal.confidence) * 0.5;
+
+ return {
+ ...signal,
+ expectedEdge: blendedEdge,
+ confidence: Math.min(0.95, blendedConf),
+ aiProbability: ai.probability,
+ aiReasoning: ai.reasoning,
+ aiRiskFlag: ai.riskFlag || 'none',
+ aiEnhanced: true,
+ };
+ } catch (e) {
+ console.log(`[Ken/Gemini] Parse error: ${e.message}`);
+ return signal;
+ }
+}
+
+// ══════════════════════════════════════════════════════
+// MONTE CARLO SIMULATION — CPU-intensive probability estimation
+// ══════════════════════════════════════════════════════
+function monteCarloSimulation(params, iterations = 10000) {
+ const { priorProb, sentimentImpact, momentum2h, momentum6h, volume24h, spread, articleCount, agreement } = params;
+
+ let successCount = 0;
+ const edgeDistribution = [];
+
+ for (let i = 0; i < iterations; i++) {
+ // Add noise to each factor (simulating uncertainty)
+ const sentimentNoise = sentimentImpact + (Math.random() - 0.5) * 0.15;
+ const momentumNoise = (momentum2h || 0) / 100 + (Math.random() - 0.5) * 0.08;
+ const volumeSignal = Math.min(1, (volume24h || 0) / 10000) * (Math.random() * 0.1);
+ const spreadPenalty = Math.max(0, (spread || 0) - 3) * -0.005 * Math.random();
+ const articleBoost = Math.min(0.1, (articleCount || 0) * 0.01) * Math.random();
+ const agreementBoost = ((agreement || 0.5) - 0.5) * 0.15 * Math.random();
+
+ // Simulate probability with all factors
+ const simProb = Math.max(0.01, Math.min(0.99,
+ priorProb + sentimentNoise + momentumNoise + volumeSignal + spreadPenalty + articleBoost + agreementBoost
+ ));
+
+ // Compare to market price — is there an edge?
+ const marketProb = priorProb;
+ const simEdge = simProb - marketProb;
+
+ if (Math.abs(simEdge) >= 0.05) successCount++;
+ edgeDistribution.push(simEdge);
+ }
+
+ // Calculate statistics from simulation
+ edgeDistribution.sort((a, b) => a - b);
+ const mean = edgeDistribution.reduce((a, b) => a + b, 0) / iterations;
+ const p5 = edgeDistribution[Math.floor(iterations * 0.05)];
+ const p25 = edgeDistribution[Math.floor(iterations * 0.25)];
+ const p50 = edgeDistribution[Math.floor(iterations * 0.50)];
+ const p75 = edgeDistribution[Math.floor(iterations * 0.75)];
+ const p95 = edgeDistribution[Math.floor(iterations * 0.95)];
+ const stdDev = Math.sqrt(edgeDistribution.reduce((sum, e) => sum + Math.pow(e - mean, 2), 0) / iterations);
+
+ return {
+ meanEdge: mean,
+ medianEdge: p50,
+ stdDev,
+ confidence: successCount / iterations,
+ percentiles: { p5, p25, p50, p75, p95 },
+ iterations,
+ edgeConsistent: Math.sign(p25) === Math.sign(p75), // Is edge direction consistent?
+ };
+}
+
+// ══════════════════════════════════════════════════════
+// PARALLEL PROCESSING — run CPU-heavy tasks across cores
+// ══════════════════════════════════════════════════════
+const CPU_CORES = Math.max(2, os.cpus().length);
+const WORKER_POOL_SIZE = Math.min(12, CPU_CORES - 2); // Use up to 14 cores, leave 2 for OS + other services
+
+function runInParallel(tasks, workerFn) {
+ return Promise.all(tasks.map(task => {
+ return new Promise(resolve => {
+ try {
+ resolve(workerFn(task));
+ } catch (e) {
+ resolve({ error: e.message, task });
+ }
+ });
+ }));
+}
+
+// Batch process markets in parallel chunks
+async function parallelMarketAnalysis(markets, analysisFunc, batchSize = 50) {
+ const results = [];
+ const batches = [];
+ for (let i = 0; i < markets.length; i += batchSize) {
+ batches.push(markets.slice(i, i + batchSize));
+ }
+
+ // Process batches concurrently (up to WORKER_POOL_SIZE at once)
+ for (let i = 0; i < batches.length; i += WORKER_POOL_SIZE) {
+ const concurrent = batches.slice(i, i + WORKER_POOL_SIZE);
+ const batchResults = await Promise.all(concurrent.map(batch =>
+ Promise.all(batch.map(m => analysisFunc(m).catch(e => ({ error: e.message, ticker: m.ticker }))))
+ ));
+ results.push(...batchResults.flat());
+ }
+ return results;
+}
+
+// Parse Kalshi weather market title into event spec
+function parseWeatherEvent(title) {
+ const t = (title || '').toLowerCase();
+ let variable = 'unknown', threshold = 80, operator = '>=';
+ const tempMatch = t.match(/(\d+)\s*°?\s*f/);
+ // Detect temperature events
+ if (t.includes('temperature') || t.includes('temp') || t.includes('°f') || t.includes('degrees') || t.includes('high') || t.includes('low') || t.includes('cold') || t.includes('hot') || t.includes('warm') || t.includes('heat')) {
+ variable = 'temperature';
+ if (tempMatch) threshold = parseInt(tempMatch[1]);
+ }
+ if (t.includes('rain') || t.includes('precipitation') || t.includes('inch')) { variable = 'precipitation'; threshold = tempMatch ? parseInt(tempMatch[1]) : 0.1; }
+ if (t.includes('snow')) { variable = 'snow'; threshold = tempMatch ? parseInt(tempMatch[1]) : 1; }
+ if (t.includes('wind') || t.includes('gust')) { variable = 'wind'; threshold = tempMatch ? parseInt(tempMatch[1]) : 40; }
+ if (t.includes('below') || t.includes('under') || t.includes('less')) operator = '<=';
+ if (t.includes('above') || t.includes('over') || t.includes('exceed') || t.includes('at least')) operator = '>=';
+ return { variable, threshold, operator };
+}
+
+// Extract city from market title
+function extractCity(title) {
+ for (const city of Object.keys(CITY_COORDS)) {
+ if (title.toLowerCase().includes(city.toLowerCase())) return city;
+ }
+ return null;
+}
+
+// ── Kalshi API Config ──
+let KALSHI_ENV = (process.env.KALSHI_ENV || 'demo').toLowerCase();
+const KALSHI_BASE_URLS = {
+ demo: 'https://demo-api.kalshi.co/trade-api/v2',
+ prod: 'https://api.elections.kalshi.com/trade-api/v2',
+};
+let KALSHI_BASE_URL = KALSHI_BASE_URLS[KALSHI_ENV] || KALSHI_BASE_URLS.demo;
+
+// Refresh env from DB config (called on startup and mode changes)
+async function refreshKalshiEnv() {
+ try {
+ const result = await pool.query('SELECT config FROM risk_state ORDER BY updated_at DESC LIMIT 1');
+ const cfg = result.rows[0]?.config || {};
+ if (cfg.kalshi_env && KALSHI_BASE_URLS[cfg.kalshi_env]) {
+ KALSHI_ENV = cfg.kalshi_env;
+ KALSHI_BASE_URL = KALSHI_BASE_URLS[KALSHI_ENV];
+ }
+ } catch {}
+}
+
+// ── Database ──
+const pool = new pg.Pool({
+ connectionString: 'postgresql://dw_admin:DW2024SecurePass@127.0.0.1:5432/bertha_betting',
+ max: 10,
+ idleTimeoutMillis: 30000,
+});
+
+const MIME = {
+ '.html': 'text/html', '.js': 'application/javascript', '.css': 'text/css',
+ '.json': 'application/json', '.png': 'image/png', '.svg': 'image/svg+xml',
+ '.ico': 'image/x-icon', '.woff2': 'font/woff2', '.woff': 'font/woff',
+ '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif',
+ '.webp': 'image/webp', '.map': 'application/json', '.txt': 'text/plain',
+};
+
+// ── DB Helper ──
+async function q(text, params) {
+ return pool.query(text, params);
+}
+
+// ── Response Helper ──
+function json(res, data, status = 200, extraHeaders = {}) {
+ res.writeHead(status, {
+ 'Content-Type': 'application/json',
+ 'Access-Control-Allow-Origin': '*',
+ 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
+ 'Access-Control-Allow-Headers': 'Content-Type, Authorization',
+ ...extraHeaders,
+ });
+ res.end(JSON.stringify(data));
+}
+
+// ── Body Parser ──
+async function readBody(req) {
+ return new Promise(resolve => {
+ let d = '';
+ req.on('data', c => d += c);
+ req.on('end', () => { try { resolve(JSON.parse(d)); } catch { resolve({}); } });
+ });
+}
+
+// ── Cookie / Session Helpers ──
+function parseCookies(req) {
+ const obj = {};
+ (req.headers.cookie || '').split(';').forEach(c => {
+ const [k, ...v] = c.trim().split('=');
+ if (k) obj[k] = v.join('=');
+ });
+ return obj;
+}
+
+function getSession(req) {
+ const cookies = parseCookies(req);
+ const token = cookies[SESSION_COOKIE];
+ if (!token) return null;
+ try {
+ const data = JSON.parse(Buffer.from(decodeURIComponent(token), 'base64').toString());
+ if (!data.authenticated) return null;
+ const age = Date.now() - data.loginTime;
+ if (age > SESSION_MAX_AGE * 1000) return null;
+ return data;
+ } catch { return null; }
+}
+
+function getClientIP(req) {
+ return req.headers['x-forwarded-for']?.split(',')[0]?.trim() || req.socket.remoteAddress || '';
+}
+
+function isWhitelistedIP(req) {
+ const ip = getClientIP(req);
+ return WHITELISTED_IPS.some(w => ip.includes(w));
+}
+
+function hasBasicAuth(req) {
+ const auth = req.headers.authorization;
+ if (!auth || !auth.startsWith('Basic ')) return false;
+ const [user, pass] = Buffer.from(auth.split(' ')[1], 'base64').toString().split(':');
+ return user === AUTH_USER && pass === AUTH_PASS;
+}
+
+function isAuthenticated(req) {
+ if (isWhitelistedIP(req)) return true;
+ if (hasBasicAuth(req)) return true;
+ if (getSession(req)) return true;
+ return false;
+}
+
+function setSessionCookie(res, sessionToken) {
+ return `${SESSION_COOKIE}=${encodeURIComponent(sessionToken)}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${SESSION_MAX_AGE}`;
+}
+
+function clearSessionCookie() {
+ return `${SESSION_COOKIE}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0`;
+}
+
+// ── Kalshi API Signing ──
+// RSA-PSS with SHA-256, salt length 32
+// Signs: timestamp_ms_string + method_uppercase + path
+function signKalshiRequest(privateKeyPem, timestampMs, method, requestPath) {
+ const message = timestampMs + method.toUpperCase() + requestPath;
+ const signature = crypto.sign('sha256', Buffer.from(message), {
+ key: privateKeyPem,
+ padding: crypto.constants.RSA_PKCS1_PSS_PADDING,
+ saltLength: 32,
+ });
+ return signature.toString('base64');
+}
+
+// ── Kalshi Authenticated Fetch ──
+async function kalshiFetch(method, apiPath, body = null) {
+ // Load keys from DB
+ const result = await q('SELECT config FROM risk_state ORDER BY updated_at DESC LIMIT 1');
+ const cfg = result.rows[0]?.config || {};
+
+ const apiKey = cfg.kalshi_api_key;
+ const privateKeyPem = cfg.kalshi_private_key;
+
+ if (!apiKey || !privateKeyPem) {
+ throw new Error('Kalshi API keys not configured. Please save your API key and private key first.');
+ }
+
+ const timestampMs = Date.now().toString();
+ // The path for signing is everything after the base domain, starting with /trade-api/v2
+ const basePath = KALSHI_ENV === 'prod' ? '/trade-api/v2' : '/trade-api/v2';
+ const fullSignPath = basePath + apiPath;
+ const signature = signKalshiRequest(privateKeyPem, timestampMs, method, fullSignPath);
+
+ const url = KALSHI_BASE_URL + apiPath;
+ const headers = {
+ 'KALSHI-ACCESS-KEY': apiKey,
+ 'KALSHI-ACCESS-TIMESTAMP': timestampMs,
+ 'KALSHI-ACCESS-SIGNATURE': signature,
+ 'Content-Type': 'application/json',
+ 'Accept': 'application/json',
+ };
+
+ const fetchOpts = { method, headers };
+ if (body && method !== 'GET' && method !== 'DELETE') {
+ fetchOpts.body = JSON.stringify(body);
+ }
+
+ const response = await fetch(url, fetchOpts);
+ const text = await response.text();
+
+ let data;
+ try {
+ data = JSON.parse(text);
+ } catch {
+ data = { raw: text };
+ }
+
+ if (!response.ok) {
+ const errMsg = data?.message || data?.error || data?.raw || `HTTP ${response.status}`;
+ throw new Error(`Kalshi API error (${response.status}): ${errMsg}`);
+ }
+
+ return data;
+}
+
+// ── Kalshi Unauthenticated Fetch (for public endpoints) ──
+async function kalshiPublicFetch(method, apiPath) {
+ const url = KALSHI_BASE_URL + apiPath;
+ const response = await fetch(url, {
+ method,
+ headers: { 'Accept': 'application/json' },
+ });
+ const text = await response.text();
+
+ let data;
+ try {
+ data = JSON.parse(text);
+ } catch {
+ data = { raw: text };
+ }
+
+ if (!response.ok) {
+ const errMsg = data?.message || data?.error || data?.raw || `HTTP ${response.status}`;
+ throw new Error(`Kalshi API error (${response.status}): ${errMsg}`);
+ }
+
+ return data;
+}
+
+// ── Build query string from params object ──
+function buildQueryString(params) {
+ if (!params || Object.keys(params).length === 0) return '';
+ const qs = Object.entries(params)
+ .filter(([, v]) => v !== undefined && v !== null && v !== '')
+ .map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)
+ .join('&');
+ return qs ? `?${qs}` : '';
+}
+
+// ── API Route Handlers ──
+const routes = {
+
+ // ════════════════════════════════════════
+ // AUTH ENDPOINTS (same DW pattern)
+ // ════════════════════════════════════════
+
+ 'POST /api/auth/login': async (req, res) => {
+ const body = await readBody(req);
+ if (body.username === AUTH_USER && body.password === AUTH_PASS) {
+ const sessionData = { authenticated: true, username: AUTH_USER, loginTime: Date.now() };
+ const token = Buffer.from(JSON.stringify(sessionData)).toString('base64');
+ json(res, { success: true, message: 'Login successful', username: AUTH_USER }, 200, {
+ 'Set-Cookie': setSessionCookie(res, token),
+ });
+ } else {
+ json(res, { error: 'Invalid credentials' }, 401);
+ }
+ },
+
+ 'POST /api/auth/logout': async (req, res) => {
+ json(res, { success: true, message: 'Logged out successfully' }, 200, {
+ 'Set-Cookie': clearSessionCookie(),
+ });
+ },
+
+ 'GET /api/auth/session': async (req, res) => {
+ if (isWhitelistedIP(req)) {
+ return json(res, { authenticated: true, username: AUTH_USER, bypassReason: 'whitelisted_ip' });
+ }
+ if (hasBasicAuth(req)) {
+ return json(res, { authenticated: true, username: AUTH_USER, bypassReason: 'basic_auth' });
+ }
+ const session = getSession(req);
+ if (session) {
+ return json(res, {
+ authenticated: true,
+ username: session.username,
+ email: session.email,
+ picture: session.picture,
+ provider: session.provider,
+ loginTime: session.loginTime,
+ });
+ }
+ json(res, { authenticated: false }, 401);
+ },
+
+ 'POST /api/auth/google': async (req, res) => {
+ if (!googleClient) return json(res, { error: 'Google OAuth not configured' }, 400);
+ const body = await readBody(req);
+ if (!body.credential) return json(res, { error: 'Missing credential' }, 400);
+ try {
+ const ticket = await googleClient.verifyIdToken({ idToken: body.credential, audience: GOOGLE_CLIENT_ID });
+ const payload = ticket.getPayload();
+ const email = payload.email;
+ if (!payload.email_verified) return json(res, { error: 'Email not verified' }, 401);
+ if (ALLOWED_EMAILS.length > 0 && !ALLOWED_EMAILS.includes(email)) {
+ return json(res, { error: 'Email not authorized' }, 403);
+ }
+ const sessionData = {
+ authenticated: true,
+ username: payload.name || email,
+ email,
+ picture: payload.picture,
+ provider: 'google',
+ loginTime: Date.now(),
+ };
+ const token = Buffer.from(JSON.stringify(sessionData)).toString('base64');
+ json(res, { success: true, username: payload.name || email, email, picture: payload.picture }, 200, {
+ 'Set-Cookie': setSessionCookie(res, token),
+ });
+ } catch (err) {
+ json(res, { error: 'Invalid Google token', details: err.message }, 401);
+ }
+ },
+
+ 'GET /api/auth/google-config': async (req, res) => {
+ json(res, { client_id: GOOGLE_CLIENT_ID || null, configured: !!GOOGLE_CLIENT_ID });
+ },
+
+ // ════════════════════════════════════════
+ // SETUP WIZARD (save/load progress)
+ // ════════════════════════════════════════
+
+ 'GET /api/setup': async (req, res) => {
+ try {
+ const result = await q('SELECT config FROM risk_state ORDER BY updated_at DESC LIMIT 1');
+ const cfg = result.rows[0]?.config || {};
+ json(res, {
+ setup_complete: !!cfg.setup_complete,
+ setup_progress: cfg.setup_progress || null,
+ });
+ } catch (err) {
+ json(res, { error: err.message }, 500);
+ }
+ },
+
+ 'POST /api/setup': async (req, res) => {
+ const body = await readBody(req);
+ try {
+ const current = await q('SELECT * FROM risk_state ORDER BY updated_at DESC LIMIT 1');
+ const row = current.rows[0] || {};
+ const cfg = row.config || {};
+
+ if (body.action === 'save_progress') {
+ const newConfig = { ...cfg, setup_progress: body.progress };
+ await q('UPDATE risk_state SET config = $1, updated_at = NOW() WHERE id = $2', [JSON.stringify(newConfig), row.id]);
+ json(res, { success: true });
+ } else if (body.action === 'complete') {
+ const newConfig = { ...cfg, setup_complete: true, setup_progress: body.progress };
+ await q('UPDATE risk_state SET config = $1, updated_at = NOW() WHERE id = $2', [JSON.stringify(newConfig), row.id]);
+ json(res, { success: true, message: 'Setup complete!' });
+ } else {
+ json(res, { error: `Unknown setup action: ${body.action}` }, 400);
+ }
+ } catch (err) {
+ json(res, { error: err.message }, 500);
+ }
+ },
+
+ // ════════════════════════════════════════
+ // HEALTH
+ // ════════════════════════════════════════
+
+ 'GET /api/health': async (req, res) => {
+ try {
+ const dbCheck = await q('SELECT 1');
+ const risk = await q('SELECT * FROM risk_state ORDER BY updated_at DESC LIMIT 1');
+ const cfg = risk.rows[0]?.config || {};
+
+ // Test Kalshi connection
+ let kalshiConnected = false;
+ let balance = null;
+ if (cfg.kalshi_api_key && cfg.kalshi_private_key) {
+ try {
+ const balData = await kalshiFetch('GET', '/portfolio/balance');
+ kalshiConnected = true;
+ balance = balData.balance ?? balData;
+ } catch {
+ // Keys exist but connection failed
+ kalshiConnected = false;
+ }
+ }
+
+ json(res, {
+ status: 'ok',
+ db_connected: !!dbCheck,
+ kalshi_connected: kalshiConnected,
+ env: KALSHI_ENV,
+ safe_mode: cfg.safe_mode ?? true,
+ balance,
+ });
+ } catch (err) {
+ json(res, { status: 'error', error: err.message }, 500);
+ }
+ },
+
+ // ════════════════════════════════════════
+ // KALSHI PROXY (all actions via POST)
+ // ════════════════════════════════════════
+
+ 'POST /api/kalshi': async (req, res) => {
+ const body = await readBody(req);
+ const { action } = body;
+
+ if (!action) {
+ return json(res, { error: 'Missing action field' }, 400);
+ }
+
+ try {
+ switch (action) {
+
+ // ── Save API Keys ──
+ case 'save_keys': {
+ if (!body.api_key || !body.private_key) {
+ return json(res, { error: 'api_key and private_key (PEM) required' }, 400);
+ }
+ const current = await q('SELECT * FROM risk_state ORDER BY updated_at DESC LIMIT 1');
+ const row = current.rows[0] || {};
+ const newConfig = {
+ ...row.config,
+ kalshi_api_key: body.api_key,
+ kalshi_private_key: body.private_key,
+ kalshi_connected: true,
+ kalshi_connected_at: new Date().toISOString(),
+ kalshi_env: KALSHI_ENV,
+ };
+ await q('UPDATE risk_state SET config = $1, updated_at = NOW() WHERE id = $2', [
+ JSON.stringify(newConfig), row.id,
+ ]);
+ json(res, {
+ success: true,
+ api_key: body.api_key.substring(0, 12) + '...',
+ env: KALSHI_ENV,
+ message: 'Kalshi API keys saved',
+ });
+ break;
+ }
+
+ // ── Test Connection ──
+ case 'test_connection': {
+ try {
+ const data = await kalshiPublicFetch('GET', '/exchange/status');
+ json(res, { success: true, exchange_status: data, env: KALSHI_ENV });
+ } catch (err) {
+ json(res, { success: false, error: err.message }, 500);
+ }
+ break;
+ }
+
+ // ── Get Balance ──
+ case 'get_balance': {
+ const data = await kalshiFetch('GET', '/portfolio/balance');
+ json(res, { success: true, balance: data });
+ break;
+ }
+
+ // ── Get Markets (public) ──
+ case 'get_markets': {
+ const params = {};
+ if (body.category) params.category = body.category;
+ if (body.status) params.status = body.status;
+ if (body.limit) params.limit = body.limit;
+ if (body.cursor) params.cursor = body.cursor;
+ if (body.series_ticker) params.series_ticker = body.series_ticker;
+ if (body.event_ticker) params.event_ticker = body.event_ticker;
+ const qs = buildQueryString(params);
+ const data = await kalshiPublicFetch('GET', `/markets${qs}`);
+ json(res, { success: true, ...data });
+ break;
+ }
+
+ // ── Get Single Market ──
+ case 'get_market': {
+ if (!body.ticker) return json(res, { error: 'ticker required' }, 400);
+ const data = await kalshiPublicFetch('GET', `/markets/${encodeURIComponent(body.ticker)}`);
+ json(res, { success: true, market: data });
+ break;
+ }
+
+ // ── Get Orderbook ──
+ case 'get_orderbook': {
+ if (!body.ticker) return json(res, { error: 'ticker required' }, 400);
+ const qs = body.depth ? `?depth=${body.depth}` : '';
+ const data = await kalshiPublicFetch('GET', `/markets/${encodeURIComponent(body.ticker)}/orderbook${qs}`);
+ json(res, { success: true, orderbook: data });
+ break;
+ }
+
+ // ── Get Trades (public market trades) ──
+ case 'get_trades': {
+ if (!body.ticker) return json(res, { error: 'ticker required' }, 400);
+ const params = {};
+ if (body.limit) params.limit = body.limit;
+ if (body.cursor) params.cursor = body.cursor;
+ const qs = buildQueryString(params);
+ const data = await kalshiPublicFetch('GET', `/markets/${encodeURIComponent(body.ticker)}/trades${qs}`);
+ json(res, { success: true, ...data });
+ break;
+ }
+
+ // ── Get Events ──
+ case 'get_events': {
+ // Accept flat fields or nested in body.params (BrowseMarkets sends params wrapper)
+ const src = body.params || body;
+ const params = {};
+ if (src.status) params.status = src.status;
+ if (src.limit) params.limit = src.limit;
+ if (src.cursor) params.cursor = src.cursor;
+ if (src.series_ticker) params.series_ticker = src.series_ticker;
+ if (src.with_nested_markets !== undefined) params.with_nested_markets = src.with_nested_markets;
+ const qs = buildQueryString(params);
+ const data = await kalshiPublicFetch('GET', `/events${qs}`);
+ json(res, { success: true, ...data });
+ break;
+ }
+
+ // ── Get Single Event ──
+ case 'get_event': {
+ if (!body.event_ticker) return json(res, { error: 'event_ticker required' }, 400);
+ const qs = body.with_nested_markets ? '?with_nested_markets=true' : '';
+ const data = await kalshiPublicFetch('GET', `/events/${encodeURIComponent(body.event_ticker)}${qs}`);
+ json(res, { success: true, event: data });
+ break;
+ }
+
+ // ── Get Series ──
+ case 'get_series': {
+ if (!body.series_ticker) return json(res, { error: 'series_ticker required' }, 400);
+ const data = await kalshiPublicFetch('GET', `/series/${encodeURIComponent(body.series_ticker)}`);
+ json(res, { success: true, series: data });
+ break;
+ }
+
+ // ── Get Positions (from portfolio trades DB, or real Kalshi API if keys configured) ──
+ case 'get_positions': {
+ {
+ // No API keys — return portfolio trades from DB
+ const { rows: posRows } = await kenQ(`
+ SELECT pt.market_id as ticker, pt.market_title, pt.direction,
+ COUNT(*) FILTER (WHERE pt.status = 'open') as open_count,
+ SUM(pt.contracts) FILTER (WHERE pt.status = 'open') as open_contracts,
+ SUM(pt.cost_cents) FILTER (WHERE pt.status = 'open') as open_cost,
+ ROUND(AVG(pt.entry_price_cents) FILTER (WHERE pt.status = 'open')) as avg_price,
+ COUNT(*) as total_trades,
+ SUM(COALESCE(pt.pnl_cents, 0)) FILTER (WHERE pt.status != 'open') as realized_pnl
+ FROM ken_portfolio_trades pt
+ WHERE pt.created_at > NOW() - INTERVAL '24 hours'
+ GROUP BY pt.market_id, pt.market_title, pt.direction
+ HAVING COUNT(*) FILTER (WHERE pt.status = 'open') > 0
+ ORDER BY SUM(pt.cost_cents) FILTER (WHERE pt.status = 'open') DESC NULLS LAST
+ `);
+ const positions = posRows.map(r => ({
+ ticker: r.ticker,
+ market_ticker: r.ticker,
+ title: r.market_title || r.ticker,
+ market_exposure: r.direction === 'BUY_YES' ? parseInt(r.open_contracts || 0) : -parseInt(r.open_contracts || 0),
+ position: r.direction === 'BUY_YES' ? parseInt(r.open_contracts || 0) : -parseInt(r.open_contracts || 0),
+ position_cost: parseInt(r.open_cost || 0) * 100,
+ realized_pnl: parseInt(r.realized_pnl || 0) * 100,
+ fees_paid: 0,
+ avg_price_cents: parseInt(r.avg_price || 0),
+ open_trades: parseInt(r.open_count || 0),
+ total_trades: parseInt(r.total_trades || 0),
+ }));
+ json(res, { success: true, positions, market_positions: positions, is_paper: true });
+ }
+ break;
+ }
+
+ // ── Get Fills (auth required) ──
+ case 'get_fills': {
+ const params = {};
+ if (body.limit) params.limit = body.limit;
+ if (body.cursor) params.cursor = body.cursor;
+ if (body.ticker) params.ticker = body.ticker;
+ if (body.order_id) params.order_id = body.order_id;
+ const qs = buildQueryString(params);
+ const data = await kalshiFetch('GET', `/portfolio/fills${qs}`);
+ json(res, { success: true, ...data });
+ break;
+ }
+
+ // ── Get Orders (auth required) ──
+ case 'get_orders': {
+ const params = {};
+ if (body.limit) params.limit = body.limit;
+ if (body.cursor) params.cursor = body.cursor;
+ if (body.ticker) params.ticker = body.ticker;
+ if (body.status) params.status = body.status;
+ const qs = buildQueryString(params);
+ const data = await kalshiFetch('GET', `/portfolio/orders${qs}`);
+ json(res, { success: true, ...data });
+ break;
+ }
+
+ // ── Create Order (auth required) ──
+ case 'create_order': {
+ if (!body.ticker || !body.side || !body.action || !body.type || !body.count) {
+ return json(res, { error: 'ticker, side, action, type, and count are required' }, 400);
+ }
+ const orderPayload = {
+ ticker: body.ticker,
+ side: body.side, // 'yes' or 'no'
+ action: body.action, // 'buy' or 'sell'
+ type: body.type, // 'limit' or 'market'
+ count: body.count,
+ };
+ if (body.yes_price !== undefined) orderPayload.yes_price = body.yes_price;
+ if (body.no_price !== undefined) orderPayload.no_price = body.no_price;
+ if (body.client_order_id) orderPayload.client_order_id = body.client_order_id;
+ if (body.time_in_force) orderPayload.time_in_force = body.time_in_force;
+ if (body.expiration_ts) orderPayload.expiration_ts = body.expiration_ts;
+
+ const data = await kalshiFetch('POST', '/portfolio/orders', orderPayload);
+ json(res, { success: true, order: data });
+ break;
+ }
+
+ // ── Cancel Order (auth required) ──
+ case 'cancel_order': {
+ if (!body.order_id) return json(res, { error: 'order_id required' }, 400);
+ const data = await kalshiFetch('DELETE', `/portfolio/orders/${encodeURIComponent(body.order_id)}`);
+ json(res, { success: true, result: data });
+ break;
+ }
+
+ // ── Get Single Order (auth required) ──
+ case 'get_order': {
+ if (!body.order_id) return json(res, { error: 'order_id required' }, 400);
+ const data = await kalshiFetch('GET', `/portfolio/orders/${encodeURIComponent(body.order_id)}`);
+ json(res, { success: true, order: data });
+ break;
+ }
+
+ // ── Auto-Trader Status ──
+ case 'trader_status': {
+ const state = await getTraderState();
+ const allTrades = await kenQ('SELECT * FROM ken_trades ORDER BY created_at DESC LIMIT 50');
+ const closedTrades = (allTrades.rows || []).filter(t => t.status !== 'open');
+ const totalPnL = closedTrades.reduce((sum, t) => sum + (t.pnl_cents || 0), 0);
+ const wins = closedTrades.filter(t => (t.pnl_cents || 0) > 0).length;
+ const losses = closedTrades.filter(t => (t.pnl_cents || 0) < 0).length;
+ json(res, {
+ success: true,
+ config: TRADE_CONFIG,
+ state: {
+ open_positions: state.openCount,
+ total_invested: state.totalInvested,
+ available_budget: state.available,
+ daily_loss: state.dailyLoss,
+ },
+ positions: state.openPositions,
+ stats: {
+ total_trades: closedTrades.length,
+ wins, losses,
+ win_rate: closedTrades.length > 0 ? Math.round(wins / closedTrades.length * 100) : 0,
+ total_pnl_cents: totalPnL,
+ total_pnl_dollars: (totalPnL / 100).toFixed(2),
+ },
+ recent_trades: (allTrades.rows || []).slice(0, 20),
+ });
+ break;
+ }
+
+ // ── Toggle Auto-Trader ──
+ case 'trader_toggle': {
+ TRADE_CONFIG.enabled = !TRADE_CONFIG.enabled;
+ saveTradeConfig();
+ json(res, { success: true, enabled: TRADE_CONFIG.enabled, message: `Auto-trader ${TRADE_CONFIG.enabled ? 'ENABLED' : 'DISABLED'}` });
+ console.log(`[Ken] Auto-trader ${TRADE_CONFIG.enabled ? 'ENABLED' : 'DISABLED'} via API`);
+ break;
+ }
+
+ // ── Run Predictions (weather model pipeline) ──
+ case 'run_predictions': {
+ // Step 1: Get weather events from Kalshi
+ let events = [];
+ try {
+ const evData = await kalshiPublicFetch('GET', '/events?status=open&limit=100');
+ events = (evData.events || []).filter(e => {
+ const t = ((e.category || '') + ' ' + (e.title || '')).toLowerCase();
+ return t.includes('weather') || t.includes('temperature') || t.includes('temp ') ||
+ t.includes('rain') || t.includes('snow') || t.includes('precipitation') ||
+ t.includes('hurricane') || t.includes('wind') || t.includes('°f');
+ });
+ } catch { /* no events available - use weather cache */ }
+
+ // Step 2: Load cached weather data
+ const riskRow = await q('SELECT config FROM risk_state ORDER BY updated_at DESC LIMIT 1');
+ const rCfg = riskRow.rows[0]?.config || {};
+ const weatherCache = rCfg.weather_cache?.results || [];
+ const month = new Date().getMonth() + 1;
+
+ // Step 3: Generate predictions (only for real weather events with a city match)
+ const predictions = [];
+ for (const evt of events) {
+ const city = extractCity(evt.title);
+ if (!city) continue; // Skip non-geographic events (climate policy, earthquakes, etc.)
+ const spec = parseWeatherEvent(evt.title);
+ if (!spec || spec.variable === 'unknown') continue; // Skip if we can't parse a weather variable
+ const cityWeather = weatherCache.find(w => w.city === city);
+ if (!cityWeather) continue; // Skip if no weather data for this city
+ const features = cityWeather[spec.variable === 'snow' ? 'precipitation' : spec.variable] || cityWeather.temperature;
+
+ if (features && features.values?.length) {
+ const rawProb = ensembleExceedance(features, spec.threshold, spec.operator);
+ const prior = climatologicalPrior(spec.variable, spec.threshold, month);
+ const combined = bayesianUpdate(prior, rawProb ?? 0.5);
+ const pYes = Math.max(0.01, Math.min(0.99, combined));
+
+ // Get market price for edge calc
+ let marketPrice = 50;
+ try {
+ const mkts = await kalshiPublicFetch('GET', `/events/${encodeURIComponent(evt.event_ticker)}?with_nested_markets=true`);
+ const mkt = mkts.event?.markets?.[0] || mkts.markets?.[0];
+ if (mkt) {
+ const p = mkt.yes_ask || mkt.last_price || 50;
+ if (p > 0 && p < 100) marketPrice = p; // Skip fully priced markets
+ }
+ } catch {}
+
+ const edgeBps = Math.round((pYes * 100 - marketPrice) * 100);
+ predictions.push({
+ event_ticker: evt.event_ticker,
+ ticker: evt.title?.substring(0, 60),
+ market: evt.title,
+ city,
+ side: edgeBps > 0 ? 'yes' : 'no',
+ p_yes: Math.round(pYes * 1000) / 10,
+ price_cents: marketPrice,
+ edge_bps: edgeBps,
+ method: 'ensemble_bayesian_v1',
+ variable: spec.variable,
+ threshold: spec.threshold,
+ data_points: features.values.length,
+ });
+ }
+ }
+
+ // If no Kalshi events but we have weather data, generate synthetic predictions
+ if (predictions.length === 0 && weatherCache.length > 0) {
+ for (const wd of weatherCache.filter(w => !w.error)) {
+ if (wd.temperature?.values?.length) {
+ const maxT = wd.temperature.max;
+ const threshold = Math.round(maxT / 5) * 5;
+ const rawProb = ensembleExceedance(wd.temperature, threshold, '>=');
+ const prior = climatologicalPrior('temperature', threshold, month);
+ const combined = bayesianUpdate(prior, rawProb ?? 0.5);
+ const pYes = Math.max(0.01, Math.min(0.99, combined));
+ predictions.push({
+ ticker: `${wd.city} temp >= ${threshold}°F`,
+ market: `Will the high temperature in ${wd.city} reach ${threshold}°F?`,
+ city: wd.city,
+ side: pYes > 0.5 ? 'yes' : 'no',
+ p_yes: Math.round(pYes * 1000) / 10,
+ price_cents: 50,
+ edge_bps: Math.round((pYes * 100 - 50) * 100),
+ method: 'synthetic_forecast',
+ variable: 'temperature',
+ threshold,
+ data_points: wd.temperature.values.length,
+ });
+ }
+ }
+ }
+
+ predictions.sort((a, b) => Math.abs(b.edge_bps) - Math.abs(a.edge_bps));
+ const buySignals = predictions.filter(p => p.edge_bps > 0);
+ const avgEdge = predictions.length ? Math.round(predictions.reduce((s, p) => s + p.edge_bps, 0) / predictions.length) : 0;
+
+ json(res, {
+ success: true,
+ predictions,
+ buy_signals: buySignals.length,
+ avg_edge_bps: avgEdge,
+ total_events_scanned: events.length,
+ weather_cities: weatherCache.filter(w => !w.error).length,
+ });
+ break;
+ }
+
+ // ── Disconnect: remove keys from config ──
+ case 'disconnect': {
+ const current = await q('SELECT * FROM risk_state ORDER BY updated_at DESC LIMIT 1');
+ const row = current.rows[0] || {};
+ const newConfig = {
+ ...row.config,
+ kalshi_api_key: null,
+ kalshi_private_key: null,
+ kalshi_connected: false,
+ kalshi_connected_at: null,
+ };
+ await q('UPDATE risk_state SET config = $1, updated_at = NOW() WHERE id = $2', [
+ JSON.stringify(newConfig), row.id,
+ ]);
+ json(res, { success: true, message: 'Kalshi keys removed, disconnected' });
+ break;
+ }
+
+ // ── Status: show current connection config (masked) ──
+ case 'status': {
+ const current = await q('SELECT config FROM risk_state ORDER BY updated_at DESC LIMIT 1');
+ const cfg = current.rows[0]?.config || {};
+ json(res, {
+ connected: !!cfg.kalshi_connected,
+ api_key: cfg.kalshi_api_key ? cfg.kalshi_api_key.substring(0, 12) + '...' : null,
+ has_private_key: !!cfg.kalshi_private_key,
+ connected_at: cfg.kalshi_connected_at || null,
+ env: KALSHI_ENV,
+ });
+ break;
+ }
+
+ default:
+ json(res, {
+ error: `Unknown action: ${action}`,
+ available_actions: [
+ 'save_keys', 'test_connection', 'get_balance',
+ 'get_markets', 'get_market', 'get_orderbook', 'get_trades',
+ 'get_events', 'get_event', 'get_series',
+ 'get_positions', 'get_fills', 'get_orders',
+ 'create_order', 'cancel_order', 'get_order',
+ 'run_predictions', 'disconnect', 'status',
+ ],
+ }, 400);
+ }
+ } catch (err) {
+ json(res, { success: false, error: err.message }, 500);
+ }
+ },
+
+ // ════════════════════════════════════════
+ // WEATHER ENDPOINTS
+ // ════════════════════════════════════════
+
+ 'POST /api/weather': async (req, res) => {
+ const body = await readBody(req);
+
+ if (body.action === 'fetch_all') {
+ try {
+ const cities = body.cities || ['New York', 'Chicago', 'Miami', 'Denver', 'Los Angeles', 'Seattle'];
+ const useNws = body.force_nws === true; // opt-in to real NWS (flaky from this server)
+
+ // ── Generate synthetic seasonal forecast data (fast, reliable) ──
+ function generateSyntheticCities(cityList) {
+ const month = new Date().getMonth();
+ const results = [];
+ let totalDP = 0;
+ for (const city of cityList) {
+ const coords = CITY_COORDS[city]; if (!coords) continue;
+ const baseTemp = [35,38,48,58,68,78,85,83,75,62,48,38][month] + (coords.lat < 35 ? 15 : coords.lat > 42 ? -8 : 0);
+ const temps = Array.from({length: 14}, (_, i) => baseTemp + Math.round((Math.random() - 0.5) * 12) + (i < 7 ? 3 : -2));
+ const precips = Array.from({length: 14}, () => Math.round(Math.random() * 60));
+ const winds = Array.from({length: 14}, () => 5 + Math.round(Math.random() * 15));
+ const mkStat = (arr) => ({ mean: arr.reduce((a,b)=>a+b)/arr.length, min: Math.min(...arr), max: Math.max(...arr), latest: arr[0] });
+ results.push({
+ city, synthetic: true,
+ temperature: { variable: 'temperature', unit: 'F', values: temps, ...mkStat(temps) },
+ precipitation: { variable: 'precipitation', unit: 'percent', values: precips, ...mkStat(precips) },
+ wind: { variable: 'wind', unit: 'mph', values: winds, ...mkStat(winds) },
+ data_points: 42,
+ });
+ totalDP += 42;
+ }
+ return { results, totalDP };
+ }
+
+ let responseData;
+
+ if (useNws) {
+ // Real NWS path — wrapped in 15s global timeout, falls back to synthetic
+ const nwsResult = await Promise.race([
+ (async () => {
+ const results = [];
+ let dp = 0;
+ const mets = new Set();
+ for (const city of cities) {
+ const coords = CITY_COORDS[city]; if (!coords) continue;
+ try {
+ const grid = await nwsFetch(`${NWS_BASE}/points/${coords.lat},${coords.lon}`);
+ const forecast = await nwsFetch(`${NWS_BASE}/gridpoints/${grid.properties.gridId}/${grid.properties.gridX},${grid.properties.gridY}/forecast`);
+ const tempF = extractForecastFeatures(forecast, 'temperature');
+ const precip = extractForecastFeatures(forecast, 'precipitation');
+ const wind = extractForecastFeatures(forecast, 'wind');
+ const cdp = (tempF?.values?.length||0) + (precip?.values?.length||0) + (wind?.values?.length||0);
+ dp += cdp;
+ if (tempF) mets.add('temperature'); if (precip) mets.add('precipitation'); if (wind) mets.add('wind');
+ results.push({ city, temperature: tempF, precipitation: precip, wind, data_points: cdp });
+ } catch (e) { results.push({ city, error: e.message }); }
+ }
+ return { results, totalDP: dp, metrics: [...mets], synthetic: false };
+ })(),
+ new Promise(resolve => setTimeout(() => resolve(null), 15000)),
+ ]);
+
+ if (nwsResult && nwsResult.results.some(r => !r.error)) {
+ responseData = nwsResult;
+ } else {
+ const syn = generateSyntheticCities(cities);
+ responseData = { ...syn, metrics: ['temperature','precipitation','wind'], synthetic: true, note: 'NWS timed out — using synthetic' };
+ }
+ } else {
+ // Default: synthetic data (instant, always works)
+ const syn = generateSyntheticCities(cities);
+ responseData = { ...syn, metrics: ['temperature','precipitation','wind'], synthetic: true, note: 'Using seasonal synthetic forecasts (pass force_nws:true for real NWS data)' };
+ }
+
+ // Cache in DB
+ const row = (await q('SELECT id, config FROM risk_state ORDER BY updated_at DESC LIMIT 1')).rows[0];
+ if (row) {
+ const newCfg = { ...(row.config || {}), weather_cache: { results: responseData.results, fetched_at: new Date().toISOString(), synthetic: responseData.synthetic } };
+ await q('UPDATE risk_state SET config = $1, updated_at = NOW() WHERE id = $2', [JSON.stringify(newCfg), row.id]);
+ }
+
+ json(res, {
+ success: true,
+ synthetic: responseData.synthetic,
+ stations: responseData.results.length,
+ data_points: responseData.totalDP,
+ metrics: responseData.metrics,
+ cities: responseData.results,
+ fetched_at: new Date().toISOString(),
+ note: responseData.note || undefined,
+ });
+ } catch (err) {
+ json(res, { success: false, error: err.message }, 500);
+ }
+ } else {
+ json(res, { error: `Unknown weather action: ${body.action}` }, 400);
+ }
+ },
+
+ // ════════════════════════════════════════
+ // RISK ENDPOINTS
+ // ════════════════════════════════════════
+
+ 'POST /api/risk': async (req, res) => {
+ const body = await readBody(req);
+
+ try {
+ const current = await q('SELECT * FROM risk_state ORDER BY updated_at DESC LIMIT 1');
+ const row = current.rows[0] || {};
+ const cfg = row.config || {};
+
+ if (body.action === 'get_config') {
+ json(res, {
+ success: true,
+ config: {
+ safe_mode: cfg.safe_mode ?? true,
+ risk_profile: cfg.risk_profile ?? 'conservative',
+ max_position_size: cfg.max_position_size ?? 100,
+ max_contracts_per_market: cfg.max_contracts_per_market ?? 25,
+ max_dollars_at_risk: cfg.max_dollars_at_risk ?? 250,
+ max_daily_loss: cfg.max_daily_loss ?? cfg.daily_loss_cap ?? 50,
+ daily_loss_cap: cfg.daily_loss_cap ?? 50,
+ max_open_orders: cfg.max_open_orders ?? 10,
+ max_exposure: cfg.max_exposure ?? 500,
+ stop_loss_pct: cfg.stop_loss_pct ?? 20,
+ auto_hedge: cfg.auto_hedge ?? false,
+ allowed_categories: cfg.allowed_categories ?? [],
+ kill_switch_active: row.kill_switch_active || false,
+ kill_reason: row.kill_reason || null,
+ bankroll: parseFloat(row.bankroll || 0),
+ daily_pnl: parseFloat(row.daily_pnl || 0),
+ open_exposure: parseFloat(row.open_exposure || 0),
+ },
+ });
+ } else if (body.action === 'update_config') {
+ // Accept flat fields (from RiskProfile step) or wrapped in config object
+ const updates = body.config || {};
+ if (body.max_contracts_per_market !== undefined) updates.max_contracts_per_market = body.max_contracts_per_market;
+ if (body.max_dollars_at_risk !== undefined) updates.max_dollars_at_risk = body.max_dollars_at_risk;
+ if (body.daily_loss_cap !== undefined) updates.daily_loss_cap = body.daily_loss_cap;
+ if (body.risk_profile !== undefined) updates.risk_profile = body.risk_profile;
+ if (body.safe_mode !== undefined) updates.safe_mode = body.safe_mode;
+ const newConfig = { ...cfg, ...updates };
+ await q('UPDATE risk_state SET config = $1, updated_at = NOW() WHERE id = $2', [
+ JSON.stringify(newConfig), row.id,
+ ]);
+
+ // Also update top-level risk fields if provided
+ if (body.config?.kill_switch_active !== undefined) {
+ await q('UPDATE risk_state SET kill_switch_active = $1, kill_reason = $2, updated_at = NOW() WHERE id = $3', [
+ body.config.kill_switch_active,
+ body.config.kill_reason || null,
+ row.id,
+ ]);
+ }
+
+ const updated = await q('SELECT * FROM risk_state ORDER BY updated_at DESC LIMIT 1');
+ const u = updated.rows[0] || {};
+ json(res, {
+ success: true,
+ message: 'Risk config updated',
+ config: u.config || {},
+ });
+ } else {
+ json(res, { error: `Unknown risk action: ${body.action}` }, 400);
+ }
+ } catch (err) {
+ json(res, { success: false, error: err.message }, 500);
+ }
+ },
+
+ // ════════════════════════════════════════
+ // TRADING MODE CONTROL
+ // ════════════════════════════════════════
+
+ 'POST /api/trading/mode': async (req, res) => {
+ const body = await readBody(req);
+ try {
+ const current = await q('SELECT * FROM risk_state ORDER BY updated_at DESC LIMIT 1');
+ const row = current.rows[0] || {};
+ const cfg = row.config || {};
+
+ if (body.action === 'get') {
+ // Get current trading mode
+ const traderState = await getTraderState().catch(() => ({ openPositions: [], openCount: 0, totalInvested: 0, dailyLoss: 0, available: 0 }));
+ return json(res, {
+ env: KALSHI_ENV,
+ safe_mode: cfg.safe_mode ?? true,
+ kalshi_connected: !!(cfg.kalshi_api_key && cfg.kalshi_private_key),
+ trade_config: TRADE_CONFIG,
+ trader_state: traderState,
+ auto_trader_enabled: TRADE_CONFIG.enabled,
+ });
+ }
+
+ if (body.action === 'switch_env') {
+ const newEnv = body.env === 'prod' ? 'prod' : 'demo';
+ const newConfig = { ...cfg, kalshi_env: newEnv };
+ await q('UPDATE risk_state SET config = $1, updated_at = NOW() WHERE id = $2', [JSON.stringify(newConfig), row.id]);
+ KALSHI_ENV = newEnv;
+ KALSHI_BASE_URL = KALSHI_BASE_URLS[newEnv];
+ console.log(`[Ken] Environment switched to ${newEnv.toUpperCase()} (${KALSHI_BASE_URL})`);
+ return json(res, { success: true, env: newEnv, base_url: KALSHI_BASE_URL });
+ }
+
+ if (body.action === 'toggle_safe_mode') {
+ const newSafe = !(cfg.safe_mode ?? true);
+ const newConfig = { ...cfg, safe_mode: newSafe };
+ await q('UPDATE risk_state SET config = $1, updated_at = NOW() WHERE id = $2', [JSON.stringify(newConfig), row.id]);
+ console.log(`[Ken] Safe mode ${newSafe ? 'ENABLED' : 'DISABLED'}`);
+ return json(res, { success: true, safe_mode: newSafe });
+ }
+
+ if (body.action === 'toggle_auto_trader') {
+ TRADE_CONFIG.enabled = !TRADE_CONFIG.enabled;
+ saveTradeConfig();
+ console.log(`[Ken] Auto-trader ${TRADE_CONFIG.enabled ? 'ENABLED' : 'DISABLED'}`);
+ return json(res, { success: true, auto_trader_enabled: TRADE_CONFIG.enabled });
+ }
+
+ if (body.action === 'update_trade_config') {
+ if (body.budget_cents !== undefined) TRADE_CONFIG.budget_cents = Math.max(100, Math.min(100000, body.budget_cents));
+ if (body.max_position_cents !== undefined) TRADE_CONFIG.max_position_cents = Math.max(50, Math.min(10000, body.max_position_cents));
+ if (body.max_open_positions !== undefined) TRADE_CONFIG.max_open_positions = Math.max(1, Math.min(20, body.max_open_positions));
+ if (body.min_confidence !== undefined) TRADE_CONFIG.min_confidence = Math.max(50, Math.min(99, body.min_confidence));
+ if (body.daily_loss_limit_cents !== undefined) TRADE_CONFIG.daily_loss_limit_cents = Math.max(100, Math.min(50000, body.daily_loss_limit_cents));
+ saveTradeConfig();
+ return json(res, { success: true, trade_config: TRADE_CONFIG });
+ }
+
+ json(res, { error: `Unknown trading mode action: ${body.action}` }, 400);
+ } catch (err) {
+ json(res, { error: err.message }, 500);
+ }
+ },
+
+ // ════════════════════════════════════════
+ // TRADING HISTORY & P&L
+ // ════════════════════════════════════════
+
+ 'GET /api/trading/history': async (req, res) => {
+ try {
+ const { rows: trades } = await kenQ('SELECT * FROM ken_trades ORDER BY created_at DESC LIMIT 100');
+ const { rows: [summary] } = await kenQ(`
+ SELECT
+ COUNT(*) as total_trades,
+ COUNT(*) FILTER (WHERE status = 'open') as open_trades,
+ COUNT(*) FILTER (WHERE pnl_cents > 0) as winning_trades,
+ COUNT(*) FILTER (WHERE pnl_cents < 0) as losing_trades,
+ COALESCE(SUM(pnl_cents), 0) as total_pnl,
+ COALESCE(SUM(cost_cents) FILTER (WHERE status = 'open'), 0) as open_exposure
+ FROM ken_trades
+ `);
+ json(res, { trades, summary });
+ } catch (err) {
+ json(res, { error: err.message }, 500);
+ }
+ },
+
+ // ════════════════════════════════════════
+ // PAPER TRADING
+ // ════════════════════════════════════════
+
+ 'POST /api/paper': async (req, res) => {
+ const body = await readBody(req);
+
+ try {
+ const current = await q('SELECT * FROM risk_state ORDER BY updated_at DESC LIMIT 1');
+ const row = current.rows[0] || {};
+ const cfg = row.config || {};
+ const paperTrades = cfg.paper_trades || [];
+
+ if (body.action === 'submit_order') {
+ if (!body.ticker || !body.side || !body.count) {
+ return json(res, { error: 'ticker, side, and count required' }, 400);
+ }
+
+ const orderId = `paper_${Date.now()}_${Math.random().toString(36).substring(2, 8)}`;
+ const fillPrice = body.yes_price || body.no_price || body.price || 50; // cents
+
+ const paperOrder = {
+ order_id: orderId,
+ ticker: body.ticker,
+ side: body.side, // 'yes' or 'no'
+ action: body.action_type || 'buy',
+ type: body.type || 'market',
+ count: body.count,
+ price: fillPrice,
+ cost: fillPrice * body.count, // in cents
+ status: 'filled',
+ created_at: new Date().toISOString(),
+ filled_at: new Date().toISOString(),
+ is_paper: true,
+ };
+
+ paperTrades.push(paperOrder);
+
+ const newConfig = { ...cfg, paper_trades: paperTrades };
+ await q('UPDATE risk_state SET config = $1, updated_at = NOW() WHERE id = $2', [
+ JSON.stringify(newConfig), row.id,
+ ]);
+
+ json(res, { success: true, order: paperOrder, message: 'Paper order filled' });
+
+ } else if (body.action === 'get_positions') {
+ // Aggregate from ken_portfolio_trades (live hyper-trading data)
+ try {
+ const { rows } = await kenQ(`
+ SELECT pt.market_id as ticker, pt.market_title, pt.direction,
+ SUM(pt.contracts) as total_contracts,
+ SUM(pt.cost_cents) as position_cost,
+ ROUND(AVG(pt.entry_price_cents)) as avg_price,
+ COUNT(*) as trades,
+ SUM(CASE WHEN pt.status != 'open' THEN pt.pnl_cents ELSE 0 END) as realized_pnl
+ FROM ken_portfolio_trades pt
+ WHERE pt.created_at > NOW() - INTERVAL '24 hours'
+ GROUP BY pt.market_id, pt.market_title, pt.direction
+ ORDER BY SUM(pt.cost_cents) DESC
+ `);
+ const positions = rows.map(r => ({
+ ticker: r.ticker,
+ market_ticker: r.ticker,
+ title: r.market_title,
+ side: r.direction === 'BUY_YES' ? 'yes' : 'no',
+ market_exposure: r.direction === 'BUY_YES' ? parseInt(r.total_contracts) : -parseInt(r.total_contracts),
+ position: r.direction === 'BUY_YES' ? parseInt(r.total_contracts) : -parseInt(r.total_contracts),
+ position_cost: parseInt(r.position_cost) * 100,
+ avg_price_cents: parseInt(r.avg_price),
+ realized_pnl: parseInt(r.realized_pnl || 0) * 100,
+ fees_paid: 0,
+ trades: parseInt(r.trades),
+ }));
+ json(res, { success: true, positions, is_paper: true });
+ } catch (e) {
+ // Fallback to old paper trades
+ const positionMap = {};
+ for (const trade of paperTrades) {
+ const key = `${trade.ticker}_${trade.side}`;
+ if (!positionMap[key]) positionMap[key] = { ticker: trade.ticker, side: trade.side, total_contracts: 0, avg_price: 0, total_cost: 0, trades: 0 };
+ const pos = positionMap[key];
+ if (trade.action === 'buy') { pos.total_cost += trade.price * trade.count; pos.total_contracts += trade.count; }
+ else { pos.total_cost -= trade.price * trade.count; pos.total_contracts -= trade.count; }
+ pos.trades++;
+ pos.avg_price = pos.total_contracts > 0 ? Math.round(pos.total_cost / pos.total_contracts) : 0;
+ }
+ const positions = Object.values(positionMap).filter(p => p.total_contracts !== 0);
+ json(res, { success: true, positions, is_paper: true });
+ }
+
+ } else if (body.action === 'get_fills') {
+ // Return paper trade history
+ const limit = body.limit || 50;
+ const fills = paperTrades.slice(-limit).reverse();
+ json(res, { success: true, fills, total: paperTrades.length, is_paper: true });
+
+ } else if (body.action === 'clear') {
+ // Clear all paper trades
+ const newConfig = { ...cfg, paper_trades: [] };
+ await q('UPDATE risk_state SET config = $1, updated_at = NOW() WHERE id = $2', [
+ JSON.stringify(newConfig), row.id,
+ ]);
+ json(res, { success: true, message: 'Paper trades cleared' });
+
+ } else {
+ json(res, { error: `Unknown paper action: ${body.action}` }, 400);
+ }
+ } catch (err) {
+ json(res, { success: false, error: err.message }, 500);
+ }
+ },
+
+ // ── Positions Detail API (collapsible tables) ──
+ 'GET /api/positions': async (req, res) => {
+ try {
+ // All positions with full stats
+ const { rows: positions } = await kenQ(`
+ SELECT
+ pt.market_id AS ticker,
+ pt.direction,
+ pt.market_title AS title,
+ COUNT(*) FILTER (WHERE pt.status = 'open') AS open_trades,
+ SUM(pt.contracts) FILTER (WHERE pt.status = 'open') AS open_contracts,
+ SUM(pt.cost_cents) FILTER (WHERE pt.status = 'open') AS open_cost_cents,
+ ROUND(AVG(pt.entry_price_cents) FILTER (WHERE pt.status = 'open')) AS avg_entry_price,
+ SUM(COALESCE(pt.pnl_cents, 0)) FILTER (WHERE pt.status != 'open') AS realized_pnl_cents,
+ COUNT(*) AS total_trades,
+ COUNT(*) FILTER (WHERE pt.status != 'open') AS closed_trades,
+ MIN(pt.created_at) AS first_trade_at,
+ MAX(pt.created_at) AS last_trade_at,
+ MIN(pt.entry_price_cents) FILTER (WHERE pt.status = 'open') AS min_entry,
+ MAX(pt.entry_price_cents) FILTER (WHERE pt.status = 'open') AS max_entry
+ FROM ken_portfolio_trades pt
+ GROUP BY pt.market_id, pt.direction, pt.market_title
+ HAVING COUNT(*) FILTER (WHERE pt.status = 'open') > 0
+ ORDER BY SUM(pt.cost_cents) FILTER (WHERE pt.status = 'open') DESC NULLS LAST
+ `);
+
+ // Category grouping by market event prefix
+ const grouped = {};
+ for (const p of positions) {
+ const prefix = (p.ticker || '').split('-')[0];
+ if (!grouped[prefix]) grouped[prefix] = { event: prefix, title: p.title, positions: [], totalCost: 0, totalPnl: 0, totalContracts: 0 };
+ grouped[prefix].positions.push(p);
+ grouped[prefix].totalCost += parseInt(p.open_cost_cents || 0);
+ grouped[prefix].totalPnl += parseInt(p.realized_pnl_cents || 0);
+ grouped[prefix].totalContracts += parseInt(p.open_contracts || 0);
+ }
+
+ // Summary stats
+ const totalCost = positions.reduce((s, p) => s + parseInt(p.open_cost_cents || 0), 0);
+ const totalPnl = positions.reduce((s, p) => s + parseInt(p.realized_pnl_cents || 0), 0);
+ const totalContracts = positions.reduce((s, p) => s + parseInt(p.open_contracts || 0), 0);
+ const totalTrades = positions.reduce((s, p) => s + parseInt(p.total_trades || 0), 0);
+
+ json(res, {
+ success: true,
+ positions: positions.map(p => ({
+ ...p,
+ open_trades: parseInt(p.open_trades || 0),
+ open_contracts: parseInt(p.open_contracts || 0),
+ open_cost_cents: parseInt(p.open_cost_cents || 0),
+ avg_entry_price: parseInt(p.avg_entry_price || 0),
+ realized_pnl_cents: parseInt(p.realized_pnl_cents || 0),
+ total_trades: parseInt(p.total_trades || 0),
+ closed_trades: parseInt(p.closed_trades || 0),
+ min_entry: parseInt(p.min_entry || 0),
+ max_entry: parseInt(p.max_entry || 0),
+ })),
+ grouped: Object.values(grouped).sort((a, b) => b.totalCost - a.totalCost),
+ summary: { totalCost, totalPnl, totalContracts, totalTrades, positionCount: positions.length },
+ });
+ } catch (err) {
+ json(res, { success: false, error: err.message }, 500);
+ }
+ },
+
+ // Get trade history for a specific position
+ 'POST /api/positions/trades': async (req, res) => {
+ try {
+ const body = await readBody(req);
+ const { ticker, direction, limit: lim } = body;
+ if (!ticker) return json(res, { error: 'ticker required' }, 400);
+
+ let sql = `SELECT * FROM ken_portfolio_trades WHERE market_id = $1`;
+ const params = [ticker];
+ if (direction) { sql += ` AND direction = $2`; params.push(direction); }
+ sql += ` ORDER BY created_at DESC LIMIT ${Math.min(parseInt(lim) || 100, 500)}`;
+
+ const { rows } = await kenQ(sql, params);
+ json(res, { success: true, trades: rows });
+ } catch (err) {
+ json(res, { success: false, error: err.message }, 500);
+ }
+ },
+
+ // ── Signal Pipeline API ──
+ 'GET /api/signals': async (req, res) => {
+ try {
+ const { rows: signals } = await kenQ(`
+ SELECT id, market_id, direction, expected_edge, size_recommendation, confidence, reasoning, sources, risk_approved, executed, created_at
+ FROM ken_strategy_signals
+ ORDER BY created_at DESC
+ LIMIT 50
+ `);
+ const { rows: shifts } = await kenQ(`
+ SELECT market_id, prior_probability, sentiment_impact, adjusted_probability, market_probability, edge, num_articles, created_at
+ FROM ken_probability_shifts
+ ORDER BY created_at DESC
+ LIMIT 50
+ `);
+ const { rows: recentSentiment } = await kenQ(`
+ SELECT event_tag, market_ticker, AVG(sentiment) as avg_sentiment, AVG(confidence) as avg_confidence, COUNT(*) as count
+ FROM ken_event_sentiment
+ WHERE created_at > NOW() - INTERVAL '1 hour'
+ GROUP BY event_tag, market_ticker
+ ORDER BY count DESC
+ LIMIT 30
+ `);
+ // Enrich with Kalshi URLs
+ const enrichWithUrl = (rows) => rows.map(r => {
+ const ticker = r.market_id || '';
+ const eventTicker = ticker.replace(/-[^-]+$/, '') || ticker;
+ const seriesTicker = eventTicker.replace(/-[^-]+$/, '') || eventTicker;
+ return { ...r, event_ticker: eventTicker, kalshi_url: `https://kalshi.com/markets/${seriesTicker.toLowerCase()}/${eventTicker.toLowerCase()}` };
+ });
+ json(res, {
+ signals: enrichWithUrl(signals),
+ probabilityShifts: enrichWithUrl(shifts),
+ eventSentiment: recentSentiment,
+ pipeline: {
+ scanInterval: '15 min',
+ signalInterval: '5 min',
+ intelligenceInterval: '30 min',
+ cachedMarkets: cachedActiveMarkets.length,
+ riskLimits: RISK_LIMITS,
+ },
+ });
+ } catch (err) {
+ json(res, { error: err.message }, 500);
+ }
+ },
+
+ 'GET /api/signals/dashboard': async (req, res) => {
+ try {
+ // Summary stats for the signal pipeline
+ const { rows: [stats] } = await kenQ(`
+ SELECT
+ COUNT(*) as total_signals,
+ COUNT(CASE WHEN risk_approved THEN 1 END) as approved_signals,
+ COUNT(CASE WHEN direction = 'BUY_YES' THEN 1 END) as buy_yes,
+ COUNT(CASE WHEN direction = 'BUY_NO' THEN 1 END) as buy_no,
+ AVG(expected_edge) as avg_edge,
+ AVG(confidence) as avg_confidence,
+ MAX(created_at) as latest_signal
+ FROM ken_strategy_signals
+ WHERE created_at > NOW() - INTERVAL '24 hours'
+ `);
+ const { rows: topSignals } = await kenQ(`
+ SELECT market_id, direction, expected_edge, confidence, reasoning, risk_approved, created_at
+ FROM ken_strategy_signals
+ WHERE created_at > NOW() - INTERVAL '4 hours' AND risk_approved = true
+ ORDER BY ABS(expected_edge) DESC
+ LIMIT 10
+ `);
+ const { rows: sourceBreakdown } = await kenQ(`
+ SELECT source, COUNT(*) as cnt, AVG(sentiment_score) as avg_sent
+ FROM ken_sentiment
+ WHERE captured_at > NOW() - INTERVAL '1 hour'
+ GROUP BY source
+ ORDER BY cnt DESC
+ LIMIT 20
+ `);
+ json(res, { stats, topSignals, sourceBreakdown, cachedMarkets: cachedActiveMarkets.length });
+ } catch (err) {
+ json(res, { error: err.message }, 500);
+ }
+ },
+
+ // ════════════════════════════════════════
+ // INTELLIGENCE FEED
+ // ════════════════════════════════════════
+
+ 'GET /api/intelligence': async (req, res) => {
+ try {
+ const { rows: recent } = await kenQ(`
+ SELECT source, subreddit, keyword, post_title, post_url, score, num_comments, sentiment_score, captured_at
+ FROM ken_sentiment
+ ORDER BY captured_at DESC
+ LIMIT 100
+ `);
+ const { rows: sourceCounts } = await kenQ(`
+ SELECT source, COUNT(*) as cnt, AVG(sentiment_score) as avg_sent,
+ MAX(captured_at) as latest
+ FROM ken_sentiment
+ WHERE captured_at > NOW() - INTERVAL '4 hours'
+ GROUP BY source ORDER BY cnt DESC
+ `);
+ const { rows: [totals] } = await kenQ(`
+ SELECT
+ COUNT(*) as total_items,
+ COUNT(*) FILTER (WHERE captured_at > NOW() - INTERVAL '1 hour') as last_hour,
+ COUNT(*) FILTER (WHERE captured_at > NOW() - INTERVAL '4 hours') as last_4h,
+ AVG(sentiment_score) FILTER (WHERE captured_at > NOW() - INTERVAL '1 hour') as avg_sentiment_1h
+ FROM ken_sentiment
+ `);
+ json(res, { recent, sourceCounts, totals });
+ } catch (err) {
+ json(res, { error: err.message }, 500);
+ }
+ },
+
+ // ════════════════════════════════════════
+ // PREDICTIONS FEED
+ // ════════════════════════════════════════
+
+ 'GET /api/predictions': async (req, res) => {
+ try {
+ const { rows } = await kenQ(`
+ SELECT ticker, event_ticker, title, signal_type, side, confidence, entry_price, edge_bps, reasoning, sources, created_at
+ FROM ken_predictions
+ ORDER BY created_at DESC
+ LIMIT 100
+ `);
+ json(res, { predictions: rows });
+ } catch (err) {
+ json(res, { error: err.message }, 500);
+ }
+ },
+
+ // ── Live Markets (all active with snapshots) ──
+ 'GET /api/markets': async (req, res) => {
+ try {
+ const { rows } = await kenQ(`
+ SELECT DISTINCT ON (ticker) ticker, event_ticker, title, subtitle, category,
+ yes_bid, yes_ask, no_bid, no_ask, last_price, volume, volume_24h, open_interest, spread,
+ captured_at
+ FROM ken_market_snapshots
+ WHERE captured_at > NOW() - INTERVAL '1 hour'
+ ORDER BY ticker, captured_at DESC
+ `);
+ json(res, { markets: rows, count: rows.length, cached: cachedActiveMarkets.length });
+ } catch (err) {
+ json(res, { error: err.message }, 500);
+ }
+ },
+
+ // ── Energy/LNG Arbitrage Opportunities ──
+ 'GET /api/energy-arb': async (req, res) => {
+ try {
+ const arbs = await energyArbitrageScan(cachedActiveMarkets);
+ // Also get recent energy-related signals
+ const { rows: energySignals } = await kenQ(`
+ SELECT ticker, title, signal_type, side, confidence, entry_price, edge_bps, reasoning, sources, created_at
+ FROM ken_predictions
+ WHERE signal_type IN ('energy_arb', 'polymarket_arb')
+ OR reasoning ILIKE '%energy%' OR reasoning ILIKE '%oil%' OR reasoning ILIKE '%gas%' OR reasoning ILIKE '%lng%'
+ ORDER BY created_at DESC LIMIT 50
+ `);
+ json(res, {
+ arbitrage_opportunities: arbs,
+ energy_signals: energySignals,
+ scan_time: new Date().toISOString(),
+ markets_scanned: cachedActiveMarkets.length,
+ });
+ } catch (err) {
+ json(res, { error: err.message }, 500);
+ }
+ },
+
+ // ── All Active Signals (for trading) ──
+ 'GET /api/signals': async (req, res) => {
+ try {
+ const { rows } = await kenQ(`
+ SELECT market_id as ticker, direction, expected_edge, confidence, reasoning, sources, risk_approved, created_at
+ FROM ken_strategy_signals
+ WHERE created_at > NOW() - INTERVAL '2 hours'
+ ORDER BY created_at DESC LIMIT 200
+ `);
+ json(res, { signals: rows, count: rows.length });
+ } catch (err) {
+ json(res, { error: err.message }, 500);
+ }
+ },
+
+ // ════════════════════════════════════════
+ // DASHBOARD — aggregated paper portfolio stats
+ // ════════════════════════════════════════
+
+ 'GET /api/dashboard': async (req, res) => {
+ try {
+ // Aggregate balance across all portfolios
+ const { rows: [balRow] } = await kenQ(`
+ SELECT SUM(balance_cents) as total_balance,
+ SUM(total_invested_cents) as total_invested,
+ SUM(total_returned_cents) as total_returned
+ FROM ken_portfolios
+ `);
+
+ // Seed money + economics
+ const totalBalance = Number(balRow?.total_balance || 0);
+ const totalInvested = Number(balRow?.total_invested || 0);
+ const totalReturned = Number(balRow?.total_returned || 0);
+ const seedMoney = totalBalance + totalInvested - totalReturned; // always 5000000 cents ($50K)
+ const netPnl = totalBalance - seedMoney; // how much above/below seed
+ const roi = seedMoney > 0 ? ((totalBalance - seedMoney) / seedMoney * 100) : 0;
+
+ // Daily spend breakdown (last 7 days)
+ const { rows: spendRows } = await kenQ(`
+ SELECT resolved_at::date as day,
+ COUNT(*) as trades,
+ SUM(CASE WHEN pnl_cents > 0 THEN 1 ELSE 0 END) as wins,
+ SUM(CASE WHEN pnl_cents < 0 THEN 1 ELSE 0 END) as losses,
+ SUM(pnl_cents) as net_pnl,
+ SUM(CASE WHEN pnl_cents < 0 THEN ABS(pnl_cents) ELSE 0 END) as gross_losses,
+ SUM(CASE WHEN pnl_cents > 0 THEN pnl_cents ELSE 0 END) as gross_wins,
+ SUM(cost_cents) as capital_deployed
+ FROM ken_portfolio_trades
+ WHERE status != 'open' AND resolved_at IS NOT NULL
+ GROUP BY resolved_at::date ORDER BY day DESC LIMIT 7
+ `);
+
+ // Daily budget across all portfolios
+ const { rows: [budgetRow] } = await kenQ(`
+ SELECT SUM(daily_budget_cents) as total_daily_budget,
+ COUNT(*) as num_portfolios
+ FROM ken_portfolios
+ `);
+
+ // Open position cost (capital currently at risk)
+ const { rows: [riskRow] } = await kenQ(`
+ SELECT COALESCE(SUM(cost_cents), 0) as capital_at_risk,
+ COUNT(*) as open_positions
+ FROM ken_portfolio_trades WHERE status = 'open'
+ `);
+
+ // Open position count + today's P&L
+ const { rows: [posRow] } = await kenQ(`
+ SELECT
+ COUNT(*) FILTER (WHERE status = 'open') as open_count,
+ COUNT(DISTINCT market_id) FILTER (WHERE status = 'open') as unique_markets,
+ COALESCE(SUM(pnl_cents) FILTER (WHERE status != 'open' AND resolved_at::date = CURRENT_DATE), 0) as daily_pnl,
+ COALESCE(SUM(pnl_cents) FILTER (WHERE status != 'open'), 0) as total_pnl
+ FROM ken_portfolio_trades
+ `);
+
+ // Recent fills (last 10 resolved trades)
+ const { rows: fills } = await kenQ(`
+ SELECT market_id as ticker, market_title, direction,
+ contracts, entry_price_cents, pnl_cents, status, resolved_at
+ FROM ken_portfolio_trades
+ WHERE status != 'open'
+ ORDER BY resolved_at DESC LIMIT 10
+ `);
+
+ // P&L history — daily totals for last 14 days
+ const { rows: pnlHistory } = await kenQ(`
+ SELECT resolved_at::date as day, SUM(pnl_cents) as daily_pnl
+ FROM ken_portfolio_trades
+ WHERE status != 'open' AND resolved_at > NOW() - INTERVAL '14 days'
+ GROUP BY resolved_at::date
+ ORDER BY day ASC
+ `);
+
+ // Top winning markets
+ const { rows: topMarkets } = await kenQ(`
+ SELECT market_id, market_title,
+ COUNT(*) as total_trades,
+ SUM(CASE WHEN pnl_cents > 0 THEN 1 ELSE 0 END) as wins,
+ SUM(CASE WHEN pnl_cents < 0 THEN 1 ELSE 0 END) as losses,
+ SUM(pnl_cents) as pnl_cents,
+ MODE() WITHIN GROUP (ORDER BY direction) as primary_direction,
+ ROUND(AVG(entry_price_cents)) as avg_entry
+ FROM ken_portfolio_trades
+ WHERE status != 'open'
+ GROUP BY market_id, market_title
+ ORDER BY SUM(pnl_cents) DESC
+ LIMIT 10
+ `);
+
+ // Bottom losing markets
+ const { rows: worstMarkets } = await kenQ(`
+ SELECT market_id, market_title,
+ COUNT(*) as total_trades,
+ SUM(CASE WHEN pnl_cents > 0 THEN 1 ELSE 0 END) as wins,
+ SUM(CASE WHEN pnl_cents < 0 THEN 1 ELSE 0 END) as losses,
+ SUM(pnl_cents) as pnl_cents,
+ MODE() WITHIN GROUP (ORDER BY direction) as primary_direction,
+ ROUND(AVG(entry_price_cents)) as avg_entry
+ FROM ken_portfolio_trades
+ WHERE status != 'open'
+ GROUP BY market_id, market_title
+ HAVING SUM(pnl_cents) < 0
+ ORDER BY SUM(pnl_cents) ASC
+ LIMIT 5
+ `);
+
+ // Top/bottom strategies
+ const { rows: strategies } = await kenQ(`
+ SELECT p.strategy, p.name,
+ p.trades_won, p.trades_lost,
+ (p.total_returned_cents - p.total_invested_cents) as net_pnl_cents,
+ p.balance_cents,
+ ROUND(100.0 * p.trades_won / NULLIF(p.trades_won + p.trades_lost, 0), 1) as win_rate
+ FROM ken_portfolios p
+ WHERE p.total_invested_cents > 0
+ ORDER BY (p.total_returned_cents - p.total_invested_cents) DESC
+ `);
+
+ // Today's stats
+ const { rows: [todayRow] } = await kenQ(`
+ SELECT COUNT(*) as trades,
+ SUM(CASE WHEN pnl_cents > 0 THEN 1 ELSE 0 END) as wins,
+ SUM(CASE WHEN pnl_cents < 0 THEN 1 ELSE 0 END) as losses
+ FROM ken_portfolio_trades
+ WHERE status != 'open' AND resolved_at::date = CURRENT_DATE
+ `);
+
+ // ── Top 3 Best Opportunities Right Now ──
+ // Combine recent high-confidence signals with historical win rates and current market prices
+ const { rows: opportunities } = await kenQ(`
+ WITH recent_signals AS (
+ SELECT DISTINCT ON (market_id)
+ market_id, direction, expected_edge, confidence, reasoning, risk_approved, created_at
+ FROM ken_strategy_signals
+ WHERE created_at > NOW() - INTERVAL '6 hours'
+ ORDER BY market_id, expected_edge DESC
+ ),
+ historical AS (
+ SELECT market_id,
+ COUNT(*) as total_trades,
+ COUNT(*) FILTER (WHERE pnl_cents > 0) as wins,
+ SUM(pnl_cents) as pnl_cents,
+ MODE() WITHIN GROUP (ORDER BY direction) as primary_direction,
+ ROUND(AVG(entry_price_cents)) as avg_entry
+ FROM ken_portfolio_trades
+ WHERE resolved_at IS NOT NULL
+ GROUP BY market_id
+ ),
+ snapshots AS (
+ SELECT DISTINCT ON (ticker)
+ ticker, title, yes_bid, no_bid, volume_24h, last_price
+ FROM ken_market_snapshots
+ WHERE captured_at > NOW() - INTERVAL '2 hours'
+ ORDER BY ticker, captured_at DESC
+ )
+ SELECT
+ s.market_id, COALESCE(snap.title, s.market_id) as title,
+ s.direction, s.expected_edge, s.confidence, s.risk_approved,
+ COALESCE(h.total_trades, 0) as hist_trades,
+ COALESCE(h.wins, 0) as hist_wins,
+ COALESCE(h.pnl_cents, 0) as hist_pnl,
+ COALESCE(h.avg_entry, 0) as avg_entry,
+ snap.yes_bid, snap.no_bid, snap.volume_24h,
+ LEFT(s.reasoning, 200) as reasoning
+ FROM recent_signals s
+ LEFT JOIN historical h ON h.market_id = s.market_id
+ LEFT JOIN snapshots snap ON snap.ticker = s.market_id
+ WHERE s.confidence >= 0.5
+ ORDER BY
+ (s.expected_edge * s.confidence * (1 + COALESCE(h.wins::float / NULLIF(h.total_trades, 0), 0))) DESC
+ LIMIT 3
+ `);
+
+ function edgeDescription(m) {
+ const wr = Number(m.wins) / (Number(m.wins) + Number(m.losses) || 1);
+ const dir = m.primary_direction === 'BUY_NO' ? 'NO' : 'YES';
+ const avg = Number(m.avg_entry);
+ if (wr >= 0.99 && avg >= 90) return `${dir} at ${avg}¢ = near-certain`;
+ if (wr >= 0.95 && avg >= 85) return `${dir} at ${avg}¢, market overprices`;
+ if (wr >= 0.80) return `${dir} side, ${(wr*100).toFixed(0)}% win rate`;
+ if (Number(m.total_trades) >= 150) return `High volume, clear direction`;
+ if (avg >= 80) return `${dir} at ${avg}¢, steady edge`;
+ return `${dir} side, avg ${avg}¢ entry`;
+ }
+
+ json(res, {
+ env: KALSHI_ENV,
+ safe_mode: true,
+ balance: totalBalance,
+ seed_money: seedMoney,
+ net_pnl_from_seed: totalBalance - seedMoney,
+ roi_pct: parseFloat(roi.toFixed(2)),
+ total_invested: totalInvested,
+ total_returned: totalReturned,
+ daily_budget: Number(budgetRow?.total_daily_budget || 0),
+ num_portfolios: Number(budgetRow?.num_portfolios || 0),
+ capital_at_risk: Number(riskRow?.capital_at_risk || 0),
+ open_positions_cost: Number(riskRow?.open_positions || 0),
+ daily_economics: spendRows.map(r => ({
+ day: r.day,
+ trades: Number(r.trades),
+ wins: Number(r.wins),
+ losses: Number(r.losses),
+ net_pnl: Number(r.net_pnl),
+ gross_wins: Number(r.gross_wins),
+ gross_losses: Number(r.gross_losses),
+ capital_deployed: Number(r.capital_deployed),
+ })),
+ position_count: Number(posRow?.open_count || 0),
+ open_orders: Number(posRow?.unique_markets || 0),
+ daily_pnl: Number(posRow?.daily_pnl || 0),
+ total_pnl: Number(posRow?.total_pnl || 0),
+ markets_tracked: cachedActiveMarkets.length,
+ today_trades: Number(todayRow?.trades || 0),
+ today_wins: Number(todayRow?.wins || 0),
+ today_losses: Number(todayRow?.losses || 0),
+ recent_fills: fills.map(f => ({
+ ticker: f.ticker,
+ title: f.market_title,
+ side: f.direction === 'BUY_YES' ? 'yes' : 'no',
+ count: f.contracts,
+ yes_price: f.entry_price_cents,
+ pnl: f.pnl_cents,
+ status: f.status,
+ })),
+ pnl_history: pnlHistory.map(p => Number(p.daily_pnl) / 100),
+ top_markets: topMarkets.map(m => {
+ const t = m.market_id || '';
+ const et = t.replace(/-[^-]+$/, '') || t;
+ const st = et.replace(/-[^-]+$/, '') || et;
+ return {
+ ticker: m.market_id,
+ title: m.market_title,
+ trades: Number(m.total_trades),
+ wins: Number(m.wins),
+ losses: Number(m.losses),
+ pnl: Number(m.pnl_cents),
+ edge: edgeDescription(m),
+ url: `https://kalshi.com/markets/${st.toLowerCase()}/${et.toLowerCase()}`,
+ }; }),
+ worst_markets: worstMarkets.map(m => {
+ const t = m.market_id || '';
+ const et = t.replace(/-[^-]+$/, '') || t;
+ const st = et.replace(/-[^-]+$/, '') || et;
+ return {
+ ticker: m.market_id,
+ title: m.market_title,
+ trades: Number(m.total_trades),
+ wins: Number(m.wins),
+ losses: Number(m.losses),
+ pnl: Number(m.pnl_cents),
+ edge: edgeDescription(m),
+ url: `https://kalshi.com/markets/${st.toLowerCase()}/${et.toLowerCase()}`,
+ }; }),
+ strategies: strategies.map(s => ({
+ name: s.name,
+ strategy: s.strategy,
+ wins: Number(s.trades_won),
+ losses: Number(s.trades_lost),
+ pnl: Number(s.net_pnl_cents),
+ balance: Number(s.balance_cents),
+ win_rate: Number(s.win_rate || 0),
+ })),
+ top_opportunities: opportunities.map(o => {
+ const wr = Number(o.hist_trades) > 0 ? Number(o.hist_wins) / Number(o.hist_trades) : null;
+ const dir = o.direction === 'BUY_NO' ? 'NO' : 'YES';
+ const edge = (parseFloat(o.expected_edge) * 100).toFixed(1);
+ const conf = (parseFloat(o.confidence) * 100).toFixed(0);
+ const yesBid = Number(o.yes_bid || 0);
+ const noBid = Number(o.no_bid || 0);
+ const price = o.direction === 'BUY_NO' ? noBid : yesBid;
+ // Build human-readable "why" from signal reasoning
+ const rawReasoning = o.reasoning || '';
+ const reasoningClean = rawReasoning.replace(/^BUY_(YES|NO) on "[^"]*"\s*—\s*/, '');
+ return {
+ ticker: o.market_id,
+ title: o.title,
+ direction: dir,
+ edge_pct: edge,
+ confidence: conf,
+ price_cents: price,
+ hist_trades: Number(o.hist_trades),
+ hist_wins: Number(o.hist_wins),
+ hist_wr: wr !== null ? (wr * 100).toFixed(1) : null,
+ hist_pnl: Number(o.hist_pnl),
+ volume_24h: Number(o.volume_24h || 0),
+ risk_approved: o.risk_approved,
+ why: reasoningClean,
+ url: (() => { const t = o.market_id || ''; const et = t.replace(/-[^-]+$/, '') || t; const st = et.replace(/-[^-]+$/, '') || et; return `https://kalshi.com/markets/${st.toLowerCase()}/${et.toLowerCase()}`; })(),
+ };
+ }),
+ });
+ } catch (err) {
+ json(res, { error: err.message }, 500);
+ }
+ },
+
+ // ════════════════════════════════════════
+ // SCAN CONFIG (User-adjustable intervals + risk params)
+ // ════════════════════════════════════════
+
+ 'GET /api/scan-config': async (req, res) => {
+ json(res, {
+ scan_interval_ms: SCAN_INTERVAL_MS,
+ signal_pipeline_ms: SIGNAL_PIPELINE_MS,
+ reddit_interval_ms: REDDIT_INTERVAL_MS,
+ resolve_interval_ms: RESOLVE_INTERVAL_MS,
+ min_edge_threshold: RISK_LIMITS.minEdgeThreshold,
+ min_liquidity: RISK_LIMITS.minLiquidity,
+ cached_markets: cachedActiveMarkets.length,
+ });
+ },
+
+ 'POST /api/scan-config': async (req, res) => {
+ try {
+ const body = await readBody(req);
+ let changed = false;
+ if (body.scan_interval_ms !== undefined) { SCAN_INTERVAL_MS = Math.max(60000, Math.min(3600000, Number(body.scan_interval_ms))); changed = true; }
+ if (body.signal_pipeline_ms !== undefined) { SIGNAL_PIPELINE_MS = Math.max(30000, Math.min(1800000, Number(body.signal_pipeline_ms))); changed = true; }
+ if (body.reddit_interval_ms !== undefined) { REDDIT_INTERVAL_MS = Math.max(60000, Math.min(3600000, Number(body.reddit_interval_ms))); changed = true; }
+ if (body.resolve_interval_ms !== undefined) { RESOLVE_INTERVAL_MS = Math.max(30000, Math.min(1800000, Number(body.resolve_interval_ms))); changed = true; }
+ if (body.min_edge_threshold !== undefined) { RISK_LIMITS.minEdgeThreshold = Math.max(0.005, Math.min(0.50, Number(body.min_edge_threshold))); changed = true; }
+ if (body.min_liquidity !== undefined) { RISK_LIMITS.minLiquidity = Math.max(0, Math.min(10000, Number(body.min_liquidity))); changed = true; }
+ if (changed) {
+ await saveScanConfig();
+ restartIntervals();
+ }
+ json(res, {
+ success: true,
+ scan_interval_ms: SCAN_INTERVAL_MS,
+ signal_pipeline_ms: SIGNAL_PIPELINE_MS,
+ reddit_interval_ms: REDDIT_INTERVAL_MS,
+ resolve_interval_ms: RESOLVE_INTERVAL_MS,
+ min_edge_threshold: RISK_LIMITS.minEdgeThreshold,
+ min_liquidity: RISK_LIMITS.minLiquidity,
+ cached_markets: cachedActiveMarkets.length,
+ });
+ } catch (err) {
+ json(res, { error: err.message }, 500);
+ }
+ },
+
+ // ════════════════════════════════════════
+ // MEMORY / SYSTEM STATUS
+ // ════════════════════════════════════════
+
+ 'GET /api/system': async (req, res) => {
+ const mem = process.memoryUsage();
+ json(res, {
+ memory: {
+ rss_mb: Math.round(mem.rss / 1024 / 1024),
+ heapUsed_mb: Math.round(mem.heapUsed / 1024 / 1024),
+ heapTotal_mb: Math.round(mem.heapTotal / 1024 / 1024),
+ external_mb: Math.round(mem.external / 1024 / 1024),
+ },
+ uptime_hours: Math.round(process.uptime() / 3600 * 10) / 10,
+ env: KALSHI_ENV,
+ cachedMarkets: cachedActiveMarkets.length,
+ pid: process.pid,
+ cpuCores: os.cpus().length,
+ enhancements: {
+ monteCarloIterations: 15000,
+ geminiModel: GEMINI_MODEL,
+ geminiCallsToday: geminiCallCount,
+ geminiDailyLimit: GEMINI_DAILY_LIMIT,
+ scanInterval: '8m',
+ signalPipeline: '2m',
+ redditInterval: '15m',
+ momentumCacheSize: Object.keys(cachedMomentumMap).length,
+ },
+ });
+ },
+
+ // ── Portfolios API ──
+ 'GET /api/portfolios': async (req, res) => {
+ try {
+ const { rows: portfolios } = await kenQ(`SELECT * FROM ken_portfolios ORDER BY id`);
+ // Get today's trade counts per portfolio
+ for (const pf of portfolios) {
+ const { rows: today } = await kenQ(`
+ SELECT COUNT(*) as trades_today, COALESCE(SUM(cost_cents),0) as spent_today
+ FROM ken_portfolio_trades WHERE portfolio_id = $1 AND created_at::date = CURRENT_DATE
+ `, [pf.id]);
+ pf.trades_today = parseInt(today[0]?.trades_today) || 0;
+ pf.spent_today = parseInt(today[0]?.spent_today) || 0;
+ pf.budget_remaining = Math.max(0, pf.balance_cents); // Remaining = whatever balance is left
+
+ // Win rate
+ const totalResolved = pf.trades_won + pf.trades_lost + pf.trades_expired;
+ pf.win_rate = totalResolved > 0 ? Math.round(pf.trades_won / totalResolved * 100) : 0;
+ pf.total_resolved = totalResolved;
+ pf.is_bankrupt = pf.balance_cents <= 0;
+ }
+ // Sort: active portfolios by ROI (best first), bankrupt portfolios at bottom
+ portfolios.sort((a, b) => {
+ if (a.is_bankrupt !== b.is_bankrupt) return a.is_bankrupt ? 1 : -1;
+ const aROI = a.total_invested_cents > 0 ? (a.total_returned_cents - a.total_invested_cents) / a.total_invested_cents : 0;
+ const bROI = b.total_invested_cents > 0 ? (b.total_returned_cents - b.total_invested_cents) / b.total_invested_cents : 0;
+ return bROI - aROI;
+ });
+ json(res, portfolios);
+ } catch(e) { json(res, { error: e.message }, 500); }
+ },
+
+ 'GET /api/portfolio-trades': async (req, res) => {
+ try {
+ const url = new URL(req.url, 'http://x');
+ const pfId = url.searchParams.get('portfolio_id');
+ const status = url.searchParams.get('status');
+ let q = `SELECT * FROM ken_portfolio_trades`;
+ const params = [];
+ const conds = [];
+ if (pfId) { conds.push(`portfolio_id = $${params.length+1}`); params.push(pfId); }
+ if (status) { conds.push(`status = $${params.length+1}`); params.push(status); }
+ if (conds.length) q += ' WHERE ' + conds.join(' AND ');
+ q += ' ORDER BY created_at DESC LIMIT 200';
+ const { rows } = await kenQ(q, params);
+ json(res, rows);
+ } catch(e) { json(res, { error: e.message }, 500); }
+ },
+
+ // ── PortFAUXlio Charts API — time-series NAV data ──
+ 'GET /api/portfauxlio/charts': async (req, res) => {
+ try {
+ const url = new URL(req.url, 'http://x');
+ const period = url.searchParams.get('period') || '7d';
+ const intervals = { '1d': '1 day', '3d': '3 days', '7d': '7 days', '14d': '14 days', '30d': '30 days' };
+ const interval = intervals[period] || '7 days';
+
+ // Snapshots (intraday)
+ const { rows: snapRows } = await kenQ(`
+ SELECT s.portfolio_id, s.nav_cents, s.open_positions, s.snapshot_at, p.name, p.strategy
+ FROM ken_portfolio_snapshots s JOIN ken_portfolios p ON p.id = s.portfolio_id
+ WHERE s.snapshot_at > NOW() - INTERVAL '${interval}' ORDER BY s.portfolio_id, s.snapshot_at ASC
+ `);
+
+ // Daily P&L (longer-term)
+ const { rows: dailyRows } = await kenQ(`
+ SELECT dp.portfolio_id, dp.date, dp.daily_pnl_cents, dp.cumulative_pnl_cents,
+ dp.wins, dp.losses, dp.closed_trades, p.name, p.strategy
+ FROM ken_daily_pnl dp JOIN ken_portfolios p ON p.id = dp.portfolio_id
+ WHERE dp.date > CURRENT_DATE - INTERVAL '${interval}' ORDER BY dp.portfolio_id, dp.date ASC
+ `);
+
+ const byPortfolio = {};
+ for (const r of snapRows) {
+ if (!byPortfolio[r.portfolio_id]) byPortfolio[r.portfolio_id] = { id: r.portfolio_id, name: r.name, strategy: r.strategy, snapshots: [], daily: [] };
+ byPortfolio[r.portfolio_id].snapshots.push({ nav: r.nav_cents, openPositions: r.open_positions, time: r.snapshot_at });
+ }
+ for (const r of dailyRows) {
+ if (!byPortfolio[r.portfolio_id]) byPortfolio[r.portfolio_id] = { id: r.portfolio_id, name: r.name, strategy: r.strategy, snapshots: [], daily: [] };
+ byPortfolio[r.portfolio_id].daily.push({ date: r.date, pnl: r.daily_pnl_cents, cumulative: r.cumulative_pnl_cents, wins: r.wins, losses: r.losses, trades: r.closed_trades });
+ }
+
+ json(res, { portfolios: Object.values(byPortfolio), period });
+ } catch (e) { json(res, { error: e.message }, 500); }
+ },
+
+ // ── PortFAUXlio SWOT — trades with strengths/weaknesses/opportunities/threats ──
+ 'GET /api/portfauxlio/swot': async (req, res) => {
+ try {
+ const { rows: trades } = await kenQ(`
+ SELECT t.id, t.market_id, t.market_title, t.direction, t.entry_price_cents,
+ t.contracts, t.cost_cents, t.status, t.pnl_cents, t.reasoning,
+ t.confidence, t.ai_enhanced, t.mc_consistent, t.created_at, t.resolved_at,
+ p.name AS portfolio_name, p.strategy, p.id AS portfolio_id
+ FROM ken_portfolio_trades t JOIN ken_portfolios p ON p.id = t.portfolio_id
+ WHERE t.created_at > NOW() - INTERVAL '7 days'
+ ORDER BY t.created_at DESC LIMIT 200
+ `);
+
+ // Group by market
+ const byMarket = {};
+ for (const t of trades) {
+ if (!byMarket[t.market_id]) byMarket[t.market_id] = { market_id: t.market_id, title: t.market_title || t.market_id, trades: [], totalCost: 0, totalPnl: 0, models: new Set() };
+ const m = byMarket[t.market_id];
+ m.trades.push(t);
+ m.totalCost += parseInt(t.cost_cents) || 0;
+ m.totalPnl += parseInt(t.pnl_cents) || 0;
+ m.models.add(t.portfolio_name);
+ }
+
+ // Generate SWOT for each market group
+ const swotMarkets = Object.values(byMarket).map(m => {
+ const t0 = m.trades[0];
+ const conf = parseFloat(t0.confidence) || 0;
+ const aiCount = m.trades.filter(t => t.ai_enhanced).length;
+ const mcCount = m.trades.filter(t => t.mc_consistent).length;
+ const totalT = m.trades.length;
+ const openCount = m.trades.filter(t => t.status === 'open').length;
+ const reasoning = t0.reasoning || '';
+
+ // Parse edge from reasoning
+ const edgeMatch = reasoning.match(/edge\s*([\d.]+)%/i);
+ const edge = edgeMatch ? parseFloat(edgeMatch[1]) : 0;
+ const mcMatch = reasoning.match(/MC:\s*\u03bc=([\d.]+)%\s*\u00b1\s*([\d.]+)%/);
+ const mcMean = mcMatch ? parseFloat(mcMatch[1]) : 0;
+ const mcStd = mcMatch ? parseFloat(mcMatch[2]) : 0;
+ const artMatch = reasoning.match(/(\d+)\s*articles?/i);
+ const articles = artMatch ? parseInt(artMatch[1]) : 0;
+ const agreeMatch = reasoning.match(/Agreement:\s*([\d.]+)%/i);
+ const agreement = agreeMatch ? parseFloat(agreeMatch[1]) : 0;
+
+ // SWOT generation
+ const strengths = [];
+ const weaknesses = [];
+ const opportunities = [];
+ const threats = [];
+
+ // Strengths
+ if (conf >= 0.6) strengths.push('High confidence (' + Math.round(conf * 100) + '%)');
+ if (mcCount > totalT * 0.5) strengths.push('Monte Carlo validated (' + mcCount + '/' + totalT + ' models)');
+ if (aiCount > 0) strengths.push('AI enhanced signals');
+ if (totalT >= 3) strengths.push('Multi-model consensus (' + totalT + ' models agree)');
+ if (agreement >= 80) strengths.push('Strong news agreement (' + agreement + '%)');
+ if (articles >= 3) strengths.push('Strong news coverage (' + articles + ' articles)');
+ if (edge >= 15) strengths.push('Large statistical edge (' + edge.toFixed(1) + '%)');
+ if (strengths.length === 0) strengths.push('Active position in play');
+
+ // Weaknesses
+ if (conf < 0.4) weaknesses.push('Low confidence (' + Math.round(conf * 100) + '%)');
+ if (mcCount === 0) weaknesses.push('No Monte Carlo validation');
+ if (aiCount === 0) weaknesses.push('No AI enhancement');
+ if (articles <= 1) weaknesses.push('Limited news coverage (' + articles + ' article' + (articles === 1 ? '' : 's') + ')');
+ if (edge < 5 && edge > 0) weaknesses.push('Narrow edge (' + edge.toFixed(1) + '%)');
+ if (mcStd > 10) weaknesses.push('High MC uncertainty (\u00b1' + mcStd.toFixed(1) + '%)');
+ if (weaknesses.length === 0) weaknesses.push('No significant weaknesses identified');
+
+ // Opportunities
+ if (edge >= 8) opportunities.push('Exploitable edge of ' + edge.toFixed(1) + '%');
+ if (m.models.size >= 5) opportunities.push(m.models.size + ' models see opportunity');
+ if (mcMean > edge) opportunities.push('MC mean (' + mcMean.toFixed(1) + '%) exceeds raw edge');
+ if (openCount > 0) opportunities.push(openCount + ' open position' + (openCount > 1 ? 's' : '') + ' tracking');
+ if (opportunities.length === 0) opportunities.push('Market exposure maintained');
+
+ // Threats
+ if (mcStd > 8) threats.push('High volatility (MC \u00b1' + mcStd.toFixed(1) + '%)');
+ if (agreement < 60 && agreement > 0) threats.push('Mixed news sentiment (' + agreement + '% agreement)');
+ if (m.totalPnl < 0) threats.push('Currently underwater ($' + (Math.abs(m.totalPnl) / 100).toFixed(2) + ' loss)');
+ const direction = t0.direction;
+ if (direction === 'BUY_YES' && edge < 10) threats.push('Thin YES margin — small price move could flip');
+ if (direction === 'BUY_NO' && conf < 0.5) threats.push('NO position with uncertain conviction');
+ if (threats.length === 0) threats.push('Standard market risk');
+
+ return {
+ market_id: m.market_id,
+ title: m.title,
+ direction: t0.direction,
+ edge,
+ confidence: conf,
+ articles,
+ agreement,
+ mc_mean: mcMean,
+ mc_std: mcStd,
+ model_count: totalT,
+ models: [...m.models],
+ open_count: openCount,
+ total_cost: m.totalCost,
+ total_pnl: m.totalPnl,
+ entry_price: parseInt(t0.entry_price_cents) || 0,
+ first_trade: m.trades[m.trades.length - 1]?.created_at,
+ reasoning: reasoning.substring(0, 200),
+ swot: { strengths, weaknesses, opportunities, threats },
+ trades: m.trades.map(t => ({
+ id: t.id, portfolio: t.portfolio_name, strategy: t.strategy,
+ direction: t.direction, contracts: t.contracts,
+ cost: parseInt(t.cost_cents) || 0, pnl: parseInt(t.pnl_cents) || 0,
+ status: t.status, created_at: t.created_at
+ }))
+ };
+ });
+
+ // Sort by model count desc (most consensus first)
+ swotMarkets.sort((a, b) => b.model_count - a.model_count);
+
+ json(res, { markets: swotMarkets, total_trades: trades.length });
+ } catch (e) { json(res, { error: e.message }, 500); }
+ },
+
+ // ── Weekly Tournament System — survive or die ──
+ 'GET /api/tournament/current': async (req, res) => {
+ try {
+ const { rows: [tourney] } = await kenQ(`SELECT * FROM ken_weekly_tournaments WHERE status = 'active' ORDER BY id DESC LIMIT 1`);
+ if (!tourney) return json(res, { active: false, message: 'No active tournament' });
+ const { rows: entries } = await kenQ(`
+ SELECT e.*, p.name, p.strategy, p.balance_cents, p.total_invested_cents, p.total_returned_cents,
+ p.trades_won, p.trades_lost, p.daily_budget_cents
+ FROM ken_tournament_entries e JOIN ken_portfolios p ON p.id = e.portfolio_id
+ WHERE e.tournament_id = $1 ORDER BY e.pnl_cents DESC NULLS LAST
+ `, [tourney.id]);
+ // Compute live P&L for each entry
+ for (const e of entries) {
+ const { rows: [stats] } = await kenQ(`
+ SELECT COUNT(*) as trades, COALESCE(SUM(cost_cents),0) as total_cost,
+ COALESCE(SUM(CASE WHEN status IN ('won','lost','closed') THEN pnl_cents ELSE 0 END),0) as realized_pnl
+ FROM ken_portfolio_trades WHERE portfolio_id = $1 AND created_at >= $2
+ `, [e.portfolio_id, tourney.week_start]);
+ e.live_trades = parseInt(stats.trades) || 0;
+ e.live_invested = parseInt(stats.total_cost) || 0;
+ e.live_pnl = parseInt(stats.realized_pnl) || 0;
+ }
+ json(res, { active: true, tournament: tourney, entries });
+ } catch (e) { json(res, { error: e.message }, 500); }
+ },
+
+ 'POST /api/tournament/start': async (req, res) => {
+ try {
+ const body = await readBody(req);
+ const portfolioIds = body.portfolio_ids || [];
+ const budgetCents = body.budget_cents || 2000; // $20 default
+ const notes = body.notes || '';
+ const weeks = body.weeks || 1;
+ if (portfolioIds.length < 1 || portfolioIds.length > 10) return json(res, { error: 'Pick 1-10 portfolios' }, 400);
+ // Check no active tournament
+ const { rows: active } = await kenQ(`SELECT id FROM ken_weekly_tournaments WHERE status = 'active'`);
+ if (active.length > 0) return json(res, { error: 'Tournament already active. Evaluate or cancel it first.', active_id: active[0].id }, 400);
+ const weekStart = new Date(); weekStart.setHours(0,0,0,0);
+ const weekEnd = new Date(weekStart); weekEnd.setDate(weekEnd.getDate() + 7 * weeks);
+ const { rows: [tourney] } = await kenQ(`
+ INSERT INTO ken_weekly_tournaments (week_start, week_end, budget_per_portfolio_cents, notes)
+ VALUES ($1, $2, $3, $4) RETURNING *
+ `, [weekStart.toISOString().split('T')[0], weekEnd.toISOString().split('T')[0], budgetCents, notes]);
+ const entries = [];
+ for (const pid of portfolioIds) {
+ const { rows: [pf] } = await kenQ(`SELECT * FROM ken_portfolios WHERE id = $1`, [pid]);
+ if (!pf) continue;
+ // Set portfolio budget for the tournament
+ await kenQ(`UPDATE ken_portfolios SET daily_budget_cents = $1, balance_cents = $2 WHERE id = $3`, [Math.round(budgetCents / 7), budgetCents, pid]);
+ const { rows: [entry] } = await kenQ(`
+ INSERT INTO ken_tournament_entries (tournament_id, portfolio_id, start_balance_cents, status)
+ VALUES ($1, $2, $3, 'alive') RETURNING *
+ `, [tourney.id, pid, budgetCents]);
+ entries.push({ ...entry, name: pf.name, strategy: pf.strategy });
+ }
+ json(res, { tournament: tourney, entries, message: `Tournament started with ${entries.length} portfolios at $${(budgetCents/100).toFixed(2)} each` });
+ } catch (e) { json(res, { error: e.message }, 500); }
+ },
+
+ 'POST /api/tournament/evaluate': async (req, res) => {
+ try {
+ const { rows: [tourney] } = await kenQ(`SELECT * FROM ken_weekly_tournaments WHERE status = 'active' ORDER BY id DESC LIMIT 1`);
+ if (!tourney) return json(res, { error: 'No active tournament' }, 400);
+ const { rows: entries } = await kenQ(`
+ SELECT e.*, p.name, p.strategy FROM ken_tournament_entries e
+ JOIN ken_portfolios p ON p.id = e.portfolio_id WHERE e.tournament_id = $1
+ `, [tourney.id]);
+ const results = [];
+ for (const e of entries) {
+ const { rows: [stats] } = await kenQ(`
+ SELECT COUNT(*) as trades,
+ COALESCE(SUM(CASE WHEN status='won' THEN payout_cents - cost_cents WHEN status='lost' THEN -cost_cents ELSE 0 END),0) as pnl
+ FROM ken_portfolio_trades WHERE portfolio_id = $1 AND created_at >= $2
+ `, [e.portfolio_id, tourney.week_start]);
+ const pnl = parseInt(stats.pnl) || 0;
+ const trades = parseInt(stats.trades) || 0;
+ const survived = pnl >= 0;
+ await kenQ(`UPDATE ken_tournament_entries SET end_balance_cents = $1, pnl_cents = $2, trades_count = $3, status = $4, elimination_reason = $5 WHERE id = $6`,
+ [e.start_balance_cents + pnl, pnl, trades, survived ? 'survived' : 'eliminated', survived ? null : `Lost $${(Math.abs(pnl)/100).toFixed(2)}`, e.id]);
+ if (!survived) await kenQ(`UPDATE ken_portfolios SET daily_budget_cents = 0 WHERE id = $1`, [e.portfolio_id]);
+ results.push({ name: e.name, strategy: e.strategy, pnl_cents: pnl, trades, status: survived ? 'SURVIVED' : 'ELIMINATED' });
+ }
+ await kenQ(`UPDATE ken_weekly_tournaments SET status = 'completed' WHERE id = $1`, [tourney.id]);
+ const survivors = results.filter(r => r.status === 'SURVIVED');
+ const eliminated = results.filter(r => r.status === 'ELIMINATED');
+ json(res, { tournament_id: tourney.id, results, survivors: survivors.length, eliminated: eliminated.length, message: `${survivors.length} survived, ${eliminated.length} eliminated` });
+ } catch (e) { json(res, { error: e.message }, 500); }
+ },
+
+ 'POST /api/tournament/cancel': async (req, res) => {
+ try {
+ const { rows: [tourney] } = await kenQ(`SELECT * FROM ken_weekly_tournaments WHERE status = 'active' ORDER BY id DESC LIMIT 1`);
+ if (!tourney) return json(res, { error: 'No active tournament' }, 400);
+ await kenQ(`UPDATE ken_weekly_tournaments SET status = 'cancelled' WHERE id = $1`, [tourney.id]);
+ await kenQ(`UPDATE ken_tournament_entries SET status = 'cancelled' WHERE tournament_id = $1`, [tourney.id]);
+ json(res, { message: 'Tournament cancelled', id: tourney.id });
+ } catch (e) { json(res, { error: e.message }, 500); }
+ },
+
+ 'GET /api/tournament/history': async (req, res) => {
+ try {
+ const { rows: tournaments } = await kenQ(`SELECT * FROM ken_weekly_tournaments ORDER BY id DESC LIMIT 20`);
+ for (const t of tournaments) {
+ const { rows: entries } = await kenQ(`
+ SELECT e.*, p.name, p.strategy FROM ken_tournament_entries e
+ JOIN ken_portfolios p ON p.id = e.portfolio_id WHERE e.tournament_id = $1 ORDER BY e.pnl_cents DESC NULLS LAST
+ `, [t.id]);
+ t.entries = entries;
+ }
+ json(res, tournaments);
+ } catch (e) { json(res, { error: e.message }, 500); }
+ },
+
+ // ── PortFAUXlio Dashboard API — full simulated trading view ──
+ 'GET /api/portfauxlio': async (req, res) => {
+ try {
+ // 1. All portfolios with computed stats
+ const { rows: portfolios } = await kenQ(`
+ SELECT p.*,
+ (p.total_returned_cents - p.total_invested_cents) AS pnl_cents,
+ CASE WHEN p.total_invested_cents > 0
+ THEN ROUND((p.total_returned_cents - p.total_invested_cents)::numeric / p.total_invested_cents * 100, 1)
+ ELSE 0 END AS roi_pct,
+ (p.trades_won + p.trades_lost + p.trades_expired) AS resolved_trades,
+ CASE WHEN (p.trades_won + p.trades_lost) > 0
+ THEN ROUND(p.trades_won::numeric / (p.trades_won + p.trades_lost) * 100, 0)
+ ELSE 0 END AS win_rate
+ FROM ken_portfolios p ORDER BY (p.total_returned_cents - p.total_invested_cents) DESC
+ `);
+
+ // 2. All active (open) trades across all portfolios
+ const { rows: activeTrades } = await kenQ(`
+ SELECT t.id, t.portfolio_id, t.market_id, t.market_title, t.direction,
+ t.contracts, t.entry_price_cents, t.cost_cents, t.confidence, t.created_at,
+ p.name AS portfolio_name, p.strategy
+ FROM ken_portfolio_trades t
+ JOIN ken_portfolios p ON p.id = t.portfolio_id
+ WHERE t.status = 'open'
+ ORDER BY t.created_at DESC
+ `);
+
+ // 3. Trade history (all trades, most recent first)
+ const { rows: tradeHistory } = await kenQ(`
+ SELECT t.id, t.portfolio_id, t.market_id, t.market_title, t.direction,
+ t.contracts, t.entry_price_cents, t.cost_cents, t.pnl_cents, t.status,
+ t.confidence, t.created_at, t.resolved_at,
+ p.name AS portfolio_name, p.strategy
+ FROM ken_portfolio_trades t
+ JOIN ken_portfolios p ON p.id = t.portfolio_id
+ ORDER BY t.created_at DESC LIMIT 200
+ `);
+
+ // 4. Per-model trade distribution: which markets each strategy traded
+ const { rows: modelMarkets } = await kenQ(`
+ SELECT p.strategy, t.market_id,
+ COUNT(*) AS trade_count,
+ SUM(t.cost_cents) AS total_cost,
+ MAX(t.created_at) AS last_trade
+ FROM ken_portfolio_trades t
+ JOIN ken_portfolios p ON p.id = t.portfolio_id
+ GROUP BY p.strategy, t.market_id
+ ORDER BY p.strategy, trade_count DESC
+ `);
+
+ // 5. Overlap analysis: markets traded by 3+ strategies
+ const { rows: overlaps } = await kenQ(`
+ SELECT t.market_id,
+ COUNT(DISTINCT p.strategy) AS num_strategies,
+ ARRAY_AGG(DISTINCT p.name ORDER BY p.name) AS portfolios,
+ SUM(t.cost_cents) AS total_exposure
+ FROM ken_portfolio_trades t
+ JOIN ken_portfolios p ON p.id = t.portfolio_id
+ GROUP BY t.market_id
+ HAVING COUNT(DISTINCT p.strategy) >= 2
+ ORDER BY num_strategies DESC
+ `);
+
+ // 6. Summary stats
+ const totalInvested = portfolios.reduce((s, p) => s + (parseInt(p.total_invested_cents) || 0), 0);
+ const totalReturned = portfolios.reduce((s, p) => s + (parseInt(p.total_returned_cents) || 0), 0);
+ const totalTrades = tradeHistory.length;
+ const openTrades = activeTrades.length;
+ const uniqueMarkets = [...new Set(tradeHistory.map(t => t.market_id))].length;
+
+ json(res, {
+ portfolios,
+ activeTrades,
+ tradeHistory,
+ modelMarkets,
+ overlaps,
+ summary: {
+ totalInvested, totalReturned,
+ totalPnl: totalReturned - totalInvested,
+ totalTrades, openTrades, uniqueMarkets,
+ activeModels: portfolios.filter(p => parseInt(p.total_invested_cents) > 0).length,
+ }
+ });
+ } catch(e) { json(res, { error: e.message }, 500); }
+ },
+
+ 'GET /api/predictions-history': async (req, res) => {
+ try {
+ const { rows } = await kenQ(`
+ SELECT id, ticker, title, signal_type, side, confidence, entry_price, exit_price,
+ edge_bps, outcome, pnl_cents, reasoning, created_at, resolved_at
+ FROM ken_predictions
+ WHERE outcome != 'pending'
+ ORDER BY resolved_at DESC NULLS LAST
+ LIMIT 100
+ `);
+ // Also get stats
+ const { rows: stats } = await kenQ(`
+ SELECT outcome, COUNT(*) as cnt, ROUND(AVG(pnl_cents),1) as avg_pnl,
+ ROUND(AVG(confidence),1) as avg_conf
+ FROM ken_predictions WHERE outcome != 'pending'
+ GROUP BY outcome
+ `);
+ json(res, { predictions: rows, stats });
+ } catch(e) { json(res, { error: e.message }, 500); }
+ },
+
+ 'GET /api/daily-pnl': async (req, res) => {
+ try {
+ const { rows } = await kenQ(`
+ SELECT dp.*, p.name as portfolio_name
+ FROM ken_daily_pnl dp
+ JOIN ken_portfolios p ON p.id = dp.portfolio_id
+ ORDER BY dp.date DESC, dp.portfolio_id
+ LIMIT 200
+ `);
+ json(res, rows);
+ } catch(e) { json(res, { error: e.message }, 500); }
+ },
+
+ // ── Heating & Weather Intelligence API ──
+ 'GET /api/heating-intel': async (req, res) => {
+ try {
+ const { rows: posts } = await kenQ(`
+ SELECT source, subreddit as area, keyword, post_title as title, post_url as url,
+ score, sentiment_score, raw_text, captured_at
+ FROM ken_sentiment
+ WHERE source IN ('heating_intel', 'noaa_alert', 'noaa_forecast')
+ ORDER BY captured_at DESC
+ LIMIT 50
+ `);
+ const { rows: stats } = await kenQ(`
+ SELECT source, COUNT(*) as cnt,
+ ROUND(AVG(sentiment_score)::numeric, 2) as avg_sentiment,
+ ROUND(AVG(score)::numeric, 0) as avg_score
+ FROM ken_sentiment
+ WHERE source IN ('heating_intel', 'noaa_alert', 'noaa_forecast')
+ AND captured_at > NOW() - INTERVAL '7 days'
+ GROUP BY source
+ `);
+ json(res, { posts, stats, keywords: HEATING_KEYWORDS });
+ } catch(e) { json(res, { error: e.message }, 500); }
+ },
+
+ // ── Ken Inc Command Center API ──
+ 'GET /api/inc': async (req, res) => {
+ const mem = process.memoryUsage();
+ // Get recent signals
+ let recentSignals = [];
+ try {
+ const { rows } = await kenQ(`SELECT market_id, direction, expected_edge, confidence, reasoning, risk_approved, created_at
+ FROM ken_strategy_signals ORDER BY created_at DESC LIMIT 20`);
+ recentSignals = rows;
+ } catch(e) {}
+
+ // Get pipeline stats
+ let pipelineStats = {};
+ try {
+ const { rows } = await kenQ(`SELECT COUNT(*) as total_signals,
+ COUNT(*) FILTER (WHERE risk_approved = true) as approved,
+ COUNT(*) FILTER (WHERE created_at > NOW() - INTERVAL '1 hour') as last_hour,
+ AVG(ABS(expected_edge::numeric)) as avg_edge,
+ MAX(confidence::numeric) as max_confidence
+ FROM ken_strategy_signals WHERE created_at > NOW() - INTERVAL '24 hours'`);
+ pipelineStats = rows[0] || {};
+ } catch(e) {}
+
+ // Sentiment stats
+ let sentimentStats = {};
+ try {
+ const { rows } = await kenQ(`SELECT COUNT(*) as total_articles,
+ COUNT(DISTINCT source) as unique_sources,
+ AVG(sentiment_score) as avg_sentiment
+ FROM ken_sentiment WHERE captured_at > NOW() - INTERVAL '24 hours'`);
+ sentimentStats = rows[0] || {};
+ } catch(e) {}
+
+ // Market snapshot stats
+ let marketStats = {};
+ try {
+ const { rows } = await kenQ(`SELECT COUNT(DISTINCT ticker) as tracked_markets
+ FROM ken_market_snapshots WHERE captured_at > NOW() - INTERVAL '24 hours'`);
+ marketStats = rows[0] || {};
+ } catch(e) {}
+
+ // Build sub-agent status
+ const subAgents = [
+ {
+ id: 'scout', name: 'Scout', role: 'Intelligence Gatherer', emoji: '🔍',
+ color: '#3B82F6', status: 'active',
+ desc: 'Sweeps 77 subreddits, 71 RSS feeds, HN, YouTube, Bluesky, Mastodon, Discord',
+ stats: { articles24h: parseInt(sentimentStats.total_articles) || 0, sources: parseInt(sentimentStats.unique_sources) || 0 },
+ skills: ['Reddit Scraping', 'RSS Feeds', 'Social Media', 'GDELT TV', 'YouTube', 'Lemmy', 'Lobsters'],
+ },
+ {
+ id: 'oracle', name: 'Oracle', role: 'Monte Carlo Engine', emoji: '🎲',
+ color: '#8B5CF6', status: 'active',
+ desc: 'Runs 15,000 iteration Monte Carlo simulations on every signal for probability validation',
+ stats: { iterations: 15000, cores: os.cpus().length, momentumTracked: Object.keys(cachedMomentumMap).length },
+ skills: ['Monte Carlo Simulation', 'Bayesian Inference', 'Ensemble Probability', 'Confidence Intervals'],
+ },
+ {
+ id: 'gemini', name: 'Nova', role: 'AI Analyst', emoji: '🧠',
+ color: '#EC4899', status: geminiCallCount < GEMINI_DAILY_LIMIT ? 'active' : 'rate_limited',
+ desc: 'Gemini 2.0 Flash analyzes high-edge signals with natural language reasoning',
+ stats: { callsToday: geminiCallCount, dailyBudget: GEMINI_DAILY_LIMIT, model: GEMINI_MODEL },
+ skills: ['Signal Analysis', 'News Interpretation', 'Risk Assessment', 'Market Reasoning'],
+ },
+ {
+ id: 'pulse', name: 'Pulse', role: 'Sentiment Analyst', emoji: '💓',
+ color: '#EF4444', status: 'active',
+ desc: '75 event-specific rules across 7 categories with certainty modifiers and source diversity scoring',
+ stats: { rules: 75, categories: 7, avgSentiment: parseFloat(sentimentStats.avg_sentiment || 0).toFixed(3) },
+ skills: ['Event Sentiment', 'Certainty Detection', 'Multi-source Agreement', 'Category Weighting'],
+ },
+ {
+ id: 'hawk', name: 'Hawk', role: 'Market Watcher', emoji: '🦅',
+ color: '#F59E0B', status: 'active',
+ desc: 'Tracks momentum, volume spikes, spreads, and price action across all active markets',
+ stats: { activeMarkets: cachedActiveMarkets.length, trackedMarkets: parseInt(marketStats.tracked_markets) || 0 },
+ skills: ['Momentum Tracking', 'Volume Analysis', 'Spread Detection', 'Price Action'],
+ },
+ {
+ id: 'arbiter', name: 'Arbiter', role: 'Cross-Market Arbitrage', emoji: '⚖️',
+ color: '#14B8A6', status: 'active',
+ desc: 'Compares Kalshi prices vs Polymarket, PredictIt, Manifold, Metaculus for arbitrage',
+ stats: { platforms: 5 },
+ skills: ['Polymarket', 'PredictIt', 'Manifold', 'Metaculus', 'Fuzzy Matching'],
+ },
+ {
+ id: 'shield', name: 'Shield', role: 'Risk Manager', emoji: '🛡️',
+ color: '#22C55E', status: 'active',
+ desc: 'Enforces exposure limits, edge thresholds, time decay, and liquidity requirements',
+ stats: {
+ signalsApproved: parseInt(pipelineStats.approved) || 0,
+ totalSignals: parseInt(pipelineStats.total_signals) || 0,
+ maxConf: parseFloat(pipelineStats.max_confidence || 0).toFixed(2),
+ },
+ skills: ['Position Sizing', 'Exposure Limits', 'Edge Threshold', 'Time Decay', 'Liquidity Check'],
+ },
+ {
+ id: 'storm', name: 'Storm', role: 'Weather Predictor', emoji: '⛈️',
+ color: '#06B6D4', status: 'active',
+ desc: 'NWS forecast data + Bayesian model for 11 US cities, climatological priors by season',
+ stats: { cities: 11 },
+ skills: ['NWS Forecasts', 'Bayesian Weather', 'Climatological Priors', 'Temperature/Precip/Wind'],
+ },
+ ];
+
+ json(res, {
+ ceo: { name: 'Ken', title: 'CEO, Ken Inc.', tagline: 'Trading Intelligence Corporation', color: '#FF69B4' },
+ agents: subAgents,
+ pipeline: {
+ signalsLast24h: parseInt(pipelineStats.total_signals) || 0,
+ approvedLast24h: parseInt(pipelineStats.approved) || 0,
+ lastHour: parseInt(pipelineStats.last_hour) || 0,
+ avgEdge: parseFloat(pipelineStats.avg_edge || 0).toFixed(3),
+ },
+ system: {
+ memory_mb: Math.round(mem.rss / 1024 / 1024),
+ uptime_hours: Math.round(process.uptime() / 3600 * 10) / 10,
+ cpuCores: os.cpus().length,
+ pid: process.pid,
+ },
+ recentSignals: recentSignals.map(s => ({
+ market: s.market_id,
+ direction: s.direction,
+ edge: parseFloat(s.expected_edge || 0),
+ confidence: parseFloat(s.confidence || 0),
+ approved: s.risk_approved,
+ reasoning: s.reasoning?.substring(0, 200),
+ time: s.created_at,
+ })),
+ });
+ },
+
+ // ── Market Data — stock-market style data points ──
+ 'GET /api/inc/market-data': async (req, res) => {
+ const out = {};
+
+ // 1. Hourly signal volume — last 24h in 1-hour buckets
+ try {
+ const { rows } = await kenQ(`SELECT date_trunc('hour', created_at) AS hour,
+ COUNT(*) AS signals, COUNT(*) FILTER (WHERE risk_approved) AS approved,
+ AVG(ABS(expected_edge::numeric)) AS avg_edge,
+ AVG(confidence::numeric) AS avg_confidence
+ FROM ken_strategy_signals
+ WHERE created_at > NOW() - INTERVAL '24 hours'
+ GROUP BY 1 ORDER BY 1`);
+ out.signalTrend = rows.map(r => ({
+ hour: r.hour, signals: parseInt(r.signals), approved: parseInt(r.approved),
+ avgEdge: parseFloat(parseFloat(r.avg_edge || 0).toFixed(4)),
+ avgConf: parseFloat(parseFloat(r.avg_confidence || 0).toFixed(3)),
+ }));
+ } catch { out.signalTrend = []; }
+
+ // 2. Sentiment volume by hour — last 24h
+ try {
+ const { rows } = await kenQ(`SELECT date_trunc('hour', captured_at) AS hour,
+ COUNT(*) AS articles, AVG(sentiment_score) AS avg_sentiment,
+ COUNT(DISTINCT source) AS sources
+ FROM ken_sentiment
+ WHERE captured_at > NOW() - INTERVAL '24 hours'
+ GROUP BY 1 ORDER BY 1`);
+ out.sentimentTrend = rows.map(r => ({
+ hour: r.hour, articles: parseInt(r.articles),
+ avgSentiment: parseFloat(parseFloat(r.avg_sentiment || 0).toFixed(3)),
+ sources: parseInt(r.sources),
+ }));
+ } catch { out.sentimentTrend = []; }
+
+ // 3. Top sentiment sources with counts
+ try {
+ const { rows } = await kenQ(`SELECT source, COUNT(*) AS cnt,
+ AVG(sentiment_score) AS avg_sent
+ FROM ken_sentiment WHERE captured_at > NOW() - INTERVAL '24 hours'
+ GROUP BY source ORDER BY cnt DESC LIMIT 15`);
+ out.sourceMix = rows.map(r => ({
+ source: r.source, count: parseInt(r.cnt),
+ avgSentiment: parseFloat(parseFloat(r.avg_sent || 0).toFixed(3)),
+ }));
+ } catch { out.sourceMix = []; }
+
+ // 4. Top tickers / categories from sentiment
+ try {
+ const { rows } = await kenQ(`SELECT
+ COALESCE(relevance_ticker, 'general') AS category, COUNT(*) AS cnt
+ FROM ken_sentiment WHERE captured_at > NOW() - INTERVAL '24 hours'
+ AND relevance_ticker IS NOT NULL AND relevance_ticker != ''
+ GROUP BY relevance_ticker ORDER BY cnt DESC LIMIT 12`);
+ out.categories = rows.map(r => ({ category: r.category, count: parseInt(r.cnt) }));
+ } catch { out.categories = []; }
+
+ // 5. Portfolio P&L (current state) — compute actual PnL from invested vs returned
+ try {
+ const { rows } = await kenQ(`SELECT p.id, p.name, p.strategy, p.trades_won, p.trades_lost, p.trades_expired,
+ p.total_invested_cents, p.total_returned_cents, p.daily_budget_cents, p.streak,
+ p.best_trade_cents, p.worst_trade_cents, p.last_trade_at,
+ (p.total_returned_cents - p.total_invested_cents) AS pnl_cents,
+ CASE WHEN (p.trades_won + p.trades_lost) > 0
+ THEN ROUND(p.trades_won * 100.0 / (p.trades_won + p.trades_lost))
+ ELSE 0 END AS win_rate,
+ (SELECT COUNT(*) FROM ken_portfolio_trades t WHERE t.portfolio_id = p.id) AS total_trades
+ FROM ken_portfolios p ORDER BY (p.total_returned_cents - p.total_invested_cents) DESC`);
+ out.portfolios = rows.map(r => ({
+ ...r,
+ pnl_cents: parseInt(r.pnl_cents) || 0,
+ win_rate: parseInt(r.win_rate) || 0,
+ total_trades: parseInt(r.total_trades) || 0,
+ total_invested_cents: parseInt(r.total_invested_cents) || 0,
+ total_returned_cents: parseInt(r.total_returned_cents) || 0,
+ }));
+ } catch { out.portfolios = []; }
+
+ // 6. Active markets count and top movers
+ out.activeMarkets = cachedActiveMarkets.length;
+ out.momentumKeys = Object.keys(cachedMomentumMap).length;
+
+ // 7. Signal approval rate over last 6 hours vs prior 6
+ try {
+ const { rows } = await kenQ(`SELECT
+ COUNT(*) FILTER (WHERE created_at > NOW() - INTERVAL '6 hours') AS recent_total,
+ COUNT(*) FILTER (WHERE created_at > NOW() - INTERVAL '6 hours' AND risk_approved) AS recent_approved,
+ COUNT(*) FILTER (WHERE created_at BETWEEN NOW() - INTERVAL '12 hours' AND NOW() - INTERVAL '6 hours') AS prior_total,
+ COUNT(*) FILTER (WHERE created_at BETWEEN NOW() - INTERVAL '12 hours' AND NOW() - INTERVAL '6 hours' AND risk_approved) AS prior_approved
+ FROM ken_strategy_signals WHERE created_at > NOW() - INTERVAL '12 hours'`);
+ const r = rows[0] || {};
+ const recentRate = r.recent_total > 0 ? (r.recent_approved / r.recent_total * 100) : 0;
+ const priorRate = r.prior_total > 0 ? (r.prior_approved / r.prior_total * 100) : 0;
+ out.approvalTrend = {
+ current: Math.round(recentRate), prior: Math.round(priorRate),
+ change: Math.round(recentRate - priorRate),
+ recentSignals: parseInt(r.recent_total), priorSignals: parseInt(r.prior_total),
+ };
+ } catch { out.approvalTrend = { current: 0, prior: 0, change: 0 }; }
+
+ // 8. Gemini usage
+ out.gemini = { callsToday: geminiCallCount, dailyLimit: GEMINI_DAILY_LIMIT, pctUsed: Math.round(geminiCallCount / GEMINI_DAILY_LIMIT * 100) };
+
+ // 9. Latest signals feed — most recent 15 signals for live ticker
+ try {
+ const { rows } = await kenQ(`SELECT market_id, direction, expected_edge, confidence, risk_approved, created_at,
+ SUBSTRING(reasoning FROM 1 FOR 80) AS reason_short
+ FROM ken_strategy_signals ORDER BY created_at DESC LIMIT 15`);
+ out.latestSignals = rows.map(r => ({
+ market: r.market_id, direction: r.direction,
+ edge: parseFloat(parseFloat(r.expected_edge || 0).toFixed(4)),
+ confidence: parseFloat(parseFloat(r.confidence || 0).toFixed(3)),
+ approved: r.risk_approved, reason: r.reason_short,
+ time: r.created_at,
+ }));
+ } catch { out.latestSignals = []; }
+
+ // 10. Per-market signal stats — heatmap data
+ try {
+ const { rows } = await kenQ(`SELECT market_id,
+ COUNT(*) AS total_signals,
+ AVG(expected_edge::numeric) AS avg_edge,
+ AVG(confidence::numeric) AS avg_conf,
+ COUNT(*) FILTER (WHERE risk_approved) AS approved,
+ MAX(created_at) AS last_signal
+ FROM ken_strategy_signals WHERE created_at > NOW() - INTERVAL '24 hours'
+ GROUP BY market_id ORDER BY total_signals DESC LIMIT 20`);
+ out.marketStats = rows.map(r => ({
+ market: r.market_id, signals: parseInt(r.total_signals),
+ avgEdge: parseFloat(parseFloat(r.avg_edge || 0).toFixed(4)),
+ avgConf: parseFloat(parseFloat(r.avg_conf || 0).toFixed(3)),
+ approved: parseInt(r.approved), lastSignal: r.last_signal,
+ }));
+ } catch { out.marketStats = []; }
+
+ // 11. Recent trades with details
+ try {
+ const { rows } = await kenQ(`SELECT t.id, t.portfolio_id, t.market_id, t.market_title, t.direction, t.contracts,
+ t.entry_price_cents, t.pnl_cents, t.status, t.cost_cents, t.confidence, t.created_at,
+ p.name AS portfolio_name, p.strategy
+ FROM ken_portfolio_trades t
+ JOIN ken_portfolios p ON p.id = t.portfolio_id
+ ORDER BY t.created_at DESC LIMIT 20`);
+ out.recentTrades = rows.map(r => ({
+ ...r, entry_price_cents: parseInt(r.entry_price_cents) || 0, pnl_cents: parseInt(r.pnl_cents) || 0,
+ contracts: parseInt(r.contracts) || 0, cost_cents: parseInt(r.cost_cents) || 0,
+ }));
+ } catch { out.recentTrades = []; }
+
+ // 12. Confidence distribution histogram (10 buckets from 0-1)
+ try {
+ const { rows } = await kenQ(`SELECT
+ WIDTH_BUCKET(confidence::numeric, 0, 1, 10) AS bucket,
+ COUNT(*) AS cnt
+ FROM ken_strategy_signals WHERE created_at > NOW() - INTERVAL '24 hours'
+ GROUP BY bucket ORDER BY bucket`);
+ out.confDistribution = Array.from({length: 10}, (_, i) => {
+ const found = rows.find(r => parseInt(r.bucket) === i + 1);
+ return { range: (i * 10) + '-' + ((i + 1) * 10) + '%', count: found ? parseInt(found.cnt) : 0 };
+ });
+ } catch { out.confDistribution = []; }
+
+ json(res, out);
+ },
+};
+
+// ════════════════════════════════════════
+// TOURNAMENT ARENA — 3D TEAM COMPETITION
+// ════════════════════════════════════════
+const ARENA_HTML = `<!DOCTYPE html>
+<html lang="en">
+<head>
+<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
+<title>Tournament Arena | Ken Trading</title>
+<style>
+*{margin:0;padding:0;box-sizing:border-box}
+body{background:#000;overflow:hidden;font-family:'Segoe UI',system-ui,sans-serif;color:#fff}
+#c{position:fixed;top:0;left:0;z-index:0}
+#hud{position:fixed;top:0;left:0;right:0;z-index:10;pointer-events:none}
+.top-bar{display:flex;justify-content:center;align-items:center;padding:20px 40px;gap:30px}
+.team-badge{display:flex;align-items:center;gap:12px;padding:10px 24px;border-radius:12px;pointer-events:auto;cursor:default}
+.team-badge.alpha{background:rgba(99,102,241,.15);border:1px solid rgba(99,102,241,.4)}
+.team-badge.beta{background:rgba(244,63,94,.15);border:1px solid rgba(244,63,94,.4)}
+.team-badge h2{font-size:16px;letter-spacing:2px;text-transform:uppercase}
+.team-badge.alpha h2{color:#818cf8}
+.team-badge.beta h2{color:#fb7185}
+.vs{font-size:32px;font-weight:900;background:linear-gradient(135deg,#818cf8,#fb7185);-webkit-background-clip:text;-webkit-text-fill-color:transparent;text-shadow:none;filter:drop-shadow(0 0 20px rgba(168,85,247,.5))}
+.scoreboard{position:fixed;bottom:20px;left:50%;transform:translateX(-50%);z-index:10;display:flex;gap:8px;background:rgba(0,0,0,.7);backdrop-filter:blur(10px);border:1px solid rgba(255,255,255,.08);border-radius:16px;padding:12px 20px}
+.score-card{text-align:center;padding:6px 16px;border-radius:10px;min-width:100px}
+.score-card.alpha{background:rgba(99,102,241,.1);border:1px solid rgba(99,102,241,.2)}
+.score-card.beta{background:rgba(244,63,94,.1);border:1px solid rgba(244,63,94,.2)}
+.score-card .name{font-size:11px;font-weight:700;letter-spacing:1px;text-transform:uppercase;margin-bottom:4px}
+.score-card.alpha .name{color:#818cf8}
+.score-card.beta .name{color:#fb7185}
+.score-card .strat{font-size:9px;color:#666;margin-bottom:6px}
+.score-card .pnl{font-size:18px;font-weight:800;font-family:'Courier New',monospace}
+.score-card .pnl.pos{color:#4ade80}
+.score-card .pnl.neg{color:#f87171}
+.score-card .pnl.zero{color:#666}
+.score-card .trades{font-size:9px;color:#888;margin-top:2px}
+.score-card .bar{height:3px;border-radius:2px;margin-top:6px;background:#1a1a2e;overflow:hidden}
+.score-card .bar-fill{height:100%;border-radius:2px;transition:width .5s ease}
+.week-info{position:fixed;top:80px;left:50%;transform:translateX(-50%);z-index:10;font-size:11px;color:#555;letter-spacing:2px;text-transform:uppercase}
+.team-total{font-size:11px;font-weight:700;margin-top:4px;letter-spacing:1px}
+.back-link{position:fixed;top:20px;left:20px;z-index:20;color:#666;text-decoration:none;font-size:12px;pointer-events:auto}
+.back-link:hover{color:#fff}
+.refresh-note{position:fixed;bottom:4px;left:50%;transform:translateX(-50%);z-index:10;font-size:9px;color:#333}
+</style>
+</head>
+<body>
+<canvas id="c"></canvas>
+<a href="/inc" class="back-link">← Command Center</a>
+<div id="hud">
+ <div class="top-bar">
+ <div class="team-badge alpha"><div style="width:12px;height:12px;border-radius:50%;background:#818cf8;box-shadow:0 0 12px #818cf8"></div><h2>Team Alpha</h2></div>
+ <div class="vs">VS</div>
+ <div class="team-badge beta"><div style="width:12px;height:12px;border-radius:50%;background:#fb7185;box-shadow:0 0 12px #fb7185"></div><h2>Team Beta</h2></div>
+ </div>
+</div>
+<div id="week-info" class="week-info">Loading tournament...</div>
+<div id="scoreboard" class="scoreboard"></div>
+<div class="refresh-note">Auto-refreshes every 15s</div>
+
+<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"><\/script>
+<script>
+const scene = new THREE.Scene();
+const camera = new THREE.PerspectiveCamera(60, innerWidth/innerHeight, 0.1, 1000);
+const renderer = new THREE.WebGLRenderer({ canvas: document.getElementById('c'), antialias: true, alpha: true });
+renderer.setSize(innerWidth, innerHeight);
+renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
+camera.position.set(0, 4, 12);
+camera.lookAt(0, 0, 0);
+
+// Lighting
+scene.add(new THREE.AmbientLight(0x222244, 0.5));
+const spotA = new THREE.SpotLight(0x6366f1, 2, 30, Math.PI/4);
+spotA.position.set(-6, 10, 5);
+scene.add(spotA);
+const spotB = new THREE.SpotLight(0xf43f5e, 2, 30, Math.PI/4);
+spotB.position.set(6, 10, 5);
+scene.add(spotB);
+const rimLight = new THREE.PointLight(0xa855f7, 1, 20);
+rimLight.position.set(0, 8, -5);
+scene.add(rimLight);
+
+// Arena floor
+const floorGeo = new THREE.CircleGeometry(8, 64);
+const floorMat = new THREE.MeshStandardMaterial({ color: 0x0a0a1a, metalness: 0.8, roughness: 0.3 });
+const floor = new THREE.Mesh(floorGeo, floorMat);
+floor.rotation.x = -Math.PI / 2;
+floor.position.y = -0.5;
+scene.add(floor);
+
+// Arena ring
+const ringGeo = new THREE.TorusGeometry(8, 0.05, 8, 128);
+const ringMat = new THREE.MeshStandardMaterial({ color: 0xa855f7, emissive: 0xa855f7, emissiveIntensity: 0.5 });
+const ring = new THREE.Mesh(ringGeo, ringMat);
+ring.rotation.x = -Math.PI / 2;
+ring.position.y = -0.48;
+scene.add(ring);
+
+// Center divider line
+const divGeo = new THREE.PlaneGeometry(0.02, 14);
+const divMat = new THREE.MeshBasicMaterial({ color: 0x333355, transparent: true, opacity: 0.3 });
+const divider = new THREE.Mesh(divGeo, divMat);
+divider.rotation.x = -Math.PI / 2;
+divider.position.y = -0.47;
+scene.add(divider);
+
+// Particle system for arena atmosphere
+const pCount = 500;
+const pGeo = new THREE.BufferGeometry();
+const pPos = new Float32Array(pCount * 3);
+const pCol = new Float32Array(pCount * 3);
+for (let i = 0; i < pCount; i++) {
+ const r = Math.random() * 10;
+ const a = Math.random() * Math.PI * 2;
+ pPos[i*3] = Math.cos(a) * r;
+ pPos[i*3+1] = Math.random() * 8 - 0.5;
+ pPos[i*3+2] = Math.sin(a) * r;
+ const isAlpha = pPos[i*3] < 0;
+ pCol[i*3] = isAlpha ? 0.38 : 0.96;
+ pCol[i*3+1] = isAlpha ? 0.39 : 0.24;
+ pCol[i*3+2] = isAlpha ? 0.95 : 0.37;
+}
+pGeo.setAttribute('position', new THREE.BufferAttribute(pPos, 3));
+pGeo.setAttribute('color', new THREE.BufferAttribute(pCol, 3));
+const pMat = new THREE.PointsMaterial({ size: 0.04, vertexColors: true, transparent: true, opacity: 0.4, blending: THREE.AdditiveBlending });
+const particles = new THREE.Points(pGeo, pMat);
+scene.add(particles);
+
+// Team node storage
+const teamNodes = [];
+const ALPHA_COLOR = 0x6366f1;
+const BETA_COLOR = 0xf43f5e;
+const TEAM_POSITIONS = {
+ alpha: [[-3.5, 1, -1.5], [-2, 1, 2], [-4.5, 1, 1]],
+ beta: [[3.5, 1, -1.5], [2, 1, 2], [4.5, 1, 1]]
+};
+
+function createTeamNode(pos, color, name, strategy) {
+ const group = new THREE.Group();
+ // Main sphere
+ const geo = new THREE.IcosahedronGeometry(0.6, 2);
+ const mat = new THREE.MeshStandardMaterial({ color, emissive: color, emissiveIntensity: 0.3, metalness: 0.7, roughness: 0.2, wireframe: false });
+ const sphere = new THREE.Mesh(geo, mat);
+ group.add(sphere);
+ // Glow ring
+ const glowGeo = new THREE.TorusGeometry(0.9, 0.03, 8, 64);
+ const glowMat = new THREE.MeshBasicMaterial({ color, transparent: true, opacity: 0.5 });
+ const glowRing = new THREE.Mesh(glowGeo, glowMat);
+ glowRing.rotation.x = Math.PI / 2;
+ group.add(glowRing);
+ // Outer shell wireframe
+ const shellGeo = new THREE.IcosahedronGeometry(0.75, 1);
+ const shellMat = new THREE.MeshBasicMaterial({ color, wireframe: true, transparent: true, opacity: 0.15 });
+ const shell = new THREE.Mesh(shellGeo, shellMat);
+ group.add(shell);
+ // Name label (canvas texture)
+ const canvas = document.createElement('canvas');
+ canvas.width = 256; canvas.height = 80;
+ const ctx = canvas.getContext('2d');
+ ctx.fillStyle = '#fff';
+ ctx.font = 'bold 28px Segoe UI';
+ ctx.textAlign = 'center';
+ ctx.fillText(name, 128, 30);
+ ctx.font = '16px Segoe UI';
+ ctx.fillStyle = '#888';
+ ctx.fillText(strategy, 128, 58);
+ const tex = new THREE.CanvasTexture(canvas);
+ const labelGeo = new THREE.PlaneGeometry(2, 0.6);
+ const labelMat = new THREE.MeshBasicMaterial({ map: tex, transparent: true, depthTest: false });
+ const label = new THREE.Mesh(labelGeo, labelMat);
+ label.position.y = 1.5;
+ group.add(label);
+ // P&L indicator bar (will be updated)
+ const barBgGeo = new THREE.PlaneGeometry(1.2, 0.08);
+ const barBgMat = new THREE.MeshBasicMaterial({ color: 0x1a1a2e, transparent: true, opacity: 0.8 });
+ const barBg = new THREE.Mesh(barBgGeo, barBgMat);
+ barBg.position.y = 1.1;
+ group.add(barBg);
+ const barGeo = new THREE.PlaneGeometry(0.01, 0.06);
+ const barMat = new THREE.MeshBasicMaterial({ color: 0x4ade80, transparent: true, opacity: 0.9 });
+ const bar = new THREE.Mesh(barGeo, barMat);
+ bar.position.y = 1.1;
+ bar.position.x = -0.58;
+ group.add(bar);
+ group.position.set(...pos);
+ scene.add(group);
+ return { group, sphere, shell, glowRing, bar, barMat, mat, name, pnl: 0, trades: 0 };
+}
+
+// Energy beams connecting team members
+function createTeamBeam(nodeA, nodeB, color) {
+ const geo = new THREE.BufferGeometry();
+ const positions = new Float32Array(6);
+ geo.setAttribute('position', new THREE.BufferAttribute(positions, 3));
+ const mat = new THREE.LineBasicMaterial({ color, transparent: true, opacity: 0.15, blending: THREE.AdditiveBlending });
+ const line = new THREE.Line(geo, mat);
+ scene.add(line);
+ return { line, nodeA, nodeB, geo };
+}
+const beams = [];
+
+// Data fetching
+let tournamentData = null;
+async function fetchData() {
+ try {
+ const r = await fetch('/api/tournament/current');
+ const d = await r.json();
+ if (!d.active) return;
+ tournamentData = d;
+ updateScene(d);
+ updateHUD(d);
+ } catch(e) { console.error('Fetch error:', e); }
+}
+
+function updateScene(d) {
+ const entries = d.entries || [];
+ // First 3 = alpha, next 3 = beta (sorted by entry id)
+ const sorted = [...entries].sort((a,b) => a.id - b.id);
+ const alphaEntries = sorted.slice(0, 3);
+ const betaEntries = sorted.slice(3, 6);
+ // Create nodes if not yet created
+ if (teamNodes.length === 0) {
+ alphaEntries.forEach((e, i) => {
+ const n = createTeamNode(TEAM_POSITIONS.alpha[i], ALPHA_COLOR, e.name, e.strategy);
+ n.entry = e;
+ n.team = 'alpha';
+ teamNodes.push(n);
+ });
+ betaEntries.forEach((e, i) => {
+ const n = createTeamNode(TEAM_POSITIONS.beta[i], BETA_COLOR, e.name, e.strategy);
+ n.entry = e;
+ n.team = 'beta';
+ teamNodes.push(n);
+ });
+ // Create beams within each team
+ for (let i = 0; i < 3; i++) for (let j = i+1; j < 3; j++) {
+ beams.push(createTeamBeam(teamNodes[i], teamNodes[j], ALPHA_COLOR));
+ }
+ for (let i = 3; i < 6; i++) for (let j = i+1; j < 6; j++) {
+ beams.push(createTeamBeam(teamNodes[i], teamNodes[j], BETA_COLOR));
+ }
+ }
+ // Update node data
+ const allEntries = [...alphaEntries, ...betaEntries];
+ allEntries.forEach((e, i) => {
+ if (!teamNodes[i]) return;
+ const n = teamNodes[i];
+ n.pnl = e.live_pnl || 0;
+ n.trades = e.live_trades || 0;
+ n.entry = e;
+ // Update emissive based on P&L
+ const intensity = Math.min(0.8, 0.3 + Math.abs(n.pnl) / 500);
+ n.mat.emissiveIntensity = intensity;
+ // Update P&L bar
+ const pnlPct = Math.max(0.01, Math.min(1, (n.pnl + 2000) / 4000));
+ n.bar.scale.x = pnlPct * 116;
+ n.bar.position.x = -0.58 + (pnlPct * 1.16) / 2;
+ n.barMat.color.setHex(n.pnl >= 0 ? 0x4ade80 : 0xf87171);
+ });
+}
+
+function updateHUD(d) {
+ const entries = d.entries || [];
+ const sorted = [...entries].sort((a,b) => a.id - b.id);
+ const t = d.tournament;
+ const wStart = new Date(t.week_start).toLocaleDateString('en-US', {month:'short',day:'numeric'});
+ const wEnd = new Date(t.week_end).toLocaleDateString('en-US', {month:'short',day:'numeric'});
+ document.getElementById('week-info').textContent = 'Week ' + t.id + ' • ' + wStart + ' - ' + wEnd + ' • $' + (t.budget_per_portfolio_cents/100).toFixed(0) + ' per portfolio';
+ let html = '';
+ let alphaTotal = 0, betaTotal = 0;
+ sorted.forEach((e, i) => {
+ const isAlpha = i < 3;
+ const pnl = e.live_pnl || 0;
+ if (isAlpha) alphaTotal += pnl; else betaTotal += pnl;
+ const pnlClass = pnl > 0 ? 'pos' : pnl < 0 ? 'neg' : 'zero';
+ const pnlStr = (pnl >= 0 ? '+' : '') + '$' + (pnl/100).toFixed(2);
+ const budgetUsed = Math.min(100, (e.live_invested || 0) / e.start_balance_cents * 100);
+ const barColor = isAlpha ? '#818cf8' : '#fb7185';
+ html += '<div class="score-card ' + (isAlpha?'alpha':'beta') + '">';
+ html += '<div class="name">' + e.name + '</div>';
+ html += '<div class="strat">' + e.strategy + '</div>';
+ html += '<div class="pnl ' + pnlClass + '">' + pnlStr + '</div>';
+ html += '<div class="trades">' + (e.live_trades||0) + ' trades • $' + ((e.live_invested||0)/100).toFixed(2) + ' deployed</div>';
+ html += '<div class="bar"><div class="bar-fill" style="width:' + budgetUsed + '%;background:' + barColor + '"></div></div>';
+ html += '</div>';
+ if (i === 2) {
+ html += '<div style="display:flex;flex-direction:column;justify-content:center;align-items:center;padding:0 8px">';
+ html += '<div style="font-size:20px;font-weight:900;background:linear-gradient(135deg,#818cf8,#fb7185);-webkit-background-clip:text;-webkit-text-fill-color:transparent">VS</div>';
+ html += '</div>';
+ }
+ });
+ document.getElementById('scoreboard').innerHTML = html;
+}
+
+// Animation
+let time = 0;
+function animate() {
+ requestAnimationFrame(animate);
+ time += 0.01;
+ // Rotate camera slowly
+ camera.position.x = Math.sin(time * 0.15) * 12;
+ camera.position.z = Math.cos(time * 0.15) * 12;
+ camera.position.y = 4 + Math.sin(time * 0.3) * 0.5;
+ camera.lookAt(0, 0.5, 0);
+ // Animate nodes
+ teamNodes.forEach((n, i) => {
+ const base = n.group.position.y;
+ n.sphere.position.y = Math.sin(time * 2 + i) * 0.15;
+ n.sphere.rotation.y = time + i;
+ n.shell.rotation.y = -time * 0.5 + i;
+ n.shell.rotation.x = time * 0.3;
+ n.glowRing.rotation.z = time * (i % 2 === 0 ? 1 : -1);
+ // Pulse based on trades
+ const pulse = 1 + Math.sin(time * 3 + i * 2) * 0.05 * (n.trades > 0 ? 1 : 0.2);
+ n.sphere.scale.setScalar(pulse);
+ });
+ // Update beams
+ beams.forEach(b => {
+ const pa = b.nodeA.group.position;
+ const pb = b.nodeB.group.position;
+ const pos = b.geo.attributes.position.array;
+ pos[0] = pa.x; pos[1] = pa.y + 1; pos[2] = pa.z;
+ pos[3] = pb.x; pos[4] = pb.y + 1; pos[5] = pb.z;
+ b.geo.attributes.position.needsUpdate = true;
+ b.line.material.opacity = 0.1 + Math.sin(time * 2) * 0.05;
+ });
+ // Animate particles
+ const pp = particles.geometry.attributes.position.array;
+ for (let i = 0; i < pCount; i++) {
+ pp[i*3+1] += Math.sin(time + i) * 0.002;
+ if (pp[i*3+1] > 8) pp[i*3+1] = -0.5;
+ }
+ particles.geometry.attributes.position.needsUpdate = true;
+ particles.rotation.y = time * 0.02;
+ // Ring pulse
+ ring.material.emissiveIntensity = 0.3 + Math.sin(time * 2) * 0.2;
+ renderer.render(scene, camera);
+}
+
+// Resize
+addEventListener('resize', () => {
+ camera.aspect = innerWidth / innerHeight;
+ camera.updateProjectionMatrix();
+ renderer.setSize(innerWidth, innerHeight);
+});
+
+// Init
+fetchData();
+setInterval(fetchData, 15000);
+animate();
+<\/script>
+</body>
+</html>`;
+
+// KEN INC COMMAND CENTER PAGE
+// ════════════════════════════════════════
+const KEN_INC_HTML = `<!DOCTYPE html>
+<html lang="en">
+<head>
+<meta charset="UTF-8">
+<meta name="viewport" content="width=device-width, initial-scale=1.0">
+<title>Ken Inc. | Trading Intelligence Command Center</title>
+<script src="https://unpkg.com/react@18/umd/react.production.min.js" crossorigin></script>
+<script src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js" crossorigin></script>
+<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
+<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.4/dist/chart.umd.min.js"></script>
+<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns@3.0.0/dist/chartjs-adapter-date-fns.bundle.min.js"></script>
+<style>
+*{margin:0;padding:0;box-sizing:border-box}
+:root{--bg:#050510;--card:rgba(15,15,35,0.85);--border:rgba(255,255,255,0.06);--text:#e2e8f0;--muted:#64748b;--pink:#ff69b4;--blue:#3b82f6;--purple:#8b5cf6;--green:#22c55e;--red:#ef4444;--yellow:#f59e0b;--cyan:#06b6d4;--teal:#14b8a6}
+body{font-family:'SF Pro Display',-apple-system,BlinkMacSystemFont,sans-serif;background:var(--bg);color:var(--text);min-height:100vh;overflow-x:hidden}
+
+/* Animated gradient background */
+body::before{content:'';position:fixed;top:0;left:0;right:0;bottom:0;background:radial-gradient(ellipse at 20% 50%,rgba(139,92,246,0.08) 0%,transparent 50%),radial-gradient(ellipse at 80% 20%,rgba(255,105,180,0.06) 0%,transparent 50%),radial-gradient(ellipse at 50% 80%,rgba(59,130,246,0.06) 0%,transparent 50%);z-index:-1;animation:bgPulse 8s ease-in-out infinite alternate}
+@keyframes bgPulse{0%{opacity:0.6}100%{opacity:1}}
+
+/* Grid lines overlay */
+body::after{content:'';position:fixed;top:0;left:0;right:0;bottom:0;background-image:linear-gradient(rgba(255,255,255,0.015) 1px,transparent 1px),linear-gradient(90deg,rgba(255,255,255,0.015) 1px,transparent 1px);background-size:60px 60px;z-index:-1;animation:gridScroll 20s linear infinite}
+@keyframes gridScroll{to{background-position:60px 60px}}
+
+.container{max-width:1400px;margin:0 auto;padding:20px}
+
+/* Header */
+.header{text-align:center;padding:30px 20px;position:relative}
+.header-glow{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);width:400px;height:400px;background:radial-gradient(circle,rgba(255,105,180,0.15) 0%,transparent 70%);border-radius:50%;filter:blur(60px);animation:glowPulse 4s ease-in-out infinite alternate;pointer-events:none}
+@keyframes glowPulse{0%{opacity:0.5;transform:translate(-50%,-50%) scale(0.9)}100%{opacity:1;transform:translate(-50%,-50%) scale(1.1)}}
+.ceo-avatar{width:80px;height:80px;border-radius:50%;background:linear-gradient(135deg,#ff69b4,#8b5cf6);display:flex;align-items:center;justify-content:center;font-size:36px;margin:0 auto 12px;box-shadow:0 0 30px rgba(255,105,180,0.4),0 0 60px rgba(139,92,246,0.2);animation:avatarFloat 3s ease-in-out infinite;position:relative;z-index:2}
+@keyframes avatarFloat{0%,100%{transform:translateY(0)}50%{transform:translateY(-8px)}}
+.ceo-name{font-size:32px;font-weight:800;background:linear-gradient(135deg,#ff69b4,#c084fc,#818cf8);-webkit-background-clip:text;-webkit-text-fill-color:transparent;position:relative;z-index:2}
+.ceo-title{color:var(--muted);font-size:14px;letter-spacing:2px;text-transform:uppercase;margin-top:4px;position:relative;z-index:2}
+.ceo-tagline{color:rgba(255,105,180,0.6);font-size:11px;letter-spacing:4px;text-transform:uppercase;margin-top:8px;position:relative;z-index:2}
+
+/* Stats bar */
+.stats-bar{display:flex;justify-content:center;gap:30px;margin:24px 0;flex-wrap:wrap}
+.stat-item{text-align:center;padding:12px 24px;background:var(--card);border:1px solid var(--border);border-radius:12px;backdrop-filter:blur(10px);min-width:120px}
+.stat-val{font-size:24px;font-weight:700;font-variant-numeric:tabular-nums}
+.stat-label{font-size:10px;color:var(--muted);text-transform:uppercase;letter-spacing:1px;margin-top:2px}
+
+/* Agent Network */
+.network{position:relative;margin:30px auto;max-width:1200px}
+.agents-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:16px}
+@media(max-width:1024px){.agents-grid{grid-template-columns:repeat(2,1fr)}}
+@media(max-width:600px){.agents-grid{grid-template-columns:1fr}}
+
+/* Agent Card */
+.agent-card{background:var(--card);border:1px solid var(--border);border-radius:16px;padding:20px;backdrop-filter:blur(10px);transition:all 0.3s cubic-bezier(0.4,0,0.2,1);position:relative;overflow:hidden;cursor:pointer}
+.agent-card::before{content:'';position:absolute;top:0;left:0;right:0;height:3px;border-radius:16px 16px 0 0;opacity:0;transition:opacity 0.3s}
+.agent-card:hover{transform:translateY(-4px);border-color:rgba(255,255,255,0.12);box-shadow:0 20px 40px rgba(0,0,0,0.3)}
+.agent-card:hover::before{opacity:1}
+.agent-card.expanded{grid-column:span 2}
+.agent-header{display:flex;align-items:center;gap:12px}
+.agent-emoji{font-size:28px;width:48px;height:48px;display:flex;align-items:center;justify-content:center;border-radius:12px;flex-shrink:0}
+.agent-name{font-size:16px;font-weight:700}
+.agent-role{font-size:11px;color:var(--muted);text-transform:uppercase;letter-spacing:0.5px}
+.status-indicator{width:8px;height:8px;border-radius:50%;position:absolute;top:16px;right:16px;animation:statusPulse 2s ease-in-out infinite}
+@keyframes statusPulse{0%,100%{opacity:1;box-shadow:0 0 4px currentColor}50%{opacity:0.6;box-shadow:0 0 12px currentColor}}
+.agent-desc{font-size:12px;color:var(--muted);line-height:1.5;margin-top:10px}
+.agent-stats{display:flex;flex-wrap:wrap;gap:6px;margin-top:12px}
+.agent-stat{padding:3px 10px;background:rgba(255,255,255,0.04);border:1px solid var(--border);border-radius:6px;font-size:11px;font-variant-numeric:tabular-nums}
+.agent-stat strong{color:var(--text);margin-right:3px}
+.skills-wrap{margin-top:12px;display:flex;flex-wrap:wrap;gap:4px}
+.skill-tag{padding:2px 8px;border-radius:4px;font-size:10px;font-weight:600;letter-spacing:0.3px}
+
+/* Signal Feed */
+.signal-feed{margin-top:30px}
+.signal-feed h2{font-size:16px;font-weight:600;margin-bottom:12px;display:flex;align-items:center;gap:8px}
+.signal-feed h2 .live-dot{width:8px;height:8px;border-radius:50%;background:var(--red);animation:livePulse 1s ease-in-out infinite}
+@keyframes livePulse{0%,100%{opacity:1;transform:scale(1)}50%{opacity:0.5;transform:scale(0.8)}}
+.signal-list{display:flex;flex-direction:column;gap:6px}
+.signal-item{display:flex;align-items:center;gap:12px;padding:10px 16px;background:var(--card);border:1px solid var(--border);border-radius:10px;font-size:12px;backdrop-filter:blur(10px);transition:border-color 0.2s}
+.signal-item:hover{border-color:rgba(255,255,255,0.12)}
+.signal-dir{padding:3px 8px;border-radius:4px;font-weight:700;font-size:11px;min-width:60px;text-align:center}
+.signal-dir.buy-yes{background:rgba(34,197,94,0.15);color:var(--green)}
+.signal-dir.buy-no{background:rgba(239,68,68,0.15);color:var(--red)}
+.signal-market{flex:1;font-weight:500;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
+.signal-edge{font-weight:700;font-variant-numeric:tabular-nums;min-width:50px;text-align:right}
+.signal-conf{color:var(--muted);font-variant-numeric:tabular-nums;min-width:40px;text-align:right}
+.signal-time{color:var(--muted);font-size:11px;min-width:65px;text-align:right}
+.signal-approved{width:18px;height:18px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:10px;flex-shrink:0}
+
+/* Connection Lines Animation */
+.connections-svg{position:absolute;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:0}
+.data-flow{stroke-dasharray:8 4;animation:flowDash 1s linear infinite}
+@keyframes flowDash{to{stroke-dashoffset:-12}}
+
+/* Particle effect */
+.particles{position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:0}
+.particle{position:absolute;width:2px;height:2px;border-radius:50%;opacity:0;animation:particleFloat linear infinite}
+@keyframes particleFloat{0%{opacity:0;transform:translateY(0)}10%{opacity:0.6}90%{opacity:0.6}100%{opacity:0;transform:translateY(-100vh)}}
+
+/* Clock */
+.clock{position:fixed;top:16px;right:20px;text-align:right;z-index:10}
+.clock-time{font-size:14px;font-weight:600;font-variant-numeric:tabular-nums;color:var(--text)}
+.clock-date{font-size:11px;color:var(--muted)}
+
+/* Sparkline */
+.sparkline-wrap{display:inline-block;vertical-align:middle}
+.sparkline-svg{display:block}
+
+/* ─── Market Data Terminal ─── */
+.mkt-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(340px,1fr));gap:14px;margin-top:16px}
+.mkt-card{background:var(--card);border:1px solid var(--border);border-radius:14px;padding:18px 20px;backdrop-filter:blur(10px);transition:all .3s;position:relative;overflow:hidden}
+.mkt-card::after{content:'';position:absolute;top:0;left:0;right:0;height:2px;background:linear-gradient(90deg,transparent,var(--border),transparent);opacity:0;transition:opacity .3s}
+.mkt-card:hover{border-color:rgba(255,255,255,.12);transform:translateY(-2px);box-shadow:0 12px 40px rgba(0,0,0,.3)}
+.mkt-card:hover::after{opacity:1}
+.mkt-card-header{display:flex;align-items:center;justify-content:space-between;margin-bottom:12px}
+.mkt-card-title{font-size:13px;font-weight:700;text-transform:uppercase;letter-spacing:.5px}
+.mkt-card-badge{padding:3px 8px;border-radius:6px;font-size:10px;font-weight:700;font-variant-numeric:tabular-nums}
+.mkt-bar-chart{display:flex;align-items:flex-end;gap:3px;height:80px;padding-top:4px}
+.mkt-bar{flex:1;border-radius:3px 3px 0 0;min-width:4px;transition:height .5s ease;position:relative}
+.mkt-bar:hover{opacity:1!important;filter:brightness(1.3)}
+.mkt-bar-label{position:absolute;top:-16px;left:50%;transform:translateX(-50%);font-size:8px;color:var(--muted);white-space:nowrap;display:none;background:var(--card);padding:1px 4px;border-radius:3px;border:1px solid var(--border)}
+.mkt-bar:hover .mkt-bar-label{display:block}
+.mkt-source-list{display:flex;flex-direction:column;gap:5px}
+.mkt-source-row{display:flex;align-items:center;gap:8px;font-size:11px;padding:2px 0;transition:background .2s;border-radius:4px}
+.mkt-source-row:hover{background:rgba(255,255,255,.03)}
+.mkt-source-bar{height:7px;border-radius:4px;transition:width .6s cubic-bezier(.4,0,.2,1)}
+.mkt-source-name{min-width:85px;font-weight:500;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
+.mkt-source-val{font-variant-numeric:tabular-nums;color:var(--muted);min-width:45px;text-align:right;font-weight:600}
+.mkt-gauge{position:relative;width:100%;height:14px;background:rgba(255,255,255,.05);border-radius:7px;overflow:hidden;margin-top:8px}
+.mkt-gauge-fill{height:100%;border-radius:7px;transition:width .6s cubic-bezier(.4,0,.2,1)}
+.mkt-gauge-label{position:absolute;top:50%;right:8px;transform:translateY(-50%);font-size:9px;font-weight:700;color:var(--text);text-shadow:0 1px 2px rgba(0,0,0,.5)}
+/* Scrolling ticker */
+.mkt-ticker-strip{overflow:hidden;padding:12px 0;border-top:1px solid rgba(255,255,255,.06);border-bottom:1px solid rgba(255,255,255,.06);margin:16px 0;background:linear-gradient(90deg,rgba(5,5,16,.8),transparent 5%,transparent 95%,rgba(5,5,16,.8))}
+.mkt-ticker-track{display:flex;gap:24px;animation:tickerScroll 40s linear infinite;width:max-content}
+.mkt-ticker-track:hover{animation-play-state:paused}
+@keyframes tickerScroll{0%{transform:translateX(0)}100%{transform:translateX(-50%)}}
+.mkt-ticker-item{display:flex;align-items:center;gap:8px;font-size:12px;font-weight:600;white-space:nowrap;font-variant-numeric:tabular-nums;padding:4px 12px;border-radius:6px;background:rgba(255,255,255,.02);border:1px solid rgba(255,255,255,.04)}
+.mkt-change{font-size:11px;font-weight:700}
+.mkt-change.up{color:var(--green)}
+.mkt-change.down{color:var(--red)}
+.mkt-change.flat{color:var(--muted)}
+/* Signal feed */
+.signal-feed{display:flex;flex-direction:column;gap:4px;max-height:300px;overflow-y:auto}
+.signal-feed::-webkit-scrollbar{width:4px}
+.signal-feed::-webkit-scrollbar-thumb{background:var(--border);border-radius:2px}
+.signal-row{display:flex;align-items:center;gap:8px;padding:6px 10px;border-radius:8px;font-size:11px;transition:all .2s;border:1px solid transparent;animation:signalIn .3s ease}
+.signal-row:hover{background:rgba(255,255,255,.04);border-color:var(--border)}
+@keyframes signalIn{from{opacity:0;transform:translateX(-8px)}to{opacity:1;transform:none}}
+.signal-dir{padding:2px 8px;border-radius:4px;font-weight:800;font-size:10px;text-transform:uppercase;letter-spacing:.5px}
+.signal-dir.yes{background:rgba(34,197,94,.15);color:var(--green)}
+.signal-dir.no{background:rgba(239,68,68,.15);color:var(--red)}
+.signal-market{font-weight:600;min-width:160px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
+.signal-edge{font-variant-numeric:tabular-nums;font-weight:700;min-width:50px;text-align:right}
+.signal-conf{font-variant-numeric:tabular-nums;min-width:40px;text-align:right;color:var(--muted)}
+.signal-time{font-size:9px;color:var(--muted);margin-left:auto;white-space:nowrap}
+.signal-approved{width:6px;height:6px;border-radius:50%;flex-shrink:0}
+/* Heatmap grid */
+.heatmap-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(140px,1fr));gap:6px}
+.heatmap-cell{padding:8px 10px;border-radius:8px;border:1px solid var(--border);transition:all .2s;cursor:default;text-align:center}
+.heatmap-cell:hover{transform:scale(1.03);z-index:1;box-shadow:0 4px 16px rgba(0,0,0,.4)}
+.heatmap-market{font-size:10px;font-weight:700;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;margin-bottom:2px}
+.heatmap-edge{font-size:16px;font-weight:800;font-variant-numeric:tabular-nums}
+.heatmap-meta{font-size:8px;color:var(--muted);margin-top:2px}
+/* Histogram */
+.histogram{display:flex;align-items:flex-end;gap:2px;height:80px}
+.hist-bar{flex:1;border-radius:3px 3px 0 0;transition:height .5s;position:relative;min-width:0}
+.hist-bar:hover{filter:brightness(1.3)}
+.hist-label{position:absolute;bottom:-16px;left:50%;transform:translateX(-50%);font-size:7px;color:var(--muted);white-space:nowrap}
+/* Trade log */
+.trade-log{display:flex;flex-direction:column;gap:3px;max-height:260px;overflow-y:auto}
+.trade-log::-webkit-scrollbar{width:4px}
+.trade-log::-webkit-scrollbar-thumb{background:var(--border);border-radius:2px}
+.trade-row{display:flex;align-items:center;gap:6px;padding:5px 10px;border-radius:6px;font-size:10px;border:1px solid transparent;transition:all .2s}
+.trade-row:hover{background:rgba(255,255,255,.03);border-color:var(--border)}
+.trade-portfolio{font-weight:600;min-width:70px}
+.trade-pnl{font-weight:800;font-variant-numeric:tabular-nums;min-width:55px;text-align:right}
+/* P&L big number */
+.pnl-hero{font-size:48px;font-weight:900;font-variant-numeric:tabular-nums;letter-spacing:-1px;line-height:1}
+@keyframes pnlPulse{0%,100%{text-shadow:0 0 8px currentColor}50%{text-shadow:0 0 20px currentColor}}
+
+/* ─── PortFAUXlio Dashboard ─── */
+.pf-banner{text-align:center;padding:14px;margin-bottom:20px;background:linear-gradient(135deg,rgba(139,92,246,.08),rgba(255,105,180,.06));border:1px solid rgba(139,92,246,.2);border-radius:14px;position:relative;overflow:hidden}
+.pf-banner::before{content:'SIMULATED';position:absolute;top:-2px;right:20px;font-size:8px;letter-spacing:3px;color:var(--purple);background:var(--bg);padding:0 8px;border-radius:0 0 4px 4px;border:1px solid rgba(139,92,246,.2);border-top:none;font-weight:800}
+.pf-banner-title{font-size:22px;font-weight:900;background:linear-gradient(135deg,#8b5cf6,#ec4899);-webkit-background-clip:text;-webkit-text-fill-color:transparent;letter-spacing:1px}
+.pf-banner-sub{font-size:10px;color:var(--muted);letter-spacing:2px;text-transform:uppercase;margin-top:4px}
+
+.pf-summary-row{display:flex;gap:10px;margin-bottom:18px;flex-wrap:wrap}
+.pf-summary-card{flex:1;min-width:100px;background:var(--card);border:1px solid var(--border);border-radius:12px;padding:14px;text-align:center}
+.pf-summary-val{font-size:22px;font-weight:800;font-variant-numeric:tabular-nums}
+.pf-summary-lbl{font-size:9px;color:var(--muted);text-transform:uppercase;letter-spacing:1px;margin-top:2px}
+
+/* Active Trades Strip */
+.pf-active-strip{margin-bottom:20px}
+.pf-active-header{display:flex;align-items:center;gap:8px;margin-bottom:10px;font-size:12px;font-weight:700;text-transform:uppercase;letter-spacing:.5px;color:var(--green)}
+.pf-active-header .dot{width:8px;height:8px;border-radius:50%;background:var(--green);animation:statusPulse 2s ease infinite}
+.pf-active-scroll{display:flex;gap:8px;overflow-x:auto;padding-bottom:8px;scroll-behavior:smooth}
+.pf-active-scroll::-webkit-scrollbar{height:4px}
+.pf-active-scroll::-webkit-scrollbar-thumb{background:var(--border);border-radius:2px}
+.pf-active-card{flex-shrink:0;min-width:200px;max-width:260px;background:var(--card);border:1px solid var(--border);border-radius:10px;padding:10px 14px;transition:all .2s;border-top:2px solid var(--border)}
+.pf-active-card:hover{border-color:rgba(255,255,255,.15);transform:translateY(-2px);box-shadow:0 8px 24px rgba(0,0,0,.3)}
+
+/* Model Leaderboard Table */
+.pf-leaderboard{margin-bottom:20px;border:1px solid var(--border);border-radius:14px;overflow:hidden;background:var(--card);max-height:800px;overflow-y:auto}
+.pf-leaderboard::-webkit-scrollbar{width:4px}
+.pf-leaderboard::-webkit-scrollbar-thumb{background:var(--border);border-radius:2px}
+.pf-lb-header{display:grid;grid-template-columns:32px 100px 90px 80px 70px 40px 40px 55px 80px 150px;gap:0;padding:10px 14px;background:rgba(255,255,255,.03);border-bottom:1px solid var(--border);font-size:9px;font-weight:700;text-transform:uppercase;letter-spacing:.5px;color:var(--muted)}
+.pf-lb-header span[style*="cursor"]:hover{color:var(--cyan)}
+.pf-lb-row{display:grid;grid-template-columns:32px 100px 90px 80px 70px 40px 40px 55px 80px 150px;gap:0;padding:10px 14px;border-bottom:1px solid rgba(255,255,255,.03);font-size:11px;transition:all .2s;cursor:pointer;align-items:center}
+/* Chart Modal */
+.chart-modal{position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,.7);z-index:1000;display:flex;align-items:center;justify-content:center;backdrop-filter:blur(4px);animation:modalFadeIn .3s ease}
+.chart-modal-content{background:var(--card);border:1px solid var(--border);border-radius:16px;padding:24px;width:92%;max-width:900px}
+@keyframes modalFadeIn{from{opacity:0;transform:scale(.95)}to{opacity:1;transform:scale(1)}}
+.chart-modal-header{display:flex;align-items:center;gap:10px;margin-bottom:16px}
+.chart-close{margin-left:auto;background:none;border:1px solid var(--border);color:var(--muted);border-radius:8px;padding:4px 12px;cursor:pointer;font-size:12px}
+.chart-close:hover{color:var(--text);border-color:var(--muted)}
+.chart-period-btns{display:flex;gap:4px;margin-left:auto}
+.chart-period,.chart-period-active{padding:3px 10px;border-radius:6px;font-size:10px;font-weight:600;cursor:pointer;border:1px solid var(--border);background:transparent;color:var(--muted);transition:all .2s}
+.chart-period-active{border-color:var(--cyan);background:rgba(6,182,212,.1);color:var(--cyan)}
+.pf-lb-chart{display:flex;align-items:center;cursor:pointer;opacity:.85;transition:opacity .2s}
+.pf-lb-chart:hover{opacity:1}
+/* SWOT Trade Analysis */
+.swot-section{margin-bottom:20px}
+.swot-card{background:var(--card);border:1px solid var(--border);border-radius:14px;overflow:hidden;margin-bottom:12px;transition:all .2s}
+.swot-card:hover{border-color:rgba(255,255,255,.1)}
+.swot-card-header{display:flex;align-items:center;gap:10px;padding:14px 16px;cursor:pointer;border-bottom:1px solid rgba(255,255,255,.03)}
+.swot-grid{display:grid;grid-template-columns:1fr 1fr;gap:10px;padding:12px 16px}
+.swot-quadrant{padding:10px;border-radius:10px;font-size:10px}
+.swot-quadrant-s{background:rgba(34,197,94,.06);border:1px solid rgba(34,197,94,.15)}
+.swot-quadrant-w{background:rgba(239,68,68,.06);border:1px solid rgba(239,68,68,.15)}
+.swot-quadrant-o{background:rgba(59,130,246,.06);border:1px solid rgba(59,130,246,.15)}
+.swot-quadrant-t{background:rgba(245,158,11,.06);border:1px solid rgba(245,158,11,.15)}
+.swot-q-title{font-weight:800;font-size:9px;text-transform:uppercase;letter-spacing:.5px;margin-bottom:6px}
+.swot-q-item{padding:2px 0;color:var(--muted);line-height:1.4}
+.swot-q-item::before{content:'• '}
+.swot-models{display:flex;flex-wrap:wrap;gap:4px;padding:8px 16px 14px}
+.swot-model-tag{padding:2px 8px;border-radius:4px;font-size:9px;font-weight:600;background:rgba(255,255,255,.04);border:1px solid rgba(255,255,255,.06)}
+.pf-lb-row:hover{background:rgba(255,255,255,.03)}
+.pf-lb-row:last-child{border-bottom:none}
+.pf-lb-rank{font-size:14px;font-weight:900;color:var(--muted)}
+.pf-lb-name{font-weight:700;display:flex;align-items:center;gap:6px;overflow:hidden}
+.pf-lb-pnl{font-weight:800;font-variant-numeric:tabular-nums}
+.pf-lb-invested{font-variant-numeric:tabular-nums;color:var(--muted)}
+.pf-lb-wr{font-weight:700;font-variant-numeric:tabular-nums}
+.pf-lb-wl{font-variant-numeric:tabular-nums;color:var(--muted)}
+.pf-lb-roi{font-weight:800;font-variant-numeric:tabular-nums;padding:2px 8px;border-radius:4px;text-align:center}
+.pf-lb-bar{height:4px;border-radius:2px;background:rgba(255,255,255,.05);overflow:hidden;margin-top:2px}
+.pf-lb-bar-fill{height:100%;border-radius:2px;transition:width .6s ease}
+
+/* Overlap Warning */
+.pf-overlap{margin-bottom:18px;background:rgba(245,158,11,.04);border:1px solid rgba(245,158,11,.15);border-radius:12px;padding:14px}
+.pf-overlap-title{font-size:11px;font-weight:700;color:var(--yellow);text-transform:uppercase;letter-spacing:.5px;margin-bottom:8px;display:flex;align-items:center;gap:6px}
+
+/* Trade History */
+.pf-history{border:1px solid var(--border);border-radius:14px;overflow:hidden;background:var(--card)}
+.pf-history-header{padding:14px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid var(--border)}
+.pf-history-list{max-height:400px;overflow-y:auto}
+.pf-history-list::-webkit-scrollbar{width:4px}
+.pf-history-list::-webkit-scrollbar-thumb{background:var(--border);border-radius:2px}
+.pf-history-row{display:flex;align-items:center;gap:8px;padding:8px 14px;font-size:11px;border-bottom:1px solid rgba(255,255,255,.02);transition:all .15s}
+.pf-history-row:hover{background:rgba(255,255,255,.03)}
+.pf-history-row:last-child{border-bottom:none}
+
+@media(max-width:900px){
+.pf-lb-header,.pf-lb-row{grid-template-columns:28px 80px 70px 70px 50px 40px 40px 50px 70px;font-size:10px;padding:8px 10px}
+.pf-active-card{min-width:180px}
+}
+
+/* Footer */
+.footer{text-align:center;padding:30px;color:var(--muted);font-size:11px;letter-spacing:1px}
+.footer a{color:var(--pink);text-decoration:none}
+</style>
+</head>
+<body>
+<div id="root"></div>
+<script type="text/babel">
+const { useState, useEffect, useRef } = React;
+
+// SECURITY (audit 2026-05-04): inline literal credentials shipped to every
+// browser via this <script> block. Removed. Dashboard MUST be refactored to
+// use the server-side session cookie (`kalshi_session`) for auth — the cookie
+// is already set on login and Express forwards it on subsequent requests.
+// Until refactor: dashboard fetches will 401 visibly, signaling the work needed.
+const AUTH = '';
+const api = (url) => fetch(url, { credentials: 'include' }).then(r => r.json());
+
+function Particles() {
+ const particles = Array.from({ length: 30 }, (_, i) => ({
+ id: i,
+ left: Math.random() * 100 + '%',
+ delay: Math.random() * 10 + 's',
+ duration: 8 + Math.random() * 12 + 's',
+ color: ['#ff69b4','#8b5cf6','#3b82f6','#22c55e','#f59e0b','#06b6d4'][Math.floor(Math.random()*6)],
+ size: 1 + Math.random() * 2 + 'px',
+ }));
+ return (
+ <div className="particles">
+ {particles.map(p => (
+ <div key={p.id} className="particle" style={{
+ left: p.left, bottom: 0, animationDelay: p.delay, animationDuration: p.duration,
+ background: p.color, width: p.size, height: p.size, boxShadow: '0 0 6px ' + p.color,
+ }} />
+ ))}
+ </div>
+ );
+}
+
+function Clock() {
+ const [now, setNow] = useState(new Date());
+ useEffect(() => { const iv = setInterval(() => setNow(new Date()), 1000); return () => clearInterval(iv); }, []);
+ const pt = now.toLocaleString('en-US', { timeZone: 'America/Los_Angeles', hour: 'numeric', minute: '2-digit', second: '2-digit', hour12: true });
+ const dateStr = now.toLocaleDateString('en-US', { timeZone: 'America/Los_Angeles', weekday: 'short', month: 'short', day: 'numeric' });
+ return <div className="clock"><div className="clock-time">{pt} PT</div><div className="clock-date">{dateStr}</div></div>;
+}
+
+function AgentCard({ agent, expanded, onToggle }) {
+ const bgColor = agent.color + '15';
+ return (
+ <div className={'agent-card' + (expanded ? ' expanded' : '')} onClick={onToggle}
+ style={{ '--agent-color': agent.color }}>
+ <div className="status-indicator" style={{ background: agent.status === 'active' ? 'var(--green)' : 'var(--yellow)', color: agent.status === 'active' ? 'var(--green)' : 'var(--yellow)' }} />
+ <div style={{ position: 'absolute', top: 0, left: 0, right: 0, height: 3, borderRadius: '16px 16px 0 0', background: agent.color, opacity: 0.7 }} />
+ <div className="agent-header">
+ <div className="agent-emoji" style={{ background: bgColor }}>{agent.emoji}</div>
+ <div>
+ <div className="agent-name" style={{ color: agent.color }}>{agent.name}</div>
+ <div className="agent-role">{agent.role}</div>
+ </div>
+ </div>
+ <div className="agent-desc">{agent.desc}</div>
+ <div className="agent-stats">
+ {Object.entries(agent.stats || {}).map(([k, v]) => (
+ <div key={k} className="agent-stat"><strong>{typeof v === 'number' ? v.toLocaleString() : v}</strong> {k.replace(/([A-Z])/g, ' $1').toLowerCase()}</div>
+ ))}
+ </div>
+ {expanded && (
+ <div className="skills-wrap">
+ {(agent.skills || []).map(s => (
+ <span key={s} className="skill-tag" style={{ background: agent.color + '20', color: agent.color, border: '1px solid ' + agent.color + '30' }}>{s}</span>
+ ))}
+ </div>
+ )}
+ </div>
+ );
+}
+
+function SignalFeed({ signals }) {
+ if (!signals?.length) return <div style={{ textAlign: 'center', color: 'var(--muted)', padding: 30, fontSize: 13 }}>Waiting for signals...</div>;
+
+ function timeAgo(ts) {
+ const ms = Date.now() - new Date(ts).getTime();
+ if (ms < 60000) return Math.floor(ms/1000) + 's ago';
+ if (ms < 3600000) return Math.floor(ms/60000) + 'm ago';
+ return Math.floor(ms/3600000) + 'h ago';
+ }
+
+ return (
+ <div className="signal-list">
+ {signals.slice(0, 12).map((s, i) => (
+ <div key={i} className="signal-item">
+ <div className={'signal-dir ' + (s.direction === 'BUY_YES' ? 'buy-yes' : 'buy-no')}>
+ {s.direction === 'BUY_YES' ? 'BUY YES' : 'BUY NO'}
+ </div>
+ <div className="signal-market" title={s.market}>{s.market}</div>
+ <div className="signal-edge" style={{ color: Math.abs(s.edge) > 0.1 ? 'var(--green)' : 'var(--muted)' }}>
+ {(s.edge * 100).toFixed(1)}%
+ </div>
+ <div className="signal-conf">{(s.confidence * 100).toFixed(0)}%</div>
+ <div className="signal-approved" style={{ background: s.approved ? 'rgba(34,197,94,0.15)' : 'rgba(239,68,68,0.1)', color: s.approved ? 'var(--green)' : 'var(--red)' }}>
+ {s.approved ? '✓' : '✗'}
+ </div>
+ <div className="signal-time">{timeAgo(s.time)}</div>
+ </div>
+ ))}
+ </div>
+ );
+}
+
+// ── PORTFOLIOS TAB ──
+function PortfoliosTab() {
+ const [data, setData] = useState(null);
+ const [histFilter, setHistFilter] = useState('all');
+ const [chartData, setChartData] = useState({});
+ const [selectedChart, setSelectedChart] = useState(null);
+ const [compareMode, setCompareMode] = useState(false);
+ const [compareIds, setCompareIds] = useState([]);
+ const [sortBy, setSortBy] = useState('pnl');
+ const [sortDir, setSortDir] = useState('desc');
+ useEffect(() => {
+ const load = () => api('/api/portfauxlio').then(setData).catch(e => console.error(e));
+ load();
+ const iv = setInterval(load, 15000);
+ return () => clearInterval(iv);
+ }, []);
+ useEffect(() => {
+ const loadCharts = () => api('/api/portfauxlio/charts?period=7d').then(d => {
+ const byId = {};
+ (d.portfolios || []).forEach(p => { byId[p.id] = p; });
+ setChartData(byId);
+ }).catch(() => {});
+ loadCharts();
+ const cv = setInterval(loadCharts, 120000);
+ return () => clearInterval(cv);
+ }, []);
+ const [swotData, setSwotData] = useState(null);
+ const [swotExpanded, setSwotExpanded] = useState({});
+ useEffect(() => {
+ const loadSwot = () => api('/api/portfauxlio/swot').then(setSwotData).catch(() => {});
+ loadSwot();
+ const sv = setInterval(loadSwot, 60000);
+ return () => clearInterval(sv);
+ }, []);
+
+ const stratColors = {aggressive:'#ef4444',conservative:'#3b82f6',weather:'#06b6d4',momentum:'#f59e0b',contrarian:'#8b5cf6',ai_enhanced:'#ec4899',mc_validated:'#a855f7',scalper:'#eab308',patient:'#22c55e',random:'#64748b',penny_pincher:'#94a3b8',spray_pray:'#fb923c',nickel_slots:'#a78bfa',degen_lite:'#f43f5e',politics_junkie:'#0ea5e9',double_down:'#dc2626',volatility_rider:'#14b8a6',whale:'#1d4ed8',yolo:'#e11d48',full_send:'#b91c1c',kelly_criterion:'#059669',sharpe_sniper:'#7c3aed',bayesian_blend:'#0891b2',ensemble_lock:'#c026d3',mean_revert:'#d97706',info_ratio:'#2563eb',anti_fomo:'#16a34a',nightcrawler:'#4c1d95',heatseeker:'#ea580c',quant_core:'#0d9488',etf_presidential:'#dc143c',etf_cabinet:'#ff6347',etf_congress:'#4169e1',etf_scotus:'#2f4f4f',etf_fed:'#228b22',etf_economy:'#daa520',etf_geopolitics:'#8b0000',etf_territory:'#006400',etf_climate:'#00bfff',etf_energy:'#ff8c00',etf_tech:'#7b68ee',etf_space:'#191970',etf_crypto:'#ffd700',etf_sports:'#32cd32',etf_entertainment:'#ff1493',etf_legal:'#708090',etf_financials:'#4682b4',etf_govreform:'#b22222',etf_global_social:'#9370db',etf_broad_market:'#c0a050'};
+ const stratEmojis = {aggressive:'🔥',conservative:'🏛️',weather:'⛈️',momentum:'🚀',contrarian:'🔄',ai_enhanced:'🧠',mc_validated:'🎲',scalper:'⚡',patient:'🐢',random:'🎰',penny_pincher:'🪙',spray_pray:'💦',nickel_slots:'🎰',degen_lite:'😈',politics_junkie:'🏛️',double_down:'⬆️',volatility_rider:'🏄',whale:'🐳',yolo:'🧨',full_send:'💣',kelly_criterion:'🎰',sharpe_sniper:'🎯',bayesian_blend:'🧮',ensemble_lock:'🔐',mean_revert:'↩️',info_ratio:'📊',anti_fomo:'🧘',nightcrawler:'🦇',heatseeker:'🔬',quant_core:'∑',etf_presidential:'🏛️',etf_cabinet:'💼',etf_congress:'🗳️',etf_scotus:'⚖️',etf_fed:'🏦',etf_economy:'📈',etf_geopolitics:'🌍',etf_territory:'🗺️',etf_climate:'🌡️',etf_energy:'⛽',etf_tech:'🤖',etf_space:'🚀',etf_crypto:'₿',etf_sports:'⚽',etf_entertainment:'🎬',etf_legal:'🔨',etf_financials:'💹',etf_govreform:'✂️',etf_global_social:'⛪',etf_broad_market:'🌐'};
+ const stratNames = {aggressive:'Alpha',conservative:'Beta',weather:'Storm',momentum:'Momentum',contrarian:'Contrarian',ai_enhanced:'Nova',mc_validated:'Oracle',scalper:'Shark',patient:'Turtle',random:'Wildcard',penny_pincher:'Penny',spray_pray:'Spray',nickel_slots:'Nickel',degen_lite:'Degen',politics_junkie:'Capitol',double_down:'Doubler',volatility_rider:'Rider',whale:'Moby',yolo:'YOLO',full_send:'Cannon',kelly_criterion:'Kelly',sharpe_sniper:'Sniper',bayesian_blend:'Bayes',ensemble_lock:'Voltron',mean_revert:'Revert',info_ratio:'Signal',anti_fomo:'Zen',nightcrawler:'Shadow',heatseeker:'Heatseek',quant_core:'Quant',etf_presidential:'PRES',etf_cabinet:'Cabinet',etf_congress:'Congress',etf_scotus:'SCOTUS',etf_fed:'Fed',etf_economy:'Economy',etf_geopolitics:'Geo',etf_territory:'Territory',etf_climate:'Climate',etf_energy:'Energy',etf_tech:'Tech',etf_space:'Space',etf_crypto:'Crypto',etf_sports:'Sports',etf_entertainment:'Showbiz',etf_legal:'Legal',etf_financials:'Finance',etf_govreform:'GovReform',etf_global_social:'Global',etf_broad_market:'Broad Mkt'};
+ const stratDesc = {aggressive:'High edge (>15%), low confidence — speculative swings',conservative:'High confidence (>70%) — quality over quantity',weather:'Weather/climate markets only',momentum:'High agreement + articles — follows the trend',contrarian:'BUY_NO only — bets against the crowd',ai_enhanced:'Gemini AI enhanced signals only',mc_validated:'Monte Carlo validated, tight spread',scalper:'Small edges (3-10%) — quantity plays',patient:'Needs everything: conf>80%, MC, 5+ articles',random:'20% random — control group for luck testing',penny_pincher:'Any edge >=1% — micro bets, max volume',spray_pray:'Random 50% of all signals — luck vs skill',nickel_slots:'Edge >=2% + conf >=20% — low bar catcher',degen_lite:'Edge >=5%, ignores confidence — pure edge',politics_junkie:'Political markets only — elections/congress',double_down:'Edge >=20% — goes big on massive edges',volatility_rider:'High MC stddev + edge — volatile markets',whale:'Edge >=25% + conf >=60% — rare massive sniper',yolo:'Edge >=30% — max degen, no filters',full_send:'Takes EVERY signal — pipeline profitability test',kelly_criterion:'Kelly fraction: edge/(1+edge) — bankroll math',sharpe_sniper:'Signal-to-noise ratio >2.0 — edge/stddev',bayesian_blend:'Bayesian posterior: conf * evidence * edge',ensemble_lock:'ALL must align: AI + MC + conf + edge + articles',mean_revert:'High volatility + moderate edge — reversion play',info_ratio:'(articles * agreement) / noise — quality intel',anti_fomo:'Small edge + high conf — calm, certain plays',nightcrawler:'BUY_NO + AI + MC — sophisticated shorts',heatseeker:'Multi-factor composite: 40e + 30c + 20a + 10n',quant_core:'Geometric mean sqrt(edge*conf) — pure math',etf_presidential:'Presidential election & 2028 race markets',etf_cabinet:'Cabinet confirmations & departures',etf_congress:'House, Senate & legislative markets',etf_scotus:'Supreme Court rulings & retirements',etf_fed:'Federal Reserve, rates & monetary policy',etf_economy:'GDP, jobs & economic indicators',etf_geopolitics:'Wars, treaties, sanctions & foreign affairs',etf_territory:'Greenland, statehood & territorial expansion',etf_climate:'Weather, warming & climate events',etf_energy:'LNG, oil, power grid & energy commodities',etf_tech:'AI, fusion, tech companies & semiconductors',etf_space:'SpaceX, NASA, Mars & Moon missions',etf_crypto:'Bitcoin, Ethereum & digital assets',etf_sports:'NBA, NFL, MLB & sports outcomes',etf_entertainment:'Celebrity, media, awards & pop culture',etf_legal:'Pardons, impeachment & legal proceedings',etf_financials:'Bonds, yields & financial markets',etf_govreform:'DOGE, agency cuts & government reform',etf_global_social:'Pope, referendums & global social movements',etf_broad_market:'Index fund — high-quality signals all sectors'};
+
+ if (!data) return <div style={{textAlign:'center',padding:60,color:'var(--muted)'}}>Loading portFAUXlio data...</div>;
+
+ const { portfolios: rawPortfolios, activeTrades, tradeHistory, overlaps, summary } = data;
+ const maxInvested = Math.max(...rawPortfolios.map(p => parseInt(p.total_invested_cents) || 0), 1);
+ const filteredHistory = histFilter === 'all' ? tradeHistory : tradeHistory.filter(t => t.strategy === histFilter);
+
+ const sortFns = {
+ pnl: p => parseInt(p.pnl_cents) || 0,
+ roi: p => parseFloat(p.roi_pct) || 0,
+ invested: p => parseInt(p.total_invested_cents) || 0,
+ trades: p => (parseInt(p.trades_won)||0) + (parseInt(p.trades_lost)||0) + (parseInt(p.trades_expired)||0),
+ wins: p => parseInt(p.trades_won) || 0,
+ name: p => (p.name || '').toLowerCase(),
+ strategy: p => (p.strategy || '').toLowerCase(),
+ };
+ const getSortVal = sortFns[sortBy] || sortFns.pnl;
+ const portfolios = [...rawPortfolios].sort((a, b) => {
+ const av = getSortVal(a), bv = getSortVal(b);
+ if (typeof av === 'string') return sortDir === 'asc' ? av.localeCompare(bv) : bv.localeCompare(av);
+ return sortDir === 'desc' ? bv - av : av - bv;
+ });
+ const toggleSort = (col) => { if (sortBy === col) setSortDir(d => d === 'desc' ? 'asc' : 'desc'); else { setSortBy(col); setSortDir('desc'); } };
+
+ return (<div>
+ {/* ═══ Banner ═══ */}
+ <div className="pf-banner">
+ <div className="pf-banner-title">portFAUXlio</div>
+ <div className="pf-banner-sub">50 Strategy Models • Paper Trading • Real Signals • Zero Real Money</div>
+ </div>
+
+ {/* ═══ Summary Stats ═══ */}
+ <div className="pf-summary-row">
+ <div className="pf-summary-card">
+ <div className="pf-summary-val" style={{color: summary.totalPnl >= 0 ? 'var(--green)' : 'var(--red)'}}>
+ {summary.totalPnl >= 0 ? '+' : ''}{'$'}{(summary.totalPnl / 100).toFixed(2)}
+ </div>
+ <div className="pf-summary-lbl">Total P&L</div>
+ </div>
+ <div className="pf-summary-card">
+ <div className="pf-summary-val" style={{color:'var(--blue)'}}>{'$'}{(summary.totalInvested / 100).toFixed(2)}</div>
+ <div className="pf-summary-lbl">Invested</div>
+ </div>
+ <div className="pf-summary-card">
+ <div className="pf-summary-val" style={{color:'var(--purple)'}}>{summary.totalTrades}</div>
+ <div className="pf-summary-lbl">Total Trades</div>
+ </div>
+ <div className="pf-summary-card">
+ <div className="pf-summary-val" style={{color:'var(--green)'}}>{summary.openTrades}</div>
+ <div className="pf-summary-lbl">Open Positions</div>
+ </div>
+ <div className="pf-summary-card">
+ <div className="pf-summary-val" style={{color:'var(--cyan)'}}>{summary.uniqueMarkets}</div>
+ <div className="pf-summary-lbl">Markets</div>
+ </div>
+ <div className="pf-summary-card">
+ <div className="pf-summary-val" style={{color:'var(--yellow)'}}>{summary.activeModels}/{portfolios ? portfolios.length : 50}</div>
+ <div className="pf-summary-lbl">Active Models</div>
+ </div>
+ </div>
+
+ {/* ═══ Active Trades Strip ═══ */}
+ {activeTrades.length > 0 && <div className="pf-active-strip">
+ <div className="pf-active-header">
+ <span className="dot" />
+ {activeTrades.length} Open Positions
+ </div>
+ <div className="pf-active-scroll">
+ {activeTrades.map((t, i) => {
+ const c = stratColors[t.strategy] || 'var(--muted)';
+ return (<div key={i} className="pf-active-card" style={{borderTopColor: c}}>
+ <div style={{display:'flex',alignItems:'center',gap:6,marginBottom:4}}>
+ <span style={{fontSize:14}}>{stratEmojis[t.strategy] || ''}</span>
+ <span style={{fontSize:11,fontWeight:700,color:c}}>{t.portfolio_name}</span>
+ <span style={{marginLeft:'auto',padding:'1px 6px',borderRadius:4,fontSize:9,fontWeight:700,
+ background: t.direction === 'BUY_YES' ? 'rgba(34,197,94,.15)' : 'rgba(239,68,68,.15)',
+ color: t.direction === 'BUY_YES' ? 'var(--green)' : 'var(--red)'
+ }}>{t.direction === 'BUY_YES' ? 'YES' : 'NO'}</span>
+ </div>
+ <div style={{fontSize:10,fontWeight:600,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap',marginBottom:3}} title={t.market_title || t.market_id}>
+ {t.market_title || t.market_id}
+ </div>
+ <div style={{display:'flex',justifyContent:'space-between',fontSize:10,color:'var(--muted)'}}>
+ <span>{t.contracts}x @ {t.entry_price_cents}¢</span>
+ <span>{'$'}{(t.cost_cents / 100).toFixed(2)}</span>
+ <span>{timeAgo(t.created_at)}</span>
+ </div>
+ </div>);
+ })}
+ </div>
+ </div>}
+
+ {/* ═══ Model Leaderboard ═══ */}
+ <div style={{marginBottom:18}}>
+ <div style={{fontSize:13,fontWeight:700,textTransform:'uppercase',letterSpacing:.5,marginBottom:10,color:'var(--pink)',display:'flex',alignItems:'center',gap:8}}>
+ Model Leaderboard
+ <span style={{fontSize:9,fontWeight:400,color:'var(--muted)',textTransform:'none',letterSpacing:0}}>ranked by {sortBy}</span>
+ <div style={{marginLeft:'auto',display:'flex',gap:6}}>
+ {compareMode && compareIds.length >= 2 && <button onClick={() => setCompareMode('show')} style={{padding:'3px 10px',borderRadius:6,fontSize:9,fontWeight:700,background:'rgba(6,182,212,.15)',border:'1px solid var(--cyan)',color:'var(--cyan)',cursor:'pointer'}}>
+ Compare {compareIds.length} →
+ </button>}
+ <button onClick={() => { if (compareMode) { setCompareMode(false); setCompareIds([]); } else setCompareMode(true); }} style={{padding:'3px 10px',borderRadius:6,fontSize:9,fontWeight:700,background:compareMode?'rgba(168,85,247,.15)':'transparent',border:'1px solid '+(compareMode?'var(--purple)':'var(--border)'),color:compareMode?'var(--purple)':'var(--muted)',cursor:'pointer'}}>
+ {compareMode ? '✕ Cancel' : '📊 Compare'}
+ </button>
+ </div>
+ </div>
+ <div className="pf-leaderboard">
+ <div className="pf-lb-header">
+ <span>#</span>
+ <span style={{cursor:'pointer'}} onClick={() => toggleSort('name')}>Model {sortBy==='name' ? (sortDir==='asc'?'▲':'▼') : ''}</span>
+ <span style={{cursor:'pointer'}} onClick={() => toggleSort('pnl')}>P&L {sortBy==='pnl' ? (sortDir==='asc'?'▲':'▼') : ''}</span>
+ <span style={{cursor:'pointer'}} onClick={() => toggleSort('invested')}>Invested {sortBy==='invested' ? (sortDir==='asc'?'▲':'▼') : ''}</span>
+ <span style={{cursor:'pointer'}} onClick={() => toggleSort('roi')}>ROI {sortBy==='roi' ? (sortDir==='asc'?'▲':'▼') : ''}</span>
+ <span style={{cursor:'pointer'}} onClick={() => toggleSort('wins')}>W {sortBy==='wins' ? (sortDir==='asc'?'▲':'▼') : ''}</span>
+ <span>L</span>
+ <span style={{cursor:'pointer'}} onClick={() => toggleSort('trades')}>Trades {sortBy==='trades' ? (sortDir==='asc'?'▲':'▼') : ''}</span>
+ <span style={{cursor:'pointer'}} onClick={() => toggleSort('strategy')}>Strategy {sortBy==='strategy' ? (sortDir==='asc'?'▲':'▼') : ''}</span>
+ <span>Chart</span>
+ </div>
+ {portfolios.map((p, i) => {
+ const c = stratColors[p.strategy] || 'var(--muted)';
+ const pnl = parseInt(p.pnl_cents) || 0;
+ const invested = parseInt(p.total_invested_cents) || 0;
+ const resolved = parseInt(p.resolved_trades) || 0;
+ const roi = parseFloat(p.roi_pct) || 0;
+ const totalT = (parseInt(p.trades_won) || 0) + (parseInt(p.trades_lost) || 0) + (parseInt(p.trades_expired) || 0);
+ const openCount = activeTrades.filter(t => t.portfolio_id === p.id).length;
+ const medals = ['🥇','🥈','🥉'];
+ const cd = chartData[p.id];
+ const miniPts = cd ? (cd.snapshots || []).map(s => s.nav / 100) : (cd?.daily || []).map(d => d.cumulative / 100);
+ return (<div key={p.id} className="pf-lb-row" style={compareMode && compareIds.includes(p.id) ? {background:'rgba(168,85,247,.08)',borderLeft:'3px solid var(--purple)'} : {}} onClick={() => {
+ if (compareMode) { setCompareIds(prev => prev.includes(p.id) ? prev.filter(x => x !== p.id) : [...prev, p.id]); }
+ else if (cd) setSelectedChart({id:p.id,strategy:p.strategy,name:p.name,color:c});
+ }}>
+ <span className="pf-lb-rank">{i < 3 ? medals[i] : (i+1)}</span>
+ <span className="pf-lb-name" style={{color:c}}>
+ <span style={{fontSize:16}}>{stratEmojis[p.strategy]||''}</span>
+ {p.name}
+ </span>
+ <span className="pf-lb-pnl" style={{color: pnl >= 0 ? 'var(--green)' : 'var(--red)'}}>
+ {pnl >= 0 ? '+' : ''}{'$'}{(pnl / 100).toFixed(2)}
+ </span>
+ <span className="pf-lb-invested">{'$'}{(invested / 100).toFixed(2)}</span>
+ <span className="pf-lb-roi" style={{
+ background: roi > 0 ? 'rgba(34,197,94,.12)' : roi < 0 ? 'rgba(239,68,68,.12)' : 'rgba(255,255,255,.04)',
+ color: roi > 0 ? 'var(--green)' : roi < 0 ? 'var(--red)' : 'var(--muted)'
+ }}>{roi > 0 ? '+' : ''}{roi}%</span>
+ <span className="pf-lb-wl" style={{color:'var(--green)'}}>{p.trades_won}</span>
+ <span className="pf-lb-wl" style={{color:'var(--red)'}}>{p.trades_lost}</span>
+ <span style={{fontVariantNumeric:'tabular-nums',color:'var(--muted)'}}>
+ {openCount > 0 ? <span>{openCount} <span style={{fontSize:8,color:'var(--green)'}}>OPEN</span></span> : <span style={{color:'var(--muted)'}}>0</span>}
+ {resolved > 0 && <span style={{marginLeft:4,fontSize:9}}>+{resolved}</span>}
+ </span>
+ <span style={{fontSize:9,color:'var(--muted)',overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}} title={stratDesc[p.strategy]}>
+ {p.strategy}
+ </span>
+ <span style={{display:'flex',alignItems:'center',justifyContent:'center'}}>
+ {miniPts && miniPts.length >= 2 ? <MiniChart data={miniPts} color={c} /> : <span style={{fontSize:9,color:'var(--muted)'}}>--</span>}
+ </span>
+ </div>);
+ })}
+ </div>
+ </div>
+
+ {/* ═══ Overlap Analysis ═══ */}
+ {overlaps.length > 0 && <div className="pf-overlap">
+ <div className="pf-overlap-title">
+ ⚠️ Strategy Overlap — Markets with 2+ models
+ </div>
+ <div style={{display:'flex',flexDirection:'column',gap:4}}>
+ {overlaps.slice(0, 8).map((o, i) => (
+ <div key={i} style={{display:'flex',alignItems:'center',gap:8,fontSize:10,padding:'4px 0'}}>
+ <span style={{fontWeight:700,color:'var(--yellow)',minWidth:20}}>{o.num_strategies}x</span>
+ <span style={{fontWeight:600,minWidth:180,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>{o.market_id}</span>
+ <span style={{color:'var(--muted)',flex:1,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>
+ {(o.portfolios || []).join(', ')}
+ </span>
+ <span style={{fontVariantNumeric:'tabular-nums',color:'var(--muted)'}}>{'$'}{((o.total_exposure || 0) / 100).toFixed(2)}</span>
+ </div>
+ ))}
+ </div>
+ </div>}
+
+ {/* ═══ SWOT Trade Intelligence ═══ */}
+ {swotData && swotData.markets && swotData.markets.length > 0 && <div className="swot-section">
+ <div style={{fontSize:13,fontWeight:700,textTransform:'uppercase',letterSpacing:.5,marginBottom:12,color:'var(--purple)',display:'flex',alignItems:'center',gap:8}}>
+ Trade Intelligence & SWOT
+ <span style={{fontSize:9,fontWeight:400,color:'var(--muted)',textTransform:'none',letterSpacing:0}}>{swotData.markets.length} active markets • {swotData.total_trades} trades this week</span>
+ </div>
+ {swotData.markets.map((m, idx) => {
+ const isOpen = swotExpanded[m.market_id];
+ return (<div key={m.market_id} className="swot-card">
+ <div className="swot-card-header" onClick={() => setSwotExpanded(prev => ({...prev, [m.market_id]: !prev[m.market_id]}))}>
+ <span style={{fontSize:16,fontWeight:900,color:'var(--muted)',minWidth:24}}>{idx+1}</span>
+ <span style={{padding:'2px 8px',borderRadius:4,fontSize:9,fontWeight:800,
+ background: m.direction === 'BUY_YES' ? 'rgba(34,197,94,.15)' : 'rgba(239,68,68,.15)',
+ color: m.direction === 'BUY_YES' ? 'var(--green)' : 'var(--red)'
+ }}>{m.direction === 'BUY_YES' ? 'YES' : 'NO'}</span>
+ <span style={{flex:1,fontWeight:700,fontSize:11,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}} title={m.title}>{m.title}</span>
+ <span style={{fontSize:10,color:'var(--cyan)',fontWeight:700}}>{m.model_count} models</span>
+ <span style={{fontSize:10,fontWeight:700,color:m.edge >= 10 ? 'var(--green)' : 'var(--yellow)'}}>{m.edge.toFixed(1)}% edge</span>
+ <span style={{fontSize:10,fontVariantNumeric:'tabular-nums',color:'var(--muted)'}}>{'$'}{(m.total_cost / 100).toFixed(2)}</span>
+ <span style={{fontSize:10,fontWeight:700,color: m.open_count > 0 ? 'var(--green)' : 'var(--muted)'}}>{m.open_count > 0 ? m.open_count + ' OPEN' : 'CLOSED'}</span>
+ <span style={{fontSize:14,color:'var(--muted)',transform:isOpen?'rotate(180deg)':'rotate(0)',transition:'transform .2s'}}>▼</span>
+ </div>
+ {isOpen && <div>
+ <div className="swot-grid">
+ <div className="swot-quadrant swot-quadrant-s">
+ <div className="swot-q-title" style={{color:'var(--green)'}}>Strengths</div>
+ {m.swot.strengths.map((s, i) => <div key={i} className="swot-q-item">{s}</div>)}
+ </div>
+ <div className="swot-quadrant swot-quadrant-w">
+ <div className="swot-q-title" style={{color:'var(--red)'}}>Weaknesses</div>
+ {m.swot.weaknesses.map((w, i) => <div key={i} className="swot-q-item">{w}</div>)}
+ </div>
+ <div className="swot-quadrant swot-quadrant-o">
+ <div className="swot-q-title" style={{color:'var(--blue)'}}>Opportunities</div>
+ {m.swot.opportunities.map((o, i) => <div key={i} className="swot-q-item">{o}</div>)}
+ </div>
+ <div className="swot-quadrant swot-quadrant-t">
+ <div className="swot-q-title" style={{color:'var(--yellow)'}}>Threats</div>
+ {m.swot.threats.map((t, i) => <div key={i} className="swot-q-item">{t}</div>)}
+ </div>
+ </div>
+ <div style={{padding:'8px 16px',fontSize:10,color:'var(--muted)',lineHeight:1.5,borderTop:'1px solid rgba(255,255,255,.03)'}}>
+ <strong style={{color:'var(--text)'}}>Signal:</strong> {m.reasoning}
+ </div>
+ <div style={{padding:'4px 16px 6px',fontSize:10,color:'var(--muted)',display:'flex',gap:16,flexWrap:'wrap'}}>
+ <span>Conf: <strong style={{color:'var(--cyan)'}}>{Math.round(m.confidence * 100)}%</strong></span>
+ <span>Entry: <strong>{m.entry_price}¢</strong></span>
+ {m.mc_mean > 0 && <span>MC: <strong>{m.mc_mean.toFixed(1)}% ±{m.mc_std.toFixed(1)}%</strong></span>}
+ {m.articles > 0 && <span>News: <strong>{m.articles} articles</strong></span>}
+ {m.agreement > 0 && <span>Agree: <strong>{m.agreement}%</strong></span>}
+ </div>
+ <div className="swot-models">
+ {m.trades.map((t, i) => (
+ <span key={i} className="swot-model-tag" style={{color:stratColors[t.strategy]||'var(--muted)',borderColor:(stratColors[t.strategy]||'var(--border)')+'40'}}>
+ {stratEmojis[t.strategy]||''} {t.portfolio} • {t.contracts}x • {t.status === 'open' ? 'OPEN' : (t.pnl >= 0 ? '+' : '') + '$' + (t.pnl / 100).toFixed(2)}
+ </span>
+ ))}
+ </div>
+ </div>}
+ </div>);
+ })}
+ </div>}
+
+ {/* ═══ Trade History ═══ */}
+ <div className="pf-history">
+ <div className="pf-history-header">
+ <span style={{fontSize:13,fontWeight:700,textTransform:'uppercase',letterSpacing:.5,color:'var(--cyan)'}}>Trade History</span>
+ <div style={{display:'flex',gap:4}}>
+ <button onClick={() => setHistFilter('all')} style={{padding:'3px 10px',borderRadius:6,border:'1px solid '+(histFilter==='all'?'var(--cyan)':'var(--border)'),background:histFilter==='all'?'rgba(6,182,212,.1)':'transparent',color:histFilter==='all'?'var(--cyan)':'var(--muted)',fontSize:10,fontWeight:600,cursor:'pointer'}}>All</button>
+ {portfolios.filter(p => parseInt(p.total_invested_cents) > 0).map(p => (
+ <button key={p.strategy} onClick={() => setHistFilter(p.strategy)} style={{padding:'3px 10px',borderRadius:6,border:'1px solid '+(histFilter===p.strategy?stratColors[p.strategy]:'var(--border)'),background:histFilter===p.strategy?stratColors[p.strategy]+'18':'transparent',color:histFilter===p.strategy?stratColors[p.strategy]:'var(--muted)',fontSize:10,fontWeight:600,cursor:'pointer'}}>
+ {stratEmojis[p.strategy] || ''} {p.name}
+ </button>
+ ))}
+ </div>
+ </div>
+ <div className="pf-history-list">
+ {filteredHistory.length === 0 && <div style={{textAlign:'center',padding:30,color:'var(--muted)',fontSize:12}}>No trades for this filter</div>}
+ {filteredHistory.slice(0, 100).map((t, i) => {
+ const c = stratColors[t.strategy] || 'var(--muted)';
+ const pnl = parseInt(t.pnl_cents) || 0;
+ return (<div key={i} className="pf-history-row">
+ <span style={{width:6,height:6,borderRadius:'50%',flexShrink:0,background:
+ t.status === 'open' ? 'var(--green)' : t.status === 'won' ? 'var(--blue)' : t.status === 'lost' ? 'var(--red)' : 'var(--muted)'
+ }} />
+ <span style={{minWidth:60,fontWeight:700,color:c,fontSize:10}}>{t.portfolio_name}</span>
+ <span style={{padding:'1px 6px',borderRadius:3,fontSize:9,fontWeight:700,
+ background: t.direction === 'BUY_YES' ? 'rgba(34,197,94,.12)' : 'rgba(239,68,68,.12)',
+ color: t.direction === 'BUY_YES' ? 'var(--green)' : 'var(--red)'
+ }}>{t.direction === 'BUY_YES' ? 'YES' : 'NO'}</span>
+ <span style={{flex:1,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap',color:'var(--text)'}} title={t.market_title || t.market_id}>
+ {t.market_title || t.market_id}
+ </span>
+ <span style={{fontVariantNumeric:'tabular-nums',color:'var(--muted)',fontSize:10}}>
+ {t.contracts}x @ {t.entry_price_cents}¢
+ </span>
+ <span style={{fontVariantNumeric:'tabular-nums',color:'var(--muted)',fontSize:10,minWidth:45,textAlign:'right'}}>
+ {'$'}{(t.cost_cents / 100).toFixed(2)}
+ </span>
+ <span style={{fontWeight:800,fontVariantNumeric:'tabular-nums',minWidth:55,textAlign:'right',fontSize:10,
+ color: t.status === 'open' ? 'var(--yellow)' : pnl >= 0 ? 'var(--green)' : 'var(--red)'
+ }}>
+ {t.status === 'open' ? 'OPEN' : (pnl >= 0 ? '+' : '') + (pnl / 100).toFixed(2)}
+ </span>
+ <span style={{fontSize:9,color:'var(--muted)',minWidth:55,textAlign:'right'}}>{timeAgo(t.created_at)}</span>
+ </div>);
+ })}
+ </div>
+ </div>
+
+ {/* ═══ FullChart Modal ═══ */}
+ {selectedChart && chartData[selectedChart.id] && <FullChart
+ chartData={chartData[selectedChart.id]}
+ portfolioId={selectedChart.id}
+ strategy={selectedChart.strategy}
+ name={selectedChart.name}
+ color={selectedChart.color || stratColors[selectedChart.strategy] || '#8b5cf6'}
+ emoji={stratEmojis[selectedChart.strategy] || ''}
+ desc={stratDesc[selectedChart.strategy] || ''}
+ onClose={() => setSelectedChart(null)}
+ />}
+
+ {/* ═══ Comparison Chart Modal ═══ */}
+ {compareMode === 'show' && compareIds.length >= 2 && <ComparisonChart
+ portfolioIds={compareIds}
+ allChartData={chartData}
+ stratColors={stratColors}
+ stratNames={stratNames}
+ stratEmojis={stratEmojis}
+ onClose={() => { setCompareMode(false); setCompareIds([]); }}
+ />}
+
+ {/* ═══ Strategy Guide ═══ */}
+ <div style={{marginTop:18,padding:16,background:'var(--card)',border:'1px solid var(--border)',borderRadius:14}}>
+ <div style={{fontSize:11,fontWeight:700,color:'var(--muted)',textTransform:'uppercase',letterSpacing:.5,marginBottom:10}}>Strategy Guide</div>
+ <div style={{display:'grid',gridTemplateColumns:'repeat(auto-fill,minmax(280px,1fr))',gap:6}}>
+ {Object.entries(stratDesc).map(([strat, desc]) => (
+ <div key={strat} style={{display:'flex',alignItems:'flex-start',gap:8,fontSize:10,padding:'4px 0',color:'var(--muted)'}}>
+ <span style={{fontSize:14,flexShrink:0}}>{stratEmojis[strat]||''}</span>
+ <div>
+ <span style={{fontWeight:700,color:stratColors[strat]}}>{stratNames[strat]}</span>
+ <span style={{margin:'0 4px'}}>—</span>
+ {desc}
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+ </div>);
+}
+
+// ── PREDICTIONS TAB ──
+function PredictionsTab() {
+ const [data, setData] = useState(null);
+ useEffect(() => {
+ api('/api/predictions-history').then(setData).catch(()=>{});
+ const iv = setInterval(() => api('/api/predictions-history').then(setData).catch(()=>{}), 30000);
+ return () => clearInterval(iv);
+ }, []);
+ if (!data) return <div style={{textAlign:'center',padding:40,color:'var(--muted)'}}>Loading predictions...</div>;
+
+ const statsMap = {};
+ (data.stats||[]).forEach(s => { statsMap[s.outcome] = s; });
+
+ return (<div>
+ <div style={{display:'flex',gap:12,marginBottom:20,flexWrap:'wrap'}}>
+ {['win','loss','expired'].map(o => {
+ const s = statsMap[o]||{cnt:0,avg_pnl:0,avg_conf:0};
+ const c = o==='win'?'var(--green)':o==='loss'?'var(--red)':'var(--muted)';
+ return (<div key={o} style={{background:'var(--card)',border:'1px solid var(--border)',borderRadius:12,padding:16,flex:1,minWidth:140,textAlign:'center'}}>
+ <div style={{fontSize:28,fontWeight:700,color:c}}>{s.cnt}</div>
+ <div style={{fontSize:10,color:'var(--muted)',textTransform:'uppercase',letterSpacing:1,marginTop:2}}>{o==='win'?'Wins':o==='loss'?'Losses':'Expired'}</div>
+ <div style={{fontSize:11,color:'var(--muted)',marginTop:4}}>Avg P&L: <strong style={{color:c}}>{parseFloat(s.avg_pnl||0)>0?'+':''}{s.avg_pnl||0}¢</strong></div>
+ <div style={{fontSize:11,color:'var(--muted)'}}>Avg Conf: {s.avg_conf||0}%</div>
+ </div>);
+ })}
+ <div style={{background:'var(--card)',border:'1px solid var(--border)',borderRadius:12,padding:16,flex:1,minWidth:140,textAlign:'center'}}>
+ <div style={{fontSize:28,fontWeight:700,color:'var(--blue)'}}>{statsMap.win?Math.round(parseInt(statsMap.win.cnt)/(parseInt(statsMap.win.cnt)+parseInt(statsMap.loss?.cnt||0))*100):0}%</div>
+ <div style={{fontSize:10,color:'var(--muted)',textTransform:'uppercase',letterSpacing:1,marginTop:2}}>Win Rate</div>
+ <div style={{fontSize:11,color:'var(--muted)',marginTop:4}}>W/L only (excl. expired)</div>
+ </div>
+ </div>
+
+ <h3 style={{fontSize:14,fontWeight:600,marginBottom:10,display:'flex',alignItems:'center',gap:8}}>Resolved Predictions <span style={{fontSize:11,color:'var(--muted)',fontWeight:400}}>— what actually happened</span></h3>
+ <div style={{display:'flex',flexDirection:'column',gap:4}}>
+ {(data.predictions||[]).slice(0,30).map((p,i) => {
+ const oc = p.outcome==='win'?'var(--green)':p.outcome==='loss'?'var(--red)':'var(--muted)';
+ return (<div key={i} style={{display:'flex',alignItems:'center',gap:10,padding:'8px 14px',background:'var(--card)',border:'1px solid var(--border)',borderRadius:8,fontSize:12}}>
+ <span style={{padding:'2px 8px',borderRadius:4,fontWeight:700,fontSize:10,background:p.outcome==='win'?'rgba(34,197,94,.15)':p.outcome==='loss'?'rgba(239,68,68,.15)':'rgba(255,255,255,.05)',color:oc,minWidth:48,textAlign:'center',textTransform:'uppercase'}}>{p.outcome}</span>
+ <span style={{padding:'2px 8px',borderRadius:4,fontSize:10,fontWeight:600,background:p.side==='YES'||p.side==='yes'?'rgba(34,197,94,.1)':'rgba(239,68,68,.1)',color:p.side==='YES'||p.side==='yes'?'var(--green)':'var(--red)'}}>{p.side}</span>
+ <span style={{flex:1,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}} title={p.title}>{p.title||p.ticker}</span>
+ <span style={{fontVariantNumeric:'tabular-nums',color:'var(--muted)',fontSize:11}}>Conf:{p.confidence}%</span>
+ <span style={{fontVariantNumeric:'tabular-nums',color:'var(--muted)',fontSize:11}}>{p.entry_price}¢→{p.exit_price||'?'}¢</span>
+ <span style={{fontWeight:700,fontVariantNumeric:'tabular-nums',color:oc,minWidth:45,textAlign:'right'}}>{p.pnl_cents>0?'+':''}{p.pnl_cents||0}¢</span>
+ <span style={{fontSize:10,color:'var(--muted)',minWidth:70,textAlign:'right'}}>{p.resolved_at?new Date(p.resolved_at).toLocaleDateString('en-US',{month:'short',day:'numeric'}):''}</span>
+ </div>);
+ })}
+ </div>
+ </div>);
+}
+
+// ── Sparkline SVG Component ──
+function Sparkline({ data, width = 120, height = 30, color = '#8b5cf6', showDots = false, showArea = true, label }) {
+ if (!data || data.length < 2) return null;
+ const max = Math.max(...data);
+ const min = Math.min(...data);
+ const range = max - min || 1;
+ const gradId = 'grad-' + color.replace('#','') + '-' + width;
+ const points = data.map((v, i) => {
+ const x = (i / (data.length - 1)) * width;
+ const y = height - ((v - min) / range) * (height - 6) - 3;
+ return x + ',' + y;
+ }).join(' ');
+ const areaPoints = points + ' ' + width + ',' + height + ' 0,' + height;
+ const lastVal = data[data.length - 1];
+ const prevVal = data[data.length - 2];
+ const trending = lastVal >= prevVal;
+ return (
+ <div style={{position:'relative'}}>
+ <svg className="sparkline-svg" width={width} height={height} viewBox={'0 0 ' + width + ' ' + height}>
+ <defs><linearGradient id={gradId} x1="0" y1="0" x2="0" y2="1">
+ <stop offset="0%" stopColor={color} stopOpacity="0.25"/><stop offset="100%" stopColor={color} stopOpacity="0.01"/>
+ </linearGradient></defs>
+ {showArea && <polygon points={areaPoints} fill={'url(#' + gradId + ')'} />}
+ <polyline points={points} fill="none" stroke={color} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
+ {showDots && data.map((v, i) => {
+ const x = (i / (data.length - 1)) * width;
+ const y = height - ((v - min) / range) * (height - 6) - 3;
+ return <circle key={i} cx={x} cy={y} r={i === data.length - 1 ? 3 : 1.5} fill={i === data.length - 1 ? color : 'transparent'} stroke={color} strokeWidth={i === data.length - 1 ? 0 : 0.5} opacity={i === data.length - 1 ? 1 : 0.5} />;
+ })}
+ </svg>
+ {label && <div style={{position:'absolute',top:2,right:4,fontSize:9,color:trending?'var(--green)':'var(--red)',fontWeight:700}}>
+ {trending?'▲':'▼'} {lastVal.toLocaleString()}
+ </div>}
+ </div>
+ );
+}
+
+// ── MiniChart: Canvas-based sparkline for leaderboard rows ──
+function MiniChart({ data, color, width = 140, height = 36 }) {
+ const canvasRef = React.useRef(null);
+ const chartRef = React.useRef(null);
+ React.useEffect(() => {
+ if (!data || data.length < 2 || !canvasRef.current) return;
+ if (chartRef.current) chartRef.current.destroy();
+ const ctx = canvasRef.current.getContext('2d');
+ const gradient = ctx.createLinearGradient(0, 0, 0, height);
+ gradient.addColorStop(0, color + '40');
+ gradient.addColorStop(1, color + '05');
+ chartRef.current = new Chart(ctx, {
+ type: 'line',
+ data: { labels: data.map((_, i) => i), datasets: [{ data, borderColor: color, borderWidth: 1.5, backgroundColor: gradient, fill: true, pointRadius: 0, tension: 0.4 }] },
+ options: { responsive: false, animation: { duration: 800, easing: 'easeOutQuart' }, plugins: { legend: { display: false }, tooltip: { enabled: false } }, scales: { x: { display: false }, y: { display: false } } }
+ });
+ return () => { if (chartRef.current) chartRef.current.destroy(); };
+ }, [data, color]);
+ return <canvas ref={canvasRef} width={width} height={height} style={{borderRadius:4}} />;
+}
+
+// ── FullChart: Modal chart for a single portfolio with period selector ──
+function FullChart({ chartData: initialData, portfolioId, strategy, name, color, emoji, desc, onClose }) {
+ const canvasRef = React.useRef(null);
+ const chartRef = React.useRef(null);
+ const clr = color || '#8b5cf6';
+ const [period, setPeriod] = React.useState('7d');
+ const [liveData, setLiveData] = React.useState(initialData);
+ const periods = ['1d','3d','7d','14d','30d'];
+
+ React.useEffect(() => {
+ if (period === '7d') { setLiveData(initialData); return; }
+ api('/api/portfauxlio/charts?period=' + period).then(d => {
+ const match = (d.portfolios || []).find(p => p.id === portfolioId);
+ if (match) setLiveData(match);
+ }).catch(() => {});
+ }, [period, portfolioId]);
+
+ React.useEffect(() => {
+ const cd = liveData || initialData;
+ const snaps = cd?.snapshots || [];
+ const daily = cd?.daily || [];
+ const dataPoints = snaps.length > 1 ? snaps.map(s => ({ x: new Date(s.time), y: s.nav / 100 }))
+ : daily.length > 1 ? daily.map(d => ({ x: new Date(d.date), y: d.cumulative / 100 })) : [];
+ if (!dataPoints.length || !canvasRef.current) return;
+ if (chartRef.current) chartRef.current.destroy();
+ const ctx = canvasRef.current.getContext('2d');
+ const gradient = ctx.createLinearGradient(0, 0, 0, 300);
+ gradient.addColorStop(0, clr + '30');
+ gradient.addColorStop(1, clr + '02');
+ const zeroLine = { id: 'zeroLine', beforeDraw(chart) {
+ const yScale = chart.scales.y;
+ if (!yScale) return;
+ const y0 = yScale.getPixelForValue(0);
+ if (y0 < yScale.top || y0 > yScale.bottom) return;
+ const cctx = chart.ctx;
+ cctx.save();
+ cctx.strokeStyle = 'rgba(255,255,255,0.15)';
+ cctx.lineWidth = 1;
+ cctx.setLineDash([4, 4]);
+ cctx.beginPath();
+ cctx.moveTo(chart.chartArea.left, y0);
+ cctx.lineTo(chart.chartArea.right, y0);
+ cctx.stroke();
+ cctx.restore();
+ }};
+ chartRef.current = new Chart(ctx, {
+ type: 'line',
+ data: { datasets: [{ label: 'NAV', data: dataPoints, borderColor: clr, borderWidth: 2, backgroundColor: gradient, fill: true, pointRadius: dataPoints.length > 50 ? 0 : 2, pointHoverRadius: 6, pointBackgroundColor: clr, tension: 0.3 }] },
+ plugins: [zeroLine],
+ options: {
+ responsive: true, maintainAspectRatio: false,
+ animation: { duration: 1200, easing: 'easeInOutQuart' },
+ interaction: { intersect: false, mode: 'index' },
+ plugins: {
+ legend: { display: false },
+ tooltip: { backgroundColor: 'rgba(15,15,35,0.95)', borderColor: clr + '60', borderWidth: 1, titleColor: '#e2e8f0', bodyColor: '#e2e8f0', padding: 12, displayColors: false,
+ callbacks: { label: (tipCtx) => 'NAV: ' + (tipCtx.parsed.y >= 0 ? '+' : '') + '$' + tipCtx.parsed.y.toFixed(2) }
+ }
+ },
+ scales: {
+ x: { type: 'time', time: { unit: snaps.length > 1 ? 'hour' : 'day' }, ticks: { color: '#64748b', maxRotation: 45, font: { size: 9 } }, grid: { color: 'rgba(255,255,255,.03)' } },
+ y: { ticks: { color: '#64748b', callback: (v) => '$' + v.toFixed(0), font: { size: 10 } }, grid: { color: 'rgba(255,255,255,.05)' } }
+ }
+ }
+ });
+ return () => { if (chartRef.current) chartRef.current.destroy(); };
+ }, [liveData, strategy, clr]);
+ return (
+ <div className="chart-modal" onClick={onClose}>
+ <div className="chart-modal-content" onClick={e => e.stopPropagation()}>
+ <div className="chart-modal-header">
+ <span style={{fontSize:18}}>{emoji||''}</span>
+ <span style={{fontWeight:800,color:clr}}>{name || strategy}</span>
+ <span style={{fontSize:10,color:'var(--muted)',flex:1}}>{desc||''}</span>
+ <div className="chart-period-btns">
+ {periods.map(p => (
+ <button key={p} className={period === p ? 'chart-period-active' : 'chart-period'} onClick={() => setPeriod(p)}>{p}</button>
+ ))}
+ </div>
+ <button className="chart-close" onClick={onClose}>✕</button>
+ </div>
+ <div style={{height:340,position:'relative'}}><canvas ref={canvasRef} /></div>
+ </div>
+ </div>
+ );
+}
+
+// ── ComparisonChart: Overlay multiple portfolios on one chart ──
+function ComparisonChart({ portfolioIds, allChartData, stratColors, stratNames, stratEmojis, onClose }) {
+ const canvasRef = React.useRef(null);
+ const chartRef = React.useRef(null);
+ const [period, setPeriod] = React.useState('7d');
+ const [compareData, setCompareData] = React.useState(allChartData);
+ const periods = ['1d','3d','7d','14d','30d'];
+
+ React.useEffect(() => {
+ if (period === '7d') { setCompareData(allChartData); return; }
+ api('/api/portfauxlio/charts?period=' + period).then(d => {
+ const byId = {};
+ (d.portfolios || []).forEach(p => { byId[p.id] = p; });
+ setCompareData(byId);
+ }).catch(() => {});
+ }, [period]);
+
+ React.useEffect(() => {
+ if (!canvasRef.current) return;
+ if (chartRef.current) chartRef.current.destroy();
+ const datasets = portfolioIds.map(id => {
+ const cd = compareData[id];
+ if (!cd) return null;
+ const strat = cd.strategy || '';
+ const clr = stratColors[strat] || '#8b5cf6';
+ const snaps = cd.snapshots || [];
+ const daily = cd.daily || [];
+ const pts = snaps.length > 1 ? snaps.map(s => ({ x: new Date(s.time), y: s.nav / 100 }))
+ : daily.length > 1 ? daily.map(d => ({ x: new Date(d.date), y: d.cumulative / 100 })) : [];
+ if (pts.length < 2) return null;
+ return { label: (stratEmojis[strat]||'') + ' ' + (cd.name || strat), data: pts, borderColor: clr, borderWidth: 2, backgroundColor: 'transparent', fill: false, pointRadius: 0, pointHoverRadius: 5, tension: 0.3 };
+ }).filter(Boolean);
+ if (!datasets.length) return;
+ const ctx = canvasRef.current.getContext('2d');
+ chartRef.current = new Chart(ctx, {
+ type: 'line', data: { datasets },
+ options: {
+ responsive: true, maintainAspectRatio: false,
+ animation: { duration: 1000, easing: 'easeOutQuart' },
+ interaction: { intersect: false, mode: 'index' },
+ plugins: {
+ legend: { display: true, position: 'bottom', labels: { color: '#94a3b8', font: { size: 10 }, boxWidth: 12, padding: 8 } },
+ tooltip: { backgroundColor: 'rgba(15,15,35,0.95)', borderWidth: 1, titleColor: '#e2e8f0', bodyColor: '#e2e8f0', padding: 12 }
+ },
+ scales: {
+ x: { type: 'time', ticks: { color: '#64748b', maxRotation: 45, font: { size: 9 } }, grid: { color: 'rgba(255,255,255,.03)' } },
+ y: { ticks: { color: '#64748b', callback: (v) => '$' + v.toFixed(0), font: { size: 10 } }, grid: { color: 'rgba(255,255,255,.05)' } }
+ }
+ }
+ });
+ return () => { if (chartRef.current) chartRef.current.destroy(); };
+ }, [compareData, portfolioIds]);
+
+ return (
+ <div className="chart-modal" onClick={onClose}>
+ <div className="chart-modal-content" onClick={e => e.stopPropagation()} style={{maxWidth:1100}}>
+ <div className="chart-modal-header">
+ <span style={{fontSize:16}}>📊</span>
+ <span style={{fontWeight:800,color:'var(--cyan)'}}>Compare {portfolioIds.length} Portfolios</span>
+ <div className="chart-period-btns" style={{marginLeft:'auto'}}>
+ {periods.map(p => (
+ <button key={p} className={period === p ? 'chart-period-active' : 'chart-period'} onClick={() => setPeriod(p)}>{p}</button>
+ ))}
+ </div>
+ <button className="chart-close" onClick={onClose}>✕</button>
+ </div>
+ <div style={{height:400,position:'relative'}}><canvas ref={canvasRef} /></div>
+ </div>
+ </div>
+ );
+}
+
+// ── Vertical Bar Chart ──
+function BarChart({ data, maxVal, height = 80, color = '#8b5cf6' }) {
+ if (!data || data.length === 0) return null;
+ const mx = maxVal || Math.max(...data.map(d => d.value)) || 1;
+ return (
+ <div className="mkt-bar-chart" style={{ height }}>
+ {data.map((d, i) => (
+ <div key={i} className="mkt-bar" style={{ height: Math.max(2, (d.value / mx) * height) + 'px', background: d.color || color, opacity: 0.7 + (d.value / mx) * 0.3 }}>
+ <div className="mkt-bar-label">{d.label}: {d.value}</div>
+ </div>
+ ))}
+ </div>
+ );
+}
+
+// ── Confidence Histogram ──
+function ConfHistogram({ data }) {
+ if (!data || data.length === 0) return null;
+ const max = Math.max(...data.map(d => d.count)) || 1;
+ const colors = ['#ef4444','#f97316','#f59e0b','#eab308','#84cc16','#22c55e','#14b8a6','#06b6d4','#3b82f6','#8b5cf6'];
+ return (
+ <div className="histogram">
+ {data.map((d, i) => (
+ <div key={i} className="hist-bar" style={{
+ height: Math.max(2, (d.count / max) * 70) + 'px',
+ background: colors[i] || 'var(--muted)',
+ opacity: d.count > 0 ? 0.8 : 0.2,
+ }}>
+ <div className="hist-label">{d.range}</div>
+ </div>
+ ))}
+ </div>
+ );
+}
+
+// ── Time ago helper ──
+function timeAgo(ts) {
+ if (!ts) return '';
+ const diff = Date.now() - new Date(ts).getTime();
+ if (diff < 60000) return Math.floor(diff / 1000) + 's ago';
+ if (diff < 3600000) return Math.floor(diff / 60000) + 'm ago';
+ if (diff < 86400000) return Math.floor(diff / 3600000) + 'h ago';
+ return Math.floor(diff / 86400000) + 'd ago';
+}
+
+// ── Market Data Tab — Bloomberg-style terminal ──
+function MarketDataTab() {
+ const [mkt, setMkt] = useState(null);
+ const [tick, setTick] = useState(0);
+
+ useEffect(() => {
+ const load = () => api('/api/inc/market-data').then(setMkt).catch(e => console.error(e));
+ load();
+ const iv = setInterval(load, 8000);
+ return () => clearInterval(iv);
+ }, []);
+ useEffect(() => { const iv = setInterval(() => setTick(t => t + 1), 1000); return () => clearInterval(iv); }, []);
+
+ if (!mkt) return <div style={{textAlign:'center',padding:60,color:'var(--muted)'}}>
+ <div style={{fontSize:24,marginBottom:8,animation:'avatarFloat 2s ease-in-out infinite'}}>Loading market data...</div>
+ </div>;
+
+ const signalVals = (mkt.signalTrend || []).map(s => s.signals);
+ const edgeVals = (mkt.signalTrend || []).map(s => s.avgEdge * 100);
+ const sentVals = (mkt.sentimentTrend || []).map(s => s.articles);
+ const sentScoreVals = (mkt.sentimentTrend || []).map(s => s.avgSentiment);
+ const totalSent24h = sentVals.reduce((a, b) => a + b, 0);
+ const totalSignals = signalVals.reduce((a, b) => a + b, 0);
+ const at = mkt.approvalTrend || {};
+ const changeArrow = at.change > 0 ? '▲' : at.change < 0 ? '▼' : '—';
+ const changeClass = at.change > 0 ? 'up' : at.change < 0 ? 'down' : 'flat';
+ const totalPnl = (mkt.portfolios || []).reduce((s, p) => s + (p.pnl_cents || 0), 0);
+ const totalTrades = (mkt.portfolios || []).reduce((s, p) => s + (p.total_trades || 0), 0);
+ const avgEdge = edgeVals.length > 0 ? (edgeVals.reduce((a,b)=>a+b,0) / edgeVals.length) : 0;
+
+ // Ticker items
+ const tickerItems = [
+ { label: 'P&L', value: (totalPnl >= 0 ? '+' : '') + (totalPnl / 100).toFixed(2), color: totalPnl >= 0 ? 'var(--green)' : 'var(--red)' },
+ { label: 'SIGNALS', value: totalSignals, color: 'var(--blue)' },
+ { label: 'APPROVAL', value: at.current + '%', change: at.change, color: 'var(--green)' },
+ { label: 'SENTIMENT', value: totalSent24h.toLocaleString(), color: 'var(--pink)' },
+ { label: 'AVG EDGE', value: avgEdge.toFixed(1) + '%', color: 'var(--purple)' },
+ { label: 'TRADES', value: totalTrades, color: 'var(--yellow)' },
+ { label: 'MARKETS', value: mkt.activeMarkets, color: 'var(--cyan)' },
+ { label: 'GEMINI', value: mkt.gemini.callsToday + '/' + mkt.gemini.dailyLimit, color: 'var(--teal)' },
+ ];
+ const doubledTicker = tickerItems.concat(tickerItems);
+
+ const stratColors = {aggressive:'#ef4444',conservative:'#3b82f6',weather:'#06b6d4',momentum:'#f59e0b',contrarian:'#8b5cf6',ai_enhanced:'#ec4899',mc_validated:'#a855f7',scalper:'#eab308',patient:'#22c55e',random:'#64748b',penny_pincher:'#94a3b8',spray_pray:'#fb923c',nickel_slots:'#a78bfa',degen_lite:'#f43f5e',politics_junkie:'#0ea5e9',double_down:'#dc2626',volatility_rider:'#14b8a6',whale:'#1d4ed8',yolo:'#e11d48',full_send:'#b91c1c',kelly_criterion:'#059669',sharpe_sniper:'#7c3aed',bayesian_blend:'#0891b2',ensemble_lock:'#c026d3',mean_revert:'#d97706',info_ratio:'#2563eb',anti_fomo:'#16a34a',nightcrawler:'#4c1d95',heatseeker:'#ea580c',quant_core:'#0d9488',etf_presidential:'#dc143c',etf_cabinet:'#ff6347',etf_congress:'#4169e1',etf_scotus:'#2f4f4f',etf_fed:'#228b22',etf_economy:'#daa520',etf_geopolitics:'#8b0000',etf_territory:'#006400',etf_climate:'#00bfff',etf_energy:'#ff8c00',etf_tech:'#7b68ee',etf_space:'#191970',etf_crypto:'#ffd700',etf_sports:'#32cd32',etf_entertainment:'#ff1493',etf_legal:'#708090',etf_financials:'#4682b4',etf_govreform:'#b22222',etf_global_social:'#9370db',etf_broad_market:'#c0a050'};
+ const stratEmojis = {aggressive:'🔥',conservative:'🏛️',weather:'⛈️',momentum:'🚀',contrarian:'🔄',ai_enhanced:'🧠',mc_validated:'🎲',scalper:'⚡',patient:'🐢',random:'🎰',penny_pincher:'🪙',spray_pray:'💦',nickel_slots:'🎰',degen_lite:'😈',politics_junkie:'🏛️',double_down:'⬆️',volatility_rider:'🏄',whale:'🐳',yolo:'🧨',full_send:'💣',kelly_criterion:'🎰',sharpe_sniper:'🎯',bayesian_blend:'🧮',ensemble_lock:'🔐',mean_revert:'↩️',info_ratio:'📊',anti_fomo:'🧘',nightcrawler:'🦇',heatseeker:'🔬',quant_core:'∑',etf_presidential:'🏛️',etf_cabinet:'💼',etf_congress:'🗳️',etf_scotus:'⚖️',etf_fed:'🏦',etf_economy:'📈',etf_geopolitics:'🌍',etf_territory:'🗺️',etf_climate:'🌡️',etf_energy:'⛽',etf_tech:'🤖',etf_space:'🚀',etf_crypto:'₿',etf_sports:'⚽',etf_entertainment:'🎬',etf_legal:'🔨',etf_financials:'💹',etf_govreform:'✂️',etf_global_social:'⛪',etf_broad_market:'🌐'};
+
+ return (<div>
+ {/* ═══ Hero P&L Banner ═══ */}
+ <div style={{textAlign:'center',padding:'20px 0 8px',borderBottom:'1px solid var(--border)'}}>
+ <div style={{fontSize:10,color:'var(--muted)',textTransform:'uppercase',letterSpacing:2,marginBottom:4}}>Total Portfolio P&L</div>
+ <div className="pnl-hero" style={{color: totalPnl >= 0 ? 'var(--green)' : 'var(--red)', animation: totalPnl !== 0 ? 'pnlPulse 3s ease-in-out infinite' : 'none'}}>
+ {totalPnl >= 0 ? '+' : ''}{(totalPnl / 100).toFixed(2)}
+ </div>
+ <div style={{display:'flex',justifyContent:'center',gap:24,marginTop:8,fontSize:11,color:'var(--muted)'}}>
+ <span>{totalTrades} trades</span>
+ <span>{(mkt.portfolios||[]).filter(p => p.pnl_cents > 0).length} winning</span>
+ <span>{(mkt.portfolios||[]).filter(p => p.pnl_cents < 0).length} losing</span>
+ <span>{avgEdge.toFixed(1)}% avg edge</span>
+ </div>
+ </div>
+
+ {/* ═══ Scrolling Ticker ═══ */}
+ <div className="mkt-ticker-strip">
+ <div className="mkt-ticker-track">
+ {doubledTicker.map((t, i) => (
+ <div key={i} className="mkt-ticker-item">
+ <span style={{color:'var(--muted)',fontSize:9,textTransform:'uppercase',letterSpacing:.5}}>{t.label}</span>
+ <span style={{color:t.color,fontWeight:800}}>{t.value}</span>
+ {t.change !== undefined && <span className={'mkt-change ' + (t.change > 0 ? 'up' : t.change < 0 ? 'down' : 'flat')}>
+ {t.change > 0 ? '▲' : t.change < 0 ? '▼' : ''}{Math.abs(t.change)}%
+ </span>}
+ </div>
+ ))}
+ </div>
+ </div>
+
+ <div className="mkt-grid">
+ {/* ═══ Live Signal Feed ═══ */}
+ <div className="mkt-card" style={{gridColumn:'span 2'}}>
+ <div className="mkt-card-header">
+ <span className="mkt-card-title" style={{color:'var(--blue)'}}>
+ <span style={{display:'inline-block',width:6,height:6,borderRadius:'50%',background:'var(--green)',marginRight:6,animation:'statusPulse 2s ease infinite'}}></span>
+ Live Signal Feed
+ </span>
+ <span className="mkt-card-badge" style={{background:'rgba(59,130,246,.15)',color:'var(--blue)'}}>{(mkt.latestSignals||[]).length} latest</span>
+ </div>
+ <div className="signal-feed">
+ {(mkt.latestSignals || []).map((sig, i) => (
+ <div key={i} className="signal-row">
+ <div className="signal-approved" style={{background: sig.approved ? 'var(--green)' : 'var(--red)'}} title={sig.approved ? 'Approved' : 'Rejected'} />
+ <span className={'signal-dir ' + sig.direction}>{sig.direction}</span>
+ <span className="signal-market" title={sig.market}>{sig.market}</span>
+ <span className="signal-edge" style={{color: sig.edge > 0 ? 'var(--green)' : 'var(--red)'}}>
+ {sig.edge > 0 ? '+' : ''}{(sig.edge * 100).toFixed(1)}%
+ </span>
+ <span className="signal-conf" title="Confidence">{(sig.confidence * 100).toFixed(0)}%</span>
+ <span className="signal-time">{timeAgo(sig.time)}</span>
+ </div>
+ ))}
+ {(!mkt.latestSignals || mkt.latestSignals.length === 0) && <div style={{padding:20,textAlign:'center',color:'var(--muted)',fontSize:12}}>No recent signals</div>}
+ </div>
+ </div>
+
+ {/* ═══ Signal Volume Sparkline ═══ */}
+ <div className="mkt-card">
+ <div className="mkt-card-header">
+ <span className="mkt-card-title" style={{color:'var(--blue)'}}>Signal Volume</span>
+ <span className="mkt-card-badge" style={{background:'rgba(59,130,246,.15)',color:'var(--blue)'}}>{totalSignals}</span>
+ </div>
+ <Sparkline data={signalVals} width={300} height={50} color="#3b82f6" showDots={true} label={true} />
+ <BarChart data={(mkt.signalTrend || []).map((s) => ({
+ value: s.signals,
+ label: new Date(s.hour).toLocaleTimeString('en-US', {hour:'numeric',hour12:true}),
+ color: s.approved > s.signals * 0.5 ? 'rgba(34,197,94,.6)' : 'rgba(239,68,68,.4)',
+ }))} height={45} />
+ </div>
+
+ {/* ═══ Sentiment Flow ═══ */}
+ <div className="mkt-card">
+ <div className="mkt-card-header">
+ <span className="mkt-card-title" style={{color:'var(--pink)'}}>Sentiment Flow</span>
+ <span className="mkt-card-badge" style={{background:'rgba(236,72,153,.15)',color:'var(--pink)'}}>{totalSent24h.toLocaleString()}</span>
+ </div>
+ <Sparkline data={sentVals} width={300} height={50} color="#ec4899" label={true} />
+ <div style={{display:'flex',justifyContent:'space-between',marginTop:8,fontSize:10,color:'var(--muted)'}}>
+ <span>Avg: <strong style={{color: sentScoreVals.length > 0 && sentScoreVals.reduce((a,b)=>a+b,0)/sentScoreVals.length > 0 ? 'var(--green)' : 'var(--red)'}}>
+ {sentScoreVals.length > 0 ? (sentScoreVals.reduce((a,b)=>a+b,0)/sentScoreVals.length).toFixed(3) : '—'}
+ </strong></span>
+ <span>{(mkt.sourceMix||[]).length} sources</span>
+ </div>
+ </div>
+
+ {/* ═══ Approval Rate ═══ */}
+ <div className="mkt-card">
+ <div className="mkt-card-header">
+ <span className="mkt-card-title" style={{color:'var(--green)'}}>Approval Rate</span>
+ <span className={'mkt-change ' + changeClass} style={{fontSize:14}}>{changeArrow} {Math.abs(at.change)}%</span>
+ </div>
+ <div style={{display:'flex',alignItems:'baseline',gap:12,marginBottom:8}}>
+ <span style={{fontSize:42,fontWeight:800,color:'var(--green)',fontVariantNumeric:'tabular-nums'}}>{at.current}%</span>
+ <span style={{fontSize:12,color:'var(--muted)'}}>vs {at.prior}% prior</span>
+ </div>
+ <div className="mkt-gauge">
+ <div className="mkt-gauge-fill" style={{width: at.current + '%', background:'linear-gradient(90deg,var(--green),var(--teal))'}} />
+ <div className="mkt-gauge-label">{at.recentSignals} signals</div>
+ </div>
+ </div>
+
+ {/* ═══ Edge Trend ═══ */}
+ <div className="mkt-card">
+ <div className="mkt-card-header">
+ <span className="mkt-card-title" style={{color:'var(--purple)'}}>Edge Trend</span>
+ <span className="mkt-card-badge" style={{background:'rgba(139,92,246,.15)',color:'var(--purple)'}}>
+ {avgEdge.toFixed(1)}% avg
+ </span>
+ </div>
+ <Sparkline data={edgeVals} width={300} height={50} color="#8b5cf6" showDots={true} label={true} />
+ </div>
+
+ {/* ═══ Market Heatmap ═══ */}
+ {(mkt.marketStats || []).length > 0 && <div className="mkt-card" style={{gridColumn:'span 2'}}>
+ <div className="mkt-card-header">
+ <span className="mkt-card-title" style={{color:'var(--yellow)'}}>Market Heatmap (24h)</span>
+ <span className="mkt-card-badge" style={{background:'rgba(245,158,11,.15)',color:'var(--yellow)'}}>{(mkt.marketStats||[]).length} markets</span>
+ </div>
+ <div className="heatmap-grid">
+ {(mkt.marketStats || []).map((m, i) => {
+ const edge = m.avgEdge * 100;
+ const intensity = Math.min(1, Math.abs(edge) / 25);
+ const bg = edge >= 0
+ ? 'rgba(34,197,94,' + (0.08 + intensity * 0.2) + ')'
+ : 'rgba(239,68,68,' + (0.08 + intensity * 0.2) + ')';
+ const borderC = edge >= 0 ? 'rgba(34,197,94,' + (0.2 + intensity * 0.3) + ')' : 'rgba(239,68,68,' + (0.2 + intensity * 0.3) + ')';
+ return (<div key={i} className="heatmap-cell" style={{background: bg, borderColor: borderC}}>
+ <div className="heatmap-market">{m.market}</div>
+ <div className="heatmap-edge" style={{color: edge >= 0 ? 'var(--green)' : 'var(--red)'}}>
+ {edge >= 0 ? '+' : ''}{edge.toFixed(1)}%
+ </div>
+ <div className="heatmap-meta">{m.signals} sig | {m.approved} appr | {(m.avgConf * 100).toFixed(0)}% conf</div>
+ </div>);
+ })}
+ </div>
+ </div>}
+
+ {/* ═══ Confidence Distribution ═══ */}
+ {(mkt.confDistribution || []).length > 0 && <div className="mkt-card">
+ <div className="mkt-card-header">
+ <span className="mkt-card-title" style={{color:'var(--cyan)'}}>Confidence Distribution</span>
+ </div>
+ <ConfHistogram data={mkt.confDistribution} />
+ <div style={{marginTop:18,display:'flex',justifyContent:'space-between',fontSize:9,color:'var(--muted)'}}>
+ <span>Low conf</span><span>High conf</span>
+ </div>
+ </div>}
+
+ {/* ═══ Intelligence Sources ═══ */}
+ <div className="mkt-card">
+ <div className="mkt-card-header">
+ <span className="mkt-card-title" style={{color:'var(--cyan)'}}>Intelligence Sources</span>
+ <span className="mkt-card-badge" style={{background:'rgba(6,182,212,.15)',color:'var(--cyan)'}}>{(mkt.sourceMix||[]).length}</span>
+ </div>
+ <div className="mkt-source-list">
+ {(mkt.sourceMix || []).slice(0, 12).map((s, i) => {
+ const maxC = (mkt.sourceMix || [])[0]?.count || 1;
+ const colors = ['#3b82f6','#8b5cf6','#ec4899','#ef4444','#f59e0b','#22c55e','#06b6d4','#14b8a6','#6366f1','#d946ef','#f97316','#a855f7'];
+ return (<div key={i} className="mkt-source-row">
+ <span className="mkt-source-name">{s.source}</span>
+ <div style={{flex:1,display:'flex',alignItems:'center',gap:4}}>
+ <div className="mkt-source-bar" style={{width: (s.count / maxC * 100) + '%', background: colors[i % colors.length]}} />
+ </div>
+ <span className="mkt-source-val">{s.count.toLocaleString()}</span>
+ <span style={{fontSize:9,color: s.avgSentiment > 0 ? 'var(--green)' : s.avgSentiment < 0 ? 'var(--red)' : 'var(--muted)', minWidth:35, textAlign:'right'}}>
+ {s.avgSentiment > 0 ? '+' : ''}{s.avgSentiment.toFixed(2)}
+ </span>
+ </div>);
+ })}
+ </div>
+ </div>
+
+ {/* ═══ Gemini + Categories row ═══ */}
+ <div className="mkt-card">
+ <div className="mkt-card-header">
+ <span className="mkt-card-title" style={{color:'var(--teal)'}}>Gemini AI</span>
+ <span className="mkt-card-badge" style={{background: mkt.gemini.pctUsed > 80 ? 'rgba(239,68,68,.15)' : 'rgba(20,184,166,.15)', color: mkt.gemini.pctUsed > 80 ? 'var(--red)' : 'var(--teal)'}}>
+ {mkt.gemini.pctUsed}%
+ </span>
+ </div>
+ <div style={{display:'flex',alignItems:'baseline',gap:8,marginBottom:8}}>
+ <span style={{fontSize:32,fontWeight:800,color:'var(--teal)',fontVariantNumeric:'tabular-nums'}}>{mkt.gemini.callsToday}</span>
+ <span style={{fontSize:11,color:'var(--muted)'}}>/ {mkt.gemini.dailyLimit}</span>
+ </div>
+ <div className="mkt-gauge">
+ <div className="mkt-gauge-fill" style={{width: mkt.gemini.pctUsed + '%', background: mkt.gemini.pctUsed > 80 ? 'linear-gradient(90deg,var(--yellow),var(--red))' : 'linear-gradient(90deg,var(--teal),var(--cyan))'}} />
+ <div className="mkt-gauge-label">{mkt.gemini.pctUsed}%</div>
+ </div>
+ {/* Categories inline */}
+ <div style={{marginTop:14,display:'flex',flexWrap:'wrap',gap:4}}>
+ {(mkt.categories || []).slice(0, 8).map((c, i) => {
+ const colors = ['#f59e0b','#3b82f6','#ec4899','#22c55e','#8b5cf6','#ef4444','#06b6d4','#14b8a6'];
+ return (<div key={i} style={{padding:'3px 10px',borderRadius:6,background:'rgba(255,255,255,.03)',border:'1px solid var(--border)',fontSize:9,display:'flex',alignItems:'center',gap:4}}>
+ <div style={{width:4,height:4,borderRadius:'50%',background:colors[i % colors.length]}} />
+ <span style={{fontWeight:600}}>{c.category}</span>
+ <span style={{color:'var(--muted)'}}>{c.count}</span>
+ </div>);
+ })}
+ </div>
+ </div>
+
+ {/* ═══ Recent Trades ═══ */}
+ {(mkt.recentTrades || []).length > 0 && <div className="mkt-card" style={{gridColumn:'span 2'}}>
+ <div className="mkt-card-header">
+ <span className="mkt-card-title" style={{color:'var(--yellow)'}}>Recent Trades</span>
+ <span className="mkt-card-badge" style={{background:'rgba(245,158,11,.15)',color:'var(--yellow)'}}>{totalTrades} total</span>
+ </div>
+ <div className="trade-log">
+ {(mkt.recentTrades || []).map((t, i) => {
+ const c = stratColors[t.strategy] || 'var(--muted)';
+ return (<div key={i} className="trade-row">
+ <span className="trade-portfolio" style={{color:c}}>{t.portfolio_name}</span>
+ <span className={'signal-dir ' + t.direction} style={{fontSize:9}}>{t.direction}</span>
+ <span style={{flex:1,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap',color:'var(--muted)'}}>{t.market_id}</span>
+ <span style={{fontSize:10,color:'var(--muted)'}}>{t.contracts}x @ {t.entry_price_cents}¢</span>
+ <span className="trade-pnl" style={{color: t.pnl_cents >= 0 ? 'var(--green)' : 'var(--red)'}}>
+ {t.pnl_cents >= 0 ? '+' : ''}{(t.pnl_cents / 100).toFixed(2)}
+ </span>
+ <span className="signal-time">{timeAgo(t.created_at)}</span>
+ </div>);
+ })}
+ </div>
+ </div>}
+
+ {/* ═══ Portfolio Leaderboard ═══ */}
+ {(mkt.portfolios || []).length > 0 && <div className="mkt-card" style={{gridColumn:'span 2'}}>
+ <div className="mkt-card-header">
+ <span className="mkt-card-title" style={{color:'var(--pink)'}}>Portfolio Leaderboard</span>
+ <span className="mkt-card-badge" style={{background:'rgba(255,105,180,.15)',color:'var(--pink)'}}>{totalTrades} trades</span>
+ </div>
+ <div style={{display:'grid',gridTemplateColumns:'repeat(auto-fill,minmax(220px,1fr))',gap:8}}>
+ {(mkt.portfolios || []).map((p, i) => {
+ const c = stratColors[p.strategy] || 'var(--muted)';
+ const emoji = stratEmojis[p.strategy] || '';
+ const pnl = p.pnl_cents || 0;
+ const invested = p.total_invested_cents || 0;
+ const roi = invested > 0 ? ((pnl / invested) * 100).toFixed(1) : '0.0';
+ return (<div key={i} style={{padding:'12px 14px',background:'rgba(255,255,255,.02)',border:'1px solid var(--border)',borderRadius:10,transition:'all .3s',borderLeftColor:c,borderLeftWidth:3,position:'relative',overflow:'hidden'}}>
+ {/* Rank badge */}
+ <div style={{position:'absolute',top:6,right:8,fontSize:8,color:'var(--muted)',fontWeight:800}}>#{i+1}</div>
+ <div style={{display:'flex',alignItems:'center',gap:8,marginBottom:6}}>
+ <span style={{fontSize:20}}>{emoji}</span>
+ <div style={{flex:1}}>
+ <div style={{fontSize:13,fontWeight:700,color:c}}>{p.name}</div>
+ <div style={{fontSize:9,color:'var(--muted)',textTransform:'uppercase',letterSpacing:.3}}>{p.strategy}</div>
+ </div>
+ <div style={{textAlign:'right'}}>
+ <div style={{fontSize:18,fontWeight:900,color: pnl >= 0 ? 'var(--green)' : 'var(--red)',fontVariantNumeric:'tabular-nums'}}>
+ {pnl >= 0 ? '+' : ''}{(pnl / 100).toFixed(2)}
+ </div>
+ <div style={{fontSize:9,color:'var(--muted)'}}>ROI: {roi}%</div>
+ </div>
+ </div>
+ <div style={{display:'flex',gap:4,fontSize:9,flexWrap:'wrap'}}>
+ <span style={{padding:'2px 7px',borderRadius:4,background:'rgba(34,197,94,.1)',color:'var(--green)'}}>W:{p.trades_won}</span>
+ <span style={{padding:'2px 7px',borderRadius:4,background:'rgba(239,68,68,.1)',color:'var(--red)'}}>L:{p.trades_lost}</span>
+ <span style={{padding:'2px 7px',borderRadius:4,background:'rgba(255,255,255,.04)',color:'var(--muted)'}}>WR:{p.win_rate}%</span>
+ <span style={{padding:'2px 7px',borderRadius:4,background:'rgba(255,255,255,.04)',color:'var(--muted)'}}>{p.total_trades} trades</span>
+ {p.streak !== 0 && <span style={{padding:'2px 7px',borderRadius:4,background: p.streak > 0 ? 'rgba(34,197,94,.1)' : 'rgba(239,68,68,.1)',color: p.streak > 0 ? 'var(--green)' : 'var(--red)'}}>{p.streak > 0 ? '+' : ''}{p.streak} streak</span>}
+ </div>
+ {invested > 0 && <div style={{marginTop:6}}>
+ <div style={{height:3,borderRadius:2,background:'rgba(255,255,255,.05)',overflow:'hidden'}}>
+ <div style={{height:'100%',borderRadius:2,width: Math.min(100, Math.abs(parseFloat(roi))) + '%',background: pnl >= 0 ? 'var(--green)' : 'var(--red)',transition:'width .5s'}} />
+ </div>
+ </div>}
+ </div>);
+ })}
+ </div>
+ </div>}
+ </div>
+ </div>);
+}
+
+function App() {
+ const [data, setData] = useState(null);
+ const [expandedAgent, setExpandedAgent] = useState(null);
+ const [tab, setTab] = useState('command');
+ const [loading, setLoading] = useState(true);
+
+ useEffect(() => {
+ const load = async () => {
+ try {
+ const d = await api('/api/inc');
+ setData(d);
+ setLoading(false);
+ } catch(e) { console.error(e); setLoading(false); }
+ };
+ load();
+ const iv = setInterval(load, 15000);
+ return () => clearInterval(iv);
+ }, []);
+
+ if (loading || !data) return (
+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: '100vh', flexDirection: 'column', gap: 16 }}>
+ <div style={{ width: 60, height: 60, borderRadius: '50%', background: 'linear-gradient(135deg,#ff69b4,#8b5cf6)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 28, animation: 'avatarFloat 2s ease-in-out infinite' }}>K</div>
+ <div style={{ color: 'var(--muted)', fontSize: 14, letterSpacing: 2 }}>INITIALIZING KEN INC...</div>
+ </div>
+ );
+
+ const d = data;
+ const approvalRate = d.pipeline.signalsLast24h > 0
+ ? Math.round(d.pipeline.approvedLast24h / d.pipeline.signalsLast24h * 100) : 0;
+
+ const tabStyle = (t) => ({
+ padding: '10px 24px', fontSize: 13, fontWeight: 600, border: '1px solid ' + (tab===t?'rgba(255,255,255,.2)':'var(--border)'),
+ borderRadius: 10, background: tab===t?'rgba(255,255,255,.08)':'transparent', color: tab===t?'var(--text)':'var(--muted)',
+ cursor: 'pointer', transition: 'all .2s', letterSpacing: .3,
+ });
+
+ return (
+ <div className="container">
+ <Particles />
+ <Clock />
+
+ <div className="header">
+ <div className="header-glow" />
+ <div className="ceo-avatar">K</div>
+ <div className="ceo-name">Ken</div>
+ <div className="ceo-title">Chief Executive Officer</div>
+ <div className="ceo-tagline">Trading Intelligence Corporation</div>
+ </div>
+
+ <div style={{display:'flex',justifyContent:'center',gap:8,marginBottom:24,flexWrap:'wrap'}}>
+ <button style={tabStyle('command')} onClick={()=>setTab('command')}>Command Center</button>
+ <button style={tabStyle('market')} onClick={()=>setTab('market')}>Market Data</button>
+ <button style={tabStyle('portfolios')} onClick={()=>setTab('portfolios')}>portFAUXlio</button>
+ <button style={tabStyle('predictions')} onClick={()=>setTab('predictions')}>Predictions</button>
+ <button style={tabStyle('signals')} onClick={()=>setTab('signals')}>Live Signals</button>
+ </div>
+
+ {tab === 'command' && <>
+ <div className="stats-bar">
+ <div className="stat-item"><div className="stat-val" style={{color:'var(--pink)'}}>{d.agents.length}</div><div className="stat-label">Sub-Agents</div></div>
+ <div className="stat-item"><div className="stat-val" style={{color:'var(--blue)'}}>{d.pipeline.signalsLast24h}</div><div className="stat-label">Signals / 24h</div></div>
+ <div className="stat-item"><div className="stat-val" style={{color:'var(--green)'}}>{approvalRate}%</div><div className="stat-label">Approval Rate</div></div>
+ <div className="stat-item"><div className="stat-val" style={{color:'var(--purple)'}}>{d.pipeline.lastHour}</div><div className="stat-label">Last Hour</div></div>
+ <div className="stat-item"><div className="stat-val" style={{color:'var(--cyan)'}}>{(parseFloat(d.pipeline.avgEdge)*100).toFixed(1)}%</div><div className="stat-label">Avg Edge</div></div>
+ <div className="stat-item"><div className="stat-val" style={{color:'var(--yellow)'}}>{d.system.memory_mb}MB</div><div className="stat-label">Memory</div></div>
+ <div className="stat-item"><div className="stat-val">{d.system.cpuCores}</div><div className="stat-label">CPU Cores</div></div>
+ </div>
+ <div className="network">
+ <div className="agents-grid">
+ {d.agents.map(a => (
+ <AgentCard key={a.id} agent={a} expanded={expandedAgent===a.id} onToggle={()=>setExpandedAgent(expandedAgent===a.id?null:a.id)} />
+ ))}
+ </div>
+ </div>
+ </>}
+
+ {tab === 'market' && <MarketDataTab />}
+ {tab === 'portfolios' && <PortfoliosTab />}
+ {tab === 'predictions' && <PredictionsTab />}
+
+ {tab === 'signals' && <div className="signal-feed">
+ <h2><span className="live-dot" /> Live Signal Feed</h2>
+ <SignalFeed signals={d.recentSignals} />
+ </div>}
+
+ <div className="footer">
+ Ken Inc. Trading Intelligence • {d.system.cpuCores} cores • {d.system.uptime_hours}h uptime • 50 paper portfolios •
+ <a href="/"> Back to Dashboard</a>
+ </div>
+ </div>
+ );
+}
+
+ReactDOM.createRoot(document.getElementById('root')).render(<App />);
+</script>
+</body>
+</html>`;
+
+// ════════════════════════════════════════
+// HTTP SERVER
+// ════════════════════════════════════════
+
+const server = http.createServer(async (req, res) => {
+ // CORS preflight
+ if (req.method === 'OPTIONS') {
+ res.writeHead(200, {
+ 'Access-Control-Allow-Origin': '*',
+ 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
+ 'Access-Control-Allow-Headers': 'Content-Type, Authorization',
+ });
+ res.end();
+ return;
+ }
+
+ // Route key for matching
+ const urlPath = req.url.split('?')[0];
+ const routeKey = `${req.method} ${urlPath}`;
+
+ // Public endpoints (no auth required)
+ const publicPaths = [
+ '/api/auth/login',
+ '/api/auth/logout',
+ '/api/auth/session',
+ '/api/auth/google',
+ '/api/auth/google-config',
+ '/api/health',
+ '/api/portfauxlio',
+ '/api/portfauxlio/charts',
+ '/api/portfauxlio/swot',
+ '/api/markets',
+ '/api/signals',
+ '/api/energy-arb',
+ '/api/predictions',
+ '/api/portfolios',
+ '/api/scan-config',
+ '/api/dashboard',
+ ];
+ const isPublic = publicPaths.includes(urlPath);
+
+ // Enforce auth on all other API routes
+ if (!isPublic && urlPath.startsWith('/api/') && !isAuthenticated(req)) {
+ return json(res, { error: 'Authentication required' }, 401);
+ }
+
+ // Check route handlers
+ if (routes[routeKey]) {
+ try {
+ await routes[routeKey](req, res);
+ } catch (err) {
+ console.error(`[ERROR] ${routeKey}:`, err.message);
+ json(res, { error: err.message }, 500);
+ }
+ return;
+ }
+
+ // Unknown API route
+ if (urlPath.startsWith('/api/')) {
+ return json(res, { error: `Unknown API endpoint: ${req.method} ${urlPath}` }, 404);
+ }
+
+ // ── Ken Inc. Command Center ──
+ if (urlPath === '/inc' || urlPath === '/inc/') {
+ res.writeHead(200, { 'Content-Type': 'text/html', 'Cache-Control': 'no-cache' });
+ res.end(KEN_INC_HTML);
+ return;
+ }
+
+ // ── Tournament Arena — 3D Team Competition ──
+ if (urlPath === '/arena' || urlPath === '/arena/') {
+ res.writeHead(200, { 'Content-Type': 'text/html', 'Cache-Control': 'no-cache' });
+ res.end(ARENA_HTML);
+ return;
+ }
+
+ // ── PortFAUXlios Dashboard ──
+ if (urlPath === '/portfauxlios' || urlPath === '/portfauxlios/') {
+ try {
+ const dashHtml = fs.readFileSync('/root/DW-Agents/ken-portfauxlios-dashboard.html', 'utf8');
+ res.writeHead(200, { 'Content-Type': 'text/html', 'Cache-Control': 'no-cache' });
+ res.end(dashHtml);
+ } catch (e) {
+ res.writeHead(500);
+ res.end('Dashboard not found: ' + e.message);
+ }
+ return;
+ }
+
+ // ── Serve Static Files / SPA Routing ──
+ let filePath = path.join(DIST, urlPath === '/' ? 'index.html' : urlPath);
+
+ // Security: prevent directory traversal
+ if (!filePath.startsWith(DIST)) {
+ res.writeHead(403);
+ res.end('Forbidden');
+ return;
+ }
+
+ // Check if file exists; if not, serve index.html for SPA routing
+ if (!fs.existsSync(filePath) || fs.statSync(filePath).isDirectory()) {
+ filePath = path.join(DIST, 'index.html');
+ }
+
+ try {
+ const content = fs.readFileSync(filePath);
+ const ext = path.extname(filePath);
+ const contentType = MIME[ext] || 'application/octet-stream';
+
+ // Cache static assets (hashed filenames from Vite)
+ const cacheHeader = ext === '.html'
+ ? 'no-cache, no-store, must-revalidate'
+ : 'public, max-age=31536000, immutable';
+
+ res.writeHead(200, {
+ 'Content-Type': contentType,
+ 'Cache-Control': cacheHeader,
+ });
+ res.end(content);
+ } catch {
+ res.writeHead(404);
+ res.end('Not found');
+ }
+});
+
+// ══════════════════════════════════════════════════════════════
+// KEN AUTONOMOUS TRADING BRAIN — 24/7 MARKET INTELLIGENCE
+// Scans every 15 min: Kalshi markets, Reddit, news, Polymarket
+// Stores everything in PostgreSQL, tracks own performance
+// ══════════════════════════════════════════════════════════════
+
+const KEN_DB = 'postgresql://dw_admin:DW2024SecurePass@127.0.0.1:5432/dw_unified';
+const kenPool = new pg.Pool({ connectionString: KEN_DB, max: 20, idleTimeoutMillis: 30000 });
+async function kenQ(text, params) { return kenPool.query(text, params); }
+
+// ── Mutable scan/pipeline intervals (adjustable via Settings UI) ──
+let SCAN_INTERVAL_MS = 8 * 60 * 1000; // 8 minutes — market scans
+let REDDIT_INTERVAL_MS = 15 * 60 * 1000; // 15 minutes — intelligence sweep
+let SIGNAL_PIPELINE_MS = 2 * 60 * 1000; // 2 minutes — signal pipeline
+let RESOLVE_INTERVAL_MS = 5 * 60 * 1000; // 5 minutes — trade resolution
+const SLACK_COOLDOWN_MS = 4 * 60 * 60 * 1000;
+let lastSlackTime = 0;
+let cachedActiveMarkets = [];
+let cachedMomentumMap = {};
+
+// Interval handles (stored so we can clear + reset when config changes)
+let scanIntervalId = null;
+let redditIntervalId = null;
+let signalIntervalId = null;
+let resolveIntervalId = null;
+
+// Load scan config from DB on startup
+async function loadScanConfig() {
+ try {
+ await initConfigTable();
+ const { rows } = await kenQ("SELECT value FROM ken_config WHERE key = 'scan_config'");
+ if (rows.length > 0) {
+ const cfg = rows[0].value;
+ if (cfg.scan_interval_ms) SCAN_INTERVAL_MS = cfg.scan_interval_ms;
+ if (cfg.reddit_interval_ms) REDDIT_INTERVAL_MS = cfg.reddit_interval_ms;
+ if (cfg.signal_pipeline_ms) SIGNAL_PIPELINE_MS = cfg.signal_pipeline_ms;
+ if (cfg.resolve_interval_ms) RESOLVE_INTERVAL_MS = cfg.resolve_interval_ms;
+ if (cfg.min_edge_threshold !== undefined) RISK_LIMITS.minEdgeThreshold = cfg.min_edge_threshold;
+ if (cfg.min_liquidity !== undefined) RISK_LIMITS.minLiquidity = cfg.min_liquidity;
+ console.log(`[Ken] Loaded scan_config: scan=${SCAN_INTERVAL_MS/1000}s, signal=${SIGNAL_PIPELINE_MS/1000}s, sweep=${REDDIT_INTERVAL_MS/1000}s, resolve=${RESOLVE_INTERVAL_MS/1000}s, edge=${RISK_LIMITS.minEdgeThreshold}, liq=${RISK_LIMITS.minLiquidity}`);
+ }
+ } catch (e) {
+ console.log(`[Ken] Failed to load scan config: ${e.message}`);
+ }
+}
+
+async function saveScanConfig() {
+ try {
+ await kenQ(`
+ INSERT INTO ken_config (key, value, updated_at) VALUES ('scan_config', $1, NOW())
+ ON CONFLICT (key) DO UPDATE SET value = $1, updated_at = NOW()
+ `, [JSON.stringify({
+ scan_interval_ms: SCAN_INTERVAL_MS,
+ reddit_interval_ms: REDDIT_INTERVAL_MS,
+ signal_pipeline_ms: SIGNAL_PIPELINE_MS,
+ resolve_interval_ms: RESOLVE_INTERVAL_MS,
+ min_edge_threshold: RISK_LIMITS.minEdgeThreshold,
+ min_liquidity: RISK_LIMITS.minLiquidity,
+ })]);
+ } catch (e) {
+ console.log(`[Ken] Failed to save scan config: ${e.message}`);
+ }
+}
+
+function restartIntervals() {
+ if (scanIntervalId) clearInterval(scanIntervalId);
+ if (redditIntervalId) clearInterval(redditIntervalId);
+ if (signalIntervalId) clearInterval(signalIntervalId);
+ if (resolveIntervalId) clearInterval(resolveIntervalId);
+
+ scanIntervalId = setInterval(() => runScanSafe(autonomousScan), SCAN_INTERVAL_MS);
+ redditIntervalId = setInterval(() => runSweepSafe('Reddit', redditIntelligenceLoop), REDDIT_INTERVAL_MS);
+ signalIntervalId = setInterval(async () => {
+ if (cachedActiveMarkets.length > 0) {
+ try { await signalPipeline(cachedActiveMarkets); } catch (e) { console.log(`[Ken] Fast pipeline error: ${e.message}`); }
+ }
+ }, SIGNAL_PIPELINE_MS);
+ resolveIntervalId = setInterval(() => {
+ resolvePortfolioTrades().catch(e => console.error('[Ken] Portfolio resolution error:', e.message));
+ }, RESOLVE_INTERVAL_MS);
+
+ console.log(`[Ken] Intervals restarted: scan=${SCAN_INTERVAL_MS/60000}m, signal=${SIGNAL_PIPELINE_MS/60000}m, sweep=${REDDIT_INTERVAL_MS/60000}m, resolve=${RESOLVE_INTERVAL_MS/60000}m`);
+}
+
+// ── Reddit Scraper (no auth needed — uses .json API) ──
+async function scrapeReddit(subreddit, searchTerm, limit = 25) {
+ try {
+ const encoded = encodeURIComponent(searchTerm);
+ const url = `https://www.reddit.com/r/${subreddit}/search.json?q=${encoded}&sort=new&restrict_sr=on&limit=${limit}&t=week`;
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), 10000);
+ const res = await fetch(url, {
+ headers: { 'User-Agent': 'Ken-Bot/2.0 (trading intelligence)' },
+ signal: controller.signal,
+ });
+ clearTimeout(timeout);
+ if (!res.ok) return [];
+ const data = await res.json();
+ const posts = (data?.data?.children || []).map(c => ({
+ title: c.data.title,
+ selftext: (c.data.selftext || '').substring(0, 500),
+ score: c.data.score || 0,
+ num_comments: c.data.num_comments || 0,
+ url: `https://reddit.com${c.data.permalink}`,
+ created: new Date(c.data.created_utc * 1000),
+ subreddit: c.data.subreddit,
+ }));
+ return posts;
+ } catch (e) {
+ console.log(`[Ken] Reddit scrape failed r/${subreddit} "${searchTerm}": ${e.message}`);
+ return [];
+ }
+}
+
+// ── Scrape Reddit hot/top posts for general sentiment ──
+async function scrapeSubredditHot(subreddit, limit = 15) {
+ try {
+ const url = `https://www.reddit.com/r/${subreddit}/hot.json?limit=${limit}`;
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), 10000);
+ const res = await fetch(url, {
+ headers: { 'User-Agent': 'Ken-Bot/2.0 (trading intelligence)' },
+ signal: controller.signal,
+ });
+ clearTimeout(timeout);
+ if (!res.ok) return [];
+ const data = await res.json();
+ return (data?.data?.children || []).map(c => ({
+ title: c.data.title,
+ selftext: (c.data.selftext || '').substring(0, 500),
+ score: c.data.score || 0,
+ num_comments: c.data.num_comments || 0,
+ url: `https://reddit.com${c.data.permalink}`,
+ created: new Date(c.data.created_utc * 1000),
+ subreddit: c.data.subreddit,
+ }));
+ } catch (e) {
+ return [];
+ }
+}
+
+// ── Google News RSS scraper ──
+async function scrapeGoogleNews(query, limit = 10) {
+ try {
+ const encoded = encodeURIComponent(query);
+ const url = `https://news.google.com/rss/search?q=${encoded}&hl=en-US&gl=US&ceid=US:en`;
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), 10000);
+ const res = await fetch(url, { signal: controller.signal });
+ clearTimeout(timeout);
+ if (!res.ok) return [];
+ const xml = await res.text();
+ // Simple XML parse for RSS items
+ const items = [];
+ const itemRegex = /<item>([\s\S]*?)<\/item>/g;
+ let match;
+ while ((match = itemRegex.exec(xml)) && items.length < limit) {
+ const block = match[1];
+ const title = (block.match(/<title>([\s\S]*?)<\/title>/) || [])[1] || '';
+ const link = (block.match(/<link>([\s\S]*?)<\/link>/) || [])[1] || '';
+ const pubDate = (block.match(/<pubDate>([\s\S]*?)<\/pubDate>/) || [])[1] || '';
+ const source = (block.match(/<source[^>]*>([\s\S]*?)<\/source>/) || [])[1] || '';
+ items.push({
+ title: title.replace(/<!\[CDATA\[|\]\]>/g, '').trim(),
+ url: link.trim(),
+ source: source.replace(/<!\[CDATA\[|\]\]>/g, '').trim(),
+ published: pubDate ? new Date(pubDate) : new Date(),
+ });
+ }
+ return items;
+ } catch (e) {
+ console.log(`[Ken] News scrape failed "${query}": ${e.message}`);
+ return [];
+ }
+}
+
+// ── Polymarket cross-reference (public events API) ──
+async function scrapePolymarketEvents(limit = 100) {
+ try {
+ const url = `https://gamma-api.polymarket.com/events?closed=false&limit=${limit}&order=volume&ascending=false`;
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), 15000);
+ const res = await fetch(url, { signal: controller.signal });
+ clearTimeout(timeout);
+ if (!res.ok) return [];
+ const events = await res.json();
+ const results = [];
+ for (const evt of (events || [])) {
+ const mkts = (evt.markets || []).sort((a, b) => (b.volume || 0) - (a.volume || 0));
+ for (const m of mkts.slice(0, 3)) {
+ let price = null;
+ try { price = Math.round(parseFloat(JSON.parse(m.outcomePrices)[0]) * 100); } catch {}
+ if (price !== null && price > 0 && price < 100) {
+ results.push({
+ event_title: evt.title || '',
+ question: m.question || '',
+ price,
+ volume: Math.round(m.volume || 0),
+ slug: evt.slug || m.slug || '',
+ });
+ }
+ }
+ }
+ return results;
+ } catch (e) {
+ console.log(`[Ken] Polymarket scrape failed: ${e.message}`);
+ return [];
+ }
+}
+
+// ── Simple keyword sentiment scorer ──
+function scoreSentiment(text) {
+ const t = (text || '').toLowerCase();
+ const bullish = ['confirmed', 'likely', 'expected', 'approved', 'passed', 'agreed', 'winning', 'surge', 'soaring', 'breaking', 'imminent', 'certain', 'guarantee', 'official', 'announced', 'done deal'];
+ const bearish = ['unlikely', 'denied', 'rejected', 'failed', 'blocked', 'withdrawn', 'canceled', 'impossible', 'no chance', 'not going', 'walked back', 'reversed', 'postponed', 'delayed', 'collapse'];
+ const uncertain = ['maybe', 'could', 'might', 'rumor', 'speculation', 'sources say', 'unconfirmed', 'developing', 'unclear'];
+
+ let score = 0;
+ for (const w of bullish) if (t.includes(w)) score += 0.15;
+ for (const w of bearish) if (t.includes(w)) score -= 0.15;
+ for (const w of uncertain) if (t.includes(w)) score *= 0.7;
+ return Math.max(-1, Math.min(1, score));
+}
+
+// ── Map keywords in text to Kalshi event tickers ──
+function matchTextToMarkets(text, activeMarkets) {
+ const t = (text || '').toLowerCase();
+ const matches = [];
+ const keywords = {
+ 'fed chair': 'KXFEDCHAIRNOM',
+ 'federal reserve': 'KXFEDCHAIRNOM',
+ 'kevin warsh': 'KXFEDCHAIRNOM',
+ 'greenland': 'KXGREEN',
+ 'cabinet': 'KXCABOUT',
+ 'gabbard': 'KXCABOUT',
+ 'tulsi': 'KXCABOUT',
+ 'hegseth': 'KXCABOUT',
+ 'defense secretary': 'KXTRUMPDEFCOUNT',
+ 'insurrection act': 'KXINSURRECTION',
+ 'supreme court': 'KXSCOTUS',
+ 'seattle basketball': 'KXNBASEATTLE',
+ 'seattle nba': 'KXNBASEATTLE',
+ '2028 election': 'KXPRESPERSON',
+ 'presidential': 'KXPRESPERSON',
+ };
+ for (const [kw, prefix] of Object.entries(keywords)) {
+ if (t.includes(kw)) {
+ const related = activeMarkets.filter(m => m.event_ticker?.startsWith(prefix) || m.ticker?.startsWith(prefix));
+ for (const m of related) {
+ if (!matches.find(x => x.ticker === m.ticker)) matches.push(m);
+ }
+ }
+ }
+ return matches;
+}
+
+function generateSyntheticWeather(cities) {
+ const month = new Date().getMonth();
+ const results = [];
+ for (const city of cities) {
+ const coords = CITY_COORDS[city]; if (!coords) continue;
+ const baseTemp = [35,38,48,58,68,78,85,83,75,62,48,38][month] + (coords.lat < 35 ? 15 : coords.lat > 42 ? -8 : 0);
+ const temps = Array.from({length: 14}, (_, i) => baseTemp + Math.round((Math.random() - 0.5) * 12) + (i < 7 ? 3 : -2));
+ const precips = Array.from({length: 14}, () => Math.round(Math.random() * 60));
+ const winds = Array.from({length: 14}, () => 5 + Math.round(Math.random() * 15));
+ const mkStat = (arr) => ({ mean: arr.reduce((a,b)=>a+b)/arr.length, min: Math.min(...arr), max: Math.max(...arr), latest: arr[0] });
+ results.push({
+ city, synthetic: true,
+ temperature: { variable: 'temperature', unit: 'F', values: temps, ...mkStat(temps) },
+ precipitation: { variable: 'precipitation', unit: 'percent', values: precips, ...mkStat(precips) },
+ wind: { variable: 'wind', unit: 'mph', values: winds, ...mkStat(winds) },
+ });
+ }
+ return results;
+}
+
+// ── Hacker News scraper (top stories + search) ──
+// ── GDELT TV News mentions (covers CNN, MSNBC, Fox News, BBC captions) ──
+async function scrapeGDELTtv(query, station = 'CNN', limit = 15) {
+ try {
+ const url = `https://api.gdeltproject.org/api/v2/tv/tv?query=${encodeURIComponent(query)}%20station:${station}&mode=clipgallery&format=json&maxrecords=${limit}&last24hours=yes`;
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), 15000);
+ const res = await fetch(url, { signal: controller.signal, headers: { 'User-Agent': 'Ken-Bot/2.0' } });
+ clearTimeout(timeout);
+ if (!res.ok) return [];
+ const text = await res.text();
+ if (!text.startsWith('{')) return []; // API returns error text, not JSON
+ const data = JSON.parse(text);
+ return (data.clips || []).map(c => ({
+ title: c.snippet || '',
+ url: c.preview_url || c.url || '',
+ source: c.station || 'TV News',
+ show: c.show || '',
+ date: c.date || '',
+ }));
+ } catch (e) {
+ return [];
+ }
+}
+
+// ── YouTube RSS search (public API, no key needed) ──
+async function scrapeYouTubeRSS(query) {
+ try {
+ const url = `https://www.youtube.com/results?search_query=${encodeURIComponent(query)}&sp=CAISBAgBEAE%253D`; // last hour filter
+ // YouTube doesn't have direct RSS search, use channel feeds for major news channels
+ const channels = [
+ { id: 'UCupvZG-5ko_eiXAupbDfxWw', name: 'CNN' },
+ { id: 'UCaXkIU1QidjPwiAYu6GcHjg', name: 'MSNBC' },
+ { id: 'UCXIJgqnII2ZOINSWNOGFThA', name: 'Fox News' },
+ { id: 'UC16niRr50-MSBwiO3YDb3RA', name: 'Bloomberg TV' },
+ { id: 'UCvJJ_dzjViJCoLf5uKUTwoA', name: 'CNBC' },
+ { id: 'UCknLrEdhRCp1aegoMqRaCZg', name: 'NBC News' },
+ { id: 'UCBi2mrWuNuyYy4gbM6fU18Q', name: 'ABC News' },
+ { id: 'UC8p1vwvWtl6T73JiExfWs1g', name: 'CBS News' },
+ { id: 'UC52X5wxOL_s5yw0dQk7NtgA', name: 'PBS NewsHour' },
+ ];
+ const results = [];
+ for (const ch of channels) {
+ try {
+ const feedUrl = `https://www.youtube.com/feeds/videos.xml?channel_id=${ch.id}`;
+ const items = await scrapeRSSFeed(feedUrl, `YT ${ch.name}`, 5);
+ results.push(...items);
+ } catch {}
+ }
+ return results;
+ } catch { return []; }
+}
+
+// ── Lemmy (federated Reddit) — public JSON API, no auth needed ──
+async function scrapeLemmy(sort = 'Hot', limit = 20) {
+ const instances = ['lemmy.world', 'lemmy.ml', 'sh.itjust.works'];
+ const results = [];
+ for (const inst of instances) {
+ try {
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), 10000);
+ const res = await fetch(`https://${inst}/api/v3/post/list?sort=${sort}&limit=${limit}&type_=All`, {
+ signal: controller.signal,
+ headers: { 'Accept': 'application/json' },
+ });
+ clearTimeout(timeout);
+ if (!res.ok) continue;
+ const data = await res.json();
+ for (const p of (data.posts || [])) {
+ const post = p.post || {};
+ const counts = p.counts || {};
+ if (post.name && post.name.length > 10) {
+ results.push({
+ title: post.name.substring(0, 500),
+ url: post.ap_id || `https://${inst}/post/${post.id}`,
+ source: `Lemmy ${inst}`,
+ score: counts.score || 0,
+ num_comments: counts.comments || 0,
+ });
+ }
+ }
+ if (results.length > 0) break; // got data from one instance
+ } catch {}
+ }
+ return results;
+}
+
+// ── Lobsters (tech/politics news) — public JSON API ──
+async function scrapeLobsters(limit = 25) {
+ try {
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), 10000);
+ const res = await fetch('https://lobste.rs/hottest.json', { signal: controller.signal });
+ clearTimeout(timeout);
+ if (!res.ok) return [];
+ const stories = await res.json();
+ return stories.slice(0, limit).map(s => ({
+ title: s.title || '',
+ url: s.url || s.short_id_url || '',
+ source: 'Lobsters',
+ score: s.score || 0,
+ num_comments: s.comment_count || 0,
+ author: s.submitter_user?.username || '',
+ tags: (s.tags || []).join(', '),
+ }));
+ } catch { return []; }
+}
+
+// ── Tildes (curated discussion) — RSS feed ──
+async function scrapeTildes() {
+ try {
+ return await scrapeRSSFeed('https://tildes.net/topics.rss', 'Tildes', 20);
+ } catch { return []; }
+}
+
+// ── Manifold Markets (open prediction market — public API) ──
+async function scrapeManifold(queries) {
+ const results = [];
+ for (const q of queries) {
+ try {
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), 8000);
+ const res = await fetch(`https://manifold.markets/api/v0/search-markets?term=${encodeURIComponent(q)}&sort=liquidity&limit=10`, {
+ signal: controller.signal, headers: { 'Accept': 'application/json' },
+ });
+ clearTimeout(timeout);
+ if (!res.ok) continue;
+ const markets = await res.json();
+ for (const m of (markets || [])) {
+ if (m.question && m.probability != null && (m.volume || 0) > 100) {
+ results.push({
+ title: m.question,
+ url: m.url || `https://manifold.markets/${m.creatorUsername}/${m.slug}`,
+ source: 'Manifold',
+ probability: Math.round((m.probability || 0) * 100),
+ volume: Math.round(m.volume || 0),
+ liquidity: Math.round(m.totalLiquidity || 0),
+ });
+ }
+ }
+ } catch {}
+ await new Promise(r => setTimeout(r, 500));
+ }
+ return results;
+}
+
+// ── Mastodon/Fediverse trending (public API, no auth) ──
+async function scrapeMastodon() {
+ const instances = ['mastodon.social', 'mas.to'];
+ const results = [];
+ for (const inst of instances) {
+ try {
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), 8000);
+ const res = await fetch(`https://${inst}/api/v1/trends/statuses?limit=10`, {
+ signal: controller.signal,
+ });
+ clearTimeout(timeout);
+ if (!res.ok) continue;
+ const statuses = await res.json();
+ for (const s of statuses) {
+ const text = (s.content || '').replace(/<[^>]+>/g, '').trim();
+ if (text.length > 20) {
+ results.push({
+ title: text.substring(0, 500),
+ url: s.url || s.uri || '',
+ source: `Mastodon ${inst}`,
+ score: s.favourites_count || 0,
+ num_comments: s.replies_count || 0,
+ });
+ }
+ }
+ } catch {}
+ }
+ return results;
+}
+
+// ── Bluesky trending (public API — using feed generators, not searchPosts which is 403) ──
+async function scrapeBluesky() {
+ const feeds = [
+ { uri: 'at://did:plc:z72i7hdynmk6r22z27h6tvur/app.bsky.feed.generator/whats-hot', name: 'whats-hot' },
+ { uri: 'at://did:plc:z72i7hdynmk6r22z27h6tvur/app.bsky.feed.generator/hot-classic', name: 'hot-classic' },
+ ];
+ const results = [];
+ for (const feed of feeds) {
+ try {
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), 10000);
+ const url = `https://public.api.bsky.app/xrpc/app.bsky.feed.getFeed?feed=${encodeURIComponent(feed.uri)}&limit=20`;
+ const res = await fetch(url, { signal: controller.signal, headers: { 'Accept': 'application/json' } });
+ clearTimeout(timeout);
+ if (!res.ok) continue;
+ const data = await res.json();
+ for (const item of (data.feed || [])) {
+ const p = item.post || {};
+ const text = (p.record?.text || '').trim();
+ if (text.length > 20) {
+ results.push({
+ title: text.substring(0, 500),
+ url: `https://bsky.app/profile/${p.author?.handle}/post/${p.uri?.split('/').pop()}`,
+ source: `Bluesky ${feed.name}`,
+ author: p.author?.handle || '',
+ score: (p.likeCount || 0) + (p.repostCount || 0),
+ num_comments: p.replyCount || 0,
+ });
+ }
+ }
+ } catch {}
+ }
+ return results;
+}
+
+async function scrapeHackerNews(query, limit = 15) {
+ try {
+ const url = query
+ ? `https://hn.algolia.com/api/v1/search_by_date?query=${encodeURIComponent(query)}&tags=story&hitsPerPage=${limit}`
+ : `https://hn.algolia.com/api/v1/search?tags=front_page&hitsPerPage=${limit}`;
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), 10000);
+ const res = await fetch(url, { signal: controller.signal });
+ clearTimeout(timeout);
+ if (!res.ok) return [];
+ const data = await res.json();
+ return (data.hits || []).map(h => ({
+ title: h.title || '',
+ url: h.url || `https://news.ycombinator.com/item?id=${h.objectID}`,
+ score: h.points || 0,
+ num_comments: h.num_comments || 0,
+ created: new Date(h.created_at),
+ source: 'hackernews',
+ }));
+ } catch (e) {
+ console.log(`[Ken] HN scrape failed: ${e.message}`);
+ return [];
+ }
+}
+
+// ── AP News RSS scraper ──
+// ── Generic RSS feed scraper ──
+async function scrapeRSSFeed(url, source, limit = 15) {
+ try {
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), 10000);
+ const res = await fetch(url, {
+ signal: controller.signal,
+ headers: { 'User-Agent': 'Ken-Bot/2.0 (RSS Reader)' },
+ });
+ clearTimeout(timeout);
+ if (!res.ok) return [];
+ const xml = await res.text();
+ const items = [];
+ // Handle both <item> (RSS) and <entry> (Atom) formats
+ const itemRegex = /<(?:item|entry)>([\s\S]*?)<\/(?:item|entry)>/g;
+ let match;
+ while ((match = itemRegex.exec(xml)) && items.length < limit) {
+ const block = match[1];
+ const title = (block.match(/<title[^>]*>([\s\S]*?)<\/title>/) || [])[1] || '';
+ const link = (block.match(/<link[^>]*href="([^"]+)"/) || block.match(/<link>([\s\S]*?)<\/link>/) || [])[1] || '';
+ const cleanTitle = title.replace(/<!\[CDATA\[|\]\]>/g, '').replace(/<[^>]+>/g, '').trim();
+ if (cleanTitle && cleanTitle.length > 10) {
+ items.push({ title: cleanTitle, url: link.trim(), source });
+ }
+ }
+ return items;
+ } catch { return []; }
+}
+
+// ── All news channel feeds ──
+const NEWS_FEEDS = [
+ // ═══ POLITICS & POLICY (Kalshi political markets) ═══
+ { url: 'https://feeds.bbci.co.uk/news/world/rss.xml', source: 'BBC World' },
+ { url: 'https://feeds.bbci.co.uk/news/politics/rss.xml', source: 'BBC Politics' },
+ { url: 'https://feeds.bbci.co.uk/news/us_and_canada/rss.xml', source: 'BBC US' },
+ { url: 'https://rss.nytimes.com/services/xml/rss/nyt/Politics.xml', source: 'NYT Politics' },
+ { url: 'https://rss.nytimes.com/services/xml/rss/nyt/World.xml', source: 'NYT World' },
+ { url: 'https://rss.nytimes.com/services/xml/rss/nyt/US.xml', source: 'NYT US' },
+ { url: 'https://feeds.washingtonpost.com/rss/politics', source: 'WaPo Politics' },
+ { url: 'https://feeds.washingtonpost.com/rss/world', source: 'WaPo World' },
+ { url: 'https://www.politico.com/rss/politicopicks.xml', source: 'Politico' },
+ { url: 'https://www.politico.com/rss/congress.xml', source: 'Politico Congress' },
+ { url: 'https://thehill.com/feed/', source: 'The Hill' },
+ { url: 'https://feeds.npr.org/1001/rss.xml', source: 'NPR News' },
+ { url: 'https://feeds.npr.org/1014/rss.xml', source: 'NPR Politics' },
+ { url: 'https://www.aljazeera.com/xml/rss/all.xml', source: 'Al Jazeera' },
+ { url: 'https://rss.dw.com/xml/rss-en-all', source: 'DW News' },
+ { url: 'https://feeds.skynews.com/feeds/rss/world.xml', source: 'Sky News World' },
+ { url: 'https://feeds.skynews.com/feeds/rss/us.xml', source: 'Sky News US' },
+ { url: 'https://www.theguardian.com/us-news/rss', source: 'Guardian US' },
+ { url: 'https://www.theguardian.com/world/rss', source: 'Guardian World' },
+ { url: 'https://rss.cbc.ca/lineup/world.xml', source: 'CBC World' },
+ { url: 'https://feeds.abcnews.com/abcnews/politicsheadlines', source: 'ABC Politics' },
+ { url: 'http://feeds.foxnews.com/foxnews/politics', source: 'Fox Politics' },
+ { url: 'https://www.axios.com/feeds/feed.rss', source: 'Axios' },
+ { url: 'https://www.vox.com/rss/index.xml', source: 'Vox' },
+
+ // ═══ ECONOMICS & FINANCIAL MARKETS (Kalshi econ/rate markets) ═══
+ { url: 'https://feeds.bloomberg.com/politics/news.rss', source: 'Bloomberg Politics' },
+ { url: 'https://feeds.bloomberg.com/markets/news.rss', source: 'Bloomberg Markets' },
+ { url: 'https://www.cnbc.com/id/10000664/device/rss/rss.html', source: 'CNBC Top' },
+ { url: 'https://www.cnbc.com/id/10001147/device/rss/rss.html', source: 'CNBC Economy' },
+ { url: 'https://search.cnbc.com/rs/search/combinedcms/view.xml?partnerId=wrss01&id=15839069', source: 'CNBC Politics' },
+ { url: 'https://www.cnbc.com/id/20910258/device/rss/rss.html', source: 'CNBC Finance' },
+ { url: 'https://feeds.marketwatch.com/marketwatch/topstories/', source: 'MarketWatch' },
+ { url: 'https://feeds.marketwatch.com/marketwatch/marketpulse/', source: 'MarketWatch Pulse' },
+ { url: 'https://rss.nytimes.com/services/xml/rss/nyt/Business.xml', source: 'NYT Business' },
+ { url: 'https://rss.nytimes.com/services/xml/rss/nyt/Economy.xml', source: 'NYT Economy' },
+ { url: 'https://www.ft.com/rss/home/us', source: 'FT US' },
+ { url: 'https://www.investing.com/rss/news.rss', source: 'Investing.com' },
+ { url: 'https://www.federalreserve.gov/feeds/press_all.xml', source: 'Fed Reserve' },
+ { url: 'https://www.bis.org/doclist/bis_fsi_publs.rss', source: 'BIS' },
+ { url: 'https://seekingalpha.com/feed.xml', source: 'Seeking Alpha' },
+ { url: 'https://finance.yahoo.com/news/rssindex', source: 'Yahoo Finance' },
+
+ // ═══ CRYPTO & PREDICTION MARKETS (cross-ref with Polymarket) ═══
+ { url: 'https://cointelegraph.com/rss', source: 'CoinTelegraph' },
+ { url: 'https://www.coindesk.com/arc/outboundfeeds/rss/', source: 'CoinDesk' },
+ { url: 'https://decrypt.co/feed', source: 'Decrypt' },
+ { url: 'https://thedefiant.io/feed', source: 'The Defiant' },
+
+ // ═══ PREDICTION & POLLING ANALYSIS ═══
+ { url: 'https://fivethirtyeight.com/features/feed/', source: 'FiveThirtyEight' },
+ { url: 'https://www.realclearpolitics.com/index.xml', source: 'RealClearPolitics' },
+ { url: 'https://electionbettingodds.com/feed', source: 'ElectionBettingOdds' },
+ { url: 'https://www.predictit.org/feed', source: 'PredictIt' },
+
+ // ═══ TECH & AI POLICY (Kalshi tech markets) ═══
+ { url: 'https://www.theverge.com/rss/index.xml', source: 'The Verge' },
+ { url: 'https://techcrunch.com/feed/', source: 'TechCrunch' },
+ { url: 'https://arstechnica.com/feed/', source: 'Ars Technica' },
+ { url: 'https://www.wired.com/feed/rss', source: 'WIRED' },
+ { url: 'https://feeds.feedburner.com/venturebeat/SZYF', source: 'VentureBeat' },
+
+ // ═══ WEATHER & CLIMATE (Kalshi weather markets - temps, snow, etc.) ═══
+ { url: 'https://www.weather.gov/rss_page.php?site_name=nws', source: 'NWS' },
+ { url: 'https://weather.com/feeds/enhancedconditions/rss', source: 'Weather.com' },
+ { url: 'https://www.accuweather.com/en/us/national/current-weather/rss', source: 'AccuWeather' },
+ { url: 'https://www.climate.gov/rss.xml', source: 'NOAA Climate' },
+
+ // ═══ SPORTS (Kalshi has sports-adjacent markets) ═══
+ { url: 'https://www.espn.com/espn/rss/news', source: 'ESPN' },
+ { url: 'https://rss.nytimes.com/services/xml/rss/nyt/Sports.xml', source: 'NYT Sports' },
+
+ // ═══ ENTERTAINMENT & CULTURE (Kalshi awards/culture markets) ═══
+ { url: 'https://variety.com/feed/', source: 'Variety' },
+ { url: 'https://deadline.com/feed/', source: 'Deadline' },
+ { url: 'https://www.hollywoodreporter.com/feed/', source: 'Hollywood Reporter' },
+
+ // ═══ ENERGY & COMMODITIES (Kalshi gas/oil markets) ═══
+ { url: 'https://oilprice.com/rss/main', source: 'OilPrice' },
+ { url: 'https://www.eia.gov/rss/todayinenergy.xml', source: 'EIA Energy' },
+
+ // ═══ DEFENSE & GEOPOLITICS (conflict/territory markets) ═══
+ { url: 'https://www.defensenews.com/arc/outboundfeeds/rss/category/global/?outputType=xml', source: 'Defense News' },
+ { url: 'https://foreignpolicy.com/feed/', source: 'Foreign Policy' },
+ { url: 'https://warontherocks.com/feed/', source: 'War On The Rocks' },
+
+ // ═══ SCIENCE & SPACE (Kalshi space markets) ═══
+ { url: 'https://www.nasa.gov/rss/dyn/breaking_news.rss', source: 'NASA' },
+ { url: 'https://www.space.com/feeds/all', source: 'Space.com' },
+ { url: 'https://www.nature.com/nature.rss', source: 'Nature' },
+ { url: 'https://www.science.org/rss/news_current.xml', source: 'Science' },
+];
+
+async function scrapeAllNewsFeeds() {
+ const allArticles = [];
+ // Process feeds in batches of 15 concurrently for speed (maxed for 16 cores)
+ const batchSize = 15;
+ for (let i = 0; i < NEWS_FEEDS.length; i += batchSize) {
+ const batch = NEWS_FEEDS.slice(i, i + batchSize);
+ const results = await Promise.allSettled(
+ batch.map(feed => scrapeRSSFeed(feed.url, feed.source, 8))
+ );
+ for (const result of results) {
+ if (result.status === 'fulfilled') allArticles.push(...result.value);
+ }
+ await new Promise(r => setTimeout(r, 100)); // minimal pause between batches
+ }
+ return allArticles;
+}
+
+// ── Metaculus predictions scraper (prediction market cross-ref) ──
+async function scrapeMetaculus() {
+ try {
+ const url = 'https://www.metaculus.com/api2/questions/?limit=20&order_by=-activity&status=open&type=forecast';
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), 10000);
+ const res = await fetch(url, { headers: { 'Accept': 'application/json' }, signal: controller.signal });
+ clearTimeout(timeout);
+ if (!res.ok) return [];
+ const data = await res.json();
+ return (data.results || []).map(q => ({
+ title: q.title || '',
+ url: `https://www.metaculus.com/questions/${q.id}`,
+ community_prediction: q.community_prediction?.full?.q2,
+ num_predictions: q.number_of_predictions || 0,
+ source: 'metaculus',
+ }));
+ } catch (e) {
+ console.log(`[Ken] Metaculus scrape failed: ${e.message}`);
+ return [];
+ }
+}
+
+// ── PredictIt API (another prediction market for cross-reference) ──
+async function scrapePredictIt() {
+ try {
+ const controller = new AbortController();
+ setTimeout(() => controller.abort(), 8000);
+ const res = await fetch('https://www.predictit.org/api/marketdata/all/', {
+ signal: controller.signal,
+ headers: { 'User-Agent': 'Ken-Bot/1.0' }
+ });
+ if (!res.ok) return [];
+ const data = await res.json();
+ return (data.markets || []).slice(0, 100).map(m => ({
+ title: m.name,
+ url: m.url || `https://www.predictit.org/markets/detail/${m.id}`,
+ score: Math.round((m.contracts?.[0]?.lastTradePrice || 0) * 100),
+ num_comments: m.contracts?.length || 0,
+ source: 'predictit',
+ extra: JSON.stringify({
+ contracts: (m.contracts || []).slice(0, 5).map(c => ({
+ name: c.name, lastPrice: c.lastTradePrice, bestBuy: c.bestBuyYesCost, bestSell: c.bestSellYesCost
+ }))
+ })
+ }));
+ } catch (e) {
+ console.log(`[Ken] PredictIt scrape failed: ${e.message}`);
+ return [];
+ }
+}
+
+// ── FRED Economic Data API (real economic indicators — no key needed for some endpoints) ──
+async function scrapeFredIndicators() {
+ const indicators = [
+ { series: 'CPIAUCSL', name: 'CPI Inflation' },
+ { series: 'UNRATE', name: 'Unemployment Rate' },
+ { series: 'GDP', name: 'GDP Growth' },
+ { series: 'FEDFUNDS', name: 'Federal Funds Rate' },
+ { series: 'T10Y2Y', name: '10Y-2Y Treasury Spread' },
+ { series: 'VIXCLS', name: 'VIX Volatility Index' },
+ { series: 'DGS10', name: '10-Year Treasury Yield' },
+ { series: 'DCOILWTICO', name: 'WTI Crude Oil Price' },
+ ];
+ const results = [];
+ for (const ind of indicators) {
+ try {
+ const controller = new AbortController();
+ setTimeout(() => controller.abort(), 5000);
+ const res = await fetch(`https://fred.stlouisfed.org/graph/fredgraph.csv?id=${ind.series}&cosd=${new Date(Date.now() - 90*86400000).toISOString().split('T')[0]}`, {
+ signal: controller.signal,
+ headers: { 'User-Agent': 'Ken-Bot/1.0' }
+ });
+ if (!res.ok) continue;
+ const csv = await res.text();
+ const lines = csv.trim().split('\n');
+ if (lines.length < 2) continue;
+ const lastLine = lines[lines.length - 1];
+ const [date, value] = lastLine.split(',');
+ if (value && value !== '.') {
+ results.push({
+ title: `${ind.name}: ${value} (${date})`,
+ url: `https://fred.stlouisfed.org/series/${ind.series}`,
+ score: Math.round(parseFloat(value) * 100) || 0,
+ source: 'fred_economic',
+ keyword: ind.series,
+ });
+ }
+ } catch {}
+ }
+ return results;
+}
+
+// ── NWS Active Weather Alerts (real severe weather data for weather markets) ──
+async function scrapeNWSAlerts() {
+ try {
+ const controller = new AbortController();
+ setTimeout(() => controller.abort(), 8000);
+ const res = await fetch('https://api.weather.gov/alerts/active?status=actual&message_type=alert&limit=50', {
+ signal: controller.signal,
+ headers: { 'User-Agent': 'Ken-Bot/1.0 (ken@designerwallcoverings.com)', 'Accept': 'application/geo+json' }
+ });
+ if (!res.ok) return [];
+ const data = await res.json();
+ return (data.features || []).map(f => ({
+ title: `${f.properties.event}: ${f.properties.headline || f.properties.description?.substring(0, 200) || ''}`.substring(0, 500),
+ url: f.properties['@id'] || 'https://alerts.weather.gov',
+ score: f.properties.severity === 'Extreme' ? 100 : f.properties.severity === 'Severe' ? 75 : f.properties.severity === 'Moderate' ? 50 : 25,
+ num_comments: 0,
+ source: 'nws_alerts',
+ keyword: f.properties.event || 'weather',
+ }));
+ } catch (e) {
+ console.log(`[Ken] NWS Alerts failed: ${e.message}`);
+ return [];
+ }
+}
+
+// ── Congressional/Government Activity (GovTrack API) ──
+async function scrapeGovTrack() {
+ try {
+ const controller = new AbortController();
+ setTimeout(() => controller.abort(), 8000);
+ const res = await fetch('https://www.govtrack.us/api/v2/vote?order_by=-created&limit=20', {
+ signal: controller.signal,
+ headers: { 'User-Agent': 'Ken-Bot/1.0' }
+ });
+ if (!res.ok) return [];
+ const data = await res.json();
+ return (data.objects || []).map(v => ({
+ title: `${v.chamber === 'senate' ? 'Senate' : 'House'} Vote: ${v.question || v.result || 'Unknown'}`.substring(0, 500),
+ url: `https://www.govtrack.us${v.link || ''}`,
+ score: v.total_plus || 0,
+ num_comments: v.total_minus || 0,
+ source: 'govtrack',
+ keyword: v.category || 'legislation',
+ }));
+ } catch (e) {
+ console.log(`[Ken] GovTrack failed: ${e.message}`);
+ return [];
+ }
+}
+
+// ── X/Twitter via Nitter instances (public, no auth needed) ──
+async function scrapeNitterTrending() {
+ const nitterInstances = [
+ 'https://nitter.poast.org',
+ 'https://nitter.privacydev.net',
+ 'https://nitter.cz',
+ ];
+ const searchTerms = ['kalshi', 'polymarket', 'prediction market', 'fed rate decision', 'hurricane season'];
+ const results = [];
+ for (const term of searchTerms) {
+ for (const instance of nitterInstances) {
+ try {
+ const controller = new AbortController();
+ setTimeout(() => controller.abort(), 6000);
+ const url = `${instance}/search?f=tweets&q=${encodeURIComponent(term)}&since=`;
+ const res = await fetch(url, { signal: controller.signal, headers: { 'User-Agent': 'Mozilla/5.0' } });
+ if (!res.ok) continue;
+ const html = await res.text();
+ // Extract tweet text from Nitter HTML
+ const tweetMatches = html.match(/<div class="tweet-content[^"]*"[^>]*>([\s\S]*?)<\/div>/g) || [];
+ for (const match of tweetMatches.slice(0, 5)) {
+ const text = match.replace(/<[^>]+>/g, '').trim().substring(0, 500);
+ if (text.length > 10) {
+ results.push({
+ title: text,
+ url: `${instance}/search?q=${encodeURIComponent(term)}`,
+ score: 0,
+ num_comments: 0,
+ source: 'twitter_nitter',
+ keyword: term,
+ });
+ }
+ }
+ break; // One working instance per term is enough
+ } catch {} // Nitter instances are unreliable, fail silently
+ }
+ await new Promise(r => setTimeout(r, 2000));
+ }
+ return results;
+}
+
+// ── Discord Bot Intelligence (reads messages from joined servers) ──
+const DISCORD_BOT_TOKEN = 'MTQ3MjYyNDg2OTk3NDg2ODA2Mg.GifeyF.C5l9KqQUia-Ex54Ldg23fuxislxwf2QtmkXYII';
+const DISCORD_API = 'https://discord.com/api/v10';
+
+// Channel names to monitor (matched case-insensitive) — covers all Kalshi/Polymarket categories
+const DISCORD_CHANNEL_KEYWORDS = [
+ // Core
+ 'general', 'chat', 'discussion', 'lounge', 'main',
+ // Trading & Markets
+ 'trading', 'markets', 'predictions', 'analysis', 'strategy', 'signals', 'alerts',
+ 'arbitrage', 'polymarket', 'kalshi', 'bets', 'picks', 'plays', 'odds',
+ // News & Facts
+ 'news', 'breaking', 'headlines', 'updates', 'osint', 'intel', 'events',
+ // Weather
+ 'weather', 'hurricane', 'tropical', 'storm', 'forecast', 'severe', 'climate',
+ // Politics & Elections
+ 'politics', 'election', 'polling', 'congress', 'senate', 'trump', 'biden',
+ 'policy', 'legislation', 'vote', 'debate',
+ // Economics & Finance
+ 'economics', 'economy', 'finance', 'stocks', 'fed', 'inflation', 'rates',
+ 'macro', 'earnings', 'options', 'futures', 'bonds',
+ // Sports
+ 'sports', 'nfl', 'nba', 'mlb', 'nhl', 'soccer', 'football', 'basketball',
+ 'baseball', 'ufc', 'mma', 'boxing', 'f1', 'golf', 'tennis',
+ // Crypto
+ 'crypto', 'bitcoin', 'btc', 'ethereum', 'eth', 'defi', 'altcoin', 'solana',
+ // Geopolitics
+ 'geopolitics', 'ukraine', 'russia', 'china', 'military', 'conflict', 'war', 'nato',
+ // Entertainment
+ 'entertainment', 'movies', 'film', 'oscars', 'grammys', 'awards', 'box-office',
+ 'music', 'tv', 'streaming', 'celebrity',
+ // Science & Space
+ 'space', 'spacex', 'nasa', 'launch', 'science', 'rocket',
+ // Tech & AI
+ 'tech', 'ai', 'artificial', 'openai', 'gpt', 'machine-learning', 'nvidia',
+];
+
+async function discordFetch(endpoint) {
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), 10000);
+ const res = await fetch(`${DISCORD_API}${endpoint}`, {
+ headers: { Authorization: `Bot ${DISCORD_BOT_TOKEN}`, 'Content-Type': 'application/json' },
+ signal: controller.signal,
+ });
+ clearTimeout(timeout);
+ if (!res.ok) {
+ if (res.status === 429) {
+ const retry = await res.json().catch(() => ({}));
+ const wait = (retry.retry_after || 5) * 1000;
+ console.log(`[Ken] Discord rate limited, waiting ${wait}ms`);
+ await new Promise(r => setTimeout(r, wait));
+ return null;
+ }
+ return null;
+ }
+ return res.json();
+}
+
+async function scrapeDiscord(limit = 50) {
+ const results = [];
+ try {
+ // 1. Get all guilds the bot is in
+ const guilds = await discordFetch('/users/@me/guilds');
+ if (!guilds || !Array.isArray(guilds)) {
+ console.log('[Ken] Discord: no guilds found (bot may not have joined any servers yet)');
+ return [];
+ }
+ console.log(`[Ken] Discord: bot is in ${guilds.length} server(s): ${guilds.map(g => g.name).join(', ')}`);
+
+ for (const guild of guilds) {
+ // 2. Get channels for this guild
+ const channels = await discordFetch(`/guilds/${guild.id}/channels`);
+ if (!channels || !Array.isArray(channels)) continue;
+
+ // 3. Filter to text channels matching keywords
+ const textChannels = channels.filter(ch => {
+ if (ch.type !== 0) return false; // type 0 = text channel
+ const name = (ch.name || '').toLowerCase();
+ return DISCORD_CHANNEL_KEYWORDS.some(kw => name.includes(kw));
+ });
+
+ console.log(`[Ken] Discord [${guild.name}]: monitoring ${textChannels.length}/${channels.filter(c => c.type === 0).length} text channels`);
+
+ for (const channel of textChannels.slice(0, 15)) { // cap at 15 channels per guild
+ try {
+ const messages = await discordFetch(`/channels/${channel.id}/messages?limit=${Math.min(limit, 50)}`);
+ if (!messages || !Array.isArray(messages)) continue;
+
+ // Only messages from last 2 hours (fresh intel)
+ const cutoff = Date.now() - (2 * 60 * 60 * 1000);
+ for (const msg of messages) {
+ const msgTime = new Date(msg.timestamp).getTime();
+ if (msgTime < cutoff) continue;
+ if (!msg.content || msg.content.length < 20) continue;
+ if (msg.author?.bot) continue; // skip bot messages
+
+ results.push({
+ title: msg.content.substring(0, 500),
+ url: `https://discord.com/channels/${guild.id}/${channel.id}/${msg.id}`,
+ source: `Discord ${guild.name}`,
+ channel: channel.name,
+ author: msg.author?.username || 'unknown',
+ score: (msg.reactions || []).reduce((sum, r) => sum + (r.count || 0), 0),
+ num_comments: msg.referenced_message ? 1 : 0, // thread indicator
+ created: new Date(msg.timestamp),
+ });
+ }
+ // Rate limit: 500ms between channel reads
+ await new Promise(r => setTimeout(r, 500));
+ } catch (e) {
+ console.log(`[Ken] Discord channel ${channel.name} error: ${e.message}`);
+ }
+ }
+ await new Promise(r => setTimeout(r, 1000)); // between guilds
+ }
+ console.log(`[Ken] Discord: ${results.length} messages from ${guilds.length} server(s)`);
+ } catch (e) {
+ console.log(`[Ken] Discord scrape failed: ${e.message}`);
+ }
+ return results;
+}
+
+// ══════════════════════════════════════════════
+// INTELLIGENCE LOOP (every 30 min) — Reddit, HN, News, Metaculus, Discord
+// ══════════════════════════════════════════════
+function logMemory(label) {
+ const mem = process.memoryUsage();
+ const rss = Math.round(mem.rss / 1024 / 1024);
+ const heap = Math.round(mem.heapUsed / 1024 / 1024);
+ if (rss > 500) console.log(`[Ken] MEM ${label}: RSS=${rss}MB Heap=${heap}MB`);
+}
+
+async function redditIntelligenceLoop() {
+ console.log('[Ken] Running Reddit intelligence sweep...');
+ logMemory('sweep-start');
+ let totalPosts = 0;
+ try {
+ // Get tracking config from DB
+ const { rows: trackers } = await kenQ('SELECT * FROM ken_reddit_tracking WHERE enabled = true');
+
+ // Process tracked subreddits in parallel batches of 12 (maxed for 16 cores)
+ const TRACKER_BATCH = 12;
+ for (let i = 0; i < trackers.length; i += TRACKER_BATCH) {
+ const batch = trackers.slice(i, i + TRACKER_BATCH);
+ const results = await Promise.allSettled(
+ batch.map(tracker => scrapeReddit(tracker.subreddit, tracker.search_term, 20)
+ .then(posts => ({ tracker, posts })))
+ );
+ for (const result of results) {
+ if (result.status !== 'fulfilled') continue;
+ const { tracker, posts } = result.value;
+ for (const post of posts) {
+ const sentiment = scoreSentiment(post.title + ' ' + post.selftext);
+ if (post.score > 2 || post.num_comments > 1) {
+ await kenQ(`
+ INSERT INTO ken_sentiment (source, subreddit, keyword, post_title, post_url, score, num_comments, sentiment_score, relevance_ticker, raw_text)
+ VALUES ('reddit', $1, $2, $3, $4, $5, $6, $7, $8, $9)
+ ON CONFLICT DO NOTHING
+ `, [
+ tracker.subreddit, tracker.search_term, post.title, post.url,
+ post.score, post.num_comments, sentiment,
+ (tracker.related_tickers || [])[0] || null,
+ (post.selftext || '').substring(0, 1000),
+ ]);
+ totalPosts++;
+ }
+ }
+ }
+ await new Promise(r => setTimeout(r, 500)); // 0.5s between batches (was 1.5s)
+ }
+
+ // Also scrape hot posts from key subreddits for general intelligence
+ // Categories: Weather | Politics | Economics | Sports | Crypto | Geopolitics | Entertainment | Science/Space | Tech/AI | General Sentiment
+ const hotSubs = [
+ // ── Core prediction markets ──
+ 'Kalshi', 'Polymarket', 'PredictionMarket', 'sportsbook',
+ // ── Weather (hurricane/temp/storm markets) ──
+ 'TropicalWeather', 'weather', 'tornado', 'hurricane', 'climate',
+ 'NaturalGas', 'energy', 'propane', 'HomeImprovement',
+ // ── Heating Bills & Utility Costs ──
+ 'personalfinance', 'Frugal', 'povertyfinance', 'homeowners',
+ 'HVAC', 'utilities', 'electricvehicles',
+ // ── Politics & Elections ──
+ 'politics', 'Conservative', 'Liberal', 'NeutralPolitics', 'PoliticalDiscussion',
+ 'fivethirtyeight', 'elections', 'supremecourt', 'moderatepolitics', 'law',
+ // ── Economics & Finance ──
+ 'economics', 'wallstreetbets', 'economy', 'inflation', 'FederalReserve',
+ 'StockMarket', 'investing', 'RealEstate', 'finance', 'commodities',
+ // ── Sports ──
+ 'nfl', 'nba', 'baseball', 'soccer', 'MMA', 'CFB', 'CollegeBasketball',
+ 'formula1', 'golf', 'hockey', 'tennis', 'boxing',
+ // ── Crypto ──
+ 'CryptoMarkets', 'Bitcoin', 'ethereum', 'CryptoCurrency', 'BitcoinMarkets', 'solana',
+ // ── Geopolitics ──
+ 'worldnews', 'geopolitics', 'UkrainianConflict', 'ukraine', 'China',
+ 'MiddleEastNews', 'foreignpolicy', 'military',
+ // ── Entertainment (awards/box office markets) ──
+ 'movies', 'boxoffice', 'television', 'Oscars', 'Music', 'entertainment',
+ // ── Science & Space (launch/milestone markets) ──
+ 'SpaceX', 'space', 'nasa', 'science', 'Futurology',
+ // ── Tech & AI ──
+ 'technology', 'artificial', 'MachineLearning', 'OpenAI', 'singularity', 'Nvidia',
+ // ── General sentiment ──
+ 'news', 'OutOfTheLoop', 'AskReddit', 'TrueReddit', 'dataisbeautiful',
+ ];
+ // Process subreddits in parallel batches of 12 (maxed for 16 cores)
+ const REDDIT_BATCH = 12;
+ for (let i = 0; i < hotSubs.length; i += REDDIT_BATCH) {
+ const batch = hotSubs.slice(i, i + REDDIT_BATCH);
+ const results = await Promise.allSettled(batch.map(sub => scrapeSubredditHot(sub, 8)));
+ for (let j = 0; j < results.length; j++) {
+ if (results[j].status !== 'fulfilled') continue;
+ const sub = batch[j];
+ for (const post of results[j].value) {
+ if (post.score > 30) { // lower threshold to catch more sentiment signals
+ const sentiment = scoreSentiment(post.title);
+ await kenQ(`
+ INSERT INTO ken_sentiment (source, subreddit, keyword, post_title, post_url, score, num_comments, sentiment_score, raw_text)
+ VALUES ('reddit_hot', $1, 'hot', $2, $3, $4, $5, $6, $7)
+ ON CONFLICT DO NOTHING
+ `, [sub, post.title, post.url, post.score, post.num_comments, sentiment, '']);
+ totalPosts++;
+ }
+ }
+ }
+ await new Promise(r => setTimeout(r, 500)); // 0.5s between batches (was 1.5s)
+ }
+ console.log(`[Ken] Reddit hot: ${hotSubs.length} subreddits across 10 categories`);
+ logMemory('after-reddit');
+ if (global.gc) global.gc();
+
+ // Scrape Google News for top market topics (covers all Kalshi categories)
+ const newsQueries = [
+ // Politics & elections
+ 'trump cabinet resign', 'federal reserve chair nomination', '2028 presidential election',
+ 'trump executive order', 'government shutdown', 'supreme court ruling',
+ // Economics
+ 'CPI inflation report', 'federal reserve rate decision', 'jobs report unemployment',
+ 'GDP growth', 'recession forecast',
+ // Weather
+ 'hurricane forecast atlantic', 'severe weather outbreak', 'temperature record',
+ // Geopolitics
+ 'ukraine russia ceasefire', 'china taiwan', 'middle east conflict',
+ // Crypto
+ 'bitcoin price prediction', 'SEC crypto regulation',
+ // Entertainment
+ 'oscar nominations', 'box office weekend',
+ // Space
+ 'SpaceX launch', 'NASA artemis',
+ ];
+ // Process Google News in batches of 5 (21 serial × 1s = too slow)
+ const NEWS_QUERY_BATCH = 5;
+ for (let i = 0; i < newsQueries.length; i += NEWS_QUERY_BATCH) {
+ const batch = newsQueries.slice(i, i + NEWS_QUERY_BATCH);
+ const results = await Promise.allSettled(
+ batch.map(nq => scrapeGoogleNews(nq, 5).then(articles => ({ nq, articles })))
+ );
+ for (const result of results) {
+ if (result.status !== 'fulfilled') continue;
+ const { nq, articles } = result.value;
+ for (const article of articles) {
+ const sentiment = scoreSentiment(article.title);
+ await kenQ(`
+ INSERT INTO ken_sentiment (source, subreddit, keyword, post_title, post_url, score, sentiment_score)
+ VALUES ('google_news', $1, $2, $3, $4, 0, $5)
+ ON CONFLICT DO NOTHING
+ `, [article.source || 'news', nq, article.title, article.url, sentiment]);
+ totalPosts++;
+ }
+ }
+ await new Promise(r => setTimeout(r, 1000));
+ }
+
+ // ── Hacker News (tech/policy sentiment) ──
+ const hnQueries = ['trump policy', 'federal reserve', 'tariff', 'ukraine russia', null]; // null = front page
+ for (const hq of hnQueries) {
+ try {
+ const stories = await scrapeHackerNews(hq, 10);
+ for (const story of stories) {
+ if (story.score > 5 || story.num_comments > 3) {
+ const sentiment = scoreSentiment(story.title);
+ await kenQ(`
+ INSERT INTO ken_sentiment (source, subreddit, keyword, post_title, post_url, score, num_comments, sentiment_score, raw_text)
+ VALUES ('hackernews', 'hackernews', $1, $2, $3, $4, $5, $6, '')
+ ON CONFLICT DO NOTHING
+ `, [hq || 'front_page', story.title, story.url, story.score, story.num_comments, sentiment]);
+ totalPosts++;
+ }
+ }
+ } catch {}
+ await new Promise(r => setTimeout(r, 1500));
+ }
+
+ // ── All News Channels (BBC, NYT, WaPo, Politico, CNBC, Bloomberg, etc.) ──
+ try {
+ let newsStored = 0;
+ // Process feeds in small batches to limit memory — don't hold all articles at once
+ const batchSize = 5;
+ for (let i = 0; i < NEWS_FEEDS.length; i += batchSize) {
+ const batch = NEWS_FEEDS.slice(i, i + batchSize);
+ const results = await Promise.allSettled(
+ batch.map(feed => scrapeRSSFeed(feed.url, feed.source, 6))
+ );
+ for (const result of results) {
+ if (result.status !== 'fulfilled') continue;
+ for (const article of result.value) {
+ const sentiment = scoreSentiment(article.title);
+ await kenQ(`
+ INSERT INTO ken_sentiment (source, subreddit, keyword, post_title, post_url, score, sentiment_score, raw_text)
+ VALUES ($1, $2, 'news', $3, $4, 0, $5, '')
+ ON CONFLICT DO NOTHING
+ `, [article.source.toLowerCase().replace(/\s+/g, '_'), article.source, article.title, article.url, sentiment]);
+ newsStored++;
+ }
+ }
+ await new Promise(r => setTimeout(r, 300));
+ }
+ totalPosts += newsStored;
+ console.log(`[Ken] News channels: ${newsStored} articles from ${NEWS_FEEDS.length} feeds`);
+ } catch (e) {
+ console.log(`[Ken] News channels failed: ${e.message}`);
+ }
+ logMemory('after-news');
+ if (global.gc) global.gc();
+
+ // ── Metaculus (prediction market community consensus) ──
+ try {
+ const metaQuestions = await scrapeMetaculus();
+ for (const mq of metaQuestions) {
+ const sentiment = scoreSentiment(mq.title);
+ const predText = mq.community_prediction ? `Community: ${Math.round(mq.community_prediction * 100)}%` : '';
+ await kenQ(`
+ INSERT INTO ken_sentiment (source, subreddit, keyword, post_title, post_url, score, num_comments, sentiment_score, raw_text)
+ VALUES ('metaculus', 'metaculus', 'predictions', $1, $2, $3, $4, $5, $6)
+ ON CONFLICT DO NOTHING
+ `, [mq.title, mq.url, mq.num_predictions || 0, 0, sentiment, predText]);
+ totalPosts++;
+ }
+ console.log(`[Ken] Metaculus: ${metaQuestions.length} predictions`);
+ } catch (e) {
+ console.log(`[Ken] Metaculus failed: ${e.message}`);
+ }
+
+ // ── Manifold Markets (cross-reference prediction probabilities) ──
+ let manifoldTotal = 0;
+ try {
+ const manifoldQueries = ['trump', 'fed rate', 'election 2028', 'ukraine', 'tariff'];
+ const manifoldMkts = await scrapeManifold(manifoldQueries);
+ for (const m of manifoldMkts) {
+ const sentiment = scoreSentiment(m.title);
+ await kenQ(`
+ INSERT INTO ken_sentiment (source, subreddit, keyword, post_title, post_url, score, num_comments, sentiment_score, raw_text)
+ VALUES ('manifold', 'manifold', $1, $2, $3, $4, 0, $5, $6)
+ ON CONFLICT DO NOTHING
+ `, [m.source, m.title, m.url, m.volume || 0, sentiment, `prob:${m.probability}% vol:${m.volume}`]);
+ manifoldTotal++;
+ }
+ } catch {}
+ console.log(`[Ken] Manifold Markets: ${manifoldTotal} prediction markets`);
+
+ // ── Kalshi & Polymarket Reddit search (community sentiment on specific trades) ──
+ let predMarketRedditTotal = 0;
+ const pmSearchTerms = ['arbitrage', 'free money', 'mispriced', 'edge'];
+ for (const term of pmSearchTerms) {
+ for (const sub of ['Kalshi', 'Polymarket']) {
+ try {
+ const posts = await scrapeReddit(sub, term, 5);
+ for (const post of posts) {
+ const sentiment = scoreSentiment(post.title);
+ await kenQ(`
+ INSERT INTO ken_sentiment (source, subreddit, keyword, post_title, post_url, score, num_comments, sentiment_score, raw_text)
+ VALUES ('reddit_predmkt', $1, $2, $3, $4, $5, $6, $7, '')
+ ON CONFLICT DO NOTHING
+ `, [sub, term, post.title, post.url, post.score || 0, post.num_comments || 0, sentiment]);
+ predMarketRedditTotal++;
+ }
+ } catch {}
+ }
+ await new Promise(r => setTimeout(r, 2000));
+ }
+ console.log(`[Ken] Prediction market Reddit: ${predMarketRedditTotal} posts from r/Kalshi + r/Polymarket`);
+ if (global.gc) global.gc();
+
+ // ── GDELT TV News (CNN, Fox closed captions) ──
+ const tvStations = ['CNN', 'FOXNEWS'];
+ const tvQueries = ['trump', 'tariff', 'ukraine', 'election'];
+ let tvTotal = 0;
+ for (const station of tvStations) {
+ for (const tq of tvQueries) {
+ try {
+ const clips = await scrapeGDELTtv(tq, station, 5);
+ for (const clip of clips) {
+ if (clip.title && clip.title.length > 15) {
+ const sentiment = scoreSentiment(clip.title);
+ await kenQ(`
+ INSERT INTO ken_sentiment (source, subreddit, keyword, post_title, post_url, score, sentiment_score, raw_text)
+ VALUES ('tv_news', $1, $2, $3, $4, 0, $5, $6)
+ ON CONFLICT DO NOTHING
+ `, [clip.source || station, tq, clip.title.substring(0, 500), clip.url, sentiment, clip.show || '']);
+ tvTotal++;
+ }
+ }
+ } catch {}
+ await new Promise(r => setTimeout(r, 500));
+ }
+ }
+ console.log(`[Ken] GDELT TV: ${tvTotal} clips from ${tvStations.length} stations`);
+
+ // ── YouTube News Channels (CNN, MSNBC, Fox, Bloomberg, CNBC, etc.) ──
+ try {
+ const ytVideos = await scrapeYouTubeRSS();
+ let ytStored = 0;
+ for (const video of ytVideos) {
+ const sentiment = scoreSentiment(video.title);
+ await kenQ(`
+ INSERT INTO ken_sentiment (source, subreddit, keyword, post_title, post_url, score, sentiment_score, raw_text)
+ VALUES ('youtube_news', $1, 'video', $2, $3, 0, $4, '')
+ ON CONFLICT DO NOTHING
+ `, [video.source, video.title, video.url, sentiment]);
+ ytStored++;
+ }
+ totalPosts += ytStored;
+ console.log(`[Ken] YouTube News: ${ytStored} videos from 9 channels`);
+ } catch (e) {
+ console.log(`[Ken] YouTube News failed: ${e.message}`);
+ }
+ if (global.gc) global.gc();
+
+ // ── Lemmy (federated Reddit — public API, no auth) ──
+ let lemmyTotal = 0;
+ try {
+ const lemmyPosts = await scrapeLemmy('Hot', 25);
+ for (const p of lemmyPosts) {
+ const sentiment = scoreSentiment(p.title);
+ await kenQ(`
+ INSERT INTO ken_sentiment (source, subreddit, keyword, post_title, post_url, score, num_comments, sentiment_score, raw_text)
+ VALUES ('lemmy', $1, 'hot', $2, $3, $4, $5, $6, '')
+ ON CONFLICT DO NOTHING
+ `, [p.source, p.title, p.url, p.score || 0, p.num_comments || 0, sentiment]);
+ lemmyTotal++;
+ }
+ } catch {}
+ console.log(`[Ken] Lemmy: ${lemmyTotal} posts`);
+
+ // ── Lobsters (tech/policy news — public JSON API) ──
+ let lobstersTotal = 0;
+ try {
+ const stories = await scrapeLobsters(25);
+ for (const s of stories) {
+ const sentiment = scoreSentiment(s.title);
+ await kenQ(`
+ INSERT INTO ken_sentiment (source, subreddit, keyword, post_title, post_url, score, num_comments, sentiment_score, raw_text)
+ VALUES ('lobsters', $1, $2, $3, $4, $5, $6, $7, '')
+ ON CONFLICT DO NOTHING
+ `, [s.author || 'lobsters', s.tags || 'tech', s.title, s.url, s.score || 0, s.num_comments || 0, sentiment]);
+ lobstersTotal++;
+ }
+ } catch {}
+ console.log(`[Ken] Lobsters: ${lobstersTotal} stories`);
+
+ // ── Tildes (curated discussion — RSS) ──
+ let tildesTotal = 0;
+ try {
+ const tildesPosts = await scrapeTildes();
+ for (const p of tildesPosts) {
+ const sentiment = scoreSentiment(p.title);
+ await kenQ(`
+ INSERT INTO ken_sentiment (source, subreddit, keyword, post_title, post_url, score, sentiment_score, raw_text)
+ VALUES ('tildes', 'tildes', 'discussion', $1, $2, 0, $3, '')
+ ON CONFLICT DO NOTHING
+ `, [p.title, p.url, sentiment]);
+ tildesTotal++;
+ }
+ } catch {}
+ console.log(`[Ken] Tildes: ${tildesTotal} discussions`);
+
+ // ── Bluesky (trending feeds — getFeed API) ──
+ let bskyTotal = 0;
+ try {
+ const posts = await scrapeBluesky();
+ for (const p of posts) {
+ if ((p.score || 0) > 2 || (p.num_comments || 0) > 1 || p.title.length > 30) {
+ const sentiment = scoreSentiment(p.title);
+ await kenQ(`
+ INSERT INTO ken_sentiment (source, subreddit, keyword, post_title, post_url, score, num_comments, sentiment_score, raw_text)
+ VALUES ('bluesky', $1, $2, $3, $4, $5, $6, $7, '')
+ ON CONFLICT DO NOTHING
+ `, [p.author || 'bluesky', p.source || 'trending', p.title, p.url, p.score || 0, p.num_comments || 0, sentiment]);
+ bskyTotal++;
+ }
+ }
+ } catch {}
+ console.log(`[Ken] Bluesky: ${bskyTotal} posts`);
+
+ // ── Mastodon/Fediverse trending ──
+ try {
+ const mastodonPosts = await scrapeMastodon();
+ let mastoTotal = 0;
+ for (const p of mastodonPosts) {
+ const sentiment = scoreSentiment(p.title);
+ await kenQ(`
+ INSERT INTO ken_sentiment (source, subreddit, keyword, post_title, post_url, score, num_comments, sentiment_score, raw_text)
+ VALUES ('mastodon', $1, 'trending', $2, $3, $4, $5, $6, '')
+ ON CONFLICT DO NOTHING
+ `, [p.source, p.title, p.url, p.score || 0, p.num_comments || 0, sentiment]);
+ mastoTotal++;
+ }
+ totalPosts += mastoTotal;
+ console.log(`[Ken] Mastodon: ${mastoTotal} trending`);
+ } catch (e) {
+ console.log(`[Ken] Mastodon failed: ${e.message}`);
+ }
+
+ totalPosts += tvTotal + lemmyTotal + lobstersTotal + tildesTotal + bskyTotal;
+ totalPosts += manifoldTotal + predMarketRedditTotal;
+
+ // ── PredictIt (cross-reference prediction market) ──
+ let predictItTotal = 0;
+ try {
+ const piMarkets = await scrapePredictIt();
+ for (const m of piMarkets) {
+ const sentiment = scoreSentiment(m.title);
+ await kenQ(`
+ INSERT INTO ken_sentiment (source, subreddit, keyword, post_title, post_url, score, num_comments, sentiment_score, raw_text)
+ VALUES ('predictit', 'predictit', 'market', $1, $2, $3, $4, $5, $6)
+ ON CONFLICT DO NOTHING
+ `, [m.title, m.url, m.score, m.num_comments || 0, sentiment, m.extra || '']);
+ predictItTotal++;
+ }
+ totalPosts += predictItTotal;
+ console.log(`[Ken] PredictIt: ${predictItTotal} markets`);
+ } catch (e) {
+ console.log(`[Ken] PredictIt failed: ${e.message}`);
+ }
+
+ // ── FRED Economic Indicators (real data for economic markets) ──
+ let fredTotal = 0;
+ try {
+ const fredData = await scrapeFredIndicators();
+ for (const ind of fredData) {
+ await kenQ(`
+ INSERT INTO ken_sentiment (source, subreddit, keyword, post_title, post_url, score, sentiment_score, raw_text)
+ VALUES ('fred_economic', 'fred', $1, $2, $3, $4, 0, '')
+ ON CONFLICT DO NOTHING
+ `, [ind.keyword, ind.title, ind.url, ind.score]);
+ fredTotal++;
+ }
+ totalPosts += fredTotal;
+ console.log(`[Ken] FRED Economic: ${fredTotal} indicators`);
+ } catch (e) {
+ console.log(`[Ken] FRED failed: ${e.message}`);
+ }
+
+ // ── NWS Active Weather Alerts (severe weather data for weather markets) ──
+ let nwsAlertTotal = 0;
+ try {
+ const alerts = await scrapeNWSAlerts();
+ for (const alert of alerts) {
+ const sentiment = scoreSentiment(alert.title);
+ await kenQ(`
+ INSERT INTO ken_sentiment (source, subreddit, keyword, post_title, post_url, score, num_comments, sentiment_score, raw_text)
+ VALUES ('nws_alerts', 'weather', $1, $2, $3, $4, 0, $5, '')
+ ON CONFLICT DO NOTHING
+ `, [alert.keyword, alert.title, alert.url, alert.score, sentiment]);
+ nwsAlertTotal++;
+ }
+ totalPosts += nwsAlertTotal;
+ console.log(`[Ken] NWS Alerts: ${nwsAlertTotal} active alerts`);
+ } catch (e) {
+ console.log(`[Ken] NWS Alerts failed: ${e.message}`);
+ }
+
+ // ── GovTrack Congressional Votes (legislation for political markets) ──
+ let govTrackTotal = 0;
+ try {
+ const votes = await scrapeGovTrack();
+ for (const v of votes) {
+ const sentiment = scoreSentiment(v.title);
+ await kenQ(`
+ INSERT INTO ken_sentiment (source, subreddit, keyword, post_title, post_url, score, num_comments, sentiment_score, raw_text)
+ VALUES ('govtrack', 'congress', $1, $2, $3, $4, $5, $6, '')
+ ON CONFLICT DO NOTHING
+ `, [v.keyword, v.title, v.url, v.score, v.num_comments || 0, sentiment]);
+ govTrackTotal++;
+ }
+ totalPosts += govTrackTotal;
+ console.log(`[Ken] GovTrack: ${govTrackTotal} congressional votes`);
+ } catch (e) {
+ console.log(`[Ken] GovTrack failed: ${e.message}`);
+ }
+
+ // ── Twitter/X via Nitter (public sentiment, no auth needed) ──
+ let nitterTotal = 0;
+ try {
+ const tweets = await scrapeNitterTrending();
+ for (const t of tweets) {
+ const sentiment = scoreSentiment(t.title);
+ await kenQ(`
+ INSERT INTO ken_sentiment (source, subreddit, keyword, post_title, post_url, score, num_comments, sentiment_score, raw_text)
+ VALUES ('twitter_nitter', 'twitter', $1, $2, $3, 0, 0, $4, '')
+ ON CONFLICT DO NOTHING
+ `, [t.keyword, t.title, t.url, sentiment]);
+ nitterTotal++;
+ }
+ totalPosts += nitterTotal;
+ console.log(`[Ken] Twitter/Nitter: ${nitterTotal} tweets`);
+ } catch (e) {
+ console.log(`[Ken] Twitter/Nitter failed: ${e.message}`);
+ }
+
+ // ── Discord (Kalshi, Polymarket, Prediction Markets servers) ──
+ let discordTotal = 0;
+ try {
+ const discordMessages = await scrapeDiscord(30);
+ for (const msg of discordMessages) {
+ const sentiment = scoreSentiment(msg.title);
+ await kenQ(`
+ INSERT INTO ken_sentiment (source, subreddit, keyword, post_title, post_url, score, num_comments, sentiment_score, raw_text)
+ VALUES ('discord', $1, $2, $3, $4, $5, $6, $7, $8)
+ ON CONFLICT DO NOTHING
+ `, [
+ msg.source, msg.channel || 'general', msg.title.substring(0, 500),
+ msg.url, msg.score || 0, msg.num_comments || 0, sentiment,
+ (msg.author || '').substring(0, 200),
+ ]);
+ discordTotal++;
+ }
+ totalPosts += discordTotal;
+ console.log(`[Ken] Discord: ${discordTotal} messages`);
+ } catch (e) {
+ console.log(`[Ken] Discord failed: ${e.message}`);
+ }
+ if (global.gc) global.gc();
+
+ logMemory('sweep-end');
+ if (global.gc) global.gc();
+ console.log(`[Ken] ═══ FULL SWEEP: ${totalPosts} items (Reddit, HN, ${NEWS_FEEDS.length} feeds, TV, YT, Manifold, r/Kalshi, r/Polymarket, Lemmy, Lobsters, Tildes, Bluesky, Mastodon, Metaculus, PredictIt, FRED, NWS Alerts, GovTrack, Twitter, Discord) ═══`);
+ return totalPosts;
+ } catch (e) {
+ console.error('[Ken] Intelligence sweep error:', e.message);
+ logMemory('sweep-error');
+ return 0;
+ }
+}
+
+// ══════════════════════════════════════════════════════════════════════════════
+// SIGNAL PIPELINE: News → Sentiment → Event Map → Probability → Signals → Risk
+// Pipeline: narrative shifts → probability inference → edge detection
+// ══════════════════════════════════════════════════════════════════════════════
+
+// ── Enhanced Event-Specific Sentiment Engine ──
+// Unlike scoreSentiment() which is general, this maps headlines to specific market directions
+const EVENT_SENTIMENT_RULES = [
+ // Weather markets
+ { pattern: /hurricane|tropical storm|cyclone/i, category: 'weather', direction: 'severity', boost: 0.3 },
+ { pattern: /category\s*[3-5]|major hurricane|extreme/i, category: 'weather', direction: 'severity', boost: 0.5 },
+ { pattern: /weakens|dissipates|downgrade/i, category: 'weather', direction: 'severity', boost: -0.4 },
+ { pattern: /record heat|heat wave|above normal/i, category: 'weather', direction: 'temperature_high', boost: 0.4 },
+ { pattern: /cold snap|polar vortex|below normal|freeze/i, category: 'weather', direction: 'temperature_low', boost: 0.4 },
+ { pattern: /heavy rain|flood|rainfall record/i, category: 'weather', direction: 'precipitation_high', boost: 0.4 },
+ { pattern: /drought|dry spell|no rain/i, category: 'weather', direction: 'precipitation_low', boost: 0.4 },
+ // Political markets
+ { pattern: /resign|step down|quit|fired/i, category: 'politics', direction: 'negative', boost: 0.5 },
+ { pattern: /appointed|confirmed|sworn in|nominated/i, category: 'politics', direction: 'positive', boost: 0.4 },
+ { pattern: /impeach|investigation|scandal|indicted/i, category: 'politics', direction: 'negative', boost: 0.4 },
+ { pattern: /leading|ahead|polling|surge in polls/i, category: 'politics', direction: 'positive', boost: 0.3 },
+ { pattern: /trailing|behind|falling|losing ground/i, category: 'politics', direction: 'negative', boost: 0.3 },
+ { pattern: /shutdown|deadlock|stalemate/i, category: 'politics', direction: 'shutdown_yes', boost: 0.5 },
+ { pattern: /deal reached|agreement|bipartisan|passed/i, category: 'politics', direction: 'shutdown_no', boost: -0.4 },
+ // Economic markets
+ { pattern: /rate cut|dovish|easing/i, category: 'economics', direction: 'rate_down', boost: 0.4 },
+ { pattern: /rate hike|hawkish|tightening/i, category: 'economics', direction: 'rate_up', boost: 0.4 },
+ { pattern: /inflation.*(?:hot|higher|above|surge|accelerat)/i, category: 'economics', direction: 'inflation_up', boost: 0.4 },
+ { pattern: /inflation.*(?:cool|lower|below|slow|deceler)/i, category: 'economics', direction: 'inflation_down', boost: 0.4 },
+ { pattern: /recession|contraction|GDP.*(?:negative|shrink)/i, category: 'economics', direction: 'recession_yes', boost: 0.5 },
+ { pattern: /growth|expansion|GDP.*(?:beat|strong|positive)/i, category: 'economics', direction: 'recession_no', boost: -0.4 },
+ { pattern: /jobs.*(?:beat|strong|added more)/i, category: 'economics', direction: 'jobs_strong', boost: 0.3 },
+ { pattern: /jobs.*(?:miss|weak|fewer)/i, category: 'economics', direction: 'jobs_weak', boost: 0.3 },
+ // Crypto markets
+ { pattern: /bitcoin.*(?:new high|surge|rally|breakout|100k|150k)/i, category: 'crypto', direction: 'btc_up', boost: 0.4 },
+ { pattern: /bitcoin.*(?:crash|plunge|selloff|bear)/i, category: 'crypto', direction: 'btc_down', boost: 0.4 },
+ { pattern: /SEC.*(?:approve|green light)/i, category: 'crypto', direction: 'btc_up', boost: 0.3 },
+ { pattern: /SEC.*(?:reject|deny|sue)/i, category: 'crypto', direction: 'btc_down', boost: 0.3 },
+ // Sports/entertainment
+ { pattern: /favou?rite|odds.*increase|bet.*heavy/i, category: 'sports', direction: 'favourite_stronger', boost: 0.3 },
+ { pattern: /upset|underdog|surprise/i, category: 'sports', direction: 'favourite_weaker', boost: 0.3 },
+ { pattern: /injured|out for|suspended|DNP/i, category: 'sports', direction: 'team_weaker', boost: 0.4 },
+ // Space/tech
+ { pattern: /launch.*(?:success|orbit|nominal)/i, category: 'space', direction: 'launch_success', boost: 0.5 },
+ { pattern: /launch.*(?:scrub|delay|abort|fail)/i, category: 'space', direction: 'launch_fail', boost: 0.5 },
+ // Geopolitics
+ { pattern: /ceasefire|peace.*(?:deal|talks|agreement)/i, category: 'geopolitics', direction: 'de_escalation', boost: 0.5 },
+ { pattern: /escalat|offensive|invasion|attack|strike/i, category: 'geopolitics', direction: 'escalation', boost: 0.4 },
+];
+
+function scoreEventSentiment(headline, marketTitle = '') {
+ const text = `${headline} ${marketTitle}`.toLowerCase();
+ const result = {
+ sentiment: 0,
+ confidence: 0,
+ magnitude: 0,
+ category: 'general',
+ direction: 'neutral',
+ matchedRules: [],
+ };
+
+ // Apply rule-based event-specific scoring
+ for (const rule of EVENT_SENTIMENT_RULES) {
+ if (rule.pattern.test(text)) {
+ result.sentiment += rule.boost;
+ result.magnitude += Math.abs(rule.boost);
+ result.category = rule.category;
+ result.direction = rule.direction;
+ result.matchedRules.push(rule.direction);
+ }
+ }
+
+ // Certainty language modifiers
+ const certainWords = /confirm|official|announce|breaking|just.*happen/i;
+ const uncertainWords = /may|might|could|rumor|unconfirm|speculat|sources say/i;
+ if (certainWords.test(text)) { result.confidence += 0.3; result.magnitude *= 1.2; }
+ if (uncertainWords.test(text)) { result.confidence -= 0.2; result.magnitude *= 0.7; }
+
+ // Multiple source agreement boosts confidence
+ if (result.matchedRules.length > 1) result.confidence += 0.15;
+
+ // Normalize
+ result.sentiment = Math.max(-1, Math.min(1, result.sentiment));
+ result.confidence = Math.max(0, Math.min(1, 0.5 + result.confidence)); // base confidence 0.5
+ result.magnitude = Math.min(1, result.magnitude);
+
+ return result;
+}
+
+// ── Event Mapper: Map news entities → Kalshi market tickers ──
+// Uses keyword-based + fuzzy matching to connect news to specific contracts
+const MARKET_CATEGORY_KEYWORDS = {
+ // Weather
+ 'temperature': ['temperature', 'temp', 'heat', 'cold', 'warm', 'degree', 'fahrenheit', 'celsius'],
+ 'hurricane': ['hurricane', 'tropical', 'cyclone', 'storm', 'named storm'],
+ 'rainfall': ['rain', 'rainfall', 'precipitation', 'flood', 'drought', 'inches'],
+ // Politics
+ 'election': ['election', 'vote', 'ballot', 'primary', 'nominee', 'candidate', 'poll'],
+ 'government': ['resign', 'cabinet', 'secretary', 'appointment', 'nomination', 'impeach'],
+ 'legislation': ['bill', 'act', 'congress', 'senate', 'house', 'passed', 'shutdown'],
+ // Economics
+ 'fed_rate': ['federal reserve', 'fed rate', 'interest rate', 'fomc', 'rate cut', 'rate hike', 'powell'],
+ 'inflation': ['cpi', 'inflation', 'consumer price', 'pce', 'core inflation'],
+ 'gdp': ['gdp', 'gross domestic', 'economic growth', 'recession', 'expansion'],
+ 'jobs': ['jobs report', 'unemployment', 'nonfarm', 'payroll', 'jobless claims'],
+ // Crypto
+ 'bitcoin': ['bitcoin', 'btc', 'cryptocurrency', 'crypto'],
+ 'ethereum': ['ethereum', 'eth', 'ether'],
+ // Space
+ 'spacex': ['spacex', 'falcon', 'starship', 'rocket launch', 'orbit'],
+ 'nasa': ['nasa', 'artemis', 'moon', 'mars mission'],
+};
+
+// Map ticker suffixes to searchable names for multi-outcome events
+const TICKER_ENTITY_MAP = {
+ // KXCABOUT - Cabinet members
+ 'RFK': ['rfk', 'kennedy', 'robert kennedy', 'rfk jr', 'health and human'],
+ 'KNOE': ['noem', 'kristi noem', 'homeland security'],
+ 'SDUF': ['duffy', 'sean duffy', 'transportation'],
+ 'BROL': ['rollins', 'brooke rollins', 'agriculture'],
+ 'JRAT': ['ratcliffe', 'john ratcliffe', 'cia director'],
+ 'SBES': ['bessent', 'scott bessent', 'treasury secretary'],
+ 'MRUB': ['rubio', 'marco rubio', 'state department', 'secretary of state'],
+ 'PHEG': ['hegseth', 'pete hegseth', 'defense secretary'],
+ 'TGAB': ['gabbard', 'tulsi gabbard', 'intelligence director'],
+ 'MWAL': ['waltz', 'mike waltz', 'national security'],
+ 'HLUT': ['lutnick', 'howard lutnick', 'commerce secretary'],
+ 'DBUR': ['burgum', 'doug burgum', 'interior secretary'],
+ 'CWRI': ['chris wright', 'energy secretary'],
+ 'LZEL': ['zeldin', 'lee zeldin', 'epa administrator'],
+ 'DCOL': ['collins', 'doug collins', 'veterans affairs'],
+ 'LMCM': ['mcmahon', 'linda mcmahon', 'education secretary'],
+ 'PBON': ['bondi', 'pam bondi', 'attorney general'],
+ 'RVOU': ['vought', 'russell vought', 'omb director'],
+ 'STUR': ['turner', 'scott turner', 'hud secretary'],
+ 'LCDR': ['cruz', 'linda cruz', 'sba administrator'],
+ 'MKRA': ['kratsios', 'michael kratsios'],
+ 'SWIL': ['wilson', 'sean wilson'],
+ // KXPRESPERSON - 2028 Presidential election
+ 'DTRU': ['trump', 'donald trump', 'president trump', 'former president trump'],
+ 'DTRUJR': ['trump jr', 'donald trump jr', 'don jr', 'trump junior'],
+ 'RDES': ['desantis', 'ron desantis', 'florida governor'],
+ 'JVAN': ['vance', 'jd vance', 'vice president vance', 'j.d. vance'],
+ 'GYOU': ['youngkin', 'glenn youngkin', 'virginia governor'],
+ // KXFEDCHAIRNOM - Fed Chair nominees
+ 'JS': ['dimon', 'jamie dimon'],
+ 'KW': ['warsh', 'kevin warsh'],
+ 'KH': ['hassett', 'kevin hassett'],
+ 'CWAL': ['waller', 'chris waller', 'christopher waller'],
+ 'MBOW': ['bowman', 'michelle bowman'],
+};
+
+function extractMarketEntity(market) {
+ // Extract ticker suffix for entity lookup first (most reliable)
+ const parts = market.ticker.split('-');
+ const suffix = parts[parts.length - 1];
+ if (TICKER_ENTITY_MAP[suffix]) return TICKER_ENTITY_MAP[suffix];
+ // Try subtitle only if it's a real description (not just the ticker repeated)
+ if (market.subtitle && market.subtitle !== market.ticker && !market.subtitle.startsWith('KX')) {
+ return market.subtitle.toLowerCase().split(/[\s\-]+/).filter(w => w.length > 2);
+ }
+ // Try the yes_sub_title field
+ if (market.yes_sub_title && market.yes_sub_title !== market.ticker) {
+ return market.yes_sub_title.toLowerCase().split(/[\s\-]+/).filter(w => w.length > 2);
+ }
+ return [];
+}
+
+function isMultiOutcomeEvent(ticker) {
+ // Multi-outcome events have a common prefix followed by person/answer suffix
+ // e.g., KXCABOUT-29JAN-RFK, KXCABOUT-29JAN-KNOE all share KXCABOUT-29JAN
+ const parts = ticker.split('-');
+ return parts.length >= 3; // Event prefix + date + answer
+}
+
+function getEventPrefix(ticker) {
+ const parts = ticker.split('-');
+ if (parts.length >= 3) return parts.slice(0, -1).join('-');
+ return ticker;
+}
+
+function mapNewsToMarkets(headline, activeMarkets) {
+ const headlineLower = headline.toLowerCase();
+ const matches = [];
+
+ // Step 1: Identify which categories the headline relates to
+ const relevantCategories = [];
+ for (const [category, keywords] of Object.entries(MARKET_CATEGORY_KEYWORDS)) {
+ for (const kw of keywords) {
+ if (headlineLower.includes(kw)) {
+ relevantCategories.push(category);
+ break;
+ }
+ }
+ }
+
+ // Step 2: Group markets by event to detect multi-outcome events
+ const eventGroups = {};
+ for (const market of activeMarkets) {
+ const prefix = getEventPrefix(market.ticker);
+ if (!eventGroups[prefix]) eventGroups[prefix] = [];
+ eventGroups[prefix].push(market);
+ }
+
+ // Step 3: Find matching Kalshi markets by title/subtitle keywords
+ for (const market of activeMarkets) {
+ const marketText = `${market.title} ${market.subtitle || ''} ${market.yes_sub_title || ''}`.toLowerCase();
+ let matchScore = 0;
+
+ // Direct keyword overlap
+ const headlineWords = headlineLower.split(/\s+/).filter(w => w.length > 3);
+ for (const word of headlineWords) {
+ if (marketText.includes(word)) matchScore += 1;
+ }
+
+ // Category match bonus
+ for (const cat of relevantCategories) {
+ const catKws = MARKET_CATEGORY_KEYWORDS[cat];
+ if (catKws.some(kw => marketText.includes(kw))) matchScore += 2;
+ }
+
+ // Entity matching (city names, person names, etc.)
+ const cities = ['phoenix', 'houston', 'miami', 'chicago', 'new york', 'los angeles', 'atlanta', 'dallas', 'denver', 'seattle', 'boston', 'detroit', 'minneapolis', 'philadelphia'];
+ for (const city of cities) {
+ if (headlineLower.includes(city) && marketText.includes(city)) matchScore += 5;
+ }
+
+ // Political figure matching
+ const figures = ['trump', 'biden', 'harris', 'desantis', 'newsom', 'vance', 'powell', 'yellen'];
+ for (const fig of figures) {
+ if (headlineLower.includes(fig) && marketText.includes(fig)) matchScore += 5;
+ }
+
+ // MULTI-OUTCOME EVENT HANDLING: For events with multiple answer markets,
+ // require headline to mention the specific answer entity, not just the general topic
+ const eventPrefix = getEventPrefix(market.ticker);
+ const siblings = eventGroups[eventPrefix] || [];
+ if (siblings.length > 1 && isMultiOutcomeEvent(market.ticker)) {
+ const entityTerms = extractMarketEntity(market);
+ const entityMatch = entityTerms.some(term => headlineLower.includes(term));
+ if (entityMatch) {
+ matchScore += 8; // Strong boost for specific entity match
+ } else {
+ // Headline mentions the topic but NOT this specific answer — reject entirely
+ // With 20+ siblings, even small scores cause massive clustering
+ matchScore = 0;
+ }
+ }
+
+ if (matchScore >= 3) {
+ matches.push({ market, matchScore });
+ }
+ }
+
+ // Sort by match score descending
+ matches.sort((a, b) => b.matchScore - a.matchScore);
+ return matches.slice(0, 5); // Top 5 matches
+}
+
+// ── Probability Shift Model (Bayesian Update) ──
+// adjustedProb = priorProb + (sentiment * weight * confidence)
+// With decay for older signals, source diversity bonus, and category-specific weights
+const CATEGORY_SENTIMENT_WEIGHTS = {
+ politics: 0.18, // Political events move markets fast
+ economics: 0.16, // Economic data is highly impactful
+ crypto: 0.22, // Crypto is volatile, sentiment-driven
+ weather: 0.10, // Weather has model data, less sentiment-dependent
+ geopolitics: 0.20, // Geopolitical events create large moves
+ sports: 0.12, // Sports have existing odds infrastructure
+ space: 0.14, // Launch outcomes are binary
+ general: 0.12, // Default
+};
+
+function calculateProbabilityShift(priorProb, sentimentSignals) {
+ if (!sentimentSignals.length) return { adjustedProb: priorProb, impact: 0, numArticles: 0, agreement: 0, sourceDiversity: 0 };
+
+ const RECENCY_DECAY = 0.85; // Faster decay — old news matters less
+ const AGREEMENT_BONUS = 1.5; // Stronger bonus for agreement
+ const DISAGREEMENT_PENALTY = 0.3; // Stronger penalty for mixed signals
+
+ let totalImpact = 0;
+ let totalWeight = 0;
+ const now = Date.now();
+
+ // Sort by recency
+ const sorted = [...sentimentSignals].sort((a, b) => (b.timestamp || 0) - (a.timestamp || 0));
+
+ // Calculate source diversity (unique sources boost signal)
+ const uniqueSources = new Set(sorted.map(s => s.source));
+ const sourceDiversity = Math.min(1, uniqueSources.size / 4); // 4+ unique sources = max diversity
+
+ for (const sig of sorted) {
+ const hoursAgo = Math.max(0, (now - (sig.timestamp || now)) / 3600000);
+ const recencyWeight = Math.pow(RECENCY_DECAY, hoursAgo);
+ // Use category-specific weight instead of flat 0.08
+ const catWeight = CATEGORY_SENTIMENT_WEIGHTS[sig.category] || CATEGORY_SENTIMENT_WEIGHTS.general;
+ // Magnitude amplifier: strong signals (|sentiment| > 0.3) get more weight
+ const magnitudeBoost = 1 + Math.min(0.5, (sig.magnitude || 0) * 0.8);
+ const impact = sig.sentiment * catWeight * sig.confidence * recencyWeight * magnitudeBoost;
+ totalImpact += impact;
+ totalWeight += recencyWeight * sig.confidence;
+ }
+
+ // Source diversity bonus: multiple independent sources confirming = stronger signal
+ totalImpact *= (1 + sourceDiversity * 0.4);
+
+ // Check agreement: if most signals agree on direction, boost; if mixed, penalize
+ const posSignals = sorted.filter(s => s.sentiment > 0).length;
+ const negSignals = sorted.filter(s => s.sentiment < 0).length;
+ const total = posSignals + negSignals;
+ if (total >= 2) {
+ const agreementRatio = Math.max(posSignals, negSignals) / total;
+ if (agreementRatio > 0.8) totalImpact *= AGREEMENT_BONUS; // Strong agreement
+ else if (agreementRatio > 0.6) totalImpact *= 1.1; // Mild agreement
+ else totalImpact *= DISAGREEMENT_PENALTY; // Mixed signals — dampen hard
+ }
+
+ // Diminishing returns: each additional article adds less new information
+ // 1 article = 100%, 4 = 50%, 9 = 33%, 16 = 25%
+ const articleDiminishing = Math.sqrt(sorted.length) / sorted.length;
+ totalImpact *= articleDiminishing;
+
+ // Prior-anchored capping: prevent unrealistic shifts on low-probability markets
+ // A 4% market shouldn't jump to 60% from sentiment alone; cap shift at 5x prior or 15%, whichever is higher
+ const maxShift = Math.max(0.15, priorProb * 5);
+ totalImpact = Math.sign(totalImpact) * Math.min(Math.abs(totalImpact), maxShift);
+
+ // Clamp adjusted probability to [0.01, 0.99]
+ const adjustedProb = Math.max(0.01, Math.min(0.99, priorProb + totalImpact));
+
+ return {
+ adjustedProb,
+ impact: totalImpact,
+ numArticles: sorted.length,
+ agreement: total > 0 ? Math.max(posSignals, negSignals) / total : 0,
+ sourceDiversity,
+ };
+}
+
+// ── Risk Engine ──
+const RISK_LIMITS = {
+ maxExposurePerMarket: 5000, // cents ($50)
+ maxExposurePerTheme: 15000, // cents ($150)
+ maxTotalExposure: 50000, // cents ($500)
+ maxContractsPerMarket: 25,
+ minEdgeThreshold: 0.03, // 3% edge minimum (lowered from 5% — entity-specific matching yields smaller edges)
+ maxDailyLoss: 5000, // cents ($50)
+ cooldownAfterLoss: 30, // minutes
+ timeDecayPenalty: 0.02, // Reduce edge by 2% per hour of signal age
+ minLiquidity: 100, // Minimum 24h volume
+};
+
+function riskCheck(signal, currentExposure = {}) {
+ const reasons = [];
+ let approved = true;
+
+ // Edge threshold
+ if (Math.abs(signal.expectedEdge) < RISK_LIMITS.minEdgeThreshold) {
+ approved = false;
+ reasons.push(`Edge ${(signal.expectedEdge * 100).toFixed(1)}% below ${(RISK_LIMITS.minEdgeThreshold * 100)}% threshold`);
+ }
+
+ // Market exposure
+ const marketExposure = currentExposure[signal.marketId] || 0;
+ if (marketExposure >= RISK_LIMITS.maxExposurePerMarket) {
+ approved = false;
+ reasons.push(`Market exposure $${(marketExposure / 100).toFixed(2)} at limit`);
+ }
+
+ // Liquidity check
+ if ((signal.volume24h || 0) < RISK_LIMITS.minLiquidity) {
+ approved = false;
+ reasons.push(`Low liquidity: ${signal.volume24h || 0} < ${RISK_LIMITS.minLiquidity} volume`);
+ }
+
+ // Time decay — use absolute edge values so BUY_NO signals aren't unfairly penalized
+ const signalAgeHours = (Date.now() - (signal.timestamp || Date.now())) / 3600000;
+ const absEdge = Math.abs(signal.expectedEdge);
+ const decayedAbsEdge = absEdge - (RISK_LIMITS.timeDecayPenalty * signalAgeHours);
+ if (decayedAbsEdge < RISK_LIMITS.minEdgeThreshold) {
+ approved = false;
+ reasons.push(`Edge decayed from ${(absEdge * 100).toFixed(1)}% to ${(decayedAbsEdge * 100).toFixed(1)}%`);
+ }
+
+ // Size recommendation based on edge and confidence
+ let sizeRecommendation = 1;
+ if (approved) {
+ const edgeFactor = Math.min(3, Math.abs(signal.expectedEdge) / RISK_LIMITS.minEdgeThreshold);
+ const confFactor = signal.confidence || 0.5;
+ sizeRecommendation = Math.max(1, Math.min(RISK_LIMITS.maxContractsPerMarket, Math.floor(edgeFactor * confFactor * 10)));
+ }
+
+ return { approved, reasons, sizeRecommendation, decayedEdge: decayedAbsEdge };
+}
+
+// ── Fast Signal Pipeline (runs every 5 minutes) ──
+async function signalPipeline(activeMarkets) {
+ const pipelineStart = Date.now();
+ let signalsGenerated = 0;
+
+ try {
+ // Step 1: Fetch recent news/sentiment from last 30 minutes
+ const { rows: recentArticles } = await kenQ(`
+ SELECT id, source, keyword, post_title as headline, post_url as url, sentiment_score, captured_at
+ FROM ken_sentiment
+ WHERE captured_at > NOW() - INTERVAL '30 minutes'
+ ORDER BY captured_at DESC
+ LIMIT 500
+ `);
+
+ if (recentArticles.length === 0) {
+ console.log('[Ken] Signal Pipeline: no new articles in last 30 min');
+ return 0;
+ }
+
+ // Step 2: Score each article with event-specific sentiment
+ const eventScores = [];
+ for (const article of recentArticles) {
+ const evtScore = scoreEventSentiment(article.headline);
+ if (evtScore.magnitude > 0.1) { // Only process articles with detectable event signal
+ // Step 3: Map to relevant markets
+ const mappedMarkets = mapNewsToMarkets(article.headline, activeMarkets);
+
+ for (const { market, matchScore } of mappedMarkets) {
+ eventScores.push({
+ articleId: String(article.id),
+ headline: article.headline,
+ source: article.source,
+ marketTicker: market.ticker,
+ marketTitle: market.title,
+ sentiment: evtScore.sentiment,
+ confidence: evtScore.confidence * (matchScore / 10), // Scale confidence by match quality
+ magnitude: evtScore.magnitude,
+ category: evtScore.category,
+ direction: evtScore.direction,
+ timestamp: new Date(article.captured_at).getTime(),
+ });
+
+ // Store event-specific sentiment
+ await kenQ(`
+ INSERT INTO ken_event_sentiment (article_id, event_tag, market_ticker, sentiment, confidence, magnitude, headline, source)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
+ `, [String(article.id), evtScore.direction, market.ticker, evtScore.sentiment,
+ evtScore.confidence, evtScore.magnitude, article.headline?.substring(0, 500), article.source]);
+ }
+ }
+ }
+
+ console.log(`[Ken] Signal Pipeline: ${eventScores.length} event-specific scores from ${recentArticles.length} articles`);
+
+ // Step 4: Group by market and calculate probability shifts
+ const marketSignals = {};
+ for (const score of eventScores) {
+ if (!marketSignals[score.marketTicker]) marketSignals[score.marketTicker] = [];
+ marketSignals[score.marketTicker].push(score);
+ }
+
+ // Step 5: For each market with signals, compute probability shift
+ for (const [ticker, signals] of Object.entries(marketSignals)) {
+ const market = activeMarkets.find(m => m.ticker === ticker);
+ if (!market) continue;
+
+ const priorProb = (market.yes_bid + market.yes_ask) / 200; // Convert cents to probability
+ const { adjustedProb, impact, numArticles, agreement, sourceDiversity } = calculateProbabilityShift(priorProb, signals);
+ const marketProb = market.last_price / 100;
+ const edge = adjustedProb - marketProb;
+
+ // Store probability shift
+ await kenQ(`
+ INSERT INTO ken_probability_shifts (market_id, prior_probability, sentiment_impact, adjusted_probability, market_probability, edge, num_articles)
+ VALUES ($1, $2, $3, $4, $5, $6, $7)
+ `, [ticker, priorProb, impact, adjustedProb, marketProb, edge, numArticles]);
+
+ // Step 6: Generate signal if edge exceeds threshold
+ if (Math.abs(edge) >= RISK_LIMITS.minEdgeThreshold) {
+ const direction = edge > 0 ? 'BUY_YES' : 'BUY_NO';
+
+ // Step 6b: Monte Carlo simulation for probability validation (CPU-intensive)
+ const momentum = cachedMomentumMap?.[ticker] || { delta_2h: 0, delta_6h: 0 };
+ const mcResult = monteCarloSimulation({
+ priorProb,
+ sentimentImpact: impact,
+ momentum2h: momentum.delta_2h,
+ momentum6h: momentum.delta_6h,
+ volume24h: market.volume_24h || 0,
+ spread: (market.yes_ask || 0) - (market.yes_bid || 0),
+ articleCount: numArticles,
+ agreement: agreement || 0.5,
+ }, 15000); // 15k iterations for higher accuracy
+
+ // Blend Monte Carlo with statistical model
+ const mcEdge = mcResult.edgeConsistent ? (edge * 0.65 + mcResult.medianEdge * 0.35) : edge * 0.8;
+
+ // Dedup: skip if we already generated a signal for this market+direction in last 30 min
+ // Compare MC-blended edge (mcEdge) against stored MC-blended edge to avoid false positives
+ const recentDup = await kenQ(`
+ SELECT id, expected_edge, confidence FROM ken_strategy_signals
+ WHERE market_id = $1 AND direction = $2 AND created_at > NOW() - INTERVAL '30 minutes'
+ ORDER BY created_at DESC LIMIT 1
+ `, [ticker, direction]);
+ if (recentDup.rows.length > 0) {
+ const prevEdge = parseFloat(recentDup.rows[0].expected_edge);
+ if (Math.abs(Math.abs(mcEdge) - Math.abs(prevEdge)) < 0.02) continue;
+ }
+
+ // Improved confidence using MC validation
+ const edgeScore = Math.min(1, Math.pow(Math.abs(mcEdge) / 0.15, 1.5));
+ const volumeScore = Math.min(1, numArticles / 8);
+ const agreementScore = Math.pow(agreement || 0.5, 0.7);
+ const diversityScore = sourceDiversity || 0;
+ const mcConfBoost = mcResult.confidence > 0.6 ? 0.08 : mcResult.confidence > 0.4 ? 0.04 : 0;
+ const consistencyBoost = mcResult.edgeConsistent ? 0.05 : -0.05;
+ const confidence = Math.min(0.95, Math.max(0.15,
+ edgeScore * 0.30 +
+ agreementScore * 0.18 +
+ volumeScore * 0.18 +
+ diversityScore * 0.12 +
+ mcConfBoost +
+ consistencyBoost +
+ (numArticles >= 5 ? 0.10 : numArticles >= 3 ? 0.05 : 0)
+ ));
+
+ let signal = {
+ marketId: ticker,
+ direction,
+ expectedEdge: mcEdge,
+ confidence,
+ volume24h: market.volume_24h || 0,
+ timestamp: Date.now(),
+ agreement,
+ mcSimulation: {
+ meanEdge: mcResult.meanEdge,
+ stdDev: mcResult.stdDev,
+ percentiles: mcResult.percentiles,
+ consistent: mcResult.edgeConsistent,
+ },
+ };
+
+ // Step 6c: AI Enhancement for high-edge signals (Gemini)
+ if (Math.abs(mcEdge) >= 0.08 && confidence >= 0.4 && numArticles >= 3) {
+ signal = await aiEnhanceSignal(signal, signals, market);
+ }
+
+ // Step 7: Risk check
+ const risk = riskCheck(signal);
+
+ const mcInfo = `MC: μ=${(mcResult.meanEdge * 100).toFixed(1)}%±${(mcResult.stdDev * 100).toFixed(1)}%, p5-p95=[${(mcResult.percentiles.p5 * 100).toFixed(1)}%,${(mcResult.percentiles.p95 * 100).toFixed(1)}%]`;
+ const aiInfo = signal.aiEnhanced ? ` | AI: ${signal.aiReasoning || 'enhanced'}` : '';
+ const reasoning = `${direction} on "${market.title}" — edge ${(mcEdge * 100).toFixed(1)}% from ${numArticles} articles (${signals[0]?.category}/${signals[0]?.direction}). Agreement: ${((agreement || 0) * 100).toFixed(0)}%. ${mcInfo}${aiInfo}. ${risk.approved ? 'RISK APPROVED' : `RISK BLOCKED: ${risk.reasons.join('; ')}`}`;
+
+ await kenQ(`
+ INSERT INTO ken_strategy_signals (market_id, direction, expected_edge, size_recommendation, confidence, reasoning, sources, risk_approved)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
+ `, [ticker, direction, mcEdge, risk.sizeRecommendation, confidence, reasoning,
+ JSON.stringify(signals.slice(0, 5).map(s => ({ headline: s.headline?.substring(0, 200), source: s.source, sentiment: s.sentiment }))),
+ risk.approved]);
+
+ signalsGenerated++;
+
+ if (risk.approved && confidence > 0.7) {
+ console.log(`[Ken] SIGNAL: ${direction} ${ticker} — edge ${(mcEdge * 100).toFixed(1)}%, conf ${(confidence * 100).toFixed(0)}%, MC:${mcResult.edgeConsistent ? 'consistent' : 'mixed'}${signal.aiEnhanced ? ', AI-enhanced' : ''}, size ${risk.sizeRecommendation}`);
+ }
+
+ // Auto-trade across all 50 paper portfolios
+ if (risk.approved) {
+ autoPortfolioTrade({
+ ...signal, marketId: ticker, market_title: market.title,
+ num_articles: numArticles, signal_type: signals[0]?.category,
+ reasoning, expected_edge: mcEdge,
+ }).catch(e => console.error('[Ken/Portfolio] Error:', e.message));
+ }
+ }
+ }
+
+ const duration = Date.now() - pipelineStart;
+ console.log(`[Ken] Signal Pipeline: ${signalsGenerated} signals from ${Object.keys(marketSignals).length} markets | ${duration}ms`);
+ return signalsGenerated;
+
+ } catch (e) {
+ console.error('[Ken] Signal Pipeline error:', e.message);
+ return 0;
+ }
+}
+
+// ── Auto-mapping: Build market mappings from active Kalshi markets ──
+async function updateMarketMappings(activeMarkets) {
+ try {
+ let mapped = 0;
+ for (const m of activeMarkets) {
+ const titleLower = `${m.title} ${m.subtitle || ''}`.toLowerCase();
+ let category = 'other';
+ const keywords = [];
+
+ for (const [cat, kws] of Object.entries(MARKET_CATEGORY_KEYWORDS)) {
+ for (const kw of kws) {
+ if (titleLower.includes(kw)) {
+ category = cat;
+ keywords.push(kw);
+ }
+ }
+ }
+
+ if (keywords.length > 0) {
+ await kenQ(`
+ INSERT INTO ken_market_mappings (market_id, keywords, category, contract_type)
+ VALUES ($1, $2, $3, 'binary')
+ ON CONFLICT (id) DO NOTHING
+ `, [m.ticker, keywords, category]);
+ mapped++;
+ }
+ }
+ return mapped;
+ } catch (e) {
+ console.log(`[Ken] Market mapping update failed: ${e.message}`);
+ return 0;
+ }
+}
+
+// ══════════════════════════════════════════════
+// POLYMARKET CROSS-REFERENCE (fuzzy matching)
+// ══════════════════════════════════════════════
+const STOP_WORDS = new Set(['will', 'the', 'this', 'that', 'what', 'when', 'where', 'which', 'with', 'from', 'have', 'been', 'before', 'after', 'than', 'more', 'less', 'next', 'last', 'does', 'would', 'could', 'should', 'about', 'into', 'over', 'under', 'between', 'through', 'during', 'each', 'every', 'other', 'some', 'most', 'many', 'much', 'also', 'just', 'only', 'very', 'still', 'even', 'back', 'first', 'year', 'years']);
+
+function extractKeywords(text) {
+ return (text || '').toLowerCase()
+ .replace(/[^a-z0-9\s]/g, ' ')
+ .split(/\s+/)
+ .filter(w => w.length > 2 && !STOP_WORDS.has(w));
+}
+
+function fuzzyMatchScore(textA, textB) {
+ const wordsA = extractKeywords(textA);
+ const wordsB = new Set(extractKeywords(textB));
+ if (wordsA.length === 0 || wordsB.size === 0) return 0;
+ let matches = 0;
+ for (const w of wordsA) {
+ if (wordsB.has(w)) matches++;
+ // Partial match for longer words (e.g. "greenland" matches "greenlands")
+ else if (w.length > 5) {
+ for (const wb of wordsB) {
+ if (wb.length > 5 && (wb.startsWith(w.slice(0, 5)) || w.startsWith(wb.slice(0, 5)))) { matches += 0.5; break; }
+ }
+ }
+ }
+ return matches / Math.min(wordsA.length, wordsB.size);
+}
+
+async function polymarketCrossRef(kalshiMarkets) {
+ const crossRefs = [];
+ try {
+ const polyEvents = await scrapePolymarketEvents(100);
+ if (polyEvents.length === 0) return [];
+ console.log(`[Ken] Polymarket: ${polyEvents.length} markets from top events`);
+
+ // Build index of Kalshi market text for faster matching
+ const kalshiIndex = kalshiMarkets.map(km => ({
+ ...km,
+ searchText: ((km.title || '') + ' ' + (km.subtitle || '')).toLowerCase(),
+ }));
+
+ for (const pm of polyEvents) {
+ const pmText = pm.event_title + ' ' + pm.question;
+ let bestMatch = null;
+ let bestScore = 0;
+
+ for (const km of kalshiIndex) {
+ const score = fuzzyMatchScore(pmText, km.searchText);
+ if (score > bestScore) {
+ bestScore = score;
+ bestMatch = km;
+ }
+ }
+
+ // Require at least 30% keyword overlap for a match
+ if (bestScore >= 0.3 && bestMatch && bestMatch.yes_ask > 0) {
+ const priceDiff = pm.price - bestMatch.yes_ask;
+ if (Math.abs(priceDiff) >= 3) { // 3¢+ divergence
+ crossRefs.push({
+ kalshi_ticker: bestMatch.ticker,
+ event_ticker: bestMatch.event_ticker,
+ kalshi_title: bestMatch.title,
+ kalshi_subtitle: bestMatch.subtitle,
+ kalshi_price: bestMatch.yes_ask,
+ poly_question: pm.question,
+ poly_event: pm.event_title,
+ poly_price: pm.price,
+ poly_volume: pm.volume,
+ poly_slug: pm.slug,
+ price_diff: priceDiff,
+ match_score: Math.round(bestScore * 100),
+ arb_side: priceDiff > 0 ? 'BUY on Kalshi (cheaper)' : 'SHORT on Kalshi (overpriced)',
+ });
+ }
+ }
+ }
+ // Dedupe: keep best match per Kalshi ticker
+ const seen = new Map();
+ for (const ref of crossRefs) {
+ const key = ref.kalshi_ticker;
+ if (!seen.has(key) || Math.abs(ref.price_diff) > Math.abs(seen.get(key).price_diff)) {
+ seen.set(key, ref);
+ }
+ }
+ return [...seen.values()].sort((a, b) => Math.abs(b.price_diff) - Math.abs(a.price_diff));
+ } catch (e) {
+ console.log(`[Ken] Polymarket cross-ref error: ${e.message}`);
+ return [];
+ }
+}
+
+// ══════════════════════════════════════════════
+// LNG / ENERGY CROSS-MARKET ARBITRAGE
+// Compares energy-related predictions across Kalshi, Polymarket, and Manifold
+// ══════════════════════════════════════════════
+const ENERGY_SEARCH_TERMS = [
+ 'oil price', 'crude oil', 'natural gas', 'LNG', 'OPEC',
+ 'energy price', 'gas price', 'heating oil', 'petroleum',
+ 'electricity price', 'EIA', 'oil production', 'pipeline',
+ 'renewable energy', 'solar', 'wind energy', 'nuclear',
+ 'carbon price', 'emissions', 'electric vehicle', 'EV',
+ 'barrel', 'WTI', 'Brent', 'refinery',
+];
+
+async function energyArbitrageScan(kalshiMarkets) {
+ const arbs = [];
+ try {
+ // 1. Get energy markets from Manifold
+ const manifoldEnergy = await scrapeManifold(ENERGY_SEARCH_TERMS.slice(0, 8));
+ console.log(`[Ken/Energy] Manifold: ${manifoldEnergy.length} energy-related markets`);
+
+ // 2. Get energy events from Polymarket
+ let polyEnergy = [];
+ try {
+ const polyAll = await scrapePolymarketEvents(200);
+ polyEnergy = polyAll.filter(p => {
+ const t = (p.event_title + ' ' + p.question).toLowerCase();
+ return /oil|gas|lng|opec|energy|crude|barrel|petroleum|electric|solar|wind|nuclear|carbon|emission|ev market|renewable/i.test(t);
+ });
+ console.log(`[Ken/Energy] Polymarket: ${polyEnergy.length} energy-related markets`);
+ } catch {}
+
+ // 3. Filter Kalshi markets for energy/commodities
+ const kalshiEnergy = kalshiMarkets.filter(m => {
+ const t = ((m.title || '') + ' ' + (m.subtitle || '') + ' ' + (m.category || '')).toLowerCase();
+ return /oil|gas|lng|opec|energy|crude|barrel|petroleum|electric|solar|wind|nuclear|carbon|emission|ev |renewable|consumption|climate/i.test(t);
+ });
+ console.log(`[Ken/Energy] Kalshi: ${kalshiEnergy.length} energy-related markets`);
+
+ // 4. Cross-reference Manifold vs Kalshi
+ for (const mf of manifoldEnergy) {
+ for (const km of kalshiEnergy) {
+ const score = fuzzyMatchScore(mf.title, (km.title + ' ' + (km.subtitle || '')).toLowerCase());
+ if (score >= 0.25) {
+ const priceDiff = mf.probability - km.yes_ask;
+ if (Math.abs(priceDiff) >= 3) {
+ arbs.push({
+ type: 'manifold_kalshi',
+ kalshi_ticker: km.ticker,
+ event_ticker: km.event_ticker,
+ kalshi_title: km.title,
+ kalshi_price: km.yes_ask,
+ other_title: mf.title,
+ other_price: mf.probability,
+ other_source: 'Manifold',
+ other_url: mf.url,
+ other_volume: mf.volume,
+ price_diff: priceDiff,
+ match_score: Math.round(score * 100),
+ category: 'energy',
+ });
+ }
+ }
+ }
+ }
+
+ // 5. Cross-reference Polymarket vs Kalshi (energy-specific)
+ for (const pm of polyEnergy) {
+ for (const km of kalshiEnergy) {
+ const score = fuzzyMatchScore(pm.event_title + ' ' + pm.question, (km.title + ' ' + (km.subtitle || '')).toLowerCase());
+ if (score >= 0.25) {
+ const priceDiff = pm.price - km.yes_ask;
+ if (Math.abs(priceDiff) >= 3) {
+ arbs.push({
+ type: 'poly_kalshi_energy',
+ kalshi_ticker: km.ticker,
+ event_ticker: km.event_ticker,
+ kalshi_title: km.title,
+ kalshi_price: km.yes_ask,
+ other_title: pm.question,
+ other_price: pm.price,
+ other_source: 'Polymarket',
+ other_url: `https://polymarket.com/event/${pm.slug}`,
+ other_volume: pm.volume,
+ price_diff: priceDiff,
+ match_score: Math.round(score * 100),
+ category: 'energy',
+ });
+ }
+ }
+ }
+ }
+
+ // 6. Cross-reference Manifold vs Polymarket (energy only, no Kalshi needed)
+ for (const mf of manifoldEnergy) {
+ for (const pm of polyEnergy) {
+ const score = fuzzyMatchScore(mf.title, pm.event_title + ' ' + pm.question);
+ if (score >= 0.3) {
+ const priceDiff = mf.probability - pm.price;
+ if (Math.abs(priceDiff) >= 5) {
+ arbs.push({
+ type: 'manifold_poly_energy',
+ kalshi_ticker: null,
+ event_ticker: null,
+ kalshi_title: `${mf.title} (cross-platform)`,
+ kalshi_price: mf.probability,
+ other_title: pm.question,
+ other_price: pm.price,
+ other_source: 'Manifold↔Polymarket',
+ other_url: mf.url,
+ other_volume: Math.max(mf.volume, pm.volume),
+ price_diff: priceDiff,
+ match_score: Math.round(score * 100),
+ category: 'energy',
+ });
+ }
+ }
+ }
+ }
+
+ // Dedupe by best price diff per Kalshi ticker
+ const seen = new Map();
+ for (const arb of arbs) {
+ const key = arb.kalshi_ticker || arb.other_title;
+ if (!seen.has(key) || Math.abs(arb.price_diff) > Math.abs(seen.get(key).price_diff)) {
+ seen.set(key, arb);
+ }
+ }
+ const result = [...seen.values()].sort((a, b) => Math.abs(b.price_diff) - Math.abs(a.price_diff));
+ if (result.length > 0) {
+ console.log(`[Ken/Energy] Found ${result.length} energy arbitrage opportunities (top: ${result[0].kalshi_title} ${result[0].price_diff > 0 ? '+' : ''}${result[0].price_diff}¢)`);
+ }
+ return result;
+ } catch (e) {
+ console.log(`[Ken/Energy] Arbitrage scan error: ${e.message}`);
+ return [];
+ }
+}
+
+// ══════════════════════════════════════════════
+// AUTO-TRADER ($20 budget, risk-managed)
+// ══════════════════════════════════════════════
+const TRADE_CONFIG = {
+ enabled: true, // Master kill switch
+ budget_cents: 2000, // $20 total budget
+ max_position_cents: 200, // $2 max per trade
+ max_open_positions: 5, // Max concurrent positions
+ daily_loss_limit_cents: 400, // $4 daily stop-loss
+ min_confidence: 80, // Only trade 80%+ confidence signals
+ min_sources: 2, // Must have 2+ corroborating sources
+ take_profit_pct: 80, // Take profit at 80% of max (e.g. sell YES at 90+ if bought at 50)
+ stop_loss_pct: 50, // Stop loss: exit if position loses 50% of cost
+ fee_rate: 0.07, // Kalshi ~7% fee on winnings
+ cooldown_minutes: 30, // Don't re-trade same ticker within 30 min
+};
+
+// ── TRADE_CONFIG Persistence ──
+async function initConfigTable() {
+ try {
+ await kenQ(`
+ CREATE TABLE IF NOT EXISTS ken_config (
+ key TEXT PRIMARY KEY,
+ value JSONB NOT NULL,
+ updated_at TIMESTAMPTZ DEFAULT NOW()
+ )
+ `);
+ } catch (e) {
+ console.log(`[Ken] Config table init error: ${e.message}`);
+ }
+}
+
+async function loadTradeConfig() {
+ try {
+ await initConfigTable();
+ const { rows } = await kenQ("SELECT value FROM ken_config WHERE key = 'trade_config'");
+ if (rows.length > 0) {
+ const saved = rows[0].value;
+ // Merge saved values into TRADE_CONFIG (preserves new keys added in code)
+ for (const [k, v] of Object.entries(saved)) {
+ if (k in TRADE_CONFIG) TRADE_CONFIG[k] = v;
+ }
+ console.log(`[Ken] Loaded TRADE_CONFIG from DB: budget=$${(TRADE_CONFIG.budget_cents/100).toFixed(0)}, conf=${TRADE_CONFIG.min_confidence}%, enabled=${TRADE_CONFIG.enabled}`);
+ }
+ } catch (e) {
+ console.log(`[Ken] Failed to load trade config: ${e.message}`);
+ }
+}
+
+async function saveTradeConfig() {
+ try {
+ await kenQ(`
+ INSERT INTO ken_config (key, value, updated_at) VALUES ('trade_config', $1, NOW())
+ ON CONFLICT (key) DO UPDATE SET value = $1, updated_at = NOW()
+ `, [JSON.stringify(TRADE_CONFIG)]);
+ } catch (e) {
+ console.log(`[Ken] Failed to save trade config: ${e.message}`);
+ }
+}
+
+async function getTraderState() {
+ try {
+ const openTrades = await kenQ('SELECT * FROM ken_trades WHERE status = $1 ORDER BY created_at DESC', ['open']);
+ const today = new Date().toISOString().split('T')[0];
+ const todayPnL = await kenQ("SELECT COALESCE(SUM(pnl_cents), 0) as total FROM ken_trades WHERE closed_at::date = $1::date", [today]);
+ const totalInvested = (openTrades.rows || []).reduce((sum, t) => sum + (t.cost_cents || 0), 0);
+ const dailyLoss = Math.abs(Math.min(0, todayPnL.rows[0]?.total || 0));
+ return {
+ openPositions: openTrades.rows || [],
+ openCount: (openTrades.rows || []).length,
+ totalInvested,
+ dailyLoss,
+ available: TRADE_CONFIG.budget_cents - totalInvested,
+ };
+ } catch (e) {
+ console.log(`[Ken] Trader state error: ${e.message}`);
+ return { openPositions: [], openCount: 0, totalInvested: 0, dailyLoss: 0, available: 0 };
+ }
+}
+
+async function autoTrader(signals) {
+ if (!TRADE_CONFIG.enabled) return;
+
+ try {
+ // Check if API keys are configured
+ const cfgRow = await q('SELECT config FROM risk_state ORDER BY updated_at DESC LIMIT 1');
+ const cfg = cfgRow.rows[0]?.config || {};
+ if (!cfg.kalshi_api_key || !cfg.kalshi_private_key) {
+ return; // Silent - no keys configured yet
+ }
+
+ const state = await getTraderState();
+
+ // Daily loss limit check
+ if (state.dailyLoss >= TRADE_CONFIG.daily_loss_limit_cents) {
+ console.log(`[Ken] TRADER: Daily loss limit hit ($${(state.dailyLoss/100).toFixed(2)}). No new trades today.`);
+ return;
+ }
+
+ // ── 1. CHECK EXISTING POSITIONS FOR EXIT ──
+ for (const trade of state.openPositions) {
+ try {
+ // Get current market price
+ const mktData = await kalshiPublicFetch('GET', `/markets/${encodeURIComponent(trade.ticker)}`);
+ const mkt = mktData.market || mktData;
+ const currentPrice = trade.side === 'yes' ? (mkt.yes_ask || mkt.last_price || 0) : (mkt.no_ask || mkt.last_price || 0);
+
+ // Market resolved?
+ if (mkt.status === 'settled' || mkt.result) {
+ const won = (mkt.result === trade.side);
+ const pnl = won ? (100 - trade.price_cents) * trade.count : -(trade.cost_cents);
+ const feeAdjusted = won ? Math.round(pnl * (1 - TRADE_CONFIG.fee_rate)) : pnl;
+ await kenQ('UPDATE ken_trades SET status=$1, exit_price=$2, pnl_cents=$3, closed_at=NOW() WHERE id=$4',
+ ['resolved', won ? 100 : 0, feeAdjusted, trade.id]);
+ const emoji = feeAdjusted > 0 ? ':moneybag:' : ':chart_with_downwards_trend:';
+ await sendSlack(`${emoji} *Ken Trade Resolved*\n*${trade.title}* (${trade.ticker})\nSide: ${trade.side.toUpperCase()} @ ${trade.price_cents}¢ → Result: ${mkt.result?.toUpperCase()}\nP&L: *${feeAdjusted > 0 ? '+' : ''}${(feeAdjusted/100).toFixed(2)}* (after fees)`);
+ continue;
+ }
+
+ // Take profit check
+ if (currentPrice >= TRADE_CONFIG.take_profit_pct) {
+ try {
+ const sellOrder = await kalshiFetch('POST', '/portfolio/orders', {
+ ticker: trade.ticker, side: trade.side, action: 'sell', type: 'market', count: trade.count,
+ });
+ const sellPrice = currentPrice;
+ const pnl = Math.round((sellPrice - trade.price_cents) * trade.count * (1 - TRADE_CONFIG.fee_rate));
+ await kenQ('UPDATE ken_trades SET status=$1, exit_price=$2, pnl_cents=$3, closed_at=NOW(), order_id=$4 WHERE id=$5',
+ ['profit', sellPrice, pnl, sellOrder.order?.order_id || trade.order_id, trade.id]);
+ await sendSlack(`:rocket: *Ken Take Profit!*\n*${trade.title}* (${trade.ticker})\nBought ${trade.side.toUpperCase()} @ ${trade.price_cents}¢ → Sold @ ${sellPrice}¢\nP&L: *+$${(pnl/100).toFixed(2)}* :moneybag:`);
+ } catch (e) {
+ console.log(`[Ken] TRADER: Take profit failed for ${trade.ticker}: ${e.message}`);
+ }
+ continue;
+ }
+
+ // Stop loss check
+ const unrealizedLoss = (trade.price_cents - currentPrice) * trade.count;
+ if (unrealizedLoss > trade.cost_cents * (TRADE_CONFIG.stop_loss_pct / 100)) {
+ try {
+ const sellOrder = await kalshiFetch('POST', '/portfolio/orders', {
+ ticker: trade.ticker, side: trade.side, action: 'sell', type: 'market', count: trade.count,
+ });
+ const sellPrice = currentPrice;
+ const pnl = (sellPrice - trade.price_cents) * trade.count;
+ await kenQ('UPDATE ken_trades SET status=$1, exit_price=$2, pnl_cents=$3, closed_at=NOW() WHERE id=$4',
+ ['stopped', sellPrice, pnl, trade.id]);
+ await sendSlack(`:stop_sign: *Ken Stop Loss*\n*${trade.title}* (${trade.ticker})\nBought ${trade.side.toUpperCase()} @ ${trade.price_cents}¢ → Stopped @ ${sellPrice}¢\nP&L: *-$${(Math.abs(pnl)/100).toFixed(2)}*`);
+ } catch (e) {
+ console.log(`[Ken] TRADER: Stop loss failed for ${trade.ticker}: ${e.message}`);
+ }
+ continue;
+ }
+ } catch (e) {
+ console.log(`[Ken] TRADER: Position check failed for ${trade.ticker}: ${e.message}`);
+ }
+ }
+
+ // ── 2. LOOK FOR NEW TRADES ──
+ // Refresh state after exits
+ const freshState = await getTraderState();
+ if (freshState.openCount >= TRADE_CONFIG.max_open_positions) {
+ console.log(`[Ken] TRADER: Max positions (${freshState.openCount}/${TRADE_CONFIG.max_open_positions}). Waiting for exits.`);
+ return;
+ }
+
+ // Filter signals: high confidence, multiple sources, tradeable price
+ const tradeable = signals.filter(s =>
+ s.confidence >= TRADE_CONFIG.min_confidence &&
+ (s.sources?.length || 0) >= TRADE_CONFIG.min_sources &&
+ s.entry_price > 5 && s.entry_price < 90 && // Don't trade near extremes
+ s.ticker
+ ).sort((a, b) => b.confidence - a.confidence);
+
+ // Check cooldown: don't re-trade same ticker
+ const recentTickers = new Set();
+ try {
+ const recent = await kenQ("SELECT ticker FROM ken_trades WHERE created_at > NOW() - INTERVAL '" + TRADE_CONFIG.cooldown_minutes + " minutes'");
+ for (const r of (recent.rows || [])) recentTickers.add(r.ticker);
+ } catch {}
+ // Also skip tickers we already have open positions on
+ for (const t of freshState.openPositions) recentTickers.add(t.ticker);
+
+ let tradesPlaced = 0;
+ for (const sig of tradeable) {
+ if (freshState.openCount + tradesPlaced >= TRADE_CONFIG.max_open_positions) break;
+ if (recentTickers.has(sig.ticker)) continue;
+
+ // Calculate position size: max $2, but respect available budget
+ const priceCents = sig.entry_price;
+ const costPerContract = priceCents; // Cost = price in cents for YES; (100 - price) for NO
+ const maxContracts = Math.floor(Math.min(TRADE_CONFIG.max_position_cents, freshState.available) / costPerContract);
+ if (maxContracts < 1) continue;
+ const count = Math.min(maxContracts, 3); // Max 3 contracts per trade
+ const totalCost = count * costPerContract;
+
+ try {
+ const side = sig.side === 'NO' ? 'no' : 'yes';
+ const order = await kalshiFetch('POST', '/portfolio/orders', {
+ ticker: sig.ticker,
+ side: side,
+ action: 'buy',
+ type: 'limit',
+ count: count,
+ yes_price: side === 'yes' ? priceCents : undefined,
+ no_price: side === 'no' ? (100 - priceCents) : undefined,
+ time_in_force: 'gtc',
+ });
+
+ const orderId = order.order?.order_id || `ken_${Date.now()}`;
+ await kenQ(`INSERT INTO ken_trades (ticker, event_ticker, title, side, action, price_cents, count, cost_cents, order_id, signal_type, confidence, reasoning, status)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, 'open')`,
+ [sig.ticker, sig.event_ticker || '', sig.market || '', side, 'buy', priceCents, count, totalCost,
+ orderId, sig.signal_type || '', sig.confidence, sig.reason || '']);
+
+ recentTickers.add(sig.ticker);
+ tradesPlaced++;
+ freshState.available -= totalCost;
+
+ const kLink = kalshiLink(sig.ticker, sig.event_ticker);
+ await sendSlack(`:chart_with_upwards_trend: *Ken Auto-Trade Placed!*\n${confBadge(sig.confidence)} *${sig.market}*\n${side.toUpperCase()} x${count} @ ${priceCents}¢ = $${(totalCost/100).toFixed(2)}\nSignal: ${sig.signal_type} | ${sig.reason}\n${kLink}\n_Budget remaining: $${(freshState.available/100).toFixed(2)}_`);
+ console.log(`[Ken] TRADER: ${side.toUpperCase()} x${count} ${sig.ticker} @ ${priceCents}¢ ($${(totalCost/100).toFixed(2)}) — ${sig.signal_type} ${sig.confidence}%`);
+
+ } catch (e) {
+ console.log(`[Ken] TRADER: Order failed for ${sig.ticker}: ${e.message}`);
+ }
+ }
+
+ if (tradesPlaced > 0) {
+ console.log(`[Ken] TRADER: ${tradesPlaced} new trades placed. Open: ${freshState.openCount + tradesPlaced}/${TRADE_CONFIG.max_open_positions}`);
+ }
+ } catch (e) {
+ console.log(`[Ken] TRADER ERROR: ${e.message}`);
+ }
+}
+
+// ══════════════════════════════════════════════
+// MAIN AUTONOMOUS SCAN (every 15 min, 24/7)
+// ══════════════════════════════════════════════
+async function autonomousScan() {
+ const scanStart = Date.now();
+ console.log('[Ken] ═══ AUTONOMOUS SCAN STARTING ═══');
+ try {
+ // 1. Refresh weather data
+ const cities = ['New York', 'Chicago', 'Miami', 'Denver', 'Los Angeles', 'Seattle', 'Houston', 'Phoenix', 'Minneapolis', 'Boston'];
+ const weatherData = generateSyntheticWeather(cities);
+
+ // Cache in DB
+ const row = (await q('SELECT id, config FROM risk_state ORDER BY updated_at DESC LIMIT 1')).rows[0];
+ if (row) {
+ const newCfg = { ...(row.config || {}), weather_cache: { results: weatherData, fetched_at: new Date().toISOString(), synthetic: true } };
+ await q('UPDATE risk_state SET config = $1, updated_at = NOW() WHERE id = $2', [JSON.stringify(newCfg), row.id]);
+ }
+
+ // 2. Fetch ALL live Kalshi events with nested markets (retry + fallback to prod)
+ let allEvents = [];
+ let weatherEvents = [];
+ let allMarkets = [];
+ const apiUrls = [KALSHI_BASE_URL, 'https://api.elections.kalshi.com/trade-api/v2', 'https://demo-api.kalshi.co/trade-api/v2'];
+ for (let attempt = 0; attempt < apiUrls.length; attempt++) {
+ try {
+ const url = apiUrls[attempt] + '/events?status=open&limit=200&with_nested_markets=true';
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), 15000);
+ const res = await fetch(url, { headers: { 'Accept': 'application/json' }, signal: controller.signal });
+ clearTimeout(timeout);
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ const evData = await res.json();
+ allEvents = evData.events || [];
+ if (allEvents.length > 0) {
+ if (attempt > 0) console.log(`[Ken] Fallback API ${attempt + 1} worked`);
+ break;
+ }
+ } catch (e) {
+ console.log(`[Ken] API ${attempt + 1}/${apiUrls.length} failed: ${e.message}`);
+ if (attempt < apiUrls.length - 1) await new Promise(r => setTimeout(r, 3000));
+ }
+ }
+ // Build market list from events
+ for (const evt of allEvents) {
+ if (evt.markets) {
+ for (const m of evt.markets) {
+ allMarkets.push({
+ ticker: m.ticker,
+ event_ticker: evt.event_ticker,
+ title: evt.title,
+ subtitle: m.subtitle || m.ticker,
+ volume: m.volume || 0,
+ volume_24h: m.volume_24h || 0,
+ open_interest: m.open_interest || 0,
+ yes_bid: m.yes_bid || 0,
+ yes_ask: m.yes_ask || 0,
+ no_bid: m.no_bid || 0,
+ no_ask: m.no_ask || 0,
+ last_price: m.last_price || 0,
+ prev_price: m.previous_price || m.last_price || 0,
+ status: m.status,
+ category: evt.category || '',
+ });
+ }
+ }
+ }
+ // Filter weather events for model-based predictions
+ weatherEvents = allEvents.filter(e => {
+ const t = ((e.category || '') + ' ' + (e.title || '')).toLowerCase();
+ return t.includes('weather') || t.includes('temperature') || t.includes('temp ') ||
+ t.includes('rain') || t.includes('snow') || t.includes('precipitation') ||
+ t.includes('hurricane') || t.includes('wind') || t.includes('°f');
+ });
+ console.log(`[Ken] Kalshi: ${allEvents.length} events, ${allMarkets.length} markets, ${weatherEvents.length} weather`);
+
+ const month = new Date().getMonth() + 1;
+ const predictions = [];
+
+ // 3. Score weather events against our weather model
+ for (const evt of weatherEvents) {
+ const city = extractCity(evt.title);
+ if (!city) continue;
+ const spec = parseWeatherEvent(evt.title);
+ if (!spec || spec.variable === 'unknown') continue;
+ const cityWeather = weatherData.find(w => w.city === city);
+ if (!cityWeather) continue;
+ const features = cityWeather[spec.variable === 'snow' ? 'precipitation' : spec.variable] || cityWeather.temperature;
+ if (!features?.values?.length) continue;
+
+ const rawProb = ensembleExceedance(features, spec.threshold, spec.operator);
+ const prior = climatologicalPrior(spec.variable, spec.threshold, month);
+ const combined = bayesianUpdate(prior, rawProb ?? 0.5);
+ const pYes = Math.max(0.01, Math.min(0.99, combined));
+
+ let marketPrice = 50;
+ const mkt = (evt.markets || [])[0];
+ if (mkt) {
+ const p = mkt.yes_ask || mkt.last_price || 50;
+ if (p > 0 && p < 100) marketPrice = p;
+ }
+
+ const edgeBps = Math.round((pYes * 100 - marketPrice) * 100);
+ predictions.push({
+ market: evt.title,
+ city,
+ side: edgeBps > 0 ? 'yes' : 'no',
+ p_yes: Math.round(pYes * 1000) / 10,
+ price_cents: marketPrice,
+ edge_bps: edgeBps,
+ variable: spec.variable,
+ threshold: spec.threshold,
+ type: 'weather_model',
+ });
+ }
+
+ // 4. Scan ALL high-volume markets for volume-based signals
+ const volumeIdeas = [];
+
+ // Sort by 24h volume to find what's hot
+ const activeMarkets = allMarkets
+ .filter(m => m.yes_bid > 0 && m.yes_ask > 0 && m.yes_ask < 100 && m.last_price > 0)
+ .sort((a, b) => b.volume_24h - a.volume_24h);
+
+ // Cache for 5-minute signal pipeline
+ cachedActiveMarkets = activeMarkets;
+
+ // Load price momentum from DB (compare current vs 2h ago and 6h ago)
+ let momentumMap = {};
+ // Also update cached version for signal pipeline MC simulations
+ try {
+ const { rows: momentumRows } = await kenQ(`
+ WITH latest AS (
+ SELECT DISTINCT ON (ticker) ticker, last_price as current_price, yes_bid, yes_ask, captured_at
+ FROM ken_market_snapshots ORDER BY ticker, captured_at DESC
+ ),
+ two_hours AS (
+ SELECT DISTINCT ON (ticker) ticker, last_price as price_2h
+ FROM ken_market_snapshots WHERE captured_at < NOW() - INTERVAL '2 hours'
+ ORDER BY ticker, captured_at DESC
+ ),
+ six_hours AS (
+ SELECT DISTINCT ON (ticker) ticker, last_price as price_6h
+ FROM ken_market_snapshots WHERE captured_at < NOW() - INTERVAL '6 hours'
+ ORDER BY ticker, captured_at DESC
+ )
+ SELECT l.ticker, l.current_price, t.price_2h, s.price_6h,
+ l.current_price - COALESCE(t.price_2h, l.current_price) as delta_2h,
+ l.current_price - COALESCE(s.price_6h, l.current_price) as delta_6h
+ FROM latest l LEFT JOIN two_hours t ON l.ticker = t.ticker LEFT JOIN six_hours s ON l.ticker = s.ticker
+ `);
+ for (const r of momentumRows) {
+ momentumMap[r.ticker] = { delta_2h: parseInt(r.delta_2h) || 0, delta_6h: parseInt(r.delta_6h) || 0, price_2h: r.price_2h, price_6h: r.price_6h };
+ }
+ } catch (e) { console.log('[Ken] Momentum query error:', e.message); }
+ cachedMomentumMap = momentumMap; // Update shared cache for signal pipeline
+
+ // ═══ INSTANT SLACK ALERT: Major Price Movements (>=10¢ in 2h or >=15¢ in 6h) ═══
+ try {
+ const bigMovers = Object.entries(momentumMap)
+ .filter(([, m]) => Math.abs(m.delta_2h) >= 10 || Math.abs(m.delta_6h) >= 15)
+ .sort((a, b) => Math.abs(b[1].delta_2h) - Math.abs(a[1].delta_2h));
+ if (bigMovers.length > 0) {
+ const moverLines = bigMovers.slice(0, 8).map(([ticker, m]) => {
+ const mkt = activeMarkets.find(am => am.ticker === ticker);
+ const title = mkt ? mkt.title : ticker;
+ const d2 = m.delta_2h > 0 ? `+${m.delta_2h}` : `${m.delta_2h}`;
+ const d6 = m.delta_6h > 0 ? `+${m.delta_6h}` : `${m.delta_6h}`;
+ const icon = Math.abs(m.delta_2h) >= 10 ? (m.delta_2h > 0 ? ':chart_with_upwards_trend:' : ':chart_with_downwards_trend:') : ':left_right_arrow:';
+ const et = mkt?.event_ticker || ticker?.replace(/-[^-]+$/, '') || ticker;
+ const link = `<https://kalshi.com/markets/${et}/${ticker}|View>`;
+ return ` ${icon} *${title}*\n 2h: *${d2}¢* | 6h: *${d6}¢* | Now: ${mkt?.last_price || '?'}¢ | ${link}`;
+ }).join('\n');
+ const timeStr = new Date().toLocaleString('en-US', { timeZone: 'America/Los_Angeles', hour: 'numeric', minute: '2-digit', hour12: true });
+ await sendSlack(`:rotating_light: *Major Price Movements* (${timeStr} PT)\n_${bigMovers.length} market(s) moved 10+¢ in 2h or 15+¢ in 6h_\n\n${moverLines}\n\nDashboard: http://45.61.58.125:7810`);
+ console.log(`[Ken] SLACK ALERT: ${bigMovers.length} major price movement(s) sent`);
+ }
+ } catch (e) { console.log('[Ken] Price movement alert error:', e.message); }
+
+ for (const m of activeMarkets.slice(0, 200)) {
+ const spread = m.yes_ask - m.yes_bid;
+ const noPrice = 100 - m.yes_ask;
+ const momentum = momentumMap[m.ticker] || { delta_2h: 0, delta_6h: 0 };
+
+ // ── SHORT: YES >= 75¢ (buy NO cheap, wider net than before) ──
+ if (m.yes_bid >= 75 && noPrice <= 25) {
+ let shortConf = 40;
+ if (noPrice <= 5) shortConf += 15; // dirt cheap NO
+ else if (noPrice <= 10) shortConf += 10;
+ else if (noPrice <= 15) shortConf += 5;
+ if (momentum.delta_2h < 0) shortConf += 10; // price dropping = good short
+ if (momentum.delta_6h < -3) shortConf += 10; // strong downtrend
+ if (m.volume_24h > 5000) shortConf += 5;
+ if (m.open_interest > 100000) shortConf += 5;
+ volumeIdeas.push({
+ market: m.title, subtitle: m.subtitle, ticker: m.ticker, event_ticker: m.event_ticker, side: 'NO',
+ reason: `YES at ${m.yes_bid}¢ → NO at ${noPrice}¢${momentum.delta_2h ? ` (${momentum.delta_2h > 0 ? '+' : ''}${momentum.delta_2h}¢/2h)` : ''}`,
+ volume_24h: m.volume_24h, open_interest: m.open_interest,
+ yes_price: m.yes_ask, no_price: noPrice, spread,
+ type: 'short_high_price', confidence: Math.min(90, shortConf),
+ });
+ }
+
+ // ── MOMENTUM SHORT: price dropping fast (was 50+, fell 5+ in 2h) ──
+ if (momentum.delta_2h <= -5 && m.last_price >= 30 && m.last_price <= 80) {
+ volumeIdeas.push({
+ market: m.title, subtitle: m.subtitle, ticker: m.ticker, event_ticker: m.event_ticker, side: 'NO',
+ reason: `Dropping ${momentum.delta_2h}¢/2h (${momentum.delta_6h || '?'}¢/6h) — momentum sell`,
+ volume_24h: m.volume_24h, open_interest: m.open_interest,
+ yes_price: m.yes_ask, no_price: noPrice, spread,
+ type: 'momentum_short', confidence: Math.min(80, 50 + Math.abs(momentum.delta_2h) * 2),
+ });
+ }
+
+ // ── MOMENTUM LONG: price rising fast (was low, jumped 5+ in 2h) ──
+ if (momentum.delta_2h >= 5 && m.last_price <= 70 && m.last_price >= 10) {
+ volumeIdeas.push({
+ market: m.title, subtitle: m.subtitle, ticker: m.ticker, event_ticker: m.event_ticker, side: 'YES',
+ reason: `Rising +${momentum.delta_2h}¢/2h (+${momentum.delta_6h || '?'}¢/6h) — momentum buy`,
+ volume_24h: m.volume_24h, open_interest: m.open_interest,
+ yes_price: m.yes_ask, no_price: noPrice, spread,
+ type: 'momentum_long', confidence: Math.min(80, 50 + momentum.delta_2h * 2),
+ });
+ }
+
+ // ── LONG CHEAP: YES <= 20¢ with volume (wider net) ──
+ if (m.yes_ask <= 20 && m.volume_24h > 100) {
+ let longConf = 35;
+ if (m.yes_ask <= 5) longConf += 5; // lottery ticket
+ if (m.volume_24h > 1000) longConf += 10; // lots of interest
+ if (m.volume_24h > 5000) longConf += 10;
+ if (momentum.delta_2h > 0) longConf += 10; // price rising
+ if (momentum.delta_6h > 2) longConf += 10;
+ volumeIdeas.push({
+ market: m.title, subtitle: m.subtitle, ticker: m.ticker, event_ticker: m.event_ticker, side: 'YES',
+ reason: `YES at ${m.yes_ask}¢, vol ${m.volume_24h.toLocaleString()}${momentum.delta_2h ? ` (${momentum.delta_2h > 0 ? '+' : ''}${momentum.delta_2h}¢/2h)` : ''}`,
+ volume_24h: m.volume_24h, open_interest: m.open_interest,
+ yes_price: m.yes_ask, no_price: noPrice, spread,
+ type: 'long_cheap', confidence: Math.min(80, longConf),
+ });
+ }
+
+ // ── CONTRARIAN SHORT: YES at 60-84¢ with negative momentum ──
+ if (m.yes_bid >= 60 && m.yes_bid < 85 && momentum.delta_2h < -2 && m.volume_24h > 200) {
+ volumeIdeas.push({
+ market: m.title, subtitle: m.subtitle, ticker: m.ticker, event_ticker: m.event_ticker, side: 'NO',
+ reason: `YES fading from ${(m.last_price + Math.abs(momentum.delta_2h))}¢→${m.last_price}¢, NO at ${noPrice}¢`,
+ volume_24h: m.volume_24h, open_interest: m.open_interest,
+ yes_price: m.yes_ask, no_price: noPrice, spread,
+ type: 'contrarian_short', confidence: Math.min(75, 45 + Math.abs(momentum.delta_2h) * 3),
+ });
+ }
+
+ // ── VOLUME SPIKE (kept but enhanced with momentum) ──
+ if (m.volume > 0 && m.volume_24h / m.volume > 0.05 && m.volume_24h > 500) {
+ volumeIdeas.push({
+ market: m.title,
+ subtitle: m.subtitle,
+ ticker: m.ticker,
+ event_ticker: m.event_ticker,
+ side: m.last_price > m.prev_price ? 'YES momentum' : 'NO momentum',
+ reason: `24h vol ${m.volume_24h.toLocaleString()} = ${Math.round(m.volume_24h / m.volume * 100)}% of all-time`,
+ volume_24h: m.volume_24h,
+ open_interest: m.open_interest,
+ yes_price: m.yes_ask,
+ no_price: noPrice,
+ spread,
+ type: 'volume_spike',
+ });
+ }
+
+ // Spread opportunity: wide spread with volume = market-making opportunity
+ if (spread >= 5 && m.volume_24h > 100 && m.open_interest > 1000) {
+ volumeIdeas.push({
+ market: m.title,
+ subtitle: m.subtitle,
+ ticker: m.ticker,
+ event_ticker: m.event_ticker,
+ side: 'SPREAD',
+ reason: `${spread}¢ spread, bid ${m.yes_bid}¢ / ask ${m.yes_ask}¢`,
+ volume_24h: m.volume_24h,
+ open_interest: m.open_interest,
+ yes_price: m.yes_ask,
+ no_price: noPrice,
+ spread,
+ type: 'wide_spread',
+ });
+ }
+ }
+
+ // Deduplicate volume ideas by ticker (keep highest confidence)
+ const deduped = new Map();
+ for (const idea of volumeIdeas) {
+ const existing = deduped.get(idea.ticker);
+ if (!existing || (idea.confidence || 50) > (existing.confidence || 50)) {
+ deduped.set(idea.ticker, idea);
+ }
+ }
+ const uniqueVolumeIdeas = [...deduped.values()];
+
+ logMemory('scan-after-signals');
+
+ // 5. Store market snapshots in DB (batch of 150 to capture more markets)
+ for (const m of activeMarkets.slice(0, 150)) {
+ try {
+ await kenQ(`
+ INSERT INTO ken_market_snapshots (ticker, event_ticker, title, subtitle, category, yes_bid, yes_ask, no_bid, no_ask, last_price, volume, volume_24h, open_interest, spread)
+ VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14)
+ `, [m.ticker, m.event_ticker, m.title, m.subtitle, m.category, m.yes_bid, m.yes_ask, m.no_bid, m.no_ask, m.last_price, m.volume, m.volume_24h, m.open_interest, m.yes_ask - m.yes_bid]);
+ } catch {}
+ }
+
+ // 6. Get sentiment data from last 2 hours for signal boosting
+ let sentimentBoosts = {};
+ try {
+ const { rows: recentSentiment } = await kenQ(`
+ SELECT relevance_ticker, AVG(sentiment_score) as avg_sent, COUNT(*) as post_count, SUM(score) as total_score
+ FROM ken_sentiment
+ WHERE captured_at > NOW() - INTERVAL '2 hours' AND relevance_ticker IS NOT NULL
+ GROUP BY relevance_ticker
+ `);
+ for (const s of recentSentiment) {
+ sentimentBoosts[s.relevance_ticker] = {
+ avgSentiment: parseFloat(s.avg_sent) || 0,
+ postCount: parseInt(s.post_count) || 0,
+ totalScore: parseInt(s.total_score) || 0,
+ };
+ }
+ } catch {}
+
+ // Get recent news sentiment (non-ticker-specific)
+ let newsSentiment = {};
+ try {
+ const { rows: newsRows } = await kenQ(`
+ SELECT keyword, AVG(sentiment_score) as avg_sent, COUNT(*) as cnt
+ FROM ken_sentiment
+ WHERE source = 'google_news' AND captured_at > NOW() - INTERVAL '4 hours'
+ GROUP BY keyword
+ `);
+ for (const n of newsRows) {
+ newsSentiment[n.keyword] = { avg: parseFloat(n.avg_sent) || 0, count: parseInt(n.cnt) || 0 };
+ }
+ } catch {}
+
+ // 7. Polymarket cross-reference for arbitrage
+ let polyArbs = [];
+ try {
+ polyArbs = await polymarketCrossRef(activeMarkets);
+ } catch (e) {
+ console.log('[Ken] Polymarket cross-ref failed:', e.message);
+ }
+
+ // 7b. Energy/LNG cross-market arbitrage scan
+ let energyArbs = [];
+ try {
+ energyArbs = await energyArbitrageScan(activeMarkets);
+ } catch (e) {
+ console.log('[Ken] Energy arb scan failed:', e.message);
+ }
+
+ // 8. Combine ALL signals with confidence scoring
+ const buySignals = predictions.filter(p => p.edge_bps > 200);
+ const shortSignals = predictions.filter(p => p.edge_bps < -200);
+ const longIdeas = uniqueVolumeIdeas.filter(v => v.side === 'YES' || v.side === 'YES momentum');
+ const shortIdeas = uniqueVolumeIdeas.filter(v => ['short_high_price', 'momentum_short', 'contrarian_short'].includes(v.type));
+ const spikeIdeas = uniqueVolumeIdeas.filter(v => v.type === 'volume_spike');
+ const momentumIdeas = uniqueVolumeIdeas.filter(v => v.type === 'momentum_long' || v.type === 'momentum_short');
+ const spreadIdeas = uniqueVolumeIdeas.filter(v => v.type === 'wide_spread');
+
+ // 9. Composite confidence with sentiment + momentum
+ const allSignals = [];
+ for (const p of [...buySignals, ...shortSignals]) {
+ let confidence = 50 + Math.min(30, Math.abs(p.edge_bps) / 50);
+ const sentBoost = sentimentBoosts[p.market] || {};
+ if (sentBoost.postCount > 3) confidence += sentBoost.avgSentiment > 0 ? 10 : -5;
+ const mom = momentumMap[p.ticker] || {};
+ if (p.edge_bps > 0 && mom.delta_2h > 0) confidence += 8; // momentum confirms long
+ if (p.edge_bps < 0 && mom.delta_2h < 0) confidence += 8; // momentum confirms short
+ const sources = ['weather_model'];
+ if (sentBoost.postCount) sources.push('reddit');
+ if (mom.delta_2h) sources.push('momentum');
+ allSignals.push({ ...p, confidence: Math.min(95, Math.round(confidence)), sources, signal_type: p.edge_bps > 0 ? 'long' : 'short' });
+ }
+ for (const v of uniqueVolumeIdeas) {
+ let confidence = v.confidence || 45; // Use pre-calculated confidence from signal detection
+ // Boost with sentiment
+ const sentKey = Object.keys(sentimentBoosts).find(k => v.ticker?.startsWith(k));
+ const sentBoost = sentKey ? sentimentBoosts[sentKey] : null;
+ if (sentBoost && sentBoost.postCount > 3) {
+ if (v.side === 'YES' && sentBoost.avgSentiment > 0.05) confidence += 10;
+ if (v.side === 'NO' && sentBoost.avgSentiment < -0.05) confidence += 10;
+ }
+ // Boost with news
+ for (const [nk, nv] of Object.entries(newsSentiment)) {
+ const titleLower = (v.market || '').toLowerCase();
+ if (nk.split(' ').some(w => w.length > 4 && titleLower.includes(w))) {
+ if (v.side === 'YES' && nv.avg > 0.05) confidence += 5;
+ if (v.side === 'NO' && nv.avg < -0.05) confidence += 5;
+ break;
+ }
+ }
+ const sources = ['volume_analysis'];
+ if (v.type?.includes('momentum')) sources.push('momentum');
+ if (sentBoost) sources.push('reddit');
+ const isShort = v.side === 'NO' || ['short_high_price', 'momentum_short', 'contrarian_short'].includes(v.type);
+ allSignals.push({
+ market: v.market, ticker: v.ticker, event_ticker: v.event_ticker, subtitle: v.subtitle,
+ side: isShort ? 'NO' : v.side === 'SPREAD' ? 'YES' : 'YES',
+ confidence: Math.min(95, Math.round(confidence)),
+ entry_price: isShort ? v.no_price : v.yes_price,
+ edge_bps: isShort ? Math.round((100 - (v.yes_price || 50)) * 100) : 0,
+ signal_type: v.type || 'volume',
+ reason: v.reason, sources, volume_24h: v.volume_24h,
+ });
+ }
+ for (const arb of polyArbs) {
+ allSignals.push({
+ market: arb.kalshi_title, ticker: arb.kalshi_ticker, event_ticker: arb.event_ticker,
+ side: arb.price_diff > 0 ? 'YES' : 'NO',
+ confidence: Math.min(90, 55 + Math.abs(arb.price_diff) * 2),
+ entry_price: arb.kalshi_price,
+ edge_bps: arb.price_diff * 100,
+ signal_type: 'polymarket_arb',
+ reason: `Kalshi ${arb.kalshi_price}¢ vs Poly ${arb.poly_price}¢ (${arb.price_diff > 0 ? '+' : ''}${arb.price_diff}¢ gap | ${arb.match_score}% match)`,
+ sources: ['polymarket_crossref'],
+ });
+ }
+ // Energy/LNG cross-market arb signals
+ for (const arb of energyArbs) {
+ if (arb.kalshi_ticker) {
+ allSignals.push({
+ market: arb.kalshi_title, ticker: arb.kalshi_ticker, event_ticker: arb.event_ticker,
+ side: arb.price_diff > 0 ? 'YES' : 'NO',
+ confidence: Math.min(92, 60 + Math.abs(arb.price_diff) * 2),
+ entry_price: arb.kalshi_price,
+ edge_bps: arb.price_diff * 100,
+ signal_type: 'energy_arb',
+ reason: `ENERGY ARB: Kalshi ${arb.kalshi_price}¢ vs ${arb.other_source} ${arb.other_price}¢ (${arb.price_diff > 0 ? '+' : ''}${arb.price_diff}¢ gap) — BUY ${arb.price_diff > 0 ? 'Kalshi' : arb.other_source}, SELL ${arb.price_diff > 0 ? arb.other_source : 'Kalshi'}`,
+ sources: ['energy_crossmarket_arb', arb.other_source.toLowerCase()],
+ });
+ }
+ }
+
+ // 10. Store predictions in DB
+ for (const sig of allSignals) {
+ try {
+ await kenQ(`
+ INSERT INTO ken_predictions (ticker, event_ticker, title, signal_type, side, confidence, entry_price, edge_bps, reasoning, sources)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
+ `, [
+ sig.ticker || '', sig.event_ticker || '', sig.market || '', sig.signal_type,
+ sig.side, sig.confidence, sig.entry_price || sig.price_cents || 0, sig.edge_bps || 0,
+ sig.reason || sig.reasoning || `${sig.signal_type} signal`, JSON.stringify(sig.sources || []),
+ ]);
+ } catch {}
+ }
+
+ // 10b. AUTO-TRADER: Execute trades on high-confidence signals
+ try {
+ await autoTrader(allSignals);
+ } catch (e) {
+ console.log(`[Ken] Auto-trader error: ${e.message}`);
+ }
+
+ // 10c. PORTFOLIO TRADER: Feed scan signals into paper portfolios
+ let portfolioTradesPlaced = 0;
+ for (const sig of allSignals.filter(s => s.confidence >= 40 && s.ticker)) {
+ try {
+ await autoPortfolioTrade({
+ marketId: sig.ticker,
+ market_title: sig.market || sig.ticker,
+ direction: sig.side === 'YES' ? 'BUY_YES' : 'BUY_NO',
+ expectedEdge: (sig.edge_bps || 0) / 10000,
+ confidence: (sig.confidence || 50) / 100,
+ reasoning: sig.reason || sig.reasoning || sig.signal_type,
+ signal_type: sig.signal_type,
+ aiEnhanced: (sig.sources || []).includes('gemini'),
+ mcSimulation: { consistent: true, stdDev: 0.05 },
+ num_articles: (sig.sources || []).length,
+ agreement: (sig.confidence || 50) / 100,
+ });
+ portfolioTradesPlaced++;
+ } catch {}
+ }
+ if (portfolioTradesPlaced > 0) console.log(`[Ken] Portfolio trades: ${portfolioTradesPlaced} signals fed to paper portfolios`);
+
+ const scanDuration = Date.now() - scanStart;
+
+ // 11. Log performance
+ try {
+ await kenQ(`
+ INSERT INTO ken_performance (total_markets, active_markets, predictions_made, long_signals, short_signals, sentiment_items, scan_duration_ms, slack_sent)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
+ `, [
+ allMarkets.length, activeMarkets.length, allSignals.length,
+ allSignals.filter(s => s.side === 'YES').length,
+ allSignals.filter(s => s.side === 'NO').length,
+ Object.keys(sentimentBoosts).length,
+ scanDuration, false,
+ ]);
+ } catch {}
+
+ console.log(`[Ken] Scan complete: ${allMarkets.length} markets, ${activeMarkets.length} active, ${allSignals.length} signals (${allSignals.filter(s=>s.side==='YES').length} long, ${allSignals.filter(s=>s.side==='NO').length} short), ${polyArbs.length} arbs, ${Object.keys(sentimentBoosts).length} sentiment boosts | ${scanDuration}ms`);
+
+ // 12a. Run Signal Pipeline (News → Sentiment → Probability → Signals → Risk)
+ try {
+ const pipelineSignals = await signalPipeline(activeMarkets);
+ if (pipelineSignals > 0) {
+ console.log(`[Ken] Signal Pipeline produced ${pipelineSignals} risk-assessed signals`);
+ }
+ } catch (e) {
+ console.log(`[Ken] Signal Pipeline error: ${e.message}`);
+ }
+
+ // 12b. Update market mappings
+ try {
+ await updateMarketMappings(activeMarkets);
+ } catch {}
+
+ // 12. Build and send Slack alert (max once per hour to not spam)
+ const now = Date.now();
+ const shouldSlack = (now - lastSlackTime > SLACK_COOLDOWN_MS) || allSignals.some(s => s.confidence >= 75);
+
+ if (shouldSlack && allSignals.length > 0) {
+ lastSlackTime = now;
+ const timeStr = new Date().toLocaleString('en-US', { timeZone: 'America/New_York', hour: 'numeric', minute: '2-digit', hour12: true });
+ const parts = [];
+
+ parts.push(`:dog: *Ken — Autonomous Scan* (${timeStr} ET)`);
+ parts.push(`_${allMarkets.length} markets | ${activeMarkets.length} active | ${allSignals.length} signals | ${KALSHI_ENV}_\n`);
+
+ // Helper: build Kalshi market link
+ const kalshiLink = (ticker, eventTicker) => {
+ const et = eventTicker || ticker?.replace(/-[^-]+$/, '') || ticker;
+ return `<https://kalshi.com/markets/${et}/${ticker}|Trade on Kalshi>`;
+ };
+
+ // Helper: confidence badge with color (green→yellow→orange→red)
+ const confBadge = (conf) => {
+ if (conf >= 80) return `:large_green_circle: *${conf}%*`;
+ if (conf >= 65) return `:large_yellow_circle: *${conf}%*`;
+ if (conf >= 50) return `:large_orange_circle: *${conf}%*`;
+ return `:red_circle: *${conf}%*`;
+ };
+
+ // Confidence legend
+ parts.push(`_:large_green_circle: 80%+ Strong :large_yellow_circle: 65-79% Good :large_orange_circle: 50-64% Moderate :red_circle: <50% Speculative_`);
+
+ // High-confidence signals first (>= 70)
+ const highConf = allSignals.filter(s => s.confidence >= 70).sort((a, b) => b.confidence - a.confidence);
+ if (highConf.length > 0) {
+ const lines = highConf.slice(0, 5).map((s, i) => {
+ const icon = s.side === 'YES' ? ':chart_with_upwards_trend:' : ':small_red_triangle_down:';
+ const link = kalshiLink(s.ticker, s.event_ticker);
+ return ` ${icon} ${confBadge(s.confidence)} *${s.market}*\n ${s.side} | ${s.reason || `Edge ${s.edge_bps}bps`}\n :link: ${link}`;
+ }).join('\n');
+ parts.push(`:rotating_light: *High Confidence Signals*\n${lines}`);
+ }
+
+ // Short ideas
+ const shorts = allSignals.filter(s => s.side === 'NO' && s.confidence >= 50).sort((a, b) => b.confidence - a.confidence);
+ if (shorts.length > 0 && highConf.filter(s => s.side === 'NO').length === 0) {
+ const lines = shorts.slice(0, 3).map((s, i) => {
+ const link = kalshiLink(s.ticker, s.event_ticker);
+ return ` ${confBadge(s.confidence)} *${s.market}* — BUY NO\n ${s.reason || ''}\n :link: ${link}`;
+ }).join('\n');
+ parts.push(`:moneybag: *Short Ideas (Buy NO)*\n${lines}`);
+ }
+
+ // Volume spikes
+ if (spikeIdeas.length > 0) {
+ const lines = spikeIdeas.sort((a, b) => b.volume_24h - a.volume_24h).slice(0, 3)
+ .map((p, i) => {
+ const link = kalshiLink(p.ticker, p.event_ticker);
+ const conf = p.confidence || 45;
+ return ` ${confBadge(conf)} *${p.market}*\n ${p.reason}\n :link: ${link}`;
+ }).join('\n');
+ parts.push(`:fire: *Volume Spikes*\n${lines}`);
+ }
+
+ // Momentum moves
+ if (momentumIdeas.length > 0) {
+ const lines = momentumIdeas.sort((a, b) => (b.confidence || 0) - (a.confidence || 0)).slice(0, 4)
+ .map((p, i) => {
+ const icon = p.type === 'momentum_long' ? ':arrow_up:' : ':arrow_down:';
+ const link = kalshiLink(p.ticker, p.event_ticker);
+ const conf = p.confidence || 50;
+ return ` ${icon} ${confBadge(conf)} *${p.market}*\n ${p.subtitle || ''} — ${p.reason}\n :link: ${link}`;
+ }).join('\n');
+ parts.push(`:rocket: *Momentum Moves*\n${lines}`);
+ }
+
+ // Polymarket arbitrage
+ if (polyArbs.length > 0) {
+ const lines = polyArbs.slice(0, 5)
+ .map(a => {
+ const conf = Math.min(90, 55 + Math.abs(a.price_diff) * 2);
+ const kLink = kalshiLink(a.kalshi_ticker, a.event_ticker);
+ const pLink = `<https://polymarket.com/event/${a.poly_slug}|Polymarket>`;
+ return ` ${confBadge(conf)} *${a.kalshi_title}* (${a.kalshi_subtitle || ''})\n Kalshi: ${a.kalshi_price}¢ vs Poly: ${a.poly_price}¢ → *${a.arb_side}*\n ${kLink} | ${pLink} | Match: ${a.match_score}%`;
+ }).join('\n');
+ parts.push(`:scales: *Polymarket Arbitrage (${polyArbs.length} found)*\n${lines}`);
+ }
+
+ // Reddit buzz
+ const buzzKeys = Object.entries(sentimentBoosts).filter(([, v]) => v.postCount >= 3).sort((a, b) => b[1].totalScore - a[1].totalScore);
+ if (buzzKeys.length > 0) {
+ const lines = buzzKeys.slice(0, 3).map(([ticker, v]) => {
+ const sentIcon = v.avgSentiment > 0.1 ? ':large_green_circle:' : v.avgSentiment < -0.1 ? ':red_circle:' : ':large_yellow_circle:';
+ return ` ${sentIcon} ${ticker}: ${v.postCount} posts, sentiment ${v.avgSentiment > 0 ? '+' : ''}${v.avgSentiment.toFixed(2)}, karma ${v.totalScore}`;
+ }).join('\n');
+ parts.push(`:speech_balloon: *Reddit Buzz*\n${lines}`);
+ }
+
+ // Auto-trader portfolio summary
+ try {
+ const traderState = await getTraderState();
+ const closed = await kenQ("SELECT COUNT(*) as total, SUM(CASE WHEN pnl_cents > 0 THEN 1 ELSE 0 END) as wins, SUM(CASE WHEN pnl_cents <= 0 THEN 1 ELSE 0 END) as losses, COALESCE(SUM(pnl_cents), 0) as pnl FROM ken_trades WHERE status != 'open'");
+ const cs = closed.rows[0] || {};
+ const pnl = parseInt(cs.pnl || 0);
+ const pnlStr = `${pnl >= 0 ? '+' : ''}$${(pnl/100).toFixed(2)}`;
+ const pnlEmoji = pnl > 0 ? ':moneybag:' : pnl < 0 ? ':chart_with_downwards_trend:' : ':neutral_face:';
+ const openLines = traderState.openPositions.map(t =>
+ ` • ${t.side.toUpperCase()} ${t.ticker} x${t.count} @ ${t.price_cents}¢ ($${(t.cost_cents/100).toFixed(2)})`
+ ).join('\n');
+ parts.push(`:bank: *Auto-Trader Portfolio*\n` +
+ `Budget: $${(TRADE_CONFIG.budget_cents/100).toFixed(2)} | Invested: $${(traderState.totalInvested/100).toFixed(2)} | Available: $${(traderState.available/100).toFixed(2)}\n` +
+ `Open: ${traderState.openCount}/${TRADE_CONFIG.max_open_positions} positions` +
+ (openLines ? `\n${openLines}` : '') + `\n` +
+ `${pnlEmoji} P&L: *${pnlStr}* (${cs.wins || 0}W/${cs.losses || 0}L) | Today loss: $${(traderState.dailyLoss/100).toFixed(2)}/$${(TRADE_CONFIG.daily_loss_limit_cents/100).toFixed(2)}`);
+ } catch {}
+
+ // Performance stats
+ try {
+ const { rows: perfRows } = await kenQ(`
+ SELECT COUNT(*) as total_preds,
+ SUM(CASE WHEN outcome='win' THEN 1 ELSE 0 END) as wins,
+ SUM(CASE WHEN outcome='loss' THEN 1 ELSE 0 END) as losses
+ FROM ken_predictions WHERE created_at > NOW() - INTERVAL '24 hours'
+ `);
+ const perf = perfRows[0];
+ if (perf && parseInt(perf.total_preds) > 0) {
+ parts.push(`_24h stats: ${perf.total_preds} predictions, ${perf.wins || 0}W/${perf.losses || 0}L_`);
+ }
+ } catch {}
+
+ parts.push(`\nDashboard: http://45.61.58.125:7810`);
+
+ await sendSlack(parts.join('\n\n'));
+
+ // Update performance row
+ try {
+ await kenQ(`UPDATE ken_performance SET slack_sent = true WHERE id = (SELECT MAX(id) FROM ken_performance)`);
+ } catch {}
+ } else if (allSignals.length > 0) {
+ const cooldownLeft = Math.max(0, Math.round((SLACK_COOLDOWN_MS - (now - lastSlackTime)) / 60000));
+ console.log(`[Ken] ${allSignals.length} signals found, Slack cooldown: ${cooldownLeft}min left`);
+ } else {
+ console.log(`[Ken] No signals this cycle (${allMarkets.length} markets scanned)`);
+ }
+
+ } catch (err) {
+ console.error('[Ken] Autonomous scan error:', err.message);
+ try { await sendSlack(`:warning: *Ken Error* — Scan failed: ${err.message}`); } catch {}
+ }
+}
+
+// ══════════════════════════════════════════════
+// AUTO-PORTFOLIO TRADING ENGINE — 10 personalities, $20/day each
+// ══════════════════════════════════════════════
+
+// Portfolio strategy filters — each personality decides differently
+// ═══ Portfolio Strategy Filters ═══
+// Each strategy is deliberately exclusive — a signal should match 1-3 portfolios, not all 10.
+// Strategies use edge/confidence/direction/article count/MC/AI to create real diversification.
+const PORTFOLIO_STRATEGIES = {
+ // Alpha: High edge (>15%) with LOWER confidence (<70%). Big edges, less certainty — speculative.
+ aggressive: (sig) => Math.abs(sig.edge) >= 0.15 && sig.confidence < 0.70,
+
+ // Beta: High confidence (>70%) with ANY edge. The "safe" bet — trusts confidence over edge size.
+ conservative: (sig) => sig.confidence >= 0.70 && Math.abs(sig.edge) >= 0.05,
+
+ // Storm: Weather/climate markets identified by market_id patterns or reasoning keywords
+ weather: (sig) => /weather|temp|rain|snow|wind|hurricane|precip|storm|°f|heat|cold|frost|drought|flood|tornado|KXTEMP|KXRAIN|KXSNOW|KXHURR/i.test((sig.reasoning || '') + ' ' + (sig.market_id || '')),
+
+ // Momentum: Only trades when edge increased (high agreement = many articles agree).
+ // Needs 3+ articles with >65% agreement — evidence of growing consensus.
+ momentum: (sig) => (sig.agreement || 0) >= 0.65 && (sig.num_articles || 0) >= 3 && Math.abs(sig.edge) >= 0.05,
+
+ // Contrarian: ONLY BUY_NO trades. Bets against the crowd. Never buys YES.
+ contrarian: (sig) => sig.direction === 'BUY_NO',
+
+ // Nova: Only Gemini AI-enhanced signals. If AI didn't weigh in, skip.
+ ai_enhanced: (sig) => sig.ai_enhanced === true,
+
+ // Oracle: MC-validated WITH tight spread (stdDev < 8%) AND moderate edge. The "careful" bot.
+ mc_validated: (sig) => sig.mc_consistent === true && (sig.mc_stddev || 99) < 0.08 && Math.abs(sig.edge) >= 0.05 && Math.abs(sig.edge) < 0.20,
+
+ // Shark: Small edges (3-10%), rapid fire. Takes quantity over quality. Rejects big edges.
+ scalper: (sig) => Math.abs(sig.edge) >= 0.03 && Math.abs(sig.edge) < 0.10 && sig.confidence >= 0.30,
+
+ // Turtle: Ultra-patient. Needs EVERYTHING: 5+ articles, MC consistent, confidence >80%, moderate edge.
+ patient: (sig) => sig.confidence >= 0.80 && sig.mc_consistent === true && (sig.num_articles || 0) >= 5 && Math.abs(sig.edge) >= 0.05,
+
+ // Wildcard: Random 20% of signals — true control group. Lower chance than before to create separation.
+ random: (sig) => Math.random() < 0.20,
+
+ // ═══ RISKY PORTFAUXLIOS: Micro → Macro ═══
+
+ // Penny: Any edge >= 1%. Catches everything. Micro bets, max volume.
+ penny_pincher: (sig) => Math.abs(sig.edge) >= 0.01,
+
+ // Spray: Random 50% of ALL signals. Shotgun approach — tests luck vs skill.
+ spray_pray: (sig) => Math.random() < 0.50,
+
+ // Nickel: Low bar (edge >= 2%, conf >= 20%). Catches most signals.
+ nickel_slots: (sig) => Math.abs(sig.edge) >= 0.02 && sig.confidence >= 0.20,
+
+ // Degen: Edge >= 5%, ignores confidence entirely. Pure edge chaser.
+ degen_lite: (sig) => Math.abs(sig.edge) >= 0.05,
+
+ // Politics: Only political markets. KXPRES, KXSEN, KXGOV, KXCONGRESS, KXPRESPERSON, etc.
+ politics_junkie: (sig) => /KXPRES|KXSEN|KXGOV|KXCONG|KXHOUSE|KXELEC|KXPARTY|KXPRESPERSON|political|election|congress|senate|president|governor/i.test((sig.market_id || '') + ' ' + (sig.reasoning || '')),
+
+ // Double: Only high-edge signals (>20%). Goes big when edge is massive.
+ double_down: (sig) => Math.abs(sig.edge) >= 0.20,
+
+ // Night: Only signals with high MC stddev (>8%) — volatile markets others reject.
+ volatility_rider: (sig) => (sig.mc_stddev || 0) >= 0.08 && Math.abs(sig.edge) >= 0.05,
+
+ // Whale: Edge >25% AND confidence >60%. Rare but massive. The sniper.
+ whale: (sig) => Math.abs(sig.edge) >= 0.25 && sig.confidence >= 0.60,
+
+ // YOLO: Edge >30%. Doesn't care about anything else. Max degen.
+ yolo: (sig) => Math.abs(sig.edge) >= 0.30,
+
+ // Full Send: Takes EVERY signal. Max exposure. Tests whether the signal pipeline itself is profitable.
+ full_send: (sig) => true,
+
+ // ═══ CPU-POWERED: Computational / Multi-Factor Strategies ═══
+
+ // Kelly: Only trades when Kelly fraction (edge / odds) > 0.10. Classic bankroll math.
+ // Kelly f* = (bp - q) / b where b=odds, p=prob_win, q=prob_lose. Simplified: edge/(1+edge).
+ kelly_criterion: (sig) => {
+ const e = Math.abs(sig.edge);
+ const kelly = e / (1 + e); // simplified Kelly fraction
+ return kelly >= 0.10 && sig.confidence >= 0.40;
+ },
+
+ // Sharpe: Signal-to-noise ratio. edge / mc_stddev > 2.0. High SNR = clean signal, low noise.
+ sharpe_sniper: (sig) => {
+ const snr = Math.abs(sig.edge) / Math.max(sig.mc_stddev, 0.01);
+ return snr >= 2.0 && sig.mc_consistent;
+ },
+
+ // Bayesian: Combines confidence with article count as evidence weight.
+ // More articles = stronger prior. posterior = conf * (1 - 1/(1+articles)) * edge_factor.
+ bayesian_blend: (sig) => {
+ const evidenceWeight = 1 - 1 / (1 + (sig.num_articles || 0));
+ const posterior = sig.confidence * evidenceWeight * (1 + Math.abs(sig.edge));
+ return posterior >= 0.55;
+ },
+
+ // Ensemble: ALL factors must align — AI + MC + confidence + edge. Maximum consensus required.
+ ensemble_lock: (sig) => sig.ai_enhanced && sig.mc_consistent && sig.confidence >= 0.60 && Math.abs(sig.edge) >= 0.10 && (sig.num_articles || 0) >= 2,
+
+ // Mean Revert: High MC volatility (stddev > 10%) + moderate edge. Bets on reversion to mean.
+ mean_revert: (sig) => (sig.mc_stddev || 0) >= 0.10 && Math.abs(sig.edge) >= 0.08 && Math.abs(sig.edge) <= 0.25,
+
+ // Info Ratio: (articles * agreement) / max(mc_stddev, 0.01). Quality of information per unit noise.
+ info_ratio: (sig) => {
+ const ir = ((sig.num_articles || 0) * (sig.agreement || 0)) / Math.max(sig.mc_stddev, 0.01);
+ return ir >= 15 && Math.abs(sig.edge) >= 0.05;
+ },
+
+ // Anti-FOMO: Small edge (<12%) but HIGH confidence (>75%). Calm, certain, steady plays.
+ anti_fomo: (sig) => Math.abs(sig.edge) >= 0.03 && Math.abs(sig.edge) <= 0.12 && sig.confidence >= 0.75,
+
+ // Nightcrawler: BUY_NO only + AI enhanced + MC consistent. Sophisticated short-bias strategy.
+ nightcrawler: (sig) => sig.direction === 'BUY_NO' && sig.ai_enhanced && sig.mc_consistent,
+
+ // Heatseeker: Composite multi-factor score. Weighted blend of all signal dimensions.
+ // score = edge*40 + conf*30 + agreement*20 + min(articles/10,1)*10. Trade when score > 35.
+ heatseeker: (sig) => {
+ const score = Math.abs(sig.edge) * 40 + sig.confidence * 30 + (sig.agreement || 0) * 20 + Math.min((sig.num_articles || 0) / 10, 1) * 10;
+ return score >= 35;
+ },
+
+ // Quant: Geometric mean of edge and confidence, weighted by MC consistency. Pure math bot.
+ // geoMean = sqrt(edge * conf). Trade when geoMean > 0.15 and MC agrees.
+ quant_core: (sig) => {
+ const geo = Math.sqrt(Math.abs(sig.edge) * Math.max(sig.confidence, 0.001));
+ return geo >= 0.15 && (sig.mc_consistent || sig.confidence >= 0.80);
+ },
+
+ // ═══ ETF CATEGORY SPECIALISTS: Sector-Focused Portfolios ═══
+
+ etf_presidential: (sig) => /KXPRESPERSON|KXPRESPARTY/i.test(sig.market_id) ||
+ /president|2028 election|presidential race|white house|oval office|nominee/i.test(sig.reasoning + ' ' + sig.market_title),
+
+ etf_cabinet: (sig) => /KXCABOUT|KXCABLEAVE/i.test(sig.market_id) ||
+ /cabinet|secretary of|confirmation hearing|appointee|gabbard|hegseth|rubio|noem|rfk|bessent|lutnick/i.test(sig.reasoning + ' ' + sig.market_title),
+
+ etf_congress: (sig) => /KXCONG|KXHOUSE|SENATE|KXNEXTSPEAKER|KXCAPCONTROL|KXVETOOVERRIDE/i.test(sig.market_id) ||
+ /congress|senate|house of rep|speaker|legislation|bill pass|shutdown|filibuster|debt ceiling/i.test(sig.reasoning + ' ' + sig.market_title),
+
+ etf_scotus: (sig) => /KXSCOURT/i.test(sig.market_id) ||
+ /supreme court|scotus|justice|ruling|overturn|constitutional|judicial review/i.test(sig.reasoning + ' ' + sig.market_title),
+
+ etf_fed: (sig) => /KXFEDCHAIRNOM|KXBALANCE/i.test(sig.market_id) ||
+ /federal reserve|fed chair|interest rate|fomc|rate cut|rate hike|powell|warsh|monetary policy|quantitative/i.test(sig.reasoning + ' ' + sig.market_title),
+
+ etf_economy: (sig) => /KXGDP/i.test(sig.market_id) ||
+ /\bgdp\b|recession|economic growth|jobs report|unemployment|nonfarm payroll|consumer spending|retail sales|pce\b|cpi\b/i.test(sig.reasoning + ' ' + sig.market_title),
+
+ etf_geopolitics: (sig) => /KXZELENSKYPUTIN|KXNEXTUKPM|KXNEXTIRANLEADER|KXEUEXIT|KXTAIWANLVL|KXFTA/i.test(sig.market_id) ||
+ /geopolit|war\b|invasion|sanction|nato|treaty|ceasefire|diplomat|putin|zelensky|china|taiwan|iran|tariff|trade war/i.test(sig.reasoning + ' ' + sig.market_title),
+
+ etf_territory: (sig) => /KXGREENLAND|KXGREENTERRITORY|KXGREENLANDPRICE|KXGTAPRICE|KXSTATE51|KXUSAEXPANDTERRITORY/i.test(sig.market_id) ||
+ /greenland|statehood|territory|annex|state 51|panama canal|territorial/i.test(sig.reasoning + ' ' + sig.market_title),
+
+ etf_climate: (sig) => /KXWARMING|KXTEMP|KXRAIN|KXSNOW|KXHURR/i.test(sig.market_id) ||
+ /warming|climate|temperature|hurricane|tornado|flood|drought|polar vortex|heat wave|cold snap|freeze|precipitation|storm/i.test(sig.reasoning + ' ' + sig.market_title),
+
+ etf_energy: (sig) => /KXPRIMEENGCONSUMPTION|KXENERG/i.test(sig.market_id) ||
+ /\benergy\b|lng\b|natural gas|oil price|petroleum|electricity|power grid|blackout|eia\b|opec|crude|pipeline|refinery|utility|heating bill/i.test(sig.reasoning + ' ' + sig.market_title),
+
+ etf_tech: (sig) => /KXOAIANTH|KXMUSKTRILLION|KXFUSION/i.test(sig.market_id) ||
+ /artificial intelligence|\bai\b|openai|anthropic|chatgpt|gpt-5|machine learning|musk.*trillion|tesla|nvidia|semiconductor|quantum computing|fusion/i.test(sig.reasoning + ' ' + sig.market_title),
+
+ etf_space: (sig) => /KXMOONMAN|KXCOLONIZEMARS|KXSPACEX/i.test(sig.market_id) ||
+ /spacex|nasa|rocket|orbit|mars|moon|starship|falcon|launch|artemis|blue origin|astronaut|satellite/i.test(sig.reasoning + ' ' + sig.market_title),
+
+ etf_crypto: (sig) => /KXCRYPTO|KXBTC|KXETH/i.test(sig.market_id) ||
+ /bitcoin|btc|ethereum|eth|crypto|blockchain|defi|stablecoin|sec.*crypto|digital asset|web3|binance|coinbase/i.test(sig.reasoning + ' ' + sig.market_title),
+
+ etf_sports: (sig) => /KXNBA|KXNFL|KXNBASEATTLE|KXCANADACUP/i.test(sig.market_id) ||
+ /\bnba\b|\bnfl\b|\bmlb\b|\bnhl\b|sports|playoff|championship|super bowl|world series|draft|mvp|coach/i.test(sig.reasoning + ' ' + sig.market_title),
+
+ etf_entertainment: (sig) => /KXSWIFTKELCE|KXTAYLORSWIFT|KXACTORSONNYCROCKETT|KXLIVENATION/i.test(sig.market_id) ||
+ /taylor swift|celebrity|movie|oscar|grammy|concert|entertainment|viral|streaming|netflix|album|tour/i.test(sig.reasoning + ' ' + sig.market_title),
+
+ etf_legal: (sig) => /KXTRUMPPARDONS|KXINSURRECTION|KXIMPEACH|KXTRUMPREMOVE|KXTRUMPRESIGN/i.test(sig.market_id) ||
+ /pardon|impeach|indictment|trial|guilty|conviction|sentencing|insurrection|special counsel|subpoena|contempt/i.test(sig.reasoning + ' ' + sig.market_title),
+
+ etf_financials: (sig) => /KXBOND/i.test(sig.market_id) ||
+ /bond yield|treasury|10-year|yield curve|s&p|nasdaq|dow jones|stock market|bear market|bull market|correction|ipo|banking/i.test(sig.reasoning + ' ' + sig.market_title),
+
+ etf_govreform: (sig) => /KXAGENCYELIM|KXGOVTCUTS|KXWITHDRAW/i.test(sig.market_id) ||
+ /\bdoge\b|government efficiency|agency.*elim|department.*cut|federal workforce|deregulat|budget cut|spending cut|executive order/i.test(sig.reasoning + ' ' + sig.market_title),
+
+ etf_global_social: (sig) => /KXNEWPOPE|KXALBERTAREFYES/i.test(sig.market_id) ||
+ /pope|vatican|catholic|referendum|independence|separatist|social movement|protest|migration|refugee/i.test(sig.reasoning + ' ' + sig.market_title),
+
+ etf_broad_market: (sig) => Math.abs(sig.edge) >= 0.08 && sig.confidence >= 0.50 && (sig.mc_consistent || sig.ai_enhanced),
+
+ // ═══ SECTOR-BASED PORTFOLIOS (IDs 51-100): Granular sub-sector filters ═══
+
+ // — Energy & Commodities (51-55) —
+ lng_exports: (sig) => /lng|liquefied natural gas|natural gas export|gas terminal|lng shipment|henry hub/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ oil_price_band: (sig) => /\boil\b|crude|brent|wti|petroleum|barrel|oil price|oil production/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ natgas_seasonal: (sig) => /natural gas|natgas|gas price|gas storage|heating season|gas futures/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ opec_decisions: (sig) => /opec|oil cartel|production cut|oil output|saudi.*oil|oil supply/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ power_grid: (sig) => /power grid|blackout|electricity|energy grid|brownout|utility|power outage|grid fail/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+
+ // — AI & Tech Stocks (56-60) —
+ semiconductor: (sig) => /semiconductor|chip|nvidia|tsmc|intel|amd|chip act|wafer|fab\b|gpu shortage/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ ai_regulation: (sig) => /ai regulation|ai safety|ai executive order|ai bill|regulate.*ai|ai governance|ai act/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ tech_earnings: (sig) => /tech.*earning|earning.*tech|apple.*revenue|google.*revenue|meta.*revenue|amazon.*revenue|magnificent seven|big tech.*report/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ autonomous_vehicles: (sig) => /autonomous|self.driving|robotaxi|waymo|cruise|lidar|adas|driverless/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ cloud_market: (sig) => /cloud computing|aws|azure|google cloud|cloud revenue|saas|cloud market|cloud spend/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+
+ // — Crypto & Digital (61-65) —
+ btc_price_bands: (sig) => /bitcoin|btc|bitcoin price|btc.*\$|bitcoin.*\$|bitcoin.*above|bitcoin.*below/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ eth_upgrades: (sig) => /ethereum|eth\b|eth.*upgrade|ethereum.*upgrade|ethereum.*merge|eth.*fork|ether.*price/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ crypto_regulation: (sig) => /crypto.*regulat|sec.*crypto|crypto.*ban|crypto.*bill|digital asset.*law|crypto.*legal|stablecoin.*act/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ stablecoin_policy: (sig) => /stablecoin|usdt|usdc|tether|circle|stablecoin.*regulat|stablecoin.*bill|cbdc/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ defi_events: (sig) => /defi|decentralized finance|dex|uniswap|aave|compound|liquidity pool|yield farm|tvl/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+
+ // — Macro Economics (66-70) —
+ cpi_monthly: (sig) => /\bcpi\b|consumer price|inflation.*rate|inflation.*report|core inflation|price index/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ nfp_monthly: (sig) => /nonfarm|non.farm|payroll|jobs report|jobs.*added|employment.*report|unemployment.*rate|jobless.*claim/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ housing_data: (sig) => /housing|home.*sale|home.*price|mortgage|existing home|housing start|case.shiller|real estate.*data/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ gdp_quarterly: (sig) => /\bgdp\b|gross domestic|economic growth|gdp.*quarter|gdp.*annual|recession.*gdp/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ yield_spread: (sig) => /yield curve|yield spread|inverted yield|2.year.*10.year|treasury spread|curve inversion/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+
+ // — Finance & Markets (71-75) —
+ sp500_levels: (sig) => /s&p|s&p 500|sp500|spx|s&p.*above|s&p.*below|stock market.*level/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ fed_rate_path: (sig) => /fed.*rate|interest rate|fomc|rate cut|rate hike|federal funds|fed.*meeting|monetary policy|powell.*rate/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ bank_stress: (sig) => /bank.*stress|bank.*fail|banking crisis|bank run|fdic|bank.*collapse|regional bank|svb|silicon valley bank/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ bond_yields: (sig) => /bond.*yield|treasury.*yield|10.year.*yield|bond.*market|treasury.*rate|bond.*price/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ volatility_index: (sig) => /\bvix\b|volatility index|volatility.*spike|cboe|fear.*index|market.*volatility/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+
+ // — Politics & Policy (76-80) —
+ state_elections: (sig) => /KXSEN|KXGOV|state election|governor.*race|senate.*race|state house|state legislature|primary.*election/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ congress_votes: (sig) => /KXCONG|KXHOUSE|congress.*vote|house.*vote|senate.*vote|bill.*pass|legislation.*vote|floor vote/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ tariff_policy: (sig) => /tariff|trade war|import duty|trade deficit|trade policy|customs duty|trade agreement|wto/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ immigration_policy: (sig) => /immigration|border|migrant|asylum|deportation|visa|daca|immigration.*reform|border.*wall/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ tax_legislation: (sig) => /tax.*bill|tax.*reform|tax.*cut|tax.*hike|tax.*code|irs|estate tax|capital gains.*tax|corporate tax/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+
+ // — Sports (81-85) —
+ nba_outcomes: (sig) => /KXNBA|\bnba\b|basketball|nba.*final|nba.*champion|nba.*mvp|nba.*draft/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ nfl_outcomes: (sig) => /KXNFL|\bnfl\b|football|super bowl|nfl.*draft|nfl.*champion|quarterback|touchdown/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ soccer_global: (sig) => /soccer|football.*world|world cup|premier league|champions league|mls|fifa|la liga|bundesliga/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ mlb_outcomes: (sig) => /KXMLB|\bmlb\b|baseball|world series|mlb.*draft|home run|batting|pitcher/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ combat_sports: (sig) => /\bufc\b|\bmma\b|boxing|fight.*night|ufc.*champion|knockout|title fight|heavyweight/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+
+ // — Health & Science (86-90) —
+ fda_approvals: (sig) => /fda.*approv|fda.*reject|drug.*approv|new drug|biologic.*approv|fda.*review|pdufa/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ disease_tracking: (sig) => /outbreak|pandemic|epidemic|covid|h5n1|bird flu|mpox|disease.*spread|cdc.*alert|who.*emergency/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ biotech_catalysts: (sig) => /biotech|clinical trial|phase 3|gene therapy|mrna|crispr|drug.*trial|biotech.*stock/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ health_metrics: (sig) => /life expectancy|obesity|opioid|drug overdose|health.*metric|public health|mortality rate|vaccination rate/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ space_milestones: (sig) => /spacex|nasa|rocket.*launch|mars|moon.*landing|starship|artemis|blue origin|orbit|satellite.*launch/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+
+ // — Media & Culture (91-95) —
+ box_office: (sig) => /box office|movie.*gross|film.*revenue|opening weekend|blockbuster|cinema.*sales/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ awards_shows: (sig) => /oscar|grammy|emmy|golden globe|academy award|best picture|best actor|awards.*ceremony/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ streaming_subs: (sig) => /netflix.*subscriber|disney.*subscriber|streaming.*war|subscriber.*count|streaming.*growth|hulu|paramount/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ social_trends: (sig) => /viral|tiktok|social media.*trend|influencer|twitter.*trend|internet.*culture|meme/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ reality_outcomes: (sig) => /reality tv|bachelor|survivor|big brother|reality.*show|dancing.*stars|masked singer/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+
+ // — Global & Geopolitics (96-100) —
+ global_conflicts: (sig) => /war\b|invasion|ceasefire|military.*conflict|armed conflict|escalation|airstrike|troops.*deploy/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ sanctions_policy: (sig) => /sanction|embargo|trade restriction|asset freeze|sanctions.*russia|sanctions.*china|sanctions.*iran/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ climate_extremes: (sig) => /climate.*extreme|extreme weather|heat.*record|cold.*record|flood|wildfire|hurricane.*category|tornado|drought/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ forex_events: (sig) => /forex|currency.*crisis|dollar.*index|yen|euro.*dollar|fx.*rate|currency.*devaluation|exchange rate/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+ geopolitical_shock: (sig) => /black swan|geopolitical.*shock|coup|assassination|regime.*change|emergency.*declaration|martial law|unexpected.*event/i.test((sig.market_id || '') + ' ' + (sig.market_title || '') + ' ' + (sig.reasoning || '')),
+};
+
+// Position sizing per strategy — differentiated risk profiles
+const PORTFOLIO_SIZING = {
+ aggressive: (edge, conf) => Math.max(2, Math.min(5, Math.round(Math.abs(edge) * 30))), // 2-5 contracts, edge-weighted
+ conservative: (edge, conf) => Math.max(1, Math.min(3, Math.round(conf * 4))), // 1-3 contracts, confidence-weighted
+ weather: (edge, conf) => 2, // Fixed 2 contracts
+ momentum: (edge, conf) => Math.max(1, Math.min(4, Math.round((conf + Math.abs(edge)) * 5))),// 1-4, blended
+ contrarian: (edge, conf) => 1, // Always 1 contract (high risk)
+ ai_enhanced: (edge, conf) => Math.max(1, Math.min(3, Math.round(conf * 3))), // 1-3, conservative
+ mc_validated: (edge, conf) => Math.max(2, Math.min(4, Math.round(conf * 5))), // 2-4, confidence-driven
+ scalper: (edge, conf) => 1, // Always 1 (high volume, small bets)
+ patient: (edge, conf) => Math.max(3, Math.min(5, Math.round(conf * 6))), // 3-5, big when confident
+ random: (edge, conf) => Math.max(1, Math.min(3, Math.ceil(Math.random() * 3))), // 1-3 random
+
+ // ═══ RISKY SIZING: Micro → Macro ═══
+ penny_pincher: () => 1, // Always 1 — micro
+ spray_pray: () => Math.ceil(Math.random() * 2), // 1-2 random
+ nickel_slots: () => 1, // Fixed 1
+ degen_lite: (edge) => Math.max(1, Math.min(3, Math.round(Math.abs(edge) * 20))), // 1-3, edge-scaled
+ politics_junkie: (edge, conf) => Math.max(2, Math.min(3, Math.round(conf * 4))), // 2-3, confidence
+ double_down: (edge) => Math.max(4, Math.min(8, Math.round(Math.abs(edge) * 30))), // 4-8, big edge bets
+ volatility_rider: (edge) => Math.max(2, Math.min(4, Math.round(Math.abs(edge) * 25))), // 2-4, edge-weighted
+ whale: (edge, conf) => Math.max(5, Math.min(10, Math.round(conf * 12))), // 5-10, confidence-heavy
+ yolo: (edge) => Math.max(8, Math.min(15, Math.round(Math.abs(edge) * 40))), // 8-15, MAX edge scale
+ full_send: (edge, conf) => Math.max(1, Math.min(25, Math.round(Math.abs(edge) * conf * 50))),// 1-25, edge*conf scaled
+
+ // ═══ CPU-POWERED SIZING: Computational approaches ═══
+ kelly_criterion: (edge, conf) => Math.max(1, Math.min(8, Math.round((edge / (1 + edge)) * 20))), // Kelly fraction scaled to 1-8
+ sharpe_sniper: (edge, conf) => Math.max(2, Math.min(6, Math.round(conf * 8))), // 2-6, conf-weighted (high SNR = trust it)
+ bayesian_blend: (edge, conf) => Math.max(1, Math.min(5, Math.round(Math.sqrt(edge * conf) * 15))), // 1-5, geometric scaling
+ ensemble_lock: (edge, conf) => Math.max(3, Math.min(7, Math.round((edge + conf) * 5))), // 3-7, sum-scaled (all factors aligned)
+ mean_revert: (edge, conf) => Math.max(1, Math.min(4, Math.round(edge * 15))), // 1-4, moderate sizing for reversion plays
+ info_ratio: (edge, conf) => Math.max(2, Math.min(5, Math.round(conf * 6))), // 2-5, confidence-driven
+ anti_fomo: (edge, conf) => Math.max(2, Math.min(4, Math.round(conf * 5))), // 2-4, steady sizing for calm plays
+ nightcrawler: (edge, conf) => Math.max(1, Math.min(3, Math.round(conf * 4))), // 1-3, conservative shorts
+ heatseeker: (edge, conf) => Math.max(2, Math.min(6, Math.round((edge * 20 + conf * 3) / 2))), // 2-6, composite score-driven
+ quant_core: (edge, conf) => Math.max(2, Math.min(8, Math.round(Math.sqrt(edge * conf) * 25))), // 2-8, geometric mean heavy
+
+ // ═══ ETF CATEGORY SIZING ═══
+ etf_presidential: (edge, conf) => Math.max(1, Math.min(4, Math.round(conf * 5))),
+ etf_cabinet: (edge, conf) => Math.max(1, Math.min(3, Math.round(conf * 4))),
+ etf_congress: (edge, conf) => Math.max(1, Math.min(3, Math.round(conf * 4))),
+ etf_scotus: (edge, conf) => Math.max(1, Math.min(3, Math.round(conf * 3))),
+ etf_fed: (edge, conf) => Math.max(2, Math.min(5, Math.round(edge * 20 + conf * 2))),
+ etf_economy: (edge, conf) => Math.max(1, Math.min(4, Math.round(edge * 15))),
+ etf_geopolitics: (edge, conf) => Math.max(1, Math.min(3, Math.round(conf * 4))),
+ etf_territory: (edge, conf) => Math.max(1, Math.min(3, Math.round(conf * 3))),
+ etf_climate: () => 2,
+ etf_energy: (edge, conf) => Math.max(1, Math.min(4, Math.round(edge * 18))),
+ etf_tech: (edge, conf) => Math.max(2, Math.min(5, Math.round(conf * 6))),
+ etf_space: (edge, conf) => Math.max(1, Math.min(3, Math.round(conf * 3))),
+ etf_crypto: (edge, conf) => Math.max(1, Math.min(4, Math.round(edge * 20))),
+ etf_sports: (edge, conf) => Math.max(1, Math.min(3, Math.round(conf * 4))),
+ etf_entertainment: (edge, conf) => Math.max(1, Math.min(2, Math.round(conf * 3))),
+ etf_legal: (edge, conf) => Math.max(1, Math.min(3, Math.round(conf * 4))),
+ etf_financials: (edge, conf) => Math.max(2, Math.min(5, Math.round(conf * 6))),
+ etf_govreform: (edge, conf) => Math.max(1, Math.min(3, Math.round(conf * 3))),
+ etf_global_social: (edge, conf) => Math.max(1, Math.min(2, Math.round(conf * 2))),
+ etf_broad_market: (edge, conf) => Math.max(2, Math.min(6, Math.round(edge * 15 + conf * 3))),
+
+ // ═══ SECTOR-BASED SIZING (IDs 51-100): Conservative niche bets ═══
+
+ // — Energy & Commodities (51-55) — Moderate sizing, energy can be volatile
+ lng_exports: (edge, conf) => Math.max(1, Math.min(3, Math.round(conf * 4))),
+ oil_price_band: (edge, conf) => Math.max(1, Math.min(4, Math.round(edge * 15))),
+ natgas_seasonal: (edge, conf) => Math.max(1, Math.min(3, Math.round(conf * 3))),
+ opec_decisions: (edge, conf) => Math.max(1, Math.min(3, Math.round(edge * 12))),
+ power_grid: (edge, conf) => Math.max(1, Math.min(2, Math.round(conf * 3))),
+
+ // — AI & Tech Stocks (56-60) — Slightly larger, higher conviction sector
+ semiconductor: (edge, conf) => Math.max(1, Math.min(4, Math.round(conf * 5))),
+ ai_regulation: (edge, conf) => Math.max(1, Math.min(3, Math.round(conf * 4))),
+ tech_earnings: (edge, conf) => Math.max(2, Math.min(5, Math.round(edge * 18))),
+ autonomous_vehicles: (edge, conf) => Math.max(1, Math.min(3, Math.round(conf * 3))),
+ cloud_market: (edge, conf) => Math.max(1, Math.min(3, Math.round(conf * 4))),
+
+ // — Crypto & Digital (61-65) — Volatile, keep positions smaller
+ btc_price_bands: (edge, conf) => Math.max(1, Math.min(4, Math.round(edge * 16))),
+ eth_upgrades: (edge, conf) => Math.max(1, Math.min(3, Math.round(conf * 3))),
+ crypto_regulation: (edge, conf) => Math.max(1, Math.min(3, Math.round(conf * 4))),
+ stablecoin_policy: (edge, conf) => Math.max(1, Math.min(2, Math.round(conf * 3))),
+ defi_events: (edge, conf) => Math.max(1, Math.min(2, Math.round(edge * 10))),
+
+ // — Macro Economics (66-70) — Data-driven, moderate confidence sizing
+ cpi_monthly: (edge, conf) => Math.max(1, Math.min(4, Math.round(conf * 5))),
+ nfp_monthly: (edge, conf) => Math.max(1, Math.min(4, Math.round(conf * 5))),
+ housing_data: (edge, conf) => Math.max(1, Math.min(3, Math.round(conf * 4))),
+ gdp_quarterly: (edge, conf) => Math.max(1, Math.min(4, Math.round(edge * 15))),
+ yield_spread: (edge, conf) => Math.max(1, Math.min(3, Math.round(conf * 4))),
+
+ // — Finance & Markets (71-75) — Established signals, moderate-to-large
+ sp500_levels: (edge, conf) => Math.max(2, Math.min(5, Math.round(edge * 20))),
+ fed_rate_path: (edge, conf) => Math.max(2, Math.min(5, Math.round(conf * 6))),
+ bank_stress: (edge, conf) => Math.max(1, Math.min(3, Math.round(edge * 12))),
+ bond_yields: (edge, conf) => Math.max(1, Math.min(4, Math.round(conf * 5))),
+ volatility_index: (edge, conf) => Math.max(1, Math.min(4, Math.round(edge * 18))),
+
+ // — Politics & Policy (76-80) — Binary outcomes, confidence-weighted
+ state_elections: (edge, conf) => Math.max(1, Math.min(3, Math.round(conf * 4))),
+ congress_votes: (edge, conf) => Math.max(1, Math.min(3, Math.round(conf * 4))),
+ tariff_policy: (edge, conf) => Math.max(1, Math.min(3, Math.round(edge * 12))),
+ immigration_policy: (edge, conf) => Math.max(1, Math.min(2, Math.round(conf * 3))),
+ tax_legislation: (edge, conf) => Math.max(1, Math.min(3, Math.round(conf * 3))),
+
+ // — Sports (81-85) — Event-driven, fixed small sizing
+ nba_outcomes: (edge, conf) => Math.max(1, Math.min(3, Math.round(conf * 4))),
+ nfl_outcomes: (edge, conf) => Math.max(1, Math.min(3, Math.round(conf * 4))),
+ soccer_global: (edge, conf) => Math.max(1, Math.min(2, Math.round(conf * 3))),
+ mlb_outcomes: (edge, conf) => Math.max(1, Math.min(3, Math.round(conf * 3))),
+ combat_sports: (edge, conf) => Math.max(1, Math.min(2, Math.round(conf * 3))),
+
+ // — Health & Science (86-90) — High-impact but rare, small positions
+ fda_approvals: (edge, conf) => Math.max(1, Math.min(3, Math.round(conf * 4))),
+ disease_tracking: (edge, conf) => Math.max(1, Math.min(3, Math.round(edge * 12))),
+ biotech_catalysts: (edge, conf) => Math.max(1, Math.min(3, Math.round(edge * 10))),
+ health_metrics: (edge, conf) => Math.max(1, Math.min(2, Math.round(conf * 2))),
+ space_milestones: (edge, conf) => Math.max(1, Math.min(2, Math.round(conf * 3))),
+
+ // — Media & Culture (91-95) — Fun bets, keep small
+ box_office: (edge, conf) => Math.max(1, Math.min(2, Math.round(conf * 3))),
+ awards_shows: (edge, conf) => Math.max(1, Math.min(2, Math.round(conf * 3))),
+ streaming_subs: (edge, conf) => Math.max(1, Math.min(2, Math.round(conf * 2))),
+ social_trends: (edge, conf) => Math.max(1, Math.min(2, Math.round(edge * 8))),
+ reality_outcomes: (edge, conf) => Math.max(1, Math.min(2, Math.round(conf * 2))),
+
+ // — Global & Geopolitics (96-100) — High uncertainty, conservative
+ global_conflicts: (edge, conf) => Math.max(1, Math.min(3, Math.round(edge * 12))),
+ sanctions_policy: (edge, conf) => Math.max(1, Math.min(2, Math.round(conf * 3))),
+ climate_extremes: (edge, conf) => Math.max(1, Math.min(3, Math.round(edge * 10))),
+ forex_events: (edge, conf) => Math.max(1, Math.min(3, Math.round(conf * 4))),
+ geopolitical_shock: (edge, conf) => Math.max(1, Math.min(2, Math.round(edge * 8))),
+};
+
+let tradeCounter = 0; // For wildcard portfolio
+
+async function autoPortfolioTrade(signal) {
+ try {
+ const { rows: portfolios } = await kenQ('SELECT * FROM ken_portfolios');
+ const today = new Date().toISOString().split('T')[0];
+
+ for (const pf of portfolios) {
+ const strategy = PORTFOLIO_STRATEGIES[pf.strategy];
+ if (!strategy) continue;
+
+ // Check balance: bankrupt portfolios can't trade (balance = 0 → move to bottom)
+ if (pf.balance_cents <= 0) continue; // BANKRUPT — no more trades
+
+ // Check if strategy accepts this signal
+ const sigData = {
+ edge: signal.expectedEdge || signal.expected_edge || 0,
+ confidence: signal.confidence || 0,
+ direction: signal.direction,
+ reasoning: signal.reasoning || '',
+ signal_type: signal.signal_type || '',
+ market_id: signal.marketId || signal.market_id || '',
+ ai_enhanced: signal.aiEnhanced || signal.ai_enhanced || false,
+ mc_consistent: signal.mcSimulation?.consistent || signal.mc_consistent || false,
+ mc_stddev: signal.mcSimulation?.stdDev || 0.99,
+ volume24h: signal.volume24h || signal.volume_24h || 0,
+ num_articles: signal.num_articles || 0,
+ agreement: signal.agreement || 0,
+ market_title: signal.market_title || signal.marketTitle || '',
+ };
+
+ if (!strategy(sigData)) continue;
+
+ // Hyper-trade: max 10 OPEN positions per market per portfolio (no daily cap)
+ const { rows: dupes } = await kenQ(`
+ SELECT id FROM ken_portfolio_trades
+ WHERE portfolio_id = $1 AND market_id = $2 AND status = 'open'
+ `, [pf.id, signal.marketId || signal.market_id]);
+ if (dupes.length >= 10) continue;
+
+ // Per-strategy position sizing
+ const absEdge = Math.abs(parseFloat(sigData.edge));
+ const conf = parseFloat(sigData.confidence);
+ const sizeFn = PORTFOLIO_SIZING[pf.strategy] || ((e, c) => Math.max(1, Math.min(3, Math.round(e * c * 15))));
+ const contracts = sizeFn(absEdge, conf);
+ const entryPrice = sigData.direction === 'BUY_YES'
+ ? Math.round((0.5 - absEdge / 2) * 100) // rough market mid
+ : Math.round((0.5 + absEdge / 2) * 100);
+ const clampedPrice = Math.max(5, Math.min(95, entryPrice));
+ const cost = clampedPrice * contracts;
+
+ if (cost > pf.balance_cents) continue; // Not enough balance for this trade
+
+ await kenQ(`
+ INSERT INTO ken_portfolio_trades (portfolio_id, signal_id, market_id, market_title, direction, entry_price_cents, contracts, cost_cents, reasoning, confidence, ai_enhanced, mc_consistent)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)
+ `, [pf.id, signal.id || null, signal.marketId || signal.market_id, signal.market_title || signal.marketTitle || '',
+ sigData.direction, clampedPrice, contracts, cost, (sigData.reasoning || '').substring(0, 500),
+ conf, sigData.ai_enhanced, sigData.mc_consistent]);
+
+ // Deduct from balance + update stats
+ await kenQ(`UPDATE ken_portfolios SET balance_cents = balance_cents - $1, total_invested_cents = total_invested_cents + $1, last_trade_at = NOW() WHERE id = $2`, [cost, pf.id]);
+ pf.balance_cents -= cost; // Update in-memory too for subsequent iterations
+
+ console.log(`[Ken/Portfolio] ${pf.name} (${pf.strategy}): ${sigData.direction} ${(signal.marketId || signal.market_id || '').substring(0, 30)} @ ${clampedPrice}¢ x${contracts} = $${(cost/100).toFixed(2)}`);
+ }
+ } catch (e) {
+ console.error('[Ken/Portfolio] Auto-trade error:', e.message);
+ }
+}
+
+// Capture NAV snapshots for charting — runs every 30 minutes
+async function capturePortfolioSnapshots() {
+ try {
+ const { rows: portfolios } = await kenQ('SELECT * FROM ken_portfolios');
+ for (const pf of portfolios) {
+ const { rows: openTrades } = await kenQ(`
+ SELECT entry_price_cents, contracts, direction, market_id
+ FROM ken_portfolio_trades WHERE portfolio_id = $1 AND status = 'open'
+ `, [pf.id]);
+
+ let openValue = 0;
+ for (const t of openTrades) {
+ const { rows: snaps } = await kenQ(`
+ SELECT last_price FROM ken_market_snapshots WHERE ticker = $1 ORDER BY captured_at DESC LIMIT 1
+ `, [t.market_id]);
+ if (snaps.length > 0) {
+ const curr = parseInt(snaps[0].last_price);
+ openValue += t.direction === 'BUY_YES'
+ ? (curr - t.entry_price_cents) * t.contracts
+ : (t.entry_price_cents - curr) * t.contracts;
+ }
+ }
+
+ const nav = (parseInt(pf.total_returned_cents) || 0) - (parseInt(pf.total_invested_cents) || 0) + openValue;
+ await kenQ(`
+ INSERT INTO ken_portfolio_snapshots (portfolio_id, nav_cents, open_positions) VALUES ($1, $2, $3)
+ `, [pf.id, nav, openTrades.length]);
+ }
+ console.log(`[Ken/Charts] NAV snapshots captured for ${portfolios.length} portfolios`);
+ } catch (e) {
+ console.error('[Ken/Charts] Snapshot error:', e.message);
+ }
+}
+
+// Resolve portfolio trades — HYPER MODE: quick take-profit/stop-loss + aging out
+async function resolvePortfolioTrades() {
+ try {
+ // Check ALL open trades (no minimum age for hyper-trading)
+ const { rows: openTrades } = await kenQ(`
+ SELECT pt.*, p.name as portfolio_name, p.strategy as portfolio_strategy
+ FROM ken_portfolio_trades pt
+ JOIN ken_portfolios p ON p.id = pt.portfolio_id
+ WHERE pt.status = 'open'
+ ORDER BY pt.created_at ASC
+ LIMIT 500
+ `);
+
+ for (const trade of openTrades) {
+ // Get latest price from snapshots
+ const { rows: snaps } = await kenQ(`
+ SELECT last_price FROM ken_market_snapshots
+ WHERE ticker = $1 ORDER BY captured_at DESC LIMIT 1
+ `, [trade.market_id]);
+
+ if (snaps.length === 0) continue;
+ const currentPrice = parseInt(snaps[0].last_price);
+ const ageMinutes = (Date.now() - new Date(trade.created_at).getTime()) / 60000;
+
+ let pnl = 0;
+ if (trade.direction === 'BUY_YES') {
+ pnl = (currentPrice - trade.entry_price_cents) * trade.contracts;
+ } else {
+ pnl = (trade.entry_price_cents - currentPrice) * trade.contracts;
+ }
+
+ // Hyper-trade exit rules:
+ // 1. Take profit: +3¢ per contract (minimum 5 min hold)
+ // 2. Stop loss: -5¢ per contract (minimum 5 min hold)
+ // 3. Age out: close after 2 hours regardless
+ let status = null;
+ const profitPerContract = pnl / Math.max(1, trade.contracts);
+
+ if (ageMinutes >= 5 && profitPerContract >= 3) {
+ status = 'won'; // Take profit
+ } else if (ageMinutes >= 5 && profitPerContract <= -5) {
+ status = 'lost'; // Stop loss
+ } else if (ageMinutes >= 120) {
+ // Age out after 2 hours — mark based on current P&L
+ status = pnl > 0 ? 'won' : pnl < 0 ? 'lost' : 'expired';
+ }
+
+ if (!status) continue; // Hold position
+
+ await kenQ(`
+ UPDATE ken_portfolio_trades SET status = $1, exit_price_cents = $2, pnl_cents = $3, resolved_at = NOW()
+ WHERE id = $4
+ `, [status, currentPrice, pnl, trade.id]);
+
+ // Update portfolio running totals
+ const streakVal = status === 'won' ? 1 : status === 'lost' ? -1 : 0;
+ // total_returned = cost_cents + pnl for winning trades (you get your money back + profit)
+ const returned = pnl > 0 ? trade.cost_cents + pnl : (pnl === 0 ? trade.cost_cents : 0);
+ const wonInc = status === 'won' ? 1 : 0;
+ const lostInc = status === 'lost' ? 1 : 0;
+ const expInc = status === 'expired' ? 1 : 0;
+ await kenQ(`
+ UPDATE ken_portfolios SET
+ balance_cents = balance_cents + $1,
+ total_returned_cents = total_returned_cents + $1,
+ trades_won = trades_won + $2,
+ trades_lost = trades_lost + $3,
+ trades_expired = trades_expired + $4,
+ streak = CASE WHEN $5 > 0 AND streak > 0 THEN streak + 1 WHEN $5 < 0 AND streak < 0 THEN streak - 1 ELSE $5 END,
+ best_trade_cents = GREATEST(best_trade_cents, $6),
+ worst_trade_cents = LEAST(worst_trade_cents, $6)
+ WHERE id = $7
+ `, [returned, wonInc, lostInc, expInc, streakVal, pnl, trade.portfolio_id]);
+
+ // Update daily P&L
+ const tradeDate = new Date(trade.created_at).toISOString().split('T')[0];
+ await kenQ(`
+ INSERT INTO ken_daily_pnl (portfolio_id, date, closed_trades, wins, losses, daily_pnl_cents, cumulative_pnl_cents)
+ VALUES ($1, $2, 1, $3, $4, $5, $5)
+ ON CONFLICT (portfolio_id, date) DO UPDATE SET
+ closed_trades = ken_daily_pnl.closed_trades + 1,
+ wins = ken_daily_pnl.wins + $3,
+ losses = ken_daily_pnl.losses + $4,
+ daily_pnl_cents = ken_daily_pnl.daily_pnl_cents + $5
+ `, [trade.portfolio_id, tradeDate, status === 'won' ? 1 : 0, status === 'lost' ? 1 : 0, pnl]);
+
+ // Update learning table
+ const category = extractSignalCategory(trade.reasoning || '');
+ await kenQ(`
+ INSERT INTO ken_learning (category, signal_type, win_rate, avg_pnl_cents, total_trades, last_updated)
+ VALUES ($1, $2, $3, $4, 1, NOW())
+ ON CONFLICT DO NOTHING
+ `, [category, trade.direction, status === 'won' ? 1 : 0, pnl]);
+ }
+
+ if (openTrades.length > 0) console.log(`[Ken/Portfolio] Resolved ${openTrades.length} trades across portfolios`);
+ } catch (e) {
+ console.error('[Ken/Portfolio] Resolution error:', e.message);
+ }
+}
+
+function extractSignalCategory(reasoning) {
+ const r = reasoning.toLowerCase();
+ if (/heating|gas bill|utility bill|electric bill|energy cost|propane|furnace|hvac/.test(r)) return 'heating_energy';
+ if (/weather|temp|rain|snow|wind|hurricane|polar vortex|cold snap|freeze|frost/.test(r)) return 'weather';
+ if (/crypto|bitcoin|btc|eth/.test(r)) return 'crypto';
+ if (/politic|elect|congress|senate|trump|biden/.test(r)) return 'politics';
+ if (/econom|rate|inflation|fed|gdp|job/.test(r)) return 'economics';
+ if (/momentum|volume|spike|spread/.test(r)) return 'momentum';
+ if (/sport|game|nfl|nba|mlb/.test(r)) return 'sports';
+ if (/lng|natural gas|oil|commodity|corn|wheat|soy|cattle|crop/.test(r)) return 'commodities';
+ return 'general';
+}
+
+// ══════════════════════════════════════════════
+// LNG & AGRICULTURAL COMMODITY INTELLIGENCE
+// ══════════════════════════════════════════════
+const COMMODITY_FEEDS = [
+ // ── LNG & Natural Gas (Government) ──
+ { url: 'https://www.eia.gov/rss/naturalgas_rss.xml', source: 'EIA Natural Gas', category: 'lng' },
+ { url: 'https://www.eia.gov/rss/petroleum_rss.xml', source: 'EIA Petroleum', category: 'oil' },
+ { url: 'https://www.eia.gov/rss/todayinenergy_rss.xml', source: 'EIA Today in Energy', category: 'energy' },
+ { url: 'https://www.eia.gov/rss/electricity_rss.xml', source: 'EIA Electricity', category: 'electricity' },
+ // ── Agriculture (Government) ──
+ { url: 'https://www.usda.gov/rss/home.xml', source: 'USDA', category: 'agriculture' },
+ { url: 'https://www.nass.usda.gov/rss/index.php', source: 'USDA NASS', category: 'agriculture' },
+ // ── NOAA Weather (Government) ──
+ { url: 'https://alerts.weather.gov/cap/us.php?x=0', source: 'NWS National Alerts', category: 'weather' },
+ { url: 'https://www.weather.gov/rss_page.php?site_name=nws', source: 'NWS News', category: 'weather' },
+ { url: 'https://www.cpc.ncep.noaa.gov/products/stratosphere/strat-trop/rss.xml', source: 'NOAA CPC', category: 'weather' },
+ // ── FERC & Energy Regulation (Government) ──
+ { url: 'https://www.ferc.gov/rss/news-releases.xml', source: 'FERC News', category: 'energy_regulation' },
+ // ── Weather Risk ──
+ { url: 'https://rfrx.rfrz.io/weatherrisk', source: 'Weather Risk', category: 'weather_commodity' },
+];
+
+// Government Open APIs for Energy & Weather Data
+const GOV_API_ENDPOINTS = {
+ // EIA Open Data API (no key needed for RSS, key for JSON)
+ eia_ng_spot: 'https://api.eia.gov/v2/natural-gas/pri/fut/data/?frequency=daily&data[0]=value&sort[0][column]=period&sort[0][direction]=desc&length=5&api_key=',
+ eia_elec_price: 'https://api.eia.gov/v2/electricity/retail-sales/data/?frequency=monthly&data[0]=price&sort[0][column]=period&sort[0][direction]=desc&length=10&api_key=',
+ // NOAA Weather API (free, no key)
+ noaa_alerts: 'https://api.weather.gov/alerts/active?status=actual&message_type=alert',
+ noaa_forecast_nyc: 'https://api.weather.gov/gridpoints/OKX/33,37/forecast',
+ noaa_forecast_chi: 'https://api.weather.gov/gridpoints/LOT/75,72/forecast',
+ noaa_forecast_dal: 'https://api.weather.gov/gridpoints/FWD/87,108/forecast',
+ noaa_forecast_den: 'https://api.weather.gov/gridpoints/BOU/62,60/forecast',
+ noaa_forecast_msp: 'https://api.weather.gov/gridpoints/MPX/107,71/forecast',
+ // FRED Economic Data (key needed but some RSS free)
+ fred_natgas: 'https://fred.stlouisfed.org/graph/fredgraph.csv?id=DHHNGSP',
+};
+
+// Fetch NOAA weather alerts for extreme cold/heat events
+async function fetchNOAAWeatherIntel() {
+ let found = 0;
+ try {
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), 10000);
+ const res = await fetch(GOV_API_ENDPOINTS.noaa_alerts, {
+ signal: controller.signal,
+ headers: { 'User-Agent': 'KenInc/1.0 Weather Intelligence', Accept: 'application/geo+json' },
+ });
+ clearTimeout(timeout);
+ if (!res.ok) return found;
+ const data = await res.json();
+
+ const heatingKeywords = /cold|freeze|frost|ice|blizzard|winter storm|wind chill|extreme cold|heating|arctic|polar vortex|below zero|record low|dangerous cold/i;
+ const energyKeywords = /power outage|grid|electricity|utility|energy emergency|rolling blackout|brownout|load shed/i;
+
+ for (const feature of (data.features || []).slice(0, 50)) {
+ const props = feature.properties || {};
+ const headline = props.headline || props.event || '';
+ const desc = props.description || '';
+ const combined = headline + ' ' + desc;
+
+ if (heatingKeywords.test(combined) || energyKeywords.test(combined)) {
+ const areas = (props.areaDesc || '').substring(0, 200);
+ const severity = props.severity || 'Unknown';
+ const certainty = props.certainty || 'Unknown';
+
+ await kenQ(`
+ INSERT INTO ken_sentiment (source, subreddit, keyword, post_title, post_url, score, num_comments, sentiment_score, raw_text)
+ VALUES ('noaa_alert', $1, 'weather_energy', $2, $3, $4, 0, $5, $6)
+ ON CONFLICT DO NOTHING
+ `, [
+ areas,
+ headline.substring(0, 500),
+ props.id || `noaa-${Date.now()}`,
+ severity === 'Extreme' ? 100 : severity === 'Severe' ? 80 : severity === 'Moderate' ? 50 : 20,
+ severity === 'Extreme' ? -0.9 : severity === 'Severe' ? -0.7 : -0.4,
+ `[${severity}/${certainty}] ${areas}: ${desc.substring(0, 400)}`
+ ]);
+ found++;
+ }
+ }
+ } catch (e) {
+ // NOAA API can be slow, don't log every failure
+ }
+
+ // Fetch regional forecasts for major metro areas (heating demand proxy)
+ const metros = [
+ { name: 'NYC', url: GOV_API_ENDPOINTS.noaa_forecast_nyc },
+ { name: 'Chicago', url: GOV_API_ENDPOINTS.noaa_forecast_chi },
+ { name: 'Dallas', url: GOV_API_ENDPOINTS.noaa_forecast_dal },
+ { name: 'Denver', url: GOV_API_ENDPOINTS.noaa_forecast_den },
+ { name: 'Minneapolis', url: GOV_API_ENDPOINTS.noaa_forecast_msp },
+ ];
+
+ for (const metro of metros) {
+ try {
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), 8000);
+ const res = await fetch(metro.url, {
+ signal: controller.signal,
+ headers: { 'User-Agent': 'KenInc/1.0', Accept: 'application/geo+json' },
+ });
+ clearTimeout(timeout);
+ if (!res.ok) continue;
+ const data = await res.json();
+
+ for (const period of (data.properties?.periods || []).slice(0, 4)) {
+ const tempF = period.temperature;
+ const wind = period.windSpeed || '';
+ const forecast = period.detailedForecast || period.shortForecast || '';
+
+ // Flag extreme cold (below 20F) or heat waves (above 100F) — heating demand signals
+ if (tempF <= 20 || tempF >= 100) {
+ await kenQ(`
+ INSERT INTO ken_sentiment (source, subreddit, keyword, post_title, post_url, score, num_comments, sentiment_score, raw_text)
+ VALUES ('noaa_forecast', $1, 'extreme_temp', $2, $3, $4, 0, $5, $6)
+ ON CONFLICT DO NOTHING
+ `, [
+ metro.name,
+ `${metro.name}: ${tempF}°F ${period.name} — ${period.shortForecast}`,
+ `noaa-forecast-${metro.name}-${period.number}-${new Date().toISOString().split('T')[0]}`,
+ Math.abs(tempF <= 20 ? (20 - tempF) * 5 : (tempF - 100) * 5),
+ tempF <= 20 ? -0.8 : -0.6,
+ `${metro.name} ${period.name}: ${tempF}°F, Wind ${wind}. ${forecast.substring(0, 300)}`
+ ]);
+ found++;
+ }
+ }
+ await new Promise(r => setTimeout(r, 500));
+ } catch (e) { /* NOAA timeout */ }
+ }
+
+ if (found > 0) console.log(`[Ken/NOAA] ${found} weather/energy alerts from government APIs`);
+ return found;
+}
+
+// Additional weather-impacted commodity keywords for market scanning
+const COMMODITY_KEYWORDS = [
+ 'natural gas', 'lng', 'henry hub', 'gas price', 'heating degree',
+ 'corn', 'wheat', 'soybeans', 'soybean', 'cotton', 'cattle', 'hogs',
+ 'crop', 'harvest', 'drought', 'frost', 'freeze', 'growing season',
+ 'el nino', 'la nina', 'commodity', 'futures', 'agriculture',
+ 'ethanol', 'fertilizer', 'grain', 'livestock', 'usda', 'crop report',
+];
+
+// ── HEATING BILL & ENERGY COST INTELLIGENCE ──
+const HEATING_KEYWORDS = [
+ 'heating bill', 'gas bill', 'electric bill', 'utility bill', 'energy bill',
+ 'heating cost', 'energy cost', 'propane', 'furnace', 'thermostat',
+ 'polar vortex', 'cold snap', 'wind chill', 'below zero', 'record cold',
+ 'heating oil', 'natural gas price', 'electricity price', 'rate hike',
+ 'winter storm', 'power outage', 'grid strain', 'rolling blackout',
+ 'hvac', 'insulation', 'heat pump', 'space heater', 'energy assistance',
+];
+
+const HEATING_SUBS = [
+ 'personalfinance', 'Frugal', 'povertyfinance', 'homeowners',
+ 'HVAC', 'energy', 'NaturalGas', 'HomeImprovement', 'utilities',
+ 'weather', 'climate', 'TropicalWeather', 'preppers',
+];
+
+async function fetchHeatingBillIntel() {
+ let found = 0;
+ const heatingRegex = new RegExp(HEATING_KEYWORDS.join('|'), 'i');
+
+ for (let i = 0; i < HEATING_SUBS.length; i += 3) {
+ const batch = HEATING_SUBS.slice(i, i + 3);
+ const results = await Promise.allSettled(batch.map(sub => scrapeSubredditHot(sub, 15)));
+ for (let j = 0; j < results.length; j++) {
+ if (results[j].status !== 'fulfilled') continue;
+ const sub = batch[j];
+ for (const post of results[j].value) {
+ const text = (post.title + ' ' + (post.selftext || '')).toLowerCase();
+ if (heatingRegex.test(text) && post.score > 10) {
+ const sentiment = scoreSentiment(post.title);
+ await kenQ(`
+ INSERT INTO ken_sentiment (source, subreddit, keyword, post_title, post_url, score, num_comments, sentiment_score, raw_text)
+ VALUES ('heating_intel', $1, 'heating', $2, $3, $4, $5, $6, $7)
+ ON CONFLICT DO NOTHING
+ `, [sub, post.title, post.url, post.score, post.num_comments, sentiment, text.substring(0, 500)]);
+ found++;
+ }
+ }
+ }
+ await new Promise(r => setTimeout(r, 2000));
+ }
+
+ if (found > 0) console.log(`[Ken/Heating] Found ${found} heating bill/energy cost discussions`);
+ return found;
+}
+
+async function fetchCommodityIntel() {
+ let total = 0;
+ for (const feed of COMMODITY_FEEDS) {
+ try {
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), 8000);
+ const res = await fetch(feed.url, {
+ signal: controller.signal,
+ headers: { 'User-Agent': 'KenInc/1.0 Commodity Intelligence' },
+ });
+ clearTimeout(timeout);
+ if (!res.ok) continue;
+ const text = await res.text();
+
+ // Extract items from RSS
+ const items = text.match(/<item>[\s\S]*?<\/item>/gi) || [];
+ for (const item of items.slice(0, 15)) {
+ const title = (item.match(/<title><!\[CDATA\[(.*?)\]\]>|<title>(.*?)<\/title>/)?.[1] || item.match(/<title>(.*?)<\/title>/)?.[1] || '').trim();
+ const link = (item.match(/<link>(.*?)<\/link>/)?.[1] || '').trim();
+ if (!title) continue;
+
+ // Score commodity relevance
+ const score = scoreEventSentiment(title);
+
+ try {
+ await kenQ(`
+ INSERT INTO ken_sentiment (source, keyword, post_title, post_url, sentiment_score, captured_at)
+ VALUES ($1, $2, $3, $4, $5, NOW())
+ ON CONFLICT DO NOTHING
+ `, [feed.source, feed.category, title.substring(0, 500), link.substring(0, 500), score.sentiment || 0]);
+ total++;
+ } catch(e) {} // skip dupes
+ }
+ } catch(e) {}
+ }
+ if (total > 0) console.log(`[Ken/Commodities] ${total} articles from ${COMMODITY_FEEDS.length} commodity feeds`);
+ return total;
+}
+
+// ══════════════════════════════════════════════
+// PERFORMANCE TRACKER — resolve old predictions
+// ══════════════════════════════════════════════
+async function resolveOldPredictions() {
+ try {
+ // Get pending predictions older than 6 hours
+ const { rows } = await kenQ(`
+ SELECT id, ticker, side, entry_price FROM ken_predictions
+ WHERE outcome = 'pending' AND created_at < NOW() - INTERVAL '6 hours'
+ LIMIT 50
+ `);
+ for (const pred of rows) {
+ // Get latest snapshot for this ticker
+ const { rows: snaps } = await kenQ(`
+ SELECT last_price FROM ken_market_snapshots
+ WHERE ticker = $1 ORDER BY captured_at DESC LIMIT 1
+ `, [pred.ticker]);
+ if (snaps.length > 0) {
+ const currentPrice = snaps[0].last_price;
+ const entryPrice = pred.entry_price || 50;
+ let outcome = 'expired';
+ let pnl = 0;
+ if (pred.side === 'YES') {
+ pnl = currentPrice - entryPrice;
+ outcome = pnl > 0 ? 'win' : pnl < 0 ? 'loss' : 'expired';
+ } else {
+ pnl = entryPrice - currentPrice; // NO side profits when price drops
+ outcome = pnl > 0 ? 'win' : pnl < 0 ? 'loss' : 'expired';
+ }
+ await kenQ(`
+ UPDATE ken_predictions SET outcome = $1, exit_price = $2, pnl_cents = $3, resolved_at = NOW()
+ WHERE id = $4
+ `, [outcome, currentPrice, pnl, pred.id]);
+ }
+ }
+ if (rows.length > 0) console.log(`[Ken] Resolved ${rows.length} old predictions`);
+ } catch (e) {
+ console.error('[Ken] Prediction resolution error:', e.message);
+ }
+}
+
+// ══════════════════════════════════════════════
+// CLEANUP — prune old data (daily)
+// ══════════════════════════════════════════════
+async function cleanupOldData() {
+ try {
+ await kenQ(`DELETE FROM ken_market_snapshots WHERE captured_at < NOW() - INTERVAL '7 days'`);
+ await kenQ(`DELETE FROM ken_sentiment WHERE captured_at < NOW() - INTERVAL '14 days'`);
+ await kenQ(`DELETE FROM ken_performance WHERE scan_time < NOW() - INTERVAL '30 days'`);
+ await kenQ(`DELETE FROM ken_portfolio_snapshots WHERE snapshot_at < NOW() - INTERVAL '60 days'`);
+ console.log('[Ken] Old data cleaned up (including portfolio snapshots 60d retention)');
+ } catch (e) {
+ console.error('[Ken] Cleanup error:', e.message);
+ }
+}
+
+// ── Start Server ──
+server.listen(PORT, '0.0.0.0', () => {
+ console.log(`[Ken] Server running on http://0.0.0.0:${PORT}`);
+ console.log(`[Ken] Kalshi environment: ${KALSHI_ENV.toUpperCase()} (${KALSHI_BASE_URL})`);
+ console.log(`[Ken] Static files: ${DIST}`);
+ console.log(`[Ken] Auth: session cookie + IP whitelist + basic auth`);
+ console.log(`[Ken] ═══════════════════════════════════════`);
+ console.log(`[Ken] AUTONOMOUS MODE: 24/7 MARKET INTELLIGENCE`);
+ console.log(`[Ken] Market scan: every 8 minutes (CPU-boosted, was 15m)`);
+ console.log(`[Ken] Signal pipeline: every 2 minutes (MC simulation + Gemini AI enhanced)`);
+ console.log(`[Ken] Reddit/news: every 15 minutes (doubled, was 30m)`);
+ console.log(`[Ken] CPU cores: ${os.cpus().length} | MC iterations: 15,000 per signal`);
+ console.log(`[Ken] Gemini AI: ${GEMINI_MODEL} (daily budget: ${GEMINI_DAILY_LIMIT} calls)`);
+ console.log(`[Ken] Slack alerts: every 4 hours (high-conf bypass)`);
+ console.log(`[Ken] Data sources: Kalshi | Reddit (80+) | ${NEWS_FEEDS.length} news feeds | HN | GDELT TV | YouTube | Manifold | r/Kalshi | r/Polymarket | Lemmy | Lobsters | Tildes | Bluesky | Mastodon | Metaculus | Polymarket | PredictIt | FRED Economic | NWS Alerts | NOAA Forecasts | EIA Energy | FERC | GovTrack | USDA | Twitter/Nitter | Discord`);
+ console.log(`[Ken] Heating intel: ${HEATING_SUBS.length} subreddits | ${HEATING_KEYWORDS.length} keywords | NOAA 5 metro forecasts | EIA electricity/gas prices`);
+ console.log(`[Ken] ═══════════════════════════════════════`);
+
+ // Separate mutexes: sweep (heavy Reddit/news) and scan (light Kalshi API) can run concurrently
+ let sweepRunning = false;
+ let scanRunning = false;
+
+ async function runSweepSafe(name, fn) {
+ if (sweepRunning) { console.log(`[Ken] Skipping ${name} — another sweep in progress`); return; }
+ sweepRunning = true;
+ try { await fn(); } catch (e) { console.error(`[Ken] ${name} error:`, e.message); }
+ sweepRunning = false;
+ if (global.gc) global.gc();
+ }
+
+ async function runScanSafe(fn) {
+ if (scanRunning) { console.log('[Ken] Skipping Scan — another scan in progress'); return; }
+ scanRunning = true;
+ try { await fn(); } catch (e) { console.error(`[Ken] Scan error:`, e.message); }
+ scanRunning = false;
+ if (global.gc) global.gc();
+ }
+
+ // Load stored Kalshi env preference, trade config, and scan config from DB
+ refreshKalshiEnv().then(() => {
+ console.log(`[Ken] Kalshi environment: ${KALSHI_ENV.toUpperCase()} (${KALSHI_BASE_URL})`);
+ });
+ loadTradeConfig();
+ loadScanConfig();
+
+ // Initial: run reddit sweep and market scan (scan uses separate mutex, can overlap)
+ setTimeout(async () => {
+ runSweepSafe('Reddit init', redditIntelligenceLoop);
+ setTimeout(() => runScanSafe(autonomousScan), 10000);
+ }, 5000);
+
+ // Start all recurring intervals via stored handles (restartIntervals can update later)
+ scanIntervalId = setInterval(() => runScanSafe(autonomousScan), SCAN_INTERVAL_MS);
+ redditIntervalId = setInterval(() => runSweepSafe('Reddit', redditIntelligenceLoop), REDDIT_INTERVAL_MS);
+ signalIntervalId = setInterval(async () => {
+ if (cachedActiveMarkets.length > 0) {
+ try { await signalPipeline(cachedActiveMarkets); } catch (e) { console.log(`[Ken] Fast pipeline error: ${e.message}`); }
+ }
+ }, SIGNAL_PIPELINE_MS);
+
+ // Resolve old predictions every hour
+ setInterval(() => {
+ resolveOldPredictions().catch(e => console.error('[Ken] Resolution error:', e.message));
+ }, 60 * 60 * 1000);
+
+ // HYPER-TRADE: Resolve portfolio trades (interval stored in handle for UI control)
+ resolveIntervalId = setInterval(() => {
+ resolvePortfolioTrades().catch(e => console.error('[Ken] Portfolio resolution error:', e.message));
+ }, RESOLVE_INTERVAL_MS);
+ setTimeout(() => resolvePortfolioTrades().catch(() => {}), 30000);
+
+ // Portfolio NAV snapshots every 30 minutes for charting
+ setInterval(() => capturePortfolioSnapshots().catch(e => console.error('[Ken/Charts] Error:', e.message)), 30 * 60 * 1000);
+ setTimeout(() => capturePortfolioSnapshots().catch(() => {}), 25000); // Initial after startup
+
+ // Commodity + heating bill + NOAA intelligence every 20 minutes
+ setInterval(() => {
+ fetchCommodityIntel().catch(e => console.error('[Ken] Commodity error:', e.message));
+ fetchHeatingBillIntel().catch(e => console.error('[Ken] Heating intel error:', e.message));
+ fetchNOAAWeatherIntel().catch(e => console.error('[Ken] NOAA intel error:', e.message));
+ }, 20 * 60 * 1000);
+ // Initial commodity + heating + NOAA fetch
+ setTimeout(() => {
+ fetchCommodityIntel().catch(() => {});
+ fetchHeatingBillIntel().catch(() => {});
+ fetchNOAAWeatherIntel().catch(() => {});
+ }, 15000);
+
+ // Weekly portfolio auto-refill: $100/portfolio every Monday (4-week trial)
+ // Checks every hour, only refills on Mondays between 0:00-0:59 UTC
+ const WEEKLY_REFILL_CENTS = 10000; // $100
+ const REFILL_WEEKS_REMAINING_KEY = 'ken_refill_weeks';
+ setInterval(async () => {
+ try {
+ const now = new Date();
+ if (now.getUTCDay() !== 1 || now.getUTCHours() !== 0) return; // Monday 0:00 UTC only
+ // Check if we already refilled this week
+ const { rows: [config] } = await kenQ(
+ `SELECT value FROM ken_config WHERE key = 'last_refill_date'`
+ ).catch(() => ({ rows: [] }));
+ const today = now.toISOString().split('T')[0];
+ if (config && config.value === today) return; // Already refilled today
+ // Check weeks remaining
+ const { rows: [weeksRow] } = await kenQ(
+ `SELECT value FROM ken_config WHERE key = $1`, [REFILL_WEEKS_REMAINING_KEY]
+ ).catch(() => ({ rows: [] }));
+ const weeksLeft = weeksRow ? parseInt(weeksRow.value) : 4;
+ if (weeksLeft <= 0) { console.log('[Ken] Weekly refill: 0 weeks remaining, skipping'); return; }
+ // Refill all portfolios
+ const { rowCount } = await kenQ(
+ `UPDATE ken_portfolios SET balance_cents = balance_cents + $1`, [WEEKLY_REFILL_CENTS]
+ );
+ // Update tracking (value column is jsonb, so wrap in JSON.stringify)
+ await kenQ(`INSERT INTO ken_config (key, value) VALUES ('last_refill_date', $1::jsonb)
+ ON CONFLICT (key) DO UPDATE SET value = $1::jsonb, updated_at = NOW()`, [JSON.stringify(today)]);
+ await kenQ(`INSERT INTO ken_config (key, value) VALUES ($1, $2::jsonb)
+ ON CONFLICT (key) DO UPDATE SET value = $2::jsonb, updated_at = NOW()`, [REFILL_WEEKS_REMAINING_KEY, JSON.stringify(String(weeksLeft - 1))]);
+ console.log(`[Ken] Weekly refill: +$${WEEKLY_REFILL_CENTS/100} to ${rowCount} portfolios. ${weeksLeft - 1} weeks remaining.`);
+ } catch (e) { console.error('[Ken] Weekly refill error:', e.message); }
+ }, 60 * 60 * 1000); // Check every hour
+
+ // Cleanup old data every 24 hours
+ setInterval(() => {
+ cleanupOldData().catch(e => console.error('[Ken] Cleanup error:', e.message));
+ }, 24 * 60 * 60 * 1000);
+});
diff --git a/public/favicon.svg b/public/favicon.svg
new file mode 100644
index 0000000..65b4e06
--- /dev/null
+++ b/public/favicon.svg
@@ -0,0 +1,4 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32">
+<rect width="32" height="32" rx="6" fill="#10b981"/>
+<text x="50%" y="55%" text-anchor="middle" dominant-baseline="middle" font-size="20" font-family="Apple Color Emoji, Segoe UI Emoji, sans-serif" fill="white">B</text>
+</svg>
\ No newline at end of file
diff --git a/react-dash/dist/assets/index-X3aldCwL.css b/react-dash/dist/assets/index-X3aldCwL.css
deleted file mode 100644
index d7882ce..0000000
--- a/react-dash/dist/assets/index-X3aldCwL.css
+++ /dev/null
@@ -1 +0,0 @@
-*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji";font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}.absolute{position:absolute}.relative{position:relative}.inset-0{top:0;right:0;bottom:0;left:0}.-top-2{top:-.5rem}.left-0\.5{left:.125rem}.left-1{left:.25rem}.left-6{left:1.5rem}.right-0{right:0}.right-2{right:.5rem}.right-3{right:.75rem}.top-0\.5{top:.125rem}.top-1{top:.25rem}.top-1\/2{top:50%}.z-10{z-index:10}.mx-auto{margin-left:auto;margin-right:auto}.my-5{margin-top:1.25rem;margin-bottom:1.25rem}.mb-0\.5{margin-bottom:.125rem}.mb-1{margin-bottom:.25rem}.mb-1\.5{margin-bottom:.375rem}.mb-2{margin-bottom:.5rem}.mb-3{margin-bottom:.75rem}.mb-4{margin-bottom:1rem}.mb-5{margin-bottom:1.25rem}.mb-8{margin-bottom:2rem}.ml-auto{margin-left:auto}.mt-0\.5{margin-top:.125rem}.mt-1{margin-top:.25rem}.mt-2{margin-top:.5rem}.mt-3{margin-top:.75rem}.mt-4{margin-top:1rem}.mt-5{margin-top:1.25rem}.mt-6{margin-top:1.5rem}.block{display:block}.inline-block{display:inline-block}.flex{display:flex}.inline-flex{display:inline-flex}.table{display:table}.grid{display:grid}.h-1\.5{height:.375rem}.h-10{height:2.5rem}.h-12{height:3rem}.h-2{height:.5rem}.h-2\.5{height:.625rem}.h-20{height:5rem}.h-3{height:.75rem}.h-3\.5{height:.875rem}.h-32{height:8rem}.h-4{height:1rem}.h-5{height:1.25rem}.h-6{height:1.5rem}.h-64{height:16rem}.h-8{height:2rem}.max-h-48{max-height:12rem}.min-h-screen{min-height:100vh}.w-1\.5{width:.375rem}.w-10{width:2.5rem}.w-11{width:2.75rem}.w-12{width:3rem}.w-16{width:4rem}.w-2{width:.5rem}.w-2\.5{width:.625rem}.w-20{width:5rem}.w-24{width:6rem}.w-3{width:.75rem}.w-3\.5{width:.875rem}.w-4{width:1rem}.w-5{width:1.25rem}.w-56{width:14rem}.w-6{width:1.5rem}.w-8{width:2rem}.w-full{width:100%}.min-w-0{min-width:0px}.max-w-2xl{max-width:42rem}.max-w-3xl{max-width:48rem}.max-w-\[140px\]{max-width:140px}.max-w-\[1600px\]{max-width:1600px}.max-w-\[180px\]{max-width:180px}.max-w-\[200px\]{max-width:200px}.max-w-\[300px\]{max-width:300px}.max-w-md{max-width:28rem}.flex-1{flex:1 1 0%}.flex-shrink-0{flex-shrink:0}.-translate-y-1\/2{--tw-translate-y: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.rotate-180{--tw-rotate: 180deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes pulse{50%{opacity:.5}}.animate-pulse{animation:pulse 2s cubic-bezier(.4,0,.6,1) infinite}@keyframes spin{to{transform:rotate(360deg)}}.animate-spin{animation:spin 1s linear infinite}.cursor-default{cursor:default}.cursor-not-allowed{cursor:not-allowed}.cursor-pointer{cursor:pointer}.list-inside{list-style-position:inside}.list-decimal{list-style-type:decimal}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-start{align-items:flex-start}.items-center{align-items:center}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.gap-1{gap:.25rem}.gap-1\.5{gap:.375rem}.gap-2{gap:.5rem}.gap-3{gap:.75rem}.gap-4{gap:1rem}.gap-6{gap:1.5rem}.space-y-0\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.125rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.125rem * var(--tw-space-y-reverse))}.space-y-1>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.25rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.25rem * var(--tw-space-y-reverse))}.space-y-1\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.375rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.375rem * var(--tw-space-y-reverse))}.space-y-2>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.5rem * var(--tw-space-y-reverse))}.space-y-2\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.625rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.625rem * var(--tw-space-y-reverse))}.space-y-3>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.75rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.75rem * var(--tw-space-y-reverse))}.space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1rem * var(--tw-space-y-reverse))}.space-y-6>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1.5rem * var(--tw-space-y-reverse))}.space-y-8>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(2rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(2rem * var(--tw-space-y-reverse))}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.overflow-x-auto{overflow-x:auto}.overflow-y-auto{overflow-y:auto}.truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.rounded{border-radius:.25rem}.rounded-2xl{border-radius:1rem}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:.5rem}.rounded-xl{border-radius:.75rem}.border{border-width:1px}.border-2{border-width:2px}.border-b{border-bottom-width:1px}.border-r{border-right-width:1px}.border-t{border-top-width:1px}.border-blue-500{--tw-border-opacity: 1;border-color:rgb(59 130 246 / var(--tw-border-opacity, 1))}.border-blue-500\/50{border-color:#3b82f680}.border-gray-700{--tw-border-opacity: 1;border-color:rgb(55 65 81 / var(--tw-border-opacity, 1))}.border-gray-800{--tw-border-opacity: 1;border-color:rgb(31 41 55 / var(--tw-border-opacity, 1))}.border-gray-800\/50{border-color:#1f293780}.border-green-500{--tw-border-opacity: 1;border-color:rgb(34 197 94 / var(--tw-border-opacity, 1))}.border-green-500\/20{border-color:#22c55e33}.border-green-500\/30{border-color:#22c55e4d}.border-purple-500{--tw-border-opacity: 1;border-color:rgb(168 85 247 / var(--tw-border-opacity, 1))}.border-purple-500\/20{border-color:#a855f733}.border-red-500\/20{border-color:#ef444433}.border-red-500\/30{border-color:#ef44444d}.border-white{--tw-border-opacity: 1;border-color:rgb(255 255 255 / var(--tw-border-opacity, 1))}.border-yellow-500\/20{border-color:#eab30833}.border-t-transparent{border-top-color:transparent}.bg-blue-500{--tw-bg-opacity: 1;background-color:rgb(59 130 246 / var(--tw-bg-opacity, 1))}.bg-blue-500\/10{background-color:#3b82f61a}.bg-blue-500\/15{background-color:#3b82f626}.bg-blue-500\/20{background-color:#3b82f633}.bg-gray-600{--tw-bg-opacity: 1;background-color:rgb(75 85 99 / var(--tw-bg-opacity, 1))}.bg-gray-700{--tw-bg-opacity: 1;background-color:rgb(55 65 81 / var(--tw-bg-opacity, 1))}.bg-gray-800{--tw-bg-opacity: 1;background-color:rgb(31 41 55 / var(--tw-bg-opacity, 1))}.bg-gray-800\/20{background-color:#1f293733}.bg-gray-800\/30{background-color:#1f29374d}.bg-gray-800\/40{background-color:#1f293766}.bg-gray-800\/50{background-color:#1f293780}.bg-gray-900{--tw-bg-opacity: 1;background-color:rgb(17 24 39 / var(--tw-bg-opacity, 1))}.bg-gray-900\/50{background-color:#11182780}.bg-green-400{--tw-bg-opacity: 1;background-color:rgb(74 222 128 / var(--tw-bg-opacity, 1))}.bg-green-500{--tw-bg-opacity: 1;background-color:rgb(34 197 94 / var(--tw-bg-opacity, 1))}.bg-green-500\/10{background-color:#22c55e1a}.bg-green-500\/30{background-color:#22c55e4d}.bg-purple-500{--tw-bg-opacity: 1;background-color:rgb(168 85 247 / var(--tw-bg-opacity, 1))}.bg-purple-500\/20{background-color:#a855f733}.bg-red-500{--tw-bg-opacity: 1;background-color:rgb(239 68 68 / var(--tw-bg-opacity, 1))}.bg-red-500\/10{background-color:#ef44441a}.bg-white{--tw-bg-opacity: 1;background-color:rgb(255 255 255 / var(--tw-bg-opacity, 1))}.bg-yellow-400{--tw-bg-opacity: 1;background-color:rgb(250 204 21 / var(--tw-bg-opacity, 1))}.bg-yellow-500{--tw-bg-opacity: 1;background-color:rgb(234 179 8 / var(--tw-bg-opacity, 1))}.bg-yellow-500\/10{background-color:#eab3081a}.bg-yellow-500\/30{background-color:#eab3084d}.bg-yellow-500\/5{background-color:#eab3080d}.bg-gradient-to-r{background-image:linear-gradient(to right,var(--tw-gradient-stops))}.from-blue-400{--tw-gradient-from: #60a5fa var(--tw-gradient-from-position);--tw-gradient-to: rgb(96 165 250 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.to-purple-400{--tw-gradient-to: #c084fc var(--tw-gradient-to-position)}.bg-clip-text{-webkit-background-clip:text;background-clip:text}.\!p-3{padding:.75rem!important}.p-2{padding:.5rem}.p-2\.5{padding:.625rem}.p-3{padding:.75rem}.p-4{padding:1rem}.p-6{padding:1.5rem}.px-1\.5{padding-left:.375rem;padding-right:.375rem}.px-2{padding-left:.5rem;padding-right:.5rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-6{padding-left:1.5rem;padding-right:1.5rem}.px-8{padding-left:2rem;padding-right:2rem}.py-0\.5{padding-top:.125rem;padding-bottom:.125rem}.py-1{padding-top:.25rem;padding-bottom:.25rem}.py-1\.5{padding-top:.375rem;padding-bottom:.375rem}.py-12{padding-top:3rem;padding-bottom:3rem}.py-16{padding-top:4rem;padding-bottom:4rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-2\.5{padding-top:.625rem;padding-bottom:.625rem}.py-4{padding-top:1rem;padding-bottom:1rem}.py-5{padding-top:1.25rem;padding-bottom:1.25rem}.py-8{padding-top:2rem;padding-bottom:2rem}.pb-10{padding-bottom:2.5rem}.pr-10{padding-right:2.5rem}.pr-16{padding-right:4rem}.pt-3{padding-top:.75rem}.pt-4{padding-top:1rem}.text-left{text-align:left}.text-center{text-align:center}.text-right{text-align:right}.font-mono{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace}.text-2xl{font-size:1.5rem;line-height:2rem}.text-3xl{font-size:1.875rem;line-height:2.25rem}.text-4xl{font-size:2.25rem;line-height:2.5rem}.text-\[10px\]{font-size:10px}.text-\[11px\]{font-size:11px}.text-\[9px\]{font-size:9px}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xs{font-size:.75rem;line-height:1rem}.font-bold{font-weight:700}.font-extrabold{font-weight:800}.font-medium{font-weight:500}.font-semibold{font-weight:600}.uppercase{text-transform:uppercase}.leading-relaxed{line-height:1.625}.tracking-wide{letter-spacing:.025em}.tracking-wider{letter-spacing:.05em}.text-blue-400{--tw-text-opacity: 1;color:rgb(96 165 250 / var(--tw-text-opacity, 1))}.text-gray-200{--tw-text-opacity: 1;color:rgb(229 231 235 / var(--tw-text-opacity, 1))}.text-gray-300{--tw-text-opacity: 1;color:rgb(209 213 219 / var(--tw-text-opacity, 1))}.text-gray-400{--tw-text-opacity: 1;color:rgb(156 163 175 / var(--tw-text-opacity, 1))}.text-gray-500{--tw-text-opacity: 1;color:rgb(107 114 128 / var(--tw-text-opacity, 1))}.text-gray-600{--tw-text-opacity: 1;color:rgb(75 85 99 / var(--tw-text-opacity, 1))}.text-green-400{--tw-text-opacity: 1;color:rgb(74 222 128 / var(--tw-text-opacity, 1))}.text-purple-400{--tw-text-opacity: 1;color:rgb(192 132 252 / var(--tw-text-opacity, 1))}.text-red-400{--tw-text-opacity: 1;color:rgb(248 113 113 / var(--tw-text-opacity, 1))}.text-transparent{color:transparent}.text-white{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.text-yellow-400{--tw-text-opacity: 1;color:rgb(250 204 21 / var(--tw-text-opacity, 1))}.opacity-50{opacity:.5}.shadow-xl{--tw-shadow: 0 20px 25px -5px rgb(0 0 0 / .1), 0 8px 10px -6px rgb(0 0 0 / .1);--tw-shadow-colored: 0 20px 25px -5px var(--tw-shadow-color), 0 8px 10px -6px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.ring-2{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.transition{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-all{transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-colors{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-transform{transition-property:transform;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.duration-200{transition-duration:.2s}:root{--bg: #0a0e1a;--card: #111827;--border: #1e293b}body{background:var(--bg);color:#e2e8f0;font-family:Inter,sans-serif;margin:0}::-webkit-scrollbar{width:6px}::-webkit-scrollbar-track{background:var(--bg)}::-webkit-scrollbar-thumb{background:#374151;border-radius:3px}.card{background:var(--card);border:1px solid var(--border);border-radius:12px;padding:1.25rem}.stat-v{font-size:1.75rem;font-weight:700;line-height:1}.badge{display:inline-flex;align-items:center;padding:2px 8px;border-radius:9999px;font-size:.75rem;font-weight:600}.bg-green{background:#10b98126;color:#10b981}.bg-red{background:#ef444426;color:#ef4444}.bg-yellow{background:#f59e0b26;color:#f59e0b}.bg-blue{background:#3b82f626;color:#3b82f6}.bg-purple{background:#8b5cf626;color:#8b5cf6}.pulse-g{animation:pg 2s infinite}@keyframes pg{0%,to{box-shadow:0 0 #10b98166}50%{box-shadow:0 0 0 6px #10b98100}}.btn{padding:.5rem 1rem;border-radius:8px;font-weight:600;font-size:.875rem;cursor:pointer;border:none;transition:all .15s}.btn-p{background:#3b82f6;color:#fff}.btn-p:hover{background:#2563eb}.btn-d{background:#ef4444;color:#fff}.btn-d:hover{background:#dc2626}.btn-s{background:#10b981;color:#fff}.btn-s:hover{background:#059669}table{width:100%;border-collapse:collapse}th{text-align:left;padding:.75rem;font-size:.7rem;text-transform:uppercase;letter-spacing:.05em;color:#64748b;border-bottom:1px solid var(--border)}td{padding:.75rem;border-bottom:1px solid rgba(30,41,59,.5);font-size:.85rem}tr:hover td{background:#3b82f608}.step-enter{opacity:0;transform:translate(24px)}.step-active{opacity:1;transform:translate(0);transition:opacity .35s ease,transform .35s ease}.step-exit{opacity:0;transform:translate(-24px);transition:opacity .2s ease,transform .2s ease}@keyframes pulse-blue{0%,to{box-shadow:0 0 #3b82f666}50%{box-shadow:0 0 0 8px #3b82f600}}.step-active-pulse{animation:pulse-blue 2s infinite}.stepper-line{height:2px;flex:1;background:#1e293b;transition:background .3s}.stepper-line.done{background:#22c55e}.wizard-gradient{background:linear-gradient(135deg,#3b82f6,#8b5cf6);-webkit-background-clip:text;-webkit-text-fill-color:transparent;background-clip:text}.wizard-btn{background:linear-gradient(135deg,#3b82f6,#8b5cf6);color:#fff;padding:.75rem 2rem;border-radius:10px;font-weight:700;font-size:1rem;border:none;cursor:pointer;transition:all .2s}.wizard-btn:hover{transform:translateY(-1px);box-shadow:0 4px 20px #3b82f64d}.wizard-btn:disabled{opacity:.5;cursor:not-allowed;transform:none;box-shadow:none}.hover\:border-blue-500\/30:hover{border-color:#3b82f64d}.hover\:border-gray-700:hover{--tw-border-opacity: 1;border-color:rgb(55 65 81 / var(--tw-border-opacity, 1))}.hover\:border-green-500\/30:hover{border-color:#22c55e4d}.hover\:border-purple-500\/30:hover{border-color:#a855f74d}.hover\:border-red-500\/50:hover{border-color:#ef444480}.hover\:bg-gray-800\/40:hover{background-color:#1f293766}.hover\:bg-gray-800\/50:hover{background-color:#1f293780}.hover\:text-blue-300:hover{--tw-text-opacity: 1;color:rgb(147 197 253 / var(--tw-text-opacity, 1))}.hover\:text-gray-200:hover{--tw-text-opacity: 1;color:rgb(229 231 235 / var(--tw-text-opacity, 1))}.hover\:text-gray-300:hover{--tw-text-opacity: 1;color:rgb(209 213 219 / var(--tw-text-opacity, 1))}.hover\:text-purple-300:hover{--tw-text-opacity: 1;color:rgb(216 180 254 / var(--tw-text-opacity, 1))}.hover\:text-red-300:hover{--tw-text-opacity: 1;color:rgb(252 165 165 / var(--tw-text-opacity, 1))}.hover\:text-red-400:hover{--tw-text-opacity: 1;color:rgb(248 113 113 / var(--tw-text-opacity, 1))}.focus\:border-blue-500:focus{--tw-border-opacity: 1;border-color:rgb(59 130 246 / var(--tw-border-opacity, 1))}.focus\:border-purple-500:focus{--tw-border-opacity: 1;border-color:rgb(168 85 247 / var(--tw-border-opacity, 1))}.focus\:outline-none:focus{outline:2px solid transparent;outline-offset:2px}.disabled\:opacity-50:disabled{opacity:.5}.group:hover .group-hover\:text-gray-400{--tw-text-opacity: 1;color:rgb(156 163 175 / var(--tw-text-opacity, 1))}.group:hover .group-hover\:text-white{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}@media (min-width: 768px){.md\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.md\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.md\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.md\:grid-cols-5{grid-template-columns:repeat(5,minmax(0,1fr))}}@media (min-width: 1024px){.lg\:col-span-2{grid-column:span 2 / span 2}.lg\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.lg\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}}
diff --git a/react-dash/dist/assets/index-qtNisuCe.js b/react-dash/dist/assets/index-qtNisuCe.js
deleted file mode 100644
index cfe7bc6..0000000
--- a/react-dash/dist/assets/index-qtNisuCe.js
+++ /dev/null
@@ -1,139 +0,0 @@
-function $k(e,t){for(var r=0;r<t.length;r++){const n=t[r];if(typeof n!="string"&&!Array.isArray(n)){for(const i in n)if(i!=="default"&&!(i in e)){const a=Object.getOwnPropertyDescriptor(n,i);a&&Object.defineProperty(e,i,a.get?a:{enumerable:!0,get:()=>n[i]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))n(i);new MutationObserver(i=>{for(const a of i)if(a.type==="childList")for(const o of a.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&n(o)}).observe(document,{childList:!0,subtree:!0});function r(i){const a={};return i.integrity&&(a.integrity=i.integrity),i.referrerPolicy&&(a.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?a.credentials="include":i.crossOrigin==="anonymous"?a.credentials="omit":a.credentials="same-origin",a}function n(i){if(i.ep)return;i.ep=!0;const a=r(i);fetch(i.href,a)}})();var Sl=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function de(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var pw={exports:{}},Yc={},hw={exports:{}},ae={};/**
- * @license React
- * react.production.min.js
- *
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- */var al=Symbol.for("react.element"),Ek=Symbol.for("react.portal"),Tk=Symbol.for("react.fragment"),Ck=Symbol.for("react.strict_mode"),Mk=Symbol.for("react.profiler"),Ik=Symbol.for("react.provider"),Lk=Symbol.for("react.context"),Dk=Symbol.for("react.forward_ref"),Rk=Symbol.for("react.suspense"),Bk=Symbol.for("react.memo"),Fk=Symbol.for("react.lazy"),Uy=Symbol.iterator;function zk(e){return e===null||typeof e!="object"?null:(e=Uy&&e[Uy]||e["@@iterator"],typeof e=="function"?e:null)}var mw={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},vw=Object.assign,yw={};function Ja(e,t,r){this.props=e,this.context=t,this.refs=yw,this.updater=r||mw}Ja.prototype.isReactComponent={};Ja.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")};Ja.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function gw(){}gw.prototype=Ja.prototype;function Rm(e,t,r){this.props=e,this.context=t,this.refs=yw,this.updater=r||mw}var Bm=Rm.prototype=new gw;Bm.constructor=Rm;vw(Bm,Ja.prototype);Bm.isPureReactComponent=!0;var Ky=Array.isArray,xw=Object.prototype.hasOwnProperty,Fm={current:null},bw={key:!0,ref:!0,__self:!0,__source:!0};function ww(e,t,r){var n,i={},a=null,o=null;if(t!=null)for(n in t.ref!==void 0&&(o=t.ref),t.key!==void 0&&(a=""+t.key),t)xw.call(t,n)&&!bw.hasOwnProperty(n)&&(i[n]=t[n]);var s=arguments.length-2;if(s===1)i.children=r;else if(1<s){for(var l=Array(s),u=0;u<s;u++)l[u]=arguments[u+2];i.children=l}if(e&&e.defaultProps)for(n in s=e.defaultProps,s)i[n]===void 0&&(i[n]=s[n]);return{$$typeof:al,type:e,key:a,ref:o,props:i,_owner:Fm.current}}function Wk(e,t){return{$$typeof:al,type:e.type,key:t,ref:e.ref,props:e.props,_owner:e._owner}}function zm(e){return typeof e=="object"&&e!==null&&e.$$typeof===al}function Uk(e){var t={"=":"=0",":":"=2"};return"$"+e.replace(/[=:]/g,function(r){return t[r]})}var Hy=/\/+/g;function ad(e,t){return typeof e=="object"&&e!==null&&e.key!=null?Uk(""+e.key):t.toString(36)}function nu(e,t,r,n,i){var a=typeof e;(a==="undefined"||a==="boolean")&&(e=null);var o=!1;if(e===null)o=!0;else switch(a){case"string":case"number":o=!0;break;case"object":switch(e.$$typeof){case al:case Ek:o=!0}}if(o)return o=e,i=i(o),e=n===""?"."+ad(o,0):n,Ky(i)?(r="",e!=null&&(r=e.replace(Hy,"$&/")+"/"),nu(i,t,r,"",function(u){return u})):i!=null&&(zm(i)&&(i=Wk(i,r+(!i.key||o&&o.key===i.key?"":(""+i.key).replace(Hy,"$&/")+"/")+e)),t.push(i)),1;if(o=0,n=n===""?".":n+":",Ky(e))for(var s=0;s<e.length;s++){a=e[s];var l=n+ad(a,s);o+=nu(a,t,r,l,i)}else if(l=zk(e),typeof l=="function")for(e=l.call(e),s=0;!(a=e.next()).done;)a=a.value,l=n+ad(a,s++),o+=nu(a,t,r,l,i);else if(a==="object")throw t=String(e),Error("Objects are not valid as a React child (found: "+(t==="[object Object]"?"object with keys {"+Object.keys(e).join(", ")+"}":t)+"). If you meant to render a collection of children, use an array instead.");return o}function Ol(e,t,r){if(e==null)return e;var n=[],i=0;return nu(e,n,"","",function(a){return t.call(r,a,i++)}),n}function Kk(e){if(e._status===-1){var t=e._result;t=t(),t.then(function(r){(e._status===0||e._status===-1)&&(e._status=1,e._result=r)},function(r){(e._status===0||e._status===-1)&&(e._status=2,e._result=r)}),e._status===-1&&(e._status=0,e._result=t)}if(e._status===1)return e._result.default;throw e._result}var jt={current:null},iu={transition:null},Hk={ReactCurrentDispatcher:jt,ReactCurrentBatchConfig:iu,ReactCurrentOwner:Fm};function jw(){throw Error("act(...) is not supported in production builds of React.")}ae.Children={map:Ol,forEach:function(e,t,r){Ol(e,function(){t.apply(this,arguments)},r)},count:function(e){var t=0;return Ol(e,function(){t++}),t},toArray:function(e){return Ol(e,function(t){return t})||[]},only:function(e){if(!zm(e))throw Error("React.Children.only expected to receive a single React element child.");return e}};ae.Component=Ja;ae.Fragment=Tk;ae.Profiler=Mk;ae.PureComponent=Rm;ae.StrictMode=Ck;ae.Suspense=Rk;ae.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=Hk;ae.act=jw;ae.cloneElement=function(e,t,r){if(e==null)throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+e+".");var n=vw({},e.props),i=e.key,a=e.ref,o=e._owner;if(t!=null){if(t.ref!==void 0&&(a=t.ref,o=Fm.current),t.key!==void 0&&(i=""+t.key),e.type&&e.type.defaultProps)var s=e.type.defaultProps;for(l in t)xw.call(t,l)&&!bw.hasOwnProperty(l)&&(n[l]=t[l]===void 0&&s!==void 0?s[l]:t[l])}var l=arguments.length-2;if(l===1)n.children=r;else if(1<l){s=Array(l);for(var u=0;u<l;u++)s[u]=arguments[u+2];n.children=s}return{$$typeof:al,type:e.type,key:i,ref:a,props:n,_owner:o}};ae.createContext=function(e){return e={$$typeof:Lk,_currentValue:e,_currentValue2:e,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null},e.Provider={$$typeof:Ik,_context:e},e.Consumer=e};ae.createElement=ww;ae.createFactory=function(e){var t=ww.bind(null,e);return t.type=e,t};ae.createRef=function(){return{current:null}};ae.forwardRef=function(e){return{$$typeof:Dk,render:e}};ae.isValidElement=zm;ae.lazy=function(e){return{$$typeof:Fk,_payload:{_status:-1,_result:e},_init:Kk}};ae.memo=function(e,t){return{$$typeof:Bk,type:e,compare:t===void 0?null:t}};ae.startTransition=function(e){var t=iu.transition;iu.transition={};try{e()}finally{iu.transition=t}};ae.unstable_act=jw;ae.useCallback=function(e,t){return jt.current.useCallback(e,t)};ae.useContext=function(e){return jt.current.useContext(e)};ae.useDebugValue=function(){};ae.useDeferredValue=function(e){return jt.current.useDeferredValue(e)};ae.useEffect=function(e,t){return jt.current.useEffect(e,t)};ae.useId=function(){return jt.current.useId()};ae.useImperativeHandle=function(e,t,r){return jt.current.useImperativeHandle(e,t,r)};ae.useInsertionEffect=function(e,t){return jt.current.useInsertionEffect(e,t)};ae.useLayoutEffect=function(e,t){return jt.current.useLayoutEffect(e,t)};ae.useMemo=function(e,t){return jt.current.useMemo(e,t)};ae.useReducer=function(e,t,r){return jt.current.useReducer(e,t,r)};ae.useRef=function(e){return jt.current.useRef(e)};ae.useState=function(e){return jt.current.useState(e)};ae.useSyncExternalStore=function(e,t,r){return jt.current.useSyncExternalStore(e,t,r)};ae.useTransition=function(){return jt.current.useTransition()};ae.version="18.3.1";hw.exports=ae;var k=hw.exports;const A=de(k),Vk=$k({__proto__:null,default:A},[k]);/**
- * @license React
- * react-jsx-runtime.production.min.js
- *
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- */var Gk=k,Yk=Symbol.for("react.element"),qk=Symbol.for("react.fragment"),Xk=Object.prototype.hasOwnProperty,Qk=Gk.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,Zk={key:!0,ref:!0,__self:!0,__source:!0};function Sw(e,t,r){var n,i={},a=null,o=null;r!==void 0&&(a=""+r),t.key!==void 0&&(a=""+t.key),t.ref!==void 0&&(o=t.ref);for(n in t)Xk.call(t,n)&&!Zk.hasOwnProperty(n)&&(i[n]=t[n]);if(e&&e.defaultProps)for(n in t=e.defaultProps,t)i[n]===void 0&&(i[n]=t[n]);return{$$typeof:Yk,type:e,key:a,ref:o,props:i,_owner:Qk.current}}Yc.Fragment=qk;Yc.jsx=Sw;Yc.jsxs=Sw;pw.exports=Yc;var c=pw.exports,fp={},Ow={exports:{}},Kt={},_w={exports:{}},Pw={};/**
- * @license React
- * scheduler.production.min.js
- *
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- */(function(e){function t(M,B){var E=M.length;M.push(B);e:for(;0<E;){var W=E-1>>>1,z=M[W];if(0<i(z,B))M[W]=B,M[E]=z,E=W;else break e}}function r(M){return M.length===0?null:M[0]}function n(M){if(M.length===0)return null;var B=M[0],E=M.pop();if(E!==B){M[0]=E;e:for(var W=0,z=M.length,X=z>>>1;W<X;){var oe=2*(W+1)-1,Pe=M[oe],Le=oe+1,Vt=M[Le];if(0>i(Pe,E))Le<z&&0>i(Vt,Pe)?(M[W]=Vt,M[Le]=E,W=Le):(M[W]=Pe,M[oe]=E,W=oe);else if(Le<z&&0>i(Vt,E))M[W]=Vt,M[Le]=E,W=Le;else break e}}return B}function i(M,B){var E=M.sortIndex-B.sortIndex;return E!==0?E:M.id-B.id}if(typeof performance=="object"&&typeof performance.now=="function"){var a=performance;e.unstable_now=function(){return a.now()}}else{var o=Date,s=o.now();e.unstable_now=function(){return o.now()-s}}var l=[],u=[],f=1,d=null,p=3,h=!1,m=!1,g=!1,x=typeof setTimeout=="function"?setTimeout:null,y=typeof clearTimeout=="function"?clearTimeout:null,v=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function b(M){for(var B=r(u);B!==null;){if(B.callback===null)n(u);else if(B.startTime<=M)n(u),B.sortIndex=B.expirationTime,t(l,B);else break;B=r(u)}}function S(M){if(g=!1,b(M),!m)if(r(l)!==null)m=!0,C(w);else{var B=r(u);B!==null&&F(S,B.startTime-M)}}function w(M,B){m=!1,g&&(g=!1,y(_),_=-1),h=!0;var E=p;try{for(b(B),d=r(l);d!==null&&(!(d.expirationTime>B)||M&&!T());){var W=d.callback;if(typeof W=="function"){d.callback=null,p=d.priorityLevel;var z=W(d.expirationTime<=B);B=e.unstable_now(),typeof z=="function"?d.callback=z:d===r(l)&&n(l),b(B)}else n(l);d=r(l)}if(d!==null)var X=!0;else{var oe=r(u);oe!==null&&F(S,oe.startTime-B),X=!1}return X}finally{d=null,p=E,h=!1}}var j=!1,O=null,_=-1,P=5,N=-1;function T(){return!(e.unstable_now()-N<P)}function $(){if(O!==null){var M=e.unstable_now();N=M;var B=!0;try{B=O(!0,M)}finally{B?I():(j=!1,O=null)}}else j=!1}var I;if(typeof v=="function")I=function(){v($)};else if(typeof MessageChannel<"u"){var D=new MessageChannel,L=D.port2;D.port1.onmessage=$,I=function(){L.postMessage(null)}}else I=function(){x($,0)};function C(M){O=M,j||(j=!0,I())}function F(M,B){_=x(function(){M(e.unstable_now())},B)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(M){M.callback=null},e.unstable_continueExecution=function(){m||h||(m=!0,C(w))},e.unstable_forceFrameRate=function(M){0>M||125<M?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):P=0<M?Math.floor(1e3/M):5},e.unstable_getCurrentPriorityLevel=function(){return p},e.unstable_getFirstCallbackNode=function(){return r(l)},e.unstable_next=function(M){switch(p){case 1:case 2:case 3:var B=3;break;default:B=p}var E=p;p=B;try{return M()}finally{p=E}},e.unstable_pauseExecution=function(){},e.unstable_requestPaint=function(){},e.unstable_runWithPriority=function(M,B){switch(M){case 1:case 2:case 3:case 4:case 5:break;default:M=3}var E=p;p=M;try{return B()}finally{p=E}},e.unstable_scheduleCallback=function(M,B,E){var W=e.unstable_now();switch(typeof E=="object"&&E!==null?(E=E.delay,E=typeof E=="number"&&0<E?W+E:W):E=W,M){case 1:var z=-1;break;case 2:z=250;break;case 5:z=1073741823;break;case 4:z=1e4;break;default:z=5e3}return z=E+z,M={id:f++,callback:B,priorityLevel:M,startTime:E,expirationTime:z,sortIndex:-1},E>W?(M.sortIndex=E,t(u,M),r(l)===null&&M===r(u)&&(g?(y(_),_=-1):g=!0,F(S,E-W))):(M.sortIndex=z,t(l,M),m||h||(m=!0,C(w))),M},e.unstable_shouldYield=T,e.unstable_wrapCallback=function(M){var B=p;return function(){var E=p;p=B;try{return M.apply(this,arguments)}finally{p=E}}}})(Pw);_w.exports=Pw;var Jk=_w.exports;/**
- * @license React
- * react-dom.production.min.js
- *
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- */var eA=k,Ut=Jk;function H(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,r=1;r<arguments.length;r++)t+="&args[]="+encodeURIComponent(arguments[r]);return"Minified React error #"+e+"; visit "+t+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var kw=new Set,as={};function Ei(e,t){ya(e,t),ya(e+"Capture",t)}function ya(e,t){for(as[e]=t,e=0;e<t.length;e++)kw.add(t[e])}var Xr=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),dp=Object.prototype.hasOwnProperty,tA=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,Vy={},Gy={};function rA(e){return dp.call(Gy,e)?!0:dp.call(Vy,e)?!1:tA.test(e)?Gy[e]=!0:(Vy[e]=!0,!1)}function nA(e,t,r,n){if(r!==null&&r.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return n?!1:r!==null?!r.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function iA(e,t,r,n){if(t===null||typeof t>"u"||nA(e,t,r,n))return!0;if(n)return!1;if(r!==null)switch(r.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function St(e,t,r,n,i,a,o){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=n,this.attributeNamespace=i,this.mustUseProperty=r,this.propertyName=e,this.type=t,this.sanitizeURL=a,this.removeEmptyString=o}var st={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){st[e]=new St(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];st[t]=new St(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){st[e]=new St(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){st[e]=new St(e,2,!1,e,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){st[e]=new St(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){st[e]=new St(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){st[e]=new St(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){st[e]=new St(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){st[e]=new St(e,5,!1,e.toLowerCase(),null,!1,!1)});var Wm=/[\-:]([a-z])/g;function Um(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(Wm,Um);st[t]=new St(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(Wm,Um);st[t]=new St(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(Wm,Um);st[t]=new St(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){st[e]=new St(e,1,!1,e.toLowerCase(),null,!1,!1)});st.xlinkHref=new St("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){st[e]=new St(e,1,!1,e.toLowerCase(),null,!0,!0)});function Km(e,t,r,n){var i=st.hasOwnProperty(t)?st[t]:null;(i!==null?i.type!==0:n||!(2<t.length)||t[0]!=="o"&&t[0]!=="O"||t[1]!=="n"&&t[1]!=="N")&&(iA(t,r,i,n)&&(r=null),n||i===null?rA(t)&&(r===null?e.removeAttribute(t):e.setAttribute(t,""+r)):i.mustUseProperty?e[i.propertyName]=r===null?i.type===3?!1:"":r:(t=i.attributeName,n=i.attributeNamespace,r===null?e.removeAttribute(t):(i=i.type,r=i===3||i===4&&r===!0?"":""+r,n?e.setAttributeNS(n,t,r):e.setAttribute(t,r))))}var nn=eA.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,_l=Symbol.for("react.element"),Hi=Symbol.for("react.portal"),Vi=Symbol.for("react.fragment"),Hm=Symbol.for("react.strict_mode"),pp=Symbol.for("react.profiler"),Aw=Symbol.for("react.provider"),Nw=Symbol.for("react.context"),Vm=Symbol.for("react.forward_ref"),hp=Symbol.for("react.suspense"),mp=Symbol.for("react.suspense_list"),Gm=Symbol.for("react.memo"),pn=Symbol.for("react.lazy"),$w=Symbol.for("react.offscreen"),Yy=Symbol.iterator;function go(e){return e===null||typeof e!="object"?null:(e=Yy&&e[Yy]||e["@@iterator"],typeof e=="function"?e:null)}var Te=Object.assign,od;function Lo(e){if(od===void 0)try{throw Error()}catch(r){var t=r.stack.trim().match(/\n( *(at )?)/);od=t&&t[1]||""}return`
-`+od+e}var sd=!1;function ld(e,t){if(!e||sd)return"";sd=!0;var r=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(t)if(t=function(){throw Error()},Object.defineProperty(t.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(t,[])}catch(u){var n=u}Reflect.construct(e,[],t)}else{try{t.call()}catch(u){n=u}e.call(t.prototype)}else{try{throw Error()}catch(u){n=u}e()}}catch(u){if(u&&n&&typeof u.stack=="string"){for(var i=u.stack.split(`
-`),a=n.stack.split(`
-`),o=i.length-1,s=a.length-1;1<=o&&0<=s&&i[o]!==a[s];)s--;for(;1<=o&&0<=s;o--,s--)if(i[o]!==a[s]){if(o!==1||s!==1)do if(o--,s--,0>s||i[o]!==a[s]){var l=`
-`+i[o].replace(" at new "," at ");return e.displayName&&l.includes("<anonymous>")&&(l=l.replace("<anonymous>",e.displayName)),l}while(1<=o&&0<=s);break}}}finally{sd=!1,Error.prepareStackTrace=r}return(e=e?e.displayName||e.name:"")?Lo(e):""}function aA(e){switch(e.tag){case 5:return Lo(e.type);case 16:return Lo("Lazy");case 13:return Lo("Suspense");case 19:return Lo("SuspenseList");case 0:case 2:case 15:return e=ld(e.type,!1),e;case 11:return e=ld(e.type.render,!1),e;case 1:return e=ld(e.type,!0),e;default:return""}}function vp(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case Vi:return"Fragment";case Hi:return"Portal";case pp:return"Profiler";case Hm:return"StrictMode";case hp:return"Suspense";case mp:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case Nw:return(e.displayName||"Context")+".Consumer";case Aw:return(e._context.displayName||"Context")+".Provider";case Vm:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case Gm:return t=e.displayName||null,t!==null?t:vp(e.type)||"Memo";case pn:t=e._payload,e=e._init;try{return vp(e(t))}catch{}}return null}function oA(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return vp(t);case 8:return t===Hm?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function Dn(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function Ew(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function sA(e){var t=Ew(e)?"checked":"value",r=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),n=""+e[t];if(!e.hasOwnProperty(t)&&typeof r<"u"&&typeof r.get=="function"&&typeof r.set=="function"){var i=r.get,a=r.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return i.call(this)},set:function(o){n=""+o,a.call(this,o)}}),Object.defineProperty(e,t,{enumerable:r.enumerable}),{getValue:function(){return n},setValue:function(o){n=""+o},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function Pl(e){e._valueTracker||(e._valueTracker=sA(e))}function Tw(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var r=t.getValue(),n="";return e&&(n=Ew(e)?e.checked?"true":"false":e.value),e=n,e!==r?(t.setValue(e),!0):!1}function vu(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function yp(e,t){var r=t.checked;return Te({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:r??e._wrapperState.initialChecked})}function qy(e,t){var r=t.defaultValue==null?"":t.defaultValue,n=t.checked!=null?t.checked:t.defaultChecked;r=Dn(t.value!=null?t.value:r),e._wrapperState={initialChecked:n,initialValue:r,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function Cw(e,t){t=t.checked,t!=null&&Km(e,"checked",t,!1)}function gp(e,t){Cw(e,t);var r=Dn(t.value),n=t.type;if(r!=null)n==="number"?(r===0&&e.value===""||e.value!=r)&&(e.value=""+r):e.value!==""+r&&(e.value=""+r);else if(n==="submit"||n==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?xp(e,t.type,r):t.hasOwnProperty("defaultValue")&&xp(e,t.type,Dn(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function Xy(e,t,r){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var n=t.type;if(!(n!=="submit"&&n!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,r||t===e.value||(e.value=t),e.defaultValue=t}r=e.name,r!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,r!==""&&(e.name=r)}function xp(e,t,r){(t!=="number"||vu(e.ownerDocument)!==e)&&(r==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+r&&(e.defaultValue=""+r))}var Do=Array.isArray;function la(e,t,r,n){if(e=e.options,t){t={};for(var i=0;i<r.length;i++)t["$"+r[i]]=!0;for(r=0;r<e.length;r++)i=t.hasOwnProperty("$"+e[r].value),e[r].selected!==i&&(e[r].selected=i),i&&n&&(e[r].defaultSelected=!0)}else{for(r=""+Dn(r),t=null,i=0;i<e.length;i++){if(e[i].value===r){e[i].selected=!0,n&&(e[i].defaultSelected=!0);return}t!==null||e[i].disabled||(t=e[i])}t!==null&&(t.selected=!0)}}function bp(e,t){if(t.dangerouslySetInnerHTML!=null)throw Error(H(91));return Te({},t,{value:void 0,defaultValue:void 0,children:""+e._wrapperState.initialValue})}function Qy(e,t){var r=t.value;if(r==null){if(r=t.children,t=t.defaultValue,r!=null){if(t!=null)throw Error(H(92));if(Do(r)){if(1<r.length)throw Error(H(93));r=r[0]}t=r}t==null&&(t=""),r=t}e._wrapperState={initialValue:Dn(r)}}function Mw(e,t){var r=Dn(t.value),n=Dn(t.defaultValue);r!=null&&(r=""+r,r!==e.value&&(e.value=r),t.defaultValue==null&&e.defaultValue!==r&&(e.defaultValue=r)),n!=null&&(e.defaultValue=""+n)}function Zy(e){var t=e.textContent;t===e._wrapperState.initialValue&&t!==""&&t!==null&&(e.value=t)}function Iw(e){switch(e){case"svg":return"http://www.w3.org/2000/svg";case"math":return"http://www.w3.org/1998/Math/MathML";default:return"http://www.w3.org/1999/xhtml"}}function wp(e,t){return e==null||e==="http://www.w3.org/1999/xhtml"?Iw(t):e==="http://www.w3.org/2000/svg"&&t==="foreignObject"?"http://www.w3.org/1999/xhtml":e}var kl,Lw=function(e){return typeof MSApp<"u"&&MSApp.execUnsafeLocalFunction?function(t,r,n,i){MSApp.execUnsafeLocalFunction(function(){return e(t,r,n,i)})}:e}(function(e,t){if(e.namespaceURI!=="http://www.w3.org/2000/svg"||"innerHTML"in e)e.innerHTML=t;else{for(kl=kl||document.createElement("div"),kl.innerHTML="<svg>"+t.valueOf().toString()+"</svg>",t=kl.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function os(e,t){if(t){var r=e.firstChild;if(r&&r===e.lastChild&&r.nodeType===3){r.nodeValue=t;return}}e.textContent=t}var zo={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},lA=["Webkit","ms","Moz","O"];Object.keys(zo).forEach(function(e){lA.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),zo[t]=zo[e]})});function Dw(e,t,r){return t==null||typeof t=="boolean"||t===""?"":r||typeof t!="number"||t===0||zo.hasOwnProperty(e)&&zo[e]?(""+t).trim():t+"px"}function Rw(e,t){e=e.style;for(var r in t)if(t.hasOwnProperty(r)){var n=r.indexOf("--")===0,i=Dw(r,t[r],n);r==="float"&&(r="cssFloat"),n?e.setProperty(r,i):e[r]=i}}var uA=Te({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function jp(e,t){if(t){if(uA[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(H(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(H(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(H(61))}if(t.style!=null&&typeof t.style!="object")throw Error(H(62))}}function Sp(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var Op=null;function Ym(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var _p=null,ua=null,ca=null;function Jy(e){if(e=ll(e)){if(typeof _p!="function")throw Error(H(280));var t=e.stateNode;t&&(t=Jc(t),_p(e.stateNode,e.type,t))}}function Bw(e){ua?ca?ca.push(e):ca=[e]:ua=e}function Fw(){if(ua){var e=ua,t=ca;if(ca=ua=null,Jy(e),t)for(e=0;e<t.length;e++)Jy(t[e])}}function zw(e,t){return e(t)}function Ww(){}var ud=!1;function Uw(e,t,r){if(ud)return e(t,r);ud=!0;try{return zw(e,t,r)}finally{ud=!1,(ua!==null||ca!==null)&&(Ww(),Fw())}}function ss(e,t){var r=e.stateNode;if(r===null)return null;var n=Jc(r);if(n===null)return null;r=n[t];e:switch(t){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(n=!n.disabled)||(e=e.type,n=!(e==="button"||e==="input"||e==="select"||e==="textarea")),e=!n;break e;default:e=!1}if(e)return null;if(r&&typeof r!="function")throw Error(H(231,t,typeof r));return r}var Pp=!1;if(Xr)try{var xo={};Object.defineProperty(xo,"passive",{get:function(){Pp=!0}}),window.addEventListener("test",xo,xo),window.removeEventListener("test",xo,xo)}catch{Pp=!1}function cA(e,t,r,n,i,a,o,s,l){var u=Array.prototype.slice.call(arguments,3);try{t.apply(r,u)}catch(f){this.onError(f)}}var Wo=!1,yu=null,gu=!1,kp=null,fA={onError:function(e){Wo=!0,yu=e}};function dA(e,t,r,n,i,a,o,s,l){Wo=!1,yu=null,cA.apply(fA,arguments)}function pA(e,t,r,n,i,a,o,s,l){if(dA.apply(this,arguments),Wo){if(Wo){var u=yu;Wo=!1,yu=null}else throw Error(H(198));gu||(gu=!0,kp=u)}}function Ti(e){var t=e,r=e;if(e.alternate)for(;t.return;)t=t.return;else{e=t;do t=e,t.flags&4098&&(r=t.return),e=t.return;while(e)}return t.tag===3?r:null}function Kw(e){if(e.tag===13){var t=e.memoizedState;if(t===null&&(e=e.alternate,e!==null&&(t=e.memoizedState)),t!==null)return t.dehydrated}return null}function eg(e){if(Ti(e)!==e)throw Error(H(188))}function hA(e){var t=e.alternate;if(!t){if(t=Ti(e),t===null)throw Error(H(188));return t!==e?null:e}for(var r=e,n=t;;){var i=r.return;if(i===null)break;var a=i.alternate;if(a===null){if(n=i.return,n!==null){r=n;continue}break}if(i.child===a.child){for(a=i.child;a;){if(a===r)return eg(i),e;if(a===n)return eg(i),t;a=a.sibling}throw Error(H(188))}if(r.return!==n.return)r=i,n=a;else{for(var o=!1,s=i.child;s;){if(s===r){o=!0,r=i,n=a;break}if(s===n){o=!0,n=i,r=a;break}s=s.sibling}if(!o){for(s=a.child;s;){if(s===r){o=!0,r=a,n=i;break}if(s===n){o=!0,n=a,r=i;break}s=s.sibling}if(!o)throw Error(H(189))}}if(r.alternate!==n)throw Error(H(190))}if(r.tag!==3)throw Error(H(188));return r.stateNode.current===r?e:t}function Hw(e){return e=hA(e),e!==null?Vw(e):null}function Vw(e){if(e.tag===5||e.tag===6)return e;for(e=e.child;e!==null;){var t=Vw(e);if(t!==null)return t;e=e.sibling}return null}var Gw=Ut.unstable_scheduleCallback,tg=Ut.unstable_cancelCallback,mA=Ut.unstable_shouldYield,vA=Ut.unstable_requestPaint,De=Ut.unstable_now,yA=Ut.unstable_getCurrentPriorityLevel,qm=Ut.unstable_ImmediatePriority,Yw=Ut.unstable_UserBlockingPriority,xu=Ut.unstable_NormalPriority,gA=Ut.unstable_LowPriority,qw=Ut.unstable_IdlePriority,qc=null,$r=null;function xA(e){if($r&&typeof $r.onCommitFiberRoot=="function")try{$r.onCommitFiberRoot(qc,e,void 0,(e.current.flags&128)===128)}catch{}}var yr=Math.clz32?Math.clz32:jA,bA=Math.log,wA=Math.LN2;function jA(e){return e>>>=0,e===0?32:31-(bA(e)/wA|0)|0}var Al=64,Nl=4194304;function Ro(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function bu(e,t){var r=e.pendingLanes;if(r===0)return 0;var n=0,i=e.suspendedLanes,a=e.pingedLanes,o=r&268435455;if(o!==0){var s=o&~i;s!==0?n=Ro(s):(a&=o,a!==0&&(n=Ro(a)))}else o=r&~i,o!==0?n=Ro(o):a!==0&&(n=Ro(a));if(n===0)return 0;if(t!==0&&t!==n&&!(t&i)&&(i=n&-n,a=t&-t,i>=a||i===16&&(a&4194240)!==0))return t;if(n&4&&(n|=r&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=n;0<t;)r=31-yr(t),i=1<<r,n|=e[r],t&=~i;return n}function SA(e,t){switch(e){case 1:case 2:case 4:return t+250;case 8:case 16:case 32:case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return t+5e3;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return-1;case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function OA(e,t){for(var r=e.suspendedLanes,n=e.pingedLanes,i=e.expirationTimes,a=e.pendingLanes;0<a;){var o=31-yr(a),s=1<<o,l=i[o];l===-1?(!(s&r)||s&n)&&(i[o]=SA(s,t)):l<=t&&(e.expiredLanes|=s),a&=~s}}function Ap(e){return e=e.pendingLanes&-1073741825,e!==0?e:e&1073741824?1073741824:0}function Xw(){var e=Al;return Al<<=1,!(Al&4194240)&&(Al=64),e}function cd(e){for(var t=[],r=0;31>r;r++)t.push(e);return t}function ol(e,t,r){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-yr(t),e[t]=r}function _A(e,t){var r=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var n=e.eventTimes;for(e=e.expirationTimes;0<r;){var i=31-yr(r),a=1<<i;t[i]=0,n[i]=-1,e[i]=-1,r&=~a}}function Xm(e,t){var r=e.entangledLanes|=t;for(e=e.entanglements;r;){var n=31-yr(r),i=1<<n;i&t|e[n]&t&&(e[n]|=t),r&=~i}}var fe=0;function Qw(e){return e&=-e,1<e?4<e?e&268435455?16:536870912:4:1}var Zw,Qm,Jw,ej,tj,Np=!1,$l=[],Pn=null,kn=null,An=null,ls=new Map,us=new Map,vn=[],PA="mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset submit".split(" ");function rg(e,t){switch(e){case"focusin":case"focusout":Pn=null;break;case"dragenter":case"dragleave":kn=null;break;case"mouseover":case"mouseout":An=null;break;case"pointerover":case"pointerout":ls.delete(t.pointerId);break;case"gotpointercapture":case"lostpointercapture":us.delete(t.pointerId)}}function bo(e,t,r,n,i,a){return e===null||e.nativeEvent!==a?(e={blockedOn:t,domEventName:r,eventSystemFlags:n,nativeEvent:a,targetContainers:[i]},t!==null&&(t=ll(t),t!==null&&Qm(t)),e):(e.eventSystemFlags|=n,t=e.targetContainers,i!==null&&t.indexOf(i)===-1&&t.push(i),e)}function kA(e,t,r,n,i){switch(t){case"focusin":return Pn=bo(Pn,e,t,r,n,i),!0;case"dragenter":return kn=bo(kn,e,t,r,n,i),!0;case"mouseover":return An=bo(An,e,t,r,n,i),!0;case"pointerover":var a=i.pointerId;return ls.set(a,bo(ls.get(a)||null,e,t,r,n,i)),!0;case"gotpointercapture":return a=i.pointerId,us.set(a,bo(us.get(a)||null,e,t,r,n,i)),!0}return!1}function rj(e){var t=li(e.target);if(t!==null){var r=Ti(t);if(r!==null){if(t=r.tag,t===13){if(t=Kw(r),t!==null){e.blockedOn=t,tj(e.priority,function(){Jw(r)});return}}else if(t===3&&r.stateNode.current.memoizedState.isDehydrated){e.blockedOn=r.tag===3?r.stateNode.containerInfo:null;return}}}e.blockedOn=null}function au(e){if(e.blockedOn!==null)return!1;for(var t=e.targetContainers;0<t.length;){var r=$p(e.domEventName,e.eventSystemFlags,t[0],e.nativeEvent);if(r===null){r=e.nativeEvent;var n=new r.constructor(r.type,r);Op=n,r.target.dispatchEvent(n),Op=null}else return t=ll(r),t!==null&&Qm(t),e.blockedOn=r,!1;t.shift()}return!0}function ng(e,t,r){au(e)&&r.delete(t)}function AA(){Np=!1,Pn!==null&&au(Pn)&&(Pn=null),kn!==null&&au(kn)&&(kn=null),An!==null&&au(An)&&(An=null),ls.forEach(ng),us.forEach(ng)}function wo(e,t){e.blockedOn===t&&(e.blockedOn=null,Np||(Np=!0,Ut.unstable_scheduleCallback(Ut.unstable_NormalPriority,AA)))}function cs(e){function t(i){return wo(i,e)}if(0<$l.length){wo($l[0],e);for(var r=1;r<$l.length;r++){var n=$l[r];n.blockedOn===e&&(n.blockedOn=null)}}for(Pn!==null&&wo(Pn,e),kn!==null&&wo(kn,e),An!==null&&wo(An,e),ls.forEach(t),us.forEach(t),r=0;r<vn.length;r++)n=vn[r],n.blockedOn===e&&(n.blockedOn=null);for(;0<vn.length&&(r=vn[0],r.blockedOn===null);)rj(r),r.blockedOn===null&&vn.shift()}var fa=nn.ReactCurrentBatchConfig,wu=!0;function NA(e,t,r,n){var i=fe,a=fa.transition;fa.transition=null;try{fe=1,Zm(e,t,r,n)}finally{fe=i,fa.transition=a}}function $A(e,t,r,n){var i=fe,a=fa.transition;fa.transition=null;try{fe=4,Zm(e,t,r,n)}finally{fe=i,fa.transition=a}}function Zm(e,t,r,n){if(wu){var i=$p(e,t,r,n);if(i===null)bd(e,t,n,ju,r),rg(e,n);else if(kA(i,e,t,r,n))n.stopPropagation();else if(rg(e,n),t&4&&-1<PA.indexOf(e)){for(;i!==null;){var a=ll(i);if(a!==null&&Zw(a),a=$p(e,t,r,n),a===null&&bd(e,t,n,ju,r),a===i)break;i=a}i!==null&&n.stopPropagation()}else bd(e,t,n,null,r)}}var ju=null;function $p(e,t,r,n){if(ju=null,e=Ym(n),e=li(e),e!==null)if(t=Ti(e),t===null)e=null;else if(r=t.tag,r===13){if(e=Kw(t),e!==null)return e;e=null}else if(r===3){if(t.stateNode.current.memoizedState.isDehydrated)return t.tag===3?t.stateNode.containerInfo:null;e=null}else t!==e&&(e=null);return ju=e,null}function nj(e){switch(e){case"cancel":case"click":case"close":case"contextmenu":case"copy":case"cut":case"auxclick":case"dblclick":case"dragend":case"dragstart":case"drop":case"focusin":case"focusout":case"input":case"invalid":case"keydown":case"keypress":case"keyup":case"mousedown":case"mouseup":case"paste":case"pause":case"play":case"pointercancel":case"pointerdown":case"pointerup":case"ratechange":case"reset":case"resize":case"seeked":case"submit":case"touchcancel":case"touchend":case"touchstart":case"volumechange":case"change":case"selectionchange":case"textInput":case"compositionstart":case"compositionend":case"compositionupdate":case"beforeblur":case"afterblur":case"beforeinput":case"blur":case"fullscreenchange":case"focus":case"hashchange":case"popstate":case"select":case"selectstart":return 1;case"drag":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"mousemove":case"mouseout":case"mouseover":case"pointermove":case"pointerout":case"pointerover":case"scroll":case"toggle":case"touchmove":case"wheel":case"mouseenter":case"mouseleave":case"pointerenter":case"pointerleave":return 4;case"message":switch(yA()){case qm:return 1;case Yw:return 4;case xu:case gA:return 16;case qw:return 536870912;default:return 16}default:return 16}}var xn=null,Jm=null,ou=null;function ij(){if(ou)return ou;var e,t=Jm,r=t.length,n,i="value"in xn?xn.value:xn.textContent,a=i.length;for(e=0;e<r&&t[e]===i[e];e++);var o=r-e;for(n=1;n<=o&&t[r-n]===i[a-n];n++);return ou=i.slice(e,1<n?1-n:void 0)}function su(e){var t=e.keyCode;return"charCode"in e?(e=e.charCode,e===0&&t===13&&(e=13)):e=t,e===10&&(e=13),32<=e||e===13?e:0}function El(){return!0}function ig(){return!1}function Ht(e){function t(r,n,i,a,o){this._reactName=r,this._targetInst=i,this.type=n,this.nativeEvent=a,this.target=o,this.currentTarget=null;for(var s in e)e.hasOwnProperty(s)&&(r=e[s],this[s]=r?r(a):a[s]);return this.isDefaultPrevented=(a.defaultPrevented!=null?a.defaultPrevented:a.returnValue===!1)?El:ig,this.isPropagationStopped=ig,this}return Te(t.prototype,{preventDefault:function(){this.defaultPrevented=!0;var r=this.nativeEvent;r&&(r.preventDefault?r.preventDefault():typeof r.returnValue!="unknown"&&(r.returnValue=!1),this.isDefaultPrevented=El)},stopPropagation:function(){var r=this.nativeEvent;r&&(r.stopPropagation?r.stopPropagation():typeof r.cancelBubble!="unknown"&&(r.cancelBubble=!0),this.isPropagationStopped=El)},persist:function(){},isPersistent:El}),t}var eo={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},ev=Ht(eo),sl=Te({},eo,{view:0,detail:0}),EA=Ht(sl),fd,dd,jo,Xc=Te({},sl,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:tv,button:0,buttons:0,relatedTarget:function(e){return e.relatedTarget===void 0?e.fromElement===e.srcElement?e.toElement:e.fromElement:e.relatedTarget},movementX:function(e){return"movementX"in e?e.movementX:(e!==jo&&(jo&&e.type==="mousemove"?(fd=e.screenX-jo.screenX,dd=e.screenY-jo.screenY):dd=fd=0,jo=e),fd)},movementY:function(e){return"movementY"in e?e.movementY:dd}}),ag=Ht(Xc),TA=Te({},Xc,{dataTransfer:0}),CA=Ht(TA),MA=Te({},sl,{relatedTarget:0}),pd=Ht(MA),IA=Te({},eo,{animationName:0,elapsedTime:0,pseudoElement:0}),LA=Ht(IA),DA=Te({},eo,{clipboardData:function(e){return"clipboardData"in e?e.clipboardData:window.clipboardData}}),RA=Ht(DA),BA=Te({},eo,{data:0}),og=Ht(BA),FA={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},zA={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},WA={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function UA(e){var t=this.nativeEvent;return t.getModifierState?t.getModifierState(e):(e=WA[e])?!!t[e]:!1}function tv(){return UA}var KA=Te({},sl,{key:function(e){if(e.key){var t=FA[e.key]||e.key;if(t!=="Unidentified")return t}return e.type==="keypress"?(e=su(e),e===13?"Enter":String.fromCharCode(e)):e.type==="keydown"||e.type==="keyup"?zA[e.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:tv,charCode:function(e){return e.type==="keypress"?su(e):0},keyCode:function(e){return e.type==="keydown"||e.type==="keyup"?e.keyCode:0},which:function(e){return e.type==="keypress"?su(e):e.type==="keydown"||e.type==="keyup"?e.keyCode:0}}),HA=Ht(KA),VA=Te({},Xc,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),sg=Ht(VA),GA=Te({},sl,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:tv}),YA=Ht(GA),qA=Te({},eo,{propertyName:0,elapsedTime:0,pseudoElement:0}),XA=Ht(qA),QA=Te({},Xc,{deltaX:function(e){return"deltaX"in e?e.deltaX:"wheelDeltaX"in e?-e.wheelDeltaX:0},deltaY:function(e){return"deltaY"in e?e.deltaY:"wheelDeltaY"in e?-e.wheelDeltaY:"wheelDelta"in e?-e.wheelDelta:0},deltaZ:0,deltaMode:0}),ZA=Ht(QA),JA=[9,13,27,32],rv=Xr&&"CompositionEvent"in window,Uo=null;Xr&&"documentMode"in document&&(Uo=document.documentMode);var e2=Xr&&"TextEvent"in window&&!Uo,aj=Xr&&(!rv||Uo&&8<Uo&&11>=Uo),lg=" ",ug=!1;function oj(e,t){switch(e){case"keyup":return JA.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function sj(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var Gi=!1;function t2(e,t){switch(e){case"compositionend":return sj(t);case"keypress":return t.which!==32?null:(ug=!0,lg);case"textInput":return e=t.data,e===lg&&ug?null:e;default:return null}}function r2(e,t){if(Gi)return e==="compositionend"||!rv&&oj(e,t)?(e=ij(),ou=Jm=xn=null,Gi=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1<t.char.length)return t.char;if(t.which)return String.fromCharCode(t.which)}return null;case"compositionend":return aj&&t.locale!=="ko"?null:t.data;default:return null}}var n2={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function cg(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t==="input"?!!n2[e.type]:t==="textarea"}function lj(e,t,r,n){Bw(n),t=Su(t,"onChange"),0<t.length&&(r=new ev("onChange","change",null,r,n),e.push({event:r,listeners:t}))}var Ko=null,fs=null;function i2(e){xj(e,0)}function Qc(e){var t=Xi(e);if(Tw(t))return e}function a2(e,t){if(e==="change")return t}var uj=!1;if(Xr){var hd;if(Xr){var md="oninput"in document;if(!md){var fg=document.createElement("div");fg.setAttribute("oninput","return;"),md=typeof fg.oninput=="function"}hd=md}else hd=!1;uj=hd&&(!document.documentMode||9<document.documentMode)}function dg(){Ko&&(Ko.detachEvent("onpropertychange",cj),fs=Ko=null)}function cj(e){if(e.propertyName==="value"&&Qc(fs)){var t=[];lj(t,fs,e,Ym(e)),Uw(i2,t)}}function o2(e,t,r){e==="focusin"?(dg(),Ko=t,fs=r,Ko.attachEvent("onpropertychange",cj)):e==="focusout"&&dg()}function s2(e){if(e==="selectionchange"||e==="keyup"||e==="keydown")return Qc(fs)}function l2(e,t){if(e==="click")return Qc(t)}function u2(e,t){if(e==="input"||e==="change")return Qc(t)}function c2(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var wr=typeof Object.is=="function"?Object.is:c2;function ds(e,t){if(wr(e,t))return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;var r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(n=0;n<r.length;n++){var i=r[n];if(!dp.call(t,i)||!wr(e[i],t[i]))return!1}return!0}function pg(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function hg(e,t){var r=pg(e);e=0;for(var n;r;){if(r.nodeType===3){if(n=e+r.textContent.length,e<=t&&n>=t)return{node:r,offset:t-e};e=n}e:{for(;r;){if(r.nextSibling){r=r.nextSibling;break e}r=r.parentNode}r=void 0}r=pg(r)}}function fj(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?fj(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function dj(){for(var e=window,t=vu();t instanceof e.HTMLIFrameElement;){try{var r=typeof t.contentWindow.location.href=="string"}catch{r=!1}if(r)e=t.contentWindow;else break;t=vu(e.document)}return t}function nv(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function f2(e){var t=dj(),r=e.focusedElem,n=e.selectionRange;if(t!==r&&r&&r.ownerDocument&&fj(r.ownerDocument.documentElement,r)){if(n!==null&&nv(r)){if(t=n.start,e=n.end,e===void 0&&(e=t),"selectionStart"in r)r.selectionStart=t,r.selectionEnd=Math.min(e,r.value.length);else if(e=(t=r.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var i=r.textContent.length,a=Math.min(n.start,i);n=n.end===void 0?a:Math.min(n.end,i),!e.extend&&a>n&&(i=n,n=a,a=i),i=hg(r,a);var o=hg(r,n);i&&o&&(e.rangeCount!==1||e.anchorNode!==i.node||e.anchorOffset!==i.offset||e.focusNode!==o.node||e.focusOffset!==o.offset)&&(t=t.createRange(),t.setStart(i.node,i.offset),e.removeAllRanges(),a>n?(e.addRange(t),e.extend(o.node,o.offset)):(t.setEnd(o.node,o.offset),e.addRange(t)))}}for(t=[],e=r;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof r.focus=="function"&&r.focus(),r=0;r<t.length;r++)e=t[r],e.element.scrollLeft=e.left,e.element.scrollTop=e.top}}var d2=Xr&&"documentMode"in document&&11>=document.documentMode,Yi=null,Ep=null,Ho=null,Tp=!1;function mg(e,t,r){var n=r.window===r?r.document:r.nodeType===9?r:r.ownerDocument;Tp||Yi==null||Yi!==vu(n)||(n=Yi,"selectionStart"in n&&nv(n)?n={start:n.selectionStart,end:n.selectionEnd}:(n=(n.ownerDocument&&n.ownerDocument.defaultView||window).getSelection(),n={anchorNode:n.anchorNode,anchorOffset:n.anchorOffset,focusNode:n.focusNode,focusOffset:n.focusOffset}),Ho&&ds(Ho,n)||(Ho=n,n=Su(Ep,"onSelect"),0<n.length&&(t=new ev("onSelect","select",null,t,r),e.push({event:t,listeners:n}),t.target=Yi)))}function Tl(e,t){var r={};return r[e.toLowerCase()]=t.toLowerCase(),r["Webkit"+e]="webkit"+t,r["Moz"+e]="moz"+t,r}var qi={animationend:Tl("Animation","AnimationEnd"),animationiteration:Tl("Animation","AnimationIteration"),animationstart:Tl("Animation","AnimationStart"),transitionend:Tl("Transition","TransitionEnd")},vd={},pj={};Xr&&(pj=document.createElement("div").style,"AnimationEvent"in window||(delete qi.animationend.animation,delete qi.animationiteration.animation,delete qi.animationstart.animation),"TransitionEvent"in window||delete qi.transitionend.transition);function Zc(e){if(vd[e])return vd[e];if(!qi[e])return e;var t=qi[e],r;for(r in t)if(t.hasOwnProperty(r)&&r in pj)return vd[e]=t[r];return e}var hj=Zc("animationend"),mj=Zc("animationiteration"),vj=Zc("animationstart"),yj=Zc("transitionend"),gj=new Map,vg="abort auxClick cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(" ");function Wn(e,t){gj.set(e,t),Ei(t,[e])}for(var yd=0;yd<vg.length;yd++){var gd=vg[yd],p2=gd.toLowerCase(),h2=gd[0].toUpperCase()+gd.slice(1);Wn(p2,"on"+h2)}Wn(hj,"onAnimationEnd");Wn(mj,"onAnimationIteration");Wn(vj,"onAnimationStart");Wn("dblclick","onDoubleClick");Wn("focusin","onFocus");Wn("focusout","onBlur");Wn(yj,"onTransitionEnd");ya("onMouseEnter",["mouseout","mouseover"]);ya("onMouseLeave",["mouseout","mouseover"]);ya("onPointerEnter",["pointerout","pointerover"]);ya("onPointerLeave",["pointerout","pointerover"]);Ei("onChange","change click focusin focusout input keydown keyup selectionchange".split(" "));Ei("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" "));Ei("onBeforeInput",["compositionend","keypress","textInput","paste"]);Ei("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" "));Ei("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" "));Ei("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var Bo="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),m2=new Set("cancel close invalid load scroll toggle".split(" ").concat(Bo));function yg(e,t,r){var n=e.type||"unknown-event";e.currentTarget=r,pA(n,t,void 0,e),e.currentTarget=null}function xj(e,t){t=(t&4)!==0;for(var r=0;r<e.length;r++){var n=e[r],i=n.event;n=n.listeners;e:{var a=void 0;if(t)for(var o=n.length-1;0<=o;o--){var s=n[o],l=s.instance,u=s.currentTarget;if(s=s.listener,l!==a&&i.isPropagationStopped())break e;yg(i,s,u),a=l}else for(o=0;o<n.length;o++){if(s=n[o],l=s.instance,u=s.currentTarget,s=s.listener,l!==a&&i.isPropagationStopped())break e;yg(i,s,u),a=l}}}if(gu)throw e=kp,gu=!1,kp=null,e}function be(e,t){var r=t[Dp];r===void 0&&(r=t[Dp]=new Set);var n=e+"__bubble";r.has(n)||(bj(t,e,2,!1),r.add(n))}function xd(e,t,r){var n=0;t&&(n|=4),bj(r,e,n,t)}var Cl="_reactListening"+Math.random().toString(36).slice(2);function ps(e){if(!e[Cl]){e[Cl]=!0,kw.forEach(function(r){r!=="selectionchange"&&(m2.has(r)||xd(r,!1,e),xd(r,!0,e))});var t=e.nodeType===9?e:e.ownerDocument;t===null||t[Cl]||(t[Cl]=!0,xd("selectionchange",!1,t))}}function bj(e,t,r,n){switch(nj(t)){case 1:var i=NA;break;case 4:i=$A;break;default:i=Zm}r=i.bind(null,t,r,e),i=void 0,!Pp||t!=="touchstart"&&t!=="touchmove"&&t!=="wheel"||(i=!0),n?i!==void 0?e.addEventListener(t,r,{capture:!0,passive:i}):e.addEventListener(t,r,!0):i!==void 0?e.addEventListener(t,r,{passive:i}):e.addEventListener(t,r,!1)}function bd(e,t,r,n,i){var a=n;if(!(t&1)&&!(t&2)&&n!==null)e:for(;;){if(n===null)return;var o=n.tag;if(o===3||o===4){var s=n.stateNode.containerInfo;if(s===i||s.nodeType===8&&s.parentNode===i)break;if(o===4)for(o=n.return;o!==null;){var l=o.tag;if((l===3||l===4)&&(l=o.stateNode.containerInfo,l===i||l.nodeType===8&&l.parentNode===i))return;o=o.return}for(;s!==null;){if(o=li(s),o===null)return;if(l=o.tag,l===5||l===6){n=a=o;continue e}s=s.parentNode}}n=n.return}Uw(function(){var u=a,f=Ym(r),d=[];e:{var p=gj.get(e);if(p!==void 0){var h=ev,m=e;switch(e){case"keypress":if(su(r)===0)break e;case"keydown":case"keyup":h=HA;break;case"focusin":m="focus",h=pd;break;case"focusout":m="blur",h=pd;break;case"beforeblur":case"afterblur":h=pd;break;case"click":if(r.button===2)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":h=ag;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":h=CA;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":h=YA;break;case hj:case mj:case vj:h=LA;break;case yj:h=XA;break;case"scroll":h=EA;break;case"wheel":h=ZA;break;case"copy":case"cut":case"paste":h=RA;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":h=sg}var g=(t&4)!==0,x=!g&&e==="scroll",y=g?p!==null?p+"Capture":null:p;g=[];for(var v=u,b;v!==null;){b=v;var S=b.stateNode;if(b.tag===5&&S!==null&&(b=S,y!==null&&(S=ss(v,y),S!=null&&g.push(hs(v,S,b)))),x)break;v=v.return}0<g.length&&(p=new h(p,m,null,r,f),d.push({event:p,listeners:g}))}}if(!(t&7)){e:{if(p=e==="mouseover"||e==="pointerover",h=e==="mouseout"||e==="pointerout",p&&r!==Op&&(m=r.relatedTarget||r.fromElement)&&(li(m)||m[Qr]))break e;if((h||p)&&(p=f.window===f?f:(p=f.ownerDocument)?p.defaultView||p.parentWindow:window,h?(m=r.relatedTarget||r.toElement,h=u,m=m?li(m):null,m!==null&&(x=Ti(m),m!==x||m.tag!==5&&m.tag!==6)&&(m=null)):(h=null,m=u),h!==m)){if(g=ag,S="onMouseLeave",y="onMouseEnter",v="mouse",(e==="pointerout"||e==="pointerover")&&(g=sg,S="onPointerLeave",y="onPointerEnter",v="pointer"),x=h==null?p:Xi(h),b=m==null?p:Xi(m),p=new g(S,v+"leave",h,r,f),p.target=x,p.relatedTarget=b,S=null,li(f)===u&&(g=new g(y,v+"enter",m,r,f),g.target=b,g.relatedTarget=x,S=g),x=S,h&&m)t:{for(g=h,y=m,v=0,b=g;b;b=Bi(b))v++;for(b=0,S=y;S;S=Bi(S))b++;for(;0<v-b;)g=Bi(g),v--;for(;0<b-v;)y=Bi(y),b--;for(;v--;){if(g===y||y!==null&&g===y.alternate)break t;g=Bi(g),y=Bi(y)}g=null}else g=null;h!==null&&gg(d,p,h,g,!1),m!==null&&x!==null&&gg(d,x,m,g,!0)}}e:{if(p=u?Xi(u):window,h=p.nodeName&&p.nodeName.toLowerCase(),h==="select"||h==="input"&&p.type==="file")var w=a2;else if(cg(p))if(uj)w=u2;else{w=s2;var j=o2}else(h=p.nodeName)&&h.toLowerCase()==="input"&&(p.type==="checkbox"||p.type==="radio")&&(w=l2);if(w&&(w=w(e,u))){lj(d,w,r,f);break e}j&&j(e,p,u),e==="focusout"&&(j=p._wrapperState)&&j.controlled&&p.type==="number"&&xp(p,"number",p.value)}switch(j=u?Xi(u):window,e){case"focusin":(cg(j)||j.contentEditable==="true")&&(Yi=j,Ep=u,Ho=null);break;case"focusout":Ho=Ep=Yi=null;break;case"mousedown":Tp=!0;break;case"contextmenu":case"mouseup":case"dragend":Tp=!1,mg(d,r,f);break;case"selectionchange":if(d2)break;case"keydown":case"keyup":mg(d,r,f)}var O;if(rv)e:{switch(e){case"compositionstart":var _="onCompositionStart";break e;case"compositionend":_="onCompositionEnd";break e;case"compositionupdate":_="onCompositionUpdate";break e}_=void 0}else Gi?oj(e,r)&&(_="onCompositionEnd"):e==="keydown"&&r.keyCode===229&&(_="onCompositionStart");_&&(aj&&r.locale!=="ko"&&(Gi||_!=="onCompositionStart"?_==="onCompositionEnd"&&Gi&&(O=ij()):(xn=f,Jm="value"in xn?xn.value:xn.textContent,Gi=!0)),j=Su(u,_),0<j.length&&(_=new og(_,e,null,r,f),d.push({event:_,listeners:j}),O?_.data=O:(O=sj(r),O!==null&&(_.data=O)))),(O=e2?t2(e,r):r2(e,r))&&(u=Su(u,"onBeforeInput"),0<u.length&&(f=new og("onBeforeInput","beforeinput",null,r,f),d.push({event:f,listeners:u}),f.data=O))}xj(d,t)})}function hs(e,t,r){return{instance:e,listener:t,currentTarget:r}}function Su(e,t){for(var r=t+"Capture",n=[];e!==null;){var i=e,a=i.stateNode;i.tag===5&&a!==null&&(i=a,a=ss(e,r),a!=null&&n.unshift(hs(e,a,i)),a=ss(e,t),a!=null&&n.push(hs(e,a,i))),e=e.return}return n}function Bi(e){if(e===null)return null;do e=e.return;while(e&&e.tag!==5);return e||null}function gg(e,t,r,n,i){for(var a=t._reactName,o=[];r!==null&&r!==n;){var s=r,l=s.alternate,u=s.stateNode;if(l!==null&&l===n)break;s.tag===5&&u!==null&&(s=u,i?(l=ss(r,a),l!=null&&o.unshift(hs(r,l,s))):i||(l=ss(r,a),l!=null&&o.push(hs(r,l,s)))),r=r.return}o.length!==0&&e.push({event:t,listeners:o})}var v2=/\r\n?/g,y2=/\u0000|\uFFFD/g;function xg(e){return(typeof e=="string"?e:""+e).replace(v2,`
-`).replace(y2,"")}function Ml(e,t,r){if(t=xg(t),xg(e)!==t&&r)throw Error(H(425))}function Ou(){}var Cp=null,Mp=null;function Ip(e,t){return e==="textarea"||e==="noscript"||typeof t.children=="string"||typeof t.children=="number"||typeof t.dangerouslySetInnerHTML=="object"&&t.dangerouslySetInnerHTML!==null&&t.dangerouslySetInnerHTML.__html!=null}var Lp=typeof setTimeout=="function"?setTimeout:void 0,g2=typeof clearTimeout=="function"?clearTimeout:void 0,bg=typeof Promise=="function"?Promise:void 0,x2=typeof queueMicrotask=="function"?queueMicrotask:typeof bg<"u"?function(e){return bg.resolve(null).then(e).catch(b2)}:Lp;function b2(e){setTimeout(function(){throw e})}function wd(e,t){var r=t,n=0;do{var i=r.nextSibling;if(e.removeChild(r),i&&i.nodeType===8)if(r=i.data,r==="/$"){if(n===0){e.removeChild(i),cs(t);return}n--}else r!=="$"&&r!=="$?"&&r!=="$!"||n++;r=i}while(r);cs(t)}function Nn(e){for(;e!=null;e=e.nextSibling){var t=e.nodeType;if(t===1||t===3)break;if(t===8){if(t=e.data,t==="$"||t==="$!"||t==="$?")break;if(t==="/$")return null}}return e}function wg(e){e=e.previousSibling;for(var t=0;e;){if(e.nodeType===8){var r=e.data;if(r==="$"||r==="$!"||r==="$?"){if(t===0)return e;t--}else r==="/$"&&t++}e=e.previousSibling}return null}var to=Math.random().toString(36).slice(2),kr="__reactFiber$"+to,ms="__reactProps$"+to,Qr="__reactContainer$"+to,Dp="__reactEvents$"+to,w2="__reactListeners$"+to,j2="__reactHandles$"+to;function li(e){var t=e[kr];if(t)return t;for(var r=e.parentNode;r;){if(t=r[Qr]||r[kr]){if(r=t.alternate,t.child!==null||r!==null&&r.child!==null)for(e=wg(e);e!==null;){if(r=e[kr])return r;e=wg(e)}return t}e=r,r=e.parentNode}return null}function ll(e){return e=e[kr]||e[Qr],!e||e.tag!==5&&e.tag!==6&&e.tag!==13&&e.tag!==3?null:e}function Xi(e){if(e.tag===5||e.tag===6)return e.stateNode;throw Error(H(33))}function Jc(e){return e[ms]||null}var Rp=[],Qi=-1;function Un(e){return{current:e}}function _e(e){0>Qi||(e.current=Rp[Qi],Rp[Qi]=null,Qi--)}function ge(e,t){Qi++,Rp[Qi]=e.current,e.current=t}var Rn={},mt=Un(Rn),Nt=Un(!1),wi=Rn;function ga(e,t){var r=e.type.contextTypes;if(!r)return Rn;var n=e.stateNode;if(n&&n.__reactInternalMemoizedUnmaskedChildContext===t)return n.__reactInternalMemoizedMaskedChildContext;var i={},a;for(a in r)i[a]=t[a];return n&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=i),i}function $t(e){return e=e.childContextTypes,e!=null}function _u(){_e(Nt),_e(mt)}function jg(e,t,r){if(mt.current!==Rn)throw Error(H(168));ge(mt,t),ge(Nt,r)}function wj(e,t,r){var n=e.stateNode;if(t=t.childContextTypes,typeof n.getChildContext!="function")return r;n=n.getChildContext();for(var i in n)if(!(i in t))throw Error(H(108,oA(e)||"Unknown",i));return Te({},r,n)}function Pu(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||Rn,wi=mt.current,ge(mt,e),ge(Nt,Nt.current),!0}function Sg(e,t,r){var n=e.stateNode;if(!n)throw Error(H(169));r?(e=wj(e,t,wi),n.__reactInternalMemoizedMergedChildContext=e,_e(Nt),_e(mt),ge(mt,e)):_e(Nt),ge(Nt,r)}var Fr=null,ef=!1,jd=!1;function jj(e){Fr===null?Fr=[e]:Fr.push(e)}function S2(e){ef=!0,jj(e)}function Kn(){if(!jd&&Fr!==null){jd=!0;var e=0,t=fe;try{var r=Fr;for(fe=1;e<r.length;e++){var n=r[e];do n=n(!0);while(n!==null)}Fr=null,ef=!1}catch(i){throw Fr!==null&&(Fr=Fr.slice(e+1)),Gw(qm,Kn),i}finally{fe=t,jd=!1}}return null}var Zi=[],Ji=0,ku=null,Au=0,Qt=[],Zt=0,ji=null,zr=1,Wr="";function ri(e,t){Zi[Ji++]=Au,Zi[Ji++]=ku,ku=e,Au=t}function Sj(e,t,r){Qt[Zt++]=zr,Qt[Zt++]=Wr,Qt[Zt++]=ji,ji=e;var n=zr;e=Wr;var i=32-yr(n)-1;n&=~(1<<i),r+=1;var a=32-yr(t)+i;if(30<a){var o=i-i%5;a=(n&(1<<o)-1).toString(32),n>>=o,i-=o,zr=1<<32-yr(t)+i|r<<i|n,Wr=a+e}else zr=1<<a|r<<i|n,Wr=e}function iv(e){e.return!==null&&(ri(e,1),Sj(e,1,0))}function av(e){for(;e===ku;)ku=Zi[--Ji],Zi[Ji]=null,Au=Zi[--Ji],Zi[Ji]=null;for(;e===ji;)ji=Qt[--Zt],Qt[Zt]=null,Wr=Qt[--Zt],Qt[Zt]=null,zr=Qt[--Zt],Qt[Zt]=null}var zt=null,Ft=null,ke=!1,mr=null;function Oj(e,t){var r=er(5,null,null,0);r.elementType="DELETED",r.stateNode=t,r.return=e,t=e.deletions,t===null?(e.deletions=[r],e.flags|=16):t.push(r)}function Og(e,t){switch(e.tag){case 5:var r=e.type;return t=t.nodeType!==1||r.toLowerCase()!==t.nodeName.toLowerCase()?null:t,t!==null?(e.stateNode=t,zt=e,Ft=Nn(t.firstChild),!0):!1;case 6:return t=e.pendingProps===""||t.nodeType!==3?null:t,t!==null?(e.stateNode=t,zt=e,Ft=null,!0):!1;case 13:return t=t.nodeType!==8?null:t,t!==null?(r=ji!==null?{id:zr,overflow:Wr}:null,e.memoizedState={dehydrated:t,treeContext:r,retryLane:1073741824},r=er(18,null,null,0),r.stateNode=t,r.return=e,e.child=r,zt=e,Ft=null,!0):!1;default:return!1}}function Bp(e){return(e.mode&1)!==0&&(e.flags&128)===0}function Fp(e){if(ke){var t=Ft;if(t){var r=t;if(!Og(e,t)){if(Bp(e))throw Error(H(418));t=Nn(r.nextSibling);var n=zt;t&&Og(e,t)?Oj(n,r):(e.flags=e.flags&-4097|2,ke=!1,zt=e)}}else{if(Bp(e))throw Error(H(418));e.flags=e.flags&-4097|2,ke=!1,zt=e}}}function _g(e){for(e=e.return;e!==null&&e.tag!==5&&e.tag!==3&&e.tag!==13;)e=e.return;zt=e}function Il(e){if(e!==zt)return!1;if(!ke)return _g(e),ke=!0,!1;var t;if((t=e.tag!==3)&&!(t=e.tag!==5)&&(t=e.type,t=t!=="head"&&t!=="body"&&!Ip(e.type,e.memoizedProps)),t&&(t=Ft)){if(Bp(e))throw _j(),Error(H(418));for(;t;)Oj(e,t),t=Nn(t.nextSibling)}if(_g(e),e.tag===13){if(e=e.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(H(317));e:{for(e=e.nextSibling,t=0;e;){if(e.nodeType===8){var r=e.data;if(r==="/$"){if(t===0){Ft=Nn(e.nextSibling);break e}t--}else r!=="$"&&r!=="$!"&&r!=="$?"||t++}e=e.nextSibling}Ft=null}}else Ft=zt?Nn(e.stateNode.nextSibling):null;return!0}function _j(){for(var e=Ft;e;)e=Nn(e.nextSibling)}function xa(){Ft=zt=null,ke=!1}function ov(e){mr===null?mr=[e]:mr.push(e)}var O2=nn.ReactCurrentBatchConfig;function So(e,t,r){if(e=r.ref,e!==null&&typeof e!="function"&&typeof e!="object"){if(r._owner){if(r=r._owner,r){if(r.tag!==1)throw Error(H(309));var n=r.stateNode}if(!n)throw Error(H(147,e));var i=n,a=""+e;return t!==null&&t.ref!==null&&typeof t.ref=="function"&&t.ref._stringRef===a?t.ref:(t=function(o){var s=i.refs;o===null?delete s[a]:s[a]=o},t._stringRef=a,t)}if(typeof e!="string")throw Error(H(284));if(!r._owner)throw Error(H(290,e))}return e}function Ll(e,t){throw e=Object.prototype.toString.call(t),Error(H(31,e==="[object Object]"?"object with keys {"+Object.keys(t).join(", ")+"}":e))}function Pg(e){var t=e._init;return t(e._payload)}function Pj(e){function t(y,v){if(e){var b=y.deletions;b===null?(y.deletions=[v],y.flags|=16):b.push(v)}}function r(y,v){if(!e)return null;for(;v!==null;)t(y,v),v=v.sibling;return null}function n(y,v){for(y=new Map;v!==null;)v.key!==null?y.set(v.key,v):y.set(v.index,v),v=v.sibling;return y}function i(y,v){return y=Cn(y,v),y.index=0,y.sibling=null,y}function a(y,v,b){return y.index=b,e?(b=y.alternate,b!==null?(b=b.index,b<v?(y.flags|=2,v):b):(y.flags|=2,v)):(y.flags|=1048576,v)}function o(y){return e&&y.alternate===null&&(y.flags|=2),y}function s(y,v,b,S){return v===null||v.tag!==6?(v=Nd(b,y.mode,S),v.return=y,v):(v=i(v,b),v.return=y,v)}function l(y,v,b,S){var w=b.type;return w===Vi?f(y,v,b.props.children,S,b.key):v!==null&&(v.elementType===w||typeof w=="object"&&w!==null&&w.$$typeof===pn&&Pg(w)===v.type)?(S=i(v,b.props),S.ref=So(y,v,b),S.return=y,S):(S=hu(b.type,b.key,b.props,null,y.mode,S),S.ref=So(y,v,b),S.return=y,S)}function u(y,v,b,S){return v===null||v.tag!==4||v.stateNode.containerInfo!==b.containerInfo||v.stateNode.implementation!==b.implementation?(v=$d(b,y.mode,S),v.return=y,v):(v=i(v,b.children||[]),v.return=y,v)}function f(y,v,b,S,w){return v===null||v.tag!==7?(v=yi(b,y.mode,S,w),v.return=y,v):(v=i(v,b),v.return=y,v)}function d(y,v,b){if(typeof v=="string"&&v!==""||typeof v=="number")return v=Nd(""+v,y.mode,b),v.return=y,v;if(typeof v=="object"&&v!==null){switch(v.$$typeof){case _l:return b=hu(v.type,v.key,v.props,null,y.mode,b),b.ref=So(y,null,v),b.return=y,b;case Hi:return v=$d(v,y.mode,b),v.return=y,v;case pn:var S=v._init;return d(y,S(v._payload),b)}if(Do(v)||go(v))return v=yi(v,y.mode,b,null),v.return=y,v;Ll(y,v)}return null}function p(y,v,b,S){var w=v!==null?v.key:null;if(typeof b=="string"&&b!==""||typeof b=="number")return w!==null?null:s(y,v,""+b,S);if(typeof b=="object"&&b!==null){switch(b.$$typeof){case _l:return b.key===w?l(y,v,b,S):null;case Hi:return b.key===w?u(y,v,b,S):null;case pn:return w=b._init,p(y,v,w(b._payload),S)}if(Do(b)||go(b))return w!==null?null:f(y,v,b,S,null);Ll(y,b)}return null}function h(y,v,b,S,w){if(typeof S=="string"&&S!==""||typeof S=="number")return y=y.get(b)||null,s(v,y,""+S,w);if(typeof S=="object"&&S!==null){switch(S.$$typeof){case _l:return y=y.get(S.key===null?b:S.key)||null,l(v,y,S,w);case Hi:return y=y.get(S.key===null?b:S.key)||null,u(v,y,S,w);case pn:var j=S._init;return h(y,v,b,j(S._payload),w)}if(Do(S)||go(S))return y=y.get(b)||null,f(v,y,S,w,null);Ll(v,S)}return null}function m(y,v,b,S){for(var w=null,j=null,O=v,_=v=0,P=null;O!==null&&_<b.length;_++){O.index>_?(P=O,O=null):P=O.sibling;var N=p(y,O,b[_],S);if(N===null){O===null&&(O=P);break}e&&O&&N.alternate===null&&t(y,O),v=a(N,v,_),j===null?w=N:j.sibling=N,j=N,O=P}if(_===b.length)return r(y,O),ke&&ri(y,_),w;if(O===null){for(;_<b.length;_++)O=d(y,b[_],S),O!==null&&(v=a(O,v,_),j===null?w=O:j.sibling=O,j=O);return ke&&ri(y,_),w}for(O=n(y,O);_<b.length;_++)P=h(O,y,_,b[_],S),P!==null&&(e&&P.alternate!==null&&O.delete(P.key===null?_:P.key),v=a(P,v,_),j===null?w=P:j.sibling=P,j=P);return e&&O.forEach(function(T){return t(y,T)}),ke&&ri(y,_),w}function g(y,v,b,S){var w=go(b);if(typeof w!="function")throw Error(H(150));if(b=w.call(b),b==null)throw Error(H(151));for(var j=w=null,O=v,_=v=0,P=null,N=b.next();O!==null&&!N.done;_++,N=b.next()){O.index>_?(P=O,O=null):P=O.sibling;var T=p(y,O,N.value,S);if(T===null){O===null&&(O=P);break}e&&O&&T.alternate===null&&t(y,O),v=a(T,v,_),j===null?w=T:j.sibling=T,j=T,O=P}if(N.done)return r(y,O),ke&&ri(y,_),w;if(O===null){for(;!N.done;_++,N=b.next())N=d(y,N.value,S),N!==null&&(v=a(N,v,_),j===null?w=N:j.sibling=N,j=N);return ke&&ri(y,_),w}for(O=n(y,O);!N.done;_++,N=b.next())N=h(O,y,_,N.value,S),N!==null&&(e&&N.alternate!==null&&O.delete(N.key===null?_:N.key),v=a(N,v,_),j===null?w=N:j.sibling=N,j=N);return e&&O.forEach(function($){return t(y,$)}),ke&&ri(y,_),w}function x(y,v,b,S){if(typeof b=="object"&&b!==null&&b.type===Vi&&b.key===null&&(b=b.props.children),typeof b=="object"&&b!==null){switch(b.$$typeof){case _l:e:{for(var w=b.key,j=v;j!==null;){if(j.key===w){if(w=b.type,w===Vi){if(j.tag===7){r(y,j.sibling),v=i(j,b.props.children),v.return=y,y=v;break e}}else if(j.elementType===w||typeof w=="object"&&w!==null&&w.$$typeof===pn&&Pg(w)===j.type){r(y,j.sibling),v=i(j,b.props),v.ref=So(y,j,b),v.return=y,y=v;break e}r(y,j);break}else t(y,j);j=j.sibling}b.type===Vi?(v=yi(b.props.children,y.mode,S,b.key),v.return=y,y=v):(S=hu(b.type,b.key,b.props,null,y.mode,S),S.ref=So(y,v,b),S.return=y,y=S)}return o(y);case Hi:e:{for(j=b.key;v!==null;){if(v.key===j)if(v.tag===4&&v.stateNode.containerInfo===b.containerInfo&&v.stateNode.implementation===b.implementation){r(y,v.sibling),v=i(v,b.children||[]),v.return=y,y=v;break e}else{r(y,v);break}else t(y,v);v=v.sibling}v=$d(b,y.mode,S),v.return=y,y=v}return o(y);case pn:return j=b._init,x(y,v,j(b._payload),S)}if(Do(b))return m(y,v,b,S);if(go(b))return g(y,v,b,S);Ll(y,b)}return typeof b=="string"&&b!==""||typeof b=="number"?(b=""+b,v!==null&&v.tag===6?(r(y,v.sibling),v=i(v,b),v.return=y,y=v):(r(y,v),v=Nd(b,y.mode,S),v.return=y,y=v),o(y)):r(y,v)}return x}var ba=Pj(!0),kj=Pj(!1),Nu=Un(null),$u=null,ea=null,sv=null;function lv(){sv=ea=$u=null}function uv(e){var t=Nu.current;_e(Nu),e._currentValue=t}function zp(e,t,r){for(;e!==null;){var n=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,n!==null&&(n.childLanes|=t)):n!==null&&(n.childLanes&t)!==t&&(n.childLanes|=t),e===r)break;e=e.return}}function da(e,t){$u=e,sv=ea=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(kt=!0),e.firstContext=null)}function nr(e){var t=e._currentValue;if(sv!==e)if(e={context:e,memoizedValue:t,next:null},ea===null){if($u===null)throw Error(H(308));ea=e,$u.dependencies={lanes:0,firstContext:e}}else ea=ea.next=e;return t}var ui=null;function cv(e){ui===null?ui=[e]:ui.push(e)}function Aj(e,t,r,n){var i=t.interleaved;return i===null?(r.next=r,cv(t)):(r.next=i.next,i.next=r),t.interleaved=r,Zr(e,n)}function Zr(e,t){e.lanes|=t;var r=e.alternate;for(r!==null&&(r.lanes|=t),r=e,e=e.return;e!==null;)e.childLanes|=t,r=e.alternate,r!==null&&(r.childLanes|=t),r=e,e=e.return;return r.tag===3?r.stateNode:null}var hn=!1;function fv(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Nj(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function Vr(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function $n(e,t,r){var n=e.updateQueue;if(n===null)return null;if(n=n.shared,le&2){var i=n.pending;return i===null?t.next=t:(t.next=i.next,i.next=t),n.pending=t,Zr(e,r)}return i=n.interleaved,i===null?(t.next=t,cv(n)):(t.next=i.next,i.next=t),n.interleaved=t,Zr(e,r)}function lu(e,t,r){if(t=t.updateQueue,t!==null&&(t=t.shared,(r&4194240)!==0)){var n=t.lanes;n&=e.pendingLanes,r|=n,t.lanes=r,Xm(e,r)}}function kg(e,t){var r=e.updateQueue,n=e.alternate;if(n!==null&&(n=n.updateQueue,r===n)){var i=null,a=null;if(r=r.firstBaseUpdate,r!==null){do{var o={eventTime:r.eventTime,lane:r.lane,tag:r.tag,payload:r.payload,callback:r.callback,next:null};a===null?i=a=o:a=a.next=o,r=r.next}while(r!==null);a===null?i=a=t:a=a.next=t}else i=a=t;r={baseState:n.baseState,firstBaseUpdate:i,lastBaseUpdate:a,shared:n.shared,effects:n.effects},e.updateQueue=r;return}e=r.lastBaseUpdate,e===null?r.firstBaseUpdate=t:e.next=t,r.lastBaseUpdate=t}function Eu(e,t,r,n){var i=e.updateQueue;hn=!1;var a=i.firstBaseUpdate,o=i.lastBaseUpdate,s=i.shared.pending;if(s!==null){i.shared.pending=null;var l=s,u=l.next;l.next=null,o===null?a=u:o.next=u,o=l;var f=e.alternate;f!==null&&(f=f.updateQueue,s=f.lastBaseUpdate,s!==o&&(s===null?f.firstBaseUpdate=u:s.next=u,f.lastBaseUpdate=l))}if(a!==null){var d=i.baseState;o=0,f=u=l=null,s=a;do{var p=s.lane,h=s.eventTime;if((n&p)===p){f!==null&&(f=f.next={eventTime:h,lane:0,tag:s.tag,payload:s.payload,callback:s.callback,next:null});e:{var m=e,g=s;switch(p=t,h=r,g.tag){case 1:if(m=g.payload,typeof m=="function"){d=m.call(h,d,p);break e}d=m;break e;case 3:m.flags=m.flags&-65537|128;case 0:if(m=g.payload,p=typeof m=="function"?m.call(h,d,p):m,p==null)break e;d=Te({},d,p);break e;case 2:hn=!0}}s.callback!==null&&s.lane!==0&&(e.flags|=64,p=i.effects,p===null?i.effects=[s]:p.push(s))}else h={eventTime:h,lane:p,tag:s.tag,payload:s.payload,callback:s.callback,next:null},f===null?(u=f=h,l=d):f=f.next=h,o|=p;if(s=s.next,s===null){if(s=i.shared.pending,s===null)break;p=s,s=p.next,p.next=null,i.lastBaseUpdate=p,i.shared.pending=null}}while(!0);if(f===null&&(l=d),i.baseState=l,i.firstBaseUpdate=u,i.lastBaseUpdate=f,t=i.shared.interleaved,t!==null){i=t;do o|=i.lane,i=i.next;while(i!==t)}else a===null&&(i.shared.lanes=0);Oi|=o,e.lanes=o,e.memoizedState=d}}function Ag(e,t,r){if(e=t.effects,t.effects=null,e!==null)for(t=0;t<e.length;t++){var n=e[t],i=n.callback;if(i!==null){if(n.callback=null,n=r,typeof i!="function")throw Error(H(191,i));i.call(n)}}}var ul={},Er=Un(ul),vs=Un(ul),ys=Un(ul);function ci(e){if(e===ul)throw Error(H(174));return e}function dv(e,t){switch(ge(ys,t),ge(vs,e),ge(Er,ul),e=t.nodeType,e){case 9:case 11:t=(t=t.documentElement)?t.namespaceURI:wp(null,"");break;default:e=e===8?t.parentNode:t,t=e.namespaceURI||null,e=e.tagName,t=wp(t,e)}_e(Er),ge(Er,t)}function wa(){_e(Er),_e(vs),_e(ys)}function $j(e){ci(ys.current);var t=ci(Er.current),r=wp(t,e.type);t!==r&&(ge(vs,e),ge(Er,r))}function pv(e){vs.current===e&&(_e(Er),_e(vs))}var Ne=Un(0);function Tu(e){for(var t=e;t!==null;){if(t.tag===13){var r=t.memoizedState;if(r!==null&&(r=r.dehydrated,r===null||r.data==="$?"||r.data==="$!"))return t}else if(t.tag===19&&t.memoizedProps.revealOrder!==void 0){if(t.flags&128)return t}else if(t.child!==null){t.child.return=t,t=t.child;continue}if(t===e)break;for(;t.sibling===null;){if(t.return===null||t.return===e)return null;t=t.return}t.sibling.return=t.return,t=t.sibling}return null}var Sd=[];function hv(){for(var e=0;e<Sd.length;e++)Sd[e]._workInProgressVersionPrimary=null;Sd.length=0}var uu=nn.ReactCurrentDispatcher,Od=nn.ReactCurrentBatchConfig,Si=0,Ee=null,Ye=null,Je=null,Cu=!1,Vo=!1,gs=0,_2=0;function lt(){throw Error(H(321))}function mv(e,t){if(t===null)return!1;for(var r=0;r<t.length&&r<e.length;r++)if(!wr(e[r],t[r]))return!1;return!0}function vv(e,t,r,n,i,a){if(Si=a,Ee=t,t.memoizedState=null,t.updateQueue=null,t.lanes=0,uu.current=e===null||e.memoizedState===null?N2:$2,e=r(n,i),Vo){a=0;do{if(Vo=!1,gs=0,25<=a)throw Error(H(301));a+=1,Je=Ye=null,t.updateQueue=null,uu.current=E2,e=r(n,i)}while(Vo)}if(uu.current=Mu,t=Ye!==null&&Ye.next!==null,Si=0,Je=Ye=Ee=null,Cu=!1,t)throw Error(H(300));return e}function yv(){var e=gs!==0;return gs=0,e}function Pr(){var e={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return Je===null?Ee.memoizedState=Je=e:Je=Je.next=e,Je}function ir(){if(Ye===null){var e=Ee.alternate;e=e!==null?e.memoizedState:null}else e=Ye.next;var t=Je===null?Ee.memoizedState:Je.next;if(t!==null)Je=t,Ye=e;else{if(e===null)throw Error(H(310));Ye=e,e={memoizedState:Ye.memoizedState,baseState:Ye.baseState,baseQueue:Ye.baseQueue,queue:Ye.queue,next:null},Je===null?Ee.memoizedState=Je=e:Je=Je.next=e}return Je}function xs(e,t){return typeof t=="function"?t(e):t}function _d(e){var t=ir(),r=t.queue;if(r===null)throw Error(H(311));r.lastRenderedReducer=e;var n=Ye,i=n.baseQueue,a=r.pending;if(a!==null){if(i!==null){var o=i.next;i.next=a.next,a.next=o}n.baseQueue=i=a,r.pending=null}if(i!==null){a=i.next,n=n.baseState;var s=o=null,l=null,u=a;do{var f=u.lane;if((Si&f)===f)l!==null&&(l=l.next={lane:0,action:u.action,hasEagerState:u.hasEagerState,eagerState:u.eagerState,next:null}),n=u.hasEagerState?u.eagerState:e(n,u.action);else{var d={lane:f,action:u.action,hasEagerState:u.hasEagerState,eagerState:u.eagerState,next:null};l===null?(s=l=d,o=n):l=l.next=d,Ee.lanes|=f,Oi|=f}u=u.next}while(u!==null&&u!==a);l===null?o=n:l.next=s,wr(n,t.memoizedState)||(kt=!0),t.memoizedState=n,t.baseState=o,t.baseQueue=l,r.lastRenderedState=n}if(e=r.interleaved,e!==null){i=e;do a=i.lane,Ee.lanes|=a,Oi|=a,i=i.next;while(i!==e)}else i===null&&(r.lanes=0);return[t.memoizedState,r.dispatch]}function Pd(e){var t=ir(),r=t.queue;if(r===null)throw Error(H(311));r.lastRenderedReducer=e;var n=r.dispatch,i=r.pending,a=t.memoizedState;if(i!==null){r.pending=null;var o=i=i.next;do a=e(a,o.action),o=o.next;while(o!==i);wr(a,t.memoizedState)||(kt=!0),t.memoizedState=a,t.baseQueue===null&&(t.baseState=a),r.lastRenderedState=a}return[a,n]}function Ej(){}function Tj(e,t){var r=Ee,n=ir(),i=t(),a=!wr(n.memoizedState,i);if(a&&(n.memoizedState=i,kt=!0),n=n.queue,gv(Ij.bind(null,r,n,e),[e]),n.getSnapshot!==t||a||Je!==null&&Je.memoizedState.tag&1){if(r.flags|=2048,bs(9,Mj.bind(null,r,n,i,t),void 0,null),rt===null)throw Error(H(349));Si&30||Cj(r,t,i)}return i}function Cj(e,t,r){e.flags|=16384,e={getSnapshot:t,value:r},t=Ee.updateQueue,t===null?(t={lastEffect:null,stores:null},Ee.updateQueue=t,t.stores=[e]):(r=t.stores,r===null?t.stores=[e]:r.push(e))}function Mj(e,t,r,n){t.value=r,t.getSnapshot=n,Lj(t)&&Dj(e)}function Ij(e,t,r){return r(function(){Lj(t)&&Dj(e)})}function Lj(e){var t=e.getSnapshot;e=e.value;try{var r=t();return!wr(e,r)}catch{return!0}}function Dj(e){var t=Zr(e,1);t!==null&&gr(t,e,1,-1)}function Ng(e){var t=Pr();return typeof e=="function"&&(e=e()),t.memoizedState=t.baseState=e,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:xs,lastRenderedState:e},t.queue=e,e=e.dispatch=A2.bind(null,Ee,e),[t.memoizedState,e]}function bs(e,t,r,n){return e={tag:e,create:t,destroy:r,deps:n,next:null},t=Ee.updateQueue,t===null?(t={lastEffect:null,stores:null},Ee.updateQueue=t,t.lastEffect=e.next=e):(r=t.lastEffect,r===null?t.lastEffect=e.next=e:(n=r.next,r.next=e,e.next=n,t.lastEffect=e)),e}function Rj(){return ir().memoizedState}function cu(e,t,r,n){var i=Pr();Ee.flags|=e,i.memoizedState=bs(1|t,r,void 0,n===void 0?null:n)}function tf(e,t,r,n){var i=ir();n=n===void 0?null:n;var a=void 0;if(Ye!==null){var o=Ye.memoizedState;if(a=o.destroy,n!==null&&mv(n,o.deps)){i.memoizedState=bs(t,r,a,n);return}}Ee.flags|=e,i.memoizedState=bs(1|t,r,a,n)}function $g(e,t){return cu(8390656,8,e,t)}function gv(e,t){return tf(2048,8,e,t)}function Bj(e,t){return tf(4,2,e,t)}function Fj(e,t){return tf(4,4,e,t)}function zj(e,t){if(typeof t=="function")return e=e(),t(e),function(){t(null)};if(t!=null)return e=e(),t.current=e,function(){t.current=null}}function Wj(e,t,r){return r=r!=null?r.concat([e]):null,tf(4,4,zj.bind(null,t,e),r)}function xv(){}function Uj(e,t){var r=ir();t=t===void 0?null:t;var n=r.memoizedState;return n!==null&&t!==null&&mv(t,n[1])?n[0]:(r.memoizedState=[e,t],e)}function Kj(e,t){var r=ir();t=t===void 0?null:t;var n=r.memoizedState;return n!==null&&t!==null&&mv(t,n[1])?n[0]:(e=e(),r.memoizedState=[e,t],e)}function Hj(e,t,r){return Si&21?(wr(r,t)||(r=Xw(),Ee.lanes|=r,Oi|=r,e.baseState=!0),t):(e.baseState&&(e.baseState=!1,kt=!0),e.memoizedState=r)}function P2(e,t){var r=fe;fe=r!==0&&4>r?r:4,e(!0);var n=Od.transition;Od.transition={};try{e(!1),t()}finally{fe=r,Od.transition=n}}function Vj(){return ir().memoizedState}function k2(e,t,r){var n=Tn(e);if(r={lane:n,action:r,hasEagerState:!1,eagerState:null,next:null},Gj(e))Yj(t,r);else if(r=Aj(e,t,r,n),r!==null){var i=bt();gr(r,e,n,i),qj(r,t,n)}}function A2(e,t,r){var n=Tn(e),i={lane:n,action:r,hasEagerState:!1,eagerState:null,next:null};if(Gj(e))Yj(t,i);else{var a=e.alternate;if(e.lanes===0&&(a===null||a.lanes===0)&&(a=t.lastRenderedReducer,a!==null))try{var o=t.lastRenderedState,s=a(o,r);if(i.hasEagerState=!0,i.eagerState=s,wr(s,o)){var l=t.interleaved;l===null?(i.next=i,cv(t)):(i.next=l.next,l.next=i),t.interleaved=i;return}}catch{}finally{}r=Aj(e,t,i,n),r!==null&&(i=bt(),gr(r,e,n,i),qj(r,t,n))}}function Gj(e){var t=e.alternate;return e===Ee||t!==null&&t===Ee}function Yj(e,t){Vo=Cu=!0;var r=e.pending;r===null?t.next=t:(t.next=r.next,r.next=t),e.pending=t}function qj(e,t,r){if(r&4194240){var n=t.lanes;n&=e.pendingLanes,r|=n,t.lanes=r,Xm(e,r)}}var Mu={readContext:nr,useCallback:lt,useContext:lt,useEffect:lt,useImperativeHandle:lt,useInsertionEffect:lt,useLayoutEffect:lt,useMemo:lt,useReducer:lt,useRef:lt,useState:lt,useDebugValue:lt,useDeferredValue:lt,useTransition:lt,useMutableSource:lt,useSyncExternalStore:lt,useId:lt,unstable_isNewReconciler:!1},N2={readContext:nr,useCallback:function(e,t){return Pr().memoizedState=[e,t===void 0?null:t],e},useContext:nr,useEffect:$g,useImperativeHandle:function(e,t,r){return r=r!=null?r.concat([e]):null,cu(4194308,4,zj.bind(null,t,e),r)},useLayoutEffect:function(e,t){return cu(4194308,4,e,t)},useInsertionEffect:function(e,t){return cu(4,2,e,t)},useMemo:function(e,t){var r=Pr();return t=t===void 0?null:t,e=e(),r.memoizedState=[e,t],e},useReducer:function(e,t,r){var n=Pr();return t=r!==void 0?r(t):t,n.memoizedState=n.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},n.queue=e,e=e.dispatch=k2.bind(null,Ee,e),[n.memoizedState,e]},useRef:function(e){var t=Pr();return e={current:e},t.memoizedState=e},useState:Ng,useDebugValue:xv,useDeferredValue:function(e){return Pr().memoizedState=e},useTransition:function(){var e=Ng(!1),t=e[0];return e=P2.bind(null,e[1]),Pr().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,r){var n=Ee,i=Pr();if(ke){if(r===void 0)throw Error(H(407));r=r()}else{if(r=t(),rt===null)throw Error(H(349));Si&30||Cj(n,t,r)}i.memoizedState=r;var a={value:r,getSnapshot:t};return i.queue=a,$g(Ij.bind(null,n,a,e),[e]),n.flags|=2048,bs(9,Mj.bind(null,n,a,r,t),void 0,null),r},useId:function(){var e=Pr(),t=rt.identifierPrefix;if(ke){var r=Wr,n=zr;r=(n&~(1<<32-yr(n)-1)).toString(32)+r,t=":"+t+"R"+r,r=gs++,0<r&&(t+="H"+r.toString(32)),t+=":"}else r=_2++,t=":"+t+"r"+r.toString(32)+":";return e.memoizedState=t},unstable_isNewReconciler:!1},$2={readContext:nr,useCallback:Uj,useContext:nr,useEffect:gv,useImperativeHandle:Wj,useInsertionEffect:Bj,useLayoutEffect:Fj,useMemo:Kj,useReducer:_d,useRef:Rj,useState:function(){return _d(xs)},useDebugValue:xv,useDeferredValue:function(e){var t=ir();return Hj(t,Ye.memoizedState,e)},useTransition:function(){var e=_d(xs)[0],t=ir().memoizedState;return[e,t]},useMutableSource:Ej,useSyncExternalStore:Tj,useId:Vj,unstable_isNewReconciler:!1},E2={readContext:nr,useCallback:Uj,useContext:nr,useEffect:gv,useImperativeHandle:Wj,useInsertionEffect:Bj,useLayoutEffect:Fj,useMemo:Kj,useReducer:Pd,useRef:Rj,useState:function(){return Pd(xs)},useDebugValue:xv,useDeferredValue:function(e){var t=ir();return Ye===null?t.memoizedState=e:Hj(t,Ye.memoizedState,e)},useTransition:function(){var e=Pd(xs)[0],t=ir().memoizedState;return[e,t]},useMutableSource:Ej,useSyncExternalStore:Tj,useId:Vj,unstable_isNewReconciler:!1};function fr(e,t){if(e&&e.defaultProps){t=Te({},t),e=e.defaultProps;for(var r in e)t[r]===void 0&&(t[r]=e[r]);return t}return t}function Wp(e,t,r,n){t=e.memoizedState,r=r(n,t),r=r==null?t:Te({},t,r),e.memoizedState=r,e.lanes===0&&(e.updateQueue.baseState=r)}var rf={isMounted:function(e){return(e=e._reactInternals)?Ti(e)===e:!1},enqueueSetState:function(e,t,r){e=e._reactInternals;var n=bt(),i=Tn(e),a=Vr(n,i);a.payload=t,r!=null&&(a.callback=r),t=$n(e,a,i),t!==null&&(gr(t,e,i,n),lu(t,e,i))},enqueueReplaceState:function(e,t,r){e=e._reactInternals;var n=bt(),i=Tn(e),a=Vr(n,i);a.tag=1,a.payload=t,r!=null&&(a.callback=r),t=$n(e,a,i),t!==null&&(gr(t,e,i,n),lu(t,e,i))},enqueueForceUpdate:function(e,t){e=e._reactInternals;var r=bt(),n=Tn(e),i=Vr(r,n);i.tag=2,t!=null&&(i.callback=t),t=$n(e,i,n),t!==null&&(gr(t,e,n,r),lu(t,e,n))}};function Eg(e,t,r,n,i,a,o){return e=e.stateNode,typeof e.shouldComponentUpdate=="function"?e.shouldComponentUpdate(n,a,o):t.prototype&&t.prototype.isPureReactComponent?!ds(r,n)||!ds(i,a):!0}function Xj(e,t,r){var n=!1,i=Rn,a=t.contextType;return typeof a=="object"&&a!==null?a=nr(a):(i=$t(t)?wi:mt.current,n=t.contextTypes,a=(n=n!=null)?ga(e,i):Rn),t=new t(r,a),e.memoizedState=t.state!==null&&t.state!==void 0?t.state:null,t.updater=rf,e.stateNode=t,t._reactInternals=e,n&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=i,e.__reactInternalMemoizedMaskedChildContext=a),t}function Tg(e,t,r,n){e=t.state,typeof t.componentWillReceiveProps=="function"&&t.componentWillReceiveProps(r,n),typeof t.UNSAFE_componentWillReceiveProps=="function"&&t.UNSAFE_componentWillReceiveProps(r,n),t.state!==e&&rf.enqueueReplaceState(t,t.state,null)}function Up(e,t,r,n){var i=e.stateNode;i.props=r,i.state=e.memoizedState,i.refs={},fv(e);var a=t.contextType;typeof a=="object"&&a!==null?i.context=nr(a):(a=$t(t)?wi:mt.current,i.context=ga(e,a)),i.state=e.memoizedState,a=t.getDerivedStateFromProps,typeof a=="function"&&(Wp(e,t,a,r),i.state=e.memoizedState),typeof t.getDerivedStateFromProps=="function"||typeof i.getSnapshotBeforeUpdate=="function"||typeof i.UNSAFE_componentWillMount!="function"&&typeof i.componentWillMount!="function"||(t=i.state,typeof i.componentWillMount=="function"&&i.componentWillMount(),typeof i.UNSAFE_componentWillMount=="function"&&i.UNSAFE_componentWillMount(),t!==i.state&&rf.enqueueReplaceState(i,i.state,null),Eu(e,r,i,n),i.state=e.memoizedState),typeof i.componentDidMount=="function"&&(e.flags|=4194308)}function ja(e,t){try{var r="",n=t;do r+=aA(n),n=n.return;while(n);var i=r}catch(a){i=`
-Error generating stack: `+a.message+`
-`+a.stack}return{value:e,source:t,stack:i,digest:null}}function kd(e,t,r){return{value:e,source:null,stack:r??null,digest:t??null}}function Kp(e,t){try{console.error(t.value)}catch(r){setTimeout(function(){throw r})}}var T2=typeof WeakMap=="function"?WeakMap:Map;function Qj(e,t,r){r=Vr(-1,r),r.tag=3,r.payload={element:null};var n=t.value;return r.callback=function(){Lu||(Lu=!0,eh=n),Kp(e,t)},r}function Zj(e,t,r){r=Vr(-1,r),r.tag=3;var n=e.type.getDerivedStateFromError;if(typeof n=="function"){var i=t.value;r.payload=function(){return n(i)},r.callback=function(){Kp(e,t)}}var a=e.stateNode;return a!==null&&typeof a.componentDidCatch=="function"&&(r.callback=function(){Kp(e,t),typeof n!="function"&&(En===null?En=new Set([this]):En.add(this));var o=t.stack;this.componentDidCatch(t.value,{componentStack:o!==null?o:""})}),r}function Cg(e,t,r){var n=e.pingCache;if(n===null){n=e.pingCache=new T2;var i=new Set;n.set(t,i)}else i=n.get(t),i===void 0&&(i=new Set,n.set(t,i));i.has(r)||(i.add(r),e=V2.bind(null,e,t,r),t.then(e,e))}function Mg(e){do{var t;if((t=e.tag===13)&&(t=e.memoizedState,t=t!==null?t.dehydrated!==null:!0),t)return e;e=e.return}while(e!==null);return null}function Ig(e,t,r,n,i){return e.mode&1?(e.flags|=65536,e.lanes=i,e):(e===t?e.flags|=65536:(e.flags|=128,r.flags|=131072,r.flags&=-52805,r.tag===1&&(r.alternate===null?r.tag=17:(t=Vr(-1,1),t.tag=2,$n(r,t,1))),r.lanes|=1),e)}var C2=nn.ReactCurrentOwner,kt=!1;function vt(e,t,r,n){t.child=e===null?kj(t,null,r,n):ba(t,e.child,r,n)}function Lg(e,t,r,n,i){r=r.render;var a=t.ref;return da(t,i),n=vv(e,t,r,n,a,i),r=yv(),e!==null&&!kt?(t.updateQueue=e.updateQueue,t.flags&=-2053,e.lanes&=~i,Jr(e,t,i)):(ke&&r&&iv(t),t.flags|=1,vt(e,t,n,i),t.child)}function Dg(e,t,r,n,i){if(e===null){var a=r.type;return typeof a=="function"&&!kv(a)&&a.defaultProps===void 0&&r.compare===null&&r.defaultProps===void 0?(t.tag=15,t.type=a,Jj(e,t,a,n,i)):(e=hu(r.type,null,n,t,t.mode,i),e.ref=t.ref,e.return=t,t.child=e)}if(a=e.child,!(e.lanes&i)){var o=a.memoizedProps;if(r=r.compare,r=r!==null?r:ds,r(o,n)&&e.ref===t.ref)return Jr(e,t,i)}return t.flags|=1,e=Cn(a,n),e.ref=t.ref,e.return=t,t.child=e}function Jj(e,t,r,n,i){if(e!==null){var a=e.memoizedProps;if(ds(a,n)&&e.ref===t.ref)if(kt=!1,t.pendingProps=n=a,(e.lanes&i)!==0)e.flags&131072&&(kt=!0);else return t.lanes=e.lanes,Jr(e,t,i)}return Hp(e,t,r,n,i)}function eS(e,t,r){var n=t.pendingProps,i=n.children,a=e!==null?e.memoizedState:null;if(n.mode==="hidden")if(!(t.mode&1))t.memoizedState={baseLanes:0,cachePool:null,transitions:null},ge(ra,Dt),Dt|=r;else{if(!(r&1073741824))return e=a!==null?a.baseLanes|r:r,t.lanes=t.childLanes=1073741824,t.memoizedState={baseLanes:e,cachePool:null,transitions:null},t.updateQueue=null,ge(ra,Dt),Dt|=e,null;t.memoizedState={baseLanes:0,cachePool:null,transitions:null},n=a!==null?a.baseLanes:r,ge(ra,Dt),Dt|=n}else a!==null?(n=a.baseLanes|r,t.memoizedState=null):n=r,ge(ra,Dt),Dt|=n;return vt(e,t,i,r),t.child}function tS(e,t){var r=t.ref;(e===null&&r!==null||e!==null&&e.ref!==r)&&(t.flags|=512,t.flags|=2097152)}function Hp(e,t,r,n,i){var a=$t(r)?wi:mt.current;return a=ga(t,a),da(t,i),r=vv(e,t,r,n,a,i),n=yv(),e!==null&&!kt?(t.updateQueue=e.updateQueue,t.flags&=-2053,e.lanes&=~i,Jr(e,t,i)):(ke&&n&&iv(t),t.flags|=1,vt(e,t,r,i),t.child)}function Rg(e,t,r,n,i){if($t(r)){var a=!0;Pu(t)}else a=!1;if(da(t,i),t.stateNode===null)fu(e,t),Xj(t,r,n),Up(t,r,n,i),n=!0;else if(e===null){var o=t.stateNode,s=t.memoizedProps;o.props=s;var l=o.context,u=r.contextType;typeof u=="object"&&u!==null?u=nr(u):(u=$t(r)?wi:mt.current,u=ga(t,u));var f=r.getDerivedStateFromProps,d=typeof f=="function"||typeof o.getSnapshotBeforeUpdate=="function";d||typeof o.UNSAFE_componentWillReceiveProps!="function"&&typeof o.componentWillReceiveProps!="function"||(s!==n||l!==u)&&Tg(t,o,n,u),hn=!1;var p=t.memoizedState;o.state=p,Eu(t,n,o,i),l=t.memoizedState,s!==n||p!==l||Nt.current||hn?(typeof f=="function"&&(Wp(t,r,f,n),l=t.memoizedState),(s=hn||Eg(t,r,s,n,p,l,u))?(d||typeof o.UNSAFE_componentWillMount!="function"&&typeof o.componentWillMount!="function"||(typeof o.componentWillMount=="function"&&o.componentWillMount(),typeof o.UNSAFE_componentWillMount=="function"&&o.UNSAFE_componentWillMount()),typeof o.componentDidMount=="function"&&(t.flags|=4194308)):(typeof o.componentDidMount=="function"&&(t.flags|=4194308),t.memoizedProps=n,t.memoizedState=l),o.props=n,o.state=l,o.context=u,n=s):(typeof o.componentDidMount=="function"&&(t.flags|=4194308),n=!1)}else{o=t.stateNode,Nj(e,t),s=t.memoizedProps,u=t.type===t.elementType?s:fr(t.type,s),o.props=u,d=t.pendingProps,p=o.context,l=r.contextType,typeof l=="object"&&l!==null?l=nr(l):(l=$t(r)?wi:mt.current,l=ga(t,l));var h=r.getDerivedStateFromProps;(f=typeof h=="function"||typeof o.getSnapshotBeforeUpdate=="function")||typeof o.UNSAFE_componentWillReceiveProps!="function"&&typeof o.componentWillReceiveProps!="function"||(s!==d||p!==l)&&Tg(t,o,n,l),hn=!1,p=t.memoizedState,o.state=p,Eu(t,n,o,i);var m=t.memoizedState;s!==d||p!==m||Nt.current||hn?(typeof h=="function"&&(Wp(t,r,h,n),m=t.memoizedState),(u=hn||Eg(t,r,u,n,p,m,l)||!1)?(f||typeof o.UNSAFE_componentWillUpdate!="function"&&typeof o.componentWillUpdate!="function"||(typeof o.componentWillUpdate=="function"&&o.componentWillUpdate(n,m,l),typeof o.UNSAFE_componentWillUpdate=="function"&&o.UNSAFE_componentWillUpdate(n,m,l)),typeof o.componentDidUpdate=="function"&&(t.flags|=4),typeof o.getSnapshotBeforeUpdate=="function"&&(t.flags|=1024)):(typeof o.componentDidUpdate!="function"||s===e.memoizedProps&&p===e.memoizedState||(t.flags|=4),typeof o.getSnapshotBeforeUpdate!="function"||s===e.memoizedProps&&p===e.memoizedState||(t.flags|=1024),t.memoizedProps=n,t.memoizedState=m),o.props=n,o.state=m,o.context=l,n=u):(typeof o.componentDidUpdate!="function"||s===e.memoizedProps&&p===e.memoizedState||(t.flags|=4),typeof o.getSnapshotBeforeUpdate!="function"||s===e.memoizedProps&&p===e.memoizedState||(t.flags|=1024),n=!1)}return Vp(e,t,r,n,a,i)}function Vp(e,t,r,n,i,a){tS(e,t);var o=(t.flags&128)!==0;if(!n&&!o)return i&&Sg(t,r,!1),Jr(e,t,a);n=t.stateNode,C2.current=t;var s=o&&typeof r.getDerivedStateFromError!="function"?null:n.render();return t.flags|=1,e!==null&&o?(t.child=ba(t,e.child,null,a),t.child=ba(t,null,s,a)):vt(e,t,s,a),t.memoizedState=n.state,i&&Sg(t,r,!0),t.child}function rS(e){var t=e.stateNode;t.pendingContext?jg(e,t.pendingContext,t.pendingContext!==t.context):t.context&&jg(e,t.context,!1),dv(e,t.containerInfo)}function Bg(e,t,r,n,i){return xa(),ov(i),t.flags|=256,vt(e,t,r,n),t.child}var Gp={dehydrated:null,treeContext:null,retryLane:0};function Yp(e){return{baseLanes:e,cachePool:null,transitions:null}}function nS(e,t,r){var n=t.pendingProps,i=Ne.current,a=!1,o=(t.flags&128)!==0,s;if((s=o)||(s=e!==null&&e.memoizedState===null?!1:(i&2)!==0),s?(a=!0,t.flags&=-129):(e===null||e.memoizedState!==null)&&(i|=1),ge(Ne,i&1),e===null)return Fp(t),e=t.memoizedState,e!==null&&(e=e.dehydrated,e!==null)?(t.mode&1?e.data==="$!"?t.lanes=8:t.lanes=1073741824:t.lanes=1,null):(o=n.children,e=n.fallback,a?(n=t.mode,a=t.child,o={mode:"hidden",children:o},!(n&1)&&a!==null?(a.childLanes=0,a.pendingProps=o):a=of(o,n,0,null),e=yi(e,n,r,null),a.return=t,e.return=t,a.sibling=e,t.child=a,t.child.memoizedState=Yp(r),t.memoizedState=Gp,e):bv(t,o));if(i=e.memoizedState,i!==null&&(s=i.dehydrated,s!==null))return M2(e,t,o,n,s,i,r);if(a){a=n.fallback,o=t.mode,i=e.child,s=i.sibling;var l={mode:"hidden",children:n.children};return!(o&1)&&t.child!==i?(n=t.child,n.childLanes=0,n.pendingProps=l,t.deletions=null):(n=Cn(i,l),n.subtreeFlags=i.subtreeFlags&14680064),s!==null?a=Cn(s,a):(a=yi(a,o,r,null),a.flags|=2),a.return=t,n.return=t,n.sibling=a,t.child=n,n=a,a=t.child,o=e.child.memoizedState,o=o===null?Yp(r):{baseLanes:o.baseLanes|r,cachePool:null,transitions:o.transitions},a.memoizedState=o,a.childLanes=e.childLanes&~r,t.memoizedState=Gp,n}return a=e.child,e=a.sibling,n=Cn(a,{mode:"visible",children:n.children}),!(t.mode&1)&&(n.lanes=r),n.return=t,n.sibling=null,e!==null&&(r=t.deletions,r===null?(t.deletions=[e],t.flags|=16):r.push(e)),t.child=n,t.memoizedState=null,n}function bv(e,t){return t=of({mode:"visible",children:t},e.mode,0,null),t.return=e,e.child=t}function Dl(e,t,r,n){return n!==null&&ov(n),ba(t,e.child,null,r),e=bv(t,t.pendingProps.children),e.flags|=2,t.memoizedState=null,e}function M2(e,t,r,n,i,a,o){if(r)return t.flags&256?(t.flags&=-257,n=kd(Error(H(422))),Dl(e,t,o,n)):t.memoizedState!==null?(t.child=e.child,t.flags|=128,null):(a=n.fallback,i=t.mode,n=of({mode:"visible",children:n.children},i,0,null),a=yi(a,i,o,null),a.flags|=2,n.return=t,a.return=t,n.sibling=a,t.child=n,t.mode&1&&ba(t,e.child,null,o),t.child.memoizedState=Yp(o),t.memoizedState=Gp,a);if(!(t.mode&1))return Dl(e,t,o,null);if(i.data==="$!"){if(n=i.nextSibling&&i.nextSibling.dataset,n)var s=n.dgst;return n=s,a=Error(H(419)),n=kd(a,n,void 0),Dl(e,t,o,n)}if(s=(o&e.childLanes)!==0,kt||s){if(n=rt,n!==null){switch(o&-o){case 4:i=2;break;case 16:i=8;break;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:i=32;break;case 536870912:i=268435456;break;default:i=0}i=i&(n.suspendedLanes|o)?0:i,i!==0&&i!==a.retryLane&&(a.retryLane=i,Zr(e,i),gr(n,e,i,-1))}return Pv(),n=kd(Error(H(421))),Dl(e,t,o,n)}return i.data==="$?"?(t.flags|=128,t.child=e.child,t=G2.bind(null,e),i._reactRetry=t,null):(e=a.treeContext,Ft=Nn(i.nextSibling),zt=t,ke=!0,mr=null,e!==null&&(Qt[Zt++]=zr,Qt[Zt++]=Wr,Qt[Zt++]=ji,zr=e.id,Wr=e.overflow,ji=t),t=bv(t,n.children),t.flags|=4096,t)}function Fg(e,t,r){e.lanes|=t;var n=e.alternate;n!==null&&(n.lanes|=t),zp(e.return,t,r)}function Ad(e,t,r,n,i){var a=e.memoizedState;a===null?e.memoizedState={isBackwards:t,rendering:null,renderingStartTime:0,last:n,tail:r,tailMode:i}:(a.isBackwards=t,a.rendering=null,a.renderingStartTime=0,a.last=n,a.tail=r,a.tailMode=i)}function iS(e,t,r){var n=t.pendingProps,i=n.revealOrder,a=n.tail;if(vt(e,t,n.children,r),n=Ne.current,n&2)n=n&1|2,t.flags|=128;else{if(e!==null&&e.flags&128)e:for(e=t.child;e!==null;){if(e.tag===13)e.memoizedState!==null&&Fg(e,r,t);else if(e.tag===19)Fg(e,r,t);else if(e.child!==null){e.child.return=e,e=e.child;continue}if(e===t)break e;for(;e.sibling===null;){if(e.return===null||e.return===t)break e;e=e.return}e.sibling.return=e.return,e=e.sibling}n&=1}if(ge(Ne,n),!(t.mode&1))t.memoizedState=null;else switch(i){case"forwards":for(r=t.child,i=null;r!==null;)e=r.alternate,e!==null&&Tu(e)===null&&(i=r),r=r.sibling;r=i,r===null?(i=t.child,t.child=null):(i=r.sibling,r.sibling=null),Ad(t,!1,i,r,a);break;case"backwards":for(r=null,i=t.child,t.child=null;i!==null;){if(e=i.alternate,e!==null&&Tu(e)===null){t.child=i;break}e=i.sibling,i.sibling=r,r=i,i=e}Ad(t,!0,r,null,a);break;case"together":Ad(t,!1,null,null,void 0);break;default:t.memoizedState=null}return t.child}function fu(e,t){!(t.mode&1)&&e!==null&&(e.alternate=null,t.alternate=null,t.flags|=2)}function Jr(e,t,r){if(e!==null&&(t.dependencies=e.dependencies),Oi|=t.lanes,!(r&t.childLanes))return null;if(e!==null&&t.child!==e.child)throw Error(H(153));if(t.child!==null){for(e=t.child,r=Cn(e,e.pendingProps),t.child=r,r.return=t;e.sibling!==null;)e=e.sibling,r=r.sibling=Cn(e,e.pendingProps),r.return=t;r.sibling=null}return t.child}function I2(e,t,r){switch(t.tag){case 3:rS(t),xa();break;case 5:$j(t);break;case 1:$t(t.type)&&Pu(t);break;case 4:dv(t,t.stateNode.containerInfo);break;case 10:var n=t.type._context,i=t.memoizedProps.value;ge(Nu,n._currentValue),n._currentValue=i;break;case 13:if(n=t.memoizedState,n!==null)return n.dehydrated!==null?(ge(Ne,Ne.current&1),t.flags|=128,null):r&t.child.childLanes?nS(e,t,r):(ge(Ne,Ne.current&1),e=Jr(e,t,r),e!==null?e.sibling:null);ge(Ne,Ne.current&1);break;case 19:if(n=(r&t.childLanes)!==0,e.flags&128){if(n)return iS(e,t,r);t.flags|=128}if(i=t.memoizedState,i!==null&&(i.rendering=null,i.tail=null,i.lastEffect=null),ge(Ne,Ne.current),n)break;return null;case 22:case 23:return t.lanes=0,eS(e,t,r)}return Jr(e,t,r)}var aS,qp,oS,sS;aS=function(e,t){for(var r=t.child;r!==null;){if(r.tag===5||r.tag===6)e.appendChild(r.stateNode);else if(r.tag!==4&&r.child!==null){r.child.return=r,r=r.child;continue}if(r===t)break;for(;r.sibling===null;){if(r.return===null||r.return===t)return;r=r.return}r.sibling.return=r.return,r=r.sibling}};qp=function(){};oS=function(e,t,r,n){var i=e.memoizedProps;if(i!==n){e=t.stateNode,ci(Er.current);var a=null;switch(r){case"input":i=yp(e,i),n=yp(e,n),a=[];break;case"select":i=Te({},i,{value:void 0}),n=Te({},n,{value:void 0}),a=[];break;case"textarea":i=bp(e,i),n=bp(e,n),a=[];break;default:typeof i.onClick!="function"&&typeof n.onClick=="function"&&(e.onclick=Ou)}jp(r,n);var o;r=null;for(u in i)if(!n.hasOwnProperty(u)&&i.hasOwnProperty(u)&&i[u]!=null)if(u==="style"){var s=i[u];for(o in s)s.hasOwnProperty(o)&&(r||(r={}),r[o]="")}else u!=="dangerouslySetInnerHTML"&&u!=="children"&&u!=="suppressContentEditableWarning"&&u!=="suppressHydrationWarning"&&u!=="autoFocus"&&(as.hasOwnProperty(u)?a||(a=[]):(a=a||[]).push(u,null));for(u in n){var l=n[u];if(s=i!=null?i[u]:void 0,n.hasOwnProperty(u)&&l!==s&&(l!=null||s!=null))if(u==="style")if(s){for(o in s)!s.hasOwnProperty(o)||l&&l.hasOwnProperty(o)||(r||(r={}),r[o]="");for(o in l)l.hasOwnProperty(o)&&s[o]!==l[o]&&(r||(r={}),r[o]=l[o])}else r||(a||(a=[]),a.push(u,r)),r=l;else u==="dangerouslySetInnerHTML"?(l=l?l.__html:void 0,s=s?s.__html:void 0,l!=null&&s!==l&&(a=a||[]).push(u,l)):u==="children"?typeof l!="string"&&typeof l!="number"||(a=a||[]).push(u,""+l):u!=="suppressContentEditableWarning"&&u!=="suppressHydrationWarning"&&(as.hasOwnProperty(u)?(l!=null&&u==="onScroll"&&be("scroll",e),a||s===l||(a=[])):(a=a||[]).push(u,l))}r&&(a=a||[]).push("style",r);var u=a;(t.updateQueue=u)&&(t.flags|=4)}};sS=function(e,t,r,n){r!==n&&(t.flags|=4)};function Oo(e,t){if(!ke)switch(e.tailMode){case"hidden":t=e.tail;for(var r=null;t!==null;)t.alternate!==null&&(r=t),t=t.sibling;r===null?e.tail=null:r.sibling=null;break;case"collapsed":r=e.tail;for(var n=null;r!==null;)r.alternate!==null&&(n=r),r=r.sibling;n===null?t||e.tail===null?e.tail=null:e.tail.sibling=null:n.sibling=null}}function ut(e){var t=e.alternate!==null&&e.alternate.child===e.child,r=0,n=0;if(t)for(var i=e.child;i!==null;)r|=i.lanes|i.childLanes,n|=i.subtreeFlags&14680064,n|=i.flags&14680064,i.return=e,i=i.sibling;else for(i=e.child;i!==null;)r|=i.lanes|i.childLanes,n|=i.subtreeFlags,n|=i.flags,i.return=e,i=i.sibling;return e.subtreeFlags|=n,e.childLanes=r,t}function L2(e,t,r){var n=t.pendingProps;switch(av(t),t.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return ut(t),null;case 1:return $t(t.type)&&_u(),ut(t),null;case 3:return n=t.stateNode,wa(),_e(Nt),_e(mt),hv(),n.pendingContext&&(n.context=n.pendingContext,n.pendingContext=null),(e===null||e.child===null)&&(Il(t)?t.flags|=4:e===null||e.memoizedState.isDehydrated&&!(t.flags&256)||(t.flags|=1024,mr!==null&&(nh(mr),mr=null))),qp(e,t),ut(t),null;case 5:pv(t);var i=ci(ys.current);if(r=t.type,e!==null&&t.stateNode!=null)oS(e,t,r,n,i),e.ref!==t.ref&&(t.flags|=512,t.flags|=2097152);else{if(!n){if(t.stateNode===null)throw Error(H(166));return ut(t),null}if(e=ci(Er.current),Il(t)){n=t.stateNode,r=t.type;var a=t.memoizedProps;switch(n[kr]=t,n[ms]=a,e=(t.mode&1)!==0,r){case"dialog":be("cancel",n),be("close",n);break;case"iframe":case"object":case"embed":be("load",n);break;case"video":case"audio":for(i=0;i<Bo.length;i++)be(Bo[i],n);break;case"source":be("error",n);break;case"img":case"image":case"link":be("error",n),be("load",n);break;case"details":be("toggle",n);break;case"input":qy(n,a),be("invalid",n);break;case"select":n._wrapperState={wasMultiple:!!a.multiple},be("invalid",n);break;case"textarea":Qy(n,a),be("invalid",n)}jp(r,a),i=null;for(var o in a)if(a.hasOwnProperty(o)){var s=a[o];o==="children"?typeof s=="string"?n.textContent!==s&&(a.suppressHydrationWarning!==!0&&Ml(n.textContent,s,e),i=["children",s]):typeof s=="number"&&n.textContent!==""+s&&(a.suppressHydrationWarning!==!0&&Ml(n.textContent,s,e),i=["children",""+s]):as.hasOwnProperty(o)&&s!=null&&o==="onScroll"&&be("scroll",n)}switch(r){case"input":Pl(n),Xy(n,a,!0);break;case"textarea":Pl(n),Zy(n);break;case"select":case"option":break;default:typeof a.onClick=="function"&&(n.onclick=Ou)}n=i,t.updateQueue=n,n!==null&&(t.flags|=4)}else{o=i.nodeType===9?i:i.ownerDocument,e==="http://www.w3.org/1999/xhtml"&&(e=Iw(r)),e==="http://www.w3.org/1999/xhtml"?r==="script"?(e=o.createElement("div"),e.innerHTML="<script><\/script>",e=e.removeChild(e.firstChild)):typeof n.is=="string"?e=o.createElement(r,{is:n.is}):(e=o.createElement(r),r==="select"&&(o=e,n.multiple?o.multiple=!0:n.size&&(o.size=n.size))):e=o.createElementNS(e,r),e[kr]=t,e[ms]=n,aS(e,t,!1,!1),t.stateNode=e;e:{switch(o=Sp(r,n),r){case"dialog":be("cancel",e),be("close",e),i=n;break;case"iframe":case"object":case"embed":be("load",e),i=n;break;case"video":case"audio":for(i=0;i<Bo.length;i++)be(Bo[i],e);i=n;break;case"source":be("error",e),i=n;break;case"img":case"image":case"link":be("error",e),be("load",e),i=n;break;case"details":be("toggle",e),i=n;break;case"input":qy(e,n),i=yp(e,n),be("invalid",e);break;case"option":i=n;break;case"select":e._wrapperState={wasMultiple:!!n.multiple},i=Te({},n,{value:void 0}),be("invalid",e);break;case"textarea":Qy(e,n),i=bp(e,n),be("invalid",e);break;default:i=n}jp(r,i),s=i;for(a in s)if(s.hasOwnProperty(a)){var l=s[a];a==="style"?Rw(e,l):a==="dangerouslySetInnerHTML"?(l=l?l.__html:void 0,l!=null&&Lw(e,l)):a==="children"?typeof l=="string"?(r!=="textarea"||l!=="")&&os(e,l):typeof l=="number"&&os(e,""+l):a!=="suppressContentEditableWarning"&&a!=="suppressHydrationWarning"&&a!=="autoFocus"&&(as.hasOwnProperty(a)?l!=null&&a==="onScroll"&&be("scroll",e):l!=null&&Km(e,a,l,o))}switch(r){case"input":Pl(e),Xy(e,n,!1);break;case"textarea":Pl(e),Zy(e);break;case"option":n.value!=null&&e.setAttribute("value",""+Dn(n.value));break;case"select":e.multiple=!!n.multiple,a=n.value,a!=null?la(e,!!n.multiple,a,!1):n.defaultValue!=null&&la(e,!!n.multiple,n.defaultValue,!0);break;default:typeof i.onClick=="function"&&(e.onclick=Ou)}switch(r){case"button":case"input":case"select":case"textarea":n=!!n.autoFocus;break e;case"img":n=!0;break e;default:n=!1}}n&&(t.flags|=4)}t.ref!==null&&(t.flags|=512,t.flags|=2097152)}return ut(t),null;case 6:if(e&&t.stateNode!=null)sS(e,t,e.memoizedProps,n);else{if(typeof n!="string"&&t.stateNode===null)throw Error(H(166));if(r=ci(ys.current),ci(Er.current),Il(t)){if(n=t.stateNode,r=t.memoizedProps,n[kr]=t,(a=n.nodeValue!==r)&&(e=zt,e!==null))switch(e.tag){case 3:Ml(n.nodeValue,r,(e.mode&1)!==0);break;case 5:e.memoizedProps.suppressHydrationWarning!==!0&&Ml(n.nodeValue,r,(e.mode&1)!==0)}a&&(t.flags|=4)}else n=(r.nodeType===9?r:r.ownerDocument).createTextNode(n),n[kr]=t,t.stateNode=n}return ut(t),null;case 13:if(_e(Ne),n=t.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(ke&&Ft!==null&&t.mode&1&&!(t.flags&128))_j(),xa(),t.flags|=98560,a=!1;else if(a=Il(t),n!==null&&n.dehydrated!==null){if(e===null){if(!a)throw Error(H(318));if(a=t.memoizedState,a=a!==null?a.dehydrated:null,!a)throw Error(H(317));a[kr]=t}else xa(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;ut(t),a=!1}else mr!==null&&(nh(mr),mr=null),a=!0;if(!a)return t.flags&65536?t:null}return t.flags&128?(t.lanes=r,t):(n=n!==null,n!==(e!==null&&e.memoizedState!==null)&&n&&(t.child.flags|=8192,t.mode&1&&(e===null||Ne.current&1?qe===0&&(qe=3):Pv())),t.updateQueue!==null&&(t.flags|=4),ut(t),null);case 4:return wa(),qp(e,t),e===null&&ps(t.stateNode.containerInfo),ut(t),null;case 10:return uv(t.type._context),ut(t),null;case 17:return $t(t.type)&&_u(),ut(t),null;case 19:if(_e(Ne),a=t.memoizedState,a===null)return ut(t),null;if(n=(t.flags&128)!==0,o=a.rendering,o===null)if(n)Oo(a,!1);else{if(qe!==0||e!==null&&e.flags&128)for(e=t.child;e!==null;){if(o=Tu(e),o!==null){for(t.flags|=128,Oo(a,!1),n=o.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),t.subtreeFlags=0,n=r,r=t.child;r!==null;)a=r,e=n,a.flags&=14680066,o=a.alternate,o===null?(a.childLanes=0,a.lanes=e,a.child=null,a.subtreeFlags=0,a.memoizedProps=null,a.memoizedState=null,a.updateQueue=null,a.dependencies=null,a.stateNode=null):(a.childLanes=o.childLanes,a.lanes=o.lanes,a.child=o.child,a.subtreeFlags=0,a.deletions=null,a.memoizedProps=o.memoizedProps,a.memoizedState=o.memoizedState,a.updateQueue=o.updateQueue,a.type=o.type,e=o.dependencies,a.dependencies=e===null?null:{lanes:e.lanes,firstContext:e.firstContext}),r=r.sibling;return ge(Ne,Ne.current&1|2),t.child}e=e.sibling}a.tail!==null&&De()>Sa&&(t.flags|=128,n=!0,Oo(a,!1),t.lanes=4194304)}else{if(!n)if(e=Tu(o),e!==null){if(t.flags|=128,n=!0,r=e.updateQueue,r!==null&&(t.updateQueue=r,t.flags|=4),Oo(a,!0),a.tail===null&&a.tailMode==="hidden"&&!o.alternate&&!ke)return ut(t),null}else 2*De()-a.renderingStartTime>Sa&&r!==1073741824&&(t.flags|=128,n=!0,Oo(a,!1),t.lanes=4194304);a.isBackwards?(o.sibling=t.child,t.child=o):(r=a.last,r!==null?r.sibling=o:t.child=o,a.last=o)}return a.tail!==null?(t=a.tail,a.rendering=t,a.tail=t.sibling,a.renderingStartTime=De(),t.sibling=null,r=Ne.current,ge(Ne,n?r&1|2:r&1),t):(ut(t),null);case 22:case 23:return _v(),n=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==n&&(t.flags|=8192),n&&t.mode&1?Dt&1073741824&&(ut(t),t.subtreeFlags&6&&(t.flags|=8192)):ut(t),null;case 24:return null;case 25:return null}throw Error(H(156,t.tag))}function D2(e,t){switch(av(t),t.tag){case 1:return $t(t.type)&&_u(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return wa(),_e(Nt),_e(mt),hv(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return pv(t),null;case 13:if(_e(Ne),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(H(340));xa()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return _e(Ne),null;case 4:return wa(),null;case 10:return uv(t.type._context),null;case 22:case 23:return _v(),null;case 24:return null;default:return null}}var Rl=!1,ft=!1,R2=typeof WeakSet=="function"?WeakSet:Set,G=null;function ta(e,t){var r=e.ref;if(r!==null)if(typeof r=="function")try{r(null)}catch(n){Me(e,t,n)}else r.current=null}function Xp(e,t,r){try{r()}catch(n){Me(e,t,n)}}var zg=!1;function B2(e,t){if(Cp=wu,e=dj(),nv(e)){if("selectionStart"in e)var r={start:e.selectionStart,end:e.selectionEnd};else e:{r=(r=e.ownerDocument)&&r.defaultView||window;var n=r.getSelection&&r.getSelection();if(n&&n.rangeCount!==0){r=n.anchorNode;var i=n.anchorOffset,a=n.focusNode;n=n.focusOffset;try{r.nodeType,a.nodeType}catch{r=null;break e}var o=0,s=-1,l=-1,u=0,f=0,d=e,p=null;t:for(;;){for(var h;d!==r||i!==0&&d.nodeType!==3||(s=o+i),d!==a||n!==0&&d.nodeType!==3||(l=o+n),d.nodeType===3&&(o+=d.nodeValue.length),(h=d.firstChild)!==null;)p=d,d=h;for(;;){if(d===e)break t;if(p===r&&++u===i&&(s=o),p===a&&++f===n&&(l=o),(h=d.nextSibling)!==null)break;d=p,p=d.parentNode}d=h}r=s===-1||l===-1?null:{start:s,end:l}}else r=null}r=r||{start:0,end:0}}else r=null;for(Mp={focusedElem:e,selectionRange:r},wu=!1,G=t;G!==null;)if(t=G,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,G=e;else for(;G!==null;){t=G;try{var m=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(m!==null){var g=m.memoizedProps,x=m.memoizedState,y=t.stateNode,v=y.getSnapshotBeforeUpdate(t.elementType===t.type?g:fr(t.type,g),x);y.__reactInternalSnapshotBeforeUpdate=v}break;case 3:var b=t.stateNode.containerInfo;b.nodeType===1?b.textContent="":b.nodeType===9&&b.documentElement&&b.removeChild(b.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(H(163))}}catch(S){Me(t,t.return,S)}if(e=t.sibling,e!==null){e.return=t.return,G=e;break}G=t.return}return m=zg,zg=!1,m}function Go(e,t,r){var n=t.updateQueue;if(n=n!==null?n.lastEffect:null,n!==null){var i=n=n.next;do{if((i.tag&e)===e){var a=i.destroy;i.destroy=void 0,a!==void 0&&Xp(t,r,a)}i=i.next}while(i!==n)}}function nf(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var r=t=t.next;do{if((r.tag&e)===e){var n=r.create;r.destroy=n()}r=r.next}while(r!==t)}}function Qp(e){var t=e.ref;if(t!==null){var r=e.stateNode;switch(e.tag){case 5:e=r;break;default:e=r}typeof t=="function"?t(e):t.current=e}}function lS(e){var t=e.alternate;t!==null&&(e.alternate=null,lS(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[kr],delete t[ms],delete t[Dp],delete t[w2],delete t[j2])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function uS(e){return e.tag===5||e.tag===3||e.tag===4}function Wg(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||uS(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Zp(e,t,r){var n=e.tag;if(n===5||n===6)e=e.stateNode,t?r.nodeType===8?r.parentNode.insertBefore(e,t):r.insertBefore(e,t):(r.nodeType===8?(t=r.parentNode,t.insertBefore(e,r)):(t=r,t.appendChild(e)),r=r._reactRootContainer,r!=null||t.onclick!==null||(t.onclick=Ou));else if(n!==4&&(e=e.child,e!==null))for(Zp(e,t,r),e=e.sibling;e!==null;)Zp(e,t,r),e=e.sibling}function Jp(e,t,r){var n=e.tag;if(n===5||n===6)e=e.stateNode,t?r.insertBefore(e,t):r.appendChild(e);else if(n!==4&&(e=e.child,e!==null))for(Jp(e,t,r),e=e.sibling;e!==null;)Jp(e,t,r),e=e.sibling}var at=null,dr=!1;function fn(e,t,r){for(r=r.child;r!==null;)cS(e,t,r),r=r.sibling}function cS(e,t,r){if($r&&typeof $r.onCommitFiberUnmount=="function")try{$r.onCommitFiberUnmount(qc,r)}catch{}switch(r.tag){case 5:ft||ta(r,t);case 6:var n=at,i=dr;at=null,fn(e,t,r),at=n,dr=i,at!==null&&(dr?(e=at,r=r.stateNode,e.nodeType===8?e.parentNode.removeChild(r):e.removeChild(r)):at.removeChild(r.stateNode));break;case 18:at!==null&&(dr?(e=at,r=r.stateNode,e.nodeType===8?wd(e.parentNode,r):e.nodeType===1&&wd(e,r),cs(e)):wd(at,r.stateNode));break;case 4:n=at,i=dr,at=r.stateNode.containerInfo,dr=!0,fn(e,t,r),at=n,dr=i;break;case 0:case 11:case 14:case 15:if(!ft&&(n=r.updateQueue,n!==null&&(n=n.lastEffect,n!==null))){i=n=n.next;do{var a=i,o=a.destroy;a=a.tag,o!==void 0&&(a&2||a&4)&&Xp(r,t,o),i=i.next}while(i!==n)}fn(e,t,r);break;case 1:if(!ft&&(ta(r,t),n=r.stateNode,typeof n.componentWillUnmount=="function"))try{n.props=r.memoizedProps,n.state=r.memoizedState,n.componentWillUnmount()}catch(s){Me(r,t,s)}fn(e,t,r);break;case 21:fn(e,t,r);break;case 22:r.mode&1?(ft=(n=ft)||r.memoizedState!==null,fn(e,t,r),ft=n):fn(e,t,r);break;default:fn(e,t,r)}}function Ug(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var r=e.stateNode;r===null&&(r=e.stateNode=new R2),t.forEach(function(n){var i=Y2.bind(null,e,n);r.has(n)||(r.add(n),n.then(i,i))})}}function ur(e,t){var r=t.deletions;if(r!==null)for(var n=0;n<r.length;n++){var i=r[n];try{var a=e,o=t,s=o;e:for(;s!==null;){switch(s.tag){case 5:at=s.stateNode,dr=!1;break e;case 3:at=s.stateNode.containerInfo,dr=!0;break e;case 4:at=s.stateNode.containerInfo,dr=!0;break e}s=s.return}if(at===null)throw Error(H(160));cS(a,o,i),at=null,dr=!1;var l=i.alternate;l!==null&&(l.return=null),i.return=null}catch(u){Me(i,t,u)}}if(t.subtreeFlags&12854)for(t=t.child;t!==null;)fS(t,e),t=t.sibling}function fS(e,t){var r=e.alternate,n=e.flags;switch(e.tag){case 0:case 11:case 14:case 15:if(ur(t,e),_r(e),n&4){try{Go(3,e,e.return),nf(3,e)}catch(g){Me(e,e.return,g)}try{Go(5,e,e.return)}catch(g){Me(e,e.return,g)}}break;case 1:ur(t,e),_r(e),n&512&&r!==null&&ta(r,r.return);break;case 5:if(ur(t,e),_r(e),n&512&&r!==null&&ta(r,r.return),e.flags&32){var i=e.stateNode;try{os(i,"")}catch(g){Me(e,e.return,g)}}if(n&4&&(i=e.stateNode,i!=null)){var a=e.memoizedProps,o=r!==null?r.memoizedProps:a,s=e.type,l=e.updateQueue;if(e.updateQueue=null,l!==null)try{s==="input"&&a.type==="radio"&&a.name!=null&&Cw(i,a),Sp(s,o);var u=Sp(s,a);for(o=0;o<l.length;o+=2){var f=l[o],d=l[o+1];f==="style"?Rw(i,d):f==="dangerouslySetInnerHTML"?Lw(i,d):f==="children"?os(i,d):Km(i,f,d,u)}switch(s){case"input":gp(i,a);break;case"textarea":Mw(i,a);break;case"select":var p=i._wrapperState.wasMultiple;i._wrapperState.wasMultiple=!!a.multiple;var h=a.value;h!=null?la(i,!!a.multiple,h,!1):p!==!!a.multiple&&(a.defaultValue!=null?la(i,!!a.multiple,a.defaultValue,!0):la(i,!!a.multiple,a.multiple?[]:"",!1))}i[ms]=a}catch(g){Me(e,e.return,g)}}break;case 6:if(ur(t,e),_r(e),n&4){if(e.stateNode===null)throw Error(H(162));i=e.stateNode,a=e.memoizedProps;try{i.nodeValue=a}catch(g){Me(e,e.return,g)}}break;case 3:if(ur(t,e),_r(e),n&4&&r!==null&&r.memoizedState.isDehydrated)try{cs(t.containerInfo)}catch(g){Me(e,e.return,g)}break;case 4:ur(t,e),_r(e);break;case 13:ur(t,e),_r(e),i=e.child,i.flags&8192&&(a=i.memoizedState!==null,i.stateNode.isHidden=a,!a||i.alternate!==null&&i.alternate.memoizedState!==null||(Sv=De())),n&4&&Ug(e);break;case 22:if(f=r!==null&&r.memoizedState!==null,e.mode&1?(ft=(u=ft)||f,ur(t,e),ft=u):ur(t,e),_r(e),n&8192){if(u=e.memoizedState!==null,(e.stateNode.isHidden=u)&&!f&&e.mode&1)for(G=e,f=e.child;f!==null;){for(d=G=f;G!==null;){switch(p=G,h=p.child,p.tag){case 0:case 11:case 14:case 15:Go(4,p,p.return);break;case 1:ta(p,p.return);var m=p.stateNode;if(typeof m.componentWillUnmount=="function"){n=p,r=p.return;try{t=n,m.props=t.memoizedProps,m.state=t.memoizedState,m.componentWillUnmount()}catch(g){Me(n,r,g)}}break;case 5:ta(p,p.return);break;case 22:if(p.memoizedState!==null){Hg(d);continue}}h!==null?(h.return=p,G=h):Hg(d)}f=f.sibling}e:for(f=null,d=e;;){if(d.tag===5){if(f===null){f=d;try{i=d.stateNode,u?(a=i.style,typeof a.setProperty=="function"?a.setProperty("display","none","important"):a.display="none"):(s=d.stateNode,l=d.memoizedProps.style,o=l!=null&&l.hasOwnProperty("display")?l.display:null,s.style.display=Dw("display",o))}catch(g){Me(e,e.return,g)}}}else if(d.tag===6){if(f===null)try{d.stateNode.nodeValue=u?"":d.memoizedProps}catch(g){Me(e,e.return,g)}}else if((d.tag!==22&&d.tag!==23||d.memoizedState===null||d===e)&&d.child!==null){d.child.return=d,d=d.child;continue}if(d===e)break e;for(;d.sibling===null;){if(d.return===null||d.return===e)break e;f===d&&(f=null),d=d.return}f===d&&(f=null),d.sibling.return=d.return,d=d.sibling}}break;case 19:ur(t,e),_r(e),n&4&&Ug(e);break;case 21:break;default:ur(t,e),_r(e)}}function _r(e){var t=e.flags;if(t&2){try{e:{for(var r=e.return;r!==null;){if(uS(r)){var n=r;break e}r=r.return}throw Error(H(160))}switch(n.tag){case 5:var i=n.stateNode;n.flags&32&&(os(i,""),n.flags&=-33);var a=Wg(e);Jp(e,a,i);break;case 3:case 4:var o=n.stateNode.containerInfo,s=Wg(e);Zp(e,s,o);break;default:throw Error(H(161))}}catch(l){Me(e,e.return,l)}e.flags&=-3}t&4096&&(e.flags&=-4097)}function F2(e,t,r){G=e,dS(e)}function dS(e,t,r){for(var n=(e.mode&1)!==0;G!==null;){var i=G,a=i.child;if(i.tag===22&&n){var o=i.memoizedState!==null||Rl;if(!o){var s=i.alternate,l=s!==null&&s.memoizedState!==null||ft;s=Rl;var u=ft;if(Rl=o,(ft=l)&&!u)for(G=i;G!==null;)o=G,l=o.child,o.tag===22&&o.memoizedState!==null?Vg(i):l!==null?(l.return=o,G=l):Vg(i);for(;a!==null;)G=a,dS(a),a=a.sibling;G=i,Rl=s,ft=u}Kg(e)}else i.subtreeFlags&8772&&a!==null?(a.return=i,G=a):Kg(e)}}function Kg(e){for(;G!==null;){var t=G;if(t.flags&8772){var r=t.alternate;try{if(t.flags&8772)switch(t.tag){case 0:case 11:case 15:ft||nf(5,t);break;case 1:var n=t.stateNode;if(t.flags&4&&!ft)if(r===null)n.componentDidMount();else{var i=t.elementType===t.type?r.memoizedProps:fr(t.type,r.memoizedProps);n.componentDidUpdate(i,r.memoizedState,n.__reactInternalSnapshotBeforeUpdate)}var a=t.updateQueue;a!==null&&Ag(t,a,n);break;case 3:var o=t.updateQueue;if(o!==null){if(r=null,t.child!==null)switch(t.child.tag){case 5:r=t.child.stateNode;break;case 1:r=t.child.stateNode}Ag(t,o,r)}break;case 5:var s=t.stateNode;if(r===null&&t.flags&4){r=s;var l=t.memoizedProps;switch(t.type){case"button":case"input":case"select":case"textarea":l.autoFocus&&r.focus();break;case"img":l.src&&(r.src=l.src)}}break;case 6:break;case 4:break;case 12:break;case 13:if(t.memoizedState===null){var u=t.alternate;if(u!==null){var f=u.memoizedState;if(f!==null){var d=f.dehydrated;d!==null&&cs(d)}}}break;case 19:case 17:case 21:case 22:case 23:case 25:break;default:throw Error(H(163))}ft||t.flags&512&&Qp(t)}catch(p){Me(t,t.return,p)}}if(t===e){G=null;break}if(r=t.sibling,r!==null){r.return=t.return,G=r;break}G=t.return}}function Hg(e){for(;G!==null;){var t=G;if(t===e){G=null;break}var r=t.sibling;if(r!==null){r.return=t.return,G=r;break}G=t.return}}function Vg(e){for(;G!==null;){var t=G;try{switch(t.tag){case 0:case 11:case 15:var r=t.return;try{nf(4,t)}catch(l){Me(t,r,l)}break;case 1:var n=t.stateNode;if(typeof n.componentDidMount=="function"){var i=t.return;try{n.componentDidMount()}catch(l){Me(t,i,l)}}var a=t.return;try{Qp(t)}catch(l){Me(t,a,l)}break;case 5:var o=t.return;try{Qp(t)}catch(l){Me(t,o,l)}}}catch(l){Me(t,t.return,l)}if(t===e){G=null;break}var s=t.sibling;if(s!==null){s.return=t.return,G=s;break}G=t.return}}var z2=Math.ceil,Iu=nn.ReactCurrentDispatcher,wv=nn.ReactCurrentOwner,rr=nn.ReactCurrentBatchConfig,le=0,rt=null,ze=null,ot=0,Dt=0,ra=Un(0),qe=0,ws=null,Oi=0,af=0,jv=0,Yo=null,Pt=null,Sv=0,Sa=1/0,Rr=null,Lu=!1,eh=null,En=null,Bl=!1,bn=null,Du=0,qo=0,th=null,du=-1,pu=0;function bt(){return le&6?De():du!==-1?du:du=De()}function Tn(e){return e.mode&1?le&2&&ot!==0?ot&-ot:O2.transition!==null?(pu===0&&(pu=Xw()),pu):(e=fe,e!==0||(e=window.event,e=e===void 0?16:nj(e.type)),e):1}function gr(e,t,r,n){if(50<qo)throw qo=0,th=null,Error(H(185));ol(e,r,n),(!(le&2)||e!==rt)&&(e===rt&&(!(le&2)&&(af|=r),qe===4&&yn(e,ot)),Et(e,n),r===1&&le===0&&!(t.mode&1)&&(Sa=De()+500,ef&&Kn()))}function Et(e,t){var r=e.callbackNode;OA(e,t);var n=bu(e,e===rt?ot:0);if(n===0)r!==null&&tg(r),e.callbackNode=null,e.callbackPriority=0;else if(t=n&-n,e.callbackPriority!==t){if(r!=null&&tg(r),t===1)e.tag===0?S2(Gg.bind(null,e)):jj(Gg.bind(null,e)),x2(function(){!(le&6)&&Kn()}),r=null;else{switch(Qw(n)){case 1:r=qm;break;case 4:r=Yw;break;case 16:r=xu;break;case 536870912:r=qw;break;default:r=xu}r=bS(r,pS.bind(null,e))}e.callbackPriority=t,e.callbackNode=r}}function pS(e,t){if(du=-1,pu=0,le&6)throw Error(H(327));var r=e.callbackNode;if(pa()&&e.callbackNode!==r)return null;var n=bu(e,e===rt?ot:0);if(n===0)return null;if(n&30||n&e.expiredLanes||t)t=Ru(e,n);else{t=n;var i=le;le|=2;var a=mS();(rt!==e||ot!==t)&&(Rr=null,Sa=De()+500,vi(e,t));do try{K2();break}catch(s){hS(e,s)}while(!0);lv(),Iu.current=a,le=i,ze!==null?t=0:(rt=null,ot=0,t=qe)}if(t!==0){if(t===2&&(i=Ap(e),i!==0&&(n=i,t=rh(e,i))),t===1)throw r=ws,vi(e,0),yn(e,n),Et(e,De()),r;if(t===6)yn(e,n);else{if(i=e.current.alternate,!(n&30)&&!W2(i)&&(t=Ru(e,n),t===2&&(a=Ap(e),a!==0&&(n=a,t=rh(e,a))),t===1))throw r=ws,vi(e,0),yn(e,n),Et(e,De()),r;switch(e.finishedWork=i,e.finishedLanes=n,t){case 0:case 1:throw Error(H(345));case 2:ni(e,Pt,Rr);break;case 3:if(yn(e,n),(n&130023424)===n&&(t=Sv+500-De(),10<t)){if(bu(e,0)!==0)break;if(i=e.suspendedLanes,(i&n)!==n){bt(),e.pingedLanes|=e.suspendedLanes&i;break}e.timeoutHandle=Lp(ni.bind(null,e,Pt,Rr),t);break}ni(e,Pt,Rr);break;case 4:if(yn(e,n),(n&4194240)===n)break;for(t=e.eventTimes,i=-1;0<n;){var o=31-yr(n);a=1<<o,o=t[o],o>i&&(i=o),n&=~a}if(n=i,n=De()-n,n=(120>n?120:480>n?480:1080>n?1080:1920>n?1920:3e3>n?3e3:4320>n?4320:1960*z2(n/1960))-n,10<n){e.timeoutHandle=Lp(ni.bind(null,e,Pt,Rr),n);break}ni(e,Pt,Rr);break;case 5:ni(e,Pt,Rr);break;default:throw Error(H(329))}}}return Et(e,De()),e.callbackNode===r?pS.bind(null,e):null}function rh(e,t){var r=Yo;return e.current.memoizedState.isDehydrated&&(vi(e,t).flags|=256),e=Ru(e,t),e!==2&&(t=Pt,Pt=r,t!==null&&nh(t)),e}function nh(e){Pt===null?Pt=e:Pt.push.apply(Pt,e)}function W2(e){for(var t=e;;){if(t.flags&16384){var r=t.updateQueue;if(r!==null&&(r=r.stores,r!==null))for(var n=0;n<r.length;n++){var i=r[n],a=i.getSnapshot;i=i.value;try{if(!wr(a(),i))return!1}catch{return!1}}}if(r=t.child,t.subtreeFlags&16384&&r!==null)r.return=t,t=r;else{if(t===e)break;for(;t.sibling===null;){if(t.return===null||t.return===e)return!0;t=t.return}t.sibling.return=t.return,t=t.sibling}}return!0}function yn(e,t){for(t&=~jv,t&=~af,e.suspendedLanes|=t,e.pingedLanes&=~t,e=e.expirationTimes;0<t;){var r=31-yr(t),n=1<<r;e[r]=-1,t&=~n}}function Gg(e){if(le&6)throw Error(H(327));pa();var t=bu(e,0);if(!(t&1))return Et(e,De()),null;var r=Ru(e,t);if(e.tag!==0&&r===2){var n=Ap(e);n!==0&&(t=n,r=rh(e,n))}if(r===1)throw r=ws,vi(e,0),yn(e,t),Et(e,De()),r;if(r===6)throw Error(H(345));return e.finishedWork=e.current.alternate,e.finishedLanes=t,ni(e,Pt,Rr),Et(e,De()),null}function Ov(e,t){var r=le;le|=1;try{return e(t)}finally{le=r,le===0&&(Sa=De()+500,ef&&Kn())}}function _i(e){bn!==null&&bn.tag===0&&!(le&6)&&pa();var t=le;le|=1;var r=rr.transition,n=fe;try{if(rr.transition=null,fe=1,e)return e()}finally{fe=n,rr.transition=r,le=t,!(le&6)&&Kn()}}function _v(){Dt=ra.current,_e(ra)}function vi(e,t){e.finishedWork=null,e.finishedLanes=0;var r=e.timeoutHandle;if(r!==-1&&(e.timeoutHandle=-1,g2(r)),ze!==null)for(r=ze.return;r!==null;){var n=r;switch(av(n),n.tag){case 1:n=n.type.childContextTypes,n!=null&&_u();break;case 3:wa(),_e(Nt),_e(mt),hv();break;case 5:pv(n);break;case 4:wa();break;case 13:_e(Ne);break;case 19:_e(Ne);break;case 10:uv(n.type._context);break;case 22:case 23:_v()}r=r.return}if(rt=e,ze=e=Cn(e.current,null),ot=Dt=t,qe=0,ws=null,jv=af=Oi=0,Pt=Yo=null,ui!==null){for(t=0;t<ui.length;t++)if(r=ui[t],n=r.interleaved,n!==null){r.interleaved=null;var i=n.next,a=r.pending;if(a!==null){var o=a.next;a.next=i,n.next=o}r.pending=n}ui=null}return e}function hS(e,t){do{var r=ze;try{if(lv(),uu.current=Mu,Cu){for(var n=Ee.memoizedState;n!==null;){var i=n.queue;i!==null&&(i.pending=null),n=n.next}Cu=!1}if(Si=0,Je=Ye=Ee=null,Vo=!1,gs=0,wv.current=null,r===null||r.return===null){qe=1,ws=t,ze=null;break}e:{var a=e,o=r.return,s=r,l=t;if(t=ot,s.flags|=32768,l!==null&&typeof l=="object"&&typeof l.then=="function"){var u=l,f=s,d=f.tag;if(!(f.mode&1)&&(d===0||d===11||d===15)){var p=f.alternate;p?(f.updateQueue=p.updateQueue,f.memoizedState=p.memoizedState,f.lanes=p.lanes):(f.updateQueue=null,f.memoizedState=null)}var h=Mg(o);if(h!==null){h.flags&=-257,Ig(h,o,s,a,t),h.mode&1&&Cg(a,u,t),t=h,l=u;var m=t.updateQueue;if(m===null){var g=new Set;g.add(l),t.updateQueue=g}else m.add(l);break e}else{if(!(t&1)){Cg(a,u,t),Pv();break e}l=Error(H(426))}}else if(ke&&s.mode&1){var x=Mg(o);if(x!==null){!(x.flags&65536)&&(x.flags|=256),Ig(x,o,s,a,t),ov(ja(l,s));break e}}a=l=ja(l,s),qe!==4&&(qe=2),Yo===null?Yo=[a]:Yo.push(a),a=o;do{switch(a.tag){case 3:a.flags|=65536,t&=-t,a.lanes|=t;var y=Qj(a,l,t);kg(a,y);break e;case 1:s=l;var v=a.type,b=a.stateNode;if(!(a.flags&128)&&(typeof v.getDerivedStateFromError=="function"||b!==null&&typeof b.componentDidCatch=="function"&&(En===null||!En.has(b)))){a.flags|=65536,t&=-t,a.lanes|=t;var S=Zj(a,s,t);kg(a,S);break e}}a=a.return}while(a!==null)}yS(r)}catch(w){t=w,ze===r&&r!==null&&(ze=r=r.return);continue}break}while(!0)}function mS(){var e=Iu.current;return Iu.current=Mu,e===null?Mu:e}function Pv(){(qe===0||qe===3||qe===2)&&(qe=4),rt===null||!(Oi&268435455)&&!(af&268435455)||yn(rt,ot)}function Ru(e,t){var r=le;le|=2;var n=mS();(rt!==e||ot!==t)&&(Rr=null,vi(e,t));do try{U2();break}catch(i){hS(e,i)}while(!0);if(lv(),le=r,Iu.current=n,ze!==null)throw Error(H(261));return rt=null,ot=0,qe}function U2(){for(;ze!==null;)vS(ze)}function K2(){for(;ze!==null&&!mA();)vS(ze)}function vS(e){var t=xS(e.alternate,e,Dt);e.memoizedProps=e.pendingProps,t===null?yS(e):ze=t,wv.current=null}function yS(e){var t=e;do{var r=t.alternate;if(e=t.return,t.flags&32768){if(r=D2(r,t),r!==null){r.flags&=32767,ze=r;return}if(e!==null)e.flags|=32768,e.subtreeFlags=0,e.deletions=null;else{qe=6,ze=null;return}}else if(r=L2(r,t,Dt),r!==null){ze=r;return}if(t=t.sibling,t!==null){ze=t;return}ze=t=e}while(t!==null);qe===0&&(qe=5)}function ni(e,t,r){var n=fe,i=rr.transition;try{rr.transition=null,fe=1,H2(e,t,r,n)}finally{rr.transition=i,fe=n}return null}function H2(e,t,r,n){do pa();while(bn!==null);if(le&6)throw Error(H(327));r=e.finishedWork;var i=e.finishedLanes;if(r===null)return null;if(e.finishedWork=null,e.finishedLanes=0,r===e.current)throw Error(H(177));e.callbackNode=null,e.callbackPriority=0;var a=r.lanes|r.childLanes;if(_A(e,a),e===rt&&(ze=rt=null,ot=0),!(r.subtreeFlags&2064)&&!(r.flags&2064)||Bl||(Bl=!0,bS(xu,function(){return pa(),null})),a=(r.flags&15990)!==0,r.subtreeFlags&15990||a){a=rr.transition,rr.transition=null;var o=fe;fe=1;var s=le;le|=4,wv.current=null,B2(e,r),fS(r,e),f2(Mp),wu=!!Cp,Mp=Cp=null,e.current=r,F2(r),vA(),le=s,fe=o,rr.transition=a}else e.current=r;if(Bl&&(Bl=!1,bn=e,Du=i),a=e.pendingLanes,a===0&&(En=null),xA(r.stateNode),Et(e,De()),t!==null)for(n=e.onRecoverableError,r=0;r<t.length;r++)i=t[r],n(i.value,{componentStack:i.stack,digest:i.digest});if(Lu)throw Lu=!1,e=eh,eh=null,e;return Du&1&&e.tag!==0&&pa(),a=e.pendingLanes,a&1?e===th?qo++:(qo=0,th=e):qo=0,Kn(),null}function pa(){if(bn!==null){var e=Qw(Du),t=rr.transition,r=fe;try{if(rr.transition=null,fe=16>e?16:e,bn===null)var n=!1;else{if(e=bn,bn=null,Du=0,le&6)throw Error(H(331));var i=le;for(le|=4,G=e.current;G!==null;){var a=G,o=a.child;if(G.flags&16){var s=a.deletions;if(s!==null){for(var l=0;l<s.length;l++){var u=s[l];for(G=u;G!==null;){var f=G;switch(f.tag){case 0:case 11:case 15:Go(8,f,a)}var d=f.child;if(d!==null)d.return=f,G=d;else for(;G!==null;){f=G;var p=f.sibling,h=f.return;if(lS(f),f===u){G=null;break}if(p!==null){p.return=h,G=p;break}G=h}}}var m=a.alternate;if(m!==null){var g=m.child;if(g!==null){m.child=null;do{var x=g.sibling;g.sibling=null,g=x}while(g!==null)}}G=a}}if(a.subtreeFlags&2064&&o!==null)o.return=a,G=o;else e:for(;G!==null;){if(a=G,a.flags&2048)switch(a.tag){case 0:case 11:case 15:Go(9,a,a.return)}var y=a.sibling;if(y!==null){y.return=a.return,G=y;break e}G=a.return}}var v=e.current;for(G=v;G!==null;){o=G;var b=o.child;if(o.subtreeFlags&2064&&b!==null)b.return=o,G=b;else e:for(o=v;G!==null;){if(s=G,s.flags&2048)try{switch(s.tag){case 0:case 11:case 15:nf(9,s)}}catch(w){Me(s,s.return,w)}if(s===o){G=null;break e}var S=s.sibling;if(S!==null){S.return=s.return,G=S;break e}G=s.return}}if(le=i,Kn(),$r&&typeof $r.onPostCommitFiberRoot=="function")try{$r.onPostCommitFiberRoot(qc,e)}catch{}n=!0}return n}finally{fe=r,rr.transition=t}}return!1}function Yg(e,t,r){t=ja(r,t),t=Qj(e,t,1),e=$n(e,t,1),t=bt(),e!==null&&(ol(e,1,t),Et(e,t))}function Me(e,t,r){if(e.tag===3)Yg(e,e,r);else for(;t!==null;){if(t.tag===3){Yg(t,e,r);break}else if(t.tag===1){var n=t.stateNode;if(typeof t.type.getDerivedStateFromError=="function"||typeof n.componentDidCatch=="function"&&(En===null||!En.has(n))){e=ja(r,e),e=Zj(t,e,1),t=$n(t,e,1),e=bt(),t!==null&&(ol(t,1,e),Et(t,e));break}}t=t.return}}function V2(e,t,r){var n=e.pingCache;n!==null&&n.delete(t),t=bt(),e.pingedLanes|=e.suspendedLanes&r,rt===e&&(ot&r)===r&&(qe===4||qe===3&&(ot&130023424)===ot&&500>De()-Sv?vi(e,0):jv|=r),Et(e,t)}function gS(e,t){t===0&&(e.mode&1?(t=Nl,Nl<<=1,!(Nl&130023424)&&(Nl=4194304)):t=1);var r=bt();e=Zr(e,t),e!==null&&(ol(e,t,r),Et(e,r))}function G2(e){var t=e.memoizedState,r=0;t!==null&&(r=t.retryLane),gS(e,r)}function Y2(e,t){var r=0;switch(e.tag){case 13:var n=e.stateNode,i=e.memoizedState;i!==null&&(r=i.retryLane);break;case 19:n=e.stateNode;break;default:throw Error(H(314))}n!==null&&n.delete(t),gS(e,r)}var xS;xS=function(e,t,r){if(e!==null)if(e.memoizedProps!==t.pendingProps||Nt.current)kt=!0;else{if(!(e.lanes&r)&&!(t.flags&128))return kt=!1,I2(e,t,r);kt=!!(e.flags&131072)}else kt=!1,ke&&t.flags&1048576&&Sj(t,Au,t.index);switch(t.lanes=0,t.tag){case 2:var n=t.type;fu(e,t),e=t.pendingProps;var i=ga(t,mt.current);da(t,r),i=vv(null,t,n,e,i,r);var a=yv();return t.flags|=1,typeof i=="object"&&i!==null&&typeof i.render=="function"&&i.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,$t(n)?(a=!0,Pu(t)):a=!1,t.memoizedState=i.state!==null&&i.state!==void 0?i.state:null,fv(t),i.updater=rf,t.stateNode=i,i._reactInternals=t,Up(t,n,e,r),t=Vp(null,t,n,!0,a,r)):(t.tag=0,ke&&a&&iv(t),vt(null,t,i,r),t=t.child),t;case 16:n=t.elementType;e:{switch(fu(e,t),e=t.pendingProps,i=n._init,n=i(n._payload),t.type=n,i=t.tag=X2(n),e=fr(n,e),i){case 0:t=Hp(null,t,n,e,r);break e;case 1:t=Rg(null,t,n,e,r);break e;case 11:t=Lg(null,t,n,e,r);break e;case 14:t=Dg(null,t,n,fr(n.type,e),r);break e}throw Error(H(306,n,""))}return t;case 0:return n=t.type,i=t.pendingProps,i=t.elementType===n?i:fr(n,i),Hp(e,t,n,i,r);case 1:return n=t.type,i=t.pendingProps,i=t.elementType===n?i:fr(n,i),Rg(e,t,n,i,r);case 3:e:{if(rS(t),e===null)throw Error(H(387));n=t.pendingProps,a=t.memoizedState,i=a.element,Nj(e,t),Eu(t,n,null,r);var o=t.memoizedState;if(n=o.element,a.isDehydrated)if(a={element:n,isDehydrated:!1,cache:o.cache,pendingSuspenseBoundaries:o.pendingSuspenseBoundaries,transitions:o.transitions},t.updateQueue.baseState=a,t.memoizedState=a,t.flags&256){i=ja(Error(H(423)),t),t=Bg(e,t,n,r,i);break e}else if(n!==i){i=ja(Error(H(424)),t),t=Bg(e,t,n,r,i);break e}else for(Ft=Nn(t.stateNode.containerInfo.firstChild),zt=t,ke=!0,mr=null,r=kj(t,null,n,r),t.child=r;r;)r.flags=r.flags&-3|4096,r=r.sibling;else{if(xa(),n===i){t=Jr(e,t,r);break e}vt(e,t,n,r)}t=t.child}return t;case 5:return $j(t),e===null&&Fp(t),n=t.type,i=t.pendingProps,a=e!==null?e.memoizedProps:null,o=i.children,Ip(n,i)?o=null:a!==null&&Ip(n,a)&&(t.flags|=32),tS(e,t),vt(e,t,o,r),t.child;case 6:return e===null&&Fp(t),null;case 13:return nS(e,t,r);case 4:return dv(t,t.stateNode.containerInfo),n=t.pendingProps,e===null?t.child=ba(t,null,n,r):vt(e,t,n,r),t.child;case 11:return n=t.type,i=t.pendingProps,i=t.elementType===n?i:fr(n,i),Lg(e,t,n,i,r);case 7:return vt(e,t,t.pendingProps,r),t.child;case 8:return vt(e,t,t.pendingProps.children,r),t.child;case 12:return vt(e,t,t.pendingProps.children,r),t.child;case 10:e:{if(n=t.type._context,i=t.pendingProps,a=t.memoizedProps,o=i.value,ge(Nu,n._currentValue),n._currentValue=o,a!==null)if(wr(a.value,o)){if(a.children===i.children&&!Nt.current){t=Jr(e,t,r);break e}}else for(a=t.child,a!==null&&(a.return=t);a!==null;){var s=a.dependencies;if(s!==null){o=a.child;for(var l=s.firstContext;l!==null;){if(l.context===n){if(a.tag===1){l=Vr(-1,r&-r),l.tag=2;var u=a.updateQueue;if(u!==null){u=u.shared;var f=u.pending;f===null?l.next=l:(l.next=f.next,f.next=l),u.pending=l}}a.lanes|=r,l=a.alternate,l!==null&&(l.lanes|=r),zp(a.return,r,t),s.lanes|=r;break}l=l.next}}else if(a.tag===10)o=a.type===t.type?null:a.child;else if(a.tag===18){if(o=a.return,o===null)throw Error(H(341));o.lanes|=r,s=o.alternate,s!==null&&(s.lanes|=r),zp(o,r,t),o=a.sibling}else o=a.child;if(o!==null)o.return=a;else for(o=a;o!==null;){if(o===t){o=null;break}if(a=o.sibling,a!==null){a.return=o.return,o=a;break}o=o.return}a=o}vt(e,t,i.children,r),t=t.child}return t;case 9:return i=t.type,n=t.pendingProps.children,da(t,r),i=nr(i),n=n(i),t.flags|=1,vt(e,t,n,r),t.child;case 14:return n=t.type,i=fr(n,t.pendingProps),i=fr(n.type,i),Dg(e,t,n,i,r);case 15:return Jj(e,t,t.type,t.pendingProps,r);case 17:return n=t.type,i=t.pendingProps,i=t.elementType===n?i:fr(n,i),fu(e,t),t.tag=1,$t(n)?(e=!0,Pu(t)):e=!1,da(t,r),Xj(t,n,i),Up(t,n,i,r),Vp(null,t,n,!0,e,r);case 19:return iS(e,t,r);case 22:return eS(e,t,r)}throw Error(H(156,t.tag))};function bS(e,t){return Gw(e,t)}function q2(e,t,r,n){this.tag=e,this.key=r,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=n,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function er(e,t,r,n){return new q2(e,t,r,n)}function kv(e){return e=e.prototype,!(!e||!e.isReactComponent)}function X2(e){if(typeof e=="function")return kv(e)?1:0;if(e!=null){if(e=e.$$typeof,e===Vm)return 11;if(e===Gm)return 14}return 2}function Cn(e,t){var r=e.alternate;return r===null?(r=er(e.tag,t,e.key,e.mode),r.elementType=e.elementType,r.type=e.type,r.stateNode=e.stateNode,r.alternate=e,e.alternate=r):(r.pendingProps=t,r.type=e.type,r.flags=0,r.subtreeFlags=0,r.deletions=null),r.flags=e.flags&14680064,r.childLanes=e.childLanes,r.lanes=e.lanes,r.child=e.child,r.memoizedProps=e.memoizedProps,r.memoizedState=e.memoizedState,r.updateQueue=e.updateQueue,t=e.dependencies,r.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},r.sibling=e.sibling,r.index=e.index,r.ref=e.ref,r}function hu(e,t,r,n,i,a){var o=2;if(n=e,typeof e=="function")kv(e)&&(o=1);else if(typeof e=="string")o=5;else e:switch(e){case Vi:return yi(r.children,i,a,t);case Hm:o=8,i|=8;break;case pp:return e=er(12,r,t,i|2),e.elementType=pp,e.lanes=a,e;case hp:return e=er(13,r,t,i),e.elementType=hp,e.lanes=a,e;case mp:return e=er(19,r,t,i),e.elementType=mp,e.lanes=a,e;case $w:return of(r,i,a,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case Aw:o=10;break e;case Nw:o=9;break e;case Vm:o=11;break e;case Gm:o=14;break e;case pn:o=16,n=null;break e}throw Error(H(130,e==null?e:typeof e,""))}return t=er(o,r,t,i),t.elementType=e,t.type=n,t.lanes=a,t}function yi(e,t,r,n){return e=er(7,e,n,t),e.lanes=r,e}function of(e,t,r,n){return e=er(22,e,n,t),e.elementType=$w,e.lanes=r,e.stateNode={isHidden:!1},e}function Nd(e,t,r){return e=er(6,e,null,t),e.lanes=r,e}function $d(e,t,r){return t=er(4,e.children!==null?e.children:[],e.key,t),t.lanes=r,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function Q2(e,t,r,n,i){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=cd(0),this.expirationTimes=cd(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=cd(0),this.identifierPrefix=n,this.onRecoverableError=i,this.mutableSourceEagerHydrationData=null}function Av(e,t,r,n,i,a,o,s,l){return e=new Q2(e,t,r,s,l),t===1?(t=1,a===!0&&(t|=8)):t=0,a=er(3,null,null,t),e.current=a,a.stateNode=e,a.memoizedState={element:n,isDehydrated:r,cache:null,transitions:null,pendingSuspenseBoundaries:null},fv(a),e}function Z2(e,t,r){var n=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:Hi,key:n==null?null:""+n,children:e,containerInfo:t,implementation:r}}function wS(e){if(!e)return Rn;e=e._reactInternals;e:{if(Ti(e)!==e||e.tag!==1)throw Error(H(170));var t=e;do{switch(t.tag){case 3:t=t.stateNode.context;break e;case 1:if($t(t.type)){t=t.stateNode.__reactInternalMemoizedMergedChildContext;break e}}t=t.return}while(t!==null);throw Error(H(171))}if(e.tag===1){var r=e.type;if($t(r))return wj(e,r,t)}return t}function jS(e,t,r,n,i,a,o,s,l){return e=Av(r,n,!0,e,i,a,o,s,l),e.context=wS(null),r=e.current,n=bt(),i=Tn(r),a=Vr(n,i),a.callback=t??null,$n(r,a,i),e.current.lanes=i,ol(e,i,n),Et(e,n),e}function sf(e,t,r,n){var i=t.current,a=bt(),o=Tn(i);return r=wS(r),t.context===null?t.context=r:t.pendingContext=r,t=Vr(a,o),t.payload={element:e},n=n===void 0?null:n,n!==null&&(t.callback=n),e=$n(i,t,o),e!==null&&(gr(e,i,o,a),lu(e,i,o)),o}function Bu(e){if(e=e.current,!e.child)return null;switch(e.child.tag){case 5:return e.child.stateNode;default:return e.child.stateNode}}function qg(e,t){if(e=e.memoizedState,e!==null&&e.dehydrated!==null){var r=e.retryLane;e.retryLane=r!==0&&r<t?r:t}}function Nv(e,t){qg(e,t),(e=e.alternate)&&qg(e,t)}function J2(){return null}var SS=typeof reportError=="function"?reportError:function(e){console.error(e)};function $v(e){this._internalRoot=e}lf.prototype.render=$v.prototype.render=function(e){var t=this._internalRoot;if(t===null)throw Error(H(409));sf(e,t,null,null)};lf.prototype.unmount=$v.prototype.unmount=function(){var e=this._internalRoot;if(e!==null){this._internalRoot=null;var t=e.containerInfo;_i(function(){sf(null,e,null,null)}),t[Qr]=null}};function lf(e){this._internalRoot=e}lf.prototype.unstable_scheduleHydration=function(e){if(e){var t=ej();e={blockedOn:null,target:e,priority:t};for(var r=0;r<vn.length&&t!==0&&t<vn[r].priority;r++);vn.splice(r,0,e),r===0&&rj(e)}};function Ev(e){return!(!e||e.nodeType!==1&&e.nodeType!==9&&e.nodeType!==11)}function uf(e){return!(!e||e.nodeType!==1&&e.nodeType!==9&&e.nodeType!==11&&(e.nodeType!==8||e.nodeValue!==" react-mount-point-unstable "))}function Xg(){}function eN(e,t,r,n,i){if(i){if(typeof n=="function"){var a=n;n=function(){var u=Bu(o);a.call(u)}}var o=jS(t,n,e,0,null,!1,!1,"",Xg);return e._reactRootContainer=o,e[Qr]=o.current,ps(e.nodeType===8?e.parentNode:e),_i(),o}for(;i=e.lastChild;)e.removeChild(i);if(typeof n=="function"){var s=n;n=function(){var u=Bu(l);s.call(u)}}var l=Av(e,0,!1,null,null,!1,!1,"",Xg);return e._reactRootContainer=l,e[Qr]=l.current,ps(e.nodeType===8?e.parentNode:e),_i(function(){sf(t,l,r,n)}),l}function cf(e,t,r,n,i){var a=r._reactRootContainer;if(a){var o=a;if(typeof i=="function"){var s=i;i=function(){var l=Bu(o);s.call(l)}}sf(t,o,e,i)}else o=eN(r,t,e,i,n);return Bu(o)}Zw=function(e){switch(e.tag){case 3:var t=e.stateNode;if(t.current.memoizedState.isDehydrated){var r=Ro(t.pendingLanes);r!==0&&(Xm(t,r|1),Et(t,De()),!(le&6)&&(Sa=De()+500,Kn()))}break;case 13:_i(function(){var n=Zr(e,1);if(n!==null){var i=bt();gr(n,e,1,i)}}),Nv(e,1)}};Qm=function(e){if(e.tag===13){var t=Zr(e,134217728);if(t!==null){var r=bt();gr(t,e,134217728,r)}Nv(e,134217728)}};Jw=function(e){if(e.tag===13){var t=Tn(e),r=Zr(e,t);if(r!==null){var n=bt();gr(r,e,t,n)}Nv(e,t)}};ej=function(){return fe};tj=function(e,t){var r=fe;try{return fe=e,t()}finally{fe=r}};_p=function(e,t,r){switch(t){case"input":if(gp(e,r),t=r.name,r.type==="radio"&&t!=null){for(r=e;r.parentNode;)r=r.parentNode;for(r=r.querySelectorAll("input[name="+JSON.stringify(""+t)+'][type="radio"]'),t=0;t<r.length;t++){var n=r[t];if(n!==e&&n.form===e.form){var i=Jc(n);if(!i)throw Error(H(90));Tw(n),gp(n,i)}}}break;case"textarea":Mw(e,r);break;case"select":t=r.value,t!=null&&la(e,!!r.multiple,t,!1)}};zw=Ov;Ww=_i;var tN={usingClientEntryPoint:!1,Events:[ll,Xi,Jc,Bw,Fw,Ov]},_o={findFiberByHostInstance:li,bundleType:0,version:"18.3.1",rendererPackageName:"react-dom"},rN={bundleType:_o.bundleType,version:_o.version,rendererPackageName:_o.rendererPackageName,rendererConfig:_o.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:nn.ReactCurrentDispatcher,findHostInstanceByFiber:function(e){return e=Hw(e),e===null?null:e.stateNode},findFiberByHostInstance:_o.findFiberByHostInstance||J2,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.3.1-next-f1338f8080-20240426"};if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"){var Fl=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!Fl.isDisabled&&Fl.supportsFiber)try{qc=Fl.inject(rN),$r=Fl}catch{}}Kt.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=tN;Kt.createPortal=function(e,t){var r=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!Ev(t))throw Error(H(200));return Z2(e,t,null,r)};Kt.createRoot=function(e,t){if(!Ev(e))throw Error(H(299));var r=!1,n="",i=SS;return t!=null&&(t.unstable_strictMode===!0&&(r=!0),t.identifierPrefix!==void 0&&(n=t.identifierPrefix),t.onRecoverableError!==void 0&&(i=t.onRecoverableError)),t=Av(e,1,!1,null,null,r,!1,n,i),e[Qr]=t.current,ps(e.nodeType===8?e.parentNode:e),new $v(t)};Kt.findDOMNode=function(e){if(e==null)return null;if(e.nodeType===1)return e;var t=e._reactInternals;if(t===void 0)throw typeof e.render=="function"?Error(H(188)):(e=Object.keys(e).join(","),Error(H(268,e)));return e=Hw(t),e=e===null?null:e.stateNode,e};Kt.flushSync=function(e){return _i(e)};Kt.hydrate=function(e,t,r){if(!uf(t))throw Error(H(200));return cf(null,e,t,!0,r)};Kt.hydrateRoot=function(e,t,r){if(!Ev(e))throw Error(H(405));var n=r!=null&&r.hydratedSources||null,i=!1,a="",o=SS;if(r!=null&&(r.unstable_strictMode===!0&&(i=!0),r.identifierPrefix!==void 0&&(a=r.identifierPrefix),r.onRecoverableError!==void 0&&(o=r.onRecoverableError)),t=jS(t,null,e,1,r??null,i,!1,a,o),e[Qr]=t.current,ps(e),n)for(e=0;e<n.length;e++)r=n[e],i=r._getVersion,i=i(r._source),t.mutableSourceEagerHydrationData==null?t.mutableSourceEagerHydrationData=[r,i]:t.mutableSourceEagerHydrationData.push(r,i);return new lf(t)};Kt.render=function(e,t,r){if(!uf(t))throw Error(H(200));return cf(null,e,t,!1,r)};Kt.unmountComponentAtNode=function(e){if(!uf(e))throw Error(H(40));return e._reactRootContainer?(_i(function(){cf(null,null,e,!1,function(){e._reactRootContainer=null,e[Qr]=null})}),!0):!1};Kt.unstable_batchedUpdates=Ov;Kt.unstable_renderSubtreeIntoContainer=function(e,t,r,n){if(!uf(r))throw Error(H(200));if(e==null||e._reactInternals===void 0)throw Error(H(38));return cf(e,t,r,!1,n)};Kt.version="18.3.1-next-f1338f8080-20240426";function OS(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(OS)}catch(e){console.error(e)}}OS(),Ow.exports=Kt;var nN=Ow.exports,Qg=nN;fp.createRoot=Qg.createRoot,fp.hydrateRoot=Qg.hydrateRoot;/**
- * @remix-run/router v1.23.2
- *
- * Copyright (c) Remix Software Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE.md file in the root directory of this source tree.
- *
- * @license MIT
- */function js(){return js=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},js.apply(this,arguments)}var wn;(function(e){e.Pop="POP",e.Push="PUSH",e.Replace="REPLACE"})(wn||(wn={}));const Zg="popstate";function iN(e){e===void 0&&(e={});function t(n,i){let{pathname:a,search:o,hash:s}=n.location;return ih("",{pathname:a,search:o,hash:s},i.state&&i.state.usr||null,i.state&&i.state.key||"default")}function r(n,i){return typeof i=="string"?i:Fu(i)}return oN(t,r,null,e)}function We(e,t){if(e===!1||e===null||typeof e>"u")throw new Error(t)}function Tv(e,t){if(!e){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function aN(){return Math.random().toString(36).substr(2,8)}function Jg(e,t){return{usr:e.state,key:e.key,idx:t}}function ih(e,t,r,n){return r===void 0&&(r=null),js({pathname:typeof e=="string"?e:e.pathname,search:"",hash:""},typeof t=="string"?ro(t):t,{state:r,key:t&&t.key||n||aN()})}function Fu(e){let{pathname:t="/",search:r="",hash:n=""}=e;return r&&r!=="?"&&(t+=r.charAt(0)==="?"?r:"?"+r),n&&n!=="#"&&(t+=n.charAt(0)==="#"?n:"#"+n),t}function ro(e){let t={};if(e){let r=e.indexOf("#");r>=0&&(t.hash=e.substr(r),e=e.substr(0,r));let n=e.indexOf("?");n>=0&&(t.search=e.substr(n),e=e.substr(0,n)),e&&(t.pathname=e)}return t}function oN(e,t,r,n){n===void 0&&(n={});let{window:i=document.defaultView,v5Compat:a=!1}=n,o=i.history,s=wn.Pop,l=null,u=f();u==null&&(u=0,o.replaceState(js({},o.state,{idx:u}),""));function f(){return(o.state||{idx:null}).idx}function d(){s=wn.Pop;let x=f(),y=x==null?null:x-u;u=x,l&&l({action:s,location:g.location,delta:y})}function p(x,y){s=wn.Push;let v=ih(g.location,x,y);u=f()+1;let b=Jg(v,u),S=g.createHref(v);try{o.pushState(b,"",S)}catch(w){if(w instanceof DOMException&&w.name==="DataCloneError")throw w;i.location.assign(S)}a&&l&&l({action:s,location:g.location,delta:1})}function h(x,y){s=wn.Replace;let v=ih(g.location,x,y);u=f();let b=Jg(v,u),S=g.createHref(v);o.replaceState(b,"",S),a&&l&&l({action:s,location:g.location,delta:0})}function m(x){let y=i.location.origin!=="null"?i.location.origin:i.location.href,v=typeof x=="string"?x:Fu(x);return v=v.replace(/ $/,"%20"),We(y,"No window.location.(origin|href) available to create URL for href: "+v),new URL(v,y)}let g={get action(){return s},get location(){return e(i,o)},listen(x){if(l)throw new Error("A history only accepts one active listener");return i.addEventListener(Zg,d),l=x,()=>{i.removeEventListener(Zg,d),l=null}},createHref(x){return t(i,x)},createURL:m,encodeLocation(x){let y=m(x);return{pathname:y.pathname,search:y.search,hash:y.hash}},push:p,replace:h,go(x){return o.go(x)}};return g}var e0;(function(e){e.data="data",e.deferred="deferred",e.redirect="redirect",e.error="error"})(e0||(e0={}));function sN(e,t,r){return r===void 0&&(r="/"),lN(e,t,r)}function lN(e,t,r,n){let i=typeof t=="string"?ro(t):t,a=Cv(i.pathname||"/",r);if(a==null)return null;let o=_S(e);uN(o);let s=null;for(let l=0;s==null&&l<o.length;++l){let u=wN(a);s=gN(o[l],u)}return s}function _S(e,t,r,n){t===void 0&&(t=[]),r===void 0&&(r=[]),n===void 0&&(n="");let i=(a,o,s)=>{let l={relativePath:s===void 0?a.path||"":s,caseSensitive:a.caseSensitive===!0,childrenIndex:o,route:a};l.relativePath.startsWith("/")&&(We(l.relativePath.startsWith(n),'Absolute route path "'+l.relativePath+'" nested under path '+('"'+n+'" is not valid. An absolute child route path ')+"must start with the combined path of all its parent routes."),l.relativePath=l.relativePath.slice(n.length));let u=Mn([n,l.relativePath]),f=r.concat(l);a.children&&a.children.length>0&&(We(a.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+u+'".')),_S(a.children,t,f,u)),!(a.path==null&&!a.index)&&t.push({path:u,score:vN(u,a.index),routesMeta:f})};return e.forEach((a,o)=>{var s;if(a.path===""||!((s=a.path)!=null&&s.includes("?")))i(a,o);else for(let l of PS(a.path))i(a,o,l)}),t}function PS(e){let t=e.split("/");if(t.length===0)return[];let[r,...n]=t,i=r.endsWith("?"),a=r.replace(/\?$/,"");if(n.length===0)return i?[a,""]:[a];let o=PS(n.join("/")),s=[];return s.push(...o.map(l=>l===""?a:[a,l].join("/"))),i&&s.push(...o),s.map(l=>e.startsWith("/")&&l===""?"/":l)}function uN(e){e.sort((t,r)=>t.score!==r.score?r.score-t.score:yN(t.routesMeta.map(n=>n.childrenIndex),r.routesMeta.map(n=>n.childrenIndex)))}const cN=/^:[\w-]+$/,fN=3,dN=2,pN=1,hN=10,mN=-2,t0=e=>e==="*";function vN(e,t){let r=e.split("/"),n=r.length;return r.some(t0)&&(n+=mN),t&&(n+=dN),r.filter(i=>!t0(i)).reduce((i,a)=>i+(cN.test(a)?fN:a===""?pN:hN),n)}function yN(e,t){return e.length===t.length&&e.slice(0,-1).every((n,i)=>n===t[i])?e[e.length-1]-t[t.length-1]:0}function gN(e,t,r){let{routesMeta:n}=e,i={},a="/",o=[];for(let s=0;s<n.length;++s){let l=n[s],u=s===n.length-1,f=a==="/"?t:t.slice(a.length)||"/",d=xN({path:l.relativePath,caseSensitive:l.caseSensitive,end:u},f),p=l.route;if(!d)return null;Object.assign(i,d.params),o.push({params:i,pathname:Mn([a,d.pathname]),pathnameBase:PN(Mn([a,d.pathnameBase])),route:p}),d.pathnameBase!=="/"&&(a=Mn([a,d.pathnameBase]))}return o}function xN(e,t){typeof e=="string"&&(e={path:e,caseSensitive:!1,end:!0});let[r,n]=bN(e.path,e.caseSensitive,e.end),i=t.match(r);if(!i)return null;let a=i[0],o=a.replace(/(.)\/+$/,"$1"),s=i.slice(1);return{params:n.reduce((u,f,d)=>{let{paramName:p,isOptional:h}=f;if(p==="*"){let g=s[d]||"";o=a.slice(0,a.length-g.length).replace(/(.)\/+$/,"$1")}const m=s[d];return h&&!m?u[p]=void 0:u[p]=(m||"").replace(/%2F/g,"/"),u},{}),pathname:a,pathnameBase:o,pattern:e}}function bN(e,t,r){t===void 0&&(t=!1),r===void 0&&(r=!0),Tv(e==="*"||!e.endsWith("*")||e.endsWith("/*"),'Route path "'+e+'" will be treated as if it were '+('"'+e.replace(/\*$/,"/*")+'" because the `*` character must ')+"always follow a `/` in the pattern. To get rid of this warning, "+('please change the route path to "'+e.replace(/\*$/,"/*")+'".'));let n=[],i="^"+e.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(o,s,l)=>(n.push({paramName:s,isOptional:l!=null}),l?"/?([^\\/]+)?":"/([^\\/]+)"));return e.endsWith("*")?(n.push({paramName:"*"}),i+=e==="*"||e==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):r?i+="\\/*$":e!==""&&e!=="/"&&(i+="(?:(?=\\/|$))"),[new RegExp(i,t?void 0:"i"),n]}function wN(e){try{return e.split("/").map(t=>decodeURIComponent(t).replace(/\//g,"%2F")).join("/")}catch(t){return Tv(!1,'The URL path "'+e+'" could not be decoded because it is is a malformed URL segment. This is probably due to a bad percent '+("encoding ("+t+").")),e}}function Cv(e,t){if(t==="/")return e;if(!e.toLowerCase().startsWith(t.toLowerCase()))return null;let r=t.endsWith("/")?t.length-1:t.length,n=e.charAt(r);return n&&n!=="/"?null:e.slice(r)||"/"}const jN=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,SN=e=>jN.test(e);function ON(e,t){t===void 0&&(t="/");let{pathname:r,search:n="",hash:i=""}=typeof e=="string"?ro(e):e,a;if(r)if(SN(r))a=r;else{if(r.includes("//")){let o=r;r=r.replace(/\/\/+/g,"/"),Tv(!1,"Pathnames cannot have embedded double slashes - normalizing "+(o+" -> "+r))}r.startsWith("/")?a=r0(r.substring(1),"/"):a=r0(r,t)}else a=t;return{pathname:a,search:kN(n),hash:AN(i)}}function r0(e,t){let r=t.replace(/\/+$/,"").split("/");return e.split("/").forEach(i=>{i===".."?r.length>1&&r.pop():i!=="."&&r.push(i)}),r.length>1?r.join("/"):"/"}function Ed(e,t,r,n){return"Cannot include a '"+e+"' character in a manually specified "+("`to."+t+"` field ["+JSON.stringify(n)+"]. Please separate it out to the ")+("`to."+r+"` field. Alternatively you may provide the full path as ")+'a string in <Link to="..."> and the router will parse it for you.'}function _N(e){return e.filter((t,r)=>r===0||t.route.path&&t.route.path.length>0)}function kS(e,t){let r=_N(e);return t?r.map((n,i)=>i===r.length-1?n.pathname:n.pathnameBase):r.map(n=>n.pathnameBase)}function AS(e,t,r,n){n===void 0&&(n=!1);let i;typeof e=="string"?i=ro(e):(i=js({},e),We(!i.pathname||!i.pathname.includes("?"),Ed("?","pathname","search",i)),We(!i.pathname||!i.pathname.includes("#"),Ed("#","pathname","hash",i)),We(!i.search||!i.search.includes("#"),Ed("#","search","hash",i)));let a=e===""||i.pathname==="",o=a?"/":i.pathname,s;if(o==null)s=r;else{let d=t.length-1;if(!n&&o.startsWith("..")){let p=o.split("/");for(;p[0]==="..";)p.shift(),d-=1;i.pathname=p.join("/")}s=d>=0?t[d]:"/"}let l=ON(i,s),u=o&&o!=="/"&&o.endsWith("/"),f=(a||o===".")&&r.endsWith("/");return!l.pathname.endsWith("/")&&(u||f)&&(l.pathname+="/"),l}const Mn=e=>e.join("/").replace(/\/\/+/g,"/"),PN=e=>e.replace(/\/+$/,"").replace(/^\/*/,"/"),kN=e=>!e||e==="?"?"":e.startsWith("?")?e:"?"+e,AN=e=>!e||e==="#"?"":e.startsWith("#")?e:"#"+e;function NN(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.internal=="boolean"&&"data"in e}const NS=["post","put","patch","delete"];new Set(NS);const $N=["get",...NS];new Set($N);/**
- * React Router v6.30.3
- *
- * Copyright (c) Remix Software Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE.md file in the root directory of this source tree.
- *
- * @license MIT
- */function Ss(){return Ss=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},Ss.apply(this,arguments)}const Mv=k.createContext(null),EN=k.createContext(null),Ci=k.createContext(null),ff=k.createContext(null),Hn=k.createContext({outlet:null,matches:[],isDataRoute:!1}),$S=k.createContext(null);function TN(e,t){let{relative:r}=t===void 0?{}:t;cl()||We(!1);let{basename:n,navigator:i}=k.useContext(Ci),{hash:a,pathname:o,search:s}=TS(e,{relative:r}),l=o;return n!=="/"&&(l=o==="/"?n:Mn([n,o])),i.createHref({pathname:l,search:s,hash:a})}function cl(){return k.useContext(ff)!=null}function fl(){return cl()||We(!1),k.useContext(ff).location}function ES(e){k.useContext(Ci).static||k.useLayoutEffect(e)}function dl(){let{isDataRoute:e}=k.useContext(Hn);return e?GN():CN()}function CN(){cl()||We(!1);let e=k.useContext(Mv),{basename:t,future:r,navigator:n}=k.useContext(Ci),{matches:i}=k.useContext(Hn),{pathname:a}=fl(),o=JSON.stringify(kS(i,r.v7_relativeSplatPath)),s=k.useRef(!1);return ES(()=>{s.current=!0}),k.useCallback(function(u,f){if(f===void 0&&(f={}),!s.current)return;if(typeof u=="number"){n.go(u);return}let d=AS(u,JSON.parse(o),a,f.relative==="path");e==null&&t!=="/"&&(d.pathname=d.pathname==="/"?t:Mn([t,d.pathname])),(f.replace?n.replace:n.push)(d,f.state,f)},[t,n,o,a,e])}const MN=k.createContext(null);function IN(e){let t=k.useContext(Hn).outlet;return t&&k.createElement(MN.Provider,{value:e},t)}function TS(e,t){let{relative:r}=t===void 0?{}:t,{future:n}=k.useContext(Ci),{matches:i}=k.useContext(Hn),{pathname:a}=fl(),o=JSON.stringify(kS(i,n.v7_relativeSplatPath));return k.useMemo(()=>AS(e,JSON.parse(o),a,r==="path"),[e,o,a,r])}function LN(e,t){return DN(e,t)}function DN(e,t,r,n){cl()||We(!1);let{navigator:i}=k.useContext(Ci),{matches:a}=k.useContext(Hn),o=a[a.length-1],s=o?o.params:{};o&&o.pathname;let l=o?o.pathnameBase:"/";o&&o.route;let u=fl(),f;if(t){var d;let x=typeof t=="string"?ro(t):t;l==="/"||(d=x.pathname)!=null&&d.startsWith(l)||We(!1),f=x}else f=u;let p=f.pathname||"/",h=p;if(l!=="/"){let x=l.replace(/^\//,"").split("/");h="/"+p.replace(/^\//,"").split("/").slice(x.length).join("/")}let m=sN(e,{pathname:h}),g=WN(m&&m.map(x=>Object.assign({},x,{params:Object.assign({},s,x.params),pathname:Mn([l,i.encodeLocation?i.encodeLocation(x.pathname).pathname:x.pathname]),pathnameBase:x.pathnameBase==="/"?l:Mn([l,i.encodeLocation?i.encodeLocation(x.pathnameBase).pathname:x.pathnameBase])})),a,r,n);return t&&g?k.createElement(ff.Provider,{value:{location:Ss({pathname:"/",search:"",hash:"",state:null,key:"default"},f),navigationType:wn.Pop}},g):g}function RN(){let e=VN(),t=NN(e)?e.status+" "+e.statusText:e instanceof Error?e.message:JSON.stringify(e),r=e instanceof Error?e.stack:null,i={padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"};return k.createElement(k.Fragment,null,k.createElement("h2",null,"Unexpected Application Error!"),k.createElement("h3",{style:{fontStyle:"italic"}},t),r?k.createElement("pre",{style:i},r):null,null)}const BN=k.createElement(RN,null);class FN extends k.Component{constructor(t){super(t),this.state={location:t.location,revalidation:t.revalidation,error:t.error}}static getDerivedStateFromError(t){return{error:t}}static getDerivedStateFromProps(t,r){return r.location!==t.location||r.revalidation!=="idle"&&t.revalidation==="idle"?{error:t.error,location:t.location,revalidation:t.revalidation}:{error:t.error!==void 0?t.error:r.error,location:r.location,revalidation:t.revalidation||r.revalidation}}componentDidCatch(t,r){console.error("React Router caught the following error during render",t,r)}render(){return this.state.error!==void 0?k.createElement(Hn.Provider,{value:this.props.routeContext},k.createElement($S.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function zN(e){let{routeContext:t,match:r,children:n}=e,i=k.useContext(Mv);return i&&i.static&&i.staticContext&&(r.route.errorElement||r.route.ErrorBoundary)&&(i.staticContext._deepestRenderedBoundaryId=r.route.id),k.createElement(Hn.Provider,{value:t},n)}function WN(e,t,r,n){var i;if(t===void 0&&(t=[]),r===void 0&&(r=null),n===void 0&&(n=null),e==null){var a;if(!r)return null;if(r.errors)e=r.matches;else if((a=n)!=null&&a.v7_partialHydration&&t.length===0&&!r.initialized&&r.matches.length>0)e=r.matches;else return null}let o=e,s=(i=r)==null?void 0:i.errors;if(s!=null){let f=o.findIndex(d=>d.route.id&&(s==null?void 0:s[d.route.id])!==void 0);f>=0||We(!1),o=o.slice(0,Math.min(o.length,f+1))}let l=!1,u=-1;if(r&&n&&n.v7_partialHydration)for(let f=0;f<o.length;f++){let d=o[f];if((d.route.HydrateFallback||d.route.hydrateFallbackElement)&&(u=f),d.route.id){let{loaderData:p,errors:h}=r,m=d.route.loader&&p[d.route.id]===void 0&&(!h||h[d.route.id]===void 0);if(d.route.lazy||m){l=!0,u>=0?o=o.slice(0,u+1):o=[o[0]];break}}}return o.reduceRight((f,d,p)=>{let h,m=!1,g=null,x=null;r&&(h=s&&d.route.id?s[d.route.id]:void 0,g=d.route.errorElement||BN,l&&(u<0&&p===0?(YN("route-fallback"),m=!0,x=null):u===p&&(m=!0,x=d.route.hydrateFallbackElement||null)));let y=t.concat(o.slice(0,p+1)),v=()=>{let b;return h?b=g:m?b=x:d.route.Component?b=k.createElement(d.route.Component,null):d.route.element?b=d.route.element:b=f,k.createElement(zN,{match:d,routeContext:{outlet:f,matches:y,isDataRoute:r!=null},children:b})};return r&&(d.route.ErrorBoundary||d.route.errorElement||p===0)?k.createElement(FN,{location:r.location,revalidation:r.revalidation,component:g,error:h,children:v(),routeContext:{outlet:null,matches:y,isDataRoute:!0}}):v()},null)}var CS=function(e){return e.UseBlocker="useBlocker",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e}(CS||{}),MS=function(e){return e.UseBlocker="useBlocker",e.UseLoaderData="useLoaderData",e.UseActionData="useActionData",e.UseRouteError="useRouteError",e.UseNavigation="useNavigation",e.UseRouteLoaderData="useRouteLoaderData",e.UseMatches="useMatches",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e.UseRouteId="useRouteId",e}(MS||{});function UN(e){let t=k.useContext(Mv);return t||We(!1),t}function KN(e){let t=k.useContext(EN);return t||We(!1),t}function HN(e){let t=k.useContext(Hn);return t||We(!1),t}function IS(e){let t=HN(),r=t.matches[t.matches.length-1];return r.route.id||We(!1),r.route.id}function VN(){var e;let t=k.useContext($S),r=KN(),n=IS();return t!==void 0?t:(e=r.errors)==null?void 0:e[n]}function GN(){let{router:e}=UN(CS.UseNavigateStable),t=IS(MS.UseNavigateStable),r=k.useRef(!1);return ES(()=>{r.current=!0}),k.useCallback(function(i,a){a===void 0&&(a={}),r.current&&(typeof i=="number"?e.navigate(i):e.navigate(i,Ss({fromRouteId:t},a)))},[e,t])}const n0={};function YN(e,t,r){n0[e]||(n0[e]=!0)}function qN(e,t){e==null||e.v7_startTransition,e==null||e.v7_relativeSplatPath}function XN(e){return IN(e.context)}function Mt(e){We(!1)}function QN(e){let{basename:t="/",children:r=null,location:n,navigationType:i=wn.Pop,navigator:a,static:o=!1,future:s}=e;cl()&&We(!1);let l=t.replace(/^\/*/,"/"),u=k.useMemo(()=>({basename:l,navigator:a,static:o,future:Ss({v7_relativeSplatPath:!1},s)}),[l,s,a,o]);typeof n=="string"&&(n=ro(n));let{pathname:f="/",search:d="",hash:p="",state:h=null,key:m="default"}=n,g=k.useMemo(()=>{let x=Cv(f,l);return x==null?null:{location:{pathname:x,search:d,hash:p,state:h,key:m},navigationType:i}},[l,f,d,p,h,m,i]);return g==null?null:k.createElement(Ci.Provider,{value:u},k.createElement(ff.Provider,{children:r,value:g}))}function ZN(e){let{children:t,location:r}=e;return LN(ah(t),r)}new Promise(()=>{});function ah(e,t){t===void 0&&(t=[]);let r=[];return k.Children.forEach(e,(n,i)=>{if(!k.isValidElement(n))return;let a=[...t,i];if(n.type===k.Fragment){r.push.apply(r,ah(n.props.children,a));return}n.type!==Mt&&We(!1),!n.props.index||!n.props.children||We(!1);let o={id:n.props.id||a.join("-"),caseSensitive:n.props.caseSensitive,element:n.props.element,Component:n.props.Component,index:n.props.index,path:n.props.path,loader:n.props.loader,action:n.props.action,errorElement:n.props.errorElement,ErrorBoundary:n.props.ErrorBoundary,hasErrorBoundary:n.props.ErrorBoundary!=null||n.props.errorElement!=null,shouldRevalidate:n.props.shouldRevalidate,handle:n.props.handle,lazy:n.props.lazy};n.props.children&&(o.children=ah(n.props.children,a)),r.push(o)}),r}/**
- * React Router DOM v6.30.3
- *
- * Copyright (c) Remix Software Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE.md file in the root directory of this source tree.
- *
- * @license MIT
- */function oh(){return oh=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},oh.apply(this,arguments)}function JN(e,t){if(e==null)return{};var r={},n=Object.keys(e),i,a;for(a=0;a<n.length;a++)i=n[a],!(t.indexOf(i)>=0)&&(r[i]=e[i]);return r}function e$(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function t$(e,t){return e.button===0&&(!t||t==="_self")&&!e$(e)}const r$=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset","viewTransition"],n$="6";try{window.__reactRouterVersion=n$}catch{}const i$="startTransition",i0=Vk[i$];function a$(e){let{basename:t,children:r,future:n,window:i}=e,a=k.useRef();a.current==null&&(a.current=iN({window:i,v5Compat:!0}));let o=a.current,[s,l]=k.useState({action:o.action,location:o.location}),{v7_startTransition:u}=n||{},f=k.useCallback(d=>{u&&i0?i0(()=>l(d)):l(d)},[l,u]);return k.useLayoutEffect(()=>o.listen(f),[o,f]),k.useEffect(()=>qN(n),[n]),k.createElement(QN,{basename:t,children:r,location:s.location,navigationType:s.action,navigator:o,future:n})}const o$=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",s$=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,l$=k.forwardRef(function(t,r){let{onClick:n,relative:i,reloadDocument:a,replace:o,state:s,target:l,to:u,preventScrollReset:f,viewTransition:d}=t,p=JN(t,r$),{basename:h}=k.useContext(Ci),m,g=!1;if(typeof u=="string"&&s$.test(u)&&(m=u,o$))try{let b=new URL(window.location.href),S=u.startsWith("//")?new URL(b.protocol+u):new URL(u),w=Cv(S.pathname,h);S.origin===b.origin&&w!=null?u=w+S.search+S.hash:g=!0}catch{}let x=TN(u,{relative:i}),y=u$(u,{replace:o,state:s,target:l,preventScrollReset:f,relative:i,viewTransition:d});function v(b){n&&n(b),b.defaultPrevented||y(b)}return k.createElement("a",oh({},p,{href:m||x,onClick:g||a?n:v,ref:r,target:l}))});var a0;(function(e){e.UseScrollRestoration="useScrollRestoration",e.UseSubmit="useSubmit",e.UseSubmitFetcher="useSubmitFetcher",e.UseFetcher="useFetcher",e.useViewTransitionState="useViewTransitionState"})(a0||(a0={}));var o0;(function(e){e.UseFetcher="useFetcher",e.UseFetchers="useFetchers",e.UseScrollRestoration="useScrollRestoration"})(o0||(o0={}));function u$(e,t){let{target:r,replace:n,state:i,preventScrollReset:a,relative:o,viewTransition:s}=t===void 0?{}:t,l=dl(),u=fl(),f=TS(e,{relative:o});return k.useCallback(d=>{if(t$(d,r)){d.preventDefault();let p=n!==void 0?n:Fu(u)===Fu(f);l(e,{replace:p,state:i,preventScrollReset:a,relative:o,viewTransition:s})}},[u,l,f,n,i,r,e,a,o,s])}const c$="/api";async function tt(e,t={}){const r=await fetch(`${c$}${e}`,{...t,credentials:"same-origin",headers:{"Content-Type":"application/json",...t.headers}});return r.status===401&&!e.startsWith("/auth/")?(window.location.href="/login",{}):r.json()}async function ie(e,t){return tt(e,{method:"POST",body:JSON.stringify(t)})}async function Iv(){try{return(await tt("/auth/session")).authenticated===!0}catch{return!1}}async function f$(e,t){return(await ie("/auth/login",{username:e,password:t})).success===!0}async function d$(e){return await ie("/auth/google",{credential:e})}async function p$(){try{return await tt("/auth/google-config")}catch{return{configured:!1}}}async function h$(){await ie("/auth/logout",{}),window.location.href="/login"}function m$(){const[e,t]=k.useState(""),[r,n]=k.useState(""),[i,a]=k.useState(!1),[o,s]=k.useState(""),[l,u]=k.useState(!1),[f,d]=k.useState(!0),[p,h]=k.useState(!1),[m,g]=k.useState(null),x=k.useRef(null),y=dl();k.useEffect(()=>{Iv().then(j=>{j?y("/"):d(!1)}),p$().then(j=>{j.configured&&j.client_id&&(g(j.client_id),v(j.client_id))})},[]);function v(j){if(document.getElementById("google-gsi"))return;const O=document.createElement("script");O.id="google-gsi",O.src="https://accounts.google.com/gsi/client",O.async=!0,O.defer=!0,O.onload=()=>b(j),document.head.appendChild(O)}function b(j){var O,_;(_=(O=window.google)==null?void 0:O.accounts)!=null&&_.id&&(window.google.accounts.id.initialize({client_id:j,callback:S,auto_select:!1}),h(!0),x.current&&window.google.accounts.id.renderButton(x.current,{type:"standard",theme:"filled_black",size:"large",text:"signin_with",shape:"pill",width:"100%"}))}k.useEffect(()=>{var j,O;p&&x.current&&((O=(j=window.google)==null?void 0:j.accounts)!=null&&O.id)&&window.google.accounts.id.renderButton(x.current,{type:"standard",theme:"filled_black",size:"large",text:"signin_with",shape:"pill",width:360})},[p]);async function S(j){s(""),u(!0);try{const O=await d$(j.credential);O.success?y("/"):s(O.error||"Google login failed")}catch{s("Connection error")}u(!1)}async function w(j){j.preventDefault(),s(""),u(!0);try{await f$(e,r)?y("/"):s("Invalid credentials")}catch{s("Connection error")}u(!1)}return f?c.jsx("div",{className:"min-h-screen flex items-center justify-center",children:c.jsx("div",{className:"animate-spin w-8 h-8 border-2 border-blue-500 border-t-transparent rounded-full"})}):c.jsx("div",{className:"min-h-screen flex items-center justify-center p-4",children:c.jsxs("div",{className:"w-full max-w-md",children:[c.jsxs("div",{className:"text-center mb-8",children:[c.jsx("div",{className:"inline-flex items-center justify-center w-20 h-20 rounded-2xl mb-4",style:{background:"linear-gradient(135deg,#3b82f6,#8b5cf6)"},children:c.jsxs("svg",{width:"40",height:"40",viewBox:"0 0 24 24",fill:"none",stroke:"white",strokeWidth:"2",children:[c.jsx("path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"}),c.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}),c.jsx("h1",{className:"text-3xl font-extrabold bg-gradient-to-r from-blue-400 to-purple-400 bg-clip-text text-transparent",children:"POLY"}),c.jsx("p",{className:"text-gray-400 mt-2 text-sm",children:"Weather Forecast Micro-Betting System"})]}),o&&c.jsxs("div",{className:"text-red-400 text-sm bg-red-500/10 rounded-lg p-3 flex items-center gap-2 mb-4",children:[c.jsx("svg",{className:"w-4 h-4 flex-shrink-0",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})}),o]}),m&&c.jsxs("div",{className:"mb-4",children:[c.jsx("div",{ref:x,className:"flex justify-center"}),c.jsxs("div",{className:"relative my-5",children:[c.jsx("div",{className:"absolute inset-0 flex items-center",children:c.jsx("div",{className:"w-full border-t border-gray-800"})}),c.jsx("div",{className:"relative flex justify-center text-xs",children:c.jsx("span",{className:"px-3 text-gray-500",style:{background:"var(--bg)"},children:"or sign in with password"})})]})]}),c.jsxs("form",{onSubmit:w,className:"card space-y-4",children:[c.jsxs("div",{children:[c.jsx("label",{className:"block text-xs font-medium text-gray-400 mb-1.5",children:"Username"}),c.jsx("input",{type:"text",value:e,onChange:j=>t(j.target.value),required:!0,autoComplete:"username",className:"w-full bg-gray-800/50 border border-gray-700 rounded-lg px-3 py-2.5 text-sm focus:outline-none focus:border-blue-500 transition",placeholder:"admin"})]}),c.jsxs("div",{children:[c.jsx("label",{className:"block text-xs font-medium text-gray-400 mb-1.5",children:"Password"}),c.jsxs("div",{className:"relative",children:[c.jsx("input",{type:i?"text":"password",value:r,onChange:j=>n(j.target.value),required:!0,autoComplete:"current-password",className:"w-full bg-gray-800/50 border border-gray-700 rounded-lg px-3 py-2.5 pr-10 text-sm focus:outline-none focus:border-blue-500 transition",placeholder:"Enter password"}),c.jsx("button",{type:"button",onClick:()=>a(!i),className:"absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-300",children:c.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:i?"M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.878 9.878L3 3m6.878 6.879L21 21":"M15 12a3 3 0 11-6 0 3 3 0 016 0z M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"})})})]})]}),c.jsxs("button",{type:"submit",disabled:l,className:"btn btn-p w-full py-2.5 flex items-center justify-center gap-2 disabled:opacity-50",children:[l&&c.jsx("span",{className:"animate-spin w-4 h-4 border-2 border-white border-t-transparent rounded-full"}),l?"Signing in...":"Sign In"]})]}),c.jsx("div",{className:"mt-6 grid grid-cols-3 gap-2 text-center",children:[{l:"Bankroll",v:"$50",c:"text-green-400"},{l:"Mode",v:"Paper",c:"text-yellow-400"},{l:"Status",v:"Active",c:"text-blue-400"}].map(j=>c.jsxs("div",{className:"card !p-3",children:[c.jsx("div",{className:`text-lg font-bold ${j.c}`,children:j.v}),c.jsx("div",{className:"text-[10px] text-gray-500 uppercase",children:j.l})]},j.l))}),c.jsxs("div",{className:"text-center mt-4 space-y-1",children:[c.jsx("p",{className:"text-gray-600 text-[10px]",children:"Session: httpOnly cookie / 30-day expiry / IP whitelist"}),m&&c.jsx("p",{className:"text-gray-600 text-[10px]",children:"Google OAuth 2.0 enabled"})]})]})})}const v$=[{to:"/",label:"Overview",d:"M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6"},{to:"/markets",label:"Markets",d:"M13 7h8m0 0v8m0-8l-8 8-4-4-6 6"},{to:"/polymarket",label:"Polymarket",d:"M21 12a9 9 0 01-9 9m9-9a9 9 0 00-9-9m9 9H3m9 9a9 9 0 01-9-9m9 9c1.657 0 3-4.03 3-9s-1.343-9-3-9m0 18c-1.657 0-3-4.03-3-9s1.343-9 3-9"},{to:"/weather",label:"Weather",d:"M3 15a4 4 0 004 4h9a5 5 0 10-.1-9.999 5.002 5.002 0 10-9.78 2.096A4.001 4.001 0 003 15z"},{to:"/models",label:"Models",d:"M9 3v2m6-2v2M9 19v2m6-2v2M5 9H3m2 6H3m18-6h-2m2 6h-2M7 19h10a2 2 0 002-2V7a2 2 0 00-2-2H7a2 2 0 00-2 2v10a2 2 0 002 2zM9 9h6v6H9V9z"},{to:"/risk",label:"Risk",d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"},{to:"/trades",label:"Trades",d:"M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4"},{to:"/bankroll",label:"Bankroll",d:"M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z"},{to:"/settings",label:"Settings",d:"M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.066 2.573c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.573 1.066c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.066-2.573c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z M15 12a3 3 0 11-6 0 3 3 0 016 0z"}];function y$(){const e=fl(),t=dl(),[r,n]=k.useState(null),[i,a]=k.useState(!1),[o,s]=k.useState(!1);if(k.useEffect(()=>{Iv().then(u=>{if(!u){t("/login");return}s(!0);const f=()=>tt("/health").then(p=>{n(p),p&&!p.setup_complete&&t("/setup")}).catch(()=>{});f();const d=setInterval(f,2e4);return()=>clearInterval(d)})},[]),!o)return c.jsx("div",{className:"flex items-center justify-center min-h-screen",children:c.jsx("div",{className:"animate-spin w-8 h-8 border-2 border-blue-500 border-t-transparent rounded-full"})});const l=r==null?void 0:r.paper_mode;return c.jsxs("div",{className:"flex min-h-screen",children:[c.jsxs("aside",{className:`${i?"w-16":"w-56"} bg-gray-900/50 border-r border-gray-800 flex flex-col transition-all duration-200`,children:[c.jsxs("div",{className:"p-4 border-b border-gray-800 flex items-center gap-3",children:[c.jsx("div",{className:"w-8 h-8 rounded-lg flex items-center justify-center flex-shrink-0",style:{background:"linear-gradient(135deg,#3b82f6,#8b5cf6)"},children:c.jsx("span",{className:"text-white font-bold text-sm",children:"P"})}),!i&&c.jsx("span",{className:"font-bold text-sm bg-gradient-to-r from-blue-400 to-purple-400 bg-clip-text text-transparent",children:"POLY"})]}),c.jsx("nav",{className:"flex-1 p-2 space-y-0.5",children:v$.map(u=>{const f=e.pathname===u.to||u.to!=="/"&&e.pathname.startsWith(u.to);return c.jsxs(l$,{to:u.to,className:`flex items-center gap-3 px-3 py-2 rounded-lg text-sm transition ${f?"bg-blue-500/15 text-blue-400 font-medium":"text-gray-400 hover:text-gray-200 hover:bg-gray-800/50"}`,children:[c.jsx("svg",{className:"flex-shrink-0",style:{width:18,height:18},fill:"none",stroke:"currentColor",strokeWidth:"1.5",viewBox:"0 0 24 24",children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:u.d})}),!i&&c.jsx("span",{children:u.label})]},u.to)})}),c.jsxs("div",{className:"p-3 border-t border-gray-800",children:[!i&&r&&c.jsxs("div",{className:"space-y-1.5 text-[11px]",children:[c.jsxs("div",{className:"flex justify-between",children:[c.jsx("span",{className:"text-gray-500",children:"Mode"}),c.jsx("span",{className:l?"text-yellow-400":"text-green-400",children:l?"PAPER":"LIVE"})]}),c.jsxs("div",{className:"flex justify-between",children:[c.jsx("span",{className:"text-gray-500",children:"Kill Switch"}),c.jsx("span",{className:r.kill_switch?"text-red-400":"text-green-400",children:r.kill_switch?"ACTIVE":"OFF"})]}),c.jsxs("div",{className:"flex justify-between",children:[c.jsx("span",{className:"text-gray-500",children:"DB"}),c.jsx("span",{className:r.db_connected?"text-green-400":"text-red-400",children:r.db_connected?"OK":"DOWN"})]})]}),c.jsxs("div",{className:"flex gap-1 mt-2",children:[c.jsx("button",{onClick:()=>a(!i),className:"flex-1 flex items-center justify-center py-1.5 text-gray-500 hover:text-gray-300",children:c.jsx("svg",{className:`w-4 h-4 transition-transform ${i?"":"rotate-180"}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M11 19l-7-7 7-7m8 14l-7-7 7-7"})})}),!i&&c.jsx("button",{onClick:h$,className:"px-2 py-1 text-xs text-gray-500 hover:text-red-400",children:"Logout"})]})]})]}),c.jsx("main",{className:"flex-1 overflow-auto",children:c.jsx("div",{className:"p-6 max-w-[1600px] mx-auto",children:c.jsx(XN,{})})})]})}const g$=[{title:"Market Intelligence",desc:"Scans Polymarket for weather prediction markets and identifies profitable opportunities",icon:"M13 7h8m0 0v8m0-8l-8 8-4-4-6 6"},{title:"Weather Forecasting",desc:"Pulls real NWS forecast data and builds probability models for weather outcomes",icon:"M3 15a4 4 0 004 4h9a5 5 0 10-.1-9.999 5.002 5.002 0 10-9.78 2.096A4.001 4.001 0 003 15z"},{title:"Automated Trading",desc:"Places bets on Polymarket when edges exceed your risk threshold, fully automated",icon:"M9 3v2m6-2v2M9 19v2m6-2v2M5 9H3m2 6H3m18-6h-2m2 6h-2M7 19h10a2 2 0 002-2V7a2 2 0 00-2-2H7a2 2 0 00-2 2v10a2 2 0 002 2zM9 9h6v6H9V9z"}],x$=["Connect to Polymarket API","Ingest weather prediction markets","Fetch NWS forecast data","Generate AI probability models","Calculate edges & signals","Execute trades automatically"];function b$({next:e}){return c.jsxs("div",{className:"space-y-8",children:[c.jsxs("div",{className:"text-center",children:[c.jsx("h1",{className:"text-4xl font-bold wizard-gradient mb-3",children:"Welcome to Poly"}),c.jsx("p",{className:"text-gray-400 text-lg",children:"Weather-forecast micro-betting on Polymarket"})]}),c.jsx("div",{className:"grid grid-cols-3 gap-4",children:g$.map(t=>c.jsxs("div",{className:"card text-center",children:[c.jsx("div",{className:"w-10 h-10 rounded-lg bg-blue-500/10 flex items-center justify-center mx-auto mb-3",children:c.jsx("svg",{className:"w-5 h-5 text-blue-400",fill:"none",stroke:"currentColor",strokeWidth:"1.5",viewBox:"0 0 24 24",children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:t.icon})})}),c.jsx("h3",{className:"font-semibold text-sm mb-1",children:t.title}),c.jsx("p",{className:"text-xs text-gray-500 leading-relaxed",children:t.desc})]},t.title))}),c.jsxs("div",{className:"card",children:[c.jsx("h3",{className:"font-semibold text-sm mb-3",children:"How it works"}),c.jsx("div",{className:"grid grid-cols-2 gap-2",children:x$.map((t,r)=>c.jsxs("div",{className:"flex items-center gap-3 py-1.5",children:[c.jsx("span",{className:"w-6 h-6 rounded-full bg-blue-500/15 text-blue-400 flex items-center justify-center text-xs font-bold flex-shrink-0",children:r+1}),c.jsx("span",{className:"text-sm text-gray-300",children:t})]},r))})]}),c.jsx("div",{className:"card bg-yellow-500/5 border-yellow-500/20",children:c.jsxs("div",{className:"flex items-start gap-3",children:[c.jsx("svg",{className:"w-5 h-5 text-yellow-400 mt-0.5 flex-shrink-0",fill:"none",stroke:"currentColor",strokeWidth:"1.5",viewBox:"0 0 24 24",children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 9v3.75m9-.75a9 9 0 11-18 0 9 9 0 0118 0zm-9 3.75h.008v.008H12v-.008z"})}),c.jsxs("div",{children:[c.jsx("p",{className:"text-sm font-medium text-yellow-400",children:"You'll need Polymarket Builder API keys"}),c.jsx("p",{className:"text-xs text-gray-400 mt-1",children:"Go to polymarket.com → Settings → Builder tab to create API credentials. You can also skip this and use paper mode."})]})]})}),c.jsx("div",{className:"flex justify-center",children:c.jsx("button",{onClick:e,className:"wizard-btn",children:"Get Started"})})]})}function w$({data:e,update:t,next:r,back:n}){var S,w,j,O;const[i,a]=k.useState(((S=e.keys)==null?void 0:S.api_key)||""),[o,s]=k.useState(((w=e.keys)==null?void 0:w.api_secret)||""),[l,u]=k.useState(((j=e.keys)==null?void 0:j.api_passphrase)||""),[f,d]=k.useState(((O=e.keys)==null?void 0:O.wallet)||""),[p,h]=k.useState(!1),[m,g]=k.useState(!1),[x,y]=k.useState(null);async function v(){g(!0),y(null);try{const _=await ie("/polymarket",{action:"save_keys",api_key:i,api_secret:o,api_passphrase:l,wallet:f||void 0});_.success?(t({keys:{api_key:i,api_secret:o,api_passphrase:l,wallet:f}}),r()):y(_.error||"Failed to save")}catch{y("Connection error")}g(!1)}function b(){t({keys:null,skippedConnect:!0}),r()}return c.jsxs("div",{className:"space-y-6",children:[c.jsxs("div",{className:"text-center",children:[c.jsx("h2",{className:"text-2xl font-bold mb-2",children:"Connect Polymarket"}),c.jsx("p",{className:"text-gray-400 text-sm",children:"Enter your Builder API credentials to enable live trading"})]}),c.jsxs("div",{className:"card space-y-4",children:[c.jsxs("div",{children:[c.jsx("label",{className:"block text-xs text-gray-400 mb-1.5 font-medium",children:"API Key"}),c.jsx("input",{type:"text",value:i,onChange:_=>a(_.target.value),placeholder:"Your Polymarket API key",className:"w-full px-3 py-2 bg-gray-800/50 border border-gray-700 rounded-lg text-sm focus:border-blue-500 focus:outline-none font-mono"})]}),c.jsxs("div",{children:[c.jsx("label",{className:"block text-xs text-gray-400 mb-1.5 font-medium",children:"API Secret"}),c.jsxs("div",{className:"relative",children:[c.jsx("input",{type:p?"text":"password",value:o,onChange:_=>s(_.target.value),placeholder:"Your API secret",className:"w-full px-3 py-2 bg-gray-800/50 border border-gray-700 rounded-lg text-sm focus:border-blue-500 focus:outline-none font-mono pr-16"}),c.jsx("button",{onClick:()=>h(!p),className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-gray-500 hover:text-gray-300",children:p?"Hide":"Show"})]})]}),c.jsxs("div",{children:[c.jsx("label",{className:"block text-xs text-gray-400 mb-1.5 font-medium",children:"Passphrase"}),c.jsx("input",{type:"password",value:l,onChange:_=>u(_.target.value),placeholder:"Your API passphrase",className:"w-full px-3 py-2 bg-gray-800/50 border border-gray-700 rounded-lg text-sm focus:border-blue-500 focus:outline-none font-mono"})]}),c.jsxs("div",{children:[c.jsxs("label",{className:"block text-xs text-gray-400 mb-1.5 font-medium",children:["Wallet Address ",c.jsx("span",{className:"text-gray-600",children:"(optional)"})]}),c.jsx("input",{type:"text",value:f,onChange:_=>d(_.target.value),placeholder:"0x...",className:"w-full px-3 py-2 bg-gray-800/50 border border-gray-700 rounded-lg text-sm focus:border-blue-500 focus:outline-none font-mono"})]}),x&&c.jsx("p",{className:"text-red-400 text-xs",children:x})]}),c.jsxs("div",{className:"card bg-gray-800/30",children:[c.jsx("h3",{className:"text-sm font-medium mb-2",children:"Where to get your keys"}),c.jsxs("ol",{className:"text-xs text-gray-400 space-y-1.5 list-decimal list-inside",children:[c.jsxs("li",{children:["Go to ",c.jsx("span",{className:"text-blue-400 font-mono",children:"polymarket.com"})]}),c.jsx("li",{children:"Click your profile → Settings"}),c.jsxs("li",{children:["Navigate to the ",c.jsx("span",{className:"text-blue-400",children:"Builder"})," tab"]}),c.jsx("li",{children:"Create a new API key — save the secret immediately"})]})]}),c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsx("button",{onClick:n,className:"text-sm text-gray-500 hover:text-gray-300",children:"Back"}),c.jsxs("div",{className:"flex items-center gap-3",children:[c.jsx("button",{onClick:b,className:"text-sm text-gray-500 hover:text-gray-300",children:"Skip (paper mode)"}),c.jsx("button",{onClick:v,disabled:m||!i&&!o,className:"wizard-btn",children:m?"Saving...":"Save & Continue"})]})]})]})}function j$({data:e,update:t,next:r,back:n}){const[i,a]=k.useState(null),[o,s]=k.useState(null),[l,u]=k.useState(!0),[f,d]=k.useState(!1);k.useEffect(()=>{p()},[]);async function p(){u(!0);try{const g=await ie("/polymarket",{action:"test_public"});a(g),g.success&&e.keys&&h()}catch{a({error:!0})}u(!1)}async function h(){d(!0);try{const g=await ie("/polymarket",{action:"auth_test"});s(g),g.success&&t({connectionOk:!0})}catch{s({error:!0})}d(!1)}const m=e.skippedConnect;return c.jsxs("div",{className:"space-y-6",children:[c.jsxs("div",{className:"text-center",children:[c.jsx("h2",{className:"text-2xl font-bold mb-2",children:"Test Connection"}),c.jsx("p",{className:"text-gray-400 text-sm",children:"Verifying your Polymarket API access"})]}),c.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[c.jsxs("div",{className:"card",children:[c.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[l?c.jsx("div",{className:"animate-spin w-5 h-5 border-2 border-blue-500 border-t-transparent rounded-full"}):i!=null&&i.success?c.jsx("div",{className:"w-5 h-5 rounded-full bg-green-500 flex items-center justify-center",children:c.jsx("svg",{className:"w-3 h-3 text-white",fill:"none",stroke:"currentColor",strokeWidth:"3",viewBox:"0 0 24 24",children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5 13l4 4L19 7"})})}):c.jsx("div",{className:"w-5 h-5 rounded-full bg-red-500 flex items-center justify-center",children:c.jsx("svg",{className:"w-3 h-3 text-white",fill:"none",stroke:"currentColor",strokeWidth:"3",viewBox:"0 0 24 24",children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})})}),c.jsx("h3",{className:"font-semibold text-sm",children:"Public CLOB"})]}),i!=null&&i.success?c.jsxs("div",{className:"space-y-1 text-xs text-gray-400",children:[c.jsxs("p",{children:["Server Time: ",c.jsx("span",{className:"text-green-400 font-mono",children:i.server_time?new Date(parseInt(i.server_time)*1e3).toLocaleTimeString():"OK"})]}),c.jsxs("p",{children:["Endpoint: ",c.jsx("span",{className:"text-gray-300 font-mono",children:"clob.polymarket.com"})]})]}):i!=null&&i.error?c.jsx("p",{className:"text-xs text-red-400",children:"Could not reach CLOB API"}):null]}),c.jsxs("div",{className:"card",children:[c.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[m?c.jsx("div",{className:"w-5 h-5 rounded-full bg-yellow-500 flex items-center justify-center",children:c.jsx("span",{className:"text-white text-xs font-bold",children:"—"})}):f?c.jsx("div",{className:"animate-spin w-5 h-5 border-2 border-purple-500 border-t-transparent rounded-full"}):o!=null&&o.success?c.jsx("div",{className:"w-5 h-5 rounded-full bg-green-500 flex items-center justify-center",children:c.jsx("svg",{className:"w-3 h-3 text-white",fill:"none",stroke:"currentColor",strokeWidth:"3",viewBox:"0 0 24 24",children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5 13l4 4L19 7"})})}):o!=null&&o.error?c.jsx("div",{className:"w-5 h-5 rounded-full bg-red-500 flex items-center justify-center",children:c.jsx("svg",{className:"w-3 h-3 text-white",fill:"none",stroke:"currentColor",strokeWidth:"3",viewBox:"0 0 24 24",children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})})}):c.jsx("div",{className:"w-5 h-5 rounded-full bg-gray-600"}),c.jsx("h3",{className:"font-semibold text-sm",children:"Authenticated"})]}),m?c.jsx("p",{className:"text-xs text-yellow-400",children:"Skipped — paper mode only"}):o!=null&&o.success?c.jsx("p",{className:"text-xs text-green-400",children:"HMAC-SHA256 auth verified"}):o!=null&&o.error?c.jsx("p",{className:"text-xs text-red-400",children:"Auth failed — check credentials"}):e.keys?c.jsx("p",{className:"text-xs text-gray-500",children:"Waiting for public test..."}):c.jsx("p",{className:"text-xs text-gray-500",children:"No keys provided"})]})]}),!l&&!f&&c.jsx("div",{className:"flex justify-center",children:c.jsx("button",{onClick:p,className:"text-xs text-gray-500 hover:text-gray-300",children:"Retry Tests"})}),c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsx("button",{onClick:n,className:"text-sm text-gray-500 hover:text-gray-300",children:"Back"}),c.jsx("button",{onClick:r,className:"wizard-btn",children:"Continue"})]})]})}function S$({data:e,update:t,next:r,back:n}){var d;const[i,a]=k.useState(!0),[o,s]=k.useState(null),[l,u]=k.useState(null);k.useEffect(()=>{f()},[]);async function f(){var p;a(!0),u(null);try{const h=await ie("/markets",{action:"ingest"});s(h),t({marketsIngested:h.ingested||((p=h.markets)==null?void 0:p.length)||0})}catch{u("Failed to ingest markets")}a(!1)}return c.jsxs("div",{className:"space-y-6",children:[c.jsxs("div",{className:"text-center",children:[c.jsx("h2",{className:"text-2xl font-bold mb-2",children:"Ingest Markets"}),c.jsx("p",{className:"text-gray-400 text-sm",children:"Scanning Polymarket for weather prediction markets"})]}),c.jsx("div",{className:"card",children:i?c.jsxs("div",{className:"flex flex-col items-center justify-center py-12 gap-4",children:[c.jsx("div",{className:"animate-spin w-10 h-10 border-3 border-purple-500 border-t-transparent rounded-full"}),c.jsx("p",{className:"text-sm text-gray-400",children:"Scanning Polymarket for weather markets..."})]}):l?c.jsxs("div",{className:"text-center py-8",children:[c.jsx("div",{className:"w-12 h-12 rounded-full bg-red-500/10 flex items-center justify-center mx-auto mb-3",children:c.jsx("svg",{className:"w-6 h-6 text-red-400",fill:"none",stroke:"currentColor",strokeWidth:"1.5",viewBox:"0 0 24 24",children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 9v3.75m9-.75a9 9 0 11-18 0 9 9 0 0118 0zm-9 3.75h.008v.008H12v-.008z"})})}),c.jsx("p",{className:"text-red-400 text-sm mb-3",children:l}),c.jsx("button",{onClick:f,className:"btn btn-s text-sm",children:"Retry"})]}):c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[c.jsxs("div",{className:"text-center",children:[c.jsx("p",{className:"stat-v text-purple-400",children:(o==null?void 0:o.scanned)||"—"}),c.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Scanned"})]}),c.jsxs("div",{className:"text-center",children:[c.jsx("p",{className:"stat-v text-green-400",children:(o==null?void 0:o.ingested)||((d=o==null?void 0:o.markets)==null?void 0:d.length)||0}),c.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Ingested"})]}),c.jsxs("div",{className:"text-center",children:[c.jsx("p",{className:"stat-v text-blue-400",children:(o==null?void 0:o.skipped)||0}),c.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Skipped"})]})]}),((o==null?void 0:o.markets)||[]).length>0&&c.jsxs("div",{className:"border-t border-gray-800 pt-3 mt-3",children:[c.jsx("p",{className:"text-xs text-gray-500 mb-2 uppercase font-medium",children:"Ingested Markets"}),c.jsxs("div",{className:"space-y-1.5 max-h-48 overflow-y-auto",children:[(o.markets||[]).slice(0,10).map((p,h)=>c.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[c.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-green-500 flex-shrink-0"}),c.jsx("span",{className:"text-gray-300 truncate",children:p.question||p})]},h)),(o.markets||[]).length>10&&c.jsxs("p",{className:"text-xs text-gray-600",children:["+",o.markets.length-10," more"]})]})]})]})}),c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsx("button",{onClick:n,className:"text-sm text-gray-500 hover:text-gray-300",children:"Back"}),c.jsx("button",{onClick:r,disabled:i,className:"wizard-btn",children:i?"Processing...":"Continue"})]})]})}function O$({data:e,update:t,next:r,back:n}){const[i,a]=k.useState(!0),[o,s]=k.useState(null),[l,u]=k.useState(null);k.useEffect(()=>{f()},[]);async function f(){a(!0),u(null);try{const d=await ie("/weather",{action:"fetch_all"});s(d),t({weatherFetched:!0})}catch{u("Failed to fetch weather data")}a(!1)}return c.jsxs("div",{className:"space-y-6",children:[c.jsxs("div",{className:"text-center",children:[c.jsx("h2",{className:"text-2xl font-bold mb-2",children:"Weather Data"}),c.jsx("p",{className:"text-gray-400 text-sm",children:"Pulling NWS forecast data for tracked markets"})]}),c.jsx("div",{className:"card",children:i?c.jsxs("div",{className:"flex flex-col items-center justify-center py-12 gap-4",children:[c.jsx("div",{className:"animate-spin w-10 h-10 border-3 border-blue-500 border-t-transparent rounded-full"}),c.jsx("p",{className:"text-sm text-gray-400",children:"Fetching NWS forecast data..."})]}):l?c.jsxs("div",{className:"text-center py-8",children:[c.jsx("div",{className:"w-12 h-12 rounded-full bg-red-500/10 flex items-center justify-center mx-auto mb-3",children:c.jsx("svg",{className:"w-6 h-6 text-red-400",fill:"none",stroke:"currentColor",strokeWidth:"1.5",viewBox:"0 0 24 24",children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 9v3.75m9-.75a9 9 0 11-18 0 9 9 0 0118 0zm-9 3.75h.008v.008H12v-.008z"})})}),c.jsx("p",{className:"text-red-400 text-sm mb-3",children:l}),c.jsx("button",{onClick:f,className:"btn btn-s text-sm",children:"Retry"})]}):c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"flex items-center justify-center gap-3 py-4",children:[c.jsx("div",{className:"w-12 h-12 rounded-full bg-green-500/10 flex items-center justify-center",children:c.jsx("svg",{className:"w-6 h-6 text-green-400",fill:"none",stroke:"currentColor",strokeWidth:"2",viewBox:"0 0 24 24",children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5 13l4 4L19 7"})})}),c.jsxs("div",{children:[c.jsx("p",{className:"font-semibold text-green-400",children:"Weather Data Loaded"}),c.jsx("p",{className:"text-xs text-gray-400",children:"NWS forecasts fetched successfully"})]})]}),c.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[c.jsxs("div",{className:"text-center p-3 bg-gray-800/30 rounded-lg",children:[c.jsx("p",{className:"stat-v text-blue-400",children:(o==null?void 0:o.cities)||(o==null?void 0:o.locations)||"—"}),c.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Cities Fetched"})]}),c.jsxs("div",{className:"text-center p-3 bg-gray-800/30 rounded-lg",children:[c.jsx("p",{className:"stat-v text-purple-400",children:(o==null?void 0:o.data_points)||(o==null?void 0:o.forecasts)||"—"}),c.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Data Points"})]})]})]})}),c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsx("button",{onClick:n,className:"text-sm text-gray-500 hover:text-gray-300",children:"Back"}),c.jsx("button",{onClick:r,disabled:i,className:"wizard-btn",children:i?"Fetching...":"Continue"})]})]})}function _$({data:e,update:t,next:r,back:n}){const[i,a]=k.useState(!0),[o,s]=k.useState(null),[l,u]=k.useState(null);k.useEffect(()=>{f()},[]);async function f(){a(!0),u(null);try{const h=await ie("/models",{action:"run_predictions"});s(h),t({predictionsRun:!0})}catch{u("Failed to generate predictions")}a(!1)}const d=(o==null?void 0:o.predictions)||[],p=d.filter(h=>h.signal==="BUY"||h.edge>0);return c.jsxs("div",{className:"space-y-6",children:[c.jsxs("div",{className:"text-center",children:[c.jsx("h2",{className:"text-2xl font-bold mb-2",children:"AI Predictions"}),c.jsx("p",{className:"text-gray-400 text-sm",children:"Generating probability models and calculating edges"})]}),c.jsx("div",{className:"card",children:i?c.jsxs("div",{className:"flex flex-col items-center justify-center py-12 gap-4",children:[c.jsx("div",{className:"animate-spin w-10 h-10 border-3 border-green-500 border-t-transparent rounded-full"}),c.jsx("p",{className:"text-sm text-gray-400",children:"Running prediction models..."})]}):l?c.jsxs("div",{className:"text-center py-8",children:[c.jsx("div",{className:"w-12 h-12 rounded-full bg-red-500/10 flex items-center justify-center mx-auto mb-3",children:c.jsx("svg",{className:"w-6 h-6 text-red-400",fill:"none",stroke:"currentColor",strokeWidth:"1.5",viewBox:"0 0 24 24",children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 9v3.75m9-.75a9 9 0 11-18 0 9 9 0 0118 0zm-9 3.75h.008v.008H12v-.008z"})})}),c.jsx("p",{className:"text-red-400 text-sm mb-3",children:l}),c.jsx("button",{onClick:f,className:"btn btn-s text-sm",children:"Retry"})]}):c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[c.jsxs("div",{className:"text-center",children:[c.jsx("p",{className:"stat-v text-purple-400",children:d.length}),c.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Predictions"})]}),c.jsxs("div",{className:"text-center",children:[c.jsx("p",{className:"stat-v text-green-400",children:p.length}),c.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Buy Signals"})]}),c.jsxs("div",{className:"text-center",children:[c.jsx("p",{className:"stat-v text-blue-400",children:(o==null?void 0:o.edges_found)||p.length}),c.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Edges Found"})]})]}),d.length>0&&c.jsxs("div",{className:"border-t border-gray-800 pt-3",children:[c.jsx("p",{className:"text-xs text-gray-500 mb-2 uppercase font-medium",children:"Top Predictions"}),c.jsxs("table",{children:[c.jsx("thead",{children:c.jsxs("tr",{children:[c.jsx("th",{children:"Market"}),c.jsx("th",{children:"P(Yes)"}),c.jsx("th",{children:"Edge"}),c.jsx("th",{children:"Signal"})]})}),c.jsx("tbody",{children:d.slice(0,6).map((h,m)=>c.jsxs("tr",{children:[c.jsx("td",{className:"max-w-[200px]",children:c.jsx("span",{className:"truncate block text-xs",children:h.question||h.market})}),c.jsxs("td",{className:"font-mono text-sm",children:[((h.p_yes||h.probability||0)*100).toFixed(1),"%"]}),c.jsxs("td",{className:`font-mono text-sm ${(h.edge||0)>0?"text-green-400":"text-gray-500"}`,children:[((h.edge||0)*100).toFixed(1),"%"]}),c.jsx("td",{children:c.jsx("span",{className:`badge ${h.signal==="BUY"||(h.edge||0)>0?"bg-green":"bg-red"}`,children:h.signal||((h.edge||0)>0?"BUY":"HOLD")})})]},m))})]})]}),d.length===0&&!l&&c.jsx("div",{className:"text-center py-4",children:c.jsx("p",{className:"text-gray-500 text-sm",children:"No predictions generated yet — models may need more market data"})})]})}),c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsx("button",{onClick:n,className:"text-sm text-gray-500 hover:text-gray-300",children:"Back"}),c.jsx("button",{onClick:r,disabled:i,className:"wizard-btn",children:i?"Processing...":"Continue"})]})]})}const s0=[{name:"Conservative",kelly:.05,maxBet:.25,survival:.99,color:"blue",desc:"Small bets, maximum safety. Best for learning."},{name:"Moderate",kelly:.1,maxBet:.5,survival:.9,color:"purple",desc:"Balanced risk/reward. Recommended for most users.",recommended:!0},{name:"Aggressive",kelly:.2,maxBet:1,survival:.7,color:"red",desc:"Larger bets, higher variance. For experienced traders."}];function P$({data:e,update:t,next:r,back:n}){const[i,a]=k.useState(e.riskProfile||"Moderate"),[o,s]=k.useState(!1);async function l(){s(!0);const u=s0.find(f=>f.name===i);try{await ie("/risk",{action:"update_config",kelly_fraction:u.kelly,max_bet:u.maxBet,survival_target:u.survival,risk_profile:u.name}),t({riskProfile:i}),r()}catch{}s(!1)}return c.jsxs("div",{className:"space-y-6",children:[c.jsxs("div",{className:"text-center",children:[c.jsx("h2",{className:"text-2xl font-bold mb-2",children:"Risk Profile"}),c.jsx("p",{className:"text-gray-400 text-sm",children:"Choose how aggressively Poly should trade"})]}),c.jsx("div",{className:"grid grid-cols-3 gap-4",children:s0.map(u=>c.jsxs("button",{onClick:()=>a(u.name),className:`card text-left transition-all relative ${i===u.name?`ring-2 ring-${u.color==="blue"?"blue":u.color==="purple"?"purple":"red"}-500 bg-${u.color==="blue"?"blue":u.color==="purple"?"purple":"red"}-500/5`:"hover:border-gray-700"}`,style:i===u.name?{boxShadow:`0 0 0 2px ${u.color==="blue"?"#3b82f6":u.color==="purple"?"#8b5cf6":"#ef4444"}`}:{},children:[u.recommended&&c.jsx("span",{className:"absolute -top-2 right-3 text-[9px] font-bold uppercase px-2 py-0.5 rounded-full bg-purple-500 text-white",children:"Recommended"}),c.jsx("h3",{className:`font-bold text-lg mb-1 ${u.color==="blue"?"text-blue-400":u.color==="purple"?"text-purple-400":"text-red-400"}`,children:u.name}),c.jsx("p",{className:"text-xs text-gray-500 mb-3",children:u.desc}),c.jsxs("div",{className:"space-y-1.5 text-xs",children:[c.jsxs("div",{className:"flex justify-between",children:[c.jsx("span",{className:"text-gray-500",children:"Kelly Fraction"}),c.jsxs("span",{className:"font-mono text-gray-300",children:[(u.kelly*100).toFixed(0),"%"]})]}),c.jsxs("div",{className:"flex justify-between",children:[c.jsx("span",{className:"text-gray-500",children:"Max Bet"}),c.jsxs("span",{className:"font-mono text-gray-300",children:["$",u.maxBet.toFixed(2)]})]}),c.jsxs("div",{className:"flex justify-between",children:[c.jsx("span",{className:"text-gray-500",children:"Survival Target"}),c.jsxs("span",{className:"font-mono text-gray-300",children:[(u.survival*100).toFixed(0),"%"]})]})]})]},u.name))}),c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsx("button",{onClick:n,className:"text-sm text-gray-500 hover:text-gray-300",children:"Back"}),c.jsx("button",{onClick:l,disabled:o,className:"wizard-btn",children:o?"Saving...":"Save & Continue"})]})]})}const Td=[{key:"keys",label:"Polymarket Connected",check:e=>!!e.keys},{key:"conn",label:"Connection Verified",check:e=>!!e.connectionOk},{key:"markets",label:"Markets Ingested",check:e=>e.marketsIngested>0},{key:"weather",label:"Weather Data Loaded",check:e=>!!e.weatherFetched},{key:"preds",label:"Predictions Generated",check:e=>!!e.predictionsRun},{key:"risk",label:"Risk Profile Set",check:e=>!!e.riskProfile}];function k$({data:e,update:t,complete:r,back:n}){const[i,a]=k.useState(!0),[o,s]=k.useState(!1),l=Td.filter(d=>d.check(e)).length,u=e.skippedConnect;async function f(){s(!0),await r()}return c.jsxs("div",{className:"space-y-6",children:[c.jsxs("div",{className:"text-center",children:[c.jsx("h2",{className:"text-2xl font-bold mb-2",children:"Ready to Launch"}),c.jsx("p",{className:"text-gray-400 text-sm",children:"Review your setup and start trading"})]}),c.jsxs("div",{className:"card",children:[c.jsx("h3",{className:"font-semibold text-sm mb-3",children:"Setup Summary"}),c.jsx("div",{className:"space-y-2",children:Td.map(d=>{const p=d.check(e),h=d.key==="keys"&&u;return c.jsxs("div",{className:"flex items-center gap-3",children:[p?c.jsx("div",{className:"w-5 h-5 rounded-full bg-green-500 flex items-center justify-center flex-shrink-0",children:c.jsx("svg",{className:"w-3 h-3 text-white",fill:"none",stroke:"currentColor",strokeWidth:"3",viewBox:"0 0 24 24",children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5 13l4 4L19 7"})})}):h?c.jsx("div",{className:"w-5 h-5 rounded-full bg-yellow-500 flex items-center justify-center flex-shrink-0",children:c.jsx("span",{className:"text-white text-[10px] font-bold",children:"—"})}):c.jsx("div",{className:"w-5 h-5 rounded-full bg-gray-700 flex-shrink-0"}),c.jsxs("span",{className:`text-sm ${p?"text-gray-200":h?"text-yellow-400":"text-gray-500"}`,children:[d.label,h?" (skipped)":""]})]},d.key)})}),c.jsx("div",{className:"mt-3 pt-3 border-t border-gray-800",children:c.jsxs("p",{className:"text-xs text-gray-500",children:[l,"/",Td.length," steps completed"]})})]}),c.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[c.jsxs("div",{className:"card text-center",children:[c.jsx("p",{className:"stat-v text-purple-400",children:e.marketsIngested||0}),c.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Markets"})]}),c.jsxs("div",{className:"card text-center",children:[c.jsx("p",{className:"stat-v text-blue-400",children:e.riskProfile||"—"}),c.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Risk Profile"})]}),c.jsxs("div",{className:"card text-center",children:[c.jsx("p",{className:"stat-v text-green-400",children:e.keys?"LIVE":"PAPER"}),c.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Mode"})]})]}),c.jsxs("div",{className:"card",children:[c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsxs("div",{children:[c.jsx("h3",{className:"font-semibold text-sm",children:"Trading Mode"}),c.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:i?"Simulated trades, no real funds":"Real trades on Polymarket"})]}),c.jsxs("div",{className:"flex items-center gap-3",children:[c.jsx("span",{className:`text-xs font-medium ${i?"text-yellow-400":"text-gray-500"}`,children:"Paper"}),c.jsx("button",{onClick:()=>a(!i),disabled:!e.keys,className:`w-11 h-6 rounded-full transition-colors relative ${i?"bg-yellow-500/30":"bg-green-500/30"} ${e.keys?"":"opacity-50 cursor-not-allowed"}`,children:c.jsx("div",{className:`w-4 h-4 rounded-full absolute top-1 transition-all ${i?"left-1 bg-yellow-400":"left-6 bg-green-400"}`})}),c.jsx("span",{className:`text-xs font-medium ${i?"text-gray-500":"text-green-400"}`,children:"Live"})]})]}),!i&&c.jsx("div",{className:"mt-3 p-2 bg-red-500/10 border border-red-500/20 rounded-lg",children:c.jsx("p",{className:"text-xs text-red-400",children:"Live mode will use real USDC on Polygon. Make sure your wallet is funded."})})]}),c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsx("button",{onClick:n,className:"text-sm text-gray-500 hover:text-gray-300",children:"Back"}),c.jsx("button",{onClick:f,disabled:o,className:"wizard-btn text-lg px-8",children:o?"Launching...":"Launch Poly"})]})]})}const zl=[{label:"Welcome",icon:"1"},{label:"Connect",icon:"2"},{label:"Test",icon:"3"},{label:"Ingest",icon:"4"},{label:"Weather",icon:"5"},{label:"Predict",icon:"6"},{label:"Risk",icon:"7"},{label:"Go Live",icon:"8"}];function A$(){const e=dl(),[t,r]=k.useState(!1),[n,i]=k.useState(0),[a,o]=k.useState("forward"),[s,l]=k.useState({keys:null,connectionOk:!1,marketsIngested:0,weatherFetched:!1,predictionsRun:!1,riskProfile:null}),u=k.useRef(null);k.useEffect(()=>{Iv().then(x=>{if(!x){e("/login");return}r(!0),tt("/setup").then(y=>{if(y.setup_complete){e("/");return}y.setup_progress&&(i(y.setup_progress.step||0),l(v=>({...v,...y.setup_progress.data})))}).catch(()=>{})})},[]),k.useEffect(()=>{t&&n>0&&ie("/setup",{action:"save_progress",progress:{step:n,data:s}}).catch(()=>{})},[n]);function f(){o("forward"),n<zl.length-1&&i(x=>x+1)}function d(){o("back"),n>0&&i(x=>x-1)}function p(x){x<=n&&(o(x<n?"back":"forward"),i(x))}function h(x){l(y=>({...y,...x}))}async function m(){await ie("/setup",{action:"complete",progress:{step:zl.length-1,data:s}}),e("/")}if(!t)return c.jsx("div",{className:"flex items-center justify-center min-h-screen",children:c.jsx("div",{className:"animate-spin w-8 h-8 border-2 border-blue-500 border-t-transparent rounded-full"})});const g=[b$,w$,j$,S$,O$,_$,P$,k$][n];return c.jsxs("div",{className:"min-h-screen flex flex-col",style:{background:"var(--bg)"},children:[c.jsxs("div",{className:"flex items-center gap-3 px-6 py-4 border-b border-gray-800",children:[c.jsx("div",{className:"w-8 h-8 rounded-lg flex items-center justify-center flex-shrink-0",style:{background:"linear-gradient(135deg,#3b82f6,#8b5cf6)"},children:c.jsx("span",{className:"text-white font-bold text-sm",children:"P"})}),c.jsx("span",{className:"font-bold text-sm wizard-gradient",children:"POLY SETUP"})]}),c.jsx("div",{className:"px-6 py-5",children:c.jsx("div",{className:"max-w-3xl mx-auto flex items-center",children:zl.map((x,y)=>c.jsxs(A.Fragment,{children:[c.jsxs("button",{onClick:()=>p(y),disabled:y>n,className:"flex flex-col items-center gap-1.5 group",style:{minWidth:56},children:[c.jsx("div",{className:`w-8 h-8 rounded-full flex items-center justify-center text-xs font-bold transition-all ${y<n?"bg-green-500 text-white":y===n?"bg-blue-500 text-white step-active-pulse":"bg-gray-800 text-gray-500"} ${y<=n?"cursor-pointer":"cursor-default"}`,children:y<n?c.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",strokeWidth:"2.5",viewBox:"0 0 24 24",children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5 13l4 4L19 7"})}):x.icon}),c.jsx("span",{className:`text-[10px] font-medium ${y<n?"text-green-400":y===n?"text-blue-400":"text-gray-600"}`,children:x.label})]}),y<zl.length-1&&c.jsx("div",{className:`stepper-line ${y<n?"done":""}`})]},y))})}),c.jsx("div",{className:"flex-1 flex items-start justify-center px-6 pb-10",children:c.jsx("div",{className:"w-full max-w-2xl",ref:u,children:c.jsx("div",{className:"step-enter step-active",children:c.jsx(g,{data:s,update:h,next:f,back:d,complete:m,step:n})},n)})})]})}function LS(e){var t,r,n="";if(typeof e=="string"||typeof e=="number")n+=e;else if(typeof e=="object")if(Array.isArray(e)){var i=e.length;for(t=0;t<i;t++)e[t]&&(r=LS(e[t]))&&(n&&(n+=" "),n+=r)}else for(r in e)e[r]&&(n&&(n+=" "),n+=r);return n}function ee(){for(var e,t,r=0,n="",i=arguments.length;r<i;r++)(e=arguments[r])&&(t=LS(e))&&(n&&(n+=" "),n+=t);return n}var N$=Array.isArray,Ct=N$,$$=typeof Sl=="object"&&Sl&&Sl.Object===Object&&Sl,DS=$$,E$=DS,T$=typeof self=="object"&&self&&self.Object===Object&&self,C$=E$||T$||Function("return this")(),Ir=C$,M$=Ir,I$=M$.Symbol,pl=I$,l0=pl,RS=Object.prototype,L$=RS.hasOwnProperty,D$=RS.toString,Po=l0?l0.toStringTag:void 0;function R$(e){var t=L$.call(e,Po),r=e[Po];try{e[Po]=void 0;var n=!0}catch{}var i=D$.call(e);return n&&(t?e[Po]=r:delete e[Po]),i}var B$=R$,F$=Object.prototype,z$=F$.toString;function W$(e){return z$.call(e)}var U$=W$,u0=pl,K$=B$,H$=U$,V$="[object Null]",G$="[object Undefined]",c0=u0?u0.toStringTag:void 0;function Y$(e){return e==null?e===void 0?G$:V$:c0&&c0 in Object(e)?K$(e):H$(e)}var an=Y$;function q$(e){return e!=null&&typeof e=="object"}var on=q$,X$=an,Q$=on,Z$="[object Symbol]";function J$(e){return typeof e=="symbol"||Q$(e)&&X$(e)==Z$}var no=J$,eE=Ct,tE=no,rE=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,nE=/^\w*$/;function iE(e,t){if(eE(e))return!1;var r=typeof e;return r=="number"||r=="symbol"||r=="boolean"||e==null||tE(e)?!0:nE.test(e)||!rE.test(e)||t!=null&&e in Object(t)}var Lv=iE;function aE(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}var Vn=aE;const io=de(Vn);var oE=an,sE=Vn,lE="[object AsyncFunction]",uE="[object Function]",cE="[object GeneratorFunction]",fE="[object Proxy]";function dE(e){if(!sE(e))return!1;var t=oE(e);return t==uE||t==cE||t==lE||t==fE}var Dv=dE;const Z=de(Dv);var pE=Ir,hE=pE["__core-js_shared__"],mE=hE,Cd=mE,f0=function(){var e=/[^.]+$/.exec(Cd&&Cd.keys&&Cd.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}();function vE(e){return!!f0&&f0 in e}var yE=vE,gE=Function.prototype,xE=gE.toString;function bE(e){if(e!=null){try{return xE.call(e)}catch{}try{return e+""}catch{}}return""}var BS=bE,wE=Dv,jE=yE,SE=Vn,OE=BS,_E=/[\\^$.*+?()[\]{}|]/g,PE=/^\[object .+?Constructor\]$/,kE=Function.prototype,AE=Object.prototype,NE=kE.toString,$E=AE.hasOwnProperty,EE=RegExp("^"+NE.call($E).replace(_E,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function TE(e){if(!SE(e)||jE(e))return!1;var t=wE(e)?EE:PE;return t.test(OE(e))}var CE=TE;function ME(e,t){return e==null?void 0:e[t]}var IE=ME,LE=CE,DE=IE;function RE(e,t){var r=DE(e,t);return LE(r)?r:void 0}var Mi=RE,BE=Mi,FE=BE(Object,"create"),df=FE,d0=df;function zE(){this.__data__=d0?d0(null):{},this.size=0}var WE=zE;function UE(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}var KE=UE,HE=df,VE="__lodash_hash_undefined__",GE=Object.prototype,YE=GE.hasOwnProperty;function qE(e){var t=this.__data__;if(HE){var r=t[e];return r===VE?void 0:r}return YE.call(t,e)?t[e]:void 0}var XE=qE,QE=df,ZE=Object.prototype,JE=ZE.hasOwnProperty;function eT(e){var t=this.__data__;return QE?t[e]!==void 0:JE.call(t,e)}var tT=eT,rT=df,nT="__lodash_hash_undefined__";function iT(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=rT&&t===void 0?nT:t,this}var aT=iT,oT=WE,sT=KE,lT=XE,uT=tT,cT=aT;function ao(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}ao.prototype.clear=oT;ao.prototype.delete=sT;ao.prototype.get=lT;ao.prototype.has=uT;ao.prototype.set=cT;var fT=ao;function dT(){this.__data__=[],this.size=0}var pT=dT;function hT(e,t){return e===t||e!==e&&t!==t}var Rv=hT,mT=Rv;function vT(e,t){for(var r=e.length;r--;)if(mT(e[r][0],t))return r;return-1}var pf=vT,yT=pf,gT=Array.prototype,xT=gT.splice;function bT(e){var t=this.__data__,r=yT(t,e);if(r<0)return!1;var n=t.length-1;return r==n?t.pop():xT.call(t,r,1),--this.size,!0}var wT=bT,jT=pf;function ST(e){var t=this.__data__,r=jT(t,e);return r<0?void 0:t[r][1]}var OT=ST,_T=pf;function PT(e){return _T(this.__data__,e)>-1}var kT=PT,AT=pf;function NT(e,t){var r=this.__data__,n=AT(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this}var $T=NT,ET=pT,TT=wT,CT=OT,MT=kT,IT=$T;function oo(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}oo.prototype.clear=ET;oo.prototype.delete=TT;oo.prototype.get=CT;oo.prototype.has=MT;oo.prototype.set=IT;var hf=oo,LT=Mi,DT=Ir,RT=LT(DT,"Map"),Bv=RT,p0=fT,BT=hf,FT=Bv;function zT(){this.size=0,this.__data__={hash:new p0,map:new(FT||BT),string:new p0}}var WT=zT;function UT(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}var KT=UT,HT=KT;function VT(e,t){var r=e.__data__;return HT(t)?r[typeof t=="string"?"string":"hash"]:r.map}var mf=VT,GT=mf;function YT(e){var t=GT(this,e).delete(e);return this.size-=t?1:0,t}var qT=YT,XT=mf;function QT(e){return XT(this,e).get(e)}var ZT=QT,JT=mf;function eC(e){return JT(this,e).has(e)}var tC=eC,rC=mf;function nC(e,t){var r=rC(this,e),n=r.size;return r.set(e,t),this.size+=r.size==n?0:1,this}var iC=nC,aC=WT,oC=qT,sC=ZT,lC=tC,uC=iC;function so(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}so.prototype.clear=aC;so.prototype.delete=oC;so.prototype.get=sC;so.prototype.has=lC;so.prototype.set=uC;var Fv=so,FS=Fv,cC="Expected a function";function zv(e,t){if(typeof e!="function"||t!=null&&typeof t!="function")throw new TypeError(cC);var r=function(){var n=arguments,i=t?t.apply(this,n):n[0],a=r.cache;if(a.has(i))return a.get(i);var o=e.apply(this,n);return r.cache=a.set(i,o)||a,o};return r.cache=new(zv.Cache||FS),r}zv.Cache=FS;var zS=zv;const fC=de(zS);var dC=zS,pC=500;function hC(e){var t=dC(e,function(n){return r.size===pC&&r.clear(),n}),r=t.cache;return t}var mC=hC,vC=mC,yC=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,gC=/\\(\\)?/g,xC=vC(function(e){var t=[];return e.charCodeAt(0)===46&&t.push(""),e.replace(yC,function(r,n,i,a){t.push(i?a.replace(gC,"$1"):n||r)}),t}),bC=xC;function wC(e,t){for(var r=-1,n=e==null?0:e.length,i=Array(n);++r<n;)i[r]=t(e[r],r,e);return i}var Wv=wC,h0=pl,jC=Wv,SC=Ct,OC=no,m0=h0?h0.prototype:void 0,v0=m0?m0.toString:void 0;function WS(e){if(typeof e=="string")return e;if(SC(e))return jC(e,WS)+"";if(OC(e))return v0?v0.call(e):"";var t=e+"";return t=="0"&&1/e==-1/0?"-0":t}var _C=WS,PC=_C;function kC(e){return e==null?"":PC(e)}var US=kC,AC=Ct,NC=Lv,$C=bC,EC=US;function TC(e,t){return AC(e)?e:NC(e,t)?[e]:$C(EC(e))}var KS=TC,CC=no;function MC(e){if(typeof e=="string"||CC(e))return e;var t=e+"";return t=="0"&&1/e==-1/0?"-0":t}var vf=MC,IC=KS,LC=vf;function DC(e,t){t=IC(t,e);for(var r=0,n=t.length;e!=null&&r<n;)e=e[LC(t[r++])];return r&&r==n?e:void 0}var Uv=DC,RC=Uv;function BC(e,t,r){var n=e==null?void 0:RC(e,t);return n===void 0?r:n}var HS=BC;const Wt=de(HS);function FC(e){return e==null}var zC=FC;const Q=de(zC);var WC=an,UC=Ct,KC=on,HC="[object String]";function VC(e){return typeof e=="string"||!UC(e)&&KC(e)&&WC(e)==HC}var GC=VC;const Pi=de(GC);var VS={exports:{}},pe={};/**
- * @license React
- * react-is.production.min.js
- *
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- */var Kv=Symbol.for("react.element"),Hv=Symbol.for("react.portal"),yf=Symbol.for("react.fragment"),gf=Symbol.for("react.strict_mode"),xf=Symbol.for("react.profiler"),bf=Symbol.for("react.provider"),wf=Symbol.for("react.context"),YC=Symbol.for("react.server_context"),jf=Symbol.for("react.forward_ref"),Sf=Symbol.for("react.suspense"),Of=Symbol.for("react.suspense_list"),_f=Symbol.for("react.memo"),Pf=Symbol.for("react.lazy"),qC=Symbol.for("react.offscreen"),GS;GS=Symbol.for("react.module.reference");function sr(e){if(typeof e=="object"&&e!==null){var t=e.$$typeof;switch(t){case Kv:switch(e=e.type,e){case yf:case xf:case gf:case Sf:case Of:return e;default:switch(e=e&&e.$$typeof,e){case YC:case wf:case jf:case Pf:case _f:case bf:return e;default:return t}}case Hv:return t}}}pe.ContextConsumer=wf;pe.ContextProvider=bf;pe.Element=Kv;pe.ForwardRef=jf;pe.Fragment=yf;pe.Lazy=Pf;pe.Memo=_f;pe.Portal=Hv;pe.Profiler=xf;pe.StrictMode=gf;pe.Suspense=Sf;pe.SuspenseList=Of;pe.isAsyncMode=function(){return!1};pe.isConcurrentMode=function(){return!1};pe.isContextConsumer=function(e){return sr(e)===wf};pe.isContextProvider=function(e){return sr(e)===bf};pe.isElement=function(e){return typeof e=="object"&&e!==null&&e.$$typeof===Kv};pe.isForwardRef=function(e){return sr(e)===jf};pe.isFragment=function(e){return sr(e)===yf};pe.isLazy=function(e){return sr(e)===Pf};pe.isMemo=function(e){return sr(e)===_f};pe.isPortal=function(e){return sr(e)===Hv};pe.isProfiler=function(e){return sr(e)===xf};pe.isStrictMode=function(e){return sr(e)===gf};pe.isSuspense=function(e){return sr(e)===Sf};pe.isSuspenseList=function(e){return sr(e)===Of};pe.isValidElementType=function(e){return typeof e=="string"||typeof e=="function"||e===yf||e===xf||e===gf||e===Sf||e===Of||e===qC||typeof e=="object"&&e!==null&&(e.$$typeof===Pf||e.$$typeof===_f||e.$$typeof===bf||e.$$typeof===wf||e.$$typeof===jf||e.$$typeof===GS||e.getModuleId!==void 0)};pe.typeOf=sr;VS.exports=pe;var XC=VS.exports,QC=an,ZC=on,JC="[object Number]";function eM(e){return typeof e=="number"||ZC(e)&&QC(e)==JC}var YS=eM;const tM=de(YS);var rM=YS;function nM(e){return rM(e)&&e!=+e}var iM=nM;const lo=de(iM);var yt=function(t){return t===0?0:t>0?1:-1},fi=function(t){return Pi(t)&&t.indexOf("%")===t.length-1},K=function(t){return tM(t)&&!lo(t)},aM=function(t){return Q(t)},Xe=function(t){return K(t)||Pi(t)},oM=0,Gn=function(t){var r=++oM;return"".concat(t||"").concat(r)},gt=function(t,r){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:0,i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;if(!K(t)&&!Pi(t))return n;var a;if(fi(t)){var o=t.indexOf("%");a=r*parseFloat(t.slice(0,o))/100}else a=+t;return lo(a)&&(a=n),i&&a>r&&(a=r),a},gn=function(t){if(!t)return null;var r=Object.keys(t);return r&&r.length?t[r[0]]:null},sM=function(t){if(!Array.isArray(t))return!1;for(var r=t.length,n={},i=0;i<r;i++)if(!n[t[i]])n[t[i]]=!0;else return!0;return!1},$e=function(t,r){return K(t)&&K(r)?function(n){return t+n*(r-t)}:function(){return r}};function zu(e,t,r){return!e||!e.length?null:e.find(function(n){return n&&(typeof t=="function"?t(n):Wt(n,t))===r})}var lM=function(t){if(!t||!t.length)return null;for(var r=t.length,n=0,i=0,a=0,o=0,s=1/0,l=-1/0,u=0,f=0,d=0;d<r;d++)u=t[d].cx||0,f=t[d].cy||0,n+=u,i+=f,a+=u*f,o+=u*u,s=Math.min(s,u),l=Math.max(l,u);var p=r*o!==n*n?(r*a-n*i)/(r*o-n*n):0;return{xmin:s,xmax:l,a:p,b:(i-p*n)/r}},uM=function(t,r){return K(t)&&K(r)?t-r:Pi(t)&&Pi(r)?t.localeCompare(r):t instanceof Date&&r instanceof Date?t.getTime()-r.getTime():String(t).localeCompare(String(r))};function ha(e,t){for(var r in e)if({}.hasOwnProperty.call(e,r)&&(!{}.hasOwnProperty.call(t,r)||e[r]!==t[r]))return!1;for(var n in t)if({}.hasOwnProperty.call(t,n)&&!{}.hasOwnProperty.call(e,n))return!1;return!0}function sh(e){"@babel/helpers - typeof";return sh=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},sh(e)}var cM=["viewBox","children"],fM=["aria-activedescendant","aria-atomic","aria-autocomplete","aria-busy","aria-checked","aria-colcount","aria-colindex","aria-colspan","aria-controls","aria-current","aria-describedby","aria-details","aria-disabled","aria-errormessage","aria-expanded","aria-flowto","aria-haspopup","aria-hidden","aria-invalid","aria-keyshortcuts","aria-label","aria-labelledby","aria-level","aria-live","aria-modal","aria-multiline","aria-multiselectable","aria-orientation","aria-owns","aria-placeholder","aria-posinset","aria-pressed","aria-readonly","aria-relevant","aria-required","aria-roledescription","aria-rowcount","aria-rowindex","aria-rowspan","aria-selected","aria-setsize","aria-sort","aria-valuemax","aria-valuemin","aria-valuenow","aria-valuetext","className","color","height","id","lang","max","media","method","min","name","style","target","width","role","tabIndex","accentHeight","accumulate","additive","alignmentBaseline","allowReorder","alphabetic","amplitude","arabicForm","ascent","attributeName","attributeType","autoReverse","azimuth","baseFrequency","baselineShift","baseProfile","bbox","begin","bias","by","calcMode","capHeight","clip","clipPath","clipPathUnits","clipRule","colorInterpolation","colorInterpolationFilters","colorProfile","colorRendering","contentScriptType","contentStyleType","cursor","cx","cy","d","decelerate","descent","diffuseConstant","direction","display","divisor","dominantBaseline","dur","dx","dy","edgeMode","elevation","enableBackground","end","exponent","externalResourcesRequired","fill","fillOpacity","fillRule","filter","filterRes","filterUnits","floodColor","floodOpacity","focusable","fontFamily","fontSize","fontSizeAdjust","fontStretch","fontStyle","fontVariant","fontWeight","format","from","fx","fy","g1","g2","glyphName","glyphOrientationHorizontal","glyphOrientationVertical","glyphRef","gradientTransform","gradientUnits","hanging","horizAdvX","horizOriginX","href","ideographic","imageRendering","in2","in","intercept","k1","k2","k3","k4","k","kernelMatrix","kernelUnitLength","kerning","keyPoints","keySplines","keyTimes","lengthAdjust","letterSpacing","lightingColor","limitingConeAngle","local","markerEnd","markerHeight","markerMid","markerStart","markerUnits","markerWidth","mask","maskContentUnits","maskUnits","mathematical","mode","numOctaves","offset","opacity","operator","order","orient","orientation","origin","overflow","overlinePosition","overlineThickness","paintOrder","panose1","pathLength","patternContentUnits","patternTransform","patternUnits","pointerEvents","pointsAtX","pointsAtY","pointsAtZ","preserveAlpha","preserveAspectRatio","primitiveUnits","r","radius","refX","refY","renderingIntent","repeatCount","repeatDur","requiredExtensions","requiredFeatures","restart","result","rotate","rx","ry","seed","shapeRendering","slope","spacing","specularConstant","specularExponent","speed","spreadMethod","startOffset","stdDeviation","stemh","stemv","stitchTiles","stopColor","stopOpacity","strikethroughPosition","strikethroughThickness","string","stroke","strokeDasharray","strokeDashoffset","strokeLinecap","strokeLinejoin","strokeMiterlimit","strokeOpacity","strokeWidth","surfaceScale","systemLanguage","tableValues","targetX","targetY","textAnchor","textDecoration","textLength","textRendering","to","transform","u1","u2","underlinePosition","underlineThickness","unicode","unicodeBidi","unicodeRange","unitsPerEm","vAlphabetic","values","vectorEffect","version","vertAdvY","vertOriginX","vertOriginY","vHanging","vIdeographic","viewTarget","visibility","vMathematical","widths","wordSpacing","writingMode","x1","x2","x","xChannelSelector","xHeight","xlinkActuate","xlinkArcrole","xlinkHref","xlinkRole","xlinkShow","xlinkTitle","xlinkType","xmlBase","xmlLang","xmlns","xmlnsXlink","xmlSpace","y1","y2","y","yChannelSelector","z","zoomAndPan","ref","key","angle"],y0=["points","pathLength"],Md={svg:cM,polygon:y0,polyline:y0},Vv=["dangerouslySetInnerHTML","onCopy","onCopyCapture","onCut","onCutCapture","onPaste","onPasteCapture","onCompositionEnd","onCompositionEndCapture","onCompositionStart","onCompositionStartCapture","onCompositionUpdate","onCompositionUpdateCapture","onFocus","onFocusCapture","onBlur","onBlurCapture","onChange","onChangeCapture","onBeforeInput","onBeforeInputCapture","onInput","onInputCapture","onReset","onResetCapture","onSubmit","onSubmitCapture","onInvalid","onInvalidCapture","onLoad","onLoadCapture","onError","onErrorCapture","onKeyDown","onKeyDownCapture","onKeyPress","onKeyPressCapture","onKeyUp","onKeyUpCapture","onAbort","onAbortCapture","onCanPlay","onCanPlayCapture","onCanPlayThrough","onCanPlayThroughCapture","onDurationChange","onDurationChangeCapture","onEmptied","onEmptiedCapture","onEncrypted","onEncryptedCapture","onEnded","onEndedCapture","onLoadedData","onLoadedDataCapture","onLoadedMetadata","onLoadedMetadataCapture","onLoadStart","onLoadStartCapture","onPause","onPauseCapture","onPlay","onPlayCapture","onPlaying","onPlayingCapture","onProgress","onProgressCapture","onRateChange","onRateChangeCapture","onSeeked","onSeekedCapture","onSeeking","onSeekingCapture","onStalled","onStalledCapture","onSuspend","onSuspendCapture","onTimeUpdate","onTimeUpdateCapture","onVolumeChange","onVolumeChangeCapture","onWaiting","onWaitingCapture","onAuxClick","onAuxClickCapture","onClick","onClickCapture","onContextMenu","onContextMenuCapture","onDoubleClick","onDoubleClickCapture","onDrag","onDragCapture","onDragEnd","onDragEndCapture","onDragEnter","onDragEnterCapture","onDragExit","onDragExitCapture","onDragLeave","onDragLeaveCapture","onDragOver","onDragOverCapture","onDragStart","onDragStartCapture","onDrop","onDropCapture","onMouseDown","onMouseDownCapture","onMouseEnter","onMouseLeave","onMouseMove","onMouseMoveCapture","onMouseOut","onMouseOutCapture","onMouseOver","onMouseOverCapture","onMouseUp","onMouseUpCapture","onSelect","onSelectCapture","onTouchCancel","onTouchCancelCapture","onTouchEnd","onTouchEndCapture","onTouchMove","onTouchMoveCapture","onTouchStart","onTouchStartCapture","onPointerDown","onPointerDownCapture","onPointerMove","onPointerMoveCapture","onPointerUp","onPointerUpCapture","onPointerCancel","onPointerCancelCapture","onPointerEnter","onPointerEnterCapture","onPointerLeave","onPointerLeaveCapture","onPointerOver","onPointerOverCapture","onPointerOut","onPointerOutCapture","onGotPointerCapture","onGotPointerCaptureCapture","onLostPointerCapture","onLostPointerCaptureCapture","onScroll","onScrollCapture","onWheel","onWheelCapture","onAnimationStart","onAnimationStartCapture","onAnimationEnd","onAnimationEndCapture","onAnimationIteration","onAnimationIterationCapture","onTransitionEnd","onTransitionEndCapture"],Wu=function(t,r){if(!t||typeof t=="function"||typeof t=="boolean")return null;var n=t;if(k.isValidElement(t)&&(n=t.props),!io(n))return null;var i={};return Object.keys(n).forEach(function(a){Vv.includes(a)&&(i[a]=r||function(o){return n[a](n,o)})}),i},dM=function(t,r,n){return function(i){return t(r,n,i),null}},Bn=function(t,r,n){if(!io(t)||sh(t)!=="object")return null;var i=null;return Object.keys(t).forEach(function(a){var o=t[a];Vv.includes(a)&&typeof o=="function"&&(i||(i={}),i[a]=dM(o,r,n))}),i},pM=["children"],hM=["children"];function g0(e,t){if(e==null)return{};var r=mM(e,t),n,i;if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i<a.length;i++)n=a[i],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function mM(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function lh(e){"@babel/helpers - typeof";return lh=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},lh(e)}var x0={click:"onClick",mousedown:"onMouseDown",mouseup:"onMouseUp",mouseover:"onMouseOver",mousemove:"onMouseMove",mouseout:"onMouseOut",mouseenter:"onMouseEnter",mouseleave:"onMouseLeave",touchcancel:"onTouchCancel",touchend:"onTouchEnd",touchmove:"onTouchMove",touchstart:"onTouchStart",contextmenu:"onContextMenu",dblclick:"onDoubleClick"},Gr=function(t){return typeof t=="string"?t:t?t.displayName||t.name||"Component":""},b0=null,Id=null,Gv=function e(t){if(t===b0&&Array.isArray(Id))return Id;var r=[];return k.Children.forEach(t,function(n){Q(n)||(XC.isFragment(n)?r=r.concat(e(n.props.children)):r.push(n))}),Id=r,b0=t,r};function wt(e,t){var r=[],n=[];return Array.isArray(t)?n=t.map(function(i){return Gr(i)}):n=[Gr(t)],Gv(e).forEach(function(i){var a=Wt(i,"type.displayName")||Wt(i,"type.name");n.indexOf(a)!==-1&&r.push(i)}),r}function Rt(e,t){var r=wt(e,t);return r&&r[0]}var w0=function(t){if(!t||!t.props)return!1;var r=t.props,n=r.width,i=r.height;return!(!K(n)||n<=0||!K(i)||i<=0)},vM=["a","altGlyph","altGlyphDef","altGlyphItem","animate","animateColor","animateMotion","animateTransform","circle","clipPath","color-profile","cursor","defs","desc","ellipse","feBlend","feColormatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence","filter","font","font-face","font-face-format","font-face-name","font-face-url","foreignObject","g","glyph","glyphRef","hkern","image","line","lineGradient","marker","mask","metadata","missing-glyph","mpath","path","pattern","polygon","polyline","radialGradient","rect","script","set","stop","style","svg","switch","symbol","text","textPath","title","tref","tspan","use","view","vkern"],yM=function(t){return t&&t.type&&Pi(t.type)&&vM.indexOf(t.type)>=0},qS=function(t){return t&&lh(t)==="object"&&"clipDot"in t},gM=function(t,r,n,i){var a,o=(a=Md==null?void 0:Md[i])!==null&&a!==void 0?a:[];return r.startsWith("data-")||!Z(t)&&(i&&o.includes(r)||fM.includes(r))||n&&Vv.includes(r)},q=function(t,r,n){if(!t||typeof t=="function"||typeof t=="boolean")return null;var i=t;if(k.isValidElement(t)&&(i=t.props),!io(i))return null;var a={};return Object.keys(i).forEach(function(o){var s;gM((s=i)===null||s===void 0?void 0:s[o],o,r,n)&&(a[o]=i[o])}),a},uh=function e(t,r){if(t===r)return!0;var n=k.Children.count(t);if(n!==k.Children.count(r))return!1;if(n===0)return!0;if(n===1)return j0(Array.isArray(t)?t[0]:t,Array.isArray(r)?r[0]:r);for(var i=0;i<n;i++){var a=t[i],o=r[i];if(Array.isArray(a)||Array.isArray(o)){if(!e(a,o))return!1}else if(!j0(a,o))return!1}return!0},j0=function(t,r){if(Q(t)&&Q(r))return!0;if(!Q(t)&&!Q(r)){var n=t.props||{},i=n.children,a=g0(n,pM),o=r.props||{},s=o.children,l=g0(o,hM);return i&&s?ha(a,l)&&uh(i,s):!i&&!s?ha(a,l):!1}return!1},S0=function(t,r){var n=[],i={};return Gv(t).forEach(function(a,o){if(yM(a))n.push(a);else if(a){var s=Gr(a.type),l=r[s]||{},u=l.handler,f=l.once;if(u&&(!f||!i[s])){var d=u(a,s,o);n.push(d),i[s]=!0}}}),n},xM=function(t){var r=t&&t.type;return r&&x0[r]?x0[r]:null},bM=function(t,r){return Gv(r).indexOf(t)},wM=["children","width","height","viewBox","className","style","title","desc"];function ch(){return ch=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},ch.apply(this,arguments)}function jM(e,t){if(e==null)return{};var r=SM(e,t),n,i;if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i<a.length;i++)n=a[i],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function SM(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function fh(e){var t=e.children,r=e.width,n=e.height,i=e.viewBox,a=e.className,o=e.style,s=e.title,l=e.desc,u=jM(e,wM),f=i||{width:r,height:n,x:0,y:0},d=ee("recharts-surface",a);return A.createElement("svg",ch({},q(u,!0,"svg"),{className:d,width:r,height:n,style:o,viewBox:"".concat(f.x," ").concat(f.y," ").concat(f.width," ").concat(f.height)}),A.createElement("title",null,s),A.createElement("desc",null,l),t)}var OM=["children","className"];function dh(){return dh=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},dh.apply(this,arguments)}function _M(e,t){if(e==null)return{};var r=PM(e,t),n,i;if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i<a.length;i++)n=a[i],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function PM(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}var te=A.forwardRef(function(e,t){var r=e.children,n=e.className,i=_M(e,OM),a=ee("recharts-layer",n);return A.createElement("g",dh({className:a},q(i,!0),{ref:t}),r)}),xr=function(t,r){for(var n=arguments.length,i=new Array(n>2?n-2:0),a=2;a<n;a++)i[a-2]=arguments[a]};function kM(e,t,r){var n=-1,i=e.length;t<0&&(t=-t>i?0:i+t),r=r>i?i:r,r<0&&(r+=i),i=t>r?0:r-t>>>0,t>>>=0;for(var a=Array(i);++n<i;)a[n]=e[n+t];return a}var AM=kM,NM=AM;function $M(e,t,r){var n=e.length;return r=r===void 0?n:r,!t&&r>=n?e:NM(e,t,r)}var EM=$M,TM="\\ud800-\\udfff",CM="\\u0300-\\u036f",MM="\\ufe20-\\ufe2f",IM="\\u20d0-\\u20ff",LM=CM+MM+IM,DM="\\ufe0e\\ufe0f",RM="\\u200d",BM=RegExp("["+RM+TM+LM+DM+"]");function FM(e){return BM.test(e)}var XS=FM;function zM(e){return e.split("")}var WM=zM,QS="\\ud800-\\udfff",UM="\\u0300-\\u036f",KM="\\ufe20-\\ufe2f",HM="\\u20d0-\\u20ff",VM=UM+KM+HM,GM="\\ufe0e\\ufe0f",YM="["+QS+"]",ph="["+VM+"]",hh="\\ud83c[\\udffb-\\udfff]",qM="(?:"+ph+"|"+hh+")",ZS="[^"+QS+"]",JS="(?:\\ud83c[\\udde6-\\uddff]){2}",eO="[\\ud800-\\udbff][\\udc00-\\udfff]",XM="\\u200d",tO=qM+"?",rO="["+GM+"]?",QM="(?:"+XM+"(?:"+[ZS,JS,eO].join("|")+")"+rO+tO+")*",ZM=rO+tO+QM,JM="(?:"+[ZS+ph+"?",ph,JS,eO,YM].join("|")+")",e3=RegExp(hh+"(?="+hh+")|"+JM+ZM,"g");function t3(e){return e.match(e3)||[]}var r3=t3,n3=WM,i3=XS,a3=r3;function o3(e){return i3(e)?a3(e):n3(e)}var s3=o3,l3=EM,u3=XS,c3=s3,f3=US;function d3(e){return function(t){t=f3(t);var r=u3(t)?c3(t):void 0,n=r?r[0]:t.charAt(0),i=r?l3(r,1).join(""):t.slice(1);return n[e]()+i}}var p3=d3,h3=p3,m3=h3("toUpperCase"),v3=m3;const kf=de(v3);function ye(e){return function(){return e}}const nO=Math.cos,Uu=Math.sin,Or=Math.sqrt,Ku=Math.PI,Af=2*Ku,mh=Math.PI,vh=2*mh,ii=1e-6,y3=vh-ii;function iO(e){this._+=e[0];for(let t=1,r=e.length;t<r;++t)this._+=arguments[t]+e[t]}function g3(e){let t=Math.floor(e);if(!(t>=0))throw new Error(`invalid digits: ${e}`);if(t>15)return iO;const r=10**t;return function(n){this._+=n[0];for(let i=1,a=n.length;i<a;++i)this._+=Math.round(arguments[i]*r)/r+n[i]}}class x3{constructor(t){this._x0=this._y0=this._x1=this._y1=null,this._="",this._append=t==null?iO:g3(t)}moveTo(t,r){this._append`M${this._x0=this._x1=+t},${this._y0=this._y1=+r}`}closePath(){this._x1!==null&&(this._x1=this._x0,this._y1=this._y0,this._append`Z`)}lineTo(t,r){this._append`L${this._x1=+t},${this._y1=+r}`}quadraticCurveTo(t,r,n,i){this._append`Q${+t},${+r},${this._x1=+n},${this._y1=+i}`}bezierCurveTo(t,r,n,i,a,o){this._append`C${+t},${+r},${+n},${+i},${this._x1=+a},${this._y1=+o}`}arcTo(t,r,n,i,a){if(t=+t,r=+r,n=+n,i=+i,a=+a,a<0)throw new Error(`negative radius: ${a}`);let o=this._x1,s=this._y1,l=n-t,u=i-r,f=o-t,d=s-r,p=f*f+d*d;if(this._x1===null)this._append`M${this._x1=t},${this._y1=r}`;else if(p>ii)if(!(Math.abs(d*l-u*f)>ii)||!a)this._append`L${this._x1=t},${this._y1=r}`;else{let h=n-o,m=i-s,g=l*l+u*u,x=h*h+m*m,y=Math.sqrt(g),v=Math.sqrt(p),b=a*Math.tan((mh-Math.acos((g+p-x)/(2*y*v)))/2),S=b/v,w=b/y;Math.abs(S-1)>ii&&this._append`L${t+S*f},${r+S*d}`,this._append`A${a},${a},0,0,${+(d*h>f*m)},${this._x1=t+w*l},${this._y1=r+w*u}`}}arc(t,r,n,i,a,o){if(t=+t,r=+r,n=+n,o=!!o,n<0)throw new Error(`negative radius: ${n}`);let s=n*Math.cos(i),l=n*Math.sin(i),u=t+s,f=r+l,d=1^o,p=o?i-a:a-i;this._x1===null?this._append`M${u},${f}`:(Math.abs(this._x1-u)>ii||Math.abs(this._y1-f)>ii)&&this._append`L${u},${f}`,n&&(p<0&&(p=p%vh+vh),p>y3?this._append`A${n},${n},0,1,${d},${t-s},${r-l}A${n},${n},0,1,${d},${this._x1=u},${this._y1=f}`:p>ii&&this._append`A${n},${n},0,${+(p>=mh)},${d},${this._x1=t+n*Math.cos(a)},${this._y1=r+n*Math.sin(a)}`)}rect(t,r,n,i){this._append`M${this._x0=this._x1=+t},${this._y0=this._y1=+r}h${n=+n}v${+i}h${-n}Z`}toString(){return this._}}function Yv(e){let t=3;return e.digits=function(r){if(!arguments.length)return t;if(r==null)t=null;else{const n=Math.floor(r);if(!(n>=0))throw new RangeError(`invalid digits: ${r}`);t=n}return e},()=>new x3(t)}function qv(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}function aO(e){this._context=e}aO.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;default:this._context.lineTo(e,t);break}}};function Nf(e){return new aO(e)}function oO(e){return e[0]}function sO(e){return e[1]}function lO(e,t){var r=ye(!0),n=null,i=Nf,a=null,o=Yv(s);e=typeof e=="function"?e:e===void 0?oO:ye(e),t=typeof t=="function"?t:t===void 0?sO:ye(t);function s(l){var u,f=(l=qv(l)).length,d,p=!1,h;for(n==null&&(a=i(h=o())),u=0;u<=f;++u)!(u<f&&r(d=l[u],u,l))===p&&((p=!p)?a.lineStart():a.lineEnd()),p&&a.point(+e(d,u,l),+t(d,u,l));if(h)return a=null,h+""||null}return s.x=function(l){return arguments.length?(e=typeof l=="function"?l:ye(+l),s):e},s.y=function(l){return arguments.length?(t=typeof l=="function"?l:ye(+l),s):t},s.defined=function(l){return arguments.length?(r=typeof l=="function"?l:ye(!!l),s):r},s.curve=function(l){return arguments.length?(i=l,n!=null&&(a=i(n)),s):i},s.context=function(l){return arguments.length?(l==null?n=a=null:a=i(n=l),s):n},s}function Wl(e,t,r){var n=null,i=ye(!0),a=null,o=Nf,s=null,l=Yv(u);e=typeof e=="function"?e:e===void 0?oO:ye(+e),t=typeof t=="function"?t:ye(t===void 0?0:+t),r=typeof r=="function"?r:r===void 0?sO:ye(+r);function u(d){var p,h,m,g=(d=qv(d)).length,x,y=!1,v,b=new Array(g),S=new Array(g);for(a==null&&(s=o(v=l())),p=0;p<=g;++p){if(!(p<g&&i(x=d[p],p,d))===y)if(y=!y)h=p,s.areaStart(),s.lineStart();else{for(s.lineEnd(),s.lineStart(),m=p-1;m>=h;--m)s.point(b[m],S[m]);s.lineEnd(),s.areaEnd()}y&&(b[p]=+e(x,p,d),S[p]=+t(x,p,d),s.point(n?+n(x,p,d):b[p],r?+r(x,p,d):S[p]))}if(v)return s=null,v+""||null}function f(){return lO().defined(i).curve(o).context(a)}return u.x=function(d){return arguments.length?(e=typeof d=="function"?d:ye(+d),n=null,u):e},u.x0=function(d){return arguments.length?(e=typeof d=="function"?d:ye(+d),u):e},u.x1=function(d){return arguments.length?(n=d==null?null:typeof d=="function"?d:ye(+d),u):n},u.y=function(d){return arguments.length?(t=typeof d=="function"?d:ye(+d),r=null,u):t},u.y0=function(d){return arguments.length?(t=typeof d=="function"?d:ye(+d),u):t},u.y1=function(d){return arguments.length?(r=d==null?null:typeof d=="function"?d:ye(+d),u):r},u.lineX0=u.lineY0=function(){return f().x(e).y(t)},u.lineY1=function(){return f().x(e).y(r)},u.lineX1=function(){return f().x(n).y(t)},u.defined=function(d){return arguments.length?(i=typeof d=="function"?d:ye(!!d),u):i},u.curve=function(d){return arguments.length?(o=d,a!=null&&(s=o(a)),u):o},u.context=function(d){return arguments.length?(d==null?a=s=null:s=o(a=d),u):a},u}class uO{constructor(t,r){this._context=t,this._x=r}areaStart(){this._line=0}areaEnd(){this._line=NaN}lineStart(){this._point=0}lineEnd(){(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line}point(t,r){switch(t=+t,r=+r,this._point){case 0:{this._point=1,this._line?this._context.lineTo(t,r):this._context.moveTo(t,r);break}case 1:this._point=2;default:{this._x?this._context.bezierCurveTo(this._x0=(this._x0+t)/2,this._y0,this._x0,r,t,r):this._context.bezierCurveTo(this._x0,this._y0=(this._y0+r)/2,t,this._y0,t,r);break}}this._x0=t,this._y0=r}}function b3(e){return new uO(e,!0)}function w3(e){return new uO(e,!1)}const Xv={draw(e,t){const r=Or(t/Ku);e.moveTo(r,0),e.arc(0,0,r,0,Af)}},j3={draw(e,t){const r=Or(t/5)/2;e.moveTo(-3*r,-r),e.lineTo(-r,-r),e.lineTo(-r,-3*r),e.lineTo(r,-3*r),e.lineTo(r,-r),e.lineTo(3*r,-r),e.lineTo(3*r,r),e.lineTo(r,r),e.lineTo(r,3*r),e.lineTo(-r,3*r),e.lineTo(-r,r),e.lineTo(-3*r,r),e.closePath()}},cO=Or(1/3),S3=cO*2,O3={draw(e,t){const r=Or(t/S3),n=r*cO;e.moveTo(0,-r),e.lineTo(n,0),e.lineTo(0,r),e.lineTo(-n,0),e.closePath()}},_3={draw(e,t){const r=Or(t),n=-r/2;e.rect(n,n,r,r)}},P3=.8908130915292852,fO=Uu(Ku/10)/Uu(7*Ku/10),k3=Uu(Af/10)*fO,A3=-nO(Af/10)*fO,N3={draw(e,t){const r=Or(t*P3),n=k3*r,i=A3*r;e.moveTo(0,-r),e.lineTo(n,i);for(let a=1;a<5;++a){const o=Af*a/5,s=nO(o),l=Uu(o);e.lineTo(l*r,-s*r),e.lineTo(s*n-l*i,l*n+s*i)}e.closePath()}},Ld=Or(3),$3={draw(e,t){const r=-Or(t/(Ld*3));e.moveTo(0,r*2),e.lineTo(-Ld*r,-r),e.lineTo(Ld*r,-r),e.closePath()}},Gt=-.5,Yt=Or(3)/2,yh=1/Or(12),E3=(yh/2+1)*3,T3={draw(e,t){const r=Or(t/E3),n=r/2,i=r*yh,a=n,o=r*yh+r,s=-a,l=o;e.moveTo(n,i),e.lineTo(a,o),e.lineTo(s,l),e.lineTo(Gt*n-Yt*i,Yt*n+Gt*i),e.lineTo(Gt*a-Yt*o,Yt*a+Gt*o),e.lineTo(Gt*s-Yt*l,Yt*s+Gt*l),e.lineTo(Gt*n+Yt*i,Gt*i-Yt*n),e.lineTo(Gt*a+Yt*o,Gt*o-Yt*a),e.lineTo(Gt*s+Yt*l,Gt*l-Yt*s),e.closePath()}};function C3(e,t){let r=null,n=Yv(i);e=typeof e=="function"?e:ye(e||Xv),t=typeof t=="function"?t:ye(t===void 0?64:+t);function i(){let a;if(r||(r=a=n()),e.apply(this,arguments).draw(r,+t.apply(this,arguments)),a)return r=null,a+""||null}return i.type=function(a){return arguments.length?(e=typeof a=="function"?a:ye(a),i):e},i.size=function(a){return arguments.length?(t=typeof a=="function"?a:ye(+a),i):t},i.context=function(a){return arguments.length?(r=a??null,i):r},i}function Hu(){}function Vu(e,t,r){e._context.bezierCurveTo((2*e._x0+e._x1)/3,(2*e._y0+e._y1)/3,(e._x0+2*e._x1)/3,(e._y0+2*e._y1)/3,(e._x0+4*e._x1+t)/6,(e._y0+4*e._y1+r)/6)}function dO(e){this._context=e}dO.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){switch(this._point){case 3:Vu(this,this._x1,this._y1);case 2:this._context.lineTo(this._x1,this._y1);break}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;break;case 2:this._point=3,this._context.lineTo((5*this._x0+this._x1)/6,(5*this._y0+this._y1)/6);default:Vu(this,e,t);break}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t}};function M3(e){return new dO(e)}function pO(e){this._context=e}pO.prototype={areaStart:Hu,areaEnd:Hu,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._y0=this._y1=this._y2=this._y3=this._y4=NaN,this._point=0},lineEnd:function(){switch(this._point){case 1:{this._context.moveTo(this._x2,this._y2),this._context.closePath();break}case 2:{this._context.moveTo((this._x2+2*this._x3)/3,(this._y2+2*this._y3)/3),this._context.lineTo((this._x3+2*this._x2)/3,(this._y3+2*this._y2)/3),this._context.closePath();break}case 3:{this.point(this._x2,this._y2),this.point(this._x3,this._y3),this.point(this._x4,this._y4);break}}},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._x2=e,this._y2=t;break;case 1:this._point=2,this._x3=e,this._y3=t;break;case 2:this._point=3,this._x4=e,this._y4=t,this._context.moveTo((this._x0+4*this._x1+e)/6,(this._y0+4*this._y1+t)/6);break;default:Vu(this,e,t);break}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t}};function I3(e){return new pO(e)}function hO(e){this._context=e}hO.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){(this._line||this._line!==0&&this._point===3)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3;var r=(this._x0+4*this._x1+e)/6,n=(this._y0+4*this._y1+t)/6;this._line?this._context.lineTo(r,n):this._context.moveTo(r,n);break;case 3:this._point=4;default:Vu(this,e,t);break}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t}};function L3(e){return new hO(e)}function mO(e){this._context=e}mO.prototype={areaStart:Hu,areaEnd:Hu,lineStart:function(){this._point=0},lineEnd:function(){this._point&&this._context.closePath()},point:function(e,t){e=+e,t=+t,this._point?this._context.lineTo(e,t):(this._point=1,this._context.moveTo(e,t))}};function D3(e){return new mO(e)}function O0(e){return e<0?-1:1}function _0(e,t,r){var n=e._x1-e._x0,i=t-e._x1,a=(e._y1-e._y0)/(n||i<0&&-0),o=(r-e._y1)/(i||n<0&&-0),s=(a*i+o*n)/(n+i);return(O0(a)+O0(o))*Math.min(Math.abs(a),Math.abs(o),.5*Math.abs(s))||0}function P0(e,t){var r=e._x1-e._x0;return r?(3*(e._y1-e._y0)/r-t)/2:t}function Dd(e,t,r){var n=e._x0,i=e._y0,a=e._x1,o=e._y1,s=(a-n)/3;e._context.bezierCurveTo(n+s,i+s*t,a-s,o-s*r,a,o)}function Gu(e){this._context=e}Gu.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=this._t0=NaN,this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x1,this._y1);break;case 3:Dd(this,this._t0,P0(this,this._t0));break}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){var r=NaN;if(e=+e,t=+t,!(e===this._x1&&t===this._y1)){switch(this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;break;case 2:this._point=3,Dd(this,P0(this,r=_0(this,e,t)),r);break;default:Dd(this,this._t0,r=_0(this,e,t));break}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t,this._t0=r}}};function vO(e){this._context=new yO(e)}(vO.prototype=Object.create(Gu.prototype)).point=function(e,t){Gu.prototype.point.call(this,t,e)};function yO(e){this._context=e}yO.prototype={moveTo:function(e,t){this._context.moveTo(t,e)},closePath:function(){this._context.closePath()},lineTo:function(e,t){this._context.lineTo(t,e)},bezierCurveTo:function(e,t,r,n,i,a){this._context.bezierCurveTo(t,e,n,r,a,i)}};function R3(e){return new Gu(e)}function B3(e){return new vO(e)}function gO(e){this._context=e}gO.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x=[],this._y=[]},lineEnd:function(){var e=this._x,t=this._y,r=e.length;if(r)if(this._line?this._context.lineTo(e[0],t[0]):this._context.moveTo(e[0],t[0]),r===2)this._context.lineTo(e[1],t[1]);else for(var n=k0(e),i=k0(t),a=0,o=1;o<r;++a,++o)this._context.bezierCurveTo(n[0][a],i[0][a],n[1][a],i[1][a],e[o],t[o]);(this._line||this._line!==0&&r===1)&&this._context.closePath(),this._line=1-this._line,this._x=this._y=null},point:function(e,t){this._x.push(+e),this._y.push(+t)}};function k0(e){var t,r=e.length-1,n,i=new Array(r),a=new Array(r),o=new Array(r);for(i[0]=0,a[0]=2,o[0]=e[0]+2*e[1],t=1;t<r-1;++t)i[t]=1,a[t]=4,o[t]=4*e[t]+2*e[t+1];for(i[r-1]=2,a[r-1]=7,o[r-1]=8*e[r-1]+e[r],t=1;t<r;++t)n=i[t]/a[t-1],a[t]-=n,o[t]-=n*o[t-1];for(i[r-1]=o[r-1]/a[r-1],t=r-2;t>=0;--t)i[t]=(o[t]-i[t+1])/a[t];for(a[r-1]=(e[r]+i[r-1])/2,t=0;t<r-1;++t)a[t]=2*e[t+1]-i[t+1];return[i,a]}function F3(e){return new gO(e)}function $f(e,t){this._context=e,this._t=t}$f.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x=this._y=NaN,this._point=0},lineEnd:function(){0<this._t&&this._t<1&&this._point===2&&this._context.lineTo(this._x,this._y),(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line>=0&&(this._t=1-this._t,this._line=1-this._line)},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;default:{if(this._t<=0)this._context.lineTo(this._x,t),this._context.lineTo(e,t);else{var r=this._x*(1-this._t)+e*this._t;this._context.lineTo(r,this._y),this._context.lineTo(r,t)}break}}this._x=e,this._y=t}};function z3(e){return new $f(e,.5)}function W3(e){return new $f(e,0)}function U3(e){return new $f(e,1)}function Oa(e,t){if((o=e.length)>1)for(var r=1,n,i,a=e[t[0]],o,s=a.length;r<o;++r)for(i=a,a=e[t[r]],n=0;n<s;++n)a[n][1]+=a[n][0]=isNaN(i[n][1])?i[n][0]:i[n][1]}function gh(e){for(var t=e.length,r=new Array(t);--t>=0;)r[t]=t;return r}function K3(e,t){return e[t]}function H3(e){const t=[];return t.key=e,t}function V3(){var e=ye([]),t=gh,r=Oa,n=K3;function i(a){var o=Array.from(e.apply(this,arguments),H3),s,l=o.length,u=-1,f;for(const d of a)for(s=0,++u;s<l;++s)(o[s][u]=[0,+n(d,o[s].key,u,a)]).data=d;for(s=0,f=qv(t(o));s<l;++s)o[f[s]].index=s;return r(o,f),o}return i.keys=function(a){return arguments.length?(e=typeof a=="function"?a:ye(Array.from(a)),i):e},i.value=function(a){return arguments.length?(n=typeof a=="function"?a:ye(+a),i):n},i.order=function(a){return arguments.length?(t=a==null?gh:typeof a=="function"?a:ye(Array.from(a)),i):t},i.offset=function(a){return arguments.length?(r=a??Oa,i):r},i}function G3(e,t){if((n=e.length)>0){for(var r,n,i=0,a=e[0].length,o;i<a;++i){for(o=r=0;r<n;++r)o+=e[r][i][1]||0;if(o)for(r=0;r<n;++r)e[r][i][1]/=o}Oa(e,t)}}function Y3(e,t){if((i=e.length)>0){for(var r=0,n=e[t[0]],i,a=n.length;r<a;++r){for(var o=0,s=0;o<i;++o)s+=e[o][r][1]||0;n[r][1]+=n[r][0]=-s/2}Oa(e,t)}}function q3(e,t){if(!(!((o=e.length)>0)||!((a=(i=e[t[0]]).length)>0))){for(var r=0,n=1,i,a,o;n<a;++n){for(var s=0,l=0,u=0;s<o;++s){for(var f=e[t[s]],d=f[n][1]||0,p=f[n-1][1]||0,h=(d-p)/2,m=0;m<s;++m){var g=e[t[m]],x=g[n][1]||0,y=g[n-1][1]||0;h+=x-y}l+=d,u+=h*d}i[n-1][1]+=i[n-1][0]=r,l&&(r-=u/l)}i[n-1][1]+=i[n-1][0]=r,Oa(e,t)}}function Os(e){"@babel/helpers - typeof";return Os=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Os(e)}var X3=["type","size","sizeType"];function xh(){return xh=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},xh.apply(this,arguments)}function A0(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function N0(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?A0(Object(r),!0).forEach(function(n){Q3(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):A0(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function Q3(e,t,r){return t=Z3(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function Z3(e){var t=J3(e,"string");return Os(t)=="symbol"?t:t+""}function J3(e,t){if(Os(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(Os(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function eI(e,t){if(e==null)return{};var r=tI(e,t),n,i;if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i<a.length;i++)n=a[i],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function tI(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}var xO={symbolCircle:Xv,symbolCross:j3,symbolDiamond:O3,symbolSquare:_3,symbolStar:N3,symbolTriangle:$3,symbolWye:T3},rI=Math.PI/180,nI=function(t){var r="symbol".concat(kf(t));return xO[r]||Xv},iI=function(t,r,n){if(r==="area")return t;switch(n){case"cross":return 5*t*t/9;case"diamond":return .5*t*t/Math.sqrt(3);case"square":return t*t;case"star":{var i=18*rI;return 1.25*t*t*(Math.tan(i)-Math.tan(i*2)*Math.pow(Math.tan(i),2))}case"triangle":return Math.sqrt(3)*t*t/4;case"wye":return(21-10*Math.sqrt(3))*t*t/8;default:return Math.PI*t*t/4}},aI=function(t,r){xO["symbol".concat(kf(t))]=r},Ef=function(t){var r=t.type,n=r===void 0?"circle":r,i=t.size,a=i===void 0?64:i,o=t.sizeType,s=o===void 0?"area":o,l=eI(t,X3),u=N0(N0({},l),{},{type:n,size:a,sizeType:s}),f=function(){var x=nI(n),y=C3().type(x).size(iI(a,s,n));return y()},d=u.className,p=u.cx,h=u.cy,m=q(u,!0);return p===+p&&h===+h&&a===+a?A.createElement("path",xh({},m,{className:ee("recharts-symbols",d),transform:"translate(".concat(p,", ").concat(h,")"),d:f()})):null};Ef.registerSymbol=aI;function _a(e){"@babel/helpers - typeof";return _a=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},_a(e)}function bh(){return bh=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},bh.apply(this,arguments)}function $0(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function oI(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?$0(Object(r),!0).forEach(function(n){_s(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):$0(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function sI(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function lI(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,wO(n.key),n)}}function uI(e,t,r){return t&&lI(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function cI(e,t,r){return t=Yu(t),fI(e,bO()?Reflect.construct(t,r||[],Yu(e).constructor):t.apply(e,r))}function fI(e,t){if(t&&(_a(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return dI(e)}function dI(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function bO(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(bO=function(){return!!e})()}function Yu(e){return Yu=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},Yu(e)}function pI(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&wh(e,t)}function wh(e,t){return wh=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,i){return n.__proto__=i,n},wh(e,t)}function _s(e,t,r){return t=wO(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function wO(e){var t=hI(e,"string");return _a(t)=="symbol"?t:t+""}function hI(e,t){if(_a(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(_a(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}var qt=32,Qv=function(e){function t(){return sI(this,t),cI(this,t,arguments)}return pI(t,e),uI(t,[{key:"renderIcon",value:function(n){var i=this.props.inactiveColor,a=qt/2,o=qt/6,s=qt/3,l=n.inactive?i:n.color;if(n.type==="plainline")return A.createElement("line",{strokeWidth:4,fill:"none",stroke:l,strokeDasharray:n.payload.strokeDasharray,x1:0,y1:a,x2:qt,y2:a,className:"recharts-legend-icon"});if(n.type==="line")return A.createElement("path",{strokeWidth:4,fill:"none",stroke:l,d:"M0,".concat(a,"h").concat(s,`
- A`).concat(o,",").concat(o,",0,1,1,").concat(2*s,",").concat(a,`
- H`).concat(qt,"M").concat(2*s,",").concat(a,`
- A`).concat(o,",").concat(o,",0,1,1,").concat(s,",").concat(a),className:"recharts-legend-icon"});if(n.type==="rect")return A.createElement("path",{stroke:"none",fill:l,d:"M0,".concat(qt/8,"h").concat(qt,"v").concat(qt*3/4,"h").concat(-qt,"z"),className:"recharts-legend-icon"});if(A.isValidElement(n.legendIcon)){var u=oI({},n);return delete u.legendIcon,A.cloneElement(n.legendIcon,u)}return A.createElement(Ef,{fill:l,cx:a,cy:a,size:qt,sizeType:"diameter",type:n.type})}},{key:"renderItems",value:function(){var n=this,i=this.props,a=i.payload,o=i.iconSize,s=i.layout,l=i.formatter,u=i.inactiveColor,f={x:0,y:0,width:qt,height:qt},d={display:s==="horizontal"?"inline-block":"block",marginRight:10},p={display:"inline-block",verticalAlign:"middle",marginRight:4};return a.map(function(h,m){var g=h.formatter||l,x=ee(_s(_s({"recharts-legend-item":!0},"legend-item-".concat(m),!0),"inactive",h.inactive));if(h.type==="none")return null;var y=Z(h.value)?null:h.value;xr(!Z(h.value),`The name property is also required when using a function for the dataKey of a chart's cartesian components. Ex: <Bar name="Name of my Data"/>`);var v=h.inactive?u:h.color;return A.createElement("li",bh({className:x,style:d,key:"legend-item-".concat(m)},Bn(n.props,h,m)),A.createElement(fh,{width:o,height:o,viewBox:f,style:p},n.renderIcon(h)),A.createElement("span",{className:"recharts-legend-item-text",style:{color:v}},g?g(y,h,m):y))})}},{key:"render",value:function(){var n=this.props,i=n.payload,a=n.layout,o=n.align;if(!i||!i.length)return null;var s={padding:0,margin:0,textAlign:a==="horizontal"?o:"left"};return A.createElement("ul",{className:"recharts-default-legend",style:s},this.renderItems())}}])}(k.PureComponent);_s(Qv,"displayName","Legend");_s(Qv,"defaultProps",{iconSize:14,layout:"horizontal",align:"center",verticalAlign:"middle",inactiveColor:"#ccc"});var mI=hf;function vI(){this.__data__=new mI,this.size=0}var yI=vI;function gI(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r}var xI=gI;function bI(e){return this.__data__.get(e)}var wI=bI;function jI(e){return this.__data__.has(e)}var SI=jI,OI=hf,_I=Bv,PI=Fv,kI=200;function AI(e,t){var r=this.__data__;if(r instanceof OI){var n=r.__data__;if(!_I||n.length<kI-1)return n.push([e,t]),this.size=++r.size,this;r=this.__data__=new PI(n)}return r.set(e,t),this.size=r.size,this}var NI=AI,$I=hf,EI=yI,TI=xI,CI=wI,MI=SI,II=NI;function uo(e){var t=this.__data__=new $I(e);this.size=t.size}uo.prototype.clear=EI;uo.prototype.delete=TI;uo.prototype.get=CI;uo.prototype.has=MI;uo.prototype.set=II;var jO=uo,LI="__lodash_hash_undefined__";function DI(e){return this.__data__.set(e,LI),this}var RI=DI;function BI(e){return this.__data__.has(e)}var FI=BI,zI=Fv,WI=RI,UI=FI;function qu(e){var t=-1,r=e==null?0:e.length;for(this.__data__=new zI;++t<r;)this.add(e[t])}qu.prototype.add=qu.prototype.push=WI;qu.prototype.has=UI;var SO=qu;function KI(e,t){for(var r=-1,n=e==null?0:e.length;++r<n;)if(t(e[r],r,e))return!0;return!1}var OO=KI;function HI(e,t){return e.has(t)}var _O=HI,VI=SO,GI=OO,YI=_O,qI=1,XI=2;function QI(e,t,r,n,i,a){var o=r&qI,s=e.length,l=t.length;if(s!=l&&!(o&&l>s))return!1;var u=a.get(e),f=a.get(t);if(u&&f)return u==t&&f==e;var d=-1,p=!0,h=r&XI?new VI:void 0;for(a.set(e,t),a.set(t,e);++d<s;){var m=e[d],g=t[d];if(n)var x=o?n(g,m,d,t,e,a):n(m,g,d,e,t,a);if(x!==void 0){if(x)continue;p=!1;break}if(h){if(!GI(t,function(y,v){if(!YI(h,v)&&(m===y||i(m,y,r,n,a)))return h.push(v)})){p=!1;break}}else if(!(m===g||i(m,g,r,n,a))){p=!1;break}}return a.delete(e),a.delete(t),p}var PO=QI,ZI=Ir,JI=ZI.Uint8Array,e4=JI;function t4(e){var t=-1,r=Array(e.size);return e.forEach(function(n,i){r[++t]=[i,n]}),r}var r4=t4;function n4(e){var t=-1,r=Array(e.size);return e.forEach(function(n){r[++t]=n}),r}var Zv=n4,E0=pl,T0=e4,i4=Rv,a4=PO,o4=r4,s4=Zv,l4=1,u4=2,c4="[object Boolean]",f4="[object Date]",d4="[object Error]",p4="[object Map]",h4="[object Number]",m4="[object RegExp]",v4="[object Set]",y4="[object String]",g4="[object Symbol]",x4="[object ArrayBuffer]",b4="[object DataView]",C0=E0?E0.prototype:void 0,Rd=C0?C0.valueOf:void 0;function w4(e,t,r,n,i,a,o){switch(r){case b4:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case x4:return!(e.byteLength!=t.byteLength||!a(new T0(e),new T0(t)));case c4:case f4:case h4:return i4(+e,+t);case d4:return e.name==t.name&&e.message==t.message;case m4:case y4:return e==t+"";case p4:var s=o4;case v4:var l=n&l4;if(s||(s=s4),e.size!=t.size&&!l)return!1;var u=o.get(e);if(u)return u==t;n|=u4,o.set(e,t);var f=a4(s(e),s(t),n,i,a,o);return o.delete(e),f;case g4:if(Rd)return Rd.call(e)==Rd.call(t)}return!1}var j4=w4;function S4(e,t){for(var r=-1,n=t.length,i=e.length;++r<n;)e[i+r]=t[r];return e}var kO=S4,O4=kO,_4=Ct;function P4(e,t,r){var n=t(e);return _4(e)?n:O4(n,r(e))}var k4=P4;function A4(e,t){for(var r=-1,n=e==null?0:e.length,i=0,a=[];++r<n;){var o=e[r];t(o,r,e)&&(a[i++]=o)}return a}var N4=A4;function $4(){return[]}var E4=$4,T4=N4,C4=E4,M4=Object.prototype,I4=M4.propertyIsEnumerable,M0=Object.getOwnPropertySymbols,L4=M0?function(e){return e==null?[]:(e=Object(e),T4(M0(e),function(t){return I4.call(e,t)}))}:C4,D4=L4;function R4(e,t){for(var r=-1,n=Array(e);++r<e;)n[r]=t(r);return n}var B4=R4,F4=an,z4=on,W4="[object Arguments]";function U4(e){return z4(e)&&F4(e)==W4}var K4=U4,I0=K4,H4=on,AO=Object.prototype,V4=AO.hasOwnProperty,G4=AO.propertyIsEnumerable,Y4=I0(function(){return arguments}())?I0:function(e){return H4(e)&&V4.call(e,"callee")&&!G4.call(e,"callee")},Jv=Y4,Xu={exports:{}};function q4(){return!1}var X4=q4;Xu.exports;(function(e,t){var r=Ir,n=X4,i=t&&!t.nodeType&&t,a=i&&!0&&e&&!e.nodeType&&e,o=a&&a.exports===i,s=o?r.Buffer:void 0,l=s?s.isBuffer:void 0,u=l||n;e.exports=u})(Xu,Xu.exports);var NO=Xu.exports,Q4=9007199254740991,Z4=/^(?:0|[1-9]\d*)$/;function J4(e,t){var r=typeof e;return t=t??Q4,!!t&&(r=="number"||r!="symbol"&&Z4.test(e))&&e>-1&&e%1==0&&e<t}var ey=J4,eL=9007199254740991;function tL(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=eL}var ty=tL,rL=an,nL=ty,iL=on,aL="[object Arguments]",oL="[object Array]",sL="[object Boolean]",lL="[object Date]",uL="[object Error]",cL="[object Function]",fL="[object Map]",dL="[object Number]",pL="[object Object]",hL="[object RegExp]",mL="[object Set]",vL="[object String]",yL="[object WeakMap]",gL="[object ArrayBuffer]",xL="[object DataView]",bL="[object Float32Array]",wL="[object Float64Array]",jL="[object Int8Array]",SL="[object Int16Array]",OL="[object Int32Array]",_L="[object Uint8Array]",PL="[object Uint8ClampedArray]",kL="[object Uint16Array]",AL="[object Uint32Array]",we={};we[bL]=we[wL]=we[jL]=we[SL]=we[OL]=we[_L]=we[PL]=we[kL]=we[AL]=!0;we[aL]=we[oL]=we[gL]=we[sL]=we[xL]=we[lL]=we[uL]=we[cL]=we[fL]=we[dL]=we[pL]=we[hL]=we[mL]=we[vL]=we[yL]=!1;function NL(e){return iL(e)&&nL(e.length)&&!!we[rL(e)]}var $L=NL;function EL(e){return function(t){return e(t)}}var $O=EL,Qu={exports:{}};Qu.exports;(function(e,t){var r=DS,n=t&&!t.nodeType&&t,i=n&&!0&&e&&!e.nodeType&&e,a=i&&i.exports===n,o=a&&r.process,s=function(){try{var l=i&&i.require&&i.require("util").types;return l||o&&o.binding&&o.binding("util")}catch{}}();e.exports=s})(Qu,Qu.exports);var TL=Qu.exports,CL=$L,ML=$O,L0=TL,D0=L0&&L0.isTypedArray,IL=D0?ML(D0):CL,EO=IL,LL=B4,DL=Jv,RL=Ct,BL=NO,FL=ey,zL=EO,WL=Object.prototype,UL=WL.hasOwnProperty;function KL(e,t){var r=RL(e),n=!r&&DL(e),i=!r&&!n&&BL(e),a=!r&&!n&&!i&&zL(e),o=r||n||i||a,s=o?LL(e.length,String):[],l=s.length;for(var u in e)(t||UL.call(e,u))&&!(o&&(u=="length"||i&&(u=="offset"||u=="parent")||a&&(u=="buffer"||u=="byteLength"||u=="byteOffset")||FL(u,l)))&&s.push(u);return s}var HL=KL,VL=Object.prototype;function GL(e){var t=e&&e.constructor,r=typeof t=="function"&&t.prototype||VL;return e===r}var YL=GL;function qL(e,t){return function(r){return e(t(r))}}var TO=qL,XL=TO,QL=XL(Object.keys,Object),ZL=QL,JL=YL,e5=ZL,t5=Object.prototype,r5=t5.hasOwnProperty;function n5(e){if(!JL(e))return e5(e);var t=[];for(var r in Object(e))r5.call(e,r)&&r!="constructor"&&t.push(r);return t}var i5=n5,a5=Dv,o5=ty;function s5(e){return e!=null&&o5(e.length)&&!a5(e)}var hl=s5,l5=HL,u5=i5,c5=hl;function f5(e){return c5(e)?l5(e):u5(e)}var Tf=f5,d5=k4,p5=D4,h5=Tf;function m5(e){return d5(e,h5,p5)}var v5=m5,R0=v5,y5=1,g5=Object.prototype,x5=g5.hasOwnProperty;function b5(e,t,r,n,i,a){var o=r&y5,s=R0(e),l=s.length,u=R0(t),f=u.length;if(l!=f&&!o)return!1;for(var d=l;d--;){var p=s[d];if(!(o?p in t:x5.call(t,p)))return!1}var h=a.get(e),m=a.get(t);if(h&&m)return h==t&&m==e;var g=!0;a.set(e,t),a.set(t,e);for(var x=o;++d<l;){p=s[d];var y=e[p],v=t[p];if(n)var b=o?n(v,y,p,t,e,a):n(y,v,p,e,t,a);if(!(b===void 0?y===v||i(y,v,r,n,a):b)){g=!1;break}x||(x=p=="constructor")}if(g&&!x){var S=e.constructor,w=t.constructor;S!=w&&"constructor"in e&&"constructor"in t&&!(typeof S=="function"&&S instanceof S&&typeof w=="function"&&w instanceof w)&&(g=!1)}return a.delete(e),a.delete(t),g}var w5=b5,j5=Mi,S5=Ir,O5=j5(S5,"DataView"),_5=O5,P5=Mi,k5=Ir,A5=P5(k5,"Promise"),N5=A5,$5=Mi,E5=Ir,T5=$5(E5,"Set"),CO=T5,C5=Mi,M5=Ir,I5=C5(M5,"WeakMap"),L5=I5,jh=_5,Sh=Bv,Oh=N5,_h=CO,Ph=L5,MO=an,co=BS,B0="[object Map]",D5="[object Object]",F0="[object Promise]",z0="[object Set]",W0="[object WeakMap]",U0="[object DataView]",R5=co(jh),B5=co(Sh),F5=co(Oh),z5=co(_h),W5=co(Ph),ai=MO;(jh&&ai(new jh(new ArrayBuffer(1)))!=U0||Sh&&ai(new Sh)!=B0||Oh&&ai(Oh.resolve())!=F0||_h&&ai(new _h)!=z0||Ph&&ai(new Ph)!=W0)&&(ai=function(e){var t=MO(e),r=t==D5?e.constructor:void 0,n=r?co(r):"";if(n)switch(n){case R5:return U0;case B5:return B0;case F5:return F0;case z5:return z0;case W5:return W0}return t});var U5=ai,Bd=jO,K5=PO,H5=j4,V5=w5,K0=U5,H0=Ct,V0=NO,G5=EO,Y5=1,G0="[object Arguments]",Y0="[object Array]",Ul="[object Object]",q5=Object.prototype,q0=q5.hasOwnProperty;function X5(e,t,r,n,i,a){var o=H0(e),s=H0(t),l=o?Y0:K0(e),u=s?Y0:K0(t);l=l==G0?Ul:l,u=u==G0?Ul:u;var f=l==Ul,d=u==Ul,p=l==u;if(p&&V0(e)){if(!V0(t))return!1;o=!0,f=!1}if(p&&!f)return a||(a=new Bd),o||G5(e)?K5(e,t,r,n,i,a):H5(e,t,l,r,n,i,a);if(!(r&Y5)){var h=f&&q0.call(e,"__wrapped__"),m=d&&q0.call(t,"__wrapped__");if(h||m){var g=h?e.value():e,x=m?t.value():t;return a||(a=new Bd),i(g,x,r,n,a)}}return p?(a||(a=new Bd),V5(e,t,r,n,i,a)):!1}var Q5=X5,Z5=Q5,X0=on;function IO(e,t,r,n,i){return e===t?!0:e==null||t==null||!X0(e)&&!X0(t)?e!==e&&t!==t:Z5(e,t,r,n,IO,i)}var ry=IO,J5=jO,eD=ry,tD=1,rD=2;function nD(e,t,r,n){var i=r.length,a=i,o=!n;if(e==null)return!a;for(e=Object(e);i--;){var s=r[i];if(o&&s[2]?s[1]!==e[s[0]]:!(s[0]in e))return!1}for(;++i<a;){s=r[i];var l=s[0],u=e[l],f=s[1];if(o&&s[2]){if(u===void 0&&!(l in e))return!1}else{var d=new J5;if(n)var p=n(u,f,l,e,t,d);if(!(p===void 0?eD(f,u,tD|rD,n,d):p))return!1}}return!0}var iD=nD,aD=Vn;function oD(e){return e===e&&!aD(e)}var LO=oD,sD=LO,lD=Tf;function uD(e){for(var t=lD(e),r=t.length;r--;){var n=t[r],i=e[n];t[r]=[n,i,sD(i)]}return t}var cD=uD;function fD(e,t){return function(r){return r==null?!1:r[e]===t&&(t!==void 0||e in Object(r))}}var DO=fD,dD=iD,pD=cD,hD=DO;function mD(e){var t=pD(e);return t.length==1&&t[0][2]?hD(t[0][0],t[0][1]):function(r){return r===e||dD(r,e,t)}}var vD=mD;function yD(e,t){return e!=null&&t in Object(e)}var gD=yD,xD=KS,bD=Jv,wD=Ct,jD=ey,SD=ty,OD=vf;function _D(e,t,r){t=xD(t,e);for(var n=-1,i=t.length,a=!1;++n<i;){var o=OD(t[n]);if(!(a=e!=null&&r(e,o)))break;e=e[o]}return a||++n!=i?a:(i=e==null?0:e.length,!!i&&SD(i)&&jD(o,i)&&(wD(e)||bD(e)))}var PD=_D,kD=gD,AD=PD;function ND(e,t){return e!=null&&AD(e,t,kD)}var $D=ND,ED=ry,TD=HS,CD=$D,MD=Lv,ID=LO,LD=DO,DD=vf,RD=1,BD=2;function FD(e,t){return MD(e)&&ID(t)?LD(DD(e),t):function(r){var n=TD(r,e);return n===void 0&&n===t?CD(r,e):ED(t,n,RD|BD)}}var zD=FD;function WD(e){return e}var fo=WD;function UD(e){return function(t){return t==null?void 0:t[e]}}var KD=UD,HD=Uv;function VD(e){return function(t){return HD(t,e)}}var GD=VD,YD=KD,qD=GD,XD=Lv,QD=vf;function ZD(e){return XD(e)?YD(QD(e)):qD(e)}var JD=ZD,eR=vD,tR=zD,rR=fo,nR=Ct,iR=JD;function aR(e){return typeof e=="function"?e:e==null?rR:typeof e=="object"?nR(e)?tR(e[0],e[1]):eR(e):iR(e)}var Lr=aR;function oR(e,t,r,n){for(var i=e.length,a=r+(n?1:-1);n?a--:++a<i;)if(t(e[a],a,e))return a;return-1}var RO=oR;function sR(e){return e!==e}var lR=sR;function uR(e,t,r){for(var n=r-1,i=e.length;++n<i;)if(e[n]===t)return n;return-1}var cR=uR,fR=RO,dR=lR,pR=cR;function hR(e,t,r){return t===t?pR(e,t,r):fR(e,dR,r)}var mR=hR,vR=mR;function yR(e,t){var r=e==null?0:e.length;return!!r&&vR(e,t,0)>-1}var gR=yR;function xR(e,t,r){for(var n=-1,i=e==null?0:e.length;++n<i;)if(r(t,e[n]))return!0;return!1}var bR=xR;function wR(){}var jR=wR,Fd=CO,SR=jR,OR=Zv,_R=1/0,PR=Fd&&1/OR(new Fd([,-0]))[1]==_R?function(e){return new Fd(e)}:SR,kR=PR,AR=SO,NR=gR,$R=bR,ER=_O,TR=kR,CR=Zv,MR=200;function IR(e,t,r){var n=-1,i=NR,a=e.length,o=!0,s=[],l=s;if(r)o=!1,i=$R;else if(a>=MR){var u=t?null:TR(e);if(u)return CR(u);o=!1,i=ER,l=new AR}else l=t?[]:s;e:for(;++n<a;){var f=e[n],d=t?t(f):f;if(f=r||f!==0?f:0,o&&d===d){for(var p=l.length;p--;)if(l[p]===d)continue e;t&&l.push(d),s.push(f)}else i(l,d,r)||(l!==s&&l.push(d),s.push(f))}return s}var LR=IR,DR=Lr,RR=LR;function BR(e,t){return e&&e.length?RR(e,DR(t)):[]}var FR=BR;const Q0=de(FR);function BO(e,t,r){return t===!0?Q0(e,r):Z(t)?Q0(e,t):e}function Pa(e){"@babel/helpers - typeof";return Pa=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Pa(e)}var zR=["ref"];function Z0(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function Dr(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Z0(Object(r),!0).forEach(function(n){Cf(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Z0(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function WR(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function J0(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,zO(n.key),n)}}function UR(e,t,r){return t&&J0(e.prototype,t),r&&J0(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function KR(e,t,r){return t=Zu(t),HR(e,FO()?Reflect.construct(t,r||[],Zu(e).constructor):t.apply(e,r))}function HR(e,t){if(t&&(Pa(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return VR(e)}function VR(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function FO(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(FO=function(){return!!e})()}function Zu(e){return Zu=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},Zu(e)}function GR(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&kh(e,t)}function kh(e,t){return kh=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,i){return n.__proto__=i,n},kh(e,t)}function Cf(e,t,r){return t=zO(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function zO(e){var t=YR(e,"string");return Pa(t)=="symbol"?t:t+""}function YR(e,t){if(Pa(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(Pa(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}function qR(e,t){if(e==null)return{};var r=XR(e,t),n,i;if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i<a.length;i++)n=a[i],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function XR(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function QR(e){return e.value}function ZR(e,t){if(A.isValidElement(e))return A.cloneElement(e,t);if(typeof e=="function")return A.createElement(e,t);t.ref;var r=qR(t,zR);return A.createElement(Qv,r)}var ex=1,Yr=function(e){function t(){var r;WR(this,t);for(var n=arguments.length,i=new Array(n),a=0;a<n;a++)i[a]=arguments[a];return r=KR(this,t,[].concat(i)),Cf(r,"lastBoundingBox",{width:-1,height:-1}),r}return GR(t,e),UR(t,[{key:"componentDidMount",value:function(){this.updateBBox()}},{key:"componentDidUpdate",value:function(){this.updateBBox()}},{key:"getBBox",value:function(){if(this.wrapperNode&&this.wrapperNode.getBoundingClientRect){var n=this.wrapperNode.getBoundingClientRect();return n.height=this.wrapperNode.offsetHeight,n.width=this.wrapperNode.offsetWidth,n}return null}},{key:"updateBBox",value:function(){var n=this.props.onBBoxUpdate,i=this.getBBox();i?(Math.abs(i.width-this.lastBoundingBox.width)>ex||Math.abs(i.height-this.lastBoundingBox.height)>ex)&&(this.lastBoundingBox.width=i.width,this.lastBoundingBox.height=i.height,n&&n(i)):(this.lastBoundingBox.width!==-1||this.lastBoundingBox.height!==-1)&&(this.lastBoundingBox.width=-1,this.lastBoundingBox.height=-1,n&&n(null))}},{key:"getBBoxSnapshot",value:function(){return this.lastBoundingBox.width>=0&&this.lastBoundingBox.height>=0?Dr({},this.lastBoundingBox):{width:0,height:0}}},{key:"getDefaultPosition",value:function(n){var i=this.props,a=i.layout,o=i.align,s=i.verticalAlign,l=i.margin,u=i.chartWidth,f=i.chartHeight,d,p;if(!n||(n.left===void 0||n.left===null)&&(n.right===void 0||n.right===null))if(o==="center"&&a==="vertical"){var h=this.getBBoxSnapshot();d={left:((u||0)-h.width)/2}}else d=o==="right"?{right:l&&l.right||0}:{left:l&&l.left||0};if(!n||(n.top===void 0||n.top===null)&&(n.bottom===void 0||n.bottom===null))if(s==="middle"){var m=this.getBBoxSnapshot();p={top:((f||0)-m.height)/2}}else p=s==="bottom"?{bottom:l&&l.bottom||0}:{top:l&&l.top||0};return Dr(Dr({},d),p)}},{key:"render",value:function(){var n=this,i=this.props,a=i.content,o=i.width,s=i.height,l=i.wrapperStyle,u=i.payloadUniqBy,f=i.payload,d=Dr(Dr({position:"absolute",width:o||"auto",height:s||"auto"},this.getDefaultPosition(l)),l);return A.createElement("div",{className:"recharts-legend-wrapper",style:d,ref:function(h){n.wrapperNode=h}},ZR(a,Dr(Dr({},this.props),{},{payload:BO(f,u,QR)})))}}],[{key:"getWithHeight",value:function(n,i){var a=Dr(Dr({},this.defaultProps),n.props),o=a.layout;return o==="vertical"&&K(n.props.height)?{height:n.props.height}:o==="horizontal"?{width:n.props.width||i}:null}}])}(k.PureComponent);Cf(Yr,"displayName","Legend");Cf(Yr,"defaultProps",{iconSize:14,layout:"horizontal",align:"center",verticalAlign:"bottom"});var tx=pl,JR=Jv,e8=Ct,rx=tx?tx.isConcatSpreadable:void 0;function t8(e){return e8(e)||JR(e)||!!(rx&&e&&e[rx])}var r8=t8,n8=kO,i8=r8;function WO(e,t,r,n,i){var a=-1,o=e.length;for(r||(r=i8),i||(i=[]);++a<o;){var s=e[a];t>0&&r(s)?t>1?WO(s,t-1,r,n,i):n8(i,s):n||(i[i.length]=s)}return i}var UO=WO;function a8(e){return function(t,r,n){for(var i=-1,a=Object(t),o=n(t),s=o.length;s--;){var l=o[e?s:++i];if(r(a[l],l,a)===!1)break}return t}}var o8=a8,s8=o8,l8=s8(),u8=l8,c8=u8,f8=Tf;function d8(e,t){return e&&c8(e,t,f8)}var KO=d8,p8=hl;function h8(e,t){return function(r,n){if(r==null)return r;if(!p8(r))return e(r,n);for(var i=r.length,a=t?i:-1,o=Object(r);(t?a--:++a<i)&&n(o[a],a,o)!==!1;);return r}}var m8=h8,v8=KO,y8=m8,g8=y8(v8),ny=g8,x8=ny,b8=hl;function w8(e,t){var r=-1,n=b8(e)?Array(e.length):[];return x8(e,function(i,a,o){n[++r]=t(i,a,o)}),n}var HO=w8;function j8(e,t){var r=e.length;for(e.sort(t);r--;)e[r]=e[r].value;return e}var S8=j8,nx=no;function O8(e,t){if(e!==t){var r=e!==void 0,n=e===null,i=e===e,a=nx(e),o=t!==void 0,s=t===null,l=t===t,u=nx(t);if(!s&&!u&&!a&&e>t||a&&o&&l&&!s&&!u||n&&o&&l||!r&&l||!i)return 1;if(!n&&!a&&!u&&e<t||u&&r&&i&&!n&&!a||s&&r&&i||!o&&i||!l)return-1}return 0}var _8=O8,P8=_8;function k8(e,t,r){for(var n=-1,i=e.criteria,a=t.criteria,o=i.length,s=r.length;++n<o;){var l=P8(i[n],a[n]);if(l){if(n>=s)return l;var u=r[n];return l*(u=="desc"?-1:1)}}return e.index-t.index}var A8=k8,zd=Wv,N8=Uv,$8=Lr,E8=HO,T8=S8,C8=$O,M8=A8,I8=fo,L8=Ct;function D8(e,t,r){t.length?t=zd(t,function(a){return L8(a)?function(o){return N8(o,a.length===1?a[0]:a)}:a}):t=[I8];var n=-1;t=zd(t,C8($8));var i=E8(e,function(a,o,s){var l=zd(t,function(u){return u(a)});return{criteria:l,index:++n,value:a}});return T8(i,function(a,o){return M8(a,o,r)})}var R8=D8;function B8(e,t,r){switch(r.length){case 0:return e.call(t);case 1:return e.call(t,r[0]);case 2:return e.call(t,r[0],r[1]);case 3:return e.call(t,r[0],r[1],r[2])}return e.apply(t,r)}var F8=B8,z8=F8,ix=Math.max;function W8(e,t,r){return t=ix(t===void 0?e.length-1:t,0),function(){for(var n=arguments,i=-1,a=ix(n.length-t,0),o=Array(a);++i<a;)o[i]=n[t+i];i=-1;for(var s=Array(t+1);++i<t;)s[i]=n[i];return s[t]=r(o),z8(e,this,s)}}var U8=W8;function K8(e){return function(){return e}}var H8=K8,V8=Mi,G8=function(){try{var e=V8(Object,"defineProperty");return e({},"",{}),e}catch{}}(),VO=G8,Y8=H8,ax=VO,q8=fo,X8=ax?function(e,t){return ax(e,"toString",{configurable:!0,enumerable:!1,value:Y8(t),writable:!0})}:q8,Q8=X8,Z8=800,J8=16,eB=Date.now;function tB(e){var t=0,r=0;return function(){var n=eB(),i=J8-(n-r);if(r=n,i>0){if(++t>=Z8)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}var rB=tB,nB=Q8,iB=rB,aB=iB(nB),oB=aB,sB=fo,lB=U8,uB=oB;function cB(e,t){return uB(lB(e,t,sB),e+"")}var fB=cB,dB=Rv,pB=hl,hB=ey,mB=Vn;function vB(e,t,r){if(!mB(r))return!1;var n=typeof t;return(n=="number"?pB(r)&&hB(t,r.length):n=="string"&&t in r)?dB(r[t],e):!1}var Mf=vB,yB=UO,gB=R8,xB=fB,ox=Mf,bB=xB(function(e,t){if(e==null)return[];var r=t.length;return r>1&&ox(e,t[0],t[1])?t=[]:r>2&&ox(t[0],t[1],t[2])&&(t=[t[0]]),gB(e,yB(t,1),[])}),wB=bB;const iy=de(wB);function Ps(e){"@babel/helpers - typeof";return Ps=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Ps(e)}function Ah(){return Ah=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},Ah.apply(this,arguments)}function jB(e,t){return PB(e)||_B(e,t)||OB(e,t)||SB()}function SB(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
-In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function OB(e,t){if(e){if(typeof e=="string")return sx(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return sx(e,t)}}function sx(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function _B(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,i,a,o,s=[],l=!0,u=!1;try{if(a=(r=r.call(e)).next,t!==0)for(;!(l=(n=a.call(r)).done)&&(s.push(n.value),s.length!==t);l=!0);}catch(f){u=!0,i=f}finally{try{if(!l&&r.return!=null&&(o=r.return(),Object(o)!==o))return}finally{if(u)throw i}}return s}}function PB(e){if(Array.isArray(e))return e}function lx(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function Wd(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?lx(Object(r),!0).forEach(function(n){kB(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):lx(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function kB(e,t,r){return t=AB(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function AB(e){var t=NB(e,"string");return Ps(t)=="symbol"?t:t+""}function NB(e,t){if(Ps(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(Ps(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function $B(e){return Array.isArray(e)&&Xe(e[0])&&Xe(e[1])?e.join(" ~ "):e}var EB=function(t){var r=t.separator,n=r===void 0?" : ":r,i=t.contentStyle,a=i===void 0?{}:i,o=t.itemStyle,s=o===void 0?{}:o,l=t.labelStyle,u=l===void 0?{}:l,f=t.payload,d=t.formatter,p=t.itemSorter,h=t.wrapperClassName,m=t.labelClassName,g=t.label,x=t.labelFormatter,y=t.accessibilityLayer,v=y===void 0?!1:y,b=function(){if(f&&f.length){var $={padding:0,margin:0},I=(p?iy(f,p):f).map(function(D,L){if(D.type==="none")return null;var C=Wd({display:"block",paddingTop:4,paddingBottom:4,color:D.color||"#000"},s),F=D.formatter||d||$B,M=D.value,B=D.name,E=M,W=B;if(F&&E!=null&&W!=null){var z=F(M,B,D,L,f);if(Array.isArray(z)){var X=jB(z,2);E=X[0],W=X[1]}else E=z}return A.createElement("li",{className:"recharts-tooltip-item",key:"tooltip-item-".concat(L),style:C},Xe(W)?A.createElement("span",{className:"recharts-tooltip-item-name"},W):null,Xe(W)?A.createElement("span",{className:"recharts-tooltip-item-separator"},n):null,A.createElement("span",{className:"recharts-tooltip-item-value"},E),A.createElement("span",{className:"recharts-tooltip-item-unit"},D.unit||""))});return A.createElement("ul",{className:"recharts-tooltip-item-list",style:$},I)}return null},S=Wd({margin:0,padding:10,backgroundColor:"#fff",border:"1px solid #ccc",whiteSpace:"nowrap"},a),w=Wd({margin:0},u),j=!Q(g),O=j?g:"",_=ee("recharts-default-tooltip",h),P=ee("recharts-tooltip-label",m);j&&x&&f!==void 0&&f!==null&&(O=x(g,f));var N=v?{role:"status","aria-live":"assertive"}:{};return A.createElement("div",Ah({className:_,style:S},N),A.createElement("p",{className:P,style:w},A.isValidElement(O)?O:"".concat(O)),b())};function ks(e){"@babel/helpers - typeof";return ks=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},ks(e)}function Kl(e,t,r){return t=TB(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function TB(e){var t=CB(e,"string");return ks(t)=="symbol"?t:t+""}function CB(e,t){if(ks(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(ks(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var ko="recharts-tooltip-wrapper",MB={visibility:"hidden"};function IB(e){var t=e.coordinate,r=e.translateX,n=e.translateY;return ee(ko,Kl(Kl(Kl(Kl({},"".concat(ko,"-right"),K(r)&&t&&K(t.x)&&r>=t.x),"".concat(ko,"-left"),K(r)&&t&&K(t.x)&&r<t.x),"".concat(ko,"-bottom"),K(n)&&t&&K(t.y)&&n>=t.y),"".concat(ko,"-top"),K(n)&&t&&K(t.y)&&n<t.y))}function ux(e){var t=e.allowEscapeViewBox,r=e.coordinate,n=e.key,i=e.offsetTopLeft,a=e.position,o=e.reverseDirection,s=e.tooltipDimension,l=e.viewBox,u=e.viewBoxDimension;if(a&&K(a[n]))return a[n];var f=r[n]-s-i,d=r[n]+i;if(t[n])return o[n]?f:d;if(o[n]){var p=f,h=l[n];return p<h?Math.max(d,l[n]):Math.max(f,l[n])}var m=d+s,g=l[n]+u;return m>g?Math.max(f,l[n]):Math.max(d,l[n])}function LB(e){var t=e.translateX,r=e.translateY,n=e.useTranslate3d;return{transform:n?"translate3d(".concat(t,"px, ").concat(r,"px, 0)"):"translate(".concat(t,"px, ").concat(r,"px)")}}function DB(e){var t=e.allowEscapeViewBox,r=e.coordinate,n=e.offsetTopLeft,i=e.position,a=e.reverseDirection,o=e.tooltipBox,s=e.useTranslate3d,l=e.viewBox,u,f,d;return o.height>0&&o.width>0&&r?(f=ux({allowEscapeViewBox:t,coordinate:r,key:"x",offsetTopLeft:n,position:i,reverseDirection:a,tooltipDimension:o.width,viewBox:l,viewBoxDimension:l.width}),d=ux({allowEscapeViewBox:t,coordinate:r,key:"y",offsetTopLeft:n,position:i,reverseDirection:a,tooltipDimension:o.height,viewBox:l,viewBoxDimension:l.height}),u=LB({translateX:f,translateY:d,useTranslate3d:s})):u=MB,{cssProperties:u,cssClasses:IB({translateX:f,translateY:d,coordinate:r})}}function ka(e){"@babel/helpers - typeof";return ka=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},ka(e)}function cx(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function fx(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?cx(Object(r),!0).forEach(function(n){$h(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):cx(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function RB(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function BB(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,YO(n.key),n)}}function FB(e,t,r){return t&&BB(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function zB(e,t,r){return t=Ju(t),WB(e,GO()?Reflect.construct(t,r||[],Ju(e).constructor):t.apply(e,r))}function WB(e,t){if(t&&(ka(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return UB(e)}function UB(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function GO(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(GO=function(){return!!e})()}function Ju(e){return Ju=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},Ju(e)}function KB(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Nh(e,t)}function Nh(e,t){return Nh=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,i){return n.__proto__=i,n},Nh(e,t)}function $h(e,t,r){return t=YO(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function YO(e){var t=HB(e,"string");return ka(t)=="symbol"?t:t+""}function HB(e,t){if(ka(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(ka(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}var dx=1,VB=function(e){function t(){var r;RB(this,t);for(var n=arguments.length,i=new Array(n),a=0;a<n;a++)i[a]=arguments[a];return r=zB(this,t,[].concat(i)),$h(r,"state",{dismissed:!1,dismissedAtCoordinate:{x:0,y:0},lastBoundingBox:{width:-1,height:-1}}),$h(r,"handleKeyDown",function(o){if(o.key==="Escape"){var s,l,u,f;r.setState({dismissed:!0,dismissedAtCoordinate:{x:(s=(l=r.props.coordinate)===null||l===void 0?void 0:l.x)!==null&&s!==void 0?s:0,y:(u=(f=r.props.coordinate)===null||f===void 0?void 0:f.y)!==null&&u!==void 0?u:0}})}}),r}return KB(t,e),FB(t,[{key:"updateBBox",value:function(){if(this.wrapperNode&&this.wrapperNode.getBoundingClientRect){var n=this.wrapperNode.getBoundingClientRect();(Math.abs(n.width-this.state.lastBoundingBox.width)>dx||Math.abs(n.height-this.state.lastBoundingBox.height)>dx)&&this.setState({lastBoundingBox:{width:n.width,height:n.height}})}else(this.state.lastBoundingBox.width!==-1||this.state.lastBoundingBox.height!==-1)&&this.setState({lastBoundingBox:{width:-1,height:-1}})}},{key:"componentDidMount",value:function(){document.addEventListener("keydown",this.handleKeyDown),this.updateBBox()}},{key:"componentWillUnmount",value:function(){document.removeEventListener("keydown",this.handleKeyDown)}},{key:"componentDidUpdate",value:function(){var n,i;this.props.active&&this.updateBBox(),this.state.dismissed&&(((n=this.props.coordinate)===null||n===void 0?void 0:n.x)!==this.state.dismissedAtCoordinate.x||((i=this.props.coordinate)===null||i===void 0?void 0:i.y)!==this.state.dismissedAtCoordinate.y)&&(this.state.dismissed=!1)}},{key:"render",value:function(){var n=this,i=this.props,a=i.active,o=i.allowEscapeViewBox,s=i.animationDuration,l=i.animationEasing,u=i.children,f=i.coordinate,d=i.hasPayload,p=i.isAnimationActive,h=i.offset,m=i.position,g=i.reverseDirection,x=i.useTranslate3d,y=i.viewBox,v=i.wrapperStyle,b=DB({allowEscapeViewBox:o,coordinate:f,offsetTopLeft:h,position:m,reverseDirection:g,tooltipBox:this.state.lastBoundingBox,useTranslate3d:x,viewBox:y}),S=b.cssClasses,w=b.cssProperties,j=fx(fx({transition:p&&a?"transform ".concat(s,"ms ").concat(l):void 0},w),{},{pointerEvents:"none",visibility:!this.state.dismissed&&a&&d?"visible":"hidden",position:"absolute",top:0,left:0},v);return A.createElement("div",{tabIndex:-1,className:S,style:j,ref:function(_){n.wrapperNode=_}},u)}}])}(k.PureComponent),GB=function(){return!(typeof window<"u"&&window.document&&window.document.createElement&&window.setTimeout)},sn={isSsr:GB()};function Aa(e){"@babel/helpers - typeof";return Aa=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Aa(e)}function px(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function hx(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?px(Object(r),!0).forEach(function(n){ay(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):px(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function YB(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function qB(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,XO(n.key),n)}}function XB(e,t,r){return t&&qB(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function QB(e,t,r){return t=ec(t),ZB(e,qO()?Reflect.construct(t,r||[],ec(e).constructor):t.apply(e,r))}function ZB(e,t){if(t&&(Aa(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return JB(e)}function JB(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function qO(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(qO=function(){return!!e})()}function ec(e){return ec=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},ec(e)}function e6(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Eh(e,t)}function Eh(e,t){return Eh=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,i){return n.__proto__=i,n},Eh(e,t)}function ay(e,t,r){return t=XO(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function XO(e){var t=t6(e,"string");return Aa(t)=="symbol"?t:t+""}function t6(e,t){if(Aa(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(Aa(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}function r6(e){return e.dataKey}function n6(e,t){return A.isValidElement(e)?A.cloneElement(e,t):typeof e=="function"?A.createElement(e,t):A.createElement(EB,t)}var Se=function(e){function t(){return YB(this,t),QB(this,t,arguments)}return e6(t,e),XB(t,[{key:"render",value:function(){var n=this,i=this.props,a=i.active,o=i.allowEscapeViewBox,s=i.animationDuration,l=i.animationEasing,u=i.content,f=i.coordinate,d=i.filterNull,p=i.isAnimationActive,h=i.offset,m=i.payload,g=i.payloadUniqBy,x=i.position,y=i.reverseDirection,v=i.useTranslate3d,b=i.viewBox,S=i.wrapperStyle,w=m??[];d&&w.length&&(w=BO(m.filter(function(O){return O.value!=null&&(O.hide!==!0||n.props.includeHidden)}),g,r6));var j=w.length>0;return A.createElement(VB,{allowEscapeViewBox:o,animationDuration:s,animationEasing:l,isAnimationActive:p,active:a,coordinate:f,hasPayload:j,offset:h,position:x,reverseDirection:y,useTranslate3d:v,viewBox:b,wrapperStyle:S},n6(u,hx(hx({},this.props),{},{payload:w})))}}])}(k.PureComponent);ay(Se,"displayName","Tooltip");ay(Se,"defaultProps",{accessibilityLayer:!1,allowEscapeViewBox:{x:!1,y:!1},animationDuration:400,animationEasing:"ease",contentStyle:{},coordinate:{x:0,y:0},cursor:!0,cursorStyle:{},filterNull:!0,isAnimationActive:!sn.isSsr,itemStyle:{},labelStyle:{},offset:10,reverseDirection:{x:!1,y:!1},separator:" : ",trigger:"hover",useTranslate3d:!1,viewBox:{x:0,y:0,height:0,width:0},wrapperStyle:{}});var i6=Ir,a6=function(){return i6.Date.now()},o6=a6,s6=/\s/;function l6(e){for(var t=e.length;t--&&s6.test(e.charAt(t)););return t}var u6=l6,c6=u6,f6=/^\s+/;function d6(e){return e&&e.slice(0,c6(e)+1).replace(f6,"")}var p6=d6,h6=p6,mx=Vn,m6=no,vx=NaN,v6=/^[-+]0x[0-9a-f]+$/i,y6=/^0b[01]+$/i,g6=/^0o[0-7]+$/i,x6=parseInt;function b6(e){if(typeof e=="number")return e;if(m6(e))return vx;if(mx(e)){var t=typeof e.valueOf=="function"?e.valueOf():e;e=mx(t)?t+"":t}if(typeof e!="string")return e===0?e:+e;e=h6(e);var r=y6.test(e);return r||g6.test(e)?x6(e.slice(2),r?2:8):v6.test(e)?vx:+e}var QO=b6,w6=Vn,Ud=o6,yx=QO,j6="Expected a function",S6=Math.max,O6=Math.min;function _6(e,t,r){var n,i,a,o,s,l,u=0,f=!1,d=!1,p=!0;if(typeof e!="function")throw new TypeError(j6);t=yx(t)||0,w6(r)&&(f=!!r.leading,d="maxWait"in r,a=d?S6(yx(r.maxWait)||0,t):a,p="trailing"in r?!!r.trailing:p);function h(j){var O=n,_=i;return n=i=void 0,u=j,o=e.apply(_,O),o}function m(j){return u=j,s=setTimeout(y,t),f?h(j):o}function g(j){var O=j-l,_=j-u,P=t-O;return d?O6(P,a-_):P}function x(j){var O=j-l,_=j-u;return l===void 0||O>=t||O<0||d&&_>=a}function y(){var j=Ud();if(x(j))return v(j);s=setTimeout(y,g(j))}function v(j){return s=void 0,p&&n?h(j):(n=i=void 0,o)}function b(){s!==void 0&&clearTimeout(s),u=0,n=l=i=s=void 0}function S(){return s===void 0?o:v(Ud())}function w(){var j=Ud(),O=x(j);if(n=arguments,i=this,l=j,O){if(s===void 0)return m(l);if(d)return clearTimeout(s),s=setTimeout(y,t),h(l)}return s===void 0&&(s=setTimeout(y,t)),o}return w.cancel=b,w.flush=S,w}var P6=_6,k6=P6,A6=Vn,N6="Expected a function";function $6(e,t,r){var n=!0,i=!0;if(typeof e!="function")throw new TypeError(N6);return A6(r)&&(n="leading"in r?!!r.leading:n,i="trailing"in r?!!r.trailing:i),k6(e,t,{leading:n,maxWait:t,trailing:i})}var E6=$6;const ZO=de(E6);function As(e){"@babel/helpers - typeof";return As=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},As(e)}function gx(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function Hl(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?gx(Object(r),!0).forEach(function(n){T6(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):gx(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function T6(e,t,r){return t=C6(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function C6(e){var t=M6(e,"string");return As(t)=="symbol"?t:t+""}function M6(e,t){if(As(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(As(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function I6(e,t){return B6(e)||R6(e,t)||D6(e,t)||L6()}function L6(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
-In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function D6(e,t){if(e){if(typeof e=="string")return xx(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return xx(e,t)}}function xx(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function R6(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,i,a,o,s=[],l=!0,u=!1;try{if(a=(r=r.call(e)).next,t!==0)for(;!(l=(n=a.call(r)).done)&&(s.push(n.value),s.length!==t);l=!0);}catch(f){u=!0,i=f}finally{try{if(!l&&r.return!=null&&(o=r.return(),Object(o)!==o))return}finally{if(u)throw i}}return s}}function B6(e){if(Array.isArray(e))return e}var pt=k.forwardRef(function(e,t){var r=e.aspect,n=e.initialDimension,i=n===void 0?{width:-1,height:-1}:n,a=e.width,o=a===void 0?"100%":a,s=e.height,l=s===void 0?"100%":s,u=e.minWidth,f=u===void 0?0:u,d=e.minHeight,p=e.maxHeight,h=e.children,m=e.debounce,g=m===void 0?0:m,x=e.id,y=e.className,v=e.onResize,b=e.style,S=b===void 0?{}:b,w=k.useRef(null),j=k.useRef();j.current=v,k.useImperativeHandle(t,function(){return Object.defineProperty(w.current,"current",{get:function(){return console.warn("The usage of ref.current.current is deprecated and will no longer be supported."),w.current},configurable:!0})});var O=k.useState({containerWidth:i.width,containerHeight:i.height}),_=I6(O,2),P=_[0],N=_[1],T=k.useCallback(function(I,D){N(function(L){var C=Math.round(I),F=Math.round(D);return L.containerWidth===C&&L.containerHeight===F?L:{containerWidth:C,containerHeight:F}})},[]);k.useEffect(function(){var I=function(B){var E,W=B[0].contentRect,z=W.width,X=W.height;T(z,X),(E=j.current)===null||E===void 0||E.call(j,z,X)};g>0&&(I=ZO(I,g,{trailing:!0,leading:!1}));var D=new ResizeObserver(I),L=w.current.getBoundingClientRect(),C=L.width,F=L.height;return T(C,F),D.observe(w.current),function(){D.disconnect()}},[T,g]);var $=k.useMemo(function(){var I=P.containerWidth,D=P.containerHeight;if(I<0||D<0)return null;xr(fi(o)||fi(l),`The width(%s) and height(%s) are both fixed numbers,
- maybe you don't need to use a ResponsiveContainer.`,o,l),xr(!r||r>0,"The aspect(%s) must be greater than zero.",r);var L=fi(o)?I:o,C=fi(l)?D:l;r&&r>0&&(L?C=L/r:C&&(L=C*r),p&&C>p&&(C=p)),xr(L>0||C>0,`The width(%s) and height(%s) of chart should be greater than 0,
- please check the style of container, or the props width(%s) and height(%s),
- or add a minWidth(%s) or minHeight(%s) or use aspect(%s) to control the
- height and width.`,L,C,o,l,f,d,r);var F=!Array.isArray(h)&&Gr(h.type).endsWith("Chart");return A.Children.map(h,function(M){return A.isValidElement(M)?k.cloneElement(M,Hl({width:L,height:C},F?{style:Hl({height:"100%",width:"100%",maxHeight:C,maxWidth:L},M.props.style)}:{})):M})},[r,h,l,p,d,f,P,o]);return A.createElement("div",{id:x?"".concat(x):void 0,className:ee("recharts-responsive-container",y),style:Hl(Hl({},S),{},{width:o,height:l,minWidth:f,minHeight:d,maxHeight:p}),ref:w},$)}),jr=function(t){return null};jr.displayName="Cell";function Ns(e){"@babel/helpers - typeof";return Ns=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Ns(e)}function bx(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function Th(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?bx(Object(r),!0).forEach(function(n){F6(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):bx(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function F6(e,t,r){return t=z6(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function z6(e){var t=W6(e,"string");return Ns(t)=="symbol"?t:t+""}function W6(e,t){if(Ns(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(Ns(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var Fi={widthCache:{},cacheCount:0},U6=2e3,K6={position:"absolute",top:"-20000px",left:0,padding:0,margin:0,border:"none",whiteSpace:"pre"},wx="recharts_measurement_span";function H6(e){var t=Th({},e);return Object.keys(t).forEach(function(r){t[r]||delete t[r]}),t}var Xo=function(t){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(t==null||sn.isSsr)return{width:0,height:0};var n=H6(r),i=JSON.stringify({text:t,copyStyle:n});if(Fi.widthCache[i])return Fi.widthCache[i];try{var a=document.getElementById(wx);a||(a=document.createElement("span"),a.setAttribute("id",wx),a.setAttribute("aria-hidden","true"),document.body.appendChild(a));var o=Th(Th({},K6),n);Object.assign(a.style,o),a.textContent="".concat(t);var s=a.getBoundingClientRect(),l={width:s.width,height:s.height};return Fi.widthCache[i]=l,++Fi.cacheCount>U6&&(Fi.cacheCount=0,Fi.widthCache={}),l}catch{return{width:0,height:0}}},V6=function(t){return{top:t.top+window.scrollY-document.documentElement.clientTop,left:t.left+window.scrollX-document.documentElement.clientLeft}};function $s(e){"@babel/helpers - typeof";return $s=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},$s(e)}function tc(e,t){return X6(e)||q6(e,t)||Y6(e,t)||G6()}function G6(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
-In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Y6(e,t){if(e){if(typeof e=="string")return jx(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return jx(e,t)}}function jx(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function q6(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,i,a,o,s=[],l=!0,u=!1;try{if(a=(r=r.call(e)).next,t===0){if(Object(r)!==r)return;l=!1}else for(;!(l=(n=a.call(r)).done)&&(s.push(n.value),s.length!==t);l=!0);}catch(f){u=!0,i=f}finally{try{if(!l&&r.return!=null&&(o=r.return(),Object(o)!==o))return}finally{if(u)throw i}}return s}}function X6(e){if(Array.isArray(e))return e}function Q6(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function Sx(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,J6(n.key),n)}}function Z6(e,t,r){return t&&Sx(e.prototype,t),r&&Sx(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function J6(e){var t=eF(e,"string");return $s(t)=="symbol"?t:t+""}function eF(e,t){if($s(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if($s(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}var Ox=/(-?\d+(?:\.\d+)?[a-zA-Z%]*)([*/])(-?\d+(?:\.\d+)?[a-zA-Z%]*)/,_x=/(-?\d+(?:\.\d+)?[a-zA-Z%]*)([+-])(-?\d+(?:\.\d+)?[a-zA-Z%]*)/,tF=/^px|cm|vh|vw|em|rem|%|mm|in|pt|pc|ex|ch|vmin|vmax|Q$/,rF=/(-?\d+(?:\.\d+)?)([a-zA-Z%]+)?/,JO={cm:96/2.54,mm:96/25.4,pt:96/72,pc:96/6,in:96,Q:96/(2.54*40),px:1},nF=Object.keys(JO),na="NaN";function iF(e,t){return e*JO[t]}var Vl=function(){function e(t,r){Q6(this,e),this.num=t,this.unit=r,this.num=t,this.unit=r,Number.isNaN(t)&&(this.unit=""),r!==""&&!tF.test(r)&&(this.num=NaN,this.unit=""),nF.includes(r)&&(this.num=iF(t,r),this.unit="px")}return Z6(e,[{key:"add",value:function(r){return this.unit!==r.unit?new e(NaN,""):new e(this.num+r.num,this.unit)}},{key:"subtract",value:function(r){return this.unit!==r.unit?new e(NaN,""):new e(this.num-r.num,this.unit)}},{key:"multiply",value:function(r){return this.unit!==""&&r.unit!==""&&this.unit!==r.unit?new e(NaN,""):new e(this.num*r.num,this.unit||r.unit)}},{key:"divide",value:function(r){return this.unit!==""&&r.unit!==""&&this.unit!==r.unit?new e(NaN,""):new e(this.num/r.num,this.unit||r.unit)}},{key:"toString",value:function(){return"".concat(this.num).concat(this.unit)}},{key:"isNaN",value:function(){return Number.isNaN(this.num)}}],[{key:"parse",value:function(r){var n,i=(n=rF.exec(r))!==null&&n!==void 0?n:[],a=tc(i,3),o=a[1],s=a[2];return new e(parseFloat(o),s??"")}}])}();function e_(e){if(e.includes(na))return na;for(var t=e;t.includes("*")||t.includes("/");){var r,n=(r=Ox.exec(t))!==null&&r!==void 0?r:[],i=tc(n,4),a=i[1],o=i[2],s=i[3],l=Vl.parse(a??""),u=Vl.parse(s??""),f=o==="*"?l.multiply(u):l.divide(u);if(f.isNaN())return na;t=t.replace(Ox,f.toString())}for(;t.includes("+")||/.-\d+(?:\.\d+)?/.test(t);){var d,p=(d=_x.exec(t))!==null&&d!==void 0?d:[],h=tc(p,4),m=h[1],g=h[2],x=h[3],y=Vl.parse(m??""),v=Vl.parse(x??""),b=g==="+"?y.add(v):y.subtract(v);if(b.isNaN())return na;t=t.replace(_x,b.toString())}return t}var Px=/\(([^()]*)\)/;function aF(e){for(var t=e;t.includes("(");){var r=Px.exec(t),n=tc(r,2),i=n[1];t=t.replace(Px,e_(i))}return t}function oF(e){var t=e.replace(/\s+/g,"");return t=aF(t),t=e_(t),t}function sF(e){try{return oF(e)}catch{return na}}function Kd(e){var t=sF(e.slice(5,-1));return t===na?"":t}var lF=["x","y","lineHeight","capHeight","scaleToFit","textAnchor","verticalAnchor","fill"],uF=["dx","dy","angle","className","breakAll"];function Ch(){return Ch=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},Ch.apply(this,arguments)}function kx(e,t){if(e==null)return{};var r=cF(e,t),n,i;if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i<a.length;i++)n=a[i],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function cF(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function Ax(e,t){return hF(e)||pF(e,t)||dF(e,t)||fF()}function fF(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
-In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function dF(e,t){if(e){if(typeof e=="string")return Nx(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return Nx(e,t)}}function Nx(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function pF(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,i,a,o,s=[],l=!0,u=!1;try{if(a=(r=r.call(e)).next,t===0){if(Object(r)!==r)return;l=!1}else for(;!(l=(n=a.call(r)).done)&&(s.push(n.value),s.length!==t);l=!0);}catch(f){u=!0,i=f}finally{try{if(!l&&r.return!=null&&(o=r.return(),Object(o)!==o))return}finally{if(u)throw i}}return s}}function hF(e){if(Array.isArray(e))return e}var t_=/[ \f\n\r\t\v\u2028\u2029]+/,r_=function(t){var r=t.children,n=t.breakAll,i=t.style;try{var a=[];Q(r)||(n?a=r.toString().split(""):a=r.toString().split(t_));var o=a.map(function(l){return{word:l,width:Xo(l,i).width}}),s=n?0:Xo(" ",i).width;return{wordsWithComputedWidth:o,spaceWidth:s}}catch{return null}},mF=function(t,r,n,i,a){var o=t.maxLines,s=t.children,l=t.style,u=t.breakAll,f=K(o),d=s,p=function(){var L=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return L.reduce(function(C,F){var M=F.word,B=F.width,E=C[C.length-1];if(E&&(i==null||a||E.width+B+n<Number(i)))E.words.push(M),E.width+=B+n;else{var W={words:[M],width:B};C.push(W)}return C},[])},h=p(r),m=function(L){return L.reduce(function(C,F){return C.width>F.width?C:F})};if(!f)return h;for(var g="…",x=function(L){var C=d.slice(0,L),F=r_({breakAll:u,style:l,children:C+g}).wordsWithComputedWidth,M=p(F),B=M.length>o||m(M).width>Number(i);return[B,M]},y=0,v=d.length-1,b=0,S;y<=v&&b<=d.length-1;){var w=Math.floor((y+v)/2),j=w-1,O=x(j),_=Ax(O,2),P=_[0],N=_[1],T=x(w),$=Ax(T,1),I=$[0];if(!P&&!I&&(y=w+1),P&&I&&(v=w-1),!P&&I){S=N;break}b++}return S||h},$x=function(t){var r=Q(t)?[]:t.toString().split(t_);return[{words:r}]},vF=function(t){var r=t.width,n=t.scaleToFit,i=t.children,a=t.style,o=t.breakAll,s=t.maxLines;if((r||n)&&!sn.isSsr){var l,u,f=r_({breakAll:o,children:i,style:a});if(f){var d=f.wordsWithComputedWidth,p=f.spaceWidth;l=d,u=p}else return $x(i);return mF({breakAll:o,children:i,maxLines:s,style:a},l,u,r,n)}return $x(i)},Ex="#808080",ki=function(t){var r=t.x,n=r===void 0?0:r,i=t.y,a=i===void 0?0:i,o=t.lineHeight,s=o===void 0?"1em":o,l=t.capHeight,u=l===void 0?"0.71em":l,f=t.scaleToFit,d=f===void 0?!1:f,p=t.textAnchor,h=p===void 0?"start":p,m=t.verticalAnchor,g=m===void 0?"end":m,x=t.fill,y=x===void 0?Ex:x,v=kx(t,lF),b=k.useMemo(function(){return vF({breakAll:v.breakAll,children:v.children,maxLines:v.maxLines,scaleToFit:d,style:v.style,width:v.width})},[v.breakAll,v.children,v.maxLines,d,v.style,v.width]),S=v.dx,w=v.dy,j=v.angle,O=v.className,_=v.breakAll,P=kx(v,uF);if(!Xe(n)||!Xe(a))return null;var N=n+(K(S)?S:0),T=a+(K(w)?w:0),$;switch(g){case"start":$=Kd("calc(".concat(u,")"));break;case"middle":$=Kd("calc(".concat((b.length-1)/2," * -").concat(s," + (").concat(u," / 2))"));break;default:$=Kd("calc(".concat(b.length-1," * -").concat(s,")"));break}var I=[];if(d){var D=b[0].width,L=v.width;I.push("scale(".concat((K(L)?L/D:1)/D,")"))}return j&&I.push("rotate(".concat(j,", ").concat(N,", ").concat(T,")")),I.length&&(P.transform=I.join(" ")),A.createElement("text",Ch({},q(P,!0),{x:N,y:T,className:ee("recharts-text",O),textAnchor:h,fill:y.includes("url")?Ex:y}),b.map(function(C,F){var M=C.words.join(_?"":" ");return A.createElement("tspan",{x:N,dy:F===0?$:s,key:"".concat(M,"-").concat(F)},M)}))};function In(e,t){return e==null||t==null?NaN:e<t?-1:e>t?1:e>=t?0:NaN}function yF(e,t){return e==null||t==null?NaN:t<e?-1:t>e?1:t>=e?0:NaN}function oy(e){let t,r,n;e.length!==2?(t=In,r=(s,l)=>In(e(s),l),n=(s,l)=>e(s)-l):(t=e===In||e===yF?e:gF,r=e,n=e);function i(s,l,u=0,f=s.length){if(u<f){if(t(l,l)!==0)return f;do{const d=u+f>>>1;r(s[d],l)<0?u=d+1:f=d}while(u<f)}return u}function a(s,l,u=0,f=s.length){if(u<f){if(t(l,l)!==0)return f;do{const d=u+f>>>1;r(s[d],l)<=0?u=d+1:f=d}while(u<f)}return u}function o(s,l,u=0,f=s.length){const d=i(s,l,u,f-1);return d>u&&n(s[d-1],l)>-n(s[d],l)?d-1:d}return{left:i,center:o,right:a}}function gF(){return 0}function n_(e){return e===null?NaN:+e}function*xF(e,t){for(let r of e)r!=null&&(r=+r)>=r&&(yield r)}const bF=oy(In),ml=bF.right;oy(n_).center;class Tx extends Map{constructor(t,r=SF){if(super(),Object.defineProperties(this,{_intern:{value:new Map},_key:{value:r}}),t!=null)for(const[n,i]of t)this.set(n,i)}get(t){return super.get(Cx(this,t))}has(t){return super.has(Cx(this,t))}set(t,r){return super.set(wF(this,t),r)}delete(t){return super.delete(jF(this,t))}}function Cx({_intern:e,_key:t},r){const n=t(r);return e.has(n)?e.get(n):r}function wF({_intern:e,_key:t},r){const n=t(r);return e.has(n)?e.get(n):(e.set(n,r),r)}function jF({_intern:e,_key:t},r){const n=t(r);return e.has(n)&&(r=e.get(n),e.delete(n)),r}function SF(e){return e!==null&&typeof e=="object"?e.valueOf():e}function OF(e=In){if(e===In)return i_;if(typeof e!="function")throw new TypeError("compare is not a function");return(t,r)=>{const n=e(t,r);return n||n===0?n:(e(r,r)===0)-(e(t,t)===0)}}function i_(e,t){return(e==null||!(e>=e))-(t==null||!(t>=t))||(e<t?-1:e>t?1:0)}const _F=Math.sqrt(50),PF=Math.sqrt(10),kF=Math.sqrt(2);function rc(e,t,r){const n=(t-e)/Math.max(0,r),i=Math.floor(Math.log10(n)),a=n/Math.pow(10,i),o=a>=_F?10:a>=PF?5:a>=kF?2:1;let s,l,u;return i<0?(u=Math.pow(10,-i)/o,s=Math.round(e*u),l=Math.round(t*u),s/u<e&&++s,l/u>t&&--l,u=-u):(u=Math.pow(10,i)*o,s=Math.round(e/u),l=Math.round(t/u),s*u<e&&++s,l*u>t&&--l),l<s&&.5<=r&&r<2?rc(e,t,r*2):[s,l,u]}function Mh(e,t,r){if(t=+t,e=+e,r=+r,!(r>0))return[];if(e===t)return[e];const n=t<e,[i,a,o]=n?rc(t,e,r):rc(e,t,r);if(!(a>=i))return[];const s=a-i+1,l=new Array(s);if(n)if(o<0)for(let u=0;u<s;++u)l[u]=(a-u)/-o;else for(let u=0;u<s;++u)l[u]=(a-u)*o;else if(o<0)for(let u=0;u<s;++u)l[u]=(i+u)/-o;else for(let u=0;u<s;++u)l[u]=(i+u)*o;return l}function Ih(e,t,r){return t=+t,e=+e,r=+r,rc(e,t,r)[2]}function Lh(e,t,r){t=+t,e=+e,r=+r;const n=t<e,i=n?Ih(t,e,r):Ih(e,t,r);return(n?-1:1)*(i<0?1/-i:i)}function Mx(e,t){let r;for(const n of e)n!=null&&(r<n||r===void 0&&n>=n)&&(r=n);return r}function Ix(e,t){let r;for(const n of e)n!=null&&(r>n||r===void 0&&n>=n)&&(r=n);return r}function a_(e,t,r=0,n=1/0,i){if(t=Math.floor(t),r=Math.floor(Math.max(0,r)),n=Math.floor(Math.min(e.length-1,n)),!(r<=t&&t<=n))return e;for(i=i===void 0?i_:OF(i);n>r;){if(n-r>600){const l=n-r+1,u=t-r+1,f=Math.log(l),d=.5*Math.exp(2*f/3),p=.5*Math.sqrt(f*d*(l-d)/l)*(u-l/2<0?-1:1),h=Math.max(r,Math.floor(t-u*d/l+p)),m=Math.min(n,Math.floor(t+(l-u)*d/l+p));a_(e,t,h,m,i)}const a=e[t];let o=r,s=n;for(Ao(e,r,t),i(e[n],a)>0&&Ao(e,r,n);o<s;){for(Ao(e,o,s),++o,--s;i(e[o],a)<0;)++o;for(;i(e[s],a)>0;)--s}i(e[r],a)===0?Ao(e,r,s):(++s,Ao(e,s,n)),s<=t&&(r=s+1),t<=s&&(n=s-1)}return e}function Ao(e,t,r){const n=e[t];e[t]=e[r],e[r]=n}function AF(e,t,r){if(e=Float64Array.from(xF(e)),!(!(n=e.length)||isNaN(t=+t))){if(t<=0||n<2)return Ix(e);if(t>=1)return Mx(e);var n,i=(n-1)*t,a=Math.floor(i),o=Mx(a_(e,a).subarray(0,a+1)),s=Ix(e.subarray(a+1));return o+(s-o)*(i-a)}}function NF(e,t,r=n_){if(!(!(n=e.length)||isNaN(t=+t))){if(t<=0||n<2)return+r(e[0],0,e);if(t>=1)return+r(e[n-1],n-1,e);var n,i=(n-1)*t,a=Math.floor(i),o=+r(e[a],a,e),s=+r(e[a+1],a+1,e);return o+(s-o)*(i-a)}}function $F(e,t,r){e=+e,t=+t,r=(i=arguments.length)<2?(t=e,e=0,1):i<3?1:+r;for(var n=-1,i=Math.max(0,Math.ceil((t-e)/r))|0,a=new Array(i);++n<i;)a[n]=e+n*r;return a}function lr(e,t){switch(arguments.length){case 0:break;case 1:this.range(e);break;default:this.range(t).domain(e);break}return this}function ln(e,t){switch(arguments.length){case 0:break;case 1:{typeof e=="function"?this.interpolator(e):this.range(e);break}default:{this.domain(e),typeof t=="function"?this.interpolator(t):this.range(t);break}}return this}const Dh=Symbol("implicit");function sy(){var e=new Tx,t=[],r=[],n=Dh;function i(a){let o=e.get(a);if(o===void 0){if(n!==Dh)return n;e.set(a,o=t.push(a)-1)}return r[o%r.length]}return i.domain=function(a){if(!arguments.length)return t.slice();t=[],e=new Tx;for(const o of a)e.has(o)||e.set(o,t.push(o)-1);return i},i.range=function(a){return arguments.length?(r=Array.from(a),i):r.slice()},i.unknown=function(a){return arguments.length?(n=a,i):n},i.copy=function(){return sy(t,r).unknown(n)},lr.apply(i,arguments),i}function Es(){var e=sy().unknown(void 0),t=e.domain,r=e.range,n=0,i=1,a,o,s=!1,l=0,u=0,f=.5;delete e.unknown;function d(){var p=t().length,h=i<n,m=h?i:n,g=h?n:i;a=(g-m)/Math.max(1,p-l+u*2),s&&(a=Math.floor(a)),m+=(g-m-a*(p-l))*f,o=a*(1-l),s&&(m=Math.round(m),o=Math.round(o));var x=$F(p).map(function(y){return m+a*y});return r(h?x.reverse():x)}return e.domain=function(p){return arguments.length?(t(p),d()):t()},e.range=function(p){return arguments.length?([n,i]=p,n=+n,i=+i,d()):[n,i]},e.rangeRound=function(p){return[n,i]=p,n=+n,i=+i,s=!0,d()},e.bandwidth=function(){return o},e.step=function(){return a},e.round=function(p){return arguments.length?(s=!!p,d()):s},e.padding=function(p){return arguments.length?(l=Math.min(1,u=+p),d()):l},e.paddingInner=function(p){return arguments.length?(l=Math.min(1,p),d()):l},e.paddingOuter=function(p){return arguments.length?(u=+p,d()):u},e.align=function(p){return arguments.length?(f=Math.max(0,Math.min(1,p)),d()):f},e.copy=function(){return Es(t(),[n,i]).round(s).paddingInner(l).paddingOuter(u).align(f)},lr.apply(d(),arguments)}function o_(e){var t=e.copy;return e.padding=e.paddingOuter,delete e.paddingInner,delete e.paddingOuter,e.copy=function(){return o_(t())},e}function Qo(){return o_(Es.apply(null,arguments).paddingInner(1))}function ly(e,t,r){e.prototype=t.prototype=r,r.constructor=e}function s_(e,t){var r=Object.create(e.prototype);for(var n in t)r[n]=t[n];return r}function vl(){}var Ts=.7,nc=1/Ts,ma="\\s*([+-]?\\d+)\\s*",Cs="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",Tr="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",EF=/^#([0-9a-f]{3,8})$/,TF=new RegExp(`^rgb\\(${ma},${ma},${ma}\\)$`),CF=new RegExp(`^rgb\\(${Tr},${Tr},${Tr}\\)$`),MF=new RegExp(`^rgba\\(${ma},${ma},${ma},${Cs}\\)$`),IF=new RegExp(`^rgba\\(${Tr},${Tr},${Tr},${Cs}\\)$`),LF=new RegExp(`^hsl\\(${Cs},${Tr},${Tr}\\)$`),DF=new RegExp(`^hsla\\(${Cs},${Tr},${Tr},${Cs}\\)$`),Lx={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074};ly(vl,Ms,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:Dx,formatHex:Dx,formatHex8:RF,formatHsl:BF,formatRgb:Rx,toString:Rx});function Dx(){return this.rgb().formatHex()}function RF(){return this.rgb().formatHex8()}function BF(){return l_(this).formatHsl()}function Rx(){return this.rgb().formatRgb()}function Ms(e){var t,r;return e=(e+"").trim().toLowerCase(),(t=EF.exec(e))?(r=t[1].length,t=parseInt(t[1],16),r===6?Bx(t):r===3?new At(t>>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):r===8?Gl(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):r===4?Gl(t>>12&15|t>>8&240,t>>8&15|t>>4&240,t>>4&15|t&240,((t&15)<<4|t&15)/255):null):(t=TF.exec(e))?new At(t[1],t[2],t[3],1):(t=CF.exec(e))?new At(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=MF.exec(e))?Gl(t[1],t[2],t[3],t[4]):(t=IF.exec(e))?Gl(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=LF.exec(e))?Wx(t[1],t[2]/100,t[3]/100,1):(t=DF.exec(e))?Wx(t[1],t[2]/100,t[3]/100,t[4]):Lx.hasOwnProperty(e)?Bx(Lx[e]):e==="transparent"?new At(NaN,NaN,NaN,0):null}function Bx(e){return new At(e>>16&255,e>>8&255,e&255,1)}function Gl(e,t,r,n){return n<=0&&(e=t=r=NaN),new At(e,t,r,n)}function FF(e){return e instanceof vl||(e=Ms(e)),e?(e=e.rgb(),new At(e.r,e.g,e.b,e.opacity)):new At}function Rh(e,t,r,n){return arguments.length===1?FF(e):new At(e,t,r,n??1)}function At(e,t,r,n){this.r=+e,this.g=+t,this.b=+r,this.opacity=+n}ly(At,Rh,s_(vl,{brighter(e){return e=e==null?nc:Math.pow(nc,e),new At(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?Ts:Math.pow(Ts,e),new At(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new At(gi(this.r),gi(this.g),gi(this.b),ic(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:Fx,formatHex:Fx,formatHex8:zF,formatRgb:zx,toString:zx}));function Fx(){return`#${di(this.r)}${di(this.g)}${di(this.b)}`}function zF(){return`#${di(this.r)}${di(this.g)}${di(this.b)}${di((isNaN(this.opacity)?1:this.opacity)*255)}`}function zx(){const e=ic(this.opacity);return`${e===1?"rgb(":"rgba("}${gi(this.r)}, ${gi(this.g)}, ${gi(this.b)}${e===1?")":`, ${e})`}`}function ic(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function gi(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function di(e){return e=gi(e),(e<16?"0":"")+e.toString(16)}function Wx(e,t,r,n){return n<=0?e=t=r=NaN:r<=0||r>=1?e=t=NaN:t<=0&&(e=NaN),new vr(e,t,r,n)}function l_(e){if(e instanceof vr)return new vr(e.h,e.s,e.l,e.opacity);if(e instanceof vl||(e=Ms(e)),!e)return new vr;if(e instanceof vr)return e;e=e.rgb();var t=e.r/255,r=e.g/255,n=e.b/255,i=Math.min(t,r,n),a=Math.max(t,r,n),o=NaN,s=a-i,l=(a+i)/2;return s?(t===a?o=(r-n)/s+(r<n)*6:r===a?o=(n-t)/s+2:o=(t-r)/s+4,s/=l<.5?a+i:2-a-i,o*=60):s=l>0&&l<1?0:o,new vr(o,s,l,e.opacity)}function WF(e,t,r,n){return arguments.length===1?l_(e):new vr(e,t,r,n??1)}function vr(e,t,r,n){this.h=+e,this.s=+t,this.l=+r,this.opacity=+n}ly(vr,WF,s_(vl,{brighter(e){return e=e==null?nc:Math.pow(nc,e),new vr(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?Ts:Math.pow(Ts,e),new vr(this.h,this.s,this.l*e,this.opacity)},rgb(){var e=this.h%360+(this.h<0)*360,t=isNaN(e)||isNaN(this.s)?0:this.s,r=this.l,n=r+(r<.5?r:1-r)*t,i=2*r-n;return new At(Hd(e>=240?e-240:e+120,i,n),Hd(e,i,n),Hd(e<120?e+240:e-120,i,n),this.opacity)},clamp(){return new vr(Ux(this.h),Yl(this.s),Yl(this.l),ic(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){const e=ic(this.opacity);return`${e===1?"hsl(":"hsla("}${Ux(this.h)}, ${Yl(this.s)*100}%, ${Yl(this.l)*100}%${e===1?")":`, ${e})`}`}}));function Ux(e){return e=(e||0)%360,e<0?e+360:e}function Yl(e){return Math.max(0,Math.min(1,e||0))}function Hd(e,t,r){return(e<60?t+(r-t)*e/60:e<180?r:e<240?t+(r-t)*(240-e)/60:t)*255}const uy=e=>()=>e;function UF(e,t){return function(r){return e+r*t}}function KF(e,t,r){return e=Math.pow(e,r),t=Math.pow(t,r)-e,r=1/r,function(n){return Math.pow(e+n*t,r)}}function HF(e){return(e=+e)==1?u_:function(t,r){return r-t?KF(t,r,e):uy(isNaN(t)?r:t)}}function u_(e,t){var r=t-e;return r?UF(e,r):uy(isNaN(e)?t:e)}const Kx=function e(t){var r=HF(t);function n(i,a){var o=r((i=Rh(i)).r,(a=Rh(a)).r),s=r(i.g,a.g),l=r(i.b,a.b),u=u_(i.opacity,a.opacity);return function(f){return i.r=o(f),i.g=s(f),i.b=l(f),i.opacity=u(f),i+""}}return n.gamma=e,n}(1);function VF(e,t){t||(t=[]);var r=e?Math.min(t.length,e.length):0,n=t.slice(),i;return function(a){for(i=0;i<r;++i)n[i]=e[i]*(1-a)+t[i]*a;return n}}function GF(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function YF(e,t){var r=t?t.length:0,n=e?Math.min(r,e.length):0,i=new Array(n),a=new Array(r),o;for(o=0;o<n;++o)i[o]=po(e[o],t[o]);for(;o<r;++o)a[o]=t[o];return function(s){for(o=0;o<n;++o)a[o]=i[o](s);return a}}function qF(e,t){var r=new Date;return e=+e,t=+t,function(n){return r.setTime(e*(1-n)+t*n),r}}function ac(e,t){return e=+e,t=+t,function(r){return e*(1-r)+t*r}}function XF(e,t){var r={},n={},i;(e===null||typeof e!="object")&&(e={}),(t===null||typeof t!="object")&&(t={});for(i in t)i in e?r[i]=po(e[i],t[i]):n[i]=t[i];return function(a){for(i in r)n[i]=r[i](a);return n}}var Bh=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,Vd=new RegExp(Bh.source,"g");function QF(e){return function(){return e}}function ZF(e){return function(t){return e(t)+""}}function JF(e,t){var r=Bh.lastIndex=Vd.lastIndex=0,n,i,a,o=-1,s=[],l=[];for(e=e+"",t=t+"";(n=Bh.exec(e))&&(i=Vd.exec(t));)(a=i.index)>r&&(a=t.slice(r,a),s[o]?s[o]+=a:s[++o]=a),(n=n[0])===(i=i[0])?s[o]?s[o]+=i:s[++o]=i:(s[++o]=null,l.push({i:o,x:ac(n,i)})),r=Vd.lastIndex;return r<t.length&&(a=t.slice(r),s[o]?s[o]+=a:s[++o]=a),s.length<2?l[0]?ZF(l[0].x):QF(t):(t=l.length,function(u){for(var f=0,d;f<t;++f)s[(d=l[f]).i]=d.x(u);return s.join("")})}function po(e,t){var r=typeof t,n;return t==null||r==="boolean"?uy(t):(r==="number"?ac:r==="string"?(n=Ms(t))?(t=n,Kx):JF:t instanceof Ms?Kx:t instanceof Date?qF:GF(t)?VF:Array.isArray(t)?YF:typeof t.valueOf!="function"&&typeof t.toString!="function"||isNaN(t)?XF:ac)(e,t)}function cy(e,t){return e=+e,t=+t,function(r){return Math.round(e*(1-r)+t*r)}}function ez(e,t){t===void 0&&(t=e,e=po);for(var r=0,n=t.length-1,i=t[0],a=new Array(n<0?0:n);r<n;)a[r]=e(i,i=t[++r]);return function(o){var s=Math.max(0,Math.min(n-1,Math.floor(o*=n)));return a[s](o-s)}}function tz(e){return function(){return e}}function oc(e){return+e}var Hx=[0,1];function xt(e){return e}function Fh(e,t){return(t-=e=+e)?function(r){return(r-e)/t}:tz(isNaN(t)?NaN:.5)}function rz(e,t){var r;return e>t&&(r=e,e=t,t=r),function(n){return Math.max(e,Math.min(t,n))}}function nz(e,t,r){var n=e[0],i=e[1],a=t[0],o=t[1];return i<n?(n=Fh(i,n),a=r(o,a)):(n=Fh(n,i),a=r(a,o)),function(s){return a(n(s))}}function iz(e,t,r){var n=Math.min(e.length,t.length)-1,i=new Array(n),a=new Array(n),o=-1;for(e[n]<e[0]&&(e=e.slice().reverse(),t=t.slice().reverse());++o<n;)i[o]=Fh(e[o],e[o+1]),a[o]=r(t[o],t[o+1]);return function(s){var l=ml(e,s,1,n)-1;return a[l](i[l](s))}}function yl(e,t){return t.domain(e.domain()).range(e.range()).interpolate(e.interpolate()).clamp(e.clamp()).unknown(e.unknown())}function If(){var e=Hx,t=Hx,r=po,n,i,a,o=xt,s,l,u;function f(){var p=Math.min(e.length,t.length);return o!==xt&&(o=rz(e[0],e[p-1])),s=p>2?iz:nz,l=u=null,d}function d(p){return p==null||isNaN(p=+p)?a:(l||(l=s(e.map(n),t,r)))(n(o(p)))}return d.invert=function(p){return o(i((u||(u=s(t,e.map(n),ac)))(p)))},d.domain=function(p){return arguments.length?(e=Array.from(p,oc),f()):e.slice()},d.range=function(p){return arguments.length?(t=Array.from(p),f()):t.slice()},d.rangeRound=function(p){return t=Array.from(p),r=cy,f()},d.clamp=function(p){return arguments.length?(o=p?!0:xt,f()):o!==xt},d.interpolate=function(p){return arguments.length?(r=p,f()):r},d.unknown=function(p){return arguments.length?(a=p,d):a},function(p,h){return n=p,i=h,f()}}function fy(){return If()(xt,xt)}function az(e){return Math.abs(e=Math.round(e))>=1e21?e.toLocaleString("en").replace(/,/g,""):e.toString(10)}function sc(e,t){if(!isFinite(e)||e===0)return null;var r=(e=t?e.toExponential(t-1):e.toExponential()).indexOf("e"),n=e.slice(0,r);return[n.length>1?n[0]+n.slice(2):n,+e.slice(r+1)]}function Na(e){return e=sc(Math.abs(e)),e?e[1]:NaN}function oz(e,t){return function(r,n){for(var i=r.length,a=[],o=0,s=e[0],l=0;i>0&&s>0&&(l+s+1>n&&(s=Math.max(1,n-l)),a.push(r.substring(i-=s,i+s)),!((l+=s+1)>n));)s=e[o=(o+1)%e.length];return a.reverse().join(t)}}function sz(e){return function(t){return t.replace(/[0-9]/g,function(r){return e[+r]})}}var lz=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function Is(e){if(!(t=lz.exec(e)))throw new Error("invalid format: "+e);var t;return new dy({fill:t[1],align:t[2],sign:t[3],symbol:t[4],zero:t[5],width:t[6],comma:t[7],precision:t[8]&&t[8].slice(1),trim:t[9],type:t[10]})}Is.prototype=dy.prototype;function dy(e){this.fill=e.fill===void 0?" ":e.fill+"",this.align=e.align===void 0?">":e.align+"",this.sign=e.sign===void 0?"-":e.sign+"",this.symbol=e.symbol===void 0?"":e.symbol+"",this.zero=!!e.zero,this.width=e.width===void 0?void 0:+e.width,this.comma=!!e.comma,this.precision=e.precision===void 0?void 0:+e.precision,this.trim=!!e.trim,this.type=e.type===void 0?"":e.type+""}dy.prototype.toString=function(){return this.fill+this.align+this.sign+this.symbol+(this.zero?"0":"")+(this.width===void 0?"":Math.max(1,this.width|0))+(this.comma?",":"")+(this.precision===void 0?"":"."+Math.max(0,this.precision|0))+(this.trim?"~":"")+this.type};function uz(e){e:for(var t=e.length,r=1,n=-1,i;r<t;++r)switch(e[r]){case".":n=i=r;break;case"0":n===0&&(n=r),i=r;break;default:if(!+e[r])break e;n>0&&(n=0);break}return n>0?e.slice(0,n)+e.slice(i+1):e}var lc;function cz(e,t){var r=sc(e,t);if(!r)return lc=void 0,e.toPrecision(t);var n=r[0],i=r[1],a=i-(lc=Math.max(-8,Math.min(8,Math.floor(i/3)))*3)+1,o=n.length;return a===o?n:a>o?n+new Array(a-o+1).join("0"):a>0?n.slice(0,a)+"."+n.slice(a):"0."+new Array(1-a).join("0")+sc(e,Math.max(0,t+a-1))[0]}function Vx(e,t){var r=sc(e,t);if(!r)return e+"";var n=r[0],i=r[1];return i<0?"0."+new Array(-i).join("0")+n:n.length>i+1?n.slice(0,i+1)+"."+n.slice(i+1):n+new Array(i-n.length+2).join("0")}const Gx={"%":(e,t)=>(e*100).toFixed(t),b:e=>Math.round(e).toString(2),c:e=>e+"",d:az,e:(e,t)=>e.toExponential(t),f:(e,t)=>e.toFixed(t),g:(e,t)=>e.toPrecision(t),o:e=>Math.round(e).toString(8),p:(e,t)=>Vx(e*100,t),r:Vx,s:cz,X:e=>Math.round(e).toString(16).toUpperCase(),x:e=>Math.round(e).toString(16)};function Yx(e){return e}var qx=Array.prototype.map,Xx=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];function fz(e){var t=e.grouping===void 0||e.thousands===void 0?Yx:oz(qx.call(e.grouping,Number),e.thousands+""),r=e.currency===void 0?"":e.currency[0]+"",n=e.currency===void 0?"":e.currency[1]+"",i=e.decimal===void 0?".":e.decimal+"",a=e.numerals===void 0?Yx:sz(qx.call(e.numerals,String)),o=e.percent===void 0?"%":e.percent+"",s=e.minus===void 0?"−":e.minus+"",l=e.nan===void 0?"NaN":e.nan+"";function u(d,p){d=Is(d);var h=d.fill,m=d.align,g=d.sign,x=d.symbol,y=d.zero,v=d.width,b=d.comma,S=d.precision,w=d.trim,j=d.type;j==="n"?(b=!0,j="g"):Gx[j]||(S===void 0&&(S=12),w=!0,j="g"),(y||h==="0"&&m==="=")&&(y=!0,h="0",m="=");var O=(p&&p.prefix!==void 0?p.prefix:"")+(x==="$"?r:x==="#"&&/[boxX]/.test(j)?"0"+j.toLowerCase():""),_=(x==="$"?n:/[%p]/.test(j)?o:"")+(p&&p.suffix!==void 0?p.suffix:""),P=Gx[j],N=/[defgprs%]/.test(j);S=S===void 0?6:/[gprs]/.test(j)?Math.max(1,Math.min(21,S)):Math.max(0,Math.min(20,S));function T($){var I=O,D=_,L,C,F;if(j==="c")D=P($)+D,$="";else{$=+$;var M=$<0||1/$<0;if($=isNaN($)?l:P(Math.abs($),S),w&&($=uz($)),M&&+$==0&&g!=="+"&&(M=!1),I=(M?g==="("?g:s:g==="-"||g==="("?"":g)+I,D=(j==="s"&&!isNaN($)&&lc!==void 0?Xx[8+lc/3]:"")+D+(M&&g==="("?")":""),N){for(L=-1,C=$.length;++L<C;)if(F=$.charCodeAt(L),48>F||F>57){D=(F===46?i+$.slice(L+1):$.slice(L))+D,$=$.slice(0,L);break}}}b&&!y&&($=t($,1/0));var B=I.length+$.length+D.length,E=B<v?new Array(v-B+1).join(h):"";switch(b&&y&&($=t(E+$,E.length?v-D.length:1/0),E=""),m){case"<":$=I+$+D+E;break;case"=":$=I+E+$+D;break;case"^":$=E.slice(0,B=E.length>>1)+I+$+D+E.slice(B);break;default:$=E+I+$+D;break}return a($)}return T.toString=function(){return d+""},T}function f(d,p){var h=Math.max(-8,Math.min(8,Math.floor(Na(p)/3)))*3,m=Math.pow(10,-h),g=u((d=Is(d),d.type="f",d),{suffix:Xx[8+h/3]});return function(x){return g(m*x)}}return{format:u,formatPrefix:f}}var ql,py,c_;dz({thousands:",",grouping:[3],currency:["$",""]});function dz(e){return ql=fz(e),py=ql.format,c_=ql.formatPrefix,ql}function pz(e){return Math.max(0,-Na(Math.abs(e)))}function hz(e,t){return Math.max(0,Math.max(-8,Math.min(8,Math.floor(Na(t)/3)))*3-Na(Math.abs(e)))}function mz(e,t){return e=Math.abs(e),t=Math.abs(t)-e,Math.max(0,Na(t)-Na(e))+1}function f_(e,t,r,n){var i=Lh(e,t,r),a;switch(n=Is(n??",f"),n.type){case"s":{var o=Math.max(Math.abs(e),Math.abs(t));return n.precision==null&&!isNaN(a=hz(i,o))&&(n.precision=a),c_(n,o)}case"":case"e":case"g":case"p":case"r":{n.precision==null&&!isNaN(a=mz(i,Math.max(Math.abs(e),Math.abs(t))))&&(n.precision=a-(n.type==="e"));break}case"f":case"%":{n.precision==null&&!isNaN(a=pz(i))&&(n.precision=a-(n.type==="%")*2);break}}return py(n)}function Yn(e){var t=e.domain;return e.ticks=function(r){var n=t();return Mh(n[0],n[n.length-1],r??10)},e.tickFormat=function(r,n){var i=t();return f_(i[0],i[i.length-1],r??10,n)},e.nice=function(r){r==null&&(r=10);var n=t(),i=0,a=n.length-1,o=n[i],s=n[a],l,u,f=10;for(s<o&&(u=o,o=s,s=u,u=i,i=a,a=u);f-- >0;){if(u=Ih(o,s,r),u===l)return n[i]=o,n[a]=s,t(n);if(u>0)o=Math.floor(o/u)*u,s=Math.ceil(s/u)*u;else if(u<0)o=Math.ceil(o*u)/u,s=Math.floor(s*u)/u;else break;l=u}return e},e}function uc(){var e=fy();return e.copy=function(){return yl(e,uc())},lr.apply(e,arguments),Yn(e)}function d_(e){var t;function r(n){return n==null||isNaN(n=+n)?t:n}return r.invert=r,r.domain=r.range=function(n){return arguments.length?(e=Array.from(n,oc),r):e.slice()},r.unknown=function(n){return arguments.length?(t=n,r):t},r.copy=function(){return d_(e).unknown(t)},e=arguments.length?Array.from(e,oc):[0,1],Yn(r)}function p_(e,t){e=e.slice();var r=0,n=e.length-1,i=e[r],a=e[n],o;return a<i&&(o=r,r=n,n=o,o=i,i=a,a=o),e[r]=t.floor(i),e[n]=t.ceil(a),e}function Qx(e){return Math.log(e)}function Zx(e){return Math.exp(e)}function vz(e){return-Math.log(-e)}function yz(e){return-Math.exp(-e)}function gz(e){return isFinite(e)?+("1e"+e):e<0?0:e}function xz(e){return e===10?gz:e===Math.E?Math.exp:t=>Math.pow(e,t)}function bz(e){return e===Math.E?Math.log:e===10&&Math.log10||e===2&&Math.log2||(e=Math.log(e),t=>Math.log(t)/e)}function Jx(e){return(t,r)=>-e(-t,r)}function hy(e){const t=e(Qx,Zx),r=t.domain;let n=10,i,a;function o(){return i=bz(n),a=xz(n),r()[0]<0?(i=Jx(i),a=Jx(a),e(vz,yz)):e(Qx,Zx),t}return t.base=function(s){return arguments.length?(n=+s,o()):n},t.domain=function(s){return arguments.length?(r(s),o()):r()},t.ticks=s=>{const l=r();let u=l[0],f=l[l.length-1];const d=f<u;d&&([u,f]=[f,u]);let p=i(u),h=i(f),m,g;const x=s==null?10:+s;let y=[];if(!(n%1)&&h-p<x){if(p=Math.floor(p),h=Math.ceil(h),u>0){for(;p<=h;++p)for(m=1;m<n;++m)if(g=p<0?m/a(-p):m*a(p),!(g<u)){if(g>f)break;y.push(g)}}else for(;p<=h;++p)for(m=n-1;m>=1;--m)if(g=p>0?m/a(-p):m*a(p),!(g<u)){if(g>f)break;y.push(g)}y.length*2<x&&(y=Mh(u,f,x))}else y=Mh(p,h,Math.min(h-p,x)).map(a);return d?y.reverse():y},t.tickFormat=(s,l)=>{if(s==null&&(s=10),l==null&&(l=n===10?"s":","),typeof l!="function"&&(!(n%1)&&(l=Is(l)).precision==null&&(l.trim=!0),l=py(l)),s===1/0)return l;const u=Math.max(1,n*s/t.ticks().length);return f=>{let d=f/a(Math.round(i(f)));return d*n<n-.5&&(d*=n),d<=u?l(f):""}},t.nice=()=>r(p_(r(),{floor:s=>a(Math.floor(i(s))),ceil:s=>a(Math.ceil(i(s)))})),t}function h_(){const e=hy(If()).domain([1,10]);return e.copy=()=>yl(e,h_()).base(e.base()),lr.apply(e,arguments),e}function eb(e){return function(t){return Math.sign(t)*Math.log1p(Math.abs(t/e))}}function tb(e){return function(t){return Math.sign(t)*Math.expm1(Math.abs(t))*e}}function my(e){var t=1,r=e(eb(t),tb(t));return r.constant=function(n){return arguments.length?e(eb(t=+n),tb(t)):t},Yn(r)}function m_(){var e=my(If());return e.copy=function(){return yl(e,m_()).constant(e.constant())},lr.apply(e,arguments)}function rb(e){return function(t){return t<0?-Math.pow(-t,e):Math.pow(t,e)}}function wz(e){return e<0?-Math.sqrt(-e):Math.sqrt(e)}function jz(e){return e<0?-e*e:e*e}function vy(e){var t=e(xt,xt),r=1;function n(){return r===1?e(xt,xt):r===.5?e(wz,jz):e(rb(r),rb(1/r))}return t.exponent=function(i){return arguments.length?(r=+i,n()):r},Yn(t)}function yy(){var e=vy(If());return e.copy=function(){return yl(e,yy()).exponent(e.exponent())},lr.apply(e,arguments),e}function Sz(){return yy.apply(null,arguments).exponent(.5)}function nb(e){return Math.sign(e)*e*e}function Oz(e){return Math.sign(e)*Math.sqrt(Math.abs(e))}function v_(){var e=fy(),t=[0,1],r=!1,n;function i(a){var o=Oz(e(a));return isNaN(o)?n:r?Math.round(o):o}return i.invert=function(a){return e.invert(nb(a))},i.domain=function(a){return arguments.length?(e.domain(a),i):e.domain()},i.range=function(a){return arguments.length?(e.range((t=Array.from(a,oc)).map(nb)),i):t.slice()},i.rangeRound=function(a){return i.range(a).round(!0)},i.round=function(a){return arguments.length?(r=!!a,i):r},i.clamp=function(a){return arguments.length?(e.clamp(a),i):e.clamp()},i.unknown=function(a){return arguments.length?(n=a,i):n},i.copy=function(){return v_(e.domain(),t).round(r).clamp(e.clamp()).unknown(n)},lr.apply(i,arguments),Yn(i)}function y_(){var e=[],t=[],r=[],n;function i(){var o=0,s=Math.max(1,t.length);for(r=new Array(s-1);++o<s;)r[o-1]=NF(e,o/s);return a}function a(o){return o==null||isNaN(o=+o)?n:t[ml(r,o)]}return a.invertExtent=function(o){var s=t.indexOf(o);return s<0?[NaN,NaN]:[s>0?r[s-1]:e[0],s<r.length?r[s]:e[e.length-1]]},a.domain=function(o){if(!arguments.length)return e.slice();e=[];for(let s of o)s!=null&&!isNaN(s=+s)&&e.push(s);return e.sort(In),i()},a.range=function(o){return arguments.length?(t=Array.from(o),i()):t.slice()},a.unknown=function(o){return arguments.length?(n=o,a):n},a.quantiles=function(){return r.slice()},a.copy=function(){return y_().domain(e).range(t).unknown(n)},lr.apply(a,arguments)}function g_(){var e=0,t=1,r=1,n=[.5],i=[0,1],a;function o(l){return l!=null&&l<=l?i[ml(n,l,0,r)]:a}function s(){var l=-1;for(n=new Array(r);++l<r;)n[l]=((l+1)*t-(l-r)*e)/(r+1);return o}return o.domain=function(l){return arguments.length?([e,t]=l,e=+e,t=+t,s()):[e,t]},o.range=function(l){return arguments.length?(r=(i=Array.from(l)).length-1,s()):i.slice()},o.invertExtent=function(l){var u=i.indexOf(l);return u<0?[NaN,NaN]:u<1?[e,n[0]]:u>=r?[n[r-1],t]:[n[u-1],n[u]]},o.unknown=function(l){return arguments.length&&(a=l),o},o.thresholds=function(){return n.slice()},o.copy=function(){return g_().domain([e,t]).range(i).unknown(a)},lr.apply(Yn(o),arguments)}function x_(){var e=[.5],t=[0,1],r,n=1;function i(a){return a!=null&&a<=a?t[ml(e,a,0,n)]:r}return i.domain=function(a){return arguments.length?(e=Array.from(a),n=Math.min(e.length,t.length-1),i):e.slice()},i.range=function(a){return arguments.length?(t=Array.from(a),n=Math.min(e.length,t.length-1),i):t.slice()},i.invertExtent=function(a){var o=t.indexOf(a);return[e[o-1],e[o]]},i.unknown=function(a){return arguments.length?(r=a,i):r},i.copy=function(){return x_().domain(e).range(t).unknown(r)},lr.apply(i,arguments)}const Gd=new Date,Yd=new Date;function Qe(e,t,r,n){function i(a){return e(a=arguments.length===0?new Date:new Date(+a)),a}return i.floor=a=>(e(a=new Date(+a)),a),i.ceil=a=>(e(a=new Date(a-1)),t(a,1),e(a),a),i.round=a=>{const o=i(a),s=i.ceil(a);return a-o<s-a?o:s},i.offset=(a,o)=>(t(a=new Date(+a),o==null?1:Math.floor(o)),a),i.range=(a,o,s)=>{const l=[];if(a=i.ceil(a),s=s==null?1:Math.floor(s),!(a<o)||!(s>0))return l;let u;do l.push(u=new Date(+a)),t(a,s),e(a);while(u<a&&a<o);return l},i.filter=a=>Qe(o=>{if(o>=o)for(;e(o),!a(o);)o.setTime(o-1)},(o,s)=>{if(o>=o)if(s<0)for(;++s<=0;)for(;t(o,-1),!a(o););else for(;--s>=0;)for(;t(o,1),!a(o););}),r&&(i.count=(a,o)=>(Gd.setTime(+a),Yd.setTime(+o),e(Gd),e(Yd),Math.floor(r(Gd,Yd))),i.every=a=>(a=Math.floor(a),!isFinite(a)||!(a>0)?null:a>1?i.filter(n?o=>n(o)%a===0:o=>i.count(0,o)%a===0):i)),i}const cc=Qe(()=>{},(e,t)=>{e.setTime(+e+t)},(e,t)=>t-e);cc.every=e=>(e=Math.floor(e),!isFinite(e)||!(e>0)?null:e>1?Qe(t=>{t.setTime(Math.floor(t/e)*e)},(t,r)=>{t.setTime(+t+r*e)},(t,r)=>(r-t)/e):cc);cc.range;const Ur=1e3,tr=Ur*60,Kr=tr*60,en=Kr*24,gy=en*7,ib=en*30,qd=en*365,pi=Qe(e=>{e.setTime(e-e.getMilliseconds())},(e,t)=>{e.setTime(+e+t*Ur)},(e,t)=>(t-e)/Ur,e=>e.getUTCSeconds());pi.range;const xy=Qe(e=>{e.setTime(e-e.getMilliseconds()-e.getSeconds()*Ur)},(e,t)=>{e.setTime(+e+t*tr)},(e,t)=>(t-e)/tr,e=>e.getMinutes());xy.range;const by=Qe(e=>{e.setUTCSeconds(0,0)},(e,t)=>{e.setTime(+e+t*tr)},(e,t)=>(t-e)/tr,e=>e.getUTCMinutes());by.range;const wy=Qe(e=>{e.setTime(e-e.getMilliseconds()-e.getSeconds()*Ur-e.getMinutes()*tr)},(e,t)=>{e.setTime(+e+t*Kr)},(e,t)=>(t-e)/Kr,e=>e.getHours());wy.range;const jy=Qe(e=>{e.setUTCMinutes(0,0,0)},(e,t)=>{e.setTime(+e+t*Kr)},(e,t)=>(t-e)/Kr,e=>e.getUTCHours());jy.range;const gl=Qe(e=>e.setHours(0,0,0,0),(e,t)=>e.setDate(e.getDate()+t),(e,t)=>(t-e-(t.getTimezoneOffset()-e.getTimezoneOffset())*tr)/en,e=>e.getDate()-1);gl.range;const Lf=Qe(e=>{e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCDate(e.getUTCDate()+t)},(e,t)=>(t-e)/en,e=>e.getUTCDate()-1);Lf.range;const b_=Qe(e=>{e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCDate(e.getUTCDate()+t)},(e,t)=>(t-e)/en,e=>Math.floor(e/en));b_.range;function Ii(e){return Qe(t=>{t.setDate(t.getDate()-(t.getDay()+7-e)%7),t.setHours(0,0,0,0)},(t,r)=>{t.setDate(t.getDate()+r*7)},(t,r)=>(r-t-(r.getTimezoneOffset()-t.getTimezoneOffset())*tr)/gy)}const Df=Ii(0),fc=Ii(1),_z=Ii(2),Pz=Ii(3),$a=Ii(4),kz=Ii(5),Az=Ii(6);Df.range;fc.range;_z.range;Pz.range;$a.range;kz.range;Az.range;function Li(e){return Qe(t=>{t.setUTCDate(t.getUTCDate()-(t.getUTCDay()+7-e)%7),t.setUTCHours(0,0,0,0)},(t,r)=>{t.setUTCDate(t.getUTCDate()+r*7)},(t,r)=>(r-t)/gy)}const Rf=Li(0),dc=Li(1),Nz=Li(2),$z=Li(3),Ea=Li(4),Ez=Li(5),Tz=Li(6);Rf.range;dc.range;Nz.range;$z.range;Ea.range;Ez.range;Tz.range;const Sy=Qe(e=>{e.setDate(1),e.setHours(0,0,0,0)},(e,t)=>{e.setMonth(e.getMonth()+t)},(e,t)=>t.getMonth()-e.getMonth()+(t.getFullYear()-e.getFullYear())*12,e=>e.getMonth());Sy.range;const Oy=Qe(e=>{e.setUTCDate(1),e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCMonth(e.getUTCMonth()+t)},(e,t)=>t.getUTCMonth()-e.getUTCMonth()+(t.getUTCFullYear()-e.getUTCFullYear())*12,e=>e.getUTCMonth());Oy.range;const tn=Qe(e=>{e.setMonth(0,1),e.setHours(0,0,0,0)},(e,t)=>{e.setFullYear(e.getFullYear()+t)},(e,t)=>t.getFullYear()-e.getFullYear(),e=>e.getFullYear());tn.every=e=>!isFinite(e=Math.floor(e))||!(e>0)?null:Qe(t=>{t.setFullYear(Math.floor(t.getFullYear()/e)*e),t.setMonth(0,1),t.setHours(0,0,0,0)},(t,r)=>{t.setFullYear(t.getFullYear()+r*e)});tn.range;const rn=Qe(e=>{e.setUTCMonth(0,1),e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCFullYear(e.getUTCFullYear()+t)},(e,t)=>t.getUTCFullYear()-e.getUTCFullYear(),e=>e.getUTCFullYear());rn.every=e=>!isFinite(e=Math.floor(e))||!(e>0)?null:Qe(t=>{t.setUTCFullYear(Math.floor(t.getUTCFullYear()/e)*e),t.setUTCMonth(0,1),t.setUTCHours(0,0,0,0)},(t,r)=>{t.setUTCFullYear(t.getUTCFullYear()+r*e)});rn.range;function w_(e,t,r,n,i,a){const o=[[pi,1,Ur],[pi,5,5*Ur],[pi,15,15*Ur],[pi,30,30*Ur],[a,1,tr],[a,5,5*tr],[a,15,15*tr],[a,30,30*tr],[i,1,Kr],[i,3,3*Kr],[i,6,6*Kr],[i,12,12*Kr],[n,1,en],[n,2,2*en],[r,1,gy],[t,1,ib],[t,3,3*ib],[e,1,qd]];function s(u,f,d){const p=f<u;p&&([u,f]=[f,u]);const h=d&&typeof d.range=="function"?d:l(u,f,d),m=h?h.range(u,+f+1):[];return p?m.reverse():m}function l(u,f,d){const p=Math.abs(f-u)/d,h=oy(([,,x])=>x).right(o,p);if(h===o.length)return e.every(Lh(u/qd,f/qd,d));if(h===0)return cc.every(Math.max(Lh(u,f,d),1));const[m,g]=o[p/o[h-1][2]<o[h][2]/p?h-1:h];return m.every(g)}return[s,l]}const[Cz,Mz]=w_(rn,Oy,Rf,b_,jy,by),[Iz,Lz]=w_(tn,Sy,Df,gl,wy,xy);function Xd(e){if(0<=e.y&&e.y<100){var t=new Date(-1,e.m,e.d,e.H,e.M,e.S,e.L);return t.setFullYear(e.y),t}return new Date(e.y,e.m,e.d,e.H,e.M,e.S,e.L)}function Qd(e){if(0<=e.y&&e.y<100){var t=new Date(Date.UTC(-1,e.m,e.d,e.H,e.M,e.S,e.L));return t.setUTCFullYear(e.y),t}return new Date(Date.UTC(e.y,e.m,e.d,e.H,e.M,e.S,e.L))}function No(e,t,r){return{y:e,m:t,d:r,H:0,M:0,S:0,L:0}}function Dz(e){var t=e.dateTime,r=e.date,n=e.time,i=e.periods,a=e.days,o=e.shortDays,s=e.months,l=e.shortMonths,u=$o(i),f=Eo(i),d=$o(a),p=Eo(a),h=$o(o),m=Eo(o),g=$o(s),x=Eo(s),y=$o(l),v=Eo(l),b={a:F,A:M,b:B,B:E,c:null,d:cb,e:cb,f:o9,g:v9,G:g9,H:n9,I:i9,j:a9,L:j_,m:s9,M:l9,p:W,q:z,Q:pb,s:hb,S:u9,u:c9,U:f9,V:d9,w:p9,W:h9,x:null,X:null,y:m9,Y:y9,Z:x9,"%":db},S={a:X,A:oe,b:Pe,B:Le,c:null,d:fb,e:fb,f:S9,g:C9,G:I9,H:b9,I:w9,j:j9,L:O_,m:O9,M:_9,p:Vt,q:Ot,Q:pb,s:hb,S:P9,u:k9,U:A9,V:N9,w:$9,W:E9,x:null,X:null,y:T9,Y:M9,Z:L9,"%":db},w={a:N,A:T,b:$,B:I,c:D,d:lb,e:lb,f:Jz,g:sb,G:ob,H:ub,I:ub,j:qz,L:Zz,m:Yz,M:Xz,p:P,q:Gz,Q:t9,s:r9,S:Qz,u:Wz,U:Uz,V:Kz,w:zz,W:Hz,x:L,X:C,y:sb,Y:ob,Z:Vz,"%":e9};b.x=j(r,b),b.X=j(n,b),b.c=j(t,b),S.x=j(r,S),S.X=j(n,S),S.c=j(t,S);function j(V,re){return function(ne){var U=[],Ce=-1,se=0,Ke=V.length,He,_t,cn;for(ne instanceof Date||(ne=new Date(+ne));++Ce<Ke;)V.charCodeAt(Ce)===37&&(U.push(V.slice(se,Ce)),(_t=ab[He=V.charAt(++Ce)])!=null?He=V.charAt(++Ce):_t=He==="e"?" ":"0",(cn=re[He])&&(He=cn(ne,_t)),U.push(He),se=Ce+1);return U.push(V.slice(se,Ce)),U.join("")}}function O(V,re){return function(ne){var U=No(1900,void 0,1),Ce=_(U,V,ne+="",0),se,Ke;if(Ce!=ne.length)return null;if("Q"in U)return new Date(U.Q);if("s"in U)return new Date(U.s*1e3+("L"in U?U.L:0));if(re&&!("Z"in U)&&(U.Z=0),"p"in U&&(U.H=U.H%12+U.p*12),U.m===void 0&&(U.m="q"in U?U.q:0),"V"in U){if(U.V<1||U.V>53)return null;"w"in U||(U.w=1),"Z"in U?(se=Qd(No(U.y,0,1)),Ke=se.getUTCDay(),se=Ke>4||Ke===0?dc.ceil(se):dc(se),se=Lf.offset(se,(U.V-1)*7),U.y=se.getUTCFullYear(),U.m=se.getUTCMonth(),U.d=se.getUTCDate()+(U.w+6)%7):(se=Xd(No(U.y,0,1)),Ke=se.getDay(),se=Ke>4||Ke===0?fc.ceil(se):fc(se),se=gl.offset(se,(U.V-1)*7),U.y=se.getFullYear(),U.m=se.getMonth(),U.d=se.getDate()+(U.w+6)%7)}else("W"in U||"U"in U)&&("w"in U||(U.w="u"in U?U.u%7:"W"in U?1:0),Ke="Z"in U?Qd(No(U.y,0,1)).getUTCDay():Xd(No(U.y,0,1)).getDay(),U.m=0,U.d="W"in U?(U.w+6)%7+U.W*7-(Ke+5)%7:U.w+U.U*7-(Ke+6)%7);return"Z"in U?(U.H+=U.Z/100|0,U.M+=U.Z%100,Qd(U)):Xd(U)}}function _(V,re,ne,U){for(var Ce=0,se=re.length,Ke=ne.length,He,_t;Ce<se;){if(U>=Ke)return-1;if(He=re.charCodeAt(Ce++),He===37){if(He=re.charAt(Ce++),_t=w[He in ab?re.charAt(Ce++):He],!_t||(U=_t(V,ne,U))<0)return-1}else if(He!=ne.charCodeAt(U++))return-1}return U}function P(V,re,ne){var U=u.exec(re.slice(ne));return U?(V.p=f.get(U[0].toLowerCase()),ne+U[0].length):-1}function N(V,re,ne){var U=h.exec(re.slice(ne));return U?(V.w=m.get(U[0].toLowerCase()),ne+U[0].length):-1}function T(V,re,ne){var U=d.exec(re.slice(ne));return U?(V.w=p.get(U[0].toLowerCase()),ne+U[0].length):-1}function $(V,re,ne){var U=y.exec(re.slice(ne));return U?(V.m=v.get(U[0].toLowerCase()),ne+U[0].length):-1}function I(V,re,ne){var U=g.exec(re.slice(ne));return U?(V.m=x.get(U[0].toLowerCase()),ne+U[0].length):-1}function D(V,re,ne){return _(V,t,re,ne)}function L(V,re,ne){return _(V,r,re,ne)}function C(V,re,ne){return _(V,n,re,ne)}function F(V){return o[V.getDay()]}function M(V){return a[V.getDay()]}function B(V){return l[V.getMonth()]}function E(V){return s[V.getMonth()]}function W(V){return i[+(V.getHours()>=12)]}function z(V){return 1+~~(V.getMonth()/3)}function X(V){return o[V.getUTCDay()]}function oe(V){return a[V.getUTCDay()]}function Pe(V){return l[V.getUTCMonth()]}function Le(V){return s[V.getUTCMonth()]}function Vt(V){return i[+(V.getUTCHours()>=12)]}function Ot(V){return 1+~~(V.getUTCMonth()/3)}return{format:function(V){var re=j(V+="",b);return re.toString=function(){return V},re},parse:function(V){var re=O(V+="",!1);return re.toString=function(){return V},re},utcFormat:function(V){var re=j(V+="",S);return re.toString=function(){return V},re},utcParse:function(V){var re=O(V+="",!0);return re.toString=function(){return V},re}}}var ab={"-":"",_:" ",0:"0"},nt=/^\s*\d+/,Rz=/^%/,Bz=/[\\^$*+?|[\]().{}]/g;function ue(e,t,r){var n=e<0?"-":"",i=(n?-e:e)+"",a=i.length;return n+(a<r?new Array(r-a+1).join(t)+i:i)}function Fz(e){return e.replace(Bz,"\\$&")}function $o(e){return new RegExp("^(?:"+e.map(Fz).join("|")+")","i")}function Eo(e){return new Map(e.map((t,r)=>[t.toLowerCase(),r]))}function zz(e,t,r){var n=nt.exec(t.slice(r,r+1));return n?(e.w=+n[0],r+n[0].length):-1}function Wz(e,t,r){var n=nt.exec(t.slice(r,r+1));return n?(e.u=+n[0],r+n[0].length):-1}function Uz(e,t,r){var n=nt.exec(t.slice(r,r+2));return n?(e.U=+n[0],r+n[0].length):-1}function Kz(e,t,r){var n=nt.exec(t.slice(r,r+2));return n?(e.V=+n[0],r+n[0].length):-1}function Hz(e,t,r){var n=nt.exec(t.slice(r,r+2));return n?(e.W=+n[0],r+n[0].length):-1}function ob(e,t,r){var n=nt.exec(t.slice(r,r+4));return n?(e.y=+n[0],r+n[0].length):-1}function sb(e,t,r){var n=nt.exec(t.slice(r,r+2));return n?(e.y=+n[0]+(+n[0]>68?1900:2e3),r+n[0].length):-1}function Vz(e,t,r){var n=/^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(t.slice(r,r+6));return n?(e.Z=n[1]?0:-(n[2]+(n[3]||"00")),r+n[0].length):-1}function Gz(e,t,r){var n=nt.exec(t.slice(r,r+1));return n?(e.q=n[0]*3-3,r+n[0].length):-1}function Yz(e,t,r){var n=nt.exec(t.slice(r,r+2));return n?(e.m=n[0]-1,r+n[0].length):-1}function lb(e,t,r){var n=nt.exec(t.slice(r,r+2));return n?(e.d=+n[0],r+n[0].length):-1}function qz(e,t,r){var n=nt.exec(t.slice(r,r+3));return n?(e.m=0,e.d=+n[0],r+n[0].length):-1}function ub(e,t,r){var n=nt.exec(t.slice(r,r+2));return n?(e.H=+n[0],r+n[0].length):-1}function Xz(e,t,r){var n=nt.exec(t.slice(r,r+2));return n?(e.M=+n[0],r+n[0].length):-1}function Qz(e,t,r){var n=nt.exec(t.slice(r,r+2));return n?(e.S=+n[0],r+n[0].length):-1}function Zz(e,t,r){var n=nt.exec(t.slice(r,r+3));return n?(e.L=+n[0],r+n[0].length):-1}function Jz(e,t,r){var n=nt.exec(t.slice(r,r+6));return n?(e.L=Math.floor(n[0]/1e3),r+n[0].length):-1}function e9(e,t,r){var n=Rz.exec(t.slice(r,r+1));return n?r+n[0].length:-1}function t9(e,t,r){var n=nt.exec(t.slice(r));return n?(e.Q=+n[0],r+n[0].length):-1}function r9(e,t,r){var n=nt.exec(t.slice(r));return n?(e.s=+n[0],r+n[0].length):-1}function cb(e,t){return ue(e.getDate(),t,2)}function n9(e,t){return ue(e.getHours(),t,2)}function i9(e,t){return ue(e.getHours()%12||12,t,2)}function a9(e,t){return ue(1+gl.count(tn(e),e),t,3)}function j_(e,t){return ue(e.getMilliseconds(),t,3)}function o9(e,t){return j_(e,t)+"000"}function s9(e,t){return ue(e.getMonth()+1,t,2)}function l9(e,t){return ue(e.getMinutes(),t,2)}function u9(e,t){return ue(e.getSeconds(),t,2)}function c9(e){var t=e.getDay();return t===0?7:t}function f9(e,t){return ue(Df.count(tn(e)-1,e),t,2)}function S_(e){var t=e.getDay();return t>=4||t===0?$a(e):$a.ceil(e)}function d9(e,t){return e=S_(e),ue($a.count(tn(e),e)+(tn(e).getDay()===4),t,2)}function p9(e){return e.getDay()}function h9(e,t){return ue(fc.count(tn(e)-1,e),t,2)}function m9(e,t){return ue(e.getFullYear()%100,t,2)}function v9(e,t){return e=S_(e),ue(e.getFullYear()%100,t,2)}function y9(e,t){return ue(e.getFullYear()%1e4,t,4)}function g9(e,t){var r=e.getDay();return e=r>=4||r===0?$a(e):$a.ceil(e),ue(e.getFullYear()%1e4,t,4)}function x9(e){var t=e.getTimezoneOffset();return(t>0?"-":(t*=-1,"+"))+ue(t/60|0,"0",2)+ue(t%60,"0",2)}function fb(e,t){return ue(e.getUTCDate(),t,2)}function b9(e,t){return ue(e.getUTCHours(),t,2)}function w9(e,t){return ue(e.getUTCHours()%12||12,t,2)}function j9(e,t){return ue(1+Lf.count(rn(e),e),t,3)}function O_(e,t){return ue(e.getUTCMilliseconds(),t,3)}function S9(e,t){return O_(e,t)+"000"}function O9(e,t){return ue(e.getUTCMonth()+1,t,2)}function _9(e,t){return ue(e.getUTCMinutes(),t,2)}function P9(e,t){return ue(e.getUTCSeconds(),t,2)}function k9(e){var t=e.getUTCDay();return t===0?7:t}function A9(e,t){return ue(Rf.count(rn(e)-1,e),t,2)}function __(e){var t=e.getUTCDay();return t>=4||t===0?Ea(e):Ea.ceil(e)}function N9(e,t){return e=__(e),ue(Ea.count(rn(e),e)+(rn(e).getUTCDay()===4),t,2)}function $9(e){return e.getUTCDay()}function E9(e,t){return ue(dc.count(rn(e)-1,e),t,2)}function T9(e,t){return ue(e.getUTCFullYear()%100,t,2)}function C9(e,t){return e=__(e),ue(e.getUTCFullYear()%100,t,2)}function M9(e,t){return ue(e.getUTCFullYear()%1e4,t,4)}function I9(e,t){var r=e.getUTCDay();return e=r>=4||r===0?Ea(e):Ea.ceil(e),ue(e.getUTCFullYear()%1e4,t,4)}function L9(){return"+0000"}function db(){return"%"}function pb(e){return+e}function hb(e){return Math.floor(+e/1e3)}var zi,P_,k_;D9({dateTime:"%x, %X",date:"%-m/%-d/%Y",time:"%-I:%M:%S %p",periods:["AM","PM"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]});function D9(e){return zi=Dz(e),P_=zi.format,zi.parse,k_=zi.utcFormat,zi.utcParse,zi}function R9(e){return new Date(e)}function B9(e){return e instanceof Date?+e:+new Date(+e)}function _y(e,t,r,n,i,a,o,s,l,u){var f=fy(),d=f.invert,p=f.domain,h=u(".%L"),m=u(":%S"),g=u("%I:%M"),x=u("%I %p"),y=u("%a %d"),v=u("%b %d"),b=u("%B"),S=u("%Y");function w(j){return(l(j)<j?h:s(j)<j?m:o(j)<j?g:a(j)<j?x:n(j)<j?i(j)<j?y:v:r(j)<j?b:S)(j)}return f.invert=function(j){return new Date(d(j))},f.domain=function(j){return arguments.length?p(Array.from(j,B9)):p().map(R9)},f.ticks=function(j){var O=p();return e(O[0],O[O.length-1],j??10)},f.tickFormat=function(j,O){return O==null?w:u(O)},f.nice=function(j){var O=p();return(!j||typeof j.range!="function")&&(j=t(O[0],O[O.length-1],j??10)),j?p(p_(O,j)):f},f.copy=function(){return yl(f,_y(e,t,r,n,i,a,o,s,l,u))},f}function F9(){return lr.apply(_y(Iz,Lz,tn,Sy,Df,gl,wy,xy,pi,P_).domain([new Date(2e3,0,1),new Date(2e3,0,2)]),arguments)}function z9(){return lr.apply(_y(Cz,Mz,rn,Oy,Rf,Lf,jy,by,pi,k_).domain([Date.UTC(2e3,0,1),Date.UTC(2e3,0,2)]),arguments)}function Bf(){var e=0,t=1,r,n,i,a,o=xt,s=!1,l;function u(d){return d==null||isNaN(d=+d)?l:o(i===0?.5:(d=(a(d)-r)*i,s?Math.max(0,Math.min(1,d)):d))}u.domain=function(d){return arguments.length?([e,t]=d,r=a(e=+e),n=a(t=+t),i=r===n?0:1/(n-r),u):[e,t]},u.clamp=function(d){return arguments.length?(s=!!d,u):s},u.interpolator=function(d){return arguments.length?(o=d,u):o};function f(d){return function(p){var h,m;return arguments.length?([h,m]=p,o=d(h,m),u):[o(0),o(1)]}}return u.range=f(po),u.rangeRound=f(cy),u.unknown=function(d){return arguments.length?(l=d,u):l},function(d){return a=d,r=d(e),n=d(t),i=r===n?0:1/(n-r),u}}function qn(e,t){return t.domain(e.domain()).interpolator(e.interpolator()).clamp(e.clamp()).unknown(e.unknown())}function A_(){var e=Yn(Bf()(xt));return e.copy=function(){return qn(e,A_())},ln.apply(e,arguments)}function N_(){var e=hy(Bf()).domain([1,10]);return e.copy=function(){return qn(e,N_()).base(e.base())},ln.apply(e,arguments)}function $_(){var e=my(Bf());return e.copy=function(){return qn(e,$_()).constant(e.constant())},ln.apply(e,arguments)}function Py(){var e=vy(Bf());return e.copy=function(){return qn(e,Py()).exponent(e.exponent())},ln.apply(e,arguments)}function W9(){return Py.apply(null,arguments).exponent(.5)}function E_(){var e=[],t=xt;function r(n){if(n!=null&&!isNaN(n=+n))return t((ml(e,n,1)-1)/(e.length-1))}return r.domain=function(n){if(!arguments.length)return e.slice();e=[];for(let i of n)i!=null&&!isNaN(i=+i)&&e.push(i);return e.sort(In),r},r.interpolator=function(n){return arguments.length?(t=n,r):t},r.range=function(){return e.map((n,i)=>t(i/(e.length-1)))},r.quantiles=function(n){return Array.from({length:n+1},(i,a)=>AF(e,a/n))},r.copy=function(){return E_(t).domain(e)},ln.apply(r,arguments)}function Ff(){var e=0,t=.5,r=1,n=1,i,a,o,s,l,u=xt,f,d=!1,p;function h(g){return isNaN(g=+g)?p:(g=.5+((g=+f(g))-a)*(n*g<n*a?s:l),u(d?Math.max(0,Math.min(1,g)):g))}h.domain=function(g){return arguments.length?([e,t,r]=g,i=f(e=+e),a=f(t=+t),o=f(r=+r),s=i===a?0:.5/(a-i),l=a===o?0:.5/(o-a),n=a<i?-1:1,h):[e,t,r]},h.clamp=function(g){return arguments.length?(d=!!g,h):d},h.interpolator=function(g){return arguments.length?(u=g,h):u};function m(g){return function(x){var y,v,b;return arguments.length?([y,v,b]=x,u=ez(g,[y,v,b]),h):[u(0),u(.5),u(1)]}}return h.range=m(po),h.rangeRound=m(cy),h.unknown=function(g){return arguments.length?(p=g,h):p},function(g){return f=g,i=g(e),a=g(t),o=g(r),s=i===a?0:.5/(a-i),l=a===o?0:.5/(o-a),n=a<i?-1:1,h}}function T_(){var e=Yn(Ff()(xt));return e.copy=function(){return qn(e,T_())},ln.apply(e,arguments)}function C_(){var e=hy(Ff()).domain([.1,1,10]);return e.copy=function(){return qn(e,C_()).base(e.base())},ln.apply(e,arguments)}function M_(){var e=my(Ff());return e.copy=function(){return qn(e,M_()).constant(e.constant())},ln.apply(e,arguments)}function ky(){var e=vy(Ff());return e.copy=function(){return qn(e,ky()).exponent(e.exponent())},ln.apply(e,arguments)}function U9(){return ky.apply(null,arguments).exponent(.5)}const mb=Object.freeze(Object.defineProperty({__proto__:null,scaleBand:Es,scaleDiverging:T_,scaleDivergingLog:C_,scaleDivergingPow:ky,scaleDivergingSqrt:U9,scaleDivergingSymlog:M_,scaleIdentity:d_,scaleImplicit:Dh,scaleLinear:uc,scaleLog:h_,scaleOrdinal:sy,scalePoint:Qo,scalePow:yy,scaleQuantile:y_,scaleQuantize:g_,scaleRadial:v_,scaleSequential:A_,scaleSequentialLog:N_,scaleSequentialPow:Py,scaleSequentialQuantile:E_,scaleSequentialSqrt:W9,scaleSequentialSymlog:$_,scaleSqrt:Sz,scaleSymlog:m_,scaleThreshold:x_,scaleTime:F9,scaleUtc:z9,tickFormat:f_},Symbol.toStringTag,{value:"Module"}));var K9=no;function H9(e,t,r){for(var n=-1,i=e.length;++n<i;){var a=e[n],o=t(a);if(o!=null&&(s===void 0?o===o&&!K9(o):r(o,s)))var s=o,l=a}return l}var zf=H9;function V9(e,t){return e>t}var I_=V9,G9=zf,Y9=I_,q9=fo;function X9(e){return e&&e.length?G9(e,q9,Y9):void 0}var Q9=X9;const jn=de(Q9);function Z9(e,t){return e<t}var L_=Z9,J9=zf,e7=L_,t7=fo;function r7(e){return e&&e.length?J9(e,t7,e7):void 0}var n7=r7;const Wf=de(n7);var i7=Wv,a7=Lr,o7=HO,s7=Ct;function l7(e,t){var r=s7(e)?i7:o7;return r(e,a7(t))}var u7=l7,c7=UO,f7=u7;function d7(e,t){return c7(f7(e,t),1)}var p7=d7;const h7=de(p7);var m7=ry;function v7(e,t){return m7(e,t)}var y7=v7;const Fn=de(y7);var ho=1e9,g7={precision:20,rounding:4,toExpNeg:-7,toExpPos:21,LN10:"2.302585092994045684017991454684364207601101488628772976033327900967572609677352480235997205089598298341967784042286"},Ny,Ae=!0,ar="[DecimalError] ",xi=ar+"Invalid argument: ",Ay=ar+"Exponent out of range: ",mo=Math.floor,oi=Math.pow,x7=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,Bt,Ze=1e7,je=7,D_=9007199254740991,pc=mo(D_/je),Y={};Y.absoluteValue=Y.abs=function(){var e=new this.constructor(this);return e.s&&(e.s=1),e};Y.comparedTo=Y.cmp=function(e){var t,r,n,i,a=this;if(e=new a.constructor(e),a.s!==e.s)return a.s||-e.s;if(a.e!==e.e)return a.e>e.e^a.s<0?1:-1;for(n=a.d.length,i=e.d.length,t=0,r=n<i?n:i;t<r;++t)if(a.d[t]!==e.d[t])return a.d[t]>e.d[t]^a.s<0?1:-1;return n===i?0:n>i^a.s<0?1:-1};Y.decimalPlaces=Y.dp=function(){var e=this,t=e.d.length-1,r=(t-e.e)*je;if(t=e.d[t],t)for(;t%10==0;t/=10)r--;return r<0?0:r};Y.dividedBy=Y.div=function(e){return qr(this,new this.constructor(e))};Y.dividedToIntegerBy=Y.idiv=function(e){var t=this,r=t.constructor;return me(qr(t,new r(e),0,1),r.precision)};Y.equals=Y.eq=function(e){return!this.cmp(e)};Y.exponent=function(){return Ue(this)};Y.greaterThan=Y.gt=function(e){return this.cmp(e)>0};Y.greaterThanOrEqualTo=Y.gte=function(e){return this.cmp(e)>=0};Y.isInteger=Y.isint=function(){return this.e>this.d.length-2};Y.isNegative=Y.isneg=function(){return this.s<0};Y.isPositive=Y.ispos=function(){return this.s>0};Y.isZero=function(){return this.s===0};Y.lessThan=Y.lt=function(e){return this.cmp(e)<0};Y.lessThanOrEqualTo=Y.lte=function(e){return this.cmp(e)<1};Y.logarithm=Y.log=function(e){var t,r=this,n=r.constructor,i=n.precision,a=i+5;if(e===void 0)e=new n(10);else if(e=new n(e),e.s<1||e.eq(Bt))throw Error(ar+"NaN");if(r.s<1)throw Error(ar+(r.s?"NaN":"-Infinity"));return r.eq(Bt)?new n(0):(Ae=!1,t=qr(Ls(r,a),Ls(e,a),a),Ae=!0,me(t,i))};Y.minus=Y.sub=function(e){var t=this;return e=new t.constructor(e),t.s==e.s?F_(t,e):R_(t,(e.s=-e.s,e))};Y.modulo=Y.mod=function(e){var t,r=this,n=r.constructor,i=n.precision;if(e=new n(e),!e.s)throw Error(ar+"NaN");return r.s?(Ae=!1,t=qr(r,e,0,1).times(e),Ae=!0,r.minus(t)):me(new n(r),i)};Y.naturalExponential=Y.exp=function(){return B_(this)};Y.naturalLogarithm=Y.ln=function(){return Ls(this)};Y.negated=Y.neg=function(){var e=new this.constructor(this);return e.s=-e.s||0,e};Y.plus=Y.add=function(e){var t=this;return e=new t.constructor(e),t.s==e.s?R_(t,e):F_(t,(e.s=-e.s,e))};Y.precision=Y.sd=function(e){var t,r,n,i=this;if(e!==void 0&&e!==!!e&&e!==1&&e!==0)throw Error(xi+e);if(t=Ue(i)+1,n=i.d.length-1,r=n*je+1,n=i.d[n],n){for(;n%10==0;n/=10)r--;for(n=i.d[0];n>=10;n/=10)r++}return e&&t>r?t:r};Y.squareRoot=Y.sqrt=function(){var e,t,r,n,i,a,o,s=this,l=s.constructor;if(s.s<1){if(!s.s)return new l(0);throw Error(ar+"NaN")}for(e=Ue(s),Ae=!1,i=Math.sqrt(+s),i==0||i==1/0?(t=Ar(s.d),(t.length+e)%2==0&&(t+="0"),i=Math.sqrt(t),e=mo((e+1)/2)-(e<0||e%2),i==1/0?t="5e"+e:(t=i.toExponential(),t=t.slice(0,t.indexOf("e")+1)+e),n=new l(t)):n=new l(i.toString()),r=l.precision,i=o=r+3;;)if(a=n,n=a.plus(qr(s,a,o+2)).times(.5),Ar(a.d).slice(0,o)===(t=Ar(n.d)).slice(0,o)){if(t=t.slice(o-3,o+1),i==o&&t=="4999"){if(me(a,r+1,0),a.times(a).eq(s)){n=a;break}}else if(t!="9999")break;o+=4}return Ae=!0,me(n,r)};Y.times=Y.mul=function(e){var t,r,n,i,a,o,s,l,u,f=this,d=f.constructor,p=f.d,h=(e=new d(e)).d;if(!f.s||!e.s)return new d(0);for(e.s*=f.s,r=f.e+e.e,l=p.length,u=h.length,l<u&&(a=p,p=h,h=a,o=l,l=u,u=o),a=[],o=l+u,n=o;n--;)a.push(0);for(n=u;--n>=0;){for(t=0,i=l+n;i>n;)s=a[i]+h[n]*p[i-n-1]+t,a[i--]=s%Ze|0,t=s/Ze|0;a[i]=(a[i]+t)%Ze|0}for(;!a[--o];)a.pop();return t?++r:a.shift(),e.d=a,e.e=r,Ae?me(e,d.precision):e};Y.toDecimalPlaces=Y.todp=function(e,t){var r=this,n=r.constructor;return r=new n(r),e===void 0?r:(Mr(e,0,ho),t===void 0?t=n.rounding:Mr(t,0,8),me(r,e+Ue(r)+1,t))};Y.toExponential=function(e,t){var r,n=this,i=n.constructor;return e===void 0?r=Ai(n,!0):(Mr(e,0,ho),t===void 0?t=i.rounding:Mr(t,0,8),n=me(new i(n),e+1,t),r=Ai(n,!0,e+1)),r};Y.toFixed=function(e,t){var r,n,i=this,a=i.constructor;return e===void 0?Ai(i):(Mr(e,0,ho),t===void 0?t=a.rounding:Mr(t,0,8),n=me(new a(i),e+Ue(i)+1,t),r=Ai(n.abs(),!1,e+Ue(n)+1),i.isneg()&&!i.isZero()?"-"+r:r)};Y.toInteger=Y.toint=function(){var e=this,t=e.constructor;return me(new t(e),Ue(e)+1,t.rounding)};Y.toNumber=function(){return+this};Y.toPower=Y.pow=function(e){var t,r,n,i,a,o,s=this,l=s.constructor,u=12,f=+(e=new l(e));if(!e.s)return new l(Bt);if(s=new l(s),!s.s){if(e.s<1)throw Error(ar+"Infinity");return s}if(s.eq(Bt))return s;if(n=l.precision,e.eq(Bt))return me(s,n);if(t=e.e,r=e.d.length-1,o=t>=r,a=s.s,o){if((r=f<0?-f:f)<=D_){for(i=new l(Bt),t=Math.ceil(n/je+4),Ae=!1;r%2&&(i=i.times(s),yb(i.d,t)),r=mo(r/2),r!==0;)s=s.times(s),yb(s.d,t);return Ae=!0,e.s<0?new l(Bt).div(i):me(i,n)}}else if(a<0)throw Error(ar+"NaN");return a=a<0&&e.d[Math.max(t,r)]&1?-1:1,s.s=1,Ae=!1,i=e.times(Ls(s,n+u)),Ae=!0,i=B_(i),i.s=a,i};Y.toPrecision=function(e,t){var r,n,i=this,a=i.constructor;return e===void 0?(r=Ue(i),n=Ai(i,r<=a.toExpNeg||r>=a.toExpPos)):(Mr(e,1,ho),t===void 0?t=a.rounding:Mr(t,0,8),i=me(new a(i),e,t),r=Ue(i),n=Ai(i,e<=r||r<=a.toExpNeg,e)),n};Y.toSignificantDigits=Y.tosd=function(e,t){var r=this,n=r.constructor;return e===void 0?(e=n.precision,t=n.rounding):(Mr(e,1,ho),t===void 0?t=n.rounding:Mr(t,0,8)),me(new n(r),e,t)};Y.toString=Y.valueOf=Y.val=Y.toJSON=Y[Symbol.for("nodejs.util.inspect.custom")]=function(){var e=this,t=Ue(e),r=e.constructor;return Ai(e,t<=r.toExpNeg||t>=r.toExpPos)};function R_(e,t){var r,n,i,a,o,s,l,u,f=e.constructor,d=f.precision;if(!e.s||!t.s)return t.s||(t=new f(e)),Ae?me(t,d):t;if(l=e.d,u=t.d,o=e.e,i=t.e,l=l.slice(),a=o-i,a){for(a<0?(n=l,a=-a,s=u.length):(n=u,i=o,s=l.length),o=Math.ceil(d/je),s=o>s?o+1:s+1,a>s&&(a=s,n.length=1),n.reverse();a--;)n.push(0);n.reverse()}for(s=l.length,a=u.length,s-a<0&&(a=s,n=u,u=l,l=n),r=0;a;)r=(l[--a]=l[a]+u[a]+r)/Ze|0,l[a]%=Ze;for(r&&(l.unshift(r),++i),s=l.length;l[--s]==0;)l.pop();return t.d=l,t.e=i,Ae?me(t,d):t}function Mr(e,t,r){if(e!==~~e||e<t||e>r)throw Error(xi+e)}function Ar(e){var t,r,n,i=e.length-1,a="",o=e[0];if(i>0){for(a+=o,t=1;t<i;t++)n=e[t]+"",r=je-n.length,r&&(a+=mn(r)),a+=n;o=e[t],n=o+"",r=je-n.length,r&&(a+=mn(r))}else if(o===0)return"0";for(;o%10===0;)o/=10;return a+o}var qr=function(){function e(n,i){var a,o=0,s=n.length;for(n=n.slice();s--;)a=n[s]*i+o,n[s]=a%Ze|0,o=a/Ze|0;return o&&n.unshift(o),n}function t(n,i,a,o){var s,l;if(a!=o)l=a>o?1:-1;else for(s=l=0;s<a;s++)if(n[s]!=i[s]){l=n[s]>i[s]?1:-1;break}return l}function r(n,i,a){for(var o=0;a--;)n[a]-=o,o=n[a]<i[a]?1:0,n[a]=o*Ze+n[a]-i[a];for(;!n[0]&&n.length>1;)n.shift()}return function(n,i,a,o){var s,l,u,f,d,p,h,m,g,x,y,v,b,S,w,j,O,_,P=n.constructor,N=n.s==i.s?1:-1,T=n.d,$=i.d;if(!n.s)return new P(n);if(!i.s)throw Error(ar+"Division by zero");for(l=n.e-i.e,O=$.length,w=T.length,h=new P(N),m=h.d=[],u=0;$[u]==(T[u]||0);)++u;if($[u]>(T[u]||0)&&--l,a==null?v=a=P.precision:o?v=a+(Ue(n)-Ue(i))+1:v=a,v<0)return new P(0);if(v=v/je+2|0,u=0,O==1)for(f=0,$=$[0],v++;(u<w||f)&&v--;u++)b=f*Ze+(T[u]||0),m[u]=b/$|0,f=b%$|0;else{for(f=Ze/($[0]+1)|0,f>1&&($=e($,f),T=e(T,f),O=$.length,w=T.length),S=O,g=T.slice(0,O),x=g.length;x<O;)g[x++]=0;_=$.slice(),_.unshift(0),j=$[0],$[1]>=Ze/2&&++j;do f=0,s=t($,g,O,x),s<0?(y=g[0],O!=x&&(y=y*Ze+(g[1]||0)),f=y/j|0,f>1?(f>=Ze&&(f=Ze-1),d=e($,f),p=d.length,x=g.length,s=t(d,g,p,x),s==1&&(f--,r(d,O<p?_:$,p))):(f==0&&(s=f=1),d=$.slice()),p=d.length,p<x&&d.unshift(0),r(g,d,x),s==-1&&(x=g.length,s=t($,g,O,x),s<1&&(f++,r(g,O<x?_:$,x))),x=g.length):s===0&&(f++,g=[0]),m[u++]=f,s&&g[0]?g[x++]=T[S]||0:(g=[T[S]],x=1);while((S++<w||g[0]!==void 0)&&v--)}return m[0]||m.shift(),h.e=l,me(h,o?a+Ue(h)+1:a)}}();function B_(e,t){var r,n,i,a,o,s,l=0,u=0,f=e.constructor,d=f.precision;if(Ue(e)>16)throw Error(Ay+Ue(e));if(!e.s)return new f(Bt);for(Ae=!1,s=d,o=new f(.03125);e.abs().gte(.1);)e=e.times(o),u+=5;for(n=Math.log(oi(2,u))/Math.LN10*2+5|0,s+=n,r=i=a=new f(Bt),f.precision=s;;){if(i=me(i.times(e),s),r=r.times(++l),o=a.plus(qr(i,r,s)),Ar(o.d).slice(0,s)===Ar(a.d).slice(0,s)){for(;u--;)a=me(a.times(a),s);return f.precision=d,t==null?(Ae=!0,me(a,d)):a}a=o}}function Ue(e){for(var t=e.e*je,r=e.d[0];r>=10;r/=10)t++;return t}function Zd(e,t,r){if(t>e.LN10.sd())throw Ae=!0,r&&(e.precision=r),Error(ar+"LN10 precision limit exceeded");return me(new e(e.LN10),t)}function mn(e){for(var t="";e--;)t+="0";return t}function Ls(e,t){var r,n,i,a,o,s,l,u,f,d=1,p=10,h=e,m=h.d,g=h.constructor,x=g.precision;if(h.s<1)throw Error(ar+(h.s?"NaN":"-Infinity"));if(h.eq(Bt))return new g(0);if(t==null?(Ae=!1,u=x):u=t,h.eq(10))return t==null&&(Ae=!0),Zd(g,u);if(u+=p,g.precision=u,r=Ar(m),n=r.charAt(0),a=Ue(h),Math.abs(a)<15e14){for(;n<7&&n!=1||n==1&&r.charAt(1)>3;)h=h.times(e),r=Ar(h.d),n=r.charAt(0),d++;a=Ue(h),n>1?(h=new g("0."+r),a++):h=new g(n+"."+r.slice(1))}else return l=Zd(g,u+2,x).times(a+""),h=Ls(new g(n+"."+r.slice(1)),u-p).plus(l),g.precision=x,t==null?(Ae=!0,me(h,x)):h;for(s=o=h=qr(h.minus(Bt),h.plus(Bt),u),f=me(h.times(h),u),i=3;;){if(o=me(o.times(f),u),l=s.plus(qr(o,new g(i),u)),Ar(l.d).slice(0,u)===Ar(s.d).slice(0,u))return s=s.times(2),a!==0&&(s=s.plus(Zd(g,u+2,x).times(a+""))),s=qr(s,new g(d),u),g.precision=x,t==null?(Ae=!0,me(s,x)):s;s=l,i+=2}}function vb(e,t){var r,n,i;for((r=t.indexOf("."))>-1&&(t=t.replace(".","")),(n=t.search(/e/i))>0?(r<0&&(r=n),r+=+t.slice(n+1),t=t.substring(0,n)):r<0&&(r=t.length),n=0;t.charCodeAt(n)===48;)++n;for(i=t.length;t.charCodeAt(i-1)===48;)--i;if(t=t.slice(n,i),t){if(i-=n,r=r-n-1,e.e=mo(r/je),e.d=[],n=(r+1)%je,r<0&&(n+=je),n<i){for(n&&e.d.push(+t.slice(0,n)),i-=je;n<i;)e.d.push(+t.slice(n,n+=je));t=t.slice(n),n=je-t.length}else n-=i;for(;n--;)t+="0";if(e.d.push(+t),Ae&&(e.e>pc||e.e<-pc))throw Error(Ay+r)}else e.s=0,e.e=0,e.d=[0];return e}function me(e,t,r){var n,i,a,o,s,l,u,f,d=e.d;for(o=1,a=d[0];a>=10;a/=10)o++;if(n=t-o,n<0)n+=je,i=t,u=d[f=0];else{if(f=Math.ceil((n+1)/je),a=d.length,f>=a)return e;for(u=a=d[f],o=1;a>=10;a/=10)o++;n%=je,i=n-je+o}if(r!==void 0&&(a=oi(10,o-i-1),s=u/a%10|0,l=t<0||d[f+1]!==void 0||u%a,l=r<4?(s||l)&&(r==0||r==(e.s<0?3:2)):s>5||s==5&&(r==4||l||r==6&&(n>0?i>0?u/oi(10,o-i):0:d[f-1])%10&1||r==(e.s<0?8:7))),t<1||!d[0])return l?(a=Ue(e),d.length=1,t=t-a-1,d[0]=oi(10,(je-t%je)%je),e.e=mo(-t/je)||0):(d.length=1,d[0]=e.e=e.s=0),e;if(n==0?(d.length=f,a=1,f--):(d.length=f+1,a=oi(10,je-n),d[f]=i>0?(u/oi(10,o-i)%oi(10,i)|0)*a:0),l)for(;;)if(f==0){(d[0]+=a)==Ze&&(d[0]=1,++e.e);break}else{if(d[f]+=a,d[f]!=Ze)break;d[f--]=0,a=1}for(n=d.length;d[--n]===0;)d.pop();if(Ae&&(e.e>pc||e.e<-pc))throw Error(Ay+Ue(e));return e}function F_(e,t){var r,n,i,a,o,s,l,u,f,d,p=e.constructor,h=p.precision;if(!e.s||!t.s)return t.s?t.s=-t.s:t=new p(e),Ae?me(t,h):t;if(l=e.d,d=t.d,n=t.e,u=e.e,l=l.slice(),o=u-n,o){for(f=o<0,f?(r=l,o=-o,s=d.length):(r=d,n=u,s=l.length),i=Math.max(Math.ceil(h/je),s)+2,o>i&&(o=i,r.length=1),r.reverse(),i=o;i--;)r.push(0);r.reverse()}else{for(i=l.length,s=d.length,f=i<s,f&&(s=i),i=0;i<s;i++)if(l[i]!=d[i]){f=l[i]<d[i];break}o=0}for(f&&(r=l,l=d,d=r,t.s=-t.s),s=l.length,i=d.length-s;i>0;--i)l[s++]=0;for(i=d.length;i>o;){if(l[--i]<d[i]){for(a=i;a&&l[--a]===0;)l[a]=Ze-1;--l[a],l[i]+=Ze}l[i]-=d[i]}for(;l[--s]===0;)l.pop();for(;l[0]===0;l.shift())--n;return l[0]?(t.d=l,t.e=n,Ae?me(t,h):t):new p(0)}function Ai(e,t,r){var n,i=Ue(e),a=Ar(e.d),o=a.length;return t?(r&&(n=r-o)>0?a=a.charAt(0)+"."+a.slice(1)+mn(n):o>1&&(a=a.charAt(0)+"."+a.slice(1)),a=a+(i<0?"e":"e+")+i):i<0?(a="0."+mn(-i-1)+a,r&&(n=r-o)>0&&(a+=mn(n))):i>=o?(a+=mn(i+1-o),r&&(n=r-i-1)>0&&(a=a+"."+mn(n))):((n=i+1)<o&&(a=a.slice(0,n)+"."+a.slice(n)),r&&(n=r-o)>0&&(i+1===o&&(a+="."),a+=mn(n))),e.s<0?"-"+a:a}function yb(e,t){if(e.length>t)return e.length=t,!0}function z_(e){var t,r,n;function i(a){var o=this;if(!(o instanceof i))return new i(a);if(o.constructor=i,a instanceof i){o.s=a.s,o.e=a.e,o.d=(a=a.d)?a.slice():a;return}if(typeof a=="number"){if(a*0!==0)throw Error(xi+a);if(a>0)o.s=1;else if(a<0)a=-a,o.s=-1;else{o.s=0,o.e=0,o.d=[0];return}if(a===~~a&&a<1e7){o.e=0,o.d=[a];return}return vb(o,a.toString())}else if(typeof a!="string")throw Error(xi+a);if(a.charCodeAt(0)===45?(a=a.slice(1),o.s=-1):o.s=1,x7.test(a))vb(o,a);else throw Error(xi+a)}if(i.prototype=Y,i.ROUND_UP=0,i.ROUND_DOWN=1,i.ROUND_CEIL=2,i.ROUND_FLOOR=3,i.ROUND_HALF_UP=4,i.ROUND_HALF_DOWN=5,i.ROUND_HALF_EVEN=6,i.ROUND_HALF_CEIL=7,i.ROUND_HALF_FLOOR=8,i.clone=z_,i.config=i.set=b7,e===void 0&&(e={}),e)for(n=["precision","rounding","toExpNeg","toExpPos","LN10"],t=0;t<n.length;)e.hasOwnProperty(r=n[t++])||(e[r]=this[r]);return i.config(e),i}function b7(e){if(!e||typeof e!="object")throw Error(ar+"Object expected");var t,r,n,i=["precision",1,ho,"rounding",0,8,"toExpNeg",-1/0,0,"toExpPos",0,1/0];for(t=0;t<i.length;t+=3)if((n=e[r=i[t]])!==void 0)if(mo(n)===n&&n>=i[t+1]&&n<=i[t+2])this[r]=n;else throw Error(xi+r+": "+n);if((n=e[r="LN10"])!==void 0)if(n==Math.LN10)this[r]=new this(n);else throw Error(xi+r+": "+n);return this}var Ny=z_(g7);Bt=new Ny(1);const he=Ny;function w7(e){return _7(e)||O7(e)||S7(e)||j7()}function j7(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
-In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function S7(e,t){if(e){if(typeof e=="string")return zh(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return zh(e,t)}}function O7(e){if(typeof Symbol<"u"&&Symbol.iterator in Object(e))return Array.from(e)}function _7(e){if(Array.isArray(e))return zh(e)}function zh(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}var P7=function(t){return t},W_={},U_=function(t){return t===W_},gb=function(t){return function r(){return arguments.length===0||arguments.length===1&&U_(arguments.length<=0?void 0:arguments[0])?r:t.apply(void 0,arguments)}},k7=function e(t,r){return t===1?r:gb(function(){for(var n=arguments.length,i=new Array(n),a=0;a<n;a++)i[a]=arguments[a];var o=i.filter(function(s){return s!==W_}).length;return o>=t?r.apply(void 0,i):e(t-o,gb(function(){for(var s=arguments.length,l=new Array(s),u=0;u<s;u++)l[u]=arguments[u];var f=i.map(function(d){return U_(d)?l.shift():d});return r.apply(void 0,w7(f).concat(l))}))})},Uf=function(t){return k7(t.length,t)},Wh=function(t,r){for(var n=[],i=t;i<r;++i)n[i-t]=i;return n},A7=Uf(function(e,t){return Array.isArray(t)?t.map(e):Object.keys(t).map(function(r){return t[r]}).map(e)}),N7=function(){for(var t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];if(!r.length)return P7;var i=r.reverse(),a=i[0],o=i.slice(1);return function(){return o.reduce(function(s,l){return l(s)},a.apply(void 0,arguments))}},Uh=function(t){return Array.isArray(t)?t.reverse():t.split("").reverse.join("")},K_=function(t){var r=null,n=null;return function(){for(var i=arguments.length,a=new Array(i),o=0;o<i;o++)a[o]=arguments[o];return r&&a.every(function(s,l){return s===r[l]})||(r=a,n=t.apply(void 0,a)),n}};function $7(e){var t;return e===0?t=1:t=Math.floor(new he(e).abs().log(10).toNumber())+1,t}function E7(e,t,r){for(var n=new he(e),i=0,a=[];n.lt(t)&&i<1e5;)a.push(n.toNumber()),n=n.add(r),i++;return a}var T7=Uf(function(e,t,r){var n=+e,i=+t;return n+r*(i-n)}),C7=Uf(function(e,t,r){var n=t-+e;return n=n||1/0,(r-e)/n}),M7=Uf(function(e,t,r){var n=t-+e;return n=n||1/0,Math.max(0,Math.min(1,(r-e)/n))});const Kf={rangeStep:E7,getDigitCount:$7,interpolateNumber:T7,uninterpolateNumber:C7,uninterpolateTruncation:M7};function Kh(e){return D7(e)||L7(e)||H_(e)||I7()}function I7(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
-In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function L7(e){if(typeof Symbol<"u"&&Symbol.iterator in Object(e))return Array.from(e)}function D7(e){if(Array.isArray(e))return Hh(e)}function Ds(e,t){return F7(e)||B7(e,t)||H_(e,t)||R7()}function R7(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
-In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function H_(e,t){if(e){if(typeof e=="string")return Hh(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return Hh(e,t)}}function Hh(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function B7(e,t){if(!(typeof Symbol>"u"||!(Symbol.iterator in Object(e)))){var r=[],n=!0,i=!1,a=void 0;try{for(var o=e[Symbol.iterator](),s;!(n=(s=o.next()).done)&&(r.push(s.value),!(t&&r.length===t));n=!0);}catch(l){i=!0,a=l}finally{try{!n&&o.return!=null&&o.return()}finally{if(i)throw a}}return r}}function F7(e){if(Array.isArray(e))return e}function V_(e){var t=Ds(e,2),r=t[0],n=t[1],i=r,a=n;return r>n&&(i=n,a=r),[i,a]}function G_(e,t,r){if(e.lte(0))return new he(0);var n=Kf.getDigitCount(e.toNumber()),i=new he(10).pow(n),a=e.div(i),o=n!==1?.05:.1,s=new he(Math.ceil(a.div(o).toNumber())).add(r).mul(o),l=s.mul(i);return t?l:new he(Math.ceil(l))}function z7(e,t,r){var n=1,i=new he(e);if(!i.isint()&&r){var a=Math.abs(e);a<1?(n=new he(10).pow(Kf.getDigitCount(e)-1),i=new he(Math.floor(i.div(n).toNumber())).mul(n)):a>1&&(i=new he(Math.floor(e)))}else e===0?i=new he(Math.floor((t-1)/2)):r||(i=new he(Math.floor(e)));var o=Math.floor((t-1)/2),s=N7(A7(function(l){return i.add(new he(l-o).mul(n)).toNumber()}),Wh);return s(0,t)}function Y_(e,t,r,n){var i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:0;if(!Number.isFinite((t-e)/(r-1)))return{step:new he(0),tickMin:new he(0),tickMax:new he(0)};var a=G_(new he(t).sub(e).div(r-1),n,i),o;e<=0&&t>=0?o=new he(0):(o=new he(e).add(t).div(2),o=o.sub(new he(o).mod(a)));var s=Math.ceil(o.sub(e).div(a).toNumber()),l=Math.ceil(new he(t).sub(o).div(a).toNumber()),u=s+l+1;return u>r?Y_(e,t,r,n,i+1):(u<r&&(l=t>0?l+(r-u):l,s=t>0?s:s+(r-u)),{step:a,tickMin:o.sub(new he(s).mul(a)),tickMax:o.add(new he(l).mul(a))})}function W7(e){var t=Ds(e,2),r=t[0],n=t[1],i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:6,a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,o=Math.max(i,2),s=V_([r,n]),l=Ds(s,2),u=l[0],f=l[1];if(u===-1/0||f===1/0){var d=f===1/0?[u].concat(Kh(Wh(0,i-1).map(function(){return 1/0}))):[].concat(Kh(Wh(0,i-1).map(function(){return-1/0})),[f]);return r>n?Uh(d):d}if(u===f)return z7(u,i,a);var p=Y_(u,f,o,a),h=p.step,m=p.tickMin,g=p.tickMax,x=Kf.rangeStep(m,g.add(new he(.1).mul(h)),h);return r>n?Uh(x):x}function U7(e,t){var r=Ds(e,2),n=r[0],i=r[1],a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,o=V_([n,i]),s=Ds(o,2),l=s[0],u=s[1];if(l===-1/0||u===1/0)return[n,i];if(l===u)return[l];var f=Math.max(t,2),d=G_(new he(u).sub(l).div(f-1),a,0),p=[].concat(Kh(Kf.rangeStep(new he(l),new he(u).sub(new he(.99).mul(d)),d)),[u]);return n>i?Uh(p):p}var K7=K_(W7),H7=K_(U7),V7="Invariant failed";function Ni(e,t){throw new Error(V7)}var G7=["offset","layout","width","dataKey","data","dataPointFormatter","xAxis","yAxis"];function Ta(e){"@babel/helpers - typeof";return Ta=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Ta(e)}function hc(){return hc=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},hc.apply(this,arguments)}function Y7(e,t){return Z7(e)||Q7(e,t)||X7(e,t)||q7()}function q7(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
-In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function X7(e,t){if(e){if(typeof e=="string")return xb(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return xb(e,t)}}function xb(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function Q7(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,i,a,o,s=[],l=!0,u=!1;try{if(a=(r=r.call(e)).next,t!==0)for(;!(l=(n=a.call(r)).done)&&(s.push(n.value),s.length!==t);l=!0);}catch(f){u=!0,i=f}finally{try{if(!l&&r.return!=null&&(o=r.return(),Object(o)!==o))return}finally{if(u)throw i}}return s}}function Z7(e){if(Array.isArray(e))return e}function J7(e,t){if(e==null)return{};var r=eW(e,t),n,i;if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i<a.length;i++)n=a[i],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function eW(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function tW(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function rW(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,Q_(n.key),n)}}function nW(e,t,r){return t&&rW(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function iW(e,t,r){return t=mc(t),aW(e,q_()?Reflect.construct(t,r||[],mc(e).constructor):t.apply(e,r))}function aW(e,t){if(t&&(Ta(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return oW(e)}function oW(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function q_(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(q_=function(){return!!e})()}function mc(e){return mc=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},mc(e)}function sW(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Vh(e,t)}function Vh(e,t){return Vh=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,i){return n.__proto__=i,n},Vh(e,t)}function X_(e,t,r){return t=Q_(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function Q_(e){var t=lW(e,"string");return Ta(t)=="symbol"?t:t+""}function lW(e,t){if(Ta(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(Ta(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}var vo=function(e){function t(){return tW(this,t),iW(this,t,arguments)}return sW(t,e),nW(t,[{key:"render",value:function(){var n=this.props,i=n.offset,a=n.layout,o=n.width,s=n.dataKey,l=n.data,u=n.dataPointFormatter,f=n.xAxis,d=n.yAxis,p=J7(n,G7),h=q(p,!1);this.props.direction==="x"&&f.type!=="number"&&Ni();var m=l.map(function(g){var x=u(g,s),y=x.x,v=x.y,b=x.value,S=x.errorVal;if(!S)return null;var w=[],j,O;if(Array.isArray(S)){var _=Y7(S,2);j=_[0],O=_[1]}else j=O=S;if(a==="vertical"){var P=f.scale,N=v+i,T=N+o,$=N-o,I=P(b-j),D=P(b+O);w.push({x1:D,y1:T,x2:D,y2:$}),w.push({x1:I,y1:N,x2:D,y2:N}),w.push({x1:I,y1:T,x2:I,y2:$})}else if(a==="horizontal"){var L=d.scale,C=y+i,F=C-o,M=C+o,B=L(b-j),E=L(b+O);w.push({x1:F,y1:E,x2:M,y2:E}),w.push({x1:C,y1:B,x2:C,y2:E}),w.push({x1:F,y1:B,x2:M,y2:B})}return A.createElement(te,hc({className:"recharts-errorBar",key:"bar-".concat(w.map(function(W){return"".concat(W.x1,"-").concat(W.x2,"-").concat(W.y1,"-").concat(W.y2)}))},h),w.map(function(W){return A.createElement("line",hc({},W,{key:"line-".concat(W.x1,"-").concat(W.x2,"-").concat(W.y1,"-").concat(W.y2)}))}))});return A.createElement(te,{className:"recharts-errorBars"},m)}}])}(A.Component);X_(vo,"defaultProps",{stroke:"black",strokeWidth:1.5,width:5,offset:0,layout:"horizontal"});X_(vo,"displayName","ErrorBar");function Rs(e){"@babel/helpers - typeof";return Rs=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Rs(e)}function bb(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function Jn(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?bb(Object(r),!0).forEach(function(n){uW(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):bb(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function uW(e,t,r){return t=cW(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function cW(e){var t=fW(e,"string");return Rs(t)=="symbol"?t:t+""}function fW(e,t){if(Rs(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(Rs(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var Z_=function(t){var r=t.children,n=t.formattedGraphicalItems,i=t.legendWidth,a=t.legendContent,o=Rt(r,Yr);if(!o)return null;var s=Yr.defaultProps,l=s!==void 0?Jn(Jn({},s),o.props):{},u;return o.props&&o.props.payload?u=o.props&&o.props.payload:a==="children"?u=(n||[]).reduce(function(f,d){var p=d.item,h=d.props,m=h.sectors||h.data||[];return f.concat(m.map(function(g){return{type:o.props.iconType||p.props.legendType,value:g.name,color:g.fill,payload:g}}))},[]):u=(n||[]).map(function(f){var d=f.item,p=d.type.defaultProps,h=p!==void 0?Jn(Jn({},p),d.props):{},m=h.dataKey,g=h.name,x=h.legendType,y=h.hide;return{inactive:y,dataKey:m,type:l.iconType||x||"square",color:$y(d),value:g||m,payload:h}}),Jn(Jn(Jn({},l),Yr.getWithHeight(o,i)),{},{payload:u,item:o})};function Bs(e){"@babel/helpers - typeof";return Bs=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Bs(e)}function wb(e){return mW(e)||hW(e)||pW(e)||dW()}function dW(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
-In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function pW(e,t){if(e){if(typeof e=="string")return Gh(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return Gh(e,t)}}function hW(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function mW(e){if(Array.isArray(e))return Gh(e)}function Gh(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function jb(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function Ie(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?jb(Object(r),!0).forEach(function(n){va(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):jb(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function va(e,t,r){return t=vW(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function vW(e){var t=yW(e,"string");return Bs(t)=="symbol"?t:t+""}function yW(e,t){if(Bs(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(Bs(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Oe(e,t,r){return Q(e)||Q(t)?r:Xe(t)?Wt(e,t,r):Z(t)?t(e):r}function Zo(e,t,r,n){var i=h7(e,function(s){return Oe(s,t)});if(r==="number"){var a=i.filter(function(s){return K(s)||parseFloat(s)});return a.length?[Wf(a),jn(a)]:[1/0,-1/0]}var o=n?i.filter(function(s){return!Q(s)}):i;return o.map(function(s){return Xe(s)||s instanceof Date?s:""})}var gW=function(t){var r,n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[],i=arguments.length>2?arguments[2]:void 0,a=arguments.length>3?arguments[3]:void 0,o=-1,s=(r=n==null?void 0:n.length)!==null&&r!==void 0?r:0;if(s<=1)return 0;if(a&&a.axisType==="angleAxis"&&Math.abs(Math.abs(a.range[1]-a.range[0])-360)<=1e-6)for(var l=a.range,u=0;u<s;u++){var f=u>0?i[u-1].coordinate:i[s-1].coordinate,d=i[u].coordinate,p=u>=s-1?i[0].coordinate:i[u+1].coordinate,h=void 0;if(yt(d-f)!==yt(p-d)){var m=[];if(yt(p-d)===yt(l[1]-l[0])){h=p;var g=d+l[1]-l[0];m[0]=Math.min(g,(g+f)/2),m[1]=Math.max(g,(g+f)/2)}else{h=f;var x=p+l[1]-l[0];m[0]=Math.min(d,(x+d)/2),m[1]=Math.max(d,(x+d)/2)}var y=[Math.min(d,(h+d)/2),Math.max(d,(h+d)/2)];if(t>y[0]&&t<=y[1]||t>=m[0]&&t<=m[1]){o=i[u].index;break}}else{var v=Math.min(f,p),b=Math.max(f,p);if(t>(v+d)/2&&t<=(b+d)/2){o=i[u].index;break}}}else for(var S=0;S<s;S++)if(S===0&&t<=(n[S].coordinate+n[S+1].coordinate)/2||S>0&&S<s-1&&t>(n[S].coordinate+n[S-1].coordinate)/2&&t<=(n[S].coordinate+n[S+1].coordinate)/2||S===s-1&&t>(n[S].coordinate+n[S-1].coordinate)/2){o=n[S].index;break}return o},$y=function(t){var r,n=t,i=n.type.displayName,a=(r=t.type)!==null&&r!==void 0&&r.defaultProps?Ie(Ie({},t.type.defaultProps),t.props):t.props,o=a.stroke,s=a.fill,l;switch(i){case"Line":l=o;break;case"Area":case"Radar":l=o&&o!=="none"?o:s;break;default:l=s;break}return l},xW=function(t){var r=t.barSize,n=t.totalSize,i=t.stackGroups,a=i===void 0?{}:i;if(!a)return{};for(var o={},s=Object.keys(a),l=0,u=s.length;l<u;l++)for(var f=a[s[l]].stackGroups,d=Object.keys(f),p=0,h=d.length;p<h;p++){var m=f[d[p]],g=m.items,x=m.cateAxisId,y=g.filter(function(O){return Gr(O.type).indexOf("Bar")>=0});if(y&&y.length){var v=y[0].type.defaultProps,b=v!==void 0?Ie(Ie({},v),y[0].props):y[0].props,S=b.barSize,w=b[x];o[w]||(o[w]=[]);var j=Q(S)?r:S;o[w].push({item:y[0],stackList:y.slice(1),barSize:Q(j)?void 0:gt(j,n,0)})}}return o},bW=function(t){var r=t.barGap,n=t.barCategoryGap,i=t.bandSize,a=t.sizeList,o=a===void 0?[]:a,s=t.maxBarSize,l=o.length;if(l<1)return null;var u=gt(r,i,0,!0),f,d=[];if(o[0].barSize===+o[0].barSize){var p=!1,h=i/l,m=o.reduce(function(S,w){return S+w.barSize||0},0);m+=(l-1)*u,m>=i&&(m-=(l-1)*u,u=0),m>=i&&h>0&&(p=!0,h*=.9,m=l*h);var g=(i-m)/2>>0,x={offset:g-u,size:0};f=o.reduce(function(S,w){var j={item:w.item,position:{offset:x.offset+x.size+u,size:p?h:w.barSize}},O=[].concat(wb(S),[j]);return x=O[O.length-1].position,w.stackList&&w.stackList.length&&w.stackList.forEach(function(_){O.push({item:_,position:x})}),O},d)}else{var y=gt(n,i,0,!0);i-2*y-(l-1)*u<=0&&(u=0);var v=(i-2*y-(l-1)*u)/l;v>1&&(v>>=0);var b=s===+s?Math.min(v,s):v;f=o.reduce(function(S,w,j){var O=[].concat(wb(S),[{item:w.item,position:{offset:y+(v+u)*j+(v-b)/2,size:b}}]);return w.stackList&&w.stackList.length&&w.stackList.forEach(function(_){O.push({item:_,position:O[O.length-1].position})}),O},d)}return f},wW=function(t,r,n,i){var a=n.children,o=n.width,s=n.margin,l=o-(s.left||0)-(s.right||0),u=Z_({children:a,legendWidth:l});if(u){var f=i||{},d=f.width,p=f.height,h=u.align,m=u.verticalAlign,g=u.layout;if((g==="vertical"||g==="horizontal"&&m==="middle")&&h!=="center"&&K(t[h]))return Ie(Ie({},t),{},va({},h,t[h]+(d||0)));if((g==="horizontal"||g==="vertical"&&h==="center")&&m!=="middle"&&K(t[m]))return Ie(Ie({},t),{},va({},m,t[m]+(p||0)))}return t},jW=function(t,r,n){return Q(r)?!0:t==="horizontal"?r==="yAxis":t==="vertical"||n==="x"?r==="xAxis":n==="y"?r==="yAxis":!0},J_=function(t,r,n,i,a){var o=r.props.children,s=wt(o,vo).filter(function(u){return jW(i,a,u.props.direction)});if(s&&s.length){var l=s.map(function(u){return u.props.dataKey});return t.reduce(function(u,f){var d=Oe(f,n);if(Q(d))return u;var p=Array.isArray(d)?[Wf(d),jn(d)]:[d,d],h=l.reduce(function(m,g){var x=Oe(f,g,0),y=p[0]-Math.abs(Array.isArray(x)?x[0]:x),v=p[1]+Math.abs(Array.isArray(x)?x[1]:x);return[Math.min(y,m[0]),Math.max(v,m[1])]},[1/0,-1/0]);return[Math.min(h[0],u[0]),Math.max(h[1],u[1])]},[1/0,-1/0])}return null},SW=function(t,r,n,i,a){var o=r.map(function(s){return J_(t,s,n,a,i)}).filter(function(s){return!Q(s)});return o&&o.length?o.reduce(function(s,l){return[Math.min(s[0],l[0]),Math.max(s[1],l[1])]},[1/0,-1/0]):null},eP=function(t,r,n,i,a){var o=r.map(function(l){var u=l.props.dataKey;return n==="number"&&u&&J_(t,l,u,i)||Zo(t,u,n,a)});if(n==="number")return o.reduce(function(l,u){return[Math.min(l[0],u[0]),Math.max(l[1],u[1])]},[1/0,-1/0]);var s={};return o.reduce(function(l,u){for(var f=0,d=u.length;f<d;f++)s[u[f]]||(s[u[f]]=!0,l.push(u[f]));return l},[])},tP=function(t,r){return t==="horizontal"&&r==="xAxis"||t==="vertical"&&r==="yAxis"||t==="centric"&&r==="angleAxis"||t==="radial"&&r==="radiusAxis"},rP=function(t,r,n,i){if(i)return t.map(function(l){return l.coordinate});var a,o,s=t.map(function(l){return l.coordinate===r&&(a=!0),l.coordinate===n&&(o=!0),l.coordinate});return a||s.push(r),o||s.push(n),s},Hr=function(t,r,n){if(!t)return null;var i=t.scale,a=t.duplicateDomain,o=t.type,s=t.range,l=t.realScaleType==="scaleBand"?i.bandwidth()/2:2,u=(r||n)&&o==="category"&&i.bandwidth?i.bandwidth()/l:0;if(u=t.axisType==="angleAxis"&&(s==null?void 0:s.length)>=2?yt(s[0]-s[1])*2*u:u,r&&(t.ticks||t.niceTicks)){var f=(t.ticks||t.niceTicks).map(function(d){var p=a?a.indexOf(d):d;return{coordinate:i(p)+u,value:d,offset:u}});return f.filter(function(d){return!lo(d.coordinate)})}return t.isCategorical&&t.categoricalDomain?t.categoricalDomain.map(function(d,p){return{coordinate:i(d)+u,value:d,index:p,offset:u}}):i.ticks&&!n?i.ticks(t.tickCount).map(function(d){return{coordinate:i(d)+u,value:d,offset:u}}):i.domain().map(function(d,p){return{coordinate:i(d)+u,value:a?a[d]:d,index:p,offset:u}})},Jd=new WeakMap,Xl=function(t,r){if(typeof r!="function")return t;Jd.has(t)||Jd.set(t,new WeakMap);var n=Jd.get(t);if(n.has(r))return n.get(r);var i=function(){t.apply(void 0,arguments),r.apply(void 0,arguments)};return n.set(r,i),i},nP=function(t,r,n){var i=t.scale,a=t.type,o=t.layout,s=t.axisType;if(i==="auto")return o==="radial"&&s==="radiusAxis"?{scale:Es(),realScaleType:"band"}:o==="radial"&&s==="angleAxis"?{scale:uc(),realScaleType:"linear"}:a==="category"&&r&&(r.indexOf("LineChart")>=0||r.indexOf("AreaChart")>=0||r.indexOf("ComposedChart")>=0&&!n)?{scale:Qo(),realScaleType:"point"}:a==="category"?{scale:Es(),realScaleType:"band"}:{scale:uc(),realScaleType:"linear"};if(Pi(i)){var l="scale".concat(kf(i));return{scale:(mb[l]||Qo)(),realScaleType:mb[l]?l:"point"}}return Z(i)?{scale:i}:{scale:Qo(),realScaleType:"point"}},Sb=1e-4,iP=function(t){var r=t.domain();if(!(!r||r.length<=2)){var n=r.length,i=t.range(),a=Math.min(i[0],i[1])-Sb,o=Math.max(i[0],i[1])+Sb,s=t(r[0]),l=t(r[n-1]);(s<a||s>o||l<a||l>o)&&t.domain([r[0],r[n-1]])}},OW=function(t,r){if(!t)return null;for(var n=0,i=t.length;n<i;n++)if(t[n].item===r)return t[n].position;return null},_W=function(t,r){if(!r||r.length!==2||!K(r[0])||!K(r[1]))return t;var n=Math.min(r[0],r[1]),i=Math.max(r[0],r[1]),a=[t[0],t[1]];return(!K(t[0])||t[0]<n)&&(a[0]=n),(!K(t[1])||t[1]>i)&&(a[1]=i),a[0]>i&&(a[0]=i),a[1]<n&&(a[1]=n),a},PW=function(t){var r=t.length;if(!(r<=0))for(var n=0,i=t[0].length;n<i;++n)for(var a=0,o=0,s=0;s<r;++s){var l=lo(t[s][n][1])?t[s][n][0]:t[s][n][1];l>=0?(t[s][n][0]=a,t[s][n][1]=a+l,a=t[s][n][1]):(t[s][n][0]=o,t[s][n][1]=o+l,o=t[s][n][1])}},kW=function(t){var r=t.length;if(!(r<=0))for(var n=0,i=t[0].length;n<i;++n)for(var a=0,o=0;o<r;++o){var s=lo(t[o][n][1])?t[o][n][0]:t[o][n][1];s>=0?(t[o][n][0]=a,t[o][n][1]=a+s,a=t[o][n][1]):(t[o][n][0]=0,t[o][n][1]=0)}},AW={sign:PW,expand:G3,none:Oa,silhouette:Y3,wiggle:q3,positive:kW},NW=function(t,r,n){var i=r.map(function(s){return s.props.dataKey}),a=AW[n],o=V3().keys(i).value(function(s,l){return+Oe(s,l,0)}).order(gh).offset(a);return o(t)},$W=function(t,r,n,i,a,o){if(!t)return null;var s=o?r.reverse():r,l={},u=s.reduce(function(d,p){var h,m=(h=p.type)!==null&&h!==void 0&&h.defaultProps?Ie(Ie({},p.type.defaultProps),p.props):p.props,g=m.stackId,x=m.hide;if(x)return d;var y=m[n],v=d[y]||{hasStack:!1,stackGroups:{}};if(Xe(g)){var b=v.stackGroups[g]||{numericAxisId:n,cateAxisId:i,items:[]};b.items.push(p),v.hasStack=!0,v.stackGroups[g]=b}else v.stackGroups[Gn("_stackId_")]={numericAxisId:n,cateAxisId:i,items:[p]};return Ie(Ie({},d),{},va({},y,v))},l),f={};return Object.keys(u).reduce(function(d,p){var h=u[p];if(h.hasStack){var m={};h.stackGroups=Object.keys(h.stackGroups).reduce(function(g,x){var y=h.stackGroups[x];return Ie(Ie({},g),{},va({},x,{numericAxisId:n,cateAxisId:i,items:y.items,stackedData:NW(t,y.items,a)}))},m)}return Ie(Ie({},d),{},va({},p,h))},f)},aP=function(t,r){var n=r.realScaleType,i=r.type,a=r.tickCount,o=r.originalDomain,s=r.allowDecimals,l=n||r.scale;if(l!=="auto"&&l!=="linear")return null;if(a&&i==="number"&&o&&(o[0]==="auto"||o[1]==="auto")){var u=t.domain();if(!u.length)return null;var f=K7(u,a,s);return t.domain([Wf(f),jn(f)]),{niceTicks:f}}if(a&&i==="number"){var d=t.domain(),p=H7(d,a,s);return{niceTicks:p}}return null};function Ca(e){var t=e.axis,r=e.ticks,n=e.bandSize,i=e.entry,a=e.index,o=e.dataKey;if(t.type==="category"){if(!t.allowDuplicatedCategory&&t.dataKey&&!Q(i[t.dataKey])){var s=zu(r,"value",i[t.dataKey]);if(s)return s.coordinate+n/2}return r[a]?r[a].coordinate+n/2:null}var l=Oe(i,Q(o)?t.dataKey:o);return Q(l)?null:t.scale(l)}var Ob=function(t){var r=t.axis,n=t.ticks,i=t.offset,a=t.bandSize,o=t.entry,s=t.index;if(r.type==="category")return n[s]?n[s].coordinate+i:null;var l=Oe(o,r.dataKey,r.domain[s]);return Q(l)?null:r.scale(l)-a/2+i},EW=function(t){var r=t.numericAxis,n=r.scale.domain();if(r.type==="number"){var i=Math.min(n[0],n[1]),a=Math.max(n[0],n[1]);return i<=0&&a>=0?0:a<0?a:i}return n[0]},TW=function(t,r){var n,i=(n=t.type)!==null&&n!==void 0&&n.defaultProps?Ie(Ie({},t.type.defaultProps),t.props):t.props,a=i.stackId;if(Xe(a)){var o=r[a];if(o){var s=o.items.indexOf(t);return s>=0?o.stackedData[s]:null}}return null},CW=function(t){return t.reduce(function(r,n){return[Wf(n.concat([r[0]]).filter(K)),jn(n.concat([r[1]]).filter(K))]},[1/0,-1/0])},oP=function(t,r,n){return Object.keys(t).reduce(function(i,a){var o=t[a],s=o.stackedData,l=s.reduce(function(u,f){var d=CW(f.slice(r,n+1));return[Math.min(u[0],d[0]),Math.max(u[1],d[1])]},[1/0,-1/0]);return[Math.min(l[0],i[0]),Math.max(l[1],i[1])]},[1/0,-1/0]).map(function(i){return i===1/0||i===-1/0?0:i})},_b=/^dataMin[\s]*-[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,Pb=/^dataMax[\s]*\+[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,Yh=function(t,r,n){if(Z(t))return t(r,n);if(!Array.isArray(t))return r;var i=[];if(K(t[0]))i[0]=n?t[0]:Math.min(t[0],r[0]);else if(_b.test(t[0])){var a=+_b.exec(t[0])[1];i[0]=r[0]-a}else Z(t[0])?i[0]=t[0](r[0]):i[0]=r[0];if(K(t[1]))i[1]=n?t[1]:Math.max(t[1],r[1]);else if(Pb.test(t[1])){var o=+Pb.exec(t[1])[1];i[1]=r[1]+o}else Z(t[1])?i[1]=t[1](r[1]):i[1]=r[1];return i},vc=function(t,r,n){if(t&&t.scale&&t.scale.bandwidth){var i=t.scale.bandwidth();if(!n||i>0)return i}if(t&&r&&r.length>=2){for(var a=iy(r,function(d){return d.coordinate}),o=1/0,s=1,l=a.length;s<l;s++){var u=a[s],f=a[s-1];o=Math.min((u.coordinate||0)-(f.coordinate||0),o)}return o===1/0?0:o}return n?void 0:0},kb=function(t,r,n){return!t||!t.length||Fn(t,Wt(n,"type.defaultProps.domain"))?r:t},sP=function(t,r){var n=t.type.defaultProps?Ie(Ie({},t.type.defaultProps),t.props):t.props,i=n.dataKey,a=n.name,o=n.unit,s=n.formatter,l=n.tooltipType,u=n.chartType,f=n.hide;return Ie(Ie({},q(t,!1)),{},{dataKey:i,unit:o,formatter:s,name:a||i,color:$y(t),value:Oe(r,i),type:l,payload:r,chartType:u,hide:f})};function Fs(e){"@babel/helpers - typeof";return Fs=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Fs(e)}function Ab(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function Br(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Ab(Object(r),!0).forEach(function(n){lP(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Ab(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function lP(e,t,r){return t=MW(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function MW(e){var t=IW(e,"string");return Fs(t)=="symbol"?t:t+""}function IW(e,t){if(Fs(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(Fs(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function LW(e,t){return FW(e)||BW(e,t)||RW(e,t)||DW()}function DW(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
-In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function RW(e,t){if(e){if(typeof e=="string")return Nb(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return Nb(e,t)}}function Nb(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function BW(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,i,a,o,s=[],l=!0,u=!1;try{if(a=(r=r.call(e)).next,t!==0)for(;!(l=(n=a.call(r)).done)&&(s.push(n.value),s.length!==t);l=!0);}catch(f){u=!0,i=f}finally{try{if(!l&&r.return!=null&&(o=r.return(),Object(o)!==o))return}finally{if(u)throw i}}return s}}function FW(e){if(Array.isArray(e))return e}var yc=Math.PI/180,zW=function(t){return t*180/Math.PI},xe=function(t,r,n,i){return{x:t+Math.cos(-yc*i)*n,y:r+Math.sin(-yc*i)*n}},uP=function(t,r){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{top:0,right:0,bottom:0,left:0};return Math.min(Math.abs(t-(n.left||0)-(n.right||0)),Math.abs(r-(n.top||0)-(n.bottom||0)))/2},WW=function(t,r,n,i,a){var o=t.width,s=t.height,l=t.startAngle,u=t.endAngle,f=gt(t.cx,o,o/2),d=gt(t.cy,s,s/2),p=uP(o,s,n),h=gt(t.innerRadius,p,0),m=gt(t.outerRadius,p,p*.8),g=Object.keys(r);return g.reduce(function(x,y){var v=r[y],b=v.domain,S=v.reversed,w;if(Q(v.range))i==="angleAxis"?w=[l,u]:i==="radiusAxis"&&(w=[h,m]),S&&(w=[w[1],w[0]]);else{w=v.range;var j=w,O=LW(j,2);l=O[0],u=O[1]}var _=nP(v,a),P=_.realScaleType,N=_.scale;N.domain(b).range(w),iP(N);var T=aP(N,Br(Br({},v),{},{realScaleType:P})),$=Br(Br(Br({},v),T),{},{range:w,radius:m,realScaleType:P,scale:N,cx:f,cy:d,innerRadius:h,outerRadius:m,startAngle:l,endAngle:u});return Br(Br({},x),{},lP({},y,$))},{})},UW=function(t,r){var n=t.x,i=t.y,a=r.x,o=r.y;return Math.sqrt(Math.pow(n-a,2)+Math.pow(i-o,2))},KW=function(t,r){var n=t.x,i=t.y,a=r.cx,o=r.cy,s=UW({x:n,y:i},{x:a,y:o});if(s<=0)return{radius:s};var l=(n-a)/s,u=Math.acos(l);return i>o&&(u=2*Math.PI-u),{radius:s,angle:zW(u),angleInRadian:u}},HW=function(t){var r=t.startAngle,n=t.endAngle,i=Math.floor(r/360),a=Math.floor(n/360),o=Math.min(i,a);return{startAngle:r-o*360,endAngle:n-o*360}},VW=function(t,r){var n=r.startAngle,i=r.endAngle,a=Math.floor(n/360),o=Math.floor(i/360),s=Math.min(a,o);return t+s*360},$b=function(t,r){var n=t.x,i=t.y,a=KW({x:n,y:i},r),o=a.radius,s=a.angle,l=r.innerRadius,u=r.outerRadius;if(o<l||o>u)return!1;if(o===0)return!0;var f=HW(r),d=f.startAngle,p=f.endAngle,h=s,m;if(d<=p){for(;h>p;)h-=360;for(;h<d;)h+=360;m=h>=d&&h<=p}else{for(;h>d;)h-=360;for(;h<p;)h+=360;m=h>=p&&h<=d}return m?Br(Br({},r),{},{radius:o,angle:VW(h,r)}):null},cP=function(t){return!k.isValidElement(t)&&!Z(t)&&typeof t!="boolean"?t.className:""};function zs(e){"@babel/helpers - typeof";return zs=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},zs(e)}var GW=["offset"];function YW(e){return ZW(e)||QW(e)||XW(e)||qW()}function qW(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
-In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function XW(e,t){if(e){if(typeof e=="string")return qh(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return qh(e,t)}}function QW(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function ZW(e){if(Array.isArray(e))return qh(e)}function qh(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function JW(e,t){if(e==null)return{};var r=eU(e,t),n,i;if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i<a.length;i++)n=a[i],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function eU(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function Eb(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function Ge(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Eb(Object(r),!0).forEach(function(n){tU(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Eb(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function tU(e,t,r){return t=rU(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function rU(e){var t=nU(e,"string");return zs(t)=="symbol"?t:t+""}function nU(e,t){if(zs(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(zs(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Ws(){return Ws=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},Ws.apply(this,arguments)}var iU=function(t){var r=t.value,n=t.formatter,i=Q(t.children)?r:t.children;return Z(n)?n(i):i},aU=function(t,r){var n=yt(r-t),i=Math.min(Math.abs(r-t),360);return n*i},oU=function(t,r,n){var i=t.position,a=t.viewBox,o=t.offset,s=t.className,l=a,u=l.cx,f=l.cy,d=l.innerRadius,p=l.outerRadius,h=l.startAngle,m=l.endAngle,g=l.clockWise,x=(d+p)/2,y=aU(h,m),v=y>=0?1:-1,b,S;i==="insideStart"?(b=h+v*o,S=g):i==="insideEnd"?(b=m-v*o,S=!g):i==="end"&&(b=m+v*o,S=g),S=y<=0?S:!S;var w=xe(u,f,x,b),j=xe(u,f,x,b+(S?1:-1)*359),O="M".concat(w.x,",").concat(w.y,`
- A`).concat(x,",").concat(x,",0,1,").concat(S?0:1,`,
- `).concat(j.x,",").concat(j.y),_=Q(t.id)?Gn("recharts-radial-line-"):t.id;return A.createElement("text",Ws({},n,{dominantBaseline:"central",className:ee("recharts-radial-bar-label",s)}),A.createElement("defs",null,A.createElement("path",{id:_,d:O})),A.createElement("textPath",{xlinkHref:"#".concat(_)},r))},sU=function(t){var r=t.viewBox,n=t.offset,i=t.position,a=r,o=a.cx,s=a.cy,l=a.innerRadius,u=a.outerRadius,f=a.startAngle,d=a.endAngle,p=(f+d)/2;if(i==="outside"){var h=xe(o,s,u+n,p),m=h.x,g=h.y;return{x:m,y:g,textAnchor:m>=o?"start":"end",verticalAnchor:"middle"}}if(i==="center")return{x:o,y:s,textAnchor:"middle",verticalAnchor:"middle"};if(i==="centerTop")return{x:o,y:s,textAnchor:"middle",verticalAnchor:"start"};if(i==="centerBottom")return{x:o,y:s,textAnchor:"middle",verticalAnchor:"end"};var x=(l+u)/2,y=xe(o,s,x,p),v=y.x,b=y.y;return{x:v,y:b,textAnchor:"middle",verticalAnchor:"middle"}},lU=function(t){var r=t.viewBox,n=t.parentViewBox,i=t.offset,a=t.position,o=r,s=o.x,l=o.y,u=o.width,f=o.height,d=f>=0?1:-1,p=d*i,h=d>0?"end":"start",m=d>0?"start":"end",g=u>=0?1:-1,x=g*i,y=g>0?"end":"start",v=g>0?"start":"end";if(a==="top"){var b={x:s+u/2,y:l-d*i,textAnchor:"middle",verticalAnchor:h};return Ge(Ge({},b),n?{height:Math.max(l-n.y,0),width:u}:{})}if(a==="bottom"){var S={x:s+u/2,y:l+f+p,textAnchor:"middle",verticalAnchor:m};return Ge(Ge({},S),n?{height:Math.max(n.y+n.height-(l+f),0),width:u}:{})}if(a==="left"){var w={x:s-x,y:l+f/2,textAnchor:y,verticalAnchor:"middle"};return Ge(Ge({},w),n?{width:Math.max(w.x-n.x,0),height:f}:{})}if(a==="right"){var j={x:s+u+x,y:l+f/2,textAnchor:v,verticalAnchor:"middle"};return Ge(Ge({},j),n?{width:Math.max(n.x+n.width-j.x,0),height:f}:{})}var O=n?{width:u,height:f}:{};return a==="insideLeft"?Ge({x:s+x,y:l+f/2,textAnchor:v,verticalAnchor:"middle"},O):a==="insideRight"?Ge({x:s+u-x,y:l+f/2,textAnchor:y,verticalAnchor:"middle"},O):a==="insideTop"?Ge({x:s+u/2,y:l+p,textAnchor:"middle",verticalAnchor:m},O):a==="insideBottom"?Ge({x:s+u/2,y:l+f-p,textAnchor:"middle",verticalAnchor:h},O):a==="insideTopLeft"?Ge({x:s+x,y:l+p,textAnchor:v,verticalAnchor:m},O):a==="insideTopRight"?Ge({x:s+u-x,y:l+p,textAnchor:y,verticalAnchor:m},O):a==="insideBottomLeft"?Ge({x:s+x,y:l+f-p,textAnchor:v,verticalAnchor:h},O):a==="insideBottomRight"?Ge({x:s+u-x,y:l+f-p,textAnchor:y,verticalAnchor:h},O):io(a)&&(K(a.x)||fi(a.x))&&(K(a.y)||fi(a.y))?Ge({x:s+gt(a.x,u),y:l+gt(a.y,f),textAnchor:"end",verticalAnchor:"end"},O):Ge({x:s+u/2,y:l+f/2,textAnchor:"middle",verticalAnchor:"middle"},O)},uU=function(t){return"cx"in t&&K(t.cx)};function et(e){var t=e.offset,r=t===void 0?5:t,n=JW(e,GW),i=Ge({offset:r},n),a=i.viewBox,o=i.position,s=i.value,l=i.children,u=i.content,f=i.className,d=f===void 0?"":f,p=i.textBreakAll;if(!a||Q(s)&&Q(l)&&!k.isValidElement(u)&&!Z(u))return null;if(k.isValidElement(u))return k.cloneElement(u,i);var h;if(Z(u)){if(h=k.createElement(u,i),k.isValidElement(h))return h}else h=iU(i);var m=uU(a),g=q(i,!0);if(m&&(o==="insideStart"||o==="insideEnd"||o==="end"))return oU(i,h,g);var x=m?sU(i):lU(i);return A.createElement(ki,Ws({className:ee("recharts-label",d)},g,x,{breakAll:p}),h)}et.displayName="Label";var fP=function(t){var r=t.cx,n=t.cy,i=t.angle,a=t.startAngle,o=t.endAngle,s=t.r,l=t.radius,u=t.innerRadius,f=t.outerRadius,d=t.x,p=t.y,h=t.top,m=t.left,g=t.width,x=t.height,y=t.clockWise,v=t.labelViewBox;if(v)return v;if(K(g)&&K(x)){if(K(d)&&K(p))return{x:d,y:p,width:g,height:x};if(K(h)&&K(m))return{x:h,y:m,width:g,height:x}}return K(d)&&K(p)?{x:d,y:p,width:0,height:0}:K(r)&&K(n)?{cx:r,cy:n,startAngle:a||i||0,endAngle:o||i||0,innerRadius:u||0,outerRadius:f||l||s||0,clockWise:y}:t.viewBox?t.viewBox:{}},cU=function(t,r){return t?t===!0?A.createElement(et,{key:"label-implicit",viewBox:r}):Xe(t)?A.createElement(et,{key:"label-implicit",viewBox:r,value:t}):k.isValidElement(t)?t.type===et?k.cloneElement(t,{key:"label-implicit",viewBox:r}):A.createElement(et,{key:"label-implicit",content:t,viewBox:r}):Z(t)?A.createElement(et,{key:"label-implicit",content:t,viewBox:r}):io(t)?A.createElement(et,Ws({viewBox:r},t,{key:"label-implicit"})):null:null},fU=function(t,r){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;if(!t||!t.children&&n&&!t.label)return null;var i=t.children,a=fP(t),o=wt(i,et).map(function(l,u){return k.cloneElement(l,{viewBox:r||a,key:"label-".concat(u)})});if(!n)return o;var s=cU(t.label,r||a);return[s].concat(YW(o))};et.parseViewBox=fP;et.renderCallByParent=fU;function dU(e){var t=e==null?0:e.length;return t?e[t-1]:void 0}var pU=dU;const hU=de(pU);function Us(e){"@babel/helpers - typeof";return Us=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Us(e)}var mU=["valueAccessor"],vU=["data","dataKey","clockWise","id","textBreakAll"];function yU(e){return wU(e)||bU(e)||xU(e)||gU()}function gU(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
-In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function xU(e,t){if(e){if(typeof e=="string")return Xh(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return Xh(e,t)}}function bU(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function wU(e){if(Array.isArray(e))return Xh(e)}function Xh(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function gc(){return gc=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},gc.apply(this,arguments)}function Tb(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function Cb(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Tb(Object(r),!0).forEach(function(n){jU(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Tb(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function jU(e,t,r){return t=SU(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function SU(e){var t=OU(e,"string");return Us(t)=="symbol"?t:t+""}function OU(e,t){if(Us(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(Us(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Mb(e,t){if(e==null)return{};var r=_U(e,t),n,i;if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i<a.length;i++)n=a[i],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function _U(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}var PU=function(t){return Array.isArray(t.value)?hU(t.value):t.value};function br(e){var t=e.valueAccessor,r=t===void 0?PU:t,n=Mb(e,mU),i=n.data,a=n.dataKey,o=n.clockWise,s=n.id,l=n.textBreakAll,u=Mb(n,vU);return!i||!i.length?null:A.createElement(te,{className:"recharts-label-list"},i.map(function(f,d){var p=Q(a)?r(f,d):Oe(f&&f.payload,a),h=Q(s)?{}:{id:"".concat(s,"-").concat(d)};return A.createElement(et,gc({},q(f,!0),u,h,{parentViewBox:f.parentViewBox,value:p,textBreakAll:l,viewBox:et.parseViewBox(Q(o)?f:Cb(Cb({},f),{},{clockWise:o})),key:"label-".concat(d),index:d}))}))}br.displayName="LabelList";function kU(e,t){return e?e===!0?A.createElement(br,{key:"labelList-implicit",data:t}):A.isValidElement(e)||Z(e)?A.createElement(br,{key:"labelList-implicit",data:t,content:e}):io(e)?A.createElement(br,gc({data:t},e,{key:"labelList-implicit"})):null:null}function AU(e,t){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;if(!e||!e.children&&r&&!e.label)return null;var n=e.children,i=wt(n,br).map(function(o,s){return k.cloneElement(o,{data:t,key:"labelList-".concat(s)})});if(!r)return i;var a=kU(e.label,t);return[a].concat(yU(i))}br.renderCallByParent=AU;function Ks(e){"@babel/helpers - typeof";return Ks=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Ks(e)}function Qh(){return Qh=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},Qh.apply(this,arguments)}function Ib(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function Lb(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Ib(Object(r),!0).forEach(function(n){NU(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Ib(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function NU(e,t,r){return t=$U(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function $U(e){var t=EU(e,"string");return Ks(t)=="symbol"?t:t+""}function EU(e,t){if(Ks(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(Ks(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var TU=function(t,r){var n=yt(r-t),i=Math.min(Math.abs(r-t),359.999);return n*i},Ql=function(t){var r=t.cx,n=t.cy,i=t.radius,a=t.angle,o=t.sign,s=t.isExternal,l=t.cornerRadius,u=t.cornerIsExternal,f=l*(s?1:-1)+i,d=Math.asin(l/f)/yc,p=u?a:a+o*d,h=xe(r,n,f,p),m=xe(r,n,i,p),g=u?a-o*d:a,x=xe(r,n,f*Math.cos(d*yc),g);return{center:h,circleTangency:m,lineTangency:x,theta:d}},dP=function(t){var r=t.cx,n=t.cy,i=t.innerRadius,a=t.outerRadius,o=t.startAngle,s=t.endAngle,l=TU(o,s),u=o+l,f=xe(r,n,a,o),d=xe(r,n,a,u),p="M ".concat(f.x,",").concat(f.y,`
- A `).concat(a,",").concat(a,`,0,
- `).concat(+(Math.abs(l)>180),",").concat(+(o>u),`,
- `).concat(d.x,",").concat(d.y,`
- `);if(i>0){var h=xe(r,n,i,o),m=xe(r,n,i,u);p+="L ".concat(m.x,",").concat(m.y,`
- A `).concat(i,",").concat(i,`,0,
- `).concat(+(Math.abs(l)>180),",").concat(+(o<=u),`,
- `).concat(h.x,",").concat(h.y," Z")}else p+="L ".concat(r,",").concat(n," Z");return p},CU=function(t){var r=t.cx,n=t.cy,i=t.innerRadius,a=t.outerRadius,o=t.cornerRadius,s=t.forceCornerRadius,l=t.cornerIsExternal,u=t.startAngle,f=t.endAngle,d=yt(f-u),p=Ql({cx:r,cy:n,radius:a,angle:u,sign:d,cornerRadius:o,cornerIsExternal:l}),h=p.circleTangency,m=p.lineTangency,g=p.theta,x=Ql({cx:r,cy:n,radius:a,angle:f,sign:-d,cornerRadius:o,cornerIsExternal:l}),y=x.circleTangency,v=x.lineTangency,b=x.theta,S=l?Math.abs(u-f):Math.abs(u-f)-g-b;if(S<0)return s?"M ".concat(m.x,",").concat(m.y,`
- a`).concat(o,",").concat(o,",0,0,1,").concat(o*2,`,0
- a`).concat(o,",").concat(o,",0,0,1,").concat(-o*2,`,0
- `):dP({cx:r,cy:n,innerRadius:i,outerRadius:a,startAngle:u,endAngle:f});var w="M ".concat(m.x,",").concat(m.y,`
- A`).concat(o,",").concat(o,",0,0,").concat(+(d<0),",").concat(h.x,",").concat(h.y,`
- A`).concat(a,",").concat(a,",0,").concat(+(S>180),",").concat(+(d<0),",").concat(y.x,",").concat(y.y,`
- A`).concat(o,",").concat(o,",0,0,").concat(+(d<0),",").concat(v.x,",").concat(v.y,`
- `);if(i>0){var j=Ql({cx:r,cy:n,radius:i,angle:u,sign:d,isExternal:!0,cornerRadius:o,cornerIsExternal:l}),O=j.circleTangency,_=j.lineTangency,P=j.theta,N=Ql({cx:r,cy:n,radius:i,angle:f,sign:-d,isExternal:!0,cornerRadius:o,cornerIsExternal:l}),T=N.circleTangency,$=N.lineTangency,I=N.theta,D=l?Math.abs(u-f):Math.abs(u-f)-P-I;if(D<0&&o===0)return"".concat(w,"L").concat(r,",").concat(n,"Z");w+="L".concat($.x,",").concat($.y,`
- A`).concat(o,",").concat(o,",0,0,").concat(+(d<0),",").concat(T.x,",").concat(T.y,`
- A`).concat(i,",").concat(i,",0,").concat(+(D>180),",").concat(+(d>0),",").concat(O.x,",").concat(O.y,`
- A`).concat(o,",").concat(o,",0,0,").concat(+(d<0),",").concat(_.x,",").concat(_.y,"Z")}else w+="L".concat(r,",").concat(n,"Z");return w},MU={cx:0,cy:0,innerRadius:0,outerRadius:0,startAngle:0,endAngle:0,cornerRadius:0,forceCornerRadius:!1,cornerIsExternal:!1},pP=function(t){var r=Lb(Lb({},MU),t),n=r.cx,i=r.cy,a=r.innerRadius,o=r.outerRadius,s=r.cornerRadius,l=r.forceCornerRadius,u=r.cornerIsExternal,f=r.startAngle,d=r.endAngle,p=r.className;if(o<a||f===d)return null;var h=ee("recharts-sector",p),m=o-a,g=gt(s,m,0,!0),x;return g>0&&Math.abs(f-d)<360?x=CU({cx:n,cy:i,innerRadius:a,outerRadius:o,cornerRadius:Math.min(g,m/2),forceCornerRadius:l,cornerIsExternal:u,startAngle:f,endAngle:d}):x=dP({cx:n,cy:i,innerRadius:a,outerRadius:o,startAngle:f,endAngle:d}),A.createElement("path",Qh({},q(r,!0),{className:h,d:x,role:"img"}))};function Hs(e){"@babel/helpers - typeof";return Hs=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Hs(e)}function Zh(){return Zh=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},Zh.apply(this,arguments)}function Db(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function Rb(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Db(Object(r),!0).forEach(function(n){IU(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Db(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function IU(e,t,r){return t=LU(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function LU(e){var t=DU(e,"string");return Hs(t)=="symbol"?t:t+""}function DU(e,t){if(Hs(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(Hs(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var Bb={curveBasisClosed:I3,curveBasisOpen:L3,curveBasis:M3,curveBumpX:b3,curveBumpY:w3,curveLinearClosed:D3,curveLinear:Nf,curveMonotoneX:R3,curveMonotoneY:B3,curveNatural:F3,curveStep:z3,curveStepAfter:U3,curveStepBefore:W3},Zl=function(t){return t.x===+t.x&&t.y===+t.y},To=function(t){return t.x},Co=function(t){return t.y},RU=function(t,r){if(Z(t))return t;var n="curve".concat(kf(t));return(n==="curveMonotone"||n==="curveBump")&&r?Bb["".concat(n).concat(r==="vertical"?"Y":"X")]:Bb[n]||Nf},BU=function(t){var r=t.type,n=r===void 0?"linear":r,i=t.points,a=i===void 0?[]:i,o=t.baseLine,s=t.layout,l=t.connectNulls,u=l===void 0?!1:l,f=RU(n,s),d=u?a.filter(function(g){return Zl(g)}):a,p;if(Array.isArray(o)){var h=u?o.filter(function(g){return Zl(g)}):o,m=d.map(function(g,x){return Rb(Rb({},g),{},{base:h[x]})});return s==="vertical"?p=Wl().y(Co).x1(To).x0(function(g){return g.base.x}):p=Wl().x(To).y1(Co).y0(function(g){return g.base.y}),p.defined(Zl).curve(f),p(m)}return s==="vertical"&&K(o)?p=Wl().y(Co).x1(To).x0(o):K(o)?p=Wl().x(To).y1(Co).y0(o):p=lO().x(To).y(Co),p.defined(Zl).curve(f),p(d)},Ln=function(t){var r=t.className,n=t.points,i=t.path,a=t.pathRef;if((!n||!n.length)&&!i)return null;var o=n&&n.length?BU(t):i;return k.createElement("path",Zh({},q(t,!1),Wu(t),{className:ee("recharts-curve",r),d:o,ref:a}))},hP={exports:{}},FU="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED",zU=FU,WU=zU;function mP(){}function vP(){}vP.resetWarningCache=mP;var UU=function(){function e(n,i,a,o,s,l){if(l!==WU){var u=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types");throw u.name="Invariant Violation",u}}e.isRequired=e;function t(){return e}var r={array:e,bigint:e,bool:e,func:e,number:e,object:e,string:e,symbol:e,any:e,arrayOf:t,element:e,elementType:e,instanceOf:t,node:e,objectOf:t,oneOf:t,oneOfType:t,shape:t,exact:t,checkPropTypes:vP,resetWarningCache:mP};return r.PropTypes=r,r};hP.exports=UU();var KU=hP.exports;const ce=de(KU),{getOwnPropertyNames:HU,getOwnPropertySymbols:VU}=Object,{hasOwnProperty:GU}=Object.prototype;function ep(e,t){return function(n,i,a){return e(n,i,a)&&t(n,i,a)}}function Jl(e){return function(r,n,i){if(!r||!n||typeof r!="object"||typeof n!="object")return e(r,n,i);const{cache:a}=i,o=a.get(r),s=a.get(n);if(o&&s)return o===n&&s===r;a.set(r,n),a.set(n,r);const l=e(r,n,i);return a.delete(r),a.delete(n),l}}function YU(e){return e!=null?e[Symbol.toStringTag]:void 0}function Fb(e){return HU(e).concat(VU(e))}const qU=Object.hasOwn||((e,t)=>GU.call(e,t));function Di(e,t){return e===t||!e&&!t&&e!==e&&t!==t}const XU="__v",QU="__o",ZU="_owner",{getOwnPropertyDescriptor:zb,keys:Wb}=Object;function JU(e,t){return e.byteLength===t.byteLength&&xc(new Uint8Array(e),new Uint8Array(t))}function eK(e,t,r){let n=e.length;if(t.length!==n)return!1;for(;n-- >0;)if(!r.equals(e[n],t[n],n,n,e,t,r))return!1;return!0}function tK(e,t){return e.byteLength===t.byteLength&&xc(new Uint8Array(e.buffer,e.byteOffset,e.byteLength),new Uint8Array(t.buffer,t.byteOffset,t.byteLength))}function rK(e,t){return Di(e.getTime(),t.getTime())}function nK(e,t){return e.name===t.name&&e.message===t.message&&e.cause===t.cause&&e.stack===t.stack}function iK(e,t){return e===t}function Ub(e,t,r){const n=e.size;if(n!==t.size)return!1;if(!n)return!0;const i=new Array(n),a=e.entries();let o,s,l=0;for(;(o=a.next())&&!o.done;){const u=t.entries();let f=!1,d=0;for(;(s=u.next())&&!s.done;){if(i[d]){d++;continue}const p=o.value,h=s.value;if(r.equals(p[0],h[0],l,d,e,t,r)&&r.equals(p[1],h[1],p[0],h[0],e,t,r)){f=i[d]=!0;break}d++}if(!f)return!1;l++}return!0}const aK=Di;function oK(e,t,r){const n=Wb(e);let i=n.length;if(Wb(t).length!==i)return!1;for(;i-- >0;)if(!yP(e,t,r,n[i]))return!1;return!0}function Mo(e,t,r){const n=Fb(e);let i=n.length;if(Fb(t).length!==i)return!1;let a,o,s;for(;i-- >0;)if(a=n[i],!yP(e,t,r,a)||(o=zb(e,a),s=zb(t,a),(o||s)&&(!o||!s||o.configurable!==s.configurable||o.enumerable!==s.enumerable||o.writable!==s.writable)))return!1;return!0}function sK(e,t){return Di(e.valueOf(),t.valueOf())}function lK(e,t){return e.source===t.source&&e.flags===t.flags}function Kb(e,t,r){const n=e.size;if(n!==t.size)return!1;if(!n)return!0;const i=new Array(n),a=e.values();let o,s;for(;(o=a.next())&&!o.done;){const l=t.values();let u=!1,f=0;for(;(s=l.next())&&!s.done;){if(!i[f]&&r.equals(o.value,s.value,o.value,s.value,e,t,r)){u=i[f]=!0;break}f++}if(!u)return!1}return!0}function xc(e,t){let r=e.byteLength;if(t.byteLength!==r||e.byteOffset!==t.byteOffset)return!1;for(;r-- >0;)if(e[r]!==t[r])return!1;return!0}function uK(e,t){return e.hostname===t.hostname&&e.pathname===t.pathname&&e.protocol===t.protocol&&e.port===t.port&&e.hash===t.hash&&e.username===t.username&&e.password===t.password}function yP(e,t,r,n){return(n===ZU||n===QU||n===XU)&&(e.$$typeof||t.$$typeof)?!0:qU(t,n)&&r.equals(e[n],t[n],n,n,e,t,r)}const cK="[object ArrayBuffer]",fK="[object Arguments]",dK="[object Boolean]",pK="[object DataView]",hK="[object Date]",mK="[object Error]",vK="[object Map]",yK="[object Number]",gK="[object Object]",xK="[object RegExp]",bK="[object Set]",wK="[object String]",jK={"[object Int8Array]":!0,"[object Uint8Array]":!0,"[object Uint8ClampedArray]":!0,"[object Int16Array]":!0,"[object Uint16Array]":!0,"[object Int32Array]":!0,"[object Uint32Array]":!0,"[object Float16Array]":!0,"[object Float32Array]":!0,"[object Float64Array]":!0,"[object BigInt64Array]":!0,"[object BigUint64Array]":!0},SK="[object URL]",OK=Object.prototype.toString;function _K({areArrayBuffersEqual:e,areArraysEqual:t,areDataViewsEqual:r,areDatesEqual:n,areErrorsEqual:i,areFunctionsEqual:a,areMapsEqual:o,areNumbersEqual:s,areObjectsEqual:l,arePrimitiveWrappersEqual:u,areRegExpsEqual:f,areSetsEqual:d,areTypedArraysEqual:p,areUrlsEqual:h,unknownTagComparators:m}){return function(x,y,v){if(x===y)return!0;if(x==null||y==null)return!1;const b=typeof x;if(b!==typeof y)return!1;if(b!=="object")return b==="number"?s(x,y,v):b==="function"?a(x,y,v):!1;const S=x.constructor;if(S!==y.constructor)return!1;if(S===Object)return l(x,y,v);if(Array.isArray(x))return t(x,y,v);if(S===Date)return n(x,y,v);if(S===RegExp)return f(x,y,v);if(S===Map)return o(x,y,v);if(S===Set)return d(x,y,v);const w=OK.call(x);if(w===hK)return n(x,y,v);if(w===xK)return f(x,y,v);if(w===vK)return o(x,y,v);if(w===bK)return d(x,y,v);if(w===gK)return typeof x.then!="function"&&typeof y.then!="function"&&l(x,y,v);if(w===SK)return h(x,y,v);if(w===mK)return i(x,y,v);if(w===fK)return l(x,y,v);if(jK[w])return p(x,y,v);if(w===cK)return e(x,y,v);if(w===pK)return r(x,y,v);if(w===dK||w===yK||w===wK)return u(x,y,v);if(m){let j=m[w];if(!j){const O=YU(x);O&&(j=m[O])}if(j)return j(x,y,v)}return!1}}function PK({circular:e,createCustomConfig:t,strict:r}){let n={areArrayBuffersEqual:JU,areArraysEqual:r?Mo:eK,areDataViewsEqual:tK,areDatesEqual:rK,areErrorsEqual:nK,areFunctionsEqual:iK,areMapsEqual:r?ep(Ub,Mo):Ub,areNumbersEqual:aK,areObjectsEqual:r?Mo:oK,arePrimitiveWrappersEqual:sK,areRegExpsEqual:lK,areSetsEqual:r?ep(Kb,Mo):Kb,areTypedArraysEqual:r?ep(xc,Mo):xc,areUrlsEqual:uK,unknownTagComparators:void 0};if(t&&(n=Object.assign({},n,t(n))),e){const i=Jl(n.areArraysEqual),a=Jl(n.areMapsEqual),o=Jl(n.areObjectsEqual),s=Jl(n.areSetsEqual);n=Object.assign({},n,{areArraysEqual:i,areMapsEqual:a,areObjectsEqual:o,areSetsEqual:s})}return n}function kK(e){return function(t,r,n,i,a,o,s){return e(t,r,s)}}function AK({circular:e,comparator:t,createState:r,equals:n,strict:i}){if(r)return function(s,l){const{cache:u=e?new WeakMap:void 0,meta:f}=r();return t(s,l,{cache:u,equals:n,meta:f,strict:i})};if(e)return function(s,l){return t(s,l,{cache:new WeakMap,equals:n,meta:void 0,strict:i})};const a={cache:void 0,equals:n,meta:void 0,strict:i};return function(s,l){return t(s,l,a)}}const NK=Xn();Xn({strict:!0});Xn({circular:!0});Xn({circular:!0,strict:!0});Xn({createInternalComparator:()=>Di});Xn({strict:!0,createInternalComparator:()=>Di});Xn({circular:!0,createInternalComparator:()=>Di});Xn({circular:!0,createInternalComparator:()=>Di,strict:!0});function Xn(e={}){const{circular:t=!1,createInternalComparator:r,createState:n,strict:i=!1}=e,a=PK(e),o=_K(a),s=r?r(o):kK(o);return AK({circular:t,comparator:o,createState:n,equals:s,strict:i})}function $K(e){typeof requestAnimationFrame<"u"&&requestAnimationFrame(e)}function Hb(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,r=-1,n=function i(a){r<0&&(r=a),a-r>t?(e(a),r=-1):$K(i)};requestAnimationFrame(n)}function Jh(e){"@babel/helpers - typeof";return Jh=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Jh(e)}function EK(e){return IK(e)||MK(e)||CK(e)||TK()}function TK(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
-In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function CK(e,t){if(e){if(typeof e=="string")return Vb(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return Vb(e,t)}}function Vb(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function MK(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function IK(e){if(Array.isArray(e))return e}function LK(){var e={},t=function(){return null},r=!1,n=function i(a){if(!r){if(Array.isArray(a)){if(!a.length)return;var o=a,s=EK(o),l=s[0],u=s.slice(1);if(typeof l=="number"){Hb(i.bind(null,u),l);return}i(l),Hb(i.bind(null,u));return}Jh(a)==="object"&&(e=a,t(e)),typeof a=="function"&&a()}};return{stop:function(){r=!0},start:function(a){r=!1,n(a)},subscribe:function(a){return t=a,function(){t=function(){return null}}}}}function Vs(e){"@babel/helpers - typeof";return Vs=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Vs(e)}function Gb(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function Yb(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Gb(Object(r),!0).forEach(function(n){gP(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Gb(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function gP(e,t,r){return t=DK(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function DK(e){var t=RK(e,"string");return Vs(t)==="symbol"?t:String(t)}function RK(e,t){if(Vs(e)!=="object"||e===null)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(Vs(n)!=="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var BK=function(t,r){return[Object.keys(t),Object.keys(r)].reduce(function(n,i){return n.filter(function(a){return i.includes(a)})})},FK=function(t){return t},zK=function(t){return t.replace(/([A-Z])/g,function(r){return"-".concat(r.toLowerCase())})},Jo=function(t,r){return Object.keys(r).reduce(function(n,i){return Yb(Yb({},n),{},gP({},i,t(i,r[i])))},{})},qb=function(t,r,n){return t.map(function(i){return"".concat(zK(i)," ").concat(r,"ms ").concat(n)}).join(",")};function WK(e,t){return HK(e)||KK(e,t)||xP(e,t)||UK()}function UK(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
-In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function KK(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,i,a,o,s=[],l=!0,u=!1;try{if(a=(r=r.call(e)).next,t!==0)for(;!(l=(n=a.call(r)).done)&&(s.push(n.value),s.length!==t);l=!0);}catch(f){u=!0,i=f}finally{try{if(!l&&r.return!=null&&(o=r.return(),Object(o)!==o))return}finally{if(u)throw i}}return s}}function HK(e){if(Array.isArray(e))return e}function VK(e){return qK(e)||YK(e)||xP(e)||GK()}function GK(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
-In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function xP(e,t){if(e){if(typeof e=="string")return em(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return em(e,t)}}function YK(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function qK(e){if(Array.isArray(e))return em(e)}function em(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}var bc=1e-4,bP=function(t,r){return[0,3*t,3*r-6*t,3*t-3*r+1]},wP=function(t,r){return t.map(function(n,i){return n*Math.pow(r,i)}).reduce(function(n,i){return n+i})},Xb=function(t,r){return function(n){var i=bP(t,r);return wP(i,n)}},XK=function(t,r){return function(n){var i=bP(t,r),a=[].concat(VK(i.map(function(o,s){return o*s}).slice(1)),[0]);return wP(a,n)}},Qb=function(){for(var t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];var i=r[0],a=r[1],o=r[2],s=r[3];if(r.length===1)switch(r[0]){case"linear":i=0,a=0,o=1,s=1;break;case"ease":i=.25,a=.1,o=.25,s=1;break;case"ease-in":i=.42,a=0,o=1,s=1;break;case"ease-out":i=.42,a=0,o=.58,s=1;break;case"ease-in-out":i=0,a=0,o=.58,s=1;break;default:{var l=r[0].split("(");if(l[0]==="cubic-bezier"&&l[1].split(")")[0].split(",").length===4){var u=l[1].split(")")[0].split(",").map(function(x){return parseFloat(x)}),f=WK(u,4);i=f[0],a=f[1],o=f[2],s=f[3]}}}var d=Xb(i,o),p=Xb(a,s),h=XK(i,o),m=function(y){return y>1?1:y<0?0:y},g=function(y){for(var v=y>1?1:y,b=v,S=0;S<8;++S){var w=d(b)-v,j=h(b);if(Math.abs(w-v)<bc||j<bc)return p(b);b=m(b-w/j)}return p(b)};return g.isStepper=!1,g},QK=function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},r=t.stiff,n=r===void 0?100:r,i=t.damping,a=i===void 0?8:i,o=t.dt,s=o===void 0?17:o,l=function(f,d,p){var h=-(f-d)*n,m=p*a,g=p+(h-m)*s/1e3,x=p*s/1e3+f;return Math.abs(x-d)<bc&&Math.abs(g)<bc?[d,0]:[x,g]};return l.isStepper=!0,l.dt=s,l},ZK=function(){for(var t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];var i=r[0];if(typeof i=="string")switch(i){case"ease":case"ease-in-out":case"ease-out":case"ease-in":case"linear":return Qb(i);case"spring":return QK();default:if(i.split("(")[0]==="cubic-bezier")return Qb(i)}return typeof i=="function"?i:null};function Gs(e){"@babel/helpers - typeof";return Gs=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Gs(e)}function Zb(e){return tH(e)||eH(e)||jP(e)||JK()}function JK(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
-In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function eH(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function tH(e){if(Array.isArray(e))return rm(e)}function Jb(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function it(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Jb(Object(r),!0).forEach(function(n){tm(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Jb(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function tm(e,t,r){return t=rH(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function rH(e){var t=nH(e,"string");return Gs(t)==="symbol"?t:String(t)}function nH(e,t){if(Gs(e)!=="object"||e===null)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(Gs(n)!=="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function iH(e,t){return sH(e)||oH(e,t)||jP(e,t)||aH()}function aH(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
-In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function jP(e,t){if(e){if(typeof e=="string")return rm(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return rm(e,t)}}function rm(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function oH(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,i,a,o,s=[],l=!0,u=!1;try{if(a=(r=r.call(e)).next,t!==0)for(;!(l=(n=a.call(r)).done)&&(s.push(n.value),s.length!==t);l=!0);}catch(f){u=!0,i=f}finally{try{if(!l&&r.return!=null&&(o=r.return(),Object(o)!==o))return}finally{if(u)throw i}}return s}}function sH(e){if(Array.isArray(e))return e}var wc=function(t,r,n){return t+(r-t)*n},nm=function(t){var r=t.from,n=t.to;return r!==n},lH=function e(t,r,n){var i=Jo(function(a,o){if(nm(o)){var s=t(o.from,o.to,o.velocity),l=iH(s,2),u=l[0],f=l[1];return it(it({},o),{},{from:u,velocity:f})}return o},r);return n<1?Jo(function(a,o){return nm(o)?it(it({},o),{},{velocity:wc(o.velocity,i[a].velocity,n),from:wc(o.from,i[a].from,n)}):o},r):e(t,i,n-1)};const uH=function(e,t,r,n,i){var a=BK(e,t),o=a.reduce(function(x,y){return it(it({},x),{},tm({},y,[e[y],t[y]]))},{}),s=a.reduce(function(x,y){return it(it({},x),{},tm({},y,{from:e[y],velocity:0,to:t[y]}))},{}),l=-1,u,f,d=function(){return null},p=function(){return Jo(function(y,v){return v.from},s)},h=function(){return!Object.values(s).filter(nm).length},m=function(y){u||(u=y);var v=y-u,b=v/r.dt;s=lH(r,s,b),i(it(it(it({},e),t),p())),u=y,h()||(l=requestAnimationFrame(d))},g=function(y){f||(f=y);var v=(y-f)/n,b=Jo(function(w,j){return wc.apply(void 0,Zb(j).concat([r(v)]))},o);if(i(it(it(it({},e),t),b)),v<1)l=requestAnimationFrame(d);else{var S=Jo(function(w,j){return wc.apply(void 0,Zb(j).concat([r(1)]))},o);i(it(it(it({},e),t),S))}};return d=r.isStepper?m:g,function(){return requestAnimationFrame(d),function(){cancelAnimationFrame(l)}}};function Ma(e){"@babel/helpers - typeof";return Ma=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Ma(e)}var cH=["children","begin","duration","attributeName","easing","isActive","steps","from","to","canBegin","onAnimationEnd","shouldReAnimate","onAnimationReStart"];function fH(e,t){if(e==null)return{};var r=dH(e,t),n,i;if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i<a.length;i++)n=a[i],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function dH(e,t){if(e==null)return{};var r={},n=Object.keys(e),i,a;for(a=0;a<n.length;a++)i=n[a],!(t.indexOf(i)>=0)&&(r[i]=e[i]);return r}function tp(e){return vH(e)||mH(e)||hH(e)||pH()}function pH(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
-In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function hH(e,t){if(e){if(typeof e=="string")return im(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return im(e,t)}}function mH(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function vH(e){if(Array.isArray(e))return im(e)}function im(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function e1(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function cr(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?e1(Object(r),!0).forEach(function(n){Fo(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):e1(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function Fo(e,t,r){return t=SP(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function yH(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function gH(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,SP(n.key),n)}}function xH(e,t,r){return t&&gH(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function SP(e){var t=bH(e,"string");return Ma(t)==="symbol"?t:String(t)}function bH(e,t){if(Ma(e)!=="object"||e===null)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(Ma(n)!=="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function wH(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&am(e,t)}function am(e,t){return am=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,i){return n.__proto__=i,n},am(e,t)}function jH(e){var t=SH();return function(){var n=jc(e),i;if(t){var a=jc(this).constructor;i=Reflect.construct(n,arguments,a)}else i=n.apply(this,arguments);return om(this,i)}}function om(e,t){if(t&&(Ma(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return sm(e)}function sm(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function SH(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function jc(e){return jc=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},jc(e)}var or=function(e){wH(r,e);var t=jH(r);function r(n,i){var a;yH(this,r),a=t.call(this,n,i);var o=a.props,s=o.isActive,l=o.attributeName,u=o.from,f=o.to,d=o.steps,p=o.children,h=o.duration;if(a.handleStyleChange=a.handleStyleChange.bind(sm(a)),a.changeStyle=a.changeStyle.bind(sm(a)),!s||h<=0)return a.state={style:{}},typeof p=="function"&&(a.state={style:f}),om(a);if(d&&d.length)a.state={style:d[0].style};else if(u){if(typeof p=="function")return a.state={style:u},om(a);a.state={style:l?Fo({},l,u):u}}else a.state={style:{}};return a}return xH(r,[{key:"componentDidMount",value:function(){var i=this.props,a=i.isActive,o=i.canBegin;this.mounted=!0,!(!a||!o)&&this.runAnimation(this.props)}},{key:"componentDidUpdate",value:function(i){var a=this.props,o=a.isActive,s=a.canBegin,l=a.attributeName,u=a.shouldReAnimate,f=a.to,d=a.from,p=this.state.style;if(s){if(!o){var h={style:l?Fo({},l,f):f};this.state&&p&&(l&&p[l]!==f||!l&&p!==f)&&this.setState(h);return}if(!(NK(i.to,f)&&i.canBegin&&i.isActive)){var m=!i.canBegin||!i.isActive;this.manager&&this.manager.stop(),this.stopJSAnimation&&this.stopJSAnimation();var g=m||u?d:i.to;if(this.state&&p){var x={style:l?Fo({},l,g):g};(l&&p[l]!==g||!l&&p!==g)&&this.setState(x)}this.runAnimation(cr(cr({},this.props),{},{from:g,begin:0}))}}}},{key:"componentWillUnmount",value:function(){this.mounted=!1;var i=this.props.onAnimationEnd;this.unSubscribe&&this.unSubscribe(),this.manager&&(this.manager.stop(),this.manager=null),this.stopJSAnimation&&this.stopJSAnimation(),i&&i()}},{key:"handleStyleChange",value:function(i){this.changeStyle(i)}},{key:"changeStyle",value:function(i){this.mounted&&this.setState({style:i})}},{key:"runJSAnimation",value:function(i){var a=this,o=i.from,s=i.to,l=i.duration,u=i.easing,f=i.begin,d=i.onAnimationEnd,p=i.onAnimationStart,h=uH(o,s,ZK(u),l,this.changeStyle),m=function(){a.stopJSAnimation=h()};this.manager.start([p,f,m,l,d])}},{key:"runStepAnimation",value:function(i){var a=this,o=i.steps,s=i.begin,l=i.onAnimationStart,u=o[0],f=u.style,d=u.duration,p=d===void 0?0:d,h=function(g,x,y){if(y===0)return g;var v=x.duration,b=x.easing,S=b===void 0?"ease":b,w=x.style,j=x.properties,O=x.onAnimationEnd,_=y>0?o[y-1]:x,P=j||Object.keys(w);if(typeof S=="function"||S==="spring")return[].concat(tp(g),[a.runJSAnimation.bind(a,{from:_.style,to:w,duration:v,easing:S}),v]);var N=qb(P,v,S),T=cr(cr(cr({},_.style),w),{},{transition:N});return[].concat(tp(g),[T,v,O]).filter(FK)};return this.manager.start([l].concat(tp(o.reduce(h,[f,Math.max(p,s)])),[i.onAnimationEnd]))}},{key:"runAnimation",value:function(i){this.manager||(this.manager=LK());var a=i.begin,o=i.duration,s=i.attributeName,l=i.to,u=i.easing,f=i.onAnimationStart,d=i.onAnimationEnd,p=i.steps,h=i.children,m=this.manager;if(this.unSubscribe=m.subscribe(this.handleStyleChange),typeof u=="function"||typeof h=="function"||u==="spring"){this.runJSAnimation(i);return}if(p.length>1){this.runStepAnimation(i);return}var g=s?Fo({},s,l):l,x=qb(Object.keys(g),o,u);m.start([f,a,cr(cr({},g),{},{transition:x}),o,d])}},{key:"render",value:function(){var i=this.props,a=i.children;i.begin;var o=i.duration;i.attributeName,i.easing;var s=i.isActive;i.steps,i.from,i.to,i.canBegin,i.onAnimationEnd,i.shouldReAnimate,i.onAnimationReStart;var l=fH(i,cH),u=k.Children.count(a),f=this.state.style;if(typeof a=="function")return a(f);if(!s||u===0||o<=0)return a;var d=function(h){var m=h.props,g=m.style,x=g===void 0?{}:g,y=m.className,v=k.cloneElement(h,cr(cr({},l),{},{style:cr(cr({},x),f),className:y}));return v};return u===1?d(k.Children.only(a)):A.createElement("div",null,k.Children.map(a,function(p){return d(p)}))}}]),r}(k.PureComponent);or.displayName="Animate";or.defaultProps={begin:0,duration:1e3,from:"",to:"",attributeName:"",easing:"ease",isActive:!0,canBegin:!0,steps:[],onAnimationEnd:function(){},onAnimationStart:function(){}};or.propTypes={from:ce.oneOfType([ce.object,ce.string]),to:ce.oneOfType([ce.object,ce.string]),attributeName:ce.string,duration:ce.number,begin:ce.number,easing:ce.oneOfType([ce.string,ce.func]),steps:ce.arrayOf(ce.shape({duration:ce.number.isRequired,style:ce.object.isRequired,easing:ce.oneOfType([ce.oneOf(["ease","ease-in","ease-out","ease-in-out","linear"]),ce.func]),properties:ce.arrayOf("string"),onAnimationEnd:ce.func})),children:ce.oneOfType([ce.node,ce.func]),isActive:ce.bool,canBegin:ce.bool,onAnimationEnd:ce.func,shouldReAnimate:ce.bool,onAnimationStart:ce.func,onAnimationReStart:ce.func};function Ys(e){"@babel/helpers - typeof";return Ys=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Ys(e)}function Sc(){return Sc=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},Sc.apply(this,arguments)}function OH(e,t){return AH(e)||kH(e,t)||PH(e,t)||_H()}function _H(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
-In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function PH(e,t){if(e){if(typeof e=="string")return t1(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return t1(e,t)}}function t1(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function kH(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,i,a,o,s=[],l=!0,u=!1;try{if(a=(r=r.call(e)).next,t!==0)for(;!(l=(n=a.call(r)).done)&&(s.push(n.value),s.length!==t);l=!0);}catch(f){u=!0,i=f}finally{try{if(!l&&r.return!=null&&(o=r.return(),Object(o)!==o))return}finally{if(u)throw i}}return s}}function AH(e){if(Array.isArray(e))return e}function r1(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function n1(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?r1(Object(r),!0).forEach(function(n){NH(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):r1(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function NH(e,t,r){return t=$H(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function $H(e){var t=EH(e,"string");return Ys(t)=="symbol"?t:t+""}function EH(e,t){if(Ys(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(Ys(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var i1=function(t,r,n,i,a){var o=Math.min(Math.abs(n)/2,Math.abs(i)/2),s=i>=0?1:-1,l=n>=0?1:-1,u=i>=0&&n>=0||i<0&&n<0?1:0,f;if(o>0&&a instanceof Array){for(var d=[0,0,0,0],p=0,h=4;p<h;p++)d[p]=a[p]>o?o:a[p];f="M".concat(t,",").concat(r+s*d[0]),d[0]>0&&(f+="A ".concat(d[0],",").concat(d[0],",0,0,").concat(u,",").concat(t+l*d[0],",").concat(r)),f+="L ".concat(t+n-l*d[1],",").concat(r),d[1]>0&&(f+="A ".concat(d[1],",").concat(d[1],",0,0,").concat(u,`,
- `).concat(t+n,",").concat(r+s*d[1])),f+="L ".concat(t+n,",").concat(r+i-s*d[2]),d[2]>0&&(f+="A ".concat(d[2],",").concat(d[2],",0,0,").concat(u,`,
- `).concat(t+n-l*d[2],",").concat(r+i)),f+="L ".concat(t+l*d[3],",").concat(r+i),d[3]>0&&(f+="A ".concat(d[3],",").concat(d[3],",0,0,").concat(u,`,
- `).concat(t,",").concat(r+i-s*d[3])),f+="Z"}else if(o>0&&a===+a&&a>0){var m=Math.min(o,a);f="M ".concat(t,",").concat(r+s*m,`
- A `).concat(m,",").concat(m,",0,0,").concat(u,",").concat(t+l*m,",").concat(r,`
- L `).concat(t+n-l*m,",").concat(r,`
- A `).concat(m,",").concat(m,",0,0,").concat(u,",").concat(t+n,",").concat(r+s*m,`
- L `).concat(t+n,",").concat(r+i-s*m,`
- A `).concat(m,",").concat(m,",0,0,").concat(u,",").concat(t+n-l*m,",").concat(r+i,`
- L `).concat(t+l*m,",").concat(r+i,`
- A `).concat(m,",").concat(m,",0,0,").concat(u,",").concat(t,",").concat(r+i-s*m," Z")}else f="M ".concat(t,",").concat(r," h ").concat(n," v ").concat(i," h ").concat(-n," Z");return f},TH=function(t,r){if(!t||!r)return!1;var n=t.x,i=t.y,a=r.x,o=r.y,s=r.width,l=r.height;if(Math.abs(s)>0&&Math.abs(l)>0){var u=Math.min(a,a+s),f=Math.max(a,a+s),d=Math.min(o,o+l),p=Math.max(o,o+l);return n>=u&&n<=f&&i>=d&&i<=p}return!1},CH={x:0,y:0,width:0,height:0,radius:0,isAnimationActive:!1,isUpdateAnimationActive:!1,animationBegin:0,animationDuration:1500,animationEasing:"ease"},Ey=function(t){var r=n1(n1({},CH),t),n=k.useRef(),i=k.useState(-1),a=OH(i,2),o=a[0],s=a[1];k.useEffect(function(){if(n.current&&n.current.getTotalLength)try{var S=n.current.getTotalLength();S&&s(S)}catch{}},[]);var l=r.x,u=r.y,f=r.width,d=r.height,p=r.radius,h=r.className,m=r.animationEasing,g=r.animationDuration,x=r.animationBegin,y=r.isAnimationActive,v=r.isUpdateAnimationActive;if(l!==+l||u!==+u||f!==+f||d!==+d||f===0||d===0)return null;var b=ee("recharts-rectangle",h);return v?A.createElement(or,{canBegin:o>0,from:{width:f,height:d,x:l,y:u},to:{width:f,height:d,x:l,y:u},duration:g,animationEasing:m,isActive:v},function(S){var w=S.width,j=S.height,O=S.x,_=S.y;return A.createElement(or,{canBegin:o>0,from:"0px ".concat(o===-1?1:o,"px"),to:"".concat(o,"px 0px"),attributeName:"strokeDasharray",begin:x,duration:g,isActive:y,easing:m},A.createElement("path",Sc({},q(r,!0),{className:b,d:i1(O,_,w,j,p),ref:n})))}):A.createElement("path",Sc({},q(r,!0),{className:b,d:i1(l,u,f,d,p)}))},MH=["points","className","baseLinePoints","connectNulls"];function ia(){return ia=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},ia.apply(this,arguments)}function IH(e,t){if(e==null)return{};var r=LH(e,t),n,i;if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i<a.length;i++)n=a[i],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function LH(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function a1(e){return FH(e)||BH(e)||RH(e)||DH()}function DH(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
-In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function RH(e,t){if(e){if(typeof e=="string")return lm(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return lm(e,t)}}function BH(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function FH(e){if(Array.isArray(e))return lm(e)}function lm(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}var o1=function(t){return t&&t.x===+t.x&&t.y===+t.y},zH=function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],r=[[]];return t.forEach(function(n){o1(n)?r[r.length-1].push(n):r[r.length-1].length>0&&r.push([])}),o1(t[0])&&r[r.length-1].push(t[0]),r[r.length-1].length<=0&&(r=r.slice(0,-1)),r},es=function(t,r){var n=zH(t);r&&(n=[n.reduce(function(a,o){return[].concat(a1(a),a1(o))},[])]);var i=n.map(function(a){return a.reduce(function(o,s,l){return"".concat(o).concat(l===0?"M":"L").concat(s.x,",").concat(s.y)},"")}).join("");return n.length===1?"".concat(i,"Z"):i},WH=function(t,r,n){var i=es(t,n);return"".concat(i.slice(-1)==="Z"?i.slice(0,-1):i,"L").concat(es(r.reverse(),n).slice(1))},UH=function(t){var r=t.points,n=t.className,i=t.baseLinePoints,a=t.connectNulls,o=IH(t,MH);if(!r||!r.length)return null;var s=ee("recharts-polygon",n);if(i&&i.length){var l=o.stroke&&o.stroke!=="none",u=WH(r,i,a);return A.createElement("g",{className:s},A.createElement("path",ia({},q(o,!0),{fill:u.slice(-1)==="Z"?o.fill:"none",stroke:"none",d:u})),l?A.createElement("path",ia({},q(o,!0),{fill:"none",d:es(r,a)})):null,l?A.createElement("path",ia({},q(o,!0),{fill:"none",d:es(i,a)})):null)}var f=es(r,a);return A.createElement("path",ia({},q(o,!0),{fill:f.slice(-1)==="Z"?o.fill:"none",className:s,d:f}))};function um(){return um=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},um.apply(this,arguments)}var xl=function(t){var r=t.cx,n=t.cy,i=t.r,a=t.className,o=ee("recharts-dot",a);return r===+r&&n===+n&&i===+i?k.createElement("circle",um({},q(t,!1),Wu(t),{className:o,cx:r,cy:n,r:i})):null};function qs(e){"@babel/helpers - typeof";return qs=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},qs(e)}var KH=["x","y","top","left","width","height","className"];function cm(){return cm=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},cm.apply(this,arguments)}function s1(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function HH(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?s1(Object(r),!0).forEach(function(n){VH(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):s1(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function VH(e,t,r){return t=GH(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function GH(e){var t=YH(e,"string");return qs(t)=="symbol"?t:t+""}function YH(e,t){if(qs(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(qs(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function qH(e,t){if(e==null)return{};var r=XH(e,t),n,i;if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i<a.length;i++)n=a[i],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function XH(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}var QH=function(t,r,n,i,a,o){return"M".concat(t,",").concat(a,"v").concat(i,"M").concat(o,",").concat(r,"h").concat(n)},ZH=function(t){var r=t.x,n=r===void 0?0:r,i=t.y,a=i===void 0?0:i,o=t.top,s=o===void 0?0:o,l=t.left,u=l===void 0?0:l,f=t.width,d=f===void 0?0:f,p=t.height,h=p===void 0?0:p,m=t.className,g=qH(t,KH),x=HH({x:n,y:a,top:s,left:u,width:d,height:h},g);return!K(n)||!K(a)||!K(d)||!K(h)||!K(s)||!K(u)?null:A.createElement("path",cm({},q(x,!0),{className:ee("recharts-cross",m),d:QH(n,a,d,h,s,u)}))},JH=zf,eV=I_,tV=Lr;function rV(e,t){return e&&e.length?JH(e,tV(t),eV):void 0}var nV=rV;const iV=de(nV);var aV=zf,oV=Lr,sV=L_;function lV(e,t){return e&&e.length?aV(e,oV(t),sV):void 0}var uV=lV;const cV=de(uV);var fV=["cx","cy","angle","ticks","axisLine"],dV=["ticks","tick","angle","tickFormatter","stroke"];function Ia(e){"@babel/helpers - typeof";return Ia=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Ia(e)}function ts(){return ts=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},ts.apply(this,arguments)}function l1(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function ei(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?l1(Object(r),!0).forEach(function(n){Hf(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):l1(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function u1(e,t){if(e==null)return{};var r=pV(e,t),n,i;if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i<a.length;i++)n=a[i],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function pV(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function hV(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function c1(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,_P(n.key),n)}}function mV(e,t,r){return t&&c1(e.prototype,t),r&&c1(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function vV(e,t,r){return t=Oc(t),yV(e,OP()?Reflect.construct(t,r||[],Oc(e).constructor):t.apply(e,r))}function yV(e,t){if(t&&(Ia(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return gV(e)}function gV(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function OP(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(OP=function(){return!!e})()}function Oc(e){return Oc=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},Oc(e)}function xV(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&fm(e,t)}function fm(e,t){return fm=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,i){return n.__proto__=i,n},fm(e,t)}function Hf(e,t,r){return t=_P(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function _P(e){var t=bV(e,"string");return Ia(t)=="symbol"?t:t+""}function bV(e,t){if(Ia(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(Ia(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var Vf=function(e){function t(){return hV(this,t),vV(this,t,arguments)}return xV(t,e),mV(t,[{key:"getTickValueCoord",value:function(n){var i=n.coordinate,a=this.props,o=a.angle,s=a.cx,l=a.cy;return xe(s,l,i,o)}},{key:"getTickTextAnchor",value:function(){var n=this.props.orientation,i;switch(n){case"left":i="end";break;case"right":i="start";break;default:i="middle";break}return i}},{key:"getViewBox",value:function(){var n=this.props,i=n.cx,a=n.cy,o=n.angle,s=n.ticks,l=iV(s,function(f){return f.coordinate||0}),u=cV(s,function(f){return f.coordinate||0});return{cx:i,cy:a,startAngle:o,endAngle:o,innerRadius:u.coordinate||0,outerRadius:l.coordinate||0}}},{key:"renderAxisLine",value:function(){var n=this.props,i=n.cx,a=n.cy,o=n.angle,s=n.ticks,l=n.axisLine,u=u1(n,fV),f=s.reduce(function(m,g){return[Math.min(m[0],g.coordinate),Math.max(m[1],g.coordinate)]},[1/0,-1/0]),d=xe(i,a,f[0],o),p=xe(i,a,f[1],o),h=ei(ei(ei({},q(u,!1)),{},{fill:"none"},q(l,!1)),{},{x1:d.x,y1:d.y,x2:p.x,y2:p.y});return A.createElement("line",ts({className:"recharts-polar-radius-axis-line"},h))}},{key:"renderTicks",value:function(){var n=this,i=this.props,a=i.ticks,o=i.tick,s=i.angle,l=i.tickFormatter,u=i.stroke,f=u1(i,dV),d=this.getTickTextAnchor(),p=q(f,!1),h=q(o,!1),m=a.map(function(g,x){var y=n.getTickValueCoord(g),v=ei(ei(ei(ei({textAnchor:d,transform:"rotate(".concat(90-s,", ").concat(y.x,", ").concat(y.y,")")},p),{},{stroke:"none",fill:u},h),{},{index:x},y),{},{payload:g});return A.createElement(te,ts({className:ee("recharts-polar-radius-axis-tick",cP(o)),key:"tick-".concat(g.coordinate)},Bn(n.props,g,x)),t.renderTickItem(o,v,l?l(g.value,x):g.value))});return A.createElement(te,{className:"recharts-polar-radius-axis-ticks"},m)}},{key:"render",value:function(){var n=this.props,i=n.ticks,a=n.axisLine,o=n.tick;return!i||!i.length?null:A.createElement(te,{className:ee("recharts-polar-radius-axis",this.props.className)},a&&this.renderAxisLine(),o&&this.renderTicks(),et.renderCallByParent(this.props,this.getViewBox()))}}],[{key:"renderTickItem",value:function(n,i,a){var o;return A.isValidElement(n)?o=A.cloneElement(n,i):Z(n)?o=n(i):o=A.createElement(ki,ts({},i,{className:"recharts-polar-radius-axis-tick-value"}),a),o}}])}(k.PureComponent);Hf(Vf,"displayName","PolarRadiusAxis");Hf(Vf,"axisType","radiusAxis");Hf(Vf,"defaultProps",{type:"number",radiusAxisId:0,cx:0,cy:0,angle:0,orientation:"right",stroke:"#ccc",axisLine:!0,tick:!0,tickCount:5,allowDataOverflow:!1,scale:"auto",allowDuplicatedCategory:!0});function La(e){"@babel/helpers - typeof";return La=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},La(e)}function si(){return si=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},si.apply(this,arguments)}function f1(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function ti(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?f1(Object(r),!0).forEach(function(n){Gf(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):f1(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function wV(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function d1(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,kP(n.key),n)}}function jV(e,t,r){return t&&d1(e.prototype,t),r&&d1(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function SV(e,t,r){return t=_c(t),OV(e,PP()?Reflect.construct(t,r||[],_c(e).constructor):t.apply(e,r))}function OV(e,t){if(t&&(La(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return _V(e)}function _V(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function PP(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(PP=function(){return!!e})()}function _c(e){return _c=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},_c(e)}function PV(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&dm(e,t)}function dm(e,t){return dm=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,i){return n.__proto__=i,n},dm(e,t)}function Gf(e,t,r){return t=kP(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function kP(e){var t=kV(e,"string");return La(t)=="symbol"?t:t+""}function kV(e,t){if(La(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(La(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var AV=Math.PI/180,p1=1e-5,Yf=function(e){function t(){return wV(this,t),SV(this,t,arguments)}return PV(t,e),jV(t,[{key:"getTickLineCoord",value:function(n){var i=this.props,a=i.cx,o=i.cy,s=i.radius,l=i.orientation,u=i.tickSize,f=u||8,d=xe(a,o,s,n.coordinate),p=xe(a,o,s+(l==="inner"?-1:1)*f,n.coordinate);return{x1:d.x,y1:d.y,x2:p.x,y2:p.y}}},{key:"getTickTextAnchor",value:function(n){var i=this.props.orientation,a=Math.cos(-n.coordinate*AV),o;return a>p1?o=i==="outer"?"start":"end":a<-p1?o=i==="outer"?"end":"start":o="middle",o}},{key:"renderAxisLine",value:function(){var n=this.props,i=n.cx,a=n.cy,o=n.radius,s=n.axisLine,l=n.axisLineType,u=ti(ti({},q(this.props,!1)),{},{fill:"none"},q(s,!1));if(l==="circle")return A.createElement(xl,si({className:"recharts-polar-angle-axis-line"},u,{cx:i,cy:a,r:o}));var f=this.props.ticks,d=f.map(function(p){return xe(i,a,o,p.coordinate)});return A.createElement(UH,si({className:"recharts-polar-angle-axis-line"},u,{points:d}))}},{key:"renderTicks",value:function(){var n=this,i=this.props,a=i.ticks,o=i.tick,s=i.tickLine,l=i.tickFormatter,u=i.stroke,f=q(this.props,!1),d=q(o,!1),p=ti(ti({},f),{},{fill:"none"},q(s,!1)),h=a.map(function(m,g){var x=n.getTickLineCoord(m),y=n.getTickTextAnchor(m),v=ti(ti(ti({textAnchor:y},f),{},{stroke:"none",fill:u},d),{},{index:g,payload:m,x:x.x2,y:x.y2});return A.createElement(te,si({className:ee("recharts-polar-angle-axis-tick",cP(o)),key:"tick-".concat(m.coordinate)},Bn(n.props,m,g)),s&&A.createElement("line",si({className:"recharts-polar-angle-axis-tick-line"},p,x)),o&&t.renderTickItem(o,v,l?l(m.value,g):m.value))});return A.createElement(te,{className:"recharts-polar-angle-axis-ticks"},h)}},{key:"render",value:function(){var n=this.props,i=n.ticks,a=n.radius,o=n.axisLine;return a<=0||!i||!i.length?null:A.createElement(te,{className:ee("recharts-polar-angle-axis",this.props.className)},o&&this.renderAxisLine(),this.renderTicks())}}],[{key:"renderTickItem",value:function(n,i,a){var o;return A.isValidElement(n)?o=A.cloneElement(n,i):Z(n)?o=n(i):o=A.createElement(ki,si({},i,{className:"recharts-polar-angle-axis-tick-value"}),a),o}}])}(k.PureComponent);Gf(Yf,"displayName","PolarAngleAxis");Gf(Yf,"axisType","angleAxis");Gf(Yf,"defaultProps",{type:"category",angleAxisId:0,scale:"auto",cx:0,cy:0,orientation:"outer",axisLine:!0,tickLine:!0,tickSize:8,tick:!0,hide:!1,allowDuplicatedCategory:!0});var NV=TO,$V=NV(Object.getPrototypeOf,Object),EV=$V,TV=an,CV=EV,MV=on,IV="[object Object]",LV=Function.prototype,DV=Object.prototype,AP=LV.toString,RV=DV.hasOwnProperty,BV=AP.call(Object);function FV(e){if(!MV(e)||TV(e)!=IV)return!1;var t=CV(e);if(t===null)return!0;var r=RV.call(t,"constructor")&&t.constructor;return typeof r=="function"&&r instanceof r&&AP.call(r)==BV}var zV=FV;const WV=de(zV);var UV=an,KV=on,HV="[object Boolean]";function VV(e){return e===!0||e===!1||KV(e)&&UV(e)==HV}var GV=VV;const YV=de(GV);function Xs(e){"@babel/helpers - typeof";return Xs=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Xs(e)}function Pc(){return Pc=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},Pc.apply(this,arguments)}function qV(e,t){return JV(e)||ZV(e,t)||QV(e,t)||XV()}function XV(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
-In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function QV(e,t){if(e){if(typeof e=="string")return h1(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return h1(e,t)}}function h1(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function ZV(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,i,a,o,s=[],l=!0,u=!1;try{if(a=(r=r.call(e)).next,t!==0)for(;!(l=(n=a.call(r)).done)&&(s.push(n.value),s.length!==t);l=!0);}catch(f){u=!0,i=f}finally{try{if(!l&&r.return!=null&&(o=r.return(),Object(o)!==o))return}finally{if(u)throw i}}return s}}function JV(e){if(Array.isArray(e))return e}function m1(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function v1(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?m1(Object(r),!0).forEach(function(n){eG(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):m1(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function eG(e,t,r){return t=tG(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function tG(e){var t=rG(e,"string");return Xs(t)=="symbol"?t:t+""}function rG(e,t){if(Xs(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(Xs(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var y1=function(t,r,n,i,a){var o=n-i,s;return s="M ".concat(t,",").concat(r),s+="L ".concat(t+n,",").concat(r),s+="L ".concat(t+n-o/2,",").concat(r+a),s+="L ".concat(t+n-o/2-i,",").concat(r+a),s+="L ".concat(t,",").concat(r," Z"),s},nG={x:0,y:0,upperWidth:0,lowerWidth:0,height:0,isUpdateAnimationActive:!1,animationBegin:0,animationDuration:1500,animationEasing:"ease"},iG=function(t){var r=v1(v1({},nG),t),n=k.useRef(),i=k.useState(-1),a=qV(i,2),o=a[0],s=a[1];k.useEffect(function(){if(n.current&&n.current.getTotalLength)try{var b=n.current.getTotalLength();b&&s(b)}catch{}},[]);var l=r.x,u=r.y,f=r.upperWidth,d=r.lowerWidth,p=r.height,h=r.className,m=r.animationEasing,g=r.animationDuration,x=r.animationBegin,y=r.isUpdateAnimationActive;if(l!==+l||u!==+u||f!==+f||d!==+d||p!==+p||f===0&&d===0||p===0)return null;var v=ee("recharts-trapezoid",h);return y?A.createElement(or,{canBegin:o>0,from:{upperWidth:0,lowerWidth:0,height:p,x:l,y:u},to:{upperWidth:f,lowerWidth:d,height:p,x:l,y:u},duration:g,animationEasing:m,isActive:y},function(b){var S=b.upperWidth,w=b.lowerWidth,j=b.height,O=b.x,_=b.y;return A.createElement(or,{canBegin:o>0,from:"0px ".concat(o===-1?1:o,"px"),to:"".concat(o,"px 0px"),attributeName:"strokeDasharray",begin:x,duration:g,easing:m},A.createElement("path",Pc({},q(r,!0),{className:v,d:y1(O,_,S,w,j),ref:n})))}):A.createElement("g",null,A.createElement("path",Pc({},q(r,!0),{className:v,d:y1(l,u,f,d,p)})))},aG=["option","shapeType","propTransformer","activeClassName","isActive"];function Qs(e){"@babel/helpers - typeof";return Qs=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Qs(e)}function oG(e,t){if(e==null)return{};var r=sG(e,t),n,i;if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i<a.length;i++)n=a[i],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function sG(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function g1(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function kc(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?g1(Object(r),!0).forEach(function(n){lG(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):g1(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function lG(e,t,r){return t=uG(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function uG(e){var t=cG(e,"string");return Qs(t)=="symbol"?t:t+""}function cG(e,t){if(Qs(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(Qs(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function fG(e,t){return kc(kc({},t),e)}function dG(e,t){return e==="symbols"}function x1(e){var t=e.shapeType,r=e.elementProps;switch(t){case"rectangle":return A.createElement(Ey,r);case"trapezoid":return A.createElement(iG,r);case"sector":return A.createElement(pP,r);case"symbols":if(dG(t))return A.createElement(Ef,r);break;default:return null}}function pG(e){return k.isValidElement(e)?e.props:e}function Ac(e){var t=e.option,r=e.shapeType,n=e.propTransformer,i=n===void 0?fG:n,a=e.activeClassName,o=a===void 0?"recharts-active-shape":a,s=e.isActive,l=oG(e,aG),u;if(k.isValidElement(t))u=k.cloneElement(t,kc(kc({},l),pG(t)));else if(Z(t))u=t(l);else if(WV(t)&&!YV(t)){var f=i(t,l);u=A.createElement(x1,{shapeType:r,elementProps:f})}else{var d=l;u=A.createElement(x1,{shapeType:r,elementProps:d})}return s?A.createElement(te,{className:o},u):u}function qf(e,t){return t!=null&&"trapezoids"in e.props}function Xf(e,t){return t!=null&&"sectors"in e.props}function Zs(e,t){return t!=null&&"points"in e.props}function hG(e,t){var r,n,i=e.x===(t==null||(r=t.labelViewBox)===null||r===void 0?void 0:r.x)||e.x===t.x,a=e.y===(t==null||(n=t.labelViewBox)===null||n===void 0?void 0:n.y)||e.y===t.y;return i&&a}function mG(e,t){var r=e.endAngle===t.endAngle,n=e.startAngle===t.startAngle;return r&&n}function vG(e,t){var r=e.x===t.x,n=e.y===t.y,i=e.z===t.z;return r&&n&&i}function yG(e,t){var r;return qf(e,t)?r=hG:Xf(e,t)?r=mG:Zs(e,t)&&(r=vG),r}function gG(e,t){var r;return qf(e,t)?r="trapezoids":Xf(e,t)?r="sectors":Zs(e,t)&&(r="points"),r}function xG(e,t){if(qf(e,t)){var r;return(r=t.tooltipPayload)===null||r===void 0||(r=r[0])===null||r===void 0||(r=r.payload)===null||r===void 0?void 0:r.payload}if(Xf(e,t)){var n;return(n=t.tooltipPayload)===null||n===void 0||(n=n[0])===null||n===void 0||(n=n.payload)===null||n===void 0?void 0:n.payload}return Zs(e,t)?t.payload:{}}function bG(e){var t=e.activeTooltipItem,r=e.graphicalItem,n=e.itemData,i=gG(r,t),a=xG(r,t),o=n.filter(function(l,u){var f=Fn(a,l),d=r.props[i].filter(function(m){var g=yG(r,t);return g(m,t)}),p=r.props[i].indexOf(d[d.length-1]),h=u===p;return f&&h}),s=n.indexOf(o[o.length-1]);return s}var mu;function Da(e){"@babel/helpers - typeof";return Da=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Da(e)}function aa(){return aa=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},aa.apply(this,arguments)}function b1(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function ve(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?b1(Object(r),!0).forEach(function(n){Jt(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):b1(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function wG(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function w1(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,$P(n.key),n)}}function jG(e,t,r){return t&&w1(e.prototype,t),r&&w1(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function SG(e,t,r){return t=Nc(t),OG(e,NP()?Reflect.construct(t,r||[],Nc(e).constructor):t.apply(e,r))}function OG(e,t){if(t&&(Da(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return _G(e)}function _G(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function NP(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(NP=function(){return!!e})()}function Nc(e){return Nc=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},Nc(e)}function PG(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&pm(e,t)}function pm(e,t){return pm=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,i){return n.__proto__=i,n},pm(e,t)}function Jt(e,t,r){return t=$P(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function $P(e){var t=kG(e,"string");return Da(t)=="symbol"?t:t+""}function kG(e,t){if(Da(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(Da(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}var un=function(e){function t(r){var n;return wG(this,t),n=SG(this,t,[r]),Jt(n,"pieRef",null),Jt(n,"sectorRefs",[]),Jt(n,"id",Gn("recharts-pie-")),Jt(n,"handleAnimationEnd",function(){var i=n.props.onAnimationEnd;n.setState({isAnimationFinished:!0}),Z(i)&&i()}),Jt(n,"handleAnimationStart",function(){var i=n.props.onAnimationStart;n.setState({isAnimationFinished:!1}),Z(i)&&i()}),n.state={isAnimationFinished:!r.isAnimationActive,prevIsAnimationActive:r.isAnimationActive,prevAnimationId:r.animationId,sectorToFocus:0},n}return PG(t,e),jG(t,[{key:"isActiveIndex",value:function(n){var i=this.props.activeIndex;return Array.isArray(i)?i.indexOf(n)!==-1:n===i}},{key:"hasActiveIndex",value:function(){var n=this.props.activeIndex;return Array.isArray(n)?n.length!==0:n||n===0}},{key:"renderLabels",value:function(n){var i=this.props.isAnimationActive;if(i&&!this.state.isAnimationFinished)return null;var a=this.props,o=a.label,s=a.labelLine,l=a.dataKey,u=a.valueKey,f=q(this.props,!1),d=q(o,!1),p=q(s,!1),h=o&&o.offsetRadius||20,m=n.map(function(g,x){var y=(g.startAngle+g.endAngle)/2,v=xe(g.cx,g.cy,g.outerRadius+h,y),b=ve(ve(ve(ve({},f),g),{},{stroke:"none"},d),{},{index:x,textAnchor:t.getTextAnchor(v.x,g.cx)},v),S=ve(ve(ve(ve({},f),g),{},{fill:"none",stroke:g.fill},p),{},{index:x,points:[xe(g.cx,g.cy,g.outerRadius,y),v]}),w=l;return Q(l)&&Q(u)?w="value":Q(l)&&(w=u),A.createElement(te,{key:"label-".concat(g.startAngle,"-").concat(g.endAngle,"-").concat(g.midAngle,"-").concat(x)},s&&t.renderLabelLineItem(s,S,"line"),t.renderLabelItem(o,b,Oe(g,w)))});return A.createElement(te,{className:"recharts-pie-labels"},m)}},{key:"renderSectorsStatically",value:function(n){var i=this,a=this.props,o=a.activeShape,s=a.blendStroke,l=a.inactiveShape;return n.map(function(u,f){if((u==null?void 0:u.startAngle)===0&&(u==null?void 0:u.endAngle)===0&&n.length!==1)return null;var d=i.isActiveIndex(f),p=l&&i.hasActiveIndex()?l:null,h=d?o:p,m=ve(ve({},u),{},{stroke:s?u.fill:u.stroke,tabIndex:-1});return A.createElement(te,aa({ref:function(x){x&&!i.sectorRefs.includes(x)&&i.sectorRefs.push(x)},tabIndex:-1,className:"recharts-pie-sector"},Bn(i.props,u,f),{key:"sector-".concat(u==null?void 0:u.startAngle,"-").concat(u==null?void 0:u.endAngle,"-").concat(u.midAngle,"-").concat(f)}),A.createElement(Ac,aa({option:h,isActive:d,shapeType:"sector"},m)))})}},{key:"renderSectorsWithAnimation",value:function(){var n=this,i=this.props,a=i.sectors,o=i.isAnimationActive,s=i.animationBegin,l=i.animationDuration,u=i.animationEasing,f=i.animationId,d=this.state,p=d.prevSectors,h=d.prevIsAnimationActive;return A.createElement(or,{begin:s,duration:l,isActive:o,easing:u,from:{t:0},to:{t:1},key:"pie-".concat(f,"-").concat(h),onAnimationStart:this.handleAnimationStart,onAnimationEnd:this.handleAnimationEnd},function(m){var g=m.t,x=[],y=a&&a[0],v=y.startAngle;return a.forEach(function(b,S){var w=p&&p[S],j=S>0?Wt(b,"paddingAngle",0):0;if(w){var O=$e(w.endAngle-w.startAngle,b.endAngle-b.startAngle),_=ve(ve({},b),{},{startAngle:v+j,endAngle:v+O(g)+j});x.push(_),v=_.endAngle}else{var P=b.endAngle,N=b.startAngle,T=$e(0,P-N),$=T(g),I=ve(ve({},b),{},{startAngle:v+j,endAngle:v+$+j});x.push(I),v=I.endAngle}}),A.createElement(te,null,n.renderSectorsStatically(x))})}},{key:"attachKeyboardHandlers",value:function(n){var i=this;n.onkeydown=function(a){if(!a.altKey)switch(a.key){case"ArrowLeft":{var o=++i.state.sectorToFocus%i.sectorRefs.length;i.sectorRefs[o].focus(),i.setState({sectorToFocus:o});break}case"ArrowRight":{var s=--i.state.sectorToFocus<0?i.sectorRefs.length-1:i.state.sectorToFocus%i.sectorRefs.length;i.sectorRefs[s].focus(),i.setState({sectorToFocus:s});break}case"Escape":{i.sectorRefs[i.state.sectorToFocus].blur(),i.setState({sectorToFocus:0});break}}}}},{key:"renderSectors",value:function(){var n=this.props,i=n.sectors,a=n.isAnimationActive,o=this.state.prevSectors;return a&&i&&i.length&&(!o||!Fn(o,i))?this.renderSectorsWithAnimation():this.renderSectorsStatically(i)}},{key:"componentDidMount",value:function(){this.pieRef&&this.attachKeyboardHandlers(this.pieRef)}},{key:"render",value:function(){var n=this,i=this.props,a=i.hide,o=i.sectors,s=i.className,l=i.label,u=i.cx,f=i.cy,d=i.innerRadius,p=i.outerRadius,h=i.isAnimationActive,m=this.state.isAnimationFinished;if(a||!o||!o.length||!K(u)||!K(f)||!K(d)||!K(p))return null;var g=ee("recharts-pie",s);return A.createElement(te,{tabIndex:this.props.rootTabIndex,className:g,ref:function(y){n.pieRef=y}},this.renderSectors(),l&&this.renderLabels(o),et.renderCallByParent(this.props,null,!1),(!h||m)&&br.renderCallByParent(this.props,o,!1))}}],[{key:"getDerivedStateFromProps",value:function(n,i){return i.prevIsAnimationActive!==n.isAnimationActive?{prevIsAnimationActive:n.isAnimationActive,prevAnimationId:n.animationId,curSectors:n.sectors,prevSectors:[],isAnimationFinished:!0}:n.isAnimationActive&&n.animationId!==i.prevAnimationId?{prevAnimationId:n.animationId,curSectors:n.sectors,prevSectors:i.curSectors,isAnimationFinished:!0}:n.sectors!==i.curSectors?{curSectors:n.sectors,isAnimationFinished:!0}:null}},{key:"getTextAnchor",value:function(n,i){return n>i?"start":n<i?"end":"middle"}},{key:"renderLabelLineItem",value:function(n,i,a){if(A.isValidElement(n))return A.cloneElement(n,i);if(Z(n))return n(i);var o=ee("recharts-pie-label-line",typeof n!="boolean"?n.className:"");return A.createElement(Ln,aa({},i,{key:a,type:"linear",className:o}))}},{key:"renderLabelItem",value:function(n,i,a){if(A.isValidElement(n))return A.cloneElement(n,i);var o=a;if(Z(n)&&(o=n(i),A.isValidElement(o)))return o;var s=ee("recharts-pie-label-text",typeof n!="boolean"&&!Z(n)?n.className:"");return A.createElement(ki,aa({},i,{alignmentBaseline:"middle",className:s}),o)}}])}(k.PureComponent);mu=un;Jt(un,"displayName","Pie");Jt(un,"defaultProps",{stroke:"#fff",fill:"#808080",legendType:"rect",cx:"50%",cy:"50%",startAngle:0,endAngle:360,innerRadius:0,outerRadius:"80%",paddingAngle:0,labelLine:!0,hide:!1,minAngle:0,isAnimationActive:!sn.isSsr,animationBegin:400,animationDuration:1500,animationEasing:"ease",nameKey:"name",blendStroke:!1,rootTabIndex:0});Jt(un,"parseDeltaAngle",function(e,t){var r=yt(t-e),n=Math.min(Math.abs(t-e),360);return r*n});Jt(un,"getRealPieData",function(e){var t=e.data,r=e.children,n=q(e,!1),i=wt(r,jr);return t&&t.length?t.map(function(a,o){return ve(ve(ve({payload:a},n),a),i&&i[o]&&i[o].props)}):i&&i.length?i.map(function(a){return ve(ve({},n),a.props)}):[]});Jt(un,"parseCoordinateOfPie",function(e,t){var r=t.top,n=t.left,i=t.width,a=t.height,o=uP(i,a),s=n+gt(e.cx,i,i/2),l=r+gt(e.cy,a,a/2),u=gt(e.innerRadius,o,0),f=gt(e.outerRadius,o,o*.8),d=e.maxRadius||Math.sqrt(i*i+a*a)/2;return{cx:s,cy:l,innerRadius:u,outerRadius:f,maxRadius:d}});Jt(un,"getComposedData",function(e){var t=e.item,r=e.offset,n=t.type.defaultProps!==void 0?ve(ve({},t.type.defaultProps),t.props):t.props,i=mu.getRealPieData(n);if(!i||!i.length)return null;var a=n.cornerRadius,o=n.startAngle,s=n.endAngle,l=n.paddingAngle,u=n.dataKey,f=n.nameKey,d=n.valueKey,p=n.tooltipType,h=Math.abs(n.minAngle),m=mu.parseCoordinateOfPie(n,r),g=mu.parseDeltaAngle(o,s),x=Math.abs(g),y=u;Q(u)&&Q(d)?(xr(!1,`Use "dataKey" to specify the value of pie,
- the props "valueKey" will be deprecated in 1.1.0`),y="value"):Q(u)&&(xr(!1,`Use "dataKey" to specify the value of pie,
- the props "valueKey" will be deprecated in 1.1.0`),y=d);var v=i.filter(function(_){return Oe(_,y,0)!==0}).length,b=(x>=360?v:v-1)*l,S=x-v*h-b,w=i.reduce(function(_,P){var N=Oe(P,y,0);return _+(K(N)?N:0)},0),j;if(w>0){var O;j=i.map(function(_,P){var N=Oe(_,y,0),T=Oe(_,f,P),$=(K(N)?N:0)/w,I;P?I=O.endAngle+yt(g)*l*(N!==0?1:0):I=o;var D=I+yt(g)*((N!==0?h:0)+$*S),L=(I+D)/2,C=(m.innerRadius+m.outerRadius)/2,F=[{name:T,value:N,payload:_,dataKey:y,type:p}],M=xe(m.cx,m.cy,C,L);return O=ve(ve(ve({percent:$,cornerRadius:a,name:T,tooltipPayload:F,midAngle:L,middleRadius:C,tooltipPosition:M},_),m),{},{value:Oe(_,y),startAngle:I,endAngle:D,payload:_,paddingAngle:yt(g)*l}),O})}return ve(ve({},m),{},{sectors:j,data:i})});var AG=Math.ceil,NG=Math.max;function $G(e,t,r,n){for(var i=-1,a=NG(AG((t-e)/(r||1)),0),o=Array(a);a--;)o[n?a:++i]=e,e+=r;return o}var EG=$G,TG=QO,j1=1/0,CG=17976931348623157e292;function MG(e){if(!e)return e===0?e:0;if(e=TG(e),e===j1||e===-j1){var t=e<0?-1:1;return t*CG}return e===e?e:0}var EP=MG,IG=EG,LG=Mf,rp=EP;function DG(e){return function(t,r,n){return n&&typeof n!="number"&&LG(t,r,n)&&(r=n=void 0),t=rp(t),r===void 0?(r=t,t=0):r=rp(r),n=n===void 0?t<r?1:-1:rp(n),IG(t,r,n,e)}}var RG=DG,BG=RG,FG=BG(),zG=FG;const $c=de(zG);function Js(e){"@babel/helpers - typeof";return Js=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Js(e)}function S1(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function O1(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?S1(Object(r),!0).forEach(function(n){TP(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):S1(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function TP(e,t,r){return t=WG(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function WG(e){var t=UG(e,"string");return Js(t)=="symbol"?t:t+""}function UG(e,t){if(Js(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(Js(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var KG=["Webkit","Moz","O","ms"],HG=function(t,r){var n=t.replace(/(\w)/,function(a){return a.toUpperCase()}),i=KG.reduce(function(a,o){return O1(O1({},a),{},TP({},o+n,r))},{});return i[t]=r,i};function Ra(e){"@babel/helpers - typeof";return Ra=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Ra(e)}function Ec(){return Ec=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},Ec.apply(this,arguments)}function _1(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function np(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?_1(Object(r),!0).forEach(function(n){Lt(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):_1(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function VG(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function P1(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,MP(n.key),n)}}function GG(e,t,r){return t&&P1(e.prototype,t),r&&P1(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function YG(e,t,r){return t=Tc(t),qG(e,CP()?Reflect.construct(t,r||[],Tc(e).constructor):t.apply(e,r))}function qG(e,t){if(t&&(Ra(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return XG(e)}function XG(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function CP(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(CP=function(){return!!e})()}function Tc(e){return Tc=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},Tc(e)}function QG(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&hm(e,t)}function hm(e,t){return hm=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,i){return n.__proto__=i,n},hm(e,t)}function Lt(e,t,r){return t=MP(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function MP(e){var t=ZG(e,"string");return Ra(t)=="symbol"?t:t+""}function ZG(e,t){if(Ra(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(Ra(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}var JG=function(t){var r=t.data,n=t.startIndex,i=t.endIndex,a=t.x,o=t.width,s=t.travellerWidth;if(!r||!r.length)return{};var l=r.length,u=Qo().domain($c(0,l)).range([a,a+o-s]),f=u.domain().map(function(d){return u(d)});return{isTextActive:!1,isSlideMoving:!1,isTravellerMoving:!1,isTravellerFocused:!1,startX:u(n),endX:u(i),scale:u,scaleValues:f}},k1=function(t){return t.changedTouches&&!!t.changedTouches.length},Ba=function(e){function t(r){var n;return VG(this,t),n=YG(this,t,[r]),Lt(n,"handleDrag",function(i){n.leaveTimer&&(clearTimeout(n.leaveTimer),n.leaveTimer=null),n.state.isTravellerMoving?n.handleTravellerMove(i):n.state.isSlideMoving&&n.handleSlideDrag(i)}),Lt(n,"handleTouchMove",function(i){i.changedTouches!=null&&i.changedTouches.length>0&&n.handleDrag(i.changedTouches[0])}),Lt(n,"handleDragEnd",function(){n.setState({isTravellerMoving:!1,isSlideMoving:!1},function(){var i=n.props,a=i.endIndex,o=i.onDragEnd,s=i.startIndex;o==null||o({endIndex:a,startIndex:s})}),n.detachDragEndListener()}),Lt(n,"handleLeaveWrapper",function(){(n.state.isTravellerMoving||n.state.isSlideMoving)&&(n.leaveTimer=window.setTimeout(n.handleDragEnd,n.props.leaveTimeOut))}),Lt(n,"handleEnterSlideOrTraveller",function(){n.setState({isTextActive:!0})}),Lt(n,"handleLeaveSlideOrTraveller",function(){n.setState({isTextActive:!1})}),Lt(n,"handleSlideDragStart",function(i){var a=k1(i)?i.changedTouches[0]:i;n.setState({isTravellerMoving:!1,isSlideMoving:!0,slideMoveStartX:a.pageX}),n.attachDragEndListener()}),n.travellerDragStartHandlers={startX:n.handleTravellerDragStart.bind(n,"startX"),endX:n.handleTravellerDragStart.bind(n,"endX")},n.state={},n}return QG(t,e),GG(t,[{key:"componentWillUnmount",value:function(){this.leaveTimer&&(clearTimeout(this.leaveTimer),this.leaveTimer=null),this.detachDragEndListener()}},{key:"getIndex",value:function(n){var i=n.startX,a=n.endX,o=this.state.scaleValues,s=this.props,l=s.gap,u=s.data,f=u.length-1,d=Math.min(i,a),p=Math.max(i,a),h=t.getIndexInRange(o,d),m=t.getIndexInRange(o,p);return{startIndex:h-h%l,endIndex:m===f?f:m-m%l}}},{key:"getTextOfTick",value:function(n){var i=this.props,a=i.data,o=i.tickFormatter,s=i.dataKey,l=Oe(a[n],s,n);return Z(o)?o(l,n):l}},{key:"attachDragEndListener",value:function(){window.addEventListener("mouseup",this.handleDragEnd,!0),window.addEventListener("touchend",this.handleDragEnd,!0),window.addEventListener("mousemove",this.handleDrag,!0)}},{key:"detachDragEndListener",value:function(){window.removeEventListener("mouseup",this.handleDragEnd,!0),window.removeEventListener("touchend",this.handleDragEnd,!0),window.removeEventListener("mousemove",this.handleDrag,!0)}},{key:"handleSlideDrag",value:function(n){var i=this.state,a=i.slideMoveStartX,o=i.startX,s=i.endX,l=this.props,u=l.x,f=l.width,d=l.travellerWidth,p=l.startIndex,h=l.endIndex,m=l.onChange,g=n.pageX-a;g>0?g=Math.min(g,u+f-d-s,u+f-d-o):g<0&&(g=Math.max(g,u-o,u-s));var x=this.getIndex({startX:o+g,endX:s+g});(x.startIndex!==p||x.endIndex!==h)&&m&&m(x),this.setState({startX:o+g,endX:s+g,slideMoveStartX:n.pageX})}},{key:"handleTravellerDragStart",value:function(n,i){var a=k1(i)?i.changedTouches[0]:i;this.setState({isSlideMoving:!1,isTravellerMoving:!0,movingTravellerId:n,brushMoveStartX:a.pageX}),this.attachDragEndListener()}},{key:"handleTravellerMove",value:function(n){var i=this.state,a=i.brushMoveStartX,o=i.movingTravellerId,s=i.endX,l=i.startX,u=this.state[o],f=this.props,d=f.x,p=f.width,h=f.travellerWidth,m=f.onChange,g=f.gap,x=f.data,y={startX:this.state.startX,endX:this.state.endX},v=n.pageX-a;v>0?v=Math.min(v,d+p-h-u):v<0&&(v=Math.max(v,d-u)),y[o]=u+v;var b=this.getIndex(y),S=b.startIndex,w=b.endIndex,j=function(){var _=x.length-1;return o==="startX"&&(s>l?S%g===0:w%g===0)||s<l&&w===_||o==="endX"&&(s>l?w%g===0:S%g===0)||s>l&&w===_};this.setState(Lt(Lt({},o,u+v),"brushMoveStartX",n.pageX),function(){m&&j()&&m(b)})}},{key:"handleTravellerMoveKeyboard",value:function(n,i){var a=this,o=this.state,s=o.scaleValues,l=o.startX,u=o.endX,f=this.state[i],d=s.indexOf(f);if(d!==-1){var p=d+n;if(!(p===-1||p>=s.length)){var h=s[p];i==="startX"&&h>=u||i==="endX"&&h<=l||this.setState(Lt({},i,h),function(){a.props.onChange(a.getIndex({startX:a.state.startX,endX:a.state.endX}))})}}}},{key:"renderBackground",value:function(){var n=this.props,i=n.x,a=n.y,o=n.width,s=n.height,l=n.fill,u=n.stroke;return A.createElement("rect",{stroke:u,fill:l,x:i,y:a,width:o,height:s})}},{key:"renderPanorama",value:function(){var n=this.props,i=n.x,a=n.y,o=n.width,s=n.height,l=n.data,u=n.children,f=n.padding,d=k.Children.only(u);return d?A.cloneElement(d,{x:i,y:a,width:o,height:s,margin:f,compact:!0,data:l}):null}},{key:"renderTravellerLayer",value:function(n,i){var a,o,s=this,l=this.props,u=l.y,f=l.travellerWidth,d=l.height,p=l.traveller,h=l.ariaLabel,m=l.data,g=l.startIndex,x=l.endIndex,y=Math.max(n,this.props.x),v=np(np({},q(this.props,!1)),{},{x:y,y:u,width:f,height:d}),b=h||"Min value: ".concat((a=m[g])===null||a===void 0?void 0:a.name,", Max value: ").concat((o=m[x])===null||o===void 0?void 0:o.name);return A.createElement(te,{tabIndex:0,role:"slider","aria-label":b,"aria-valuenow":n,className:"recharts-brush-traveller",onMouseEnter:this.handleEnterSlideOrTraveller,onMouseLeave:this.handleLeaveSlideOrTraveller,onMouseDown:this.travellerDragStartHandlers[i],onTouchStart:this.travellerDragStartHandlers[i],onKeyDown:function(w){["ArrowLeft","ArrowRight"].includes(w.key)&&(w.preventDefault(),w.stopPropagation(),s.handleTravellerMoveKeyboard(w.key==="ArrowRight"?1:-1,i))},onFocus:function(){s.setState({isTravellerFocused:!0})},onBlur:function(){s.setState({isTravellerFocused:!1})},style:{cursor:"col-resize"}},t.renderTraveller(p,v))}},{key:"renderSlide",value:function(n,i){var a=this.props,o=a.y,s=a.height,l=a.stroke,u=a.travellerWidth,f=Math.min(n,i)+u,d=Math.max(Math.abs(i-n)-u,0);return A.createElement("rect",{className:"recharts-brush-slide",onMouseEnter:this.handleEnterSlideOrTraveller,onMouseLeave:this.handleLeaveSlideOrTraveller,onMouseDown:this.handleSlideDragStart,onTouchStart:this.handleSlideDragStart,style:{cursor:"move"},stroke:"none",fill:l,fillOpacity:.2,x:f,y:o,width:d,height:s})}},{key:"renderText",value:function(){var n=this.props,i=n.startIndex,a=n.endIndex,o=n.y,s=n.height,l=n.travellerWidth,u=n.stroke,f=this.state,d=f.startX,p=f.endX,h=5,m={pointerEvents:"none",fill:u};return A.createElement(te,{className:"recharts-brush-texts"},A.createElement(ki,Ec({textAnchor:"end",verticalAnchor:"middle",x:Math.min(d,p)-h,y:o+s/2},m),this.getTextOfTick(i)),A.createElement(ki,Ec({textAnchor:"start",verticalAnchor:"middle",x:Math.max(d,p)+l+h,y:o+s/2},m),this.getTextOfTick(a)))}},{key:"render",value:function(){var n=this.props,i=n.data,a=n.className,o=n.children,s=n.x,l=n.y,u=n.width,f=n.height,d=n.alwaysShowText,p=this.state,h=p.startX,m=p.endX,g=p.isTextActive,x=p.isSlideMoving,y=p.isTravellerMoving,v=p.isTravellerFocused;if(!i||!i.length||!K(s)||!K(l)||!K(u)||!K(f)||u<=0||f<=0)return null;var b=ee("recharts-brush",a),S=A.Children.count(o)===1,w=HG("userSelect","none");return A.createElement(te,{className:b,onMouseLeave:this.handleLeaveWrapper,onTouchMove:this.handleTouchMove,style:w},this.renderBackground(),S&&this.renderPanorama(),this.renderSlide(h,m),this.renderTravellerLayer(h,"startX"),this.renderTravellerLayer(m,"endX"),(g||x||y||v||d)&&this.renderText())}}],[{key:"renderDefaultTraveller",value:function(n){var i=n.x,a=n.y,o=n.width,s=n.height,l=n.stroke,u=Math.floor(a+s/2)-1;return A.createElement(A.Fragment,null,A.createElement("rect",{x:i,y:a,width:o,height:s,fill:l,stroke:"none"}),A.createElement("line",{x1:i+1,y1:u,x2:i+o-1,y2:u,fill:"none",stroke:"#fff"}),A.createElement("line",{x1:i+1,y1:u+2,x2:i+o-1,y2:u+2,fill:"none",stroke:"#fff"}))}},{key:"renderTraveller",value:function(n,i){var a;return A.isValidElement(n)?a=A.cloneElement(n,i):Z(n)?a=n(i):a=t.renderDefaultTraveller(i),a}},{key:"getDerivedStateFromProps",value:function(n,i){var a=n.data,o=n.width,s=n.x,l=n.travellerWidth,u=n.updateId,f=n.startIndex,d=n.endIndex;if(a!==i.prevData||u!==i.prevUpdateId)return np({prevData:a,prevTravellerWidth:l,prevUpdateId:u,prevX:s,prevWidth:o},a&&a.length?JG({data:a,width:o,x:s,travellerWidth:l,startIndex:f,endIndex:d}):{scale:null,scaleValues:null});if(i.scale&&(o!==i.prevWidth||s!==i.prevX||l!==i.prevTravellerWidth)){i.scale.range([s,s+o-l]);var p=i.scale.domain().map(function(h){return i.scale(h)});return{prevData:a,prevTravellerWidth:l,prevUpdateId:u,prevX:s,prevWidth:o,startX:i.scale(n.startIndex),endX:i.scale(n.endIndex),scaleValues:p}}return null}},{key:"getIndexInRange",value:function(n,i){for(var a=n.length,o=0,s=a-1;s-o>1;){var l=Math.floor((o+s)/2);n[l]>i?s=l:o=l}return i>=n[s]?s:o}}])}(k.PureComponent);Lt(Ba,"displayName","Brush");Lt(Ba,"defaultProps",{height:40,travellerWidth:5,gap:1,fill:"#fff",stroke:"#666",padding:{top:1,right:1,bottom:1,left:1},leaveTimeOut:1e3,alwaysShowText:!1});var eY=ny;function tY(e,t){var r;return eY(e,function(n,i,a){return r=t(n,i,a),!r}),!!r}var rY=tY,nY=OO,iY=Lr,aY=rY,oY=Ct,sY=Mf;function lY(e,t,r){var n=oY(e)?nY:aY;return r&&sY(e,t,r)&&(t=void 0),n(e,iY(t))}var uY=lY;const cY=de(uY);var Cr=function(t,r){var n=t.alwaysShow,i=t.ifOverflow;return n&&(i="extendDomain"),i===r},A1=VO;function fY(e,t,r){t=="__proto__"&&A1?A1(e,t,{configurable:!0,enumerable:!0,value:r,writable:!0}):e[t]=r}var dY=fY,pY=dY,hY=KO,mY=Lr;function vY(e,t){var r={};return t=mY(t),hY(e,function(n,i,a){pY(r,i,t(n,i,a))}),r}var yY=vY;const gY=de(yY);function xY(e,t){for(var r=-1,n=e==null?0:e.length;++r<n;)if(!t(e[r],r,e))return!1;return!0}var bY=xY,wY=ny;function jY(e,t){var r=!0;return wY(e,function(n,i,a){return r=!!t(n,i,a),r}),r}var SY=jY,OY=bY,_Y=SY,PY=Lr,kY=Ct,AY=Mf;function NY(e,t,r){var n=kY(e)?OY:_Y;return r&&AY(e,t,r)&&(t=void 0),n(e,PY(t))}var $Y=NY;const IP=de($Y);var EY=["x","y"];function el(e){"@babel/helpers - typeof";return el=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},el(e)}function mm(){return mm=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},mm.apply(this,arguments)}function N1(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function Io(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?N1(Object(r),!0).forEach(function(n){TY(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):N1(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function TY(e,t,r){return t=CY(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function CY(e){var t=MY(e,"string");return el(t)=="symbol"?t:t+""}function MY(e,t){if(el(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(el(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function IY(e,t){if(e==null)return{};var r=LY(e,t),n,i;if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i<a.length;i++)n=a[i],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function LY(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function DY(e,t){var r=e.x,n=e.y,i=IY(e,EY),a="".concat(r),o=parseInt(a,10),s="".concat(n),l=parseInt(s,10),u="".concat(t.height||i.height),f=parseInt(u,10),d="".concat(t.width||i.width),p=parseInt(d,10);return Io(Io(Io(Io(Io({},t),i),o?{x:o}:{}),l?{y:l}:{}),{},{height:f,width:p,name:t.name,radius:t.radius})}function $1(e){return A.createElement(Ac,mm({shapeType:"rectangle",propTransformer:DY,activeClassName:"recharts-active-bar"},e))}var RY=function(t){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;return function(n,i){if(typeof t=="number")return t;var a=K(n)||aM(n);return a?t(n,i):(a||Ni(),r)}},BY=["value","background"],LP;function Fa(e){"@babel/helpers - typeof";return Fa=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Fa(e)}function FY(e,t){if(e==null)return{};var r=zY(e,t),n,i;if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i<a.length;i++)n=a[i],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function zY(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function Cc(){return Cc=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},Cc.apply(this,arguments)}function E1(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function Fe(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?E1(Object(r),!0).forEach(function(n){Sn(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):E1(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function WY(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function T1(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,RP(n.key),n)}}function UY(e,t,r){return t&&T1(e.prototype,t),r&&T1(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function KY(e,t,r){return t=Mc(t),HY(e,DP()?Reflect.construct(t,r||[],Mc(e).constructor):t.apply(e,r))}function HY(e,t){if(t&&(Fa(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return VY(e)}function VY(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function DP(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(DP=function(){return!!e})()}function Mc(e){return Mc=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},Mc(e)}function GY(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&vm(e,t)}function vm(e,t){return vm=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,i){return n.__proto__=i,n},vm(e,t)}function Sn(e,t,r){return t=RP(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function RP(e){var t=YY(e,"string");return Fa(t)=="symbol"?t:t+""}function YY(e,t){if(Fa(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(Fa(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}var Tt=function(e){function t(){var r;WY(this,t);for(var n=arguments.length,i=new Array(n),a=0;a<n;a++)i[a]=arguments[a];return r=KY(this,t,[].concat(i)),Sn(r,"state",{isAnimationFinished:!1}),Sn(r,"id",Gn("recharts-bar-")),Sn(r,"handleAnimationEnd",function(){var o=r.props.onAnimationEnd;r.setState({isAnimationFinished:!0}),o&&o()}),Sn(r,"handleAnimationStart",function(){var o=r.props.onAnimationStart;r.setState({isAnimationFinished:!1}),o&&o()}),r}return GY(t,e),UY(t,[{key:"renderRectanglesStatically",value:function(n){var i=this,a=this.props,o=a.shape,s=a.dataKey,l=a.activeIndex,u=a.activeBar,f=q(this.props,!1);return n&&n.map(function(d,p){var h=p===l,m=h?u:o,g=Fe(Fe(Fe({},f),d),{},{isActive:h,option:m,index:p,dataKey:s,onAnimationStart:i.handleAnimationStart,onAnimationEnd:i.handleAnimationEnd});return A.createElement(te,Cc({className:"recharts-bar-rectangle"},Bn(i.props,d,p),{key:"rectangle-".concat(d==null?void 0:d.x,"-").concat(d==null?void 0:d.y,"-").concat(d==null?void 0:d.value,"-").concat(p)}),A.createElement($1,g))})}},{key:"renderRectanglesWithAnimation",value:function(){var n=this,i=this.props,a=i.data,o=i.layout,s=i.isAnimationActive,l=i.animationBegin,u=i.animationDuration,f=i.animationEasing,d=i.animationId,p=this.state.prevData;return A.createElement(or,{begin:l,duration:u,isActive:s,easing:f,from:{t:0},to:{t:1},key:"bar-".concat(d),onAnimationEnd:this.handleAnimationEnd,onAnimationStart:this.handleAnimationStart},function(h){var m=h.t,g=a.map(function(x,y){var v=p&&p[y];if(v){var b=$e(v.x,x.x),S=$e(v.y,x.y),w=$e(v.width,x.width),j=$e(v.height,x.height);return Fe(Fe({},x),{},{x:b(m),y:S(m),width:w(m),height:j(m)})}if(o==="horizontal"){var O=$e(0,x.height),_=O(m);return Fe(Fe({},x),{},{y:x.y+x.height-_,height:_})}var P=$e(0,x.width),N=P(m);return Fe(Fe({},x),{},{width:N})});return A.createElement(te,null,n.renderRectanglesStatically(g))})}},{key:"renderRectangles",value:function(){var n=this.props,i=n.data,a=n.isAnimationActive,o=this.state.prevData;return a&&i&&i.length&&(!o||!Fn(o,i))?this.renderRectanglesWithAnimation():this.renderRectanglesStatically(i)}},{key:"renderBackground",value:function(){var n=this,i=this.props,a=i.data,o=i.dataKey,s=i.activeIndex,l=q(this.props.background,!1);return a.map(function(u,f){u.value;var d=u.background,p=FY(u,BY);if(!d)return null;var h=Fe(Fe(Fe(Fe(Fe({},p),{},{fill:"#eee"},d),l),Bn(n.props,u,f)),{},{onAnimationStart:n.handleAnimationStart,onAnimationEnd:n.handleAnimationEnd,dataKey:o,index:f,className:"recharts-bar-background-rectangle"});return A.createElement($1,Cc({key:"background-bar-".concat(f),option:n.props.background,isActive:f===s},h))})}},{key:"renderErrorBar",value:function(n,i){if(this.props.isAnimationActive&&!this.state.isAnimationFinished)return null;var a=this.props,o=a.data,s=a.xAxis,l=a.yAxis,u=a.layout,f=a.children,d=wt(f,vo);if(!d)return null;var p=u==="vertical"?o[0].height/2:o[0].width/2,h=function(x,y){var v=Array.isArray(x.value)?x.value[1]:x.value;return{x:x.x,y:x.y,value:v,errorVal:Oe(x,y)}},m={clipPath:n?"url(#clipPath-".concat(i,")"):null};return A.createElement(te,m,d.map(function(g){return A.cloneElement(g,{key:"error-bar-".concat(i,"-").concat(g.props.dataKey),data:o,xAxis:s,yAxis:l,layout:u,offset:p,dataPointFormatter:h})}))}},{key:"render",value:function(){var n=this.props,i=n.hide,a=n.data,o=n.className,s=n.xAxis,l=n.yAxis,u=n.left,f=n.top,d=n.width,p=n.height,h=n.isAnimationActive,m=n.background,g=n.id;if(i||!a||!a.length)return null;var x=this.state.isAnimationFinished,y=ee("recharts-bar",o),v=s&&s.allowDataOverflow,b=l&&l.allowDataOverflow,S=v||b,w=Q(g)?this.id:g;return A.createElement(te,{className:y},v||b?A.createElement("defs",null,A.createElement("clipPath",{id:"clipPath-".concat(w)},A.createElement("rect",{x:v?u:u-d/2,y:b?f:f-p/2,width:v?d:d*2,height:b?p:p*2}))):null,A.createElement(te,{className:"recharts-bar-rectangles",clipPath:S?"url(#clipPath-".concat(w,")"):null},m?this.renderBackground():null,this.renderRectangles()),this.renderErrorBar(S,w),(!h||x)&&br.renderCallByParent(this.props,a))}}],[{key:"getDerivedStateFromProps",value:function(n,i){return n.animationId!==i.prevAnimationId?{prevAnimationId:n.animationId,curData:n.data,prevData:i.curData}:n.data!==i.curData?{curData:n.data}:null}}])}(k.PureComponent);LP=Tt;Sn(Tt,"displayName","Bar");Sn(Tt,"defaultProps",{xAxisId:0,yAxisId:0,legendType:"rect",minPointSize:0,hide:!1,data:[],layout:"vertical",activeBar:!1,isAnimationActive:!sn.isSsr,animationBegin:0,animationDuration:400,animationEasing:"ease"});Sn(Tt,"getComposedData",function(e){var t=e.props,r=e.item,n=e.barPosition,i=e.bandSize,a=e.xAxis,o=e.yAxis,s=e.xAxisTicks,l=e.yAxisTicks,u=e.stackedData,f=e.dataStartIndex,d=e.displayedData,p=e.offset,h=OW(n,r);if(!h)return null;var m=t.layout,g=r.type.defaultProps,x=g!==void 0?Fe(Fe({},g),r.props):r.props,y=x.dataKey,v=x.children,b=x.minPointSize,S=m==="horizontal"?o:a,w=u?S.scale.domain():null,j=EW({numericAxis:S}),O=wt(v,jr),_=d.map(function(P,N){var T,$,I,D,L,C;u?T=_W(u[f+N],w):(T=Oe(P,y),Array.isArray(T)||(T=[j,T]));var F=RY(b,LP.defaultProps.minPointSize)(T[1],N);if(m==="horizontal"){var M,B=[o.scale(T[0]),o.scale(T[1])],E=B[0],W=B[1];$=Ob({axis:a,ticks:s,bandSize:i,offset:h.offset,entry:P,index:N}),I=(M=W??E)!==null&&M!==void 0?M:void 0,D=h.size;var z=E-W;if(L=Number.isNaN(z)?0:z,C={x:$,y:o.y,width:D,height:o.height},Math.abs(F)>0&&Math.abs(L)<Math.abs(F)){var X=yt(L||F)*(Math.abs(F)-Math.abs(L));I-=X,L+=X}}else{var oe=[a.scale(T[0]),a.scale(T[1])],Pe=oe[0],Le=oe[1];if($=Pe,I=Ob({axis:o,ticks:l,bandSize:i,offset:h.offset,entry:P,index:N}),D=Le-Pe,L=h.size,C={x:a.x,y:I,width:a.width,height:L},Math.abs(F)>0&&Math.abs(D)<Math.abs(F)){var Vt=yt(D||F)*(Math.abs(F)-Math.abs(D));D+=Vt}}return Fe(Fe(Fe({},P),{},{x:$,y:I,width:D,height:L,value:u?T:T[1],payload:P,background:C},O&&O[N]&&O[N].props),{},{tooltipPayload:[sP(r,P)],tooltipPosition:{x:$+D/2,y:I+L/2}})});return Fe({data:_,layout:m},p)});function tl(e){"@babel/helpers - typeof";return tl=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},tl(e)}function qY(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function C1(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,BP(n.key),n)}}function XY(e,t,r){return t&&C1(e.prototype,t),r&&C1(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function M1(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function pr(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?M1(Object(r),!0).forEach(function(n){Qf(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):M1(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function Qf(e,t,r){return t=BP(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function BP(e){var t=QY(e,"string");return tl(t)=="symbol"?t:t+""}function QY(e,t){if(tl(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(tl(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var Zf=function(t,r,n,i,a){var o=t.width,s=t.height,l=t.layout,u=t.children,f=Object.keys(r),d={left:n.left,leftMirror:n.left,right:o-n.right,rightMirror:o-n.right,top:n.top,topMirror:n.top,bottom:s-n.bottom,bottomMirror:s-n.bottom},p=!!Rt(u,Tt);return f.reduce(function(h,m){var g=r[m],x=g.orientation,y=g.domain,v=g.padding,b=v===void 0?{}:v,S=g.mirror,w=g.reversed,j="".concat(x).concat(S?"Mirror":""),O,_,P,N,T;if(g.type==="number"&&(g.padding==="gap"||g.padding==="no-gap")){var $=y[1]-y[0],I=1/0,D=g.categoricalDomain.sort(uM);if(D.forEach(function(oe,Pe){Pe>0&&(I=Math.min((oe||0)-(D[Pe-1]||0),I))}),Number.isFinite(I)){var L=I/$,C=g.layout==="vertical"?n.height:n.width;if(g.padding==="gap"&&(O=L*C/2),g.padding==="no-gap"){var F=gt(t.barCategoryGap,L*C),M=L*C/2;O=M-F-(M-F)/C*F}}}i==="xAxis"?_=[n.left+(b.left||0)+(O||0),n.left+n.width-(b.right||0)-(O||0)]:i==="yAxis"?_=l==="horizontal"?[n.top+n.height-(b.bottom||0),n.top+(b.top||0)]:[n.top+(b.top||0)+(O||0),n.top+n.height-(b.bottom||0)-(O||0)]:_=g.range,w&&(_=[_[1],_[0]]);var B=nP(g,a,p),E=B.scale,W=B.realScaleType;E.domain(y).range(_),iP(E);var z=aP(E,pr(pr({},g),{},{realScaleType:W}));i==="xAxis"?(T=x==="top"&&!S||x==="bottom"&&S,P=n.left,N=d[j]-T*g.height):i==="yAxis"&&(T=x==="left"&&!S||x==="right"&&S,P=d[j]-T*g.width,N=n.top);var X=pr(pr(pr({},g),z),{},{realScaleType:W,x:P,y:N,scale:E,width:i==="xAxis"?n.width:g.width,height:i==="yAxis"?n.height:g.height});return X.bandSize=vc(X,z),!g.hide&&i==="xAxis"?d[j]+=(T?-1:1)*X.height:g.hide||(d[j]+=(T?-1:1)*X.width),pr(pr({},h),{},Qf({},m,X))},{})},FP=function(t,r){var n=t.x,i=t.y,a=r.x,o=r.y;return{x:Math.min(n,a),y:Math.min(i,o),width:Math.abs(a-n),height:Math.abs(o-i)}},ZY=function(t){var r=t.x1,n=t.y1,i=t.x2,a=t.y2;return FP({x:r,y:n},{x:i,y:a})},zP=function(){function e(t){qY(this,e),this.scale=t}return XY(e,[{key:"domain",get:function(){return this.scale.domain}},{key:"range",get:function(){return this.scale.range}},{key:"rangeMin",get:function(){return this.range()[0]}},{key:"rangeMax",get:function(){return this.range()[1]}},{key:"bandwidth",get:function(){return this.scale.bandwidth}},{key:"apply",value:function(r){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},i=n.bandAware,a=n.position;if(r!==void 0){if(a)switch(a){case"start":return this.scale(r);case"middle":{var o=this.bandwidth?this.bandwidth()/2:0;return this.scale(r)+o}case"end":{var s=this.bandwidth?this.bandwidth():0;return this.scale(r)+s}default:return this.scale(r)}if(i){var l=this.bandwidth?this.bandwidth()/2:0;return this.scale(r)+l}return this.scale(r)}}},{key:"isInRange",value:function(r){var n=this.range(),i=n[0],a=n[n.length-1];return i<=a?r>=i&&r<=a:r>=a&&r<=i}}],[{key:"create",value:function(r){return new e(r)}}])}();Qf(zP,"EPS",1e-4);var Ty=function(t){var r=Object.keys(t).reduce(function(n,i){return pr(pr({},n),{},Qf({},i,zP.create(t[i])))},{});return pr(pr({},r),{},{apply:function(i){var a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},o=a.bandAware,s=a.position;return gY(i,function(l,u){return r[u].apply(l,{bandAware:o,position:s})})},isInRange:function(i){return IP(i,function(a,o){return r[o].isInRange(a)})}})};function JY(e){return(e%180+180)%180}var eq=function(t){var r=t.width,n=t.height,i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,a=JY(i),o=a*Math.PI/180,s=Math.atan(n/r),l=o>s&&o<Math.PI-s?n/Math.sin(o):r/Math.cos(o);return Math.abs(l)},tq=Lr,rq=hl,nq=Tf;function iq(e){return function(t,r,n){var i=Object(t);if(!rq(t)){var a=tq(r);t=nq(t),r=function(s){return a(i[s],s,i)}}var o=e(t,r,n);return o>-1?i[a?t[o]:o]:void 0}}var aq=iq,oq=EP;function sq(e){var t=oq(e),r=t%1;return t===t?r?t-r:t:0}var lq=sq,uq=RO,cq=Lr,fq=lq,dq=Math.max;function pq(e,t,r){var n=e==null?0:e.length;if(!n)return-1;var i=r==null?0:fq(r);return i<0&&(i=dq(n+i,0)),uq(e,cq(t),i)}var hq=pq,mq=aq,vq=hq,yq=mq(vq),gq=yq;const xq=de(gq);var bq=fC(function(e){return{x:e.left,y:e.top,width:e.width,height:e.height}},function(e){return["l",e.left,"t",e.top,"w",e.width,"h",e.height].join("")}),Cy=k.createContext(void 0),My=k.createContext(void 0),WP=k.createContext(void 0),UP=k.createContext({}),KP=k.createContext(void 0),HP=k.createContext(0),VP=k.createContext(0),I1=function(t){var r=t.state,n=r.xAxisMap,i=r.yAxisMap,a=r.offset,o=t.clipPathId,s=t.children,l=t.width,u=t.height,f=bq(a);return A.createElement(Cy.Provider,{value:n},A.createElement(My.Provider,{value:i},A.createElement(UP.Provider,{value:a},A.createElement(WP.Provider,{value:f},A.createElement(KP.Provider,{value:o},A.createElement(HP.Provider,{value:u},A.createElement(VP.Provider,{value:l},s)))))))},wq=function(){return k.useContext(KP)},GP=function(t){var r=k.useContext(Cy);r==null&&Ni();var n=r[t];return n==null&&Ni(),n},jq=function(){var t=k.useContext(Cy);return gn(t)},Sq=function(){var t=k.useContext(My),r=xq(t,function(n){return IP(n.domain,Number.isFinite)});return r||gn(t)},YP=function(t){var r=k.useContext(My);r==null&&Ni();var n=r[t];return n==null&&Ni(),n},Oq=function(){var t=k.useContext(WP);return t},_q=function(){return k.useContext(UP)},Iy=function(){return k.useContext(VP)},Ly=function(){return k.useContext(HP)};function za(e){"@babel/helpers - typeof";return za=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},za(e)}function Pq(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function kq(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,XP(n.key),n)}}function Aq(e,t,r){return t&&kq(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function Nq(e,t,r){return t=Ic(t),$q(e,qP()?Reflect.construct(t,r||[],Ic(e).constructor):t.apply(e,r))}function $q(e,t){if(t&&(za(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return Eq(e)}function Eq(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function qP(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(qP=function(){return!!e})()}function Ic(e){return Ic=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},Ic(e)}function Tq(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&ym(e,t)}function ym(e,t){return ym=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,i){return n.__proto__=i,n},ym(e,t)}function L1(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function D1(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?L1(Object(r),!0).forEach(function(n){Dy(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):L1(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function Dy(e,t,r){return t=XP(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function XP(e){var t=Cq(e,"string");return za(t)=="symbol"?t:t+""}function Cq(e,t){if(za(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(za(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}function Mq(e,t){return Rq(e)||Dq(e,t)||Lq(e,t)||Iq()}function Iq(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
-In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Lq(e,t){if(e){if(typeof e=="string")return R1(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return R1(e,t)}}function R1(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function Dq(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,i,a,o,s=[],l=!0,u=!1;try{if(a=(r=r.call(e)).next,t!==0)for(;!(l=(n=a.call(r)).done)&&(s.push(n.value),s.length!==t);l=!0);}catch(f){u=!0,i=f}finally{try{if(!l&&r.return!=null&&(o=r.return(),Object(o)!==o))return}finally{if(u)throw i}}return s}}function Rq(e){if(Array.isArray(e))return e}function gm(){return gm=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},gm.apply(this,arguments)}var Bq=function(t,r){var n;return A.isValidElement(t)?n=A.cloneElement(t,r):Z(t)?n=t(r):n=A.createElement("line",gm({},r,{className:"recharts-reference-line-line"})),n},Fq=function(t,r,n,i,a,o,s,l,u){var f=a.x,d=a.y,p=a.width,h=a.height;if(n){var m=u.y,g=t.y.apply(m,{position:o});if(Cr(u,"discard")&&!t.y.isInRange(g))return null;var x=[{x:f+p,y:g},{x:f,y:g}];return l==="left"?x.reverse():x}if(r){var y=u.x,v=t.x.apply(y,{position:o});if(Cr(u,"discard")&&!t.x.isInRange(v))return null;var b=[{x:v,y:d+h},{x:v,y:d}];return s==="top"?b.reverse():b}if(i){var S=u.segment,w=S.map(function(j){return t.apply(j,{position:o})});return Cr(u,"discard")&&cY(w,function(j){return!t.isInRange(j)})?null:w}return null};function zq(e){var t=e.x,r=e.y,n=e.segment,i=e.xAxisId,a=e.yAxisId,o=e.shape,s=e.className,l=e.alwaysShow,u=wq(),f=GP(i),d=YP(a),p=Oq();if(!u||!p)return null;xr(l===void 0,'The alwaysShow prop is deprecated. Please use ifOverflow="extendDomain" instead.');var h=Ty({x:f.scale,y:d.scale}),m=Xe(t),g=Xe(r),x=n&&n.length===2,y=Fq(h,m,g,x,p,e.position,f.orientation,d.orientation,e);if(!y)return null;var v=Mq(y,2),b=v[0],S=b.x,w=b.y,j=v[1],O=j.x,_=j.y,P=Cr(e,"hidden")?"url(#".concat(u,")"):void 0,N=D1(D1({clipPath:P},q(e,!0)),{},{x1:S,y1:w,x2:O,y2:_});return A.createElement(te,{className:ee("recharts-reference-line",s)},Bq(o,N),et.renderCallByParent(e,ZY({x1:S,y1:w,x2:O,y2:_})))}var Ry=function(e){function t(){return Pq(this,t),Nq(this,t,arguments)}return Tq(t,e),Aq(t,[{key:"render",value:function(){return A.createElement(zq,this.props)}}])}(A.Component);Dy(Ry,"displayName","ReferenceLine");Dy(Ry,"defaultProps",{isFront:!1,ifOverflow:"discard",xAxisId:0,yAxisId:0,fill:"none",stroke:"#ccc",fillOpacity:1,strokeWidth:1,position:"middle"});function xm(){return xm=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},xm.apply(this,arguments)}function Wa(e){"@babel/helpers - typeof";return Wa=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Wa(e)}function B1(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function F1(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?B1(Object(r),!0).forEach(function(n){Jf(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):B1(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function Wq(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function Uq(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,ZP(n.key),n)}}function Kq(e,t,r){return t&&Uq(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function Hq(e,t,r){return t=Lc(t),Vq(e,QP()?Reflect.construct(t,r||[],Lc(e).constructor):t.apply(e,r))}function Vq(e,t){if(t&&(Wa(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return Gq(e)}function Gq(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function QP(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(QP=function(){return!!e})()}function Lc(e){return Lc=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},Lc(e)}function Yq(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&bm(e,t)}function bm(e,t){return bm=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,i){return n.__proto__=i,n},bm(e,t)}function Jf(e,t,r){return t=ZP(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function ZP(e){var t=qq(e,"string");return Wa(t)=="symbol"?t:t+""}function qq(e,t){if(Wa(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(Wa(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}var Xq=function(t){var r=t.x,n=t.y,i=t.xAxis,a=t.yAxis,o=Ty({x:i.scale,y:a.scale}),s=o.apply({x:r,y:n},{bandAware:!0});return Cr(t,"discard")&&!o.isInRange(s)?null:s},ed=function(e){function t(){return Wq(this,t),Hq(this,t,arguments)}return Yq(t,e),Kq(t,[{key:"render",value:function(){var n=this.props,i=n.x,a=n.y,o=n.r,s=n.alwaysShow,l=n.clipPathId,u=Xe(i),f=Xe(a);if(xr(s===void 0,'The alwaysShow prop is deprecated. Please use ifOverflow="extendDomain" instead.'),!u||!f)return null;var d=Xq(this.props);if(!d)return null;var p=d.x,h=d.y,m=this.props,g=m.shape,x=m.className,y=Cr(this.props,"hidden")?"url(#".concat(l,")"):void 0,v=F1(F1({clipPath:y},q(this.props,!0)),{},{cx:p,cy:h});return A.createElement(te,{className:ee("recharts-reference-dot",x)},t.renderDot(g,v),et.renderCallByParent(this.props,{x:p-o,y:h-o,width:2*o,height:2*o}))}}])}(A.Component);Jf(ed,"displayName","ReferenceDot");Jf(ed,"defaultProps",{isFront:!1,ifOverflow:"discard",xAxisId:0,yAxisId:0,r:10,fill:"#fff",stroke:"#ccc",fillOpacity:1,strokeWidth:1});Jf(ed,"renderDot",function(e,t){var r;return A.isValidElement(e)?r=A.cloneElement(e,t):Z(e)?r=e(t):r=A.createElement(xl,xm({},t,{cx:t.cx,cy:t.cy,className:"recharts-reference-dot-dot"})),r});function wm(){return wm=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},wm.apply(this,arguments)}function Ua(e){"@babel/helpers - typeof";return Ua=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Ua(e)}function z1(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function W1(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?z1(Object(r),!0).forEach(function(n){td(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):z1(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function Qq(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function Zq(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,ek(n.key),n)}}function Jq(e,t,r){return t&&Zq(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function eX(e,t,r){return t=Dc(t),tX(e,JP()?Reflect.construct(t,r||[],Dc(e).constructor):t.apply(e,r))}function tX(e,t){if(t&&(Ua(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return rX(e)}function rX(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function JP(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(JP=function(){return!!e})()}function Dc(e){return Dc=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},Dc(e)}function nX(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&jm(e,t)}function jm(e,t){return jm=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,i){return n.__proto__=i,n},jm(e,t)}function td(e,t,r){return t=ek(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function ek(e){var t=iX(e,"string");return Ua(t)=="symbol"?t:t+""}function iX(e,t){if(Ua(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(Ua(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}var aX=function(t,r,n,i,a){var o=a.x1,s=a.x2,l=a.y1,u=a.y2,f=a.xAxis,d=a.yAxis;if(!f||!d)return null;var p=Ty({x:f.scale,y:d.scale}),h={x:t?p.x.apply(o,{position:"start"}):p.x.rangeMin,y:n?p.y.apply(l,{position:"start"}):p.y.rangeMin},m={x:r?p.x.apply(s,{position:"end"}):p.x.rangeMax,y:i?p.y.apply(u,{position:"end"}):p.y.rangeMax};return Cr(a,"discard")&&(!p.isInRange(h)||!p.isInRange(m))?null:FP(h,m)},rd=function(e){function t(){return Qq(this,t),eX(this,t,arguments)}return nX(t,e),Jq(t,[{key:"render",value:function(){var n=this.props,i=n.x1,a=n.x2,o=n.y1,s=n.y2,l=n.className,u=n.alwaysShow,f=n.clipPathId;xr(u===void 0,'The alwaysShow prop is deprecated. Please use ifOverflow="extendDomain" instead.');var d=Xe(i),p=Xe(a),h=Xe(o),m=Xe(s),g=this.props.shape;if(!d&&!p&&!h&&!m&&!g)return null;var x=aX(d,p,h,m,this.props);if(!x&&!g)return null;var y=Cr(this.props,"hidden")?"url(#".concat(f,")"):void 0;return A.createElement(te,{className:ee("recharts-reference-area",l)},t.renderRect(g,W1(W1({clipPath:y},q(this.props,!0)),x)),et.renderCallByParent(this.props,x))}}])}(A.Component);td(rd,"displayName","ReferenceArea");td(rd,"defaultProps",{isFront:!1,ifOverflow:"discard",xAxisId:0,yAxisId:0,r:10,fill:"#ccc",fillOpacity:.5,stroke:"none",strokeWidth:1});td(rd,"renderRect",function(e,t){var r;return A.isValidElement(e)?r=A.cloneElement(e,t):Z(e)?r=e(t):r=A.createElement(Ey,wm({},t,{className:"recharts-reference-area-rect"})),r});function tk(e,t,r){if(t<1)return[];if(t===1&&r===void 0)return e;for(var n=[],i=0;i<e.length;i+=t)n.push(e[i]);return n}function oX(e,t,r){var n={width:e.width+t.width,height:e.height+t.height};return eq(n,r)}function sX(e,t,r){var n=r==="width",i=e.x,a=e.y,o=e.width,s=e.height;return t===1?{start:n?i:a,end:n?i+o:a+s}:{start:n?i+o:a+s,end:n?i:a}}function Rc(e,t,r,n,i){if(e*t<e*n||e*t>e*i)return!1;var a=r();return e*(t-e*a/2-n)>=0&&e*(t+e*a/2-i)<=0}function lX(e,t){return tk(e,t+1)}function uX(e,t,r,n,i){for(var a=(n||[]).slice(),o=t.start,s=t.end,l=0,u=1,f=o,d=function(){var m=n==null?void 0:n[l];if(m===void 0)return{v:tk(n,u)};var g=l,x,y=function(){return x===void 0&&(x=r(m,g)),x},v=m.coordinate,b=l===0||Rc(e,v,y,f,s);b||(l=0,f=o,u+=1),b&&(f=v+e*(y()/2+i),l+=u)},p;u<=a.length;)if(p=d(),p)return p.v;return[]}function rl(e){"@babel/helpers - typeof";return rl=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},rl(e)}function U1(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function ct(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?U1(Object(r),!0).forEach(function(n){cX(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):U1(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function cX(e,t,r){return t=fX(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function fX(e){var t=dX(e,"string");return rl(t)=="symbol"?t:t+""}function dX(e,t){if(rl(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(rl(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function pX(e,t,r,n,i){for(var a=(n||[]).slice(),o=a.length,s=t.start,l=t.end,u=function(p){var h=a[p],m,g=function(){return m===void 0&&(m=r(h,p)),m};if(p===o-1){var x=e*(h.coordinate+e*g()/2-l);a[p]=h=ct(ct({},h),{},{tickCoord:x>0?h.coordinate-x*e:h.coordinate})}else a[p]=h=ct(ct({},h),{},{tickCoord:h.coordinate});var y=Rc(e,h.tickCoord,g,s,l);y&&(l=h.tickCoord-e*(g()/2+i),a[p]=ct(ct({},h),{},{isShow:!0}))},f=o-1;f>=0;f--)u(f);return a}function hX(e,t,r,n,i,a){var o=(n||[]).slice(),s=o.length,l=t.start,u=t.end;if(a){var f=n[s-1],d=r(f,s-1),p=e*(f.coordinate+e*d/2-u);o[s-1]=f=ct(ct({},f),{},{tickCoord:p>0?f.coordinate-p*e:f.coordinate});var h=Rc(e,f.tickCoord,function(){return d},l,u);h&&(u=f.tickCoord-e*(d/2+i),o[s-1]=ct(ct({},f),{},{isShow:!0}))}for(var m=a?s-1:s,g=function(v){var b=o[v],S,w=function(){return S===void 0&&(S=r(b,v)),S};if(v===0){var j=e*(b.coordinate-e*w()/2-l);o[v]=b=ct(ct({},b),{},{tickCoord:j<0?b.coordinate-j*e:b.coordinate})}else o[v]=b=ct(ct({},b),{},{tickCoord:b.coordinate});var O=Rc(e,b.tickCoord,w,l,u);O&&(l=b.tickCoord+e*(w()/2+i),o[v]=ct(ct({},b),{},{isShow:!0}))},x=0;x<m;x++)g(x);return o}function By(e,t,r){var n=e.tick,i=e.ticks,a=e.viewBox,o=e.minTickGap,s=e.orientation,l=e.interval,u=e.tickFormatter,f=e.unit,d=e.angle;if(!i||!i.length||!n)return[];if(K(l)||sn.isSsr)return lX(i,typeof l=="number"&&K(l)?l:0);var p=[],h=s==="top"||s==="bottom"?"width":"height",m=f&&h==="width"?Xo(f,{fontSize:t,letterSpacing:r}):{width:0,height:0},g=function(b,S){var w=Z(u)?u(b.value,S):b.value;return h==="width"?oX(Xo(w,{fontSize:t,letterSpacing:r}),m,d):Xo(w,{fontSize:t,letterSpacing:r})[h]},x=i.length>=2?yt(i[1].coordinate-i[0].coordinate):1,y=sX(a,x,h);return l==="equidistantPreserveStart"?uX(x,y,g,i,o):(l==="preserveStart"||l==="preserveStartEnd"?p=hX(x,y,g,i,o,l==="preserveStartEnd"):p=pX(x,y,g,i,o),p.filter(function(v){return v.isShow}))}var mX=["viewBox"],vX=["viewBox"],yX=["ticks"];function Ka(e){"@babel/helpers - typeof";return Ka=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Ka(e)}function oa(){return oa=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},oa.apply(this,arguments)}function K1(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function Ve(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?K1(Object(r),!0).forEach(function(n){Fy(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):K1(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function ip(e,t){if(e==null)return{};var r=gX(e,t),n,i;if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i<a.length;i++)n=a[i],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function gX(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function xX(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function H1(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,nk(n.key),n)}}function bX(e,t,r){return t&&H1(e.prototype,t),r&&H1(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function wX(e,t,r){return t=Bc(t),jX(e,rk()?Reflect.construct(t,r||[],Bc(e).constructor):t.apply(e,r))}function jX(e,t){if(t&&(Ka(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return SX(e)}function SX(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function rk(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(rk=function(){return!!e})()}function Bc(e){return Bc=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},Bc(e)}function OX(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Sm(e,t)}function Sm(e,t){return Sm=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,i){return n.__proto__=i,n},Sm(e,t)}function Fy(e,t,r){return t=nk(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function nk(e){var t=_X(e,"string");return Ka(t)=="symbol"?t:t+""}function _X(e,t){if(Ka(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(Ka(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}var yo=function(e){function t(r){var n;return xX(this,t),n=wX(this,t,[r]),n.state={fontSize:"",letterSpacing:""},n}return OX(t,e),bX(t,[{key:"shouldComponentUpdate",value:function(n,i){var a=n.viewBox,o=ip(n,mX),s=this.props,l=s.viewBox,u=ip(s,vX);return!ha(a,l)||!ha(o,u)||!ha(i,this.state)}},{key:"componentDidMount",value:function(){var n=this.layerReference;if(n){var i=n.getElementsByClassName("recharts-cartesian-axis-tick-value")[0];i&&this.setState({fontSize:window.getComputedStyle(i).fontSize,letterSpacing:window.getComputedStyle(i).letterSpacing})}}},{key:"getTickLineCoord",value:function(n){var i=this.props,a=i.x,o=i.y,s=i.width,l=i.height,u=i.orientation,f=i.tickSize,d=i.mirror,p=i.tickMargin,h,m,g,x,y,v,b=d?-1:1,S=n.tickSize||f,w=K(n.tickCoord)?n.tickCoord:n.coordinate;switch(u){case"top":h=m=n.coordinate,x=o+ +!d*l,g=x-b*S,v=g-b*p,y=w;break;case"left":g=x=n.coordinate,m=a+ +!d*s,h=m-b*S,y=h-b*p,v=w;break;case"right":g=x=n.coordinate,m=a+ +d*s,h=m+b*S,y=h+b*p,v=w;break;default:h=m=n.coordinate,x=o+ +d*l,g=x+b*S,v=g+b*p,y=w;break}return{line:{x1:h,y1:g,x2:m,y2:x},tick:{x:y,y:v}}}},{key:"getTickTextAnchor",value:function(){var n=this.props,i=n.orientation,a=n.mirror,o;switch(i){case"left":o=a?"start":"end";break;case"right":o=a?"end":"start";break;default:o="middle";break}return o}},{key:"getTickVerticalAnchor",value:function(){var n=this.props,i=n.orientation,a=n.mirror,o="end";switch(i){case"left":case"right":o="middle";break;case"top":o=a?"start":"end";break;default:o=a?"end":"start";break}return o}},{key:"renderAxisLine",value:function(){var n=this.props,i=n.x,a=n.y,o=n.width,s=n.height,l=n.orientation,u=n.mirror,f=n.axisLine,d=Ve(Ve(Ve({},q(this.props,!1)),q(f,!1)),{},{fill:"none"});if(l==="top"||l==="bottom"){var p=+(l==="top"&&!u||l==="bottom"&&u);d=Ve(Ve({},d),{},{x1:i,y1:a+p*s,x2:i+o,y2:a+p*s})}else{var h=+(l==="left"&&!u||l==="right"&&u);d=Ve(Ve({},d),{},{x1:i+h*o,y1:a,x2:i+h*o,y2:a+s})}return A.createElement("line",oa({},d,{className:ee("recharts-cartesian-axis-line",Wt(f,"className"))}))}},{key:"renderTicks",value:function(n,i,a){var o=this,s=this.props,l=s.tickLine,u=s.stroke,f=s.tick,d=s.tickFormatter,p=s.unit,h=By(Ve(Ve({},this.props),{},{ticks:n}),i,a),m=this.getTickTextAnchor(),g=this.getTickVerticalAnchor(),x=q(this.props,!1),y=q(f,!1),v=Ve(Ve({},x),{},{fill:"none"},q(l,!1)),b=h.map(function(S,w){var j=o.getTickLineCoord(S),O=j.line,_=j.tick,P=Ve(Ve(Ve(Ve({textAnchor:m,verticalAnchor:g},x),{},{stroke:"none",fill:u},y),_),{},{index:w,payload:S,visibleTicksCount:h.length,tickFormatter:d});return A.createElement(te,oa({className:"recharts-cartesian-axis-tick",key:"tick-".concat(S.value,"-").concat(S.coordinate,"-").concat(S.tickCoord)},Bn(o.props,S,w)),l&&A.createElement("line",oa({},v,O,{className:ee("recharts-cartesian-axis-tick-line",Wt(l,"className"))})),f&&t.renderTickItem(f,P,"".concat(Z(d)?d(S.value,w):S.value).concat(p||"")))});return A.createElement("g",{className:"recharts-cartesian-axis-ticks"},b)}},{key:"render",value:function(){var n=this,i=this.props,a=i.axisLine,o=i.width,s=i.height,l=i.ticksGenerator,u=i.className,f=i.hide;if(f)return null;var d=this.props,p=d.ticks,h=ip(d,yX),m=p;return Z(l)&&(m=p&&p.length>0?l(this.props):l(h)),o<=0||s<=0||!m||!m.length?null:A.createElement(te,{className:ee("recharts-cartesian-axis",u),ref:function(x){n.layerReference=x}},a&&this.renderAxisLine(),this.renderTicks(m,this.state.fontSize,this.state.letterSpacing),et.renderCallByParent(this.props))}}],[{key:"renderTickItem",value:function(n,i,a){var o,s=ee(i.className,"recharts-cartesian-axis-tick-value");return A.isValidElement(n)?o=A.cloneElement(n,Ve(Ve({},i),{},{className:s})):Z(n)?o=n(Ve(Ve({},i),{},{className:s})):o=A.createElement(ki,oa({},i,{className:"recharts-cartesian-axis-tick-value"}),a),o}}])}(k.Component);Fy(yo,"displayName","CartesianAxis");Fy(yo,"defaultProps",{x:0,y:0,width:0,height:0,viewBox:{x:0,y:0,width:0,height:0},orientation:"bottom",ticks:[],stroke:"#666",tickLine:!0,axisLine:!0,tick:!0,mirror:!1,minTickGap:5,tickSize:6,tickMargin:2,interval:"preserveEnd"});var PX=["x1","y1","x2","y2","key"],kX=["offset"];function $i(e){"@babel/helpers - typeof";return $i=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},$i(e)}function V1(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function dt(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?V1(Object(r),!0).forEach(function(n){AX(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):V1(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function AX(e,t,r){return t=NX(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function NX(e){var t=$X(e,"string");return $i(t)=="symbol"?t:t+""}function $X(e,t){if($i(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if($i(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function hi(){return hi=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},hi.apply(this,arguments)}function G1(e,t){if(e==null)return{};var r=EX(e,t),n,i;if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i<a.length;i++)n=a[i],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function EX(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}var TX=function(t){var r=t.fill;if(!r||r==="none")return null;var n=t.fillOpacity,i=t.x,a=t.y,o=t.width,s=t.height,l=t.ry;return A.createElement("rect",{x:i,y:a,ry:l,width:o,height:s,stroke:"none",fill:r,fillOpacity:n,className:"recharts-cartesian-grid-bg"})};function ik(e,t){var r;if(A.isValidElement(e))r=A.cloneElement(e,t);else if(Z(e))r=e(t);else{var n=t.x1,i=t.y1,a=t.x2,o=t.y2,s=t.key,l=G1(t,PX),u=q(l,!1);u.offset;var f=G1(u,kX);r=A.createElement("line",hi({},f,{x1:n,y1:i,x2:a,y2:o,fill:"none",key:s}))}return r}function CX(e){var t=e.x,r=e.width,n=e.horizontal,i=n===void 0?!0:n,a=e.horizontalPoints;if(!i||!a||!a.length)return null;var o=a.map(function(s,l){var u=dt(dt({},e),{},{x1:t,y1:s,x2:t+r,y2:s,key:"line-".concat(l),index:l});return ik(i,u)});return A.createElement("g",{className:"recharts-cartesian-grid-horizontal"},o)}function MX(e){var t=e.y,r=e.height,n=e.vertical,i=n===void 0?!0:n,a=e.verticalPoints;if(!i||!a||!a.length)return null;var o=a.map(function(s,l){var u=dt(dt({},e),{},{x1:s,y1:t,x2:s,y2:t+r,key:"line-".concat(l),index:l});return ik(i,u)});return A.createElement("g",{className:"recharts-cartesian-grid-vertical"},o)}function IX(e){var t=e.horizontalFill,r=e.fillOpacity,n=e.x,i=e.y,a=e.width,o=e.height,s=e.horizontalPoints,l=e.horizontal,u=l===void 0?!0:l;if(!u||!t||!t.length)return null;var f=s.map(function(p){return Math.round(p+i-i)}).sort(function(p,h){return p-h});i!==f[0]&&f.unshift(0);var d=f.map(function(p,h){var m=!f[h+1],g=m?i+o-p:f[h+1]-p;if(g<=0)return null;var x=h%t.length;return A.createElement("rect",{key:"react-".concat(h),y:p,x:n,height:g,width:a,stroke:"none",fill:t[x],fillOpacity:r,className:"recharts-cartesian-grid-bg"})});return A.createElement("g",{className:"recharts-cartesian-gridstripes-horizontal"},d)}function LX(e){var t=e.vertical,r=t===void 0?!0:t,n=e.verticalFill,i=e.fillOpacity,a=e.x,o=e.y,s=e.width,l=e.height,u=e.verticalPoints;if(!r||!n||!n.length)return null;var f=u.map(function(p){return Math.round(p+a-a)}).sort(function(p,h){return p-h});a!==f[0]&&f.unshift(0);var d=f.map(function(p,h){var m=!f[h+1],g=m?a+s-p:f[h+1]-p;if(g<=0)return null;var x=h%n.length;return A.createElement("rect",{key:"react-".concat(h),x:p,y:o,width:g,height:l,stroke:"none",fill:n[x],fillOpacity:i,className:"recharts-cartesian-grid-bg"})});return A.createElement("g",{className:"recharts-cartesian-gridstripes-vertical"},d)}var DX=function(t,r){var n=t.xAxis,i=t.width,a=t.height,o=t.offset;return rP(By(dt(dt(dt({},yo.defaultProps),n),{},{ticks:Hr(n,!0),viewBox:{x:0,y:0,width:i,height:a}})),o.left,o.left+o.width,r)},RX=function(t,r){var n=t.yAxis,i=t.width,a=t.height,o=t.offset;return rP(By(dt(dt(dt({},yo.defaultProps),n),{},{ticks:Hr(n,!0),viewBox:{x:0,y:0,width:i,height:a}})),o.top,o.top+o.height,r)},Wi={horizontal:!0,vertical:!0,stroke:"#ccc",fill:"none",verticalFill:[],horizontalFill:[]};function ht(e){var t,r,n,i,a,o,s=Iy(),l=Ly(),u=_q(),f=dt(dt({},e),{},{stroke:(t=e.stroke)!==null&&t!==void 0?t:Wi.stroke,fill:(r=e.fill)!==null&&r!==void 0?r:Wi.fill,horizontal:(n=e.horizontal)!==null&&n!==void 0?n:Wi.horizontal,horizontalFill:(i=e.horizontalFill)!==null&&i!==void 0?i:Wi.horizontalFill,vertical:(a=e.vertical)!==null&&a!==void 0?a:Wi.vertical,verticalFill:(o=e.verticalFill)!==null&&o!==void 0?o:Wi.verticalFill,x:K(e.x)?e.x:u.left,y:K(e.y)?e.y:u.top,width:K(e.width)?e.width:u.width,height:K(e.height)?e.height:u.height}),d=f.x,p=f.y,h=f.width,m=f.height,g=f.syncWithTicks,x=f.horizontalValues,y=f.verticalValues,v=jq(),b=Sq();if(!K(h)||h<=0||!K(m)||m<=0||!K(d)||d!==+d||!K(p)||p!==+p)return null;var S=f.verticalCoordinatesGenerator||DX,w=f.horizontalCoordinatesGenerator||RX,j=f.horizontalPoints,O=f.verticalPoints;if((!j||!j.length)&&Z(w)){var _=x&&x.length,P=w({yAxis:b?dt(dt({},b),{},{ticks:_?x:b.ticks}):void 0,width:s,height:l,offset:u},_?!0:g);xr(Array.isArray(P),"horizontalCoordinatesGenerator should return Array but instead it returned [".concat($i(P),"]")),Array.isArray(P)&&(j=P)}if((!O||!O.length)&&Z(S)){var N=y&&y.length,T=S({xAxis:v?dt(dt({},v),{},{ticks:N?y:v.ticks}):void 0,width:s,height:l,offset:u},N?!0:g);xr(Array.isArray(T),"verticalCoordinatesGenerator should return Array but instead it returned [".concat($i(T),"]")),Array.isArray(T)&&(O=T)}return A.createElement("g",{className:"recharts-cartesian-grid"},A.createElement(TX,{fill:f.fill,fillOpacity:f.fillOpacity,x:f.x,y:f.y,width:f.width,height:f.height,ry:f.ry}),A.createElement(CX,hi({},f,{offset:u,horizontalPoints:j,xAxis:v,yAxis:b})),A.createElement(MX,hi({},f,{offset:u,verticalPoints:O,xAxis:v,yAxis:b})),A.createElement(IX,hi({},f,{horizontalPoints:j})),A.createElement(LX,hi({},f,{verticalPoints:O})))}ht.displayName="CartesianGrid";var BX=["type","layout","connectNulls","ref"],FX=["key"];function Ha(e){"@babel/helpers - typeof";return Ha=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Ha(e)}function Y1(e,t){if(e==null)return{};var r=zX(e,t),n,i;if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i<a.length;i++)n=a[i],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function zX(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function rs(){return rs=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},rs.apply(this,arguments)}function q1(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function It(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?q1(Object(r),!0).forEach(function(n){hr(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):q1(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function Ui(e){return HX(e)||KX(e)||UX(e)||WX()}function WX(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
-In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function UX(e,t){if(e){if(typeof e=="string")return Om(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return Om(e,t)}}function KX(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function HX(e){if(Array.isArray(e))return Om(e)}function Om(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function VX(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function X1(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,ok(n.key),n)}}function GX(e,t,r){return t&&X1(e.prototype,t),r&&X1(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function YX(e,t,r){return t=Fc(t),qX(e,ak()?Reflect.construct(t,r||[],Fc(e).constructor):t.apply(e,r))}function qX(e,t){if(t&&(Ha(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return XX(e)}function XX(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function ak(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(ak=function(){return!!e})()}function Fc(e){return Fc=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},Fc(e)}function QX(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&_m(e,t)}function _m(e,t){return _m=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,i){return n.__proto__=i,n},_m(e,t)}function hr(e,t,r){return t=ok(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function ok(e){var t=ZX(e,"string");return Ha(t)=="symbol"?t:t+""}function ZX(e,t){if(Ha(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(Ha(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}var On=function(e){function t(){var r;VX(this,t);for(var n=arguments.length,i=new Array(n),a=0;a<n;a++)i[a]=arguments[a];return r=YX(this,t,[].concat(i)),hr(r,"state",{isAnimationFinished:!0,totalLength:0}),hr(r,"generateSimpleStrokeDasharray",function(o,s){return"".concat(s,"px ").concat(o-s,"px")}),hr(r,"getStrokeDasharray",function(o,s,l){var u=l.reduce(function(y,v){return y+v});if(!u)return r.generateSimpleStrokeDasharray(s,o);for(var f=Math.floor(o/u),d=o%u,p=s-o,h=[],m=0,g=0;m<l.length;g+=l[m],++m)if(g+l[m]>d){h=[].concat(Ui(l.slice(0,m)),[d-g]);break}var x=h.length%2===0?[0,p]:[p];return[].concat(Ui(t.repeat(l,f)),Ui(h),x).map(function(y){return"".concat(y,"px")}).join(", ")}),hr(r,"id",Gn("recharts-line-")),hr(r,"pathRef",function(o){r.mainCurve=o}),hr(r,"handleAnimationEnd",function(){r.setState({isAnimationFinished:!0}),r.props.onAnimationEnd&&r.props.onAnimationEnd()}),hr(r,"handleAnimationStart",function(){r.setState({isAnimationFinished:!1}),r.props.onAnimationStart&&r.props.onAnimationStart()}),r}return QX(t,e),GX(t,[{key:"componentDidMount",value:function(){if(this.props.isAnimationActive){var n=this.getTotalLength();this.setState({totalLength:n})}}},{key:"componentDidUpdate",value:function(){if(this.props.isAnimationActive){var n=this.getTotalLength();n!==this.state.totalLength&&this.setState({totalLength:n})}}},{key:"getTotalLength",value:function(){var n=this.mainCurve;try{return n&&n.getTotalLength&&n.getTotalLength()||0}catch{return 0}}},{key:"renderErrorBar",value:function(n,i){if(this.props.isAnimationActive&&!this.state.isAnimationFinished)return null;var a=this.props,o=a.points,s=a.xAxis,l=a.yAxis,u=a.layout,f=a.children,d=wt(f,vo);if(!d)return null;var p=function(g,x){return{x:g.x,y:g.y,value:g.value,errorVal:Oe(g.payload,x)}},h={clipPath:n?"url(#clipPath-".concat(i,")"):null};return A.createElement(te,h,d.map(function(m){return A.cloneElement(m,{key:"bar-".concat(m.props.dataKey),data:o,xAxis:s,yAxis:l,layout:u,dataPointFormatter:p})}))}},{key:"renderDots",value:function(n,i,a){var o=this.props.isAnimationActive;if(o&&!this.state.isAnimationFinished)return null;var s=this.props,l=s.dot,u=s.points,f=s.dataKey,d=q(this.props,!1),p=q(l,!0),h=u.map(function(g,x){var y=It(It(It({key:"dot-".concat(x),r:3},d),p),{},{index:x,cx:g.x,cy:g.y,value:g.value,dataKey:f,payload:g.payload,points:u});return t.renderDotItem(l,y)}),m={clipPath:n?"url(#clipPath-".concat(i?"":"dots-").concat(a,")"):null};return A.createElement(te,rs({className:"recharts-line-dots",key:"dots"},m),h)}},{key:"renderCurveStatically",value:function(n,i,a,o){var s=this.props,l=s.type,u=s.layout,f=s.connectNulls;s.ref;var d=Y1(s,BX),p=It(It(It({},q(d,!0)),{},{fill:"none",className:"recharts-line-curve",clipPath:i?"url(#clipPath-".concat(a,")"):null,points:n},o),{},{type:l,layout:u,connectNulls:f});return A.createElement(Ln,rs({},p,{pathRef:this.pathRef}))}},{key:"renderCurveWithAnimation",value:function(n,i){var a=this,o=this.props,s=o.points,l=o.strokeDasharray,u=o.isAnimationActive,f=o.animationBegin,d=o.animationDuration,p=o.animationEasing,h=o.animationId,m=o.animateNewValues,g=o.width,x=o.height,y=this.state,v=y.prevPoints,b=y.totalLength;return A.createElement(or,{begin:f,duration:d,isActive:u,easing:p,from:{t:0},to:{t:1},key:"line-".concat(h),onAnimationEnd:this.handleAnimationEnd,onAnimationStart:this.handleAnimationStart},function(S){var w=S.t;if(v){var j=v.length/s.length,O=s.map(function($,I){var D=Math.floor(I*j);if(v[D]){var L=v[D],C=$e(L.x,$.x),F=$e(L.y,$.y);return It(It({},$),{},{x:C(w),y:F(w)})}if(m){var M=$e(g*2,$.x),B=$e(x/2,$.y);return It(It({},$),{},{x:M(w),y:B(w)})}return It(It({},$),{},{x:$.x,y:$.y})});return a.renderCurveStatically(O,n,i)}var _=$e(0,b),P=_(w),N;if(l){var T="".concat(l).split(/[,\s]+/gim).map(function($){return parseFloat($)});N=a.getStrokeDasharray(P,b,T)}else N=a.generateSimpleStrokeDasharray(b,P);return a.renderCurveStatically(s,n,i,{strokeDasharray:N})})}},{key:"renderCurve",value:function(n,i){var a=this.props,o=a.points,s=a.isAnimationActive,l=this.state,u=l.prevPoints,f=l.totalLength;return s&&o&&o.length&&(!u&&f>0||!Fn(u,o))?this.renderCurveWithAnimation(n,i):this.renderCurveStatically(o,n,i)}},{key:"render",value:function(){var n,i=this.props,a=i.hide,o=i.dot,s=i.points,l=i.className,u=i.xAxis,f=i.yAxis,d=i.top,p=i.left,h=i.width,m=i.height,g=i.isAnimationActive,x=i.id;if(a||!s||!s.length)return null;var y=this.state.isAnimationFinished,v=s.length===1,b=ee("recharts-line",l),S=u&&u.allowDataOverflow,w=f&&f.allowDataOverflow,j=S||w,O=Q(x)?this.id:x,_=(n=q(o,!1))!==null&&n!==void 0?n:{r:3,strokeWidth:2},P=_.r,N=P===void 0?3:P,T=_.strokeWidth,$=T===void 0?2:T,I=qS(o)?o:{},D=I.clipDot,L=D===void 0?!0:D,C=N*2+$;return A.createElement(te,{className:b},S||w?A.createElement("defs",null,A.createElement("clipPath",{id:"clipPath-".concat(O)},A.createElement("rect",{x:S?p:p-h/2,y:w?d:d-m/2,width:S?h:h*2,height:w?m:m*2})),!L&&A.createElement("clipPath",{id:"clipPath-dots-".concat(O)},A.createElement("rect",{x:p-C/2,y:d-C/2,width:h+C,height:m+C}))):null,!v&&this.renderCurve(j,O),this.renderErrorBar(j,O),(v||o)&&this.renderDots(j,L,O),(!g||y)&&br.renderCallByParent(this.props,s))}}],[{key:"getDerivedStateFromProps",value:function(n,i){return n.animationId!==i.prevAnimationId?{prevAnimationId:n.animationId,curPoints:n.points,prevPoints:i.curPoints}:n.points!==i.curPoints?{curPoints:n.points}:null}},{key:"repeat",value:function(n,i){for(var a=n.length%2!==0?[].concat(Ui(n),[0]):n,o=[],s=0;s<i;++s)o=[].concat(Ui(o),Ui(a));return o}},{key:"renderDotItem",value:function(n,i){var a;if(A.isValidElement(n))a=A.cloneElement(n,i);else if(Z(n))a=n(i);else{var o=i.key,s=Y1(i,FX),l=ee("recharts-line-dot",typeof n!="boolean"?n.className:"");a=A.createElement(xl,rs({key:o},s,{className:l}))}return a}}])}(k.PureComponent);hr(On,"displayName","Line");hr(On,"defaultProps",{xAxisId:0,yAxisId:0,connectNulls:!1,activeDot:!0,dot:!0,legendType:"line",stroke:"#3182bd",strokeWidth:1,fill:"#fff",points:[],isAnimationActive:!sn.isSsr,animateNewValues:!0,animationBegin:0,animationDuration:1500,animationEasing:"ease",hide:!1,label:!1});hr(On,"getComposedData",function(e){var t=e.props,r=e.xAxis,n=e.yAxis,i=e.xAxisTicks,a=e.yAxisTicks,o=e.dataKey,s=e.bandSize,l=e.displayedData,u=e.offset,f=t.layout,d=l.map(function(p,h){var m=Oe(p,o);return f==="horizontal"?{x:Ca({axis:r,ticks:i,bandSize:s,entry:p,index:h}),y:Q(m)?null:n.scale(m),value:m,payload:p}:{x:Q(m)?null:r.scale(m),y:Ca({axis:n,ticks:a,bandSize:s,entry:p,index:h}),value:m,payload:p}});return It({points:d,layout:f},u)});var JX=["layout","type","stroke","connectNulls","isRange","ref"],eQ=["key"],sk;function Va(e){"@babel/helpers - typeof";return Va=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Va(e)}function lk(e,t){if(e==null)return{};var r=tQ(e,t),n,i;if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i<a.length;i++)n=a[i],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function tQ(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function mi(){return mi=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},mi.apply(this,arguments)}function Q1(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function dn(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Q1(Object(r),!0).forEach(function(n){Nr(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Q1(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function rQ(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function Z1(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,ck(n.key),n)}}function nQ(e,t,r){return t&&Z1(e.prototype,t),r&&Z1(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function iQ(e,t,r){return t=zc(t),aQ(e,uk()?Reflect.construct(t,r||[],zc(e).constructor):t.apply(e,r))}function aQ(e,t){if(t&&(Va(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return oQ(e)}function oQ(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function uk(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(uk=function(){return!!e})()}function zc(e){return zc=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},zc(e)}function sQ(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Pm(e,t)}function Pm(e,t){return Pm=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,i){return n.__proto__=i,n},Pm(e,t)}function Nr(e,t,r){return t=ck(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function ck(e){var t=lQ(e,"string");return Va(t)=="symbol"?t:t+""}function lQ(e,t){if(Va(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(Va(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}var Sr=function(e){function t(){var r;rQ(this,t);for(var n=arguments.length,i=new Array(n),a=0;a<n;a++)i[a]=arguments[a];return r=iQ(this,t,[].concat(i)),Nr(r,"state",{isAnimationFinished:!0}),Nr(r,"id",Gn("recharts-area-")),Nr(r,"handleAnimationEnd",function(){var o=r.props.onAnimationEnd;r.setState({isAnimationFinished:!0}),Z(o)&&o()}),Nr(r,"handleAnimationStart",function(){var o=r.props.onAnimationStart;r.setState({isAnimationFinished:!1}),Z(o)&&o()}),r}return sQ(t,e),nQ(t,[{key:"renderDots",value:function(n,i,a){var o=this.props.isAnimationActive,s=this.state.isAnimationFinished;if(o&&!s)return null;var l=this.props,u=l.dot,f=l.points,d=l.dataKey,p=q(this.props,!1),h=q(u,!0),m=f.map(function(x,y){var v=dn(dn(dn({key:"dot-".concat(y),r:3},p),h),{},{index:y,cx:x.x,cy:x.y,dataKey:d,value:x.value,payload:x.payload,points:f});return t.renderDotItem(u,v)}),g={clipPath:n?"url(#clipPath-".concat(i?"":"dots-").concat(a,")"):null};return A.createElement(te,mi({className:"recharts-area-dots"},g),m)}},{key:"renderHorizontalRect",value:function(n){var i=this.props,a=i.baseLine,o=i.points,s=i.strokeWidth,l=o[0].x,u=o[o.length-1].x,f=n*Math.abs(l-u),d=jn(o.map(function(p){return p.y||0}));return K(a)&&typeof a=="number"?d=Math.max(a,d):a&&Array.isArray(a)&&a.length&&(d=Math.max(jn(a.map(function(p){return p.y||0})),d)),K(d)?A.createElement("rect",{x:l<u?l:l-f,y:0,width:f,height:Math.floor(d+(s?parseInt("".concat(s),10):1))}):null}},{key:"renderVerticalRect",value:function(n){var i=this.props,a=i.baseLine,o=i.points,s=i.strokeWidth,l=o[0].y,u=o[o.length-1].y,f=n*Math.abs(l-u),d=jn(o.map(function(p){return p.x||0}));return K(a)&&typeof a=="number"?d=Math.max(a,d):a&&Array.isArray(a)&&a.length&&(d=Math.max(jn(a.map(function(p){return p.x||0})),d)),K(d)?A.createElement("rect",{x:0,y:l<u?l:l-f,width:d+(s?parseInt("".concat(s),10):1),height:Math.floor(f)}):null}},{key:"renderClipRect",value:function(n){var i=this.props.layout;return i==="vertical"?this.renderVerticalRect(n):this.renderHorizontalRect(n)}},{key:"renderAreaStatically",value:function(n,i,a,o){var s=this.props,l=s.layout,u=s.type,f=s.stroke,d=s.connectNulls,p=s.isRange;s.ref;var h=lk(s,JX);return A.createElement(te,{clipPath:a?"url(#clipPath-".concat(o,")"):null},A.createElement(Ln,mi({},q(h,!0),{points:n,connectNulls:d,type:u,baseLine:i,layout:l,stroke:"none",className:"recharts-area-area"})),f!=="none"&&A.createElement(Ln,mi({},q(this.props,!1),{className:"recharts-area-curve",layout:l,type:u,connectNulls:d,fill:"none",points:n})),f!=="none"&&p&&A.createElement(Ln,mi({},q(this.props,!1),{className:"recharts-area-curve",layout:l,type:u,connectNulls:d,fill:"none",points:i})))}},{key:"renderAreaWithAnimation",value:function(n,i){var a=this,o=this.props,s=o.points,l=o.baseLine,u=o.isAnimationActive,f=o.animationBegin,d=o.animationDuration,p=o.animationEasing,h=o.animationId,m=this.state,g=m.prevPoints,x=m.prevBaseLine;return A.createElement(or,{begin:f,duration:d,isActive:u,easing:p,from:{t:0},to:{t:1},key:"area-".concat(h),onAnimationEnd:this.handleAnimationEnd,onAnimationStart:this.handleAnimationStart},function(y){var v=y.t;if(g){var b=g.length/s.length,S=s.map(function(_,P){var N=Math.floor(P*b);if(g[N]){var T=g[N],$=$e(T.x,_.x),I=$e(T.y,_.y);return dn(dn({},_),{},{x:$(v),y:I(v)})}return _}),w;if(K(l)&&typeof l=="number"){var j=$e(x,l);w=j(v)}else if(Q(l)||lo(l)){var O=$e(x,0);w=O(v)}else w=l.map(function(_,P){var N=Math.floor(P*b);if(x[N]){var T=x[N],$=$e(T.x,_.x),I=$e(T.y,_.y);return dn(dn({},_),{},{x:$(v),y:I(v)})}return _});return a.renderAreaStatically(S,w,n,i)}return A.createElement(te,null,A.createElement("defs",null,A.createElement("clipPath",{id:"animationClipPath-".concat(i)},a.renderClipRect(v))),A.createElement(te,{clipPath:"url(#animationClipPath-".concat(i,")")},a.renderAreaStatically(s,l,n,i)))})}},{key:"renderArea",value:function(n,i){var a=this.props,o=a.points,s=a.baseLine,l=a.isAnimationActive,u=this.state,f=u.prevPoints,d=u.prevBaseLine,p=u.totalLength;return l&&o&&o.length&&(!f&&p>0||!Fn(f,o)||!Fn(d,s))?this.renderAreaWithAnimation(n,i):this.renderAreaStatically(o,s,n,i)}},{key:"render",value:function(){var n,i=this.props,a=i.hide,o=i.dot,s=i.points,l=i.className,u=i.top,f=i.left,d=i.xAxis,p=i.yAxis,h=i.width,m=i.height,g=i.isAnimationActive,x=i.id;if(a||!s||!s.length)return null;var y=this.state.isAnimationFinished,v=s.length===1,b=ee("recharts-area",l),S=d&&d.allowDataOverflow,w=p&&p.allowDataOverflow,j=S||w,O=Q(x)?this.id:x,_=(n=q(o,!1))!==null&&n!==void 0?n:{r:3,strokeWidth:2},P=_.r,N=P===void 0?3:P,T=_.strokeWidth,$=T===void 0?2:T,I=qS(o)?o:{},D=I.clipDot,L=D===void 0?!0:D,C=N*2+$;return A.createElement(te,{className:b},S||w?A.createElement("defs",null,A.createElement("clipPath",{id:"clipPath-".concat(O)},A.createElement("rect",{x:S?f:f-h/2,y:w?u:u-m/2,width:S?h:h*2,height:w?m:m*2})),!L&&A.createElement("clipPath",{id:"clipPath-dots-".concat(O)},A.createElement("rect",{x:f-C/2,y:u-C/2,width:h+C,height:m+C}))):null,v?null:this.renderArea(j,O),(o||v)&&this.renderDots(j,L,O),(!g||y)&&br.renderCallByParent(this.props,s))}}],[{key:"getDerivedStateFromProps",value:function(n,i){return n.animationId!==i.prevAnimationId?{prevAnimationId:n.animationId,curPoints:n.points,curBaseLine:n.baseLine,prevPoints:i.curPoints,prevBaseLine:i.curBaseLine}:n.points!==i.curPoints||n.baseLine!==i.curBaseLine?{curPoints:n.points,curBaseLine:n.baseLine}:null}}])}(k.PureComponent);sk=Sr;Nr(Sr,"displayName","Area");Nr(Sr,"defaultProps",{stroke:"#3182bd",fill:"#3182bd",fillOpacity:.6,xAxisId:0,yAxisId:0,legendType:"line",connectNulls:!1,points:[],dot:!1,activeDot:!0,hide:!1,isAnimationActive:!sn.isSsr,animationBegin:0,animationDuration:1500,animationEasing:"ease"});Nr(Sr,"getBaseValue",function(e,t,r,n){var i=e.layout,a=e.baseValue,o=t.props.baseValue,s=o??a;if(K(s)&&typeof s=="number")return s;var l=i==="horizontal"?n:r,u=l.scale.domain();if(l.type==="number"){var f=Math.max(u[0],u[1]),d=Math.min(u[0],u[1]);return s==="dataMin"?d:s==="dataMax"||f<0?f:Math.max(Math.min(u[0],u[1]),0)}return s==="dataMin"?u[0]:s==="dataMax"?u[1]:u[0]});Nr(Sr,"getComposedData",function(e){var t=e.props,r=e.item,n=e.xAxis,i=e.yAxis,a=e.xAxisTicks,o=e.yAxisTicks,s=e.bandSize,l=e.dataKey,u=e.stackedData,f=e.dataStartIndex,d=e.displayedData,p=e.offset,h=t.layout,m=u&&u.length,g=sk.getBaseValue(t,r,n,i),x=h==="horizontal",y=!1,v=d.map(function(S,w){var j;m?j=u[f+w]:(j=Oe(S,l),Array.isArray(j)?y=!0:j=[g,j]);var O=j[1]==null||m&&Oe(S,l)==null;return x?{x:Ca({axis:n,ticks:a,bandSize:s,entry:S,index:w}),y:O?null:i.scale(j[1]),value:j,payload:S}:{x:O?null:n.scale(j[1]),y:Ca({axis:i,ticks:o,bandSize:s,entry:S,index:w}),value:j,payload:S}}),b;return m||y?b=v.map(function(S){var w=Array.isArray(S.value)?S.value[0]:null;return x?{x:S.x,y:w!=null&&S.y!=null?i.scale(w):null}:{x:w!=null?n.scale(w):null,y:S.y}}):b=x?i.scale(g):n.scale(g),dn({points:v,baseLine:b,layout:h,isRange:y},p)});Nr(Sr,"renderDotItem",function(e,t){var r;if(A.isValidElement(e))r=A.cloneElement(e,t);else if(Z(e))r=e(t);else{var n=ee("recharts-area-dot",typeof e!="boolean"?e.className:""),i=t.key,a=lk(t,eQ);r=A.createElement(xl,mi({},a,{key:i,className:n}))}return r});function Ga(e){"@babel/helpers - typeof";return Ga=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Ga(e)}function uQ(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function cQ(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,pk(n.key),n)}}function fQ(e,t,r){return t&&cQ(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function dQ(e,t,r){return t=Wc(t),pQ(e,fk()?Reflect.construct(t,r||[],Wc(e).constructor):t.apply(e,r))}function pQ(e,t){if(t&&(Ga(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return hQ(e)}function hQ(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function fk(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(fk=function(){return!!e})()}function Wc(e){return Wc=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},Wc(e)}function mQ(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&km(e,t)}function km(e,t){return km=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,i){return n.__proto__=i,n},km(e,t)}function dk(e,t,r){return t=pk(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function pk(e){var t=vQ(e,"string");return Ga(t)=="symbol"?t:t+""}function vQ(e,t){if(Ga(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(Ga(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}var bl=function(e){function t(){return uQ(this,t),dQ(this,t,arguments)}return mQ(t,e),fQ(t,[{key:"render",value:function(){return null}}])}(k.Component);dk(bl,"displayName","ZAxis");dk(bl,"defaultProps",{zAxisId:0,range:[64,64],scale:"auto",type:"number"});var yQ=["option","isActive"];function ns(){return ns=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},ns.apply(this,arguments)}function gQ(e,t){if(e==null)return{};var r=xQ(e,t),n,i;if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i<a.length;i++)n=a[i],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function xQ(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function bQ(e){var t=e.option,r=e.isActive,n=gQ(e,yQ);return typeof t=="string"?k.createElement(Ac,ns({option:k.createElement(Ef,ns({type:t},n)),isActive:r,shapeType:"symbols"},n)):k.createElement(Ac,ns({option:t,isActive:r,shapeType:"symbols"},n))}function Ya(e){"@babel/helpers - typeof";return Ya=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Ya(e)}function is(){return is=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},is.apply(this,arguments)}function J1(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function Xt(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?J1(Object(r),!0).forEach(function(n){_n(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):J1(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function wQ(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function ew(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,mk(n.key),n)}}function jQ(e,t,r){return t&&ew(e.prototype,t),r&&ew(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function SQ(e,t,r){return t=Uc(t),OQ(e,hk()?Reflect.construct(t,r||[],Uc(e).constructor):t.apply(e,r))}function OQ(e,t){if(t&&(Ya(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return _Q(e)}function _Q(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function hk(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(hk=function(){return!!e})()}function Uc(e){return Uc=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},Uc(e)}function PQ(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Am(e,t)}function Am(e,t){return Am=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,i){return n.__proto__=i,n},Am(e,t)}function _n(e,t,r){return t=mk(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function mk(e){var t=kQ(e,"string");return Ya(t)=="symbol"?t:t+""}function kQ(e,t){if(Ya(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(Ya(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}var bi=function(e){function t(){var r;wQ(this,t);for(var n=arguments.length,i=new Array(n),a=0;a<n;a++)i[a]=arguments[a];return r=SQ(this,t,[].concat(i)),_n(r,"state",{isAnimationFinished:!1}),_n(r,"handleAnimationEnd",function(){r.setState({isAnimationFinished:!0})}),_n(r,"handleAnimationStart",function(){r.setState({isAnimationFinished:!1})}),_n(r,"id",Gn("recharts-scatter-")),r}return PQ(t,e),jQ(t,[{key:"renderSymbolsStatically",value:function(n){var i=this,a=this.props,o=a.shape,s=a.activeShape,l=a.activeIndex,u=q(this.props,!1);return n.map(function(f,d){var p=l===d,h=p?s:o,m=Xt(Xt({},u),f);return A.createElement(te,is({className:"recharts-scatter-symbol",key:"symbol-".concat(f==null?void 0:f.cx,"-").concat(f==null?void 0:f.cy,"-").concat(f==null?void 0:f.size,"-").concat(d)},Bn(i.props,f,d),{role:"img"}),A.createElement(bQ,is({option:h,isActive:p,key:"symbol-".concat(d)},m)))})}},{key:"renderSymbolsWithAnimation",value:function(){var n=this,i=this.props,a=i.points,o=i.isAnimationActive,s=i.animationBegin,l=i.animationDuration,u=i.animationEasing,f=i.animationId,d=this.state.prevPoints;return A.createElement(or,{begin:s,duration:l,isActive:o,easing:u,from:{t:0},to:{t:1},key:"pie-".concat(f),onAnimationEnd:this.handleAnimationEnd,onAnimationStart:this.handleAnimationStart},function(p){var h=p.t,m=a.map(function(g,x){var y=d&&d[x];if(y){var v=$e(y.cx,g.cx),b=$e(y.cy,g.cy),S=$e(y.size,g.size);return Xt(Xt({},g),{},{cx:v(h),cy:b(h),size:S(h)})}var w=$e(0,g.size);return Xt(Xt({},g),{},{size:w(h)})});return A.createElement(te,null,n.renderSymbolsStatically(m))})}},{key:"renderSymbols",value:function(){var n=this.props,i=n.points,a=n.isAnimationActive,o=this.state.prevPoints;return a&&i&&i.length&&(!o||!Fn(o,i))?this.renderSymbolsWithAnimation():this.renderSymbolsStatically(i)}},{key:"renderErrorBar",value:function(){var n=this.props.isAnimationActive;if(n&&!this.state.isAnimationFinished)return null;var i=this.props,a=i.points,o=i.xAxis,s=i.yAxis,l=i.children,u=wt(l,vo);return u?u.map(function(f,d){var p=f.props,h=p.direction,m=p.dataKey;return A.cloneElement(f,{key:"".concat(h,"-").concat(m,"-").concat(a[d]),data:a,xAxis:o,yAxis:s,layout:h==="x"?"vertical":"horizontal",dataPointFormatter:function(x,y){return{x:x.cx,y:x.cy,value:h==="x"?+x.node.x:+x.node.y,errorVal:Oe(x,y)}}})}):null}},{key:"renderLine",value:function(){var n=this.props,i=n.points,a=n.line,o=n.lineType,s=n.lineJointType,l=q(this.props,!1),u=q(a,!1),f,d;if(o==="joint")f=i.map(function(b){return{x:b.cx,y:b.cy}});else if(o==="fitting"){var p=lM(i),h=p.xmin,m=p.xmax,g=p.a,x=p.b,y=function(S){return g*S+x};f=[{x:h,y:y(h)},{x:m,y:y(m)}]}var v=Xt(Xt(Xt({},l),{},{fill:"none",stroke:l&&l.fill},u),{},{points:f});return A.isValidElement(a)?d=A.cloneElement(a,v):Z(a)?d=a(v):d=A.createElement(Ln,is({},v,{type:s})),A.createElement(te,{className:"recharts-scatter-line",key:"recharts-scatter-line"},d)}},{key:"render",value:function(){var n=this.props,i=n.hide,a=n.points,o=n.line,s=n.className,l=n.xAxis,u=n.yAxis,f=n.left,d=n.top,p=n.width,h=n.height,m=n.id,g=n.isAnimationActive;if(i||!a||!a.length)return null;var x=this.state.isAnimationFinished,y=ee("recharts-scatter",s),v=l&&l.allowDataOverflow,b=u&&u.allowDataOverflow,S=v||b,w=Q(m)?this.id:m;return A.createElement(te,{className:y,clipPath:S?"url(#clipPath-".concat(w,")"):null},v||b?A.createElement("defs",null,A.createElement("clipPath",{id:"clipPath-".concat(w)},A.createElement("rect",{x:v?f:f-p/2,y:b?d:d-h/2,width:v?p:p*2,height:b?h:h*2}))):null,o&&this.renderLine(),this.renderErrorBar(),A.createElement(te,{key:"recharts-scatter-symbols"},this.renderSymbols()),(!g||x)&&br.renderCallByParent(this.props,a))}}],[{key:"getDerivedStateFromProps",value:function(n,i){return n.animationId!==i.prevAnimationId?{prevAnimationId:n.animationId,curPoints:n.points,prevPoints:i.curPoints}:n.points!==i.curPoints?{curPoints:n.points}:null}}])}(k.PureComponent);_n(bi,"displayName","Scatter");_n(bi,"defaultProps",{xAxisId:0,yAxisId:0,zAxisId:0,legendType:"circle",lineType:"joint",lineJointType:"linear",data:[],shape:"circle",hide:!1,isAnimationActive:!sn.isSsr,animationBegin:0,animationDuration:400,animationEasing:"linear"});_n(bi,"getComposedData",function(e){var t=e.xAxis,r=e.yAxis,n=e.zAxis,i=e.item,a=e.displayedData,o=e.xAxisTicks,s=e.yAxisTicks,l=e.offset,u=i.props.tooltipType,f=wt(i.props.children,jr),d=Q(t.dataKey)?i.props.dataKey:t.dataKey,p=Q(r.dataKey)?i.props.dataKey:r.dataKey,h=n&&n.dataKey,m=n?n.range:bl.defaultProps.range,g=m&&m[0],x=t.scale.bandwidth?t.scale.bandwidth():0,y=r.scale.bandwidth?r.scale.bandwidth():0,v=a.map(function(b,S){var w=Oe(b,d),j=Oe(b,p),O=!Q(h)&&Oe(b,h)||"-",_=[{name:Q(t.dataKey)?i.props.name:t.name||t.dataKey,unit:t.unit||"",value:w,payload:b,dataKey:d,type:u},{name:Q(r.dataKey)?i.props.name:r.name||r.dataKey,unit:r.unit||"",value:j,payload:b,dataKey:p,type:u}];O!=="-"&&_.push({name:n.name||n.dataKey,unit:n.unit||"",value:O,payload:b,dataKey:h,type:u});var P=Ca({axis:t,ticks:o,bandSize:x,entry:b,index:S,dataKey:d}),N=Ca({axis:r,ticks:s,bandSize:y,entry:b,index:S,dataKey:p}),T=O!=="-"?n.scale(O):g,$=Math.sqrt(Math.max(T,0)/Math.PI);return Xt(Xt({},b),{},{cx:P,cy:N,x:P-$,y:N-$,xAxis:t,yAxis:r,zAxis:n,width:2*$,height:2*$,size:T,node:{x:w,y:j,z:O},tooltipPayload:_,tooltipPosition:{x:P,y:N},payload:b},f&&f[S]&&f[S].props)});return Xt({points:v},l)});function qa(e){"@babel/helpers - typeof";return qa=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},qa(e)}function AQ(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function NQ(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,gk(n.key),n)}}function $Q(e,t,r){return t&&NQ(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function EQ(e,t,r){return t=Kc(t),TQ(e,vk()?Reflect.construct(t,r||[],Kc(e).constructor):t.apply(e,r))}function TQ(e,t){if(t&&(qa(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return CQ(e)}function CQ(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function vk(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(vk=function(){return!!e})()}function Kc(e){return Kc=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},Kc(e)}function MQ(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Nm(e,t)}function Nm(e,t){return Nm=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,i){return n.__proto__=i,n},Nm(e,t)}function yk(e,t,r){return t=gk(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function gk(e){var t=IQ(e,"string");return qa(t)=="symbol"?t:t+""}function IQ(e,t){if(qa(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(qa(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}function $m(){return $m=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},$m.apply(this,arguments)}function LQ(e){var t=e.xAxisId,r=Iy(),n=Ly(),i=GP(t);return i==null?null:k.createElement(yo,$m({},i,{className:ee("recharts-".concat(i.axisType," ").concat(i.axisType),i.className),viewBox:{x:0,y:0,width:r,height:n},ticksGenerator:function(o){return Hr(o,!0)}}))}var Re=function(e){function t(){return AQ(this,t),EQ(this,t,arguments)}return MQ(t,e),$Q(t,[{key:"render",value:function(){return k.createElement(LQ,this.props)}}])}(k.Component);yk(Re,"displayName","XAxis");yk(Re,"defaultProps",{allowDecimals:!0,hide:!1,orientation:"bottom",width:0,height:30,mirror:!1,xAxisId:0,tickCount:5,type:"category",padding:{left:0,right:0},allowDataOverflow:!1,scale:"auto",reversed:!1,allowDuplicatedCategory:!0});function Xa(e){"@babel/helpers - typeof";return Xa=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Xa(e)}function DQ(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function RQ(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,wk(n.key),n)}}function BQ(e,t,r){return t&&RQ(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function FQ(e,t,r){return t=Hc(t),zQ(e,xk()?Reflect.construct(t,r||[],Hc(e).constructor):t.apply(e,r))}function zQ(e,t){if(t&&(Xa(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return WQ(e)}function WQ(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function xk(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(xk=function(){return!!e})()}function Hc(e){return Hc=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},Hc(e)}function UQ(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Em(e,t)}function Em(e,t){return Em=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,i){return n.__proto__=i,n},Em(e,t)}function bk(e,t,r){return t=wk(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function wk(e){var t=KQ(e,"string");return Xa(t)=="symbol"?t:t+""}function KQ(e,t){if(Xa(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(Xa(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}function Tm(){return Tm=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},Tm.apply(this,arguments)}var HQ=function(t){var r=t.yAxisId,n=Iy(),i=Ly(),a=YP(r);return a==null?null:k.createElement(yo,Tm({},a,{className:ee("recharts-".concat(a.axisType," ").concat(a.axisType),a.className),viewBox:{x:0,y:0,width:n,height:i},ticksGenerator:function(s){return Hr(s,!0)}}))},Be=function(e){function t(){return DQ(this,t),FQ(this,t,arguments)}return UQ(t,e),BQ(t,[{key:"render",value:function(){return k.createElement(HQ,this.props)}}])}(k.Component);bk(Be,"displayName","YAxis");bk(Be,"defaultProps",{allowDuplicatedCategory:!0,allowDecimals:!0,hide:!1,orientation:"left",width:60,height:0,mirror:!1,yAxisId:0,tickCount:5,type:"number",padding:{top:0,bottom:0},allowDataOverflow:!1,scale:"auto",reversed:!1});function tw(e){return qQ(e)||YQ(e)||GQ(e)||VQ()}function VQ(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
-In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function GQ(e,t){if(e){if(typeof e=="string")return Cm(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return Cm(e,t)}}function YQ(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function qQ(e){if(Array.isArray(e))return Cm(e)}function Cm(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}var Mm=function(t,r,n,i,a){var o=wt(t,Ry),s=wt(t,ed),l=[].concat(tw(o),tw(s)),u=wt(t,rd),f="".concat(i,"Id"),d=i[0],p=r;if(l.length&&(p=l.reduce(function(g,x){if(x.props[f]===n&&Cr(x.props,"extendDomain")&&K(x.props[d])){var y=x.props[d];return[Math.min(g[0],y),Math.max(g[1],y)]}return g},p)),u.length){var h="".concat(d,"1"),m="".concat(d,"2");p=u.reduce(function(g,x){if(x.props[f]===n&&Cr(x.props,"extendDomain")&&K(x.props[h])&&K(x.props[m])){var y=x.props[h],v=x.props[m];return[Math.min(g[0],y,v),Math.max(g[1],y,v)]}return g},p)}return a&&a.length&&(p=a.reduce(function(g,x){return K(x)?[Math.min(g[0],x),Math.max(g[1],x)]:g},p)),p},jk={exports:{}};(function(e){var t=Object.prototype.hasOwnProperty,r="~";function n(){}Object.create&&(n.prototype=Object.create(null),new n().__proto__||(r=!1));function i(l,u,f){this.fn=l,this.context=u,this.once=f||!1}function a(l,u,f,d,p){if(typeof f!="function")throw new TypeError("The listener must be a function");var h=new i(f,d||l,p),m=r?r+u:u;return l._events[m]?l._events[m].fn?l._events[m]=[l._events[m],h]:l._events[m].push(h):(l._events[m]=h,l._eventsCount++),l}function o(l,u){--l._eventsCount===0?l._events=new n:delete l._events[u]}function s(){this._events=new n,this._eventsCount=0}s.prototype.eventNames=function(){var u=[],f,d;if(this._eventsCount===0)return u;for(d in f=this._events)t.call(f,d)&&u.push(r?d.slice(1):d);return Object.getOwnPropertySymbols?u.concat(Object.getOwnPropertySymbols(f)):u},s.prototype.listeners=function(u){var f=r?r+u:u,d=this._events[f];if(!d)return[];if(d.fn)return[d.fn];for(var p=0,h=d.length,m=new Array(h);p<h;p++)m[p]=d[p].fn;return m},s.prototype.listenerCount=function(u){var f=r?r+u:u,d=this._events[f];return d?d.fn?1:d.length:0},s.prototype.emit=function(u,f,d,p,h,m){var g=r?r+u:u;if(!this._events[g])return!1;var x=this._events[g],y=arguments.length,v,b;if(x.fn){switch(x.once&&this.removeListener(u,x.fn,void 0,!0),y){case 1:return x.fn.call(x.context),!0;case 2:return x.fn.call(x.context,f),!0;case 3:return x.fn.call(x.context,f,d),!0;case 4:return x.fn.call(x.context,f,d,p),!0;case 5:return x.fn.call(x.context,f,d,p,h),!0;case 6:return x.fn.call(x.context,f,d,p,h,m),!0}for(b=1,v=new Array(y-1);b<y;b++)v[b-1]=arguments[b];x.fn.apply(x.context,v)}else{var S=x.length,w;for(b=0;b<S;b++)switch(x[b].once&&this.removeListener(u,x[b].fn,void 0,!0),y){case 1:x[b].fn.call(x[b].context);break;case 2:x[b].fn.call(x[b].context,f);break;case 3:x[b].fn.call(x[b].context,f,d);break;case 4:x[b].fn.call(x[b].context,f,d,p);break;default:if(!v)for(w=1,v=new Array(y-1);w<y;w++)v[w-1]=arguments[w];x[b].fn.apply(x[b].context,v)}}return!0},s.prototype.on=function(u,f,d){return a(this,u,f,d,!1)},s.prototype.once=function(u,f,d){return a(this,u,f,d,!0)},s.prototype.removeListener=function(u,f,d,p){var h=r?r+u:u;if(!this._events[h])return this;if(!f)return o(this,h),this;var m=this._events[h];if(m.fn)m.fn===f&&(!p||m.once)&&(!d||m.context===d)&&o(this,h);else{for(var g=0,x=[],y=m.length;g<y;g++)(m[g].fn!==f||p&&!m[g].once||d&&m[g].context!==d)&&x.push(m[g]);x.length?this._events[h]=x.length===1?x[0]:x:o(this,h)}return this},s.prototype.removeAllListeners=function(u){var f;return u?(f=r?r+u:u,this._events[f]&&o(this,f)):(this._events=new n,this._eventsCount=0),this},s.prototype.off=s.prototype.removeListener,s.prototype.addListener=s.prototype.on,s.prefixed=r,s.EventEmitter=s,e.exports=s})(jk);var XQ=jk.exports;const QQ=de(XQ);var ap=new QQ,op="recharts.syncMouseEvents";function nl(e){"@babel/helpers - typeof";return nl=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},nl(e)}function ZQ(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function JQ(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,Sk(n.key),n)}}function eZ(e,t,r){return t&&JQ(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function sp(e,t,r){return t=Sk(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function Sk(e){var t=tZ(e,"string");return nl(t)=="symbol"?t:t+""}function tZ(e,t){if(nl(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(nl(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}var rZ=function(){function e(){ZQ(this,e),sp(this,"activeIndex",0),sp(this,"coordinateList",[]),sp(this,"layout","horizontal")}return eZ(e,[{key:"setDetails",value:function(r){var n,i=r.coordinateList,a=i===void 0?null:i,o=r.container,s=o===void 0?null:o,l=r.layout,u=l===void 0?null:l,f=r.offset,d=f===void 0?null:f,p=r.mouseHandlerCallback,h=p===void 0?null:p;this.coordinateList=(n=a??this.coordinateList)!==null&&n!==void 0?n:[],this.container=s??this.container,this.layout=u??this.layout,this.offset=d??this.offset,this.mouseHandlerCallback=h??this.mouseHandlerCallback,this.activeIndex=Math.min(Math.max(this.activeIndex,0),this.coordinateList.length-1)}},{key:"focus",value:function(){this.spoofMouse()}},{key:"keyboardEvent",value:function(r){if(this.coordinateList.length!==0)switch(r.key){case"ArrowRight":{if(this.layout!=="horizontal")return;this.activeIndex=Math.min(this.activeIndex+1,this.coordinateList.length-1),this.spoofMouse();break}case"ArrowLeft":{if(this.layout!=="horizontal")return;this.activeIndex=Math.max(this.activeIndex-1,0),this.spoofMouse();break}}}},{key:"setIndex",value:function(r){this.activeIndex=r}},{key:"spoofMouse",value:function(){var r,n;if(this.layout==="horizontal"&&this.coordinateList.length!==0){var i=this.container.getBoundingClientRect(),a=i.x,o=i.y,s=i.height,l=this.coordinateList[this.activeIndex].coordinate,u=((r=window)===null||r===void 0?void 0:r.scrollX)||0,f=((n=window)===null||n===void 0?void 0:n.scrollY)||0,d=a+l+u,p=o+this.offset.top+s/2+f;this.mouseHandlerCallback({pageX:d,pageY:p})}}}])}();function nZ(e,t,r){if(r==="number"&&t===!0&&Array.isArray(e)){var n=e==null?void 0:e[0],i=e==null?void 0:e[1];if(n&&i&&K(n)&&K(i))return!0}return!1}function iZ(e,t,r,n){var i=n/2;return{stroke:"none",fill:"#ccc",x:e==="horizontal"?t.x-i:r.left+.5,y:e==="horizontal"?r.top+.5:t.y-i,width:e==="horizontal"?n:r.width-1,height:e==="horizontal"?r.height-1:n}}function Ok(e){var t=e.cx,r=e.cy,n=e.radius,i=e.startAngle,a=e.endAngle,o=xe(t,r,n,i),s=xe(t,r,n,a);return{points:[o,s],cx:t,cy:r,radius:n,startAngle:i,endAngle:a}}function aZ(e,t,r){var n,i,a,o;if(e==="horizontal")n=t.x,a=n,i=r.top,o=r.top+r.height;else if(e==="vertical")i=t.y,o=i,n=r.left,a=r.left+r.width;else if(t.cx!=null&&t.cy!=null)if(e==="centric"){var s=t.cx,l=t.cy,u=t.innerRadius,f=t.outerRadius,d=t.angle,p=xe(s,l,u,d),h=xe(s,l,f,d);n=p.x,i=p.y,a=h.x,o=h.y}else return Ok(t);return[{x:n,y:i},{x:a,y:o}]}function il(e){"@babel/helpers - typeof";return il=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},il(e)}function rw(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function eu(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?rw(Object(r),!0).forEach(function(n){oZ(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):rw(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function oZ(e,t,r){return t=sZ(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function sZ(e){var t=lZ(e,"string");return il(t)=="symbol"?t:t+""}function lZ(e,t){if(il(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(il(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function uZ(e){var t,r,n=e.element,i=e.tooltipEventType,a=e.isActive,o=e.activeCoordinate,s=e.activePayload,l=e.offset,u=e.activeTooltipIndex,f=e.tooltipAxisBandSize,d=e.layout,p=e.chartName,h=(t=n.props.cursor)!==null&&t!==void 0?t:(r=n.type.defaultProps)===null||r===void 0?void 0:r.cursor;if(!n||!h||!a||!o||p!=="ScatterChart"&&i!=="axis")return null;var m,g=Ln;if(p==="ScatterChart")m=o,g=ZH;else if(p==="BarChart")m=iZ(d,o,l,f),g=Ey;else if(d==="radial"){var x=Ok(o),y=x.cx,v=x.cy,b=x.radius,S=x.startAngle,w=x.endAngle;m={cx:y,cy:v,startAngle:S,endAngle:w,innerRadius:b,outerRadius:b},g=pP}else m={points:aZ(d,o,l)},g=Ln;var j=eu(eu(eu(eu({stroke:"#ccc",pointerEvents:"none"},l),m),q(h,!1)),{},{payload:s,payloadIndex:u,className:ee("recharts-tooltip-cursor",h.className)});return k.isValidElement(h)?k.cloneElement(h,j):k.createElement(g,j)}var cZ=["item"],fZ=["children","className","width","height","style","compact","title","desc"];function Qa(e){"@babel/helpers - typeof";return Qa=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Qa(e)}function sa(){return sa=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},sa.apply(this,arguments)}function nw(e,t){return hZ(e)||pZ(e,t)||Pk(e,t)||dZ()}function dZ(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
-In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function pZ(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,i,a,o,s=[],l=!0,u=!1;try{if(a=(r=r.call(e)).next,t!==0)for(;!(l=(n=a.call(r)).done)&&(s.push(n.value),s.length!==t);l=!0);}catch(f){u=!0,i=f}finally{try{if(!l&&r.return!=null&&(o=r.return(),Object(o)!==o))return}finally{if(u)throw i}}return s}}function hZ(e){if(Array.isArray(e))return e}function iw(e,t){if(e==null)return{};var r=mZ(e,t),n,i;if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i<a.length;i++)n=a[i],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function mZ(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function vZ(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function yZ(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,kk(n.key),n)}}function gZ(e,t,r){return t&&yZ(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function xZ(e,t,r){return t=Vc(t),bZ(e,_k()?Reflect.construct(t,r||[],Vc(e).constructor):t.apply(e,r))}function bZ(e,t){if(t&&(Qa(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return wZ(e)}function wZ(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function _k(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(_k=function(){return!!e})()}function Vc(e){return Vc=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},Vc(e)}function jZ(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Im(e,t)}function Im(e,t){return Im=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,i){return n.__proto__=i,n},Im(e,t)}function Za(e){return _Z(e)||OZ(e)||Pk(e)||SZ()}function SZ(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
-In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Pk(e,t){if(e){if(typeof e=="string")return Lm(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return Lm(e,t)}}function OZ(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function _Z(e){if(Array.isArray(e))return Lm(e)}function Lm(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function aw(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function R(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?aw(Object(r),!0).forEach(function(n){J(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):aw(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function J(e,t,r){return t=kk(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function kk(e){var t=PZ(e,"string");return Qa(t)=="symbol"?t:t+""}function PZ(e,t){if(Qa(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(Qa(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var kZ={xAxis:["bottom","top"],yAxis:["left","right"]},AZ={width:"100%",height:"100%"},Ak={x:0,y:0};function tu(e){return e}var NZ=function(t,r){return r==="horizontal"?t.x:r==="vertical"?t.y:r==="centric"?t.angle:t.radius},$Z=function(t,r,n,i){var a=r.find(function(f){return f&&f.index===n});if(a){if(t==="horizontal")return{x:a.coordinate,y:i.y};if(t==="vertical")return{x:i.x,y:a.coordinate};if(t==="centric"){var o=a.coordinate,s=i.radius;return R(R(R({},i),xe(i.cx,i.cy,s,o)),{},{angle:o,radius:s})}var l=a.coordinate,u=i.angle;return R(R(R({},i),xe(i.cx,i.cy,l,u)),{},{angle:u,radius:l})}return Ak},nd=function(t,r){var n=r.graphicalItems,i=r.dataStartIndex,a=r.dataEndIndex,o=(n??[]).reduce(function(s,l){var u=l.props.data;return u&&u.length?[].concat(Za(s),Za(u)):s},[]);return o.length>0?o:t&&t.length&&K(i)&&K(a)?t.slice(i,a+1):[]};function Nk(e){return e==="number"?[0,"auto"]:void 0}var Dm=function(t,r,n,i){var a=t.graphicalItems,o=t.tooltipAxis,s=nd(r,t);return n<0||!a||!a.length||n>=s.length?null:a.reduce(function(l,u){var f,d=(f=u.props.data)!==null&&f!==void 0?f:r;d&&t.dataStartIndex+t.dataEndIndex!==0&&t.dataEndIndex-t.dataStartIndex>=n&&(d=d.slice(t.dataStartIndex,t.dataEndIndex+1));var p;if(o.dataKey&&!o.allowDuplicatedCategory){var h=d===void 0?s:d;p=zu(h,o.dataKey,i)}else p=d&&d[n]||s[n];return p?[].concat(Za(l),[sP(u,p)]):l},[])},ow=function(t,r,n,i){var a=i||{x:t.chartX,y:t.chartY},o=NZ(a,n),s=t.orderedTooltipTicks,l=t.tooltipAxis,u=t.tooltipTicks,f=gW(o,s,u,l);if(f>=0&&u){var d=u[f]&&u[f].value,p=Dm(t,r,f,d),h=$Z(n,s,f,a);return{activeTooltipIndex:f,activeLabel:d,activePayload:p,activeCoordinate:h}}return null},EZ=function(t,r){var n=r.axes,i=r.graphicalItems,a=r.axisType,o=r.axisIdKey,s=r.stackGroups,l=r.dataStartIndex,u=r.dataEndIndex,f=t.layout,d=t.children,p=t.stackOffset,h=tP(f,a);return n.reduce(function(m,g){var x,y=g.type.defaultProps!==void 0?R(R({},g.type.defaultProps),g.props):g.props,v=y.type,b=y.dataKey,S=y.allowDataOverflow,w=y.allowDuplicatedCategory,j=y.scale,O=y.ticks,_=y.includeHidden,P=y[o];if(m[P])return m;var N=nd(t.data,{graphicalItems:i.filter(function(z){var X,oe=o in z.props?z.props[o]:(X=z.type.defaultProps)===null||X===void 0?void 0:X[o];return oe===P}),dataStartIndex:l,dataEndIndex:u}),T=N.length,$,I,D;nZ(y.domain,S,v)&&($=Yh(y.domain,null,S),h&&(v==="number"||j!=="auto")&&(D=Zo(N,b,"category")));var L=Nk(v);if(!$||$.length===0){var C,F=(C=y.domain)!==null&&C!==void 0?C:L;if(b){if($=Zo(N,b,v),v==="category"&&h){var M=sM($);w&&M?(I=$,$=$c(0,T)):w||($=kb(F,$,g).reduce(function(z,X){return z.indexOf(X)>=0?z:[].concat(Za(z),[X])},[]))}else if(v==="category")w?$=$.filter(function(z){return z!==""&&!Q(z)}):$=kb(F,$,g).reduce(function(z,X){return z.indexOf(X)>=0||X===""||Q(X)?z:[].concat(Za(z),[X])},[]);else if(v==="number"){var B=SW(N,i.filter(function(z){var X,oe,Pe=o in z.props?z.props[o]:(X=z.type.defaultProps)===null||X===void 0?void 0:X[o],Le="hide"in z.props?z.props.hide:(oe=z.type.defaultProps)===null||oe===void 0?void 0:oe.hide;return Pe===P&&(_||!Le)}),b,a,f);B&&($=B)}h&&(v==="number"||j!=="auto")&&(D=Zo(N,b,"category"))}else h?$=$c(0,T):s&&s[P]&&s[P].hasStack&&v==="number"?$=p==="expand"?[0,1]:oP(s[P].stackGroups,l,u):$=eP(N,i.filter(function(z){var X=o in z.props?z.props[o]:z.type.defaultProps[o],oe="hide"in z.props?z.props.hide:z.type.defaultProps.hide;return X===P&&(_||!oe)}),v,f,!0);if(v==="number")$=Mm(d,$,P,a,O),F&&($=Yh(F,$,S));else if(v==="category"&&F){var E=F,W=$.every(function(z){return E.indexOf(z)>=0});W&&($=E)}}return R(R({},m),{},J({},P,R(R({},y),{},{axisType:a,domain:$,categoricalDomain:D,duplicateDomain:I,originalDomain:(x=y.domain)!==null&&x!==void 0?x:L,isCategorical:h,layout:f})))},{})},TZ=function(t,r){var n=r.graphicalItems,i=r.Axis,a=r.axisType,o=r.axisIdKey,s=r.stackGroups,l=r.dataStartIndex,u=r.dataEndIndex,f=t.layout,d=t.children,p=nd(t.data,{graphicalItems:n,dataStartIndex:l,dataEndIndex:u}),h=p.length,m=tP(f,a),g=-1;return n.reduce(function(x,y){var v=y.type.defaultProps!==void 0?R(R({},y.type.defaultProps),y.props):y.props,b=v[o],S=Nk("number");if(!x[b]){g++;var w;return m?w=$c(0,h):s&&s[b]&&s[b].hasStack?(w=oP(s[b].stackGroups,l,u),w=Mm(d,w,b,a)):(w=Yh(S,eP(p,n.filter(function(j){var O,_,P=o in j.props?j.props[o]:(O=j.type.defaultProps)===null||O===void 0?void 0:O[o],N="hide"in j.props?j.props.hide:(_=j.type.defaultProps)===null||_===void 0?void 0:_.hide;return P===b&&!N}),"number",f),i.defaultProps.allowDataOverflow),w=Mm(d,w,b,a)),R(R({},x),{},J({},b,R(R({axisType:a},i.defaultProps),{},{hide:!0,orientation:Wt(kZ,"".concat(a,".").concat(g%2),null),domain:w,originalDomain:S,isCategorical:m,layout:f})))}return x},{})},CZ=function(t,r){var n=r.axisType,i=n===void 0?"xAxis":n,a=r.AxisComp,o=r.graphicalItems,s=r.stackGroups,l=r.dataStartIndex,u=r.dataEndIndex,f=t.children,d="".concat(i,"Id"),p=wt(f,a),h={};return p&&p.length?h=EZ(t,{axes:p,graphicalItems:o,axisType:i,axisIdKey:d,stackGroups:s,dataStartIndex:l,dataEndIndex:u}):o&&o.length&&(h=TZ(t,{Axis:a,graphicalItems:o,axisType:i,axisIdKey:d,stackGroups:s,dataStartIndex:l,dataEndIndex:u})),h},MZ=function(t){var r=gn(t),n=Hr(r,!1,!0);return{tooltipTicks:n,orderedTooltipTicks:iy(n,function(i){return i.coordinate}),tooltipAxis:r,tooltipAxisBandSize:vc(r,n)}},sw=function(t){var r=t.children,n=t.defaultShowTooltip,i=Rt(r,Ba),a=0,o=0;return t.data&&t.data.length!==0&&(o=t.data.length-1),i&&i.props&&(i.props.startIndex>=0&&(a=i.props.startIndex),i.props.endIndex>=0&&(o=i.props.endIndex)),{chartX:0,chartY:0,dataStartIndex:a,dataEndIndex:o,activeTooltipIndex:-1,isTooltipActive:!!n}},IZ=function(t){return!t||!t.length?!1:t.some(function(r){var n=Gr(r&&r.type);return n&&n.indexOf("Bar")>=0})},lw=function(t){return t==="horizontal"?{numericAxisName:"yAxis",cateAxisName:"xAxis"}:t==="vertical"?{numericAxisName:"xAxis",cateAxisName:"yAxis"}:t==="centric"?{numericAxisName:"radiusAxis",cateAxisName:"angleAxis"}:{numericAxisName:"angleAxis",cateAxisName:"radiusAxis"}},LZ=function(t,r){var n=t.props,i=t.graphicalItems,a=t.xAxisMap,o=a===void 0?{}:a,s=t.yAxisMap,l=s===void 0?{}:s,u=n.width,f=n.height,d=n.children,p=n.margin||{},h=Rt(d,Ba),m=Rt(d,Yr),g=Object.keys(l).reduce(function(w,j){var O=l[j],_=O.orientation;return!O.mirror&&!O.hide?R(R({},w),{},J({},_,w[_]+O.width)):w},{left:p.left||0,right:p.right||0}),x=Object.keys(o).reduce(function(w,j){var O=o[j],_=O.orientation;return!O.mirror&&!O.hide?R(R({},w),{},J({},_,Wt(w,"".concat(_))+O.height)):w},{top:p.top||0,bottom:p.bottom||0}),y=R(R({},x),g),v=y.bottom;h&&(y.bottom+=h.props.height||Ba.defaultProps.height),m&&r&&(y=wW(y,i,n,r));var b=u-y.left-y.right,S=f-y.top-y.bottom;return R(R({brushBottom:v},y),{},{width:Math.max(b,0),height:Math.max(S,0)})},DZ=function(t,r){if(r==="xAxis")return t[r].width;if(r==="yAxis")return t[r].height},wl=function(t){var r=t.chartName,n=t.GraphicalChild,i=t.defaultTooltipEventType,a=i===void 0?"axis":i,o=t.validateTooltipEventTypes,s=o===void 0?["axis"]:o,l=t.axisComponents,u=t.legendContent,f=t.formatAxisMap,d=t.defaultProps,p=function(y,v){var b=v.graphicalItems,S=v.stackGroups,w=v.offset,j=v.updateId,O=v.dataStartIndex,_=v.dataEndIndex,P=y.barSize,N=y.layout,T=y.barGap,$=y.barCategoryGap,I=y.maxBarSize,D=lw(N),L=D.numericAxisName,C=D.cateAxisName,F=IZ(b),M=[];return b.forEach(function(B,E){var W=nd(y.data,{graphicalItems:[B],dataStartIndex:O,dataEndIndex:_}),z=B.type.defaultProps!==void 0?R(R({},B.type.defaultProps),B.props):B.props,X=z.dataKey,oe=z.maxBarSize,Pe=z["".concat(L,"Id")],Le=z["".concat(C,"Id")],Vt={},Ot=l.reduce(function(Qn,Zn){var id=v["".concat(Zn.axisType,"Map")],zy=z["".concat(Zn.axisType,"Id")];id&&id[zy]||Zn.axisType==="zAxis"||Ni();var Wy=id[zy];return R(R({},Qn),{},J(J({},Zn.axisType,Wy),"".concat(Zn.axisType,"Ticks"),Hr(Wy)))},Vt),V=Ot[C],re=Ot["".concat(C,"Ticks")],ne=S&&S[Pe]&&S[Pe].hasStack&&TW(B,S[Pe].stackGroups),U=Gr(B.type).indexOf("Bar")>=0,Ce=vc(V,re),se=[],Ke=F&&xW({barSize:P,stackGroups:S,totalSize:DZ(Ot,C)});if(U){var He,_t,cn=Q(oe)?I:oe,Ri=(He=(_t=vc(V,re,!0))!==null&&_t!==void 0?_t:cn)!==null&&He!==void 0?He:0;se=bW({barGap:T,barCategoryGap:$,bandSize:Ri!==Ce?Ri:Ce,sizeList:Ke[Le],maxBarSize:cn}),Ri!==Ce&&(se=se.map(function(Qn){return R(R({},Qn),{},{position:R(R({},Qn.position),{},{offset:Qn.position.offset-Ri/2})})}))}var jl=B&&B.type&&B.type.getComposedData;jl&&M.push({props:R(R({},jl(R(R({},Ot),{},{displayedData:W,props:y,dataKey:X,item:B,bandSize:Ce,barPosition:se,offset:w,stackedData:ne,layout:N,dataStartIndex:O,dataEndIndex:_}))),{},J(J(J({key:B.key||"item-".concat(E)},L,Ot[L]),C,Ot[C]),"animationId",j)),childIndex:bM(B,y.children),item:B})}),M},h=function(y,v){var b=y.props,S=y.dataStartIndex,w=y.dataEndIndex,j=y.updateId;if(!w0({props:b}))return null;var O=b.children,_=b.layout,P=b.stackOffset,N=b.data,T=b.reverseStackOrder,$=lw(_),I=$.numericAxisName,D=$.cateAxisName,L=wt(O,n),C=$W(N,L,"".concat(I,"Id"),"".concat(D,"Id"),P,T),F=l.reduce(function(z,X){var oe="".concat(X.axisType,"Map");return R(R({},z),{},J({},oe,CZ(b,R(R({},X),{},{graphicalItems:L,stackGroups:X.axisType===I&&C,dataStartIndex:S,dataEndIndex:w}))))},{}),M=LZ(R(R({},F),{},{props:b,graphicalItems:L}),v==null?void 0:v.legendBBox);Object.keys(F).forEach(function(z){F[z]=f(b,F[z],M,z.replace("Map",""),r)});var B=F["".concat(D,"Map")],E=MZ(B),W=p(b,R(R({},F),{},{dataStartIndex:S,dataEndIndex:w,updateId:j,graphicalItems:L,stackGroups:C,offset:M}));return R(R({formattedGraphicalItems:W,graphicalItems:L,offset:M,stackGroups:C},E),F)},m=function(x){function y(v){var b,S,w;return vZ(this,y),w=xZ(this,y,[v]),J(w,"eventEmitterSymbol",Symbol("rechartsEventEmitter")),J(w,"accessibilityManager",new rZ),J(w,"handleLegendBBoxUpdate",function(j){if(j){var O=w.state,_=O.dataStartIndex,P=O.dataEndIndex,N=O.updateId;w.setState(R({legendBBox:j},h({props:w.props,dataStartIndex:_,dataEndIndex:P,updateId:N},R(R({},w.state),{},{legendBBox:j}))))}}),J(w,"handleReceiveSyncEvent",function(j,O,_){if(w.props.syncId===j){if(_===w.eventEmitterSymbol&&typeof w.props.syncMethod!="function")return;w.applySyncEvent(O)}}),J(w,"handleBrushChange",function(j){var O=j.startIndex,_=j.endIndex;if(O!==w.state.dataStartIndex||_!==w.state.dataEndIndex){var P=w.state.updateId;w.setState(function(){return R({dataStartIndex:O,dataEndIndex:_},h({props:w.props,dataStartIndex:O,dataEndIndex:_,updateId:P},w.state))}),w.triggerSyncEvent({dataStartIndex:O,dataEndIndex:_})}}),J(w,"handleMouseEnter",function(j){var O=w.getMouseInfo(j);if(O){var _=R(R({},O),{},{isTooltipActive:!0});w.setState(_),w.triggerSyncEvent(_);var P=w.props.onMouseEnter;Z(P)&&P(_,j)}}),J(w,"triggeredAfterMouseMove",function(j){var O=w.getMouseInfo(j),_=O?R(R({},O),{},{isTooltipActive:!0}):{isTooltipActive:!1};w.setState(_),w.triggerSyncEvent(_);var P=w.props.onMouseMove;Z(P)&&P(_,j)}),J(w,"handleItemMouseEnter",function(j){w.setState(function(){return{isTooltipActive:!0,activeItem:j,activePayload:j.tooltipPayload,activeCoordinate:j.tooltipPosition||{x:j.cx,y:j.cy}}})}),J(w,"handleItemMouseLeave",function(){w.setState(function(){return{isTooltipActive:!1}})}),J(w,"handleMouseMove",function(j){j.persist(),w.throttleTriggeredAfterMouseMove(j)}),J(w,"handleMouseLeave",function(j){w.throttleTriggeredAfterMouseMove.cancel();var O={isTooltipActive:!1};w.setState(O),w.triggerSyncEvent(O);var _=w.props.onMouseLeave;Z(_)&&_(O,j)}),J(w,"handleOuterEvent",function(j){var O=xM(j),_=Wt(w.props,"".concat(O));if(O&&Z(_)){var P,N;/.*touch.*/i.test(O)?N=w.getMouseInfo(j.changedTouches[0]):N=w.getMouseInfo(j),_((P=N)!==null&&P!==void 0?P:{},j)}}),J(w,"handleClick",function(j){var O=w.getMouseInfo(j);if(O){var _=R(R({},O),{},{isTooltipActive:!0});w.setState(_),w.triggerSyncEvent(_);var P=w.props.onClick;Z(P)&&P(_,j)}}),J(w,"handleMouseDown",function(j){var O=w.props.onMouseDown;if(Z(O)){var _=w.getMouseInfo(j);O(_,j)}}),J(w,"handleMouseUp",function(j){var O=w.props.onMouseUp;if(Z(O)){var _=w.getMouseInfo(j);O(_,j)}}),J(w,"handleTouchMove",function(j){j.changedTouches!=null&&j.changedTouches.length>0&&w.throttleTriggeredAfterMouseMove(j.changedTouches[0])}),J(w,"handleTouchStart",function(j){j.changedTouches!=null&&j.changedTouches.length>0&&w.handleMouseDown(j.changedTouches[0])}),J(w,"handleTouchEnd",function(j){j.changedTouches!=null&&j.changedTouches.length>0&&w.handleMouseUp(j.changedTouches[0])}),J(w,"handleDoubleClick",function(j){var O=w.props.onDoubleClick;if(Z(O)){var _=w.getMouseInfo(j);O(_,j)}}),J(w,"handleContextMenu",function(j){var O=w.props.onContextMenu;if(Z(O)){var _=w.getMouseInfo(j);O(_,j)}}),J(w,"triggerSyncEvent",function(j){w.props.syncId!==void 0&&ap.emit(op,w.props.syncId,j,w.eventEmitterSymbol)}),J(w,"applySyncEvent",function(j){var O=w.props,_=O.layout,P=O.syncMethod,N=w.state.updateId,T=j.dataStartIndex,$=j.dataEndIndex;if(j.dataStartIndex!==void 0||j.dataEndIndex!==void 0)w.setState(R({dataStartIndex:T,dataEndIndex:$},h({props:w.props,dataStartIndex:T,dataEndIndex:$,updateId:N},w.state)));else if(j.activeTooltipIndex!==void 0){var I=j.chartX,D=j.chartY,L=j.activeTooltipIndex,C=w.state,F=C.offset,M=C.tooltipTicks;if(!F)return;if(typeof P=="function")L=P(M,j);else if(P==="value"){L=-1;for(var B=0;B<M.length;B++)if(M[B].value===j.activeLabel){L=B;break}}var E=R(R({},F),{},{x:F.left,y:F.top}),W=Math.min(I,E.x+E.width),z=Math.min(D,E.y+E.height),X=M[L]&&M[L].value,oe=Dm(w.state,w.props.data,L),Pe=M[L]?{x:_==="horizontal"?M[L].coordinate:W,y:_==="horizontal"?z:M[L].coordinate}:Ak;w.setState(R(R({},j),{},{activeLabel:X,activeCoordinate:Pe,activePayload:oe,activeTooltipIndex:L}))}else w.setState(j)}),J(w,"renderCursor",function(j){var O,_=w.state,P=_.isTooltipActive,N=_.activeCoordinate,T=_.activePayload,$=_.offset,I=_.activeTooltipIndex,D=_.tooltipAxisBandSize,L=w.getTooltipEventType(),C=(O=j.props.active)!==null&&O!==void 0?O:P,F=w.props.layout,M=j.key||"_recharts-cursor";return A.createElement(uZ,{key:M,activeCoordinate:N,activePayload:T,activeTooltipIndex:I,chartName:r,element:j,isActive:C,layout:F,offset:$,tooltipAxisBandSize:D,tooltipEventType:L})}),J(w,"renderPolarAxis",function(j,O,_){var P=Wt(j,"type.axisType"),N=Wt(w.state,"".concat(P,"Map")),T=j.type.defaultProps,$=T!==void 0?R(R({},T),j.props):j.props,I=N&&N[$["".concat(P,"Id")]];return k.cloneElement(j,R(R({},I),{},{className:ee(P,I.className),key:j.key||"".concat(O,"-").concat(_),ticks:Hr(I,!0)}))}),J(w,"renderPolarGrid",function(j){var O=j.props,_=O.radialLines,P=O.polarAngles,N=O.polarRadius,T=w.state,$=T.radiusAxisMap,I=T.angleAxisMap,D=gn($),L=gn(I),C=L.cx,F=L.cy,M=L.innerRadius,B=L.outerRadius;return k.cloneElement(j,{polarAngles:Array.isArray(P)?P:Hr(L,!0).map(function(E){return E.coordinate}),polarRadius:Array.isArray(N)?N:Hr(D,!0).map(function(E){return E.coordinate}),cx:C,cy:F,innerRadius:M,outerRadius:B,key:j.key||"polar-grid",radialLines:_})}),J(w,"renderLegend",function(){var j=w.state.formattedGraphicalItems,O=w.props,_=O.children,P=O.width,N=O.height,T=w.props.margin||{},$=P-(T.left||0)-(T.right||0),I=Z_({children:_,formattedGraphicalItems:j,legendWidth:$,legendContent:u});if(!I)return null;var D=I.item,L=iw(I,cZ);return k.cloneElement(D,R(R({},L),{},{chartWidth:P,chartHeight:N,margin:T,onBBoxUpdate:w.handleLegendBBoxUpdate}))}),J(w,"renderTooltip",function(){var j,O=w.props,_=O.children,P=O.accessibilityLayer,N=Rt(_,Se);if(!N)return null;var T=w.state,$=T.isTooltipActive,I=T.activeCoordinate,D=T.activePayload,L=T.activeLabel,C=T.offset,F=(j=N.props.active)!==null&&j!==void 0?j:$;return k.cloneElement(N,{viewBox:R(R({},C),{},{x:C.left,y:C.top}),active:F,label:L,payload:F?D:[],coordinate:I,accessibilityLayer:P})}),J(w,"renderBrush",function(j){var O=w.props,_=O.margin,P=O.data,N=w.state,T=N.offset,$=N.dataStartIndex,I=N.dataEndIndex,D=N.updateId;return k.cloneElement(j,{key:j.key||"_recharts-brush",onChange:Xl(w.handleBrushChange,j.props.onChange),data:P,x:K(j.props.x)?j.props.x:T.left,y:K(j.props.y)?j.props.y:T.top+T.height+T.brushBottom-(_.bottom||0),width:K(j.props.width)?j.props.width:T.width,startIndex:$,endIndex:I,updateId:"brush-".concat(D)})}),J(w,"renderReferenceElement",function(j,O,_){if(!j)return null;var P=w,N=P.clipPathId,T=w.state,$=T.xAxisMap,I=T.yAxisMap,D=T.offset,L=j.type.defaultProps||{},C=j.props,F=C.xAxisId,M=F===void 0?L.xAxisId:F,B=C.yAxisId,E=B===void 0?L.yAxisId:B;return k.cloneElement(j,{key:j.key||"".concat(O,"-").concat(_),xAxis:$[M],yAxis:I[E],viewBox:{x:D.left,y:D.top,width:D.width,height:D.height},clipPathId:N})}),J(w,"renderActivePoints",function(j){var O=j.item,_=j.activePoint,P=j.basePoint,N=j.childIndex,T=j.isRange,$=[],I=O.props.key,D=O.item.type.defaultProps!==void 0?R(R({},O.item.type.defaultProps),O.item.props):O.item.props,L=D.activeDot,C=D.dataKey,F=R(R({index:N,dataKey:C,cx:_.x,cy:_.y,r:4,fill:$y(O.item),strokeWidth:2,stroke:"#fff",payload:_.payload,value:_.value},q(L,!1)),Wu(L));return $.push(y.renderActiveDot(L,F,"".concat(I,"-activePoint-").concat(N))),P?$.push(y.renderActiveDot(L,R(R({},F),{},{cx:P.x,cy:P.y}),"".concat(I,"-basePoint-").concat(N))):T&&$.push(null),$}),J(w,"renderGraphicChild",function(j,O,_){var P=w.filterFormatItem(j,O,_);if(!P)return null;var N=w.getTooltipEventType(),T=w.state,$=T.isTooltipActive,I=T.tooltipAxis,D=T.activeTooltipIndex,L=T.activeLabel,C=w.props.children,F=Rt(C,Se),M=P.props,B=M.points,E=M.isRange,W=M.baseLine,z=P.item.type.defaultProps!==void 0?R(R({},P.item.type.defaultProps),P.item.props):P.item.props,X=z.activeDot,oe=z.hide,Pe=z.activeBar,Le=z.activeShape,Vt=!!(!oe&&$&&F&&(X||Pe||Le)),Ot={};N!=="axis"&&F&&F.props.trigger==="click"?Ot={onClick:Xl(w.handleItemMouseEnter,j.props.onClick)}:N!=="axis"&&(Ot={onMouseLeave:Xl(w.handleItemMouseLeave,j.props.onMouseLeave),onMouseEnter:Xl(w.handleItemMouseEnter,j.props.onMouseEnter)});var V=k.cloneElement(j,R(R({},P.props),Ot));function re(Zn){return typeof I.dataKey=="function"?I.dataKey(Zn.payload):null}if(Vt)if(D>=0){var ne,U;if(I.dataKey&&!I.allowDuplicatedCategory){var Ce=typeof I.dataKey=="function"?re:"payload.".concat(I.dataKey.toString());ne=zu(B,Ce,L),U=E&&W&&zu(W,Ce,L)}else ne=B==null?void 0:B[D],U=E&&W&&W[D];if(Le||Pe){var se=j.props.activeIndex!==void 0?j.props.activeIndex:D;return[k.cloneElement(j,R(R(R({},P.props),Ot),{},{activeIndex:se})),null,null]}if(!Q(ne))return[V].concat(Za(w.renderActivePoints({item:P,activePoint:ne,basePoint:U,childIndex:D,isRange:E})))}else{var Ke,He=(Ke=w.getItemByXY(w.state.activeCoordinate))!==null&&Ke!==void 0?Ke:{graphicalItem:V},_t=He.graphicalItem,cn=_t.item,Ri=cn===void 0?j:cn,jl=_t.childIndex,Qn=R(R(R({},P.props),Ot),{},{activeIndex:jl});return[k.cloneElement(Ri,Qn),null,null]}return E?[V,null,null]:[V,null]}),J(w,"renderCustomized",function(j,O,_){return k.cloneElement(j,R(R({key:"recharts-customized-".concat(_)},w.props),w.state))}),J(w,"renderMap",{CartesianGrid:{handler:tu,once:!0},ReferenceArea:{handler:w.renderReferenceElement},ReferenceLine:{handler:tu},ReferenceDot:{handler:w.renderReferenceElement},XAxis:{handler:tu},YAxis:{handler:tu},Brush:{handler:w.renderBrush,once:!0},Bar:{handler:w.renderGraphicChild},Line:{handler:w.renderGraphicChild},Area:{handler:w.renderGraphicChild},Radar:{handler:w.renderGraphicChild},RadialBar:{handler:w.renderGraphicChild},Scatter:{handler:w.renderGraphicChild},Pie:{handler:w.renderGraphicChild},Funnel:{handler:w.renderGraphicChild},Tooltip:{handler:w.renderCursor,once:!0},PolarGrid:{handler:w.renderPolarGrid,once:!0},PolarAngleAxis:{handler:w.renderPolarAxis},PolarRadiusAxis:{handler:w.renderPolarAxis},Customized:{handler:w.renderCustomized}}),w.clipPathId="".concat((b=v.id)!==null&&b!==void 0?b:Gn("recharts"),"-clip"),w.throttleTriggeredAfterMouseMove=ZO(w.triggeredAfterMouseMove,(S=v.throttleDelay)!==null&&S!==void 0?S:1e3/60),w.state={},w}return jZ(y,x),gZ(y,[{key:"componentDidMount",value:function(){var b,S;this.addListener(),this.accessibilityManager.setDetails({container:this.container,offset:{left:(b=this.props.margin.left)!==null&&b!==void 0?b:0,top:(S=this.props.margin.top)!==null&&S!==void 0?S:0},coordinateList:this.state.tooltipTicks,mouseHandlerCallback:this.triggeredAfterMouseMove,layout:this.props.layout}),this.displayDefaultTooltip()}},{key:"displayDefaultTooltip",value:function(){var b=this.props,S=b.children,w=b.data,j=b.height,O=b.layout,_=Rt(S,Se);if(_){var P=_.props.defaultIndex;if(!(typeof P!="number"||P<0||P>this.state.tooltipTicks.length-1)){var N=this.state.tooltipTicks[P]&&this.state.tooltipTicks[P].value,T=Dm(this.state,w,P,N),$=this.state.tooltipTicks[P].coordinate,I=(this.state.offset.top+j)/2,D=O==="horizontal",L=D?{x:$,y:I}:{y:$,x:I},C=this.state.formattedGraphicalItems.find(function(M){var B=M.item;return B.type.name==="Scatter"});C&&(L=R(R({},L),C.props.points[P].tooltipPosition),T=C.props.points[P].tooltipPayload);var F={activeTooltipIndex:P,isTooltipActive:!0,activeLabel:N,activePayload:T,activeCoordinate:L};this.setState(F),this.renderCursor(_),this.accessibilityManager.setIndex(P)}}}},{key:"getSnapshotBeforeUpdate",value:function(b,S){if(!this.props.accessibilityLayer)return null;if(this.state.tooltipTicks!==S.tooltipTicks&&this.accessibilityManager.setDetails({coordinateList:this.state.tooltipTicks}),this.props.layout!==b.layout&&this.accessibilityManager.setDetails({layout:this.props.layout}),this.props.margin!==b.margin){var w,j;this.accessibilityManager.setDetails({offset:{left:(w=this.props.margin.left)!==null&&w!==void 0?w:0,top:(j=this.props.margin.top)!==null&&j!==void 0?j:0}})}return null}},{key:"componentDidUpdate",value:function(b){uh([Rt(b.children,Se)],[Rt(this.props.children,Se)])||this.displayDefaultTooltip()}},{key:"componentWillUnmount",value:function(){this.removeListener(),this.throttleTriggeredAfterMouseMove.cancel()}},{key:"getTooltipEventType",value:function(){var b=Rt(this.props.children,Se);if(b&&typeof b.props.shared=="boolean"){var S=b.props.shared?"axis":"item";return s.indexOf(S)>=0?S:a}return a}},{key:"getMouseInfo",value:function(b){if(!this.container)return null;var S=this.container,w=S.getBoundingClientRect(),j=V6(w),O={chartX:Math.round(b.pageX-j.left),chartY:Math.round(b.pageY-j.top)},_=w.width/S.offsetWidth||1,P=this.inRange(O.chartX,O.chartY,_);if(!P)return null;var N=this.state,T=N.xAxisMap,$=N.yAxisMap,I=this.getTooltipEventType(),D=ow(this.state,this.props.data,this.props.layout,P);if(I!=="axis"&&T&&$){var L=gn(T).scale,C=gn($).scale,F=L&&L.invert?L.invert(O.chartX):null,M=C&&C.invert?C.invert(O.chartY):null;return R(R({},O),{},{xValue:F,yValue:M},D)}return D?R(R({},O),D):null}},{key:"inRange",value:function(b,S){var w=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1,j=this.props.layout,O=b/w,_=S/w;if(j==="horizontal"||j==="vertical"){var P=this.state.offset,N=O>=P.left&&O<=P.left+P.width&&_>=P.top&&_<=P.top+P.height;return N?{x:O,y:_}:null}var T=this.state,$=T.angleAxisMap,I=T.radiusAxisMap;if($&&I){var D=gn($);return $b({x:O,y:_},D)}return null}},{key:"parseEventsOfWrapper",value:function(){var b=this.props.children,S=this.getTooltipEventType(),w=Rt(b,Se),j={};w&&S==="axis"&&(w.props.trigger==="click"?j={onClick:this.handleClick}:j={onMouseEnter:this.handleMouseEnter,onDoubleClick:this.handleDoubleClick,onMouseMove:this.handleMouseMove,onMouseLeave:this.handleMouseLeave,onTouchMove:this.handleTouchMove,onTouchStart:this.handleTouchStart,onTouchEnd:this.handleTouchEnd,onContextMenu:this.handleContextMenu});var O=Wu(this.props,this.handleOuterEvent);return R(R({},O),j)}},{key:"addListener",value:function(){ap.on(op,this.handleReceiveSyncEvent)}},{key:"removeListener",value:function(){ap.removeListener(op,this.handleReceiveSyncEvent)}},{key:"filterFormatItem",value:function(b,S,w){for(var j=this.state.formattedGraphicalItems,O=0,_=j.length;O<_;O++){var P=j[O];if(P.item===b||P.props.key===b.key||S===Gr(P.item.type)&&w===P.childIndex)return P}return null}},{key:"renderClipPath",value:function(){var b=this.clipPathId,S=this.state.offset,w=S.left,j=S.top,O=S.height,_=S.width;return A.createElement("defs",null,A.createElement("clipPath",{id:b},A.createElement("rect",{x:w,y:j,height:O,width:_})))}},{key:"getXScales",value:function(){var b=this.state.xAxisMap;return b?Object.entries(b).reduce(function(S,w){var j=nw(w,2),O=j[0],_=j[1];return R(R({},S),{},J({},O,_.scale))},{}):null}},{key:"getYScales",value:function(){var b=this.state.yAxisMap;return b?Object.entries(b).reduce(function(S,w){var j=nw(w,2),O=j[0],_=j[1];return R(R({},S),{},J({},O,_.scale))},{}):null}},{key:"getXScaleByAxisId",value:function(b){var S;return(S=this.state.xAxisMap)===null||S===void 0||(S=S[b])===null||S===void 0?void 0:S.scale}},{key:"getYScaleByAxisId",value:function(b){var S;return(S=this.state.yAxisMap)===null||S===void 0||(S=S[b])===null||S===void 0?void 0:S.scale}},{key:"getItemByXY",value:function(b){var S=this.state,w=S.formattedGraphicalItems,j=S.activeItem;if(w&&w.length)for(var O=0,_=w.length;O<_;O++){var P=w[O],N=P.props,T=P.item,$=T.type.defaultProps!==void 0?R(R({},T.type.defaultProps),T.props):T.props,I=Gr(T.type);if(I==="Bar"){var D=(N.data||[]).find(function(M){return TH(b,M)});if(D)return{graphicalItem:P,payload:D}}else if(I==="RadialBar"){var L=(N.data||[]).find(function(M){return $b(b,M)});if(L)return{graphicalItem:P,payload:L}}else if(qf(P,j)||Xf(P,j)||Zs(P,j)){var C=bG({graphicalItem:P,activeTooltipItem:j,itemData:$.data}),F=$.activeIndex===void 0?C:$.activeIndex;return{graphicalItem:R(R({},P),{},{childIndex:F}),payload:Zs(P,j)?$.data[C]:P.props.data[C]}}}return null}},{key:"render",value:function(){var b=this;if(!w0(this))return null;var S=this.props,w=S.children,j=S.className,O=S.width,_=S.height,P=S.style,N=S.compact,T=S.title,$=S.desc,I=iw(S,fZ),D=q(I,!1);if(N)return A.createElement(I1,{state:this.state,width:this.props.width,height:this.props.height,clipPathId:this.clipPathId},A.createElement(fh,sa({},D,{width:O,height:_,title:T,desc:$}),this.renderClipPath(),S0(w,this.renderMap)));if(this.props.accessibilityLayer){var L,C;D.tabIndex=(L=this.props.tabIndex)!==null&&L!==void 0?L:0,D.role=(C=this.props.role)!==null&&C!==void 0?C:"application",D.onKeyDown=function(M){b.accessibilityManager.keyboardEvent(M)},D.onFocus=function(){b.accessibilityManager.focus()}}var F=this.parseEventsOfWrapper();return A.createElement(I1,{state:this.state,width:this.props.width,height:this.props.height,clipPathId:this.clipPathId},A.createElement("div",sa({className:ee("recharts-wrapper",j),style:R({position:"relative",cursor:"default",width:O,height:_},P)},F,{ref:function(B){b.container=B}}),A.createElement(fh,sa({},D,{width:O,height:_,title:T,desc:$,style:AZ}),this.renderClipPath(),S0(w,this.renderMap)),this.renderLegend(),this.renderTooltip()))}}])}(k.Component);J(m,"displayName",r),J(m,"defaultProps",R({layout:"horizontal",stackOffset:"none",barCategoryGap:"10%",barGap:4,margin:{top:5,right:5,bottom:5,left:5},reverseStackOrder:!1,syncMethod:"index"},d)),J(m,"getDerivedStateFromProps",function(x,y){var v=x.dataKey,b=x.data,S=x.children,w=x.width,j=x.height,O=x.layout,_=x.stackOffset,P=x.margin,N=y.dataStartIndex,T=y.dataEndIndex;if(y.updateId===void 0){var $=sw(x);return R(R(R({},$),{},{updateId:0},h(R(R({props:x},$),{},{updateId:0}),y)),{},{prevDataKey:v,prevData:b,prevWidth:w,prevHeight:j,prevLayout:O,prevStackOffset:_,prevMargin:P,prevChildren:S})}if(v!==y.prevDataKey||b!==y.prevData||w!==y.prevWidth||j!==y.prevHeight||O!==y.prevLayout||_!==y.prevStackOffset||!ha(P,y.prevMargin)){var I=sw(x),D={chartX:y.chartX,chartY:y.chartY,isTooltipActive:y.isTooltipActive},L=R(R({},ow(y,b,O)),{},{updateId:y.updateId+1}),C=R(R(R({},I),D),L);return R(R(R({},C),h(R({props:x},C),y)),{},{prevDataKey:v,prevData:b,prevWidth:w,prevHeight:j,prevLayout:O,prevStackOffset:_,prevMargin:P,prevChildren:S})}if(!uh(S,y.prevChildren)){var F,M,B,E,W=Rt(S,Ba),z=W&&(F=(M=W.props)===null||M===void 0?void 0:M.startIndex)!==null&&F!==void 0?F:N,X=W&&(B=(E=W.props)===null||E===void 0?void 0:E.endIndex)!==null&&B!==void 0?B:T,oe=z!==N||X!==T,Pe=!Q(b),Le=Pe&&!oe?y.updateId:y.updateId+1;return R(R({updateId:Le},h(R(R({props:x},y),{},{updateId:Le,dataStartIndex:z,dataEndIndex:X}),y)),{},{prevChildren:S,dataStartIndex:z,dataEndIndex:X})}return null}),J(m,"renderActiveDot",function(x,y,v){var b;return k.isValidElement(x)?b=k.cloneElement(x,y):Z(x)?b=x(y):b=A.createElement(xl,y),A.createElement(te,{className:"recharts-active-dot",key:v},b)});var g=k.forwardRef(function(y,v){return A.createElement(m,sa({},y,{ref:v}))});return g.displayName=m.displayName,g},uw=wl({chartName:"LineChart",GraphicalChild:On,axisComponents:[{axisType:"xAxis",AxisComp:Re},{axisType:"yAxis",AxisComp:Be}],formatAxisMap:Zf}),zn=wl({chartName:"BarChart",GraphicalChild:Tt,defaultTooltipEventType:"axis",validateTooltipEventTypes:["axis","item"],axisComponents:[{axisType:"xAxis",AxisComp:Re},{axisType:"yAxis",AxisComp:Be}],formatAxisMap:Zf}),RZ=wl({chartName:"PieChart",GraphicalChild:un,validateTooltipEventTypes:["item"],defaultTooltipEventType:"item",legendContent:"children",axisComponents:[{axisType:"angleAxis",AxisComp:Yf},{axisType:"radiusAxis",AxisComp:Vf}],formatAxisMap:WW,defaultProps:{layout:"centric",startAngle:0,endAngle:360,cx:"50%",cy:"50%",innerRadius:0,outerRadius:"80%"}}),BZ=wl({chartName:"ScatterChart",GraphicalChild:bi,defaultTooltipEventType:"item",validateTooltipEventTypes:["item"],axisComponents:[{axisType:"xAxis",AxisComp:Re},{axisType:"yAxis",AxisComp:Be},{axisType:"zAxis",AxisComp:bl}],formatAxisMap:Zf}),Gc=wl({chartName:"AreaChart",GraphicalChild:Sr,axisComponents:[{axisType:"xAxis",AxisComp:Re},{axisType:"yAxis",AxisComp:Be}],formatAxisMap:Zf});function ru({label:e,value:t,color:r,sub:n,onClick:i}){return c.jsxs("div",{className:`card ${i?"cursor-pointer hover:border-blue-500/30":""}`,onClick:i,children:[c.jsx("p",{className:"text-xs text-gray-500 uppercase tracking-wide mb-1",children:e}),c.jsx("p",{className:`stat-v ${r||"text-white"}`,children:t}),n&&c.jsx("p",{className:"text-xs text-gray-500 mt-1",children:n})]})}function Ki({icon:e,title:t,desc:r,onClick:n,busy:i,color:a,badge:o}){return c.jsx("button",{onClick:n,disabled:i,className:`card text-left hover:border-${a||"blue"}-500/40 hover:bg-${a||"blue"}-500/5 transition-all group cursor-pointer disabled:opacity-50`,children:c.jsxs("div",{className:"flex items-start gap-3",children:[c.jsx("div",{className:`w-10 h-10 rounded-lg flex items-center justify-center flex-shrink-0 bg-${a||"blue"}-500/15`,children:c.jsx("svg",{className:`w-5 h-5 text-${a||"blue"}-400`,fill:"none",stroke:"currentColor",strokeWidth:"1.5",viewBox:"0 0 24 24",children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:e})})}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("p",{className:"font-semibold text-sm group-hover:text-white transition",children:t}),o&&c.jsx("span",{className:`badge bg-${o.color||"blue"}`,children:o.text})]}),c.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:r})]}),i?c.jsx("div",{className:"animate-spin w-4 h-4 border-2 border-blue-500 border-t-transparent rounded-full flex-shrink-0 mt-1"}):c.jsx("svg",{className:"w-4 h-4 text-gray-600 group-hover:text-gray-400 transition flex-shrink-0 mt-1",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M9 5l7 7-7 7"})})]})})}const lp=({active:e,payload:t,label:r,prefix:n="$"})=>!e||!(t!=null&&t.length)?null:c.jsxs("div",{className:"bg-gray-900 border border-gray-700 rounded-lg px-3 py-2 text-xs shadow-xl",children:[c.jsx("p",{className:"text-gray-400 mb-1",children:r}),t.map((i,a)=>c.jsxs("p",{style:{color:i.color},className:"font-mono",children:[i.name,": ",n,typeof i.value=="number"?i.value.toFixed(2):i.value]},a))]});function FZ(){var C,F,M,B;const[e,t]=k.useState(null),[r,n]=k.useState(null),[i,a]=k.useState(null),[o,s]=k.useState(!0),[l,u]=k.useState({}),[f,d]=k.useState([]),p=dl(),h=()=>Promise.all([tt("/dashboard"),tt("/risk"),tt("/bankroll")]).then(([E,W,z])=>{t(E),n(W==null?void 0:W.state),a(z),s(!1)}).catch(()=>s(!1));k.useEffect(()=>{h();const E=setInterval(h,12e3);return()=>clearInterval(E)},[]);function m(E,W="info"){d(z=>[{msg:E,type:W,ts:Date.now()},...z].slice(0,5))}async function g(E,W){u(z=>({...z,[E]:!0}));try{await W(),h()}catch(z){m(`Error: ${z.message}`,"error")}u(z=>({...z,[E]:!1}))}async function x(){await g("ingest",async()=>{const E=await ie("/markets",{action:"ingest"});m(E.error?`Ingest failed: ${E.error}`:`Ingested ${E.ingested||0} markets from ${E.total_scanned||0} scanned`,E.error?"error":"success")})}async function y(){await g("weather",async()=>{const E=await ie("/weather",{action:"fetch_all"});m(E.error?`Weather fetch failed: ${E.error}`:`Fetched forecasts for ${E.cities_fetched||0} cities`,E.error?"error":"success")})}async function v(){await g("predict",async()=>{const E=await ie("/models",{action:"run_predictions"});m(E.error?`Predictions failed: ${E.error}`:`Generated ${E.predictions_made||0} predictions`,E.error?"error":"success")})}async function b(){await g("risk",async()=>{const W=(await tt("/risk")).state||{};m(`Risk: $${parseFloat(W.bankroll||50).toFixed(2)} bankroll, $${parseFloat(W.open_exposure||0).toFixed(2)} exposure, Kill: ${W.kill_switch_active?"ON":"off"}`,"success")})}async function S(){await g("pipeline",async()=>{m("Pipeline: Ingest -> Weather -> Predict...","info");const E=await ie("/markets",{action:"ingest"});m(`1/3 Ingested ${E.ingested||0} markets`,E.error?"error":"info");const W=await ie("/weather",{action:"fetch_all"});m(`2/3 Weather for ${W.cities_fetched||0} cities`,W.error?"error":"info");const z=await ie("/models",{action:"run_predictions"});m(`3/3 ${z.predictions_made||0} predictions generated`,z.error?"error":"success"),m("Pipeline complete!","success")})}if(o)return c.jsx("div",{className:"flex items-center justify-center h-64",children:c.jsx("div",{className:"animate-spin w-8 h-8 border-2 border-blue-500 border-t-transparent rounded-full"})});const w=(r==null?void 0:r.config)||{},j=parseFloat((r==null?void 0:r.daily_pnl)||0),O=((e==null?void 0:e.market_count)||0)>0,_=((e==null?void 0:e.forecast_count)||0)>0,P=(((C=e==null?void 0:e.recent_predictions)==null?void 0:C.length)||0)>0,N=((i==null?void 0:i.ledger)||[]).slice().reverse().map((E,W)=>({idx:W,time:new Date(E.ts).toLocaleDateString("en-US",{month:"short",day:"numeric"}),balance:parseFloat(E.balance_after||0),amount:parseFloat(E.amount||0),event:E.event_type})),T=((e==null?void 0:e.recent_predictions)||[]).filter(E=>E.edge!=null).map(E=>({name:(E.condition_id||"").substring(0,8),edge:parseFloat((E.edge*100).toFixed(2)),pYes:parseFloat((E.p_yes*100).toFixed(1)),signal:E.recommendation||"HOLD"})),$=parseFloat((r==null?void 0:r.bankroll)||50),I=parseFloat((r==null?void 0:r.open_exposure)||0),D=$-I,L=[{name:"Available",value:Math.max(0,D),fill:"#10b981"},{name:"Exposed",value:I,fill:"#3b82f6"}];return c.jsxs("div",{className:"space-y-6",children:[c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsxs("div",{children:[c.jsx("h1",{className:"text-2xl font-bold",children:"Dashboard"}),c.jsx("p",{className:"text-gray-500 text-sm mt-0.5",children:"Weather micro-betting system overview"})]}),c.jsxs("div",{className:"flex items-center gap-3",children:[c.jsx("span",{className:`badge ${w.paper_mode!==!1?"bg-yellow":"bg-green"}`,children:w.paper_mode!==!1?"PAPER MODE":"LIVE MODE"}),(r==null?void 0:r.kill_switch_active)&&c.jsx("span",{className:"badge bg-red",children:"KILL SWITCH"}),c.jsx("span",{className:`w-2.5 h-2.5 rounded-full ${r!=null&&r.kill_switch_active?"bg-red-500":"bg-green-500 pulse-g"}`})]})]}),c.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[c.jsx(ru,{label:"Bankroll",value:`$${$.toFixed(2)}`,color:"text-green-400",sub:"Starting: $50.00",onClick:()=>p("/bankroll")}),c.jsx(ru,{label:"Daily P&L",value:`$${j.toFixed(2)}`,color:j>=0?"text-green-400":"text-red-400",sub:`Limit: -$${w.max_daily_loss_usd||5}`}),c.jsx(ru,{label:"Open Exposure",value:`$${I.toFixed(2)}`,color:"text-blue-400",sub:`Max: $${w.max_open_exposure_usd||5}`}),c.jsx(ru,{label:"Max Drawdown",value:`${parseFloat((r==null?void 0:r.max_drawdown_pct)||0).toFixed(1)}%`,color:"text-purple-400",sub:`Limit: ${w.max_drawdown_pct||20}%`})]}),c.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-4",children:[c.jsxs("div",{className:"card lg:col-span-2",children:[c.jsx("h2",{className:"font-semibold mb-3",children:"Bankroll History"}),N.length>1?c.jsx(pt,{width:"100%",height:200,children:c.jsxs(Gc,{data:N,children:[c.jsx("defs",{children:c.jsxs("linearGradient",{id:"bgGreen",x1:"0",y1:"0",x2:"0",y2:"1",children:[c.jsx("stop",{offset:"5%",stopColor:"#10b981",stopOpacity:.3}),c.jsx("stop",{offset:"95%",stopColor:"#10b981",stopOpacity:0})]})}),c.jsx(ht,{strokeDasharray:"3 3",stroke:"#1f2937"}),c.jsx(Re,{dataKey:"time",tick:{fill:"#6b7280",fontSize:11},axisLine:!1,tickLine:!1}),c.jsx(Be,{tick:{fill:"#6b7280",fontSize:11},axisLine:!1,tickLine:!1,domain:["dataMin - 2","dataMax + 2"],tickFormatter:E=>`$${E}`}),c.jsx(Se,{content:c.jsx(lp,{})}),c.jsx(Sr,{type:"monotone",dataKey:"balance",stroke:"#10b981",strokeWidth:2,fill:"url(#bgGreen)",name:"Balance"})]})}):c.jsx("p",{className:"text-gray-500 text-sm text-center py-12",children:"Chart appears after trades begin"})]}),c.jsxs("div",{className:"card",children:[c.jsx("h2",{className:"font-semibold mb-3",children:"Capital Allocation"}),c.jsx(pt,{width:"100%",height:200,children:c.jsxs(RZ,{children:[c.jsx(un,{data:L,cx:"50%",cy:"50%",innerRadius:50,outerRadius:80,paddingAngle:4,dataKey:"value",children:L.map((E,W)=>c.jsx(jr,{fill:E.fill},W))}),c.jsx(Se,{content:c.jsx(lp,{})})]})}),c.jsxs("div",{className:"flex justify-center gap-4 text-xs mt-2",children:[c.jsxs("span",{className:"flex items-center gap-1.5",children:[c.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-green-500"}),"Available $",D.toFixed(2)]}),c.jsxs("span",{className:"flex items-center gap-1.5",children:[c.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-blue-500"}),"Exposed $",I.toFixed(2)]})]})]})]}),T.length>0&&c.jsxs("div",{className:"card",children:[c.jsx("h2",{className:"font-semibold mb-3",children:"Prediction Edge Distribution"}),c.jsx(pt,{width:"100%",height:180,children:c.jsxs(zn,{data:T,barSize:24,children:[c.jsx(ht,{strokeDasharray:"3 3",stroke:"#1f2937"}),c.jsx(Re,{dataKey:"name",tick:{fill:"#6b7280",fontSize:10},axisLine:!1,tickLine:!1}),c.jsx(Be,{tick:{fill:"#6b7280",fontSize:11},axisLine:!1,tickLine:!1,tickFormatter:E=>`${E}%`}),c.jsx(Se,{content:c.jsx(lp,{prefix:""})}),c.jsx(Tt,{dataKey:"edge",name:"Edge %",children:T.map((E,W)=>c.jsx(jr,{fill:E.edge>0?"#10b981":"#ef4444",fillOpacity:.8},W))})]})})]}),c.jsxs("div",{className:"card",style:{background:"linear-gradient(135deg, rgba(59,130,246,0.05), rgba(139,92,246,0.05))"},children:[c.jsxs("div",{className:"flex items-center justify-between mb-4",children:[c.jsxs("div",{children:[c.jsx("h2",{className:"font-semibold",children:"Quick Actions"}),c.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:"Run pipeline steps or navigate to details"})]}),c.jsxs("button",{onClick:S,disabled:l.pipeline,className:"btn btn-p text-xs flex items-center gap-2",children:[l.pipeline?c.jsx("span",{className:"animate-spin w-3 h-3 border-2 border-white border-t-transparent rounded-full"}):c.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M13 10V3L4 14h7v7l9-11h-7z"})}),"Run Full Pipeline"]})]}),c.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3",children:[c.jsx(Ki,{icon:"M13 7h8m0 0v8m0-8l-8 8-4-4-6 6",title:"Ingest Markets",desc:"Scan Polymarket for weather events",onClick:x,busy:l.ingest,color:"blue",badge:O?{text:`${e.market_count} tracked`,color:"blue"}:{text:"Start here",color:"yellow"}}),c.jsx(Ki,{icon:"M3 15a4 4 0 004 4h9a5 5 0 10-.1-9.999 5.002 5.002 0 10-9.78 2.096A4.001 4.001 0 003 15z",title:"Fetch Weather",desc:"Pull latest NWS forecasts",onClick:y,busy:l.weather,color:"green",badge:_?{text:`${e.forecast_count} runs`,color:"green"}:null}),c.jsx(Ki,{icon:"M9 3v2m6-2v2M9 19v2m6-2v2M5 9H3m2 6H3m18-6h-2m2 6h-2M7 19h10a2 2 0 002-2V7a2 2 0 00-2-2H7a2 2 0 00-2 2v10a2 2 0 002 2zM9 9h6v6H9V9z",title:"Run Predictions",desc:"Generate P(YES) + edge",onClick:v,busy:l.predict,color:"purple",badge:P?{text:`${e.recent_predictions.length} active`,color:"purple"}:null}),c.jsx(Ki,{icon:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z",title:"Risk Scan",desc:"Check limits and kill switch",onClick:b,busy:l.risk,color:"yellow"}),c.jsx(Ki,{icon:"M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8V7m0 1v8m0 0v1",title:"View Bankroll",desc:"Balance history and P&L",onClick:()=>p("/bankroll"),color:"green"}),c.jsx(Ki,{icon:"M21 12a9 9 0 01-9 9m9-9a9 9 0 00-9-9m9 9H3m9 9a9 9 0 01-9-9m9 9c1.657 0 3-4.03 3-9s-1.343-9-3-9m0 18c-1.657 0-3-4.03-3-9s1.343-9 3-9",title:"Polymarket CLOB",desc:"Live prices, orderbooks & trading",onClick:()=>p("/polymarket"),color:"purple",badge:{text:"LIVE",color:"purple"}})]})]}),f.length>0&&c.jsxs("div",{className:"card",children:[c.jsxs("div",{className:"flex items-center justify-between mb-3",children:[c.jsx("h2",{className:"font-semibold text-sm",children:"Action Log"}),c.jsx("button",{onClick:()=>d([]),className:"text-xs text-gray-500 hover:text-gray-300",children:"Clear"})]}),c.jsx("div",{className:"space-y-1.5",children:f.map((E,W)=>c.jsxs("div",{className:`flex items-center gap-2 text-xs px-3 py-2 rounded-lg ${E.type==="error"?"bg-red-500/10 text-red-400":E.type==="success"?"bg-green-500/10 text-green-400":"bg-blue-500/10 text-blue-400"}`,children:[c.jsx("span",{className:`w-1.5 h-1.5 rounded-full flex-shrink-0 ${E.type==="error"?"bg-red-500":E.type==="success"?"bg-green-500":"bg-blue-500"}`}),c.jsx("span",{className:"flex-1",children:E.msg}),c.jsx("span",{className:"text-gray-600",children:new Date(E.ts).toLocaleTimeString()})]},E.ts+W))})]}),c.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:[c.jsxs("div",{className:"card",children:[c.jsxs("div",{className:"flex items-center justify-between mb-3",children:[c.jsx("h2",{className:"font-semibold",children:"Recent Predictions"}),c.jsx("button",{onClick:()=>p("/models"),className:"text-xs text-blue-400 hover:text-blue-300",children:"View All"})]}),((F=e==null?void 0:e.recent_predictions)==null?void 0:F.length)>0?c.jsxs("table",{children:[c.jsx("thead",{children:c.jsxs("tr",{children:[c.jsx("th",{children:"Market"}),c.jsx("th",{children:"P(Yes)"}),c.jsx("th",{children:"Edge"}),c.jsx("th",{children:"Signal"})]})}),c.jsx("tbody",{children:e.recent_predictions.slice(0,6).map((E,W)=>{var z,X;return c.jsxs("tr",{children:[c.jsx("td",{className:"max-w-[180px] truncate font-mono text-xs",children:(z=E.condition_id)==null?void 0:z.substring(0,20)}),c.jsxs("td",{className:"font-mono text-green-400",children:[(E.p_yes*100).toFixed(1),"%"]}),c.jsx("td",{className:`font-mono ${E.edge>0?"text-green-400":"text-red-400"}`,children:E.edge?(E.edge*100).toFixed(1)+"%":"-"}),c.jsx("td",{children:c.jsx("span",{className:`badge ${(X=E.recommendation)!=null&&X.startsWith("BUY")?"bg-green":"bg-yellow"}`,children:E.recommendation||"HOLD"})})]},W)})})]}):c.jsx("p",{className:"text-gray-500 text-sm",children:"No predictions yet. Ingest markets to begin."})]}),c.jsxs("div",{className:"card",children:[c.jsxs("div",{className:"flex items-center justify-between mb-3",children:[c.jsx("h2",{className:"font-semibold",children:"Recent Trades"}),c.jsx("button",{onClick:()=>p("/trades"),className:"text-xs text-blue-400 hover:text-blue-300",children:"View All"})]}),((M=e==null?void 0:e.recent_trades)==null?void 0:M.length)>0?c.jsxs("table",{children:[c.jsx("thead",{children:c.jsxs("tr",{children:[c.jsx("th",{children:"Time"}),c.jsx("th",{children:"Side"}),c.jsx("th",{children:"Size"}),c.jsx("th",{children:"P&L"})]})}),c.jsx("tbody",{children:e.recent_trades.map((E,W)=>{var z;return c.jsxs("tr",{children:[c.jsx("td",{className:"text-gray-400 text-sm",children:new Date(E.match_time).toLocaleString()}),c.jsx("td",{children:c.jsx("span",{className:`badge ${E.side==="buy"?"bg-green":"bg-red"}`,children:(z=E.side)==null?void 0:z.toUpperCase()})}),c.jsxs("td",{className:"font-mono",children:["$",parseFloat(E.size_usd||0).toFixed(2)]}),c.jsxs("td",{className:`font-mono ${parseFloat(E.pnl||0)>=0?"text-green-400":"text-red-400"}`,children:["$",parseFloat(E.pnl||0).toFixed(2)]})]},W)})})]}):c.jsx("p",{className:"text-gray-500 text-sm",children:"No trades yet. System in paper mode."})]})]}),c.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[c.jsxs("div",{className:"card cursor-pointer hover:border-blue-500/30 transition",onClick:()=>p("/markets"),children:[c.jsx("p",{className:"text-xs text-gray-500 uppercase mb-1",children:"Markets Tracked"}),c.jsx("p",{className:"stat-v text-blue-400",children:(e==null?void 0:e.market_count)||0}),c.jsxs("p",{className:"text-xs text-gray-500 mt-1",children:[(e==null?void 0:e.weather_market_count)||0," weather"]})]}),c.jsxs("div",{className:"card cursor-pointer hover:border-purple-500/30 transition",onClick:()=>p("/weather"),children:[c.jsx("p",{className:"text-xs text-gray-500 uppercase mb-1",children:"Forecast Runs"}),c.jsx("p",{className:"stat-v text-purple-400",children:(e==null?void 0:e.forecast_count)||0})]}),c.jsxs("div",{className:"card cursor-pointer hover:border-green-500/30 transition",onClick:()=>p("/risk"),children:[c.jsx("p",{className:"text-xs text-gray-500 uppercase mb-1",children:"Risk Config"}),c.jsxs("div",{className:"space-y-1 text-sm",children:[c.jsxs("div",{className:"flex justify-between",children:[c.jsx("span",{className:"text-gray-500",children:"Max Bet"}),c.jsxs("span",{children:["$",w.max_bet_usd||.5]})]}),c.jsxs("div",{className:"flex justify-between",children:[c.jsx("span",{className:"text-gray-500",children:"Min Edge"}),c.jsxs("span",{children:[((w.min_edge_threshold||.03)*100).toFixed(0),"%"]})]}),c.jsxs("div",{className:"flex justify-between",children:[c.jsx("span",{className:"text-gray-500",children:"Kelly"}),c.jsxs("span",{children:[w.fractional_kelly||.1,"x"]})]})]})]})]}),c.jsxs("div",{className:"card",children:[c.jsx("h2",{className:"font-semibold mb-3",children:"System Alerts"}),((B=e==null?void 0:e.recent_alerts)==null?void 0:B.length)>0?c.jsx("div",{className:"space-y-2",children:e.recent_alerts.map((E,W)=>c.jsxs("div",{className:`flex items-start gap-3 p-3 rounded-lg ${E.severity==="critical"?"bg-red-500/10":E.severity==="warning"?"bg-yellow-500/10":"bg-blue-500/10"}`,children:[c.jsx("span",{className:`badge ${E.severity==="critical"?"bg-red":E.severity==="warning"?"bg-yellow":"bg-blue"}`,children:E.severity}),c.jsxs("div",{children:[c.jsx("p",{className:"text-sm",children:E.message}),c.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:new Date(E.ts).toLocaleString()})]})]},W))}):c.jsx("p",{className:"text-gray-500 text-sm",children:"No alerts. System healthy."})]})]})}function zZ(){const[e,t]=k.useState([]),[r,n]=k.useState(!0),[i,a]=k.useState(!1),o=()=>tt("/markets").then(u=>{t(u.markets||[]),n(!1)});k.useEffect(()=>{o()},[]);async function s(){a(!0);const u=await ie("/markets",{action:"ingest"});alert(`Ingested ${u.ingested||0} weather markets from ${u.total_scanned||0} scanned`),o(),a(!1)}async function l(u){const f=await ie("/markets",{action:"parse",condition_id:u});alert(JSON.stringify(f.parsed,null,2)),o()}return r?c.jsx("div",{className:"flex items-center justify-center h-64",children:c.jsx("div",{className:"animate-spin w-8 h-8 border-2 border-blue-500 border-t-transparent rounded-full"})}):c.jsxs("div",{className:"space-y-6",children:[c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsxs("div",{children:[c.jsx("h1",{className:"text-2xl font-bold",children:"Markets"}),c.jsx("p",{className:"text-gray-500 text-sm",children:"Polymarket weather-related markets"})]}),c.jsx("button",{onClick:s,disabled:i,className:"btn btn-p",children:i?"Ingesting...":"Ingest Markets"})]}),c.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[c.jsxs("div",{className:"card",children:[c.jsx("p",{className:"text-xs text-gray-500 uppercase mb-1",children:"Total"}),c.jsx("p",{className:"stat-v text-blue-400",children:e.length})]}),c.jsxs("div",{className:"card",children:[c.jsx("p",{className:"text-xs text-gray-500 uppercase mb-1",children:"Active"}),c.jsx("p",{className:"stat-v text-green-400",children:e.filter(u=>u.active).length})]}),c.jsxs("div",{className:"card",children:[c.jsx("p",{className:"text-xs text-gray-500 uppercase mb-1",children:"Parsed"}),c.jsx("p",{className:"stat-v text-purple-400",children:e.filter(u=>{var f;return(f=u.parsed_event)==null?void 0:f.variable}).length})]})]}),c.jsx("div",{className:"card overflow-x-auto",children:c.jsxs("table",{children:[c.jsx("thead",{children:c.jsxs("tr",{children:[c.jsx("th",{children:"Question"}),c.jsx("th",{children:"Category"}),c.jsx("th",{children:"Liquidity"}),c.jsx("th",{children:"End Date"}),c.jsx("th",{children:"Parsed"}),c.jsx("th",{children:"Actions"})]})}),c.jsx("tbody",{children:e.length===0?c.jsx("tr",{children:c.jsx("td",{colSpan:6,className:"text-center text-gray-500 py-8",children:"No markets. Click Ingest."})}):e.map(u=>{var f;return c.jsxs("tr",{children:[c.jsxs("td",{className:"max-w-[300px]",children:[c.jsx("p",{className:"truncate font-medium",children:u.question}),c.jsx("p",{className:"text-xs text-gray-500 truncate",children:u.condition_id})]}),c.jsx("td",{children:c.jsx("span",{className:"badge bg-blue",children:u.category||"weather"})}),c.jsxs("td",{className:"font-mono",children:["$",parseFloat(u.liquidity||0).toFixed(0)]}),c.jsx("td",{className:"text-gray-400 text-sm",children:u.end_ts?new Date(u.end_ts).toLocaleDateString():"-"}),c.jsx("td",{children:(f=u.parsed_event)!=null&&f.variable?c.jsx("span",{className:"badge bg-green",children:"Yes"}):c.jsx("span",{className:"badge bg-yellow",children:"No"})}),c.jsx("td",{children:c.jsx("button",{onClick:()=>l(u.condition_id),className:"text-xs text-blue-400 hover:text-blue-300",children:"Parse"})})]},u.condition_id)})})]})})]})}const WZ=["New York","Chicago","Los Angeles","Miami","Denver","Seattle","Boston","San Francisco","Houston","Phoenix"],cw=["#3b82f6","#10b981","#f59e0b","#ef4444","#8b5cf6","#06b6d4","#ec4899","#f97316"],fw=({active:e,payload:t,label:r})=>!e||!(t!=null&&t.length)?null:c.jsxs("div",{className:"bg-gray-900 border border-gray-700 rounded-lg px-3 py-2 text-xs shadow-xl",children:[c.jsxs("p",{className:"text-gray-400 mb-1",children:[r,"h lead"]}),t.map((n,i)=>{var a;return c.jsxs("p",{style:{color:n.color},className:"font-mono",children:[n.name,": ",(a=n.value)==null?void 0:a.toFixed(1)]},i)})]});function UZ(){var S;const[e,t]=k.useState([]),[r,n]=k.useState(!0),[i,a]=k.useState(!1),[o,s]=k.useState("New York"),[l,u]=k.useState("temperature"),f=()=>tt("/weather").then(w=>{t(w.forecasts||[]),n(!1)});k.useEffect(()=>{f()},[]);async function d(){a(!0),await ie("/weather",{action:"fetch",city:o}),f(),a(!1)}async function p(){a(!0),await ie("/weather",{action:"fetch_all"}),f(),a(!1)}if(r)return c.jsx("div",{className:"flex items-center justify-center h-64",children:c.jsx("div",{className:"animate-spin w-8 h-8 border-2 border-blue-500 border-t-transparent rounded-full"})});const h={};e.forEach(w=>{const j=w.location_name||w.geom_hash;h[j]||(h[j]=[]),h[j].push(w)});const m=[...new Set(e.map(w=>w.variable))],g=Object.keys(h),x={};Object.entries(h).forEach(([w,j])=>{j.filter(O=>O.variable===l).forEach(O=>{const _=parseInt(O.lead_hours||0);x[_]||(x[_]={lead:_}),x[_][w]=parseFloat(O.value_mean||0)})});const y=Object.values(x).sort((w,j)=>w.lead-j.lead),v=g[0],b=v?h[v].filter(w=>w.variable===l).sort((w,j)=>(w.lead_hours||0)-(j.lead_hours||0)).map(w=>({lead:parseInt(w.lead_hours||0),mean:parseFloat(w.value_mean||0),min:parseFloat(w.value_min||0),max:parseFloat(w.value_max||0)})):[];return c.jsxs("div",{className:"space-y-6",children:[c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsxs("div",{children:[c.jsx("h1",{className:"text-2xl font-bold",children:"Weather Forecasts"}),c.jsx("p",{className:"text-gray-500 text-sm",children:"NWS forecast data + ensemble analysis"})]}),c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("select",{value:o,onChange:w=>s(w.target.value),className:"bg-gray-800 border border-gray-700 rounded-lg px-3 py-2 text-sm",children:WZ.map(w=>c.jsx("option",{value:w,children:w},w))}),c.jsx("button",{onClick:d,disabled:i,className:"btn btn-p",children:i?"...":"Fetch City"}),c.jsx("button",{onClick:p,disabled:i,className:"btn btn-s",children:"Fetch All"})]})]}),c.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[c.jsxs("div",{className:"card",children:[c.jsx("p",{className:"text-xs text-gray-500 uppercase mb-1",children:"Data Points"}),c.jsx("p",{className:"stat-v text-blue-400",children:e.length})]}),c.jsxs("div",{className:"card",children:[c.jsx("p",{className:"text-xs text-gray-500 uppercase mb-1",children:"Locations"}),c.jsx("p",{className:"stat-v text-green-400",children:g.length})]}),c.jsxs("div",{className:"card",children:[c.jsx("p",{className:"text-xs text-gray-500 uppercase mb-1",children:"Latest Run"}),c.jsx("p",{className:"text-sm text-gray-300 mt-1",children:(S=e[0])!=null&&S.run_ts?new Date(e[0].run_ts).toLocaleString():"None"})]}),c.jsxs("div",{className:"card",children:[c.jsx("p",{className:"text-xs text-gray-500 uppercase mb-1",children:"Variables"}),c.jsx("p",{className:"stat-v text-purple-400",children:m.length})]})]}),c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm text-gray-400",children:"Chart variable:"}),m.slice(0,6).map(w=>c.jsx("button",{onClick:()=>u(w),className:`px-3 py-1 text-xs rounded-full border transition ${l===w?"bg-blue-500/20 border-blue-500/50 text-blue-400":"border-gray-700 text-gray-500 hover:text-gray-300"}`,children:w},w))]}),y.length>0&&c.jsxs("div",{className:"card",children:[c.jsxs("h2",{className:"font-semibold mb-3",children:[l," Forecast by Location (Lead Hours)"]}),c.jsx(pt,{width:"100%",height:300,children:c.jsxs(uw,{data:y,children:[c.jsx(ht,{strokeDasharray:"3 3",stroke:"#1f2937"}),c.jsx(Re,{dataKey:"lead",tick:{fill:"#6b7280",fontSize:11},axisLine:!1,tickLine:!1,label:{value:"Lead Hours",position:"insideBottom",offset:-5,fill:"#6b7280",fontSize:11}}),c.jsx(Be,{tick:{fill:"#6b7280",fontSize:11},axisLine:!1,tickLine:!1}),c.jsx(Se,{content:c.jsx(fw,{})}),c.jsx(Yr,{wrapperStyle:{fontSize:11,color:"#9ca3af"}}),g.slice(0,8).map((w,j)=>c.jsx(On,{type:"monotone",dataKey:w,stroke:cw[j%cw.length],strokeWidth:2,dot:!1,name:w},w))]})})]}),b.length>0&&c.jsxs("div",{className:"card",children:[c.jsxs("h2",{className:"font-semibold mb-3",children:[v,": ",l," Range (Mean / Min / Max)"]}),c.jsx(pt,{width:"100%",height:240,children:c.jsxs(uw,{data:b,children:[c.jsx(ht,{strokeDasharray:"3 3",stroke:"#1f2937"}),c.jsx(Re,{dataKey:"lead",tick:{fill:"#6b7280",fontSize:11},axisLine:!1,tickLine:!1}),c.jsx(Be,{tick:{fill:"#6b7280",fontSize:11},axisLine:!1,tickLine:!1}),c.jsx(Se,{content:c.jsx(fw,{})}),c.jsx(Yr,{wrapperStyle:{fontSize:11}}),c.jsx(On,{type:"monotone",dataKey:"max",stroke:"#ef4444",strokeWidth:1.5,dot:!1,strokeDasharray:"4 4",name:"Max"}),c.jsx(On,{type:"monotone",dataKey:"mean",stroke:"#10b981",strokeWidth:2,dot:!1,name:"Mean"}),c.jsx(On,{type:"monotone",dataKey:"min",stroke:"#3b82f6",strokeWidth:1.5,dot:!1,strokeDasharray:"4 4",name:"Min"})]})})]}),Object.entries(h).slice(0,8).map(([w,j])=>c.jsxs("div",{className:"card",children:[c.jsx("h3",{className:"font-semibold mb-3",children:w}),c.jsxs("table",{children:[c.jsx("thead",{children:c.jsxs("tr",{children:[c.jsx("th",{children:"Var"}),c.jsx("th",{children:"Lead"}),c.jsx("th",{children:"Mean"}),c.jsx("th",{children:"Min"}),c.jsx("th",{children:"Max"})]})}),c.jsx("tbody",{children:j.slice(0,15).map((O,_)=>c.jsxs("tr",{children:[c.jsx("td",{className:"font-medium",children:O.variable}),c.jsxs("td",{className:"font-mono",children:[O.lead_hours,"h"]}),c.jsx("td",{className:"font-mono text-green-400",children:parseFloat(O.value_mean||0).toFixed(1)}),c.jsx("td",{className:"font-mono text-blue-400",children:parseFloat(O.value_min||0).toFixed(1)}),c.jsx("td",{className:"font-mono text-red-400",children:parseFloat(O.value_max||0).toFixed(1)})]},_))})]})]},w)),e.length===0&&c.jsx("div",{className:"card text-center py-12",children:c.jsx("p",{className:"text-gray-500",children:"No forecast data. Click Fetch."})})]})}const KZ=({active:e,payload:t})=>{var n,i,a,o;if(!e||!(t!=null&&t.length))return null;const r=(n=t[0])==null?void 0:n.payload;return r?c.jsxs("div",{className:"bg-gray-900 border border-gray-700 rounded-lg px-3 py-2 text-xs shadow-xl",children:[c.jsx("p",{className:"text-gray-400 mb-1 font-mono",children:r.id}),c.jsxs("p",{className:"text-green-400",children:["P(Yes): ",(i=r.pYes)==null?void 0:i.toFixed(1),"%"]}),c.jsxs("p",{className:r.edge>=0?"text-green-400":"text-red-400",children:["Edge: ",(a=r.edge)==null?void 0:a.toFixed(2),"%"]}),c.jsxs("p",{className:"text-blue-400",children:["Confidence: ",(o=r.confidence)==null?void 0:o.toFixed(0),"%"]}),c.jsxs("p",{className:"text-purple-400",children:["Signal: ",r.signal]})]}):null};function HZ(){const[e,t]=k.useState([]),[r,n]=k.useState([]),[i,a]=k.useState(!0);k.useEffect(()=>{tt("/models").then(m=>{t(m.models||[]),n(m.predictions||[]),a(!1)}).catch(()=>a(!1))},[]);async function o(){await ie("/models",{action:"run_predictions"}),window.location.reload()}if(i)return c.jsx("div",{className:"flex items-center justify-center h-64",children:c.jsx("div",{className:"animate-spin w-8 h-8 border-2 border-blue-500 border-t-transparent rounded-full"})});const s=r.filter(m=>m.edge!=null&&m.p_yes!=null).map(m=>({id:(m.condition_id||"").substring(0,12),pYes:parseFloat((m.p_yes*100).toFixed(1)),edge:parseFloat((m.edge*100).toFixed(2)),confidence:parseFloat(((m.confidence||.5)*100).toFixed(0)),signal:m.recommendation||"HOLD"})),l=s.filter(m=>m.signal.startsWith("BUY")),u=s.filter(m=>!m.signal.startsWith("BUY")&&m.signal!=="SKIP"),f=s.filter(m=>m.signal==="SKIP"),d=s.map(m=>({name:m.id,edge:m.edge})).sort((m,g)=>g.edge-m.edge),p=[0,0,0,0,0];s.forEach(m=>{const g=Math.min(Math.floor(m.confidence/20),4);p[g]++});const h=p.map((m,g)=>({range:`${g*20}-${(g+1)*20}%`,count:m}));return c.jsxs("div",{className:"space-y-6",children:[c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsxs("div",{children:[c.jsx("h1",{className:"text-2xl font-bold",children:"Models & Predictions"}),c.jsx("p",{className:"text-gray-500 text-sm",children:"Probabilistic forecasting pipeline"})]}),c.jsx("button",{onClick:o,className:"btn btn-p",children:"Run Predictions"})]}),c.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[c.jsxs("div",{className:"card",children:[c.jsx("p",{className:"text-xs text-gray-500 uppercase mb-1",children:"Model Versions"}),c.jsx("p",{className:"stat-v text-blue-400",children:e.length})]}),c.jsxs("div",{className:"card",children:[c.jsx("p",{className:"text-xs text-gray-500 uppercase mb-1",children:"Predictions"}),c.jsx("p",{className:"stat-v text-purple-400",children:r.length})]}),c.jsxs("div",{className:"card",children:[c.jsx("p",{className:"text-xs text-gray-500 uppercase mb-1",children:"Active"}),c.jsx("p",{className:"stat-v text-green-400",children:e.filter(m=>m.active).length})]}),c.jsxs("div",{className:"card",children:[c.jsx("p",{className:"text-xs text-gray-500 uppercase mb-1",children:"Buy Signals"}),c.jsx("p",{className:"stat-v text-green-400",children:l.length})]})]}),c.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:[c.jsxs("div",{className:"card",children:[c.jsx("h2",{className:"font-semibold mb-3",children:"P(Yes) vs Edge"}),s.length>0?c.jsx(pt,{width:"100%",height:280,children:c.jsxs(BZ,{margin:{top:10,right:10,bottom:10,left:0},children:[c.jsx(ht,{strokeDasharray:"3 3",stroke:"#1f2937"}),c.jsx(Re,{type:"number",dataKey:"pYes",name:"P(Yes)",unit:"%",tick:{fill:"#6b7280",fontSize:11},axisLine:!1,tickLine:!1,domain:[0,100]}),c.jsx(Be,{type:"number",dataKey:"edge",name:"Edge",unit:"%",tick:{fill:"#6b7280",fontSize:11},axisLine:!1,tickLine:!1}),c.jsx(bl,{type:"number",dataKey:"confidence",range:[40,200]}),c.jsx(Se,{content:c.jsx(KZ,{})}),l.length>0&&c.jsx(bi,{name:"BUY",data:l,fill:"#10b981",fillOpacity:.8}),u.length>0&&c.jsx(bi,{name:"HOLD",data:u,fill:"#eab308",fillOpacity:.8}),f.length>0&&c.jsx(bi,{name:"SKIP",data:f,fill:"#ef4444",fillOpacity:.6}),c.jsx(Yr,{wrapperStyle:{fontSize:11,color:"#9ca3af"}})]})}):c.jsx("p",{className:"text-gray-500 text-sm text-center py-16",children:"Run predictions to see chart"})]}),c.jsxs("div",{className:"card",children:[c.jsx("h2",{className:"font-semibold mb-3",children:"Edge Distribution"}),d.length>0?c.jsx(pt,{width:"100%",height:280,children:c.jsxs(zn,{data:d,barSize:20,children:[c.jsx(ht,{strokeDasharray:"3 3",stroke:"#1f2937"}),c.jsx(Re,{dataKey:"name",tick:{fill:"#6b7280",fontSize:9},axisLine:!1,tickLine:!1}),c.jsx(Be,{tick:{fill:"#6b7280",fontSize:11},axisLine:!1,tickLine:!1,tickFormatter:m=>`${m}%`}),c.jsx(Se,{formatter:m=>[`${m}%`,"Edge"],contentStyle:{background:"#111827",border:"1px solid #374151",borderRadius:8,fontSize:12}}),c.jsx(Tt,{dataKey:"edge",name:"Edge %",children:d.map((m,g)=>c.jsx(jr,{fill:m.edge>0?"#10b981":"#ef4444",fillOpacity:.8},g))})]})}):c.jsx("p",{className:"text-gray-500 text-sm text-center py-16",children:"No predictions yet"})]})]}),s.length>0&&c.jsxs("div",{className:"card",children:[c.jsx("h2",{className:"font-semibold mb-3",children:"Confidence Distribution"}),c.jsx(pt,{width:"100%",height:160,children:c.jsxs(zn,{data:h,barSize:40,children:[c.jsx(ht,{strokeDasharray:"3 3",stroke:"#1f2937"}),c.jsx(Re,{dataKey:"range",tick:{fill:"#6b7280",fontSize:11},axisLine:!1,tickLine:!1}),c.jsx(Be,{tick:{fill:"#6b7280",fontSize:11},axisLine:!1,tickLine:!1,allowDecimals:!1}),c.jsx(Se,{formatter:m=>[m,"Predictions"],contentStyle:{background:"#111827",border:"1px solid #374151",borderRadius:8,fontSize:12}}),c.jsx(Tt,{dataKey:"count",fill:"#8b5cf6",fillOpacity:.7,radius:[4,4,0,0]})]})})]}),c.jsxs("div",{className:"card",children:[c.jsx("h2",{className:"font-semibold mb-3",children:"Model Versions"}),c.jsxs("table",{children:[c.jsx("thead",{children:c.jsxs("tr",{children:[c.jsx("th",{children:"ID"}),c.jsx("th",{children:"Type"}),c.jsx("th",{children:"Tag"}),c.jsx("th",{children:"Status"}),c.jsx("th",{children:"Created"})]})}),c.jsx("tbody",{children:e.map(m=>c.jsxs("tr",{children:[c.jsxs("td",{className:"font-mono",children:["#",m.id]}),c.jsx("td",{children:m.model_type}),c.jsx("td",{children:m.version_tag}),c.jsx("td",{children:c.jsx("span",{className:`badge ${m.active?"bg-green":"bg-yellow"}`,children:m.active?"Active":"Off"})}),c.jsx("td",{className:"text-gray-400 text-sm",children:new Date(m.created_at).toLocaleDateString()})]},m.id))})]})]}),c.jsxs("div",{className:"card",children:[c.jsx("h2",{className:"font-semibold mb-3",children:"Predictions"}),c.jsxs("table",{children:[c.jsx("thead",{children:c.jsxs("tr",{children:[c.jsx("th",{children:"Market"}),c.jsx("th",{children:"P(Yes)"}),c.jsx("th",{children:"Confidence"}),c.jsx("th",{children:"Edge"}),c.jsx("th",{children:"Signal"}),c.jsx("th",{children:"Time"})]})}),c.jsx("tbody",{children:r.length===0?c.jsx("tr",{children:c.jsx("td",{colSpan:6,className:"text-center text-gray-500 py-8",children:"No predictions yet"})}):r.map((m,g)=>{var x,y;return c.jsxs("tr",{children:[c.jsx("td",{className:"font-mono text-xs max-w-[140px] truncate",children:m.question||((x=m.condition_id)==null?void 0:x.substring(0,20))}),c.jsxs("td",{className:"font-mono text-green-400",children:[(m.p_yes*100).toFixed(1),"%"]}),c.jsx("td",{className:"font-mono",children:m.confidence?(m.confidence*100).toFixed(0)+"%":"-"}),c.jsx("td",{className:`font-mono ${(m.edge||0)>0?"text-green-400":"text-red-400"}`,children:m.edge?(m.edge*100).toFixed(2)+"%":"-"}),c.jsx("td",{children:c.jsx("span",{className:`badge ${(y=m.recommendation)!=null&&y.startsWith("BUY")?"bg-green":m.recommendation==="SKIP"?"bg-red":"bg-yellow"}`,children:m.recommendation||"-"})}),c.jsx("td",{className:"text-gray-400 text-sm",children:new Date(m.asof_ts).toLocaleString()})]},g)})})]})]})]})}const up={conservative:{label:"Conservative",color:"blue",desc:"Preserve capital. Small bets, strict limits.",icon:"M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z",config:{paper_mode:!0,max_bet_usd:.25,max_daily_loss_usd:2,max_open_exposure_usd:3,max_drawdown_pct:10,min_edge_threshold:.05,min_liquidity:200,fractional_kelly:.05},kelly_note:"5% Kelly -> ~$0.12 avg bet on 10% edge",survival:"99% chance to survive 30 days"},moderate:{label:"Moderate",color:"yellow",desc:"Balanced risk/reward. Default for $50 experiment.",icon:"M3 6l3 1m0 0l-3 9a5.002 5.002 0 006.001 0M6 7l3 9M6 7l6-2m6 2l3-1m-3 1l-3 9a5.002 5.002 0 006.001 0M18 7l3 9m-3-9l-6-2m0-2v2m0 16V5m0 16H9m3 0h3",config:{paper_mode:!0,max_bet_usd:.5,max_daily_loss_usd:5,max_open_exposure_usd:5,max_drawdown_pct:20,min_edge_threshold:.03,min_liquidity:100,fractional_kelly:.1},kelly_note:"10% Kelly -> ~$0.25 avg bet on 5% edge",survival:"90% chance to survive 30 days"},aggressive:{label:"Aggressive",color:"red",desc:"Max growth. Higher risk of ruin.",icon:"M17.657 18.657A8 8 0 016.343 7.343S7 9 9 10c0-2 .5-5 2.986-7C14 5 16.09 5.777 17.656 7.343A7.975 7.975 0 0120 13a7.975 7.975 0 01-2.343 5.657z",config:{paper_mode:!0,max_bet_usd:1,max_daily_loss_usd:8,max_open_exposure_usd:10,max_drawdown_pct:35,min_edge_threshold:.02,min_liquidity:50,fractional_kelly:.2},kelly_note:"20% Kelly -> ~$0.50 avg bet on 5% edge",survival:"70% chance to survive 30 days"}};function VZ(){var y;const[e,t]=k.useState(null),[r,n]=k.useState(!0),[i,a]=k.useState(null),o=()=>tt("/risk").then(v=>{t(v.state),n(!1)});k.useEffect(()=>{o();const v=setInterval(o,1e4);return()=>clearInterval(v)},[]);async function s(){if(e==null?void 0:e.kill_switch_active)await ie("/risk",{action:"kill_switch_deactivate"});else{const b=prompt("Kill switch reason:");if(!b)return;await ie("/risk",{action:"kill_switch_activate",reason:b})}o()}async function l(v,b){const S={...e.config,[v]:b};await ie("/risk",{action:"update_config",config:S}),o()}async function u(v){a(v);const b=up[v];await ie("/risk",{action:"update_config",config:b.config}),o(),setTimeout(()=>a(null),600)}if(r)return c.jsx("div",{className:"flex items-center justify-center h-64",children:c.jsx("div",{className:"animate-spin w-8 h-8 border-2 border-blue-500 border-t-transparent rounded-full"})});const f=(e==null?void 0:e.config)||{},d=parseFloat((e==null?void 0:e.bankroll)||50),p=parseFloat((e==null?void 0:e.open_exposure)||0),h=parseFloat((e==null?void 0:e.daily_pnl)||0),m=parseFloat((e==null?void 0:e.max_drawdown_pct)||0),g=[{name:"Exposure",value:Math.min(100,p/(f.max_open_exposure_usd||5)*100),fill:"#3b82f6"},{name:"Daily Loss",value:Math.min(100,Math.abs(h)/(f.max_daily_loss_usd||5)*100),fill:h<0?"#ef4444":"#10b981"},{name:"Drawdown",value:Math.min(100,m/(f.max_drawdown_pct||20)*100),fill:"#8b5cf6"}],x=(y=Object.entries(up).find(([v,b])=>b.config.fractional_kelly===f.fractional_kelly&&b.config.max_bet_usd===f.max_bet_usd))==null?void 0:y[0];return c.jsxs("div",{className:"space-y-6",children:[c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsxs("div",{children:[c.jsx("h1",{className:"text-2xl font-bold",children:"Risk Management"}),c.jsx("p",{className:"text-gray-500 text-sm",children:"Controls, presets & kill switches"})]}),c.jsx("button",{onClick:s,className:`btn ${e!=null&&e.kill_switch_active?"btn-s":"btn-d"}`,children:e!=null&&e.kill_switch_active?"Deactivate Kill Switch":"Activate Kill Switch"})]}),(e==null?void 0:e.kill_switch_active)&&c.jsxs("div",{className:"bg-red-500/10 border border-red-500/30 rounded-xl p-4 flex items-center gap-3",children:[c.jsx("span",{className:"text-2xl",children:"🚨"}),c.jsxs("div",{children:[c.jsx("p",{className:"font-semibold text-red-400",children:"KILL SWITCH ACTIVE"}),c.jsx("p",{className:"text-sm text-gray-400",children:e.kill_reason})]})]}),c.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[c.jsxs("div",{className:"card",children:[c.jsx("p",{className:"text-xs text-gray-500 uppercase mb-1",children:"Bankroll"}),c.jsxs("p",{className:"stat-v text-green-400",children:["$",d.toFixed(2)]})]}),c.jsxs("div",{className:"card",children:[c.jsx("p",{className:"text-xs text-gray-500 uppercase mb-1",children:"Daily P&L"}),c.jsxs("p",{className:`stat-v ${h>=0?"text-green-400":"text-red-400"}`,children:["$",h.toFixed(2)]})]}),c.jsxs("div",{className:"card",children:[c.jsx("p",{className:"text-xs text-gray-500 uppercase mb-1",children:"Exposure"}),c.jsxs("p",{className:"stat-v text-blue-400",children:["$",p.toFixed(2)]})]}),c.jsxs("div",{className:"card",children:[c.jsx("p",{className:"text-xs text-gray-500 uppercase mb-1",children:"Drawdown"}),c.jsxs("p",{className:"stat-v text-purple-400",children:[m.toFixed(1),"%"]})]})]}),c.jsxs("div",{className:"card",children:[c.jsx("h2",{className:"font-semibold mb-3",children:"Risk Utilization"}),c.jsx(pt,{width:"100%",height:160,children:c.jsxs(zn,{data:g,layout:"vertical",barSize:20,children:[c.jsx(ht,{strokeDasharray:"3 3",stroke:"#1f2937",horizontal:!1}),c.jsx(Re,{type:"number",domain:[0,100],tick:{fill:"#6b7280",fontSize:11},axisLine:!1,tickLine:!1,tickFormatter:v=>`${v}%`}),c.jsx(Be,{type:"category",dataKey:"name",tick:{fill:"#9ca3af",fontSize:12},axisLine:!1,tickLine:!1,width:80}),c.jsx(Se,{formatter:v=>[`${v.toFixed(0)}%`,"Utilization"],contentStyle:{background:"#111827",border:"1px solid #374151",borderRadius:8,fontSize:12}}),c.jsx(Tt,{dataKey:"value",radius:[0,4,4,0],children:g.map((v,b)=>c.jsx(A.Fragment,{children:A.createElement("rect",null)},b))})]})})]}),c.jsxs("div",{className:"card",style:{background:"linear-gradient(135deg, rgba(59,130,246,0.03), rgba(139,92,246,0.03))"},children:[c.jsxs("div",{className:"mb-4",children:[c.jsx("h2",{className:"font-semibold",children:"Risk Presets"}),c.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:"One-click profiles optimized for $50 bankroll / 30-day experiment"})]}),c.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:Object.entries(up).map(([v,b])=>{const S=x===v;return c.jsxs("button",{onClick:()=>u(v),disabled:i===v,className:`text-left rounded-xl border p-4 transition-all ${S?`border-${b.color}-500/50 bg-${b.color}-500/10`:"border-gray-800 hover:border-gray-700 bg-gray-800/20 hover:bg-gray-800/40"} ${i===v?"opacity-50":""}`,children:[c.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[c.jsx("div",{className:`w-10 h-10 rounded-lg flex items-center justify-center bg-${b.color}-500/15`,children:c.jsx("svg",{className:`w-5 h-5 text-${b.color}-400`,fill:"none",stroke:"currentColor",strokeWidth:"1.5",viewBox:"0 0 24 24",children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:b.icon})})}),c.jsxs("div",{children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("p",{className:"font-semibold",children:b.label}),S&&c.jsx("span",{className:`badge bg-${b.color}`,children:"Active"})]}),c.jsx("p",{className:"text-xs text-gray-500",children:b.desc})]})]}),c.jsxs("div",{className:"space-y-1.5 text-xs",children:[c.jsxs("div",{className:"flex justify-between",children:[c.jsx("span",{className:"text-gray-500",children:"Max Bet"}),c.jsxs("span",{className:"font-mono",children:["$",b.config.max_bet_usd]})]}),c.jsxs("div",{className:"flex justify-between",children:[c.jsx("span",{className:"text-gray-500",children:"Kelly Fraction"}),c.jsxs("span",{className:"font-mono",children:[b.config.fractional_kelly,"x"]})]}),c.jsxs("div",{className:"flex justify-between",children:[c.jsx("span",{className:"text-gray-500",children:"Max Exposure"}),c.jsxs("span",{className:"font-mono",children:["$",b.config.max_open_exposure_usd]})]}),c.jsxs("div",{className:"flex justify-between",children:[c.jsx("span",{className:"text-gray-500",children:"Min Edge"}),c.jsxs("span",{className:"font-mono",children:[b.config.min_edge_threshold*100,"%"]})]}),c.jsxs("div",{className:"flex justify-between",children:[c.jsx("span",{className:"text-gray-500",children:"Max Drawdown"}),c.jsxs("span",{className:"font-mono",children:[b.config.max_drawdown_pct,"%"]})]})]}),c.jsxs("div",{className:"mt-3 pt-3 border-t border-gray-800",children:[c.jsx("p",{className:"text-[10px] text-gray-500",children:b.kelly_note}),c.jsx("p",{className:"text-[10px] text-gray-400 mt-0.5",children:b.survival})]})]},v)})})]}),c.jsxs("div",{className:"card",children:[c.jsx("h2",{className:"font-semibold mb-4",children:"Risk Configuration"}),c.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[{k:"paper_mode",l:"Paper Mode",t:"toggle",desc:"No real orders"},{k:"max_bet_usd",l:"Max Bet ($)",t:"num",s:.05},{k:"max_daily_loss_usd",l:"Max Daily Loss ($)",t:"num",s:.5},{k:"max_open_exposure_usd",l:"Max Exposure ($)",t:"num",s:.5},{k:"max_drawdown_pct",l:"Max Drawdown (%)",t:"num",s:1},{k:"min_edge_threshold",l:"Min Edge",t:"num",s:.005},{k:"min_liquidity",l:"Min Liquidity ($)",t:"num",s:10},{k:"fractional_kelly",l:"Kelly Fraction",t:"num",s:.05}].map(v=>c.jsxs("div",{className:"flex items-center justify-between bg-gray-800/30 rounded-lg p-3",children:[c.jsxs("div",{children:[c.jsx("p",{className:"text-sm font-medium",children:v.l}),v.desc&&c.jsx("p",{className:"text-xs text-gray-500",children:v.desc})]}),v.t==="toggle"?c.jsx("button",{onClick:()=>l(v.k,!f[v.k]),className:`w-12 h-6 rounded-full relative ${f[v.k]?"bg-green-500":"bg-gray-600"}`,children:c.jsx("span",{className:`absolute top-0.5 w-5 h-5 bg-white rounded-full transition-transform ${f[v.k]?"left-6":"left-0.5"}`})}):c.jsx("input",{type:"number",step:v.s,value:f[v.k]??"",onChange:b=>l(v.k,parseFloat(b.target.value)),className:"w-24 bg-gray-800 border border-gray-700 rounded px-2 py-1 text-sm text-right font-mono"})]},v.k))})]}),c.jsxs("div",{className:"card",children:[c.jsx("h2",{className:"font-semibold mb-3",children:"Kelly Bet Calculator"}),c.jsx("p",{className:"text-xs text-gray-500 mb-4",children:"Suggested bet sizes for current config with $50 bankroll"}),c.jsx("div",{className:"grid grid-cols-3 md:grid-cols-5 gap-3",children:[.02,.03,.05,.08,.1].map(v=>{const b=f.fractional_kelly||.1,S=v/(1-v),w=Math.min(f.max_bet_usd||.5,d*b*S);return c.jsxs("div",{className:"bg-gray-800/30 rounded-lg p-3 text-center",children:[c.jsxs("p",{className:"text-xs text-gray-500 mb-1",children:[(v*100).toFixed(0),"% edge"]}),c.jsxs("p",{className:`font-mono font-semibold ${w>0?"text-green-400":"text-gray-500"}`,children:["$",w.toFixed(2)]}),c.jsxs("p",{className:"text-[10px] text-gray-600 mt-0.5",children:["of $",d.toFixed(0)]})]},v)})})]})]})}const dw=({active:e,payload:t,label:r,prefix:n="$"})=>!e||!(t!=null&&t.length)?null:c.jsxs("div",{className:"bg-gray-900 border border-gray-700 rounded-lg px-3 py-2 text-xs shadow-xl",children:[c.jsx("p",{className:"text-gray-400 mb-1",children:r}),t.map((i,a)=>c.jsxs("p",{style:{color:i.color},className:"font-mono",children:[i.name,": ",n,typeof i.value=="number"?i.value.toFixed(2):i.value]},a))]});function GZ(){const[e,t]=k.useState([]),[r,n]=k.useState([]),[i,a]=k.useState(!0);if(k.useEffect(()=>{tt("/trades").then(h=>{t(h.orders||[]),n(h.trades||[]),a(!1)});const p=setInterval(()=>tt("/trades").then(h=>{t(h.orders||[]),n(h.trades||[])}),15e3);return()=>clearInterval(p)},[]),i)return c.jsx("div",{className:"flex items-center justify-center h-64",children:c.jsx("div",{className:"animate-spin w-8 h-8 border-2 border-blue-500 border-t-transparent rounded-full"})});const o=r.reduce((p,h)=>p+parseFloat(h.pnl||0),0);r.reduce((p,h)=>p+parseFloat(h.fee_usd||0),0);const s=r.length>0?r.filter(p=>parseFloat(p.pnl||0)>0).length/r.length*100:0,l=r.length>0?r.reduce((p,h)=>p+parseFloat(h.size_usd||0),0)/r.length:0,u=r.slice().reverse().map((p,h)=>({idx:h+1,time:new Date(p.match_time).toLocaleDateString("en-US",{month:"short",day:"numeric"}),pnl:parseFloat(p.pnl||0),size:parseFloat(p.size_usd||0)}));let f=0;const d=u.map(p=>(f+=p.pnl,{...p,cumPnl:f}));return c.jsxs("div",{className:"space-y-6",children:[c.jsxs("div",{children:[c.jsx("h1",{className:"text-2xl font-bold",children:"Trades & Orders"}),c.jsx("p",{className:"text-gray-500 text-sm",children:"Execution history & analysis"})]}),c.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-4",children:[c.jsxs("div",{className:"card",children:[c.jsx("p",{className:"text-xs text-gray-500 uppercase mb-1",children:"Orders"}),c.jsx("p",{className:"stat-v text-blue-400",children:e.length})]}),c.jsxs("div",{className:"card",children:[c.jsx("p",{className:"text-xs text-gray-500 uppercase mb-1",children:"Fills"}),c.jsx("p",{className:"stat-v text-green-400",children:r.length})]}),c.jsxs("div",{className:"card",children:[c.jsx("p",{className:"text-xs text-gray-500 uppercase mb-1",children:"P&L"}),c.jsxs("p",{className:`stat-v ${o>=0?"text-green-400":"text-red-400"}`,children:["$",o.toFixed(2)]})]}),c.jsxs("div",{className:"card",children:[c.jsx("p",{className:"text-xs text-gray-500 uppercase mb-1",children:"Win Rate"}),c.jsxs("p",{className:"stat-v text-purple-400",children:[s.toFixed(0),"%"]})]}),c.jsxs("div",{className:"card",children:[c.jsx("p",{className:"text-xs text-gray-500 uppercase mb-1",children:"Avg Size"}),c.jsxs("p",{className:"stat-v text-yellow-400",children:["$",l.toFixed(2)]})]})]}),r.length>0&&c.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:[c.jsxs("div",{className:"card",children:[c.jsx("h2",{className:"font-semibold mb-3",children:"P&L Per Trade"}),c.jsx(pt,{width:"100%",height:220,children:c.jsxs(zn,{data:u,barSize:16,children:[c.jsx(ht,{strokeDasharray:"3 3",stroke:"#1f2937"}),c.jsx(Re,{dataKey:"time",tick:{fill:"#6b7280",fontSize:10},axisLine:!1,tickLine:!1}),c.jsx(Be,{tick:{fill:"#6b7280",fontSize:11},axisLine:!1,tickLine:!1,tickFormatter:p=>`$${p}`}),c.jsx(Se,{content:c.jsx(dw,{})}),c.jsx(Tt,{dataKey:"pnl",name:"P&L",children:u.map((p,h)=>c.jsx(jr,{fill:p.pnl>=0?"#10b981":"#ef4444",fillOpacity:.8},h))})]})})]}),c.jsxs("div",{className:"card",children:[c.jsx("h2",{className:"font-semibold mb-3",children:"Cumulative P&L"}),c.jsx(pt,{width:"100%",height:220,children:c.jsxs(Gc,{data:d,children:[c.jsx("defs",{children:c.jsxs("linearGradient",{id:"cumTrade",x1:"0",y1:"0",x2:"0",y2:"1",children:[c.jsx("stop",{offset:"5%",stopColor:f>=0?"#10b981":"#ef4444",stopOpacity:.3}),c.jsx("stop",{offset:"95%",stopColor:f>=0?"#10b981":"#ef4444",stopOpacity:0})]})}),c.jsx(ht,{strokeDasharray:"3 3",stroke:"#1f2937"}),c.jsx(Re,{dataKey:"time",tick:{fill:"#6b7280",fontSize:10},axisLine:!1,tickLine:!1}),c.jsx(Be,{tick:{fill:"#6b7280",fontSize:11},axisLine:!1,tickLine:!1,tickFormatter:p=>`$${p}`}),c.jsx(Se,{content:c.jsx(dw,{})}),c.jsx(Sr,{type:"monotone",dataKey:"cumPnl",stroke:f>=0?"#10b981":"#ef4444",strokeWidth:2,fill:"url(#cumTrade)",name:"Cumulative P&L"})]})})]})]}),c.jsxs("div",{className:"card overflow-x-auto",children:[c.jsx("h2",{className:"font-semibold mb-3",children:"Orders"}),c.jsxs("table",{children:[c.jsx("thead",{children:c.jsxs("tr",{children:[c.jsx("th",{children:"ID"}),c.jsx("th",{children:"Side"}),c.jsx("th",{children:"Outcome"}),c.jsx("th",{children:"Price"}),c.jsx("th",{children:"Size"}),c.jsx("th",{children:"Status"}),c.jsx("th",{children:"Paper"}),c.jsx("th",{children:"Time"})]})}),c.jsx("tbody",{children:e.length===0?c.jsx("tr",{children:c.jsx("td",{colSpan:8,className:"text-center text-gray-500 py-8",children:"No orders yet"})}):e.map(p=>{var h;return c.jsxs("tr",{children:[c.jsx("td",{className:"font-mono text-xs",children:p.order_id.substring(0,12)}),c.jsx("td",{children:c.jsx("span",{className:`badge ${p.side==="buy"?"bg-green":"bg-red"}`,children:(h=p.side)==null?void 0:h.toUpperCase()})}),c.jsx("td",{children:p.outcome}),c.jsxs("td",{className:"font-mono",children:["$",parseFloat(p.price).toFixed(4)]}),c.jsxs("td",{className:"font-mono",children:["$",parseFloat(p.size_usd||0).toFixed(2)]}),c.jsx("td",{children:c.jsx("span",{className:`badge ${p.status==="filled"?"bg-green":p.status==="rejected"?"bg-red":"bg-yellow"}`,children:p.status})}),c.jsx("td",{children:p.paper_trade?c.jsx("span",{className:"badge bg-yellow",children:"PAPER"}):c.jsx("span",{className:"badge bg-green",children:"LIVE"})}),c.jsx("td",{className:"text-gray-400 text-sm",children:new Date(p.submitted_ts).toLocaleString()})]},p.order_id)})})]})]}),r.length>0&&c.jsxs("div",{className:"card overflow-x-auto",children:[c.jsx("h2",{className:"font-semibold mb-3",children:"Trade Fills"}),c.jsxs("table",{children:[c.jsx("thead",{children:c.jsxs("tr",{children:[c.jsx("th",{children:"Time"}),c.jsx("th",{children:"Size"}),c.jsx("th",{children:"Price"}),c.jsx("th",{children:"Fee"}),c.jsx("th",{children:"P&L"})]})}),c.jsx("tbody",{children:r.map((p,h)=>c.jsxs("tr",{children:[c.jsx("td",{className:"text-gray-400 text-sm",children:p.match_time?new Date(p.match_time).toLocaleString():"-"}),c.jsxs("td",{className:"font-mono",children:["$",parseFloat(p.size_usd||0).toFixed(2)]}),c.jsxs("td",{className:"font-mono",children:["$",parseFloat(p.fill_price||0).toFixed(4)]}),c.jsxs("td",{className:"font-mono text-yellow-400",children:["$",parseFloat(p.fee_usd||0).toFixed(4)]}),c.jsxs("td",{className:`font-mono ${parseFloat(p.pnl||0)>=0?"text-green-400":"text-red-400"}`,children:["$",parseFloat(p.pnl||0).toFixed(2)]})]},h))})]})]})]})}const cp=({active:e,payload:t,label:r,prefix:n="$"})=>!e||!(t!=null&&t.length)?null:c.jsxs("div",{className:"bg-gray-900 border border-gray-700 rounded-lg px-3 py-2 text-xs shadow-xl",children:[c.jsx("p",{className:"text-gray-400 mb-1",children:r}),t.map((i,a)=>c.jsxs("p",{style:{color:i.color},className:"font-mono",children:[i.name,": ",n,typeof i.value=="number"?i.value.toFixed(2):i.value]},a))]});function YZ(){const[e,t]=k.useState([]),[r,n]=k.useState({}),[i,a]=k.useState(!0);if(k.useEffect(()=>{tt("/bankroll").then(m=>{t(m.ledger||[]),n(m.summary||{}),a(!1)})},[]),i)return c.jsx("div",{className:"flex items-center justify-center h-64",children:c.jsx("div",{className:"animate-spin w-8 h-8 border-2 border-blue-500 border-t-transparent rounded-full"})});const o={deposit:"bg-green",withdrawal:"bg-red",trade_pnl:"bg-blue",fee:"bg-yellow",adjustment:"bg-purple"},s=e.slice().reverse().map((m,g)=>({idx:g,time:new Date(m.ts).toLocaleDateString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),balance:parseFloat(m.balance_after||0),amount:parseFloat(m.amount||0),event:m.event_type})),l=e.slice().reverse().filter(m=>m.event_type==="trade_pnl"||m.event_type==="fee").map((m,g)=>({idx:g,time:new Date(m.ts).toLocaleDateString("en-US",{month:"short",day:"numeric"}),pnl:parseFloat(m.amount||0),event:m.event_type}));let u=0;const f=l.map(m=>(u+=m.pnl,{...m,cumPnl:u})),d={};e.forEach(m=>{d[m.event_type]=(d[m.event_type]||0)+1}),Object.entries(d).map(([m,g])=>({name:m,count:g}));const p=parseFloat(r.current_balance||50),h=(p-50)/50*100;return c.jsxs("div",{className:"space-y-6",children:[c.jsxs("div",{children:[c.jsx("h1",{className:"text-2xl font-bold",children:"Bankroll"}),c.jsx("p",{className:"text-gray-500 text-sm",children:"Balance tracking and P&L analysis"})]}),c.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-4",children:[c.jsxs("div",{className:"card",children:[c.jsx("p",{className:"text-xs text-gray-500 uppercase mb-1",children:"Balance"}),c.jsxs("p",{className:"stat-v text-green-400",children:["$",p.toFixed(2)]})]}),c.jsxs("div",{className:"card",children:[c.jsx("p",{className:"text-xs text-gray-500 uppercase mb-1",children:"Deposits"}),c.jsxs("p",{className:"stat-v text-blue-400",children:["$",parseFloat(r.total_deposits||50).toFixed(2)]})]}),c.jsxs("div",{className:"card",children:[c.jsx("p",{className:"text-xs text-gray-500 uppercase mb-1",children:"Total P&L"}),c.jsxs("p",{className:`stat-v ${parseFloat(r.total_pnl||0)>=0?"text-green-400":"text-red-400"}`,children:["$",parseFloat(r.total_pnl||0).toFixed(2)]})]}),c.jsxs("div",{className:"card",children:[c.jsx("p",{className:"text-xs text-gray-500 uppercase mb-1",children:"Fees"}),c.jsxs("p",{className:"stat-v text-yellow-400",children:["$",parseFloat(r.total_fees||0).toFixed(2)]})]}),c.jsxs("div",{className:"card",children:[c.jsx("p",{className:"text-xs text-gray-500 uppercase mb-1",children:"ROI"}),c.jsxs("p",{className:`stat-v ${h>=0?"text-green-400":"text-red-400"}`,children:[h>=0?"+":"",h.toFixed(1),"%"]})]})]}),c.jsxs("div",{className:"card",children:[c.jsx("h2",{className:"font-semibold mb-3",children:"Balance History"}),s.length>1?c.jsx(pt,{width:"100%",height:280,children:c.jsxs(Gc,{data:s,children:[c.jsx("defs",{children:c.jsxs("linearGradient",{id:"balGrad",x1:"0",y1:"0",x2:"0",y2:"1",children:[c.jsx("stop",{offset:"5%",stopColor:"#10b981",stopOpacity:.3}),c.jsx("stop",{offset:"95%",stopColor:"#10b981",stopOpacity:0})]})}),c.jsx(ht,{strokeDasharray:"3 3",stroke:"#1f2937"}),c.jsx(Re,{dataKey:"time",tick:{fill:"#6b7280",fontSize:10},axisLine:!1,tickLine:!1,interval:"preserveStartEnd"}),c.jsx(Be,{tick:{fill:"#6b7280",fontSize:11},axisLine:!1,tickLine:!1,domain:["dataMin - 1","dataMax + 1"],tickFormatter:m=>`$${m}`}),c.jsx(Se,{content:c.jsx(cp,{})}),c.jsx(Sr,{type:"monotone",dataKey:"balance",stroke:"#10b981",strokeWidth:2,fill:"url(#balGrad)",name:"Balance",dot:!1})]})}):c.jsx("p",{className:"text-gray-500 text-sm text-center py-12",children:"Chart appears after multiple entries"})]}),c.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:[c.jsxs("div",{className:"card",children:[c.jsx("h2",{className:"font-semibold mb-3",children:"P&L Events"}),l.length>0?c.jsx(pt,{width:"100%",height:220,children:c.jsxs(zn,{data:l,barSize:16,children:[c.jsx(ht,{strokeDasharray:"3 3",stroke:"#1f2937"}),c.jsx(Re,{dataKey:"time",tick:{fill:"#6b7280",fontSize:10},axisLine:!1,tickLine:!1}),c.jsx(Be,{tick:{fill:"#6b7280",fontSize:11},axisLine:!1,tickLine:!1,tickFormatter:m=>`$${m}`}),c.jsx(Se,{content:c.jsx(cp,{})}),c.jsx(Tt,{dataKey:"pnl",name:"P&L",children:l.map((m,g)=>c.jsx(jr,{fill:m.pnl>=0?"#10b981":"#ef4444",fillOpacity:.8},g))})]})}):c.jsx("p",{className:"text-gray-500 text-sm text-center py-12",children:"No P&L events yet"})]}),c.jsxs("div",{className:"card",children:[c.jsx("h2",{className:"font-semibold mb-3",children:"Cumulative P&L"}),f.length>0?c.jsx(pt,{width:"100%",height:220,children:c.jsxs(Gc,{data:f,children:[c.jsx("defs",{children:c.jsxs("linearGradient",{id:"cumGrad",x1:"0",y1:"0",x2:"0",y2:"1",children:[c.jsx("stop",{offset:"5%",stopColor:u>=0?"#10b981":"#ef4444",stopOpacity:.3}),c.jsx("stop",{offset:"95%",stopColor:u>=0?"#10b981":"#ef4444",stopOpacity:0})]})}),c.jsx(ht,{strokeDasharray:"3 3",stroke:"#1f2937"}),c.jsx(Re,{dataKey:"time",tick:{fill:"#6b7280",fontSize:10},axisLine:!1,tickLine:!1}),c.jsx(Be,{tick:{fill:"#6b7280",fontSize:11},axisLine:!1,tickLine:!1,tickFormatter:m=>`$${m}`}),c.jsx(Se,{content:c.jsx(cp,{})}),c.jsx(Sr,{type:"monotone",dataKey:"cumPnl",stroke:u>=0?"#10b981":"#ef4444",strokeWidth:2,fill:"url(#cumGrad)",name:"Cumulative P&L"})]})}):c.jsx("p",{className:"text-gray-500 text-sm text-center py-12",children:"No P&L events yet"})]})]}),c.jsxs("div",{className:"card overflow-x-auto",children:[c.jsx("h2",{className:"font-semibold mb-3",children:"Ledger Entries"}),c.jsxs("table",{children:[c.jsx("thead",{children:c.jsxs("tr",{children:[c.jsx("th",{children:"Time"}),c.jsx("th",{children:"Event"}),c.jsx("th",{children:"Amount"}),c.jsx("th",{children:"Balance"}),c.jsx("th",{children:"Note"})]})}),c.jsx("tbody",{children:e.map((m,g)=>c.jsxs("tr",{children:[c.jsx("td",{className:"text-gray-400 text-sm",children:new Date(m.ts).toLocaleString()}),c.jsx("td",{children:c.jsx("span",{className:`badge ${o[m.event_type]||"bg-blue"}`,children:m.event_type})}),c.jsxs("td",{className:`font-mono ${parseFloat(m.amount)>=0?"text-green-400":"text-red-400"}`,children:[parseFloat(m.amount)>=0?"+":"","$",parseFloat(m.amount).toFixed(2)]}),c.jsxs("td",{className:"font-mono font-medium",children:["$",parseFloat(m.balance_after).toFixed(2)]}),c.jsx("td",{className:"text-gray-400 text-sm max-w-[200px] truncate",children:m.note||"-"})]},g))})]})]})]})}function qZ(){const[e,t]=k.useState(null),[r,n]=k.useState(""),[i,a]=k.useState(""),[o,s]=k.useState(""),[l,u]=k.useState(""),[f,d]=k.useState(!1),[p,h]=k.useState(null),[m,g]=k.useState(null),[x,y]=k.useState(""),[v,b]=k.useState(null),[S,w]=k.useState({});k.useEffect(()=>{tt("/health").then(t),j()},[]);async function j(){h("checking");try{const C=await ie("/polymarket",{action:"status"});g(C),h(C.connected?"connected":"disconnected")}catch{h("disconnected")}}async function O(){b("testing");try{const C=await ie("/polymarket",{action:"test_public"});b(C.success?"ok":"error"),C.success&&y(`CLOB OK — Server time: ${C.server_time}`)}catch{b("error")}}async function _(){if(!(!r||!i||!o)){h("saving"),y("");try{const C=await ie("/polymarket",{action:"save_keys",api_key:r,secret:i,passphrase:o,wallet:l||null});C.success?(h("connected"),g({api_key:C.api_key,wallet:l,connected_at:new Date().toISOString(),connected:!0}),y('Credentials saved! Use "Test Auth" to verify.'),n(""),a(""),s("")):(h("error"),y(C.error||"Failed to save"))}catch(C){h("error"),y("Error: "+C.message)}}}async function P(){y("Testing authenticated connection...");try{const C=await ie("/polymarket",{action:"auth_test"});C.success?(y(`${C.message} | ${C.trades??0} trades found`),h("connected")):y(C.error||"Auth test failed")}catch(C){y("Error: "+C.message)}}async function N(){try{await ie("/polymarket",{action:"disconnect"}),h("disconnected"),g(null),y("Disconnected")}catch{y("Error disconnecting")}}async function T(C,F){w(M=>({...M,[C]:"testing"}));try{const M=await F();w(B=>({...B,[C]:M.success||M.sent?"ok":"error"}))}catch{w(M=>({...M,[C]:"error"}))}}async function $(){await T("nws",()=>ie("/weather",{action:"test_nws"}))}async function I(){await T("slack",()=>ie("/alerts",{action:"test"}))}async function D(C){const F=await ie("/workers",{action:"run",worker:C});w(M=>({...M,[C]:F.message?"ok":"error"}))}const L=C=>C===!0||C==="ok"||C==="connected"?"bg-green-500":C==="testing"||C==="checking"||C==="saving"?"bg-yellow-500 animate-pulse":C==="error"?"bg-red-500":"bg-gray-600";return c.jsxs("div",{className:"space-y-6",children:[c.jsxs("div",{children:[c.jsx("h1",{className:"text-2xl font-bold",children:"Settings"}),c.jsx("p",{className:"text-gray-500 text-sm",children:"System config & Polymarket login"})]}),c.jsxs("div",{className:"card border border-purple-500/20",style:{background:"linear-gradient(135deg, rgba(139,92,246,0.08), rgba(59,130,246,0.04))"},children:[c.jsxs("div",{className:"flex items-center gap-3 mb-5",children:[c.jsx("div",{className:"w-12 h-12 rounded-xl flex items-center justify-center bg-purple-500/20",children:c.jsx("svg",{className:"w-6 h-6 text-purple-400",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M21 12a9 9 0 01-9 9m9-9a9 9 0 00-9-9m9 9H3m9 9a9 9 0 01-9-9m9 9c1.657 0 3-4.03 3-9s-1.343-9-3-9m0 18c-1.657 0-3-4.03-3-9s1.343-9 3-9"})})}),c.jsxs("div",{className:"flex-1",children:[c.jsx("h2",{className:"text-lg font-bold",children:"Polymarket CLOB Login"}),c.jsx("p",{className:"text-xs text-gray-500",children:"Connect with your Builder API keys for live trading on Polygon"})]}),c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:`w-2.5 h-2.5 rounded-full ${L(p)}`}),c.jsx("span",{className:`text-sm font-medium ${p==="connected"?"text-green-400":p==="error"?"text-red-400":"text-gray-500"}`,children:p==="connected"?"Connected":p==="saving"?"Saving...":p==="checking"?"Checking...":p==="error"?"Error":"Not Connected"})]})]}),p==="connected"&&m&&c.jsxs("div",{className:"bg-green-500/10 border border-green-500/20 rounded-lg p-4 mb-4",children:[c.jsxs("div",{className:"grid grid-cols-3 gap-4 text-sm",children:[c.jsxs("div",{children:[c.jsx("span",{className:"text-gray-500 text-xs block mb-0.5",children:"API Key"}),c.jsx("span",{className:"font-mono text-green-400",children:m.api_key||"—"})]}),c.jsxs("div",{children:[c.jsx("span",{className:"text-gray-500 text-xs block mb-0.5",children:"Wallet"}),c.jsx("span",{className:"font-mono text-green-400",children:m.wallet?`${m.wallet.substring(0,6)}...${m.wallet.slice(-4)}`:"Not set"})]}),c.jsxs("div",{children:[c.jsx("span",{className:"text-gray-500 text-xs block mb-0.5",children:"Connected"}),c.jsx("span",{className:"text-green-400",children:m.connected_at?new Date(m.connected_at).toLocaleDateString():"—"})]})]}),c.jsxs("div",{className:"flex gap-3 mt-3",children:[c.jsx("button",{onClick:P,className:"btn btn-s text-xs",children:"Test Auth"}),c.jsx("button",{onClick:O,className:`btn btn-s text-xs ${v==="ok"?"text-green-400 border-green-500/30":""}`,children:v==="testing"?"...":v==="ok"?"CLOB OK":"Test CLOB"}),c.jsx("button",{onClick:N,className:"btn text-xs text-red-400 hover:text-red-300 border border-red-500/30 hover:border-red-500/50",children:"Disconnect"})]})]}),p!=="connected"&&c.jsxs("div",{className:"space-y-3",children:[c.jsxs("div",{className:"bg-gray-800/40 rounded-lg p-4",children:[c.jsxs("p",{className:"text-xs text-gray-400 mb-3",children:["Get your Builder API keys from"," ",c.jsx("span",{className:"text-purple-400 font-mono",children:"polymarket.com/settings"})," ","→ Builder tab → Create New"]}),c.jsxs("div",{className:"space-y-2.5",children:[c.jsxs("div",{children:[c.jsx("label",{className:"text-[11px] text-gray-500 mb-1 block",children:"API Key"}),c.jsx("input",{type:"text",value:r,onChange:C=>n(C.target.value),placeholder:"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",className:"w-full bg-gray-900 border border-gray-700 rounded-lg px-3 py-2 text-sm font-mono focus:outline-none focus:border-purple-500 transition"})]}),c.jsxs("div",{children:[c.jsx("label",{className:"text-[11px] text-gray-500 mb-1 block",children:"API Secret"}),c.jsxs("div",{className:"relative",children:[c.jsx("input",{type:f?"text":"password",value:i,onChange:C=>a(C.target.value),placeholder:"Base64 encoded secret",className:"w-full bg-gray-900 border border-gray-700 rounded-lg px-3 py-2 pr-10 text-sm font-mono focus:outline-none focus:border-purple-500 transition"}),c.jsx("button",{type:"button",onClick:()=>d(!f),className:"absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-300",children:c.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:f?"M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.878 9.878L3 3m6.878 6.879L21 21":"M15 12a3 3 0 11-6 0 3 3 0 016 0z M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"})})})]})]}),c.jsxs("div",{children:[c.jsx("label",{className:"text-[11px] text-gray-500 mb-1 block",children:"Passphrase"}),c.jsx("input",{type:"password",value:o,onChange:C=>s(C.target.value),placeholder:"Passphrase",className:"w-full bg-gray-900 border border-gray-700 rounded-lg px-3 py-2 text-sm font-mono focus:outline-none focus:border-purple-500 transition"})]}),c.jsxs("div",{children:[c.jsxs("label",{className:"text-[11px] text-gray-500 mb-1 block",children:["Wallet Address ",c.jsx("span",{className:"text-gray-600",children:"(optional)"})]}),c.jsx("input",{type:"text",value:l,onChange:C=>u(C.target.value),placeholder:"0x...",className:"w-full bg-gray-900 border border-gray-700 rounded-lg px-3 py-2 text-sm font-mono focus:outline-none focus:border-purple-500 transition"})]})]})]}),c.jsxs("div",{className:"flex gap-3",children:[c.jsxs("button",{onClick:_,disabled:!r||!i||!o||p==="saving",className:"btn btn-p flex items-center gap-2 disabled:opacity-50",children:[p==="saving"&&c.jsx("span",{className:"animate-spin w-4 h-4 border-2 border-white border-t-transparent rounded-full"}),p==="saving"?"Saving...":"Connect"]}),c.jsx("button",{onClick:O,className:`btn btn-s ${v==="ok"?"text-green-400 border-green-500/30":""}`,children:v==="testing"?"...":v==="ok"?"CLOB Reachable":"Test CLOB"})]})]}),x&&c.jsx("div",{className:`mt-3 text-sm p-3 rounded-lg ${x.toLowerCase().includes("error")||x.toLowerCase().includes("fail")?"bg-red-500/10 text-red-400":"bg-green-500/10 text-green-400"}`,children:x}),c.jsxs("div",{className:"mt-5 pt-4 border-t border-gray-800/50",children:[c.jsx("p",{className:"text-xs text-gray-500 mb-3 font-medium uppercase tracking-wider",children:"API Endpoints"}),c.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2 text-xs",children:[{tag:"CLOB",color:"purple",host:"clob.polymarket.com",desc:"Orders & trading"},{tag:"GAMMA",color:"blue",host:"gamma-api.polymarket.com",desc:"Market metadata"},{tag:"DATA",color:"green",host:"data-api.polymarket.com",desc:"User positions"},{tag:"WS",color:"yellow",host:"ws-subscriptions-clob...",desc:"Live orderbook"}].map(C=>c.jsxs("div",{className:"bg-gray-800/30 rounded-lg p-2.5",children:[c.jsx("span",{className:`inline-block px-1.5 py-0.5 rounded bg-${C.color}-500/20 text-${C.color}-400 font-mono text-[10px] mb-1`,children:C.tag}),c.jsx("p",{className:"text-gray-400 font-mono text-[11px]",children:C.host}),c.jsx("p",{className:"text-gray-600 mt-0.5",children:C.desc})]},C.tag))}),c.jsxs("div",{className:"mt-3 text-[11px] text-gray-600",children:[c.jsx("span",{className:"text-gray-500",children:"Auth:"})," L2 HMAC-SHA256 — API Key + Secret + Passphrase per request"]})]})]}),c.jsxs("div",{className:"card",children:[c.jsx("h2",{className:"font-semibold mb-3",children:"System Status"}),c.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[{l:"Database",s:e==null?void 0:e.db_connected,d:"PostgreSQL poly_betting"},{l:"NWS API",s:S.nws||"unknown",d:"api.weather.gov"},{l:"Polymarket",s:p==="connected"?!0:v||"unknown",d:"clob.polymarket.com"},{l:"Slack",s:e!=null&&e.slack_configured?"ok":S.slack||"no_token",d:"Alerts channel"}].map(C=>c.jsxs("div",{className:"bg-gray-800/30 rounded-lg p-3",children:[c.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[c.jsx("span",{className:`w-2 h-2 rounded-full ${L(C.s)}`}),c.jsx("span",{className:"text-sm font-medium",children:C.l})]}),c.jsx("p",{className:"text-xs text-gray-500",children:C.d})]},C.l))})]}),c.jsxs("div",{className:"card",children:[c.jsx("h2",{className:"font-semibold mb-3",children:"Connectivity Tests"}),c.jsxs("div",{className:"flex gap-3",children:[c.jsx("button",{onClick:$,className:`btn ${S.nws==="ok"?"btn-s":"btn-p"}`,children:S.nws==="testing"?"...":S.nws==="ok"?"NWS OK":"Test NWS"}),c.jsx("button",{onClick:O,className:`btn ${v==="ok"?"btn-s":"btn-p"}`,children:v==="testing"?"...":v==="ok"?"CLOB OK":"Test CLOB"}),c.jsx("button",{onClick:I,className:`btn ${S.slack==="ok"?"btn-s":"btn-p"}`,children:S.slack==="testing"?"...":S.slack==="ok"?"Slack OK":"Test Slack"})]})]}),c.jsxs("div",{className:"card",children:[c.jsx("h2",{className:"font-semibold mb-3",children:"Manual Workers"}),c.jsx("div",{className:"flex flex-wrap gap-3",children:[{w:"market_ingest",l:"Ingest Markets"},{w:"weather_fetch",l:"Fetch Weather"},{w:"run_predictions",l:"Run Predictions"},{w:"risk_scan",l:"Risk Scan"},{w:"paper_trade",l:"Paper Trade"}].map(({w:C,l:F})=>c.jsx("button",{onClick:()=>D(C),className:`btn ${S[C]==="ok"?"btn-s":"btn-p"}`,children:S[C]==="ok"?`${F} Done`:F},C))})]}),c.jsxs("div",{className:"card",children:[c.jsx("h2",{className:"font-semibold mb-3",children:"Architecture"}),c.jsxs("div",{className:"grid grid-cols-2 gap-4 text-sm",children:[c.jsxs("div",{children:[c.jsx("p",{className:"text-gray-500 text-xs uppercase mb-2",children:"Data Sources"}),c.jsxs("ul",{className:"space-y-1",children:[c.jsxs("li",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"badge bg-blue",children:"NWS"}),"Live US forecasts"]}),c.jsxs("li",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"badge bg-purple",children:"GEFS"}),"Ensembles"]}),c.jsxs("li",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"badge bg-green",children:"Gamma"}),"Polymarket"]}),c.jsxs("li",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"badge bg-yellow",children:"CLOB"}),"Orderbooks"]})]})]}),c.jsxs("div",{children:[c.jsx("p",{className:"text-gray-500 text-xs uppercase mb-2",children:"Pipeline"}),c.jsxs("ol",{className:"space-y-1 list-decimal list-inside text-gray-300",children:[c.jsx("li",{children:"Market parse + event extraction"}),c.jsx("li",{children:"Ensemble exceedance probability"}),c.jsx("li",{children:"Climatological prior"}),c.jsx("li",{children:"Bayesian calibration"}),c.jsx("li",{children:"Edge gate + risk sizing"}),c.jsx("li",{children:"Paper/live execution"})]})]})]})]})]})}function XZ(){const[e,t]=k.useState(null),[r,n]=k.useState(null),[i,a]=k.useState([]),[o,s]=k.useState([]),[l,u]=k.useState(null),[f,d]=k.useState(null),[p,h]=k.useState(!0),[m,g]=k.useState(!1),[x,y]=k.useState(!1);k.useEffect(()=>{v()},[]);async function v(){h(!0);try{const[P,N]=await Promise.all([ie("/polymarket",{action:"status"}),tt("/markets")]);t(P),a(N.markets||[])}catch{}h(!1)}async function b(){n("testing");try{const P=await ie("/polymarket",{action:"test_public"});n(P.success?P:{error:!0})}catch{n({error:!0})}}async function S(){g(!0);try{const P=await ie("/polymarket",{action:"get_markets"});P.success&&s(P.tracked_prices||[])}catch{}g(!1)}async function w(P){u(P),y(!0),d(null);try{const N=await ie("/polymarket",{action:"get_orderbook",token_id:P});N.success&&d(N.orderbook)}catch{}y(!1)}const j=P=>P?"bg-green-500":"bg-gray-600",O=[];if(f){const P=(f.bids||[]).slice(0,10).map(T=>({price:parseFloat(T.price),size:parseFloat(T.size),side:"bid"})),N=(f.asks||[]).slice(0,10).map(T=>({price:parseFloat(T.price),size:parseFloat(T.size),side:"ask"}));P.reverse().forEach(T=>O.push(T)),N.forEach(T=>O.push(T))}const _=o.map(P=>({name:(P.question||"").substring(0,30)+"...",price:parseFloat(P.price||0),outcome:P.outcome}));return p?c.jsx("div",{className:"flex items-center justify-center h-64",children:c.jsx("div",{className:"animate-spin w-8 h-8 border-2 border-purple-500 border-t-transparent rounded-full"})}):c.jsxs("div",{className:"space-y-6",children:[c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsxs("div",{children:[c.jsx("h1",{className:"text-2xl font-bold",children:"Polymarket"}),c.jsx("p",{className:"text-gray-500 text-sm",children:"Live CLOB data, orderbooks & market prices"})]}),c.jsxs("div",{className:"flex gap-3",children:[c.jsx("button",{onClick:b,className:`btn btn-s text-sm ${r!=null&&r.ok?"text-green-400 border-green-500/30":""}`,children:r==="testing"?"Testing...":r!=null&&r.ok?"CLOB OK":r!=null&&r.error?"Error":"Test CLOB"}),c.jsx("button",{onClick:S,disabled:m,className:"btn btn-p text-sm",children:m?"Fetching...":"Fetch Live Prices"})]})]}),c.jsx("div",{className:"card",children:c.jsxs("div",{className:"flex items-center gap-6",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:`w-2 h-2 rounded-full ${j(e==null?void 0:e.connected)}`}),c.jsx("span",{className:"text-sm",children:e!=null&&e.connected?"API Connected":"Not Connected"})]}),(e==null?void 0:e.api_key)&&c.jsxs("span",{className:"text-xs text-gray-500 font-mono",children:["Key: ",e.api_key]}),(e==null?void 0:e.wallet)&&c.jsxs("span",{className:"text-xs text-gray-500 font-mono",children:["Wallet: ",e.wallet]}),(r==null?void 0:r.server_time)&&c.jsxs("span",{className:"text-xs text-gray-500",children:["Server: ",new Date(parseInt(r.server_time)*1e3).toLocaleTimeString()]}),c.jsxs("span",{className:"text-xs text-gray-500 ml-auto",children:[i.length," tracked markets"]})]})}),c.jsxs("div",{className:"grid grid-cols-4 gap-4",children:[c.jsxs("div",{className:"card",children:[c.jsx("p",{className:"text-xs text-gray-500 uppercase mb-1",children:"Tracked Markets"}),c.jsx("p",{className:"stat-v text-purple-400",children:i.length})]}),c.jsxs("div",{className:"card",children:[c.jsx("p",{className:"text-xs text-gray-500 uppercase mb-1",children:"Active"}),c.jsx("p",{className:"stat-v text-green-400",children:i.filter(P=>P.active).length})]}),c.jsxs("div",{className:"card",children:[c.jsx("p",{className:"text-xs text-gray-500 uppercase mb-1",children:"Live Prices"}),c.jsx("p",{className:"stat-v text-blue-400",children:o.length})]}),c.jsxs("div",{className:"card",children:[c.jsx("p",{className:"text-xs text-gray-500 uppercase mb-1",children:"API Status"}),c.jsx("p",{className:`stat-v ${e!=null&&e.connected?"text-green-400":"text-gray-500"}`,children:e!=null&&e.connected?"LIVE":"OFF"})]})]}),_.length>0&&c.jsxs("div",{className:"card",children:[c.jsx("h2",{className:"font-semibold mb-3",children:"Live Token Prices"}),c.jsx(pt,{width:"100%",height:250,children:c.jsxs(zn,{data:_,layout:"vertical",children:[c.jsx(ht,{strokeDasharray:"3 3",stroke:"#1f2937"}),c.jsx(Re,{type:"number",domain:[0,1],tickFormatter:P=>`${(P*100).toFixed(0)}%`,stroke:"#6b7280"}),c.jsx(Be,{type:"category",dataKey:"name",width:200,tick:{fontSize:11,fill:"#9ca3af"}}),c.jsx(Se,{formatter:P=>`${(P*100).toFixed(1)}%`,contentStyle:{background:"#1f2937",border:"1px solid #374151",borderRadius:8}}),c.jsx(Tt,{dataKey:"price",radius:[0,4,4,0],children:_.map((P,N)=>c.jsx(jr,{fill:P.outcome==="YES"?"#22c55e":"#ef4444",fillOpacity:.7},N))})]})})]}),c.jsxs("div",{className:"card overflow-x-auto",children:[c.jsxs("div",{className:"flex items-center justify-between mb-3",children:[c.jsx("h2",{className:"font-semibold",children:"Weather Markets"}),c.jsxs("span",{className:"text-xs text-gray-500",children:[i.length," markets"]})]}),c.jsxs("table",{children:[c.jsx("thead",{children:c.jsxs("tr",{children:[c.jsx("th",{children:"Question"}),c.jsx("th",{children:"Category"}),c.jsx("th",{children:"Liquidity"}),c.jsx("th",{children:"End Date"}),c.jsx("th",{children:"Live Price"}),c.jsx("th",{children:"Orderbook"})]})}),c.jsx("tbody",{children:i.length===0?c.jsx("tr",{children:c.jsx("td",{colSpan:6,className:"text-center text-gray-500 py-8",children:"No markets tracked. Go to Markets page to ingest."})}):i.map(P=>{var T,$;const N=o.find(I=>I.condition_id===P.condition_id);return c.jsxs("tr",{children:[c.jsxs("td",{className:"max-w-[300px]",children:[c.jsx("p",{className:"truncate font-medium",children:P.question}),c.jsxs("p",{className:"text-xs text-gray-600 truncate font-mono",children:[(T=P.condition_id)==null?void 0:T.substring(0,12),"..."]})]}),c.jsx("td",{children:c.jsx("span",{className:"badge bg-purple",children:P.category||"weather"})}),c.jsxs("td",{className:"font-mono text-sm",children:["$",parseFloat(P.liquidity||0).toFixed(0)]}),c.jsx("td",{className:"text-gray-400 text-sm",children:P.end_ts?new Date(P.end_ts).toLocaleDateString():"-"}),c.jsx("td",{children:N?c.jsxs("span",{className:"font-mono text-green-400 font-medium",children:[(parseFloat(N.price)*100).toFixed(1),"%"]}):c.jsx("span",{className:"text-gray-600 text-xs",children:"—"})}),c.jsx("td",{children:(($=P.tokens)==null?void 0:$.length)>0||N!=null&&N.token_id?c.jsx("button",{onClick:()=>{var I,D;return w((N==null?void 0:N.token_id)||((D=(I=P.tokens)==null?void 0:I[0])==null?void 0:D.token_id))},className:"text-xs text-purple-400 hover:text-purple-300",children:"View"}):c.jsx("span",{className:"text-gray-600 text-xs",children:"—"})})]},P.condition_id)})})]})]}),(f||x)&&c.jsxs("div",{className:"card",children:[c.jsxs("div",{className:"flex items-center justify-between mb-4",children:[c.jsx("h2",{className:"font-semibold",children:"Orderbook"}),c.jsxs("div",{className:"flex items-center gap-3",children:[c.jsxs("span",{className:"text-xs text-gray-500 font-mono",children:[l==null?void 0:l.substring(0,12),"..."]}),c.jsx("button",{onClick:()=>{d(null),u(null)},className:"text-xs text-gray-500 hover:text-gray-300",children:"Close"})]})]}),x?c.jsx("div",{className:"flex items-center justify-center h-32",children:c.jsx("div",{className:"animate-spin w-6 h-6 border-2 border-purple-500 border-t-transparent rounded-full"})}):f?c.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[c.jsxs("div",{children:[c.jsx("h3",{className:"text-sm font-medium text-green-400 mb-2",children:"Bids (Buy Orders)"}),c.jsxs("div",{className:"space-y-1",children:[c.jsxs("div",{className:"flex justify-between text-[10px] text-gray-500 uppercase px-2",children:[c.jsx("span",{children:"Price"}),c.jsx("span",{children:"Size"})]}),(f.bids||[]).slice(0,12).map((P,N)=>c.jsxs("div",{className:"flex justify-between text-sm px-2 py-1 rounded relative overflow-hidden",children:[c.jsx("div",{className:"absolute inset-0 bg-green-500/10",style:{width:`${Math.min(parseFloat(P.size)*10,100)}%`}}),c.jsx("span",{className:"font-mono text-green-400 relative z-10",children:parseFloat(P.price).toFixed(3)}),c.jsx("span",{className:"font-mono text-gray-400 relative z-10",children:parseFloat(P.size).toFixed(1)})]},N)),(!f.bids||f.bids.length===0)&&c.jsx("p",{className:"text-gray-600 text-xs text-center py-4",children:"No bids"})]})]}),c.jsxs("div",{children:[c.jsx("h3",{className:"text-sm font-medium text-red-400 mb-2",children:"Asks (Sell Orders)"}),c.jsxs("div",{className:"space-y-1",children:[c.jsxs("div",{className:"flex justify-between text-[10px] text-gray-500 uppercase px-2",children:[c.jsx("span",{children:"Price"}),c.jsx("span",{children:"Size"})]}),(f.asks||[]).slice(0,12).map((P,N)=>c.jsxs("div",{className:"flex justify-between text-sm px-2 py-1 rounded relative overflow-hidden",children:[c.jsx("div",{className:"absolute inset-0 bg-red-500/10 right-0",style:{width:`${Math.min(parseFloat(P.size)*10,100)}%`}}),c.jsx("span",{className:"font-mono text-red-400 relative z-10",children:parseFloat(P.price).toFixed(3)}),c.jsx("span",{className:"font-mono text-gray-400 relative z-10",children:parseFloat(P.size).toFixed(1)})]},N)),(!f.asks||f.asks.length===0)&&c.jsx("p",{className:"text-gray-600 text-xs text-center py-4",children:"No asks"})]})]})]}):null,O.length>0&&c.jsxs("div",{className:"mt-4 pt-4 border-t border-gray-800",children:[c.jsx("h3",{className:"text-sm font-medium text-gray-400 mb-2",children:"Depth Chart"}),c.jsx(pt,{width:"100%",height:200,children:c.jsxs(zn,{data:O,children:[c.jsx(ht,{strokeDasharray:"3 3",stroke:"#1f2937"}),c.jsx(Re,{dataKey:"price",tickFormatter:P=>P.toFixed(2),stroke:"#6b7280"}),c.jsx(Be,{stroke:"#6b7280"}),c.jsx(Se,{formatter:P=>P.toFixed(2),contentStyle:{background:"#1f2937",border:"1px solid #374151",borderRadius:8}}),c.jsx(Tt,{dataKey:"size",radius:[4,4,0,0],children:O.map((P,N)=>c.jsx(jr,{fill:P.side==="bid"?"#22c55e":"#ef4444",fillOpacity:.6},N))})]})})]})]}),c.jsxs("div",{className:"card",children:[c.jsx("h2",{className:"font-semibold mb-3",children:"CLOB Quick Reference"}),c.jsxs("div",{className:"grid grid-cols-3 gap-4 text-sm",children:[c.jsxs("div",{children:[c.jsx("p",{className:"text-gray-500 text-xs uppercase mb-2",children:"Public Endpoints"}),c.jsxs("ul",{className:"space-y-1 text-gray-400 text-xs font-mono",children:[c.jsx("li",{children:"/ok — Health check"}),c.jsx("li",{children:"/time — Server time"}),c.jsx("li",{children:"/book?token_id=X — Orderbook"}),c.jsx("li",{children:"/price?token_id=X — Best price"}),c.jsx("li",{children:"/midpoint?token_id=X — Mid price"}),c.jsx("li",{children:"/spread?token_id=X — Bid-ask spread"})]})]}),c.jsxs("div",{children:[c.jsx("p",{className:"text-gray-500 text-xs uppercase mb-2",children:"Auth Endpoints"}),c.jsxs("ul",{className:"space-y-1 text-gray-400 text-xs font-mono",children:[c.jsx("li",{children:"POST /order — Place order"}),c.jsx("li",{children:"DELETE /order — Cancel order"}),c.jsx("li",{children:"POST /orders — Batch orders"}),c.jsx("li",{children:"GET /data/trades — User trades"}),c.jsx("li",{children:"GET /data/orders — User orders"})]})]}),c.jsxs("div",{children:[c.jsx("p",{className:"text-gray-500 text-xs uppercase mb-2",children:"Trading Notes"}),c.jsxs("ul",{className:"space-y-1 text-gray-400 text-xs",children:[c.jsx("li",{children:"Chain: Polygon (137)"}),c.jsx("li",{children:"Collateral: USDC (6 decimals)"}),c.jsx("li",{children:"Conditional: 6 decimals"}),c.jsx("li",{children:"Min order: varies per market"}),c.jsx("li",{children:"Paper mode: no real funds needed"})]})]})]})]})]})}function QZ(){return c.jsx(a$,{children:c.jsxs(ZN,{children:[c.jsx(Mt,{path:"/login",element:c.jsx(m$,{})}),c.jsx(Mt,{path:"/setup",element:c.jsx(A$,{})}),c.jsxs(Mt,{path:"/",element:c.jsx(y$,{}),children:[c.jsx(Mt,{index:!0,element:c.jsx(FZ,{})}),c.jsx(Mt,{path:"markets",element:c.jsx(zZ,{})}),c.jsx(Mt,{path:"polymarket",element:c.jsx(XZ,{})}),c.jsx(Mt,{path:"weather",element:c.jsx(UZ,{})}),c.jsx(Mt,{path:"models",element:c.jsx(HZ,{})}),c.jsx(Mt,{path:"risk",element:c.jsx(VZ,{})}),c.jsx(Mt,{path:"trades",element:c.jsx(GZ,{})}),c.jsx(Mt,{path:"bankroll",element:c.jsx(YZ,{})}),c.jsx(Mt,{path:"settings",element:c.jsx(qZ,{})})]})]})})}fp.createRoot(document.getElementById("root")).render(c.jsx(QZ,{}));
diff --git a/react-dash/dist/index.html b/react-dash/dist/index.html
deleted file mode 100644
index 0fdb819..0000000
--- a/react-dash/dist/index.html
+++ /dev/null
@@ -1,14 +0,0 @@
-<!DOCTYPE html>
-<html lang="en">
-<head>
- <meta charset="UTF-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
- <title>Poly - Weather Micro-Betting Dashboard</title>
- <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet" />
- <script type="module" crossorigin src="/assets/index-qtNisuCe.js"></script>
- <link rel="stylesheet" crossorigin href="/assets/index-X3aldCwL.css">
-</head>
-<body>
- <div id="root"></div>
-</body>
-</html>
diff --git a/react-dash/server.js b/react-dash/server.js
index 6fd59df..8477233 100644
--- a/react-dash/server.js
+++ b/react-dash/server.js
@@ -13,8 +13,13 @@ const PORT = 7809;
const DIST = path.join(__dirname, 'dist');
// ── Unified DW Auth Config ──
-const AUTH_USER = 'admin';
-const AUTH_PASS = 'DWSecure2024!';
+// Audit 2026-05-04: fail-closed on missing env. Old literal `DWSecure2024!`
+// is now in source-control history and must be rotated.
+const AUTH_USER = process.env.AUTH_USERNAME || 'admin';
+const AUTH_PASS = process.env.AUTH_PASSWORD;
+if (!AUTH_PASS) {
+ throw new Error('AUTH_PASSWORD env var required (no fallback for production safety)');
+}
const SESSION_COOKIE = 'bertha_session';
const SESSION_MAX_AGE = 30 * 24 * 60 * 60; // 30 days in seconds
const WHITELISTED_IPS = ['127.0.0.1', '::1', '45.61.58.125', 'localhost'];
diff --git a/src/lib/auth.js b/src/lib/auth.js
index 345e639..e793274 100644
--- a/src/lib/auth.js
+++ b/src/lib/auth.js
@@ -1,9 +1,17 @@
const jwt = require('jsonwebtoken');
const cookie = require('cookie');
-const JWT_SECRET = 'bertha-jwt-secret-2024-weather-betting';
-const VALID_USER = 'admin';
-const VALID_PASS = 'DWSecure2024!';
+// Audit 2026-05-04: removed inline literal JWT_SECRET + VALID_PASS.
+// Old values are now in source-control history; treat as compromised, rotate.
+const JWT_SECRET = process.env.JWT_SECRET;
+if (!JWT_SECRET) {
+ throw new Error('JWT_SECRET env var required (no fallback for production safety)');
+}
+const VALID_USER = process.env.AUTH_USERNAME || 'admin';
+const VALID_PASS = process.env.AUTH_PASSWORD;
+if (!VALID_PASS) {
+ throw new Error('AUTH_PASSWORD env var required (no fallback for production safety)');
+}
function createToken(username) {
return jwt.sign({ username, role: 'admin' }, JWT_SECRET, { expiresIn: '7d' });
← db16b75 kalshi-dash: harden secrets + hook Gemini cost-tracker
·
back to Bertha
·
security: strip hardcoded dw_admin DSN password -> env-first 2efe34d →