// shell.jsx — sidebar, topbar, mobile nav (7-hub IA)

// Hub definitions: each hub may have sub-tabs displayed inside the screen
const NAV = [
  { id: 'dashboard', label: 'Tổng quan',  icon: 'dashboard' },
  { id: 'sources',   label: 'Nguồn',      icon: 'store',     badge: 'brandErr' },
  { id: 'products',  label: 'Sản phẩm',   icon: 'package',   badge: 'pool' },
  { id: 'content',   label: 'Nội dung',   icon: 'sparkle',   badge: 'awaiting' },
  { id: 'schedule',  label: 'Lên lịch',   icon: 'calendar',  badge: 'scheduled' },
  { id: 'analytics', label: 'Hiệu suất',  icon: 'trending' },
  { id: 'settings',  label: 'Cài đặt',    icon: 'settings' },
];

// Sub-tab definitions per hub. Mỗi hub gom đủ cấu hình thuộc giai đoạn của nó:
// — Nguồn: brand health + cấu hình brand + field detection
// — Sản phẩm: pool + chi tiết + bộ lọc + chấm điểm deal
// — Nội dung: caption + visual + tone preset (Tạo bài AI là top-level, vào từ Sản phẩm)
// — Lên lịch: calendar + queue + log + kênh publish
// — Hiệu suất: channels + bài đăng + quảng cáo + inbox + archive
// — Cài đặt: chỉ còn các cấu hình toàn cục (tỉ giá, phases, API-Hub, team)
const HUB_TABS = {
  sources: [
    { value: 'brands',     label: 'Sức khỏe brand',     icon: 'thermometer' },
    { value: 'crawl',      label: 'Lượt thu thập',      icon: 'rotate' },
    { value: 'campaigns',  label: 'Chiến dịch',         icon: 'megaphone' },
    { value: 'watchlist',  label: 'Danh sách theo dõi', icon: 'star' },
    { value: 'brand-cfg',  label: 'Cấu hình brand',     icon: 'store' },
    { value: 'detection',  label: 'Nhận diện trường',   icon: 'scan' },
  ],
  products: [
    { value: 'pool',       label: 'Kho sản phẩm',       icon: 'package' },
    { value: 'detail',     label: 'Chi tiết SP',        icon: 'target' },
    { value: 'presets',    label: 'Bộ lọc lưu sẵn',     icon: 'filter' },
    { value: 'score',      label: 'Điểm phân loại (theo mục đích)', icon: 'zap' },
  ],
  content: [
    { value: 'caption',    label: 'Soạn caption',       icon: 'edit' },
    { value: 'visual',     label: 'Soạn ảnh',           icon: 'paintbrush' },
    { value: 'tone',       label: 'Giọng văn',          icon: 'palette' },
  ],
  schedule: [
    { value: 'calendar',   label: 'Lịch',               icon: 'calendar' },
    { value: 'queue',      label: 'Hàng chờ',           icon: 'clock' },
    { value: 'log',        label: 'Nhật ký đăng',       icon: 'list' },
    { value: 'channel-cfg',label: 'Kênh đăng',          icon: 'send' },
  ],
  analytics: [
    { value: 'channels',   label: 'Kênh',               icon: 'barChart' },
    { value: 'posts',      label: 'Bài đăng',           icon: 'pieChart' },
    { value: 'ads',        label: 'Quảng cáo',          icon: 'megaphone' },
    { value: 'inbox',      label: 'Inbox',              icon: 'mail' },
    { value: 'archive',    label: 'Lưu trữ',            icon: 'archive' },
  ],
  settings: [
    { value: 'general',    label: 'Tỉ giá & AI',        icon: 'settings' },
    { value: 'phases',     label: 'Giai đoạn',          icon: 'layers' },
    { value: 'api',        label: 'API-Hub',            icon: 'key' },
    { value: 'team',       label: 'Nhóm',               icon: 'user' },
  ],
};

function Sidebar({ view, go, collapsed, setCollapsed }) {
  const app = useApp();
  const counts = app.counts;
  return (
    <nav className={'sidebar ' + (collapsed ? 'collapsed' : '')}>
      <div className="sb-brand">
        <div className="sb-logo">Z</div>
        <div style={{ minWidth: 0 }}>
          <div className="sb-brand-name">Zei JP</div>
          <div className="sb-brand-sub">Operator Console</div>
        </div>
      </div>

      <div className="sb-nav">
        {!collapsed && <div className="sb-section-label">Vận hành</div>}
        {NAV.map(n => {
          const badge = n.badge === 'pool' ? counts.pool
                      : n.badge === 'brandErr' ? counts.brandErr
                      : n.badge === 'awaiting' ? counts.awaiting
                      : n.badge === 'scheduled' ? counts.scheduled
                      : 0;
          return (
            <a key={n.id} className={'nav-item ' + (view === n.id ? 'active' : '')}
               onClick={() => go(n.id)} title={n.label}>
              <Icon name={n.icon} size={18} />
              <span>{n.label}</span>
              {badge > 0 && <span className="nav-badge">{badge}</span>}
            </a>
          );
        })}
      </div>

      <div className="sb-foot">
        <a className="nav-item" onClick={() => setCollapsed(!collapsed)} title="Thu gọn">
          <Icon name="panelLeft" size={18} />
          <span>Thu gọn</span>
        </a>
        <div className="sb-user">
          <div className="brand-logo" style={{ background: 'var(--surface-2)', color: 'var(--text)', border: '1px solid var(--border-2)' }}>A</div>
          {!collapsed && (
            <div style={{ minWidth: 0, flex: 1 }}>
              <div className="t-sm strong clip-1">Admin Zei</div>
              <div className="t-2xs dimmer clip-1">admin@zei.com</div>
            </div>
          )}
        </div>
      </div>
    </nav>
  );
}

