'use strict';

Object.assign(HubHost, {
  showSessionExpired(){
    const dialog=document.createElement('dialog');
    dialog.className='session-expired box-border w-[min(400px,calc(100vw_-_40px))] rounded-xl border border-solid border-[#d9dee5] bg-white p-6 text-[#172026] [font:16px/1.5_system-ui,sans-serif] [box-shadow:0_22px_55px_#0f172a2e] backdrop:bg-[#eef1f4f5] dark:border-[#334155] dark:bg-[#182231] dark:text-[#e5edf5] dark:backdrop:bg-[#111827f5]';
    dialog.setAttribute('aria-labelledby','session-expired-title');
    const root = ReactDOM.createRoot(dialog);
    ReactDOM.flushSync(() => root.render(<>
      <h2 id="session-expired-title" className="m-0 mb-3 text-[20px]">Please sign in again</h2>
      <p className="m-0 mb-4">Your session has expired. We will return you to this page after sign-in.</p>
      <p className="m-0 mb-4 text-[13px] text-[#52606d] dark:text-[#bac5d4]">Unsaved changes in an open app may be lost.</p>
      <button type="button" className="flex min-h-11 w-full cursor-pointer items-center justify-center rounded-lg border border-solid border-[#d9dee5] bg-transparent text-[14px] font-semibold text-inherit [transition:background_160ms_ease,border-color_160ms_ease,box-shadow_160ms_ease] hover:border-[#64748b]" onClick={() => this.signInBrowser()}>Continue with Microsoft</button>
    </>));
    dialog.addEventListener('cancel',event=>event.preventDefault());
    document.body.append(dialog);dialog.showModal();
  },
  showNotificationInvitation(browserChoice){
    if (document.getElementById('notification-invitation')) return;
    const dialog = document.createElement('dialog');
    dialog.id = 'notification-invitation';
    dialog.setAttribute('aria-labelledby', 'notification-invitation-title');
    dialog.setAttribute('aria-describedby', 'notification-invitation-description');
    const root = ReactDOM.createRoot(dialog);
    ReactDOM.flushSync(() => root.render(<>
      <img src="/sa/evenflow.png" alt="" width="56" height="40" />
      <h2 id="notification-invitation-title">{browserChoice?'Turn on notifications in this browser?':'Turn on notifications?'}</h2>
      <p id="notification-invitation-description">Get an alert when someone messages you, asks for your approval, or assigns you a task. You can turn this on later in Account → Notifications.</p>
      <button type="button" value="continue">{browserChoice?'Turn on notifications':'Continue'}</button>
      <button type="button" value="later">Not now</button>
    </>));
    const choose = enable => {
      if (!this.authenticated || this.loginAs) return;
      if (browserChoice) return browserChoice(enable);
      localStorage.setItem(this.notificationOfferKey, '1');
      if (enable) void this.syncNativeNotifications(true);
    };
    dialog.addEventListener('click', event => {
      if (!event.target.matches('button')) return;
      // Browsers require the permission request to run inside the user's click.
      choose(event.target.value === 'continue');
      dialog.close();
    });
    dialog.addEventListener('cancel', () => choose(false));
    dialog.addEventListener('close', () => { root.unmount(); dialog.remove(); }, {once:true});
    document.body.append(dialog);
    dialog.showModal();
    return () => dialog.close();
  },

  loginPageClass:'login-page grid min-h-[var(--safe-height,100svh)] place-items-center bg-[color:var(--bg,#fff)] p-[18px]',
  loginLayout(...children){
    return (
      <main className={this.loginPageClass}>
        <section className="login-card grid w-[min(360px,100%)] gap-3 rounded-xl border border-solid border-[color:var(--login-line)] bg-[color:var(--login-surface)] p-[18px] [box-shadow:0_22px_55px_#0f172a2e]">
          {children}
        </section>
      </main>
    );
  },
  signInCard({onSignIn,alternateAction,error}){
    const brand=(
      <div className="mb-0.5 flex items-center gap-2.5">
        <div className="flex h-[38px] w-[54px] flex-[0_0_54px] items-center justify-center overflow-hidden">
          <img src="/sa/evenflow.png" alt="" className="h-[52px] w-[76px] object-contain object-center" />
        </div>
        <h1 className="m-0 text-[20px] font-bold leading-none tracking-normal text-[color:var(--login-text)]">
          EvenFlow
        </h1>
      </div>
    );
    const action=onSignIn?(
      <button
        type="button"
        onClick={onSignIn}
        className="flex min-h-11 items-center justify-center gap-2.5 rounded-lg border border-solid border-[color:var(--login-line)] bg-[color:var(--login-surface)] text-[14px] font-semibold text-[color:var(--login-text)] no-underline [transition:background_160ms_ease,border-color_160ms_ease,box-shadow_160ms_ease] hover:border-[#64748b] hover:bg-[color:var(--login-panel)]"
      >
        <span className="grid h-[18px] w-[18px] grid-cols-2 gap-0.5" aria-hidden={true}>
          {['bg-[#f25022]', 'bg-[#7fba00]', 'bg-[#00a4ef]', 'bg-[#ffb900]'].map((color) => (
            <span key={color} className={color} />
          ))}
        </span>
        Continue with Microsoft
      </button>
    ):alternateAction;
    return this.loginLayout(brand,action,error&&(
      <p
        className="m-0 text-[12px] font-medium leading-[1.5] text-danger [overflow-wrap:anywhere]"
        role="alert"
      >
        {error}
      </p>
    ));
  },
  signIn(root,error){
    if(this.signInFailure){this.startupError(root,error||{status:401},()=>location.reload());return;}
    if(this.inTeams){
      root.render(this.loginLayout(
        <h1>EvenFlow</h1>,(
          <p role="alert">
            {error?.signedOut
              ? 'You signed out of Hub.'
              : 'We couldn’t sign you in through Teams. Please try again.'}
          </p>
        ),
        (
          <button type="button" className="small" onClick={() => location.reload()}>
            {error?.signedOut ? 'Continue with Teams' : 'Retry'}
          </button>
        )));
      return;
    }
    const host=this;
    function BrowserSignIn(){
      const [message,setMessage]=React.useState(host.signInError||(error?.status===401?'':error?.message||''));
      const login=async()=>{setMessage('');try{await host.signInBrowser();}catch(failure){if(host.accessFailure(failure))host.startupError(root,failure,login);else setMessage(failure.message);}};
      return host.signInCard({onSignIn:login,error:message});
    }
    root.render(<BrowserSignIn />);
  },
  accessPage(unavailable,onRetry){
    return (
      <main className={this.loginPageClass + ' hub-access-page text-center text-[color:var(--login-text)]'}>
        <section className="w-full max-w-[560px] py-6" aria-labelledby="hub-access-title">
          <img
            className="mx-auto mb-6 block h-[76px] w-28 object-contain"
            src="/sa/evenflow.png"
            alt="EvenFlow"
          />
          <h1
            id="hub-access-title"
            className="mx-0 mb-4 mt-0 text-[clamp(28px,5vw,36px)] [font-weight:var(--access-title-weight,700)] leading-[1.2] tracking-[-.03em]"
          >
            {unavailable ? 'We couldn’t check your access' : "Sorry, you don't have access to this app yet."}
          </h1>
          {unavailable && (
            <p className="mx-auto mb-6 mt-0 max-w-[44ch] text-base leading-[1.65] [overflow-wrap:anywhere]">
              Please try again in a moment.
            </p>
          )}
          {unavailable && (
            <button
              type="button"
              className="min-h-11 rounded-lg border border-solid border-[var(--login-line)] bg-[var(--login-surface)] px-6 py-2.5 text-[14px] font-semibold text-[color:var(--login-text)] hover:bg-[var(--login-panel)]"
              onClick={onRetry}
            >
              Retry
            </button>
          )}
          <p className="mx-auto mb-0 mt-8 max-w-[44ch] text-[14px] leading-[1.65] [overflow-wrap:anywhere]">
            {unavailable ? 'For assistance, contact ' : 'Please contact '}
            <a
              className="font-semibold text-[color:var(--accent,#2563eb)] underline underline-offset-[3px]"
              href="mailto:support@evenflow.world"
            >
              support@evenflow.world
            </a>
            {unavailable ? '.' : ' for assistance.'}
          </p>
        </section>
      </main>
    );
  },
  startupError(root,error,retry){
    const failure=this.accessFailure(error);
    if(failure){
      root.render(this.accessPage(failure==='access_unavailable',async()=>{
        this.signInFailure=null;this.signInError='';
        try{if(error.status===401&&!this.inTeams)await this.signInBrowser();else await retry();}
        catch(next){this.startupError(root,next,retry);}
      }));return;
    }
    if(error.status===401){this.signIn(root,error);return;}
    root.render((
      <main className="startup-error grid place-items-center p-6">
        <section
          className="w-full max-w-[420px] rounded-[20px] border border-solid border-edge bg-canvas p-7 shadow-[0_16px_48px_#0002]"
          aria-labelledby="startup-error-title"
        >
          <h1 id="startup-error-title" className="mx-0 mb-3 mt-0 text-2xl leading-[1.25]">
            We couldn’t load your apps
          </h1>
          <p className="mx-0 mb-6 mt-0 leading-[1.6] text-muted" role="alert">
            {error.status === 403 ? 'You don’t have access to this page.' : 'Please try again in a moment.'}
          </p>
          <button type="button" className="small primary" onClick={retry}>
            Retry
          </button>
        </section>
      </main>
    ));
  }
});
