// screens-head.jsx — HEAD: the Executive Headquarters. ASSEM (CEO) + 7 directors, each reusing an
// existing engine. Founder Command panel makes REAL audited settings changes (money-adjacent stays
// directive-only). Reuse-only: ASSEM reuses the existing AssemScreen; directors reuse directorView.
const { useState: useHeadState, useEffect: useHeadEffect } = React;

// SALES-ONLY ORG: ASSEM (CEO) + 6 directors. Sales merged into Revenue; Research folded into Data;
// Marketing renamed to Channel Director (real messaging outreach — WhatsApp/Instagram/Messenger/TikTok).
const HEAD_DIRECTORS = [
  ["assem", "ASSEM (CEO)", "عاصم (المدير التنفيذي)", "sparkles"],
  ["revenue", "Revenue Director", "مدير الإيراد", "trending"],
  ["marketing", "Channel Director", "مدير القنوات", "message"],
  ["customer_success", "Customer Success Director", "مدير نجاح العملاء", "heart"],
  ["operations", "Operations Director", "مدير العمليات", "grid"],
  ["cto", "CTO", "المدير التقني", "cpu"],
  ["data", "Data Director", "مدير البيانات", "layers"],
];
const HEAD_STATUS_TONE = { on_track: "var(--color-success)", healthy: "var(--color-success)", operating: "var(--color-success)", active: "var(--color-success)", GO: "var(--color-success)", GO_ON_CREDENTIALS: "var(--color-warning, #B45309)", behind: "var(--color-warning, #B45309)", watch: "var(--color-warning, #B45309)", degraded: "var(--color-danger)", NO_GO: "var(--color-danger)", critical: "var(--color-danger)", idle: "var(--fg-3)", no_target: "var(--fg-3)", no_customers: "var(--fg-3)", coordinator: "var(--color-secondary)", unknown: "var(--fg-3)" };

function HeadDirectorView({ id, lang, part, data, trainingData }) {
  const T = (ar, en) => (lang === "ar" ? ar : en);
  // P3·P2 — the director page is decomposed into Chat→Objectives→Subagents→Actions→Reports→Learning.
  // When the parent (DirectorPage) has already fetched director()/training once, it passes them as props so
  // the "objectives" and "reports" instances SHARE one fetch (no double request). part filters what renders.
  const usingProp = data !== undefined;
  const [vState, setV] = useHeadState(null);
  const [trainingState, setTraining] = useHeadState(null);
  const [recActed, setRecActed] = useHeadState({});   // recommendation text → action taken
  const v = usingProp ? data : vState;
  const training = usingProp ? trainingData : trainingState;
  const showObj = part == null || part === "objectives";
  const showRep = part == null || part === "reports";
  // Every action records a REAL auditable decision (no dead buttons). Modify/Assign additionally focus
  // the director chat so the founder can refine or re-route the directive in conversation.
  const actRec = (text, action) => {
    setRecActed((a) => ({ ...a, [text]: action }));
    API.assem.recommendationAction(id, text, action).catch(() => {});
    if (action === "modify" || action === "assign") { try { document.querySelector(".dirchat-input")?.focus(); } catch (e) {} }
  };
  useHeadEffect(() => { if (usingProp) return; setV(null); API.assem.director(id, lang).then(setV).catch(() => setV({ error: true })); }, [id]);
  // Phase 11 — Training Status per director (reuses directorTraining; matched by id; honest NOT_ENOUGH_DATA).
  useHeadEffect(() => { if (usingProp || id === "assem") return; API.assem.directorTraining(lang).then((d) => setTraining((d && d.reports || []).find((r) => r.director === id) || null)).catch(() => setTraining(null)); }, [id]);
  // ASSEM/CEO area = the Supreme Executive Intelligence sub-nav (Chat + Brain + Growth + Strategic + …).
  if (id === "assem") return (window.AssemSupreme ? <AssemSupreme lang={lang} /> : <AssemScreen embedded />);
  if (!v) return <Card><div className="skel" style={{ height: 80, borderRadius: 10 }} /></Card>;
  if (v.error) return <Card><EmptyState icon="alert" title={T("تعذّر التحميل", "Could not load")} /></Card>;
  const L = (x) => (x && typeof x === "object" ? (lang === "ar" ? x.ar : x.en) : x);
  // S — coerce ANY value to a renderable string (never pass a raw {ar,en}/object to React).
  const S = (x) => { if (x == null) return ""; if (typeof x === "string" || typeof x === "number") return String(x); if (x.ar || x.en) return L(x) || ""; if (x.label) return S(x.label); if (x.title) return S(x.title); return x.action || x.name || x.vertical || S(x.headline) || x.why || ""; };
  // card — a founderMode card object: render "title: headline" (the actionable line, not just the label).
  const cardLine = (x) => { if (x == null) return ""; if (typeof x === "string") return x; const t = x.title ? S(x.title) : ""; const h = x.headline ? S(x.headline) : S(x); return t && h && t !== h ? `${t}: ${h}` : (h || t); };
  // goalText — human-readable goal line (real numbers only; honest note when no data).
  const money = (n) => `${v.currency || ""} ${typeof n === "number" ? n.toLocaleString() : n}`.trim();
  const goalText = (g) => {
    if (!g) return "—";
    if (g.note) return S(g.note);
    const metric = g.metric ? String(g.metric).replace(/_/g, " ") : "";
    const parts = [];
    if (g.target != null) parts.push(`${T("الهدف", "target")} ${money(g.target)}`);
    if (g.forecast != null) parts.push(`${T("التوقّع", "forecast")} ${money(g.forecast)}`);
    if (g.gap != null) parts.push(`${T("الفجوة", "gap")} ${money(g.gap)}`);
    if (g.openActions != null) parts.push(`${g.openActions} ${T("إجراء مفتوح", "open actions")}`);
    if (g.activeCampaigns != null) parts.push(`${g.activeCampaigns} ${T("حملة نشطة", "active campaigns")}`);
    if (g.customers != null) parts.push(`${g.customers} ${T("عميل", "customers")}`);
    if (g.score != null) parts.push(`${T("الصحّة", "health")} ${g.score}${g.band ? " (" + g.band + ")" : ""}`);
    if (g.openItems != null) parts.push(`${g.openItems} ${T("بند متراكم", "backlog items")}`);
    if (g.agents != null) parts.push(`${g.agents} ${T("وكيل", "agents")}`);
    return (metric + (parts.length ? " — " + parts.join(" · ") : "")) || "—";
  };
  const list = (title, items, render) => (Array.isArray(items) && items.length) ? (
    <Card><div className="col" style={{ gap: 6, padding: 4 }}><b style={{ fontSize: 13 }}>{title}</b>{items.slice(0, 6).map((it, i) => <div key={i} className="row" style={{ gap: 6, fontSize: 12.5 }}>{render(it)}</div>)}</div></Card>
  ) : null;
  return (
    <div className="col" style={{ gap: 12 }}>
      {showObj ? (
      <Card><div className="between" style={{ padding: 4 }}>
        <b style={{ fontSize: 14 }}>{L(v.label)}</b>
        <Badge tone={v.status === "on_track" || v.status === "healthy" || v.status === "operating" ? "success" : /behind|watch|GO_ON/.test(v.status) ? "warning" : /degraded|NO_GO|critical/.test(v.status) ? "danger" : "neutral"}>{String(v.status).replace(/_/g, " ")}</Badge>
      </div>
        {v.goal ? <div className="subtle" style={{ fontSize: 12, padding: "0 4px 4px" }}>{T("الهدف", "Goal")}: {goalText(v.goal)}</div> : null}
        {Array.isArray(v.kpis) && v.kpis.length ? <div className="row wrap" style={{ gap: 6, padding: "0 4px 4px" }}>{v.kpis.map((k, i) => <span key={i} style={{ fontSize: 11, padding: "2px 8px", borderRadius: 6, background: "var(--bg-2)", border: "1px solid var(--border-1)" }}>{k.k}: <b>{k.v == null ? "—" : String(k.v)}</b></span>)}</div> : null}
      </Card>
      ) : null}
      {showRep ? (<React.Fragment>
      {list(T("المخاطر", "Risks"), v.risks, (x) => <><Icon name="alert" size={12} style={{ color: "var(--color-danger)", flexShrink: 0 }} />{S(x)}</>)}
      {list(T("العوائق", "Blockers"), v.blockers, (x) => <><Icon name="x" size={12} style={{ color: "var(--color-warning, #B45309)", flexShrink: 0 }} />{S(x)}</>)}
      {list(T("الفرص", "Opportunities"), v.opportunities, (x) => { const t = S(x); const why = x && typeof x === "object" && x.why && S(x.why) !== t ? " — " + S(x.why) : ""; return <><Icon name="sparkles" size={12} style={{ color: "var(--color-secondary)", flexShrink: 0 }} />{t}{why}</>; })}
      {/* PART 11 — memory health: are we REMEMBERING customers? (Revenue + Customer-Success directors only) */}
      {v.memoryHealth && v.memoryHealth.status !== "not_enough_data" ? (
        <Card><div className="col" style={{ gap: 8, padding: 4 }}>
          <b style={{ fontSize: 13 }}>{T("صحّة الذاكرة", "Memory health")}</b>
          <div className="row wrap" style={{ gap: 6 }}>
            {v.memoryHealth.avgMemoryQuality != null ? <span style={{ fontSize: 11, padding: "2px 8px", borderRadius: 6, background: "var(--bg-2)", border: "1px solid var(--border-1)" }}>{T("متوسّط الجودة", "Avg quality")}: <b>{v.memoryHealth.avgMemoryQuality}/100</b></span> : null}
            {v.memoryHealth.contextFailures != null ? <span style={{ fontSize: 11, padding: "2px 8px", borderRadius: 6, background: "var(--bg-2)", border: "1px solid var(--border-1)" }}>{T("فشل سياق", "Context failures")}: <b>{v.memoryHealth.contextFailures}</b></span> : null}
            {v.memoryHealth.repeatedQuestionCount != null ? <span style={{ fontSize: 11, padding: "2px 8px", borderRadius: 6, background: "var(--bg-2)", border: "1px solid var(--border-1)" }}>{T("أسئلة مكرّرة", "Repeated questions")}: <b>{v.memoryHealth.repeatedQuestionCount}</b></span> : null}
            {v.memoryHealth.overduePromises != null ? <span style={{ fontSize: 11, padding: "2px 8px", borderRadius: 6, background: "var(--bg-2)", border: "1px solid var(--border-1)" }}>{T("وعود متأخّرة", "Overdue promises")}: <b>{v.memoryHealth.overduePromises}</b></span> : null}
            {v.memoryHealth.relationshipHealth != null ? <span style={{ fontSize: 11, padding: "2px 8px", borderRadius: 6, background: "var(--bg-2)", border: "1px solid var(--border-1)" }}>{T("صحّة العلاقة", "Relationship health")}: <b>{v.memoryHealth.relationshipHealth}/100</b></span> : null}
            {v.memoryHealth.trustHealth != null ? <span style={{ fontSize: 11, padding: "2px 8px", borderRadius: 6, background: "var(--bg-2)", border: "1px solid var(--border-1)" }}>{T("صحّة الثقة", "Trust health")}: <b>{v.memoryHealth.trustHealth}/100</b></span> : null}
            {v.memoryHealth.promiseCompletion != null ? <span style={{ fontSize: 11, padding: "2px 8px", borderRadius: 6, background: "var(--bg-2)", border: "1px solid var(--border-1)" }}>{T("إتمام الوعود", "Promise completion")}: <b>{v.memoryHealth.promiseCompletion}%</b></span> : null}
          </div>
          {Array.isArray(v.memoryHealth.weakContacts) && v.memoryHealth.weakContacts.length ? (
            <div className="col" style={{ gap: 3 }}>
              <span className="subtle" style={{ fontSize: 11 }}>{T("أضعف ذاكرة عملاء", "Weakest-memory customers")}:</span>
              {v.memoryHealth.weakContacts.slice(0, 5).map((w, i) => <div key={i} style={{ fontSize: 11.5 }}>· {w.name} — <b>{w.score}/100</b> <span className="subtle">({w.weakestAxis})</span></div>)}
            </div>
          ) : null}
          <div className="subtle" style={{ fontSize: 10.5, color: "var(--color-orange)" }}>{T("قياس حقيقي أو «لا بيانات»؛ عرض فقط — لا تنفيذ تلقائي.", "Measured or NOT_ENOUGH_DATA; visibility only — no auto-action.")}</div>
        </div></Card>
      ) : null}
      {Array.isArray(v.recommendations) && v.recommendations.length ? (
        <Card><div className="col" style={{ gap: 8, padding: 4 }}>
          <b style={{ fontSize: 13 }}>{T("التوصيات", "Recommendations")}</b>
          {v.recommendations.slice(0, 6).map((x, i) => { const text = cardLine(x); if (!text) return null; const done = recActed[text]; return (
            <div key={i} className="col" style={{ gap: 5, paddingTop: i ? 6 : 0, borderTop: i ? "1px solid var(--border-1)" : "none" }}>
              <div className="row" style={{ gap: 6, fontSize: 12.5 }}><Icon name="arrowRight" size={12} style={{ color: "var(--color-secondary)", flexShrink: 0 }} />{text}</div>
              {done ? <div className="subtle" style={{ fontSize: 11, color: "#15803D" }}><Icon name="checkcircle" size={11} /> {T("سُجّل", "Recorded")}: {done}</div> : (
                <div className="row" style={{ gap: 5, flexWrap: "wrap" }}>
                  <Button size="sm" onClick={() => actRec(text, "approve")}>{T("اعتمد", "Approve")}</Button>
                  <Button size="sm" variant="ghost" onClick={() => actRec(text, "reject")}>{T("ارفض", "Reject")}</Button>
                  <Button size="sm" variant="ghost" onClick={() => actRec(text, "modify")}>{T("عدّل", "Modify")}</Button>
                  <Button size="sm" variant="ghost" onClick={() => actRec(text, "assign")}>{T("أسند", "Assign")}</Button>
                  <Button size="sm" variant="ghost" onClick={() => actRec(text, "escalate")}>{T("تصعيد", "Escalate")}</Button>
                </div>
              )}
            </div>
          ); })}
          <div className="subtle" style={{ fontSize: 10.5, color: "var(--color-orange)" }}>{T("الاعتماد/الرفض يُسجَّل كقرار قابل للتدقيق — لا تنفيذ تلقائي.", "Approve/Reject records an auditable decision — nothing auto-executes.")}</div>
        </div></Card>
      ) : null}
      {training ? (
        <Card><div className="col" style={{ gap: 4, padding: 4 }}>
          <div className="between"><b style={{ fontSize: 13 }}>{T("حالة التدريب", "Training status")}</b>
            <Badge tone={/strong|high/.test(training.knowledgeLevel) ? "success" : /developing|medium/.test(training.knowledgeLevel) ? "warning" : training.knowledgeLevel === "not_enough_data" ? "neutral" : "danger"}>{String(training.knowledgeLevel).replace(/_/g, " ")}</Badge>
          </div>
          <div className="subtle" style={{ fontSize: 11.5 }}>{T("جودة القرار", "Decision quality")}: {String(training.decisionQuality).replace(/_/g, " ")} · {training.executionImpact.decisionsRecorded} {T("قرار مسجّل", "decisions recorded")}</div>
          {(training.trainingNeeds || []).length ? <div className="subtle" style={{ fontSize: 11.5 }}>{T("يحتاج", "Needs")}: {training.trainingNeeds[0]}</div> : null}
          <div className="subtle" style={{ fontSize: 10.5, color: "var(--color-orange)" }}>{T("توصية فقط — تتطلّب موافقة المؤسس.", "Recommendation only — requires founder approval.")}</div>
        </div></Card>
      ) : null}
      </React.Fragment>) : null}
    </div>
  );
}

