// shell.jsx — portal chrome + the shared PortalContext (provided by main.jsx).
const { useState: uS, useRef: uR, useEffect: uE, useMemo: uM, createContext: cC, useContext: uC } = React;

const PortalContext = cC(null);
function usePortal(){ return uC(PortalContext); }

/* ===================== Topbar ===================== */
function Topbar() {
  const p = usePortal();
  const { lang, setLang, t, tt } = useLang();
  const me = p.me;
  const roleColors = { staff:'var(--text-muted)', manager:'var(--accent)', admin:'var(--primary)' };
  const unread = NOTIFS.filter(n => n.unread).length;
  return (
    <div className="topbar">
      <button className="iconbtn mobile-only" onClick={() => p.setDrawerOpen(true)} aria-label="Menu"><i className="bi bi-list" style={{ fontSize:20 }}></i></button>
      <span className="bname mobile-only" style={{ marginRight:2 }}>My S.W.O</span>
      <button className="topsearch" onClick={p.openCmdk}>
        <i className="bi bi-search"></i><span className="grow" style={{ textAlign:'left' }}>{t('shell.search')}</span>
        <kbd>⌘K</kbd>
      </button>
      <div className="spacer"></div>

      {/* role switcher */}
      <Popover align="right" width={180} button={({ toggle }) => (
        <button className="role-pill" onClick={toggle}>
          <span className="rdot" style={{ background:roleColors[p.role] }}></span>
          <span className="rlabel">{t('role.' + p.role)}</span><i className="bi bi-chevron-down" style={{ fontSize:10, color:'var(--text-subtle)' }}></i>
        </button>
      )}>
        {({ close }) => (
          <>
            <div className="menu-label">{t('role.switch')}</div>
            {['staff','manager','admin'].map(r => (
              <button key={r} className="menu-item" onClick={() => { p.setRole(r); close(); }}>
                <span className="rdot" style={{ width:7, height:7, borderRadius:'50%', background:roleColors[r] }}></span>
                {t('role.' + r)}{p.role === r && <i className="bi bi-check2" style={{ marginLeft:'auto' }}></i>}
              </button>
            ))}
          </>
        )}
      </Popover>

      {/* language */}
      <span className="lang-seg"><Segmented value={lang} onChange={setLang} options={[{ value:'vi', label:'VI' }, { value:'en', label:'EN' }]} /></span>

      {/* notifications */}
      <Popover align="right" width={300} button={({ toggle }) => (
        <button className="iconbtn" onClick={toggle} aria-label="Notifications">
          <i className="bi bi-bell"></i>{unread > 0 && <span className="nbadge">{unread}</span>}
        </button>
      )}>
        <div className="menu-label">{t('nav.notifs')}</div>
        {NOTIFS.map(n => (
          <div key={n.id} className="menu-item" style={{ height:'auto', alignItems:'flex-start', padding:'7px 9px' }}>
            <i className={'bi ' + n.icon}></i>
            <div style={{ flex:1 }}>
              <div style={{ fontWeight:n.unread ? 600 : 400 }}>{tt(n.text)}</div>
              <div className="subtle" style={{ fontSize:'var(--fs-sm)' }}>{n.time}</div>
            </div>
            {n.unread && <span className="rdot" style={{ width:6, height:6, borderRadius:'50%', background:'var(--primary)', marginTop:5 }}></span>}
          </div>
        ))}
      </Popover>

      {/* app launcher */}
      <Popover align="right" button={({ toggle }) => (
        <button className="iconbtn hide-sm" onClick={toggle} aria-label="Apps"><span className="dot9">{Array.from({length:9}).map((_,i)=><i key={i}></i>)}</span></button>
      )}>
        {({ close }) => <AppLauncher onClose={close} />}
      </Popover>

      {/* user menu */}
      <Popover align="right" width={210} button={({ toggle }) => (
        <button className="iconbtn" onClick={toggle} style={{ width:'auto', gap:7, paddingLeft:4 }}>
          <Avatar name={me.name} size={26} />
        </button>
      )}>
        {({ close }) => (
          <>
            <div style={{ padding:'8px 10px 6px' }}>
              <div style={{ fontWeight:600 }}>{me.name}</div>
              <div className="subtle mono" style={{ fontSize:'var(--fs-sm)' }}>{me.email}</div>
            </div>
            <div className="menu-sep"></div>
            <button className="menu-item" onClick={() => { p.navigate({ name:'settings' }); close(); }}><i className="bi bi-gear"></i>{t('nav.settings')}</button>
            <button className="menu-item" onClick={close}><i className="bi bi-person"></i>{me.title}</button>
            <div className="menu-sep"></div>
            <button className="menu-item danger" onClick={() => { p.logout(); close(); }}><i className="bi bi-box-arrow-right"></i>{lang === 'vi' ? 'Đăng xuất' : 'Sign out'}</button>
          </>
        )}
      </Popover>
    </div>
  );
}

