// Molara — global TopBar shown on every page when signed in.
// Sits above the page (the Stage scales the design body but the TopBar
// stays in document flow so it renders at full size on any viewport).
//
// Layout: brand on the left, primary nav links in the middle, bell + avatar
// dropdown on the right. The avatar dropdown links to all portal sections.

const TOPBAR_LINKS = [
  { route: '/',             label: 'Home' },
  { route: '/find',         label: 'Find a dentist' },
  { route: '/pay?emergency=1',label: '24/7 emergency consult', emergency: true },
  { route: '/appointments', label: 'Appointments' },
  { route: '/records',      label: 'Records' },
];

const MENU_ITEMS = [
  { route: '/dashboard',    label: 'Patient dashboard', icon: 'pulse' },
  { route: '/profile',      label: 'Profile & settings', icon: 'user' },
  { route: '/appointments', label: 'My appointments',    icon: 'calendar' },
  { route: '/records',      label: 'Health records',     icon: 'doc' },
  { route: '/payments',     label: 'Payments & billing', icon: 'card' },
];

function TopBar({ user, route, onSignOut }) {
  const [open, setOpen] = React.useState(false);
  const menuRef = React.useRef(null);

  React.useEffect(() => {
    if (!open) return;
    const handler = (e) => {
      if (menuRef.current && !menuRef.current.contains(e.target)) setOpen(false);
    };
    const esc = (e) => e.key === 'Escape' && setOpen(false);
    document.addEventListener('mousedown', handler);
    document.addEventListener('keydown', esc);
    return () => {
      document.removeEventListener('mousedown', handler);
      document.removeEventListener('keydown', esc);
    };
  }, [open]);

  // Close menu on route change
  React.useEffect(() => { setOpen(false); }, [route]);

  const go = (r) => { window.navigate && window.navigate(r); };

  return (
    <header className="ml-topbar" style={{
      position: 'sticky', top: 0, zIndex: 100,
      background: 'rgba(255,255,255,0.94)',
      backdropFilter: 'saturate(140%) blur(10px)',
      WebkitBackdropFilter: 'saturate(140%) blur(10px)',
      borderBottom: '1px solid var(--line)',
      fontFamily: 'var(--sans)',
    }}>
      <style>{`
        @media (max-width: 900px) {
          .ml-topbar__inner { gap: 12px !important; padding: 0 16px !important; }
          .ml-topbar__links button:nth-child(n+5), .ml-topbar__consult { display: none !important; }
        }
        @media (max-width: 720px) {
          .ml-topbar__links button:nth-child(n+3) { display: none !important; }
          .ml-topbar__account-name { display: none !important; }
        }
        .ml-topbar__account .ml-topbar__menu {
          opacity: 0;
          visibility: hidden;
          pointer-events: none;
          transform: translateY(-4px);
          transition: opacity 120ms ease, transform 120ms ease, visibility 120ms ease;
        }
        .ml-topbar__account:hover .ml-topbar__menu,
        .ml-topbar__account:focus-within .ml-topbar__menu,
        .ml-topbar__menu.is-open {
          opacity: 1;
          visibility: visible;
          pointer-events: auto;
          transform: translateY(0);
        }
      `}</style>
      <div className="ml-topbar__inner" style={{
        maxWidth: 1440, margin: '0 auto',
        height: 60, padding: '0 28px',
        display: 'flex', alignItems: 'center', gap: 28,
      }}>
        {/* Brand */}
        <div onClick={() => go('/')} style={{
          display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer',
        }}>
          <div style={{
            width: 26, height: 26, borderRadius: 7,
            background: 'var(--blue)', color: '#fff',
            display: 'grid', placeItems: 'center',
          }}>
            <I.pulse size={14}/>
          </div>
          <div style={{ fontFamily: 'var(--display)', fontSize: 18, letterSpacing: '-0.02em' }}>molara</div>
        </div>

        {/* Primary nav */}
        <nav className="ml-topbar__links" style={{ display: 'flex', gap: 4, marginLeft: 12, flex: '0 1 auto', minWidth: 0, overflow: 'hidden' }}>
          {TOPBAR_LINKS.map((it) => {
            const on = it.route === route
              || (it.route === '/dashboard' && route === '/dashboard')
              || (it.route === '/appointments' && (route === '/appointments' || route === '/confirmed'));
            return (
              <button
                key={it.route}
                onClick={() => it.emergency ? (window.startEmergencyConsult ? window.startEmergencyConsult(user) : window.requireAuth('/pay?emergency=1')) : go(it.route)}
                style={{
                  background: on ? 'var(--blue-soft)' : it.emergency ? 'var(--ink)' : 'transparent',
                  color: on ? 'var(--blue-deep)' : it.emergency ? '#fff' : 'var(--ink-2)',
                  border: 'none', cursor: 'pointer',
                  padding: '7px 13px', borderRadius: 999,
                  fontSize: 13, fontWeight: on ? 500 : 450,
                  fontFamily: 'inherit',
                  letterSpacing: '-0.005em',
                }}
              >{it.label}</button>
            );
          })}
        </nav>

        <div style={{ flex: 1 }}/>

        {/* Bell */}
        <button aria-label="Notifications" style={{
          position: 'relative',
          width: 36, height: 36, borderRadius: '50%',
          background: 'transparent', border: '1px solid var(--line)',
          display: 'grid', placeItems: 'center', cursor: 'pointer',
          color: 'var(--ink-2)',
        }}>
          <I.bell size={15}/>
          <span style={{
            position: 'absolute', top: 6, right: 7,
            width: 7, height: 7, borderRadius: '50%',
            background: 'oklch(60% 0.18 25)',
            border: '1.5px solid #fff',
          }}/>
        </button>

        {/* Avatar + dropdown */}
        <div
          className="ml-topbar__account"
          style={{ position: 'relative' }}
          ref={menuRef}
          onMouseEnter={() => setOpen(true)}
          onMouseLeave={() => setOpen(false)}
        >
          <button
            onClick={() => setOpen((v) => !v)}
            aria-haspopup="menu"
            aria-expanded={open}
            style={{
              display: 'flex', alignItems: 'center', gap: 8,
              padding: '4px 10px 4px 4px',
              borderRadius: 999,
              background: open ? 'var(--paper-2)' : 'transparent',
              border: '1px solid ' + (open ? 'var(--line-2)' : 'transparent'),
              cursor: 'pointer',
              fontFamily: 'inherit',
            }}
          >
            <div className="ml-avatar" style={{ width: 32, height: 32, borderRadius: '50%', fontSize: 12 }}>
              {user?.initials || 'PT'}
            </div>
            <span className="ml-topbar__account-name" style={{ fontSize: 13, fontWeight: 500, color: 'var(--ink)' }}>
              {user?.name?.split(' ')[0] || 'Account'}
            </span>
            <I.chevronD size={13} color="var(--ink-3)"/>
          </button>

            <div role="menu" className={'ml-topbar__menu' + (open ? ' is-open' : '')} style={{
              position: 'absolute', top: 'calc(100% + 8px)', right: 0,
              minWidth: 280,
              background: '#fff',
              border: '1px solid var(--line)',
              borderRadius: 14,
              boxShadow: '0 18px 50px rgba(14,20,40,.14), 0 2px 8px rgba(14,20,40,.06)',
              padding: 6,
              fontSize: 13.5,
              overflow: 'hidden',
            }}>
              {/* Identity */}
              <div style={{
                display: 'flex', alignItems: 'center', gap: 12,
                padding: '12px 12px 14px',
                borderBottom: '1px solid var(--line)',
                marginBottom: 6,
              }}>
                <div className="ml-avatar" style={{ width: 40, height: 40, borderRadius: '50%', fontSize: 14 }}>
                  {user?.initials || 'PT'}
                </div>
                <div style={{ minWidth: 0 }}>
                  <div style={{ fontWeight: 500, color: 'var(--ink)', fontSize: 13.5 }}>{user?.name || 'Patient'}</div>
                  <div style={{ fontSize: 11.5, color: 'var(--ink-3)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                    {user?.email || user?.phone || 'Signed in'}
                  </div>
                </div>
              </div>

              {MENU_ITEMS.map((it) => {
                const Icon = I[it.icon];
                return (
                  <button key={it.route} role="menuitem" onClick={() => go(it.route)}
                    style={{
                      width: '100%', display: 'flex', alignItems: 'center', gap: 10,
                      padding: '9px 12px', borderRadius: 9,
                      background: 'transparent', border: 'none', cursor: 'pointer',
                      textAlign: 'left', color: 'var(--ink)',
                      fontFamily: 'inherit', fontSize: 13,
                    }}
                    onMouseEnter={(e) => e.currentTarget.style.background = 'var(--paper-2)'}
                    onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}
                  >
                    <Icon size={15} color="var(--ink-2)"/>
                    {it.label}
                  </button>
                );
              })}

              <div style={{ borderTop: '1px solid var(--line)', margin: '6px 0' }}/>

              <button role="menuitem" onClick={onSignOut}
                style={{
                  width: '100%', display: 'flex', alignItems: 'center', gap: 10,
                  padding: '9px 12px', borderRadius: 9,
                  background: 'transparent', border: 'none', cursor: 'pointer',
                  textAlign: 'left', color: 'var(--danger)',
                  fontFamily: 'inherit', fontSize: 13,
                }}
                onMouseEnter={(e) => e.currentTarget.style.background = 'oklch(97% 0.02 25)'}
                onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}
              >
                <I.power size={15}/> Sign out
              </button>
            </div>
        </div>
      </div>
    </header>
  );
}

window.TopBar = TopBar;