// Founder Command panel — Part 2: PER-DIRECTOR commands (each director shows only the levers it owns).
// Every command is REAL + reuse-only — one of three kinds: cmd (audited founderCommand settings change),
// ask (a real directorChat message → pending recommendation, no auto-execute), nav (deep-link to the
// existing screen that performs it). No fake buttons. Money-adjacent stays directive-only (Assem never spends).
const DIRECTOR_QUICK = {
  revenue: [
    { en: "Change the target", ar: "غيّر الهدف", kind: "cmd", type: "set_revenue_target", input: "number", placeholder: "500000" },
    { en: "Generate a revenue plan", ar: "أنشئ خطة إيراد", kind: "ask", text: { en: "Generate a revenue plan: forecast by vertical and product, the gap to target, and the actions to close it.", ar: "أنشئ خطة إيراد: توقّع بحسب القطاع والمنتج، والفجوة عن الهدف، والإجراءات لإغلاقها." } },
    { en: "Approve revenue actions", ar: "اعتمد إجراءات الإيراد", kind: "ask", text: { en: "Which revenue actions should we prioritize and approve now, and what's the expected impact?", ar: "أي إجراءات إيراد نعطيها الأولوية ونعتمدها الآن، وما الأثر المتوقّع؟" } },
    { en: "Change market focus", ar: "غيّر تركيز السوق", kind: "cmd", type: "focus_enterprise" },
    { en: "Change vertical focus", ar: "غيّر تركيز القطاع", kind: "cmd", type: "set_vertical_focus", input: "text", placeholder: "logistics" },
    // Sales merged into Revenue — the selling commands live here now (Revenue owns the selling agents).
    { en: "Review leads", ar: "راجع العملاء المحتملين", kind: "ask", text: { en: "Which leads should we prioritize right now, and why?", ar: "أي العملاء المحتملين نعطيهم الأولوية الآن، ولماذا؟" } },
    { en: "Improve conversion", ar: "حسّن التحويل", kind: "ask", text: { en: "What's our conversion rate by stage, where are we losing deals, and how do we improve it?", ar: "ما معدّل التحويل بحسب المرحلة، وأين نخسر الصفقات، وكيف نحسّنه؟" } },
    { en: "Review opportunities", ar: "راجع الفرص", kind: "nav", screen: "opportunities" },
  ],
  // Channel Director — REAL messaging outreach (WhatsApp / Instagram / Messenger / TikTok). NOT ads.
  marketing: [
    { en: "Create an outreach campaign", ar: "أنشئ حملة تواصل", kind: "nav", screen: "campaigns" },
    { en: "Review outreach performance", ar: "راجع أداء التواصل", kind: "ask", text: { en: "Which outreach campaigns perform best by replies and conversions, and which should we pause?", ar: "أي حملات التواصل أفضل أداءً من حيث الردود والتحويلات، وأيّها نوقف؟" } },
    { en: "Change target audience", ar: "غيّر الجمهور المستهدف", kind: "ask", text: { en: "Who should we reach next, and how should we change our audience and messaging?", ar: "من نراسل تالياً، وكيف نغيّر الجمهور والرسائل؟" } },
    { en: "Pause all campaigns", ar: "أوقف كل الحملات", kind: "cmd", type: "pause_campaigns" },
    { en: "Resume campaigns", ar: "استأنف الحملات", kind: "cmd", type: "resume_campaigns" },
  ],
  customer_success: [
    { en: "Review churn risk", ar: "راجع مخاطر التسرّب", kind: "ask", text: { en: "Which customers are most at risk of churning, and what should we do to keep them?", ar: "أي العملاء الأكثر عرضة للتسرّب، وماذا نفعل للحفاظ عليهم؟" } },
    { en: "Review renewals", ar: "راجع التجديدات", kind: "ask", text: { en: "Which renewals are coming up and how do we secure them?", ar: "أي تجديدات قادمة وكيف نضمنها؟" } },
    { en: "Review expansion", ar: "راجع فرص التوسّع", kind: "ask", text: { en: "Which customers are ready for an upsell or expansion, and what should we offer?", ar: "أي العملاء جاهزون للبيع الإضافي أو التوسّع، وبماذا نعرض عليهم؟" } },
    { en: "Review at-risk accounts", ar: "راجع الحسابات المهدّدة", kind: "nav", screen: "customers" },
  ],
  research: [
    { en: "Research a competitor", ar: "ابحث منافساً", kind: "ask", text: { en: "Research our top competitor and summarize their pricing, strengths, and weaknesses.", ar: "ابحث أكبر منافس لدينا ولخّص أسعاره ونقاط قوته وضعفه." } },
    { en: "Find a new market", ar: "جد سوقاً جديداً", kind: "ask", text: { en: "Find a promising new vertical or market we should target next, and why.", ar: "جد قطاعاً أو سوقاً جديداً واعداً نستهدفه تالياً، ولماذا." } },
    { en: "Summarize a market", ar: "لخّص سوقاً", kind: "ask", text: { en: "Summarize the market we sell into: size, demand, and what buyers want.", ar: "لخّص السوق الذي نبيع فيه: الحجم والطلب وما يطلبه المشترون." } },
  ],
  cto: [
    { en: "Review integrations", ar: "راجع التكاملات", kind: "nav", screen: "settings", tab: "integrations" },
    { en: "Generate a Claude fix report", ar: "أنشئ تقرير إصلاح", kind: "ask", text: { en: "Generate a fix report: root causes of recent failures and the recommended fixes for Claude Code.", ar: "أنشئ تقرير إصلاح: الأسباب الجذرية للأعطال الأخيرة والإصلاحات الموصى بها." } },
    { en: "Analyze technical problems", ar: "حلّل المشكلات التقنية", kind: "ask", text: { en: "What are the root causes of our recent technical issues and outages?", ar: "ما الأسباب الجذرية لمشكلاتنا التقنية وأعطالنا الأخيرة؟" } },
    { en: "Review deployment readiness", ar: "راجع جاهزية النشر", kind: "ask", text: { en: "Give me a deployment readiness plan: what's blocking go-live and the steps to fix it.", ar: "أعطني خطة جاهزية للنشر: ما الذي يعيق الإطلاق وخطوات إصلاحه." } },
  ],
  operations: [
    { en: "Review escalations", ar: "راجع التصعيدات", kind: "nav", screen: "escalations" },
    { en: "Review requests", ar: "راجع الطلبات", kind: "nav", screen: "requests" },
    { en: "Optimize workflows", ar: "حسّن سير العمل", kind: "ask", text: { en: "Which process or workflow should we streamline first to move faster, and how?", ar: "أي عملية أو سير عمل نبسّطه أولاً لنتحرّك أسرع، وكيف؟" } },
    { en: "Find bottlenecks", ar: "اكشف الاختناقات", kind: "ask", text: { en: "Where are the operational bottlenecks slowing us down, and how do we clear them?", ar: "أين الاختناقات التشغيلية التي تبطئنا، وكيف نزيلها؟" } },
  ],
  // Data Director — actionable insight from REAL data (funnel / objections / agent performance). Read-only.
  data: [
    { en: "Review the sales funnel", ar: "راجع قمع المبيعات", kind: "ask", text: { en: "Show the sales funnel: leads → replies → qualified → meetings → proposals → closed, with conversion and the biggest drop-off.", ar: "اعرض قمع المبيعات: عملاء ← ردود ← مؤهّلون ← اجتماعات ← عروض ← مغلقة، مع التحويل وأكبر تسرّب." } },
    { en: "Top objection costing deals", ar: "أكثر اعتراض يكلّفنا", kind: "ask", text: { en: "Which objection is losing us the most deals, and what should we add to the playbook?", ar: "أي اعتراض يخسّرنا أكثر الصفقات، وماذا نضيف إلى دليل المبيعات؟" } },
    { en: "Which agent is underperforming?", ar: "أي وكيل أداؤه ضعيف؟", kind: "ask", text: { en: "Which agent is underperforming, on what metric, and what's the recommended fix?", ar: "أي وكيل أداؤه ضعيف، وعلى أي مقياس، وما الإصلاح الموصى به؟" } },
    { en: "Open analytics", ar: "افتح التحليلات", kind: "nav", screen: "data" },
  ],
};
function FounderCommandPanel({ id, lang, go }) {
  const T = (ar, en) => (lang === "ar" ? ar : en);
  const [val, setVal] = useHeadState({});
  const [result, setResult] = useHeadState(null);
  const [busy, setBusy] = useHeadState(false);
  const cmds = DIRECTOR_QUICK[id] || [];
  const label = (c) => (lang === "ar" ? c.ar : c.en);
  const run = (cmd) => {
    if (cmd.kind === "nav") {
      try { window.__navTab = { screen: cmd.screen, tab: cmd.tab, revtab: cmd.revtab, director: cmd.director }; window.dispatchEvent(new CustomEvent("maxab:navtab", { detail: window.__navTab })); } catch (e) {}
      if (go) go(cmd.screen);
      return;
    }
    setBusy(true); setResult(null);
    if (cmd.kind === "ask") {
      const text = lang === "ar" ? cmd.text.ar : cmd.text.en;
      API.assem.directorChat(id, text, lang).then((r) => setResult({ ok: true, ask: true, mode: r.mode })).catch((e) => setResult({ ok: false, error: e.message })).finally(() => setBusy(false));
      return;
    }
    const v = cmd.input === "number" ? Number(val[cmd.type] || 0) : (val[cmd.type] || "");
    API.assem.founderCommand(cmd.type, v, label(cmd)).then((r) => setResult(r)).catch((e) => setResult({ ok: false, error: e.message })).finally(() => setBusy(false));
  };
  if (!cmds.length) return null;
  return (
    <Card><div className="col" style={{ gap: 8, padding: 4 }}>
      <b style={{ fontSize: 13 }}>{T("أوامر المؤسس", "Founder commands")}</b>
      <div className="subtle" style={{ fontSize: 11, color: "var(--color-orange)" }}>{T("أوامر تخصّ هذا المدير فقط. تغييرات حقيقية موثّقة — لا ينفق عاصم مالاً؛ التوجيهات تُسجَّل كتوصيات تعتمدها.", "Only this manager's own levers. Real, audited changes — Assem never spends money; directions are recorded as recommendations you approve.")}</div>
      {cmds.map((cmd) => (
        <div key={cmd.en} className="row" style={{ gap: 8, alignItems: "center" }}>
          {cmd.kind === "cmd" && cmd.input ? <input className="input" style={{ flex: "0 0 150px", fontSize: 12.5 }} type={cmd.input} placeholder={cmd.placeholder} value={val[cmd.type] || ""} onChange={(e) => setVal({ ...val, [cmd.type]: e.target.value })} /> : <span style={{ flex: "0 0 150px", fontSize: 11, color: "var(--fg-4)" }}>{cmd.kind === "nav" ? T("يفتح الشاشة", "opens screen") : cmd.kind === "ask" ? T("يسأل المدير", "asks the manager") : ""}</span>}
          <Button size="sm" variant="ghost" disabled={busy} onClick={() => run(cmd)}>{label(cmd)}{cmd.kind === "nav" ? " →" : ""}</Button>
        </div>
      ))}
      {result ? <div className="row" style={{ gap: 7, fontSize: 12, padding: "6px 8px", borderRadius: 8, background: result.ok ? "var(--color-success-soft)" : "var(--color-danger-soft)", color: result.ok ? "#15803D" : "var(--color-danger)" }}>
        <Icon name={result.ok ? "checkcircle" : "alert"} size={14} />
        {result.ok ? (result.ask
          ? T("سُجّلت توصية معلّقة — راجعها في التوصيات أعلاه.", "Recorded as a pending recommendation — review it in Recommendations above.")
          : `${result.command}: ${result.applied ? T("طُبّق", "applied") : T("سُجّل كتوجيه (لا إنفاق)", "recorded as directive (no spend)")}${result.recalc && result.recalc.target ? ` · target ${result.recalc.target}` : ""}${result.effect && result.effect.campaignsChanged != null ? ` · ${result.effect.campaignsChanged} campaign(s)` : ""}`) : (result.error || "failed")}
      </div> : null}
    </div></Card>
  );
}

