// Shell da plataforma Xcope: chrome comum (rail, seletor de empresa e de produto,
// Spotlight ⌘K, Copiloto, Ajuda, tema). Lê o manifesto do produto em window.XCOPE_PRODUCT
// e expõe window.XcopeShell (mount + helpers) e window.WFA para os ecrãs do produto.

const B = window.XCOPEDesignSystem_bf80f1;
const { UIButton, UIInput, UIToggle, UICard, UIPill, UINavItem, UIStat, UITabs, UITable, UIAvatar, UIAvatarGroup, UISelect, UIBanner, UIModal, UIDrawer } = B;
const I = ({d,size=18,c="currentColor"})=><svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">{(Array.isArray(d)?d:[d]).map((p,i)=><path key={i} d={p}/>)}</svg>;
const P = {
  home:["M3 9.5 12 3l9 6.5V21H3z"], mail:["M3 5h18v14H3z","M3 6l9 7 9-7"], chat:["M21 15a2 2 0 0 1-2 2H8l-5 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"],
  bell:["M18 8a6 6 0 1 0-12 0c0 7-3 9-3 9h18s-3-2-3-9","M13.7 21a2 2 0 0 1-3.4 0"], badge:["M4 4h16v16H4z","M9 9h6M9 13h6"], folder:["M3 7h6l2 2h10v10H3z"],
  share:["M4 12v8h16v-8","M12 3v13M8 7l4-4 4 4"], career:["M12 2 3 7l9 5 9-5-9-5z","M3 12l9 5 9-5"], task:["M9 11l3 3 8-8","M20 12v7H4V5h11"],
  ticket:["M3 8a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v3a2 2 0 0 0 0 4v3a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-3a2 2 0 0 0 0-4z"], survey:["M9 5H5v14h14V5h-4","M9 3h6v4H9z","M9 12l2 2 4-4"],
  away:["M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18z","M12 8v5l3 2"], cal:["M3 4h18v18H3zM3 10h18M8 2v4M16 2v4"], clock:["M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18z","M12 7v5l3 2"],
  grid:["M3 3h8v8H3zM13 3h8v8h-8zM13 13h8v8h-8zM3 13h8v8H3z"], car:["M5 16l1.5-5h11L19 16","M3 16h18v3H3z","M6 19v2M18 19v2"], pulse:["M3 12h4l3 8 4-16 3 8h4"],
  imp:["M12 3v12M8 11l4 4 4-4","M4 21h16"], exp:["M12 15V3M8 7l4-4 4 4","M4 21h16"], report:["M4 4h16v16H4z","M8 16v-4M12 16V8M16 16v-6"],
  people:["M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2","M9 11a4 4 0 1 0 0-8 4 4 0 0 0 0 8"], org:["M9 3h6v4H9zM3 17h6v4H3zM15 17h6v4h-6z","M12 7v4M6 17v-2h12v2"],
  shield:["M12 3l8 3v6c0 5-3.5 8-8 9-4.5-1-8-4-8-9V6z"], users:["M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2","M9 11a4 4 0 1 0 0-8 4 4 0 0 0 0 8","M23 21v-2a4 4 0 0 0-3-3.87"],
  building:["M4 21V4h10v17M14 9h6v12M8 8h2M8 12h2M8 16h2"], team:["M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2","M9 11a4 4 0 1 0 0-8 4 4 0 0 0 0 8","M22 21v-2a4 4 0 0 0-3-3.87"],
  doc:["M6 3h9l4 4v14H6z","M15 3v4h4"], cog:["M12 9a3 3 0 1 0 0 6 3 3 0 0 0 0-6z","M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"],
  life:["M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18z","M12 8a4 4 0 1 0 0 8 4 4 0 0 0 0-8z"], send:["M22 2 11 13M22 2l-7 20-4-9-9-4z"], search:["M11 4a7 7 0 1 0 0 14 7 7 0 0 0 0-14z","M20 20l-3.5-3.5"], plus:["M12 5v14M5 12h14"], tag:["M12 2H2v10l9.3 9.3a1.7 1.7 0 0 0 2.4 0l7.6-7.6a1.7 1.7 0 0 0 0-2.4z","M7 7h.01"], trash:["M3 6h18","M8 6V4h8v2","M6 6l1 14a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2l1-14","M10 11v6M14 11v6"], pin:["M12 17v5","M9 4h6l1 6 2.5 2.5H5.5L8 10z"], pencil:["M17 3l4 4L8 20l-5 1 1-5z"], smile:["M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18z","M8 14s1.5 2 4 2 4-2 4-2","M9 9h.01M15 9h.01"], x:["M18 6 6 18M6 6l12 12"], lock:["M5 11h14v10H5z","M8 11V7a4 4 0 0 1 8 0v4"], hash:["M4 9h16M4 15h16M10 3 8 21M16 3l-2 18"], info:["M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18z","M12 11v5","M12 8h.01"], clock:["M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18z","M12 7v5l3 2"], bmark:["M6 3h12v18l-6-4-6 4z"], fwd:["M4 17v-2a6 6 0 0 1 6-6h9","M15 4l5 5-5 5"], head:["M4 18v-5a8 8 0 0 1 16 0v5","M2 16h4v5H4a2 2 0 0 1-2-2z","M22 16h-4v5h2a2 2 0 0 0 2-2z"], chev:["M9 6l6 6-6 6"], globe:["M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18z","M3 12h18","M12 3a15 15 0 0 1 0 18","M12 3a15 15 0 0 0 0 18"], cam:["M2 7h13v10H2z","M15 10l7-3v10l-7-3"], mon:["M3 4h18v12H3z","M8 20h8","M12 16v4"], mic:["M12 2a3 3 0 0 1 3 3v6a3 3 0 0 1-6 0V5a3 3 0 0 1 3-3z","M5 11a7 7 0 0 0 14 0","M12 18v4"],
};

