/* ============ TOAST SYSTEM ============ */
let _toastId = 0;
const _toastListeners = new Set();
function toast(opts){
  const t = typeof opts==='string' ? {title:opts} : opts;
  const item = {id:++_toastId, kind:'ok', ...t};
  _toastListeners.forEach(fn=>fn(item));
}
function ToastHost(){
  const [items, setItems] = React.useState([]);
  React.useEffect(()=>{
    const fn = item => {
      setItems(p=>[...p, item]);
      setTimeout(()=> setItems(p=>p.filter(x=>x.id!==item.id)), item.duration||3400);
    };
    _toastListeners.add(fn);
    return ()=> _toastListeners.delete(fn);
  },[]);
  const ic = {ok:'checkCircle', err:'alert', info:'info'};
  const tint = {ok:['#16A34A','#E8F7EE'], err:['#DC2626','#FDE7E7'], info:['#D70059','#FDEAF2']};
  return (
    <div className="toast-wrap">
      {items.map(t=>(
        <div key={t.id} className={'toast '+(t.kind==='err'?'err':t.kind==='info'?'info':'')}>
          <div className="ti" style={{background:tint[t.kind][1], color:tint[t.kind][0]}}>
            <Icon name={ic[t.kind]} size={19}/>
          </div>
          <div>
            <div className="tt">{t.title}</div>
            {t.desc && <div className="td">{t.desc}</div>}
          </div>
        </div>
      ))}
    </div>
  );
}

/* ============ MODAL ============ */
function Modal({title, onClose, children, footer, width=560}){
  React.useEffect(()=>{
    const fn = e => { if(e.key==='Escape') onClose(); };
    window.addEventListener('keydown', fn);
    return ()=> window.removeEventListener('keydown', fn);
  },[onClose]);
  return (
    <div className="overlay" onMouseDown={e=>{ if(e.target===e.currentTarget) onClose(); }}>
      <div className="modal" style={{width:'min('+width+'px, calc(100vw - 32px))'}}>
        <div className="modal-head">
          <h3>{title}</h3>
          <button className="icon-btn" style={{width:38,height:38,boxShadow:'none'}} onClick={onClose}><Icon name="x" size={19}/></button>
        </div>
        <div className="modal-body">{children}</div>
        {footer && <div className="modal-foot">{footer}</div>}
      </div>
    </div>
  );
}

/* ============ FORM FIELDS ============ */
function Field({label, hint, children, style}){
  return (<div className="field" style={style}>
    {label && <label>{label}</label>}
    {children}
    {hint && <div className="hint">{hint}</div>}
  </div>);
}
function Segmented({value, onChange, options}){
  return (<div className="seg">
    {options.map(o=>(
      <button key={o.value} className={value===o.value?'on':''} onClick={()=>onChange(o.value)}>{o.label}</button>
    ))}
  </div>);
}

/* ============ NAV ITEMS ============ */
const NAV = [
  {id:'dashboard',  label:'Dashboard',        icon:'dashboard'},
  {id:'items',      label:'Items',             icon:'items'},
  {id:'batches',    label:'Batches',           icon:'batches'},
  {section:'Operations'},
  {id:'stock-in',   label:'Stock In',          icon:'stockIn'},
  {id:'stock-out',  label:'Stock Out',         icon:'stockOut'},
  {id:'scan',       label:'Scan Barcode',      icon:'scan'},
  {id:'movements',  label:'Movement History',  icon:'clock'},
  {section:'Insights'},
  {id:'low-stock',  label:'Low Stock',         icon:'alert', alert:true},
  {id:'reports',    label:'Reports',           icon:'reports'},
];

/* ── items shown in the mobile bottom bar (6 tabs) ── */
const MOBILE_NAV = [
  {id:'dashboard', label:'Home',     icon:'dashboard'},
  {id:'stock-in',  label:'Stock In', icon:'stockIn'},
  {id:'stock-out', label:'Stock Out',icon:'stockOut'},
  {id:'scan',      label:'Scan',     icon:'scan'},
  {id:'reports',   label:'Reports',  icon:'reports'},
  {id:'items',     label:'Items',    icon:'items'},
];

