"use strict";
window.HubWorkspaces={
  async ensure(root,returnWorkspace){
    const owner=HubHost.user.email;
    if(this.owner!==owner||returnWorkspace){
      const result=await HubHost.request('/api/nh/workspaces');
      this.workspaces=result.workspaces;this.owner=owner;
    }
    const storageKey='ef5-hub:workspace:'+encodeURIComponent(owner);
    const storage=HubHost.nativeHost()||HubHost.inTeams?localStorage:sessionStorage;
    const options=[{key:'all',name:'All workspaces',providers:null},...this.workspaces];
    let saved;try{saved=storage.getItem(storageKey);}catch{}
    const linked=returnWorkspace && this.workspaces.find(workspace=>
      Object.hasOwn(workspace.providers,returnWorkspace.providerKey) && workspace.providers[returnWorkspace.providerKey].includes(returnWorkspace.id));
    let selected=linked || (this.workspaces.length<=1?(this.workspaces[0]||options[0]):options.find(option=>option.key===saved));
    const url=new URL(location.href),force=url.searchParams.get('chooseWorkspace')==='1';
    if(!selected||(force&&this.workspaces.length>1)){
      const previous=selected;
      selected=await new Promise(resolve=>{
        const workspaces=options.slice(1);
        function Chooser(){
          const [error,setError]=React.useState('');
          const [query,setQuery]=React.useState('');
          const [limit,setLimit]=React.useState(50);
          const list=React.useRef(null);
          const filtered=HubWorkspaces.filter(workspaces,query),shown=filtered.slice(0,limit);
          function choose(option){
            try{storage.setItem(storageKey,option.key);resolve(option);}catch{setError('Your workspace choice couldn’t be saved. Allow storage and try again.');}
          }
          function optionButton(option){
            return (
              <button
                key={option.key}
                type="button"
                className={
                  'workspace-choice-option flex w-full shrink-0 cursor-pointer items-center gap-3 rounded-[10px] border border-solid border-edge bg-canvas p-[15px] text-left [font:inherit] text-ink hover:border-accent' +
                  (option.key === 'all' ? ' col-span-full' : '')
                }
                onClick={() => choose(option)}
              >
                {HubIcons.render(option.key === 'all' ? 'layout-grid' : 'building', {
                  className: 'shrink-0 text-[20px]'
                })}
                <span className="min-w-0 flex-1 [overflow-wrap:anywhere]">{option.name}</span>
                {previous?.key === option.key &&
                  HubIcons.render('check', {
                    className: 'shrink-0 text-[20px]'
                  })}
              </button>
            );
          }
          return (
            <main className="workspace-choice-page box-border grid place-items-center bg-canvas p-6 text-ink [@media(max-width:520px)]:p-4">
              <section
                className="workspace-choice box-border flex w-[min(100%,880px)] flex-col rounded-[20px] border border-solid border-edge bg-[var(--card,var(--bg))] p-7 shadow-[0_16px_60px_#0002] [@media(max-width:520px)]:p-5"
                aria-labelledby="workspace-choice-title"
              >
                <header className="workspace-choice-heading">
                  <img
                    className="h-12 w-16 shrink-0 object-contain object-left"
                    src="/sa/evenflow.png"
                    alt="EvenFlow"
                  />
                  <h1
                    id="workspace-choice-title"
                    className="mx-0 mb-5 mt-[18px] shrink-0 text-[26px] tracking-[-.035em]"
                  >
                    Choose a workspace
                  </h1>
                </header>
                {workspaces.length > 8 && (
                  <input
                    type="search"
                    className="mb-3 mt-0 box-border w-full shrink-0 rounded-[10px] border border-solid border-edge bg-canvas p-3 [font:inherit] text-ink"
                    aria-label="Search workspaces"
                    placeholder="Search workspaces"
                    value={query}
                    onChange={(event) => {
                      setQuery(event.target.value);
                      setLimit(50);
                      if (list.current) list.current.scrollTop = 0;
                    }}
                  />
                )}
                <div
                  className="workspace-choice-options -mx-[3px] mb-[18px] mt-0 grid max-h-[65dvh] min-h-0 shrink grid-cols-2 content-start gap-3 overflow-auto p-[3px] [@media(max-width:640px)]:grid-cols-1"
                  ref={list}
                >
                  {optionButton(options[0])}
                  {shown.map(optionButton)}
                  {!filtered.length && (
                    <p role="status" className="col-span-full mx-0 mb-5 mt-0 text-muted">
                      No workspaces found.
                    </p>
                  )}
                  {shown.length < filtered.length && (
                    <button
                      className="small col-span-full"
                      type="button"
                      onClick={() => setLimit((value) => value + 50)}
                    >
                      Show more
                    </button>
                  )}
                </div>
                {filtered.length > 0 && (workspaces.length > 50 || query) && (
                  <small className="mb-3.5 shrink-0 text-muted" role="status">
                    {(shown.length < filtered.length ? shown.length + ' of ' : '') +
                      filtered.length +
                      (filtered.length === 1 ? ' workspace' : ' workspaces')}
                  </small>
                )}
                {error && (
                  <p className="mx-0 mb-5 mt-0 text-muted" role="alert">
                    {error}
                  </p>
                )}
                {previous && (
                  <button className="small shrink-0 self-start" type="button" onClick={() => resolve(previous)}>
                    Cancel
                  </button>
                )}
              </section>
            </main>
          );
        }
        root.render(<Chooser />);
      });
    }
    storage.setItem(storageKey,selected.key);
    this.current=selected;
    HubHost.workspaceSelection=selected.providers;
    if(force){url.searchParams.delete('chooseWorkspace');history.replaceState(null,'',url.pathname+url.search+url.hash);}
    return selected;
  },
  Button({disabled=false,compactHome=false,inbox=false}={}){
    const current=HubWorkspaces.current;
    if(!current||!HubWorkspaces.workspaces?.length)return null;
    const canSwitch=HubWorkspaces.workspaces.length>1;
    let layout='max-w-[240px]';
    if(compactHome)layout='min-h-11 max-w-full justify-start px-2.5 text-[14px] phone:gap-[5px] phone:py-[5px] phone:[&_.ti-building]:hidden';
    if(inbox)layout='max-w-full flex-initial justify-start gap-1.5 border-transparent bg-transparent px-2 py-1.5 shadow-none hover:bg-transparent';
    const Control = canSwitch ? 'button' : 'span';
    return (
      <Control
        className={
          'small workspace-switch min-w-0 shrink text-inherit no-underline ' +
          layout +
          ' ' +
          (canSwitch ? 'cursor-pointer' : 'cursor-default')
        }
        {...(canSwitch
          ? {
              type: 'button',
              disabled,
              onClick: () => HubWorkspaces.switch()
            }
          : {})}
        aria-label={'Workspace: ' + current.name}
        title={'Workspace: ' + current.name}
      >
        {HubIcons.render('building', {
          className: 'shrink-0 text-[18px]'
        })}
        <span className="min-w-0 truncate">{current.name}</span>
        {canSwitch &&
          HubIcons.render('chevron-down', {
            className: 'shrink-0 text-[14px]'
          })}
      </Control>
    );
  },
  filter(workspaces,query){
    const value=query.trim().toLowerCase();return value?workspaces.filter(workspace=>workspace.name.toLowerCase().includes(value)):workspaces;
  },
  switch(){
    const inbox=new URL(location.href).pathname.startsWith('/nh/inbox/');
    const url=new URL(inbox?HubHost.inboxUrl():HubHost.homeUrl(),location.origin);
    url.searchParams.set('chooseWorkspace','1');location.assign(url.pathname+url.search);
  }
};
