/* global React, Ic, useStore */
const { useState: useS1, useMemo: useM1, useEffect: useE1, useRef: useR1 } = React;

// ============ Sidebar ============
function Sidebar({ active, onNav }) {
  const allGroups = [
    { label: 'Overview', items: [
      { id: 'dashboard', label: 'Dashboard', icon: 'dashboard' },
    ]},
    { label: 'Operations', items: [
      { id: 'receive', label: 'รับเข้า', sub: 'Goods Receipt', icon: 'receive' },
      { id: 'issue', label: 'จ่ายออก', sub: 'Goods Issue', icon: 'issue' },
      { id: 'transfer', label: 'โอนระหว่าง Location', sub: 'Transfer', icon: 'transfer' },
      { id: 'count', label: 'Stock Count', sub: 'Cycle Count', icon: 'count' },
      { id: 'scanner', label: 'Barcode Scanner', icon: 'scanner' },
    ]},
    { label: 'Inventory', items: [
      { id: 'items', label: 'รายการสินค้า', sub: 'Item Master', icon: 'items' },
      { id: 'locations', label: 'Locations & Map', icon: 'map' },
    ]},
    { label: 'Reports', items: [
      { id: 'stock-report', label: 'สต็อกคงเหลือ', sub: 'Stock Balance', icon: 'report' },
      { id: 'movement', label: 'รายการเคลื่อนไหว', sub: 'Movement', icon: 'movement' },
      { id: 'lifeshelf', label: 'Life Shelf Monitor', sub: 'Shelf Life · ห้าง', icon: 'truck' },
      { id: 'documents', label: 'ประวัติเอกสาร', sub: 'Doc Trail', icon: 'history' },
    ]},
    { label: 'Admin', items: [
      { id: 'users', label: 'จัดการผู้ใช้งาน', sub: 'User Management', icon: 'user' },
    ]},
  ];

  const store = useStore();
  const cwh = store.currentWarehouse();
  const user = store.currentUser;

  // Filter nav to only what the current user may access
  const groups = useM1(() => allGroups
    .map(g => ({ ...g, items: g.items.filter(it => store.hasPerm(it.id)) }))
    .filter(g => g.items.length > 0),
  [store.currentUser]);

  const lowCount = useM1(() => {
    const totals = {};
    store.state.stock.forEach(s => { totals[s.sku] = (totals[s.sku] || 0) + s.qty; });
    return store.state.items.filter(i => (totals[i.sku] || 0) < i.min).length;
  }, [store.state]);

  return (
    <aside className="sidebar">
      <div className="brand">
        <div className="brand-mark">W</div>
        <div className="brand-text">
          <div className="brand-name">Warehouse OS</div>
          <div className="brand-sub">v2.6 · {cwh.id}</div>
        </div>
      </div>

      {groups.map(g => (
        <React.Fragment key={g.label}>
          <div className="nav-group-label">{g.label}</div>
          {g.items.map(it => (
            <div key={it.id}
              className={`nav-item ${active === it.id ? 'active' : ''}`}
              onClick={() => onNav(it.id)}>
              <span className="nav-ic"><Ic name={it.icon} size={16}/></span>
              <span style={{ display: 'flex', flexDirection: 'column', lineHeight: 1.1 }}>
                <span>{it.label}</span>
                {it.sub && <span style={{ fontSize: 9.5, color: 'var(--nav-muted)', fontFamily: 'var(--font-mono)', letterSpacing: '0.08em', marginTop: 2 }}>{it.sub.toUpperCase()}</span>}
              </span>
              {it.id === 'stock-report' && lowCount > 0 && <span className="nav-badge">{lowCount}</span>}
            </div>
          ))}
        </React.Fragment>
      ))}

      <div className="sidebar-foot">
        <div className="avatar" style={user ? { background: user.color } : undefined}>{user ? (user.initials || user.name.slice(0,2).toUpperCase()) : 'SK'}</div>
        <div className="user-meta">
          <div className="user-name">{user ? user.name : '—'}</div>
          <div className="user-role">{user ? (user.role === 'admin' ? 'ADMIN · สิทธิ์เต็ม' : `${user.perms.length} เมนู`) : ''}</div>
        </div>
      </div>
    </aside>
  );
}

