// Account shell — top bar, primary nav, search/help/notifications icons,
// and the avatar dropdown menu. Used by every post-login page.

const NAV_ITEMS = [
  { key: 'overview',     label: 'Overview',      href: 'Account-Overview.html' },
  { key: 'applications', label: 'Applications',  href: 'Account-Applications.html' },
  { key: 'find',         label: 'Find Services', href: 'Account-Find.html' },
];

// ─── Top bar ────────────────────────────────────────────────

function AccountTopBar({ activeNav = 'overview' }) {
  const t = window.tokens;
  const [account, setAccount] = useActiveAccount();
  const profile = ACCOUNTS[account];
  const counts = countByBucket(account);
  const unread = notifCount(account);

  // Arriving on any account page means we're signed in. Mirror that to
  // localStorage + <html data-signed-in> so the public-portal headers
  // (Home, Apply, Confirmation) flip to the avatar pill next time the
  // user navigates back out to one of those pages.
  React.useEffect(() => { setSignedIn(true); }, []);

  return (
    <header style={{
      borderBottom: `1px solid ${t.color.hair}`,
      background: t.color.bg,
      position: 'sticky', top: 0, zIndex: 20,
    }}>
      <div style={{
        padding: '12px 32px',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        gap: 24,
      }}>
        {/* LEFT — logo + primary nav */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 28 }}>
          <a href="Resident Portal - Home.html" style={{
            display: 'flex', alignItems: 'center', gap: 12,
            textDecoration: 'none', color: t.color.text,
          }}>
            <img src="assets/nj-logo.svg" alt="" width="26" height="28" style={{ display: 'block' }} />
            <span style={{ display: 'flex', flexDirection: 'column', lineHeight: 1.15, gap: 3 }}>
              <span style={{ fontSize: 13.5, fontWeight: 600, letterSpacing: -0.1 }}>State of New Jersey</span>
              <span style={{ fontFamily: t.font.mono, fontSize: 9.5, fontWeight: 500, letterSpacing: 1.4, textTransform: 'uppercase', color: t.color.muted }}>Resident Portal</span>
            </span>
          </a>

          <nav style={{ display: 'flex', alignItems: 'center', gap: 2 }}>
            {NAV_ITEMS.map(it => (
              <NavTab key={it.key} label={it.label} href={it.href}
                count={it.key === 'applications' ? counts.open : null}
                active={it.key === activeNav} />
            ))}
          </nav>
        </div>

        {/* RIGHT — icon buttons + avatar menu */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <IconBtn name="search_24_regular" title="Search" />
          <IconBtn name="question_circle_24_regular" title="Help" />
          <IconBtn name="alert_24_regular" title="Notifications" badge={unread} href="Account-Overview.html" />
          <AvatarMenu account={account} setAccount={setAccount} profile={profile} />
        </div>
      </div>
    </header>
  );
}

function NavTab({ label, href, count, active }) {
  const t = window.tokens;
  return (
    <a href={href} style={{
      display: 'inline-flex', alignItems: 'center', gap: 8,
      padding: '8px 14px',
      borderRadius: t.radius.sm,
      background: active ? t.color.surfaceHi : 'transparent',
      color: active ? t.color.text : t.color.body,
      fontSize: 14, fontWeight: active ? 600 : 400, letterSpacing: -0.1,
      textDecoration: 'none',
    }}>
      {label}
      {count != null && (
        <span style={{
          fontFamily: t.font.mono, fontSize: 11, color: t.color.muted,
          padding: '0 6px', borderRadius: 999, background: active ? t.color.bg : 'transparent',
          minWidth: 18, textAlign: 'center',
        }}>{count}</span>
      )}
    </a>
  );
}