const PROD=window.XCOPE_PRODUCT;
const {NAV,FIT,S,PEOPLE,GROUP,SPOT_ACTIONS,USER,PRODUCTS,BRAND}=PROD;
const CP_SUG=PROD.COPILOT.sug,CP_DEF=PROD.COPILOT.def;

const LABELS={};NAV.forEach(([,,items])=>items.forEach(([id,l,,kids])=>{if(kids)kids.forEach(([k,kl])=>LABELS[k]=kl);else LABELS[id]=l;}));Object.assign(LABELS,PROD.labelExtras||{});
const SECTION_OF={};NAV.forEach(([g,,items])=>items.forEach(([id,l,,kids])=>{if(kids)kids.forEach(([k])=>SECTION_OF[k]=l);else SECTION_OF[id]=g;}));

const AV=(n,s="sm",st)=><UIAvatar name={n} size={s} status={st}/>;

const CTX=React.createContext({});
const useCtx=()=>React.useContext(CTX);
function ScopeChip(){const {scope,setScope,company}=useCtx();const [open,setOpen]=React.useState(false);
  const cs=GROUP.companies.filter(c=>!c.noAccess);const all=scope.length===cs.length;
  const label=all?"Todas as empresas · "+cs.length:scope.length===1?(cs.find(c=>c.id===scope[0])||{}).name:scope.length+" empresas";
  const tog=id=>setScope(s=>s.includes(id)?(s.length>1?s.filter(x=>x!==id):s):[...s,id]);
  const cn=(company&&company.name)||"";const coName=cn.charAt(cn.length-1)==="."?cn.slice(0,-1):cn;
  return <div style={{position:"relative"}}>
    <div className="row" onClick={()=>setOpen(v=>!v)} title="Âmbito dos dados" style={{gap:8,height:36,padding:"0 12px",border:"1px solid var(--ui-border)",borderRadius:"var(--ui-r-pill)",background:"var(--ui-surface)",cursor:"pointer",fontSize:"var(--ui-fs-sm)",fontWeight:600}}>
      <I d={P.building} size={15} c="var(--ui-text-3)"/><span>{label}</span><I d={["m6 9 6 6 6-6"]} size={13} c="var(--ui-text-3)"/></div>
    {open&&<React.Fragment><div onClick={()=>setOpen(false)} style={{position:"fixed",inset:0,zIndex:40}}></div>
    <div style={{position:"absolute",top:"calc(100% + 6px)",right:0,minWidth:280,background:"var(--ui-surface)",border:"1px solid var(--ui-border)",borderRadius:"var(--ui-r-md)",boxShadow:"var(--ui-elev-2)",padding:8,zIndex:41}}>
      <div className="muted" style={{fontSize:"var(--ui-fs-xs)",fontWeight:600,letterSpacing:"0.06em",textTransform:"uppercase",padding:"8px 12px"}}>Mostrar dados de</div>
      <div className="row" onClick={()=>setScope(cs.map(c=>c.id))} style={{gap:10,padding:"9px 10px",borderRadius:"var(--ui-r-sm)",cursor:"pointer",fontSize:"var(--ui-fs-sm)",fontWeight:600,background:all?"var(--ui-accent-weak)":"transparent"}}><I d={P.grid} size={15}/><span style={{flex:1}}>Todas as empresas</span>{all&&<I d={["M20 6 9 17l-5-5"]} size={15} c="var(--ui-accent)"/>}</div>
      <div style={{height:1,background:"var(--ui-divider)",margin:"6px 4px"}}></div>
      {cs.map(c=><div key={c.id} onClick={()=>tog(c.id)} className="row" style={{gap:10,padding:"9px 10px",borderRadius:"var(--ui-r-sm)",cursor:"pointer",fontSize:"var(--ui-fs-sm)"}}>
        <span style={{width:16,height:16,borderRadius:5,border:"1.5px solid "+(scope.includes(c.id)?"var(--ui-accent)":"var(--ui-border-2)"),background:scope.includes(c.id)?"var(--ui-accent)":"transparent",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0}}>{scope.includes(c.id)&&<I d={["M20 6 9 17l-5-5"]} size={11} c="var(--ui-on-accent)"/>}</span>
        <span style={{width:6,height:22,borderRadius:3,background:c.color,flexShrink:0}}></span>
        <span style={{flex:1,fontWeight:500}}>{c.name}</span><span className="muted" style={{fontSize:"var(--ui-fs-xs)"}}>{c.people}</span></div>)}
      <div className="muted" style={{fontSize:"var(--ui-fs-xs)",padding:"8px 10px 4px",lineHeight:1.45}}>Fluxos operacionais (ponto, pedidos) usam sempre {coName}.</div>
    </div></React.Fragment>}
  </div>;}