/* ============ SIDEBAR (desktop / tablet) ============ */
function Sidebar({route, setRoute, products, lowCount, isManager, user, onLogout}){
  return (
    <aside className="sidebar">
      <div className="sb-logo">
        <img src="assets/helbawi-logo-mark.png" alt="Helbawi"/>
      </div>
      <nav className="sb-nav">
        {NAV.map((n,i)=> {
          if (n.section) return <div key={i} className="nav-section">{n.section}</div>;
          if (n.id === 'reports' && !isManager) return null; // hide Reports for employees
          return (
            <button key={n.id}
              className={'nav-item'+(route===n.id?' active':'')+(n.alert&&lowCount?' alert':'')}
              onClick={()=>setRoute(n.id)}
              title={n.label}>
              <Icon name={n.icon} size={20}/>
              <span className="nav-label">{n.label}</span>
              {n.alert && lowCount>0 && <span className="nav-badge">{lowCount}</span>}
            </button>
          );
        })}
      </nav>
      <div className="sb-foot">
        <div className="sb-card">
          <div>
            <div className="lbl">Total Items</div>
            <div className="big num">{products.length}</div>
          </div>
          <div className="ic"><Icon name="box" size={22}/></div>
        </div>
        {user && (
          <div style={{marginTop:10,display:'flex',alignItems:'center',justifyContent:'space-between',
            background:'rgba(255,255,255,.13)',borderRadius:12,padding:'8px 12px',border:'1px solid rgba(255,255,255,.16)'}}>
            <div>
              <div style={{fontSize:12,fontWeight:700,color:'#fff'}}>{user.displayName}</div>
              <div style={{fontSize:11,color:'rgba(255,255,255,.6)'}}>{user.username}</div>
            </div>
            <button onClick={onLogout} title="Sign out"
              style={{background:'rgba(255,255,255,.15)',border:'none',borderRadius:8,padding:'6px 8px',
                color:'#fff',cursor:'pointer',fontSize:11,fontWeight:700}}>
              Sign out
            </button>
          </div>
        )}
      </div>
      <div className="sb-copy">© 2026 Helbawi Inventory System<br/>Main Warehouse · v1.2.0</div>
    </aside>
  );
}

/* ============ MOBILE BOTTOM NAV ============ */
function MobileNav({route, setRoute, lowCount, isManager}){
  const visibleNav = MOBILE_NAV.filter(n => n.id !== 'reports' || isManager);
  return (
    <nav className="mobile-nav">
      {visibleNav.map(n=>(
        <button key={n.id}
          className={route===n.id ? 'active' : ''}
          onClick={()=>setRoute(n.id)}>
          <Icon name={n.icon} size={22}/>
          <span>{n.label}</span>
          {n.alert && lowCount>0 && (
            <span style={{
              position:'absolute',top:6,right:'50%',transform:'translateX(14px)',
              background:'#fff',color:'var(--magenta)',fontSize:10,fontWeight:800,
              minWidth:16,height:16,borderRadius:8,display:'flex',alignItems:'center',
              justifyContent:'center',padding:'0 4px',
            }}>{lowCount}</span>
          )}
        </button>
      ))}
    </nav>
  );
}

/* ============ TOPBAR ============ */
function Topbar({title, welcome, search, setSearch, notifCount, onBell, onAdd, onMenu, user, onLogout}){
  return (
    <header className="topbar">
      {onMenu && (
        <button className="icon-btn hamburger-btn" onClick={onMenu} aria-label="Menu">
          <Icon name="menu" size={22}/>
        </button>
      )}
      <div className="title-wrap">
        <h1>{title}</h1>
        <div className="welcome">{welcome}</div>
      </div>
      <div className="search">
        <Icon name="search" size={18}/>
        <input placeholder="Search…" value={search} onChange={e=>setSearch(e.target.value)}/>
      </div>
      {onAdd && (
        <button className="btn btn-primary topbar-add" onClick={onAdd}>
          <Icon name="plus" size={18}/>
          <span className="btn-label">Add Product</span>
        </button>
      )}
      <button className="icon-btn" onClick={onBell} title="Alerts" style={{flexShrink:0}}>
        <Icon name="bell" size={21}/>
        {notifCount>0 && <span className="dot num">{notifCount}</span>}
      </button>
      {/* logout button — visible on mobile only */}
      {onLogout && (
        <button className="icon-btn topbar-logout" onClick={onLogout} title="Sign out" style={{flexShrink:0}}>
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" y1="12" x2="9" y2="12"/>
          </svg>
        </button>
      )}
    </header>
  );
}

Object.assign(window,{toast,ToastHost,Modal,Field,Segmented,Sidebar,MobileNav,Topbar,NAV});
