const {HostedApp,LoginAsBanner}=HubContent;
const {useState,useEffect,useRef}=React;
function ItemTags({item,className=''}) {
 if(!item?.tags?.length)return null;
 return (
   <span className={'item-tags inline-flex min-w-0 items-center gap-[3px] align-middle ' + className}>
     {item.tags.map((tag) => (
       <span
         key={tag.label}
         className={
           'tag-chip inline-block min-w-0 max-w-24 flex-initial truncate rounded-md border border-solid font-semibold ' +
           badgeSpacing +
           ' ' +
           tag.className
         }
         title={tag.label}
       >
         {tag.label}
       </span>
     ))}
   </span>
 );
}
const badgeSpacing='px-[7px] py-[2px] text-[11px] leading-[16px]';
function ItemContext({item,showOrigin=true,card=false,originClassName='inline-block'}){
 const origin=showOrigin&&(typeof HubHost==='undefined'||!HubHost.workspaceSelection)&&itemOrigin(item);
 if(!origin&&!item?.tags?.length)return null;
 const layout=card
  ?'card-context arranging:mr-[62px] pointer-events-none relative z-[1] -order-1 mx-[12px] my-[calc(-1*var(--card-context-overhang))] shrink-0 items-start justify-between self-stretch [filter:drop-shadow(0_1px_2px_#0002)] [&_.tag-chip]:pointer-events-auto'
  :'items-center';
 return (
   <span
     className={
       'item-context inline-flex min-w-0 max-w-full gap-1.5 align-middle [text-shadow:none] ' + layout
     }
   >
     {origin && (
       <span
         className={
           'tag-chip origin-chip min-w-0 flex-initial whitespace-normal rounded-md border border-solid text-left font-medium [overflow-wrap:anywhere] ' +
           badgeSpacing +
           ' ' +
           originClassName
         }
         title={origin}
       >
         {origin}
       </span>
     )}
     <ItemTags
       item={item}
       className={card ? 'ml-auto max-w-[45%] flex-none' : 'ml-auto max-w-full flex-initial'}
     />
   </span>
 );
}
function AppTileLabels({app,showContext}){
 const origin=showContext&&itemOrigin(app),tags=app.tags||[];
 if(!origin&&!tags.length)return null;
 const chip='tag-chip pointer-events-auto box-border w-fit min-w-0 shrink-0 rounded-md border border-solid text-left [overflow-wrap:anywhere] '+badgeSpacing;
 return (
   <span className="item-context card-context pointer-events-none z-[1] col-start-1 row-start-1 row-end-3 -mb-2 -mt-[var(--card-context-overhang)] flex min-h-0 flex-wrap content-start items-start justify-end gap-x-1 gap-y-0.5 overflow-y-auto px-2 [scrollbar-width:none] arranging:mt-6">
     {origin && (
       <span title={origin} className={chip + ' origin-chip mr-auto line-clamp-2 max-w-[65%] font-medium'}>
         {origin}
       </span>
     )}
     {tags.map((tag) => (
       <span
         key={tag.label}
         title={tag.label}
         className={chip + ' max-w-[80%] font-semibold ' + tag.className}
       >
         {tag.label}
       </span>
     ))}
   </span>
 );
}
function Icon({name}){return HubIcons.render(name,{className:'icon'});}
function AppIcon({app}){
 if(app.iconUrl)return <img src={app.iconUrl} alt="" className="max-h-[80%] max-w-[80%] object-contain" />;
 const name=app.iconClass;
 if(typeof name==='string'){
  if(/^(fas|far|fab|ti) [a-z0-9 -]+$/.test(name))return <i className={name + ' app-glyph text-[1.7em]'} aria-hidden={true} />;
 }
 return <Icon name={HubIcons.catalogName(app.icon)} />;
}
function appIconStyle(app){return {'--app-color':app.color||'var(--icon-bg)','--app-ink':app.ink||(app.color?'var(--color-white)':'var(--icon-ink)')};}
function IconButton({label,icon,onClick,disabled=false,shortcut,className='',buttonRef}){return (
  <button
    ref={buttonRef}
    className={className ? 'iconbtn ' + className : 'iconbtn'}
    type="button"
    aria-label={label}
    aria-keyshortcuts={shortcut}
    title={label + (shortcut ? ' (⌘K / Ctrl+K)' : '')}
    onClick={onClick}
    disabled={disabled}
  >
    <Icon name={icon} />
  </button>
);}
const dialogPadding='px-6 pb-6 pt-2 phone:px-[18px] phone:pb-5';
const moreDialogProps={
 className:'home-more w-[min(22rem,calc(var(--safe-width,100vw)_-_32px))] open:flex open:flex-col open:overflow-hidden [&>.dialoghead]:flex-none',
 bodyClassName:'min-h-0 overflow-y-auto overscroll-y-contain px-3.5 pb-3.5 pt-0'
};
const dialogContext='text-[12px] leading-[1.5] text-muted [overflow-wrap:anywhere]';
const menuActionClass='flex min-h-11 w-full items-center gap-3 rounded-lg border-0 bg-transparent px-3 py-2 text-start [font:inherit] text-ink no-underline hover:bg-hover focus-visible:bg-hover [&>.icon]:text-muted';
const doneButtonClass='layout-done no-drag h-10 rounded-[10px] border-0 bg-accent px-[9px] py-0 text-[12px] font-semibold text-[color:var(--color-white)]';
function HomeToolbar({arranging, onEdit, onDone, open, moreOpen, closeMore}){
 const headerRef=useRef(null),menuReturnRef=useRef(null),[compact,setCompact]=useState(true);
 React.useLayoutEffect(()=>{
  // The content box already excludes any padding reserved for the camera.
  const observer=new ResizeObserver(([entry])=>setCompact(entry.contentRect.width<760));
  observer.observe(headerRef.current);
  return ()=>observer.disconnect();
 },[]);
 const compactIcon=compact?'min-h-11 min-w-11 phone:size-8 phone:p-1.5':'';
 const inbox=HubHost.features?.inbox&&(
   <IconButton
     className={compactIcon}
     disabled={arranging}
     label="Inbox"
     icon="mail"
     onClick={() => location.assign(HubHost.inboxUrl())}
   />
 );
 const search=(
   <IconButton
     className={compactIcon}
     disabled={arranging}
     label="Search apps and folders"
     icon="search"
     shortcut="Meta+K Control+K"
     onClick={() =>
       open({
         type: 'search'
       })
     }
   />
 );
 const workspace=<HubWorkspaces.Button disabled={arranging} compactHome={compact} />;
 const acting=HubHost.loginAs;
 const account=acting?acting.actor:hubSession.user;
 const appearance={label:'Appearance',icon:'palette',onClick:()=>open({type:'appearance'})};
 const add={label:'Add apps or widgets',icon:'plus',onClick:()=>open({type:'catalog',destination:'home'})};
 function dismissMore(){
  closeMore();
  requestAnimationFrame(()=>menuReturnRef.current?.focus({preventScroll:true}));
 }
 const edit={label:'Edit layout',icon:'layout',onClick:()=>{if(moreOpen)dismissMore();onEdit();}};
 const admin=HubHost.isSuperAdmin?[
  {label:'Login as',icon:'users',onClick:()=>open({type:'login-as'})},
  {label:'Super admin',icon:'admin',href:HubHost.inTeams?'/sa/?inTeams=true':'/sa/'}
 ]:[];
 const accountAction=!acting&&{label:'Account',icon:'person',href:HubHost.accountUrl()};
 const signOut=acting&&!HubHost.inTeams&&{label:'Sign out',icon:'logout',onClick:HubAccount.signOutOfHub};
 function action(item,labelled=false){
  if(!item)return null;
  const {label,icon,href,onClick}=item;
  if(!labelled&&!href)return (
    <IconButton
      key={label}
      label={label}
      icon={icon}
      onClick={onClick}
      disabled={arranging}
      buttonRef={item === add && !arranging ? menuReturnRef : undefined}
    />
  );
  const Action = href ? 'a' : 'button';
  return (
    <Action
      key={label}
      className={labelled ? menuActionClass : 'iconbtn'}
      aria-label={label}
      {...(href
        ? {
            href,
            title: label,
            inert: arranging ? '' : undefined
          }
        : {
            type: 'button',
            onClick,
            disabled: arranging
          })}
    >
      <Icon name={icon} />
      {labelled && label}
    </Action>
  );
 }
 const done=(
   <button
     ref={menuReturnRef}
     type="button"
     className={doneButtonClass + (compact ? ' min-h-11 min-w-11' : ' min-w-[54px]')}
     onClick={onDone}
   >
     Done
   </button>
 );
 return (
   <React.Fragment>
     <header
       ref={headerRef}
       className={
         'launcherbar mx-[var(--launcher-gutter)] flex justify-between border-b [border-bottom-style:solid] px-0 pb-[22px] pt-3 [@media(max-width:760px)]:pb-[18px] ' +
         (compact
           ? 'min-h-0 flex-col flex-nowrap items-stretch gap-1.5'
           : 'min-h-[58px] flex-wrap items-center gap-[18px]')
       }
     >
       {compact ? (
         <React.Fragment>
           <div className="flex w-full min-w-0 items-center gap-1">
             <h1
               className={
                 'home-title ' + (HubWorkspaces.workspaces?.length ? 'sr-only' : 'm-0 text-[1.2rem]')
               }
             >
               Home
             </h1>
             {workspace}
             <div className="ms-auto flex flex-none items-center gap-1">
               {inbox}
               {search}
               {arranging ? (
                 done
               ) : (
                 <button
                   ref={menuReturnRef}
                   type="button"
                   className={'iconbtn ' + compactIcon}
                   title="More"
                   aria-label="More"
                   aria-haspopup="dialog"
                   onClick={() =>
                     open({
                       type: 'home-more'
                     })
                   }
                 >
                   <Icon name="more" />
                 </button>
               )}
             </div>
           </div>
           {acting && <LoginAsBanner toolbar={true} />}
         </React.Fragment>
       ) : (
         <React.Fragment>
           <div className="welcome min-w-0 flex-[1_1_260px]">
             <h1
               className={
                 acting
                   ? 'sr-only'
                   : 'm-0 text-[28px] font-semibold leading-[1.3] tracking-[-.6px] [overflow-wrap:anywhere]'
               }
             >
               {acting ? 'Home' : 'Welcome back, ' + (account?.name || '')}
             </h1>
             {acting && <LoginAsBanner toolbar={true} />}
           </div>
           <div className="actions ml-auto flex shrink-0 items-center gap-1 min-w-0 max-w-full flex-wrap justify-end pt-0">
             {inbox}
             {admin.map((item) => action(item))}
             {search}
             {action(appearance)}
             {action(add)}
             {arranging ? done : action(edit)}
             <div
               className={
                 'launcher-account flex min-w-0 max-w-full items-center gap-[inherit] [&>.iconbtn]:shrink-0'
               }
             >
               {workspace}
               {action(accountAction)}
               {action(signOut)}
             </div>
           </div>
         </React.Fragment>
       )}
     </header>
     {moreOpen && (
       <Modal key="home-more" {...moreDialogProps} title="More" onClose={dismissMore}>
         <p className={dialogContext + ' mx-3 mb-1.5 mt-0'}>{account?.name || account?.email}</p>
         <div className="py-1">{[add, edit, appearance].map((item) => action(item, true))}</div>
         {admin.length > 0 && (
           <div className="py-1 [border-top:1px_solid_var(--edge)]">
             {admin.map((item) => action(item, true))}
           </div>
         )}
         {(accountAction || signOut) && (
           <div className="py-1 [border-top:1px_solid_var(--edge)]">
             {action(accountAction, true)}
             {action(signOut, true)}
           </div>
         )}
       </Modal>
     )}
   </React.Fragment>
 );
}
function Button({children,onClick,primary=false,danger=false,disabled=false,type='button'}){return (
  <button
    type={type}
    className={'small' + (primary ? ' primary' : '') + (danger ? ' text-danger' : '')}
    onClick={onClick}
    disabled={disabled}
  >
    {children}
  </button>
);}
let STORAGE=''; // Set from the verified email identity before rendering Home.
const LEGACY_APPEARANCE_STORAGE='ef5-hub-frontend-poc:sample-tenant:sample-user:v1:';
const DEFAULT_BACKGROUND_DIMMING={light:0,dark:65};
// Sample the displayed wallpaper, including crop, blur and dimming. No per-image presets.
function wallpaperTextTone(pixels){
 let total=0,count=0;
 const linear=value=>{const channel=value/255;return channel<=.04045?channel/12.92:Math.pow((channel+.055)/1.055,2.4);};
 for(let i=0;i<pixels.length;i+=4){total+=.2126*linear(pixels[i])+.7152*linear(pixels[i+1])+.0722*linear(pixels[i+2]);count++;}
 const luminance=total/count;
 return (luminance+.05)/(.0088+.05)>=1.05/(luminance+.05)?'dark':'light';
}
function wallpaperImageRect(width,height,imageWidth,imageHeight,fit,position){
 const inset=fit==='fill'?72:0,boxWidth=width+inset*2,boxHeight=height+inset*2;
 const scale=fit==='fit'?Math.min(boxWidth/imageWidth,boxHeight/imageHeight):Math.max(boxWidth/imageWidth,boxHeight/imageHeight);
 const w=fit==='stretch'?boxWidth:imageWidth*scale,h=fit==='stretch'?boxHeight:imageHeight*scale;
 const [horizontal,vertical='center']=(fit==='fill'?position:'center center').split(' ');
 const xFactor=horizontal==='left'?0:horizontal==='right'?1:.5,yFactor=vertical==='top'?0:vertical==='bottom'?1:.5;
 return {x:-inset+(boxWidth-w)*xFactor,y:-inset+(boxHeight-h)*yFactor,w,h};
}
function updateWallpaperText(image,{fit,position,blur,brightness,dark}){
 const width=document.documentElement.clientWidth,height=window.innerHeight,scale=Math.min(192/width,256/height);
 const canvas=document.createElement('canvas');canvas.width=Math.ceil(width*scale);canvas.height=Math.ceil(height*scale);
 const context=canvas.getContext('2d',{willReadFrequently:true});
 const rect=wallpaperImageRect(width,height,image.naturalWidth,image.naturalHeight,fit,position);
 context.filter='blur('+blur*scale+'px)';
 context.drawImage(image,rect.x*scale,rect.y*scale,rect.w*scale,rect.h*scale);
 // Canvas filters are unavailable in Safari. Dim the image with portable compositing.
 context.filter='none';context.globalCompositeOperation='source-atop';context.globalAlpha=1-brightness;
 context.fillStyle='#000';context.fillRect(0,0,canvas.width,canvas.height);
 // Fit margins and transparent image areas retain the underlying theme background.
 context.globalAlpha=1;context.globalCompositeOperation='destination-over';
 context.fillStyle=dark?'#020617':'#ffffff';context.fillRect(0,0,canvas.width,canvas.height);
 for(const label of document.querySelectorAll('.workspace .appcaption,.launcherbar .welcome,.launcherbar .home-title,.launcherbar .iconbtn,.shell>.hub-footer')){
  const bounds=label.getBoundingClientRect(),x=Math.max(0,Math.floor(bounds.left*scale)),y=Math.max(0,Math.floor(bounds.top*scale));
  const right=Math.min(canvas.width,Math.ceil(bounds.right*scale)),bottom=Math.min(canvas.height,Math.ceil(bounds.bottom*scale));
  if(right<=x||bottom<=y)continue;
  const tone=wallpaperTextTone(context.getImageData(x,y,right-x,bottom-y).data),darkInk=tone==='dark';
  label.dataset.wallpaperText=tone;
  label.style.setProperty('--wallpaper-ink',darkInk?'var(--color-slate-900)':'var(--color-white)');
  label.style.setProperty('--wallpaper-secondary',darkInk?'var(--color-slate-800)':'var(--color-slate-200)');
  label.style.setProperty('--wallpaper-shadow',darkInk?'0 1px 2px #ffffff80':'0 1px 2px #020617cc,0 2px 8px #02061799');
 }
}

