'use strict';

const {useState,useEffect,useRef}=React;

function accountSection(){
 return location.hash.slice(1);
}

async function signOutOfHub(){
 try{await HubHost.signOutBrowser();location.assign('/nh/');}
 catch{HubToast.show('Could not sign out. Please try again.',{type:'error'});}
}

function AccountPage(){
 const {Icon,Button}=HubLauncherControls;
 const [section,setSection]=useState(accountSection);
 useEffect(()=>{
  const change=()=>setSection(accountSection());
  window.addEventListener('hashchange',change);
  return ()=>window.removeEventListener('hashchange',change);
 },[]);
 const sections=[
  {id:'sessions',label:'My sessions',icon:'devices',description:'See where you’re signed in and end sessions.',view:MySessions},
  {id:'notifications',label:'Notifications',icon:'bell',description:'Choose which sessions receive alerts.',view:NotificationPreferences}
 ];
 const active=sections.find(item=>item.id===section);
 const heading=useRef(null);
 useEffect(()=>{
  document.title=(active?active.label+' · ':'')+'Account · EvenFlow';
  heading.current?.focus({preventScroll:true});
 },[section]);
 const {name,email}=HubHost.user;
 return (
   <main className={'account-page [&_.icon]:size-[1em] [&_.icon]:flex-none [&_.icon]:text-[length:1.2em]'}>
     <header className="account-header">
       {active ? (
         <div className="account-section-header">
           <a href="#" className="iconbtn" aria-label="Back to Account" title="Back to Account">
             <Icon name="left" />
           </a>
           <h1 ref={heading} tabIndex={-1}>
             {active.label}
           </h1>
         </div>
       ) : (
         <React.Fragment>
           <a href={HubHost.homeUrl()} className="account-home">
             <Icon name="left" />
             Home
           </a>
           <h1 ref={heading} tabIndex={-1}>
             Account
           </h1>
         </React.Fragment>
       )}
       <div className="account-identity">
         <div>
           <strong>{name || email}</strong>
           {name && name !== email && <span>{email}</span>}
         </div>
         {!active && !HubHost.inTeams && <Button onClick={signOutOfHub}>Sign out</Button>}
       </div>
     </header>
     {active ? (
       <section aria-label={active.label} className="account-panel">
         <active.view />
       </section>
     ) : (
       <nav aria-label="Account settings" className="account-directory">
         {sections.map(({ id, label, icon, description }) => (
           <a key={id} href={'#' + id} aria-label={label}>
             <Icon name={icon} />
             <span>
               <strong>{label}</strong>
               <small>{description}</small>
             </span>
             <Icon name="right" />
           </a>
         ))}
       </nav>
     )}
     <HubContent.Footer />
   </main>
 );
}