// ============ Warehouse Switcher (topbar dropdown) ============
function WarehouseSwitcher() {
  const store = useStore();
  const [open, setOpen] = useS1(false);
  const ref = useR1(null);
  const cwh = store.currentWarehouse();

  useE1(() => {
    const close = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', close);
    return () => document.removeEventListener('mousedown', close);
  }, []);

  const whStats = useM1(() => {
    return store.state.warehouses.map(wh => {
      const locs = store.state.locations.filter(l => l.wh === wh.id);
      const locIds = new Set(locs.map(l => l.id));
      const stock = store.state.stock.filter(s => locIds.has(s.locId));
      const totalQty = stock.reduce((a, b) => a + b.qty, 0);
      const skuCount = new Set(stock.map(s => s.sku)).size;
      const capacity = locs.length * 200;
      return { ...wh, locCount: locs.length, totalQty, skuCount, util: Math.min(100, (totalQty / capacity) * 100) };
    });
  }, [store.state]);

  return (
    <div className="wh-switcher" ref={ref}>
      <button className={`wh-trigger ${open ? 'open' : ''}`} onClick={() => setOpen(!open)}>
        <span className="wh-trigger-dot"/>
        <span className="wh-trigger-meta">
          <span className="wh-trigger-code">{cwh.id}</span>
          <span className="wh-trigger-name">{cwh.name} · {cwh.city}</span>
        </span>
        <Ic name="chevron-down" size={12}/>
      </button>
      {open && (
        <div className="wh-menu">
          <div className="wh-menu-label">SWITCH WAREHOUSE · {whStats.length} ACTIVE</div>
          {whStats.map(wh => (
            <div key={wh.id}
              className={`wh-menu-item ${wh.id === store.state.currentWh ? 'active' : ''}`}
              onClick={() => { store.setCurrentWh(wh.id); setOpen(false); }}>
              <div className="wh-menu-mark">{wh.id.split('-')[1]}</div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div className="row" style={{ justifyContent: 'space-between' }}>
                  <span className="wh-menu-name">{wh.name}</span>
                  <span className="badge info" style={{ fontSize: 9.5 }}>{wh.kind}</span>
                </div>
                <div className="wh-menu-sub mono">{wh.id} · {wh.city} · {wh.locCount} bins · {wh.totalQty.toLocaleString()} u</div>
                <div className="wh-menu-bar"><div style={{ width: `${wh.util}%` }}/></div>
              </div>
              {wh.id === store.state.currentWh && <Ic name="check" size={14} style={{ color: 'var(--accent)' }}/>}
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

// ============ Sync status pill ============
// Reflects the REAL cloud-save state from data.js (it used to be a static "SYNCED" label).
const SYNC_PILL = {
  synced:  { cls: '',        label: 'SYNCED',                         tip: 'ข้อมูลล่าสุดถูกบันทึกขึ้นระบบแล้ว' },
  saving:  { cls: 'saving',  label: 'กำลังบันทึก…',                    tip: 'กำลังส่งข้อมูลขึ้นระบบ' },
  error:   { cls: 'error',   label: 'บันทึกไม่สำเร็จ',                 tip: 'รายการล่าสุดยังอยู่ในเครื่องนี้เท่านั้น — อย่าปิดหรือรีเฟรชหน้านี้ ระบบจะลองบันทึกใหม่อัตโนมัติ' },
  offline: { cls: 'offline', label: 'OFFLINE',                        tip: 'โหลดข้อมูลจากระบบไม่สำเร็จ — รายการที่ทำตอนนี้จะไม่ถูกบันทึกขึ้นระบบ ตรวจอินเทอร์เน็ตแล้วรีเฟรชหน้า' },
};
function SyncPill() {
  const [st, setSt] = useS1(() => (window.WMSData.syncStatus ? window.WMSData.syncStatus() : 'synced'));
  useE1(() => {
    const h = (e) => setSt((e.detail && e.detail.status) || 'synced');
    window.addEventListener('wms-sync-status', h);
    return () => window.removeEventListener('wms-sync-status', h);
  }, []);
  const m = SYNC_PILL[st] || SYNC_PILL.synced;
  return <div className={`live-pill ${m.cls}`} title={m.tip}><span className="pulse"/>{m.label}</div>;
}

// ============ TopBar ============
function TopBar({ title, subtitle, actions }) {
  const store = useStore();
  const cwh = store.currentWarehouse();
  const user = store.currentUser;
  const [now, setNow] = useS1(new Date());
  React.useEffect(() => { const t = setInterval(() => setNow(new Date()), 1000); return () => clearInterval(t); }, []);
  const time = now.toLocaleTimeString('en-GB');
  return (
    <header className="topbar">
      <div className="topbar-title">
        <h1>{title}</h1>
        <small>{cwh.id} · {cwh.city} · {time}</small>
      </div>
      <WarehouseSwitcher/>
      <SyncPill/>
      <div className="searchbar">
        <Ic name="search" size={14}/>
        <input placeholder="ค้นหา SKU, ชื่อสินค้า, location, document..." />
        <kbd>⌘K</kbd>
      </div>
      <div className="topbar-actions">
        {actions}
        <button className="icon-btn" data-tip="3 alerts"><Ic name="bell" size={16}/><span className="dot"/></button>
        {user && (
          <div className="topbar-user">
            <div className="avatar" style={{ width: 30, height: 30, background: user.color }}>{user.initials || user.name.slice(0,2).toUpperCase()}</div>
            <div className="topbar-user-meta">
              <span className="topbar-user-name">{user.name}</span>
              <span className="topbar-user-role mono">{user.role === 'admin' ? 'ผู้ดูแลระบบ' : 'ผู้ใช้งาน'}</span>
            </div>
          </div>
        )}
        <button className="icon-btn" data-tip="ออกจากระบบ"
          onClick={() => { if (confirm('ออกจากระบบ?')) store.logout(); }}>
          <Ic name="logout" size={16}/>
        </button>
      </div>
    </header>
  );
}

Object.assign(window, { Sidebar, TopBar, WarehouseSwitcher });
