const {S,Head,AV,I,P}=window.WFA;
const {UIButton,UIInput,UICard,UIAvatar,UIToggle,UIModal,UIBanner,UIPill,UISelect,UITabs}=window.XCOPEDesignSystem_bf80f1;
const chatMe="Hugo Montenegro",chatDept="Pessoas",chatAdmins=["Tomás Machado"];
const CDEPTS={"Comercial":["Tomás Jervell","Marta Lopes"],"Pessoas":["Hugo Montenegro","Tomás Machado"],"Produto":["Ana Reis","Bruno Costa"]};
const CPEOPLE=[...new Set(Object.values(CDEPTS).flat())];
const CEMOJI=["\u{1F44D}","\u2705","\u2764\uFE0F","\u{1F602}","\u{1F389}","\u{1F440}","\u{1F64F}","\u{1F525}"];
const CSTATUS={"Ana Reis":"\u{1F3AF} Focada até 15h","Tomás Jervell":"\u{1F4C5} Em reunião"};
const CSTATUS_PRESETS=["\u{1F3AF} Focado","\u{1F4C5} Em reunião","\u{1F37D}\uFE0F Almoço","\u{1F3D6}\uFE0F De férias"];
const CH_SEED={
 "anuncios":{type:"ch",label:"anúncios",desc:"Comunicações oficiais da empresa. Apenas administradores publicam.",topic:"Comunicações oficiais",group:"empresa",private:false,post:"admins",muted:false,archived:false,members:{people:[],depts:["Comercial","Pessoas","Produto"]},canvas:"Guia do canal\n\nEste canal é reservado a comunicações oficiais. Para conversa geral usa o #geral.",unread:0,msgs:[
  {id:1,from:"Tomás Machado",time:"09:02",text:"*All-hands* sexta às 11h no auditório. A agenda segue por email.",reacts:{"\u{1F44D}":["Ana Reis","Bruno Costa","Hugo Montenegro"]},thread:[],pinned:true}]},
 "geral":{type:"ch",label:"geral",desc:"Conversa aberta a toda a empresa.",topic:"Conversa da empresa",group:"empresa",private:false,post:"all",muted:false,archived:false,members:{people:[],depts:["Comercial","Pessoas","Produto"]},canvas:"",unread:0,msgs:[
  {id:1,from:"Ana Reis",time:"09:15",text:"Os novos cartões de acesso chegam esta semana. Quem não entregou foto, envie para @Tomás Machado.",reacts:{},thread:[{from:"Bruno Costa",time:"09:20",text:"Enviada!"}],pinned:false},
  {id:2,from:"Bruno Costa",time:"10:41",text:"Alguém sabe se a sala 2 está livre à tarde?",reacts:{},thread:[],pinned:false}]},
 "produto":{type:"ch",label:"produto",desc:"Coordenação da equipa de produto.",topic:"Sprint 14 · demo às quintas",group:"produto-g",private:false,post:"all",muted:false,archived:false,members:{people:["Hugo Montenegro"],depts:["Produto"]},canvas:"Notas do sprint 14\n\n- Onboarding novo entra esta semana\n- Demo quinta às 11h\n- Piloto: métricas na pasta partilhada",unread:2,msgs:[
  {id:1,from:"Ana Reis",time:"11:02",text:"Enviei o mockup do onboarding. @Hugo Montenegro consegues rever hoje?",tr:"I sent the onboarding mockup. @Hugo Montenegro can you review it today?",reacts:{"\u2705":["Hugo Montenegro"]},thread:[{from:"Hugo Montenegro",time:"11:30",text:"Vejo depois do almoço e comento lá."}],pinned:false},
  {id:2,from:"Marta Lopes",time:"11:45",text:"Números do piloto atualizados: `conversao 12%` — detalhe na pasta.",tr:"Pilot numbers updated: `conversion 12%` — details in the shared folder.",reacts:{"\u{1F389}":["Ana Reis"]},thread:[],pinned:false,att:"Piloto_metricas.xlsx"}]},
 "rh-interno":{type:"ch",label:"rh-interno",desc:"Assuntos internos da equipa de Pessoas.",topic:"Só equipa de Pessoas",group:"pessoas-g",private:true,post:"all",muted:false,archived:false,members:{people:[],depts:["Pessoas"]},canvas:"",unread:0,msgs:[
  {id:1,from:"Tomás Machado",time:"Ontem",text:"As avaliações de desempenho abrem dia 1. Confirmem os formulários até quarta.",reacts:{},thread:[],pinned:true}]},
 "vendas-pipeline":{type:"ch",label:"vendas-pipeline",desc:"Pipeline e contas.",topic:"",group:"vendas-g",private:false,post:"all",muted:false,archived:false,members:{people:[],depts:["Comercial"]},canvas:"",unread:0,msgs:[]},
 "dm:Tomás Jervell":{type:"dm",label:"Tomás Jervell",online:true,muted:false,archived:false,unread:0,canvas:"",members:{people:["Hugo Montenegro","Tomás Jervell"],depts:[]},msgs:[
  {id:1,from:"Tomás Jervell",time:"14:20",text:"Vemo-nos às 15h?",reacts:{},thread:[],pinned:false},
  {id:2,from:"Hugo Montenegro",time:"14:22",text:"Sim, levo os números do piloto.",reacts:{"\u{1F44D}":["Tomás Jervell"]},thread:[],pinned:false}]},
 "dm:Ana Reis":{type:"dm",label:"Ana Reis",online:true,muted:false,archived:false,unread:1,canvas:"",members:{people:["Hugo Montenegro","Ana Reis"],depts:[]},msgs:[
  {id:1,from:"Ana Reis",time:"12:03",text:"Quando puderes vê o contrato que te enviei por email \u{1F64F}",reacts:{},thread:[],pinned:false}]},
 "dm:Ana Reis, Bruno Costa":{type:"dm",label:"Ana Reis, Bruno Costa",gdm:true,online:false,muted:false,archived:false,unread:0,canvas:"",members:{people:["Hugo Montenegro","Ana Reis","Bruno Costa"],depts:[]},msgs:[
  {id:1,from:"Bruno Costa",time:"Seg",text:"Alinhamos os três amanhã sobre o piloto?",reacts:{},thread:[],pinned:false}]}};
const GRP_SEED=[{id:"empresa",name:"Empresa",audience:["*"]},{id:"pessoas-g",name:"Pessoas",audience:["Pessoas"]},{id:"produto-g",name:"Produto",audience:["Produto","Pessoas"]},{id:"vendas-g",name:"Vendas",audience:["Comercial"]}];
const isMember=c=>c.type==="dm"||c.members.people.includes(chatMe)||c.members.depts.some(d=>(CDEPTS[d]||[]).includes(chatMe));
const rTxt=t=>t.split(/(@[A-Za-zÀ-ú]+(?: [A-Za-zÀ-ú]+)?|\*[^*]+\*|_[^_]+_|`[^`]+`)/g).map((p,i)=>{
  if(!p)return null;
  if(p.startsWith("@"))return <span key={i} style={{background:"var(--ui-accent-weak)",color:"var(--ui-accent)",borderRadius:4,padding:"0 3px",fontWeight:600}}>{p}</span>;
  if(p.startsWith("*"))return <strong key={i} style={{color:"var(--ui-text)"}}>{p.slice(1,-1)}</strong>;
  if(p.startsWith("_"))return <em key={i}>{p.slice(1,-1)}</em>;
  if(p.startsWith("`"))return <code key={i} style={{background:"var(--ui-surface-2)",border:"1px solid var(--ui-border)",borderRadius:4,padding:"1px 5px",fontSize:"0.9em"}}>{p.slice(1,-1)}</code>;
  return p;});
const popStyle={position:"absolute",background:"var(--ui-surface)",border:"1px solid var(--ui-border)",borderRadius:"var(--ui-r-sm)",boxShadow:"var(--ui-elev-2)",padding:6,zIndex:30,display:"flex",flexDirection:"column",gap:2};
const popRow={display:"flex",alignItems:"center",gap:8,padding:"7px 10px",borderRadius:6,cursor:"pointer",fontSize:"var(--ui-fs-sm)",fontWeight:500};
const TRANSCRIPT_POOL=[["Ana Reis","Consigo ouvir-vos bem, podemos começar."],["Tu","Vamos rever primeiro os números do piloto."],["Ana Reis","A conversão subiu para 12% esta semana."],["Tu","Boa. Partilho o ecrã com o dashboard."],["Ana Reis","O onboarding novo entra no sprint 14, certo?"],["Tu","Sim, a demo fica para quinta às 11h."]];
const HoverRow=({children,onClick,style})=><div onClick={onClick} style={{...popRow,...style}} onMouseEnter={e=>e.currentTarget.style.background="var(--ui-surface-2)"} onMouseLeave={e=>e.currentTarget.style.background="transparent"}>{children}</div>;

