1import{i as rs,k as ts,r as i,s as c,j as e,C as ye,d as p,a as ms,b as ps,E as ke,B as m,q as Ce,I as Ve,h as d,M as Ge,L as U,t as hs,c as Ee,X as ns,am as is,e as os,Z as Ye,a0 as Te,g as ls,a7 as gs,w as bs,$ as b,_ as _s,u as vs,al as js,z as Ns,A as ws,F as ys,G as ks,H as Cs,a1 as Es,Y as Ss}from"./index-UhpylRvY.js";import{u as As}from"./useMutation-DDUPvvZi.js";import{T as Ds,a as Ts,b as fe}from"./tabs-gHTCexuJ.js";import{C as Ze,a as Xe,b as Je}from"./collapsible-Cv1IGgSt.js";import{O as Os}from"./OfferContextStrip-DwvbpUiX.js";import{S as Se}from"./send-DGzy-c0y.js";import{M as ve}from"./index-Drlx1K6g.js";import{M as cs}from"./mouse-pointer-click-CBaz4Dzt.js";import{A as qs}from"./arrow-up-right-D2pWsH8W.js";import{H as Ms}from"./hand-coins-B_XUQkvS.js";import{E as ds}from"./external-link-CL3_UnNn.js";import{T as fs}from"./trending-up-CXbuwWOi.js";import{A as Ae}from"./activity-BED91j_-.js";import{C as Ie}from"./chevron-up-I27GzVCW.js";import{C as es}from"./chevron-down-Dr6pKxk8.js";import{d as G}from"./differenceInDays-BYoSj18P.js";import{f as De}from"./format-C-8x8zgz.js";import{C as Ls}from"./CollapsibleAIPanel-kUAJ9Rrm.js";import{C as Ps}from"./circle-alert-B3T5Omxl.js";import"./index-5vnHJd8E.js";import"./index-DElkbwns.js";import"./thumbnail-image-LnekvR4i.js";import"./map-pin-1LLayUj6.js";import"./differenceInCalendarDays-Bz1OIFRn.js";import"./constants-BEUXd630.js";import"./getTimezoneOffsetInMilliseconds-8oUTNwRy.js";import"./en-US-ClfMaaVW.js";import"./constructFrom-DWjd9ymD.js";const ss={positive:{border:"border-l-green-500",bg:"bg-green-50/50 dark:bg-green-950/20",text:"text-green-700 dark:text-green-400",label:"Positive"},negative:{border:"border-l-red-500",bg:"bg-red-50/50 dark:bg-red-950/20",text:"text-red-700 dark:text-red-400",label:"Negative"},neutral:{border:"border-l-slate-400",bg:"bg-slate-50/50 dark:bg-slate-950/20",text:"text-slate-700 dark:text-slate-400",label:"Neutral"},opportunity:{border:"border-l-blue-500",bg:"bg-blue-50/50 dark:bg-blue-950/20",text:"text-blue-700 dark:text-blue-400",label:"Opportunity"},high_value:{border:"border-l-purple-500",bg:"bg-purple-50/50 dark:bg-purple-950/20",text:"text-purple-700 dark:text-purple-400",label:"High Value"}},Rs={email_sent:is,offer_viewed:cs,price_updated:fs,status_changed:Ae,resent:Te,follow_up:Se};function Fs({activeCount:z,updatesCount:H,staleCount:je,opportunitiesCount:Oe,resolvedCount:Y,watchlistItems:ue=[],selectedItem:a,onItemClick:k,onDismissItem:_,onRefreshData:O,className:Z}){var _e,se,ae,re,te,ne,ie,oe,y,qe,Me,Le,Pe,Re;const q=rs(),B=ts(),[C,K]=i.useState([]),[N,M]=i.useState(""),[v,l]=i.useState(!1),[xe,V]=i.useState(!a),[me,Ne]=i.useState(!1),[L,Q]=i.useState([]),[we,pe]=i.useState(!1),[P,E]=i.useState(null),w=i.useRef(null),j=!!a;i.useEffect(()=>{w.current&&(w.current.scrollTop=w.current.scrollHeight)},[C]),i.useEffect(()=>{V(!a)},[a]),i.useEffect(()=>{if(!(a!=null&&a.offer_id)){Q([]);return}pe(!0),c.from("offer_activities").select("*").eq("offer_id",a.offer_id).order("created_at",{ascending:!1}).limit(20).then(({data:r})=>{Q(r||[]),pe(!1)})},[a==null?void 0:a.offer_id]);const R=async()=>{var o,f,g,A,D,T,F,$,le,Fe,Ue,ze,Qe,We,$e,He,Be,Ke;if(!N.trim()||v)return;const r={role:"user",content:N};K(ce=>[...ce,r]),M(""),l(!0);try{const ce=a?{offer_id:a.offer_id,offer_number:(o=a.offer)==null?void 0:o.offer_number,customer_name:(f=a.offer)==null?void 0:f.customer_name,customer_email:(g=a.offer)==null?void 0:g.customer_email,customer_address:(A=a.offer)==null?void 0:A.customer_address,customer_notes:(D=a.offer)==null?void 0:D.customer_notes,reason_for_selling:(T=a.offer)==null?void 0:T.reason_for_selling,status:(F=a.offer)==null?void 0:F.status,offer_type:($=a.offer)==null?void 0:$.offer_type,quick_cash_total:(le=a.offer)==null?void 0:le.quick_cash_total,consignment_total:(Fe=a.offer)==null?void 0:Fe.consignment_total,collection_fee:(Ue=a.offer)==null?void 0:Ue.collection_fee,rating:(ze=a.offer)==null?void 0:ze.rating,sent_at:(Qe=a.offer)==null?void 0:Qe.sent_at,email_opened_at:(We=a.offer)==null?void 0:We.email_opened_at,first_viewed_at:($e=a.offer)==null?void 0:$e.first_viewed_at,responded_at:(He=a.offer)==null?void 0:He.responded_at,view_count:(Be=a.offer)==null?void 0:Be.view_count,watchlist_instruction:a.instruction,ai_update:a.ai_update,ai_suggested_action:a.ai_suggested_action,sentiment:a.sentiment,days_watching:G(new Date,new Date(a.created_at)),feedback:a.feedback,recent_activities:L.slice(0,10)}:void 0,de=await c.functions.invoke("ai-chat",{body:{message:N,page_context:"watchlist",conversation_history:C,offer_context:ce}});if(de.error)throw de.error;const us={role:"assistant",content:((Ke=de.data)==null?void 0:Ke.response)||"I couldn't process that request."};K(xs=>[...xs,us])}catch(ce){console.error("AI Chat error:",ce),b.error("Failed to get AI response"),K(de=>de.slice(0,-1))}finally{l(!1)}},X=async r=>{if(!(a!=null&&a.offer_id))return;const o=`increase_${r}`;E(o);try{const{data:f,error:g}=await c.from("offer_items").select("id, quick_cash_price, quantity").eq("offer_id",a.offer_id);if(g)throw g;if(!(f!=null&&f.length)){b.error("No items found on this offer");return}const A=1+r/100;for(const T of f){const F=T.quick_cash_price||0,$=Math.round(F*A);await c.from("offer_items").update({quick_cash_price:$,line_quick_cash_total:$*(T.quantity||1)}).eq("id",T.id)}await c.rpc("recalculate_offer_totals",{p_offer_id:a.offer_id}),await c.from("offer_activities").insert({offer_id:a.offer_id,activity_type:"price_updated",description:`Offer increased by ${r}% from watchlist`,metadata:{percent:r,source:"watchlist"}}),await c.from("offer_updates").insert({offer_id:a.offer_id,update_type:"price_increase",update_note:`Increased offer by ${r}% via watchlist quick action`}),b.success(`Offer increased by ${r}%`),O==null||O(),B.invalidateQueries({queryKey:["watchlist-items"]});const{data:D}=await c.from("offer_activities").select("*").eq("offer_id",a.offer_id).order("created_at",{ascending:!1}).limit(20);Q(D||[])}catch(f){console.error("Price increase failed:",f),b.error("Failed to increase offer: "+(f.message||"Unknown error"))}finally{E(null)}},he=async()=>{var r,o;
1if(!(!(a!=null&&a.offer_id)||!((r=a.feedback)!=null&&r.minimum_acceptable_price))){E("match");try{const f=a.feedback.minimum_acceptable_price,g=((o=a.offer)==null?void 0:o.quick_cash_total)||0;if(g<=0){b.error("Current offer value is zero");return}const A=f/g,{data:D,error:T}=await c.from("offer_items").select("id, quick_cash_price, quantity").eq("offer_id",a.offer_id);if(T)throw T;for(const F of D||[]){const $=F.quick_cash_price||0,le=Math.round($*A);await c.from("offer_items").update({quick_cash_price:le,line_quick_cash_total:le*(F.quantity||1)}).eq("id",F.id)}await c.rpc("recalculate_offer_totals",{p_offer_id:a.offer_id}),await c.from("offer_activities").insert({offer_id:a.offer_id,activity_type:"price_updated",description:`Matched customer minimum: R${f}`,metadata:{match_target:f,previous:g,source:"watchlist"}}),b.success(`Offer matched to customer minimum: R${f}`),O==null||O(),B.invalidateQueries({queryKey:["watchlist-items"]})}catch(f){console.error("Match offer failed:",f),b.error("Failed to match offer")}finally{E(null)}}},J=async()=>{if(a!=null&&a.offer_id){E("resend");try{const{error:r}=await c.functions.invoke("send-offer",{body:{offerId:a.offer_id,isResend:!0}});if(r)throw r;await c.from("offer_activities").insert({offer_id:a.offer_id,activity_type:"resent",description:"Offer resent from watchlist"}),b.success("Offer resent successfully")}catch(r){console.error("Resend failed:",r),b.error("Failed to resend offer")}finally{E(null)}}},ge=r=>ss[r||"neutral"]||ss.neutral,s=[...ue].filter(r=>r.status==="watching").sort((r,o)=>r.ai_update&&!o.ai_update?-1:!r.ai_update&&o.ai_update?1:new Date(r.created_at).getTime()-new Date(o.created_at).getTime()).slice(0,10),t=((_e=a==null?void 0:a.offer)==null?void 0:_e.quick_cash_total)||0,n=((se=a==null?void 0:a.feedback)==null?void 0:se.minimum_acceptable_price)||0,u=n>0&&t>0?n-t:0,h=n>0?Math.round(u/n*100):0,S=ge(a==null?void 0:a.sentiment),I=((ae=a==null?void 0:a.offer)==null?void 0:ae.view_count)||0,ee=(re=a==null?void 0:a.offer)!=null&&re.sent_at?G(new Date,new Date(a.offer.sent_at)):null,x=((te=a==null?void 0:a.offer)==null?void 0:te.email_opened_at)||((ne=a==null?void 0:a.offer)==null?void 0:ne.first_viewed_at),W=(ie=a==null?void 0:a.offer)!=null&&ie.responded_at?G(new Date,new Date(a.offer.responded_at)):x?G(new Date,new Date(x)):ee,be=j?["Best strategy for this one?","Should I follow up?","Teach: when to increase offer"]:["What needs attention today?","Any stale items?","Teach: follow-up timing","Which ones declined?"];return e.jsxs(ye,{className:p("h-full flex flex-col","bg-gradient-to-b from-blue-50/50 to-background dark:from-blue-950/20 dark:to-background","border-l-[3px] border-l-blue-500 shadow-sm",Z),children:[e.jsx(ms,{className:"pb-3 border-b",children:e.jsxs(ps,{className:"flex items-center gap-2 text-lg",children:[e.jsx(ke,{className:"h-5 w-5 text-blue-500"}),"Watchlist Intelligence",e.jsxs(m,{variant:"outline",className:"ml-auto text-xs bg-blue-100 text-blue-700 dark:bg-blue-950 dark:text-blue-400",children:[e.jsx(Ce,{className:"h-3 w-3 mr-1"}),"Active"]})]})}),j&&e.jsxs("div",{className:"p-4 border-b space-y-2",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ve,{placeholder:"Ask about this watchlist item...",value:N,onChange:r=>M(r.target.value),onKeyDown:r=>r.key==="Enter"&&!r.shiftKey&&R(),disabled:v,className:"flex-1"}),e.jsx(d,{size:"icon",onClick:R,disabled:v||!N.trim(),children:e.jsx(Se,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"flex flex-wrap gap-1",children:be.map(r=>e.jsx(d,{variant:"outline",size:"sm",className:"text-xs h-6",onClick:()=>{M(r),setTimeout(()=>R(),100)},disabled:v,children:r},r))})]}),j&&C.length>0&&e.jsxs("div",{className:"px-4 pt-3 space-y-3 border-b pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium text-muted-foreground",children:[e.jsx(Ge,{className:"h-4 w-4"}),"Conversation"]}),C.map((r,o)=>e.jsx("div",{className:p("p-3 rounded-lg text-sm",r.role==="user"?"bg-primary text-primary-foreground ml-4":"bg-muted mr-4"),children:e.jsx(ve,{className:"prose prose-sm dark:prose-invert max-w-none [&>p]:m-0",children:r.content})},o)),v&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-sm",children:[e.jsx(U,{className:"h-4 w-4 animate-spin"}),"Thinking..."]})]}),e.jsx(hs,{className:"flex-1",ref:w,children:e.jsxs(Ee,{className:"p-4 space-y-4",children:[a&&e.jsxs("div",{className:"space-y-3 pb-3 border-b",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-mono font-bold text-sm",children:(oe=a.offer)==null?void 0:oe.offer_number}),e.jsx(m,{variant:"outline",className:p("text-[10px]",S.text,S.bg),children:S.label})]}),e.jsx(d,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:()=>k==null?void 0:k(null),children:e.jsx(ns,{className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[e.jsxs("div",{className:"text-center p-1.5 rounded bg-muted/50 border",children:[e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(cs,{className:"h-3 w-3 text-muted-foreground"}),e.jsx("span",{className:"text-sm font-bold",children:I})]}),e.jsx("div",{className:"text-[9px] text-muted-foreground",children:"Link Views"})]}),e.jsxs("div",{className:"text-center p-1.5 rounded bg-muted/50 border",children:[e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(is,{className:"h-3 w-3 text-muted-foreground"}),e.jsx("span",{className:"text-sm font-bold",children:(y=a.offer)!=null&&y.email_opened_at||(qe=a.offer)!=null&&qe.first_viewed_at?"Yes":"No"})]}),e.jsx("div",{className:"text-[9px] text-muted-foreground",children:"Email Opened"})]}),e.jsxs("div",{className:"text-center p-1.5 rounded bg-muted/50 border",children:[e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(os,{className:"h-3 w-3 text-muted-foreground"}),e.jsx("span",{className:p("text-sm font-bold",W!==null&&W>=3?"text-red-600":""),children:W!==null?`${W}d`:"â"})]}),e.jsx("div",{className:"text-[9px] text-muted-foreground",children:"Since Activity"})]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[e.jsxs("div",{className:"text-center p-2 rounded-lg bg-background border",children:[e.jsxs("div",{className:"text-sm font-bold",children:["R",t.toLocaleStr
1ing()]}),e.jsx("div",{className:"text-[10px] text-muted-foreground",children:"Our Offer"})]}),e.jsxs("div",{className:"text-center p-2 rounded-lg bg-background border",children:[e.jsx("div",{className:"text-sm font-bold",children:n>0?`R${n.toLocaleString()}`:"â"}),e.jsx("div",{className:"text-[10px] text-muted-foreground",children:"Their Min"})]}),e.jsxs("div",{className:p("text-center p-2 rounded-lg border",u>0?"bg-red-50 dark:bg-red-950/20 border-red-200 dark:border-red-800":"bg-green-50 dark:bg-green-950/20 border-green-200 dark:border-green-800"),children:[e.jsx("div",{className:p("text-sm font-bold",u>0?"text-red-600":"text-green-600"),children:u>0?`${h}%`:"â"}),e.jsx("div",{className:"text-[10px] text-muted-foreground",children:"Gap"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"text-xs font-medium text-muted-foreground flex items-center gap-1",children:[e.jsx(Ye,{className:"h-3 w-3"}),"Quick Actions"]}),e.jsxs("div",{className:"flex gap-1.5",children:[[5,10,15].map(r=>e.jsxs(d,{size:"sm",variant:"outline",className:"flex-1 text-xs h-8 gap-1",disabled:!!P,onClick:()=>X(r),children:[P===`increase_${r}`?e.jsx(U,{className:"h-3 w-3 animate-spin"}):e.jsx(qs,{className:"h-3 w-3"}),"+",r,"%"]},r)),n>0&&e.jsxs(d,{size:"sm",variant:"outline",className:"flex-1 text-xs h-8 gap-1 border-blue-200 text-blue-700 hover:bg-blue-50 dark:border-blue-800 dark:text-blue-400 dark:hover:bg-blue-950",disabled:!!P,onClick:he,children:[P==="match"?e.jsx(U,{className:"h-3 w-3 animate-spin"}):e.jsx(Ms,{className:"h-3 w-3"}),"Match"]})]}),e.jsxs("div",{className:"flex gap-1.5",children:[e.jsxs(d,{size:"sm",variant:"outline",className:"flex-1 gap-1 text-xs h-8",onClick:()=>q(`/offers/${a.offer_id}`),children:[e.jsx(ds,{className:"h-3 w-3"}),"View"]}),e.jsxs(d,{size:"sm",variant:"outline",className:"flex-1 gap-1 text-xs h-8",disabled:!!P,onClick:J,children:[P==="resend"?e.jsx(U,{className:"h-3 w-3 animate-spin"}):e.jsx(Te,{className:"h-3 w-3"}),"Resend"]}),e.jsxs(d,{size:"sm",variant:"outline",className:"flex-1 gap-1 text-xs h-8",onClick:()=>q("/offers/negotiate"),children:[e.jsx(fs,{className:"h-3 w-3"}),"Negotiate"]}),e.jsxs(d,{size:"sm",variant:"ghost",className:"gap-1 text-xs h-8 text-muted-foreground",onClick:()=>_==null?void 0:_(a),children:[e.jsx(ls,{className:"h-3 w-3"}),"Resolve"]})]})]}),e.jsx(Os,{offerId:a.offer_id,offerNumber:(Me=a.offer)==null?void 0:Me.offer_number,customerAddress:((Le=a.offer)==null?void 0:Le.customer_address)||null,customerNotes:((Pe=a.offer)==null?void 0:Pe.customer_notes)||null,reasonForSelling:((Re=a.offer)==null?void 0:Re.reason_for_selling)||null,feedback:a.feedback?{decline_reasons:a.feedback.decline_reasons||null,additional_notes:a.feedback.additional_notes||null,consignment_interest:a.feedback.consignment_interest||null,minimum_acceptable_price:a.feedback.minimum_acceptable_price||null}:null,compact:!0}),a.ai_update&&e.jsxs("div",{className:"p-3 rounded-lg bg-muted/50 border space-y-2",children:[e.jsxs("div",{className:"text-xs font-medium flex items-center gap-1.5",children:[e.jsx(gs,{className:"h-3.5 w-3.5 text-purple-500"}),"AI Synopsis"]}),e.jsx("div",{className:"text-xs",children:e.jsx(ve,{className:"prose prose-sm dark:prose-invert max-w-none [&>p]:m-0 [&>ul]:m-0 [&>ul]:pl-4",children:a.ai_update})}),a.ai_suggested_action&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs font-medium text-blue-600 dark:text-blue-400",children:[e.jsx(Ye,{className:"h-3 w-3"}),"Suggested: ",a.ai_suggested_action]})]}),e.jsxs(Ze,{open:me,onOpenChange:Ne,children:[e.jsx(Xe,{asChild:!0,children:e.jsxs(d,{variant:"ghost",className:"w-full justify-between p-2 h-auto",children:[e.jsxs("span",{className:"flex items-center gap-2 text-xs font-medium",children:[e.jsx(Ae,{className:"h-3.5 w-3.5 text-blue-500"}),"Activity Feed",L.length>0&&e.jsx(m,{variant:"secondary",className:"text-[10px] h-4 px-1",children:L.length})]}),me?e.jsx(Ie,{className:"h-3.5 w-3.5"}):e.jsx(es,{className:"h-3.5 w-3.5"})]})}),e.jsx(Je,{className:"space-y-1 pt-1",children:we?e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground p-2",children:[e.jsx(U,{className:"h-3 w-3 animate-spin"})," Loading..."]}):L.length>0?L.map(r=>{const o=Rs[r.activity_type]||Ae;return e.jsxs("div",{className:"flex items-start gap-2 p-1.5 rounded text-xs",children:[e.jsx(o,{className:"h-3 w-3 text-muted-foreground mt-0.5 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("span",{className:"text-foreground",children:r.description||r.activity_type}),e.jsx("div",{className:"text-[10px] text-muted-foreground",children:De(new Date(r.created_at),"dd MMM HH:mm")}
1)]})]},r.id)}):e.jsx("p",{className:"text-[10px] text-muted-foreground p-2",children:"No activity recorded yet."})})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"text-center p-2 rounded-lg bg-background border",children:[e.jsx("div",{className:"text-xl font-bold",children:z}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Watching"})]}),e.jsxs("div",{className:"text-center p-2 rounded-lg bg-amber-50 dark:bg-amber-950/30 border border-amber-200 dark:border-amber-900",children:[e.jsx("div",{className:"text-xl font-bold text-amber-600",children:H}),e.jsx("div",{className:"text-xs text-amber-600/70",children:"Updates"})]}),e.jsxs("div",{className:"text-center p-2 rounded-lg bg-red-50 dark:bg-red-950/30 border border-red-200 dark:border-red-900",children:[e.jsx("div",{className:"text-xl font-bold text-red-600",children:je}),e.jsx("div",{className:"text-xs text-red-600/70",children:"Stale 3d+"})]}),e.jsxs("div",{className:"text-center p-2 rounded-lg bg-muted",children:[e.jsx("div",{className:"text-xl font-bold text-muted-foreground",children:Y}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Resolved"})]})]}),e.jsxs(Ze,{open:xe,onOpenChange:V,children:[e.jsx(Xe,{asChild:!0,children:e.jsxs(d,{variant:"ghost",className:"w-full justify-between p-2 h-auto",children:[e.jsxs("span",{className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx(bs,{className:"h-4 w-4 text-blue-500"}),"Priority Queue",s.length>0&&e.jsx(m,{variant:"secondary",className:"text-xs",children:s.length})]}),xe?e.jsx(Ie,{className:"h-4 w-4"}):e.jsx(es,{className:"h-4 w-4"})]})}),e.jsx(Je,{className:"space-y-2 pt-2",children:s.length>0?s.map(r=>{var A,D;const o=ge(r.sentiment),f=(a==null?void 0:a.id)===r.id,g=G(new Date,new Date(r.created_at));return e.jsxs("div",{className:p("p-2.5 rounded-lg text-xs cursor-pointer hover:opacity-90 transition-all border-l-[3px]",o.border,o.bg,f&&"ring-1 ring-primary"),onClick:()=>k==null?void 0:k(r),children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("span",{className:"font-medium",children:((A=r.offer)==null?void 0:A.offer_number)||"â"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsxs(m,{variant:"outline",className:p("text-[10px] border-0",g>=6?"bg-red-100 text-red-700 dark:bg-red-950 dark:text-red-400":g>=3?"bg-amber-100 text-amber-700 dark:bg-amber-950 dark:text-amber-400":"bg-green-100 text-green-700 dark:bg-green-950 dark:text-green-400"),children:[g,"d"]}),r.ai_update&&e.jsx(m,{variant:"outline",className:"text-[10px] bg-amber-100 text-amber-700 dark:bg-amber-950 dark:text-amber-400",children:"Update"})]})]}),e.jsx("div",{className:"text-muted-foreground",children:((D=r.offer)==null?void 0:D.customer_name)||"Unknown"}),e.jsx("div",{className:"text-muted-foreground/70 italic mt-0.5 line-clamp-1",children:r.instruction}),r.ai_suggested_action&&e.jsxs("div",{className:p("mt-1 font-medium",o.text),children:["â ",r.ai_suggested_action]})]},r.id)}):e.jsx("p",{className:"text-xs text-muted-foreground p-2",children:"No active watchlist items."})})]}),!j&&C.length>0&&e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium text-muted-foreground",children:[e.jsx(Ge,{className:"h-4 w-4"}),"Conversation"]}),C.map((r,o)=>e.jsx("div",{className:p("p-3 rounded-lg text-sm",r.role==="user"?"bg-primary text-primary-foreground ml-4":"bg-muted mr-4"),children:e.jsx(ve,{className:"prose prose-sm dark:prose-invert max-w-none [&>p]:m-0",children:r.content})},o)),v&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-sm",children:[e.jsx(U,{className:"h-4 w-4 animate-spin"}),"Thinking..."]})]}),!j&&e.jsxs("div",{className:"space-y-2 border-t pt-3",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Quick Questions"}),e.jsx("div",{className:"flex flex-wrap gap-1",children:be.map(r=>e.jsx(d,{variant:"outline",size:"sm",className:"text-xs h-7",onClick:()=>{M(r),setTimeout(()=>R(),100)},disabled:v,children:r},r))})]})]})}),!j&&e.jsx("div",{className:"p-4 border-t",children:e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ve,{placeholder:"Ask about watchlist...",value:N,onChange:r=>M(r.target.value),onKeyDown:r=>r.key==="Enter"&&!r.shiftKey&&R(),disabled:v,className:"flex-1"}),e.jsx(d,{size:"icon",onClick:R,disabled:v||!N.trim(),children:e.jsx(Se,{className:"h-4 w-4"})})]})})]})}const Us={positive:"border-l-4 border-l-green-500",negative:"border-l-4 border-l-red-500",neutral:"border-l-4 border-l-slate-400",opportunity:"border-l-4 border-l-blue-500",high_value:"border-l-4 border-l-purple-500"},zs={positive:"bg-green-50/30 dark:bg-green-950/10",negative:"bg-red-50/30 dark:bg-red-950/10",neutral:"",opportunity:"bg-blue-50/30 dark:bg-blue-950/10",high_value:"bg-purple-50/30 dark:bg-purple-950/10"},Qs=z=>z<=2?{color:"bg-green-100 text-green-700 dark:bg-green-950 dark:text-green-400",label:"Fresh"}
1:z<=5?{color:"bg-amber-100 text-amber-700 dark:bg-amber-950 dark:text-amber-400",label:"Aging"}:{color:"bg-red-100 text-red-700 dark:bg-red-950 dark:text-red-400",label:"Stale"},as="watchlist-last-viewed",ha=()=>{const z=rs(),H=ts();_s();const[je,Oe]=i.useState(new Set),[Y,ue]=i.useState(!1),[a,k]=i.useState(null),[_,O]=i.useState("all"),[Z,q]=i.useState(null),[B,C]=i.useState(""),[K,N]=i.useState(""),[M,v]=i.useState(()=>{try{return localStorage.getItem(as)||""}catch{return""}});i.useEffect(()=>{const s=new Date().toISOString();localStorage.setItem(as,s),v(s)},[]);const{data:l,isLoading:xe}=vs({queryKey:["watchlist-items"],queryFn:async()=>{const{data:s,error:t}=await c.from("offer_watchlist").select("*").order("created_at",{ascending:!1});if(t)throw t;const n=[...new Set((s||[]).map(x=>x.offer_id))];if(n.length===0)return[];const{data:u,error:h}=await c.from("offers").select("id, offer_number, customer_name, customer_email, customer_address, customer_notes, reason_for_selling, status, responded_at, sent_at, email_opened_at, first_viewed_at, view_count, quick_cash_total, consignment_total, rating, offer_type, collection_fee").in("id",n);if(h)throw h;const{data:S}=await c.from("offer_feedback").select("offer_id, decline_reasons, minimum_acceptable_price, consignment_interest, additional_notes, offer_expectation").in("offer_id",n),I=new Map((u||[]).map(x=>[x.id,x])),ee=new Map((S||[]).map(x=>[x.offer_id,x]));return(s||[]).map(x=>({...x,offer:I.get(x.offer_id)||null,feedback:ee.get(x.offer_id)||null}))}}),V=As({mutationFn:async({id:s,outcome:t,notes:n})=>{const{error:u}=await c.from("offer_watchlist").update({status:"resolved",resolved_at:new Date().toISOString()}).eq("id",s);if(u)throw u;if(t){const h=l==null?void 0:l.find(S=>S.id===s);await c.from("ai_owner_feedback").insert({feedback_type:"watchlist_outcome",offer_id:h==null?void 0:h.offer_id,original_value:(h==null?void 0:h.instruction)||"",new_value:t,reason:n||null})}},onSuccess:()=>{H.invalidateQueries({queryKey:["watchlist-items"]}),H.invalidateQueries({queryKey:["sidebar-watchlist-count"]}),b.success("Watchlist item resolved â AI learning updated"),q(null),C(""),N("")}}),me=async()=>{ue(!0);try{const{data:s,error:t}=await c.functions.invoke("watchlist-cron",{body:{}});if(t)throw t;b.success(`AI updates refreshed for ${(s==null?void 0:s.processed)||0} offers`),H.invalidateQueries({queryKey:["watchlist-items"]})}catch(s){b.error("Failed to refresh: "+(s.message||"Unknown error"))}finally{ue(!1)}},Ne=s=>{Oe(t=>{const n=new Set(t);return n.has(s)?n.delete(s):n.add(s),n})},L=s=>{var t,n,u;return s.sentiment?s.sentiment:((t=s.offer)==null?void 0:t.status)==="ACCEPTED"?"positive":s.ai_suggested_action==="convert_to_consignment"?"opportunity":(n=s.ai_update)!=null&&n.toLowerCase().includes("declined")||(u=s.ai_update)!=null&&u.toLowerCase().includes("hostile")?"negative":"neutral"},Q=s=>G(new Date,new Date(s.created_at)),we=s=>{var n;const t=[s.ai_updated_at,(n=s.offer)==null?void 0:n.responded_at,s.resolved_at].filter(Boolean).map(u=>new Date(u).getTime());return t.length===0?new Date(s.created_at):new Date(Math.max(...t))},pe=s=>!s.ai_updated_at||!M?!1:new Date(s.ai_updated_at)>new Date(M),P=s=>{switch(s){case"SENT":return e.jsx(m,{variant:"outline",className:"text-[10px] bg-blue-50 text-blue-700 dark:bg-blue-950 dark:text-blue-400",children:"Sent"});case"DECLINED":return e.jsx(m,{variant:"outline",className:"text-[10px] bg-red-50 text-red-700 dark:bg-red-950 dark:text-red-400",children:"Declined"});case"ACCEPTED":case"ACCEPTED - COLLECT":case"ACCEPTED - DROP OFF":return e.jsx(m,{variant:"outline",className:"text-[10px] bg-green-50 text-green-700 dark:bg-green-950 dark:text-green-400",children:"Accepted"});case"UPDATE_REQUESTED":return e.jsx(m,{variant:"outline",className:"text-[10px] bg-amber-50 text-amber-700 dark:bg-amber-950 dark:text-amber-400",children:"Update Req"});default:return null}},E=i.useMemo(()=>{if(!l)return[];switch(_){case"needs_attention":return l.filter(s=>{var t;return s.status!=="resolved"&&(s.ai_update||["DECLINED","UPDATE_REQUESTED","ACCEPTED","ACCEPTED - COLLECT","ACCEPTED - DROP OFF"].includes(((t=s.offer)==null?void 0:t.status)||""))});case"awaiting":return l.filter(s=>{var t,n;return s.status!=="resolved"&&((t=s.offer)==null?void 0:t.status)==="SENT"&&!((n=s.offer)!=null&&n.responded_at)});case"stale":return l.filter(s=>s.status!=="resolved"&&Q(s)>=3);case"resolved":return l.filter(s=>s.status==="resolved");default:return l.filter(s=>s.status!=="resolved")}},[l,_]),w=(l==null?void 0:l.filter(s=>s.status!=="resolved"))||[],j=w.length,R=w.filter(s=>s.ai_update).length,X=w.filter(s=>Q(s)>=3).length,he=w.filter(s=>{var t;return s.ai_update||["DECLINED","UPDATE_REQUESTED","ACCEPTED","ACCEPTED - COLLECT","ACCEPTED - DROP OFF"].includes(((t=s.offer)==null?void 0:t.status)||"")}).length,J=(l==null?void 0:l.filter(s=>s.status==="resolved").length)||0,ge=w.filter(s=>L(s)==="opportunity").length;return xe?e.jsx("div",{className:"flex items-center justify-center h-64",children:e.jsx(U,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"flex gap-6",children:[e.jsxs("div",{className:"flex-1 min-w-0 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl font-bold flex items-center gap-2",children:[e.jsx(ke,{className:"h-6 w-6"}),"Watchlist"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"AI-monitored offers â daily synopsis with sentiment analysis"})]}),e.jsxs(d,{onClick:me,disabled:Y||j===0,children:[e.jsx(Te,{className:p("h-4 w-4 mr-2",Y&&"animate-spin")}),Y?"Refreshing...":"Refresh AI"]})]}),e.jsx(Ds,{value:_,onValueChange:s=>O(s),children:e.jsxs(Ts,{className:"w-full justify-start",children:[e.jsxs(fe,{value:"all",className:"gap-1.5",children:["All",j>0&&e.jsx(m,{variant:"secondary",className:"text-[10px] h-4 px-1",children:j})]}),e.jsxs(fe,{value:"needs_attention",className:"gap-1.5",children:[e.jsx(js,{className:"h-3 w-3"}),"Needs Attention",he>0&&e.jsx(m,{className:"text-[10px] h-4 px-1 bg-amber-500",children:he})]}),e.jsxs(fe,{value:"awaiting",className:"gap-1.5",children:[e.jsx(os,{className:"h-3 w-3"}),"Awaiting"]}),e.jsxs(fe,{value:"stale",className:"gap-1.5",children:[e.jsx(Ps,{className:"h-3 w-3"}),"Stale 3d+",X>0&&e.jsx(m,{className:"text-[10px] h-4 px-1 bg-red-500 text-white",children:X})]}),e.jsxs(fe,{value:"resolved",className:"gap-1.5",children:[e.jsx(ls,{className:"h-3 w-3"}),"Resolved",J>0&&e.jsx(m,{variant:"secondary",className:"text-[10px] h-4 px-1",children:J})]})]})}),E.length>0?e.jsx("div",{className:"space-y-3",children:E.map(s=>{var se,ae,re,te,ne,ie,oe;const t=je.has(s.id),n=s.ai_update||"Waiting for customer activity...",u=n.length>200&&!t,h=L(s),S=Us[h]||"",I=zs[h]||"",ee=(a==null?void 0:a.id)===s.id,x=Q(s),W=Qs(x),be=we(s),_e=pe(s);return e.jsx(ye,{className:p("transition-all cursor-pointer hover:shadow-md",S,I,ee&&"ring-2 ring-primary",s.status==="resolved"&&"opacity-60"),onClick:()=>k(s),children:e.jsxs(Ee,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[_e&&e.jsxs("span",{className:"relative flex h-2.5 w-2.5",children:[e.jsx("span",{className:"animate-ping absolute inline-flex h-full w-full rounded-full bg-amber-400 opacity-75"}),e.jsx("span",{className:"relative inline-flex rounded-full h-2.5 w-2.5 bg-amber-500"})]}),e.jsx(d,{variant:"link",className:"p-0 h-auto font-mono text-sm font-bold",onClick:y=>{y.stopPropagation(),z(`/offers/${s.offer_id}`)},children:((se=s.offer)==null?void 0:se.offer_number)||"â"}),e.jsxs(m,{variant:"outline",className:p("text-[10px] border-0",W.color),children:[x,"d ⢠",W.label]}),P((ae=s.offer)==null?void 0:ae.status),s.ai_suggested_action&&e.jsxs(m,{variant:"outline",className:"text-[10px]",children:[e.jsx(Ce,{className:"h-2.5 w-2.5 mr-0.5"}),s.ai_suggested_action]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["Last: ",De(be,"dd MMM HH:mm")]}),e.jsx(d,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:y=>{y.stopPropagation(),z(`/offers/${s.offer_id}`)},title:"View Offer",children:e.jsx(ds,{className:"h-3.5 w-3.5"})}),s.status==="watching"&&e.jsx(d,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:y=>{y.stopPropagation(),q(s)},title:"Dismiss",children:e.jsx(ns,{className:"h-3.5 w-3.5"})})]})]}),e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("span",{className:"text-sm font-medium",children:((re=s.offer)==null?void 0:re.customer_name)||"Unknown"}),((te=s.offer)==null?void 0:te.quick_cash_total)&&e.jsxs("span",{className:"text-sm text-primary font-bold",children:["R",(s.offer.quick_cash_total||0).toLocaleStr
1ing()]}),((ne=s.offer)==null?void 0:ne.rating)&&e.jsx("span",{className:"text-xs text-amber-500",children:"â
".repeat(s.offer.rating)}),((ie=s.feedback)==null?void 0:ie.minimum_acceptable_price)&&((oe=s.offer)==null?void 0:oe.quick_cash_total)&&e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["Gap: R",(s.feedback.minimum_acceptable_price-s.offer.quick_cash_total).toLocaleString()]})]}),e.jsxs("div",{className:"text-xs text-muted-foreground italic mb-2",children:["ð ",s.instruction]}),s.ai_update?e.jsxs("div",{className:"mt-2",children:[e.jsx("div",{className:p(u?"line-clamp-3":""),children:e.jsx(ve,{className:"prose prose-sm dark:prose-invert max-w-none text-sm [&>p]:m-0 [&>ul]:m-0 [&>ul]:pl-4",children:u?n.slice(0,200)+"...":n})}),n.length>200&&e.jsx(d,{variant:"link",size:"sm",className:"p-0 h-auto text-xs",onClick:y=>{y.stopPropagation(),Ne(s.id)},children:t?"Show less":"Show more"}),s.ai_updated_at&&e.jsxs("div",{className:"text-[10px] text-muted-foreground mt-1",children:["Updated ",De(new Date(s.ai_updated_at),"dd MMM HH:mm")]})]}):e.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:"Waiting for activity..."})]})},s.id)})}):e.jsx(ye,{children:e.jsxs(Ee,{className:"py-12 text-center",children:[e.jsx(ke,{className:"h-12 w-12 mx-auto text-muted-foreground/50 mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:_==="resolved"?"No Resolved Items":_==="stale"?"No Stale Items":"No Watchlist Items"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:_==="all"?"Add offers to your watchlist from the offer detail page to receive AI-powered daily synopses.":`No items match the "${_.replace("_"," ")}" filter.`})]})})]}),e.jsx(Ls,{widthClass:"w-[450px]",children:e.jsx(Fs,{activeCount:j,updatesCount:R,staleCount:X,opportunitiesCount:ge,resolvedCount:J,watchlistItems:l,selectedItem:a,onItemClick:k,onDismissItem:s=>q(s),onRefreshData:()=>H.invalidateQueries({queryKey:["watchlist-items"]})})}),e.jsx(Ns,{open:!!Z,onOpenChange:s=>!s&&q(null),children:e.jsxs(ws,{children:[e.jsxs(ys,{children:[e.jsxs(ks,{className:"flex items-center gap-2",children:[e.jsx(Ce,{className:"h-5 w-5 text-primary"}),"Teach AI â What was the outcome?"]}),e.jsx(Cs,{children:"Recording this helps the AI learn which watchlist strategies work best."})]}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsx("div",{className:"grid grid-cols-2 gap-2",children:[{value:"accepted",label:"â
Accepted",desc:"Customer accepted our offer"},{value:"declined_final",label:"â Declined Final",desc:"Customer won't proceed"},{value:"no_response",label:"ð¶ No Response",desc:"Customer went silent"},{value:"other",label:"ð Other",desc:"Different outcome"}].map(s=>e.jsxs("button",{className:p("p-3 rounded-lg border text-left transition-all",B===s.value?"border-primary bg-primary/5 ring-1 ring-primary":"hover:border-muted-foreground/30"),onClick:()=>C(s.value),children:[e.jsx("div",{className:"text-sm font-medium",children:s.label}),e.jsx("div",{className:"text-xs text-muted-foreground",children:s.desc})]},s.value))}),e.jsx(Es,{placeholder:"Any notes? (optional) â e.g. 'Customer came back after 3 days and accepted 10% increase'",value:K,onChange:s=>N(s.target.value),rows:3})]}),e.jsxs(Ss,{children:[e.jsx(d,{variant:"outline",onClick:()=>q(null),children:"Cancel"}),e.jsxs(d,{onClick:()=>Z&&V.mutate({id:Z.id,outcome:B,notes:K}),disabled:!B||V.isPending,children:[V.isPending&&e.jsx(U,{className:"h-4 w-4 mr-2 animate-spin"}),"Resolve & Teach AI"]})]})]})})]})};export{ha 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.