// Shell: Header, Sidebar, Toasts
const { useState, useEffect, useMemo, useRef, useCallback } = React;

function Header({ onNavigate, currentPage, role, setRole, unread, onHelp, onMenuToggle }) {
  const [roleOpen, setRoleOpen] = useState(false);
  const ref = useRef(null);
  useEffect(() => {
    const close = (e) => { if (ref.current && !ref.current.contains(e.target)) setRoleOpen(false); };
    document.addEventListener('click', close);
    return () => document.removeEventListener('click', close);
  }, []);

  const roles = [
    { id: 'learner', label: 'Learner', sub: 'Cardiology Nurse', icon: I.Stethoscope },
    { id: 'manager', label: 'Manager', sub: 'Compliance', icon: I.BarChart },
    { id: 'admin', label: 'Admin', sub: 'Content Library', icon: I.Folder },
  ];
  const current = roles.find(r => r.id === role);

  return (
    <header className="header" role="banner">
      <button className="icon-btn mobile-menu-btn" aria-label="Open navigation" onClick={onMenuToggle}>
        <I.Menu size={18}/>
      </button>
      <button className="logo" onClick={() => onNavigate(role === 'manager' ? 'manager' : role === 'admin' ? 'admin' : 'dashboard')}>
        <span className="logo-mark"><I.Shield size={14} color="white"/></span>
        MediShield
      </button>
      <div className="header-search">
        <I.Search size={14}/>
        <input placeholder="Search trainings, policies, incidents" aria-label="Search"/>
        <span className="kbd">⌘K</span>
      </div>
      <div className="header-right">
        <div style={{position: 'relative'}} ref={ref}>
          <button className="role-select" onClick={(e) => { e.stopPropagation(); setRoleOpen(v => !v); }} aria-label="Switch role (demo)" aria-expanded={roleOpen}>
            <span className="role-select-label">View as</span>
            <span style={{color: 'var(--navy)', fontWeight: 600}}>{current.label}</span>
            <I.ChevronDown size={13}/>
          </button>
          {roleOpen && (
            <div className="role-menu">
              <div style={{padding: '8px 12px', fontSize: 10.5, textTransform: 'uppercase', letterSpacing: '0.05em', color: 'var(--ink-4)', fontWeight: 600, borderBottom: '1px solid var(--border-3)'}}>
                Demo — switch perspective
              </div>
              {roles.map(r => {
                const Icon = r.icon;
                return (
                  <button key={r.id} className={role === r.id ? 'active' : ''} onClick={() => { setRole(r.id); setRoleOpen(false); }}>
                    <Icon size={14}/>
                    <div>
                      <div style={{fontWeight: 600}}>{r.label}</div>
                      <div style={{fontSize: 11, color: 'var(--ink-3)', fontWeight: 400}}>{r.sub}</div>
                    </div>
                    {role === r.id && <span className="check"><I.CheckCircle size={14}/></span>}
                  </button>
                );
              })}
            </div>
          )}
        </div>
        <div style={{width: 1, height: 20, background: 'var(--border)', margin: '0 6px'}}/>
        <button className="icon-btn" aria-label="Help" onClick={onHelp}><I.Info size={15}/></button>
        <button className="icon-btn" aria-label={`Notifications (${unread} unread)`}>
          <I.Bell size={15}/>
          {unread > 0 && <span className="badge-dot"/>}
        </button>
        <div style={{width: 1, height: 20, background: 'var(--border)', margin: '0 6px'}}/>
        <button className="user-chip" aria-label="User menu">
          <span className="avatar">EP</span>
          <span className="user-info">
            <span className="user-name" style={{display: 'block'}}>Dr. E. Papadaki</span>
            <span className="user-role">
              {role === 'manager' ? 'Compliance Manager' : role === 'admin' ? 'Content Admin' : 'Cardiology Nurse'}
            </span>
          </span>
        </button>
      </div>
    </header>
  );
}

