/*
 * dashboard-v2/office.js — Al Moasis Unified Company Floor (v0.9)
 *
 * ONE open-plan office floor (not separate cards). Each department is a zone on
 * the same floor, represented by a SINGLE pixel avatar (the department lead),
 * with a live count of its agents + a speech bubble of what they're doing. The
 * Founder sits at the executive strip up top. Al Moasis brand palette (emerald).
 * Click a department to see its agents + their work. When a council convenes, a
 * meeting room takes over the top of the floor.
 *
 * Data: /api/subagents + /api/council/active. Public API unchanged.
 */
(() => {
  'use strict';
  const HOST_ID = 'office-canvas';
  const api = () => (window.__moasis && window.__moasis.api) || null;
  const workers = new Map();
  let pollTimer=null, founderState='idle', founderResetTimer=null, openDept=null, mounted=false, councilMeeting=null;

  // ── Al Moasis brand palette (emerald) + soft pixel floor ─────────────────
  const C = {
    brand:'#10B981', brandDk:'#059669', mint:'#ECFDF5',
    floor:'#F6FAF8', surface:'#FFFFFF', line:'#D7E7DE', wall:'#E8F2EC',
    ink:'#0E1B14', muted:'#5E7468', shadow:'rgba(16,80,50,.14)', grid:'rgba(16,185,129,.06)',
    amber:'#D9A441', rose:'#D06B6B', slate:'#5E7468',
  };

  const DEPARTMENTS = [
    { key:'marketing', name:'التسويق', icon:'📣', accent:'#A855F7', kw:['تسويق','marketing','seo','سيو','محتوى','content','اعلان','إعلان','ads','حملة','social','انستقرام','instagram','tiktok','تواصل','براند','brand'] },
    { key:'sales', name:'المبيعات', icon:'🤝', accent:'#F59E0B', kw:['مبيعات','sales','عميل','عملاء','lead','صفقة','deal','عرض سعر','quote','متابعة','followup','crm','تفاوض'] },
    { key:'programming', name:'البرمجة', icon:'💻', accent:'#3B82F6', kw:['برمجة','كود','code','تطوير','develop','موقع','website','app','تطبيق','api','backend','frontend','bug','deploy','نشر'] },
    { key:'research', name:'البحث', icon:'🔬', accent:'#14B8A6', kw:['بحث','research','تحليل','analy','دراسة','سوق','market','منافس','competitor','إحصاء','data','تقرير','report'] },
    { key:'finance', name:'المالية', icon:'📊', accent:'#0EA5E9', kw:['مالية','finance','فاتورة','invoice','محاسب','account','zatca','ضريبة','tax','ميزانية','budget','تكلفة','cost','price','تسعير'] },
    { key:'design', name:'التصميم', icon:'🎨', accent:'#EC4899', kw:['تصميم','design','شعار','logo','جرافيك','graphic','ui','ux','هوية','واجهة','بنر','banner','تصوير','photo'] },
    { key:'operations', name:'العمليات', icon:'⚙️', accent:'#64748B', kw:[] },
  ];
  function deptFor(task){ const t=String(task||'').toLowerCase(); for(const d of DEPARTMENTS){ if(d.kw.length&&d.kw.some(k=>t.includes(k))) return d; } return DEPARTMENTS[DEPARTMENTS.length-1]; }

  const TOOL_LABEL={ web_search:'يبحث في الويب', web_fetch:'يقرأ صفحة', research_topic:'يجمع معلومات', write_file:'يكتب ملفاً', read_file:'يقرأ ملفاً', create_excel:'يحضّر Excel', create_pdf_report:'يحضّر PDF', create_presentation:'يحضّر عرضاً', exec_command:'ينفّذ أمراً', send_email:'يرسل بريداً', spawn_subagent:'يفوّض وكيلاً', remember_fact:'يحفظ معلومة', create_goal:'يضع هدفاً', record_insight:'يدوّن فكرة', convene_council:'يعقد مجلساً' };
  const friendlyTool=(n)=>TOOL_LABEL[n]||n||'يعمل';
  function hashId(id){ let h=0; const s=String(id); for(let i=0;i<s.length;i++) h=((h<<5)-h+s.charCodeAt(i))|0; return Math.abs(h); }
  function escHtml(s){ return String(s??'').replace(/[&<>"]/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c])); }

  // ── Pixel sprites (crisp SVG, no external assets) ────────────────────────
  const PERSON=['  HHHH  ',' HHHHHH ',' HSSSSH ',' SSSSSS ',' SEESES ','  SSSS  ',' CCCCCC ','CCCCCCCC',' CCCCCC ',' PP  PP ',' P    P '];
  function pixelPerson(shirt,scale){ const COL={H:'#3C2E26',S:'#E7B98C',E:'#2A2018',C:shirt,P:'#46505E'}; let r='';
    for(let y=0;y<PERSON.length;y++){const row=PERSON[y];for(let x=0;x<row.length;x++){const ch=row[x];if(ch===' ')continue;r+=`<rect x="${x}" y="${y}" width="1" height="1" fill="${COL[ch]||'#000'}"/>`;}}
    const w=Math.round(8*(scale||4.4)), h=Math.round(11*(scale||4.4));
    return `<svg viewBox="0 0 8 11" width="${w}" height="${h}" shape-rendering="crispEdges" style="image-rendering:pixelated;display:block;">${r}</svg>`; }
  function deskSprite(){ return `<svg viewBox="0 0 16 12" width="50" height="38" shape-rendering="crispEdges" style="image-rendering:pixelated;"><rect x="1" y="4" width="9" height="1" fill="#3C7AA0"/><rect x="2" y="2" width="7" height="2" fill="#5AA0C8"/><rect x="0" y="6" width="11" height="2" fill="#A98C5C"/><rect x="1" y="8" width="1" height="3" fill="#8B7045"/><rect x="9" y="8" width="1" height="3" fill="#8B7045"/></svg>`; }
  function plantSprite(){ return `<svg viewBox="0 0 8 12" width="24" height="34" shape-rendering="crispEdges" style="image-rendering:pixelated;"><rect x="2" y="1" width="4" height="4" fill="#10B981"/><rect x="1" y="2" width="6" height="2" fill="#34D399"/><rect x="3" y="5" width="2" height="3" fill="#0E8A66"/><rect x="2" y="8" width="4" height="3" fill="#B5723E"/></svg>`; }
  // Big leafy plant in a pot (lounge accent).
  function bigPlantSprite(){ return `<svg viewBox="0 0 10 16" width="30" height="48" shape-rendering="crispEdges" style="image-rendering:pixelated;"><rect x="3" y="0" width="4" height="3" fill="#10B981"/><rect x="1" y="2" width="3" height="3" fill="#34D399"/><rect x="6" y="2" width="3" height="3" fill="#34D399"/><rect x="2" y="4" width="6" height="3" fill="#0E8A66"/><rect x="4" y="7" width="2" height="4" fill="#0B6B4F"/><rect x="2" y="11" width="6" height="4" fill="#C8773E"/><rect x="2" y="11" width="6" height="1" fill="#E0905A"/></svg>`; }
  // Two-seat couch.
  function couchSprite(){ return `<svg viewBox="0 0 22 11" width="74" height="37" shape-rendering="crispEdges" style="image-rendering:pixelated;"><rect x="0" y="3" width="2" height="6" fill="#7E8C9E"/><rect x="20" y="3" width="2" height="6" fill="#7E8C9E"/><rect x="2" y="2" width="18" height="3" fill="#8FA0B2"/><rect x="2" y="5" width="8" height="3" fill="#A7B6C6"/><rect x="11" y="5" width="9" height="3" fill="#A7B6C6"/><rect x="2" y="8" width="18" height="1" fill="#6E7C8E"/><rect x="3" y="9" width="1" height="2" fill="#4A5562"/><rect x="18" y="9" width="1" height="2" fill="#4A5562"/></svg>`; }
  // Water dispenser (blue bottle + white cooler).
  function waterSprite(){ return `<svg viewBox="0 0 6 15" width="22" height="55" shape-rendering="crispEdges" style="image-rendering:pixelated;"><rect x="1" y="0" width="4" height="5" fill="#7FC4E8"/><rect x="1" y="0" width="4" height="1" fill="#A9DBF2"/><rect x="2" y="5" width="2" height="1" fill="#5A93B0"/><rect x="0" y="6" width="6" height="8" fill="#EDF2F5"/><rect x="0" y="6" width="6" height="1" fill="#CFD8DE"/><rect x="2" y="9" width="2" height="2" fill="#5AA0C8"/><rect x="0" y="13" width="6" height="2" fill="#C2CDD4"/></svg>`; }
  // Wall-mounted AC unit.
  function acSprite(){ return `<svg viewBox="0 0 16 6" width="58" height="22" shape-rendering="crispEdges" style="image-rendering:pixelated;"><rect x="0" y="0" width="16" height="4" fill="#F2F5F7"/><rect x="0" y="0" width="16" height="1" fill="#FFFFFF"/><rect x="1" y="4" width="14" height="1" fill="#CBD5DA"/><rect x="2" y="3" width="12" height="1" fill="#AEBCC4"/><rect x="13" y="1" width="2" height="1" fill="#10B981"/></svg>`; }
  // Floor rug.
  function rugSprite(){ return `<svg viewBox="0 0 20 10" width="120" height="60" shape-rendering="crispEdges" style="image-rendering:pixelated;opacity:.7;"><rect x="0" y="0" width="20" height="10" fill="#E3D8C4"/><rect x="1" y="1" width="18" height="8" fill="#ECE3D2"/><rect x="2" y="2" width="16" height="6" fill="#E3D8C4"/><rect x="4" y="3" width="12" height="4" fill="#D7C9AE"/></svg>`; }

  function injectAnimStyles(){
    if(document.getElementById('moasis-office-anims'))return; const s=document.createElement('style'); s.id='moasis-office-anims';
    s.textContent=`
      @keyframes moasis-pulse{0%,100%{transform:scale(.8);opacity:.5}50%{transform:scale(1.15);opacity:1}}
      @keyframes mo-stroll{0%{transform:translate(0,0)}25%{transform:translate(10px,2px)}50%{transform:translate(14px,-3px)}75%{transform:translate(5px,4px)}100%{transform:translate(0,0)}}
      @keyframes mo-step{0%,100%{transform:translateY(0) rotate(-1.5deg)}50%{transform:translateY(-2px) rotate(1.5deg)}}
      @keyframes mo-bubble{0%{opacity:0;transform:translate(-50%,3px)}100%{opacity:1;transform:translate(-50%,0)}}
      @keyframes mo-council-in{0%{opacity:0;transform:translate(-50%,90px) scale(.8)}100%{opacity:1;transform:translate(-50%,-50%) scale(1)}}
      .moasis-pulse{animation:moasis-pulse 1.5s ease-in-out infinite;}
      .mo-step{animation:mo-step .5s steps(2,end) infinite;}
      .mo-zone{cursor:pointer;transition:background .15s;}
      .mo-zone:hover{background:rgba(16,185,129,.06);}
      .mo-pix{font-family:'Courier New',ui-monospace,monospace;letter-spacing:.03em;}
    `; document.head.appendChild(s);
  }

  function ensureScaffold(){
    if(mounted)return; const host=document.getElementById(HOST_ID); if(!host)return; injectAnimStyles();
    host.setAttribute('style',`background:${C.floor};border:1px solid ${C.line};border-radius:14px;overflow:hidden;display:flex;flex-direction:column;height:100%;min-height:540px;`);
    host.innerHTML=`
      <div class="mo-pix" style="display:flex;align-items:center;justify-content:space-between;padding:13px 20px;border-bottom:1px solid ${C.line};background:${C.surface};flex:0 0 auto;">
        <div style="display:flex;align-items:center;gap:9px;">
          <span style="width:18px;height:18px;border-radius:5px;background:linear-gradient(135deg,${C.brand},${C.brandDk});display:inline-block;"></span>
          <div style="font-size:14px;font-weight:700;color:${C.ink};">شركة المؤسس</div>
          <div style="font-size:11px;color:${C.muted};">مكتب واحد · كل الأقسام</div>
        </div>
        <div style="display:inline-flex;align-items:center;gap:7px;font-size:11px;color:${C.brandDk};background:${C.mint};border:1px solid ${C.line};border-radius:999px;padding:4px 11px;">
          <span class="moasis-pulse" style="width:7px;height:7px;border-radius:50%;background:${C.brand};display:inline-block;"></span><span data-bind="office-count">جاهز</span>
        </div>
      </div>
      <div style="flex:1 1 0;display:flex;min-height:0;overflow:hidden;">
        <div data-bind="office-floor" style="flex:1 1 0;min-width:0;padding:16px;overflow-y:auto;"></div>
        <aside data-bind="office-panel" class="mo-pix" style="width:0;transition:width .2s;background:${C.surface};border-inline-start:1px solid ${C.line};display:flex;flex-direction:column;overflow:hidden;flex:0 0 auto;">
          <div style="padding:16px 18px;border-bottom:1px solid ${C.line};display:flex;justify-content:space-between;align-items:start;gap:10px;">
            <div style="min-width:0;flex:1;"><div style="font-size:13px;font-weight:700;color:${C.ink};" data-bind="panel-title">—</div><div style="font-size:11px;color:${C.muted};margin-top:3px;" data-bind="panel-sub">—</div></div>
            <button type="button" data-action="office-close" style="background:none;border:none;cursor:pointer;color:${C.muted};font-size:20px;line-height:1;padding:0 4px;">×</button>
          </div>
          <div data-bind="panel-body" style="flex:1;overflow-y:auto;padding:12px 18px 18px;font-size:12px;color:${C.ink};">—</div>
        </aside>
      </div>`;
    host.querySelector('[data-action="office-close"]').addEventListener('click', closePanel);
    mounted=true;
  }

  // Aggregate workers per department → one lead avatar each.
  function deptStats(){
    const active=Array.from(workers.entries()).filter(([,w])=>w.status!=='completed'||(Date.now()-(w.completedAt||w.since||0))<2*60_000);
    const map=new Map(DEPARTMENTS.map(d=>[d.key,{count:0,running:0,activity:'',agents:[]}]));
    for(const [id,w] of active){ const k=deptFor(w.task).key; const s=map.get(k); s.count++; if(w.status==='running'){ s.running++; if(!s.activity) s.activity=w.lastStep||friendlyTool(w.lastTool); } s.agents.push([id,w]); }
    return map;
  }

  function leadAvatar(dept,stats){
    const running=stats.running>0; const h=hashId(dept.key);
    const stroll=running?`animation:mo-stroll ${8+(h%5)}s ease-in-out infinite;`:'';
    const dim=stats.count===0?'opacity:.4;filter:grayscale(.5);':'';
    const bubble=running&&stats.activity?`<div class="mo-pix" style="position:absolute;bottom:54px;left:50%;transform:translateX(-50%);white-space:nowrap;max-width:150px;overflow:hidden;text-overflow:ellipsis;background:${C.surface};border:1px solid ${C.line};color:${C.ink};font-size:9.5px;padding:3px 8px;border-radius:9px;box-shadow:0 2px 6px ${C.shadow};animation:mo-bubble .25s ease both;pointer-events:none;">${escHtml(String(stats.activity).slice(0,32))}</div>`:'';
    return `<div style="position:relative;${stroll}"><div class="${running?'mo-step':''}" style="position:relative;${dim}">${bubble}${pixelPerson(dept.accent,4.6)}</div></div>`;
  }

  function zoneHtml(dept,stats){
    const badge=stats.count>0?`<span style="display:inline-flex;align-items:center;gap:4px;font-size:10px;color:${C.brandDk};background:${C.mint};border-radius:999px;padding:1px 7px;">${stats.running>0?`<span class="moasis-pulse" style="width:5px;height:5px;border-radius:50%;background:${C.brand};display:inline-block;"></span>`:''}${stats.count}</span>`:`<span style="font-size:10px;color:${C.muted};">متفرّغ</span>`;
    return `<div class="mo-zone" data-dept="${dept.key}" style="position:relative;min-height:160px;border-inline-start:1px dashed ${C.line};border-top:1px dashed ${C.line};display:flex;flex-direction:column;">
      <div class="mo-pix" style="display:flex;align-items:center;justify-content:space-between;padding:7px 11px;">
        <div style="display:flex;align-items:center;gap:6px;font-size:12px;font-weight:700;color:${C.ink};"><span style="width:8px;height:8px;border-radius:2px;background:${dept.accent};display:inline-block;"></span>${dept.icon} ${escHtml(dept.name)}</div>
        ${badge}
      </div>
      <div style="position:relative;flex:1;display:flex;align-items:flex-end;justify-content:center;padding-bottom:8px;gap:6px;">
        <div style="position:absolute;left:10px;bottom:6px;opacity:.85;">${deskSprite()}</div>
        ${leadAvatar(dept,stats)}
        <div style="position:absolute;right:10px;bottom:6px;opacity:.85;">${plantSprite()}</div>
      </div></div>`;
  }

  function founderStripHtml(){
    const active=founderState==='thinking'||founderState==='delegating';
    const label=founderState==='thinking'?'يفكّر…':founderState==='delegating'?'يوزّع المهام':'يدير الشركة';
    return `<div class="mo-pix" style="grid-column:1/-1;background:linear-gradient(135deg,${C.mint},${C.surface} 70%);border:1px solid ${C.line};border-radius:12px;padding:10px 16px;display:flex;align-items:center;gap:14px;">
      <div style="flex:0 0 auto;">${pixelPerson(C.brand,4.6)}</div>
      <div style="flex:1;min-width:0;"><div style="font-size:13px;font-weight:700;color:${C.ink};">المؤسس · المدير التنفيذي</div>
        <div style="font-size:11px;color:${C.muted};margin-top:2px;display:flex;align-items:center;gap:6px;"><span class="${active?'moasis-pulse':''}" style="width:7px;height:7px;border-radius:50%;background:${founderState==='delegating'?C.amber:C.brand};display:inline-block;"></span>${escHtml(label)} — يدير الفريق ويوزّع المهام على الأقسام</div>
      </div></div>`;
  }

  const PHASE_LABEL={ arriving:'الأعضاء يدخلون…', gathering:'يأخذون أماكنهم', debating:'نقاش وتداول', founder_review:'المؤسس يقيّم', concluded:'صدر القرار', failed:'تعذّر الاجتماع' };
  const SHIRTS=['#C98B6B','#7B9E89','#9A8FB0','#C9A66B','#B0879E','#6B8F9E','#A8845C','#8B9E6B'];
  function meetingRoomHtml(m){
    const members=m.members||[], n=Math.max(members.length,1);
    const seats=members.map((mem,i)=>{ const ang=(-90+(360/n)*i)*Math.PI/180, cx=50+33*Math.cos(ang), cy=50+34*Math.sin(ang);
      const topHalf=Math.sin(ang)<-0.15, walking=mem.status==='walking', speaking=mem.status==='speaking';
      const walkIn=walking?`animation:mo-council-in .9s ease ${(i*0.12).toFixed(2)}s both;`:'';
      const side=topHalf?'top:-12px;transform:translate(-50%,-100%);':'bottom:-12px;transform:translate(-50%,100%);';
      const bubble=(mem.bubble&&!walking)?`<div class="mo-pix" style="position:absolute;left:50%;${side}width:128px;text-align:center;background:${C.surface};border:1px solid ${speaking?C.brand:C.line};color:${C.ink};font-size:9px;line-height:1.4;padding:5px 7px;border-radius:9px;box-shadow:0 3px 8px ${C.shadow};pointer-events:none;z-index:40;">${escHtml(String(mem.bubble).slice(0,64))}</div>`:'';
      return `<div style="position:absolute;left:${cx}%;top:${cy}%;transform:translate(-50%,-50%);${walkIn}z-index:20;"><div class="${speaking?'mo-step':''}" style="position:relative;display:flex;flex-direction:column;align-items:center;">${bubble}<div style="font-size:12px;">${escHtml(mem.emoji||'👤')}</div>${pixelPerson(SHIRTS[i%SHIRTS.length],3.6)}<div class="mo-pix" style="font-size:8.5px;color:${C.ink};white-space:nowrap;font-weight:700;">${escHtml(mem.role||'')}</div></div></div>`; }).join('');
    return `<div style="grid-column:1/-1;background:${C.surface};border:1px solid ${C.brand};border-radius:12px;overflow:hidden;">
      <div class="mo-pix" style="display:flex;align-items:center;justify-content:space-between;padding:9px 14px;border-bottom:1px solid ${C.line};background:${C.mint};"><div style="font-size:13px;font-weight:700;color:${C.brandDk};">🏛️ قاعة مجلس المؤسس</div><div style="font-size:10px;color:${C.brandDk};display:inline-flex;align-items:center;gap:6px;"><span class="moasis-pulse" style="width:7px;height:7px;border-radius:50%;background:${C.brand};display:inline-block;"></span>${escHtml(PHASE_LABEL[m.phase||'gathering']||m.phase)}</div></div>
      <div style="position:relative;height:300px;background:repeating-linear-gradient(0deg,transparent 0 18px,${C.grid} 18px 19px),repeating-linear-gradient(90deg,transparent 0 18px,${C.grid} 18px 19px);">
        <div style="position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);width:42%;height:34%;background:linear-gradient(135deg,${C.brandDk},${C.brand});border-radius:50%;display:flex;align-items:center;justify-content:center;box-shadow:0 6px 16px ${C.shadow};"><div class="mo-pix" style="color:#fff;font-size:10px;text-align:center;padding:0 12px;max-width:82%;line-height:1.5;">${escHtml(String(m.question||'').slice(0,84))}</div></div>
        <div style="position:absolute;left:50%;bottom:2px;transform:translateX(-50%);font-size:12px;">🚪</div>${seats}</div></div>`;
  }

  function render(){
    if(!mounted)return; const floor=document.querySelector(`#${HOST_ID} [data-bind="office-floor"]`); if(!floor)return;
    // ONE floor: a single bordered building, departments are open-plan zones in a grid inside it.
    floor.setAttribute('style',`flex:1 1 0;min-width:0;padding:16px;overflow-y:auto;`);
    const stats=deptStats();
    const zones=DEPARTMENTS.map(d=>zoneHtml(d,stats.get(d.key))).join('');
    const council=(councilMeeting&&councilMeeting.members&&councilMeeting.members.length)?meetingRoomHtml(councilMeeting):'';
    // Wall AC units mounted along the top of the building.
    const acStrip=`<div style="grid-column:1/-1;display:flex;justify-content:space-around;align-items:flex-start;padding:0 8px 2px;margin-top:-4px;">${acSprite()}${acSprite()}${acSprite()}</div>`;
    // Common lounge: couch + coffee/water + plants on a rug — makes it feel real.
    const lounge=`<div style="grid-column:1/-1;position:relative;border-radius:10px;border:1px solid ${C.line};background:linear-gradient(${C.wall},${C.surface});padding:8px 12px;display:flex;align-items:flex-end;justify-content:center;gap:18px;min-height:78px;overflow:hidden;">
        <div style="position:absolute;left:50%;bottom:2px;transform:translateX(-50%);">${rugSprite()}</div>
        <div style="position:relative;z-index:2;">${bigPlantSprite()}</div>
        <div style="position:relative;z-index:2;">${couchSprite()}</div>
        <div style="position:relative;z-index:2;">${waterSprite()}</div>
        <div style="position:relative;z-index:2;">${plantSprite()}</div>
        <div class="mo-pix" style="position:absolute;top:5px;right:11px;font-size:9.5px;color:${C.muted};">الاستراحة ☕</div>
      </div>`;
    floor.innerHTML=`
      <div style="background:${C.surface};border:2px solid ${C.brand};border-radius:14px;padding:12px;box-shadow:0 4px 16px ${C.shadow};">
        <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:0;">
          ${acStrip}
          ${founderStripHtml()}
          ${council}
          <div style="grid-column:1/-1;height:8px;"></div>
          ${lounge}
          <div style="grid-column:1/-1;height:8px;"></div>
          <div style="grid-column:1/-1;border-radius:10px;overflow:hidden;background:repeating-linear-gradient(0deg,transparent 0 18px,${C.grid} 18px 19px),repeating-linear-gradient(90deg,transparent 0 18px,${C.grid} 18px 19px);border:1px solid ${C.line};">
            <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(190px,1fr));">${zones}</div>
          </div>
        </div>
      </div>`;
    const total=Array.from(stats.values()).reduce((a,s)=>a+s.running,0);
    const cEl=document.querySelector(`#${HOST_ID} [data-bind="office-count"]`); if(cEl) cEl.textContent=total>0?`${total} موظف يعمل`:'الشركة جاهزة';
    for(const el of floor.querySelectorAll('[data-dept]')){ const k=el.getAttribute('data-dept'); el.addEventListener('click',()=>openDeptPanel(k)); }
  }

  async function openDeptPanel(key){
    openDept=key; const dept=DEPARTMENTS.find(d=>d.key===key); const stats=deptStats().get(key);
    const panel=document.querySelector(`#${HOST_ID} [data-bind="office-panel"]`);
    const t=document.querySelector(`#${HOST_ID} [data-bind="panel-title"]`), sub=document.querySelector(`#${HOST_ID} [data-bind="panel-sub"]`), body=document.querySelector(`#${HOST_ID} [data-bind="panel-body"]`);
    if(!panel)return; panel.style.width='360px';
    if(t)t.textContent=`${dept.icon} قسم ${dept.name}`; if(sub)sub.textContent=`${stats.count} موظف · ${stats.running} يعمل الآن`;
    if(!body)return;
    if(stats.count===0){ body.innerHTML=`<div style="color:${C.muted};">القسم متفرّغ حالياً. لمّا تُسند مهمة من نوع ${dept.name}، يظهر الموظفون هنا.</div>`; return; }
    body.innerHTML=`<div style="font-size:11px;color:${C.muted};font-weight:700;margin-bottom:8px;">👥 موظفو القسم وما يعملون عليه</div>`+
      stats.agents.map(([id,w])=>{ const st=w.status==='running'?C.brand:w.status==='failed'?C.rose:C.slate;
        return `<div style="padding:9px 0;border-bottom:1px solid ${C.line};"><div style="display:flex;align-items:center;gap:7px;"><span style="width:7px;height:7px;border-radius:50%;background:${st};display:inline-block;"></span><span style="font-weight:700;color:${C.ink};font-size:12px;">وكيل ${id.slice(0,4).toUpperCase()}</span><span style="color:${C.muted};font-size:10.5px;">${escHtml(w.lastStep||friendlyTool(w.lastTool)||'')}</span></div><div style="color:${C.muted};font-size:11.5px;line-height:1.5;margin-top:3px;">🎯 ${escHtml((w.task||'مهمة قيد التنفيذ').slice(0,160))}</div></div>`; }).join('');
  }
  function closePanel(){ openDept=null; const p=document.querySelector(`#${HOST_ID} [data-bind="office-panel"]`); if(p)p.style.width='0'; }

  async function poll(){
    const a=api(); if(!a)return;
    try{ const r=await a('/api/subagents'); const runs=(r&&r.data&&r.data.runs)||[];
      try{ const cr=await a('/api/council/active'); councilMeeting=(cr&&cr.data)||null; }catch{ councilMeeting=null; }
      const now=Date.now(), seen=new Set();
      for(const run of runs){ if(!run||!run.id)continue; seen.add(run.id); const prev=workers.get(run.id); const done=prev&&prev.status!=='completed'&&run.status==='completed';
        workers.set(run.id,{status:run.status||'running',task:run.task||(prev&&prev.task)||'',since:prev?prev.since:now,completedAt:done?now:(prev&&prev.completedAt)||(run.status==='completed'?now:0),lastTool:run.last_step_tool||(prev&&prev.lastTool)||'',lastStep:run.last_step_tool?friendlyTool(run.last_step_tool):(prev&&prev.lastStep)||''}); }
      for(const [id,w] of workers){ if(!seen.has(id)){ const fin=w.status==='completed'||w.status==='failed'; const age=now-(w.completedAt||w.since||now); if(!fin||age>2*60_000) workers.delete(id); } }
      render(); if(openDept) openDeptPanel(openDept);
    }catch{}
  }
  function startPolling(){ poll(); if(pollTimer)clearInterval(pollTimer); pollTimer=setInterval(poll,4000); }
  function stopPolling(){ if(pollTimer){clearInterval(pollTimer);pollTimer=null;} }
  function onShow(){ ensureScaffold(); render(); startPolling(); }
  function onHide(){ stopPolling(); }
  function setFounder(state){ founderState=state||'idle'; if(founderResetTimer)clearTimeout(founderResetTimer); if(state&&state!=='idle'){ founderResetTimer=setTimeout(()=>{founderState='idle';render();},8000);} render(); }
  window.__moasisOffice={ onShow,onHide,setFounder, openAgentPanel:openDeptPanel };
})();
