1import{a as cs,u as Ne,c as rt,b as J,j as e}from"./vendor-query-DvnPdOMX.js";import{r as n,L as us,u as ms,k as xs}from"./vendor-react-woJBpfBI.js";import{c as _}from"./vendor-utils-BNe0Xlio.js";import{u as ps}from"./usePageTitle-648OBlq4.js";import{de as hs,v as fs,U as k,Q as de,ab as Fe,e as bs,ao as _e,c as Yt,R as Ge,a as te,b as ys,an as q,ck as jt,bi as ze,gP as gs,aD as js,df as vs,br as ws,aH as Ns}from"./index-1YQNuixL.js";import{u as ks}from"./useGateDebug-C1gY7_rA.js";import{getRedditFeed as _s,getRedditOpportunities as vt,triggerRedditScan as Ss,resetRedditData as Cs,dismissRedditOpportunity as wt,bulkDismissRedditOpportunities as Rs,markRedditThreadResponded as Ms,generateRedditDraft as Ts,addRedditSubreddit as Ds,removeRedditSubreddit as As,addRedditTrigger as Es,removeRedditTrigger as Qs,updateRedditSettings as Ls,generateRedditSetupSuggestions as Is,applyRedditSetup as Os,getRedditState as Ps,getRedditStats as zs,getRedditThreadDetail as Fs,getRedditDrafts as qs,getRedditAnalytics as Ks,searchRedditSubreddits as Bs}from"./reddit-DfYJLlsY.js";import{T as $s}from"./TabBar-Bd4u7NpX.js";import{S as ce}from"./StateNotice-CUVE_HHP.js";import{A as Us}from"./AsyncProcess-B6w3WMkx.js";import{B as Ys}from"./BulkActionBar-hK4tvw8H.js";import{O as qe}from"./OverflowMenu-C97PGN8W.js";import{aE as dt,ac as Wt,i as ve,a4 as Ht,aY as ct,c7 as Ws,ap as He,ah as Hs,q as Vs,t as Vt,C as Se,m as Gt,d as Gs,k as ot,X as me,L as Ke,aS as lt,T as Xs,A as Zs,R as Ce,e as Nt,bh as Js,j as ea,_ as ta,ax as ut,b_ as mt,bl as kt,aT as sa,M as Xt,Z as aa,eT as ra,z as na}from"./vendor-icons-BLMEbmRV.js";import{F as ia}from"./NavigationControls-BHA2q2LU.js";import{A as Ve,m as ue}from"./vendor-motion-ZmH_6coE.js";import{R as _t,A as St,X as Ct,Y as Rt,T as Mt,a as nt}from"./vendor-charts-aEJ5Vv6F.js";import{S as da,a as oa,e as la,c as ca}from"./SetupFrame-CKYdXbt3.js";import"./vendor-supabase-DaZXgOw0.js";const Tt=20,ua=100;function je(t){const a=t;return a?.response?.data?.detail||a?.message||"Couldn't complete that. Try again."}function ma(t){return Array.isArray(t)?t.filter(a=>typeof a=="string"&&a.trim().length>0):[]}function xa(t,a,d="threads"){const{brand:h,isLoading:u}=hs(),{entitlements:v}=fs(),p=cs(),i=h?.id||"",y=typeof a=="string"?a:null,S=n.useMemo(()=>ma(t.subreddits),[t.subreddits]),j=v?.hasReddit??!1,w=v?.redditSubredditLimit||0,N=v?.redditTriggerLimit||0,R=v?.redditHistoryDays||0,O=v?.redditDraftsPerMonth||0,f=Ne({queryKey:["reddit-state",i],queryFn:()=>Ps(i),enabled:!!i&&j,staleTime:6e4,refetchInterval:o=>{const P=o.state.data?.scan_status||o.state.data?.settings?.last_scan_status||"idle";return P==="queued"||P==="scanning"?5e3:!1}}),b=f.data?.scan_status||f.data?.settings?.last_scan_status||"idle",m=f.data?.settings?.is_onboarded??!1,M=f.data?.last_scan_at||f.data?.settings?.last_scan_at,K=f.data?.scan_error||f.data?.settings?.last_scan_error||null,C=f.data?.scan_error_code||null,z=f.data?.scan_run_id||null,I=f.data?.scan_progress,B=Ne({queryKey:["reddit-stats",i,t.days],queryFn:()=>zs(i,t.days),enabled:!!i&&j&&m&&d==="threads",staleTime:6e4}),A=n.useMemo(()=>{switch(t.citationBand){case"high":return{min:70,max:void 0};case"mid":return{min:40,max:69};case"low":return{min:void 0,max:39};default:return{min:void 0,max:void 0}}},[t.citationBand]),g=rt({queryKey:["reddit-feed-infinite",i,t.search,t.mentionType,t.citationBand,t.days,S,t.sortBy],queryFn:({pageParam:o=1})=>_s({brandId:i,search:t.search||void 0,subreddits:S.length>0?S:void 0,mentionType:t.mentionType!=="all"?t.mentionType:void 0,minCitationScore:A.min,maxCitationScore:A.max,days:t.days,page:o,pageSize:Tt,sort:t.sortBy}),initialPageParam:1,getNextPageParam:(o,P)=>P.reduce((Y,W)=>Y+W.items.length,0)<o.total?P.length+1:void 0,enabled:!!i&&j&&m&&t.preset!=="opportunities"&&t.preset!=="responded",staleTime:3e4}),T=n.useMemo(()=>{const o=g.data?.pages;return Array.isArray(o)?o.flatMap(P=>Array.isArray(P?.items)?P.items:[]):[]},[g.data]),E=g.data?.pages?.[0]?.total||0,H=t.preset==="opportunities"||t.preset==="responded",D=rt({queryKey:["reddit-opportunities","index",i],queryFn:({pageParam:o=1})=>vt({brandId:i,status:"all",includeDismissed:!1,limit:ua,page:o}),initialPageParam:1,getNextPageParam:(o,P)=>o.has_more?P.length+1:void 0,enabled:!!i&&j&&m,staleTime:3e4}),x=n.useMemo(()=>{const o=D.data?.pages;return Array.isArray(o)?o.flatMap(P=>Array.isArray(P?.items)?P.items:[]):[]},[D.data]),l=D.data?.pages?.[0]?.summary??{total:0,open:0,responded:0,dismissed:0},Q=rt({queryKey:["reddit-opportunities","filtered",i,t.preset,t.search,t.mentionType,t.citationBand,t.days,S,t.sortBy,t.keyword??""],queryFn:({pageParam:o=1})=>vt({brandId:i,includeDismissed:t.preset==="responded",status:t.preset==="responded"?"responded":"open",search:t.search||void 0,subreddits:S.length>0?S:void 0,mentionType:t.mentionType!=="all"?t.mentionType:void 0,minCitationScore:A.min,maxCitationScore:A.max,days:t.days,keyword:t.keyword,sort:t.sortBy,limit:Tt,page:o}),initialPageParam:1,getNextPageParam:(o,P)=>o.has_more?P.length+1:void 0,enabled:!!i&&j&&m&&H,staleTime:3e4}),X=n.useMemo(()=>{const o=Q.data?.pages;return Array.isArray(o)?o.flatMap(P=>Array.isArray(P?.items)?P.items:[]):[]},[Q.data]),se=Ne({queryKey:["reddit-thread",i,y],queryFn:()=>Fs(i,y),enabled:!!i&&!!y&&j,staleTime:6e4,retry:!1,refetchOnWindowFocus:!1}),xe=Ne({queryKey:["reddit-drafts",i,y],queryFn:()=>qs(i),enabled:!!i&&!!y&&j,staleTime:12e4}
1),pe=Ne({queryKey:["reddit-analytics",i,t.days],queryFn:()=>Ks(i,Math.max(t.days,30)),enabled:!!i&&j&&m&&d==="analytics",staleTime:3e5}),ae=f.data?.subreddits?.length||0,Re=f.data?.keyword_triggers?.length||0,oe=f.data?.drafts_used_this_month||0,Me=w>999||w===1/0,he=N>999||N===1/0,Ze=R>999||R===1/0,Te=O>999||O===1/0,De=!Me&&ae>=w,Be=!he&&Re>=N,Ae=Te?1/0:Math.max(0,O-oe),we=n.useMemo(()=>x.find(o=>o.thread_id===a),[x,a]),ee=n.useCallback(()=>{p.invalidateQueries({queryKey:["reddit-state",i]}),p.invalidateQueries({queryKey:["reddit-stats"]}),p.invalidateQueries({queryKey:["reddit-feed-infinite"]}),p.invalidateQueries({queryKey:["reddit-opportunities"]}),p.invalidateQueries({queryKey:["reddit-analytics"]})},[p,i]),s=n.useCallback(()=>p.getQueriesData({queryKey:["reddit-opportunities"]}),[p]),G=n.useCallback(o=>{for(const[P,F]of o)p.setQueryData(P,F)},[p]),ne=n.useRef(b);n.useEffect(()=>{const o=ne.current;ne.current=b,(o==="queued"||o==="scanning")&&(b==="completed"||b==="failed")&&ee()},[b,ee]);const $=J({mutationFn:()=>Ss(i),onSuccess:o=>{o.status==="queue_failed"?k.error(o.detail||"Could not queue scan"):o.status==="already_scanning"?k.info("Scan already in progress"):k.success(o.status==="queued_local"?"Scan started locally":"Scan queued"),p.invalidateQueries({queryKey:["reddit-state",i]})},onError:()=>k.error("Failed to start scan")}),Ee=J({mutationFn:()=>Cs(i),onSuccess:()=>{k.success("Reddit data cleared"),p.invalidateQueries({queryKey:["reddit-state",i]}),p.invalidateQueries({queryKey:["reddit-feed-infinite"]}),p.invalidateQueries({queryKey:["reddit-opportunities"]}),p.invalidateQueries({queryKey:["reddit-drafts"]}),p.invalidateQueries({queryKey:["reddit-thread"]}),p.invalidateQueries({queryKey:["reddit-analytics"]}),p.invalidateQueries({queryKey:["reddit-stats"]})},onError:o=>k.error(je(o))}),V=J({mutationFn:o=>wt(i,o),onMutate:async o=>{await p.cancelQueries({queryKey:["reddit-opportunities"]});const P=s();return p.setQueriesData({queryKey:["reddit-opportunities"]},F=>F&&{...F,pages:F.pages.map(Y=>({...Y,items:Y.items.map(W=>W.id===o?{...W,is_dismissed:!0}:W)}))}),{prev:P}},onError:(o,P,F)=>{F?.prev&&G(F.prev)},onSettled:()=>{p.invalidateQueries({queryKey:["reddit-opportunities"]}),p.invalidateQueries({queryKey:["reddit-stats"]})}}),fe=J({mutationFn:o=>wt(i,o,!1),onMutate:async o=>{await p.cancelQueries({queryKey:["reddit-opportunities"]}),p.setQueriesData({queryKey:["reddit-opportunities"]},P=>P&&{...P,pages:P.pages.map(F=>({...F,items:F.items.map(Y=>Y.id===o?{...Y,is_dismissed:!1}:Y)}))})},onSettled:()=>{p.invalidateQueries({queryKey:["reddit-opportunities"]}),p.invalidateQueries({queryKey:["reddit-stats"]})}}),re=J({mutationFn:o=>Rs(i,o),onMutate:async o=>{await p.cancelQueries({queryKey:["reddit-opportunities"]});const P=s(),F=new Set(o);return p.setQueriesData({queryKey:["reddit-opportunities"]},Y=>Y&&{...Y,pages:Y.pages.map(W=>({...W,items:W.items.map(Qe=>F.has(Qe.id)?{...Qe,is_dismissed:!0}:Qe)}))}),{prev:P}},onError:(o,P,F)=>{F?.prev&&G(F.prev),k.error("Failed to dismiss opportunities")},onSettled:()=>{p.invalidateQueries({queryKey:["reddit-opportunities"]}),p.invalidateQueries({queryKey:["reddit-stats"]})}}),le=J({mutationFn:o=>Ms(i,o),onMutate:async o=>{await p.cancelQueries({queryKey:["reddit-opportunities"]});const P=new Date().toISOString();p.setQueriesData({queryKey:["reddit-opportunities"]},F=>F&&{...F,pages:F.pages.map(Y=>({...Y,items:Y.items.map(W=>W.thread_id===o?{...W,responded_at:W.responded_at||P}:W)}))})},onSuccess:()=>k.success("Marked as responded"),onSettled:()=>{p.invalidateQueries({queryKey:["reddit-opportunities"]}),p.invalidateQueries({queryKey:["reddit-stats"]})}}),Je=J({mutationFn:o=>Ts({brandId:i,threadId:o.threadId,attempts:o.attempts??3}),onSuccess:()=>{p.setQueryData(["reddit-state",i],o=>o&&{...o,drafts_used_this_month:(o.drafts_used_this_month||0)+1}),p.invalidateQueries({queryKey:["reddit-state",i]}),p.invalidateQueries({queryKey:["reddit-drafts",i]})}}),ie=J({mutationFn:o=>Ds(i,o),onSuccess:()=>{p.invalidateQueries({queryKey:["reddit-state",i]}),k.success("Subreddit added")},onError:o=>k.error(je(o))}),be=J({mutationFn:o=>As(i,o),onSuccess:()=>{p.invalidateQueries({queryKey:["reddit-state",i]}),k.success("Subreddit removed")},onError:o=>k.error(je(o))}),ye=J({mutationFn:o=>Es(i,o),onSuccess:()=>{p.invalidateQueries({queryKey:["reddit-state",i]}),k.success("Trigger added")},onError:()=>k.error("Failed to add trigger")}),et=J({mutationFn:o=>Qs(i,o),onSuccess:()=>{p.invalidateQueries({queryKey:["reddit-state",i]}),k.success("Trigger removed")},onError:o=>k.error(je(o))}),$e=J({mutationFn:o=>Ls(i,o),onSuccess:()=>p.invalidateQueries({queryKey:["reddit-state",i]}),onError:o=>k.error(je(o))}),Ue=J({mutationFn:()=>Is({brandId:i}),onError:o=>k.error(je(o))}),tt=J({mutationFn:o=>Os({brandId:i,subreddits:o.subreddits,keywordTriggers:o.triggers}),onSuccess:()=>{p.invalidateQueries({queryKey:["reddit-state",i]}),$.mutate()},onError:o=>k.error(je(o))});return{brand:h,brandId:i,brandLoading:u,hasReddit:j,stateQuery:f,isOnboarded:m,scanStatus:b,lastScanAt:M,scanError:K,scanErrorCode:C,scanRunId:z,scanProgress:I,statsQuery:B,feedQuery:g,feedItems:T,feedTotal:E,opportunitiesQuery:D,opportunities:x,opportunitySummary:l,filteredOpportunitiesQuery:Q,filteredOpportunities:X,threadDetailQuery:se,currentOpp:we,draftsQuery:xe,draftsRemaining:Ae,draftIsUnlimited:Te,draftLimit:O,draftsUsed:oe,analyticsQuery:pe,subCount:ae,trigCount:Re,subLimit:w,trigLimit:N,historyLimit:R,subAtLimit:De,trigAtLimit:Be,subIsUnlimited:Me,trigIsUnlimited:he,historyIsUnlimited:Ze,scanMutation:$,resetDataMutation:Ee,dismissOppMutation:V,restoreOppMutation:fe,bulkDismissOppMutation:re,markRespondedMutation:le,generateDraftMutation:Je,addSubredditMutation:ie,removeSubredditMutation:be,addTriggerMutation:ye,removeTriggerMutation:et,updateSettingsMutation:$e,suggestionsMutation:Ue,applySetupMutation:tt,invalidateAll:ee}}function Xe(t){const a=new Date(t).getTime();return Number.isNaN(a)?null:a}function ke(t){if(!t)return"";const a=Xe(t);if(a===null)return"";const d=Math.max(0,Date.now()-a),h=Math.floor(d/6e4);if(h<1)return"just now";if(h<60)return`${h}m ago`;const u=Math.floor(h/60);return u<24?`${u}h ago`:`${Math.floor(u/24)}d ago`}function pa(t){if(!t)return"";const a=Xe(t);if(a===null)return"";const d=Math.max(0,Date.now()-a),h=Math.floor(d/6e4);if(h<1)return"just now";if(h<60)return`${h}m`;const u=Math.floor(h/60);return u<24?`${u}h`:`${Math.floor(u/24)}d`}function ha(t){if(!t)return"";const a=Xe(t);if(a===null)return"";const d=Math.max(0,Date.now()-a),h=Math.floor(d/864e5);return h===0?"Today":h===1?"Yesterday":`${h} days ago`}function fa(t){if(!t)return"text-muted";const a=Xe(t);return a===null?"text-muted":Math.max(0,Date.now()-a)/36e5<24?"text-secondary":"text-muted"}const ba={keyword_match:"Keyword match",competitor_gap:"Competitor gap",keyword_competitor_gap:"Keyword + competitor",high_citation_competitor_gap:"High-value gap",manual_response:"Marked responded"};function ya(t){return t?ba[t]||t.replace(/_/g," "):"Opportunity"}function Dt(t){return t>=1e3?`${(t/1e3).toFixed(1)}k`:String(t)}function ga({state:t}){return t==="responded"?e.jsx(Se,{size:12,strokeWidth:2,className:"text-success flex-shrink-0"}):t==="neutral"?e.jsx("span",{className:"inline-block w-3 h-3 rounded-full border border-faint flex-shrink-0"}):e.jsxs("span",{className:"relative inline-flex items-center justify-center w-3 h-3 flex-shrink-0",title:"Opportunity - a thread worth joining",children:[e.jsx("span",{className:"absolute inset-0 rounded-full border border-accent/40"}),e.jsx("span",{className:"w-1 h-1 rounded-full bg-accent"})]})}function ja(t,a,d){const h=(d||"").trim().toLowerCase(),u=t.mentions.filter(i=>!i.is_own_brand).map(i=>i.mentioned_name),v=a?.competitor_names??[],p=new Set;return[...u,...v].filter(i=>{const y=(i||"").trim().toLowerCase();return!y||y===h||p.has(y)?!1:(p.add(y),!0)})}function va({item:t,brandName:a,isSelected:d,isChecked:h,isFocused:u,opportunity:v,onClick:p,onToggleSelect:i,onDraft:y,onDismiss:S,onMarkResponded:j,draftsRemaining:w=0}){const N=!!v&&!v.is_dismissed&&!v.responded_at,R=!!v?.responded_at,O=R?"responded":N?"open":"neutral",f=pa(t.created_utc),b=t.summary||t.selftext||"",m=ja(t,v,a),M=m.slice(0,2),K=m.length-M.length,C=(a||"").trim().toLowerCase(),z=t.matched_triggers?.find(A=>A.trim().toLowerCase()!==C),I=!!y&&w>0,B=[{id:"open",label:"View thread detail",icon:e.jsx(dt,{size:13}),onClick:p},...t.url?[{id:"reddit",label:"Open on Reddit",icon:e.jsx(Wt,{size:13}),shortcut:"O",href:t.url,target:"_blank",rel:"noreferrer",divider:!0}]:[],{id:"copy-title",label:"Copy title",icon:e.jsx(ve,{size:13}),onClick:async()=>{await de(t.title)?k.copied():k.error("Couldn't copy the title")}},...t.url?[{id:"copy-url",label:"Copy URL",icon:e.jsx(Ht,{size:13}),onClick:async()=>{await de(t.url)?k.copied():k.error("Couldn't copy the URL")},divider:!!(I||N&&S||!R&&j)}]:[],...y?[{id:"draft",label:"Draft a response",icon:e.jsx(ct,{size:13}),shortcut:"D",onClick:y,disabled:!I,description:I?void 0:"The monthly draft limit has been reached."}]:[],...!R&&j?[{id:"responded",label:"Mark as responded",icon:e.jsx(Ws,{size:13}),onClick:j}]:[],...N&&S?[{id:"dismiss",label:"Dismiss opportunity",icon:e.jsx(He,{size:13}),variant:"danger",onClick:S}]:[]];return e.jsx(Fe,{items:B,triggerClassName:"h-full",children:e.jsxs("article",{className:_("group relative h-full overflow-hidden border bg-surface text-left transition-colors duration-250 focus-within:ring-2 focus-within:ring-accent/30",d?"border-accent ring-1 ring-accent/30":h?"border-accent/60":u?"border-hover bg-muted/20":"border-default hover:border-hover"),children:[i&&e.jsx("input",{type:"checkbox",checked:!!h,"aria-label":`Select ${t.title}`,className:_("absolute right-10 top-3 z-[2] size-4 cursor-pointer accent-accent transition-opacity duration-150",h?"opacity-100":"opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 [@media(hover:none)]:opacity-100"),onClick:A=>A.stopPropagation(),onChange:A=>
1{A.stopPropagation(),i("shiftKey"in A.nativeEvent&&A.nativeEvent.shiftKey===!0)}}),e.jsx(qe,{items:B,label:`More actions for ${t.title}`,className:"absolute right-1.5 top-1.5 z-[2]"}),e.jsxs("button",{type:"button",onClick:p,"data-thread-id":t.id,className:"flex h-full w-full cursor-pointer flex-col p-4 text-left outline-none",children:[e.jsxs("div",{className:_("mb-2.5 flex items-center gap-2",i?"pr-14":"pr-7"),children:[e.jsx(ga,{state:O}),e.jsxs("span",{className:"text-[11px] font-mono text-accent/80 truncate",children:["r/",t.subreddit_name]}),R&&e.jsx("span",{className:"text-[10px] font-medium px-1.5 py-0.5 rounded border border-success/20 text-success",children:"Responded"}),e.jsx("div",{className:"flex-1"}),e.jsx("span",{className:_("text-[11px] tabular-nums flex-shrink-0",fa(t.created_utc)),children:f})]}),e.jsx("h3",{className:"text-[14px] font-medium text-primary leading-snug line-clamp-2 mb-2.5",children:t.title}),b?e.jsx("p",{className:"text-[12.5px] text-secondary leading-relaxed line-clamp-3 mb-4 flex-1",children:b}):e.jsx("div",{className:"flex-1 min-h-[8px]"}),e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"min-w-0 flex items-center gap-2.5",children:M.length>0?e.jsxs("span",{className:"inline-flex items-center gap-2.5 min-w-0",children:[M.map(A=>e.jsxs("span",{className:"inline-flex items-center gap-1 min-w-0",children:[e.jsx(bs,{name:A,size:13,context:"brand",className:"rounded-[2px]",fallbackClassName:"rounded-[2px]"}),e.jsx("span",{className:"text-[11px] text-secondary truncate max-w-[78px]",children:A})]},A)),K>0&&e.jsxs("span",{className:"text-[11px] text-muted flex-shrink-0",children:["+",K]})]}):z?e.jsxs("span",{className:"inline-flex items-center gap-1.5 min-w-0",children:[e.jsx(Hs,{size:11,strokeWidth:1.5,className:"flex-shrink-0 text-accent/70"}),e.jsx("span",{className:"text-[11px] text-muted truncate max-w-[150px]",children:z})]}):e.jsx("span",{className:"text-[11px] text-muted",children:"Tracked thread"})}),e.jsxs("span",{className:"group/btn inline-flex flex-shrink-0 items-center gap-1 rounded-sm px-1 py-1 text-[11px] font-medium text-muted transition-colors duration-200 group-hover:text-secondary",children:["View thread",e.jsx(Vs,{size:12,className:"transition-transform duration-200 group-hover/btn:translate-x-0.5"})]})]}),(t.score>0||t.num_comments>0)&&e.jsxs("div",{className:"flex items-center gap-3 mt-2 text-[10px] text-muted font-mono tabular-nums",children:[e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(Vt,{size:10})," ",Dt(t.score)]}),e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(dt,{size:10})," ",Dt(t.num_comments)]})]})]})]})})}function wa(t){return t>=1e3?`${(t/1e3).toFixed(1)}k`:t.toLocaleString()}function At({value:t,label:a,loading:d}){return e.jsxs("span",{className:"tabular-nums",children:[d?e.jsx("span",{className:"text-faint",children:"-"}):e.jsx("span",{className:"text-secondary font-medium",children:wa(t)})," ",a]})}function Na({metrics:t,loading:a}){return e.jsxs("div",{className:"hidden xl:flex items-center gap-2 text-[11px] text-muted whitespace-nowrap flex-shrink-0 pl-1",children:[e.jsx(At,{value:t.threads,label:"threads",loading:a}),e.jsx("span",{className:"text-faint",children:"·"}),e.jsx(At,{value:t.mentions,label:"mentions",loading:a}),e.jsx("span",{className:"text-faint",children:"·"}),e.jsxs("span",{className:"tabular-nums",children:[a?e.jsx("span",{className:"text-faint",children:"-"}):e.jsx("span",{className:"text-secondary font-medium",children:t.avgCitation})," avg citation"]})]})}const ka=[{value:"all",label:"All"},{value:"opportunities",label:"Opportunities"},{value:"responded",label:"Responded"}],Et=[{value:"citation",label:"Highest citation"},{value:"newest",label:"Newest"},{value:"comments",label:"Most comments"},{value:"score",label:"Most upvoted"}],Qt=[{value:"all",label:"All"},{value:"own",label:"Your brand"},{value:"competitor",label:"Competitors"},{value:"both",label:"Both"},{value:"none",label:"None"}],Lt=[{value:"any",label:"Any"},{value:"high",label:"High (70+)"},{value:"mid",label:"Mid (40â69)"},{value:"low",label:"Low (<40)"}],It=[{value:7,label:"Last 7 days"},{value:14,label:"Last 14 days"},{value:30,label:"Last 30 days"},{value:60,label:"Last 60 days"},{value:90,label:"Last 90 days"}];function Ot({open:t,children:a,width:d="w-40"}){return e.jsx(Ve,{children:t&&e.jsx(ue.div,{initial:{opacity:0,y:-4}
1,animate:{opacity:1,y:0},exit:{opacity:0,y:-4},transition:{duration:.12},className:_("absolute top-full mt-1 right-0 z-50 bg-white border border-default rounded shadow-[0_1px_3px_0_rgba(0,0,0,0.04)] py-1",d),children:a})})}function Pt({active:t,label:a,suffix:d,disabled:h,onClick:u}){return e.jsxs("button",{type:"button",onClick:()=>{h||u()},disabled:h,className:_("w-full px-3 py-1.5 text-left text-[11px] flex items-center gap-2 transition-colors duration-250",h?"text-muted/50 cursor-not-allowed":t?"text-accent bg-accent-subtle":"text-secondary hover:bg-muted/50"),children:[e.jsx("span",{className:"w-3 flex-shrink-0",children:t&&e.jsx(Se,{size:10,className:"text-accent"})}),e.jsx("span",{className:"flex-1 truncate",children:a}),d&&e.jsx("span",{className:"text-[10px] text-muted",children:d})]})}function Ye({label:t,onRemove:a}){return e.jsxs("button",{onClick:a,className:"h-6 pl-2 pr-1.5 rounded border border-accent/25 bg-accent-subtle text-accent text-[11px] flex items-center gap-1 hover:border-accent/50 transition-colors duration-250 whitespace-nowrap max-w-[160px] group",children:[e.jsx("span",{className:"truncate",children:t}),e.jsx(me,{size:10,className:"flex-shrink-0 opacity-60 group-hover:opacity-100 transition-opacity"})]})}function We({active:t,label:a,onClick:d}){return e.jsx("button",{onClick:d,className:_("h-7 px-2.5 rounded border text-[11px] transition-colors duration-250",t?"border-accent bg-accent-subtle text-accent font-medium":"border-default text-secondary hover:bg-muted/50"),children:a})}function _a({filters:t,searchInput:a,onChange:d,subreddits:h,triggers:u,historyLimit:v,historyIsUnlimited:p=!1,opportunityCount:i,respondedCount:y,metrics:S,metricsLoading:j}){const w=a??t.search,[N,R]=n.useState(!1),[O,f]=n.useState(!1),[b,m]=n.useState(!1),M=n.useRef(null),K=n.useRef(null),C=n.useRef(null);n.useEffect(()=>{function x(l){const Q=l.target;N&&M.current&&!M.current.contains(Q)&&R(!1),O&&K.current&&!K.current.contains(Q)&&f(!1),b&&C.current&&!C.current.contains(Q)&&m(!1)}return document.addEventListener("mousedown",x),()=>document.removeEventListener("mousedown",x)},[N,O,b]),n.useEffect(()=>{if(!N&&!O&&!b)return;function x(l){l.key==="Escape"&&(R(!1),f(!1),m(!1))}return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[N,O,b]);const z=(t.subreddits.length>0?1:0)+(t.keyword?1:0)+(t.mentionType!=="all"?1:0)+(t.citationBand!=="any"?1:0),I=w.trim()!==""||t.preset!=="all"||z>0||t.days!==30||t.sortBy!=="citation",B=x=>{const l=t.subreddits.includes(x)?t.subreddits.filter(Q=>Q!==x):[...t.subreddits,x];d({subreddits:l})},A=()=>{d({search:"",preset:"all",sortBy:"citation",subreddits:[],keyword:void 0,mentionType:"all",citationBand:"any",days:30}),R(!1)},g=Qt.find(x=>x.value===t.mentionType)?.label||"All",T=Lt.find(x=>x.value===t.citationBand)?.label||"Any",E=It.find(x=>x.value===t.days)?.label||`Last ${t.days}d`,H=Et.find(x=>x.value===t.sortBy)?.label||"Highest citation",D=t.subreddits.length===1?`r/${t.subreddits[0]}`:`${t.subreddits.length} subreddits`;return e.jsxs("div",{className:"px-5 py-2 border-b border-default flex items-center gap-2 bg-surface flex-shrink-0 min-h-[48px]",children:[e.jsxs("div",{className:"relative group flex-shrink-0",children:[e.jsx(Gt,{size:14,className:"absolute left-2.5 top-1/2 -translate-y-1/2 text-muted group-focus-within:text-accent transition-colors"}),e.jsx("input",{value:w,onChange:x=>d({search:x.target.value}),placeholder:"Search threads...",className:"w-52 h-8 pl-8 pr-3 rounded border border-default text-[12px] text-primary placeholder:text-muted focus:ring-2 focus:ring-accent/20 focus:border-accent outline-none transition-colors duration-250"})]}),e.jsxs(Ve,{mode:"popLayout",children:[t.subreddits.length>0&&e.jsx(ue.div,{initial:{opacity:0,scale:.9},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.9},transition:{duration:.15},children:e.jsx(Ye,{label:D,onRemove:()=>d({subreddits:[]})})},"sub-chip"),t.keyword&&e.jsx(ue.div,{initial:{opacity:0,scale:.9},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.9},transition:{duration:.15},children:e.jsx(Ye,{label:t.keyword,onRemove:()=>
1d({keyword:void 0})})},"kw-chip"),t.mentionType!=="all"&&e.jsx(ue.div,{initial:{opacity:0,scale:.9},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.9},transition:{duration:.15},children:e.jsx(Ye,{label:g,onRemove:()=>d({mentionType:"all"})})},"mention-chip"),t.citationBand!=="any"&&e.jsx(ue.div,{initial:{opacity:0,scale:.9},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.9},transition:{duration:.15},children:e.jsx(Ye,{label:T,onRemove:()=>d({citationBand:"any"})})},"citation-chip")]}),S&&e.jsx(Na,{metrics:S,loading:j}),e.jsx("div",{className:"flex-1"}),e.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[e.jsx(ia,{items:ka.map(x=>({id:x.value,label:x.label,count:x.value==="opportunities"?i:x.value==="responded"?y:void 0})),selected:new Set([t.preset]),onToggle:x=>d({preset:x}),label:"Filter Reddit threads",size:"sm"}),e.jsxs("div",{className:"relative",ref:M,children:[e.jsxs("button",{onClick:()=>{R(!N),f(!1),m(!1)},className:_("h-8 px-2.5 rounded border text-[12px] transition-colors duration-250 flex items-center gap-1.5",z>0?"border-accent bg-accent-subtle text-accent":"border-default text-secondary hover:bg-muted/50"),children:[e.jsx(Gs,{size:13}),e.jsx("span",{children:"Filter"}),z>0&&e.jsx("span",{className:"min-w-[16px] h-4 px-0.5 rounded-full bg-accent text-white text-[10px] flex items-center justify-center font-medium leading-none",children:z})]}),e.jsx(Ve,{children:N&&e.jsxs(ue.div,{initial:{opacity:0,y:-4},animate:{opacity:1,y:0},exit:{opacity:0,y:-4},transition:{duration:.15},className:"absolute top-full mt-1.5 right-0 z-50 bg-white border border-default rounded shadow-[0_4px_16px_-4px_rgba(0,0,0,0.08)] w-[300px]",children:[e.jsxs("div",{className:"divide-y divide-subtle",children:[e.jsxs("div",{className:"p-3",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-2",children:"Mentions"}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:Qt.map(x=>e.jsx(We,{active:t.mentionType===x.value,label:x.label,onClick:()=>d({mentionType:x.value})},x.value))})]}),e.jsxs("div",{className:"p-3",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-2",children:"Citation score"}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:Lt.map(x=>e.jsx(We,{active:t.citationBand===x.value,label:x.label,onClick:()=>d({citationBand:x.value})},x.value))})]}),h.length>1&&e.jsxs("div",{className:"p-3",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted",children:"Subreddit"}),t.subreddits.length>0&&e.jsx("button",{onClick:()=>d({subreddits:[]}),className:"text-[10px] text-accent hover:underline",children:"Clear"})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5 max-h-[140px] overflow-y-auto",children:h.map(x=>e.jsx(We,{active:t.subreddits.includes(x.subreddit_name),label:`r/${x.subreddit_name}`,onClick:()=>B(x.subreddit_name)},x.id))})]}),u.length>0&&e.jsxs("div",{className:"p-3",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted",children:"Keyword"}),t.keyword&&e.jsx("button",{onClick:()=>d({keyword:void 0}),className:"text-[10px] text-accent hover:underline",children:"Clear"})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5 max-h-[140px] overflow-y-auto",children:u.map(x=>e.jsx(We,{active:t.keyword===x.keyword,label:x.keyword,onClick:()=>d({keyword:t.keyword===x.keyword?void 0:x.keyword})},x.id))})]})]}),z>0&&e.jsx("div",{className:"px-3 py-2 border-t border-default",children:e.jsx("button",{onClick:()=>{d({subreddits:[],keyword:void 0,mentionType:"all",citationBand:"any"})},className:"text-[11px] text-muted hover:text-secondary transition-colors duration-250",children:"Clear all filters"})})]})})]}),e.jsxs("div",{className:"relative",ref:K,children:[e.jsxs("button",{onClick:()=>{f(!O),R(!1),m(!1)},className:_("h-8 px-2.5 rounded border text-[12px] transition-colors duration-250 flex items-center gap-1.5 whitespace-nowrap",t.days!==30?"border-accent bg-accent-subtle text-accent":"border-default text-secondary hover:bg-muted/50"),children:[E,e.jsx(ot,{size:12,className:_(O&&"rotate-180","transition-transform duration-250")})]}),e.jsx(Ot,{open:O,children:It.map(x=>e.jsx(Pt,{active:t.days===x.value,label:x.label,suffix:!p&&x.value>v?"Upgrade":void 0,disabled:!p&&x.value>v,onClick:()=>{d({days:x.value}),f(!1)}},x.value))})]}),e.jsxs("div",{className:"relative",ref:C,children:[e.jsxs("button",{onClick:()=>{m(!b),R(!1),f(!1)},className:_("h-8 px-2.5 rounded border text-[12px] transition-colors duration-250 flex items-center gap-1.5 whitespace-nowrap",t.sortBy!=="citation"?"border-accent bg-accent-subtle text-accent":"border-default text-secondary hover:bg-muted/50"),children:[H,e.jsx(ot,{size:12,className:_(b&&"rotate-180","transition-transform duration-250")})]}),e.jsx(Ot,{open:b,children:Et.map(x=>e.jsx(Pt,{active:t.sortBy===x.value,label:x.label,onClick:()=>{d({sortBy:x.value}),m(!1)}},x.value))})]}),I&&e.jsxs("button",{onClick:A,className:"h-8 px-2 text-[11px] text-muted hover:text-secondary transition-colors duration-250 flex items-center gap-1",children:[e.jsx(me,{size:12})," Clear"]})]})]})}function zt(t){return t>=70?{text:"text-success",bg:"bg-success-subtle",bar:"bg-success"}:t>=40?{text:"text-warning",bg:"bg-warning-subtle",bar:"bg-warning"}:{text:"text-muted",bg:"bg-white",bar:"bg-muted/60"}}const Sa={format:"Format",authority:"Authority",response_quality:"Response quality",engagement:"Engagement",freshness:"Freshness"};function Ca({score:t,factors:a}){const[d,h]=n.useState(!1),u=zt(t);return e.jsxs("div",{children:[e.jsxs("button",{onClick:()=>h(!d),className:"w-full flex items-center justify-between group",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wider text-muted font-medium",children:"Citation score"}),e.jsx("span",{className:_("text-[14px] font-medium tabular-nums tracking-tight font-mono",u.text),children:t})]}),e.jsx("span",{className:"text-[11px] text-muted group-hover:text-secondary transition-colors duration-250",children:d?"Hide":"Details"})]}),e.jsx("div",{className:"h-1 bg-muted/40 rounded-sm overflow-hidden mt-2.5",children:e.jsx("div",{className:_("h-full rounded-sm transition-all duration-500",u.bar),style:{width:`${t}%`}})}),d&&a&&Object.keys(a).length>0&&e.jsx("div",{className:"mt-3.5 space-y-2.5",children:Object.entries(a).map(([v,p])=>{const i=Sa[v]||v.replace(/_/g," "),y=zt(p);return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("span",{className:"text-[11px] text-muted capitalize",children:i}),e.jsx("span",{className:_("text-[11px] font-mono tabular-nums",y.text),children:p})]}),e.jsx("div",{className:"h-1 bg-muted/40 rounded-sm overflow-hidden",children:e.jsx("div",{className:_("h-full rounded-sm transition-all duration-300",y.bar),style:{width:`${p}%`}})})]},v)})})]})}function Ra(t,a){const d=a.filter(i=>i.trim());if(!d.length||!t)return t;const h=d.map(i=>i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|"),u=new RegExp(`(${h})`,"gi"),v=new RegExp(`^(${h})$`,"i");return t.split(u).map((i,y)=>v.test(i)?e.jsx("mark",{className:"bg-accent-subtle text-accent px-0.5 rounded",children:i},y):i)}function Ft({data:t,isLoading:a,isError:d,onRetry:h,onClose:u,onDraft:v,onRespond:p,onDismiss:i,opportunity:y,draftsRemaining:S,draftIsUnlimited:j,draftLimit:w}){const N=!!y?.responded_at,R=t?.thread?.created_utc,[O]=n.useState(()=>Date.now()),f=R?Math.floor((O-new Date(R).getTime())/864e5):0;if(a)return e.jsx("div",{className:"h-full flex items-center justify-center p-8",children:e.jsxs("div",{className:"flex flex-col items-center gap-2.5 -mt-8",children:[e.jsx(Ke,{size:16,strokeWidth:1.5,className:"text-muted animate-spin"}),e.jsx("p",{className:"text-[12px] text-muted",children:"Loading thread"})]})});if(d||!t)return e.jsx("div",{className:"h-full flex items-center justify-center p-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-[13px] text-secondary mb-2",children:"Failed to load thread."}),e.jsx("button",{onClick:h,className:"text-[13px] text-accent hover:underline",children:"Retry"})]})});const b=t.thread,m=(t.matched_triggers||[]).map(C=>C.keyword),M=y&&!y.is_dismissed&&!y.responded_at,K=[...b.url?[{id:"open-reddit",label:"Open on Reddit",icon:e.jsx(lt,{size:13}),href:b.url,target:"_blank",rel:"noreferrer"}]:[],{id:"copy-title",label:"Copy title",icon:e.jsx(ve,{size:13}),onClick:async()=>{await de(b.title??"")?k.copied():k.error("Couldn't copy the title")}},...b.url?[{id:"copy-url",label:"Copy URL",icon:e.jsx(Ht,{size:13}),onClick:async()=>{await de(b.url)?k.copied():k.error("Couldn't copy the URL")}}]:[],...b.summary||b.selftext?[{id:"copy-summary",label:"Copy summary",icon:e.jsx(ve,{size:13}),onClick:async()=>{await de(b.summary||b.selftext||"")?k.copied():k.error("Couldn't copy the summary")}
1,divider:!!(v||M&&i)}]:[],...S>0?[{id:"draft",label:"Draft a response",icon:e.jsx(ct,{size:13}),shortcut:"D",onClick:v}]:[],...!N&&p?[{id:"responded",label:"Mark as responded",icon:e.jsx(Se,{size:13}),onClick:p}]:[],...M&&i?[{id:"dismiss",label:"Dismiss opportunity",icon:e.jsx(He,{size:13}),variant:"danger",onClick:i}]:[]];return e.jsx("div",{className:"h-full overflow-y-auto",children:e.jsxs("div",{className:"p-5",children:[e.jsx(Fe,{items:K,triggerClassName:"w-full",children:e.jsxs("div",{className:"flex items-start justify-between gap-3 pb-4 border-b border-default",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsxs("span",{className:"text-[11px] font-mono text-accent",children:["r/",b.subreddit_name]}),e.jsx("span",{className:"text-[11px] text-muted",children:ha(b.created_utc)})]}),e.jsx("h2",{className:"text-[15px] font-semibold text-primary leading-snug",children:b.title})]}),e.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[e.jsx(qe,{items:K,label:`More actions for ${b.title}`,visibility:"always"}),b.url&&e.jsxs("a",{href:b.url,target:"_blank",rel:"noreferrer",className:"h-8 px-2.5 text-[12px] font-medium border border-default rounded hover:bg-muted/50 text-secondary hover:text-primary flex items-center gap-1.5 transition-colors duration-250",children:["Reddit ",e.jsx(lt,{size:11})]}),e.jsx("button",{type:"button",onClick:u,"aria-label":"Close thread detail",className:"h-8 w-8 rounded hover:bg-muted/50 flex items-center justify-center transition-colors duration-250",children:e.jsx(me,{size:14,className:"text-muted"})})]})]})}),e.jsxs("div",{className:"flex items-center gap-4 text-[11px] text-muted font-mono tabular-nums py-3 border-b border-default",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Vt,{size:11})," ",b.score||0]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(dt,{size:11})," ",b.num_comments||0]}),y&&e.jsx("span",{className:"flex items-center gap-1.5 text-accent text-[10px] font-sans font-medium",children:ya(y.opportunity_type)})]}),f>=7&&e.jsxs("div",{className:"flex items-center gap-2 mt-4 py-2 px-3 rounded bg-warning-subtle",children:[e.jsx(Xs,{size:12,className:"text-warning flex-shrink-0"}),e.jsxs("p",{className:"text-[11px] text-warning",children:[f,"d old - responses to older threads get less visibility."]})]}),e.jsxs("div",{className:"py-4 border-b border-default",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wider text-muted font-medium mb-2",children:"Summary"}),e.jsx("p",{className:"text-[13px] text-secondary leading-relaxed",children:Ra(b.summary||b.selftext||"Summary pending.",m)})]}),y?.reason_text&&e.jsxs("div",{className:"py-4 border-b border-default",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wider text-muted font-medium mb-2",children:"Opportunity"}),e.jsx("p",{className:"text-[13px] text-secondary leading-relaxed",children:y.reason_text}),y.competitor_names?.length>0&&e.jsxs("p",{className:"text-[11px] text-muted mt-1.5",children:["Competitors: ",y.competitor_names.join(", ")]}),e.jsx(us,{to:"/actions?category=reddit",className:"inline-block mt-3 text-[13px] text-secondary hover:text-accent transition-colors duration-250",children:"View actions â"})]}),e.jsxs("div",{className:"py-4 border-b border-default",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wider text-muted font-medium mb-2",children:"Mentioned brands"}),(t.mentions||[]).length===0?e.jsx("p",{className:"text-[11px] text-muted italic",children:"No brand mentions detected."}):e.jsx("div",{className:"flex flex-wrap gap-1.5",children:(t.mentions||[]).map((C,z)=>e.jsxs("span",{className:_("inline-flex items-center gap-1.5 text-[11px] font-medium px-2 py-1 rounded border border-default",C.is_own_brand?"text-accent":"text-secondary"),children:[C.is_own_brand&&e.jsx("span",{className:"w-1 h-1 rounded-full bg-accent flex-shrink-0"}),C.mentioned_name,(C.mention_count||1)>1&&e.jsxs("span",{className:"text-[10px] text-muted",children:[C.mention_count,"x"]})]},`${C.mentioned_name}-${z}`))})]}),(t.matched_triggers||[]).length>0&&e.jsxs("div",{className:"py-4 border-b border-default",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wider text-muted font-medium mb-2",children:"Matched triggers"}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:t.matched_triggers.map((C,z)=>e.jsxs("span",{className:"inline-flex items-center gap-1 text-[11px] px-2 py-1 rounded border border-default bg-white text-secondary",children:[C.keyword,e.jsx("span",{className:"text-[10px] text-muted",children:C.match_type})]},`${C.keyword}-${z}`))})]}),e.jsx("div",{className:"py-4 border-b border-default",children:e.jsx(Ca,{score:b.citation_score||0,factors:t.citation_breakdown||b.citation_factors})}),e.jsxs("div",{className:"flex items-center gap-2 pt-4",children:[e.jsx("button",{onClick:()=>
1v(),disabled:S<=0,className:_("h-8 px-4 rounded text-[12px] font-medium transition-colors duration-250",S>0?"bg-accent-subtle text-accent hover:bg-accent hover:text-white":"border border-default bg-white text-muted cursor-not-allowed"),children:S<=0?"Draft limit reached":"Draft a Response"}),!N&&p&&e.jsxs("button",{onClick:p,className:"h-8 px-3 border border-default rounded text-[12px] font-medium text-secondary hover:text-primary hover:bg-muted/50 transition-colors duration-250 flex items-center gap-1.5",children:[e.jsx(Se,{size:12})," Responded"]}),M&&i&&e.jsxs("button",{onClick:i,className:"h-8 px-3 rounded border border-default text-[12px] font-medium text-muted hover:text-error hover:border-error/30 transition-colors duration-250 flex items-center gap-1.5",children:[e.jsx(He,{size:12})," Dismiss"]}),N&&e.jsxs("span",{className:"h-8 px-3 flex items-center gap-1.5 text-[12px] font-medium text-success",children:[e.jsx(Se,{size:12})," Responded"]})]}),!j&&e.jsxs("p",{className:"text-[11px] text-muted text-center tabular-nums mt-3",children:[Math.max(0,S)," of ",w," drafts remaining this month"]})]})})}function it(t){return t>=7?"text-success":t>=5?"text-warning":"text-error"}function Ma(t){return t>=7?"bg-success":t>=5?"bg-warning":"bg-error"}const Ta={helpfulness:"Helpfulness",specificity:"Specificity",tone:"Tone",non_spammy:"Non-spammy"};function qt({threadTitle:t,threadUrl:a,draftText:d,setDraftText:h,draftGrade:u,isGenerating:v,onGenerate:p,onCopy:i,onBack:y,onMarkResponded:S,opportunity:j,drafts:w,onUseDraft:N,draftAttempts:R,draftsRemaining:O,draftIsUnlimited:f,draftLimit:b}){const[m,M]=n.useState(!1),[K,C]=n.useState(!1),[z,I]=n.useState(!1),B=n.useRef(null),A=n.useRef(null),g=d.trim()?d.trim().split(/\s+/).length:0,T=d.length,E=!!j?.responded_at,H=O>0;n.useEffect(()=>
1{B.current&&(B.current.style.height="auto",B.current.style.height=`${Math.max(200,B.current.scrollHeight)}px`)},[d]),n.useEffect(()=>()=>{A.current&&clearTimeout(A.current)},[]);const D=()=>{p(),I(!0),A.current&&clearTimeout(A.current),A.current=setTimeout(()=>I(!1),3e3)},x=()=>{i(),S&&!E&&C(!0)};return e.jsx("div",{className:"h-full overflow-y-auto",children:e.jsxs("div",{className:"p-5 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("button",{onClick:y,className:"text-[12px] text-secondary hover:text-primary transition-colors duration-250 flex items-center gap-1.5",children:[e.jsx(Zs,{size:12})," Back to thread"]}),t&&e.jsx("span",{className:"text-[11px] text-muted truncate max-w-[180px]",children:t})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wider text-muted mb-2",children:"Draft response"}),e.jsxs("div",{className:"relative",children:[e.jsx("textarea",{ref:B,value:d,onChange:l=>h(l.target.value),className:_("w-full min-h-[180px] border border-default rounded p-3.5 text-[13px] leading-relaxed resize-none","focus:border-accent/40 focus:ring-1 focus:ring-accent/20 transition-colors duration-250 outline-none",v&&"animate-pulse bg-muted/20"),placeholder:v?"Generating draft...":"Draft will appear here.",disabled:v}),v&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-white/60 rounded",children:e.jsxs("div",{className:"flex items-center gap-2 text-[13px] text-accent",children:[e.jsx(Ce,{size:14,className:"animate-spin"}),e.jsxs("span",{children:["Generating best draft (",R>0?`attempt ${R}`:"...",")"]})]})})]}),e.jsxs("div",{className:"mt-2 flex items-center justify-between text-[11px] text-muted tabular-nums",children:[e.jsxs("span",{children:[g," words · ",T," chars"]}),R>0&&e.jsxs("span",{children:[R," attempts"]})]})]}),(u.overall!==void 0||(u.issues?.length??0)>0)&&e.jsxs("div",{className:"border border-default rounded overflow-hidden",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-default flex items-center justify-between",children:[e.jsx("span",{className:"text-[10px] text-muted uppercase tracking-wider font-medium",children:"Quality score"}),e.jsxs("span",{className:_("text-[14px] font-medium font-mono tabular-nums tracking-tight",it(u.overall||0)),children:[Number(u.overall||0).toFixed(1),e.jsx("span",{className:"text-[11px] text-muted font-normal ml-0.5",children:"/10"})]})]}),e.jsxs("div",{className:"p-4 space-y-3",children:[["helpfulness","specificity","tone","non_spammy"].map(l=>{const Q=u[l]??0;return l==="non_spammy"&&u.non_spammy===void 0?null:e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("span",{className:"text-[11px] text-muted",children:Ta[l]||l}),e.jsx("span",{className:_("text-[11px] font-mono tabular-nums",it(Q)),children:Number(Q).toFixed(1)})]}),e.jsx("div",{className:"h-1 bg-muted/40 rounded-sm overflow-hidden",children:e.jsx("div",{className:_("h-full rounded-sm transition-all duration-500",Ma(Q)),style:{width:`${Q*10}%`}})})]},l)}),e.jsx("div",{className:"flex items-center gap-2 pt-1",children:u.disclosure?e.jsxs("span",{className:"flex items-center gap-1.5 text-[11px] text-success",children:[e.jsx(Se,{size:12})," Brand disclosure included"]}):e.jsxs("span",{className:"flex items-center gap-1.5 text-[11px] text-warning",children:[e.jsx(Nt,{size:12})," No brand disclosure"]})}),(u.issues?.length??0)>0&&e.jsx("div",{className:"pt-2 space-y-1",children:u.issues.map((l,Q)=>e.jsxs("p",{className:"text-[11px] text-error flex items-start gap-1.5",children:[e.jsx(Nt,{size:11,className:"mt-0.5 flex-shrink-0"}),l]},Q))}),(u.improvements?.length??0)>0&&e.jsx("div",{className:"pt-1 space-y-1",children:u.improvements.map((l,Q)=>e.jsxs("p",{className:"text-[11px] text-accent flex items-start gap-1.5",children:[e.jsx(Js,{size:11,className:"mt-0.5 flex-shrink-0"}),l]},Q))})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{onClick:D,disabled:v||z||!H,className:"h-8 px-3 border border-default rounded text-[12px] text-secondary hover:text-primary hover:bg-muted/50 flex items-center gap-1.5 disabled:opacity-40 transition-colors duration-250",children:[e.jsx(Ce,{size:12,className:v?"animate-spin":""})," ",H?"Regenerate":"Limit reached"]}),e.jsxs("button",{onClick:x,disabled:!d.trim(),className:"h-8 px-4 bg-accent-subtle text-accent rounded text-[12px] font-medium flex items-center justify-center gap-1.5 disabled:opacity-40 transition-colors duration-250 hover:bg-accent hover:text-white",children:[e.jsx(ve,{size:12})," Copy to clipboard"]})]}),a&&d.trim()&&e.jsxs("a",{href:a,target:"_blank",rel:"noreferrer",className:"flex items-center justify-center gap-1.5 h-8 border border-default rounded text-[12px] text-secondary hover:text-primary hover:bg-muted/50 transition-colors duration-250",children:["Open on Reddit ",e.jsx(lt,{size:11})]}),!f&&e.jsxs("p",{className:"text-[11px] text-muted text-center tabular-nums",children:[Math.max(0,O)," of ",b," drafts remaining this month"]}),K&&S&&!E&&e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 rounded border border-default",children:[e.jsx("p",{className:"text-[11px] text-muted flex-1",children:"Posted this?"}),e.jsx("button",{onClick:()=>{S?.(),C(!1)},className:"text-[11px] font-medium text-accent hover:underline",children:"Mark as responded"}),e.jsx("button",{onClick:()=>C(!1),className:"text-muted hover:text-secondary transition-colors duration-250",children:e.jsx(me,{size:11})})]}),e.jsxs("div",{className:"border-t border-default pt-4",children:[e.jsxs("button",{type:"button",onClick:()=>M(!m),"aria-expanded":m,"aria-controls":"reddit-draft-history",className:"w-full flex items-center justify-between text-[11px] text-secondary hover:text-primary transition-colors duration-250",children:[e.jsxs("span",{children:["Past drafts (",w.length,")"]}),m?e.jsx(ea,{size:12}):e.jsx(ot,{size:12})]}),m&&w.length>0&&e.jsx("div",{id:"reddit-draft-history",className:"mt-3 space-y-2",children:w.map(l=>{const Q=[{id:"use-draft",label:"Use this draft",icon:e.jsx(ta,{size:13}),onClick:()=>N(l)},{id:"copy-draft",label:"Copy draft text",icon:e.jsx(ve,{size:13}),onClick:async()=>{await de(l.draft_text)?k.copied():k.error("Couldn't copy this draft")}}];return e.jsx(Fe,{items:Q,triggerClassName:"w-full",children:e.jsxs("div",{className:"group group/draft relative -mx-1 border-b border-subtle px-1 py-2.5 pr-9 transition-colors duration-250 last:border-b-0 hover:bg-muted/30",children:[e.jsx(qe,{items:Q,label:"More actions for this draft",className:"absolute right-1 top-1"}),e.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[e.jsx("span",{className:"text-[10px] text-muted",children:l.created_at?new Date(l.created_at).toLocaleDateString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}):"Draft"}),l.grade?.overall!==void 0&&e.jsxs("span",{className:_("text-[10px] font-mono tabular-nums",it(l.grade.overall)),children:[Number(l.grade.overall).toFixed(1),"/10"]})]}),e.jsx("p",{className:"text-[11px] text-secondary line-clamp-2 leading-relaxed",children:l.draft_text}),e.jsx("button",{onClick:()=>N(l),className:"text-[10px] text-accent hover:underline mt-1",children:"Use this draft"})]})},l.id)})}),m&&w.length===0&&e.jsx("p",{className:"text-[11px] text-muted mt-2 italic",children:"No past drafts for this thread."})]})]})})}function Da(t){return t>=70?"text-success":t>=40?"text-warning":"text-muted"}function Kt({active:t,payload:a,label:d}){return!t||!a?.length?null:e.jsxs("div",{className:"bg-white border border-default rounded px-3 py-2 shadow-[0_1px_3px_0_rgba(0,0,0,0.04)]",children:[e.jsx("p",{className:"text-[10px] text-muted mb-1",children:d}),a.map((h,u)=>e.jsxs("p",{className:"text-[11px] font-mono tabular-nums",style:{color:h.stroke},children:[h.name,": ",Math.round(h.value)]},u))]})}function Aa(){return e.jsxs("div",{className:"animate-pulse",children:[e.jsx("div",{className:"flex border-b border-default",children:Array.from({length:4}).map((t,a)=>e.jsxs("div",{className:_("flex-1 px-5 py-4",a<3&&"border-r border-default"),children:[e.jsx(q,{className:"h-3 w-16 mb-3"}),e.jsx(q,{className:"h-6 w-14 mb-1"}),e.jsx(q,{className:"h-2 w-12"})]},a))}),e.jsxs("div",{className:"grid grid-cols-3 border-b border-default",children:[e.jsxs("div",{className:"col-span-2 px-8 py-6 border-r border-default",children:[e.jsx(q,{className:"h-3 w-24 mb-4"}),e.jsx(q,{className:"h-[200px] w-full rounded"})]}),e.jsxs("div",{className:"px-6 py-6",children:[e.jsx(q,{className:"h-3 w-28 mb-4"}),e.jsx("div",{className:"space-y-3",children:Array.from({length:5}).map((t,a)=>e.jsx(q,{className:"h-4 w-full"},a))})]})]}),e.jsxs("div",{className:"px-8 py-6",children:[e.jsx(q,{className:"h-3 w-32 mb-4"}),e.jsx(q,{className:"h-[160px] w-full rounded"})]})]})}function Ea({data:t,isLoading:a,isError:d,onRetry:h,onRunScan:u,dataUpdatedAt:v}){if(a)return e.jsx(Aa,{});if(d&&!t)return e.jsx(_e,{kind:"recoverable-error",scope:"section",title:"Couldn't load Reddit analytics",description:"Analytics are temporarily unavailable. Try again in a moment.",action:{label:"Try again",onClick:h,variant:"secondary"}});if(!t)return e.jsx(_e,{kind:"recoverable-error",scope:"section",title:"Reddit analytics are unavailable",description:"Try loading this section again.",action:{label:"Try again",onClick:h,variant:"secondary"}});if(!(t.mention_trend.length>0||t.citation_trend.length>0||t.top_subreddits.length>0||t.opportunity_summary.total>0))return e.jsx(_e,{kind:"initial-empty",scope:"section",title:"No Reddit analytics yet",description:"Run a scan to start building mention, citation, and opportunity trends.",action:{label:"Run scan",onClick:u,variant:"primary"}});const i=Yt(6,.05),y=t.mention_trend.map(w=>({date:w.date.slice(5),brand:w.own_mentions,competitors:w.competitor_mentions})),S=t.citation_trend.map(w=>({date:w.date.slice(5),score:w.avg_citation_score})),j=[{label:"Surfaced",value:t.opportunity_summary.total},{label:"Open",value:t.opportunity_summary.open,highlight:t.opportunity_summary.open>0},{label:"Responded",value:t.opportunity_summary.responded},{label:"Dismissed",value:t.opportunity_summary.dismissed}];return e.jsxs(e.Fragment,{children:[d&&e.jsx(ce,{kind:"stale",scope:"page",title:"Reddit analytics may be out of date",description:"Showing the last analytics we loaded while we reconnect.",timestamp:v?`Last updated ${ke(new Date(v).toISOString())}`:void 0,action:{label:"Try again",onClick:h,variant:"secondary"}}),e.jsxs(Ge,{children:[e.jsx("div",{className:"flex border-b border-default",children:j.map((w,N)=>e.jsx(te,{delay:i[N],direction:"up",distance:8,duration:.35,className:_("flex-1",N<j.length-1&&"border-r border-default"),children:e.jsxs("div",{className:"px-5 py-3",children:[e.jsx("p",{className:"text-[10px] font-medium uppercase tracking-wider text-muted mb-1",children:w.label}),e.jsx("span",{className:_("text-[24px] font-medium font-mono tabular-nums tracking-tight leading-none",w.highlight?"text-accent":"text-primary"),children:e.jsx(ys,{value:w.value,delay:i[N]+.15,duration:800})})]})},w.label))}),e.jsxs("div",{className:"grid grid-cols-3 border-b border-default",children:[e.jsx("div",{className:"col-span-2 px-8 py-6 border-r border-default",children:e.jsxs(te,{delay:i[4],direction:"up",distance:8,children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("p",{className:"text-[10px] font-medium uppercase tracking-wider text-muted",children:"Mention trend"}),y.length>0&&e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("span",{className:"flex items-center gap-1.5 text-[10px] text-muted",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-accent"}),"Your brand"]}),e.jsxs("span",{className:"flex items-center gap-1.5 text-[10px] text-muted",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-warning"}),"Competitors"]})]})]}),y.length>0?e.jsx(_t,{width:"100%",height:200,children:e.jsxs(St,{accessibilityLayer:!0,data:y,margin:{top:0,right:0,left:0,bottom:0},children:[e.jsxs("defs",{children:[e.jsxs("linearGradient",{id:"mentionBrand",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"var(--color-accent)",stopOpacity:.12}),e.jsx("stop",{offset:"100%",stopColor:"var(--color-accent)",stopOpacity:0})]}),e.jsxs("linearGradient",{id:"mentionComp",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"var(--color-warning)",stopOpacity:.08}),e.jsx("stop",{offset:"100%",stopColor:"var(--color-warning)",stopOpacity:0})]})]}),e.jsx(Ct,{dataKey:"date",tick:{fontSize:10,fill:"var(--color-text-muted)"}
1,tickLine:!1,axisLine:!1,interval:"preserveStartEnd"}),e.jsx(Rt,{hide:!0}),e.jsx(Mt,{content:e.jsx(Kt,{})}),e.jsx(nt,{type:"monotone",dataKey:"brand",name:"Your brand",stroke:"var(--color-accent)",strokeWidth:1.5,fill:"url(#mentionBrand)"}),e.jsx(nt,{type:"monotone",dataKey:"competitors",name:"Competitors",stroke:"var(--color-warning)",strokeWidth:1.5,fill:"url(#mentionComp)"})]})}):e.jsx("div",{className:"h-[200px] flex items-center justify-center",children:e.jsx("p",{className:"text-[11px] text-muted",children:"Not enough data to show trends yet."})})]})}),e.jsx("div",{className:"flex flex-col min-h-0",children:e.jsxs(te,{delay:i[5],direction:"up",distance:8,children:[e.jsx("div",{className:"px-6 py-4",children:e.jsx("p",{className:"text-[10px] font-medium uppercase tracking-wider text-muted",children:"Top subreddits"})}),t.top_subreddits.length>0?e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"grid grid-cols-[1fr_72px_96px_72px] gap-x-4 px-6 py-2 border-t border-b border-subtle text-[10px] uppercase tracking-wider text-muted font-medium",children:[e.jsx("span",{children:"Subreddit"}),e.jsx("span",{className:"text-right",children:"Threads"}),e.jsx("span",{className:"text-right",children:"Avg citation"}),e.jsx("span",{className:"text-right",children:"Latest"})]}),t.top_subreddits.map(w=>e.jsxs("div",{className:"grid grid-cols-[1fr_72px_96px_72px] gap-x-4 px-6 py-2.5 text-[11px] border-b border-subtle last:border-b-0 hover:bg-muted/20 transition-colors duration-250",children:[e.jsxs("span",{className:"font-mono text-accent truncate",children:["r/",w.subreddit]}),e.jsx("span",{className:"text-right text-secondary tabular-nums font-mono",children:w.thread_count}),e.jsx("span",{className:_("text-right tabular-nums font-mono",Da(w.avg_citation)),children:w.avg_citation}),e.jsx("span",{className:"text-right text-muted",children:ke(w.latest_thread)})]},w.subreddit))]}):e.jsx("div",{className:"px-6 py-6",children:e.jsx("p",{className:"text-[11px] text-muted",children:"No subreddit data yet."})})]})})]}),e.jsx("div",{className:"px-8 py-6 border-b border-default",children:e.jsxs(te,{delay:.35,direction:"up",distance:8,children:[e.jsx("p",{className:"text-[10px] font-medium uppercase tracking-wider text-muted mb-4",children:"Citation score trend"}),S.length>0?e.jsx(_t,{width:"100%",height:160,children:e.jsxs(St,{accessibilityLayer:!0,data:S,margin:{top:0,right:0,left:0,bottom:0},children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"citationFill",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"var(--color-accent)",stopOpacity:.12}),e.jsx("stop",{offset:"100%",stopColor:"var(--color-accent)",stopOpacity:0})]})}),e.jsx(Ct,{dataKey:"date",tick:{fontSize:10,fill:"var(--color-text-muted)"},tickLine:!1,axisLine:!1,interval:"preserveStartEnd"}),e.jsx(Rt,{hide:!0,domain:[0,100]}),e.jsx(Mt,{content:e.jsx(Kt,{})}),e.jsx(nt,{type:"monotone",dataKey:"score",name:"Avg citation",stroke:"var(--color-accent)",strokeWidth:1.5,fill:"url(#citationFill)"})]})}):e.jsx("div",{className:"h-[160px] flex items-center justify-center",children:e.jsx("p",{className:"text-[11px] text-muted",children:"Not enough data to show trends yet."})})]})})]})]})}const Qa=/^[A-Za-z0-9_]{1,21}$/;function La(t){return t==null?"":t>=1e6?`${(t/1e6).toFixed(1)}m members`:t>=1e3?`${Math.floor(t/1e3)}k members`:`${t} members`}function Zt({onAdd:t,existingNames:a=[],disabled:d=!1,disabledReason:h,isAdding:u=!1,allowDirectEntry:v=!0,className:p,prominent:i=!1}){const[y,S]=n.useState(""),[j,w]=n.useState(!1),[N,R]=n.useState(-1),O=n.useRef(null),f=n.useRef(null),b=n.useRef(null),m=y.trim().replace(/^r\//,""),M=Ia(m,250),{data:K=[],isFetching:C}=Ne({queryKey:["subreddit-search",M],queryFn:()=>Bs(M,5),enabled:M.length>=2&&j,staleTime:6e4,retry:0}),z=a.map(D=>D.toLowerCase()),I=K.filter(D=>!z.includes(D.name.toLowerCase())),B=j&&m.length>=2&&(I.length>0||C),A=D=>{t(D),S(""),R(-1)},g=()=>{N>=0&&N<I.length?A(I[N].name):m&&I.length===1?A(I[0].name):v&&m&&Qa.test(m)&&!z.includes(m.toLowerCase())&&A(m)},T=D=>{D.key==="Enter"?(D.preventDefault(),g()):D.key==="ArrowDown"&&B?(D.preventDefault(),R(x=>Math.min(x+1,I.length-1))):D.key==="ArrowUp"&&B?(D.preventDefault(),R(x=>Math.max(x-1,-1))):D.key==="Escape"&&O.current?.blur()};n.useEffect(()=>{R(-1)},[M]);const E=()=>{b.current&&clearTimeout(b.current),w(!0)},H=()=>{b.current=setTimeout(()=>w(!1),200)};return e.jsxs("div",{className:_("relative",p),children:[e.jsxs("div",{className:_("flex items-center h-[36px] px-3 transition-colors duration-250",i?"border-b border-default":"border-b border-subtle",d&&"opacity-50"),children:[e.jsx(ut,{size:12,className:_("shrink-0 mr-1.5",i?"text-accent":"text-accent/50")}),e.jsx("span",{className:"text-[11px] text-muted shrink-0 select-none mr-0.5",children:"r/"}),e.jsx("input",{ref:O,value:y,onChange:D=>S(D.target.value),onKeyDown:T,onFocus:E,onBlur:H,placeholder:h||(i?"Track a subreddit...":"Add subreddit..."),disabled:d,title:h,className:_("flex-1 min-w-0 text-[12px] bg-transparent outline-none disabled:cursor-not-allowed",i?"placeholder:text-muted":"placeholder:text-muted/40")}),u?e.jsx(Ke,{size:12,className:"animate-spin text-muted shrink-0"}):y.trim()?e.jsx(mt,{size:12,className:_("shrink-0",i?"text-muted":"text-muted/40")}):null]}),B&&e.jsx("div",{ref:f,className:"absolute left-0 right-0 top-[36px] z-20 bg-white border border-default rounded shadow-[0_4px_16px_
1-4px_rgba(0,0,0,0.08)] overflow-hidden",children:C&&I.length===0?e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2.5",children:[e.jsx(Ke,{size:11,className:"animate-spin text-muted"}),e.jsx("span",{className:"text-[11px] text-muted",children:"Searching Reddit..."})]}):I.map((D,x)=>e.jsxs("button",{type:"button",onMouseDown:l=>{l.preventDefault(),A(D.name)},onMouseEnter:()=>R(x),className:_("w-full flex items-center gap-2 px-3 py-2 text-left transition-colors duration-150",x===N?"bg-accent-subtle/40":"hover:bg-muted/40"),children:[e.jsxs("span",{className:"text-[12px] font-mono text-accent truncate",children:["r/",D.name]}),D.subscribers!=null&&e.jsx("span",{className:"text-[10px] text-muted tabular-nums font-mono shrink-0 ml-auto",children:La(D.subscribers)})]},D.name))})]})}function Ia(t,a){const[d,h]=n.useState(t);return n.useEffect(()=>{const u=setTimeout(()=>h(t),a);return()=>clearTimeout(u)},[t,a]),d}function Oa(t){return t>=1e6?`${(t/1e6).toFixed(1)}m`:t>=1e3?`${Math.floor(t/1e3)}k`:String(t)}function Pa({isOpen:t,onClose:a,state:d,subAtLimit:h,trigAtLimit:u,subIsUnlimited:v,trigIsUnlimited:p,subCount:i,trigCount:y,subLimit:S,trigLimit:j,onAddSubreddit:w,onRemoveSubreddit:N,onAddTrigger:R,onRemoveTrigger:O,onReset:f,isResetting:b,isAddingSubreddit:m,isAddingTrigger:M,digestFrequency:K,onUpdateDigestFrequency:C,isUpdatingSettings:z}){const[I,B]=n.useState(""),A=n.useRef(null),g=n.useRef(null),T=ms();n.useEffect(()=>{if(!t)return;const l=Q=>{if(Q.key==="Escape"){a();return}if(Q.key==="Tab"&&g.current){const X=g.current.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');if(X.length===0)return;const se=X[0],xe=X[X.length-1];Q.shiftKey?document.activeElement===se&&(Q.preventDefault(),xe.focus()):document.activeElement===xe&&(Q.preventDefault(),se.focus())}};return window.addEventListener("keydown",l),()=>window.removeEventListener("keydown",l)},[t,a]);const E=n.useMemo(()=>(d?.subreddits||[]).map(l=>l.subreddit_name),[d?.subreddits]),H=()=>{const l=I.trim();!l||M||(R(l),B(""))},D=n.useMemo(()=>[...d?.subreddits||[]].sort((l,Q)=>(Q.subscriber_count??0)-(l.subscriber_count??0)),[d?.subreddits]),x=n.useMemo(()=>[...d?.keyword_triggers||[]].sort((l,Q)=>(Q.match_count??0)-(l.match_count??0)),[d?.keyword_triggers]);return e.jsx(Ve,{children:t&&e.jsxs("div",{className:"fixed inset-0 z-50",onClick:a,children:[e.jsx(ue.div,{initial:{opacity:0}
1,animate:{opacity:1},exit:{opacity:0},transition:{duration:.2},className:"absolute inset-0 bg-black/8"}),e.jsxs(ue.div,{ref:g,role:"dialog","aria-modal":"true","aria-label":"Manage Monitoring",initial:{x:"100%"},animate:{x:0},exit:{x:"100%"},transition:{duration:.3,ease:[.16,1,.3,1]},className:"absolute inset-y-0 right-0 w-full sm:max-w-[420px] bg-white border-l border-default shadow-[0_4px_16px_rgba(0,0,0,0.08)] flex flex-col",onClick:l=>l.stopPropagation(),children:[e.jsxs("div",{className:"h-14 px-5 border-b border-default flex items-center justify-between shrink-0",children:[e.jsx("h3",{className:"text-[15px] font-semibold text-primary",children:"Manage monitoring"}),e.jsx("button",{type:"button",onClick:a,"aria-label":"Close monitoring settings",className:"w-7 h-7 rounded flex items-center justify-center text-muted hover:text-primary hover:bg-muted/60 transition-colors duration-250",children:e.jsx(me,{size:14})})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto",children:[e.jsxs("div",{className:"p-5 space-y-5",children:[e.jsxs("section",{children:[e.jsx("div",{className:"flex items-baseline justify-between mb-2.5",children:e.jsxs("div",{className:"flex items-baseline gap-1.5",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wider text-muted font-medium",children:"Subreddits"}),!v&&e.jsxs("span",{className:_("text-[10px] tabular-nums font-mono",h?"text-error":"text-muted/60"),children:[i,"/",S]})]})}),e.jsxs("div",{className:"border border-default rounded overflow-hidden",children:[e.jsx(Zt,{onAdd:l=>w(l.replace(/^r\//,"")),existingNames:E,disabled:h,disabledReason:h?"Subreddit limit reached - upgrade to add more":void 0,isAdding:m,prominent:!0}),D.length>0&&e.jsx("div",{className:"divide-y divide-subtle",children:D.map(l=>{const Q=()=>{ze({title:`Remove r/${l.subreddit_name}?`,description:"New conversations from this subreddit will no longer be monitored.",confirmLabel:"Remove subreddit",tone:"danger"}).then(se=>{se&&N(l.id)})},X=[{id:"copy",label:`Copy r/${l.subreddit_name}`,icon:e.jsx(ve,{size:13}),onClick:async()=>{await de(`r/${l.subreddit_name}`)?k.copied():k.error("Couldn't copy the subreddit")}},{id:"open",label:"Open on Reddit",icon:e.jsx(Wt,{size:13}),href:`https://reddit.com/r/${l.subreddit_name}`,target:"_blank",rel:"noreferrer",divider:!0},{id:"remove",label:"Remove subreddit",icon:e.jsx(kt,{size:13}),variant:"danger",onClick:Q}];return e.jsx(Fe,{items:X,triggerClassName:"w-full",children:e.jsxs("div",{className:"flex items-center h-[34px] px-3 hover:bg-muted/40 transition-colors duration-250 group",children:[e.jsxs("span",{className:"text-[12px] text-accent font-mono truncate min-w-0 flex-1",children:["r/",l.subreddit_name]}),l.subscriber_count!=null&&e.jsx("span",{className:"text-[10px] text-muted tabular-nums font-mono shrink-0 mr-2",children:Oa(l.subscriber_count)}),e.jsx(qe,{items:X,label:`More actions for r/${l.subreddit_name}`})]})},l.id)})})]}),h&&e.jsx("p",{className:"text-[11px] text-muted mt-2",children:!v&&i>S?`Over limit. Remove ${i-S} to add new subreddits.`:e.jsxs(e.Fragment,{children:["Limit reached."," ",e.jsx("button",{onClick:()=>T(jt({feature:"reddit",reason:"limit"})),className:"text-accent hover:underline",children:"Upgrade"})]})}),D.length===0&&!h&&e.jsx("p",{className:"text-[11px] text-muted mt-2",children:"Add subreddits to start monitoring conversations."})]}),e.jsxs("section",{children:[e.jsx("div",{className:"flex items-baseline justify-between mb-2.5",children:e.jsxs("div",{className:"flex items-baseline gap-1.5",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wider text-muted font-medium",children:"Keyword Triggers"}),!p&&e.jsxs("span",{className:_("text-[10px] tabular-nums font-mono",u?"text-error":"text-muted/60"),children:[y,"/",j]})]})}),e.jsxs("div",{className:"border border-default rounded overflow-hidden",children:[e.jsxs("div",{className:_("flex items-center h-[36px] px-3 transition-colors duration-250",x.length>0?"border-b border-default":"",u&&"opacity-50"),children:[e.jsx(ut,{size:12,className:"text-accent shrink-0 mr-1.5"}),e.jsx("input",{ref:A,value:I,onChange:l=>B(l.target.value),onKeyDown:l=>{l.key==="Enter"&&(l.preventDefault(),H())},placeholder:u?"Keyword limit reached":"Track a keyword...",disabled:u||M,title:u?"Keyword limit reached - upgrade to add more":void 0,className:"flex-1 min-w-0 text-[12px] bg-transparent outline-none placeholder:text-muted disabled:cursor-not-allowed"}),M?e.jsx(Ke,{size:12,className:"animate-spin text-muted shrink-0"}):I.trim()?e.jsx(mt,{size:12,className:"text-muted shrink-0"}):null]}),x.length>0&&e.jsx("div",{className:"divide-y divide-subtle",children:x.map(l
1=>{const Q=()=>{ze({title:`Remove â${l.keyword}â?`,description:"New conversations will no longer be matched against this keyword.",confirmLabel:"Remove keyword",tone:"danger"}).then(se=>{se&&O(l.id)})},X=[{id:"copy",label:"Copy keyword",icon:e.jsx(ve,{size:13}),onClick:async()=>{await de(l.keyword)?k.copied():k.error("Couldn't copy the keyword")},divider:!0},{id:"remove",label:"Remove trigger",icon:e.jsx(kt,{size:13}),variant:"danger",onClick:Q}];return e.jsx(Fe,{items:X,triggerClassName:"w-full",children:e.jsxs("div",{className:"flex items-center h-[34px] px-3 hover:bg-muted/40 transition-colors duration-250 group",children:[e.jsx("span",{className:"text-[12px] text-primary truncate min-w-0 flex-1",children:l.keyword}),(l.match_count??0)>0&&e.jsxs("span",{className:"text-[10px] tabular-nums font-mono shrink-0 mr-2 text-muted",children:[l.match_count," ",l.match_count===1?"match":"matches"]}),e.jsx(qe,{items:X,label:`More actions for ${l.keyword}`})]})},l.id)})})]}),u&&e.jsx("p",{className:"text-[11px] text-muted mt-2",children:!p&&y>j?`Over limit. Remove ${y-j} to add new triggers.`:e.jsxs(e.Fragment,{children:["Limit reached."," ",e.jsx("button",{onClick:()=>T(jt({feature:"reddit",reason:"limit"})),className:"text-accent hover:underline",children:"Upgrade"})]})}),x.length===0&&!u&&e.jsx("p",{className:"text-[11px] text-muted mt-2",children:"Keywords match against thread titles and body text."})]}),e.jsxs("section",{children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wider text-muted font-medium",children:"Email Digest"}),e.jsx("div",{className:"flex items-center gap-1.5 mt-2.5",children:["daily","weekly","monthly","off"].map(l=>e.jsx("button",{onClick:()=>C?.(l),disabled:z,className:_("h-7 px-2.5 rounded border text-[11px] font-medium transition-colors duration-250",K===l?"border-accent bg-accent-subtle text-accent":"border-default text-secondary hover:bg-muted/50"),children:l==="off"?"Off":l.charAt(0).toUpperCase()+l.slice(1)},l))})]})]}),f&&e.jsx("div",{className:"border-t border-default px-5 py-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[13px] font-medium text-primary",children:"Reset monitoring"}),e.jsx("p",{className:"text-[11px] text-muted mt-0.5",children:"Clear all Reddit data and monitoring settings."})]}),e.jsxs("button",{type:"button",onClick:()=>{ze({title:"Reset Reddit monitoring?",description:"This clears saved threads, opportunities, drafts, subreddits, keywords, and digest settings. You will return to setup.",confirmLabel:"Reset monitoring",tone:"danger"}).then(l=>{l&&f()})},disabled:b,className:"h-7 px-2.5 flex items-center gap-1.5 rounded border border-default text-[12px] font-medium text-secondary hover:text-error hover:border-error/30 transition-colors duration-250 disabled:opacity-50",children:[b?e.jsx(Ke,{size:12,className:"animate-spin"}):e.jsx(sa,{size:12}),"Reset"]})]})})]})]})]})})}const Bt=["Analyzing your website...","Finding relevant subreddits...","Generating keyword triggers...","Validating subreddit activity..."];function za({brandName:t,isGenerating:a,isApplying:d,isError:h,suggestions:u,onGenerateSuggestions:v,onApply:p,subLimit:i,trigLimit:y,subIsUnlimited:S,trigIsUnlimited:j}){const[w,N]=n.useState([]),[R,O]=n.useState([]),[f,b]=n.useState([]),[m,M]=n.useState([]),[K,C]=n.useState(0);return n.useEffect(()=>{if(u){N(u.subreddits),O(u.keyword_triggers);const z=S?u.subreddits.length:Math.min(u.subreddits.length,i),I=j?u.keyword_triggers.length:Math.min(u.keyword_triggers.length,y);b(u.subreddits.slice(0,z)),M(u.keyword_triggers.slice(0,I))}},[u,i,y,S,j]),n.useEffect(()=>{if(!a)return;const z=setInterval(()=>{C(I=>(I+1)%Bt.length)},3e3);return()=>clearInterval(z)},[a]),e.jsx("div",{className:"min-h-screen bg-white flex flex-col",children:e.jsxs("div",{className:"max-w-[1800px] mx-auto w-full min-[2000px]:border-l min-[2000px]:border-r border-default flex-1 flex flex-col",children:[e.jsxs("div",{className:"px-8 py-5 border-b border-default flex items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-[20px] font-semibold text-primary tracking-tight",children:"Reddit monitoring"}),e.jsx("p",{className:"text-[13px] text-secondary mt-0.5",children:"The threads that shape AI's answers"})]}),e.jsx(da,{state:a?"waiting":"setup",className:"mt-1"})]}),a?e.jsx(qa,{step:Bt[K]}):u?e.jsx(Ka,{brandName:t,availableSubs:w,availableTriggers:R,selectedSubs:f,selectedTriggers:m,setAvailableSubs:N,setAvailableTriggers:O,setSelectedSubs:b,setSelectedTriggers:M,isApplying:d,onApply:p,subLimit:i,trigLimit:y,subIsUnlimited:S,trigIsUnlimited:j}):e.jsx(Fa,{brandName:t,isError:h,onStart:v})]})})}function Fa({brandName:t,isError:a,onStart:d}){return e.jsx("div",{className:"flex-1 flex justify-center px-8 py-14",children:e.jsx(Ge,{children:e.jsxs("div",{className:"w-full max-w-2xl flex flex-col items-center",children:[e.jsx(te,{delay:.04,className:"w-full",children:e.jsx(oa,{icon:Xt,question:`Which threads teach AI about ${t}?`,description:"We watch the subreddits your buyers read, flag the threads AI cites, and draft replies grounded in your site."})}),e.jsx(te,{delay:.1,className:"w-full",children:e.jsx("div",{className:"mt-8 w-full",children:e.jsx(la,{items:[{icon:Gt,title:"Track mentions",text:`Every mention of ${t} across the subreddits your buyers read.`},{icon:aa,title:"Spot the gaps",text:"Threads AI already cites, where rivals show up and you don't."},{icon:ct,title:"Draft replies",text:"Authentic responses grounded in your site, ready for review."}]})})}),e.jsx(te,{delay:.16,children:e.jsxs("div",{className:"mt-8 flex flex-col items-center",children:[e.jsx("button",{type:"button",onClick:d,className:"btn btn-primary",children:"Start monitoring"}),e.jsx("p",{className:"mt-4 text-[12px] text-muted",children:a?e.jsxs(e.Fragment,{children:["Couldn't generate suggestions."," ",e.jsx("button",{onClick:d,className:"text-accent hover:underline",children:"Retry"})]}):"About two minutes. We suggest subreddits, you approve them."})]})}),e.jsx(te,{delay:.22,className:"w-full",children:e.jsx(ca,{href:"/learn/docs/features/reddit",children:"We never post anything without your approval."})})]})})})}function qa({step:t}){return e.jsx("div",{className:"flex-1 flex items-center justify-center pb-16",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Ce,{size:16,className:"text-accent animate-spin mx-auto mb-3"}),e.jsx("p",{className:"text-[13px] text-secondary",children:t})]})})}function Ka({brandName:t,availableSubs:a,availableTriggers:d,selectedSubs:h,selectedTriggers:u,setAvailableSubs:v,setAvailableTriggers:p,setSelectedSubs:i,setSelectedTriggers:y,isApplying:S,onApply:j,subLimit:w,trigLimit:N,subIsUnlimited:R,trigIsUnlimited:O}){const[f,b]=n.useState(""),m=!R&&h.length>=w,M=!O&&u.length>=N,K=h.length===a.length&&a.length>0,C=u.length===d.length&&d.length>0,z=g=>{const T=g.trim().replace(/^r\//,"");!T||a.includes(T)||m||(v(E=>[T,...E]),i(E=>[T,...E]))},I=g=>{v(T=>T.filter(E=>E!==g)),i(T=>T.filter(E=>E!==g))},B=()=>{const g=f.trim();!g||d.includes(g)||M||(p(T=>[g,...T]),y(T=>[g,...T]),b(""))},A=g=>{p(T=>T.filter(E=>E!==g)),y(T=>T.filter(E=>E!==g))};return e.jsx("div",{className:"flex-1 overflow-y-auto",children:e.jsx("div",{className:"max-w-[1200px] mx-auto px-8 py-10",children:e.jsxs(Ge,{children:[e.jsx(te,{delay:.04,children:e.jsxs("div",{className:"mb-8",children:[e.jsx("h2",{className:"text-[16px] font-semibold tracking-tight text-primary mb-1",children:"Review monitoring setup"}),e.jsxs("p",{className:"text-[13px] text-muted",children:["Recommendations based on ",t,". Deselect any that don't fit, or add your own."]})]})}),e.jsx(te,{delay:.08,children:e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs("div",{className:"border border-default rounded overflow-hidden",children:[e.jsxs("div",{className:"px-5 py-3 border-b border-default flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-baseline gap-1.5",children:[e.jsxs("p",{className:"text-[10px] uppercase tracking-wider text-muted font-medium",children:["Subreddits (",h.length,"/",a.length,")"]}),!R&&e.jsxs("span",{className:_("text-[10px] tabular-nums font-mono",m?"text-error":"text-muted/60"),
1children:["max ",w]})]}),e.jsx("button",{onClick:()=>{if(K)i([]);else{const g=R?a.length:w;i(a.slice(0,g))}},className:"text-[11px] text-accent hover:underline",children:K?"Deselect all":"Select all"})]}),e.jsx(Zt,{onAdd:z,existingNames:a,allowDirectEntry:!1,disabled:m,disabledReason:m?"Subreddit limit reached":void 0}),e.jsx("div",{className:"p-2 space-y-0.5 max-h-[400px] overflow-y-auto",children:a.map(g=>{const T=h.includes(g),E=!T&&m;return e.jsxs("div",{className:"group flex items-center",children:[e.jsxs("label",{"aria-disabled":E,title:E?"Deselect one subreddit to add this.":void 0,className:_("flex items-center gap-3 px-3 py-2 rounded transition-colors duration-250 flex-1 min-w-0",E?"cursor-not-allowed opacity-50":"cursor-pointer",T?"bg-accent-subtle/30":!E&&"hover:bg-muted/40"),children:[e.jsx("input",{type:"checkbox",checked:T,disabled:E,onChange:()=>i(H=>T?H.filter(D=>D!==g):[...H,g]),className:"accent-accent rounded shrink-0"}),e.jsxs("span",{className:"text-[12px] font-mono text-accent truncate",children:["r/",g]})]}),e.jsx("button",{onClick:()=>I(g),className:"shrink-0 w-6 h-6 flex items-center justify-center rounded text-transparent group-hover:text-muted hover:!text-error transition-colors duration-250",children:e.jsx(me,{size:11,strokeWidth:2})})]},g)})})]}),e.jsxs("div",{className:"border border-default rounded overflow-hidden",children:[e.jsxs("div",{className:"px-5 py-3 border-b border-default flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-baseline gap-1.5",children:[e.jsxs("p",{className:"text-[10px] uppercase tracking-wider text-muted font-medium",children:["Keywords (",u.length,"/",d.length,")"]}),!O&&e.jsxs("span",{className:_("text-[10px] tabular-nums font-mono",M?"text-error":"text-muted/60"),children:["max ",N]})]}),e.jsx("button",{onClick:()=>{if(C)y([]);else{const g=O?d.length:N;y(d.slice(0,g))}},className:"text-[11px] text-accent hover:underline",children:C?"Deselect all":"Select all"})]}),e.jsxs("div",{className:_("flex items-center h-[36px] px-3 border-b border-default",M&&"opacity-50"),children:[e.jsx(ut,{size:12,className:"text-accent/50 shrink-0 mr-1.5"}),e.jsx("input",{value:f,onChange:g=>b(g.target.value),onKeyDown:g=>{g.key==="Enter"&&(g.preventDefault(),B())},placeholder:M?"Keyword limit reached":"Add keyword...",disabled:M,title:M?"Deselect one keyword to add another.":void 0,className:"flex-1 min-w-0 text-[12px] bg-transparent outline-none placeholder:text-muted/40 disabled:cursor-not-allowed"}),f.trim()&&!M&&e.jsx(mt,{size:12,className:"text-muted/40 shrink-0"})]}),e.jsx("div",{className:"p-2 space-y-0.5 max-h-[400px] overflow-y-auto",children:d.map(g=>{const T=u.includes(g),E=!T&&M;return e.jsxs("div",{className:"group flex items-center",children:[e.jsxs("label",{"aria-disabled":E,title:E?"Deselect one keyword to add this.":void 0,className:_("flex items-center gap-3 px-3 py-2 rounded transition-colors duration-250 flex-1 min-w-0",E?"cursor-not-allowed opacity-50":"cursor-pointer",T?"bg-accent-subtle/30":!E&&"hover:bg-muted/40"),children:[e.jsx("input",{type:"checkbox",checked:T,disabled:E,onChange:()=>y(H=>T?H.filter(D=>D!==g):[...H,g]),className:"accent-accent rounded shrink-0"}),e.jsx("span",{className:"text-[12px] text-primary truncate",children:g})]}),e.jsx("button",{onClick:()=>A(g),className:"shrink-0 w-6 h-6 flex items-center justify-center rounded text-transparent group-hover:text-muted hover:!text-error transition-colors duration-250",children:e.jsx(me,{size:11,strokeWidth:2})})]},g)})})]})]})}),e.jsx(te,{delay:.12,children:e.jsxs("div",{className:"mt-8 flex items-center gap-4",children:[e.jsx("button",{onClick:()=>j(h,u),disabled:S||h.length===0||u.length===0,className:"h-9 px-5 bg-accent-subtle text-accent rounded text-[13px] font-medium hover:bg-accent hover:text-white transition-colors duration-250 disabled:opacity-40",children:S?"Setting up...":"Start Monitoring"}),e.jsx("span",{className:"text-[11px] text-muted tabular-nums",children:h.length===0||u.length===0?"Need at least 1 subreddit and 1 keyword":`${h.length} subreddits, ${u.length} keywords`})]})})]})})})}
1function Ba({isOnboarded:t,subCount:a,scanStatus:d,isPending:h,isCoolingDown:u}){return t?a===0?"needs-subreddit":d==="queued"||d==="scanning"||h?"busy":u?"cooldown":"ready":"needs-setup"}function $a({activeTab:t,selectedThreadId:a,shouldValidate:d,isLoading:h,isError:u,displayItems:v}){return t!=="threads"||!a||!d||h||u?!1:!v.some(p=>p.id===a)}const Ua=[{id:"reddit",name:"Reddit",checked:!0}],Ya=[{id:"threads",label:"Threads",icon:Xt},{id:"analytics",label:"Analytics",icon:na}];function Wa(t){return t==="newest"||t==="comments"||t==="citation"||t==="score"?t:"citation"}function Ha(t,a){return t==="all"||t==="opportunities"||t==="responded"?t:a==="opportunities"||a==="responded"?a:"all"}function $t(t){return t==="analytics"?"analytics":"threads"}function Va(t){return t==="own"||t==="competitor"||t==="both"||t==="none"?t:"all"}function Ga(t){return t==="high"||t==="mid"||t==="low"?t:"any"}function Xa(t){const a=Number(t);return[7,14,30,60,90].includes(a)?a:30}function Ut(t,a){return t instanceof Ns?t.status===401?"Your session expired. Refresh the page and try again.":t.status===403?"Reddit drafting isn't available for this brand or plan.":t.status===404?"This Reddit thread is no longer available.":t.status===429?"Too many draft requests. Wait a moment and try again.":a:a}function Za(t){if(!t||typeof t!="object")return{};const a=t;if("nativeEvent"in a||"target"in a&&"currentTarget"in a)return{};const d={};return typeof a.search=="string"&&(d.search=a.search),(a.preset==="all"||a.preset==="opportunities"||a.preset==="responded")&&(d.preset=a.preset),(a.mentionType==="all"||a.mentionType==="own"||a.mentionType==="competitor"||a.mentionType==="both"||a.mentionType==="none")&&(d.mentionType=a.mentionType),(a.citationBand==="any"||a.citationBand==="high"||a.citationBand==="mid"||a.citationBand==="low")&&(d.citationBand=a.citationBand),typeof a.days=="number"&&Number.isFinite(a.days)&&(d.days=a.days),(a.sortBy==="newest"||a.sortBy==="comments"||a.sortBy==="citation"||a.sortBy==="score")&&(d.sortBy=a.sortBy),Array.isArray(a.subreddits)&&(d.subreddits=a.subreddits.filter(h=>typeof h=="string"&&h.trim().length>0)),typeof a.keyword=="string"&&(d.keyword=a.keyword),a.keyword===void 0&&(d.keyword=void 0),d}function br(){ps("Reddit");const{showGate:t}=ks(),[a,d]=xs(),h=a.get("refresh")==="true",u=n.useCallback(r=>{d(c=>{const L=new URLSearchParams(c);for(const[U,Z]of Object.entries(r))Z===null||Z===""?L.delete(U):L.set(U,Z);return L},{replace:!0})},[d]),v=a.get("view"),p=a.get("tab"),i=Ha(v,p),y=a.get("thread")||null,S=$t(p),[j,w]=n.useState(S),[N,R]=n.useState(a.get("q")||""),O=n.useDeferredValue(N),[f,b]=n.useState({preset:i,search:O,mentionType:Va(a.get("mention")),citationBand:Ga(a.get("citation")),days:Xa(a.get("days")),sortBy:Wa(a.get("sort")),subreddits:a.getAll("sub"),keyword:a.get("keyword")||void 0}),[m,M]=n.useState(y),[K,C]=n.useState("detail"),[z,I]=n.useState(a.get("manage")==="true"),[B,A]=n.useState(-1),[g,T]=n.useState(new Set),E=n.useRef(-1),[H,D]=n.useState(typeof window<"u"?window.innerWidth>=1024:!0),[x,l]=n.useState(!1),[Q,X]=n.useState(!1),[se,xe]=n.useState(null),[pe,ae]=n.useState(""),[Re,oe]=n.useState({}),[Me,he]=n.useState(0),[Ze,Te]=n.useState(null),De=n.useRef(!0),Be=n.useRef(!1),Ae=n.useRef(null),we=n.useRef(null),ee=n.useRef(!1),s=xa(f,m,j);n.useEffect(()=>{!h||Be.current||s.brandLoading||!s.brandId||!s.hasReddit||(Be.current=!0,s.resetDataMutation.mutate(void 0,{onSettled:()=>{u({refresh:null})}}))},[h,s.brandLoading,s.brandId,s.hasReddit,s.resetDataMutation,u]),n.useEffect(()=>{if(s.brandId){if(we.current===null){we.current=s.brandId;return}we.current!==s.brandId&&(we.current=s.brandId,ee.current=!1,M(null),R(""),b({preset:"all",search:"",mentionType:"all",citationBand:"any",days:30,sortBy:"citation",subreddits:[],keyword:void 0}),C("detail"),I(!1),ae(""),oe({}),he(0),A(-1),Te(null),xe(null))}},[s.brandId]);const G=f.preset==="opportunities"||f.preset==="responded",ne=n.useMemo(()=>{const r=new Map;for(const c of s.opportunities)r.set(c.thread_id,c);return r},[s.opportunities]),$=n.useMemo(()=>{let r;return G?r=s.filteredOpportunities.map(c=>({id:c.thread?.id||c.thread_id,reddit_id:void 0,subreddit_name:c.thread?.subreddit_name||"reddit",title:c.thread?.title||"Untitled",summary:c.thread?.summary||c.reason_text,selftext:void 0,url:c.thread?.url,score:c.thread?.score||0,num_comments:c.thread?.num_comments||0,citation_score:c.thread?.citation_score||0,citation_factors:void 0,created_utc:c.thread?.created_utc||c.created_at,age_label:"",mentions:[],matched_triggers:c.matched_trigger_texts||[],has_own_brand_mention:c.has_own_brand_mention??!1,has_competitor_mention:c.has_competitor_mention??(c.competitor_names?.length??0)>0,_opportunity:c??null})):r=s.feedItems.map(c=>({...c,_opportunity:ne.get(c.id)||null})),!G&&f.keyword&&(r=r.filter(c=>c.matched_triggers?.includes(f.keyword))),r},[G,s.filteredOpportunities,s.feedItems,ne,f.keyword]),Ee=n.useCallback(r=>r&&((r._opportunity??null)||ne.get(r.id))||null,[ne]),V=n.useMemo(()=>m&&(s.filteredOpportunities.find(r=>r.thread_id===m)||ne.get(m)||s.currentOpp)||null,[m,s.filteredOpportunities,ne,s.currentOpp]),fe=G?s.filteredOpportunitiesQuery:s.feedQuery,re=fe.isLoading,le=fe.isError,Je=fe.isFetchNextPageError,ie=s.scanStatus==="queued"||s.scanStatus==="scanning",be=N.trim().length>0,ye=f.preset!=="all"||f.mentionType!=="all"||f.citationBand!=="any"||f.days!==30||f.subreddits.length>0||!!f.keyword,et=s.scanErrorCode==="scan_stale_timeout"||/tim(e|ed)\s?out|marked failed automatically/i.test(s.scanError||""),$e=s.scanRunId||s.scanError||"failed",Ue=s.scanStatus==="failed"&&!et&&se!==$e,tt=s.scanErrorCode==="queue_create_failed"?"Couldn't start the last scan. Try again in a moment.":"Your last scan didn't finish. Try again when you're ready.",o=s.scanProgress?.phase==="fetching"&&s.scanProgress.subreddits_total?{value:s.scanProgress.subreddits_done??0,max:s.scanProgress.subreddits_total,label:"Subreddits scanned"}:s.scanProgress?.phase==="scoring"&&s.scanProgress.threads_total?{value:s.scanProgress.threads_scored??0,max:s.scanProgress.threads_total,label:"Threads scored"}:void 0;n.useEffect(()=>{if(ie)X(!0);else if(s.scanStatus==="completed"&&Q){const r=setTimeout(()=>X(!1),8e3);return()=>clearTimeout(r)}else s.scanStatus==="failed"&&X(!1)},[ie,s.scanStatus,Q]),n.useEffect(()=>{if(s.scanStatus==="completed"){l(!0);const r=setTimeout(()=>l(!1),3e4);return()=>clearTimeout(r)}(s.scanStatus==="queued"||s.scanStatus==="scanning"||s.scanStatus==="failed")&&l(!1)},[s.scanStatus]);const P=n.useCallback(()=>{s.scanMutation.mutate(void 0,{onSuccess:r=>l(r.status!=="queue_failed"),onError:()=>l(!1)})},[s.scanMutation]),F=n.useCallback(()=>{const r=Ba({isOnboarded:s.isOnboarded,subCount:s.subCount,scanStatus:s.scanStatus,isPending:s.scanMutation.isPending,isCoolingDown:x});switch(r){case"needs-setup":k.info("Finish setup first",{description:"Set up monitoring before running your first Reddit scan."});break;case"needs-subreddit":I(!0),k.info("Add a subreddit first",{description:"Choose at least one subreddit before running a scan."});break;case"busy":k.info(s.scanStatus==="queued"?"Scan already queued":"Scan already in progress");break;case"cooldown":k.info("Scan just finished",{description:"Give the feed a moment before running another scan."});break;case"ready":P();break}return r},[s.isOnboarded,s.subCount,s.scanStatus,s.scanMutation,x,P]);n.useEffect(()=>{!s.hasReddit||s.historyIsUnlimited||!s.historyLimit||f.days<=s.historyLimit||(b(r=>r.days===s.historyLimit?r:{...r,days:s.historyLimit}),k.info(`Showing last ${s.historyLimit} days`,{description:`Your plan supports up to ${s.historyLimit} days of Reddit history.`}))},[f.days,s.hasReddit,s.historyLimit,s.historyIsUnlimited]),n.useEffect(()=>{const r=a.get("action");if(!r){Ae.current=null;return}if(Ae.current!==r&&!(s.brandLoading||!s.brandId||!s.hasReddit)){if(Ae.current=r,r==="manage"||r==="add-subreddit"){I(!0),u({action:null,manage:"true"});return}if(r==="scan"){const c=F();u(c==="needs-subreddit"?{action:null,manage:"true"}:{action:null});return}u({action:null})}},[a,s.brandLoading,s.brandId,s.hasReddit,s.isOnboarded,s.scanMutation.isPending,s.scanStatus,s.subCount,F,u]),n.useEffect(()=>{d(r=>{const c=new URLSearchParams(r),L={tab:j!=="threads"?j:null,view:f.preset!=="all"?f.preset:null,thread:m,q:N||null,keyword:f.keyword||null,mention:f.mentionType!=="all"?f.mentionType:null,citation:f.citationBand!=="any"?f.citationBand:null,days:f.days!==30?String(f.days):null,sort:f.
1sortBy!=="citation"?f.sortBy:null,manage:z?"true":null};for(const[U,Z]of Object.entries(L))Z===null||Z===""?c.delete(U):c.set(U,Z);c.delete("sub");for(const U of f.subreddits)c.append("sub",U);return c},{replace:!0})},[j,f,m,z,N,d]),n.useEffect(()=>{De.current=!1},[]),n.useEffect(()=>{b(r=>r.search!==O?{...r,search:O}:r)},[O]);const Y=n.useCallback(()=>{ae(""),oe({}),he(0)},[]),W=n.useCallback(()=>{ee.current=!1,M(null),C("detail"),Y()},[Y]),Qe=n.useCallback(()=>{R(""),b(r=>({...r,preset:"all",search:"",mentionType:"all",citationBand:"any",days:30,subreddits:[],keyword:void 0,sortBy:"citation"})),A(-1),W()},[W]),Jt=n.useCallback(r=>{const c=Za(r);Object.keys(c).length!==0&&(m&&(ee.current=!0),"search"in c&&R(c.search??""),b(L=>{const U={...L,...c};return"search"in c&&(U.search=L.search),U}),A(-1))},[m]);n.useEffect(()=>{$a({activeTab:j,selectedThreadId:m,shouldValidate:ee.current,isLoading:re,isError:le,displayItems:$})&&W()},[j,m,re,le,$,W]);const st=n.useCallback(r=>{ee.current=!0,M(r),C("detail"),Y()},[Y]),Le=n.useCallback(()=>{W()},[W]),Ie=n.useCallback(r=>{const c=typeof r=="string"?r:m;c&&(ee.current=!0,M(c),C("draft"),Y(),s.generateDraftMutation.mutate({threadId:c},{onSuccess:L=>{ae(L.draft_text),oe(L.grade||{}),he(L.attempts||1)},onError:L=>k.error(Ut(L,"Failed to generate draft"))}))},[m,s.generateDraftMutation,Y]),xt=n.useCallback(()=>{m&&s.generateDraftMutation.mutate({threadId:m},{onSuccess:r=>{ae(r.draft_text),oe(r.grade||{}),he(r.attempts||1)},onError:r=>k.error(Ut(r,"Failed to regenerate draft"))})},[m,s.generateDraftMutation]),pt=n.useCallback(async()=>{pe.trim()&&(await de(pe)?k.copied():k.error("Failed to copy",{description:"Try selecting the text manually."}))},[pe]),ht=n.useCallback(r=>{ae(r.draft_text),oe(r.grade||{})},[]),Oe=n.useCallback(async r=>{await ze({title:"Dismiss this opportunity?",description:"It will leave the open queue. You can restore it from the confirmation message.",confirmLabel:"Dismiss opportunity",tone:"danger"})&&(ee.current=!0,s.dismissOppMutation.mutate(r),k.success("Opportunity dismissed",{action:{label:"Undo",onClick:()=>s.restoreOppMutation.mutate(r)}}))},[s.dismissOppMutation,s.restoreOppMutation]),Pe=n.useCallback(r=>{ee.current=!0,s.markRespondedMutation.mutate(r)},[s.markRespondedMutation]),es=n.useCallback((r,c,L)=>{if(L&&E.current>=0){const U=Math.min(E.current,c),Z=Math.max(E.current,c),ds=$.slice(U,Z+1);T(os=>{const yt=new Set(os);for(const ls of ds){const gt=Ee(ls);gt&&yt.add(gt.id)}return yt})}else T(U=>{const Z=new Set(U);return Z.has(r)?Z.delete(r):Z.add(r),Z}),E.current=c},[$,Ee]),ge=n.useCallback(()=>{T(new Set),E.current=-1},[]),ts=n.useCallback(async()=>{const r=Array.from(g);await ze({title:`Dismiss ${r.length} ${r.length===1?"opportunity":"opportunities"}?`,description:"They will leave the open queue. You can restore them from the confirmation message.",confirmLabel:r.length===1?"Dismiss opportunity":"Dismiss opportunities",tone:"danger"})&&(m&&(ee.current=!0),s.bulkDismissOppMutation.mutate(r),k.success(`${r.length} ${r.length===1?"opportunity":"opportunities"} dismissed`,{action:{label:"Undo",onClick:()=>{for(const L of r)s.restoreOppMutation.mutate(L)}}}),ge())},[g,m,s.bulkDismissOppMutation,s.restoreOppMutation,ge]);n.useEffect(()=>{ge()},[f.preset,ge]);const ss=n.useCallback(()=>{ge(),W(),s.resetDataMutation.mutate()},[ge,W,s.resetDataMutation]),at=n.useRef(null);n.useEffect(()=>{const r=window.matchMedia("(min-width: 1024px)"),c=L=>D(L.matches);return D(r.matches),r.addEventListener("change",c),()=>r.removeEventListener("change",c)},[]),n.useEffect(()=>{function r(c){if(!ws(c))switch(c.key){case"j":case"ArrowDown":{if(j!=="threads")return;c.preventDefault(),A(L=>{const U=Math.min(L+1,$.length-1);return at.current?.querySelector(`[data-thread-id="${$[U]?.id}"]`)?.scrollIntoView({block:"nearest",behavior:"smooth"}),U});break}case"k":case"ArrowUp":{if(j!=="threads")return;c.preventDefault(),A(L=>{const U=Math.max(L-1,0);return at.current?.querySelector(`[data-thread-id="${$[U]?.id}"]`)?.scrollIntoView({block:"nearest",behavior:"smooth"}),U});break}case"Enter":{if(j!=="threads")return;if(B>=0&&B<$.length){c.preventDefault();const L=$[B];st(L.id)}break}case"Escape":{c.preventDefault(),K==="draft"?C("detail"):m&&Le();break}case"d":{m&&K==="detail"&&s.draftsRemaining>0&&(c.preventDefault(),Ie());break}
1case"x":{m&&V&&!V.is_dismissed&&(c.preventDefault(),Oe(V.id));break}}}return window.addEventListener("keydown",r),()=>window.removeEventListener("keydown",r)},[j,$,B,m,K,s.draftsRemaining,Le,Oe,st,Ie,V]),n.useEffect(()=>{if(m&&!H)return document.body.style.overflow="hidden",()=>{document.body.style.overflow=""}},[m,H]);const ft=n.useRef(null);n.useEffect(()=>{if(j!=="threads")return;const r=ft.current;if(!r)return;const c=G?s.filteredOpportunitiesQuery:s.feedQuery,L=new IntersectionObserver(U=>{U[0].isIntersecting&&c.hasNextPage&&!c.isFetchingNextPage&&c.fetchNextPage()},{rootMargin:"200px"});return L.observe(r),()=>L.disconnect()},[j,G,s.feedQuery,s.filteredOpportunitiesQuery]);const as=()=>{s.suggestionsMutation.mutate(void 0,{onSuccess:r=>{Te(r.recommended_setup)}})},rs=(r,c)=>{s.applySetupMutation.mutate({subreddits:r,triggers:c})},bt=n.useMemo(()=>{const r=s.draftsQuery.data;return Array.isArray(r)?r.filter(c=>c.thread_id===m):[]},[s.draftsQuery.data,m]),ns=s.opportunitySummary.open,is=s.opportunitySummary.responded;return s.brandLoading?e.jsx("div",{className:"min-h-screen bg-white"}):t||!s.hasReddit?e.jsxs(e.Fragment,{children:[t&&s.hasReddit&&e.jsx("div",{className:"fixed top-4 right-4 z-[100] flex items-center gap-2 px-3 py-1.5 bg-amber-50 border border-amber-200 rounded text-[11px] text-amber-700 font-medium shadow-sm",children:"Gate Preview (ââ§Y to toggle)"}),e.jsx(gs,{})]}):s.brand?s.stateQuery.isLoading?e.jsx("div",{className:"min-h-screen bg-white flex flex-col",children:e.jsxs("div",{className:"max-w-[1800px] mx-auto w-full min-[2000px]:border-l min-[2000px]:border-r border-default flex-1 flex flex-col",children:[e.jsxs("div",{className:"px-8 py-5 border-b border-default flex items-center justify-between",children:[e.jsx(q,{className:"h-6 w-52"}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(q,{className:"h-3 w-24"}),e.jsx(q,{className:"h-8 w-16 rounded"}),e.jsx(q,{className:"h-8 w-20 rounded"})]})]}),e.jsxs("div",{className:"px-8 h-10 border-b border-default flex items-center gap-6",children:[e.jsx(q,{className:"h-3 w-16"}),e.jsx(q,{className:"h-3 w-16"})]}),e.jsxs("div",{className:"px-5 py-2.5 border-b border-default flex items-center gap-3",children:[e.jsx(q,{className:"h-8 w-56 rounded"}),e.jsx(q,{className:"h-8 w-16 rounded"}),e.jsx(q,{className:"h-8 w-24 rounded"})]}),e.jsx("div",{className:"divide-y divide-subtle flex-1",children:Array.from({length:8}).map((r,c)=>e.jsxs("div",{className:"px-5 py-3 space-y-2 animate-pulse",style:{animationDelay:`${c*50}ms`},children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(q,{className:"h-3 w-16"}),e.jsx(q,{className:"h-3 w-12"})]}),e.jsx(q,{className:"h-4 w-full"}),e.jsx(q,{className:"h-3 w-3/4"})]},c))})]})}):s.stateQuery.isError&&!s.stateQuery.data?e.jsx("div",{className:"min-h-screen bg-white flex flex-col",children:e.jsxs("div",{className:"max-w-[1800px] mx-auto w-full min-[2000px]:border-l min-[2000px]:border-r border-default min-h-screen flex flex-col",children:[e.jsxs("div",{className:"px-8 py-5 border-b border-default",children:[e.jsx("h1",{className:"text-[20px] font-semibold text-primary tracking-tight",children:"Reddit monitoring"}),e.jsx("p",{className:"text-[13px] text-secondary mt-0.5",children:"Track discussions shaping what AI says about your brand"})]}),e.jsx(_e,{kind:"recoverable-error",scope:"page",title:"Couldn't load Reddit monitoring",description:"Monitoring is temporarily unavailable. Try again in a moment.",action:{label:"Try again",onClick:()=>{s.stateQuery.refetch()},variant:"secondary"},className:"flex-1"})]})}):s.isOnboarded?e.jsxs("div",{className:"h-screen bg-white flex flex-col overflow-hidden",children:[e.jsxs("div",{className:"max-w-[1800px] mx-auto w-full min-[2000px]:border-l min-[2000px]:border-r border-default flex-1 flex flex-col overflow-hidden",children:[e.jsxs("div",{className:"flex-shrink-0 bg-surface",children:[e.jsxs("div",{className:"px-8 py-5 flex items-center justify-between",children:[e.jsx("h1",{className:"text-[20px] font-semibold text-primary tracking-tight",children:"Reddit monitoring"}),e.jsxs("div",{className:"flex items-center gap-3",children:[s.lastScanAt&&(s.scanStatus==="queued"||s.scanStatus==="scanning"?e.jsx("span",{className:"text-[11px] text-muted",children:s.scanStatus==="queued"?"Queued...":"Scanning..."}):s.statsQuery.dataUpdatedAt>0?e.jsx(vs,{updatedAt:new Date(s.statsQuery.dataUpdatedAt).toISOString(),variant:"inline",label:`Last scan ${
1ke(s.lastScanAt)}`,provenance:{lastChecked:new Date(s.statsQuery.dataUpdatedAt).toISOString(),platforms:Ua,sourcesLabel:"Channels Monitored",coverage:{threads:s.statsQuery.data?.active_threads||void 0},methodologyKey:"reddit"}}):e.jsxs("span",{className:"text-[11px] text-muted",children:["Last scan ",ke(s.lastScanAt)]})),ie?e.jsxs("div",{className:"h-8 px-2.5 flex items-center gap-1.5 rounded border border-default text-[12px] font-medium text-muted",children:[e.jsx(Ce,{size:14,className:"animate-spin"}),s.scanStatus==="queued"?"Queued":"Scanning"]}):e.jsxs("button",{onClick:F,disabled:x||s.scanMutation.isPending,className:"h-8 px-2.5 flex items-center gap-1.5 rounded border border-default text-[12px] font-medium text-secondary hover:bg-muted/50 transition-colors duration-250 disabled:opacity-40",children:[e.jsx(Ce,{size:14,className:s.scanMutation.isPending?"animate-spin":""}),"Scan"]}),e.jsxs("button",{onClick:()=>I(!0),className:"h-8 px-2.5 flex items-center gap-1.5 rounded border border-default text-[12px] font-medium text-secondary hover:bg-muted/50 transition-colors duration-250",children:[e.jsx(ra,{size:14}),"Manage"]})]})]}),e.jsx("div",{className:"px-8 h-10 flex items-center border-b border-default",children:e.jsx($s,{tabs:Ya,activeTab:j,ariaLabel:"Reddit monitoring sections",idBase:"reddit-monitoring",onTabChange:r=>{const c=$t(r);w(c),c==="analytics"&&W()},layoutId:"reddit-tabs"})})]}),(Q||ie||Ue)&&!(ie&&j==="threads"&&!re&&$.length===0)&&e.jsxs(e.Fragment,{children:[s.scanStatus==="queued"&&e.jsx(ce,{kind:"delayed",scope:"page",className:"flex-shrink-0 border-b border-default",title:"Scan queued",description:"The scan is waiting for a worker. You can leave this page."}),s.scanStatus==="scanning"&&e.jsx(ce,{kind:"delayed",scope:"page",className:"flex-shrink-0 border-b border-default",title:s.scanProgress?.phase==="storing"?"Saving scan results":"Reddit scan in progress",description:e.jsxs("div",{children:[e.jsxs("p",{children:[s.scanProgress?.phase==="fetching"&&s.scanProgress.current_subreddit?`Scanning r/${s.scanProgress.current_subreddit}.`:s.scanProgress?.phase==="scoring"&&s.scanProgress.threads_total?`Scoring threads (${s.scanProgress.threads_scored??0}/${s.scanProgress.threads_total}).`:s.scanProgress?.phase==="storing"?"The scan finished collecting threads and is saving them now.":"The scan is running in the background.",e.jsx("span",{className:"ml-1 text-muted",children:"You can leave this page."})]}),o&&o.max>0&&e.jsxs("div",{className:"mt-2 flex items-center gap-3",children:[e.jsx("div",{role:"progressbar","aria-label":o.label,"aria-valuemin":0,"aria-valuemax":o.max,"aria-valuenow":o.value,className:"h-1 flex-1 overflow-hidden rounded-sm bg-muted",children:e.jsx("div",{className:"h-full rounded-sm bg-accent transition-[width] duration-500 motion-reduce:transition-none",style:{width:`${Math.min(100,o.value/o.max*100)}%`}})}),e.jsxs("span",{className:"text-[11px] tabular-nums text-muted",children:[o.value,"/",o.max]})]})]})}),s.scanStatus==="completed"&&Q&&e.jsx(ce,{kind:"completion",scope:"page",className:"flex-shrink-0 border-b border-default",title:"Scan complete",description:"New threads are ready to review.",onDismiss:()=>X(!1)}),Ue&&e.jsx(ce,{kind:"mutation-error",scope:"page",className:"flex-shrink-0 border-b border-default",title:"Scan didn't finish",description:tt,action:{label:"Try again",onClick:F,variant:"secondary",disabled:s.scanMutation.isPending},onDismiss:()=>xe($e)})]}),s.stateQuery.isError&&s.stateQuery.data&&e.jsx(ce,{kind:"stale",scope:"page",className:"flex-shrink-0 border-b border-default",title:"Monitoring settings may be out of date",description:"Showing the last settings we loaded while we reconnect.",timestamp:s.stateQuery.dataUpdatedAt?`Last updated ${ke(new Date(s.stateQuery.dataUpdatedAt).toISOString())}`:void 0,action:{label:"Try again",onClick:()=>{s.stateQuery.refetch()},variant:"secondary"}}),j==="threads"&&e.jsxs("section",{id:"reddit-monitoring-panel-threads",role:"tabpanel","aria-labelledby":"reddit-monitoring-tab-threads",tabIndex:0,className:"focus-ring flex flex-1 min-h-0 flex-col overflow-hidden",children:[e.jsx(_a,{filters:f,searchInput:N,onChange:Jt,subreddits:s.stateQuery.data?.subreddits||[],triggers:s.stateQuery.data?.keyword_triggers||[],historyLimit:s.historyLimit,historyIsUnlimited:s.historyIsUnlimited,opportunityCount:ns,respondedCount:is,metrics:{threads:s.statsQuery.data?.active_threads??0,mentions:s.statsQuery.data?.your_mentions??0,avgCitation:s.statsQuery.data?.avg_citation_score??0},metricsLoading:s.statsQuery.isLoading}),e.jsxs("div",{className:"flex flex-1 min-h-0 overflow-hidden",children:[e.jsxs("div",{ref:at,className:_("overflow-y-auto flex-shrink-0 transition-all duration-200",m?"w-[420px] min-w-[320px] border-r border-default hidden lg:block":"w-full"),children:[re&&e.jsx("div",{className:"p-5 grid gap-4 content-start",style:{gridTemplateColumns:"repeat(auto-fill, minmax(340px, 1fr))"},children:Array.from({length:9}).map((r,c)=>e.jsxs("div",{className:"bg-surface border border-default rounded p-4 space-y-3",style:{animationDelay:`${c*50}ms`},children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(q,{className:"h-3 w-3 rounded-full"}),e.jsx(q,{className:"h-3 w-20"})]}),e.jsx(q,{className:"h-4 w-full"}),e.jsx(q,{className:"h-3 w-5/6"}),e.jsx(q,{className:"h-3 w-2/3"}),e.jsxs("div",{className:"pt-3 flex items-center justify-between",children:[e.jsx(q,{className:"h-3 w-24"}),e.jsx(q,{className:"h-3 w-14"})]}),e.jsx(q,{className:"h-8 w-full rounded"})]},c))}),le&&!re&&$.length===0&&e.jsx(_e,{kind:"recoverable-error",scope:"section",title:`Couldn't load ${G?"opportunities":"threads"}`,description:"Reddit data is temporarily unavailable. Try again in a moment.",action:{label:"Try again",onClick:()=>{G?s.filteredOpportunitiesQuery.refetch():s.feedQuery.refetch()},variant:"secondary"}}),!re&&!le&&$.length===0&&ie&&e.jsx("div",{className:"p-5 sm:p-8",children:e.jsx(Us,{phase:s.scanStatus==="queued"?"queued":"running",title:s.scanStatus==="queued"?"Reddit scan queued":s.scanProgress?.phase==="storing"?"Saving scan results":"Scanning Reddit",description:s.scanProgress?.phase==="fetching"&&s.scanProgress.current_subreddit?`Scanning r/${s.scanProgress.current_subreddit}.`:s.scanProgress?.phase==="scoring"?"Scoring the threads found so far.":s.scanProgress?.phase==="storing"?"The scan finished collecting threads and is saving them now.":"New threads will appear here as soon as the scan finishes.",progress:o,knownInputs:`${s.subCount} tracked subreddit${s.subCount===1?"":"s"} and ${s.trigCount} keyword trigger${s.trigCount===1?"":"s"}`,safeToLeaveMessage:"You can leave this page. The scan will keep running in the background."})}),!re&&!le&&$.length===0&&!ie&&e.jsx(_e,{kind:be?"search-empty":ye?"filtered-empty":"initial-empty",scope:"section",title:be?"No threads match this search":ye?"No threads match these filters":"No Reddit threads yet",description:be||ye?"Clear the current filters to
1see all monitored discussions.":s.subCount===0?"Add subreddits and keywords to start monitoring discussions.":"Run a scan to look for new discussions.",action:be||ye?{label:"Clear filters",onClick:Qe,variant:"secondary"}:s.subCount===0?{label:"Edit monitoring",onClick:()=>I(!0),variant:"primary"}:{label:"Run scan",onClick:F,variant:"primary",disabled:x||s.scanMutation.isPending},secondaryAction:!be&&!ye&&s.subCount>0?{label:"Edit monitoring",onClick:()=>I(!0),variant:"ghost"}:void 0}),le&&$.length>0&&e.jsx("div",{className:"px-5 pt-5",children:e.jsx(ce,{kind:"stale",scope:"section",title:`Couldn't refresh ${G?"opportunities":"threads"}`,description:"Showing the last Reddit data we loaded.",timestamp:fe.dataUpdatedAt?`Last updated ${ke(new Date(fe.dataUpdatedAt).toISOString())}`:void 0,action:{label:"Try again",onClick:()=>{G?s.filteredOpportunitiesQuery.refetch():s.feedQuery.refetch()},variant:"secondary"}})}),!re&&$.length>0&&e.jsx("div",{className:"p-5 grid gap-4 content-start",style:{gridTemplateColumns:"repeat(auto-fill, minmax(340px, 1fr))"},children:e.jsx(Ge,{enabled:De.current,children:$.map((r,c)=>{const L=Ee(r);return e.jsx(te,{className:"h-full",delay:De.current?Yt(Math.min($.length,10),.03)[Math.min(c,9)]:0,children:e.jsx(va,{item:r,brandName:s.brand?.name,isSelected:r.id===m,isChecked:G&&L?g.has(L.id):void 0,isFocused:c===B,opportunity:L,onClick:()=>{st(r.id),A(c)},onToggleSelect:G&&L?U=>es(L.id,c,U):void 0,onDraft:()=>{Ie(r.id)},onDismiss:L&&!L.is_dismissed?()=>Oe(L.id):void 0,onMarkResponded:L?.responded_at?void 0:()=>Pe(r.id),draftsRemaining:s.draftsRemaining})},r.id)})})}),e.jsx("div",{ref:ft,className:"h-px"}),Je&&$.length>0&&e.jsx("div",{className:"px-5 py-4",children:e.jsx(ce,{kind:"partial",scope:"section",title:"Couldn't load more Reddit threads",description:"The threads already shown are still available.",action:{label:"Try again",onClick:()=>{G?s.filteredOpportunitiesQuery.fetchNextPage():s.feedQuery.fetchNextPage()},variant:"secondary"}})}),(G?s.filteredOpportunitiesQuery.isFetchingNextPage:s.feedQuery.isFetchingNextPage)&&e.jsxs("div",{className:"py-4 flex items-center justify-center gap-2 text-[11px] text-muted",children:[e.jsx(Ce,{size:11,className:"animate-spin"}),"Loading more..."]}),!G&&!s.feedQuery.hasNextPage&&$.length>0&&!s.feedQuery.isLoading&&e.jsxs("div",{className:"py-4 text-center text-[11px] text-muted",children:[s.feedTotal," threads loaded"]})]}),m&&H&&e.jsx("div",{className:"flex-1 min-w-0 bg-white overflow-y-auto",children:K==="detail"?e.jsx(Ft,{data:s.threadDetailQuery.data,isLoading:s.threadDetailQuery.isLoading,isError:s.threadDetailQuery.isError,onRetry:()=>s.threadDetailQuery.refetch(),onClose:Le,onDraft:Ie,onRespond:m&&!V?.responded_at?()=>Pe(m):void 0,onDismiss:V&&!V.is_dismissed?()=>Oe(V.id):void 0,opportunity:V,draftsRemaining:s.draftsRemaining,draftIsUnlimited:s.draftIsUnlimited,draftLimit:s.draftLimit}):e.jsx(qt,{threadTitle:s.threadDetailQuery.data?.thread?.title,threadUrl:s.threadDetailQuery.data?.thread?.url,draftText:pe,setDraftText:ae,draftGrade:Re,isGenerating:s.generateDraftMutation.isPending,onGenerate:xt,onCopy:pt,onBack:()=>C("detail"),onMarkResponded:m&&!V?.responded_at?()=>Pe(m):void 0,opportunity:V,drafts:bt,onUseDraft:ht,draftAttempts:Me,draftsRemaining:s.draftsRemaining,draftIsUnlimited:s.draftIsUnlimited,draftLimit:s.draftLimit})}),m&&!H&&e.jsxs("div",{className:"fixed inset-0 z-40 bg-white overflow-y-auto",children:[e.jsx("div",{className:"h-[48px] px-4 border-b border-default flex items-center",children:e.jsxs("button",{onClick:Le,className:"text-[12px] text-secondary hover:text-primary flex items-center gap-1.5",children:[e.jsx(me,{size:14})," Close"]})}),K==="detail"?e.jsx(Ft,{data:s.threadDetailQuery.data,isLoading:s.threadDetailQuery.isLoading,isError:s.threadDetailQuery.isError,onRetry:()=>s.threadDetailQuery.refetch(),onClose:Le,onDraft:Ie,onRespond:m&&!V?.responded_at?()=>Pe(m):void 0,onDismiss:V&&!V.is_dismissed?()=>Oe(V.id):void 0,opportunity:V,draftsRemaining:s.draftsRemaining,draftIsUnlimited:s.draftIsUnlimited,draftLimit:s.draftLimit}):e.jsx(qt,{threadTitle:s.threadDetailQuery.data?.thread?.title,threadUrl:s.threadDetailQuery.data?.thread?.url,draftText:pe,setDraftText:ae,draftGrade:Re,isGenerating:s.generateDraftMutation.isPending,onGenerate:xt,onCopy:pt,onBack:()=>C("detail"),onMarkResponded:m&&!V?.responded_at?()=>Pe(m):void 0,opportunity:V,drafts:bt,onUseDraft:ht,draftAttempts:Me,draftsRemaining:s.draftsRemaining,draftIsUnlimited:s.draftIsUnlimited,draftLimit:s.draftLimit})]})]})]}),j==="analytics"&&e.jsx("section",{id:"reddit-monitoring-panel-analytics",role:"tabpanel","aria-labelledby":"reddit-monitoring-tab-analytics",tabIndex:0,className:"focus-ring flex-1 overflow-y-auto",children:e.jsx(Ea,{data:s.analyticsQuery.data,isLoading:s.analyticsQuery.isLoading,isError:s.analyticsQuery.isError,onRetry:()=>s.analyticsQuery.refetch(),onRunScan:F,dataUpdatedAt:s.analyticsQuery.dataUpdatedAt})})]}),e.jsx(Pa,{isOpen:z,onClose:()=>I(!1),state:s.stateQuery.data,subAtLimit:s.subAtLimit,trigAtLimit:s.trigAtLimit,subIsUnlimited:s.subIsUnlimited,trigIsUnlimited:s.trigIsUnlimited,subCount:s.subCount,trigCount:s.trigCount,subLimit:s.subLimit,trigLimit:s.trigLimit,onAddSubreddit:r=>s.addSubredditMutation.mutate(r),onRemoveSubreddit:r=>s.removeSubredditMutation.mutate(r),onAddTrigger:r=>s.addTriggerMutation.mutate(r),onRemoveTrigger:r=>s.removeTriggerMutation.mutate(r),onReset:ss,isResetting:s.resetDataMutation.isPending,isAddingSubreddit:s.addSubredditMutation.isPending,isAddingTrigger:s.addTriggerMutation.isPending,digestFrequency:s.stateQuery.data?.settings?.digest_frequency||"off",onUpdateDigestFrequency:r=>s.updateSettingsMutation.mutate({digestFrequency:r}),isUpdatingSettings:s.updateSettingsMutation.isPending}),e.jsx(Ys,{selectedCount:g.size,actions:[{id:"dismiss",label:"Dismiss",icon:e.jsx(He,{size:14}),variant:"danger",onClick:ts,disabled:s.bulkDismissOppMutation.isPending}],onClear:ge,label:"opportunities"}),j==="threads"&&$.length>0&&e.jsxs("div",{className:"fixed bottom-4 right-4 hidden lg:flex items-center gap-2.5 px-2.5 py-1.5 border border-default bg-white text-[10px] text-muted rounded shadow-[0_1px_3px_0_rgba(0,0,0,0.04)]",children:[!m&&e.jsxs(e.Fragment,{children:[e.jsxs("span",{children:[e.jsx("kbd",{className:"font-mono text-[9px]",children:"J"}),"/",e.jsx("kbd",{className:"font-mono text-[9px]",children:"K"})," navigate"]}),e.jsxs("span",{children:[e.jsx("kbd",{className:"font-mono text-[9px]",children:"Enter"})," open"]})]}),m&&e.jsxs(e.Fragment,{children:[e.jsxs("span",{children:[e.jsx("kbd",{className:"font-mono text-[9px]",children:"D"})," draft"]}),e.jsxs("span",{children:[e.jsx("kbd",{className:"font-mono text-[9px]",children:"X"})," dismiss"]})]}),e.jsxs("span",{children:[e.jsx("kbd",{className:"font-mono text-[9px]",children:"Esc"})," close"]})]})]}):e.jsx(za,{brandName:s.brand.name,isGenerating:s.suggestionsMutation.isPending,isApplying:s.applySetupMutation.isPending,isError:s.suggestionsMutation.isError,suggestions:Ze,onGenerateSuggestions:as,onApply:rs,subLimit:s.subLimit,trigLimit:s.trigLimit,subIsUnlimited:s.subIsUnlimited,trigIsUnlimited:s.trigIsUnlimited}):e.jsx("div",{className:"min-h-screen bg-surface",children:e.jsxs("div",{className:"max-w-[1800px] mx-auto w-full min-[2000px]:border-l min-[2000px]:border-r border-default min-h-screen flex flex-col",children:[e.jsxs("div",{className:"px-8 py-5 border-b border-default",children:[e.jsx("h1",{className:"text-[20px] font-semibold text-primary tracking-tight",children:"Reddit monitoring"}),e.jsx("p",{className:"text-[13px] text-secondary mt-0.5",children:"Track discussions shaping what AI says about your brand"})]}),e.jsx(js,{reason:"no-brand",title:"No brand selected",description:"Select a brand to monitor the Reddit discussions shaping its AI visibility.",scope:"page",className:"flex-1"})]})})}export{br 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.