function Head({title,desc,actions,scoped}){return <div className="head"><div><div className="h-t">{title}</div>{desc&&<div className="h-d">{desc}</div>}</div><div className="spring"/>{scoped&&<ScopeChip/>}{actions}</div>;}
function Stub({icon,title,desc}){return <div className="stub"><div className="stub-ic"><I d={P[icon]||P.grid} size={28}/></div><div style={{fontSize:"var(--ui-fs-h3)",fontWeight:600,color:"var(--ui-text)"}}>{title}</div><div style={{maxWidth:420,fontSize:"var(--ui-fs-body)"}}>{desc}</div></div>;}


const CP_ICON=["M12 4.2l2.2 5.6 5.6 2.2-5.6 2.2-2.2 5.6-2.2-5.6L4.2 12l5.6-2.2z"];
function Copilot({route,label,open,setOpen}){
  const [msgs,setMsgs]=React.useState([]);const [q,setQ]=React.useState("");
  const [ctx,setCtx]=React.useState(true);
  const listRef=React.useRef(null);
  React.useEffect(()=>{const el=listRef.current;if(el)el.scrollTop=el.scrollHeight;},[msgs]);
  const sug=(CP_SUG[route]||[]).slice(0,2);
  const send=text=>{const v=(text||q).trim();if(!v)return;
    setMsgs(m=>[...m,{me:true,t:v},{me:false,t:ctx?"Com o contexto de "+label+", respondia aqui ligado aos dados reais.":"Respondia aqui, sem contexto de nenhum ecrã em particular."}]);setQ("");};
  if(!open)return <React.Fragment>
    <div className="cp-rail" onClick={()=>setOpen(true)} title="Abrir copiloto (⌘J)">
      <span className="cp-orb"><I d={CP_ICON} size={17}/></span>
    </div>
    <button className="cpfab" onClick={()=>setOpen(true)} aria-label="Abrir copiloto"><I d={CP_ICON} size={22}/></button>
  </React.Fragment>;
  return <React.Fragment>
  <div className="cpscrim" onClick={()=>setOpen(false)}/>
  <aside className="cp">
    <div className="row" style={{padding:"0 20px",height:64,flexShrink:0,gap:12}}>
      <span className="cp-orb"><I d={CP_ICON} size={16}/></span>
      <span style={{fontWeight:600,flex:1}}>Copiloto</span>
      {msgs.length>0&&<span className="ico-btn" title="Nova conversa" onClick={()=>setMsgs([])}><I d={["M12 5v14","M5 12h14"]} size={16}/></span>}
      <span className="ico-btn" title="Fechar (⌘J)" onClick={()=>setOpen(false)}><I d={["m9 18 6-6-6-6"]} size={16}/></span>
    </div>

    <div ref={listRef} style={{flex:1,minHeight:0,overflow:"auto",padding:"4px 20px 20px",display:"flex",flexDirection:"column",gap:14}}>
      {!msgs.length&&<React.Fragment>
        <div style={{padding:"4px 0 4px"}}>
          <div style={{fontSize:"var(--ui-fs-h3)",fontWeight:600,letterSpacing:"var(--ui-ls-h3)",lineHeight:1.3}}>Em que posso ajudar?</div>
          <div className="muted" style={{fontSize:"var(--ui-fs-sm)",marginTop:6,lineHeight:1.5}}>Pergunta o que quiseres, sobre qualquer assunto. Se quiseres, junto o contexto do que tens aberto.</div>
        </div>
        <div style={{display:"flex",flexWrap:"wrap",gap:8}}>
          {[...sug,"Escreve um email","Resume um documento"].slice(0,4).map(s=>
            <span key={s} onClick={()=>send(s)} className="cp-sug">{s}</span>)}
        </div>
      </React.Fragment>}
      {msgs.map((m,i)=><div key={i} className={m.me?"cp-me":"cp-ai"}>{m.t}</div>)}
    </div>

    <div style={{padding:"0 16px 16px",flexShrink:0}}>
      <div className="cp-box">
        {ctx&&<div className="row" style={{gap:8,marginBottom:10}}>
          <span className="cp-ctx">{label}<span onClick={()=>setCtx(false)} title="Remover contexto" style={{cursor:"pointer",display:"inline-flex",opacity:0.6}}><I d={["M18 6 6 18","m6 6 12 12"]} size={11}/></span></span>
        </div>}
        <textarea value={q} onChange={e=>setQ(e.target.value)} onKeyDown={e=>{if(e.key==="Enter"&&!e.shiftKey){e.preventDefault();send();}}}
          rows={2} placeholder="Escreve uma pergunta…" className="cp-ta"/>
        <div className="row" style={{gap:8,marginTop:6}}>
          {!ctx&&<span className="cp-add" onClick={()=>setCtx(true)} title="Juntar o contexto desta página"><I d={["M12 5v14","M5 12h14"]} size={13}/>contexto</span>}
          <div className="spring"/>
          <span className="cp-send" onClick={()=>send()} title="Enviar"><I d={["m22 2-7 20-4-9-9-4z"]} size={15}/></span>
        </div>
      </div>
    </div>
  </aside>
  </React.Fragment>;
}

function RailTips({active}){
  const [tip,setTip]=React.useState(null);
  React.useEffect(()=>{
    if(!active){setTip(null);return;}
    const enter=e=>{const el=e.target.closest?e.target.closest("[data-tip]"):null;
      if(!el||!el.closest(".rail"))return;
      const r=el.getBoundingClientRect();
      setTip({t:el.getAttribute("data-tip"),x:r.right+12,y:r.top+r.height/2});};
    const leave=e=>{const el=e.target.closest?e.target.closest("[data-tip]"):null;if(el)setTip(null);};
    document.addEventListener("mouseover",enter);
    document.addEventListener("mouseout",leave);
    window.addEventListener("scroll",()=>setTip(null),true);
    return ()=>{document.removeEventListener("mouseover",enter);document.removeEventListener("mouseout",leave);};
  },[active]);
  if(!active||!tip)return null;
  return <div className="tip on" style={{left:tip.x,top:tip.y,transform:"translateY(-50%)"}}>{tip.t}</div>;
}