const backgroundFitOptions=[
 {value:'fill',name:'Fill screen',size:'cover',inset:'-72px',description:'Fills the window without stretching. Edges may be cropped.'},
 {value:'fit',name:'Fit to screen',size:'contain',inset:'0px',description:'Shows the whole image without stretching. May leave empty space.'},
 {value:'stretch',name:'Stretch',size:'100% 100%',inset:'0px',description:'Fills the window by stretching the image. Proportions may change.'}
];
const backgroundPositionsOptions=[
 {name:'Top left',value:'left top'},{name:'Top',value:'center top'},{name:'Top right',value:'right top'},
 {name:'Left',value:'left center'},{name:'Center',value:'center'},{name:'Right',value:'right center'},
 {name:'Bottom left',value:'left bottom'},{name:'Bottom',value:'center bottom'},{name:'Bottom right',value:'right bottom'}
];
const backgrounds=[
 {id:'none',name:'None'},
 {"id":"palm","name":"Palm","image":"backgrounds/palm.webp","position":"left center"},
 {"id":"peaks","name":"Peaks","image":"backgrounds/peaks.webp"},
 {"id":"dream","name":"Dream big","image":"backgrounds/dream.webp"},
 {"id":"curves","name":"Curves","image":"backgrounds/curves.webp"},
 {"id":"city","name":"New York","image":"backgrounds/city.webp"},
 {"id":"tuscany","name":"Tuscany","image":"backgrounds/tuscany.webp"},
 {"id":"evenflow-dawn","name":"EvenFlow Dawn","image":"backgrounds/evenflow-dawn.webp"},
 {"id":"evenflow-midnight","name":"EvenFlow Midnight","image":"backgrounds/evenflow-midnight.webp"}
];
// All launcher settings are part of the user's server-owned preferences document.
function appearancePreferences(value={}){
 const bounded=(number,max,fallback)=>Number.isInteger(number)&&number>=0&&number<=max?number:fallback;
 return {
  theme:['system','light','dark'].includes(value?.theme)?value.theme:'system',
  background:backgrounds.some(item=>item.id===value?.background)?value.background:'evenflow-midnight',
  blur:bounded(value?.blur,24,8),
  dimming:Object.fromEntries(['light','dark'].map(mode=>[mode,bounded(value?.dimming?.[mode],100,DEFAULT_BACKGROUND_DIMMING[mode])])),
  positions:Object.fromEntries(backgrounds.filter(item=>backgroundPositionsOptions.some(option=>option.value===value?.positions?.[item.id])).map(item=>[item.id,value.positions[item.id]])),
  fits:Object.fromEntries(backgrounds.filter(item=>backgroundFitOptions.some(option=>option.value===value?.fits?.[item.id])).map(item=>[item.id,value.fits[item.id]]))
 };
}
function legacyAppearance(){
 const read=(key,json=false)=>{try{const raw=localStorage.getItem(LEGACY_APPEARANCE_STORAGE+key);return json?JSON.parse(raw||'null'):raw;}catch{return null;}};
 return {theme:read('theme'),background:read('background'),blur:read('background-blur')===null?undefined:Number(read('background-blur')),dimming:read('background-dimming',true),positions:read('background-positions',true),fits:read('background-fits',true)};
}
// Convert old fractional rows once; placements, folders and visibility stay intact.
function migrateGridPreferences(prefs){
 if(prefs.gridUnits===1)return prefs;
 return {...prefs,gridUnits:1,gridLayouts:Object.fromEntries(Object.entries(prefs.gridLayouts).map(([key,cells])=>[key,cells.map(cell=>({...cell,y:Math.floor(cell.y/3),h:cell.i.startsWith('widget-')?Math.max(1,Math.round(cell.h/2)):1}))]))};
}
function loadPreferences(){
 try{
  let stored=HubHost.savedPreferences;
  if(!stored&&!HubHost.loginAs){try{stored=JSON.parse(localStorage.getItem(STORAGE)||'null');}catch{}}
  const saved=stored?validatePreferences(stored):emptyPreferences();
  const prefs={...migrateGridPreferences(saved),gridColumns:saved.gridColumns||3,appearance:appearancePreferences(saved.appearance===undefined&&!HubHost.loginAs?legacyAppearance():saved.appearance)};
  return {prefs,error:'',needsSave:!HubHost.savedPreferences||saved.appearance===undefined||saved.gridUnits!==1||saved.gridColumns===undefined};
 }catch{return {prefs:{...emptyPreferences(),appearance:appearancePreferences()},needsSave:false,error:'Saved preferences could not be read. Home is using its default arrangement. Reset the arrangement to clear the saved data.'};}
}
let initial;
const dialogControl='border border-solid border-[var(--control-edge)] bg-[var(--control-bg)] text-ink enabled:hover:bg-[var(--control-hover)] motion-safe:transition-[background-color,border-color] motion-safe:duration-150 motion-safe:ease-[ease]';
const compactFolderButton='folder-compact:size-11 folder-compact:flex-none';
const compactFolderNav='iconbtn hidden folder-compact:inline-flex '+compactFolderButton;
const folderDialog='folder-dialog mx-auto mb-auto mt-[4dvh] h-[88dvh] w-[min(1440px,calc(100%_-_32px))] [container:folder_/_inline-size] open:flex open:flex-col has-[.launcher-drag-layer]:overflow-visible';
const folderHeader=' shrink-0 flex-wrap px-6 pb-3 pt-[22px] phone:px-[18px] phone:pb-2 phone:pt-[18px] folder-compact:flex-nowrap folder-compact:gap-1 folder-compact:bg-[var(--panel)]';
const folderBody=' min-h-0 flex-1 overflow-y-auto overscroll-contain px-[28px] pb-[36px] pt-[28px] [scrollbar-gutter:stable] phone:px-[14px] phone:py-[24px] folder-compact:bg-[var(--panel)]';
const dialogTextInput=dialogControl+' w-full min-w-0 rounded-[10px] px-3 py-[11px] text-[14px]';

function Modal({title,subtitle,tags=[],titleContent,onClose,children,palette=false,folder=false,onCustomize,customizeLabel,headerAction,className='',bodyClassName='',focusInput=true}){
 const ref=useRef(null),titleId=React.useId();
 useEffect(()=>{ref.current.showModal();if(focusInput)ref.current.querySelector('input:not([type="range"]):not([disabled]), select:not([disabled])')?.focus();return()=>{ref.current?.close();};},[]);
 return (
   <dialog
     ref={ref}
     className={
       'dialog rounded-[24px] border border-solid border-[var(--panel-edge)] bg-[var(--panel)] p-0 text-ink [box-shadow:var(--dialog-shadow)] ' +
       (palette
         ? 'spotlight mx-auto mb-auto mt-[var(--launcher-dialog-top)] w-[min(640px,calc(100%_-_32px))] overflow-hidden'
         : folder
           ? folderDialog
           : className || 'w-[min(560px,calc(100%_-_32px))]')
     }
     onCancel={(event) => {
       event.preventDefault();
       onClose();
     }}
     onClick={(event) => {
       if (event.target === ref.current) {
         const rect = ref.current.getBoundingClientRect();
         if (
           event.clientX < rect.left ||
           event.clientX > rect.right ||
           event.clientY < rect.top ||
           event.clientY > rect.bottom
         )
           onClose();
       }
     }}
     aria-labelledby={titleId}
   >
     {palette ? (
       <h2 id={titleId} className="sr-only">
         {title}
       </h2>
     ) : (
       <div
         className={
           'dialoghead flex items-center justify-between gap-[15px] phone:[&_.iconbtn]:min-w-10' +
           (folder ? folderHeader : ' px-6 pb-3 pt-5 phone:px-[18px] phone:pb-2 phone:pt-4')
         }
       >
         {titleContent ? (
           <React.Fragment>
             <h2 id={titleId} className="sr-only">
               {title}
             </h2>
             {titleContent}
           </React.Fragment>
         ) : (
           <div className="min-w-0 flex-1">
             <h2 id={titleId} className="m-0 text-[17px] font-semibold">
               {title}{' '}
               <ItemTags
                 item={{
                   tags
                 }}
               />
             </h2>
             {subtitle && <p className={dialogContext + ' m-0 mt-[5px]'}>{subtitle}</p>}
           </div>
         )}
         {onCustomize && <IconButton label={customizeLabel} icon="settings" onClick={onCustomize} />}
         {headerAction}
         <IconButton
           label="Close dialog"
           icon="close"
           className={folder ? compactFolderButton : ''}
           onClick={onClose}
         />
       </div>
     )}
     {palette ? (
       children
     ) : (
       <div
         className={
           'dialogbody ' +
           (folder
             ? folderBody
             : '[&_p]:text-[13px] [&_p]:leading-[1.6] ' + (bodyClassName || dialogPadding))
         }
       >
         {children}
       </div>
     )}
   </dialog>
 );
}

window.HubLauncherControls={Icon,Button,Modal};

function searchScore(item,query){
 const normalize=text=>text.normalize('NFD').replace(/[\u0300-\u036f]/g,'').toLowerCase();
 const name=normalize(item.name), text=normalize(item.name+' '+item.detail+' '+item.category+' '+itemTagText(item.app));
 const terms=normalize(query).trim().split(/\s+/).filter(Boolean);
 if(!terms.length)return 0;
 let score=0;
 for(const term of terms){
  if(name.startsWith(term))continue;
  if(name.includes(term)){score+=1;continue;}
  if(text.includes(term)){score+=2;continue;}
  let position=0;
  for(const letter of name){if(letter===term[position])position++;if(position===term.length)break;}
  if(position!==term.length)return null;
  score+=3;
 }
 return score;
}
function SearchPalette({items,onChoose,onClose}){
 const [query,setQuery]=useState(''),[selected,setSelected]=useState(0);
 const inputRef=useRef(null),listRef=useRef(null);
 const matches=items.map(item=>({item,score:searchScore(item,query)})).filter(x=>x.score!==null).sort((a,b)=>a.score-b.score).map(x=>x.item);
 const index=Math.min(selected,Math.max(0,matches.length-1));
 useEffect(()=>{inputRef.current?.focus();},[]);
 useEffect(()=>{listRef.current?.querySelector('[aria-selected="true"]')?.scrollIntoView({block:'nearest'});},[index,query]);
 const keycap='min-w-[19px] rounded border border-solid border-edge bg-surface px-1 py-0.5 text-center [font-family:inherit] text-[10px]';
 function handleKey(event){
  if(event.isComposing)return;
  if(event.key==='ArrowDown'||event.key==='ArrowUp'){
   event.preventDefault();if(matches.length)setSelected((index+(event.key==='ArrowDown'?1:-1)+matches.length)%matches.length);
  }else if(event.key==='Enter'){
   event.preventDefault();if(matches[index])onChoose(matches[index]);
  }
 }
 return (
   <Modal title="Search apps and folders" onClose={onClose} palette={true}>
     <div className="spotlight-input-row flex items-center gap-3.5 border-0 border-b border-solid border-edge px-5 py-[17px] text-muted phone:gap-2.5 phone:p-3.5">
       <Icon name="search" />
       <input
         ref={inputRef}
         className="spotlight-input min-w-0 flex-1 border-0 bg-transparent px-0 py-1.5 text-[18px] text-ink outline-offset-[6px] placeholder:text-muted phone:text-[16px]"
         type="text"
         role="combobox"
         aria-label="Search apps and folders"
         aria-autocomplete="list"
         aria-expanded={true}
         aria-controls="spotlight-results"
         aria-activedescendant={matches[index] ? 'spotlight-option-' + matches[index].id : undefined}
         placeholder="Search apps and folders…"
         autoComplete="off"
         spellCheck={false}
         value={query}
         onChange={(event) => {
           setQuery(event.target.value);
           setSelected(0);
         }}
         onKeyDown={handleKey}
       />
       <kbd className={keycap + ' phone:hidden'}>
         {/Mac|iPhone|iPad/.test(navigator.platform) ? '⌘ K' : 'Ctrl K'}
       </kbd>
       <IconButton label="Close search" icon="close" className="size-[30px] shrink-0" onClick={onClose} />
     </div>
     <div
       className="max-h-[min(440px,48vh)] overflow-y-auto overscroll-contain p-2"
       id="spotlight-results"
       role="listbox"
       aria-label="Search results"
       ref={listRef}
     >
       {matches.map((item, i) => (
         <button
           key={item.id}
           id={'spotlight-option-' + item.id}
           className="flex w-full items-center gap-3 rounded-[9px] border-0 bg-transparent px-3 py-[11px] text-left text-ink aria-selected:bg-surface phone:px-[9px] phone:py-3"
           role="option"
           tabIndex={-1}
           aria-selected={i === index}
           onPointerMove={() => setSelected(i)}
           onClick={() => onChoose(item)}
         >
           {item.folder ? (
             <FolderIcon folder={item.folder} compact={true} />
           ) : (
             <span
               className="grid size-[35px] shrink-0 place-items-center rounded-[9px] bg-[var(--app-color,var(--icon-bg))] text-[color:var(--app-ink,var(--icon-ink))]"
               style={appIconStyle(item.app)}
             >
               <AppIcon app={item.app} />
             </span>
           )}
           <span className="grid min-w-0 flex-1 gap-[3px]">
             <strong className="text-[13px] font-[550] [overflow-wrap:anywhere]">{item.name}</strong>
             <small className="text-[11px] text-muted">{item.detail}</small>
           </span>
           <span className="shrink-0 text-[10px] text-muted phone:hidden">
             <ItemTags item={item.app} />
             {itemTagText(item.app) ? ' ' : ''}
             {item.category}
           </span>
         </button>
       ))}
     </div>
     {!matches.length && (
       <div className="px-3.5 py-[30px] text-center text-[13px] text-muted" role="status">
         {'No apps or folders match “' + query + '”.'}
       </div>
     )}
     <div className="flex flex-wrap items-center gap-4 border-0 border-t border-solid border-edge px-5 py-3 text-[11px] text-muted phone:gap-3 phone:px-3.5">
       <span className="flex items-center gap-1.5">
         <kbd className={keycap}>↑</kbd>
         <kbd className={keycap}>↓</kbd>Navigate
       </span>
       <span className="flex items-center gap-1.5">
         <kbd className={keycap}>↵</kbd>Open
       </span>
       <span className="flex items-center gap-1.5">
         <kbd className={keycap}>Esc</kbd>Close
       </span>
     </div>
   </Modal>
 );
}

