// Shared components for TVS CRM
const { useState, useEffect, useMemo, useRef } = React;

// =============================================================
// Format helpers
// =============================================================
const formatVND = (n) => {
  if (n == null) return '—';
  if (n >= 1_000_000_000) return (n / 1_000_000_000).toFixed(2).replace(/\.?0+$/, '') + ' tỷ';
  if (n >= 1_000_000) return (n / 1_000_000).toFixed(1).replace(/\.0$/, '') + 'tr';
  if (n >= 1_000) return (n / 1_000).toFixed(0) + 'K';
  return n.toString();
};
const formatVNDFull = (n) => {
  if (n == null) return '—';
  return n.toLocaleString('vi-VN') + 'đ';
};
// Parse 'YYYY-MM-DD' theo giờ địa phương — new Date(str) parse UTC làm lệch ngày ở VN
const parseLocalDate = (iso) => {
  if (iso instanceof Date) return iso;
  const m = String(iso).match(/^(\d{4})-(\d{2})-(\d{2})/);
  if (m) return new Date(+m[1], +m[2] - 1, +m[3]);
  return new Date(iso);
};
const formatDate = (iso) => {
  if (!iso) return '—';
  const d = parseLocalDate(iso);
  return `${String(d.getDate()).padStart(2,'0')}/${String(d.getMonth()+1).padStart(2,'0')}/${d.getFullYear()}`;
};
const formatRelative = (iso) => {
  if (!iso) return '—';
  const today = window.TVS_DATA ? window.TVS_DATA.today : (() => { const d = new Date(); d.setHours(0,0,0,0); return d; })();
  const d = parseLocalDate(iso);
  const diff = Math.round((today - d) / (1000*60*60*24));
  if (diff === 0) return 'Hôm nay';
  if (diff === 1) return 'Hôm qua';
  if (diff > 0) return `${diff} ngày trước`;
  if (diff === -1) return 'Ngày mai';
  return `${Math.abs(diff)} ngày nữa`;
};

window.fmt = { vnd: formatVND, vndFull: formatVNDFull, date: formatDate, rel: formatRelative, parseDate: parseLocalDate };

// Chuẩn hoá chuỗi tìm kiếm: thường hoá + bỏ dấu tiếng Việt ("dang" khớp "Đặng")
const searchNorm = (s) => String(s || '').toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '').replace(/đ/g, 'd');
const phoneDigits = (s) => String(s || '').replace(/\D/g, '');
window.searchNorm = searchNorm;
window.phoneDigits = phoneDigits;

// =============================================================
// Avatar
// =============================================================
function Avatar({ name, size = 'md', tier, src }) {
  const cls = size === 'sm' ? 'avatar-sm' : size === 'lg' ? 'avatar-lg' : size === 'xl' ? 'avatar-xl' : '';
  const tierCls = tier ? tier.toLowerCase() : '';
  const initials = useMemo(() => {
    if (!name) return '??';
    const parts = name.trim().split(/\s+/);
    if (parts.length === 1) return parts[0].slice(0,2).toUpperCase();
    return (parts[0][0] + parts[parts.length-1][0]).toUpperCase();
  }, [name]);
  return (
    <span className={`avatar ${cls} ${tierCls}`}>
      {src ? <img src={src} alt="" style={{width:'100%',height:'100%',borderRadius:'50%',objectFit:'cover'}}/> : initials}
    </span>
  );
}