function MySessions(){
 const {Button,Modal}=HubLauncherControls;
 const [sessions,setSessions]=useState([]),[cursor,setCursor]=useState(null),[busy,setBusy]=useState(true);
 const [error,setError]=useState(''),[confirm,setConfirm]=useState(null),[notice,setNotice]=useState('');
 const [now,setNow]=useState(Date.now);
 const endpoint='/api/nh/sessions';
 function label(row){
  const parts=[row.clientType,row.os,row.deviceType].filter(value=>value&&value!=='Unknown');
  return parts.join(' · ')||'Hub session';
 }
 async function load(after){
  setBusy(true);setError('');
  try{
   const page=await HubHost.request(endpoint+(after?'?cursor='+encodeURIComponent(after):''));
   setSessions(previous=>after?previous.concat(page.sessions):page.sessions);setCursor(page.nextCursor);
  }catch{setError('Could not load your sessions.');}
  finally{setBusy(false);}
 }
 useEffect(()=>{load();const timer=setInterval(()=>setNow(Date.now()),60000);return()=>clearInterval(timer);},[]);
 async function signOut(){
  setBusy(true);setError('');
  try{
   const body=confirm.all?{all:true}:{sessionId:confirm.id};
   const result=await HubHost.request(endpoint+'/revoke',{method:'POST',body:JSON.stringify(body)});
   if(result.signedOut){
    if(HubHost.inTeams){sessionStorage.removeItem(HubHost.teamsStorageKey());HubHost.requireSignIn(true);return;}
    try{await HubHost.signOutBrowser();location.replace('/nh/');}catch{HubHost.requireSignIn(true);}
    return;
   }
   setConfirm(null);setNotice(confirm.notificationsOnly?'Browser alerts stopped.':'Session signed out.');await load();
  }catch(err){
   if(err.status===404){setConfirm(null);setNotice('That session has already ended.');await load();}
   else setError('Could not sign out. Please try again.');
  }finally{setBusy(false);}
 }
 const all=confirm?.all;
 const cancel=()=>{if(!busy){setError('');setConfirm(null);}};
 return (
   <React.Fragment>
     {confirm && (
       <Modal
         title={
           all
             ? 'Sign out of all Hub sessions?'
             : confirm.notificationsOnly
               ? 'Stop alerts on this browser?'
               : 'Sign out of this Hub session?'
         }
         onClose={cancel}
         className="account-confirm"
       >
         <p>
           {all
             ? 'This includes the session you’re using now.'
             : label(confirm) + (confirm.current ? ' (this session)' : '')}
         </p>
         {(all || confirm.clientType === 'Teams') && (
           <p className="text-muted">Teams can reconnect through Microsoft SSO.</p>
         )}
         <div className="session-actions">
           <Button disabled={busy} onClick={cancel}>
             Cancel
           </Button>
           <Button danger={true} disabled={busy} onClick={signOut}>
             {all ? 'Sign out of all sessions' : confirm.notificationsOnly ? 'Stop alerts' : 'Sign out'}
           </Button>
         </div>
         {error && <p role="alert">{error}</p>}
       </Modal>
     )}
     {sessions.length > 0 && (
       <ul className="own-session-list">
         {sessions.map((row) => (
           <li key={row.id}>
             <div>
               <strong>{label(row)}</strong>
               {row.notificationsOnly && <small>Signed out · Browser alerts enabled</small>}
               {row.current && <small>This session</small>}
               <small>
                 {'Last active '}
                 <time dateTime={row.lastActivityAt} title={new Date(row.lastActivityAt).toLocaleString()}>
                   {sessionRelativeTime(row.lastActivityAt, now)}
                 </time>
               </small>
               <small>
                 {'Signed in '}
                 {new Date(row.createdAt).toLocaleString()}
                 {[row.signInCity, row.signInCountry]
                   .filter(Boolean)
                   .map((value) => ' · ' + value)
                   .join('')}
               </small>
             </div>
             <button
               type="button"
               className="small"
               disabled={busy}
               aria-label={
                 (row.notificationsOnly ? 'Stop alerts on ' : 'Sign out of ') +
                 label(row) +
                 (row.current ? ', this session' : '')
               }
               onClick={() => {
                 setError('');
                 setNotice('');
                 setConfirm(row);
               }}
             >
               {row.notificationsOnly ? 'Stop alerts' : 'Sign out'}
             </button>
           </li>
         ))}
       </ul>
     )}
     {busy && <p role="status">Loading sessions…</p>}
     {!sessions.length && !error && !busy && <p>No active sessions.</p>}
     {cursor && (
       <Button disabled={busy} onClick={() => load(cursor)}>
         Load more
       </Button>
     )}
     {sessions.length > 0 && (
       <Button
         danger={true}
         disabled={busy}
         onClick={() => {
           setError('');
           setNotice('');
           setConfirm({
             all: true
           });
         }}
       >
         Sign out of all sessions
       </Button>
     )}
     {notice && <p role="status">{notice}</p>}
     {!confirm && error && (
       <p role="alert">
         {error}{' '}
         <Button disabled={busy} onClick={() => load()}>
           Retry
         </Button>
       </p>
     )}
   </React.Fragment>
 );
}
function NotificationPreferences(){
 const [recent,setRecent]=useState(null),[saving,setSaving]=useState(false),[error,setError]=useState('');
 const endpoint='/api/nh/preferences?section=notifications';
 useEffect(()=>{
  let current=true;
  HubHost.request(endpoint).then(data=>{if(current)setRecent(data.recentDeviceOnly);})
   .catch(()=>{if(current)setError('Could not load notification preferences.');});
  return ()=>{current=false;};
 },[]);
 async function select(value){
  const previous=recent;setRecent(value);setSaving(true);setError('');
  try{await HubHost.request(endpoint,{method:'PUT',body:JSON.stringify({recentDeviceOnly:value})});}
  catch{setRecent(previous);setError('Could not save your choice. Please try again.');}
  finally{setSaving(false);}
 }
 return (
   <React.Fragment>
     <fieldset className="notification-choices" disabled={recent === null || saving}>
       <legend>Where to notify me</legend>
       {[
         [true, 'Most recently active session'],
         [false, 'All eligible sessions']
       ].map(([value, label]) => (
         <label key={label}>
           <input
             type="radio"
             name="notification-devices"
             checked={recent === value}
             onChange={() => select(value)}
           />
           {label}
         </label>
       ))}
     </fieldset>
     {!HubHost.loginAs && (window.HubBrowserPush?.available || HubHost.notificationSync()) && (
       <fieldset className="notification-choices">
         <legend>{window.HubBrowserPush?.available ? 'This browser' : 'This device'}</legend>
         <DeviceNotificationControl />
       </fieldset>
     )}
     {error && <p role="alert">{error}</p>}
   </React.Fragment>
 );
}