function IconBtn({ name, title, badge, href }) {
  const t = window.tokens;
  const inner = (
    <span style={{
      position: 'relative',
      width: 36, height: 36, borderRadius: t.radius.sm,
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      color: t.color.body, background: 'transparent',
      transition: 'background .15s',
    }}
      onMouseEnter={(e) => (e.currentTarget.style.background = t.color.surfaceHi)}
      onMouseLeave={(e) => (e.currentTarget.style.background = 'transparent')}
    >
      <FluentIcon name={name.replace(/_24_(regular|filled)$/, '')} size={20} weight={name.endsWith('filled') ? 'filled' : 'regular'} />
      {badge != null && badge > 0 && (
        <span style={{
          position: 'absolute', top: 4, right: 4,
          minWidth: 16, height: 16, padding: '0 4px', borderRadius: 8,
          background: t.color.action, color: '#fff',
          fontSize: 10, fontWeight: 600, fontFamily: t.font.sans,
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          border: `1.5px solid ${t.color.bg}`, lineHeight: 1,
        }}>{badge}</span>
      )}
    </span>
  );
  if (href) return <a href={href} title={title} style={{ textDecoration: 'none' }}>{inner}</a>;
  return <button title={title} style={{ border: 'none', background: 'transparent', padding: 0, cursor: 'pointer' }}>{inner}</button>;
}

// ─── Avatar menu (switch account · manage settings · sign out) ─

function AvatarMenu({ account, setAccount, profile }) {
  const t = window.tokens;
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef(null);

  React.useEffect(() => {
    if (!open) return;
    const off = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', off);
    return () => document.removeEventListener('mousedown', off);
  }, [open]);

  const other = account === 'personal' ? 'business' : 'personal';
  const otherProfile = ACCOUNTS[other];
  const otherCounts = countByBucket(other);

  return (
    <div ref={ref} style={{ position: 'relative' }}>
      <button onClick={() => setOpen(o => !o)} style={{
        display: 'inline-flex', alignItems: 'center', gap: 8,
        padding: '4px 10px 4px 5px', borderRadius: 999,
        background: open ? t.color.surfaceHi : t.color.bg,
        border: `1px solid ${t.color.hair}`,
        cursor: 'pointer', fontFamily: t.font.sans,
      }}>
        <Avatar initials={profile.initials} size={28} />
        <span style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-start', lineHeight: 1.15 }}>
          <span style={{ fontFamily: t.font.mono, fontSize: 9.5, fontWeight: 500, letterSpacing: 1.2, textTransform: 'uppercase', color: t.color.muted }}>
            {profile.kind === 'business' ? 'Business' : 'Personal'}
          </span>
          <span style={{ fontSize: 13, fontWeight: 500, color: t.color.text }}>{profile.short}</span>
        </span>
        <FluentIcon name="chevron_down" size={14} style={{ color: t.color.muted }} />
      </button>

      {open && (
        <div style={{
          position: 'absolute', top: 'calc(100% + 6px)', right: 0,
          width: 340, background: t.color.bg,
          border: `1px solid ${t.color.hair}`, borderRadius: t.radius.lg,
          boxShadow: t.shadow.pop,
          padding: 6, zIndex: 30,
        }}>
          <div style={{ padding: '12px 14px 10px' }}>
            <div style={{ fontFamily: t.font.mono, fontSize: 10, letterSpacing: 1.4, textTransform: 'uppercase', color: t.color.muted, marginBottom: 2 }}>Signed in as</div>
            <div style={{ fontSize: 13.5, color: t.color.text, fontWeight: 500 }}>jamie.morrison@email.com</div>
          </div>

          <div style={{ borderTop: `1px solid ${t.color.hair}`, padding: '8px 4px' }}>
            <div style={{ padding: '4px 12px 6px', fontFamily: t.font.mono, fontSize: 10, letterSpacing: 1.4, textTransform: 'uppercase', color: t.color.dim, fontWeight: 500 }}>Switch account</div>
            <AccountRow active profile={ACCOUNTS[account]} />
            <AccountRow profile={otherProfile} actionCount={otherCounts.action} onClick={() => { setAccount(other); setOpen(false); }} />
            <MenuRow icon="add" label="Add another account" muted />
          </div>

          <div style={{ borderTop: `1px solid ${t.color.hair}`, padding: '6px 4px' }}>
            <MenuRow icon="settings" label="Manage settings" sub="Profile, properties, pets, sign-in" arrow href="Account-Settings.html" />
            <MenuRow icon="arrow_exit" label="Sign out" muted href="Resident Portal - Home.html"
              onClick={() => { setSignedIn(false); }} />
          </div>
        </div>
      )}
    </div>
  );
}