// =============================================================
// Sidebar (Classic / Compact variants)
// =============================================================
function Sidebar({ role, currentScreen, onNavigate, navItems, onLogout }) {
  return (
    <aside className="sidebar">
      <div className="sidebar-brand">
        <img src="assets/logo-horiz-white.png" alt="The Vitamin Shoppe" />
      </div>
      <div className="sidebar-section">Workspace</div>
      <nav style={{display:'flex',flexDirection:'column',gap:2}}>
        {navItems.map(item => (
          <button
            key={item.id}
            className={`sidebar-item ${currentScreen === item.id ? 'active' : ''}`}
            onClick={() => onNavigate(item.id)}
            title={item.label}>
            <Icon name={item.icon} size={18} />
            <span className="label">{item.label}</span>
            {item.badge ? <span className="badge">{item.badge}</span> : null}
          </button>
        ))}
      </nav>
      <div className="sidebar-footer">
        <Avatar name={role.person} size="sm" />
        <div className="meta">
          <div className="name">{role.person}</div>
          <div className="role-tag">{role.team}</div>
        </div>
        {onLogout && (
          <button className="btn btn-icon btn-sm btn-ghost" onClick={onLogout} title="Đăng xuất"
            style={{color:'rgba(255,255,255,0.5)',background:'transparent'}}>
            <Icon name="close" size={14}/>
          </button>
        )}
      </div>
    </aside>
  );
}

