/*
 * The account menu, shared by every page that has a header.
 *
 * Loaded as <script type="text/babel" src="..."> before each page's own
 * block, so it is compiled by the same in-browser Babel and its declarations
 * land in global scope. That is also the constraint on how it is written:
 *
 *   NO top-level `const { useState } = React`. Every page already does that
 *   in its own block, and two top-level `const useState` in the same global
 *   scope is a SyntaxError that kills the page. Hooks are reached through
 *   React.* here for that reason.
 *
 * It lives in one file because the dismissal behaviour is the fiddly part —
 * a second copy is how the capture-phase bug comes back on one page and not
 * the other.
 */

function tierLabel(access) {
  if (!access) return 'Guest';
  if (access.tier === 'owner') return 'Staff';
  if (access.tier === 'pro') return 'Subscribed';
  return access.signedIn ? 'Free' : 'Guest';
}

/**
 * One control instead of four.
 *
 * A header used to carry a tier badge, the email, and a button each for
 * managing the account and signing out — all competing with the page for the
 * same strip. None of them is frequent, so they sit behind the one thing you
 * might want: who am I signed in as.
 *
 * `links` are page-specific destinations shown above the common ones.
 */
function AccountMenu({ access, onSignOut, links }) {
  const [open, setOpen] = React.useState(false);
  const wrap = React.useRef(null);

  // Capture phase — in the bubble phase React has already re-rendered and the
  // clicked node may be detached, which reads as a click outside the menu.
  React.useEffect(() => {
    if (!open) return;
    const away = (e) => { if (wrap.current && !wrap.current.contains(e.target)) setOpen(false); };
    const esc = (e) => { if (e.key === 'Escape') setOpen(false); };
    document.addEventListener('mousedown', away, true);
    document.addEventListener('keydown', esc);
    return () => {
      document.removeEventListener('mousedown', away, true);
      document.removeEventListener('keydown', esc);
    };
  }, [open]);

  // The local part identifies the person; the domain is the same for everyone
  // at their company and only eats width. The whole address is in the menu.
  const short = String(access.email || '').split('@')[0];

  return (
    <div className="account" ref={wrap}>
      <button type="button" className="header-btn account-btn"
              aria-expanded={open} aria-haspopup="menu"
              title={access.email || ''}
              onClick={() => setOpen((o) => !o)}>
        <span className="account-name">{short}</span>
        <span className="account-caret" aria-hidden="true">{open ? '▴' : '▾'}</span>
      </button>
      {open && (
        <div className="account-menu" role="menu">
          <div className="account-head">
            <div className="account-email">{access.email}</div>
            {access.company && <div className="account-company">{access.company}</div>}
            <span className={'tier tier-' + access.tier}>{tierLabel(access)}</span>
          </div>

          {(links || []).map((l) => (
            <a key={l.href} className="account-item" role="menuitem" href={l.href}>{l.label}</a>
          ))}

          {/* Billing, seats, company profile and password all live in the
              Fulcrum360 admin portal — this product deliberately owns no
              account management of its own. The URL comes from the server so
              the ng → app cutover is a config change, not a code one. */}
          {access.accountUrl &&
            <a className="account-item" role="menuitem" href={access.accountUrl}
               target="_blank" rel="noopener noreferrer">Manage account ↗</a>}
          {access.tier === 'owner' &&
            <a className="account-item" role="menuitem" href="/admin-claims.html">PMA holder claims</a>}

          <button type="button" className="account-item" role="menuitem" onClick={onSignOut}>
            Sign out
          </button>
        </div>
      )}
    </div>
  );
}
