PageSourceSearch

https://www.valueinvestinghub.com/assets/StockDetails-Bfo04QiK.js

js valueinvestinghub.com collected 2026-10-09 22:57:49 UTC 388,376 bytes, 2 lines download raw bytes

1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/PerformanceComparison-mtstRMEb.js","assets/react-query-DtH7GInu.js","assets/charts-DXTQz_Nw.js","assets/index-Bk2jHtle.js","assets/ui-components-BYDPAGXP.js","assets/vendors-C_aCOv2N.js","assets/index-CuZOww-N.css","assets/TickerBadge-QT547Jwj.js","assets/StatBlock-n7oBxilU.js","assets/QualityScorecard-BSARZv3o.js","assets/PriceRangeBar-BInhA2cx.js","assets/useHybridPeerDetection-BEDKyNi-.js","assets/useBatchDetailsCached-DBSSBAtd.js"])))=>i.map(i=>d[i]);
2import{a as yt,j as e}from"./react-query-DtH7GInu.js";import{e as ke,h as Tr,i as Or,j as Qn,k as Er,l as Pr,T as Pe,m as $r,n as Lr,B as Ca,X as Le,o as Ws,C as Kn,r as E,A as Xn,Y as Me,p as Jn,q as As,s as Ve,t as Mt,u as Se,v as Kt,R as jt,w as Xt,a as Mr,x as Dr,L as Fa,y as qr}from"./charts-DXTQz_Nw.js";import{n as He,d as _e,o as D,B as ye,p as Zn,q as ei,r as si,t as ti,e as J,v as ai,w as be,x as Os,y as ni,C as le,l as pe,m as ge,b as ce,_ as Br,z as W,f as xt,D as Ss,T,G as bs,k as fs,I as ss,J as ii,K as gt,L as Jt,M as zr,N as ts,O as us,Q as vs,R as ms,U as Gr,X as Vr,Y as Yr,Z as Ur,$ as Wr,a0 as Hr,a1 as bt,a2 as Qr,a3 as Kr,a4 as Xr,a5 as Jr,a6 as Zr,a7 as eo,a8 as so,u as to,a9 as ao,E as Zt,S as ea,a as sa,aa as os,ab as ls,ac as no,ad as io,ae as ro,af as Rs,ag as ks,ah as oo,ai as lo,aj as Ga,ak as co,A as Va}from"./index-Bk2jHtle.js";import{W as uo}from"./WatchlistButton-B4m_YxJD.js";import{u as zt,D as ri}from"./DCFAnalysisContainer-kl2YSZt4.js";import{B as mo}from"./BreadcrumbNav-CHaBW6HO.js";import{F as Ya}from"./FiftyTwoWeekRange-Cuvs8vr9.js";import{T as Es,a as re}from"./tabs-Ce-pKgjy.js";import{F as Ts}from"./FeatureTabTrigger-D-881LVI.js";import{P as We}from"./progress-wV8gSBlx.js";import{P as Gt,a as cs,B as oi,b as ho,c as li}from"./BedrockDisclaimer-mwbkYb3v.js";import"./TickerBadge-QT547Jwj.js";import{S as O}from"./StatBlock-n7oBxilU.js";import{S as po,P as go,C as fo,M as he,a as At,c as Js,F as Ia,b as ci,d as Ra,Q as St,e as ka,f as xo,g as Ns,h as Ta,T as Ua,i as Wa,s as Ha}from"./QualityScorecard-BSARZv3o.js";import{P as bo}from"./PriceRangeBar-BInhA2cx.js";import{d as vo}from"./deriveAvailableRanges-DiTKys7t.js";import{S as Ps}from"./StyledTabsList-XiII8IH3.js";import{S as me}from"./StyledTabTrigger-CdlTltxQ.js";import{u as yo}from"./useBedrockScore-DkycBykJ.js";import{u as jo}from"./useBedrockRecalculate-BG_O012J.js";import{C as Z,a as Oe,b as di,c as Ie,d as ws,B as Qa,g as No,f as wo,e as Hs,S as ze,h as Vt,i as Ys,u as _o,P as Ao,j as So,E as Co,F as Fo,k as Io,M as Ro,l as ko}from"./MarginOfSafetySubMetrics-DoScP2z4.js";import{b7 as Ls,a4 as Ye,T as ys,az as To,bW as Ka,x as ui,z as Oo,a5 as Qs,at as mi,bn as Ee,p as hi,a6 as pi,bU as js,aG as hs,bq as Fe,bo as gi,aj as Ks,aD as Nt,aV as Oa,bk as Eo,y as Po,aZ as Pt,L as Us,a2 as $s,bX as $o,bY as Lo,a3 as Mo,a$ as fi,aw as xi,bZ as Do,aq as qo,ax as fa,bl as xa,bN as Bo}from"./ui-components-BYDPAGXP.js";import{T as zo}from"./textarea-ouqu71nA.js";import{S as Go}from"./scroll-area-BSWcZ4AB.js";import{g as ue,a as de,V as Xa,E as Ja,P as Za,F as en}from"./PerformanceComparison-mtstRMEb.js";import{u as bi}from"./useHybridPeerDetection-BEDKyNi-.js";import{u as Vo}from"./useBatchDetailsCached-DBSSBAtd.js";import{D as Yo}from"./DCFCalculatorValueProp-CBRVq_7K.js";import{S as $}from"./SmartTooltip-C3SmJddF.js";import{t as P}from"./tooltipData-DjR4nkp-.js";import{T as Uo}from"./TenKAnalysisButton-C3LLeuuD.js";import{u as Wo,a as Ho,b as Qo,c as Ko}from"./useTenKAnalysis-DyxGWbPi.js";import{n as Xo,u as Jo,a as Zo,A as el,C as sl,E as tl,S as qs,b as al,F as nl,R as il,B as rl,D as ol,c as ll,d as cl,V as dl,e as ul}from"./useTenKAnalysisDelta-YC_JfZaq.js";import{A as sn}from"./AnalysisRequestForm-VZMq5V0W.js";import{u as ml}from"./use10KAvailability-Bv0cYG3J.js";import{u as Ea,e as hl,a as pl}from"./vendors-C_aCOv2N.js";import{C as gl,a as fl}from"./CacheStatusBadge-WiFsDs-0.js";import{T as xl}from"./TenKAnalysisValueProp-D226R2_0.js";import{T as Yt}from"./TimeRangeSelector-BWiT2_Mh.js";import"./accordion-BX48Nl4U.js";import"./index-_wdzqCxp.js";import"./useDCFConfig-Dc-_wEec.js";import"./collapsible-CcE06dtV.js";import"./DCFMetricsCards-Ck6nyS0J.js";import"./ValuePropWithSignUp-ukNXBsVn.js";function bl(s,t){const{period:a="quarterly",enabled:n=!0}=t;return yt({queryKey:["all-financial-statements",s,a],queryFn:async()=>
2{if(!s)throw new Error("Symbol is required");console.log(`📊 Fetching ALL ${a} financial statements for ${s}...`);const[i,r,o]=await Promise.all([He.functions.invoke("get-financial-data-cached",{body:{symbol:s.toUpperCase(),period:a,statementType:"income"}}),He.functions.invoke("get-financial-data-cached",{body:{symbol:s.toUpperCase(),period:a,statementType:"balance"}}),He.functions.invoke("get-financial-data-cached",{body:{symbol:s.toUpperCase(),period:a,statementType:"cash_flow"}})]);if(i.error)throw i.error;if(r.error)throw r.error;if(o.error)throw o.error;const l=((i.data?.metadata?.cacheHitRate||0)+(r.data?.metadata?.cacheHitRate||0)+(o.data?.metadata?.cacheHitRate||0))/3;return console.log(`✅ All financial statements loaded | Avg Cache Hit: ${l.toFixed(1)}%`),{income:i.data?.data||[],balance:r.data?.data||[],cashflow:o.data?.data||[],metadata:{income:i.data?.metadata||{},balance:r.data?.metadata||{},cashflow:o.data?.metadata||{}}}},enabled:n&&!!s,staleTime:a==="quarterly"?60*60*1e3:24*60*60*1e3,gcTime:60*60*1e3,retry:2})}const vl={business_quality:"Quality",earnings_power:"Earnings",financial_fortress:"Fortress",capital_allocation:"Allocation",margin_of_safety:"Valuation"};function yl({pillars:s,height:t=240}){const a=Gt.map(n=>({pillar:vl[n],fullName:cs[n],score:Math.round(s[n]?.score??0)}));return e.jsx(ke,{width:"100%",height:t,children:e.jsxs(Tr,{data:a,outerRadius:"72%",children:[e.jsx(Or,{stroke:Z.grid,strokeWidth:Oe.grid}),e.jsx(Qn,{dataKey:"pillar",tick:di.axis,stroke:Z.borderSoft}),e.jsx(Er,{domain:[0,100],tick:!1,axisLine:!1,tickCount:5}),e.jsx(Pr,{name:"Score",dataKey:"score",stroke:Z.primary,fill:Z.primary,fillOpacity:.18,strokeWidth:Oe.series,isAnimationActive:!0,animationDuration:Ie.series,animationEasing:Ie.easing}),e.jsx(Pe,{content:e.jsx(ws,{hideLabel:!0,valueFormatter:n=>`${n}/100`,labelFormatter:n=>""}),cursor:!1})]})})}function jl({score:s,band:t,height:a=200}){const n=[{name:"composite",value:Math.max(0,Math.min(100,Math.round(s))),fill:Qa[t]}];return e.jsxs("div",{className:"relative",style:{height:a},children:[e.jsx(ke,{width:"100%",height:"100%",children:e.jsxs($r,{cx:"50%",cy:"65%",innerRadius:"68%",outerRadius:"100%",startAngle:180,endAngle:0,data:n,barSize:14,children:[e.jsx(Qn,{type:"number",domain:[0,100],tick:!1}),e.jsx(Lr,{background:{fill:"hsl(var(--muted) / 0.6)"},dataKey:"value",cornerRadius:8,isAnimationActive:!0,animationDuration:Ie.series,animationEasing:Ie.easing})]})}),e.jsxs("div",{className:"pointer-events-none absolute inset-0 flex flex-col items-center justify-end pb-4",children:[e.jsx("span",{className:"text-3xl font-semibold tabular-nums leading-none",style:{color:Qa[t]},children:Math.round(s)}),e.jsx("span",{className:"mt-1 text-[10px] uppercase tracking-wider text-muted-foreground",children:"Composite"})]})]})}const Bs={business_quality:{roic_level:.25,roic_trend:.12,roic_consistency:.12,gross_margin_level:.1,gross_margin_stability:.1,operating_margin_trend:.08,operating_leverage:.1,rd_investment_ratio:.05,cash_conversion_cycle:.08},earnings_power:{revenue_cagr:.12,net_income_cagr:.12,eps_cagr:.18,eps_consistency:.12,worst_year_eps:.1,fcf_ni_quality:.1,owner_earnings:.08,owner_earnings_cagr:.1,sequential_eps_deceleration:.05,accruals_quality:.03},financial_fortress:{net_debt_ebitda:.25,interest_coverage:.25,debt_equity:.2,current_ratio:.15,cash_coverage:.15},capital_allocation:{share_count_5yr:.22,buyback_yield:.13,dividend_streak:.13,dividend_cagr:.08,reinvestment_roi:.16,goodwill_ratio:.13,sbc_revenue_trend:.1,goodwill_growth_rate:.05},margin_of_safety:{dcf_margin_of_safety:.5,oe_yield_spread:.15,fcf_yield:.15,ev_ebitda:.1,reverse_dcf:.1}},Nl={business_quality:.25,earnings_power:.2,financial_fortress:.15,capital_allocation:.15,margin_of_safety:.25},wl={wonderful:"Wonderful","high-quality":"High Quality",decent:"Decent",average:"Average",pass:"Pass"},_l={wonderful:"success","high-quality":"info",decent:"warning",average:"neutral",pass:"error"};function Al(s){const{symbol:t,composite:a,band:n,confidence:i,predictabilityMultiplier:r,inversionPenalty:o,pillars:l,engineVersion:c,configVersion:m,calculatedAt:h,narrative:y,universeStats:j,onRecalculate:u,recalculating:f}=s,g=No(j,"composite",a),x=Sl(l);return e.jsx(_e,{variant:"elevated",padding:{base:"md",sm:"lg"},className:"overflow-hidden",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("span",{className:"text-sm font-medium text-muted-foreground",children:[t," · Bedrock Analysis"]}),e.jsx(D,{tone:_l[n],intensity:"subtle",children:wl[n]}),g!==null&&e.jsxs(D,{variant:"outline",className:"font-normal",children:[wo(g)," of universe"]})]}),e.jsxs(ye,{type:"button",size:"sm",variant:"outline",onClick:u,disabled:f,children:[e.jsx(Ls,{className:`mr-1.5 h-3.5 w-3.5 ${f?"animate-spin":""}`}),f?"Recalculating…":"Recalculate"]})]}),e.jsx("p",{className:"max-w-3xl text-base leading-relaxed text-foreground sm:text-lg",children:y.headline}),e.jsxs("div",{className:"grid grid-cols-1 gap-6 md:grid-cols-3",children:[e.jsxs("div",{className:"flex min-w-0 flex-col items-center justify-center overflow-hidden",children:[e.jsx("div",{className:"w-full max-w-[220px]",children:e.jsx(jl,{score:a,band:n,height:150})}),e.jsxs("div",{className:"mt-2 w-full max-w-[220px] space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between text-[11px] text-muted-foreground",children:[e.jsx("span",{children:"Confidence"}),e.jsxs("span",{className:"font-medium tabular-nums text-foreground",children:[Math.round(i*100),"%"]})]}),e.jsx(po,{value:Math.round(i*100),tone:"gradient",size:"sm",label:"Data completeness"})]})]}),e.jsxs("div",{className:"min-w-0 overflow-hidden",children:[e.jsx("div",{className:"mb-1 text-center text-[11px] font-medium uppercase tracking-wider text-muted-foreground",children:"Pillar Shape"}),e.jsx(yl,{pillars:l,height:170}),e.jsx("div",{className:"mt-1 text-center text-[10px] text-muted-foreground",children:"Balanced is healthy · pinched corners reveal weakness"})]}),e.jsxs("div",{className:"min-w-0 space-y-2.5",children:[e.jsx("div",{className:"text-[11px] font-medium uppercase tracking-wider text-muted-foreground",children:"How the score is built"}),e.jsx(ta,{label:"Weighted pillar average",value:x.toFixed(1),tooltip:"Sum of (pillar score × pillar weight) across all five pillars."}),e.jsx(ta,{label:"× Predictability multiplier",value:`× ${r.toFixed(2)}`,tooltip:"Adjustment for earnings volatility. 0.7 (least predictable) to 1.15 (highly predictable). Predictable businesses earn a premium."}),e.jsx(ta,{label:"− Inversion penalty",value:`− ${Math.round(o)}`,tooltip:"Aggregate deduction from red flags (catastrophe-risk signals). 0–40.",highlight:o>0}),e.jsxs("div",{className:"pt-1 text-[10px] text-muted-foreground",children:["Engine v",c," · Config v",m," ·"," ",new Date(h).toLocaleDateString()]})]})]})]})})}function Sl(s){let t=0;for(const a of Gt){const n=s?.[a]?.score??0;t+=n*Nl[a]}return t}function ta({label:s,value:t,tooltip:a,highlight:n}){return e.jsx(Zn,{delayDuration:200,children:e.jsxs(ei,{children:[e.jsx(si,{asChild:!0,children:e.jsxs("div",{className:"flex cursor-help items-center justify-between text-sm",children:[e.jsx("span",{className:"border-b border-dotted border-muted-foreground
2/40 text-muted-foreground",children:s}),e.jsx("span",{className:n?"font-medium text-loss tabular-nums":"font-medium tabular-nums",children:t})]})}),e.jsx(ti,{className:"max-w-xs",children:e.jsx("p",{className:"text-xs",children:a})})]})})}function Cl({narrative:s}){const{strength:t,concern:a,valuation:n}=s.standouts;return e.jsxs("div",{className:"grid grid-cols-1 gap-3 md:grid-cols-3",children:[e.jsx(aa,{tone:"success",icon:Ye,eyebrow:"Strength",item:t}),e.jsx(aa,{tone:"error",icon:ys,eyebrow:"Concern",item:a}),e.jsx(aa,{tone:"info",icon:To,eyebrow:"Valuation",item:n})]})}function aa({tone:s,icon:t,eyebrow:a,item:n}){return e.jsxs(J,{tone:s,icon:t,children:[e.jsx("div",{className:"text-[11px] font-medium uppercase tracking-wider text-muted-foreground",children:a}),e.jsx(J.Title,{children:n.title}),e.jsx(J.Description,{children:n.sentence})]})}const tn={critical:"bg-loss/10 text-loss border-loss/30",high:"bg-cautionary/10 text-cautionary border-cautionary/30",medium:"bg-muted text-muted-foreground border-border",low:"bg-primary/10 text-primary border-primary/30"},an={critical:"#dc2626",high:"#f59e0b",medium:"#6b7280",low:"#2563eb"};function Fl({redFlags:s,inversionPenalty:t}){const a=Math.round(t);if(!s||s.length===0)return e.jsxs("section",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("h2",{className:"flex items-center gap-2 text-base font-semibold",children:[e.jsx(Ka,{className:"h-4 w-4 text-gain"}),"Red Flags"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Inversion checks for catastrophe risk: silent dilution, debt outpacing earnings, accruals divergence, and 13 other failure modes."})]}),e.jsxs(J,{tone:"success",icon:Ka,children:[e.jsx(J.Title,{children:"No catastrophe-risk signals detected"}),e.jsx(J.Description,{children:"All inversion checks passed."})]})]});const n=[s.reduce((i,r)=>(i[r.code]=r.penalty,i),{name:"Penalty"})];return e.jsxs("section",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"text-base font-semibold",children:"Red Flags"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[s.length," signal",s.length===1?"":"s"," detected · total penalty −",a," from composite score"]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"mb-1.5 text-[11px] uppercase tracking-wider text-muted-foreground",children:"Penalty composition"}),e.jsx(ke,{width:"100%",height:36,children:e.jsxs(Ca,{data:n,layout:"vertical",margin:{top:2,right:4,bottom:2,left:4},children:[e.jsx(Le,{type:"number",domain:[0,40],hide:!0}),e.jsx(Pe,{cursor:!1,content:e.jsx(ws,{valueFormatter:i=>`−${i}`,hideLabel:!0})}),s.map(i=>e.jsx(Ws,{name:i.code,dataKey:i.code,stackId:"penalty",radius:2,isAnimationActive:!0,animationDuration:Ie.series,children:e.jsx(Kn,{fill:an[i.severity]??an.medium})},i.code))]})}),e.jsxs("div",{className:"mt-1 flex justify-between text-[10px] tabular-nums text-muted-foreground",children:[e.jsx("span",{children:"0"}),e.jsx("span",{children:"max −40"})]})]}),e.jsx("ul",{className:"space-y-2",children:s.map(i=>e.jsx(Il,{flag:i},i.code))})]})}function Il({flag:s}){const[t,a]=E.useState(!1),n=s.evidence&&Object.keys(s.evidence).length>0;return e.jsxs("li",{className:"rounded-md border bg-background",children:[e.jsxs("button",{type:"button",onClick:()=>a(i=>!i),className:"flex w-full items-start gap-3 p-3 text-left hover:bg-muted/40",disabled:!n,children:[e.jsxs(D,{variant:"outline",className:tn[s.severity]??tn.medium,children:["−",s.penalty]}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx("span",{children:s.description}),e.jsx(D,{variant:"outline",className:"text-[10px] capitalize",children:s.severity})]}),e.jsx("div",{className:"mt-0.5 font-mono text-[10px] text-muted-foreground",children:s.code})]}),n&&(t?e.jsx(ui,{className:"mt-0.5 h-4 w-4 text-muted-foreground"}):e.jsx(Oo,{className:"mt-0.5 h-4 w-4 text-muted-foreground"}))]}),t&&n&&e.jsx("div",{className:"border-t bg-muted/30 px-3 py-2",children:e.jsx("dl",{className:"grid grid-cols-2 gap-2 text-xs",children:Object.entries(s.evidence).map(([i,r])=>e.jsxs("div",{className:"contents",children:[e.jsx("dt",{className:"font-medium text-muted-foreground",children:i}),e.jsx("dd",{className:"font-mono",children:Rl(r)})]},i))})})]})}function Rl(s){return s==null?"—":typeof s=="number"?Number.isFinite(s)?Math.abs(s)<1&&s!==0?s.toFixed(4):s.toFixed(2):"—":typeof s=="boolean"?s?"true":"false":typeof s=="string"?s:JSON.stringify(s)}const nn={revenue:"Revenue",net_income:"Net Income",eps:"EPS",shares_outstanding:"Shares Outstanding",fcf_per_share:"FCF / Share",book_value_per_share:"Book Value / Share",dividends_per_share:"Dividends / Share"},kl=["revenue","net_income","eps","fcf_per_share","book_value_per_share","dividends_per_share","shares_outstanding"];
2function Tl({trendSnapshots:s}){if(!s||s.length===0)return null;const t=new Map(s.map(n=>[n.metric,n])),a=kl.map(n=>t.get(n)).filter(n=>!!n);return a.length===0?null:e.jsxs("section",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] font-medium uppercase tracking-wider text-muted-foreground",children:"Multi-Year Trends"}),e.jsx("h2",{className:"text-xl font-semibold tracking-tight",children:"Per-share series — the long-run trajectory"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-muted-foreground",children:"The shape matters more than any single year. Look for steady upward slopes in earnings, cash flow, and book value — and a downward slope in share count."})]}),e.jsx("div",{className:"grid grid-cols-2 gap-3 md:grid-cols-4",children:a.map(n=>e.jsx(Ol,{snap:n},n.metric))})]})}function Ol({snap:s}){const t=s.series.filter(m=>m.value!==null&&Number.isFinite(m.value)).map(m=>({year:m.year,value:m.value}));if(t.length<2)return e.jsxs("div",{className:"rounded-lg border bg-card/40 p-3",style:{borderColor:Z.borderSoft},children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider text-muted-foreground",children:nn[s.metric]}),e.jsx("div",{className:"mt-2 text-xs text-muted-foreground",children:"Insufficient data"})]});const a=t[0].value,n=t[t.length-1].value,i=a!==0?(n-a)/Math.abs(a)*100:0,r=i>=0,l=(s.metric==="shares_outstanding"?!r:r)?Z.success:Z.danger,c=r?Ye:Qs;return e.jsxs("div",{className:"group rounded-lg border bg-card/40 p-3 transition-colors hover:bg-card/70",style:{borderColor:Z.borderSoft},children:[e.jsxs("div",{className:"flex items-baseline justify-between gap-2",children:[e.jsx("span",{className:"truncate text-[11px] uppercase tracking-wider text-muted-foreground",children:nn[s.metric]}),e.jsxs("span",{className:"inline-flex items-center gap-0.5 text-xs font-medium tabular-nums",style:{color:l},children:[e.jsx(c,{className:"h-3 w-3"}),r?"+":"",i.toFixed(0),"%"]})]}),e.jsx("div",{className:"mt-2 h-12",children:e.jsx(ke,{width:"100%",height:"100%",children:e.jsxs(Xn,{data:t,margin:{top:4,right:0,left:0,bottom:0},children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:`grad-${s.metric}`,x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:l,stopOpacity:.35}),e.jsx("stop",{offset:"100%",stopColor:l,stopOpacity:0})]})}),e.jsx(Me,{hide:!0,domain:["dataMin","dataMax"]}),e.jsx(Jn,{type:"monotone",dataKey:"value",stroke:l,fill:`url(#grad-${s.metric})`,strokeWidth:Oe.series,isAnimationActive:!0,animationDuration:Ie.series,animationEasing:Ie.easing})]})})}),e.jsxs("div",{className:"mt-1.5 flex items-baseline justify-between text-[10px] tabular-nums text-muted-foreground",children:[e.jsxs("span",{children:[t[0].year," · ",rn(a,s.metric)]}),e.jsxs("span",{className:"font-medium text-foreground",children:[t[t.length-1].year," · ",rn(n,s.metric)]})]})]})}function rn(s,t){return Number.isFinite(s)?t==="shares_outstanding"?Math.abs(s)>=1e9?`${(s/1e9).toFixed(2)}B`:Math.abs(s)>=1e6?`${(s/1e6).toFixed(0)}M`:s.toFixed(0):t==="eps"||t==="fcf_per_share"||t==="book_value_per_share"||t==="dividends_per_share"?`$${s.toFixed(2)}`:Math.abs(s)>=1e9?`$${(s/1e9).toFixed(1)}B`:Math.abs(s)>=1e6?`$${(s/1e6).toFixed(0)}M`:`$${s.toFixed(0)}`:"—"}const El={success:Z.success,warning:Z.warning,danger:Z.danger,neutral:Z.text,accent:Z.accent};function Ms({title:s,subtitle:t,pinnedValue:a,pinnedLabel:n,pinnedTone:i="neutral",children:r,empty:o,className:l}){return e.jsxs("div",{className:`rounded-lg border bg-card/40 p-4 ${l??""}`,style:{borderColor:Z.borderSoft},children:[(s||a)&&e.jsxs("div",{className:"mb-3 flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[s&&e.jsx("div",{className:"text-sm font-medium leading-tight",children:s}),t&&e.jsx("div",{className:"mt-0.5 text-xs text-muted-foreground",children:t})]}),a&&e.jsxs("div",{className:"shrink-0 text-right",children:[e.jsx("div",{className:"text-base font-semibold tabular-nums leading-tight",style:{color:El[i]},children:a}),n&&e.jsx("div",{className:"mt-0.5 text-[9px] uppercase tracking-wider text-muted-foreground",children:n})]})]}),o?e.jsxs("div",{className:"flex h-[180px] flex-col items-center justify-center rounded-md bg-muted/20 text-xs text-muted-foreground",children:[e.jsx(mi,{className:"mb-2 h-4 w-4 opacity-40"}),o]}):r]})}const Pl=s=>Number.isFinite(s)?`${s.toFixed(1)}%`:"—",on=s=>Number.isFinite(s)?`${s.toFixed(1)}×`:"—",Dt=s=>{if(!Number.isFinite(s))return"—";const t=Math.abs(s),a=s<0?"-":"";return t>=1e9?`${a}$${(t/1e9).toFixed(1)}B`:t>=1e6?`${a}$${(t/1e6).toFixed(1)}M`:`${a}$${t.toFixed(0)}`},ln=s=>Number.isFinite(s)?Math.abs(s)>=1e9?`${(s/1e9).toFixed(2)}B`:Math.abs(s)>=1e6?`${(s/1e6).toFixed(0)}M`:s.toFixed(0):"—",$l=s=>Number.isFinite(s)?`$${s.toFixed(2)}`:"—",Xs=220;function Ll({analysis:s}){const t=E.useMemo(()=>[...s?.roicTrend??[]].sort((r,o)=>r.period.localeCompare(o.period)).map(r=>({period:r.period,roic:r.roic!==void 0&&r.roic!==null?r.roic*100:null})).filter(r=>r.roic!==null),[s?.roicTrend]),a=t.length>0?t[t.length-1].roic:null,n=a===null?"neutral":a>=15?"success":a>=8?"warning":"danger";return e.jsx(Ms,{title:"Return on Invested Capital",subtitle:"The 15% line is the quality threshold for a durable moat.",pinnedValue:a===null?void 0:`${a.toFixed(1)}%`,pinnedLabel:"Latest",pinnedTone:n,empty:t.length<2?"ROIC history unavailable":void 0,children:e.jsx(ke,{width:"100%",height:Xs,children:e.jsxs(As,{data:t,margin:Hs,children:[e.jsx(Ve,{stroke:Z.grid,strokeWidth:Oe.grid,vertical:!1,strokeDasharray:"2 4"}),e.jsx(Le,{dataKey:"period",...ze}),e.jsx(Me,{...ze,tickFormatter:i=>`${i}%`,width:36}),e.jsx(Mt,{y:15,stroke:Z.success,strokeDasharray:"4 4",strokeOpacity:.6,ifOverflow:"extendDomain"}),e.jsx(Pe,{cursor:Vt,content:e.jsx(ws,{valueFormatter:i=>Pl(i)})}),e.jsx(Se,{name:"ROIC",type:"monotone",dataKey:"roic",stroke:Z.primary,strokeWidth:Oe.series,dot:!1,activeDot:{r:4,strokeWidth:0},isAnimationActive:!0,animationDuration:Ie.series,animationEasing:Ie.easing})]})})})}function Ml({analysis:s}){const t=E.useMemo(()=>{const a=s?.revenueNetIncome??[],n=s?.fcfDivsBuybacks??[],i=new Map(n.map(r=>[r.period,r.fcf]));return[...a].sort((r,o)=>r.period.localeCompare(o.period)).map(r=>({period:r.period,revenue:r.revenue??null,netIncome:r.netIncome??null,fcf:i.get(r.period)??null}))},[s?.revenueNetIncome,s?.fcfDivsBuybacks]);return e.jsxs(Ms,{title:"Revenue · Net Income · Free Cash Flow",subtitle:"If FCF tracks net income, earnings are real. If revenue grows but FCF doesn't, look closer.",empty:t.length<2?"Earnings history unavailable":void 0,children:[e.jsx(ke,{width:"100%",height:Xs,children:e.jsxs(As,{data:t,margin:Hs,children:[e.jsx(Ve,{stroke:Z.grid,strokeWidth:Oe.grid,vertical:!1,strokeDasharray:"2 4"}),e.jsx(Le,{dataKey:"period",...ze}),e.jsx(Me,{...ze,tickFormatter:Dt,width:50}),e.jsx(Pe,{cursor:Vt,content:e.jsx(ws,{valueFormatter:a=>Dt(a)})}),e.jsx(Se,{name:"Revenue",type:"monotone",dataKey:"revenue",stroke:Z.accent,strokeWidth:Oe.series,dot:!1,isAnimationActive:!0,animationDuration:Ie.series}),e.jsx(Se,{name:"Net Income",type:"monotone",dataKey:"netIncome",stroke:Z.success,strokeWidth:Oe.series,dot:!1,isAnimationActive:!0,animationDuration:Ie.series}),e.jsx(Se,{name:"Free Cash Flow",type:"monotone",dataKey:"fcf",stroke:Z.warning,strokeWidth:Oe.series,dot:!1,isAnimationActive:!0,animationDuration:Ie.series})]})}),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-3 text-[11px] text-muted-foreground",children:[e.jsx(vt,{color:Z.accent,label:"Revenue"}),e.jsx(vt,{color:Z.success,label:"Net Income"}),e.jsx(vt,{color:Z.warning,label:"Free Cash Flow"})]})]})}function Dl({financials:s}){const t=E.useMemo(()=>{const o=s?.balance??[],l=s?.income??[],c=new Map(l.map(m=>[m.period,m.normalizedEbitda]));
2return[...o].sort((m,h)=>m.period.localeCompare(h.period)).map(m=>{const h=c.get(m.period),y=m.cash??0,u=(m.totalDebt??m.longTermDebt??0)-y,f=h&&h>0?u/h:null;return{period:m.period,ratio:f}}).filter(m=>m.ratio!==null&&Number.isFinite(m.ratio))},[s?.balance,s?.income]),a=t.length>0?t[t.length-1].ratio:null,n=a===null?"neutral":a<2?"success":a<4?"warning":"danger",i=Math.max(6,...t.map(o=>o.ratio)),r=Math.min(-2,...t.map(o=>o.ratio));return e.jsx(Ms,{title:"Net Debt / EBITDA",subtitle:"Lower is stronger. Below 2× is comfortable; above 4× is fragile in a downturn.",pinnedValue:a===null?void 0:`${a.toFixed(1)}×`,pinnedLabel:"Latest",pinnedTone:n,empty:t.length<2?"Balance-sheet history unavailable":void 0,children:e.jsx(ke,{width:"100%",height:Xs,children:e.jsxs(As,{data:t,margin:Hs,children:[e.jsx(Ve,{stroke:Z.grid,strokeWidth:Oe.grid,vertical:!1,strokeDasharray:"2 4"}),e.jsx(Le,{dataKey:"period",...ze}),e.jsx(Me,{...ze,domain:[r,i],tickFormatter:on,width:40}),e.jsx(Kt,{y1:r,y2:2,fill:Z.success,fillOpacity:.05}),e.jsx(Kt,{y1:2,y2:4,fill:Z.warning,fillOpacity:.05}),e.jsx(Kt,{y1:4,y2:i,fill:Z.danger,fillOpacity:.05}),e.jsx(Mt,{y:2,stroke:Z.success,strokeDasharray:"3 4",strokeOpacity:.5}),e.jsx(Mt,{y:4,stroke:Z.danger,strokeDasharray:"3 4",strokeOpacity:.5}),e.jsx(Pe,{cursor:Vt,content:e.jsx(ws,{valueFormatter:o=>on(o)})}),e.jsx(Se,{name:"Net Debt / EBITDA",type:"monotone",dataKey:"ratio",stroke:Z.primary,strokeWidth:Oe.series,dot:!1,activeDot:{r:4,strokeWidth:0},isAnimationActive:!0,animationDuration:Ie.series})]})})})}function ql({analysis:s}){const t=E.useMemo(()=>[...s?.sharesTrend??[]].sort((l,c)=>l.period.localeCompare(c.period)).map(l=>({period:l.period,shares:l.shares??null})).filter(l=>l.shares!==null),[s?.sharesTrend]),a=E.useMemo(()=>[...s?.fcfDivsBuybacks??[]].sort((l,c)=>l.period.localeCompare(c.period)).map(l=>({period:l.period,dividends:-(l.dividendsPaid??0)||0,buybacks:-(l.buybacks??0)||0})),[s?.fcfDivsBuybacks]),n=t.length>0?t[t.length-1].shares:null,i=t.length>0?t[0].shares:null,r=n!==null&&i!==null&&i>0?(n-i)/i*100:null;return e.jsxs("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-2",children:[e.jsx(Ms,{title:"Shares Outstanding",subtitle:"Down = buybacks (good). Up = dilution (look for why).",pinnedValue:r===null?void 0:`${r>=0?"+":""}${r.toFixed(1)}%`,pinnedLabel:"5y change",pinnedTone:r===null?"neutral":r<0?"success":r<2?"neutral":"warning",empty:t.length<2?"Share-count history unavailable":void 0,children:e.jsx(ke,{width:"100%",height:Xs,children:e.jsxs(Xn,{data:t,margin:Hs,children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"sharesGrad",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:Z.primary,stopOpacity:.25}),e.jsx("stop",{offset:"100%",stopColor:Z.primary,stopOpacity:0})]})}),e.jsx(Ve,{stroke:Z.grid,strokeWidth:Oe.grid,vertical:!1,strokeDasharray:"2 4"}),e.jsx(Le,{dataKey:"period",...ze}),e.jsx(Me,{...ze,tickFormatter:ln,domain:["auto","auto"],width:50}),e.jsx(Pe,{cursor:Vt,content:e.jsx(ws,{valueFormatter:o=>ln(o)})}),e.jsx(Jn,{type:"monotone",dataKey:"shares",name:"Shares",stroke:Z.primary,fill:"url(#sharesGrad)",strokeWidth:Oe.series,isAnimationActive:!0,animationDuration:Ie.series})]})})}),a.length>=2&&e.jsxs(Ms,{title:"Capital Returned to Shareholders",subtitle:"Dividends + buybacks. Both should track free cash flow.",empty:a.length<2?"Capital-return history unavailable":void 0,children:[e.jsx(ke,{width:"100%",height:Xs,children:e.jsxs(Ca,{data:a,margin:Hs,children:[e.jsx(Ve,{stroke:Z.grid,strokeWidth:Oe.grid,vertical:!1,strokeDasharray:"2 4"}),e.jsx(Le,{dataKey:"period",...ze}),e.jsx(Me,{...ze,tickFormatter:Dt,width:50}),e.jsx(Pe,{cursor:{fill:Z.surfaceMuted},content:e.jsx(ws,{valueFormatter:o=>Dt(o)})}),e.jsx(Ws,{name:"Dividends",dataKey:"dividends",stackId:"returns",fill:Z.accent,radius:[Ys.radius,Ys.radius,0,0],maxBarSize:Ys.maxSize,isAnimationActive:!0,animationDuration:Ie.series}),e.jsx(Ws,{name:"Buybacks",dataKey:"buybacks",stackId:"returns",fill:Z.success,maxBarSize:Ys.maxSize,isAnimationActive:!0,animationDuration:Ie.series})]})}),e.jsxs("div",{className:"mt-2 flex gap-3 text-[11px] text-muted-foreground",children:[e.jsx(vt,{color:Z.accent,label:"Dividends"}),e.jsx(vt,{color:Z.success,label:"Buybacks"})]})]})]})}function Bl({currentPrice:s,intrinsicValue:t}
2){if(!(s!=null&&Number.isFinite(s)&&t!==null&&t!==void 0&&Number.isFinite(t)))return e.jsx(Ms,{title:"Price vs. DCF Intrinsic Value",empty:"DCF intrinsic value unavailable",children:e.jsx("div",{})});const n=s,i=t,r=[{name:"Current Price",value:n,fill:Z.accent},{name:"DCF Intrinsic",value:i,fill:i>=n?Z.success:Z.danger}],o=(i-n)/i*100,l=o>=0,c=l?"success":"danger";return e.jsx(Ms,{title:"Price vs. DCF Intrinsic Value",subtitle:l?"Trading below intrinsic value — positive margin of safety.":"Trading above intrinsic value — negative margin of safety.",pinnedValue:`${o>=0?"+":""}${o.toFixed(0)}%`,pinnedLabel:"DCF MoS",pinnedTone:c,children:e.jsx(ke,{width:"100%",height:Xs,children:e.jsxs(Ca,{data:r,margin:Hs,children:[e.jsx(Ve,{stroke:Z.grid,strokeWidth:Oe.grid,vertical:!1,strokeDasharray:"2 4"}),e.jsx(Le,{dataKey:"name",...ze,tick:di.tickValue}),e.jsx(Me,{...ze,tickFormatter:m=>`$${m}`,width:50}),e.jsx(Pe,{cursor:{fill:Z.surfaceMuted},content:e.jsx(ws,{valueFormatter:m=>$l(m),hideLabel:!0})}),e.jsx(Ws,{dataKey:"value",radius:[Ys.radius,Ys.radius,0,0],maxBarSize:48,isAnimationActive:!0,animationDuration:Ie.series,children:r.map((m,h)=>e.jsx(Kn,{fill:m.fill},h))})]})})})}function vt({color:s,label:t}){return e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx("span",{className:"h-2 w-2 rounded-full",style:{backgroundColor:s}}),t]})}const zl=[{short:"Commodity-like business",tone:"negative"},{short:"Weak moat",tone:"negative"},{short:"Modest moat",tone:"neutral"},{short:"Strong moat",tone:"positive"},{short:"Wonderful moat",tone:"positive"}],Gl=[{short:"Earnings struggle",tone:"negative"},{short:"Sluggish earner",tone:"negative"},{short:"Inconsistent earner",tone:"neutral"},{short:"Steady earner",tone:"positive"},{short:"Compounding earner",tone:"positive"}],Vl=[{short:"Fragile balance sheet",tone:"negative"},{short:"Stretched balance sheet",tone:"negative"},{short:"Adequate balance sheet",tone:"neutral"},{short:"Strong balance sheet",tone:"positive"},{short:"Fortress balance sheet",tone:"positive"}],Yl=[{short:"Value-destroying",tone:"negative"},{short:"Wasteful allocator",tone:"negative"},{short:"Mixed allocator",tone:"neutral"},{short:"Sound allocator",tone:"positive"},{short:"Disciplined allocator",tone:"positive"}],Ul=[{short:"Stretched price",tone:"negative"},{short:"Overvalued",tone:"negative"},{short:"Full price",tone:"neutral"},{short:"Fairly valued",tone:"positive"},{short:"Undervalued",tone:"positive"}],Wl={business_quality:zl,earnings_power:Gl,financial_fortress:Vl,capital_allocation:Yl,margin_of_safety:Ul};function Ut(s){return s>=85?4:s>=70?3:s>=55?2:s>=40?1:0}function Wt(s,t){return Wl[s][Ut(t)]}const vi={4:"a wonderful business",3:"a high-quality business",2:"a decent business",1:"an unremarkable business",0:"a lower-quality business"},yi={4:"trading well below intrinsic value",3:"trading at a reasonable price",2:"trading at a full price",1:"trading at a stretched price",0:"trading at a deeply stretched price"};function Hl(s,t,a,n,i,r){const o=vi[t]??"a business",l=yi[a]??"priced uncertainly",c=[];return c.push(`${s} looks like ${o} ${l}.`),t>=3&&a<=1&&r!==null&&r<-.05?c.push(`Quality is high across the four business pillars, but DCF says the market is paying ${Ql(r)}.`):t>=3&&a>=3?c.push("Strong business quality and a reasonable price — the rare combination value investors look for."):t<=1&&a>=3?c.push("Cheap on valuation, but the business itself scores poorly — a value trap is the obvious risk."):t<=1&&a<=1?c.push("Weak across both quality and price — neither lens makes a case here."):n>0&&i?c.push(`Notable concern: ${i.description.toLowerCase()}.`):t>=3&&c.push("Quality scores well across the framework; price determines whether returns will compound."),c.join(" ")}function Ql(s){if(s<=-.5){const a=1/(1+s);if(Number.isFinite(a)&&a>0)return`roughly ${a.toFixed(1)}× intrinsic value`}const t=Math.abs(s*100);return s<0?`about ${t.toFixed(0)}% above intrinsic value`:`about ${t.toFixed(0)}% below intrinsic value`}function Kl(s,t){const a=t?.score??0,n=Ut(a),i=t?.subScores??{},r=t?.rawMetrics??{};switch(s){case"business_quality":return Xl(n,i,r);case"earnings_power":return Jl(n,i,r);case"financial_fortress":return Zl(n,i,r);case"capital_allocation":return ec(n,i,r);case"margin_of_safety":return sc(n,i,r,t?.notes??[]);default:return""}}function Xl(s,t,a){const n=ve(a.roic_ttm),i=ve(a.roic_trend_pp_per_year),r=ve(a.gross_margin_ttm),l=[s>=3?"The moat is in solid shape.":s===2?"A real but limited moat.":"The moat looks thin."];if(n!==null){const c=n>=.2?"well above the 15% quality threshold":n>=.15?"above the 15% quality threshold":n>=.08?"below the 15% threshold typical of high-quality businesses":"far below the 15% threshold";l.push(`ROIC sits at ${(n*100).toFixed(1)}%, ${c}.`)}if(i!==null&&Math.abs(i)>.1&&(i>.5?l.push("Returns on capital are widening, which is what you want to see in a moat."):i<-.5&&l.push("Returns on capital are compressing — a warning sign for the moat.")),r!==null){const c=r*100;c>=50?l.push(`Gross margin of ${c.toFixed(0)}% indicates strong pricing power.`):c<25&&l.push(`Gross margin of ${c.toFixed(0)}% is commodity-like.`)}return l.join(" ")}function Jl(s,t,a){const n=ve(a.revenue_cagr_5y),i=ve(a.eps_cagr_5y),r=ve(a.fcf_ni_quality),l=[s>=3?"Earnings are real and growing.":s===2?"Earnings exist, but with caveats.":"The earnings story is weak."];if(n!==null&&i!==null){const c=(n*100).toFixed(1),m=(i*100).toFixed(1);l.push(`Revenue has compounded at ${c}%/year over 5 years, EPS at ${m}%/year.`)}return r!==null&&(r>
2=.85&&r<=1.2?l.push("Free cash flow tracks reported earnings closely — earnings quality is high."):r<.6&&l.push(`FCF is only ${r.toFixed(2)}× net income — reported earnings are not fully backed by cash.`)),l.join(" ")}function Zl(s,t,a){const n=ve(a.net_debt_ebitda),i=ve(a.interest_coverage),o=[s>=3?"The balance sheet is built to last.":s===2?"The balance sheet is adequate, not exceptional.":"The balance sheet is a concern."];return n!==null&&(n<0?o.push(`Net cash position (net debt is ${n.toFixed(1)}× EBITDA, i.e. negative).`):n<2?o.push(`Net debt at ${n.toFixed(1)}× EBITDA — comfortably manageable.`):n<4?o.push(`Net debt at ${n.toFixed(1)}× EBITDA — moderate leverage.`):o.push(`Net debt at ${n.toFixed(1)}× EBITDA — fragile in a downturn.`)),i===null?o.push("Interest coverage data is unavailable from the upstream feed (often the case for cash-rich, low-debt companies)."):i>=10?o.push(`Interest coverage of ${i.toFixed(1)}× is comfortably safe.`):i<3&&o.push(`Interest coverage of only ${i.toFixed(1)}× is in the danger zone.`),o.join(" ")}function ec(s,t,a){const n=ve(a.share_count_5yr_change),i=ve(a.buyback_yield),r=ve(a.reinvestment_roi),l=[s>=3?"Capital is being allocated thoughtfully.":s===2?"Allocation is mixed — some good moves, some questionable.":"Capital allocation has not served shareholders well."];if(n!==null){const c=n*100;c<-1?l.push(`Share count has declined ${Math.abs(c).toFixed(1)}%/year — meaningful buybacks.`):c>2?l.push(`Share count has grown ${c.toFixed(1)}%/year — significant dilution.`):l.push(`Share count has been roughly flat (${c>=0?"+":""}${c.toFixed(1)}%/year).`)}return i!==null&&i>.02&&l.push(`Buyback yield runs ~${(i*100).toFixed(1)}%.`),r!==null&&(r>=.2?l.push(`Reinvestment ROI of ${(r*100).toFixed(0)}% means new capital compounds.`):r<.05&&l.push(`Reinvestment ROI of only ${(r*100).toFixed(0)}% suggests capital is not earning its keep.`)),l.join(" ")}function sc(s,t,a,n){const i=ve(a.dcf_margin_of_safety),r=ve(a.fcf_yield),o=ve(a.ev_to_ebitda),c=[s>=3?"Price looks attractive relative to value.":s===2?"Price is in the fair-value zone.":"Price runs ahead of intrinsic value."];if(i!==null&&c.push(`DCF margin of safety is ${tc(i)}.`),r!==null){const m=(r*100).toFixed(1);r>=.05?c.push(`FCF yield of ${m}% is reasonable for a long-term holder.`):r<.03&&c.push(`FCF yield of only ${m}% leaves little room for error.`)}return o!==null&&o>18&&c.push(`EV/EBITDA of ${o.toFixed(1)}× is in the premium-growth zone.`),n.some(m=>m.toLowerCase().includes("pillar floor"))&&c.push("The pillar floor capped this score because the DCF gap is severe enough that ratio-based sub-metrics cannot compensate."),c.join(" ")}function tc(s){if(s<=-.5){const t=1/(1+s);if(Number.isFinite(t)&&t>0)return`${(s*100).toFixed(0)}% (price is roughly ${t.toFixed(1)}× intrinsic value)`}return`${s>0?"+":""}${(s*100).toFixed(0)}%`}function ac(s,t){const a=t.indexOf(". ");return a===-1?t:t.slice(0,a+1)}const Pa=["business_quality","earnings_power","financial_fortress","capital_allocation"];function nc(s){let t="business_quality",a=-1;for(const i of Pa){const r=s.pillars?.[i]?.score??0;r>a&&(a=r,t=i)}return{title:Wt(t,a).short,sentence:ic(t,s),pillar:t}}function ic(s,t){const a=t.pillars?.[s]?.rawMetrics??{};switch(s){case"business_quality":{const n=ve(a.roic_ttm);return n!==null?`ROIC of ${(n*100).toFixed(0)}% is the headline strength.`:`${cs[s]} scores ${Math.round(t.pillars[s].score)}/100.`}case"earnings_power":{const n=ve(a.eps_cagr_5y);return n!==null?`EPS has compounded at ${(n*100).toFixed(1)}%/year over the last 5 years.`:`${cs[s]} scores ${Math.round(t.pillars[s].score)}/100.`}case"financial_fortress":{const n=ve(a.net_debt_ebitda);return n!==null&&n<1?`Net debt at ${n.toFixed(1)}× EBITDA — practically debt-free.`:`${cs[s]} scores ${Math.round(t.pillars[s].score)}/100.`}case"capital_allocation":{const n=ve(a.share_count_5yr_change);return n!==null&&n<-.01?`Share count has shrunk ${Math.abs(n*100).toFixed(1)}%/year — buying back stock at scale.`:`${cs[s]} scores ${Math.round(t.pillars[s].score)}/100.`}default:return`${cs[s]} scores ${Math.round(t.pillars[s].score)}/100.`}}function rc(s){if(s.redFlags&&s.redFlags.length>0){const n=[...s.redFlags].sort((i,r)=>r.penalty-i.penalty)[0];return{title:cc(n.severity)+" red flag",sentence:n.description+".",pillar:"business_quality"}}let t="business_quality",a=101;for(const n of Pa){const i=s.pillars?.[n]?.score??0;i<a&&(a=i,t=n)}return a<70?{title:Wt(t,a).short,sentence:oc(t,s),pillar:t}:s.confidence<.7?{title:"Limited data",sentence:`Only ${Math.round(s.confidence*100)}% of the framework's inputs were available — interpret the score with caution.`,pillar:"business_quality"}:{title:"No major concerns",sentence:"No catastrophe-risk signals detected. Quality pillars all score above 70.",pillar:"business_quality"}}function oc(s,t){const a=t.pillars?.[s]?.rawMetrics??{};switch(s){case"business_quality":{const n=ve(a.roic_ttm);return n!==null&&n<.1?`ROIC of ${(n*100).toFixed(0)}% is well below the 15% quality bar.`:"The moat is thin — sub-metrics across margins and capital efficiency are weak."}case"earnings_power":{const n=ve(a.worst_year_eps);return n!==null&&n<-.25?`Worst-year EPS dropped ${Math.abs(n*100).toFixed(0)}% — earnings are not resilient.`:"Earnings growth and quality are below the framework expectations."}case"financial_fortress":{const n=ve(a.net_debt_ebitda);return n!==null&&n>4?`Net debt at ${n.toFixed(1)}× EBITDA — uncomfortably leveraged.`:"Balance-sheet strength is below the framework expectations."}case"capital_allocation":{const n=ve(a.share_count_5yr_change);return n!==null&&n>.02?`Shares grew ${(n*100).toFixed(1)}%/year — meaningful dilution.`:"Capital allocation has not delivered for shareholders over the last cycle."}default:return`${cs[s]} scores ${Math.round(t.pillars[s].score)}/100.`}}function lc(s){const t=s.pillars?.margin_of_safety,a=Wt("margin_of_safety",t?.score??0),n=ve(t?.rawMetrics?.dcf_margin_of_safety);let i;if(n===null)i="DCF intrinsic value is unavailable — the valuation pillar relies on ratio sub-metrics only.";else if(n>=.25)i=`DCF says the price is ${(n*100).toFixed(0)}% below intrinsic value — a meaningful margin of safety.`;else if(n>=0)i=`DCF says the price is roughly fair (${(n*100).toFixed(0)}% margin of safety).`;else if(n>=-.3)i=`DCF says the price runs ${Math.abs(n*100).toFixed(0)}% above intrinsic value.`;else{const r=1/(1+n);i=Number.isFinite(r)&&r>0?`DCF says you're paying roughly ${r.toFixed(1)}× intrinsic value — deeply stretched.`:`DCF margin of safety is ${(n*100).toFixed(0)}% — deeply stretched.`}return{title:a.short,sentence:i,pillar:"margin_of_safety"}}function ve(s){return s==null||typeof s=="string"||!Number.isFinite(s)?null:s}function cc(s){return s&&s.charAt(0).toUpperCase()+s.slice(1)}function dc(s){let t=0,a=0;for(const i of Pa){const r=s.pillars?.[i]?.score;typeof r=="number"&&(t+=r,a+=1)}if(a===0)return 0;const n=t/a;return Ut(n)}function uc(s){const t=s.symbol,a=dc(s),n=Ut(s.pillars?.margin_of_safety?.score??0),i=ve(s.pillars?.margin_of_safety?.rawMetrics?.dcf_margin_of_safety),r=s.redFlags&&s.redFlags.length>0?[...s.redFlags].sort((h,y)=>y.penalty-h.penalty)[0]:null,o=Hl(t,a,n,s.redFlags?.length??0,r,i),l=vi[a],c=yi[n],m={business_quality:rt("business_quality",s),earnings_power:rt("earnings_power",s),financial_fortress:rt("financial_fortress",s),capital_allocation:rt("capital_allocation",s),margin_of_safety:rt("margin_of_safety",s)};return{headline:o,qualityVerdict:l,valueVerdict:c,pillarVerdicts:m,standout
2s:{strength:nc(s),concern:rc(s),valuation:lc(s)}}}function rt(s,t){const a=t.pillars?.[s]?.score??0,n=Wt(s,a),i=Kl(s,t.pillars?.[s]);return{short:n.short,oneLiner:ac(n,i),paragraph:i,tone:n.tone}}const cn=.8;function mc({symbol:s,subTab:t,onSubTabChange:a}){const[n,i]=E.useState("overview"),r=t??n,o=I=>{a?a(I):i(I)},{toast:l}=ai(),c=yo(s),m=jo(s),h=_o(),y=zt(s,{dataScope:"analysis"}),j=()=>{m.mutate(void 0,{onSuccess:()=>{l({title:"Bedrock score recalculated",description:`Fresh score for ${s} computed from latest upstream data.`})},onError:I=>{l({title:"Recalculation failed",description:I instanceof Error?I.message:"Unknown error",variant:"destructive"})}})},u=c.data,f=y.data?.data??y.data,g=f?.analysis,x=f?.financials,S=f?.price??null,k=h.data,w=u?.pillars?.margin_of_safety?.rawMetrics?.dcf_margin_of_safety,p=typeof w=="number"&&Number.isFinite(w)?w:null,v=p!==null&&S!==null&&Number.isFinite(S)?S/(1-p):null,M=E.useMemo(()=>u?uc(u):null,[u]),L=c.isLoading,b=c.isError;return L?e.jsx(pc,{}):b||!u||!M?e.jsx(gc,{symbol:s,message:String(c.error??"")}):u.confidence<cn?e.jsx(fc,{symbol:s,confidence:u.confidence,threshold:cn,pillars:u.pillars,engineVersion:u.engineVersion,configVersion:u.configVersion,calculatedAt:u.calculatedAt,dataFreshness:u.dataFreshness??[],onRecalculate:j,recalculating:m.isPending}):e.jsxs("div",{className:"min-w-0 space-y-8 overflow-x-hidden",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"text-xl font-semibold tracking-tight",children:"Bedrock Analysis"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Five-pillar quality score and pillar breakdown"})]}),e.jsxs(Es,{value:r,onValueChange:I=>o(I),className:"w-full",children:[e.jsx("div",{className:"sticky top-0 z-20 -mx-4 border-b bg-background/90 px-4 py-2 backdrop-blur supports-[backdrop-filter]:bg-background/75 md:-mx-0 md:px-0",children:e.jsx(Ps,{children:oi.map(I=>e.jsx(me,{value:I,children:ho[I]},I))})}),e.jsxs(re,{value:"overview",className:"mt-6 space-y-6",children:[e.jsx(Al,{symbol:s,composite:u.compositeScore,band:u.qualityBand,confidence:u.confidence,predictabilityMultiplier:u.predictabilityMultiplier,inversionPenalty:u.inversionPenalty,pillars:u.pillars,engineVersion:u.engineVersion,configVersion:u.configVersion,calculatedAt:u.calculatedAt,narrative:M,universeStats:k,onRecalculate:j,recalculating:m.isPending}),e.jsx(Cl,{narrative:M})]}),Gt.map(I=>e.jsxs(re,{value:I,className:"mt-6",children:[e.jsx("div",{className:"mb-3 text-[11px] font-medium uppercase tracking-wider text-muted-foreground",children:cs[I]}),e.jsx(Ao,{pillarKey:I,pillar:u.pillars?.[I],weights:Bs[I],verdict:M.pillarVerdicts[I],universeStats:k,subMetricSection:I==="business_quality"?e.jsx(So,{pillar:u.pillars?.[I],weights:Bs[I],analysisData:g,financialsData:x}):I==="earnings_power"?e.jsx(Co,{pillar:u.pillars?.[I],weights:Bs[I],analysisData:g,financialsData:x}):I==="financial_fortress"?e.jsx(Fo,{pillar:u.pillars?.[I],weights:Bs[I],financialsData:x}):I==="capital_allocation"?e.jsx(Io,{pillar:u.pillars?.[I],weights:Bs[I],analysisData:g,financialsData:x}):I==="margin_of_safety"?e.jsx(Ro,{pillar:u.pillars?.[I],weights:Bs[I],analysisData:g,financialsData:x,currentPrice:S,intrinsicValue:v}):void 0,signatureChart:I==="business_quality"||I==="earnings_power"||I==="financial_fortress"||I==="capital_allocation"||I==="margin_of_safety"?void 0:e.jsx(hc,{pillarKey:I,analysisData:g,financialsData:x,currentPrice:S,intrinsicValue:v})})]},I))]}),e.jsx(Fl,{redFlags:u.redFlags??[],inversionPenalty:u.inversionPenalty}),e.jsx(Tl,{trendSnapshots:u.trendSnapshots??[]}),e.jsx(ji,{sources:u.dataFreshness??[],engineVersion:u.engineVersion,configVersion:u.configVersion,calculatedAt:u.calculatedAt}),e.jsx(li,{})]})}function hc({pillarKey:s,analysisData:t,financialsData:a,currentPrice:n,intrinsicValue:i}){switch(s){case"business_quality":return e.jsxs("div",{children:[e.jsx("h4",{className:"mb-2 text-sm font-medium",children:"Long-run trend"}),e.jsx(Ll,{analysis:t})]});case"earnings_power":return e.jsxs("div",{children:[e.jsx("h4",{className:"mb-2 text-sm font-medium",children:"Long-run trend"}),e.jsx(Ml,{analysis:t})]});case"financial_fortress":return e.jsxs("div",{children:[e.jsx("h4",{className:"mb-2 text-sm font-medium",children:"Long-run trend"}),e.jsx(Dl,{financials:a})]});case"capital_allocation":return e.jsxs("div",{children:[e.jsx("h4",{className:"mb-2 text-sm font-medium",children:"Long-run trend"}),e.jsx(ql,{analysis:t})]});case"margin_of_safety":return e.jsxs("div",{children:[e.jsx("h4",{className:"mb-2 text-sm font-medium",children:"Price vs. intrinsic value"}),e.jsx(Bl,{currentPrice:n,intrinsicValue:i})]});default:return null}}function ji({sources:s,engineVersion:t,configVersion:a,calculatedAt:n}){return e.jsxs("details",{className:"group rounded-md border bg-muted/30 px-4 py-3 text-xs",children:[e.jsx("summary",{className:"cursor-pointer list-none select-none",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"font-medium text-muted-foreground",children:["Data freshness · ",s.length," source",s.length===1?"":"s"]}),e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["v",t," · ",new Date(n).toLocaleDateString()," ·"," ",e.jsx("span",{className:"underline group-open:no-underline",children:"expand"})]})]})}),e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx("div",{className:"grid grid-cols-1 gap-1.5 sm:grid-cols-2",children:s.length===0?e.jsx("div",{className:"text-muted-foreground",children:"No source metadata available."}):s.map((i,r)=>e.jsxs("div",{className:"flex justify-between rounded border bg-background px-3 py-1.5",children:[e.jsx("span",{className:"font-mono text-muted-foreground",children:i.source}),e.jsx("span",{children:i.date})]},r))}),e.jsxs("div",{className:"text-[10px] text-muted-foreground",children:["Engine v",t," · Config v",a," · Calculated"," ",new Date(n).toLocaleStr
2ing()]})]})]})}function pc(){return e.jsxs("div",{className:"space-y-4",children:[e.jsx(be,{className:"h-48 w-full"}),e.jsxs("div",{className:"grid grid-cols-1 gap-3 md:grid-cols-3",children:[e.jsx(be,{className:"h-28 w-full"}),e.jsx(be,{className:"h-28 w-full"}),e.jsx(be,{className:"h-28 w-full"})]}),e.jsx(be,{className:"h-64 w-full"})]})}function gc({symbol:s,message:t}){return e.jsxs("section",{className:"space-y-2",children:[e.jsxs("h2",{className:"text-lg font-semibold",children:["Bedrock Analysis — ",s]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:t?`Unable to load Bedrock score: ${t}`:"Insufficient data to compute Bedrock score for this symbol."})]})}function fc({symbol:s,confidence:t,threshold:a,pillars:n,engineVersion:i,configVersion:r,calculatedAt:o,dataFreshness:l,onRecalculate:c,recalculating:m}){const h=Math.round(t*100),y=Math.round(a*100),j=y-h,u=Gt.map(f=>{const g=Object.keys(ko[f]).length,x=n?.[f]?.subScores??{},S=Object.keys(x).length,k=n?.[f]?.notes??[];return{key:f,label:cs[f],expected:g,present:S,missing:Math.max(0,g-S),notes:k}});return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("section",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"rounded-md bg-cautionary/10 p-2",children:e.jsx(Ee,{className:"h-5 w-5 text-cautionary"})}),e.jsxs("div",{children:[e.jsxs("h2",{className:"text-xl font-semibold tracking-tight",children:["Bedrock can't reliably analyze ",s," yet"]}),e.jsxs("p",{className:"mt-1 max-w-2xl text-sm text-muted-foreground",children:["Only ",e.jsxs("span",{className:"font-medium text-foreground",children:[h,"%"]})," ","of the framework's inputs are available. Bedrock requires at least ",e.jsxs("span",{className:"font-medium text-foreground",children:[y,"%"]})," ",`to show a score — a low result built on missing data isn't the same as a low result built on bad performance, and we'd rather say "don't know" than mislead you.`]})]})]}),e.jsxs(ye,{type:"button",size:"sm",variant:"outline",onClick:c,disabled:m,children:[e.jsx(Ls,{className:`mr-1.5 h-3.5 w-3.5 ${m?"animate-spin":""}`}),m?"Recalculating…":"Recalculate"]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2 flex items-baseline justify-between text-sm",children:[e.jsx("span",{className:"font-medium",children:"Data completeness"}),e.jsxs("span",{className:"tabular-nums",children:[h,"% / ",y,"% required",e.jsxs("span",{className:"ml-2 text-xs text-muted-foreground",children:["(",j>0?`${j}pp short`:"threshold met",")"]})]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(We,{value:h,className:"h-2"}),e.jsx("div",{className:"absolute top-0 h-full w-px bg-foreground
2/60",style:{left:`${y}%`},"aria-hidden":!0})]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"mb-3 text-[11px] font-medium uppercase tracking-wider text-muted-foreground",children:"Pillar Coverage"}),e.jsx("ul",{className:"space-y-2",children:u.map(f=>e.jsx(xc,{...f},f.key))})]}),e.jsx("div",{className:"rounded-md border bg-muted/30 p-3 text-xs text-muted-foreground",children:e.jsxs("p",{children:["The score might fill in once upstream caches catch up."," ",e.jsx("button",{type:"button",onClick:c,disabled:m,className:"underline underline-offset-2 hover:text-foreground disabled:opacity-50",children:"Click Recalculate"})," ","to fetch fresh data and recompute. If the gap persists, the underlying caches for ",s," likely don't have the required data points yet."]})})]}),l.length>0&&e.jsx(ji,{sources:l,engineVersion:i,configVersion:r,calculatedAt:o}),e.jsx(li,{})]})}function xc({label:s,expected:t,present:a,missing:n,notes:i}){const r=n===0,o=t>0?a/t:0,l=o>=.8?"success":o>=.5?"warning":"danger",c={success:"text-gain",warning:"text-cautionary",danger:"text-loss"}[l];return e.jsxs("li",{className:"rounded-md border bg-card/40 p-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[r?e.jsx(hi,{className:"h-3.5 w-3.5 text-gain"}):e.jsx(pi,{className:`h-3.5 w-3.5 ${c}`}),e.jsx("span",{className:"text-sm font-medium",children:s})]}),e.jsxs(D,{variant:"outline",className:"font-normal tabular-nums",children:[a," / ",t," sub-metrics"]})]}),i.length>0&&e.jsx("ul",{className:"mt-2 space-y-0.5 pl-5 text-xs text-muted-foreground",children:i.map((m,h)=>e.jsx("li",{className:"list-disc",children:m},h))})]})}function na({value:s,flag:t,defaultValue:a=!1,className:n="mt-4",children:i}){return e.jsx(re,{value:s,className:n,children:e.jsx(Os,{flag:t,defaultValue:a,children:i})})}function bc({open:s,onClose:t}){return null}function vc({symbol:s,name:t}){const[a,n]=E.useState([]),[i,r]=E.useState(""),[o,l]=E.useState(!1),[c,m]=E.useState(!1),{session:h}=ni(),y=!h,j=async()=>{const f=i.trim();if(!f)return;if(y){m(!0),n(x=>[...x,{role:"assistant",content:"Sign in to continue the AI chat."}]);return}r("");const g={role:"user",content:f};n(x=>[...x,g]),l(!0);try{const{data:x,error:S}=await He.functions.invoke("ai-chat",{body:{symbol:s,question:f}});if(x?.missingOpenAIKey)n(k=>[...k,{role:"assistant",content:"AI chat is not configured: missing OpenAI API key in Supabase Edge Function secrets."}]);else if(S||x?.error){const k=typeof x?.error=="string"&&x.error||S?.message||"AI error";n(w=>[...w,{role:"assistant",content:k}])}else{const k=x?.generatedText||x?.answer||"";n(w=>[...w,{role:"assistant",content:k||"(No response)"}])}}catch(x){const S=x&&(x.message||(typeof x=="string"?x:""))||"AI chat is not configured yet. Please add your OpenAI API key in Supabase Edge Function secrets.";n(k=>[...k,{role:"assistant",content:S}])}finally{l(!1)}},u=f=>{if(f.key==="Enter"){if(f.altKey)return;f.preventDefault(),o||j()}};return e.jsxs(e.Fragment,{children:[e.jsxs(le,{children:[e.jsx(pe,{children:e.jsxs(ge,{className:"text-xl",children:["Ask AI about ",s,t?` · ${t}`:""]})}),e.jsxs(ce,{className:"space-y-3",children:[e.jsx(Go,{className:"h-56 rounded-md border p-3",children:e.jsx("div",{className:"space-y-3 text-sm",children:a.length===0?e.jsxs("p",{className:"text-muted-foreground",children:["Start a conversation about ",s,". Press Enter to send, Alt+Enter for a new line."]}):a.map((f,g)=>e.jsxs("div",{className:f.role==="user"?"font-medium":"text-muted-foreground",children:[e.jsx("span",{className:"uppercase tracking-wide text-xs mr-2 text-muted-foreground",children:f.role==="user"?"You":"AI"}),f.content]},g))})}),e.jsxs("div",{className:"flex items-end gap-2",children:[e.jsx(zo,{value:i,onChange:f=>r(f.target.value),onKeyDown:u,placeholder:`Ask about ${s}'s valuation, risks, catalysts...`,className:"min-h-[64px]"}),e.jsx(ye,{onClick:j,disabled:o,children:o?"Sending...":"Send"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Answers use a general AI model and are for research only. Press Enter to send; Alt+Enter adds a new line."})]})]}),e.jsx(bc,{open:c,onClose:()=>m(!1)})]})}function yc(s){const{totalDebt:t,longTermDebt:a,shortTermDebt:n,totalEquity:i}=s;if(!i||i===0)return null;const r=t||(a||0)+(n||0);return r==null?null:r/i}
2function jc({symbol:s,companyName:t,marketCap:a,maxPeers:n=8,minMarketCap:i=1e9,useV2:r=!0,configId:o}){const[l,c]=E.useState(null),[m,h]=E.useState(!1),[y,j]=E.useState(null),[u,f]=E.useState(!1),g=async()=>{if(!(!s||!r)){h(!0),j(null);try{console.log(`🔍 Fetching enhanced peer detection for ${s}`);const{data:p,error:v}=await He.functions.invoke("intelligent-peer-detection-v2",{body:{symbol:s.toUpperCase(),max_peers:n,min_market_cap:i,config_id:o}});if(v)throw console.error("❌ V2 peer detection failed:",{error:v,message:v.message,details:v.details,hint:v.hint,code:v.code}),v;if(!p?.target||!p?.peers)throw new Error("Invalid response format from peer detection");if(p.peers.length===0||p.methodology?.total_candidates_analyzed===0)throw console.log("⚠️ V2 returned empty results, falling back to static detection"),new Error("V2 returned empty results");const M=Nc(p),L={target:p.target,peers:p.peers,methodology:p.methodology,reason:M,cache_ttl:p.cache_ttl};c(L),f(!0),console.log(`✅ V2 peer detection successful: ${p.peers.length} peers found`)}catch(p){console.error("❌ Enhanced peer detection failed:",p),j(p instanceof Error?p.message:"Failed to fetch peer analysis"),await x()}finally{h(!1)}}},x=async()=>{try{console.log(`🔄 Falling back to static peer detection for ${s}`);const{detectIntelligentPeers:p}=await Br(async()=>{const{detectIntelligentPeers:L}=await import("./PerformanceComparison-mtstRMEb.js").then(b=>b.i);return{detectIntelligentPeers:L}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12])),v=p(s,t,a),M={target:{symbol:v.symbol,name:v.name,sector:"Unknown",industry:"Unknown",marketCap:a||0},peers:v.peers.map(L=>({...L,financial_similarity:75,etf_similarity:0,size_similarity:wc(a||0,L.marketCap),sector_match:80,composite_score:75,confidence_level:60,shared_etfs:[]})),methodology:{data_sources_used:["Static_Database"],scoring_weights:{sector_industry_match:1},total_candidates_analyzed:126,etfs_analyzed:0},reason:v.reason+" (Static fallback)",cache_ttl:1*60*60};c(M),f(!1)}catch(p){console.error("❌ Static fallback also failed:",p),j("All peer detection methods failed")}};E.useEffect(()=>{if(!s){c(null);return}r?g():x()},[s,t,a,n,i,r,o]);const S=E.useMemo(()=>l?.peers||[],[l]),k=E.useMemo(()=>S.map(p=>p.symbol),[S]);return{peerAnalysis:l,allPeers:S,peerSymbols:k,loading:m,error:y,isV2:u,refresh:async()=>{await g()}}}function Nc(s){const{methodology:t,peers:a,target:n}=s,i=t.etfs_analyzed,r=t.total_candidates_analyzed,o=a.length>0?a[0].composite_score:0;let l=`Analyzed ${r} companies using advanced multi-signal detection. `;return i>0&&(l+=`Found co-holdings in ${i} major ETFs. `),o>80?l+="High-confidence matches based on financial similarity and institutional co-ownership patterns.":o>60?l+="Good matches identified through sector analysis and market positioning.":l+="Moderate similarity based on available financial and sector data.",l}function wc(s,t){return s===0||t===0?50:Math.min(s,t)/Math.max(s,t)*100}function ba(s){return s==null||!Number.isFinite(s)?null:s>.15?"strong":s>.1?"good":"moderate"}function va(s){return s==null||!Number.isFinite(s)?"moderate":s>.05?"strong":s>.02?"good":"moderate"}function _c(s){return!s||!Number.isFinite(s)?null:s<3?"strong":s<6?"good":"moderate"}function Ac(s){return!s||!Number.isFinite(s)?null:s<2?"strong":s<4?"good":"moderate"}function dn(s){return s==null||!Number.isFinite(s)?"moderate":s>60?"strong":s>40?"good":"moderate"}function Ni(s){return!s||!Number.isFinite(s)?null:s<.5?"strong":s<1?"good":"weak"}function Sc(s){return!s||!Number.isFinite(s)?null:s<.3?"strong":s<.7?"good":"moderate"}function Cc(s){return s>=3?"strong":s>=2?"good":s>=1?"moderate":"weak"}const Fc={strong:"Wide Moat",good:"Narrow Moat",moderate:"Limited Moat",weak:"No Moat"};function Ic(s){return Fc[s]}function wi(s){switch(s){case"Wide Moat":return"strong";case"Narrow Moat":return"good";case"Limited Moat":return"moderate";case"No Moat":return"weak";default:return null}}function Te(s){if(s==null)return"na";switch(s){case"strong":return"strong";case"good":return"adequate";case"moderate":return"caution";case"weak":return"weak"}}function ia(s){const t=a=>{const n=a.match(/(\d{4}).*?(?:Q([1-4]))?/i);if(n){const r=parseInt(n[1],10),o=n[2]?parseInt(n[2],10):0;return r*10+o}const i=Date.parse(a);return Number.isNaN(i)?0:Math.floor(i/864e5)};return[...s].sort((a,n)=>t(n.period)-t(a.period))}const un=s=>s===null?"muted":s==="strong"?"gain":s==="good"?"primary":s==="moderate"?"cautionary":"loss",zs=({tone:s})=>{const t=Te(s);return e.jsx(D,{tone:ue(t),intensity:"subtle",children:de(t)})};
2function mn({symbol:s,name:t,marketCap:a,ratios:n,financials:i,manualPeers:r=[],useManualPeers:o=!1}){const{peerAnalysis:l,allPeers:c}=bi({symbol:o?"":s||"",strategy:"hybrid",maxPeers:8,lightweightMode:!1}),{loading:m}=jc({symbol:o?"":s||"",companyName:t,marketCap:a,maxPeers:8,useV2:!0}),y=o?r:(o?[]:c).slice(0,8).map(C=>C.symbol),{map:j,loading:u}=Vo(y,"analysis"),f=y.map(C=>{const V=j[C];if(!V)return null;const ie=V?.data||V;if(!ie)return null;const Fs=ie.ratios?.grossProfitMargin||0,Zs=ie.ratios?.fcfYield||0,_=ie.ratios?.roic||0;return{symbol:ie.symbol,name:ie.name||ie.symbol,marketCap:ie.marketCap||0,roic:_,fcfYield:Zs,pb:ie.ratios?.pb||0,debtToEquity:ie.ratios?.de||0,grossProfitMargin:Fs}}).filter(Boolean),g=n?.roic||0,x=n?.fcfYield||0,S=i?.balance?ia(i.balance)[0]:null,k=S?yc({totalDebt:S.totalDebt,longTermDebt:S.longTermDebt,shortTermDebt:S.shortTermDebt,totalEquity:S.totalEquity}):null,w=n?.de||k||0,p=n?.pb||0,v={roic:f.length>0?f.reduce((C,V)=>C+(V?.roic||0),0)/f.length:0,fcfYield:f.length>0?f.reduce((C,V)=>C+(V?.fcfYield||0),0)/f.length:0,pb:f.length>0?f.reduce((C,V)=>C+(V?.pb||0),0)/f.length:0,debtToEquity:f.length>0?f.reduce((C,V)=>C+(V?.debtToEquity||0),0)/f.length:0,grossProfitMargin:f.length>0?f.reduce((C,V)=>C+(V?.grossProfitMargin||0),0)/f.length:0},M=i?.income?ia(i.income)[0]:null,L=M?.revenue&&M?.grossProfit?M.grossProfit/M.revenue*100:0,b=i?.income?ia(i.income).slice(0,5):[],I=b.filter(C=>C.netIncome&&C.netIncome>0).length,ee=b.length>0?I/b.length:0,U=()=>{if(g===0&&L===0&&x===0)return"No Data";let C=0;return g>.15?C+=2:g>.1&&(C+=1),L>60?C+=2:L>40&&(C+=1),ee>=.8&&(C+=1),x>.05&&(C+=1),w>0&&w<.5&&(C+=1),C>=5?"Wide Moat":C>=3?"Narrow Moat":C>=1?"Limited Moat":"No Moat"},A=jt.useMemo(()=>f.length?[{name:s,roic:g*100,isTarget:!0},...f.map(V=>({name:V.symbol,roic:(V.roic||0)*100,isTarget:!1}))].sort((V,ie)=>(ie.roic||0)-(V.roic||0)):[],[f,s,g]);if(m||u)return e.jsxs("div",{className:"space-y-6",children:[e.jsx(be,{className:"h-6 w-1/3"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsx(be,{className:"h-32 w-full"}),e.jsx(be,{className:"h-32 w-full"})]})]});const K=U(),ne=wi(K),je=g===0&&x===0&&p===0&&L===0&&w===0,se=g<=0?null:ba(g),oe=x<=0?null:va(x),De=L<=0?null:dn(L),is=Ni(w),rs=[{metric:"Return on Invested Capital",value:g?`${(g*100).toFixed(1)}%`:"—",peerAvg:v?.roic?`${(v.roic*100).toFixed(1)}%`:"—",threshold:">15%",vsPeers:v?.roic?g*100>v.roic*100?"↗️":"↘️":"—",assessmentTone:se},{metric:"Free Cash Flow Yield",value:x?`${(x*100).toFixed(1)}%`:"—",peerAvg:v?.fcfYield?`${(v.fcfYield*100).toFixed(1)}%`:"—",threshold:">5%",vsPeers:v?.fcfYield?x*100>v.fcfYield*100?"↗️":"↘️":"—",assessmentTone:oe},{metric:"Gross Margin",value:L?`${L.toFixed(1)}%`:"—",peerAvg:v?.grossProfitMargin?`${(v.grossProfitMargin*100).toFixed(1)}%`:"—",threshold:">40%",vsPeers:v?.grossProfitMargin?L>v.grossProfitMargin*100?"↗️":"↘️":"—",assessmentTone:De},{metric:"Debt-to-Equity Ratio",value:w?`${w.toFixed(2)}x`:"—",peerAvg:v?.debtToEquity?`${v.debtToEquity.toFixed(2)}x`:"—",threshold:"<0.5x",vsPeers:v?.debtToEquity?w<v.debtToEquity?"↗️":"↘️":"—",assessmentTone:is}],ps=[{id:"metric",sticky:!0,header:"Metric",accessor:C=>C.metric,priority:"primary",cell:C=>e.jsx("span",{className:"font-medium text-sm",children:C.metric})},{id:"value",header:s,accessor:C=>C.value,align:"right"},{id:"peerAvg",header:"Peer Avg",accessor:C=>C.peerAvg,align:"right"},{id:"threshold",header:"Threshold",accessor:C=>C.threshold,align:"right"},{id:"vsPeers",header:"vs Peers",accessor:C=>C.vsPeers,align:"right"},{id:"assessment",header:"Assessment",accessor:C=>de(Te(C.assessmentTone)),align:"right",cell:C=>e.jsx(zs,{tone:C.assessmentTone})}],te=A.map(C=>({label:C.name,value:C.roic,highlight:C.isTarget})),Cs=v?.roic&&v.roic>0?v.roic*100:void 0;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("section",{className:"space-y-4",children:[e.jsx(W,{as:"h3",size:{base:"5",md:"6"},icon:js,title:"Economic Moat Overview",subtitle:`Assessment of ${t}'s competitive advantages and moat strength vs peers`}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsx(O,{al
2ign:"center",size:"lg",label:"Moat Strength",value:K,valueColor:un(ne),subtext:K==="No Data"?"Insufficient data":"Based on ROIC, margins, and consistency"}),e.jsx(O,{align:"center",size:"lg",label:"Peer Ranking",value:g>0?(()=>{const C=g*100;return`${f.filter(ie=>(ie.roic||0)*100>C).length+1} of ${f.length+1}`})():"N/A",subtext:g>0?"ROIC ranking vs industry peers":"Insufficient data"}),e.jsx(O,{align:"center",size:"lg",label:"Industry vs Peers",value:v?.roic?g*100>v.roic*100?"Above Average":"Below Average":"N/A",subtext:v?.roic?`Industry avg: ${(v.roic*100).toFixed(1)}%`:"Insufficient peer data"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsxs("section",{className:"space-y-4",children:[e.jsx(W,{as:"h3",size:"4",title:"Sources of Competitive Advantage",subtitle:"Analysis of different moat types and their strength vs peers"}),je?e.jsx(xt,{icon:js,title:"No Competitive Advantage Data",description:"Insufficient financial data available to assess competitive advantages for this stock. This may indicate limited analyst coverage or data availability."}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-border/50",children:[e.jsx("th",{className:"text-left p-3 font-medium",children:"Competitive Advantage"}),e.jsx("th",{className:"text-center p-3 font-medium min-w-[120px]",children:s}),f.map(C=>e.jsx("th",{className:"text-center p-3 font-medium min-w-[80px]",children:C.symbol},C.symbol)),e.jsx("th",{className:"text-center p-3 font-medium min-w-[80px]",children:"Avg"})]})}),e.jsxs("tbody",{children:[e.jsxs("tr",{className:"border-b border-border/30 hover:bg-muted/30",children:[e.jsxs("td",{className:"p-3",children:[e.jsx("div",{className:"font-medium text-sm",children:"Brand Power"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"ROIC"})]}),e.jsxs("td",{className:"p-3 text-center",children:[e.jsxs("div",{className:"font-semibold",children:[(g*100).toFixed(1),"%"]}),e.jsx("div",{className:"mt-1",children:e.jsx(zs,{tone:g<=0?null:ba(g)})})]}),f.map(C=>e.jsx("td",{className:"p-3 text-center",children:e.jsxs("div",{className:"font-medium text-sm",children:[C.roic!==null&&C.roic!==void 0?(C.roic*100).toFixed(1):"—","%"]})},C.symbol)),e.jsx("td",{className:"p-3 text-center",children:e.jsx("div",{className:"font-medium text-sm",children:(()=>{const C=f.filter(V=>V.roic!=null).map(V=>(V.roic||0)*100);return C.length>0?`${(C.reduce((V,ie)=>V+ie,0)/C.length).toFixed(1)}%`:"—"})()})})]}),e.jsxs("tr",{className:"border-b border-border/30 hover:bg-muted/30",children:[e.jsxs("td",{className:"p-3",children:[e.jsx("div",{className:"font-medium text-sm",children:"Switching Costs"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"FCF Yield"})]}),e.jsxs("td",{className:"p-3 text-center",children:[e.jsxs("div",{className:"font-semibold",children:[(x*100).toFixed(1),"%"]}),e.jsx("div",{className:"mt-1",children:e.jsx(zs,{tone:x<=0?null:va(x)})})]}),f.map(C=>e.jsx("td",{className:"p-3 text-center",children:e.jsxs("div",{className:"font-medium text-sm",children:[C.fcfYield!==null&&C.fcfYield!==void 0?(C.fcfYield*100).toFixed(1):"—","%"]})},C.symbol)),e.jsx("td",{className:"p-3 text-center",children:e.jsx("div",{className:"font-medium text-sm",children:(()=>{const C=f.filter(V=>V.fcfYield!=null).map(V=>(V.fcfYield||0)*100);return C.length>0?`${(C.reduce((V,ie)=>V+ie,0)/C.length).toFixed(1)}%`:"—"})()})})]}),e.jsxs("tr",{className:"border-b border-border/30 hover:bg-muted/30",children:[e.jsxs("td",{className:"p-3",children:[e.jsx("div",{className:"font-medium text-sm",children:"Network Effects"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"P/B Ratio"})]}),e.jsxs("td",{className:"p-3 text-center",children:[e.jsxs("div",{className:"font-semibold",children:[p?.toFixed(2)||"—","x"]}),e.jsx("div",{className:"mt-1",children:e.jsx(zs,{tone:Ac(p)})})]}),f.map(C=>e.jsx("td",{className:"p-3 text-center",children:e.jsxs("div",{className:"font-medium text-sm",children:[C.pb!==null&&C.pb!==void 0?C.pb.toFixed(2):"—","x"]})},C.symbol)),e.jsx("td",{className:"p-3 text-center",children:e.jsx("div",{className:"font-medium text-sm",children:(()=>{const C=f.filter(V=>V.pb!=null).map(V=>V.pb||0);return C.length>0?`${(C.reduce((V,ie)=>V+ie,0)/C.length).toFixed(2)}x`:"—"})()})})]}),e.jsxs("tr",{className:"border-b border-border/30 hover:bg-muted/30",children:[e.jsxs("td",{className:"p-3",children:[e.jsx("div",{className:"font-medium text-sm",children:"Cost Advantages"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Gross Margin"})]}),e.jsxs("td",{className:"p-3 text-center",children:[e.jsxs("div",{className:"font-semibold",children:[L.toFixed(1),"%"]}),e.jsx("div",{className:"mt-1",children:e.jsx(zs,{tone:L<=0?null:dn(L)})})]}),f.map(C=>e.jsx("td",{className:"p-3 text-center",children:e.jsxs("div",{className:"font-medium text-sm",children:[C.grossProfitMargin!==null&&C.grossProfitMargin!==void 0?(C.grossProfitMargin*100).toFixed(1):"—","%"]})},C.symbol)),e.jsx("td",{className:"p-3 text-center",children:e.jsx("div",{className:"font-medium text-sm",children:(()=>{const C=f.filter(V=>V.grossProfitMargin!=null).map(V=>(V.grossProfitMargin||0)*100);return C.length>0?`${(C.reduce((V,ie)=>V+ie,0)/C.length).toFixed(1)}%`:"—"})()})})]}),e.jsxs("tr",{className:"hover:bg-muted/30",children:[e.jsxs("td",{className:"p-3",children:[e.jsx("div",{className:"font-medium text-sm",children:"Financial Strength"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"D/E Ratio"})]}),e.jsxs("td",{className:"p-3 text-center",children:[e.jsxs("div",{className:"font-semibold",children:[w.toFixed(2),"x"]}),e.jsx("div",{className:"mt-1",children:e.jsx(zs,{tone:Sc(w)})})]}),f.map(C=>e.jsx("td",{className:"p-3 text-center",children:e.jsxs("div",{className:"font-medium text-sm",children:[C.debtToEquity!==null&&C.debtToEquity!==void 0?C.debtToEquity.toFixed(2):"—","x"]})},C.symbol)),e.jsx("td",{className:"p-3 text-center",children:e.jsx("div",{className:"font-medium text-sm",children:(()=>{const C=f.filter(V=>V.debtToEquity!=null).map(V=>V.debtToEquity||0);return C.length>0?`${(C.reduce((V,ie)=>V+ie,0)/C.length).toFixed(2)}x`:"—"})()})})]})]})]})})]}),e.jsxs("section",{className:"space-y-4",children:[e.jsx(W,{as:"h3",size:"4",title:"Moat Assessment Matrix",subtitle:"Comprehensive evaluation of competitive advantage indicators vs peers"}),e.jsx(Ss,{columns:ps,data:rs,getRowKey:C=>C.metric,variant:"elevated",mobileVariant:"scroll"})]})]}),te.length>0&&e.jsxs("section",{className:"space-y-4",children:[e.jsx(W,{as:"h3",size:"4",title:"ROIC Comparison vs Peers",subtitle:"Return on Invested Capital across the peer group, with industry average marker"}),e.jsx(go,{items:te,average:Cs,averageLabel:"Industry Avg",format:"percent",precision:1})]}),e.jsxs("section",{className:"space-y-4",children:[e.jsx(W,{as:"h3",size:"4",title:"Economic Moat Summary & Analysis",subtitle:"Investment implications of competitive advantages and business sustainability vs peers"}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsx(O,{al
2ign:"center",size:"lg",label:"Moat Width",value:K,valueColor:un(ne),subtext:`Relative to ${f.length} industry peers`}),e.jsx(O,{align:"center",size:"lg",label:"Capital Efficiency",value:g>.15?"Strong":g>.1?"Adequate":g>0?"Caution":"N/A",valueColor:g>.15?"gain":g>.1?"primary":g>0?"cautionary":"muted",subtext:g?`${(g*100).toFixed(1)}% ROIC`:"Insufficient data"}),e.jsx(O,{align:"center",size:"lg",label:"Competitive Position",value:g>0?(()=>{const C=f.filter(Fs=>(Fs.roic||0)>g).length,V=f.length+1,ie=(V-C-1)/V*100;return ie>=75?"Top Quartile":ie>=50?"Above Median":ie>=25?"Below Median":"Bottom Quartile"})():"N/A",subtext:g>0?"Based on ROIC vs peer group":"Insufficient data"})]}),e.jsxs(J,{tone:"neutral",children:[e.jsx(J.Title,{children:"Investment Perspective"}),e.jsx(J.Description,{children:(()=>{if(g===0&&x===0&&L===0)return`Insufficient financial data available to assess ${t}'s economic moat and competitive positioning. Key profitability metrics (ROIC, FCF Yield, Gross Margin) are not available, which limits the ability to evaluate sustainable competitive advantages. Consider alternative data sources or wait for more comprehensive financial reporting before making investment decisions.`;const C=g>0?(()=>{const V=f.filter(ie=>(ie.roic||0)>g).length;return V===0?"leads its peer group":V<=f.length*.25?"ranks in the top quartile of peers":V<=f.length*.5?"performs above the peer median":"lags behind most peers"})():"has limited comparable data versus peers";return K==="Wide Moat"?`${t} demonstrates a wide economic moat with strong competitive advantages. The company ${C} in key profitability metrics, suggesting sustainable competitive positioning. This creates potential for long-term value creation through pricing power and market share defense.`:K==="Narrow Moat"?`${t} shows evidence of a narrow economic moat with some competitive advantages. While the company ${C}, the moat may be vulnerable to industry disruption or increased competition. Monitor competitive dynamics and margin sustainability.`:K==="Limited Moat"?`${t} displays limited economic moat characteristics. The company ${C}, but competitive advantages appear modest. Investment returns may be more dependent on market conditions and execution rather than sustainable competitive positioning.`:`${t} shows minimal evidence of an economic moat. The company ${C} and may face significant competitive pressures. Consider the cyclical nature of the business and potential for industry disruption when evaluating investment merit.`})()})]})]})]})]})}function Ct({data:s,selectedTimeRange:t,dateField:a="period"}){return E.useMemo(()=>{if(!s||s.length===0)return{filteredData:{data:[],isLimited:!1},dataAvailability:{},bestTimeRange:"Max",isDataLimited:!1,availabilityMessage:"No data available"};const n={"1Y":1,"3Y":3,"5Y":5,"10Y":10};return{filteredData:{data:t==="Max"?s:s.slice(-n[t]),isLimited:!1},dataAvailability:{},bestTimeRange:t,isDataLimited:!1,availabilityMessage:void 0}},[s,t,a])}function X(s,t="plain"){if(s==null||!Number.isFinite(s))return"—";switch(t){case"currency":const a=Math.abs(s),n=s<0?"-":"";return a>=1e12?`${n}$${(a/1e12).toFixed(2)}T`:a>=1e9?`${n}$${(a/1e9).toFixed(2)}B`:a>=1e6?`${n}$${(a/1e6).toFixed(2)}M`:a>=1e3?`${n}$${(a/1e3).toFixed(0)}K`:`${n}$${a.toLocaleString(void 0,{maximumFractionDigits:0})}`;case"ratio":return s.toFixed(2);case"percentage":return`${s.toFixed(1)}%`;default:return s.toLocaleString(void 0,{maximumFractionDigits:2})}}function Rc(s,t,a){let n=0;const i=[];return s&&(s<15?(n+=2,i.push("Low P/E")):s<20?(n+=1,i.push("Reasonable P/E")):s>30?(n-=2,i.push("High P/E")):(n-=1,i.push("Elevated P/E"))),t&&(t<1.5?(n+=2,i.push("Low P/B")):t<3?(n+=1,i.push("Moderate P/B")):(n-=1,i.push("High P/B"))),a&&(a>8?(n+=2,i.push("Strong FCF Yield")):a>4?(n+=1,i.push("Decent FCF Yield")):(n-=1,i.push("Weak FCF Yield"))),n>=3?{assessment:"Undervalued",tone:"success",description:`Strong value signals: ${i.slice(0,2).join(", ")}`}:n>=0?{assessment:"Fairly Valued",tone:"info",description:`Mixed signals: ${i.slice(0,2).join(", ")}`}:{assessment:"Potentially Overvalued",tone:"warning",description:`Caution signals: ${i.slice(0,2).join(", ")}`}}
2function kc({symbol:s,ratios:t,financials:a,analysis:n,marketCap:i,price:r,sharesOutstanding:o,priceData:l,dividendData:c}){const m=a?.income?.[0],h=a?.balance?.[0],y=a?.cashflow?.[0],j=_=>{const q=_?.incomeBeforeTax,H=_?.incomeTaxExpense;return q!=null&&Math.abs(q)>0&&H!=null?Math.min(Math.max(Math.abs(H)/Math.abs(q),0),1):.25},u=(_,q)=>{if(!_||!q)return null;const H=_.operatingIncome;if(H==null)return null;const Q=q.totalAssets;if(Q==null||Q<=0)return null;const ae=_.revenue??0,et=q.currentLiabilities??0,d=q.shortTermDebt??0,qa=q.cash??0,st=Math.max(0,et-d),qe=Math.max(0,qa-ae*.02),tt=Q-st-qe;if(tt<=0)return null;const at=j(_),Ds=H*(1-at)/tt*100;return Number.isFinite(Ds)?Ds:null},f=u(m,h)??(t?.roic!=null?t.roic*100:null),g=h?.currentAssets&&h?.currentLiabilities?h.currentAssets/h.currentLiabilities:null,x=h?.totalDebt&&h?.shareholdersEquity?h.totalDebt/h.shareholdersEquity:null,S=m?.revenue&&m?.grossProfit?m.grossProfit/m.revenue*100:null,k=m?.revenue&&m?.operatingIncome?m.operatingIncome/m.revenue*100:null,w=m?.revenue&&m?.netIncome?m.netIncome/m.revenue*100:null,p=m?.netIncome&&h?.shareholdersEquity?m.netIncome/h.shareholdersEquity*100:null,v=m?.netIncome&&h?.totalAssets?m.netIncome/h.totalAssets*100:null,M=h?.shareholdersEquity&&o?h.shareholdersEquity/o:null,L=m?.revenue&&i?i/m.revenue:null,b=h?.currentAssets&&h?.currentLiabilities&&h?.cash?(h.currentAssets-h.cash)/h.currentLiabilities:null,I=h?.currentAssets&&h?.currentLiabilities?h.currentAssets-h.currentLiabilities:null,ee=m?.revenue&&h?.totalAssets?m.revenue/h.totalAssets:null,U=m?.operatingIncome&&h?.longTermDebt?m.operatingIncome/(h.longTermDebt*.05):null,A=a?.income?.length>=2?((a.income[0].revenue||0)-(a.income[1].revenue||0))/(a.income[1].revenue||1)*100:null,K=a?.income?.length>=2?((a.income[0].netIncome||0)-(a.income[1].netIncome||0))/(a.income[1].netIncome||1)*100:null,ne=a?.income?.length>=5?((a.income[0].revenue||0)-(a.income[4].revenue||0))/(a.income[4].revenue||1)*100/5:null,je=a?.income?.length>=5?((a.income[0].netIncome||0)-(a.income[4].netIncome||0))/(a.income[4].netIncome||1)*100/5:null,se=(()=>{const _=n?.sharesTrend;if(!_||_.length<2)return null;const q=_[0]?.shares,H=_[1]?.shares;if(!q||!H||H<=0)return null;const Q=(q-H)/H*100;return Math.abs(Q)>1e3?(console.warn(`[FundamentalsAnalysis] Share count change rejected: ${Q.toFixed(1)}% (exceeds ±1000%)`),null):Q})();y?.fcf&&i&&y.fcf>0&&i/y.fcf,h?.longTermDebt&&y?.fcf&&y.fcf>0&&h.longTermDebt/y.fcf;const oe=a?.cashflow?.length>=5?a.cashflow.slice(0,5).reduce((_,q)=>_+(q.fcf||0),0)/5:y?.fcf||null,De=a?.cashflow?.length>=5?((a.cashflow[0].fcf||0)-(a.cashflow[4].fcf||0))/(a.cashflow[4].fcf||1)*100/5:null,is=a?.income?.length>=5&&a?.balance?.length>=5?(()=>{const _=[];for(let q=0;q<5;q++){const H=u(a.income[q],a.balance[q]);H!=null&&_.push(H)}return _.length>0?_.reduce((q,H)=>q+H,0)/_.length:null})():f,rs=h?.longTermDebt&&oe&&oe>0?h.longTermDebt/oe:null,ps=oe&&i&&oe>0?i/oe:null,te=t?.pe||null,Cs=Rc(t?.pe,t?.pb,t?.fcfYield),C=E.useMemo(()=>[{key:"5y-pe",label:"5 Year P/E",value:X(te,"ratio"),threshold:"< 22.5",pass:!!(te&&te<22.5)},{key:"5y-roic",label:"5 Year ROIC",value:X(is,"percentage"),threshold:"> 9%",pass:!!(is&&is>9)},{key:"share-count",label:"Share Count",value:X(se,"percentage"),threshold:"Declining preferred",pass:se!==null&&se<=0},{key:"fcf-growth-5y",label:"FCF Growth 5Y",value:X(De,"percentage"),threshold:"Positive preferred",pass:!!(De&&De>0)},{key:"net-income-growth-5y",label:"Income Growth 5Y",value:X(je,"percentage"),threshold:"Positive preferred",pass:!!(je&&je>0)},{key:"revenue-growth-5y",label:"Revenue Growth 5Y",value:X(ne,"percentage"),threshold:"Positive preferred",pass:!!(ne&&ne>0)},{key:"ltl-vs-5y-fcf",label:"LTL vs 5Y FCF",value:X(rs,"ratio"),threshold:"< 5 years",pass:!!(rs&&rs<5)},{key:"5y-price-to-fcf",label:"5Y Price to FCF",value:X(ps,"ratio"),threshold:"< 22.5",pass:!!(ps&&ps<22.5)}],[te,is,se,De,je,ne,rs,ps]),V=C.filter(_=>_.pass).length,ie=V>=6?"Strong value candidate":V>=4?"Potential value opportunity":"Requires careful analysis",Fs=[{label:"Revenue",value:X(m?.revenue,"currency"),tooltipId:void 0},{label:"Gross Margin",value:X(S,"percentage"),tooltipId:"grossMargin"},{label:"Operating Margin",value:X(k,"percentage"),tooltipId:"operatingMargin"},{label:"Net Margin",value:X(w,"percentage"),tooltipId:"netMargin"}],Zs=[{label:"Operating Cash Flow",value:X(y?.operatingCashFlow,"currency")},{label:"Free Cash Flow",value:X(y?.fcf,"currency")}
2,{label:"Dividends Paid",value:X(y?.dividendsPaid,"currency")},{label:"Share Buybacks",value:X(y?.buybacks,"currency")}];return e.jsxs("div",{className:"space-y-6",children:[e.jsx(W,{as:"h2",size:"6",title:"Fundamentals",subtitle:"Value investing metrics and quality analysis"}),e.jsxs("section",{className:"space-y-4",children:[e.jsx(W,{as:"h3",size:"4",title:"Advanced Value Investing Metrics",subtitle:"8 key criteria for value investment analysis"}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:C.map(_=>e.jsx(fo,{label:_.label,value:_.value,threshold:_.threshold,pass:_.pass},_.key))}),e.jsx(J,{tone:"neutral",children:e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx(T,{as:"p",size:"2",weight:"medium",children:"Value Investment Score"}),e.jsx(T,{as:"p",size:"1",color:"muted",children:ie})]}),e.jsxs("div",{className:"text-right",children:[e.jsxs("div",{className:"text-2xl font-bold tabular-nums",children:[V,"/8"]}),e.jsx(T,{as:"div",size:"1",color:"muted",children:"Criteria Met"})]})]})})]}),e.jsxs("section",{className:"space-y-4",children:[e.jsx(W,{as:"h3",size:"4",title:"Value Assessment",subtitle:"Overall valuation based on key metrics",actions:e.jsx(D,{tone:Cs.tone,intensity:"subtle",children:Cs.assessment})}),e.jsx(T,{size:"2",color:"muted",children:Cs.description})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsxs("section",{className:"space-y-4",children:[e.jsx(W,{as:"h3",size:"4",title:"Valuation Ratios",subtitle:"Price-based valuation metrics"}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(he,{label:e.jsx($,{id:"pe",data:P.pe,children:e.jsx("span",{children:"Price-to-Earnings (P/E)"})}),value:X(t?.pe,"ratio"),numeric:!0}),e.jsx(he,{label:e.jsx($,{id:"pb",data:P.pb,children:e.jsx("span",{children:"Price-to-Book (P/B)"})}),value:X(t?.pb,"ratio"),numeric:!0}),e.jsx(he,{label:e.jsx($,{id:"priceToSales",data:P.priceToSales,children:e.jsx("span",{children:"Price-to-Sales (P/S)"})}),value:X(L,"ratio"),numeric:!0}),e.jsx(he,{label:e.jsx($,{id:"fcfYield",data:P.fcfYield,children:e.jsx("span",{children:"Free Cash Flow Yield"})}),value:X(t?.fcfYield,"percentage"),numeric:!0}),e.jsx(he,{label:e.jsx($,{id:"bookValuePerShare",data:P.bookValuePerShare,children:e.jsx("span",{children:"Book Value Per Share"})}),value:X(M,"currency"),numeric:!0}),e.jsx(bs,{}),e.jsx(he,{label:"Market Cap",value:X(i,"currency"),numeric:!0}),e.jsx(he,{label:"Shares Outstanding",value:X(o,"plain"),numeric:!0})]}),e.jsx(J,{tone:"info",className:"mt-4",children:e.jsx("div",{className:"text-sm",children:(()=>{const _=t?.pe,q=t?.pb,H=t?.fcfYield;return _&&q&&H?_<15&&q<1.5&&H>.08?`Strong value signal: ${s} trading at P/E ${_.toFixed(1)}x generates ${(H*100).toFixed(1)}% free cash flow yield - this ${_.toFixed(1)}x multiple is paying you ${(H*100).toFixed(1)}% annually in cash generation.`:_<15&&H>.06?`Decent entry point: ${s} at P/E ${_.toFixed(1)}x with ${(H*100).toFixed(1)}% FCF yield means you're paying ${_.toFixed(1)} years of earnings for a business generating ${(H*100).toFixed(1)}% cash returns.`:_>25||q>3?`Expensive valuation: ${s} demands ${_.toFixed(1)} years to pay back your investment through earnings${q>3?` while trading at ${q.toFixed(1)}x book value`:""} - high price for current fundamentals.`:`Fair valuation: ${s} at P/E ${_.toFixed(1)}x, P/B ${q.toFixed(1)}x represents ${_.toFixed(1)} years of current earnings - reasonable but not compelling on metrics alone.`:_?_<12?`Attractive multiple: ${s} at P/E ${_.toFixed(1)}x means current earnings could recover your investment in just ${_.toFixed(1)} years - investigate what's creating this discount.`:_>30?`High price: ${s} at P/E ${_.toFixed(1)}x requires ${_.toFixed(1)} years of current earnings to justify today's price - expensive unless growth accelerates significantly.`:`Standard multiple: ${s} at P/E ${_.toFixed(1)}x offers moderate pricing - ${_.toFixed(1)} years of earnings to break even at current profit levels.`:`Limited valuation data: ${s} lacks sufficient pricing metrics - need to analyze asset value, cash generation, and business fundamentals directly.`})()})})]}),e.jsxs("section",{className:"space-y-4",children:[e.jsx(W,{as:"h3",size:"4",title:"Financial Strength",subtitle:"Balance sheet and liquidity metrics"}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(he,{label:e.jsx($,{id:"currentRatio",data:P.currentRatio,children:e.jsx("span",{children:"Current Ratio"})}),value:X(g,"ratio"),numeric:!0}),e.jsx(he,{label:e.jsx($,{id:"quickRatio",data:P.quickRatio,children:e.jsx("span",{children:"Qu
2ick Ratio"})}),value:X(b,"ratio"),numeric:!0}),e.jsx(he,{label:e.jsx($,{id:"debtToEquity",data:P.debtToEquity,children:e.jsx("span",{children:"Debt-to-Equity"})}),value:X(x,"ratio"),numeric:!0}),e.jsx(he,{label:e.jsx($,{id:"interestCoverage",data:P.interestCoverage,children:e.jsx("span",{children:"Interest Coverage"})}),value:X(U,"ratio"),numeric:!0}),e.jsx(he,{label:e.jsx($,{id:"workingCapital",data:P.workingCapital,children:e.jsx("span",{children:"Working Capital"})}),value:X(I,"currency"),numeric:!0}),e.jsx(bs,{}),e.jsx(he,{label:e.jsx($,{id:"roe",data:P.roe,children:e.jsx("span",{children:"Return on Equity (ROE)"})}),value:X(p,"percentage"),numeric:!0}),e.jsx(he,{label:e.jsx($,{id:"roa",data:P.roa,children:e.jsx("span",{children:"Return on Assets (ROA)"})}),value:X(v,"percentage"),numeric:!0}),e.jsx(he,{label:e.jsx($,{id:"roic",data:P.roic,children:e.jsx("span",{children:"ROIC (Enhanced)"})}),value:X(f,"percentage"),valueColor:f&&f>15?"gain":f&&f>10?"cautionary":"loss",numeric:!0}),e.jsx(he,{label:e.jsx($,{id:"assetTurnover",data:P.assetTurnover,children:e.jsx("span",{children:"Asset Turnover"})}),value:X(ee,"ratio"),numeric:!0})]}),e.jsx(J,{tone:"success",className:"mt-4",children:e.jsx("div",{className:"text-sm",children:(()=>{const _=x,q=g,H=p,Q=f;return _!==null&&q!==null&&H!==null&&Q!==null?_<.3&&H>20&&Q>15?`Exceptional financials: ${s} generates ${H.toFixed(1)}% return on equity and ${Q.toFixed(1)}% on invested capital with minimal debt (${_.toFixed(2)} D/E) - every dollar of equity produces ${(H/100).toFixed(2)} in profit.`:_>.8&&q<1.2?`Leverage risk: ${s} has ${(_*100).toFixed(0)}% as much debt as equity with only ${q.toFixed(2)}x current assets covering short-term obligations - debt service could strain cash flows.`:Q>15&&_<.5?`Efficient capital use: ${s} generates ${Q.toFixed(1)}% returns on invested capital while maintaining conservative ${_.toFixed(2)} debt ratio - reinvestment creates ${Q.toFixed(1)} cents per invested dollar.`:H<10||Q<8?`Weak profitability: ${s} produces only ${H?H.toFixed(1):"N/A"}% ROE and ${Q?Q.toFixed(1):"N/A"}% ROIC - each equity dollar generates just ${H?(H/100).toFixed(2):"N/A"} in annual profit.`:`Adequate returns: ${s}'s ${H.toFixed(1)}% ROE with ${_.toFixed(2)} D/E means each equity dollar produces ${(H/100).toFixed(2)} annually - solid but not outstanding profitability.`:_!==null&&H!==null?_<.3&&H>15?`Strong combination: ${s} achieves ${H.toFixed(1)}% ROE (${(H/100).toFixed(2)} profit per equity dollar) with minimal debt burden of ${_.toFixed(2)} D/E - self-funding growth potential.`:_>.6?`High leverage: ${s} carries ${_.toFixed(2)}x debt-to-equity ratio - for every dollar of equity, there's ${_.toFixed(2)} in debt obligations requiring service.`:`Balanced profile: ${s} maintains ${_.toFixed(2)} D/E ratio while generating ${H.toFixed(1)}% ROE - moderate debt with decent ${(H/100).toFixed(2)} return per equity dollar.`:`Insufficient data: ${s} needs complete financial metrics to assess debt capacity, profitability ratios, and capital efficiency.`})()})})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsxs("section",{className:"space-y-4",children:[e.jsx(W,{as:"h3",size:"4",title:"Price Performance",subtitle:"Current price trends and volatility"}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(he,{label:"Current Price",value:X(r,"currency"),numeric:!0}),e.jsx(he,{label:"52-Week High",value:X(l?.high52w,"currency"),numeric:!0}),e.jsx(he,{label:"52-Week Low",value:X(l?.low52w,"currency"),numeric:!0}),e.jsx(bs,{}),e.jsx(he,{label:"1-Week Change",value:X(l?.change1w,"percentage"),valueColor:l?.change1w!=null?l.change1w>=0?"gain":"loss":"foreground",numeric:!0}),e.jsx(he,{label:"1-Month Change",value:X(l?.change1m,"percentage"),valueColor:l?.change1m!=null?l.change1m>=0?"gain":"loss":"foreground",numeric:!0}),e.jsx(he,{label:"1-Year Change",value:X(l?.change1y,"percentage"),valueColor:l?.change1y!=null?l.change1y>=0?"gain":"loss":"foreground",numeric:!0})]}),e.jsx(J,{tone:"warning",className:"mt-4",children:e.jsx("div",{className:"text-sm",children:(()=>{const _=l?.high52w,q=l?.low52w,H=r,Q=l?.change1y;if(_&&q&&H){const ae=(H-q)/(_-q)*100,et=(_-H)/_*100,d=(H-q)/q*100;return ae<20?`Near low: ${s} at $${H.toFixed(2)} trades only ${d.toFixed(0)}% above its 52-week low of $${q.toFixed(2)} - current price represents ${((H/q-1)*100).toFixed(0)}% premium to recent bottom.`:ae>90?`Near peak: ${s} at $${H.toFixed(2)} sits ${et.toFixed(0)}% below its 52-week high of $${_.toFixed(2)} - stock has recovered ${ae.toFixed(0)}% of its annual range.`:Q&&Math.abs(Q)>50?`Major move: ${s} has ${Q>0?"gained":"lost"} ${Math.abs(Q).toFixed(1)}% over 12 months - this dramatic ${Math.abs(Q).toFixed(1)}% shift warrants investigation of underlying business changes.`:`Mid-range trading: ${s} at $${H.toFixed(2)} represents ${ae.toFixed(0)}% of its 52-week range from $${q.toFixed(2)} to $${_.toFixed(2)} - balanced market positioning.`}else return Q!=null?Q<-30?`Significant decline: ${s} down ${Math.abs(Q).toFixed(1)}% over 12 months - this ${Math.abs(Q).toFixed(1)}% drop may reflect temporary issues or fundamental deterioration.`:Q>50?`Strong appreciation: ${s} up ${Q.toFixed(1)}% over 12 months - this ${Q.toFixed(1)}% gain suggests market optimism about business prospects or valuation expansion.`:`Moderate performance: ${s} shows ${Q.toFixed(1)}% annual return - this ${Math.abs(Q).toFixed(1)}% move indicates steady market assessment of value.`:`Limited price data: ${s} lacks sufficient price history - need fundamental analysis of business value without relying on market pricing patterns.`})()})})]}),e.jsxs("section",{className:"space-y-4",children:[e.jsx(W,{as:"h3",size:"4",title:"Dividend & Growth",subtitle:"Income generation and historical growth"}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(he,{label:"Dividend Yield",value:X(c?.dividendYield,"percentage"),numeric:!0}
2),e.jsx(he,{label:"Annual Dividend",value:X(c?.annualDividend,"currency"),numeric:!0}),e.jsx(he,{label:"Payout Ratio",value:X(c?.payoutRatio,"percentage"),numeric:!0}),e.jsx(he,{label:"Dividend Growth",value:X(c?.dividendGrowth,"percentage"),numeric:!0}),e.jsx(bs,{}),e.jsx(he,{label:e.jsx($,{id:"revenueGrowth",data:P.revenueGrowth,children:e.jsx("span",{children:"Revenue Growth (YoY)"})}),value:X(A,"percentage"),valueColor:A!=null?A>=0?"gain":"loss":"foreground",numeric:!0}),e.jsx(he,{label:e.jsx($,{id:"earningsGrowth",data:P.earningsGrowth,children:e.jsx("span",{children:"Earnings Growth (YoY)"})}),value:X(K,"percentage"),valueColor:K!=null?K>=0?"gain":"loss":"foreground",numeric:!0})]}),e.jsx(J,{tone:"neutral",className:"mt-4",children:e.jsx("div",{className:"text-sm",children:(()=>{const _=c?.dividendYield,q=c?.payoutRatio,H=c?.dividendGrowth,Q=A,ae=K;return _&&q&&Q&&ae?_>3&&q<60&&H&&H>5&&ae>8?`Growth with income: ${s} delivers ${ae.toFixed(1)}% earnings growth while paying ${_.toFixed(1)}% dividend from ${q.toFixed(0)}% of profits - retaining ${(100-q).toFixed(0)}% for reinvestment.`:q>80?`High payout risk: ${s} distributes ${q.toFixed(0)}% of earnings as dividends, leaving only ${(100-q).toFixed(0)}% for business reinvestment or economic downturns.`:Q>12&&ae>Q&&q<40?`Expanding profitability: ${s} grows earnings ${ae.toFixed(1)}% vs ${Q.toFixed(1)}% revenue growth while retaining ${(100-q).toFixed(0)}% of profits for reinvestment - margin expansion with capital retention.`:Q<-5&&ae<-10?`Declining business: ${s} faces ${Math.abs(Q).toFixed(1)}% revenue decline and ${Math.abs(ae).toFixed(1)}% earnings drop - shrinking operations with uncertain dividend sustainability.`:`Steady profile: ${s} combines ${ae.toFixed(1)}% earnings growth with ${_.toFixed(1)}% dividend yield - moderate growth with ${q.toFixed(0)}% earnings distributed to shareholders.`:Q!==null&&ae!==null?Q>15&&ae>20?`Strong fundamentals: ${s} expands earnings ${ae.toFixed(1)}% while growing revenue ${Q.toFixed(1)}% - the ${(ae-Q).toFixed(1)}% margin expansion indicates operational efficiency gains.`:Q<0&&ae<0?`Contracting operations: ${s} shows ${Math.abs(Q).toFixed(1)}% revenue decline with ${Math.abs(ae).toFixed(1)}% earnings drop - business is shrinking on both top and bottom lines.`:ae>15&&Q>10?`Profitable expansion: ${s} achieves ${ae.toFixed(1)}% earnings growth from ${Q.toFixed(1)}% revenue growth - strong ${(ae/Q*100).toFixed(0)}% conversion of sales growth to profit growth.`:`Measured growth: ${s} grows earnings ${ae.toFixed(1)}% and revenue ${Q.toFixed(1)}% - consistent but moderate business expansion across operations.`:_&&q?_>4&&q<50?`Attractive income: ${s} yields ${_.toFixed(1)}% while paying only ${q.toFixed(0)}% of earnings - dividend covered ${(100/q).toFixed(1)}x by profits with room for growth.`:_<2&&q<30?`Reinvestment focus: ${s} pays minimal ${_.toFixed(1)}% dividend from just ${q.toFixed(0)}% of earnings - retaining ${(100-q).toFixed(0)}% of profits for business growth.`:`Standard policy: ${s} yields ${_.toFixed(1)}% from ${q.toFixed(0)}% payout ratio - dividends covered ${(100/q).toFixed(1)}x by current earnings with moderate retention.`:`Need growth metrics: ${s} requires revenue, earnings, and dividend data to assess business expansion patterns and capital allocation effectiveness.`})()})})]})]}),e.jsxs("section",{className:"space-y-4",children:[e.jsx(W,{as:"h3",size:"4",title:"Profitability Analysis",subtitle:`Revenue quality and margin trends (${m?.period??"—"})`}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:Fs.map(_=>e.jsx("div",{className:"rounded-lg bg-muted/20 p-4",children:e.jsx(O,{align:"center",size:"md",label:_.tooltipId?e.jsx($,{id:_.tooltipId,data:P[_.tooltipId],children:e.jsx("span",{children:_.label})}):_.label,value:_.value})},_.label))})]}),e.jsxs("section",{className:"space-y-4",children:[e.jsx(W,{as:"h3",size:"4",title:"Cash Flow & Capital Allocation",subtitle:`How the company generates and uses cash (${y?.period??"—"})`}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:Zs.map(_=>e.jsx("div",{className:"rounded-lg bg-muted/20 p-4",children:e.jsx(O,{al
2ign:"center",size:"md",label:_.label,value:_.value})},_.label))})]}),e.jsxs("section",{className:"space-y-4",children:[e.jsx(W,{as:"h3",size:"4",title:"Fundamentals Summary",subtitle:"Investment implications and key metrics analysis"}),e.jsxs("div",{className:"space-y-6",children:[e.jsx(J,{tone:"neutral",children:e.jsx(T,{size:"2",color:"muted",children:(()=>{const _=[t?.roic&&t.roic>15?"strong capital efficiency":null,x!==null&&x<.3?"conservative balance sheet":null,t?.pe&&t.pe<15?"attractive valuation":null,t?.fcfYield&&t.fcfYield>8?"excellent cash generation":null,w&&w>15?"high profitability":null].filter(Boolean),q=[t?.roic&&t.roic<10?"weak returns on capital":null,x!==null&&x>.6?"high leverage":null,t?.pe&&t.pe>25?"expensive valuation":null,A&&A<0?"declining revenues":null].filter(Boolean);return _.length>=3?`Strong investment profile with ${_.slice(0,2).join(" and ")}. This combination suggests a quality business with competitive advantages.`:q.length>=2?`Investment concerns include ${q.slice(0,2).join(" and ")}. Careful analysis of business fundamentals is recommended.`:"Mixed investment signals. Consider both strengths and weaknesses before making investment decisions."})()})}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4",children:[(()=>{const _=f&&f>15?"success":f&&f>10?"warning":"error";return e.jsx(At,{label:"Capital Efficiency (Enhanced)",value:X(f,"percentage"),statusLabel:f&&f>15?"Excellent ROIC":f&&f>10?"Good ROIC":"Poor ROIC",tone:_})})(),(()=>{const _=x!==null&&x<.3?"success":x!==null&&x<.6?"warning":"error";return e.jsx(At,{label:"Financial Strength",value:X(x,"ratio"),statusLabel:x!==null&&x<.3?"Strong D/E":x!==null&&x<.6?"Moderate D/E":"High D/E",tone:_})})(),(()=>{const _=t?.pe&&t.pe<15?"success":t?.pe&&t.pe<25?"warning":"error";return e.jsx(At,{label:"Valuation",value:X(t?.pe,"ratio"),statusLabel:t?.pe&&t.pe<15?"Attractive P/E":t?.pe&&t.pe<25?"Fair P/E":"Expensive P/E",tone:_})})(),(()=>{const _=t?.fcfYield&&t.fcfYield>8?"success":t?.fcfYield&&t.fcfYield>4?"warning":"error";return e.jsx(At,{label:"Cash Generation",value:X(t?.fcfYield,"percentage"),statusLabel:t?.fcfYield&&t.fcfYield>8?"Excellent FCF":t?.fcfYield&&t.fcfYield>4?"Good FCF":"Poor FCF",tone:_})})()]})]})]})]})}function Tc(s,t,a,n){const i=[],r=s.strongBuy+s.buy,o=t>0?r/t*100:0;return o>=70?i.push({type:"positive",title:"Strong Analyst Support",description:`${Math.round(o)}% of analysts issued buy ratings`,icon:Fe}):o>=50?i.push({type:"neutral",title:"Mixed Analyst Sentiment",description:`${Math.round(o)}% of analysts have buy ratings`,icon:gi}):i.push({type:"negative",title:"Weak Analyst Support",description:`${Math.round(o)}% of analyst ratings are positive`,icon:Ee}),a!==null&&(a>20?i.push({type:"positive",title:"High Upside Potential",description:`${a.toFixed(1)}% upside to analyst targets`,icon:Ye}):a>0?i.push({type:"neutral",title:"Modest Upside Potential",description:`${a.toFixed(1)}% upside to analyst targets`,icon:hs}):i.push({type:"negative",title:"Limited Upside",description:`${Math.abs(a).toFixed(1)}% below analyst targets`,icon:Qs})),n.length>0&&(n.every(c=>c.revenueGrowth&&c.epsGrowth&&c.revenueGrowth>0&&c.epsGrowth>0)?i.push({type:"positive",title:"Consistent Growth Expected",description:"Analysts forecast positive revenue and earnings growth",icon:Fe}):i.push({type:"negative",title:"Inconsistent Growth",description:"Mixed growth expectations across forecast periods",icon:Ee})),i}const Oc={positive:"success",neutral:"info",negative:"error"};function Ec({consensusRating:s,targetUpside:t,totalAnalysts:a,ratings:n,forecasts:i}){const r=Tc(n,a,t,i),o=n.strongBuy+n.buy,l=a>0?o/a*100:0;return e.jsxs("section",{className:"mt-6 space-y-6",children:[e.jsx("div",{children:e.jsxs(T,{as:"h3",size:"5",weight:"semibold",children:["Analyst Rating Summary"," ",e.jsx(T,{as:"span",size:"1",color:"cautionary",children:"(Not investment advice)"})]})}),e.jsxs("div",{children:[e.jsx(T,{as:"h4",size:"3",weight:"semibold",className:"mb-3",children:"Key Value Signals"}),e.jsx(fs,{gap:"sm",children:r.map((c,m)=>e.jsxs(J,{tone:Oc[c.type],icon:c.icon,children:[e.jsx(J.Title,{children:c.title}),e.jsx(J.Description,{children:c.description})]},m))})]}),e.jsxs("div",{children:[e.jsx(T,{as:"h4",size:"3",weight:"semibold",className:"mb-3",children:"Value Investment Considerations"}),e.jsxs(fs,{gap:"xs",children:[e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[e.jsx("div",{className:"w-2 h-2 bg-primary rounded-full mt-2 shrink-0"}),e.jsxs("div",{children:[e.jsx("strong",{children:"Analyst Consensus:"})," ",s," rating from ",a," ","analysts suggests",l>=70?" strong institutional confidence":l>=50?" moderate institutional support":" limited institutional enthusiasm"]})]}),t!==null&&e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[e.jsx("div",{className:"w-2 h-2 bg-primary rounded-full mt-2 shrink-0"}),e.jsxs("div",{children:[e.jsx("strong",{children:"Margin of Safety:"})," Current price offers",t>15?" significant":t>5?" moderate":" limited"," ","margin of safety based on analyst valuations (",t>0?`${t.toFixed(1)}% upside`:`${Math.abs(t).toFixed(1)}% premium`,")"]})]}),e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[e.jsx("div",{className:"w-2 h-2 bg-primary rounded-full mt-2 shrink-0"}),e.jsxs("div",{children:[e.jsx("strong",{children:"Growth Quality:"}),i.length>0?i.every(c=>c.revenueGrowth&&c.epsGrowth&&c.revenueGrowth>0&&c.epsGrowth>0)?" Analysts expect consistent revenue and earnings growth":" Mixed growth expectations warrant careful analysis":" Limited forecast data available for growth assessment"]})]})]})]}),e.jsx(J,{tone:"neutral",children:e.jsxs(J.Description,{children:[e.jsx("strong",{children:"Educational Context:"})," Analyst ratings represent opinions, not advice. This summary shows how traditional value investing frameworks interpret analyst consensus data. Always conduct your own research."]})})]})}function Ft(s,t){return s==null||t==null||t===0?null:(s-t)/t*100}function Pc(s,t){if(!s.length)return[];const a=[...s].sort((l,c)=>l.date.localeCompare(c.date)),n=new Date;n.setMonth(n.getMonth()-t);const i=n.toISOString().slice(0,10),r=a.filter(l=>l.date>=i),o=new Map;for(const l of r){const c=l.date.slice(0,7);o.set(c,l)}return Array.from(o.values())}function hn(s){const t=new Date(s);return isNaN(t.getTime())?s:t.toLocaleDateString("en-US",{month:"short",year:"2-digit"})}function $c(s,t,a,n,i){const o=Pc(s,12).map(y=>({date:y.date,price:y.price,lowTarget:null,avgTarget:null,highTarget:null})),l=new Date,c=l.toISOString().slice(0,10),m={date:c,price:t,lowTarget:a!=null?t:null,avgTarget:n!=null?t:null,highTarget:i!=null?t:null},h=[];for(let y=1;y<=12;y++){const j=new Date(l.getFullYear(),l.getMonth()+y,1),u=y/12;h.push({date:j.toISOString().slice(0,10),price:null,lowTarget:a!=null?t+(a-t)*u:null,avgTarget:n!=null?t+(n-t)*u:null,highTarget:i!=null?t+(i-t)*u:null})}return{chartData:[...o,m,...h],forecastStartDate:c}}function Lc({currentPrice:s,averagePriceTarget:t,lowPriceTarget:a,highPriceTarget:n,medianPriceTarget:i,symbol:r}){const{data:o,isLoading:l}=zt(r,{dataScope:"analysis",enabled:!!r}),m=(o?.data??o)?.historical??[],h=e.jsx(W,{size:"5",title:e.jsxs(ss,{gap:"sm",align:"center",children:[e.jsx(ii,{icon:Ye,size:"md",decorative:!0}),e.jsx("span",{children:"Price Target Analysis"})]})});if(!(t!=null||a!=null||n!=null||i!=null))return e.jsxs("section",{className:"space-y-4",children:[h,e.jsx(xt,{icon:Ye,title:"No price targets available",description:`No analyst price targets are currently published for ${r}.`})]});const j=s!=null&&m.length>0&&(a!=null||t!=null||n!=null),{chartData:u,forecastStartDate:f}=j?$c(m,s,a,t,n):{chartData:[],forecastStartDate:null};return e.jsxs("section",{className:"space-y-4",children:[h,j?e.jsx("div",{className:"h-80",children:e.jsx(ke,{width:"100%",height:"100%",children:e.jsxs(As,{data:u,margin:{top:20,right:88,left:20,bottom:20},children:[e.jsx(Ve,{strokeDasharray:"3 3",className:"stroke-muted"}),e.jsx(Le,{dataKey:"date",tick:{fontSize:12},tickFormatter:hn,interval:"preserveStartEnd",minTickGap:40}),e.jsx(Me,{...Js,domain:[g=>Math.floor(g*.9),g=>Math.ceil(g*1.1)],tick:{fontSize:12},tickFormatter:g=>`$${Math.round(g)}`}),e.jsx(Pe,{labelFormatter:g=>hn(g),formatter:g=>typeof g=="number"?`$${g.toFixed(2)}`:g,contentStyle:{backgroundColor:"hsl(var(--popover))",border:"1px solid hsl(var(--border))",borderRadius:8,fontSize:12}}),e.jsx(Se,{type:"monotone",dataKey:"price",name:"Historical price",stroke:"hsl(var(--gain))",strokeWidth:2.5,dot:{fill:"hsl(var(--gain))",r:3},connectNulls:!1,isAnimationActive:!1}),e.jsx(Se,{type:"monotone",dataKey:"lowTarget",name:"Low target",stroke:"hsl(var(--loss))",strokeWidth:2,strokeDasharray:"5 5",dot:!1,connectNulls:!0,isAnimationActive:!1}),e.jsx(Se,{type:"monotone",dataKey:"avgTarget",name:"Average target",stroke:"hsl(var(--muted-foreground))",strokeWidth:2,strokeDasharray:"5 5",dot:!1,connectNulls:!0,isAnimationActive:!1}),e.jsx(Se,{type:"monotone",dataKey:"highTarget",name:"High target",stroke:"hsl(var(--primary))",strokeWidth:2,strokeDasharray:"5 5",dot:!1,connectNulls:!0,isAnimationActive:!1}),f&&e.jsx(Mt,{x:f,stroke:"hsl(var(--border))",strokeDasharray:"2 2",label:{value:"Today",position:"top",fill:"hsl(var(--muted-foreground))",fontSize:11}}),n!=null&&e.jsx(Xt,{x:u[u.length-1]?.date,y:n,r:0,label:{value:`High $${Math.round(n)}
2`,position:"right",offset:8,fill:"hsl(var(--primary))",fontSize:11,fontWeight:500}}),t!=null&&e.jsx(Xt,{x:u[u.length-1]?.date,y:t,r:0,label:{value:`Avg $${Math.round(t)}`,position:"right",offset:8,fill:"hsl(var(--muted-foreground))",fontSize:11,fontWeight:500}}),a!=null&&e.jsx(Xt,{x:u[u.length-1]?.date,y:a,r:0,label:{value:`Low $${Math.round(a)}`,position:"right",offset:8,fill:"hsl(var(--loss))",fontSize:11,fontWeight:500}})]})})}):l?e.jsx(be,{className:"h-80 w-full"}):null,j&&e.jsx(T,{size:"1",color:"muted",children:"Historical line is real market data (past 12 months, monthly closes). Target lines are a linear glide from today's price to each real 12-month analyst target — a visual aid, not an analyst-issued monthly trajectory."}),a!=null&&n!=null&&e.jsx(bo,{low:a,current:s??null,high:n,size:"lg",showLabels:!0,showPercentage:!0,percentageLabel:"Analyst Target Range",gradient:!0}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3 md:gap-4",children:[e.jsx("div",{className:"border rounded-lg p-3 md:p-4",children:e.jsx(O,{size:"sm",label:"Low",value:a!=null?`$${a.toFixed(2)}`:"N/A",delta:Ft(a,s),deltaFormat:"percent",deltaPrecision:1})}),e.jsx("div",{className:"border rounded-lg p-3 md:p-4",children:e.jsx(O,{size:"sm",label:"Average",value:t!=null?`$${t.toFixed(2)}`:"N/A",delta:Ft(t,s),deltaFormat:"percent",deltaPrecision:1})}),e.jsx("div",{className:"border rounded-lg p-3 md:p-4",children:e.jsx(O,{size:"sm",label:"Median",value:i!=null?`$${i.toFixed(2)}`:"N/A",delta:Ft(i,s),deltaFormat:"percent",deltaPrecision:1})}),e.jsx("div",{className:"border rounded-lg p-3 md:p-4",children:e.jsx(O,{size:"sm",label:"High",value:n!=null?`$${n.toFixed(2)}`:"N/A",delta:Ft(n,s),deltaFormat:"percent",deltaPrecision:1})})]}),s!=null&&e.jsxs(T,{size:"1",color:"muted",children:["% change is measured against the current price of $",s.toFixed(2),"."]})]})}const It=10;function Mc(s){const t=s.toLowerCase();return t.includes("buy")?"success":t.includes("sell")?"error":t.includes("hold")?"warning":"neutral"}function Dc(s){const t=s.toLowerCase();return t.includes("buy")?e.jsx(Ye,{className:"h-3 w-3"}):t.includes("sell")?e.jsx(Qs,{className:"h-3 w-3"}):e.jsx(pi,{className:"h-3 w-3"})}function ra(s){return s===null?"N/A":`$${s.toFixed(2)}`}function qc(s){return s===null?"N/A":`${s>=0?"+":""}${s.toFixed(1)}%`}function Bc(s){return new Date(s).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})}function Rt(){return e.jsx(W,{size:"5",title:e.jsxs(ss,{gap:"sm",align:"center",children:[e.jsx(ii,{icon:Ks,size:"md",decorative:!0}),e.jsx("span",{children:"Stock Review"})]}),subtitle:"Analyst ratings, forecasts, and consensus"})}function zc({symbol:s,currentPrice:t}){const[a,n]=E.useState(1);E.useEffect(()=>{n(1)},[s]);const{data:i,isLoading:r,error:o}=yt({queryKey:["stock-review",s],queryFn:async()=>{console.log(`🔍 Fetching analyst data for ${s}`);const{data:v,error:M}=await He.functions.invoke("fmp-analyst-data",{body:{symbol:s}});if(console.log("📊 Analyst data response:",{data:v,error:M}),M)throw console.error("❌ Error fetching analyst data:",M),M;return v},enabled:!!s,staleTime:30*60*1e3,gcTime:60*60*1e3,retry:1});if(r)return e.jsxs("section",{className:"space-y-4",children:[e.jsx(Rt,{}),e.jsxs(fs,{gap:"md",children:[e.jsx(be,{className:"h-8 w-full"}),e.jsx(be,{className:"h-40 w-full"}),e.jsx(be,{className:"h-20 w-full"})]})]});if(o||!i)return e.jsxs("section",{className:"space-y-4",children:[e.jsx(Rt,{}),e.jsxs(T,{color:"muted",children:["Unable to load analyst data for ",s]})]});if(i.totalAnalysts===0)return e.jsxs("section",{className:"space-y-4",children:[e.jsx(Rt,{}),e.jsx(xt,{icon:Ks,title:"No Analyst Coverage",description:"This stock is not currently covered by professional analysts. Analyst ratings and forecasts are not available at this time."})]});const l=Math.max(1,Math.ceil(i.analystRatings.length/It)),c=Math.min(a,l),m=(c-1)*It,h=i.analystRatings.slice(m,m+It),y=[{id:"period",header:"Period",accessor:v=>v.period,cell:v=>e.jsx("span",{className:"font-medium",children:v.period}),align:"left",sticky:!0},{id:"revenue",header:"Revenue",accessor:v=>v.revenue,cell:v=>v.revenue?`$${(v.revenue/1e9).toFixed(2)}B`:"N/A",align:"right"},{id:"revenueGrowth",header:"Revenue Growth",accessor:v=>v.revenueGrowth,cell:v=>v.revenueGrowth==null?e.jsx("span",{className:"text-muted-foreground",children:"N/A"}):e.jsx(Jt,{value:v.revenueGrowth,format:"percent",precision:1,size:"2",className:"justify-end"}),align:"right"},{id:"eps",header:"EPS",accessor:v=>v.eps,cell:v=>
2ra(v.eps),align:"right"},{id:"epsGrowth",header:"EPS Growth",accessor:v=>v.epsGrowth,cell:v=>v.epsGrowth==null?e.jsx("span",{className:"text-muted-foreground",children:"N/A"}):e.jsx(Jt,{value:v.epsGrowth,format:"percent",precision:1,size:"2",className:"justify-end"}),align:"right"}],j=[{label:"Strong Buy",count:i.ratings.strongBuy,fill:"bg-gain"},{label:"Buy",count:i.ratings.buy,fill:"bg-gain/70"},{label:"Hold",count:i.ratings.hold,fill:"bg-cautionary"},{label:"Sell",count:i.ratings.sell,fill:"bg-loss/70"},{label:"Strong Sell",count:i.ratings.strongSell,fill:"bg-loss"}],u=Date.now(),f=i.forecasts.findIndex(v=>{const M=new Date(v.period).getTime();return!isNaN(M)&&M>=u}),g=f>=0?i.forecasts[f]:i.forecasts[i.forecasts.length-1],x=f>0?i.forecasts[f-1]:null,S=f>=0&&f+1<i.forecasts.length?i.forecasts[f+1]:null,k=v=>{if(!v?.period)return"";const M=new Date(v.period).getUTCFullYear();return isNaN(M)?"":` (FY${M})`},w=v=>v?`$${(v/1e9).toFixed(1)}B`:"N/A",p=v=>v?`$${v.toFixed(2)}`:"N/A";return e.jsxs("section",{className:"space-y-4",children:[e.jsx(Rt,{}),e.jsxs(Es,{defaultValue:"ratings",className:"w-full",children:[e.jsxs(Ps,{children:[e.jsx(me,{value:"ratings",children:"Analyst Ratings"}),e.jsx(me,{value:"forecast",children:"Analyst Forecast"})]}),e.jsxs(re,{value:"ratings",className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3 md:gap-4",children:[e.jsx(_e,{variant:"subtle",padding:{base:"sm",md:"md"},children:e.jsx(O,{align:"center",size:"md",label:"Total Analysts",value:i.totalAnalysts})}),e.jsx(_e,{variant:"subtle",padding:{base:"sm",md:"md"},children:e.jsx(O,{align:"center",size:"sm",label:"Consensus Rating",value:i.consensusRating})}),e.jsx(_e,{variant:"subtle",padding:{base:"sm",md:"md"},children:e.jsx(O,{align:"center",size:"sm",label:"Price Target",value:ra(i.averagePriceTarget)})}),e.jsx(_e,{variant:"subtle",padding:{base:"sm",md:"md"},children:e.jsx(O,{align:"center",size:"sm",label:"Upside",value:qc(i.targetUpside),valueColor:i.targetUpside==null?"foreground":i.targetUpside>=0?"gain":"loss"})})]}),e.jsxs("div",{children:[e.jsx(gt,{as:"h4",size:"3",weight:"semibold",className:"mb-3",children:"Rating Distribution"}),e.jsx(fs,{gap:"sm",children:j.map(v=>e.jsxs(ss,{gap:"md",align:"center",children:[e.jsx("div",{className:"w-20 text-sm",children:v.label}),e.jsx("div",{className:"flex-1 bg-muted rounded-full h-2 relative max-w-full overflow-hidden",children:e.jsx("div",{className:`h-2 rounded-full ${v.fill}`,style:{width:`${v.count/i.totalAnalysts*100}%`}})}),e.jsx("div",{className:"w-8 text-sm text-right tabular-nums",children:v.count})]},v.label))})]}),e.jsx(bs,{}),e.jsxs("div",{children:[e.jsx(gt,{as:"h4",size:"3",weight:"semibold",className:"mb-3",children:"Recent Analyst Ratings"}),i.analystRatings.length===0?e.jsx(xt,{icon:Nt,title:"No recent analyst ratings available"}):e.jsxs(e.Fragment,{children:[e.jsx(fs,{gap:"sm",children:h.map((v,M)=>e.jsx(_e,{variant:"flat",padding:"md",children:e.jsxs(fs,{gap:"sm",children:[e.jsxs(ss,{justify:"between",align:"start",children:[e.jsxs(fs,{gap:"2xs",children:[e.jsx(T,{weight:"medium",children:v.analyst}),e.jsxs(ss,{gap:"xs",align:"center",children:[e.jsx(Nt,{className:"h-3 w-3 text-muted-foreground"}),e.jsx(T,{size:"2",color:"muted",children:v.firm})]})]}),e.jsxs(fs,{gap:"2xs",align:"end",children:[e.jsx(D,{tone:Mc(v.rating),intensity:"solid",children:e.jsxs("span",{className:"flex items-center gap-1",children:[Dc(v.rating),v.rating]})}),e.jsxs(ss,{gap:"xs",align:"center",children:[e.jsx(Oa,{className:"h-3 w-3 text-muted-foreground"}),e.jsx(T,{size:"2",color:"muted",children:Bc(v.date)})]})]})]}),e.jsxs(ss,{justify:"between",align:"center",children:[e.jsxs(ss,{gap:"xs",align:"center",children:[e.jsx(T,{size:"2",color:"muted",children:"Action:"}),e.jsx(T,{size:"2",children:v.action})]}),e.jsxs(ss,{gap:"md",align:"center",children:[v.priceTarget&&e.jsxs(ss,{gap:"xs",align:"center",children:[e.jsx(hs,{className:"h-3 w-3"}),e.jsxs(T,{size:"2",children:["Target: ",ra(v.priceTarget)]})]}),v.upside!==null&&e.jsx(Jt,{value:v.upside,format:"percent",precision:1,size:"2"})]})]})]})},m+M))}),l>1&&e.jsx("div",{className:"mt-4",children:e.jsx(zr,{page:c,pageSize:It,total:i.analystRatings.length,onPageChange:n,variant:"compact",size:"sm"})})]})]}),e.jsx(Ec,{symbol:s,consensusRating:i.consensusRating,averagePriceTarget:i.averagePriceTarget,targetUpside:i.targetUpside,totalAnalysts:i.totalAnalysts,ratings:i.ratings,analystRatings:i.analystRatings,forecasts:i.forecasts})]}),e.jsxs(re,{value:"forecast",className:"space-y-6",children:[i.forecasts.length>=2&&e.jsxs("div",{children:[e.jsx(gt,{as:"h4",size:"3",weight:"semibold",className:"mb-3",children:"Financial Forecast"}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3 md:gap-4 mb-6",children:[e.jsx(_e,{variant:"flat",padding:{base:"sm",md:"md"},children:e.jsx(O,{size:"sm",label:`Revenue This Year${k(g)}`,value:w(g?.revenue),delta:g?.revenueGrowth??void 0,deltaFormat:"percent",deltaPrecision:1,subtext:x?.revenue?`from ${w(x.revenue)}${k(x)}`:void 0})}),e.jsx(_e,{variant:"flat",padding:{base:"sm",md:"md"},children:e.jsx(O,{size:"sm",label:`Revenue Next Year${k(S)}`,value:w(S?.revenue),delta:S?.revenueGrowth??void 0,deltaFormat:"percent",deltaPrecision:1,subtext:g?.revenue?`from ${w(g.revenue)}${k(g)}`:void 0})}),e.jsx(_e,{variant:"flat",padding:{base:"sm",md:"md"},children:e.jsx(O,{size:"sm",label:`EPS This Year${k(g)}`,value:p(g?.eps),delta:g?.epsGrowth??void 0,deltaFormat:"percent",deltaPrecision:1,subtext:x?.eps?`from ${p(x.eps)}${k(x)}`:void 0})}),e.jsx(_e,{variant:"flat",padding:{base:"sm",md:"md"},children:e.jsx(O,{size:"sm",label:`EPS Next Year${k(S)}`,value:p(S?.eps),delta:S?.epsGrowth??void 0,deltaFormat:"percent",deltaPrecision:1,subtext:g?.eps?`from ${p(g.eps)}${k(g)}`:void 0})})]})]}),e.jsx(Lc,{currentPrice:t,averagePriceTarget:i.averagePriceTarget,lowPriceTarget:i.lowPriceTarget,highPriceTarget:i.highPriceTarget,medianPriceTarget:i.medianPriceTarget,targetUpside:i.targetUpside,symbol
2:s}),e.jsxs("div",{children:[e.jsx(gt,{as:"h4",size:"3",weight:"semibold",className:"mb-3",children:"Analyst Forecasts"}),e.jsxs(T,{size:"2",color:"muted",className:"mb-4",children:["Revenue and earnings estimates from ",i.totalAnalysts," covering analysts"]})]}),e.jsx(Ss,{columns:y,data:i.forecasts,getRowKey:(v,M)=>M,density:"sm",variant:"elevated",mobileVariant:"scroll",empty:e.jsx(xt,{icon:Eo,title:"No forecast data available",description:s})})]})]})]})}function Gc(s){switch(s){case"related":return"bg-green-600";case"adjacent":return"bg-yellow-600";case"unrelated":return"bg-red-600";default:return"bg-gray-600"}}function Vc(s){switch(s){case"highly_focused":return"Company maintains sharp focus on core competency";case"moderately_focused":return"Company has some diversification but remains coherent";case"diversified":return"Company operates across multiple business lines";case"over_diversified":return"Excessive diversification risks conglomerate discount";default:return"Unknown"}}function Yc(s){switch(s){case"low":return"bg-green-600";case"medium":return"bg-yellow-600";case"high":return"bg-red-600";default:return"bg-gray-600"}}function Uc({data:s,confidence:t}){const[a,n]=E.useState(!1);if(!s||!s.core_business)return null;const i=o=>{switch(o){case"high":return e.jsx(D,{className:"bg-green-600 text-white text-xs",children:"High Confidence"});case"medium":return e.jsx(D,{className:"bg-yellow-600 text-white text-xs",children:"Medium Confidence"});case"low":return e.jsx(D,{className:"bg-orange-600 text-white text-xs",children:"Low Confidence"});default:return null}},r=o=>{switch(o){case"growing":return e.jsx(Ye,{className:"w-4 h-4 text-green-600"});case"declining":return e.jsx(Qs,{className:"w-4 h-4 text-red-600"});default:return e.jsx("span",{className:"text-muted-foreground",children:"—"})}};return e.jsxs(le,{className:"border-l-4 border-l-primary/30",children:[e.jsx(pe,{children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsxs(ge,{className:"text-base flex items-center gap-2",children:[e.jsx(hs,{className:"w-5 h-5 text-primary"}),"Business Focus & Circle of Competence"]}),e.jsx(ts,{children:"Analysis of business diversification and strategic focus using Buffett-Munger principles"}),t&&e.jsx("div",{className:"mt-2",children:i(t)})]}),e.jsx(ye,{variant:"ghost",size:"sm",onClick:()=>n(!a),className:"flex items-center gap-1",children:a?e.jsxs(e.Fragment,{children:["Hide Details ",e.jsx(Po,{className:"w-4 h-4"})]}):e.jsxs(e.Fragment,{children:["Show Details ",e.jsx(ui,{className:"w-4 h-4"})]})})]})}),e.jsxs(ce,{className:"space-y-4",children:[e.jsx("div",{className:"p-4 bg-primary/5 border-2 border-primary/20 rounded-lg",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Nt,{className:"w-6 h-6 text-primary mt-1"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsxs("h3",{className:"font-semibold text-lg",children:["Core Business: ",s.core_business.name]}),r(s.core_business.trend)]}),e.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:s.core_business.description}),e.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Revenue: "}),e.jsxs("span",{className:"font-semibold",children:[s.core_business.revenue_pct.toFixed(1),"%"]})]}),s.core_business.years_established&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Established: "}),e.jsxs("span",{className:"font-semibold",children:[s.core_business.years_established,"+ years"]})]})]})]})]})}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsx(le,{className:"border-l-4 border-l-primary/30",children:e.jsxs(ce,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("span",{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(hs,{className:"w-4 h-4 text-primary"}),"Focus Rating"]}),e.jsx(D,{className:"bg-blue-600 text-white capitalize",children:s.focus_rating.replace("_"," ")})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Vc(s.focus_rating)})]})}),e.jsx(le,{className:"border-l-4 border-l-primary/30",children:e.jsxs(ce,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("span",{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Ee,{className:"w-4 h-4 text-primary"}),"Diversification Risk"]}),e.jsx(D,{className:`${Yc(s.diversification_risk)} text-white uppercase`,children:s.diversification_risk})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Circle of Competence: ",s.circle_of_competence_adherence]})]})})]}),s.score_adjustments.total_impact!==0&&e.jsxs(us,{className:s.score_adjustments.total_impact>0?"border-green-500":"border-red-500",children:[e.jsx(gi,{className:"h-4 w-4"}),e.jsxs(vs,{children:["Score Impact: ",s.score_adjustments.total_impact>0?"+":"",s.score_adjustments.total_impact," points"]}),e.jsx(ms,{className:"text-sm",children:s.score_adjustments.explanation})]}),a&&e.jsxs("div",{className:"space-y-4 pt-4 border-t",children:[s.expansion_ventures.length>0&&e.jsxs(le,{children:[e.jsxs(pe,{children:[e.jsx(ge,{className:"text-base",children:"Expansion Ventures"}),e.jsx(ts,{children:"New business lines and strategic fit assessment"})]}),e.jsx(ce,{className:"space-y-3",children:s.expansion_ventures.map((o,l)=>e.jsxs("div",{className:"p-3 border-l-4 border-l-primary/30 bg-muted/30 rounded",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2 mb-2",children:[e.jsx("h4",{className:"font-semibold text-sm",children:o.name}),e.jsx(D,{className:`${Gc(o.strategic_fit)} text-white text-xs`,children:o.strategic_fit.toUpperCase()})]}),e.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:o.description}),e.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1 text-xs",children:[e.jsxs("span",{children:[e.jsx("strong",{children:"Revenue:"})," ",o.revenue_pct.toFixed(1),"%"]}),e.jsxs("span",{children:[e.jsx("strong",{children:"Active:"})," ",o.years_active," years"]}),e.jsxs("span",{className:"capitalize",children:[e.jsx("strong",{children:"Status:"})," ",o.profitability_status.replace("_"," ")]})]}),e.jsxs("div",{className:"mt-2 text-xs",children:[e.jsx("strong",{children:"Classification Reasoning:"})," ",o.strategic_fit_reasoning]})]},l))})]}),s.segments.length>0&&e.jsxs(le,{children:[e.jsxs(pe,{children:[e.jsx(ge,{className:"text-base",children:"All Business Segments"}),e.jsx(ts,{children:"Complete revenue breakdown by segment"})]}),e.jsx(ce,{children:e.jsx("div",{className:"space-y-2",children:s.segments.map((o,l)=>e.jsxs("div",{className:"flex items-center justify-between p-2 bg-muted/30 rounded",children:[e.jsx("span",{className:"text-sm font-medium",children:o.name}),e.jsxs("div",{className:"flex items-center gap-3",children:[o.yoy_growth_pct!==void 0&&o.yoy_growth_pct!==null&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["Growth: ",o.yoy_growth_pct>0?"+":"",o.yoy_growth_pct.toFixed(1),"%"]}),e.jsxs("span",{className:"text-sm font-semibold",children:[o.revenue_pct.toFixed(1),"%"]})]})]},l))})})]}
2),(s.empire_building_concerns||s.conglomerate_discount_risk)&&e.jsxs(us,{variant:"destructive",children:[e.jsx(ys,{className:"h-4 w-4"}),e.jsx(vs,{children:"Red Flags Detected"}),e.jsx(ms,{children:e.jsxs("ul",{className:"list-disc list-inside text-sm space-y-1 mt-2",children:[s.empire_building_concerns&&e.jsx("li",{children:"Empire building concerns: Multiple unprofitable ventures suggest poor capital allocation"}),s.conglomerate_discount_risk&&e.jsx("li",{children:"Conglomerate discount risk: Over-diversification may lead to valuation discount"})]})})]}),e.jsxs(le,{className:"border-primary/50 bg-primary/5",children:[e.jsx(pe,{children:e.jsx(ge,{children:"Understanding Circle of Competence"})}),e.jsx(ce,{children:e.jsxs("ul",{className:"space-y-2 text-sm",children:[e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx(Fe,{className:"w-4 h-4 mt-0.5 text-primary flex-shrink-0"}),e.jsxs("span",{children:[e.jsx("strong",{children:"Related (Green):"})," Expansion leverages existing competitive advantages and moat"]})]}),e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx(Ee,{className:"w-4 h-4 mt-0.5 text-primary flex-shrink-0"}),e.jsxs("span",{children:[e.jsx("strong",{children:"Adjacent (Yellow):"})," Reasonable extension with some skill overlap but moderate risk"]})]}),e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx(ys,{className:"w-4 h-4 mt-0.5 text-primary flex-shrink-0"}),e.jsxs("span",{children:[e.jsx("strong",{children:"Unrelated (Red):"}),' "Diworsification" - outside circle of competence, high execution risk']})]})]})})]}),s.analysis_notes&&e.jsxs("div",{className:"text-xs text-muted-foreground p-3 bg-muted/30 rounded",children:[e.jsx("strong",{children:"Analysis Notes:"})," ",s.analysis_notes]})]})]})]})}function Wc({onPoll:s,interval:t=2e3,maxInterval:a=5e3,enabled:n,onComplete:i,onError:r}){const o=E.useRef(null),l=E.useRef(t),c=E.useRef(!0),m=E.useCallback(()=>{o.current&&(clearTimeout(o.current),o.current=null)},[]),h=E.useCallback(async()=>{if(c.current)try{if(await s()){m(),i?.();return}c.current&&n&&(l.current=Math.min(l.current*1.2,a),o.current=setTimeout(h,l.current))}catch(y){console.error("Polling error:",y),r?.(y),m()}},[s,n,a,i,r,m]);return E.useEffect(()=>(c.current=!0,n&&(l.current=t,o.current=setTimeout(h,t)),()=>{c.current=!1,m()}),[n,t,h,m]),{stopPolling:m}}const Hc={fetching:{label:"Fetching 10-K HTML from SEC...",icon:e.jsx($s,{className:"w-5 h-5"}),estimatedDuration:30},analyzing:{label:"Comprehensive analysis...",icon:e.jsx($o,{className:"w-5 h-5"}),estimatedDuration:120},generating:{label:"DCF valuation & scoring...",icon:e.jsx(Lo,{className:"w-5 h-5"}),estimatedDuration:30},complete:{label:"Analysis complete!",icon:e.jsx(Fe,{className:"w-5 h-5 text-gain"}),estimatedDuration:0}};function _i({isOpen:s,symbol:t,fiscalYear:a,analysisId:n,onClose:i}){console.log("[AnalysisProgressModal] Component render with props:",{isOpen:s,symbol:t,fiscalYear:a,analysisId:n,timestamp:new Date().toISOString()});const r=Ea(),[o,l]=E.useState("fetching"),[c,m]=E.useState(0),[h,y]=E.useState(0),[j,u]=E.useState(!1),[f,g]=E.useState(!1),[x]=E.useState(Date.now()),S=!0,k=Hc;console.log("[AnalysisProgressModal] Using analysis version:","V2"),E.useEffect(()=>(console.log("[🔍 DIAGNOSTIC] ========================================"),console.log("[🔍 DIAGNOSTIC] AnalysisProgressModal MOUNTED at",new Date().toISOString()),console.log("[🔍 DIAGNOSTIC] Initial props:",{isOpen:s,symbol:t,fiscalYear:a,analysisId:n}),()=>{console.log("[🔍 DIAGNOSTIC] ========================================"),console.log("[🔍 DIAGNOSTIC] AnalysisProgressModal UNMOUNTED at",new Date().toISOString())}),[]),E.useEffect(()=>{console.log("[🔍 DIAGNOSTIC] isOpen prop changed (useEffect triggered):",{isOpen:s,previousValue:"unknown",timestamp:new Date().toISOString()}),console.log("[AnalysisProgressModal] isOpen prop changed:",{isOpen:s,symbol:t,fiscalYear:a,analysisId:n,timestamp:new Date().toISOString()}),console.log(s?"[🔍 DIAGNOSTIC] ✅ Modal should be VISIBLE now (isOpen=true)":"[🔍 DIAGNOSTIC] ⚠️  Modal should be HIDDEN (isOpen=false)")},[s,t,a,n]);const w=50;E.useEffect(()=>{if(console.log("[AnalysisProgressModal] Progress effect - isOpen:",s),!s)return;const U=Date.now(),A=setInterval(()=>{const K=Math.floor((Date.now()-U)/1e3);y(K);let ne="fetching",je=0;K<20?(ne="fetching",je=K/20*25):K<80?(ne="analyzing",je=25+(K-20)/60*50):(ne="generating",je=75+Math.min((K-80)/120*20,20)),l(ne),m(Math.min(je,95))},500);return()=>clearInterval(A)},[s,S]);const p=async()=>{const U=Math.floor((Date.now()-x)/1e3);if(!n){console.log("[AnalysisProgressModal] No analysisId, checking by symbol and fiscal year");try{const{data:A,error:K}
2=await He.from("stock_10k_analyses").select("id, processing_status, processing_error, total_score").eq("symbol",t.toUpperCase()).eq("fiscal_year",a).is("superseded_by",null).maybeSingle();if(K)return console.error("[AnalysisProgressModal] Error checking by symbol:",K),{shouldStop:!1};if(console.log("[AnalysisProgressModal] Fallback check result:",{id:A?.id,processing_status:A?.processing_status,total_score:A?.total_score,elapsedSeconds:U}),!A)return console.warn("[AnalysisProgressModal] No analysis record found, stopping polling"),{shouldStop:!0};if(A?.processing_status==="completed"||A?.processing_status==="completed_partial"){const ne=parseFloat(A.total_score||"0");return ne>=w?(console.log("[AnalysisProgressModal] Analysis completed with meaningful data:",{totalScore:ne,elapsedSeconds:U,status:A.processing_status}),{shouldStop:!0,status:A.processing_status}):(console.log("[AnalysisProgressModal] Waiting for meaningful score:",{hasMeaningfulScore:`${ne} / ${w}`,status:A.processing_status,elapsedSeconds:U}),{shouldStop:!1})}return A?.processing_status==="failed"?(console.error("[AnalysisProgressModal] Analysis failed:",A.processing_error),u(!0),{shouldStop:!0}):{shouldStop:!1}}catch(A){return console.error("[AnalysisProgressModal] Error in fallback check:",A),{shouldStop:!1}}}try{const{data:A,error:K}=await He.from("stock_10k_analyses").select("processing_status, processing_error, total_score").eq("id",n).single();if(K)return console.error("[AnalysisProgressModal] Error checking analysis status:",K),{shouldStop:!1};if(console.log("[AnalysisProgressModal] Current status:",{processing_status:A?.processing_status,total_score:A?.total_score,elapsedSeconds:U}),A?.processing_status==="completed"||A?.processing_status==="completed_partial"){const ne=parseFloat(A.total_score||"0");return ne>=w?(console.log("[AnalysisProgressModal] Analysis completed with meaningful data:",{totalScore:ne,elapsedSeconds:U,status:A.processing_status}),{shouldStop:!0,status:A.processing_status}):(console.log("[AnalysisProgressModal] Waiting for meaningful score:",{hasMeaningfulScore:`${ne} / ${w}`,status:A.processing_status,elapsedSeconds:U}),{shouldStop:!1})}return A?.processing_status==="failed"?(console.error("[AnalysisProgressModal] Analysis failed:",A.processing_error),u(!0),{shouldStop:!0}):{shouldStop:!1}}catch(A){return console.error("[AnalysisProgressModal] Error in checkAnalysisStatus:",A),{shouldStop:!1}}},v=U=>{if(U==="completed")m(100),l("complete"),setTimeout(async()=>{const A=`/stocks/${t.toUpperCase()}`,K=window.location.pathname,ne=K.toLowerCase().includes(A.toLowerCase());console.log("[AnalysisProgressModal] Completion handling:",{isOnTargetPage:ne,currentPath:K,targetPath:A}),await i(),ne?(console.log("[AnalysisProgressModal] Already on analysis page, data will refresh automatically"),window.dispatchEvent(new CustomEvent("analysis-completed",{detail:{symbol:t,fiscalYear:a}}))):(console.log("[AnalysisProgressModal] Navigating to analysis page"),r(`/stocks/${t.toUpperCase()}?tab=value&subtab=10k&year=${a}`))},1500);else if(U==="completed_partial"){console.log("[AnalysisProgressModal] Analysis completed partially, closing modal without completion animation");const A=`/stocks/${t.toUpperCase()}`,ne=window.location.pathname.toLowerCase().includes(A.toLowerCase());i(),ne?(console.log("[AnalysisProgressModal] Already on analysis page, data will refresh automatically"),window.dispatchEvent(new CustomEvent("analysis-completed",{detail:{symbol:t,fiscalYear:a}}))):(console.log("[AnalysisProgressModal] Navigating to analysis page"),r(`/stocks/${t.toUpperCase()}?tab=value&subtab=10k&year=${a}`))}},[M,L]=jt.useState();Wc({onPoll:async()=>{const U=await p();return U.shouldStop&&U.status&&L(U.status),U.shouldStop},interval:3e3,maxInterval:5e3,enabled:s,onComplete:()=>v(M),onError:U=>{console.error("Polling error:",U)}});const b=U=>{const A=Math.floor(U/60),K=U%60;return`${A}:${K.toString().padStart(2,"0")}`},I=j?"error":o==="complete"?"success":"info",ee=j?Ee:o==="complete"?Fe:Us;return e.jsx(Gr,{open:s,onOpenChange:U=>{U||i()},title:"Processing 10-K Analysis",description:`${t.toUpperCase()} • Fiscal Year ${a}
2`,icon:ee,tone:I,size:"md",footer:j?e.jsxs(e.Fragment,{children:[e.jsx(ye,{onClick:i,variant:"outline",children:"Close"}),e.jsxs(ye,{onClick:()=>{window.location.reload()},variant:"default",children:[e.jsx(Ls,{className:"w-4 h-4 mr-2"}),"Retry Analysis"]})]}):void 0,children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(We,{value:c,className:"h-2"}),e.jsxs("div",{className:"flex justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{children:[Math.round(c),"% complete"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Pt,{className:"w-3 h-3"}),b(h)]})]})]}),e.jsx("div",{className:"space-y-3",children:Object.keys(k).map(U=>{const A=k[U],K=U===o,ne=U==="fetching"?o!=="fetching":U==="analyzing"?["generating","complete"].includes(o):U==="generating"?o==="complete":!1;return e.jsxs("div",{className:`flex items-center gap-3 p-3 rounded-lg border transition-all ${K?"border-primary bg-primary/5 shadow-sm":ne?"border-gain-border bg-gain-subtle":"border-muted bg-muted/30 opacity-50"}`,children:[e.jsx("div",{className:`flex-shrink-0 ${K?"text-primary animate-pulse":ne?"text-gain":"text-muted-foreground"}`,children:ne?e.jsx(Fe,{className:"w-5 h-5"}):A.icon}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-medium text-sm",children:ne?A.label.replace("...",""):A.label}),K&&e.jsxs("div",{className:"text-xs text-muted-foreground mt-0.5",children:["Estimated: ~",A.estimatedDuration,"s"]})]})]},U)})}),f&&!j&&e.jsxs(J,{tone:"info",icon:Us,children:[e.jsx(J.Title,{children:"Retrying Failed Sections..."}),e.jsx(J.Description,{children:"Some sections encountered temporary issues (usually API rate limits). The system is automatically retrying them. This may take a few more minutes."})]}),o==="complete"&&!j&&!f&&e.jsx("div",{className:"text-center text-sm text-muted-foreground",children:"Redirecting to analysis..."}),j&&e.jsxs(J,{tone:"error",icon:Ee,children:[e.jsx(J.Title,{children:"Analysis Failed"}),e.jsx(J.Description,{children:"The analysis encountered an error and could not complete. This can happen with very large 10-K filings, missing data, or server issues. Please try again."})]}),o!=="complete"&&!j&&e.jsx("div",{className:"text-xs text-muted-foreground text-center pt-2 border-t",children:f?"Auto-retry in progress. This may take a few more minutes. You can safely close this window and return later.":"This typically takes 2-3 minutes. You can safely close this window and return later."})]})})}function Qc({isOpen:s,onClose:t,symbol:a,currentYear:n}){const i=Ea(),[r,o]=E.useState(null),[l,c]=E.useState(!1),[m,h]=E.useState(),y=E.useRef(0),j=E.useRef(null),u=Wo();y.current+=1,console.log("[🔍 DIAGNOSTIC] RequestYearModal render #"+y.current,{timestamp:new Date().toISOString(),selectedYear:r,showProgressModal:l,analysisId:m,isOpen:s,timeSinceRequest:j.current?`${Date.now()-j.current}ms`:"N/A"}),E.useEffect(()=>{console.log("[🔍 DIAGNOSTIC] showProgressModal state changed:",{newValue:l,timestamp:new Date().toISOString(),timeSinceRequest:j.current?`${Date.now()-j.current}ms`:"N/A"})},[l]),E.useEffect(()=>{console.log("[🔍 DIAGNOSTIC] selectedYear state changed:",{newValue:r,timestamp:new Date().toISOString(),timeSinceRequest:j.current?`${Date.now()-j.current}ms`:"N/A"})},[r]),E.useEffect(()=>{s||(console.log("[🔍 DIAGNOSTIC] Modal closed, resetting state"),o(null),c(!1),h(void 0),j.current=null)},[s]);const f=new Date().getFullYear(),g=Array.from({length:7},(b,I)=>f-I),x=ml(a,g),S=Object.values(x).some(b=>b.isLoading),k=async()=>{await Promise.all(Object.values(x).map(b=>b.refetch()))},w=g.map(b=>{const I=x[b]?.data;return{year:b,filingAvailable:I?.isAvailable??!1,filingDate:I?.filingDate,filingUrl:I?.filingUrl,hasAnalysis:I?.hasAnalysis??!1,analysisStatus:I?.analysisStatus,canRequest:I?.canRequest??!1}}),p=async b=>{const I=Date.now();j.current=I,console.log("[🔍 DIAGNOSTIC] ========================================"),console.log("[🔍 DIAGNOSTIC] handleRequestAnalysis START at",new Date().toISOString()),console.log("[RequestYearModal] handleRequestAnalysis called:",{symbol:a,year:b,currentSelectedYear:r,currentShowProgressModal:l});try{const ee=Date.now();console.log("[🔍 DIAGNOSTIC] About to use flushSync to force synchronous state update at T+"+(ee-I)+"ms"),Mr.flushSync(()=>{o(b),c(!0)}),console.log("[🔍 DIAGNOSTIC] ✅ flushSync completed at T+"+(Date.now()-I)+"ms"),console.log("[🔍 DIAGNOSTIC] Modal should now be visible in the DOM"),
2console.log("[RequestYearModal] Set selectedYear to:",b),console.log("[RequestYearModal] Setting showProgressModal to true"),console.log("[RequestYearModal] showProgressModal state updated"),console.log("[🔍 DIAGNOSTIC] Closing parent RequestYearModal"),t(),await new Promise(se=>setTimeout(se,50)),console.log("[🔍 DIAGNOSTIC] 50ms paint delay completed at T+"+(Date.now()-I)+"ms");const U=Date.now();console.log("[🔍 DIAGNOSTIC] About to call backend API at T+"+(U-I)+"ms"),console.log("[RequestYearModal] Calling requestMutation.mutateAsync...");const A=await u.mutateAsync({symbol:a.toUpperCase(),fiscalYear:b}),K=Date.now();console.log("[🔍 DIAGNOSTIC] Backend API responded at T+"+(K-I)+"ms"),console.log("[🔍 DIAGNOSTIC] Backend response time: "+(K-U)+"ms"),console.log("[RequestYearModal] Request mutation completed:",A);const ne=A?.id||A?.analysis_id,je=A?.existing===!0;if(console.log("[RequestYearModal] Analysis ID:",ne,"isExisting:",je),h(ne),je){console.log("[RequestYearModal] Analysis already exists, showing feedback then navigating..."),bt({title:"Analysis Already Exists",description:`10-K analysis for ${a} (${b}) is already available.`}),await new Promise(se=>setTimeout(se,800)),console.log("[🔍 DIAGNOSTIC] Existing analysis delay completed, closing modal and navigating"),c(!1),i(`/stocks/${a.toUpperCase()}?tab=value&subtab=10k&year=${b}`);return}bt({title:"Analysis Requested",description:`10-K analysis for ${a} (${b}) has been requested.`}),console.log("[RequestYearModal] Refetching available years..."),await k(),console.log("[RequestYearModal] Refetch complete")}catch(ee){console.error("[RequestYearModal] Error requesting analysis:",ee),c(!1),o(null),bt({title:"Request Failed",description:ee.message||"Failed to request analysis. Please try again.",variant:"destructive"})}},v=b=>{i(`/stocks/${a.toUpperCase()}?tab=value&subtab=10k&year=${b}`),t()},M=()=>{c(!1),h(void 0),o(null),t()},L=b=>{const I=b+1;return`Q1 ${I} (Feb-Mar ${I})`};return e.jsxs(e.Fragment,{children:[e.jsx(Vr,{open:s,onOpenChange:t,children:e.jsxs(Yr,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Ur,{children:[e.jsxs(Wr,{className:"flex items-center gap-2",children:[e.jsx($s,{className:"w-5 h-5 text-primary"}),"Request 10-K Analysis for ",a.toUpperCase()]}),e.jsx(Hr,{children:"Select a fiscal year to request analysis or view existing analyses"})]}),e.jsx("div",{className:"space-y-4 mt-4",children:S?e.jsxs("div",{className:"flex items-center justify-center py-8",children:[e.jsx(Us,{className:"w-6 h-6 animate-spin text-primary"}),e.jsx("span",{className:"ml-2 text-sm text-muted-foreground",children:"Checking availability..."})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2 p-4 bg-muted/50 rounded-lg border",children:[e.jsx(Oa,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{className:"text-sm",children:["Currently viewing: ",e.jsxs("strong",{className:"font-semibold",children:["Fiscal Year ",n]})]})]}),e.jsxs("div",{className:"space-y-4",children:[w.length>0&&e.jsx(pn,{yearStatus:w[0],currentYear:n,isRequesting:u.isPending&&r===w[0].year,onRequest:p,onView:v,estimatedFilingDate:L(w[0].year)},w[0].year),w.length>1&&e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:w.slice(1).map(b=>e.jsx(pn,{yearStatus:b,currentYear:n,isRequesting:u.isPending&&r===b.year,onRequest:p,onView:v,estimatedFilingDate:L(b.year)},b.year))})]}),e.jsxs("div",{className:"flex items-start gap-2 p-3 bg-blue-50 border border-blue-200 rounded-lg mt-2",children:[e.jsx(Ee,{className:"h-4 w-4 text-blue-600 mt-0.5 flex-shrink-0"}),e.jsx("p",{className:"text-xs text-blue-900",children:"10-K filings are typically available 60-90 days after fiscal year end. Analysis takes 2-3 minutes to complete and is cached for all users."})]})]})})]})}),r?e.jsx(_i,{isOpen:l,symbol:a,fiscalYear:r,analysisId:m,onClose:M}):null]})}function pn({yearStatus:s,currentYear:t,isRequesting:a,onRequest:n,onView:i,estimatedFilingDate:r}){const{year:o,filingAvailable:l,hasAnalysis:c,analysisStatus:m,canRequest:h}=s,y=o===t,j=()=>c&&m==="completed"?e.jsxs(D,{variant:"outline",className:"bg-green-100 text-green-800 border-green-300",children:[e.jsx(Fe,{className:"w-3 h-3 mr-1"}),"Completed"]}):m==="processing"||m==="pending"?e.jsxs(D,{variant:"outline",className:"bg-blue-100 text-blue-800 border-blue-300",children:[e.jsx(Us,{className:"w-3 h-3 mr-1 animate-spin"}),m==="pending"?"Queued":"Processing"]}):l?e.jsxs(D,{variant:"outline",className:"bg-blue-100 text-blue-800 border-blue-300",children:[e.jsx($s,{className:"w-3 h-3 mr-1"}),"Available"]}):e.jsxs(D,{variant:"outline",className:"bg-gray-100 text-gray-600 border-gray-300",children:[e.jsx(Pt,{className:"w-3 h-3 mr-1"}),"Coming Soon"]}),u=()=>c&&m==="completed"?y?e.jsxs(ye,{variant:"outline",size:"sm",disabled:!0,className:"w-full",children:[e.jsx(Fe,{className:"w-4 h-4 mr-2"}),"Currently Viewing"]}):e.jsxs(ye,{size:"sm",variant:"default",onClick:()=>i(o),className:"w-full",children:[e.jsx(Mo,{className:"w-4 h-4 mr-2"}),"View Analysis"]}):m==="processing"||m==="pending"?e.jsxs(ye,{variant:"outline",size:"sm",disabled:!0,className:"w-full",children:[e.jsx(Us,{className:"w-4 h-4 mr-2 animate-spin"}),m==="pending"?"Queued":"Processing"]}):h&&l?e.jsx(ye,{size:"sm",variant:"default",onClick:()=>{console.log("[🔍 DIAGNOSTIC] Request button clicked for year:",o),console.log("[🔍 DIAGNOSTIC] isRequesting:",a),console.log("[🔍 DIAGNOSTIC] Calling onRequest..."),n(o)},disabled:a,className:"w-full",children:a?e.jsxs(e.Fragment,{children:[e.jsx(Us,{className:"w-4 h-4 mr-2 animate-spin"}),"Requesting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(fi,{className:"w-4 h-4 mr-2"}),"Request Analysis"]})}):e.jsxs(ye,{variant:"outline",size:"sm",disabled:!0,className:"w-full",children:[e.jsx(Pt,{className:"w-4 h-4 mr-2"}),"Not Available"]}),f=y&&c&&m==="completed";return e.jsx(le,{className:f?"border-primary border-2":"",children:e.jsx(ce,{className:"pt-5 pb-5 px-5",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("h3",{className:"text-lg font-semibold",children:["FY ",o]}),f&&e.jsx(D,{className:"text-xs bg-primary hover:bg-primary/90 text-primary-foreground",children:"VIEWING"})]}),j()]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:l?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Fe,{className:"w-3 h-3 text-primary"}),e.jsx("span",{children:"10-K filing available"})]}):e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Pt,{className:"w-3 h-3"}),e.jsxs("span",{children:["Expected: ",r]})]})}
2),u()]})})})}function Kc({daysRemaining:s}){return e.jsxs(us,{variant:"default",className:"border-yellow-500 bg-yellow-50 dark:bg-yellow-950/20 animate-in fade-in duration-300",children:[e.jsx(Ee,{className:"h-4 w-4 text-yellow-600"}),e.jsx(vs,{children:"Analysis Expiring Soon"}),e.jsxs(ms,{children:["This analysis will expire in ",s," day",s!==1?"s":"",". Consider requesting a refresh for the most current information."]})]})}function Xc({message:s,onRetry:t}){return e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 px-4 animate-in fade-in duration-300",children:[e.jsx("div",{className:"rounded-full bg-red-100 dark:bg-red-950 p-4 mb-4",children:e.jsx(Ee,{className:"w-8 h-8 text-red-600 dark:text-red-400"})}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Something went wrong"}),e.jsx("p",{className:"text-sm text-muted-foreground text-center mb-4 max-w-md",children:s||"An error occurred while loading the data. Please try again."}),t&&e.jsxs(ye,{onClick:t,variant:"outline",size:"sm",children:[e.jsx(Ls,{className:"w-4 h-4 mr-2"}),"Try Again"]})]})}function Jc({businessDescription:s,revenueModel:t,simplicityRating:a}){if(!s&&!t)return null;const n=i=>{switch(i){case"simple":return e.jsx(D,{className:"bg-green-600 text-white",children:"✅ Simple & Understandable"});case"moderate":return e.jsx(D,{className:"bg-yellow-600 text-white",children:"⚠️ Moderately Complex"});case"complex":return e.jsx(D,{className:"bg-red-600 text-white",children:"❌ Complex Business"});default:return null}};return e.jsxs("div",{className:"space-y-4",children:[s&&e.jsxs(le,{children:[e.jsx(pe,{children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsxs(ge,{className:"flex items-center gap-2",children:[e.jsx(Nt,{className:"w-5 h-5"}),"Business Understanding"]}),e.jsx(ts,{children:"Plain-English explanation of what the company does"})]}),a&&n(a)]})}),e.jsx(ce,{children:e.jsx("div",{className:"prose prose-sm max-w-none",children:e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:s})})})]}),t&&e.jsxs(le,{children:[e.jsxs(pe,{children:[e.jsxs(ge,{className:"flex items-center gap-2",children:[e.jsx(Ye,{className:"w-5 h-5"}),"Revenue Model"]}),e.jsx(ts,{children:"How the company makes money"})]}),e.jsx(ce,{children:e.jsx("div",{className:"prose prose-sm max-w-none",children:e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:t})})})]})]})}function Zc({riskScore:s,maxRiskScore:t,debtAssessment:a,recessionSurvivability:n,structuralRisks:i,manageableRisks:r}){const o=x=>x==null?"N/A":x>=1e9?`$${(x/1e9).toFixed(1)}B`:x>=1e6?`$${(x/1e6).toFixed(1)}M`:x>=1e3?`$${(x/1e3).toFixed(1)}K`:`$${x.toFixed(0)}`,l=x=>x==null?"N/A":x.toFixed(2),c=x=>x==null?{label:"Unknown",color:"text-gray-600"}:x<.5?{label:"Excellent - Conservative leverage",color:"text-green-600"}:x<1?{label:"Good - Manageable leverage",color:"text-green-600"}:x<1.5?{label:"Fair - Moderate leverage",color:"text-yellow-600"}:x<2?{label:"Concerning - High leverage",color:"text-orange-600"}:{label:"Critical - Very high leverage",color:"text-red-600"},m=x=>x==null?{label:"Unknown",color:"text-gray-600"}:x>=8?{label:"Excellent - Strong debt coverage",color:"text-green-600"}:x>=5?{label:"Good - Adequate coverage",color:"text-green-600"}:x>=3?{label:"Fair - Acceptable coverage",color:"text-yellow-600"}:x>=1.5?{label:"Concerning - Weak coverage",color:"text-orange-600"}:{label:"Critical - Insufficient coverage",color:"text-red-600"},h=x=>x==null?{label:"Unknown",color:"text-gray-600"}:x>=2?{label:"Excellent - Strong liquidity",color:"text-green-600"}:x>=1.5?{label:"Good - Healthy liquidity",color:"text-green-600"}:x>=1?{label:"Fair - Adequate liquidity",color:"text-yellow-600"}:{label:"Concerning - Weak liquidity",color:"text-red-600"},y=x=>{switch(x){case"strong":return{label:"Strong - Well positioned for downturns",color:"text-green-600",badge:"bg-green-600 text-white"};case"moderate":return{label:"Moderate - Some vulnerability to recession",color:"text-yellow-600",badge:"bg-yellow-600 text-white"};case"weak":return{label:"Weak - Significant recession risk",color:"text-red-600",badge:"bg-red-600 text-white"};default:return{label:"Unknown",color:"text-gray-600",badge:"bg-gray-600 text-white"}}},j=s/t*100,u=()=>j>=75?e.jsx(D,{className:"bg-green-700 text-white",children:"Low Risk"}):j>=50?e.jsx(D,{className:"bg-yellow-600 text-white",children:"Moderate Risk"}):j>=25?e.jsx(D,{className:"bg-orange-600 text-white",children:"High Risk"}):e.jsx(D,{className:"bg-red-600 text-white",children:"Severe Risk"}),f=i?.filter(x=>x.severity==="high").length||0,g=i?.length||0;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(le,{children:[e.jsx(pe,{children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-1",children:[e.jsx(ys,{className:"w-6 h-6 text-primary flex-shrink-0"}),e.jsxs("div",{children:[e.jsx(ge,{className:"text-lg md:text-xl",children:"Risk & Debt Assessment"}),e.jsx(ts,{className:"text-xs md:text-sm",children:"Comprehensive analysis of financial risks and balance sheet strength"})]})]}),e.jsxs(D,{variant:"outline",className:"text-sm font-semibold whitespace-nowrap",children:[s,"/",t," pts"]})]})}),e.jsx(ce,{children:e.jsxs("div",{className:"flex items-center justify-between p-4 bg-primary/5 border-2 border-primary/20 rounded-lg",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(js,{className:"w-8 h-8 text-primary"}),e.jsxs("div",{children:[u(),e.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:["Safety Score: ",Math.round(j),"%"]})]})]}),e.jsxs("div",{className:"text-right",children:[e.jsxs("p",{className:"text-3xl font-bold text-primary",children:[s,"/",t]}),e.jsx(We,{value:j,className:"h-2 w-24 mt-2"})]})]})})]}),g>0&&e.jsxs(le,{className:"border-red-500 bg-red-50/50",children:[e.jsx(pe,{className:"pb-3",children:e.jsxs(ge,{className:"text-base flex items-center gap-2 text-red-700",children:[e.jsx(ys,{className:"w-5 h-5"}),"Critical Risk Alert"]})}),e.jsx(ce,{children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Ee,{className:"w-5 h-5 text-red-600 mt-0.5 flex-shrink-0"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("p",{className:"text-sm text-red-900 font-medium",children:[g," Structural Risk",g>1?"s":""," ","Identified",f>0&&e.jsxs("span",{className:"ml-2",children:["(",f," High Severity)"]})]}),e.jsx("p",{className:"text-xs text-red-800 mt-1",children:"These are fundamental threats to the business model that require careful evaluation. Review the details below before making investment decisions."})]})]})})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs(le,{className:"border-l-4 border-l-primary/30",children:[e.jsx(pe,{className:"pb-3",children:e.jsxs(ge,{className:"text-base flex items-center gap-2",children:[e.jsx(Qs,{className:"w-5 h-5 text-primary"}),"Debt-to-Equity Ratio"]})}),e.jsx(ce,{children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"flex items-baseline gap-2",children:e.jsx("span",{className:"text-3xl font-bold text-primary",children:l(a?.total_debt_to_equity)})}),e.jsx("div",{className:`text-sm font-semibold ${c(a?.total_debt_to_equity).color}`,children:c(a?.total_debt_to_equity).label})]})})]}),e.jsxs(le,{className:"border-l-4 border-l-primary/30",children:[e.jsx(pe,{className:"pb-3",children:e.jsxs(ge,{className:"text-base flex items-center gap-2",children:[e.jsx(js,{className:"w-5 h-5 text-primary"}),"Interest Coverage Ratio"]})}),e.jsx(ce,{children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-baseline gap-2",children:[e.jsx("span",{className:"text-3xl font-bold text-primary",children:l(a?.interest_coverage)}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"x"})]}),e.jsx("div",{className:`text-sm font-semibold ${m(a?.interest_coverage).color}`,children:m(a?.interest_coverage).label})]})})]}),e.jsxs(le,{className:"border-l-4 border-l-primary/30",children:[e.jsx(pe,{className:"pb-3",children:e.jsxs(ge,{className:"text-base flex items-center gap-2",children:[e.jsx(mi,{className:"w-5 h-5 text-primary"}),"Current Ratio"]})}),e.jsx(ce,{children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"flex items-baseline gap-2",children:e.jsx("span",{className:"text-3xl font-bold text-primary",children:l(a?.liquidity?.current_ratio)})}),e.jsx("div",{className:`text-sm font-semibold ${h(a?.liquidity?.current_ratio).color}`,children:h(a?.liquidity?.current_ratio).label})]})})]}),e.jsxs(le,{className:"border-l-4 border-l-primary/30",children:[e.jsx(pe,{className:"pb-3",children:e.jsxs(ge,{className:"text-base flex items-center gap-2",children:[e.jsx(js,{className:"w-5 h-5 text-primary"}),"Recession Survivability"]})}),e.jsx(ce,{children:e.jsxs("div",{className:"space-y-3",children:[e.jsx(D,{className:y(n).badge,children:n?n.charAt(0).toUpperCase()+n.slice(1):"Unknown"}),e.jsx("div",{className:`text-sm font-semibold ${y(n).color}`,children:y(n).label})]})})]}),e.jsxs(le,{className:"border-l-4 border-l-primary/30",children:[e.jsx(pe,{className:"pb-3",children:e.jsxs(ge,{className:"text-base flex items-center gap-2",children:[e.jsx(xi,{className:"w-5 h-5 text-primary"}),"Cash & Equivalents"]})}),e.jsxs(ce,{children:[e.jsx("div",{className:"flex items-baseline gap-2",children:e.jsx("span",{className:"text-3xl font-bold text-primary",children:o(a?.liquidity?.cash)})}),e.jsx("p",{className:"text-xs text-muted-foreground mt-2",children:"Available liquid assets"})]})]}),e.jsxs(le,{className:"border-l-4 border-l-primary/30",children:[e.jsx(pe,{className:"pb-3",children:e.jsxs(ge,{className:"text-base flex items-center gap-2",children:[e.jsx(Qs,{className:"w-5 h-5 text-primary"}),"Total Debt"]})}),e.jsxs(ce,{children:[e.jsx("div",{className:"flex items-baseline gap-2",children:e.jsx("span",{className:"text-3xl font-bold text-primary",children:o(a?.total_debt)})}),e.jsx("p",{className:"text-xs text-muted-foreground mt-2",children:"Total debt obligations"})]})]})]}),e.jsxs(le,{className:"border-primary/50 bg-primary/5",children:[e.jsx(pe,{children:e.jsx(ge,{children:"Key Insights"})}),e.jsx(ce,{children:e.jsxs("ul",{className:"space-y-2 text-sm",children:[e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx(Fe,{className:"w-4 h-4 mt-0.5 text-primary flex-shrink-0"}),e.jsxs("span",{children:[e.jsx("strong",{children:"Risk Assessment:"})," Higher Safety Score indicates better risk management and financial stability"]})]}),e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx(Fe,{className:"w-4 h-4 mt-0.5 text-primary flex-shrink-0"}),e.jsxs("span",{children:[e.jsx("strong",{children:"Leverage Analysis:"})," Low debt-to-equity ratios provide financial flexibility"]})]}),e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx(Fe,{className:"w-4 h-4 mt-0.5 text-primary flex-shrink-0"}),e.jsxs("span",{children:[e.jsx("strong",{children:"Debt Service:"})," Strong interest coverage ensures ability to service debt obligations"]})]}),e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx(Fe,{className:"w-4 h-4 mt-0.5 text-primary flex-shrink-0"}),e.jsxs("span",{children:[e.jsx("strong",{children:"Liquidity Buffer:"})," Adequate cash and current ratio protect against short-term pressures"]})]})]})})]})]})}
2function ed({symbol:s,defaultFiscalYear:t,compact:a=!1}){const n=()=>{const se=new Date,oe=se.getFullYear();return se.getMonth()<3?oe-2:oe-1},[i,r]=E.useState(t||n()),[o,l]=E.useState(!1),[c,m]=E.useState(!1),{toast:h}=ai(),y=Ho(),{data:j,isLoading:u,error:f}=Qo(s),{analysis:g,isLoading:x,error:S,refetch:k,refresh:w,isRefreshing:p}=Ko({symbol:s?.toUpperCase()||"",fiscalYear:i,enabled:!!s}),{data:v,isLoading:M}=zt(s||"",{dataScope:"analysis",enabled:!!s}),L=E.useMemo(()=>v?v?.data||v:null,[v]),b=E.useMemo(()=>g?Xo(g):null,[g]),{priorScores:I,priorLabel:ee}=Jo(s,i),{data:U}=Zo(L?.sector??null),A=E.useMemo(()=>!j||j.length===0?[]:j.map(se=>se.fiscal_year).sort((se,oe)=>oe-se),[j]);jt.useEffect(()=>{A.length>0&&(t&&A.includes(t)?i!==t&&r(t):i!==A[0]&&r(A[0]))},[A,i,t]),jt.useEffect(()=>{const se=g?.processing_status,oe=g?.processing_attempts||0,De=g?.failed_sections||[];se==="processing"||se==="pending"?oe===0?m(!0):(m(!1),h({title:"Retrying failed sections",description:`Retrying ${De.length} section${De.length!==1?"s":""} in the background. You'll see updated data when complete.`,duration:5e3})):(se==="completed"||se==="completed_partial")&&m(!1)},[g?.processing_status,g?.processing_attempts,g?.id,h]);const K=async()=>{await k(),m(!1)},ne=async()=>{if(!g?.id||!g?.failed_sections||g.failed_sections.length===0)return;const se=g.failed_sections;try{h({title:"Retrying Failed Sections",description:`Retrying ${se.length} section${se.length!==1?"s":""} in the background. This may take a few minutes...`,duration:5e3});const oe=await y.mutateAsync({analysisId:g.id,failedSections:se,symbol:s.toUpperCase(),fiscalYear:i});oe.successCount>0&&h({title:"✅ Retry Complete",description:`Successfully retried ${oe.successCount} of ${se.length} section${se.length!==1?"s":""}.`,duration:6e3}),oe.failCount>0&&h({title:"⚠️ Some Sections Failed",description:`${oe.failCount} section${oe.failCount!==1?"s":""} failed to retry. They will be automatically retried later.`,variant:"destructive",duration:6e3})}catch(oe){console.error("[TenKAnalysisDisplay] Error retrying sections:",oe),h({title:"Retry Failed",description:oe.message||"Failed to retry sections. Please try again later.",variant:"destructive",duration:6e3})}},je=se=>{switch(se){case"BUY":return"bg-green-100 text-green-800 border-green-300";case"HOLD":return"bg-blue-100 text-blue-800 border-blue-300";case"CAUTION":return"bg-yellow-100 text-yellow-800 border-yellow-300";case"AVOID":return"bg-red-100 text-red-800 border-red-300";default:return"bg-gray-100 text-gray-800 border-gray-300"}};if(x||u)return a?e.jsxs("div",{className:"space-y-4",children:[e.jsx(be,{className:"h-12 w-full"}),e.jsx(be,{className:"h-64 w-full"})]}):e.jsx(el,{});if(S)return e.jsx(Xc,{error:S,onRetry:k});if(g&&(g.total_score===0||(g.total_score||0)<30))return e.jsxs(le,{className:"border-yellow-200 bg-yellow-50",children:[e.jsxs(pe,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ys,{className:"w-6 h-6 text-yellow-600"}),e.jsx(ge,{className:"text-yellow-900",children:"Analysis Needs Refresh"})]}),e.jsxs(ts,{className:"text-yellow-800",children:["The existing analysis for ",s," (",i,") has incomplete data and needs to be regenerated."]})]}),e.jsxs(ce,{className:"space-y-4",children:[e.jsxs(us,{className:"bg-yellow-100 border-yellow-300",children:[e.jsx(Ee,{className:"h-4 w-4 text-yellow-600"}),e.jsx(ms,{className:"text-yellow-900",children:"This typically happens when an analysis was interrupted during processing. The system will automatically regenerate it when you request it again."})]}),e.jsxs("div",{className:"flex gap-3",children:[e.jsxs(ye,{onClick:()=>l(!0),className:"flex-1",children:[e.jsx(Ls,{className:"w-4 h-4 mr-2"}),"Regenerate Analysis"]}),e.jsx(ye,{variant:"outline",onClick:()=>window.open("mailto:[email protected]","_blank"),children:"Contact Support"})]})]})]});if(!g){if(A.length>0){const oe=A[0];return e.jsxs(le,{children:[e.jsxs(pe,{children:[e.jsxs(ge,{className:"flex items-center gap-2",children:[e.jsx($s,{className:"w-5 h-5"}),"No Analysis for ",i]}),e.jsxs(ts,{children:["No 10-K analysis found for ",s," (",i,"), but ",A.length," other analysis",A.length>1?"es are":" is"," available."]})]}),e.jsxs(ce,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 p-4 bg-blue-50 border border-blue-200 rounded-lg",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("p",{className:"text-sm font-medium text-blue-900",children:["Latest analysis available: ",oe]}),e.jsx("p",{className:"text-xs text-blue-700 mt-1",children:"Click below to view the most recent 10-K analysis"})]}),e.jsxs(ye,{variant:"default",size:"sm",onClick:()=>r(oe),children:["View ",oe," Analysis"]})]}),e.jsxs("div",{className:"pt-4 border-t",children:[e.jsxs("p",{className:"text-sm text-muted-foreground mb-3",children:["Or request a new anal
2ysis for ",i,":"]}),e.jsx(sn,{symbol:s,defaultYear:i,onSuccess:()=>k()})]})]})]})}return e.jsxs(le,{children:[e.jsxs(pe,{children:[e.jsxs(ge,{className:"flex items-center gap-2",children:[e.jsx($s,{className:"w-5 h-5"}),"No Analysis Available"]}),e.jsxs(ts,{children:["No 10-K analysis found for ",s," (",i,")"]})]}),e.jsx(ce,{children:e.jsx(sn,{symbol:s,defaultYear:i,onSuccess:()=>k()})})]})}return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx($s,{className:"w-6 h-6 text-primary"}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h2",{className:"text-2xl font-bold",children:"10-K Analysis"}),A.length>0&&i===A[0]&&e.jsx(D,{variant:"default",className:"bg-green-600 text-white",children:"LATEST"})]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Fiscal Year ",i," • Comprehensive SEC filing analysis"]})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[A.length>1&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Oa,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(Qr,{value:i.toString(),onValueChange:se=>r(parseInt(se)),children:[e.jsx(Kr,{className:"w-32",children:e.jsx(Xr,{placeholder:"Select year"})}),e.jsx(Jr,{children:A.map((se,oe)=>e.jsxs(Zr,{value:se.toString(),children:["FY ",se,oe===0?" (Latest)":""]},se))})]})]}),g?.processing_status!=="processing"&&g?.processing_status!=="pending"&&e.jsxs(ye,{variant:"default",size:"sm",onClick:()=>l(!0),children:[e.jsx(fi,{className:"w-4 h-4 mr-2"}),"Request Analysis"]})]})]}),g&&e.jsxs("div",{className:"flex items-center gap-3 text-sm",children:[e.jsx(gl,{createdAt:g.created_at,cacheExpiresAt:g.cache_expires_at}),e.jsx(fl,{createdAt:g.created_at})]}),g?.processing_note&&g.processing_note.includes("iXBRL")&&e.jsxs(us,{className:"border-yellow-300 bg-yellow-50",children:[e.jsx($s,{className:"h-4 w-4 text-yellow-600"}),e.jsx(vs,{className:"text-yellow-900",children:"iXBRL Preprocessing Failed"}),e.jsx(ms,{className:"text-yellow-800",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{children:"This filing uses inline XBRL (iXBRL) format. Our parser attempted to extract qualitative sections but encountered an error."}),e.jsxs("p",{className:"text-sm",children:[e.jsx("strong",{children:"Available:"})," Financial metrics, ratios, historical trends, and quantitative analysis",e.jsx("br",{}),e.jsx("strong",{children:"Limited:"})," Qualitative sections (moat analysis, management insights, business description)"]}),e.jsx("div",{className:"mt-3",children:e.jsx("a",{href:g.processing_note.match(/\(([^)]+)\)/)?.[1]||"#",target:"_blank",rel:"noopener noreferrer",className:"text-sm font-medium text-yellow-700 hover:text-yellow-900 underline",children:"View original filing on SEC →"})})]})})]}),g?.failed_sections&&g.failed_sections.length>0&&!g?.processing_note?.includes("iXBRL")&&e.jsxs(us,{className:"border-orange-300 bg-orange-50",children:[e.jsx(ys,{className:"h-4 w-4 text-orange-600"}),e.jsx(vs,{className:"text-orange-900",children:"Incomplete Analysis"}),e.jsx(ms,{className:"text-orange-800",children:e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsxs("p",{className:"mb-2",children:[g.failed_sections.length," section",g.failed_sections.length!==1?"s":""," failed during analysis:"," ",e.jsx("span",{className:"font-medium",children:g.failed_sections.map(se=>se.replace(/_/g," ")).join(", ")})]}),e.jsx("p",{className:"text-sm",children:"These sections will be automatically retried in the background, or you can retry them now."})]}),e.jsx(ye,{variant:"outline",size:"sm",onClick:ne,disabled:y.isPending,className:"whitespace-nowrap border-orange-400 text-orange-700 hover:bg-orange-100",children:y.isPending?e.jsxs(e.Fragment,{children:[e.jsx(Ls,{className:"w-4 h-4 mr-2 animate-spin"}),"Retrying..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ls,{className:"w-4 h-4 mr-2"}),"Retry Now"]})})]})})]}),g?.expires_at&&new Date(g.expires_at)<new Date&&e.jsx(Kc,{onRefresh:w,isRefreshing:p}),e.jsx(le,{children:e.jsx(ce,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center justify-between gap-6",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-4 mb-3",children:[e.jsxs("div",{className:"text-3xl font-bold text-primary",children:[b?.total_score||0,e.jsx("span",{className:"text-xl text-muted-foreground",children:"/100"})]}),e.jsx("div",{className:"text-sm font-medium text-muted-foreground",children:"Total Score"})]}),e.jsx("div",{className:"w-full",children:e.jsx("div",{className:"h-3 bg-muted rounded-full overflow-hidden",children:e.jsx("div",{className:`h-full transition-all duration-500 ${(b?.total_score||0)>=80?"bg-gradient-to-r from-green-500 to-green-600":(b?.total_score||0)>=60?"bg-gradient-to-r from-yellow-500 to-yellow-600":(b?.total_score||0)>=40?"bg-gradient-to-r from-orange-500 to-orange-600":"bg-gradient-to-r from-red-500 to-red-600"}`,style:{width:`${b?.total_score||0}%`}})})})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(hs,{className:"w-6 h-6 text-muted-foreground"}),e.jsxs("div",{className:"text-right",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground mb-1",children:"Investment Verdict"}),e.jsx(D,{variant:"outline",className:`text-lg px-4 py-1.5 ${je(g.investment_verdict)}`,children:g.investment_verdict||"N/A"})]})]})]})})}),e.jsx(le,{children:e.jsx(ce,{className:"pt-6",children:e.jsxs(Es,{defaultValue:"business",className:"w-full",children:[e.jsx("div",{className:"relative",children:e.jsxs(Ps,{className:"flex overflow-x-auto w-full scrollbar-hide",children:[e.jsx(me,{value:"business",className:"flex-shrink-0",children:"Business"}),e.jsx(me,{value:"moat",className:"flex-shrink-0",children:"Moat"}),e.jsx(me,{value:"management",className:"flex-shrink-0",children:"Management"}),e.jsx(me,{value:"financial",className:"flex-shrink-0",children:"Financial Health"}),e.jsx(me,{value:"revenue",className:"flex-shrink-0",children:"Revenue & Segments"}),e.jsx(me,{value:"risks",className:"flex-shrink-0",children:"Risks & Debt"}),e.jsx(me,{value:"valuation",className:"flex-shrink-0",children:"Valuation"}),e.jsx(me,{value:"rationale",className:"flex-shrink-0",children:"Rationale"})]})}),e.jsx(re,{value:"business",className:"mt-6",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Jc,{analysis:g}),e.jsx(sl,{symbol:s,companyName:g.symbol||s,businessDescription:g.business_description,revenueModel:g.revenue_model,simplicityRating:g.simplicity_rating,simplicityExplanation:g.simplicity_explanation,businessUnderstandingScore:b?.business_understanding_score??null,financialData:{customerBase:g.customer_base,evidence:g.evidence_data,currentYear:g.fiscal_year},unitEconomicsData:g.unit_economics_data}),e.jsx(Uc,{data:g.segment_analysis,confidence:g.segment_analysis?.confidence})]})}),e.jsx(re,{value:"moat",className:"mt-6",children:e.jsx("div",{className:"space-y-6",children:e.jsx(tl,{moatRating:g.moat_rating,moatDurability:g.moat_durability_years,moatAnalysis:g.moat_analysis,score:b?.business_moat_score??0,maxScore:qs.business_moat,moatSourcesData:g.moat_sources_data,moatSummary:g.moat_summary,confidence:g.moat_data?.confidence,priorScore:I?.business_moat_score,priorLabel:ee,sectorAvgScore:U?.avg_business_moat??null,sectorSampleCount:U?.sample_count??null})})}),e.jsx(re,{value:"management",className:"mt-6",children:e.jsx("div",{className:"space-y-6",children:e.jsx(al,{managementScore:g.management_score,managementAnalysis:g.management_analysis,displayScore:b?.management_quality_score??0,maxScore:qs.management_quality,managementHistoricalData:g.management_historical_data,priorScore:I?.management_quality_score,priorLabel:ee,sectorAvgScore:U?.avg_management_quality??null,sectorSampleCount:U?.sample_count??null})})}),e.jsx(re,{value:"financial",className:"mt-6",children:e.jsx(nl,{data:g.financial_strength_data,score:b?.financial_strength_score??0,maxScore:qs.financial_strength,financialHealthHistoricalData:g.financial_health_historical_data,priorScore:I?.financial_strength_score,priorLabel:ee,sectorAvgScore:U?.avg_financial_strength??null,sectorSampleCount:U?.sample_count??null})}),e.jsx(re,{value:"revenue",className:"mt-6",children:e.jsx(il,{data:g.revenue_trends_data,score:b?.revenue_trends_score??0,maxScore:qs.revenue_trends,revenueHistoricalData:g.revenue_historical_data,priorScore:I?.revenue_trends_score,priorLabel:ee,sectorAvgScore:U?.avg_revenue_trends??null,sectorSampleCount:U?.sample_count??null})}),e.jsx(re,{value:"risks",className:"mt-6",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Zc,{r
2iskScore:b?.risk_assessment_score??0,maxRiskScore:qs.risk_assessment,debtAssessment:g.debt_assessment,recessionSurvivability:g.recession_survivability,structuralRisks:g.structural_risks,manageableRisks:g.manageable_risks}),e.jsx(rl,{manageableRisks:g.manageable_risks,structuralRisks:g.structural_risks}),e.jsx(ol,{debtAssessment:g.debt_assessment,recessionSurvivability:g.recession_survivability}),e.jsx(ll,{data:g.risk_assessment_data,score:b?.risk_assessment_score??0,maxScore:qs.risk_assessment,confidence:g.risk_assessment_data?.confidence}),e.jsx(cl,{})]})}),e.jsx(re,{value:"valuation",className:"mt-6",children:e.jsx("div",{className:"space-y-6",children:L&&e.jsx(ri,{stockData:L,context:"analysis",showStockInfo:!1,storedValuationData:g?.valuation_data})})}),e.jsx(re,{value:"rationale",className:"mt-6",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs(le,{children:[e.jsx(pe,{children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-1",children:[e.jsx(hs,{className:"w-6 h-6 text-primary flex-shrink-0"}),e.jsxs("div",{children:[e.jsx(ge,{className:"text-lg md:text-xl",children:"Overall Investment Score"}),e.jsx(ts,{className:"text-xs md:text-sm",children:"Comprehensive quality assessment across all dimensions"})]})]}),e.jsxs(D,{variant:"outline",className:"text-sm font-semibold whitespace-nowrap",children:[b?.total_score||0,"/100 pts"]})]})}),e.jsx(ce,{children:e.jsxs("div",{className:"flex items-center justify-between p-4 bg-primary/5 border-2 border-primary/20 rounded-lg",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Do,{className:"w-8 h-8 text-primary"}),e.jsxs("div",{children:[e.jsx(D,{className:(b?.total_score||0)>=80?"bg-green-700 text-white":(b?.total_score||0)>=60?"bg-green-600 text-white":(b?.total_score||0)>=40?"bg-yellow-600 text-white":"bg-red-600 text-white",children:(b?.total_score||0)>=80?"Excellent":(b?.total_score||0)>=60?"Good":(b?.total_score||0)>=40?"Fair":"Poor"}),e.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:["Overall Quality: ",b?.total_score||0,"%"]})]})]}),e.jsxs("div",{className:"text-right",children:[e.jsxs("p",{className:"text-3xl font-bold text-primary",children:[b?.total_score||0,"/100"]}),e.jsx(We,{value:b?.total_score||0,className:"h-2 w-24 mt-2"})]})]})})]}),e.jsx(dl,{scores:{business_understanding_score:b?.business_understanding_score||0,business_moat_score:b?.business_moat_score||0,management_quality_score:b?.management_quality_score||0,financial_strength_score:b?.financial_strength_score||0,revenue_trends_score:b?.revenue_trends_score||0,risk_assessment_score:b?.risk_assessment_score||0,valuation_score:b?.valuation_score||0}}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3",style:{display:"none"},children:[e.jsxs(le,{className:"border-l-4 border-l-primary/30",children:[e.jsx(pe,{className:"pb-3",children:e.jsxs(ge,{className:"text-base flex items-center gap-2",children:[e.jsx(Nt,{className:"w-5 h-5 text-primary"}),"Business Understanding"]})}),e.jsx(ce,{children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-baseline gap-2",children:[e.jsx("span",{className:"text-2xl font-bold text-primary",children:g.business_understanding_score||0}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"/10 pts"})]}),e.jsx(We,{value:Math.min((g.business_understanding_score||0)/10*100,100),className:"h-2"})]})})]}),e.jsxs(le,{className:"border-l-4 border-l-primary/30",children:[e.jsx(pe,{className:"pb-3",children:e.jsxs(ge,{className:"text-base flex items-center gap-2",children:[e.jsx(js,{className:"w-5 h-5 text-primary"}),"Competitive Moat"]})}),e.jsx(ce,{children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-baseline gap-2",children:[e.jsx("span",{className:"text-2xl font-bold text-primary",children:g.business_moat_score||0}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"/20 pts"})]}),e.jsx(We,{value:Math.min((g.business_moat_score||0)/20*100,100),className:"h-2"})]})})]}),e.jsxs(le,{className:"border-l-4 border-l-primary/30",children:[e.jsx(pe,{className:"pb-3",children:e.jsxs(ge,{className:"text-base flex items-center gap-2",children:[e.jsx(Ks,{className:"w-5 h-5 text-primary"}),"Management Quality"]})}),e.jsx(ce,{children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-baseline gap-2",children:[e.jsx("span",{className:"text-2xl font-bold text-primary",children:g.management_quality_score||0}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"/15 pts"})]}),e.jsx(We,{value:Math.min((g.management_quality_score||0)/15*100,100),className:"h-2"})]})})]}),e.jsxs(le,{className:"border-l-4 border-l-primary/30",children:[e.jsx(pe,{className:"pb-3",children:e.jsxs(ge,{className:"text-base flex items-center gap-2",children:[e.jsx(xi,{className:"w-5 h-5 text-primary"}),"Financial Strength"]})}),e.jsx(ce,{children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-baseline gap-2",children:[e.jsx("span",{className:"text-2xl font-bold text-primary",children:g.financial_strength_score||0}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"/15 pts"})]}),e.jsx(We,{value:Math.min((g.financial_strength_score||0)/15*100,100),className:"h-2"})]})})]}),e.jsxs(le,{className:"border-l-4 border-l-primary/30",children:[e.jsx(pe,{className:"pb-3",children:e.jsxs(ge,{className:"text-base flex items-center gap-2",children:[e.jsx(Ye,{className:"w-5 h-5 text-primary"}),"Revenue Quality"]})}),e.jsx(ce,{children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-baseline gap-2",children:[e.jsx("span",{className:"text-2xl font-bold text-primary",children:g.revenue_trends_score||0}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"/10 pts"})]}),e.jsx(We,{value:Math.min((g.revenue_trends_score||0)/10*100,100),className:"h-2"})]})})]}),e.jsxs(le,{className:"border-l-4 border-l-primary/30",children:[e.jsx(pe,{className:"pb-3",children:e.jsxs(ge,{className:"text-base flex items-center gap-2",children:[e.jsx(ys,{className:"w-5 h-5 text-primary"}),"Risk & Debt Assessment"]})}),e.jsx(ce,{children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-baseline gap-2",children:[e.jsx("span",{className:"text-2xl font-bold text-primary",children:g.risk_assessment_score||0}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"/10 pts"})]}),e.jsx(We,{value:Math.min((g.risk_assessment_score||0)/10*100,100),className:"h-2"})]})})]}),e.jsxs(le,{className:"border-l-4 border-l-primary/30",children:[e.jsx(pe,{className:"pb-3",children:e.jsxs(ge,{className:"text-base flex items-center gap-2",children:[e.jsx(qo,{className:"w-5 h-5 text-primary"}),"Valuation"]})}),e.jsx(ce,{children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-baseline gap-2",children:[e.jsx("span",{className:"text-2xl font-bold text-primary",children:b?.valuation_score||0}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"/20 pts"})]}),e.jsx(We,{value:Math.min((b?.valuation_score||0)/20*100,100),className:"h-2",title:"Valuation Score (capped at 100%)"})]})})]})]}),e.jsxs(le,{className:"border-primary/50 bg-primary/5",children:[e.jsx(pe,{children:e.jsx(ge,{children:"Investment Framework"})}),e.jsx(ce,{children:e.jsxs("ul",{className:"space-y-2 text-sm",children:[e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx(Fe,{className:"w-4 h-4 mt-0.5 text-primary flex-shrink-0"}),e.jsxs("span",{children:[e.jsx("strong",{children:"Quality Focus:"})," Higher scores indicate businesses with sustainable competitive advantages"]})]}),e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx(Fe,{className:"w-4 h-4 mt-0.5 text-primary flex-shrink-0"}),e.jsxs("span",{children:[e.jsx("strong",{children:"Long-term Perspective:"}
2)," Evaluation emphasizes durable economics over short-term metrics"]})]}),e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx(Fe,{className:"w-4 h-4 mt-0.5 text-primary flex-shrink-0"}),e.jsxs("span",{children:[e.jsx("strong",{children:"Risk-Adjusted Returns:"})," Balance quality assessment with margin of safety principles"]})]}),e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx(Fe,{className:"w-4 h-4 mt-0.5 text-primary flex-shrink-0"}),e.jsxs("span",{children:[e.jsx("strong",{children:"Holistic Analysis:"})," Consider all dimensions together rather than individual scores in isolation"]})]})]})})]}),e.jsx(ul,{finalVerdict:g.final_verdict,verdictReasoning:g.verdict_reasoning,isWonderfulBusiness:g.is_wonderful_business,longTermDurability:g.long_term_durability,scorecard:g.scorecard,conservativeBuyBelowPrice:g.conservative_buy_below_price,currentPrice:L?.price||null,dcfData:null})]})})]})})}),e.jsx(Qc,{isOpen:o,onClose:()=>l(!1),symbol:s,currentYear:i}),g&&e.jsx(_i,{isOpen:c,symbol:s,fiscalYear:i,analysisId:g.id,onClose:K})]})}const sd={textClass:"text-gain",bgClass:"bg-gain/10",borderClass:"border-gain/20",label:"Excellent"},td={textClass:"text-primary",bgClass:"bg-primary/10",borderClass:"border-primary/20",label:"Good"},ad={textClass:"text-cautionary",bgClass:"bg-cautionary/10",borderClass:"border-cautionary/20",label:"Average"},nd={textClass:"text-loss",bgClass:"bg-loss/10",borderClass:"border-loss/20",label:"Poor"},id={textClass:"text-muted-foreground",bgClass:"bg-muted",borderClass:"border-border",label:"N/A"};function Ai(s){return s==null||!Number.isFinite(s)?null:s>=15?"excellent":s>=10?"good":s>=5?"average":"poor"}function rd(s){if(s==null)return id;switch(s){case"excellent":return sd;case"good":return td;case"average":return ad;case"poor":return nd}}function Si(s){if(s==null)return"na";switch(s){case"excellent":return"strong";case"good":return"adequate";case"average":return"caution";case"poor":return"weak"}}function od(s){switch(s){case"Technology":return 9.5;case"Healthcare":return 8.8;case"Energy":return 10.2;case"Financial Services":return 7.5;default:return 9}}function ld(s){switch(s){case"Energy":return 8.5;case"Technology":return 15.2;case"Healthcare":return 12.8;case"Financial Services":return 9.3;default:return 10.5}}const oa=s=>s!=null&&Number.isFinite(s)?`${s.toFixed(1)}%`:"—";function cd(s){return s==null?"N/A":s>20?"A+":s>15?"A":s>12?"B+":s>10?"B":s>8?"C+":s>6?"C":s>4?"D+":s>2?"D":"F"}function dd({roicData:s,symbol:t,sector:a}){const n=od(a),r=s.map(f=>({...f,wacc:n})).filter(f=>f.roic!=null&&Number.isFinite(f.roic));if(r.length===0)return e.jsxs("section",{className:"space-y-4",children:[e.jsx(W,{as:"h3",size:{base:"5",md:"6"},icon:hs,title:"ROIC Overview",subtitle:"Key return on invested capital metrics"}),e.jsxs("div",{className:"text-center py-8",children:[e.jsx(T,{as:"div",color:"muted",className:"mb-2",children:"No ROIC Data Available"}),e.jsxs(T,{as:"p",size:"2",color:"muted",className:"max-w-md mx-auto",children:["Return on Invested Capital data is not available for ",t,". This may be due to insufficient financial data or the company's financial structure."]})]})]});const o=r[r.length-1]?.roic,l=r.slice(-3),c=l.length>0?l.reduce((f,g)=>f+(g.roic||0),0)/l.length:void 0,m=ld(a),h=r.length>=3?(r[r.length-1]?.roic||0)-(r[r.length-3]?.roic||0):0,y=cd(o),j=Si(Ai(o)),u=()=>{if(!o||o===0)return"Insufficient ROIC data available for analysis.";let f="";return o>15?f="Excellent ROIC demonstrates exceptional capital efficiency and competitive advantages. ":o>10?f="Strong ROIC indicates effective capital allocation and solid business fundamentals. ":o>6?f="Moderate ROIC suggests reasonable capital efficiency, though improvement opportunities may exist. ":f="Below-average ROIC raises concerns about capital allocation efficiency and competitive positioning. ",h>2?f+="The improving trend is encouraging and suggests strengthening business fundamentals.":h<-2?f+="The declining trend warrants investigation into operational challenges or market headwinds.":f+="ROIC appears relatively stable over the recent period.",c&&Math.abs(o-c)>3&&(f+=o>c?" Current performance exceeds the 3-year average, indicating recent improvements.":" Current performance trails the 3-year average, suggesting recent challenges."),f};return e.jsxs("section",{className:"space-y-4",children:[e.jsx(W,{as:"h3",size:{base:"5",md:"6"},icon:hs,title:"ROIC Overview",subtitle:"Key return on invested capital metrics",actions:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-semibold text-foreground",children:y}),e.jsx(D,{tone:ue(j),intensity:"subtle",children:de(j)})]})}),e.jsxs("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-4",children:[e.jsxs("div",{className:"text-center p-4 rounded-lg bg-card border",children:[e.jsx(T,{as:"div",size:"2",color:"muted",className:"mb-2",children:"Current ROIC"}),e.jsx(T,{as:"div",size:"6",weight:"bold",color:"primary",numeric:!0,children:oa(o)}),e.jsx(T,{as:"div",size:"1",color:"muted",className:"mt-1",children:r.length>0?r[r.length-1]?.period:""})]}),e.jsxs("div",{className:"text-center p-4 rounded-lg bg-card border",children:[e.jsx(T,{as:"div",size:"2",color:"muted",className:"mb-2",children:"3-Year Average"}),e.jsx(T,{as:"div",size:"6",weight:"bold",numeric:!0,children:oa(c)}),e.jsx(T,{as:"div",size:"1",color:"muted",className:"mt-1",children:"Historical avg"})]}),e.jsxs("div",{className:"text-center p-4 rounded-lg bg-card border",children:[e.jsx(T,{as:"div",size:"2",color:"muted",className:"mb-2",children:"Industry Avg"}),e.jsx(T,{as:"div",size:"6",weight:"bold",numeric:!0,className:"text-ring",children:oa(m)}),e.jsx(T,{as:"div",size:"1",color:"muted",className:"mt-1",children:a||"General"})]}),e.jsxs("div",{className:"text-center p-4 rounded-lg bg-card border",children:[e.jsx(T,{as:"div",size:"2",color:"muted",className:"mb-2",children:"Trend Direction"}),e.jsx(T,{as:"div",size:"6",weight:"bold",color:h>0?"gain":h<0?"loss":"muted",children:h>0?"↗":h<0?"↘":"→"}),e.jsx(T,{as:"div",size:"1",color:"muted",className:"mt-1",children:h>2?"Improving":h<-2?"Declining":"Stable"})]})]}),e.jsx(J,{tone:"neutral",children:e.jsxs(T,{as:"p",size:"2",color:"muted",className:"leading-relaxed",children:[e.jsx("strong",{className:"text-foreground",children:"Qu
2ick Assessment:"})," ",u()]})})]})}const ud={textClass:"text-gain",bgClass:"bg-gain/10",borderClass:"border-gain/20",label:"Conservative"},md={textClass:"text-primary",bgClass:"bg-primary/10",borderClass:"border-primary/20",label:"Balanced"},hd={textClass:"text-cautionary",bgClass:"bg-cautionary/10",borderClass:"border-cautionary/20",label:"Aggressive"},pd={textClass:"text-loss",bgClass:"bg-loss/10",borderClass:"border-loss/20",label:"Unsustainable"};function Ci(s){return s==null?"unsustainable":s<.6?"conservative":s<=1?"balanced":s<=1.5?"aggressive":"unsustainable"}function Fi(s){switch(s){case"conservative":return ud;case"balanced":return md;case"aggressive":return hd;case"unsustainable":return pd}}function Ii(s){switch(s){case"conservative":return"strong";case"balanced":return"adequate";case"aggressive":return"caution";case"unsustainable":return"weak"}}function la(s){const t=Math.abs(s);return t>=1e9?`$${(s/1e9).toFixed(1)}B`:t>=1e6?`$${(s/1e6).toFixed(1)}M`:t>=1e3?`$${(s/1e3).toFixed(1)}K`:`$${s.toFixed(0)}`}function gd({fcfData:s,payoutWindow:t,symbol:a,marketCap:n}){if(s.length===0)return e.jsxs("section",{className:"space-y-4",children:[e.jsx(W,{as:"h3",size:{base:"5",md:"6"},icon:fa,title:"Free Cash Flow Overview",subtitle:"Key metrics and capital allocation assessment"}),e.jsxs("div",{className:"text-center py-8",children:[e.jsx(T,{as:"div",color:"muted",className:"mb-2",children:"No FCF Data Available"}),e.jsxs(T,{as:"p",size:"2",color:"muted",className:"max-w-md mx-auto",children:["Free Cash Flow data is not available for ",a,". This may be due to insufficient financial data or recent IPO status."]})]})]});const i=s.reduce((p,v)=>p+(typeof v.fcf=="number"?v.fcf:0),0),r=s.reduce((p,v)=>p+(typeof v.dividends=="number"?Math.abs(v.dividends):0),0),o=s.reduce((p,v)=>p+(typeof v.buybacks=="number"?Math.abs(v.buybacks):0),0),l=r+o,c=i>0?l/i:void 0,m=Ci(c),y=Fi(m).label,j=Ii(m),u=s.length>0?s[s.length-1]?.fcf:void 0,f=(()=>{if(s.length<2)return;const p=s[s.length-1]?.fcf,v=s[s.length-2]?.fcf;if(!(!p||!v||v===0))return(p-v)/Math.abs(v)*100})(),g=u&&n?u/n*100:void 0,x=s.filter(p=>(p.fcf||0)>0).length,S=x/s.length,k=S>=.8?"strong":S>=.6?"adequate":S>=.4?"caution":"weak",w=()=>{const p=l>0?r/l:0;return p>.7?"Dividend-Weighted":p<.3?"Buyback-Weighted":"Mixed"};return e.jsxs("section",{className:"space-y-4",children:[e.jsx(W,{as:"h3",size:{base:"5",md:"6"},icon:fa,title:"Free Cash Flow Overview",subtitle:"Key metrics and capital allocation assessment"}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(O,{size:"sm",label:"Latest FCF",value:u!=null?la(u):"—",delta:f!=null?f/100:null,deltaFormat:"percent",deltaPrecision:1}),e.jsx(O,{size:"sm",label:`Total FCF (${t})`,value:la(i),subtext:"Cumulative"}),e.jsx(O,{size:"sm",label:"FCF Yield",value:g!=null?`${g.toFixed(1)}%`:"—",subtext:"vs Market Cap"}),e.jsxs("div",{className:"flex flex-col items-start gap-1",children:[e.jsx(O,{size:"sm",label:"Payout Ratio",value:c!=null?`${(c*100).toFixed(0)}%`:"—",subtext:y}),e.jsx(D,{tone:ue(j),intensity:"subtle",children:de(j)})]})]}),e.jsx(bs,{}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsx("div",{className:"bg-muted/30 rounded-lg p-4",children:e.jsx(O,{size:"sm",label:"FCF Quality",value:de(k),subtext:s.length>0?`${x} of ${s.length} periods positive`:"Insufficient data"})}),e.jsxs("div",{className:"bg-muted/30 rounded-lg p-4 flex flex-col items-start gap-1",children:[e.jsx(O,{size:"sm",label:"Capital Efficiency",value:y,subtext:c!=null?`${(c*100).toFixed(0)}% payout ratio`:"Insufficient data"}),e.jsx(D,{tone:ue(j),intensity:"subtle",children:de(j)})]}),e.jsx("div",{className:"bg-muted/30 rounded-lg p-4",children:e.jsx(O,{size:"sm",label:"Payout Composition",value:w(),subtext:l>0?`${(r/l*100).toFixed(0)}% dividends, ${(o/l*100).toFixed(0)}% buybacks`:"No significant payouts"})})]}),e.jsx(J,{tone:"neutral",children:e.jsxs(T,{as:"p",size:"2",color:"muted",className:"leading-relaxed",children:[e.jsx("strong",{className:"text-foreground",children:"Cash Generation Assessment:"})," ",a," has generated ",la(i)," in free cash flow over the ",t.toLowerCase()," period",l>0?`, returning ${(l/Math.abs(i)*100).toFixed(0)}% to shareholders (${(o/l*100).toFixed(0)}% via buybacks, ${(r/l*100).toFixed(0)}% via dividends)`:" with minimal shareholder returns",g&&g>5?". The FCF yield suggests strong cash generation relative to market valuation":"","."]})})]})}function Ri(s){return s==null||!Number.isFinite(s)?null:s>=20?"top":s>=10?"good":s>=5?"marginal":"bottom"}function ki(s){return s==null||!Number.isFinite(s)?null:s>=10?"top":s>=5?"good":s>=0?"marginal":"bottom"}const fd={top:"Strong",good:"Steady",marginal:"Slow",bottom:"Declining"};function Ti(s){return s==null?"N/A":fd[s]}function qt(s){if(s==null)return"na";switch(s){case"top":return"strong";case"good":return"adequate";case"marginal":return"caution";case"bottom":return"weak"}}function gn(s){const t=Math.abs(s);return t>=1e9?`$${(s/1e9).toFixed(1)}B`:t>=1e6?`$${(s/1e6).toFixed(1)}M`:t>=1e3?`$${(s/1e3).toFixed(1)}K`:`$${s.toFixed(0)}`}function xd({revenueData:s,symbol:t}){const a=s.filter(S=>S.revenue!=null&&S.netIncome!=null).slice().reverse();if(a.length===0)return e.jsxs("section",{className:"space-y-4",children:[e.jsx(W,{as:"h3",size:{base:"5",md:"6"},icon:Ye,title:"Revenue & Profitability Overview",subtitle:"Key financial performance metrics and growth analysis"}),e.jsxs("div",{className:"text-center py-8",children:[e.jsx(T,{as:"div",color:"muted",className:"mb-2",children:"No Revenue Data Available"}),e.jsxs(T,{as:"p",size:"2",color:"muted",className:"max-w-md mx-auto",children:["Revenue and profitability data is not available for ",t,". This may be due to insufficient financial data or recent IPO status."]})]})]});const n=a[a.length-1],i=n?.revenue,r=n?.netIncome,o=i&&r?r/i*100:void 0,l=a.length>=2?((a[a.length-1]?.revenue||0)/(a[0]?.revenue||1)-1)*100/(a.length-1):void 0,c=a.length>=2?((a[a.length-1]?.netIncome||0)/(a[0]?.netIncome||1)-1)*100/(a.length-1):void 0,m=a.length>=2?((a[a.length-1]?.revenue||0)-(a[a.length-2]?.revenue||0))/(a[a.length-2]?.revenue||1)*100:void 0,h=a.length>=2?((a[a.length-1]?.netIncome||0)-(a[a.length-2]?.netIncome||0))/M
2ath.abs(a[a.length-2]?.netIncome||1)*100:void 0,y=Ri(o),j=qt(y),u=ki(l),f=qt(u),g=Ti(u),x=()=>{if(o==null||l==null||c==null)return"Insufficient data for comprehensive revenue and profitability analysis.";let S="";return o>20?S="Excellent profitability margins demonstrate strong pricing power and operational efficiency. ":o>10?S="Healthy profit margins indicate solid business fundamentals and competitive positioning. ":o>5?S="Moderate margins suggest room for operational improvements or competitive pressures. ":o>0?S="Low margins may indicate operational challenges or highly competitive industry dynamics. ":S="Negative margins require immediate attention to operational efficiency and cost management. ",l>10&&c>l?S+="Strong revenue growth coupled with expanding margins indicates excellent operational leverage.":l>5&&c>0?S+="Steady growth with positive profitability trends support long-term value creation.":l>0&&c<0?S+="Revenue growth with declining profitability suggests margin pressures requiring investigation.":l<0&&(S+="Declining revenues present challenges; focus on business model sustainability and competitive position."),S};return e.jsxs("section",{className:"space-y-4",children:[e.jsx(W,{as:"h3",size:{base:"5",md:"6"},icon:Ye,title:"Revenue & Profitability Overview",subtitle:"Key financial performance metrics and growth analysis"}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(O,{size:"sm",label:"Latest Revenue",value:gn(i),delta:m!=null?m/100:null,deltaFormat:"percent",deltaPrecision:1}),e.jsx(O,{size:"sm",label:"Net Income",value:gn(r),valueColor:r&&r>0?"gain":"loss",delta:h!=null?h/100:null,deltaFormat:"percent",deltaPrecision:1}),e.jsxs("div",{className:"flex flex-col items-start gap-1",children:[e.jsx(O,{size:"sm",label:"Net Margin",value:o!=null?`${o.toFixed(1)}%`:"—"}),e.jsx(D,{tone:ue(j),intensity:"subtle",children:de(j)})]}),e.jsxs("div",{className:"flex flex-col items-start gap-1",children:[e.jsx(O,{size:"sm",label:"Revenue CAGR",value:l!=null?`${l.toFixed(1)}%`:"—",subtext:g}),e.jsx(D,{tone:ue(f),intensity:"subtle",children:de(f)})]})]}),e.jsxs(J,{tone:"neutral",children:[e.jsx("h4",{className:"font-semibold text-sm text-foreground mb-2",children:"Growth Quality Assessment"}),e.jsx(T,{as:"p",size:"2",color:"muted",children:x()})]})]})}function Oi(s){return s==null||!Number.isFinite(s)?null:s<=-3?"aggressive-buybacks":s<=-1?"moderate-buybacks":s<=1?"stable":"dilutive"}const bd={"aggressive-buybacks":"Aggressive Buybacks","moderate-buybacks":"Moderate Buybacks",stable:"Stable Count",dilutive:"Dilutive"};function Ei(s){return s==null?"N/A":bd[s]}function Pi(s){if(s==null)return"na";switch(s){case"aggressive-buybacks":return"strong";case"moderate-buybacks":return"adequate";case"stable":return"caution";case"dilutive":return"weak"}}function vd(s){return s?s>=1e9?`${(s/1e9).toFixed(1)}B`:s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${(s/1e3).toFixed(1)}K`:s.toFixed(0):"—"}function yd({sharesData:s,symbol:t}){if(s.length===0)return e.jsxs("section",{className:"space-y-4",children:[e.jsx(W,{as:"h3",size:{base:"5",md:"6"},icon:Ks,title:"Share Count Overview",subtitle:"Capital allocation and shareholder value analysis"}),e.jsxs("div",{className:"text-center py-8",children:[e.jsx(T,{as:"div",color:"muted",className:"mb-2",children:"No Share Count Data Available"}),e.jsxs(T,{as:"p",size:"2",color:"muted",className:"max-w-md mx-auto",children:["Share count data is not available for ",t,". This may be due to insufficient financial data or recent IPO status."]})]})]});const a=(u,f)=>{if(u!=null){if(Math.abs(u)>1e3){console.warn(`[ShareCountOverviewCard] ${t} - ${f} REJECTED: ${u.toFixed(1)}% (exceeds ±1000%)`);return}return u}},n=s.slice().reverse(),i=n[n.length-1]?.shares,r=n[0]?.shares,o=i&&r&&r>0?a((i-r)/r*100,"Total Change"):void 0,l=o&&n.length>1?o/(n.length-1):void 0,c=n.length>=2&&(n[n.length-2]?.shares||0)>0?a(((n[n.length-1]?.shares||0)-(n[n.length-2]?.shares||0))/(n[n.length-2]?.shares||0)*100,"YoY Change"):void 0,m=Oi(l),h=Pi(m),y=Ei(m),j=()=>{if(l==null)return"Insufficient share count data for comprehensive analysis of capital allocation efficie
2ncy.";let u="";return l<-3?(u="Aggressive share buybacks demonstrate strong cash generation and management's commitment to shareholder value. ",u+="This capital allocation strategy can significantly boost per-share metrics and returns for remaining shareholders."):l<-1?(u="Moderate share reduction indicates disciplined capital allocation and confidence in business prospects. ",u+="Buybacks at reasonable valuations can enhance long-term shareholder returns."):l<1?(u="Stable share count suggests balanced capital allocation between growth investments and shareholder returns. ",u+="This approach may be appropriate for companies in stable, mature industries."):l<3?(u="Modest share dilution may indicate growth investments or employee compensation programs. ",u+="Monitor that dilution is offset by corresponding growth in business value."):(u="Significant share dilution raises concerns about value destruction for existing shareholders. ",u+="Investigate whether new capital is generating adequate returns to justify dilution."),u};return e.jsxs("section",{className:"space-y-4",children:[e.jsx(W,{as:"h3",size:{base:"5",md:"6"},icon:Ks,title:"Share Count Overview",subtitle:"Capital allocation and shareholder value analysis"}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(O,{size:"sm",label:"Current Shares",value:vd(i),delta:c!=null?c/100:null,deltaFormat:"percent",deltaPrecision:1,direction:c!=null?c<=0?"gain":"loss":void 0}),e.jsx(O,{size:"sm",label:"Total Change",value:o!=null?`${o>0?"+":""}${o.toFixed(1)}%`:"—",valueColor:o!=null&&o<0?"gain":o!=null&&o>0?"loss":"foreground",subtext:o!=null&&o<0?"Buybacks":o!=null&&o>0?"Dilution":"Stable"}),e.jsx(O,{size:"sm",label:"Annual Change",value:l!=null?`${l>0?"+":""}${l.toFixed(1)}%`:"—",valueColor:l!=null&&l<0?"gain":l!=null&&l>0?"loss":"foreground",subtext:"Per year average"}),e.jsxs("div",{className:"flex flex-col items-start gap-1",children:[e.jsx(O,{size:"sm",label:"Capital Allocation",value:y}),e.jsx(D,{tone:ue(h),intensity:"subtle",children:de(h)})]})]}),e.jsxs(J,{tone:"neutral",children:[e.jsx("h4",{className:"font-semibold text-sm text-foreground mb-2",children:"Capital Allocation Assessment"}),e.jsx(T,{as:"p",size:"2",color:"muted",children:j()})]})]})}function ya(s,t){return s==null||!Number.isFinite(s)?null:s>=2&&(t==null||t>=1)?"excellent":s>=1.5&&(t==null||t>=.7)?"good":s>=1?"fair":s>=.8?"poor":"critical"}const jd={excellent:"Excellent",good:"Good",fair:"Fair",poor:"Poor",critical:"Critical"};function $i(s){return s==null?"N/A":jd[s]}function Li(s){return s==null||!Number.isFinite(s)?null:s>=.2?"strong":s>=.1?"adequate":s>.05?"limited":"weak"}function ja(s){if(s==null)return"na";switch(s){case"excellent":return"strong";case"good":return"adequate";case"fair":return"caution";case"poor":return"weak";case"critical":return"weak"}}function Mi(s){if(s==null)return"na";switch(s){case"strong":return"strong";case"adequate":return"adequate";case"limited":return"caution";case"weak":return"weak"}}function Nd({balanceSheetData:s,symbol:t}){const a=s.map(u=>{const f=u.currentAssets&&u.currentLiabilities&&u.currentLiabilities>0?u.currentAssets/u.currentLiabilities:void 0,g=u.currentAssets&&u.currentLiabilities&&u.currentLiabilities>0?(u.currentAssets-(u.intangibles||0))/u.currentLiabilities:void 0,x=u.cash&&u.currentLiabilities&&u.currentLiabilities>0?u.cash/u.currentLiabilities:void 0,S=u.currentAssets&&u.currentLiabilities?u.currentAssets-u.currentLiabilities:void 0,k=u.totalDebt&&u.shareholdersEquity&&u.shareholdersEquity>0?u.totalDebt/u.shareholdersEquity:void 0;return{period:u.period,currentRatio:f,quickRatio:g,cashRatio:x,workingCapital:S?S/1e9:void 0,debtToEquity:k,currentAssets:u.currentAssets?u.currentAssets/1e9:void 0,currentLiabilities:u.currentLiabilities?u.currentLiabilities/1e9:void 0,cash:u.cash?u.cash/1e9:void 0}}).reverse(),n=a[a.length-1],i=a[a.length-2];if(a.length===0||!n)return e.jsxs("section",{className:"space-y-4",children:[e.jsx(W,{as:"h3",size:{base:"5",md:"6"},icon:xa,title:"Financial Health Overview",subtitle:"Liquidity, solvency, and financial stability analysis"}),e.jsxs("div",{className:"text-center py-8",children:[e.jsx(T,{as:"div",color:"muted",className:"mb-2",children:"No Financial Health Data Available"}),e.jsxs(T,{as:"p",size:"2",color:"muted",className:"max-w-md mx-auto",children:["Balance sheet data is not available for ",t,". This may be due to insufficient financial data or recent IPO status."]})]})]});const r=n?.currentRatio&&i?.currentRatio?n.currentRatio-i.currentRatio:void 0,o=n?.quickRatio&&i?.quickRatio?n.quickRatio-i.quickRatio:void 0,l=ya(n?.currentRatio,n?.quickRatio),c=ja(l),m=$i(l),h=Li(n?.cashRatio),y=Mi(h),j=()=>
2{if(!n?.currentRatio)return"Insufficient balance sheet data for comprehensive liquidity analysis.";let u="";const f=n.currentRatio,g=n.quickRatio||0;return f>=2?(u="Strong liquidity position with current ratio above 2.0, indicating excellent ability to meet short-term obligations. ",u+="This conservative approach provides a substantial safety margin for value investors."):f>=1.5?(u="Solid liquidity with current ratio above 1.5, demonstrating good short-term financial health. ",u+="The company appears well-positioned to handle operational cash flow fluctuations."):f>=1?(u="Adequate liquidity with current ratio above 1.0, though closer monitoring is warranted. ",u+="Consider the quality of current assets and industry-specific working capital requirements."):(u="Concerning liquidity position with current ratio below 1.0, indicating potential difficulty meeting short-term obligations. ",u+="This raises red flags for conservative value investors seeking financial stability."),g>=1?u+=" The quick ratio above 1.0 confirms strong liquid asset coverage excluding inventory.":g>=.7?u+=" Acceptable quick ratio suggests reasonable liquidity when excluding less liquid current assets.":g>0&&(u+=" Lower quick ratio indicates dependence on inventory conversion for liquidity."),u};return e.jsxs("section",{className:"space-y-4",children:[e.jsx(W,{as:"h3",size:{base:"5",md:"6"},icon:xa,title:"Financial Health Overview",subtitle:"Liquidity, solvency, and financial stability analysis"}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(O,{size:"sm",label:"Current Ratio",value:n?.currentRatio?n.currentRatio.toFixed(2):"—",delta:r??null,deltaFormat:"number",deltaPrecision:2}),e.jsx(O,{size:"sm",label:"Quick Ratio",value:n?.quickRatio?n.quickRatio.toFixed(2):"—",delta:o??null,deltaFormat:"number",deltaPrecision:2}),e.jsxs("div",{className:"flex flex-col items-start gap-1",children:[e.jsx(O,{size:"sm",label:"Cash Ratio",value:n?.cashRatio?n.cashRatio.toFixed(2):"—"}),e.jsx(D,{tone:ue(y),intensity:"subtle",children:de(y)})]}),e.jsxs("div",{className:"flex flex-col items-start gap-1",children:[e.jsx(O,{size:"sm",label:"Overall Health",value:m}),e.jsx(D,{tone:ue(c),intensity:"subtle",children:de(c)})]})]}),e.jsxs(J,{tone:"neutral",children:[e.jsx("h4",{className:"font-semibold text-sm text-foreground mb-2",children:"Financial Stability Assessment"}),e.jsx(T,{as:"p",size:"2",color:"muted",children:j()})]})]})}function ca(s,t){return s>=t.strong?{tone:"strong"}:s>=t.reasonable?{tone:"moderate"}:{tone:"weak"}}function wd({roicData:s,cashflowData:t,marketCap:a,ratios:n,symbol:i,name:r}){const l=(s?.slice(0,1)||[])[0]?.roic,c=w=>typeof w.fcf=="number"?w.fcf:typeof w.operatingCashFlow=="number"&&typeof w.capex=="number"?w.operatingCashFlow-w.capex:void 0,m=t?[...t].sort((w,p)=>p.period.localeCompare(w.period)).slice(0,1):[],h=m.length>0?c(m[0]):void 0,y=h&&a?h/a*100:void 0,j=n?.pb||0,u=l?ca(l*100,{strong:15,reasonable:10}):{tone:null},f=y?ca(y,{strong:8,reasonable:5}):{tone:null},g=j?ca(5-j,{strong:3,reasonable:2}):{tone:null},x=[u.tone==="strong",f.tone==="strong",g.tone==="strong"].filter(Boolean).length,S=x>=2?"Wide Moat":x>=1?"Narrow Moat":"No Moat",k=Te(wi(S));return e.jsxs("section",{className:"space-y-4",children:[e.jsx(W,{as:"h3",size:{base:"5",md:"6"},icon:js,title:"Economic Moat Overview",subtitle:"Competitive advantages and business sustainability assessment"}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-6",children:[e.jsxs("div",{className:"text-center",children:[e.jsx(T,{as:"div",size:"2",color:"muted",className:"mb-1",children:"Return on Capital"}),e.jsx(T,{as:"div",size:"7",weight:"bold",numeric:!0,children:l?`${(l*100).toFixed(1)}%`:"N/A"}),e.jsx("div",{className:"mt-2 inline-flex",children:e.jsxs(D,{tone:ue(Te(u.tone)),intensity:"subtle",children:[de(Te(u.tone)),u.tone==="strong"&&e.jsx("span",{className:"ml-1",children:"🔥"})]})})]}),e.jsxs("div",{className:"text-center",children:[e.jsx(T,{as:"div",size:"2",color:"muted",className:"mb-1",children:"FCF Yield"}),e.jsx(T,{as:"div",size:"7",weight:"bold",numeric:!0,children:y?`${y.toFixed(1)}%`:"N/A"}),e.jsx("div",{className:"mt-2 inline-flex",children:e.jsxs(D,{tone:ue(Te(f.tone)),intensity:"subtle",children:[de(Te(f.tone)),f.tone==="strong"&&e.jsx("span",{className:"ml-1",children:"💰"})]})})]}),e.jsxs("div",{className:"text-center",children:[e.jsx(T,{as:"div",size:"2",color:"muted",className:"mb-1",children:"Price-to-Book"}),e.jsx(T,{as:"div",size:"7",weight:"bold",numeric:!0,children:j?`${j.toFixed(2)}x`:"N/A"}),e.jsx("div",{className:"mt-2 inline-flex",children:e.jsxs(D,{tone:ue(Te(g.tone)),intensity:"subtle",children:[de(Te(g.tone)),g.tone==="strong"&&e.jsx("span",{className:"ml-1",children:"🔥"})]})})]}),e.jsxs("div",{className:"text-center",children:[e.jsx(T,{as:"div",size:"2",color:"muted",className:"mb-1",children:"Moat Strength"}),e.jsx(T,{as:"div",size:"6",weight:"bold",children:S}),e.jsx("div",{className:"mt-2 inline-flex",children:e.jsx(D,{tone:ue(k),intensity:"subtle",children:de(k)})})]})]}),e.jsx(bs,{}),e.jsxs(J,{tone:"neutral",children:[e.jsx("h4",{className:"font-medium text-sm text-foreground mb-3",children:"Competitive Advantage Assessment"}),e.jsxs(T,{as:"p",size:"2",color:"muted",children:[r," demonstrates"," ",S==="Wide Moat"?"strong":S==="Narrow Moat"?"moderate":"limited"," ","economic moat characteristics",l&&l>.15?` with high ROIC of ${(l*100).toFixed(1)}%`:"",y&&y>8?" and strong cash generation":"",". The company's financial metrics suggest"," ",S==="Wide Moat"?"sustainable competitive advantages that protect against competition":S==="Narrow Moat"?"some competitive advantages, though they may be vulnerable over time":"limited protection against competitive pressures","."]})]})]})}function Re(s){if(s==null||!Number.isFinite(s))return"—";const t=Math.abs(s);return t>=1e12?`$${(s/1e12).toFixed(2)}T`:t>=1e9?`$${(s/1e9).toFixed(2)}B`:t>=1e6?`$${(s/1e6).toFixed(2)}M`:t>=1e3?`$${(s/1e3).toFixed(2)}K`:`$${s.toFixed(2)}`}function _d(s){return s==null||!Number.isFinite(s)?"—":`$${s.toFixed(2)}`}function Ad(s){if(s==null||!Number.isFinite(s))return"—";const t=Math.abs(s);return t>=1e9?`${(s/1e9).toFixed(2)}B`:t>=1e6?`${(s/1e6).toFixed(2)}M`:t>=1e3?`${(s/1e3).toFixed(2)}K`:s.toFixed(2)}function fn(s){const t=s.selling_general_and_administrative_expenses??s.sellingGeneralAndAdministrativeExpenses;if(typeof t=="number"&&Number.isFinite(t)&&t>0)return t;const a=s.selling_and_marketing_expenses??s.sellingAndMarketingExpenses,n=s.general_and_administrative_expenses??s.generalAndAdministrativeExpenses;if(typeof a=="number"&&Number.isFinite(a)&&typeof n=="number"&&Number.isFinite(n)){const i=a+n;return i>0?i:void 0}}function xe(s){return[...s].sort((t,a)=>{const n=parseInt(t.period.replace(/Q[1-4]-/g,""),10),i=parseInt(a.period.replace(/Q[1-4]-/g,""),10);if(n!==i)return i-n;const r=t.period.match(/Q(\d)/)?.[1],o=a.period.match(/Q(\d)/)?.[1];return r&&o?parseInt(o,10)-parseInt(r,10):0})}
2function Sd({incomeData:s,periodType:t}){const a=xe(s).slice(0,8),n=a.length,i=a[n-1],r=a[0],o=(g,x)=>{if(t==="quarterly"){const S=a[1];return S?.revenue&&r?.revenue?(r.revenue-S.revenue)/S.revenue:void 0}return n>1&&g!=null&&g>0&&x!=null&&x>0?Math.pow(x/g,1/(n-1))-1:void 0},l=()=>{if(t==="quarterly"){const g=a[1];return g?.netIncome&&r?.netIncome&&g.netIncome>0?(r.netIncome-g.netIncome)/g.netIncome:void 0}return c(i?.netIncome,r?.netIncome)},c=(g,x)=>n>1&&g!=null&&g>0&&x!=null&&x>0?Math.pow(x/g,1/(n-1))-1:void 0,m=o(i?.revenue,r?.revenue),h=l(),y=r?.netIncome!=null&&r?.revenue?r.netIncome/r.revenue:void 0,j=g=>g!=null&&Number.isFinite(g)?`${(g*100).toFixed(1)}%`:"—",[u,f]=(()=>{const g=m??-1/0,x=h??-1/0,S=y??0,k=t==="quarterly"?.02:.05,w=t==="quarterly"?.02:.05;return g>=k&&x>=w&&S>=.1?["success","Strong"]:g>=0&&S>=.05?["info","Stable"]:["warning","Weak"]})();return e.jsx(Ia,{title:"Income Statement Overview",subtitle:"Profitability and growth assessment",metrics:[{label:"Latest Revenue",value:r?.revenue?Re(r.revenue):"N/A"},{label:t==="quarterly"?"QoQ Revenue Growth":"Revenue CAGR",value:j(m)},{label:e.jsx($,{id:"netMargin-overview",data:P.netMargin,children:e.jsx("span",{children:"Net Margin"})}),value:j(y)},{label:"Growth Quality",value:f,tone:u}]})}function Cd({incomeData:s,periodType:t}){const a=xe(s).slice(0,8).reverse();return e.jsx(ci,{title:"Revenue & Profitability Trends",subtitle:"Historical income statement metrics",data:a,series:[{dataKey:"revenue",name:"Revenue",tone:"primary"},{dataKey:"grossProfit",name:"Gross Profit",tone:"chart-4"},{dataKey:"netIncome",name:"Net Income",tone:"gain"}],yAxisFormatter:Re,tooltipFormatter:Re,emptyMessage:"No income statement data available"})}function we(s,t){return!t||!P[t]?s:e.jsx($,{id:t,data:P[t],children:e.jsx("span",{children:s})})}function Fd({incomeData:s,periodType:t}){const a=xe(s).slice(0,8),n=r=>Re(r),i=t==="annual"?e.jsx($,{id:"yoyGrowth-income",data:P.yoyGrowth,children:e.jsx("span",{children:"YoY Growth"})}):e.jsx($,{id:"qoqGrowth-income",data:P.qoqGrowth,children:e.jsx("span",{children:"QoQ Growth"})});return e.jsx(Ra,{title:"Income Statement Details",subtitle:"Comprehensive income statement breakdown",data:a,periodKey:"period",formatValue:n,periodType:t,subRowLabel:i,metrics:[{key:"revenue",label:we("Revenue","revenue")},{key:"costOfRevenue",label:we("Cost of Goods Sold","costOfRevenue"),mobileLabel:we("COGS","costOfRevenue")},{key:"grossProfit",label:we("Gross Profit","grossProfit")},{key:"operatingExpenses",label:we("Operating Expenses","operatingExpenses"),mobileLabel:we("OpEx","operatingExpenses")},{key:"operatingIncome",label:we("Operating Income","operatingIncome"),mobileLabel:we("Op Income","operatingIncome")},{key:"otherIncomeExpense",label:we("Other Income (Expense)","otherIncomeExpense"),mobileLabel:we("Other Inc/Exp","otherIncomeExpense")},{key:"incomeBeforeTax",label:we("Pre Tax Income","preTaxIncome"),mobileLabel:we("Pre-Tax","preTaxIncome")},{key:"incomeTaxExpense",label:we("Tax Provision","taxProvision")},{key:"netIncome",label:we("Net Profit","netIncome")},{key:"epsDiluted",label:we("Diluted EPS","eps"),mobileLabel:we("EPS","eps"),formatValue:_d},{key:"sharesDiluted",label:we("Diluted Average Shares","dilutedShares"),mobileLabel:we("Shares","dilutedShares"),formatValue:Ad},{key:"normalizedEbitda",label:we("Normalized EBITDA","normalizedEbitda"),mobileLabel:we("EBITDA","normalizedEbitda")}]})}const Id={medians:{},loading:!1,error:null,updatedAt:null};function Rd(s,t={}){const{cyclical:a=!1,enabled:n=!0}=t,i=s?.trim()||null,r=yt({queryKey:["sector-medians",i,a],queryFn:async()=>{if(!i)return{lookup:{},updatedAt:null};const{data:o,error:l}=await He.from("sector_metric_medians").select("sector,metric,period,cyclical_only,p10,p25,p50,p75,p90,n_symbols,updated_at").eq("sector",i).eq("cyclical_only",a);if(l)throw l;const c=o??[],m={};let h=null;for(const y of c){if(y.p50===null)continue;const j={sector:y.sector,p10:Number(y.p10),p25:Number(y.p25),p50:Number(y.p50),p75:Number(y.p75),p90:Number(y.p90),nSymbols:y.n_symbols};m[y.metric]=j,(!h||y.updated_at>h)&&(h=y.updated_at)}return{lookup:m,updatedAt:h}},enabled:n&&!!i,staleTime:60*60*1e3,gcTime:24*60*60*1e3,retry:1});return!n||!i?Id:{medians:r.data?.lookup??{},loading:r.isLoading,error:r.error instanceof Error?r.error:null,updatedAt:r.data?.updatedAt??null}}const ft="Educational assessment; not investment advice. This scorecard is a rule-based summary of publicly reported financials. It does not incorporate management guidance, industry outlook, valuation, or qualitative factors. It is not a recommendation to buy, sell, or hold any security. Conduct your own research and consult a qualified financial advisor before making investment decisions.",ot={GM_10Y_MEAN_PASS:.4,GM_10Y_MEAN_CAUTION:.25,GM_10Y_COV_PASS:.1,GM_10Y_COV_CAUTION:.2,MIN_PERIODS:5},xn={SGA_OVER_GP_PASS:.3,SGA_OVER_GP_CAUTION:.8}
2,xs={OM_LATEST_PASS:.15,OM_LATEST_CAUTION:.08,OM_SLOPE_IMPROVING_BPS:100,MIN_PERIODS_FOR_SLOPE:5,CYCLICAL:{OM_10Y_MEAN_PASS:.12,OM_10Y_MEAN_CAUTION:.07}},bn={COVERAGE_PASS:10,COVERAGE_CAUTION:5},$e={POSITIVE_YEARS_PASS:9,POSITIVE_YEARS_CAUTION:7,EPS_COV_PASS:.3,EPS_COV_CAUTION:.6,EPS_WORST_DRAWDOWN_PASS:-.4,EPS_WORST_DRAWDOWN_FAIL:-.6,MIN_ANNUAL_PERIODS:7,CYCLICAL:{POSITIVE_YEARS_PASS:8,POSITIVE_YEARS_CAUTION:6,EPS_COV_PASS:.8,EPS_COV_CAUTION:1.2,EPS_WORST_DRAWDOWN_PASS:-.75,EPS_WORST_DRAWDOWN_FAIL:-.9}},lt={EPS_CAGR_PASS:.07,EPS_CAGR_CAUTION:.03,EPS_ACCRETIVE_TOLERANCE:.01,SHARE_DILUTION_CAUTION_MAX:.02},Ke={ETR_NORMAL_MIN:.15,ETR_NORMAL_MAX:.3,ETR_NORMAL_YEARS_PASS:8,ETR_NORMAL_YEARS_CAUTION:6,NONRECURRING_MAGNITUDE_THRESHOLD:.1,NONRECURRING_MAX_PASS:2,NONRECURRING_MAX_CAUTION:4,CFO_OVER_NI_PASS:.9,CFO_OVER_NI_CAUTION:.75},ds={ROIC_10Y_MEAN_PASS:.15,ROIC_10Y_MEAN_CAUTION:.1,ROIC_LATEST_PASS:.12,ROIC_LATEST_CAUTION_MIN:.08,CYCLICAL:{ROIC_10Y_MEAN_PASS:.12,ROIC_10Y_MEAN_CAUTION:.08,ROIC_10Y_MIN_PASS:.04,ROIC_10Y_MIN_FAIL:-.05}},_s=10,kd={"BRK.A":{template:"PLACEHOLDER",banner:"Hybrid business — this holding company includes insurance, rail, industrials, and retail segments. Sector-appropriate scorecard is deferred to a later phase."},"BRK.B":{template:"PLACEHOLDER",banner:"Hybrid business — this holding company includes insurance, rail, industrials, and retail segments. Sector-appropriate scorecard is deferred to a later phase."},UNH:{template:"UNIVERSAL",banner:"Hybrid business — this company combines managed care (insurance-like economics) with health-services delivery. The universal template applies to the consolidated view; individual segment quality may differ."},ELV:{template:"UNIVERSAL",banner:"Hybrid business — this company combines managed care (insurance-like economics) with health-services delivery. The universal template applies to the consolidated view; individual segment quality may differ."},MKL:{template:"INSURANCE_PC",banner:"Hybrid business — insurance is the primary segment, but Markel Ventures (industrials portfolio) is material. The insurance scorecard reflects the primary segment."},AMZN:{template:"UNIVERSAL",banner:"Hybrid business — retail, AWS, and advertising have different economics. The universal template applies to the consolidated view; segment-level analysis is not shown here."}},Td=new Set(["Energy","Materials","Basic Materials"]),Od=["chemicals","metals","mining","steel","paper","forest","aerospace","defense","construction","engineering","machinery","airlines","marine","trucking","air freight","auto","household durables","consumer durables","semiconductor"],Ed=["containers","packaging","construction materials"];function Pd(s){const{symbol:t,sector:a,industry:n,subIndustry:i}=s,r=kd[t.toUpperCase()];if(r)return{template:r.template,hybridBanner:r.banner,reason:`hybrid-override:${t.toUpperCase()}`};if(!a||a.trim()===""||a.toLowerCase()==="unknown")return{template:"PLACEHOLDER",reason:"missing-sector-metadata"};const o=a.trim(),l=(n??"").toLowerCase(),c=(i??"").toLowerCase(),m=`${l} ${c}`;if(o==="Financials"||o==="Financial Services")return/investment banking|brokerage|capital markets|asset management|consumer finance|diversified financial/.test(m)?{template:"PLACEHOLDER",reason:"financials-non-bank-non-insurance-deferred"}:/bank|savings|thrift/.test(m)?{template:"BANK",reason:"financials-banks"}:/insurance|reinsur/.test(m)?/life|health/.test(m)&&!/property|casualty|p&c/.test(m)?{template:"PLACEHOLDER",reason:"financials-insurance-life-health-deferred"}:{template:"INSURANCE_PC",reason:"financials-insurance-pc"}:{template:"PLACEHOLDER",reason:"financials-non-bank-non-insurance-deferred"};if(o==="Real Estate")return/management|development|services/.test(m)&&!/reit/.test(m)?{template:"UNIVERSAL",reason:"real-estate-operating-company"}:{template:"REIT",reason:"real-estate-reit"};const h=Td.has(o),y=Od.some(f=>m.includes(f)),j=Ed.some(f=>m.includes(f));return(h||y)&&!j?{template:"UNIVERSAL_CYCLICAL",reason:y?`cyclical-sub-industry:${m.trim()}`:`cyclical-sector:${o}`}:{template:"UNIVERSAL",reason:`universal-default:${o}`}}function G(s){return typeof s=="number"&&Number.isFinite(s)}function as(s){if(s.length===0)return NaN;let t=0;for(const a of s)t+=a;return t/s.length}function $d(s){if(s.length<2)return NaN;const t=as(s);let a=0;
2for(const n of s)a+=(n-t)*(n-t);return Math.sqrt(a/(s.length-1))}function Ht(s){const t=as(s);if(!Number.isFinite(t)||Math.abs(t)<1e-9)return NaN;const a=$d(s);return Number.isFinite(a)?a/Math.abs(t):NaN}function wt(s,t,a){return a<1||!G(s)||!G(t)||s<=0||t<=0?null:Math.pow(t/s,1/a)-1}function $a(s,t){if(s.length!==t.length||s.length<2)return NaN;const a=as(s),n=as(t);let i=0,r=0;for(let o=0;o<s.length;o++)i+=(s[o]-a)*(t[o]-n),r+=(s[o]-a)*(s[o]-a);return Math.abs(r)<1e-9?NaN:i/r}function La(s){if(s.length<2)return 0;let t=s[0],a=0;for(let n=1;n<s.length;n++){if(s[n]>t&&(t=s[n]),t<=0)continue;const i=(s[n]-t)/t;i<a&&(a=i)}return a}function z(s,t=1){return s==null||!Number.isFinite(s)?"—":`${(s*100).toFixed(t)}%`}function Qe(s,t=1){return s==null||!Number.isFinite(s)?"—":`${s.toFixed(t)}x`}function Ld(s){return s==null||!Number.isFinite(s)?"—":String(Math.round(s))}function Md(s,t=0){return s==null||!Number.isFinite(s)?"—":`${s.toFixed(t)} bps/yr`}function R(s,t){return s.replace(/\{([a-zA-Z0-9_]+)\}/g,(a,n)=>{const i=t[n];return i==null||typeof i=="number"&&!Number.isFinite(i)?"—":String(i)})}function Ge(s,t){const a=[];for(const n of s){const i=t(n);typeof i=="number"&&Number.isFinite(i)&&a.push(i)}return a}function Ae(s,t){return s.length<=t?s:s.slice(0,t)}function Dd(s,t,a){const{p10:n,p25:i,p50:r,p75:o,p90:l}=t;return a==="higher_is_better"?s>=l?"top decile":s>=o?"top quartile":s>=r?"above median":s>=i?"below median":s>=n?"bottom quartile":"bottom decile":a==="lower_is_better"?s<=n?"top decile":s<=i?"top quartile":s<=r?"above median":s<=o?"below median":s<=l?"bottom quartile":"bottom decile":s>=l||s<=n?"sector extreme":s>=o||s<=i?"off-median":"near median"}function ns(s,t,a,n){if(!t||s==null||!Number.isFinite(s)||!Number.isFinite(t.p50))return;const i=a(t.p50),r=Dd(s,t,n);return`sector median ${i} • ${r}`}const vn="Pricing power",yn="Gross margin level and persistence over 10 years. Durable pricing power shows up as a high gross margin held stable through cycles — a marker of brand, switching costs, or scale advantage.",qd="Gross margin averaged {mean_pct} over the last {n} years with a coefficient of variation of {cov_pct} — a persistence pattern consistent with pricing power.",Bd="Gross margin at {latest_pct} sits in the competitive zone. Averaged {mean_pct} over {n} years; watch for margin compression as an early indicator of moat erosion.",zd="Gross margin at {latest_pct} indicates a commoditized cost structure. Averaged {mean_pct} over {n} years with coefficient of variation of {cov_pct} — pricing power is weak or absent.",Gd="Insufficient annual history ({n} usable periods) to judge gross-margin persistence over the standard 10-year window.";function Vd(s,t){const a=Ae(s,_s),n=Ge(a,u=>!G(u.revenue)||u.revenue<=0||!G(u.grossProfit)?null:u.grossProfit/u.revenue);if(n.length<ot.MIN_PERIODS)return{id:"q1",label:vn,labelTooltip:yn,status:"na",value:"—",rawValue:null,observation:R(Gd,{n:n.length})};const i=as(n),r=Ht(n),o=n[0],l=n.length,c=i>=ot.GM_10Y_MEAN_PASS&&r<ot.GM_10Y_COV_PASS,m=!c&&i>=ot.GM_10Y_MEAN_CAUTION&&r<ot.GM_10Y_COV_CAUTION,h=c?"pass":m?"caution":"fail",y={mean_pct:z(i),cov_pct:z(r),latest_pct:z(o),n:l},j=R(h==="pass"?qd:h==="caution"?Bd:zd,y);return{id:"q1",label:vn,labelTooltip:yn,status:h,value:z(i),rawValue:i,sectorContext:ns(i,t?.gm_10y_mean,z,"higher_is_better"),observation:j}}const Na="Operational leanness",wa="Selling, general & administrative expenses as a share of gross profit. Cost-disciplined operators translate more of the gross-profit dollar into operating income; overhead-heavy businesses do not.",Yd="SG&A absorbs {ratio_pct} of gross profit — well below the 30% level associated with cost-disciplined operators.",Ud="SG&A absorbs {ratio_pct} of gross profit — in the competitive band between disciplined operators and overhead-heavy businesses.",Wd="SG&A absorbs {ratio_pct} of gross profit — overhead consumes most of the gross-profit dollar, leaving little for reinvestment or return of capital.",Hd="Gross profit is not positive in the latest period; SG&A leanness cannot be judged against a healthy cost base.",Qd="Latest SG&A or gross profit is not reported — operational leanness cannot be computed for this period.";function Kd(s,t){if(s.length===0)return da();const a=s[0],n=a.sellingGeneralAndAdministrativeExpenses,i=a.grossProfit;if(!G(n)||!G(i))return da();if(i<=0)return{id:"q2",label:Na,labelTooltip:wa,status:"fail",value:"—",rawValue:null,observation:R(Hd,{gp:i})};const r=n/i,o=r<xn.SGA_OVER_GP_PASS?"pass":r<xn.SGA_OVER_GP_CAUTION?"caution":"fail",l={ratio_pct:z(r)},c=R(o==="pass"?Yd:o==="caution"?Ud:Wd,l);return{id:"q2",label:Na,labelTooltip:wa,status:o,value:z(r),rawValue:r,sectorContext:ns(r,t?.sga_over_gp_latest,z,"lower_is_better"),observation:c}}function da(){return{id:"q2",label:Na,labelTooltip:wa,status:"na",value:"—",rawValue:null,observation:Qd}}const _a="Operating leverage",Aa="Operating margin level and trajectory over 10 years. Businesses that convert incremental revenue into disproportionately higher operating profit are widening their moat; declining margins signal erosion.",Xd="Operating margin at {om_latest_pct}, above the 15% durable-earning-power bar. Ten-year slope of {slope_bps} indicates non-eroding operating leverage.",Jd="Operating margin at {om_latest_pct} sits in the mid-band. Ten-year slope of {slope_bps} — watch whether the trend accelerates or stalls.",Zd="Operating margin at {om_latest_pct} is below the durable bar but the ten-year slope of {slope_bps} shows meaningful improvement.",eu="Operating margin at {om_latest_pct}, well below the 15% durable bar, with a ten-year slope of {slope_bps} — no evidence of operating leverage.",su="Insufficient annual history ({n} usable periods) to judge operating leverage over the standard window.",tu="Operating margin averaged {om_mean_pct} through the last {n}-year cycle (range {om_min_pct} to {om_max_pct}, peak-to-trough spread {spread_pp} pp). Through-cycle earnings power is durable.",au="Operating margin averaged {om_mean_pct} through the last {n}-year cycle — above the cost of capital on average but with material cycle amplitude (spread {spread_pp} pp).",nu="Operating margin averaged only {om_mean_pct} through the last {n}-year cycle — the cycle destroys enough operating profit that the base is not compounding.";function iu(s,t=!1,a){const n=Ae(s,_s),i=Ge(n,g=>!G(g.revenue)||g.revenue<=0||!G(g.operatingIncome)?null:g.operatingIncome/g.revenue);if(i.length<xs.MIN_PERIODS_FOR_SLOPE)return{id:"q3",label:_a,labelTooltip:Aa,status:"na",value:"—",rawValue:null,observation:R(su,{n:i.length})};const r=[...i].reverse(),o=r.map((g,x)=>x),l=$a(o,r),c=Number.isFinite(l)?l*1e4:NaN;if(t)return ru(i,r,c,a);const m=i[0],h=m>=xs.OM_LATEST_PASS&&Number.isFinite(c)&&c>=0,y=!h&&(m>=xs.OM_LATEST_CAUTION||m<xs.OM_LATEST_PASS&&Number.isFinite(c)&&c>xs.OM_SLOPE_IMPROVING_BPS),j=h?"pass":y?"caution":"fail",u={om_latest_pct:z(m),slope_bps:Md(c),n:i.length},f=j==="pass"?R(Xd,u):j==="caution"?m>=xs.OM_LATEST_CAUTION?R(Jd,u):R(Zd,u):R(eu,u);return{id:"q3",label:_a,labelTooltip:Aa,status:j,value:z(m),rawValue:m,sectorContext:ns(m,a?.om_latest,z,"higher_is_better"),observation:f}}function ru(s,t,a,n){const i=as(s),r=Math.min(...s),o=Math.max(...s),l=o-r,c=i>=xs.CYCLICAL.OM_10Y_MEAN_PASS&&Number.isFinite(a)&&a>=0,m=!c&&i>=xs.CYCLICAL.OM_10Y_MEAN_CAUTION,h=c?"pass":m?"caution":"fail",y={om_mean_pct:z(i),om_min_pct:z(r),om_max_pct:z(o),spread_pp:(l*100).toFixed(1),n:s.length},j=R(h==="pass"?tu:h==="caution"?au:nu,y);return{id:"q3",label:_a,labelTooltip:Aa,status:h,value:z(i),rawValue:i,sectorContext:ns(i,n?.om_10y_mean,z,"higher_is_better"),observation:j}}const $t="Financial durability",Lt="How many times operating income covers interest expense. Businesses that lean heavily on debt are fragile in a downturn — earnings compression that a durable business absorbs becomes existential for a leveraged one.",ou="No material interest expense reported — the balance sheet does not rely on debt-service capacity.",lu="Operating income covers interest expense {ratio_x}, well above the conservative 10x bar. Earnings compression would not threaten debt service.",cu="Operating income covers interest expense {ratio_x} — manageable, but leaves less cushion in a cyclical or macro downturn.",du="Operating income covers interest expense only {ratio_x}. A modest earnings compression would leave the business under financial stress.",uu="Operating income is not positive in the latest period — no coverage of interest expense from operations.",mu="Latest operating income or interest expense is not reported — coverage cannot be computed.";function hu(s,t){if(s.length===0)return jn();const a=s[0],n=a.operatingIncome,i=a.interestExpense;if(!G(n))return jn();const r=G(i)?Math.abs(i):0;if(r<1)return{id:"q4",label:$t,labelTooltip:Lt,status:"pass",value:"—",rawValue:null,observation:ou};if(n<=0)return{id:"q4",label:$t,labelTooltip:Lt,status:"fail",value:z(0),rawValue:0,observation:uu};const o=n/r,l=o>=bn.COVERAGE_PASS?"pass":o>=bn.COVERAGE_CAUTION?"caution":"fail",c={ratio_x:Qe(o)},m=R(l==="pass"?lu:l==="caution"?cu:du,c);return{id:"q4",label:$t,labelTooltip:Lt,status:l,value:Qe(o),rawValue:o,sectorContext:ns(o,t?.interest_coverage_latest,Qe,"higher_is_better"),observation:m}}function jn(){return{id:"q4",label:$t,labelTooltip:Lt,status:"na",value:"—",rawValue:null,observation:mu}}const Nn="Predictability",wn='Consistency of earnings over 10 years — profitable-year streak, EPS variability, and worst drawdown. Predictable earnings are the hallmark of the "inevitables" — businesses whose earnings power is durable through economic cycles.',pu="Positive earnings in {positive_years}/10 years, EPS coefficient of variation of {eps_cov_pct}, worst drawdown of {worst_dd_pct} — a predictable earnings base.",gu="Positive earnings in {positive_years}/10 years, EPS coefficient of variation of {eps_cov_pct} — predictable but with rough patches.",fu="Predictability is weak — positive earnings in only {positive_years}/10 years. Not a stable earning-power base.",xu="Predictability is weak — worst EPS drawdown of {worst_dd_pct} indicates a cycle-vulnerable earnings base.",bu="Positive earnings in {positive_years}/10 years, but EPS coefficient of variation of {eps_cov_pct} — earnings level is too variable to be considered predictable at the standard-quality bar.",vu="Insufficient annual history ({n} usable periods) to judge earnings predictability over the standard window.",yu="Positive earnings in {positive_years}/10 years with worst drawdown of {worst_dd_pct} — the business demonstrated durability through a full cycle. CoV of {eps_cov_pct} reflects the sector's natural amplitude, not fragility.",ju="Positive earnings in {positive_years}/10 years, CoV of {eps_cov_pct} — rough cycle but the business survived. Worst drawdown of {worst_dd_pct}.",Nu="Cycle-destroyed profile — only {positive_years}/10 profitable years and worst drawdown of {worst_dd_pct}. The cycle destroys enough earnings that the base does not compound.";function wu(s,t=!1,a){const n=Ae(s,_s),i=Ge(n,L=>L.netIncome),r=Ge(n,L=>L.epsDiluted),o=$e.MIN_ANNUAL_PERIODS;if(i.length<o||r.length<o)return{id:"q5",label:Nn,labelTooltip:wn,status:"na",value:"—",rawValue:null,observation:R(vu,{n:Math.min(i.length,r.length)})};const l=i.filter(L=>L>0).length,c=Ht(r),m=[...r].reverse(),h=La(m),y=t?$e.CYCLICAL.POSITIVE_YEARS_PASS:$e.POSITIVE_YEARS_PASS,j=t?$e.CYCLICAL.POSITIVE_YEARS_CAUTION:$e.POSITIVE_YEARS_CAUTION,u=t?$e.CYCLICAL.EPS_COV_PASS:$e.EPS_COV_PASS,f=t?$e.CYCLICAL.EPS_COV_CAUTION:$e.EPS_COV_CAUTION,g=t?$e.CYCLICAL.EPS_WORST_DRAWDOWN_PASS:$e.EPS_WORST_DRAWDOWN_PASS,x=t?$e.CYCLICAL.EPS_WORST_DRAWDOWN_FAIL:$e.EPS_WORST_DRAWDOWN_FAIL,S=l>=y&&Number.isFinite(c)&&c<u&&h>g,k=l<j||h<=x,w=S?"pass":k?"fail":l>=j&&Number.isFinite(c)&&c<f?"caution":"fail",p={positive_years:l,eps_cov_pct:z(c),worst_dd_pct:z(h),n:r.length},v=l<j?fu:h<=x?xu:bu,M=R(t?w==="pass"?yu:w==="caution"?ju:Nu:w==="pass"?pu:w==="caution"?gu:v,p);return{id:"q5",label:Nn,labelTooltip:wn,status:w,value:`${l}/10 positive`,rawValue:l,sectorContext:ns(l,a?.positive_years_10y,L=>`${Ld(L)}/10`,"higher_is_better"),observation:M}}const Di="Per-share compounding",qi="Diluted EPS growth vs. net income growth vs. share count trend. Aggregate earnings growth does not equal owner growth — the per-share view isolates whether the company is compounding c
2apital for its actual owners.",_u="Diluted EPS compounded at {eps_cagr_pct}/yr while share count declined {share_change_pct}/yr — buybacks amplified per-share economics.",Au="Diluted EPS compounded at {eps_cagr_pct}/yr with flat share count — per-share economics compounding cleanly.",Su="Diluted EPS compounded at {eps_cagr_pct}/yr, but share count grew {share_change_pct}/yr — dilution is diluting the owner economics.",Cu="Diluted EPS compounded only {eps_cagr_pct}/yr over the 10-year window — per-share economics are not meaningfully compounding.",Fu="Share count grew {share_change_pct}/yr — aggregate NI growth of {ni_cagr_pct}/yr does not translate into meaningful per-share economics.",_n="Diluted EPS is negative in an endpoint of the 10-year window — CAGR cannot be computed.";function Iu(s,t){const a=Ae(s,_s),n=Ge(a,ee=>ee.epsDiluted),i=Ge(a,ee=>ee.netIncome),r=Ge(a,ee=>ee.sharesDiluted??ee.shares);if(n.length<2||r.length<2)return An(_n);const o=n[0],l=n[n.length-1],c=i[0],m=i[i.length-1];if(!(l>0&&o>0))return An(_n);const h=n.length-1,y=wt(l,o,h),j=m>0&&c>0?wt(m,c,h):null,u=[...r].reverse(),f=u[0],g=u.map((ee,U)=>U),x=$a(g,u),S=f>0&&Number.isFinite(x)?x/f:NaN,k=y??-1/0,w=j??k,p=Number.isFinite(S)?S:0,v=k>=lt.EPS_CAGR_PASS&&k>=w-lt.EPS_ACCRETIVE_TOLERANCE&&p<=0,M=!v&&k>=lt.EPS_CAGR_CAUTION&&p<lt.SHARE_DILUTION_CAUTION_MAX,L=v?"pass":M?"caution":"fail",b={eps_cagr_pct:z(y),ni_cagr_pct:z(j),share_change_pct:z(Math.abs(p))},I=v?p<0?R(_u,b):R(Au,b):M?R(Su,b):p>=lt.SHARE_DILUTION_CAUTION_MAX?R(Fu,b):R(Cu,b);return{id:"q6",label:Di,labelTooltip:qi,status:L,value:z(y),rawValue:y,sectorContext:ns(y,t?.eps_cagr_10y,z,"higher_is_better"),observation:I}}function An(s){return{id:"q6",label:Di,labelTooltip:qi,status:"na",value:"—",rawValue:null,observation:s}}const Sn="Earnings quality",Cn='Whether reported net income reflects true economic earnings. High-quality earnings show up as normal tax rates, few "one-time" items, and operating cash flow that roughly matches reported net income.',Ru="Tax rate in the 15–30% band in {etr_normal}/10 years, non-recurring items in {nonrecurring}/10 years, and operating cash flow averaged {cfo_ni_pct} of reported net income — a clean earnings-quality profile.",ku="Earnings quality is broadly acceptable but with some noise — tax normality {etr_normal}/10, non-recurring items {nonrecurring}/10, CFO/NI averaged {cfo_ni_pct}.",Tu="Operating cash flow averaged only {cfo_ni_pct} of reported net income — reported earnings materially overstate cash generation. Investigate working c
2apital or accruals.",Ou="Reported earnings show low quality — tax normality {etr_normal}/10, non-recurring items {nonrecurring}/10, CFO/NI averaged {cfo_ni_pct}.",Eu="Insufficient data across income + cash flow to judge earnings quality over the standard window.";function Pu(s,t,a){const n=Ae(s,_s),i=Ae(t,_s);let r=0,o=0;for(const x of n){if(!G(x.incomeBeforeTax)||x.incomeBeforeTax<=0||!G(x.incomeTaxExpense))continue;const S=x.incomeTaxExpense/x.incomeBeforeTax;o++,S>=Ke.ETR_NORMAL_MIN&&S<=Ke.ETR_NORMAL_MAX&&r++}let l=0,c=0;for(const x of n){if(!G(x.operatingIncome)||x.operatingIncome===0||!G(x.otherIncomeExpense))continue;c++,Math.abs(x.otherIncomeExpense/x.operatingIncome)>Ke.NONRECURRING_MAGNITUDE_THRESHOLD&&l++}const m=[];for(let x=0;x<n.length;x++){const S=n[x]?.netIncome,k=i[x]?.operatingCashFlow??i[x]?.cfo;!G(S)||S<=0||G(k)&&m.push(k/S)}const h=m.length>0?as(m):NaN;if(o<5||c<5||m.length<5)return{id:"q7",label:Sn,labelTooltip:Cn,status:"na",value:"—",rawValue:null,observation:Eu};const y=r>=Ke.ETR_NORMAL_YEARS_PASS&&l<=Ke.NONRECURRING_MAX_PASS&&Number.isFinite(h)&&h>=Ke.CFO_OVER_NI_PASS,j=!y&&r>=Ke.ETR_NORMAL_YEARS_CAUTION&&l<=Ke.NONRECURRING_MAX_CAUTION&&Number.isFinite(h)&&h>=Ke.CFO_OVER_NI_CAUTION,u=y?"pass":j?"caution":"fail",f={etr_normal:r,nonrecurring:l,cfo_ni_pct:z(h)},g=u==="pass"?R(Ru,f):u==="caution"?R(ku,f):Number.isFinite(h)&&h<Ke.CFO_OVER_NI_CAUTION?R(Tu,f):R(Ou,f);return{id:"q7",label:Sn,labelTooltip:Cn,status:u,value:z(h),rawValue:h,sectorContext:ns(h,a?.cfo_over_ni_10y_mean,z,"higher_is_better"),observation:g}}const Ma="Returns on capital",Da="Return on invested capital — NOPAT divided by shareholder equity plus net debt. Compounders earn materially above their cost of capital durably; businesses that do not clear this bar destroy value regardless of headline growth.",$u="ROIC averaged {roic_mean_pct} over 10 years, latest reading {roic_latest_pct} — the business earns materially above its likely cost of capital, the defining characteristic of a durable compounder.",Lu="ROIC averaged {roic_mean_pct} over 10 years — above typical cost of capital but not exceptional. Latest reading {roic_latest_pct}.",Mu="ROIC averaged a strong {roic_mean_pct} over 10 years but the latest reading of {roic_latest_pct} shows deceleration. Watch whether returns rebuild or continue to compress.",Du="ROIC averaged {roic_mean_pct} over 10 years — not clearing a typical cost of capital. Reinvestment is likely destroying rather than compounding value.",qu="Insufficient IS + balance-sheet data over the 10-year window to compute ROIC reliably.",Bu="Through-cycle ROIC averaged {roic_mean_pct} with a trough reading of {roic_min_pct} — the business earned positive returns even at cycle lows, a signature of low-cost-position advantage.",zu="Through-cycle ROIC averaged {roic_mean_pct}, above cost of capital on average but volatile through the cycle (trough {roic_min_pct}).",Gu="Through-cycle ROIC averaged only {roic_mean_pct} with a trough of {roic_min_pct} — capital destroyed at some point in the cycle.";function Vu(s,t,a=!1,n){const i=Ae(s,_s),r=Ae(t,_s),o=[];for(let x=0;x<i.length;x++){const S=i[x],k=r[x];if(!k||!G(S?.operatingIncome)||!G(S?.incomeBeforeTax)||S.incomeBeforeTax===0||!G(S?.incomeTaxExpense))continue;const w=S.incomeTaxExpense/S.incomeBeforeTax,p=S.operatingIncome*(1-w),v=k.shareholdersEquity,M=k.totalDebt??k.longTermDebt,L=k.cash;if(!G(v))continue;const b=G(M)?M:0,I=G(L)?L:0,ee=v+b-I;ee<=0||o.push(p/ee)}if(o.length<5)return Uu();const l=as(o),c=o[0],m=Math.min(...o);if(a)return Yu(l,m,n);const h=l>=ds.ROIC_10Y_MEAN_PASS&&c>=ds.ROIC_LATEST_PASS,y=!h&&l>=ds.ROIC_10Y_MEAN_PASS&&c>=ds.ROIC_LATEST_CAUTION_MIN,j=!h&&!y&&l>=ds.ROIC_10Y_MEAN_CAUTION,u=h?"pass":y||j?"caution":"fail",f={roic_mean_pct:z(l),roic_latest_pct:z(c)},g=R(u==="pass"?$u:y?Mu:u==="caution"?Lu:Du,f);return{id:"q8",label:Ma,labelTooltip:Da,status:u,value:z(l),rawValue:l,sectorContext:ns(l,n?.roic_10y_mean,z,"higher_is_better"),observation:g}}function Yu(s,t,a){const n=s>=ds.CYCLICAL.ROIC_10Y_MEAN_PASS&&t>=ds.CYCLICAL.ROIC_10Y_MIN_PASS,i=s<ds.CYCLICAL.ROIC_10Y_MEAN_CAUTION||t<=ds.CYCLICAL.ROIC_10Y_MIN_FAIL,r=n?"pass":i?"fail":"caution",o={roic_mean_pct:z(s),roic_min_pct:z(t)},l=R(r==="pass"?Bu:r==="caution"?zu:Gu,o);return{id:"q8",label:Ma,labelTooltip:Da,status:r,value:z(s),rawValue:s,sectorContext:ns(s,a?.roic_10y_mean,z,"higher_is_better"),observation:l}}function Uu(){return{id:"q8",label:Ma,labelTooltip:Da,status:"na",value:"—",rawValue:null,observation:qu}}function Wu(s){const t=s.applyCyclicalModifier??!1,a=s.sectorMedians,n=Vd(s.income,a),i=Kd(s.income,a),r=iu(s.income,t,a),o=hu(s.income,a),l=wu(s.income,t,a),c=Iu(s.income,a),m=Pu(s.income,s.c
2ashflow,a),h=Vu(s.income,s.balance,t,a);return[{heading:"Moat and pricing power",results:[n,i]},{heading:"Operating leverage and durability",results:[r,o]},{heading:"Predictability and per-share compounding",results:[l,c]},{heading:"Earnings quality and returns on capital",results:[m,h]}]}const Fn={COVERAGE_PASS:1.3,COVERAGE_CAUTION:1},ct={CAGR_PASS:.03,CAGR_CAUTION:0,MIN_PERIODS:4},In={RATIO_PASS:.4,RATIO_CAUTION:.55},Rn={COVERAGE_PASS:3,COVERAGE_CAUTION:2},kt={RATIO_PASS:.9,RATIO_CAUTION:.75,MIN_PERIODS:4},Gs={GROWTH_PASS:.02,GROWTH_CAUTION:.08,MIN_PERIODS:4},Bt=10,Bi="Dividend safety",zi="Funds from operations (FFO = net income + depreciation & amortization) divided by dividends paid. Coverage below 1.0x means the current distribution is unsustainable from operations; 1.3x+ is the durable-safety bar.",Hu="FFO covers the current dividend {ratio_x} — a healthy cushion for both distribution safety and reinvestment.",Qu="FFO covers the current dividend {ratio_x} — above the sustainability floor but limited room for growth in the payout without pressuring reinvestment.",Ku="FFO covers the current dividend only {ratio_x} — the current distribution is not fully funded by operations.",Xu="Dividends paid not reported in the latest period — dividend safety cannot be judged.",kn="Net income or depreciation not reported in the latest period — FFO and dividend safety cannot be computed.";function Ju(s,t){const a=s[0],n=t[0],i=a?.netIncome,r=a?.depreciationAndAmortization;if(!G(i)||!G(r))return ua(kn);const o=i+r,l=n?.dividendsPaid;if(!G(l)||Math.abs(l)<1)return ua(Xu);const c=Math.abs(l);if(o<=0)return ua(kn);const m=o/c,h=m>=Fn.COVERAGE_PASS?"pass":m>=Fn.COVERAGE_CAUTION?"caution":"fail",y={ratio_x:Qe(m)},j=R(h==="pass"?Hu:h==="caution"?Qu:Ku,y);return{id:"q1",label:Bi,labelTooltip:zi,status:h,value:Qe(m),rawValue:m,observation:j}}function ua(s){return{id:"q1",label:Bi,labelTooltip:zi,status:"na",value:"—",rawValue:null,observation:s}}const Gi="FFO per share growth",Vi="Compound annual growth rate of funds-from-operations per diluted share. Per-share economics isolate whether ATM issuances and follow-on offerings dilute owner earnings faster than the underlying business grows.",Zu="FFO per share compounded at {cagr_pct}/yr over {n} years — genuine per-owner growth despite equity issuance.",em="FFO per share compounded at {cagr_pct}/yr — positive but below the 3%/yr bar for a durable REIT compounder.",sm="FFO per share contracted at {cagr_pct}/yr — new equity issuance is diluting owner earnings faster than the business grows.",Tn="Insufficient annual data ({n} periods) to judge FFO per share growth (minimum {min} required).";function tm(s){const t=Ae(s,Bt),a=[];for(const h of t){const y=h.netIncome,j=h.depreciationAndAmortization,u=h.sharesDiluted;if(!G(y)||!G(j)||!G(u)||u<=0)continue;const f=y+j;f<=0||a.push(f/u)}if(a.length<ct.MIN_PERIODS)return On(R(Tn,{n:a.length,min:ct.MIN_PERIODS}));const n=a.length,i=a[0],r=a[n-1],o=wt(r,i,n-1);if(o==null)return On(R(Tn,{n,min:ct.MIN_PERIODS}));const l=o>=ct.CAGR_PASS?"pass":o>=ct.CAGR_CAUTION?"caution":"fail",c={cagr_pct:z(o),n},m=R(l==="pass"?Zu:l==="caution"?em:sm,c);return{id:"q2",label:Gi,labelTooltip:Vi,status:l,value:z(o),rawValue:o,observation:m}}function On(s){return{id:"q2",label:Gi,labelTooltip:Vi,status:"na",value:"—",rawValue:null,observation:s}}const Yi="Balance-sheet leverage",Ui="Long-term debt as a share of total assets. REITs are structurally leveraged; above ~55% of gross assets constrains flexibility, forces asset sales in downturns, and elevates dividend risk.",am="Long-term debt is {ratio_pct} of total assets — conservative leverage, room for opportunistic acquisitions and durability in a rate-shock scenario.",nm="Long-term debt is {ratio_pct} of total assets — within the industry-normal band but limited financial flexibility.",im="Long-term debt is {ratio_pct} of total assets — elevated leverage constrains the REIT's ability to weather a rate shock or asset-price decline.",rm="Long-term debt or total assets not reported in the latest period — leverage cannot be computed.";function om(s){const t=s[0],a=t?.longTermDebt,n=t?.totalAssets;if(!G(a)||!G(n)||n<=0)return lm();const i=a/n,r=i<In.RATIO_PASS?"pass":i<In.RATIO_CAUTION?"caution":"fail",o={ratio_pct:z(i)},l=R(r==="pass"?am:r==="caution"?nm:im,o);return{id:"q3",label:Yi,labelTooltip:Ui,status:r,value:z(i),rawValue:i,observation:l}}function lm(){return{id:"q3",label:Yi,labelTooltip:Ui,status:"na",value:"—",rawValue:null,observation:rm}}const Wi="Interest coverage",Hi="FFO-equivalent (operating income + depreciation & amortization) divided by interest expense. REIT D&A is non-cash on appreciating real estate — using GAAP operating income alone systematically understates true cash coverage. 3x+ is the durable bar; below 2x approaches rating-agency stress territory.",cm="FFO-equivalent covers interest expense {ratio_x} — comfortable coverage even accounting for the sector's structural leverage.",dm="FFO-equivalent covers interest expense {ratio_x} — within the industry-normal band but tight cushion in a rate-shock scenario.",um="FFO-equivalent covers interest expense only {ratio_x} — approaching rating-agency stress territory for REITs.",mm="Operating income, depreciation, or interest expense not reported in the latest period — 
2coverage cannot be computed.";function hm(s){const t=s[0],a=t?.operatingIncome,n=t?.depreciationAndAmortization,i=t?.interestExpense;if(!G(a)||!G(n)||!G(i))return dt();const r=Math.abs(i);if(r<1)return dt();const o=a+n;if(o<=0)return dt();const l=o/r,c=l>=Rn.COVERAGE_PASS?"pass":l>=Rn.COVERAGE_CAUTION?"caution":"fail",m={ratio_x:Qe(l)},h=R(c==="pass"?cm:c==="caution"?dm:um,m);return{id:"q4",label:Wi,labelTooltip:Hi,status:c,value:Qe(l),rawValue:l,observation:h}}function dt(){return{id:"q4",label:Wi,labelTooltip:Hi,status:"na",value:"—",rawValue:null,observation:mm}}const Qi="Cash-flow quality",Ki="Mean of operating cash flow divided by FFO over the recent window. Close to 1.0 indicates FFO is a faithful cash proxy; sustained divergence suggests working-capital churn or aggressive add-backs.",pm="Operating cash flow averaged {ratio_x} of FFO over {n} years — reported FFO reflects underlying cash generation faithfully.",gm="Operating cash flow averaged {ratio_x} of FFO over {n} years — some divergence between reported FFO and cash truth; monitor working-capital trends.",fm="Operating cash flow averaged only {ratio_x} of FFO over {n} years — reported FFO materially overstates cash generation.",xm="Insufficient data ({n} periods) to judge FFO / cash-flow alignment (minimum {min} required).";function bm(s,t){const a=Ae(s,Bt),n=Ae(t,Bt),i=[];for(let m=0;m<a.length;m++){const h=a[m],y=n[m],j=h?.netIncome,u=h?.depreciationAndAmortization,f=y?.operatingCashFlow??y?.cfo;if(!G(j)||!G(u))continue;const g=j+u;g<=0||!G(f)||i.push(f/g)}if(i.length<kt.MIN_PERIODS)return vm(R(xm,{n:i.length,min:kt.MIN_PERIODS}));const r=as(i),o=r>=kt.RATIO_PASS?"pass":r>=kt.RATIO_CAUTION?"caution":"fail",l={ratio_x:Qe(r),n:i.length},c=R(o==="pass"?pm:o==="caution"?gm:fm,l);return{id:"q5",label:Qi,labelTooltip:Ki,status:o,value:Qe(r),rawValue:r,observation:c}}function vm(s){return{id:"q5",label:Qi,labelTooltip:Ki,status:"na",value:"—",rawValue:null,observation:s}}const Xi="Share count discipline",Ji="Annualized growth rate of diluted share count. REITs finance acquisitions via ATM programs and follow-on offerings; growth above ~8%/yr means new equity issuance is likely dilutive to existing owners.",ym="Share count grew {growth_pct}/yr over {n} years — disciplined equity issuance, unlikely to dilute existing owners meaningfully.",jm="Share count grew {growth_pct}/yr over {n} years — active equity issuance; whether it's accretive depends on whether acquisitions clear the cost of the new equity.",Nm="Share count grew {growth_pct}/yr over {n} years — heavy dilution. Per-owner economics require growth in FFO/share, not aggregate FFO, to remain intact.",ma="Insufficient annual data ({n} periods) to judge share count discipline (minimum {min} required).";function wm(s){const t=Ae(s,Bt),a=Ge(t,y=>y.sharesDiluted);if(a.length<Gs.MIN_PERIODS)return ha(R(ma,{n:a.length,min:Gs.MIN_PERIODS}));const n=[...a].reverse(),i=n[0];if(!G(i)||i<=0)return ha(R(ma,{n:a.length,min:Gs.MIN_PERIODS}));const r=n.map((y,j)=>j),o=$a(r,n);if(!Number.isFinite(o))return ha(R(ma,{n:a.length,min:Gs.MIN_PERIODS}));const l=o/i,c=l<=Gs.GROWTH_PASS?"pass":l<=Gs.GROWTH_CAUTION?"caution":"fail",m={growth_pct:z(l),n:a.length},h=R(c==="pass"?ym:c==="caution"?jm:Nm,m);return{id:"q6",label:Xi,labelTooltip:Ji,status:c,value:z(l),rawValue:l,observation:h}}function ha(s){return{id:"q6",label:Xi,labelTooltip:Ji,status:"na",value:"—",rawValue:null,observation:s}}
2function _m(s){const t=Ju(s.income,s.cashflow),a=tm(s.income),n=om(s.balance),i=hm(s.income),r=bm(s.income,s.cashflow),o=wm(s.income);return[{heading:"Distribution safety",results:[t,a]},{heading:"Balance sheet and durability",results:[n,i]},{heading:"Cash-flow quality and share discipline",results:[r,o]}]}const En={MARGIN_PASS:.025,MARGIN_CAUTION:.018},Pn={RATIO_PASS:.55,RATIO_CAUTION:.65},$n={ROA_PASS:.012,ROA_CAUTION:.009},Ln={ROE_PASS:.12,ROE_CAUTION:.08},Mn={RATIO_PASS:.08,RATIO_CAUTION:.06},ut={CAGR_PASS:.05,CAGR_CAUTION:.02,MIN_PERIODS:4},Xe={POSITIVE_YEARS_PASS:9,POSITIVE_YEARS_CAUTION:7,EPS_COV_PASS:.3,EPS_COV_CAUTION:.6,EPS_WORST_DRAWDOWN_PASS:-.4,EPS_WORST_DRAWDOWN_FAIL:-.6,MIN_ANNUAL_PERIODS:7},Sa=10,Zi="Net interest margin",er="Net interest income as a share of total assets — the bank's deposit-franchise pricing power. Proxy divides by total assets rather than interest-earning assets, so real NIM is typically 0.3-0.5pp higher.",Am="NII of {margin_pct} of total assets — strong deposit franchise; the bank captures a durable spread on its asset base.",Sm="NII of {margin_pct} of total assets — competitive but not top-tier; deposit costs and wholesale-funding reliance are pressuring the spread.",Cm="NII of {margin_pct} of total assets — weak spread capture; either high cost of funds or subpar asset yields relative to peers.",Fm="Net interest income or total assets not reported — NIM cannot be computed.";function Im(s,t){const a=s[0]?.netInterestIncome,n=t[0]?.totalAssets;if(!G(a)||!G(n)||n<=0)return Rm();const i=a/n,r=i>=En.MARGIN_PASS?"pass":i>=En.MARGIN_CAUTION?"caution":"fail",o={margin_pct:z(i,2)},l=R(r==="pass"?Am:r==="caution"?Sm:Cm,o);return{id:"q1",label:Zi,labelTooltip:er,status:r,value:z(i,2),rawValue:i,observation:l}}function Rm(){return{id:"q1",label:Zi,labelTooltip:er,status:"na",value:"—",rawValue:null,observation:Fm}}const sr="Efficiency ratio",tr="Operating expenses as a share of net bank revenue (NII + non-interest income). Buffett's WFC-era test: below 55% is best-in-class; 55-65% is industry-normal; above 65% signals overhead-heavy operations.",km="Operating expenses absorb {ratio_pct} of net bank revenue — best-in-class cost discipline consistent with a durable franchise.",Tm="Operating expenses absorb {ratio_pct} of net bank revenue — industry-normal band; monitor for margin pressure or cost-inflation trends.",Om="Operating expenses absorb {ratio_pct} of net bank revenue — overhead-heavy operations leave less operating leverage for shareholders.",Em="Revenue, interest expense, or operating expenses not reported — efficiency ratio cannot be computed.";function Pm(s){const t=s[0],a=t?.revenue,n=t?.interestExpense,i=t?.operatingExpenses;if(!G(a)||!G(n)||!G(i))return Dn();const r=a-Math.abs(n);if(r<=0)return Dn();const o=i/r,l=o<Pn.RATIO_PASS?"pass":o<Pn.RATIO_CAUTION?"caution":"fail",c={ratio_pct:z(o)},m=R(l==="pass"?km:l==="caution"?Tm:Om,c);return{id:"q2",label:sr,labelTooltip:tr,status:l,value:z(o),rawValue:o,observation:m}}function Dn(){return{id:"q2",label:sr,labelTooltip:tr,status:"na",value:"—",rawValue:null,observation:Em}}const ar="Return on assets",nr="Net income divided by total assets — the cleanest operating-quality metric for a bank (factors out leverage). 1.2%+ is the durable-quality bar; below 1% suggests weak spread, heavy cost base, or credit-cycle stress.",$m="ROA of {roa_pct} — the bank earns a full-cycle return on its asset base consistent with a durable franchise.",Lm="ROA of {roa_pct} — above stress-cycle thresholds but below the top-tier bank bar; monitor for cost-inflation or spread compression.",Mm="ROA of {roa_pct} — below the durable-quality bar; the bank is either overhead-heavy, running weak spread, or in a credit-cycle stress window.",Dm="Net income or total assets not reported — ROA cannot be computed.";function qm(s,t){const a=s[0]?.netIncome,n=t[0]?.totalAssets;if(!G(a)||!G(n)||n<=0)return Bm();const i=a/n,r=i>=$n.ROA_PASS?"pass":i>=$n.ROA_CAUTION?"caution":"fail",o={roa_pct:z(i,2)},l=R(r==="pass"?$m:r==="caution"?Lm:Mm,o);return{id:"q3",label:ar,labelTooltip:nr,status:r,value:z(i,2),rawValue:i,observation:l}}function Bm(){return{id:"q3",label:ar,labelTooltip:nr,status:"na",value:"—",rawValue:null,observation:Dm}}const ir="Return on equity",rr="Net income divided by shareholders equity. Bank equity is levered 10-12x into assets, so 12%+ ROE requires ROA of ~1.1%+ on typical bank leverage — internally consistent with Q3. Check pass on ROE + fail on ROA for over-leverage.",zm="ROE of {roe_pct} — attractive returns for shareholders on typical bank leverage.",Gm="ROE of {roe_pct} — acceptable but below the top-tier bank bar; the bank may be capital-constrained or earning subpar spread.",Vm="ROE of {roe_pct} — weak returns on shareholder capital; either weak operating returns or excess capital deployed.",Ym="Net income or shareholders equity not reported — ROE cannot be computed.";function Um(s,t){const a=s[0]?.netIncome,n=t[0]?.shareholdersEquity;if(!G(a)||!G(n)||n<=0)return Wm();const i=a/n,r=i>=Ln.ROE_PASS?"pass":i>=Ln.ROE_CAUTION?"caution":"fail",o={roe_pct:z(i,1)},l=R(r==="pass"?zm:r==="caution"?Gm:Vm,o);return{id:"q4",label:ir,labelTooltip:rr,status:r,value:z(i,1),rawValue:i,observation:l}}function Wm(){return{id:"q4",label:ir,labelTooltip:rr,status:"na",value:"—",rawValue:null,observation:Ym}}const or="Capital adequacy",lr="Total shareholders equity as a share of total assets. Modern well-capitalized US banks run 8-11%; below 6% approaches Basel III leverage floor; 2008-era failed banks operated below 5%.",Hm="Equity is {ratio_pct} of total assets — well-capitalized, ample cushion against credit cycles.",Qm="Equity is {ratio_pct} of total assets — within the regulatory-adequate band but limited buffer for a severe downtur
2n.",Km="Equity is {ratio_pct} of total assets — thin capital cushion approaching Basel III leverage-ratio stress floor.",Xm="Shareholders equity or total assets not reported — capital adequacy cannot be computed.";function Jm(s){const t=s[0]?.shareholdersEquity,a=s[0]?.totalAssets;if(!G(t)||!G(a)||a<=0)return Zm();const n=t/a,i=n>=Mn.RATIO_PASS?"pass":n>=Mn.RATIO_CAUTION?"caution":"fail",r={ratio_pct:z(n,1)},o=R(i==="pass"?Hm:i==="caution"?Qm:Km,r);return{id:"q5",label:or,labelTooltip:lr,status:i,value:z(n,1),rawValue:n,observation:o}}function Zm(){return{id:"q5",label:or,labelTooltip:lr,status:"na",value:"—",rawValue:null,observation:Xm}}const cr="Tangible book value per share growth",dr="Compound annual growth rate of tangible book value per diluted share. Buffett's central bank compounding metric: growing TBV/share means retained earnings are outrunning dilution and acquisition write-offs.",eh="Tangible book value per share compounded at {cagr_pct}/yr over {n} years — genuine per-owner value creation.",sh="Tangible book value per share compounded at {cagr_pct}/yr — positive but below the 5%/yr bar for a durable bank compounder.",th="Tangible book value per share compounded at only {cagr_pct}/yr — per-owner economics not compounding; new capital deployment is dilutive or destroying tangible value.",qn="Insufficient annual data ({n} periods) to judge TBV per share growth (minimum {min} required).";function ah(s,t){const a=Ae(s,Sa),n=Ae(t,Sa),i=[];for(let j=0;j<Math.min(a.length,n.length);j++){const u=n[j],f=a[j]?.sharesDiluted,g=u?.shareholdersEquity;if(!G(g)||!G(f)||f<=0)continue;const x=G(u?.goodwill)?u.goodwill:0,S=G(u?.intangibles)?u.intangibles:0,k=g-x-S;k<=0||i.push(k/f)}if(i.length<ut.MIN_PERIODS)return Bn(R(qn,{n:i.length,min:ut.MIN_PERIODS}));const r=i.length,o=i[0],l=i[r-1],c=wt(l,o,r-1);if(c==null)return Bn(R(qn,{n:r,min:ut.MIN_PERIODS}));const m=c>=ut.CAGR_PASS?"pass":c>=ut.CAGR_CAUTION?"caution":"fail",h={cagr_pct:z(c),n:r},y=R(m==="pass"?eh:m==="caution"?sh:th,h);return{id:"q6",label:cr,labelTooltip:dr,status:m,value:z(c),rawValue:c,observation:y}}function Bn(s){return{id:"q6",label:cr,labelTooltip:dr,status:"na",value:"—",rawValue:null,observation:s}}const ur="Earnings predictability",mr="Positive-year streak, EPS coefficient of variation, and worst EPS drawdown over the available window. Durable banks earn positive every year with moderate variability; multiple loss years or high CoV signal credit-cycle vulnerability.",nh="Positive earnings in {positive_years}/10 years, EPS coefficient of variation of {eps_cov_pct}, worst drawdown of {worst_dd_pct} — a predictable bank earnings base.",ih="Positive earnings in {positive_years}/10 years, EPS coefficient of variation of {eps_cov_pct} — predictable enough, with some rough years.",rh="Positive earnings in only {positive_years}/10 years with EPS coefficient of variation of {eps_cov_pct} — the bank's earnings are cycle-vulnerable.",oh="Insufficient annual history ({n} periods) to judge earnings predictability (minimum {min} required).";function lh(s){const t=Ae(s,Sa),a=Ge(t,u=>u.netIncome),n=Ge(t,u=>u.epsDiluted);if(a.length<Xe.MIN_ANNUAL_PERIODS||n.length<Xe.MIN_ANNUAL_PERIODS)return ch(R(oh,{n:Math.min(a.length,n.length),min:Xe.MIN_ANNUAL_PERIODS}));const i=a.filter(u=>u>0).length,r=Ht(n),o=La([...n].reverse()),l=i>=Xe.POSITIVE_YEARS_PASS&&Number.isFinite(r)&&r<Xe.EPS_COV_PASS&&o>Xe.EPS_WORST_DRAWDOWN_PASS,c=i<Xe.POSITIVE_YEARS_CAUTION||o<=Xe.EPS_WORST_DRAWDOWN_FAIL,m=!l&&!c&&i>=Xe.POSITIVE_YEARS_CAUTION&&Number.isFinite(r)&&r<Xe.EPS_COV_CAUTION,h=l?"pass":m?"caution":"fail",y={positive_years:i,eps_cov_pct:z(r),worst_dd_pct:z(o),n:n.length},j=R(h==="pass"?nh:h==="caution"?ih:rh,y);return{id:"q7",label:ur,labelTooltip:mr,status:h,value:`${i}/10 positive`,rawValue:i,observation:j}}function ch(s){return{id:"q7",label:ur,labelTooltip:mr,status:"na",value:"—",rawValue:null,observation:s}}function dh(s){const t=Im(s.income,s.balance),a=Pm(s.income),n=qm(s.income,s.balance),i=Um(s.income,s.balance),r=Jm(s.balance),o=ah(s.income,s.balance),l=lh(s.income);return[{heading:"Interest margin and cost discipline",results:[t,a]},{heading:"Returns on capital",results:[n,i]},{heading:"Capital adequacy and compounding",results:[r,o,l]}]}const zn={MARGIN_PASS:.1,MARGIN_CAUTION:.05},Gn={ROE_PASS:.1,ROE_CAUTION:.07},Vn={RATIO_PASS:.2,RATIO_CAUTION:.12},mt={CAGR_PASS:.08,CAGR_CAUTION:.04,MIN_PERIODS:4},Tt={RATIO_PASS:1.2,RATIO_CAUTION:.9,MIN_PERIODS:4},Je={POSITIVE_YEARS_PASS:9,POSITIVE_YEARS_CAUTION:7,EPS_COV_PASS:.3,EPS_COV_CAUTION:.6,EPS_WORST_DRAWDOWN_PASS:-.4,EPS_WORST_DRAWDOWN_FAIL:-.6,MIN_ANNUAL_PERIODS:7},_t=10,hr="Underwriting profitability",pr="Operating income as a share of revenue. Captures comb
2ined underwriting + investment profitability (FMP embeds investment income in insurance revenue). Best-in-class P&C insurers earn 10-20% through-cycle.",uh="Operating margin of {margin_pct} — strong underwriting and investment profitability consistent with a durable P&C franchise.",mh="Operating margin of {margin_pct} — profitable but below the top-tier P&C bar; monitor for cat-year exposure or pricing pressure.",hh="Operating margin of {margin_pct} — insufficient underwriting + investment profitability to compound value durably; the insurer is either in a loss year or structurally under-earning.",ph="Revenue or operating income not reported — underwriting profitability cannot be computed.";function gh(s){const t=s[0],a=t?.revenue,n=t?.operatingIncome;if(!G(a)||a<=0||!G(n))return fh();const i=n/a,r=i>=zn.MARGIN_PASS?"pass":i>=zn.MARGIN_CAUTION?"caution":"fail",o={margin_pct:z(i)},l=R(r==="pass"?uh:r==="caution"?mh:hh,o);return{id:"q1",label:hr,labelTooltip:pr,status:r,value:z(i),rawValue:i,observation:l}}function fh(){return{id:"q1",label:hr,labelTooltip:pr,status:"na",value:"—",rawValue:null,observation:ph}}const gr="Return on equity",fr="Net income divided by shareholders equity. P&C insurers are less levered than banks so a lower ROE bar applies; 10%+ is durable-quality; below 7% suggests weak underwriting, poor investment yield, or excess capital.",xh="ROE of {roe_pct} — attractive returns on shareholder capital for a P&C insurer.",bh="ROE of {roe_pct} — acceptable but below the top-tier P&C bar.",vh="ROE of {roe_pct} — weak returns on shareholder capital; either weak underwriting, poor investment yield, or excess capital.",yh="Net income or shareholders equity not reported — ROE cannot be computed.";function jh(s,t){const a=s[0]?.netIncome,n=t[0]?.shareholdersEquity;if(!G(a)||!G(n)||n<=0)return Nh();const i=a/n,r=i>=Gn.ROE_PASS?"pass":i>=Gn.ROE_CAUTION?"caution":"fail",o={roe_pct:z(i,1)},l=R(r==="pass"?xh:r==="caution"?bh:vh,o);return{id:"q2",label:gr,labelTooltip:fr,status:r,value:z(i,1),rawValue:i,observation:l}}function Nh(){return{id:"q2",label:gr,labelTooltip:fr,status:"na",value:"—",rawValue:null,observation:yh}}const xr="Capital adequacy",br="Total shareholders equity as a share of total assets. Well-capitalized P&C insurers run 20-35% — higher than banks because insurance liabilities can spike unpredictably (catastrophes, adverse reserve development).",wh="Equity is {ratio_pct} of total assets — well-capitalized, ample cushion against a cat year or adverse reserve development.",_h="Equity is {ratio_pct} of total assets — within the regulatory-adequate band but limited buffer for a severe cat event.",Ah="Equity is {ratio_pct} of total assets — thinly capitalized; a single-year cat event or reserve strengthening could pressure the balance sheet.",Sh="Shareholders equity or total assets not reported — capital adequacy cannot be computed.";function Ch(s){const t=s[0]?.shareholdersEquity,a=s[0]?.totalAssets;if(!G(t)||!G(a)||a<=0)return Fh();const n=t/a,i=n>=Vn.RATIO_PASS?"pass":n>=Vn.RATIO_CAUTION?"caution":"fail",r={ratio_pct:z(n,1)},o=R(i==="pass"?wh:i==="caution"?_h:Ah,r);return{id:"q3",label:xr,labelTooltip:br,status:i,value:z(n,1),rawValue:n,observation:o}}function Fh(){return{id:"q3",label:xr,labelTooltip:br,status:"na",value:"—",rawValue:null,observation:Sh}}const vr="Book value per share growth",yr="Compound annual growth of tangible book value per diluted share. The Berkshire-style insurance-quality metric: retained underwriting profits plus investment gains, minus dilution, minus goodwill amortization.",Ih="Tangible book value per share compounded at {cagr_pct}/yr over {n} years — genuine per-owner value creation from retained profits and investment gains.",Rh="Tangible book value per share compounded at {cagr_pct}/yr — positive but below the 8%/yr bar for a durable insurance compounder.",kh="Tangible book value per share compounded at only {cagr_pct}/yr — per-owner economics stagnant or shrinking; retained profits are not compounding meaningfully.",Yn="Insufficient annual data ({n} periods) to judge TBV per share growth (minimum {min} required).";function Th(s,t){const a=Ae(s,_t),n=Ae(t,_t),i=[];for(let j=0;j<Math.min(a.length,n.length);j++){const u=n[j],f=a[j]?.sharesDiluted,g=u?.shareholdersEquity;if(!G(g)||!G(f)||f<=0)continue;const x=G(u?.goodwill)?u.goodwill:0,S=G(u?.intangibles)?u.intangibles:0,k=g-x-S;k<=0||i.push(k/f)}if(i.length<mt.MIN_PERIODS)return Un(R(Yn,{n:i.length,min:mt.MIN_PERIODS}));const r=i.length,o=i[0],l=i[r-1],c=wt(l,o,r-1);if(c==null)return Un(R(Yn,{n:r,min:mt.MIN_PERIODS}));const m=c>=mt.CAGR_PASS?"pass":c>=mt.CAGR_CAUTION?"caution":"fail",h={cagr_pct:z(c),n:r},y=R(m==="pass"?Ih:m==="caution"?Rh:kh,h);return{id:"q4",label:vr,labelTooltip:yr,status:m,value:z(c),rawValue:c,observation:y}}function Un(s){return{id:"q4",label:vr,labelTooltip:yr,status:"na",value:"—",rawValue:null,observation:s}}const jr="Cash generation",Nr='Mean of operating cash flow divided by net income. P&C insurers collect premiums before paying claims (the "float" phenomenon) so CFO should exceed NI. Ratio ≥ 1.2x indicates genuine float building; below 0.9x sustained means reserves are running off.',Oh="Operating cash flow averaged {ratio_x} of reported net income over {n} years — genuine float building, the hallmark of a durable P&C franchise.",Eh="Operating cash flow averaged {ratio_x} of reported net income over {n} years — cash generation matches earnings but not building meaningful float.",Ph="Operating cash flow averaged only {ratio_x} of reported net income over {n} years — the insurer's reserve base is running off faster than new premiums are building it.",$h="Insufficient data ({n} periods) to judge cash generation (minimum {min} required).";function Lh(s,t){const a=Ae(s,_t),n=Ae(t,_t),i=[];for(let m=0;m<Math.min(a.length,n.length);m++){const h=a[m]?.netIncome,y=n[m],j=y?.operatingCashFlow??y?.cfo;!G(h)||h<=0||G(j)&&i.push(j/h)}if(i.length<Tt.MIN_PERIODS)return Mh(R($h,{n:i.length,min:Tt.MIN_PERIODS}));const r=as(i),o=r>=Tt.RATIO_PASS?"pass":r>=Tt.RATIO_CAUTION?"caution":"fail",l={ratio_x:Qe(r),n:i.length},c=R(o==="pass"?Oh:o==="caution"?Eh:Ph,l);return{id:"q5",label:jr,labelTooltip:Nr,status:o,value:Qe(r),rawValue:r,observation:c}}function Mh(s){return{id:"q5",label:jr,labelTooltip:Nr,status:"na",value:"—",rawValue:null,observation:s}}const wr="Earnings predictability",_r="Positive-year streak, EPS coefficient of variation, and worst EPS drawdown over the available window. Durable P&C insurers earn positive every year with moderate variability; multiple loss years signal cat-exposure or under-pricing.",Dh="Positive earnings in {positive_years}/10 years, EPS coefficient of variation of {eps_cov_pct}, worst drawdown of {worst_dd_pct} — a predictable insurance earnings base.",qh="Positive earnings in {positive_years}/10 years, EPS coefficient of variation of {eps_cov_pct} — predictable enough, with some rough cat-exposed years.",Bh="Positive earnings in only {positive_years}/10 years with EPS coefficient of variation of {eps_cov_pct} — the insurer is cat-vulnerable or systematically under-priced through cycles.",zh="Insufficient annual history ({n} periods) to judge earnings predictability (minimum {min} required).";function Gh(s){const t=Ae(s,_t),a=Ge(t,u=>u.netIncome),n=Ge(t,u=>u.epsDiluted);if(a.length<Je.MIN_ANNUAL_PERIODS||n.length<Je.MIN_ANNUAL_PERIODS)return Vh(R(zh,{n:Math.min(a.length,n.length),min:Je.MIN_ANNUAL_PERIODS}));const i=a.filter(u=>u>0).length,r=Ht(n),o=La([...n].reverse()),l=i>=Je.POSITIVE_YEARS_PASS&&Number.isFinite(r)&&r<Je.EPS_COV_PASS&&o>Je.EPS_WORST_DRAWDOWN_PASS,c=i<Je.POSITIVE_YEARS_CAUTION||o<=Je.EPS_WORST_DRAWDOWN_FAIL,m=!l&&!c&&i>=Je.POSITIVE_YEARS_CAUTION&&Number.isFinite(r)&&r<Je.EPS_COV_CAUTION,h=l?"pass":m?"caution":"fail",y={positive_years:i,eps_cov_pct:z(r),worst_dd_pct:z(o),n:n.length},j=R(h==="pass"?Dh:h==="caution"?qh:Bh,y);return{id:"q6",label:wr,labelTooltip:_r,status:h,value:`${i}/10 positive`,rawValue:i,observation:j}}function Vh(s){return{id:"q6",label:wr,labelTooltip:_r,status:"na",value:"—",rawValue:null,observation:s}}function Yh(s){const t=gh(s.income),a=jh(s.income,s.balance),n=Ch(s.balance),i=Th(s.income,s.balance),r=Lh(s.income,s.c
2ashflow),o=Gh(s.income);return[{heading:"Underwriting and returns on capital",results:[t,a]},{heading:"Capital adequacy and compounding",results:[n,i]},{heading:"Cash discipline and predictability",results:[r,o]}]}const Uh={REIT:{label:"REIT",note:"A REIT-specific scorecard (FFO / AFFO / dividend coverage / same-store NOI) is under development. GAAP net income is not the right lens for real estate — the universal template is intentionally not shown for this sector."},BANK:{label:"Bank",note:"A bank-specific scorecard (net interest margin / efficiency ratio / loan-loss coverage) is under development. Universal quality metrics do not apply to banks — the underlying revenue construct is fundamentally different."},INSURANCE_PC:{label:"Insurance",note:"A P&C insurance-specific scorecard (combined ratio / float growth / underwriting margin) is under development. Universal metrics do not apply — reported net income is distorted by reserve development and realized gains."},PLACEHOLDER:{label:"Detailed scorecard not available",note:"A sector-appropriate quality scorecard is not yet available for this business type. See the detailed statement below for the underlying data."}};function Wh({template:s,hybridBanner:t}){const{label:a,note:n}=Uh[s];return e.jsx(_e,{variant:"elevated","data-quality-scorecard-placeholder":!0,children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{className:"text-base md:text-lg font-semibold tracking-tight",children:"Long-Term Quality Lens"}),e.jsx("p",{className:"text-xs text-muted-foreground uppercase tracking-wider",children:a})]}),t&&e.jsx("p",{className:"text-sm text-muted-foreground border-l-2 border-primary/40 pl-3",children:t}),e.jsx("p",{className:"text-sm text-muted-foreground leading-relaxed",children:n}),e.jsx("p",{className:"text-[11px] leading-relaxed text-muted-foreground pt-2 border-t border-border",children:ft})]})})}function Ot(s){switch(s){case"UNIVERSAL":return"Universal Business";case"UNIVERSAL_CYCLICAL":return"Cyclical Business";case"REIT":return"REIT";case"BANK":return"Bank";case"INSURANCE_PC":return"Insurance (P&C)";default:return"Detailed scorecard not available"}}function Hh({symbol:s,sector:t,industry:a,subIndustry:n,annualIncome:i,annualBalance:r,annualCashflow:o}){const{template:l,hybridBanner:c}=Pd({symbol:s,sector:t,industry:a,subIndustry:n}),{medians:m}=Rd(t,{cyclical:l==="UNIVERSAL_CYCLICAL",enabled:l==="UNIVERSAL"||l==="UNIVERSAL_CYCLICAL"});if(l==="UNIVERSAL"||l==="UNIVERSAL_CYCLICAL"){const h=Wu({income:xe(i).slice(0,10),balance:xe(r).slice(0,10),cashflow:xe(o).slice(0,10),applyCyclicalModifier:l==="UNIVERSAL_CYCLICAL",sectorMedians:m});return e.jsx(St,{title:"Long-Term Quality Lens",templateLabel:Ot(l),hybridBanner:c,disclaimer:ft,sections:h})}if(l==="REIT"){const h=_m({income:xe(i).slice(0,10),balance:xe(r).slice(0,10),cashflow:xe(o).slice(0,10)});return e.jsx(St,{title:"Long-Term Quality Lens",templateLabel:Ot(l),hybridBanner:c,disclaimer:ft,sections:h})}if(l==="BANK"){const h=dh({income:xe(i).slice(0,10),balance:xe(r).slice(0,10),cashflow:xe(o).slice(0,10)});return e.jsx(St,{title:"Long-Term Quality Lens",templateLabel:Ot(l),hybridBanner:c,disclaimer:ft,sections:h})}if(l==="INSURANCE_PC"){const h=Yh({income:xe(i).slice(0,10),balance:xe(r).slice(0,10),cashflow:xe(o).slice(0,10)});return e.jsx(St,{title:"Long-Term Quality Lens",templateLabel:Ot(l),hybridBanner:c,disclaimer:ft,sections:h})}return e.jsx(Wh,{template:l,hybridBanner:c})}function Qh({incomeData:s}){const t=xe(s).slice(0,8),a=t.length,n=t[a-1],i=t[0],r=(u,f)=>a>1&&u!=null&&u>0&&f!=null&&f>0?Math.pow(f/u,1/(a-1))-1:void 0,o=r(n?.revenue,i?.revenue),l=r(n?.netIncome,i?.netIncome),c=i?.grossProfit!=null&&i?.revenue?i.grossProfit/i.revenue:void 0,m=i?.netIncome!=null&&i?.revenue?i.netIncome/i.revenue:void 0,h=u=>u!=null&&Number.isFinite(u)?`${(u*100).toFixed(1)}%`:"—",[y,j]=(()=>{const u=o??-1/0,f=l??-1/0,g=m??0;return u>=.05&&f>=.05&&g>=.1?["success",e.jsxs("p",{children:["Strong revenue growth combined with healthy profit margins indicates a"," ",e.jsx("strong",{children:"well-managed, growing business"}),". This supports sustainable competitive advantages and pricing power."]},"strong")]:u>=0&&g>=.05?["info",e.jsxs("p",{children:["The company shows ",e.jsx("strong",{children:"stable fundamentals"})," with acceptable margins. Monitor for signs of accelerating growth or margin expansion opportunities."]},"stable")]:["warning",e.jsxs("p",{children:["Weak profitability trends suggest ",e.jsx("strong",{children:"operational challenges"}),". Consider whether current difficulties are cyclical or structural before investing."]},"weak")]})();return e.jsx(ka,{title:"Income Statement Summary & Analysis",subtitle:"Key insights and investment implications",groups:[{heading:"Growth Metrics",metrics:[{label:e.jsx($,{id:"cagr-revenue",data:P.cagr,children:e.jsx("span",{children:"Revenue CAGR:"})}),value:h(o)},{label:e.jsx($,{id:"cagr-netincome",data:P.cagr,children:e.jsx("span",{children:"Net Income CAGR:"})}),value:h(l)},{label:"Latest Revenue:",value:i?.revenue?Re(i.revenue):"N/A"}]},{heading:"Profitability Metrics",metrics:[{label:"Gross Margin:",value:h(c)},{label:"Net Margin:",value:h(m)},{label:"Latest Net Income:",value:i?.netIncome?Re(i.netIncome):"N/A"}]}],analysis:{heading:"Investment Analysis",tone:y,children:j}})}
2function Kh({incomeData:s,periodType:t,symbol:a,sector:n,industry:i,subIndustry:r,balanceData:o,cashflowData:l}){const{enabled:c}=eo("long_term_quality_lens_v1",!1);return c&&!!a&&Array.isArray(o)&&Array.isArray(l)&&s.length>0?e.jsx(Hh,{symbol:a,sector:n,industry:i,subIndustry:r,annualIncome:s,annualBalance:o,annualCashflow:l}):e.jsx(Qh,{incomeData:s})}function Xh({balanceData:s,periodType:t}){const n=xe(s).slice(0,8)[0],i=n&&typeof n.longTermDebt=="number"?n.longTermDebt:void 0,r=n&&typeof n.shareholdersEquity=="number"?n.shareholdersEquity:void 0,o=n&&typeof n.currentAssets=="number"?n.currentAssets:void 0,l=n&&typeof n.currentLiabilities=="number"?n.currentLiabilities:void 0,c=i!=null&&r!=null&&r!==0?i/r:void 0,m=o!=null&&l!=null&&l!==0?o/l:void 0,[h,y]=(()=>{const j=c??1/0,u=m??0;return j<.5&&u>=1.5?["success","Conservative"]:j<1&&u>=1?["info","Balanced"]:["warning","Aggressive"]})();return e.jsx(Ia,{title:"Balance Sheet Overview",subtitle:"Financial strength and leverage assessment",metrics:[{label:"Total Assets",value:n?.totalAssets?Re(n.totalAssets):"N/A"},{label:"Debt/Equity",value:c!=null&&Number.isFinite(c)?c.toFixed(2):"N/A"},{label:e.jsx($,{id:"currentRatio-overview",data:P.currentRatio,children:e.jsx("span",{children:"Current Ratio"})}),value:m!=null&&Number.isFinite(m)?m.toFixed(2):"N/A"},{label:"Financial Health",value:y,tone:h}]})}function Jh({balanceData:s,periodType:t}){const a=xe(s).slice(0,8).reverse();return e.jsx(ci,{title:"Balance Sheet Trends",subtitle:"Historical asset and liability composition",data:a,series:[{dataKey:"totalAssets",name:"Total Assets",tone:"primary"},{dataKey:"shareholdersEquity",name:"Shareholders Equity",tone:"chart-4"},{dataKey:"longTermDebt",name:"Long Term Debt",tone:"destructive"}],yAxisFormatter:Re,tooltipFormatter:Re,emptyMessage:"No balance sheet data available"})}function Ze(s,t){return!t||!P[t]?s:e.jsx($,{id:t,data:P[t],children:e.jsx("span",{children:s})})}function Zh({balanceData:s,periodType:t}){const a=xe(s).slice(0,8),n=r=>Re(r),i=t==="annual"?e.jsx($,{id:"yoyGrowth-balance",data:P.yoyGrowth,children:e.jsx("span",{children:"YoY Growth"})}):e.jsx($,{id:"qoqGrowth-balance",data:P.qoqGrowth,children:e.jsx("span",{children:"QoQ Growth"})});return e.jsx(Ra,{title:"Balance Sheet Details",subtitle:"Comprehensive balance sheet breakdown",data:a,periodKey:"period",formatValue:n,periodType:t,subRowLabel:i,metrics:[{key:"currentAssets",label:Ze("Current Assets","currentAssets"),mobileLabel:Ze("Curr Assets","currentAssets")},{key:"fixedAssets",label:Ze("Fixed Assets","fixedAssets")},{key:"intangibles",label:Ze("Intangibles","intangibles")},{key:"currentLiabilities",label:Ze("Current Liabilities","currentLiabilities"),mobileLabel:Ze("Curr Liab","currentLiabilities")},{key:"longTermDebt",label:Ze("Long Term Debt","totalDebt"),mobileLabel:Ze("LT Debt","totalDebt")},{key:"shareholdersEquity",label:Ze("Shareholders Equity","shareholdersEquity"),mobileLabel:Ze("Equity","shareholdersEquity")}]})}function ep({balanceData:s,periodType:t}){const n=xe(s).slice(0,8)[0],i=n&&typeof n.longTermDebt=="number"?n.longTermDebt:void 0,r=n&&typeof n.shareholdersEquity=="number"?n.shareholdersEquity:void 0,o=n&&typeof n.currentAssets=="number"?n.currentAssets:void 0,l=n&&typeof n.currentLiabilities=="number"?n.currentLiabilities:void 0,c=n&&typeof n.cash=="number"?n.cash:void 0,m=i!=null&&r!=null&&r!==0?i/r:void 0,h=o!=null&&l!=null&&l!==0?o/l:void 0,y=c!=null&&i!=null?c-i:void 0,j=g=>Re(g),[u,f]=(()=>{const g=m??1/0,x=h??0;return g<.5&&x>=1.5?["success",e.jsxs("p",{children:["The company maintains a ",e.jsx("strong",{children:"conservative balance sheet"})," with low leverage and strong liquidity. This provides resilience during economic downturns and flexibility for growth investments."]},"conservative")]:g<1&&x>=1?["info",e.jsxs("p",{children:["The balance sheet shows ",e.jsx("strong",{children:"reasonable leverage"})," with adequate liquidity. Monitor debt levels and ensure cash flow can service obligations comfortably."]},"balanced")]:["warning",e.jsxs("p",{children:["The company has ",e.jsx("strong",{children:"elevated leverage or weak liquidity"}),". This increases financial risk, particularly during economic stress periods. Seek wider margin of safety."]}
2,"aggressive")]})();return e.jsx(ka,{title:"Balance Sheet Summary & Analysis",subtitle:"Financial strength and risk assessment",groups:[{heading:"Asset Composition",metrics:[{label:"Total Assets:",value:n?.totalAssets?j(n.totalAssets):"N/A"},{label:"Current Assets:",value:o?j(o):"N/A"},{label:e.jsx($,{id:"cashAndEquivalents-balance-summary",data:P.cashAndEquivalents,children:e.jsx("span",{children:"Cash & Equivalents:"})}),value:c?j(c):"N/A"}]},{heading:"Leverage & Liquidity",metrics:[{label:"Debt/Equity Ratio:",value:m!=null&&Number.isFinite(m)?m.toFixed(2):"N/A"},{label:e.jsx($,{id:"currentRatio-balance-summary",data:P.currentRatio,children:e.jsx("span",{children:"Current Ratio:"})}),value:h!=null&&Number.isFinite(h)?h.toFixed(2):"N/A"},{label:e.jsx($,{id:"netCashPosition-balance-summary",data:P.netCashPosition,children:e.jsx("span",{children:"Net Cash Position:"})}),value:j(y)}]}],analysis:{heading:"Investment Analysis",tone:u,children:f}})}function sp({cashflowData:s,periodType:t}){const a=xe(s).slice(0,8),n=u=>typeof u.fcf=="number"?u.fcf:typeof u.operatingCashFlow=="number"&&typeof u.capex=="number"?u.operatingCashFlow-u.capex:void 0,i=a.map(n).filter(u=>u!=null&&Number.isFinite(u)),r=i.slice(0,4).filter(u=>u>0).length,o=t==="quarterly"?4:3,l=a.slice(0,o).reduce((u,f)=>u+(n(f)??0),0),c=a.slice(0,o).reduce((u,f)=>u+(typeof f.dividendsPaid=="number"?Math.abs(f.dividendsPaid):0),0),m=l>0?c/l:void 0,h=u=>u!=null&&Number.isFinite(u)?`${(u*100).toFixed(0)}%`:"—",[y,j]=(()=>{const u=m??1/0;return r>=3&&u<=.6?["success","Strong"]:r>=2&&u<=1?["info","Balanced"]:["warning","Weak"]})();return e.jsx(Ia,{title:"Cash Flow Overview",subtitle:"Cash generation and capital allocation assessment",metrics:[{label:"Latest FCF",value:i[0]!=null?Re(i[0]):"N/A"},{label:t==="quarterly"?"FCF (TTM)":"FCF (3-yr total)",value:Re(l)},{label:e.jsx($,{id:"payoutCoverage-overview",data:P.payoutCoverage,children:e.jsx("span",{children:"Payout Coverage"})}),value:h(m)},{label:"Cash Flow Quality",value:j,tone:y}]})}function tp({cashflowData:s,periodType:t}){const a=xe(s).slice(0,8).reverse();return e.jsx(xo,{title:"Cash Flow Trends",subtitle:"Historical cash flow components",data:a,series:[{dataKey:"operatingCashFlow",name:"Operating Cash Flow",tone:"chart-1"},{dataKey:"fcf",name:"Free Cash Flow",tone:"chart-4"},{dataKey:"capex",name:"Capital Expenditures",tone:"loss"}],yAxisFormatter:Re,tooltipFormatter:Re,emptyMessage:"No cash flow data available"})}function Be(s,t){return!t||!P[t]?s:e.jsx($,{id:t,data:P[t],children:e.jsx("span",{children:s})})}function ap({cashflowData:s,periodType:t}){const a=xe(s).slice(0,8),n=r=>Re(r),i=t==="annual"?e.jsx($,{id:"yoyGrowth-cashflow",data:P.yoyGrowth,children:e.jsx("span",{children:"YoY Growth"})}):e.jsx($,{id:"qoqGrowth-cashflow",data:P.qoqGrowth,children:e.jsx("span",{children:"QoQ Growth"})});return e.jsx(Ra,{title:"Cash Flow Details",subtitle:"Comprehensive cash flow breakdown",data:a,periodKey:"period",formatValue:n,periodType:t,subRowLabel:i,metrics:[{key:"operatingCashFlow",label:Be("Operating Cash Flow","operatingCashFlow"),mobileLabel:Be("Op Cash Flow","operatingCashFlow")},{key:"investingCashFlow",label:Be("Investing Cash Flow","investingCashFlow"),mobileLabel:Be("Inv Cash Flow","investingCashFlow")},{key:"financingCashFlow",label:Be("Financing Cash Flow","financingCashFlow"),mobileLabel:Be("Fin Cash Flow","financingCashFlow")},{key:"endingCash",label:Be("Ending Cash Position","endingCash"),mobileLabel:Be("Ending Cash","endingCash")},{key:"capex",label:Be("Capital Expenditures","capex"),mobileLabel:Be("CapEx","capex")},{key:"fcf",label:Be("Free Cash Flow","freeCashFlow"),mobileLabel:Be("FCF","freeCashFlow")}]})}function np({cashflowData:s,periodType:t}){const a=xe(s).slice(0,8),n=u=>typeof u.fcf=="number"?u.fcf:typeof u.operatingCashFlow=="number"&&typeof u.capex=="number"?u.operatingCashFlow-u.capex:void 0,i=a.map(n).filter(u=>u!=null&&Number.isFinite(u)),r=i.slice(0,4).filter(u=>u>0).length,o=a.slice(0,3).reduce((u,f)=>u+(n(f)??0),0),l=a.slice(0,3).reduce((u,f)=>u+(typeof f.dividendsPaid=="number"?Math.abs(f.dividendsPaid):0),0),c=o>0?l/o:void 0,m=u=>u!=null&&Number.isFinite(u)?`${(u*100).toFixed(0)}%`:"—",h=u=>Re(u),[y,j]=(()=>{const u=c??1/0;return r>=3&&u<=.6?["success",e.jsxs("p",{children:["The company demonstrates ",e.jsx("strong",{children:"excellent cash generation"})," with consistent free cash flow that comfortably covers dividends and provides flexibility for growth investments or shareholder returns."]},"strong")]:r>=2&&u<=1?["info",e.jsxs("p",{children:["Cash flow generation is ",e.jsx("strong",{children:"adequate"})," with reasonable coverage of obligations. Monitor for consistency and ensure FCF remains stable through economic cycles."]},"balanced")]:["warning",e.jsxs("p",{children:["Cash flow shows ",e.jsx("strong",{children:"concerning patterns"})," with inconsistent generation or stretched payout coverage. This may signal operational challenges or unsustainable capital allocation."]},"weak")]})();return e.jsx(ka,{title:"Cash Flow Summary & Analysis",subtitle:"Cash generation quality and sustainability",groups:[{heading:"Cash Generation",metrics:[{label:"Latest Operating CF:",value:a[0]?.operatingCashFlow!=null?h(a[0].operatingCashFlow):"N/A"},{label:"Latest Free CF:",value:i[0]!=null?h(i[0]):"N/A"},{label:"Positive FCF (last 4):",value:`${r}/4 periods`}]},{heading:e.jsx($,{id:"capitalAllocation-cf-summary",data:P.capitalAllocation,children:e.jsx("span",{children:"Capital Allocation"})}),metrics:[{label:"FCF (3-yr total):",value:h(o)},{label:"Dividends (3-yr total):",value:h(l)},{label:e.jsx($,{id:"payoutCoverage-summary",data:P.payoutCoverage,children:e.jsx("span",{children:"Payout Coverage:"})}),value:m(c)}]}],analysis:{heading:"Investment Analysis",tone:y,children:j}})}function ip({data:s,payoutWindow:t,onWindowChange:a,bestTimeRange:n,dataAvailability:i,isDataLimited:r,availabilityMessage:o,formatXAxisPeriod:l,fmtMoney:c}){return e.jsxs("section",{className:"space-y-4",children:[e.jsxs("header",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"text-base md:text-lg font-semibold tracking-tight",children:["Historical FCF &"," ",e.jsx($,{id:"capitalAllocation-chart-title",data:P.capitalAllocation,children:e.jsx("span",{children:"Capital Allocation"})})]}),e.jsxs("p",{className:"text-xs md:text-sm text-muted-foreground",children:["Free cash flow trends vs dividends and buybacks",r&&o&&e.jsxs("span",{className:"block text-cautionary text-xs mt-1",children:["⚠ ",o]})]})]}),e.jsx(Yt,{selectedRange:n,onRangeChange:m=>a(m),dataAvailability:i})]}),e.jsx("div",{children:e.jsx("div",{className:"h-64 sm:h-72 md:h-80",children:e.jsx(ke,{width:"100%",height:"100%",children:e.jsxs(Dr,{data:s,margin:{left:8,right:8},maxBarSize:60,children:[e.jsx(Ve,{strokeDasharray:"1 3",opacity:.3}),e.jsx(Le,{dataKey:"period",...Ns,tickFormatter:m=>l(m,t)}),e.jsx(Me,{...Js,...Ns,tickFormatter:m=>c(m)}),e.jsx(Pe,{formatter:m=>c(m),contentStyle:{backgroundColor:"hsl(var(--background))",border:"1px solid hsl(var(--border))",borderRadius:"12px",boxShadow:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)"}}),e.jsx(Fa,{}),e.jsx(Ws,{dataKey:"dividends",name:"Dividends",stackId:"payout",fill:"hsl(var(--chart-1) / 0.6)",radius:[2,2,0,0]}),e.jsx(Ws,{dataKey:"buybacks",name:"Buybacks",stackId:"payout",fill:"hsl(var(--chart-4) / 0.6)",radius:[2,2,0,0]}),e.jsx(Se,{type:"monotone",dataKey:"fcf",name:"Free Cash Flow",stroke:"hsl(var(--primary))",strokeWidth:3,dot:{r:5,strokeWidth:2,fill:"hsl(var(--primary))"},activeDot:{r:7,strokeWidth:0}}),e.jsx(qr,{dataKey:"period",height:28})]})})})})]})}const es=s=>{const t=Math.abs(s);return t>=1e9?`$${(s/1e9).toFixed(1)}B`:t>=1e6?`$${(s/1e6).toFixed(1)}M`:t>=1e3?`$${(s/1e3).toFixed(1)}K`:`$${s.toFixed(0)}`},rp=(s,t)=>t==="1Y"||t==="3Y"||s.length>=4?s.slice(-4):s;function op({fcfData:s,fcfChartData:t,symbol:a,payoutWindow:n,onPayoutWindowChange:i}){const{filteredData:r,dataAvailability:o,bestTimeRange:l,isDataLimited:c,availabilityMessage:m}=t,h=r.data;if(s.length===0||h.length===0)return e.jsx("div",{className:"space-y-6",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx(T,{as:"div",color:"muted",className:"mb-2",children:"No FCF Data Available"}),e.jsxs(T,{as:"p",size:"2",color:"muted",className:"max-w-md mx-auto",children:["Free Cash Flow data is not available for ",a,". This may be due to insufficient financial data or recent IPO status."]})]})});const y=h.reduce((b,I)=>b+(typeof I.fcf=="number"?I.fcf:0),0),j=h.reduce((b,I)=>b+(typeof I.dividends=="number"?Math.abs(I.dividends):0),0),u=h.reduce((b,I)=>b+(typeof I.buybacks=="number"?Math.abs(I.buybacks):0),0),f=j+u,g=y>0?f/y:void 0,x=Ci(g),k=Fi(x).label,w=Ii(x),p=h.length>0?h[h.length-1]?.fcf:void 0,v=(()=>
2{if(h.length<2)return;const b=h[h.length-1]?.fcf,I=h[h.length-2]?.fcf;if(!(!b||!I||I===0))return(b-I)/Math.abs(I)*100})(),M=h.slice(-5).reverse().map(b=>{const I=b.fcf||0,ee=b.dividends||0,U=b.buybacks||0,A=ee+U,K=I>0?A/I*100:0;return{period:b.period,fcf:I,divs:ee,buybacks:U,totalPayout:A,payoutRatio:K}}),L=[{id:"period",sticky:!0,header:"Period",accessor:b=>b.period,sortable:!1},{id:"fcf",header:e.jsx($,{id:"fcf-table",data:P.freeCashFlow,children:e.jsx("span",{children:"FCF"})}),accessor:b=>b.fcf,align:"right",sortable:!1,cell:b=>e.jsx("span",{className:b.fcf>=0?"text-gain":"text-loss",children:es(b.fcf)})},{id:"divs",header:e.jsx($,{id:"dividends-table",data:P.dividends,children:e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"sm:hidden",children:"Divs"}),e.jsx("span",{className:"hidden sm:inline",children:"Dividends"})]})}),accessor:b=>b.divs,align:"right",sortable:!1,cell:b=>es(b.divs)},{id:"buybacks",header:e.jsx($,{id:"buybacks-table",data:P.buybacks,children:e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"sm:hidden",children:"BB"}),e.jsx("span",{className:"hidden sm:inline",children:"Buybacks"})]})}),accessor:b=>b.buybacks,align:"right",sortable:!1,cell:b=>es(b.buybacks)},{id:"totalPayout",header:e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"sm:hidden",children:"Payouts"}),e.jsx("span",{className:"hidden sm:inline",children:"Total Payouts"})]}),accessor:b=>b.totalPayout,align:"right",sortable:!1,cell:b=>e.jsx("span",{className:"font-medium",children:es(b.totalPayout)})},{id:"payoutRatio",header:e.jsx($,{id:"payoutRatio-table",data:P.payoutRatio,children:e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"sm:hidden",children:"Ratio"}),e.jsx("span",{className:"hidden sm:inline",children:"Payout Ratio"})]})}),accessor:b=>b.payoutRatio,align:"right",sortable:!1,cell:b=>e.jsxs("span",{className:b.payoutRatio>100?"text-cautionary":void 0,children:[b.payoutRatio.toFixed(0),"%"]})}];return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("section",{className:"space-y-4",children:[e.jsx(W,{as:"h3",size:{base:"5",md:"6"},icon:fa,title:"Free Cash Flow Overview",subtitle:"Key metrics and capital allocation assessment"}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(O,{size:"sm",label:"Latest FCF",value:p!=null?es(p):"—",delta:v!=null?v/100:null,deltaFormat:"percent",deltaPrecision:1}),e.jsx(O,{size:"sm",label:`Total FCF (${n})`,value:es(y),subtext:y>=0?"Cash Generation":"Cash Consumption"}),e.jsx(O,{size:"sm",label:`Total Payouts (${n})`,value:es(f),subtext:`Div: ${es(j)} | BB: ${es(u)}`}),e.jsxs("div",{className:"flex flex-col items-start gap-1",children:[e.jsx(O,{size:"sm",label:e.jsx($,{id:"payoutRatio-overview",data:P.payoutRatio,children:e.jsx("span",{children:"Payout Ratio"})}),value:g!=null?`${(g*100).toFixed(0)}%`:"—",subtext:k}),e.jsx(D,{tone:ue(w),intensity:"subtle",children:de(w)})]})]}),e.jsxs(J,{tone:"neutral",children:[e.jsx("h4",{className:"font-semibold text-sm text-foreground mb-2",children:e.jsx($,{id:"capitalAllocation-assessment-payout",data:P.capitalAllocation,children:e.jsx("span",{children:"Capital Allocation Assessment"})})}),e.jsx(T,{as:"p",size:"2",color:"muted",children:(()=>{if(g==null)return"Insufficient FCF data for comprehensive capital allocation analysis.";let b="";g<.6?b="Excellent capital efficiency with conservative payout ratios, demonstrating strong cash generation and disciplined capital allocation.":g<=1?b="Balanced capital allocation with payouts roughly matching FCF generation. Monitor consistency for sustainability.":b="High payout ratios exceeding FCF may indicate reliance on balance sheet strength or debt financing.";const I=f>0?j/f:0;return I>.7?b+=" Dividend-focused approach suggests commitment to income investors.":I<.3?b+=" Buyback-focused strategy indicates management confidence in share value.":b+=" Balanced approach between dividends and buybacks provides flexibility.",b})()})]})]}),e.jsx(ip,{data:h,payoutWindow:n,onWindowChange:i,bestTimeRange:l,dataAvailability:o,isDataLimited:c,availabilityMessage:m,formatXAxisPeriod:rp,fmtMoney:es}),e.jsxs("section",{className:"space-y-4",children:[e.jsx(W,{as:"h3",size:"4",title:"FCF Analysis Table",subt
2itle:"Detailed breakdown of free cash flow and capital allocation"}),e.jsx(Ss,{columns:L,data:M,getRowKey:b=>b.period,density:"sm",variant:"elevated",mobileVariant:"scroll"})]}),e.jsxs("section",{className:"space-y-4",children:[e.jsx(W,{as:"h3",size:"4",title:"FCF Summary & Analysis",subtitle:"Comprehensive evaluation of capital allocation efficiency"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsx("div",{className:"bg-muted/30 rounded-lg p-4",children:e.jsx(O,{size:"sm",label:e.jsx($,{id:"fcfQuality",data:P.fcfQuality,children:e.jsx("span",{children:"FCF Quality"})}),value:(()=>{const b=h.filter(I=>(I.fcf||0)>0).length/h.length;return b>=.8?"Excellent":b>=.6?"Good":b>=.4?"Average":"Poor"})(),subtext:"Based on FCF consistency over selected period"})}),e.jsx("div",{className:"bg-muted/30 rounded-lg p-4",children:e.jsx(O,{size:"sm",label:"Capital Efficiency",value:k,subtext:g!=null?`${(g*100).toFixed(0)}% payout ratio`:"Insufficient data"})}),e.jsx("div",{className:"bg-muted/30 rounded-lg p-4",children:e.jsx(O,{size:"sm",label:"Allocation Strategy",value:(()=>{const b=f>0?j/f:0;return b>.7?"Dividend Focused":b<.3?"Buyback Focused":"Balanced"})(),subtext:f>0?`${(j/f*100).toFixed(0)}% dividends, ${(u/f*100).toFixed(0)}% buybacks`:"No significant payouts"})})]}),e.jsxs(J,{tone:"neutral",children:[e.jsx("h4",{className:"font-semibold text-sm text-foreground mb-2",children:"Investment Perspective"}),e.jsx(T,{as:"p",size:"2",color:"muted",children:(()=>{if(g==null)return"Insufficient positive FCF data for comprehensive assessment. Monitor for improvement in cash generation.";let b="";g<.6?(b="Excellent capital discipline with conservative payouts provides strong margin of safety. ",b+="This conservative approach preserves financial flexibility and suggests management prioritizes long-term sustainability."):g<=1?(b="Balanced capital allocation approach with payouts matching FCF generation. ",b+="Monitor for consistency across economic cycles to ensure sustainable shareholder returns."):(b="Aggressive payout policy exceeding FCF generation. ",b+="Evaluate balance sheet strength and debt capacity to assess sustainability during potential downturns.");const I=(()=>{if(h.length<3)return"";const ee=h.slice(-3).map(A=>A.fcf||0);return ee[2]>ee[0]?" FCF trend shows improvement.":" Monitor FCF stability going forward."})();return b+I})()})]})]})]})}function lp(s){switch(s){case"Technology":return 9.5;case"Healthcare":return 8.8;case"Energy":return 10.2;case"Financial Services":return 7.5;default:return 9}}function cp(s){switch(s){case"Energy":return 8.5;case"Technology":return 15.2;case"Healthcare":return 12.8;case"Financial Services":return 9.3;default:return 10.5}}const ht=s=>s!=null&&Number.isFinite(s)?`${s.toFixed(1)}%`:"—";function dp({roicData:s,roicChartData:t,symbol:a,sector:n,onRoicWindowChange:i}){const r=lp(n),o=s.map(A=>({...A,wacc:r})),{filteredData:l,dataAvailability:c,bestTimeRange:m,isDataLimited:h,availabilityMessage:y}=t,j=l.data,u=o.filter(A=>A.roic!=null&&Number.isFinite(A.roic));if(u.length===0)return e.jsx("div",{className:"space-y-6",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx(T,{as:"div",color:"muted",className:"mb-2",children:"No ROIC Data Available"}),e.jsxs(T,{as:"p",size:"2",color:"muted",className:"max-w-md mx-auto",children:["Return on Invested Capital data is not available for ",a,". This may be due to insufficient financial data or the company's financial structure."]})]})});const f=u[u.length-1]?.roic,g=u[u.length-1]?.wacc??null,x=f!=null&&g!=null?f-g:0,S=u.slice(-3),k=S.length>0?S.reduce((A,K)=>A+(K.roic||0),0)/S.length:void 0,w=cp(n),p=u.length>=3?(u[u.length-1]?.roic||0)-(u[u.length-3]?.roic||0):0,v=Ai(f),L=rd(v).label,b=Si(v),I=()=>{if(!f||f===0)return"Insufficient ROIC data available for analysis.";let A="";return f>15?A="Excellent ROIC demonstrates exceptional capital efficiency and competitive advantages. ":f>10?A="Strong ROIC indicates effective capital allocation and solid business fundamentals. ":f>6?A="Moderate ROIC suggests reasonable capital efficiency, though improvement opportunities may exist. ":A="Below-average ROIC raise
2s concerns about capital allocation efficiency and competitive positioning. ",p>2?A+="The improving trend is encouraging and suggests strengthening business fundamentals.":p<-2?A+="The declining trend warrants investigation into operational challenges or market headwinds.":A+="ROIC appears relatively stable over the recent period.",k&&Math.abs(f-k)>3&&(A+=f>k?" Current performance exceeds the 3-year average, indicating recent improvements.":" Current performance trails the 3-year average, suggesting recent challenges."),A},ee=[{id:"current-roic",metric:e.jsx($,{id:"roic-table",data:P.roic,children:e.jsx("span",{children:"Current ROIC"})}),value:e.jsx("span",{className:"font-semibold text-primary",children:ht(f)}),assessment:e.jsx(D,{tone:ue(b),intensity:"subtle",children:de(b)})},{id:"current-wacc",metric:e.jsx($,{id:"wacc-current",data:P.wacc,children:e.jsx("span",{children:"Current WACC"})}),value:e.jsx("span",{className:"font-semibold",children:g!=null?`${g.toFixed(1)}%`:"—"}),assessment:e.jsx(D,{tone:"neutral",intensity:"subtle",children:"Cost of Capital"})},{id:"economic-profit",metric:e.jsx($,{id:"economicProfit-roic",data:P.economicProfit,children:e.jsx("span",{children:"Economic Profit"})}),value:f!=null&&g!=null?e.jsxs("span",{className:`font-semibold ${x>0?"text-gain":"text-loss"}`,children:[x>0?"+":"",x.toFixed(1),"%"]}):"—",assessment:f!=null&&g!=null?x>5?e.jsx(D,{tone:"success",intensity:"subtle",children:"Strong Creator"}):x>0?e.jsx(D,{tone:"info",intensity:"subtle",children:e.jsx($,{id:"valueCreator-badge",data:P.valueCreator,children:e.jsx("span",{children:"Value Creator"})})}):x>-3?e.jsx(D,{tone:"warning",intensity:"subtle",children:"Neutral"}):e.jsx(D,{tone:"error",intensity:"subtle",children:e.jsx($,{id:"valueDestroyer-badge",data:P.valueDestroyer,children:e.jsx("span",{children:"Value Destroyer"})})}):"—"},{id:"three-year-avg",metric:"3-Year Avg ROIC",value:e.jsx("span",{className:"font-semibold",children:ht(k)}),assessment:f!=null&&k!=null?e.jsx(D,{tone:f>k?"success":"error",intensity:"subtle",children:f>k?"Above Average":"Below Average"}):"—"},{id:"vs-industry",metric:"vs Industry",value:e.jsx("span",{className:"font-semibold",children:f!=null&&w?`${(f-w).toFixed(1)}pp`:"—"}),assessment:f!=null&&w?e.jsx(D,{tone:f>w?"success":"error",intensity:"subtle",children:f>w?"Outperforming":"Underperforming"}):"—"},{id:"trend-direction",metric:"Trend Direction",value:e.jsx("span",{className:"font-semibold",children:p!==0?`${p.toFixed(1)}pp`:"—"}),assessment:e.jsx(D,{tone:p>2?"success":p<-2?"error":"neutral",intensity:"subtle",children:p>2?"Improving":p<-2?"Declining":"Stable"})}],U=[{id:"metric",header:"Metric",accessor:A=>A.id,sortable:!1,sticky:!0,cell:A=>A.metric},{id:"value",header:"Value",accessor:A=>A.id,align:"right",sortable:!1,cell:A=>A.value},{id:"assessment",header:"Assessment",accessor:A=>A.id,align:"right",sortable:!1,cell:A=>A.assessment}];return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("section",{className:"space-y-4",children:[e.jsx(W,{as:"h3",size:{base:"5",md:"6"},icon:hs,title:"ROIC Overview",subtitle:"Key return on invested capital metrics",actions:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"text-sm font-medium text-foreground",children:[L," Capital Efficiency"]}),e.jsx(D,{tone:ue(b),intensity:"subtle",children:de(b)})]})}),e.jsxs("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-4",children:[e.jsxs("div",{className:"text-center p-4 rounded-lg bg-card border",children:[e.jsx($,{id:"roic-overview",data:P.roic,children:e.jsx(T,{as:"div",size:"2",color:"muted",className:"mb-2",children:"Current ROIC"})}),e.jsx(T,{as:"div",size:{base:"5",md:"6"},weight:"bold",color:"primary",numeric:!0,children:ht(f)}),e.jsx(T,{as:"div",size:"1",color:"muted",className:"mt-1",children:s.length>0?s[s.length-1]?.period:""})]}),e.jsxs("div",{className:"text-center p-4 rounded-lg bg-card border",children:[e.jsx(T,{as:"div",size:"2",color:"muted",className:"mb-2",children:"3-Year Average"}),e.jsx(T,{as:"div",size:{base:"5",md:"6"},weight:"bold",numeric:!0,children:ht(k)}),e.jsx(T,{as:"div",size:"1",color:"muted",className:"mt-1",children:"Historical avg"})]}),e.jsxs("div",{className:"text-center p-4 rounded-lg bg-card border",children:[e.jsx(T,{as:"div",size:"2",color:"muted",className:"mb-2",children:"Industry Avg"}),e.jsx(T,{as:"div",size:{base:"5",md:"6"},weight:"bold",numeric:!0,className:"text-ring",children:ht(w)}),e.jsx(T,{as:"div",size:"1",color:"muted",className:"mt-1",children:n||"General"})]}),e.jsxs("div",{className:"text-center p-4 rounded-lg bg-card border",children:[e.jsx(T,{as:"div",size:"2",color:"muted",className:"mb-2",children:"Trend Direction"}),e.jsx(T,{as:"div",size:{base:"5",md:"6"},weight:"bold",color:p>0?"gain":p<0?"loss":"muted",children:p>0?"↗":p<0?"↘":"→"}),e.jsx(T,{as:"div",size:"1",color:"muted",className:"mt-1",children:p>2?"Improving":p<-2?"Declining":"Stable"})]})]}),e.jsx(J,{tone:"neutral",children:e.jsxs(T,{as:"p",size:"2",color:"muted",className:"leading-relaxed",children:[e.jsx("strong",{className:"text-foreground",children:"Qu
2ick Assessment:"})," ",I()]})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs("section",{className:"space-y-4",children:[e.jsx(W,{as:"h3",size:"4",title:"ROIC vs WACC Analysis",subtitle:"Return on invested capital vs cost of capital over time",actions:e.jsx(Yt,{selectedRange:m,onRangeChange:A=>i(A),dataAvailability:c})}),h&&y&&e.jsx(J,{tone:"warning",children:e.jsxs(T,{as:"p",size:"2",color:"muted",children:[e.jsx("strong",{className:"text-foreground",children:"Data Notice:"})," ",y]})}),e.jsx("div",{className:"h-72 sm:h-80 md:h-96",children:e.jsx(ke,{width:"100%",height:"100%",children:e.jsxs(As,{data:j.filter(A=>A.roic!=null),margin:{left:8,right:8,top:5,bottom:5},children:[e.jsx(Ve,{strokeDasharray:"3 3",className:"stroke-muted"}),e.jsx(Le,{dataKey:"period",tick:{fontSize:12},axisLine:{stroke:"hsl(var(--border))"}}),e.jsx(Me,{...Js,tick:{fontSize:12},domain:["auto","auto"],axisLine:{stroke:"hsl(var(--border))"},tickFormatter:A=>`${A}%`}),e.jsx(Pe,{formatter:(A,K)=>[`${Number(A).toFixed(1)}%`,K==="roic"?"ROIC":"WACC"],labelFormatter:A=>`Year: ${A}`,contentStyle:{backgroundColor:"hsl(var(--popover))",border:"1px solid hsl(var(--border))",borderRadius:"6px"}}),e.jsx(Se,{type:"monotone",dataKey:"roic",stroke:"hsl(var(--primary))",strokeWidth:3,dot:{fill:"hsl(var(--primary))",strokeWidth:2,r:4},activeDot:{r:6,stroke:"hsl(var(--primary))",strokeWidth:2}}),e.jsx(Se,{type:"monotone",dataKey:"wacc",stroke:"hsl(var(--destructive))",strokeWidth:2,strokeDasharray:"5 5",dot:{fill:"hsl(var(--destructive))",strokeWidth:2,r:3},activeDot:{r:5,stroke:"hsl(var(--destructive))",strokeWidth:2}})]})})})]}),e.jsxs("section",{className:"space-y-4",children:[e.jsx(W,{as:"h3",size:"4",title:"Value Creation Analysis",subtitle:"ROIC vs WACC comparison and economic profit assessment"}),e.jsx(Ss,{columns:U,data:ee,getRowKey:A=>A.id,density:"sm",variant:"elevated",mobileVariant:"scroll"})]})]}),e.jsxs("section",{className:"space-y-4",children:[e.jsx(W,{as:"h3",size:"4",title:"Value Creation Investment Analysis",subtitle:"ROIC vs WACC assessment for investment decisions"}),e.jsxs(J,{tone:"neutral",children:[e.jsx("h4",{className:"font-semibold text-sm mb-2 text-foreground",children:"Executive Summary"}),e.jsxs(T,{as:"p",size:"2",color:"muted",className:"leading-relaxed",children:[e.jsx("strong",{className:"text-foreground",children:"Value Creation Assessment:"})," ",f!=null&&g!=null?e.jsxs(e.Fragment,{children:[a," shows ROIC = ",f.toFixed(1),"%, WACC ="," ",g.toFixed(1),"% →",x>0?e.jsxs("span",{className:"text-gain font-medium",children:[" ","creates ",x.toFixed(1),"% excess return annually. Long-term compounding machine."]}):e.jsxs("span",{className:"text-loss font-medium",children:[" ","destroys ",Math.abs(x).toFixed(1),"% per year. Cheap stock might stay cheap."]})]}):`Capital efficiency analysis requires both ROIC and WACC data for ${a}.`]})]}),p!==void 0&&e.jsxs(J,{tone:"neutral",children:[e.jsx("h5",{className:"font-medium text-sm mb-2 text-foreground",children:"Trend Analysis"}),e.jsxs(T,{as:"p",size:"2",color:"muted",children:["The company's ROIC trend is"," ",p>2?"improving":p<-2?"declining":"stable",p>2&&x>0&&", which strengthens the value creation thesis as the gap above WACC is widening",p>2&&x<=0&&", which could indicate a turnaround story if ROIC approaches WACC levels",p<-2&&x>0&&", which warrants monitoring as the value creation advantage may be eroding",p<-2&&x<=0&&", compounding the value destruction problem",Math.abs(p)<=2&&", showing consistent capital allocation performance relative to cost of capital","."]})]}),e.jsxs(J,{tone:"neutral",children:[e.jsx("h5",{className:"font-medium text-sm mb-2 text-foreground",children:"Investment Implications"}),e.jsxs(T,{as:"p",size:"2",color:"muted",children:[x>5&&"Exceptional value creator with sustainable competitive advantages. Prime candidate for long-term holding with strong wealth compounding potential.",x>0&&x<=5&&"Solid value creator that generates returns above cost of capital. Monitor sustainability of competitive position.",x>-3&&x<=0&&"Marginal value creation. Focus on management execution and industry dynamics for improvement potential.",x<=-3&&"Significant value destroyer. Requires exceptional catalyst or turnaround story to justify investment.",(!f||!g)&&"Complete capital efficiency analysis requires both ROIC and cost of capital data to assess true value creation."]})]})]})]})}function Vs(s){if(s==null||!Number.isFinite(s))return"—";const t=s<0?"-":"",a=Math.abs(s);return a>=1e12?`${t}$${(a/1e12).toFixed(2)}T`:a>=1e9?`${t}$${(a/1e9).toFixed(2)}B`:a>=1e6?`${t}$${(a/1e6).toFixed(2)}M`:`${t}
2$${a.toLocaleString(void 0,{maximumFractionDigits:0})}`}function up({revenueData:s,symbol:t}){const a=s.filter(w=>w.revenue!=null&&w.netIncome!=null).slice().reverse();if(a.length===0)return e.jsxs("div",{className:"text-center py-12",children:[e.jsx(T,{as:"div",color:"muted",className:"mb-2",children:"No Revenue Data Available"}),e.jsxs(T,{as:"p",size:"2",color:"muted",className:"max-w-md mx-auto",children:["Revenue and income data is not available for ",t,". This may be due to insufficient financial data or recent IPO status."]})]});const n=a[a.length-1],i=n?.revenue,r=n?.netIncome,o=i!=null&&r!=null&&i!==0?r/i*100:void 0,l=a.length>=2?((a[a.length-1]?.revenue||0)/(a[0]?.revenue||1)-1)*100/(a.length-1):void 0,c=a.length>=2?((a[a.length-1]?.netIncome||0)/(a[0]?.netIncome||1)-1)*100/(a.length-1):void 0,m=a.length>=2?((a[a.length-1]?.revenue||0)-(a[a.length-2]?.revenue||0))/(a[a.length-2]?.revenue||1)*100:void 0,h=a.length>=2?((a[a.length-1]?.netIncome||0)-(a[a.length-2]?.netIncome||0))/Math.abs(a[a.length-2]?.netIncome||1)*100:void 0,y=Ri(o),j=qt(y),u=ki(l),f=qt(u),g=Ti(u),S=a.slice(-5).reverse().map((w,p,v)=>{const M=w.revenue!=null&&w.netIncome!=null&&w.revenue!==0?w.netIncome/w.revenue*100:void 0,L=v[p+1],b=L?.revenue?((w.revenue||0)-L.revenue)/L.revenue*100:void 0,I=L?.netIncome&&L.netIncome!==0?((w.netIncome||0)-L.netIncome)/Math.abs(L.netIncome)*100:void 0;return{period:w.period,revenue:w.revenue,netIncome:w.netIncome,margin:M,revGrowth:b,incGrowth:I}}),k=[{id:"period",sticky:!0,header:"Period",accessor:w=>w.period,sortable:!1,cell:w=>e.jsx("span",{className:"font-medium",children:w.period})},{id:"revenue",header:"Revenue",accessor:w=>w.revenue,align:"right",sortable:!1,cell:w=>Vs(w.revenue)},{id:"netIncome",header:e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"sm:hidden",children:"Income"}),e.jsx("span",{className:"hidden sm:inline",children:"Net Income"})]}),accessor:w=>w.netIncome,align:"right",sortable:!1,cell:w=>e.jsx("span",{className:(w.netIncome||0)>=0?"text-gain":"text-loss",children:Vs(w.netIncome)})},{id:"margin",header:e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"sm:hidden",children:"Margin"}),e.jsx("span",{className:"hidden sm:inline",children:"Net Margin"})]}),accessor:w=>w.margin,align:"right",sortable:!1,cell:w=>w.margin!=null?`${w.margin.toFixed(1)}%`:"—"},{id:"revGrowth",header:e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"sm:hidden",children:"Rev %"}),e.jsx("span",{className:"hidden sm:inline",children:"Revenue Growth"})]}),accessor:w=>w.revGrowth,align:"right",sortable:!1,cell:w=>w.revGrowth!=null?e.jsxs("span",{className:w.revGrowth>=0?"text-gain":"text-loss",children:[w.revGrowth.toFixed(1),"%"]}):"—"},{id:"incGrowth",header:e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"sm:hidden",children:"Inc %"}),e.jsx("span",{className:"hidden sm:inline",children:"Income Growth"})]}),accessor:w=>w.incGrowth,align:"right",sortable:!1,cell:w=>w.incGrowth!=null?e.jsxs("span",{className:w.incGrowth>=0?"text-gain":"text-loss",children:[w.incGrowth.toFixed(1),"%"]}):"—"}];return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("section",{className:"space-y-4",children:[e.jsx(W,{as:"h3",size:{base:"5",md:"6"},icon:Ye,title:"Revenue & Profitability Overview",subtitle:"Key financial performance metrics and growth analysis"}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(O,{size:"sm",label:"Latest Revenue",value:Vs(i),delta:m!=null?m/100:null,deltaFormat:"percent",deltaPrecision:1}),e.jsx(O,{size:"sm",label:"Net Income",value:Vs(r),valueColor:r!=null&&r>0?"gain":"loss",delta:h!=null?h/100:null,deltaFormat:"percent",deltaPrecision:1}),e.jsxs("div",{className:"flex flex-col items-start gap-1",children:[e.jsx(O,{size:"sm",label:"Net Margin",value:o!=null?`${o.toFixed(1)}%`:"—"}),e.jsx(D,{tone:ue(j),intensity:"subtle",children:de(j)})]}),e.jsxs("div",{className:"flex flex-col items-start gap-1",children:[e.jsx(O,{size:"sm",label:e.jsx($,{id:"cagr-revenue-growth",data:P.cagr,children:e.jsx("span",{children:"Revenue CAGR"})}),value:l!=null?`${l.toFixed(1)}%`:"—",subtext:g}),e.jsx(D,{tone:ue(f),intensity:"subtle",children:de(f)})]})]}),e.jsxs(J,{tone:"neutral",children:[e.jsx("h4",{className:"font-semibold text-sm text-foreground mb-2",children:"Growth Quality Assessment"}),e.jsx(T,{as:"p",size:"2",color:"muted",children:(()=>
2{if(o==null||l==null||c==null)return"Insufficient data for comprehensive revenue and profitability analysis.";let w="";return o>20?w="Excellent profitability margins demonstrate strong pricing power and operational efficiency. ":o>10?w="Healthy profit margins indicate solid business fundamentals and competitive positioning. ":o>5?w="Moderate margins suggest room for operational improvements or competitive pressures. ":o>0?w="Low margins may indicate operational challenges or highly competitive industry dynamics. ":w="Negative margins require immediate attention to operational efficiency and cost management. ",l>10&&c>l?w+="Strong revenue growth coupled with expanding margins indicates excellent operational leverage.":l>5&&c>0?w+="Steady growth with positive profitability trends support long-term value creation.":l>0&&c<0?w+="Revenue growth with declining profitability suggests margin pressures requiring investigation.":l<0&&(w+="Declining revenues present challenges; focus on business model sustainability and competitive position."),w})()})]})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs("section",{className:"space-y-4",children:[e.jsx(W,{as:"h3",size:"4",title:"Historical Revenue & Net Income",subtitle:"Trend analysis of top-line growth and profitability"}),e.jsx("div",{className:"h-56 sm:h-64 md:h-72",children:e.jsx(ke,{width:"100%",height:"100%",children:e.jsxs(As,{data:a,margin:{left:8,right:8,top:5,bottom:5},children:[e.jsx(Ve,{...Ta}),e.jsx(Le,{dataKey:"period",...Ns,tickFormatter:w=>String(w)}),e.jsx(Me,{...Js,...Ns,domain:["auto","auto"],tickFormatter:w=>Vs(w)}),e.jsx(Pe,{formatter:(w,p)=>[Vs(Number(w)),p],labelFormatter:w=>`Year: ${w}`,contentStyle:{backgroundColor:"hsl(var(--background))",border:"1px solid hsl(var(--border))",borderRadius:"12px",boxShadow:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)"}}),e.jsx(Fa,{}),e.jsx(Se,{type:"monotone",dataKey:"revenue",name:"Revenue",stroke:"hsl(var(--primary))",strokeWidth:3,dot:{r:5,strokeWidth:2,fill:"hsl(var(--primary))"},activeDot:{r:7,strokeWidth:0}}),e.jsx(Se,{type:"monotone",dataKey:"netIncome",name:"Net Income",stroke:"hsl(var(--chart-4))",strokeWidth:3,dot:{r:5,strokeWidth:2,fill:"hsl(var(--chart-4))"},activeDot:{r:7,strokeWidth:0}})]})})})]}),e.jsxs("section",{className:"space-y-4",children:[e.jsx(W,{as:"h3",size:"4",title:"Revenue & Profitability Table",subtitle:"Detailed breakdown of financial performance"}),e.jsx(Ss,{columns:k,data:S,getRowKey:w=>w.period,density:"sm",variant:"elevated",mobileVariant:"scroll"})]})]}),e.jsxs("section",{className:"space-y-4",children:[e.jsx(W,{as:"h3",size:"4",title:"Revenue Summary & Analysis",subtitle:"Comprehensive evaluation of business performance and quality"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsx("div",{className:"bg-muted/30 rounded-lg p-4",children:e.jsx(O,{size:"sm",label:"Revenue Quality",value:l==null?"N/A":l>=10?"Excellent":l>=5?"Good":l>=0?"Average":"Poor",subtext:l!=null?`${l.toFixed(1)}% CAGR`:"Insufficient data"})}),e.jsx("div",{className:"bg-muted/30 rounded-lg p-4",children:e.jsx(O,{size:"sm",label:"Profitability",value:o==null?"N/A":o>=20?"Excellent":o>=10?"Good":o>=5?"Average":"Poor",subtext:o!=null?`${o.toFixed(1)}% net margin`:"Insufficient data"})}),e.jsx("div",{className:"bg-muted/30 rounded-lg p-4",children:e.jsx(O,{size:"sm",label:"Growth Consistency",value:(()=>{const w=a.filter((p,v)=>v===0||(p.revenue||0)>=(a[v-1]?.revenue||0)).length/a.length;return w>=.8?"Excellent":w>=.6?"Good":w>=.4?"Average":"Poor"})(),subtext:"Based on revenue growth consistency"})})]}),e.jsxs(J,{tone:"neutral",children:[e.jsx("h4",{className:"font-semibold text-sm text-foreground mb-2",children:"Investment Perspective"}),e.jsx(T,{as:"p",size:"2",color:"muted",children:(()=>{if(o==null||l==null||c==null)return"Insufficient data for comprehensive analysis. Monitor for consistent revenue growth and margin expansion.";let w="";return o>15&&l>8?(w="High-quality business with excellent margins and strong growth. ",w+="This combination suggests pricing power, operational efficiency, and sustainable competitive advantages."):o>10&&l>5?(w="Solid business fundamentals with healthy margins and steady growth. ",w+="Good candidate for long-term value creation with reasonable valuation."):o>5||l>3?(w="Moderate business quality with room for improvement. ",w+="Monitor operational efficiency initiatives and competitive positioning."):(w="Challenging business dynamics with margin pressures or declining revenues. ",w+="Requires careful analysis of turnaround potential and management execution."),c>l?w+=" Operating leverage is evident with margin expansion.":c<0&&l>0&&(w+=" Margin compression warrants investigation into cost structure."),w})()})]})]})]})}function pa(s){if(s!=null&&!(Math.abs(s)>1e3))return s}function pt(s){return s?s>=1e9?`${(s/1e9).toFixed(1)}B`:s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${(s/1e3).toFixed(1)}K`:s.toFixed(0):"—"}function mp({sharesData:s,sharesChartData:t,symbol:a,shareCountTimeRange:n,onShareCountTimeRangeChange:i}){const r=s,o=t.filteredData;if(r.length===0)return e.jsxs("div",{className:"text-center py-12",children:[e.jsx(T,{as:"div",color:"muted",className:"mb-2",children:"No Share Count Data Available"}),e.jsxs(T,{as:"p",size:"2",color:"muted",className:"max-w-md mx-auto",children:["Share count data is not available for ",a,". This may be due to insufficient financial data or recent IPO status."]})]});const l=r[r.length-1]?.shares,c=r[0]?.shares,m=l!=null&&c!=null&&c>0?pa((l-c)/c*100):void 0,h=m!=null&&r.length>1?m/(r.length-1):void 0,y=r.slice(-3),j=y.length>=2&&(y[0]?.shares||0)>0?pa(((y[y.length-1]?.shares||0)-(y[0]?.shares||0))/(y[0]?.shares||0)*100):void 0,u=r.length>=2&&(r[r.length-2]?.shares||0)>0?pa(((r[r.length-1]?.shares||0)-(r[r.length-2]?.shares||0))/(r[r.length-2]?.shares||0)*100):void 0,f=Oi(h),g=Pi(f),x=Ei(f),k=o.data.slice(-5).reverse().map((p,v,M)=>{const L=M[v+1],b=L?.shares?(p.shares||0)-L.shares:void 0;let I,ee=!1;if(L?.shares&&L.shares>0){const U=((p.shares||0)-L.shares)/L.shares*100;Math.abs(U)>1e3?ee=!0:I=U}return{period:p.period,shares:p.shares,sharesDiff:b,sharesChangePercent:I,isDataError:ee}}),w=[{id:"period",sticky:!0,header:"Period",accessor:p=>
2p.period,sortable:!1,cell:p=>e.jsx("span",{className:"font-medium",children:p.period})},{id:"shares",header:e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"sm:hidden",children:"Shares"}),e.jsx("span",{className:"hidden sm:inline",children:"Shares Outstanding"})]}),accessor:p=>p.shares,align:"right",sortable:!1,cell:p=>pt(p.shares)},{id:"yoyChange",header:"YoY Change",accessor:p=>p.sharesDiff,align:"right",sortable:!1,cell:p=>p.sharesDiff!=null?e.jsxs("span",{className:p.sharesDiff<=0?"text-gain":"text-loss",children:[p.sharesDiff>0?"+":"",pt(p.sharesDiff)]}):"—"},{id:"yoyChangePct",header:e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"sm:hidden",children:"Change %"}),e.jsx("span",{className:"hidden sm:inline",children:"YoY Change %"})]}),accessor:p=>p.sharesChangePercent,align:"right",sortable:!1,cell:p=>p.isDataError?e.jsx("span",{className:"text-cautionary",children:"Data Error"}):p.sharesChangePercent==null?"—":e.jsxs("span",{className:p.sharesChangePercent<=0?"text-gain":"text-loss",children:[p.sharesChangePercent>0?"+":"",p.sharesChangePercent.toFixed(1),"%"]})},{id:"activity",header:"Activity",accessor:p=>p.sharesChangePercent,align:"right",sortable:!1,cell:p=>{if(p.isDataError||p.sharesChangePercent==null)return"—";const v=p.sharesChangePercent;return v<=-5?"Aggressive Buybacks":v<=-1?"Buybacks":v<=1?"Stable":v<=5?"Modest Dilution":"Significant Dilution"}}];return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("section",{className:"space-y-4",children:[e.jsx(W,{as:"h3",size:{base:"5",md:"6"},icon:Ks,title:"Share Count Overview",subtitle:"Capital allocation and shareholder value analysis"}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(O,{size:"sm",label:"Current Shares",value:pt(l),delta:u!=null?u/100:null,deltaFormat:"percent",deltaPrecision:1,direction:u!=null?u<=0?"gain":"loss":void 0}),e.jsx(O,{size:"sm",label:"Total Change",value:m!=null?`${m>0?"+":""}${m.toFixed(1)}%`:"—",valueColor:m!=null&&m<0?"gain":m!=null&&m>0?"loss":"foreground",subtext:m!=null&&m<0?"Buybacks":m!=null&&m>0?"Dilution":"Stable"}),e.jsx(O,{size:"sm",label:"Annual Change",value:h!=null?`${h>0?"+":""}${h.toFixed(1)}%`:"—",valueColor:h!=null&&h<0?"gain":h!=null&&h>0?"loss":"foreground",subtext:"Per year average"}),e.jsxs("div",{className:"flex flex-col items-start gap-1",children:[e.jsx(O,{size:"sm",label:"Capital Allocation",value:x}),e.jsx(D,{tone:ue(g),intensity:"subtle",children:de(g)})]})]}),e.jsxs(J,{tone:"neutral",children:[e.jsx("h4",{className:"font-semibold text-sm text-foreground mb-2",children:e.jsx($,{id:"capitalAllocation-assessment-shares",data:P.capitalAllocation,children:e.jsx("span",{children:"Capital Allocation Assessment"})})}),e.jsx(T,{as:"p",size:"2",color:"muted",children:(()=>{if(h==null)return"Insufficient share count data for comprehensive analysis of capital allocation efficiency.";let p="";return h<-3?(p="Aggressive share buybacks demonstrate strong cash generation and management's commitment to shareholder value. ",p+="This capital allocation strategy can significantly boost per-share metrics and returns for remaining shareholders."):h<-1?(p="Moderate share reduction indicates disciplined capital allocation and confidence in business prospects. ",p+="Buybacks at reasonable valuations can enhance long-term shareholder returns."):h<1?(p="Stable share count suggests balanced capital allocation between growth investments and shareholder returns. ",p+="This approach may be appropriate for companies in stable, mature industries."):h<3?(p="Modest share dilution may indicate growth investments or employee compensation programs. ",p+="Monitor that dilution is offset by corresponding growth in business value."):(p="Significant share dilution raises concerns about value destruction for existing shareholders. ",p+="Investigate whether new capital is generating adequate returns to justify dilution."),p})()})]})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs("section",{className:"space-y-4",children:[e.jsx(W,{as:"h3",size:"4",title:"Historical Share Count Trend",subtitle:"Analysis of share buybacks and dilution over time",actions:e.jsx(Yt,{selectedRange:n,onRangeChange:i})}),e.jsx("div",{className:"h-56 sm:h-64 md:h-72",children:e.jsx(ke,{width:"100%",height:"100%",children:e.jsxs(As,{data:o.data,margin:{left:8,right:8,top:5,bottom:5},children:[e.jsx(Ve,{...Ta}),e.jsx(Le,{dataKey:"period",...Ns,tickFormatter:p=>String(p)}),e.jsx(Me,{...Js,...Ns,domain:["auto","auto"],tickFormatter:p=>pt(p)}),e.jsx(Pe,{formatter:p=>[pt(Number(p)),"Shares Outstanding"],labelFormatter:p=>`Year: ${p}`,contentStyle:{backgroundColor:"hsl(var(--background))",border:"1px solid hsl(var(--border))",borderRadius:"12px",boxShadow:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)"}}),e.jsx(Se,{type:"monotone",dataKey:"shares",stroke:"hsl(var(--primary))",strokeWidth:3,dot:{fill:"hsl(var(--primary))",r:4,strokeWidth:2},activeDot:{r:6,strokeWidth:0}})]})})})]}),e.jsxs("section",{className:"space-y-4",children:[e.jsx(W,{as:"h3",size:"4",title:"Share Count Analysis Table",subt
2itle:"Detailed breakdown of share changes and capital allocation"}),e.jsx(Ss,{columns:w,data:k,getRowKey:p=>p.period,density:"sm",variant:"elevated",mobileVariant:"scroll"})]})]}),e.jsxs("section",{className:"space-y-4",children:[e.jsx(W,{as:"h3",size:"4",title:"Share Count Summary & Analysis",subtitle:"Capital allocation efficiency and shareholder value impact"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsx("div",{className:"bg-muted/30 rounded-lg p-4",children:e.jsx(O,{size:"sm",label:"Allocation Strategy",value:h==null?"N/A":h<=-3?"Aggressive Buybacks":h<=-1?"Moderate Buybacks":h<=1?"Stable Count":"Dilutive",subtext:h!=null?`${h.toFixed(1)}% annual change`:"Insufficient data"})}),e.jsx("div",{className:"bg-muted/30 rounded-lg p-4",children:e.jsx(O,{size:"sm",label:"Shareholder Impact",value:h==null?"N/A":h<=-1?"Positive":h<=1?"Neutral":"Negative",subtext:h==null?"Insufficient data":h<=-1?"Value accretive":h<=1?"Minimal impact":"Value dilutive"})}),e.jsx("div",{className:"bg-muted/30 rounded-lg p-4",children:e.jsx(O,{size:"sm",label:"Trend Consistency",value:(()=>{const p=r.reduce((v,M,L)=>{if(L===0)return v;const b=r[L-1],I=((M.shares||0)-(b.shares||0))/(b.shares||1),ee=Math.sign(I)===Math.sign(h||0);return v+(ee?1:0)},0)/Math.max(r.length-1,1);return p>=.8?"Excellent":p>=.6?"Good":p>=.4?"Average":"Poor"})(),subtext:"Based on direction consistency"})})]}),e.jsxs(J,{tone:"neutral",children:[e.jsx("h4",{className:"font-semibold text-sm text-foreground mb-2",children:"Investment Perspective"}),e.jsx(T,{as:"p",size:"2",color:"muted",children:(()=>{if(h==null)return"Insufficient share count data for comprehensive capital allocation analysis. Monitor future financial reports for share count trends.";let p="";return h<-3?(p="Aggressive share buyback program demonstrates exceptional cash generation and management confidence in intrinsic value. ",p+="This creates substantial value for remaining shareholders through increased ownership concentration and improved per-share metrics."):h<-1?(p="Consistent share reduction program indicates disciplined capital allocation and prudent shareholder returns. ",p+="Well-executed buybacks at reasonable valuations can significantly enhance long-term investor returns."):h<1?(p="Stable share count suggests balanced capital allocation philosophy prioritizing both growth investments and shareholder returns. ",p+="This measured approach may be optimal for mature businesses with steady cash flows."):h<3?(p="Moderate share dilution may reflect strategic growth investments or employee compensation programs. ",p+="Critical to ensure that dilution is offset by proportional increases in business value and earnings per share."):(p="Significant share dilution presents material concerns about value preservation for existing shareholders. ",p+="Requires thorough investigation into capital deployment effectiveness and management's commitment to shareholder value creation."),j!=null&&h!=null&&Math.abs(j)>Math.abs(h)&&(j<h?p+=" Recent acceleration in buyback activity suggests improving cash generation or management's view of undervaluation.":p+=" Recent increase in dilution pace warrants investigation into evolving capital needs and strategic direction."),p})()})]})]})]})}function hp({income:s,balance:t,ratios:a,name:n}){const i=xe(s||[])[0],r=xe(t||[])[0];let o=a?.roic??void 0;if(i?.netIncome!=null&&r?.totalAssets!=null&&r?.currentLiabilities!=null){const b=r.totalAssets-r.currentLiabilities;b>0&&(o=i.netIncome/b)}const l=a?.fcfYield||0,c=a?.pb||0,m=a?.de||0,h=[!!o&&o>.15,l>.05,m<.5,!!c&&c<3].filter(Boolean).length,y=Cc(h),j=Ic(y),u=Te(y),f=ba(o),g=va(l),x=_c(c),S=Ni(m),k=Te(f),w=Te(g),p=Te(x),v=[{id:"brand",title:e.jsx($,{id:"brandPower-moat",data:P.brandPower,children:e.jsx("span",{children:"Brand Power & Recognition"})}),description:"Pricing power and customer loyalty",strengthLabel:o&&o>.15?"Strong 🏰":o&&o>.1?"Moderate ⚡":"Weak ⚠️",basedOn:"Based on ROIC performance"},{id:"switching",title:e.jsx($,{id:"switchingCosts-moat",data:P.switchingCosts,children:e.jsx("span",{children:"Customer Switching Costs"})}
2),description:"Difficulty for customers to switch providers",strengthLabel:l>.05?"High 🏰":l>.02?"Moderate ⚡":"Low ⚠️",basedOn:"Based on cash generation"},{id:"network",title:e.jsx($,{id:"networkEffects-moat",data:P.networkEffects,children:e.jsx("span",{children:"Network Effects"})}),description:"Value increases with more users",strengthLabel:c&&c<2?"Strong 🏰":c&&c<4?"Present ⚡":"Limited ⚠️",basedOn:"Based on book value premium"},{id:"cost",title:e.jsx($,{id:"costAdvantages-moat",data:P.costAdvantages,children:e.jsx("span",{children:"Cost Advantages"})}),description:"Economies of scale and operational efficiency",strengthLabel:m&&m<.5?"Significant 🏰":m&&m<1?"Moderate ⚡":"Limited ⚠️",basedOn:"Based on financial leverage"}],M=[{id:"roic",metric:"Return on Invested Capital",value:o?`${(o*100).toFixed(1)}%`:"—",threshold:">15%",assessment:e.jsx(D,{tone:ue(k),intensity:"subtle",children:de(k)}),contribution:o&&o>.15?"✓":"✗"},{id:"fcf",metric:"Free Cash Flow Yield",value:l?`${(l*100).toFixed(1)}%`:"—",threshold:">5%",assessment:e.jsx(D,{tone:ue(w),intensity:"subtle",children:de(w)}),contribution:l>.05?"✓":"✗"},{id:"de",metric:"Debt-to-Equity Ratio",value:m?`${m.toFixed(2)}x`:"—",threshold:"<0.5x",assessment:e.jsx(D,{tone:ue(Te(S)),intensity:"subtle",children:de(Te(S))}),contribution:m&&m<.5?"✓":"✗"},{id:"pb",metric:"Price-to-Book Ratio",value:c?`${c.toFixed(2)}x`:"—",threshold:"<3.0x",assessment:e.jsx(D,{tone:ue(p),intensity:"subtle",children:de(p)}),contribution:c&&c<3?"✓":"✗"}],L=[{id:"metric",header:"Metric",accessor:b=>b.id,sortable:!1,sticky:!0,cell:b=>e.jsx("span",{className:"font-medium",children:b.metric})},{id:"value",header:e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"sm:hidden",children:"Value"}),e.jsx("span",{className:"hidden sm:inline",children:"Current Value"})]}),accessor:b=>b.id,align:"right",sortable:!1,cell:b=>b.value},{id:"threshold",header:"Threshold",accessor:b=>b.id,align:"right",sortable:!1,cell:b=>b.threshold},{id:"assessment",header:e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"sm:hidden",children:"Status"}),e.jsx("span",{className:"hidden sm:inline",children:"Assessment"})]}),accessor:b=>b.id,align:"right",sortable:!1,cell:b=>b.assessment},{id:"contribution",header:e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"sm:hidden",children:"Met"}),e.jsx("span",{className:"hidden sm:inline",children:"Contribution"})]}),accessor:b=>b.id,align:"right",sortable:!1,cell:b=>b.contribution}];return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("section",{className:"space-y-4",children:[e.jsx(W,{as:"h3",size:{base:"5",md:"6"},icon:js,title:e.jsx($,{id:"economicMoat-overview",data:P.economicMoat,children:e.jsx("span",{children:"Economic Moat Overview"})}),subtitle:"Competitive advantages and business sustainability assessment"}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs("div",{className:"flex flex-col items-start gap-1",children:[e.jsx(O,{size:"sm",label:"Return on Capital",value:o?`${(o*100).toFixed(1)}%`:"—"}),e.jsxs(D,{tone:ue(k),intensity:"subtle",children:[de(k),f==="strong"&&e.jsx("span",{className:"ml-1",children:"🏰"})]})]}),e.jsxs("div",{className:"flex flex-col items-start gap-1",children:[e.jsx(O,{size:"sm",label:"FCF Yield",value:l?`${(l*100).toFixed(1)}%`:"—"}),e.jsxs(D,{tone:ue(w),intensity:"subtle",children:[de(w),g==="strong"&&e.jsx("span",{className:"ml-1",children:"🏰"})]})]}),e.jsxs("div",{className:"flex flex-col items-start gap-1",children:[e.jsx(O,{size:"sm",label:"Price-to-Book",value:c?`${c.toFixed(2)}x`:"—"}),e.jsxs(D,{tone:ue(p),intensity:"subtle",children:[de(p),x==="strong"&&e.jsx("span",{className:"ml-1",children:"🏰"})]})]}),e.jsxs("div",{className:"flex flex-col items-start gap-1",children:[e.jsx(O,{size:"sm",label:"Moat Strength",value:j}),e.jsx(D,{tone:ue(u),intensity:"subtle",children:de(u)})]})]}),e.jsxs(J,{tone:"neutral",children:[e.jsx("h4",{className:"font-semibold text-sm text-foreground mb-2",children:"Competitive Advantage Assessment"}),e.jsx(T,{as:"p",size:"2",color:"muted",children:j==="Wide Moat"?`${n} demonstrates strong economic moat characteristics with high ROIC of ${o?(o*100).toFixed(1):"N/A"}% and strong cash generation. The company's financial metrics suggest sustainable competitive advantages that protect against competition.`:j==="Narrow Moat"?`${n} shows moderate economic moat potential with some competitive advantages evident in its financial metrics. Monitor the sustainability of current returns and cash generation over time.`:j==="Limited Moat"?`${n} displays limited competitive advantages based on current financial metrics. Some protection exists but requires ongoing assessment of competitive positioning.`:`${n} appears to have limited economic moat protection based on current financial metrics. The company may face challenges defending market position and maintaining competitive advantages.`})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsxs("section",{className:"space-y-4",children:[e.jsx(W,{as:"h3",size:"4",title:"Sources of Competitive Advantage",subt
2itle:"Analysis of different moat types and their strength"}),e.jsx("div",{className:"space-y-4",children:v.map(b=>e.jsxs("div",{className:"flex items-center justify-between border-l-4 border-l-primary/30 pl-3 md:pl-4 py-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:b.title}),e.jsx(T,{size:"2",color:"muted",children:b.description})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("div",{className:"font-semibold",children:b.strengthLabel}),e.jsx(T,{size:"1",color:"muted",children:b.basedOn})]})]},b.id))})]}),e.jsxs("section",{className:"space-y-4",children:[e.jsx(W,{as:"h3",size:"4",title:"Moat Assessment Matrix",subtitle:"Comprehensive evaluation of competitive advantage indicators"}),e.jsx(Ss,{columns:L,data:M,getRowKey:b=>b.id,density:"sm",variant:"elevated",mobileVariant:"scroll"})]})]}),e.jsxs("section",{className:"space-y-4",children:[e.jsx(W,{as:"h3",size:"4",title:e.jsx($,{id:"economicMoat-summary",data:P.economicMoat,children:e.jsx("span",{children:"Economic Moat Summary & Analysis"})}),subtitle:"Investment implications of competitive advantages and business sustainability"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsx("div",{className:"bg-muted/30 rounded-lg p-4",children:e.jsx(O,{size:"sm",label:"Moat Width",value:j,subtext:`${h} of 4 strong indicators present`})}),e.jsx("div",{className:"bg-muted/30 rounded-lg p-4",children:e.jsx(O,{size:"sm",label:"Capital Efficiency",value:o&&o>.15?"Excellent":o&&o>.1?"Good":o?"Fair":"N/A",subtext:o?`${(o*100).toFixed(1)}% ROIC`:"Insufficient data"})}),e.jsx("div",{className:"bg-muted/30 rounded-lg p-4",children:e.jsx(O,{size:"sm",label:"Financial Strength",value:m&&m<.5?"Strong":m&&m<1?"Adequate":m?"Weak":"N/A",subtext:m?`${m.toFixed(2)}x debt/equity`:"Insufficient data"})})]}),e.jsxs(J,{tone:"neutral",children:[e.jsx("h4",{className:"font-semibold text-sm text-foreground mb-2",children:"Investment Perspective"}),e.jsx(T,{as:"p",size:"2",color:"muted",children:(()=>{let b="";return j==="Wide Moat"?(b="Exceptional competitive advantages with multiple strong moat indicators present. ",b+="The company demonstrates sustainable competitive positioning through high returns on capital, strong cash generation, and conservative financial structure. ",b+="This wide moat provides significant protection against competitors and supports long-term wealth creation through sustained above-average returns."):j==="Narrow Moat"?(b="Solid competitive advantages with moderate moat characteristics evident. ",b+="The company shows good financial metrics suggesting some protection against competition. ",b+="Monitor the sustainability and strengthening of these advantages over time to ensure competitive positioning remains intact."):j==="Limited Moat"?(b="Some competitive advantages present but limited overall moat protection. ",b+="The company displays certain positive indicators but lacks comprehensive competitive barriers. ",b+="Requires careful monitoring of industry dynamics and competitive pressures that could erode market position."):(b="Limited evidence of sustainable competitive advantages based on current financial metrics. ",b+="The company may struggle to defend market position against competitors and maintain pricing power. ",b+="Higher investment risk due to potential margin compression and market share erosion in competitive environments."),o&&o>.15?b+=" Exceptional capital efficiency suggests strong competitive positioning and management execution.":o&&o<.08&&(b+=" Below-average capital returns indicate potential competitive pressures or operational inefficiencies."),b})()})]})]})]})}function pp({balance:s,liquidityChartData:t,symbol:a,healthTimeRange:n,onHealthTimeRangeChange:i}){const o=xe(s||[]).map(p=>{const v=p.currentAssets!=null&&p.currentLiabilities!=null&&p.currentLiabilities>0?p.currentAssets/p.currentLiabilities:void 0,M=p.currentAssets!=null&&p.currentLiabilities!=null&&p.currentLiabilities>0?(p.currentAssets-(p.intangibles||0))/p.currentLiabilities:void 0,L=p.cash!=null&&p.currentLiabilities!=null&&p.currentLiabilities>0?p.cash/p.currentLiabilities:void 0,b=p.currentAssets!=null&&p.currentLiabilities!=null?p.currentAssets-p.currentLiabilities:void 0,I=p.totalDebt!=null&&p.shareholdersEquity!=null&&p.shareholdersEquity>0?p.totalDebt/p.shareholdersEquity:void 0;return{period:p.period,currentRatio:v,quickRatio:M,cashRatio:L,workingCapital:b!=null?b/1e9:void 0,debtToEquity:I,currentAssets:p.currentAssets!=null?p.currentAssets/1e9:void 0,currentLiabilities:p.currentLiabilities!=null?p.currentLiabilities/1e9:void 0,cash:p.cash!=null?p.cash/1e9:void 0}}).reverse(),l=t.filteredData,c=o[o.length-1],m=o[o.length-2],h=c?.currentRatio!=null&&m?.currentRatio!=null?c.currentRatio-m.currentRatio:void 0,y=c?.quickRatio!=null&&m?.quickRatio!=null?c.quickRatio-m.quickRatio:void 0,j=()=>
2{if(c?.currentRatio==null)return"Insufficient Data";const p=c.currentRatio,v=c.quickRatio||0;return p>=2&&v>=1?"Excellent":p>=1.5&&v>=.7?"Good":p>=1&&v>=.5?"Fair":p>=.8?"Poor":"Critical"};if(o.length===0||!c)return e.jsxs("div",{className:"text-center py-12",children:[e.jsx(T,{as:"div",color:"muted",className:"mb-2",children:"No Financial Health Data Available"}),e.jsxs(T,{as:"p",size:"2",color:"muted",className:"max-w-md mx-auto",children:["Balance sheet data is not available for ",a,". This may be due to insufficient financial data or recent IPO status."]})]});const u=Li(c?.cashRatio),f=Mi(u),g=ya(c?.currentRatio,c?.quickRatio),x=ja(g),S=$i(g),k=o.slice(-5).reverse(),w=[{id:"period",sticky:!0,header:"Period",accessor:p=>p.period,sortable:!1,cell:p=>e.jsx("span",{className:"font-medium",children:p.period})},{id:"currentRatio",header:e.jsx($,{id:"currentRatio-table",data:P.currentRatio,children:e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"sm:hidden",children:"Curr"}),e.jsx("span",{className:"hidden sm:inline",children:"Current Ratio"})]})}),accessor:p=>p.currentRatio,align:"right",sortable:!1,cell:p=>{const v=p.currentRatio;if(v==null)return"—";const M=v>=1.5?"text-gain":v>=1?"text-cautionary":"text-loss";return e.jsx("span",{className:M,children:v.toFixed(2)})}},{id:"quickRatio",header:e.jsx($,{id:"quickRatio-table",data:P.quickRatio,children:e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"sm:hidden",children:"Quick"}),e.jsx("span",{className:"hidden sm:inline",children:"Quick Ratio"})]})}),accessor:p=>p.quickRatio,align:"right",sortable:!1,cell:p=>{const v=p.quickRatio;if(v==null)return"—";const M=v>=1?"text-gain":v>=.7?"text-cautionary":"text-loss";return e.jsx("span",{className:M,children:v.toFixed(2)})}},{id:"cashRatio",header:e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"sm:hidden",children:"Cash"}),e.jsx("span",{className:"hidden sm:inline",children:"Cash Ratio"})]}),accessor:p=>p.cashRatio,align:"right",sortable:!1,cell:p=>p.cashRatio!=null?p.cashRatio.toFixed(2):"—"},{id:"debtToEquity",header:e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"sm:hidden",children:"D/E"}),e.jsx("span",{className:"hidden sm:inline",children:"Debt/Equity"})]}),accessor:p=>p.debtToEquity,align:"right",sortable:!1,cell:p=>{const v=p.debtToEquity;if(v==null)return"—";const M=v<=.5?"text-gain":v<=1?"text-cautionary":"text-loss";return e.jsx("span",{className:M,children:v.toFixed(2)})}},{id:"healthGrade",header:e.jsx($,{id:"healthGrade-table",data:P.healthGrade,children:e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"sm:hidden",children:"Grade"}),e.jsx("span",{className:"hidden sm:inline",children:"Health Grade"})]})}),accessor:p=>p.period,align:"right",sortable:!1,cell:p=>{const v=ya(p.currentRatio,p.quickRatio),M=ja(v);return e.jsx(D,{tone:ue(M),intensity:"subtle",children:de(M)})}}];return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("section",{className:"space-y-4",children:[e.jsx(W,{as:"h3",size:{base:"5",md:"6"},icon:xa,title:"Financial Health Overview",subtitle:"Liquidity, solvency, and financial stability analysis"}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(O,{size:"sm",label:e.jsx($,{id:"currentRatio-health",data:P.currentRatio,children:e.jsx("span",{children:"Current Ratio"})}),value:c?.currentRatio!=null?c.currentRatio.toFixed(2):"—",delta:h??null,deltaFormat:"number",deltaPrecision:2}),e.jsx(O,{size:"sm",label:e.jsx($,{id:"quickRatio-health",data:P.quickRatio,children:e.jsx("span",{children:"Quick Ratio"})}),value:c?.quickRatio!=null?c.quickRatio.toFixed(2):"—",delta:y??null,deltaFormat:"number",deltaPrecision:2}),e.jsxs("div",{className:"flex flex-col items-start gap-1",children:[e.jsx(O,{size:"sm",label:e.jsx($,{id:"cashRatio-overview",data:P.cashRatio,children:e.jsx("span",{children:"Cash Ratio"})}),value:c?.cashRatio!=null?c.cashRatio.toFixed(2):"—"}),e.jsx(D,{tone:ue(f),intensity:"subtle",children:de(f)})]}),e.jsxs("div",{className:"flex flex-col items-start gap-1",children:[e.jsx(O,{size:"sm",label:"Overall Health",value:S}),e.jsx(D,{tone:ue(x),intensity:"subtle",children:de(x)})]})]}),e.jsxs(J,{tone:"neutral",children:[e.jsx("h4",{className:"font-semibold text-sm text-foreground mb-2",children:"Financial Stability Assessment"}),e.jsx(T,{as:"p",size:"2",color:"muted",children:(()=>
2{if(c?.currentRatio==null)return"Insufficient balance sheet data for comprehensive liquidity analysis.";let p="";const v=c.currentRatio,M=c.quickRatio||0;return v>=2?(p="Strong liquidity position with current ratio above 2.0, indicating excellent ability to meet short-term obligations. ",p+="This conservative approach provides a substantial safety margin for value investors."):v>=1.5?(p="Solid liquidity with current ratio above 1.5, demonstrating good short-term financial health. ",p+="The company appears well-positioned to handle operational cash flow fluctuations."):v>=1?(p="Adequate liquidity with current ratio above 1.0, though closer monitoring is warranted. ",p+="Consider the quality of current assets and industry-specific working capital requirements."):(p="Concerning liquidity position with current ratio below 1.0, indicating potential difficulty meeting short-term obligations. ",p+="This raises red flags for conservative value investors seeking financial stability."),M>=1?p+=" The quick ratio above 1.0 confirms strong liquid asset coverage excluding inventory.":M>=.7?p+=" Acceptable quick ratio suggests reasonable liquidity when excluding less liquid current assets.":M>0&&(p+=" Lower quick ratio indicates dependence on inventory conversion for liquidity."),p})()})]})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs("section",{className:"space-y-4",children:[e.jsx(W,{as:"h3",size:"4",title:"Historical Liquidity Trends",subtitle:"Current ratio, quick ratio, and cash position over time",actions:e.jsx(Yt,{selectedRange:n,onRangeChange:i})}),e.jsx("div",{className:"h-56 sm:h-64 md:h-72",children:e.jsx(ke,{width:"100%",height:"100%",children:e.jsxs(As,{data:l.data,margin:{left:8,right:8,top:5,bottom:5},children:[e.jsx(Ve,{...Ta}),e.jsx(Le,{dataKey:"period",...Ns,tickFormatter:p=>String(p)}),e.jsx(Me,{...Js,...Ns,domain:[0,"auto"],tickFormatter:p=>p.toFixed(1)}),e.jsx(Pe,{formatter:(p,v)=>[typeof p=="number"?p.toFixed(2):p,v],labelFormatter:p=>`Year: ${p}`,contentStyle:{backgroundColor:"hsl(var(--background))",border:"1px solid hsl(var(--border))",borderRadius:"12px",boxShadow:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)"}}),e.jsx(Fa,{}),e.jsx(Se,{type:"monotone",dataKey:"currentRatio",name:"Current Ratio",stroke:"hsl(var(--chart-1))",strokeWidth:3,dot:{r:5,strokeWidth:2,fill:"hsl(var(--chart-1))"},activeDot:{r:7,strokeWidth:0}}),e.jsx(Se,{type:"monotone",dataKey:"quickRatio",name:"Quick Ratio",stroke:"hsl(var(--chart-4))",strokeWidth:3,dot:{r:5,strokeWidth:2,fill:"hsl(var(--chart-4))"},activeDot:{r:7,strokeWidth:0}}),e.jsx(Se,{type:"monotone",dataKey:"cashRatio",name:"Cash Ratio",stroke:"hsl(var(--chart-5))",strokeWidth:2,dot:{r:4,strokeWidth:2,fill:"hsl(var(--chart-5))"},activeDot:{r:6,strokeWidth:0}})]})})})]}),e.jsxs("section",{className:"space-y-4",children:[e.jsx(W,{as:"h3",size:"4",title:"Financial Health Analysis Table",subtitle:"Detailed breakdown of liquidity and s
2olvency metrics"}),e.jsx(Ss,{columns:w,data:k,getRowKey:p=>p.period,density:"sm",variant:"elevated",mobileVariant:"scroll"})]})]}),e.jsxs("section",{className:"space-y-4",children:[e.jsx(W,{as:"h3",size:"4",title:"Financial Health Summary & Analysis",subtitle:"Comprehensive evaluation of financial stability and risk"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsx("div",{className:"bg-muted/30 rounded-lg p-4",children:e.jsx(O,{size:"sm",label:"Liquidity Strength",value:c?.currentRatio==null?"N/A":c.currentRatio>=2?"Excellent":c.currentRatio>=1.5?"Good":c.currentRatio>=1?"Fair":"Poor",subtext:c?.currentRatio!=null?`${c.currentRatio.toFixed(2)} current ratio`:"Insufficient data"})}),e.jsx("div",{className:"bg-muted/30 rounded-lg p-4",children:e.jsx(O,{size:"sm",label:"Asset Quality",value:c?.quickRatio==null?"N/A":c.quickRatio>=1?"Excellent":c.quickRatio>=.7?"Good":c.quickRatio>=.5?"Fair":"Poor",subtext:c?.quickRatio!=null?`${c.quickRatio.toFixed(2)} quick ratio`:"Insufficient data"})}),e.jsx("div",{className:"bg-muted/30 rounded-lg p-4",children:e.jsx(O,{size:"sm",label:"Cash Position",value:c?.cashRatio==null?"N/A":c.cashRatio>=.2?"Strong":c.cashRatio>=.1?"Adequate":c.cashRatio>.05?"Limited":"Weak",subtext:c?.cashRatio!=null?`${c.cashRatio.toFixed(2)} cash ratio`:"Insufficient data"})})]}),e.jsxs(J,{tone:"neutral",children:[e.jsx("h4",{className:"font-semibold text-sm text-foreground mb-2",children:"Investment Perspective"}),e.jsx(T,{as:"p",size:"2",color:"muted",children:(()=>{if(c?.currentRatio==null)return"Insufficient balance sheet data for comprehensive financial health assessment. Monitor future financial reports for liquidity and s
2olvency metrics.";let p="";const v=j();return v==="Excellent"?(p="Exceptional financial health with strong liquidity ratios across all metrics. ",p+="This provides substantial margin of safety for value investors and indicates management's conservative financial approach. The company is well-positioned to navigate economic downturns and capitalize on growth opportunities."):v==="Good"?(p="Solid financial health with good liquidity coverage for short-term obligations. ",p+="The company demonstrates prudent working capital management and adequate cash flow generation to support operations and growth initiatives."):v==="Fair"?(p="Adequate financial health though closer monitoring is warranted. ",p+="While current obligations can be met, limited margin for error exists. Monitor cash flow trends and working capital efficiency closely."):v==="Poor"?(p="Concerning financial health indicators suggest potential liquidity stress. ",p+="The company may face challenges meeting short-term obligations without improved cash generation or refinancing activities."):(p="Critical financial health situation requiring immediate attention. ",p+="Significant liquidity concerns pose material risks to business continuity and shareholder value preservation."),h!=null&&Math.abs(h)>.1&&(h>0?p+=" Recent improvement in liquidity metrics suggests strengthening financial position and operational efficiency.":p+=" Recent deterioration in liquidity warrants investigation into working capital management and cash flow dynamics."),p})()})]})]})]})}function ga(s,t,a){return Math.max(t,Math.min(a,s))}function gp(s){if(!s)return 50;let t=50;return typeof s.pe=="number"&&(s.pe<12?t+=12:s.pe<18?t+=6:s.pe>30?t-=12:s.pe>22&&(t-=6)),typeof s.pb=="number"&&(s.pb<1?t+=10:s.pb<2?t+=5:s.pb>4?t-=10:s.pb>3&&(t-=5)),typeof s.fcfYield=="number"&&(t+=ga((s.fcfYield-5)*2,-12,18)),typeof s.de=="number"&&(s.de<.5?t+=8:s.de<1?t+=4:s.de>2?t-=8:s.de>1.5&&(t-=4)),typeof s.roic=="number"&&(t+=ga((s.roic-8)*.8,-8,16)),Math.round(ga(t,0,100))}function Et(s){if(!s&&s!==0)return"—";const t=Math.abs(s);return t>=1e12?`${(s/1e12).toFixed(2)}T`:t>=1e9?`${(s/1e9).toFixed(2)}B`:t>=1e6?`${(s/1e6).toFixed(2)}M`:t>=1e3?`${(s/1e3).toFixed(0)}K`:String(s)}function Wn(s){return s==null||!Number.isFinite(s)?"—":s.toFixed(2)}function Hn(s){if(s==null||!Number.isFinite(s))return"—";const t=Math.abs(s),a=s<0?"-":"";return t>=1e9?`${a}${(t/1e9).toFixed(2)}B`:t>=1e6?`${a}${(t/1e6).toFixed(2)}M`:`${a}${t.toLocaleString(void 0,{maximumFractionDigits:0})}`}function fp(s,t){const a=s.ratios||{},n=[];return typeof a.pe=="number"&&n.push(`P/E ${a.pe.toFixed(1)}`),typeof a.pb=="number"&&n.push(`P/B ${a.pb.toFixed(1)}`),typeof a.fcfYield=="number"&&n.push(`FCF Yield ${(a.fcfYield*100).toFixed(1)}%`),typeof a.de=="number"&&n.push(`D/E ${a.de.toFixed(2)}`),typeof a.roic=="number"&&n.push(`ROIC ${(a.roic*100).toFixed(1)}%`),`${t>=66?"Attractive value":t>=40?"Fairly valued":"Potentially expensive"} based on current fundamentals. ${n.join(", ")}.`}function cg(){const t=(hl().symbol||"").toUpperCase().trim(),a=pl(),n=Ea(),{isAdmin:i}=so(),r=yt({queryKey:["etf-symbol-probe",t],enabled:!!t,staleTime:24*60*60*1e3,gcTime:48*60*60*1e3,refetchOnWindowFocus:!1,retry:!1,queryFn:async()=>{const{data:N}=await He.from("etfs").select("symbol").eq("symbol",t).maybeSingle();return!!N}});E.useEffect(()=>{r.data===!0&&n(`/etfs/${t}${a.search}`,{replace:!0})},[r.data,t,a.search,n]);const[o,l]=E.useState("1Y"),[c,m]=E.useState(""),[h,y]=E.useState("dcf"),[j,u]=E.useState("all"),[f,g]=E.useState("overview");ni();const{trackFeature:x,trackConversion:S}=to(),{isEnabled:k}=ao(),w=new URLSearchParams(a.search),p=w.get("tab"),v=w.get("subtab"),M=w.get("year"),L=()=>{const N=a.state;N?.from?n(N.from):n(-1)},b=()=>{const N=[{value:"summary",flag:"stock_details_summary_tab"},{value:"financials",flag:"stock_details_financials_tab"},{value:"fundamentals",flag:"stock_details_fundamentals_tab"},{value:"value",flag:"stock_details_value_analysis_tab"},{value:"comparative",flag:"stock_details_comparative_tab"},{value:"bedrock",flag:"bedrock_analysis_tab"},{value:"stock-review",flag:"stock_details_stock_review_tab"}];for(const B of N)if(k(B.flag,!0))return B.value;return"summary"};E.useEffect(()=>{if(!c){const N=p||b();m(N)}},[c,k,p]),E.useEffect(()=>{v&&c==="value"&&y(v)},[v,c]),E.useEffect(()=>{v&&c==="comparative"&&u(v)},[v,c]),E.useEffect(()=>{v&&c==="bedrock"&&oi.includes(v)&&g(v)},[v,c]),E.useEffect(()=>{const N=B=>{const{symbol:fe}=B.detail;fe&&fe.toUpperCase()===t&&m("value")};
2return window.addEventListener("analysis-completed",N),()=>{window.removeEventListener("analysis-completed",N)}},[t]);const[I,ee]=E.useState("10Y"),[U,A]=E.useState("10Y"),[K,ne]=E.useState("Max"),[je,se]=E.useState("Max"),[oe,De]=E.useState(!1),[is,rs]=E.useState(!1),ps=async()=>{let N=`${window.location.origin}${a.pathname}?tab=${c}`;c==="value"&&h&&h!=="all"?N+=`&subtab=${h}`:c==="comparative"&&j&&j!=="all"?N+=`&subtab=${j}`:c==="bedrock"&&f&&f!=="overview"&&(N+=`&subtab=${f}`);try{await navigator.clipboard.writeText(N),rs(!0);const B=c==="value"&&h&&h!=="all"?`${c} - ${h} tab`:c==="comparative"&&j&&j!=="all"?`${c} - ${j} tab`:c==="bedrock"&&f&&f!=="overview"?`${c} - ${f} tab`:`${c} tab`;bt({title:"Link Copied!",description:`Link to ${B} copied to clipboard`}),setTimeout(()=>rs(!1),2e3)}catch(B){console.error("Failed to copy link:",B),bt({title:"Copy Failed",description:"Please copy the URL from your browser's address bar",variant:"destructive"})}},[te,Cs]=E.useState("annual"),{data:C,isLoading:V,error:ie,isCacheHit:Fs,cacheStats:Zs}=zt(t,{dataScope:"analysis",enabled:!!t}),{data:_,isLoading:q,error:H}=bl(t,{period:te,enabled:!!t&&c==="financials"});E.useEffect(()=>{console.log("📊 Smart Cache Fetch Status:",{periodType:te,isLoadingSmartCache:q,hasIncome:!!_?.income?.length,hasBalance:!!_?.balance?.length,hasCashflow:!!_?.cashflow?.length})},[te,q,_]),E.useEffect(()=>{if(_){const N=((_.metadata?.income?.cacheHitRate||0)+(_.metadata?.balance?.cacheHitRate||0)+(_.metadata?.cashflow?.cacheHitRate||0))/3;console.log("🚀 Smart Cache Performance:",{avgCacheHitRate:`${N.toFixed(1)}%`,income:`${_.income?.length||0} items`,balance:`${_.balance?.length||0} items`,cashflow:`${_.cashflow?.length||0} items`})}},[_]),E.useEffect(()=>{_&&te==="quarterly"&&console.log("📊 All Financial Statements Response:",{hasIncome:!!_.income?.length,hasBalance:!!_.balance?.length,hasCashflow:!!_.cashflow?.length,firstIncomeItem:_.income?.[0],firstBalanceItem:_.balance?.[0],firstCashflowItem:_.cashflow?.[0]})},[_,te]);const Q=(N,B)=>{const fe=B;if(_&&fe==="quarterly"){console.log(`📊 Using smart cache for ${fe} ${N} data`);const Is=_[N]||[];return N==="income"?Is.map(F=>({period:(()=>{if(!F.date)return F.period;const Ne=new Date(F.date),Y=Ne.getFullYear(),Ue=Ne.getMonth()+1;let Ce="Q1";return Ue<=3?Ce="Q1":Ue<=6?Ce="Q2":Ue<=9?Ce="Q3":Ce="Q4",`${Y} ${Ce}`})(),date:F.date,revenue:F.revenue,costOfRevenue:F.cost_of_revenue||F.costOfRevenue,grossProfit:F.gross_profit||F.grossProfit,operatingExpenses:F.operating_expenses||F.operatingExpenses,operatingIncome:F.operating_income||F.operatingIncome,otherIncomeExpense:F.total_other_income_expenses_net||F.otherIncomeExpense||0,incomeBeforeTax:F.income_before_tax||F.incomeBeforeTax,incomeTaxExpense:F.income_tax_expense||F.incomeTaxExpense,netIncome:F.net_income||F.netIncome,epsDiluted:F.eps_diluted||F.epsdiluted||F.eps,sharesDiluted:F.weighted_average_shs_out_dil||F.weightedAverageShsOutDil||F.shares,normalizedEbitda:F.ebitda||F.normalizedEbitda,shares:F.weighted_average_shs_out||F.weightedAverageShsOut,researchAndDevelopmentExpenses:F.research_and_development_expenses||F.researchAndDevelopmentExpenses,sellingGeneralAndAdministrativeExpenses:fn(F),salesAndMarketingExpenses:F.selling_and_marketing_expenses||F.sellingAndMarketingExpenses,generalAndAdministrativeExpenses:F.general_and_administrative_expenses||F.generalAndAdministrativeExpenses,interestExpense:F.interest_expense||F.interestExpense,interestIncome:F.interest_income||F.interestIncome,netInterestIncome:F.net_interest_income||F.netInterestIncome,depreciationAndAmortization:F.depreciation_and_amortization||F.depreciationAndAmortization,eps:F.eps,ebitda:F.ebitda})):N==="balance"?Is.map(F=>({period:(()=>{if(!F.date)return F.period;const Ne=new Date(F.date),Y=Ne.getFullYear(),Ue=Ne.getMonth()+1;let Ce="Q1";return Ue<=3?Ce="Q1":Ue<=6?Ce="Q2":Ue<=9?Ce="Q3":Ce="Q4",`${Y} ${Ce}`})(),date:F.date,currentAssets:F.total_current_assets||F.totalCurrentAssets,fixedAssets:F.property_plant_equipment_net||F.propertyPlantEquipmentNet,intangibles:F.intangible_assets||F.intangibleAssets,goodwill:F.goodwill,currentLiabilities:F.total_current_liabilities||F.totalCurrentLiabilities,longTermDebt:F.long_term_debt||F.longTermDebt,shortTermDebt:F.short_term_debt||F.shortTermDebt,shareholdersEquity:F.total_stockholders_equity||F.totalStockholdersEquity,cash:F.cash_and_cash_equivalents||F.cashAndCashEquivalents,totalDebt:F.total_debt||F.totalDebt,totalAssets:F.total_assets||F.totalAssets,totalLiabilities:F.total_liabilities||F.totalLiabilities,currentRatio:F.total_current_assets&&F.total_current_liabilities?F.total_current_assets/F.total_current_liabilities:void 0,quickRatio:F.total_current_assets&&F.inventory&&F.total_current_liabilities?(F.total_current_assets-F.inventory)/F.total_current_liabilities:void 0})):N==="cashflow"?Is.map(F=>({period:(()=>
2{if(!F.date)return F.period;const Ne=new Date(F.date),Y=Ne.getFullYear(),Ue=Ne.getMonth()+1;let Ce="Q1";return Ue<=3?Ce="Q1":Ue<=6?Ce="Q2":Ue<=9?Ce="Q3":Ce="Q4",`${Y} ${Ce}`})(),date:F.date,operatingCashFlow:F.operating_cash_flow||F.operatingCashFlow||F.net_cash_provided_by_operating_activities||F.netCashProvidedByOperatingActivities,investingCashFlow:F.net_cash_used_for_investing_activites||F.netCashUsedForInvestingActivites||F.investing_cash_flow||F.investingCashFlow,financingCashFlow:F.net_cash_used_provided_by_financing_activities||F.netCashUsedProvidedByFinancingActivities||F.financing_cash_flow||F.financingCashFlow,endingCash:F.cash_at_end_of_period||F.cashAtEndOfPeriod||F.endingCash,capex:F.capital_expenditure||F.capitalExpenditure,fcf:F.free_cash_flow||F.freeCashFlow,dividendsPaid:F.dividends_paid||F.dividendsPaid,buybacks:F.common_stock_repurchased||F.commonStockRepurchased})):Is}return console.log("⚠️ Quarterly data requested but smart cache not available:",{type:N,currentPeriod:fe,allStatementsLoaded:!!_}),[]},ae=N=>Q(N,"quarterly"),{data:et}=yt({queryKey:["processed-logo",t],queryFn:async()=>{const{data:N,error:B}=await He.from("stock_symbols_cache").select("processed_logo_url").eq("symbol",t).single();return B?(console.warn("Failed to fetch processed logo:",B),null):N},enabled:!!t,staleTime:1e3*60*60}),d=E.useMemo(()=>{if(!C)return;const N=C.data||C,B=(Ne=[])=>Ne.map(Y=>({period:Y.period||"",revenue:Y.revenue,costOfRevenue:Y.costOfRevenue,grossProfit:Y.grossProfit,operatingExpenses:Y.operatingExpenses,operatingIncome:Y.operatingIncome,otherIncomeExpense:Y.otherIncomeExpense,incomeBeforeTax:Y.incomeBeforeTax,incomeTaxExpense:Y.incomeTaxExpense,netIncome:Y.netIncome,normalizedEbitda:Y.normalizedEbitda,shares:Y.shares,epsDiluted:Y.epsDiluted,sharesDiluted:Y.sharesDiluted,researchAndDevelopmentExpenses:Y.research_and_development_expenses||Y.researchAndDevelopmentExpenses,sellingGeneralAndAdministrativeExpenses:fn(Y),salesAndMarketingExpenses:Y.selling_and_marketing_expenses||Y.sellingAndMarketingExpenses,generalAndAdministrativeExpenses:Y.general_and_administrative_expenses||Y.generalAndAdministrativeExpenses,interestExpense:Y.interest_expense||Y.interestExpense,interestIncome:Y.interest_income||Y.interestIncome,netInterestIncome:Y.net_interest_income||Y.netInterestIncome,depreciationAndAmortization:Y.depreciation_and_amortization||Y.depreciationAndAmortization})),fe=(Ne=[])=>Ne.map(Y=>({period:Y.period||"",currentAssets:Y.currentAssets,fixedAssets:Y.fixedAssets,intangibles:Y.intangibles,goodwill:Y.goodwill,currentLiabilities:Y.currentLiabilities,longTermDebt:Y.longTermDebt,shortTermDebt:Y.shortTermDebt,shareholdersEquity:Y.shareholdersEquity,cash:Y.cash,totalDebt:Y.totalDebt,totalAssets:Y.totalAssets,totalLiabilities:Y.totalLiabilities,currentRatio:Y.currentRatio,quickRatio:Y.quickRatio})),Is=(Ne=[])=>Ne.map(Y=>({period:Y.period||"",operatingCashFlow:Y.operatingCashFlow,investingCashFlow:Y.investingCashFlow,financingCashFlow:Y.financingCashFlow,endingCash:Y.endingCash,cfo:Y.cfo,capex:Y.capex,fcf:Y.fcf,dividendsPaid:Y.dividendsPaid,buybacks:Y.buybacks}));return{symbol:N.symbol,name:N.name||N.companyProfile?.companyName||N.symbol,exchange:N.exchange||N.companyProfile?.exchange,sector:N.sector,industry:N.industry,companyProfile:N.companyProfile?{sector:N.sector,industry:N.industry,exch
2ange:N.exchange,description:N.companyProfile.description||"",ceo:N.companyProfile.ceo||"",employees:N.companyProfile.employees||null,founded:N.companyProfile.founded||"",headquarters:N.companyProfile.headquarters||"",website:N.companyProfile.website||"",phone:N.companyProfile.phone||"",address:N.companyProfile.address||"",zip:N.companyProfile.zip||"",dcfDiff:N.companyProfile.dcfDiff||null,dcf:N.companyProfile.dcf||null,image:N.companyProfile.image||"",defaultImage:N.companyProfile.defaultImage||!1,isEtf:N.companyProfile.isEtf||!1,isActivelyTrading:N.companyProfile.isActivelyTrading||!0,isFund:N.companyProfile.isFund||!1,isAdr:N.companyProfile.isAdr||!1}:void 0,price:N.price||0,change:N.change||null,changesPercentage:N.changesPercentage,afterHoursChange:N.afterHoursChange,afterHoursChangePercent:N.afterHoursChangePercent,marketCap:N.marketCap,fiftyTwoWeekHigh:N.fiftyTwoWeekHigh,fiftyTwoWeekLow:N.fiftyTwoWeekLow,eps:N.eps||null,sharesOutstanding:N.sharesOutstanding,enterpriseValue:N.enterpriseValue,ratios:N.ratios?{pe:N.ratios.pe,pb:N.ratios.pb,de:N.ratios.de,roic:N.ratios.roic,fcfYield:N.ratios.fcfYield}:void 0,daily:N.daily||N.historical||[],historical:N.historical||[],pricesAll:N.historical||[],intradayToday:N.intradayToday||[],financials:N.financials?{income:B(N.financials.income),balance:fe(N.financials.balance),cashflow:Is(N.financials.cashflow)}:void 0,financialsQ:N.financialsQ?{income:B(N.financialsQ.income),balance:fe(N.financialsQ.balance),cashflow:Is(N.financialsQ.cashflow)}:void 0,analysis:N.analysis||void 0,balance:N.financials?.balance?fe(N.financials.balance):void 0,metrics:N.metrics||void 0,news:N.news?.map(Ne=>({title:Ne.title,url:Ne.url,publishedDate:Ne.publishedDate,site:Ne.site,text:Ne.text||"",image:Ne.image||null}))||void 0}},[C]);jt.useEffect(()=>{},[t,Zs,Fs]);const{peerAnalysis:qa,allPeers:st}=bi({symbol:d?.symbol||t,strategy:"hybrid",maxPeers:8,lightweightMode:!1}),qe=E.useMemo(()=>{const N=d?.symbol||t;console.log("🚀 DEBUG StockDetails - unifiedAllPeers:",st),console.log("🚀 DEBUG StockDetails - mainSymbol:",N);const B=st.filter(fe=>fe.symbol!==N).slice(0,6).map(fe=>fe.symbol);return console.log("🚀 DEBUG StockDetails - unifiedPeers result:",B),B},[st,d?.symbol,t]),tt=E.useMemo(()=>vo(d?.pricesAll&&d.pricesAll.length?d.pricesAll:d?.historical),[d?.pricesAll,d?.historical]),at=E.useMemo(()=>d?.analysis?.fcfDivsBuybacks?d.analysis.fcfDivsBuybacks.map(N=>({period:N.period,fcf:N.fcf,dividends:N.dividendsPaid,buybacks:N.buybacks})).sort((N,B)=>N.period.localeCompare(B.period)):[],[d?.analysis?.fcfDivsBuybacks]),Ds=E.useMemo(()=>d?.analysis?.roicTrend?d.analysis.roicTrend.map(N=>({period:N.period,roic:N.roic,roa:N.roa,roe:N.roe})).sort((N,B)=>N.period.localeCompare(B.period)):[],[d?.analysis?.roicTrend]),Ba=E.useMemo(()=>d?.analysis?.sharesTrend?d.analysis.sharesTrend.filter(N=>N.shares!=null&&N.shares>0).reverse():[],[d?.analysis?.sharesTrend]),Ar=E.useMemo(()=>d?.balance?d.balance.map(N=>({period:N.period,currentRatio:N.currentRatio,quickRatio:N.quickRatio,cash:N.cash?N.cash/1e9:void 0})).reverse():[],[d?.balance]),Sr=Ct({data:at,selectedTimeRange:I,dateField:"period"}),Cr=Ct({data:Ds,selectedTimeRange:U,dateField:"period"}),Fr=Ct({data:Ba,selectedTimeRange:K,dateField:"period"}),Ir=Ct({data:Ar,selectedTimeRange:je,dateField:"period"});if(E.useEffect(()=>{d?.symbol&&(x("stock-view","view",{symbol:d.symbol}),S("stock-details-view",1,{symbol:d.symbol}))},[d?.symbol,x,S]),V)return e.jsxs("main",{className:"container mx-auto px-4 py-8",children:[e.jsx(Zt,{title:`${t} Stock Analysis | Value Investing Hub`,description:`Loading ${t} stock details including valuation metrics, financial ratios, DCF analysis, and value score.`,canonicalUrl:`/stocks/${t}`}),e.jsx(ea,{data:[sa([{name:"Home",url:"/"},{name:"Stocks",url:"/stock-screener"},{name:t,url:`/stocks/${t}`}])]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(be,{className:"h-8 w-72"}),e.jsx(be,{className:"h-4 w-40"})]}),e.jsxs("section",{className:"grid gap-6 md:grid-cols-3 mt-6",children:[e.jsxs(_e,{padding:"0",className:"md:col-span-2",children:[e.jsxs(os,{className:"flex-col md:flex-row items-start md:items-center justify-between gap-3 md:gap-0 p-4 md:p-6",children:[e.jsxs("div",{children:[e.jsx(be,{className:"h-6 w-56"}),e.jsx(be,{className:"h-4 w-40 mt-2"})]}),e.jsx(be,{className:"h-6 w-24"})]}),e.jsx(ls,{className:"p-4 md:p-6 pt-0",children:e.jsx(be,{className:"h-64 w-full"})})]}),e.jsxs(_e,{padding:"0",children:[e.jsxs(os,{className:"p-4 md:p-6",children:[e.jsx(be,{className:"h-6 w-40"}),e.jsx(be,{className:"h-4 w-32 mt-2"})]}),e.jsx(ls,{className:"p-4 md:p-6 pt-0",children:e.jsx("div",{className:"grid grid-cols-2 gap-3 text-sm",children:Array.from({length:6}).map((N,B)=>e.jsxs("div",{children:[e.jsx(be,{className:"h-4 w-20"}),e.jsx(be,{className:"h-5 w-16 mt-1"})]},B))})})]})]})]});const gs=d?.exchange?no(d.exchange):null,nt=gs&&!gs.isSupported;
2if(ie||!d||nt){console.log("🚨 StockDetails Error Details:",{symbol:t,error:ie?.message||ie,hasData:!!d,exchange:d?.exchange,isExchangeSupported:gs?.isSupported,errorType:typeof ie});const N=t?io(t):null,B=N&&(N.isInternational||N.isOTC);return e.jsxs("main",{className:"container mx-auto px-4 py-8",children:[e.jsx(Zt,{title:`${t} Stock Not Found | Value Investing Hub`,description:`Stock ${t} could not be found. The symbol may be delisted, incorrect, or temporarily unavailable.`,canonicalUrl:`/stocks/${t}`}),e.jsx(ea,{data:[sa([{name:"Home",url:"/"},{name:"Stocks",url:"/stock-screener"},{name:t,url:`/stocks/${t}`}])]}),e.jsxs("div",{className:"space-y-4 max-w-2xl",children:[e.jsx("h1",{className:"text-2xl font-semibold",children:"Stock not found"}),nt&&gs&&e.jsxs(us,{variant:"destructive",children:[e.jsx(Ee,{className:"h-4 w-4"}),e.jsx(vs,{children:"Unsupported Exchange"}),e.jsxs(ms,{className:"space-y-2",children:[e.jsx("p",{children:gs.warning}),gs.suggestion&&e.jsx("p",{className:"font-medium",children:gs.suggestion}),e.jsxs("div",{className:"mt-3 p-3 bg-muted/50 rounded text-sm",children:[e.jsx("strong",{children:"Detected Exchange:"})," ",gs.displayName]})]})]}),!nt&&B&&e.jsxs(us,{variant:"destructive",children:[e.jsx(Ee,{className:"h-4 w-4"}),e.jsx(vs,{children:"Market Not Supported"}),e.jsxs(ms,{className:"space-y-2",children:[e.jsx("p",{children:N.warning}),N.suggestion&&e.jsx("p",{className:"font-medium",children:N.suggestion}),e.jsx("p",{className:"text-sm mt-2",children:"We currently only support US-listed stocks from NASDAQ, NYSE, and AMEX exchanges."})]})]}),!B&&!nt&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"mt-2 text-muted-foreground",children:["We couldn't find detailed information for ",t,". This could be due to:"]}),e.jsxs("ul",{className:"list-disc list-inside text-muted-foreground space-y-1 ml-4",children:[e.jsx("li",{children:"Temporary API issues"}),e.jsx("li",{children:"Symbol not available in our data provider"}),e.jsx("li",{children:"Market closure or data feed delays"}),e.jsx("li",{children:"Symbol may be delisted or incorrect"})]})]}),e.jsxs(us,{children:[e.jsx(Ee,{className:"h-4 w-4"}),e.jsx(vs,{children:"Supported Markets"}),e.jsxs(ms,{children:["Only stocks listed on the following US exchanges are currently supported:",e.jsxs("ul",{className:"list-disc list-inside mt-2 space-y-1",children:[e.jsx("li",{children:"NASDAQ (including Global Market and Capital Market)"}),e.jsx("li",{children:"NYSE (New York Stock Exchange)"}),e.jsx("li",{children:"AMEX (American Stock Exchange)"})]})]})]}),e.jsxs("div",{className:"flex gap-3 mt-6",children:[e.jsx(ye,{variant:"outline",onClick:L,children:"Go Back"}),!B&&!nt&&e.jsx(ye,{onClick:()=>window.location.reload(),variant:"default",children:"Try Again"}),e.jsx(ye,{onClick:()=>n("/"),variant:"secondary",children:"Search Again"})]}),!1]})]})}const Rr=gp(d.ratios),kr=fp(d,Rr),it=(()=>{const N=`${d.symbol} - ${d.name}`,B=[d.symbol,d.name,"stock analysis"];switch(c){case"10k":return{title:`${N} | 10-K Analysis - SEC Filing Deep Dive`,description:`AI-powered analysis of ${d.symbol}'s SEC 10-K filing: Economic moat, management quality, risk assessment, growth prospects, and valuation insights.`,ogTitle:`${d.symbol} 10-K Analysis - Economic Moat & Management Quality`,ogDescription:`Comprehensive 10-K analysis for ${d.name} (${d.symbol}) including moat strength, management evaluation, and risk factors from SEC filings.`,keywords:[...B,"10-K analysis","SEC filing","economic moat","management quality","10-K AI analysis"]};case"financials":return{title:`${N} | Financial Statements - Income, Balance, Cash Flow`,description:`${d.symbol} complete financial statements: income statement, balance sheet, cash flow analysis with trends and visualizations.`,ogTitle:`${d.symbol} Financial Statements & Analysis`,ogDescription:`View ${d.name} financial data: revenue, earnings, assets, liabilities, and cash flows with historical trends.`,keywords:[...B,"financial statements","income statement","balance sheet","cash flow"]};case"value":return{title:`${N} | Value Analysis - DCF Valuation & Intrinsic Value`,description:`${d.symbol} DCF valuation model: intrinsic value calculation, margin of safety, value score, and investment verdict.`,ogTitle:`${d.symbol} DCF Valuation & Value Analysis`,ogDescription:`Calculate ${d.name} intrinsic value using DCF methodology with detailed valuation metrics and investment recommendation.`,keywords:[...B,"dcf valuation","intrinsic value","value investing","margin of safety"]};case"fundamentals":return{title:`${N} | Fundamental Analysis - Metrics & Ratios`,description:`${d.symbol} fundamental metrics: P/E ratio, ROIC, FCF yield, debt/equity, profitability, and growth analysis.`,ogTitle:`${d.symbol} Fundamental Analysis & Key Metrics`,ogDescription:`${d.name} key fundamental metrics including valuation ratios, profitability measures, and financial health indicators.`,keywords:[...B,"fundamentals","pe ratio","roic","fcf yield","financial ratios"]};default:return{title:`${N} | Stock Analysis - Value Score & DCF`,description:`${d.symbol} (${d.name}) stock analysis: P/E ${d.ratios?.pe?.toFixed(1)||"N/A"}, Market Cap $${d.metrics?.marketCap?(d.metrics.marketCap/1e9).toFixed(1)+"B":"N/A"}. Full DCF valuation, financial metrics, and value score.`,ogTitle:`${d.symbol} - ${d.name} Stock Analysis & Valuation`,ogDescription:`Comprehensive ${d.symbol} analysis including DCF valuation, P/E ratio, value score, and key financial metrics.`,keywords:[...B,"stock analysis","dcf valuation","value score","pe ratio","stock fundamentals"]}}})(),Qt=d.companyProfile?.sector,za=[{name:"Home",url:"/"},{name:"Stocks",url:"/stock-screener"},...Qt?[{name:Qt,url:`/stock-screener?sector=${encodeURIComponent(Qt)}`}]:[],{name:`${d.symbol} - ${d.name}`,url:`/stocks/${d.symbol}`}];
2return e.jsxs(e.Fragment,{children:[e.jsx(Zt,{title:it.title,description:it.description,canonicalUrl:`/stocks/${d.symbol}${c?`?tab=${c}`:""}`,ogType:"article",ogTitle:it.ogTitle,ogDescription:it.ogDescription,twitterCard:"summary_large_image",keywords:it.keywords.filter(Boolean)}),e.jsx(ea,{data:[sa(za),{"@context":"https://schema.org","@type":"WebPage",name:`${d.symbol} - ${d.name} Stock Analysis`,description:`Comprehensive stock analysis for ${d.name} (${d.symbol}) including valuation metrics, financial health, DCF analysis, and value investing score.`,url:`https://www.valueinvestinghub.com/stocks/${d.symbol}`,dateModified:new Date().toISOString().split("T")[0],isPartOf:{"@type":"WebSite",name:"Value Investing Hub",url:"https://www.valueinvestinghub.com"},about:{"@type":"Corporation",name:d.name,tickerSymbol:d.symbol,...d.companyProfile?.sector&&{industry:d.companyProfile.sector},...d.companyProfile?.website&&{url:d.companyProfile.website},...d.companyProfile?.ceo&&{employee:{"@type":"Person",name:d.companyProfile.ceo,jobTitle:"CEO"}}},publisher:{"@type":"Organization",name:"Value Investing Hub",url:"https://www.valueinvestinghub.com"}},{"@context":"https://schema.org","@type":"Article",headline:`${d.name} (${d.symbol}) Stock Analysis & Valuation`,description:`Comprehensive stock analysis for ${d.name} (${d.symbol}) including valuation metrics, financial health, DCF analysis, and value investing score.`,url:`https://www.valueinvestinghub.com/stocks/${d.symbol}`,datePublished:new Date().toISOString().split("T")[0],dateModified:new Date().toISOString().split("T")[0],author:{"@type":"Organization",name:"Value Investing Hub",url:"https://www.valueinvestinghub.com"},publisher:{"@type":"Organization",name:"Value Investing Hub",logo:{"@type":"ImageObject",url:"https://www.valueinvestinghub.com/icons/icon-512x512.png"}},mainEntityOfPage:{"@type":"WebPage","@id":`https://www.valueinvestinghub.com/stocks/${d.symbol}`},about:{"@type":"Corporation",name:d.name,tickerSymbol:d.symbol},articleSection:d.companyProfile?.sector||"Stock Analysis",isAccessibleForFree:!0}]}),e.jsxs("header",{className:"container mx-auto px-4 py-3",children:[e.jsx(mo,{items:za}),e.jsx("div",{className:"mb-3 animate-fade-in",children:e.jsxs("div",{className:"flex flex-col md:flex-row items-start md:items-center justify-between gap-4 md:gap-0",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx(ro,{symbol:d.symbol,name:d.name,logoUrl:d.companyProfile?.image,processedLogoUrl:et?.processed_logo_url,size:"md"}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold bg-gradient-to-r from-primary to-primary/60 bg-clip-text text-transparent",children:d.symbol}),e.jsx(uo,{symbol:d.symbol,variant:"full"}),e.jsx(Zn,{children:e.jsxs(ei,{children:[e.jsx(si,{asChild:!0,children:e.jsx(ye,{variant:"outline",size:"icon",onClick:ps,className:"h-9 w-9",children:is?e.jsx(hi,{className:"h-4 w-4 text-primary"}):e.jsx(Bo,{className:"h-4 w-4"})})}),e.jsx(ti,{children:e.jsx("p",{children:is?"Link copied!":`Copy link to ${c} tab`})})]})})]}),e.jsxs("p",{className:"text-sm md:text-base text-muted-foreground leading-relaxed",children:[d.name," · ",d.sector||d.exchange||""]})]}),e.jsxs("div",{className:"text-left md:text-right",children:[e.jsx("div",{className:"text-3xl md:text-4xl font-bold",children:typeof d.price=="number"?`$${d.price.toFixed(2)}`:"—"}),e.jsx("div",{className:"text-sm md:text-base text-muted-foreground",children:typeof d.change=="number"&&typeof d.changesPercentage=="number"?e.jsxs("span",{className:d.change>=0?"text-gain":"text-loss",children:[d.change>=0?"+":"",d.change.toFixed(2)," (",d.changesPercentage.toFixed(2),"%)"]}):e.jsx("span",{children:"Day change —"})})]})]})},t)]}),e.jsxs("main",{className:"container mx-auto px-4 pb-6 space-y-6",children:[e.jsx(Os,{flag:"stock_details_tabs",defaultValue:!0,fallback:e.jsx("section",{className:"space-y-6",children:e.jsxs("section",{className:"grid gap-6",children:[e.jsxs("div",{className:"grid gap-6 md:grid-cols-3",children:[e.jsxs(_e,{padding:"0",className:"md:col-span-2",children:[e.jsx(os,{className:"flex-col md:flex-row items-start md:items-center justify-between gap-3 md:gap-0 p-4 md:p-6",children:e.jsxs("div",{children:[e.jsx(Rs,{className:"text-xl",children:"Price Chart"}
2),e.jsx(ks,{children:"Stock movement and trend analysis"})]})}),e.jsxs(ls,{className:"p-4 md:p-6 pt-0",children:[e.jsx("div",{className:"mb-4",children:e.jsx(Ua,{value:o,onChange:l,ranges:tt})}),e.jsx(Wa,{data:Ha(o,{intraday:d.intradayToday,daily:d.pricesAll&&d.pricesAll.length?d.pricesAll:d.daily&&d.daily.length?d.daily:d.historical,all:d.historical}),height:"h-48 sm:h-56 md:h-64"})]})]}),e.jsxs(_e,{padding:"0",children:[e.jsxs(os,{className:"p-4 md:p-6",children:[e.jsx(Rs,{className:"text-xl",children:"Key Metrics"}),e.jsx(ks,{children:"Live fundamentals"})]}),e.jsx(ls,{className:"p-4 md:p-6 pt-0",children:e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3 text-sm",children:[e.jsxs("div",{children:[e.jsx($,{id:"price-summary-simple",data:P.stockPrice,children:e.jsx("span",{className:"text-muted-foreground",children:"Price"})}),e.jsx("div",{className:"font-medium",children:typeof d.price=="number"?`$${d.price.toFixed(2)}`:"—"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Market Cap"}),e.jsx("div",{className:"font-medium",children:Et(d.marketCap)})]}),e.jsxs("div",{className:"col-span-1 sm:col-span-2",children:[e.jsx($,{id:"fiftyTwoWeekRange-summary-1",data:P.fiftyTwoWeekRange,children:e.jsx("span",{className:"text-muted-foreground text-sm",children:"52-Week Range"})}),e.jsx("div",{className:"mt-1",children:d.price!=null&&d.fiftyTwoWeekLow!=null&&d.fiftyTwoWeekHigh!=null?e.jsx(Ya,{low:d.fiftyTwoWeekLow,high:d.fiftyTwoWeekHigh,current:d.price,size:"sm",variant:"default"}):e.jsx("span",{className:"text-muted-foreground",children:"—"})})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"EPS"}),e.jsx("div",{className:"font-medium",children:d.eps!=null?Wn(d.eps):"—"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Shares Out"}),e.jsx("div",{className:"font-medium",children:d.sharesOutstanding!=null?Hn(d.sharesOutstanding):"—"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Enterprise Value"}),e.jsx("div",{className:"font-medium",children:Et(d.enterpriseValue)})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"P/E"}),e.jsx("div",{className:"font-medium",children:d.ratios?.pe!=null?d.ratios.pe.toFixed(1):"—"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"P/B"}),e.jsx("div",{className:"font-medium",children:d.ratios?.pb!=null?d.ratios.pb.toFixed(1):"—"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"FCF Yield"}),e.jsx("div",{className:"font-medium",children:d.ratios?.fcfYield!=null?`${(d.ratios.fcfYield*100).toFixed(1)}%`:"—"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"D/E"}),e.jsx("div",{className:"font-medium",children:d.ratios?.de!=null?d.ratios.de.toFixed(2):"—"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"ROIC"}),e.jsx("div",{className:"font-medium",children:d.ratios?.roic!=null?`${(d.ratios.roic*100).toFixed(1)}%`:"—"})]})]})})]})]}),e.jsxs(_e,{padding:"0",children:[e.jsxs(os,{className:"p-4 md:p-6",children:[e.jsx(Rs,{children:"Content Available in Full Version"}),e.jsx(ks,{children:"Enable tabs feature flag to access all analysis sections"})]}),e.jsx(ls,{className:"p-4 md:p-6 pt-0",children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"This simplified view shows basic stock information. Enable the stock details tabs feature flag to access financial analysis, value analysis, comparative analysis, and stock reviews."})})]})]})}),children:e.jsxs(Es,{value:c,onValueChange:N=>{m(N);const B=`${a.pathname}?tab=${N}`;window.history.replaceState({},"",B)},className:"w-full",children:[e.jsx("div",{className:"-mx-4 px-4 md:mx-0 md:px-0",children:e.jsxs(Ps,{children:[e.jsx(Ts,{flag:"stock_details_summary_tab",value:"summary",mobileLabel:"Summary",children:"Summary"}),e.jsx(Ts,{flag:"stock_details_financials_tab",value:"financials",mobileLabel:"Financials",children:"Financials"}
2),e.jsx(Ts,{flag:"stock_details_fundamentals_tab",value:"fundamentals",mobileLabel:"Funds",children:"Fundamentals"}),e.jsx(Ts,{flag:"value_analysis",value:"value",mobileLabel:"Value",children:"Value Analysis"}),e.jsx(Ts,{flag:"comparative_analysis",value:"comparative",mobileLabel:"Compare",children:"Comparative Analysis"}),e.jsx(Ts,{flag:"bedrock_analysis_tab",value:"bedrock",mobileLabel:"Bedrock",children:"Bedrock Analysis"}),e.jsx(Ts,{flag:"stock_details_stock_review_tab",value:"stock-review",mobileLabel:"Review",children:"Stock Review"})]})}),e.jsx(re,{value:"summary",className:"mt-3 md:mt-4",children:e.jsx(Os,{flag:"stock_details_summary_tab",defaultValue:!0,children:e.jsxs("section",{className:"space-y-4",children:[e.jsx(W,{title:"Summary",subtitle:"Price trends and key metrics"}),e.jsxs("div",{className:"grid gap-3 md:gap-6 md:grid-cols-3",children:[e.jsxs(_e,{padding:"0",className:"md:col-span-2",children:[e.jsx(os,{className:"flex-col md:flex-row items-start md:items-center justify-between gap-2 md:gap-0 p-3 md:p-6",children:e.jsxs("div",{children:[e.jsx(Rs,{className:"text-lg md:text-xl",children:"Price Trend"}),e.jsx(ks,{className:"text-xs md:text-sm",children:"Trend across ranges"})]})}),e.jsxs(ls,{className:"p-3 md:p-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:justify-between sm:items-center gap-2 mb-2 md:mb-3",children:[e.jsx("div",{className:"text-xs sm:text-sm text-muted-foreground",children:"Select Range"}),e.jsx(Ua,{value:o,onChange:l,ranges:tt,className:"sm:w-auto"})]}),e.jsx(Wa,{data:Ha(o,{intraday:d.intradayToday,daily:d.pricesAll&&d.pricesAll.length?d.pricesAll:d.historical}),height:"h-48 sm:h-64 md:h-72"})]})]}),e.jsxs(_e,{padding:"0",children:[e.jsxs(os,{className:"p-3 md:p-6",children:[e.jsx(Rs,{className:"text-lg md:text-xl",children:"Key Metrics"}),e.jsx(ks,{className:"text-xs md:text-sm",children:"Live fundamentals"})]}),e.jsx(ls,{className:"p-3 md:p-6",children:e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2 md:gap-3",children:[e.jsx(O,{size:"sm",label:e.jsx($,{id:"price-summary",data:P.stockPrice,children:e.jsx("span",{children:"Price"})}),value:typeof d.price=="number"?`$${d.price.toFixed(2)}`:"—"}),e.jsx(O,{size:"sm",label:e.jsx($,{id:"marketCap",data:P.marketCap,children:e.jsx("span",{children:"Market Cap"})}),value:Et(d.marketCap)}),e.jsx("div",{className:"col-span-1 sm:col-span-2",children:e.jsx(O,{size:"sm",valueLayout:"block",label:e.jsx($,{id:"fiftyTwoWeekRange-summary-2",data:P.fiftyTwoWeekRange,children:e.jsx("span",{children:"52-Week Range"})}),value:d.price!=null&&d.fiftyTwoWeekLow!=null&&d.fiftyTwoWeekHigh!=null?e.jsx(Ya,{low:d.fiftyTwoWeekLow,high:d.fiftyTwoWeekHigh,current:d.price,size:"sm",variant:"default"}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"—"})})}),e.jsx(O,{size:"sm",label:e.jsx($,{id:"eps",data:P.eps,children:e.jsx("span",{children:"EPS"})}),value:d.eps!=null?Wn(d.eps):"—"}),e.jsx(O,{size:"sm",label:e.jsx($,{id:"sharesOutstanding",data:P.sharesOutstanding,children:e.jsx("span",{children:"Shares Out"})}),value:d.sharesOutstanding!=null?Hn(d.sharesOutstanding):"—"}),e.jsx(O,{size:"sm",label:e.jsx($,{id:"enterpriseValue",data:P.enterpriseValue,children:e.jsx("span",{children:"Enterprise Value"})}),value:Et(d.enterpriseValue)}),e.jsx(O,{size:"sm",label:e.jsx($,{id:"pe",data:P.pe,children:e.jsx("span",{children:"P/E"})}),value:d.ratios?.pe!=null?d.ratios.pe.toFixed(1):"—"}),e.jsx(O,{size:"sm",label:e.jsx($,{id:"pb",data:P.pb,children:e.jsx("span",{children:"P/B"})}),value:d.ratios?.pb!=null?d.ratios.pb.toFixed(1):"—"}),e.jsx(O,{size:"sm",label:e.jsx($,{id:"fcfYield",data:P.fcfYield,children:e.jsx("span",{children:"FCF Yield"})}),value:d.ratios?.fcfYield!=null?`${(d.ratios.fcfYield*100).toFixed(1)}%`:"—"}),e.jsx(O,{size:"sm",label:e.jsx($,{id:"debtToEquity",data:P.debtToEquity,children:e.jsx("span",{children:"D/E"})}),value:d.ratios?.de!=null?d.ratios.de.toFixed(2):"—"}),e.jsx(O,{size:"sm",label:e.jsx($,{id:"roic",data:P.roic,children:e.jsx("span",{children:"ROIC"})}),value:d.ratios?.roic!=null?`${(d.ratios.roic*100).toFixed(1)}%`:"—"})]})})]}),d.companyProfile&&e.jsxs(_e,{padding:"0",className:"col-span-full md:col-span-3",children:[e.jsxs(os,{className:"p-3 md:p-6",children:[e.jsx(Rs,{className:"text-lg md:text-xl",children:"Company Profile"}),e.jsx(ks,{className:"text-xs md:text-sm",children:"Business overview and ke
2y details"})]}),e.jsx(ls,{className:"p-3 md:p-6",children:e.jsxs("div",{className:"space-y-3 md:space-y-6",children:[d.companyProfile.description&&e.jsxs("div",{children:[e.jsx(gt,{as:"h4",size:{base:"1",md:"2"},weight:"semibold",color:"muted",className:"mb-1.5 md:mb-2",children:"Business Description"}),e.jsx(T,{size:{base:"1",md:"2"},className:"leading-relaxed",children:d.companyProfile.description})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3 md:gap-4",children:[d.companyProfile.ceo&&e.jsx(O,{size:"sm",label:"Chief Executive Officer",value:d.companyProfile.ceo}),d.companyProfile.employees!=null&&e.jsx(O,{size:"sm",label:"Employees",value:d.companyProfile.employees.toLocaleString()}),d.companyProfile.founded&&e.jsx(O,{size:"sm",label:"Founded / IPO Date",value:new Date(d.companyProfile.founded).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric"})}),d.companyProfile.headquarters&&e.jsx(O,{size:"sm",label:"Headquarters",value:d.companyProfile.headquarters}),d.companyProfile.website&&e.jsx(O,{size:"sm",label:"Website",value:e.jsx(oo,{external:!0,href:d.companyProfile.website.startsWith("http")?d.companyProfile.website:`https://${d.companyProfile.website}`,target:"_blank",children:d.companyProfile.website.replace(/^https?:\/\//,"")})}),d.companyProfile.phone&&e.jsx(O,{size:"sm",label:"Phone",value:d.companyProfile.phone}),d.sector&&e.jsx(O,{size:"sm",label:"Sector",value:d.sector}),d.industry&&e.jsx(O,{size:"sm",label:"Industry",value:d.industry}),d.exchange&&e.jsx(O,{size:"sm",label:"Exchange",value:d.exchange})]}),(d.companyProfile.isEtf||d.companyProfile.isFund||d.companyProfile.isAdr)&&e.jsxs("div",{children:[e.jsx(bs,{className:"mb-4"}),e.jsx(T,{size:"1",color:"muted",children:"Security Type"}),e.jsxs("div",{className:"flex gap-2 mt-1",children:[d.companyProfile.isEtf&&e.jsx(D,{tone:"info",variant:"secondary",children:"ETF"}),d.companyProfile.isFund&&e.jsx(D,{tone:"success",variant:"secondary",children:"Fund"}),d.companyProfile.isAdr&&e.jsx(D,{tone:"neutral",variant:"secondary",children:"ADR"})]})]})]})})]}),d.news&&d.news.length>0&&e.jsxs(_e,{padding:"0",className:"col-span-full md:col-span-3",children:[e.jsxs(os,{className:"p-3 md:p-6",children:[e.jsx(Rs,{className:"text-lg md:text-xl",children:"Latest News"}),e.jsx(ks,{className:"text-xs md:text-sm",children:"Recent developments and market updates"})]}),e.jsxs(ls,{className:"p-2.5 md:p-6",children:[e.jsx("div",{className:"space-y-1.5 md:space-y-3",children:(oe?d.news:d.news.slice(0,5)).map((N,B)=>e.jsx("a",{href:N.url,target:"_blank",rel:"noopener noreferrer",className:"group block border rounded-lg p-2 md:p-4 hover:bg-muted/20 hover:border-primary/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 transition-colors min-h-[64px] md:min-h-[80px]",children:e.jsxs("div",{className:"flex gap-2 md:gap-3",children:[N.image&&e.jsx("img",{src:N.image,alt:N.title,className:"w-12 h-12 sm:w-20 sm:h-20 object-cover rounded-md flex-shrink-0",onError:fe=>{fe.target.style.display="none"}}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h4",{className:"font-medium text-sm md:text-base leading-tight mb-1 md:mb-2 line-clamp-2 group-hover:text-primary transition-colors",children:N.title}),N.text&&e.jsxs("p",{className:"text-xs md:text-sm text-muted-foreground mb-1 md:mb-2 line-clamp-2",children:[N.text.substring(0,150),N.text.length>150&&"..."]}),e.jsxs(lo,{size:"sm",children:[e.jsx(Ga,{emphasized:!0,children:N.site}),e.jsx(Ga,{children:new Date(N.publishedDate).toLocaleDateString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})})]})]})]})},B))}),d.news.length>5&&e.jsx("div",{className:"mt-4 text-center",children:e.jsx(ye,{variant:"outline",size:"sm",onClick:()=>De(!oe),className:"min-h-[44px] px-6",children:oe?"Show Less":`Show More (${d.news.length-5} more)`})})]})]})]})]})})}),e.jsx(na,{value:"financials",flag:"stock_details_financials_tab",defaultValue:!0,children:e.jsxs("section",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center md:justify-between gap-3",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(W,{title:"Financials",subtitle:te==="annual"?"Annual comparison (last 10 years)":"Quarterly comparison (last 12 quarters)"}),i&&_&&e.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Cache Status:"}),e.jsx("span",{className:"text-xs font-semibold text-gain",children:"Active"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(Income: ",_.income?.length||0,", Balance: ",_.balance?.length||0,", Cash: ",_.cashflow?.length||0," items)"]})]})]}),e.jsx(co,{value:te,onChange:Cs,options:[{value:"annual",label:"Annual"},{value:"quarterly",label:"Quarterly"}],size:"sm","aria-label":"Period type",className:"max-w-[240px]"})]}),e.jsxs(Es,{defaultValue:"income",className:"w-full",children:[e.jsxs(Ps,{bleed:!0,children:[e.jsx(me,{value:"income",mobileLabel:"Income",children:"Income Statement"}),e.jsx(me,{value:"balance",mobileLabel:"Balance",children:"Balance Sheet"}),e.jsx(me,{value:"cashflow",mobileLabel:"Cash Flow",children:"Cash Flow"})]}),e.jsxs(re,{value:"income",className:"space-y-6",children:[e.jsx(Sd,{incomeData:te==="annual"?d.financials?.income||[]:ae("income"),periodType:te}),e.jsx(Cd,{incomeData:te==="annual"?d.financials?.income||[]:ae("income"),periodType:te}),e.jsx(Fd,{incomeData:te==="annual"?d.financials?.income||[]:ae("income"),periodType:te}),e.jsx(Kh,{incomeData:te==="annual"?d.financials?.income||[]:ae("income"),periodType:te,symbol:d.symbol,sector:d.sector,industry:d.industry,subIndustry:d.companyProfile?.subIndustry??void 0,balanceData:d.financials?.balance??[],
2cashflowData:d.financials?.cashflow??[]})]}),e.jsxs(re,{value:"balance",className:"space-y-6",children:[e.jsx(Xh,{balanceData:te==="annual"?d.financials?.balance||[]:ae("balance"),periodType:te}),e.jsx(Jh,{balanceData:te==="annual"?d.financials?.balance||[]:ae("balance"),periodType:te}),e.jsx(Zh,{balanceData:te==="annual"?d.financials?.balance||[]:ae("balance"),periodType:te}),e.jsx(ep,{balanceData:te==="annual"?d.financials?.balance||[]:ae("balance"),periodType:te})]}),e.jsxs(re,{value:"cashflow",className:"space-y-6",children:[e.jsx(sp,{cashflowData:te==="annual"?d.financials?.cashflow||[]:ae("cashflow"),periodType:te}),e.jsx(tp,{cashflowData:te==="annual"?d.financials?.cashflow||[]:ae("cashflow"),periodType:te}),e.jsx(ap,{cashflowData:te==="annual"?d.financials?.cashflow||[]:ae("cashflow"),periodType:te}),e.jsx(np,{cashflowData:te==="annual"?d.financials?.cashflow||[]:ae("cashflow"),periodType:te})]})]})]})}),e.jsx(na,{value:"fundamentals",flag:"stock_details_fundamentals_tab",defaultValue:!0,children:e.jsx(kc,{symbol:d.symbol,ratios:d.ratios,financials:d.financials,analysis:d.analysis,marketCap:d.marketCap,price:d.price,sharesOutstanding:d.sharesOutstanding,priceData:{high52w:d.fiftyTwoWeekHigh,low52w:d.fiftyTwoWeekLow,change1w:void 0,change1m:void 0,change1y:void 0},dividendData:{dividendYield:(()=>{const N=d.financials?.cashflow?.[0]?.dividendsPaid?Math.abs(d.financials.cashflow[0].dividendsPaid):0,B=d.sharesOutstanding||d.financials?.income?.[0]?.sharesDiluted;if(N>0&&B&&d.price)return N/B/d.price*100})(),annualDividend:d.financials?.cashflow?.[0]?.dividendsPaid?Math.abs(d.financials.cashflow[0].dividendsPaid):void 0,payoutRatio:(()=>{const N=d.financials?.income?.[0],B=d.financials?.cashflow?.[0];if(N?.netIncome&&B?.dividendsPaid)return Math.abs(B.dividendsPaid)/N.netIncome*100})(),dividendGrowth:(()=>{const N=d.financials?.cashflow||[];if(N.length>=2){const B=Math.abs(N[0]?.dividendsPaid||0),fe=Math.abs(N[1]?.dividendsPaid||0);if(B>0&&fe>0)return(B-fe)/fe*100}})()}})}),e.jsx(na,{value:"value",flag:"value_analysis",defaultValue:!0,children:e.jsxs("section",{className:"space-y-4",children:[e.jsx(W,{title:"Value Analysis",subtitle:"Deeper fundamentals and trends"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:kr}),e.jsxs(Es,{value:h,onValueChange:N=>{y(N);const B=`${a.pathname}?tab=${c}`,fe=N==="all"?B:`${B}&subtab=${N}`;window.history.replaceState({},"",fe)},className:"w-full",children:[e.jsx("div",{className:"-mx-4 px-4 md:mx-0 md:px-0",children:e.jsxs(Ps,{children:[e.jsx(me,{value:"all",children:"All"}),e.jsx(me,{value:"dcf",mobileLabel:"DCF",children:"DCF Analysis"}),e.jsx(me,{value:"fcf",mobileLabel:"FCF",children:"FCF vs Dividends & Buybacks"}),e.jsx(me,{value:"roic",mobileLabel:"ROIC",children:"ROIC Trend"}),e.jsx(me,{value:"revenue",mobileLabel:"Revenue",children:"Revenue & Net Income"}),e.jsx(me,{value:"shares",mobileLabel:"Shares",children:"Share Count Trend"}),e.jsx(me,{value:"health",mobileLabel:"Health",children:"Financial Health"}),e.jsx(me,{value:"moat",mobileLabel:"Moat",children:"Moat Analysis"}),k("10k_analysis",!1)&&e.jsx(me,{value:"10k",mobileLabel:"10-K",children:"10-K Analysis"})]})}),e.jsx(re,{value:"all",className:"mt-4",children:e.jsxs("div",{className:"space-y-10",children:[e.jsx(gd,{fcfData:at,payoutWindow:I,symbol:d.symbol,marketCap:d.marketCap}),e.jsx(dd,{roicData:Ds,symbol:d.symbol,sector:d.sector}),e.jsx(xd,{revenueData:d.analysis?.revenueNetIncome||[],symbol:d.symbol}),e.jsx(yd,{sharesData:d.analysis?.sharesTrend||[],symbol:d.symbol}),e.jsx(Nd,{balanceSheetData:d.financials?.balance||[],symbol:d.symbol}),e.jsx(wd,{roicData:d.analysis?.roicTrend,cashflowData:d.financials?.cashflow,marketCap:d.marketCap,ratios:d.ratios,symbol:d.symbol,name:d.name}),e.jsx(Uo,{symbol:d.symbol,fiscalYear:new Date().getFullYear()})]})}),e.jsx(re,{value:"dcf",className:"space-y-6",children:e.jsx(Va,{featureName:"dcf_calculator",fallback:e.jsx(Yo,{}),children:e.jsx(ri,{stockData:d,context:"analysis",showStockInfo:!1})})}),e.jsx(re,{value:"fcf",className:"mt-4",children:e.jsx(op,{fcfData:at,fcfChartData:Sr,symbol:d.symbol,payoutWindow:I,onPayoutWindowChange:ee})}),e.jsx(re,{value:"roic",className:"mt-4",children:e.jsx(dp,{roicData:Ds,roicChartData:Cr,symbol:d.symbol,sector:d.sector,onRoicWindowChange:A})}),e.jsx(re,{value:"revenue",children:e.jsx(up,{revenueData:d.analysis?.revenueNetIncome||[],symbol:d.symbol})}),e.jsx(re,{value:"shares",children:e.jsx(mp,{sharesData:Ba,sharesChartData:Fr,symbol:d.symbol,shareCountTimeRange:K,onShareCountTimeRangeChange:ne})}),e.jsx(re,{value:"health",className:"mt-4",children:e.jsx(pp,{balance:d.financials?.balance||[],liquidityChartData:Ir,symbol:d.symbol,healthTimeRange:je,onHealthTimeRangeChange:se})}),e.jsx(re,{value:"moat",className:"mt-4",children:e.jsx(hp,{income:d.financials?.income||[],balance:d.financials?.balance||[],ratios:d.ratios||{},name:d.name})}),k("10k_analysis",!1)&&e.jsx(re,{value:"10k",className:"mt-4",children:e.jsx("div",{className:"space-y-6",children:e.jsx(Va,{featureName:"10k_analysis",fallback:e.jsx(xl,{}),children:e.jsx(ed,{symbol:d.symbol,defaultFiscalYear:M?parseInt(M):void 0})})})})]})]})}),e.jsx(re,{value:"comparative",className:"mt-4",children:e.jsx(Os,{flag:"comparative_analysis",defaultValue:!0,children:e.jsxs("section",{className:"space-y-4",children:[e.jsx(W,{title:"Comparative Analysis",subtitle:"Historical trends and performance comparison"}),e.jsxs(Es,{value:j,onValueChange:N=>{u(N);const B=`${a.pathname}?tab=${c}`,fe=N==="all"?B:`${B}&subtab=${N}`;window.history.replaceState({},"",fe)},className:"w-full",children:[e.jsx("div",{className:"-mx-4 px-4 md:mx-0 md:px-0",children:e.jsxs(Ps,{children:[e.jsx(me,{value:"all",children:"All"}),e.jsx(me,{value:"valuation",mobileLabel:"Valuation",children:"Valuation"}),e.jsx(me,{value:"earnings",mobileLabel:"Earnings",children:"Earnings"}),e.jsx(me,{value:"performance",mobileLabel:"Performance",children:"Performance"}),e.jsx(me,{value:"financial-health",mobileLabel:"Health",children:"Financial Health"}),e.jsx(me,{value:"moat",mobileLabel:"Moat",children:"Economic Moat"})]})}),e.jsx(re,{value:"all",className:"mt-4",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(mn,{symbol:d.symbol,n
2ame:d.name,marketCap:d.marketCap,ratios:d.ratios,financials:d.financials,useManualPeers:!0,manualPeers:qe}),e.jsx(Xa,{companyData:{symbol:d.symbol,name:d.name,price:d.price||0,marketCap:d.marketCap||0,pe:d.ratios?.pe||void 0,ps:(()=>{const N=d.financials?.income?.[0];return N?.revenue&&d.marketCap?d.marketCap/N.revenue:void 0})(),pb:d.ratios?.pb||void 0,evEbitda:(()=>{const B=d.financials?.income?.[0]?.normalizedEbitda;return B&&d.marketCap&&B>0?d.marketCap/B:void 0})(),earnings:d.financials?.income?.[0]?.netIncome||void 0,revenue:d.financials?.income?.[0]?.revenue||void 0,sector:d.sector||"Consumer Staples"},useManualPeers:!0,manualPeers:qe}),e.jsx(Ja,{companyData:{symbol:d.symbol,name:d.name,financials:d.financials?.income||[],sector:d.sector},useManualPeers:!0,manualPeers:qe}),e.jsx(Za,{companyData:{symbol:d.symbol,name:d.name,sector:d.sector,marketCap:d.marketCap,financials:d.financials,financialsQ:d.financialsQ},useManualPeers:!0,manualPeers:qe}),e.jsx(en,{balanceData:d.financials?.balance||[],cashflowData:d.financials?.cashflow||[],companySymbol:d.symbol||"Unknown",timeframe:"Max",useManualPeers:!0,manualPeers:qe})]})}),e.jsx(re,{value:"valuation",className:"mt-4",children:e.jsx(Xa,{companyData:{symbol:d.symbol,name:d.name,price:d.price||0,marketCap:d.marketCap||0,pe:d.ratios?.pe||void 0,ps:(()=>{const N=d.financials?.income?.[0];return N?.revenue&&d.marketCap?d.marketCap/N.revenue:void 0})(),pb:d.ratios?.pb||void 0,evEbitda:(()=>{const B=d.financials?.income?.[0]?.normalizedEbitda;return B&&d.marketCap&&B>0?d.marketCap/B:void 0})(),earnings:d.financials?.income?.[0]?.netIncome||void 0,revenue:d.financials?.income?.[0]?.revenue||void 0,sector:d.sector||"Consumer Staples"},useManualPeers:!0,manualPeers:qe})}),e.jsx(re,{value:"earnings",className:"mt-4",children:e.jsx("div",{className:"space-y-6",children:e.jsx(Ja,{companyData:{symbol:d.symbol,name:d.name,financials:d.financials?.income||[],sector:d.sector},useManualPeers:!0,manualPeers:qe})})}),e.jsx(re,{value:"performance",className:"mt-4",children:e.jsx("div",{className:"space-y-6",children:e.jsx(Za,{companyData:{symbol:d.symbol,name:d.name,sector:d.sector,marketCap:d.marketCap,financials:d.financials,financialsQ:d.financialsQ},useManualPeers:!0,manualPeers:qe})})}),e.jsx(re,{value:"financial-health",className:"mt-4",children:e.jsx(en,{balanceData:d.financials?.balance||[],cashflowData:d.financials?.cashflow||[],companySymbol:d.symbol||"Unknown",timeframe:"Max",useManualPeers:!0,manualPeers:qe})}),e.jsx(re,{value:"moat",className:"mt-4",children:e.jsx(mn,{symbol:d.symbol,name:d.name,marketCap:d.marketCap,ratios:d.ratios,financials:d.financials,useManualPeers:!0,manualPeers:qe})})]})]})})}),e.jsx(re,{value:"bedrock",className:"mt-4",children:e.jsx(Os,{flag:"bedrock_analysis_tab",defaultValue:!0,children:e.jsx("section",{className:"grid gap-6",children:e.jsx(mc,{symbol:d.symbol,subTab:f,onSubTabChange:N=>{g(N);const B=`${a.pathname}?tab=${c}`,fe=N==="overview"?B:`${B}&subtab=${N}`;window.history.replaceState({},"",fe)}})})})}),e.jsx(re,{value:"stock-review",className:"mt-4",children:e.jsx(Os,{flag:"stock_details_stock_review_tab",defaultValue:!0,children:e.jsx("section",{className:"grid gap-6",children:e.jsx(zc,{symbol:d.symbol,currentPrice:d.price||0})})})})]})}),e.jsx(Os,{flag:"ai_chat",defaultValue:!1,children:e.jsx(vc,{symbol:d.symbol,name:d.name})})]})]})}export{cg as default};

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.