PageSourceSearch

https://aidealer360.com/assets/Inventory-Dmd2bfSE.js

js aidealer360.com collected 2026-10-01 15:56:18 UTC 85,898 bytes, 19 lines download raw bytes

1import{j as e}from"./ui-vendor-B12AOeKi.js";import{r as l,L as Fe,u as Bs}from"./react-vendor-DZt7wVAJ.js";import{P as ce,ax as ss,i as de,ba as qs,u as $s,s as j,g as K,B as L,D as Je,b as Ke,c as Ye,d as He,e as pt,L as he,h as as,Y as is,p as xt,ao as ot,bn as rs,q as Se,a4 as me,bz as As,aa as ct,an as Ot,T as Ps,I as Ls,X as Vt,U as Ms,R as Ut,av as Rs}from"./index-BZo64Z7H.js";import{S as ve,a as ye,b as Ne,c as ke,d as ne}from"./select-B9Z9mxdV.js";import{T as Ts,b as Is,c as Pe}from"./tabs-BcL48lVI.js";import{A as zt,a as Gt,b as Xt,c as Qt,d as Jt,e as Kt,g as Yt,f as Ht}from"./alert-dialog-Diwn5aYx.js";import{q as Os,s as Vs,F as Us,g as Ce,a as Me}from"./api-yesdblu2.js";import{R as ns}from"./rotate-cw-B4yJW96d.js";import{F as Ee}from"./facebook-DRz6IjqJ.js";import{C as Le}from"./circle-check-BmAvJLJ8.js";import{T as zs}from"./tag-BDVlXBsS.js";import{E as dt}from"./external-link-B_oQ01HE.js";import{r as Gs,u as Xs}from"./xlsx-CwpDMyS9.js";import{F as Qs}from"./file-spreadsheet-BEw0f8A5.js";import{U as ut}from"./upload-CzyNu08p.js";import{T as Js}from"./trending-down-C5bokXPm.js";import{R as Ks}from"./RemoveBgButton-BdJoXzQ7.js";import{S as nt}from"./switch-D_kCiubG.js";import{S as mt}from"./sparkles-BkfsvibN.js";import{u as Ys}from"./M360AccessContext-DFZl1nl9.js";import{S as Hs}from"./square-check-big-CbzWFgOM.js";import"./charts-vendor-B6q1L48j.js";import"./supabase-vendor-dOy44Gxq.js";import"./animation-vendor-BAVy02gd.js";import"./image-BRglW2oI.js";import"./undo-2-H8CVnlb0.js";function Wt(s){return s?!!s.certified_status||s.condition==="certified":!1}function lt(s){const a=s==null?void 0:s.condition;return a==="used"||a==="certified"}function ht(s,a){if(a==="all")return!0;if(!s)return!1;switch(a){case"new":return s.condition==="new";case"used":return lt(s);case"certified":return lt(s)&&Wt(s);case"value":return lt(s)&&!Wt(s);default:return!0}}function Ws({vehicleId:s,myQueued:a,myPosted:i,myError:r,onStaged:u,onStageError:m,className:p}){const[g,f]=l.useState(!1),b=async N=>{if(N.preventDefault(),N.stopPropagation(),!(g||a)){f(!0),u==null||u();try{await Os(s),de.success("Queued for Facebook Marketplace",{description:"Open the Marketplace360 Chrome extension → My Queue → Post to Facebook."})}catch($){m==null||m(),de.error(($==null?void 0:$.message)||"Failed to queue vehicle")}finally{f(!1)}}},C="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-md text-[11px] font-medium border transition cursor-pointer select-none",S=i?"bg-emerald-500/15 border-emerald-500/40 text-emerald-300 hover:bg-emerald-500/25":a?"bg-amber-500/15 border-amber-500/40 text-amber-200 hover:bg-amber-500/25":r?"bg-red-500/15 border-red-500/40 text-red-300 hover:bg-red-500/25":"bg-gradient-to-r from-[#2F80ED] to-[#1C5ED6] border-[#2F80ED]/50 text-white hover:opacity-90",B=i?"Posted — repost":a?"In your queue":g?"Queueing…":r?"Retry":"Queue for Posting",v=g&&!a?ce:i?ss:r?ns:Ee;return e.jsxs("button",{type:"button",onClick:b,disabled:g||a,className:`${C} ${S} ${p||""}`,title:"Stage this vehicle for the Chrome extension to post to Facebook Marketplace",children:[e.jsx(v,{className:`h-3 w-3 ${g&&!a?"animate-spin":""}`}),B]})}function Zs({vehicleId:s,myPosted:a,className:i,onPosted:r,variant:u="primary"}){const[m,p]=l.useState(!1),g=async C=>{if(C.preventDefault(),C.stopPropagation(),m)return;const S=window.open("about:blank","_blank");p(!0);try{await Vs(s);const B=Us;S?S.location.href=B:window.location.href=B,de.success("Opening Facebook Marketplace",{description:"The Marketplace360 extension will auto-fill this listing."}),r==null||r()}catch(B){try{S==null||S.close()}catch{}de.error((B==null?void 0:B.message)||"Failed to start post")}finally{p(!1)}},f=m?"Opening…":a?"Repost to FB":"Post to FB",b=m?ce:Ee;return e.jsxs("button",{type:"button",onClick:g,disabled:m,title:"Open Facebook Marketplace and auto-fill this listing via the Marketplace360 extension",className:"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-medium border transition select-none "+(u==="secondary"?"bg-white/[0.04] border-white/15 text-[#B8C7D9] hover:bg-white/[0.08] hover:text-[#E6EDF3] disabled:opacity-60 ":"bg-gradient-to-r from-[#2F80ED] to-[#1C5ED6] border-[#2F80ED]/60 text-white hover:opacity-90 disabled:opacity-60 ")+(i||""),children:[e.jsx(b,{className:`h-3.5 w-3.5 ${m?"animate-spin":""}`}),f]})}const ea="ebay_enabled";function ls(){const{organization:s}=qs(),{user:a}=$s(),[i,r]=l.useState(!1),[u,m]=l.useState(!0),[p,g]=l.useState(!0);return l.useEffect(()=>{let f=!1;async function b(){var $,U;if(!(s!=null&&s.id)){r(!1),g(!1);return}g(!0);const[C,S]=await Promise.all([j.from("organization_settings").select("setting_value").eq("organization_id",s.id).eq("setting_key",ea).maybeSingle(),a?j.from("m360_user_ebay_access").select("enabled").eq("user_id",a.id).eq("organization_id",s.id).maybeSingle():Promise.resolve({data:null})]);if(f)return;const B=($=C==null?void 0:C.data)==null?void 0:$.setting_value,v=B===!0||B==="true"||(B==null?void 0:B.enabled)===!0;r(!!v);const N=(U=S==null?void 0:S.data)==null?void 0:U.enabled;m(N==null?!0:!!N),g(!1)}return b(),()=>{f=!0}},[s==null?void 0:s.id,a==null?void 0:a.id]),{orgEnabled:i,userEnabled:u,canUseEbay:i&&u,loading:p}}function ta({vehicle:s,ebayAccountId:a,alreadyListed:i,onListed:r}){const[u,m]=l.useState(!1),[p,g]=l.useState(!1),{canUseEbay:f,loading:b}=ls();if(b||!f)return null;
1const C=[s.year,s.make,s.model,s.trim].filter(Boolean).join(" ").trim(),S=C.slice(0,80),B=(s.stock_number||s.vin||s.id).toString().slice(0,50),v=(s.m360_vehicle_images||[]).slice().sort((R,A)=>(R.sort_order??0)-(A.sort_order??0)).map(R=>R.url).filter(Boolean).slice(0,24),N=[C,s.mileage?`Mileage: ${Number(s.mileage).toLocaleString()} mi`:null,s.vin?`VIN: ${s.vin}`:null,s.stock_number?`Stock #: ${s.stock_number}`:null,s.description||null].filter(Boolean).join(`
2
3`),$=!!a&&!!s.price&&!!S&&v.length>0,U=async()=>{var R;if(a){g(!0);try{const{data:A,error:I}=await j.functions.invoke("ebay-create-listing",{body:{ebay_account_id:a,vehicle_id:s.id,sku:B,price:s.price,title:S,description:N,image_urls:v,year:s.year,make:s.make,model:s.model,trim:s.trim,vin:s.vin,mileage:s.mileage,body_style:s.body_style,transmission:s.transmission,fuel_type:s.fuel_type,exterior_color:s.exterior_color,interior_color:s.interior_color,drivetrain:s.drivetrain,engine:s.engine}});if(I){let se=I.message;try{const _=I.context;if(_&&typeof _.json=="function"){const k=await _.json();k!=null&&k.error&&(se=k.error)}else if(_&&typeof _.text=="function"){const k=await _.text();k&&(se=k)}}catch{}throw new Error(se)}if(A!=null&&A.error)throw new Error(A.error);const H=(A==null?void 0:A.listingId)||(A==null?void 0:A.offerId);de.success("Posted to eBay",{description:H?`Listing ${H}`:void 0}),r==null||r(H),m(!1)}catch(A){de.error("eBay post failed",{description:((R=A==null?void 0:A.message)==null?void 0:R.slice(0,500))||"Unknown error"})}finally{g(!1)}}};return i?e.jsxs(K,{variant:"outline",className:"text-[10px] gap-1 border-emerald-500/40 text-emerald-300",children:[e.jsx(Le,{className:"h-3 w-3"})," On eBay"]}):e.jsxs(e.Fragment,{children:[e.jsxs(L,{size:"sm",variant:"outline",disabled:!a,title:a?"Post this vehicle to eBay":"Connect an eBay account in Admin → eBay",onClick:()=>m(!0),children:[e.jsx(zs,{className:"h-3.5 w-3.5 mr-1.5"}),"Post to eBay"]}),e.jsx(Je,{open:u,onOpenChange:R=>!p&&m(R),children:e.jsxs(Ke,{children:[e.jsxs(Ye,{children:[e.jsx(He,{children:"Post to eBay"}),e.jsx(pt,{children:"Review the listing details before publishing."})]}),e.jsxs("div",{className:"space-y-3 text-sm",children:[e.jsxs("div",{children:[e.jsx(he,{className:"text-xs text-muted-foreground",children:"Title"}),e.jsx("div",{className:"text-foreground",children:S||e.jsx("span",{className:"text-destructive",children:"Missing"})})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(he,{className:"text-xs text-muted-foreground",children:"SKU"}),e.jsx("div",{children:B})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs text-muted-foreground",children:"Price"}),e.jsx("div",{children:s.price?`$${Number(s.price).toLocaleString()}`:e.jsx("span",{className:"text-destructive",children:"Missing"})})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs text-muted-foreground",children:"Photos"}),e.jsxs("div",{children:[v.length," ",v.length===0&&e.jsx("span",{className:"text-destructive",children:"(none)"})]})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs text-muted-foreground",children:"Category"}),e.jsx("div",{children:"Cars & Trucks (6001)"})]})]}),!a&&e.jsx("div",{className:"text-xs text-destructive",children:"No connected eBay account for this dealership."})]}),e.jsxs(as,{children:[e.jsx(L,{variant:"outline",onClick:()=>m(!1),disabled:p,children:"Cancel"}),e.jsxs(L,{onClick:U,disabled:!$||p,children:[p&&e.jsx(ce,{className:"h-4 w-4 mr-2 animate-spin"}),"Publish to eBay"]})]})]})})]})}function sa({open:s,onOpenChange:a,vehicle:i,thumbnail:r}){const{canUseEbay:u}=ls(),[m,p]=l.useState(null),[g,f]=l.useState(null),[b,C]=l.useState(null),[S,B]=l.useState(!1);l.useEffect(()=>{!s||!(i!=null&&i.id)||(B(!0),Promise.all([j.from("m360_vehicles").select("fb_stats, fb_stats_imported_at, fb_listing_url, fb_stats_previous, fb_stats_previous_imported_at").eq("id",i.id).maybeSingle(),j.from("ebay_listings").select("*").eq("vehicle_id",i.id).order("created_at",{ascending:!1}).limit(1).maybeSingle(),i!=null&&i.vin?j.from("m360_cargurus_vin_stats").select("vdp_views,srp_views,leads_total,lead_breakdown,window_start,window_end,updated_at").eq("vin",String(i.vin).toUpperCase()).order("updated_at",{ascending:!1}).limit(1).maybeSingle():Promise.resolve({data:null})]).then(([n,d,c])=>{p(n.data||null),f(d.data||null),C((c==null?void 0:c.data)||null),B(!1)}))},[s,i==null?void 0:i.id,i==null?void 0:i.vin]);const v=(m==null?void 0:m.fb_stats)||null,N=(m==null?void 0:m.fb_stats_previous)||null,$=Array.isArray(v==null?void 0:v.groups)?v.groups:[],U=Array.isArray(N==null?void 0:N.groups)?N.groups:[],R=m!=null&&m.fb_stats_imported_at?new Date(m.fb_stats_imported_at).toLocaleStr
3ing():null,A=m!=null&&m.fb_stats_previous_imported_at?new Date(m.fb_stats_previous_imported_at).toLocaleString():null,I=(n,d,c=0)=>{if(!n)return c;for(const x of d)if(typeof n[x]=="number")return n[x];return c},H=I(v,["totalClicks","marketplace_clicks"]),se=I(N,["totalClicks","marketplace_clicks"]),_=I(v,["totalComments","total_comments"],$.reduce((n,d)=>n+(d.comments||0),0)),k=I(N,["totalComments","total_comments"],U.reduce((n,d)=>n+(d.comments||0),0)),G=I(v,["placesCount","total_places"],$.length),Q=I(N,["placesCount","total_places"],U.length),F=H-se,X=_-k,le=G-Q,ee=({n,label:d})=>N&&n>0?e.jsxs("span",{className:"ml-1 inline-flex items-center px-1.5 py-0.5 rounded-full bg-emerald-500/20 border border-emerald-400/40 text-emerald-200 text-[10px] font-semibold",children:["+",n," new ",d]}):null,o=n=>{const d=U.find(c=>(c.name||c.group)===n);return d&&d.comments||0};return e.jsx(Je,{open:s,onOpenChange:a,children:e.jsxs(Ke,{className:"overflow-y-auto bg-[#0F2A4D] border-white/10 text-[#E6EDF3]",children:[e.jsx(Ye,{children:e.jsx(He,{className:"text-white",children:"Listing stats"})}),e.jsxs("div",{className:"flex gap-3 items-start",children:[e.jsx("div",{className:"w-28 h-20 rounded-md overflow-hidden bg-black/40 shrink-0",children:r?e.jsx("img",{src:r,alt:"",className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-xs text-[#9FB3C8]",children:"No image"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"text-sm font-medium text-white truncate",children:[i==null?void 0:i.year," ",i==null?void 0:i.make," ",i==null?void 0:i.model," ",(i==null?void 0:i.trim)||""]}),e.jsxs("div",{className:"text-xs text-[#9FB3C8] truncate",children:["VIN ",(i==null?void 0:i.vin)||"—"," · Stk ",(i==null?void 0:i.stock_number)||"—"]}),e.jsx(Fe,{to:`/marketplace360/inventory/${i==null?void 0:i.id}`,className:"text-xs text-[#2F80ED] hover:underline",onClick:()=>a(!1),children:"View full details →"})]})]}),S?e.jsxs("div",{className:"flex items-center justify-center py-6 text-[#9FB3C8] text-sm",children:[e.jsx(ce,{className:"h-4 w-4 animate-spin mr-2"})," Loading…"]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"text-xs font-semibold uppercase tracking-wide text-[#9FB3C8]",children:"Facebook listing stats"}),R&&e.jsxs("span",{className:"text-[10px] text-[#9FB3C8] whitespace-nowrap",children:["imported ",R]})]}),v?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(K,{variant:"outline",className:"border-[#2F80ED]/40 text-[#E6EDF3]",children:["Listed in ",G," places",e.jsx(ee,{n:le,label:"places"})]}),e.jsxs(K,{variant:"outline",className:"border-[#2F80ED]/40 text-[#E6EDF3]",children:[H," marketplace clicks",e.jsx(ee,{n:F,label:"clicks"})]}),e.jsxs(K,{variant:"outline",className:"border-[#2F80ED]/40 text-[#E6EDF3]",children:[_," total comments",e.jsx(ee,{n:X,label:"comments"})]})]}),N&&A&&(F>0||X>0||le>0)&&e.jsxs("div",{className:"text-[10px] text-emerald-300/80",children:["Changes since last import (",A,")"]}),$.length>0&&e.jsxs("details",{className:"text-xs",children:[e.jsxs("summary",{className:"cursor-pointer text-[#B8C7D9] py-1",children:["▾ Per-group breakdown (",$.length,")"]}),e.jsx("div",{className:"mt-1 max-h-48 overflow-y-auto divide-y divide-white/5",children:$.map((n,d)=>{const c=n.name||n.group||"—",x=n.comments??0,D=x-o(c);return e.jsxs("div",{className:"flex justify-between py-1",children:[e.jsx("span",{className:"text-[#E6EDF3] truncate pr-2",children:c}),e.jsxs("span",{className:"text-[#9FB3C8] shrink-0",children:[x," comments",N&&D>0&&e.jsxs("span",{className:"ml-1 text-emerald-300",children:["+",D]})]})]},d)})})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[(m==null?void 0:m.fb_listing_url)&&e.jsxs("a",{href:m.fb_listing_url,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-[#2F80ED] hover:underline inline-flex items-center gap-1",children:["Open on Facebook ",e.jsx(dt,{className:"h-3 w-3"})]}),e.jsxs("span",{className:"text-[10px] text-[#9FB3C8] inline-flex items-center gap-1",children:[e.jsx(is,{className:"h-3 w-3"})," Re-import from the Facebook listing modal to refresh."]})]})]}):e.jsx("div",{className:"text-xs text-[#9FB3C8]",children:'No Facebook stats yet. Open the listing in Facebook and click "Import stats".'})]}),u&&e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsx("div",{className:"text-xs font-semibold uppercase tracking-wide text-[#9FB3C8]",children:"eBay stats"}),g?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(K,{variant:"outline",className:"border-amber-500/40 text-[#E6EDF3]",children:["Status: ",g.status||"—"]}
3),e.jsxs(K,{variant:"outline",className:"border-amber-500/40 text-[#E6EDF3]",children:[g.view_count??g.views??0," views"]}),e.jsxs(K,{variant:"outline",className:"border-amber-500/40 text-[#E6EDF3]",children:[g.watch_count??g.watchers??0," watchers"]})]}),g.listing_url&&e.jsxs("a",{href:g.listing_url,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-[#2F80ED] hover:underline inline-flex items-center gap-1",children:["View on eBay ",e.jsx(dt,{className:"h-3 w-3"})]})]}):e.jsx("div",{className:"text-xs text-[#9FB3C8]",children:"Not listed on eBay yet."})]}),b&&e.jsxs("div",{className:"rounded-lg border border-white/10 bg-black/20 p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"text-xs font-semibold uppercase tracking-wide text-[#9FB3C8]",children:"CarGurus shopper demand"}),b.window_start&&b.window_end&&e.jsxs("span",{className:"text-[10px] text-[#9FB3C8] whitespace-nowrap",children:[b.window_start," – ",b.window_end]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(K,{variant:"outline",className:"border-[#2F80ED]/40 text-[#E6EDF3]",children:[b.vdp_views??0," detail page views"]}),e.jsxs(K,{variant:"outline",className:"border-[#2F80ED]/40 text-[#E6EDF3]",children:[b.srp_views??0," search appearances"]}),e.jsxs(K,{variant:"outline",className:"border-[#2F80ED]/40 text-[#E6EDF3]",children:[b.leads_total??0," inquiries"]}),(b.srp_views??0)>0&&e.jsxs(K,{variant:"outline",className:"border-[#2F80ED]/40 text-[#E6EDF3]",children:[((b.vdp_views??0)/b.srp_views*100).toFixed(1),"% click-through"]})]}),b.lead_breakdown&&Object.keys(b.lead_breakdown).length>0&&e.jsx("div",{className:"text-[11px] text-[#9FB3C8]",children:Object.entries(b.lead_breakdown).map(([n,d])=>`${n.replace(/_/g," ")}: ${d}`).join(" · ")})]})]}),e.jsx("div",{className:"flex justify-end mt-2",children:e.jsx(L,{variant:"outline",onClick:()=>a(!1),children:"Close"})})]})})}function te(s){if(s==null)return null;const a=String(s).trim();return a===""?null:a}function os(s){if(s==null||s==="")return null;const a=typeof s=="number"?s:Number(String(s).replace(/[^0-9.\-]/g,""));return Number.isFinite(a)?a:null}function ze(s){const a=os(s);return a==null?null:Math.round(a)}function aa(s){var i;const a=(i=te(s))==null?void 0:i.toUpperCase();return a?a==="N"||a==="NEW"?"new":a==="U"||a==="USED"?"used":a==="C"||a==="CERTIFIED"?"certified":a.toLowerCase():null}function ia(s){const a=te(s.Features),i=te(s["Photo Url List"]),r=s.Certified,u=r===1||r===!0||typeof r=="string"&&["1","true","yes","y"].includes(r.trim().toLowerCase()),m=aa(s["New/Used"]);return{vin:te(s.VIN),stock_number:te(s["Stock #"]),condition:u?"certified":m,year:ze(s.Year),make:te(s.Make),model:te(s.Model),trim:te(s.Series),body_style:te(s.Body)||te(s["Style Description"]),transmission:te(s.Transmission),engine:te(s.Engine),fuel_type:te(s.Fuel),drivetrain:te(s["Drivetrain Desc"]),mileage:ze(s.Odometer),exterior_color:te(s.Colour),interior_color:te(s["Interior Color"]),price:os(s.Price),certified_status:u,description:te(s.Description),features:a?a.split("|").map(p=>p.trim()).filter(Boolean):null,mpg_city:ze(s["City MPG"]),mpg_highway:ze(s["Highway MPG"]),vehicle_url:te(s["VDP Data"]),photo_urls:i?i.split("|").map(p=>p.trim()).filter(Boolean).slice(0,20):[]}}function ra({open:s,onOpenChange:a,onComplete:i}){const{toast:r}=xt(),[u,m]=l.useState(null),[p,g]=l.useState(!1),[f,b]=l.useState(0),[C,S]=l.useState(null),[B,v]=l.useState(null),[N,$]=l.useState(!0),[U,R]=l.useState(!1),A=l.useRef(null);l.useEffect(()=>{s&&(async()=>{const _=await Ce();if(!_){v(null);return}const{data:k}=await j.from("m360_settings").select("default_doc_fee_amount").eq("dealership_id",_).maybeSingle(),G=Number(k==null?void 0:k.default_doc_fee_amount);v(Number.isFinite(G)&&G>0?G:null)})()},[s]);function I(_){if(!_)return;const k=_.name.toLowerCase();if(!k.endsWith(".xlsx")&&!k.endsWith(".xls")){r({title:"Unsupported file",description:"Drop an .xlsx or .xls file.",variant:"destructive"});return}m(_),S(null)}async function H(){var _;if(u){g(!0),S(null),b(5);try{const k=await Ce();if(!k){r({title:"No dealership selected",variant:"destructive"}),g(!1);return}let G=[];try{const o=await u.arrayBuffer(),n=Gs(o,{type:"array"}),d=(_=n.SheetNames)==null?void 0:_[0];if(!d)throw new Error("Workbook has no sheets");const c=n.Sheets[d];if(!c)throw new Error(`Sheet "${d}" is empty`);G=Xs.sheet_to_json(c,{defval:null})}catch(o){r({title:"Could not read spreadsheet",description:(o==null?void 0:o.message)||"The file isn't a valid .xlsx/.xls workbook.",variant:"destructive"}),g(!1),b(0);return}b(15);const Q=G.map(ia).filter(o=>!!o.vin);if(Q.length===0){r({title:"No rows with a VIN found",variant:"destructive"}),g(!1),b(0);return}const F={added:0,updated:0,skipped:G.length-Q.length,photosInserted:0,flagged:0,errors:[]},X=200,le=Math.ceil(Q.length/X);for(let o=0;o<le;o++){const n=Q.slice(o*X,(o+1)*X);try{const{data:d,error:c}=await j.functions.invoke("m360-xlsx-import",{body:{dealership_id:k,rows:n}});if(c)F.errors.push({error:`batch ${o+1}
3: ${c.message||String(c)}`});else if(d&&(F.added+=d.added||0,F.updated+=d.updated||0,F.skipped+=d.skipped||0,F.photosInserted+=d.photosInserted||0,Array.isArray(d.errors)))for(const x of d.errors)F.errors.push({vin:x==null?void 0:x.vin,error:typeof(x==null?void 0:x.error)=="string"?x.error:JSON.stringify((x==null?void 0:x.error)??x)})}catch(d){F.errors.push({error:`batch ${o+1}: ${(d==null?void 0:d.message)||String(d)}`})}b(15+Math.round((o+1)/le*75))}let ee=0;if(N){const o=Array.from(new Set(Q.map(n=>String(n.vin||"").trim().toUpperCase()).filter(Boolean)));try{const{data:n,error:d}=await j.functions.invoke("m360-mark-missing-sold",{body:{dealership_id:k,present_vins:o}});if(d)F.errors.push({error:`flag missing: ${d.message||String(d)}`});else if(n){F.flagged=n.flagged||0;const c=Array.isArray(n.flagged_vehicle_ids)?n.flagged_vehicle_ids:[];if(c.length)try{const{data:x}=await j.functions.invoke("m360-check-sold-alerts",{body:{dealership_id:k,vehicle_ids:c}});ee=Number((x==null?void 0:x.alerts_created)||0)}catch{}}}catch(n){F.errors.push({error:`flag missing: ${(n==null?void 0:n.message)||String(n)}`})}}b(100),S(F),r({title:"Import complete",description:`${F.added} added, ${F.updated} updated, ${F.flagged||0} flagged for sold review`}),ee>0&&r({title:`${ee} likely-sold vehicle${ee===1?"":"s"} still live on Facebook`,description:"Open Sold Alerts to review and remove the Marketplace listings."}),i==null||i()}catch(k){r({title:"Import failed",description:(k==null?void 0:k.message)||String(k),variant:"destructive"})}finally{g(!1)}}}function se(){p||(m(null),b(0),S(null),a(!1))}return e.jsx(Je,{open:s,onOpenChange:_=>{_?a(!0):se()},children:e.jsxs(Ke,{className:"",children:[e.jsxs(Ye,{children:[e.jsx(He,{children:"Import inventory from XLSX"}),e.jsxs(pt,{children:["Drop your AutoLeadStar (or similar) inventory export. Matches by VIN. Existing vehicles are updated in place (photos preserved). New vehicles get up to 20 photos from ",e.jsx("code",{children:"Photo Url List"}),"."]})]}),e.jsxs("div",{className:"space-y-3",children:[B!=null?e.jsxs("div",{className:"rounded border border-emerald-400/20 bg-emerald-400/5 px-3 py-2 text-xs text-emerald-100",children:["Listing price will include this dealership's documentation fee — ",e.jsxs("span",{className:"font-medium",children:["$",B.toFixed(2)]})," added to each vehicle's file price."]}):e.jsx("div",{className:"rounded border border-amber-400/20 bg-amber-400/5 px-3 py-2 text-xs text-amber-100",children:'No documentation fee configured. Set one in Marketplace360 → Settings → "Default doc fee disclosure" so the listing price is all-in.'}),e.jsxs("div",{onClick:()=>{var _;return!p&&((_=A.current)==null?void 0:_.click())},onDragOver:_=>{_.preventDefault(),p||R(!0)},onDragLeave:()=>R(!1),onDrop:_=>{var G;if(_.preventDefault(),R(!1),p)return;const k=((G=_.dataTransfer.files)==null?void 0:G[0])||null;I(k)},className:`rounded-lg border-2 border-dashed px-4 py-8 text-center cursor-pointer transition ${U?"border-[#2F80ED] bg-[#2F80ED]/10":u?"border-emerald-400/40 bg-emerald-400/5":"border-white/15 bg-black/25 hover:bg-black/30"} ${p?"opacity-60 pointer-events-none":""}`,children:[e.jsx("input",{ref:A,type:"file",accept:".xlsx,.xls",disabled:p,onChange:_=>{var k;return I(((k=_.target.files)==null?void 0:k[0])||null)},className:"hidden"}),u?e.jsxs("div",{className:"flex items-center justify-center gap-2 text-sm text-[#E6EDF3]",children:[e.jsx(Qs,{className:"h-5 w-5 text-emerald-300"}),e.jsx("span",{className:"font-medium",children:u.name}),e.jsxs("span",{className:"text-[#9FB3C8]",children:["· ",(u.size/1024).toFixed(0)," KB"]})]}):e.jsxs("div",{className:"space-y-1",children:[e.jsx(ut,{className:"h-6 w-6 mx-auto text-[#9FB3C8]"}),e.jsx("div",{className:"text-sm text-[#E6EDF3]",children:"Drag & drop your XLSX here"}),e.jsx("div",{className:"text-xs text-[#9FB3C8]",children:"or click to browse (.xlsx, .xls)"})]})]}),e.jsxs("label",{className:"flex items-start gap-2 cursor-pointer",children:[e.jsx(ot,{checked:N,onCheckedChange:_=>$(_===!0),disabled:p,className:"mt-0.5"}),e.jsxs("span",{className:"text-xs text-[#B8C7D9] leading-snug",children:["Mark vehicles missing from this file as ",e.jsx("span",{className:"text-white",children:"likely sold"}),". They move to the Sold Review tab so an admin can confirm. Turn off for partial files."]})]}),p&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(rs,{value:f}),e.jsxs("div",{className:"text-xs text-[#9FB3C8]",children:["Importing… ",f,"%"]})]}),C&&e.jsxs("div",{className:"rounded border border-white/10 bg-black/25 p-3 text-sm text-[#E6EDF3] space-y-1",children:[e.jsxs("div",{children:["Added: ",e.jsx("span",{className:"font-medium",children:C.added})]}),e.jsxs("div",{children:["Updated: ",e.jsx("span",{className:"font-medium",children:C.updated})]}),e.jsxs("div",{children:["Skipped (no VIN): ",e.jsx("span",{className:"font-medium",children:C.skipped})]}),e.jsxs("div",{children:["Photos inserted: ",e.jsx("span",{className:"font-medium",children:C.photosInserted})]}),N&&e.jsxs("div",{children:["Flagged as likely sold: ",e.jsx("span",{className:"font-medium",children:C.flagged||0})]}),C.errors.length>0&&e.jsxs("details",{className:"pt-1",children:[e.jsxs("summary",{className:"cursor-pointer text-[#9FB3C8]",children:[C.errors.length," error(s)"]}),e.jsx("ul",{className:"mt-1 max-h-40 overflow-auto text-xs text-[#9FB3C8] list-disc pl-5",children:C.errors.slice(0,50).map((_,k)=>e.jsxs("li",{children:[_!=null&&_.vin?`${_.vin}
3: `:"",typeof(_==null?void 0:_.error)=="string"?_.error:JSON.stringify((_==null?void 0:_.error)??_)]},k))})]})]})]}),e.jsxs(as,{children:[e.jsx(L,{variant:"outline",onClick:se,disabled:p,children:"Close"}),e.jsxs(L,{onClick:H,disabled:!u||p,className:"bg-gradient-to-r from-[#2F80ED] to-[#1C5ED6] text-white border-0",children:[p?e.jsx(ce,{className:"h-4 w-4 mr-1.5 animate-spin"}):e.jsx(ut,{className:"h-4 w-4 mr-1.5"}),"Start import"]})]})]})})}const cs=["year","make","model","trim","trim_detail","condition","price","mileage","exterior_color","interior_color","body_style","transmission","drivetrain","engine","fuel_type","doors","description","features","options","photo_urls"];function Re(s){return Array.isArray(s)?s.map(Re).filter(a=>a!==null&&a!==""):typeof s=="string"?s.trim():s??null}function na(s,a){return s?cs.filter(i=>{const r=i==="photo_urls"?(a.m360_vehicle_images||[]).slice().sort((u,m)=>u.sort_order-m.sort_order).filter(u=>u.selected_for_post!==!1).map(u=>u.url):a[i];return JSON.stringify(Re(s[i]))!==JSON.stringify(Re(r))}):[]}function la(s,a,i){return!(i!=null&&i.listing_snapshot)||!a?!1:s.every(r=>{const u=r.field;return JSON.stringify(Re(i.listing_snapshot[u]))===JSON.stringify(Re(a[u]))})}function Ge(s){return s==null?"—":`$${Number(s).toLocaleString(void 0,{maximumFractionDigits:0})}`}function Zt(s){return s==null?"—":`${Number(s).toLocaleString()} mi`}function oa({mode:s,dealershipId:a,vehicleType:i,onCountChange:r}){const{toast:u}=xt(),[m,p]=l.useState(!0),[g,f]=l.useState([]),[b,C]=l.useState(""),[S,B]=l.useState([]),[v,N]=l.useState({}),[$,U]=l.useState(new Set),[R,A]=l.useState({}),[I,H]=l.useState(null),[se,_]=l.useState([]),[k,G]=l.useState({});l.useEffect(()=>{s!=="since_import"||!a||(async()=>{var d;const{data:o}=await j.from("m360_import_jobs").select("id,started_at,completed_at,success_count").eq("dealership_id",a).order("started_at",{ascending:!1}).limit(10),n=o||[];if(f(n),n.length&&!b){const{data:c}=await j.from("m360_vehicle_changes").select("import_job_id").eq("dealership_id",a).in("import_job_id",n.map(D=>D.id)),x=new Set((c||[]).map(D=>D.import_job_id));C(((d=n.find(D=>x.has(D.id)))==null?void 0:d.id)||n[0].id)}})()},[s,a]),l.useEffect(()=>{s!=="since_import"||!a||!b||(async()=>{p(!0);const{data:o}=await j.from("m360_vehicle_changes").select("id,vehicle_id,import_job_id,field,old_value,new_value,numeric_delta,changed_at").eq("dealership_id",a).eq("import_job_id",b).order("changed_at",{ascending:!1}),n=o||[];B(n);const d=Array.from(new Set(n.map(c=>c.vehicle_id)));if(d.length){const{data:c}=await j.from("m360_vehicles").select("*, m360_vehicle_images(url,sort_order,selected_for_post)").in("id",d),x={};(c||[]).forEach(q=>{x[q.id]=q}),N(x);const{data:D}=await j.from("m360_post_records").select("id,vehicle_id,user_id,posted_at,facebook_listing_url,listing_snapshot,notes,updated_at").in("vehicle_id",d).in("status",["posted","live_confirmed"]).order("posted_at",{ascending:!1}),Y={};(D||[]).forEach(q=>{Y[q.vehicle_id]||(Y[q.vehicle_id]={id:q.id,vehicle_id:q.vehicle_id,user_id:q.user_id,posted_at:q.posted_at,facebook_listing_url:q.facebook_listing_url,listing_snapshot:q.listing_snapshot??null})}),A(Y),U(new Set(Object.keys(Y)));const w=Array.from(new Set(Object.values(Y).map(q=>q.user_id).filter(Boolean)));if(w.length){const{data:q}=await j.from("registration_users").select("id,name,username,email").in("id",w),J={};(q||[]).forEach(O=>{J[O.id]=O.name||O.username||O.email||"Unknown"}),G(J)}}else N({}),U(new Set),A({});p(!1)})()},[s,a,b]),l.useEffect(()=>{s!=="since_posted"||!a||(async()=>{p(!0);const{data:o}=await j.from("m360_post_records").select("vehicle_id,user_id,posted_at,listed_price,posted_mileage,facebook_listing_url,status,listing_snapshot").eq("dealership_id",a).in("status",["posted","live_confirmed"]).not("posted_at","is",null).order("posted_at",{ascending:!1}).limit(2e3),n=new Map;for(const w of o||[])n.has(w.vehicle_id)||n.set(w.vehicle_id,{vehicle_id:w.vehicle_id,user_id:w.user_id,posted_at:w.posted_at,listed_price:w.listed_price,posted_mileage:w.posted_mileage,facebook_listing_url:w.facebook_listing_url,listing_snapshot:w.listing_snapshot});const d=Array.from(n.keys());if(d.length===0){_([]),p(!1);return}const{data:c}=await j.from("m360_vehicles").select("*, m360_vehicle_images(url,sort_order,selected_for_post)").in("id",d),x={};
3(c||[]).forEach(w=>{x[w.id]=w}),N(x);const D=[];n.forEach(w=>{const q=x[w.vehicle_id];if(!q)return;const J=w.listed_price!=null&&q.price!=null&&Number(w.listed_price)!==Number(q.price),O=w.posted_mileage!=null&&q.mileage!=null&&Number(w.posted_mileage)!==Number(q.mileage),ae=na(w.listing_snapshot,q);(J||O||ae.length>0)&&D.push({...w,changed_fields:ae})}),D.sort((w,q)=>q.posted_at.localeCompare(w.posted_at)),_(D);const Y=Array.from(new Set(D.map(w=>w.user_id).filter(Boolean)));if(Y.length){const{data:w}=await j.from("registration_users").select("id,name,username,email").in("id",Y),q={};(w||[]).forEach(J=>{q[J.id]=J.name||J.username||J.email||"Unknown"}),G(q)}p(!1)})()},[s,a]);const Q=o=>ht(o,i),F=l.useMemo(()=>{if(s!=="since_import")return[];const o=new Map;for(const n of S)o.has(n.vehicle_id)||o.set(n.vehicle_id,[]),o.get(n.vehicle_id).push(n);return Array.from(o.entries()).filter(([n])=>Q(v[n])).filter(([n,d])=>!la(d,v[n],R[n])).map(([n,d])=>({vehicle_id:n,rows:d}))},[S,s,i,v,R]),X=l.useMemo(()=>se.filter(o=>Q(v[o.vehicle_id])),[se,i,v]);l.useEffect(()=>{r==null||r(s==="since_import"?F.length:X.length)},[X.length,F.length,s]);async function le(o){const n=R[o];if(n){H(o);try{const{data:d,error:c}=await j.from("m360_vehicles").select("*, m360_vehicle_images(url,sort_order,selected_for_post)").eq("id",o).maybeSingle();if(c)throw c;if(!d)throw new Error("Vehicle not found");const x=d,D=(x.m360_vehicle_images||[]).slice().sort((O,ae)=>O.sort_order-ae.sort_order).filter(O=>O.selected_for_post!==!1).map(O=>O.url),Y={};cs.forEach(O=>{Y[O]=O==="photo_urls"?D:x[O]??null});const w=n.user_id?k[n.user_id]:null,q=`Reconciled with feed${w?` (posted by ${w})`:""} on ${new Date().toLocaleString()}`,{error:J}=await j.from("m360_post_records").update({listing_snapshot:Y,listed_price:x.price??null,posted_mileage:x.mileage??null,notes:q}).eq("id",n.id);if(J)throw J;A(O=>({...O,[o]:{...O[o],listing_snapshot:Y}})),u({title:"Marked as updated on Facebook — removed from this list"})}catch(d){u({title:"Failed",description:(d==null?void 0:d.message)||"Could not save",variant:"destructive"})}finally{H(null)}}}async function ee(o){const{error:n}=await j.from("m360_vehicles").update({marketplace_status:"needs_repost"}).eq("id",o);if(n){u({title:"Failed",description:n.message,variant:"destructive"});return}u({title:"Marked for repost"}),_(d=>d.filter(c=>c.vehicle_id!==o))}return m?e.jsxs("div",{className:"flex items-center gap-2 text-[#9FB3C8] text-sm",children:[e.jsx(ce,{className:"h-4 w-4 animate-spin"}),"Loading…"]}):s==="since_import"?e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsx("span",{className:"text-xs text-[#9FB3C8]",children:"Import:"}),e.jsxs(ve,{value:b,onValueChange:o=>C(o),children:[e.jsx(ye,{className:"w-72 bg-black/25 border-white/10 text-[#E6EDF3]",children:e.jsx(Ne,{placeholder:"Select an import"})}),e.jsx(ke,{children:g.map(o=>e.jsxs(ne,{value:o.id,children:[new Date(o.started_at).toLocaleString()," · ",o.success_count," rows"]},o.id))})]}),e.jsxs("span",{className:"text-xs text-[#9FB3C8]",children:[F.length," vehicles changed"]})]}),F.length===0?e.jsx(Se,{className:"p-8 bg-white/[0.03] border-white/10 text-center text-[#9FB3C8]",children:"No price or mileage changes detected for this import."}):e.jsxs(Se,{className:"bg-white/[0.03] border-white/10 overflow-hidden",children:[e.jsxs("div",{className:"grid grid-cols-12 gap-2 px-4 py-2 text-[10px] uppercase tracking-wide text-[#9FB3C8] border-b border-white/10",children:[e.jsx("div",{className:"col-span-4",children:"Vehicle"}),e.jsx("div",{className:"col-span-2",children:"Field"}),e.jsx("div",{className:"col-span-2",children:"Old"}),e.jsx("div",{className:"col-span-2",children:"New"}),e.jsx("div",{className:"col-span-2 text-right",children:"Δ"})]}),e.jsx("div",{className:"divide-y divide-white/5",children:F.map(({vehicle_id:o,rows:n})=>{const d=v[o],c=(d==null?void 0:d.availability_status)||"available",x=c==="sold",D=c==="pending_sold_review",Y=(x||D)&&((d==null?void 0:d.marketplace_status)==="removal_needed"||$.has(o)),w=R[o],q=!!w&&!x&&!D;return e.jsx("div",{className:"px-4 py-3",children:e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-12 gap-2 items-start",children:[e.jsxs("div",{className:"sm:col-span-4 min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 min-w-0",children:[e.jsx(Fe,{to:`/marketplace360/inventory/${o}`,className:"text-sm font-medium text-white hover:underline",children:d?`${d.year||""} ${d.make||""} ${d.model||""} ${d.trim||""}`.trim():o.slice(0,8)}),x&&e.jsx(K,{className:"text-[10px] uppercase tracking-wide bg-rose-500/20 text-rose-200 border border-rose-400/40",children:"Sold"}),D&&e.jsx(K,{className:"text-[10px] uppercase tracking-wide bg-orange-500/20 text-orange-200 border border-orange-400/40",children:"Pending sold review"}),Y&&e.jsx(K,{className:"text-[10px] uppercase tracking-wide bg-amber-500/20 text-amber-200 border border-amber-400/40",children:"Marketplace removal needed"}),q&&e.jsxs(K,{className:"text-[10px] uppercase tracking-wide bg-[#2F80ED]/20 text-[#9dc4ff] border border-[#2F80ED]/50",children:[e.jsx(Ee,{className:"h-2.5 w-2.5 mr-1"}),"Live on Marketplace"]})]}),e.jsxs("div",{className:"text-[11px] text-[#9FB3C8]",children:["Stk ",(d==null?void 0:d.stock_number)||"—"," · VIN ",(d==null?void 0:d.vin)||"—"]}
3),q&&e.jsxs("div",{className:"mt-1.5 space-y-1",children:[e.jsxs("div",{className:"text-[11px] text-[#9FB3C8]",children:["Posted ",w.posted_at?new Date(w.posted_at).toLocaleDateString():"—",w.user_id&&k[w.user_id]?` · ${k[w.user_id]}`:""]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[w.facebook_listing_url&&e.jsx(me,{componentId:"marketplace360:link-fb-listing",appName:"Marketplace360",componentType:"button",componentLabel:"View Facebook listing",children:e.jsx("a",{href:w.facebook_listing_url,target:"_blank",rel:"noopener noreferrer",children:e.jsxs(L,{size:"sm",variant:"outline",className:"h-7 text-[11px]",children:[e.jsx(dt,{className:"h-3 w-3 mr-1"}),"View on FB"]})})}),e.jsx(me,{componentId:"marketplace360:button-mark-fb-updated",appName:"Marketplace360",componentType:"button",componentLabel:"Mark updated on FB",children:e.jsxs(L,{size:"sm",onClick:()=>le(o),disabled:I===o,className:"h-7 text-[11px] bg-[#2F80ED] hover:bg-[#1C5ED6] text-white",children:[I===o?e.jsx(ce,{className:"h-3 w-3 mr-1 animate-spin"}):e.jsx(ss,{className:"h-3 w-3 mr-1"}),"Mark updated on FB"]})})]})]})]}),e.jsx("div",{className:"sm:col-span-8 space-y-1 min-w-0",children:n.map(J=>{const O=J.field==="price",ae=je=>je==null?"—":O?Ge(Number(je)):Number(je).toLocaleString(),pe=J.numeric_delta,_e=pe!=null&&pe>0;return e.jsxs("div",{className:"grid grid-cols-4 sm:grid-cols-8 gap-2 text-xs",children:[e.jsx("div",{className:"col-span-2",children:e.jsx(K,{variant:"outline",className:"text-[10px] capitalize",children:J.field})}),e.jsx("div",{className:"col-span-2 text-[#B8C7D9]",children:ae(J.old_value)}),e.jsx("div",{className:"col-span-2 text-white",children:ae(J.new_value)}),e.jsx("div",{className:`col-span-2 text-right ${_e?"text-emerald-300":"text-rose-300"}`,children:pe!=null?e.jsxs("span",{className:"inline-flex items-center gap-1",children:[_e?e.jsx(As,{className:"h-3 w-3"}):e.jsx(Js,{className:"h-3 w-3"}),O?Ge(Math.abs(pe)):Math.abs(pe).toLocaleString()]}):"—"})]},J.id)})})]})},o)})})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"text-xs text-[#9FB3C8]",children:[X.length," posted ",X.length===1?"vehicle":"vehicles"," with customer-visible information that changed after being posted."]}),X.length===0?e.jsx(Se,{className:"p-8 bg-white/[0.03] border-white/10 text-center text-[#9FB3C8]",children:"No posted vehicles with stale information. Complete listing snapshots are captured for every new post."}):e.jsxs(Se,{className:"bg-white/[0.03] border-white/10 overflow-hidden",children:[e.jsxs("div",{className:"hidden md:grid grid-cols-12 gap-2 px-4 py-2 text-[10px] uppercase tracking-wide text-[#9FB3C8] border-b border-white/10",children:[e.jsx("div",{className:"col-span-3",children:"Vehicle"}),e.jsx("div",{className:"col-span-2",children:"Posted"}),e.jsx("div",{className:"col-span-2",children:"Listed → Current"}),e.jsx("div",{className:"col-span-2",children:"Miles → Current"}),e.jsx("div",{className:"col-span-1",children:"By"}),e.jsx("div",{className:"col-span-2 text-right",children:"Actions"})]}),e.jsx("div",{className:"divide-y divide-white/5",children:X.map(o=>{var x;const n=v[o.vehicle_id],d=o.listed_price!=null&&(n==null?void 0:n.price)!=null&&Number(o.listed_price)!==Number(n.price),c=o.posted_mileage!=null&&(n==null?void 0:n.mileage)!=null&&Number(o.posted_mileage)!==Number(n.mileage);return e.jsxs("div",{className:"grid grid-cols-12 gap-2 px-4 py-3 items-center text-sm",children:[e.jsxs("div",{className:"col-span-12 md:col-span-3",children:[e.jsx(Fe,{to:`/marketplace360/inventory/${o.vehicle_id}`,className:"font-medium text-white hover:underline",children:n?`${n.year||""} ${n.make||""} ${n.model||""}`.trim():o.vehicle_id.slice(0,8)}),e.jsxs("div",{className:"text-[11px] text-[#9FB3C8]",children:["Stk ",(n==null?void 0:n.stock_number)||"—"]}),!!((x=o.changed_fields)!=null&&x.length)&&e.jsxs("div",{className:"text-[11px] text-amber-200 mt-1",children:["Changed: ",o.changed_fields.map(D=>D.replace(/_/g," ")).join(", ")]}),!o.listing_snapshot&&e.jsx("div",{className:"text-[11px] text-[#9FB3C8] mt-1",children:"Legacy post: only price and mileage c
3an be compared."})]}),e.jsx("div",{className:"col-span-6 md:col-span-2 text-xs text-[#B8C7D9]",children:new Date(o.posted_at).toLocaleDateString()}),e.jsxs("div",{className:`col-span-6 md:col-span-2 text-xs ${d?"text-amber-200":"text-[#9FB3C8]"}`,children:[Ge(o.listed_price)," ",e.jsx("span",{className:"text-[#9FB3C8]",children:"→"})," ",Ge((n==null?void 0:n.price)??null)]}),e.jsxs("div",{className:`col-span-6 md:col-span-2 text-xs ${c?"text-amber-200":"text-[#9FB3C8]"}`,children:[Zt(o.posted_mileage)," ",e.jsx("span",{className:"text-[#9FB3C8]",children:"→"})," ",Zt((n==null?void 0:n.mileage)??null)]}),e.jsx("div",{className:"col-span-6 md:col-span-1 text-xs text-[#B8C7D9] truncate",children:o.user_id&&k[o.user_id]||"—"}),e.jsxs("div",{className:"col-span-12 md:col-span-2 flex items-center justify-end gap-2",children:[o.facebook_listing_url&&e.jsx("a",{href:o.facebook_listing_url,target:"_blank",rel:"noopener noreferrer",children:e.jsxs(L,{size:"sm",variant:"outline",className:"h-7",children:[e.jsx(ct,{className:"h-3 w-3 mr-1"}),"FB"]})}),e.jsxs(L,{size:"sm",onClick:()=>ee(o.vehicle_id),className:"h-7 bg-[#2F80ED] hover:bg-[#1C5ED6] text-white",children:[e.jsx(ns,{className:"h-3 w-3 mr-1"}),"Repost"]})]})]},o.vehicle_id)})})]})]})}const ca={already_authored:"Already has a description you wrote or generated earlier (skip option is on)"},da=new Set(["mobile_ai","user","inventory_ai"]);function ds(s){const a=(s.description_source||"").trim();return da.has(a)&&!!(s.description||"").trim()}const be={seoMode:!0,tone:"friendly",length:"standard",useEmojis:!1,skipExisting:!0};async function ua(s){try{const a=await Me();if(!(a!=null&&a.id))return{...be};let i=j.from("m360_user_settings").select("allow_emojis, ai_tone, ai_length").eq("user_id",a.id);s&&(i=i.eq("dealership_id",s));const{data:r}=await i.limit(1).maybeSingle();return r?{...be,tone:r.ai_tone||be.tone,length:r.ai_length||be.length,useEmojis:!!r.allow_emojis}:{...be}}catch{return{...be}}}const ma="dealership_id, updated_at, ai_equipment_focus, ai_must_include, ai_custom_rules, ai_cta, ai_avoid, ai_required_phrases";function es(s){return(Array.isArray(s)?s:[]).map(i=>{if(typeof i=="string")return{text:i,placement:"anywhere",exact:!0};const r=typeof(i==null?void 0:i.text)=="string"?i.text:"",u=(i==null?void 0:i.placement)==="start"||(i==null?void 0:i.placement)==="end"?i.placement:"anywhere";return{text:r,placement:u,exact:(i==null?void 0:i.exact)!==!1}}).filter(i=>(i.text||"").trim().length>0).slice(0,20)}async function ft(s){const a={requiredPhrases:[]};try{const i=await Me();if(!(i!=null&&i.id))return a;const{data:r}=await j.from("m360_user_settings").select(ma).eq("user_id",i.id).order("updated_at",{ascending:!1}).limit(20),u=r||[];if(!u.length)return a;const m=s&&u.find(p=>p.dealership_id===s)||u.find(p=>es(p.ai_required_phrases).length>0)||u[0];return{equipmentFocus:m.ai_equipment_focus!==!1,mustInclude:m.ai_must_include??null,customRules:m.ai_custom_rules??null,cta:m.ai_cta??null,avoid:m.ai_avoid??null,requiredPhrases:es(m.ai_required_phrases)}}catch{return a}}const Qe=s=>s.toLowerCase().replace(/\s+/g," ").trim();function ha(s,a,i){if(!a.length||!s.trim())return s;let r=s;const u=f=>Qe(r).includes(Qe(f)),m=a.filter(f=>f.exact!==!1&&f.placement==="start"&&!u(f.text));m.length&&(r=`${m.map(f=>f.text.trim()).join(`
4
5`)}
6
7${r}`);const p=a.filter(f=>f.exact!==!1&&(f.placement??"anywhere")==="anywhere"&&!u(f.text));if(p.length){const f=p.map(S=>S.text.trim()).join(`
8
9`),b=(i||"").trim(),C=b?r.lastIndexOf(b):-1;r=C>=0?`${r.slice(0,C).replace(/\s+$/,"")}
10
11${f}
12
13${r.slice(C)}`:`${r.replace(/\s+$/,"")}
14
15${f}`}const g=a.filter(f=>f.exact!==!1&&f.placement==="end"&&!u(f.text));return g.length&&(r=`${r.replace(/\s+$/,"")}
16
17${g.map(f=>f.text.trim()).join(`
18
19`)}`),r}function pa(s,a){const i=(s||"").trim();if(!i||!a.length)return!1;const r=Qe(i);return a.some(u=>u.exact!==!1&&!r.includes(Qe(u.text)))}async function xa(s){const a=await ft(s.dealershipId);if(!a.requiredPhrases.length||!s.vehicleIds.length)return{updated:0,checked:0,phrases:a.requiredPhrases.length};const{data:i,error:r}=await j.from("m360_vehicles").select("id, description").in("id",s.vehicleIds.slice(0,500));if(r)throw r;const u=i||[];let m=0;for(const p of u){if(!pa(p.description,a.requiredPhrases))continue;const g=ha(String(p.description||""),a.requiredPhrases,a.cta);if(g===p.description)continue;const{error:f}=await j.from("m360_vehicles").update({description:g,description_source:"inventory_ai"}).eq("id",p.id);f||m++}return{updated:m,checked:u.length,phrases:a.requiredPhrases.length}}async function fa(s){var u;const a=(s==null?void 0:s.context)instanceof Response?s.context:void 0,i=Number((a==null?void 0:a.status)??((u=s==null?void 0:s.context)==null?void 0:u.status)??(s==null?void 0:s.status)??0);let r=(s==null?void 0:s.message)||"Request failed";try{if(a){const m=await a.clone().text();try{const p=JSON.parse(m),g=(p==null?void 0:p.error)||(p==null?void 0:p.message);g&&(r=String(g))}catch{m.trim()&&(r=m.trim().slice(0,300))}}}catch{}return{status:i,message:r}}function ga(s,a){return s===402||s===403?!0:s>=400&&/insufficient credit|credits|payment required|forbidden|not enabled|disabled/i.test(a)}async function _a(){try{const s=await Me();if(!(s!=null&&s.id))return{allowed:!0};const{data:a}=await j.from("platform_admins").select("is_active").eq("user_id",s.id).eq("is_active",!0).maybeSingle();if(a)return{allowed:!0};const{data:i}=await j.from("m360_user_settings").select("access_status, trial_ends_at, ai_descriptions_enabled").eq("user_id",s.id).limit(1).maybeSingle(),r=i;return(r==null?void 0:r.access_status)==="active"||(r==null?void 0:r.access_status)==="trial"&&(!(r!=null&&r.trial_ends_at)||new Date(r.trial_ends_at).getTime()>Date.now())?r!=null&&r.ai_descriptions_enabled?{allowed:!0}:{allowed:!1,reason:"AI descriptions aren't enabled for your account — ask an admin to enable it in Marketplace360 → Users."}:{allowed:!1,reason:"Your Marketplace360 access is disabled. Ask an admin."}}catch{return{allowed:!0}}}async function ba(s,a,i){const{data:r,error:u}=await j.from("m360_vehicles").select("*").eq("id",s).maybeSingle();if(u||!r)throw new Error((u==null?void 0:u.message)||"Vehicle not found");const{data:m,error:p}=await j.functions.invoke("m360-generate-description",{body:{vehicle:r,vehicle_id:s,dealership_id:r.dealership_id,organization_id:r.organization_id,mode:a.seoMode?"seo":"standard",persist:!0,useEmojis:a.useEmojis,style:{tone:a.tone,length:a.length,equipmentFocus:i.equipmentFocus!==!1,mustInclude:i.mustInclude??void 0,customRules:i.customRules??void 0,cta:i.cta??void 0,avoid:i.avoid??void 0,requiredPhrases:i.requiredPhrases}}});if(p){const{status:b,message:C}=await fa(p),S=new Error(C);throw S.httpStatus=b,S}const g=String((m==null?void 0:m.description)||"").trim();if(!g)throw new Error("AI returned an empty description");const{error:f}=await j.from("m360_vehicles").update({description:g,description_source:"inventory_ai"}).eq("id",s);if(f)throw f;return g}async function ja(s){const{error:a}=await j.rpc("m360_queue_vehicle",{_vehicle_id:s});if(a)throw a}async function wa(s){const{vehicles:a,step:i,options:r,onProgress:u,onVehicleDone:m,shouldCancel:p}=s,g=Math.max(1,Math.min(s.concurrency,5)),f={generated:0,queued:0,skipped:0,skips:[],failures:[]},b=i==="generate_and_queue"?await ft(s.dealershipId??null):{requiredPhrases:[]},C=[...a],S=C.length;let B=0;const v=async()=>{for(;C.length;){if(f.halted||p!=null&&p())return;const N=C.shift();if(!N)return;try{i==="generate_and_queue"&&(r.skipExisting&&ds(N)?(f.skips.push({id:N.id,label:N.label,reason:"already_authored"}),f.skipped=f.skips.length):(await ba(N.id,r,b),f.generated++)),await ja(N.id),f.queued++,m==null||m(N.id,"queued")}catch($){const U=($==null?void 0:$.message)||String($);if(ga(Number(($==null?void 0:$.httpStatus)??0),U)){f.halted=U,m==null||m(N.id,"failed");return}f.failures.push({id:N.id,label:N.label,error:U}),m==null||m(N.id,"failed")}finally{B++,u==null||u(B,S,N.label)}}};return await Promise.all(Array.from({length:Math.min(g,S)},v)),f}const va=["friendly","professional","enthusiastic","concise","luxury"],ya=["short","standard","detailed"];function Na({open:s,onOpenChange:a,vehicles:i,dealershipId:r,step:u,onQueued:m,onFinished:p}){var d;const[g,f]=l.useState({...be}),[b,C]=l.useState(!1),[S,B]=l.useState({done:0,total:0,label:""}),[v,N]=l.useState(null),[$,U]=l.useState(!1),[R,A]=l.useState(null),[I,H]=l.useState(null),[se,_]=l.useState([]),[k,G]=l.useState(!1),Q=l.useRef(!1);l.useEffect(()=>{s&&(N(null),U(!1),A(null),B({done:0,total:0,label:""}),Q.current=!1,ua(r).then(f),ft(r).then(c=>_(c.requiredPhrases)),u==="generate_and_queue"?_a().then(c=>H(c.allowed?null:c.reason||"AI descriptions are not available for your account.")):H(null))},[s,r,u]);const F=R??i,X=l.useMemo(()=>u==="generate_and_queue"&&g.skipExisting?F.filter(ds).length:0,[F,g.skipExisting,u]);async function le(c){if(c.length===0)return;Q.current=!1,C(!0),N(null),U(!1),B({done:0,total:c.length,label:""});const x=await wa({vehicles:c,step:u,options:g,concurrency:3,onProgress:(D,Y,
19w)=>B({done:D,total:Y,label:w}),onVehicleDone:(D,Y)=>{Y==="queued"&&m(D)},shouldCancel:()=>Q.current,dealershipId:r});C(!1),N(x),A(x.failures.length?x.failures.map(D=>({id:D.id,label:D.label})):null),x.halted?de.error("AI generation stopped",{description:x.halted}):x.failures.length===0&&de.success(u==="queue_only"?`${x.queued} vehicle${x.queued===1?"":"s"} queued`:`${x.generated} generated · ${x.queued} queued`),p==null||p()}async function ee(){G(!0);try{const c=await xa({vehicleIds:F.map(x=>x.id),dealershipId:r});c.updated===0?de.success("All selected vehicles already include your required wording"):de.success(`Required wording added to ${c.updated} description${c.updated===1?"":"s"}`),p==null||p()}catch(c){de.error("Could not add required wording",{description:(c==null?void 0:c.message)||String(c)})}finally{G(!1)}}const o=u==="generate_and_queue",n=S.total?Math.round(S.done/S.total*100):0;return e.jsx(Je,{open:s,onOpenChange:c=>{!c&&b||a(c)},children:e.jsxs(Ke,{className:"max-w-2xl",children:[e.jsxs(Ye,{children:[e.jsxs(He,{className:"flex items-center gap-2",children:[o?e.jsx(mt,{className:"h-4 w-4"}):e.jsx(Ee,{className:"h-4 w-4"}),o?"Generate descriptions & queue":"Queue for posting"]}),e.jsxs(pt,{children:[F.length," vehicle",F.length===1?"":"s"," selected.",o?" Descriptions are written, saved, then each vehicle is added to your Chrome extension queue.":" Vehicles are added to your Chrome extension queue as-is."]})]}),e.jsxs("div",{className:"space-y-4",children:[o&&I&&e.jsxs("div",{className:"flex items-start gap-2 rounded-lg border border-amber-400/30 bg-amber-400/10 p-3 text-xs text-amber-200",children:[e.jsx(Ot,{className:"h-3.5 w-3.5 mt-0.5 shrink-0"}),e.jsx("span",{children:I})]}),o&&e.jsxs("div",{className:"space-y-3 rounded-lg border border-white/10 bg-white/[0.03] p-3",children:[e.jsxs("div",{className:"flex flex-wrap items-end gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(nt,{id:"bulk-seo",checked:g.seoMode,disabled:b,onCheckedChange:c=>f(x=>({...x,seoMode:c}))}),e.jsx(he,{htmlFor:"bulk-seo",className:"text-xs text-[#B8C7D9]",children:"SEO mode"})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs text-[#9FB3C8]",children:"Tone"}),e.jsx("select",{value:g.tone,disabled:b,onChange:c=>f(x=>({...x,tone:c.target.value})),className:"block bg-black/25 border border-white/10 rounded px-2 py-1.5 text-sm text-[#E6EDF3]",children:va.map(c=>e.jsx("option",{value:c,children:c},c))})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs text-[#9FB3C8]",children:"Length"}),e.jsx("select",{value:g.length,disabled:b,onChange:c=>f(x=>({...x,length:c.target.value})),className:"block bg-black/25 border border-white/10 rounded px-2 py-1.5 text-sm text-[#E6EDF3]",children:ya.map(c=>e.jsx("option",{value:c,children:c},c))})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(nt,{id:"bulk-emoji",checked:g.useEmojis,disabled:b,onCheckedChange:c=>f(x=>({...x,useEmojis:c}))}),e.jsx(he,{htmlFor:"bulk-emoji",className:"text-xs text-[#B8C7D9]",children:"Emojis"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(nt,{id:"bulk-skip",checked:g.skipExisting,disabled:b,onCheckedChange:c=>f(x=>({...x,skipExisting:c}))}),e.jsxs(he,{htmlFor:"bulk-skip",className:"text-xs text-[#B8C7D9]",children:["Skip vehicles that already have an AI/user-written description",X>0&&e.jsxs("span",{className:"text-[#9FB3C8]",children:[" (",X," would be skipped)"]})]})]}),se.length>0&&e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 rounded-lg border border-white/10 bg-black/20 p-2.5",children:[e.jsxs("span",{className:"text-xs text-[#9FB3C8]",children:["Your required wording (",se.length," phrase",se.length===1?"":"s",") is included in every description. Already-written descriptions can be patched without using AI."]}),e.jsx(me,{componentId:"marketplace360:button-backfill-required-wording",appName:"Marketplace360",componentType:"button",componentLabel:"Add missing required wording",children:e.jsxs(L,{type:"button",size:"sm",variant:"outline",disabled:b||k||F.length===0,onClick:()=>void ee(),children:[k&&e.jsx(ce,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),"Add missing required wording"]})})]})]}),b&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(rs,{value:n}),e.jsxs("div",{className:"text-xs text-[#9FB3C8]",children:[S.done," of ",S.total," processed",S.label?` · ${S.label}`:""]})]}),v&&e.jsxs("div",{className:"space-y-2 rounded-lg border border-white/10 bg-white/[0.03] p-3 text-sm",children:[e.jsxs("div",{className:"text-[#E6EDF3]",children:[o&&e.jsxs(e.Fragment,{children:["Generated ",v.generated," · "]}),"Queued ",v.queued,v.skipped>0&&e.jsxs(e.Fragment,{children:[" · ",e.jsx(me,{componentId:"marketplace360:button-skipped-detail
19s",appName:"Marketplace360",componentType:"button",componentLabel:"Show why vehicles were skipped",children:e.jsxs("button",{type:"button",onClick:()=>U(c=>!c),className:"underline underline-offset-2 text-amber-200 hover:text-amber-100","aria-expanded":$,children:["Skipped ",v.skipped]})})]}),v.failures.length>0&&e.jsxs(e.Fragment,{children:[" · Failed ",v.failures.length]})]}),$&&(((d=v.skips)==null?void 0:d.length)??0)>0&&e.jsx("div",{className:"max-h-40 overflow-y-auto space-y-1 text-xs text-amber-200/90",children:v.skips.map(c=>e.jsxs("div",{children:[c.label," — ",ca[c.reason]||"Skipped"]},c.id))}),v.halted&&e.jsxs("div",{className:"flex items-start gap-2 text-amber-300 text-xs",children:[e.jsx(Ot,{className:"h-3.5 w-3.5 mt-0.5"})," Run stopped: ",v.halted]}),v.failures.length>0&&e.jsx("div",{className:"max-h-40 overflow-y-auto space-y-1 text-xs text-red-300",children:v.failures.map(c=>e.jsxs("div",{children:[c.label," — ",c.error]},c.id))})]}),e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[b?e.jsx(L,{variant:"outline",onClick:()=>{Q.current=!0},children:"Cancel run"}):e.jsxs(e.Fragment,{children:[e.jsx(L,{variant:"outline",onClick:()=>a(!1),children:"Close"}),e.jsx(L,{onClick:()=>void le(F),disabled:F.length===0||o&&!!I,title:o&&I?I:void 0,className:"bg-gradient-to-r from-[#2F80ED] to-[#1C5ED6] text-white",children:v?R?`Retry ${R.length} failed`:"Run again":o?e.jsxs(e.Fragment,{children:[e.jsx(mt,{className:"h-3.5 w-3.5 mr-1.5"})," Generate & queue ",F.length]}):e.jsxs(e.Fragment,{children:[e.jsx(Ee,{className:"h-3.5 w-3.5 mr-1.5"})," Queue ",F.length]})})]}),b&&e.jsxs("span",{className:"inline-flex items-center text-xs text-[#9FB3C8]",children:[e.jsx(ce,{className:"h-3 w-3 mr-1 animate-spin"})," working…"]})]})]})]})})}const ka=[{value:"any",label:"Any CarGurus demand"},{value:"hot",label:"Trending on CarGurus"},{value:"boost",label:"Seen but skipped"},{value:"cold",label:"No CarGurus traffic"}
19],Sa={hot:"Trending",boost:"Seen but skipped",cold:"No traffic",none:"No data"},Ca={hot:"bg-emerald-500/15 text-emerald-200 border-emerald-400/30",boost:"bg-amber-500/15 text-amber-200 border-amber-400/30",cold:"bg-white/10 text-[#9FB3C8] border-white/15",none:"bg-white/10 text-[#9FB3C8] border-white/15"};function Fa(s){const a=s.map(r=>r.vdp_views).filter(r=>r>0).sort((r,u)=>r-u);if(a.length===0)return 1/0;const i=Math.floor(a.length*.8);return Math.max(1,a[Math.min(i,a.length-1)])}function Ea(s,a){if(!s)return"none";const{vdp_views:i,srp_views:r}=s;return i===0&&r===0?"none":i>=a?"hot":i===0?"cold":r>=25&&i/r<.02?"boost":"cold"}const Da=s=>{const a={};for(const i of s)i.vin&&(a[i.vin.toUpperCase()]=i);return a},Xe=[{value:"all",label:"All vehicles"},{value:"unposted_me",label:"Not yet posted"},{value:"posted_any",label:"Already posted"},{value:"in_my_queue",label:"In my queue"},{value:"posted_by_me",label:"Posted by me"},{value:"needs_repost",label:"Needs repost"},{value:"sold",label:"Sold"},{value:"removal_needed",label:"Removal needed"}],Ba=new Set(["sent_to_extension","in_progress","posted","live_confirmed","needs_repost","price_changed","removal_needed","removed"]),ts=["active","sold_review","sold","changed_since_import","changed_since_posted"];function ii(){const[s,a]=l.useState([]),[i,r]=l.useState({}),[u,m]=l.useState({}),[p,g]=l.useState(new Set),[f,b]=l.useState(new Set),[C,S]=l.useState(new Set),[B,v]=l.useState(new Set),[N,$]=l.useState(null),[U,R]=l.useState(new Set),[A,I]=l.useState(!0),[H,se]=l.useState(""),[_]=Bs(),k=_.get("status"),G=!!k&&Xe.some(t=>t.value===k),[Q,F]=l.useState(G?k:"all"),[X,le]=l.useState("all"),[ee,o]=l.useState("all"),[n,d]=l.useState(!1),[c,x]=l.useState(!1),[D,Y]=l.useState({}),[w,q]=l.useState("any"),[J,O]=l.useState(!1);l.useEffect(()=>{const t=_.get("status");t&&Xe.some(y=>y.value===t)&&F(t);const h=_.get("tab");h&&ts.includes(h)&&jt(h)},[_]);const[ae,pe]=l.useState(null),[_e,je]=l.useState(!1),[Te,gt]=l.useState(null),[us,_t]=l.useState(!1),[bt,De]=l.useState(0),We=_.get("tab"),[z,jt]=l.useState(We&&ts.includes(We)?We:"active"),[ms,Ze]=l.useState(!1),[Ie,wt]=l.useState(!1),[vt,yt]=l.useState(!1),[Be,hs]=l.useState(null),[Nt,ps]=l.useState(null),[ue,xs]=l.useState(null),[Oe,fs]=l.useState({import:null,posted:null}),[xe,et]=l.useState(new Set),[kt,tt]=l.useState(null),gs=t=>et(h=>{const y=new Set(h);return y.has(t)?y.delete(t):y.add(t),y}),St=()=>et(new Set),{toast:W}=xt(),{isSalespersonMode:st,canUsePrivileged:_s}=Ys();l.useEffect(()=>{J||(async()=>{try{const t=await Me();if(!(t!=null&&t.id)){O(!0);return}const{data:h}=await j.from("m360_user_settings").select("default_inventory_status, default_inventory_condition, default_inventory_posted_by, default_inventory_min_photos_10").eq("user_id",t.id).maybeSingle();h&&(!G&&h.default_inventory_status&&Xe.some(y=>y.value===h.default_inventory_status)&&F(h.default_inventory_status),h.default_inventory_condition&&le(h.default_inventory_condition),h.default_inventory_posted_by&&o(h.default_inventory_posted_by),d(!!h.default_inventory_min_photos_10))}catch{}O(!0)})()},[]),l.useEffect(()=>{(async()=>{var Tt;const[t,h]=await Promise.all([Ce(),Me()]);if(!t){I(!1);return}hs(t);const{data:y}=await j.from("m360_sftp_feeds").select("last_run_at,last_run_status,last_run_message,last_file_name,last_file_modified_at").eq("dealership_id",t).maybeSingle();xs(y);const E=(h==null?void 0:h.id)??null,[V,ie,Z,fe,T,M]=await Promise.all([j.from("m360_vehicles").select("*, m360_vehicle_images(url, sort_order)").eq("dealership_id",t).order("created_at",{ascending:!1}).limit(1e3),j.from("m360_post_records").select("vehicle_id,posted_at,status,user_id").eq("dealership_id",t).not("posted_at","is",null),j.from("ebay_accounts").select("id").eq("dealership_id",t).eq("status","active").order("connected_at",{ascending:!1}).limit(1).maybeSingle(),j.from("ebay_listings").select("vehicle_id,status").eq("dealership_id",t).eq("status","active"),E?j.from("m360_posting_queue").select("vehicle_id,status").eq("dealership_id",t).eq("assigned_user_id",E).in("status",["queued","in_progress"]):Promise.resolve({data:[]}),j.from("m360_posting_queue").select("vehicle_id").eq("dealership_id",t).in("status",["queued","in_progress"])]);$(((Tt=Z.data)==null?void 0:Tt.id)||null);const ge=new Set;for(const P of fe.data||[])P.vehicle_id&&ge.add(P.vehicle_id);R(ge),a(V.data||[]);const{data:qe}=await j.from("m360_vehicles").select("last_seen_at").eq("dealership_id",t).not("last_seen_at","is",null).order("last_seen_at",{ascending:!1}).limit(1).maybeSingle();ps((qe==null?void 0:qe.last_seen_at)??null);const Ve=new Set;for(const P of T.data||[])P.vehicle_id&&Ve.add(P.vehicle_id);g(Ve);const Ue=new Set;for(const P of M.data||[])P.vehicle_id&&Ue.add(P.vehicle_id);v(Ue);const $e={},we={},Ae=new Set,Lt=new Set;for(const P of ie.data||[]){if(!P.vehicle_id||!P.posted_at)continue;const oe=$e[P.vehicle_id];(!oe||P.posted_at<oe)&&($e[P.vehicle_id]=P.posted_at);const It=we[P.vehicle_id];(!It||P.posted_at>It.posted_at)&&(we[P.vehicle_id]={user_id:P.user_id||null,posted_at:P.posted_at}),Lt.add(P.vehicle_id),E&&P.user_id===E&&P.status==="posted"&&Ae.add(P.vehicle_id)}r($e),b(Ae),S(Lt);const Mt=Array.from(new Set(Object.values(we).map(P=>
19P.user_id).filter(Boolean)));let rt={};if(Mt.length){const{data:P}=await j.from("registration_users").select("id,name,username,email").in("id",Mt);for(const oe of P||[])rt[oe.id]=oe.name||oe.username||oe.email||"Unknown"}const Rt={};for(const[P,oe]of Object.entries(we))oe.user_id&&rt[oe.user_id]&&(Rt[P]={userId:oe.user_id,name:rt[oe.user_id]});m(Rt),I(!1)})()},[bt]),l.useEffect(()=>{if(!Be)return;let t=!1;return(async()=>{const{data:h}=await j.from("m360_cargurus_vin_stats").select("vin,vdp_views,srp_views,leads_total,lead_breakdown,window_start,window_end").eq("dealership_id",Be);t||Y(Da(h||[]))})(),()=>{t=!0}},[Be,bt]);const Ct=l.useMemo(()=>Fa(Object.values(D)),[D]),Ft=t=>Ea(t?D[String(t).toUpperCase()]:void 0,Ct),bs=Object.keys(D).length>0,js=l.useMemo(()=>{const t=new Map;return Object.values(u).forEach(h=>t.set(h.userId,h.name)),Array.from(t.entries()).map(([h,y])=>({userId:h,name:y})).sort((h,y)=>h.name.localeCompare(y.name))},[u]),Et=l.useMemo(()=>s.filter(t=>t.availability_status==="available"),[s]),Dt=l.useMemo(()=>s.filter(t=>t.availability_status==="pending_sold_review").sort((t,h)=>String(h.pending_sold_at||"").localeCompare(String(t.pending_sold_at||""))),[s]),Bt=l.useMemo(()=>s.filter(t=>t.availability_status==="sold"||t.availability_status==="pending_sold_review"&&t.marketplace_status==="removal_needed").sort((t,h)=>String(h.sold_detected_at||"").localeCompare(String(t.sold_detected_at||""))),[s]),at=t=>ht(t,X),ws=Et.filter(at).length,qt=Dt.filter(at).length,vs=Bt.filter(at).length,it=z==="active"?Et:z==="sold"?Bt:Dt,re=l.useMemo(()=>it.filter(t=>{var ie;if(H&&!`${t.year} ${t.make} ${t.model} ${t.vin} ${t.stock_number}`.toLowerCase().includes(H.toLowerCase())||!ht(t,X))return!1;const h=p.has(t.id),y=f.has(t.id),E=C.has(t.id)||B.has(t.id)||h||y||Ba.has(String(t.marketplace_status||"")),V=t.marketplace_status==="sold"||t.availability_status==="sold";switch(Q){case"all":if(z==="active"&&V)return!1;break;case"unposted_me":if(E||z==="active"&&V)return!1;break;case"posted_any":if(!E)return!1;break;case"in_my_queue":if(!h)return!1;break;case"posted_by_me":if(!y)return!1;break;case"needs_repost":if(t.marketplace_status!=="needs_repost")return!1;break;case"sold":if(t.marketplace_status!=="sold")return!1;break;case"removal_needed":if(t.marketplace_status!=="removal_needed")return!1;break;default:if(t.marketplace_status!==Q)return!1}if(z==="active"){if(ee==="unposted"){if(u[t.id])return!1}else if(ee!=="all"&&((ie=u[t.id])==null?void 0:ie.userId)!==ee)return!1;const Z=(t.m360_vehicle_images||[]).length;if(n&&Z<10||c&&Z>=5||w!=="any"&&Ft(t.vin)!==w)return!1}return!0}),[it,H,Q,X,ee,u,z,p,f,C,B,n,c,w,D,Ct]),ys=l.useMemo(()=>re.filter(t=>xe.has(t.id)).map(t=>({id:t.id,label:`${t.year||""} ${t.make||""} ${t.model||""}`.trim()+(t.stock_number?` (Stk ${t.stock_number})`:""),description:t.description,description_source:t.description_source})),[re,xe]),Ns=re.length>0&&re.every(t=>xe.has(t.id));async function ks(t){const{error:h}=await j.from("m360_vehicles").update({availability_status:"sold",marketplace_status:"sold",pending_sold_at:null}).eq("id",t);if(h){W({title:"Failed",description:h.message,variant:"destructive"});return}a(y=>y.map(E=>E.id===t?{...E,availability_status:"sold",marketplace_status:"sold",pending_sold_at:null}:E)),W({title:"Marked as sold"}),Pt([t])}async function $t(t){const h=s.find(V=>V.id===t),y={availability_status:"available",pending_sold_at:null,sold_detected_at:null};(h==null?void 0:h.marketplace_status)==="sold"&&(y.marketplace_status="not_ready");const{error:E}=await j.from("m360_vehicles").update(y).eq("id",t);if(E){W({title:"Failed",description:E.message,variant:"destructive"});return}a(V=>V.map(ie=>ie.id===t?{...ie,...y}:ie)),W({title:"Restored to active inventory"})}async function At(t){if(t.length===0)return!1;const{error:h}=await j.from("m360_vehicles").update({marketplace_status:"removed"}).in("id",t);return h?(W({title:"Failed",description:h.message,variant:"destructive"}),!1):(await j.from("m360_post_records").update({status:"removed",removed_at:new Date().toISOString()}).in("vehicle_id",t).in("status",["posted","live_confirmed","removal_needed"]),await j.from("m360_alerts").update({status:"resolved"}).in("vehicle_id",t).eq("alert_type","sold_needs_removal").eq("status","open"),a(y=>y.map(E=>t.includes(E.id)?{...E,marketplace_status:"removed"}:E)),!0)}async function Ss(t){await At([t])&&W({title:"Marked removed from Marketplace"})}async function Cs(){const t=re.filter(h=>h.marketplace_status==="removal_needed").map(h=>h.id);t.length!==0&&await At(t)&&W({title:`${t.length} vehicles marked removed`})}async function Fs(){const t=re.map(y=>y.id);if(t.length===0)return;const{error:h}=await j.from("m360_vehicles").update({availability_status:"sold",marketplace_status:"sold",pen
19ding_sold_at:null}).in("id",t);if(h){W({title:"Failed",description:h.message,variant:"destructive"});return}a(y=>y.map(E=>t.includes(E.id)?{...E,availability_status:"sold",marketplace_status:"sold",pending_sold_at:null}:E)),W({title:`${t.length} vehicles marked sold`}),Pt(t)}async function Pt(t){try{const h=await Ce();if(!h||t.length===0)return;const{data:y}=await j.functions.invoke("m360-check-sold-alerts",{body:{dealership_id:h,vehicle_ids:t}}),E=Number((y==null?void 0:y.alerts_created)||0);E>0&&W({title:`${E} vehicle${E===1?"":"s"} still live on Facebook`,description:"Open Sold Alerts to remove the Marketplace listing."})}catch{}}async function Es(){wt(!0);try{const t=await Ce();if(!t)throw new Error("No dealership selected");const{data:h,error:y}=await j.functions.invoke("m360-clear-inventory",{body:{dealership_id:t}});if(y)throw y;a([]),m({}),r({}),W({title:"Inventory cleared",description:`${(h==null?void 0:h.deleted)??0} vehicles deleted.`}),Ze(!1),De(E=>E+1)}catch(t){W({title:"Clear failed",description:(t==null?void 0:t.message)||String(t),variant:"destructive"})}finally{wt(!1)}}async function Ds(){var t;yt(!0);try{const h=await Ce();if(!h)throw new Error("No dealership selected");const{data:y,error:E}=await j.from("m360_sftp_feeds").select("id, enabled").eq("dealership_id",h).order("created_at",{ascending:!1}).limit(1).maybeSingle();if(E)throw E;if(!y){W({title:"No vAuto SFTP feed configured",description:"Add the feed in Marketplace360 → Settings first.",variant:"destructive"});return}if(!y.enabled){W({title:"SFTP feed is disabled",description:"Enable the vAuto feed in Marketplace360 → Settings.",variant:"destructive"});return}const{data:V,error:ie}=await j.functions.invoke("m360-sftp-sync",{body:{feed_id:y.id,force:!0}});if(ie)throw ie;if(V!=null&&V.started){W({title:"Sync started",description:"Vehicles will update over the next few minutes."}),setTimeout(()=>De(fe=>fe+1),6e4);return}const Z=(t=V==null?void 0:V.results)==null?void 0:t[0];if(!(Z!=null&&Z.ok))throw new Error((Z==null?void 0:Z.error)||(V==null?void 0:V.error)||"Sync failed");W({title:"Inventory refreshed from vAuto",description:`${Z.added??0} added · ${Z.updated??0} updated · ${Z.changes_detected??0} changed · ${Z.sent_to_sold_review??0} sold review · ${Z.restored??0} restored`}),De(fe=>fe+1)}catch(h){W({title:"Refresh failed",description:(h==null?void 0:h.message)||String(h),variant:"destructive"})}finally{yt(!1)}}return e.jsxs("div",{className:"p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-3",children:[e.jsxs("div",{className:"flex items-baseline gap-3 flex-wrap",children:[e.jsx("h1",{className:"text-2xl font-semibold text-[#E6EDF3]",children:"Inventory"}),Nt&&e.jsxs("span",{className:"text-sm text-[#9FB3C8]",children:["Refreshed: ",new Date(Nt).toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})]}),ue&&e.jsxs("span",{className:`text-xs ${ue.last_run_status==="error"?"text-red-300":"text-[#9FB3C8]"}`,children:["Last check ",ue.last_run_at?new Date(ue.last_run_at).toLocaleString():"—",ue.last_file_name?` · ${ue.last_file_name}`:"",ue.last_file_modified_at?` · file ${new Date(ue.last_file_modified_at).toLocaleString()}`:"",ue.last_run_message?` · ${ue.last_run_message}`:""]})]}),e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsxs("div",{className:"text-sm text-[#9FB3C8]",children:[re.length," of ",it.length]}),_s&&e.jsxs(e.Fragment,{children:[e.jsx(me,{componentId:"marketplace360:button-sftp-refresh",appName:"marketplace360",componentType:"button",componentLabel:"Refresh from vAuto",defaultRole:"user",children:e.jsx(L,{size:"sm",variant:"outline",onClick:Ds,disabled:vt,className:"bg-white/[0.03] border-white/10 text-[#E6EDF3] hover:bg-white/[0.06]",children:vt?e.jsxs(e.Fragment,{children:[e.jsx(ce,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"})," Refreshing…"]}):e.jsxs(e.Fragment,{children:[e.jsx(is,{className:"h-3.5 w-3.5 mr-1.5"})," Refresh from vAuto"]})})}),e.jsxs(L,{size:"sm",variant:"outline",onClick:()=>_t(!0),className:"bg-white/[0.03] border-white/10 text-[#E6EDF3] hover:bg-white/[0.06]",children:[e.jsx(ut,{className:"h-3.5 w-3.5 mr-1.5"})," Import XLSX"]}),e.jsxs(L,{size:"sm",variant:"outline",onClick:()=>Ze(!0),className:"bg-red-500/10 border-red-500/30 text-red-200 hover:bg-red-500/20 hover:text-red-100",children:[e.jsx(Ps,{className:"h-3.5 w-3.5 mr-1.5"})," Clear Inventory"]})]})]})]}),e.jsx(Ts,{value:z,onValueChange:t=>jt(t),children:e.jsxs(Is,{className:"bg-white/[0.03] border border-white/10 flex-wrap h-auto",children:[e.jsxs(Pe,{value:"active",children:["Active (",
19ws,")"]}),e.jsxs(Pe,{value:"sold_review",children:["Sold Review (",qt,")",qt>0&&e.jsx(K,{className:"ml-2 bg-amber-500/20 text-amber-200 border-amber-500/30",children:"Needs review"})]}),e.jsxs(Pe,{value:"sold",children:["Sold (",vs,")"]}),e.jsxs(Pe,{value:"changed_since_import",children:["Changed (last import)",Oe.import!==null?` (${Oe.import})`:""]}),e.jsxs(Pe,{value:"changed_since_posted",children:["Posted — info changed",Oe.posted!==null?` (${Oe.posted})`:""]})]})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-[#9FB3C8]",children:"Vehicle type"}),e.jsxs(ve,{value:X,onValueChange:le,children:[e.jsx(ye,{className:"w-36 bg-black/25 border-white/10","aria-label":"Vehicle type",children:e.jsx(Ne,{})}),e.jsxs(ke,{children:[e.jsx(ne,{value:"all",children:"All"}),e.jsx(ne,{value:"new",children:"New"}),e.jsx(ne,{value:"used",children:"Used"}),e.jsx(ne,{value:"certified",children:"Certified"}),e.jsx(ne,{value:"value",children:"Value"})]})]})]}),(z==="changed_since_import"||z==="changed_since_posted")&&e.jsx(oa,{mode:z==="changed_since_import"?"since_import":"since_posted",dealershipId:Be,vehicleType:X,onCountChange:t=>fs(h=>({...h,[z==="changed_since_import"?"import":"posted"]:t}))}),(z==="active"||z==="sold_review"||z==="sold")&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(Ls,{placeholder:"Search VIN, stock, make, model…",value:H,onChange:t=>se(t.target.value),className:"max-w-xs bg-black/25 border-white/10"}),e.jsxs(ve,{value:Q,onValueChange:F,children:[e.jsx(ye,{className:"w-48 bg-black/25 border-white/10",children:e.jsx(Ne,{})}),e.jsx(ke,{children:Xe.map(t=>e.jsx(ne,{value:t.value,children:t.label},t.value))})]}),Q!=="all"&&e.jsx(L,{size:"sm",variant:"outline",onClick:()=>F("all"),className:"bg-white/[0.03] border-white/10",children:"Clear filter"}),z==="active"&&e.jsxs(e.Fragment,{children:[e.jsxs(ve,{value:ee,onValueChange:o,children:[e.jsx(ye,{className:"w-56 bg-black/25 border-white/10",children:e.jsx(Ne,{placeholder:"Posted by"})}),e.jsxs(ke,{children:[e.jsx(ne,{value:"all",children:"Posted by — All users"}),e.jsx(ne,{value:"unposted",children:"Not yet posted"}),js.map(t=>e.jsx(ne,{value:t.userId,children:t.name},t.userId))]})]}),e.jsxs(ve,{value:n?"10plus":c?"under5":"any",onValueChange:t=>{d(t==="10plus"),x(t==="under5")},children:[e.jsx(ye,{className:"w-44 bg-black/25 border-white/10",children:e.jsx(Ne,{})}),e.jsxs(ke,{children:[e.jsx(ne,{value:"any",children:"Any photo count"}),e.jsx(ne,{value:"10plus",children:"10+ photos only"}),e.jsx(ne,{value:"under5",children:"Light on photos (under 5)"})]})]}),bs&&e.jsxs(ve,{value:w,onValueChange:t=>q(t),children:[e.jsx(ye,{className:"w-56 bg-black/25 border-white/10",children:e.jsx(Ne,{})}),e.jsx(ke,{children:ka.map(t=>e.jsx(ne,{value:t.value,children:t.label},t.value))})]})]}),z==="sold"&&re.some(t=>t.marketplace_status==="removal_needed")&&e.jsx(me,{componentId:"marketplace360:button-mark-all-removed",appName:"marketplace360",componentType:"button",componentLabel:"Mark all removed",defaultRole:"user",children:e.jsxs(L,{size:"sm",variant:"outline",onClick:Cs,className:"bg-emerald-500/10 border-emerald-500/30 text-emerald-200 hover:bg-emerald-500/20",children:[e.jsx(Le,{className:"h-3.5 w-3.5 mr-1.5"})," Mark all removed"]})}),z==="sold_review"&&re.length>0&&e.jsxs(L,{size:"sm",variant:"outline",onClick:Fs,className:"bg-emerald-500/10 border-emerald-500/30 text-emerald-200 hover:bg-emerald-500/20",children:[e.jsx(Le,{className:"h-3.5 w-3.5 mr-1.5"})," Confirm all sold"]})]}),z==="active"&&re.length>0&&e.jsxs("div",{className:`flex flex-wrap items-center gap-3 rounded-lg border px-3 py-2 ${st?"border-[#2F80ED]/40 bg-[#2F80ED]/10":"border-white/10 bg-white/[0.03]"}`,children:[st&&e.jsx("span",{className:"text-xs font-medium text-[#E6EDF3]",children:"Recommended: select vehicles, then generate descriptions & queue"}),e.jsxs("label",{className:"inline-flex items-center gap-2 text-xs text-[#B8C7D9] cursor-pointer",children:[e.jsx(ot,{checked:Ns,onCheckedChange:t=>{t?et(new Set(re.map(h=>h.id))):St()},"aria-label":"Select all filtered vehicles"}),"Select all filtered (",re.length,")"]}),xe.size>0&&e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"text-xs text-[#9FB3C8]",children:[xe.size," selected"]}),e.jsx(me,{componentId:"marketplace360:button-bulk-generate-queue",appName:"marketplace360",componentType:"button",componentLabel:"Bulk generate descriptions & queue",defaultRole:"user",children:e.jsxs(L,{size:"sm",onClick:()=>tt("generate_and_queue"),className:"bg-gradient-to-r from-[#2F80ED] to-[#1C5ED6] text-white border-0",children:[e.jsx(mt,{className:"h-3.5 w-3.5 mr-1.5"})," Generate descriptions & queue"]})}),e.jsx(me,{componentId:"marketplace360:button-bulk-queue-only",appName:"marketplace360",componentType:"button",componentLabel:"Bulk queue only",defaultRole:"user",children:e.jsxs(L,{size:"sm",variant:"outline",onClick:()=>tt("queue_only"),className:"bg-white/[0.03] border-white/10 text-[#E6EDF3] hover:bg-white/[0.06]",children:[e.jsx(Ee,{className:"h-3.5 w-3.5 mr-1.5"})," Queue only"]})}),e.jsxs(L,{size:"sm",variant:"ghost",onClick:St,className:"text-[#9FB3C8] hover:text-[#E6EDF3]",children:[e.jsx(Vt,{className:"h-3.5 w-3.5 mr-1"})," Clear"]})]}),xe.size===0&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-[#9FB3C8]",children:[e.jsx(Hs,{className:"h-3.5 w-3.5"})," Tick vehicles to bulk-generate AI descriptions and queue them"]})]}),A?e.jsxs("div",{className:"flex items-center gap-2 text-[#9FB3C8]",children:[e.jsx(ce,{className:"h-4 w-4 animate-spin"}),"Loading…"]}):re.length===0?e.jsx(Se,{className:"p-8 bg-white/[0.03] border-white/10 text-center text-[#9FB3C8]",children:z==="active"?e.jsxs(e.Fragment,{children:["No vehicles yet. Install the ",e.jsx(Fe,{to:"/marketplace360/extension",className:"text-[#2F80ED] underline",children:"Marketplace360 Chrome extension"})," and open your dealer's inventory pages — or import an XLSX above."]}):z==="sold"?e.jsx(e.Fragment,{children:"No sold or retired vehicles yet. Vehicles confirmed sold from the review queue show up here."}):e.jsx(e.Fragment,{children:"No vehicles waiting on sold review. Each daily vAuto import sends any vehicle missing from the file here for confirmation."})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3",children:re.map(t=>{var fe;const h=(fe=(t.m360_vehicle_images||[]).sort((T,M)=>T.sort_order-M.sort_order)[0])==null?void 0:fe.url,y=t.hero_processed_url||h,E=u[t.id],V=z==="sold_review",ie=z==="sold",Z=V||ie;return e.jsxs(Se,{className:`bg-white/[0.03] border-white/10 overflow-hidden group relative ${V?"ring-1 ring-amber-500/30":""} ${ie?"opacity-80":""} ${xe.has(t.id)?"ring-2 ring-[#2F80ED]":""}`,children:[z==="active"&&e.jsx("label",{className:"absolute top-2 left-2 z-10 inline-flex items-center justify-center h-7 w-7 rounded-md bg-black/60 cursor-pointer",onClick:T=>T.stopPropagation(),children:e.jsx(ot,{checked:xe.has(t.id),onCheckedChange:()=>gs(t.id),"aria-label":`Select ${t.year} ${t.make} ${t.model}`})}),!Z&&e.jsx("button",{type:"button","aria-label":"Remove vehicle",onClick:T=>{T.preventDefault(),T.stopPropagation(),pe(t)},className:"absolute top-2 right-2 z-10 h-7 w-7 inline-flex items-center justify-center rounded-full bg-black/60 text-white/80 opacity-70 hover:opacity-100 hover:bg-red-600 hover:text-white transition focus:outline-none focus:ring-2 focus:ring-red-500",children:e.jsx(Vt,{className:"h-4 w-4"})}),e.jsx("div",{className:"aspect-video bg-black/40 flex items-center justify-center",children:y?e.jsx("img",{src:y,alt:`${t.year} ${t.make} ${t.model}`,className:"w-full h-full object-cover"}):e.jsx("div",{className:"text-[#9FB3C8] text-xs",children:"No image"})}),e.jsxs("div",{className:"p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"text-sm font-medium text-white truncate",children:[t.year," ",t.make," ",t.model," ",t.trim||""]}),e.jsxs("div",{className:"text-xs text-[#9FB3C8] truncate",children:["VIN ",t.vin||"—"," · Stk ",t.stock_number||"—"]})]}),e.jsxs("div",{className:"flex flex-col items-end gap-1 shrink-0",children:[e.jsx(K,{variant:"outline",className:"text-[10px]",children:t.marketplace_status}),(()=>{const T=Ft(t.vin);if(T==="none")return null;const M=D[String(t.vin).toUpperCase()];return e.jsx(K,{className:`text-[10px] ${Ca[T]}`,title:`CarGurus: ${(M==null?void 0:M.vdp_views)??0} detail views · ${(M==null?void 0:M.srp_views)??0} search appearances · ${(M==null?void 0:M.leads_total)??0} inquiries`,children:Sa[T]})})(),t.dealer_name&&e.jsx(K,{variant:"outline",className:"text-[10px] max-w-[110px] truncate",title:t.dealer_name,children:t.dealer_name}),(t.certified_status||t.condition==="certified")&&e.jsx(K,{className:"text-[10px] bg-emerald-500/15 text-emerald-200 border-emerald-500/30",children:"Certified"})]})]}),e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsxs("span",{className:"text-white",children:["$",Number(t.price||0).toLocaleStr
19ing()]}),e.jsxs("span",{className:"text-[#9FB3C8]",children:[Number(t.mileage||0).toLocaleString()," mi"]})]}),V&&t.pending_sold_at&&e.jsxs("div",{className:"text-[11px] text-amber-200",children:["Missing since ",new Date(t.pending_sold_at).toLocaleDateString()]}),ie&&e.jsxs("div",{className:"text-[11px] text-[#9FB3C8]",children:["Sold ",t.sold_detected_at?new Date(t.sold_detected_at).toLocaleDateString():"—"]}),!Z&&(i[t.id]||E)&&e.jsxs("div",{className:"flex items-center justify-between text-[11px] pt-1 border-t border-white/5 gap-2",children:[i[t.id]&&e.jsxs("span",{className:"text-[#9FB3C8]",children:["Listed"," ",e.jsx("span",{className:"text-white",children:`${Math.floor((Date.now()-new Date(i[t.id]).getTime())/864e5)}d`})]}),E&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-[#9FB3C8] truncate",title:`Posted by ${E.name}`,children:[e.jsx(Ms,{className:"h-3 w-3"}),e.jsx("span",{className:"text-white truncate max-w-[110px]",children:E.name})]})]}),ie?e.jsxs("div",{className:"flex items-center justify-between gap-2 pt-1 flex-wrap",children:[e.jsx(Fe,{to:`/marketplace360/inventory/${t.id}`,children:e.jsxs(L,{size:"sm",variant:"outline",children:[e.jsx(ct,{className:"h-3.5 w-3.5 mr-1.5"}),"View"]}
19)}),e.jsxs("div",{className:"flex items-center gap-2",children:[t.marketplace_status==="removal_needed"&&e.jsx(me,{componentId:"marketplace360:button-mark-removed",appName:"marketplace360",componentType:"button",componentLabel:"Mark Removed",defaultRole:"user",children:e.jsxs(L,{size:"sm",onClick:()=>Ss(t.id),className:"bg-emerald-600 hover:bg-emerald-700 text-white border-0",children:[e.jsx(Le,{className:"h-3.5 w-3.5 mr-1.5"}),"Mark Removed"]})}),e.jsxs(L,{size:"sm",variant:"outline",onClick:()=>$t(t.id),className:"bg-white/[0.03] border-white/10 hover:bg-white/[0.08]",children:[e.jsx(Ut,{className:"h-3.5 w-3.5 mr-1.5"}),"Restore"]})]})]}):V?e.jsxs("div",{className:"flex items-center justify-between gap-2 pt-1",children:[e.jsxs(L,{size:"sm",variant:"outline",onClick:()=>$t(t.id),className:"bg-white/[0.03] border-white/10 hover:bg-white/[0.08]",children:[e.jsx(Ut,{className:"h-3.5 w-3.5 mr-1.5"}),"Restore"]}),e.jsxs(L,{size:"sm",onClick:()=>ks(t.id),className:"bg-emerald-600 hover:bg-emerald-700 text-white border-0",children:[e.jsx(Le,{className:"h-3.5 w-3.5 mr-1.5"}),"Confirm Sold"]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 pt-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fe,{to:`/marketplace360/inventory/${t.id}`,children:e.jsxs(L,{size:"sm",variant:"outline",children:[e.jsx(ct,{className:"h-3.5 w-3.5 mr-1.5"}),"View"]}
19)}),(()=>{const T=t.fb_stats||{},M=t.fb_stats_previous||{},ge=T.totalClicks??T.marketplace_clicks??0,qe=M.totalClicks??M.marketplace_clicks??0,Ve=T.totalComments??T.total_comments??0,Ue=M.totalComments??M.total_comments??0,$e=T.placesCount??T.total_places??0,we=M.placesCount??M.total_places??0,Ae=M&&(ge>qe||Ve>Ue||$e>we);return e.jsxs(L,{size:"sm",variant:"outline",onClick:()=>gt({vehicle:t,thumbnail:y}),className:Ae?"relative ring-2 ring-[#2F80ED] shadow-[0_0_12px_rgba(47,128,237,0.55)]":"",children:[e.jsx(Rs,{className:"h-3.5 w-3.5 mr-1.5"}),"Stats",Ae&&e.jsx("span",{className:"absolute -top-1 -right-1 h-2 w-2 rounded-full bg-[#2F80ED] ring-2 ring-[#0F2A4D]"})]})})()]}),e.jsx(Ws,{vehicleId:t.id,myQueued:p.has(t.id),myPosted:f.has(t.id),onStaged:()=>g(T=>{const M=new Set(T);return M.add(t.id),M}),onStageError:()=>g(T=>{const M=new Set(T);return M.delete(t.id),M})})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx(Ks,{vehicleId:t.id,hasProcessed:!!t.hero_processed_url,onChanged:T=>{a(M=>M.map(ge=>ge.id===t.id?{...ge,hero_processed_url:T}:ge))}}),e.jsx(me,{componentId:"marketplace360:button-post-to-fb",appName:"marketplace360",componentType:"button",componentLabel:"Post to FB",defaultRole:"user",children:e.jsx(Zs,{vehicleId:t.id,myPosted:f.has(t.id),variant:st?"secondary":"primary"})}),e.jsx(ta,{vehicle:t,ebayAccountId:N,alreadyListed:U.has(t.id),onListed:()=>R(T=>new Set(T).add(t.id))})]})]})]})]},t.id)})})]}),e.jsx(zt,{open:!!ae,onOpenChange:t=>!t&&!_e&&pe(null),children:e.jsxs(Gt,{children:[e.jsxs(Xt,{children:[e.jsx(Qt,{children:"Remove this vehicle?"}),e.jsx(Jt,{children:ae&&e.jsxs(e.Fragment,{children:["Removes ",e.jsxs("strong",{children:[ae.year," ",ae.make," ",ae.model]}),ae.stock_number?e.jsxs(e.Fragment,{children:[" (Stk ",ae.stock_number,")"]}):null," from Marketplace360. This cannot be undone."]})})]}),e.jsxs(Kt,{children:[e.jsx(Yt,{disabled:_e,children:"Cancel"}),e.jsx(Ht,{disabled:_e,onClick:async t=>{if(t.preventDefault(),!ae)return;je(!0);const h=ae.id,{error:y}=await j.from("m360_vehicles").delete().eq("id",h);if(je(!1),y){W({title:"Failed to remove",description:y.message,variant:"destructive"});return}a(E=>E.filter(V=>V.id!==h)),pe(null),W({title:"Vehicle removed"})},className:"bg-red-600 hover:bg-red-700 text-white",children:_e?"Removing…":"Remove"})]})]})}),e.jsx(zt,{open:ms,onOpenChange:t=>!Ie&&Ze(t),children:e.jsxs(Gt,{children:[e.jsxs(Xt,{children:[e.jsx(Qt,{children:"Clear entire inventory?"}),e.jsx(Jt,{asChild:!0,children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{children:["This permanently deletes ",e.jsx("strong",{children:"every vehicle"})," for this dealership — both XLSX-imported and website-scraped."]}),e.jsxs("ul",{className:"list-disc pl-5 text-xs space-y-1",children:[e.jsx("li",{children:"All vehicle photos are removed."}),e.jsx("li",{children:"Queued and in-progress posts are dropped."}),e.jsx("li",{children:"Scraped vehicles will lose their FB stats history until the next stats refresh repopulates them."})]}),e.jsx("p",{className:"text-amber-300 text-xs",children:"This cannot be undone. You'll need to re-import the XLSX or wait for the next scrape to rebuild inventory."})]})})]}),e.jsxs(Kt,{children:[e.jsx(Yt,{disabled:Ie,children:"Cancel"}),e.jsx(Ht,{disabled:Ie,onClick:t=>{t.preventDefault(),Es()},className:"bg-red-600 hover:bg-red-700 text-white",children:Ie?e.jsxs(e.Fragment,{children:[e.jsx(ce,{className:"h-4 w-4 mr-1.5 animate-spin"}),"Clearing…"]}):"Delete everything"})]})]})}),Te&&e.jsx(sa,{open:!!Te,onOpenChange:t=>!t&&gt(null),vehicle:Te.vehicle,thumbnail:Te.thumbnail}),e.jsx(ra,{open:us,onOpenChange:_t,onComplete:()=>De(t=>t+1)}),e.jsx(Na,{open:!!kt,onOpenChange:t=>{t||tt(null)},vehicles:ys,dealershipId:Be,step:kt||"generate_and_queue",onQueued:t=>g(h=>new Set(h).add(t)),onFinished:()=>De(t=>t+1)})]})}export{ii 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.