function useWidth(ref){
  const [w,setW]=React.useState(0);
  React.useLayoutEffect(()=>{
    let raf=0,last=0;
    const read=()=>{const el=ref.current;if(!el)return;const n=el.getBoundingClientRect().width;
      if(n&&Math.abs(n-last)>0.5){last=n;setW(n);}};
    read();
    let ro;if(window.ResizeObserver){try{ro=new ResizeObserver(read);ro.observe(ref.current);}catch(e){}}
    window.addEventListener("resize",read);
    const tick=()=>{read();raf=window.setTimeout(tick,250);};
    raf=window.setTimeout(tick,250);
    return ()=>{if(ro)ro.disconnect();window.removeEventListener("resize",read);clearTimeout(raf);};
  },[ref]);
  return w;
}

const isMac=typeof navigator!=="undefined"&&/Mac|iPhone|iPad/.test(navigator.platform||navigator.userAgent);
function Spotlight({onClose,go}){
  const [q,setQ]=React.useState("");const [i,setI]=React.useState(0);const ref=React.useRef(null);
  const nav=NAV.flatMap(([,,items])=>items.flatMap(([id,l,ic,kids])=>kids?kids.map(([k,kl])=>({kind:"Ecrã",label:kl,id:k,ic})):[{kind:"Ecrã",label:l,id,ic}]));
  const acts=SPOT_ACTIONS.map(([l,id,ic])=>({kind:"Ação",label:l,id,ic}));
  const people=["Ana Reis","Bruno Costa","Marta Lopes","Tomás Jervell","Tomás Machado"].map(n=>({kind:"Pessoa",label:n,id:"admin-employees",person:true}));
  const all=[...acts,...nav,...people];
  const res=(q?all.filter(r=>r.label.toLowerCase().includes(q.toLowerCase())):[...acts.slice(0,4),...nav.slice(0,5)]).slice(0,9);
  React.useEffect(()=>{if(ref.current)ref.current.focus();},[]);
  React.useEffect(()=>setI(0),[q]);
  const key=e=>{if(e.key==="Escape")onClose();if(e.key==="ArrowDown"){e.preventDefault();setI(v=>Math.min(v+1,res.length-1));}if(e.key==="ArrowUp"){e.preventDefault();setI(v=>Math.max(v-1,0));}if(e.key==="Enter"&&res[i])go(res[i].id);};
  const tone={"Ação":"accent","Ecrã":"neutral","Pessoa":"info"};
  return <div onClick={onClose} style={{position:"fixed",inset:0,zIndex:200,background:"rgba(12,16,18,0.34)",backdropFilter:"blur(6px)",display:"grid",placeItems:"center",padding:16,animation:"spotIn 140ms ease-out"}}>
    <div onClick={e=>e.stopPropagation()} style={{width:"min(620px,100%)",background:"var(--ui-surface)",border:"1px solid var(--ui-border)",borderRadius:"var(--ui-r-xl)",boxShadow:"var(--ui-elev-3, 0 24px 70px rgba(10,20,25,0.28))",overflow:"hidden",animation:"spotPanel 200ms cubic-bezier(0.16,1,0.3,1)"}}>
      <div className="row" style={{gap:12,padding:"16px 20px",borderBottom:res.length?"1px solid var(--ui-divider)":"none"}}>
        <I d={P.search} size={19} c="var(--ui-text-3)"/>
        <input ref={ref} value={q} onChange={e=>setQ(e.target.value)} onKeyDown={key} placeholder="Pesquisar ecrãs, ações e pessoas…" style={{flex:1,border:"none",outline:"none",background:"transparent",color:"var(--ui-text)",fontFamily:"var(--font-sans)",fontSize:"var(--ui-fs-h3)",fontWeight:500}}/>
        <kbd style={{fontFamily:"var(--font-sans)",fontSize:"var(--ui-fs-xs)",fontWeight:600,border:"1px solid var(--ui-border-2)",borderRadius:5,padding:"2px 6px",color:"var(--ui-text-3)"}}>esc</kbd>
      </div>
      <div style={{maxHeight:"min(420px,50vh)",overflow:"auto",padding:res.length?6:0}}>
        {res.map((r,j)=><div key={r.kind+r.label} onMouseEnter={()=>setI(j)} onClick={()=>go(r.id)} className="row" style={{gap:12,padding:"11px 14px",borderRadius:"var(--ui-r-sm)",cursor:"pointer",background:i===j?"var(--ui-accent-weak)":"transparent"}}>
          {r.person?<UIAvatar name={r.label} size="sm"/>:<I d={P[r.ic||"grid"]} size={17} c="var(--ui-text-2)"/>}
          <span style={{flex:1,fontSize:"var(--ui-fs-body)",fontWeight:500}}>{r.label}</span>
          <UIPill tone={tone[r.kind]}>{r.kind}</UIPill>
        </div>)}
        {q&&res.length===0&&<div className="muted" style={{padding:"26px 20px",fontSize:"var(--ui-fs-sm)"}}>Sem resultados para «{q}».</div>}
      </div>
      <div className="row" style={{gap:16,padding:"9px 18px",borderTop:"1px solid var(--ui-divider)",background:"var(--ui-surface-2)"}}>
        {[["↑↓","navegar"],["↵","abrir"],["esc","fechar"]].map(([k,l])=><span key={k} className="row" style={{gap:8,fontSize:"var(--ui-fs-xs)",color:"var(--ui-text-3)"}}><kbd style={{fontFamily:"var(--font-sans)",fontWeight:600,border:"1px solid var(--ui-border-2)",borderRadius:4,padding:"0 5px"}}>{k}</kbd>{l}</span>)}
      </div>
    </div>
  </div>;
}