// =============================================================
// Topbar (Classic / Compact: thin top bar with search + quick actions
//          Airy: brand + nav tabs row + filter row )
// =============================================================
function Topbar({ role, currentScreen, navItems, onNavigate, variation, onSearch, breadcrumb, onAddCustomer, onAddPartner, onOpenMobileNav, onLogout, onSwitchUser, onOpenSearch, onOpenAccount }) {
  const screen = navItems.find(n => n.id === currentScreen);
  const [showProfile, setShowProfile] = useState(false);
  const [showNotif, setShowNotif] = useState(false);

  const notifs = []; // Thông báo thật lấy từ backend
  const notifPanel = (
    <div className="topbar-pop" style={{position:'absolute',right:0,top:'calc(100% + 8px)',background:'var(--bg-page)',border:'1px solid var(--border-1)',borderRadius:'var(--radius-md)',boxShadow:'var(--shadow-pop)',width:360,maxWidth:'90vw',zIndex:50,overflow:'hidden'}}>
      <div style={{padding:'12px 16px',borderBottom:'1px solid var(--border-1)',display:'flex',alignItems:'center'}}>
        <span className="strong fg-1">Thông báo</span>
        <Tag variant="danger" style={{marginLeft:8}}>{notifs.filter(n=>n.unread).length} mới</Tag>
        <button className="text-xs" style={{marginLeft:'auto',background:'none',border:'none',color:'var(--vs-light-blue)',cursor:'pointer',fontWeight:700}} onClick={() => window.tvsDemo('Đánh dấu đã đọc')}>Đánh dấu đã đọc</button>
      </div>
      <div style={{maxHeight:380,overflow:'auto'}}>
        {notifs.length === 0 && <div className="text-sm fg-muted" style={{padding:'20px 16px',textAlign:'center'}}>Chưa có thông báo</div>}
        {notifs.map((n, i) => (
          <button key={i} onClick={() => { setShowNotif(false); window.tvsToast('Đang mở: ' + n.title); }}
            style={{display:'flex',gap:10,padding:'12px 16px',width:'100%',border:'none',borderBottom:'1px solid var(--border-1)',background: n.unread ? 'rgba(65,182,230,0.04)' : 'none',cursor:'pointer',textAlign:'left'}}>
            <div style={{width:32,height:32,borderRadius:'50%',background:'var(--bg-soft)',color:n.color,display:'flex',alignItems:'center',justifyContent:'center',flexShrink:0}}>
              <Icon name={n.ic} size={15}/>
            </div>
            <div style={{flex:1,minWidth:0}}>
              <div className="text-sm strong fg-1" style={{lineHeight:1.3}}>{n.title}</div>
              <div className="text-xs fg-muted" style={{marginTop:2}}>{n.meta}</div>
              <div className="text-xs fg-muted" style={{marginTop:3,color:'var(--vs-light-blue)'}}>{n.t}</div>
            </div>
            {n.unread && <span style={{width:8,height:8,borderRadius:'50%',background:'var(--vs-light-blue)',flexShrink:0,marginTop:6}}/>}
          </button>
        ))}
      </div>
      <button style={{display:'block',width:'100%',padding:'12px',border:'none',borderTop:'1px solid var(--border-1)',background:'var(--bg-soft)',cursor:'pointer',color:'var(--vs-dark-blue)',fontWeight:700,fontSize:13}} onClick={() => window.tvsDemo('Trang thông báo đầy đủ')}>
        Xem tất cả thông báo
      </button>
    </div>
  );

  const profileMenu = (
    <div className="topbar-pop" style={{position:'absolute',right:0,top:'calc(100% + 8px)',background:'var(--bg-page)',border:'1px solid var(--border-1)',borderRadius:'var(--radius-md)',boxShadow:'var(--shadow-pop)',minWidth:240,padding:6,zIndex:50}}>
      <div style={{padding:'10px 12px',borderBottom:'1px solid var(--border-1)',marginBottom:6}}>
        <div className="strong fg-1">{role.person}</div>
        <div className="text-xs fg-muted">{role.team}</div>
      </div>
      {[
        {ic:'user',     l:'Hồ sơ cá nhân', go:'profile'},
        {ic:'settings', l:'Cài đặt tài khoản', go:'account'},
        {ic:'fileText', l:'Tài liệu hướng dẫn', demo:'Tài liệu hướng dẫn'},
        {ic:'mail',     l:'Liên hệ IT support', demo:'Liên hệ IT support'},
      ].map(m => (
        <button key={m.l} onClick={() => { setShowProfile(false); if (m.go && onOpenAccount) onOpenAccount(m.go); else if (m.demo) window.tvsDemo(m.demo); }} style={{display:'flex',width:'100%',alignItems:'center',gap:10,padding:'8px 12px',border:'none',background:'none',borderRadius:'var(--radius-sm)',cursor:'pointer',textAlign:'left'}}
          onMouseEnter={(e)=>e.currentTarget.style.background='var(--bg-soft)'}
          onMouseLeave={(e)=>e.currentTarget.style.background='none'}>
          <Icon name={m.ic} size={14} style={{color:'var(--fg-muted)'}}/>
          <span className="text-sm fg-2">{m.l}</span>
        </button>
      ))}
      {onLogout && (
        <>
          <div className="divider" style={{margin:'6px 8px'}}/>
          <button onClick={() => { setShowProfile(false); onLogout(); }}
            style={{display:'flex',width:'100%',alignItems:'center',gap:10,padding:'8px 12px',border:'none',background:'none',borderRadius:'var(--radius-sm)',cursor:'pointer',textAlign:'left'}}
            onMouseEnter={(e)=>e.currentTarget.style.background='rgba(191,9,35,0.06)'}
            onMouseLeave={(e)=>e.currentTarget.style.background='none'}>
            <Icon name="arrowleft" size={14} style={{color:'var(--status-sale)'}}/>
            <span className="text-sm" style={{color:'var(--status-sale)',fontWeight:600}}>Đăng xuất</span>
          </button>
        </>
      )}
    </div>
  );

  if (variation === 'airy') {
    return (
      <header className="topbar topbar-airy">
        <div className="row1">
          <div className="brand-h">
            <img src="assets/logo-horiz.png" alt="The Vitamin Shoppe" />
          </div>
          <div className="topbar-search" style={{flex:'0 1 380px',marginLeft:'auto',cursor:'pointer'}} onClick={() => onOpenSearch && onOpenSearch()}>
            <Icon name="search" size={16} style={{color:'var(--fg-muted)'}}/>
            <input placeholder="Tìm khách hàng, đơn hàng, sản phẩm, đối tác..." readOnly style={{cursor:'pointer'}} onFocus={() => onOpenSearch && onOpenSearch()} />
            <kbd>⌘K</kbd>
          </div>
          <div style={{position:'relative'}}>
            <button className="btn btn-icon btn-ghost" title="Thông báo" style={{position:'relative'}} onClick={() => setShowNotif(s => !s)}>
              <Icon name="bell" size={18}/>
              <span className="notif-dot"/>
            </button>
            {showNotif && <><div style={{position:'fixed',inset:0,zIndex:69}} onClick={() => setShowNotif(false)}/>{notifPanel}</>}
          </div>
          <div style={{position:'relative'}}>
            <button onClick={() => setShowProfile(p => !p)} style={{background:'none',border:'none',cursor:'pointer',padding:0}}>
              <Avatar name={role.person} size="sm" />
            </button>
            {showProfile && <><div style={{position:'fixed',inset:0,zIndex:69}} onClick={() => setShowProfile(false)}/>{profileMenu}</>}
          </div>
        </div>
        <div className="row2">
          {navItems.map(n => (
            <button key={n.id}
              className={`tab ${currentScreen === n.id ? 'active' : ''}`}
              onClick={() => onNavigate(n.id)}>
              <Icon name={n.icon} size={16}/>
              {n.label}
              {n.badge ? <span className="badge">{n.badge}</span> : null}
            </button>
          ))}
        </div>
      </header>
    );
  }
  return (
    <header className="topbar">
      {onOpenMobileNav && (
        <button className="btn btn-icon btn-ghost mobile-only" onClick={onOpenMobileNav} title="Mở menu">
          <Icon name="menu" size={20}/>
        </button>
      )}
      <div className="crumbs">
        <span className="hide-on-mobile">{role.team}</span>
        <span className="sep hide-on-mobile">/</span>
        <span className="current">{breadcrumb || (screen ? screen.label : '')}</span>
      </div>
      <div className="topbar-search hide-on-mobile" style={{cursor:'pointer'}} onClick={() => onOpenSearch && onOpenSearch()}>
        <Icon name="search" size={16} style={{color:'var(--fg-muted)'}}/>
        <input placeholder="Tìm khách hàng, đơn hàng, sản phẩm..." readOnly style={{cursor:'pointer'}} onFocus={() => onOpenSearch && onOpenSearch()} />
        <kbd>⌘K</kbd>
      </div>
      <div className="topbar-actions">
        <div style={{position:'relative'}}>
          <button className="btn btn-icon btn-ghost" title="Thông báo" style={{position:'relative'}} onClick={() => setShowNotif(s => !s)}>
            <Icon name="bell" size={18}/>
            <span className="notif-dot"/>
          </button>
          {showNotif && <><div style={{position:'fixed',inset:0,zIndex:69}} onClick={() => setShowNotif(false)}/>{notifPanel}</>}
        </div>
        {/* Mobile: nút tìm kiếm mở bảng ⌘K — đường vào Đối tác B2B / Tồn kho trên điện thoại */}
        <button className="btn btn-icon btn-ghost mobile-only" title="Tìm kiếm" onClick={() => onOpenSearch && onOpenSearch()}>
          <Icon name="search" size={18}/>
        </button>
        <button className="btn btn-icon btn-ghost hide-on-mobile" title="Tin nhắn" onClick={() => window.tvsDemo('Tin nhắn nội bộ')}>
          <Icon name="chat" size={18}/>
        </button>
        <div className="hide-on-mobile" style={{width:1,height:24,background:'var(--border-1)'}}/>
        <div style={{position:'relative'}}>
          <button onClick={() => setShowProfile(p => !p)} style={{background:'none',border:'none',cursor:'pointer',padding:0}}>
            <Avatar name={role.person} size="sm" />
          </button>
          {showProfile && <><div style={{position:'fixed',inset:0,zIndex:69}} onClick={() => setShowProfile(false)}/>{profileMenu}</>}
        </div>
      </div>
    </header>
  );
}