// What each director can actually do — a plain one-liner helper shown above the chat (matches each
// director's real exclusive domain; not marketing copy).
const DIRECTOR_CAN_DO = {
  revenue: ["يضبط الأهداف، يختار التركيز، يتوقّع الإيراد، ويحدّد ماذا نبيع.", "Set targets, choose focus, forecast revenue, and decide what to sell."],
  sales: ["يرتّب أولوية الصفقات، يدير خطّ البيع، ويدفع المتابعات للإغلاق.", "Prioritize deals, manage the pipeline, and push follow-ups to close."],
  marketing: ["يدير التواصل عبر واتساب وإنستغرام وماسنجر وتيك توك ويستهدف الجمهور الصحيح.", "Run messaging outreach on WhatsApp/Instagram/Messenger/TikTok and target the right audience."],
  research: ["يبحث المنافسين والسوق وما يطلبه المشترون.", "Research competitors, markets, and what buyers want."],
  customer_success: ["يتابع صحّة العملاء، يمنع التسرّب، ويجد فرص البيع الإضافي.", "Track customer health, prevent churn, and find upsells."],
  cto: ["يراقب صحّة النظام، التكاملات، النشر، وما يجب إصلاحه.", "Watch system health, integrations, deployment, and what to fix."],
  operations: ["يكشف الاختناقات، يوازن الأحمال، ويبسّط العمليات.", "Find bottlenecks, balance workload, and streamline operations."],
  data: ["يحوّل البيانات الحقيقية إلى رؤى: القمع، الاعتراضات، أداء الوكلاء.", "Turn real data into insight: the funnel, objections, and agent performance."],
};
// Suggested prompts per director — a mix of questions and commands. Each chip sends a REAL message to
// the directorChat endpoint (no fake/canned answers). Commands become pending recommendations.
const DIRECTOR_PROMPTS = {
  revenue: [["ما فجوة الإيراد هذا الشهر؟", "What's our revenue gap this month?"], ["ركّز على عملاء المؤسسات", "Focus on enterprise customers"], ["أي منتج أكثر ربحية؟", "Which product is most profitable?"], ["ارفع الهدف الشهري إلى 750 ألف", "Raise the monthly target to 750k"]],
  sales: [["أي الصفقات نغلقها أولاً؟", "Which deals should we close first?"], ["رتّب أولوية عملاء اللوجستيات", "Prioritize logistics leads"], ["كيف حال خطّ البيع؟", "How is the pipeline doing?"], ["ادفع أكثر في المتابعات", "Push harder on follow-ups"]],
  marketing: [["ما حملة التواصل التالية؟", "What outreach campaign should we launch next?"], ["ركّز التواصل على متاجر شوبيفاي", "Focus outreach on Shopify stores"], ["أي قناة تؤدّي أفضل؟", "Which channel performs best?"], ["أوقف الحملات ضعيفة الأداء", "Pause low-performing campaigns"]],
  research: [["ابحث أكبر منافس لدينا", "Research our top competitor"], ["ماذا يطلب المشترون؟", "What are buyers asking for?"], ["جد قطاعاً جديداً نستهدفه", "Find a new vertical to target"], ["لخّص سوق اللوجستيات", "Summarize the logistics market"]],
  data: [["اعرض قمع المبيعات", "Show the sales funnel"], ["أكثر اعتراض يكلّفنا الصفقات؟", "Top objection costing us deals?"], ["أي وكيل أداؤه ضعيف؟", "Which agent is underperforming?"], ["أين نخسر الإيراد؟", "Where are we losing revenue?"]],
  customer_success: [["أي عملاء مهدّدون بالتسرّب؟", "Which customers are at risk of churn?"], ["من جاهز للبيع الإضافي؟", "Who is ready for an upsell?"], ["ما صحّة قاعدة عملائنا؟", "How healthy is our customer base?"], ["أعطِ أولوية لتهيئة الحسابات الجديدة", "Prioritize onboarding for new accounts"]],
  cto: [["ما الذي يعيق النشر؟", "What's blocking deployment?"], ["أي التكاملات تفشل؟", "Which integrations are failing?"], ["هل النظام بصحّة جيدة؟", "Is the system healthy?"], ["ما أول ما يجب إصلاحه؟", "What should we fix first?"]],
  operations: [["ما الذي يبطئنا؟", "What's slowing us down?"], ["أين الاختناقات؟", "Where are the bottlenecks?"], ["كيف توزيع أحمال الفريق؟", "How is the team's workload?"], ["بسّط عمليتنا", "Streamline our process"]],
};

