/* chrome.jsx — responsive top nav, sidebar, audit rail, page shell */

const NAV_SECTIONS = [
  {
    group: 'Lập kế hoạch',
    roles: ['PLANNER','OPS','ADMIN','AUDITOR'],
    items: [
      { id: 'home',         route: '/',                              label: 'Trang chủ',     icon: 'home' },
      { id: 'fc-overview',  route: '/planner/forecast',              label: 'Dự báo',         icon: 'forecast', indent: 0 },
      { id: 'fc-review',    route: '/planner/forecast/review',       label: 'Phê duyệt',         icon: 'check',     indent: 1 },
      { id: 'fc-customer',  route: '/planner/forecast/customer',     label: 'Khách hàng',         icon: 'users',     indent: 1 },
      { id: 'fc-warehouse', route: '/planner/forecast/warehouse',    label: 'Kho',                  icon: 'warehouse', indent: 1 },
      { id: 'plan',         route: '/planner/shift-plan',            label: 'Kế hoạch ca',     icon: 'plan' },
      { id: 'hiring',       route: '/planner/hiring',                label: 'Tuyển dụng',     icon: 'hiring' },
      { id: 'override',     route: '/planner/override-import',       label: 'Gửi điều chỉnh', icon: 'upload' },
      { id: 'history-pl',   route: '/admin/history-import',          label: 'Dữ liệu lịch sử', icon: 'history' },
    ],
  },
  {
    group: 'Cấu hình',
    roles: ['PLANNER','OPS','ADMIN'],
    items: [
      { id: 'cfg-root',    route: '/admin/config',         label: 'Tham số vận hành', icon: 'sliders' },
      { id: 'cfg-dinhmuc', route: '/admin/config/dinhmuc', label: 'Định mức',         icon: 'layers',   indent: 1 },
      { id: 'cfg-thamso',  route: '/admin/config/thamso',  label: 'Tham số',          icon: 'calendar', indent: 1 },
    ],
  },
  {
    group: 'Quản trị',
    roles: ['OPS','ADMIN'],
    items: [
      { id: 'warehouses',   route: '/admin/warehouses',     label: 'Kho',                 icon: 'warehouse' },
      { id: 'staff',        route: '/admin/staff',          label: 'Nhân sự',             icon: 'users' },
      { id: 'history',      route: '/admin/history-import', label: 'Dữ liệu lịch sử',     icon: 'history' },
    ],
  },
  {
    group: 'Kiểm toán',
    roles: ['AUDITOR','ADMIN','OPS'],
    items: [
      { id: 'activity',   route: '/audit/activity',   label: 'Nhật ký hoạt động', icon: 'audit',   disabled: true, hint: 'Sắp có' },
      { id: 'plans',      route: '/audit/plans',      label: 'Lưu trữ kế hoạch', icon: 'history', disabled: true, hint: 'Sắp có' },
    ],
  },
];

