/* global React, RC, LiveLogin, LiveAdmin, LiveViewer */
const { useState, useEffect, useCallback } = React;

function useToast() {
  const [toast, setToast] = useState(null);
  useEffect(() => {
    if (!toast) return;
    const t = setTimeout(() => setToast(null), toast.ttl || 3500);
    return () => clearTimeout(t);
  }, [toast]);
  const show = useCallback((message, kind = 'info') => setToast({ message, kind }), []);
  const node = toast ? (
    <div className={'ed-toast ' + (toast.kind === 'error' ? 'ed-toast--error' : '')}>{toast.message}</div>
  ) : null;
  return [node, show];
}

function RCApp() {
  // route: ?view=<slug>  -> public viewer
  //        otherwise     -> login -> admin
  const params = new URLSearchParams(window.location.search);
  const viewSlug = params.get('view');

  const [me, setMe] = useState(null);
  const [bootDone, setBootDone] = useState(false);
  const [toastNode, toast] = useToast();

  // On boot, if we have a token try /api/auth/me
  useEffect(() => {
    let cancelled = false;
    if (viewSlug) { setBootDone(true); return; }
    if (!RC.getToken()) { setBootDone(true); return; }
    RC.apiFetch('/api/auth/me')
      .then((data) => { if (!cancelled) setMe(data); })
      .catch(() => RC.logout())
      .finally(() => { if (!cancelled) setBootDone(true); });
    return () => { cancelled = true; };
  }, [viewSlug]);

  if (!bootDone) {
    return (
      <div style={{ height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <Spinner />
      </div>
    );
  }

  if (viewSlug) {
    return (<>
      <LiveViewer slug={viewSlug} toast={toast} />
      {toastNode}
    </>);
  }

  if (!me) {
    return (<>
      <LiveLogin
        onLogin={async (token, user) => {
          const data = await RC.apiFetch('/api/auth/me');
          setMe(data);
        }}
        toast={toast}
      />
      {toastNode}
    </>);
  }

  return (<>
    <LiveAdmin
      me={me}
      onLogout={() => { RC.logout(); setMe(null); }}
      toast={toast}
    />
    {toastNode}
  </>);
}

function Spinner({ size = 22 }) {
  return (
    <span style={{
      display: 'inline-block', width: size, height: size,
      border: '2px solid rgba(255,255,255,0.15)',
      borderTopColor: 'var(--rc-red)',
      borderRadius: '50%',
      animation: 'rc-spin 0.7s linear infinite',
    }} />
  );
}

window.RCApp = RCApp;
window.RCSpinner = Spinner;