function FolderIcon({folder,compact=false}){
 const entries=folder.entries||folder.apps.map(app=>({id:app.id,app}));
 const overflow=entries.length>4;
 const previews=entries.slice(0,overflow?3:4);
 const count=entries.length;
 const columns=compact&&count ? (count===1?'grid-cols-[10px]':'grid-cols-[repeat(2,10px)]') : (count<=1?'grid-cols-1':'grid-cols-2');
 const rows=compact&&count ? (count<=2?'grid-rows-[10px]':'grid-rows-[repeat(2,10px)]') : (count<=2?'grid-rows-1':'grid-rows-2');
 const frame=compact
  ?'compact size-[35px] shrink-0 place-content-center gap-[3px] rounded-[9px] border border-solid border-[var(--panel-edge)] bg-[var(--panel)] [box-shadow:var(--icon-shadow)] [&>.icon]:text-[18px] [&>.icon]:leading-none'
  :'relative h-full w-[85%] justify-self-center gap-x-[16px] gap-y-[8px] px-[10px] pb-[8px] pt-[20px] phone:px-[8px]';
 const mini='foldermini grid min-w-0 place-items-center overflow-hidden [&>img]:size-4/5 '+(compact
  ?'size-[10px] rounded-[3px] [&>i]:text-[7px] [&>i]:leading-none'
  :'relative z-[1] size-[36px] rounded-[10px] phone:size-[32px] [&>i]:text-[22px] [&>i]:leading-none');
 return (
   <span
     className={
       'foldericon in-launcher:motion-safe:transition-[box-shadow,background-color,filter] in-launcher:motion-safe:duration-200 in-launcher:motion-safe:ease-[ease] grid min-h-0 place-items-center text-muted ' +
       frame +
       ' ' +
       columns +
       ' ' +
       rows
     }
     aria-hidden={true}
   >
     {!compact && (
       <svg
         className="pointer-events-none absolute inset-0 size-full fill-slate-100/60 stroke-slate-500/50 stroke-[1.5] dark:fill-slate-700/40 dark:stroke-slate-400/50 [@media(prefers-reduced-transparency:reduce)]:!fill-surface"
         viewBox="0 0 240 128"
         preserveAspectRatio="none"
         focusable="false"
       >
         <path
           d="M10 1H76L91 13H230A9 9 0 0 1 239 22V118A9 9 0 0 1 230 127H10A9 9 0 0 1 1 118V10A9 9 0 0 1 10 1Z"
           vectorEffect="non-scaling-stroke"
         />
       </svg>
     )}
     {count ? (
       previews.map((entry) => (
         <span
           key={entry.id}
           className={
             mini +
             (entry.app ? ' bg-[var(--app-color)] text-[color:var(--app-ink)]' : ' bg-hover text-muted')
           }
           style={entry.app ? appIconStyle(entry.app) : undefined}
         >
           {entry.app ? (
             <AppIcon app={entry.app} />
           ) : (
             <Icon name={entry.widget ? (entry.widget.type === 'clock' ? 'clock' : 'chart') : 'folder'} />
           )}
         </span>
       ))
     ) : compact ? (
       <Icon name="folder" />
     ) : null}
     {overflow && (
       <span
         className={
           mini +
           ' folder-more bg-hover font-semibold text-muted ' +
           (compact ? 'text-[7px]' : 'text-[13px]')
         }
       >
         {'+' + (count - previews.length)}
       </span>
     )}
   </span>
 );
}
// All provider templates use this one renderer. No business-specific widget components.
function useManifestData(widget){
 const [state,setState]=useState(()=>({data:Object.hasOwn(widgetData,widget.manifest.data)?widgetData[widget.manifest.data]:null,loading:!Object.hasOwn(widgetData,widget.manifest.data),error:''}));
 useEffect(()=>{
  let active=true,controller,generation=0;
  async function refresh(){
   controller?.abort();const request=controller=new AbortController(),current=++generation;
   if(Object.hasOwn(widgetData,widget.manifest.data)){setState({data:widgetData[widget.manifest.data],loading:false,error:''});return;}
   setState(old=>({...old,loading:true,error:''}));
   const timer=setTimeout(()=>request.abort(),10000);
   try{
    const endpoint=resolvePageAction({type:'openPage',url:widget.manifest.data},widget.provider).url;
    const response=await fetch(endpoint,{signal:request.signal,credentials:'omit',headers:{Accept:'application/json'}});
    if(!response.ok)throw new Error('Widget data request failed');
    const text=await response.text();if(text.length>64000)throw new Error('Widget data is too large');
    const data=JSON.parse(text);validateJSONData(data);
    if(active&&current===generation)setState({data,loading:false,error:''});
   }catch(error){if(active&&current===generation&&!request.signal.aborted)setState(old=>({...old,loading:false,error:'Could not load this widget.'}));else if(active&&current===generation)setState(old=>({...old,loading:false,error:'Widget request timed out.'}));}
   finally{clearTimeout(timer);}
  }
  const onPageClosed=event=>{if(event.detail?.providerId===widget.id)refresh();};
  refresh();window.addEventListener('hub-page-closed',onPageClosed);
  return()=>{active=false;controller?.abort();window.removeEventListener('hub-page-closed',onPageClosed);};
 },[widget]);
 return state;
}
function manifestNodeToReact(node,onAction,key){
 if(node.nodeType===Node.TEXT_NODE)return node.textContent;
 if(node.nodeType!==Node.ELEMENT_NODE)return null;
 const Tag=node.tagName.toLowerCase(),props={};
 for(const attribute of node.attributes){
  const name=attribute.name,value=attribute.value;
  if(name==='class')props.className=value;
  else if(name.toLowerCase()==='viewbox')props.viewBox=value;
  else if(name.toLowerCase()==='preserveaspectratio')props.preserveAspectRatio=value;
  else if(name==='stroke-width')props.strokeWidth=value;
  else if(name==='stroke-linecap')props.strokeLinecap=value;
  else if(name==='stroke-linejoin')props.strokeLinejoin=value;
  else props[name]=value;
 }
 const children=[...node.childNodes].map((child,i)=>manifestNodeToReact(child,onAction,key+'-'+i));
 if(Tag==='a'){
  props.className='no-drag inline-flex flex-none cursor-pointer items-center gap-1 whitespace-nowrap rounded-[3px] border-0 bg-transparent p-0 text-[11px] font-medium leading-[18px] text-accent no-underline';
  props.onClick=event=>{event.preventDefault();event.stopPropagation();onAction({type:'openPage',url:props.href,title:props.title||node.textContent.trim()});};
  children.push(HubIcons.render('arrow-up-right',{key:'arrow'}));
 }
 return children.length ? <Tag key={key} {...props}>{children}</Tag> : <Tag key={key} {...props} />;
}
function clockDisplay(date,locale,timeZone){
 const parts=new Intl.DateTimeFormat(locale,{timeZone,hour:'2-digit',minute:'2-digit',hourCycle:'h23'}).formatToParts(date);
 const value=type=>parts.find(part=>part.type===type).value;
 return {hours:value('hour'),minutes:value('minute'),time:value('hour')+':'+value('minute'),date:new Intl.DateTimeFormat(locale,{timeZone,weekday:'short',day:'numeric',month:'short'}).format(date)};
}
function ClockWidget({widget}){
 const [now,setNow]=useState(()=>new Date());
 useEffect(()=>{
  let timer;const tick=()=>{clearTimeout(timer);setNow(new Date());timer=setTimeout(tick,60000-Date.now()%60000);};
  const resume=()=>{if(document.visibilityState==='visible')tick();};
  tick();document.addEventListener('visibilitychange',resume);
  return()=>{clearTimeout(timer);document.removeEventListener('visibilitychange',resume);};
 },[]);
 const zone=Intl.DateTimeFormat().resolvedOptions().timeZone,display=clockDisplay(now,navigator.language,zone);
 const dot=<span className="size-[.065em] min-h-[3px] min-w-[3px] rounded-full bg-current opacity-60" />;
 return (
   <article
     className="widget min-w-0 overflow-hidden rounded-[20px] border border-solid border-[var(--panel-edge)] bg-[var(--panel)] px-5 py-[18px] [box-shadow:var(--panel-shadow)]"
     data-widget={widget.id}
     data-renderer="clock"
     aria-label={widget.name}
   >
     <div className="grid h-full min-w-0 grid-rows-[minmax(0,1fr)_auto] gap-3 [container:clock/size]">
       <time
         className={
           'flex min-w-0 items-center justify-center gap-[clamp(5px,2cqi,14px)] whitespace-nowrap font-clock text-[clamp(34px,min(34cqi,64cqh),240px)] font-[450] tabular-nums leading-[.94] tracking-[-.035em] text-ink [font-feature-settings:"zero"_0] clock-stacked:flex-col clock-stacked:gap-0 clock-stacked:text-[clamp(34px,min(68cqi,37cqh),280px)] clock-stacked:leading-[.87]'
         }
         dateTime={now.toISOString()}
         aria-label={display.time}
       >
         <span className="block" aria-hidden={true}>
           {display.hours}
         </span>
         <span className="mt-[.05em] flex flex-col gap-[.17em] clock-stacked:hidden" aria-hidden={true}>
           {dot}
           {dot}
         </span>
         <span className="block" aria-hidden={true}>
           {display.minutes}
         </span>
       </time>
       <div className="flex min-w-0 flex-wrap items-center justify-between gap-2 border-0 border-t border-solid border-[var(--panel-edge)] pt-2.5 clock-stacked:justify-center clock-stacked:gap-x-3 clock-stacked:gap-y-0.5 clock-stacked:text-center">
         <div className="text-xs font-[450] leading-4 text-ink">{display.date}</div>
         <div className="text-[10px] font-medium uppercase leading-4 tracking-[.09em] text-[color:var(--label-muted)] [overflow-wrap:anywhere]">
           {zone.split('/').pop().replaceAll('_', ' ')}
         </div>
       </div>
     </div>
   </article>
 );
}
const clockWidget = {
  id: 'hub-clock', name: 'Clock', description: 'Your local time and date.',
  type: 'clock', onHome: true, icon: 'clock', color: 'var(--color-blue-600)', tags: [],
  sizing: {
    w: 2, h: 1, minW: 1, maxW: 3, minH: 1, maxH: 3,
    sizes: [1, 2, 3].flatMap(w => [1, 2, 3].map(h => ({w, h})))
  }
};
function WorkspaceWidget({widget,onAction}){
 const {data,loading,error}=useManifestData(widget),ref=useRef(null),[compact,setCompact]=useState(false);
 React.useLayoutEffect(()=>{
  const measure=()=>setCompact(ref.current.getBoundingClientRect().height<170);
  measure();const observer=new ResizeObserver(measure);observer.observe(ref.current);return()=>observer.disconnect();
 },[widget]);
 const content=React.useMemo(()=>{
  if(!data)return {nodes:null,error:''};
  try{const fragment=renderManifestContent(widget,data);return {nodes:[...fragment.childNodes].map((node,i)=>manifestNodeToReact(node,onAction,'body-'+i)),error:''};}
  catch(error){console.error('Widget '+widget.id+' rejected:',error.message);return {nodes:null,error:'This widget could not be displayed.'};}
 },[widget,data,onAction]);
 const canOpen=!!widget.manifest.url,activate=()=>onAction({type:'openPage',url:widget.manifest.url,title:widget.name});
 const spacing=compact?'widget-small gap-[6px] p-[12px]':'gap-[12px] p-[18px]';
 return (
   <article
     ref={ref}
     className={
       'widget flex min-h-0 min-w-0 flex-col overflow-hidden rounded-[14px] border border-solid border-edge bg-[var(--panel)] [box-shadow:var(--panel-shadow)] [container:widget/size] ' +
       spacing +
       (canOpen ? ' cursor-pointer' : ' cursor-default')
     }
     data-widget={widget.id}
     data-renderer="mustache"
     onClick={canOpen ? activate : undefined}
     {...(compact && canOpen
       ? {
           role: 'button',
           tabIndex: 0,
           'aria-label': appLabel(widget),
           onKeyDown: (event) => {
             if (event.target === event.currentTarget && (event.key === 'Enter' || event.key === ' ')) {
               event.preventDefault();
               activate();
             }
           }
         }
       : {})}
   >
     <div
       className={
         'flex min-w-0 flex-none items-center justify-between text-[13px] text-muted ' +
         (compact ? 'min-h-[16px] gap-[4px]' : 'min-h-[18px] gap-[10px]')
       }
     >
       <h2
         className={
           'm-0 truncate text-[14px] font-medium ' +
           (compact ? 'min-w-0 flex-1 leading-[16px]' : 'leading-[18px]')
         }
       >
         {widget.name}
       </h2>
       {canOpen &&
         (compact ? (
           <span
             className="flex-none text-[11px] [@container_widget_(max-width:90px)]:hidden"
             aria-hidden={true}
           >
             {HubIcons.render('arrow-up-right')}
           </span>
         ) : (
           <button
             type="button"
             className="widget-corner-open arranging:pointer-events-none no-drag flex-none cursor-pointer rounded-[3px] border-0 bg-transparent px-0.5 py-0 text-muted hover:text-accent"
             aria-label={'Open ' + appLabel(widget)}
             onClick={(event) => {
               event.stopPropagation();
               activate();
             }}
           >
             {HubIcons.render('arrow-up-right')}
           </button>
         ))}
     </div>
     <div
       className={
         'widget-content arranging:[&_a]:pointer-events-none isolate min-h-0 min-w-0 flex-1 overflow-hidden text-xs leading-4 [contain:layout_paint]'
       }
     >
       {loading && !data ? (
         <p className="text-muted" role="status">
           Loading…
         </p>
       ) : error || content.error ? (
         <p className="text-muted" role="status">
           {error || content.error}
         </p>
       ) : (
         content.nodes
       )}
     </div>
   </article>
 );
}