// ---------- Sidebar ----------
function Sidebar({ route, navigate, collapsed, onToggle, role, drawerOpen, onCloseDrawer, isMobile }) {
  const W = collapsed && !isMobile ? 64 : 224;

  const body = (
    <>
      <div style={{ flex: 1, overflowY: 'auto', padding: '10px 8px 8px' }}>
        {NAV_SECTIONS.filter(g => g.roles.includes(role)).map(g => (
          <div key={g.group} style={{ marginTop: 8, marginBottom: 4 }}>
            {!(collapsed && !isMobile) && (
              <div style={{
                fontSize: 10, color: 'var(--bx-text-muted)', textTransform: 'uppercase',
                letterSpacing: '0.08em', fontWeight: 700, padding: '8px 10px 4px',
              }}>{g.group}</div>
            )}
            {g.items.map(it => {
              const active = route === it.route;
              const indent = it.indent || 0;
              return (
                <button key={it.id} disabled={it.disabled}
                  onClick={() => { if (!it.disabled) { navigate(it.route); if (isMobile && onCloseDrawer) onCloseDrawer(); } }}
                  title={collapsed && !isMobile ? it.label : undefined}
                  style={{
                    width: '100%', display: 'flex', alignItems: 'center',
                    gap: (collapsed && !isMobile) ? 0 : 10,
                    padding: (collapsed && !isMobile)
                      ? '10px 0'
                      : ('9px 10px 9px ' + (10 + indent * 14) + 'px'),
                    justifyContent: (collapsed && !isMobile) ? 'center' : 'flex-start',
                    borderRadius: 8, cursor: it.disabled ? 'not-allowed' : 'pointer',
                    background: active ? '#eef2ff' : 'transparent',
                    color: active ? 'var(--bx-primary)' : it.disabled ? 'var(--bx-text-muted)' : 'var(--bx-text-body)',
                    fontWeight: active ? 600 : 500, fontSize: 13,
                    marginBottom: 1, border: 'none', textAlign: 'left',
                    fontFamily: 'var(--bx-font-sans)',
                    opacity: it.disabled ? 0.55 : 1,
                    whiteSpace: 'nowrap',
                    position: 'relative',
                  }}>
                  {indent > 0 && !(collapsed && !isMobile) && (
                    <span aria-hidden style={{
                      position: 'absolute', left: 16, top: 4, bottom: 4, width: 1,
                      background: active ? 'var(--bx-primary)' : 'var(--bx-border-muted)', opacity: active ? 0.5 : 1,
                    }}/>
                  )}
                  <Icon name={it.icon} size={15}/>
                  {!(collapsed && !isMobile) && <span style={{ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis' }}>{it.label}</span>}
                  {!(collapsed && !isMobile) && it.hint && <span style={{ fontSize: 9.5, color: 'var(--bx-text-muted)' }}>{it.hint}</span>}
                </button>
              );
            })}
          </div>
        ))}
      </div>
      {!isMobile && (
        <div style={{ borderTop: '1px solid var(--bx-border-muted)', padding: 8 }}>
          <button onClick={onToggle} title={collapsed ? 'Mở rộng' : 'Thu gọn'} style={{
            width: '100%', display: 'flex', alignItems: 'center', justifyContent: collapsed ? 'center' : 'flex-start',
            gap: 10, padding: collapsed ? '8px 0' : '7px 10px',
            border: 'none', background: 'transparent', cursor: 'pointer',
            color: 'var(--bx-text-muted)', fontSize: 12, borderRadius: 8,
          }}>
            <Icon name={collapsed ? 'chevron-right' : 'chevron-left'} size={13}/>
            {!collapsed && <span>Thu gọn</span>}
          </button>
        </div>
      )}
    </>
  );

  if (isMobile) {
    return (
      <>
        {drawerOpen && (
          <div onClick={onCloseDrawer} style={{
            position: 'fixed', inset: 0, background: 'var(--bx-scrim)', zIndex: 70,
          }}/>
        )}
        <aside style={{
          position: 'fixed', top: 0, left: 0, bottom: 0, width: 260,
          background: '#fff', borderRight: '1px solid var(--bx-border-muted)',
          display: 'flex', flexDirection: 'column', flexShrink: 0,
          transform: drawerOpen ? 'translateX(0)' : 'translateX(-100%)',
          transition: 'transform 220ms var(--bx-ease)',
          zIndex: 80, boxShadow: drawerOpen ? 'var(--bx-shadow-pop)' : 'none',
        }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '12px 14px', borderBottom: '1px solid var(--bx-border-muted)' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <div style={{ width: 28, height: 28, borderRadius: 7, background: 'var(--bx-primary)', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 700 }}>W</div>
              <div style={{ fontWeight: 700, fontSize: 13.5, color: 'var(--bx-text-heading)' }}>Kế hoạch nhân sự</div>
            </div>
            <IconBtn name="x" onClick={onCloseDrawer} title="Đóng"/>
          </div>
          {body}
        </aside>
      </>
    );
  }
  return (
    <aside style={{
      width: W, background: '#fff', borderRight: '1px solid var(--bx-border-muted)',
      display: 'flex', flexDirection: 'column', flexShrink: 0,
      transition: 'width 180ms var(--bx-ease)',
    }}>
      {body}
    </aside>
  );
}

// ---------- Switcher (country/warehouse) ----------
function Switcher({ icon, label, value, options, onChange, width = 200, compact }) {
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef(null);
  React.useEffect(() => {
    function onDoc(e) { if (ref.current && !ref.current.contains(e.target)) setOpen(false); }
    document.addEventListener('mousedown', onDoc); return () => document.removeEventListener('mousedown', onDoc);
  }, []);
  const current = options.find(o => o.value === value);
  return (
    <div ref={ref} style={{ position: 'relative' }}>
      <button onClick={() => setOpen(v => !v)} style={{
        display: 'inline-flex', alignItems: 'center', gap: 8, height: 36, padding: '0 10px',
        background: '#fff', border: '1px solid var(--bx-border)',
        borderRadius: 'var(--bx-radius-md)', cursor: 'pointer',
        fontFamily: 'var(--bx-font-sans)', fontSize: 12.5, color: 'var(--bx-text-dark)',
        minWidth: width, maxWidth: width + 60,
      }}>
        {icon ? <Icon name={icon} size={13} style={{ color: 'var(--bx-text-muted)', flexShrink: 0 }}/> : null}
        <div style={{ flex: 1, textAlign: 'left', display: 'flex', flexDirection: 'column', lineHeight: 1.15, minWidth: 0 }}>
          {!compact && <span style={{ fontSize: 10, color: 'var(--bx-text-muted)', textTransform: 'uppercase', letterSpacing: '0.05em', fontWeight: 600, whiteSpace: 'nowrap' }}>{label}</span>}
          <span style={{ fontWeight: 600, marginTop: compact ? 0 : 1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{current ? current.label : '—'}</span>
        </div>
        <Icon name="chevron-down" size={11} style={{ color: 'var(--bx-text-muted)', flexShrink: 0 }}/>
      </button>
      {open && (
        <div style={{
          position: 'absolute', top: 'calc(100% + 4px)', left: 0, minWidth: width + 40, maxWidth: 320,
          background: '#fff', border: '1px solid var(--bx-border-muted)',
          borderRadius: 'var(--bx-radius-md)', boxShadow: 'var(--bx-shadow-pop)',
          zIndex: 60, padding: 4,
        }}>
          {options.map(o => {
            const active = o.value === value;
            return (
              <button key={o.value} onClick={() => { onChange(o.value); setOpen(false); }} style={{
                width: '100%', display: 'flex', alignItems: 'center', gap: 8,
                padding: '8px 10px', border: 'none', background: active ? '#eef2ff' : 'transparent',
                cursor: 'pointer', borderRadius: 6, color: 'var(--bx-text-dark)',
                fontFamily: 'var(--bx-font-sans)', fontSize: 12.5, textAlign: 'left',
              }}>
                <span style={{ flex: 1, minWidth: 0 }}>
                  <span style={{ fontWeight: active ? 600 : 500, whiteSpace: 'nowrap' }}>{o.label}</span>
                  {o.sublabel ? <span style={{ marginLeft: 8, fontSize: 11, color: 'var(--bx-text-muted)' }}>{o.sublabel}</span> : null}
                </span>
                {o.badge ? <Badge kind={o.badge} size="sm">{o.badge}</Badge> : null}
                {active ? <Icon name="check" size={11} style={{ color: 'var(--bx-primary)' }}/> : null}
              </button>
            );
          })}
        </div>
      )}
    </div>
  );
}

// ---------- Scope sheet (mobile/compact): country + warehouse + role chooser ----------
function ScopeSheet({ open, onClose, country, setCountry, warehouseId, setWarehouseId, role, setRole }) {
  if (!open) return null;
  const whOptions = WFP.WAREHOUSES.filter(w => w.countryCode === country);
  return (
    <Dialog open={open} onClose={onClose}
      title="Không gian làm việc"
      subtitle="Chọn quốc gia, kho và vai trò cho phiên hôm nay."
      footer={<Button variant="primary" onClick={onClose}>Xong</Button>}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        <Field label="Quốc gia">
          <div style={{ display: 'flex', gap: 6 }}>
            {WFP.COUNTRIES.map(c => (
              <button key={c.code} onClick={() => setCountry(c.code)} style={{
                flex: 1, padding: '10px 12px', borderRadius: 10, cursor: 'pointer',
                border: '1px solid ' + (country === c.code ? 'var(--bx-primary)' : 'var(--bx-border)'),
                background: country === c.code ? '#eef2ff' : '#fff',
                color: country === c.code ? 'var(--bx-primary)' : 'var(--bx-text-dark)',
                fontWeight: 600, fontSize: 13, fontFamily: 'var(--bx-font-sans)',
                display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2,
              }}>
                <span style={{ fontFamily: 'var(--bx-font-mono)' }}>{c.code}</span>
                <span style={{ fontSize: 11, fontWeight: 400, color: 'var(--bx-text-muted)' }}>{c.name}</span>
              </button>
            ))}
          </div>
        </Field>
        <Field label="Kho">
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            {whOptions.map(w => (
              <button key={w.id} onClick={() => setWarehouseId(w.id)} style={{
                display: 'flex', alignItems: 'center', gap: 10, padding: '10px 12px',
                borderRadius: 10, cursor: 'pointer', textAlign: 'left',
                border: '1px solid ' + (warehouseId === w.id ? 'var(--bx-primary)' : 'var(--bx-border)'),
                background: warehouseId === w.id ? '#eef2ff' : '#fff',
                fontFamily: 'var(--bx-font-sans)',
              }}>
                <Icon name="warehouse" size={14} style={{ color: warehouseId === w.id ? 'var(--bx-primary)' : 'var(--bx-text-muted)' }}/>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontWeight: 600, fontSize: 13, color: 'var(--bx-text-dark)', fontFamily: 'var(--bx-font-mono)' }}>{w.code}</div>
                  <div style={{ fontSize: 11.5, color: 'var(--bx-text-muted)' }}>{w.name}</div>
                </div>
                {warehouseId === w.id && <Icon name="check" size={13} style={{ color: 'var(--bx-primary)' }}/>}
              </button>
            ))}
          </div>
        </Field>
        <Field label="Vai trò của bạn">
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 6 }}>
            {[{ v: 'PLANNER', l: 'Lập kế hoạch' }, { v: 'OPS', l: 'Quản lý vận hành' }, { v: 'ADMIN', l: 'Quản trị' }, { v: 'AUDITOR', l: 'Kiểm toán' }].map(r => (              <button key={r.v} onClick={() => setRole(r.v)} style={{
                padding: '8px 10px', borderRadius: 10, cursor: 'pointer',
                border: '1px solid ' + (role === r.v ? 'var(--bx-primary)' : 'var(--bx-border)'),
                background: role === r.v ? '#eef2ff' : '#fff',
                color: role === r.v ? 'var(--bx-primary)' : 'var(--bx-text-dark)',
                fontWeight: 600, fontSize: 12.5, fontFamily: 'var(--bx-font-sans)',
              }}>{r.l}</button>
            ))}
          </div>
        </Field>
      </div>
    </Dialog>
  );
}

// ---------- TopNav ----------
function TopNav({ country, setCountry, warehouseId, setWarehouseId, role, setRole, openCmdK, openSidebar, user, onLogout }) {
  const { isMobile, isCompact, vw } = useViewport();
  const [scopeOpen, setScopeOpen] = React.useState(false);

  const whOptions = WFP.WAREHOUSES
    .filter(w => w.countryCode === country)
    .map(w => ({ value: w.id, label: w.code, sublabel: w.name, badge: w.active ? 'ACTIVE' : 'INACTIVE' }));
  if (!whOptions.find(o => o.value === warehouseId)) {
    setTimeout(() => setWarehouseId(whOptions[0]?.value), 0);
  }
  const cOptions = WFP.COUNTRIES.map(c => ({ value: c.code, label: c.code, sublabel: c.name }));
  const roleOpts = [
    { value: 'PLANNER',  label: 'Lập kế hoạch' },
    { value: 'OPS',      label: 'Quản lý vận hành' },
    { value: 'ADMIN',    label: 'Quản trị' },
    { value: 'AUDITOR',  label: 'Kiểm toán' },
  ];

  // Mobile / very compact: combined scope chip
  const showFullSwitchers = vw >= 1024;
  const showRolePill      = vw >= 1180;
  const showCmdKLabel     = vw >= 960;
  const showSubtitle      = vw >= 560;
  const showLogoText      = vw >= 480;

  const wh = WFP.WAREHOUSES.find(w => w.id === warehouseId);
  const scopeLabel = country + ' · ' + (wh ? wh.code : '—');

  return (
    <header style={{
      height: 56, background: '#fff',
      borderBottom: '1px solid var(--bx-border-muted)',
      display: 'flex', alignItems: 'center', padding: '0 12px', gap: 10, flexShrink: 0,
    }}>
      {/* Mobile hamburger */}
      {isMobile && (
        <IconBtn name="grid" onClick={openSidebar} title="Menu" style={{ flexShrink: 0 }}/>
      )}

      {/* Logo */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, paddingRight: isCompact ? 0 : 14,
        borderRight: isCompact ? 'none' : '1px solid var(--bx-border-muted)', height: '100%', flexShrink: 0 }}>
        <div style={{
          width: 28, height: 28, borderRadius: 8,
          background: 'var(--bx-primary)', color: '#fff',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontWeight: 700, fontSize: 13,
        }}>W</div>
        {showLogoText && (
          <div style={{ display: 'flex', flexDirection: 'column', lineHeight: 1.1, minWidth: 0 }}>
            <span style={{ fontWeight: 700, fontSize: 13.5, color: 'var(--bx-text-heading)', whiteSpace: 'nowrap' }}>Kế hoạch nhân sự</span>
            {showSubtitle && <span style={{ fontSize: 10, color: 'var(--bx-text-muted)', letterSpacing: '0.05em', whiteSpace: 'nowrap' }}>v2 · Boxme Vận hành</span>}
          </div>
        )}
      </div>

      {/* Switchers (full or condensed) */}
      {showFullSwitchers ? (
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginLeft: 4, minWidth: 0 }}>
          <Switcher icon="globe"     label="Quốc gia" value={country}     options={cOptions}  onChange={setCountry}    width={88}/>
          <Switcher icon="warehouse" label="Kho"      value={warehouseId} options={whOptions} onChange={setWarehouseId} width={180}/>
        </div>
      ) : (
        <button onClick={() => setScopeOpen(true)} style={{
          display: 'inline-flex', alignItems: 'center', gap: 8, height: 36, padding: '0 10px',
          background: '#fff', border: '1px solid var(--bx-border)', borderRadius: 'var(--bx-radius-md)',
          cursor: 'pointer', fontFamily: 'var(--bx-font-sans)', fontSize: 12.5, color: 'var(--bx-text-dark)',
          whiteSpace: 'nowrap', minWidth: 0, flexShrink: 1, overflow: 'hidden',
        }}>
          <Icon name="warehouse" size={13} style={{ color: 'var(--bx-text-muted)' }}/>
          <span style={{ fontWeight: 600, fontFamily: 'var(--bx-font-mono)', overflow: 'hidden', textOverflow: 'ellipsis' }}>{scopeLabel}</span>
          <Icon name="chevron-down" size={11} style={{ color: 'var(--bx-text-muted)' }}/>
        </button>
      )}

      {/* Cmd+K — collapses to icon on narrow */}
      {showCmdKLabel ? (
        <button onClick={openCmdK} style={{
          marginLeft: 'auto', display: 'inline-flex', alignItems: 'center', gap: 8,
          height: 36, padding: '0 10px',
          background: 'var(--bx-surface-2)', border: '1px solid var(--bx-border-muted)',
          borderRadius: 'var(--bx-radius-md)', cursor: 'pointer',
          color: 'var(--bx-text-muted)', fontSize: 12.5, minWidth: 220, maxWidth: 320,
        }}>
          <Icon name="search" size={13}/>
          <span style={{ flex: 1, textAlign: 'left', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>Tìm kế hoạch, nhân sự, tham số…</span>
          <kbd style={{
            fontFamily: 'var(--bx-font-mono)', fontSize: 10.5,
            background: '#fff', border: '1px solid var(--bx-border-muted)',
            padding: '2px 6px', borderRadius: 4, color: 'var(--bx-text-body)',
          }}>⌘K</kbd>
        </button>
      ) : (
        <IconBtn name="search" onClick={openCmdK} title="Tìm · ⌘K" style={{ marginLeft: 'auto' }}/>
      )}

      {/* Right cluster */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 4, flexShrink: 0 }}>
        <button title="Thông báo" style={iconBtnStyle()}>
          <Icon name="bell" size={15}/>
          <span style={{
            position: 'absolute', top: 6, right: 6, width: 7, height: 7,
            background: 'var(--bx-error)', borderRadius: 9999, border: '2px solid #fff',
          }}></span>
        </button>
        {showRolePill && (
          <>
            <div style={{ width: 1, height: 24, background: 'var(--bx-border-muted)', margin: '0 6px' }}/>
            <Switcher icon="shield" label="Vai trò" value={role} options={roleOpts} onChange={setRole} width={130}/>
          </>
        )}
        <div style={{ width: 1, height: 24, background: 'var(--bx-border-muted)', margin: '0 4px' }}/>
        <UserMenu user={user} role={role} setRole={setRole} onLogout={onLogout} compact={!showRolePill}/>
      </div>

      <ScopeSheet open={scopeOpen} onClose={() => setScopeOpen(false)}
        country={country} setCountry={setCountry}
        warehouseId={warehouseId} setWarehouseId={setWarehouseId}
        role={role} setRole={setRole}/>
    </header>
  );
}