// =============================================================
// KPI Card
// =============================================================
function KPI({ label, value, unit, delta, deltaDir = 'up', progress, progressLabel, feature, sub, children }) {
  if (!Number.isFinite(progress)) progress = progress == null ? progress : 0; // 0/0 từ dữ liệu trống không được vẽ NaN%
  return (
    <div className={`kpi ${feature ? 'feature' : ''}`}>
      <div className="label">{label}</div>
      <div className="value tnum">
        {value}
        {unit && <span className="unit">{unit}</span>}
      </div>
      {sub && <div style={{fontSize:'var(--t-xs)',color:'var(--fg-muted)',marginTop:4}}>{sub}</div>}
      {delta && (
        <div className={`delta ${deltaDir}`}>
          <Icon name={deltaDir === 'up' ? 'trending' : deltaDir === 'down' ? 'trendingDown' : 'activity'} size={12} stroke={2.2}/>
          {delta}
        </div>
      )}
      {progress != null && (
        <>
          <div className="kpi-progress">
            <div style={{width: Math.min(100, progress) + '%'}}/>
          </div>
          {progressLabel && (
            <div className="kpi-progress-meta">
              <span>{progressLabel.left}</span>
              <span>{progressLabel.right}</span>
            </div>
          )}
        </>
      )}
      {children}
    </div>
  );
}

