import{b as r,o as T,A as K}from"./vendor-lit-B2r-dKc0.js";import{a as c}from"./vendor-mini-lit-CpUQub-j.js";import{aU as Q,c as E}from"./app-session-runtime-CeFJDILJ.js";import{r as d}from"./app-review-C3CmcSYC.js";import{getRouteFromHash as J,setHashRoute as L}from"./app-routing-C_r2pdnC.js";import{s as V,H as w,ac as M,as as W,B as X,k as Y,G as Z,A as ee,aa as te}from"./vendor-lucide-B9Yl1Gez.js";import"./vendor-marked-_iteVaMm.js";import"./app-message-reducer-wATqnZGf.js";import"./vendor-sortable-B1o3v0Qs.js";import"./app-inbox-CaZD85aD.js";import"./app-panel-workspace-C3XDRCgE.js";import"./app-pr-walkthrough-WipZACSB.js";let o="",l=[],p=!1,f=new Set(["goals","sessions","staff","messages"]),x=0,g=0,S=null,b=!1,u=new Set,v=new Set,y=null,h=null,R=!1;async function C(e=!1){if(!o.trim()){l=[],g=0,p=!1,e||u.clear(),d();return}p=!0,e||u.clear(),d();const s=o;try{const a=await Q(o,"all",50,e?x:0);if(o!==s)return;e?(l=[...l,...a.results],x+=a.results.length):(l=a.results,x=a.results.length),g=a.total}catch(a){console.error("[search-page] Search failed:",a)}p=!1,d()}function se(e){o=e.target.value,S&&clearTimeout(S),S=setTimeout(()=>{x=0,C();const s=o?`#/search?q=${encodeURIComponent(o)}`:"#/search";window.location.hash!==s&&history.replaceState({},"",s)},200),d()}function ae(e){e.key==="Escape"&&(o?(o="",l=[],g=0,x=0,u.clear(),d()):(b=!1,history.back()))}function ne(e){f.has(e)?f.size>1&&f.delete(e):f.add(e),d()}function ie(){C(!0)}function U(){R||typeof window>"u"||(R=!0,window.addEventListener("search-result-stale",e=>{const s=e.detail;s?.id&&(v.add(s.id),y={kind:s.kind||"result",id:s.id,at:Date.now()},h&&clearTimeout(h),h=setTimeout(()=>{y=null,h=null,d()},5e3),d())}))}function B(){h&&(clearTimeout(h),h=null),y=null,d()}function _(e){if(y&&B(),e.type==="goal"){try{window.__bobbitFromSearch=!0}catch{}L("goal-dashboard",e.id)}else e.type==="session"?E(e.id,!0,{onMissing:"toast"}):e.type==="staff"?L("staff-edit",e.id):e.type==="message"&&e.sessionId&&E(e.sessionId,!0,{onMissing:"toast"})}function re(e){const s=new Map,a=(n,i)=>{let t=s.get(n);return t||(t={key:n,kind:i,parent:null,children:[],matchCount:{title:0,messages:0},bestScore:0,latestTs:0},s.set(n,t)),t};for(const n of e)switch(n.type){case"staff":{const i=`staff:${n.id}`,t=a(i,"staff");t.parent=n,t.matchCount.title++,t.bestScore=Math.max(t.bestScore,n.score??0),t.latestTs=Math.max(t.latestTs,n.timestamp??0);break}case"goal":{const i=`goal:${n.id}`,t=a(i,"goal");t.parent=n,t.matchCount.title++,t.bestScore=Math.max(t.bestScore,n.score??0),t.latestTs=Math.max(t.latestTs,n.timestamp??0);break}case"session":{const i=`session:${n.id}`,t=a(i,"session");t.parent=n,t.matchCount.title++,t.bestScore=Math.max(t.bestScore,n.score??0),t.latestTs=Math.max(t.latestTs,n.timestamp??0);break}case"message":{if(!n.sessionId)continue;const i=`session:${n.sessionId}`,t=a(i,"session");!t.parent&&!t.parentFallback&&(t.parentFallback={id:n.sessionId,title:n.sessionTitle??"Untitled session",archived:n.archived??!1,timestamp:n.timestamp??0,projectId:n.projectId}),t.children.push(n),t.matchCount.messages++,t.bestScore=Math.max(t.bestScore,n.score??0),t.latestTs=Math.max(t.latestTs,n.timestamp??0);break}default:{const i=`${n.type}:${n.id}`,t=a(i,"session");t.parent=n,t.matchCount.title++}break}return Array.from(s.values()).sort((n,i)=>i.bestScore!==n.bestScore?i.bestScore-n.bestScore:i.latestTs-n.latestTs)}function P(e){if(!e)return"";const s=Math.max(0,Date.now()-e),a=Math.floor(s/1e3);if(a<60)return"now";const n=Math.floor(a/60);if(n<60)return`${n}m`;const i=Math.floor(n/60);if(i<24)return`${i}h`;const t=Math.floor(i/24);return t<30?`${t}d`:`${Math.floor(t/30)}mo`}function I(e){return e.replace(/<b>/gi,"\0B").replace(/<\/b>/gi,"\0E").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/\x00B/g,"<b>").replace(/\x00E/g,"</b>")}function oe(e){return e.charAt(0).toUpperCase()+e.slice(1)}function j(e){switch(e){case"goals":case"goal":return Z;case"sessions":case"session":return Y;case"staff":return X;case"messages":case"message":return W;default:return M}}function Te(){if(U(),b)return;o=J().searchQuery||"",x=0,b=!0,u.clear(),v.clear(),o?C():(l=[],g=0,p=!1)}function Me(){b=!1}function le(e){const s=e.type==="message"&&e.sessionTitle||e.title,a=v.has(e.id)||(e.sessionId?v.has(e.sessionId):!1);return r`
		<button
			data-role="result-child"
			data-type=${e.type}
			data-id=${e.id}
			class="w-full text-left px-3 py-2 rounded-md hover:bg-accent/40 transition-colors cursor-pointer flex flex-col gap-1 ${a?"opacity-50":""}"
			@click=${n=>{n.stopPropagation(),_(e)}}
		>
			<div class="flex items-center gap-2 min-w-0">
				${c(j(e.type),"xs")}
				<span class="truncate text-xs text-foreground">${s||"Untitled"}</span>
				${a?r`
					<span class="shrink-0 text-[10px] text-muted-foreground italic">stale</span>
				`:""}
				<span class="ml-auto shrink-0 text-[10px] text-muted-foreground tabular-nums">
					${P(e.timestamp)}
				</span>
			</div>
			${e.snippet?r`
				<div class="text-xs text-muted-foreground line-clamp-2 leading-relaxed search-snippet pl-5">
					${T(I(e.snippet))}
				</div>
			`:""}
		</button>
	`}function ce(e){const s=e.title+e.messages;if(s===0)return K;const a=e.title>0&&e.messages>0?`${e.title} in title · ${e.messages} in messages`:s===1?"1 match":`${s} matches`;return r`
		<span class="shrink-0 inline-flex items-center px-1.5 py-0 rounded text-[10px] bg-primary/10 text-primary">
			${a}
		</span>
	`}function de(e){const s=[],a=i=>{s.push(r`
			<div class="text-xs text-muted-foreground line-clamp-1 leading-relaxed search-snippet">
				${T(I(i))}
			</div>
		`)};if(e.parent?.matchedOn!=="metadata"&&e.parent?.snippet&&a(e.parent.snippet),s.length<2&&e.children.length>0){const i=e.children.find(t=>t.snippet);i?.snippet&&a(i.snippet)}if(s.length<2&&e.children.length>1){const i=e.children.slice(1).find(t=>t.snippet);i?.snippet&&a(i.snippet)}return s.slice(0,2)}function pe(e){const s=e.parent,a=e.parentFallback,n=s?.id??a?.id??e.key,i=s?.title||a?.title||"Untitled",t=s?.archived??a?.archived??!1,F=s?.timestamp??a?.timestamp??0,A=v.has(n),q=e.matchCount.title+e.matchCount.messages===1,G=u.has(e.key),m=q!==G,H=e.children.length>0,O=j(e.kind),z=()=>{s?_(s):a&&_({type:"session",id:a.id,title:a.title,timestamp:a.timestamp,archived:a.archived,projectId:a.projectId})},D=k=>{k.stopPropagation(),u.has(e.key)?u.delete(e.key):u.add(e.key),d()},$=m?[]:de(e),N=!m&&s?.matchedOn==="metadata"&&$.length===0;return r`
		<div
			data-role="result-group"
			data-kind=${e.kind}
			data-key=${e.key}
			data-expanded=${m?"true":"false"}
			class="rounded-lg border border-border/50 bg-background/40 overflow-hidden ${A?"opacity-60":""}"
		>
			<div class="flex items-stretch">
				<button
					class="flex-1 min-w-0 text-left px-3 py-2.5 hover:bg-accent/50 transition-colors cursor-pointer flex flex-col gap-1"
					@click=${z}
				>
					<div class="flex items-center gap-2 min-w-0">
						<span class="shrink-0 text-muted-foreground">
							${c(O,"sm")}
						</span>
						<span class="truncate font-medium text-foreground text-sm">${i}</span>
						${t?r`
							<span class="shrink-0 inline-flex items-center gap-0.5 px-1.5 py-0 rounded text-[10px] bg-muted text-muted-foreground">
								${c(ee,"xs")} archived
							</span>
						`:""}
						${A?r`
							<span class="shrink-0 text-[10px] text-muted-foreground italic">stale</span>
						`:""}
						${ce(e.matchCount)}
						<span class="ml-auto shrink-0 text-[11px] text-muted-foreground tabular-nums">
							${P(F)}
						</span>
					</div>
					${N?r`
						<div class="text-xs text-muted-foreground/70 italic pl-6">matched on title/metadata</div>
					`:$.length>0?r`
						<div class="flex flex-col gap-0.5 pl-6">${$}</div>
					`:""}
				</button>
				${H?r`
					<button
						data-role="group-chevron"
						aria-expanded=${m?"true":"false"}
						aria-label=${m?"Collapse group":"Expand group"}
						class="shrink-0 px-2 flex items-center justify-center text-muted-foreground hover:text-foreground hover:bg-accent/60 border-l border-border/50 transition-colors"
						@click=${D}
					>
						<span class="inline-block transition-transform ${m?"rotate-90":""}">
							${c(te,"sm")}
						</span>
					</button>
				`:""}
			</div>
			${m?r`
				<div class="border-t border-border/50 bg-muted/20 px-2 py-2 flex flex-col gap-1">
					${s?.snippet&&s.matchedOn!=="metadata"?r`
						<div class="text-xs text-muted-foreground leading-relaxed search-snippet px-3 py-1">
							${T(I(s.snippet))}
						</div>
					`:s?.matchedOn==="metadata"?r`
						<div class="text-xs text-muted-foreground/70 italic px-3 py-1">matched on title/metadata</div>
					`:""}
					${e.children.length>0?r`
						<div class="flex flex-col gap-0.5 border-l-2 border-border/50 ml-2 pl-1">
							${e.children.map(k=>le(k))}
						</div>
					`:""}
				</div>
			`:""}
		</div>
	`}function fe(){if(p&&l.length===0)return r`
			<div class="flex items-center justify-center py-12 text-muted-foreground text-sm gap-2">
				<span class="inline-block animate-spin">${c(w,"sm")}</span>
				Searching…
			</div>
		`;if(!p&&o&&l.length===0)return r`
			<div class="flex flex-col items-center justify-center py-12 text-muted-foreground text-sm gap-1">
				<span>No matches for "${o}"</span>
			</div>
		`;if(!o)return r`
			<div class="flex flex-col items-center justify-center py-12 text-muted-foreground text-sm gap-2">
				${c(M,"lg")}
				<span>Search across goals, sessions, staff, and messages</span>
			</div>
		`;const e=l.filter(a=>a.type==="goal"?f.has("goals"):a.type==="session"?f.has("sessions"):a.type==="staff"?f.has("staff"):a.type==="message"?f.has("messages"):!0);if(e.length===0)return r`
			<div class="flex flex-col items-center justify-center py-12 text-muted-foreground text-sm gap-1">
				<span>No matches for the selected filters</span>
			</div>
		`;const s=re(e);return r`
		<div class="flex flex-col gap-2">
			${p?r`
				<div class="flex items-center gap-1.5 px-3 py-1 text-xs text-muted-foreground">
					<span class="inline-block animate-spin">${c(w,"sm")}</span>
					Updating…
				</div>
			`:""}
			${s.map(a=>pe(a))}
		</div>
	`}function Ce(){U();const e=["goals","sessions","staff","messages"];return r`
		<div class="flex-1 flex flex-col h-full overflow-hidden" style="background: var(--sidebar);">
			<div class="max-w-3xl w-full mx-auto px-4 py-6 flex flex-col gap-4 h-full overflow-y-auto">
				<!-- Search input -->
				<div class="flex items-center gap-2">
					<button
						class="shrink-0 p-2 rounded-md text-muted-foreground hover:text-foreground hover:bg-secondary/50 transition-colors"
						@click=${()=>{b=!1,history.back()}}
						title="Back"
					>${c(V,"sm")}</button>
					<div class="relative flex-1">
						<span class="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground">
							${p?r`<span class="inline-block animate-spin">${c(w,"sm")}</span>`:c(M,"sm")}
						</span>
						<input
							type="text"
							.value=${o}
							placeholder="Search everything..."
							class="w-full h-11 pl-10 pr-4 rounded-lg border border-input bg-background text-sm text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:border-transparent"
							@input=${se}
							@keydown=${ae}
							autofocus
						/>
					</div>
					<search-status-dot></search-status-dot>
				</div>

				<!-- Type filter toggles -->
				<div class="flex gap-2 flex-wrap">
					${e.map(s=>r`
						<button
							class="px-3 py-1 rounded-full text-xs font-medium transition-colors inline-flex items-center gap-1.5
								${f.has(s)?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground hover:bg-muted/80"}"
							@click=${()=>ne(s)}
						>
							${c(j(s),"xs")}
							${oe(s)}
						</button>
					`)}
				</div>

				<!-- Stale-result toast -->
				${y?r`
					<div
						data-role="stale-toast"
						class="px-3 py-2 rounded-md bg-destructive/10 text-destructive text-xs flex items-center justify-between gap-2"
						role="status"
					>
						<span>This result is no longer available — it may have been deleted.</span>
						<button
							class="shrink-0 px-2 py-0.5 rounded hover:bg-destructive/20 transition-colors"
							@click=${B}
						>Dismiss</button>
					</div>
				`:""}

				<!-- Results -->
				${fe()}

				<!-- Load More -->
				${l.length>0&&l.length<g?r`
					<div class="flex justify-center py-2">
						<button
							class="px-4 py-2 rounded-md text-sm text-primary hover:bg-primary/10 transition-colors"
							@click=${ie}
							?disabled=${p}
						>
							${p?"Loading…":`Load More (${g-l.length} remaining)`}
						</button>
					</div>
				`:""}
			</div>
		</div>
	`}export{re as buildGroups,Te as initSearchPage,Ce as renderSearchPage,Me as resetSearchPage};