function Sidebar({ current, onNavigate, role, onHelp, onSignOut, mobileOpen, onMobileClose }) {
  const learnerNav = [
    { id: 'dashboard', label: 'Home', icon: I.Home },
    { id: 'lesson', label: 'My training', icon: I.BookOpen, count: 3 },
    { id: 'phishing', label: 'Simulations', icon: I.Target },
    { id: 'incident', label: 'Report incident', icon: I.Flag },
  ];
  const managerNav = [
    { id: 'manager', label: 'Compliance', icon: I.BarChart },
    { id: 'triage', label: 'Triage queue', icon: I.Flag, count: 2 },
    { id: 'audit', label: 'Audit log', icon: I.FileText },
    { id: 'dashboard', label: 'My training', icon: I.BookOpen },
    { id: 'phishing', label: 'Simulations', icon: I.Target },
    { id: 'incident', label: 'Report incident', icon: I.Flag },
  ];
  const adminNav = [
    { id: 'admin', label: 'Content library', icon: I.Folder },
    { id: 'audit', label: 'Audit log', icon: I.FileText },
    { id: 'manager', label: 'Compliance', icon: I.BarChart },
    { id: 'dashboard', label: 'My training', icon: I.BookOpen },
  ];

  const nav = role === 'manager' ? managerNav : role === 'admin' ? adminNav : learnerNav;

  const navigate = (id) => {
    onNavigate(id);
    if (onMobileClose) onMobileClose();
  };

  return (
    <>
    {mobileOpen && <div className="mobile-nav-scrim" onClick={onMobileClose}/>}
    <div className={`sidebar-col ${mobileOpen ? 'mobile-open' : ''}`}>
    <aside className="sidebar" aria-label="Primary navigation">
      <button className="icon-btn mobile-close-btn" aria-label="Close navigation" onClick={onMobileClose}>
        <I.X size={16}/>
      </button>
      <div className="side-section-label">Workspace</div>
      {nav.map(item => {
        const Icon = item.icon;
        const active = current === item.id;
        const tourKey =
          role === 'learner' && item.id === 'lesson' ? 'learner-training' :
          role === 'learner' && item.id === 'phishing' ? 'learner-simulations' :
          role === 'learner' && item.id === 'incident' ? 'learner-incident' :
          null;
        return (
          <button
            key={item.id}
            className={`side-item ${active ? 'active' : ''}`}
            onClick={() => navigate(item.id)}
            data-tour={tourKey || undefined}
          >
            <Icon size={15}/>
            <span>{item.label}</span>
            {item.count && <span className="side-count">{item.count}</span>}
          </button>
        );
      })}

      <div className="side-divider"/>
      <div className="side-section-label">Account</div>
      <button className="side-item"><I.Settings size={15}/> Settings</button>
      <button className="side-item" onClick={onSignOut}><I.LogOut size={15}/> Sign out</button>

      <div className="side-divider"/>
      <button className="side-item" onClick={onHelp} aria-label="Open help">
        <I.HelpCircle size={15}/> Help
      </button>
      <div style={{padding: '8px 16px 12px'}}>
        <div style={{background: 'var(--bg)', padding: 12, border: '1px solid var(--border-2)', borderRadius: 2}}>
          <div style={{display: 'flex', gap: 7, alignItems: 'center', marginBottom: 6}}>
            <I.FileText size={13} color="var(--ink-3)"/>
            <span style={{fontSize: 10.5, fontWeight: 700, color: 'var(--navy)', textTransform: 'uppercase', letterSpacing: '0.05em'}}>Policy reminder</span>
          </div>
          <p style={{fontSize: 11.5, color: 'var(--ink-2)', lineHeight: 1.5}}>
            Report suspicious emails immediately via the Report Phishing button or call SOC at x4400.
          </p>
        </div>
      </div>
    </aside>
    </div>
    </>
  );
}

function ToastContainer({ toasts }) {
  return (
    <div className="toast-container" aria-live="polite" aria-atomic="true">
      {toasts.map(t => (
        <div key={t.id} className={`toast ${t.kind || ''}`}>
          {t.kind === 'success' && <I.CheckCircle size={14}/>}
          {t.kind === 'error' && <I.AlertTriangle size={14}/>}
          {!t.kind && <I.Info size={14}/>}
          {t.message}
        </div>
      ))}
    </div>
  );
}

function PageFooter() {
  return (
    <div className="page-footer">
      <div>
        <strong style={{color: 'var(--navy)'}}>MediShield</strong>
        <span className="sep">·</span>Demo build
        <span className="sep">·</span>Synthetic data only
        <span className="sep">·</span>St. Luke General Hospital
        <span className="sep">·</span>WCAG 2.2 AA
      </div>
      <div style={{display: 'flex', gap: 16}}>
        <span>HIPAA<HelpIcon title="HIPAA" text="US Health Insurance Portability and Accountability Act — federal privacy & security rules for patient health information."/></span>
        <span>NIST CSF 2.0<HelpIcon title="NIST CSF 2.0" text="US National Institute of Standards and Technology Cybersecurity Framework, version 2.0."/></span>
        <span>Tbilisi Conference 2026</span>
      </div>
    </div>
  );
}

// Deprecated but kept for prop compat
function RoleSwitcher() { return null; }

Object.assign(window, { Header, Sidebar, RoleSwitcher, ToastContainer, PageFooter });