/* ===================== App launcher popover ===================== */
function AppLauncher({ onClose }) {
  const p = usePortal();
  const { tt, t } = useLang();
  const apps = p.apps.slice(0, 9);
  return (
    <div className="launcher">
      <div className="lgrid">
        {apps.map(a => (
          <button key={a.id} className="ltile" onClick={() => { p.openApp(a); onClose(); }}>
            <span className="ic" style={{ background:a.color }}><i className={'bi ' + a.icon}></i></span>
            <span className="lt">{tt(a.name)}</span>
          </button>
        ))}
      </div>
      <div className="menu-sep"></div>
      <button className="menu-item" onClick={() => { p.navigate({ name:'allapps' }); onClose(); }} style={{ justifyContent:'center', color:'var(--primary)', fontWeight:600 }}>
        {t('shell.allApps')}<i className="bi bi-arrow-right"></i>
      </button>
    </div>
  );
}

/* ===================== Brandbar ===================== */
function Brandbar() {
  const p = usePortal();
  return (
    <div className="brandbar">
      <button className="brand-logo-btn" onClick={() => p.setCollapsed(c => !c)} aria-label="Toggle sidebar" title={p.collapsed ? 'Mở rộng thanh bên' : 'Thu gọn thanh bên'}>
        <span className="swo-mark" style={{ width:26, height:26, fontSize:10 }}>SWO</span>
      </button>
      <span className="bname">My S.W.O</span>
      <button className="iconbtn collapse-btn" onClick={() => p.setCollapsed(c => !c)} aria-label="Collapse sidebar" title="Thu gọn thanh bên">
        <i className="bi bi-chevron-double-left"></i>
      </button>
    </div>
  );
}

/* ===================== Command palette ===================== */
function CommandPalette({ onClose }) {
  const p = usePortal();
  const { tt, t } = useLang();
  const [q, setQ] = uS('');
  const [idx, setIdx] = uS(0);
  const inputRef = uR();
  uE(() => { inputRef.current && inputRef.current.focus(); }, []);
  const nav = [
    { id:'dashboard', icon:'bi-grid-1x2', color:'var(--primary)', label:t('nav.dashboard'), run:() => p.navigate({ name:'dashboard' }) },
    { id:'allapps', icon:'bi-grid-3x3-gap', color:'var(--accent)', label:t('nav.allApps'), run:() => p.navigate({ name:'allapps' }) },
  ];
  const appItems = p.apps.map(a => ({ id:'app-' + a.id, icon:a.icon, color:a.color, label:tt(a.name), meta:'App', run:() => p.openApp(a) }));
  const all = [...nav, ...appItems];
  const filtered = q ? all.filter(i => i.label.toLowerCase().includes(q.toLowerCase())) : all;
  uE(() => { setIdx(0); }, [q]);
  const run = (i) => { const item = filtered[i]; if (item) { item.run(); onClose(); } };
  return (
    <div className="cmdk-overlay" onMouseDown={e => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="cmdk">
        <div className="cmdk-input">
          <i className="bi bi-search"></i>
          <input ref={inputRef} value={q} placeholder={lAng(t)}
            onChange={e => setQ(e.target.value)}
            onKeyDown={e => {
              if (e.key === 'ArrowDown') { e.preventDefault(); setIdx(i => Math.min(i + 1, filtered.length - 1)); }
              else if (e.key === 'ArrowUp') { e.preventDefault(); setIdx(i => Math.max(i - 1, 0)); }
              else if (e.key === 'Enter') { e.preventDefault(); run(idx); }
              else if (e.key === 'Escape') onClose();
            }} />
          <kbd>esc</kbd>
        </div>
        <div className="cmdk-list">
          {filtered.length === 0 && <div className="empty" style={{ padding:24 }}><div>{t('c.empty')}</div></div>}
          {filtered.map((i, n) => (
            <div key={i.id} className={'cmdk-item' + (n === idx ? ' is-active' : '')}
              onMouseEnter={() => setIdx(n)} onClick={() => run(n)}>
              <span className="ic" style={{ background:i.color }}><i className={'bi ' + i.icon}></i></span>
              <span>{i.label}</span>{i.meta && <span className="meta">{i.meta}</span>}
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}
function lAng(t){ return t('shell.search'); }

/* ===================== Portal FAB (draggable) ===================== */
function PortalFAB() {
  const p = usePortal();
  const { t } = useLang();
  const [pos, setPos] = usePersist('fab-pos', { x: window.innerWidth - 150, y: window.innerHeight - 70 });
  const drag = uR({ on:false, moved:false, dx:0, dy:0 });
  const onDown = (e) => {
    drag.current = { on:true, moved:false, dx:e.clientX - pos.x, dy:e.clientY - pos.y };
    const move = (ev) => {
      if (!drag.current.on) return;
      drag.current.moved = true;
      setPos({ x:Math.max(8, Math.min(window.innerWidth - 130, ev.clientX - drag.current.dx)),
               y:Math.max(8, Math.min(window.innerHeight - 50, ev.clientY - drag.current.dy)) });
    };
    const up = () => { drag.current.on = false; document.removeEventListener('mousemove', move); document.removeEventListener('mouseup', up); };
    document.addEventListener('mousemove', move); document.addEventListener('mouseup', up);
  };
  return (
    <button className="fab" style={{ left:pos.x, top:pos.y }}
      onMouseDown={onDown}
      onClick={() => { if (!drag.current.moved) p.navigate({ name:'dashboard' }); }}>
      <i className="bi bi-grid-1x2-fill"></i>{t('shell.backPortal')}
    </button>
  );
}

Object.assign(window, { PortalContext, usePortal, Topbar, Brandbar, AppLauncher, CommandPalette, PortalFAB });
