// Five Nodes Hospital — Sidebar + TopBar
const { useState, useEffect } = React;

function initials(str) {
  if (!str) return '?';
  const parts = String(str).trim().split(/\s+/);
  if (parts.length >= 2) return (parts[0][0] + parts[1][0]).toUpperCase();
  return str.slice(0, 2).toUpperCase();
}

const Sidebar = ({ current, onNav, user, lang, mobileOpen, onCloseMobile, mode = 'advanced' }) => {
  const [menuOpen, setMenuOpen] = useState(false);
  const isEasy = mode === 'easy';
  const displayName = user?.user_metadata?.full_name || user?.user_metadata?.name || user?.email || 'Signed in';
  const userInitials = initials(displayName);
  const onSignOut = () => window.__api.signOut().then(() => window.location.reload());

  // Easy mode keeps it to the three essentials — Overview, Conversations, Patients.
  // Appointments / Doctor schedule / Today's patients and Enterprise are Advanced-only.
  const workspace = [
    { key: 'overview',     label: 'Overview',         icon: 'overview' },
    { key: 'inbox',        label: 'Conversations',    icon: 'inbox',    count: 0 },
    { key: 'leads',        label: 'Patients',         icon: 'leads',    count: 0 },
    ...(isEasy ? [] : [
      { key: 'appointments', label: 'Appointments',     icon: 'calendar', count: 0 },
      { key: 'schedule',     label: 'Doctor schedule',  icon: 'stethoscope' },
      { key: 'today',        label: "Today's patients", icon: 'today',    count: 0 }
    ])
  ];
  const enterprise = isEasy ? [] : [
    { key: 'analytics', label: 'Analytics', icon: 'analytics' },
    { key: 'swot',      label: 'SWOT',      icon: 'target' },
    { key: 'settings',  label: 'Settings',  icon: 'settings' }
  ];

  return (
    <>
      {mobileOpen && <div className="mobile-backdrop active" onClick={onCloseMobile} />}
      <aside className={`sidebar ${mobileOpen ? 'mobile-open' : ''}`}>
        <button className="mobile-close-btn" onClick={onCloseMobile} aria-label="Close menu">
          <Icon name="close" size={18} />
        </button>
      <div className="brand">
        <div className="brand-mark">F</div>
        <div>
          <div className="brand-name">Five Nodes</div>
          <div className="brand-sub">Hospital · v1.0</div>
        </div>
      </div>

      <div className="nav-section">
        <div className="nav-label">{window.__t ? window.__t('nav.workspace') : 'Workspace'}</div>
        {workspace.map(it => (
          <button key={it.key} data-onboarding-id={`nav-${it.key}`} className={`nav-item ${current === it.key ? 'active' : ''}`} onClick={() => onNav(it.key)}>
            <Icon name={it.icon} />
            <span>{window.__t ? window.__t('nav.' + it.key) : it.label}</span>
            {typeof it.count === 'number' && <span className="count">{it.count}</span>}
          </button>
        ))}
      </div>

      {enterprise.length > 0 && (
      <div className="nav-section">
        <div className="nav-label">{window.__t ? window.__t('nav.enterprise') : 'Enterprise'}</div>
        {enterprise.map(it => (
          <button key={it.key} data-onboarding-id={`nav-${it.key}`} className={`nav-item ${current === it.key ? 'active' : ''}`} onClick={() => onNav(it.key)}>
            <Icon name={it.icon} />
            <span>{window.__t ? window.__t('nav.' + it.key) : it.label}</span>
          </button>
        ))}
      </div>
      )}

      <div className="sidebar-foot">
        <div className="sidebar-meta">
          <div className="row"><span>{window.__t ? window.__t('side.specialties', lang) : 'SPECIALTIES'}</span><b>12</b></div>
          <div className="row"><span>{window.__t ? window.__t('side.doctors', lang) : 'DOCTORS'}</span><b>60</b></div>
          <div className="row"><span>{window.__t ? window.__t('side.openSlots', lang) : 'OPEN SLOTS / WK'}</span><b>—</b></div>
        </div>
        <div className="user-chip" style={{ position: 'relative' }}>
          <div className="avatar">{userInitials}</div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div className="name" title={displayName}>{displayName}</div>
            <div className="role">{window.__t ? window.__t('side.role', lang) : 'Care coordinator'}</div>
          </div>
          <button onClick={() => setMenuOpen(o => !o)} title="Account"
            style={{ width: 26, height: 26, display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--fg-3)', background: 'transparent', border: 'none', cursor: 'pointer', borderRadius: 4 }}>
            <Icon name="more" size={14} />
          </button>
          {menuOpen && (
            <div style={{ position: 'absolute', bottom: 'calc(100% + 6px)', right: 0,
                          minWidth: 170, background: 'var(--bg-elev)',
                          border: '1px solid var(--line)', borderRadius: 8,
                          boxShadow: 'var(--shadow-md)', zIndex: 50, overflow: 'hidden' }}>
              <button onClick={onSignOut}
                style={{ width: '100%', textAlign: 'left', padding: '10px 12px', background: 'transparent', color: 'var(--fg-1)', border: 'none', fontSize: 13, cursor: 'pointer' }}
                onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-soft)'}
                onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                {window.__t ? window.__t('top.signOut', lang) : 'Sign out'}
              </button>
            </div>
          )}
        </div>
      </div>
      </aside>
    </>
  );
};