function App(){
  const [dark,setDarkRaw]=React.useState(()=>{try{return localStorage.getItem("xcope-theme")==="dark";}catch(e){return false;}});
  const setDark=v=>{setDarkRaw(v);try{localStorage.setItem("xcope-theme",v?"dark":"light");}catch(e){}};
  const [spot,setSpot]=React.useState(false);const [navOpen,setNavOpen]=React.useState(false);const [help,setHelp]=React.useState(false);
  const [manualMini,setManualMini]=React.useState(null);const [autoMini,setAutoMini]=React.useState(false);const [phone,setPhone]=React.useState(false);
  const [sw,setSw]=React.useState(false);const [more,setMore]=React.useState(false);
  const railScroll=React.useRef(null);
  React.useEffect(()=>{const box=railScroll.current;if(!box)return;
    const id=window.setTimeout(()=>{
      const el=box.querySelector('.nav-i[data-active="1"]');if(!el)return;
      const b=box.getBoundingClientRect(),r=el.getBoundingClientRect();
      if(r.bottom>b.bottom-4) box.scrollTop+=r.bottom-b.bottom+12;
      else if(r.top<b.top+4) box.scrollTop-=b.top-r.top+12;
    },60);
    return ()=>window.clearTimeout(id);
  },[route]);const [companyId,setCompanyId]=React.useState("norte");const [groupView,setGroupView]=React.useState(false);
  const [scope,setScope]=React.useState(["norte"]);const [done,setDone]=React.useState([]);
  const pendCount=PEND.filter(p=>scope.includes(p.co)&&p.kind==="action"&&!done.includes(p.id)).length;
  const company=GROUP.companies.find(c=>c.id===companyId);
  const mini=phone?true:(manualMini===null?autoMini:manualMini);const setMini=v=>setManualMini(v);
  React.useEffect(()=>{const el=document.getElementById("app");if(!el||!window.ResizeObserver)return;const ro=new ResizeObserver(es=>{const w=es[0].contentRect.width;setAutoMini(w<1180);setPhone(w<760);});ro.observe(el);return ()=>ro.disconnect();},[]);
  React.useEffect(()=>{const h=e=>{if((e.metaKey||e.ctrlKey)&&e.key.toLowerCase()==="b"){e.preventDefault();setManualMini(v=>!(v===null?autoMini:v));}};window.addEventListener("keydown",h);return ()=>window.removeEventListener("keydown",h);},[autoMini]);
  React.useEffect(()=>{const h=e=>{if((e.metaKey||e.ctrlKey)&&e.key.toLowerCase()==="k"){e.preventDefault();setSpot(v=>!v);}};window.addEventListener("keydown",h);return ()=>window.removeEventListener("keydown",h);},[]);
  const [openNav,setOpenNav]=React.useState({});const swRef=React.useRef(null);const [swPos,setSwPos]=React.useState({top:0,left:0,w:224});const [rowMenu,setRowMenu]=React.useState(null);const [userMenu,setUserMenu]=React.useState(false);
  React.useEffect(()=>{const h=e=>{if(!(e.metaKey||e.ctrlKey))return;const n=parseInt(e.key,10);
    if(!n)return;const list=GROUP.companies.filter(c=>!c.noAccess);const c=list[n-1];if(!c)return;
    e.preventDefault();setCompanyId(c.id);setGroupView(false);setScope([c.id]);setSw(false);};
   window.addEventListener("keydown",h);return ()=>window.removeEventListener("keydown",h);},[]);
  const [cp,setCp]=React.useState(()=>{try{return window.innerWidth>=1100;}catch(e){return true;}});
  React.useEffect(()=>{const h=e=>{if((e.metaKey||e.ctrlKey)&&e.key.toLowerCase()==="j"){e.preventDefault();setCp(v=>!v);}};window.addEventListener("keydown",h);return ()=>window.removeEventListener("keydown",h);},[]);
  React.useEffect(()=>{const h=e=>{if((e.metaKey||e.ctrlKey)&&e.key==="/"){e.preventDefault();setHelp(v=>!v);}};window.addEventListener("keydown",h);return ()=>window.removeEventListener("keydown",h);},[]);
  const [hist,setHist]=React.useState(["home"]);const [hi,setHi]=React.useState(0);
  const route=hist[hi];
  const secOf=id=>{const g=SECTION_OF[id]||null;return g;};
  const setRoute=React.useCallback(id=>{
    // pushing only makes sense inside the same nav tab/section; crossing tabs starts a new flow
    setHist(h=>{const cur=h[hi];if(cur===id)return h;
      if(secOf(cur)!==secOf(id)){setHi(0);return [id];}
      const base=h.slice(0,hi+1);setHi(base.length);return [...base,id];});
  },[hi]);
  // rail / breadcrumb = switching tab: starts a fresh flow, arrows reset
  const jump=React.useCallback(id=>{setHist([id]);setHi(0);},[]);
  const canBack=hi>0,canFwd=hi<hist.length-1;
  React.useEffect(()=>{document.getElementById("app").setAttribute("data-theme",dark?"dark":"");},[dark]);
  React.useEffect(()=>{const el=document.getElementById("app");if(el)el.setAttribute("data-nav",navOpen?"open":"");},[navOpen]);
  React.useEffect(()=>{setNavOpen(false);},[route]);
  const Screen=S[route]||(()=><Stub icon="grid" title={LABELS[route]||"Ecrã"} desc="Mock em construção."/>);
  return (<CTX.Provider value={{scope,setScope,company,groupView,companies:GROUP.companies,done,setDone}}><React.Fragment>
    <div className={"railcol"+(mini?" mini":"")}>
    <div className="rail-srch" title="Pesquisar" onClick={()=>setSpot(true)}>
      <I d={P.search} size={16}/>
      <span className="lbl" style={{flex:1,fontSize:"var(--ui-fs-body)"}}>Pesquisar…</span>
      <span className="kbds">{[isMac?"⌘":"Ctrl","K"].map(k=><kbd key={k}>{k}</kbd>)}</span>
    </div>
    <aside className={"rail"+(mini?" mini":"")} style={{position:"relative"}}>
      <div className="rail-top">
        <div className="rail-hdr">
          <div ref={swRef} className="ws" style={{flex:1,minWidth:0,position:"relative"}} onClick={()=>{const el=swRef.current.closest(".rail")||swRef.current;const r=el.getBoundingClientRect();const t0=swRef.current.getBoundingClientRect().top;setSwPos({top:t0,left:r.right+8,w:256});setSw(v=>!v);}}><img className="mk" src={BRAND.logo} alt="Xcope" style={{objectFit:"cover"}}/><div className="ws-txt" style={{flex:1,minWidth:0}}><div style={{fontSize:"var(--ui-fs-body)",fontWeight:600,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}}>{company.name}</div><div className="muted" style={{fontSize:"var(--ui-fs-xs)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}}>{company.role}</div></div><span className="ws-txt" style={{display:"inline-flex",color:"var(--ui-text-3)",flexShrink:0}}><I d={["m7 15 5 5 5-5","m7 9 5-5 5 5"]} size={14}/></span></div>
        </div>
        {sw&&<React.Fragment><div onClick={()=>setSw(false)} style={{position:"fixed",inset:0,zIndex:60}}></div>
        <div className="teammenu" style={{top:swPos.top,left:swPos.left,width:swPos.w}}>
          <div className="tm-label">Plataforma Xcope</div>
          {PRODUCTS.map(p=><div key={p.id} className="tm-item" title={p.desc}
            onClick={()=>{if(p.url){window.location.href=p.url;}else{setSw(false);}}}>
            <span className="tm-ic" style={p.active?{background:"var(--ui-accent)",color:"var(--ui-on-accent)",borderColor:"transparent",fontWeight:600,fontSize:"var(--ui-fs-xs)"}:undefined}>{p.label.replace("XCOPE ","")[0]}</span>
            <span className="tm-name">{p.label}</span>
            {p.active
              ? <I d={["M20 6 9 17l-5-5"]} size={15} c="var(--ui-accent)"/>
              : <I d={["M7 17 17 7","M8 7h9v9"]} size={13} c="var(--ui-text-3)"/>}
          </div>)}
          <div className="tm-sep"/>
          <div className="tm-label">{GROUP.name}</div>
          <div className="tm-item" onClick={()=>{setGroupView(true);setScope(GROUP.companies.filter(c=>!c.noAccess).map(c=>c.id));setSw(false);jump("group");}}>
            <span className="tm-ic"><I d={P.grid} size={14}/></span>
            <span className="tm-name">Visão consolidada</span>
            {groupView&&<I d={["M20 6 9 17l-5-5"]} size={15} c="var(--ui-accent)"/>}
          </div>
          <div className="tm-sep"/>
          <div className="tm-label">Empresas</div>
          {GROUP.companies.map(c=>{const idx=GROUP.companies.filter(x=>!x.noAccess).indexOf(c)+1;
            return <div key={c.id} className={"tm-item"+(c.noAccess?" off":"")} title={c.noAccess?"Sem acesso a esta empresa":c.name}
              onClick={()=>{if(c.noAccess)return;setCompanyId(c.id);setGroupView(false);setScope([c.id]);setSw(false);}}>
              <span className="tm-ic" style={{background:c.color,color:"#fff",borderColor:"transparent",fontWeight:600,fontSize:"var(--ui-fs-xs)"}}>{c.short}</span>
              <span className="tm-name">{c.name}</span>
              {!groupView&&companyId===c.id
                ? <I d={["M20 6 9 17l-5-5"]} size={15} c="var(--ui-accent)"/>
                : !c.noAccess&&<span className="tm-kbd">{isMac?"⌘":"^"}{idx}</span>}
            </div>;})}
          <div className="tm-sep"/>
          <div className="tm-item" onClick={()=>{setSw(false);jump("admin-tenants");}}>
            <span className="tm-ic dashed"><I d={["M12 5v14","M5 12h14"]} size={14}/></span>
            <span className="tm-name muted" style={{fontWeight:500}}>Adicionar empresa</span>
          </div>
        </div></React.Fragment>}
      </div>
      <div className="rail-scroll" ref={railScroll}>{NAV.map(([group,kind,items],gi)=>
        <div key={gi} className={kind==="flat"?"navgroup flat":"navgroup"}>
          <div className="sec"><span>{group}</span></div>
          {items.map(([id,l,ic,kids])=>{
            if(!kids)return <div key={id} className="menuitem">
              <UINavItem title={mini?undefined:l} data-tip={l} aria-label={l} className="nav-i" icon={<I d={P[ic]} size={16}/>}
                active={route===id} data-active={route===id?"1":undefined} onClick={()=>{setSw(false);jump(id);}}><span className="lbl">{l}</span></UINavItem>
              <span className="menuaction" title="Mais" onClick={e=>{e.stopPropagation();setRowMenu(rowMenu===id?null:id);}}><I d={["M12 5h.01","M12 12h.01","M12 19h.01"]} size={15}/></span>
              {rowMenu===id&&<React.Fragment>
                <div onClick={()=>setRowMenu(null)} style={{position:"fixed",inset:0,zIndex:70}}/>
                <div className="rowmenu">
                  <div onClick={()=>setRowMenu(null)}><I d={P.folder} size={15}/>Abrir</div>
                  <div onClick={()=>setRowMenu(null)}><I d={P.share} size={15}/>Partilhar</div>
                  <div className="sep"/>
                  <div onClick={()=>setRowMenu(null)}><I d={["M4 7h16","M10 11v6","M14 11v6","M6 7l1 13h10l1-13","M9 7V4h6v3"]} size={15}/>Remover do menu</div>
                </div></React.Fragment>}
            </div>;
            const inKids=kids.some(([k])=>k===route);
            const open=!mini&&(openNav[id]!==undefined?openNav[id]:inKids);
            return <div key={id} className="menuitem">
              <UINavItem title={mini?undefined:l} data-tip={l} aria-label={l} className="nav-i" icon={<I d={P[ic]} size={16}/>}
                active={route===id||(inKids&&!open)}
                onClick={()=>{setSw(false);if(mini){jump(kids[0][0]);}else setOpenNav(o=>({...o,[id]:!open}));}}
                badge={!mini?<span className={"treechev"+(open?" open":"")}><I d={["m9 18 6-6-6-6"]} size={14}/></span>:undefined}>
                <span className="lbl">{l}</span></UINavItem>
              {open&&<div className="menusub">{kids.map(([kid,kl])=>
                <div key={kid} className={"subbtn nav-i"+(route===kid?" on":"")} data-active={route===kid?"1":undefined} onClick={()=>{setSw(false);jump(kid);}}>{kl}</div>)}</div>}
            </div>;})}
          {kind==="flat"&&<div className="menuitem" style={{position:"relative"}}>
            <UINavItem className="nav-i more" data-tip="Mais" aria-label="Mais" title={mini?undefined:"Mais"} onClick={()=>setMore(v=>!v)}
              icon={<I d={["M12 5h.01","M12 12h.01","M12 19h.01"]} size={16}/>}><span className="lbl">Mais</span></UINavItem>
            {more&&<React.Fragment>
              <div onClick={()=>setMore(false)} style={{position:"fixed",inset:0,zIndex:70}}/>
              <div className="usermenu" style={{left:mini?56:8,right:"auto",bottom:"auto",top:0,width:220}}>
                {[["calendar","Calendário"],["my-tickets","Os meus tickets"],["surveys","Inquéritos"],["career","Carreira"]].map(([id,l])=>
                  <div key={id} onClick={()=>{setMore(false);jump(id);}}>{l}</div>)}
              </div>
            </React.Fragment>}
          </div>}
        </div>)}</div>
      <div className="rail-bot">
        <div className="ws navuser" onClick={()=>setUserMenu(v=>!v)} style={{position:"relative"}}>
          <UIAvatar name={USER.name} size="sm"/>
          <div className="ws-txt" style={{flex:1,minWidth:0}}>
            <div style={{fontSize:"var(--ui-fs-body)",fontWeight:600,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}}>{USER.name}</div>
            <div className="muted" style={{fontSize:"var(--ui-fs-xs)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}}>{USER.email}</div>
          </div>
          <span className="ws-txt" style={{display:"inline-flex",color:"var(--ui-text-3)",flexShrink:0}}><I d={["m7 15 5 5 5-5","m7 9 5-5 5 5"]} size={14}/></span>
        </div>
        {userMenu&&<React.Fragment>
          <div onClick={()=>setUserMenu(false)} style={{position:"fixed",inset:0,zIndex:70}}/>
          <div className="usermenu">
            <div className="row" style={{gap:8,padding:"6px 8px 10px"}}>
              <UIAvatar name={USER.name} size="sm"/>
              <div style={{minWidth:0}}><div style={{fontSize:"var(--ui-fs-body)",fontWeight:600}}>{USER.name}</div><div className="muted" style={{fontSize:"var(--ui-fs-xs)"}}>{USER.email}</div></div>
            </div>
            <div className="sep"/>
            <div onClick={()=>{setUserMenu(false);jump("profile");}}><I d={P.badge} size={15}/>Conta</div>
            <div onClick={()=>{setUserMenu(false);jump("notifications");}}><I d={P.bell} size={15}/>Notificações</div>
            <div onClick={()=>{setUserMenu(false);jump("settings");}}><I d={P.cog} size={15}/>Definições</div>
            <div onClick={()=>{setUserMenu(false);setHelp(true);}}><I d={P.info} size={15}/>Ajuda e atalhos</div>
            <div className="sep"/>
            <div onClick={()=>setUserMenu(false)}><I d={["M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4","m16 17 5-5-5-5","M21 12H9"]} size={15}/>Terminar sessão</div>
          </div></React.Fragment>}
      </div>
    </aside>
    </div>
    <div className="main">
      <div className="navscrim" onClick={()=>setNavOpen(false)}/>
      <nav className="tabbar">
        {[["home","Início",P.home],["inbox","Inbox",P.mail],["chat","Chat",P.chat],["notifications","Pendentes",P.bell],["profile","Perfil",P.badge]].map(([id,l,d])=>
          <button key={id} aria-current={route===id?"page":undefined} onClick={()=>jump(id)}>
            <I d={d} size={20}/>
            <span>{l}</span>
            {id==="notifications"&&pendCount>0&&<span className="dot"/>}
          </button>)}
      </nav>
      <header className="top">
        <span className="ico-btn navtoggle" title="Menu" onClick={()=>setNavOpen(true)}><I d={["M4 6h16","M4 12h16","M4 18h16"]} size={18}/></span>
        <div className="row" style={{flex:1,minWidth:0,gap:8,fontSize:"var(--ui-fs-sm)",overflow:"hidden"}}>
          <span className="bare-btn" title={(mini?"Expandir":"Condensar")+" menu (⌘B)"} onClick={()=>setMini(!mini)}><I d={["M3 4h18v16H3z","M9 4v16"]} size={16}/></span>
          <span style={{width:1,height:16,background:"var(--ui-border)",flexShrink:0,margin:"0 4px"}}/>
          {(()=>{const sect=SECTION_OF[route];const grp=null;const lbl=LABELS[route];
            return <React.Fragment>{sect&&<React.Fragment><span className="muted" style={{whiteSpace:"nowrap"}}>{sect}</span><span className="muted" style={{display:"inline-flex",opacity:0.6,flexShrink:0}}><I d={["m9 18 6-6-6-6"]} size={14}/></span></React.Fragment>}{lbl&&<span style={{fontWeight:600,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"}}>{lbl}</span>}</React.Fragment>;})()}
        </div>
        <div className="row" style={{gap:14}}>
        <div className="ico-btn" title="Pendentes" onClick={()=>jump("notifications")}><I d={P.bell} size={17}/>{pendCount>0&&<span className="cnt">{pendCount}</span>}</div>
        <UIAvatar name={USER.name} size="md" status="online"/>
        </div>
      </header>
      {spot&&<Spotlight onClose={()=>setSpot(false)} go={id=>{setSpot(false);jump(id);}}/>}
      <div className="scroll"><div style={{display:"flex",flexDirection:"column",minHeight:"100%",height:FIT.includes(route)?"100%":undefined}}><Screen go={setRoute} dark={dark} setDark={setDark}/></div></div>
    </div>
    <Copilot route={route} label={LABELS[route]||"esta página"} open={cp} setOpen={setCp}/>
    <UIModal open={help} onClose={()=>setHelp(false)} title="Ajuda e atalhos" width={480}
      footer={<div className="row" style={{gap:8}}><span className="muted" style={{fontSize:"var(--ui-fs-sm)"}}>Suporte: suporte@xcope.ai</span><div className="spring"/><UIButton variant="ghost" onClick={()=>setHelp(false)}>Fechar</UIButton></div>}>
      <div style={{display:"flex",flexDirection:"column",gap:4}}>
        {[[isMac?"⌘ K":"Ctrl K","Pesquisa e ações rápidas"],[isMac?"⌘ B":"Ctrl B","Recolher ou expandir a barra lateral"],[isMac?"⌘ J":"Ctrl J","Abrir ou fechar o Copiloto"],[isMac?"⌘ /":"Ctrl /","Esta janela de ajuda"],[isMac?"⌘ 1-3":"Ctrl 1-3","Mudar de empresa do grupo"],["Esc","Fechar janelas e painéis"]].map(([k,d])=>
          <div key={k} className="row" style={{gap:12,padding:"9px 0",borderBottom:"1px solid var(--ui-divider)",fontSize:"var(--ui-fs-sm)"}}>
            <span style={{minWidth:70}}>{k.split(" ").map(x=><kbd key={x} style={{fontFamily:"var(--font-sans)",fontSize:"var(--ui-fs-xs)",fontWeight:600,border:"1px solid var(--ui-border-2)",borderRadius:5,padding:"1px 6px",marginRight:4,background:"var(--ui-surface-2)"}}>{x}</kbd>)}</span>
            <span>{d}</span></div>)}
        <div className="muted" style={{fontSize:"var(--ui-fs-sm)",paddingTop:12,lineHeight:1.55}}>Precisas de mais? O Copiloto responde a perguntas sobre qualquer ecrã, e a equipa de suporte responde em menos de um dia útil.</div>
      </div>
    </UIModal>
    <RailTips active={mini}/>
  </React.Fragment></CTX.Provider>);
}
window.WFA={S,Head,AV,I,P,PEOPLE,useCtx,GROUP,useWidth};
window.XcopeShell={I,P,Head,Stub,useCtx,useWidth,
  mount:()=>ReactDOM.createRoot(document.getElementById("app")).render(<App/>)};