function iconBtnStyle() {
  return {
    position: 'relative', width: 34, height: 34, border: 'none',
    background: 'transparent', borderRadius: 8,
    display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
    color: 'var(--bx-text-body)', cursor: 'pointer', flexShrink: 0,
  };
}

function UserMenu({ user, role, setRole, onLogout, compact }) {
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef(null);
  React.useEffect(() => {
    function onDoc(e) { if (ref.current && !ref.current.contains(e.target)) setOpen(false); }
    document.addEventListener('mousedown', onDoc); return () => document.removeEventListener('mousedown', onDoc);
  }, []);
  return (
    <div ref={ref} style={{ position: 'relative' }}>
      <button onClick={() => setOpen(v => !v)} style={{
        display: 'flex', alignItems: 'center', gap: 8, padding: '4px 8px 4px 4px',
        borderRadius: 9999, cursor: 'pointer', border: 'none', background: 'transparent',
      }}>
        <Avatar name={user.name}/>
        {!compact && (
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-start', lineHeight: 1.1 }}>
            <span style={{ fontSize: 12.5, color: 'var(--bx-text-dark)', fontWeight: 600, whiteSpace: 'nowrap' }}>{user.name}</span>
            <span style={{ fontSize: 10.5, color: 'var(--bx-text-muted)', whiteSpace: 'nowrap' }}>{user.email}</span>
          </div>
        )}
        {!compact && <Icon name="chevron-down" size={11} style={{ color: 'var(--bx-text-muted)' }}/>}
      </button>
      {open && (
        <div style={{
          position: 'absolute', top: 'calc(100% + 6px)', right: 0, minWidth: 240,
          background: '#fff', border: '1px solid var(--bx-border-muted)',
          borderRadius: 'var(--bx-radius-md)', boxShadow: 'var(--bx-shadow-pop)',
          zIndex: 60, padding: 4,
        }}>
          <div style={{ padding: '10px 12px', borderBottom: '1px solid var(--bx-border-muted)' }}>
            <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--bx-text-heading)' }}>{user.name}</div>
            <div style={{ fontSize: 11, color: 'var(--bx-text-muted)' }}>{user.email}</div>
          </div>
          {compact && (
            <div style={{ padding: 8 }}>
              <div style={{ fontSize: 10, color: 'var(--bx-text-muted)', textTransform: 'uppercase', letterSpacing: '0.05em', fontWeight: 600, marginBottom: 6 }}>Vai trò</div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 4 }}>
                {[{ v: 'PLANNER', l: 'Lập KH' }, { v: 'OPS', l: 'Vận hành' }, { v: 'ADMIN', l: 'Quản trị' }, { v: 'AUDITOR', l: 'Kiểm toán' }].map(r => (                  <button key={r.v} onClick={() => setRole(r.v)} style={{
                    padding: '6px 8px', borderRadius: 6, fontSize: 12, cursor: 'pointer',
                    border: '1px solid ' + (role === r.v ? 'var(--bx-primary)' : 'var(--bx-border-muted)'),
                    background: role === r.v ? '#eef2ff' : '#fff',
                    color: role === r.v ? 'var(--bx-primary)' : 'var(--bx-text-dark)',
                    fontWeight: 600, fontFamily: 'var(--bx-font-sans)',
                  }}>{r.l}</button>
                ))}
              </div>
            </div>
          )}
          <MenuItem icon="user" label="Hồ sơ của tôi"/>
          <MenuItem icon="cog"  label="Tùy chỉnh"/>
          <MenuItem icon="mail" label="Hộp thư"/>
          <div style={{ height: 1, background: 'var(--bx-border-muted)', margin: '4px 0' }}/>
          <MenuItem icon="logout" label="Đăng xuất" onClick={onLogout} danger/>
        </div>
      )}
    </div>
  );
}
function MenuItem({ icon, label, onClick, danger }) {
  return (
    <button onClick={onClick} style={{
      width: '100%', display: 'flex', alignItems: 'center', gap: 10,
      padding: '8px 10px', border: 'none', background: 'transparent', cursor: 'pointer',
      borderRadius: 6, fontFamily: 'var(--bx-font-sans)', fontSize: 12.5,
      color: danger ? 'var(--bx-error)' : 'var(--bx-text-dark)', textAlign: 'left',
    }}>
      <Icon name={icon} size={13}/><span>{label}</span>
    </button>
  );
}