function Topbar({ title, subtitle, live, onAdd, theme, setTheme, extra }) {
  const [menu, setMenu] = useState(false);
  return (
    <header className="topbar">
      <button className="btn-ghost btn btn-icon btn-sm mobile-only" onClick={onAdd} style={{ display: 'none' }}></button>
      <div style={{ display: 'flex', flexDirection: 'column', minWidth: 0 }}>
        <div className="topbar-title">{title}</div>
        {subtitle && <div className="t-2xs dimmer clip-1" style={{ marginTop: -2 }}>{subtitle}</div>}
      </div>
      {extra}
      <div className="topbar-spacer"></div>

      {live && (
        <div className="live-dot desktop-only" title="Realtime đang kết nối">
          <span className="pulse"></span>Live
        </div>
      )}
      <Button variant="primary" size="sm" icon="plus" onClick={onAdd} className="desktop-only">Thêm sản phẩm</Button>
      <Button variant="ghost" size="sm" icon="bell" aria-label="Thông báo" className="desktop-only" />
      <Button variant="ghost" size="sm" icon={theme === 'dark' ? 'sun' : 'moon'}
              onClick={() => setTheme(theme === 'dark' ? 'light' : 'dark')} aria-label="Đổi theme" />
      <div style={{ position: 'relative' }} className="desktop-only">
        <button className="sb-user" style={{ padding: 4 }} onClick={() => setMenu(m => !m)}>
          <div className="brand-logo" style={{ background: 'var(--surface-2)', color: 'var(--text)', border: '1px solid var(--border-2)' }}>A</div>
        </button>
        {menu && (
          <>
            <div style={{ position: 'fixed', inset: 0, zIndex: 9 }} onClick={() => setMenu(false)}></div>
            <div className="card" style={{ position: 'absolute', right: 0, top: 44, width: 200, zIndex: 10, padding: 6, boxShadow: 'var(--shadow-2)' }}>
              <div style={{ padding: '8px 10px' }}>
                <div className="t-sm strong">Admin Zei</div>
                <div className="t-2xs dimmer">admin@zei.com</div>
              </div>
              <div className="divider" style={{ margin: '4px 0' }}></div>
              <MenuRow icon="globe" label="Ngôn ngữ: Tiếng Việt" />
              <MenuRow icon="user" label="Hồ sơ" />
              <MenuRow icon="lock" label="Đăng xuất" danger />
            </div>
          </>
        )}
      </div>
    </header>
  );
}
function MenuRow({ icon, label, danger }) {
  return (
    <button className="nav-item" style={{ width: '100%', color: danger ? 'var(--red)' : undefined }}>
      <Icon name={icon} size={16} /><span style={{ fontSize: 13 }}>{label}</span>
    </button>
  );
}

// Sub-tab bar shown under the topbar for hubs that have tabs.
// Sticky, scrollable on mobile, accent underline for active.
function HubTabBar({ hub, tab, setTab }) {
  const tabs = HUB_TABS[hub];
  if (!tabs) return null;
  return (
    <div className="hub-tabbar">
      <div className="hub-tabbar-inner">
        {tabs.map(t => (
          <button key={t.value}
                  className={'hub-tab ' + (tab === t.value ? 'active' : '')}
                  onClick={() => setTab(t.value)}>
            {t.icon && <Icon name={t.icon} size={14} />}
            <span>{t.label}</span>
          </button>
        ))}
      </div>
    </div>
  );
}

function MobileNav({ view, go, onAdd }) {
  const app = useApp();
  const items = [
    { id: 'dashboard', label: 'Tổng quan', icon: 'dashboard' },
    { id: 'products', label: 'Sản phẩm', icon: 'package', badge: app.counts.pool },
    { id: 'content',  label: 'Nội dung', icon: 'sparkle', badge: app.counts.awaiting },
    { id: 'schedule', label: 'Lịch', icon: 'calendar', badge: app.counts.scheduled },
    { id: 'more', label: 'Thêm', icon: 'menu' },
  ];
  const moreViews = ['sources','analytics','settings'];
  return (
    <>
      <button className="fab" onClick={onAdd} aria-label="Thêm sản phẩm"><Icon name="plus" size={24} /></button>
      <nav className="tabbar">
        {items.map(it => (
          <a key={it.id} className={view === it.id || (it.id === 'more' && moreViews.includes(view)) ? 'active' : ''}
             onClick={() => go(it.id)}>
            <div style={{ position: 'relative' }}>
              <Icon name={it.icon} size={20} />
              {it.badge > 0 && <span style={{ position: 'absolute', top: -5, right: -8, background: 'var(--accent)', color: 'var(--accent-text)', fontSize: 9, fontWeight: 700, minWidth: 15, height: 15, borderRadius: 99, display: 'grid', placeItems: 'center', padding: '0 3px' }}>{it.badge}</span>}
            </div>
            {it.label}
          </a>
        ))}
      </nav>
    </>
  );
}

Object.assign(window, { Sidebar, Topbar, MobileNav, HubTabBar, NAV, HUB_TABS });