function buildTitles(lang) {
  const t = (k) => window.__t ? window.__t(k, lang) : k;
  const dash = t('crumb.dashboard') + ' / ';
  return {
    overview:     { crumb: dash + t('nav.overview'),     title: null /* greeting */ },
    inbox:        { crumb: dash + t('nav.inbox'),        title: <><em>{t('title.conversations')}</em></> },
    leads:        { crumb: dash + t('nav.leads'),        title: <>{t('title.patients').replace(t('title.patients.em'), '').trim()} <em>{t('title.patients.em')}</em></> },
    appointments: { crumb: dash + t('nav.appointments'), title: <>{t('title.appointments').replace(t('title.appointments.em'), '').trim()} <em>{t('title.appointments.em')}</em></> },
    schedule:     { crumb: dash + t('nav.schedule'),     title: <>{t('title.schedule').replace(t('title.schedule.em'), '').trim()} <em>{t('title.schedule.em')}</em></> },
    today:        { crumb: dash + t('nav.today'),        title: <>{t('title.today').replace(t('title.today.em'), '').trim()} <em>{t('title.today.em')}</em></> },
    analytics:    { crumb: dash + t('nav.analytics'),    title: <>{t('title.analytics').replace(t('title.analytics.em'), '').trim()} <em>{t('title.analytics.em')}</em></> },
    swot:         { crumb: dash + t('nav.swot'),         title: <>{t('title.swot').replace(t('title.swot.em'), '').trim()} <em>{t('title.swot.em')}</em></> },
    settings:     { crumb: dash + t('nav.settings'),     title: <><em>{t('title.settings')}</em></> }
  };
}

function firstNameOf(user) {
  const full = user?.user_metadata?.full_name || user?.user_metadata?.name || user?.email?.split('@')[0] || 'there';
  return String(full).trim().split(/\s+/)[0];
}
function greetingFor(hour) {
  if (hour < 12) return 'Good morning';
  if (hour < 18) return 'Good afternoon';
  return 'Good evening';
}

const ModeSwitch = ({ mode, setMode, lang }) => {
  const t = (k) => window.__t ? window.__t(k, lang) : k;
  return (
    <div className="mode-switch" data-onboarding-id="mode-switch" role="group" aria-label={t('mode.label')}>
      <span className="mode-switch-label">{t('mode.label')}</span>
      <button className={mode === 'easy' ? 'active' : ''} onClick={() => setMode('easy')} aria-pressed={mode === 'easy'}>{t('mode.easy')}</button>
      <button className={mode === 'advanced' ? 'active' : ''} onClick={() => setMode('advanced')} aria-pressed={mode === 'advanced'}>{t('mode.advanced')}</button>
    </div>
  );
};

const TopBar = ({ section, theme, setTheme, user, lang, setLang, onToggleMobile, mode, setMode }) => {
  const TITLES = buildTitles(lang);
  const meta = TITLES[section] || TITLES.overview;
  const toggleTheme = () => setTheme(theme === 'dark' ? 'light' : 'dark');
  const toggleLang = () => {
    const next = lang === 'ar' ? 'en' : 'ar';
    window.__lang = next;
    document.documentElement.setAttribute('lang', next);
    document.documentElement.setAttribute('dir', next === 'ar' ? 'rtl' : 'ltr');
    setLang(next);
  };
  const t = (k) => window.__t ? window.__t(k, lang) : k;

  const greetingKey = (() => { const h = new Date().getHours(); return h < 12 ? 'greet.morning' : h < 18 ? 'greet.afternoon' : 'greet.evening'; })();
  const title = section === 'overview'
    ? <>{t(greetingKey)}, <em>{firstNameOf(user)}</em></>
    : meta.title;
  return (
    <header className="topbar">
      <button className="mobile-menu-btn" onClick={onToggleMobile} aria-label="Open menu">
        <Icon name="menu" size={18} />
      </button>
      <div className="topbar-left">
        <div className="path">{meta.crumb}</div>
        <h1>{title}</h1>
      </div>
      <div className="topbar-right">
        {setMode && <ModeSwitch mode={mode} setMode={setMode} lang={lang} />}
        <button className="icon-btn" aria-label="Notifications"><Icon name="bell" /><span className="dot" /></button>
        <button data-onboarding-id="top-lang" className="icon-btn" onClick={toggleLang} title={t('top.lang.toggle')}
          style={{ fontFamily: 'var(--mono)', fontSize: 11, fontWeight: 600 }}>
          {lang === 'ar' ? 'EN' : 'ع'}
        </button>
        <button className="icon-btn" onClick={toggleTheme} title="Toggle theme">
          <Icon name={theme === 'dark' ? 'sun' : 'moon'} />
        </button>
      </div>
    </header>
  );
};

window.Sidebar = Sidebar;
window.TopBar = TopBar;
window.initials = initials;