// ---------- Cmd+K Palette ----------
function CmdK({ open, onClose, navigate }) {
  const [q, setQ] = React.useState('');
  const { isMobile } = useViewport();
  React.useEffect(() => { if (open) setQ(''); }, [open]);
  if (!open) return null;
  const ROUTES = [
    { route: '/',                              label: 'Trang chủ',                       group: 'Điểm đến', icon: 'home' },
    { route: '/planner/forecast',              label: 'Dự báo · tổng quan',            group: 'Điểm đến', icon: 'forecast' },
    { route: '/planner/forecast/review',       label: 'Dự báo · phê duyệt',         group: 'Điểm đến', icon: 'check' },
    { route: '/planner/forecast/customer',     label: 'Dự báo · khách hàng',         group: 'Điểm đến', icon: 'users' },
    { route: '/planner/forecast/warehouse',    label: 'Dự báo · kho',                  group: 'Điểm đến', icon: 'warehouse' },
    { route: '/planner/shift-plan',            label: 'Kế hoạch ca',                     group: 'Điểm đến', icon: 'plan' },
    { route: '/planner/hiring',                label: 'Yêu cầu tuyển dụng',           group: 'Điểm đến', icon: 'hiring' },
    { route: '/planner/override-import',       label: 'Gửi điều chỉnh dự báo',       group: 'Điểm đến', icon: 'upload' },
    { route: '/admin/warehouses',              label: 'Kho',                              group: 'Điểm đến', icon: 'warehouse' },
    { route: '/admin/staff',                   label: 'Nhân sự',                         group: 'Điểm đến', icon: 'users' },
    { route: '/admin/history-import',          label: 'Nhập dữ liệu lịch sử',           group: 'Điểm đến', icon: 'history' },
    { route: '/admin/config',                  label: 'Cấu hình · Tham số vận hành',     group: 'Điểm đến', icon: 'sliders' },
    { route: '/admin/config/dinhmuc',          label: 'Cấu hình · Định mức (WLU)',       group: 'Điểm đến', icon: 'layers' },
    { route: '/admin/config/thamso',           label: 'Cấu hình · Tham số mùa vụ & sale', group: 'Điểm đến', icon: 'calendar' },
  ];
  const filtered = ROUTES.filter(r => !q || r.label.toLowerCase().includes(q.toLowerCase()));
  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, background: 'var(--bx-scrim)', zIndex: 200,
      display: 'flex', alignItems: 'flex-start', justifyContent: 'center', paddingTop: isMobile ? '6vh' : '14vh',
      padding: isMobile ? '6vh 12px' : '14vh 24px',
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        width: 560, maxWidth: '100%', background: '#fff', borderRadius: 'var(--bx-radius-lg)',
        boxShadow: 'var(--bx-shadow-pop)', overflow: 'hidden',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '12px 14px', borderBottom: '1px solid var(--bx-border-muted)' }}>
          <Icon name="search" size={14} style={{ color: 'var(--bx-text-muted)' }}/>
          <input autoFocus value={q} onChange={e => setQ(e.target.value)}
            placeholder="Tìm trang, nhân sự, tham số…"
            style={{ flex: 1, border: 'none', outline: 'none', fontSize: 14, fontFamily: 'var(--bx-font-sans)', color: 'var(--bx-text-dark)', minWidth: 0 }}
          />
          <kbd style={{ fontFamily: 'var(--bx-font-mono)', fontSize: 10.5, padding: '2px 6px', border: '1px solid var(--bx-border-muted)', borderRadius: 4, color: 'var(--bx-text-muted)' }}>esc</kbd>
        </div>
        <div style={{ maxHeight: 360, overflowY: 'auto', padding: 6 }}>
          {filtered.length === 0 ? (
            <div style={{ padding: 24, textAlign: 'center', color: 'var(--bx-text-muted)', fontSize: 12.5 }}>Không có kết quả</div>
          ) : (
            <div>
              <div style={{ fontSize: 10, color: 'var(--bx-text-muted)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 700, padding: '8px 10px 4px' }}>Điểm đến</div>
              {filtered.map(r => (
                <button key={r.route} onClick={() => { navigate(r.route); onClose(); }} style={{
                  width: '100%', display: 'flex', alignItems: 'center', gap: 10,
                  padding: '10px 10px', border: 'none', background: 'transparent', cursor: 'pointer',
                  borderRadius: 6, fontSize: 13, color: 'var(--bx-text-dark)', textAlign: 'left',
                  fontFamily: 'var(--bx-font-sans)',
                }}
                onMouseEnter={e => e.currentTarget.style.background = '#f5f5f5'}
                onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                  <Icon name={r.icon} size={13} style={{ color: 'var(--bx-text-muted)' }}/>
                  <span style={{ flex: 1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{r.label}</span>
                  <span style={{ fontFamily: 'var(--bx-font-mono)', fontSize: 11, color: 'var(--bx-text-muted)' }}>{r.route}</span>
                </button>
              ))}
            </div>
          )}
        </div>
        {!isMobile && (
          <div style={{
            padding: '8px 14px', borderTop: '1px solid var(--bx-border-muted)',
            background: 'var(--bx-surface-2)', display: 'flex', gap: 16,
            fontSize: 11, color: 'var(--bx-text-muted)',
          }}>
            <span><kbd style={kbd}>↑↓</kbd> di chuyển</span>
            <span><kbd style={kbd}>↵</kbd> mở</span>
            <span><kbd style={kbd}>esc</kbd> đóng</span>
          </div>
        )}
      </div>
    </div>
  );
}
const kbd = { fontFamily: 'var(--bx-font-mono)', background: '#fff', padding: '1px 5px', border: '1px solid var(--bx-border-muted)', borderRadius: 4, marginRight: 4 };

// ---------- Page header (responsive) ----------
function PageHeader({ title, subtitle, breadcrumb, actions, status, children }) {
  const { isMobile, isTablet } = useViewport();
  const stacked = isMobile;
  return (
    <div style={{
      padding: stacked ? '14px 16px 12px' : '20px 24px 16px',
      borderBottom: '1px solid var(--bx-border-muted)',
      background: '#fff', display: 'flex', flexDirection: 'column', gap: 8,
    }}>
      {breadcrumb && !stacked && (
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 11.5, color: 'var(--bx-text-muted)', flexWrap: 'wrap' }}>
          {breadcrumb.map((b, i) => (
            <React.Fragment key={i}>
              {i > 0 ? <Icon name="chevron-right" size={9}/> : null}
              <span style={{
                fontWeight: i === breadcrumb.length - 1 ? 600 : 400,
                color: i === breadcrumb.length - 1 ? 'var(--bx-text-dark)' : 'var(--bx-text-muted)',
                whiteSpace: 'nowrap',
              }}>{b}</span>
            </React.Fragment>
          ))}
        </div>
      )}
      <div style={{
        display: 'flex',
        alignItems: stacked ? 'stretch' : 'center',
        justifyContent: 'space-between', gap: stacked ? 10 : 16,
        flexDirection: stacked ? 'column' : 'row',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, minWidth: 0, flexWrap: 'wrap' }}>
          <div style={{ minWidth: 0 }}>
            <h1 style={{
              fontSize: stacked ? 18 : 22, fontWeight: 600,
              color: 'var(--bx-text-heading)', margin: 0, letterSpacing: '-0.01em',
              lineHeight: 1.2, textWrap: 'balance',
            }}>{title}</h1>
            {subtitle && (
              <div style={{
                fontSize: stacked ? 12 : 13, color: 'var(--bx-text-muted)',
                marginTop: 4, lineHeight: 1.45,
              }}>{subtitle}</div>
            )}
          </div>
          {status ? <div style={{ marginLeft: 4 }}>{status}</div> : null}
        </div>
        {actions ? (
          <div style={{
            display: 'flex', gap: 8, alignItems: 'center',
            flexWrap: 'wrap',
            justifyContent: stacked ? 'flex-end' : 'flex-end',
          }}>{actions}</div>
        ) : null}
      </div>
      {children}
    </div>
  );
}

