PageSourceSearch

https://aidealer360.com/assets/Wholesale360-DmjqF18X.js

js aidealer360.com collected 2026-09-24 12:37:40 UTC 262,085 bytes, 353 lines download raw bytes

1import{j as e}from"./ui-vendor-B12AOeKi.js";import{r as v,g as Oa,d as Ua}from"./react-vendor-DZt7wVAJ.js";import{ak as Ga,a as Us,u as Pr,B as ce,aq as Ba,aC as za,aP as Va,g as Pe,ac as ra,ai as Zt,aH as qa,aI as Wa,aJ as Ya,p as ys,q as $e,y as Ae,P as es,s as ne,v as At,w as Mt,n as Ha,I as Ct,D as Gs,b as Bs,c as zs,d as Vs,e as xr,a8 as pr,ap as Lr,L as Rs,R as Ka,bm as aa,Y as Ks,T as Or,E as lr,a3 as $s,F as As,by as Ze,C as Qa}from"./index-CUOC2qQu.js";import{T as na,b as la,c as ht,a as ut}from"./tabs-Cesl5pOW.js";import{S as Cr,f as Ja,a as $r,b as Ar,c as Mr}from"./sheet-D40jqZ33.js";import{u as ia}from"./useResponsive-DgP2iP9p.js";import{L as Xa}from"./layout-grid-DwP6H9SU.js";import{b as ke,c as Le,T as q,d as h,e as Ce,a as c}from"./table-CslgGg9T.js";import{A as Za}from"./AppLogo-DHfXijyC.js";import{S as It,a as Ot,b as Ut,c as Gt,d as Te}from"./select-B8RrBf7t.js";import{b as en,c as Bt,a as tn,f as Je,d as xe,e as is,v as os,g as sn,m as rn,h as Es,i as an}from"./reportsHelpers-CooLZYCr.js";import{P as Is}from"./printer-BNAVOmS6.js";import{R as gr,B as nn,j as fr,X as vr,Y as Os,T as jr,h as _r,i as ir,k as oa,e as ar,S as ln,l as Ur}from"./charts-vendor-B6q1L48j.js";import{R as on}from"./ReportRunnerButton-B1MeDF2q.js";import{A as cn}from"./index-BrL6o1HN.js";import{r as Gr,u as dn}from"./xlsx-BQptaUDQ.js";import{F as hn}from"./file-spreadsheet-BXdlMI0T.js";import{U as Er}from"./upload-krIPvW5L.js";import{C as ca}from"./circle-check-CwVqBPQR.js";import{T as un}from"./textarea-BsyLd3-L.js";import{S as mn}from"./save-CgF44BVm.js";import{P as Br}from"./pencil-Clt1PLkW.js";import{H as xn}from"./history-BxaZ1doz.js";import{F as pn}from"./filter-DqCshXAe.js";import{T as Wt}from"./trending-down-Dtf-_mlH.js";import"./supabase-vendor-dOy44Gxq.js";import"./animation-vendor-BAVy02gd.js";import"./inProcessAgeColor-8VnRak4A.js";/**
2 * @license lucide-react v0.462.0 - ISC
3 *
4 * This source code is licensed under the ISC license.
5 * See the LICENSE file in the root directory of this source tree.
6 */const gn=Ga("Rows3",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M21 9H3",key:"1338ky"}],["path",{d:"M21 15H3",key:"9uk58r"}]]),Jt=t=>{if(t==null||t==="")return"—";const s=Number(t);return Number.isFinite(s)?s.toLocaleString("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}):"—"},zr=t=>{if(t==null||t==="")return"—";const s=Number(t);return Number.isFinite(s)?s.toLocaleString("en-US"):String(t)},wt=t=>t==null||t===""?"—":String(t).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),fn=t=>[t.year,t.make,t.model,t.trim].filter(Boolean).join(" ")||t.vin||"Wholesale Lot";function vn(t,s){const a=fn(t),r=t.sale_price,n=s==null?"":s>=0?"pos":"neg",o=new Date().toLocaleString("en-US",{dateStyle:"medium",timeStyle:"short"}),i=(f,j,y={})=>`
7    <tr>
8      <td class="lbl">${wt(f)}</td>
9      <td class="val ${y.mono?"mono":""} ${y.cls??""}">${j}</td>
10    </tr>`,m=`<!DOCTYPE html>
11<html lang="en">
12<head>
13<meta charset="UTF-8" />
14<title>${wt(a)} — intel360 Lot Detail</title>
15<style>
16  @page { size: letter; margin: 0.5in; }
17  @media print { body { -webkit-print-color-adjust: exact; print-color-adjust: exact; } .no-print { display: none !important; } }
18  * { box-sizing: border-box; }
19  body {
20    margin: 0; padding: 24px;
21    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
22    font-size: 12px; color: #1a1a1a; background: #fff;
23  }
24  .header { border-bottom: 2px solid #1C5ED6; padding-bottom: 12px; margin-bottom: 18px; display: flex; justify-content: space-between; align-items: flex-end; }
25  .header h1 { margin: 0; font-size: 20px; color: #0B1F3A; }
26  .header .sub { font-size: 11px; color: #666; margin-top: 4px; }
27  .meta { font-size: 11px; color: #666; text-align: right; }
28  .section { margin-bottom: 18px; break-inside: avoid; }
29  .section h2 {
30    font-size: 11px; text-transform: uppercase; letter-spacing: 0.08em;
31    color: #1C5ED6; margin: 0 0 6px; padding-bottom: 4px; border-bottom: 1px solid #d6e0ee;
32  }
33  table { width: 100%; border-collapse: collapse; }
34  td { padding: 6px 8px; vertical-align: top; border-bottom: 1px solid #eef1f5; }
35  td.lbl { color: #555; width: 45%; }
36  td.val { text-align: right; font-weight: 500; }
37  td.val.mono { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; }
38  .pos { color: #138a4a; font-weight: 600; }
39  .neg { color: #c0392b; font-weight: 600; }
40  .amber { color: #b7791f; font-weight: 600; }
41  .footer { margin-top: 24px; padding-top: 10px; border-top: 1px solid #ddd; font-size: 10px; color: #888; text-align: center; }
42  .toolbar { margin-bottom: 14px; }
43  .toolbar button { padding: 8px 14px; font-size: 12px; cursor: pointer; background: #1C5ED6; color: #fff; border: 0; border-radius: 6px; }
44</style>
45</head>
46<body>
47  <div class="toolbar no-print">
48    <button onclick="window.print()">Print</button>
49  </div>
50  <div class="header">
51    <div>
52      <h1>${wt(a)}</h1>
53      <div class="sub">intel360 — Lot Detail Report</div>
54    </div>
55    <div class="meta">Generated: ${wt(o)}</div>
56  </div>
57
58  <div class="section">
59    <h2>Selling Dealer</h2>
60    <table>
61      ${i("Dealer Code",wt(t.dealer_code),{mono:!0})}
62      ${i("Dealer Name",wt(t.dealer_name))}
63    </table>
64  </div>
65
66  <div class="section">
67    <h2>Vehicle</h2>
68    <table>
69      ${i("VIN",wt(t.vin),{mono:!0})}
70      ${i("Stock #",wt(t.stock_number),{mono:!0})}
71      ${i("Year / Make / Model",wt(a))}
72      ${i("Color",wt(t.color))}
73      ${i("Miles",zr(t.miles))}
74      ${i("Title State",wt(t.title_state))}
75    </table>
76  </div>
77
78  <div class="section">
79    <h2>Pricing</h2>
80    <table>
81      ${i("Floor Price",Jt(t.floor_price))}
82      ${i("Sale Price",r==null?'<span class="amber">NO SALE</span>':Jt(r))}
83      ${i("Auction Fee",Jt(t.auction_fee))}
84      ${i("Net Check to Dealer",Jt(t.net_check_to_dealer))}
85      ${i("Profit / Loss",Jt(s),{cls:n})}
86      ${i("Local CV",Jt(t.local_cv))}
87      ${i("National CV",Jt(t.natl_cv))}
88      ${i("Guidebook",Jt(t.guidebook))}
89      ${i("Highest Bid",Jt(t.highest_bid_amount))}
90    </table>
91  </div>
92
93  <div class="section">
94    <h2>Condition</h2>
95    <table>
96      ${i("Codes",wt(t.condition_codes))}
97      ${i("CR Comments",wt(t.cr_comments))}
98      ${i("Appraiser",wt(t.appraiser))}
99      ${i("Days in Inventory",zr(t.days_in_inventory))}
100    </table>
101  </div>
102
103  <div class="footer">AI Dealer 360 — intel360 • ${wt(o)}</div>
104
105  <script>
106    window.addEventListener("load", function () { setTimeout(function () { window.print(); }, 250); });
107  <\/script>
108</body>
109</html>`,g=window.open("","_blank","width=900,height=1100");if(!g){alert("Please allow pop-ups to print this report.");return}g.document.open(),g.document.write(m),g.document.close()}const Lt=t=>{if(t==null||t==="")return"—";const s=Number(t);
109return Number.isFinite(s)?s.toLocaleString("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}):"—"},jn=t=>{if(t==null||t==="")return"—";const s=Number(t);return Number.isFinite(s)?s.toLocaleString("en-US"):String(t)},Yt=t=>t==null||t===""?"—":String(t).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),_n=t=>[t.year,t.make,t.model,t.trim].filter(Boolean).join(" ")||t.vin||"—";function bn(t,s,a,r){const n=new Date().toLocaleString("en-US",{dateStyle:"medium",timeStyle:"short"}),o=t.lots_count?t.sold/t.lots_count*100:0,i=r&&r.incomplete?`<div class="warn">Incomplete import — ${t.lots_count} of ${r.reportListed??t.lots_count} vehicles read${r.soldGap>0?`; auction report shows ${r.reportSold} sold, this report shows ${t.sold}`:""}. Figures below are lower than the auction report.</div>`:"";let m=0,g=0,f=0,j=0,y=0,k=!1,C=!1;for(const L of s){m+=Number(L.floor_price)||0,L.sale_price!=null&&(g+=Number(L.sale_price)||0,k=!0),f+=Number(L.auction_fee)||0,j+=Number(L.net_check_to_dealer)||0;const _=a(L);_!=null&&(y+=_,C=!0)}const x=s.map(L=>{const _=a(L),H=_==null?"muted":_>=0?"pos":"neg",F=L.sale_price!=null,p=[];return L.as_is&&p.push('<span class="flag">AS IS</span>'),L.structural_damage&&p.push('<span class="flag red">STRUCT</span>'),L.over_200k&&p.push('<span class="flag">200K+</span>'),L.over_100k&&!L.over_200k&&p.push('<span class="flag">100K+</span>'),L.canadian_vehicle&&p.push('<span class="flag">CDN</span>'),`
110      <tr>
111        <td class="mono">${Yt(L.lot_number)}</td>
112        <td>
113          <div>${Yt(_n(L))}</div>
114          <div class="sub">${Yt([L.color,L.title_state].filter(Boolean).join(" • ")||"")}</div>
115        </td>
116        <td class="mono">${Yt(L.vin)}</td>
117        <td class="r">${jn(L.miles)}</td>
118        <td class="r">${Lt(L.floor_price)}</td>
119        <td class="r">${F?Lt(L.sale_price):'<span class="amber">—</span>'}</td>
120        <td class="r">${Lt(L.auction_fee)}</td>
121        <td class="r">${Lt(L.net_check_to_dealer)}</td>
122        <td class="r ${H}">${Lt(_)}</td>
123        <td>${Yt(L.appraiser)}</td>
124        <td>${F?'<span class="badge sold">SOLD</span>':'<span class="badge nosale">NO SALE</span>'}</td>
125        <td>${p.join(" ")||"—"}</td>
126      </tr>`}).join(""),A=t.profit_loss>=0?"pos":"neg",S=t.sold>0?t.profit_loss/t.sold:0,X=S>=0?"pos":"neg",N=`<!DOCTYPE html>
127<html lang="en">
128<head>
129<meta charset="UTF-8" />
130<title>${Yt(t.dealer_code)} — intel360 Store Report</title>
131<style>
132  @page { size: letter landscape; margin: 0.4in; }
133  @media print { body { -webkit-print-color-adjust: exact; print-color-adjust: exact; } .no-print { display: none !important; } }
134  * { box-sizing: border-box; }
135  body { margin: 0; padding: 18px; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; font-size: 11px; color: #1a1a1a; background: #fff; }
136  .toolbar { margin-bottom: 12px; }
137  .toolbar button { padding: 8px 14px; font-size: 12px; cursor: pointer; background: #1C5ED6; color: #fff; border: 0; border-radius: 6px; }
138  .header { border-bottom: 2px solid #1C5ED6; padding-bottom: 10px; margin-bottom: 14px; display: flex; justify-content: space-between; align-items: flex-end; }
139  .header h1 { margin: 0; font-size: 18px; color: #0B1F3A; }
140  .header .sub { font-size: 11px; color: #555; margin-top: 4px; }
141  .header .meta { font-size: 10px; color: #666; text-align: right; }
142  .kpis { display: grid; grid-template-columns: repeat(8, 1fr); gap: 8px; margin-bottom: 14px; break-inside: avoid; }
143  .kpi { border: 1px solid #d6e0ee; border-radius: 6px; padding: 8px 10px; background: #f7faff; }
144  .kpi .label { font-size: 9px; text-transform: uppercase; letter-spacing: 0.08em; color: #1C5ED6; margin-bottom: 4px; }
145  .kpi .value { font-size: 15px; font-weight: 700; color: #0B1F3A; }
146  .kpi .value.pos { color: #138a4a; }
147  .kpi .value.neg { color: #c0392b; }
148  table { width: 100%; border-collapse: collapse; font-size: 10px; }
149  thead { display: table-header-group; }
150  th { background: #1C5ED6; color: #fff; text-align: left; padding: 6px 6px; font-weight: 600; font-size: 10px; }
151  th.r, td.r { text-align: right; }
152  td { padding: 6px 6px; border-bottom: 1px solid #e8edf3; vertical-align: top; }
153  tbody tr:nth-child(even) { background: #fafbfd; }
154  td.mono { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; }
155  .sub { color: #777; font-size: 9px; }
156  .pos { color: #138a4a; font-weight: 600; }
157  .neg { color: #c0392b; font-weight: 600; }
158  .muted { color: #999; }
159  .amber { color: #b7791f; }
160  .badge { display: inline-block; padding: 2px 6px; border-radius: 10px; font-size: 9px; font-weight: 700; }
161  .badge.sold { background: #d4f4e0; color: #138a4a; }
162  .badge.nosale { background: #fff1d6; color: #b7791f; }
163  .flag { display: inline-block; padding: 1px 5px; border: 1px solid #cfd6e0; border-radius: 8px; font-size: 9px; color: #4a5568; margin-right: 3px; }
164  .flag.red { border-color: #f5c2c0; color: #c0392b; background: #fdecec; }
165  tfoot td { border-top: 2px solid #0B1F3A; font-weight: 700; background: #f0f4fa; }
166  .footer { margin-top: 18px; padding-top: 8px; border-top: 1px solid #ddd; font-size: 9px; color: #888; text-align: center; }
167  .warn { border: 1px solid #b45309; background: #fef3c7; color: #7c2d12; padding: 6px 10px; border-radius: 6px; font-size: 11px; font-weight: 600; margin-bottom: 10px; }
168</style>
169</head>
170<body>
171  <div class="toolbar no-print"><button onclick="window.print()">Print</button></div>
172  <div class="header">
173    <div>
174      <h1>${Yt(t.dealer_code)} — ${Yt(t.dealer_name||"—")}</h1>
175      <div class="sub">intel360 — Store Performance Report</div>
176    </div>
177    <div class="meta">Generated: ${Yt(n)}</div>
178  </div>
179
180  ${i}
181
182  <div class="kpis">
183    <div class="kpi"><div class="label">Lots</div><div class="value">${t.lots_count}</div></div>
184    <div class="kpi"><div class="label">Sold</div><div class="value">${t.sold}</div></div>
185    <div class="kpi"><div class="label">No Sale</div><div class="value">${t.no_sale}</div></div>
186    <div class="kpi"><div class="label">Sell-through</div><div class="value">${o.toFixed(1)}%</div></div>
187    <div class="kpi"><div class="label">
187Total Sale</div><div class="value">${Lt(t.total_sale)}</div></div>
188    <div class="kpi"><div class="label">Total Net</div><div class="value">${Lt(t.total_net)}</div></div>
189    <div class="kpi"><div class="label">Profit / Loss</div><div class="value ${A}">${Lt(t.profit_loss)}</div></div>
190    <div class="kpi"><div class="label">Avg P/L / Vehicle</div><div class="value ${X}">${t.sold>0?Lt(S):"—"}</div></div>
191  </div>
192
193  <table>
194    <thead>
195      <tr>
196        <th>Lot</th><th>Vehicle</th><th>VIN</th>
197        <th class="r">Miles</th><th class="r">Floor</th><th class="r">Sale</th>
198        <th class="r">Fee</th><th class="r">Net Check</th><th class="r">P/L</th>
199        <th>Appraiser</th><th>Status</th><th>Flags</th>
200      </tr>
201    </thead>
202    <tbody>${x}</tbody>
203    <tfoot>
204      <tr>
205        <td colspan="4" class="r">Totals (${s.length} lots)</td>
206        <td class="r">${Lt(m)}</td>
207        <td class="r">${k?Lt(g):"—"}</td>
208        <td class="r">${Lt(f)}</td>
209        <td class="r">${Lt(j)}</td>
210        <td class="r ${y>=0?"pos":"neg"}">${C?Lt(y):"—"}</td>
211        <td colspan="3"></td>
212      </tr>
213    </tfoot>
214  </table>
215
216  <div class="footer">AI Dealer 360 — intel360 • ${Yt(n)}</div>
217  <script>window.addEventListener("load", function () { setTimeout(function () { window.print(); }, 300); });<\/script>
218</body>
219</html>`,M=window.open("","_blank","width=1200,height=900");if(!M){alert("Please allow pop-ups to print this report.");return}M.document.open(),M.document.write(N),M.document.close()}async function Nn(t){const s=await t.arrayBuffer(),a=await crypto.subtle.digest("SHA-256",s);return Array.from(new Uint8Array(a)).map(r=>r.toString(16).padStart(2,"0")).join("")}const da=v.createContext(void 0),ha=t=>`w360:scope:${t??"anon"}`;function wn(t){try{const s=localStorage.getItem(ha(t));if(!s)return null;const a=JSON.parse(s);return Array.isArray(a==null?void 0:a.ids)?{ids:a.ids.filter(r=>typeof r=="string"),mode:a.mode==="byStore"?"byStore":"combined",all:a.all===!0}:null}catch{return null}}function yn({children:t}){const{userDealerships:s,selectedDealership:a,loading:r}=Us(),{currentUser:n}=Pr(),o=(n==null?void 0:n.id)??null,i=v.useMemo(()=>(s??[]).map(u=>({id:u.id,name:u.name,code:u.code})).sort((u,w)=>u.name.localeCompare(w.name)),[s]),m=v.useMemo(()=>new Set(i.map(u=>u.id)),[i]),[g,f]=v.useState([]),[j,y]=v.useState("combined"),[k,C]=v.useState(!1),[x,A]=v.useState(!1);v.useEffect(()=>{if(r||i.length===0)return;const u=x?null:wn(o),w=((u==null?void 0:u.ids)??[]).filter(T=>m.has(T));f(T=>{const $=T.filter(B=>m.has(B));return x?$.length>0?$.length===T.length?T:$:[a&&m.has(a.id)?a.id:i[0].id]:u!=null&&u.all?i.map(_e=>_e.id):w.length>0?w:[a&&m.has(a.id)?a.id:i[0].id]}),x||(u!=null&&u.mode&&y(u.mode),u!=null&&u.all&&C(!0),A(!0))},[r,i,m,a,o,x]),v.useEffect(()=>{!k||i.length===0||f(u=>u.length===i.length?u:i.map(w=>w.id))},[k,i]);const S=v.useCallback((u,w,T)=>{try{localStorage.setItem(ha(o),JSON.stringify({ids:u,mode:w,all:T}))}catch{}},[o]),X=v.useCallback(u=>{const w=Array.from(new Set(u.filter(W=>m.has(W))));if(w.length===0)return;const T=w.length===i.length&&i.length>1;C(T),f(w);const $=w.length===1?"combined":j;$!==j&&y($),S(w,$,T)},[m,i.length,S,j]),N=v.useCallback(()=>{if(i.length===0)return;const u=i.map(w=>w.id);C(i.length>1),f(u),S(u,j,i.length>1)},[i,S,j]),M=v.useCallback(u=>{y(u),S(g,u,k)},[S,g,k]),L=v.useMemo(()=>new Map(i.map(u=>[u.id,u.name])),[i]),_=v.useMemo(()=>i.filter(u=>g.includes(u.id)),[i,g]),H=i.length>1&&g.length===i.length,F=v.useMemo(()=>_.length===0?"No store selected":H?"All My Stores":_.length===1?_[0].name:_.length===2?_.map(u=>u.name).join(" + "):`${_.length} selected stores`,[_,H]),p={authorized:i,selectedIds:g,selectedDealerships:_,canSelect:i.length>1,isMultiStore:g.length>1,isAllAuthorized:H,viewMode:g.length>1?j:"combined",setViewMode:M,setSelectedIds:X,selectAllAuthorized:N,scopeLabel:F,storeName:u=>u?L.get(u)??"Unlinked seller":"Unlinked seller",loading:r||g.length===0};return e.jsx(da.Provider,{value:p,children:t})}function br(){const t=v.useContext(da);if(!t)throw new Error("useW360Scope must be used within a W360ScopeProvider");return t}function Sn(){const{authorized:t,selectedIds:s,setSelectedIds:a,selectAllAuthorized:r,canSelect:n,isMultiStore:o,isAllAuthorized:i,scopeLabel:m,viewM
219ode:g,setViewMode:f}=br(),{isMobile:j}=ia(),[y,k]=v.useState(!1),[C,x]=v.useState(s);if(v.useEffect(()=>{y&&x(s)},[y,s]),!n)return null;const A=M=>x(L=>L.includes(M)?L.filter(_=>_!==M):[...L,M]),S=()=>{C.length!==0&&(a(C),k(!1))},X=e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"My authorized stores"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(ce,{variant:"ghost",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>x(t.map(M=>M.id)),children:"Select all"}),e.jsx(ce,{variant:"ghost",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>x([]),disabled:C.length===0,children:"Clear"})]})]}),e.jsx("div",{className:"max-h-72 space-y-1 overflow-y-auto pr-1",children:t.map(M=>{const L=C.includes(M.id);return e.jsxs("label",{className:"flex cursor-pointer items-center gap-3 rounded-md px-2 py-2 hover:bg-white/[0.04]",children:[e.jsx(Ba,{checked:L,onCheckedChange:()=>A(M.id)}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block truncate text-sm text-foreground",children:M.name}),e.jsx("span",{className:"block text-xs text-muted-foreground",children:M.code})]}),L&&e.jsx(za,{className:"h-4 w-4 text-sky-300"})]},M.id)})}),C.length===0&&e.jsx("p",{className:"text-xs text-amber-300",children:"Pick at least one store — Wholesale360 always needs a scope."}),e.jsxs("div",{className:"flex items-center justify-between gap-2 border-t border-white/10 pt-3",children:[e.jsx(ce,{variant:"outline",size:"sm",onClick:()=>{r(),k(!1)},children:"All My Stores"}),e.jsx(ce,{size:"sm",onClick:S,disabled:C.length===0,children:"Apply"})]})]}),N=e.jsxs(ce,{variant:"outline",className:"max-w-[280px] justify-start gap-2",children:[e.jsx(Va,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:m}),i&&e.jsx(Pe,{variant:"outline",className:"ml-1 shrink-0 text-[10px]",children:t.length}),e.jsx(ra,{className:"ml-auto h-4 w-4 shrink-0 opacity-60"})]});return e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(Zt,{componentId:"wholesale360:dropdown-store-scope",appName:"Wholesale 360",componentType:"dropdown",componentLabel:"Wholesale360 store scope",children:j?e.jsxs(Cr,{open:y,onOpenChange:k,children:[e.jsx(Ja,{asChild:!0,children:N}),e.jsxs($r,{side:"bottom",className:"max-h-[85vh] overflow-y-auto",children:[e.jsx(Ar,{className:"text-left",children:e.jsx(Mr,{children:"Store scope"})}),e.jsx("div",{className:"mt-4",children:X})]})]}):e.jsxs(qa,{open:y,onOpenChange:k,children:[e.jsx(Wa,{asChild:!0,children:N}),e.jsx(Ya,{align:"start",className:"w-80 p-3",children:X})]})}),o&&e.jsxs("div",{className:"flex items-center rounded-md border border-white/10 p-0.5",children:[e.jsx(Zt,{componentId:"wholesale360:button-scope-combined",appName:"Wholesale 360",componentType:"button",componentLabel:"Combined view",children:e.jsxs(ce,{variant:g==="combined"?"default":"ghost",size:"sm",className:"h-7",onClick:()=>f("combined"),children:[e.jsx(Xa,{className:"mr-1.5 h-3.5 w-3.5"}),"Combined"]})}),e.jsx(Zt,{componentId:"wholesale360:button-scope-by-store",appName:"Wholesale 360",componentType:"button",componentLabel:"By store view",children:e.jsxs(ce,{variant:g==="byStore"?"default":"ghost",size:"sm",className:"h-7",onClick:()=>f("byStore"),children:[e.jsx(gn,{className:"mr-1.5 h-3.5 w-3.5"}),"By Store"]})})]})]})}var ua={exports:{}};/* @license
220Papa Parse
221v5.5.3
222https://github.com/mholt/PapaParse
223License: MIT
224*/(function(t,s){((a,r)=>{t.exports=r()})(Ua,function a(){var r=typeof self<"u"?self:typeof window<"u"?window:r!==void 0?r:{},n,o=!r.document&&!!r.postMessage,i=r.IS_PAPA_WORKER||!1,m={},g=0,f={};function j(p){this._handle=null,this._finished=!1,this._completed=!1,this._halted=!1,this._input=null,this._baseIndex=0,this._partialLine="",this._rowCount=0,this._start=0,this._nextChunk=null,this.isFirstChunk=!0,this._completeResults={data:[],errors:[],meta:{}},(function(u){var w=_(u);w.chunkSize=parseInt(w.chunkSize),u.step||u.chunk||(w.chunkSize=null),this._handle=new A(w),(this._handle.streamer=this)._config=w}).call(this,p),this.parseChunk=function(u,w){var T=parseInt(this._config.skipFirstNLines)||0;if(this.isFirstChunk&&0<T){let W=this._config.newline;W||($=this._config.quoteChar||'"',W=this._handle.guessLineEndings(u,$)),u=[...u.split(W).slice(T)].join(W)}this.isFirstChunk&&F(this._config.beforeFirstChunk)&&($=this._config.beforeFirstChunk(u))!==void 0&&(u=$),this.isFirstChunk=!1,this._halted=!1;var T=this._partialLine+u,$=(this._partialLine="",this._handle.parse(T,this._baseIndex,!this._finished));if(!this._handle.paused()&&!this._handle.aborted()){if(u=$.meta.cursor,T=(this._finished||(this._partialLine=T.substring(u-this._baseIndex),this._baseIndex=u),$&&$.data&&(this._rowCount+=$.data.length),this._finished||this._config.preview&&this._rowCount>=this._config.preview),i)r.postMessage({results:$,workerId:f.WORKER_ID,finished:T});else if(F(this._config.chunk)&&!w){if(this._config.chunk($,this._handle),this._handle.paused()||this._handle.aborted())return void(this._halted=!0);this._completeResults=$=void 0}return this._config.step||this._config.chunk||(this._completeResults.data=this._completeResults.data.concat($.data),this._completeResults.errors=this._completeResults.errors.concat($.errors),this._completeResults.meta=$.meta),this._completed||!T||!F(this._config.complete)||$&&$.meta.aborted||(this._config.complete(this._completeResults,this._input),this._completed=!0),T||$&&$.meta.paused||this._nextChunk(),$}this._halted=!0},this._sendError=function(u){F(this._config.error)?this._config.error(u):i&&this._config.error&&r.postMessage({workerId:f.WORKER_ID,error:u,finished:!1})}}function y(p){var u;(p=p||{}).chunkSize||(p.chunkSize=f.RemoteChunkSize),j.call(this,p),this._nextChunk=o?function(){this._readChunk(),this._chunkLoaded()}:function(){this._readChunk()},this.stream=function(w){this._input=w,this._nextChunk()},this._readChunk=function(){if(this._finished)this._chunkLoaded();else{if(u=new XMLHttpRequest,this._config.withCredentials&&(u.withCredentials=this._config.withCredentials),o||(u.onload=H(this._chunkLoaded,this),u.onerror=H(this._chunkError,this)),u.open(this._config.downloadRequestBody?"POST":"GET",this._input,!o),this._config.downloadRequestHeaders){var w,T=this._config.downloadRequestHeaders;for(w in T)u.setRequestHeader(w,T[w])}var $;this._config.chunkSize&&($=this._start+this._config.chunkSize-1,u.setRequestHeader("Range","bytes="+this._start+"-"+$));try{u.send(this._config.downloadRequestBody)}catch(W){this._chunkError(W.message)}o&&u.status===0&&this._chunkError()}},this._chunkLoaded=function(){u.readyState===4&&(u.status<200||400<=u.status?this._chunkError():(this._start+=this._config.chunkSize||u.responseText.length,this._finished=!this._config.chunkSize||this._start>=(w=>(w=w.getResponseHeader("Content-Range"))!==null?parseInt(w.substring(w.lastIndexOf("/")+1)):-1)(u),this.parseChunk(u.responseText)))},this._chunkError=function(w){w=u.statusText||w,this._sendError(new Error(w))}}function k(p){(p=p||{}).chunkSize||(p.chunkSize=f.LocalChunkSize),j.call(this,p);var u,w,T=typeof FileReader<"u";this.stream=function($){this._input=$,w=$.slice||$.webkitSlice||$.mozSlice,T?((u=new FileReader).onload=H(this._chunkLoaded,this),u.onerror=H(this._chunkError,this)):u=new FileReaderSync,this._nextChunk()},this._nextChunk=function(){this._finished||this._config.preview&&!(this._rowCount<this._config.preview)||this._readChunk()},this._readChunk=function(){var $=this._input,W=(this._config.chunkSize&&(W=Math.min(this._start+this._config.chunkSize,this._input.size),$=w.call($,this._start,W)),u.readAsText($,this._config.encoding));T||this._chunkLoaded({target:{result:W}})},this._chunkLoaded=function($){this._start+=this._config.chunkSize,this._finished=!this._config.chunkSize||this._start>=this._input.size,this.parseChunk($.target.result)},this._chunkError=function(){this._sendError(u.error)}}function C(p){var u;j.call(this,p=p||{}),this.stream=function(w){return u=w,this._nextChunk()},this._nextChunk=function(){var w,T;if(!this._finished)return w=this._config.chunkSize,u=w?(T=u.substring(0,w),u.substring(w)):(T=u,""),this._finished=!u,this.parseChunk(T)}}function x(p){j.call(this,p=p||{});var u=[],w=!0,T=!1;this.pause=function(){j.prototype.pause.apply(this,arguments),this._input.pause()},this.resume=function(){j.prototype.resume.apply(this,arguments),this._input.resume()},this.stream=function($){this._input=$,this._input.on("data",this._streamData),this._input.on("end",this._streamEnd),this._input.on("error",this._streamError)},this._checkIsFinished=function(){T&&u.length===1&&(this._finished=!0)},this._nextChunk=function(){this._checkIsFinished(),u.length?this.parseChunk(u.shift()):w=!0},this._streamData=H(function($){try{u.push(typeof $=="string"?$:$.toString(this._config.encoding)),w&&(w=!1,this._checkIsFinished(),this.parseChunk(u.shift()))}catch(W){this._streamError(W)}},this),this._streamError=H(function($){this._streamCleanUp(),this._sendError($)},this),this._streamEnd=H(function(){this._streamCleanUp(),T=!0,this._streamData("")},this),this._streamCleanUp=H(function(){this._input.removeListener("data",this._streamData),this._input.removeListener("end",this._streamEnd),this._input.removeListener("error",this._streamError)},this)}function A(p){var u,w,T,$,W=Math.pow(2,53),B=-W,_e=/^\s*-?(\d+\.?|\.\d+|\d+\.\d+)([eE][-+]?\d+)?\s*$/,ue=/^((\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z)))$/,D=this,P=0,U=0,ie=!1,z=!1,G=[],I={data:[],errors:[],meta:{}};function he(de){return p.skipEmptyLines==="greedy"?de.join("").trim()==="":de.length===1&&de[0].length===0}function De(){if(I&&T&&(st("Delimiter","UndetectableDelimiter","Unable to auto-detect delimiting character; defaulted to '"+f.DefaultDelimiter+"'"),T=!1),p.skipEmptyLines&&(I.data=I.data.filter(function(se){return!he(se)})),Ne()){let se=function(we,Oe){F(p.transformHeader)&&(we=p.transformHeader(we,Oe)),G.push(we)};if(I)if(Array.isArray(I.data[0])){for(var de=0;Ne()&&de<I.data.length;de++)I.data[de].forEach(se);I.data.splice(0,1)}else I.data.forEach(se)}function ge(se,we){for(var Oe=p.header?{}:[],je=0;je<se.length;je++){var ae=je,re=se[je],re=((it,te)=>(Ee=>(p.dynamicTypingFunction&&p.dynamicTyping[Ee]===void 0&&(p.dynamicTyping[Ee]=p.dynamicTypingFunction(Ee)),(p.dynamicTyping[Ee]||p.dynamicTyping)===!0))(it)?te==="true"||te==="TRUE"||te!=="false"&&te!=="FALSE"&&((Ee=>{if(_e.test(Ee)&&(Ee=parseFloat(Ee),B<Ee&&Ee<W))return 1})(te)?parseFloat(te):ue.test(te)?new Date(te):te===""?null:te):te)(ae=p.header?je>=G.length?"__parsed_extra":G[je]:ae,re=p.transform?p.transform(re,ae):re);ae==="__parsed_extra"?(Oe[ae]=Oe[ae]||[],Oe[ae].push(re)):Oe[ae]=re}return p.header&&(je>G.length?st("FieldMismatch","TooManyFields","Too many fields: expected "+G.length+" fields but parsed "+je,U+we):je<G.length&&st("FieldMismatch","TooFewFields","Too few fields: expected "+G.length+" fields but parsed "+je,U+we)),Oe}var Me;I&&(p.header||p.dynamicTyping||p.transform)&&(Me=1,!I.data.length||Array.isArray(I.data[0])?(I.data=I.data.map(ge),Me=I.data.length):I.data=ge(I.data,0),p.header&&I.meta&&(I.meta.fields=G),U+=Me)}function Ne(){return p.header&&G.length===0}function st(de,ge,Me,se){de={type:de,code:ge,message:Me},se!==void 0&&(de.row=se),I.errors.push(de)}F(p.step)&&($=p.step,p.step=function(de){I=de,Ne()?De():(De(),I.data.length!==0&&(P+=de.data.length,p.preview&&P>p.preview?w.abort():(I.data=I.data[0],$(I,D))))}),this.parse=function(de,ge,Me){var se=p.quoteChar||'"',se=(p.newline||(p.newline=this.guessLineEndings(de,se)),T=!1,p.delimiter?F(p.delimiter)&&(p.delimiter=p.delimiter(de),I.meta.delimiter=p.delimiter):((se=((we,Oe,je,ae,re)=>{var it,te,Ee,Nt;re=re||[",","	","|",";",f.RECORD_SEP,f.UNIT_SEP];for(var zt=0;zt<re.length;zt++){for(var xt,Kt=re[zt],We=0,fe=0,ye=0,Xe=(Ee=void 0,new X({comments:ae,delimiter:Kt,newline:Oe,preview:10}).parse(we)),rt=0;rt<Xe.data.length;rt++)je&&he(Xe.data[rt])?ye++:(xt=Xe.data[rt].length,fe+=xt,Ee===void 0?Ee=xt:0<xt&&(We+=Math.abs(xt-Ee),Ee=xt));0<Xe.data.length&&(fe/=Xe.data.length-ye),(te===void 0||We<=te)&&(Nt===void 0||Nt<fe)&&1.99<fe&&(te=We,it=Kt,Nt=fe)}return{successful:!!(p.delimiter=it),bestDelimiter:it}})(de,p.newline,p.skipEmptyLines,p.comments,p.delimitersToGuess)).successful?p.delimiter=se.bestDelimiter:(T=!0,p.delimiter=f.DefaultDelimiter),I.meta.delimiter=p.delimiter),_(p));return p.preview&&p.header&&se.preview++,u=de,w=new X(se),I=w.parse(u,ge,Me),De(),ie?{meta:{paused:!0}}:I||{meta:{paused:!1}}},this.paused=function(){return ie},this.pause=function(){ie=!0,w.abort(),u=F(p.chunk)?"":u.substring(w.getCharIndex())},this.resume=function(){D.streamer._halted?(ie=!1,D.streamer.parseChunk(u,!0)):setTimeout(D.resume,3)},this.aborted=function(){return z},this.abort=function(){z=!0,w.abort(),I.meta.aborted=!0,F(p.complete)&&p.complete(I),u=""},this.guessLineEndings=function(we,se){we=we.substring(0,1048576);var se=new RegExp(S(se)+"([^]*?)"+S(se),"gm"),Me=(we=we.replace(se,"")).split("\r"),se=we.split(`
225`),we=1<se.length&&se[0].length<Me[0].length;if(Me.length===1||we)return`
226`;for(var Oe=0,je=0;je<Me.length;je++)Me[je][0]===`
227`&&Oe++;return Oe>=Me.length/2?`\r
228`:"\r"}}function S(p){return p.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function X(p){var u=(p=p||{}).delimiter,w=p.newline,T=p.comments,$=p.step,W=p.preview,B=p.fastMode,_e=null,ue=!1,D=p.quoteChar==null?'"':p.quoteChar,P=D;if(p.escapeChar!==void 0&&(P=p.escapeChar),(typeof u!="string"||-1<f.BAD_DELIMITERS.indexOf(u))&&(u=","),T===u)throw new Error("Comment character same as delimiter");T===!0?T="#":(typeof T!="string"||-1<f.BAD_DELIMITERS.indexOf(T))&&(T=!1),w!==`
229`&&w!=="\r"&&w!==`\r
230`&&(w=`
231`);var U=0,ie=!1;this.parse=function(z,G,I){if(typeof z!="string")throw new Error("Input must be a string");var he=z.length,De=u.length,Ne=w.length,st=T.length,de=F($),ge=[],Me=[],se=[],we=U=0;if(!z)return We();if(B||B!==!1&&z.indexOf(D)===-1){for(var Oe=z.split(w),je=0;je<Oe.length;je++){if(se=Oe[je],U+=se.length,je!==Oe.length-1)U+=w.length;else if(I)return We();
231if(!T||se.substring(0,st)!==T){if(de){if(ge=[],Nt(se.split(u)),fe(),ie)return We()}else Nt(se.split(u));if(W&&W<=je)return ge=ge.slice(0,W),We(!0)}}return We()}for(var ae=z.indexOf(u,U),re=z.indexOf(w,U),it=new RegExp(S(P)+S(D),"g"),te=z.indexOf(D,U);;)if(z[U]===D)for(te=U,U++;;){if((te=z.indexOf(D,te+1))===-1)return I||Me.push({type:"Quotes",code:"MissingQuotes",message:"Quoted field unterminated",row:ge.length,index:U}),xt();if(te===he-1)return xt(z.substring(U,te).replace(it,D));if(D===P&&z[te+1]===P)te++;else if(D===P||te===0||z[te-1]!==P){ae!==-1&&ae<te+1&&(ae=z.indexOf(u,te+1));var Ee=zt((re=re!==-1&&re<te+1?z.indexOf(w,te+1):re)===-1?ae:Math.min(ae,re));if(z.substr(te+1+Ee,De)===u){se.push(z.substring(U,te).replace(it,D)),z[U=te+1+Ee+De]!==D&&(te=z.indexOf(D,U)),ae=z.indexOf(u,U),re=z.indexOf(w,U);break}if(Ee=zt(re),z.substring(te+1+Ee,te+1+Ee+Ne)===w){if(se.push(z.substring(U,te).replace(it,D)),Kt(te+1+Ee+Ne),ae=z.indexOf(u,U),te=z.indexOf(D,U),de&&(fe(),ie))return We();if(W&&ge.length>=W)return We(!0);break}Me.push({type:"Quotes",code:"InvalidQuotes",message:"Trailing quote on quoted field is malformed",row:ge.length,index:U}),te++}}else if(T&&se.length===0&&z.substring(U,U+st)===T){if(re===-1)return We();U=re+Ne,re=z.indexOf(w,U),ae=z.indexOf(u,U)}else if(ae!==-1&&(ae<re||re===-1))se.push(z.substring(U,ae)),U=ae+De,ae=z.indexOf(u,U);else{if(re===-1)break;if(se.push(z.substring(U,re)),Kt(re+Ne),de&&(fe(),ie))return We();if(W&&ge.length>=W)return We(!0)}return xt();function Nt(ye){ge.push(ye),we=U}function zt(ye){var Xe=0;return Xe=ye!==-1&&(ye=z.substring(te+1,ye))&&ye.trim()===""?ye.length:Xe}function xt(ye){return I||(ye===void 0&&(ye=z.substring(U)),se.push(ye),U=he,Nt(se),de&&fe()),We()}function Kt(ye){U=ye,Nt(se),se=[],re=z.indexOf(w,U)}function We(ye){if(p.header&&!G&&ge.length&&!ue){var Xe=ge[0],rt=Object.create(null),St=new Set(Xe);let Qt=!1;for(let Dt=0;Dt<Xe.length;Dt++){let pt=Xe[Dt];if(rt[pt=F(p.transformHeader)?p.transformHeader(pt,Dt):pt]){let ot,at=rt[pt];for(;ot=pt+"_"+at,at++,St.has(ot););St.add(ot),Xe[Dt]=ot,rt[pt]++,Qt=!0,(_e=_e===null?{}:_e)[ot]=pt}else rt[pt]=1,Xe[Dt]=pt;St.add(pt)}Qt&&console.warn("Duplicate headers found and renamed."),ue=!0}return{data:ge,errors:Me,meta:{delimiter:u,linebreak:w,aborted:ie,truncated:!!ye,cursor:we+(G||0),renamedHeaders:_e}}}function fe(){$(We()),ge=[],Me=[]}},this.abort=function(){ie=!0},this.getCharIndex=function(){return U}}function N(p){var u=p.data,w=m[u.workerId],T=!1;if(u.error)w.userError(u.error,u.file);else if(u.results&&u.results.data){var $={abort:function(){T=!0,M(u.workerId,{data:[],errors:[],meta:{aborted:!0}})},pause:L,resume:L};if(F(w.userStep)){for(var W=0;W<u.results.data.length&&(w.userStep({data:u.results.data[W],errors:u.results.errors,meta:u.results.meta},$),!T);W++);delete u.results}else F(w.userChunk)&&(w.userChunk(u.results,$,u.file),delete u.results)}u.finished&&!T&&M(u.workerId,u.results)}function M(p,u){var w=m[p];F(w.userComplete)&&w.userComplete(u),w.terminate(),delete m[p]}function L(){throw new Error("Not implemented.")}function _(p){if(typeof p!="object"||p===null)return p;var u,w=Array.isArray(p)?[]:{};for(u in p)w[u]=_(p[u]);return w}function H(p,u){return function(){p.apply(u,arguments)}}function F(p){return typeof p=="function"}return f.parse=function(p,u){var w=(u=u||{}).dynamicTyping||!1;if(F(w)&&(u.dynamicTypingFunction=w,w={}),u.dynamicTyping=w,u.transform=!!F(u.transform)&&u.transform,!u.worker||!f.WORKERS_SUPPORTED)return w=null,f.NODE_STREAM_INPUT,typeof p=="string"?(p=(T=>T.charCodeAt(0)!==65279?T:T.slice(1))(p),w=new(u.download?y:C)(u)):p.readable===!0&&F(p.read)&&F(p.on)?w=new x(u):(r.File&&p instanceof File||p instanceof Object)&&(w=new k(u)),w.stream(p);(w=(()=>{var T;return!!f.WORKERS_SUPPORTED&&(T=(()=>{var $=r.URL||r.webkitURL||null,W=a.toString();return f.BLOB_URL||(f.BLOB_URL=$.createObjectURL(new Blob(["var global = (function() { if (typeof self !== 'undefined') { return self; } if (typeof window !== 'undefined') { return window; } if (typeof global !== 'undefined') { return global; } return {}; })(); global.IS_PAPA_WORKER=true; ","(",W,")();"],{type:"text/javascript"})))})(),(T=new r.Worker(T)).onmessage=N,T.id=g++,m[T.id]=T)})()).userStep=u.step,w.userChunk=u.chunk,w.userComplete=u.complete,w.userError=u.error,u.step=F(u.step),u.chunk=F(u.chunk),u.complete=F(u.complete),u.error=F(u.error),delete u.worker,w.postMessage({input:p,config:u,workerId:w.id})},f.unparse=function(p,u){var w=!1,T=!0,$=",",W=`\r
232`,B='"',_e=B+B,ue=!1,D=null,P=!1,U=((()=>
232{if(typeof u=="object"){if(typeof u.delimiter!="string"||f.BAD_DELIMITERS.filter(function(G){return u.delimiter.indexOf(G)!==-1}).length||($=u.delimiter),typeof u.quotes!="boolean"&&typeof u.quotes!="function"&&!Array.isArray(u.quotes)||(w=u.quotes),typeof u.skipEmptyLines!="boolean"&&typeof u.skipEmptyLines!="string"||(ue=u.skipEmptyLines),typeof u.newline=="string"&&(W=u.newline),typeof u.quoteChar=="string"&&(B=u.quoteChar),typeof u.header=="boolean"&&(T=u.header),Array.isArray(u.columns)){if(u.columns.length===0)throw new Error("Option columns is empty");D=u.columns}u.escapeChar!==void 0&&(_e=u.escapeChar+B),u.escapeFormulae instanceof RegExp?P=u.escapeFormulae:typeof u.escapeFormulae=="boolean"&&u.escapeFormulae&&(P=/^[=+\-@\t\r].*$/)}})(),new RegExp(S(B),"g"));if(typeof p=="string"&&(p=JSON.parse(p)),Array.isArray(p)){if(!p.length||Array.isArray(p[0]))return ie(null,p,ue);if(typeof p[0]=="object")return ie(D||Object.keys(p[0]),p,ue)}else if(typeof p=="object")return typeof p.data=="string"&&(p.data=JSON.parse(p.data)),Array.isArray(p.data)&&(p.fields||(p.fields=p.meta&&p.meta.fields||D),p.fields||(p.fields=Array.isArray(p.data[0])?p.fields:typeof p.data[0]=="object"?Object.keys(p.data[0]):[]),Array.isArray(p.data[0])||typeof p.data[0]=="object"||(p.data=[p.data])),ie(p.fields||[],p.data||[],ue);throw new Error("Unable to serialize unrecognized input");function ie(G,I,he){var De="",Ne=(typeof G=="string"&&(G=JSON.parse(G)),typeof I=="string"&&(I=JSON.parse(I)),Array.isArray(G)&&0<G.length),st=!Array.isArray(I[0]);if(Ne&&T){for(var de=0;de<G.length;de++)0<de&&(De+=$),De+=z(G[de],de);0<I.length&&(De+=W)}for(var ge=0;ge<I.length;ge++){var Me=(Ne?G:I[ge]).length,se=!1,we=Ne?Object.keys(I[ge]).length===0:I[ge].length===0;if(he&&!Ne&&(se=he==="greedy"?I[ge].join("").trim()==="":I[ge].length===1&&I[ge][0].length===0),he==="greedy"&&Ne){for(var Oe=[],je=0;je<Me;je++){var ae=st?G[je]:je;Oe.push(I[ge][ae])}se=Oe.join("").trim()===""}if(!se){for(var re=0;re<Me;re++){0<re&&!we&&(De+=$);var it=Ne&&st?G[re]:re;De+=z(I[ge][it],re)}ge<I.length-1&&(!he||0<Me&&!we)&&(De+=W)}}return De}function z(G,I){var he,De;return G==null?"":G.constructor===Date?JSON.stringify(G).slice(1,25):(De=!1,P&&typeof G=="string"&&P.test(G)&&(G="'"+G,De=!0),he=G.toString().replace(U,_e),(De=De||w===!0||typeof w=="function"&&w(G,I)||Array.isArray(w)&&w[I]||((Ne,st)=>{for(var de=0;de<st.length;de++)if(-1<Ne.indexOf(st[de]))return!0;return!1})(he,f.BAD_DELIMITERS)||-1<he.indexOf($)||he.charAt(0)===" "||he.charAt(he.length-1)===" ")?B+he+B:he)}},f.RECORD_SEP="�",f.UNIT_SEP="�",f.BYTE_ORDER_MARK="\uFEFF",f.BAD_DELIMITERS=["\r",`
233`,'"',f.BYTE_ORDER_MARK],f.WORKERS_SUPPORTED=!o&&!!r.Worker,f.NODE_STREAM_INPUT=1,f.LocalChunkSize=10485760,f.RemoteChunkSize=5242880,f.DefaultDelimiter=",",f.Parser=X,f.ParserHandle=A,f.NetworkStreamer=y,f.FileStreamer=k,f.StringStreamer=C,f.ReadableStreamStreamer=x,r.jQuery&&((n=r.jQuery).fn.parse=function(p){var u=p.config||{},w=[];return this.each(function(W){if(!(n(this).prop("tagName").toUpperCase()==="INPUT"&&n(this).attr("type").toLowerCase()==="file"&&r.FileReader)||!this.files||this.files.length===0)return!0;for(var B=0;B<this.files.length;B++)w.push({file:this.files[B],inputElem:this,instanceConfig:n.extend({},u)})}),T(),this;function T(){if(w.length===0)F(p.complete)&&p.complete();else{var W,B,_e,ue,D=w[0];if(F(p.before)){var P=p.before(D.file,D.inputElem);if(typeof P=="object"){if(P.action==="abort")return W="AbortError",B=D.file,_e=D.inputElem,ue=P.reason,void(F(p.error)&&p.error({name:W},B,_e,ue));if(P.action==="skip")return void $();typeof P.config=="object"&&(D.instanceConfig=n.extend(D.instanceConfig,P.config))}else if(P==="skip")return void $()}var U=D.instanceConfig.complete;D.instanceConfig.complete=function(ie){F(U)&&U(ie,D.file,D.inputElem),$()},f.parse(D.file,D.instanceConfig)}}function $(){w.splice(0,1),T()}}),i&&(r.onmessage=function(p){p=p.data,f.WORKER_ID===void 0&&p&&(f.WORKER_ID=p.workerId),typeof p.input=="string"?r.postMessage({workerId:f.WORKER_ID,results:f.parse(p.input,p.config),finished:!0}):(r.File&&p.input instanceof File||p.input instanceof Object)&&(p=f.parse(p.input,p.config))&&r.postMessage({workerId:f.WORKER_ID,results:p,finished:!0})}),(y.prototype=Object.create(j.prototype)).constructor=y,(k.prototype=Object.create(j.prototype)).constructor=k,(C.prototype=Object.create(C.prototype)).constructor=C,(x.prototype=Object.create(j.prototype)).constructor=x,f})})(ua);var kn=ua.exports;const Ln=Oa(kn),Cn=["EXCLUDE FROM STATS FLAG","SALE DATE","LANE NUMBER","RUN NUMBER"];function $n(t){const s=t.map(a=>a.trim().toUpperCase());return Cn.every(a=>s.includes(a))}function Xt(t){if(t==null)return null;const s=String(t).trim();if(!s)return null;const a=/^\(.*\)$/.test(s),r=s.replace(/[(),$\s]/g,"");if(!r||r==="-")return null;const n=Number(r);return Number.isFinite(n)?a?-n:n:null}function Qs(t){const s=Xt(t);return s==null?null:Math.trunc(s)}function tt(t){if(t==null)return null;const s=String(t).trim();return s||null}function An(t){const s=tt(t);if(!s)return null;const a=s.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})/);if(!a)return null;const r=a[1].padStart(2,"0"),n=a[2].padStart(2,"0");return`${a[3]}-${r}-${n}`}function Mn(t){const s=a=>{const r=tt(t[a]);return r&&r.toUpperCase()==="X"};return s("RED LIGHT")?"RED":s("YELLOW LIGHT")?"YELLOW":s("GREEN LIGHT")?"GREEN":s("BLUE LIGHT")?"BLUE":null}function Tn(t){if(!t)return null;const s=t.match(/LOAN\s*\$?\s*([\d,]+(?:\.\d+)?)/i);return s?Xt(s[1]):null}function Dn(t){const s=t.replace(/^\uFEFF/,""),r=Ln.parse(s,{skipEmptyLines:!0}).data||[];if(r.length<2)return{saleDate:null,lots:[]};const n=r[0].map(j=>j.trim());if(!$n(n))throw new Error("CSV does not look like a Manheim After Sale Report.");const o=new Map;
233n.forEach((j,y)=>{const k=j.trim().toUpperCase(),C=o.get(k)??[];C.push(y),o.set(k,C)});const i=(j,y)=>(o.get(y.toUpperCase())??[]).map(C=>j[C]??"").map(C=>C),m=(j,y)=>i(j,y).find(C=>C!=null&&String(C).trim()!=="")??"";let g=null;const f=[];for(let j=1;j<r.length;j++){const y=r[j];if(!y||y.length===0)continue;const k=tt(m(y,"VIN"));if(!k||/^no\s+vehicle\s+assigned$/i.test(k)||k.length!==17)continue;const C={};n.forEach((ue,D)=>{const P=ue.trim();P&&C[P]===void 0&&(C[P]=y[D]??"")});const x={};for(const[ue,D]of o){const U=D.map(ie=>y[ie]??"").find(ie=>String(ie).trim()!=="")??"";x[ue]=U}g||(g=An(x["SALE DATE"]));const A=tt(x["LANE NUMBER"]),S=tt(x["RUN NUMBER"]),X=A&&S?`L${A}/R${S}`:A??S??null,N=[tt(x.ANNOUNCEMENTS),tt(x["ADDITIONAL ANN"])].filter(Boolean).join(" | ")||null,M=i(y,"NOTES").map(ue=>ue.trim()).filter(Boolean),L=tt(x.REMARKS),_=tt(x["ADDITIONAL INFO"]),H=[L,M.join(" "),_].filter(Boolean).join(" | ")||null,F=(N??"").toUpperCase(),p=(M.join(" ")??"").toUpperCase(),u=Qs(x.ODO),w=Xt(x["SALE PRICE"]),T=w!=null&&w>0,$=Tn(M.join(`
234`)),W=T&&$!=null?w-$:null;let B=!1,_e=null;T&&$==null&&(B=!0,_e="missing_loan"),f.push({lot_number:X,dealer_code:tt(x["SELLER NUMBER"]),dealer_name:tt(x["SELLER NAME"]),stock_number:tt(x["STOCK#"])??tt(x["STOCK NUMBER"])??tt(x["WO#"]),vin:k,year:Qs(x.YEAR),make:tt(x.MAKE),model:tt(x.MODEL),trim:tt(x.TRIM),body_style:tt(x["BODY TYPE"]),color:tt(x["EXTERIOR COLOR"]),miles:u,title_state:tt(x.STATE),lights:Mn(x),floor_price:Xt(x["IN-LANE FLOOR"])??Xt(x["TIMED SALE FLOOR"]),sale_price:T?w:null,highest_bid_amount:Xt(x["HIGH BID"]),local_cv:Xt(x["MY VALUE"]),natl_cv:Xt(x["ADJ NAT MMR"]),guidebook:Xt(x["MY VALUE"]),loan_amount:$,profit_loss:W,days_in_inventory:Qs(x["MY AGE"]),sales_veh_run_by_seller:Qs(x["TIMES RUN"]),sold:T,no_sale:!T,as_is:/AS\s*IS/.test(F),structural_damage:/FRAME|STRUCT/.test(F)||/FRAME\s*FAIL/.test(p),over_100k:u!=null&&u>=1e5&&u<2e5,over_200k:u!=null&&u>=2e5,caution:/CAUTION/.test(F),condition_codes:N,cr_comments:H,needs_review:B,review_reason:_e,raw_data:C})}return{saleDate:g,lots:f}}const Js="__unmapped__";function Rn(){const{selectedDealership:t}=Us(),s=(t==null?void 0:t.organization_id)??null,{toast:a}=ys(),[r,n]=v.useState([]),[o,i]=v.useState([]),[m,g]=v.useState({}),[f,j]=v.useState(null),[y,k]=v.useState(!1),[C,x]=v.useState({});async function A(){if(s){k(!0);try{const[N,M]=await Promise.all([ne.from("wholesale360_dealer_aliases").select("id, dealer_code, dealer_name, dealership_id, source").eq("organization_id",s).order("dealer_name",{ascending:!0}),ne.from("dealerships").select("id, name").eq("organization_id",s).order("name",{ascending:!0})]);n(N.data??[]),i(M.data??[]);const{data:L}=await ne.from("wholesale360_lots").select("dealer_code, dealer_name").eq("organization_id",s).limit(5e3),_={};for(const H of L??[]){const F=`${(H.dealer_code??"").toUpperCase()}|${(H.dealer_name??"").toUpperCase()}`;_[F]=(_[F]??0)+1}x(_)}finally{k(!1)}}}v.useEffect(()=>{A()},[s]);async function S(N){const M=m[N.id];if(M===void 0)return;const L=M===Js?null:M;j(N.id);try{const{error:_}=await ne.from("wholesale360_dealer_aliases").update({dealership_id:L}).eq("id",N.id);if(_)throw _;const H=ne.from("wholesale360_lots").update({dealership_id:L,needs_review:!1,review_reason:null}).eq("organization_id",s);N.dealer_code?H.eq("dealer_code",N.dealer_code):N.dealer_name&&H.is("dealer_code",null).eq("dealer_name",N.dealer_name);const{error:F}=await H;if(F)throw F;a({title:"Seller mapped",description:N.dealer_name??N.dealer_code??"Updated"}),g(p=>{const{[N.id]:u,...w}=p;return w}),await A()}catch(_){a({title:"Save failed",description:(_==null?void 0:_.message)??String(_),variant:"destructive"})}finally{j(null)}}if(!s)return e.jsx($e,{className:"bg-white/[0.03] border-white/10",children:e.jsx(Ae,{className:"p-8 text-center text-muted-foreground",children:"Select a dealership to manage seller aliases."})});const X=r.filter(N=>!N.dealership_id).length;return e.jsx($e,{className:"bg-white/[0.03] border-white/10",children:e.jsxs(Ae,{className:"p-0",children:[e.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-white/10",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:"Map each auction seller name to one of your dealerships. Changes re-tag every historical lot for that seller."}),X>0&&e.jsxs(Pe,{className:"bg-amber-500/15 text-amber-200 border-amber-500/30",children:[X," unmapped"]})]}),y?e.jsx("div",{className:"p-8 text-center text-muted-foreground",children:"Loading…"}):r.length===0?e.jsx("div",{className:"p-8 text-center text-muted-foreground",children:"No sellers seen yet. Upload an auction file to populate this list."}):e.jsxs(ke,{children:[e.jsx(Le,{children:e.jsxs(q,{children:[e.jsx(h,{children:"Source"}),e.jsx(h,{children:"Seller #"}),e.jsx(h,{children:"Seller Name"}),e.jsx(h,{className:"text-right",children:"Lots"}),e.jsx(h,{children:"Mapped Dealership"}),e.jsx(h,{className:"w-24"})]})}),e.jsx(Ce,{children:r.map(N=>{const M=`${(N.dealer_code??"").toUpperCase()}|${(N.dealer_name??"").toUpperCase()}`,L=C[M]??0,_=m[N.id]??N.dealership_id??Js,H=m[N.id]!==void 0&&m[N.id]!==(N.dealership_id??Js);return e.jsxs(q,{children:[e.jsx(c,{className:"text-xs text-muted-foreground",children:N.source??"—"}),e.jsx(c,{className:"font-mono text-xs",children:N.dealer_code??"—"}),e.jsx(c,{className:"text-sm",children:N.dealer_name??"—"}),e.jsx(c,{className:"text-right",children:L}),e.jsx(c,{children:e.jsxs(It,{value:_,onValueChange:F=>g(p=>({...p,[N.id]:F})),children:[e.jsx(Ot,{className:"w-[260px]",children:e.jsx(Ut,{placeholder:"Unmapped"})}),e.jsxs(Gt,{children:[e.jsx(Te,{value:Js,children:"— Unmapped —"}),o.map(F=>e.jsx(Te,{value:F.id,children:F.name},F.id))]})]})}),e.jsx(c,{children:e.jsx(ce,{size:"sm",disabled:!H||f===N.id,onClick:()=>S(N),children:f===N.id?e.jsx(es,{className:"h-3 w-3 animate-spin"}):"Save"})})]},N.id)})})]})]})})}const ma=[{id:"dealer_scorecard",group:"Performance",label:"Dealer P/L Scorecard",desc:"Per-dealer volume, sell-through, total + avg P/L."},{id:"source_comparison",group:"Performance",label:"Auction Source Comparison",desc:"ADESA vs Manheim side-by-side."},{id:"sale_date_trend",group:"Performance",label:"Sale Date P/L Trend",desc:"Daily P/L with sold vs no-sale volume."},{id:"floor_variance",group:"Pricing",label:"Floor vs Net Check Variance",desc:"Scatter + top outliers."},{id:"floor_accuracy",group:"Pricing",label:"Floor Accuracy",desc:"
234% of sold lots within ±5/10/>10% of floor."},{id:"no_sale_analysis",group:"Pricing",label:"No-Sale Analysis",desc:"No-sale lots grouped by floor band."},{id:"ymm_leaderboard",group:"Vehicle",label:"Year/Make/Model Leaderboard",desc:"Top 20 + bottom 20 by total P/L."},{id:"mileage_band",group:"Vehicle",label:"Mileage Band P/L",desc:"P/L grouped by mileage bucket."},{id:"condition_impact",group:"Vehicle",label:"Condition-Flag Impact",desc:"Avg P/L by AS-IS / structural / etc."},{id:"aging_times_run",group:"Operational",label:"Aging / Times Run",desc:"Lots run 3+ times, still unsold."},{id:"repeat_vin_trends",group:"Operational",label:"Repeat VIN Bid Trends",desc:"VINs run 2+ times — floor, high bid, and sale price across each run."},{id:"unmapped_sellers",group:"Operational",label:"Unmapped Sellers Audit",desc:"Dealers missing alias mapping."},{id:"per_run_recap",group:"Operational",label:"Per-Run Recap",desc:"Printable single-run summary."}];function Pn(){const{selectedDealership:t}=Us(),{selectedIds:s,scopeLabel:a}=br(),r=(t==null?void 0:t.organization_id)??null,[n,o]=v.useState([]),[i,m]=v.useState([]),[g,f]=v.useState([]),[j,y]=v.useState([]),[k,C]=v.useState(!0),[x,A]=v.useState("dealer_scorecard"),[S,X]=v.useState("90"),[N,M]=v.useState("ALL"),[L,_]=v.useState(""),H=v.useMemo(()=>[...s].sort().join(","),[s]);v.useEffect(()=>{s.length!==0&&(async()=>{C(!0);const[{data:T},{data:$},{data:W},{data:B}]=await Promise.all([ne.from("wholesale360_runs").select("id,source,sale_date,total_lots,sold_lots,no_sale_lots,total_profit_loss").in("dealership_id",s).order("sale_date",{ascending:!1}).limit(500),ne.from("wholesale360_lots").select("id,run_id,dealer_code,dealer_name,stock_number,vin,year,make,model,trim,miles,floor_price,sale_price,auction_fee,net_check_to_dealer,profit_loss,loan_amount,sold,no_sale,as_is,structural_damage,over_100k,over_200k,condition_codes,days_in_inventory,highest_bid_amount").in("dealership_id",s).limit(2e4),r?ne.from("wholesale360_dealer_aliases").select("dealer_code,dealer_name,dealership_id").eq("organization_id",r):Promise.resolve({data:[]}),ne.from("dealerships").select("id,name")]);o(T??[]),m($??[]),f(W??[]),y(B??[]),C(!1)})()},[H,r]);const F=v.useMemo(()=>{const T=new Map;return n.forEach($=>T.set($.id,$)),T},[n]),p=v.useMemo(()=>en(g,j,i),[g,j,i]),u=v.useMemo(()=>{const T=S==="all"?null:(()=>{const B=new Date;return B.setDate(B.getDate()-Number(S)),B.toISOString().slice(0,10)})(),$=new Set(n.filter(B=>!(N!=="ALL"&&(B.source??"").toUpperCase()!==N||T&&B.sale_date&&B.sale_date<T)).map(B=>B.id)),W=L.trim().toLowerCase();return i.filter(B=>{if(!$.has(B.run_id))return!1;if(W){const _e=p(B).displayName.toLowerCase(),ue=`${B.dealer_code??""} ${B.dealer_name??""}`.toLowerCase();if(!_e.includes(W)&&!ue.includes(W))return!1}return!0})},[i,n,S,N,L,p]),w=()=>window.print();return e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-[260px_1fr] gap-4",children:[e.jsxs($e,{className:"bg-white/[0.03] border-white/10 h-fit",children:[e.jsxs(At,{className:"pb-2",children:[e.jsx(Mt,{className:"text-sm",children:"Reports"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Showing ",a]})]}),e.jsx(Ae,{className:"p-2",children:e.jsx(Ha,{className:"max-h-[70vh]",children:["Performance","Pricing","Vehicle","Operational"].map(T=>e.jsxs("div",{className:"mb-3",children:[e.jsx("div",{className:"text-xs uppercase tracking-wide text-muted-foreground px-2 py-1",children:T}),ma.filter($=>$.group===T).map($=>e.jsx("button",{onClick:()=>A($.id),className:`w-full text-left px-2 py-1.5 rounded text-sm transition-colors ${x===$.id?"bg-primary/20 text-foreground":"hover:bg-white/5 text-muted-foreground"}`,children:$.label},$.id))]},T))})})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx($e,{className:"bg-white/[0.03] border-white/10",children:e.jsxs(Ae,{className:"p-3 flex flex-wrap gap-3 items-center",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Range"}),e.jsxs(It,{value:S,onValueChange:X,children:[e.jsx(Ot,{className:"h-8 w-32",children:e.jsx(Ut,{})}),e.jsxs(Gt,{children:[e.jsx(Te,{value:"30",children:"Last 30 days"}),e.jsx(Te,{value:"90",children:"Last 90 days"}),e.jsx(Te,{value:"180",children:"Last 180 days"}),e.jsx(Te,{value:"365",children:"Last 365 days"}),e.jsx(Te,{value:"all",children:"All time"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Source"}),e.jsxs(It,{value:N,onValueChange:M,children:[e.jsx(Ot,{className:"h-8 w-32",children:e.jsx(Ut,{})}),e.jsxs(Gt,{children:[e.jsx(Te,{value:"ALL",children:"All"}),e.jsx(Te,{value:"ADESA",children:"ADESA"}),e.jsx(Te,{value:"MANHEIM",children:"Manheim"})]})]})]}),e.jsx(Ct,{value:L,onChange:T=>_(T.target.value),placeholder:"Filter dealer…",className:"h-8 w-48"}),e.jsx("div",{className:"flex-1"}),e.jsxs(ce,{size:"sm",variant:"outline",onClick:w,children:[e.jsx(Is,{className:"h-3.5 w-3.5 mr-1"})," Print"]})]})}),k?e.jsx($e,{className:"bg-white/[0.03] border-white/10",children:e.jsxs(Ae,{className:"p-8 text-center text-muted-foreground",children:[e.jsx(es,{className:"h-5 w-5 animate-spin inline mr-2"}),"Loading data…"]})}):e.jsx(En,{reportId:x,lots:u,runs:n,runById:F,aliases:g,resolveDealer:p})]})]})}function En({reportId:t,lots:s,runs:a,runById:r,aliases:n,resolveDealer:o}){const i=ma.find(f=>f.id===t),m=f=>{var j;return((j=r.get(f.run_id))==null?void 0:j.source)??null},g=v.useMemo(()=>{const f=s.filter(C=>C.sold).length,j=s.reduce((C,x)=>C+(Bt(x,m(x))??0),0),y=tn(s,m),k=s.length>0?f/s.length:0;return{sold:f,totalPL:j,avg:y,sellThrough:k}},[s,r]);return e.jsxs($e,{className:"bg-white/[0.03] border-white/10",children:[e.jsx(At,{className:"pb-2 flex flex-row items-start justify-between gap-2",children:e.jsxs("div",{children:[e.jsx(Mt,{children:i.label}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:i.desc})]})}),e.jsxs(Ae,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/20 p-3",children:[e.jsx("div",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Sold Lots"}),e.jsx("div",{className:"text-xl font-semibold mt-1",children:Je(g.sold)})]}),e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/20 p-3",children:[e.jsx("div",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Total P/L"}),e.jsx("div",{className:`text-xl font-semibold mt-1 ${g.totalPL>=0?"text-emerald-400":"text-red-400"}`,children:xe(g.totalPL)})]}),e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/20 p-3",children:[e.jsx("div",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Avg P/L / Vehicle"}),e.jsx("div",{className:`text-xl font-semibold mt-1 ${g.avg>=0?"text-emerald-400":"text-red-400"}`,children:g.sold>0?xe(g.avg):"—"})]}),e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/20 p-3",children:[e.jsx("div",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Sell-through"}),e.jsx("div",{className:"text-xl font-semibold mt-1 text-sky-300",children:is(g.sellThrough)})]})]}),t==="dealer_scorecard"&&e.jsx(Fn,{lots:s,sourceOf:m,resolveDealer:o}),t==="source_comparison"&&e.jsx(In,{lots:s,runs:a}),t==="sale_date_trend"&&e.jsx(On,{lots:s,runs:a,sourceOf:m}),t==="floor_variance"&&e.jsx(Un,{lots:s,sourceOf:m}),t==="floor_accuracy"&&e.jsx(Gn,{lots:s,sourceOf:m}),t==="no_sale_analysis"&&e.jsx(Bn,{lots:s}),t==="ymm_leaderboard"&&e.jsx(zn,{lots:s,sourceOf:m}),t==="mileage_band"&&e.jsx(qn,{lots:s,sourceOf:m}),t==="condition_impact"&&e.jsx(Wn,{lots:s,sourceOf:m}),t==="aging_times_run"&&e.jsx(Yn,{lots:s}),t==="repeat_vin_trends"&&e.jsx(Hn,{lots:s,runById:r,resolveDealer:o}),t==="unmapped_sellers"&&e.jsx(Kn,{lots:s,aliases:n,sourceOf:m}),t==="per_run_recap"&&e.jsx(Qn,{lots:s,runs:a})]})]})}function xa({name:t,rows:s}){return e.jsxs(ce,{size:"sm",variant:"outline",onClick:()=>an(t,s),disabled:!s.length,children:[e.jsx(pr,{className:"h-3.5 w-3.5 mr-1"})," CSV"]})}function Pt({name:t,rows:s,children:a}){return e.jsxs("div",{className:"flex items-center justify-between mb-3 gap-2 flex-wrap",children:[e.jsx("div",{className:"flex items-center gap-2",children:a}),e.jsx(xa,{name:t,rows:s})]})}function Fn({lots:t,sourceOf:s,resolveDealer:a}){const r=v.useMemo(()=>{const n=new Map;return t.forEach(o=>{const{key:i,displayName:m}=a(o),g=n.get(i)??{dealer:m,total:0,sold:0,pl:0,sums:0,best:-1/0,worst:1/0};if(g.dealer=m,g.total+=1,o.sold){g.sold+=1;const f=Bt(o,s(o));f!==null&&(g.pl+=f,g.sums+=1,f>g.best&&(g.best=f),f<g.worst&&(g.worst=f))}n.set(i,g)}),[...n.values()].map(o=>({Dealer:o.dealer,Lots:o.total,Sold:o.sold,"Sell-through":o.total?o.sold/o.total:0,"Total P/L":Math.round(o.pl),"Avg P/L / Sold":o.sums?Math.round(o.pl/o.sums):0,Best:Number.isFinite(o.best)?Math.round(o.best):null,Worst:Number.isFinite(o.worst)?Math.round(o.worst):null})).sort((o,i)=>i["Total P/L"]-o["Total P/L"])},[t,s]);return e.jsxs(e.Fragment,{children:[e.jsx(Pt,{name:"dealer-scorecard.csv",rows:r}),e.jsx("div",{className:"overflow-auto",children:e.jsxs(ke,{children:[e.jsx(Le,{children:e.jsxs(q,{children:[e.jsx(h,{children:"Dealer"}),e.jsx(h,{className:"text-right",children:"Lots"}),e.jsx(h,{className:"text-right",children:"Sold"}),e.jsx(h,{className:"text-right",children:"Sell-through"}),e.jsx(h,{className:"text-right",children:"Total P/L"}),e.jsx(h,{className:"text-right",children:"Avg P/L / Vehicle"}),e.jsx(h,{className:"text-right",children:"Best"}),e.jsx(h,{className:"text-right",children:"Worst"})]})}),e.jsxs(Ce,{children:[r.map((n,o)=>e.jsxs(q,{children:[e.jsx(c,{className:"font-medium",children:n.Dealer}),e.jsx(c,{className:"text-right",children:Je(n.Lots)}),e.jsx(c,{className:"text-right",children:Je(n.Sold)}),e.jsx(c,{className:"text-right",children:is(n["Sell-through"])}),e.jsx(c,{className:`text-right ${n["Total P/L"]>=0?"text-green-400":"text-red-400"}`,children:xe(n["Total P/L"])}),e.jsx(c,{className:"text-right",children:xe(n["Avg P/L / Sold"])}),e.jsx(c,{className:"text-right text-green-400",children:xe(n.Best)}),e.jsx(c,{className:"text-right text-red-400",children:xe(n.Worst)})]},o)),!r.length&&e.jsx(q,{children:e.jsx(c,{colSpan:8,className:"text-center text-muted-foreground py-6",children:"No data."})})]})]})})]})}function In({lots:t,runs:s}){const a=v.useMemo(()=>new Map(s.map(n=>[n.id,n])),[s]),r=v.useMemo(()=>["ADESA","MANHEIM"].map(o=>{const i=t.filter(y=>{var k;return(((k=a.get(y.run_id))==null?void 0:k.source)??"").toUpperCase()===o}),m=i.filter(y=>y.sold),g=m.map(y=>Bt(y,o)).filter(y=>y!==null),f=m.map(y=>Number(y.auction_fee??0)),j=i.map(y=>y.days_in_inventory).filter(y=>y!=null);return{Source:o,Lots:i.length,Sold:m.length,"Sell-through":i.length?m.length/i.length:0,"Total P/L":Math.round(g.reduce((y,k)=>y+k,0)),"Avg P/L":g.length?Math.round(g.reduce((y,k)=>y+k,0)/g.length):0,"Avg Fee":f.length?Math.round(f.reduce((y,k)=>y+k,0)/f.length):0,"Avg Days In Inv":j.length?Math.round(j.reduce((y,k)=>y+k,0)/j.length):0}}),[t,a]);return e.jsxs(e.Fragment,{children:[e.jsx(Pt,{name:"source-comparison.csv",rows:r}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:[e.jsx("div",{className:"overflow-auto",children:e.jsxs(ke,{children:[e.jsx(Le,{children:e.jsxs(q,{children:[e.jsx(h,{children:"Source"}),e.jsx(h,{className:"text-right",children:"Lots"}),e.jsx(h,{className:"text-right",children:"Sold"}),e.jsx(h,{className:"text-right",children:"Sell-through"}),e.jsx(h,{className:"text-right",children:"Total P/L"}),e.jsx(h,{className:"text-right",children:"Avg P/L / Vehicle"}),e.jsx(h,{className:"text-right",children:"Avg Fee"}),e.jsx(h,{className:"text-right",children:"Avg Days"})]})}),e.jsx(Ce,{children:r.map(n=>e.jsxs(q,{children:[e.jsx(c,{className:"font-medium",children:n.Source}),e.jsx(c,{className:"text-right",children:Je(n.Lots)}),e.jsx(c,{className:"text-right",children:Je(n.Sold)}),e.jsx(c,{className:"text-right",children:is(n["Sell-through"])}),e.jsx(c,{className:`text-right ${n["Total P/L"]>=0?"text-green-400":"text-red-400"}`,children:xe(n["Total P/L"])}),e.jsx(c,{className:"text-right",children:xe(n["Avg P/L"])}),e.jsx(c,{className:"text-right",children:xe(n["Avg Fee"])}),e.jsx(c,{className:"text-right",children:Je(n["Avg Days In Inv"])})]},n.Source))})]})}),e.jsx("div",{className:"h-72",children:e.jsx(gr,{children:e.jsxs(nn,{data:r,children:[e.jsx(fr,{strokeDasharray:"3 3",stroke:"#ffffff20"}),e.jsx(vr,{dataKey:"Source",stroke:"#9FB3C8"}),e.jsx(Os,{stroke:"#9FB3C8"}),e.jsx(jr,{contentStyle:{background:"#0B1F3A",border:"1px solid #ffffff20"}}),e.jsx(_r,{}),e.jsx(ir,{dataKey:"Avg P/L",fill:"#2F80ED"}),e.jsx(ir,{dataKey:"Avg Fee",fill:"#E94560"})]})})})]})]})}function On({lots:t,runs:s,sourceOf:a}){const r=v.useMemo(()=>new Map(s.map(o=>[o.id,o])),[s]),n=v.useMemo(()=>{const o=new Map;return t.forEach(i=>
234{var f;const m=((f=r.get(i.run_id))==null?void 0:f.sale_date)??null;if(!m)return;const g=o.get(m)??{date:m,pl:0,sold:0,noSale:0};if(i.sold){g.sold+=1;const j=Bt(i,a(i));j!==null&&(g.pl+=j)}else i.no_sale&&(g.noSale+=1);o.set(m,g)}),[...o.values()].sort((i,m)=>i.date.localeCompare(m.date)).map(i=>({...i,pl:Math.round(i.pl)}))},[t,r,a]);return e.jsxs(e.Fragment,{children:[e.jsx(Pt,{name:"sale-date-trend.csv",rows:n}),e.jsx("div",{className:"h-80",children:e.jsx(gr,{children:e.jsxs(oa,{data:n,children:[e.jsx(fr,{strokeDasharray:"3 3",stroke:"#ffffff20"}),e.jsx(vr,{dataKey:"date",stroke:"#9FB3C8"}),e.jsx(Os,{yAxisId:"left",stroke:"#9FB3C8"}),e.jsx(Os,{yAxisId:"right",orientation:"right",stroke:"#9FB3C8"}),e.jsx(jr,{contentStyle:{background:"#0B1F3A",border:"1px solid #ffffff20"}}),e.jsx(_r,{}),e.jsx(ir,{yAxisId:"right",dataKey:"sold",stackId:"v",fill:"#2F80ED",name:"Sold"}),e.jsx(ir,{yAxisId:"right",dataKey:"noSale",stackId:"v",fill:"#E94560",name:"No Sale"}),e.jsx(ar,{yAxisId:"left",type:"monotone",dataKey:"pl",stroke:"#34D399",name:"P/L"})]})})})]})}function Un({lots:t,sourceOf:s}){const a=v.useMemo(()=>t.filter(i=>i.sold&&i.floor_price!=null&&i.net_check_to_dealer!=null).map(i=>({floor:Number(i.floor_price),net:Number(i.net_check_to_dealer),source:(s(i)??"").toUpperCase(),desc:os(i),dealer:i.dealer_name??i.dealer_code??"",delta:Number(i.net_check_to_dealer)-Number(i.floor_price)})),[t,s]),r=a.filter(i=>i.source==="ADESA"),n=a.filter(i=>i.source==="MANHEIM"),o=v.useMemo(()=>[...a].sort((i,m)=>Math.abs(m.delta)-Math.abs(i.delta)).slice(0,20).map(i=>({Vehicle:i.desc,Dealer:i.dealer,Source:i.source,Floor:Math.round(i.floor),"Net Check":Math.round(i.net),Delta:Math.round(i.delta)})),[a]);return e.jsxs(e.Fragment,{children:[e.jsx(Pt,{name:"floor-variance.csv",rows:o}),e.jsx("div",{className:"h-72 mb-4",children:e.jsx(gr,{children:e.jsxs(ln,{children:[e.jsx(fr,{stroke:"#ffffff20"}),e.jsx(vr,{dataKey:"floor",name:"Floor",stroke:"#9FB3C8"}),e.jsx(Os,{dataKey:"net",name:"Net Check",stroke:"#9FB3C8"}),e.jsx(jr,{contentStyle:{background:"#0B1F3A",border:"1px solid #ffffff20"},cursor:{strokeDasharray:"3 3"}}),e.jsx(_r,{}),e.jsx(Ur,{name:"ADESA",data:r,fill:"#2F80ED"}),e.jsx(Ur,{name:"Manheim",data:n,fill:"#E94560"})]})})}),e.jsx("div",{className:"overflow-auto",children:e.jsxs(ke,{children:[e.jsx(Le,{children:e.jsxs(q,{children:[e.jsx(h,{children:"Vehicle"}),e.jsx(h,{children:"Dealer"}),e.jsx(h,{children:"Source"}),e.jsx(h,{className:"text-right",children:"Floor"}),e.jsx(h,{className:"text-right",children:"Net Check"}),e.jsx(h,{className:"text-right",children:"Δ"})]})}),e.jsx(Ce,{children:o.map((i,m)=>e.jsxs(q,{children:[e.jsx(c,{children:i.Vehicle}),e.jsx(c,{children:i.Dealer}),e.jsx(c,{children:e.jsx(Pe,{variant:"outline",children:i.Source})}),e.jsx(c,{className:"text-right",children:xe(i.Floor)}),e.jsx(c,{className:"text-right",children:xe(i["Net Check"])}),e.jsx(c,{className:`text-right ${i.Delta>=0?"text-green-400":"text-red-400"}`,children:xe(i.Delta)})]},m))})]})})]})}function Gn({lots:t,sourceOf:s}){const a=v.useMemo(()=>["ADESA","MANHEIM","ALL"].map(n=>{const o=t.filter(j=>j.sold&&j.floor_price&&Number(j.floor_price)>0&&(n==="ALL"||(s(j)??"").toUpperCase()===n));let i=0,m=0,g=0;o.forEach(j=>{const y=Bt(j,s(j));if(y===null)return;const k=Math.abs(y/Number(j.floor_price));k<=.05?i++:k<=.1?m++:g++});const f=i+m+g;return{Group:n,"Sold (measured)":f,"Within ±5%":f?i/f:0,"Within ±10%":f?(i+m)/f:0,">10%":f?g/f:0}}),[t,s]);return e.jsxs(e.Fragment,{children:[e.jsx(Pt,{name:"floor-accuracy.csv",rows:a}),e.jsx("div",{className:"overflow-auto",children:e.jsxs(ke,{children:[e.jsx(Le,{children:e.jsxs(q,{children:[e.jsx(h,{children:"Source"}),e.jsx(h,{className:"text-right",children:"Sold (measured)"}),e.jsx(h,{className:"text-right",children:"Within ±5%"}),e.jsx(h,{className:"text-right",children:"Within ±10%"}),e.jsx(h,{className:"text-right",children:">10%"})]})}),e.jsx(Ce,{children:a.map(r=>e.jsxs(q,{children:[e.jsx(c,{className:"font-medium",children:r.Group}),e.jsx(c,{className:"text-right",children:Je(r["Sold (measured)"])}),e.jsx(c,{className:"text-right",children:is(r["Within ±5%"])}),e.jsx(c,{className:"text-right",children:is(r["Within ±10%"])}),e.jsx(c,{className:"text-right",children:is(r[">10%"])})]},r.Group))})]})})]})}function Bn({lots:t}){const s=v.useMemo(()=>{const a=new Map;t.filter(n=>
234n.no_sale||!n.sold).forEach(n=>{const o=sn(n.floor_price),i=a.get(o)??{band:o,count:0,gapSum:0,gapN:0,runsSum:0,runsN:0,asis:0,struct:0,caution:0};i.count+=1,n.floor_price!=null&&n.highest_bid_amount!=null&&(i.gapSum+=Number(n.floor_price)-Number(n.highest_bid_amount),i.gapN+=1),n.days_in_inventory!=null&&(i.runsSum+=n.days_in_inventory,i.runsN+=1),n.as_is&&(i.asis+=1),n.structural_damage&&(i.struct+=1),(n.condition_codes??"").toLowerCase().includes("caution")&&(i.caution+=1),a.set(o,i)});const r=["$0–5k","$5k–10k","$10k–20k","$20k+","Unknown"];return[...a.values()].map(n=>({"Floor Band":n.band,"No-Sale Lots":n.count,"Avg Bid Gap":n.gapN?Math.round(n.gapSum/n.gapN):0,"Avg Days Inv":n.runsN?Math.round(n.runsSum/n.runsN):0,"AS-IS":n.asis,Structural:n.struct,Caution:n.caution})).sort((n,o)=>r.indexOf(n["Floor Band"])-r.indexOf(o["Floor Band"]))},[t]);return e.jsxs(e.Fragment,{children:[e.jsx(Pt,{name:"no-sale-analysis.csv",rows:s}),e.jsx("div",{className:"overflow-auto",children:e.jsxs(ke,{children:[e.jsx(Le,{children:e.jsxs(q,{children:[e.jsx(h,{children:"Floor Band"}),e.jsx(h,{className:"text-right",children:"No-Sale Lots"}),e.jsx(h,{className:"text-right",children:"Avg Bid Gap"}),e.jsx(h,{className:"text-right",children:"Avg Days Inv"}),e.jsx(h,{className:"text-right",children:"AS-IS"}),e.jsx(h,{className:"text-right",children:"Structural"}),e.jsx(h,{className:"text-right",children:"Caution"})]})}),e.jsx(Ce,{children:s.map((a,r)=>e.jsxs(q,{children:[e.jsx(c,{className:"font-medium",children:a["Floor Band"]}),e.jsx(c,{className:"text-right",children:Je(a["No-Sale Lots"])}),e.jsx(c,{className:"text-right text-red-400",children:xe(a["Avg Bid Gap"])}),e.jsx(c,{className:"text-right",children:Je(a["Avg Days Inv"])}),e.jsx(c,{className:"text-right",children:Je(a["AS-IS"])}),e.jsx(c,{className:"text-right",children:Je(a.Structural)}),e.jsx(c,{className:"text-right",children:Je(a.Caution)})]},r))})]})})]})}function zn({lots:t,sourceOf:s}){const[a,r]=v.useState(null),{ranked:n,lotsByKey:o}=v.useMemo(()=>{const j=new Map,y=new Map;return t.filter(k=>k.sold).forEach(k=>{const C=`${k.year??"?"} ${k.make??"?"} ${k.model??"?"}`,x=j.get(C)??{ymm:C,count:0,pl:0,sums:0};x.count+=1;const A=Bt(k,s(k));A!==null&&(x.pl+=A,x.sums+=1),j.set(C,x);const S=y.get(C)??[];S.push(k),y.set(C,S)}),{ranked:[...j.values()].map(k=>({"Year/Make/Model":k.ymm,Count:k.count,"Total P/L":Math.round(k.pl),"Avg P/L":k.sums?Math.round(k.pl/k.sums):0})),lotsByKey:y}},[t,s]),i=[...n].sort((j,y)=>y["Total P/L"]-j["Total P/L"]).slice(0,20),m=[...n].sort((j,y)=>j["Total P/L"]-y["Total P/L"]).slice(0,20),g=j=>{r({ymm:j,lots:o.get(j)??[]})},f=j=>e.jsx("div",{className:"overflow-auto",children:e.jsxs(ke,{children:[e.jsx(Le,{children:e.jsxs(q,{children:[e.jsx(h,{children:"Year/Make/Model"}),e.jsx(h,{className:"text-right",children:"Count"}),e.jsx(h,{className:"text-right",children:"Total P/L"}),e.jsx(h,{className:"text-right",children:"Avg P/L / Vehicle"})]})}),e.jsx(Ce,{children:j.map((y,k)=>e.jsxs(q,{className:"cursor-pointer hover:bg-white/5",onClick:()=>g(y["Year/Make/Model"]),children:[e.jsx(c,{className:"underline-offset-2 hover:underline",children:y["Year/Make/Model"]}),e.jsx(c,{className:"text-right",children:Je(y.Count)}),e.jsx(c,{className:`text-right ${y["Total P/L"]>=0?"text-green-400":"text-red-400"}`,children:xe(y["Total P/L"])}),e.jsx(c,{className:"text-right",children:xe(y["Avg P/L"])})]},k))})]})});return e.jsxs(e.Fragment,{children:[e.jsx(Pt,{name:"ymm-leaderboard.csv",rows:n}),e.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Top 20 are the highest-P/L groups (best performers); Bottom 20 are the lowest (biggest losses). Click a row to see the individual lots."}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-medium mb-2 text-green-400",children:"Top 20"}),f(i)]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-medium mb-2 text-red-400",children:"Bottom 20"}),f(m)]})]}),e.jsx(Vn,{drill:a,onClose:()=>r(null),sourceOf:s})]})}function Vn({drill:t,onClose:s,sourceOf:a}){return e.jsx(Gs,{open:!!t,onOpenChange:r=>{r||s()},children:e.jsxs(Bs,{className:"",children:[e.jsxs(zs,{children:[e.jsx(Vs,{children:t==null?void 0:t.ymm}),e.jsxs(xr,{children:[(t==null?void 0:t.lots.length)??0," sold lot",((t==null?void 0:t.lots.length)??0)===1?"":"s"," contributing to this group's P/L."]})]}),e.jsx("div",{className:"overflow-auto max-h-[60vh]",children:e.jsxs(ke,{children:[e.jsx(Le,{children:e.jsxs(q,{children:[e.jsx(h,{children:"Dealer"}),e.jsx(h,{children:"Stock #"}),e.jsx(h,{children:"VIN"}),e.jsx(h,{children:"Source"}),e.jsx(h,{className:"text-right",children:"Miles"}),e.jsx(h,{className:"text-right",children:"Floor"}),e.jsx(h,{className:"text-right",children:"Sale Price"}),e.jsx(h,{className:"text-right",children:"Net Check"}),e.jsx(h,{className:"text-right",children:"P/L"})]})}),e.jsx(Ce,{children:t==null?void 0:t.lots.map(r=>{const n=a(r),o=Bt(r,n);return e.jsxs(q,{children:[e.jsx(c,{children:r.dealer_name||r.dealer_code||"—"}),e.jsx(c,{children:r.stock_number||"—"}),e.jsx(c,{className:"font-mono text-xs",children:r.vin||"—"}),e.jsx(c,{children:n||"—"}),e.jsx(c,{className:"text-right",children:Je(r.miles)}),e.jsx(c,{className:"text-right",children:xe(r.floor_price)}),e.jsx(c,{className:"text-right",children:xe(r.sale_price)}),e.jsx(c,{className:"text-right",children:xe(r.net_check_to_dealer)}),e.jsx(c,{className:`text-right ${o!==null&&o>=0?"text-green-400":"text-red-400"}`,children:xe(o)})]},r.id)})})]})})]})})}function qn({lots:t,sourceOf:s}){const a=v.useMemo(()=>{const r=new Map;t.forEach(o=>{const i=rn(o.miles),m=r.get(i)??{band:i,total:0,sold:0,pl:0,sums:0};if(m.total+=1,o.sold){m.sold+=1;const g=Bt(o,s(o));g!==null&&(m.pl+=g,m.sums+=1)}r.set(i,m)});const n=["0–50k","50k–100k","100k–200k","200k+","Unknown"];return[...r.values()].map(o=>({"Mileage Band":o.band,Count:o.total,Sold:o.sold,"Avg P/L":o.sums?Math.round(o.pl/o.sums):0,"Total P/L":Math.round(o.pl)})).sort((o,i)=>n.indexOf(o["Mileage Band"])-n.indexOf(i["Mileage Band"]))},[t,s]);return e.jsxs(e.Fragment,{children:[e.jsx(Pt,{name:"mileage-band.csv",rows:a}),e.jsx("div",{className:"overflow-auto",children:e.jsxs(ke,{children:[e.jsx(Le,{children:e.jsxs(q,{children:[e.jsx(h,{children:"Mileage Band"}),e.jsx(h,{className:"text-right",children:"Count"}),e.jsx(h,{className:"text-right",children:"Sold"}),e.jsx(h,{className:"text-right",children:"Avg P/L / Vehicle"}),e.jsx(h,{className:"text-right",children:"Total P/L"})]})}),e.jsx(Ce,{children:a.map((r,n)=>e.jsxs(q,{children:[e.jsx(c,{className:"font-medium",children:r["Mileage Band"]}),e.jsx(c,{className:"text-right",children:Je(r.Count)}),e.jsx(c,{className:"text-right",children:Je(r.Sold)}),e.jsx(c,{className:"text-right",children:xe(r["Avg P/L"])}),e.jsx(c,{className:`text-right ${r["Total P/L"]>=0?"text-green-400":"text-red-400"}`,children:xe(r["Total P/L"])})]},n))})]})})]})}function Wn({lots:t,sourceOf:s}){const a=v.useMemo(()=>[{name:"AS-IS",test:n=>n.as_is},{name:"Structural",test:n=>n.structural_damage},{name:"100k+ mi",test:n=>n.over_100k},{name:"200k+ mi",test:n=>n.over_200k},{name:"Caution",test:n=>(n.condition_codes??"").toLowerCase().includes("caution")},{name:"Clean (no flags)",test:n=>!n.as_is&&!n.structural_damage&&!n.over_100k&&!n.over_200k&&!(n.condition_codes??"").toLowerCase().includes("caution")}].map(n=>{const o=t.filter(m=>m.sold&&n.test(m)),i=o.map(m=>Bt(m,s(m))).filter(m=>m!==null);return{Flag:n.name,"Sold Count":o.length,"Avg P/L":i.length?Math.round(i.reduce((m,g)=>m+g,0)/i.length):0,"Total P/L":Math.round(i.reduce((m,g)=>m+g,0))}}),[t,s]);return e.jsxs(e.Fragment,{children:[e.jsx(Pt,{name:"condition-impact.csv",rows:a}),e.jsx("div",{className:"overflow-auto",children:e.jsxs(ke,{children:[e.jsx(Le,{children:e.jsxs(q,{children:[e.jsx(h,{children:"Flag"}),e.jsx(h,{className:"text-right",children:"Sold Count"}),e.jsx(h,{className:"text-right",children:"Avg P/L / Vehicle"}),e.jsx(h,{className:"text-right",children:"Total P/L"})]})}),e.jsx(Ce,{children:a.map(r=>e.jsxs(q,{children:[e.jsx(c,{className:"font-medium",children:r.Flag}),e.jsx(c,{className:"text-right",children:Je(r["Sold Count"])}),e.jsx(c,{className:`text-right ${r["Avg P/L"]>=0?"text-green-400":"text-red-400"}`,children:xe(r["Avg P/L"])}),e.jsx(c,{className:`text-right ${r["Total P/L"]>=0?"text-green-400":"text-red-400"}`,children:xe(r["Total P/L"])})]},r.Flag))})]})})]})}function Yn({lots:t}){const s=v.useMemo(()=>t.filter(a=>!a.sold&&(a.days_in_inventory??0)>=60).map(a=>({Vehicle:os(a),VIN:a.vin??"",Stock:a.stock_number??"",Dealer:a.dealer_name??a.dealer_code??"",Miles:a.miles,Floor:a.floor_price?Math.round(Number(a.floor_price)):null,"High Bid":a.highe
234st_bid_amount?Math.round(Number(a.highest_bid_amount)):null,"Days In Inv":a.days_in_inventory})).sort((a,r)=>(r["Days In Inv"]??0)-(a["Days In Inv"]??0)),[t]);return e.jsxs(e.Fragment,{children:[e.jsx(Pt,{name:"aging-times-run.csv",rows:s,children:e.jsx("span",{className:"text-xs text-muted-foreground",children:"Unsold lots with 60+ days in inventory."})}),e.jsx("div",{className:"overflow-auto",children:e.jsxs(ke,{children:[e.jsx(Le,{children:e.jsxs(q,{children:[e.jsx(h,{children:"Vehicle"}),e.jsx(h,{children:"Dealer"}),e.jsx(h,{className:"text-right",children:"Miles"}),e.jsx(h,{className:"text-right",children:"Floor"}),e.jsx(h,{className:"text-right",children:"High Bid"}),e.jsx(h,{className:"text-right",children:"Days"})]})}),e.jsxs(Ce,{children:[s.map((a,r)=>e.jsxs(q,{children:[e.jsx(c,{children:a.Vehicle}),e.jsx(c,{children:a.Dealer}),e.jsx(c,{className:"text-right",children:Je(a.Miles)}),e.jsx(c,{className:"text-right",children:xe(a.Floor)}),e.jsx(c,{className:"text-right",children:xe(a["High Bid"])}),e.jsx(c,{className:"text-right",children:Je(a["Days In Inv"])})]},r)),!s.length&&e.jsx(q,{children:e.jsx(c,{colSpan:6,className:"text-center text-muted-foreground py-6",children:"No aging lots."})})]})]})})]})}function Hn({lots:t,runById:s,resolveDealer:a}){const[r,n]=v.useState("2"),[o,i]=v.useState(null),m=v.useMemo(()=>{const N=new Map;t.forEach(L=>{const _=(L.vin??"").trim();if(!_)return;const H=s.get(L.run_id);N.set(_,[...N.get(_)??[],{vin:_,lot:L,run:H,sale_date:(H==null?void 0:H.sale_date)??null,source:(H==null?void 0:H.source)??null}])});const M=[];return N.forEach((L,_)=>{L.length<2||(L.sort((H,F)=>(H.sale_date??"").localeCompare(F.sale_date??"")),M.push({vin:_,entries:L}))}),M},[t,s]),g=Number(r)||2,f=v.useMemo(()=>m.filter(N=>N.entries.length>=g),[m,g]),j=v.useMemo(()=>f.reduce((N,M)=>Math.max(N,M.entries.length),0),[f]),y=N=>{const M=["th","st","nd","rd"],L=N%100;return N+(M[(L-20)%10]??M[L]??M[0])},k=v.useMemo(()=>f.map(({vin:N,entries:M})=>{const L=M[M.length-1],_=M.find(p=>p.lot.sold),H=a(L.lot).displayName,F={};for(let p=0;p<j;p++){const u=M[p],w=`${y(p+1)} Floor`,T=`${y(p+1)} High Bid`,$=`${y(p+1)} Run Date`;F[w]=(u==null?void 0:u.lot.floor_price)!=null?Math.round(Number(u.lot.floor_price)):null,F[T]=(u==null?void 0:u.lot.highest_bid_amount)!=null?Math.round(Number(u.lot.highest_bid_amount)):null,F[$]=(u==null?void 0:u.sale_date)??null}return{vin:N,entries:M,Vehicle:os(L.lot),VIN:N,Dealer:H,"Times Run":M.length,"Last Date":L.sale_date,...F,Status:_?"Sold":"Still No-Sale","Final Sale Price":(_==null?void 0:_.lot.sale_price)!=null?Math.round(Number(_.lot.sale_price)):null}}).sort((N,M)=>M["Times Run"]-N["Times Run"]||(M["Last Date"]??"").localeCompare(N["Last Date"]??"")),[f,a,j]),C=k.map(({entries:N,vin:M,...L})=>L),x=v.useMemo(()=>{const N=f.length,M=f.reduce((F,p)=>F+p.entries.length,0),L=N?M/N:0,_=f.filter(F=>F.entries.some(p=>p.lot.sold)).length,H=N?_/N:0;return{repeatVins:N,totalRuns:M,avgTimes:L,pctSold:H}},[f]),A=o?f.find(N=>N.vin===o):null,S=Array.from({length:j},(N,M)=>M),X=5+j+2;return e.jsxs(e.Fragment,{children:[e.jsxs(Pt,{name:"repeat-vin-bid-trends.csv",rows:C,children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Min runs"}),e.jsxs(It,{value:r,onValueChange:n,children:[e.jsx(Ot,{className:"h-8 w-24",children:e.jsx(Ut,{})}),e.jsxs(Gt,{children:[e.jsx(Te,{value:"2",children:"2+"}),e.jsx(Te,{value:"3",children:"3+"}),e.jsx(Te,{value:"4",children:"4+"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3 mb-3",children:[e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/20 p-3",children:[e.jsx("div",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Repeat VINs"}),e.jsx("div",{className:"text-xl font-semibold mt-1",children:Je(x.repeatVins)})]}),e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/20 p-3",children:[e.jsx("div",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Total Repeat Runs"}),e.jsx("div",{className:"text-xl font-semibold mt-1",children:Je(x.totalRuns)})]}),e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/20 p-3",children:[e.jsx("div",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Avg Times Run"}),e.jsx("div",{className:"text-xl font-semibold mt-1",children:x.avgTimes.toFixed(2)})]}),e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/20 p-3",children:[e.jsx("div",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"% Eventually Sold"}),e.jsx("div",{className:"text-xl font-semibold mt-1 text-sky-300",children:is(x.pctSold)})]})]}),e.jsx("div",{className:"overflow-auto",children:e.jsxs(ke,{children:[e.jsx(Le,{children:e.jsxs(q,{children:[e.jsx(h,{children:"Vehicle"}),e.jsx(h,{children:"VIN"}),e.jsx(h,{children:"Dealer"}),e.jsx(h,{className:"text-right",children:"Runs"}),S.map(N=>e.jsxs(h,{className:"text-right whitespace-nowrap",children:[y(N+1)," Run",e.jsx("div",{className:"text-[10px] font-normal text-muted-foreground",children:"Floor / High Bid"})]},N)),e.jsx(h,{children:"Status"}),e.jsx(h,{className:"text-right",children:"Final Sale"})]})}),e.jsxs(Ce,{children:[k.map(N=>e.jsxs(q,{className:"cursor-pointer hover:bg-white/5",onClick:()=>i(N.vin),children:[e.jsx(c,{children:N.Vehicle}),e.jsx(c,{className:"font-mono text-xs",children:N.VIN}),e.jsx(c,{children:N.Dealer}),e.jsx(c,{className:"text-right",children:N["Times Run"]}),S.map(M=>{const L=N[`${y(M+1)} Floor`],_=N[`${y(M+1)} High Bid`],H=N[`${y(M+1)} Run Date`],F=M<N["Times Run"];return e.jsx(c,{className:"text-right whitespace-nowrap",children:F?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-amber-300",children:L!=null?xe(L):"—"}),e.jsx("div",{className:"text-sky-300",children:_!=null?xe(_):"—"}),H&&e.jsx("div",{className:"text-[10px] text-muted-foreground",children:Es(H)})]}):""},M)}),e.jsx(c,{children:e.jsx(Pe,{variant:N.Status==="Sold"?"default":"secondary",children:N.Status})}),e.jsx(c,{className:"text-right",children:xe(N["Final Sale Price"])})]}
234,N.vin)),!k.length&&e.jsx(q,{children:e.jsx(c,{colSpan:X,className:"text-center text-muted-foreground py-6",children:"No repeat VINs in this range."})})]})]})}),e.jsx(Gs,{open:!!A,onOpenChange:N=>!N&&i(null),children:e.jsx(Bs,{className:"",children:A&&e.jsxs(e.Fragment,{children:[e.jsxs(zs,{children:[e.jsx(Vs,{children:os(A.entries[A.entries.length-1].lot)}),e.jsxs(xr,{className:"font-mono text-xs",children:["VIN ",A.vin," · ",A.entries.length," runs"]})]}),e.jsx("div",{className:"h-64 w-full",children:e.jsx(gr,{width:"100%",height:"100%",children:e.jsxs(oa,{data:A.entries.map(N=>({date:Es(N.sale_date),Floor:N.lot.floor_price!=null?Number(N.lot.floor_price):null,"High Bid":N.lot.highest_bid_amount!=null?Number(N.lot.highest_bid_amount):null,"Sale Price":N.lot.sold&&N.lot.sale_price!=null?Number(N.lot.sale_price):null,source:N.source,dealer:N.lot.dealer_name??N.lot.dealer_code??"",result:N.lot.sold?"Sold":N.lot.no_sale?"No-Sale":"—"})),children:[e.jsx(fr,{strokeDasharray:"3 3",stroke:"#ffffff20"}),e.jsx(vr,{dataKey:"date",tick:{fontSize:11},stroke:"#94a3b8"}),e.jsx(Os,{tick:{fontSize:11},stroke:"#94a3b8",tickFormatter:N=>`$${(N/1e3).toFixed(0)}k`}),e.jsx(jr,{contentStyle:{background:"#0f172a",border:"1px solid #ffffff30",borderRadius:8},formatter:N=>N==null?"—":xe(N)}),e.jsx(_r,{wrapperStyle:{fontSize:12}}),e.jsx(ar,{type:"monotone",dataKey:"Floor",stroke:"#fbbf24",strokeWidth:2,dot:!0,connectNulls:!0}),e.jsx(ar,{type:"monotone",dataKey:"High Bid",stroke:"#38bdf8",strokeWidth:2,dot:!0,connectNulls:!0}),e.jsx(ar,{type:"monotone",dataKey:"Sale Price",stroke:"#34d399",strokeWidth:2,dot:!0,connectNulls:!0})]})})}),e.jsx("div",{className:"overflow-auto",children:e.jsxs(ke,{children:[e.jsx(Le,{children:e.jsxs(q,{children:[e.jsx(h,{children:"Date"}),e.jsx(h,{children:"Source"}),e.jsx(h,{children:"Dealer"}),e.jsx(h,{className:"text-right",children:"Floor"}),e.jsx(h,{className:"text-right",children:"High Bid"}),e.jsx(h,{className:"text-right",children:"Sale Price"}),e.jsx(h,{children:"Result"})]})}),e.jsx(Ce,{children:A.entries.map((N,M)=>e.jsxs(q,{children:[e.jsx(c,{children:Es(N.sale_date)}),e.jsx(c,{children:N.source??"—"}),e.jsx(c,{children:N.lot.dealer_name??N.lot.dealer_code??"—"}),e.jsx(c,{className:"text-right",children:xe(N.lot.floor_price)}),e.jsx(c,{className:"text-right",children:xe(N.lot.highest_bid_amount)}),e.jsx(c,{className:"text-right",children:N.lot.sold?xe(N.lot.sale_price):"—"}),e.jsx(c,{children:e.jsx(Pe,{variant:N.lot.sold?"default":"secondary",children:N.lot.sold?"Sold":N.lot.no_sale?"No-Sale":"—"})})]},M))})]})})]})})})]})}function Kn({lots:t,aliases:s,sourceOf:a}){const r=v.useMemo(()=>{const n=new Set;s.forEach(i=>{i.dealer_code&&n.add(`C:${i.dealer_code.toUpperCase()}`),i.dealer_name&&n.add(`N:${i.dealer_name.toUpperCase()}`)});const o=new Map;return t.forEach(i=>{const m=i.dealer_code?`C:${i.dealer_code.toUpperCase()}`:"",g=i.dealer_name?`N:${i.dealer_name.toUpperCase()}`:"";if(m&&n.has(m)||g&&n.has(g))return;const f=m||g||"UNKNOWN",j=o.get(f)??{code:i.dealer_code??"",name:i.dealer_name??"Unknown",count:0,pl:0};if(j.count+=1,i.sold){const y=Bt(i,a(i));y!==null&&(j.pl+=y)}o.set(f,j)}),[...o.values()].map(i=>({Code:i.code,Name:i.name,Lots:i.count,"Total P/L":Math.round(i.pl)})).sort((i,m)=>m.Lots-i.Lots)},[t,s,a]);return e.jsxs(e.Fragment,{children:[e.jsx(Pt,{name:"unmapped-sellers.csv",rows:r}),e.jsx("div",{className:"overflow-auto",children:e.jsxs(ke,{children:[e.jsx(Le,{children:e.jsxs(q,{children:[e.jsx(h,{children:"Code"}),e.jsx(h,{children:"Name"}),e.jsx(h,{className:"text-right",children:"Lots"}),e.jsx(h,{className:"text-right",children:"Total P/L"})]})}),e.jsxs(Ce,{children:[r.map((n,o)=>e.jsxs(q,{children:[e.jsx(c,{className:"font-mono text-xs",children:n.Code}),e.jsx(c,{children:n.Name}),e.jsx(c,{className:"text-right",children:Je(n.Lots)}),e.jsx(c,{className:`text-right ${n["Total P/L"]>=0?"text-green-400":"text-red-400"}`,children:xe(n["Total P/L"])})]},o)),!r.length&&e.jsx(q,{children:e.jsx(c,{colSpan:4,className:"text-center text-muted-foreground py-6",children:"All sellers are mapped. 🎉"})})]})]})})]})}function Qn({lots:t,runs:s}){var A;const a=s.filter(S=>t.some(X=>X.run_id===S.id)),[r,n]=v.useState(((A=a[0])==null?void 0:A.id)??"");v.useEffect(()=>{!r&&a[0]&&n(a[0].id)},[a,r]);const o=s.find(S=>S.id===r),i=v.useMemo(()=>t.filter(S=>S.run_id===r),[t,r]),m=i.filter(S=>S.sold),g=i.filter(S=>!S.sold),f=m.map(S=>({l:S,p:Bt(S,o==null?void 0:o.source)})).filter(S=>S.p!==null),j=[...f].sort((S,X)=>X.p-S.p).slice(0,10),y=[...f].sort((S,X)=>S.p-X.p).slice(0,10),k=f.reduce((S,X)=>S+X.p,0),C=f.map(({l:S,p:X})=>({Vehicle:os(S),VIN:S.vin,Dealer:S.dealer_name??S.dealer_code,Floor:S.floor_price,"Net Check":S.net_check_to_dealer,"P/L":X})),x=S=>S.map(({l:X,p:N},M)=>e.jsxs(q,{children:[e.jsx(c,{children:os(X)}),e.jsx(c,{className:"text-muted-foreground text-xs",children:X.dealer_name??X.dealer_code}),e.jsx(c,{className:"text-right",children:xe(X.floor_price)}),e.jsx(c,{className:"text-right",children:xe(X.net_check_to_dealer)}),e.jsx(c,{className:`text-right ${N>=0?"text-green-400":"text-red-400"}`,children:xe(N)})]},M));return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between mb-3 gap-2 flex-wrap",children:[e.jsxs(It,{value:r,onValueChange:n,children:[e.jsx(Ot,{className:"h-8 w-72",children:e.jsx(Ut,{placeholder:"Select a run…"})}),e.jsx(Gt,{children:a.map(S=>e.jsxs(Te,{value:S.id,children:[Es(S.sale_date)," — ",S.source," (",S.total_lots," lots)"]},S.id))})]}),e.jsx(xa,{name:`run-recap-${r.slice(0,8)}.csv`,rows:C})]}),o&&e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3 mb-4",children:[e.jsx($e,{className:"bg-white/[0.03] border-white/10",children:e.jsxs(Ae,{className:"p-3",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Sale Date"}),e.jsx("div",{className:"text-lg font-semibold",children:Es(o.sale_date)})]})}),e.jsx($e,{className:"bg-white/[0.03] border-white/10",children:e.jsxs(Ae,{className:"p-3",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Source"}),e.jsx("div",{className:"text-lg font-semibold",children:o.source})]})}),e.jsx($e,{className:"bg-white/[0.03] border-white/10",children:e.jsxs(Ae,{className:"p-3",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Sold / Total"}),e.jsxs("div",{className:"text-lg font-semibold",children:[o.sold_lots," / ",o.total_lots]})]})}),e.jsx($e,{className:"bg-white/[0.03] border-white/10",children:e.jsxs(Ae,{className:"p-3",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Net P/L"}),e.jsx("div",{className:`text-lg font-semibold ${k>=0?"text-green-400":"text-red-400"}`,children:xe(Math.round(k))})]})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("h4",{className:"text-sm font-medium mb-2 text-green-400",children:"Top 10 Wins"}),e.jsx("div",{className:"overflow-auto",children:e.jsxs(ke,{children:[e.jsx(Le,{children:e.jsxs(q,{children:[e.jsx(h,{children:"Vehicle"}),e.jsx(h,{children:"Dealer"}),e.jsx(h,{className:"text-right",children:"Floor"}),e.jsx(h,{className:"text-right",children:"Net"}),e.jsx(h,{className:"text-right",children:"P/L"})]})}),e.jsx(Ce,{children:x(j)})]})})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h4",{className:"text-sm font-medium mb-2 text-red-400",children:"Bottom 10 
234Losses"}),e.jsx("div",{className:"overflow-auto",children:e.jsxs(ke,{children:[e.jsx(Le,{children:e.jsxs(q,{children:[e.jsx(h,{children:"Vehicle"}),e.jsx(h,{children:"Dealer"}),e.jsx(h,{className:"text-right",children:"Floor"}),e.jsx(h,{className:"text-right",children:"Net"}),e.jsx(h,{className:"text-right",children:"P/L"})]})}),e.jsx(Ce,{children:x(y)})]})})]})]}),e.jsxs("div",{className:"mt-4",children:[e.jsxs("h4",{className:"text-sm font-medium mb-2",children:["No-Sale Lots (",g.length,")"]}),e.jsx("div",{className:"overflow-auto",children:e.jsxs(ke,{children:[e.jsx(Le,{children:e.jsxs(q,{children:[e.jsx(h,{children:"Vehicle"}),e.jsx(h,{children:"Dealer"}),e.jsx(h,{className:"text-right",children:"Floor"}),e.jsx(h,{className:"text-right",children:"High Bid"})]})}),e.jsxs(Ce,{children:[g.map((S,X)=>e.jsxs(q,{children:[e.jsx(c,{children:os(S)}),e.jsx(c,{className:"text-xs text-muted-foreground",children:S.dealer_name??S.dealer_code}),e.jsx(c,{className:"text-right",children:xe(S.floor_price)}),e.jsx(c,{className:"text-right",children:xe(S.highest_bid_amount)})]},X)),!g.length&&e.jsx(q,{children:e.jsx(c,{colSpan:4,className:"text-center text-muted-foreground py-6",children:"No no-sale lots."})})]})]})})]})]})}const ze=(t,s="—")=>{if(t==null||!Number.isFinite(t))return s;const a=Math.round(t),r=Math.abs(a).toLocaleString("en-US");return a<0?`-$${r}`:`$${r}`},bt=(t,s=1,a="—")=>t==null||!Number.isFinite(t)?a:`${(t*100).toFixed(s)}%`,Ve=(t,s=1,a="—")=>t==null||!Number.isFinite(t)?a:t.toFixed(s),le=(t,s="—")=>t==null||!Number.isFinite(t)?s:Math.round(t).toLocaleString("en-US"),js=(t,s="—")=>t==null||!Number.isFinite(t)?s:t.toFixed(3),Tt=t=>typeof t=="number"&&Number.isFinite(t)&&t<0,Vr=t=>[t.make,t.model,t.trim].filter(Boolean).join(" "),Tr={dealershipLabel:["dealership","store","dealer","dealership name","dealer name"],make:["make","vehicle make"],model:["model","vehicle model"],trim:["series","trim","trim/series","series/trim","trim level"],vehiclesSold:["vehicles sold","3m sold","sold","units sold","vehicle sold","retail units"],projectedSales:["projected sales count","projected sales","projected"],priorYearSold:["vehicles sold last year","prior-year sold","prior year sold","last year sold","ly sold"],salesDeltaText:["sales count delta","sales delta","delta"],salesDeltaPct:["sales count delta pct","sales change"],averageAge:["age at sale avg.","age at sale avg","avg. days","avg days","average age","age at sale average","avg. age at sale"],ptm:["vauto ptm avg.","vauto ptm avg","ptm","ptm avg"],averageListPrice:["vauto list price avg.","vauto list price avg","avg. list","avg list price","average list price","list price avg"],averageDiscount:["vehicle discount avg.","vehicle discount avg","avg. discount","average discount","discount avg"],averageFrontGross:["front gross avg.","front gross avg","avg. front","average front gross","front gross average","avg front"],averageBackGross:["back gross avg.","back gross avg","avg. back","average back gross","avg back"],tradeOverUnder:["trade over/under avg.","trade over/under avg","trade o/u","trade over under"],averageTotalGross:["total gross avg.","total gross avg","avg. total","average total gross","total gross average","avg total"]},Dr=["dealershipLabel","make","model","trim","vehiclesSold","averageAge","averageFrontGross","averageTotalGross"],pa={dealershipLabel:"Dealership",make:"Make",model:"Model",trim:"Series / Trim",vehiclesSold:"Vehicles sold",averageAge:"Age at sale average",averageFrontGross:"Front gross average",averageTotalGross:"Total gross average"},qs=t=>String(t??"").replace(/^\uFEFF/,"").replace(/["'`]/g,"").replace(/\s+/g," ").trim().toLowerCase(),mt=t=>{if(t==null)return null;const s=String(t).replace(/\s+/g," ").trim();return s===""?null:s};function Ke(t){if(t==null||t==="")return null;if(typeof t=="number")return Number.isFinite(t)?t:null;let s=String(t).replace(/[\u2191\u2193\u25B2\u25BC]/g,"").replace(/\s+/g," ").trim();if(s===""||s==="-"||s==="—"||s==="n/a"||s.toLowerCase()==="na")return null;let a=!1;/^\(.*\)$/.test(s)&&(a=!0,s=s.slice(1,-1)),s.startsWith("-")&&(a=!0,s=s.slice(1));const r=s.includes("%");s=s.replace(/[$,%\s]/g,"");const n=Number(s);if(!Number.isFinite(n))return null;const o=r?n/100:n;
234return a?-o:o}function Jn(t){const s=String(t??""),a=Ke(s);if(a===null)return null;const r=s.includes("▼")||s.includes("↓"),n=Math.abs(a);return r?-n:n}const Ht=t=>!!t&&t.toLowerCase()==="total";function Xn(t,s,a,r){return Ht(t)?"overall":t?Ht(s)?"dealership":s?Ht(a)?"make":a?!r||Ht(r)?"model":"trim":null:null:null}function ga(t,s){const a=t.map(n=>mt(n)??""),r={};return a.forEach((n,o)=>{const i=qs(n);i&&Object.keys(Tr).forEach(m=>{r[m]===void 0&&Tr[m].includes(i)&&(r[m]=o)})}),s&&Object.entries(s).forEach(([n,o])=>{o>=0&&(r[n]=o)}),{map:r,headers:a}}function Fr(t){for(let s=0;s<Math.min(t.length,25);s+=1)if(t[s].map(qs).filter(n=>n&&Object.values(Tr).some(o=>o.includes(n))).length>=3)return s;return-1}function Zn(t,s,a){const r=j=>{const y=s[j];return y===void 0?void 0:t[y]},n=mt(r("dealershipLabel"))??a,o=mt(r("make")),i=mt(r("model")),m=mt(r("trim")),g=Xn(n,o,i,m);if(!g)return null;const f=r("salesDeltaText");return{rowLevel:g,dealershipLabel:n,make:Ht(o)?null:o,model:Ht(i)?null:i,trim:Ht(m)?null:m,vehiclesSold:Ke(r("vehiclesSold")),projectedSales:Ke(r("projectedSales")),priorYearSold:Ke(r("priorYearSold")),salesDeltaText:mt(f),salesDeltaPct:f===void 0?null:Jn(f),averageAge:Ke(r("averageAge")),ptm:Ke(r("ptm")),averageListPrice:Ke(r("averageListPrice")),averageDiscount:Ke(r("averageDiscount")),averageFrontGross:Ke(r("averageFrontGross")),averageBackGross:Ke(r("averageBackGross")),tradeOverUnder:Ke(r("tradeOverUnder")),averageTotalGross:Ke(r("averageTotalGross"))}}const el="Unknown",qr={dealershipLabel:["dealership","store","dealer","dealer name","dealership name"],stockNumber:["stock number","stock #","stock","stock no","stocknumber"],vin:["vin","vin number","vehicle identification number"],modelYear:["model year","year","vehicle year"],make:["make","vehicle make"],model:["model","vehicle model"],trim:["series","trim","series/trim","trim level"],soldDate:["sold date","sale date","date sold","delivery date"],daysInInventory:["days in inventory","days in stock","days to sale","age at sale","days"],priceToMarket:["price to market","vauto ptm","ptm","price to market %"],listPrice:["list price","vauto list price","asking price"],transactionPrice:["transaction price","sale price","selling price","sold price"],vehicleDiscount:["vehicle discount","discount"],frontGross:["front gross","front end gross"],backGross:["back gross","back end gross","f&i gross"],tradeOverUnder:["trade over/under","trade over under","trade o/u","trade allowance over/under"],source:["source","vehicle source","acquisition source","inventory source","purchase source","stock type","acquired from","how acquired","acquisition type","inventory type"],totalGross:["total gross","total gross profit"]};function fa(t){const s={};return t.forEach((a,r)=>{const n=qs(a);n&&Object.keys(qr).forEach(o=>{s[o]===void 0&&qr[o].includes(n)&&(s[o]=r)})}),s}function tl(t){const s=fa(t);return s.soldDate!==void 0&&(s.vin!==void 0||s.stockNumber!==void 0)}function sl(t){if(t==null)return null;if(typeof t=="number"&&Number.isFinite(t)&&t>2e4&&t<6e4){const o=Date.UTC(1899,11,30)+t*864e5;return new Date(o).toISOString().slice(0,10)}const s=String(t).trim();if(!s)return null;const a=/^(\d{4})-(\d{1,2})-(\d{1,2})/.exec(s);if(a)return`${a[1]}-${a[2].padStart(2,"0")}-${a[3].padStart(2,"0")}`;const r=/^(\d{1,2})[/-](\d{1,2})[/-](\d{2,4})/.exec(s);if(r)return`${r[3].length===2?`20${r[3]}`:r[3]}-${r[1].padStart(2,"0")}-${r[2].padStart(2,"0")}`;const n=Date.parse(s);return Number.isFinite(n)?new Date(n).toISOString().slice(0,10):null}function rl(t,s){const a=f=>{const j=s[f];return j===void 0?void 0:t[j]},r=mt(a("dealershipLabel"));if(!r||Ht(r))return null;const n=sl(a("soldDate")),o=mt(a("make")),i=mt(a("model"));if(!o||!i)return null;const m=Ke(a("tradeOverUnder")),g=mt(a("trim"));return{dealershipLabel:r,stockNumber:mt(a("stockNumber")),vin:mt(a("vin")),modelYear:Ke(a("modelYear")),make:o,model:i,trim:g&&!Ht(g)?g:"Unknown",soldDate:n,daysInInventory:Ke(a("daysInInventory")),priceToMarket:Ke(a("priceToMarket")),listPrice:Ke(a("listPrice")),transactionPrice:Ke(a("transactionPrice")),vehicleDiscount:Ke(a("vehicleDiscount")),frontGross:Ke(a("frontGross")),backGross:Ke(a("backGross")),tradeOverUnder:m,totalGross:Ke(a("totalGross")),isTrade:m!==null&&m!==0,source:mt(a("source"))||el}}function al(t,s){const a=fa(t[s]??[]),r=[];let n=0;for(let o=s+1;o<t.length;o+=1){const i=t[o];if(!i||i.every(g=>g==null||String(g).trim()===""))continue;const m=rl(i,a);m?r.push(m):n+=1}return{records:r,skipped:n}}function nl(t){const s=new Uint8Array(t);if(s.length>=2&&s[0]===255&&s[1]===254)return new TextDecoder("utf-16le").decode(t);if(s.length>=2&&s[0]===254&&s[1]===255)return new TextDecoder("utf-16be").decode(t);const a=s.subarray(0,Math.min(s.length,4e3));let r=0;for(const n of a)n===0&&(r+=1);return r>a.length/4?new TextDecoder(a[0]===0?"utf-16be":"utf-16le").decode(t):null}async function va(t){const s=await t.arrayBuffer();if(/\.(csv|txt|tsv)$/i.test(t.name)){const r=nl(s)??new TextDecoder("utf-8").decode(s);return Gr(r,{type:"string",cellDates:!1,raw:!1})}return Gr(s,{type:"array",cellDates:!1,raw:!1})}function Ns(t,s){const a=t.Sheets[s];return a?dn.sheet_to_json(a,{header:1,raw:!1,defval:null}):[]}function ll(t){return t.SheetNames.map(s=>{const a=Ns(t,s),r=Fr(a);return{name:s,headerRowIndex:r,headers:r>=0?a[r].map(n=>mt(n)??""):[]}})}const Wr=["source data","source","raw data","sold data"],il=["aggressive sourcing","aggressively source"];function nr(t,s){return t.SheetNames.find(r=>s.includes(qs(r)))??null}function Yr(t){const s=nr(t,il);
234if(!s)return[];const a=Ns(t,s),r=Fr(a);if(r<0)return[];const{map:n}=ga(a[r]),o=[];for(let i=r+1;i<a.length;i+=1){const m=a[i],g=mt(n.make!==void 0?m[n.make]:null),f=mt(n.model!==void 0?m[n.model]:null),j=mt(n.trim!==void 0?m[n.trim]:null);g&&f&&j&&!Ht(g)&&o.push({make:g,model:f,trim:j})}return o}const Hr=[{make:"Chevrolet",model:"Express 3500",trim:"Work Van"},{make:"Ford",model:"Transit-250",trim:"Base"},{make:"Kia",model:"Forte",trim:"LXS"},{make:"Ford",model:"F-150",trim:"Raptor"},{make:"Ford",model:"F-350SD",trim:"Lariat"},{make:"Ford",model:"Bronco Sport",trim:"Outer Banks"},{make:"Ford",model:"Mustang",trim:"GT Premium"},{make:"Ford",model:"F-150",trim:"XL"},{make:"Ford",model:"Escape",trim:"SEL"},{make:"Cadillac",model:"XT5",trim:"Premium Luxury"}],_s=(t,s,a)=>[t,s,a].map(r=>(r??"").toLowerCase().replace(/\s+/g," ").trim()).filter((r,n)=>n<2||r!=="").join("|");async function ol(t,s={}){var _e,ue;const a=[],r=[],n=t.name.toLowerCase();if(!/\.(xlsx|xls|csv)$/.test(n))return xs(t.name,["Unsupported file type. Upload an .xlsx, .xls or .csv file."]);let o;try{o=await va(t)}catch{return xs(t.name,["The file could not be read. It may be corrupt or password protected."])}if(!o.SheetNames.length)return xs(t.name,["The workbook is empty."]);const i=[...o.SheetNames],m=nr(o,Wr)??o.SheetNames[0],g=nr(o,Wr)!==null,f=Ns(o,m);if(!f.length)return xs(t.name,[`Worksheet "${m}" contains no rows.`]);const j=Fr(f);if(j<0&&!s.columnOverrides)return xs(t.name,["The column headings could not be recognized. Use the column mapping screen to identify them."]);const y=j>=0?f[j]:f[0];if(!s.columnOverrides&&tl(y)){const{records:D,skipped:P}=al(f,j>=0?j:0);if(!D.length)return xs(t.name,["No sold vehicles were found in the report."]);const U=D.filter(I=>!I.soldDate).length;U&&a.push(`${U} sold vehicle(s) have no sold date and were left out of the date ranges.`);const ie=new Map;D.forEach(I=>{const he=(I.vin??I.stockNumber??"").toLowerCase();he&&ie.set(he,(ie.get(he)??0)+1)});const z=[...ie.values()].filter(I=>I>1).length;z&&a.push(`${z} vehicle identification number(s) appear more than once — each sale is still counted separately.`),P&&a.push(`${P} row(s) were skipped because they carried no make and model.`);const G=D.filter(I=>I.soldDate).map(I=>I.soldDate).sort();return{filename:t.name,dealershipLabel:D[0].dealershipLabel,reportPeriodLabel:null,periodKey:"custom",periodMonths:null,reportStartDate:G[0]??null,reportEndDate:G[G.length-1]??null,importMode:"detail",sheetsFound:i,records:D,rows:[],modelRows:[],trimRows:[],excludedRows:P,totalsRow:null,warnings:a,errors:r,approvedOrder:Yr(o)}}const{map:k,headers:C}=ga(y,s.columnOverrides),x=C.filter((D,P)=>D&&C.indexOf(D)!==P);x.length&&a.push(`Duplicate column headings found: ${[...new Set(x)].join(", ")}.`);const A=Dr.filter(D=>k[D]===void 0);A.length&&r.push(`Required columns could not be identified: ${A.map(D=>pa[D]).join(", ")}.`);const S=[];let X=0;for(let D=(j>=0?j:0)+1;D<f.length;D+=1){const P=f[D];if(!P||P.every(ie=>ie==null||String(ie).trim()===""))continue;const U=Zn(P,k,null);if(!U){X+=1;continue}S.push(U)}!S.length&&!r.length&&r.push("No usable data rows were found in the report.");const N=S.filter(D=>D.rowLevel==="model"),M=S.filter(D=>D.rowLevel==="trim"),L=S.find(D=>D.rowLevel==="dealership")??S.find(D=>D.rowLevel==="overall")??null,_=N.filter(D=>(D.vehiclesSold??0)>0),H=M.filter(D=>(D.vehiclesSold??0)>0),F=N.length-_.length+(M.length-H.length)+X,p=new Map;M.forEach(D=>{const P=`${D.dealershipLabel}|${_s(D.make,D.model,D.trim)}`;p.set(P,(p.get(P)??0)+1)});const u=[...p.entries()].filter(([,D])=>D>1);u.length&&a.push(`${u.length} duplicate make/model/trim record(s) detected; the first record was kept.`);const w=_.reduce((D,P)=>D+(P.vehiclesSold??0),0);(L==null?void 0:L.vehiclesSold)!=null&&Math.abs(w-L.vehiclesSold)>.5&&a.push(`Model-level units (${w}) do not reconcile with the report total (${L.vehiclesSold}).`),L||a.push("No dealership total row was found; top-level figures were calculated from model rows.");const T=((_e=S.find(D=>D.rowLevel==="dealership"))==null?void 0:_e.dealershipLabel)??((ue=S.find(D=>D.rowLevel!=="overall"))==null?void 0:ue.dealershipLabel)??null,$=Yr(o);let W=null;const B=nr(o,["acquisition summary","summary"]);
234if(B){const D=Ns(o,B);for(const P of D.slice(0,8)){const U=mt(P==null?void 0:P[0]);if(U&&/month/i.test(U)){W=U;break}}}return{filename:t.name,dealershipLabel:T,reportPeriodLabel:W,importMode:g?"workbook":"raw",sheetsFound:i,rows:S,modelRows:_,trimRows:H,excludedRows:F,totalsRow:L,warnings:a,errors:r,approvedOrder:$}}function xs(t,s){return{filename:t,dealershipLabel:null,reportPeriodLabel:null,importMode:"raw",sheetsFound:[],rows:[],modelRows:[],trimRows:[],excludedRows:0,totalsRow:null,warnings:[],errors:s,approvedOrder:[]}}function bs(t,s){let a=0,r=0;return t.forEach(n=>{const o=n[s],i=n.vehiclesSold??0;typeof o=="number"&&Number.isFinite(o)&&i>0&&(a+=o*i,r+=i)}),r>0?a/r:null}const rs=3;function ja(t,s){const[a,r,n]=t.split("-").map(Number),[o,i,m]=s.split("-").map(Number);if(!a||!r||!n||!o||!i||!m)return null;const g=Date.UTC(a,r-1,n),f=Date.UTC(o,i-1,m);if(f<g)return null;const j=(f-g)/864e5+1;return Math.max(.5,Math.round(j/30.4375*10)/10)}const cs=t=>{const s=t??rs;return s<=1?"1M":`${Number.isInteger(s)?s:s.toFixed(1)}M`},Kr=t=>{const[s,a,r]=t.split("-").map(Number);return!s||!a||!r?t:new Date(Date.UTC(s,a-1,r)).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",timeZone:"UTC"})};function vs(t,s,a){if(!t||!s)return"All sold dates";const r=a??ja(t,s);return`${Kr(t)} – ${Kr(s)}${r?` (${r} months)`:""}`}const Qe=t=>typeof t=="number"&&Number.isFinite(t)?t:null,_a=(t,s=rs)=>{const a=s>0?s:rs;return t===null?null:t/a},ba=t=>t===null?null:Math.ceil(t*1.5),Na=(t,s)=>t===null||s===null?null:t*s,or=(t,s)=>t===null||s===null||s===0?null:t/s;function Nr(t,s){return t===null||s===null||s===0?null:(t-s)/s}function cl(t){const s=t??0;return s>=8?30:s>=5?24:s>=3?18:s>=2?12:s>=1?6:0}function dl(t){return t===null?0:t<=30?25:t<=45?20:t<=60?12:t<=75?5:0}function hl(t){return t===null||t<0?0:t>=6e3?25:t>=4500?20:t>=3500?15:t>=2500?8:2}function ul(t){return t===null||t<0?0:t>=2e3?10:t>=1e3?8:5}function ml(t,s){const a=t??0;if(s===null||s===0)return a>=2?10:a>=1?5:0;const r=(a-s)/s;return r>=.25?10:r>=0?7:r>=-.25?4:0}function wa(t){const s=t??0;return s>=5?"High":s>=3?"Medium":"Low"}function xl(t,s,a,r){const n=s??0;return r!==null&&r<0||a!==null&&a>75&&r!==null&&r<3e3?"Avoid":t>=75&&n>=3&&a!==null&&a<=50&&r!==null&&r>=3500?"Core Buy":t>=58&&n>=2?"Buy Selectively":t<35?"Avoid/Exit":"Opportunistic"}function ya(t,s,a){return a!==null&&a<0?{level:"Avoid",reason:"Average total gross is negative."}:t!==null&&t>=75&&a!==null&&a<3e3?{level:"Avoid",reason:"Average age of 75 days or more combined with total gross under $3,000."}:t!==null&&t>60?{level:"High",reason:"Average age above 60 days."}:s!==null&&s<=-500?{level:"High",reason:"Average front gross of -$500 or worse."}:a!==null&&a<2500?{level:"High",reason:"Average total gross below $2,500."}:s!==null&&s<0?{level:"Watch",reason:"Negative average front gross."}:t!==null&&t>45?{level:"Watch",reason:"Average age above 45 days."}:{level:"Normal",reason:"Age, front gross and total gross are within acceptable range."}}function pl(t,s){return t==="Avoid"?"Stop acquiring until the economics change.":t==="High"?"Only acquire with a corrected appraisal, recon allowance and retail price.":t==="Watch"?"Acquire with tighter cost discipline and a faster retail plan.":s==="Core Buy"?"Source at planned depth.":"Acquire selectively at current basis."}function gl(t,s=rs){const a=Qe(t.vehiclesSold),r=Qe(t.averageAge),n=Qe(t.averageFrontGross),o=Qe(t.averageTotalGross),i=Qe(t.priorYearSold),m={volume:cl(a),turn:dl(r),gross:hl(o),front:ul(n),trend:ml(a,i),total:0};m.total=m.volume+m.turn+m.gross+m.front+m.trend;const g=_a(a,s),f=xl(m.total,a,r,o),j=ya(r,n,o);return{...t,monthlyPace:g,target45DayQuantity:ba(g),estimatedThreeMonthGross:Na(a,o),frontGrossPct:or(n,Qe(t.averageListPrice)),totalGrossPct:or(o,Qe(t.averageListPrice)),salesChangePct:Nr(a,i),newDemand:(i===null||i===0)&&(a??0)>0,scores:m,confidence:wa(a),recommendation:f,riskLevel:j.level,riskReason:j.reason,acquisitionAction:pl(j.level,f)}}function fl(t){const s=t??0;return s>=5?30:s>=3?24:s>=2?16:s>=1?8:0}function vl(t){return t===null?0:t<=15?30:t<=30?25:t<=45?18:t<=60?10:0}function jl(t){return t===null||t<0?0:t>=3e3?25:t>=1500?20:t>=750?15:8}function _l(t){return t===null?0:t>=6e3?15:t>=4500?12:t>=3500?8:t>=2500?4:0}function bl(t,s,a,r,n,o,i,m){const g=t??0;if(r!==null&&r<0||s!==null&&s>60&&r!==null&&r<2500||a!==null&&a<0&&r!==null&&r<2500)return"Avoid/Exit";if(g>=2&&a!==null&&a>0&&r!==null&&r>=3500&&s!==null&&s<=50&&n>=60)return"Aggressively Source";if(g===1&&(s!==null&&s<=30&&r!==null&&r>=3500||r!==null&&r>=6e3))return"One-Off Opportunity";if(n<30)return"Avoid/Exit";const f=i!==null&&m!==null&&m>0&&i/m>.03,j=o!==null&&o<.95;return a!==null&&a<=0||s!==null&&s>50||r!==null&&r<3500||f||j?"Corrected Buy Basis":g===1?"One-Off Opportunity":"Corrected Buy Basis"}function Sa(t,s,a){switch(t){case"Aggressively Source":return a==="Low"?`Replace on a controlled one-unit depth (${s??1} at a time); sample is small.`:`Source aggressively to a ${s??1}-unit 45-day depth.`;case"Corrected Buy Basis":return"Keep as a target only with a corrected appraisal, purchase cost, recon allowance or retail price.";
234case"One-Off Opportunity":return"Buy opportunistically; maximum depth of one unit. Do not create standing inventory.";default:return"Do not acquire; economics do not support continued sourcing."}}function Nl(t,s=rs){const a=Qe(t.vehiclesSold),r=Qe(t.averageAge),n=Qe(t.averageFrontGross),o=Qe(t.averageTotalGross),i=Qe(t.priorYearSold),m={volume:fl(a),turn:vl(r),gross:_l(o),front:jl(n),trend:0,total:0};m.total=m.volume+m.turn+m.gross+m.front;const g=_a(a,s),f=ba(g),j=wa(a),y=bl(a,r,n,o,m.total,Qe(t.ptm),Qe(t.averageDiscount),Qe(t.averageListPrice)),k=ya(r,n,o);return{...t,monthlyPace:g,target45DayQuantity:f,estimatedThreeMonthGross:Na(a,o),frontGrossPct:or(n,Qe(t.averageListPrice)),totalGrossPct:or(o,Qe(t.averageListPrice)),salesChangePct:Nr(a,i),newDemand:(i===null||i===0)&&(a??0)>0,scores:m,confidence:j,sourcingTier:y,priority:null,acquisitionDirection:Sa(y,f,j),riskLevel:k.level,riskReason:k.reason,managementApproved:!1}}function wl(t,s){const a=t.totalsRow,r=Qe((a==null?void 0:a.vehiclesSold)??null)??s.reduce((g,f)=>g+(f.vehiclesSold??0),0),n=Qe((a==null?void 0:a.priorYearSold)??null)??s.reduce((g,f)=>g+(f.priorYearSold??0),0),i=t.rows.filter(g=>g.rowLevel==="make"&&(g.vehiclesSold??0)>0).filter(g=>(g.make??"").toLowerCase()==="ford").reduce((g,f)=>g+(f.vehiclesSold??0),0)||s.filter(g=>(g.make??"").toLowerCase()==="ford").reduce((g,f)=>g+(f.vehiclesSold??0),0),m=typeof(a==null?void 0:a.tradeCount)=="number"?a.tradeCount:t.rows.some(g=>typeof g.tradeCount=="number")?t.rows.filter(g=>g.rowLevel==="model").reduce((g,f)=>g+(f.tradeCount??0),0):null;return{unitsSold:r||null,priorYearUnits:n||null,changeVsPriorYear:Nr(r,n),tradeCount:m,tradeRate:m!==null&&r>0?m/r:null,averageAge:Qe((a==null?void 0:a.averageAge)??null)??bs(s,"averageAge"),averageFrontGross:Qe((a==null?void 0:a.averageFrontGross)??null)??bs(s,"averageFrontGross"),averageTotalGross:Qe((a==null?void 0:a.averageTotalGross)??null)??bs(s,"averageTotalGross"),fordMix:r>0?i/r:null}}function yl(t,s){const a=t.reduce((m,g)=>m+(g.vehiclesSold??0),0),r=t.reduce((m,g)=>m+(g.priorYearSold??0),0),n=t.filter(m=>(m.make??"").toLowerCase()==="ford").reduce((m,g)=>m+(g.vehiclesSold??0),0),o=t.some(m=>typeof m.tradeCount=="number"),i=o?t.reduce((m,g)=>m+(g.tradeCount??0),0):s.tradeCount??null;return{unitsSold:a||null,priorYearUnits:r||null,changeVsPriorYear:Nr(a,r),tradeCount:o?i:null,tradeRate:o&&i!==null&&a>0?i/a:null,averageAge:bs(t,"averageAge"),averageFrontGross:bs(t,"averageFrontGross"),averageTotalGross:bs(t,"averageTotalGross"),fordMix:a>0?n/a:null}}const Sl=t=>[t.make,t.model,t.trim].filter(Boolean).join(" ");function kl(t,s){const a=new Map(t.map(i=>[_s(i.make,i.model,i.trim),i]));let r=s;r.length||(r=Hr.every(m=>a.has(_s(m.make,m.model,m.trim)))?Hr:[]);const n=[];r.forEach(i=>{const m=a.get(_s(i.make,i.model,i.trim));m&&!n.includes(m)&&(m.sourcingTier="Aggressively Source",m.managementApproved=!0,m.priority=n.length+1,m.acquisitionDirection=Sa("Aggressively Source",m.target45DayQuantity,m.confidence),n.push(m))});const o=t.filter(i=>i.sourcingTier==="Aggressively Source"&&!n.includes(i)).sort((i,m)=>m.scores.total-i.scores.total||(m.vehiclesSold??0)-(i.vehiclesSold??0));return r.length?o.forEach(i=>{i.priority=null,i.managementApproved=!1}):o.forEach(i=>{n.push(i),i.priority=n.length}),t}function Ll(t){const s=t.filter(i=>i.sourcingTier==="Aggressively Source"&&i.priority!==null).sort((i,m)=>(i.priority??0)-(m.priority??0));if(!s.length)return"No trims currently meet the aggressive-sourcing standard. Review the corrected-buy-basis list before committing acquisition dollars.";const a=s.filter(i=>(i.vehiclesSold??0)>=3),r=s.filter(i=>(i.vehiclesSold??0)<3),n=i=>{const m=i.map(Sl);return m.length===1?m[0]:`${m.slice(0,-1).join(", ")} and ${m[m.length-1]}`},o=[];return a.length&&o.push(`Primary acquisition targets are the ${n(a)}.`),r.length&&o.push(`Maintain controlled one-unit replacement depth on the ${n(r)} because those trims are supported by smaller sales samples.`),o.join(" ")}const ps=t=>`$${Math.round(t).toLocaleString("en-US")}`,Qr=t=>`${(t*100).toFixed(1)}%`;function ka(t,s){const a=t.reduce((L,_)=>L+(_.vehiclesSold??0),0),n=t.filter(L=>L.averageAge!==null&&L.averageAge<=45).reduce((L,_)=>L+(_.vehiclesSold??0),0),o=t.filter(L=>L.averageAge!==null&&L.averageAge>60),i=o.reduce((L,_)=>L+(_.vehiclesSold??0),0),m=o.reduce((L,_)=>L+(_.averageFrontGross??0)*(_.vehiclesSold??0),0),g=m<0?Math.abs(m):0,f=t.filter(L=>L.averageFrontGross!==null&&L.averageFrontGross<0),j=f.reduce((L,_)=>L+(_.vehiclesSold??0),0),y=f.reduce((L,_)=>L+Math.abs(_.averageFrontGross??0)*(_.vehiclesSold??0),0),k=[...t].sort((L,_)=>(_.vehiclesSold??0)-(L.vehiclesSold??0)),C=k.slice(0,5).reduce((L,_)=>L+(_.vehiclesSold??0),0),x=k.slice(0,10).reduce((L,_)=>L+(_.vehiclesSold??0),0),A=t.filter(L=>L.recommendation==="Core Buy"),S=A.reduce((L,_)=>L+(_.vehiclesSold??0),0),X=A.reduce((L,_)=>L+(_.estimatedThreeMonthGross??0),0),N=t.reduce((L,_)=>L+(_.estimatedThreeMonthGross??0),0),M=L=>a>0?Qr(L/a):"n/a";return[{label:"Fast-turning demand",value:`${n} units (${M(n)})`,detail:`${n} units, or approximately ${M(n)}, came from models averaging 45 days or less.`,method:"Sum of vehicles sold for every model-level row with an average age at sale of 45 days or less, divided by total model-level units."},{label:"Slow-turning exposure",value:`${i} units · ${ps(g)}`,detail:`Models averaging more than 60 days represented ${i} units and approximately ${ps(g)} in estimated front-gross losses.`,method:"Models with average age above 60 days. Estimated loss = negative average front gross × vehicles sold for those models."},{label:"Negative front gross",value:`${j} units · ${ps(y)}`,detail:`Models with negative average front gross represented ${j} units and produced approximately ${ps(y)} in estimated front-gross losses.`,method:"Models whose average front gross is below zero. Estimated loss = |average front gross| × vehicles sold."},{label:"Volume concentration",value:`${M(C)} / ${M(x)}`,detail:`The top five models represented ${M(C)} of units and the top ten models represented ${M(x)} of units.`,method:"Models ranked by vehicles sold; the top five and top ten unit counts divided by total units."},{label:"Core-buy contribution",value:`${S} units · ${ps(X)}`,detail:`The core-buy group represented ${S} units and approximately ${ps(X)} in estimated total gross — about ${M(S)} of unit volume and ${N>0?Qr(X/N):"n/a"} of total gross.`,method:"Models classified Core Buy (score 75+, 3+ units, 50 days or less, $3,500+ total gross). Estimated gross = vehicles sold × average total gross."}]}const Ss="This analysis identifies which models and trims deserve acquisition attention based on sold performance. It cannot establish a VIN-level appraisal or true days-supply target without year, mileage, cost, recon, current inventory and market-supply data.";function La(t){const s=t.periodMonths&&t.periodMonths>0?t.periodMonths:rs,a=t.modelRows.map(o=>gl(o,s)),r=kl(t.trimRows.map(o=>Nl(o,s)),t.approvedOrder);return{kpis:wl(t,a),models:a,trims:r,periodMonths:s,findings:ka(a),conclusion:Ll(r)}}const qe=t=>{let s=0,a=0;return t.forEach(r=>{typeof r=="number"&&Number.isFinite(r)&&(s+=r,a+=1)}),a>0?s/a:null},vt=t=>(t??"").toLowerCase().trim();function cr(t,s,a){return t.filter(r=>!(!r.soldDate||s&&r.soldDate<s||a&&r.soldDate>a))}function Ca(t){const s=t.map(a=>a.soldDate).filter(a=>!!a).sort();return{start:s[0]??null,end:s[s.length-1]??null}}const Fs=(t,s)=>{const[a,r,n]=t.split("-").map(Number);return`${String(a+s).padStart(4,"0")}-${String(r).padStart(2,"0")}-${String(n).padStart(2,"0")}`};function Ms(t,s){const a=new Map;return t.forEach(r=>{const o=(s==="overall"?["all"]:s==="dealership"?[vt(r.dealershipLabel)]:s==="make"?[vt(r.dealershipLabel),vt(r.make)]:s==="model"?[vt(r.dealershipLabel),vt(r.make),vt(r.model)]:[vt(r.dealershipLabel),vt(r.make),vt(r.model),vt(r.trim)]).join("|"),i=a.get(o);i?i.push(r):a.set(o,[r])}),[...a.values()].map(r=>Cl(r,s))}function Cl(t,s){const a=t[0];return{rowLevel:s,dealershipLabel:s==="overall"?"Total":a.dealershipLabel,make:s==="make"||s==="model"||s==="trim"?a.make:null,model:s==="model"||s==="trim"?a.model:null,trim:s==="trim"?a.trim:null,vehiclesSold:t.length,projectedSales:null,priorYearSold:null,salesDeltaText:null,salesDeltaPct:null,averageAge:qe(t.map(r=>r.daysInInventory)),ptm:qe(t.map(r=>r.priceToMarket)),averageListPrice:qe(t.map(r=>r.listPrice)),averageDiscount:qe(t.map(r=>r.vehicleDiscount)),averageFrontGross:qe(t.map(r=>r.frontGross)),averageBackGross:qe(t.map(r=>r.backGross)),tradeOverUnder:qe(t.map(r=>r.tradeOverUnder)),averageTotalGross:qe(t.map(r=>r.totalGross)),tradeCount:t.filter(r=>r.isTrade).length,averageTransactionPrice:qe(t.map(r=>r.transactionPrice))}}const yr=t=>[vt(t.make),vt(t.model),vt(t.trim??null)].join("|");function $l(t,s=[]){if(!t.length)return{rows:[],totalsRow:null};const a=Ms(t,"overall"),r=Ms(t,"dealership"),n=Ms(t,"make"),o=Ms(t,"model"),i=Ms(t,"trim");if(s.length){const g=new Map,f=new Map;let j=0;
234s.forEach(y=>{j+=1;const k=`${vt(y.make)}|${vt(y.model)}|`;g.set(k,(g.get(k)??0)+1);const C=yr(y);f.set(C,(f.get(C)??0)+1)}),o.forEach(y=>{y.priorYearSold=g.get(yr(y))??0}),i.forEach(y=>{y.priorYearSold=f.get(yr(y))??0}),[...a,...r].forEach(y=>{y.priorYearSold=j})}return{rows:[...a,...r,...n,...o,...i],totalsRow:r[0]??a[0]??null}}function Al(t,s){return!t||!s?null:ja(t,s)}function dr(t){const s=t.recordFilter?t.records.filter(t.recordFilter):t.records,a=Ca(s),r=t.start??a.start,n=t.end??a.end,o=cr(s,r,n),i=r?Fs(r,-1):null,g=!!(i&&a.start&&i>=a.start)&&r&&n?cr(s,Fs(r,-1),Fs(n,-1)):[],{rows:f,totalsRow:j}=$l(o,g),y=Al(r,n)??1,k={filename:t.filename,dealershipLabel:t.dealershipLabel,reportPeriodLabel:vs(r,n,y),periodKey:null,periodMonths:y,reportStartDate:r,reportEndDate:n,importMode:"detail",sheetsFound:[],records:s,rows:f,modelRows:f.filter(C=>C.rowLevel==="model"&&(C.vehiclesSold??0)>0),trimRows:f.filter(C=>C.rowLevel==="trim"&&(C.vehiclesSold??0)>0),excludedRows:s.length-o.length,totalsRow:j,warnings:t.warnings??[],errors:[],approvedOrder:t.approvedOrder??[]};return{report:k,analysis:La(k),records:o}}const Ml=[{label:"0–2 years old",min:0,max:2},{label:"3–5 years old",min:3,max:5},{label:"6–9 years old",min:6,max:9},{label:"10+ years old",min:10,max:999}],Tl=(t,s,a,r)=>t?a!==null&&a<0?"Stop buying in this band; total gross is negative.":a!==null&&a>=4e3&&s!==null&&s<=45?"Buy at full planned depth; this band turns quickly at strong gross.":s!==null&&s>60?"Buy sparingly; this band sits too long.":r!==null&&r<0?"Buy only with a corrected purchase cost; front gross is negative.":"Buy selectively with tight cost discipline.":"No sales in this band.";function Dl(t){return Ml.map(s=>{const a=t.filter(m=>{if(!m.modelYear||!m.soldDate)return!1;const g=Number(m.soldDate.slice(0,4))-m.modelYear;return g>=s.min&&g<=s.max}),r=qe(a.map(m=>m.daysInInventory)),n=qe(a.map(m=>m.totalGross)),o=qe(a.map(m=>m.frontGross)),i=a.filter(m=>m.isTrade).length;return{label:s.label,units:a.length,tradeCount:i,tradeRate:a.length?i/a.length:null,averageAge:r,averageFrontGross:o,averageTotalGross:n,guidance:Tl(a.length,r,n,o)}})}function Rl(t){const s=new Map;return t.forEach(a=>{if(!a.soldDate)return;const r=a.soldDate.slice(0,7),n=s.get(r);n?n.push(a):s.set(r,[a])}),[...s.entries()].sort((a,r)=>a[0].localeCompare(r[0])).map(([a,r])=>{const[n,o]=a.split("-").map(Number);return{month:a,label:new Date(Date.UTC(n,o-1,1)).toLocaleDateString("en-US",{month:"short",year:"2-digit",timeZone:"UTC"}),units:r.length,tradeCount:r.filter(i=>i.isTrade).length,averageAge:qe(r.map(i=>i.daysInInventory)),averageFrontGross:qe(r.map(i=>i.frontGross)),averageTotalGross:qe(r.map(i=>i.totalGross))}})}function Pl(t){const s=new Map;return t.forEach(a=>{const r=`${vt(a.make)}|${vt(a.model)}`,n=s.get(r);n?n.push(a):s.set(r,[a])}),[...s.values()].map(a=>{const r=qe(a.map(g=>g.listPrice)),n=qe(a.map(g=>g.vehicleDiscount)),o=qe(a.map(g=>g.frontGross)),i=r&&r>0&&n!==null?n/r:null;let m=null;return i!==null&&i>.03&&o!==null&&o<1e3?m="Discounting is consuming the front gross":o!==null&&o<0?m="Negative front gross":i!==null&&i>.05&&(m="Heavy discounting"),{make:a[0].make,model:a[0].model,units:a.length,averageListPrice:r,averageTransactionPrice:qe(a.map(g=>g.transactionPrice)),averageDiscount:n,discountPctOfList:i,averagePriceToMarket:qe(a.map(g=>g.priceToMarket)),averageFrontGross:o,flag:m}}).sort((a,r)=>r.units-a.units)}const Xs="Unknown";function El(t){const s=new Map;t.forEach(r=>{const n=(r.source??"").trim()||Xs,o=s.get(n);o?o.push(r):s.set(n,[r])});const a=t.length;return[...s.entries()].map(([r,n])=>({source:r,units:n.length,unitShare:a?n.length/a:null,tradeCount:n.filter(o=>o.isTrade).length,averageAge:qe(n.map(o=>o.daysInInventory)),averageFrontGross:qe(n.map(o=>o.frontGross)),averageTotalGross:qe(n.map(o=>o.totalGross)),averageTransactionPrice:qe(n.map(o=>o.transactionPrice))})).sort((r,n)=>r.source===Xs!=(n.source===Xs)?r.source===Xs?1:-1:n.units-r.units||r.source.localeCompare(n.source))}const $a="id, filename, dealership_id, dealership_label, report_period_label, report_start_date, report_end_date, period_key, period_months, import_mode, uploaded_by_name, uploaded_at, status, source_row_count, model_row_count, trim_row_count, excluded_row_count, total_units_sold, record_count, trade_count, validation_summary, is_active",Fl="dealership_label, stock_number, vin, model_year, make, model, trim, sold_date, days_in_inventory, price_to_market, list_price, transaction_price, vehicle_discount, front_gross, back_gross, trade_over_under, total_gross, is_trade, source",Il
234=t=>({dealershipLabel:t.dealership_label,stockNumber:t.stock_number,vin:t.vin,modelYear:t.model_year,make:t.make,model:t.model,trim:t.trim,soldDate:t.sold_date,daysInInventory:t.days_in_inventory,priceToMarket:t.price_to_market,listPrice:t.list_price,transactionPrice:t.transaction_price,vehicleDiscount:t.vehicle_discount,frontGross:t.front_gross,backGross:t.back_gross,tradeOverUnder:t.trade_over_under,totalGross:t.total_gross,isTrade:!!t.is_trade,source:(t.source??"").trim()||"Unknown"});async function Ol(t,s){let a=ne.from("uva_imports").select($a).eq("organization_id",t).order("uploaded_at",{ascending:!1});s.length&&(a=a.in("dealership_id",s));const{data:r,error:n}=await a;if(n)throw n;return r??[]}async function Ul(t){var g,f;const{report:s,analysis:a,organizationId:r,dealershipId:n}=t,{data:o,error:i}=await ne.from("uva_imports").insert({organization_id:r,dealership_id:n,filename:s.filename,dealership_label:s.dealershipLabel,report_period_label:s.reportPeriodLabel,report_start_date:t.reportStartDate??s.reportStartDate??null,report_end_date:t.reportEndDate??s.reportEndDate??null,period_key:s.periodKey??null,period_months:s.periodMonths??null,import_mode:s.importMode,uploaded_by:t.uploadedBy,uploaded_by_name:t.uploadedByName,status:"ready",source_row_count:s.rows.length,model_row_count:s.modelRows.length,trim_row_count:s.trimRows.length,excluded_row_count:s.excludedRows,total_units_sold:Math.round(a.kpis.unitsSold??0),record_count:((g=s.records)==null?void 0:g.length)??0,trade_count:((f=s.records)==null?void 0:f.filter(j=>j.isTrade).length)??0,kpis:a.kpis,validation_summary:{warnings:s.warnings,errors:s.errors},is_active:!0}).select("id").single();if(i||!o)throw i??new Error("The import could not be saved.");const m=o.id;try{const j=s.records??[];if(j.length){const x=j.map(A=>({import_id:m,organization_id:r,dealership_id:n,dealership_label:A.dealershipLabel,stock_number:A.stockNumber,vin:A.vin,model_year:A.modelYear,make:A.make,model:A.model,trim:A.trim,sold_date:A.soldDate,days_in_inventory:A.daysInInventory,price_to_market:A.priceToMarket,list_price:A.listPrice,transaction_price:A.transactionPrice,vehicle_discount:A.vehicleDiscount,front_gross:A.frontGross,back_gross:A.backGross,trade_over_under:A.tradeOverUnder,total_gross:A.totalGross,is_trade:A.isTrade,source:A.source??null}));for(let A=0;A<x.length;A+=400){const{error:S}=await ne.from("uva_sales_records").insert(x.slice(A,A+400));if(S)throw S}}const y=s.rows.map(x=>({import_id:m,organization_id:r,dealership_id:n,row_level:x.rowLevel,dealership_label:x.dealershipLabel,make:x.make,model:x.model,trim:x.trim,vehicles_sold:x.vehiclesSold,projected_sales:x.projectedSales,prior_year_sold:x.priorYearSold,sales_delta_text:x.salesDeltaText,sales_delta_pct:x.salesDeltaPct,average_age:x.averageAge,ptm:x.ptm,average_list_price:x.averageListPrice,average_discount:x.averageDiscount,average_front_gross:x.averageFrontGross,average_back_gross:x.averageBackGross,trade_over_under:x.tradeOverUnder,average_total_gross:x.averageTotalGross}));for(let x=0;x<y.length;x+=400){const{error:A}=await ne.from("uva_sales_metrics").insert(y.slice(x,x+400));if(A)throw A}const k=[...a.models.map(x=>({import_id:m,organization_id:r,dealership_id:n,result_level:"model",make:x.make,model:x.model,trim:null,vehicles_sold:x.vehiclesSold,prior_year_sold:x.priorYearSold,monthly_pace:x.monthlyPace,target_45_day_quantity:x.target45DayQuantity,estimated_three_month_gross:x.estimatedThreeMonthGross,average_age:x.averageAge,ptm:x.ptm,average_list_price:x.averageListPrice,average_front_gross:x.averageFrontGross,average_back_gross:x.averageBackGross,average_total_gross:x.averageTotalGross,volume_score:x.scores.volume,turn_score:x.scores.turn,gross_score:x.scores.gross,front_score:x.scores.front,trend_score:x.scores.trend,total_score:x.scores.total,confidence:x.confidence,recommendation:x.recommendation,risk_level:x.riskLevel,risk_reason:x.riskReason,sourcing_tier:null,priority:null,acquisition_direction:x.acquisitionAction})),...a.trims.map(x=>({import_id:m,organization_id:r,dealership_id:n,result_level:"trim",make:x.make,model:x.model,trim:x.trim,vehicles_sold:x.vehiclesSold,prior_year_sold:x.priorYearSold,monthly_pace:x.monthlyPace,target_45_day_quantity:x.target45DayQuantity,estimated_three_month_gross:x.estimatedThreeMonthGross,average_age:x.averageAge,ptm:x.ptm,average_list_price:x.averageListPrice,average_front_gross:x.averageFrontGross,average_back_gross:x.averageBackGross,average_total_gross:x.averageTotalGross,volume_score:x.scores.volume,turn_score:x.scores.turn,gross_
234score:x.scores.gross,front_score:x.scores.front,trend_score:x.scores.trend,total_score:x.scores.total,confidence:x.confidence,recommendation:null,risk_level:x.riskLevel,risk_reason:x.riskReason,sourcing_tier:x.sourcingTier,priority:x.priority,acquisition_direction:x.acquisitionDirection}))];for(let x=0;x<k.length;x+=400){const{error:A}=await ne.from("uva_acquisition_results").insert(k.slice(x,x+400));if(A)throw A}let C=ne.from("uva_imports").update({is_active:!1}).eq("organization_id",r).neq("id",m);C=n?C.eq("dealership_id",n):C.is("dealership_id",null),await C}catch(j){throw await ne.from("uva_imports").delete().eq("id",m),j}return m}async function Gl(t){const s=[];for(let r=0;r<30;r+=1){const{data:n,error:o}=await ne.from("uva_sales_records").select(Fl).eq("import_id",t).order("sold_date",{ascending:!0}).range(r*1e3,r*1e3+1e3-1);if(o)throw o;const i=n??[];if(s.push(...i.map(Il)),i.length<1e3)break}return s}async function Bl(t){var y,k,C;const[{data:s,error:a},r,n]=await Promise.all([ne.from("uva_imports").select($a).eq("id",t).single(),ne.from("uva_sales_metrics").select("row_level, dealership_label, make, model, trim, vehicles_sold, projected_sales, prior_year_sold, sales_delta_text, sales_delta_pct, average_age, ptm, average_list_price, average_discount, average_front_gross, average_back_gross, trade_over_under, average_total_gross").eq("import_id",t).limit(5e3),ne.from("uva_acquisition_results").select("id, make, model, trim, priority, sourcing_tier, acquisition_direction, management_override, override_tier, override_priority, override_direction, override_reason, approved, result_level").eq("import_id",t).eq("result_level","trim").limit(5e3)]);if(a||!s)throw a??new Error("Import not found.");if(r.error)throw r.error;if(n.error)throw n.error;const o=(r.data??[]).map(x=>({rowLevel:x.row_level,dealershipLabel:x.dealership_label,make:x.make,model:x.model,trim:x.trim,vehiclesSold:x.vehicles_sold,projectedSales:x.projected_sales,priorYearSold:x.prior_year_sold,salesDeltaText:x.sales_delta_text,salesDeltaPct:x.sales_delta_pct,averageAge:x.average_age,ptm:x.ptm,averageListPrice:x.average_list_price,averageDiscount:x.average_discount,averageFrontGross:x.average_front_gross,averageBackGross:x.average_back_gross,tradeOverUnder:x.trade_over_under,averageTotalGross:x.average_total_gross})),i=s,m=n.data??[],g=m.filter(x=>(x.override_priority??x.priority)!==null).sort((x,A)=>(x.override_priority??x.priority??0)-(A.override_priority??A.priority??0)).map(x=>({make:x.make??"",model:x.model??"",trim:x.trim??""})),f={filename:i.filename,dealershipLabel:i.dealership_label,reportPeriodLabel:i.report_period_label,periodKey:i.period_key,periodMonths:i.period_months,reportStartDate:i.report_start_date,reportEndDate:i.report_end_date,importMode:i.import_mode??"workbook",sheetsFound:[],rows:o,modelRows:o.filter(x=>x.rowLevel==="model"&&(x.vehiclesSold??0)>0),trimRows:o.filter(x=>x.rowLevel==="trim"&&(x.vehiclesSold??0)>0),excludedRows:i.excluded_row_count,totalsRow:o.find(x=>x.rowLevel==="dealership")??o.find(x=>x.rowLevel==="overall")??null,warnings:((y=i.validation_summary)==null?void 0:y.warnings)??[],errors:((k=i.validation_summary)==null?void 0:k.errors)??[],approvedOrder:g};if((i.record_count??0)>0){const x=await Gl(t);if(x.length){const A=dr({records:x,filename:i.filename,dealershipLabel:i.dealership_label,start:i.report_start_date,end:i.report_end_date,approvedOrder:g,warnings:((C=i.validation_summary)==null?void 0:C.warnings)??[]});return Jr(A.analysis.trims,m),{record:i,report:A.report,analysis:A.analysis,overrides:m,records:x}}}const j=La(f);return Jr(j.trims,m),{record:i,report:f,analysis:j,overrides:m,records:[]}}function Jr(t,s){const a=new Map(s.map(r=>[_s(r.make,r.model,r.trim),r]));t.forEach(r=>{const n=a.get(_s(r.make,r.model,r.trim));!n||!n.management_override||(n.override_tier&&(r.sourcingTier=n.override_tier),n.override_priority!==null&&(r.priority=n.override_priority),n.override_direction&&(r.acquisitionDirection=n.override_direction),r.managementApproved=!0)})}async function Aa(t,s,a){let r=ne.from("uva_acquisition_results").update({...a,approved_at:a.approved?new Date().toISOString():void 0}).eq("import_id",t).eq("result_level","trim").eq("make",s.make??"").eq("model",s.model??"");r=s.trim?r.eq("trim",s.trim):r.is("trim",null);const{error:n}=await r;if(n)throw n}async function zl(t,s){await Aa(t,s,{management_override:!1,override_tier:null,override_priority:null,override_direction:null,override_reason:null,approved:!1})}async function Vl(t,s,a){let r=ne.from("uva_imports").update({is_active:!1}).eq("organization_id",s);r=a?r.eq("dealership_id",a):r.is("dealership_id",null);const{error:n}=await r;if(n)throw n;const{error:o}=await ne.from("uva_imports").update({is_active:!0}).eq("id",t);if(o)throw o}async function ql(t){const{error:s}=await ne.from("uva_saved_reports").insert({import_id:t.importId,organization_id:t.organizationId,dealership_id:t.dealershipId,report_type:t.reportType,report_name:t.reportName,filters:t.filters,generated_html:t.html,created_by:t.createdBy});if(s)throw s}const Ps={executive:"Executive Acquisition Report",aggressive:"Aggressive Sourcing Report",risk:"Acquisition Risk Report","model-scorec
234ard":"Model Scorecard Report","trim-detail":"Trim Detail Report"},Ma={executive:10,aggressive:15,risk:15,"model-scorecard":18,"trim-detail":18},Wl=8,Ws=(t,s)=>Math.min(Ma[s],t.maxRows??Number.POSITIVE_INFINITY),me=t=>String(t??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),yt=t=>`<span class="${Tt(t)?"neg":""}">${me(ze(t))}</span>`,Yl=`
235:root{--navy:#17365D;--blue:#1F4E78;--row:#D9EAF7;--good:#E2F0D9;--goodtext:#2F641C;--risk:#FCE4D6;--warn:#FFF2CC;--ink:#333333;}
236*{box-sizing:border-box;}
237html,body{margin:0;padding:0;background:#ffffff;color:var(--ink);font-family:Arial,Helvetica,sans-serif;}
238body{-webkit-print-color-adjust:exact;print-color-adjust:exact;}
239.print-page{box-sizing:border-box;width:10.4in;height:7.9in;overflow:hidden;margin:0 auto;padding:0;background:#fff;}
240.hdr{display:flex;justify-content:space-between;align-items:flex-end;border-bottom:2.5pt solid var(--navy);padding-bottom:4pt;margin-bottom:6pt;}
241.hdr h1{margin:0;font-size:15pt;color:var(--navy);letter-spacing:.3pt;}
242.hdr .brand{font-size:8pt;font-weight:bold;color:var(--blue);letter-spacing:1.2pt;text-transform:uppercase;}
243.hdr .meta{text-align:right;font-size:8pt;line-height:1.35;color:#555;}
244.hdr .meta strong{color:var(--navy);font-size:9.5pt;}
245.kpis{display:flex;gap:5pt;margin-bottom:6pt;}
246.kpi{flex:1;border:0.75pt solid #c9d7e6;border-top:2.5pt solid var(--blue);background:#f7fafd;padding:3.5pt 5pt;}
247.kpi .l{font-size:6.8pt;text-transform:uppercase;letter-spacing:.4pt;color:#5a6b7d;}
248.kpi .v{font-size:12.5pt;font-weight:bold;color:var(--navy);line-height:1.15;}
249.concl{background:var(--good);border-left:3.5pt solid var(--goodtext);padding:4.5pt 6pt;margin-bottom:6pt;}
250.concl .t{font-size:7pt;font-weight:bold;text-transform:uppercase;letter-spacing:.5pt;color:var(--goodtext);margin-bottom:1.5pt;}
251.concl p{margin:0;font-size:8.4pt;line-height:1.32;color:#22331a;}
252h2{font-size:8.4pt;margin:0 0 2.5pt;color:var(--navy);text-transform:uppercase;letter-spacing:.5pt;border-bottom:0.75pt solid #c9d7e6;padding-bottom:1.5pt;}
253table{width:100%;border-collapse:collapse;table-layout:fixed;font-size:7.6pt;}
254th{background:var(--navy);color:#fff;text-align:left;padding:2pt 3pt;font-size:7pt;font-weight:bold;}
255td{padding:1.7pt 3pt;border-bottom:0.5pt solid #dfe7ef;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}
256tbody tr:nth-child(even) td{background:var(--row);}
257.num{text-align:right;}
258.neg{color:#C00000;}
259.tag{font-size:6.6pt;padding:0.5pt 2.5pt;border-radius:2pt;font-weight:bold;}
260.tag.high{background:var(--good);color:var(--goodtext);}
261.tag.med{background:var(--warn);color:#7f6000;}
262.tag.low{background:var(--risk);color:#943c1e;}
263.tag.avoid{background:var(--risk);color:#943c1e;}
264.tag.risk-high{background:var(--risk);color:#943c1e;}
265.tag.watch{background:var(--warn);color:#7f6000;}
266.tag.normal{background:var(--good);color:var(--goodtext);}
267.cols{display:flex;gap:7pt;}
268.cols>div{flex:1;min-width:0;}
269.findings{margin:0;padding-left:11pt;font-size:7.6pt;line-height:1.35;}
270.findings li{margin-bottom:1.5pt;}
271.note{font-size:6.8pt;color:#5a6b7d;line-height:1.3;margin-top:4pt;}
272.ftr{position:relative;margin-top:5pt;border-top:0.75pt solid #c9d7e6;padding-top:3pt;display:flex;justify-content:space-between;font-size:6.8pt;color:#5a6b7d;}
273tr,td,th{break-inside:avoid;page-break-inside:avoid;}
274@page{size:Letter landscape;margin:0.30in;}
275@media print{
276  html,body{width:11in;height:8.5in;margin:0;padding:0;overflow:hidden;}
277  .no-print{display:none !important;}
278  .print-page{width:10.4in;height:7.9in;overflow:hidden;page-break-after:avoid;break-after:avoid-page;}
279}
280`,Ta=t=>`<span class="tag ${t==="High"?"high":t==="Medium"?"med":"low"}">${me(t)}</span>`,Da=t=>`<span class="tag ${t==="Avoid"?"avoid":t==="High"?"risk-high":t==="Watch"?"w
280atch":"normal"}">${me(t)}</span>`;function Ys(t,s){return`<div class="hdr">
281  <div><div class="brand">INTEL360</div><h1>${me(s)}</h1></div>
282  <div class="meta"><strong>${me(t.dealershipName)}</strong><br>${me(t.reportPeriod)}<br>Generated ${me(t.generatedAt.toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"}))}${t.filterSummary?`<br>${me(t.filterSummary)}`:""}</div>
283</div>`}function Hs(t){return'<div class="ftr"><div>Based on the sold dates shown above. Results identify where to source; they do not establish a VIN-level bid.</div><div>Page 1 of 1</div></div>'}function wr(t){const s=t.kpis,a=[[`Units sold (${cs(t.periodMonths)})`,le(s.unitsSold)],["Vs. prior year",bt(s.changeVsPriorYear)],["Avg. age at sale",`${Ve(s.averageAge)} days`],["Avg. front gross",ze(s.averageFrontGross)],["Avg. total gross",ze(s.averageTotalGross)],["Ford mix",bt(s.fordMix)]];return s.tradeRate!==null&&s.tradeRate!==void 0&&a.push(["Sales with a trade",bt(s.tradeRate)]),`<div class="kpis">${a.map(([r,n])=>`<div class="kpi"><div class="l">${me(r)}</div><div class="v">${me(n)}</div></div>`).join("")}</div>`}function Ra(t){return`<div class="concl"><div class="t">Acquisition conclusion</div><p>${me(t.conclusion)}</p></div>`}const ws=(t,s)=>s>t?`<div class="note">Showing top ${t} of ${s}.</div>`:"";function hr(t){return t.trims.filter(s=>s.sourcingTier==="Aggressively Source").sort((s,a)=>(s.priority??999)-(a.priority??999)||a.scores.total-s.scores.total)}function ur(t){const s={Avoid:0,High:1,Watch:2,Normal:3};return t.models.filter(a=>a.riskLevel!=="Normal").sort((a,r)=>s[a.riskLevel]-s[r.riskLevel]||(r.vehiclesSold??0)-(a.vehiclesSold??0))}function Hl(t,s){return`<ul class="findings">${t.slice(0,s).map(a=>`<li>${me(a.detail)}</li>`).join("")}</ul>`}function Kl(t){const s=(t.sourceRows??[]).slice(0,6);return s.length?`<h2 style="margin-top:6pt">Where these vehicles came from</h2>
284<table><colgroup><col style="width:34%"><col style="width:14%"><col style="width:14%"><col style="width:19%"><col style="width:19%"></colgroup>
285<thead><tr><th>Source</th><th class="num">Units</th><th class="num">Share</th><th class="num">Days</th><th class="num">Total</th></tr></thead>
286<tbody>${s.map(a=>`<tr><td>${me(a.source)}</td><td class="num">${le(a.units)}</td><td class="num">${me(bt(a.unitShare))}</td><td class="num">${Ve(a.averageAge)}</td><td class="num">${yt(a.averageTotalGross)}</td></tr>`).join("")}</tbody></table>`:""}function Ql(t){const s=t.analysis,a=hr(s).slice(0,Ws(t,"executive")),r=ur(s).slice(0,Math.min(Wl,t.maxRows??Number.POSITIVE_INFINITY));return`${Ys(t,"Used Vehicle Acquisition Analysis")}
287${wr(s)}
288${Ra(s)}
289<h2>Aggressively source — exact make, model and trim</h2>
290<table>
291<colgroup><col style="width:4%"><col style="width:12%"><col style="width:16%"><col style="width:18%"><col style="width:6%"><col style="width:7%"><col style="width:9%"><col style="width:9%"><col style="width:9%"><col style="width:10%"></colgroup>
292<thead><tr><th>#</th><th>Make</th><th>Model</th><th>Trim</th><th class="num">Sold</th><th class="num">Days</th><th class="num">Front</th><th class="num">Total</th><th class="num">45-day qty</th><th>Confidence</th></tr></thead>
293<tbody>${a.map((n,o)=>`<tr><td class="num">${n.priority??o+1}</td><td>${me(n.make)}</td><td>${me(n.model)}</td><td>${me(n.trim)}</td><td class="num">${le(n.vehiclesSold)}</td><td class="num">${Ve(n.averageAge)}</td><td class="num">${yt(n.averageFrontGross)}</td><td class="num">${yt(n.averageTotalGross)}</td><td class="num">${le(n.target45DayQuantity)}</td><td>${Ta(n.confidence)}</td></tr>`).join("")}</tbody></table>
294${ws(a.length,hr(s).length)}
295<div class="cols" style="margin-top:6pt">
296<div><h2>Price discipline — avoid / high risk</h2>
297<table><colgroup><col style="width:34%"><col style="width:11%"><col style="width:12%"><col style="width:16%"><col style="width:16%"><col style="width:11%"></colgroup>
298<thead><tr><th>Model</th><th class="num">Sold</th><th class="num">Days</th><th class="num">Front</th><th class="num">Total</th><th>Risk</th></tr></thead>
299<tbody>${r.map(n=>`<tr><td>${me(`${n.make} ${n.model}`)}</td><td class="num">${le(n.vehiclesSold)}</td><td class="num">${Ve(n.averageAge)}</td><td class="num">${yt(n.averageFrontGross)}</td><td class="num">${yt(n.averageTotalGross)}</td><td>${Da(n.riskLevel)}</td></tr>`).join("")}</tbody></table>
300${ws(r.length,ur(s).length)}
301</div>
302<div><h2>Management findings</h2>${Hl(s.findings,5)}
303${Kl(t)}
304<div class="note">${me(Ss)}</div></div>
305</div>
306${Hs()}`}function Jl(t){var n;const s=t.analysis,a=hr(s),r=a.slice(0,Ws(t,"aggressive"));return`${Ys(t,"Aggressive Sourcing Report")}
307${Ra(s)}
308<h2>Aggressively source — exact make, model and trim</h2>
309<table>
310<colgroup><col style="width:3.5%"><col style="width:9%"><col style="width:12%"><col style="width:13%"><col style="width:5%"><col style="width:5.5%"><col style="width:6%"><col style="width:5.5%"><col style="width:8%"><col style="width:7.5%"><col style="width:7.5%"><col style="width:8.5%"><col style="width:5%"><col style="width:5%"></colgroup>
311<thead><tr><th>
311#</th><th>Make</th><th>Model</th><th>Trim</th><th class="num">${cs(t.analysis.periodMonths)}</th><th class="num">PY</th><th class="num">Pace</th><th class="num">Days</th><th class="num">PTM</th><th class="num">Front</th><th class="num">Total</th><th class="num">Est. ${cs(t.analysis.periodMonths)} gross</th><th class="num">Qty</th><th class="num">Score</th></tr></thead>
312<tbody>${r.map((o,i)=>`<tr><td class="num">${o.priority??i+1}</td><td>${me(o.make)}</td><td>${me(o.model)}</td><td>${me(o.trim)}</td><td class="num">${le(o.vehiclesSold)}</td><td class="num">${le(o.priorYearSold)}</td><td class="num">${Ve(o.monthlyPace,2)}</td><td class="num">${Ve(o.averageAge)}</td><td class="num">${js(o.ptm)}</td><td class="num">${yt(o.averageFrontGross)}</td><td class="num">${yt(o.averageTotalGross)}</td><td class="num">${yt(o.estimatedThreeMonthGross)}</td><td class="num">${le(o.target45DayQuantity)}</td><td class="num">${le(o.scores.total)}</td></tr>`).join("")}</tbody></table>
313${ws(r.length,a.length)}
314<div class="note" style="margin-top:5pt">Acquisition direction: ${me(((n=r[0])==null?void 0:n.acquisitionDirection)??"")}</div>
315<div class="note">${me(Ss)}</div>
316${Hs()}`}function Xl(t){const s=t.analysis,a=ur(s),r=a.slice(0,Ws(t,"risk"));return`${Ys(t,"Acquisition Risk Report")}
317${wr(s)}
318<h2>Price discipline and avoidance list</h2>
319<table>
320<colgroup><col style="width:9%"><col style="width:13%"><col style="width:5%"><col style="width:5.5%"><col style="width:8%"><col style="width:8%"><col style="width:6.5%"><col style="width:7%"><col style="width:19%"><col style="width:19%"></colgroup>
321<thead><tr><th>Make</th><th>Model</th><th class="num">${cs(t.analysis.periodMonths)}</th><th class="num">Days</th><th class="num">Front</th><th class="num">Total</th><th class="num">PTM</th><th>Risk</th><th>Acquisition action</th><th>Supporting reason</th></tr></thead>
322<tbody>${r.map(n=>`<tr><td>${me(n.make)}</td><td>${me(n.model)}</td><td class="num">${le(n.vehiclesSold)}</td><td class="num">${Ve(n.averageAge)}</td><td class="num">${yt(n.averageFrontGross)}</td><td class="num">${yt(n.averageTotalGross)}</td><td class="num">${js(n.ptm)}</td><td>${Da(n.riskLevel)}</td><td style="white-space:normal">${me(n.acquisitionAction)}</td><td style="white-space:normal">${me(n.riskReason)}</td></tr>`).join("")}</tbody></table>
323${ws(r.length,a.length)}
324<div class="note">${me(Ss)}</div>
325${Hs()}`}function Zl(t){const s=t.analysis,a=[...s.models].sort((n,o)=>o.scores.total-n.scores.total),r=a.slice(0,Ws(t,"model-scorecard"));return`${Ys(t,"Model Scorecard Report")}
326${wr(s)}
327<h2>Model acquisition scorecard</h2>
328<table>
329<colgroup><col style="width:9%"><col style="width:13%"><col style="width:4.5%"><col style="width:5%"><col style="width:5.5%"><col style="width:7.5%"><col style="width:7.5%"><col style="width:5%"><col style="width:5%"><col style="width:5%"><col style="width:5%"><col style="width:5%"><col style="width:5.5%"><col style="width:6.5%"><col style="width:11%"></colgroup>
330<thead><tr><th>Make</th><th>Model</th><th class="num">${cs(t.analysis.periodMonths)}</th><th class="num">PY</th><th class="num">Days</th><th class="num">Front</th><th class="num">Total</th><th class="num">Vol</th><th class="num">Turn</th><th class="num">Gross</th><th class="num">Frt</th><th class="num">Trend</th><th class="num">Score</th><th>Conf.</th><th>Recommendation</th></tr></thead>
331<tbody>${r.map(n=>`<tr><td>${me(n.make)}</td><td>${me(n.model)}</td><td class="num">${le(n.vehiclesSold)}</td><td class="num">${le(n.priorYearSold)}</td><td class="num">${Ve(n.averageAge)}</td><td class="num">${yt(n.averageFrontGross)}</td><td class="num">${yt(n.averageTotalGross)}</td><td class="num">${n.scores.volume}</td><td class="num">${n.scores.turn}</td><td class="num">${n.scores.gross}</td><td class="num">${n.scores.front}</td><td class="num">${n.scores.trend}</td><td class="num"><b>${n.scores.total}</b></td><td>${Ta(n.confidence)}</td><td>${me(n.recommendation)}</td></tr>`).join("")}</tbody></table>
332${ws(r.length,a.length)}
333<div class="note">${me(Ss)}</div>
334${Hs()}`}function ei(t){const s=t.analysis,a=[...s.trims].sort((n,o)=>(n.priority??999)-(o.priority??999)||o.scores.total-n.scores.total),r=a.slice(0,Ws(t,"trim-detail"));return`${Ys(t,"Trim Detail Report")}
335${wr(s)}
336<h2>Trim-level results and sourcing score</h2>
337<table>
338<colgroup><col style="width:8%"><col style="width:11%"><col style="width:12%"><col style="width:4.5%"><col style="width:4.5%"><col style="width:5%"><col style="width:6%"><col style="width:7%"><col style="width:7%"><col style="width:7%"><col style="width:4.5%"><col style="width:5%"><col style="width:18.5%"></colgroup>
339<thead><tr><th>
339Make</th><th>Model</th><th>Trim</th><th class="num">${cs(t.analysis.periodMonths)}</th><th class="num">PY</th><th class="num">Days</th><th class="num">PTM</th><th class="num">List</th><th class="num">Front</th><th class="num">Total</th><th class="num">Qty</th><th class="num">Score</th><th>Sourcing tier</th></tr></thead>
340<tbody>${r.map(n=>`<tr><td>${me(n.make)}</td><td>${me(n.model)}</td><td>${me(n.trim)}</td><td class="num">${le(n.vehiclesSold)}</td><td class="num">${le(n.priorYearSold)}</td><td class="num">${Ve(n.averageAge)}</td><td class="num">${js(n.ptm)}</td><td class="num">${yt(n.averageListPrice)}</td><td class="num">${yt(n.averageFrontGross)}</td><td class="num">${yt(n.averageTotalGross)}</td><td class="num">${le(n.target45DayQuantity)}</td><td class="num">${le(n.scores.total)}</td><td>${me(n.sourcingTier)}</td></tr>`).join("")}</tbody></table>
341${ws(r.length,a.length)}
342<div class="note">${me(Ss)}</div>
343${Hs()}`}function ti(t,s){switch(t){case"aggressive":return Jl(s);case"risk":return Xl(s);case"model-scorecard":return Zl(s);case"trim-detail":return ei(s);default:return Ql(s)}}function Pa(t,s){return`<!DOCTYPE html>
344<html lang="en"><head><meta charset="utf-8">
345<meta name="viewport" content="width=device-width, initial-scale=1">
346<title>${me(Ps[t])} — ${me(s.dealershipName)}</title>
347<style>${Yl}
348@media screen{body{background:#eef2f7;padding:12px;}.print-page{box-shadow:0 2px 12px rgba(0,0,0,.18);}}
349</style></head>
350<body><div class="print-page">${ti(t,s)}</div></body></html>`}const Rr=t=>[t.modelYear??"",t.make??"",t.model??"",t.trim??""].join(" ").replace(/\s+/g," ").trim()||"—",si=["Stock #","VIN","Vehicle","Source","Sold date","Days to sale","Sale price","Front gross","Total gross"],ri=t=>{const s=t==null?"":String(t);return/[",\n]/.test(s)?`"${s.replace(/"/g,'""')}"`:s},ai=t=>[t.stockNumber,t.vin,Rr(t),t.source??"Unknown",t.soldDate,t.daysInInventory,t.transactionPrice,t.frontGross,t.totalGross].map(ri).join(",");function ni({open:t,onOpenChange:s,title:a,valueLabel:r,records:n,priorRecords:o,priorLabel:i}){const m=v.useMemo(()=>[si.join(","),...n.map(ai)].join(`
351`),[n]),g=()=>{const k=new Blob([m],{type:"text/csv;charset=utf-8"}),C=URL.createObjectURL(k),x=document.createElement("a");x.href=C,x.download=`${a.toLowerCase().replace(/[^a-z0-9]+/g,"-")}-vehicles.csv`,x.click(),URL.revokeObjectURL(C)},f=k=>k.map((C,x)=>e.jsxs(q,{children:[e.jsx(c,{className:"whitespace-nowrap",children:C.stockNumber??"—"}),e.jsx(c,{className:"whitespace-nowrap font-mono text-xs",children:C.vin??"—"}),e.jsx(c,{className:"min-w-[190px]",children:Rr(C)}),e.jsx(c,{className:"whitespace-nowrap",children:C.source??"Unknown"}),e.jsx(c,{className:"whitespace-nowrap",children:C.soldDate??"—"}),e.jsx(c,{className:"text-right",children:Ve(C.daysInInventory)}),e.jsx(c,{className:"text-right",children:ze(C.transactionPrice)}),e.jsx(c,{className:`text-right ${Tt(C.frontGross)?"text-red-400":""}`,children:ze(C.frontGross)}),e.jsx(c,{className:`text-right ${Tt(C.totalGross)?"text-red-400":""}`,children:ze(C.totalGross)})]},`${C.stockNumber??C.vin??"row"}-${x}`)),j=k=>k.map((C,x)=>e.jsxs("div",{className:"rounded-lg border border-white/10 bg-white/[0.02] p-3",children:[e.jsx("div",{className:"text-sm font-semibold text-foreground",children:Rr(C)}),e.jsxs("div",{className:"mt-0.5 text-xs text-muted-foreground",children:[C.stockNumber??"—"," · ",C.source??"Unknown"," · ",C.soldDate??"—"]}),e.jsxs("div",{className:"mt-2 grid grid-cols-2 gap-1 text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Days to sale"}),e.jsx("span",{className:"text-right text-foreground",children:Ve(C.daysInInventory)}),e.jsx("span",{className:"text-muted-foreground",children:"Sale price"}),e.jsx("span",{className:"text-right text-foreground",children:ze(C.transactionPrice)}),e.jsx("span",{className:"text-muted-foreground",children:"Front gross"}),e.jsx("span",{className:`text-right ${Tt(C.frontGross)?"text-red-400":"text-foreground"}`,children:ze(C.frontGross)}),e.jsx("span",{className:"text-muted-foreground",children:"Total gross"}),e.jsx("span",{className:`text-right ${Tt(C.totalGross)?"text-red-400":"text-foreground"}`,children:ze(C.totalGross)})]})]},`${C.stockNumber??C.vin??"card"}-${x}
351`)),y=(k,C)=>e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:[k," — ",le(C.length)," vehicles"]}),C.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No vehicles in this group."}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"hidden overflow-x-auto md:block",children:e.jsxs(ke,{children:[e.jsx(Le,{children:e.jsxs(q,{children:[e.jsx(h,{children:"Stock #"}),e.jsx(h,{children:"VIN"}),e.jsx(h,{children:"Vehicle"}),e.jsx(h,{children:"Source"}),e.jsx(h,{children:"Sold"}),e.jsx(h,{className:"text-right",children:"Days"}),e.jsx(h,{className:"text-right",children:"Sale price"}),e.jsx(h,{className:"text-right",children:"Front"}),e.jsx(h,{className:"text-right",children:"Total"})]})}),e.jsx(Ce,{children:f(C)})]})}),e.jsx("div",{className:"space-y-2 md:hidden",children:j(C)})]})]});return e.jsx(Gs,{open:t,onOpenChange:s,children:e.jsxs(Bs,{className:"max-h-[90vh] max-w-5xl overflow-y-auto",children:[e.jsxs(zs,{children:[e.jsx(Vs,{children:a}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[r," · ",le(n.length)," vehicles"]})]}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(ce,{size:"sm",variant:"outline",onClick:g,disabled:!n.length,children:[e.jsx(pr,{className:"mr-2 h-4 w-4"}),"Download CSV"]})}),e.jsxs("div",{className:"space-y-5",children:[y(o?"This period":"Vehicles",n),o?y(i??"Same window last year",o):null]})]})})}const Xr="This file has no sold dates. Please upload the sold report that includes a sold date for every vehicle. Nothing was saved.",Sr=(t,s,a)=>e.jsx(Zt,{componentId:`intel360:button-${t}`,appName:"Wholesale 360",componentType:"button",componentLabel:s,children:a});function li({open:t,onOpenChange:s,organizationId:a,dealershipId:r,dealershipLabel:n,userId:o,userName:i,onSaved:m}){var D;const{toast:g}=ys(),f=v.useRef(null),[j,y]=v.useState("choose"),[k,C]=v.useState(null),[x,A]=v.useState(!1),[S,X]=v.useState(null),[N,M]=v.useState(null),[L,_]=v.useState([]),[H,F]=v.useState({}),p=v.useCallback(()=>{y("choose"),C(null),X(null),M(null),_([]),F({}),A(!1)},[]),u=P=>{P||p(),s(P)},w=v.useCallback(async P=>{try{const U=await va(P),ie=ll(U),z=ie.find(G=>qs(G.name)==="source data")??[...ie].sort((G,I)=>
351Ns(U,I.name).length-Ns(U,G.name).length)[0];_((z==null?void 0:z.headers)??[])}catch{_([])}},[]),T=v.useCallback(async(P,U)=>{var ie;A(!0);try{const z=await ol(P,{columnOverrides:U});if(z.errors.length){X(z),await w(P),y("mapping");return}if(!((ie=z.records)!=null&&ie.length)){X(null),M(null),y("choose"),g({title:"No sold dates found",description:Xr,variant:"destructive"});return}const G=dr({records:z.records,filename:z.filename,dealershipLabel:z.dealershipLabel,approvedOrder:z.approvedOrder,warnings:z.warnings});X(G.report),M(G.analysis),y("preview")}catch(z){g({title:"The file could not be read",description:z instanceof Error?z.message:"Please check the file and try again.",variant:"destructive"})}finally{A(!1)}},[w,g]),$=P=>{P&&(C(P),T(P))},W=v.useMemo(()=>Dr.every(P=>H[P]!==void 0),[H]),B=v.useMemo(()=>S?vs(S.reportStartDate,S.reportEndDate,S.periodMonths):"",[S]),_e=async()=>{var P;if(!(!S||!N)){if(!a){g({title:"No store selected",description:"Choose a store before importing so the results are saved to the right place.",variant:"destructive"});return}if(!((P=S.records)!=null&&P.length)||!S.reportStartDate||!S.reportEndDate){g({title:"No sold dates found",description:Xr,variant:"destructive"});return}y("saving");try{const U=await Ul({report:S,analysis:N,organizationId:a,dealershipId:r,uploadedBy:o,uploadedByName:i});g({title:"Report imported",description:`${le(N.kpis.unitsSold)} sold vehicles loaded.`}),m(U),u(!1)}catch(U){y("preview"),g({title:"The import was not saved",description:U instanceof Error?U.message:"Nothing was saved. Please try the upload again.",variant:"destructive"})}}},ue=N==null?void 0:N.kpis;return e.jsx(Gs,{open:t,onOpenChange:u,children:e.jsxs(Bs,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(zs,{children:[e.jsx(Vs,{children:"Upload sold used-vehicle report"}),e.jsxs(xr,{children:["Sold used vehicles for ",n,". The report must include a sold date for every vehicle — the date range is read from the file. Accepts .xlsx, .xls or .csv."]})]}),j==="choose"&&e.jsxs("div",{className:"space-y-4",children:[Sr("uva-choose-file","Choose report file",e.jsxs(ce,{onClick:()=>{var P;return(P=f.current)==null?void 0:P.click()},disabled:x,className:"w-full",children:[x?e.jsx(es,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Er,{className:"mr-2 h-4 w-4"}),x?"Reading file…":"Choose file"]})),e.jsx("input",{ref:f,type:"file",accept:".xlsx,.xls,.csv",className:"hidden",onChange:P=>{var U;return $((U=P.target.files)==null?void 0:U[0])}})]}),j==="mapping"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-lg border border-amber-500/30 bg-amber-500/10 p-3 text-sm text-amber-200",children:[e.jsxs("div",{className:"flex items-center gap-2 font-medium",children:[e.jsx(Lr,{className:"h-4 w-4"})," Some required columns were not recognised"]}),e.jsx("ul",{className:"mt-1 list-disc pl-5 text-xs",children:S==null?void 0:S.errors.map(P=>e.jsx("li",{children:P},P))})]}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2",children:Dr.map(P=>e.jsxs("div",{className:"space-y-1",children:[e.jsx(Rs,{className:"text-xs",children:pa[P]??P}),e.jsxs(It,{value:H[P]!==void 0?String(H[P]):void 0,onValueChange:U=>F(ie=>({...ie,[P]:Number(U)})),children:[e.jsx(Ot,{className:"h-9",children:e.jsx(Ut,{placeholder:"Select a column"})}),e.jsx(Gt,{children:L.map((U,ie)=>e.jsx(Te,{value:String(ie),children:U||`Column ${ie+1}`},`${U}-${ie}`))})]})]},P))}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[Sr("uva-apply-mapping","Apply column mapping",e.jsxs(ce,{disabled:!W||x||!k,onClick:()=>k&&T(k,H),children:[x?e.jsx(es,{className:"mr-2 h-4 w-4 animate-spin"}):null,"Apply mapping"]})),e.jsx(ce,{variant:"outline",onClick:p,children:"Start over"})]})]}),(j==="preview"||j==="saving")&&S&&N&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-foreground",children:[e.jsx(hn,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"font-mono text-xs",children:S.filename}),e.jsx(Pe,{variant:"outline",children:"Sold vehicle report"})]}),e.jsxs("div",{className:"space-y-1 rounded-lg border border-white/10 bg-white/[0.03] p-3",children:[e.jsxs("p",{className:"text-sm text-foreground",children:[le(((D=S.records)==null?void 0:D.length)??0)," sold vehicles read · ",B]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Monthly pace and the 45-day stocking quantity are calculated from these sold dates. You can change the date range on the dashboard at any time without uploading again."})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2 sm:grid-cols-4",children:[["Store",S.dealershipLabel??n],["Rows read",le(S.rows.length)],["Model rows",le(S.modelRows.length)],["Trim rows",le(S.trimRows.length)],["Excluded (zero sold)",le(S.excludedRows)],["Vehicles sold",le(ue==null?void 0:ue.unitsSold)],["Avg. age at sale",`${Ve(ue==null?void 0:ue.averageAge)} days`],["Avg. total gross",ze(ue==null?void 0:ue.averageTotalGross)]].map(([P,U])=>e.jsxs("div",{className:"rounded-lg border border-white/10 bg-white/[0.03] p-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:P}),e.jsx("div",{className:"text-sm font-semibold text-foreground",children:U})]},P))}),S.warnings.length>0&&e.jsxs("div",{className:"rounded-lg border border-amber-500/30 bg-amber-500/10 p-3 text-xs text-amber-200",children:[e.jsxs("div",{className:"mb-1 flex items-center gap-2 font-medium",children:[e.jsx(Lr,{className:"h-4 w-4"})," Review before importing"]}),e.jsx("ul",{className:"list-disc space-y-0.5 pl-5",children:S.warnings.slice(0,8).map(P=>e.jsx("li",{children:P},P))})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[Sr("uva-confirm-import","Confirm import",e.jsxs(ce,{onClick:_e,disabled:j==="saving",children:[j==="saving"?e.jsx(es,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(ca,{className:"mr-2 h-4 w-4"}),j==="saving"?"Saving…":"Confirm and import"]}
351)),e.jsx(ce,{variant:"outline",onClick:p,disabled:j==="saving",children:"Choose a different file"})]})]})]})})}const ii=["Aggressively Source","Corrected Buy Basis","One-Off Opportunity","Avoid/Exit"];function oi({row:t,importId:s,userId:a,onClose:r,onSaved:n}){const{toast:o}=ys(),[i,m]=v.useState("Aggressively Source"),[g,f]=v.useState(""),[j,y]=v.useState(""),[k,C]=v.useState(""),[x,A]=v.useState(!1);v.useEffect(()=>{t&&(m(t.sourcingTier),f(t.priority?String(t.priority):""),y(t.acquisitionDirection),C(""))},[t]);const S=t?{make:t.make,model:t.model,trim:t.trim}:null,X=async()=>{if(!(!t||!s||!S)){if(!k.trim()){o({title:"Add a reason",description:"A short reason keeps the change explainable later.",variant:"destructive"});return}A(!0);try{await Aa(s,S,{management_override:!0,override_tier:i,override_priority:g.trim()?Number(g):null,override_direction:j.trim()||null,override_reason:k.trim(),approved:!0,approved_by:a}),o({title:"Change saved",description:`${Vr(t)} updated.`}),n(),r()}catch(M){o({title:"The change was not saved",description:M instanceof Error?M.message:"Please try again.",variant:"destructive"})}finally{A(!1)}}},N=async()=>{if(!(!t||!s||!S)){A(!0);try{await zl(s,S),o({title:"Calculated values restored"}),n(),r()}catch(M){o({title:"The values were not restored",description:M instanceof Error?M.message:"Please try again.",variant:"destructive"})}finally{A(!1)}}};return e.jsx(Gs,{open:!!t,onOpenChange:M=>!M&&r(),children:e.jsxs(Bs,{className:"max-w-lg",children:[e.jsxs(zs,{children:[e.jsx(Vs,{children:"Adjust acquisition decision"}),e.jsx(xr,{children:t?Vr(t):""})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(Rs,{className:"text-xs",children:"Sourcing tier"}),e.jsxs(It,{value:i,onValueChange:M=>m(M),children:[e.jsx(Ot,{className:"h-9",children:e.jsx(Ut,{})}),e.jsx(Gt,{children:ii.map(M=>e.jsx(Te,{value:M,children:M},M))})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(Rs,{className:"text-xs",children:"Priority position (blank leaves it unranked)"}),e.jsx(Ct,{value:g,inputMode:"numeric",onChange:M=>f(M.target.value.replace(/[^0-9]/g,"")),className:"h-9"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(Rs,{className:"text-xs",children:"Acquisition direction"}),e.jsx(Ct,{value:j,onChange:M=>y(M.target.value),className:"h-9"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(Rs,{className:"text-xs",children:"Reason for the change"}),e.jsx(un,{value:k,onChange:M=>C(M.target.value),rows:2})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(ce,{onClick:X,disabled:x,children:"Save change"}),e.jsx(ce,{variant:"outline",onClick:N,disabled:x,children:"Restore calculated values"})]})]})]})})}const ci=["executive","aggressive","risk","model-scorecard","trim-detail"];function di({analysis:t,dealershipName:s,reportPeriod:a,filterSummary:r,sourceRows:n,importId:o,organizationId:i,dealershipId:m,userId:g}){const{toast:f}=ys(),[j,y]=v.useState("executive"),[k,C]=v.useState(void 0),[x,A]=v.useState(null),S=v.useRef(null),X=v.useMemo(()=>({dealershipName:s,reportPeriod:a,generatedAt:new Date,analysis:t,filterSummary:r,sourceRows:n,maxRows:k}),[s,a,t,r,n,k]),N=v.useMemo(()=>Pa(j,X),[j,X]);v.useEffect(()=>{C(void 0),A(null)},[j]);const M=v.useCallback(()=>{var w;const F=(w=S.current)==null?void 0:w.contentDocument,p=F==null?void 0:F.querySelector(".print-page");if(!p)return;if(p.scrollHeight>p.clientHeight+2||p.scrollWidth>p.clientWidth+2){const T=k??Ma[j];if(T>7){C(T-2);return}A(!1);return}A(!0)},[k,j]),L=()=>{var p;const F=(p=S.current)==null?void 0:p.contentWindow;F&&(F.focus(),F.print())},_=()=>{const F=new Blob([N],{type:"text/html;charset=utf-8"}),p=URL.createObjectURL(F),u=document.createElement("a");u.href=p,u.download=`intel360-${j}-${new Date().toISOString().slice(0,10)}.html`,u.click(),URL.revokeObjectURL(p)},H=async()=>{if(!(!o||!i))try{await ql({importId:o,organizationId:i,dealershipId:m,reportType:j,reportName:`${Ps[j]} — ${s}`,filters:{filterSummary:r??null,maxRows:k??null},html:N,createdBy:g}),f({title:"Report saved",description:"You can reopen it from your saved reports."})}
351catch(F){f({title:"The report was not saved",description:F instanceof Error?F.message:"Please try again.",variant:"destructive"})}};return e.jsxs($e,{className:"bg-white/[0.03] border-white/10",children:[e.jsxs(At,{className:"pb-3",children:[e.jsx(Mt,{className:"text-base",children:"Report center"}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-2",children:ci.map(F=>e.jsx(Zt,{componentId:`intel360:button-uva-report-${F}`,appName:"Wholesale 360",componentType:"button",componentLabel:Ps[F],children:e.jsx(ce,{size:"sm",variant:F===j?"default":"outline",onClick:()=>y(F),className:"min-h-[36px]",children:Ps[F]})},F))})]}),e.jsxs(Ae,{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[x===!0&&e.jsxs(Pe,{className:"bg-emerald-500/15 text-emerald-300",children:[e.jsx(ca,{className:"mr-1 h-3 w-3"})," Fits on one page"]}),x===!1&&e.jsxs(Pe,{className:"bg-amber-500/15 text-amber-200",children:[e.jsx(Lr,{className:"mr-1 h-3 w-3"})," Trimmed as far as readable text allows"]}),k!==void 0&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["Row cap reduced to ",k," to keep one page."]}),e.jsxs("div",{className:"ml-auto flex flex-wrap gap-2",children:[e.jsxs(ce,{size:"sm",variant:"outline",onClick:L,children:[e.jsx(Is,{className:"mr-1.5 h-3.5 w-3.5"})," Print"]}),e.jsxs(ce,{size:"sm",variant:"outline",onClick:_,children:[e.jsx(pr,{className:"mr-1.5 h-3.5 w-3.5"})," Download HTML"]}),e.jsxs(ce,{size:"sm",variant:"outline",onClick:H,disabled:!o,children:[e.jsx(mn,{className:"mr-1.5 h-3.5 w-3.5"})," Save"]})]})]}),e.jsx("div",{className:"overflow-auto rounded-lg border border-white/10 bg-white",children:e.jsx("iframe",{ref:S,title:`${Ps[j]} preview`,srcDoc:N,onLoad:M,className:"h-[560px] w-full min-w-[1040px] border-0"})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"The preview is exactly what prints: one US Letter landscape page, no navigation or buttons."})]})]})}const Zr=["Aggressively Source","Corrected Buy Basis","One-Off Opportunity","Avoid/Exit"],pe="__any__",hi={units:"Units sold",prior:"Vs. prior year",age:"Average age at sale",front:"Average front gross",total:"Average total gross",ford:"Ford mix",trade:"Sales with a trade"},Zs=(t,s)=>(s.soldDate??"").localeCompare(t.soldDate??""),er=t=>t??Number.POSITIVE_INFINITY,ea=t=>t??Number.NEGATIVE_INFINITY,Ts=(t,s,a)=>e.jsx(Zt,{componentId:`intel360:button-${t}`,appName:"Wholesale 360",componentType:"button",componentLabel:s,children:a}),_t=t=>e.jsx("span",{className:Tt(t)?"text-red-300":"text-foreground",children:ze(t)}),tr=t=>e.jsx(Pe,{className:t==="High"?"bg-emerald-500/15 text-emerald-300":t==="Medium"?"bg-amber-500/15 text-amber-200":"bg-rose-500/15 text-rose-200",children:t}),ui=t=>e.jsx(Pe,{className:t==="Avoid"?"bg-rose-500/20 text-rose-200":t==="High"?"bg-rose-500/15 text-rose-200":t==="Watch"?"bg-amber-500/15 text-amber-200":"bg-emerald-500/15 text-emerald-300",children:t}),ta={source:pe,make:pe,model:pe,trim:pe,tier:pe,confidence:pe,recommendation:pe,risk:pe};function mi(){const{toast:t}=ys(),{currentUser:s,isAdmin:a,isPlatformAdmin:r}=Pr(),{selectedDealership:n}=Us(),{selectedIds:o,selectedDealerships:i,scopeLabel:m}=br(),g=(s==null?void 0:s.organization_id)??(n==null?void 0:n.organization_id)??null,f=o.length===1?o[0]:(n==null?void 0:n.id)??null,j=a||r,[y,k]=v.useState([]),[C,x]=v.useState(null),[A,S]=v.useState(null),[X,N]=v.useState(!0),[M,L]=v.useState("overview"),[_,H]=v.useState(ta),[F,p]=v.useState(!1),[u,w]=v.useState(null),[T,$]=v.useState(!1),[W,B]=v.useState("all"),[_e,ue]=v.useState(""),[D,P]=v.useState(""),U=v.useCallback(async()=>{if(!g){N(!1);return}try{const d=await Ol(g,o);k(d),x(V=>{var K,Fe;return V??((K=d.find(be=>be.is_active))==null?void 0:K.id)??((Fe=d[0])==null?void 0:Fe.id)??null})}catch(d){t({title:"The saved reports could not be loaded",description:d instanceof Error?d.message:"Please try again.",variant:"destructive"})}finally{N(!1)}},[g,o,t]);v.useEffect(()=>{U()},[U]);const ie=v.useCallback(async()=>{if(!C){S(null);return}N(!0);try{S(await Bl(C))}catch(d){S(null),t({title:"That report could not be opened",description:d instanceof Error?d.message:"Please try again.",variant:"destructive"})}finally{N(!1)}},[C,t]);v.useEffect(()=>{ie()},[ie]);const z=(A==null?void 0:A.records)??[],G=z.length>0,I=v.useMemo(()=>Ca(z),[z]),he=v.useMemo(()=>
351{if(!G||!I.end)return{start:null,end:null};if(W==="custom")return{start:_e||I.start,end:D||I.end};if(W==="all")return I;if(W==="cur-month"||W==="prev-month"){const ct=new Date,ds=$t=>`${$t.getFullYear()}-${String($t.getMonth()+1).padStart(2,"0")}-${String($t.getDate()).padStart(2,"0")}`;let ns,ts;return W==="cur-month"?(ns=ds(new Date(ct.getFullYear(),ct.getMonth(),1)),ts=ds(ct)):(ns=ds(new Date(ct.getFullYear(),ct.getMonth()-1,1)),ts=ds(new Date(ct.getFullYear(),ct.getMonth(),0))),I.start&&ns<I.start&&(ns=I.start),I.end&&ts>I.end&&(ts=I.end),{start:ns,end:ts}}const d=W==="30d"?30:W==="90d"?90:W==="6m"?183:365,[V,K,Fe]=I.end.split("-").map(Number),be=new Date(Date.UTC(V,K-1,Fe)-(d-1)*864e5).toISOString().slice(0,10);return{start:be>(I.start??be)?be:I.start,end:I.end}},[G,I,W,_e,D]),De=v.useMemo(()=>!G||!A?null:dr({records:z,filename:A.record.filename,dealershipLabel:A.record.dealership_label,start:he.start,end:he.end,approvedOrder:A.report.approvedOrder,warnings:A.report.warnings}),[G,A,z,he]),Ne=(De==null?void 0:De.analysis)??(A==null?void 0:A.analysis)??null,st=v.useMemo(()=>G?cr(z,he.start,he.end):[],[G,z,he]),de=v.useMemo(()=>{const d=(Ne==null?void 0:Ne.trims)??[],V=K=>Array.from(new Set(K.filter(Fe=>!!Fe))).sort();return{makes:V(d.map(K=>K.make)),models:V(d.filter(K=>_.make===pe||K.make===_.make).map(K=>K.model)),trims:V(d.filter(K=>(_.make===pe||K.make===_.make)&&(_.model===pe||K.model===_.model)).map(K=>K.trim)),recommendations:V(((Ne==null?void 0:Ne.models)??[]).map(K=>K.recommendation)),sources:V(z.map(K=>K.source??null))}},[Ne,_.make,_.model,z]),ge=v.useCallback(d=>(_.make===pe||d.make===_.make)&&(_.model===pe||d.model===_.model)&&(_.trim===pe||d.trim===_.trim)&&(_.tier===pe||d.sourcingTier===_.tier)&&(_.confidence===pe||d.confidence===_.confidence)&&(_.risk===pe||d.riskLevel===_.risk),[_]),Me=v.useCallback(d=>(_.make===pe||d.make===_.make)&&(_.model===pe||d.model===_.model)&&(_.confidence===pe||d.confidence===_.confidence)&&(_.recommendation===pe||d.recommendation===_.recommendation)&&(_.risk===pe||d.riskLevel===_.risk),[_]),se=v.useCallback(d=>(_.make===pe||d.make===_.make)&&(_.model===pe||d.model===_.model)&&(_.trim===pe||d.trim===_.trim)&&(_.source===pe||(d.source??"Unknown")===_.source),[_.make,_.model,_.trim,_.source]),we=_.make!==pe||_.model!==pe||_.trim!==pe||_.source!==pe,Oe=Object.values(_).some(d=>d!==pe),je=v.useMemo(()=>!G||!A||!we?null:dr({records:z,filename:A.record.filename,dealershipLabel:A.record.dealership_label,start:he.start,end:he.end,approvedOrder:A.report.approvedOrder,warnings:A.report.warnings,recordFilter:se}),[G,A,z,he,we,se]),ae=v.useMemo(()=>{const d=(je==null?void 0:je.analysis)??Ne;if(!d)return null;const V=d.models.filter(Me),K=d.trims.filter(ge),Fe=Oe?yl(V,d.kpis):d.kpis;return{...d,models:V,trims:K,kpis:Fe,findings:Oe?ka(V):d.findings}},[Ne,je,Me,ge,Oe]),re=v.useMemo(()=>we?st.filter(se):st,[we,st,se]),it=v.useMemo(()=>G?El(re):[],[G,re]),[te,Ee]=v.useState(null),Nt=v.useMemo(()=>{if(!te)return[];const d=[...re];switch(te){case"age":return d.sort((V,K)=>ea(K.daysInInventory)-ea(V.daysInInventory));case"front":return d.sort((V,K)=>er(V.frontGross)-er(K.frontGross));case"total":return d.sort((V,K)=>er(V.totalGross)-er(K.totalGross));case"ford":return d.filter(V=>(V.make??"").toLowerCase()==="ford").sort(Zs);case"trade":return d.filter(V=>V.isTrade).sort(Zs);default:return d.sort(Zs)}},[te,re]),zt=v.useMemo(()=>{if(!(te!=="prior"||!he.start||!he.end))return cr(z.filter(se),Fs(he.start,-1),Fs(he.end,-1)).sort(Zs)},[te,he,z,se]),xt=v.useMemo(()=>G?Dl(re):[],[G,re]),Kt=v.useMemo(()=>G?Rl(re):[],[G,re]),We=v.useMemo(()=>G?Pl(re):[],[G,re]),fe=(A==null?void 0:A.record)??null,ye=(fe==null?void 0:fe.dealership_label)??(i.length===1?i[0].name:m),Xe=G?(De==null?void 0:De.analysis.periodMonths)??rs:(fe==null?void 0:fe.period_months)??(Ne==null?void 0:Ne.periodMonths)??rs,rt=cs(Xe),St=G?vs(he.start,he.end,Xe):(fe==null?void 0:fe.report_period_label)??vs(fe==null?void 0:fe.report_start_date,fe==null?void 0:fe.report_end_date,Xe),Qt=v.useMemo(()=>{const d=Object.entries(_).filter(([,V])=>V!==pe).map(([V,K])=>`${V}: ${K}`);return d.length?`Filtered — ${d.join(", ")}`:void 0},[_]),Dt=v.useCallback(()=>ae?Pa("executive",{dealershipName:ye,reportPeriod:St,generatedAt:new Date,analysis:ae,filterSummary:Qt,sourceRows:it}):"",[ae,ye,St,Qt,it]),pt=()=>{const d=Dt();if(!d)return;const V=document.createElement("iframe");V.style.position="fixed",V.style.right="100%",V.style.width="11in",V.style.height="8.5in",V.srcdoc=d,V.onload=()=>{var K,Fe;(K=V.contentWindow)==null||K.focus(),(Fe=V.contentWindow)==null||Fe.print(),setTimeout(()=>V.remove(),1e3)},document.body.appendChild(V)},ot=()=>{const d=Dt();if(!d)return;const V=new Blob([d],{type:"text/html;charset=utf-8"}),K=URL.createObjectURL(V),Fe=document.createElement("a");Fe.href=K,Fe.download=`intel360-used-vehicle-acquisition-${new Date().toISOString().slice(0,10)}.html`,Fe.click(),URL.revokeObjectURL(K)},at=async d=>{if(g)try{await Vl(d,g,f),x(d),await U(),t({title:"Report activated"})}catch(V){t({title:"That report could not be activated",description:V 
351instanceof Error?V.message:"Please try again.",variant:"destructive"})}},oe=ae==null?void 0:ae.kpis,Rt=v.useMemo(()=>{if(!te)return"";switch(te){case"prior":return`${bt(oe==null?void 0:oe.changeVsPriorYear)} vs. prior year`;case"age":return`${Ve(oe==null?void 0:oe.averageAge)} days average`;case"front":return`${ze(oe==null?void 0:oe.averageFrontGross)} average front gross`;case"total":return`${ze(oe==null?void 0:oe.averageTotalGross)} average total gross`;case"ford":return`${bt(oe==null?void 0:oe.fordMix)} of units`;case"trade":return`${bt(oe==null?void 0:oe.tradeRate)} of units`;default:return St}},[te,oe,St]),as=ae?hr(ae):[],Ue=ae?ur(ae):[],Vt=(d,V,K,Fe)=>e.jsxs("div",{className:"min-w-[140px] flex-1",children:[e.jsx("div",{className:"mb-1 text-[11px] uppercase tracking-wide text-muted-foreground",children:d}),e.jsxs(It,{value:V,onValueChange:Fe,children:[e.jsx(Ot,{className:"h-9",children:e.jsx(Ut,{})}),e.jsxs(Gt,{children:[e.jsx(Te,{value:pe,children:"All"}),K.map(be=>e.jsx(Te,{value:be,children:be},be))]})]})]});return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("h2",{className:"text-lg font-semibold text-foreground",children:"Used Vehicle Acquisition Analysis"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[ye," · ",St,fe?` · ${fe.filename}`:""]})]}),Ts("uva-upload","Upload New Report",e.jsxs(ce,{onClick:()=>p(!0),className:"min-h-[40px]",children:[e.jsx(Er,{className:"mr-2 h-4 w-4"})," Upload New Report"]})),Ts("uva-generate-report","Generate Report",e.jsx(ce,{variant:"outline",onClick:()=>L("reports"),disabled:!ae,children:"Generate Report"})),Ts("uva-print","Print",e.jsxs(ce,{variant:"outline",onClick:pt,disabled:!ae,children:[e.jsx(Is,{className:"mr-2 h-4 w-4"})," Print"]})),Ts("uva-download-html","Download HTML",e.jsxs(ce,{variant:"outline",onClick:ot,disabled:!ae,children:[e.jsx(pr,{className:"mr-2 h-4 w-4"})," Download HTML"]}))]}),e.jsx($e,{className:"bg-white/[0.03] border-white/10",children:e.jsxs(Ae,{className:"flex flex-wrap items-end gap-3 p-3",children:[e.jsxs("div",{className:"min-w-[180px] max-w-[320px] flex-1",children:[e.jsx("div",{className:"mb-1 text-[11px] uppercase tracking-wide text-muted-foreground",children:"Imported report"}),e.jsx("div",{className:"flex h-9 items-center text-sm text-foreground",children:fe?`${fe.report_start_date&&fe.report_end_date?vs(fe.report_start_date,fe.report_end_date,null):fe.report_period_label??fe.filename} · ${Number(Xe.toFixed(1))} months of data`:"No report imported"})]}),G&&e.jsxs("div",{className:"min-w-[160px] flex-1",children:[e.jsx("div",{className:"mb-1 text-[11px] uppercase tracking-wide text-muted-foreground",children:"Sold date range"}),e.jsx(Zt,{componentId:"intel360:select-uva-date-range",appName:"Wholesale 360",componentType:"dropdown",componentLabel:"Sold date range",children:e.jsxs(It,{value:W,onValueChange:B,children:[e.jsx(Ot,{className:"h-9",children:e.jsx(Ut,{})}),e.jsxs(Gt,{children:[e.jsx(Te,{value:"all",children:"All sold dates"}),e.jsx(Te,{value:"cur-month",children:"Current month"}),e.jsx(Te,{value:"prev-month",children:"Last month"}),e.jsx(Te,{value:"30d",children:"Last 30 days"}),e.jsx(Te,{value:"90d",children:"Last 90 days"}),e.jsx(Te,{value:"6m",children:"Last 6 months"}),e.jsx(Te,{value:"12m",children:"Last 12 months"}),e.jsx(Te,{value:"custom",children:"Custom dates"})]})]})})]}),G&&W==="custom"&&e.jsxs("div",{className:"flex min-w-[220px] flex-1 items-end gap-2",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"mb-1 text-[11px] uppercase tracking-wide text-muted-foreground",children:"From"}),e.jsx("input",{type:"date",value:_e,min:I.start??void 0,max:I.end??void 0,onChange:d=>ue(d.target.value),className:"h-9 w-full rounded-md border border-white/10 bg-black/25 px-2 text-sm text-foreground"})]}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"mb-1 text-[11px] uppercase tracking-wide text-muted-foreground",children:"To"}),e.jsx("input",{type:"date",value:D,min:I.start??void 0,max:I.end??void 0,onChange:d=>P(d.target.value),className:"h-9 w-full rounded-md border border-white/10 bg-black/25 px-2 text-sm text-foreground"})]})]}),G&&Vt("Source",_.source,de.sources,d=>H(V=>({...V,source:d}
351))),Vt("Make",_.make,de.makes,d=>H(V=>({...V,make:d,model:pe,trim:pe}))),Vt("Model",_.model,de.models,d=>H(V=>({...V,model:d,trim:pe}))),Vt("Trim",_.trim,de.trims,d=>H(V=>({...V,trim:d}))),Vt("Sourcing tier",_.tier,Zr,d=>H(V=>({...V,tier:d}))),Vt("Confidence",_.confidence,["High","Medium","Low"],d=>H(V=>({...V,confidence:d}))),Vt("Recommendation",_.recommendation,de.recommendations,d=>H(V=>({...V,recommendation:d}))),Vt("Risk level",_.risk,["Avoid","High","Watch","Normal"],d=>H(V=>({...V,risk:d}))),Ts("uva-reset-filters","Reset Filters",e.jsxs(ce,{variant:"ghost",onClick:()=>H(ta),className:"min-h-[36px]",children:[e.jsx(Ka,{className:"mr-2 h-4 w-4"})," Reset Filters"]}))]})}),X&&e.jsxs("div",{className:"flex items-center gap-2 p-8 text-sm text-muted-foreground",children:[e.jsx(es,{className:"h-4 w-4 animate-spin"})," Loading acquisition analysis…"]}),!X&&!A&&e.jsx($e,{className:"bg-white/[0.03] border-white/10",children:e.jsxs(Ae,{className:"p-8 text-center text-sm text-muted-foreground",children:["No sold-vehicle report has been imported for ",ye," yet. Upload your sold used vehicles to see what to source."]})}),!X&&A&&ae&&e.jsxs(na,{value:M,onValueChange:L,children:[e.jsx("div",{className:"-mx-1 overflow-x-auto px-1 pb-0.5",children:e.jsxs(la,{className:"flex w-max min-w-full",children:[e.jsx(ht,{value:"overview",children:"Overview"}),e.jsx(ht,{value:"aggressive",children:"Aggressive Sourcing"}),e.jsx(ht,{value:"models",children:"Model Scorecard"}),e.jsx(ht,{value:"trims",children:"Trim Detail"}),e.jsx(ht,{value:"risks",children:"Risks"}),G&&e.jsx(ht,{value:"source",children:"Source"}),G&&e.jsx(ht,{value:"bands",children:"Age Bands"}),G&&e.jsx(ht,{value:"monthly",children:"Monthly Trend"}),G&&e.jsx(ht,{value:"pricing",children:"Pricing"}),e.jsx(ht,{value:"history",children:"Import History"}),e.jsx(ht,{value:"reports",children:"Report Center"})]})}),e.jsxs(ut,{value:"overview",className:"mt-4 space-y-4",children:[e.jsx("div",{className:"grid grid-cols-2 gap-2 sm:grid-cols-3 lg:grid-cols-7",children:[{key:"units",label:`Units sold (${rt})`,value:le(oe==null?void 0:oe.unitsSold)},{key:"prior",label:"Vs. prior year",value:bt(oe==null?void 0:oe.changeVsPriorYear)},{key:"age",label:"Avg. age at sale",value:`${Ve(oe==null?void 0:oe.averageAge)} days`},{key:"front",label:"Avg. front gross",value:ze(oe==null?void 0:oe.averageFrontGross)},{key:"total",label:"Avg. total gross",value:ze(oe==null?void 0:oe.averageTotalGross)},{key:"ford",label:"Ford mix",value:bt(oe==null?void 0:oe.fordMix)},{key:"trade",label:"Sales with a trade",value:(oe==null?void 0:oe.tradeRate)!==null&&(oe==null?void 0:oe.tradeRate)!==void 0?`${bt(oe.tradeRate)} (${le(oe.tradeCount)})`:"—"}].map(d=>{const V=e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:d.label}),e.jsx("div",{className:"text-lg font-semibold text-foreground",children:d.value})]});return G?e.jsx(Zt,{componentId:`intel360:tile-uva-kpi-${d.key}`,appName:"Wholesale 360",componentType:"button",componentLabel:d.label,children:e.jsx("button",{type:"button",onClick:()=>Ee(d.key),className:"w-full rounded-xl border border-white/10 bg-white/[0.03] p-3 text-left transition-colors hover:border-primary/40 hover:bg-white/[0.06] focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/60",title:"Click to see the vehicles behind this number",children:V})},d.key):e.jsx("div",{className:"rounded-xl border border-white/10 bg-white/[0.03] p-3",children:V},d.key)})}),e.jsx($e,{className:"border-emerald-500/30 bg-emerald-500/10",children:e.jsxs(Ae,{className:"p-4",children:[e.jsx("div",{className:"mb-1 text-[11px] font-semibold uppercase tracking-wide text-emerald-300",children:"Acquisition conclusion"}),e.jsx("p",{className:"text-sm leading-relaxed text-foreground",children:ae.conclusion})]})}),e.jsxs($e,{className:"bg-white/[0.03] border-white/10",children:[e.jsx(At,{className:"pb-2",children:e.jsx(Mt,{className:"text-base",children:"Management findings"})}),e.jsxs(Ae,{className:"space-y-2",children:[ae.findings.map(d=>e.jsxs("div",{className:"rounded-lg border border-white/10 bg-white/[0.02] p-3",children:[e.jsxs("div",{className:"flex flex-wrap items-baseline gap-2",children:[e.jsx("span",{className:"text-sm font-semibold text-foreground",children:d.value}),e.jsx("span",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:d.label})]}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:d.detail})]},d.label)),e.jsxs("button",{type:"button",onClick:()=>$(d=>!d),className:"flex items-center gap-1 text-xs text-primary underline-offset-2 hover:underline",children:[e.jsx(ra,{className:`h-3.5 w-3.5 transition ${T?"rotate-180":""}`}),"How this was calculated"]}),T&&e.jsx("ul",{className:"space-y-1 rounded-lg border border-white/10 bg-black/20 p-3 text-xs text-muted-foreground",children:ae.findings.map(d=>e.jsxs("li",{children:[e.jsxs("span",{className:"text-foreground",children:[d.label,":"]}
351)," ",d.method]},`m-${d.label}`))}),e.jsx("p",{className:"pt-1 text-xs text-muted-foreground",children:Ss})]})]})]}),e.jsxs(ut,{value:"aggressive",className:"mt-4 space-y-4",children:[e.jsxs($e,{className:"bg-white/[0.03] border-white/10",children:[e.jsx(At,{className:"pb-2",children:e.jsx(Mt,{className:"text-base",children:"Aggressively source — exact make, model and trim"})}),e.jsx(Ae,{className:"p-0",children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(ke,{children:[e.jsx(Le,{children:e.jsxs(q,{children:[e.jsx(h,{className:"w-10",children:"#"}),e.jsx(h,{children:"Make"}),e.jsx(h,{children:"Model"}),e.jsx(h,{children:"Trim"}),e.jsxs(h,{className:"text-right",children:[rt," sold"]}),e.jsx(h,{className:"text-right",children:"Prior yr."}),e.jsx(h,{className:"text-right",children:"Monthly pace"}),e.jsx(h,{className:"text-right",children:"Avg. days"}),e.jsx(h,{className:"text-right",children:"PTM"}),e.jsx(h,{className:"text-right",children:"Avg. list"}),e.jsx(h,{className:"text-right",children:"Avg. front"}),e.jsx(h,{className:"text-right",children:"Avg. total"}),e.jsxs(h,{className:"text-right",children:["Est. ",rt," gross"]}),e.jsx(h,{className:"text-right",children:"45-day qty"}),e.jsx(h,{className:"text-right",children:"Score"}),e.jsx(h,{children:"Confidence"}),e.jsx(h,{children:"Acquisition direction"}),j&&e.jsx(h,{className:"w-16",children:"Adjust"})]})}),e.jsx(Ce,{children:as.map(d=>e.jsxs(q,{children:[e.jsx(c,{className:"text-right",children:d.priority??"—"}),e.jsx(c,{children:d.make}),e.jsx(c,{children:d.model}),e.jsx(c,{children:d.trim}),e.jsx(c,{className:"text-right",children:le(d.vehiclesSold)}),e.jsx(c,{className:"text-right",children:d.newDemand?"New demand":le(d.priorYearSold)}),e.jsx(c,{className:"text-right",children:Ve(d.monthlyPace,2)}),e.jsx(c,{className:"text-right",children:Ve(d.averageAge)}),e.jsx(c,{className:"text-right",children:js(d.ptm)}),e.jsx(c,{className:"text-right",children:_t(d.averageListPrice)}),e.jsx(c,{className:"text-right",children:_t(d.averageFrontGross)}),e.jsx(c,{className:"text-right",children:_t(d.averageTotalGross)}),e.jsx(c,{className:"text-right",children:_t(d.estimatedThreeMonthGross)}),e.jsx(c,{className:"text-right",children:le(d.target45DayQuantity)}),e.jsx(c,{className:"text-right",children:le(d.scores.total)}),e.jsx(c,{children:tr(d.confidence)}),e.jsxs(c,{className:"max-w-[260px] whitespace-normal text-xs",children:[d.acquisitionDirection,d.managementApproved&&e.jsx(Pe,{variant:"outline",className:"ml-1 text-[10px]",children:"management set"})]}),j&&e.jsx(c,{children:e.jsx(ce,{size:"sm",variant:"ghost",onClick:()=>w(d),children:e.jsx(Br,{className:"h-3.5 w-3.5"})})})]},`${d.make}-${d.model}-${d.trim}`))})]})})})]}),Zr.filter(d=>d!=="Aggressively Source").map(d=>{const V=ae.trims.filter(K=>K.sourcingTier===d);return V.length?e.jsxs($e,{className:"bg-white/[0.03] border-white/10",children:[e.jsx(At,{className:"pb-2",children:e.jsx(Mt,{className:"text-base",children:d})}),e.jsx(Ae,{className:"p-0",children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(ke,{children:[e.jsx(Le,{children:e.jsxs(q,{children:[e.jsx(h,{children:"Make"}),e.jsx(h,{children:"Model"}),e.jsx(h,{children:"Trim"}),e.jsxs(h,{className:"text-right",children:[rt," sold"]}),e.jsx(h,{className:"text-right",children:"Avg. days"}),e.jsx(h,{className:"text-right",children:"Avg. front"}),e.jsx(h,{className:"text-right",children:"Avg. total"}),e.jsx(h,{className:"text-right",children:"45-day qty"}),e.jsx(h,{className:"text-right",children:"Score"}),e.jsx(h,{children:"Confidence"}),e.jsx(h,{children:"Acquisition direction"}),j&&e.jsx(h,{className:"w-16",children:"Adjust"})]})}),e.jsx(Ce,{children:V.map(K=>e.jsxs(q,{children:[e.jsx(c,{children:K.make}),e.jsx(c,{children:K.model}),e.jsx(c,{children:K.trim}),e.jsx(c,{className:"text-right",children:le(K.vehiclesSold)}),e.jsx(c,{className:"text-right",children:Ve(K.averageAge)}),e.jsx(c,{className:"text-right",children:_t(K.averageFrontGross)}),e.jsx(c,{className:"text-right",children:_t(K.averageTotalGross)}),e.jsx(c,{className:"text-right",children:le(K.target45DayQuantity)}),e.jsx(c,{className:"text-right",children:le(K.scores.total)}),e.jsx(c,{children:tr(K.confidence)}),e.jsx(c,{className:"max-w-[260px] whitespace-normal text-xs",children:K.acquisitionDirection}),j&&e.jsx(c,{children:e.jsx(ce,{size:"sm",variant:"ghost",onClick:()=>w(K),children:e.jsx(Br,{className:"h-3.5 w-3.5"})})})]},`${d}-${K.make}-${K.model}-${K.trim}`))})]})})})]},d):null})]}),e.jsx(ut,{value:"models",className:"mt-4",children:e.jsx($e,{className:"bg-white/[0.03] border-white/10",children:e.jsx(Ae,{className:"p-0",children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(ke,{children:[e.jsx(Le,{children:e.jsxs(q,{children:[e.jsx(h,{children:"Make"}),e.jsx(h,{children:"Model"}),e.jsxs(h,{className:"text-right",children:[rt," sold"]}),e.jsx(h,{className:"text-right",children:"Prior yr."}),e.jsx(h,{className:"text-right",children:"Change"}),e.jsx(h,{className:"text-right",children:"Avg. days"}),e.jsx(h,{className:"text-right",children:"Avg. front"}),e.jsx(h,{className:"text-right",children:"Avg. back"}),e.jsx(h,{className:"text-right",children:"Avg. total"}),e.jsx(h,{className:"text-right",children:"Volume"}),e.jsx(h,{className:"text-right",children:"Turn"}),e.jsx(h,{className:"text-right",children:"Gross"}),e.jsx(h,{className:"text-right",children:"Front"}),e.jsx(h,{className:"text-right",children:"Trend"}),e.jsx(h,{className:"text-right",children:"Score"}),e.jsx(h,{children:"Confidence"}),e.jsx(h,{children:"Recommendation"})]})}),e.jsx(Ce,{children:[...ae.models].sort((d,V)=>V.scores.total-d.scores.total).map(d=>e.jsxs(q,{children:[e.jsx(c,{children:d.make}),e.jsx(c,{children:d.model}),e.jsx(c,{className:"text-right",children:le(d.vehiclesSold)}),e.jsx(c,{className:"text-right",children:le(d.priorYearSold)}),e.jsx(c,{className:"text-right",children:d.newDemand?"New demand":bt(d.salesChangePct)}),e.jsx(c,{className:"text-right",children:Ve(d.averageAge)}),e.jsx(c,{className:"text-right",children:_t(d.averageFrontGross)}),e.jsx(c,{className:"text-right",children:_t(d.averageBackGross)}),e.jsx(c,{className:"text-right",children:_t(d.averageTotalGross)}),e.jsx(c,{className:"text-right",children:d.scores.volume}),e.jsx(c,{className:"text-right",children:d.scores.turn}),e.jsx(c,{className:"text-right",children:d.scores.gross}),e.jsx(c,{className:"text-right",children:d.scores.front}),e.jsx(c,{className:"text-right",children:d.scores.trend}),e.jsx(c,{className:"text-right font-semibold",children:d.scores.total}),e.jsx(c,{children:tr(d.confidence)}),e.jsx(c,{children:d.recommendation})]},`${d.make}-${d.model}`))})]})})})})}),e.jsx(ut,{value:"trims",className:"mt-4",children:e.jsx($e,{className:"bg-white/[0.03] border-white/10",children:e.jsx(Ae,{className:"p-0",children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(ke,{children:[e.jsx(Le,{children:e.jsxs(q,{children:[e.jsx(h,{children:"Make"}),e.jsx(h,{children:"Model"}),e.jsx(h,{children:"Trim"}),e.jsxs(h,{className:"text-right",children:[rt," sold"]}),e.jsx(h,{className:"text-right",children:"Prior yr."}),e.jsx(h,{className:"text-right",children:"Avg. days"}),e.jsx(h,{className:"text-right",children:"PTM"}),e.jsx(h,{className:"text-right",children:"Avg. list"}),e.jsx(h,{className:"text-right",children:"Discount"}),e.jsx(h,{className:"text-right",children:"Avg. front"}),e.jsx(h,{className:"text-right",children:"Trade +/-"}),e.jsx(h,{className:"text-right",children:"Avg. total"}),e.jsx(h,{className:"text-right",children:"45-day qty"}),e.jsx(h,{className:"text-right",children:"Score"}),e.jsx(h,{children:"Confidence"}),e.jsx(h,{children:"Sourcing tier"})]})}),e.jsx(Ce,{children:[...ae.trims].sort((d,V)=>(d.priority??999)-(V.priority??999)||V.scores.total-d.scores.total).map(d=>e.jsxs(q,{children:[e.jsx(c,{children:d.make}),e.jsx(c,{children:d.model}),e.jsx(c,{children:d.trim}),e.jsx(c,{className:"text-right",children:le(d.vehiclesSold)}),e.jsx(c,{className:"text-right",children:le(d.priorYearSold)}),e.jsx(c,{className:"text-right",children:Ve(d.averageAge)}),e.jsx(c,{className:"text-right",children:js(d.ptm)}),e.jsx(c,{className:"text-right",children:_t(d.averageListPrice)}),e.jsx(c,{className:"text-right",children:_t(d.averageDiscount)}),e.jsx(c,{className:"text-right",children:_t(d.averageFrontGross)}),e.jsx(c,{className:"text-right",children:_t(d.tradeOverUnder)}),e.jsx(c,{className:"text-right",children:_t(d.averageTotalGross)}),e.jsx(c,{className:"text-right",children:le(d.target45DayQuantity)}),e.jsx(c,{className:"text-right font-semibold",children:le(d.scores.total)}),e.jsx(c,{children:tr(d.confidence)}),e.jsx(c,{className:"text-xs",children:d.sourcingTier})]},`td-${d.make}-${d.model}-${d.trim}`))})]})})})})}),e.jsx(ut,{value:"risks",className:"mt-4",children:e.jsxs($e,{className:"bg-white/[0.03] border-white/10",children:[e.jsx(At,{className:"pb-2",children:e.jsx(Mt,{className:"text-base",children:"Price discipline and avoidance list"})}),e.jsx(Ae,{className:"p-0",children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(ke,{children:[e.jsx(Le,{children:e.jsxs(q,{children:[e.jsx(h,{children:"Make"}),e.jsx(h,{children:"Model"}),e.jsxs(h,{className:"text-right",children:[rt," sold"]}),e.jsx(h,{className:"text-right",children:"Avg. days"}),e.jsx(h,{className:"text-right",children:"Avg. front"}),e.jsx(h,{className:"text-right",children:"Avg. total"}),e.jsx(h,{className:"text-right",children:"PTM"}),e.jsx(h,{children:"Risk level"}),e.jsx(h,{children:"Acquisition action"}),e.jsx(h,{children:"Supporting reason"})]})}),e.jsx(Ce,{children:Ue.map(d=>e.jsxs(q,{children:[e.jsx(c,{children:d.make}),e.jsx(c,{children:d.model}),e.jsx(c,{className:"text-right",children:le(d.vehiclesSold)}),e.jsx(c,{className:"text-right",children:Ve(d.averageAge)}),e.jsx(c,{className:"text-right",children:_t(d.averageFrontGross)}),e.jsx(c,{className:"text-right",children:_t(d.averageTotalGross)}),e.jsx(c,{className:"text-right",children:js(d.ptm)}),e.jsx(c,{children:ui(d.riskLevel)}),e.jsx(c,{className:"max-w-[240px] whitespace-normal text-xs",children:d.acquisitionAction}),e.jsx(c,{className:"max-w-[260px] whitespace-normal text-xs text-muted-foreground",children:d.riskReason})]},`r-${d.make}-${d.model}`))})]})})})]})}),e.jsx(ut,{value:"source",className:"mt-4",children:e.jsxs($e,{className:"bg-white/[0.03] border-white/10",children:[e.jsxs(At,{className:"pb-2",children:[e.jsx(Mt,{className:"text-base",children:"Where the sold vehicles came from"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Sold performance by acquisition source for the vehicles currently selected. A blank source is shown as Unknown."})]}),e.jsx(Ae,{className:"p-0",children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(ke,{children:[e.jsx(Le,{children:e.jsxs(q,{children:[e.jsx(h,{children:"Source"}),e.jsx(h,{className:"text-right",children:"Units"}),e.jsx(h,{className:"text-right",children:"Share"}),e.jsx(h,{className:"text-right",children:"Avg. days"}),e.jsx(h,{className:"text-right",children:"Avg. front"}),e.jsx(h,{className:"text-right",children:"Avg. total"}),e.jsx(h,{className:"text-right",children:"Avg. sale price"})]})}),e.jsx(Ce,{children:it.map(d=>e.jsxs(q,{children:[e.jsx(c,{className:"whitespace-nowrap",children:d.source}),e.jsx(c,{className:"text-right",children:le(d.units)}),e.jsx(c,{className:"text-right",children:bt(d.unitShare)}),e.jsx(c,{className:"text-right",children:Ve(d.averageAge)}),e.jsx(c,{className:`text-right ${Tt(d.averageFrontGross)?"text-red-400":""}`,children:ze(d.averageFrontGross)}),e.jsx(c,{className:`text-right ${Tt(d.averageTotalGross)?"text-red-400":""}`,children:ze(d.averageTotalGross)}),e.jsx(c,{className:"text-right",children:ze(d.averageTransactionPrice)})]},d.source))})]})})})]})}),e.jsx(ut,{value:"bands",className:"mt-4",children:e.jsxs($e,{className:"bg-white/[0.03] border-white/10",children:[e.jsxs(At,{className:"pb-2",children:[e.jsx(Mt,{className:"text-base",children:"Vehicle age at sale"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Age is the sold year minus the model year, for the selected sold-date range."})]}),e.jsx(Ae,{className:"p-0",children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(ke,{children:[e.jsx(Le,{children:e.jsxs(q,{children:[e.jsx(h,{children:"Age band"}),e.jsx(h,{className:"text-right",children:"Units"}),e.jsx(h,{className:"text-right",children:"Share"}),e.jsx(h,{className:"text-right",children:"With a trade"}),e.jsx(h,{className:"text-right",children:"Avg. days"}),e.jsx(h,{className:"text-right",children:"Avg. front"}),e.jsx(h,{className:"text-right",children:"Avg. total"}),e.jsx(h,{children:"What to do"})]})}),e.jsx(Ce,{children:xt.map(d=>e.jsxs(q,{children:[e.jsx(c,{className:"whitespace-nowrap",children:d.label}),e.jsx(c,{className:"text-right",children:le(d.units)}),e.jsx(c,{className:"text-right",children:bt(re.length?d.units/re.length:null)}),e.jsx(c,{className:"text-right",children:bt(d.tradeRate)}),e.jsx(c,{className:"text-right",children:Ve(d.averageAge)}),e.jsx(c,{className:`text-right ${Tt(d.averageFrontGross)?"text-red-400":""}`,children:ze(d.averageFrontGross)}),e.jsx(c,{className:`text-right ${Tt(d.averageTotalGross)?"text-red-400":""}`,children:ze(d.averageTotalGross)}),e.jsx(c,{className:"text-xs text-muted-foreground",children:d.guidance})]},d.label))})]})})})]})}),e.jsx(ut,{value:"monthly",className:"mt-4",children:e.jsxs($e,{className:"bg-white/[0.03] border-white/10",children:[e.jsxs(At,{className:"pb-2",children:[e.jsx(Mt,{className:"text-base",children:"Month by month"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Units, trade share, days to sale and gross for each month of sold activity."})]}),e.jsx(Ae,{className:"p-0",children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(ke,{children:[e.jsx(Le,{children:e.jsxs(q,{children:[e.jsx(h,{children:"Month"}),e.jsx(h,{className:"text-right",children:"Units"}),e.jsx(h,{className:"text-right",children:"With a trade"}),e.jsx(h,{className:"text-right",children:"Avg. days"}),e.jsx(h,{className:"text-right",children:"Avg. front"}),e.jsx(h,{className:"text-right",children:"Avg. total"})]})}),e.jsx(Ce,{children:Kt.map(d=>e.jsxs(q,{children:[e.jsx(c,{className:"whitespace-nowrap",children:d.label}),e.jsx(c,{className:"text-right",children:le(d.units)}),e.jsxs(c,{className:"text-right",children:[le(d.tradeCount),d.units?` · ${bt(d.tradeCount/d.units)}`:""]}),e.jsx(c,{className:"text-right",children:Ve(d.averageAge)}),e.jsx(c,{className:`text-right ${Tt(d.averageFrontGross)?"text-red-400":""}`,children:ze(d.averageFrontGross)}),e.jsx(c,{className:`text-right ${Tt(d.averageTotalGross)?"text-red-400":""}`,children:ze(d.averageTotalGross)})]},d.month))})]})})})]})}),e.jsx(ut,{value:"pricing",className:"mt-4",children:e.jsxs($e,{className:"bg-white/[0.03] border-white/10",children:[e.jsxs(At,{className:"pb-2",children:[e.jsx(Mt,{className:"text-base",children:"List price vs. what it sold for"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Where discounting is eating the front gross, by model."})]}),e.jsx(Ae,{className:"p-0",children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(ke,{children:[e.jsx(Le,{children:e.jsxs(q,{children:[e.jsx(h,{children:"Make"}),e.jsx(h,{children:"Model"}),e.jsx(h,{className:"text-right",children:"Units"}),e.jsx(h,{className:"text-right",children:"Avg. list"}),e.jsx(h,{className:"text-right",children:"Avg. sold"}),e.jsx(h,{className:"text-right",children:"Avg. discount"}),e.jsx(h,{className:"text-right",children:"Discount of list"}),e.jsx(h,{className:"text-right",children:"Price to market"}),e.jsx(h,{className:"text-right",children:"Avg. front"}),e.jsx(h,{children:"Flag"})]})}),e.jsx(Ce,{children:We.filter(d=>(_.make===pe||d.make===_.make)&&(_.model===pe||d.model===_.model)).map(d=>e.jsxs(q,{children:[e.jsx(c,{className:"whitespace-nowrap",children:d.make}),e.jsx(c,{className:"whitespace-nowrap",children:d.model}),e.jsx(c,{className:"text-right",children:le(d.units)}),e.jsx(c,{className:"text-right",children:ze(d.averageListPrice)}),e.jsx(c,{className:"text-right",children:ze(d.averageTransactionPrice)}),e.jsx(c,{className:"text-right",children:ze(d.averageDiscount)}),e.jsx(c,{className:"text-right",children:bt(d.discountPctOfList)}),
351e.jsx(c,{className:"text-right",children:Ve(d.averagePriceToMarket)}),e.jsx(c,{className:`text-right ${Tt(d.averageFrontGross)?"text-red-400":""}`,children:ze(d.averageFrontGross)}),e.jsx(c,{className:"text-xs text-amber-200",children:d.flag??""})]},`${d.make}-${d.model}`))})]})})})]})}),e.jsx(ut,{value:"history",className:"mt-4",children:e.jsx($e,{className:"bg-white/[0.03] border-white/10",children:e.jsx(Ae,{className:"p-0",children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(ke,{children:[e.jsx(Le,{children:e.jsxs(q,{children:[e.jsx(h,{children:"Uploaded"}),e.jsx(h,{children:"File"}),e.jsx(h,{children:"Sold date range"}),e.jsx(h,{children:"By"}),e.jsx(h,{className:"text-right",children:"Rows"}),e.jsx(h,{className:"text-right",children:"Models"}),e.jsx(h,{className:"text-right",children:"Trims"}),e.jsx(h,{className:"text-right",children:"Units sold"}),e.jsx(h,{children:"Status"}),e.jsx(h,{className:"w-28"})]})}),e.jsx(Ce,{children:y.map(d=>e.jsxs(q,{children:[e.jsx(c,{children:new Date(d.uploaded_at).toLocaleString("en-US")}),e.jsx(c,{className:"max-w-[220px] truncate font-mono text-xs",children:d.filename}),e.jsx(c,{children:d.report_start_date&&d.report_end_date?vs(d.report_start_date,d.report_end_date,d.period_months):d.report_period_label??"—"}),e.jsx(c,{children:d.uploaded_by_name??"—"}),e.jsx(c,{className:"text-right",children:le(d.source_row_count)}),e.jsx(c,{className:"text-right",children:le(d.model_row_count)}),e.jsx(c,{className:"text-right",children:le(d.trim_row_count)}),e.jsx(c,{className:"text-right",children:le(d.total_units_sold)}),e.jsx(c,{children:d.is_active?e.jsx(Pe,{className:"bg-emerald-500/15 text-emerald-300",children:"Active"}):e.jsx(Pe,{variant:"outline",children:"Stored"})}),e.jsx(c,{children:!d.is_active&&j&&e.jsxs(ce,{size:"sm",variant:"outline",onClick:()=>at(d.id),children:[e.jsx(xn,{className:"mr-1.5 h-3.5 w-3.5"})," Activate"]})})]},d.id))})]})})})})}),e.jsx(ut,{value:"reports",className:"mt-4",children:e.jsx(di,{analysis:ae,dealershipName:ye,reportPeriod:St,filterSummary:Qt,sourceRows:it,importId:C,organizationId:g,dealershipId:f,userId:(s==null?void 0:s.id)??null})})]}),e.jsx(li,{open:F,onOpenChange:p,organizationId:g,dealershipId:f,dealershipLabel:ye,userId:(s==null?void 0:s.id)??null,userName:(s==null?void 0:s.full_name)??null,onSaved:async d=>{x(d),await U()}}),e.jsx(oi,{row:u,importId:C,userId:(s==null?void 0:s.id)??null,onClose:()=>w(null),onSaved:ie}),e.jsx(ni,{open:te!==null,onOpenChange:d=>!d&&Ee(null),title:te?hi[te]:"",valueLabel:Rt,records:Nt,priorRecords:zt,priorLabel:"Same window last year"})]})}function kr(t,s){const a=(t??"").trim();if(a)return a.toUpperCase();const r=(s??"").trim();return r?r.replace(/^[A-Z0-9]{4,8}\s*[-–]\s*/i,"").replace(/\s+/g," ").toUpperCase():"UNKNOWN"}const mr="W360_PROGRESS ",ee=t=>t==null?"—":new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(t),gs=t=>t==null?"—":t.toLocaleString(),sr=t=>{if(!t)return"—";const[s,a,r]=t.split("-");return`${a}/${r}/${s}`},fs=t=>[t.year,t.make,t.model,t.trim].filter(Boolean).join(" ")||"—",Ft=(t,s)=>t.sale_price===null||t.sale_price===void 0?null:(s??"").toUpperCase()==="MANHEIM"?t.floor_price===null||t.floor_price===void 0?null:Number(t.sale_price)-Number(t.floor_price):t.net_check_to_dealer!==null&&t.net_check_to_dealer!==void 0&&t.floor_price!==null&&t.floor_price!==void 0?Number(t.net_check_to_dealer)-Number(t.floor_price):null;function xi(t){if(!(t!=null&&t.startsWith(mr)))return null;try{return JSON.parse(t.slice(mr.length))}catch{return null}}function pi(t){return t!=null&&t.total?Math.max(1,Math.min(99,Math.round(t.current/t.total*100))):(t==null?void 0:t.phase)==="starting"?3:0}async function gi(t,s,a){a(10);let r=10;const n=window.setInterval(()=>{r=Math.min(90,r+5),a(r)},400);try{const{error:o}=await ne.storage.from("wholesale360-pdfs").upload(t,s,{upsert:!0,contentType:"application/pdf"});if(o){const i=(o==null?void 0:o.message)||(o==null?void 0:o.error)||JSON.stringify(o);throw new Error(i)}a(100)}finally{window.clearInterval(n)}}function lt({label:t,sortKey:s,sort:a,onSort:r,align:n="left"}){const o=a.key===s;return e.jsx(h,{className:n==="right"?"text-right":"",children:e.jsxs("button",{type:"button",onClick:()=>r(s),className:`inline-flex items-center gap-1 hover:text-foreground transition-colors ${o?"text-foreground":""}`,children:[t,o&&e.jsx("span",{className:"text-xs",children:a.dir==="asc"?"▲":"▼"})]})})}function Wi(){return e.jsx(yn,{children:e.jsx(fi,{})})}function fi(){const{currentUser:t}=Pr(),{selectedDealership:s}=Us(),{selectedIds:a,scopeLabel:r,loading:n}=br(),{toast:o}=ys(),{isMobile:i}=ia(),[m,g]=v.useState(!1),f=v.useRef(null),[j,y]=v.useState([]),[k,C]=v.useState([]),[x,A]=v.useState([]),[S,X]=v.useState(!0),[N,M]=v.useState(!1),[L,_]=v.useState(0),[H,F]=v.useState(new Set),[p,u]=v.useState(typeof window<"u"&&window.location.pathname.endsWith("/used-vehicle-acquisition")?"used-acquisition":"runs"),[w,T]=v.useState({key:"profit_loss",dir:"desc"}),[$,W]=v.useState(null),[B,_e]=v.useState(null),[ue,D]=v.useState(""),[P,U]=v.useState("__all__"),[ie,z]=v.useState(null),[G,I]=v.useState({key:"profit_loss",dir:"desc"}),[he,De]=v.useState(""),[Ne,st]=v.useState(!1),[de,ge]=v.useState(""),[Me,se]=v.useState(""),[we,Oe]=v.useState(""),[je,ae]=v.useState(""),[re,it]=v.useState(""),[te,Ee]=v.useState("15000"),[Nt,zt]=v.useState("1"),[xt,Kt]=v.useState(!1),[We,fe]=v.useState(!1);async function ye(l=!1){if(a.length===0)return;l||X(!0);const{data:b,error:O}=await ne.from("wholesale360_runs").select("*").in("dealership_id",a).order("sale_date",{ascending:!1,nullsFirst:!1}).order("created_at",{ascending:!1}).limit(200);O&&(console.error("[Wholesale360] loadData runs error:",O),o({title:"Couldn't load auction runs",description:O.message,variant:"destructive"})),y(b||[]);const{data:Q,error:Z}=await ne.from("wholesale360_lots").select("*").in("dealership_id",a).order("created_at",{ascending:!1}).limit(2e3);Z&&console.error("[Wholesale360] loadData lots error:",Z),C(Q||[]);const J=(b||[]).map(R=>R.id);if(J.length>0){const{data:R,error:Y}=await ne.from("w360_store_stats").select("*").in("run_id",J);Y&&console.error("[Wholesale360] loadData store stats error:",Y),A(R||[])}else A([]);l||X(!1)}v.useEffect(()=>{ye()},[a.join(",")]),v.useEffect(()=>{if(!j.some(O=>O.status==="processing"))return;const b=window.setInterval(()=>ye(!0),3e4);return()=>window.clearInterval(b)}
351,[j]);async function Xe(l){var O;if(!(t!=null&&t.id)){o({title:"Not signed in",variant:"destructive"});return}const b=l.name.toLowerCase();if(b.endsWith(".csv"))return rt(l);if(!b.endsWith(".pdf")){o({title:"Unsupported file",description:"Upload an ADESA PDF or a Manheim After Sale Report CSV.",variant:"destructive"});return}M(!0);try{const{data:Q}=await ne.auth.getUser(),Z=(O=Q==null?void 0:Q.user)==null?void 0:O.id;if(!Z)throw new Error("Not signed in.");let J=(s==null?void 0:s.organization_id)??null;if(!J){const{data:gt}=await ne.from("registration_users").select("organization_id").eq("auth_uid",Z).maybeSingle();J=(gt==null?void 0:gt.organization_id)||null}if(!J)throw new Error("No organization context for your account — contact an administrator.");const R=await Nn(l),{data:Y}=await ne.from("wholesale360_runs").select("id, file_name, created_at, total_lots, status").eq("organization_id",J).eq("content_sha256",R).maybeSingle();if(Y){M(!1),_(0),o({title:"This exact file was already imported",description:`Uploaded ${new Date(Y.created_at).toLocaleDateString()} as "${Y.file_name}" (${Y.total_lots??0} lots). Nothing was duplicated — use Reprocess on that run if you need to re-parse it.`});return}const Ie={organization_id:J,dealership_id:(s==null?void 0:s.id)??null,uploaded_by:t.id,source:"ADESA",file_name:l.name,content_sha256:R,status:"processing"},{data:Se,error:Re}=await ne.from("wholesale360_runs").insert(Ie).select().single();if(Re||!Se)throw Re||new Error("Failed to create run");const He=`${J}/${Se.id}/${l.name}`;_(1),await gi(He,l,_),await ne.from("wholesale360_runs").update({storage_path:He}).eq("id",Se.id);const{error:Ge}=await ne.functions.invoke("parse-wholesale360-pdf",{body:{run_id:Se.id,storage_path:He,reset:!0}});Ge&&(console.error("parser invoke error:",Ge),o({title:"Parser unavailable",description:Ge.message||"Could not start the PDF parser.",variant:"destructive"})),ne.functions.invoke("send-wholesale360-notification",{body:{event:"file_uploaded",run_id:Se.id}}).catch(gt=>console.warn("file_uploaded notification failed:",gt)),o({title:"Upload received",description:`Parsing ${l.name} in the background — large PDFs can take a couple of minutes.`}),await ye(),St(Se.id)}catch(Q){console.error(Q),o({title:"Upload failed",description:(Q==null?void 0:Q.message)||String(Q),variant:"destructive"})}finally{M(!1),window.setTimeout(()=>_(0),1200),f.current&&(f.current.value="")}}async function rt(l){var b;M(!0),_(5);try{const{data:O}=await ne.auth.getUser(),Q=(b=O==null?void 0:O.user)==null?void 0:b.id;if(!Q)throw new Error("Not signed in.");let Z=(s==null?void 0:s.organization_id)??null;if(!Z){const{data:E}=await ne.from("registration_users").select("organization_id").eq("auth_uid",Q).maybeSingle();Z=(E==null?void 0:E.organization_id)||null}if(!Z)throw new Error("No organization context for your account — contact an administrator.");_(20);const J=await l.text(),{saleDate:R,lots:Y}=Dn(J);if(Y.length===0)throw new Error("No lots found in CSV.");_(40);const[Ie,Se]=await Promise.all([ne.from("wholesale360_dealer_aliases").select("id, dealer_code, dealer_name, dealership_id").eq("organization_id",Z),ne.from("dealerships").select("id, name").eq("organization_id",Z)]),Re=new Map,He=new Map;for(const E of Ie.data??[])E.dealer_code&&Re.set(String(E.dealer_code).toUpperCase(),E.dealership_id),E.dealer_name&&He.set(String(E.dealer_name).toUpperCase(),E.dealership_id);const Ge=Se.data??[],gt=E=>E.toUpperCase().replace(/[^A-Z0-9 ]+/g," ").split(/\s+/).filter(Boolean),hs=E=>{if(!E)return null;const Ye=new Set(gt(E));if(Ye.size===0)return null;for(const dt of Ge){const kt=gt(dt.name||"");if(kt.length===0)continue;if(kt.filter(ss=>Ye.has(ss)).length/kt.length>=.85)return dt.id}return null},{data:jt,error:Ls}=await ne.from("wholesale360_runs").insert({organization_id:Z,dealership_id:(s==null?void 0:s.id)??null,uploaded_by:t.id,source:"Manheim",file_name:l.name,status:"ready",sale_date:R,total_lots:Y.length}).select().single();if(Ls||!jt)throw Ls||new Error("Failed to create run");_(60);const Cs=new Map;let us=0,ms=0,ve=0;const nt=Y.map(E=>
351{const Ye=(E.dealer_code||"").toUpperCase(),dt=(E.dealer_name||"").toUpperCase();let kt=null;Ye&&Re.has(Ye)?kt=Re.get(Ye)??null:dt&&He.has(dt)?kt=He.get(dt)??null:E.dealer_name&&(kt=hs(E.dealer_name));const ls=`${Ye}|${dt}`;Cs.has(ls)||Cs.set(ls,{dealer_code:E.dealer_code,dealer_name:E.dealer_name,dealership_id:kt}),E.sold?us+=1:ms+=1,E.profit_loss!=null&&(ve+=E.profit_loss);const ss=kt==null,Ir=E.needs_review||ss,Ia=Ir?ss&&E.review_reason?`${E.review_reason},unmapped_seller`:ss?"unmapped_seller":E.review_reason:null;return{run_id:jt.id,organization_id:Z,dealership_id:kt,lot_number:E.lot_number,dealer_code:E.dealer_code,dealer_name:E.dealer_name,stock_number:E.stock_number,vin:E.vin,year:E.year,make:E.make,model:E.model,trim:E.trim,body_style:E.body_style,color:E.color,miles:E.miles,title_state:E.title_state,lights:E.lights,floor_price:E.floor_price,sale_price:E.sale_price,highest_bid_amount:E.highest_bid_amount,local_cv:E.local_cv,natl_cv:E.natl_cv,guidebook:E.guidebook,loan_amount:E.loan_amount,profit_loss:E.profit_loss,days_in_inventory:E.days_in_inventory,sales_veh_run_by_seller:E.sales_veh_run_by_seller,sold:E.sold,no_sale:E.no_sale,as_is:E.as_is,structural_damage:E.structural_damage,over_100k:E.over_100k,over_200k:E.over_200k,caution:E.caution,condition_codes:E.condition_codes,cr_comments:E.cr_comments,needs_review:Ir,review_reason:Ia,raw_data:E.raw_data}}),ft=200;try{for(let E=0;E<nt.length;E+=ft){const Ye=nt.slice(E,E+ft),{error:dt}=await ne.from("wholesale360_lots").insert(Ye);if(dt)throw dt;_(60+Math.round((E+Ye.length)/nt.length*30))}}catch(E){await ne.from("wholesale360_runs").delete().eq("id",jt.id);const Ye=(E==null?void 0:E.message)||String(E);throw console.error("Manheim lot insert failed:",E),new Error(`Lot insert failed: ${Ye}`)}for(const E of Cs.values()){const Ye=ne.from("wholesale360_dealer_aliases").select("id").eq("organization_id",Z);if(E.dealer_code)Ye.eq("dealer_code",E.dealer_code);else if(E.dealer_name)Ye.is("dealer_code",null).eq("dealer_name",E.dealer_name);else continue;const{data:dt}=await Ye.limit(1);(!dt||dt.length===0)&&await ne.from("wholesale360_dealer_aliases").insert({organization_id:Z,dealer_code:E.dealer_code,dealer_name:E.dealer_name,dealership_id:E.dealership_id,source:"Manheim"})}await ne.from("wholesale360_runs").update({total_lots:Y.length,sold_lots:us,no_sale_lots:ms,total_profit_loss:ve,needs_review:nt.some(E=>E.needs_review)}).eq("id",jt.id),_(100);const qt=Array.from(Cs.values()).filter(E=>!E.dealership_id).length;o({title:"Manheim CSV imported",description:`${Y.length} lots — ${us} sold / ${ms} no-sale`+(qt>0?` • ${qt} seller${qt===1?"":"s"} need mapping (Seller Aliases tab)`:"")}),await ye(),u("runs")}catch(O){console.error(O),o({title:"Upload failed",description:(O==null?void 0:O.message)||String(O),variant:"destructive"})}finally{M(!1),window.setTimeout(()=>_(0),1200),f.current&&(f.current.value="")}}async function St(l){if(H.has(l))return;F(Q=>new Set(Q).add(l));const b=Date.now(),O=15*60*1e3;try{for(;Date.now()-b<O;){await new Promise(Z=>setTimeout(Z,4e3));const{data:Q}=await ne.from("wholesale360_runs").select("status, total_lots, sold_lots, no_sale_lots, error_message, updated_at").eq("id",l).maybeSingle();if(Q){if(await ye(!0),Q.status==="ready"){o({title:"Auction parsed",description:`${Q.total_lots} lots — ${Q.sold_lots} sold / ${Q.no_sale_lots} no-sale${Q.error_message&&!Q.error_message.startsWith(mr)?` (${Q.error_message})`:""}`});return}if(Q.status==="failed"){o({title:"Parse failed",description:Q.error_message||"Unknown error",variant:"destructive"});return}}}}finally{F(Q=>{const Z=new Set(Q);return Z.delete(l),Z})}}async function Qt(l){if(!confirm(`Delete auction run "${l.file_name}" and all its lots?`))return;const{error:b}=await ne.from("wholesale360_runs").delete().eq("id",l.id);if(b){o({title:"Delete failed",description:b.message,variant:"destructive"});return}o({title:"Run deleted"}),await ye()}async function Dt(l){if(!l.storage_path){o({title:"Cannot reprocess",description:"Original file path is missing — please re-upload.",variant:"destructive"});return}await ne.from("wholesale360_runs").update({status:"processing",error_message:`${mr}${JSON.stringify({phase:"starting",current:0,total:0,failed:0,lots:0})}`,total_lots:0,sold_lots:0,no_sale_lots:0,total_profit_loss:0}).eq("id",l.id),ne.functions.invoke("parse-wholesale360-pdf",{body:{run_id:l.id,storage_path:l.storage_path,reset:!0}}).catch(b=>console.warn("parser invoke warning:",b)),o({title:"Reprocessing started",description:`Re-parsing ${l.file_name} in the background.`}),await ye(),St(l.id)}function pt(l){if(l.status!=="processing")return!1;const b=new Date(l.updated_at||l.created_at).getTime();return Date.now()-b>3*60*1e3}const ot=v.useMemo(()=>{const l=new Map;for(const b of j)l.set(b.id,b);return l},[j]),at=v.useMemo(()=>{let l=$?k.filter(O=>O.run_id===$.id):k;if(P!=="__all__"&&(l=l.filter(O=>(O.appraiser??"—")===P)),!ue.trim())return l;const b=ue.trim().toLowerCase();return l.filter(O=>{var Q,Z,J,R,Y;return((Q=O.vin)==null?void 0:Q.toLowerCase().includes(b))||((Z=O.stock_number)==null?void 0:Z.toLowerCase().includes(b))||((J=O.dealer_code)==null?void 0:J.toLowerCase().includes(b))||((R=O.dealer_name)==null?void 0:R.toLowerCase().includes(b))||((Y=O.appraiser)==null?void 0:Y.toLowerCase().includes(b))||fs(O).toLowerCase().includes(b)})},[k,ue,$,P]),oe=v.useMemo(()=>{var O;const l=$?k.filter(Q=>Q.run_id===$.id):k,b=new Map;for(const Q of l){const Z=((O=Q.appraiser)==null?void 0:O.trim())||"—";b.set(Z,(b.get(Z)??0)+1)}return Array.from(b.entries()).sort((Q,Z)=>Q[0].localeCompare(Z[0])).map(([Q,Z])=>({name:Q,count:Z}))},[k,$]);v.useMemo(()=>{const l=at.filter(Z=>Z.sale_price!==null).length,b=at.length-l,O=at.reduce((Z,J)=>Z+(J.sale_price!==null&&J.floor_price!==null?J.sale_price-J.floor_price:0),0),Q=l>0?O/l:0;return{sold:l,noSale:b,totalPL:O,avgPL:Q}},[at]);const Rt=v.useMemo(()=>{const l=at.length,b=at.filter(R=>R.sale_price!==null).length,O=at.reduce((R,Y)=>
351R+(Y.floor_price??0),0),Q=at.reduce((R,Y)=>R+(Y.sale_price??0),0),Z=at.reduce((R,Y)=>R+(Y.sale_price!==null&&Y.floor_price!==null?Y.sale_price-Y.floor_price:0),0),J=b>0?Z/b:0;return{appraisals:l,sold:b,totalFloor:O,totalSale:Q,netPL:Z,avgPL:J}},[at]),as=v.useMemo(()=>{var J,R,Y,Ie,Se;const l=new Map;for(const Re of at){const He=kr(Re.dealer_code,Re.dealer_name);let Ge=l.get(He);Ge||(Ge={key:He,dealer_code:((J=Re.dealer_code)==null?void 0:J.trim())||"—",dealer_name:((R=Re.dealer_name)==null?void 0:R.trim())||"",lots:[],lots_count:0,sold:0,no_sale:0,total_sale:0,total_net:0,profit_loss:0},l.set(He,Ge));const gt=((Y=Re.dealer_name)==null?void 0:Y.trim())??"";gt.length>Ge.dealer_name.length&&(Ge.dealer_name=gt),(Ge.dealer_code==="—"||!Ge.dealer_code)&&((Ie=Re.dealer_code)!=null&&Ie.trim())&&(Ge.dealer_code=Re.dealer_code.trim()),Ge.lots.push(Re),Ge.lots_count+=1,Re.sale_price!=null?(Ge.sold+=1,Ge.total_sale+=Number(Re.sale_price)||0):Ge.no_sale+=1,Ge.total_net+=Number(Re.net_check_to_dealer)||0,Ge.profit_loss+=Ft(Re,(Se=ot.get(Re.run_id??""))==null?void 0:Se.source)??0}const b=Array.from(l.values()),{key:O,dir:Q}=G,Z=Q==="asc"?1:-1;return b.sort((Re,He)=>{const Ge=jt=>O==="sell_rate"?jt.lots_count?jt.sold/jt.lots_count:0:jt[O],gt=Ge(Re),hs=Ge(He);return typeof gt=="string"?gt.localeCompare(hs)*Z:((gt??0)-(hs??0))*Z}),b},[at,G]),Ue=v.useMemo(()=>ie?as.find(l=>l.key===ie)??null:null,[ie,as]),Vt=v.useMemo(()=>{const l=new Map;for(const b of x){if($&&b.run_id!==$.id||b.scope!=="STORE")continue;const O=kr(b.store_code,b.store_name);if(!O||O==="UNKNOWN")continue;(!l.get(O)||b.stat_source==="ADESA_PRINTED")&&l.set(O,b)}return l},[x,$]);function d(l){const b=Vt.get(l.key);if(!b)return null;const O=b.listed!=null?b.listed-l.lots_count:0,Q=b.sold!=null?b.sold-l.sold:0;return{reportListed:b.listed,reportSold:b.sold,listedGap:O,soldGap:Q,incomplete:O>0||Q>0}}async function V(l){const b=(l.page_gaps??[]).map(O=>Number(O.page)).filter(O=>Number.isFinite(O)&&O>=1);if(!l.storage_path||b.length===0){o({title:"Nothing to re-read",description:"No incomplete pages were recorded for this file."});return}ne.functions.invoke("parse-wholesale360-pdf",{body:{run_id:l.id,storage_path:l.storage_path,reset:!1,pages:b}}).catch(O=>console.warn("re-read invoke warning:",O)),o({title:"Re-reading pages",description:`Reading ${b.length} incomplete page(s) again in the background.`}),St(l.id)}function K(l){I(b=>b.key===l?{key:l,dir:b.dir==="asc"?"desc":"asc"}:{key:l,dir:"desc"})}const Fe=v.useMemo(()=>{var Z;const l=new Map;for(const J of at){const R=(J.dealer_code??"").trim(),Y=(J.dealer_name??"").trim(),Ie=kr(R,Y);let Se=l.get(Ie);if(Se||(Se={key:Ie,dealer_code:R||"—",dealer_name:Y||"Unknown",lots_run:0,sold:0,no_sale:0,sell_through:0,total_sale_price:0,total_net:0,total_fees:0,profit_loss:0,avg_pl:0},l.set(Ie,Se)),(Y.length>Se.dealer_name.length||Se.dealer_name==="Unknown")&&(Se.dealer_name=Y||Se.dealer_name),(Se.dealer_code==="—"||!Se.dealer_code)&&R&&(Se.dealer_code=R),Se.lots_run+=1,J.sold||J.sale_price!==null){Se.sold+=1,Se.total_sale_price+=J.sale_price??0,Se.total_net+=J.net_check_to_dealer??0,Se.total_fees+=J.auction_fee??0;const He=Ft(J,(Z=ot.get(J.run_id??""))==null?void 0:Z.source)??0;Se.profit_loss+=He}else Se.no_sale+=1}const b=Array.from(l.values()).map(J=>({...J,sell_through:J.lots_run>0?J.sold/J.lots_run*100:0,avg_pl:J.sold>0?J.profit_loss/J.sold:0})),{key:O,dir:Q}=w;return b.sort((J,R)=>{const Y=J[O],Ie=R[O];return typeof Y=="string"?Q==="asc"?Y.localeCompare(Ie):Ie.localeCompare(Y):Q==="asc"?Y-Ie:Ie-Y}),b},[at,w]),be=v.useMemo(()=>Fe.reduce((l,b)=>(l.lots_run+=b.lots_run,l.sold+=b.sold,l.no_sale+=b.no_sale,l.total_sale_price+=b.total_sale_price,l.total_net+=b.total_net,l.total_fees+=b.total_fees,l.profit_loss+=b.profit_loss,l),{lots_run:0,sold:0,no_sale:0,total_sale_price:0,total_net:0,total_fees:0,profit_loss:0}),[Fe]);function ct(l){T(b=>b.key===l?{key:l,dir:b.dir==="asc"?"desc":"asc"}:{key:l,dir:"desc"})}function ds(){const l=["Dealer Code","Dealer Name","Lots Run","Sold","No Sale","Sell-through %","Total Sale Price","Total Net to Dealer","Total Auction Fees","Profit/Loss","Avg P/L per Vehicle"],b=R=>{const Y=String(R??"");return/[",\n]/.test(Y)?`"${Y.replace(/"/g,'""')}"`:Y},O=[l.join(",")];for(const R of Fe)O.push([R.dealer_code,R.dealer_name,R.lots_run,R.sold,R.no_sale,R.sell_through.toFixed(1),R.total_sale_price.toFixed(2),R.total_net.toFixed(2),R.total_fees.toFixed(2),R.profit_loss.toFixed(2),R.avg_pl.toFixed(2)].map(b).join(","));const Q=new Blob([O.join(`
352`)],{type:"text/csv;charset=utf-8"}),Z=URL.createObjectURL(Q),J=document.createElement("a");J.href=Z,J.download=`wholesale360-dealer-summary-${new Date().toISOString().slice(0,10)}.csv`,J.click(),URL.revokeObjectURL(Z)}async function ns(){const l=he.trim().toUpperCase();if(l.length!==17){o({title:"Invalid VIN",description:"VIN must be 17 characters.",variant:"destructive"});return}st(!0);try{const{data:b,error:O}=await ne.functions.invoke("decode-vin",{body:{vin:l}});if(O)throw O;ge(b!=null&&b.year?String(b.year):""),se((b==null?void 0:b.make)||""),Oe((b==null?void 0:b.model)||""),ae((b==null?void 0:b.trim)||""),o({title:"VIN decoded",description:`${(b==null?void 0:b.year)??""} ${(b==null?void 0:b.make)??""} ${(b==null?void 0:b.model)??""}`.trim()})}catch(b){o({title:"Decode failed",description:(b==null?void 0:b.message)??"Could not decode VIN",variant:"destructive"})}finally{st(!1)}}const ts=v.useMemo(()=>{var us,ms;const l={rows:[],diag:{makeModel:0,afterYear:0,afterMiles:0,afterTrim:0,afterWindow:0}};if(!We)return l;const b=ve=>(ve??"").toLowerCase().replace(/[^a-z0-9]+/g," ").trim(),O=b(Me),Q=b(we),Z=b(je),J=parseInt(de,10),R=parseInt(re.replace(/[^\d]/g,""),10),Y=Math.max(0,parseInt(Nt,10)||0),Ie=Math.max(0,parseInt(te.replace(/[^\d]/g,""),10)||0);if(!O||!Q||!Number.isFinite(J)||!Number.isFinite(R))return l;const Se=Date.now()-60*24*60*60*1e3,Re=ve=>{if(!ve)return null;const[nt,ft,qt]=ve.split("-").map(E=>parseInt(E,10));return!nt||!ft||!qt?null:new Date(nt,ft-1,qt).getTime()},He={makeModel:0,afterYear:0,afterMiles:0,afterTrim:0,afterWindow:0}
352,Ge=Q.split(" ").filter(Boolean),gt=k.filter(ve=>{const nt=b(ve.make),ft=b(ve.model),qt=b(ve.trim);if(!nt||!ft||nt!==O||!(ft===Q||Ge.every(ss=>ft.includes(ss)))||(He.makeModel++,ve.year==null||ve.year<J-Y||ve.year>J+Y)||(He.afterYear++,ve.miles==null||ve.miles<R-Ie||ve.miles>R+Ie)||(He.afterMiles++,xt&&Z&&!`${qt} ${ft}`.includes(Z)))return!1;He.afterTrim++;const Ye=ve.run_id?ot.get(ve.run_id):void 0,dt=Re(Ye==null?void 0:Ye.sale_date),kt=ve.created_at?new Date(ve.created_at).getTime():null,ls=dt??kt;return ls==null||ls<Se?!1:(He.afterWindow++,!0)}),hs=ve=>(ve??"").toUpperCase().replace(/[^A-Z0-9]/g,""),jt=new Map,Ls=[];for(const ve of gt){const nt=hs(ve.vin);if(!nt){Ls.push(ve);continue}const ft=jt.get(nt);if(!ft){jt.set(nt,ve);continue}const qt=ft.sale_price!=null,E=ve.sale_price!=null;if(E!==qt){E&&jt.set(nt,ve);continue}const Ye=Re((us=ot.get(ft.run_id??""))==null?void 0:us.sale_date)??(ft.created_at?new Date(ft.created_at).getTime():0),dt=Re((ms=ot.get(ve.run_id??""))==null?void 0:ms.sale_date)??(ve.created_at?new Date(ve.created_at).getTime():0);if(dt!==Ye){dt>Ye&&jt.set(nt,ve);continue}const kt=Math.abs((ft.miles??0)-R);Math.abs((ve.miles??0)-R)<kt&&jt.set(nt,ve)}return{rows:[...jt.values(),...Ls].sort((ve,nt)=>Math.abs((ve.miles??0)-R)-Math.abs((nt.miles??0)-R)),diag:He}},[We,Me,we,je,de,re,Nt,te,xt,k,ot]),$t=ts.rows,ks=ts.diag,Et=v.useMemo(()=>{const l=$t.filter(R=>R.sale_price!=null),b=l.map(R=>Number(R.sale_price)).filter(R=>Number.isFinite(R)),O=l.map(R=>Number(R.net_check_to_dealer)).filter(R=>Number.isFinite(R)),Q=l.map(R=>Ft(R)).filter(R=>R!==null&&Number.isFinite(R)),Z=R=>R.length?R.reduce((Y,Ie)=>Y+Ie,0)/R.length:0,J=R=>{if(!R.length)return 0;const Y=[...R].sort((Se,Re)=>Se-Re),Ie=Math.floor(Y.length/2);return Y.length%2?Y[Ie]:(Y[Ie-1]+Y[Ie])/2};return{total:$t.length,sold:l.length,noSale:$t.length-l.length,avgPrice:Z(b),medianPrice:J(b),lowPrice:b.length?Math.min(...b):0,highPrice:b.length?Math.max(...b):0,avgNet:Z(O),avgPL:Z(Q)}},[$t]);function Ea(){if(!Me||!we||!de||!re){o({title:"Missing info",description:"Year, Make, Model, and Miles are required.",variant:"destructive"});return}fe(!0)}function Fa(){const l=["Sale Date","Year","Make","Model","Trim","Miles","Sale Price","Net to Dealer","P/L","Status","Lot #","Dealer","VIN"],b=R=>{const Y=String(R??"");return/[",\n]/.test(Y)?`"${Y.replace(/"/g,'""')}"`:Y},O=[l.join(",")];for(const R of $t){const Y=R.run_id?ot.get(R.run_id):void 0;O.push([(Y==null?void 0:Y.sale_date)??"",R.year??"",R.make??"",R.model??"",R.trim??"",R.miles??"",R.sale_price??"",R.net_check_to_dealer??"",Ft(R,Y==null?void 0:Y.source)??"",R.sale_price==null?"NO SALE":"SOLD",R.lot_number??"",R.dealer_name??R.dealer_code??"",R.vin??""].map(b).join(","))}const Q=new Blob([O.join(`
353`)],{type:"text/csv;charset=utf-8"}),Z=URL.createObjectURL(Q),J=document.createElement("a");J.href=Z,J.download=`wholesale360-vin-comps-${new Date().toISOString().slice(0,10)}.csv`,J.click(),URL.revokeObjectURL(Z)}return e.jsxs("div",{className:"min-h-screen p-4 md:p-8 space-y-6",children:[e.jsxs("header",{className:"flex flex-wrap items-center gap-4",children:[e.jsx(Za,{appName:"Wholesale 360",sizeClassName:"h-10 w-10",size:"md"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h1",{className:"text-2xl md:text-3xl font-semibold text-foreground",children:"intel360"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Vehicle sales intelligence — retail + wholesale VIN history — ",r]})]}),e.jsx(Sn,{}),e.jsx(Zt,{componentId:"wholesale360:button-upload-pdf",appName:"Wholesale 360",componentType:"button",componentLabel:"Upload Auction File",children:e.jsxs(ce,{onClick:()=>{var l;return(l=f.current)==null?void 0:l.click()},disabled:N,className:"bg-gradient-to-r from-[#2F80ED] to-[#1C5ED6] text-white",children:[e.jsx(Er,{className:"mr-2 h-4 w-4"}),N?"Processing…":"Upload Auction File"]})}),e.jsx(on,{slug:cn.wholesale360LotRunSummary,label:"Lot Run Summary"}),e.jsx("input",{ref:f,type:"file",accept:"application/pdf,.pdf,text/csv,.csv",className:"hidden",onChange:l=>{var b;return((b=l.target.files)==null?void 0:b[0])&&Xe(l.target.files[0])}})]}),e.jsx("p",{className:"text-xs text-muted-foreground -mt-2",children:'Supports ADESA "Detailed Block Summary" PDFs and Manheim "After Sale Report" CSVs.'}),N&&L>0&&e.jsxs("div",{className:"rounded-2xl border border-white/10 bg-white/[0.03] p-4",children:[e.jsxs("div",{className:"mb-2 flex items-center justify-between text-sm",children:[e.jsxs("span",{className:"flex items-center gap-2 text-foreground",children:[e.jsx(es,{className:"h-4 w-4 animate-spin text-primary"}),"Uploading auction PDF"]}),e.jsxs("span",{className:"font-mono text-muted-foreground",children:[L,"%"]})]}),e.jsx(aa,{value:L,className:"h-2"})]}),e.jsxs(na,{value:p,onValueChange:l=>u(l),children:[e.jsx("div",{className:"overflow-x-auto -mx-1 px-1 pb-0.5",children:e.jsxs(la,{className:"flex w-max min-w-full",children:[e.jsx(ht,{value:"runs",children:"Auction Runs"}),e.jsx(ht,{value:"lots",children:"Lots"}),e.jsx(ht,{value:"dealers",children:"Dealer Summary"}),e.jsx(ht,{value:"vin-comp",children:"VIN Comp Check"}),e.jsx(ht,{value:"aliases",children:"Seller Aliases"}),e.jsx(ht,{value:"used-acquisition",children:"Used Vehicle Acquisition"}),e.jsx(ht,{value:"reports",children:"Reports"})]})}),e.jsx(ut,{value:"used-acquisition",className:"mt-4",children:e.jsx(mi,{})}),e.jsx(ut,{value:"runs",className:"mt-4",children:e.jsx($e,{className:"bg-white/[0.03] border-white/10",children:e.jsx(Ae,{className:"p-0",children:S?e.jsx("div",{className:"p-8 text-center text-muted-foreground",children:"Loading…"}):j.length===0?e.jsx("div",{className:"p-8 text-center text-muted-foreground",children:"No auction runs yet. Upload your first PDF to get started."}
353):i?e.jsx("div",{className:"divide-y divide-white/10",children:j.map(l=>{const b=l.sold_lots>0?(l.total_profit_loss??0)/l.sold_lots:0;return e.jsxs("button",{type:"button",className:"w-full text-left p-4 hover:bg-white/[0.04] active:bg-white/[0.06] min-h-[44px] space-y-2",onClick:()=>{W(l),u("lots")},children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"text-sm font-medium text-foreground",children:[sr(l.sale_date)," · ",l.source]}),e.jsx("div",{className:"text-xs text-muted-foreground font-mono truncate max-w-[220px]",children:l.file_name})]}),e.jsx(sa,{status:l.status,message:l.error_message,stale:pt(l)})]}),e.jsxs("div",{className:"min-w-0 grid grid-cols-2 sm:grid-cols-3 gap-2 text-xs",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Lots "}),e.jsx("span",{className:"text-foreground font-medium",children:l.total_lots})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Sold "}),e.jsx("span",{className:"text-emerald-300 font-medium",children:l.sold_lots})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"No Sale "}),e.jsx("span",{className:"text-amber-300 font-medium",children:l.no_sale_lots})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"P/L "}),e.jsx("span",{className:`font-medium ${(l.total_profit_loss??0)>=0?"text-emerald-300":"text-red-300"}`,children:ee(l.total_profit_loss)})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Avg "}),e.jsx("span",{className:`font-medium ${b>=0?"text-emerald-300":"text-red-300"}`,children:l.sold_lots>0?ee(b):"—"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",onClick:O=>O.stopPropagation(),children:[(l.status==="failed"||pt(l))&&l.storage_path&&e.jsx(ce,{size:"sm",variant:"ghost",onClick:()=>Dt(l),className:"text-sky-300 h-9 min-w-[44px]",children:e.jsx(Ks,{className:"h-4 w-4"})}),e.jsx(ce,{size:"sm",variant:"ghost",onClick:()=>Qt(l),className:"text-red-400 h-9 min-w-[44px]",children:e.jsx(Or,{className:"h-4 w-4"})})]})]},l.id)})}):e.jsxs(ke,{children:[e.jsx(Le,{children:e.jsxs(q,{children:[e.jsx(h,{children:"Sale Date"}),e.jsx(h,{children:"Source"}),e.jsx(h,{children:"File"}),e.jsx(h,{className:"text-right",children:"Lots"}),e.jsx(h,{className:"text-right",children:"Sold"}),e.jsx(h,{className:"text-right",children:"Sell %"}),e.jsx(h,{className:"text-right",children:"No Sale"}),e.jsx(h,{className:"text-right",children:"Total P/L"}),e.jsx(h,{className:"text-right",children:"Avg P/L / Vehicle"}),e.jsx(h,{children:"Status"}),e.jsx(h,{className:"w-20"})]})}),e.jsx(Ce,{children:j.map(l=>e.jsxs(q,{className:"cursor-pointer hover:bg-white/[0.04]",onClick:()=>{W(l),u("lots")},children:[e.jsx(c,{children:sr(l.sale_date)}),e.jsx(c,{children:l.source}),e.jsx(c,{className:"font-mono text-xs",children:l.file_name}),e.jsx(c,{className:"text-right",children:l.total_lots}),e.jsx(c,{className:"text-right text-emerald-300",children:l.sold_lots}),e.jsx(c,{className:"text-right text-sky-300",children:l.total_lots?`${(l.sold_lots/l.total_lots*100).toFixed(1)}%`:"—"}),e.jsx(c,{className:"text-right text-amber-300",children:l.no_sale_lots}),e.jsx(c,{className:`text-right font-medium ${(l.total_profit_loss??0)>=0?"text-emerald-300":"text-red-300"}`,children:ee(l.total_profit_loss)}),(()=>{const b=l.sold_lots>0?(l.total_profit_loss??0)/l.sold_lots:0;return e.jsx(c,{className:`text-right font-medium ${b>=0?"text-emerald-300":"text-red-300"}`,children:l.sold_lots>0?ee(b):"—"})})(),e.jsx(c,{children:e.jsx(sa,{status:l.status,message:l.error_message,stale:pt(l)})}),e.jsx(c,{onClick:b=>b.stopPropagation(),children:e.jsxs("div",{className:"flex items-center gap-1",children:[(l.status==="failed"||pt(l))&&l.storage_path&&e.jsx(ce,{size:"sm",variant:"ghost",onClick:()=>Dt(l),className:"text-sky-300 hover:text-sky-200",title:"Reprocess this PDF",children:e.jsx(Ks,{className:"h-4 w-4"})}),e.jsx(ce,{size:"sm",variant:"ghost",onClick:()=>Qt(l),className:"text-red-400 hover:text-red-300",children:e.jsx(Or,{className:"h-4 w-4"})})]})})]},l.id))})]})})})}),e.jsxs(ut,{value:"lots",className:"mt-4 space-y-4",children:[$&&(()=>{var Y;const l=$.report_listed,b=$.report_sold,O=$.total_lots,Q=$.sold_lots,Z=l!=null?l-O:0,J=b!=null?b-Q:0,R=k.filter(Ie=>Ie.run_id===$.id&&Ie.needs_review).length;return Z<=0&&J<=0&&R===0?null:e.jsx("div",{className:"rounded-lg border border-amber-500/40 bg-amber-500/10 px-4 py-3 text-sm text-amber-100",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(lr,{className:"h-4 w-4 mt-0.5 shrink-0"}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"font-medium",children:"Possible extraction discrepancy"}),Z>0&&e.jsxs("div",{children:["Extracted ",e.jsx("b",{children:O})," of ",e.jsx("b",{children:l})," lots per ADESA report — ",Z," missing."]}),J>0&&e.jsxs("div",{children:["ADESA reports ",e.jsx("b",{children:b})," vehicles sold; app shows ",e.jsx("b",{children:Q})," — ",J," sale(s) missing."]}),R>0&&e.jsxs("div",{children:[e.jsx("b",{children:R})," lot",R===1?"":"s"," flagged for review (possible missed sale price)."]}),(((Y=$.page_gaps)==null?void 0:Y.length)??0)>0&&e.jsx("div",{className:"pt-1",children:e.jsxs(ce,{size:"sm",variant:"outline",onClick:()=>V($),className:"h-8",children:[e.jsx(Ks,{className:"h-3.5 w-3.5 mr-2"}),"Re-read ",$.page_gaps.length," incomplete page",$.page_gaps.length===1?"":"s"]})}),e.jsx("div",{className:"text-xs text-amber-200/80 pt-1",children:"Re-upload the PDF to re-parse if numbers still don't match."})]})]})})})(),i?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx($s,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ct,{placeholder:"Search lots…",value:ue,onChange:l=>D(l.target.value),className:"pl-9 h-11 text-base"})]}),e.jsxs(Cr,{open:m,onOpenChange:g,children:[e.jsxs(ce,{variant:"outline",className:"h-11 px-3 shrink-0",onClick:()=>g(!0),children:[e.jsx(pn,{className:"h-4 w-4"}),($||P!=="__all__")&&e.jsx("span",{className:"ml-1 h-2 w-2 rounded-full bg-primary inline-block"})]}),e.jsxs($r,{side:"bottom",className:"h-auto pb-8 rounded-t-2xl",children:[e.jsx(Ar,{children:e.jsx(Mr,{children:"Filters"})}),e.jsxs("div",{className:"mt-4 space-y-4",children:[$&&e.jsxs("div",{className:"flex items-center justify-between gap-2 rounded-lg border border-white/10 p-3",children:[e.jsx("span",{className:"text-sm text-muted-foreground truncate",children:$.file_name}),e.jsx(ce,{size:"sm",variant:"ghost",onClick:()=>W(null),children:"Clear"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Appraiser"}),e.jsxs(It,{value:P,onValueChange:U,children:[e.jsx(Ot,{className:"h-11",children:e.jsx(Ut,{placeholder:"All appraisers"})}),e.jsxs(Gt,{children:[e.jsx(Te,{value:"__all__",children:"All appraisers"}),oe.map(l=>e.jsxs(Te,{value:l.name,children:[l.name," (",l.count,")"]},l.name))]})]})]}),e.jsx(ce,{className:"w-full h-11",onClick:()=>g(!1),children:"Done"})]})]})]})]}):e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("div",{className:"relative flex-1 min-w-[240px]",children:[e.jsx($s,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ct,{placeholder:"Search VIN, stock #, dealer, vehicle…",value:ue,onChange:l=>D(l.target.value),className:"pl-9"})]}),$&&e.jsxs(Pe,{variant:"outline",className:"gap-2",children:["Filtered to: ",$.file_name,e.jsx("button",{onClick:()=>W(null),className:"ml-1 hover:text-foreground",children:"×"})]}),e.jsxs(It,{value:P,onValueChange:U,children:[e.jsx(Ot,{className:"w-[240px]",children:e.jsx(Ut,{placeholder:"All appraisers"})}),e.jsxs(Gt,{children:[e.jsx(Te,{value:"__all__",children:"All appraisers"}),oe.map(l=>e.jsxs(Te,{value:l.name,children:[l.name," (",l.count,")"]},l.name))]})]}),P!=="__all__"&&e.jsxs(Pe,{variant:"outline",className:"gap-2",children:["Appraiser: ",P,e.jsx("button",{onClick:()=>U("__all__"),className:"ml-1 hover:text-foreground",children:"×"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-6 gap-3",children:[e.jsx(Be,{label:"Appraisals",value:Rt.appraisals.toString(),icon:As}),e.jsx(Be,{label:"Sold",value:Rt.sold.toString(),icon:Ze}),e.jsx(Be,{label:"Total Floor",value:ee(Rt.totalFloor),icon:Ze}),e.jsx(Be,{label:"Total Sale",value:ee(Rt.totalSale),icon:Ze}),e.jsx(Be,{label:"Net P/L",value:ee(Rt.netPL),icon:Rt.netPL>=0?Ze:Wt,tone:Rt.netPL>=0?"green":"red"}),e.jsx(Be,{label:"Avg P/L / Vehicle",value:ee(Rt.avgPL),icon:Rt.avgPL>=0?Ze:Wt,tone:Rt.avgPL>=0?"green":"red"})]}),Ue?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ce,{variant:"outline",size:"sm",onClick:()=>z(null),children:"← Back to all dealers"}),e.jsxs("div",{children:[e.jsx("div",{className:"font-mono text-sm",children:Ue.dealer_code}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Ue.dealer_name||"—"})]})]}),e.jsxs(ce,{variant:"outline",size:"sm",onClick:()=>bn(Ue,Ue.lots,l=>{var b;return Ft(l,(b=ot.get(l.run_id??""))==null?void 0:b.source)},d(Ue)),children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Print Store Report"]})]}),(()=>{var b;const l=d(Ue);return l?l.incomplete?e.jsx("div",{className:"rounded-lg border border-amber-500/40 bg-amber-500/10 px-4 py-3 text-sm text-amber-100",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(lr,{className:"h-4 w-4 mt-0.5 shrink-0"}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"font-medium",children:"Incomplete import"}),l.listedGap>0&&e.jsxs("div",{children:["Only ",e.jsx("b",{children:Ue.lots_count})," of ",e.jsx("b",{children:l.reportListed})," vehicles were read for this store."]}),l.soldGap>0&&e.jsxs("div",{children:["The auction report shows ",e.jsx("b",{children:l.reportSold})," sold; this page shows"," ",e.jsx("b",{children:Ue.sold}),"."]}),$&&(((b=$.page_gaps)==null?void 0:b.length)??0)>0&&e.jsx("div",{className:"pt-1",children:e.jsxs(ce,{size:"sm",variant:"outline",onClick:()=>V($),className:"h-8",children:[e.jsx(Ks,{className:"h-3.5 w-3.5 mr-2"}),"Re-read missing pages"]})})]})]})}):e.jsxs("div",{className:"rounded-lg border border-emerald-500/40 bg-emerald-500/10 px-4 py-2 text-sm text-emerald-100",children:["Complete — all ",l.reportListed??Ue.lots_count," vehicles on the auction report were read",l.reportSold!=null?`, ${l.reportSold} sold`:"","."]}):null})(),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-7 gap-3",children:[e.jsx(Be,{label:"Lots",value:Ue.lots_count.toString(),icon:As}),e.jsx(Be,{label:"Sold",value:Ue.sold.toString(),icon:Ze}),e.jsx(Be,{label:"No Sale",value:Ue.no_sale.toString(),icon:Wt}),e.jsx(Be,{label:"Total Sale",value:ee(Ue.total_sale),icon:Ze}),e.jsx(Be,{label:"Total Net",value:ee(Ue.total_net),icon:Ze}),e.jsx(Be,{label:"Profit / Loss",value:ee(Ue.profit_loss),icon:Ue.profit_loss>=0?Ze:Wt,tone:Ue.profit_loss>=0?"green":"red"}),(()=>{const l=Ue.sold>0?Ue.profit_loss/Ue.sold:0;return e.jsx(Be,{label:"Avg P/L / Vehicle",value:Ue.sold>0?ee(l):"—",icon:l>=0?Ze:Wt,tone:l>=0?"green":"red"})})()]}),e.jsx($e,{className:"bg-white/[0.03] border-white/10",children:e.jsx(Ae,{className:"p-0 overflow-x-auto",children:i?e.jsx("div",{className:"divide-y divide-white/10",children:Ue.lots.map(l
353=>{const b=Ft(l);return e.jsxs("button",{type:"button",className:"w-full text-left p-4 hover:bg-white/[0.04] active:bg-white/[0.06] min-h-[44px] space-y-2",onClick:()=>_e(l),children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium text-foreground",children:fs(l)}),e.jsxs("div",{className:"text-xs text-muted-foreground font-mono",children:["Lot ",l.lot_number??"—"," · ",l.stock_number??"—"]})]}),l.sale_price===null?e.jsx(Pe,{className:"bg-amber-500/15 text-amber-200 border-amber-500/30 shrink-0",children:"NO SALE"}):e.jsx(Pe,{className:"bg-emerald-500/15 text-emerald-300 border-emerald-500/30 shrink-0",children:"SOLD"})]}),e.jsxs("div",{className:"min-w-0 grid grid-cols-2 sm:grid-cols-3 gap-2 text-xs",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Floor "}),e.jsx("span",{className:"font-medium",children:ee(l.floor_price)})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Sale "}),e.jsx("span",{className:"font-medium",children:l.sale_price==null?"—":ee(l.sale_price)})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"P/L "}),e.jsx("span",{className:`font-medium ${b==null?"":b>=0?"text-emerald-300":"text-red-300"}`,children:ee(b)})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Miles "}),e.jsx("span",{children:gs(l.miles)})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"VIN "}),e.jsx("span",{className:"font-mono text-xs",children:l.vin??"—"})]})]})]},l.id)})}):e.jsxs(ke,{children:[e.jsx(Le,{children:e.jsxs(q,{children:[e.jsx(h,{children:"Lot"}),e.jsx(h,{children:"Vehicle"}),e.jsx(h,{children:"VIN"}),e.jsx(h,{className:"text-right",children:"Miles"}),e.jsx(h,{className:"text-right",children:"Floor"}),e.jsx(h,{className:"text-right",children:"Sale"}),e.jsx(h,{className:"text-right",children:"Fee"}),e.jsx(h,{className:"text-right",children:"Net Check"}),e.jsx(h,{className:"text-right",children:"P/L"}),e.jsx(h,{children:"Appraiser"}),e.jsx(h,{children:"Status"}),e.jsx(h,{children:"Flags"})]})}),e.jsx(Ce,{children:Ue.lots.map(l=>{const b=Ft(l);return e.jsxs(q,{className:"cursor-pointer hover:bg-white/[0.04]",onClick:()=>_e(l),children:[e.jsx(c,{className:"font-mono text-xs",children:l.lot_number??"—"}),e.jsxs(c,{className:"text-xs",children:[e.jsx("div",{children:fs(l)}),e.jsx("div",{className:"text-muted-foreground",children:[l.color,l.title_state].filter(Boolean).join(" • ")})]}),e.jsx(c,{className:"font-mono text-xs",children:l.vin??"—"}),e.jsx(c,{className:"text-right",children:gs(l.miles)}),e.jsx(c,{className:"text-right",children:ee(l.floor_price)}),e.jsx(c,{className:"text-right",children:l.sale_price===null?e.jsx("span",{className:"text-amber-300",children:"—"}):ee(l.sale_price)}),e.jsx(c,{className:"text-right",children:ee(l.auction_fee)}),e.jsx(c,{className:"text-right",children:ee(l.net_check_to_dealer)}),e.jsx(c,{className:`text-right font-medium ${b===null?"text-muted-foreground":b>=0?"text-emerald-300":"text-red-300"}`,children:ee(b)}),e.jsx(c,{className:"text-xs",children:l.appraiser??"—"}),e.jsx(c,{children:l.sale_price===null?e.jsx(Pe,{className:"bg-amber-500/15 text-amber-200 border-amber-500/30",children:"NO SALE"}):e.jsx(Pe,{className:"bg-emerald-500/15 text-emerald-300 border-emerald-500/30",children:"SOLD"})}),e.jsx(c,{children:e.jsxs("div",{className:"flex flex-wrap gap-1",children:[l.as_is&&e.jsx(Ds,{children:"AS IS"}),l.structural_damage&&e.jsx(Ds,{tone:"red",children:"STRUCT"}),l.over_200k&&e.jsx(Ds,{children:"200K+"}),l.over_100k&&!l.over_200k&&e.jsx(Ds,{children:"100K+"}),l.canadian_vehicle&&e.jsx(Ds,{children:"CDN"})]})})]},l.id)})})]})})})]}):e.jsx($e,{className:"bg-white/[0.03] border-white/10",children:e.jsx(Ae,{className:"p-0 overflow-x-auto",children:S?e.jsx("div",{className:"p-8 text-center text-muted-foreground",children:"Loading…"}):as.length===0?e.jsx("div",{className:"p-8 text-center text-muted-foreground",children:"No lots match."}
353):i?e.jsx("div",{className:"divide-y divide-white/10",children:as.map(l=>{const b=l.sold>0?l.profit_loss/l.sold:0;return e.jsxs("button",{type:"button",className:"w-full text-left p-4 hover:bg-white/[0.04] active:bg-white/[0.06] min-h-[44px] space-y-2",onClick:()=>z(l.key),children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium text-foreground",children:l.dealer_name||l.dealer_code}),e.jsx("div",{className:"text-xs text-muted-foreground font-mono",children:l.dealer_code})]}),e.jsxs("div",{className:"min-w-0 grid grid-cols-2 sm:grid-cols-3 gap-2 text-xs",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Lots "}),e.jsx("span",{className:"font-medium",children:l.lots_count})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Sold "}),e.jsx("span",{className:"text-emerald-300 font-medium",children:l.sold})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Sell% "}),e.jsx("span",{className:"text-sky-300 font-medium",children:l.lots_count?`${(l.sold/l.lots_count*100).toFixed(0)}%`:"—"})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"P/L "}),e.jsx("span",{className:`font-medium ${l.profit_loss>=0?"text-emerald-300":"text-red-300"}`,children:ee(l.profit_loss)})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Avg "}),e.jsx("span",{className:`font-medium ${b>=0?"text-emerald-300":"text-red-300"}`,children:l.sold>0?ee(b):"—"})]})]})]},l.key)})}):e.jsxs(ke,{children:[e.jsx(Le,{children:e.jsxs(q,{children:[e.jsx(lt,{sortKey:"dealer_code",sort:G,onSort:K,label:"Dealer Code"}),e.jsx(lt,{sortKey:"dealer_name",sort:G,onSort:K,label:"Dealer Name"}),e.jsx(lt,{sortKey:"lots_count",sort:G,onSort:K,align:"right",label:"Lots"}),e.jsx(lt,{sortKey:"sold",sort:G,onSort:K,align:"right",label:"Sold"}),e.jsx(lt,{sortKey:"sell_rate",sort:G,onSort:K,align:"right",label:"Sell %"}
353),e.jsx(lt,{sortKey:"no_sale",sort:G,onSort:K,align:"right",label:"No Sale"}),e.jsx(lt,{sortKey:"total_sale",sort:G,onSort:K,align:"right",label:"Total Sale"}),e.jsx(lt,{sortKey:"total_net",sort:G,onSort:K,align:"right",label:"Total Net"}),e.jsx(lt,{sortKey:"profit_loss",sort:G,onSort:K,align:"right",label:"P/L"}),e.jsx(h,{className:"text-right",children:"Avg P/L / Vehicle"})]})}),e.jsx(Ce,{children:as.map(l=>e.jsxs(q,{className:"cursor-pointer hover:bg-white/[0.04]",onClick:()=>z(l.key),children:[e.jsx(c,{className:"font-mono text-sm",children:l.dealer_code}),e.jsx(c,{className:"text-sm",children:l.dealer_name||"—"}),e.jsx(c,{className:"text-right",children:l.lots_count}),e.jsx(c,{className:"text-right text-emerald-300",children:l.sold}),e.jsx(c,{className:"text-right text-sky-300",children:l.lots_count?`${(l.sold/l.lots_count*100).toFixed(1)}%`:"—"}),e.jsx(c,{className:"text-right text-amber-300",children:l.no_sale}),e.jsx(c,{className:"text-right",children:ee(l.total_sale)}),e.jsx(c,{className:"text-right",children:ee(l.total_net)}),e.jsx(c,{className:`text-right font-medium ${l.profit_loss>=0?"text-emerald-300":"text-red-300"}`,children:ee(l.profit_loss)}),(()=>{const b=l.sold>0?l.profit_loss/l.sold:0;return e.jsx(c,{className:`text-right font-medium ${b>=0?"text-emerald-300":"text-red-300"}`,children:l.sold>0?ee(b):"—"})})()]},l.key))})]})})})]}),e.jsxs(ut,{value:"dealers",className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("div",{className:"relative flex-1 min-w-[240px] max-w-md",children:[e.jsx($s,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ct,{placeholder:"Search dealer code or name…",value:ue,onChange:l=>D(l.target.value),className:"pl-9 bg-black/25 border-white/10"})]}),$&&e.jsxs(Pe,{variant:"outline",className:"border-white/15",children:["Filtered to: ",$.file_name]}),e.jsx("div",{className:"ml-auto flex items-center gap-2",children:e.jsx(ce,{variant:"outline",size:"sm",onClick:ds,disabled:Fe.length===0,children:"Export CSV"})})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-4",children:[e.jsx(Be,{label:"Dealers",value:Fe.length.toString(),icon:As}),e.jsx(Be,{label:"Lots Run",value:be.lots_run.toString(),icon:As}),e.jsx(Be,{label:"Sold / No Sale",value:`${be.sold} / ${be.no_sale}`,icon:Ze}),e.jsx(Be,{label:"Aggregate P/L",value:ee(be.profit_loss),icon:be.profit_loss>=0?Ze:Wt,tone:be.profit_loss>=0?"green":"red"}),(()=>{const l=be.sold>0?be.profit_loss/be.sold:0;return e.jsx(Be,{label:"Avg P/L / Vehicle",value:be.sold>0?ee(l):"—",icon:l>=0?Ze:Wt,tone:l>=0?"green":"red"})})()]}),e.jsx($e,{className:"bg-white/[0.03] border-white/10",children:e.jsx(Ae,{className:"p-0",children:S?e.jsx("div",{className:"p-8 text-center text-muted-foreground",children:"Loading…"}):Fe.length===0?e.jsx("div",{className:"p-8 text-center text-muted-foreground",children:"No dealer data yet."}):i?e.jsx("div",{className:"divide-y divide-white/10",children:Fe.map(l=>e.jsxs("div",{className:"p-4 space-y-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium text-foreground",children:l.dealer_name}),e.jsx("div",{className:"text-xs text-muted-foreground font-mono",children:l.dealer_code})]}),e.jsxs("div",{className:"min-w-0 grid grid-cols-2 sm:grid-cols-3 gap-2 text-xs",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Lots "}),e.jsx("span",{className:"font-medium",children:l.lots_run})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Sold "}),e.jsx("span",{className:"text-emerald-300 font-medium",children:l.sold})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Sell% "}),e.jsxs("span",{className:"text-sky-300 font-medium",children:[l.sell_through.toFixed(0),"%"]})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"P/L "}),e.jsx("span",{className:`font-medium ${l.profit_loss>=0?"text-emerald-300":"text-red-300"}`,children:ee(l.profit_loss)})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Avg "}),e.jsx("span",{className:`font-medium ${l.avg_pl>=0?"text-emerald-300":"text-red-300"}`,children:ee(l.avg_pl)})]})]})]},l.key))}):e.jsxs(ke,{children:[e.jsx(Le,{children:e.jsxs(q,{children:[e.jsx(lt,{label:"Dealer",sortKey:"dealer_code",sort:w,onSort:ct}),e.jsx(lt,{label:"Lots Run",sortKey:"lots_run",sort:w,onSort:ct,align:"right"}),e.jsx(lt,{label:"Sold",sortKey:"sold",sort:w,onSort:ct,align:"right"}
353),e.jsx(lt,{label:"No Sale",sortKey:"no_sale",sort:w,onSort:ct,align:"right"}),e.jsx(lt,{label:"Sell-through",sortKey:"sell_through",sort:w,onSort:ct,align:"right"}),e.jsx(lt,{label:"Total Sale",sortKey:"total_sale_price",sort:w,onSort:ct,align:"right"}),e.jsx(lt,{label:"Net to Dealer",sortKey:"total_net",sort:w,onSort:ct,align:"right"}),e.jsx(lt,{label:"Fees",sortKey:"total_fees",sort:w,onSort:ct,align:"right"}),e.jsx(lt,{label:"Profit / Loss",sortKey:"profit_loss",sort:w,onSort:ct,align:"right"}),e.jsx(lt,{label:"Avg P/L / Vehicle",sortKey:"avg_pl",sort:w,onSort:ct,align:"right"})]})}),e.jsxs(Ce,{children:[Fe.map(l=>e.jsxs(q,{children:[e.jsxs(c,{children:[e.jsx("div",{className:"font-medium text-foreground",children:l.dealer_code}),e.jsx("div",{className:"text-xs text-muted-foreground",children:l.dealer_name})]}),e.jsx(c,{className:"text-right",children:l.lots_run}),e.jsx(c,{className:"text-right",children:l.sold}),e.jsx(c,{className:"text-right",children:l.no_sale}),e.jsxs(c,{className:"text-right",children:[l.sell_through.toFixed(1),"%"]}),e.jsx(c,{className:"text-right",children:ee(l.total_sale_price)}),e.jsx(c,{className:"text-right",children:ee(l.total_net)}),e.jsx(c,{className:"text-right",children:ee(l.total_fees)}),e.jsx(c,{className:"text-right",children:e.jsxs("span",{className:`inline-flex items-center gap-1 font-medium ${l.profit_loss>=0?"text-emerald-400":"text-destructive"}`,children:[l.profit_loss>=0?e.jsx(Ze,{className:"h-3.5 w-3.5"}):e.jsx(Wt,{className:"h-3.5 w-3.5"}),ee(l.profit_loss)]})}),e.jsx(c,{className:"text-right",children:ee(l.avg_pl)})]},l.key)),e.jsxs(q,{className:"bg-white/[0.04] font-medium",children:[e.jsxs(c,{children:["Totals (",Fe.length," dealers)"]}),e.jsx(c,{className:"text-right",children:be.lots_run}),e.jsx(c,{className:"text-right",children:be.sold}),e.jsx(c,{className:"text-right",children:be.no_sale}),e.jsxs(c,{className:"text-right",children:[be.lots_run>0?(be.sold/be.lots_run*100).toFixed(1):"0.0","%"]}),e.jsx(c,{className:"text-right",children:ee(be.total_sale_price)}),e.jsx(c,{className:"text-right",children:ee(be.total_net)}),e.jsx(c,{className:"text-right",children:ee(be.total_fees)}),e.jsx(c,{className:"text-right",children:e.jsx("span",{className:`font-semibold ${be.profit_loss>=0?"text-emerald-400":"text-destructive"}`,children:ee(be.profit_loss)})}),e.jsx(c,{className:"text-right",children:ee(be.sold>0?be.profit_loss/be.sold:0)})]})]})]})})})]}),e.jsxs(ut,{value:"vin-comp",className:"mt-4 space-y-4",children:[e.jsxs($e,{className:"bg-white/[0.03] border-white/10",children:[e.jsx(At,{children:e.jsxs(Mt,{className:"text-base flex items-center gap-2",children:[e.jsx(Qa,{className:"h-4 w-4"})," Appraise by VIN"]})}),e.jsxs(Ae,{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[e.jsxs("div",{className:"flex-1 min-w-[260px]",children:[e.jsx("label",{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"VIN"}),e.jsx(Ct,{value:he,onChange:l=>De(l.target.value.toUpperCase()),placeholder:"17-character VIN",maxLength:17,className:"font-mono"})]}),e.jsxs(ce,{onClick:ns,disabled:Ne||he.trim().length!==17,children:[Ne?e.jsx(es,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx($s,{className:"h-4 w-4 mr-2"}),"Decode VIN"]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Year"}),e.jsx(Ct,{value:de,onChange:l=>ge(l.target.value),placeholder:"2022"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Make"}),e.jsx(Ct,{value:Me,onChange:l=>se(l.target.value),placeholder:"Toyota"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Model"}),e.jsx(Ct,{value:we,onChange:l=>Oe(l.target.value),placeholder:"Camry"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Trim"}),e.jsx(Ct,{value:je,onChange:l=>ae(l.target.value),placeholder:"SE"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Miles *"}),e.jsx(Ct,{value:re,onChange:l=>it(l.target.value),placeholder:"45000",inputMode:"numeric"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"± Miles"}),e.jsx(Ct,{value:te,onChange:l=>Ee(l.target.value),inputMode:"numeric"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"± Years"}),e.jsx(Ct,{value:Nt,onChange:l=>zt(l.target.value),inputMode:"numeric"})]}),e.jsx("div",{className:"flex items-end",children:e.jsxs("label",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx("input",{type:"checkbox",checked:xt,onChange:l=>Kt(l.target.checked)}),"Trim must match"]})})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(ce,{onClick:Ea,children:[e.jsx($s,{className:"h-4 w-4 mr-2"})," Find Comps"]}),We&&$t.length>0&&e.jsx(ce,{variant:"outline",onClick:Fa,children:"Export CSV"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Showing auction results from the last 60 days."})]})]})]}),We&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(Be,{label:"Comps Found",value:Et.total.toString(),icon:As}),e.jsx(Be,{label:"Sold / No Sale",value:`${Et.sold} / ${Et.noSale}`,icon:Ze}),e.jsx(Be,{label:"Avg Sale Price",value:ee(Et.avgPrice),icon:Ze}),e.jsx(Be,{label:"Median Sale Price",value:ee(Et.medianPrice),icon:Ze}),e.jsx(Be,{label:"Low Sale",value:ee(Et.lowPrice),icon:Wt}),e.jsx(Be,{label:"High Sale",value:ee(Et.highPrice),icon:Ze}),e.jsx(Be,{label:"Avg Net to Dealer",value:ee(Et.avgNet),icon:Ze}),e.jsx(Be,{label:"Avg P/L / Vehicle",value:ee(Et.avgPL),icon:Et.avgPL>=0?Ze:Wt,tone:Et.avgPL>=0?"green":"red"})]}),e.jsx($e,{className:"bg-white/[0.03] border-white/10",children:e.jsx(Ae,{className:"p-0",children:$t.length===0?e.jsxs("div",{className:"p-8 text-center text-muted-foreground space-y-2",children:[e.jsx("div",{children:"No comparable auction lots found in your current scope."}),e.jsxs("div",{className:"text-xs",children:["Matching ",e.jsxs("span",{className:"text-sky-300",children:[Me," ",we]})," in last 60 days:"," ",e.jsx("span",{className:"text-foreground",children:ks.makeModel})," same make/model"," → ",e.jsx("span",{className:"text-foreground",children:ks.afterYear})," within ±",Nt," yrs"," → ",e.jsx("span",{className:"text-foreground",children:ks.afterMiles}
353)," within ±",Number(te).toLocaleString()," mi",xt&&e.jsxs(e.Fragment,{children:[" → ",e.jsx("span",{className:"text-foreground",children:ks.afterTrim})," trim match"]})," → ",e.jsx("span",{className:"text-foreground",children:ks.afterWindow})," in last 60 days"]}),e.jsx("div",{className:"text-xs",children:'Try widening the mileage or year tolerance, or unchecking "Trim must match".'})]}):i?e.jsx("div",{className:"divide-y divide-white/10",children:$t.map(l=>{const b=l.run_id?ot.get(l.run_id):void 0,O=Ft(l);return e.jsxs("button",{type:"button",className:"w-full text-left p-4 hover:bg-white/[0.04] active:bg-white/[0.06] min-h-[44px] space-y-2",onClick:()=>_e(l),children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium text-foreground",children:fs(l)}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[sr((b==null?void 0:b.sale_date)??null)," · ",l.dealer_name??l.dealer_code??"—"]})]}),l.sale_price===null?e.jsx(Pe,{className:"bg-amber-500/15 text-amber-200 border-amber-500/30 shrink-0",children:"No Sale"}):e.jsx(Pe,{className:"bg-emerald-500/15 text-emerald-300 border-emerald-500/30 shrink-0",children:"Sold"})]}),e.jsxs("div",{className:"min-w-0 grid grid-cols-2 sm:grid-cols-3 gap-2 text-xs",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Miles "}),e.jsx("span",{children:gs(l.miles)})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Sale "}),e.jsx("span",{className:"font-medium",children:l.sale_price==null?"—":ee(l.sale_price)})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"P/L "}),e.jsx("span",{className:`font-medium ${O==null?"":O>=0?"text-emerald-300":"text-red-300"}`,children:ee(O)})]})]})]},l.id)})}):e.jsxs(ke,{children:[e.jsx(Le,{children:e.jsxs(q,{children:[e.jsx(h,{children:"Sale Date"}),e.jsx(h,{children:"Vehicle"}),e.jsx(h,{className:"text-right",children:"Miles"}),e.jsx(h,{className:"text-right",children:"Sale Price"}),e.jsx(h,{className:"text-right",children:"Net to Dealer"}),e.jsx(h,{className:"text-right",children:"P/L"}),e.jsx(h,{children:"Status"}),e.jsx(h,{children:"Dealer"}),e.jsx(h,{children:"Lot #"})]})}),e.jsx(Ce,{children:$t.map(l=>{const b=l.run_id?ot.get(l.run_id):void 0,O=Ft(l);return e.jsxs(q,{className:"cursor-pointer hover:bg-white/[0.04]",onClick:()=>_e(l),children:[e.jsx(c,{children:sr((b==null?void 0:b.sale_date)??null)}),e.jsxs(c,{children:[e.jsx("div",{children:fs(l)}),l.trim&&e.jsx("div",{className:"text-xs text-muted-foreground",children:l.trim})]}),e.jsx(c,{className:"text-right",children:gs(l.miles)}),e.jsx(c,{className:"text-right",children:l.sale_price===null?e.jsx("span",{className:"text-amber-300",children:"NO SALE"}):ee(l.sale_price)}),e.jsx(c,{className:"text-right",children:ee(l.net_check_to_dealer)}),e.jsx(c,{className:`text-right font-medium ${O==null?"":O>=0?"text-emerald-300":"text-red-300"}`,children:ee(O)}),e.jsx(c,{children:l.sale_price===null?e.jsx(Pe,{className:"bg-amber-500/15 text-amber-200 border-amber-500/30",children:"No Sale"}):e.jsx(Pe,{className:"bg-emerald-500/15 text-emerald-300 border-emerald-500/30",children:"Sold"})}),e.jsx(c,{className:"text-sm",children:l.dealer_name??l.dealer_code??"—"}),e.jsx(c,{className:"font-mono text-xs",children:l.lot_number??"—"})]},l.id)})})]})})})]})]}),e.jsx(ut,{value:"aliases",className:"mt-4",children:e.jsx(Rn,{})}),e.jsx(ut,{value:"reports",className:"mt-4",children:e.jsx(Pn,{})})]}),e.jsx(Cr,{open:!!B,onOpenChange:l=>!l&&_e(null),children:e.jsxs($r,{side:i?"bottom":"right",className:i?"h-[90vh] overflow-y-auto rounded-t-2xl":"w-full sm:max-w-xl overflow-y-auto",children:[e.jsx(Ar,{children:e.jsxs("div",{className:"flex items-start justify-between gap-3 pr-8",children:[e.jsx(Mr,{children:B?fs(B):""}),B&&e.jsxs(ce,{size:"sm",variant:"outline",onClick:()=>vn(B,Ft(B)),children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Print"]})]})}),B&&e.jsxs("div",{className:"mt-6 space-y-5 text-sm",children:[e.jsxs(rr,{title:"Selling Dealer",children:[e.jsx(et,{label:"Dealer Code",value:B.dealer_code,mono:!0}),e.jsx(et,{label:"Dealer Name",value:B.dealer_name})]}),e.jsxs(rr,{title:"Vehicle",children:[e.jsx(et,{label:"VIN",value:
353B.vin,mono:!0}),e.jsx(et,{label:"Stock #",value:B.stock_number,mono:!0}),e.jsx(et,{label:"Color",value:B.color}),e.jsx(et,{label:"Miles",value:gs(B.miles)}),e.jsx(et,{label:"Title State",value:B.title_state})]}),e.jsxs(rr,{title:"Pricing",children:[e.jsx(et,{label:"Floor Price",value:ee(B.floor_price)}),e.jsx(et,{label:"Sale Price",value:B.sale_price===null?"NO SALE":ee(B.sale_price),tone:B.sale_price===null?"amber":void 0}),e.jsx(et,{label:"Auction Fee",value:ee(B.auction_fee)}),e.jsx(et,{label:"Net Check to Dealer",value:ee(B.net_check_to_dealer)}),(()=>{const l=Ft(B);return e.jsx(et,{label:"Profit / Loss",value:ee(l),tone:l===null?void 0:l>=0?"green":"red"})})(),e.jsx(et,{label:"Local CV",value:ee(B.local_cv)}),e.jsx(et,{label:"National CV",value:ee(B.natl_cv)}),e.jsx(et,{label:"Guidebook",value:ee(B.guidebook)}),e.jsx(et,{label:"Highest Bid",value:ee(B.highest_bid_amount)})]}),e.jsxs(rr,{title:"Condition",children:[e.jsx(et,{label:"Codes",value:B.condition_codes}),e.jsx(et,{label:"CR Comments",value:B.cr_comments}),e.jsx(et,{label:"Appraiser",value:B.appraiser}),e.jsx(et,{label:"Days in Inventory",value:gs(B.days_in_inventory)})]})]})]})})]})}function Be({label:t,value:s,icon:a,tone:r}){const n=r==="green"?"text-emerald-300":r==="red"?"text-red-300":"text-foreground";return e.jsxs($e,{className:"bg-white/[0.03] border-white/10",children:[e.jsxs(At,{className:"pb-2 flex flex-row items-center justify-between space-y-0",children:[e.jsx(Mt,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:t}),e.jsx(a,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Ae,{children:e.jsx("div",{className:`text-2xl font-semibold ${n}`,children:s})})]})}function sa({status:t,message:s,stale:a}){const r=xi(s),n=pi(r);return t==="ready"?e.jsx(Pe,{className:"bg-emerald-500/15 text-emerald-300 border-emerald-500/30",children:"Ready"}):t==="processing"?a?e.jsxs(Pe,{className:"bg-amber-500/15 text-amber-200 border-amber-500/30 cursor-help",title:s??"Processing seems stuck — use Reprocess.",children:[e.jsx(lr,{className:"h-3 w-3 mr-1"}),"Stuck"]}):e.jsxs("div",{className:"min-w-[150px] space-y-1",title:(r==null?void 0:r.label)??s??"Processing…",children:[e.jsxs(Pe,{className:"bg-sky-500/15 text-sky-300 border-sky-500/30 cursor-help",children:[e.jsx(es,{className:"h-3 w-3 mr-1 animate-spin"}),r!=null&&r.total?`Parsing ${n}%`:"Starting"]}),e.jsx(aa,{value:n,className:"h-1.5 bg-white/10"}),e.jsxs("div",{className:"text-[10px] text-muted-foreground",children:[r!=null&&r.total?`Chunk ${r.current}/${r.total}`:"Queued",r!=null&&r.failed?` • ${r.failed} skipped`:""]})]}):e.jsxs(Pe,{className:"bg-red-500/15 text-red-300 border-red-500/30 cursor-help",title:s??"Failed",children:[e.jsx(lr,{className:"h-3 w-3 mr-1"}),"Failed"]})}function Ds({children:t,tone:s}){const a=s==="red"?"bg-red-500/15 text-red-300 border-red-500/30":"bg-white/5 text-foreground/70 border-white/10";return e.jsx(Pe,{variant:"outline",className:`text-[10px] py-0 ${a}`,children:t})}function rr({title:t,children:s}){return e.jsxs("div",{children:[e.jsx("div",{className:"text-xs uppercase tracking-wider text-muted-foreground mb-2",children:t}),e.jsx("div",{className:"space-y-1.5 rounded-md border border-white/10 bg-black/20 p-3",children:s})]})}function et({label:t,value:s,mono:a,tone:r}){const n=r==="green"?"text-emerald-300":r==="red"?"text-red-300":r==="amber"?"text-amber-300":"text-foreground";return e.jsxs("div",{className:"flex justify-between gap-3",children:[e.jsx("span",{className:"text-muted-foreground",children:t}),e.jsx("span",{className:`${a?"font-mono":""} ${n}`,children:s??"—"})]})}export{Wi 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.