const NAV=[
  {key:"builder",label:"Home",icon:"house",perm:"Design editor"},
  {key:"designs",label:"Templates",icon:"layers",perm:"Design editor"},
  {key:"studio",label:"Art Tools",icon:"sparkles",perm:"Design editor"},
  {key:"teams",label:"Lockers",icon:"users",perm:"Design editor"},
  {key:"orders",label:"Orders",icon:"clipboard-list",perm:"Orders"},
  {key:"dashboard",label:"Dashboard",icon:"layout-dashboard",perm:"Quoting"},
  {key:"admin",label:"Admin",icon:"settings",perm:"User admin"}
];

// El menu se recorta al rol: una entrada aparece si el rol tiene su permiso, y una
// seccion solo si le queda alguna entrada debajo. Sin esto el Viewer, que es el
// cliente del cliente, veria Admin y Dashboard.
function navFor(role){
  const perms=(window.DATA.perms||{})[role]||[];
  const out=[];
  NAV.forEach(it=>{
    if(it.section){out.push(it);return}
    // Admin aparece si al rol le queda alguna pestaña de admin (Users/Catalog/Settings).
    if(it.key==="admin"){if(((window.DATA.adminTabs||{})[role]||[]).length)out.push(it);return}
    // El contador sale de los pedidos reales: si se libera uno nuevo, sube.
    if(perms.indexOf(it.perm)>=0)out.push(it.key==="orders"?{...it,count:(window.DATA.orders||[]).length}:it);
  });
  return out.filter((it,i)=>!it.section||(out[i+1]&&!out[i+1].section));
}

const SEED=[
  {from:"user",text:"Design a jersey from the Eagles logo — navy and gold, varsity feel."},
  {from:"bruce",text:"Three uniforms using your uploaded mark. Full-button front, tackle-twill numbers.",attachments:[{label:"Uniform A"},{label:"Uniform B"},{label:"Navy",swatch:"#00263e"},{label:"Gold",swatch:"#f1c400"}]}
];