// DirectorChat — Part 4: a REAL chat per director, redesigned to feel like ChatGPT/Claude — the manager
// is a NAMED person (avatar + name), large conversation area, clean message hierarchy (avatar + name on
// each manager reply), a rounded input with a send button, contextual follow-up suggestions, and a clear
// recommendation card. A question is answered by the exec brain; a command becomes a pending
// recommendation + Assem awareness + cross-director alignment (no auto-execute). Reuse-only — same endpoint.
function DirectorChat({ id, lang }) {
  const T = (ar, en) => (lang === "ar" ? ar : en);
  const [q, setQ] = useHeadState("");
  const [log, setLog] = useHeadState([]);   // [{role, text, result}]
  const [busy, setBusy] = useHeadState(false);
  const scrollRef = React.useRef(null);
  useHeadEffect(() => { if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight; }, [log, busy]);
  const dmeta = HEAD_DIRECTORS.find((d) => d[0] === id) || [id, id, id, "sparkles"];
  const dirName = lang === "ar" ? dmeta[2] : dmeta[1];
  const dirIcon = dmeta[3];
  const canDo = DIRECTOR_CAN_DO[id];
  const prompts = DIRECTOR_PROMPTS[id] || [];
  const send = (preset) => {
    const text = (preset || q).trim(); if (!text || busy) return;
    setBusy(true); setLog((l) => [...l, { role: "founder", text }]); setQ("");
    API.assem.directorChat(id, text, lang).then((r) => {
      setLog((l) => [...l, { role: "director", text: r.answer || "", result: r }]);
    }).catch((e) => setLog((l) => [...l, { role: "director", text: T("تعذّر الإرسال", "Could not send") + ": " + e.message }])).finally(() => setBusy(false));
  };
  // EXECUTION CHAIN — approve/reject a pending recommendation right here. Approving RUNS the suggested
  // founder command (real audited settings change) and records the outcome; the result is shown inline.
  const approve = (i, decisionId, status) => {
    if (!decisionId) return;
    setLog((l) => l.map((m, j) => (j === i ? { ...m, approving: status } : m)));
    API.assem.approveDecision(decisionId, status)
      .then((r) => setLog((l) => l.map((m, j) => (j === i ? { ...m, approving: null, approval: { status, result: r } } : m))))
      .catch((e) => setLog((l) => l.map((m, j) => (j === i ? { ...m, approving: null, approval: { status, error: e.message } } : m))));
  };
  const avatar = (size) => <div style={{ width: size, height: size, borderRadius: size / 3, background: "var(--color-primary)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}><Icon name={dirIcon} size={Math.round(size * 0.52)} style={{ color: "#fff" }} /></div>;
  return (
    <Card flush>
      {/* Header — the manager as a NAMED person, with a one-line capability + approval reminder. */}
      <div className="row between" style={{ padding: "12px 16px", borderBottom: "1px solid var(--border-1)", gap: 10, alignItems: "center" }}>
        <div className="row" style={{ gap: 10, minWidth: 0, alignItems: "center" }}>
          {avatar(36)}
          <div className="col" style={{ gap: 1, minWidth: 0 }}>
            <b style={{ fontSize: 14 }}>{dirName}</b>
            {canDo ? <span className="subtle" style={{ fontSize: 11.5, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", maxWidth: 360 }}>{lang === "ar" ? canDo[0] : canDo[1]}</span> : null}
          </div>
        </div>
        <span className="subtle" style={{ fontSize: 10.5, color: "var(--color-orange)", flexShrink: 0, textAlign: "end", maxWidth: 150, lineHeight: 1.35 }}>🔑 {T("توجيهاتك تُعتمد قبل التنفيذ", "Your directions need your approval")}</span>
      </div>
      {/* Conversation — large, readable, ChatGPT-style hierarchy. */}
      <div ref={scrollRef} style={{ minHeight: 320, maxHeight: "58vh", overflowY: "auto", padding: 16, display: "flex", flexDirection: "column", gap: 16 }}>
        {!log.length ? (
          <div className="col" style={{ gap: 12, alignItems: "center", textAlign: "center", padding: "24px 8px", margin: "auto 0" }}>
            <div style={{ width: 50, height: 50, borderRadius: 15, background: "var(--color-primary-tint-soft)", display: "flex", alignItems: "center", justifyContent: "center" }}><Icon name={dirIcon} size={25} style={{ color: "var(--color-secondary)" }} /></div>
            <div style={{ fontSize: 14.5, fontWeight: 700 }}>{T("تحدّث مع " + dirName, "Talk to the " + dirName)}</div>
            <div className="subtle" style={{ fontSize: 12.5, maxWidth: 420, lineHeight: 1.55 }}>{T("اسأله سؤالاً أو أعطه توجيهاً. التوجيهات تُسجَّل كتوصيات معلّقة تعتمدها — لا تنفيذ تلقائي.", "Ask a question or give a direction. Directions become pending recommendations you approve — nothing runs automatically.")}</div>
          </div>
        ) : log.map((m, i) => (
          m.role === "founder" ? (
            <div key={i} style={{ alignSelf: "flex-end", maxWidth: "85%" }}>
              <div style={{ fontSize: 13, lineHeight: 1.55, padding: "10px 14px", borderRadius: "16px 16px 4px 16px", background: "var(--color-primary)", color: "#fff", whiteSpace: "pre-wrap" }}>{m.text}</div>
            </div>
          ) : (
            <div key={i} className="row" style={{ gap: 9, alignItems: "flex-start", maxWidth: "92%" }}>
              {avatar(28)}
              <div className="col" style={{ gap: 6, minWidth: 0 }}>
                <span style={{ fontSize: 11, fontWeight: 700, color: "var(--fg-3)" }}>{dirName}</span>
                <div style={{ fontSize: 13, lineHeight: 1.6, padding: "10px 14px", borderRadius: "4px 16px 16px 16px", background: "var(--bg-2)", border: "1px solid var(--border-1)", color: "var(--fg-1)", whiteSpace: "pre-wrap" }}>{m.text}</div>
                {m.result && m.result.mode === "command" && m.result.pendingDecisionId ? (
                  <div className="col" style={{ gap: 8, padding: "9px 12px", borderRadius: 11, background: "var(--color-success-soft)", color: "#15803D", border: "1px solid #BBF7D0" }}>
                    {!m.approval ? (
                      <React.Fragment>
                        <div className="row" style={{ gap: 8, alignItems: "flex-start", fontSize: 11.5 }}>
                          <Icon name="checkcircle" size={14} style={{ flexShrink: 0, marginTop: 1 }} />
                          <div className="col" style={{ gap: 2 }}>
                            <b>{T("توصية معلّقة — اعتمدها للتنفيذ", "Pending recommendation — approve to execute")}</b>
                            {m.result.suggestedFounderCommand && m.result.suggestedFounderCommand.valid
                              ? <span style={{ color: "var(--fg-3)" }}>{T("سيُطبَّق", "Will apply")}: {String(m.result.suggestedFounderCommand.type).replace(/_/g, " ")}{m.result.suggestedFounderCommand.value != null ? " = " + m.result.suggestedFounderCommand.value : ""}</span>
                              : <span style={{ color: "var(--fg-3)" }}>{T("ملاحظة استراتيجية بلا إجراء تلقائي", "Strategic note — no automatic action")}</span>}
                            {m.result.alignment && m.result.alignment.length ? <span style={{ color: "var(--fg-3)" }}>{T("بالتنسيق مع", "Coordinated with")}: {m.result.alignment.map((a) => a.director).join("، ")}</span> : null}
                          </div>
                        </div>
                        <div className="row" style={{ gap: 8 }}>
                          <button className="btn btn--sm" style={{ background: "var(--color-secondary)", color: "#fff", border: "none" }} disabled={!!m.approving} onClick={() => approve(i, m.result.pendingDecisionId, "approved")}>{m.approving === "approved" ? T("جارٍ…", "Running…") : T("اعتمد ونفّذ", "Approve & execute")}</button>
                          <button className="btn btn--sm btn--subtle" disabled={!!m.approving} onClick={() => approve(i, m.result.pendingDecisionId, "rejected")}>{T("ارفض", "Reject")}</button>
                        </div>
                      </React.Fragment>
                    ) : (
                      <div className="row" style={{ gap: 8, alignItems: "flex-start", fontSize: 12 }}>
                        <Icon name={m.approval.error || m.approval.status === "rejected" ? "alert" : "checkcircle"} size={14} style={{ flexShrink: 0, marginTop: 1 }} />
                        <div className="col" style={{ gap: 1 }}>
                          {m.approval.error ? <b style={{ color: "var(--color-danger)" }}>{T("تعذّر الاعتماد", "Could not apply")}: {m.approval.error}</b>
                            : m.approval.status === "rejected" ? <b>{T("رُفِضت — لم يُنفَّذ شيء", "Rejected — nothing executed")}</b>
                            : (m.approval.result && m.approval.result.executed) ? <b>{T("اعتُمد ونُفِّذ", "Approved & executed")}{m.approval.result.command ? " · " + String(m.approval.result.command).replace(/_/g, " ") : ""}{m.approval.result.applied === false ? T(" (سُجِّل كتوجيه)", " (recorded as directive)") : ""}</b>
                            : <b>{T("اعتُمد", "Approved")}</b>}
                          {m.approval.result && m.approval.result.note ? <span style={{ color: "var(--fg-3)" }}>{lang === "ar" ? m.approval.result.note.ar : m.approval.result.note.en}</span> : null}
                        </div>
                      </div>
                    )}
                  </div>
                ) : (m.result && m.result.mode === "command") ? (
                  <div className="row" style={{ gap: 8, fontSize: 11.5, padding: "9px 12px", borderRadius: 11, background: "var(--color-success-soft)", color: "#15803D", border: "1px solid #BBF7D0", alignItems: "flex-start" }}>
                    <Icon name="checkcircle" size={14} style={{ flexShrink: 0, marginTop: 1 }} />
                    <b>{T("سُجّلت توصية معلّقة لاعتمادك", "Pending recommendation recorded")}</b>
                  </div>
                ) : null}
              </div>
            </div>
          )
        ))}
        {busy ? (
          <div className="row" style={{ gap: 9, alignItems: "center" }}>
            {avatar(28)}
            <div style={{ fontSize: 13, color: "var(--fg-3)", padding: "10px 14px", borderRadius: "4px 16px 16px 16px", background: "var(--bg-2)", border: "1px solid var(--border-1)" }}>{dirName} {T("يكتب…", "is typing…")}</div>
          </div>
        ) : null}
      </div>
      {/* Follow-up suggestions — fewer once a conversation is going. */}
      {prompts.length && !busy ? (
        <div className="chipscroll" style={{ gap: 7, padding: "10px 14px 2px" }}>
          {(log.length ? prompts.slice(0, 3) : prompts).map(([ar, en], i) => <button key={i} className="btn btn--sm btn--subtle" style={{ flexShrink: 0, fontSize: 12 }} onClick={() => send(lang === "ar" ? ar : en)}>{lang === "ar" ? ar : en}</button>)}
        </div>
      ) : null}
      {/* Input — a single rounded field + a circular send button, like ChatGPT/Claude. */}
      <div className="row" style={{ padding: 12 }}>
        <div className="row" style={{ flex: 1, alignItems: "center", gap: 6, background: "var(--bg-2)", border: "1px solid var(--border-1)", borderRadius: 999, paddingInline: "14px 5px" }}>
          <input className="input dirchat-input" style={{ flex: 1, fontSize: 13, border: "none", background: "transparent", padding: "9px 0", boxShadow: "none" }} dir="auto" placeholder={T("اكتب رسالة لـ" + dirName + "…", "Message the " + dirName + "…")} value={q} onChange={(e) => setQ(e.target.value)} onKeyDown={(e) => e.key === "Enter" && send()} />
          <button onClick={() => send()} disabled={busy || !q.trim()} aria-label={T("إرسال", "Send")} style={{ width: 34, height: 34, borderRadius: 999, border: "none", background: q.trim() && !busy ? "var(--color-primary)" : "var(--border-1)", color: "#fff", cursor: q.trim() && !busy ? "pointer" : "default", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}><Icon name="arrowRight" size={16} /></button>
        </div>
      </div>
    </Card>
  );
}

// Director TABS — a horizontal, ChatGPT-style "switch conversation" strip (replaces the old side-list).
// Switching a director feels like switching chats: instant, no reload.
// ORGANIZATION — the company hierarchy (Part: Organization screen). ASSEM (CEO) over 6 directors, each
// leading its agents. 100% real, read-only, over headOrganization() (agents grouped by authored ownership).
// Answers the UX questions: where am I (the company), what (talk to a manager), why (they run the work).
const ORG_ICON = { revenue: "trending", marketing: "message", customer_success: "heart", operations: "grid", cto: "cpu", data: "layers" };
function OrganizationPanel({ org, lang, onPick }) {
  const T = (ar, en) => (lang === "ar" ? ar : en);
  if (!org) return <Card><div className="skel" style={{ height: 140, borderRadius: 10 }} /></Card>;
  const dirs = org.directors || [];
  const managers = dirs.filter((d) => d.id !== "assem");
  const L = (d) => (d.label && (lang === "ar" ? d.label.ar : d.label.en)) || d.id;
  return (
    <div className="col" style={{ gap: 12 }}>
      <Card><div className="col" style={{ gap: 4, padding: 10 }}>
        <div className="row" style={{ gap: 8, alignItems: "center" }}><Icon name="sparkles" /><strong>{T("الهيكل التنظيمي للشركة", "Company Organization")}</strong></div>
        <div className="subtle" style={{ fontSize: 12 }}>{T("عاصم (المدير التنفيذي) فوق 6 مديرين، وكل مدير يقود وكلاءه. اضغط أي مدير لتتحدّث معه.", "ASSEM (CEO) over 6 directors, each leading their agents. Click any manager to talk to them.")}</div>
      </div></Card>
      <Card><div className="between" style={{ padding: 12, gap: 10, flexWrap: "wrap", borderInlineStart: "3px solid var(--color-secondary)" }}>
        <div className="row" style={{ gap: 8 }}><Icon name="sparkles" /><div><strong>{T("عاصم (المدير التنفيذي)", "ASSEM (CEO)")}</strong><div className="subtle" style={{ fontSize: 11 }}>{T("يدير الشركة عبر المديرين — لا يدير محادثات البيع.", "Runs the company through the directors — never handles sales conversations.")}</div></div></div>
        <Button size="sm" variant="ghost" onClick={() => onPick("assem")}>{T("تحدّث مع عاصم", "Talk to Assem")}</Button>
      </div></Card>
      <div className="col" style={{ gap: 8 }}>
        {managers.map((d) => {
          const tone = HEAD_STATUS_TONE[d.status] || "var(--fg-3)";
          const agents = d.agents || [];
          return (
            <Card key={d.id}><div className="col" style={{ gap: 8, padding: 10 }}>
              <div className="between" style={{ gap: 8, flexWrap: "wrap" }}>
                <div className="row" style={{ gap: 8 }}><Icon name={ORG_ICON[d.id] || "grid"} size={16} /><strong style={{ fontSize: 13.5 }}>{L(d)}</strong><span className="sdot" style={{ background: tone }} title={d.status} /><span className="subtle" style={{ fontSize: 11 }}>{agents.length} {T("وكيل", "agents")}</span></div>
                <Button size="sm" variant="ghost" onClick={() => onPick(d.id)}>{T("تحدّث", "Talk")}</Button>
              </div>
              {agents.length ? (
                <div className="row" style={{ gap: 6, flexWrap: "wrap" }}>
                  {agents.slice(0, 12).map((a) => (
                    <span key={a.id} className="row" style={{ gap: 5, fontSize: 11.5, padding: "3px 9px", borderRadius: 999, background: "var(--bg-2)", border: "1px solid var(--border-1)" }}>
                      <Icon name="bot" size={12} /><span>{a.name}</span>{a.role ? <span className="subtle" style={{ fontSize: 10 }}>· {a.role}</span> : null}
                    </span>
                  ))}
                </div>
              ) : <div className="subtle" style={{ fontSize: 11.5 }}>{T("لا وكلاء معيّنون بعد — عيّنهم من «وكلاء الذكاء».", "No agents assigned yet — assign them in AI Agents.")}</div>}
            </div></Card>
          );
        })}
      </div>
      <div className="subtle" style={{ fontSize: 10.5, color: "var(--color-orange)" }}>{T("هيكل حقيقي — الوكلاء يتبعون مديرهم؛ المديرون يوصون والمؤسس يعتمد.", "Real hierarchy — agents report to their director; directors recommend, the founder approves.")}</div>
    </div>
  );
}

function DirectorTabs({ active, onPick, byId, lang }) {
  const TT = (ar, en) => (lang === "ar" ? ar : en);
  return (
    <div className="chipscroll" style={{ gap: 6, marginBottom: 14, paddingBottom: 2 }}>
      <button key="org" onClick={() => onPick("org")} className="row" style={{ gap: 7, flexShrink: 0, padding: "8px 13px", borderRadius: 999, border: "1px solid " + (active === "org" ? "var(--color-secondary)" : "var(--border-1)"), background: active === "org" ? "var(--color-primary-tint-soft)" : "#fff", cursor: "pointer", fontSize: 12.5, fontWeight: active === "org" ? 700 : 600, color: active === "org" ? "var(--color-secondary)" : "var(--fg-2)" }}>
        <Icon name="grid" size={15} /><span>{TT("الهيكل", "Organization")}</span>
      </button>
      {HEAD_DIRECTORS.map(([id, en, ar, icon]) => {
        const d = byId(id); const tone = d ? (HEAD_STATUS_TONE[d.status] || "var(--fg-3)") : "var(--fg-3)";
        const on = active === id;
        return (
          <button key={id} onClick={() => onPick(id)} className="row" style={{ gap: 7, flexShrink: 0, padding: "8px 13px", borderRadius: 999, border: "1px solid " + (on ? "var(--color-secondary)" : "var(--border-1)"), background: on ? "var(--color-primary-tint-soft)" : "#fff", cursor: "pointer", fontSize: 12.5, fontWeight: on ? 700 : 600, color: on ? "var(--color-secondary)" : "var(--fg-2)" }}>
            <Icon name={icon} size={15} />
            <span>{lang === "ar" ? ar : en}</span>
            {id !== "assem" && d ? <span className="sdot" style={{ background: tone }} title={d.status} /> : null}
          </button>
        );
      })}
    </div>
  );
}

// Director HISTORY — recent Company-Memory events owned by this director's department (honest empty state,
// reuse-only: API.assem.companyMemory). Departments without typed events show an honest "no history yet".
const DIR_DEPT = { revenue: "revenue", sales: "sales", marketing: "marketing", research: "research", customer_success: "customer_success", cto: "cto", operations: "operations", data: "data" };
const MEM_LABEL = { won_deal: ["صفقة رابحة", "Won deal"], lost_deal: ["صفقة خاسرة", "Lost deal"], churn: ["تسرّب", "Churn"], renewal: ["تجديد", "Renewal"], campaign_result: ["نتيجة حملة", "Campaign result"], product_launch: ["إطلاق منتج", "Product launch"], director_decision: ["قرار مدير", "Director decision"], founder_decision: ["قرار المؤسس", "Founder decision"], market_insight: ["رؤية سوق", "Market insight"] };
function DirectorHistory({ id, lang }) {
  const T = (ar, en) => (lang === "ar" ? ar : en);
  const [mem, setMem] = useHeadState(null);
  useHeadEffect(() => { setMem(null); API.assem.companyMemory(null, 100).then((r) => setMem(r || { memories: [] })).catch(() => setMem({ memories: [] })); }, [id]);
  if (!mem) return <Card><div className="skel" style={{ height: 40, borderRadius: 8 }} /></Card>;
  const dept = DIR_DEPT[id];
  const items = (mem.memories || []).filter((m) => m.director === id || (dept && m.department === dept)).slice(0, 6);
  return (
    <Card><div className="col" style={{ gap: 6, padding: 4 }}>
      <b style={{ fontSize: 13 }}>{T("السجل", "History")}</b>
      {items.length ? items.map((m, i) => { const lab = MEM_LABEL[m.type] || [m.type, m.type]; return (
        <div key={i} className="row" style={{ gap: 7, fontSize: 12, paddingTop: i ? 5 : 0, borderTop: i ? "1px solid var(--border-1)" : "none" }}>
          <span style={{ fontSize: 10.5, padding: "1px 7px", borderRadius: 6, background: "var(--bg-2)", border: "1px solid var(--border-1)", flexShrink: 0 }}>{lang === "ar" ? lab[0] : lab[1]}</span>
          <span style={{ minWidth: 0, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{m.title || ""}</span>
          {m.date ? <span className="subtle" style={{ marginInlineStart: "auto", fontSize: 10.5, flexShrink: 0 }}>{String(m.date).slice(0, 10)}</span> : null}
        </div>
      ); }) : <div className="subtle" style={{ fontSize: 12 }}>{T("لا سجل بعد لهذا المدير — يمتلئ مع كل صفقة/تجديد/قرار حقيقي.", "No history yet for this manager — it fills as real deals, renewals and decisions happen.")}</div>}
    </div></Card>
  );
}

// P3·P3 — Subagents panel: this director's REAL agents (grouped by authored ownership). Each card shows
// name / role / status / readiness / certification / last-activity / current-objective from REAL engines
// (agentCommandCenter + agentReadiness + headOrganization). Manager commands render ONLY where a real route
// exists — Review conversations (nav), Train (Learning Hub), Reassign (PATCH agent.director). Objective-assign,
// per-agent escalate, and disable/pause are NOT rendered (no per-agent route) — documented in the audit report.
const SUBAGENT_DIRECTORS = [["revenue", "مدير الإيراد", "Revenue"], ["marketing", "مدير القنوات", "Channel"], ["customer_success", "نجاح العملاء", "Customer Success"], ["operations", "العمليات", "Operations"], ["cto", "التقني", "CTO"], ["data", "البيانات", "Data"]];
function SubagentCard({ a, cc, lang, go }) {
  const T = (ar, en) => (lang === "ar" ? ar : en);
  const [rd, setRd] = useHeadState(null);
  const [dir, setDir] = useHeadState(a.director || "");
  const [busy, setBusy] = useHeadState(false);
  useHeadEffect(() => { let on = true; API.metrics.agentReadiness(a.id).then((r) => on && setRd(r)).catch(() => {}); return () => { on = false; }; }, [a.id]);
  const reassign = (d) => { setDir(d); setBusy(true); API.agents.update(a.id, { director: d }).catch(() => {}).finally(() => setBusy(false)); };
  const status = (cc && cc.status) || null;
  const obj = cc && Array.isArray(cc.currentObjectives) && cc.currentObjectives[0] ? (cc.currentObjectives[0].title || String(cc.currentObjectives[0].type || "").replace(/_/g, " ")) : null;
  const last = cc && cc.lastActiveAt ? (() => { try { return new Date(cc.lastActiveAt).toLocaleDateString(); } catch (e) { return null; } })() : null;
  const readyTone = rd && rd.status === "READY" ? "success" : rd && rd.status === "PARTIALLY_READY" ? "warning" : rd && rd.status === "NOT_READY" ? "danger" : "neutral";
  const cert = rd && rd.certification;
  const navTo = (screen, tab) => { try { window.__navTab = { screen, tab }; window.dispatchEvent(new CustomEvent("maxab:navtab", { detail: { screen, tab } })); } catch (e) {} if (go) go(screen); };
  return (
    <div className="col" style={{ gap: 7, padding: "10px 12px", borderRadius: "var(--radius-md)", background: "var(--bg-2)", border: "1px solid var(--border-1)" }}>
      <div className="between" style={{ gap: 8, flexWrap: "wrap" }}>
        <div className="row" style={{ gap: 7, alignItems: "center" }}><Icon name="bot" size={14} /><b style={{ fontSize: 13 }}>{a.name}</b>{a.role ? <span className="subtle" style={{ fontSize: 11 }}>· {a.role}</span> : null}</div>
        {status ? <Badge tone={status === "active" || status === "working" || status === "on_track" ? "success" : status === "blocked" || status === "overloaded" ? "danger" : "neutral"}>{String(status).replace(/_/g, " ")}</Badge> : null}
      </div>
      <div className="row" style={{ gap: 10, flexWrap: "wrap", fontSize: 11, alignItems: "center" }}>
        <span className="row" style={{ gap: 4, alignItems: "center" }}><b>{T("الجاهزية", "Readiness")}:</b> {rd ? <Badge tone={readyTone}>{String(rd.status || "—").replace(/_/g, " ")}</Badge> : "…"}</span>
        <span><b>{T("الشهادة", "Cert")}:</b> {cert ? (cert.certified ? (cert.level || "—") : T("غير معتمد", "Uncertified")) : "…"}</span>
        {last ? <span className="subtle"><b>{T("آخر نشاط", "Last active")}:</b> {last}</span> : <span className="subtle">{T("لا نشاط بعد", "No activity yet")}</span>}
      </div>
      {obj ? <div className="subtle" style={{ fontSize: 11 }}><b>{T("الهدف الحالي", "Current objective")}:</b> {obj}</div> : <div className="subtle" style={{ fontSize: 11 }}>{T("لا هدف مُسند — يُشتق من قائمة المهام.", "No assigned objective — derived from the task queue.")}</div>}
      <div className="row" style={{ gap: 6, flexWrap: "wrap", alignItems: "center" }}>
        <Button size="sm" variant="ghost" onClick={() => navTo("conversations")}>{T("راجع المحادثات", "Review conversations")}</Button>
        <Button size="sm" variant="ghost" onClick={() => navTo("agents", "learning")}>{T("درّب", "Train")}</Button>
        <span className="row" style={{ gap: 4, alignItems: "center" }}><span className="subtle" style={{ fontSize: 10.5 }}>{T("أعد الإسناد", "Reassign")}:</span>
          <select className="input" style={{ fontSize: 11, padding: "3px 6px" }} value={dir} disabled={busy} onChange={(e) => reassign(e.target.value)}>
            {SUBAGENT_DIRECTORS.map(([k, ar, en]) => <option key={k} value={k}>{lang === "ar" ? ar : en}</option>)}
          </select>
        </span>
      </div>
    </div>
  );
}
function SubagentsPanel({ id, lang, go }) {
  const T = (ar, en) => (lang === "ar" ? ar : en);
  const [org, setOrg] = useHeadState(null);
  const [cc, setCc] = useHeadState(null);
  useHeadEffect(() => { API.assem.head(lang).then(setOrg).catch(() => setOrg({ directors: [] })); API.assem.agentCommandCenter().then(setCc).catch(() => setCc(null)); }, []);
  if (!org) return <Card><div className="skel" style={{ height: 80, borderRadius: 10 }} /></Card>;
  const dir = (org.directors || []).find((d) => d.id === id);
  const agents = (dir && dir.agents) || [];
  const ccById = {};
  for (const x of (cc && Array.isArray(cc.agents) ? cc.agents : [])) { if (x && x.agentId) ccById[x.agentId] = x; }
  if (!agents.length) return <Card><EmptyState icon="bot" title={T("لا وكلاء معيّنون", "No agents assigned")} subtitle={T("عيّن وكلاء لهذا المدير من «وكلاء الذكاء».", "Assign agents to this director in AI Agents.")} /></Card>;
  return (
    <div className="col" style={{ gap: 8 }}>
      {agents.map((a) => <SubagentCard key={a.id} a={a} cc={ccById[a.id]} lang={lang} go={go} />)}
      <div className="subtle" style={{ fontSize: 10.5, color: "var(--color-orange)" }}>{T("الأوامر المعروضة حقيقية فقط — إسناد الأهداف/التعطيل لكل وكيل غير مُفعّلين بعد.", "Only real commands are shown — per-agent objective-assign / disable are not wired yet (see the manager-authority report).")}</div>
    </div>
  );
}

// P11 — Director KPI Scorecard: the 6-axis 0-100 card — "how is this director performing?" at a glance.
function DirectorScorecardCard({ id, lang }) {
  const T = (ar, en) => (lang === "ar" ? ar : en);
  const [d, setD] = useHeadState(null);
  useHeadEffect(() => { setD(null); API.assem.directorScorecard(id, lang).then(setD).catch(() => setD({ error: true })); }, [id]);
  if (!d) return <Card><div className="skel" style={{ height: 70, borderRadius: 10 }} /></Card>;
  if (d.error) return null;
  const s = d.scores || {};
  const AX = [["overall", T("الإجمالي", "Overall")], ["performance", T("الأداء", "Performance")], ["learning", T("التعلّم", "Learning")], ["execution", T("التنفيذ", "Execution")], ["team", T("الفريق", "Team")], ["revenueImpact", T("أثر الإيراد", "Revenue impact")]];
  const col = (v) => v == null ? "var(--fg-4)" : v >= 70 ? "var(--color-green)" : v >= 45 ? "var(--color-orange)" : "var(--color-danger)";
  return (
    <Card><div className="col" style={{ gap: 8, padding: 4 }}>
      <div className="between"><b style={{ fontSize: 13 }}>{T("بطاقة أداء المدير", "Director scorecard")}</b><span className="subtle" style={{ fontSize: 11 }}>{d.confidence === "measured" ? T("مقاسة", "measured") : T("بيانات غير كافية", "not enough data")}</span></div>
      <div className="row" style={{ gap: 8, flexWrap: "wrap" }}>
        {AX.map(([k, label]) => (
          <div key={k} className="card" style={{ padding: 9, flex: "1 1 90px", minWidth: 82, textAlign: "center", border: k === "overall" ? "1px solid var(--color-secondary)" : undefined }}>
            <div className="subtle" style={{ fontSize: 10 }}>{label}</div>
            <div style={{ fontSize: 18, fontWeight: 800, color: col(s[k]) }}>{s[k] == null ? "—" : s[k]}</div>
          </div>
        ))}
      </div>
      {d.trainingGap ? <span className="subtle" style={{ fontSize: 11, color: "var(--color-orange)" }}>{T("فجوة تدريب", "Training gap")}: {d.trainingGap}</span> : null}
    </div></Card>
  );
}

// P10 — Director Learning Accountability: what this director + team learned, what changed, approval-gated.
function DirectorLearningCard({ id, lang }) {
  const T = (ar, en) => (lang === "ar" ? ar : en);
  const [d, setD] = useHeadState(null);
  useHeadEffect(() => { setD(null); API.assem.directorLearning(id, lang).then(setD).catch(() => setD({ error: true })); }, [id]);
  if (!d) return <Card><div className="skel" style={{ height: 60, borderRadius: 10 }} /></Card>;
  if (d.error) return null;
  if (d.status === "not_enough_data") return <Card><div className="col" style={{ gap: 4, padding: 6 }}><b style={{ fontSize: 13 }}>{T("مساءلة التعلّم", "Learning accountability")}</b><span className="subtle" style={{ fontSize: 11.5 }}>{T("لا دروس مسجّلة لهذا المدير بعد — تظهر عند تسجيل نتائج حقيقية.", "No recorded lessons for this director yet — they appear as real outcomes are recorded.")}</span></div></Card>;
  return (
    <Card><div className="col" style={{ gap: 6, padding: 6 }}>
      <div className="between"><b style={{ fontSize: 13 }}>{T("مساءلة التعلّم", "Learning accountability")}</b><span className="subtle" style={{ fontSize: 11 }}>{T("قرارات", "decisions")}: {d.decisionsOwned} · ✓{d.succeeded} ✗{d.failed}</span></div>
      {(d.whatILearned || []).slice(0, 4).map((l, i) => (<div key={i} style={{ fontSize: 12 }}>• {l.learned && l.learned !== "—" ? l.learned : (l.what || "—")}</div>))}
      {(d.whatChanged || []).length ? <div className="subtle" style={{ fontSize: 11 }}>{T("ما تغيّر", "What changed")}: {d.whatChanged.slice(0, 3).map((c) => `${c.decision} (${c.outcome})`).join(" · ")}</div> : null}
      <span className="subtle" style={{ fontSize: 10.5, color: "var(--color-orange)" }}>{T("كل درس يحتاج موافقتك — لا تطبيق تلقائي.", "Every lesson needs your approval — nothing auto-applies.")}</span>
    </div></Card>
  );
}

// P7 — Director Team: subagent hierarchy (responsibilities/status/training/readiness/last-learning) + role map.
function DirectorTeamPanel({ id, lang, go }) {
  const T = (ar, en) => (lang === "ar" ? ar : en);
  const [d, setD] = useHeadState(null);
  useHeadEffect(() => { setD(null); API.assem.directorTeam(id, lang).then(setD).catch(() => setD({ error: true })); }, [id]);
  if (!d) return <Card><div className="skel" style={{ height: 80, borderRadius: 10 }} /></Card>;
  if (d.error || d.status === "not_enough_data") return <Card><EmptyState icon="bot" title={T("لا وكلاء معيّنون", "No agents assigned")} subtitle={T("عيّن وكلاء لهذا المدير من «وكلاء الذكاء».", "Assign agents to this director in AI Agents.")} /></Card>;
  const statusTone = (s) => s === "ready" ? "green" : s === "partial" ? "orange" : s === "not_ready" ? "danger" : "neutral";
  const pill = (v) => v == null ? "—" : v;
  return (
    <div className="col" style={{ gap: 8 }}>
      {d.roleMap ? (
        <Card><div className="col" style={{ gap: 5, padding: 6 }}>
          <b style={{ fontSize: 12.5 }}>{T("أدوار مراحل البيع", "Sales-stage roles")}</b>
          {d.roleMap.map((r, i) => (
            <div key={i} className="row between" style={{ fontSize: 12 }}>
              <span>{lang === "ar" ? r.role.ar : r.role.en}</span>
              <span style={{ color: r.assignment === "real_agent" ? "var(--color-green)" : "var(--color-orange)" }}>{r.coveredBy || T("موصى به — لا متخصّص", "recommended — no specialist")}</span>
            </div>
          ))}
        </div></Card>
      ) : null}
      {d.subagents.map((a) => (
        <Card key={a.id}><div className="col" style={{ gap: 4, padding: 8 }}>
          <div className="between"><b style={{ fontSize: 13 }}>{a.name}</b><Badge tone={statusTone(a.status)}>{a.status}</Badge></div>
          {a.responsibilities ? <span className="subtle" style={{ fontSize: 11.5 }}>{a.responsibilities}</span> : null}
          <div className="row" style={{ gap: 6, flexWrap: "wrap", fontSize: 11 }}>
            <Badge tone="neutral">{T("تدريب", "Training")} {pill(a.trainingScore)}</Badge>
            <Badge tone="neutral">{T("جاهزية", "Readiness")} {pill(a.readinessScore)}</Badge>
            {a.lastLearning ? <Badge tone="neutral">{T("آخر تعلّم", "Last learning")}: {a.lastLearning}</Badge> : null}
          </div>
        </div></Card>
      ))}
    </div>
  );
}

// P9 — Funnel ownership: per-stage owner / conversion / emotion / objection / action / responsible-agent.
function FunnelOwnershipCard({ lang }) {
  const T = (ar, en) => (lang === "ar" ? ar : en);
  const [d, setD] = useHeadState(null);
  useHeadEffect(() => { API.assem.funnelOwnership().then(setD).catch(() => setD({ error: true })); }, []);
  if (!d) return <Card><div className="skel" style={{ height: 80, borderRadius: 10 }} /></Card>;
  if (d.error) return null;
  return (
    <Card><div className="col" style={{ gap: 6, padding: 6 }}>
      <b style={{ fontSize: 13 }}>{T("ملكية القمع — كل مرحلة", "Funnel ownership — every stage")}</b>
      {(d.stages || []).map((s, i) => (
        <div key={i} className="col" style={{ gap: 2, paddingTop: i ? 6 : 0, borderTop: i ? "1px solid var(--border-1)" : "none" }}>
          <div className="between" style={{ fontSize: 12 }}>
            <b>{lang === "ar" ? s.ar : s.en} <span className="subtle">· {s.count}</span></b>
            <span className="subtle">{s.conversion == null ? "—" : s.conversion + "%"} {T("تحويل", "conv")}</span>
          </div>
          <div className="row" style={{ gap: 6, flexWrap: "wrap", fontSize: 10.5 }}>
            {s.responsibleAgent ? <Badge tone="neutral">{s.responsibleAgent.name}</Badge> : null}
            {s.emotionProfile && s.emotionProfile.length ? <Badge tone="lime">{s.emotionProfile[0].emotion}</Badge> : null}
            {s.topObjection ? <Badge tone="orange">{s.topObjection.key}</Badge> : null}
          </div>
          {s.recommendedAction ? <span className="subtle" style={{ fontSize: 10.5 }}>→ {lang === "ar" ? s.recommendedAction.ar : s.recommendedAction.en}</span> : null}
        </div>
      ))}
      <span className="subtle" style={{ fontSize: 10.5 }}>{T("يملكها مدير الإيراد", "Owned by the Revenue Director")}</span>
    </div></Card>
  );
}

// P12 — Company Operating View: who's performing / failing / needs-help / drives-revenue in 30 seconds.
function CompanyOperatingViewCard({ lang, onPick }) {
  const T = (ar, en) => (lang === "ar" ? ar : en);
  const [d, setD] = useHeadState(null);
  useHeadEffect(() => { API.assem.companyOperatingView(lang).then(setD).catch(() => setD({ error: true })); }, []);
  if (!d || d.error) return null;
  const a = d.answers || {};
  const lbl = (x) => x ? (lang === "ar" ? x.label.ar : x.label.en) : "—";
  const col = (v) => v == null ? "var(--fg-4)" : v >= 70 ? "var(--color-green)" : v >= 45 ? "var(--color-orange)" : "var(--color-danger)";
  return (
    <Card style={{ marginBottom: 12, border: "1px solid var(--color-primary)", background: "linear-gradient(180deg, var(--color-primary-tint-soft), #fff)" }}>
      <div className="col" style={{ gap: 8, padding: 8 }}>
        <b style={{ fontSize: 14 }}>{T("نظرة تشغيل الشركة", "Company operating view")}</b>
        <div className="row" style={{ gap: 6, flexWrap: "wrap", fontSize: 11.5 }}>
          {a.whoIsPerforming ? <span style={{ padding: "3px 9px", borderRadius: 7, background: "var(--color-success-soft, #e7f7ec)", color: "#15803D" }}>★ {T("الأفضل", "Top")}: {lbl(a.whoIsPerforming)} {a.whoIsPerforming.overall}</span> : null}
          {a.whoIsFailing ? <span style={{ padding: "3px 9px", borderRadius: 7, background: "var(--color-danger-soft, #FEF2F2)", color: "var(--color-danger)" }}>↓ {T("متعثّر", "Failing")}: {lbl(a.whoIsFailing)} {a.whoIsFailing.overall}</span> : null}
          {(a.whoNeedsHelp || []).length ? <span style={{ padding: "3px 9px", borderRadius: 7, background: "var(--color-orange-soft, #FFF7ED)", color: "var(--color-orange)" }}>⚑ {T("يحتاج مساعدة", "Needs help")}: {a.whoNeedsHelp.length}</span> : null}
          {a.whoGeneratesRevenue ? <span style={{ padding: "3px 9px", borderRadius: 7, background: "var(--bg-2)" }}>$ {lbl(a.whoGeneratesRevenue)}: {a.whoGeneratesRevenue.revenueImpact == null ? "—" : a.whoGeneratesRevenue.revenueImpact}</span> : null}
        </div>
        <div className="col" style={{ gap: 4 }}>
          {(d.directors || []).map((dir) => (
            <button key={dir.id} onClick={() => onPick && onPick(dir.id)} className="row between" style={{ gap: 8, padding: "7px 10px", borderRadius: 8, border: "1px solid var(--border-1)", background: "#fff", cursor: "pointer", textAlign: "start" }}>
              <span style={{ fontSize: 12.5 }}>{lang === "ar" ? dir.label.ar : dir.label.en} <span className="subtle">· {dir.teamSize} {T("وكلاء", "agents")}</span></span>
              <span className="row" style={{ gap: 8, alignItems: "center" }}>
                {dir.status === "blocked" || dir.status === "needs_attention" ? <Badge tone="orange">{dir.status}</Badge> : null}
                <b style={{ color: col(dir.overall) }}>{dir.overall == null ? "—" : dir.overall}</b>
              </span>
            </button>
          ))}
        </div>
        <span className="subtle" style={{ fontSize: 10.5 }}>{T("الشركة ← المديرون ← الفرق ← الإجراءات ← النتائج. للقراءة فقط.", "Company → Directors → Teams → Actions → Results. Read-only.")}</span>
      </div>
    </Card>
  );
}

// Phase 9 P3 — Director Training Impact: "did this director improve the team?" from snapshot deltas.
function DirectorTrainingImpactCard({ id, lang }) {
  const T = (ar, en) => (lang === "ar" ? ar : en);
  const [d, setD] = useHeadState(null);
  useHeadEffect(() => { setD(null); API.assem.directorTrainingImpact(id, lang).then(setD).catch(() => setD({ error: true })); }, [id]);
  if (!d) return <Card><div className="skel" style={{ height: 50, borderRadius: 10 }} /></Card>;
  if (d.error) return null;
  if (d.status === "not_enough_data") return <Card><div className="col" style={{ gap: 4, padding: 6 }}><b style={{ fontSize: 13 }}>{T("أثر التدريب على الفريق", "Team training impact")}</b><span className="subtle" style={{ fontSize: 11.5 }}>{T(d.note.ar, d.note.en)}</span></div></Card>;
  const chip = (label, v) => <span style={{ fontSize: 11.5, padding: "3px 9px", borderRadius: 7, background: "var(--bg-2)", border: "1px solid var(--border-1)" }}>{label}: <b style={{ color: v > 0 ? "var(--color-green)" : v < 0 ? "var(--color-danger)" : "inherit" }}>{v == null ? "—" : (v > 0 ? "+" : "") + v}</b></span>;
  return (
    <Card><div className="col" style={{ gap: 6, padding: 6 }}>
      <div className="between"><b style={{ fontSize: 13 }}>{T("هل حسّن هذا المدير الفريق؟", "Did this director improve the team?")}</b>{d.didImproveTeam ? <Badge tone="green">{T("نعم", "Yes")}</Badge> : <Badge tone="neutral">{T("لا يكفي", "No lift yet")}</Badge>}</div>
      <div className="subtle" style={{ fontSize: 11.5 }}>{d.agentsImproved}/{d.agentsTracked} {T("وكلاء تحسّنوا خلال", "agents improved over")} {d.spanDays} {T("يوماً", "days")}</div>
      <div className="row" style={{ gap: 6, flexWrap: "wrap" }}>{chip(T("الجودة", "Quality"), d.qualityDeltaAvg)}{chip(T("الإغلاق", "Close"), d.closeRateDelta)}{chip(T("الإنسانية", "Humanity"), d.humanityDelta)}{chip(T("الثقة", "Trust"), d.trustDelta)}</div>
    </div></Card>
  );
}

// Phase 9 P10 — Company Evolution: This-Week / Month / Quarter learning + revenue + humanity/trust growth.
function CompanyEvolutionCard({ lang }) {
  const T = (ar, en) => (lang === "ar" ? ar : en);
  const [d, setD] = useHeadState(null);
  useHeadEffect(() => { API.assem.companyEvolution().then(setD).catch(() => setD({ error: true })); }, []);
  if (!d || d.error) return null;
  const fmtMoney = (n) => (typeof window.fmtCurrency === "function" ? window.fmtCurrency(n) : String(n));
  const period = (key, label) => {
    const p = (d.evolution && d.evolution[key]) || {}; const r = p.revenue || {};
    return (
      <div key={key} className="card" style={{ padding: 10, flex: "1 1 150px", minWidth: 140 }}>
        <b style={{ fontSize: 12.5 }}>{label}</b>
        <div className="subtle" style={{ fontSize: 11, marginTop: 4 }}>{T("الإيراد", "Revenue")}: {r.thisPeriod != null ? fmtMoney(r.thisPeriod) : "—"} {r.deltaPct != null ? <span style={{ color: r.deltaPct > 0 ? "var(--color-green)" : "var(--color-danger)" }}>({r.deltaPct > 0 ? "+" : ""}{r.deltaPct}%)</span> : null}</div>
        <div className="subtle" style={{ fontSize: 11 }}>{T("الإنسانية", "Humanity")}: {p.humanityGrowth != null ? (p.humanityGrowth > 0 ? "+" : "") + p.humanityGrowth : "—"} · {T("الثقة", "Trust")}: {p.trustGrowth != null ? (p.trustGrowth > 0 ? "+" : "") + p.trustGrowth : "—"}</div>
      </div>
    );
  };
  return (
    <Card style={{ marginBottom: 12 }}><div className="col" style={{ gap: 8, padding: 6 }}>
      <b style={{ fontSize: 14 }}>{T("تطوّر الشركة", "Company evolution")}</b>
      {d.status === "building_history" ? <span className="subtle" style={{ fontSize: 11.5 }}>{T(d.note.ar, d.note.en)}</span> : (
        <div className="row" style={{ gap: 8, flexWrap: "wrap" }}>{period("weekly", T("هذا الأسبوع", "This week"))}{period("monthly", T("هذا الشهر", "This month"))}{period("quarterly", T("هذا الربع", "This quarter"))}</div>
      )}
      <span className="subtle" style={{ fontSize: 10 }}>{T("التعلّم المضاف", "Learning added")}: {d.learningAdded.approvedDocuments} {T("وثيقة", "docs")} · {d.learningAdded.scoredConversations} {T("محادثة مقيّمة", "scored chats")}{d.mostImprovedAgent ? " · ★ " + d.mostImprovedAgent.name : ""}</span>
    </div></Card>
  );
}

// ===========================================================================
// PHASE 16 — MANAGER EXECUTION SURFACE cards (compose the Phase 13/14/16 director engines into the per-director
// page so it reads like an operating desk). All read-only + real-or-NED; escalation is founder-approval-pending.
// ===========================================================================
const P16L = (o, lang) => (o == null ? "" : typeof o === "string" ? o : (lang === "ar" ? (o.ar || o.en) : (o.en || o.ar)) || "");
// PART 1 — Operating Desk: the at-a-glance situation header.
function OperatingDeskCard({ id, lang }) {
  const T = (ar, en) => (lang === "ar" ? ar : en); const L = (o) => P16L(o, lang);
  const [d, setD] = useHeadState(null);
  useHeadEffect(() => { setD(null); API.assem.directorOperatingDesk(id).then(setD).catch(() => setD({ error: true })); }, [id]);
  if (!d) return <Card><div className="skel" style={{ height: 90, borderRadius: 10 }} /></Card>;
  if (d.error || !d.desk) return null;
  const k = d.desk; const row = (label, v, tone) => (v && v !== "—" ? <div className="row between" style={{ fontSize: 11.5, gap: 8 }}><span className="subtle" style={{ flexShrink: 0 }}>{label}</span><span style={{ textAlign: "end", color: tone }}>{typeof v === "object" ? L(v) : v}</span></div> : null);
  const ned = T("لا بيانات كافية", "—");
  return (
    <Card style={{ borderInlineStart: "3px solid var(--color-secondary)" }}><div className="col" style={{ gap: 5, padding: 4 }}>
      <div className="between"><b style={{ fontSize: 13 }}>{T("مكتب العمل", "Operating desk")}</b><Badge tone={k.status === "on_track" ? "green" : k.status === "behind" ? "danger" : "neutral"}>{k.status}</Badge></div>
      {row(T("الهدف", "Objective"), L(k.objective) || ned)}
      {row(T("العائق", "Blocker"), L(k.blocker) || ned, "var(--color-danger)")}
      {row(T("الفرصة", "Opportunity"), L(k.opportunity) || ned, "var(--color-green)")}
      {row(T("الإجراء التالي", "Next action"), L(k.nextAction) || ned)}
      {k.doNothing && L(k.doNothing) ? <span className="subtle" style={{ fontSize: 10.5, color: "var(--color-orange)" }}>{T("لو لم نفعل شيئاً", "If we do nothing")}: {L(k.doNothing)}</span> : null}
      {(k.needsFounderApproval || []).length ? <span className="subtle" style={{ fontSize: 10.5 }}>{T("بانتظار موافقتك", "Needs your approval")}: {k.needsFounderApproval.length}</span> : null}
    </div></Card>
  );
}
// PART 5 — Leadership scorecard (9 axes).
function DirectorLeadershipScorecardCard({ id, lang }) {
  const T = (ar, en) => (lang === "ar" ? ar : en);
  const [d, setD] = useHeadState(null);
  useHeadEffect(() => { setD(null); API.assem.directorLeadershipScorecard(id).then(setD).catch(() => setD({ error: true })); }, [id]);
  if (!d) return <Card><div className="skel" style={{ height: 80, borderRadius: 10 }} /></Card>;
  if (d.error || !d.axes) return null;
  const a = d.axes;
  const AX = [["overall", T("الإجمالي", "Overall")], ["performance", T("الأداء", "Performance")], ["learning", T("التعلّم", "Learning")], ["execution", T("التنفيذ", "Execution")], ["teamHealth", T("صحة الفريق", "Team health")], ["revenueImpact", T("أثر الإيراد", "Revenue")], ["decisionQuality", T("جودة القرار", "Decisions")], ["trainingImpact", T("أثر التدريب", "Training")], ["trustImpact", T("أثر الثقة", "Trust")]];
  const col = (v) => v == null ? "var(--fg-4)" : v >= 70 ? "var(--color-green)" : v >= 45 ? "var(--color-orange)" : "var(--color-danger)";
  return (
    <Card><div className="col" style={{ gap: 8, padding: 4 }}>
      <div className="between"><b style={{ fontSize: 13 }}>{T("بطاقة القيادة", "Leadership scorecard")}</b><span className="subtle" style={{ fontSize: 11 }}>{d.confidence === "measured" ? <span><b style={{ color: col(a.overall) }}>{d.grade || "—"}</b> · {T("مقاسة", "measured")}</span> : T("بيانات غير كافية", "not enough data")}</span></div>
      <div className="row" style={{ gap: 6, flexWrap: "wrap" }}>
        {AX.map(([key, label]) => (
          <div key={key} className="card" style={{ padding: 8, flex: "1 1 80px", minWidth: 72, textAlign: "center", border: key === "overall" ? "1px solid var(--color-secondary)" : undefined }}>
            <div className="subtle" style={{ fontSize: 9.5 }}>{label}</div>
            <div style={{ fontSize: 16, fontWeight: 800, color: col(a[key]) }}>{a[key] == null ? "—" : a[key]}</div>
          </div>
        ))}
      </div>
    </div></Card>
  );
}
// PART 6 — Executive Council participation.
function DirectorCouncilParticipationCard({ id, lang }) {
  const T = (ar, en) => (lang === "ar" ? ar : en); const L = (o) => P16L(o, lang);
  const [d, setD] = useHeadState(null);
  useHeadEffect(() => { setD(null); API.assem.directorCouncilParticipation(id).then(setD).catch(() => setD({ error: true })); }, [id]);
  if (!d) return <Card><div className="skel" style={{ height: 70, borderRadius: 10 }} /></Card>;
  if (d.error) return null;
  return (
    <Card><div className="col" style={{ gap: 4, padding: 4 }}>
      <div className="between"><b style={{ fontSize: 13 }}>{T("دوره في المجلس التنفيذي", "Role in the Executive Council")}</b><Badge tone={d.agreement ? "green" : "neutral"}>{d.agreement ? T("ملتزم", "committed") : T("ممتنع", "abstains")}</Badge></div>
      {L(d.contribution) && L(d.contribution) !== "—" ? <div style={{ fontSize: 11.5 }}><b>{T("مساهمته", "Contribution")}:</b> <span className="subtle">{L(d.contribution)}</span></div> : <span className="subtle" style={{ fontSize: 11.5 }}>{T("لا مساهمة مقاسة بعد.", "No measured contribution yet.")}</span>}
      {L(d.concern) && L(d.concern) !== "—" ? <div style={{ fontSize: 11 }}><b>{T("قلقه", "Concern")}:</b> <span className="subtle">{L(d.concern)}</span></div> : null}
      {d.pendingFounderApprovals ? <span className="subtle" style={{ fontSize: 10.5, color: "var(--color-orange)" }}>{T("قرارات بانتظار موافقتك", "Decisions awaiting your approval")}: {d.pendingFounderApprovals}</span> : null}
    </div></Card>
  );
}
// PART 4 — Diagnostics (the 7 questions).
function DirectorDiagnosticsCard({ id, lang }) {
  const T = (ar, en) => (lang === "ar" ? ar : en); const L = (o) => P16L(o, lang);
  const [d, setD] = useHeadState(null);
  useHeadEffect(() => { setD(null); API.assem.directorDiagnostics(id).then(setD).catch(() => setD({ error: true })); }, [id]);
  if (!d) return <Card><div className="skel" style={{ height: 70, borderRadius: 10 }} /></Card>;
  if (d.error || !d.answers) return null;
  const Q = [["biggest_problem", T("أكبر مشكلة", "Biggest problem")], ["biggest_opportunity", T("أكبر فرصة", "Biggest opportunity")], ["fastest_revenue", T("أسرع إيراد", "Fastest revenue")], ["hurting_conversion", T("ما يضرّ التحويل", "Hurting conversion")]];
  return (
    <Card><div className="col" style={{ gap: 4, padding: 4 }}>
      <div className="between"><b style={{ fontSize: 13 }}>{T("تشخيص المدير", "Director diagnostics")}</b><span className="subtle" style={{ fontSize: 11 }}>{d.measuredCount}/{d.total} {T("مدعوم بأدلة", "evidence-backed")}</span></div>
      {Q.map(([k, label]) => { const a = d.answers[k]; if (!a) return null; return (
        <div key={k} className="row between" style={{ fontSize: 11, gap: 8 }}>
          <span style={{ flexShrink: 0, fontWeight: 700, maxWidth: "42%" }}>{label}</span>
          <span className="subtle" style={{ textAlign: "end", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{a.confidence === "not_enough_data" ? T("لا بيانات كافية", "—") : L(a.answer)}</span>
        </div>); })}
    </div></Card>
  );
}
// PART 7/8 — allowed actions + escalate to Assem.
function DirectorActionsCard({ id, lang }) {
  const T = (ar, en) => (lang === "ar" ? ar : en); const L = (o) => P16L(o, lang);
  const [d, setD] = useHeadState(null);
  const [esc, setEsc] = useHeadState(null);
  const [issue, setIssue] = React.useState("");
  useHeadEffect(() => { setD(null); setEsc(null); setIssue(""); API.assem.directorActions(id).then(setD).catch(() => setD({ error: true })); }, [id]);
  if (!d || d.error) return null;
  const escalate = async () => { if (!issue.trim()) return; try { const r = await API.assem.directorEscalate(id, { issue }); setEsc(r && r.ok ? "ok" : "err"); } catch { setEsc("err"); } };
  return (
    <Card><div className="col" style={{ gap: 6, padding: 4 }}>
      <b style={{ fontSize: 13 }}>{T("إجراءات المدير", "Director actions")}</b>
      <div className="row" style={{ gap: 5, flexWrap: "wrap" }}>
        {(d.actions || []).map((a) => <Badge key={a.verb} tone="neutral">{L(a.label)}</Badge>)}
      </div>
      <span className="subtle" style={{ fontSize: 10 }}>{T("كل إجراء بموافقة المؤسس — لا تنفيذ تلقائي.", "Every action is founder-approved — nothing auto-executes.")}</span>
      <div className="row" style={{ gap: 6, flexWrap: "wrap", marginTop: 2 }}>
        <input value={issue} onChange={(e) => setIssue(e.target.value)} placeholder={T("صعّد مشكلة لعاصم…", "Escalate an issue to Assem…")} style={{ flex: "1 1 200px", fontSize: 12, padding: "7px 10px", borderRadius: 8, border: "1px solid var(--border-1)" }} />
        <button onClick={escalate} disabled={!issue.trim()} style={{ fontSize: 12, padding: "7px 13px", borderRadius: 8, border: "none", background: "var(--color-secondary)", color: "#fff", fontWeight: 700, cursor: issue.trim() ? "pointer" : "default", opacity: issue.trim() ? 1 : 0.6 }}>{T("تصعيد", "Escalate")}</button>
      </div>
      {esc === "ok" ? <span style={{ fontSize: 11, color: "var(--color-green)" }}>{T("سُجّل التصعيد — بانتظار موافقتك.", "Escalation recorded — pending your approval.")}</span> : esc === "err" ? <span style={{ fontSize: 11, color: "var(--color-danger)" }}>{T("تعذّر التصعيد", "Couldn't escalate")}</span> : null}
    </div></Card>
  );
}
// PART 3 — per-agent 30/60/90 plan summary (open the full plan via the engine).
function DirectorAgentPlansCard({ id, lang }) {
  const T = (ar, en) => (lang === "ar" ? ar : en);
  const [d, setD] = useHeadState(null);
  useHeadEffect(() => { setD(null); API.assem.agentImprovementPlans(id).then(setD).catch(() => setD({ error: true })); }, [id]);
  if (!d || d.error) return null;
  if (d.status === "not_enough_data" || !(d.agents || []).length) return null;
  return (
    <Card><div className="col" style={{ gap: 3, padding: 4 }}>
      <b style={{ fontSize: 13 }}>{T("خطط تحسين الوكلاء (30/60/90)", "Agent improvement plans (30/60/90)")}</b>
      {(d.agents || []).slice(0, 8).map((a) => (
        <div key={a.agentId} className="row between" style={{ fontSize: 11.5 }}>
          <span style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", maxWidth: "60%" }}>{a.name}</span>
          <span className="subtle">{T("جاهزية", "ready")} {a.readinessScore == null ? "—" : a.readinessScore} · {a.realHorizons}/3 {T("آفاق", "horizons")}</span>
        </div>
      ))}
      <span className="subtle" style={{ fontSize: 10 }}>{T("خطط بموافقة المؤسس — لا تدريب تلقائي.", "Founder-approved plans — no auto-training.")}</span>
    </div></Card>
  );
}

// P3·P2 + P6 — the Manager (director) page, in the mandated order: Chat → Objectives → Team →
// Recommendations → Reports → Learning → Scorecard → Executive Council. Chat is ALWAYS first.
function DirectorPage({ id, lang, go }) {
  const T = (ar, en) => (lang === "ar" ? ar : en);
  const [v, setV] = useHeadState(null);
  const [training, setTraining] = useHeadState(null);
  useHeadEffect(() => { setV(null); API.assem.director(id, lang).then(setV).catch(() => setV({ error: true })); }, [id]);
  useHeadEffect(() => { setTraining(null); API.assem.directorTraining(lang).then((d) => setTraining((d && d.reports || []).find((r) => r.director === id) || null)).catch(() => setTraining(null)); }, [id]);
  const Section = ({ n, title, children }) => (
    <div className="col" style={{ gap: 8 }}>
      <div className="row" style={{ gap: 8, alignItems: "center", marginTop: 2 }}>
        <span style={{ width: 20, height: 20, borderRadius: 999, display: "grid", placeItems: "center", fontSize: 11, fontWeight: 700, background: "var(--color-secondary)", color: "#fff", flexShrink: 0 }}>{n}</span>
        <b style={{ fontSize: 13 }}>{title}</b>
      </div>
      {children}
    </div>
  );
  return (
    <div className="col" style={{ gap: 16 }}>
      {/* P16 — Operating Desk header: the at-a-glance situation, above the tabs. */}
      <OperatingDeskCard id={id} lang={lang} />
      <Section n={1} title={T("المحادثة", "Chat")}><DirectorChat key={id} id={id} lang={lang} /></Section>
      <Section n={2} title={T("الأهداف الحالية", "Objectives")}><HeadDirectorView id={id} lang={lang} part="objectives" data={v} trainingData={training} /></Section>
      <Section n={3} title={T("الفريق", "Team")}>
        <DirectorTeamPanel id={id} lang={lang} go={go} />
        <DirectorAgentPlansCard id={id} lang={lang} />
      </Section>
      <Section n={4} title={T("التوصيات", "Recommendations")}>
        <FounderCommandPanel id={id} lang={lang} go={go} />
        <DirectorActionsCard id={id} lang={lang} />
        {id === "revenue" && window.RevenueWorkflowPanel ? <RevenueWorkflowPanel T={T} /> : null}
      </Section>
      <Section n={5} title={T("التقارير", "Reports")}>
        <DirectorDiagnosticsCard id={id} lang={lang} />
        <DirectorTrainingImpactCard id={id} lang={lang} />
        <HeadDirectorView id={id} lang={lang} part="reports" data={v} trainingData={training} />
        {id === "revenue" ? <FunnelOwnershipCard lang={lang} /> : null}
        {id === "revenue" && window.SalesFunnelPanel ? <SalesFunnelPanel T={T} /> : null}
      </Section>
      <Section n={6} title={T("التعلّم", "Learning")}>
        <DirectorLearningCard id={id} lang={lang} />
        <DirectorHistory id={id} lang={lang} />
      </Section>
      <Section n={7} title={T("بطاقة الأداء", "Scorecard")}>
        <DirectorLeadershipScorecardCard id={id} lang={lang} />
      </Section>
      <Section n={8} title={T("المجلس التنفيذي", "Executive Council")}>
        <DirectorCouncilParticipationCard id={id} lang={lang} />
      </Section>
    </div>
  );
}

function HeadScreen() {
  const { lang } = useLang();
  const _app = (typeof useApp === "function") ? useApp() : null;
  const go = (_app && _app.go) ? _app.go : ((r) => { try { window.dispatchEvent(new CustomEvent("maxab:navtab", { detail: { screen: r } })); } catch (e) {} });
  const T = (ar, en) => (lang === "ar" ? ar : en);
  const [dir, setDir] = useHeadState(() => { try { return (window.__navTab && window.__navTab.screen === "head" && window.__navTab.director) || "org"; } catch (e) { return "org"; } });
  const [org, setOrg] = useHeadState(null);
  useHeadEffect(() => { API.assem.head(lang).then(setOrg).catch(() => {}); }, []);
  // Deep-link from the Managers sidebar: a child sets window.__navTab.director and dispatches maxab:navtab.
  useHeadEffect(() => { const h = (e) => { const d = e && e.detail; if (d && d.screen === "head" && d.director) setDir(d.director); }; window.addEventListener("maxab:navtab", h); return () => window.removeEventListener("maxab:navtab", h); }, []);
  const byId = (id) => (org && org.directors || []).find((d) => d.id === id);
  return (
    <div className="content__inner content__inner--wide fade-up" style={{ maxWidth: 1100 }}>
      <div className="between wrap" style={{ marginBottom: 12, gap: 10 }}>
        <div><h4 style={{ margin: 0 }}>{T("المديرون", "Managers")}</h4><div className="subtle" style={{ fontSize: 12.5 }}>{T("اختر مديراً وتحدّث معه مباشرة — كل مدير ذكاء يعمل تحت عاصم.", "Pick a manager and talk to them directly — every AI director works under Assem.")}</div></div>
      </div>
      <DirectorTabs active={dir} onPick={setDir} byId={byId} lang={lang} />
      {dir === "org" ? (
        <React.Fragment>
          <CompanyOperatingViewCard lang={lang} onPick={setDir} />
          <CompanyEvolutionCard lang={lang} />
          <OrganizationPanel org={org} lang={lang} onPick={setDir} />
        </React.Fragment>
      ) : dir === "assem" ? (
        window.AssemSupreme ? <AssemSupreme lang={lang} /> : <AssemScreen embedded />
      ) : (
        /* P3·P2 — every director page follows ONE order: Chat → Objectives → Subagents → Actions → Reports
           → Learning. Revenue's Workflow (Actions) + Sales Funnel Intelligence (Reports) mount inside it. */
        <DirectorPage id={dir} lang={lang} go={go} />
      )}
    </div>
  );
}
window.HeadScreen = HeadScreen;