// =============================================================
// Sparkline (simple SVG)
// =============================================================
function Sparkline({ data, color = 'var(--vs-light-blue)', height = 56, fill }) {
  if (!data || data.length === 0) return null;
  const max = Math.max(...data) || 1;
  const min = Math.min(...data);
  const range = max - min || 1;
  const w = 200;
  const step = w / (data.length - 1 || 1);
  const points = data.map((v, i) => [i*step, height - ((v - min) / range) * (height - 8) - 4]);
  const path = points.map((p,i) => `${i===0?'M':'L'}${p[0]},${p[1]}`).join(' ');
  const area = path + ` L${w},${height} L0,${height} Z`;
  return (
    <svg className="spark" viewBox={`0 0 ${w} ${height}`} preserveAspectRatio="none">
      {fill && <path d={area} fill={fill} opacity="0.18"/>}
      <path d={path} fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" vectorEffect="non-scaling-stroke"/>
      {points.map((p,i) => i === points.length-1 && <circle key={i} cx={p[0]} cy={p[1]} r="3" fill={color}/>)}
    </svg>
  );
}

// =============================================================
// Tag
// =============================================================
function Tag({ children, variant = 'default', dot, style }) {
  return (
    <span className={`tag ${variant !== 'default' ? variant : ''}`} style={style}>
      {dot && <span className="tag-dot" style={{background: typeof dot === 'string' ? dot : 'currentColor'}}/>}
      {children}
    </span>
  );
}

function tierVariant(tier) {
  const t = (tier || '').toLowerCase();
  if (t.includes('kim cương') || t.includes('diamond') || t.includes('platinum') || t.includes('bạch')) return 'platinum'; // 'platinum' = khoá CSS nội bộ, hiển thị là Kim cương
  if (t.includes('gold') || t.includes('vàng')) return 'gold';
  if (t.includes('silver') || t.includes('bạc')) return 'silver';
  if (t.includes('bronze') || t.includes('đồng')) return 'bronze';
  return 'outline';
}

// =============================================================
// Card / CardHeader
// =============================================================
function Card({ children, pad = true, className = '', style }) {
  return <div className={`card ${pad ? 'card-pad' : ''} ${className}`} style={style}>{children}</div>;
}
function CardHeader({ title, sub, actions }) {
  return (
    <div className="card-h">
      <div>
        <h3>{title}</h3>
        {sub && <div className="sub">{sub}</div>}
      </div>
      {actions && <div className="actions">{actions}</div>}
    </div>
  );
}

// =============================================================
// Segmented control
// =============================================================
function Segmented({ value, options, onChange }) {
  return (
    <div className="segmented">
      {options.map(o => (
        <button key={o.value || o}
          className={value === (o.value || o) ? 'active' : ''}
          onClick={() => onChange(o.value || o)}>
          {o.label || o}
        </button>
      ))}
    </div>
  );
}