// The grid renders positions and resizes widgets; HubPlacement owns all movement.
function cleanGridLayout(layout){return layout.map(({i,x,y,w,h})=>({i,x,y,w,h}));}
const GRID_RULES={compactType:null,preventCollision:true,allowOverlap:false};
function moveGridItem(layout,id,dx,dy,cols){return HubPlacement.nudge(layout,id,dx,dy,cols);}
function widgetSizeBounds(widget,cols,width){
 const sizes=widget.sizing.sizes,fit=sizes.filter(size=>size.w<=cols);
 // Narrow screens project to the available columns without changing saved sizes.
 const allowed=fit.length?fit:sizes.filter(size=>size.w===widget.sizing.minW);
 const widths=[...new Set(allowed.map(size=>Math.min(size.w,cols)))];
 const w=widths.reduce((best,value)=>Math.abs(value-width)<Math.abs(best-width)?value:best,widths[0]);
 const heights=allowed.filter(size=>Math.min(size.w,cols)===w).map(size=>size.h);
 return {minW:Math.min(...widths),maxW:Math.max(...widths),minH:Math.min(...heights),maxH:Math.max(...heights)};
}
const LAUNCHER_FOOTPRINT={w:1,h:1};
function reconcileGrid(items,saved,cols){
 const cells=[];
 const intersects=(a,b)=>a.x<b.x+b.w&&a.x+a.w>b.x&&a.y<b.y+b.h&&a.y+a.h>b.y;
 const make=(item,cell)=>{
  const widget=!!item.widget,size=item.widget?.sizing||{w:3,h:3,minW:3,maxW:6,minH:3,maxH:6};
  const w=widget?Math.min(size.maxW,cols,Math.max(Math.min(size.minW,cols),cell?.w||item.span||size.w)):Math.min(LAUNCHER_FOOTPRINT.w,cols);
  const {minW,maxW,minH,maxH}=widget?widgetSizeBounds(item.widget,cols,w):{minW:w,maxW:w,minH:LAUNCHER_FOOTPRINT.h,maxH:LAUNCHER_FOOTPRINT.h};
  const h=widget?Math.min(maxH,Math.max(minH,Math.round(cell?.h||size.h))):LAUNCHER_FOOTPRINT.h;
  return {i:item.id,x:Math.min(Math.max(0,cell?.x||0),cols-w),y:Math.max(0,cell?.y||0),w,h,isResizable:widget,minW,maxW,minH,maxH};
 };
 for(const item of items){const old=saved?.find(cell=>cell.i===item.id);if(old){const cell=make(item,old);if(!cells.some(other=>intersects(cell,other)))cells.push(cell);}}
 for(const item of items){if(cells.some(cell=>cell.i===item.id))continue;const cell=make(item);let y=0,placed=false;while(!placed){for(let x=0;x<=cols-cell.w;x++){cell.x=x;cell.y=y;if(!cells.some(other=>intersects(cell,other))){placed=true;break;}}if(!placed)y++;}cells.push(cell);}
 return items.map(item=>cells.find(cell=>cell.i===item.id));
}
// Prefer this size's saved arrangement; generate an initial layout only when absent.
function responsiveGrid(items,gridLayouts,container,cols){
 const savedKeys=Object.keys(gridLayouts).filter(key=>key.startsWith(container+':')).sort((a,b)=>Number(b.split(':')[1])-Number(a.split(':')[1]));
 const ownKey=container+':'+cols;
 const sourceKey=Object.hasOwn(gridLayouts,ownKey)?ownKey:savedKeys[0],sourceCols=sourceKey?Number(sourceKey.split(':')[1]):3;
 const saved=sourceKey?gridLayouts[sourceKey]:[];
 const itemById=new Map(items.map(item=>[item.id,item]));
 // Reflow former narrow shortcuts once, preserving their visual order and widget sizes.
 const narrow=saved.some(cell=>itemById.has(cell.i)&&!itemById.get(cell.i).widget&&(cell.w!==LAUNCHER_FOOTPRINT.w||cell.h!==LAUNCHER_FOOTPRINT.h));
 const cells=reconcileGrid(items,saved,sourceCols);
 const source=cells;
 if(cols===sourceCols&&!narrow)return source;
 // Wrap the visual order while preserving each widget's chosen footprint.
 const previous=new Map(saved.map(cell=>[cell.i,cell]));
 const visual=[...source].sort((a,b)=>{const left=narrow?(previous.get(a.i)||a):a,right=narrow?(previous.get(b.i)||b):b;return left.y-right.y||left.x-right.x;});
 const projected=new Map();let x=0,y=0,rowHeight=0;
 for(const cell of visual){
  const widget=!!itemById.get(cell.i).widget,size=itemById.get(cell.i).widget?.sizing,w=widget?Math.min(cols,cell.w):Math.min(LAUNCHER_FOOTPRINT.w,cols),h=cell.h;
  if(x+w>cols){y+=rowHeight;x=0;rowHeight=0;}
  projected.set(cell.i,{...cell,x,y,w,...(widget?widgetSizeBounds(itemById.get(cell.i).widget,cols,w):{})});
  x+=w;rowHeight=Math.max(rowHeight,h);
  if(x===cols){y+=rowHeight;x=0;rowHeight=0;}
 }
 return items.map(item=>projected.get(item.id));
}

function workspaceGridItems(workspace,prefs,container){
 if(container!=='home')return workspace.folders.find(folder=>folder.id===container).entries;
 return homeEntries(workspace,prefs);
}

const GRID_MARGIN=[12,16],GRID_PADDING=[0,0];
function useGridWidth(){
 const containerRef=useRef(null),[width,setWidth]=useState(0);
 React.useLayoutEffect(()=>{
  const node=containerRef.current;
  const measure=()=>{const next=Math.round(node.getBoundingClientRect().width);setWidth(current=>current===next?current:next);};
  measure();const observer=new ResizeObserver(measure);observer.observe(node);return()=>observer.disconnect();
 },[]);
 return {width,containerRef,mounted:width>0};
}
// Capture before React moves keyed DOM nodes: CSS transitions alone skip those moves.
class LauncherGridMotion extends React.Component{
 animations=new Set();
 getSnapshotBeforeUpdate(previous){
  if(previous.layout===this.props.layout&&previous.width===this.props.width)return null;
  const positions=new Map(),root=this.props.root.current;
  if(!previous.arranging||!this.props.arranging||previous.width!==this.props.width||previous.cols!==this.props.cols||window.matchMedia('(prefers-reduced-motion: reduce)').matches)return positions;
  const origin=root.getBoundingClientRect();
  for(const node of root.querySelectorAll('[data-grid-id]')){
   const rect=node.getBoundingClientRect();positions.set(node.dataset.gridId,{x:rect.left-origin.left,y:rect.top-origin.top});
  }
  const held=previous.dragId&&root.ownerDocument.querySelector('.launcher-drag-overlay');
  if(held){const rect=held.getBoundingClientRect();positions.set(previous.dragId,{x:rect.left-origin.left,y:rect.top-origin.top});}
  return positions;
 }
 componentDidUpdate(previous,state,positions){
  if(!positions)return;
  this.stopAnimations();
  const root=this.props.root.current,origin=root.getBoundingClientRect(),moves=[];
  for(const node of root.querySelectorAll('[data-grid-id]')){
   const before=positions.get(node.dataset.gridId);if(!before)continue;
   const after=node.getBoundingClientRect(),dx=before.x-(after.left-origin.left),dy=before.y-(after.top-origin.top);
   if(Math.abs(dx)>.5||Math.abs(dy)>.5)moves.push({node,dx,dy});
  }
  for(const {node,dx,dy} of moves){
   const target=node.style.transform;
   const animation=node.animate([{transform:`translate(${dx}px, ${dy}px) ${target}`},{transform:target}],{duration:300,easing:'cubic-bezier(.2,0,0,1)'});
   this.animations.add(animation);animation.onfinish=()=>this.animations.delete(animation);
  }
 }
 stopAnimations(){for(const animation of this.animations)animation.cancel();this.animations.clear();}
 componentWillUnmount(){this.stopAnimations();}
 render(){return this.props.children;}
}
function LauncherLayoutGrid({items,label,container,gridLayouts,arranging,showContext,columns=3,dragId,onStart,onCancel,onResize}){
 const {width,containerRef,mounted}=useGridWidth();
 const cols=Math.min(columns,width<450?2:width<760?3:6);
 const gridKey=container+':'+cols;
 const signature=items.map(item=>item.id+':'+(item.span||'')).join('|');
 const contentSignature=arranging+JSON.stringify(items.map(({node,...item})=>item));
 const layout=React.useMemo(()=>responsiveGrid(items,gridLayouts,container,cols).map(cell=>({...cell,isDraggable:false,isResizable:arranging&&!!items.find(item=>item.id===cell.i).widget})),[gridKey,gridLayouts,signature,arranging]);
 const children=React.useMemo(()=>items.map(item=>(
   <div
     key={item.id}
     className={
       'grid-cell' +
       (item.widget ? ' widget-cell' : '') +
       (dragId === item.id ? ' drag-source [&>.tile]:invisible [&>.widget-wrap]:invisible' : '')
     }
     data-grid-id={item.id}
   >
     {item.node}
   </div>
 )),[contentSignature,showContext,dragId]);
 return (
   <section
     ref={containerRef}
     aria-label={label + (arranging ? ' — arranging' : '')}
     data-arranging={arranging}
     className="launcher-grid-shell min-w-0"
     data-layout-library="react-grid-layout"
     data-layout-version="1.5.4"
     data-grid-compaction="none"
     data-grid-key={gridKey}
     data-columns={cols}
     onPointerDown={(event) => onStart(container, gridKey, items, layout, event)}
     onLostPointerCapture={(event) => {
       if (event.target === event.currentTarget) onCancel();
     }}
   >
     {mounted && (
       <LauncherGridMotion
         root={containerRef}
         layout={layout}
         width={width}
         cols={cols}
         arranging={arranging}
         dragId={dragId}
       >
         <HubGrid.GridLayout
           width={width}
           layout={layout}
           cols={cols}
           rowHeight={188}
           margin={GRID_MARGIN}
           containerPadding={GRID_PADDING}
           isDraggable={false}
           isResizable={arranging}
           onResizeStart={() => onCancel()}
           onResize={(layout, oldItem, item, placeholder) => {
             const widget = items.find((entry) => entry.id === item.i)?.widget;
             if (!widget) return;
             const bounds = widgetSizeBounds(widget, cols, item.w);
             Object.assign(item, bounds);
             item.h = Math.min(bounds.maxH, Math.max(bounds.minH, Math.round(item.h)));
             if (placeholder) placeholder.h = item.h;
           }}
           onResizeStop={(next) => onResize(container, gridKey, next)}
           useCSSTransforms={true}
           {...GRID_RULES}
           className="apps launcher-grid"
         >
           {children}
         </HubGrid.GridLayout>
       </LauncherGridMotion>
     )}
   </section>
 );
}
function PlacementOverlay({drag,children}){
 if(!drag?.moved)return null;
 const portal=drag.dialog||document.body,bounds=drag.dialog?.getBoundingClientRect(),origin={x:(bounds?.left||0)+(drag.dialog?.clientLeft||0),y:(bounds?.top||0)+(drag.dialog?.clientTop||0)};
 const labelClass='absolute left-1/2 -translate-x-1/2 whitespace-nowrap rounded-lg border border-solid border-edge bg-[var(--panel)] px-2 py-[5px] text-[12px] text-ink [box-shadow:var(--panel-shadow)]';
 const grid=drag.root.getBoundingClientRect(),target=drag.targets.find(target=>target.id===drag.intent?.targetId),intent=drag.intent;
 let marker=null;
 if(intent?.type==='move'){
  const destination=HubPlacement.place(drag.original,drag.entry.id,intent,drag.cols).find(cell=>cell.i===drag.entry.id);
  if(destination.x===intent.x&&destination.y===intent.y){
   const unit=(Math.round(grid.width)+GRID_MARGIN[0])/drag.cols;
   marker=(
     <div
       className="placement-marker empty absolute z-0 box-border rounded-[18px] border border-dashed border-[color:color-mix(in_srgb,var(--accent)_45%,transparent)] bg-[color:color-mix(in_srgb,var(--accent)_8%,transparent)]"
       style={{
         left: grid.left - origin.x + Math.round(intent.x * unit),
         top: grid.top - origin.y + intent.y * (188 + GRID_MARGIN[1]),
         width: drag.width,
         height: drag.height
       }}
     />
   );
  }
 }
 if(target&&(intent.type==='insert'||intent.type==='combine')){
  const r=target.rect,edge=intent.edge,vertical=edge==='left'||edge==='right';
  const left=grid.left-origin.x+r.left+(edge==='right'?r.right-r.left:0),top=grid.top-origin.y+r.top+(edge==='bottom'?r.bottom-r.top:0);
  const insert='rounded-[2px] bg-accent before:absolute before:-left-[3px] before:-top-[3px] before:size-2 before:rounded-full before:bg-accent before:content-[""] '+(vertical?'vertical -ml-1.5':'horizontal -mt-2');
  const combine='combine rounded-2xl border-2 border-solid border-accent '+(drag.ready?'ready bg-[color:color-mix(in_srgb,var(--accent)_16%,transparent)]':'bg-[color:color-mix(in_srgb,var(--accent)_8%,transparent)] opacity-[.65]');
  marker=(
    <div
      className={'placement-marker absolute z-[2] ' + (intent.type === 'combine' ? combine : insert)}
      style={{
        left,
        top,
        width: intent.type === 'combine' ? r.right - r.left : vertical ? 2 : r.right - r.left,
        height: intent.type === 'combine' ? r.bottom - r.top : vertical ? r.bottom - r.top : 2
      }}
    >
      {intent.type === 'combine' && (
        <span className={labelClass + ' -top-[30px]'}>
          {drag.ready
            ? target.item.folder
              ? 'Release to add to ' + target.item.folder.name
              : 'Release to create folder'
            : 'Hold to create folder'}
        </span>
      )}
    </div>
  );
 }
 return ReactDOM.createPortal((
   <div
     className={
       'launcher-drag-layer pointer-events-none inset-0 z-[100] overflow-visible ' +
       (drag.dialog ? 'absolute' : 'fixed')
     }
     aria-hidden={true}
   >
     {marker}
     <div
       className="launcher-drag-overlay grid-cell pointer-events-none absolute origin-center scale-[.94] opacity-75"
       style={{
         left: drag.point.x - drag.grab.x - origin.x,
         top: drag.point.y - drag.grab.y - origin.y,
         width: drag.width,
         height: drag.height
       }}
     >
       {children}
     </div>
     {intent.type === 'home' && (
       <div
         className={'placement-home ' + labelClass}
         style={{
           left: drag.point.x - origin.x,
           top: drag.point.y - origin.y - 32
         }}
       >
         Release to move to Home
       </div>
     )}
   </div>
 ),portal);
}