// ---------- Audit Trail Rail ----------
function AuditRail({ entries, title = 'Nhật ký' }) {
  return (
    <div style={{
      width: 280, flexShrink: 0, background: '#fff',
      borderLeft: '1px solid var(--bx-border-muted)',
      display: 'flex', flexDirection: 'column',
    }}>
      <div style={{ padding: '14px 16px', borderBottom: '1px solid var(--bx-border-muted)' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 11, color: 'var(--bx-text-muted)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 700 }}>
          <Icon name="audit" size={11}/><span>{title}</span>
        </div>
      </div>
      <div style={{ flex: 1, overflowY: 'auto', padding: 14 }}>
        {entries.length === 0 ? (
          <div style={{ fontSize: 12, color: 'var(--bx-text-muted)', textAlign: 'center', padding: 24 }}>Chưa có hoạt động</div>
        ) : entries.map((e, i) => (
          <div key={i} style={{ display: 'flex', gap: 10, paddingBottom: 14, position: 'relative' }}>
            <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', flexShrink: 0 }}>
              <div style={{ width: 8, height: 8, borderRadius: 9999, background: 'var(--bx-primary)', marginTop: 5 }}></div>
              {i < entries.length - 1 ? <div style={{ flex: 1, width: 1, background: 'var(--bx-border-muted)', marginTop: 4 }}></div> : null}
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 12, color: 'var(--bx-text-dark)', lineHeight: 1.45 }}>{e.what}</div>
              <div style={{ fontSize: 11, color: 'var(--bx-text-muted)', marginTop: 4, display: 'flex', gap: 8 }}>
                <span style={{ fontFamily: 'var(--bx-font-mono)' }}>{fmt.dateTime(e.ts)}</span>
                <span>·</span>
                <span>{e.who}</span>
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ---------- Toaster ----------
function Toaster({ toasts, dismiss }) {
  return (
    <div style={{
      position: 'fixed', bottom: 16, right: 16, left: 16, zIndex: 150,
      display: 'flex', flexDirection: 'column', gap: 8, alignItems: 'flex-end',
      pointerEvents: 'none',
    }}>
      {toasts.map(t => (
        <div key={t.id} style={{ pointerEvents: 'auto', maxWidth: 'min(380px, 100%)' }}>
          <Toast kind={t.kind} title={t.title} body={t.body} onClose={() => dismiss(t.id)}/>
        </div>
      ))}
    </div>
  );
}

// expose
Object.assign(window, { Sidebar, TopNav, CmdK, PageHeader, AuditRail, Toaster, NAV_SECTIONS, UserMenu, ScopeSheet });