// =============================================================
// Bar chart (simple, vertical)
// =============================================================
function BarChart({ data, height = 120, color = 'var(--vs-light-blue)', highlight }) {
  if (!data || data.length === 0) return null;
  const max = Math.max(...data) || 1;
  return (
    <div className="bar-row" style={{height}}>
      {data.map((v, i) => (
        <div key={i}
          className={highlight != null && highlight !== i ? 'dim' : ''}
          style={{height: `${(v/max)*100}%`, background: highlight === i ? 'var(--vs-dark-blue)' : color}}
          title={`${v}`}
        />
      ))}
    </div>
  );
}

Object.assign(window, {
  Avatar, Sidebar, Topbar, KPI, Sparkline, Tag, tierVariant,
  Card, CardHeader, Segmented, BarChart,
});

// =============================================================
// Global Search overlay (Cmd+K)
// =============================================================
function GlobalSearch({ onClose, onOpenCustomer, onNavigate, role }) {
  const [q, setQ] = useState('');
  const [active, setActive] = useState(0);
  const D = window.TVS_DATA;

  const results = useMemo(() => {
    if (!q.trim()) return null;
    const s = searchNorm(q.trim());
    const digits = phoneDigits(q);
    const phoneHit = (p) => digits.length >= 3 && phoneDigits(p).includes(digits);
    const customers = D.customers.filter(c =>
      searchNorm(c.name).includes(s) || phoneHit(c.phone) || c.id.toLowerCase().includes(s) ||
      searchNorm(c.email).includes(s)
    ).slice(0, 5);
    // Kết quả đối tác chỉ cho vị trí có quyền vào module B2B — click sẽ điều hướng sang màn B2B
    const partners = (window.tvsCan && tvsCan(role, 'b2b.view')) ? D.partners.filter(p =>
      searchNorm(p.name).includes(s) || searchNorm(p.contact).includes(s) || phoneHit(p.phone) ||
      searchNorm(p.email).includes(s)
    ).slice(0, 4) : [];
    const products = (window.tvsCan && tvsCan(role, 'inventory.view')) ? D.products.filter(p =>
      searchNorm(p.name).includes(s) || p.sku.toLowerCase().includes(s) || searchNorm(p.cat).includes(s)
    ).slice(0, 4) : [];
    return { customers, partners, products };
  }, [q]);

  const pages = [
    {l:'Tổng quan', s:'dashboard', ic:'dashboard'},
    {l:'Khách hàng', s:'customers', ic:'users'},
    // Chỉ gợi ý trang mà vị trí này có QUYỀN vào (ma trận phân quyền trong Cài đặt)
    ...(window.tvsCan && tvsCan(role, 'reports.view')   ? [{l:'Báo cáo', s:'reports', ic:'chart'}] : []),
    ...(window.tvsCan && tvsCan(role, 'settings.view')  ? [{l:'Cài đặt', s:'settings', ic:'settings'}] : []),
    ...(window.tvsCan && tvsCan(role, 'b2b.view')       ? [{l:'Đối tác B2B', s:'b2b', ic:'handshake'}] : []),
    ...(window.tvsCan && tvsCan(role, 'inventory.view') ? [{l:'Tồn kho', s:'inventory', ic:'package'}] : []),
  ].filter(p => !q.trim() || searchNorm(p.l).includes(searchNorm(q)));

  // Danh sách phẳng cho điều hướng bàn phím (↑↓ + Enter)
  const flatItems = useMemo(() => {
    const items = [];
    if (!q.trim()) {
      pages.forEach(p => items.push({ key: 'page-' + p.s, run: () => { onNavigate(p.s); onClose(); } }));
    } else if (results) {
      results.customers.forEach(c => items.push({ key: 'c-' + c.id, run: () => { onOpenCustomer(c); onClose(); } }));
      results.partners.forEach(p => items.push({ key: 'p-' + p.id, run: () => { onNavigate('b2b'); onClose(); } }));
      results.products.forEach(p => items.push({ key: 'sku-' + p.sku, run: () => { onNavigate('inventory'); onClose(); } }));
      pages.forEach(p => items.push({ key: 'page-' + p.s, run: () => { onNavigate(p.s); onClose(); } }));
    }
    return items;
  }, [q, results]);

  useEffect(() => { setActive(0); }, [q]);
  const isActive = (key) => flatItems[active] && flatItems[active].key === key;
  const activeBg = (key) => isActive(key) ? 'var(--bg-soft)' : 'none';
  const onKeyDown = (e) => {
    if (e.key === 'ArrowDown') { e.preventDefault(); setActive(a => Math.min(a + 1, flatItems.length - 1)); }
    if (e.key === 'ArrowUp')   { e.preventDefault(); setActive(a => Math.max(a - 1, 0)); }
    if (e.key === 'Enter' && flatItems[active]) { e.preventDefault(); flatItems[active].run(); }
  };

  return (
    <div style={{position:'fixed',inset:0,background:'rgba(1,33,105,0.40)',zIndex:300,display:'flex',justifyContent:'center',alignItems:'flex-start',paddingTop:'12vh',animation:'fadein 0.16s ease-out'}} onClick={onClose}>
      <div onClick={(e)=>e.stopPropagation()}
        style={{background:'var(--bg-page)',width:'min(620px,94vw)',maxHeight:'70vh',borderRadius:'var(--radius-lg)',boxShadow:'var(--shadow-pop)',overflow:'hidden',display:'flex',flexDirection:'column',animation:'slidein 0.2s var(--ease-out)'}}>
        <div style={{display:'flex',alignItems:'center',gap:12,padding:'16px 20px',borderBottom:'1px solid var(--border-1)'}}>
          <Icon name="search" size={20} style={{color:'var(--fg-muted)'}}/>
          <input autoFocus value={q} onChange={(e)=>setQ(e.target.value)} onKeyDown={onKeyDown}
            placeholder="Tìm khách hàng, đối tác, sản phẩm, trang..."
            style={{flex:1,border:'none',outline:'none',fontSize:16,fontFamily:'inherit',color:'var(--fg-1)',background:'none'}}/>
          <kbd style={{fontFamily:'var(--font-mono)',fontSize:11,background:'var(--bg-soft)',border:'1px solid var(--border-1)',borderRadius:4,padding:'2px 6px',color:'var(--fg-muted)'}}>ESC</kbd>
        </div>
        <div style={{overflow:'auto',flex:1}}>
          {!q.trim() ? (
            <div style={{padding:'14px 20px'}}>
              <div className="text-xs fg-muted mb-2" style={{textTransform:'uppercase',letterSpacing:'0.1em',fontWeight:700}}>Truy cập nhanh</div>
              {pages.map(p => (
                <button key={p.s} onClick={() => { onNavigate(p.s); onClose(); }}
                  style={{display:'flex',width:'100%',alignItems:'center',gap:12,padding:'10px 12px',border:'none',background:activeBg('page-'+p.s),borderRadius:'var(--radius-sm)',cursor:'pointer',textAlign:'left'}}
                  onMouseEnter={(e)=>e.currentTarget.style.background='var(--bg-soft)'}
                  onMouseLeave={(e)=>e.currentTarget.style.background=activeBg('page-'+p.s)}>
                  <Icon name={p.ic} size={16} style={{color:'var(--vs-light-blue)'}}/>
                  <span className="text-sm fg-1">{p.l}</span>
                </button>
              ))}
            </div>
          ) : (
            <div style={{padding:'8px 0'}}>
              {results.customers.length > 0 && (
                <SearchGroup label="Khách hàng">
                  {results.customers.map(c => (
                    <SearchItem key={c.id} active={isActive('c-'+c.id)} onClick={() => { onOpenCustomer(c); onClose(); }}>
                      <Avatar name={c.name} size="sm" tier={tierVariant(c.tier)}/>
                      <div style={{flex:1,minWidth:0}}>
                        <div className="text-sm strong fg-1">{c.name}</div>
                        <div className="text-xs fg-muted tnum">{c.phone} · {c.id} · {c.city}</div>
                      </div>
                      <Tag variant={tierVariant(c.tier)}>{c.tier}</Tag>
                    </SearchItem>
                  ))}
                </SearchGroup>
              )}
              {results.partners.length > 0 && (
                <SearchGroup label="Đối tác B2B">
                  {results.partners.map(p => (
                    <SearchItem key={p.id} active={isActive('p-'+p.id)} onClick={() => { onNavigate('b2b'); onClose(); }}>
                      <Avatar name={p.name} size="sm" tier={tierVariant(p.tier)}/>
                      <div style={{flex:1,minWidth:0}}>
                        <div className="text-sm strong fg-1">{p.name}</div>
                        <div className="text-xs fg-muted">{p.type} · {p.contact}</div>
                      </div>
                    </SearchItem>
                  ))}
                </SearchGroup>
              )}
              {results.products.length > 0 && (
                <SearchGroup label="Sản phẩm">
                  {results.products.map(p => (
                    <SearchItem key={p.sku} active={isActive('sku-'+p.sku)} onClick={() => { onNavigate('inventory'); onClose(); }}>
                      <div style={{width:28,height:28,borderRadius:4,background:'var(--bg-soft)',color:'var(--vs-light-blue)',display:'flex',alignItems:'center',justifyContent:'center',flexShrink:0}}><Icon name="pill" size={15}/></div>
                      <div style={{flex:1,minWidth:0}}>
                        <div className="text-sm strong fg-1">{p.name}</div>
                        <div className="text-xs fg-muted">{p.sku} · {p.cat}</div>
                      </div>
                    </SearchItem>
                  ))}
                </SearchGroup>
              )}
              {pages.length > 0 && (
                <SearchGroup label="Trang">
                  {pages.map(p => (
                    <SearchItem key={p.s} active={isActive('page-'+p.s)} onClick={() => { onNavigate(p.s); onClose(); }}>
                      <div style={{width:28,height:28,borderRadius:4,background:'var(--bg-soft)',color:'var(--vs-light-blue)',display:'flex',alignItems:'center',justifyContent:'center',flexShrink:0}}><Icon name={p.ic} size={15}/></div>
                      <span className="text-sm fg-1">{p.l}</span>
                    </SearchItem>
                  ))}
                </SearchGroup>
              )}
              {results.customers.length === 0 && results.partners.length === 0 && results.products.length === 0 && pages.length === 0 && (
                <div style={{padding:'32px 20px',textAlign:'center',color:'var(--fg-muted)'}}>
                  <div className="text-sm">Không tìm thấy kết quả cho "<b>{q}</b>"</div>
                </div>
              )}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
function SearchGroup({ label, children }) {
  return (
    <div style={{marginBottom:4}}>
      <div className="text-xs fg-muted" style={{padding:'8px 20px 4px',textTransform:'uppercase',letterSpacing:'0.1em',fontWeight:700}}>{label}</div>
      {children}
    </div>
  );
}
function SearchItem({ children, onClick, active }) {
  const bg = active ? 'var(--bg-soft)' : 'none';
  return (
    <button onClick={onClick}
      style={{display:'flex',width:'100%',alignItems:'center',gap:12,padding:'8px 20px',border:'none',background:bg,cursor:'pointer',textAlign:'left'}}
      onMouseEnter={(e)=>e.currentTarget.style.background='var(--bg-soft)'}
      onMouseLeave={(e)=>e.currentTarget.style.background=bg}>
      {children}
    </button>
  );
}
window.GlobalSearch = GlobalSearch;