function WidgetCard({widget,onAction,showContext=true}){
 // Each extra grid row adds 204px, enough for twelve additional 16px lines of context.
 const originLines='line-clamp-4 [@container_widget-frame_(min-height:392px)]:line-clamp-[16] [@container_widget-frame_(min-height:596px)]:line-clamp-[28]';
 return (
   <div
     className={
       'widget-wrap relative flex h-full arranging:cursor-grab arranging:touch-none touch-pan-y select-none flex-col rounded-[20px] [container:widget-frame/size] [-webkit-touch-callout:none] [&>.widget]:h-auto [&>.widget]:min-h-0 [&>.widget]:flex-1'
     }
     aria-label={widget.name}
   >
     {widget.type === 'clock' ? (
       <ClockWidget widget={widget} />
     ) : (
       <WorkspaceWidget widget={widget} onAction={onAction} />
     )}
     <ItemContext item={widget} showOrigin={showContext} card={true} originClassName={originLines} />
   </div>
 );
}
function LauncherTile({entry,container,arranging,onLaunch,onNudge,showContext=true}){
 const {app,folder}=entry;
 const interaction='in-launcher:transition-transform in-launcher:duration-200 in-launcher:ease-[ease] arranging:cursor-grab arranging:touch-none '+
  'browsing:fine-pointer:hover:[&_.appicon]:[filter:brightness(1.07)] '+
  (app?.disabled?'unavailable cursor-not-allowed opacity-[.45]':'cursor-pointer browsing:fine-pointer:[&:hover:not(:active)]:scale-105 browsing:active:scale-95 browsing:fine-pointer:hover:[&_.appicon]:[box-shadow:var(--icon-hover-shadow)]');
 return (
   <div className="tile drag-tile relative h-full min-w-0" data-app={app?.id} data-folder={folder?.id}>
     <button
       className={
         'app app-card relative flex size-full min-h-0 touch-pan-y select-none flex-col items-center justify-center rounded-[18px] border border-solid border-transparent bg-transparent p-0 [-webkit-touch-callout:none] [.launcher-drag-overlay_&]:rounded-[15px] [.launcher-drag-overlay_&]:border-0 ' +
         interaction
       }
       type="button"
       aria-label={app ? appLabel(app) : 'Open ' + folder.name + ' folder'}
       aria-keyshortcuts={arranging ? 'Alt+ArrowLeft Alt+ArrowRight Alt+ArrowUp Alt+ArrowDown' : undefined}
       aria-disabled={!!app && !arranging && app.disabled}
       title={app?.disabled ? app.disabledReason : undefined}
       onClick={() => onLaunch(entry, container)}
       onKeyDown={(event) => {
         if (
           arranging &&
           event.altKey &&
           ['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown'].includes(event.key)
         ) {
           event.preventDefault();
           onNudge(entry, container, event.key);
         }
       }}
     >
       <span
         className={
           'appbody min-h-0 w-full flex-1 rounded-[14px] border border-solid border-edge bg-[var(--panel)] [box-shadow:var(--panel-shadow)] ' +
           (folder
             ? 'folderbody grid grid-cols-1 grid-rows-[minmax(0,1fr)_auto] items-stretch justify-stretch gap-[12px] py-[16px] phone:gap-[10px] phone:pb-[14px]'
             : 'grid grid-cols-[minmax(0,1fr)] grid-rows-[1fr_4rem_auto_1fr]')
         }
       >
         {app && <AppTileLabels app={app} showContext={showContext} />}
         {app ? (
           <span
             className={
               'appicon col-start-1 row-start-2 justify-self-center in-launcher:[box-shadow:var(--icon-shadow)] in-launcher:motion-safe:transition-[box-shadow,background-color,filter] in-launcher:motion-safe:duration-200 in-launcher:motion-safe:ease-[ease] grid size-16 min-h-16 shrink-0 place-items-center rounded-[18px] [box-shadow:inset_0_0_0_1px_#ffffff10] bg-[var(--app-color)] text-[color:var(--app-ink,var(--icon-ink))] [&>.icon]:text-[29px] [&>.icon]:leading-none'
             }
             style={appIconStyle(app)}
           >
             <AppIcon app={app} />
           </span>
         ) : (
           <FolderIcon folder={folder} />
         )}
         <span
           className={
             'appcaption grid w-full min-w-0 shrink-0 gap-[3px] phone:gap-0.5 ' +
             (folder
               ? 'px-[16px] phone:px-[14px]'
               : 'col-start-1 row-start-3 mt-2.5 max-w-[260px] justify-self-center px-1.5')
           }
         >
           <span className="appname text-center text-[15px] font-normal leading-[21px] [overflow-wrap:anywhere]">
             {app?.name || folder.name}
           </span>
         </span>
       </span>
     </button>
   </div>
 );
}
function LoginAsDialog({onClose}){
 const [email,setEmail]=useState(HubHost.loginAs?.user.email||'');
 const [busy,setBusy]=useState(false),[error,setError]=useState('');
 async function start(event){
  event.preventDefault();setBusy(true);setError('');
  try{await HubHost.startLoginAs(email.trim());}catch(error){setError(error.message);setBusy(false);}
 }
 return (
   <Modal
     title="Login as"
     onClose={() => {
       if (!busy) onClose();
     }}
   >
     <form onSubmit={start}>
       <label className="my-[15px] grid gap-2 text-xs leading-[normal]" htmlFor="login-as-email">
         User email
         <input
           id="login-as-email"
           className={dialogTextInput}
           type="email"
           required={true}
           autoComplete="off"
           value={email}
           disabled={busy}
           onChange={(event) => setEmail(event.target.value)}
         />
       </label>
       <p className="text-[12px] text-muted">
         Open this user’s home and apps. Home changes are saved for this user.
       </p>
       {error && (
         <p className="mx-0 my-3 text-[12px] text-danger" role="alert">
           {error}
         </p>
       )}
       <div className="flex flex-wrap items-center justify-between gap-3">
         <Button onClick={onClose} disabled={busy}>
           Cancel
         </Button>
         <button type="submit" className="small primary" disabled={busy}>
           {busy ? 'Opening…' : 'Login as'}
         </button>
       </div>
     </form>
   </Modal>
 );
}
function App({initialTarget}){
 const folderMoreRef=useRef(null),folderNameRef=useRef(null);
 const [savedPrefs,setPrefs]=useState(initial.prefs),[storageError,setStorageError]=useState(initial.error);
 const workspace=React.useMemo(()=>effectiveWorkspace(registry,new Set(registry.map(app=>app.id)),savedPrefs),[savedPrefs,registry,widgetRegistry]);
 const prefs=workspace.preferences;
 const [hosted,setHosted]=useState(()=>initialTarget?{page:initialTarget}:null);
 const [modal,setModal]=useState(null),[query,setQuery]=useState(''),[name,setName]=useState(''),[error,setError]=useState('');
 const [notice,setNotice]=useState(''),[history,setHistory]=useState([]),[arranging,setArranging]=useState(false),[dragView,setDragView]=useState(null);
 const dragRef=useRef(null),suppressClick=useRef(false),uiActions=useRef(null);
 uiActions.current={nudge,hideEntry,openWidget:(widget,action,container)=>{if(!arranging&&!suppressClick.current)open({type:'app',app:{...widget,manifest:widget.provider},action,returnTo:container==='home'?null:container});},launch:(item,location)=>{if(suppressClick.current)return;if(item.folder)open({type:'folder',folderId:item.folder.id});else if(!arranging&&!item.app.disabled)open({type:'app',app:item.app,returnTo:location==='home'?null:location});}};
 const tileActions=React.useMemo(()=>({onNudge:(...args)=>uiActions.current.nudge(...args),onLaunch:(...args)=>uiActions.current.launch(...args)}),[]);
 const [systemDark,setSystemDark]=useState(hubSession?.hostTheme?hubSession.hostTheme==='dark':matchMedia('(prefers-color-scheme: dark)').matches);
 const {theme,background,blur:backgroundBlur,dimming:backgroundDimming,positions:backgroundPositions,fits:backgroundFits}=prefs.appearance;
 const backgroundPosition=backgroundPositions[background]||backgrounds.find(item=>item.id===background).position||'center';
 const backgroundFit=backgroundFits[background]||'fill';
 const selectedFit=backgroundFitOptions.find(option=>option.value===backgroundFit);
 const dark=HubHost.inTeams?systemDark:theme==='dark'||(theme==='system'&&systemDark);
 const activeDimming=backgroundDimming[dark?'dark':'light'];
 useEffect(()=>{if(!hosted)return window.HubBrowserPush?.offerOnView();},[hosted]);
 useEffect(()=>{if(initial.needsSave)persist(initial.prefs);},[]);
 const folderById=id=>workspace.folders.find(folder=>folder.id===id);
 const locationOf=app=>workspace.entries.some(entry=>entry.app?.id===app.id)?'home':workspace.folders.find(folder=>folder.apps.some(item=>item.id===app.id))?.id;
 const locationLabel=id=>id==='home'?'Home':folderById(id)?.name;
 useEffect(()=>{const media=matchMedia('(prefers-color-scheme: dark)');const listener=e=>{if(!hubSession?.hostTheme)setSystemDark(e.matches);};media.addEventListener('change',listener);return()=>media.removeEventListener('change',listener);},[]);
 useEffect(()=>{HubHost.setDocumentTheme(dark);},[dark]);
 useEffect(()=>{const listener=event=>setSystemDark(event.detail==='dark');window.addEventListener('hub-host-theme',listener);return()=>window.removeEventListener('hub-host-theme',listener);},[]);
 useEffect(()=>{const selected=backgrounds.find(item=>item.id===background);document.body.classList.toggle('has-background',!!selected.image);document.body.dataset.background=background;document.body.dataset.backgroundFit=backgroundFit;document.body.style.setProperty('--background-position',backgroundFit==='fill'?backgroundPosition:'center');document.body.style.setProperty('--background-size',selectedFit.size);document.body.style.setProperty('--background-inset',selectedFit.inset);if(selected.image)document.body.style.setProperty('--launcher-background','url("'+selected.image+'")');else document.body.style.removeProperty('--launcher-background');},[background,backgroundPosition,backgroundFit]);
 useEffect(()=>{document.body.style.setProperty('--background-blur',backgroundBlur+'px');},[backgroundBlur]);
 useEffect(()=>{document.body.style.setProperty('--background-brightness',String(1-activeDimming/100));},[activeDimming]);
 useEffect(()=>{
  const selected=backgrounds.find(item=>item.id===background);if(!selected.image)return;
  let stopped=false,failed=false,frame=0;
  const image=new Image();image.crossOrigin='anonymous';
  const refresh=()=>{frame=0;if(stopped||failed||!image.complete||!image.naturalWidth)return;try{updateWallpaperText(image,{fit:backgroundFit,position:backgroundPosition,blur:backgroundBlur,brightness:1-activeDimming/100,dark});}catch{failed=true;setNotice('Wallpaper text contrast could not be calculated. Use an image hosted by Hub or one that allows cross-origin access.');}};
  const schedule=()=>{if(!frame&&!stopped)frame=requestAnimationFrame(refresh);};
  image.onload=schedule;image.onerror=()=>{if(!stopped)setNotice('The wallpaper could not be loaded for text contrast.');};image.src=selected.image;
  window.addEventListener('resize',schedule);window.addEventListener('scroll',schedule,{passive:true});
  const observer=new ResizeObserver(schedule);observer.observe(document.querySelector('.workspace'));
  return()=>{stopped=true;cancelAnimationFrame(frame);image.onload=null;image.onerror=null;observer.disconnect();window.removeEventListener('resize',schedule);window.removeEventListener('scroll',schedule);};
 },[background,backgroundFit,backgroundPosition,backgroundBlur,activeDimming,dark,prefs,arranging]);
 useEffect(()=>{if(notice)HubToast.show(notice,{id:'launcher-notice',duration:5500,onDismiss:()=>setNotice(''),action:history.length?{label:'Undo',onClick:undo}:null});},[notice,prefs,history]);
 useEffect(()=>()=>HubToast.dismiss('launcher-notice'),[]);
 function persist(next){
  setPrefs(next);
  try{localStorage.setItem(STORAGE,JSON.stringify(next));}catch{} // Optional per-user cache; saving does not depend on browser storage.
  HubHost.savePreferences(next).then(()=>setStorageError('')).catch(error=>{if(error.status!==401)HubToast.error('Your changes could not be saved to Hub. Please try again.');});
 }
 function save(next,label){if(JSON.stringify(next)===JSON.stringify(prefs))return;setHistory(items=>[...items.slice(-19),prefs]);persist(next);setNotice(label);}
 function undo(){if(!history.length)return;const previous=history[history.length-1];persist({...previous,appearance:prefs.appearance});setHistory(items=>items.slice(0,-1));setNotice('Change undone.');if(modal?.folderId&&!effectiveWorkspace(registry,new Set(registry.map(app=>app.id)),previous).folders.some(folder=>folder.id===modal.folderId))setModal(null);}
 function openPage(action,app,returnTo){
  if(arranging||suppressClick.current)return;
  if(app.disabled){setNotice(app.disabledReason);return;}
  const page=resolvePageAction(action,app.manifest);
  setQuery('');setError('');
  setModal(null);setHosted({app,page,returnTo});
 }
 function open(next){if(next.type==='app')return openPage(next.action||next.app.action||{type:'openPage',url:'./'},next.app,next.returnTo);setQuery('');setError('');setModal(next);}
 function enterArrange(){suppressClick.current=false;setArranging(true);}
 function exitArrange(){clearDrag();suppressClick.current=false;setArranging(false);}
 function closeApp(){
  if(hosted.app)window.dispatchEvent(new CustomEvent('hub-page-closed',{detail:{providerId:hosted.app.id}}));
  setHosted(null);if(hosted.returnTo)setModal({type:'folder',folderId:hosted.returnTo});
 }
 function closeModal(){setModal(modal?.returnTo?{type:'folder',folderId:modal.returnTo}:null);}
 function changeAppearance(values){persist({...prefs,appearance:{...prefs.appearance,...values}});}
 function setAppearance(value){changeAppearance({theme:value});}
 function chooseBackground(value){changeAppearance({background:value});}
 function chooseBackgroundFit(value){changeAppearance({fits:{...backgroundFits,[background]:value}});}
 function chooseBackgroundPosition(value){changeAppearance({positions:{...backgroundPositions,[background]:value}});}
 function chooseBackgroundBlur(value){changeAppearance({blur:value});}
 function chooseBackgroundDimming(value){changeAppearance({dimming:{...backgroundDimming,[dark?'dark':'light']:value}});}

 useEffect(()=>{
  const shortcut=event=>{
   if(event.key==='Escape'&&arranging){event.preventDefault();exitArrange();return;}
   if(dragRef.current?.moved)return;
   if(arranging&&(event.metaKey||event.ctrlKey)&&event.key.toLowerCase()==='k'){event.preventDefault();return;}
   const typing=/INPUT|TEXTAREA|SELECT/.test(event.target.tagName)||event.target.isContentEditable;
   if((event.metaKey||event.ctrlKey)&&event.key.toLowerCase()==='z'&&!typing&&(!modal||modal.type==='folder')){event.preventDefault();undo();}
   if((event.metaKey||event.ctrlKey)&&!event.altKey&&event.key.toLowerCase()==='k'&&(!modal||['search','folder'].includes(modal.type))){event.preventDefault();setModal(modal?.type==='search'?(modal.returnTo?{type:'folder',folderId:modal.returnTo}:null):{type:'search',returnTo:modal?.folderId});}
  };
  window.addEventListener('keydown',shortcut);return()=>window.removeEventListener('keydown',shortcut);
 },[prefs,modal,history,arranging]);
 useEffect(()=>{
  window.addEventListener('pointermove',moveDrag,{passive:false});
  window.addEventListener('pointerup',finishDrag);
  window.addEventListener('pointercancel',clearDrag);
  return()=>{window.removeEventListener('pointermove',moveDrag);window.removeEventListener('pointerup',finishDrag);window.removeEventListener('pointercancel',clearDrag);clearDrag();};
 },[prefs,modal,arranging]);
 function moveApp(app,destination){
  let next=moveAppsPreferences(workspace,prefs,[app.id],destination);
  const original=locationOf(app),after=effectiveWorkspace(registry,new Set(registry.map(item=>item.id)),next),emptied=after.folders.find(folder=>folder.id===original);
  if(emptied&&!emptied.entries.length&&!emptied.org)next=removeFolderPreferences(after,next,original);
  save(next,app.name+' moved to '+locationLabel(destination)+'.');
  if(modal?.type==='folder'&&modal.folderId===original&&!emptied?.entries.length)setModal(null);
 }
 function focusFolderName(onlyIfLost=false){
  requestAnimationFrame(()=>{
   if(!onlyIfLost||document.activeElement===document.body)folderNameRef.current?.focus({preventScroll:true});
  });
 }
 function renameFolder(event,folder){
  event.preventDefault();const value=name.trim();
  if(!value||value.toLowerCase()==='home'){setError('Choose a folder name other than Home.');return;}
  const next={...prefs,folderNames:{...prefs.folderNames,...Object.fromEntries(folder.sourceIds.map(id=>[id,value]))}};
  const after=effectiveWorkspace(registry,new Set(registry.map(app=>app.id)),next);
  save(next,'Folder renamed.');setModal({type:'folder',folderId:after.aliases.get(folder.id)});setError('');
  if(event.type==='submit')focusFolderName();
  else if(!event.relatedTarget)focusFolderName(true);
 }
 function beginRename(folder){setName(folder.name);setError('');setModal({type:'folder',folderId:folder.id,renaming:true});}
 function nudge(entry,container,key){
  const section=document.querySelector('[data-grid-key^="'+container+':"]'),cols=Number(section.dataset.columns);
  const layout=responsiveGrid(workspaceGridItems(workspace,prefs,container),prefs.gridLayouts,container,cols);
  const [dx,dy]={ArrowLeft:[-1,0],ArrowRight:[1,0],ArrowUp:[0,-1],ArrowDown:[0,1]}[key];
  const next=moveGridItem(layout,entry.id,dx,dy,cols);
  if(JSON.stringify(cleanGridLayout(next))!==JSON.stringify(cleanGridLayout(layout)))save(layoutPreferences(prefs,container,section.dataset.gridKey,next),'Position saved.');
 }
 function clearDrag(){
  const drag=dragRef.current;if(drag?.timer)clearTimeout(drag.timer);
  dragRef.current=null;setDragView(null);
  if(drag?.moved)setTimeout(()=>{suppressClick.current=false;},0);
  if(drag?.root.hasPointerCapture?.(drag.pointerId))drag.root.releasePointerCapture(drag.pointerId);
 }
 function startDrag(container,key,items,layout,event){
  if(!arranging||event.button!==0||event.isPrimary===false||event.target.closest('input,textarea,select,.no-drag,.react-resizable-handle'))return;
  const root=event.currentTarget,cell=event.target.closest('[data-grid-id]'),entry=items.find(item=>item.id===cell?.dataset.gridId);if(!entry)return;
  const grid=root.getBoundingClientRect(),rect=cell.getBoundingClientRect(),dialog=root.closest('dialog');
  const relative=rect=>({left:rect.left-grid.left,top:rect.top-grid.top,right:rect.right-grid.left,bottom:rect.bottom-grid.top});
  const targets=[...root.querySelectorAll('[data-grid-id]')].filter(node=>node!==cell).map(node=>{
   const item=items.find(item=>item.id===node.dataset.gridId);
   return {id:item.id,item,rect:relative(node.getBoundingClientRect()),
    combine:!!entry.widget&&!!item.folder||entry.app?.policy!=='required'&&!!entry.app&&(!!item.folder||!!item.app&&item.app.policy!=='required'&&(container==='home'||(workspace.folders?.find(folder=>folder.id===container)?.depth||1)<3))};
  });
  dragRef.current={container,key,entry,original:cleanGridLayout(layout),cols:Number(root.dataset.columns),root,dialog,targets,pointerId:event.pointerId,
   origin:{x:event.clientX,y:event.clientY},point:{x:event.clientX,y:event.clientY},grab:{x:event.clientX-rect.left,y:event.clientY-rect.top},width:rect.width,height:rect.height,moved:false};
 }
 function moveDrag(event){
  const drag=dragRef.current;if(!drag||drag.pointerId!==event.pointerId)return;
  drag.point={x:event.clientX,y:event.clientY};
  if(!drag.moved&&Math.hypot(drag.point.x-drag.origin.x,drag.point.y-drag.origin.y)<6)return;
  if(!drag.moved)drag.root.setPointerCapture(event.pointerId);
  drag.moved=true;suppressClick.current=true;event.preventDefault();
  const grid=drag.root.getBoundingClientRect(),bounds=drag.dialog?.getBoundingClientRect();
  const outside=bounds&&(drag.point.x<bounds.left||drag.point.x>bounds.right||drag.point.y<bounds.top||drag.point.y>bounds.bottom);
  const intent=outside?(drag.entry.folder||drag.entry.widget||drag.entry.app?.policy!=='required'&&drag.entry.app?{type:'home'}:{type:'cancel'}):HubPlacement.hitTest({point:{x:drag.point.x-grid.left,y:drag.point.y-grid.top},targets:drag.targets,source:drag.original.find(cell=>cell.i===drag.entry.id),grab:drag.grab,cols:drag.cols,width:grid.width});
  const same=JSON.stringify(intent)===JSON.stringify(drag.intent);
  if(!same){if(drag.timer)clearTimeout(drag.timer);drag.timer=null;drag.ready=false;drag.intent=intent;}
  if(intent.type==='combine'){
   const target=drag.targets.find(target=>target.id===intent.targetId);
   if(target.item.folder)drag.ready=true;
   else if(!drag.ready&&!drag.timer)drag.timer=setTimeout(()=>{if(dragRef.current===drag){drag.ready=true;setDragView({...drag});}},500);
  }
  setDragView({...drag});
 }
 function finishDrag(event){
  const drag=dragRef.current;if(!drag||drag.pointerId!==event.pointerId)return;
  moveDrag(event);const {intent,entry,container,key,original,cols,ready}=drag;clearDrag();
  if(!drag.moved)return;
  if(intent.type==='combine'&&ready){
   const target=drag.targets.find(target=>target.id===intent.targetId).item;
   if(target.folder){
    const next=entry.widget?moveWidgetPreferences(workspace,prefs,entry.widget.id,target.folder.id):moveAppsPreferences(workspace,prefs,[entry.app.id],target.folder.id);
    save(layoutPreferences(next,container,key,original.filter(cell=>cell.i!==entry.id)),(entry.widget?'Widget':'App')+' added to '+target.folder.name+'.');open({type:'folder',folderId:target.folder.id});
   }else{
    const folderId='personal-'+crypto.randomUUID(),next=combineAppsPreferences(workspace,prefs,entry.app.id,target.app.id,folderId,container);
    const layout=original.filter(cell=>cell.i!==entry.id).map(cell=>cell.i===target.id?{...cell,i:'folder-'+folderId}:cell);
    save(layoutPreferences(next,container,key,layout),'Folder created.');open({type:'folder',folderId});
   }
  }else if(intent.type==='home'){
   if(entry.folder)save(moveFolderPreferences(workspace,prefs,entry.folder.id,'home'),entry.folder.name+' moved to Home.');
   else if(entry.widget)save(moveWidgetPreferences(workspace,prefs,entry.widget.id,'home'),entry.widget.name+' moved to Home.');
   else moveApp(entry.app,'home');
   setModal(null);
  }
  else{
   const layout=HubPlacement.place(original,entry.id,intent,cols);
   if(JSON.stringify(layout)!==JSON.stringify(original))save(layoutPreferences(prefs,container,key,layout),'Position saved.');
  }
 }
 function layoutPreferences(base,container,key,layout){
  const cleaned=cleanGridLayout(layout),order=[...cleaned].sort((a,b)=>a.y-b.y||a.x-b.x).map(cell=>cell.i);
  const nextWorkspace=effectiveWorkspace(registry,new Set(registry.map(app=>app.id)),base);
  const items=workspaceGridItems(nextWorkspace,base,container);
  const gridLayouts={...base.gridLayouts};
  // Freeze initial arrangements before saving this edit so another size cannot
  // silently inherit the edit later. Existing size layouts remain untouched.
  for(const columns of [2,3,4,6]){
   const sizeKey=container+':'+columns;
   if(!Object.hasOwn(gridLayouts,sizeKey))gridLayouts[sizeKey]=cleanGridLayout(responsiveGrid(items,base.gridLayouts,container,columns));
  }
  const unavailable=cell=>cell.i.startsWith('app-')?!registry.some(app=>'app-'+app.id===cell.i):cell.i.startsWith('widget-')?!widgetRegistry.some(widget=>'widget-'+widget.id===cell.i):cell.i.startsWith('folder-')?!nextWorkspace.folders.some(folder=>'folder-'+folder.id===cell.i):false;
  gridLayouts[key]=[...cleaned,...(base.gridLayouts[key]||[]).filter(unavailable)];
  return {...base,gridLayouts,...(container==='home'?{rootOrder:order}:{orders:{...base.orders,[container]:order}})};
 }
 function finishResize(container,key,layout){
  const original=responsiveGrid(workspaceGridItems(workspace,prefs,container),prefs.gridLayouts,container,Number(key.split(':').at(-1)));
  if(JSON.stringify(cleanGridLayout(layout))!==JSON.stringify(cleanGridLayout(original)))save(layoutPreferences(prefs,container,key,layout),'Widget resized.');
 }
 function hideEntry(entry){
  if(!arranging||dragRef.current?.moved)return;
  if(entry.widget){save({...prefs,hiddenWidgets:[...new Set([...prefs.hiddenWidgets,entry.widget.id])]},'Widget hidden.');return;}
  if(entry.app){if(entry.app.policy==='required')return;save({...prefs,hidden:[...new Set([...prefs.hidden,entry.app.id])]},'Shortcut hidden. It remains in search.');return;}
  const next=removeFolderPreferences(workspace,prefs,entry.folder.id);
  save({...next,hidden:[...new Set([...next.hidden,...folderApps(entry.folder).map(app=>app.id)])],hiddenWidgets:[...new Set([...next.hiddenWidgets,...folderWidgets(entry.folder).map(widget=>widget.id)])]},'Folder and its contents hidden. Use Add to restore them.');
 }
 function hideControl(entry){
  if(!arranging||entry.app?.policy==='required')return null;
  const label=entry.widget?'Hide '+entry.widget.name+' widget':entry.folder?'Hide '+entry.folder.name+' folder and its contents':'Hide '+appLabel(entry.app)+' shortcut';
  return (
    <button
      type="button"
      className={
        'item-hide no-drag absolute z-[4] grid touch-manipulation place-items-center border-0 bg-transparent p-0 text-ink ' +
        "before:absolute before:size-6 before:rounded-full before:border before:border-solid before:border-edge before:bg-canvas before:shadow-[0_2px_5px_#0001] before:content-[''] hover:before:bg-hover [&>.icon]:relative [&>.icon]:text-[14px] [&>.icon]:leading-none " +
        (entry.widget ? '-right-3 -top-3 size-11' : '-right-1.5 -top-1.5 size-8')
      }
      aria-label={label}
      title={label}
      onClick={(event) => {
        event.preventDefault();
        event.stopPropagation();
        uiActions.current.hideEntry(entry);
      }}
    >
      <Icon name="minus" />
    </button>
  );
 }
 function navigateFolder(id){setError('');setModal(id==='home'?null:{type:'folder',folderId:id});}
 function folderNavigation(id,onNavigate,currentName){
  const ancestors=folderAncestors(workspace,id);
  const crumbButton='border-0 bg-transparent px-0.5 py-1.5 text-muted [overflow-wrap:anywhere] aria-[current]:font-semibold aria-[current]:text-ink';
  return (
    <div className={'flex min-w-0 items-center gap-3 ' + (currentName ? 'flex-1' : 'mb-6')}>
      <nav
        className={
          'flex min-w-0 flex-wrap items-center gap-1.5 [&>.icon]:shrink-0 [&>.icon]:text-[14px] [&>.icon]:leading-none ' +
          (currentName ? 'folder-compact:flex-1 folder-compact:[&>.icon]:hidden' : '')
        }
        aria-label="Folder location"
      >
        {[
          {
            id: 'home',
            name: 'Home'
          },
          ...ancestors
        ].map((folder, index) => (
          <React.Fragment key={folder.id}>
            {index > 0 && <Icon name="right" />}
            {folder.id === id && currentName ? (
              currentName
            ) : (
              <button
                type="button"
                className={crumbButton + (currentName ? ' folder-compact:hidden' : '')}
                aria-current={folder.id === id ? 'location' : undefined}
                onClick={() => onNavigate(folder.id)}
              >
                {folder.name}
              </button>
            )}
          </React.Fragment>
        ))}
      </nav>
    </div>
  );
 }
 function openMove(entry,container){
  setError('');setModal({type:'move',entry,destination:container,returnTo:container==='home'?null:container});
 }
 function finishMove(){
  try{
   const {entry,destination}=modal;
   const next=entry.widget?moveWidgetPreferences(workspace,prefs,entry.widget.id,destination):entry.app?moveAppsPreferences(workspace,prefs,[entry.app.id],destination):moveFolderPreferences(workspace,prefs,entry.folder.id,destination);
   save(next,(entry.widget?.name||entry.app?.name||entry.folder.name)+' moved to '+locationLabel(destination)+'.');closeModal();
  }catch(error){setError(error.message);}
 }
 function createFolder(event){
  event.preventDefault();
  const value=name.trim(),parentId=modal.destination||'home';
  if(!value||folderNameKey(value)==='home'){setError('Choose a folder name other than Home.');return;}
  if((folderById(parentId)?.depth||0)>=3){setError('Folders can be at most three levels deep.');return;}
  const existing=workspace.folders.find(folder=>folder.parentId===parentId&&folderNameKey(folder.name)===folderNameKey(value));
  if(existing){navigateFolder(existing.id);return;}
  const id='personal-'+crypto.randomUUID();
  save({...prefs,folders:[...prefs.folders,{id,name:value,parentId,org:false}]},'Folder created.');
  setModal({type:'folder',folderId:id});setError('');
 }
 function startCreate(parentId){setName('');setError('');setModal({type:'create-folder',destination:parentId,returnTo:parentId==='home'?null:parentId});}
 function tile(entry,container='home'){return (
   <LauncherTile
     key={entry.id}
     entry={entry}
     container={container}
     arranging={arranging}
     showContext={!HubHost.workspaceSelection}
     {...tileActions}
   />
 );}
 function launcherGrid(container,label){
  const items=workspaceGridItems(workspace,prefs,container).map(entry=>({...entry,node:(
    <React.Fragment>
      {entry.widget ? (
        <WidgetCard
          widget={entry.widget}
          showContext={!HubHost.workspaceSelection}
          onAction={(action) => uiActions.current.openWidget(entry.widget, action, container)}
        />
      ) : (
        tile(entry, container)
      )}
      {hideControl(entry)}
      {arranging && entry.app?.policy !== 'required' && (
        <button
          type="button"
          className={
            'no-drag absolute -top-1.5 right-[26px] z-[5] grid size-8 touch-manipulation place-items-center border-0 bg-transparent p-0 text-ink ' +
            "before:absolute before:size-6 before:rounded-full before:border before:border-solid before:border-edge before:bg-canvas before:shadow-[0_2px_5px_#0001] before:content-[''] hover:before:bg-hover [&>.icon]:relative [&>.icon]:text-[14px] [&>.icon]:leading-none"
          }
          aria-label={'Move ' + (entry.widget?.name || entry.app?.name || entry.folder.name) + ' to…'}
          title="Move to…"
          onClick={() => openMove(entry, container)}
        >
          <Icon name="right" />
        </button>
      )}
    </React.Fragment>
  )}));
  return (
    <LauncherLayoutGrid
      key={container}
      items={items}
      label={label}
      container={container}
      gridLayouts={prefs.gridLayouts}
      columns={container === 'home' ? prefs.gridColumns || 3 : 6}
      arranging={arranging}
      showContext={!HubHost.workspaceSelection}
      dragId={dragView?.container === container ? dragView.entry.id : null}
      onStart={startDrag}
      onCancel={clearDrag}
      onResize={finishResize}
    />
  );
 }
 const modalContent=()=>{
  if(!modal)return null;
  if(modal.type==='login-as'&&HubHost.isSuperAdmin)return <LoginAsDialog key="login-as" onClose={closeModal} />;
  if(modal.type==='search'){
   const items=[...registry.filter(app=>app.hasShortcut).map(app=>{const location=locationOf(app);return {id:'app-'+app.id,name:app.name,detail:[itemOrigin(app),location&&folderAncestors(workspace,location).map(folder=>folder.name).join(' / ')].filter(Boolean).join(' · '),icon:app.icon,category:'App',app};}),...workspace.folders.filter(folder=>folder.entries.length||!folder.org).map(folder=>({id:'folder-'+folder.id,name:folder.name,detail:folderAncestors(workspace,folder.id).map(item=>item.name).join(' / '),icon:'folder',category:'Folder',folder}))];
   return (
     <SearchPalette
       key="search"
       items={items}
       onClose={closeModal}
       onChoose={(item) =>
         item.app
           ? open({
               type: 'app',
               app: item.app,
               returnTo: modal.returnTo
             })
           : open({
               type: 'folder',
               folderId: item.folder.id
             })
       }
     />
   );
  }
  if(modal.type==='folder'){
   const folder=folderById(modal.folderId);if(!folder)return null;
   const currentName=modal.renaming
    ? (
      <form
        className="min-w-[90px] flex-[0_1_200px] folder-compact:min-w-0 folder-compact:flex-1"
        onSubmit={(event) => renameFolder(event, folder)}
      >
        <input
          className={dialogControl + ' w-full min-w-0 rounded-lg px-[9px] py-1.5 text-[18px] font-semibold'}
          aria-label="Folder name"
          autoFocus={true}
          maxLength={32}
          value={name}
          onChange={(event) => setName(event.target.value)}
          onBlur={(event) => renameFolder(event, folder)}
          onKeyDown={(event) => {
            if (event.key !== 'Escape') return;
            event.preventDefault();
            event.stopPropagation();
            navigateFolder(folder.id);
            focusFolderName();
          }}
        />
      </form>
    )
    : (
      <button
        ref={folderNameRef}
        type="button"
        className="min-w-0 flex-initial cursor-text border-0 bg-transparent px-0.5 py-1.5 text-left text-[18px] font-semibold text-ink [overflow-wrap:anywhere] folder-compact:block folder-compact:truncate"
        aria-current="location"
        aria-label={'Rename ' + folder.name}
        title="Rename folder"
        onClick={() => beginRename(folder)}
      >
        {folder.name}
      </button>
    );
   const dismissMore=()=>{navigateFolder(folder.id);requestAnimationFrame(()=>folderMoreRef.current?.focus());};
   const actions=[
    folder.depth<3&&{label:'Create folder',description:'Create folder in '+folder.name,icon:'folder',run:()=>startCreate(folder.id)},
    !arranging&&{label:'Edit layout',icon:'layout',run:()=>{if(modal.more)navigateFolder(folder.id);enterArrange();}},
    {label:'Add apps or widgets',description:'Add apps or widgets to '+folder.name,icon:'plus',disabled:arranging,run:()=>open({type:'catalog',destination:folder.id,returnTo:folder.id})}
   ].filter(Boolean);
   const headerActions=(
     <React.Fragment>
       <div className="flex shrink-0 items-center gap-1 folder-compact:hidden">
         {actions.map((item) => (
           <IconButton
             key={item.label}
             label={item.description || item.label}
             icon={item.icon}
             onClick={item.run}
             disabled={item.disabled}
           />
         ))}
       </div>
       {arranging ? (
         <button
           type="button"
           className={
             doneButtonClass +
             ' min-w-[54px] folder-compact:min-w-11 folder-compact:min-h-11 folder-compact:flex-none'
           }
           onClick={exitArrange}
         >
           Done
         </button>
       ) : (
         <button
           ref={folderMoreRef}
           type="button"
           className={compactFolderNav}
           aria-label="More"
           title="More"
           aria-haspopup="dialog"
           onClick={() =>
             setModal({
               ...modal,
               more: true
             })
           }
         >
           <Icon name="more" />
         </button>
       )}
     </React.Fragment>
   );
   const titleContent=(
     <React.Fragment>
       <button
         type="button"
         className={compactFolderNav}
         aria-label="Back"
         title="Back"
         onClick={() => navigateFolder(folder.parentId)}
       >
         <Icon name="left" />
       </button>
       {folderNavigation(folder.id, navigateFolder, currentName)}
     </React.Fragment>
   );
   return (
     <React.Fragment>
       <Modal
         key="folder-browser"
         title={folder.name}
         titleContent={titleContent}
         onClose={() => setModal(null)}
         folder={true}
         headerAction={headerActions}
       >
         {error && (
           <p className="mx-0 my-3 text-[13px] leading-[1.6] text-danger" role="alert">
             {error}
           </p>
         )}
         {launcherGrid(folder.id, folder.name + ' apps, folders and widgets')}
         {!folder.entries.length && (
           <div className="px-2 py-12 text-center text-[13px] text-muted">
             <p className="leading-[1.6]">Add apps or widgets here.</p>
             <Button
               onClick={() =>
                 open({
                   type: 'catalog',
                   destination: folder.id,
                   returnTo: folder.id
                 })
               }
             >
               Add apps or widgets
             </Button>
           </div>
         )}
       </Modal>
       {modal.more && (
         <Modal key="folder-more" title="More" {...moreDialogProps} onClose={dismissMore}>
           <nav
             className={'grid py-1 [border-bottom:1px_solid_var(--edge)] [&_.icon]:flex-none'}
             aria-label="Folder location"
           >
             {[
               {
                 id: 'home',
                 name: 'Home'
               },
               ...folderAncestors(workspace, folder.id)
             ].map((crumb) =>
               crumb.id === folder.id ? (
                 <span
                   key={crumb.id}
                   className={
                     menuActionClass + ' aria-[current=location]:font-semibold [overflow-wrap:anywhere]'
                   }
                   aria-current="location"
                 >
                   <Icon name="folder" />
                   {crumb.name}
                 </span>
               ) : (
                 <button
                   key={crumb.id}
                   type="button"
                   className={menuActionClass + ' [overflow-wrap:anywhere]'}
                   onClick={() => navigateFolder(crumb.id)}
                 >
                   <Icon name="left" />
                   {crumb.name}
                 </button>
               )
             )}
           </nav>
           <div className="py-1">
             {actions.map((item) => (
               <button
                 key={item.label}
                 type="button"
                 className={menuActionClass}
                 onClick={item.run}
                 disabled={item.disabled}
               >
                 <Icon name={item.icon} />
                 {item.label}
               </button>
             ))}
           </div>
         </Modal>
       )}
     </React.Fragment>
   );
  }
  if(modal.type==='move'){
   const {entry,destination}=modal,canMove=id=>!entry.folder||canMoveFolder(workspace,entry.folder.id,id);
   const current=entry.folder?.parentId||(entry.widget?prefs.widgetPlacements?.[entry.widget.id]||'home':locationOf(entry.app));
   return (
     <Modal
       key="move"
       title={'Move ' + (entry.widget?.name || entry.app?.name || entry.folder.name)}
       onClose={closeModal}
     >
       {folderNavigation(destination, (id) =>
         setModal({
           ...modal,
           destination: id
         })
       )}
       <div className="grid max-h-[45dvh] gap-2 overflow-auto p-1">
         {workspace.folders
           .filter((folder) => folder.parentId === destination)
           .map((folder) => (
             <button
               key={folder.id}
               type="button"
               className="flex items-center gap-3 rounded-xl border border-solid border-edge bg-[var(--panel)] p-3.5 text-left text-ink disabled:opacity-[.45]"
               disabled={!canMove(folder.id)}
               onClick={() =>
                 setModal({
                   ...modal,
                   destination: folder.id
                 })
               }
             >
               <Icon name="folder" />
               <span className="flex-1 [overflow-wrap:anywhere]">{folder.name}</span>
               <Icon name="right" />
             </button>
           ))}
       </div>
       {error && (
         <p className="mx-0 my-3 text-[13px] leading-[1.6] text-danger" role="alert">
           {error}
         </p>
       )}
       <div className="mt-5 flex justify-end gap-2.5">
         <Button onClick={closeModal}>Cancel</Button>
         <Button
           primary={true}
           disabled={!canMove(destination) || destination === current}
           onClick={finishMove}
         >
           Move here
         </Button>
       </div>
     </Modal>
   );
  }
  if(modal.type==='create-folder')return (
    <Modal key="create-folder" title="Create folder" onClose={closeModal}>
      <form onSubmit={createFolder}>
        <label className="my-[15px] grid gap-2 text-[12px]">
          Folder name
          <input
            className={dialogTextInput}
            value={name}
            maxLength={32}
            required={true}
            onChange={(event) => setName(event.target.value)}
          />
        </label>
        {error && (
          <p className="mx-0 my-3 text-[12px] text-danger" role="alert">
            {error}
          </p>
        )}
        <div className="mt-5 flex justify-end gap-2.5">
          <Button onClick={closeModal}>Cancel</Button>
          <Button primary={true} type="submit">
            Create
          </Button>
        </div>
      </form>
    </Modal>
  );
  if(modal.type==='catalog'){
   const destination=modal.destination||'home',needle=query.trim().toLowerCase();
   const entries=[...registry.filter(app=>app.hasShortcut&&!locationOf(app)).map(app=>({id:'app-'+app.id,type:'App',name:app.name,description:app.description,app})),...widgetRegistry.filter(widget=>!workspace.widgets.some(visible=>visible.id===widget.id)).map(widget=>({id:'widget-'+widget.id,type:'Widget',name:widget.name,description:widget.description,widget,app:widget}))];
   const results=entries.filter(item=>(item.name+' '+item.description+' '+itemOrigin(item.widget||item.app)+' '+itemTagText(item.widget||item.app)).toLowerCase().includes(needle)).sort((a,b)=>a.name.localeCompare(b.name)||itemOrigin(a.widget||a.app).localeCompare(itemOrigin(b.widget||b.app))||a.type.localeCompare(b.type));
   return (
     <Modal key="catalog" title={'Add to ' + locationLabel(destination)} onClose={closeModal}>
       {(folderById(destination)?.depth || 0) < 3 && (
         <div className="mb-4 flex items-center gap-2.5">
           <Button onClick={() => startCreate(destination)}>
             <Icon name="folder" />
             Create folder
           </Button>
         </div>
       )}
       <input
         className={dialogTextInput}
         type="search"
         aria-label="Find apps or widgets"
         placeholder="Find apps or widgets…"
         value={query}
         onChange={(event) => setQuery(event.target.value)}
       />
       <div className="mt-3.5 max-h-[45vh] overflow-auto overscroll-contain pe-4 [scrollbar-gutter:stable] phone:max-h-[48vh]">
         {results.length ? (
           results.map((item) => {
             return (
               <div
                 className="flex items-center gap-3 border-0 border-b border-solid border-edge py-3.5 last:border-0 phone:gap-[9px]"
                 key={item.id}
                 data-catalog-kind={item.type.toLowerCase()}
               >
                 <span
                   className="grid size-10 shrink-0 place-items-center rounded-xl bg-[var(--app-color)] text-[color:var(--app-ink,var(--icon-ink))]"
                   style={appIconStyle(item.app)}
                 >
                   {item.widget ? (
                     <Icon name={item.widget.type === 'clock' ? 'clock' : 'chart'} />
                   ) : (
                     <AppIcon app={item.app} />
                   )}
                 </span>
                 <div className="min-w-0 flex-1">
                   <div className="flex flex-wrap items-baseline gap-2">
                     <strong className="block text-[13px] font-[550] [overflow-wrap:anywhere]">
                       {item.name}
                     </strong>
                     <ItemContext item={item.widget || item.app} />
                     <span className="whitespace-nowrap text-[10px] text-muted">{item.type}</span>
                   </div>
                   {item.description && (
                     <small className="mt-1 block text-[11px] leading-[1.5] text-muted">
                       {item.description}
                     </small>
                   )}
                 </div>
                 <button
                   type="button"
                   className="small shrink-0"
                   aria-label={
                     'Add ' +
                     item.name +
                     ' ' +
                     item.type.toLowerCase() +
                     (itemOrigin(item.widget || item.app) ? ', ' + itemOrigin(item.widget || item.app) : '')
                   }
                   onClick={() =>
                     item.widget
                       ? save(
                           moveWidgetPreferences(workspace, prefs, item.widget.id, destination),
                           'Widget added.'
                         )
                       : save(
                           moveAppsPreferences(workspace, prefs, [item.app.id], destination),
                           item.name + ' added.'
                         )
                   }
                 >
                   Add
                 </button>
               </div>
             );
           })
         ) : (
           <div className="px-2 py-12 text-center text-[13px] text-muted">
             {needle ? 'No matching hidden items.' : 'Everything available is already on your launcher.'}
           </div>
         )}
       </div>
     </Modal>
   );
  }
  if(modal.type==='appearance'){
   const label='text-[12px] font-semibold text-muted';
   const heading='m-0 mb-2.5 '+label;
   const setting='grid grid-cols-[64px_minmax(0,1fr)] items-center gap-x-4 gap-y-2';
   const select=dialogControl+' w-full min-w-0 min-h-10 rounded-[9px] px-2.5 py-2 text-[12px]';
   const help='col-start-2 m-0 !text-[11px] !leading-[1.5] text-muted';
   const range='mx-0 mb-0 mt-1 block h-8 w-full cursor-pointer accent-[var(--accent)] disabled:cursor-default disabled:opacity-40';
   const rangeLabel='flex items-center justify-between text-[12px] text-muted';
   return (
     <Modal
       key="appearance"
       title="Appearance"
       className={
         'appearance-dialog mx-auto mb-auto mt-[var(--launcher-dialog-top)] w-[min(460px,calc(100%-32px))] overscroll-contain open:flex open:flex-col open:overflow-hidden [&>.dialoghead]:shrink-0'
       }
       bodyClassName={
         dialogPadding + ' min-h-0 space-y-6 overflow-y-auto overscroll-contain [scrollbar-gutter:stable]'
       }
       focusInput={false}
       onClose={closeModal}
     >
       {!HubHost.inTeams && (
         <section aria-labelledby="theme-heading">
           <h3 id="theme-heading" className={heading}>
             Theme
           </h3>
           <div className="flex gap-1.5 phone:flex-wrap">
             {['system', 'light', 'dark'].map((value) => (
               <button
                 type="button"
                 className={
                   'small flex-1 ' +
                   dialogControl +
                   ' aria-pressed:border-accent aria-pressed:bg-[color:color-mix(in_srgb,var(--control-bg),var(--accent)_10%)] aria-pressed:text-accent'
                 }
                 key={value}
                 aria-pressed={theme === value}
                 onClick={() => setAppearance(value)}
               >
                 {value[0].toUpperCase() + value.slice(1)}
               </button>
             ))}
           </div>
         </section>
       )}
       <section className={setting}>
         <label htmlFor="launcher-columns" className={label}>
           Columns
         </label>
         <select
           id="launcher-columns"
           className={select}
           value={prefs.gridColumns || 3}
           onChange={(event) =>
             persist({
               ...prefs,
               gridColumns: Number(event.target.value)
             })
           }
         >
           {[3, 4, 6].map((value) => (
             <option key={value} value={value}>
               {value + ' columns'}
             </option>
           ))}
         </select>
         <p className={help}>Fewer columns give names more room. Smaller windows adapt automatically.</p>
       </section>
       <section aria-labelledby="background-heading">
         <h3 id="background-heading" className={heading}>
           Background
         </h3>
         <div className="grid grid-cols-3 gap-2.5 phone:gap-y-3">
           {backgrounds.map((item) => (
             <button
               type="button"
               className="background-choice min-w-0 rounded-[10px] border-0 bg-transparent p-0 text-center text-[12px] text-ink"
               key={item.id}
               aria-label={item.name + ' background'}
               aria-pressed={background === item.id}
               onClick={() => chooseBackground(item.id)}
             >
               <span className="background-preview relative grid aspect-[1.8] w-full place-items-center overflow-hidden rounded-[10px] bg-surface shadow-[inset_0_0_0_1px_var(--edge)]">
                 {item.image ? (
                   <img className="block size-full object-cover" src={item.image} alt="" decoding="async" />
                 ) : (
                   HubIcons.render('photo-off', {
                     className: 'text-[24px] font-light text-muted'
                   })
                 )}
                 {background === item.id && (
                   <span className="absolute right-[7px] top-[7px] grid size-5 place-items-center rounded-full bg-[var(--color-blue-600)] text-[color:var(--color-white)] shadow-[0_1px_4px_#0003]">
                     {HubIcons.render('tick', {
                       className: 'icon text-[13px] leading-none'
                     })}
                   </span>
                 )}
               </span>
               <span
                 className={'mt-[5px] block leading-[18px]' + (background === item.id ? ' text-accent' : '')}
               >
                 {item.name}
               </span>
             </button>
           ))}
         </div>
       </section>
       <section className={setting}>
         <label htmlFor="background-fit" className={label}>
           Image fit
         </label>
         <select
           id="background-fit"
           className={select}
           value={backgroundFit}
           disabled={background === 'none'}
           aria-describedby="background-fit-description"
           onChange={(event) => chooseBackgroundFit(event.target.value)}
         >
           {backgroundFitOptions.map((option) => (
             <option key={option.value} value={option.value}>
               {option.name}
             </option>
           ))}
         </select>
         <p id="background-fit-description" className={help}>
           {selectedFit.description}
         </p>
       </section>
       {backgroundFit === 'fill' && (
         <section className={setting}>
           <label htmlFor="background-position" className={label}>
             Position
           </label>
           <select
             id="background-position"
             className={select}
             value={backgroundPosition}
             disabled={background === 'none'}
             onChange={(event) => chooseBackgroundPosition(event.target.value)}
           >
             {backgroundPositionsOptions.map((option) => (
               <option key={option.value} value={option.value}>
                 {option.name}
               </option>
             ))}
           </select>
         </section>
       )}
       <section>
         <div className={rangeLabel}>
           <label htmlFor="background-blur" className="font-semibold">
             Blur
           </label>
           <output htmlFor="background-blur" className="tabular-nums">
             {backgroundBlur + ' px'}
           </output>
         </div>
         <input
           id="background-blur"
           className={range}
           type="range"
           aria-label="Background blur"
           min={0}
           max={24}
           step={1}
           value={backgroundBlur}
           disabled={background === 'none'}
           onChange={(event) => chooseBackgroundBlur(Number(event.target.value))}
         />
       </section>
       <section>
         <div className={rangeLabel}>
           <label htmlFor="background-dimming" className="font-semibold">
             Dimming
           </label>
           <output htmlFor="background-dimming" className="tabular-nums">
             {activeDimming + '%'}
           </output>
         </div>
         <input
           id="background-dimming"
           className={range}
           type="range"
           aria-label="Background dimming"
           aria-describedby="background-dimming-description"
           min={0}
           max={100}
           step={1}
           value={activeDimming}
           disabled={background === 'none'}
           onChange={(event) => chooseBackgroundDimming(Number(event.target.value))}
         />
         <p id="background-dimming-description" className="text-muted">
           Saved separately for light and dark mode.
         </p>
       </section>
     </Modal>
   );
  }
 };
 const header=(
   <HomeToolbar
     arranging={arranging}
     onEdit={enterArrange}
     onDone={exitArrange}
     open={open}
     moreOpen={modal?.type === 'home-more'}
     closeMore={closeModal}
   />
 );
 return (
   <div>
     {storageError && (
       <div className="bg-surface px-5 py-[15px] text-[13px] text-danger" role="alert">
         {storageError}
       </div>
     )}
     <div
       style={
         hosted
           ? {
               visibility: 'hidden'
             }
           : undefined
       }
       inert={hosted ? '' : undefined}
       className={
         'shell hub-page mx-auto flex w-full flex-col px-[clamp(14px,2.34375vw,30px)] pt-5 [@media(480px<width<=760px)]:pt-3 phone:pt-2 [&>.hub-footer]:mt-auto' +
         (arranging ? ' arranging' : '')
       }
     >
       {header}
       <main
         className="workspace mx-[var(--launcher-gutter)] pb-10 pt-[var(--workspace-gap)] [--workspace-gap:32px] [@media(max-width:760px)]:pb-8 [@media(max-width:760px)]:[--workspace-gap:28px]"
         data-safe-edge="top"
         aria-label="Home launcher"
       >
         {(hubSession?.providers.some((provider) => !provider.available) ||
           compiledManifests.errors.length > 0) && (
           <p className="text-[12px] text-muted" role="status">
             Some items are temporarily unavailable. Your layout is preserved.
           </p>
         )}
         {!registry.length && hubSession && (
           <p className="text-[12px] text-muted">No apps are available yet.</p>
         )}
         {launcherGrid('home', 'Apps, folders and widgets')}
       </main>
       <HubContent.Footer />
     </div>
     {!hosted && modalContent()}
     {dragView && (
       <PlacementOverlay drag={dragView}>
         {dragView.entry.widget ? (
           <div
             className="widget-wrap widget relative flex h-full min-h-0 min-w-0 flex-col overflow-hidden rounded-[18px] bg-surface p-6 [@media(max-width:760px)]:p-5"
             aria-hidden={true}
           >
             <h2>{dragView.entry.widget.name}</h2>
           </div>
         ) : (
           tile(dragView.entry, dragView.container)
         )}
       </PlacementOverlay>
     )}
     {hosted && <HostedApp key={hosted.page.url} page={hosted.page} onClose={closeApp} />}
   </div>
 );
}
function restoreServerPreferences(session){
 if(HubHost.loginAs||HubHost.savedPreferences||!session.previousLayoutKey)return;
 let prior;
 try{prior=JSON.parse(localStorage.getItem('efhub:nh:home-layout:'+encodeURIComponent(session.previousLayoutKey)+':v1')||'null');}catch{return;}
 if(!prior)return;
 const ids=new Map();
 for(const item of [...session.apps,...session.widgets,...session.folders])if(item.sourceId){ids.set(item.sourceId,item.id);ids.set('app-'+item.sourceId,'app-'+item.id);ids.set('folder-'+item.sourceId,'folder-'+item.id);for(const n of [2,3,4,6])ids.set(item.sourceId+':'+n,item.id+':'+n);}
 function map(value){if(typeof value==='string')return ids.get(value)||value;if(Array.isArray(value))return value.map(map);if(value&&typeof value==='object')return Object.fromEntries(Object.entries(value).map(([key,v])=>[ids.get(key)||key,map(v)]));return value;}
 const migrated=map(prior);HubHost.savedPreferences=migrated;
 return true;
}
let launcherRoot;
async function startLauncher(root=launcherRoot||(launcherRoot=ReactDOM.createRoot(document.getElementById('root'))),returnWorkspace){
 if(new URLSearchParams(location.search).get('cardPreview')==='1'){HubCardPreview.start({root,registerManifestCatalog,widgetData,LauncherTile,WidgetCard,icons:ICON_NAMES,colors:ICON_COLORS});return;}
 // Keep the initial loader mounted until the catalog and widgets are ready.
 root.render(<HubContent.Loading label="Loading your apps" />);
 try{
  await HubHost.initialize();
  if(HubHost.features?.inbox===true&&new URLSearchParams(location.search).get('view')==='inbox'){
   const destination=new URL(location.href);destination.pathname='/nh/inbox/';destination.searchParams.delete('view');
   location.replace(destination.pathname+destination.search+destination.hash);return;
  }
  if(new URLSearchParams(location.search).get('view')==='account'){
   if(HubHost.loginAs){location.replace(HubHost.homeUrl());return;}
   root.render(<HubAccount.AccountPage />);return;
  }
  const target=HubHost.deepLink();
  if(target){
   root.render((
     <HostedApp
       page={target}
       onClose={() => {
         HubHost.clearDeepLink();
         startLauncher(root, target.workspace);
       }}
     />
   ));return;
  }
  await HubWorkspaces.ensure(root,returnWorkspace);
  hubSession=await HubHost.catalog();
  STORAGE='efhub:nh:home-layout:'+encodeURIComponent(hubSession.layoutKey)+':v1';
  // Providers own permitted entries and initial folders; Hub owns saved placement.
  const catalog={folders:hubSession.folders,widgetOrder:[],apps:hubSession.apps,
   widgets:hubSession.widgets.map(widget=>{
    const filename='provider-data:'+widget.id;widgetData[filename]=widget.data;
    return {...widget,data:filename};
   })
  };
  compiledManifests=registerManifestCatalog(catalog);
  registry=compiledManifests.apps;publishedFolders=compiledManifests.folders;widgetRegistry=[...compiledManifests.widgets, clockWidget];
  Object.assign(window.LauncherModel,{registry,publishedFolders,widgetRegistry});
  window.HubManifests.catalog=catalog;
  const imported=restoreServerPreferences(hubSession);
  initial=loadPreferences();if(imported)initial.needsSave=true;root.render((
    <App key={hubSession.user.email + ':' + (HubHost.loginAs?.sessionId || 'own')} initialTarget={target} />
  ));
 }catch(error){
  HubHost.startupError(root,error,()=>startLauncher(root,returnWorkspace));
 }
}
window.addEventListener('hub-auth-required',event=>{if(launcherRoot)HubHost.signIn(launcherRoot,event.detail);});
window.addEventListener('hub-identity-changed',()=>startLauncher(launcherRoot));
startLauncher();