S.chat=()=>{
  const [chans,setChans]=React.useState(CH_SEED);const [groups,setGroups]=React.useState(GRP_SEED);
  const [cur,setCur]=React.useState("produto");const [view,setView]=React.useState(null);
  const [drafts,setDrafts]=React.useState({});const [thread,setThread]=React.useState(null);const [tInput,setTInput]=React.useState("");
  const [hover,setHover]=React.useState(null);const [emoPop,setEmoPop]=React.useState(null);const [fwdPop,setFwdPop]=React.useState(null);const [schedPop,setSchedPop]=React.useState(false);
  const [editId,setEditId]=React.useState(null);const [editText,setEditText]=React.useState("");
  const [q,setQ]=React.useState("");const [chTab,setChTab]=React.useState("msgs");const [detail,setDetail]=React.useState(false);const [detailTab,setDetailTab]=React.useState("sobre");
  const [collapsed,setCollapsed]=React.useState({});const [huddle,setHuddle]=React.useState(null);const [myStatus,setMyStatus]=React.useState(null);const [statusPop,setStatusPop]=React.useState(false);
  const [saved,setSaved]=React.useState([]);const [sched,setSched]=React.useState([]);const [reminders,setReminders]=React.useState([]);
  const [modal,setModal]=React.useState(null);const [profile,setProfile]=React.useState(null);
  const [call,setCall]=React.useState(null);const [transl,setTransl]=React.useState({});const [gq,setGq]=React.useState("");
  const camRef=React.useRef(null);const shareRef=React.useRef(null);const streams=React.useRef({cam:null,share:null});
  React.useEffect(()=>{if(!call)return;const t=setInterval(()=>{setCall(c=>c?{...c,transcript:[...c.transcript,TRANSCRIPT_POOL[c.transcript.length%TRANSCRIPT_POOL.length]]}:c);},3200);return ()=>clearInterval(t);},[!!call]);
  const stopStream=k=>{if(streams.current[k]){streams.current[k].getTracks().forEach(t=>t.stop());streams.current[k]=null;}};
  const endCall=()=>{stopStream("cam");stopStream("share");setCall(null);};
  const toggleCam=async()=>{if(call.video){stopStream("cam");setCall(c=>({...c,video:false}));return;}try{const s=await navigator.mediaDevices.getUserMedia({video:true});streams.current.cam=s;setCall(c=>({...c,video:true}));setTimeout(()=>{if(camRef.current)camRef.current.srcObject=s;},50);}catch(e){setCall(c=>({...c,video:false,err:"Câmara indisponível ou sem permissão."}));}};
  const toggleShare=async()=>{if(call.sharing){stopStream("share");setCall(c=>({...c,sharing:false}));return;}try{const s=await navigator.mediaDevices.getDisplayMedia({video:true});streams.current.share=s;s.getVideoTracks()[0].onended=()=>{streams.current.share=null;setCall(c=>c?{...c,sharing:false}:c);};setCall(c=>({...c,sharing:true}));setTimeout(()=>{if(shareRef.current)shareRef.current.srcObject=s;},50);}catch(e){setCall(c=>({...c,err:"Partilha de ecrã cancelada ou sem permissão."}));}};
  const [fName,setFName]=React.useState("");const [fDesc,setFDesc]=React.useState("");const [fGroup,setFGroup]=React.useState("empresa");const [fPriv,setFPriv]=React.useState(false);const [fPost,setFPost]=React.useState("all");const [fMembers,setFMembers]=React.useState([]);const [fMemQ,setFMemQ]=React.useState("");
  const [gName,setGName]=React.useState("");const [gAll,setGAll]=React.useState(true);const [gAud,setGAud]=React.useState([]);
  const input=drafts[cur]||"";const setInput=v=>setDrafts(d=>({...d,[cur]:v}));
  const ch=chans[cur];const canPost=ch&&(ch.type==="dm"||ch.post!=="admins"||chatAdmins.includes(chatMe));
  const visGroups=groups.filter(g=>g.audience.includes("*")||g.audience.includes(chatDept));
  const hiddenG=groups.length-visGroups.length;
  const chIn=gid=>Object.entries(chans).filter(([k,c])=>c.type==="ch"&&!c.archived&&c.group===gid&&isMember(c));
  const loose=Object.entries(chans).filter(([k,c])=>c.type==="ch"&&!c.archived&&isMember(c)&&!visGroups.some(g=>g.id===c.group));
  const mention=input.match(/@([\wÀ-ú]*)$/);const mSugg=mention?["canal","aqui",...CPEOPLE].filter(d=>d.toLowerCase().startsWith(mention[1].toLowerCase())&&d!==chatMe).slice(0,5):[];
  const upd=(k,fn)=>setChans(cs=>({...cs,[k]:fn(cs[k])}));
  const openCh=k=>{setCur(k);setView(null);setThread(null);setDetail(false);setChTab("msgs");setQ("");upd(k,c=>({...c,unread:0}));};
  const send=()=>{const t=input.trim();if(!t||!canPost)return;upd(cur,c=>({...c,msgs:[...c.msgs,{id:Date.now(),from:chatMe,time:"Agora",text:t,reacts:{},thread:[],pinned:false}]}));setInput("");};
  const react=(id,e)=>{setEmoPop(null);upd(cur,c=>({...c,msgs:c.msgs.map(m=>{if(m.id!==id)return m;const r={...m.reacts};const has=(r[e]||[]).includes(chatMe);r[e]=has?r[e].filter(x=>x!==chatMe):[...(r[e]||[]),chatMe];if(!r[e].length)delete r[e];return {...m,reacts:r};})}));};
  const togglePin=id=>upd(cur,c=>({...c,msgs:c.msgs.map(m=>m.id===id?{...m,pinned:!m.pinned}:m)}));
  const delMsg=id=>{upd(cur,c=>({...c,msgs:c.msgs.filter(m=>m.id!==id)}));if(thread===id)setThread(null);};
  const saveEdit=()=>{upd(cur,c=>({...c,msgs:c.msgs.map(m=>m.id===editId?{...m,text:editText,edited:true}:m)}));setEditId(null);};
  const sendThread=()=>{const t=tInput.trim();if(!t)return;upd(cur,c=>({...c,msgs:c.msgs.map(m=>m.id===thread?{...m,thread:[...m.thread,{from:chatMe,time:"Agora",text:t}]}:m)}));setTInput("");};
  const toggleSave=(k,id)=>setSaved(s=>s.some(r=>r.ch===k&&r.id===id)?s.filter(r=>!(r.ch===k&&r.id===id)):[...s,{ch:k,id}]);
  const isSaved=(k,id)=>saved.some(r=>r.ch===k&&r.id===id);
  const forward=(msg,dest)=>{setFwdPop(null);upd(dest,c=>({...c,msgs:[...c.msgs,{id:Date.now(),from:chatMe,time:"Agora",text:"\u21AA\uFE0E Reencaminhada de "+(ch.type==="ch"?"#"+ch.label:ch.label)+": "+msg.text,reacts:{},thread:[],pinned:false}]}));};
  const remind=msg=>{setReminders(r=>[...r,{ch:cur,text:msg.text,from:msg.from,when:"Amanhã às 09:00"}]);setHover(null);};
  const schedule=when=>{const t=input.trim();if(!t)return;setSched(s=>[...s,{id:Date.now(),ch:cur,text:t,when}]);setInput("");setSchedPop(false);};
  const sendNow=it=>{upd(it.ch,c=>({...c,msgs:[...c.msgs,{id:Date.now(),from:chatMe,time:"Agora",text:it.text,reacts:{},thread:[],pinned:false}]}));setSched(s=>s.filter(x=>x.id!==it.id));};
  const addMember=v=>{if(!fMembers.some(m=>m.v===v.v))setFMembers(ms=>[...ms,v]);setFMemQ("");};
  const memSugg=fMemQ.trim()?[...Object.keys(CDEPTS).filter(d=>d.toLowerCase().includes(fMemQ.toLowerCase())).map(d=>({t:"d",v:d})),...CPEOPLE.filter(p=>p!==chatMe&&p.toLowerCase().includes(fMemQ.toLowerCase())).map(p=>({t:"p",v:p}))].slice(0,5):[];
  const createCh=()=>{const slug=fName.trim().toLowerCase().replace(/\s+/g,"-");if(!slug)return;
    setChans(cs=>({...cs,[slug]:{type:"ch",label:slug,desc:fDesc,topic:fDesc.slice(0,60),group:fGroup,private:fPriv,post:fPost,muted:false,archived:false,members:{people:[chatMe,...fMembers.filter(m=>m.t==="p").map(m=>m.v)],depts:fMembers.filter(m=>m.t==="d").map(m=>m.v)},canvas:"",unread:0,msgs:[]}}));
    setModal(null);setFName("");setFDesc("");setFPriv(false);setFPost("all");setFMembers([]);setCur(slug);setView(null);};
  const createGrp=()=>{const n=gName.trim();if(!n)return;setGroups(gs=>[...gs,{id:n.toLowerCase().replace(/\s+/g,"-"),name:n,audience:gAll?["*"]:gAud}]);setModal(null);setGName("");setGAll(true);setGAud([]);};
  const tMsg=thread!==null&&ch?ch.msgs.find(m=>m.id===thread):null;
  const visible=ch?ch.msgs.filter(m=>!q||m.text.toLowerCase().includes(q.toLowerCase())||m.from.toLowerCase().includes(q.toLowerCase())):[];
  const pinned=ch?ch.msgs.filter(m=>m.pinned):[];
  const files=ch?ch.msgs.filter(m=>m.att):[];
  const activity=[...Object.entries(chans).flatMap(([k,c])=>c.msgs.filter(m=>m.text.includes("@"+chatMe)).map(m=>({kind:"Menção",ch:k,from:m.from,text:m.text}))),...Object.entries(chans).flatMap(([k,c])=>c.msgs.filter(m=>m.from===chatMe&&Object.keys(m.reacts).length).map(m=>({kind:"Reação",ch:k,from:Object.values(m.reacts)[0][0],text:Object.keys(m.reacts)[0]+" à tua mensagem: "+m.text}))),...reminders.map(r=>({kind:"Lembrete",ch:r.ch,from:r.from,text:r.text+" · "+r.when}))];
  const deptOf=n=>Object.keys(CDEPTS).find(d=>CDEPTS[d].includes(n));
  const Row=(k,c)=>{const agg=c.unread||0;return <div key={k} onClick={()=>openCh(k)} className="row" style={{gap:8,padding:"6px 12px",borderRadius:"var(--ui-r-sm)",cursor:"pointer",fontSize:"var(--ui-fs-sm)",opacity:c.muted?0.55:1,fontWeight:cur===k&&!view?600:(agg?700:500),background:cur===k&&!view?"var(--ui-accent-weak)":"transparent",color:cur===k&&!view?"var(--ui-text)":(agg?"var(--ui-text)":"var(--ui-text-2)")}}>
    {c.type==="ch"?<I d={c.private?P.lock:P.hash} size={14}/>:(c.gdm?<span style={{fontSize:"var(--ui-fs-xs)",fontWeight:600,background:"var(--ui-surface-2)",border:"1px solid var(--ui-border)",borderRadius:6,padding:"1px 6px"}}>{c.members.people.length}</span>:AV(c.label,"sm",c.online?"online":undefined))}
    <span style={{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}}>{c.label}</span>
    {drafts[k]&&cur!==k&&<I d={P.pencil} size={12} c="var(--ui-text-3)"/>}
    {!c.muted&&agg>0&&<span style={{background:"var(--ui-accent)",color:"var(--ui-on-accent)",borderRadius:999,fontSize:"var(--ui-fs-xs)",fontWeight:600,padding:"1px 7px"}}>{agg}</span>}</div>;};
  const Util=(id,icon,label,count)=><div onClick={()=>{setView(id);setThread(null);setDetail(false);}} className="row" style={{gap:8,padding:"6px 12px",borderRadius:"var(--ui-r-sm)",cursor:"pointer",fontSize:"var(--ui-fs-sm)",fontWeight:view===id?600:500,background:view===id?"var(--ui-accent-weak)":"transparent",color:view===id?"var(--ui-text)":"var(--ui-text-2)"}}><I d={icon} size={15}/><span style={{flex:1}}>{label}</span>{count>0&&<span className="muted" style={{fontSize:"var(--ui-fs-xs)",fontWeight:600}}>{count}</span>}</div>;
  const sec={fontSize:"var(--ui-fs-xs)",fontWeight:600,letterSpacing:"0.06em",textTransform:"uppercase",padding:"12px 12px 4px",color:"var(--ui-text-3)"};
  return <React.Fragment><Head title="Chat" desc="Canais, mensagens diretas e threads da empresa" actions={<div className="row" style={{gap:8}}><UIButton variant="outline" size="sm" onClick={()=>setModal("browse")}>Explorar canais</UIButton><UIButton size="sm" icon={<I d={P.plus} size={15}/>} onClick={()=>setModal("channel")}>Novo canal</UIButton></div>}/>
  <UICard style={{padding:0,overflow:"hidden",flex:1,display:"flex",flexDirection:"column"}}><div className={(thread!==null||detail)&&!view?"panes panes3":"panes"} style={(thread!==null||detail)&&!view?{}:{"--pane":"250px"}}>
    <div style={{borderRight:"1px solid var(--ui-divider)",display:"flex",flexDirection:"column",minHeight:0}}>
      <div style={{flex:1,overflow:"auto",padding:"12px 10px",display:"flex",flexDirection:"column",gap:1}}>
        <div style={{padding:"0 2px 8px"}}><UIInput leading={<I d={P.search} size={14}/>} placeholder="Pesquisar em tudo" value={gq} onChange={e=>{setGq(e.target.value);if(e.target.value)setView("gsearch");else setView(null);}}/></div>
        {Util("activity",P.bell,"Atividade",activity.length)}{Util("saved",P.bmark,"Guardados",saved.length)}{Util("sched",P.clock,"Agendadas",sched.length)}
        {visGroups.map(g=>{const list=chIn(g.id);const agg=list.reduce((n,[k,c])=>n+(c.muted?0:c.unread),0);const col=collapsed[g.id];
          return <div key={g.id}><div className="row" onClick={()=>setCollapsed(s=>({...s,[g.id]:!col}))} style={{...sec,cursor:"pointer",gap:5,display:"flex",alignItems:"center"}}><I d={P.chev} size={11} style={{}} c="var(--ui-text-3)"/><span style={{flex:1,transform:"none"}}>{g.name}</span>{col&&agg>0&&<span style={{background:"var(--ui-accent)",color:"var(--ui-on-accent)",borderRadius:999,fontSize:"var(--ui-fs-xs)",fontWeight:600,padding:"0 6px"}}>{agg}</span>}</div>
          {!col&&list.map(([k,c])=>Row(k,c))}</div>;})}
        {loose.length>0&&<div><div style={sec}>Sem grupo</div>{loose.map(([k,c])=>Row(k,c))}</div>}
        {hiddenG>0&&<div className="muted" style={{fontSize:"var(--ui-fs-xs)",padding:"6px 12px"}}>{hiddenG} grupo{hiddenG>1?"s":""} de outros departamentos oculto{hiddenG>1?"s":""}</div>}
        <div className="row" onClick={()=>setModal("group")} style={{gap:8,padding:"6px 12px",borderRadius:"var(--ui-r-sm)",cursor:"pointer",fontSize:"var(--ui-fs-sm)",fontWeight:500,color:"var(--ui-text-3)"}}><I d={P.plus} size={14}/>Novo grupo</div>
        <div style={sec}>Mensagens diretas</div>
        {Object.entries(chans).filter(([k,c])=>c.type==="dm").map(([k,c])=>Row(k,c))}
      </div>
      {huddle&&<div className="row" style={{margin:10,padding:"10px 12px",borderRadius:"var(--ui-r-sm)",background:"var(--ui-success-bg)",gap:8}}><span style={{width:8,height:8,borderRadius:999,background:"var(--ui-success)"}}></span><div style={{flex:1,minWidth:0}}><div style={{fontWeight:600,fontSize:"var(--ui-fs-xs)"}}>Huddle · #{chans[huddle.ch].label}</div><div className="muted" style={{fontSize:"var(--ui-fs-xs)"}}>Tu e Ana Reis</div></div><span title={huddle.muted?"Ligar micro":"Silenciar"} onClick={()=>setHuddle(h=>({...h,muted:!h.muted}))} style={{cursor:"pointer",fontWeight:600,fontSize:"var(--ui-fs-xs)",color:huddle.muted?"var(--ui-danger)":"var(--ui-text-2)"}}>{huddle.muted?"Mudo":"Mic"}</span><span onClick={()=>setHuddle(null)} style={{cursor:"pointer",display:"flex"}}><I d={P.x} size={14}/></span></div>}
      <div style={{borderTop:"1px solid var(--ui-divider)",padding:16,position:"relative",display:"flex",alignItems:"center",minHeight:73,boxSizing:"border-box"}}>
        <div className="row" style={{gap:8,cursor:"pointer",flex:1,minWidth:0}} onClick={()=>setStatusPop(v=>!v)}>{AV(chatMe,"sm","online")}<div style={{flex:1,minWidth:0}}><div style={{fontWeight:600,fontSize:"var(--ui-fs-sm)"}}>Tu</div><div className="muted" style={{fontSize:"var(--ui-fs-xs)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}}>{myStatus||"Definir estado"}</div></div><I d={P.smile} size={15} c="var(--ui-text-3)"/></div>
        {statusPop&&<div style={{...popStyle,bottom:"calc(100% + 6px)",left:14,right:14}}>{CSTATUS_PRESETS.map(s=><HoverRow key={s} onClick={()=>{setMyStatus(s);setStatusPop(false);}}>{s}</HoverRow>)}{myStatus&&<HoverRow onClick={()=>{setMyStatus(null);setStatusPop(false);}} style={{color:"var(--ui-danger)"}}>Limpar estado</HoverRow>}</div>}
      </div>
    </div>
    {view==="gsearch"?<div style={{padding:24,overflow:"auto"}}><div style={{fontWeight:600,fontSize:"var(--ui-fs-h3)",marginBottom:14}}>Resultados para «{gq}»</div>{(()=>{const res=Object.entries(chans).flatMap(([k,c])=>c.msgs.filter(m=>m.text.toLowerCase().includes(gq.toLowerCase())||m.from.toLowerCase().includes(gq.toLowerCase())).map(m=>({ch:k,m})));return res.length===0?<div className="muted" style={{fontSize:"var(--ui-fs-sm)"}}>Nenhuma mensagem encontrada em canais, DMs ou threads.</div>:res.map((r,i)=><div key={i} className="row" style={{gap:12,padding:"12px 4px",borderBottom:"1px solid var(--ui-divider)",cursor:"pointer",alignItems:"flex-start"}} onClick={()=>{setGq("");openCh(r.ch);}}>{AV(r.m.from,"sm")}<div style={{flex:1,minWidth:0}}><div className="row" style={{gap:8}}><span style={{fontWeight:600,fontSize:"var(--ui-fs-sm)"}}>{r.m.from===chatMe?"Tu":r.m.from}</span><span className="muted" style={{fontSize:"var(--ui-fs-xs)"}}>{chans[r.ch].type==="ch"?"#"+chans[r.ch].label:chans[r.ch].label} · {r.m.time}</span></div><div style={{fontSize:"var(--ui-fs-sm)",marginTop:4,color:"var(--ui-text-2)"}}>{rTxt(r.m.text)}</div></div></div>);})()}</div>
    :view==="activity"?<div style={{padding:24,overflow:"auto"}}><div style={{fontWeight:600,fontSize:"var(--ui-fs-h3)",marginBottom:14}}>Atividade</div>{activity.length===0&&<div className="muted" style={{fontSize:"var(--ui-fs-sm)"}}>Sem atividade nova.</div>}{activity.map((a,i)=><div key={i} className="row" style={{gap:12,padding:"12px 4px",borderBottom:"1px solid var(--ui-divider)",cursor:"pointer",alignItems:"flex-start"}} onClick={()=>openCh(a.ch)}>{AV(a.from,"sm")}<div style={{flex:1,minWidth:0}}><div className="row" style={{gap:8}}><UIPill tone={a.kind==="Menção"?"accent":a.kind==="Lembrete"?"warning":"neutral"}>{a.kind}</UIPill><span className="muted" style={{fontSize:"var(--ui-fs-xs)"}}>{chans[a.ch].type==="ch"?"#"+chans[a.ch].label:chans[a.ch].label}</span></div><div style={{fontSize:"var(--ui-fs-sm)",marginTop:4,color:"var(--ui-text-2)"}}>{rTxt(a.text)}</div></div></div>)}</div>
    :view==="saved"?<div style={{padding:24,overflow:"auto"}}><div style={{fontWeight:600,fontSize:"var(--ui-fs-h3)",marginBottom:14}}>Guardados</div>{saved.length===0&&<div className="muted" style={{fontSize:"var(--ui-fs-sm)"}}>Guarda mensagens com o marcador para as encontrares aqui.</div>}{saved.map((r,i)=>{const m=(chans[r.ch]||{msgs:[]}).msgs.find(x=>x.id===r.id);if(!m)return null;return <div key={i} className="row" style={{gap:12,padding:"12px 4px",borderBottom:"1px solid var(--ui-divider)",alignItems:"flex-start"}}>{AV(m.from,"sm")}<div style={{flex:1,minWidth:0,cursor:"pointer"}} onClick={()=>openCh(r.ch)}><div className="row" style={{gap:8}}><span style={{fontWeight:600,fontSize:"var(--ui-fs-sm)"}}>{m.from}</span><span className="muted" style={{fontSize:"var(--ui-fs-xs)"}}>{chans[r.ch].type==="ch"?"#"+chans[r.ch].label:chans[r.ch].label}</span></div><div style={{fontSize:"var(--ui-fs-sm)",marginTop:4,color:"var(--ui-text-2)"}}>{rTxt(m.text)}</div></div><span className="ico-btn" style={{width:30,height:30}} onClick={()=>toggleSave(r.ch,r.id)}><I d={P.x} size={13}/></span></div>;})}</div>
    :view==="sched"?<div style={{padding:24,overflow:"auto"}}><div style={{fontWeight:600,fontSize:"var(--ui-fs-h3)",marginBottom:14}}>Mensagens agendadas</div>{sched.length===0&&<div className="muted" style={{fontSize:"var(--ui-fs-sm)"}}>Agenda mensagens com o relógio no composer.</div>}{sched.map(it=><div key={it.id} className="row" style={{gap:12,padding:"12px 4px",borderBottom:"1px solid var(--ui-divider)",alignItems:"flex-start"}}><I d={P.clock} size={16} c="var(--ui-text-3)"/><div style={{flex:1,minWidth:0}}><div className="row" style={{gap:8}}><span style={{fontWeight:600,fontSize:"var(--ui-fs-sm)"}}>{chans[it.ch].type==="ch"?"#"+chans[it.ch].label:chans[it.ch].label}</span><span className="muted" style={{fontSize:"var(--ui-fs-xs)"}}>{it.when}</span></div><div style={{fontSize:"var(--ui-fs-sm)",marginTop:4,color:"var(--ui-text-2)"}}>{it.text}</div></div><UIButton size="sm" variant="outline" onClick={()=>sendNow(it)}>Enviar agora</UIButton><UIButton size="sm" variant="ghost" onClick={()=>setSched(s=>s.filter(x=>x.id!==it.id))}>Cancelar</UIButton></div>)}</div>
    :<div style={{display:"flex",flexDirection:"column",minHeight:0}}>
      <div className="row chat-hdr" style={{padding:"12px 16px",borderBottom:"1px solid var(--ui-divider)",gap:10}}>
        <div className="row" style={{gap:8,cursor:"pointer",minWidth:0}} onClick={()=>{setDetail(v=>!v);setThread(null);}}>
          {ch.type==="ch"?<I d={ch.private?P.lock:P.hash} size={16}/>:AV(ch.label,"sm",ch.online?"online":undefined)}
          <div style={{minWidth:0}}><div style={{fontWeight:600}}>{ch.label}{ch.muted&&<span className="muted" style={{fontWeight:500,fontSize:"var(--ui-fs-xs)"}}> · silenciado</span>}</div>{ch.topic&&<div className="muted" style={{fontSize:"var(--ui-fs-xs)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}}>{ch.topic}</div>}</div>
        </div>
        <div className="spring" style={{flex:1}}></div>
        <UITabs variant="pill" value={chTab} onChange={setChTab} items={[{value:"msgs",label:"Mensagens"},{value:"canvas",label:"Canvas"}]}/>
        <div style={{width:170}}><UIInput leading={<I d={P.search} size={14}/>} placeholder="Procurar" value={q} onChange={e=>setQ(e.target.value)}/></div>
        <div className="ico-btn" title="Iniciar huddle" onClick={()=>setHuddle({ch:cur,muted:false})} style={{width:34,height:34,color:huddle&&huddle.ch===cur?"var(--ui-success)":undefined}}><I d={P.head} size={15}/></div>
        <div className="ico-btn" title="Chamada de vídeo" onClick={()=>setCall({ch:cur,video:false,sharing:false,muted:false,transcript:[],showTr:true})} style={{width:34,height:34}}><I d={P.cam} size={15}/></div>
        <div className="ico-btn" title="Detalhes do canal" onClick={()=>{setDetail(v=>!v);setThread(null);}} style={{width:34,height:34}}><I d={P.info} size={15}/></div>
      </div>
      {chTab==="canvas"?<div style={{flex:1,display:"flex",flexDirection:"column",padding:24,gap:10}}>
        <div className="row"><span style={{fontWeight:600}}>Canvas de {ch.type==="ch"?"#"+ch.label:ch.label}</span><span className="muted" style={{fontSize:"var(--ui-fs-xs)"}}>Guardado automaticamente · visível a todos os membros</span></div>
        <textarea value={ch.canvas} onChange={e=>upd(cur,c=>({...c,canvas:e.target.value}))} placeholder="Um documento partilhado do canal: agendas, decisões, links importantes…" style={{flex:1,resize:"none",padding:16,border:"1px solid var(--ui-border)",borderRadius:"var(--ui-r-md)",background:"var(--ui-surface)",color:"var(--ui-text)",fontFamily:"var(--font-sans)",fontSize:"var(--ui-fs-body)",lineHeight:1.7,outline:"none"}}></textarea>
      </div>
      :<React.Fragment>
      <div style={{flex:1,overflow:"auto",padding:"16px 16px",display:"flex",flexDirection:"column",gap:2}}>
        {pinned.length>0&&<div className="row" style={{gap:8,padding:"8px 12px",borderRadius:"var(--ui-r-sm)",background:"var(--ui-surface-2)",marginBottom:8,fontSize:"var(--ui-fs-sm)"}}><I d={P.pin} size={13}/><span style={{fontWeight:600}}>{pinned.length} afixada{pinned.length>1?"s":""}:</span><span className="muted" style={{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}}>{pinned[0].text}</span></div>}
        <div className="row" style={{gap:12,margin:"4px 0 10px"}}><div style={{flex:1,height:1,background:"var(--ui-divider)"}}></div><span className="muted" style={{fontSize:"var(--ui-fs-xs)",fontWeight:600}}>Hoje</span><div style={{flex:1,height:1,background:"var(--ui-divider)"}}></div></div>
        {visible.length===0&&<div className="muted" style={{fontSize:"var(--ui-fs-sm)",padding:12}}>{q?"Sem resultados.":"Ainda não há mensagens. Escreve a primeira!"}</div>}
        {visible.map(m=><div key={m.id} onMouseEnter={()=>setHover(m.id)} onMouseLeave={()=>{setHover(null);setEmoPop(null);setFwdPop(null);}} style={{display:"flex",gap:12,padding:"7px 10px",borderRadius:"var(--ui-r-sm)",position:"relative",background:hover===m.id?"var(--ui-surface-2)":"transparent"}}>
          <span style={{cursor:"pointer"}} onClick={()=>setProfile(m.from)}>{AV(m.from,"md")}</span>
          <div style={{flex:1,minWidth:0}}>
            <div className="row" style={{gap:8}}><span style={{fontWeight:600,fontSize:"var(--ui-fs-sm)",cursor:"pointer"}} onClick={()=>setProfile(m.from)}>{m.from===chatMe?"Tu":m.from}</span><span className="muted" style={{fontSize:"var(--ui-fs-xs)"}}>{m.time}</span>{m.pinned&&<I d={P.pin} size={12} c="var(--ui-text-3)"/>}{isSaved(cur,m.id)&&<I d={P.bmark} size={12} c="var(--ui-accent)"/>}{m.edited&&<span className="muted" style={{fontSize:"var(--ui-fs-xs)"}}>(editado)</span>}</div>
            {editId===m.id?<div style={{marginTop:4,display:"flex",gap:8}}><input autoFocus value={editText} onChange={e=>setEditText(e.target.value)} onKeyDown={e=>{if(e.key==="Enter")saveEdit();if(e.key==="Escape")setEditId(null);}} style={{flex:1,padding:"8px 12px",border:"1px solid var(--ui-accent)",borderRadius:"var(--ui-r-sm)",background:"var(--ui-surface)",color:"var(--ui-text)",fontFamily:"var(--font-sans)",fontSize:"var(--ui-fs-sm)",outline:"none"}}/><UIButton size="sm" onClick={saveEdit}>Guardar</UIButton></div>
            :<div style={{fontSize:"var(--ui-fs-sm)",lineHeight:1.55,color:"var(--ui-text-2)"}}>{rTxt(m.text)}</div>}
            {transl[m.id]&&<div style={{marginTop:6,padding:"8px 12px",borderLeft:"2px solid var(--ui-accent)",background:"var(--ui-surface-2)",borderRadius:"0 8px 8px 0"}}><div className="muted" style={{fontSize:"var(--ui-fs-xs)",fontWeight:600,marginBottom:2}}><I d={P.globe} size={10}/> Tradução automática · EN</div><div style={{fontSize:"var(--ui-fs-sm)",lineHeight:1.5,color:"var(--ui-text-2)"}}>{m.tr||"(Tradução automática disponível quando ligada ao motor de tradução — mock.)"}</div></div>}
            {m.att&&<div className="row" style={{gap:8,marginTop:6}}><span className="row" style={{gap:8,padding:"6px 12px",border:"1px solid var(--ui-border)",borderRadius:"var(--ui-r-sm)",fontSize:"var(--ui-fs-sm)",fontWeight:500,cursor:"pointer"}}><I d={P.doc} size={14}/>{m.att}</span></div>}
            {(Object.keys(m.reacts).length>0||m.thread.length>0)&&<div className="row" style={{gap:8,marginTop:6,flexWrap:"wrap"}}>
              {Object.entries(m.reacts).map(([e,who])=><span key={e} onClick={()=>react(m.id,e)} title={who.join(", ")} style={{cursor:"pointer",padding:"3px 9px",borderRadius:999,fontSize:"var(--ui-fs-xs)",fontWeight:600,border:"1px solid "+(who.includes(chatMe)?"var(--ui-accent)":"var(--ui-border)"),background:who.includes(chatMe)?"var(--ui-accent-weak)":"var(--ui-surface)"}}>{e} {who.length}</span>)}
              {m.thread.length>0&&<span onClick={()=>{setThread(m.id);setDetail(false);}} style={{cursor:"pointer",fontSize:"var(--ui-fs-xs)",fontWeight:600,color:"var(--ui-accent)",padding:"3px 4px"}}>{m.thread.length} resposta{m.thread.length>1?"s":""} →</span>}
            </div>}
          </div>
          {hover===m.id&&editId!==m.id&&<div className="row" style={{position:"absolute",top:-14,right:10,gap:2,background:"var(--ui-surface)",border:"1px solid var(--ui-border)",borderRadius:"var(--ui-r-sm)",boxShadow:"var(--ui-elev-1)",padding:3}}>
            <span title="Reagir" onClick={()=>setEmoPop(emoPop===m.id?null:m.id)} style={{cursor:"pointer",padding:"4px 6px",display:"flex"}}><I d={P.smile} size={15}/></span>
            <span title="Thread" onClick={()=>{setThread(m.id);setDetail(false);}} style={{cursor:"pointer",padding:"4px 6px",display:"flex"}}><I d={P.chat} size={15}/></span>
            <span title="Reencaminhar" onClick={()=>setFwdPop(fwdPop===m.id?null:m.id)} style={{cursor:"pointer",padding:"4px 6px",display:"flex"}}><I d={P.fwd} size={15}/></span>
            <span title={transl[m.id]?"Ocultar tradução":"Traduzir"} onClick={()=>setTransl(s=>({...s,[m.id]:!s[m.id]}))} style={{cursor:"pointer",padding:"4px 6px",display:"flex",color:transl[m.id]?"var(--ui-accent)":undefined}}><I d={P.globe} size={15}/></span>
            <span title={isSaved(cur,m.id)?"Remover dos guardados":"Guardar"} onClick={()=>toggleSave(cur,m.id)} style={{cursor:"pointer",padding:"4px 6px",display:"flex",color:isSaved(cur,m.id)?"var(--ui-accent)":undefined}}><I d={P.bmark} size={15}/></span>
            <span title="Lembrar-me amanhã" onClick={()=>remind(m)} style={{cursor:"pointer",padding:"4px 6px",display:"flex"}}><I d={P.clock} size={15}/></span>
            <span title={m.pinned?"Desafixar":"Afixar"} onClick={()=>togglePin(m.id)} style={{cursor:"pointer",padding:"4px 6px",display:"flex"}}><I d={P.pin} size={15}/></span>
            {m.from===chatMe&&<span title="Editar" onClick={()=>{setEditId(m.id);setEditText(m.text);}} style={{cursor:"pointer",padding:"4px 6px",display:"flex"}}><I d={P.pencil} size={15}/></span>}
            {m.from===chatMe&&<span title="Eliminar" onClick={()=>delMsg(m.id)} style={{cursor:"pointer",padding:"4px 6px",display:"flex",color:"var(--ui-danger)"}}><I d={P.trash} size={15}/></span>}
            {emoPop===m.id&&<div className="row" style={{position:"absolute",top:"calc(100% + 4px)",right:0,gap:2,background:"var(--ui-surface)",border:"1px solid var(--ui-border)",borderRadius:999,boxShadow:"var(--ui-elev-2)",padding:"4px 8px",zIndex:30}}>{CEMOJI.map(e=><span key={e} onClick={()=>react(m.id,e)} style={{cursor:"pointer",fontSize:"var(--ui-fs-h2)",padding:"2px 4px"}}>{e}</span>)}</div>}
            {fwdPop===m.id&&<div style={{...popStyle,top:"calc(100% + 4px)",right:0,minWidth:200}}><div className="muted" style={{fontSize:"var(--ui-fs-xs)",fontWeight:600,textTransform:"uppercase",letterSpacing:"0.06em",padding:"6px 10px 2px"}}>Reencaminhar para</div>{Object.entries(chans).filter(([k,c])=>k!==cur&&!c.archived&&isMember(c)).slice(0,6).map(([k,c])=><HoverRow key={k} onClick={()=>forward(m,k)}><I d={c.type==="ch"?P.hash:P.users} size={13}/>{c.label}</HoverRow>)}</div>}
          </div>}
        </div>)}
        {cur==="produto"&&<div className="muted" style={{fontSize:"var(--ui-fs-xs)",padding:"8px 10px",fontStyle:"italic"}}>Ana Reis está a escrever…</div>}
      </div>
      <div style={{padding:16,borderTop:"1px solid var(--ui-divider)",position:"relative"}}>
        {!canPost?<UIBanner tone="info">Só administradores podem publicar em #{ch.label}. Podes reagir e responder em threads.</UIBanner>
        :<React.Fragment>
        {mSugg.length>0&&<div style={{...popStyle,bottom:"calc(100% + 4px)",left:14,minWidth:220}}>{mSugg.map(d=><HoverRow key={d} onClick={()=>setInput(input.replace(/@[\wÀ-ú]*$/,"@"+d+" "))}>{["canal","aqui"].includes(d)?<I d={P.hash} size={13}/>:AV(d,"sm")}{d}</HoverRow>)}</div>}
        {emoPop==="composer"&&<div className="row" style={{...popStyle,bottom:"calc(100% + 4px)",right:70,flexDirection:"row",borderRadius:999,padding:"4px 8px"}}>{CEMOJI.map(e=><span key={e} onClick={()=>{setInput(input+e+" ");setEmoPop(null);}} style={{cursor:"pointer",fontSize:"var(--ui-fs-h2)",padding:"2px 4px"}}>{e}</span>)}</div>}
        {schedPop&&<div style={{...popStyle,bottom:"calc(100% + 4px)",right:14,minWidth:190}}><div className="muted" style={{fontSize:"var(--ui-fs-xs)",fontWeight:600,textTransform:"uppercase",letterSpacing:"0.06em",padding:"6px 10px 2px"}}>Enviar mais tarde</div>{["Hoje às 18:00","Amanhã às 09:00","Segunda às 09:00"].map(w=><HoverRow key={w} onClick={()=>schedule(w)}><I d={P.clock} size={13}/>{w}</HoverRow>)}</div>}
        <div className="row" style={{gap:8}}>
          <div className="row" style={{gap:2}}>
            {[["*","B",700],["_","I",500],["`","{ }",600]].map(([mk,lb,w])=><span key={lb} title={mk==="*"?"Negrito":mk==="_"?"Itálico":"Código"} onClick={()=>setInput(input+(input&&!input.endsWith(" ")?" ":"")+mk+"texto"+mk+" ")} style={{cursor:"pointer",padding:"6px 8px",borderRadius:6,fontSize:"var(--ui-fs-xs)",fontWeight:w,fontStyle:mk==="_"?"italic":"normal",color:"var(--ui-text-3)",border:"1px solid var(--ui-border)"}}>{lb}</span>)}
          </div>
          <div style={{flex:1}}><UIInput placeholder={"Mensagem "+(ch.type==="ch"?"#"+ch.label:ch.label)} value={input} onChange={e=>setInput(e.target.value)} onKeyDown={e=>{if(e.key==="Enter"&&mSugg.length)setInput(input.replace(/@[\wÀ-ú]*$/,"@"+mSugg[0]+" "));else if(e.key==="Enter")send();}}/></div>
          <span className="ico-btn" title="Emoji" style={{width:38,height:38}} onClick={()=>setEmoPop(emoPop==="composer"?null:"composer")}><I d={P.smile} size={16}/></span>
          <span className="ico-btn" title="Enviar mais tarde" style={{width:38,height:38}} onClick={()=>setSchedPop(v=>!v)}><I d={P.clock} size={16}/></span>
          <UIButton style={{width:44,padding:0}} onClick={send} icon={<I d={P.send} size={16}/>}></UIButton>
        </div></React.Fragment>}
      </div></React.Fragment>}
    </div>}
    {!view&&(thread!==null&&tMsg?<div style={{borderLeft:"1px solid var(--ui-divider)",display:"flex",flexDirection:"column",minHeight:0}}>
      <div className="row" style={{padding:"12px 16px",borderBottom:"1px solid var(--ui-divider)"}}><span style={{fontWeight:600,flex:1}}>Thread</span><span className="ico-btn" style={{width:30,height:30}} onClick={()=>setThread(null)}><I d={P.x} size={14}/></span></div>
      <div style={{flex:1,overflow:"auto",padding:16,display:"flex",flexDirection:"column",gap:14}}>
        <div style={{display:"flex",gap:10}}>{AV(tMsg.from,"md")}<div><div className="row" style={{gap:8}}><span style={{fontWeight:600,fontSize:"var(--ui-fs-sm)"}}>{tMsg.from===chatMe?"Tu":tMsg.from}</span><span className="muted" style={{fontSize:"var(--ui-fs-xs)"}}>{tMsg.time}</span></div><div style={{fontSize:"var(--ui-fs-sm)",lineHeight:1.55,color:"var(--ui-text-2)"}}>{rTxt(tMsg.text)}</div></div></div>
        {tMsg.thread.length>0&&<div className="row" style={{gap:10}}><div style={{flex:1,height:1,background:"var(--ui-divider)"}}></div><span className="muted" style={{fontSize:"var(--ui-fs-xs)",fontWeight:600}}>{tMsg.thread.length} resposta{tMsg.thread.length>1?"s":""}</span><div style={{flex:1,height:1,background:"var(--ui-divider)"}}></div></div>}
        {tMsg.thread.map((r,i)=><div key={i} style={{display:"flex",gap:10}}>{AV(r.from,"sm")}<div><div className="row" style={{gap:8}}><span style={{fontWeight:600,fontSize:"var(--ui-fs-sm)"}}>{r.from===chatMe?"Tu":r.from}</span><span className="muted" style={{fontSize:"var(--ui-fs-xs)"}}>{r.time}</span></div><div style={{fontSize:"var(--ui-fs-sm)",lineHeight:1.55,color:"var(--ui-text-2)"}}>{rTxt(r.text)}</div></div></div>)}
      </div>
      <div className="row" style={{padding:12,borderTop:"1px solid var(--ui-divider)"}}><div style={{flex:1}}><UIInput placeholder="Responder na thread…" value={tInput} onChange={e=>setTInput(e.target.value)} onKeyDown={e=>{if(e.key==="Enter")sendThread();}}/></div><UIButton size="sm" style={{width:38,padding:0}} onClick={sendThread} icon={<I d={P.send} size={14}/>}></UIButton></div>
    </div>
    :detail?<div style={{borderLeft:"1px solid var(--ui-divider)",display:"flex",flexDirection:"column",minHeight:0}}>
      <div className="row" style={{padding:"12px 16px",borderBottom:"1px solid var(--ui-divider)"}}><span style={{fontWeight:600,flex:1}}>{ch.type==="ch"?"#"+ch.label:ch.label}</span><span className="ico-btn" style={{width:30,height:30}} onClick={()=>setDetail(false)}><I d={P.x} size={14}/></span></div>
      <div style={{padding:"10px 16px 0"}}><UITabs value={detailTab} onChange={setDetailTab} items={[{value:"sobre",label:"Sobre"},{value:"membros",label:"Membros"},{value:"pins",label:"Afixadas"},{value:"files",label:"Ficheiros"}]}/></div>
      <div style={{flex:1,overflow:"auto",padding:16,display:"flex",flexDirection:"column",gap:14}}>
        {detailTab==="sobre"&&<React.Fragment>
          <div><div className="muted" style={{fontSize:"var(--ui-fs-xs)",fontWeight:600,textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:4}}>Descrição</div><div style={{fontSize:"var(--ui-fs-sm)",lineHeight:1.5}}>{ch.desc||"Sem descrição."}</div></div>
          {ch.type==="ch"&&<div><div className="muted" style={{fontSize:"var(--ui-fs-xs)",fontWeight:600,textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:4}}>Publicação</div><div style={{fontSize:"var(--ui-fs-sm)"}}>{ch.post==="admins"?"Apenas administradores":"Todos os membros"}</div></div>}
          <UIToggle checked={!!ch.muted} onChange={v=>upd(cur,c=>({...c,muted:v}))} label="Silenciar notificações"/>
          {ch.type==="ch"&&<div className="row" style={{gap:8,marginTop:"auto"}}><UIButton size="sm" variant="outline" onClick={()=>{upd(cur,c=>({...c,members:{...c.members,people:c.members.people.filter(p=>p!==chatMe)}}));openCh("geral");}}>Sair do canal</UIButton><UIButton size="sm" variant="ghost" onClick={()=>{upd(cur,c=>({...c,archived:true}));openCh("geral");}} style={{color:"var(--ui-danger)"}}>Arquivar</UIButton></div>}
        </React.Fragment>}
        {detailTab==="membros"&&<React.Fragment>
          {ch.members.depts.length>0&&<div><div className="muted" style={{fontSize:"var(--ui-fs-xs)",fontWeight:600,textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:6}}>Departamentos</div><div className="row" style={{gap:8,flexWrap:"wrap"}}>{ch.members.depts.map(d=><UIPill key={d} tone="neutral">{d} · {(CDEPTS[d]||[]).length}</UIPill>)}</div></div>}
          <div><div className="muted" style={{fontSize:"var(--ui-fs-xs)",fontWeight:600,textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:6}}>Pessoas</div>{[...new Set([...ch.members.people,...ch.members.depts.flatMap(d=>CDEPTS[d]||[])])].map(p=><div key={p} className="row" style={{gap:10,padding:"6px 0",cursor:"pointer"}} onClick={()=>setProfile(p)}>{AV(p,"sm",CSTATUS[p]?undefined:"online")}<span style={{fontSize:"var(--ui-fs-sm)",fontWeight:500,flex:1}}>{p===chatMe?"Tu":p}</span>{CSTATUS[p]&&<span className="muted" style={{fontSize:"var(--ui-fs-xs)"}}>{CSTATUS[p]}</span>}{chatAdmins.includes(p)&&<UIPill tone="neutral">admin</UIPill>}</div>)}</div>
        </React.Fragment>}
        {detailTab==="pins"&&(pinned.length===0?<div className="muted" style={{fontSize:"var(--ui-fs-sm)"}}>Sem mensagens afixadas.</div>:pinned.map(m=><div key={m.id} style={{border:"1px solid var(--ui-border)",borderRadius:"var(--ui-r-sm)",padding:12}}><div className="row" style={{gap:8}}><span style={{fontWeight:600,fontSize:"var(--ui-fs-sm)"}}>{m.from}</span><span className="muted" style={{fontSize:"var(--ui-fs-xs)"}}>{m.time}</span></div><div style={{fontSize:"var(--ui-fs-sm)",marginTop:4,color:"var(--ui-text-2)"}}>{rTxt(m.text)}</div></div>))}
        {detailTab==="files"&&(files.length===0?<div className="muted" style={{fontSize:"var(--ui-fs-sm)"}}>Sem ficheiros partilhados.</div>:files.map(m=><div key={m.id} className="row" style={{gap:10,padding:"8px 0"}}><I d={P.doc} size={16} c="var(--ui-text-3)"/><div style={{flex:1}}><div style={{fontSize:"var(--ui-fs-sm)",fontWeight:600}}>{m.att}</div><div className="muted" style={{fontSize:"var(--ui-fs-xs)"}}>{m.from} · {m.time}</div></div></div>))}
      </div>
    </div>:null)}
  </div></UICard>
  {call&&<div style={{position:"fixed",inset:0,background:"rgba(10,14,16,0.92)",zIndex:100,display:"flex",flexDirection:"column"}}>
    <div className="row" style={{padding:"16px 24px",gap:10}}><span style={{width:9,height:9,borderRadius:999,background:"var(--ui-success)"}}></span><span style={{color:"#fff",fontWeight:600}}>Chamada · {chans[call.ch].type==="ch"?"#"+chans[call.ch].label:chans[call.ch].label}</span><span style={{color:"rgba(255,255,255,0.55)",fontSize:"var(--ui-fs-sm)"}}>3 participantes</span><div style={{flex:1}}></div>
      <span onClick={()=>setCall(c=>({...c,showTr:!c.showTr}))} style={{cursor:"pointer",color:call.showTr?"#fff":"rgba(255,255,255,0.55)",fontSize:"var(--ui-fs-sm)",fontWeight:600}}>Transcrição</span></div>
    <div style={{flex:1,display:"grid",gridTemplateColumns:call.showTr?"minmax(0,1fr) minmax(0,clamp(240px,22cqi,320px))":"minmax(0,1fr)",gap:16,padding:"0 clamp(12px,2cqi,24px) 16px",minHeight:0}}>
      <div style={{display:"grid",gridTemplateColumns:call.sharing?"minmax(0,1fr)":"repeat(auto-fit,minmax(200px,1fr))",gridTemplateRows:call.sharing?"minmax(0,1fr) 120px":undefined,gap:12,minHeight:0}}>
        {call.sharing&&<div style={{background:"#000",borderRadius:16,overflow:"hidden",position:"relative"}}><video ref={shareRef} autoPlay muted style={{width:"100%",height:"100%",objectFit:"contain"}}></video><span style={{position:"absolute",top:10,left:12,color:"#fff",fontSize:"var(--ui-fs-xs)",fontWeight:600,background:"rgba(0,0,0,0.5)",borderRadius:6,padding:"3px 8px"}}>A partilhar o teu ecrã</span></div>}
        <div style={{display:call.sharing?"flex":"contents",gap:12}}>
          <div style={{background:"#1c2427",borderRadius:16,display:"flex",alignItems:"center",justifyContent:"center",position:"relative",overflow:"hidden",minHeight:call.sharing?110:180,flex:call.sharing?1:undefined}}>
            {call.video?<video ref={camRef} autoPlay muted style={{width:"100%",height:"100%",objectFit:"cover",transform:"scaleX(-1)"}}></video>:<UIAvatar name={chatMe} size="xl"/>}
            <span style={{position:"absolute",bottom:10,left:12,color:"#fff",fontSize:"var(--ui-fs-xs)",fontWeight:600,background:"rgba(0,0,0,0.5)",borderRadius:6,padding:"3px 8px"}}>Tu{call.muted?" · mudo":""}</span></div>
          {["Ana Reis","Bruno Costa"].map(n=><div key={n} style={{background:"#1c2427",borderRadius:16,display:"flex",alignItems:"center",justifyContent:"center",position:"relative",minHeight:call.sharing?110:180,flex:call.sharing?1:undefined}}><UIAvatar name={n} size="xl"/><span style={{position:"absolute",bottom:10,left:12,color:"#fff",fontSize:"var(--ui-fs-xs)",fontWeight:600,background:"rgba(0,0,0,0.5)",borderRadius:6,padding:"3px 8px"}}>{n}</span></div>)}
        </div>
      </div>
      {call.showTr&&<div style={{background:"rgba(255,255,255,0.06)",borderRadius:16,display:"flex",flexDirection:"column",minHeight:0}}>
        <div style={{padding:"12px 16px",color:"#fff",fontWeight:600,fontSize:"var(--ui-fs-sm)",borderBottom:"1px solid rgba(255,255,255,0.1)"}}>Transcrição em direto</div>
        <div style={{flex:1,overflow:"auto",padding:16,display:"flex",flexDirection:"column",gap:10}}>{call.transcript.length===0&&<span style={{color:"rgba(255,255,255,0.45)",fontSize:"var(--ui-fs-sm)"}}>A transcrição começa quando alguém falar…</span>}{call.transcript.map((l,i)=><div key={i}><span style={{color:"rgba(255,255,255,0.55)",fontSize:"var(--ui-fs-xs)",fontWeight:600}}>{l[0]}</span><div style={{color:"rgba(255,255,255,0.85)",fontSize:"var(--ui-fs-sm)",lineHeight:1.5}}>{l[1]}</div></div>)}</div>
      </div>}
    </div>
    {call.err&&<div style={{textAlign:"center",color:"#ffb4a0",fontSize:"var(--ui-fs-sm)",paddingBottom:6}}>{call.err}</div>}
    <div className="row" style={{justifyContent:"center",gap:12,padding:"0 0 22px"}}>
      {[[call.muted?"Mudo":"Mic",P.mic,()=>setCall(c=>({...c,muted:!c.muted})),call.muted],[call.video?"Câmara on":"Câmara",P.cam,toggleCam,call.video],[call.sharing?"Parar partilha":"Partilhar ecrã",P.mon,toggleShare,call.sharing]].map(([lb,ic,fn,on])=><div key={lb} onClick={fn} title={lb} style={{width:52,height:52,borderRadius:999,background:on?"var(--ui-accent, #f27101)":"rgba(255,255,255,0.12)",color:"#fff",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer"}}><I d={ic} size={20}/></div>)}
      <div onClick={endCall} title="Terminar" style={{width:52,height:52,borderRadius:999,background:"#e5484d",color:"#fff",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer"}}><I d={P.x} size={20}/></div>
    </div>
  </div>}
  <UIModal open={modal==="channel"} onClose={()=>setModal(null)} title="Novo canal" width={560}
    footer={<div className="row" style={{gap:10,justifyContent:"flex-end"}}><UIButton variant="ghost" onClick={()=>setModal(null)}>Cancelar</UIButton><UIButton disabled={!fName.trim()} onClick={createCh}>Criar canal</UIButton></div>}>
    <div style={{display:"flex",flexDirection:"column",gap:14}}>
      <UIInput label="Nome" placeholder="ex. onboarding-clientes" value={fName} onChange={e=>setFName(e.target.value)}/>
      <UIInput label="Descrição" placeholder="Para que serve este canal?" value={fDesc} onChange={e=>setFDesc(e.target.value)}/>
      <div className="grid g2" style={{display:"grid",gap:12}}>
        <UISelect label="Grupo" value={fGroup} onChange={e=>setFGroup(e.target.value)} options={visGroups.map(g=>({value:g.id,label:g.name}))}/>
        <UISelect label="Quem pode publicar" value={fPost} onChange={e=>setFPost(e.target.value)} options={[{value:"all",label:"Todos os membros"},{value:"admins",label:"Só administradores"}]}/>
      </div>
      <UIToggle checked={fPriv} onChange={setFPriv} label="Canal privado — só visível a quem for convidado"/>
      <div><div style={{fontSize:"var(--ui-fs-sm)",fontWeight:600,marginBottom:6}}>Membros — pessoas ou departamentos inteiros</div>
        <div style={{display:"flex",flexWrap:"wrap",gap:8,padding:"8px 10px",border:"1px solid var(--ui-border)",borderRadius:"var(--ui-r-sm)"}}>
          {fMembers.map(mb=><span key={mb.v} className="row" style={{gap:8,padding:"4px 10px",borderRadius:999,background:"var(--ui-surface-2)",fontSize:"var(--ui-fs-sm)",fontWeight:500}}><I d={mb.t==="d"?P.building:P.users} size={12}/>{mb.v}{mb.t==="d"&&<span className="muted">· {(CDEPTS[mb.v]||[]).length}</span>}<span style={{cursor:"pointer",color:"var(--ui-text-3)"}} onClick={()=>setFMembers(ms=>ms.filter(x=>x.v!==mb.v))}>×</span></span>)}
          <input style={{flex:1,minWidth:140,border:"none",outline:"none",background:"transparent",color:"var(--ui-text)",fontFamily:"var(--font-sans)",fontSize:"var(--ui-fs-body)"}} placeholder={fMembers.length?"":"Nome ou departamento…"} value={fMemQ} onChange={e=>setFMemQ(e.target.value)} onKeyDown={e=>{if(e.key==="Enter"&&memSugg.length)addMember(memSugg[0]);}}/>
        </div>
        {memSugg.length>0&&<div style={{border:"1px solid var(--ui-border)",borderRadius:"var(--ui-r-sm)",marginTop:4,overflow:"hidden",boxShadow:"var(--ui-elev-1)"}}>{memSugg.map(s=><HoverRow key={s.t+s.v} onClick={()=>addMember(s)} style={{borderRadius:0}}><I d={s.t==="d"?P.building:P.users} size={14}/><span style={{fontWeight:600}}>{s.v}</span>{s.t==="d"&&<span className="muted">departamento · {(CDEPTS[s.v]||[]).length} pessoas</span>}</HoverRow>)}</div>}
      </div>
    </div>
  </UIModal>
  <UIModal open={modal==="group"} onClose={()=>setModal(null)} title="Novo grupo de canais" width={480}
    footer={<div className="row" style={{gap:10,justifyContent:"flex-end"}}><UIButton variant="ghost" onClick={()=>setModal(null)}>Cancelar</UIButton><UIButton disabled={!gName.trim()||(!gAll&&!gAud.length)} onClick={createGrp}>Criar grupo</UIButton></div>}>
    <div style={{display:"flex",flexDirection:"column",gap:14}}>
      <UIInput label="Nome do grupo" placeholder="ex. Operações" value={gName} onChange={e=>setGName(e.target.value)}/>
      <UIToggle checked={gAll} onChange={setGAll} label="Visível a toda a empresa"/>
      {!gAll&&<div><div style={{fontSize:"var(--ui-fs-sm)",fontWeight:600,marginBottom:6}}>Visível aos departamentos</div><div className="row" style={{gap:8,flexWrap:"wrap"}}>{Object.keys(CDEPTS).map(d=><span key={d} onClick={()=>setGAud(a=>a.includes(d)?a.filter(x=>x!==d):[...a,d])} style={{cursor:"pointer",padding:"6px 14px",borderRadius:999,fontSize:"var(--ui-fs-sm)",fontWeight:600,border:"1px solid "+(gAud.includes(d)?"var(--ui-accent)":"var(--ui-border)"),background:gAud.includes(d)?"var(--ui-accent-weak)":"transparent"}}>{d}</span>)}</div></div>}
      <UIBanner tone="info">Cada pessoa vê apenas os grupos do seu departamento — a sidebar mantém-se organizada mesmo com muitos canais.</UIBanner>
    </div>
  </UIModal>
  <UIModal open={modal==="browse"} onClose={()=>setModal(null)} title="Explorar canais" width={520}>
    <div style={{display:"flex",flexDirection:"column"}}>{Object.entries(chans).filter(([k,c])=>c.type==="ch"&&!c.private).map(([k,c])=><div key={k} className="row" style={{gap:10,padding:"10px 0",borderBottom:"1px solid var(--ui-divider)"}}><I d={P.hash} size={15}/><div style={{flex:1,minWidth:0}}><div style={{fontWeight:600,fontSize:"var(--ui-fs-sm)"}}>{c.label}{c.archived&&<span className="muted" style={{fontWeight:500}}> · arquivado</span>}</div><div className="muted" style={{fontSize:"var(--ui-fs-xs)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}}>{c.desc||"Sem descrição"}</div></div>
      {c.archived?<UIButton size="sm" variant="outline" onClick={()=>upd(k,x=>({...x,archived:false}))}>Restaurar</UIButton>
      :isMember(c)?<UIButton size="sm" variant="ghost" onClick={()=>upd(k,x=>({...x,members:{...x.members,people:x.members.people.filter(p=>p!==chatMe),depts:x.members.depts.filter(d=>!(CDEPTS[d]||[]).includes(chatMe))}}))}>Sair</UIButton>
      :<UIButton size="sm" variant="outline" onClick={()=>{upd(k,x=>({...x,members:{...x.members,people:[...x.members.people,chatMe]}}));}}>Entrar</UIButton>}</div>)}</div>
  </UIModal>
  <UIModal open={!!profile} onClose={()=>setProfile(null)} title="Perfil" width={380}>
    {profile&&<div style={{display:"flex",flexDirection:"column",alignItems:"center",gap:10,padding:"8px 0"}}>
      <UIAvatar name={profile} size="xl" status={profile===chatMe||["Ana Reis","Tomás Jervell"].includes(profile)?"online":undefined}/>
      <div style={{fontWeight:600,fontSize:"var(--ui-fs-h3)"}}>{profile===chatMe?"Tu":profile}</div>
      <div className="muted" style={{fontSize:"var(--ui-fs-sm)"}}>{deptOf(profile)||"—"}{chatAdmins.includes(profile)?" · admin":""}</div>
      {(profile===chatMe?myStatus:CSTATUS[profile])&&<UIPill tone="neutral">{profile===chatMe?myStatus:CSTATUS[profile]}</UIPill>}
      {profile!==chatMe&&<UIButton size="sm" onClick={()=>{const k="dm:"+profile;if(!chans[k])setChans(cs=>({...cs,[k]:{type:"dm",label:profile,online:true,muted:false,archived:false,unread:0,canvas:"",members:{people:[chatMe,profile],depts:[]},msgs:[]}}));setProfile(null);openCh(k);}}>Enviar mensagem</UIButton>}
    </div>}
  </UIModal>
  </React.Fragment>;};
