// @license magnet:?xt=urn:btih:0b31508aeb0634b347b8270c7bee4d411b5d4109&dn=agpl-3.0.txt AGPL-3.0-or-later
// @source: https://gitlab.com/soapbox-pub/ditto/-/tree/f0a3877c
import{r as e}from"./rolldown-runtime-QTnfLwEv.js";import{$t as t,A as n,Ar as r,At as i,B as a,Dr as o,Et as s,F as c,Fn as l,Ft as u,Gi as d,Hi as f,Ht as p,I as m,It as h,Kt as g,N as _,Nn as v,Pr as y,Q as b,S as x,Sn as S,Sr as C,Tr as w,Tt as T,W as E,X as ee,Y as te,Zt as D,_ as O,_n as k,a as A,an as j,ct as M,fi as N,hr as ne,ht as P,ir as re,jr as F,kt as ie,li as I,o as L,oi as ae,or as R,ot as oe,pi as se,qi as z,qt as ce,r as B,ri as le,rn as V,si as ue,st as de,v as fe,x as pe,z as me,zt as he}from"./lucide-icons-BdRF0moN.js";import{t as ge}from"./react-dom-YCZzGcHh.js";import{t as _e}from"./jsx-runtime-By8HlURe.js";import{t as ve}from"./dist-DQ82bf9M.js";import{u as ye}from"./esm-CRVqHnq2.js";import{h as be,t as H}from"./useQuery-rCAlChE8.js";import{t as U}from"./useMutation-CgsR0O-3.js";import{t as xe}from"./useLocalStorage-DLDvi0Ge.js";import{t as Se}from"./useAppContext-Ughdk2-Z.js";import{r as Ce}from"./sanitizeUrl-Bk5f35GN.js";import{t as we}from"./dist-DQ_zK-Nr.js";import{a as Te}from"./downloadFile-kpATXaJi.js";import{t as Ee}from"./fetchFreshEvent-Kkz3MzZN.js";import{l as De,o as W,s as Oe,t as G}from"./useCurrentUser-C6OJJlWo.js";import{t as K}from"./utils-BFSTDHdM.js";import{t as q}from"./button-Cs26nq0r.js";import{t as ke}from"./useNostrPublish-CrMjnYm4.js";import{c as Ae,n as je}from"./chunk-62JRHF6Z-yJW_vgm4.js";import{t as Me}from"./profileUrl-DpJiPx2H.js";import{i as J,n as Ne,r as Pe,t as Fe}from"./haptics-Cp_uF-bV.js";import{t as Ie}from"./input-CM5Fnyvy.js";import{i as Le,r as Re,t as ze}from"./popover-Dw5E1auH.js";import{t as Be}from"./skeleton-CVls4GW9.js";import{t as Ve}from"./useUploadFile-BpPXwoE0.js";import{a as He,c as Ue,n as We,t as Ge}from"./dialog-C3CFmras.js";import{t as Ke}from"./timeAgo-BXjjbyXp.js";import"./badge-eEdLlpTp.js";import{c as qe}from"./LayoutContext-CjQBLGO-.js";import{i as Je,t as Ye}from"./SubHeaderBar-BYwNp4Nc.js";import{n as Xe,t as Ze}from"./useInteractionReaction-03diUK1e.js";import"./label-BBIj2Nkw.js";import{t as Qe}from"./switch-B6lxwP1L.js";import"./separator-CWY6Ovdb.js";import{t as $e}from"./scroll-area-D2CmkWvj.js";import{O as et,Q as tt,Z as nt,o as rt,w as it}from"./index-CYEZWNq6.js";import{A as at,C as ot,D as st,E as ct,H as lt,I as ut,L as dt,M as ft,N as pt,O as mt,P as ht,R as gt,S as _t,_ as vt,a as Y,b as yt,c as bt,d as xt,f as St,h as Ct,i as wt,j as X,k as Tt,l as Et,n as Dt,o as Ot,p as kt,s as At,u as jt,v as Mt,z as Nt}from"./blobbi-CLChx8JU.js";import{S as Pt,_ as Ft,a as It,b as Lt,c as Rt,d as zt,f as Bt,g as Vt,h as Ht,i as Ut,l as Wt,m as Gt,n as Kt,o as qt,p as Jt,r as Yt,s as Xt,t as Zt,v as Qt,x as $t,y as en}from"./useStatusReaction-L-HlqtEq.js";import{_ as tn,a as nn,b as rn,d as an,f as on,g as sn,h as cn,m as ln,n as un,s as dn,t as fn,u as pn,x as mn,y as hn}from"./blobbi-shop-items-gin9pdH4.js";import{i as gn,m as _n}from"./interaction-DDXkTFyb.js";import{l as vn,s as yn,t as bn}from"./BlobbiStageVisual-Cyhy_5-y.js";import{_ as xn,g as Sn,l as Cn,o as wn,r as Tn,u as En}from"./blobbi-action-utils-CeIPzrFd.js";import{a as Dn,c as On,i as kn,n as An,o as jn,s as Mn,t as Nn}from"./useBlobbiUseInventoryItem-B5QuVTwd.js";import{t as Pn}from"./useBlobbiInteractions-BR0C9tjk.js";import{n as Fn,r as In,t as Ln}from"./ItemCarousel-DJoTWUZ6.js";import{n as Rn,r as zn,t as Bn}from"./FloatingSocialHearts-ChoPyJfb.js";import{t as Vn}from"./slider-C6-KCls8.js";import"./select-DRTcxeFR.js";var Z=e(z(),1),Hn=e(ge(),1),Q=_e(),Un=[0,100,250,500,850,1300,1900,2650,3600,4800,6300,8100,10200,12700,15600,19e3,23e3,27600,33e3,39200];Un.length;function Wn(e){let t=Math.max(0,Math.floor(e));for(let e=Un.length-1;e>=0;e--)if(t>=Un[e])return e+1;return 1}function Gn(e){return{xp:Math.max(0,Math.floor(e)).toString(),level:Wn(e).toString()}}async function Kn(e,t,n={}){let{signal:r}=n,i=AbortSignal.timeout(1e4),a=r?AbortSignal.any([r,i]):i,o=await e.query([{...t,limit:1}],{signal:a});return o.length?o.reduce((e,t)=>t.created_at>e.created_at?t:e):null}function qn(e,t){return e.find(e=>e.id===t)}var Jn=[{id:`create_theme`,title:`Create Theme`,description:`Create a custom theme for your profile`,target:1,tracking:`event`,action:`navigate`,actionTarget:`/themes`,actionLabel:`Create Theme`},{id:`color_moment`,title:`Color Moment`,description:`Share a color moment on espy`,target:1,tracking:`event`,action:`external_link`,actionTarget:`https://espy.you/`,actionLabel:`Open espy`},{id:`interactions`,title:`Interact with Blobbi`,description:`Care for your Blobbi 7 times`,target:7,tracking:`tally`}],Yn=[{id:`create_themes`,title:`Create Themes`,description:`Create 3 custom themes`,target:3,tracking:`event`,action:`navigate`,actionTarget:`/themes`,actionLabel:`Create Theme`},{id:`color_moments`,title:`Color Moments`,description:`Share 3 color moments on espy`,target:3,tracking:`event`,action:`external_link`,actionTarget:`https://espy.you/`,actionLabel:`Open espy`},{id:`interactions`,title:`Interact with Blobbi`,description:`Care for your Blobbi 21 times`,target:21,tracking:`tally`},{id:`edit_profile`,title:`Edit Your Profile`,description:`Update your profile info or customize your profile tabs`,target:1,tracking:`event`,action:`navigate`,actionTarget:`/settings/profile`,actionLabel:`Edit Profile`}];function Xn(e,t){if(e.length!==t.length)return!1;let n=new Set(e.map(e=>e.id));return t.every(e=>n.has(e.id))}function Zn(e,t){let n=new Map(e.map(e=>[e.id,e]));return t.map(e=>n.get(e.id)||Qn(e))}function Qn(e){return e.tracking===`event`?{id:e.id,target:e.target,events:[]}:{id:e.id,target:e.target,count:0}}function $n(){return Jn.map(Qn)}function er(){return Yn.map(Qn)}function tr(e){let{pubkey:t,publish:n,updateProfileEvent:r,onSuccess:i,onError:a}=e,{nostr:o}=ve();return U({mutationFn:async({missions:e})=>{if(!t)throw Error(`Must be logged in`);let i=en(e);if(i<=0)return{xpAwarded:0,newTotalXp:0};let a=await Kn(o,{kinds:[Ot],authors:[t]}),s=((a?st(a):void 0)?.xp??0)+i,c=ft(a?.tags??[],Gn(s)),l=Nt(a?.content??``,{missions:e}),u=await n({kind:Ot,content:l,tags:c,prev:a??void 0});return r?.(u),{xpAwarded:i,newTotalXp:s}},onSuccess:i,onError:a})}var nr=20,rr=1440*60;function ir(e){let{nostr:t}=ve(),n=(0,Z.useMemo)(()=>{if(e)return bt(e.event.pubkey,e.d)},[e]),r=H({queryKey:[`blobbi-activity-history`,n],queryFn:async({signal:r})=>{if(!n||!e)return[];let i=Math.floor(Date.now()/1e3)-rr,a=await t.query([{kinds:[on],"#a":[n],limit:nr,since:i}],{signal:r}),o=e.event.pubkey,s=[];for(let e of a){if(e.pubkey===o)continue;let t=cn(e);t&&s.push(t)}return s.sort((e,t)=>t.createdAt-e.createdAt||t.event.id.localeCompare(e.event.id)),s.slice(0,nr)},enabled:!!n,staleTime:2*6e4,gcTime:300*1e3,refetchOnWindowFocus:!1,refetchOnReconnect:!0});return{interactions:r.data??[],isLoading:r.isLoading}}function ar(e,t){return JSON.stringify({})}function or({companion:e,profile:t,pubkey:n,publish:r,ensureCanonicalBeforeAction:i,updateCompanionEvent:a,onSuccess:o,onError:s}){return U({mutationFn:async()=>{if(!n)throw Error(`You must be logged in to evolve`);if(!e)throw Error(`No companion selected`);if(!t)throw Error(`Profile not found`);if(e.stage!==`baby`)throw e.stage===`egg`?Error(`Eggs must hatch before they can evolve`):e.stage===`adult`?Error(`This Blobbi is already fully evolved`):Error(`Only baby Blobbis can evolve`);let o=await i();if(!o)throw Error(`Failed to prepare companion for evolution`);let s=Math.floor(Date.now()/1e3),c=rn({stage:o.companion.stage,state:o.companion.state,stats:o.companion.stats,lastDecayAt:o.companion.lastDecayAt,now:s}),l=c.stats,u=s.toString(),d=Kt(o.companion)??{},f=lt(X(o.allTags,{stage:`adult`,state:`active`,hunger:l.hunger.toString(),happiness:l.happiness.toString(),health:l.health.toString(),hygiene:l.hygiene.toString(),energy:l.energy.toString(),...d,last_interaction:u,last_decay_at:u}),o.allTags,{cleanupTaskTags:!0});if(f.errors.length>0)throw console.error(`[Evolve] Tag validation errors:`,f.errors),Error(`Tag validation failed: ${f.errors.join(`, `)}`);let p=X(f.tags,{progression_state:`none`});return a(await r({kind:Y,content:gt(ar(o.companion.name,`adult`),[]),tags:p})),Yt(n,o.companion.d),{previousStage:`baby`,newStage:`adult`,name:o.companion.name,decayedStats:c.stats}},onSuccess:o,onError:s})}function sr({companion:e,profile:t,pubkey:n,publish:r,ensureCanonicalBeforeAction:i,updateCompanionEvent:a,onSuccess:o,onError:s}){let{nostr:c}=ve();return U({mutationFn:async o=>{let{mode:s,stopOtherD:l}=o;if(!n)throw Error(`You must be logged in to start incubation`);if(!e)throw Error(`No companion selected`);if(!t)throw Error(`Profile not found`);if(e.stage!==`egg`)throw Error(`Only eggs can be incubated`);if(s===`switch`&&!l)throw Error(`Switch mode requires stopOtherD parameter`);let u;if(s===`switch`&&l){let[e]=await c.query([{kinds:[Y],authors:[n],"#d":[l],limit:1}]);if(e){u=e.tags.find(e=>e[0]===`name`)?.[1]??l;let t=Math.floor(Date.now()/1e3),i=t.toString(),o=(e,t)=>parseInt(e.find(e=>e[0]===t)?.[1]??`50`,10),s=rn({stage:`egg`,state:`active`,stats:{hunger:o(e.tags,`hunger`),happiness:o(e.tags,`happiness`),health:o(e.tags,`health`),hygiene:o(e.tags,`hygiene`),energy:o(e.tags,`energy`)},lastDecayAt:o(e.tags,`last_decay_at`)||t,now:t}),c=X(e.tags.filter(e=>e[0]!==`task`&&e[0]!==`task_completed`&&e[0]!==`state_started_at`&&e[0]!==`progression_started_at`),{health:s.stats.health.toString(),hygiene:s.stats.hygiene.toString(),happiness:s.stats.happiness.toString(),hunger:`100`,energy:`100`,progression_state:`none`,last_interaction:i,last_decay_at:i});a(await r({kind:Y,content:gt(e.content,[]),tags:c})),Yt(n,l)}}let d=await i();if(!d)throw Error(`Failed to prepare companion for incubation`);let f=Math.floor(Date.now()/1e3),p=f.toString(),m=rn({stage:d.companion.stage,state:d.companion.state,stats:d.companion.stats,lastDecayAt:d.companion.lastDecayAt,now:f}),h=X(d.allTags.filter(e=>e[0]!==`task`&&e[0]!==`task_completed`),{health:m.stats.health.toString(),hygiene:m.stats.hygiene.toString(),happiness:m.stats.happiness.toString(),hunger:`100`,energy:`100`,progression_state:`incubating`,progression_started_at:p,last_interaction:p,last_decay_at:p}),g=$n();return a(await r({kind:Y,content:gt(d.content,g),tags:h})),Jt(g,n,d.companion.d),window.dispatchEvent(new CustomEvent(`daily-missions-updated`,{detail:{evolution:!0,d:d.companion.d}})),{name:d.companion.name,progressionStartedAt:f,mode:s,stoppedOtherName:u}},onSuccess:o,onError:s})}function cr({companion:e,pubkey:t,publish:n,ensureCanonicalBeforeAction:r,updateCompanionEvent:i,onSuccess:a,onError:o}){return U({mutationFn:async()=>{if(!t)throw Error(`You must be logged in to stop incubation`);if(!e)throw Error(`No companion selected`);if(e.progressionState!==`incubating`)throw Error(`This Blobbi is not incubating`);let a=await r();if(!a)throw Error(`Failed to prepare companion`);let o=Math.floor(Date.now()/1e3),s=o.toString(),c=rn({stage:a.companion.stage,state:a.companion.state,stats:a.companion.stats,lastDecayAt:a.companion.lastDecayAt,now:o}),l=X(a.allTags.filter(e=>e[0]!==`task`&&e[0]!==`task_completed`&&e[0]!==`state_started_at`&&e[0]!==`progression_started_at`),{health:c.stats.health.toString(),hygiene:c.stats.hygiene.toString(),happiness:c.stats.happiness.toString(),hunger:`100`,energy:`100`,progression_state:`none`,last_interaction:s,last_decay_at:s});return i(await n({kind:Y,content:gt(a.content,[]),tags:l})),Yt(t,a.companion.d),window.dispatchEvent(new CustomEvent(`daily-missions-updated`,{detail:{evolution:!0,d:a.companion.d}})),{name:a.companion.name}},onSuccess:a,onError:o})}function lr({companion:e,pubkey:t,publish:n,ensureCanonicalBeforeAction:r,updateCompanionEvent:i,onSuccess:a,onError:o}){return U({mutationFn:async()=>{if(!t)throw Error(`You must be logged in to start evolution`);if(!e)throw Error(`No companion selected`);if(e.stage!==`baby`)throw Error(`Only baby Blobbis can evolve`);if(e.progressionState===`evolving`)throw Error(`This Blobbi is already evolving`);let a=await r();if(!a)throw Error(`Failed to prepare companion for evolution`);let o=Math.floor(Date.now()/1e3),s=o.toString(),c=rn({stage:a.companion.stage,state:a.companion.state,stats:a.companion.stats,lastDecayAt:a.companion.lastDecayAt,now:o}),l=X(a.allTags.filter(e=>e[0]!==`task`&&e[0]!==`task_completed`),{health:c.stats.health.toString(),hygiene:c.stats.hygiene.toString(),happiness:c.stats.happiness.toString(),hunger:c.stats.hunger.toString(),energy:c.stats.energy.toString(),progression_state:`evolving`,progression_started_at:s,last_interaction:s,last_decay_at:s}),u=er();return i(await n({kind:Y,content:gt(a.content,u),tags:l})),Jt(u,t,a.companion.d),window.dispatchEvent(new CustomEvent(`daily-missions-updated`,{detail:{evolution:!0,d:a.companion.d}})),{name:a.companion.name,progressionStartedAt:o}},onSuccess:a,onError:o})}function ur({companion:e,pubkey:t,publish:n,ensureCanonicalBeforeAction:r,updateCompanionEvent:i,onSuccess:a,onError:o}){return U({mutationFn:async()=>{if(!t)throw Error(`You must be logged in to stop evolution`);if(!e)throw Error(`No companion selected`);if(e.progressionState!==`evolving`)throw Error(`This Blobbi is not evolving`);let a=await r();if(!a)throw Error(`Failed to prepare companion`);let o=Math.floor(Date.now()/1e3),s=o.toString(),c=rn({stage:a.companion.stage,state:a.companion.state,stats:a.companion.stats,lastDecayAt:a.companion.lastDecayAt,now:o}),l=X(a.allTags.filter(e=>e[0]!==`task`&&e[0]!==`task_completed`&&e[0]!==`state_started_at`&&e[0]!==`progression_started_at`),{health:c.stats.health.toString(),hygiene:c.stats.hygiene.toString(),happiness:c.stats.happiness.toString(),hunger:c.stats.hunger.toString(),energy:c.stats.energy.toString(),progression_state:`none`,last_interaction:s,last_decay_at:s});return i(await n({kind:Y,content:gt(a.content,[]),tags:l})),Yt(t,a.companion.d),window.dispatchEvent(new CustomEvent(`daily-missions-updated`,{detail:{evolution:!0,d:a.companion.d}})),{name:a.companion.name}},onSuccess:a,onError:o})}var dr=()=>void 0,fr=60;function pr(e){let{companion:t,interactions:n,interactionsLoading:r,updateCompanionEvent:i,ensureCanonicalBeforeAction:a,onSocialConsolidated:o,publish:s,resolveCareItemEffect:c=dr}=e,l=be(),u=(0,Z.useRef)(null),d=(0,Z.useRef)(!1),f=(0,Z.useCallback)(async(e,t)=>{if(!d.current){d.current=!0;try{let n=Math.floor(Date.now()/1e3),r=rn({stage:e.stage,state:e.state,stats:e.stats,lastDecayAt:e.lastDecayAt,now:n}),u=!1;if(t.length>0){let n=sn(e),i=hn(r.stats,t,n.checkpoint,c);u=i.consumedCount>0&&!!i.lastConsumed}if(!u&&r.elapsedSeconds<fr)return;let d=await a();if(!d)return;let f=Math.floor(Date.now()/1e3),p=rn({stage:d.companion.stage,state:d.companion.state,stats:d.companion.stats,lastDecayAt:d.companion.lastDecayAt,now:f}),m=p.stats,h=d.content,g=0;if(t.length>0){let e=sn(d.companion),n=hn(p.stats,t,e.checkpoint,c);if(n.consumedCount>0&&n.lastConsumed){m=n.stats,g=n.consumedCount;let e={processed_until:n.lastConsumed.createdAt,last_event_id:n.lastConsumed.event.id};h=tn(d.content,e)}}if(g===0&&p.elapsedSeconds<fr)return;let _=X(d.allTags,at(m,f)),v=d.companion.event,y=await s({kind:Y,content:h,tags:_,prev:v});i(y);let b=bt(e.event.pubkey,e.d);l.invalidateQueries({queryKey:[`blobbi-interactions`,b]}),g>0&&o&&o(g)}catch(e){console.error(`[useCanonicalSync] Sync failed:`,e)}finally{d.current=!1}}},[a,s,i,l,o,c]);(0,Z.useEffect)(()=>{t&&(r||t.isLegacy||u.current!==t.d&&(u.current=t.d,f(t,n)))},[t,t?.d,n,r,f])}function mr(e={}){let{pubkey:t,availableStages:n,profileContent:r}=e,[i,a]=(0,Z.useState)(0),o=(0,Z.useRef)(null),s=(0,Z.useRef)(null);(0,Z.useEffect)(()=>{if(!t)return;if(!r){o.current!==t&&(o.current=t,a(e=>e+1));return}if(s.current===t)return;s.current=t;let e=dt(r);e.missions&&!Qt(e.missions)&&(e.missions.daily.some(e=>ut(e)>0)?Bt(e.missions,t):It(t)||Bt(e.missions,t)),o.current=t,a(e=>e+1)},[t,r]),(0,Z.useEffect)(()=>{let e=()=>a(e=>e+1);return window.addEventListener(`daily-missions-updated`,e),()=>window.removeEventListener(`daily-missions-updated`,e)},[]);let c=n?.sort().join(`,`)??``,l=o.current===t,u=(0,Z.useMemo)(()=>{let e=It(t);if(!Qt(e))return e;if(!e&&!l)return;let r=Ht(Ft(),t,n);return Bt(r,t),r},[i,t,c,l]),d=(0,Z.useMemo)(()=>u?.daily?u.daily.map(e=>{let t=Vt(e.id);return{id:e.id,title:t?.title??e.id,description:t?.description??``,action:t?.action??`interact`,target:e.target,progress:ut(e),complete:ht(e),xp:t?.xp??0}}):[],[u]),f=u?Gt(u):!1,p=u?en(u):0,m=f,h=n?n.includes(`baby`)||n.includes(`adult`):!0;return{missions:d,raw:u,allComplete:f,todayXp:p,bonusUnlocked:m,bonusXp:50,noMissionsAvailable:!h,isLoading:!u&&h,rerollsRemaining:u?.rerolls??3,maxRerolls:3,forceReset:(0,Z.useCallback)(()=>{Bt(Ht(Ft(),t,n),t),a(e=>e+1)},[t,c])}}var hr=3e3;function gr(e){let{pubkey:t,publish:n,updateProfileEvent:r}=e,{nostr:i}=ve(),a=(0,Z.useRef)(null),o=(0,Z.useRef)(!1),s=(0,Z.useRef)(!1),c=(0,Z.useRef)(!1),l=(0,Z.useRef)(t),u=(0,Z.useRef)(i),d=(0,Z.useRef)(n),f=(0,Z.useRef)(r);l.current=t,u.current=i,d.current=n,f.current=r;let p=(0,Z.useRef)(async()=>{let e=l.current;if(!e)return;if(o.current){s.current=!0;return}let t=It(e);if(!(!t||t.daily.length===0)){if(Gt(t)){c.current=!1;return}o.current=!0;try{let t=await Kn(u.current,{kinds:[Ot],authors:[e]});if(!t){console.warn(`[PersistDailyProgress] No existing profile event found, skipping persist`);return}let n=It(e);if(!n||Gt(n))return;let r=Nt(t.content,{missions:n});if(r===t.content){c.current=!1;return}let i=await d.current({kind:Ot,content:r,tags:t.tags,prev:t});c.current=!1,f.current?.(i)}catch(e){console.warn(`[PersistDailyProgress] Failed to persist:`,e)}finally{o.current=!1,s.current&&(s.current=!1,c.current=!0,a.current=setTimeout(()=>{p.current().catch(e=>{console.warn(`[PersistDailyProgress] Pending persist error:`,e)})},hr))}}});(0,Z.useEffect)(()=>{let e=e=>{e.detail?.evolution||(c.current=!0,a.current&&clearTimeout(a.current),a.current=setTimeout(()=>{p.current().catch(e=>{console.warn(`[PersistDailyProgress] Persist error:`,e)})},hr))},t=()=>{document.visibilityState===`hidden`&&c.current&&(a.current&&=(clearTimeout(a.current),null),p.current().catch(()=>{}))};window.addEventListener(`daily-missions-updated`,e),document.addEventListener(`visibilitychange`,t);let n=p.current;return()=>{window.removeEventListener(`daily-missions-updated`,e),document.removeEventListener(`visibilitychange`,t),a.current&&clearTimeout(a.current),c.current&&n().catch(()=>{})}},[])}var _r=5e3;function vr(e){let{pubkey:t,companionD:n,publish:r,updateCompanionEvent:i}=e,{nostr:a}=ve(),o=be(),s=(0,Z.useRef)(null),c=(0,Z.useRef)(!1),l=(0,Z.useCallback)(async()=>{if(!t||!n||c.current)return;let e=qt(t,n);if(!(!e||e.length===0)){c.current=!0;try{let s=await Kn(a,{kinds:[Y],authors:[t],"#d":[n]});if(!s){console.warn(`[PersistEvolution] No Blobbi event found for d-tag:`,n);return}let c=gt(s.content,e);if(c===s.content)return;let l=await r({kind:Y,content:c,tags:s.tags,prev:s});i(l),o.invalidateQueries({queryKey:[`blobbi-collection`,t]})}finally{c.current=!1}}},[t,n,a,r,i,o]);(0,Z.useEffect)(()=>{let e=e=>{let t=e.detail;t?.evolution&&(t.d&&t.d!==n||(s.current&&clearTimeout(s.current),s.current=setTimeout(()=>{l().catch(e=>{console.warn(`[PersistEvolution] Failed to persist:`,e)})},_r)))};return window.addEventListener(`daily-missions-updated`,e),()=>{window.removeEventListener(`daily-missions-updated`,e),s.current&&clearTimeout(s.current)}},[l,n])}var yr=36767,br=3367;function xr(e,t){let{nostr:n}=ve(),r=e?.d,i=e?.progressionState===`incubating`,a=(0,Z.useMemo)(()=>{if(!t||!r)return[];let n=qt(t,r);return n&&n.length>0?n:e?.evolution??[]},[t,r,e?.evolution]),o=(0,Z.useRef)(null);(0,Z.useEffect)(()=>{if(!i||!t||!r)return;let n=`${t}:${r}`;if(o.current===n)return;o.current=n;let a=e?.evolution??[];a.length>0&&Ut(a,t,r)},[i,t,r,e?.evolution]);let s=(0,Z.useRef)(null);(0,Z.useEffect)(()=>{let n=`${t}:${r}`;if(!i||!t||!r||s.current===n)return;let a=qt(t,r),o=a&&a.length>0?a:e?.evolution??[];o.length===0?(Jt($n(),t,r),window.dispatchEvent(new CustomEvent(`daily-missions-updated`,{detail:{evolution:!0,d:r}}))):Xn(o,Jn)||(Jt(Zn(o,Jn),t,r),window.dispatchEvent(new CustomEvent(`daily-missions-updated`,{detail:{evolution:!0,d:r}}))),s.current=n},[i,t,r,e?.evolution]);let{data:c,isLoading:l,error:u,refetch:d}=H({queryKey:[`hatch-tasks`,t,r],queryFn:async()=>{if(!t)return null;let e=[{kinds:[yr],authors:[t],limit:1},{kinds:[br],authors:[t],limit:1}],r=await n.query(e);return{themeEvents:r.filter(e=>e.kind===yr),colorMomentEvents:r.filter(e=>e.kind===br)}},enabled:!!t&&i,staleTime:3e4,refetchInterval:6e4}),f=(0,Z.useMemo)(()=>c?{create_theme:c.themeEvents.length,color_moment:c.colorMomentEvents.length}:{},[c]),p=(0,Z.useRef)(null);(0,Z.useEffect)(()=>{if(!c||!t||!r||a.length===0||c===p.current)return;p.current=c;let e=qt(t,r);if(!(!e||e.length===0)){for(let n of c.themeEvents){let i=qn(e,`create_theme`);i&&pt(i)&&!i.events.includes(n.id)&&Rt(`create_theme`,n.id,t,r)}for(let n of c.colorMomentEvents){let i=qn(e,`color_moment`);i&&pt(i)&&!i.events.includes(n.id)&&Rt(`color_moment`,n.id,t,r)}}},[c,t,r,a]);let m=Jn.map(e=>{let t=qn(a,e.id),n=t?ut(t):0,r=f[e.id]??0,i=Math.max(n,r),o=i>=e.target;return{id:e.id,name:e.title,description:e.description,current:Math.min(i,e.target),required:e.target,completed:o,type:`persistent`,action:e.action,actionTarget:e.actionTarget,actionLabel:e.actionLabel}}),h=m.every(e=>e.completed);return{tasks:m,persistentTasksComplete:h,dynamicTaskComplete:!0,allCompleted:h&&!0,isLoading:l,error:u,refetch:d}}var Sr=16769;function Cr(e,t){let{nostr:n}=ve(),r=e?.d,i=e?.progressionState===`evolving`,a=(0,Z.useMemo)(()=>{if(!t||!r)return[];let n=qt(t,r);return n&&n.length>0?n:e?.evolution??[]},[t,r,e?.evolution]),o=(0,Z.useRef)(null);(0,Z.useEffect)(()=>{if(!i||!t||!r)return;let n=`${t}:${r}`;if(o.current===n)return;o.current=n;let a=e?.evolution??[];a.length>0&&Ut(a,t,r)},[i,t,r,e?.evolution]);let s=(0,Z.useRef)(null);(0,Z.useEffect)(()=>{let n=`${t}:${r}`;if(!i||!t||!r||s.current===n)return;let a=qt(t,r),o=a&&a.length>0?a:e?.evolution??[];o.length===0?(Jt(er(),t,r),window.dispatchEvent(new CustomEvent(`daily-missions-updated`,{detail:{evolution:!0,d:r}}))):Xn(o,Yn)||(Jt(Zn(o,Yn),t,r),window.dispatchEvent(new CustomEvent(`daily-missions-updated`,{detail:{evolution:!0,d:r}}))),s.current=n},[i,t,r,e?.evolution]);let{data:c,isLoading:l,error:u,refetch:d}=H({queryKey:[`evolve-tasks`,t,r],queryFn:async()=>{if(!t)return null;let e=[{kinds:[yr],authors:[t],limit:3},{kinds:[br],authors:[t],limit:3},{kinds:[Sr],authors:[t],limit:1},{kinds:[0],authors:[t],limit:1}],r=await n.query(e);return{themeEvents:r.filter(e=>e.kind===yr),colorMomentEvents:r.filter(e=>e.kind===br),profileTabsEvents:r.filter(e=>e.kind===Sr),hasProfileMetadata:r.some(e=>e.kind===0)}},enabled:!!t&&i,staleTime:3e4,refetchInterval:6e4}),f=(0,Z.useMemo)(()=>c?{create_themes:c.themeEvents.length,color_moments:c.colorMomentEvents.length,edit_profile:c.profileTabsEvents.length>=1||c.hasProfileMetadata?1:0}:{},[c]),p=(0,Z.useRef)(null);(0,Z.useEffect)(()=>{if(!c||!t||!r||a.length===0||c===p.current)return;p.current=c;let e=qt(t,r);if(!e||e.length===0)return;for(let n of c.themeEvents){let i=qn(e,`create_themes`);i&&pt(i)&&!i.events.includes(n.id)&&Rt(`create_themes`,n.id,t,r)}for(let n of c.colorMomentEvents){let i=qn(e,`color_moments`);i&&pt(i)&&!i.events.includes(n.id)&&Rt(`color_moments`,n.id,t,r)}let n=[...c.profileTabsEvents,...c.hasProfileMetadata?[{id:`profile-metadata`}]:[]];for(let i of n){let n=qn(e,`edit_profile`);n&&pt(n)&&!n.events.includes(i.id)&&Rt(`edit_profile`,i.id,t,r)}},[c,t,r,a]);let m=Yn.map(e=>{let t=qn(a,e.id),n=t?ut(t):0,r=f[e.id]??0,i=Math.max(n,r),o=i>=e.target;return{id:e.id,name:e.title,description:e.description,current:Math.min(i,e.target),required:e.target,completed:o,type:`persistent`,action:e.action,actionTarget:e.actionTarget,actionLabel:e.actionLabel}}),h=e?.stats??{},g=h.hunger??0,_=h.happiness??0,v=h.health??0,y=h.hygiene??0,b=h.energy??0,x=g>=80&&_>=80&&v>=80&&y>=80&&b>=80,S=Math.min(g,_,v,y,b);m.push({id:`maintain_stats`,name:`Peak Condition`,description:`Keep all stats above 80`,current:x?80:S,required:80,completed:x,type:`dynamic`});let C=m.filter(e=>e.type===`persistent`),w=m.filter(e=>e.type===`dynamic`),T=C.every(e=>e.completed),E=w.every(e=>e.completed);return{tasks:m,persistentTasksComplete:T,dynamicTaskComplete:E,allCompleted:T&&E,isLoading:l,error:u,refetch:d}}function wr({profile:e,updateProfileEvent:t,invalidateProfile:n}){let{user:r}=G(),{nostr:i}=ve(),{mutateAsync:a}=ke(),o=(0,Z.useRef)(new Set);(0,Z.useEffect)(()=>{if(!e||!r?.pubkey||e.event.pubkey!==r.pubkey||o.current.has(e.event.id))return;let s=Tt(e),c=_t(e.event),l=mt(e);if(!s&&!c&&!l){o.current.add(e.event.id);return}o.current.add(e.event.id);let u=[];s&&u.push(`missing pettingLevel`),c&&u.push(`legacy kind 31125 → 11125`),l&&u.push(`onboarding_done → blobbi_onboarding_done`),console.log(`[ProfileNormalization] Profile needs normalization: ${u.join(`, `)}`),(async()=>{try{let o=await Ee(i,{kinds:[11125],authors:[r.pubkey]})??e.event,s=jt({...e,allTags:o.tags,event:o});t(await a({kind:Ot,content:o.content,tags:s,prev:o})),n(),console.log(`[ProfileNormalization] Profile normalized successfully to kind`,Ot)}catch(t){console.error(`[ProfileNormalization] Failed to normalize profile:`,t),o.current.delete(e.event.id)}})()},[e,r?.pubkey,i,a,t,n])}function Tr(e,t=`Egg`){let n=kt(),r=Ct(e,n),i=Math.floor(Date.now()/1e3),a=xt(e,r,i);return{petId:n,d:r,seed:a,name:t,stage:`egg`,state:`active`,progressionState:`incubating`,visualTraits:St([],a),stats:{...wt},createdAt:i,ownerPubkey:e}}function Er(e){let t=e.createdAt.toString(),{visualTraits:n}=e;return[[`d`,e.d],[`b`,Dt],[`name`,e.name],[`stage`,e.stage],[`state`,e.state],[`progression_state`,e.progressionState],[`seed`,e.seed],[`generation`,`1`],[`breeding_ready`,`false`],[`experience`,`0`],[`care_streak`,`1`],[`care_streak_last_at`,t],[`care_streak_last_day`,vt(new Date(e.createdAt*1e3))],[`hunger`,e.stats.hunger.toString()],[`happiness`,e.stats.happiness.toString()],[`health`,e.stats.health.toString()],[`hygiene`,e.stats.hygiene.toString()],[`energy`,e.stats.energy.toString()],[`last_interaction`,t],[`last_decay_at`,t],[`progression_started_at`,t],[`base_color`,n.baseColor],[`secondary_color`,n.secondaryColor],[`eye_color`,n.eyeColor],[`pattern`,n.pattern],[`special_mark`,n.specialMark],[`size`,n.size]]}function Dr(e){return{d:e.d,name:e.name,stage:e.stage,state:e.state,seed:e.seed,visualTraits:e.visualTraits,stats:e.stats,isLegacy:!1,lastInteraction:e.createdAt,lastDecayAt:e.createdAt,generation:1,breedingReady:!1,socialOpen:!1,experience:0,careStreak:1,careStreakLastAt:e.createdAt,careStreakLastDay:vt(new Date(e.createdAt*1e3)),incubationTime:void 0,startIncubation:void 0,adultType:void 0,progressionState:e.progressionState,stateStartedAt:e.createdAt,progressionStartedAt:e.createdAt,tasks:[],tasksCompleted:[],evolution:[],allTags:Er(e),event:{id:``,pubkey:e.ownerPubkey,created_at:e.createdAt,kind:31124,tags:Er(e),content:``,sig:``}}}var Or=new Set([`egg`,`baby`,`adult`]);function kr(e,t){return e.tags.find(([e])=>e===t)?.[1]}function Ar(e){if(e.kind!==31124||!kr(e,`d`))return!1;let t=kr(e,`stage`);return!(!t||!Or.has(t))}var jr={adult:3,baby:2,egg:1};async function Mr(e,t,n={}){let r={hasBlobbi:!1,rawCount:0,ownedCount:0};if(!t)return r;let i=AbortSignal.timeout(1e4),a=n.signal?AbortSignal.any([n.signal,i]):i,o=[];try{o=await e.query([{kinds:[Y],authors:[t]}],{signal:a})}catch(e){return console.error(`[preflightBlobbiOwnership] query failed:`,e),r}let s=o.filter(Ar);if(s.length===0)return{hasBlobbi:!1,rawCount:o.length,ownedCount:0};let c=[...s].sort((e,t)=>{let n=jr[kr(e,`stage`)??``]??0,r=jr[kr(t,`stage`)??``]??0;return n===r?t.created_at-e.created_at:r-n}),l;for(let e of c){let t=ct(e);if(t){l=t;break}}return{hasBlobbi:!0,existing:l,rawCount:o.length,ownedCount:s.length}}function Nr(e,t,n=35){let[r,i]=(0,Z.useState)(``),[a,o]=(0,Z.useState)(!1),s=(0,Z.useRef)(null),c=(0,Z.useRef)(0);return(0,Z.useEffect)(()=>{i(``),o(!1),c.current=0},[e]),(0,Z.useEffect)(()=>{if(!(!t||a))return s.current=setInterval(()=>{c.current++;let t=e.slice(0,c.current);i(t),c.current>=e.length&&(o(!0),s.current&&clearInterval(s.current))},n),()=>{s.current&&clearInterval(s.current)}},[t,a,e,n]),{displayed:r,done:a,complete:(0,Z.useCallback)(()=>{s.current&&clearInterval(s.current),i(e),o(!0)},[e])}}function Pr(e){let t=e.replace(`#`,``);return{r:parseInt(t.substring(0,2),16),g:parseInt(t.substring(2,4),16),b:parseInt(t.substring(4,6),16)}}function Fr(e,t){return Math.round(e+(255-e)*t)}function Ir(e){let{r:t,g:n,b:r}=Pr(e),i=e=>`rgb(${Fr(t,e)},${Fr(n,e)},${Fr(r,e)})`;return`radial-gradient(ellipse at 50% 45%, ${i(.65)} 0%, ${i(.68)} 25%, ${i(.72)} 50%, ${i(.76)} 75%, ${i(.8)} 100%)`}var Lr=[`Something stirs...`,`A tiny life has chosen you. It knows only warmth, and your presence.`],Rr=`Every life deserves a name.
What will you call this one?`,zr=new Set;function Br({profile:e,updateProfileEvent:t,updateCompanionEvent:n,invalidateProfile:r,invalidateCompanion:i,setStoredSelectedD:a,onComplete:o,existingCompanion:s,eggOnly:c=!1,userInitiated:l=!1,onExistingBlobbiFound:u}){let d=!!s,{user:f}=G(),{nostr:p}=ve(),{mutateAsync:m}=ke(),{data:h}=De(f?.pubkey),[g,_]=(0,Z.useState)(`loading`),[v,y]=(0,Z.useState)(null),[b,x]=(0,Z.useState)(s?.name??``),[S,C]=(0,Z.useState)(!1),[w,T]=(0,Z.useState)(!1),[E,ee]=(0,Z.useState)(!1),[te,D]=(0,Z.useState)(!1),[,O]=(0,Z.useState)(!1),[k,A]=(0,Z.useState)(!1),[j,M]=(0,Z.useState)(0),[N,ne]=(0,Z.useState)(!1),[P,re]=(0,Z.useState)(!1),F=(0,Z.useRef)(!1),ie=(0,Z.useRef)(!1),I=(0,Z.useRef)(e);I.current=e;let L=(0,Z.useRef)(v);L.current=v;let ae=(0,Z.useRef)(null),R=(0,Z.useRef)(null),oe=(0,Z.useRef)(!1),se=(0,Z.useRef)(null),z=(0,Z.useRef)(o);z.current=o;let ce=(0,Z.useRef)(u);ce.current=u;let B=(0,Z.useMemo)(()=>v?Dr(v):null,[v?.d]),le=(0,Z.useMemo)(()=>B?{...B,stage:`baby`,state:`active`,progressionState:`evolving`}:null,[B]),V=v?.visualTraits.baseColor??`#f59e0b`,ue=(0,Z.useMemo)(()=>Ir(V),[V]),de=Nr(g===`dialog`?Lr[j]??``:``,N),fe=Nr(Rr,P);(0,Z.useEffect)(()=>{if(!d||F.current||!s)return;F.current=!0;let e={d:s.d,petId:s.d,ownerPubkey:f?.pubkey??``,name:s.name,stage:`egg`,state:`active`,progressionState:s.progressionState===`incubating`?`incubating`:`none`,seed:s.seed??``,stats:{hunger:s.stats.hunger??100,happiness:s.stats.happiness??100,health:s.stats.health??100,hygiene:s.stats.hygiene??100,energy:s.stats.energy??100},visualTraits:s.visualTraits,createdAt:Math.floor(Date.now()/1e3)};y(e),L.current=e,se.current=s.allTags,_(`egg`),setTimeout(()=>T(!0),200)},[d,s?.d]),(0,Z.useEffect)(()=>{if(d||F.current||!f?.pubkey||zr.has(f.pubkey))return;F.current=!0,zr.add(f.pubkey);let e=setTimeout(async()=>{ie.current=!0;try{if(!l){let e=await Mr(p,f.pubkey);if(e.hasBlobbi){r(),i(),e.existing?(a(e.existing.d),ce.current?ce.current(e.existing):z.current?.()):z.current?.();return}}let e=I.current;e||(e=await On(p,f.pubkey),e&&(I.current=e,t(e.event)));let o=e?.allTags??null;if(!e){let e=h?.metadata?.name||h?.metadata?.display_name||`Blobbonaut`,n=[...Et(f.pubkey),[`name`,e]];t(await m({kind:Ot,content:``,tags:n})),r(),o=n}let s=Tr(f.pubkey,`Egg`);y(s),L.current=s;let c=Er(s);if(se.current=c,n(await m({kind:Y,content:`A new Blobbi egg!`,tags:c,created_at:s.createdAt})),o){let n=o,r=``,i;if(e){let t=await On(p,f.pubkey);t?(n=t.allTags,r=t.event.content??``,i=t.event):(r=e.event.content??``,i=e.event)}let a=[...n.filter(([e])=>e===`has`).map(([,e])=>e),s.d],c=ft(n,{has:a});t(await m({kind:Ot,content:r,tags:c,prev:i}))}a(s.d),r(),i(),_(`egg`),setTimeout(()=>T(!0),200)}catch(e){console.error(`[HatchingCeremony] Setup failed:`,e),W({title:`Something went wrong`,description:`Failed to set up your Blobbi. Please try again.`,variant:`destructive`})}finally{f?.pubkey&&zr.delete(f.pubkey)}},600);return()=>{clearTimeout(e),!ie.current&&f?.pubkey&&zr.delete(f.pubkey)}},[f?.pubkey]),(0,Z.useEffect)(()=>{e&&(I.current=e)},[e]),(0,Z.useEffect)(()=>{if(!c||!w)return;let e=setTimeout(()=>{_(`complete`),z.current?.()},1500);return()=>clearTimeout(e)},[c,w]),(0,Z.useEffect)(()=>{if(w&&!oe.current&&R.current){oe.current=!0;let e=R.current;e.classList.add(`animate-egg-onboard-entrance`);let t=()=>{e.classList.remove(`animate-egg-onboard-entrance`),e.removeEventListener(`animationend`,t)};e.addEventListener(`animationend`,t)}},[w]);let pe=(0,Z.useCallback)(e=>{let t=R.current;t&&(t.classList.remove(`animate-egg-onboard-shake-light`,`animate-egg-onboard-shake-medium`,`animate-egg-onboard-shake-heavy`),t.offsetWidth,t.classList.add(e))},[]),me=(0,Z.useCallback)(async()=>{let e=se.current;if(!e)return;let t=Math.floor(Date.now()/1e3).toString(),r=s??(L.current?Dr(L.current):null),a=lt(X(e,{stage:`baby`,state:`active`,hunger:`100`,happiness:`100`,health:`100`,hygiene:`100`,energy:`100`,...r?Kt(r)??{}:{},last_interaction:t,last_decay_at:t}),e,{cleanupTaskTags:!0});if(a.errors.length>0)throw console.error(`[HatchingCeremony] Tag validation errors:`,a.errors),Error(`Tag validation failed: ${a.errors.join(`, `)}`);let o=X(a.tags,{progression_state:`evolving`,progression_started_at:t}),c=er(),l=gt(JSON.stringify({}),c),u=await m({kind:Y,content:l,tags:o});se.current=o,n(u),i();let d=L.current?.d;f?.pubkey&&d&&(Jt(c,f.pubkey,d),window.dispatchEvent(new CustomEvent(`daily-missions-updated`,{detail:{evolution:!0,d}})))},[m,n,i,s,f?.pubkey]),he=(0,Z.useCallback)(()=>{g===`egg`?(pe(`animate-egg-onboard-shake-light`),Ne(),_(`crack_1`)):g===`crack_1`?(pe(`animate-egg-onboard-shake-medium`),Pe(),_(`crack_2`)):g===`crack_2`?(pe(`animate-egg-onboard-shake-heavy`),Fe(),_(`crack_3`)):g===`crack_3`&&(J(),_(`hatching`),D(!0),me().catch(console.error),setTimeout(()=>{D(!1),O(!0),_(`reveal`),setTimeout(()=>ee(!0),400),setTimeout(()=>{_(`dialog`),M(0),ne(!0)},2200)},1400))},[g,pe,me]),ge=(0,Z.useCallback)(()=>{if(g!==`dialog`)return;if(!de.done){de.complete();return}let e=j+1;e<Lr.length?(ne(!1),M(e),setTimeout(()=>ne(!0),150)):(ne(!1),setTimeout(()=>{_(`naming`),setTimeout(()=>{re(!0),setTimeout(()=>ae.current?.focus(),600)},200)},400))},[g,de,j]),_e=(0,Z.useCallback)(async e=>{try{let a=se.current;if(a&&e!==(L.current?.name??`Egg`)){let t=X(a,{name:e}),r=er(),i=gt(JSON.stringify({}),r);n(await m({kind:Y,content:i,tags:t}))}let o=I.current;if(o&&f?.pubkey){let e=(await On(p,f.pubkey))?.event??o.event,n=ft(e.tags,{blobbi_onboarding_done:`true`});t(await m({kind:Ot,content:e.content??``,tags:n,prev:e}))}r(),i()}catch(e){console.error(`[HatchingCeremony] Failed to persist completion:`,e)}},[p,f?.pubkey,m,n,t,r,i]),ye=(0,Z.useCallback)(async()=>{if(!(S||!b.trim())){C(!0);try{await _e(b.trim()),re(!1),setTimeout(()=>{A(!0),setTimeout(()=>{_(`complete`),o?.()},2200)},600)}catch(e){console.error(`[HatchingCeremony] Naming failed:`,e),W({title:`Failed to save name`,description:`Your Blobbi was created, but the name could not be saved.`,variant:`destructive`}),A(!0),setTimeout(()=>{_(`complete`),o?.()},2200)}finally{C(!1)}}},[b,S,_e,o]),be=(0,Z.useMemo)(()=>{switch(g){case`crack_1`:return`crack_stage_1`;case`crack_2`:return`crack_stage_2`;case`crack_3`:return`crack_stage_3`;case`hatching`:return`opening`;default:return`idle`}},[g]),H=g===`egg`||g===`crack_1`||g===`crack_2`||g===`crack_3`,U=g===`hatching`,xe=g===`reveal`||g===`dialog`||g===`naming`;return g===`loading`?(0,Q.jsx)(`div`,{className:`fixed inset-0 z-50 flex items-center justify-center`,style:{background:`radial-gradient(ellipse at center, #0a1a2a 0%, #081520 50%, #060f18 100%)`},children:(0,Q.jsx)(`div`,{className:`absolute size-32 rounded-full opacity-20 animate-pulse`,style:{background:`radial-gradient(circle, ${V}40 0%, transparent 70%)`}})}):(0,Q.jsxs)(`div`,{className:`fixed inset-0 z-50 overflow-hidden select-none`,style:{background:xe?ue:`radial-gradient(ellipse at center, #0a1a2a 0%, #081520 50%, #060f18 100%)`,transition:`background 2s ease-out`},onClick:g===`dialog`?ge:void 0,children:[!xe&&(0,Q.jsx)(`div`,{className:`absolute inset-0 transition-opacity`,style:{transitionDuration:`3000ms`,background:`radial-gradient(ellipse at 50% 50%, ${V}30 0%, transparent 60%)`,opacity:H||U?.07:.05}}),xe&&(0,Q.jsx)(`div`,{className:`absolute inset-0 pointer-events-none`,style:{background:`radial-gradient(ellipse at 50% 45%, transparent 30%, rgba(0,0,0,0.12) 70%, rgba(0,0,0,0.25) 100%)`}}),H&&(0,Q.jsx)(`div`,{className:`absolute inset-0 pointer-events-none overflow-hidden`,children:Array.from({length:6}).map((e,t)=>(0,Q.jsx)(`div`,{className:`absolute rounded-full`,style:{width:2+t%3,height:2+t%3,left:`${20+t*12%60}%`,bottom:`40%`,backgroundColor:`${V}40`,animation:`onboard-particle-rise ${4+t*.7}s ease-out ${t*.8}s infinite`}},t))}),(H||U)&&B&&(0,Q.jsx)(`div`,{className:`absolute inset-0 flex items-center justify-center`,children:(0,Q.jsxs)(`div`,{ref:R,className:K(`cursor-pointer relative`,w?``:`opacity-0`,w&&H&&`animate-egg-onboard-breathe`,U&&`animate-egg-onboard-burst`),onClick:H?he:void 0,children:[(0,Q.jsx)(`div`,{className:`absolute -inset-12 rounded-full blur-2xl transition-opacity duration-1000`,style:{background:`radial-gradient(circle, ${V}50 0%, transparent 70%)`,opacity:g===`crack_3`?.5:g===`crack_2`?.35:g===`crack_1`?.25:.15}}),(0,Q.jsx)(bn,{companion:B,size:`lg`,animated:!0,className:`size-56 sm:size-64 md:size-72`,tourVisualState:be})]})}),te&&(0,Q.jsx)(`div`,{className:`absolute inset-0 bg-white animate-onboard-screen-flash pointer-events-none`,style:{zIndex:80}}),xe&&le&&(0,Q.jsxs)(`div`,{className:`absolute inset-0 flex items-center justify-center pointer-events-none`,style:{paddingBottom:`18%`},children:[(0,Q.jsx)(`div`,{className:K(`absolute animate-onboard-golden-fadein`,E?``:`opacity-0`),children:(0,Q.jsx)(`div`,{className:`animate-onboard-golden-rotate`,style:{width:900,height:900,background:`conic-gradient(
                  from 0deg,
                  rgba(255, 250, 230, 0.18) 0deg,
                  rgba(255, 245, 210, 0.50) 50deg,
                  rgba(255, 250, 235, 0.22) 100deg,
                  rgba(255, 248, 220, 0.15) 150deg,
                  rgba(255, 245, 210, 0.48) 210deg,
                  rgba(255, 250, 230, 0.20) 270deg,
                  rgba(255, 248, 220, 0.15) 320deg,
                  rgba(255, 250, 230, 0.18) 360deg
                )`,borderRadius:`50%`,filter:`blur(30px)`}})}),(0,Q.jsx)(`div`,{className:K(`absolute rounded-full transition-opacity duration-1000`,E?`opacity-100`:`opacity-0`),style:{width:320,height:320,background:`radial-gradient(circle, rgba(255,255,245,0.70) 0%, rgba(255,250,225,0.30) 40%, transparent 70%)`}}),(0,Q.jsx)(`div`,{className:K(`absolute rounded-full transition-opacity [transition-duration:2000ms]`,E?`opacity-100`:`opacity-0`),style:{width:700,height:700,background:`radial-gradient(circle, rgba(255, 248, 210, 0.40) 0%, rgba(255, 240, 190, 0.18) 40%, transparent 65%)`,filter:`blur(15px)`}}),Array.from({length:20}).map((e,t)=>{let n=t/20*Math.PI*2,r=80+t%4*35,i=4+t%3*3;return(0,Q.jsx)(`div`,{className:`absolute`,style:{width:i,height:i,left:`calc(50% + ${Math.cos(n)*r}px - ${i/2}px)`,top:`calc(50% + ${Math.sin(n)*r}px - ${i/2}px)`,borderRadius:`50%`,background:t%2==0?`radial-gradient(circle, rgba(255,255,255,1) 0%, rgba(255,255,255,0.4) 40%, transparent 70%)`:`radial-gradient(circle, rgba(255,240,130,1) 0%, rgba(255,220,80,0.3) 50%, transparent 70%)`,animation:`onboard-sparkle-twinkle ${1.5+t%6*.5}s ease-in-out ${t*.15}s infinite`}},`inner-${t}`)}),Array.from({length:16}).map((e,t)=>{let n=t/16*Math.PI*2+.3,r=170+t%3*50,i=5+t%4*3;return(0,Q.jsx)(`div`,{className:`absolute`,style:{width:i,height:i,left:`calc(50% + ${Math.cos(n)*r}px - ${i/2}px)`,top:`calc(50% + ${Math.sin(n)*r}px - ${i/2}px)`,borderRadius:`50%`,background:t%3==0?`radial-gradient(circle, rgba(255,255,255,0.9) 0%, transparent 60%)`:`radial-gradient(circle, rgba(255,235,120,0.85) 0%, transparent 60%)`,animation:`onboard-sparkle-twinkle ${2.5+t%5*.7}s ease-in-out ${t*.25}s infinite`}},`outer-${t}`)}),Array.from({length:24}).map((e,t)=>{let n=(Math.sin(t*2.7+1.3)*.5+.5)*80+10,r=(Math.cos(t*3.1+.7)*.5+.5)*70+10,i=3+t%3*2;return(0,Q.jsx)(`div`,{className:`absolute`,style:{width:i,height:i,left:`${n}%`,top:`${r}%`,borderRadius:`50%`,background:t%4==0?`radial-gradient(circle, rgba(255,255,255,0.95) 0%, transparent 70%)`:`radial-gradient(circle, rgba(255,240,160,0.8) 0%, transparent 70%)`,animation:`onboard-sparkle-twinkle ${2+t%7*.6}s ease-in-out ${t*.18}s infinite`}},`field-${t}`)}),Array.from({length:10}).map((e,t)=>{let n=(Math.sin(t*1.9)*.5+.5)*70+15;return(0,Q.jsx)(`div`,{className:`absolute`,style:{width:5+t%3*3,height:5+t%3*3,left:`${n}%`,bottom:`20%`,borderRadius:`50%`,background:`radial-gradient(circle, rgba(255,250,200,0.9) 0%, rgba(255,230,120,0.3) 50%, transparent 100%)`,animation:`onboard-sparkle-drift ${4+t*.5}s ease-out ${t*.5}s infinite`}},`drift-${t}`)}),(0,Q.jsx)(`div`,{className:K(`relative transition-opacity duration-1000`,E?`opacity-100`:`opacity-0`),children:(0,Q.jsx)(bn,{companion:le,size:`lg`,animated:!0,className:`size-[30rem] sm:size-[36rem] md:size-[44rem]`})})]}),g===`dialog`&&(0,Q.jsx)(`div`,{className:`absolute inset-x-0 bottom-0 flex justify-center pb-28 sm:pb-36 px-8`,children:(0,Q.jsxs)(`div`,{className:`relative max-w-md w-full text-center`,children:[(0,Q.jsx)(`div`,{className:`absolute -inset-32`,style:{background:`radial-gradient(ellipse at center, rgba(0,30,50,0.40) 0%, rgba(0,30,50,0.18) 35%, transparent 65%)`,backdropFilter:`blur(24px)`,WebkitBackdropFilter:`blur(24px)`,mask:`radial-gradient(ellipse at center, black 25%, transparent 65%)`,WebkitMask:`radial-gradient(ellipse at center, black 25%, transparent 65%)`}}),(0,Q.jsxs)(`div`,{className:`relative`,children:[(0,Q.jsx)(`p`,{className:`text-[11px] text-white/50 tracking-[0.2em] uppercase mb-3`,children:`???`}),(0,Q.jsxs)(`p`,{className:`text-base sm:text-lg text-white leading-relaxed font-light min-h-[3em]`,children:[de.displayed,!de.done&&(0,Q.jsx)(`span`,{className:`inline-block w-[2px] h-[1em] bg-white/50 ml-0.5 animate-pulse align-text-bottom`})]}),de.done&&(0,Q.jsx)(`div`,{className:`mt-4 animate-onboard-continue-pulse`,children:(0,Q.jsx)(`span`,{className:`text-xs text-white/30`,children:`▼`})})]})]})}),g===`naming`&&(0,Q.jsx)(`div`,{className:`absolute inset-x-0 bottom-0 flex justify-center pb-28 sm:pb-36 px-8`,children:(0,Q.jsxs)(`div`,{className:K(`relative max-w-md w-full text-center`,P?`animate-onboard-soft-fade-in`:`opacity-0`),children:[(0,Q.jsx)(`div`,{className:`absolute -inset-32`,style:{background:`radial-gradient(ellipse at center, rgba(0,30,50,0.40) 0%, rgba(0,30,50,0.18) 35%, transparent 65%)`,backdropFilter:`blur(24px)`,WebkitBackdropFilter:`blur(24px)`,mask:`radial-gradient(ellipse at center, black 25%, transparent 65%)`,WebkitMask:`radial-gradient(ellipse at center, black 25%, transparent 65%)`}}),(0,Q.jsxs)(`div`,{className:`relative`,children:[(0,Q.jsx)(`p`,{className:`text-[11px] text-white/50 tracking-[0.2em] uppercase mb-3`,children:`???`}),(0,Q.jsxs)(`p`,{className:`text-base sm:text-lg text-white/85 leading-relaxed font-light mb-6 min-h-[1.5em] whitespace-pre-line`,children:[fe.displayed,!fe.done&&(0,Q.jsx)(`span`,{className:`inline-block w-[2px] h-[1em] bg-white/50 ml-0.5 animate-pulse align-text-bottom`})]}),fe.done&&(0,Q.jsxs)(`div`,{className:`space-y-3 animate-onboard-soft-fade-in`,children:[(0,Q.jsx)(Ie,{ref:ae,type:`text`,value:b,onChange:e=>x(e.target.value),placeholder:`...`,maxLength:32,autoFocus:!0,className:K(`text-center text-lg font-light h-12`,`bg-white/10 border-transparent text-white placeholder:text-white/30`,`focus:bg-white/[0.25] focus:border-transparent focus:ring-0 focus:outline-none`,`focus-visible:ring-0 focus-visible:ring-offset-0`,`focus:shadow-[0_0_15px_rgba(255,255,255,0.15),0_0_40px_rgba(255,250,230,0.08)]`,`transition-all duration-300`,`rounded-full transition-shadow duration-500`),onKeyDown:e=>{e.key===`Enter`&&b.trim()&&ye()}}),b.trim()&&(0,Q.jsx)(q,{onClick:ye,disabled:S,className:K(`max-w-[12rem] mx-auto h-10 px-8 text-sm font-light tracking-wide`,`bg-white/15 hover:bg-white/22 text-white/80 border-transparent`,`rounded-full transition-all duration-300`,`focus-visible:ring-0 focus-visible:ring-offset-0`),variant:`ghost`,children:`That's the one.`})]})]})]})}),k&&(0,Q.jsx)(`div`,{className:`absolute inset-0 bg-white pointer-events-none`,style:{zIndex:90,animation:`blobbi-fade-to-white 2s ease-in forwards`}})]})}function Vr(e,t){if(t){let n=e.find(e=>e.d===t);if(n)return n}return e[0]}function Hr({companions:e,currentCompanionD:t}){let n=e.filter(e=>e.stage===`baby`||e.stage===`adult`);if(n.length>0)return{kind:`has-blobbi`,selected:Vr(n,t)};let r=e.filter(e=>e.stage===`egg`);return r.length>0?{kind:`reuse-egg`,egg:(t?r.find(e=>e.d===t):void 0)??(r.length===1?r[0]:r[Math.floor(Math.random()*r.length)])}:{kind:`allow-hatch`}}var Ur=new Set([`incubation_time`,`incubation_progress`,`egg_temperature`,`egg_status`,`shell_integrity`,`fees`,`start_incubation`,`interact_6_progress`]);function Wr(e,t){return e.tags.find(([e])=>e===t)?.[1]}function Gr(e){return e.tags.some(([e])=>Ur.has(e))}function Kr(e){if(e.kind!==31124||!ot(e)||Gr(e))return!1;let t=Wr(e,`d`);if(!t||!yt(t))return!1;let n=Wr(e,`seed`);return!(!n||n.length!==64||!Wr(e,`name`))}function qr(e){let t=e.filter(Kr),n=new Map;for(let e of t){let t=Wr(e,`d`);if(!t)continue;let r=n.get(t);(!r||e.created_at>r.created_at)&&n.set(t,e)}let r=[];for(let e of n.values()){let t=ct(e);t&&r.push({...t,isLegacy:!1})}return r.sort((e,t)=>e.d.localeCompare(t.d))}function Jr(e,t){let{nostr:n}=ve(),r=H({queryKey:[`blobbi-recovery`,e],queryFn:async({signal:t})=>e?qr(await n.query([{kinds:[Y],authors:[e]}],{signal:t})):[],enabled:!!e&&t,staleTime:3e4,gcTime:300*1e3,refetchOnWindowFocus:!1,refetchOnReconnect:!0,retry:2});return{companions:(0,Z.useMemo)(()=>r.data??[],[r.data]),isLoading:r.isLoading,isFetching:r.isFetching}}function Yr({companion:e,onEvolve:t,onComplete:n}){let[r,i]=(0,Z.useState)(`gather`),[a,o]=(0,Z.useState)(!1),[s,c]=(0,Z.useState)(!1),[l,u]=(0,Z.useState)(!1),[d,f]=(0,Z.useState)(!1),p=(0,Z.useRef)(!1),m=(0,Z.useRef)(n);m.current=n;let h=(0,Z.useRef)(t);h.current=t;let g=e.visualTraits.baseColor??`#8b5cf6`,{r:_,g:v,b:y}=(0,Z.useMemo)(()=>Pr(g),[g]),b=Nr(`${e.name} has evolved!`,l),x=Nr(`A new chapter begins...`,b.done),S=(0,Z.useMemo)(()=>({...e,stage:`adult`,state:`active`,progressionState:`none`}),[e]),C=(0,Z.useMemo)(()=>Ir(g),[g]),w=(0,Z.useMemo)(()=>{let e=Math.round(_*.12),t=Math.round(v*.12),n=Math.round(y*.12);return`radial-gradient(ellipse at center, rgb(${e+10},${t+15},${n+25}) 0%, rgb(${e+5},${t+10},${n+18}) 50%, rgb(${e},${t+5},${n+12}) 100%)`},[_,v,y]);(0,Z.useEffect)(()=>{let e=setTimeout(()=>{i(`flash`),o(!0),J()},2800),t=setTimeout(()=>{o(!1),i(`reveal`),c(!0),u(!0)},3200),n=setTimeout(()=>{f(!0),setTimeout(()=>{i(`complete`),m.current()},2e3)},6e3);return()=>{clearTimeout(e),clearTimeout(t),clearTimeout(n)}},[]),(0,Z.useEffect)(()=>{r===`flash`&&!p.current&&(p.current=!0,h.current().catch(console.error))},[r]);let T=r===`gather`,E=r===`reveal`;return(0,Q.jsxs)(`div`,{"data-evolve-ceremony":!0,className:`fixed inset-0 z-50 overflow-hidden select-none`,style:{background:E?C:w,transition:`background 0.15s ease-out`},children:[E&&(0,Q.jsx)(`div`,{className:`absolute inset-0 pointer-events-none`,style:{background:`radial-gradient(ellipse at 50% 45%, transparent 30%, rgba(0,0,0,0.12) 70%, rgba(0,0,0,0.25) 100%)`}}),T&&(0,Q.jsx)(`div`,{className:`absolute inset-0`,style:{background:`radial-gradient(ellipse at 50% 50%, rgba(${_},${v},${y},0.25) 0%, transparent 60%)`,opacity:.15}}),T&&(0,Q.jsx)(`div`,{className:`absolute inset-0 pointer-events-none overflow-hidden`,children:Array.from({length:12}).map((e,t)=>{let n=t/12*360,r=t*.25;return(0,Q.jsx)(`div`,{className:`absolute left-1/2 top-1/2`,style:{width:4+t%3*2,height:4+t%3*2,borderRadius:`50%`,background:t%2==0?`radial-gradient(circle, rgba(${_},${v},${y},0.9) 0%, transparent 70%)`:`radial-gradient(circle, rgba(255,255,255,0.9) 0%, transparent 70%)`,animation:`evolve-spiral-in 3s ease-in ${r}s infinite`,transform:`rotate(${n}deg) translateX(200px)`}},`particle-${t}`)})}),T&&(0,Q.jsxs)(`div`,{className:`absolute inset-0 flex items-center justify-center`,style:{paddingBottom:`10%`},children:[(0,Q.jsx)(`div`,{className:`absolute rounded-full`,style:{width:250,height:250,background:`radial-gradient(circle, rgba(${_},${v},${y},0.2) 0%, transparent 70%)`,filter:`blur(20px)`,animation:`evolve-glow-pulse 2s ease-in-out infinite`}}),(0,Q.jsx)(`div`,{className:`relative`,children:(0,Q.jsx)(bn,{companion:e,size:`lg`,animated:!0,className:`size-56 sm:size-64 md:size-72`})})]}),a&&(0,Q.jsx)(`div`,{className:`absolute inset-0 bg-white pointer-events-none`,style:{zIndex:80,animation:`onboard-screen-flash 2s ease-out forwards`}}),E&&(0,Q.jsxs)(`div`,{className:`absolute inset-0 flex items-center justify-center pointer-events-none`,style:{paddingBottom:`18%`},children:[(0,Q.jsx)(`div`,{className:`absolute`,style:{opacity:+!!s,transform:s?`scale(1)`:`scale(0.7)`,transition:`opacity 0.2s ease-out, transform 0.2s ease-out`},children:(0,Q.jsx)(`div`,{className:`animate-onboard-golden-rotate`,style:{width:800,height:800,background:`conic-gradient(
                  from 0deg,
                  rgba(${_},${v},${y},0.15) 0deg,
                  rgba(255,255,255,0.35) 50deg,
                  rgba(${_},${v},${y},0.18) 100deg,
                  rgba(255,255,255,0.12) 150deg,
                  rgba(${_},${v},${y},0.30) 210deg,
                  rgba(255,255,255,0.15) 270deg,
                  rgba(${_},${v},${y},0.12) 320deg,
                  rgba(${_},${v},${y},0.15) 360deg
                )`,borderRadius:`50%`,filter:`blur(30px)`}})}),(0,Q.jsx)(`div`,{className:K(`absolute rounded-full transition-opacity duration-150`,s?`opacity-100`:`opacity-0`),style:{width:320,height:320,background:`radial-gradient(circle, rgba(255,255,245,0.60) 0%, rgba(${_},${v},${y},0.20) 40%, transparent 70%)`}}),(0,Q.jsx)(`div`,{className:K(`absolute rounded-full transition-opacity duration-200`,s?`opacity-100`:`opacity-0`),style:{width:650,height:650,background:`radial-gradient(circle, rgba(${_},${v},${y},0.25) 0%, rgba(${_},${v},${y},0.10) 40%, transparent 65%)`,filter:`blur(15px)`}}),Array.from({length:18}).map((e,t)=>{let n=t/18*Math.PI*2,r=90+t%4*40,i=4+t%3*3;return(0,Q.jsx)(`div`,{className:`absolute`,style:{width:i,height:i,left:`calc(50% + ${Math.cos(n)*r}px - ${i/2}px)`,top:`calc(50% + ${Math.sin(n)*r}px - ${i/2}px)`,borderRadius:`50%`,background:t%2==0?`radial-gradient(circle, rgba(255,255,255,1) 0%, rgba(255,255,255,0.3) 50%, transparent 70%)`:`radial-gradient(circle, rgba(${_},${v},${y},0.9) 0%, rgba(${_},${v},${y},0.2) 50%, transparent 70%)`,animation:`onboard-sparkle-twinkle ${1.5+t%6*.5}s ease-in-out ${t*.15}s infinite`}},`spark-${t}`)}),Array.from({length:14}).map((e,t)=>{let n=t/14*Math.PI*2+.4,r=180+t%3*45,i=5+t%4*2;return(0,Q.jsx)(`div`,{className:`absolute`,style:{width:i,height:i,left:`calc(50% + ${Math.cos(n)*r}px - ${i/2}px)`,top:`calc(50% + ${Math.sin(n)*r}px - ${i/2}px)`,borderRadius:`50%`,background:t%3==0?`radial-gradient(circle, rgba(255,255,255,0.9) 0%, transparent 60%)`:`radial-gradient(circle, rgba(${_},${v},${y},0.7) 0%, transparent 60%)`,animation:`onboard-sparkle-twinkle ${2.5+t%5*.7}s ease-in-out ${t*.2}s infinite`}},`outer-${t}`)}),Array.from({length:8}).map((e,t)=>{let n=(Math.sin(t*2.3)*.5+.5)*70+15;return(0,Q.jsx)(`div`,{className:`absolute`,style:{width:5+t%3*3,height:5+t%3*3,left:`${n}%`,bottom:`20%`,borderRadius:`50%`,background:`radial-gradient(circle, rgba(${_},${v},${y},0.8) 0%, rgba(${_},${v},${y},0.2) 50%, transparent 100%)`,animation:`onboard-sparkle-drift ${4+t*.5}s ease-out ${t*.4}s infinite`}},`mote-${t}`)}),(0,Q.jsx)(`div`,{className:K(`relative transition-opacity duration-150`,s?`opacity-100`:`opacity-0`),children:(0,Q.jsx)(bn,{companion:S,size:`lg`,animated:!0,className:`size-[30rem] sm:size-[36rem] md:size-[44rem]`})})]}),E&&l&&(0,Q.jsx)(`div`,{className:`absolute inset-x-0 bottom-0 flex justify-center pb-28 sm:pb-36 px-8`,children:(0,Q.jsxs)(`div`,{className:`relative max-w-md w-full text-center`,children:[(0,Q.jsx)(`div`,{className:`absolute -inset-32`,style:{background:`radial-gradient(ellipse at center, rgba(0,30,50,0.35) 0%, rgba(0,30,50,0.15) 35%, transparent 65%)`,backdropFilter:`blur(24px)`,WebkitBackdropFilter:`blur(24px)`,mask:`radial-gradient(ellipse at center, black 25%, transparent 65%)`,WebkitMask:`radial-gradient(ellipse at center, black 25%, transparent 65%)`}}),(0,Q.jsxs)(`div`,{className:`relative`,children:[(0,Q.jsxs)(`p`,{className:`text-base sm:text-lg text-white leading-relaxed font-light min-h-[1.5em]`,children:[b.displayed,!b.done&&(0,Q.jsx)(`span`,{className:`inline-block w-[2px] h-[1em] bg-white/50 ml-0.5 animate-pulse align-text-bottom`})]}),b.done&&(0,Q.jsxs)(`p`,{className:`text-sm text-white/60 mt-2 font-light min-h-[1.25em]`,children:[x.displayed,!x.done&&(0,Q.jsx)(`span`,{className:`inline-block w-[2px] h-[0.85em] bg-white/30 ml-0.5 animate-pulse align-text-bottom`})]})]})]})}),d&&(0,Q.jsx)(`div`,{className:`absolute inset-0 bg-white pointer-events-none`,style:{zIndex:90,animation:`blobbi-fade-to-white 2s ease-in forwards`}})]})}function Xr(e,t){if(e.match(/^[a-z]+:\/\//i))return e;if(e.match(/^\/\//))return window.location.protocol+e;if(e.match(/^[a-z]+:/i))return e;let n=document.implementation.createHTMLDocument(),r=n.createElement(`base`),i=n.createElement(`a`);return n.head.appendChild(r),n.body.appendChild(i),t&&(r.href=t),i.href=e,i.href}var Zr=(()=>{let e=0,t=()=>`0000${(Math.random()*36**4<<0).toString(36)}`.slice(-4);return()=>(e+=1,`u${t()}${e}`)})();function Qr(e){let t=[];for(let n=0,r=e.length;n<r;n++)t.push(e[n]);return t}var $r=null;function ei(e={}){return $r||(e.includeStyleProperties?($r=e.includeStyleProperties,$r):($r=Qr(window.getComputedStyle(document.documentElement)),$r))}function ti(e,t){let n=(e.ownerDocument.defaultView||window).getComputedStyle(e).getPropertyValue(t);return n?parseFloat(n.replace(`px`,``)):0}function ni(e){let t=ti(e,`border-left-width`),n=ti(e,`border-right-width`);return e.clientWidth+t+n}function ri(e){let t=ti(e,`border-top-width`),n=ti(e,`border-bottom-width`);return e.clientHeight+t+n}function ii(e,t={}){return{width:t.width||ni(e),height:t.height||ri(e)}}function ai(){let e,t;try{t=process}catch{}let n=t&&t.env?t.env.devicePixelRatio:null;return n&&(e=parseInt(n,10),Number.isNaN(e)&&(e=1)),e||window.devicePixelRatio||1}var oi=16384;function si(e){(e.width>oi||e.height>oi)&&(e.width>oi&&e.height>oi?e.width>e.height?(e.height*=oi/e.width,e.width=oi):(e.width*=oi/e.height,e.height=oi):e.width>oi?(e.height*=oi/e.width,e.width=oi):(e.width*=oi/e.height,e.height=oi))}function ci(e){return new Promise((t,n)=>{let r=new Image;r.onload=()=>{r.decode().then(()=>{requestAnimationFrame(()=>t(r))})},r.onerror=n,r.crossOrigin=`anonymous`,r.decoding=`async`,r.src=e})}async function li(e){return Promise.resolve().then(()=>new XMLSerializer().serializeToString(e)).then(encodeURIComponent).then(e=>`data:image/svg+xml;charset=utf-8,${e}`)}async function ui(e,t,n){let r=`http://www.w3.org/2000/svg`,i=document.createElementNS(r,`svg`),a=document.createElementNS(r,`foreignObject`);return i.setAttribute(`width`,`${t}`),i.setAttribute(`height`,`${n}`),i.setAttribute(`viewBox`,`0 0 ${t} ${n}`),a.setAttribute(`width`,`100%`),a.setAttribute(`height`,`100%`),a.setAttribute(`x`,`0`),a.setAttribute(`y`,`0`),a.setAttribute(`externalResourcesRequired`,`true`),i.appendChild(a),a.appendChild(e),li(i)}var di=(e,t)=>{if(e instanceof t)return!0;let n=Object.getPrototypeOf(e);return n===null?!1:n.constructor.name===t.name||di(n,t)};function fi(e){let t=e.getPropertyValue(`content`);return`${e.cssText} content: '${t.replace(/'|"/g,``)}';`}function pi(e,t){return ei(t).map(t=>`${t}: ${e.getPropertyValue(t)}${e.getPropertyPriority(t)?` !important`:``};`).join(` `)}function mi(e,t,n,r){let i=`.${e}:${t}`,a=n.cssText?fi(n):pi(n,r);return document.createTextNode(`${i}{${a}}`)}function hi(e,t,n,r){let i=window.getComputedStyle(e,n),a=i.getPropertyValue(`content`);if(a===``||a===`none`)return;let o=Zr();try{t.className=`${t.className} ${o}`}catch{return}let s=document.createElement(`style`);s.appendChild(mi(o,n,i,r)),t.appendChild(s)}function gi(e,t,n){hi(e,t,`:before`,n),hi(e,t,`:after`,n)}var _i=`application/font-woff`,vi=`image/jpeg`,yi={woff:_i,woff2:_i,ttf:`application/font-truetype`,eot:`application/vnd.ms-fontobject`,png:`image/png`,jpg:vi,jpeg:vi,gif:`image/gif`,tiff:`image/tiff`,svg:`image/svg+xml`,webp:`image/webp`};function bi(e){let t=/\.([^./]*?)$/g.exec(e);return t?t[1]:``}function xi(e){return yi[bi(e).toLowerCase()]||``}function Si(e){return e.split(/,/)[1]}function Ci(e){return e.search(/^(data:)/)!==-1}function wi(e,t){return`data:${t};base64,${e}`}async function Ti(e,t,n){let r=await fetch(e,t);if(r.status===404)throw Error(`Resource "${r.url}" not found`);let i=await r.blob();return new Promise((e,t)=>{let a=new FileReader;a.onerror=t,a.onloadend=()=>{try{e(n({res:r,result:a.result}))}catch(e){t(e)}},a.readAsDataURL(i)})}var Ei={};function Di(e,t,n){let r=e.replace(/\?.*/,``);return n&&(r=e),/ttf|otf|eot|woff2?/i.test(r)&&(r=r.replace(/.*\//,``)),t?`[${t}]${r}`:r}async function Oi(e,t,n){let r=Di(e,t,n.includeQueryParams);if(Ei[r]!=null)return Ei[r];n.cacheBust&&(e+=(/\?/.test(e)?`&`:`?`)+new Date().getTime());let i;try{i=wi(await Ti(e,n.fetchRequestInit,({res:e,result:n})=>(t||=e.headers.get(`Content-Type`)||``,Si(n))),t)}catch(t){i=n.imagePlaceholder||``;let r=`Failed to fetch resource: ${e}`;t&&(r=typeof t==`string`?t:t.message),r&&console.warn(r)}return Ei[r]=i,i}async function ki(e){let t=e.toDataURL();return t===`data:,`?e.cloneNode(!1):ci(t)}async function Ai(e,t){if(e.currentSrc){let t=document.createElement(`canvas`),n=t.getContext(`2d`);return t.width=e.clientWidth,t.height=e.clientHeight,n?.drawImage(e,0,0,t.width,t.height),ci(t.toDataURL())}let n=e.poster;return ci(await Oi(n,xi(n),t))}async function ji(e,t){try{if(e?.contentDocument?.body)return await Vi(e.contentDocument.body,t,!0)}catch{}return e.cloneNode(!1)}async function Mi(e,t){return di(e,HTMLCanvasElement)?ki(e):di(e,HTMLVideoElement)?Ai(e,t):di(e,HTMLIFrameElement)?ji(e,t):e.cloneNode(Pi(e))}var Ni=e=>e.tagName!=null&&e.tagName.toUpperCase()===`SLOT`,Pi=e=>e.tagName!=null&&e.tagName.toUpperCase()===`SVG`;async function Fi(e,t,n){if(Pi(t))return t;let r=[];return r=Ni(e)&&e.assignedNodes?Qr(e.assignedNodes()):di(e,HTMLIFrameElement)&&e.contentDocument?.body?Qr(e.contentDocument.body.childNodes):Qr((e.shadowRoot??e).childNodes),r.length===0||di(e,HTMLVideoElement)||await r.reduce((e,r)=>e.then(()=>Vi(r,n)).then(e=>{e&&t.appendChild(e)}),Promise.resolve()),t}function Ii(e,t,n){let r=t.style;if(!r)return;let i=window.getComputedStyle(e);i.cssText?(r.cssText=i.cssText,r.transformOrigin=i.transformOrigin):ei(n).forEach(n=>{let a=i.getPropertyValue(n);n===`font-size`&&a.endsWith(`px`)&&(a=`${Math.floor(parseFloat(a.substring(0,a.length-2)))-.1}px`),di(e,HTMLIFrameElement)&&n===`display`&&a===`inline`&&(a=`block`),n===`d`&&t.getAttribute(`d`)&&(a=`path(${t.getAttribute(`d`)})`),r.setProperty(n,a,i.getPropertyPriority(n))})}function Li(e,t){di(e,HTMLTextAreaElement)&&(t.innerHTML=e.value),di(e,HTMLInputElement)&&t.setAttribute(`value`,e.value)}function Ri(e,t){if(di(e,HTMLSelectElement)){let n=t,r=Array.from(n.children).find(t=>e.value===t.getAttribute(`value`));r&&r.setAttribute(`selected`,``)}}function zi(e,t,n){return di(t,Element)&&(Ii(e,t,n),gi(e,t,n),Li(e,t),Ri(e,t)),t}async function Bi(e,t){let n=e.querySelectorAll?e.querySelectorAll(`use`):[];if(n.length===0)return e;let r={};for(let i=0;i<n.length;i++){let a=n[i].getAttribute(`xlink:href`);if(a){let n=e.querySelector(a),i=document.querySelector(a);!n&&i&&!r[a]&&(r[a]=await Vi(i,t,!0))}}let i=Object.values(r);if(i.length){let t=`http://www.w3.org/1999/xhtml`,n=document.createElementNS(t,`svg`);n.setAttribute(`xmlns`,t),n.style.position=`absolute`,n.style.width=`0`,n.style.height=`0`,n.style.overflow=`hidden`,n.style.display=`none`;let r=document.createElementNS(t,`defs`);n.appendChild(r);for(let e=0;e<i.length;e++)r.appendChild(i[e]);e.appendChild(n)}return e}async function Vi(e,t,n){return!n&&t.filter&&!t.filter(e)?null:Promise.resolve(e).then(e=>Mi(e,t)).then(n=>Fi(e,n,t)).then(n=>zi(e,n,t)).then(e=>Bi(e,t))}var Hi=/url\((['"]?)([^'"]+?)\1\)/g,Ui=/url\([^)]+\)\s*format\((["']?)([^"']+)\1\)/g,Wi=/src:\s*(?:url\([^)]+\)\s*format\([^)]+\)[,;]\s*)+/g;function Gi(e){let t=e.replace(/([.*+?^${}()|\[\]\/\\])/g,`\\$1`);return RegExp(`(url\\(['"]?)(${t})(['"]?\\))`,`g`)}function Ki(e){let t=[];return e.replace(Hi,(e,n,r)=>(t.push(r),e)),t.filter(e=>!Ci(e))}async function qi(e,t,n,r,i){try{let a=n?Xr(t,n):t,o=xi(t),s;return s=i?wi(await i(a),o):await Oi(a,o,r),e.replace(Gi(t),`$1${s}$3`)}catch{}return e}function Ji(e,{preferredFontFormat:t}){return t?e.replace(Wi,e=>{for(;;){let[n,,r]=Ui.exec(e)||[];if(!r)return``;if(r===t)return`src: ${n};`}}):e}function Yi(e){return e.search(Hi)!==-1}async function Xi(e,t,n){if(!Yi(e))return e;let r=Ji(e,n);return Ki(r).reduce((e,r)=>e.then(e=>qi(e,r,t,n)),Promise.resolve(r))}async function Zi(e,t,n){let r=t.style?.getPropertyValue(e);if(r){let i=await Xi(r,null,n);return t.style.setProperty(e,i,t.style.getPropertyPriority(e)),!0}return!1}async function Qi(e,t){await Zi(`background`,e,t)||await Zi(`background-image`,e,t),await Zi(`mask`,e,t)||await Zi(`-webkit-mask`,e,t)||await Zi(`mask-image`,e,t)||await Zi(`-webkit-mask-image`,e,t)}async function $i(e,t){let n=di(e,HTMLImageElement);if(!(n&&!Ci(e.src))&&!(di(e,SVGImageElement)&&!Ci(e.href.baseVal)))return;let r=n?e.src:e.href.baseVal,i=await Oi(r,xi(r),t);await new Promise((r,a)=>{e.onload=r,e.onerror=t.onImageErrorHandler?(...e)=>{try{r(t.onImageErrorHandler(...e))}catch(e){a(e)}}:a;let o=e;o.decode&&=r,o.loading===`lazy`&&(o.loading=`eager`),n?(e.srcset=``,e.src=i):e.href.baseVal=i})}async function ea(e,t){let n=Qr(e.childNodes).map(e=>ta(e,t));await Promise.all(n).then(()=>e)}async function ta(e,t){di(e,Element)&&(await Qi(e,t),await $i(e,t),await ea(e,t))}function na(e,t){let{style:n}=e;t.backgroundColor&&(n.backgroundColor=t.backgroundColor),t.width&&(n.width=`${t.width}px`),t.height&&(n.height=`${t.height}px`);let r=t.style;return r!=null&&Object.keys(r).forEach(e=>{n[e]=r[e]}),e}var ra={};async function ia(e){let t=ra[e];return t??(t={url:e,cssText:await(await fetch(e)).text()},ra[e]=t,t)}async function aa(e,t){let n=e.cssText,r=/url\(["']?([^"')]+)["']?\)/g,i=(n.match(/url\([^)]+\)/g)||[]).map(async i=>{let a=i.replace(r,`$1`);return a.startsWith(`https://`)||(a=new URL(a,e.url).href),Ti(a,t.fetchRequestInit,({result:e})=>(n=n.replace(i,`url(${e})`),[i,e]))});return Promise.all(i).then(()=>n)}function oa(e){if(e==null)return[];let t=[],n=e.replace(/(\/\*[\s\S]*?\*\/)/gi,``),r=RegExp(`((@.*?keyframes [\\s\\S]*?){([\\s\\S]*?}\\s*?)})`,`gi`);for(;;){let e=r.exec(n);if(e===null)break;t.push(e[0])}n=n.replace(r,``);let i=/@import[\s\S]*?url\([^)]*\)[\s\S]*?;/gi,a=RegExp(`((\\s*?(?:\\/\\*[\\s\\S]*?\\*\\/)?\\s*?@media[\\s\\S]*?){([\\s\\S]*?)}\\s*?})|(([\\s\\S]*?){([\\s\\S]*?)})`,`gi`);for(;;){let e=i.exec(n);if(e===null){if(e=a.exec(n),e===null)break;i.lastIndex=a.lastIndex}else a.lastIndex=i.lastIndex;t.push(e[0])}return t}async function sa(e,t){let n=[],r=[];return e.forEach(n=>{if(`cssRules`in n)try{Qr(n.cssRules||[]).forEach((e,i)=>{if(e.type===CSSRule.IMPORT_RULE){let a=i+1,o=e.href,s=ia(o).then(e=>aa(e,t)).then(e=>oa(e).forEach(e=>{try{n.insertRule(e,e.startsWith(`@import`)?a+=1:n.cssRules.length)}catch(t){console.error(`Error inserting rule from remote css`,{rule:e,error:t})}})).catch(e=>{console.error(`Error loading remote css`,e.toString())});r.push(s)}})}catch(i){let a=e.find(e=>e.href==null)||document.styleSheets[0];n.href!=null&&r.push(ia(n.href).then(e=>aa(e,t)).then(e=>oa(e).forEach(e=>{a.insertRule(e,a.cssRules.length)})).catch(e=>{console.error(`Error loading remote stylesheet`,e)})),console.error(`Error inlining remote css file`,i)}}),Promise.all(r).then(()=>(e.forEach(e=>{if(`cssRules`in e)try{Qr(e.cssRules||[]).forEach(e=>{n.push(e)})}catch(t){console.error(`Error while reading CSS rules from ${e.href}`,t)}}),n))}function ca(e){return e.filter(e=>e.type===CSSRule.FONT_FACE_RULE).filter(e=>Yi(e.style.getPropertyValue(`src`)))}async function la(e,t){if(e.ownerDocument==null)throw Error(`Provided element is not within a Document`);return ca(await sa(Qr(e.ownerDocument.styleSheets),t))}function ua(e){return e.trim().replace(/["']/g,``)}function da(e){let t=new Set;function n(e){(e.style.fontFamily||getComputedStyle(e).fontFamily).split(`,`).forEach(e=>{t.add(ua(e))}),Array.from(e.children).forEach(e=>{e instanceof HTMLElement&&n(e)})}return n(e),t}async function fa(e,t){let n=await la(e,t),r=da(e);return(await Promise.all(n.filter(e=>r.has(ua(e.style.fontFamily))).map(e=>{let n=e.parentStyleSheet?e.parentStyleSheet.href:null;return Xi(e.cssText,n,t)}))).join(`
`)}async function pa(e,t){let n=t.fontEmbedCSS==null?t.skipFonts?null:await fa(e,t):t.fontEmbedCSS;if(n){let t=document.createElement(`style`),r=document.createTextNode(n);t.appendChild(r),e.firstChild?e.insertBefore(t,e.firstChild):e.appendChild(t)}}async function ma(e,t={}){let{width:n,height:r}=ii(e,t),i=await Vi(e,t,!0);return await pa(i,t),await ta(i,t),na(i,t),await ui(i,n,r)}async function ha(e,t={}){let{width:n,height:r}=ii(e,t),i=await ci(await ma(e,t)),a=document.createElement(`canvas`),o=a.getContext(`2d`),s=t.pixelRatio||ai(),c=t.canvasWidth||n,l=t.canvasHeight||r;return a.width=c*s,a.height=l*s,t.skipAutoScale||si(a),a.style.width=`${c}`,a.style.height=`${l}`,t.backgroundColor&&(o.fillStyle=t.backgroundColor,o.fillRect(0,0,a.width,a.height)),o.drawImage(i,0,0,a.width,a.height),a}async function ga(e,t={}){return(await ha(e,t)).toDataURL()}var _a=320,va=400,ya=16,ba=16,xa=80,Sa=_a-ba*2,Ca=va-ya-xa,wa=(0,Z.forwardRef)(function({companion:e,caption:t,showStage:n=!1,className:r},i){let a=t??e.name,o=e.stage.charAt(0).toUpperCase()+e.stage.slice(1);return(0,Q.jsxs)(`div`,{ref:i,className:K(`relative flex flex-col`,`bg-[#fafafa]`,`rounded-sm`,`shadow-lg`,r),style:{width:_a,height:va,paddingTop:ya,paddingLeft:ba,paddingRight:ba,paddingBottom:xa},children:[(0,Q.jsxs)(`div`,{className:`relative flex items-center justify-center overflow-hidden`,style:{width:Sa,height:Ca,background:`linear-gradient(135deg, #e0e7ff 0%, #c7d2fe 50%, #ddd6fe 100%)`},children:[(0,Q.jsx)(`div`,{className:`absolute inset-0 pointer-events-none`,style:{background:`radial-gradient(ellipse at center, transparent 40%, rgba(0,0,0,0.08) 100%)`}}),(0,Q.jsx)(bn,{companion:e,size:`lg`,animated:!1,lookMode:`forward`,disableBlink:!0,className:`size-48 z-10`})]}),(0,Q.jsxs)(`div`,{style:{position:`absolute`,left:0,right:0,bottom:0,height:xa,paddingBottom:12,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,width:_a},children:[(0,Q.jsx)(`p`,{style:{fontFamily:`'Permanent Marker', 'Comic Sans MS', cursive, sans-serif`,fontSize:`1.25rem`,fontWeight:500,color:`#1f2937`,textAlign:`center`,letterSpacing:`0.02em`,maxWidth:`90%`,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`,margin:0},children:a}),n&&(0,Q.jsx)(`span`,{style:{marginTop:4,fontSize:`0.75rem`,color:`#6b7280`,textTransform:`uppercase`,letterSpacing:`0.05em`,whiteSpace:`nowrap`},children:o}),(0,Q.jsx)(`div`,{style:{marginTop:6,fontSize:10,color:`#9ca3af`,whiteSpace:`nowrap`},children:new Date().toLocaleDateString(`en-US`,{month:`short`,day:`numeric`,year:`numeric`})})]})]})});function Ta(e,t){let n=e.split(`,`),r=n[0].match(/:(.*?);/)?.[1]??`image/png`,i=atob(n[1]),a=i.length,o=new Uint8Array(a);for(;a--;)o[a]=i.charCodeAt(a);return new File([o],t,{type:r})}function Ea({open:e,onOpenChange:t,companion:n}){let r=(0,Z.useRef)(null),[i,a]=(0,Z.useState)(!1),[o,s]=(0,Z.useState)(!1),{user:c}=G(),{mutateAsync:l}=Ve(),{mutateAsync:u}=ke(),d=(0,Z.useCallback)(async()=>{if(!r.current)return null;try{return await ga(r.current,{quality:1,pixelRatio:2,cacheBust:!0,skipFonts:!0})}catch(e){return console.error(`[BlobbiPhoto] Failed to generate image:`,e),W({variant:`destructive`,title:`Error`,description:`Failed to capture photo.`}),null}},[]),f=(0,Z.useCallback)(async()=>{a(!0);try{let e=await d();if(!e)return;let t=`${n.name.toLowerCase().replace(/\s+/g,`-`)}-photo.png`;if(we.isNativePlatform()){let n=Ta(e,t),r=URL.createObjectURL(n);await Te(r),URL.revokeObjectURL(r)}else{let n=document.createElement(`a`);n.download=t,n.href=e,n.click()}W({title:`Photo saved!`})}finally{a(!1)}},[d,n.name]),p=(0,Z.useCallback)(async()=>{if(c){s(!0);try{let e=await d();if(!e)return;let r=Ta(e,`${n.name.toLowerCase().replace(/\s+/g,`-`)}-${Date.now()}.png`),i=await l(r),a=i.find(e=>e[0]===`url`);if(!a?.[1])throw Error(`Upload succeeded but no URL returned`);let o=a[1],s=i.map(e=>`${e[0]} ${e[1]}`);await u({kind:1,content:`${n.name} ${o}`,tags:[[`imeta`,...s]]}),W({title:`Posted!`,description:`Your Blobbi photo has been shared.`}),t(!1)}catch(e){console.error(`[BlobbiPhoto] Failed to share:`,e),W({variant:`destructive`,title:`Failed to post`,description:e instanceof Error?e.message:`Please try again.`})}finally{s(!1)}}},[c,d,n.name,l,u,t]);if(!e)return null;let m=i||o;return(0,Q.jsxs)(`div`,{className:`absolute inset-0 z-50 flex flex-col items-center justify-center`,children:[(0,Q.jsx)(`div`,{className:`absolute inset-0 bg-background/60 backdrop-blur-sm`,onClick:()=>!m&&t(!1)}),(0,Q.jsx)(`button`,{onClick:()=>!m&&t(!1),className:`absolute top-3 right-3 z-10 p-2 text-muted-foreground hover:text-foreground transition-colors`,children:(0,Q.jsx)(A,{className:`size-5`})}),(0,Q.jsx)(`div`,{className:`relative z-10 animate-in fade-in zoom-in-95 duration-200`,children:(0,Q.jsx)(wa,{ref:r,companion:n,showStage:!0})}),(0,Q.jsxs)(`div`,{className:`relative z-10 flex items-center gap-6 mt-8`,children:[(0,Q.jsxs)(`button`,{onClick:f,disabled:m,className:K(`flex flex-col items-center gap-1.5 transition-all duration-200`,`hover:scale-110 active:scale-95`,m&&`opacity-50 pointer-events-none`),children:[(0,Q.jsx)(`div`,{className:`size-14 rounded-full flex items-center justify-center text-sky-500`,style:{background:`radial-gradient(circle at 40% 35%, color-mix(in srgb, #0ea5e9 25%, transparent), color-mix(in srgb, #0ea5e9 10%, transparent) 70%)`},children:i?(0,Q.jsx)(k,{className:`size-6 animate-spin`}):(0,Q.jsx)(F,{className:`size-6`})}),(0,Q.jsx)(`span`,{className:`text-xs font-medium text-muted-foreground`,children:`Save`})]}),c&&(0,Q.jsxs)(`button`,{onClick:p,disabled:m,className:K(`flex flex-col items-center gap-1.5 transition-all duration-200`,`hover:scale-110 active:scale-95`,m&&`opacity-50 pointer-events-none`),children:[(0,Q.jsx)(`div`,{className:`size-14 rounded-full flex items-center justify-center text-violet-500`,style:{background:`radial-gradient(circle at 40% 35%, color-mix(in srgb, #8b5cf6 25%, transparent), color-mix(in srgb, #8b5cf6 10%, transparent) 70%)`},children:o?(0,Q.jsx)(k,{className:`size-6 animate-spin`}):(0,Q.jsx)(P,{className:`size-6`})}),(0,Q.jsx)(`span`,{className:`text-xs font-medium text-muted-foreground`,children:`Post`})]})]})]})}var Da=[{id:`nap_in_the_meadow`,title:`Nap in the Meadow`,artist:`Chilltape FM`,url:`https://blossom.ditto.pub/6be1c95e879187f83af2a661ccac2bd96196f7bc334af44529ede6270b2811fc.m4a`,durationSeconds:240,tags:[`relaxing`,`nature`]},{id:`happy_kids`,title:`Happy Kids`,artist:`Dmitrii Kolesnikov`,url:`https://blossom.ditto.pub/94d49abd178aa8afb14737a55e0a7143f6b337f618d74858d011232bb2db845d.m4a`,durationSeconds:129,tags:[`upbeat`,`fun`]},{id:`soft_piano`,title:`Soft Piano`,artist:`Dmitrii Kolesnikov`,url:`https://blossom.ditto.pub/5367242d3dc555c77f5c637fd153df1166708a24c5a4c222bb4dcaeabf740743.m4a`,durationSeconds:124,tags:[`calming`,`sleep`]},{id:`epic_sacred_light`,title:`Epic Sacred Light`,artist:`Ura Megis`,url:`https://blossom.dreamith.to/c22953791d686605958165fd44a84cd7d9fd3d4423ebf786e47891ed3a82c6db.m4a`,durationSeconds:223,tags:[`energetic`,`adventure`]},{id:`split_memories`,title:`Split Memories`,artist:`ido berg`,url:`https://blossom.ditto.pub/57ba2e2122a732449880ae531d4bfac9a580bc19693c7dda735afbfa336b35fe.m4a`,durationSeconds:153,tags:[`ambient`,`relaxing`]},{id:`minhas_mensagens`,title:`Minhas Mensagens`,artist:`PReis`,url:`https://blossom.ditto.pub/0945064dc8f946f3392be23629b166e72090cafca7cca865a20b5395dd83ff46.m4a`,durationSeconds:248,tags:[`ambient`,`relaxing`]}];function Oa(){return Da}function ka(e){return`${Math.floor(e/60)}:${Math.floor(e%60).toString().padStart(2,`0`)}`}function Aa({open:e,onOpenChange:t,onConfirm:n,isLoading:r}){let[i,a]=(0,Z.useState)(null),[o,s]=(0,Z.useState)(!1),[c,l]=(0,Z.useState)(null),u=(0,Z.useRef)(null),d=(0,Z.useRef)(null),f=Oa();(0,Z.useEffect)(()=>()=>{u.current&&=(u.current.pause(),null)},[]),(0,Z.useEffect)(()=>{e&&(a(null),s(!1),l(null),d.current=null)},[e]);let m=(0,Z.useCallback)(e=>{u.current&&(u.current.pause(),s(!1)),a({track:e,url:e.url}),l(null)},[]),g=(0,Z.useCallback)(()=>{if(!i)return;let e=i.url,t=!u.current||d.current!==e;t&&(u.current&&(u.current.pause(),u.current.onended=null,u.current.onerror=null),u.current=new Audio(e),d.current=e,u.current.onended=()=>s(!1),u.current.onerror=()=>{l(`Failed to load this track. Please try another one.`),s(!1)}),o&&!t?(u.current?.pause(),s(!1)):(u.current?.play().catch(()=>{l(`Failed to play this track. Please try another one.`),s(!1)}),s(!0))},[i,o]),_=(0,Z.useCallback)(()=>{i&&(u.current&&(u.current.pause(),s(!1)),n(i))},[i,n]),v=(0,Z.useCallback)(e=>{!e&&u.current&&(u.current.pause(),s(!1)),t(e)},[t]);return(0,Q.jsx)(Ge,{open:e,onOpenChange:v,children:(0,Q.jsxs)(We,{className:`max-w-md max-h-[85vh] flex flex-col p-0`,children:[(0,Q.jsx)(He,{className:`px-6 pt-6 pb-4 border-b`,children:(0,Q.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,Q.jsx)(`div`,{className:`size-10 rounded-xl bg-gradient-to-br from-pink-500/20 to-pink-500/5 flex items-center justify-center`,children:(0,Q.jsx)(D,{className:`size-5 text-pink-500`})}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(Ue,{className:`text-xl`,children:`Play Music`}),(0,Q.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Choose a track to play for your Blobbi`})]})]})}),(0,Q.jsxs)(`div`,{className:`flex-1 overflow-y-auto px-6 py-4`,children:[(0,Q.jsx)(`div`,{className:`grid gap-2`,children:f.map(e=>(0,Q.jsx)(ja,{track:e,isSelected:i?.track.id===e.id,onSelect:()=>m(e)},e.id))}),c&&(0,Q.jsx)(`div`,{className:`mt-4 p-3 rounded-lg bg-amber-500/10 border border-amber-500/30`,children:(0,Q.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,Q.jsx)(le,{className:`size-4 text-amber-500 mt-0.5 shrink-0`}),(0,Q.jsx)(`p`,{className:`text-sm text-amber-600 dark:text-amber-400`,children:c})]})})]}),(0,Q.jsxs)(`div`,{className:`px-6 py-4 border-t bg-muted/30`,children:[i&&(0,Q.jsx)(`div`,{className:`mb-4 p-3 rounded-lg bg-card border`,children:(0,Q.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,Q.jsx)(q,{size:`icon`,variant:`outline`,onClick:g,className:`size-10 rounded-full shrink-0`,children:o?(0,Q.jsx)(p,{className:`size-4`}):(0,Q.jsx)(h,{className:`size-4 ml-0.5`})}),(0,Q.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,Q.jsx)(`p`,{className:`font-medium truncate text-sm`,children:i.track.title}),(0,Q.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:o?`Now playing...`:`Click to preview`})]}),o&&(0,Q.jsx)(fe,{className:`size-4 text-primary animate-pulse shrink-0`})]})}),(0,Q.jsxs)(`div`,{className:`flex gap-3`,children:[(0,Q.jsx)(q,{variant:`outline`,onClick:()=>v(!1),className:`flex-1`,disabled:r,children:`Cancel`}),(0,Q.jsx)(q,{onClick:_,disabled:!i||r,className:`flex-1`,children:r?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(k,{className:`size-4 mr-2 animate-spin`}),`Playing...`]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(D,{className:`size-4 mr-2`}),`Play for Blobbi`]})})]})]})]})})}function ja({track:e,isSelected:t,onSelect:n}){return(0,Q.jsx)(`button`,{type:`button`,onClick:n,className:K(`w-full p-3 rounded-xl text-left transition-all`,`border hover:border-primary/30`,t?`border-primary bg-primary/5 ring-2 ring-primary/20`:`border-border bg-card/60`),children:(0,Q.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,Q.jsx)(`div`,{className:K(`size-10 rounded-lg flex items-center justify-center`,t?`bg-primary/20`:`bg-muted`),children:(0,Q.jsx)(D,{className:K(`size-5`,t?`text-primary`:`text-muted-foreground`)})}),(0,Q.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,Q.jsx)(`p`,{className:`font-medium truncate`,children:e.title}),(0,Q.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:e.artist})]}),(0,Q.jsxs)(`div`,{className:`flex items-center gap-2 shrink-0`,children:[(0,Q.jsx)(`span`,{className:`text-sm text-muted-foreground`,children:ka(e.durationSeconds)}),t&&(0,Q.jsx)(I,{className:`size-4 text-primary`})]})]})})}var Ma=.8;function Na(e={}){let{onEnded:t,onError:n,initialVolume:r=Ma}=e,[i,a]=(0,Z.useState)(`idle`),[o,s]=(0,Z.useState)(null),[c,l]=(0,Z.useState)(null),[u,d]=(0,Z.useState)(r),f=(0,Z.useRef)(null),p=(0,Z.useRef)(null),m=(0,Z.useRef)(r),h=(0,Z.useCallback)(()=>{f.current&&=(f.current.pause(),f.current.onended=null,f.current.onerror=null,f.current.oncanplay=null,f.current.onplaying=null,null),p.current=null,a(`idle`),l(null),s(null)},[]);(0,Z.useEffect)(()=>()=>{h()},[h]);let g=(0,Z.useCallback)((e,r=!1)=>{if(p.current===e&&f.current){r&&f.current.play().catch(()=>{});return}f.current&&(f.current.pause(),f.current.onended=null,f.current.onerror=null,f.current.oncanplay=null,f.current.onplaying=null),a(`loading`),s(null),l(e),p.current=e;let o=new Audio(e);o.volume=m.current,f.current=o,o.oncanplay=()=>{r?o.play().catch(e=>{let t={message:Pa(e),code:e.name};s(t),a(`error`),n?.(t)}):a(`paused`)},o.onplaying=()=>{a(`playing`)},o.onpause=()=>{i===`playing`&&a(`paused`)},o.onended=()=>{a(`paused`),t?.()},o.onerror=()=>{let e={message:`Failed to load audio. The format may not be supported.`,code:`MEDIA_ERR`};s(e),a(`error`),n?.(e)},o.load()},[t,n,i]),_=(0,Z.useCallback)(async()=>{if(f.current)try{s(null),await f.current.play(),a(`playing`)}catch(e){let t={message:Pa(e),code:e instanceof Error?e.name:`UNKNOWN`};s(t),a(`error`),n?.(t)}},[n]),v=(0,Z.useCallback)(()=>{f.current&&(f.current.pause(),a(`paused`))},[]),y=(0,Z.useCallback)(()=>{f.current&&(f.current.pause(),f.current.currentTime=0,p.current=null,a(`stopped`))},[]),b=(0,Z.useCallback)(async()=>{if(f.current){f.current.currentTime=0;try{await f.current.play(),a(`playing`)}catch(e){let t={message:Pa(e),code:e instanceof Error?e.name:`UNKNOWN`};s(t),a(`error`),n?.(t)}}},[n]),x=(0,Z.useCallback)(async()=>{i===`playing`?v():await _()},[i,_,v]),S=(0,Z.useCallback)(e=>{let t=Math.max(0,Math.min(1,e));m.current=t,d(t),f.current&&(f.current.volume=t)},[]);return{state:i,error:o,currentUrl:c,load:g,play:_,pause:v,stop:y,restart:b,toggle:x,isPlaying:i===`playing`,volume:u,setVolume:S,cleanup:h}}function Pa(e){return e instanceof Error?e.name===`NotSupportedError`?`This audio format is not supported by your browser.`:e.name===`NotAllowedError`?`Playback was blocked. Try interacting with the page first.`:e.message:`An unknown error occurred during playback.`}function Fa({selection:e,onChangeTrack:t,onClose:n,onPlaybackStart:r,onPlaybackStop:i,isPublished:a,isPublishing:o}){let{state:c,error:l,load:u,toggle:d,restart:f,stop:m,isPlaying:g,volume:_,setVolume:v,cleanup:y}=Na({onEnded:()=>{i?.()}});(0,Z.useEffect)(()=>{a&&c===`idle`&&(u(e.url,!0),r?.())},[a,c,e.url,u,r]),(0,Z.useEffect)(()=>{a&&(c===`playing`||c===`paused`)&&u(e.url,!0)},[e.url]),(0,Z.useEffect)(()=>{g?r?.():(c===`paused`||c===`stopped`)&&i?.()},[g,c,r,i]);let b=(0,Z.useCallback)(()=>{m(),y(),i?.(),n()},[m,y,i,n]),x=(0,Z.useCallback)(async()=>{c===`idle`||c===`stopped`?u(e.url,!0):await d()},[c,e.url,u,d]),S=e.track.title,C=e.track.artist,T=c===`loading`||o,E=c===`error`;return(0,Q.jsx)(`div`,{className:`mx-4 sm:mx-6 mb-4`,children:(0,Q.jsxs)(`div`,{className:K(`rounded-xl border bg-card/80 backdrop-blur-sm overflow-hidden`,`shadow-sm transition-all`,g&&`ring-2 ring-pink-500/30`),children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-3 p-3`,children:[(0,Q.jsx)(`div`,{className:K(`size-10 rounded-lg flex items-center justify-center shrink-0`,g?`bg-pink-500/20`:`bg-muted`),children:(0,Q.jsx)(D,{className:K(`size-5`,g?`text-pink-500 animate-pulse`:`text-muted-foreground`)})}),(0,Q.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,Q.jsx)(`p`,{className:`font-medium text-sm truncate`,children:S}),C&&(0,Q.jsx)(`p`,{className:`text-xs text-muted-foreground truncate`,children:C}),!C&&(0,Q.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:g?`Now playing...`:o?`Starting...`:`Ready to play`})]}),(0,Q.jsxs)(`div`,{className:`flex items-center gap-1 shrink-0`,children:[(0,Q.jsx)(q,{size:`icon`,variant:`ghost`,onClick:x,disabled:T||!a,className:`size-9 rounded-full`,children:T?(0,Q.jsx)(k,{className:`size-4 animate-spin`}):g?(0,Q.jsx)(p,{className:`size-4`}):(0,Q.jsx)(h,{className:`size-4 ml-0.5`})}),a&&(c===`playing`||c===`paused`)&&(0,Q.jsx)(q,{size:`icon`,variant:`ghost`,onClick:()=>{f()},className:`size-9 rounded-full`,title:`Restart from beginning`,children:(0,Q.jsx)(s,{className:`size-3.5`})}),(0,Q.jsxs)(ze,{children:[(0,Q.jsx)(Le,{asChild:!0,children:(0,Q.jsx)(q,{size:`icon`,variant:`ghost`,className:`size-9 rounded-full`,title:_===0?`Unmute`:`Volume`,children:_===0?(0,Q.jsx)(O,{className:`size-4`}):(0,Q.jsx)(fe,{className:`size-4`})})}),(0,Q.jsx)(Re,{side:`top`,align:`center`,className:`w-32 p-3`,children:(0,Q.jsx)(Vn,{value:[_*100],onValueChange:([e])=>v(e/100),max:100,step:1,className:`w-full`})})]}),(0,Q.jsx)(q,{size:`icon`,variant:`ghost`,onClick:t,disabled:o,className:`size-9 rounded-full`,children:(0,Q.jsx)(w,{className:`size-4`})}),(0,Q.jsx)(q,{size:`icon`,variant:`ghost`,onClick:b,disabled:o,className:`size-9 rounded-full text-muted-foreground hover:text-foreground`,children:(0,Q.jsx)(A,{className:`size-4`})})]})]}),E&&l&&(0,Q.jsx)(`div`,{className:`px-3 pb-3`,children:(0,Q.jsxs)(`div`,{className:`flex items-start gap-2 p-2 rounded-lg bg-amber-500/10 text-amber-600 dark:text-amber-400`,children:[(0,Q.jsx)(le,{className:`size-4 mt-0.5 shrink-0`}),(0,Q.jsx)(`p`,{className:`text-xs`,children:l.message})]})})]})})}var Ia=[{id:`lullaby-1`,title:`Blobbi Lullaby`,lines:[`Little Blobbi, close your eyes,`,`Dream of stars up in the skies.`,`Safe and warm, you drift away,`,`We'll play again another day.`]},{id:`happy-song-1`,title:`Happy Blobbi Song`,lines:[`Blobbi, Blobbi, jump around!`,`You're the happiest friend I've found!`,`Dancing, playing, full of cheer,`,`I'm so glad that you are here!`]},{id:`adventure-1`,title:`Adventure Time`,lines:[`Let's go on an adventure today,`,`Through the clouds and far away!`,`Mountains high and valleys deep,`,`Memories to always keep.`]},{id:`breakfast-song`,title:`Breakfast Song`,lines:[`Wake up, wake up, sleepy head,`,`Time to get out of your bed!`,`Breakfast's waiting, fresh and yummy,`,`Food to fill your happy tummy!`]},{id:`rainy-day`,title:`Rainy Day`,lines:[`Pitter patter on the roof,`,`Rainy days can be so nice.`,`We'll stay cozy, me and you,`,`Watching raindrops, one by two.`]},{id:`sunshine-song`,title:`Sunshine Song`,lines:[`Good morning, sunshine, bright and warm,`,`A brand new day is being born!`,`Blue sky smiling down on me,`,`Happy as can be, so free!`]},{id:`bedtime-1`,title:`Bedtime Blues`,lines:[`The moon is up, the stars are bright,`,`Time to say a soft goodnight.`,`Snuggle up and close your eyes,`,`Sweet dreams under starry skies.`]},{id:`play-time`,title:`Play Time`,lines:[`Bounce and jump and run around,`,`Spin and twirl without a sound!`,`Playing games is so much fun,`,`Laughing underneath the sun!`]}];function La(){return Ia[Math.floor(Math.random()*Ia.length)]}var Ra=[`audio/mp4`,`audio/mp4;codecs=aac`,`audio/aac`,`audio/webm;codecs=opus`,`audio/webm`,`audio/ogg;codecs=opus`,`audio/ogg`];function za(){if(!(typeof MediaRecorder>`u`)){for(let e of Ra)if(MediaRecorder.isTypeSupported(e))return e}}function Ba({onConfirm:e,onClose:t,onRecordingStart:n,onRecordingStop:r,isPublishing:a}){let[o,s]=(0,Z.useState)(`idle`),[c,l]=(0,Z.useState)(null),[u,d]=(0,Z.useState)(0),[f,m]=(0,Z.useState)(null),[g,_]=(0,Z.useState)(null),[v,y]=(0,Z.useState)(!1),b=(0,Z.useRef)(null),x=(0,Z.useRef)([]),S=(0,Z.useRef)(null),C=(0,Z.useRef)(null),w=(0,Z.useRef)(void 0),{state:T,error:E,load:ee,toggle:D,stop:O,isPlaying:M,cleanup:N}=Na(),P=(0,Z.useCallback)(()=>{if(C.current&&=(clearInterval(C.current),null),b.current&&b.current.state!==`inactive`)try{b.current.stop()}catch{}b.current=null,S.current&&=(S.current.getTracks().forEach(e=>e.stop()),null),N(),f&&URL.revokeObjectURL(f)},[f,N]);(0,Z.useEffect)(()=>()=>{P()},[P]);let re=(0,Z.useCallback)(()=>{P(),s(`idle`),l(null),d(0),m(null),x.current=[],w.current=void 0},[P]),F=()=>!(typeof navigator>`u`||!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia||typeof MediaRecorder>`u`),ie=(0,Z.useCallback)(async()=>{if(!F()){l(`Audio recording is not supported in this browser.`),s(`error`);return}s(`requesting`),l(null);try{let e=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}});S.current=e,x.current=[];let t=za(),r;r=t?new MediaRecorder(e,{mimeType:t}):new MediaRecorder(e),w.current=r.mimeType||t,b.current=r,r.ondataavailable=e=>{e.data.size>0&&x.current.push(e.data)},r.onstop=()=>{let e=w.current||`audio/webm`,t=new Blob(x.current,{type:e}),n=URL.createObjectURL(t);m(n),s(`recorded`),S.current&&=(S.current.getTracks().forEach(e=>e.stop()),null)},r.onerror=()=>{l(`Recording failed. Please try again.`),s(`error`)},r.start(100),s(`recording`),d(0),n?.(),C.current=setInterval(()=>{d(e=>e+1)},1e3)}catch(e){e instanceof Error?e.name===`NotAllowedError`||e.name===`PermissionDeniedError`?l(`Microphone access was denied.`):e.name===`NotFoundError`?l(`No microphone found.`):l(e.message):l(`Failed to access microphone.`),s(`error`)}},[n]),L=(0,Z.useCallback)(()=>{C.current&&=(clearInterval(C.current),null),b.current&&b.current.state!==`inactive`&&b.current.stop(),r?.()},[r]),ae=(0,Z.useCallback)(()=>{f&&(T===`idle`?ee(f,!0):D())},[f,T,ee,D]),R=(0,Z.useCallback)(async()=>{O(),await e(),t()},[O,e,t]),oe=(0,Z.useCallback)(()=>{P(),t()},[P,t]),se=(0,Z.useCallback)(()=>{!g&&!v&&_(La()),y(!v)},[g,v]),z=(0,Z.useCallback)(()=>{_(La())},[]),ce=e=>`${Math.floor(e/60)}:${(e%60).toString().padStart(2,`0`)}`,B=o===`recorded`,V=o===`recording`,ue=B&&!a;return(0,Q.jsx)(`div`,{className:`mx-4 sm:mx-6 mb-4`,children:(0,Q.jsxs)(`div`,{className:K(`rounded-xl border bg-card/80 backdrop-blur-sm overflow-hidden`,`shadow-sm transition-all`,V&&`ring-2 ring-red-500/30`),children:[v&&g&&(0,Q.jsxs)(`div`,{className:`px-3 pt-3 pb-2 border-b border-border/50`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center justify-between mb-2`,children:[(0,Q.jsx)(`span`,{className:`text-sm font-medium`,children:g.title}),(0,Q.jsx)(q,{size:`icon`,variant:`ghost`,onClick:z,className:`size-7 rounded-full`,children:(0,Q.jsx)(i,{className:`size-3`})})]}),(0,Q.jsx)(`div`,{className:`p-3 rounded-lg bg-muted/50 text-sm leading-relaxed whitespace-pre-line max-h-32 overflow-y-auto`,children:g.lines.join(`
`)})]}),(V||B)&&(0,Q.jsx)(`div`,{className:`px-3 pt-3 pb-2 border-b border-border/50`,children:(0,Q.jsxs)(`div`,{className:`flex items-center justify-center gap-2`,children:[V&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`size-2 rounded-full bg-red-500 animate-pulse`}),(0,Q.jsx)(`span`,{className:`text-sm font-mono font-medium text-red-500`,children:ce(u)}),(0,Q.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Recording...`})]}),B&&!V&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(I,{className:`size-4 text-purple-500`}),(0,Q.jsx)(`span`,{className:`text-sm font-mono font-medium text-purple-500`,children:ce(u)}),(0,Q.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Recorded`})]})]})}),(c||E)&&(0,Q.jsx)(`div`,{className:`px-3 pt-2`,children:(0,Q.jsxs)(`div`,{className:`flex items-start gap-2 p-2 rounded-lg bg-amber-500/10 text-amber-600 dark:text-amber-400`,children:[(0,Q.jsx)(le,{className:`size-4 mt-0.5 shrink-0`}),(0,Q.jsx)(`p`,{className:`text-xs`,children:c||E?.message})]})}),(0,Q.jsxs)(`div`,{className:`flex items-center justify-between gap-2 p-3`,children:[(0,Q.jsx)(q,{size:`icon`,variant:v?`secondary`:`ghost`,onClick:se,className:`size-10 rounded-full shrink-0`,children:(0,Q.jsx)(ne,{className:`size-4`})}),(0,Q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[!V&&!B&&(0,Q.jsxs)(q,{onClick:ie,disabled:a,className:`rounded-full px-6 bg-purple-500 hover:bg-purple-600`,children:[(0,Q.jsx)(j,{className:`size-4 mr-2`}),`Sing`]}),V&&(0,Q.jsxs)(q,{onClick:L,variant:`destructive`,className:`rounded-full px-6`,children:[(0,Q.jsx)(te,{className:`size-4 mr-2`}),`Stop`]}),B&&!V&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(q,{onClick:re,variant:`outline`,size:`icon`,className:`size-10 rounded-full`,children:(0,Q.jsx)(i,{className:`size-4`})}),(0,Q.jsxs)(q,{onClick:R,disabled:!ue,className:`rounded-full px-6 bg-purple-500 hover:bg-purple-600`,children:[a?(0,Q.jsx)(k,{className:`size-4 mr-2 animate-spin`}):(0,Q.jsx)(I,{className:`size-4 mr-2`}),a?`Singing...`:`Sing for Blobbi`]})]})]}),B?(0,Q.jsx)(q,{size:`icon`,variant:`ghost`,onClick:ae,disabled:a,className:`size-10 rounded-full shrink-0`,children:M?(0,Q.jsx)(p,{className:`size-4`}):(0,Q.jsx)(h,{className:`size-4 ml-0.5`})}):(0,Q.jsx)(q,{size:`icon`,variant:`ghost`,onClick:oe,className:`size-10 rounded-full shrink-0 text-muted-foreground hover:text-foreground`,children:(0,Q.jsx)(A,{className:`size-4`})})]}),B&&(0,Q.jsx)(`div`,{className:`px-3 pb-3 pt-0 flex justify-end`,children:(0,Q.jsxs)(q,{size:`sm`,variant:`ghost`,onClick:oe,disabled:a,className:`text-muted-foreground hover:text-foreground`,children:[(0,Q.jsx)(A,{className:`size-3 mr-1`}),`Cancel`]})})]})})}function Va({companion:e,profile:t,ensureCanonicalBeforeAction:n,updateCompanionEvent:r}){let{user:i}=G(),{mutateAsync:a}=ke();return or({companion:e,profile:t,pubkey:i?.pubkey,publish:a,ensureCanonicalBeforeAction:n,updateCompanionEvent:r,onError:e=>{W({title:`Failed to evolve`,description:e.message,variant:`destructive`})}})}function Ha({companion:e,profile:t,ensureCanonicalBeforeAction:n,updateCompanionEvent:r}){let{user:i}=G(),{mutateAsync:a}=ke();return sr({companion:e,profile:t,pubkey:i?.pubkey,publish:a,ensureCanonicalBeforeAction:n,updateCompanionEvent:r,onSuccess:({name:e,mode:t,stoppedOtherName:n})=>{W(t===`switch`&&n?{title:`Switched incubation!`,description:`Stopped ${n}, now incubating ${e}.`}:t===`restart`?{title:`Incubation restarted!`,description:`${e}'s task progress has been reset.`}:{title:`Incubation started!`,description:`${e} is now incubating. Complete the tasks to hatch!`})},onError:e=>{W({title:`Failed to start incubation`,description:e.message,variant:`destructive`})}})}function Ua({companion:e,ensureCanonicalBeforeAction:t,updateCompanionEvent:n}){let{user:r}=G(),{mutateAsync:i}=ke();return cr({companion:e,pubkey:r?.pubkey,publish:i,ensureCanonicalBeforeAction:t,updateCompanionEvent:n})}function Wa({companion:e,ensureCanonicalBeforeAction:t,updateCompanionEvent:n}){let{user:r}=G(),{mutateAsync:i}=ke();return lr({companion:e,pubkey:r?.pubkey,publish:i,ensureCanonicalBeforeAction:t,updateCompanionEvent:n,onSuccess:({name:e})=>{W({title:`Evolution started!`,description:`${e} is now working towards evolution. Complete the tasks to evolve!`})},onError:e=>{W({title:`Failed to start evolution`,description:e.message,variant:`destructive`})}})}function Ga({companion:e,ensureCanonicalBeforeAction:t,updateCompanionEvent:n}){let{user:r}=G(),{mutateAsync:i}=ke();return ur({companion:e,pubkey:r?.pubkey,publish:i,ensureCanonicalBeforeAction:t,updateCompanionEvent:n,onSuccess:({name:e})=>{W({title:`Evolution stopped`,description:`${e} is no longer evolving. Task progress has been reset.`})},onError:e=>{W({title:`Failed to stop evolution`,description:e.message,variant:`destructive`})}})}var Ka={play_music:15,sing:20};function qa({companion:e,ensureCanonicalBeforeAction:t,updateCompanionEvent:n,interactionSource:r=`blobbi-page`}){let{user:i}=G(),{mutateAsync:a}=ke(),o=be();return U({mutationFn:async({action:s})=>{if(!i?.pubkey)throw Error(`You must be logged in to perform actions`);if(!e)throw Error(`No companion selected`);let c=await t();if(!c)throw Error(`Failed to prepare companion for action`);let l=Math.floor(Date.now()/1e3),u=rn({stage:c.companion.stage,state:c.companion.state,stats:c.companion.stats,lastDecayAt:c.companion.lastDecayAt,now:l}).stats,d=Ka[s],f=wn(u.happiness,d),p=f!==u.happiness,m=c.companion.stage===`egg`,h={happiness:f.toString(),health:u.health.toString(),hygiene:u.hygiene.toString()};m?(h.hunger=`100`,h.energy=`100`):(h.hunger=Cn(u.hunger).toString(),h.energy=Cn(u.energy).toString());let g=l.toString(),_=c.companion.progressionState,v=c.allTags;(_===`incubating`||_===`evolving`)&&Wt(`interactions`,1,i.pubkey,c.companion.d);let y=c.content;if(_===`incubating`||_===`evolving`){let e=qt(i.pubkey,c.companion.d);e&&e.length>0&&(y=gt(c.content,e))}let b=Kt(c.companion)??{},x=p?jn(s):0,S=Dn(c.companion.experience??0,x),C=X(v,{...h,...b,experience:S.toString(),last_interaction:g,last_decay_at:g});n(await a({kind:Y,content:y,tags:C,prev:c.companion.event}));let w=an[s];if(w){ln(a,{ownerPubkey:c.companion.event.pubkey,blobbiDTag:c.companion.d,action:w,source:r});let e=bt(c.companion.event.pubkey,c.companion.d);o.invalidateQueries({queryKey:[`blobbi-interactions`,e]})}return{action:s,happinessChange:d,xpGained:x,newXP:S}},onSuccess:({action:e,happinessChange:t,xpGained:n})=>{let r=Tn[e],a=Mn(n);W({title:`${r.label} complete!`,description:`Your Blobbi's happiness increased by ${t}! ${a}`});let o=[`interact`];e===`sing`&&o.push(`sing`),e===`play_music`&&o.push(`play_music`),zt(o,i?.pubkey)},onError:e=>{W({title:`Action failed`,description:e.message,variant:`destructive`})}})}function Ja(e){return{type:`music`,selection:e,isPublished:!1}}function Ya(){return{type:`sing`}}function Xa(){return{type:`none`}}function Za(e){let{user:t}=G(),{mutateAsync:n}=ke(),r=be();return tr({pubkey:t?.pubkey,publish:n,updateProfileEvent:e,onSuccess:({xpAwarded:e})=>{t?.pubkey&&r.invalidateQueries({queryKey:[`blobbonaut-profile`,t.pubkey]}),e>0&&W({title:`XP Earned!`,description:`You earned ${e} XP from daily missions.`})},onError:e=>{W({title:`Failed to Award XP`,description:e.message,variant:`destructive`})}})}function Qa({profile:e,updateProfileEvent:t,updateCompanionEvent:n,invalidateProfile:r,invalidateCompanion:i,setStoredSelectedD:a,onComplete:o,existingCompanion:s,onExistingBlobbiFound:c,adoptionOnly:l,userInitiated:u}){return(0,Q.jsx)(Br,{profile:e,updateProfileEvent:t,updateCompanionEvent:n,invalidateProfile:r,invalidateCompanion:i,setStoredSelectedD:a,onComplete:o,existingCompanion:s,onExistingBlobbiFound:c,eggOnly:l,userInitiated:u})}function $a({companion:e,updateCompanionEvent:t}){let{nostr:n}=ve(),{user:r}=G(),{mutateAsync:i}=ke();return U({mutationFn:async a=>{if(!r?.pubkey)throw Error(`You must be logged in`);if(!e)throw Error(`No companion selected`);let o={},s=[],c=Math.floor(Date.now()/1e3);if(a.stage!==void 0&&(o.stage=a.stage,s.push(`stage`)),a.state!==void 0&&(o.state=a.state,s.push(`state`),(a.state===`evolving`||a.state===`incubating`)&&(o.progression_state=a.state,o.progression_started_at=c.toString(),o.state=`active`,s.push(`progression_state`))),(a.stage??e.stage)===`adult`&&a.adultType!==void 0&&e.seed){let t=At(e.seed,a.adultType);t!==e.seed&&(o.seed=t,s.push(`seed`,`adult_type`))}a.stats&&(a.stats.hunger!==void 0&&(o.hunger=a.stats.hunger.toString(),s.push(`hunger`)),a.stats.happiness!==void 0&&(o.happiness=a.stats.happiness.toString(),s.push(`happiness`)),a.stats.health!==void 0&&(o.health=a.stats.health.toString(),s.push(`health`)),a.stats.hygiene!==void 0&&(o.hygiene=a.stats.hygiene.toString(),s.push(`hygiene`)),a.stats.energy!==void 0&&(o.energy=a.stats.energy.toString(),s.push(`energy`))),a.experience!==void 0&&(o.experience=a.experience.toString(),s.push(`experience`)),a.careStreak!==void 0&&(o.care_streak=a.careStreak.toString(),o.care_streak_last_at=c.toString(),o.care_streak_last_day=vt(),s.push(`care_streak`)),a.breedingReady!==void 0&&(o.breeding_ready=a.breedingReady?`true`:`false`,s.push(`breeding_ready`)),a.generation!==void 0&&(o.generation=a.generation.toString(),s.push(`generation`)),o.last_interaction=c.toString(),o.last_decay_at=c.toString();let l=await Ee(n,{kinds:[Y],authors:[r.pubkey],"#d":[e.d]}),u=l?.tags??e.allTags,d=l?.content??e.event.content,f=X(u,o),p=a.stage??e.stage;return t(await i({kind:Y,content:d,tags:f,prev:l??void 0})),{previousStage:e.stage,newStage:p,changedFields:s}},onSuccess:({changedFields:e,previousStage:t,newStage:n})=>{W({title:`Blobbi state updated (DEV)`,description:t===n?`Updated: ${e.join(`, `)}`:`Stage: ${t} → ${n}. Updated: ${e.join(`, `)}`})},onError:e=>{console.error(`[DevUpdate] Failed:`,e),W({title:`Failed to update Blobbi`,description:e.message,variant:`destructive`})}})}var eo=.38,to=4,no=[1,.7,.52,.38],ro={offsetMs:0,durationMs:72,startHz:520,endHz:370,gain:.13},io={offsetMs:140,durationMs:55,startHz:400,endHz:310,gain:.065},ao={offsetMs:30,durationMs:130,startHz:740,midHz:840,endHz:680,gain:.055},oo=(to-1)*vn+vn+.04,so=null;function co(){if(so)return so;try{so=new AudioContext}catch{so=null}return so}function lo(e,t,n,r,i){let a=n+r.offsetMs/1e3,o=a+r.durationMs/1e3,s=a+r.durationMs/1e3*.35,c=e.createOscillator();c.type=`sine`,c.frequency.setValueAtTime(r.startHz,a),c.frequency.exponentialRampToValueAtTime(r.endHz,o);let l=e.createGain();return l.gain.setValueAtTime(1e-4,a),l.gain.linearRampToValueAtTime(r.gain*i,a+.006),l.gain.setValueAtTime(r.gain*i,s),l.gain.exponentialRampToValueAtTime(1e-4,o),c.connect(l),l.connect(t),c.start(a),c.stop(o),[c,l]}function uo(e,t,n,r){let i=n+ao.offsetMs/1e3,a=i+ao.durationMs/1e3,o=i+ao.durationMs/1e3*.42,s=e.createOscillator();s.type=`triangle`,s.frequency.setValueAtTime(ao.startHz,i),s.frequency.exponentialRampToValueAtTime(ao.midHz,o),s.frequency.exponentialRampToValueAtTime(ao.endHz,a);let c=e.createGain();return c.gain.setValueAtTime(1e-4,i),c.gain.linearRampToValueAtTime(ao.gain*r,i+.02),c.gain.setValueAtTime(ao.gain*r,i+.07),c.gain.exponentialRampToValueAtTime(1e-4,a),s.connect(c),c.connect(t),s.start(i),s.stop(a),[s,c]}function fo(){try{let e=co();if(!e)return;e.state===`suspended`&&e.resume().catch(()=>{});let t=e.currentTime,n=e.createBiquadFilter();n.type=`lowpass`,n.frequency.setValueAtTime(1900,t),n.Q.setValueAtTime(.55,t);let r=e.createDelay();r.delayTime.setValueAtTime(.018,t);let i=e.createGain();i.gain.setValueAtTime(.88,t);let a=e.createGain();a.gain.setValueAtTime(.12,t);let o=e.createGain();o.gain.setValueAtTime(eo,t),o.gain.setValueAtTime(eo,t+oo*.82),o.gain.exponentialRampToValueAtTime(1e-4,t+oo),n.connect(i),n.connect(r),r.connect(a),i.connect(o),a.connect(o),o.connect(e.destination);let s=[n,r,i,a,o],c=null;for(let r=0;r<to;r++){let i=t+r*vn,a=no[r]??no[no.length-1],o=lo(e,n,i,ro,a);s.push(...o),o[0]instanceof OscillatorNode&&(c=o[0]);let l=uo(e,n,i,a);s.push(...l),l[0]instanceof OscillatorNode&&(c=l[0]);let u=lo(e,n,i,io,a);s.push(...u),u[0]instanceof OscillatorNode&&(c=u[0])}c&&(c.onended=()=>{try{for(let e of s)e.disconnect()}catch{}})}catch{}}var po={home:{id:`home`,label:`Home`,description:`Main living room`,icon:v},kitchen:{id:`kitchen`,label:`Kitchen`,description:`Feed your Blobbi`,icon:ie},care:{id:`care`,label:`Care Room`,description:`Hygiene, care, and medicine`,icon:y},rest:{id:`rest`,label:`Bedroom`,description:`Rest and recharge`,icon:t},closet:{id:`closet`,label:`Closet`,description:`Wardrobe and accessories`,icon:M}},mo=[`care`,`kitchen`,`home`,`rest`],ho=`home`;function go(e){return!!e&&e in po}function _o(e,t=mo){let n=t.indexOf(e);return n===-1?t[0]:t[(n+1)%t.length]}function vo(e,t=mo){let n=t.indexOf(e);return n===-1?t[t.length-1]:t[(n-1+t.length)%t.length]}function yo(e,t=mo){return t.indexOf(e)}var bo={home:{wall:{style:`gradient`,palette:[`#fef9ef`,`#fef3c7`]},floor:{style:`wood`,palette:[`#b45309`,`#78350f`],variant:`wide`}},kitchen:{wall:{style:`solid`,palette:[`#fafaf9`,`#f5f5f4`]},floor:{style:`tile`,palette:[`#f5f5f4`,`#d6d3d1`]}},care:{wall:{style:`solid`,palette:[`#f0f9ff`,`#e0f2fe`]},floor:{style:`tile`,palette:[`#f0f9ff`,`#bae6fd`],angle:45}},rest:{wall:{style:`gradient`,palette:[`#faf5ff`,`#ede9fe`]},floor:{style:`carpet`,palette:[`#a78bfa`,`#8b5cf6`],variant:`soft`}},closet:{wall:{style:`solid`,palette:[`#faf5f0`,`#f0e8df`]},floor:{style:`wood`,palette:[`#78350f`,`#451a03`],variant:`narrow`}}};function xo(e,t){return t?.by_room[e]||bo[e]}var So=[`solid`,`stripes`,`dots`,`gradient`],Co=[`solid`,`wood`,`tile`,`carpet`],wo=[`soft`,`medium`,`bold`,`wide`,`narrow`],To=.28,Eo={bloomi:12,breezy:18,cacti:15,catti:15,cloudi:20,crysti:14,droppi:16,flammi:14,froggi:15,leafy:12,mushie:15,owli:16,pandi:14,rocky:10,rosey:13,starri:16},Do=15,Oo=12,ko=0;function Ao(e,t){switch(e){case`egg`:return ko;case`baby`:return Oo;case`adult`:return Eo[t??``]??Do;default:return Oo}}var jo=/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/;function Mo(e){return typeof e==`string`&&jo.test(e)}function No(e){return typeof e==`string`&&So.includes(e)}function Po(e){return typeof e==`string`&&Co.includes(e)}function Fo(e){return typeof e==`string`&&wo.includes(e)}function Io(e){if(!(!e||!e.trim()))try{let t=JSON.parse(e);if(typeof t!=`object`||!t||Array.isArray(t))return;let n=t.room_layouts;if(typeof n!=`object`||!n||Array.isArray(n)||n.v!==1)return;let r=n.by_room;if(typeof r!=`object`||!r||Array.isArray(r))return;let i={v:1,by_room:{}};for(let e of Object.keys(r)){if(!go(e))continue;let t=Lo(r[e]);t&&(i.by_room[e]=t)}return i}catch{return}}function Lo(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e,n=Ro(t.wall,`wall`),r=Ro(t.floor,`floor`);if(!(!n||!r))return{wall:n,floor:r}}function Ro(e,t){if(typeof e!=`object`||!e||Array.isArray(e))return;let n=e,r=n.style;if(t===`wall`&&!No(r)||t===`floor`&&!Po(r)||!Array.isArray(n.palette))return;let i=n.palette.filter(Mo);if(i.length<1||i.length>4)return;let a=Fo(n.variant)?n.variant:void 0,o=n.angle;return{style:r,palette:i,variant:a,angle:typeof o==`number`&&Number.isFinite(o)?(Math.round(o)%360+360)%360:void 0}}var zo=[`back`,`floor`,`front`],Bo=/^[a-z][a-z0-9]*:[a-z][a-z0-9-]*$/;function Vo(e){return typeof e==`string`&&Bo.test(e)}function Ho(e){return typeof e==`string`&&zo.includes(e)}function Uo(e,t,n){return Math.min(n,Math.max(t,e))}function Wo(e){if(!(!e||!e.trim()))try{let t=JSON.parse(e);if(typeof t!=`object`||!t||Array.isArray(t))return;let n=t.room_furniture;if(typeof n!=`object`||!n||Array.isArray(n)||n.v!==1)return;let r=n.by_room;if(typeof r!=`object`||!r||Array.isArray(r))return;let i={v:1,by_room:{}};for(let e of Object.keys(r)){if(!go(e)||!Array.isArray(r[e]))continue;let t=Go(r[e]);i.by_room[e]=t}return i}catch{return}}function Go(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(t.length>=20)break;let e=Ko(n);e&&t.push(e)}return t}function Ko(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e;if(!Vo(t.id)||typeof t.x!=`number`||!Number.isFinite(t.x)||typeof t.y!=`number`||!Number.isFinite(t.y)||!Ho(t.layer))return;let n={id:t.id,x:Uo(t.x,0,1),y:Uo(t.y,0,1),layer:t.layer};if(typeof t.scale==`number`&&Number.isFinite(t.scale)&&(n.scale=Uo(t.scale,.5,2)),typeof t.flip==`boolean`&&(n.flip=t.flip),typeof t.variant==`string`&&t.variant.length>0&&t.variant.length<=32&&(n.variant=t.variant),typeof t.content==`object`&&t.content!==null&&!Array.isArray(t.content)){let e=t.content,r=qo(e);r&&(n.content=r)}return n}function qo(e){let t={},n=!1;if(typeof e.imageUrl==`string`){let r=Ce(e.imageUrl);r&&(t.imageUrl=r,n=!0)}return n?t:void 0}var Jo=[{id:`official:plant-small`,category:`plants`,label:`Small Plant`,asset:`/furniture/plant-small.svg`,aspectRatio:.7,baseWidth:.08,allowedLayers:[`floor`,`front`],defaultLayer:`front`,flippable:!0,shadow:`narrow`},{id:`official:plant-tall`,category:`plants`,label:`Tall Plant`,asset:`/furniture/plant-tall.svg`,aspectRatio:.5,baseWidth:.09,allowedLayers:[`floor`,`front`],defaultLayer:`front`,flippable:!0,shadow:`narrow`},{id:`official:lamp-floor`,category:`decor`,label:`Floor Lamp`,asset:`/furniture/lamp-floor.svg`,aspectRatio:.3,baseWidth:.06,allowedLayers:[`floor`,`front`],defaultLayer:`front`,flippable:!1,shadow:`narrow`},{id:`official:rug-round`,category:`decor`,label:`Round Rug`,asset:`/furniture/rug-round.svg`,aspectRatio:1.8,baseWidth:.25,allowedLayers:[`floor`],defaultLayer:`floor`,flippable:!1,shadow:`none`,renderOrder:-20},{id:`official:shelf-wall`,category:`furniture`,label:`Wall Shelf`,asset:`/furniture/shelf-wall.svg`,aspectRatio:2.5,baseWidth:.15,allowedLayers:[`back`],defaultLayer:`back`,flippable:!1,shadow:`none`},{id:`official:clock-wall`,category:`clocks`,label:`Wall Clock`,asset:`/furniture/clock-wall.svg`,aspectRatio:1,baseWidth:.07,allowedLayers:[`back`],defaultLayer:`back`,flippable:!1,shadow:`none`,isClock:!0,clockKind:`analog`,clockStyle:`classic`},{id:`official:clock-wall-modern`,category:`clocks`,label:`Modern Clock`,asset:`/furniture/clock-wall-modern.svg`,aspectRatio:1,baseWidth:.07,allowedLayers:[`back`],defaultLayer:`back`,flippable:!1,shadow:`none`,isClock:!0,clockKind:`analog`,clockStyle:`modern`},{id:`official:clock-wall-cute`,category:`clocks`,label:`Cute Clock`,asset:`/furniture/clock-wall-cute.svg`,aspectRatio:1,baseWidth:.08,allowedLayers:[`back`],defaultLayer:`back`,flippable:!1,shadow:`none`,isClock:!0,clockKind:`analog`,clockStyle:`cute`},{id:`official:clock-table`,category:`clocks`,label:`Table Clock`,asset:`/furniture/clock-table.svg`,aspectRatio:100/110,baseWidth:.06,allowedLayers:[`floor`,`front`],defaultLayer:`front`,flippable:!1,shadow:`narrow`,isClock:!0,clockKind:`analog`,clockStyle:`analog-table`},{id:`official:clock-bedside`,category:`clocks`,label:`Bedside Clock`,asset:`/furniture/clock-bedside.svg`,aspectRatio:2,baseWidth:.09,allowedLayers:[`floor`,`front`],defaultLayer:`front`,allowedRooms:[`rest`,`home`],flippable:!1,shadow:`narrow`,isClock:!0,clockKind:`digital`,clockStyle:`digital-bedside`},{id:`official:clock-alarm`,category:`clocks`,label:`Alarm Clock`,asset:`/furniture/clock-alarm.svg`,aspectRatio:100/115,baseWidth:.07,allowedLayers:[`floor`,`front`],defaultLayer:`front`,allowedRooms:[`rest`,`home`],flippable:!1,shadow:`narrow`,isClock:!0,clockKind:`analog`,clockStyle:`cute-alarm`},{id:`official:clock-wall-digital`,category:`clocks`,label:`Digital Wall Clock`,asset:`/furniture/clock-wall-digital.svg`,aspectRatio:2.2,baseWidth:.12,allowedLayers:[`back`],defaultLayer:`back`,flippable:!1,shadow:`none`,isClock:!0,clockKind:`digital`,clockStyle:`digital-wall`},{id:`official:clock-wall-flip`,category:`clocks`,label:`Flip Wall Clock`,asset:`/furniture/clock-wall-flip.svg`,aspectRatio:2,baseWidth:.12,allowedLayers:[`back`],defaultLayer:`back`,flippable:!1,shadow:`none`,isClock:!0,clockKind:`digital`,clockStyle:`flip-wall`},{id:`official:clock-table-digital`,category:`clocks`,label:`Table Digital Clock`,asset:`/furniture/clock-table-digital.svg`,aspectRatio:2,baseWidth:.08,allowedLayers:[`floor`,`front`],defaultLayer:`front`,allowedRooms:[`rest`,`home`],flippable:!1,shadow:`narrow`,isClock:!0,clockKind:`digital`,clockStyle:`digital-table`},{id:`official:bed-single`,category:`furniture`,label:`Bed`,asset:`/furniture/bed-single.svg`,aspectRatio:4/3,baseWidth:.22,allowedLayers:[`floor`],defaultLayer:`floor`,allowedRooms:[`rest`,`home`],flippable:!0,shadow:`none`,renderOrder:-10},{id:`official:table-side`,category:`furniture`,label:`Side Table`,asset:`/furniture/table-side.svg`,aspectRatio:.9,baseWidth:.08,allowedLayers:[`floor`,`front`],defaultLayer:`floor`,flippable:!0,shadow:`wide`},{id:`official:picture-frame`,category:`frames`,label:`Picture Frame`,asset:`/furniture/frame-wood.svg`,aspectRatio:.8,baseWidth:.1,allowedLayers:[`back`],defaultLayer:`back`,flippable:!1,shadow:`none`,isFrame:!0,frameImageInset:`12% 15% 12% 15%`},{id:`official:picture-frame-gold`,category:`frames`,label:`Gold Frame`,asset:`/furniture/frame-gold.svg`,aspectRatio:.8,baseWidth:.11,allowedLayers:[`back`],defaultLayer:`back`,flippable:!1,shadow:`none`,isFrame:!0,frameImageInset:`12% 15% 12% 15%`},{id:`official:picture-frame-square`,category:`frames`,label:`Square Frame`,asset:`/furniture/frame-square.svg`,aspectRatio:1,baseWidth:.1,allowedLayers:[`back`],defaultLayer:`back`,flippable:!1,shadow:`none`,isFrame:!0,frameImageInset:`12.5% 12.5% 12.5% 12.5%`},{id:`official:picture-frame-oval`,category:`frames`,label:`Oval Frame`,asset:`/furniture/frame-oval.svg`,aspectRatio:70/90,baseWidth:.09,allowedLayers:[`back`],defaultLayer:`back`,flippable:!1,shadow:`none`,isFrame:!0,frameImageInset:`8.9% 11.4% 8.9% 11.4%`,frameImageRadius:`50%`},{id:`official:bed-round`,category:`furniture`,label:`Round Bed`,asset:`/furniture/bed-round.svg`,aspectRatio:1.6,baseWidth:.2,allowedLayers:[`floor`],defaultLayer:`floor`,allowedRooms:[`rest`,`home`],flippable:!1,shadow:`none`,renderOrder:-10},{id:`official:bed-cushion`,category:`furniture`,label:`Cushion Bed`,asset:`/furniture/bed-cushion.svg`,aspectRatio:1.5,baseWidth:.18,allowedLayers:[`floor`],defaultLayer:`floor`,allowedRooms:[`rest`,`home`],flippable:!0,shadow:`none`,renderOrder:-10},{id:`official:bed-basket`,category:`furniture`,label:`Basket Bed`,asset:`/furniture/bed-basket.svg`,aspectRatio:1.3,baseWidth:.16,allowedLayers:[`floor`],defaultLayer:`floor`,allowedRooms:[`rest`,`home`],flippable:!0,shadow:`none`,renderOrder:-10},{id:`official:rug-rectangle`,category:`decor`,label:`Rectangle Rug`,asset:`/furniture/rug-rectangle.svg`,aspectRatio:1.6,baseWidth:.28,allowedLayers:[`floor`],defaultLayer:`floor`,flippable:!1,shadow:`none`,renderOrder:-20},{id:`official:rug-runner`,category:`decor`,label:`Runner Rug`,asset:`/furniture/rug-runner.svg`,aspectRatio:3,baseWidth:.3,allowedLayers:[`floor`],defaultLayer:`floor`,flippable:!1,shadow:`none`,renderOrder:-20},{id:`official:rug-paw`,category:`decor`,label:`Paw Rug`,asset:`/furniture/rug-paw.svg`,aspectRatio:1,baseWidth:.18,allowedLayers:[`floor`],defaultLayer:`floor`,flippable:!1,shadow:`none`,renderOrder:-20},{id:`official:plant-hanging`,category:`plants`,label:`Hanging Plant`,asset:`/furniture/plant-hanging.svg`,aspectRatio:.7,baseWidth:.09,allowedLayers:[`back`],defaultLayer:`back`,flippable:!0,shadow:`none`},{id:`official:plant-cactus`,category:`plants`,label:`Cactus`,asset:`/furniture/plant-cactus.svg`,aspectRatio:.5,baseWidth:.06,allowedLayers:[`floor`,`front`],defaultLayer:`front`,flippable:!1,shadow:`narrow`},{id:`official:plant-fern`,category:`plants`,label:`Fern`,asset:`/furniture/plant-fern.svg`,aspectRatio:.8,baseWidth:.1,allowedLayers:[`floor`,`front`],defaultLayer:`front`,flippable:!0,shadow:`narrow`},{id:`official:lamp-table`,category:`decor`,label:`Table Lamp`,asset:`/furniture/lamp-table.svg`,aspectRatio:.6,baseWidth:.05,allowedLayers:[`floor`,`front`],defaultLayer:`front`,flippable:!1,shadow:`narrow`},{id:`official:lamp-wall`,category:`decor`,label:`Wall Sconce`,asset:`/furniture/lamp-wall.svg`,aspectRatio:.6,baseWidth:.05,allowedLayers:[`back`],defaultLayer:`back`,flippable:!0,shadow:`none`},{id:`official:lamp-string`,category:`decor`,label:`String Lights`,asset:`/furniture/lamp-string.svg`,aspectRatio:4,baseWidth:.25,allowedLayers:[`back`],defaultLayer:`back`,flippable:!1,shadow:`none`},{id:`official:shelf-books`,category:`furniture`,label:`Bookshelf`,asset:`/furniture/shelf-books.svg`,aspectRatio:.5,baseWidth:.1,allowedLayers:[`back`],defaultLayer:`back`,flippable:!1,shadow:`none`},{id:`official:shelf-floating`,category:`furniture`,label:`Floating Shelf`,asset:`/furniture/shelf-floating.svg`,aspectRatio:3,baseWidth:.14,allowedLayers:[`back`],defaultLayer:`back`,flippable:!1,shadow:`none`},{id:`official:cabinet-small`,category:`furniture`,label:`Small Cabinet`,asset:`/furniture/cabinet-small.svg`,aspectRatio:70/90,baseWidth:.09,allowedLayers:[`floor`,`front`],defaultLayer:`floor`,flippable:!0,shadow:`narrow`}],Yo=new Map(Jo.map(e=>[e.id,e]));function Xo(e){let t=e.indexOf(`:`);if(!(t<=0))switch(e.slice(0,t)){case`official`:return Yo.get(e);default:return}}function Zo(e,t){if(!e.variants||!t||!e.variants.includes(t))return e.asset;let n=e.asset.lastIndexOf(`.`);return n<=0?e.asset:`${e.asset.slice(0,e.asset.lastIndexOf(`-`))}-${t}${e.asset.slice(n)}`}function Qo(e,t){return e.allowedRooms?e.allowedRooms.includes(t):!0}function $o(e){return Jo.filter(t=>Qo(t,e))}var es={furniture:`Furniture`,decor:`Decor`,plants:`Plants`,clocks:`Clocks`,frames:`Frames`},ts=[`furniture`,`decor`,`plants`,`clocks`,`frames`];function ns(e){let t=$o(e),n=[];for(let e of ts){let r=t.filter(t=>t.category===e);r.length>0&&n.push({category:e,label:es[e],items:r})}return n}var rs={home:[{id:`official:rug-round`,x:.5,y:.85,layer:`floor`,scale:1},{id:`official:plant-tall`,x:.88,y:.72,layer:`front`,scale:1},{id:`official:lamp-floor`,x:.12,y:.72,layer:`front`,scale:1},{id:`official:shelf-wall`,x:.5,y:.25,layer:`back`,scale:1}],kitchen:[{id:`official:plant-small`,x:.85,y:.72,layer:`front`,scale:.9},{id:`official:clock-wall`,x:.5,y:.18,layer:`back`,scale:1}],care:[{id:`official:plant-small`,x:.1,y:.72,layer:`front`,scale:.8}],rest:[{id:`official:bed-single`,x:.5,y:.82,layer:`floor`,scale:1},{id:`official:lamp-floor`,x:.85,y:.72,layer:`front`,scale:.9},{id:`official:table-side`,x:.82,y:.78,layer:`floor`,scale:.8}],closet:[{id:`official:plant-small`,x:.88,y:.72,layer:`front`,scale:.9}]};function is(e,t){return t?.by_room[e]||(rs[e]??[])}function as(e,t){let n=Math.abs(e-t)%360;return Math.min(n,360-n)}function os(e,t=1){let[n,r]=e.palette;if(!n)return`#ccc`;let i=e.angle??0;switch(e.style){case`solid`:return n;case`gradient`:return r?`linear-gradient(${i||180}deg, ${n} 0%, ${r} 100%)`:n;case`stripes`:{let a=e.variant===`narrow`?8:e.variant===`wide`?24:14,o=Math.round(a*t),s=e.variant===`soft`?`90`:e.variant===`bold`?``:`cc`,c=r?`${r}${s}`:n;return`repeating-linear-gradient(${i||180}deg, ${n} 0px, ${n} ${o}px, ${c} ${o}px, ${c} ${o*2}px)`}case`dots`:{let e=Math.round(20*t),a=Math.max(1.5,3*t),o=i*Math.PI/180,s=Math.round(Math.cos(o)*e*.4),c=Math.round(Math.sin(o)*e*.4);return r?`radial-gradient(circle ${a}px at ${e/2}px ${e/2}px, ${r} ${a*.7}px, transparent ${a}px) ${s}px ${c}px / ${e}px ${e}px, ${n}`:n}case`wood`:{let a=e.variant===`narrow`?8:e.variant===`wide`?22:14,o=e.variant===`bold`?4:e.variant===`soft`?1:2,s=Math.round(a*t),c=Math.max(1,Math.round(o*t));return r?`repeating-linear-gradient(${i||90}deg, ${n} 0px, ${n} ${s}px, ${r} ${s}px, ${r} ${s+c}px)`:n}case`tile`:{let e=Math.round(28*t),a=Math.max(1,Math.round(2*t)),o=r?`${r}60`:`#00000020`,s=(i%360+360)%360;if([45,135,225,315].some(e=>as(s,e)<=10)){let t=Math.round(e*.707);return[`repeating-linear-gradient(45deg, ${o} 0px, ${o} ${a}px, transparent ${a}px, transparent ${t}px)`,`repeating-linear-gradient(-45deg, ${o} 0px, ${o} ${a}px, transparent ${a}px, transparent ${t}px)`,n].join(`, `)}return[`repeating-linear-gradient(0deg, ${o} 0px, ${o} ${a}px, transparent ${a}px, transparent ${e}px)`,`repeating-linear-gradient(90deg, ${o} 0px, ${o} ${a}px, transparent ${a}px, transparent ${e}px)`,n].join(`, `)}case`carpet`:return r?`linear-gradient(${i||135}deg, ${n} 0%, ${r} 100%)`:n;default:return n}}function ss(e){let t=e.trim().split(/\s+/);if(t.length<3)return null;let n=parseFloat(t[0]),r=parseFloat(t[1]),i=parseFloat(t[2]);return!Number.isFinite(n)||!Number.isFinite(r)||!Number.isFinite(i)?null:[n,r,i]}function cs(e,t,n){t/=100,n/=100;let r=t*Math.min(n,1-n),i=t=>{let i=(t+e/30)%12,a=n-r*Math.max(Math.min(i-3,9-i,1),-1);return Math.round(255*a).toString(16).padStart(2,`0`)};return`#${i(0)}${i(8)}${i(4)}`}function $(e,t,n){return cs(e[0]+(t[0]-e[0])*n,e[1]+(t[1]-e[1])*n,e[2]+(t[2]-e[2])*n)}function ls(e,t){return[e[0],e[1],Math.max(0,Math.min(100,e[2]+t))]}function us(){if(typeof document>`u`)return null;let e=getComputedStyle(document.documentElement),t=ss(e.getPropertyValue(`--background`)),n=ss(e.getPropertyValue(`--foreground`)),r=ss(e.getPropertyValue(`--primary`)),i=ss(e.getPropertyValue(`--primary-foreground`));return!t||!n||!r||!i?null:{background:t,foreground:n,primary:r,primaryForeground:i,accent:ss(e.getPropertyValue(`--accent`))}}function ds(){let e=us();if(!e)return bo;let{background:t,foreground:n,primary:r}=e,i=e.accent??[t[0]+(r[0]-t[0])*.5,t[1]+(r[1]-t[1])*.5,t[2]+(r[2]-t[2])*.5],a=cs(t[0],t[1],t[2]),o=$(t,r,.08),s=$(r,n,.3),c=$(r,n,.45),l=$(t,n,.06),u=$(t,n,.03),d=$(t,n,.1),f=$(t,r,.05),p=$(t,r,.1),m=$(t,i,.06),h=$(t,r,.12),g=$(t,r,.15),_=$(r,t,.55),v=$(r,t,.65),y=$(t,n,.08),b=cs(...ls(r,-8)),x=cs(...ls(r,-18));return{home:{wall:{style:`gradient`,palette:[a,o]},floor:{style:`wood`,palette:[s,c],variant:`wide`}},kitchen:{wall:{style:`solid`,palette:[a,l]},floor:{style:`tile`,palette:[u,d]}},care:{wall:{style:`solid`,palette:[f,p]},floor:{style:`tile`,palette:[m,h],angle:45}},rest:{wall:{style:`gradient`,palette:[a,g]},floor:{style:`carpet`,palette:[_,v],variant:`soft`}},closet:{wall:{style:`solid`,palette:[a,y]},floor:{style:`wood`,palette:[b,x],variant:`medium`}}}}var fs={solid:`Solid`,stripes:`Stripes`,dots:`Dots`,gradient:`Gradient`},ps={solid:`Solid`,wood:`Wood`,tile:`Tile`,carpet:`Carpet`},ms={soft:`Soft`,medium:`Medium`,bold:`Bold`,wide:`Wide`,narrow:`Narrow`},hs=[0,45,90,135,180],gs=[0,45];function _s(e){return[`stripes`,`gradient`,`dots`,`wood`,`tile`,`carpet`].includes(e)}function vs(e){switch(e){case`stripes`:return[`narrow`,`medium`,`wide`,`soft`,`bold`];case`wood`:return[`narrow`,`medium`,`wide`,`soft`,`bold`];case`carpet`:return[`soft`,`medium`,`bold`];default:return null}}function ys({type:e,value:t,onChange:n}){let r=e===`wall`?So:Co,i=e===`wall`?fs:ps,a=vs(t.style),o=(0,Z.useCallback)(e=>{let r=vs(e);n({...t,style:e,variant:r?t.variant&&r.includes(t.variant)?t.variant:`medium`:void 0})},[t,n]),s=(0,Z.useCallback)(e=>{let r=[...t.palette];r[0]=e,n({...t,palette:r})},[t,n]),c=(0,Z.useCallback)(e=>{let r=[...t.palette];r[1]=e,n({...t,palette:r})},[t,n]),l=(0,Z.useCallback)(e=>{n({...t,variant:e})},[t,n]),u=(0,Z.useCallback)(e=>{n({...t,angle:(e%360+360)%360})},[t,n]);return(0,Q.jsxs)(`div`,{className:`space-y-3`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`label`,{className:`text-[10px] font-medium text-muted-foreground uppercase tracking-wide mb-1.5 block`,children:`Pattern`}),(0,Q.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:r.map(e=>(0,Q.jsx)(`button`,{type:`button`,onClick:()=>o(e),className:K(`px-2.5 py-1 rounded-md text-xs font-medium transition-all`,`hover:bg-accent/60 active:scale-95`,t.style===e?`bg-primary/15 text-primary ring-1 ring-primary/30`:`bg-muted/50 text-muted-foreground`),children:i[e]??e},e))})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`label`,{className:`text-[10px] font-medium text-muted-foreground uppercase tracking-wide mb-1.5 block`,children:`Colors`}),(0,Q.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,Q.jsx)(bs,{label:`Base`,value:t.palette[0]??`#ffffff`,onChange:s}),t.style!==`solid`&&(0,Q.jsx)(bs,{label:`Accent`,value:t.palette[1]??t.palette[0]??`#000000`,onChange:c}),(0,Q.jsx)(`div`,{className:`ml-auto`,children:(0,Q.jsx)(xs,{surface:t})})]})]}),a&&(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`label`,{className:`text-[10px] font-medium text-muted-foreground uppercase tracking-wide mb-1.5 block`,children:`Detail`}),(0,Q.jsx)(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:a.map((e,n)=>(0,Q.jsxs)(`span`,{className:`contents`,children:[n>0&&a[n-1]===`wide`&&(e===`soft`||e===`bold`)&&(0,Q.jsx)(`span`,{className:`w-px h-4 bg-border/60 mx-0.5`}),(0,Q.jsx)(`button`,{type:`button`,onClick:()=>l(e),className:K(`px-2 py-0.5 rounded text-[11px] font-medium transition-all`,`hover:bg-accent/60 active:scale-95`,t.variant===e?`bg-primary/15 text-primary ring-1 ring-primary/30`:`bg-muted/50 text-muted-foreground`),children:ms[e]})]},e))})]}),_s(t.style)&&(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`label`,{className:`text-[10px] font-medium text-muted-foreground uppercase tracking-wide mb-1.5 block`,children:(0,Q.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[(0,Q.jsx)(T,{className:`size-3`}),`Angle`]})}),(0,Q.jsx)(`div`,{className:`flex items-center gap-1.5`,children:(t.style===`tile`?gs:hs).map(e=>(0,Q.jsxs)(`button`,{type:`button`,onClick:()=>u(e),className:K(`size-7 rounded text-[10px] font-medium transition-all flex items-center justify-center`,`hover:bg-accent/60 active:scale-95`,(t.angle??0)===e?`bg-primary/15 text-primary ring-1 ring-primary/30`:`bg-muted/50 text-muted-foreground`),children:[e,`°`]},e))})]})]})}function bs({label:e,value:t,onChange:n}){return(0,Q.jsxs)(`label`,{className:`flex items-center gap-1.5 cursor-pointer`,children:[(0,Q.jsx)(`input`,{type:`color`,value:t,onChange:e=>n(e.target.value),className:`size-7 rounded border border-border/50 cursor-pointer p-0 bg-transparent [&::-webkit-color-swatch-wrapper]:p-0.5 [&::-webkit-color-swatch]:rounded-sm [&::-webkit-color-swatch]:border-0`}),(0,Q.jsx)(`span`,{className:`text-[10px] text-muted-foreground`,children:e})]})}function xs({surface:e}){return(0,Q.jsx)(`div`,{className:`size-10 rounded-lg border border-border/40 shadow-sm`,style:{background:os(e,.6)},"aria-hidden":!0})}function Ss({onClick:e}){return(0,Q.jsx)(q,{variant:`ghost`,size:`icon`,onClick:e,className:`size-9 rounded-full bg-background/70 border border-border/60 shadow-sm backdrop-blur-sm text-muted-foreground hover:text-foreground hover:bg-background/90`,"aria-label":`Edit room style`,children:(0,Q.jsx)(ce,{className:`size-4`})})}function Cs({wall:e,floor:t}){let n=os(e),r=os(t);return(0,Q.jsxs)(`div`,{className:`w-full h-24 rounded-xl border border-border/40 overflow-hidden shadow-inner relative`,children:[(0,Q.jsx)(`div`,{className:`absolute inset-x-0 top-0`,style:{background:n,bottom:`${To*100}%`}}),(0,Q.jsx)(`div`,{className:`absolute inset-x-0 bottom-0`,style:{background:r,top:`${(1-To)*100}%`}}),(0,Q.jsxs)(`div`,{className:`absolute inset-x-0 flex flex-col`,style:{top:`${(1-To)*100}%`},children:[(0,Q.jsx)(`div`,{className:`h-px bg-foreground/10`}),(0,Q.jsx)(`div`,{className:`h-0.5 bg-background/15`})]}),(0,Q.jsx)(`div`,{className:`absolute inset-x-0 h-2`,style:{top:`${(1-To)*100}%`,background:`linear-gradient(to bottom, hsl(var(--foreground) / 0.06), transparent)`}})]})}function ws({roomId:e,currentLayout:t,onSave:n,onClose:r,isSaving:i}){let[a,o]=(0,Z.useState)(t.wall),[c,l]=(0,Z.useState)(t.floor),[u,d]=(0,Z.useState)(`wall`),f=(0,Z.useCallback)(()=>{r?.()},[r]),p=(0,Z.useCallback)(async()=>{if(!i)try{await n(e,{wall:a,floor:c}),r?.()}catch{}},[e,a,c,n,r,i]),m=(0,Z.useCallback)(()=>{let t=bo[e];o(t.wall),l(t.floor)},[e]),h=(0,Z.useCallback)(()=>{let t=ds()[e];o(t.wall),l(t.floor)},[e]),_=(0,Z.useMemo)(()=>JSON.stringify({wall:a,floor:c})!==JSON.stringify(t),[a,c,t]),v=po[e];return(0,Q.jsxs)(`div`,{className:`absolute inset-0 z-[55] flex items-center justify-center p-4 pb-[calc(var(--bottom-nav-height)+1rem)] sm:pb-4`,children:[(0,Q.jsx)(`div`,{className:`absolute inset-0 bg-background/55 backdrop-blur-sm`,onClick:f}),(0,Q.jsxs)(`div`,{className:K(`relative z-[56] w-full max-w-xl`,`rounded-3xl border border-border/60`,`bg-background/95 shadow-2xl backdrop-blur-md`,`overflow-hidden`,`animate-in fade-in-0 zoom-in-95 duration-200`,`max-h-[calc(100%-4rem)] sm:max-h-[78dvh]`,`flex flex-col`),onClick:e=>e.stopPropagation(),children:[(0,Q.jsxs)(`div`,{className:`flex items-center justify-between px-5 pt-4 pb-3`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-2.5`,children:[(0,Q.jsx)(`div`,{className:`size-8 rounded-xl bg-primary/10 flex items-center justify-center`,children:(0,Q.jsx)(v.icon,{className:`size-4 text-primary`})}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsxs)(`h2`,{className:`text-sm font-semibold leading-tight`,children:[`Edit `,v.label]}),(0,Q.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:`Customize wall and floor style`})]})]}),(0,Q.jsx)(`button`,{onClick:f,className:`size-8 rounded-full flex items-center justify-center text-muted-foreground hover:text-foreground hover:bg-accent/50 transition-colors`,"aria-label":`Close editor`,children:(0,Q.jsx)(A,{className:`size-4`})})]}),(0,Q.jsx)(`div`,{className:`px-5 pb-3`,children:(0,Q.jsxs)(`div`,{className:`flex p-1 rounded-xl bg-muted/50`,children:[(0,Q.jsx)(`button`,{type:`button`,onClick:()=>d(`wall`),className:K(`flex-1 py-1.5 rounded-lg text-xs font-semibold text-center transition-all duration-150`,u===`wall`?`bg-background shadow-sm text-foreground`:`text-muted-foreground hover:text-foreground`),children:`Wall`}),(0,Q.jsx)(`button`,{type:`button`,onClick:()=>d(`floor`),className:K(`flex-1 py-1.5 rounded-lg text-xs font-semibold text-center transition-all duration-150`,u===`floor`?`bg-background shadow-sm text-foreground`:`text-muted-foreground hover:text-foreground`),children:`Floor`})]})}),(0,Q.jsxs)(`div`,{className:`overflow-y-auto flex-1 min-h-0 px-5 pb-4 space-y-4 blobbi-room-editor-scroll`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`label`,{className:`text-[10px] font-medium text-muted-foreground uppercase tracking-wide mb-1.5 block`,children:`Preview`}),(0,Q.jsx)(Cs,{wall:a,floor:c})]}),(0,Q.jsx)(`div`,{className:`rounded-2xl border border-border/40 bg-muted/20 p-3.5`,children:u===`wall`?(0,Q.jsx)(ys,{type:`wall`,value:a,onChange:o}):(0,Q.jsx)(ys,{type:`floor`,value:c,onChange:l})})]}),(0,Q.jsxs)(`div`,{className:`px-5 py-3 border-t border-border/30 bg-muted/10 space-y-2`,children:[(0,Q.jsxs)(`div`,{className:`grid grid-cols-2 gap-2`,children:[(0,Q.jsxs)(q,{variant:`ghost`,size:`sm`,onClick:m,disabled:i,"aria-label":`Reset to default`,className:`gap-1 text-muted-foreground hover:text-foreground h-8 text-xs justify-center`,children:[(0,Q.jsx)(s,{className:`size-3.5`}),`Reset`]}),(0,Q.jsxs)(q,{variant:`ghost`,size:`sm`,onClick:h,disabled:i,"aria-label":`Use theme colors`,className:`gap-1 text-muted-foreground hover:text-foreground h-8 text-xs justify-center`,children:[(0,Q.jsx)(g,{className:`size-3.5`}),`Use theme`]})]}),(0,Q.jsxs)(`div`,{className:`flex items-center justify-end gap-2`,children:[(0,Q.jsx)(q,{variant:`outline`,size:`sm`,onClick:f,disabled:i,children:`Cancel`}),(0,Q.jsxs)(q,{size:`sm`,onClick:p,disabled:!_||i,className:`gap-1.5`,children:[(0,Q.jsx)(I,{className:`size-3.5`}),i?`Saving...`:`Apply`]})]})]})]})]})}var Ts=2,Es=3,Ds=2,Os=To*100-2,ks=[{bottom:10,left:8},{bottom:6,left:78},{bottom:16,left:14},{bottom:13,left:82},{bottom:4,left:20},{bottom:8,left:72}].map(({bottom:e,left:t})=>({bottom:Math.max(Ds,Math.min(e,Os)),left:t})),As=0;function js(){return`poop_${++As}_${Date.now()}`}function Ms(e){return ks[e%ks.length]}function Ns(e,t){let n=[],r=Date.now(),i=0;if(e>=95&&Math.random()<.4&&n.push({id:js(),room:`kitchen`,source:`overfeed`,createdAt:r,position:Ms(i++)}),t){let e=(r-t)/(1e3*60*60),a=Math.min(Math.floor(e/Ts),Es-n.length);for(let e=0;e<a;e++)n.push({id:js(),room:`kitchen`,source:`time`,createdAt:r-e*1e3,position:Ms(i++)})}return n}function Ps(e,t=`overfeed`){return e.length>=Es?e:[...e,{id:js(),room:`kitchen`,source:t,createdAt:Date.now(),position:Ms(e.length)}]}function Fs(e,t){return e.filter(e=>e.room===t)}function Is(e,t){let n=e.filter(e=>e.id!==t);return{remaining:n,xpReward:n.length<e.length?5:0}}function Ls(e){return e.length>0}var Rs=(0,Z.forwardRef)(function({icon:e,label:t,color:n,glowHex:r,onClick:i,disabled:a,loading:o,badge:s,glow:c,className:l,onMouseDown:u,onTouchStart:d},f){return(0,Q.jsxs)(`button`,{ref:f,onClick:i,disabled:a,onMouseDown:u,onTouchStart:d,className:K(`flex flex-col items-center gap-1 transition-all duration-300 ease-out shrink-0 translate-y-1`,`active:scale-95`,a&&`opacity-50 pointer-events-none`,l),children:[(0,Q.jsxs)(`div`,{className:`relative`,children:[(0,Q.jsx)(`div`,{className:K(`size-10 sm:size-14 rounded-full flex items-center justify-center`,`bg-background/50 backdrop-blur-[2px] border border-border/20 shadow-sm transition-shadow duration-200`,`hover:shadow-[0_0_12px_var(--glow)]`,n,c&&`ring-2 ring-primary ring-offset-2 ring-offset-background animate-[guide-pulse_1.5s_ease-in-out_infinite]`),style:{"--glow":`color-mix(in srgb, ${r} 50%, transparent)`,backgroundImage:`radial-gradient(circle at 40% 35%, color-mix(in srgb, ${r} 14%, transparent), color-mix(in srgb, ${r} 4%, transparent) 70%)`},children:o?(0,Q.jsx)(k,{className:`size-5 sm:size-6 animate-spin`}):(0,Q.jsx)(`span`,{className:`[&>svg]:size-5 sm:[&>svg]:size-6`,children:e})}),s&&(0,Q.jsx)(`div`,{className:`absolute -top-0.5 -right-0.5`,children:s})]}),(0,Q.jsx)(`span`,{className:`text-[10px] sm:text-xs font-medium text-muted-foreground bg-background/50 backdrop-blur-[2px] rounded-full px-1.5 py-px`,children:t})]})});function zs(e,t,n){return Math.min(n,Math.max(t,e))}var Bs=500,Vs=8;function Hs({containerRef:e,onMove:t}){let[n,r]=(0,Z.useState)(!1),[i,a]=(0,Z.useState)(!1),o=(0,Z.useRef)(null),s=(0,Z.useRef)(null),c=(0,Z.useRef)(!1),l=(0,Z.useRef)(!1),u=(0,Z.useRef)(!1),d=(0,Z.useRef)(t);d.current=t;let f=(0,Z.useCallback)(()=>{s.current!==null&&(clearTimeout(s.current),s.current=null),o.current=null,c.current&&(c.current=!1,r(!1)),l.current&&(l.current=!1,a(!1))},[]),p=(0,Z.useCallback)(t=>{let n=o.current;if(!n||t.pointerId!==n.pointerId)return;let r=t.clientX-n.startX,i=t.clientY-n.startY;if(l.current){Math.sqrt(r*r+i*i)>Vs&&f();return}if(c.current){let r=e.current?.getBoundingClientRect();if(!r)return;let i=(t.clientX-r.left)/r.width,a=(t.clientY-r.top)/r.height;d.current(zs(i+n.offsetDx,0,1),zs(a+n.offsetDy,0,1))}},[e,f]),m=(0,Z.useCallback)(e=>{let t=o.current;!t||e.pointerId!==t.pointerId||((c.current||l.current)&&(u.current=!0,setTimeout(()=>{u.current=!1},0)),f())},[f]),h=(0,Z.useCallback)(e=>{let t=o.current;!t||e.pointerId!==t.pointerId||f()},[f]),g=(0,Z.useCallback)(()=>{window.addEventListener(`pointermove`,p),window.addEventListener(`pointerup`,m),window.addEventListener(`pointercancel`,h)},[p,m,h]),_=(0,Z.useCallback)(()=>{window.removeEventListener(`pointermove`,p),window.removeEventListener(`pointerup`,m),window.removeEventListener(`pointercancel`,h)},[p,m,h]);return(0,Z.useEffect)(()=>()=>{_(),s.current!==null&&clearTimeout(s.current)},[_]),(0,Z.useEffect)(()=>{if(n||i)return g(),()=>_()},[n,i,g,_]),{isDragging:n,isHolding:i,startHold:(0,Z.useCallback)((t,n,i)=>{t.preventDefault(),t.stopPropagation();let u=e.current?.getBoundingClientRect();if(!u)return;let d=(t.clientX-u.left)/u.width,f=(t.clientY-u.top)/u.height,p={pointerId:t.pointerId,startX:t.clientX,startY:t.clientY,offsetDx:n-d,offsetDy:i-f};o.current=p,l.current=!0,a(!0),s.current=setTimeout(()=>{s.current=null,l.current=!1,a(!1),c.current=!0,r(!0)},Bs)},[e]),shouldSuppressClick:(0,Z.useCallback)(()=>u.current,[])}}var Us=new Set,Ws=Math.floor(Date.now()/6e4),Gs=null;function Ks(e){return Us.add(e),Gs||=setInterval(()=>{let e=Math.floor(Date.now()/6e4);e!==Ws&&(Ws=e,Us.forEach(e=>e()))},1e3),()=>{Us.delete(e),Us.size===0&&Gs&&(clearInterval(Gs),Gs=null)}}function qs(){return Ws}function Js(){return(0,Z.useSyncExternalStore)(Ks,qs,qs),new Date}function Ys({clockKind:e,clockStyle:t,isSelected:n,isDragging:r,isHolding:i}){let a=Js();return(0,Q.jsx)(`div`,{className:K(`w-full h-full`,n&&`ring-2 ring-primary ring-offset-1 rounded-sm`,r&&`opacity-80 scale-105 transition-transform duration-100`,i&&`scale-[1.02] transition-transform duration-100`),children:e===`digital`?(0,Q.jsx)($s,{now:a,style:t}):(0,Q.jsx)(Zs,{now:a,style:t})})}var Xs={classic:{faceFill:`#f8f4ee`,rimStroke:`#706050`,rimWidth:4,hourHandColor:`#333`,minuteHandColor:`#333`,hourHandWidth:3,minuteHandWidth:2,hourHandLength:22,minuteHandLength:30,markerColor:`#706050`,centerDotColor:`#333`,centerDotRadius:3,extras:()=>(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`rect`,{x:`48`,y:`10`,width:`4`,height:`10`,fill:`#706050`}),(0,Q.jsx)(`rect`,{x:`48`,y:`80`,width:`4`,height:`10`,fill:`#706050`}),(0,Q.jsx)(`rect`,{x:`80`,y:`48`,width:`10`,height:`4`,fill:`#706050`}),(0,Q.jsx)(`rect`,{x:`10`,y:`48`,width:`10`,height:`4`,fill:`#706050`})]})},modern:{faceFill:`#ffffff`,rimStroke:`#b0b0b0`,rimWidth:2,hourHandColor:`#222`,minuteHandColor:`#222`,hourHandWidth:2.5,minuteHandWidth:1.5,hourHandLength:20,minuteHandLength:32,markerColor:`#999`,centerDotColor:`#222`,centerDotRadius:2.5,extras:()=>(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`rect`,{x:`49`,y:`8`,width:`2`,height:`6`,fill:`#999`}),(0,Q.jsx)(`rect`,{x:`49`,y:`86`,width:`2`,height:`6`,fill:`#999`}),(0,Q.jsx)(`rect`,{x:`86`,y:`49`,width:`6`,height:`2`,fill:`#999`}),(0,Q.jsx)(`rect`,{x:`8`,y:`49`,width:`6`,height:`2`,fill:`#999`})]})},cute:{faceFill:`#fff0f5`,rimStroke:`#f0a0c0`,rimWidth:4,hourHandColor:`#d06090`,minuteHandColor:`#d06090`,hourHandWidth:4,minuteHandWidth:3,hourHandLength:20,minuteHandLength:28,markerColor:`#f0a0c0`,centerDotColor:`#d06090`,centerDotRadius:4,extras:()=>(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`circle`,{cx:`50`,cy:`14`,r:`3`,fill:`#f0a0c0`}),(0,Q.jsx)(`circle`,{cx:`50`,cy:`86`,r:`3`,fill:`#f0a0c0`}),(0,Q.jsx)(`circle`,{cx:`86`,cy:`50`,r:`3`,fill:`#f0a0c0`}),(0,Q.jsx)(`circle`,{cx:`14`,cy:`50`,r:`3`,fill:`#f0a0c0`}),(0,Q.jsx)(`polygon`,{points:`22,12 30,2 38,12`,fill:`#f0a0c0`}),(0,Q.jsx)(`polygon`,{points:`62,12 70,2 78,12`,fill:`#f0a0c0`})]})},"analog-table":{faceFill:`#f5f0e8`,rimStroke:`#8b7355`,rimWidth:3,hourHandColor:`#4a3728`,minuteHandColor:`#4a3728`,hourHandWidth:2.5,minuteHandWidth:1.8,hourHandLength:18,minuteHandLength:26,markerColor:`#8b7355`,centerDotColor:`#4a3728`,centerDotRadius:2.5,viewBox:`0 0 100 110`,extras:()=>(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`rect`,{x:`49`,y:`14`,width:`2`,height:`5`,fill:`#8b7355`}),(0,Q.jsx)(`rect`,{x:`49`,y:`81`,width:`2`,height:`5`,fill:`#8b7355`}),(0,Q.jsx)(`rect`,{x:`81`,y:`49`,width:`5`,height:`2`,fill:`#8b7355`}),(0,Q.jsx)(`rect`,{x:`14`,y:`49`,width:`5`,height:`2`,fill:`#8b7355`})]}),outer:()=>(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`rect`,{x:`30`,y:`95`,width:`6`,height:`15`,rx:`2`,fill:`#8b7355`}),(0,Q.jsx)(`rect`,{x:`64`,y:`95`,width:`6`,height:`15`,rx:`2`,fill:`#8b7355`}),(0,Q.jsx)(`rect`,{x:`25`,y:`108`,width:`50`,height:`4`,rx:`2`,fill:`#6b5335`})]})},"cute-alarm":{faceFill:`#ffe8ec`,rimStroke:`#ff6b8a`,rimWidth:3,hourHandColor:`#cc3355`,minuteHandColor:`#cc3355`,hourHandWidth:3,minuteHandWidth:2.5,hourHandLength:18,minuteHandLength:26,markerColor:`#ff6b8a`,centerDotColor:`#cc3355`,centerDotRadius:3,viewBox:`0 0 100 115`,extras:()=>(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`circle`,{cx:`50`,cy:`16`,r:`2.5`,fill:`#ff6b8a`}),(0,Q.jsx)(`circle`,{cx:`50`,cy:`84`,r:`2.5`,fill:`#ff6b8a`}),(0,Q.jsx)(`circle`,{cx:`84`,cy:`50`,r:`2.5`,fill:`#ff6b8a`}),(0,Q.jsx)(`circle`,{cx:`16`,cy:`50`,r:`2.5`,fill:`#ff6b8a`})]}),outer:()=>(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`circle`,{cx:`25`,cy:`12`,r:`10`,fill:`#ff8fa8`}),(0,Q.jsx)(`circle`,{cx:`75`,cy:`12`,r:`10`,fill:`#ff8fa8`}),(0,Q.jsx)(`rect`,{x:`45`,y:`2`,width:`10`,height:`5`,rx:`2.5`,fill:`#cc3355`}),(0,Q.jsx)(`rect`,{x:`32`,y:`98`,width:`5`,height:`12`,rx:`2`,fill:`#ff6b8a`,transform:`rotate(-10 34.5 104)`}),(0,Q.jsx)(`rect`,{x:`63`,y:`98`,width:`5`,height:`12`,rx:`2`,fill:`#ff6b8a`,transform:`rotate(10 65.5 104)`})]})}};function Zs({now:e,style:t}){let n=Xs[t]??Xs.classic,r=e.getHours(),i=e.getMinutes(),a=r%12*30+i*.5,o=i*6;return(0,Q.jsxs)(`svg`,{viewBox:n.viewBox??`0 0 100 100`,className:`w-full h-full`,"aria-label":`Clock`,children:[n.outer?.(),(0,Q.jsx)(`circle`,{cx:`50`,cy:`50`,r:`45`,fill:n.faceFill,stroke:n.rimStroke,strokeWidth:n.rimWidth}),n.extras?.({hours:r,minutes:i}),(0,Q.jsx)(`line`,{x1:`50`,y1:`50`,x2:`50`,y2:50-n.hourHandLength,stroke:n.hourHandColor,strokeWidth:n.hourHandWidth,strokeLinecap:`round`,transform:`rotate(${a} 50 50)`}),(0,Q.jsx)(`line`,{x1:`50`,y1:`50`,x2:`50`,y2:50-n.minuteHandLength,stroke:n.minuteHandColor,strokeWidth:n.minuteHandWidth,strokeLinecap:`round`,transform:`rotate(${o} 50 50)`}),(0,Q.jsx)(`circle`,{cx:`50`,cy:`50`,r:n.centerDotRadius,fill:n.centerDotColor})]})}var Qs={"digital-bedside":{viewBox:`0 0 120 60`,caseFill:`#1a1a2e`,caseStroke:`#333355`,caseStrokeWidth:2,caseRadius:6,screenFill:`#0a0a18`,textFill:`#44ff88`,fontSize:22,fontFamily:`monospace`,ledColor:`#44ff88`},"digital-wall":{viewBox:`0 0 132 60`,caseFill:`#2c2c2c`,caseStroke:`#555555`,caseStrokeWidth:2,caseRadius:4,screenFill:`#111111`,textFill:`#ff3333`,fontSize:26,fontFamily:`monospace`,ledColor:`#ff3333`},"flip-wall":{viewBox:`0 0 120 60`,caseFill:`#1a1a1a`,caseStroke:`#444444`,caseStrokeWidth:2,caseRadius:3,screenFill:`#0d0d0d`,textFill:`#f0f0f0`,fontSize:24,fontFamily:`monospace`,extras:(e,t)=>(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`line`,{x1:`10`,y1:`30`,x2:`110`,y2:`30`,stroke:`#333`,strokeWidth:`1.5`}),(0,Q.jsx)(`rect`,{x:`14`,y:`14`,width:`40`,height:`32`,rx:`2`,fill:`#1a1a1a`}),(0,Q.jsx)(`rect`,{x:`66`,y:`14`,width:`40`,height:`32`,rx:`2`,fill:`#1a1a1a`}),(0,Q.jsx)(`text`,{x:`34`,y:`35`,textAnchor:`middle`,dominantBaseline:`middle`,fill:`#f0f0f0`,fontSize:`22`,fontFamily:`monospace`,fontWeight:`bold`,children:e}),(0,Q.jsx)(`text`,{x:`86`,y:`35`,textAnchor:`middle`,dominantBaseline:`middle`,fill:`#f0f0f0`,fontSize:`22`,fontFamily:`monospace`,fontWeight:`bold`,children:t}),(0,Q.jsx)(`circle`,{cx:`60`,cy:`24`,r:`2.5`,fill:`#f0f0f0`}),(0,Q.jsx)(`circle`,{cx:`60`,cy:`36`,r:`2.5`,fill:`#f0f0f0`})]})},"digital-table":{viewBox:`0 0 120 60`,caseFill:`#f5f0e8`,caseStroke:`#c0b090`,caseStrokeWidth:2,caseRadius:8,screenFill:`#2a2a3a`,textFill:`#66ccff`,fontSize:20,fontFamily:`monospace`,ledColor:`#66ccff`}};function $s({now:e,style:t}){let n=e.getHours().toString().padStart(2,`0`),r=e.getMinutes().toString().padStart(2,`0`),i=Qs[t]??Qs[`digital-bedside`],a=Number(i.viewBox.split(` `)[2])||120,o=a-8,s=a-24,c=a/2;return i.extras?(0,Q.jsxs)(`svg`,{viewBox:i.viewBox,className:`w-full h-full`,"aria-label":`Digital clock`,children:[(0,Q.jsx)(`rect`,{x:4,y:`4`,width:o,height:`52`,rx:i.caseRadius,fill:i.caseFill,stroke:i.caseStroke,strokeWidth:i.caseStrokeWidth}),(0,Q.jsx)(`rect`,{x:12,y:`10`,width:s,height:`40`,rx:`2`,fill:i.screenFill}),i.extras(n,r)]}):(0,Q.jsxs)(`svg`,{viewBox:i.viewBox,className:`w-full h-full`,"aria-label":`Digital clock`,children:[(0,Q.jsx)(`rect`,{x:4,y:`8`,width:o,height:`44`,rx:i.caseRadius,fill:i.caseFill,stroke:i.caseStroke,strokeWidth:i.caseStrokeWidth}),(0,Q.jsx)(`rect`,{x:12,y:`14`,width:s,height:`32`,rx:`3`,fill:i.screenFill}),(0,Q.jsxs)(`text`,{x:c,y:`38`,textAnchor:`middle`,dominantBaseline:`middle`,fill:i.textFill,fontSize:i.fontSize,fontFamily:i.fontFamily,fontWeight:`bold`,children:[n,`:`,r]}),i.ledColor&&(0,Q.jsx)(`circle`,{cx:12+s-8,cy:`20`,r:`2`,fill:i.ledColor,opacity:`0.6`})]})}var ec={back:`z-[3]`,floor:`z-[8]`,front:`z-[12]`};function tc(e){switch(e.shadow??`narrow`){case`none`:return null;case`wide`:return{widthPct:`105%`,heightPct:`13%`,alpha:.3};case`narrow`:return{widthPct:`95%`,heightPct:`14%`,alpha:.26}}}var nc=.1;function rc(e){return e.replace(`.svg`,`-overlay.svg`)}function ic({placements:e,isEditing:t=!1,selectedIndex:n,onSelectItem:r,onMoveItem:i,containerRef:a,activeLayer:o,onBackgroundClick:s}){let c=(0,Z.useCallback)(e=>{e.target===e.currentTarget&&s?.()},[s]);if(!e||e.length===0)return t&&s?(0,Q.jsx)(`div`,{className:`absolute inset-0 z-[2] pointer-events-auto`,onClick:c,"aria-hidden":!0}):null;let l=e.map((e,t)=>({placement:e,originalIndex:t})),u={back:[],floor:[],front:[]};for(let e of l)u[e.placement.layer].push(e);for(let e of[`back`,`floor`,`front`])u[e].sort((e,t)=>(Xo(e.placement.id)?.renderOrder??0)-(Xo(t.placement.id)?.renderOrder??0));return(0,Q.jsxs)(Q.Fragment,{children:[t&&s&&(0,Q.jsx)(`div`,{className:`absolute inset-0 z-[2] pointer-events-auto`,onClick:c,"aria-hidden":!0}),[`back`,`floor`,`front`].map(e=>{let s=u[e];return s.length===0?null:(0,Q.jsx)(`div`,{className:K(`absolute inset-0 pointer-events-none`,ec[e]),"aria-hidden":!t,children:s.map(({placement:e,originalIndex:s})=>(0,Q.jsx)(ac,{placement:e,index:s,isEditing:t,isSelected:n===s,isDimmed:!!o&&e.layer!==o,onSelect:r,onMove:i,containerRef:a},`${e.id}-${s}`))},e)})]})}function ac({placement:e,index:t,isEditing:n,isSelected:r,isDimmed:i,onSelect:a,onMove:o,containerRef:s}){let{isDragging:c,isHolding:l,startHold:u,shouldSuppressClick:d}=Hs({containerRef:s??{current:null},onMove:(e,n)=>o?.(t,e,n)}),f=Xo(e.id);if(!f)return null;let p=Zo(f,e.variant),m=e.scale??1,h=f.baseWidth*m*100,g=e.flip?` scaleX(-1)`:``,_=Ce(e.content?.imageUrl??``),v=t=>{n&&(t.stopPropagation(),r&&u(t,e.x,e.y))},y=e=>{n&&(e.stopPropagation(),!d()&&a?.(t))},b=tc(f);return(0,Q.jsxs)(`div`,{className:K(`absolute select-none`,n&&`cursor-pointer touch-none pointer-events-auto`,i&&!r&&`opacity-40`),style:{left:`${e.x*100}%`,top:`${e.y*100}%`,width:`${h}%`,aspectRatio:`${f.aspectRatio}`,transform:`translateX(-50%) translateY(-100%)${g}`,transition:`opacity 150ms ease`},onClick:y,onPointerDown:v,children:[b&&(0,Q.jsx)(`div`,{className:`absolute pointer-events-none`,"aria-hidden":!0,style:{left:`50%`,bottom:0,width:c?`calc(${b.widthPct} + 10%)`:b.widthPct,height:b.heightPct,transform:`translateX(-50%) translateY(${f.shadowOffsetY??`45%`})`,borderRadius:`50%`,background:`radial-gradient(ellipse at center, rgba(0,0,0,${c?b.alpha+nc:b.alpha}) 0%, rgba(0,0,0,${(c?b.alpha+nc:b.alpha)*.5}) 40%, transparent 70%)`,transition:`width 150ms ease, background 150ms ease`}}),f.isClock?(0,Q.jsx)(Ys,{clockKind:f.clockKind??`analog`,clockStyle:f.clockStyle??`classic`,isSelected:r,isDragging:c,isHolding:l}):f.isFrame&&_?(0,Q.jsx)(oc,{imageUrl:_,overlayAsset:rc(p),fallbackAsset:p,imageInset:f.frameImageInset,imageRadius:f.frameImageRadius,isSelected:r,isDragging:c,isHolding:l},_):(0,Q.jsx)(`img`,{src:p,alt:``,draggable:!1,className:K(`w-full h-full object-contain`,r&&`ring-2 ring-primary ring-offset-1 rounded-sm`,c&&`opacity-80 scale-105 transition-transform duration-100`,l&&`scale-[1.02] transition-transform duration-100`),decoding:`async`}),l&&(0,Q.jsx)(`div`,{className:`absolute -bottom-2 left-1/2 -translate-x-1/2 w-8 h-1 rounded-full bg-muted/60 overflow-hidden`,children:(0,Q.jsx)(`div`,{className:`h-full bg-primary rounded-full`,style:{animation:`furniture-hold-fill 500ms linear forwards`}})})]})}function oc({imageUrl:e,overlayAsset:t,fallbackAsset:n,imageInset:r,imageRadius:i,isSelected:a,isDragging:o,isHolding:s}){let[c,l]=(0,Z.useState)(!1),u=K(`relative w-full h-full`,a&&`ring-2 ring-primary ring-offset-1 rounded-sm`,o&&`opacity-80 scale-105 transition-transform duration-100`,s&&`scale-[1.02] transition-transform duration-100`);return c?(0,Q.jsx)(`img`,{src:n,alt:``,draggable:!1,className:K(`w-full h-full object-contain`,a&&`ring-2 ring-primary ring-offset-1 rounded-sm`,o&&`opacity-80 scale-105 transition-transform duration-100`,s&&`scale-[1.02] transition-transform duration-100`),decoding:`async`}):(0,Q.jsxs)(`div`,{className:u,children:[(0,Q.jsx)(`div`,{className:`absolute overflow-hidden`,style:{inset:r??`12% 15% 12% 15%`,borderRadius:i},children:(0,Q.jsx)(`img`,{src:e,alt:``,draggable:!1,className:`w-full h-full object-cover`,onError:()=>l(!0),decoding:`async`})}),(0,Q.jsx)(`img`,{src:t,alt:``,draggable:!1,className:`absolute inset-0 w-full h-full object-contain`,decoding:`async`})]})}function sc({onClick:e}){return(0,Q.jsx)(q,{variant:`ghost`,size:`icon`,onClick:e,className:`size-9 rounded-full bg-background/70 border border-border/60 shadow-sm backdrop-blur-sm text-muted-foreground hover:text-foreground hover:bg-background/90`,"aria-label":`Edit room furniture`,children:(0,Q.jsx)(f,{className:`size-4`})})}function cc({roomId:e,draft:t,onDraftChange:n,selectedIndex:r,onSelectItem:i,onClose:a,onSave:o,isSaving:l=!1,placement:d=`bottom`}){let[f,p]=(0,Z.useState)(!1);(0,Z.useEffect)(()=>{p(!1)},[d]);let m=r===null?null:t[r],h=m?Xo(m.id):null,g=po[e],_=t.length>=20,v=(0,Z.useMemo)(()=>ns(e),[e]),y=(0,Z.useCallback)(e=>{if(_)return;let r={id:e.id,x:.5,y:.75,layer:e.defaultLayer,scale:1},a=[...t,r];n(a),i(a.length-1),p(!1)},[t,n,i,_]),b=(0,Z.useCallback)(()=>{r!==null&&(n(t.filter((e,t)=>t!==r)),i(null))},[t,r,n,i]),x=(0,Z.useCallback)(()=>{r!==null&&n(t.map((e,t)=>t===r?{...e,flip:!e.flip}:e))},[t,r,n]),S=(0,Z.useCallback)(e=>{r!==null&&n(t.map((t,n)=>n===r?{...t,layer:e}:t))},[t,r,n]),C=(0,Z.useCallback)(e=>{r!==null&&n(t.map((t,n)=>{if(n!==r)return t;let i=t.scale??1,a=Math.round(Math.min(2,Math.max(.5,i+e))*10)/10;return{...t,scale:a}}))},[t,r,n]),w=(0,Z.useCallback)(()=>{n([...rs[e]??[]]),i(null)},[e,n,i]),T=(0,Z.useCallback)(e=>{r!==null&&n(t.map((t,n)=>{if(n!==r)return t;if(!e){let{content:e,...n}=t;return n}return{...t,content:e}}))},[t,r,n]);return(0,Q.jsxs)(`div`,{className:K(`absolute inset-x-0 z-[55] pointer-events-none`,d===`top`?`top-0`:`bottom-0`),children:[f&&(0,Q.jsx)(`div`,{className:K(`absolute inset-x-0 px-3 pointer-events-auto`,d===`top`?`top-full mt-2`:`bottom-full mb-2`),children:(0,Q.jsxs)(`div`,{className:K(`rounded-2xl border border-border/60 bg-background/95 backdrop-blur-md shadow-xl p-3 max-h-48 overflow-y-auto animate-in fade-in-0 duration-150`,d===`top`?`slide-in-from-bottom-2`:`slide-in-from-top-2`),children:[(0,Q.jsxs)(`div`,{className:`flex items-center justify-between mb-2`,children:[(0,Q.jsx)(`span`,{className:`text-xs font-semibold text-muted-foreground`,children:`Add furniture`}),(0,Q.jsx)(`button`,{onClick:()=>p(!1),className:`size-6 rounded-full flex items-center justify-center text-muted-foreground hover:text-foreground hover:bg-accent/50`,children:(0,Q.jsx)(A,{className:`size-3.5`})})]}),(0,Q.jsx)(`div`,{className:`grid grid-cols-4 gap-2`,children:v.map(e=>(0,Q.jsxs)(Z.Fragment,{children:[(0,Q.jsx)(`span`,{className:`col-span-4 text-[9px] font-semibold text-muted-foreground mt-1 first:mt-0`,children:e.label}),e.items.map(e=>(0,Q.jsxs)(`button`,{onClick:()=>y(e),disabled:_,className:K(`flex flex-col items-center gap-1 p-2 rounded-xl`,`border border-border/40 bg-muted/30`,`hover:bg-accent/50 hover:border-primary/30`,`transition-colors duration-100`,`disabled:opacity-40 disabled:pointer-events-none`),children:[(0,Q.jsx)(`img`,{src:e.asset,alt:e.label,className:`size-8 object-contain`,draggable:!1,decoding:`async`}),(0,Q.jsx)(`span`,{className:`text-[9px] text-muted-foreground leading-tight text-center truncate w-full`,children:e.label})]},e.id))]},e.category))}),_&&(0,Q.jsxs)(`p`,{className:`text-[10px] text-destructive mt-2 text-center`,children:[`Maximum `,20,` items reached`]})]})}),(0,Q.jsx)(`div`,{className:K(`relative pointer-events-auto px-3`,d===`top`?`pt-14 pb-2`:`pt-2 pb-4 max-sidebar:pb-[calc(var(--bottom-nav-height)+env(safe-area-inset-bottom,0px)+0.75rem)]`),children:(0,Q.jsxs)(`div`,{className:`rounded-2xl border border-border/60 bg-background/95 backdrop-blur-md shadow-xl`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center justify-between px-3 pt-2.5 pb-1`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Q.jsx)(g.icon,{className:`size-3.5 text-primary`}),(0,Q.jsx)(`span`,{className:`text-xs font-semibold`,children:`Furniture`}),(0,Q.jsxs)(`span`,{className:`text-[10px] text-muted-foreground`,children:[t.length,`/`,20]})]}),(0,Q.jsx)(`div`,{className:`flex items-center gap-1`,children:(0,Q.jsx)(q,{variant:`ghost`,size:`icon`,onClick:w,className:`size-7 rounded-full text-muted-foreground hover:text-foreground`,"aria-label":`Reset to defaults`,children:(0,Q.jsx)(s,{className:`size-3.5`})})})]}),t.length>0&&(0,Q.jsx)(`div`,{className:`px-3 pt-1 overflow-x-auto`,children:(0,Q.jsx)(`div`,{className:`flex gap-1.5 w-max`,children:t.map((e,t)=>{let n=Xo(e.id),a=n?Zo(n,e.variant):void 0,o=n?.label??`Unknown`,s=t===r;return(0,Q.jsx)(`button`,{type:`button`,onClick:()=>i(t),"aria-label":`Select ${o} (item ${t+1})`,title:`${o} (${t+1})`,className:K(`size-9 shrink-0 rounded-lg flex items-center justify-center border transition-all duration-100`,s?`ring-2 ring-primary border-primary/60 bg-primary/10`:`border-border/40 bg-muted/30 hover:bg-accent/50`),children:a?(0,Q.jsx)(`img`,{src:a,alt:o,className:`size-6 object-contain`,draggable:!1,decoding:`async`}):(0,Q.jsx)(`span`,{className:`text-[10px] text-muted-foreground`,children:`?`})},t)})})}),m&&(0,Q.jsxs)(`div`,{className:`px-3 pb-2 pt-1 space-y-2`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Q.jsx)(`span`,{className:`text-[10px] text-muted-foreground w-10 shrink-0`,children:`Layer`}),(0,Q.jsx)(`div`,{className:`flex p-0.5 rounded-lg bg-muted/50 flex-1`,children:zo.map(e=>(0,Q.jsx)(`button`,{type:`button`,onClick:()=>S(e),className:K(`flex-1 py-1 rounded-md text-[10px] font-medium text-center transition-all duration-100`,m.layer===e?`bg-background shadow-sm text-foreground`:`text-muted-foreground hover:text-foreground`),children:e},e))})]}),h?.isFrame&&(0,Q.jsx)(lc,{imageUrl:m.content?.imageUrl,onImageChange:e=>{if(e){let t=m.content;T({...t,imageUrl:e})}else{let e=m.content;if(e){let{imageUrl:t,...n}=e,r=Object.keys(n).length>0;T(r?n:void 0)}}}},r),(0,Q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Q.jsx)(`span`,{className:`text-[10px] text-muted-foreground w-10 shrink-0`,children:`Size`}),(0,Q.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,Q.jsx)(q,{variant:`outline`,size:`icon`,onClick:()=>C(-.1),disabled:(m.scale??1)<=.5,className:`size-6 rounded-md`,children:(0,Q.jsx)(V,{className:`size-3`})}),(0,Q.jsxs)(`span`,{className:`text-[10px] font-mono w-7 text-center`,children:[((m.scale??1)*100).toFixed(0),`%`]}),(0,Q.jsx)(q,{variant:`outline`,size:`icon`,onClick:()=>C(.1),disabled:(m.scale??1)>=2,className:`size-6 rounded-md`,children:(0,Q.jsx)(u,{className:`size-3`})})]}),(0,Q.jsx)(`div`,{className:`flex-1`}),(0,Q.jsx)(q,{variant:`outline`,size:`icon`,onClick:x,disabled:!h?.flippable,className:`size-7 rounded-lg`,"aria-label":`Flip horizontal`,children:(0,Q.jsx)(ee,{className:`size-3.5`})}),(0,Q.jsx)(q,{variant:`outline`,size:`icon`,onClick:b,className:`size-7 rounded-lg text-destructive hover:text-destructive`,"aria-label":`Remove item`,children:(0,Q.jsx)(c,{className:`size-3.5`})})]})]}),(0,Q.jsx)(`div`,{className:`px-3 pb-2 pt-1`,children:(0,Q.jsxs)(q,{variant:`outline`,size:`sm`,onClick:()=>p(!f),disabled:_,className:`w-full gap-1.5 h-8 text-xs`,children:[(0,Q.jsx)(u,{className:`size-3.5`}),`Add furniture`]})}),(0,Q.jsxs)(`div`,{className:`flex items-center gap-2 px-3 pb-2.5`,children:[(0,Q.jsxs)(q,{variant:`ghost`,size:`sm`,onClick:a,disabled:l,className:`flex-1 h-8 text-xs`,children:[(0,Q.jsx)(A,{className:`size-3.5 mr-1`}),`Cancel`]}),(0,Q.jsxs)(q,{size:`sm`,onClick:o,disabled:l,className:`flex-1 h-8 text-xs`,children:[l?(0,Q.jsx)(`span`,{className:`size-3.5 mr-1 animate-spin rounded-full border-2 border-current border-t-transparent`}):(0,Q.jsx)(I,{className:`size-3.5 mr-1`}),l?`Saving...`:`Save`]})]})]})})]})}function lc({imageUrl:e,onImageChange:t}){let{mutateAsync:r,isPending:i}=Ve(),{toast:a}=Oe(),o=(0,Z.useRef)(null),[s,c]=(0,Z.useState)(``),[l,u]=(0,Z.useState)(!1),d=(0,Z.useCallback)(async e=>{let n=e.target.files?.[0];if(n){e.target.value=``;try{let[[,e]]=await r(n);t(e)}catch{a({title:`Upload failed`,description:`Could not upload image.`,variant:`destructive`})}}},[r,t,a]),f=(0,Z.useCallback)(e=>{let n=e.trim();if(!n){u(!1);return}let r=Ce(n);r?(t(r),c(``),u(!1)):u(!0)},[t]);return(0,Q.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Q.jsx)(`span`,{className:`text-[10px] text-muted-foreground w-10 shrink-0`,children:`Image`}),(0,Q.jsxs)(`div`,{className:`flex items-center gap-1.5 flex-1 min-w-0`,children:[(0,Q.jsxs)(q,{variant:`outline`,size:`sm`,onClick:()=>o.current?.click(),disabled:i,className:`h-6 px-2 text-[10px] gap-1`,children:[i?(0,Q.jsx)(k,{className:`size-3 animate-spin`}):(0,Q.jsx)(n,{className:`size-3`}),i?`Uploading…`:`Upload`]}),(0,Q.jsx)(`input`,{ref:o,type:`file`,accept:`image/*`,className:`hidden`,onChange:d}),e&&(0,Q.jsxs)(`div`,{className:`flex items-center gap-1 min-w-0`,children:[(0,Q.jsx)(`img`,{src:e,alt:``,className:`size-6 rounded-sm object-cover border border-border/60`,decoding:`async`}),(0,Q.jsx)(`button`,{type:`button`,onClick:()=>t(void 0),className:`size-5 rounded-full flex items-center justify-center text-muted-foreground hover:text-destructive hover:bg-destructive/10 transition-colors`,"aria-label":`Remove image`,children:(0,Q.jsx)(A,{className:`size-3`})})]})]})]}),(0,Q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Q.jsx)(`span`,{className:`text-[10px] text-muted-foreground w-10 shrink-0`,children:(0,Q.jsx)(S,{className:`size-3 mx-auto`})}),(0,Q.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,Q.jsx)(`input`,{type:`url`,value:s,onChange:e=>{c(e.target.value),u(!1)},onKeyDown:e=>{e.key===`Enter`&&f(s)},onBlur:()=>f(s),placeholder:`Paste image URL…`,className:K(`w-full h-6 px-2 text-[10px] rounded-md border bg-muted/30 outline-none`,`focus:ring-1 focus:ring-primary/50 focus:border-primary/40`,`placeholder:text-muted-foreground/60`,l&&`border-destructive/60 focus:ring-destructive/50`)}),l&&(0,Q.jsx)(`p`,{className:`text-[9px] text-destructive mt-0.5`,children:`Must be an https:// URL`})]})]})]})}var uc=(0,Z.memo)(function({companion:e,isActiveFloatingCompanion:t,isUpdatingCompanion:n,handleSetAsCompanion:r,className:i}){return t?(0,Q.jsxs)(`div`,{className:K(`flex flex-col items-center justify-center gap-4 text-center flex-1 px-4`,i),children:[(0,Q.jsx)(R,{className:`size-12 text-muted-foreground/30`}),(0,Q.jsxs)(`p`,{className:`text-muted-foreground text-sm`,children:[e.name,` is out exploring right now.`]}),(0,Q.jsxs)(`button`,{onClick:r,disabled:n,className:K(`flex items-center justify-center gap-2 px-6 py-3 rounded-full text-white font-semibold transition-all duration-300 ease-out text-sm`,`hover:-translate-y-0.5 hover:scale-105 hover:brightness-110 active:scale-95`,n&&`opacity-50 pointer-events-none`),style:{background:`linear-gradient(135deg, #8b5cf6, #ec4899, #f59e0b)`},children:[n?(0,Q.jsx)(k,{className:`size-4 animate-spin`}):(0,Q.jsx)(R,{className:`size-4`}),(0,Q.jsxs)(`span`,{children:[`Bring `,e.name,` home`]})]})]}):(0,Q.jsx)(`div`,{className:K(`flex-1 min-h-0`,i)})}),dc=4/5;function fc({poopStateRef:e}){let t=e.current;if(!t||t.poops.length===0)return null;let n=t.poops;return(0,Q.jsx)(Q.Fragment,{children:n.map(e=>(0,Q.jsx)(`div`,{className:`absolute z-10 pointer-events-none select-none`,style:{bottom:`${e.position.bottom}%`,left:`${e.position.left}%`},children:(0,Q.jsx)(`span`,{className:`text-2xl sm:text-3xl block`,children:`💩`})},e.id))})}function pc({drag:e,poopStateRef:t,roomId:n}){let r=t.current,i=r?Fs(r.poops,n):[];return i.length===0&&!e.isDragging?null:(0,Q.jsxs)(Q.Fragment,{children:[i.map(t=>(0,Q.jsx)(`div`,{ref:n=>{n?e.poopRefs.current.set(t.id,n):e.poopRefs.current.delete(t.id)},className:K(`absolute z-10 transition-transform duration-200 pointer-events-none select-none`,e.hoveredPoopId===t.id&&e.isDragging&&`scale-150`),style:{bottom:`${t.position.bottom}%`,left:`${t.position.left}%`},children:(0,Q.jsx)(`span`,{className:K(`text-2xl sm:text-3xl block`,e.isDragging&&`drop-shadow-lg`),children:`💩`})},t.id)),e.isDragging&&e.dragPos&&(0,Q.jsx)(`div`,{className:`fixed z-[60] pointer-events-none`,style:{left:e.dragPos.x,top:e.dragPos.y,transform:`translate(-50%, -50%)`},children:(0,Q.jsx)(`div`,{className:`size-14 sm:size-20 rounded-full flex items-center justify-center text-amber-600 bg-amber-500/15 ring-2 ring-amber-500/40 shadow-lg`,children:(0,Q.jsx)(de,{className:`size-7 sm:size-9`})})})]})}function mc({drag:e,guideActionGlow:t}){return(0,Q.jsx)(Rs,{ref:e.shovelRef,icon:(0,Q.jsx)(de,{className:`size-7 sm:size-9`}),label:`Shovel`,color:`text-stone-500`,glowHex:`#78716c`,onClick:()=>{e.anyPoop||W({title:`Nothing to clean!`,description:`Your Blobbi hasn't made a mess.`})},onMouseDown:e.anyPoop?e.onMouseDown:void 0,onTouchStart:e.anyPoop?e.onTouchStart:void 0,className:K(e.anyPoop&&`touch-none`,e.isDragging&&`opacity-30`),glow:e.anyPoop&&t===`clean`})}function hc(e){let t=e?Ls(e.poops):!1,[n,r]=(0,Z.useState)(!1),i=(0,Z.useRef)({x:0,y:0}),a=(0,Z.useRef)(null),[o,s]=(0,Z.useState)(null),c=(0,Z.useRef)(new Map),[l,u]=(0,Z.useState)(null),d=(0,Z.useCallback)((e,n)=>{if(!t||!a.current)return;let o=a.current.getBoundingClientRect();i.current={x:e-(o.left+o.width/2),y:n-(o.top+o.height/2)},s({x:e-i.current.x,y:n-i.current.y}),r(!0)},[t]),f=(0,Z.useCallback)((e,t)=>{if(!n)return;s({x:e-i.current.x,y:t-i.current.y});let r=null;c.current.forEach((n,i)=>{let a=n.getBoundingClientRect();e>=a.left&&e<=a.right&&t>=a.top&&t<=a.bottom&&(r=i)}),u(r)},[n]),p=(0,Z.useCallback)(()=>{r(!1),s(null),u(null)},[]),m=(0,Z.useCallback)(()=>{n&&(l&&e&&e.onRemovePoop(l),p())},[n,l,e,p]),h=(0,Z.useCallback)(e=>{e.preventDefault(),d(e.clientX,e.clientY)},[d]);return(0,Z.useEffect)(()=>{if(!n)return;let e=e=>f(e.clientX,e.clientY),t=()=>m(),r=e=>f(e.touches[0].clientX,e.touches[0].clientY),i=()=>m(),a=()=>p();return window.addEventListener(`mousemove`,e),window.addEventListener(`mouseup`,t),window.addEventListener(`touchmove`,r),window.addEventListener(`touchend`,i),window.addEventListener(`touchcancel`,a),()=>{window.removeEventListener(`mousemove`,e),window.removeEventListener(`mouseup`,t),window.removeEventListener(`touchmove`,r),window.removeEventListener(`touchend`,i),window.removeEventListener(`touchcancel`,a)}},[n,f,m,p]),{anyPoop:t,isDragging:n,dragPos:o,hoveredPoopId:l,shovelRef:a,poopRefs:c,onMouseDown:h,onTouchStart:(0,Z.useCallback)(e=>{e.stopPropagation(),d(e.touches[0].clientX,e.touches[0].clientY)},[d])}}var gc=50,_c=56;function vc({roomId:e,onChangeRoom:t,isSleeping:n,hero:r,children:i,middleSlot:a,stageOverlay:o,statusHud:s,roomOrder:c=mo,hunger:l,lastFeedTimestamp:u,poopStateRef:d,onPoopCleaned:f,guideRoomDirection:p,roomLayout:m,editorSlot:h,editorSlotLeft:g,editorOverlay:_,roomOverlay:v,shovelDragRef:y,hudVisible:b=!0,furniturePlacements:x,containerRef:S,isFurnitureEditing:C,furnitureSelectedIndex:w,onFurnitureSelect:T,onFurnitureMove:E,furnitureActiveLayer:ee,onFurnitureBackgroundClick:te}){let D=(0,Z.useCallback)(()=>{t(vo(e,c))},[e,c,t]),O=(0,Z.useCallback)(()=>{t(_o(e,c))},[e,c,t]),k=po[vo(e,c)],A=po[_o(e,c)],j=po[e],M=yo(e,c),N=(0,Z.useRef)(null),ne=(0,Z.useCallback)(e=>{e.target.closest?.(`[data-food-drag]`)||(N.current=e.touches[0].clientX)},[N]),P=(0,Z.useCallback)(e=>{if(N.current===null)return;if(C){N.current=null;return}let t=e.changedTouches[0].clientX-N.current;N.current=null,!(Math.abs(t)<gc)&&(Ne(),t>0?D():O())},[N,D,O,C]),[re,F]=(0,Z.useState)([]);(0,Z.useEffect)(()=>{F(Ns(l,u))},[]);let ie=(0,Z.useCallback)(e=>{F(t=>{let{remaining:n}=Is(t,e);return n.length<t.length&&f?.(),n})},[f]),I=(0,Z.useCallback)((e=`overfeed`)=>{F(t=>Ps(t,e))},[]),L=(0,Z.useMemo)(()=>({poops:re,onRemovePoop:ie,addPoop:I}),[re,ie,I]);d&&(d.current=L);let R=(0,Z.useRef)(null);R.current=L;let oe=hc(e===`kitchen`?L:null);y&&(y.current=oe);let se=(0,Z.useMemo)(()=>{if(m)return os(m.wall)},[m]),z=(0,Z.useMemo)(()=>{if(m)return os(m.floor)},[m]);return(0,Q.jsxs)(`div`,{className:`flex flex-col flex-1 min-h-0 relative`,onTouchStart:ne,onTouchEnd:P,children:[(0,Q.jsxs)(`div`,{ref:S,className:K(`absolute inset-x-0 mx-auto pointer-events-none`,C&&`ring-2 ring-primary/30 rounded-sm`),style:{aspectRatio:`${dc}`,width:`100%`,maxWidth:`100%`,top:_c,maxHeight:`calc(100% - ${_c}px - var(--blobbi-room-dock-height))`},children:[m&&(0,Q.jsxs)(Q.Fragment,{children:[se&&(0,Q.jsx)(`div`,{className:`absolute inset-x-0`,style:{top:-60,background:se,bottom:`${.28*100}%`},"aria-hidden":!0}),z&&(0,Q.jsx)(`div`,{className:`absolute inset-x-0 bottom-0`,style:{background:z,top:`${.72*100}%`},"aria-hidden":!0}),(0,Q.jsxs)(`div`,{className:`absolute inset-x-0 z-[1] flex flex-col`,style:{top:`${.72*100}%`},"aria-hidden":!0,children:[(0,Q.jsx)(`div`,{className:`h-px bg-foreground/10`}),(0,Q.jsx)(`div`,{className:`h-0.5 bg-background/15`})]}),(0,Q.jsx)(`div`,{className:`absolute inset-x-0 h-3 z-[1]`,style:{top:`${.72*100}%`,background:`linear-gradient(to bottom, hsl(var(--foreground) / 0.06), transparent)`},"aria-hidden":!0})]}),z&&(0,Q.jsx)(`div`,{className:`absolute inset-x-0 pointer-events-none`,style:{top:`${.72*100}%`,height:`80%`,background:z},"aria-hidden":!0}),(0,Q.jsx)(ic,{placements:x,isEditing:C,selectedIndex:w,onSelectItem:T,onMoveItem:E,containerRef:S,activeLayer:ee,onBackgroundClick:te}),e===`kitchen`?(0,Q.jsx)(pc,{drag:oe,poopStateRef:R,roomId:e}):(0,Q.jsx)(fc,{poopStateRef:R}),o&&(0,Q.jsx)(`div`,{className:K(`absolute inset-0 z-10 transition-opacity duration-300`,C&&`opacity-30`),children:o}),n&&(0,Q.jsx)(`div`,{className:`absolute inset-0 z-20 transition-opacity duration-700`,style:{background:`radial-gradient(ellipse at 50% 40%, rgba(0,0,0,0.25) 0%, rgba(0,0,0,0.45) 100%)`}}),(0,Q.jsx)(`button`,{onClick:D,disabled:C,className:K(`group absolute left-1 top-1/2 -translate-y-1/2 z-40 pointer-events-auto`,`flex items-center justify-center`,`size-10 sm:size-12 rounded-full`,In,`text-muted-foreground/60 hover:text-foreground/80 hover:bg-background/70`,`transition-all duration-200 active:scale-90`,`cursor-pointer select-none`,p===`left`&&[`ring-2 ring-primary ring-offset-2 ring-offset-background`,`animate-[guide-ring-pulse_1.2s_ease-in-out_infinite]`],C&&`opacity-20 pointer-events-none`),"aria-label":`Go to ${k.label}`,children:(0,Q.jsx)(ue,{className:`size-7 sm:size-8 shrink-0`,strokeWidth:4,style:p===`left`?void 0:{animation:`room-arrow-nudge-left 2.5s ease-in-out infinite`}})}),(0,Q.jsx)(`button`,{onClick:O,disabled:C,className:K(`group absolute right-1 top-1/2 -translate-y-1/2 z-40 pointer-events-auto`,`flex items-center justify-center`,`size-10 sm:size-12 rounded-full`,In,`text-muted-foreground/60 hover:text-foreground/80 hover:bg-background/70`,`transition-all duration-200 active:scale-90`,`cursor-pointer select-none`,p===`right`&&[`ring-2 ring-primary ring-offset-2 ring-offset-background`,`animate-[guide-ring-pulse_1.2s_ease-in-out_infinite]`],C&&`opacity-20 pointer-events-none`),"aria-label":`Go to ${A.label}`,children:(0,Q.jsx)(ae,{className:`size-7 sm:size-8 shrink-0`,strokeWidth:4,style:p===`right`?void 0:{animation:`room-arrow-nudge-right 2.5s ease-in-out infinite`}})}),(0,Q.jsxs)(`div`,{className:K(`absolute top-3 inset-x-0 z-30 flex flex-col items-center pointer-events-none gap-2 transition-opacity duration-200`,!b&&`opacity-0`,C&&`opacity-30`),children:[(0,Q.jsxs)(`div`,{className:`pointer-events-auto flex flex-col items-center gap-0.5 py-1 px-3 rounded-full bg-background/60 backdrop-blur-sm`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,Q.jsx)(j.icon,{className:`size-3.5 text-foreground/50`}),(0,Q.jsx)(`span`,{className:`text-xs font-semibold text-foreground/60`,children:j.label})]}),(0,Q.jsx)(`div`,{className:`flex items-center gap-1`,children:c.map((e,t)=>(0,Q.jsx)(`div`,{className:K(`rounded-full transition-all duration-300`,t===M?`w-3 h-1 bg-primary`:`w-1 h-1 bg-muted-foreground/20`)},e))})]}),s&&(0,Q.jsx)(`div`,{className:`pointer-events-auto`,children:s})]}),h&&(0,Q.jsx)(`div`,{className:K(`absolute top-3 right-3 z-[55] pointer-events-auto transition-opacity duration-200`,!b&&`opacity-0 pointer-events-none`,C&&`opacity-0 pointer-events-none`),children:h}),g&&(0,Q.jsx)(`div`,{className:K(`absolute top-3 left-3 z-[55] pointer-events-auto transition-opacity duration-200`,!b&&`opacity-0 pointer-events-none`,C&&`opacity-0 pointer-events-none`),children:g})]}),(0,Q.jsxs)(`div`,{className:K(`flex-1 min-h-0 flex flex-col relative z-[15] transition-opacity duration-200`,C&&`opacity-30 pointer-events-none`),children:[r,a,(0,Q.jsxs)(`div`,{className:`relative`,children:[(0,Q.jsx)(Je,{variant:`up-subtle`}),i]})]}),v&&(0,Q.jsx)(`div`,{className:`absolute inset-0 z-50`,children:v}),_]})}var yc=(1-To)*100;function bc({companion:e,currentStats:t,isSleeping:n,isEgg:r,statusRecipe:i,statusRecipeLabel:a,effectiveEmotion:o,hasDevOverride:s,blobbiReaction:c,interactionReaction:l,stageRef:u}){let d=Ao(e.stage,e.adultType??void 0),f=`${4-t.happiness/100*1.5}s`;return(0,Q.jsx)(`div`,{ref:u,className:`absolute inset-0 pointer-events-none`,children:(0,Q.jsxs)(`div`,{className:`absolute inset-x-0`,style:{top:`${yc}%`},children:[(0,Q.jsx)(`div`,{className:`absolute z-0 pointer-events-none`,"aria-hidden":!0,style:{top:4,left:`50%`,transformOrigin:`center center`,background:`radial-gradient(ellipse, rgba(0,0,0,0.22) 0%, rgba(0,0,0,0.13) 38%, transparent 68%)`,width:r?`22%`:`28%`,aspectRatio:r?`4`:`4.5`,...n?{transform:`translateX(-50%)`}:{animation:`blobbi-shadow-breathe ${f} ease-in-out infinite`}}}),(0,Q.jsx)(`div`,{className:`relative z-10`,style:{transform:`translateY(calc(-100% + ${d}%))`},children:(0,Q.jsxs)(`div`,{className:`relative w-full flex justify-center`,style:n?void 0:{animation:`blobbi-bob ${f} ease-in-out infinite`},children:[!r&&(0,Q.jsx)(`div`,{className:`absolute bottom-full left-1/2 mb-1 pointer-events-none`,style:{transform:`translateX(-50%)`},children:(0,Q.jsx)(`span`,{className:`whitespace-nowrap text-sm font-bold drop-shadow-sm`,style:{color:e.visualTraits.baseColor},children:e.name})}),(0,Q.jsxs)(`div`,{"data-blobbi-visual":!0,className:K(`relative transition-all duration-500 pointer-events-none`,l?.bodyAnimation),style:{width:r?`24%`:`30%`,aspectRatio:`1`,...n?void 0:{animation:`blobbi-sway ${6-t.happiness/100*2}s ease-in-out infinite`}},children:[(0,Q.jsx)(`div`,{className:`absolute inset-0 -m-16 sm:-m-20 bg-primary/5 rounded-full blur-3xl`}),(0,Q.jsx)(bn,{companion:e,size:`lg`,animated:!n,reaction:c,recipe:s?void 0:i,recipeLabel:s?void 0:a,emotion:o,className:`!size-full`}),(0,Q.jsx)(zn,{active:l?.sparkles??!1}),(0,Q.jsx)(Rn,{active:l?.bubbles??!1,showBackdrop:!1}),(0,Q.jsx)(Bn,{active:l?.hearts??!1})]})]})})]})})}var xc={hunger:`orange`,happiness:`yellow`,health:`green`,hygiene:`blue`,energy:`violet`},Sc={orange:`text-orange-500`,yellow:`text-yellow-500`,green:`text-green-500`,blue:`text-blue-500`,violet:`text-violet-500`},Cc={orange:`bg-orange-500/10`,yellow:`bg-yellow-500/10`,green:`bg-green-500/10`,blue:`bg-blue-500/10`,violet:`bg-violet-500/10`},wc={orange:`#f97316`,yellow:`#eab308`,green:`#22c55e`,blue:`#3b82f6`,violet:`#8b5cf6`},Tc={hunger:pe,happiness:re,health:l,hygiene:r,energy:B};function Ec(e,t){if(t<=1)return 0;let n=(t-1)/2,r=Math.max(n,t-1-n),i=Math.abs(e-n),a=r===0?0:1-i/r;return Math.round(a*10)}function Dc({companion:e,currentStats:t,onGuide:n}){let r=(0,Z.useMemo)(()=>mn(e.stage).map(n=>{let r=t[n]??100,i=xn({stage:e.stage,stat:n,value:r});return{stat:n,value:r,careState:i.careState,filled:i.filled,max:i.max,color:xc[n]}}),[e.stage,t]);if(r.length===0)return null;let i=r.length;return(0,Q.jsx)(`div`,{className:`flex items-start justify-center gap-2 sm:gap-3`,style:{animation:`stat-glow-clock 2s linear infinite`},children:r.map((e,t)=>(0,Q.jsx)(`div`,{style:{transform:`translateY(${Ec(t,i)}px)`},children:(0,Q.jsx)(`button`,{type:`button`,className:K(`transition-transform duration-200 active:scale-90`,n&&`cursor-pointer`),onClick:n?()=>n(e.stat):void 0,children:(0,Q.jsx)(Oc,{stat:e.stat,value:e.value,color:e.color,careState:e.careState,filled:e.filled,max:e.max})})},e.stat))})}function Oc({stat:e,value:t,color:n,careState:r=`good`,filled:i,max:a}){let o=t??0,s=r===`attention`||r===`urgent`,c=r===`urgent`,l=r===`urgent`?`text-red-500`:`text-amber-500`,u=wc[n],d=Tc[e],f=i!==void 0&&a!==void 0,p=r===`attention`||r===`urgent`,m=r===`attention`?{boxShadow:`0 0 calc(var(--stat-glow-intensity) * 6px) calc(var(--stat-glow-intensity) * 2px) currentColor`}:r===`urgent`?{boxShadow:`0 0 calc(var(--stat-glow-intensity) * 10px) calc(var(--stat-glow-intensity) * 3px) currentColor`}:void 0;return(0,Q.jsxs)(`div`,{className:K(`relative size-10 sm:size-12 rounded-full flex items-center justify-center`,In,`border border-border/20 shadow-sm`,Cc[n],p&&Sc[n],c&&`animate-pulse`),style:m,children:[(0,Q.jsx)(`svg`,{className:`absolute inset-0 -rotate-90`,viewBox:`0 0 36 36`,children:f?(0,Q.jsx)(An,{filled:i,max:a,fillHex:u,strokeWidth:2.5,gapDeg:16}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`circle`,{cx:`18`,cy:`18`,r:`15`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.5`,className:`text-muted/15`}),(0,Q.jsx)(`circle`,{cx:`18`,cy:`18`,r:`15`,fill:`none`,strokeWidth:`2.5`,strokeLinecap:`round`,stroke:u,strokeDasharray:`${o*.94} 100`,className:`transition-all duration-500`})]})}),(0,Q.jsxs)(`div`,{className:`relative`,children:[d&&(0,Q.jsx)(d,{className:K(`size-4 sm:size-5`,Sc[n]),strokeWidth:2.5}),s&&(0,Q.jsx)(_,{className:K(`absolute -top-1 -right-1.5 size-2.5`,l),strokeWidth:3})]})]})}var kc={health:`care`,hygiene:`care`,hunger:`kitchen`,happiness:`home`,energy:`rest`},Ac={health:`item`,hygiene:`item`,hunger:`item`,happiness:`item`,energy:`action`},jc={energy:`sleep`},Mc={home:[`toy`],kitchen:[`food`,`energy`],care:[`hygiene`,`medicine`],rest:[],closet:[]},Nc={care:new Set([`hyg_towel`])};function Pc(e){if(Ac[e]!==`item`)return null;let t=kc[e],n=Mc[t],r=Nc[t];return fn().find(t=>t.effect&&(t.effect[e]??0)>0&&n.includes(t.type)&&(!r||!r.has(t.id)))?.id??null}function Fc(e,t){let n=kc[e],r=Ac[e],i=t===n;return{stat:e,targetRoom:n,targetType:r,targetItemId:r===`item`?Pc(e):null,targetAction:r===`action`?jc[e]??null:null,step:i?r:`room`}}function Ic(e,t,n=mo){if(e===t)return null;let r=n.indexOf(e),i=n.indexOf(t);if(r===-1||i===-1)return null;let a=n.length;return(i-r+a)%a<=(r-i+a)%a?`right`:`left`}var Lc=80,Rc=.5,zc=.67,Bc=-1;function Vc(){let e=document.querySelector(`[data-blobbi-visual]`);if(!e)return null;let t=e.getBoundingClientRect();return{mx:t.left+t.width*Rc,my:t.top+t.height*zc}}function Hc(e,t){let n=Vc();if(!n)return!1;let r=e-n.mx,i=t-n.my;return Math.sqrt(r*r+i*i)<=Lc}function Uc(e,t){let[n,r]=(0,Z.useState)(null),i=(0,Z.useRef)(Bc),a=(0,Z.useRef)(null),o=(0,Z.useRef)(!1),s=(0,Z.useRef)(0),c=(0,Z.useRef)(e);c.current=e;let l=(0,Z.useRef)(t);l.current=t;let u=(0,Z.useRef)(null),d=(0,Z.useCallback)((e,t)=>{let n=u.current;n&&(n.style.display=``,n.style.left=`${e}px`,n.style.top=`${t}px`)},[]),f=(0,Z.useCallback)(()=>{let e=u.current;e&&(e.style.display=`none`,e.firstElementChild&&e.firstElementChild.classList.remove(`scale-75`))},[]),p=(0,Z.useRef)(null),m=(0,Z.useCallback)(e=>{i.current!==Bc&&(i.current,i.current=Bc,a.current=null,o.current=!1,f(),r(null),p.current?.(),p.current=null)},[f]),h=(0,Z.useCallback)((e,t,n)=>{i.current!==Bc&&m(`new-drag-while-active`),e.preventDefault(),e.stopPropagation();let f=e.pointerId,h=e.clientX,g=e.clientY,_=++s.current;i.current=f,a.current=t,o.current=!1,r({itemId:t,emoji:n,startX:h,startY:g});let v=e=>{if(e.pointerId!==f||_!==s.current){e.pointerId,s.current;return}d(e.clientX,e.clientY);let t=u.current;if(t?.firstElementChild){let n=Hc(e.clientX,e.clientY);t.firstElementChild.classList.toggle(`scale-75`,n),n!==o.current&&(o.current=n,l.current?.(n))}},y=e=>{if(e.pointerId!==f||_!==s.current)return;let t=a.current,n=t?Hc(e.clientX,e.clientY):!1,r=o.current;e.clientX,e.clientY,m(n?`feed`:`miss`),n&&t?c.current(t):r&&l.current?.(!1)},b=e=>{if(e.pointerId!==f||_!==s.current)return;let t=o.current;m(`cancel`),t&&l.current?.(!1)},x=()=>{if(_!==s.current)return;let e=o.current;m(`blur`),e&&l.current?.(!1)};window.addEventListener(`pointermove`,v),window.addEventListener(`pointerup`,y),window.addEventListener(`pointercancel`,b),window.addEventListener(`blur`,x),p.current=()=>{window.removeEventListener(`pointermove`,v),window.removeEventListener(`pointerup`,y),window.removeEventListener(`pointercancel`,b),window.removeEventListener(`blur`,x)}},[m,d]);return(0,Z.useEffect)(()=>()=>{m(`unmount`)},[m]),{drag:n,ghostRef:u,onDragStart:h}}var Wc=e=>un(e)?.effect,Gc=[`hunger`,`happiness`,`hygiene`,`health`];function Kc(e){let t=0;for(let n of Gc){let r=e.stats[n]??100,{careState:i}=xn({stage:e.stage,stat:n,value:r});if(i===`urgent`)return!0;i===`attention`&&t++}return t>=2}function qc(){let{config:e}=Se(),{user:t}=G();return qe({hasSubHeader:!0,noOverscroll:!0}),it({title:`Blobbi | ${e.appName}`,description:`Care for your virtual pet companion on Nostr`}),t?(0,Q.jsx)(Yc,{}):(0,Q.jsx)(Jc,{})}function Jc(){return(0,Q.jsx)(`main`,{className:`flex flex-col items-center justify-center p-6 gap-6 min-h-[60vh]`,children:(0,Q.jsxs)(`div`,{className:`flex flex-col items-center gap-3 text-center max-w-sm`,children:[(0,Q.jsx)(`div`,{className:`size-20 rounded-3xl bg-primary/10 flex items-center justify-center`,children:(0,Q.jsx)(o,{className:`size-10 text-primary`})}),(0,Q.jsx)(`h1`,{className:`text-2xl font-bold`,children:`Blobbi`}),(0,Q.jsx)(`p`,{className:`text-muted-foreground`,children:`Log in with your Nostr account to care for your virtual pet companion.`}),(0,Q.jsx)(et,{className:`mt-2`})]})})}function Yc(){let{user:e}=G(),{nostr:t}=ve(),{mutateAsync:n,isPending:r}=ke(),{fetchFreshBlobbiBeforeAction:a}=kn(e?.pubkey),{profile:o,isLoading:s,invalidate:c,updateProfileEvent:l}=Pt();wr({profile:o,updateProfileEvent:l,invalidateProfile:c});let{companions:u,isLoading:d,isFetching:f,invalidate:p,updateCompanionEvent:m}=$t(void 0,e?.pubkey),h=!d&&!f&&u.length===0,{companions:g,isFetching:_}=Jr(e?.pubkey,h),v=(0,Z.useMemo)(()=>u.length>0?u:g,[u,g]),y=v,b=(0,Z.useMemo)(()=>{let e={};for(let t of y)e[t.d]=t;return e},[y]),[x,S]=xe(e?.pubkey?Mt(e.pubkey):`blobbi:selected:d:none`,null),[C,w]=(0,Z.useState)(!1),T=(0,Z.useMemo)(()=>{if(x&&b[x])return x;if(y.length>0)return y[0].d},[x,b,y]),E=T?b[T]??null:null;(0,Z.useEffect)(()=>{},[T,E]);let ee=f,te=p,[D,O]=(0,Z.useState)(null),k=(0,Z.useCallback)(e=>{S(e)},[S,x]),A=(0,Z.useCallback)(async()=>!E||!o?null:a({companion:E,profile:o,updateProfileEvent:l,updateCompanionEvent:m}),[E,o,a,l,m]),j=(0,Z.useCallback)(async()=>{if(!e?.pubkey||!E)return;let t=E.state===`sleeping`,r=t?`active`:`sleeping`;O(`rest`);try{let i=await A();if(!i){O(null);return}let a=Math.floor(Date.now()/1e3),o=rn({stage:i.companion.stage,state:i.companion.state,stats:i.companion.stats,lastDecayAt:i.companion.lastDecayAt,now:a}),s=Kt(i.companion)??{},c=X(i.allTags,{state:r,...at(o.stats,a),...s}),l=i.companion.event,u=await n({kind:Y,content:i.content,tags:c,prev:l});m(u),W({title:t?`Woke up!`:`Resting...`,description:t?`Your Blobbi is now awake and active!`:`Your Blobbi is taking a rest.`}),t||Xt(`sleep`,1,e?.pubkey)}catch(e){console.error(`Failed to update state:`,e),W({title:`Failed to update`,description:e instanceof Error?e.message:`Unknown error`,variant:`destructive`})}finally{O(null)}},[e?.pubkey,E,A,n,m]),{mutateAsync:M,isPending:N}=Nn({companion:E,profile:o,ensureCanonicalBeforeAction:A,updateCompanionEvent:m,updateProfileEvent:l}),ne=(0,Z.useCallback)(async(e,t)=>{await M({itemId:e,action:t})},[M]);gn((0,Z.useMemo)(()=>!E||!o?null:async(e,t)=>{try{return{success:!0,statsChanged:(await M({itemId:e,action:t}))?.statsChanged}}catch(e){return{success:!1,error:e instanceof Error?e.message:`Unknown error`}}},[M,E,o]),N);let{mutateAsync:P,isPending:re}=Va({companion:E,profile:o,ensureCanonicalBeforeAction:A,updateCompanionEvent:m}),F=(0,Z.useCallback)(async()=>{await P()},[P]),{mutateAsync:ie,isPending:I}=qa({companion:E,ensureCanonicalBeforeAction:A,updateCompanionEvent:m}),L=(0,Z.useCallback)(async e=>{await ie({action:e})},[ie]),{mutateAsync:ae,isPending:R}=$a({companion:E,updateCompanionEvent:m}),[oe,se]=(0,Z.useState)(!1),z=(0,Z.useCallback)(async e=>{await ae(e)},[ae]);(0,Z.useMemo)(()=>s?`loading-profile`:o?d?`loading-companions`:f&&v.length===0?`fetching-companions`:v.length===0?`no-pets`:T?E?`dashboard`:`companion-not-resolved`:`no-selection`:`no-profile`,[s,o,d,f,v.length,T,E]);let[ce,B]=(0,Z.useState)(!1),[le,V]=(0,Z.useState)(!1),ue=(0,Z.useRef)(null),de=!d&&(!f||u.length>0),fe=!h||!_||g.length>0,pe=de&&fe,me=!le;return(0,Z.useEffect)(()=>{if(!me||!pe||ce)return;V(!0);let r=Hr({companions:v,currentCompanionD:o?.currentCompanion});r.kind===`has-blobbi`?(o?.currentCompanion&&S(r.selected.d),o&&!o.onboardingDone&&e?.pubkey&&Ee(t,{kinds:[Ot],authors:[e.pubkey]}).then(e=>{if(!e)return;let t=ft(e.tags,{blobbi_onboarding_done:`true`});return n({kind:Ot,content:e.content,tags:t,prev:e})}).then(e=>{e&&(l(e),c())}).catch(e=>console.error(`[BlobbiPage] Failed to auto-fix onboardingDone:`,e))):(r.kind===`reuse-egg`&&(ue.current=r.egg),B(!0))},[me,pe,ce]),s&&!ce||me&&!pe&&!ce?(0,Q.jsx)(hl,{}):ce?(0,Hn.createPortal)((0,Q.jsx)(`div`,{className:`fixed inset-0 z-[100] bg-background`,children:(0,Q.jsx)(Qa,{profile:o??null,updateProfileEvent:l,updateCompanionEvent:m,invalidateProfile:c,invalidateCompanion:te,setStoredSelectedD:S,existingCompanion:ue.current,onExistingBlobbiFound:e=>{S(e.d),p(),B(!1)},onComplete:()=>B(!1)})}),document.body):!o||d?(0,Q.jsx)(hl,{}):(f||h&&_)&&v.length===0?(0,Q.jsx)(Xc,{children:(0,Q.jsx)(`div`,{className:`flex-1 flex flex-col items-center justify-center p-6 gap-6`,children:(0,Q.jsxs)(`div`,{className:`flex flex-col items-center gap-4 text-center max-w-sm`,children:[(0,Q.jsx)(`div`,{className:`size-24 rounded-3xl bg-muted/50 flex items-center justify-center`,children:(0,Q.jsx)(i,{className:`size-12 text-muted-foreground animate-spin`})}),(0,Q.jsx)(`h1`,{className:`text-2xl font-bold`,children:`Syncing your Blobbi...`}),(0,Q.jsx)(`p`,{className:`text-muted-foreground`,children:`Fetching your pet data from relays...`})]})})}):v.length===0?(0,Q.jsx)(Xc,{children:(0,Q.jsx)(`div`,{className:`flex-1 flex flex-col items-center justify-center p-6 gap-6`,children:(0,Q.jsxs)(`div`,{className:`flex flex-col items-center gap-4 text-center max-w-sm`,children:[(0,Q.jsx)(`div`,{className:`size-24 rounded-3xl bg-amber-500/10 flex items-center justify-center`,children:(0,Q.jsx)(i,{className:`size-12 text-amber-500`})}),(0,Q.jsx)(`h1`,{className:`text-2xl font-bold`,children:`Pet Data Not Found`}),(0,Q.jsx)(`p`,{className:`text-muted-foreground`,children:`No Blobbi data could be loaded from relays. This may be a sync issue - try refreshing the page.`}),(0,Q.jsxs)(q,{onClick:()=>{c(),te()},variant:`outline`,children:[(0,Q.jsx)(i,{className:`size-4 mr-2`}),`Retry`]})]})})}):!T||!E?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(ml,{companions:y,onSelect:k,isLoading:ee,onAdopt:()=>w(!0),currentCompanion:o?.currentCompanion}),(0,Q.jsx)(Ge,{open:C,onOpenChange:w,children:(0,Q.jsx)(We,{className:`max-w-lg max-h-[90vh] overflow-y-auto p-0`,children:(0,Q.jsx)(Qa,{profile:o,updateProfileEvent:l,updateCompanionEvent:m,invalidateProfile:c,invalidateCompanion:te,setStoredSelectedD:S,adoptionOnly:!0,userInitiated:!0,onComplete:()=>w(!1)})})})]}):(0,Q.jsx)(Zc,{companion:E,companions:y,selectedD:T,onSelectBlobbi:k,onRest:j,onUseItem:ne,onDirectAction:L,isUsingItem:N,isDirectActionPending:I,actionInProgress:D,isPublishing:r,profile:o,onEvolve:F,isHatching:!1,isEvolving:re,publishEvent:n,updateProfileEvent:l,updateCompanionEvent:m,invalidateProfile:c,invalidateCompanion:te,setStoredSelectedD:S,ensureCanonicalBeforeAction:A,showDevEditor:oe,setShowDevEditor:se,onDevEditorApply:z,isDevUpdating:R})}function Xc({children:e}){return(0,Q.jsx)(`main`,{className:K(`flex flex-col overflow-hidden bg-background`,`max-sidebar:fixed max-sidebar:inset-0 max-sidebar:top-mobile-bar max-sidebar:z-0`,`sidebar:h-dvh`),children:(0,Q.jsx)(`div`,{className:`mx-auto w-full max-w-2xl lg:max-w-3xl flex-1 min-h-0 flex flex-col`,children:e})})}function Zc({companion:e,companions:t,selectedD:n,onSelectBlobbi:r,onRest:i,onUseItem:s,onDirectAction:c,isUsingItem:l,isDirectActionPending:u,actionInProgress:f,isPublishing:p,profile:m,onEvolve:h,isHatching:g,isEvolving:_,publishEvent:v,updateProfileEvent:y,updateCompanionEvent:b,invalidateProfile:x,invalidateCompanion:S,setStoredSelectedD:C,ensureCanonicalBeforeAction:w,showDevEditor:T,setShowDevEditor:E,onDevEditorApply:ee,isDevUpdating:te}){let{user:D}=G(),{nostr:O}=ve(),j=e.state===`sleeping`,M=e.stage===`egg`,[N,ne]=(0,Z.useState)(`none`),[P,re]=xe(`blobbi:room:${D?.pubkey??`anon`}:${e.d}`,go(m?.room)?m.room:ho),F=j?`rest`:go(P)?P:ho,I=(0,Z.useRef)(null),{interactions:L,isLoading:ae}=Pn(M?null:e),{state:R,trigger:oe}=Xe();pr({companion:e,interactions:L,interactionsLoading:ae,updateCompanionEvent:b,ensureCanonicalBeforeAction:w,onSocialConsolidated:(0,Z.useCallback)(()=>{oe(`social_hearts`)},[oe]),publish:v,resolveCareItemEffect:Wc});let[se,z]=(0,Z.useState)(!1),ce=(0,Z.useCallback)(async t=>{if(e){z(!0);try{let e=await w();if(!e){z(!1);return}let n=X(e.allTags,{social:t?`open`:`closed`}),r=e.companion.event;b(await v({kind:Y,content:e.content,tags:n,prev:r})),W({title:t?`Social interactions enabled`:`Social interactions disabled`,description:t?`Other people can now care for this Blobbi.`:`Only you can interact with this Blobbi.`})}catch(e){console.error(`Failed to toggle social permission:`,e),W({title:`Failed to update`,description:`Could not change the social interaction setting. Please try again.`,variant:`destructive`})}finally{z(!1)}}},[e,w,v,b]),B=(0,Z.useMemo)(()=>Io(m?.content),[m?.content]),le=(0,Z.useMemo)(()=>xo(F,B),[F,B]),V=(0,Z.useMemo)(()=>Wo(m?.content),[m?.content]),ue=(0,Z.useMemo)(()=>is(F,V),[F,V]),[de,fe]=(0,Z.useState)(!1),[pe,me]=(0,Z.useState)(!1),[he,ge]=(0,Z.useState)(!1),[_e,be]=(0,Z.useState)(null),[H,U]=(0,Z.useState)(null),[Se,Ce]=(0,Z.useState)(!1),we=(0,Z.useRef)(null),Te=H!==null&&_e?_e[H]?.layer:void 0,Ee=(0,Z.useMemo)(()=>{if(H===null||!_e)return`bottom`;let e=_e[H];return e&&e.y>=.5?`top`:`bottom`},[H,_e]),De=(0,Z.useCallback)(()=>{me(!1),ne(`none`),be([...ue]),U(null),ge(!0)},[ue]),Oe=(0,Z.useCallback)(()=>{ge(!1),be(null),U(null)},[]),q=(0,Z.useCallback)(()=>{U(null)},[]),ke=(0,Z.useCallback)(async()=>{if(!(!D?.pubkey||!_e)){Ce(!0);try{let e=await On(O,D.pubkey);if(!e){W({title:`Error`,description:`Could not fetch profile. Try again.`});return}let t=e.event,n={v:1,by_room:{...Wo(t.content)?.by_room,[F]:_e}};y(await v({kind:Ot,content:Nt(t.content,{room_furniture:n}),tags:t.tags,prev:t})),W({title:`Saved`,description:`${po[F].label} furniture updated.`}),ge(!1),be(null),U(null)}catch{W({title:`Error`,description:`Failed to save furniture.`})}finally{Ce(!1)}}},[D?.pubkey,O,_e,F,v,y]),Ae=(0,Z.useCallback)((e,t,n)=>{be(r=>r&&r.map((r,i)=>i===e?{...r,x:t,y:n}:r))},[]),je=(0,Z.useCallback)(()=>{Oe(),me(!0)},[Oe]),Me=(0,Z.useCallback)(async(e,t)=>{if(D?.pubkey){fe(!0);try{let n=await On(O,D.pubkey);if(!n){W({title:`Error`,description:`Could not fetch profile. Try again.`});return}let r=n.event,i={v:1,by_room:{...Io(r.content)?.by_room,[e]:t}};y(await v({kind:Ot,content:Nt(r.content,{room_layouts:i}),tags:r.tags,prev:r})),W({title:`Saved`,description:`${po[e].label} style updated.`})}catch{W({title:`Error`,description:`Failed to save room style.`})}finally{fe(!1)}}},[D?.pubkey,O,v,y]),[J,Ne]=(0,Z.useState)(null),Pe=(0,Z.useCallback)(e=>{Ne(Fc(e,F))},[F]);(0,Z.useEffect)(()=>{if(!J)return;let e=F===J.targetRoom;J.step===`room`&&e?Ne(e=>e?{...e,step:e.targetType}:null):J.step!==`room`&&!e&&Ne(e=>e?{...e,step:`room`}:null)},[F,J]);let Fe=(0,Z.useMemo)(()=>!J||J.step!==`room`?null:Ic(F,J.targetRoom,mo),[J,F]),Ie=J?.step===`item`?J.targetItemId:null,Le=J?.step===`action`?J.targetAction:null,Re=(0,Z.useCallback)(e=>{ne(t=>t===e?`none`:e)},[]),ze=(0,Z.useMemo)(()=>ye.naddrEncode({kind:Y,pubkey:e.event.pubkey,identifier:e.d}),[e.event.pubkey,e.d]),Be=(0,Z.useMemo)(()=>{let e=new Set;for(let n of t)e.add(n.stage);return Array.from(e)},[t]),{companion:Ve}=Lt(),He=Ve?.d===e.d,Ue=pn(e);(0,Z.useEffect)(()=>{j&&J?.targetAction===`sleep`&&Ne(null)},[j,J]);let Ke=(0,Z.useRef)(null),[qe,Je]=(0,Z.useState)(!1),[Qe,et]=(0,Z.useState)(!1),[it,at]=(0,Z.useState)(!1);(0,Z.useEffect)(()=>{et(!1),at(!1)},[n]);let[ot,st]=(0,Z.useState)(!1),ct=nt(),[lt,ut]=(0,Z.useState)(null),[dt,pt]=(0,Z.useState)(null),mt=(0,Z.useMemo)(()=>({hunger:Ue?.stats.hunger??e.stats.hunger??100,happiness:Ue?.stats.happiness??e.stats.happiness??100,health:Ue?.stats.health??e.stats.health??100,hygiene:Ue?.stats.hygiene??e.stats.hygiene??100,energy:Ue?.stats.energy??e.stats.energy??100}),[Ue,e.stats]),ht=lt??R.emotionOverride??dt,{recipe:gt,recipeLabel:_t}=Zt({stats:mt,enabled:!M,actionOverride:j?null:ht}),vt=j?yn(gt):gt,yt=j?`sleeping`:_t,bt=tt()&&ct!==`neutral`,xt=bt?ct:`neutral`,[St,Ct]=(0,Z.useState)(!1),[wt,Tt]=(0,Z.useState)(null),[Et,Dt]=(0,Z.useState)(!1),[kt,At]=(0,Z.useState)(Xa()),[jt,Mt]=(0,Z.useState)(`idle`),Pt=e.progressionState===`incubating`,Ft=e.progressionState===`evolving`,It=e.stage===`baby`,Rt=M&&!Pt&&!Ft,zt=It&&!Ft&&!Pt,Bt=mr({pubkey:D?.pubkey,availableStages:Be,profileContent:m?.content}),Vt=xr(Pt?e:null,D?.pubkey),Ht=Cr(Ft?e:null,D?.pubkey),{mutateAsync:Ut,isPending:Wt}=Ha({companion:e,profile:m,ensureCanonicalBeforeAction:w,updateCompanionEvent:b}),{mutateAsync:Gt,isPending:Kt}=Ua({companion:e,ensureCanonicalBeforeAction:w,updateCompanionEvent:b}),{mutateAsync:qt,isPending:Jt}=Wa({companion:e,ensureCanonicalBeforeAction:w,updateCompanionEvent:b}),{mutateAsync:Yt,isPending:Xt}=Ga({companion:e,ensureCanonicalBeforeAction:w,updateCompanionEvent:b}),Qt=m?.currentCompanion===e.d,[$t,en]=(0,Z.useState)(!1),tn=e.stage===`egg`||e.stage===`baby`||e.stage===`adult`,rn=(0,Z.useCallback)(async()=>{if(m){if(!Qt&&!tn){W({title:`Cannot set as companion`,description:`Only hatched Blobbis (baby or adult) can be set as your companion.`,variant:`destructive`});return}en(!0);try{let t=await w();if(!t)return;let n;n=Qt?ft(t.profileAllTags,{}).filter(e=>e[0]!==`current_companion`):ft(t.profileAllTags.filter(e=>e[0]!==`current_companion`),{current_companion:e.d});let r=t.profileEvent;y(await v({kind:Ot,content:r.content,tags:n,prev:r})),x(),W({title:Qt?`Companion unset`:`Companion set!`,description:Qt?`${e.name} is no longer your companion`:`${e.name} is now your companion`})}catch(e){console.error(`Failed to update companion:`,e),W({title:`Failed to update companion`,description:e instanceof Error?e.message:`Unknown error`,variant:`destructive`})}finally{en(!1)}}},[m,Qt,tn,e.d,e.name,w,v,y,x]),an=async(e,t)=>{try{await Ut({mode:e,stopOtherD:t})}catch(e){console.error(`Failed to start incubation:`,e)}},on=async()=>{try{await qt()}catch(e){console.error(`Failed to start evolution:`,e)}},sn=async()=>{await Gt()},cn=async()=>{await Yt()},ln=e=>{e===`play_music`?Dt(!0):e===`sing`&&At(Ya())},mn=async e=>{if(Dt(!1),kt.type===`music`&&kt.isPublished)At(t=>t.type===`music`?{...t,selection:e}:t);else{At(Ja(e));try{await c(`play_music`),At(e=>e.type===`music`?{...e,isPublished:!0}:e)}catch{At(Xa())}}},hn=async()=>{await c(`sing`)},gn=()=>{At(Xa()),Mt(`idle`),pt(null)},_n=()=>{Mt(`listening`),pt(dn(`music`))},vn=()=>{Mt(`idle`),pt(null)},bn=()=>{Mt(`singing`),pt(dn(`sing`))},xn=()=>{Mt(`idle`),pt(null)},Cn=()=>{Dt(!0)};vr({pubkey:D?.pubkey,companionD:e.d,publish:v,updateCompanionEvent:b}),gr({pubkey:D?.pubkey,publish:v,updateProfileEvent:y});let{mutate:wn}=Za(y),Tn=(0,Z.useRef)(null);(0,Z.useEffect)(()=>{if(!Bt.allComplete||!Bt.raw)return;let e=Bt.raw.date;Tn.current!==e&&(Tn.current=e,wn({missions:Bt.raw}))},[Bt.allComplete,Bt.raw,wn]);let kn=(0,Z.useRef)(0),An=(0,Z.useRef)(null),jn=(0,Z.useCallback)(()=>{kn.current+=5,W({title:`+5 XP`,description:`Cleaned up!`}),An.current&&clearTimeout(An.current),An.current=setTimeout(async()=>{let e=kn.current;if(kn.current=0,!(e<=0))try{let t=await w();if(!t)return;let n=Dn(t.companion.experience??0,e),r=X(t.allTags,{experience:n.toString()});b(await v({kind:Y,content:t.content,tags:r,prev:t.companion.event}))}catch(e){console.error(`Failed to persist poop cleanup XP:`,e)}},1500)},[w,v,b]),Mn=(0,Z.useRef)(void 0),Nn=(0,Z.useRef)(J);Nn.current=J;let Fn=(0,Z.useCallback)(e=>{let t=En(e);if(!t||l)return;clearTimeout(Mn.current),Tt(e);let n=t===`clean`&&mt.hygiene<nn.warning,r=Ze[t]??`feed`;t!==`clean`&&oe(r),s(e,t).then(()=>{if(Nn.current?.targetItemId===e&&Ne(null),t===`clean`){let t=un(e)?.effect?.hygiene??0,r=mt.hygiene+t>=nn.warning;oe(n&&r?`clean_complete`:`clean`)}}).finally(()=>{Tt(null),Mn.current=setTimeout(()=>ut(null),1500)})},[l,s,mt.hygiene,oe]),[In,Ln]=(0,Z.useState)(null),Rn=(0,Z.useRef)(0),zn=(0,Z.useRef)(!0),Bn=(0,Z.useRef)(void 0),Vn=(0,Z.useRef)(void 0),Un=(0,Z.useRef)(void 0),Wn=(0,Z.useRef)(void 0),Gn=(0,Z.useCallback)(()=>{clearTimeout(Mn.current),Mn.current=void 0,clearTimeout(Bn.current),Bn.current=void 0,clearTimeout(Vn.current),Vn.current=void 0,clearTimeout(Un.current),Un.current=void 0,clearTimeout(Wn.current),Wn.current=void 0},[]);(0,Z.useEffect)(()=>()=>{zn.current=!1,Gn()},[Gn]);let Kn=(0,Z.useCallback)(e=>{ut(e?`eating`:null)},[]),qn=Uc((0,Z.useCallback)(t=>{let n=En(t);if(!n||l)return;Gn();let r=++Rn.current,i=()=>zn.current&&r===Rn.current;tl(n,e.stats.hunger??0,I.current),Tt(t),ut(`chewing`),fo();let a=document.querySelector(`[data-blobbi-visual]`);a&&requestAnimationFrame(()=>{if(!i())return;let e=a.getBoundingClientRect(),t=a.querySelector(`[data-blobbi-mouth]`),n,r;if(t){let e=t.getBoundingClientRect();n=e.left+e.width/2,r=e.top+e.height/2+4}else n=e.left+e.width*.5,r=e.top+e.height*.67+4;Ln({crumbX:n,crumbY:r,rewardX:e.left+e.width*.5,rewardY:e.top+e.height*.08}),Un.current=setTimeout(()=>{i()&&Ln(null)},1200)});let o=`pending`,c=!1,u=()=>{!c||o===`pending`||i()&&(clearTimeout(Wn.current),Wn.current=void 0,o===`ok`?(ut(`happy`),Vn.current=setTimeout(()=>{i()&&ut(null)},1500)):ut(null))};s(t,n).then(()=>{o=`ok`,i()&&J?.targetItemId===t&&Ne(null)},()=>{o=`failed`}).finally(()=>{i()&&Tt(null),u()}),Bn.current=setTimeout(()=>{c=!0,u()},1200),Wn.current=setTimeout(()=>{i()&&(ut(null),Tt(null))},5e3)},[l,s,J,Gn,e.stats.hunger,I]),Kn),[Jn,Yn]=(0,Z.useState)(!1);(0,Z.useEffect)(()=>{F!==`kitchen`&&Yn(!1)},[F]);let Xn=p||f!==null||l,Zn=(0,Z.useMemo)(()=>fn().filter(e=>e.type===`food`).map(t=>({...t,statChanges:Sn(mt,t.effect,e.stage)})),[mt,e.stage]),Qn=(0,Z.useCallback)(t=>{let n=En(t),r=e.stats.hunger??0;Fn(t),n===`feed`&&r>=95&&Math.random()<.4&&I.current?.addPoop(`overfeed`)},[e.stats.hunger,Fn]),$n=(0,Z.useRef)(null);return(0,Q.jsxs)(Xc,{children:[N!==`none`&&(0,Q.jsx)(`div`,{className:`fixed inset-0 z-[60]`,onClick:()=>ne(`none`)}),(0,Q.jsxs)(`div`,{className:K(`absolute top-0 left-0 right-0 z-[70] transition-opacity duration-200`,he&&`opacity-40 pointer-events-none`),children:[(0,Q.jsx)(`div`,{className:`bg-background/90 backdrop-blur-sm overflow-hidden transition-[max-height] duration-250 ease-in-out`,style:{maxHeight:N===`none`?`0`:`256px`},children:(0,Q.jsx)($e,{style:{height:248},children:(0,Q.jsxs)(`div`,{className:`max-w-2xl mx-auto w-full pb-4 pt-2`,children:[N===`missions`&&(0,Q.jsx)(ol,{isIncubating:Pt,isEvolvingState:Ft,isEgg:M,isBaby:It,hatchTasks:Vt,evolveTasks:Ht,onHatch:async()=>et(!0),isHatching:g||Qe,onEvolve:async()=>at(!0),isEvolving:_||it,onStopIncubation:sn,isStoppingIncubation:Kt,onStopEvolution:cn,isStoppingEvolution:Xt,dailyMissions:Bt,canStartIncubation:Rt,canStartEvolution:zt,isStartingIncubation:Wt,isStartingEvolution:Jt,onStartIncubation:()=>an(`start`),onStartEvolution:on}),N===`activity`&&(0,Q.jsx)(fl,{companion:e,projectedStats:mt,socialOpen:e.socialOpen,onToggleSocial:ce,isSocialToggling:se,isEgg:M}),N===`more`&&(0,Q.jsx)(ll,{companion:e,companions:t,selectedD:n,profile:m,blobbiNaddr:ze,onSelectBlobbi:r,onAdopt:()=>Ct(!0),onDevOpenEditor:()=>E(!0),onDevOpenEmotionPanel:()=>st(!0),onDevInstantTransition:M?()=>et(!0):It?()=>at(!0):void 0,isHatching:g,isEvolving:_})]})})}),(0,Q.jsxs)(Ye,{className:`relative !top-0`,innerClassName:`md:min-h-0 min-h-[50px]`,children:[(0,Q.jsx)(rt,{label:`Quests`,active:N===`missions`,onClick:()=>Re(`missions`),className:`translate-y-0`,children:(0,Q.jsxs)(`span`,{className:`flex items-center gap-1.5`,children:[(0,Q.jsx)(a,{className:`size-4`}),(0,Q.jsx)(`span`,{className:`text-sm`,children:`Quests`})]})}),(0,Q.jsx)(rt,{label:`Activity`,active:N===`activity`,onClick:()=>Re(`activity`),className:`translate-y-2`,children:(0,Q.jsxs)(`span`,{className:`flex items-center gap-1.5`,children:[(0,Q.jsx)(d,{className:`size-4`}),(0,Q.jsx)(`span`,{className:`text-sm`,children:`Activity`})]})}),(0,Q.jsx)(rt,{label:`Blobbis`,active:N===`more`,onClick:()=>Re(`more`),className:`translate-y-0`,children:(0,Q.jsxs)(`span`,{className:`flex items-center gap-1.5`,children:[(0,Q.jsx)(o,{className:`size-4`}),(0,Q.jsx)(`span`,{className:`text-sm`,children:`Blobbis`})]})})]})]}),(0,Q.jsx)(vc,{roomId:F,onChangeRoom:t=>{if(j){W({title:`Zzz...`,description:`${e.name} is sleeping. Wake up first!`});return}re(t)},isSleeping:j,hunger:mt.hunger,lastFeedTimestamp:e.lastInteraction?e.lastInteraction*1e3:void 0,poopStateRef:I,onPoopCleaned:jn,guideRoomDirection:Fe,hudVisible:N===`none`,roomLayout:le,furniturePlacements:_e??ue,containerRef:we,isFurnitureEditing:he,furnitureSelectedIndex:H,onFurnitureSelect:U,onFurnitureMove:Ae,furnitureActiveLayer:Te,onFurnitureBackgroundClick:q,editorSlot:(0,Q.jsx)(Ss,{onClick:je}),editorSlotLeft:(0,Q.jsx)(sc,{onClick:De}),editorOverlay:pe?(0,Q.jsx)(ws,{roomId:F,currentLayout:le,onSave:Me,onClose:()=>me(!1),isSaving:de}):he?(0,Q.jsx)(cc,{roomId:F,draft:_e??[],onDraftChange:be,selectedIndex:H,onSelectItem:U,onClose:Oe,onSave:ke,isSaving:Se,placement:Ee}):void 0,shovelDragRef:$n,roomOverlay:Jn?(0,Q.jsx)(`div`,{className:`absolute inset-0 flex flex-col items-center justify-center bg-background/95 backdrop-blur-md animate-in fade-in duration-200`,onClick:()=>Yn(!1),children:(0,Q.jsxs)(`div`,{className:`w-full max-w-md px-4`,onClick:e=>e.stopPropagation(),children:[(0,Q.jsxs)(`div`,{className:`relative flex items-center justify-center mb-4`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Q.jsx)(ie,{className:`size-5 text-orange-500`}),(0,Q.jsx)(`h3`,{className:`text-sm font-semibold`,children:`Fridge`})]}),(0,Q.jsx)(`button`,{onClick:e=>{e.stopPropagation(),Yn(!1)},className:`absolute right-0 size-8 rounded-full flex items-center justify-center text-muted-foreground hover:text-foreground transition-colors`,"aria-label":`Close fridge`,children:(0,Q.jsx)(A,{className:`size-5`,strokeWidth:4})})]}),(0,Q.jsx)(`div`,{className:`flex flex-wrap justify-center gap-1`,children:Zn.map(e=>{let t=l&&wt===e.id;return(0,Q.jsxs)(`button`,{onClick:()=>Qn(e.id),disabled:Xn,className:K(`relative flex flex-col items-center gap-1.5 p-3 rounded-2xl transition-all duration-200`,`hover:bg-foreground/5 active:scale-95`,t&&`bg-foreground/5`,Xn&&!t&&`opacity-40`),children:[(0,Q.jsx)(`span`,{className:`text-4xl leading-none`,children:e.icon}),(0,Q.jsx)(`span`,{className:`text-[11px] font-medium text-foreground/80`,children:e.name}),(0,Q.jsx)(`div`,{className:`grid grid-cols-2 gap-x-2 gap-y-0.5`,children:e.statChanges.map(e=>{let t=el[e.stat],n=e.delta>0,r=e.segmentDelta;return(0,Q.jsxs)(`span`,{className:`flex items-center gap-0.5`,children:[t&&(0,Q.jsx)(t,{className:`size-3.5 text-muted-foreground/60`}),(0,Q.jsxs)(`span`,{className:K(`text-[11px] font-semibold tabular-nums`,n?`text-emerald-600 dark:text-emerald-400`:`text-red-600 dark:text-red-400`),children:[n?`+`:``,e.delta]}),r!==0&&(0,Q.jsxs)(`span`,{className:`text-[9px] text-muted-foreground/70 tabular-nums`,children:[r>0?`+`:``,r,`▮`]})]},e.stat)})}),t&&(0,Q.jsx)(k,{className:`size-3.5 animate-spin text-primary absolute top-2 right-2`})]},e.id)})})]})}):void 0,hero:(0,Q.jsx)(uc,{companion:e,isActiveFloatingCompanion:He,isUpdatingCompanion:$t,handleSetAsCompanion:rn}),stageOverlay:He?void 0:(0,Q.jsx)(bc,{companion:e,currentStats:mt,isSleeping:j,isEgg:M,statusRecipe:vt,statusRecipeLabel:yt,effectiveEmotion:xt,hasDevOverride:bt,blobbiReaction:jt,interactionReaction:M?void 0:R,stageRef:Ke}),statusHud:He?void 0:(0,Q.jsx)(Dc,{companion:e,currentStats:mt,onGuide:Pe}),middleSlot:(0,Q.jsxs)(Q.Fragment,{children:[kt.type===`music`&&(0,Q.jsx)(`div`,{className:`px-4 sm:px-6 pb-2`,children:(0,Q.jsx)(Fa,{selection:kt.selection,onChangeTrack:Cn,onClose:gn,onPlaybackStart:_n,onPlaybackStop:vn,isPublished:kt.isPublished,isPublishing:u})}),kt.type===`sing`&&(0,Q.jsx)(`div`,{className:`px-4 sm:px-6 pb-2`,children:(0,Q.jsx)(Ba,{onConfirm:hn,onClose:gn,onRecordingStart:bn,onRecordingStop:xn,isPublishing:u})})]}),children:!He&&(0,Q.jsx)(Qc,{room:F,companion:e,currentStats:mt,profile:m,isEgg:M,isSleeping:j,isUsingItem:l,usingItemId:wt,isPublishing:p,actionInProgress:f,isDirectActionPending:u,isCurrentCompanion:Qt,canBeCompanion:tn,isUpdatingCompanion:$t,handleSetAsCompanion:rn,handleUseItemFromTab:Fn,handleDirectAction:ln,onUseItem:s,onRest:i,setShowPhotoModal:Je,poopStateRef:I,guideHighlightId:Ie,guideActionGlow:Le,foodDragHook:qn,carouselKeyPrefix:`blobbi:carousel:${D?.pubkey??`anon`}:${e.d}`,setShowFridge:Yn,foodItems:Zn,handleFeedItem:Qn,shovelDragRef:$n})}),qn.drag&&(0,Q.jsx)(`div`,{ref:qn.ghostRef,className:`fixed pointer-events-none z-[60]`,style:{left:qn.drag.startX,top:qn.drag.startY,transform:`translate(-50%, -50%)`},children:(0,Q.jsx)(`span`,{className:`text-4xl sm:text-5xl drop-shadow-lg transition-transform duration-150`,children:qn.drag.emoji})}),In&&(0,Q.jsx)(vl,{crumbX:In.crumbX,crumbY:In.crumbY,rewardX:In.rewardX,rewardY:In.rewardY},Rn.current),(0,Q.jsx)(Aa,{open:Et,onOpenChange:Dt,onConfirm:mn,isLoading:u}),(0,Q.jsx)(Ea,{open:qe,onOpenChange:Je,companion:e}),Qe&&(0,Hn.createPortal)((0,Q.jsx)(`div`,{className:`fixed inset-0 z-[100] bg-background`,children:(0,Q.jsx)(Br,{profile:m,updateProfileEvent:y,updateCompanionEvent:b,invalidateProfile:x,invalidateCompanion:S,setStoredSelectedD:C,existingCompanion:e,onComplete:()=>et(!1)})}),document.body),it&&(0,Hn.createPortal)((0,Q.jsx)(`div`,{className:`fixed inset-0 z-[100] bg-background`,children:(0,Q.jsx)(Yr,{companion:e,onEvolve:h,onComplete:()=>at(!1)})}),document.body),(0,Q.jsx)(Ge,{open:St,onOpenChange:Ct,children:(0,Q.jsx)(We,{className:`max-w-lg max-h-[90vh] overflow-y-auto p-0`,children:(0,Q.jsx)(Qa,{profile:m,updateProfileEvent:y,updateCompanionEvent:b,invalidateProfile:x,invalidateCompanion:S,setStoredSelectedD:C,adoptionOnly:!0,userInitiated:!0,onComplete:()=>Ct(!1)})})}),!1,!1]})}function Qc(e){switch(e.room){case`home`:return(0,Q.jsx)($c,{...e});case`kitchen`:return(0,Q.jsx)(nl,{...e});case`care`:return(0,Q.jsx)(rl,{...e});case`rest`:return(0,Q.jsx)(il,{...e});case`closet`:return(0,Q.jsx)(al,{})}}function $c({isUsingItem:e,usingItemId:t,isPublishing:n,actionInProgress:r,isCurrentCompanion:i,canBeCompanion:a,isUpdatingCompanion:o,handleSetAsCompanion:s,handleUseItemFromTab:c,handleDirectAction:l,setShowPhotoModal:u,guideHighlightId:d,carouselKeyPrefix:f}){let{user:p}=G(),[m,h]=xe(`${f}:home`,null),g=(0,Z.useCallback)(e=>h(e.id),[h]),_=(0,Z.useMemo)(()=>[...fn().filter(e=>e.type===`toy`).map(e=>({id:e.id,icon:(0,Q.jsx)(`span`,{children:e.icon}),label:e.name})),{id:`__action_music`,icon:(0,Q.jsx)(`div`,{className:`size-10 sm:size-12 rounded-full flex items-center justify-center bg-pink-500/15 text-pink-500`,children:(0,Q.jsx)(D,{className:`size-5 sm:size-6`})}),label:`Music`},{id:`__action_sing`,icon:(0,Q.jsx)(`div`,{className:`size-10 sm:size-12 rounded-full flex items-center justify-center bg-purple-500/15 text-purple-500`,children:(0,Q.jsx)(j,{className:`size-5 sm:size-6`})}),label:`Sing`}],[]),v=n||r!==null||e,y=(0,Z.useCallback)(e=>{e===`__action_music`?l(`play_music`):e===`__action_sing`?l(`sing`):c(e)},[l,c]);return(0,Q.jsx)(Q.Fragment,{children:(0,Q.jsx)(`div`,{className:Fn,children:(0,Q.jsxs)(`div`,{className:`flex items-center justify-between gap-1 sm:gap-3`,children:[(0,Q.jsx)(Rs,{icon:(0,Q.jsx)(se,{className:`size-7 sm:size-9`}),label:`Photo`,color:`text-pink-500`,glowHex:`#ec4899`,onClick:()=>{u(!0),Xt(`take_photo`,1,p?.pubkey)}}),(0,Q.jsx)(`div`,{className:`flex-1 min-w-0 flex justify-center`,children:(0,Q.jsx)(Ln,{items:_,onUse:y,activeItemId:e?t:null,disabled:v,highlightId:d,initialItemId:m??void 0,onFocusChange:g})}),a?(0,Q.jsx)(Rs,{icon:(0,Q.jsx)(R,{className:`size-7 sm:size-9`}),label:i?`With you`:`Take along`,color:i?`text-emerald-500`:`text-violet-500`,glowHex:i?`#10b981`:`#8b5cf6`,onClick:s,disabled:o,loading:o}):(0,Q.jsx)(`div`,{className:`w-14 sm:w-20 shrink-0`})]})})})}var el={hunger:pe,happiness:re,health:l,hygiene:r,energy:B};function tl(e,t,n){e===`feed`&&t>=95&&Math.random()<.4&&n?.addPoop(`overfeed`)}function nl({companion:e,currentStats:t,isUsingItem:n,usingItemId:r,isPublishing:i,actionInProgress:a,handleUseItemFromTab:o,poopStateRef:s,guideHighlightId:c,guideActionGlow:l,foodDragHook:u,carouselKeyPrefix:d,setShowFridge:f,foodItems:p,handleFeedItem:m,shovelDragRef:h}){let[g,_]=xe(`${d}:kitchen`,null),v=(0,Z.useCallback)(e=>_(e.id),[_]),y=h?.current,b=(0,Z.useMemo)(()=>fn().filter(e=>e.id===`nrg_drink`).map(n=>({...n,statChanges:Sn(t,n.effect,e.stage)})),[t,e.stage]),x=(0,Z.useMemo)(()=>[...p??[],...b],[p,b]),S=(0,Z.useMemo)(()=>x.map(e=>({id:e.id,icon:(0,Q.jsx)(`span`,{children:e.icon}),label:e.name})),[x]),C=(0,Z.useMemo)(()=>new Set((p??[]).map(e=>e.id)),[p]),w=(0,Z.useMemo)(()=>new Set(x.map(e=>e.id)),[x]),T=i||a!==null||n,E=(0,Z.useCallback)(t=>{C.has(t)&&tl(En(t),e.stats.hunger??0,s.current),o(t)},[e.stats.hunger,o,C,s]),ee=(0,Z.useMemo)(()=>{if(!u||S.length===0||T)return;let{onDragStart:e}=u;return{onPointerDown:(t,n)=>{if(!w.has(n.id))return;let r=x.find(e=>e.id===n.id);e(t,n.id,r?.icon??`🍽`)}}},[u,S.length,x,w,T]);return(0,Q.jsx)(`div`,{className:Fn,children:(0,Q.jsxs)(`div`,{className:`flex items-center justify-between gap-1 sm:gap-3`,children:[y&&(0,Q.jsx)(mc,{drag:y,guideActionGlow:l}),(0,Q.jsx)(`div`,{className:`flex-1 min-w-0 flex justify-center`,children:(0,Q.jsx)(Ln,{items:S,onUse:E,activeItemId:n?r:null,centerPointerHandlers:ee,disabled:T,highlightId:c,initialItemId:g??void 0,onFocusChange:v})}),(0,Q.jsx)(Rs,{icon:(0,Q.jsx)(ie,{className:`size-7 sm:size-9`}),label:`Fridge`,color:`text-orange-500`,glowHex:`#f97316`,onClick:()=>f?.(!0),disabled:T})]})})}function rl({isUsingItem:e,usingItemId:t,isPublishing:n,actionInProgress:r,handleUseItemFromTab:i,guideHighlightId:a,carouselKeyPrefix:o}){let s=(0,Z.useMemo)(()=>fn(),[]),c=(0,Z.useMemo)(()=>s.filter(e=>e.type===`hygiene`),[s]),l=(0,Z.useMemo)(()=>s.find(e=>e.type===`food`),[s]),u=(0,Z.useMemo)(()=>{let e=c.filter(e=>e.id!==`hyg_towel`).map(e=>({id:e.id,icon:(0,Q.jsx)(`span`,{children:e.icon}),label:e.name,meta:`hygiene`})),t=s.filter(e=>e.type===`medicine`).map(e=>({id:e.id,icon:(0,Q.jsx)(`span`,{children:e.icon}),label:e.name,meta:`medicine`}));return[...e,...t]},[c,s]),[d,f]=xe(`${o}:care`,null),[p,h]=(0,Z.useState)(()=>{if(d){let e=u.find(e=>e.id===d);if(e)return e.meta??`hygiene`}return u[0]?.meta??`hygiene`});(0,Z.useEffect)(()=>{if(!d)return;let e=u.find(e=>e.id===d);e&&h(e.meta??`hygiene`)},[d,u]);let g=(0,Z.useCallback)(e=>{h(e.meta??`hygiene`),f(e.id)},[f]),_=p===`hygiene`,v=n||r!==null||e,y=c.find(e=>e.id===`hyg_towel`);return(0,Q.jsx)(Q.Fragment,{children:(0,Q.jsx)(`div`,{className:Fn,children:(0,Q.jsxs)(`div`,{className:`flex items-center justify-between gap-1 sm:gap-3`,children:[_?y?(0,Q.jsx)(Rs,{icon:(0,Q.jsx)(m,{className:`size-7 sm:size-9`}),label:`Towel`,color:`text-cyan-500`,glowHex:`#06b6d4`,onClick:()=>i(y.id),disabled:v,loading:e&&t===y.id}):(0,Q.jsx)(`div`,{className:`w-14 sm:w-20 shrink-0`}):l?(0,Q.jsx)(Rs,{icon:(0,Q.jsx)(N,{className:`size-7 sm:size-9`}),label:l.name,color:`text-pink-400`,glowHex:`#f472b6`,onClick:()=>i(l.id),disabled:v}):(0,Q.jsx)(`div`,{className:`w-14 sm:w-20 shrink-0`}),(0,Q.jsx)(`div`,{className:`flex-1 min-w-0 flex justify-center`,children:(0,Q.jsx)(Ln,{items:u,onUse:i,activeItemId:e?t:null,disabled:v,onFocusChange:g,highlightId:a,initialItemId:d??void 0})}),_?(0,Q.jsx)(Rs,{icon:(0,Q.jsx)(oe,{className:`size-7 sm:size-9`}),label:`Shower`,color:`text-blue-500`,glowHex:`#3b82f6`,onClick:()=>{let e=c.find(e=>e.id===`hyg_shampoo`);e&&i(e.id)},disabled:v}):(0,Q.jsx)(`div`,{className:`w-14 sm:w-20 shrink-0`})]})})})}function il({isEgg:e,isSleeping:n,onRest:r,isPublishing:i,actionInProgress:a,isUsingItem:o,guideActionGlow:s}){return(0,Q.jsx)(Q.Fragment,{children:(0,Q.jsx)(`div`,{className:Fn,children:(0,Q.jsxs)(`div`,{className:`flex items-center justify-between gap-1 sm:gap-3`,children:[(0,Q.jsx)(`div`,{className:`size-14 sm:size-16`}),e?null:(0,Q.jsx)(Rs,{icon:a===`rest`?(0,Q.jsx)(k,{className:`size-7 sm:size-9 animate-spin`}):n?(0,Q.jsx)(E,{className:`size-7 sm:size-9`}):(0,Q.jsx)(t,{className:`size-7 sm:size-9`}),label:n?`Wake up`:`Sleep`,color:n?`text-amber-500`:`text-violet-500`,glowHex:n?`#f59e0b`:`#8b5cf6`,onClick:r,disabled:i||a!==null||o,glow:s===`sleep`}),(0,Q.jsx)(`div`,{className:`size-14 sm:size-16`})]})})})}function al(){return(0,Q.jsx)(`div`,{className:Fn,children:(0,Q.jsx)(`div`,{className:`flex items-center justify-center gap-2 py-1`,children:(0,Q.jsx)(`p`,{className:`text-xs text-muted-foreground/40 font-medium`,children:`Closet coming soon`})})})}function ol({isIncubating:e,isEvolvingState:t,isEgg:n,isBaby:r,hatchTasks:i,evolveTasks:s,onHatch:c,isHatching:l,onEvolve:u,isEvolving:d,onStopIncubation:f,isStoppingIncubation:p,onStopEvolution:m,isStoppingEvolution:h,dailyMissions:g,canStartIncubation:_,canStartEvolution:v,isStartingIncubation:y,isStartingEvolution:x,onStartIncubation:S,onStartEvolution:C}){let[w,T]=(0,Z.useState)(`journey`),E=e&&n||t&&r,ee=l||d||p||h,te=e?i.tasks:s.tasks,D=e?i.allCompleted:s.allCompleted,O=e?i.isLoading:s.isLoading,A=Ae(),j=te.filter(e=>e.completed).length,M=te.length,{missions:N}=g,ne=N.filter(e=>e.complete).length,P=N.length;return(0,Q.jsxs)(`div`,{className:`flex flex-col h-full px-3 sm:px-4`,children:[(0,Q.jsx)(`div`,{className:`flex justify-center py-2`,children:(0,Q.jsxs)(`div`,{className:`inline-flex rounded-full bg-muted/50 p-1 gap-0.5`,children:[(0,Q.jsxs)(`button`,{onClick:()=>T(`journey`),className:K(`flex items-center gap-1.5 px-4 py-1.5 rounded-full text-xs font-semibold transition-all duration-200`,w===`journey`?`bg-background shadow-sm text-foreground`:`text-muted-foreground hover:text-foreground`),children:[(0,Q.jsx)(o,{className:`size-3.5`}),`Journey`,E&&(0,Q.jsxs)(`span`,{className:`text-[10px] tabular-nums text-muted-foreground`,children:[j,`/`,M]})]}),(0,Q.jsxs)(`button`,{onClick:()=>T(`bounties`),className:K(`flex items-center gap-1.5 px-4 py-1.5 rounded-full text-xs font-semibold transition-all duration-200`,w===`bounties`?`bg-background shadow-sm text-foreground`:`text-muted-foreground hover:text-foreground`),children:[(0,Q.jsx)(a,{className:`size-3.5`}),`Bounties`,P>0&&(0,Q.jsxs)(`span`,{className:`text-[10px] tabular-nums text-muted-foreground`,children:[ne,`/`,P]})]})]})}),(0,Q.jsxs)(`div`,{className:`flex-1 min-h-0 overflow-y-auto space-y-1`,children:[w===`journey`&&(0,Q.jsxs)(Q.Fragment,{children:[O&&(0,Q.jsx)(`div`,{className:`flex items-center justify-center py-8`,children:(0,Q.jsx)(k,{className:`size-5 animate-spin text-muted-foreground`})}),E&&!O&&te.map(e=>{let t=()=>{if(!(!e.action||!e.actionTarget))switch(e.action){case`navigate`:A(e.actionTarget);break;case`external_link`:Te(e.actionTarget);break}},n=!e.completed&&!!e.action&&!!e.actionTarget;return(0,Q.jsxs)(`button`,{onClick:n?t:void 0,disabled:!n,className:K(`w-full flex items-center gap-3 px-3 py-2.5 rounded-2xl transition-all text-left`,n&&`hover:bg-accent/50 active:scale-[0.98] cursor-pointer`,!n&&`cursor-default`),children:[(0,Q.jsx)(sl,{taskId:e.id,completed:e.completed}),(0,Q.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,Q.jsx)(`p`,{className:K(`text-sm font-medium leading-tight`,e.completed&&`text-muted-foreground line-through`),children:e.name}),(0,Q.jsx)(`p`,{className:`text-[10px] text-muted-foreground leading-snug mt-0.5 line-clamp-1`,children:e.description})]}),e.required>1&&!e.completed&&(0,Q.jsxs)(`span`,{className:`text-[10px] tabular-nums font-medium text-muted-foreground shrink-0`,children:[e.current,`/`,e.required]})]},e.id)}),E&&D&&!O&&(0,Q.jsxs)(`button`,{onClick:e?c:u,disabled:ee,className:K(`w-full flex items-center justify-center gap-2 px-6 py-3 mt-1 rounded-full text-white font-semibold transition-all duration-300`,`hover:-translate-y-0.5 hover:scale-105 hover:brightness-110 active:scale-95`,ee&&`opacity-50 pointer-events-none`),style:{background:e?`linear-gradient(135deg, #0ea5e9, #8b5cf6)`:`linear-gradient(135deg, #8b5cf6, #ec4899)`},children:[l||d?(0,Q.jsx)(k,{className:`size-5 animate-spin`}):(0,Q.jsx)(`span`,{className:`text-lg`,children:e?`🐣`:`✨`}),(0,Q.jsx)(`span`,{children:l||d?e?`Hatching...`:`Evolving...`:e?`Hatch!`:`Evolve!`})]}),E&&!O&&(0,Q.jsx)(`button`,{onClick:e?f:m,disabled:ee,className:`w-full text-center text-[11px] text-muted-foreground/40 hover:text-destructive/60 transition-colors pt-1`,children:p||h?`Stopping...`:`Stop ${e?`incubation`:`evolution`}`}),!E&&!O&&(0,Q.jsx)(`div`,{className:`flex flex-col items-center gap-3 py-4`,children:_||v?(0,Q.jsxs)(`button`,{onClick:_?S:C,disabled:y||x,className:K(`flex items-center justify-center gap-2 px-8 py-3 rounded-full text-white font-semibold transition-all duration-300`,`hover:-translate-y-0.5 hover:scale-105 hover:brightness-110 active:scale-95`,(y||x)&&`opacity-50 pointer-events-none`),style:{background:_?`linear-gradient(135deg, #0ea5e9, #8b5cf6)`:`linear-gradient(135deg, #8b5cf6, #ec4899)`},children:[y||x?(0,Q.jsx)(k,{className:`size-5 animate-spin`}):(0,Q.jsx)(b,{className:`size-5`}),(0,Q.jsx)(`span`,{children:_?`Begin Hatching`:`Begin Evolution`})]}):(0,Q.jsx)(`p`,{className:`text-xs text-muted-foreground/50`,children:`No journey available right now`})})]}),w===`bounties`&&(0,Q.jsxs)(Q.Fragment,{children:[g.isLoading&&(0,Q.jsx)(`div`,{className:`flex flex-col items-center gap-2 py-6 text-center`,children:(0,Q.jsx)(`p`,{className:`text-xs text-muted-foreground/50`,children:`Loading daily bounties...`})}),!g.isLoading&&g.noMissionsAvailable&&(0,Q.jsxs)(`div`,{className:`flex flex-col items-center gap-2 py-6 text-center`,children:[(0,Q.jsx)(o,{className:`size-6 text-muted-foreground/30`}),(0,Q.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Hatch your Blobbi to unlock daily bounties`})]}),!g.noMissionsAvailable&&!g.isLoading&&N.map(e=>(0,Q.jsxs)(`div`,{className:K(`w-full flex items-center gap-3 px-3 py-2.5 rounded-2xl transition-all`,e.complete&&`bg-emerald-500/[0.06]`),children:[(0,Q.jsx)(cl,{action:e.action,complete:e.complete}),(0,Q.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,Q.jsx)(`p`,{className:K(`text-sm font-medium leading-tight`,e.complete&&`text-muted-foreground`),children:e.title}),(0,Q.jsx)(`p`,{className:`text-[10px] text-muted-foreground leading-snug mt-0.5`,children:e.description})]}),!e.complete&&(0,Q.jsxs)(`span`,{className:`text-[10px] tabular-nums font-medium text-muted-foreground shrink-0`,children:[e.progress,`/`,e.target]}),e.complete&&(0,Q.jsxs)(`span`,{className:`text-[10px] font-medium text-emerald-600 dark:text-emerald-400 shrink-0`,children:[`+`,e.xp,` XP`]})]},e.id)),!g.noMissionsAvailable&&!g.isLoading&&g.bonusUnlocked&&(0,Q.jsxs)(`div`,{className:`w-full flex items-center gap-3 px-3 py-2.5 rounded-2xl bg-violet-500/[0.06]`,children:[(0,Q.jsx)(`div`,{className:`size-8 rounded-full bg-violet-500/15 flex items-center justify-center shrink-0`,children:(0,Q.jsx)(b,{className:`size-4 text-violet-500`})}),(0,Q.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,Q.jsx)(`p`,{className:`text-sm font-medium leading-tight`,children:`Daily Champion`}),(0,Q.jsx)(`p`,{className:`text-[10px] text-muted-foreground`,children:`All missions complete!`})]}),(0,Q.jsxs)(`span`,{className:`text-[10px] font-medium text-violet-600 dark:text-violet-400 shrink-0`,children:[`+`,g.bonusXp,` XP`]})]}),!g.noMissionsAvailable&&!g.isLoading&&ne===P&&P>0&&g.allComplete&&(0,Q.jsxs)(`div`,{className:`flex flex-col items-center gap-1 py-4 text-center`,children:[(0,Q.jsx)(b,{className:`size-5 text-primary/40`}),(0,Q.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`All done for today — come back tomorrow!`})]})]})]})]})}function sl({taskId:e,completed:t}){let n=`size-4`,i=(()=>{switch(e){case`create_themes`:return(0,Q.jsx)(b,{className:n});case`color_moments`:return(0,Q.jsx)(r,{className:n});case`create_posts`:return(0,Q.jsx)(a,{className:n});case`interactions`:return(0,Q.jsx)(l,{className:n});case`edit_profile`:return(0,Q.jsx)(L,{className:n});case`maintain_stats`:return(0,Q.jsx)(B,{className:n});default:return(0,Q.jsx)(a,{className:n})}})();return(0,Q.jsx)(`div`,{className:K(`size-8 rounded-full flex items-center justify-center shrink-0`,t?`bg-emerald-500/15 text-emerald-500`:`bg-muted/60 text-muted-foreground`),children:t?(0,Q.jsx)(I,{className:`size-4`}):i})}function cl({action:e,complete:n}){let i=`size-4`,o=(()=>{switch(e){case`interact`:return(0,Q.jsx)(l,{className:i});case`feed`:return(0,Q.jsx)(pe,{className:i});case`clean`:return(0,Q.jsx)(r,{className:i});case`sleep`:return(0,Q.jsx)(t,{className:i});case`take_photo`:return(0,Q.jsx)(se,{className:i});case`sing`:return(0,Q.jsx)(j,{className:i});case`play_music`:return(0,Q.jsx)(D,{className:i});case`medicine`:return(0,Q.jsx)(he,{className:i});default:return(0,Q.jsx)(a,{className:i})}})();return(0,Q.jsx)(`div`,{className:K(`size-8 rounded-full flex items-center justify-center shrink-0`,n?`bg-emerald-500/15 text-emerald-500`:`bg-muted/60 text-muted-foreground`),children:n?(0,Q.jsx)(I,{className:`size-4`}):o})}function ll({companion:e,companions:t,selectedD:n,profile:r,blobbiNaddr:i,onSelectBlobbi:a,onAdopt:o,onDevOpenEditor:s,onDevOpenEmotionPanel:c,onDevInstantTransition:l,isHatching:d,isEvolving:f}){let p=d||f;return(0,Q.jsxs)(`div`,{className:`flex flex-col items-center h-full min-h-[210px] px-3 sm:px-4`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center justify-center gap-4 sm:gap-6 py-3`,children:[t.map(e=>{let t=e.d===n,i=e.d===r?.currentCompanion;return(0,Q.jsxs)(`button`,{onClick:()=>a(e.d),className:K(`flex flex-col items-center gap-1 transition-all duration-200`,`hover:-translate-y-1 hover:scale-105 active:scale-95`),children:[(0,Q.jsxs)(`div`,{className:`relative`,children:[(0,Q.jsx)(`div`,{className:K(`rounded-full p-1 transition-all`,t?`ring-2 ring-primary ring-offset-2 ring-offset-background`:``),children:(0,Q.jsx)(bn,{companion:e,size:`sm`,recipe:e.state===`sleeping`?yn():void 0,recipeLabel:e.state===`sleeping`?`sleeping`:void 0})}),i&&(0,Q.jsx)(`div`,{className:`absolute -bottom-0.5 -right-0.5 size-5 rounded-full bg-background ring-2 ring-background flex items-center justify-center`,children:(0,Q.jsx)(R,{className:`size-3 text-emerald-500`})}),Kc(e)&&!i&&(0,Q.jsx)(`div`,{className:`absolute -top-0.5 -right-0.5 size-4 rounded-full bg-amber-500 flex items-center justify-center`,children:(0,Q.jsx)(`span`,{className:`text-[8px] text-white font-bold`,children:`!`})})]}),e.stage!==`egg`&&(0,Q.jsx)(`span`,{className:K(`text-[11px] font-medium max-w-[4.5rem] truncate`,t?`text-foreground`:`text-muted-foreground`),children:e.name})]},e.d)}),(0,Q.jsxs)(`button`,{onClick:o,className:`flex flex-col items-center gap-1 transition-all duration-200 hover:-translate-y-1 hover:scale-105 active:scale-95`,children:[(0,Q.jsx)(`div`,{className:`size-14 rounded-full flex items-center justify-center`,style:{background:`radial-gradient(circle at 40% 35%, color-mix(in srgb, currentColor 10%, transparent), color-mix(in srgb, currentColor 3%, transparent) 70%)`},children:(0,Q.jsx)(u,{className:`size-6 text-muted-foreground/60`})}),(0,Q.jsx)(`span`,{className:`text-[11px] font-medium text-muted-foreground/60`,children:`Adopt`})]})]}),(0,Q.jsxs)(`div`,{className:`flex items-center justify-center gap-6 pt-1`,children:[(0,Q.jsxs)(je,{to:`/${i}`,className:`flex flex-col items-center gap-1 text-muted-foreground hover:text-foreground transition-colors`,children:[(0,Q.jsx)(C,{className:`size-5`}),(0,Q.jsx)(`span`,{className:`text-[10px]`,children:`View`})]}),tt()&&(0,Q.jsxs)(Q.Fragment,{children:[e.stage!==`adult`&&l&&(0,Q.jsxs)(`button`,{onClick:l,disabled:p,className:`flex flex-col items-center gap-1 text-amber-500 hover:text-amber-400 transition-colors disabled:opacity-40`,children:[(0,Q.jsx)(b,{className:`size-5`}),(0,Q.jsx)(`span`,{className:`text-[10px]`,children:e.stage===`egg`?`Hatch`:`Evolve`})]}),(0,Q.jsxs)(`button`,{onClick:s,className:`flex flex-col items-center gap-1 text-amber-500 hover:text-amber-400 transition-colors`,children:[(0,Q.jsx)(L,{className:`size-5`}),(0,Q.jsx)(`span`,{className:`text-[10px]`,children:`Editor`})]}),(0,Q.jsxs)(`button`,{onClick:c,className:`flex flex-col items-center gap-1 text-amber-500 hover:text-amber-400 transition-colors`,children:[(0,Q.jsx)(me,{className:`size-5`}),(0,Q.jsx)(`span`,{className:`text-[10px]`,children:`Emote`})]})]})]})]})}var ul={feed:{label:`Feed`,icon:`🍎`},play:{label:`Play`,icon:`⚽`},clean:{label:`Clean`,icon:`🧼`},medicate:{label:`Medicine`,icon:`💊`},boost:{label:`Boost`,icon:`⚡`}},dl={hunger:{label:`Hungry`,icon:`🍎`},happiness:{label:`Unhappy`,icon:`⚽`},hygiene:{label:`Dirty`,icon:`🧼`},health:{label:`Unwell`,icon:`💊`},energy:{label:`Tired`,icon:`⚡`}};function fl({companion:e,projectedStats:t,socialOpen:n,onToggleSocial:r,isSocialToggling:i,isEgg:a}){let{interactions:s,isLoading:c}=ir(a?null:e),u=(0,Z.useMemo)(()=>_n(t),[t]),d=`blobbi-social-toggle`;return(0,Q.jsxs)(`div`,{className:`px-4 sm:px-6 space-y-4`,children:[!a&&(0,Q.jsx)(`div`,{className:`rounded-lg border p-3`,children:u.length===0?(0,Q.jsx)(`p`,{className:`text-sm text-muted-foreground text-center`,children:`All good! No needs right now.`}):(0,Q.jsxs)(`div`,{className:`space-y-2`,children:[(0,Q.jsx)(`p`,{className:`text-xs font-medium text-muted-foreground uppercase tracking-wide`,children:`Needs now`}),(0,Q.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:u.map(({stat:e,priority:t})=>{let n=dl[e]??{label:e,icon:`?`};return(0,Q.jsxs)(`span`,{className:K(`inline-flex items-center gap-1 px-2 py-1 rounded-md text-xs font-medium`,t===`critical`&&`bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400`,t===`high`&&`bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-400`,t===`normal`&&`bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400`,t===`low`&&`bg-muted text-muted-foreground`),children:[(0,Q.jsx)(`span`,{children:n.icon}),(0,Q.jsx)(`span`,{children:n.label})]},e)})})]})}),a?(0,Q.jsxs)(`div`,{className:`flex items-center gap-2.5 rounded-lg border border-dashed p-3`,children:[(0,Q.jsx)(o,{className:`size-4 shrink-0 text-muted-foreground`}),(0,Q.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Social care settings will unlock after your Blobbi hatches.`})]}):(0,Q.jsxs)(`div`,{className:`flex items-center justify-between gap-3 rounded-lg border p-3`,children:[(0,Q.jsxs)(`label`,{htmlFor:d,className:`flex items-center gap-2.5 cursor-pointer select-none min-w-0`,children:[(0,Q.jsx)(x,{className:`size-4 shrink-0 text-muted-foreground`}),(0,Q.jsxs)(`div`,{className:`min-w-0`,children:[(0,Q.jsx)(`p`,{className:`text-sm font-medium leading-tight`,children:`Allow others to care for this Blobbi`}),(0,Q.jsx)(`p`,{className:`text-xs text-muted-foreground mt-0.5`,children:n?`Anyone can feed, play, and clean.`:`Only you can interact.`})]})]}),(0,Q.jsx)(Qe,{id:d,checked:n,onCheckedChange:r,disabled:i,"aria-label":`Allow other people to care for this Blobbi`})]}),c?(0,Q.jsx)(`div`,{className:`space-y-2`,children:[...[,,,,]].map((e,t)=>(0,Q.jsx)(Be,{className:`h-9 w-full rounded-lg`},t))}):s.length===0?(0,Q.jsxs)(`div`,{className:`flex flex-col items-center justify-center py-8 text-muted-foreground`,children:[(0,Q.jsx)(l,{className:`size-6 mb-2 opacity-40`}),(0,Q.jsx)(`p`,{className:`text-sm`,children:`No recent help`})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Recent help`}),(0,Q.jsx)(`div`,{className:`space-y-1 max-h-60 overflow-y-auto`,children:s.map(e=>{let t=ul[e.action]??{label:e.action,icon:`?`},n=e.itemId?un(e.itemId):void 0;return(0,Q.jsxs)(`div`,{className:`flex items-center gap-2 py-1.5 px-2 rounded-md bg-muted/40 text-sm`,children:[(0,Q.jsx)(`span`,{className:`text-base leading-none`,children:t.icon}),(0,Q.jsx)(`span`,{className:`font-medium`,children:t.label}),n&&(0,Q.jsxs)(`span`,{className:`text-muted-foreground truncate max-w-[7rem]`,children:[n.icon,` `,n.name]}),(0,Q.jsxs)(`span`,{className:`ml-auto flex items-center gap-1.5 shrink-0 text-xs text-muted-foreground`,children:[(0,Q.jsx)(pl,{pubkey:e.authorPubkey}),(0,Q.jsx)(`span`,{children:Ke(e.createdAt)})]})]},e.event.id)})})]})]})}function pl({pubkey:e}){let t=De(e),n=t.data?.metadata?.name??`Anonymous`;return(0,Q.jsx)(je,{to:Me(e,t.data?.metadata),className:`font-medium text-foreground hover:underline truncate max-w-[6rem]`,title:n,onClick:e=>e.stopPropagation(),children:n})}function ml({companions:e,onSelect:t,isLoading:n,onAdopt:r,currentCompanion:a}){return(0,Q.jsxs)(Xc,{children:[(0,Q.jsxs)(`div`,{className:`flex items-center justify-between px-4 py-3 sm:px-6 sm:py-4`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,Q.jsx)(o,{className:`size-5 text-primary`}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`h1`,{className:`text-lg font-semibold`,children:`Choose Your Blobbi`}),(0,Q.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Select a companion to care for`})]})]}),n&&(0,Q.jsx)(i,{className:`size-4 text-muted-foreground animate-spin`})]}),(0,Q.jsx)(`div`,{className:`flex-1 flex flex-col items-center justify-center px-4 sm:px-6 py-6`,children:(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center justify-center gap-6 sm:gap-8`,children:[e.map(e=>{let n=e.d===a;return(0,Q.jsxs)(`button`,{onClick:()=>t(e.d),className:`flex flex-col items-center gap-1.5 transition-all duration-200 hover:-translate-y-1 hover:scale-105 active:scale-95`,children:[(0,Q.jsxs)(`div`,{className:`relative`,children:[(0,Q.jsx)(bn,{companion:e,size:`sm`}),n&&(0,Q.jsx)(`div`,{className:`absolute -bottom-0.5 -right-0.5 size-5 rounded-full bg-background ring-2 ring-background flex items-center justify-center`,children:(0,Q.jsx)(R,{className:`size-3 text-emerald-500`})})]}),(0,Q.jsx)(`span`,{className:`text-xs font-medium text-muted-foreground max-w-[5rem] truncate`,children:e.name})]},e.d)}),r&&(0,Q.jsxs)(`button`,{onClick:r,className:`flex flex-col items-center gap-1.5 transition-all duration-200 hover:-translate-y-1 hover:scale-105 active:scale-95`,children:[(0,Q.jsx)(`div`,{className:`size-14 rounded-full flex items-center justify-center`,style:{background:`radial-gradient(circle at 40% 35%, color-mix(in srgb, currentColor 10%, transparent), color-mix(in srgb, currentColor 3%, transparent) 70%)`},children:(0,Q.jsx)(u,{className:`size-6 text-muted-foreground/60`})}),(0,Q.jsx)(`span`,{className:`text-xs font-medium text-muted-foreground/60`,children:`Adopt`})]})]})})]})}function hl(){return(0,Q.jsxs)(Xc,{children:[(0,Q.jsxs)(`div`,{className:`flex-1 flex flex-col items-center justify-center px-4 py-4`,children:[(0,Q.jsx)(Be,{className:`h-8 w-32 mb-6`}),(0,Q.jsx)(Be,{className:`size-80 sm:size-96 md:size-[28rem] rounded-full`})]}),(0,Q.jsx)(`div`,{className:`px-4 pb-6 sm:px-6`,children:(0,Q.jsx)(`div`,{className:`flex justify-center gap-4 sm:gap-6`,children:[...[,,,,,]].map((e,t)=>(0,Q.jsxs)(`div`,{className:`flex flex-col items-center gap-1`,children:[(0,Q.jsx)(Be,{className:`size-14 sm:size-16 rounded-full`}),(0,Q.jsx)(Be,{className:`h-3 w-10`})]},t))})})]})}var gl=[`nhom!`,`nom nom!`,`yum!`,`yum yum!`,`mmm~`,`munch!`,`cronch!`,`tasty!`,`hehe!`,`♡`],_l=[{sx:-7,sy:0,dx:-4,dy:14,delay:0,size:2,color:`bg-amber-600/90`},{sx:-5,sy:1,dx:-2,dy:18,delay:50,size:3,color:`bg-orange-500/85`},{sx:-8,sy:-1,dx:-5,dy:12,delay:100,size:2,color:`bg-yellow-600/80`},{sx:-2,sy:2,dx:1,dy:20,delay:30,size:3,color:`bg-amber-700/90`},{sx:1,sy:3,dx:-1,dy:24,delay:80,size:4,color:`bg-orange-600/85`},{sx:0,sy:2,dx:2,dy:16,delay:120,size:2,color:`bg-amber-500/90`},{sx:5,sy:1,dx:3,dy:18,delay:40,size:3,color:`bg-amber-600/80`},{sx:7,sy:0,dx:5,dy:14,delay:90,size:2,color:`bg-yellow-700/80`},{sx:8,sy:-1,dx:4,dy:12,delay:130,size:2,color:`bg-orange-500/75`},{sx:-3,sy:2,dx:-3,dy:26,delay:60,size:4,color:`bg-amber-700/80`},{sx:3,sy:2,dx:2,dy:28,delay:110,size:3,color:`bg-yellow-600/75`},{sx:0,sy:3,dx:0,dy:22,delay:140,size:2,color:`bg-orange-600/80`}];function vl({crumbX:e,crumbY:t,rewardX:n,rewardY:r}){let[i]=(0,Z.useState)(()=>gl[Math.floor(Math.random()*gl.length)]);return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`fixed pointer-events-none z-[60]`,style:{left:e,top:t},"aria-hidden":`true`,children:_l.map((e,t)=>(0,Q.jsx)(`span`,{className:`absolute rounded-full ${e.color} animate-crumb-fall`,style:{left:e.sx,top:e.sy,width:e.size,height:e.size,animationDelay:`${e.delay}ms`,"--crumb-dx":`${e.dx}px`,"--crumb-dy":`${e.dy}px`}},t))}),(0,Q.jsx)(`span`,{className:`fixed pointer-events-none z-[60] text-xs font-bold text-amber-500 drop-shadow-[0_1px_2px_rgba(180,83,9,0.4)] animate-reward-pop whitespace-nowrap select-none`,style:{left:n,top:r,transform:`translate(-50%, 0)`},"aria-hidden":`true`,children:i})]})}export{qc as BlobbiPage};
// @license-end