function AccountRow({ profile, active, actionCount, onClick }) {
  const t = window.tokens;
  const [hover, setHover] = React.useState(false);
  return (
    <button onClick={onClick} disabled={active}
      onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      style={{
        display: 'flex', alignItems: 'center', gap: 10,
        width: '100%', padding: '8px 10px', borderRadius: t.radius.sm,
        background: active ? t.color.surfaceHi : (hover ? t.color.surfaceLo : 'transparent'),
        border: 'none', cursor: active ? 'default' : 'pointer', textAlign: 'left',
      }}
    >
      <Avatar initials={profile.initials} size={28} />
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 13, fontWeight: active ? 600 : 500, color: t.color.text }}>{profile.name}</div>
        <div style={{ fontFamily: t.font.mono, fontSize: 10, color: t.color.muted, letterSpacing: 1.2, textTransform: 'uppercase' }}>{profile.kind === 'business' ? 'Business' : 'Personal'}</div>
      </div>
      {actionCount > 0 && (
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, color: t.color.action, fontFamily: t.font.mono, fontSize: 11 }}>
          <span style={{ width: 6, height: 6, borderRadius: 3, background: t.color.action }} />
          {actionCount}
        </span>
      )}
      {active && <FluentIcon name="checkmark" size={16} style={{ color: t.color.muted }} />}
    </button>
  );
}

function MenuRow({ icon, label, sub, muted, arrow, href, onClick }) {
  const t = window.tokens;
  const [hover, setHover] = React.useState(false);
  const inner = (
    <>
      <FluentIcon name={icon} size={18} style={{ color: muted ? t.color.muted : t.color.body, flexShrink: 0 }} />
      <span style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 13.5, color: muted ? t.color.muted : t.color.text, fontWeight: 400 }}>{label}</div>
        {sub && <div style={{ fontFamily: t.font.mono, fontSize: 10, color: t.color.dim, letterSpacing: 1.1, textTransform: 'uppercase', marginTop: 1 }}>{sub}</div>}
      </span>
      {arrow && <FluentIcon name="chevron_right" size={14} style={{ color: t.color.dim }} />}
    </>
  );
  const style = {
    display: 'flex', alignItems: 'center', gap: 10,
    width: '100%', padding: '9px 12px', borderRadius: t.radius.sm,
    background: hover ? t.color.surfaceLo : 'transparent',
    border: 'none', cursor: 'pointer', textAlign: 'left',
    fontFamily: t.font.sans, textDecoration: 'none',
  };
  const handlers = {
    onMouseEnter: () => setHover(true),
    onMouseLeave: () => setHover(false),
  };
  if (href) return <a href={href} style={style} onClick={onClick} {...handlers}>{inner}</a>;
  return <button onClick={onClick} style={style} {...handlers}>{inner}</button>;
}

// ─── Page shell wrapper ─────────────────────────────────────

function AccountPage({ activeNav, children, maxWidth = 1240 }) {
  const t = window.tokens;
  return (
    <div style={{ minHeight: '100vh', background: t.color.surfaceLo, display: 'flex', flexDirection: 'column' }}>
      <AccountTopBar activeNav={activeNav} />
      <main style={{ flex: 1, padding: '32px 32px 64px' }}>
        <div style={{ maxWidth, margin: '0 auto' }}>{children}</div>
      </main>
    </div>
  );
}

Object.assign(window, { AccountTopBar, AccountPage, NavTab, IconBtn, AvatarMenu, MenuRow });