function DeviceNotificationControl(){
 const {Button}=HubLauncherControls;
 const push=window.HubBrowserPush;
 const [,refresh]=useState(0),[error,setError]=useState('');
 useEffect(()=>{
  const changed=()=>refresh(n=>n+1);
  window.addEventListener('hub-notification-status',changed);
  return ()=>window.removeEventListener('hub-notification-status',changed);
 },[]);
 async function enable(){
  setError('');
  try{await push.enable();}catch(e){setError(Notification.permission==='denied'?
   'Allow notifications for this site in your browser settings.':'Could not update browser notifications. Please try again.');}
 }
 if (!push?.available) {
  switch (HubHost.nativeNotificationStatus) {
   case 'undecided': return (
     <Button
       disabled={HubHost.syncingNativeNotifications}
       onClick={() => HubHost.syncNativeNotifications(true)}
     >
       Enable notifications on this device
     </Button>
   );
   case 'enabled': return <p>Notifications are on. You can change this in your device settings.</p>;
   case 'blocked': return (
     <p>
       Notifications are blocked. Allow notifications for EvenFlow in your device settings, then return here.
     </p>
   );
   case 'unavailable': return (
     <p>
       {'Could not check notifications. '}
       <Button disabled={HubHost.syncingNativeNotifications} onClick={() => HubHost.syncNativeNotifications()}>
         Retry
       </Button>
     </p>
   );
   default: return null;
  }
 }
 if (Notification.permission==='denied') return (
   <p>
     Notifications are blocked for this site. Allow them in your browser’s site settings, then return here.
   </p>
 );
 if (push.enabled) return <p>Notifications are on. You can change this in your browser’s site settings.</p>;
 return (
   <div>
     <Button disabled={push.busy} onClick={enable}>
       {push.reconnect ? 'Reconnect notifications in this browser' : 'Enable notifications in this browser'}
     </Button>
     {error && <p role="alert">{error}</p>}
   </div>
 );
}

window.HubAccount={AccountPage,signOutOfHub};