function Shell({view,go,title,breadcrumb,actions,children,chatOpen,setChatOpen,noPad,bare,role,setRole,askBruce}){
  const {isMobile,isTablet}=useBreakpoint();
  const [collapsed,setCollapsed]=React.useState(false);
  React.useEffect(()=>{setCollapsed(isTablet)},[isTablet]);
  const [drawerOpen,setDrawerOpen]=React.useState(false);
  const [userMenu,setUserMenu]=React.useState(false);
  const [menuPos,setMenuPos]=React.useState(null);
  const [msgs,setMsgs]=React.useState(SEED);
  const [convos,setConvos]=React.useState([
    {id:"c1",title:"Eagles varsity jersey",date:"Today"},
    {id:"c2",title:"Fabric for summer league",date:"Aug 21"},
    {id:"c3",title:"Dragons crest lockup",date:"Aug 18"}
  ]);
  const [activeId,setActiveId]=React.useState("c1");
  const ask=t=>{setMsgs(m=>[...m,{from:"user",text:t},{from:"bruce",text:"Poly interlock 145gsm holds sublimation best for a summer league — it keeps edge definition on small type."}]);};
  const newChat=()=>{const id="c"+(convos.length+1);setConvos([{id,title:"New conversation",date:"Today"},...convos]);setActiveId(id);setMsgs([]);};
  const restart=()=>setMsgs([]);
  const pick=id=>{setActiveId(id);setMsgs(id==="c1"?SEED:[{from:"bruce",text:"Picking this conversation back up — what do you need?"}]);};
  const drop=id=>{setConvos(c=>c.filter(x=>x.id!==id));if(id===activeId){setActiveId(null);setMsgs([]);}};

  // En tablet arranca colapsado, pero el boton tiene que poder expandirlo: antes
  // isTablet forzaba true y el toggle cambiaba un estado que nadie leia.
  const navCollapsed=isMobile?false:collapsed;
  React.useEffect(()=>{if(!isMobile)setDrawerOpen(false)},[isMobile]);
  const goAndClose=v=>{go(v);setDrawerOpen(false)};

  const items=navFor(role);
  // Al cambiar de rol la vista abierta puede dejar de existir para ti.
  React.useEffect(()=>{
    const permitidas=items.filter(i=>!i.section).map(i=>i.key);
    if(view!=="profile"&&permitidas.indexOf(view)<0&&permitidas.length)go(permitidas[0]);
  },[role]);

  const menuItem=(txt,on,activo)=><button key={txt} type="button" onClick={on}
    style={{display:"flex",alignItems:"center",gap:8,width:"100%",textAlign:"left",border:"none",cursor:"pointer",
      background:activo?"rgba(255,255,255,.08)":"none",color:activo?"#fff":"var(--text-muted-inverse)",
      font:"inherit",fontSize:12,padding:"8px 10px",borderRadius:6}}>
    {txt}{activo&&<span style={{marginLeft:"auto"}}><Icon name="check" size={13} strokeColor="#fff"/></span>}
  </button>;

  // El nav recorta lo que se salga (overflow:hidden), asi que el menu no puede
  // colgar del pie: se posiciona fijo, midiendo el boton al abrirlo.
  const abrirMenu=e=>{
    if(userMenu){setUserMenu(false);return}
    const r=e.currentTarget.getBoundingClientRect();
    setMenuPos({left:Math.round(r.left),bottom:Math.round(window.innerHeight-r.top+8)});
    setUserMenu(true);
  };
  React.useEffect(()=>{
    if(!userMenu)return;
    const fuera=ev=>{const t=ev.target;if(!t||!t.closest||!t.closest("[data-user-menu]"))setUserMenu(false)};
    const esc=ev=>{if(ev.key==="Escape")setUserMenu(false)};
    document.addEventListener("mousedown",fuera);document.addEventListener("keydown",esc);
    return ()=>{document.removeEventListener("mousedown",fuera);document.removeEventListener("keydown",esc)};
  },[userMenu]);

  const sidebar=<SidebarNav base="../.." items={items} active={view} onSelect={goAndClose}
    collapsed={navCollapsed} onToggleCollapsed={()=>setCollapsed(!collapsed)}
    footer={<button data-user-menu onClick={abrirMenu} aria-expanded={userMenu} aria-haspopup="menu"
      style={{display:"flex",alignItems:"center",gap:10,border:"none",background:"none",
      cursor:"pointer",padding:0,width:navCollapsed?"auto":"100%",textAlign:"left",font:"inherit"}}>
      <Avatar name={window.DATA.me.name} size="sm"/>
      {!navCollapsed&&<div style={{minWidth:0,flex:1}}>
        <div style={{fontSize:12,fontWeight:700,color:"#fff"}}>{window.DATA.me.name}</div>
        <div style={{fontSize:11,color:"var(--text-muted-inverse)"}}>{role} · {window.DATA.me.plan}</div>
      </div>}
    </button>}/>;

  const userPopover=userMenu&&menuPos&&<div data-user-menu role="menu"
    style={{position:"fixed",left:menuPos.left,bottom:menuPos.bottom,zIndex:80,width:200,
      background:"var(--bruce-black)",border:"1px solid rgba(255,255,255,.14)",borderRadius:8,
      boxShadow:"var(--shadow-lg)",padding:6,display:"flex",flexDirection:"column",gap:2}}>
    {menuItem("Profile",()=>{setUserMenu(false);goAndClose("profile")})}
    <span style={{fontSize:10,fontWeight:700,textTransform:"uppercase",letterSpacing:".1em",
      color:"var(--text-subtle-inverse)",padding:"8px 10px 4px"}}>View as</span>
    {Object.keys(window.DATA.roles).map(r=>menuItem(r,()=>{setRole(r);setUserMenu(false)},r===role))}
  </div>;

  return <div style={{display:"flex",height:"100dvh",overflow:"hidden",background:"var(--surface-sunken)"}}>
    {!isMobile&&sidebar}
    {isMobile&&drawerOpen&&<React.Fragment>
      <div onClick={()=>setDrawerOpen(false)} style={{position:"fixed",inset:0,zIndex:50,background:"var(--overlay-scrim)"}}/>
      <div style={{position:"fixed",top:0,bottom:0,left:0,zIndex:51,display:"flex"}}>{sidebar}</div>
    </React.Fragment>}
    <div style={{flex:1,display:"flex",flexDirection:"column",minWidth:0}}>
      {/* En Home la barra sobra: el titulo repite el sidebar y no hay acciones.
          En movil se queda, porque ahi vive el boton que abre el menu. */}
      {(!bare||isMobile)&&<Toolbar
        left={<div style={{display:"flex",alignItems:"center",gap:12,minWidth:0}}>
          {isMobile&&<IconButton label="Open menu" variant="ghost" onClick={()=>setDrawerOpen(true)}><Icon name="menu" size={20}/></IconButton>}
          <div style={{display:"flex",flexDirection:"column",gap:2,minWidth:0}}>
            {title&&!bare&&<span style={{fontSize:isMobile?16:20,fontWeight:700,textTransform:"uppercase",letterSpacing:"-.01em",
              whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"}}>{title}</span>}
            {!isMobile&&breadcrumb&&breadcrumb.length>1&&<Breadcrumb items={breadcrumb}/>}
          </div>
        </div>}
        right={<div style={{display:"flex",alignItems:"center",gap:12}}>{actions}</div>}/>}
      <div style={{flex:1,display:"flex",minHeight:0}}>
        {/* El lanzador de Ask Bruce flota fijo en la esquina: se le reserva su hueco
            para que ningun control acabe debajo. Si el chat esta abierto, no hay lanzador. */}
        <main style={{flex:1,overflow:"auto",padding:noPad?0:(isMobile?"16px":"24px 32px"),
          paddingBottom:(noPad?0:(isMobile?16:24))+(chatOpen?0:76),minWidth:0}}>{children}</main>
        {chatOpen&&<ChatPanel base="../.." mode="floating" width={isMobile?"100%":340} messages={msgs} onSend={ask} onClose={()=>setChatOpen(false)}
          history={convos} activeId={activeId} onNew={newChat} onRestart={restart}
          onSelectConversation={pick} onDeleteConversation={drop}
          style={isMobile?{inset:0,borderRadius:0}:{bottom:0,right:24,borderBottomLeftRadius:0,borderBottomRightRadius:0,borderBottom:"none"}}/>}
      </div>
    </div>
    {userPopover}
    {askBruce&&!chatOpen&&<AskBruceLauncher base="../.." onClick={()=>setChatOpen(true)}/>}
  </div>;
}
window.Shell=Shell;
