// screens-validation.jsx — Phase 6 Live Revenue Validation & Agent Certification UI.
// One hub screen, internal tabs. Every metric renders LIVE from /api/validation|/founder|/evidence
// and is LABELLED with its data-source validation level. Honest empty/PRE-VALIDATION states
// everywhere — when there is no real-customer data, the UI says so. Nothing fabricated.

const VT = (lang, ar, en) => (lang === "ar" ? ar : en);
// Company-currency money formatter for the Revenue Command Center (target/closed/
// forecast/gap are all denominated in the company target currency).
function vsar(n) { return window.fmtCurrency(n, window.MaxabCurrency.companyCurrency()); }
function vpct(n) { return n == null ? "—" : n + "%"; }
function VLevelBadge({ level, label }) {
  const tone = level >= 3 ? "lime" : level === 2 ? "blue" : "neutral";
  return <Badge tone={tone}>{"L" + level + " · " + (label || "")}</Badge>;
}
function VEmpty({ icon, title, body }) {
  return <div style={{ padding: "26px 16px", textAlign: "center", color: "var(--fg-3)" }}>
    <Icon name={icon || "shield"} size={26} style={{ color: "var(--fg-disabled)", marginBottom: 8 }} />
    <div style={{ fontWeight: 700, fontSize: 14, color: "var(--fg-1)" }}>{title}</div>
    {body && <div style={{ fontSize: 13, marginTop: 4, lineHeight: 1.5, maxWidth: 480, margin: "4px auto 0" }}>{body}</div>}
  </div>;
}
function VStat({ label, value, sub, tone }) {
  return <div className="card" style={{ padding: 16 }}>
    <div style={{ fontSize: 12, color: "var(--fg-4)", fontWeight: 600 }}>{label}</div>
    <div style={{ fontSize: 24, fontWeight: 800, letterSpacing: "-0.02em", marginTop: 4, color: tone || "var(--fg-1)" }}>{value}</div>
    {sub && <div style={{ fontSize: 12, color: "var(--fg-4)", marginTop: 2 }}>{sub}</div>}
  </div>;
}

const VALIDATION_TABS = [
  { key: "report", ar: "الأداء الحقيقي", en: "Real Performance" },
  { key: "certification", ar: "الشهادات", en: "Certifications" },
  { key: "benchmark", ar: "المقارنة", en: "Benchmark" },
  { key: "founder", ar: "مراجعة المؤسس", en: "Founder Review" },
  { key: "humanVsAi", ar: "بشري مقابل ذكاء", en: "Human vs AI" },
  { key: "marketScore", ar: "تحقّق السوق", en: "Market Score" },
  { key: "evidence", ar: "سجل الأدلة", en: "Evidence" },
  { key: "product", ar: "تحقّق المنتج", en: "Product Validation" },
  { key: "readiness", ar: "الجاهزية", en: "Readiness" },
];

// SINGLE-OWNER: the Target → Plan → Approve → Execute workflow is owned by Managers → Revenue Director
// (RevenueWorkflowPanel). This screen is the Revenue & Customer DATA / audit layer — its planning &
// execution surfaces render READ-ONLY and LINK to the Revenue Director instead of duplicating ownership.
function navToRevenueDirector(go) { try { window.__navTab = { screen: "head", director: "revenue" }; window.dispatchEvent(new CustomEvent("maxab:navtab", { detail: window.__navTab })); } catch (e) {} if (go) go("head"); }
function RevenueOwnerPointer({ go, T }) {
  return (
    <Card><div className="row between wrap" style={{ gap: 10, padding: 4, alignItems: "center" }}>
      <div className="col" style={{ gap: 2 }}>
        <b style={{ fontSize: 13 }}>{T("لتغيير الهدف أو الخطة أو التنفيذ", "To change the target, plan or execution")}</b>
        <span className="subtle" style={{ fontSize: 12 }}>{T("الورك‑فلو يملكه مدير الإيراد — هذه الشاشة للعرض والتدقيق فقط.", "This workflow is owned by the Revenue Director — this screen is read-only data & audit.")}</span>
      </div>
      <Button size="sm" icon="arrowRight" onClick={() => navToRevenueDirector(go)}>{T("افتح مدير الإيراد", "Open Revenue Director")}</Button>
    </div></Card>
  );
}

// REVENUE SECTION IA (action-first rebuild) — the dense Advanced wall is split into 7 focused
// sub-screens, each answering ONE business question with action-first cards. Every section component
// is REUSED verbatim (no engine/collection/calc rebuilt) — this is purely information architecture.
const REVENUE_TABS = [
  { key: "command", ar: "نظرة عامة", en: "Overview", desc: ["اليوم: الهدف، أهم الإجراءات، والقرارات المطلوبة. الورك‑فلو يملكه مدير الإيراد.", "Today: the target, top actions, and the decisions you must approve. The workflow is owned by the Revenue Director."] },
  { key: "planning", ar: "تخطيط الهدف", en: "Target Planning", desc: ["اضبط الهدف والاستراتيجية: السُّلّم، تلقائي/يدوي، القطاع، المنتج، والحدود.", "Set the target + strategy: the ladder, auto/manual, vertical, product and limits."] },
  { key: "execution", ar: "لوحة التنفيذ", en: "Execution Board", desc: ["حوّل توصيات مدير الإيرادات إلى عمل: اعتمد، نفّذ، عدّل، أو ارفض.", "Turn Revenue Director recommendations into work: approve, execute, edit, reject."] },
  { key: "product", ar: "استراتيجية المنتج", en: "Product Strategy", desc: ["ماذا نبيع؟ الربحية، الباقات، المسارات، والعروض.", "What to sell: profitability, packages, revenue paths and offers."] },
  { key: "vertical", ar: "استراتيجية القطاع", en: "Vertical Strategy", desc: ["لمن نبيع؟ ربحية القطاعات وأين نركّز الشهر القادم.", "Who to sell to: vertical profitability and where to focus next month."] },
  { key: "success", ar: "نجاح العملاء", en: "Customer Success", desc: ["احمِ الإيراد ووسّعه: التجديد، التوسّع، ومخاطر التسرّب.", "Protect + expand revenue: renewals, expansion and churn risk."] },
  { key: "intelligence", ar: "الذكاء والتدقيق", en: "Intelligence & Audit", desc: ["من أين تأتي الأرقام؟ المصدر، الحساب، الثقة، وفجوات البيانات.", "Where the numbers come from: source, calculation, confidence and data gaps."] },
];

function RevenueTabStrip({ active, onPick, lang }) {
  return (
    <div className="chipscroll-wrap" style={{ marginBottom: 18 }}>
      <div className="chipscroll" style={{ gap: 6, paddingBottom: 6 }}>
        {REVENUE_TABS.map((tb) => (
          <button key={tb.key} className={"btn btn--sm " + (active === tb.key ? "btn--dark" : "btn--subtle")} onClick={() => onPick(tb.key)} style={{ flexShrink: 0 }}>{lang === "ar" ? tb.ar : tb.en}</button>
        ))}
      </div>
    </div>
  );
}

// Shared loading/error guard for a Revenue tab panel (all panels read cc = commandCenter payload).
function revGuard(cc, T) {
  if (!cc || cc.error) return <Card flush><VEmpty icon={cc && cc.error ? "alert" : "dollar"} title={cc && cc.error ? T("تعذّر التحميل", "Couldn't load") : T("جارٍ التحميل…", "Loading…")} body={cc && cc.error} /></Card>;
  return null;
}

function ValidationScreen() {
  const { lang } = useLang();
  const { go } = useApp();
  useStore();
  const T = (ar, en) => VT(lang, ar, en);
  // The Target → Plan → Approve → Execute workflow has a SINGLE owner: Managers → Revenue Director.
  // This screen is the Revenue/Customer DATA + audit layer; it points to the owner instead of duplicating it.
  const goRevenueDirector = () => { try { window.__navTab = { screen: "head", director: "revenue" }; window.dispatchEvent(new CustomEvent("maxab:navtab", { detail: window.__navTab })); } catch (e) {} go("head"); };
  const [revtab, setRevtab] = React.useState("command");
  const [auditView, setAuditView] = React.useState(null); // old validation-metrics sub-views (inside Intelligence)
  // Deep link from the sidebar / events. New: {revtab}. Legacy: {mode:"ceo"|"advanced"} → command/intelligence.
  React.useEffect(() => {
    const apply = (n) => { if (n && n.screen === "validation") { if (n.revtab) setRevtab(n.revtab); else if (n.mode === "advanced") setRevtab("intelligence"); else if (n.mode === "ceo") setRevtab("command"); window.__navTab = null; } };
    try { apply(window.__navTab); } catch (e) {}
    const h = (e) => apply(e.detail);
    window.addEventListener("maxab:navtab", h);
    return () => window.removeEventListener("maxab:navtab", h);
  }, []);
  // Every Revenue tab reads the single commandCenter + ownerOverview payload (no duplicate fetches).
  React.useEffect(() => {
    Actions.loadValidation("ownerOverview"); Actions.loadValidation("commandCenter");
    if (revtab === "product") { Actions.loadValidation("productSubscription"); Actions.loadValidation("productSourceCode"); }
  }, [revtab]);
  React.useEffect(() => { if (!auditView) return; if (auditView === "founder") { Actions.loadFounderReviews(); return; } Actions.loadValidation(auditView); }, [auditView]);

  const goTab = (k) => { setRevtab(k); setAuditView(null); try { window.scrollTo(0, 0); } catch (e) {} };
  const meta = REVENUE_TABS.find((t) => t.key === revtab) || REVENUE_TABS[0];
  return (
    <div className="content__inner fade-up">
      <div style={{ marginBottom: 14 }}>
        <h4 style={{ marginBottom: 4 }}>{T("بيانات الإيراد والعملاء", "Revenue & Customer Data")}</h4>
        <div className="subtle" style={{ fontSize: 13, maxWidth: 680, lineHeight: 1.5 }}>{lang === "ar" ? meta.desc[0] : meta.desc[1]}</div>
      </div>
      <RevenueTabStrip active={revtab} onPick={goTab} lang={lang} />
      {/* PERSISTENT read-only banner (mandate Part 9) — every Revenue tab here is DATA & AUDIT. The single
          operable Target → Plan → Approve → Execute workflow is owned by Managers → Revenue Director, so the
          founder is never confused about where to act. Shown on all tabs, not just Overview. */}
      <div className="row between wrap" style={{ gap: 10, alignItems: "center", marginBottom: 14, padding: "9px 13px", borderRadius: "var(--radius-md)", background: "var(--bg-2)", border: "1px solid var(--border-1)" }}>
        <div className="col" style={{ gap: 1, minWidth: 0 }}>
          <b style={{ fontSize: 12.5 }}>{T("شاشة للعرض والتدقيق فقط", "Read-only — data & audit")}</b>
          <span className="subtle" style={{ fontSize: 11.5 }}>{T("لضبط الهدف أو الخطة أو التنفيذ، افتح مدير الإيراد — هو المالك الوحيد للورك‑فلو.", "To set the target, plan or execute, open the Revenue Director — the single owner of the workflow.")}</span>
        </div>
        <Button size="sm" icon="arrowRight" onClick={goRevenueDirector}>{T("افتح مدير الإيراد", "Open Revenue Director")}</Button>
      </div>
      {revtab === "command" && <CeoModePanel T={T} onAdvanced={() => goTab("planning")} />}
      {revtab === "planning" && <TargetPlanningTab T={T} />}
      {revtab === "execution" && <ExecutionBoardTab T={T} />}
      {revtab === "product" && <ProductStrategyTab T={T} />}
      {revtab === "vertical" && <VerticalStrategyTab T={T} />}
      {revtab === "success" && <CustomerSuccessTab T={T} />}
      {revtab === "intelligence" && <IntelligenceAuditTab T={T} auditView={auditView} setAuditView={setAuditView} />}
    </div>
  );
}

// ---- The 7 Revenue tab panels — each composes EXISTING sections (reuse, nothing rebuilt). --------

// 2. TARGET PLANNING — set + control the revenue strategy (target ladder, Auto/Manual, focus, limits).
function TargetPlanningTab({ T }) {
  const { lang } = useLang(); const { go } = useApp(); const cc = vget("commandCenter");
  const L = (x) => (x && typeof x === "object" && !Array.isArray(x) ? (lang === "ar" ? x.ar : x.en) : x);
  const g = revGuard(cc, T); if (g) return g;
  return (
    <div className="col" style={{ gap: 22 }}>
      <RevenueOwnerPointer go={go} T={T} />
      <RevenueDirectorConsole cc={cc} T={T} lang={lang} readOnly go={go} />
      <CommandHero cc={cc} T={T} L={L} go={go} readOnly />
      <TargetScenariosSection cc={cc} T={T} lang={lang} />
      <TargetEvolutionSection cc={cc} T={T} lang={lang} />
      <TargetDistributionSection cc={cc} T={T} lang={lang} />
      <CascadeSection cc={cc} T={T} L={L} />
      <AllocationSection cc={cc} T={T} L={L} />
      <CampaignGuidanceSection cc={cc} T={T} lang={lang} />
    </div>
  );
}

// 3. EXECUTION BOARD — turn recommendations into work (approve / execute / edit / reject + agent plans).
function ExecutionBoardTab({ T }) {
  const { lang } = useLang(); const { go } = useApp(); const cc = vget("commandCenter");
  const L = (x) => (x && typeof x === "object" && !Array.isArray(x) ? (lang === "ar" ? x.ar : x.en) : x);
  const g = revGuard(cc, T); if (g) return g;
  return (
    <div className="col" style={{ gap: 22 }}>
      <RevenueOwnerPointer go={go} T={T} />
      <ManagerBriefSection cc={cc} T={T} lang={lang} go={go} />
      <ExecutionBoardSection cc={cc} T={T} lang={lang} mode="advanced" readOnly go={go} />
      <WeeklyPlaybookSection cc={cc} T={T} lang={lang} />
      <AgentPlansSection cc={cc} T={T} lang={lang} />
      <AgentWorkloadSection cc={cc} T={T} lang={lang} />
      <AgentBoardSection cc={cc} T={T} L={L} />
      <UpcomingMeetingsSection cc={cc} T={T} lang={lang} go={go} />
    </div>
  );
}

// 4. PRODUCT STRATEGY — what to sell (profitability, packages, paths, offers, ROI).
function ProductStrategyTab({ T }) {
  const { lang } = useLang(); const { go } = useApp(); const cc = vget("commandCenter");
  const L = (x) => (x && typeof x === "object" && !Array.isArray(x) ? (lang === "ar" ? x.ar : x.en) : x);
  const g = revGuard(cc, T); if (g) return g;
  return (
    <div className="col" style={{ gap: 22 }}>
      <ProductProfitabilitySection cc={cc} T={T} lang={lang} />
      <RevenuePriorityBoardSection cc={cc} T={T} lang={lang} />
      <ProductStrategySection cc={cc} T={T} lang={lang} />
      <ProductPerformanceSection cc={cc} T={T} lang={lang} />
      <ProductOwnershipSection cc={cc} T={T} L={L} />
      <AiSalesAgentFocusSection cc={cc} T={T} lang={lang} />
      <PackageClaritySection cc={cc} T={T} lang={lang} />
      <AvoidSellingSection cc={cc} T={T} lang={lang} />
      <RevenueStrategyPlanSection cc={cc} T={T} lang={lang} />
      <RoiCalculatorSection cc={cc} T={T} lang={lang} />
      <RoiFunnelSection cc={cc} T={T} lang={lang} />
    </div>
  );
}

// 5. VERTICAL STRATEGY — who to sell to (vertical profitability + competitive position).
function VerticalStrategyTab({ T }) {
  const { lang } = useLang(); const cc = vget("commandCenter");
  const g = revGuard(cc, T); if (g) return g;
  return (
    <div className="col" style={{ gap: 22 }}>
      <VerticalIntelligenceSection cc={cc} T={T} lang={lang} />
      <CompetitiveGapSection cc={cc} T={T} lang={lang} />
      <CompetitorIntelSection cc={cc} T={T} lang={lang} />
    </div>
  );
}

// 6. CUSTOMER SUCCESS & RENEWALS — protect + expand revenue (renewals, expansion, churn, danger zone).
// Founder Decisions live in Command Center (the daily approve-queue); Customer Success keeps its own
// founder-decision surface via the Danger Zone (keep / extend grace / suspend / reactivate).
function CustomerSuccessTab({ T }) {
  const { lang } = useLang(); const cc = vget("commandCenter");
  const g = revGuard(cc, T); if (g) return g;
  return (
    <div className="col" style={{ gap: 22 }}>
      <CustomerSuccessSection cc={cc} T={T} lang={lang} />
      <DangerZoneSection cc={cc} T={T} lang={lang} />
    </div>
  );
}

// 7. INTELLIGENCE & REALITY AUDIT — where the numbers come from + the validation/certification views.
// Setup gates + funnel-health diagnostic + foundational "finish setup" actions (from ownerOverview).
// Reused verbatim from the old Advanced wall so the onboarding/data-health view is not lost.
function SetupHealthSection({ T, setAuditView }) {
  const { lang } = useLang(); const { go } = useApp();
  const L = (x) => (x && typeof x === "object" && !Array.isArray(x) ? (lang === "ar" ? x.ar : x.en) : x);
  const d = vget("ownerOverview");
  if (!d || d.error) return null;
  const s = d.summary || {};
  const stageTone = d.stage === "Earning" ? "lime" : d.stage === "First customers" ? "blue" : "orange";
  const foundational = (d.actions || []).filter((a) => a.kind === "setup" || a.kind === "proof");
  const handle = (target) => { if (OWNER_ADVANCED_TABS.includes(target)) { setAuditView && setAuditView(target); } else { go(target); } };
  return (
    <div className="col" style={{ gap: 14 }}>
      <div className="card" style={{ padding: 16, borderInlineStart: "3px solid var(--color-secondary)" }}>
        <div className="row" style={{ gap: 8, marginBottom: 6, flexWrap: "wrap" }}>
          <Badge tone={stageTone}>{T("المرحلة", "Stage")}: {L(d.stageLabel) || d.stage}</Badge>
          <Badge tone="neutral">{T("بوابات الإطلاق", "Setup gates")}: {s.gatesPassed}/{s.gatesTotal}</Badge>
        </div>
        <div style={{ fontSize: 14, lineHeight: 1.55, color: "var(--fg-2)" }}>{L(d.headline)}</div>
      </div>
      <div>
        <div className="subtle" style={{ fontSize: 12, fontWeight: 600, marginBottom: 8, textTransform: "uppercase", letterSpacing: "0.04em" }}>{T("صحّة المسار", "Funnel health")}</div>
        <div className="grid" style={{ gridTemplateColumns: "repeat(auto-fit, minmax(240px, 1fr))", gap: 14 }}>
          {(d.questions || []).map((q) => <OwnerQuestionCard key={q.key} q={q} T={T} L={L} />)}
        </div>
      </div>
      {foundational.length ? (
        <Card title={T("إكمال الإعداد", "Finish setup")} flush>
          <div style={{ padding: "4px 0" }}>
            {foundational.map((a) => (
              <div key={a.key} className="between" style={{ padding: "12px 16px", borderBottom: "1px solid var(--border-1)", gap: 12, alignItems: "flex-start", flexWrap: "wrap" }}>
                <div className="row" style={{ gap: 10, alignItems: "flex-start", minWidth: 0, flex: 1 }}>
                  <span className="opp" style={{ width: 32, height: 32, borderRadius: 9, background: "var(--bg-2)", color: a.priority === 1 ? "var(--color-orange)" : "var(--color-secondary)", flexShrink: 0 }}><Icon name={OWNER_ACTION_ICON[a.kind] || "arrowRight"} size={15} /></span>
                  <div style={{ minWidth: 0 }}>
                    <div style={{ fontWeight: 700, fontSize: 13.5 }}>{L(a.title)}</div>
                    <div style={{ fontSize: 12.5, color: "var(--fg-3)", marginTop: 2, lineHeight: 1.5 }}>{L(a.detail)}</div>
                  </div>
                </div>
                <Button size="sm" variant="dark" iconEnd="chevronRight" onClick={() => handle(a.target)}>{L(a.cta)}</Button>
              </div>
            ))}
          </div>
        </Card>
      ) : null}
    </div>
  );
}

function auditPanel(view, T) {
  switch (view) {
    case "report": return <RealPerformancePanel T={T} />;
    case "certification": return <CertificationPanel T={T} />;
    case "benchmark": return <BenchmarkPanel T={T} />;
    case "founder": return <FounderReviewPanel T={T} />;
    case "humanVsAi": return <HumanVsAiPanel T={T} />;
    case "marketScore": return <MarketScorePanel T={T} />;
    case "evidence": return <EvidencePanel T={T} />;
    case "product": return <ProductValidationPanel T={T} />;
    case "readiness": return <ReadinessPanel T={T} />;
    default: return null;
  }
}
function IntelligenceAuditTab({ T, auditView, setAuditView }) {
  const { lang } = useLang(); const { go } = useApp(); const cc = vget("commandCenter");
  const L = (x) => (x && typeof x === "object" && !Array.isArray(x) ? (lang === "ar" ? x.ar : x.en) : x);
  const g = revGuard(cc, T); if (g) return g;
  return (
    <div className="col" style={{ gap: 22 }}>
      <RealityAuditSection cc={cc} T={T} lang={lang} />
      <CurrencyHealthSection cc={cc} T={T} go={go} />
      <CurrencyBreakdownSection cc={cc} T={T} go={go} />
      <AccountabilitySection cc={cc} T={T} L={L} />
      <GapOwnershipSection cc={cc} T={T} />
      <OwnershipTreeSection cc={cc} T={T} lang={lang} />
      <MeetingConversionSection cc={cc} T={T} lang={lang} />
      <KnowledgeEffectivenessSection cc={cc} T={T} lang={lang} />
      <LearningWatchSection cc={cc} T={T} L={L} />
      <ActionPlanSection cc={cc} T={T} L={L} />
      {/* Setup gates + funnel-health diagnostic + foundational setup actions (from ownerOverview). */}
      <SetupHealthSection T={T} setAuditView={setAuditView} />
      {/* Market validation + certification (the legacy validation-metrics views) — on demand. */}
      <Card flush>
        <div style={{ padding: "14px 16px" }}>
          <b style={{ fontSize: 14 }}>{T("التحقق والشهادات والجاهزية", "Validation, certification & readiness")}</b>
          <div className="subtle" style={{ fontSize: 12, marginTop: 2 }}>{T("الأدلة الحقيقية على نضج المنتج في السوق — افتح أيّ تقرير.", "The real evidence of market maturity — open any report.")}</div>
          <div className="chipscroll" style={{ gap: 6, marginTop: 10, paddingBottom: 4 }}>
            {VALIDATION_TABS.map((tb) => <button key={tb.key} className={"btn btn--sm " + (auditView === tb.key ? "btn--dark" : "btn--subtle")} onClick={() => setAuditView(auditView === tb.key ? null : tb.key)} style={{ flexShrink: 0 }}>{lang === "ar" ? tb.ar : tb.en}</button>)}
          </div>
        </div>
        {auditView ? <div style={{ padding: "0 16px 16px", borderTop: "1px solid var(--border-1)" }}><div style={{ marginTop: 14 }}>{auditPanel(auditView, T)}</div></div> : null}
      </Card>
    </div>
  );
}

function vget(view) { return (DATA.VALIDATION && DATA.VALIDATION[view]) || null; }

// ---- Owner Overview (plain-language default tab) -------------------------------
const OWNER_STATUS = {
  good: { tone: "lime", dot: "var(--color-secondary)" },
  testing: { tone: "orange", dot: "var(--color-orange)" },
  none: { tone: "neutral", dot: "var(--fg-disabled)" },
};
const OWNER_ACTION_ICON = { setup: "settings", follow_up: "clock", review: "search", proof: "clipboard", coach: "sparkles" };
const OWNER_ADVANCED_TABS = ["report", "certification", "benchmark", "founder", "humanVsAi", "marketScore", "evidence", "product", "readiness"];

function OwnerQuestionCard({ q, T, L }) {
  const [open, setOpen] = React.useState(false);
  const st = OWNER_STATUS[q.status] || OWNER_STATUS.none;
  const m = q.metric || {};
  const unit = L(m.unit);
  const metricText = m.currency ? vsar(m.value) : (m.of != null ? `${m.value} ${T("من", "of")} ${m.of}` : String(m.value));
  return (
    <div className="card" style={{ padding: 16, display: "flex", flexDirection: "column", gap: 8 }}>
      <div className="row" style={{ gap: 8, alignItems: "center" }}>
        <span style={{ width: 9, height: 9, borderRadius: 999, background: st.dot, flexShrink: 0 }} />
        <Badge tone={st.tone}>{L(q.answer)}</Badge>
      </div>
      <div style={{ fontSize: 14, fontWeight: 700, lineHeight: 1.4 }}>{L(q.question)}</div>
      <div style={{ fontSize: 22, fontWeight: 800, letterSpacing: "-0.02em", lineHeight: 1.1, overflowWrap: "anywhere" }}>
        {metricText} {unit ? <span style={{ fontSize: 12, fontWeight: 600, color: "var(--fg-4)" }}>{unit}</span> : null}
      </div>
      {m.currency && m.testValue > 0 ? <div style={{ fontSize: 12, color: "var(--fg-4)" }}>+ {vsar(m.testValue)} {T("معلّم كمكسوب بلا دفع", "marked won, unpaid")}</div> : null}
      <div style={{ fontSize: 12.5, color: "var(--fg-2)", background: "var(--bg-2)", borderRadius: 8, padding: "8px 10px", lineHeight: 1.5 }}>
        <b style={{ color: "var(--fg-1)" }}>{T("الخطوة", "Do this")}: </b>{L(q.action)}
      </div>
      <button className="btn btn--subtle btn--sm" style={{ alignSelf: "flex-start" }} onClick={() => setOpen((o) => !o)}>{open ? T("إخفاء", "Hide") : T("لماذا يهم؟", "Why this matters")}</button>
      {open ? (
        <div style={{ fontSize: 12.5, color: "var(--fg-3)", lineHeight: 1.5 }}>
          <div>{L(q.meaning)}</div>
          <div style={{ marginTop: 4, color: "var(--fg-4)" }}>{L(q.why)}</div>
        </div>
      ) : null}
    </div>
  );
}

// ---- Slice 2: Command Center sections -----------------------------------------
const AGENT_STATUS = {
  exceeding: { tone: "lime", ar: "يتجاوز الهدف", en: "Exceeding" },
  on_track: { tone: "blue", ar: "على المسار", en: "On Track" },
  behind: { tone: "orange", ar: "متأخّر", en: "Behind" },
  at_risk: { tone: "orange", ar: "في خطر", en: "At Risk" },
  critical: { tone: "red", ar: "حرج", en: "Critical" },
};
const ALLOC_ICON = { allocate_opportunities: "users", follow_up: "clock", coach: "sparkles", product_focus: "layers", prioritise_opportunity: "target" };

// Company target hero + inline editor (Parts 1+2).
// Multi-currency reporting — Revenue/Pipeline grouped by currency. Renders ONLY when
// more than one currency is present (a single-currency install shows the normal totals).
// Honest: converts into the company currency only when the operator configured rates;
// otherwise shows the per-currency breakdown + "no conversion configured".
function CurrencyBreakdownSection({ cc, T, go }) {
  const { lang } = useLang();
  const ctx = cc && cc.currencyContext;
  if (!ctx || !ctx.mixed) return null;
  const chips = (m) => Object.keys(m || {}).sort().map((c) => window.fmtCurrency(m[c], c, lang)).join("   ·   ");
  const block = (title, sum) => (
    <div style={{ background: "var(--bg-2)", borderRadius: 10, padding: "12px 14px" }}>
      <div className="subtle" style={{ fontSize: 11.5, marginBottom: 4 }}>{title}</div>
      <div style={{ fontSize: 14, fontWeight: 700, overflowWrap: "anywhere" }}>{chips(sum.byCurrency)}</div>
      {sum.converted && sum.total != null ? <div className="subtle" style={{ fontSize: 11.5, marginTop: 3 }}>≈ {window.fmtCurrency(sum.total, ctx.target, lang)} {T("محوّل بأسعارك", "converted at your rates")}</div> : null}
    </div>
  );
  return (
    <Card title={T("الإيراد حسب العملة", "Revenue by currency")} flush>
      <div className="col" style={{ gap: 12, padding: 14 }}>
        {!ctx.ratesConfigured ? (
          <div className="row" style={{ gap: 8, background: "var(--color-orange-soft, #FFF7ED)", borderRadius: 10, padding: "10px 12px", alignItems: "center" }}>
            <span className="sdot" style={{ background: "var(--color-orange)" }} />
            <div style={{ fontSize: 12.5, color: "var(--fg-2)", lineHeight: 1.5 }}>{T("عملات متعددة — لم تُهيَّأ أسعار التحويل، لذا لا نجمعها في رقم واحد. أضِف أسعاراً في الإعدادات ← العملة لعرض إجمالي محوَّل.", "Multiple currencies — no conversion configured, so we don't merge them into one number. Add rates in Settings → Currency to see a converted total.")}</div>
          </div>
        ) : null}
        <div className="grid" style={{ gridTemplateColumns: "repeat(auto-fit, minmax(240px, 1fr))", gap: 12 }}>
          {block(T("الإيراد المغلق", "Closed revenue"), ctx.closed)}
          {block(T("خط الأنابيب المفتوح", "Open pipeline"), ctx.pipeline)}
        </div>
        <button className="btn btn--subtle btn--sm" style={{ alignSelf: "flex-start" }} onClick={() => go && go("settings")}>{T("إعداد العملة وأسعار التحويل", "Configure currency & rates")}</button>
      </div>
    </Card>
  );
}

// ============================================================================
// ROI CLOSING SYSTEM — the AI Revenue Organization vs cost-of-team calculator. Sells a
// Revenue Team Replacement, not software. Math mirrors server roi-calculator (honest, from
// inputs); saving persists for the Revenue Director ROI funnel. Currency = SAR (packages).
// ============================================================================
function RoiCalculatorSection({ cc, T, lang }) {
  const packages = (cc && cc.roiPackages) || [];
  const fmt = (v) => window.fmtCurrency(v, "SAR", lang);
  const [salesEmployees, setSalesEmployees] = React.useState("");
  const [salesSalary, setSalesSalary] = React.useState("");
  const [csEmployees, setCsEmployees] = React.useState("");
  const [csSalary, setCsSalary] = React.useState("");
  const [recruitmentCost, setRecruitmentCost] = React.useState("");
  const [trainingCost, setTrainingCost] = React.useState("");
  const [managementCost, setManagementCost] = React.useState("");
  const [packageId, setPackageId] = React.useState((cc && cc.companyTargets) ? "growth" : "growth");
  const [saved, setSaved] = React.useState(false);
  const [busy, setBusy] = React.useState(false);
  const n = (v) => { const x = Number(v); return Number.isFinite(x) && x > 0 ? x : 0; };
  const pkg = packages.find((p) => p.id === packageId) || packages.find((p) => p.id === "growth") || packages[0];
  const annualSalesCost = Math.round(n(salesEmployees) * n(salesSalary) * 12);
  const annualCsCost = Math.round(n(csEmployees) * n(csSalary) * 12);
  const extras = Math.round(n(recruitmentCost) + n(trainingCost) + n(managementCost));
  const totalTeamCost = annualSalesCost + annualCsCost + extras;
  const maxabCost = pkg ? pkg.priceYear : 0;
  const savings = totalTeamCost - maxabCost;
  const monthly = Math.round(savings / 12);
  const roiPct = maxabCost > 0 ? Math.round((savings / maxabCost) * 100) : null;
  const payback = savings > 0 ? Math.round((maxabCost / (savings / 12)) * 10) / 10 : null;
  const hasInputs = totalTeamCost > 0;
  const maxBar = Math.max(totalTeamCost, maxabCost, 1);

  const save = async () => {
    setBusy(true);
    try { await API.validation.roiSave({ salesEmployees: n(salesEmployees), salesSalary: n(salesSalary), csEmployees: n(csEmployees), csSalary: n(csSalary), recruitmentCost: n(recruitmentCost), trainingCost: n(trainingCost), managementCost: n(managementCost), packageId }); await Actions.loadValidation("commandCenter"); setSaved(true); setTimeout(() => setSaved(false), 2500); }
    catch (_) {} finally { setBusy(false); }
  };
  const inp = (label, val, setter, ph) => (
    <label style={{ fontSize: 12, color: "var(--fg-4)" }}>{label}<input className="input" type="number" min="0" inputMode="numeric" placeholder={ph || "0"} value={val} onChange={(e) => setter(e.target.value)} style={{ marginTop: 3 }} /></label>
  );
  const stat = (label, value, tone) => (
    <div style={{ background: "var(--bg-2)", borderRadius: 10, padding: "12px 14px" }}>
      <div style={{ fontSize: 18, fontWeight: 800, letterSpacing: "-0.02em", color: tone || "var(--fg-1)", overflowWrap: "anywhere" }}>{value}</div>
      <div style={{ fontSize: 11.5, color: "var(--fg-4)", marginTop: 3 }}>{label}</div>
    </div>
  );
  return (
    <Card title={<span className="row" style={{ gap: 8 }}><Icon name="dollar" size={15} style={{ color: "var(--color-secondary)" }} />{T("حاسبة العائد — استبدال فريق الإيرادات", "ROI Calculator — Revenue Team Replacement")}</span>} flush>
      <div className="col" style={{ gap: 14, padding: 14 }}>
        <div style={{ fontSize: 12.5, color: "var(--fg-3)", lineHeight: 1.5 }}>{T("قارن تكلفة فريقك الحالي بتكلفة منظومة الإيرادات الذكية السنوية. الأرقام مشتقّة من مدخلاتك — لا تقديرات ملفّقة.", "Compare your current team's cost to the AI Revenue Organization annual subscription. Numbers derive from your inputs — no fabricated estimates.")}</div>
        <div className="grid" style={{ gridTemplateColumns: "repeat(auto-fit, minmax(150px, 1fr))", gap: 10 }}>
          {inp(T("عدد موظفي المبيعات", "Sales employees"), salesEmployees, setSalesEmployees)}
          {inp(T("متوسط راتب المبيعات (شهري)", "Avg sales salary (monthly)"), salesSalary, setSalesSalary)}
          {inp(T("عدد موظفي خدمة العملاء", "Customer-service employees"), csEmployees, setCsEmployees)}
          {inp(T("متوسط راتب خدمة العملاء (شهري)", "Avg CS salary (monthly)"), csSalary, setCsSalary)}
          {inp(T("تكلفة التوظيف (سنوي، اختياري)", "Recruitment cost (annual, optional)"), recruitmentCost, setRecruitmentCost)}
          {inp(T("تكلفة التدريب (سنوي، اختياري)", "Training cost (annual, optional)"), trainingCost, setTrainingCost)}
          {inp(T("تكلفة الإدارة (سنوي، اختياري)", "Management cost (annual, optional)"), managementCost, setManagementCost)}
          <label style={{ fontSize: 12, color: "var(--fg-4)" }}>{T("باقة MAXAB", "MAXAB package")}
            <select className="select" value={packageId} onChange={(e) => setPackageId(e.target.value)} style={{ marginTop: 3 }}>
              {packages.map((p) => <option key={p.id} value={p.id}>{(lang === "ar" ? p.name.ar : p.name.en)} — {fmt(p.priceYear)}/{T("سنة", "yr")}</option>)}
            </select>
          </label>
        </div>

        {hasInputs ? (
          <>
            {/* visual comparison: current team vs MAXAB AI */}
            <div className="col" style={{ gap: 8 }}>
              <div>
                <div className="between" style={{ fontSize: 12.5, marginBottom: 3 }}><span style={{ fontWeight: 600 }}>{T("الفريق الحالي", "Current team")}</span><b>{fmt(totalTeamCost)}/{T("سنة", "yr")}</b></div>
                <div style={{ height: 14, background: "var(--bg-3)", borderRadius: 7, overflow: "hidden" }}><div style={{ width: Math.round((totalTeamCost / maxBar) * 100) + "%", height: "100%", background: "var(--color-orange)" }} /></div>
              </div>
              <div>
                <div className="between" style={{ fontSize: 12.5, marginBottom: 3 }}><span style={{ fontWeight: 600 }}>MAXAB AI ({lang === "ar" ? (pkg && pkg.name.ar) : (pkg && pkg.name.en)})</span><b style={{ color: "var(--color-secondary)" }}>{fmt(maxabCost)}/{T("سنة", "yr")}</b></div>
                <div style={{ height: 14, background: "var(--bg-3)", borderRadius: 7, overflow: "hidden" }}><div style={{ width: Math.max(2, Math.round((maxabCost / maxBar) * 100)) + "%", height: "100%", background: "var(--color-secondary)" }} /></div>
              </div>
            </div>

            <div className="grid" style={{ gridTemplateColumns: "repeat(auto-fit, minmax(150px, 1fr))", gap: 10 }}>
              {stat(T("تكلفة الفريق السنوية", "Current annual team cost"), fmt(totalTeamCost))}
              {stat(T("تكلفة MAXAB السنوية", "MAXAB AI annual cost"), fmt(maxabCost), "var(--color-secondary)")}
              {stat(T("التوفير السنوي", "Annual savings"), savings >= 0 ? fmt(savings) : "−" + fmt(-savings), savings > 0 ? "var(--color-secondary)" : "var(--color-orange)")}
              {stat(T("التوفير الشهري", "Monthly savings"), savings >= 0 ? fmt(monthly) : "−" + fmt(-monthly), savings > 0 ? "var(--color-secondary)" : "var(--color-orange)")}
              {stat(T("نسبة العائد", "ROI %"), roiPct != null ? roiPct + "%" : "—", roiPct > 0 ? "var(--color-secondary)" : "var(--fg-1)")}
              {stat(T("فترة الاسترداد", "Payback period"), payback != null ? payback + " " + T("شهر", "mo") : T("—", "—"))}
            </div>
            {pkg && pkg.replaces ? <div className="subtle" style={{ fontSize: 12 }}>{T(`تستبدل ${pkg.replaces.min}–${pkg.replaces.max} موظفين بمنظومة إيرادات تعمل 24/7.`, `Replaces ${pkg.replaces.min}–${pkg.replaces.max} employees with a 24/7 revenue organization.`)}</div> : null}
            <div className="row" style={{ gap: 10, alignItems: "center" }}>
              <Button size="sm" variant="dark" disabled={busy} onClick={save}>{busy ? T("جارٍ الحفظ…", "Saving…") : T("احفظ هذا الحساب", "Save this calculation")}</Button>
              {saved ? <span style={{ color: "var(--color-success)", fontSize: 13, fontWeight: 600 }}>{T("تم الحفظ — يُحتسب في قمع العائد", "Saved — counts toward the ROI funnel")}</span> : null}
            </div>
          </>
        ) : <div className="subtle" style={{ fontSize: 13, padding: "4px 0" }}>{T("أدخل عدد الموظفين والرواتب لرؤية المقارنة.", "Enter employee counts and salaries to see the comparison.")}</div>}
      </div>
    </Card>
  );
}

// V6 P4/P5/P6 — PACKAGE CLARITY: the 7 attributes per subscription tier (Professional = Unlimited),
// the Enterprise Source Code License (one-time 100k), and the hosting/ownership model. Reads the
// payload's aiPackageMatrix / enterprisePackage / hostingModel — no fabricated numbers.
function PackageClaritySection({ cc, T, lang }) {
  const matrix = (cc && cc.aiPackageMatrix) || [];
  const ent = cc && cc.enterprisePackage;
  const host = cc && cc.hostingModel;
  if (!matrix.length) return null;
  const Lx = (o) => (o ? (lang === "ar" ? (o.ar || o.en) : (o.en || o.ar)) : "—");
  const fmt = (v) => window.fmtCurrency(v, "SAR", lang);
  const yes = T("نعم", "Yes"), no = T("—", "—");
  const cap = (v) => (v == null ? T("بلا حدود", "Unlimited") : v.toLocaleString());
  const rows = [
    [T("الوكلاء", "AI Agents"), (m) => (m.unlimitedAgents ? T("غير محدود", "Unlimited") : (m.agentCountLabelI18n ? Lx(m.agentCountLabelI18n) : m.agentCountLabel))],
    [T("القنوات المتصلة", "Connected channels"), (m) => cap(m.channelCap)],
    [T("تجديد السنة الثانية (50%)", "Year-2 renewal (50%)"), (m) => `${fmt(m.renewalYear2)}/${T("سنة", "yr")}`],
    [T("الفرص النشطة", "Active opportunities"), (m) => cap(m.opportunityCap)],
    [T("الرصيد الشهري", "Monthly credits"), (m) => cap(m.monthlyCredits)],
    [T("الأتمتة", "Automations"), (m) => cap(m.automationCap)],
    [T("مستوى التقارير", "Reporting level"), (m) => m.reportingDepth],
    [T("مستوى الدعم", "Support level"), (m) => Lx(m.supportLevel)],
    [T("ذكاء المنافسين", "Competitive Intelligence"), (m) => (m.competitiveIntelligence ? yes : no)],
    [T("ميزات نجاح العملاء", "Customer Success features"), (m) => (m.customerSuccess ? yes : no)],
    [T("ملكية/إعادة بيع الكود", "Source ownership / resale"), (m) => ((m.resaleRights || m.sourceCodeOwnership) ? yes : T("لا (ترخيص إعادة البيع فقط)", "No (Resale License only)"))],
  ];
  return (
    <Card title={<span className="row" style={{ gap: 8 }}><Icon name="sparkles" size={15} style={{ color: "var(--color-secondary)" }} />{T("وضوح الباقات", "Package Clarity")}</span>} flush>
      <div className="col" style={{ gap: 14, padding: 14 }}>
        <div style={{ overflowX: "auto" }}>
          <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 12.5, minWidth: 420 }}>
            <thead><tr>
              <th style={{ textAlign: "start", padding: "6px 8px", color: "var(--fg-4)", fontWeight: 600 }}></th>
              {matrix.map((m) => <th key={m.id} style={{ textAlign: "start", padding: "6px 8px" }}><div style={{ fontWeight: 800 }}>{Lx(m.name)}</div><div style={{ color: "var(--color-secondary)", fontWeight: 700 }}>{fmt(m.priceYear)}/{T("سنة", "yr")}</div></th>)}
            </tr></thead>
            <tbody>
              {rows.map(([label, get], i) => (
                <tr key={i} style={{ borderTop: "1px solid var(--border-1)" }}>
                  <td style={{ padding: "6px 8px", color: "var(--fg-4)" }}>{label}</td>
                  {matrix.map((m) => <td key={m.id} style={{ padding: "6px 8px", fontWeight: 600 }}>{get(m)}</td>)}
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        <div style={{ fontSize: 11.5, color: "var(--fg-4)" }}>{T("استهلاك الذكاء غير مشمول — تحضر مفتاحك الخاص. MAXAB لا تبيع الرموز.", "AI usage is not included — bring your own key. MAXAB does not resell tokens.")}</div>

        {ent ? (
          <div className="card" style={{ padding: 14, borderInlineStart: "3px solid var(--color-secondary)" }}>
            <div className="between" style={{ flexWrap: "wrap", gap: 8 }}>
              <div><b style={{ fontSize: 14 }}>{Lx(ent.name)}</b><div className="subtle" style={{ fontSize: 12 }}>{Lx(ent.forWho)}</div></div>
              <div style={{ textAlign: "end" }}><b style={{ fontSize: 16, color: "var(--color-secondary)" }}>{fmt(ent.priceOneTime)}</b><div className="subtle" style={{ fontSize: 11 }}>{T("دفعة واحدة", "one-time")}</div></div>
            </div>
            <ul style={{ margin: "8px 0 0", paddingInlineStart: 18, fontSize: 12.5, lineHeight: 1.6 }}>
              {(lang === "ar" ? ent.includes.ar : ent.includes.en).map((x, i) => <li key={i}>{x}</li>)}
            </ul>
          </div>
        ) : null}

        {host ? (
          <div className="grid" style={{ gridTemplateColumns: "repeat(auto-fit, minmax(220px, 1fr))", gap: 10 }}>
            <div className="card" style={{ padding: 12 }}>
              <b style={{ fontSize: 12.5 }}>{T("الباقات المُستضافة (على خوادم MAXAB)", "Hosted packages (on MAXAB servers)")}</b>
              <div style={{ fontSize: 11.5, color: "var(--fg-3)", marginTop: 6, lineHeight: 1.5 }}>{Lx(host.subscription.note)}</div>
            </div>
            <div className="card" style={{ padding: 12 }}>
              <b style={{ fontSize: 12.5 }}>{T("ترخيص إعادة البيع (الاستثناء)", "Resale License (the exception)")}</b>
              <div style={{ fontSize: 11.5, color: "var(--fg-3)", marginTop: 6, lineHeight: 1.5 }}>{Lx((host.resale || host.enterprise || {}).note)}</div>
            </div>
          </div>
        ) : null}
      </div>
    </Card>
  );
}

// V6 P8/P9 — CAMPAIGN GUIDANCE: founder sets this month's focus (the Revenue Director biases toward
// it) + the Autonomous Campaign Mode toggle (money + suspension still never auto).
function CampaignGuidanceSection({ cc, T, lang }) {
  const g = (cc && cc.campaignGuidance) || null;
  const lim = (g && g.limits) || {};
  const [text, setText] = React.useState(g && g.objectives ? g.objectives.map((o) => o.focus).join("\n") : "");
  const [busy, setBusy] = React.useState(false);
  const [saved, setSaved] = React.useState(false);
  const [budget, setBudget] = React.useState(lim.budgetLimit ?? "");
  const [maxC, setMaxC] = React.useState(lim.monthlyLimit ?? "");
  React.useEffect(() => { if (g && g.objectives) setText(g.objectives.map((o) => o.focus).join("\n")); }, [g && g.objectives && g.objectives.length]);
  React.useEffect(() => { setBudget(lim.budgetLimit ?? ""); setMaxC(lim.monthlyLimit ?? ""); }, [lim.budgetLimit, lim.monthlyLimit]);
  const saveLimits = async () => { setBusy(true); try { await API.agentActions.setCampaignLimits({ budgetLimit: budget === "" ? null : Number(budget), monthlyLimit: maxC === "" ? null : Number(maxC) }); await Actions.loadValidation("commandCenter"); } catch (_) {} finally { setBusy(false); } };
  if (!g) return null;
  const Lx = (o) => (o ? (lang === "ar" ? (o.ar || o.en) : (o.en || o.ar)) : "");
  const save = async () => {
    setBusy(true);
    try {
      const objectives = text.split("\n").map((s) => s.trim()).filter(Boolean).map((focus) => ({ focus }));
      await API.agentActions.setCampaignObjectives(objectives);
      await Actions.loadValidation("commandCenter");
      setSaved(true); setTimeout(() => setSaved(false), 2500);
    } catch (_) {} finally { setBusy(false); }
  };
  const toggleAuto = async () => { setBusy(true); try { await API.agentActions.setAutonomousCampaigns(!g.autonomousCampaigns); await Actions.loadValidation("commandCenter"); } catch (_) {} finally { setBusy(false); } };
  return (
    <Card title={<span className="row" style={{ gap: 8 }}><Icon name="target" size={15} style={{ color: "var(--color-secondary)" }} />{T("توجيه الحملات", "Campaign Guidance")}</span>} flush>
      <div className="col" style={{ gap: 12, padding: 14 }}>
        <div style={{ fontSize: 12.5, color: "var(--fg-3)", lineHeight: 1.5 }}>{Lx(g.note)}</div>
        <label style={{ fontSize: 12, color: "var(--fg-4)" }}>{T("أهداف هذا الشهر (سطر لكل تركيز، مثال: Focus Shopify Design)", "This month's objectives (one focus per line, e.g. Focus Shopify Design)")}
          <textarea className="input" rows={4} value={text} onChange={(e) => setText(e.target.value)} placeholder={"Focus Shopify Design\nFocus AI Sales Agent\nFocus Real Estate"} style={{ marginTop: 4, resize: "vertical" }} />
        </label>
        {g.objectives && g.objectives.length ? (
          <div className="row" style={{ gap: 6, flexWrap: "wrap" }}>
            {g.objectives.map((o) => <Badge key={o.id} tone={o.value ? "lime" : "neutral"}>{Lx(o.label) || o.focus}{o.value ? "" : T(" (لم يُطابق)", " (unmapped)")}</Badge>)}
          </div>
        ) : null}
        <div className="row" style={{ gap: 10, alignItems: "center", flexWrap: "wrap" }}>
          <Button size="sm" variant="dark" disabled={busy} onClick={save}>{busy ? T("جارٍ…", "Saving…") : T("احفظ التركيز", "Save focus")}</Button>
          {saved ? <span style={{ color: "var(--color-success)", fontSize: 13, fontWeight: 600 }}>{T("تم الحفظ — مدير الإيرادات يميل نحوه", "Saved — the Revenue Director biases toward it")}</span> : null}
        </div>
        <div className="between" style={{ gap: 10, flexWrap: "wrap", borderTop: "1px solid var(--border-1)", paddingTop: 10 }}>
          <div style={{ minWidth: 0 }}>
            <b style={{ fontSize: 12.5 }}>{T("الحملات المستقلة", "Autonomous Campaigns")}</b>
            <div className="subtle" style={{ fontSize: 11.5 }}>{T("يجوز لمدير الإيرادات إطلاق الحملات — الأموال والإيقاف تتطلّب المؤسس دائماً.", "The Revenue Director may launch campaigns — money + suspension always require the founder.")}</div>
          </div>
          <Button size="sm" variant={g.autonomousCampaigns ? "dark" : "ghost"} disabled={busy} onClick={toggleAuto}>{g.autonomousCampaigns ? T("مُفعّل", "ON") : T("مُعطّل", "OFF")}</Button>
        </div>
        {/* Part 8 — founder budget + campaign ceilings (the Revenue Director refuses to over-launch / over-spend). */}
        <div style={{ borderTop: "1px solid var(--border-1)", paddingTop: 10 }}>
          <b style={{ fontSize: 12.5 }}>{T("حدود الحملات", "Campaign limits")}</b>
          <div className="subtle" style={{ fontSize: 11.5, marginBottom: 6, lineHeight: 1.5 }}>
            {T("سقوف يحترمها مدير الإيرادات هذا الشهر — اتركها فارغة = بلا حد.", "Ceilings the Revenue Director respects this month — leave blank = no limit.")}
            {lim.monthCount != null ? ` · ${T("هذا الشهر", "this month")}: ${lim.monthCount}${lim.monthlyLimit != null ? "/" + lim.monthlyLimit : ""} ${T("حملة", "campaigns")}, ${vsar(lim.monthSpent || 0)}${lim.budgetLimit != null ? " / " + vsar(lim.budgetLimit) : ""} ${T("ميزانية", "budget")}` : ""}
          </div>
          <div className="row" style={{ gap: 8, flexWrap: "wrap", alignItems: "flex-end" }}>
            <label style={{ fontSize: 11, color: "var(--fg-4)" }}>{T("حد الميزانية الشهري", "Monthly budget limit")}<input className="input" type="number" min="0" value={budget} onChange={(e) => setBudget(e.target.value)} style={{ marginTop: 2, maxWidth: 160 }} placeholder={T("بلا حد", "no limit")} /></label>
            <label style={{ fontSize: 11, color: "var(--fg-4)" }}>{T("حد الحملات/الشهر", "Max campaigns/month")}<input className="input" type="number" min="0" value={maxC} onChange={(e) => setMaxC(e.target.value)} style={{ marginTop: 2, maxWidth: 150 }} placeholder={T("بلا حد", "no limit")} /></label>
            <Button size="sm" variant="subtle" disabled={busy} onClick={saveLimits}>{T("احفظ الحدود", "Save limits")}</Button>
          </div>
        </div>
      </div>
    </Card>
  );
}

// Revenue Director — ROI closing funnel (generated / sent / won-after / conversion / avg savings).
function RoiFunnelSection({ cc, T, lang }) {
  const m = cc && cc.roiMetrics;
  if (!m) return null;
  const fmt = (v) => window.fmtCurrency(v, "SAR", lang);
  const stat = (label, value) => <div style={{ background: "var(--bg-2)", borderRadius: 10, padding: "10px 12px" }}><div style={{ fontSize: 17, fontWeight: 800 }}>{value}</div><div className="subtle" style={{ fontSize: 11.5 }}>{label}</div></div>;
  return (
    <Card title={T("قمع العائد على الاستثمار", "ROI funnel (Revenue Director)")} flush>
      <div className="col" style={{ gap: 8, padding: 14 }}>
        {m.hasData ? (
          <div className="grid" style={{ gridTemplateColumns: "repeat(auto-fit, minmax(130px, 1fr))", gap: 10 }}>
            {stat(T("حسابات أُنشئت", "Calculations generated"), m.generated)}
            {stat(T("تلقائي (محادثة)", "Auto (conversation)"), m.auto != null ? m.auto : "—")}
            {stat(T("يدوي (الحاسبة)", "Manual (calculator)"), m.manual != null ? m.manual : "—")}
            {stat(T("عروض بعائد", "ROI proposals sent"), m.proposalsSent != null ? m.proposalsSent : "—")}
            {stat(T("حسابات أُرسلت", "Calculations sent"), m.sent)}
            {stat(T("صفقات بعد العائد", "Deals won after ROI"), m.wonAfter)}
            {stat(T("نسبة التحويل", "ROI conversion rate"), m.conversionRate != null ? m.conversionRate + "%" : "—")}
            {stat(T("متوسط التوفير المعروض", "Avg savings presented"), fmt(m.avgSavingsPresented))}
            {stat(T("إيراد متأثّر بالعائد", "ROI-influenced revenue"), fmt(m.roiInfluencedRevenue || 0))}
          </div>
        ) : <div className="subtle" style={{ fontSize: 13 }}>{T("لا حسابات عائد محفوظة بعد — احفظها من الحاسبة أعلاه أو دع الوكيل يحسبها في المحادثة.", "No saved ROI calculations yet — save one from the calculator above, or let the agent compute it in conversation.")}</div>}
      </div>
    </Card>
  );
}

// ============================================================================
// AI Operating System — Advanced sections (Parts 1,3,4,5,6). All read the command-center
// payload (sales-os.operatingSystem) — pure presentation of real data, honest empties.
// ============================================================================

// PART 3 — AI Sales Manager Daily Brief.
// Competitive Intelligence widgets (Slice 5) — reads operatingSystem.competitorIntel. Honest
// empty state; never fabricated. Threat level colour-coded from real loss data.
function CompetitorIntelSection({ cc, T, lang }) {
  const ci = cc && cc.competitorIntel;
  if (!ci) return null;
  const THREAT = { high: "red", medium: "orange", low: "neutral" };
  const hasAny = ci.hasData && ((ci.topCompetitorsMentioned || []).length || (ci.threats || []).length || (ci.mostLostDealsAgainst || []).length || ci.commonPriceObjections || ci.commonFeatureObjections);
  return (
    <Card title={<span className="row" style={{ gap: 8 }}><Icon name="shield" size={15} style={{ color: "#7C3AED" }} />{T("ذكاء المنافسين", "Competitive Intelligence")}</span>} flush>
      <div className="col" style={{ gap: 12, padding: 14 }}>
        {!hasAny ? (
          <div className="subtle" style={{ fontSize: 12.5, lineHeight: 1.5 }}>{T("لا بيانات منافسين بعد — أضِف منافسين وحدّد المنافس في الفرص لتظهر هنا (لا تُعرض بيانات ملفّقة).", "No competitor data yet — add competitors and tag the competitor on opportunities to populate this (no fabricated data is shown).")}</div>
        ) : (
          <>
            <div className="grid" style={{ gridTemplateColumns: "repeat(auto-fit, minmax(180px, 1fr))", gap: 10 }}>
              <div style={{ background: "var(--bg-2)", borderRadius: 10, padding: "10px 12px" }}>
                <div className="subtle" style={{ fontSize: 11.5, fontWeight: 700, marginBottom: 6 }}>{T("الأكثر ذكرًا", "Top mentioned")}</div>
                {(ci.topCompetitorsMentioned || []).length ? ci.topCompetitorsMentioned.map((c, i) => <div key={i} className="between" style={{ fontSize: 12.5, marginBottom: 3 }}><span>{c.competitor}</span><Badge tone="neutral">{c.mentions}</Badge></div>) : <div className="subtle" style={{ fontSize: 12 }}>{T("لا شيء", "None")}</div>}
              </div>
              <div style={{ background: "var(--bg-2)", borderRadius: 10, padding: "10px 12px" }}>
                <div className="subtle" style={{ fontSize: 11.5, fontWeight: 700, marginBottom: 6 }}>{T("الأكثر خسارة أمامه", "Most lost against")}</div>
                {(ci.mostLostDealsAgainst || []).length ? ci.mostLostDealsAgainst.map((c, i) => <div key={i} className="between" style={{ fontSize: 12.5, marginBottom: 3 }}><span>{c.competitor}</span><span style={{ color: "var(--color-orange)", fontWeight: 700 }}>{c.lostTo}× · {vsar(c.revenueLost)}</span></div>) : <div className="subtle" style={{ fontSize: 12 }}>{T("لا شيء", "None")}</div>}
              </div>
              <div style={{ background: "var(--bg-2)", borderRadius: 10, padding: "10px 12px" }}>
                <div className="subtle" style={{ fontSize: 11.5, fontWeight: 700, marginBottom: 6 }}>{T("اعتراضات معتمدة", "Approved objections")}</div>
                <div className="row" style={{ gap: 6, flexWrap: "wrap" }}><Badge tone="blue">{T("السعر", "Price")}: {ci.commonPriceObjections || 0}</Badge><Badge tone="blue">{T("الميزات", "Features")}: {ci.commonFeatureObjections || 0}</Badge></div>
                <div className="subtle" style={{ fontSize: 11.5, marginTop: 8 }}>{T("الإيراد: فوز", "Revenue: won")} <b style={{ color: "var(--color-secondary)" }}>{vsar(ci.revenueSummary && ci.revenueSummary.won)}</b> · {T("خسارة", "lost")} <b style={{ color: "var(--color-orange)" }}>{vsar(ci.revenueSummary && ci.revenueSummary.lost)}</b></div>
              </div>
            </div>
            {(ci.threats || []).length ? (
              <div>
                <div className="subtle" style={{ fontSize: 11.5, fontWeight: 700, marginBottom: 6 }}>{T("درجة التهديد", "Threat score")}</div>
                {ci.threats.map((t, i) => (
                  <div key={i} className="between" style={{ padding: "6px 0", borderBottom: "1px solid var(--border-1)", gap: 10 }}>
                    <span style={{ fontSize: 12.5, fontWeight: 600 }}>{t.competitor}</span>
                    <div className="row" style={{ gap: 8, alignItems: "center" }}>
                      <span className="subtle" style={{ fontSize: 11.5 }}>{t.mentions} {T("ذكر", "mentions")} · {t.lostTo} {T("خسارة", "lost")}</span>
                      <Badge tone={THREAT[t.threatLevel] || "neutral"}>{t.riskScore}/100 · {t.threatLevel}</Badge>
                    </div>
                  </div>
                ))}
              </div>
            ) : null}
          </>
        )}
      </div>
    </Card>
  );
}

function ManagerBriefSection({ cc, T, lang, go }) {
  const mb = cc && cc.managerBrief;
  if (!mb) return null;
  const L = (x) => (x && typeof x === "object" ? (lang === "ar" ? x.ar : x.en) : x);
  const riskCol = (title, items) => (
    <div style={{ background: "var(--bg-2)", borderRadius: 10, padding: "10px 12px", minWidth: 0 }}>
      <div className="subtle" style={{ fontSize: 11.5, fontWeight: 700, marginBottom: 6 }}>{title}</div>
      {items && items.length ? items.map((r, i) => (
        <div key={i} style={{ marginBottom: 6 }}>
          <div className="between" style={{ gap: 6, flexWrap: "wrap" }}><span style={{ fontSize: 12.5, fontWeight: 600 }}>{L(r.title)}</span>{r.impactSar > 0 ? <span style={{ fontSize: 12, fontWeight: 700, color: "var(--color-orange)", whiteSpace: "nowrap" }}>{vsar(r.impactSar)}</span> : null}</div>
          {r.action ? <div className="subtle" style={{ fontSize: 11.5 }}>→ {L(r.action)}</div> : null}
        </div>
      )) : <div className="subtle" style={{ fontSize: 12 }}>{T("لا مخاطر", "None")}</div>}
    </div>
  );
  return (
    <Card title={<span className="row" style={{ gap: 8 }}><Icon name="sparkles" size={15} style={{ color: "var(--color-secondary)" }} />{T("مدير المبيعات الذكي — الموجز اليومي", "AI Sales Manager — Daily Brief")}</span>} flush>
      <div className="col" style={{ gap: 12, padding: 14 }}>
        <div style={{ fontSize: 13.5, fontWeight: 600, color: "var(--fg-1)", lineHeight: 1.5 }}>{L(mb.headline)}</div>
        <div className="row" style={{ gap: 8, flexWrap: "wrap" }}>
          <Badge tone="green">{mb.summary.ahead} {T("على المسار", "on track")}</Badge>
          <Badge tone="orange">{mb.summary.behind} {T("متأخّر", "behind")}</Badge>
          <Badge tone="red">{mb.summary.critical} {T("حرج", "critical")}</Badge>
        </div>
        {/* Competitor threat — shown ONLY when real approved competitor intelligence exists. */}
        {mb.competitorThreat ? (
          <div className="row" style={{ gap: 8, padding: "8px 10px", background: "var(--bg-2)", borderRadius: 10, borderInlineStart: "3px solid var(--color-purple, #7C3AED)", alignItems: "flex-start" }}>
            <Icon name="shield" size={15} style={{ color: "#7C3AED", flexShrink: 0, marginTop: 1 }} />
            <span style={{ fontSize: 12.5, lineHeight: 1.5, color: "var(--fg-2)" }}>{L(mb.competitorThreat.line)}</span>
          </div>
        ) : null}
        <div className="grid" style={{ gridTemplateColumns: "repeat(auto-fit, minmax(220px, 1fr))", gap: 10 }}>
          {riskCol(T("مخاطر الإيراد", "Revenue risks"), mb.revenueRisks)}
          {riskCol(T("مخاطر الاجتماعات", "Meeting risks"), mb.meetingRisks)}
          {riskCol(T("مخاطر خط الأنابيب", "Pipeline risks"), mb.pipelineRisks)}
        </div>
        {(mb.todaysFocus || []).length ? (
          <div>
            <div className="subtle" style={{ fontSize: 11.5, fontWeight: 700, marginBottom: 6 }}>{T("تركيز اليوم", "Today's focus")}</div>
            {mb.todaysFocus.map((f, i) => (
              <div key={i} className="between" style={{ padding: "7px 0", borderBottom: "1px solid var(--border-1)", gap: 10 }}>
                <span style={{ fontSize: 12.5, minWidth: 0, overflow: "hidden", textOverflow: "ellipsis" }}>{L(f.title)}{f.action ? <span className="subtle"> — {L(f.action)}</span> : null}</span>
                {f.impactSar > 0 ? <span style={{ fontSize: 12, fontWeight: 700, color: "var(--color-secondary)", whiteSpace: "nowrap" }}>{vsar(f.impactSar)}</span> : null}
              </div>
            ))}
          </div>
        ) : null}
        {(mb.recommendedTraining || []).length ? (
          <div>
            <div className="subtle" style={{ fontSize: 11.5, fontWeight: 700, marginBottom: 6 }}>{T("تدريب موصى به", "Recommended training")}</div>
            <div className="row" style={{ gap: 6, flexWrap: "wrap" }}>
              {mb.recommendedTraining.map((t, i) => <button key={i} className="btn btn--subtle btn--sm" onClick={() => go("agents")}>{L(t.title)}</button>)}
            </div>
          </div>
        ) : null}
        {/* Part 9 — Revenue Director product strategy → per-agent tasks (ADVISORY, not applied). */}
        {(mb.productStrategyTasks || []).length ? (
          <div>
            <div className="subtle" style={{ fontSize: 11.5, fontWeight: 700, marginBottom: 6 }}>{T("استراتيجية المنتج ← مهام الوكلاء (موصى بها)", "Product strategy → agent tasks (recommended)")}</div>
            {mb.productStrategyTasks.map((tk, i) => (
              <div key={i} className="between" style={{ padding: "7px 0", borderBottom: "1px solid var(--border-1)", gap: 10, flexWrap: "wrap" }}>
                <div style={{ minWidth: 0, flex: 1 }}>
                  <div style={{ fontSize: 12.5, fontWeight: 600 }}>{L(tk.label)}{tk.ownerName ? <span className="subtle" style={{ fontWeight: 400 }}> · {tk.ownerName}</span> : null}</div>
                  <div className="subtle" style={{ fontSize: 11.5 }}>{L(tk.task)}{tk.assignment ? ` — ${L(tk.assignment)}` : ""}</div>
                </div>
                <Badge tone={tk.overloaded ? "orange" : "neutral"}>{T("موصى به", "Recommended")}</Badge>
              </div>
            ))}
            <div className="subtle" style={{ fontSize: 11, marginTop: 4 }}>{T("توصيات — لا تُطبَّق تلقائيًا.", "Recommendations — not applied automatically.")}</div>
          </div>
        ) : null}
      </div>
    </Card>
  );
}

// PART 1 (Advanced) — Revenue Ownership Tree: company → product → agent → opportunity.
function OwnershipTreeSection({ cc, T, lang }) {
  const tree = cc && cc.ownershipTree;
  const [open, setOpen] = React.useState({});
  if (!tree) return null;
  const L = (x) => (x && typeof x === "object" ? (lang === "ar" ? x.ar : x.en) : x);
  return (
    <Card title={T("شجرة ملكية الإيراد", "Revenue ownership tree")} flush>
      <div style={{ padding: "4px 0" }}>
        <div className="between" style={{ padding: "10px 16px", borderBottom: "1px solid var(--border-1)", background: "var(--bg-2)" }}>
          <b style={{ fontSize: 13 }}>{T("الشركة", "Company")}</b>
          <span style={{ fontSize: 12.5 }}>{T("هدف", "Target")} {vsar(tree.company.target)} · {T("متوقّع", "fcst")} {vsar(tree.company.forecast)} · <span style={{ color: tree.company.gap > 0 ? "var(--color-orange)" : "var(--color-secondary)" }}>{T("فجوة", "gap")} {vsar(tree.company.gap)}</span></span>
        </div>
        {(tree.products || []).length ? tree.products.map((p) => (
          <div key={p.productType}>
            <button onClick={() => setOpen((o) => ({ ...o, [p.productType]: !o[p.productType] }))} className="between" style={{ width: "100%", textAlign: "start", padding: "10px 16px", borderBottom: "1px solid var(--border-1)", gap: 10, background: "transparent", cursor: "pointer" }}>
              <span className="row" style={{ gap: 8, minWidth: 0 }}><Icon name={open[p.productType] ? "chevronDown" : "chevronRight"} size={14} style={{ color: "var(--fg-4)" }} /><b style={{ fontSize: 13 }}>{L(p.label)}</b>{p.owner ? <span className="subtle" style={{ fontSize: 11.5 }}>· {p.owner}</span> : null}</span>
              <span style={{ fontSize: 12, whiteSpace: "nowrap" }}>{vsar(p.revenue)} <span className="subtle">+ {vsar(p.forecast)} {T("متوقّع", "fcst")}</span></span>
            </button>
            {open[p.productType] ? (p.agents || []).map((a) => (
              <div key={a.agentId || a.name} style={{ padding: "8px 16px 8px 36px", borderBottom: "1px solid var(--border-1)" }}>
                <div className="between" style={{ gap: 8 }}><span className="row" style={{ gap: 6 }}><Avatar name={a.name} size="sm" /><b style={{ fontSize: 12.5 }}>{a.name}</b></span><span style={{ fontSize: 12 }}>{vsar(a.won)} <span className="subtle">+ {vsar(a.forecast)}</span></span></div>
                {(a.opportunities || []).map((o) => (
                  <div key={o.id} className="between" style={{ fontSize: 11.5, padding: "3px 0 3px 24px", color: "var(--fg-3)" }}><span style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", maxWidth: "65%" }}>• {o.name}</span><span>{window.fmtCurrency(o.value, o.currency, lang)}</span></div>
                ))}
              </div>
            )) : null}
          </div>
        )) : <div style={{ padding: "18px 16px" }}><VEmpty icon="trending" title={T("لا بيانات منتجات بعد", "No product data yet")} /></div>}
      </div>
    </Card>
  );
}

// PART 6 — Product performance.
function ProductPerformanceSection({ cc, T, lang }) {
  const pp = cc && cc.productPerformance;
  if (!pp) return null;
  const L = (x) => (x && typeof x === "object" ? (lang === "ar" ? x.ar : x.en) : x);
  const tag = (label, row, tone) => row ? <Badge tone={tone}>{label}: {L(row.label)}</Badge> : null;
  return (
    <Card title={T("أداء المنتجات", "Product performance")} flush>
      <div className="col" style={{ gap: 10, padding: 14 }}>
        <div className="row" style={{ gap: 6, flexWrap: "wrap" }}>
          {tag(T("الأفضل", "Best"), pp.best, "green")}
          {tag(T("الأضعف", "Worst"), pp.worst, "orange")}
          {tag(T("الأكثر خطرًا", "Most at risk"), pp.mostAtRisk, "red")}
          <Badge tone="neutral">{T("الأسرع نموًا", "Fastest growing")}: {T("يحتاج سجلًا", "needs history")}</Badge>
        </div>
        <div style={{ overflowX: "auto", width: "100%" }}>
          <table className="table" style={{ minWidth: 640, width: "100%" }}>
            <thead><tr><th>{T("المنتج", "Product")}</th><th>{T("الإيراد", "Revenue")}</th><th>{T("متوقّع", "Forecast")}</th><th>{T("فرص", "Opps")}</th><th>{T("اجتماعات", "Meet.")}</th><th>{T("نسبة الفوز", "Win rate")}</th></tr></thead>
            <tbody>
              {(pp.rows || []).map((r) => (
                <tr key={r.productType}>
                  <td style={{ fontWeight: 600 }}>{L(r.label)}</td>
                  <td>{vsar(r.revenue)}</td><td>{vsar(r.forecast)}</td>
                  <td>{r.opportunities}</td><td>{r.meetings}</td>
                  <td>{r.winRate != null ? r.winRate + "%" : <span className="subtle">{T("بيانات غير كافية", "needs data")}</span>}</td>
                </tr>
              ))}
              {!(pp.rows || []).length ? <tr><td colSpan={6} style={{ textAlign: "center", color: "var(--fg-3)", padding: 14 }}>{T("لا بيانات منتجات بعد", "No product data yet")}</td></tr> : null}
            </tbody>
          </table>
        </div>
      </div>
    </Card>
  );
}

// PART 4 — Meeting conversion metrics (meeting→proposal→won, per product).
function MeetingConversionSection({ cc, T, lang }) {
  const mc = cc && cc.meetingConversion;
  if (!mc) return null;
  const L = (x) => (x && typeof x === "object" ? (lang === "ar" ? x.ar : x.en) : x);
  const pctCell = (r) => r && r.reliable ? <b>{r.pct}%</b> : <span className="subtle">{T("بيانات غير كافية", "needs data")}</span>;
  const o = mc.overall;
  return (
    <Card title={T("تحويلات الاجتماعات", "Meeting conversion")} flush>
      <div className="col" style={{ gap: 10, padding: 14 }}>
        <div className="grid" style={{ gridTemplateColumns: "repeat(auto-fit, minmax(150px, 1fr))", gap: 10 }}>
          <div style={{ background: "var(--bg-2)", borderRadius: 10, padding: "10px 12px" }}><div className="subtle" style={{ fontSize: 11.5 }}>{T("اجتماع ← عرض", "Meeting → Proposal")}</div><div style={{ fontSize: 17 }}>{pctCell(o.meetingToProposal)}</div></div>
          <div style={{ background: "var(--bg-2)", borderRadius: 10, padding: "10px 12px" }}><div className="subtle" style={{ fontSize: 11.5 }}>{T("عرض ← فوز", "Proposal → Won")}</div><div style={{ fontSize: 17 }}>{pctCell(o.proposalToWon)}</div></div>
          <div style={{ background: "var(--bg-2)", borderRadius: 10, padding: "10px 12px" }}><div className="subtle" style={{ fontSize: 11.5 }}>{T("اجتماع ← فوز", "Meeting → Won")}</div><div style={{ fontSize: 17 }}>{pctCell(o.meetingToWon)}</div></div>
        </div>
        {(mc.byProduct || []).length ? (
          <div style={{ overflowX: "auto", width: "100%" }}>
            <table className="table" style={{ minWidth: 520, width: "100%" }}>
              <thead><tr><th>{T("المنتج", "Product")}</th><th>{T("اجتماع←عرض", "Mtg→Prop")}</th><th>{T("عرض←فوز", "Prop→Won")}</th><th>{T("اجتماع←فوز", "Mtg→Won")}</th></tr></thead>
              <tbody>{mc.byProduct.map((g) => <tr key={g.key}><td style={{ fontWeight: 600 }}>{L(g.label)}</td><td>{pctCell(g.meetingToProposal)}</td><td>{pctCell(g.proposalToWon)}</td><td>{pctCell(g.meetingToWon)}</td></tr>)}</tbody>
            </table>
          </div>
        ) : null}
        <div className="subtle" style={{ fontSize: 11 }}>{T(`الأرقام موثوقة عند ≥${mc.minSample} صفقات مغلقة — وإلا "بيانات غير كافية".`, `Rates show only at ≥${mc.minSample} closed deals — otherwise "needs data".`)}</div>
      </div>
    </Card>
  );
}

// PART 2 — Agent operating plans (required activity from real rates; needs-more-data honest).
function AgentPlansSection({ cc, T, lang }) {
  const plans = cc && cc.agentPlans;
  if (!plans || !plans.length) return null;
  const req = (r) => r && r.required != null ? "+" + r.required : <span className="subtle">{T("—", "—")}</span>;
  return (
    <Card title={T("خطط تشغيل الوكلاء", "Agent operating plans")} flush>
      <div style={{ overflowX: "auto", width: "100%" }}>
        <table className="table" style={{ minWidth: 720, width: "100%" }}>
          <thead><tr><th>{T("الوكيل", "Agent")}</th><th>{T("شهري", "Monthly")}</th><th>{T("ربعي", "Qtr")}</th><th>{T("سنوي", "Annual")}</th><th>{T("فجوة", "Gap")}</th><th>{T("فرص", "Opps")}</th><th>{T("اجتماعات", "Meet.")}</th><th>{T("عروض", "Prop.")}</th><th>{T("صفقات", "Deals")}</th></tr></thead>
          <tbody>
            {plans.map((p) => (
              <tr key={p.agentId}>
                <td style={{ fontWeight: 600 }}>{p.name}</td>
                <td>{p.targets.monthly != null ? vsar(p.targets.monthly) : "—"}</td>
                <td>{p.targets.quarterly != null ? vsar(p.targets.quarterly) : "—"}</td>
                <td>{p.targets.annual != null ? vsar(p.targets.annual) : "—"}</td>
                <td style={{ color: p.gap > 0 ? "var(--color-orange)" : "var(--color-secondary)" }}>{vsar(p.gap)}</td>
                <td>{req(p.required.opportunities)}</td><td>{req(p.required.meetings)}</td><td>{req(p.required.proposals)}</td><td>{req(p.required.deals)}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      <div className="subtle" style={{ fontSize: 11, padding: "6px 14px" }}>{T("الأعداد المطلوبة مشتقّة من معدّلات التحويل الحقيقية. «—» = تحتاج بيانات أكثر.", "Required counts derive from real conversion rates. \"—\" = needs more data.")}</div>
    </Card>
  );
}

// PART 5 — Knowledge effectiveness (real objection influence; honest not-enough-data else).
function KnowledgeEffectivenessSection({ cc, T, lang }) {
  const ke = cc && cc.knowledgeEffectiveness;
  if (!ke) return null;
  const counts = { knowledge: (ke.knowledge || []).length, winning: (ke.winning || []).length, sources: (ke.sources || []).length };
  return (
    <Card title={T("فعالية المعرفة", "Knowledge effectiveness")} flush>
      <div className="col" style={{ gap: 10, padding: 14 }}>
        <div style={{ overflowX: "auto", width: "100%" }}>
          <table className="table" style={{ minWidth: 520, width: "100%" }}>
            <thead><tr><th>{T("الاعتراض", "Objection")}</th><th>{T("الاستخدام", "Usage")}</th><th>{T("أثر الفوز", "Won")}</th><th>{T("أثر الخسارة", "Lost")}</th></tr></thead>
            <tbody>
              {(ke.objections || []).length ? ke.objections.map((o) => (
                <tr key={o.id}>
                  <td style={{ fontWeight: 600 }}>{o.title}</td>
                  {o.dataState === "measured"
                    ? <><td>{o.usageCount}</td><td style={{ color: "var(--color-secondary)" }}>{o.wonInfluence}</td><td style={{ color: "var(--color-orange)" }}>{o.lostInfluence}</td></>
                    : <td colSpan={3} className="subtle">{o.dataState === "no_match" ? T("لا تطابق في سجلات الإغلاق", "no match in close records") : T("بيانات غير كافية", "not enough data")}</td>}
                </tr>
              )) : <tr><td colSpan={4} style={{ textAlign: "center", color: "var(--fg-3)", padding: 14 }}>{T("لا اعتراضات معرّفة بعد", "No objections defined yet")}</td></tr>}
            </tbody>
          </table>
        </div>
        <div className="subtle" style={{ fontSize: 11.5, lineHeight: 1.5 }}>
          {T(`المعرفة (${counts.knowledge}) والردود (${counts.winning}) والمصادر (${counts.sources}): لا يوجد تتبّع استخدام بعد — تظهر «بيانات غير كافية» بدل أرقام ملفّقة.`,
             `Knowledge (${counts.knowledge}), winning responses (${counts.winning}) & sources (${counts.sources}): no usage tracking yet — shown as "not enough data" rather than fabricated numbers.`)}
        </div>
      </div>
    </Card>
  );
}

// CEO Mode — the honest mixed-currency executive view: Revenue / Pipeline / Forecast BY
// currency, never a fabricated single total (Part 1 Stage 3). Shows the converted total only
// when the operator configured rates for every currency.
function CeoCurrencyView({ ctx, T, lang, onAdvanced }) {
  const chips = (m) => Object.keys(m || {}).sort().map((c) => window.fmtCurrency(m[c], c, lang)).join("   ·   ") || "—";
  const block = (label, sum) => (
    <div style={{ background: "var(--bg-2)", borderRadius: 10, padding: "12px 14px" }}>
      <div className="subtle" style={{ fontSize: 11.5, marginBottom: 4 }}>{label}</div>
      <div style={{ fontSize: 16, fontWeight: 800, overflowWrap: "anywhere", lineHeight: 1.35 }}>{chips(sum.byCurrency)}</div>
      {ctx.ratesConfigured && sum.total != null ? <div className="subtle" style={{ fontSize: 11.5, marginTop: 3 }}>≈ {window.fmtCurrency(sum.total, ctx.target, lang)} {T("محوّل", "converted")}</div> : null}
    </div>
  );
  return (
    <div className="card" style={{ padding: 16, borderInlineStart: "3px solid var(--color-orange)" }}>
      <div className="row" style={{ gap: 8, marginBottom: 10, alignItems: "center", flexWrap: "wrap" }}>
        <span className="sdot" style={{ background: "var(--color-orange)" }} />
        <b style={{ fontSize: 15 }}>{T("عملات متعددة", "Multiple currencies detected")}</b>
        <span className="subtle" style={{ fontSize: 12 }}>{ctx.ratesConfigured ? T("محوّلة بأسعارك — وموزّعة حسب العملة.", "Converted at your rates — and shown per currency.") : T("لا نعرض إجماليًا واحدًا قد يخلط العملات.", "We don't show one total that would mix currencies.")}</span>
      </div>
      <div className="grid" style={{ gridTemplateColumns: "repeat(auto-fit, minmax(240px, 1fr))", gap: 12 }}>
        {block(T("الإيراد حسب العملة", "Revenue by currency"), ctx.closed)}
        {block(T("خط الأنابيب حسب العملة", "Pipeline by currency"), ctx.pipeline)}
        {block(T("التوقّع حسب العملة", "Forecast by currency"), ctx.forecast)}
      </div>
      <button className="btn btn--subtle btn--sm" style={{ marginTop: 12 }} onClick={onAdvanced}>{T("صحّة العملات والإعداد", "Currency health & setup")}</button>
    </div>
  );
}

// Advanced Mode — Currency Health (Part 1 Stage 4): currencies in use, records per currency,
// which currencies are missing rates, exchange-rate status, and what reporting is blocked.
function CurrencyHealthSection({ cc, T, go }) {
  const { lang } = useLang();
  const h = cc && cc.currencyContext && cc.currencyContext.health;
  if (!h) return null;
  const single = !h.mixed;
  return (
    <Card title={T("صحّة العملات", "Currency health")} flush>
      <div className="col" style={{ gap: 12, padding: 14 }}>
        <div className="grid" style={{ gridTemplateColumns: "repeat(auto-fit, minmax(180px, 1fr))", gap: 12 }}>
          <div style={{ background: "var(--bg-2)", borderRadius: 10, padding: "10px 12px" }}>
            <div className="subtle" style={{ fontSize: 11.5 }}>{T("العملات المستخدمة", "Currencies in use")}</div>
            <div style={{ fontWeight: 800, fontSize: 15 }}>{(h.currenciesUsed || []).join("  ·  ") || "—"}</div>
          </div>
          <div style={{ background: "var(--bg-2)", borderRadius: 10, padding: "10px 12px" }}>
            <div className="subtle" style={{ fontSize: 11.5 }}>{T("حالة أسعار التحويل", "Exchange-rate status")}</div>
            <div style={{ fontWeight: 800, fontSize: 15, color: single ? "var(--fg-1)" : h.ratesConfigured ? "var(--color-secondary)" : "var(--color-orange)" }}>
              {single ? T("عملة واحدة", "Single currency") : h.ratesConfigured ? T("مكتملة", "All configured") : T("ناقصة", "Incomplete")}
            </div>
          </div>
        </div>
        <div>
          <div className="subtle" style={{ fontSize: 11.5, marginBottom: 6 }}>{T("السجلات حسب العملة", "Records by currency")}</div>
          <div className="row" style={{ gap: 8, flexWrap: "wrap" }}>
            {(h.recordsByCurrency || []).map((r) => (
              <span key={r.currency} className="row" style={{ gap: 6, background: "var(--bg-2)", borderRadius: 8, padding: "6px 10px", fontSize: 12.5, fontWeight: 600 }}>
                {r.currency}<span className="subtle">·</span>{r.records} {T("سجل", "records")}
                {!single && h.missingRates.includes(r.currency) ? <Badge tone="orange">{T("لا سعر", "no rate")}</Badge> : null}
              </span>
            ))}
            {!(h.recordsByCurrency || []).length ? <span className="subtle" style={{ fontSize: 12.5 }}>{T("لا سجلات", "no records")}</span> : null}
          </div>
        </div>
        {h.missingRates && h.missingRates.length ? (
          <div className="row" style={{ gap: 8, background: "var(--color-orange-soft, #FFF7ED)", borderRadius: 10, padding: "10px 12px", alignItems: "flex-start" }}>
            <span className="sdot" style={{ background: "var(--color-orange)", marginTop: 5 }} />
            <div style={{ fontSize: 12.5, color: "var(--fg-2)", lineHeight: 1.5 }}>
              {T("عملات بلا سعر تحويل:", "Currencies missing a rate:")} <b>{h.missingRates.join(", ")}</b>.
              {h.blockedReports && h.blockedReports.length ? <> {T("التقارير المحجوبة عن إجمالي موحّد:", "Reports blocked from a single total:")} {h.blockedReports.map((b) => (lang === "ar" ? b.ar : b.en)).join("، ")}.</> : null}
            </div>
          </div>
        ) : null}
        <button className="btn btn--subtle btn--sm" style={{ alignSelf: "flex-start" }} onClick={() => go && go("settings")}>{T("إعداد أسعار التحويل", "Configure exchange rates")}</button>
      </div>
    </Card>
  );
}

function CommandHero({ cc, T, L, go, readOnly }) {
  const { lang } = useLang();
  const [editing, setEditing] = React.useState(false);
  const cas = cc && cc.cascade;
  const ct = (cc && cc.companyTargets) || {};
  const [mo, setMo] = React.useState("");
  const [qt, setQt] = React.useState("");
  const [an, setAn] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState("");
  const openEdit = () => { setMo(ct.monthly ?? (cas ? cas.target : "") ?? ""); setQt(ct.quarterly ?? ""); setAn(ct.annual ?? ""); setErr(""); setEditing(true); };
  const save = async () => {
    setBusy(true); setErr("");
    try {
      const r = await Actions.setCompanyTarget({ monthly: mo === "" ? null : Number(mo), quarterly: qt === "" ? null : Number(qt), annual: an === "" ? null : Number(an) });
      if (r && r.cascade) { await Actions.loadValidation("ownerOverview"); setEditing(false); }
      else setErr((r && r.error) || "failed");
    } catch (e) { setErr((e && e.message) || "failed"); } finally { setBusy(false); }
  };
  if (!cas) return <Card flush><VEmpty icon="dollar" title={T("جارٍ التحميل…", "Loading…")} /></Card>;
  const band = !cas.targetSet ? { tone: "neutral", ar: "لا هدف محدد", en: "No target set" }
    : cas.onTrack ? { tone: "lime", ar: "على المسار", en: "On track" }
    : (cas.forecast >= cas.target * 0.8 ? { tone: "orange", ar: "في خطر", en: "At risk" } : { tone: "red", ar: "خارج المسار", en: "Off track" });
  const fpct = cas.targetSet && cas.target > 0 ? Math.round((cas.forecast / cas.target) * 100) : null;
  return (
    <div className="card" style={{ padding: 16 }}>
      <div className="between" style={{ marginBottom: 12, flexWrap: "wrap", gap: 8 }}>
        <div className="row" style={{ gap: 8, alignItems: "center" }}>
          <Icon name="target" size={16} style={{ color: "var(--color-secondary)" }} />
          <b style={{ fontSize: 14 }}>{T("هدف الإيراد الشهري", "Monthly revenue target")}</b>
        </div>
        <div className="row" style={{ gap: 8, flexWrap: "wrap" }}>
          <Badge tone={band.tone}>{lang === "ar" ? band.ar : band.en}{fpct != null ? ` · ${fpct}% ${T("متوقّع", "forecast")}` : ""}</Badge>
          {readOnly
            ? <button className="btn btn--subtle btn--sm" onClick={() => navToRevenueDirector(go)}>{T("افتح مدير الإيراد ←", "Open Revenue Director →")}</button>
            : <button className="btn btn--subtle btn--sm" onClick={() => (editing ? setEditing(false) : openEdit())}>{editing ? T("إلغاء", "Cancel") : T("تعديل الهدف", "Edit target")}</button>}
        </div>
      </div>
      {editing ? (
        <div className="col" style={{ gap: 10 }}>
          <div className="grid" style={{ gridTemplateColumns: "repeat(auto-fit, minmax(150px, 1fr))", gap: 10 }}>
            {[[T("شهري", "Monthly") + " (" + window.MaxabCurrency.companyCurrency() + ")", mo, setMo], [T("ربع سنوي (اختياري)", "Quarterly (optional)"), qt, setQt], [T("سنوي (اختياري)", "Annual (optional)"), an, setAn]].map(([lbl, val, set]) => (
              <label key={lbl} style={{ fontSize: 12, color: "var(--fg-4)" }}>{lbl}
                <input className="input" type="number" min="0" step="1000" inputMode="numeric" value={val} onChange={(e) => set(e.target.value)} style={{ marginTop: 4 }} />
              </label>
            ))}
          </div>
          {err ? <div style={{ color: "var(--color-orange)", fontSize: 12 }}>{err}</div> : null}
          <div className="row" style={{ gap: 8 }}>
            <Button size="sm" variant="dark" onClick={save} disabled={busy}>{busy ? T("جارٍ…", "Saving…") : T("حفظ الهدف", "Save target")}</Button>
            <span className="subtle" style={{ fontSize: 11.5, alignSelf: "center" }}>{T("اترك الحقل فارغًا للرجوع إلى مجموع أهداف الوكلاء.", "Leave a field blank to fall back to the sum of agent targets.")}</span>
          </div>
        </div>
      ) : !cas.targetSet ? (
        <div className="row" style={{ gap: 10, flexWrap: "wrap", alignItems: "center" }}>
          <div className="subtle" style={{ fontSize: 13, flex: 1, minWidth: 200, lineHeight: 1.5 }}>{T("لا يوجد هدف إيراد محدد بعد. اضبط هدفًا شهريًا للشركة لتفعيل السلسلة وخطة العمل.", "No revenue target set yet. Set a company monthly target to activate the cascade and action plan.")}</div>
          {readOnly
            ? <Button size="sm" variant="dark" icon="arrowRight" onClick={() => navToRevenueDirector(go)}>{T("اضبط هدفًا مع مدير الإيراد", "Set a target in Revenue Director")}</Button>
            : <Button size="sm" variant="dark" onClick={openEdit}>{T("اضبط هدفًا", "Set a target")}</Button>}
        </div>
      ) : (
        <>
          <div className="grid" style={{ gridTemplateColumns: "repeat(auto-fit, minmax(130px, 1fr))", gap: 12 }}>
            {[
              [T("الهدف", "Target"), vsar(cas.target), "var(--fg-1)"],
              [T("محقّق", "Closed"), vsar(cas.closed), "var(--color-secondary)"],
              [T("متوقّع (خط الأنابيب)", "Forecast (pipeline)"), vsar(cas.forecast), "var(--fg-1)"],
              [T("الفجوة", "Gap"), vsar(cas.gap), cas.gap > 0 ? "var(--color-orange)" : "var(--color-secondary)"],
            ].map(([k, v, c]) => (
              <div key={k} style={{ background: "var(--bg-2)", borderRadius: 10, padding: "12px 14px" }}>
                <div style={{ fontSize: 20, fontWeight: 800, letterSpacing: "-0.02em", color: c, overflowWrap: "anywhere" }}>{v}</div>
                <div style={{ fontSize: 11.5, color: "var(--fg-4)", marginTop: 3 }}>{k}</div>
              </div>
            ))}
          </div>
          <div className="subtle" style={{ fontSize: 11, marginTop: 8 }}>{cas.source === "company_target" ? T("الهدف: هدف الشركة المحدد · المتوقّع مرجّح بخط الأنابيب الحقيقي.", "Target: your set company target · Forecast weighted from the real pipeline.") : T("الهدف: مجموع أهداف الوكلاء (اضغط \"تعديل الهدف\" لضبط هدف شركة) · المتوقّع مرجّح بخط الأنابيب.", "Target: sum of agent targets (click “Edit target” to set a company target) · Forecast weighted from the real pipeline.")}</div>
        </>
      )}
    </div>
  );
}

// Target cascade — the funnel of required NEW activity to close the gap.
function CascadeSection({ cc, T, L }) {
  const cas = cc && cc.cascade;
  if (!cas) return null;
  return (
    <Card title={T("سلسلة الهدف — لإغلاق الفجوة، تحتاج إلى:", "Target cascade — to close the gap, you need:")} flush>
      {cas.onTrack ? (
        <div style={{ padding: "16px", fontSize: 13, color: "var(--fg-3)", lineHeight: 1.5 }}>
          <Icon name="checkcircle" size={16} style={{ color: "var(--color-secondary)" }} /> {T("التوقّع يغطّي الهدف — لا حاجة لعمل جديد هذا الشهر. أغلق ما في خط الأنابيب.", "Forecast covers the target — no new work needed this month. Close what's in the pipeline.")}
        </div>
      ) : (
        <div style={{ padding: "4px 0" }}>
          {(cas.layers || []).map((l) => (
            <div key={l.key} className="between" style={{ padding: "11px 16px", borderBottom: "1px solid var(--border-1)", gap: 12, alignItems: "center", flexWrap: "wrap" }}>
              <div style={{ minWidth: 0, flex: 1 }}>
                <div style={{ fontWeight: 700, fontSize: 13.5 }}>{L(l.label)}</div>
                <div style={{ fontSize: 11.5, color: "var(--fg-4)", marginTop: 2 }}>
                  {l.rate ? (l.rate.value != null ? `${T("متوسط", "avg")} ${vsar(l.rate.value)}` : `${L(l.rate.label)} ${l.rate.pct}%`) : (l.note ? l.note : "")}
                  {l.current != null ? ` · ${l.current} ${L(l.currentLabel) || ""}` : ""}
                </div>
              </div>
              <div style={{ textAlign: "end", flexShrink: 0, minWidth: 90 }}>
                {l.required != null
                  ? <div style={{ fontSize: 20, fontWeight: 800, letterSpacing: "-0.02em", color: "var(--color-secondary)" }}>+{l.required}</div>
                  : <Badge tone="neutral">{T("بيانات غير كافية", "needs more data")}</Badge>}
              </div>
            </div>
          ))}
        </div>
      )}
    </Card>
  );
}

// Agent ownership board — per-agent target/progress/forecast/gap/conv/status; expandable
// to the ownership panel (assigned workload + top responsible opportunities).
function AgentOwnershipRow({ b, T, L }) {
  const [open, setOpen] = React.useState(false);
  const st = AGENT_STATUS[b.status] || AGENT_STATUS.on_track;
  const a = b.assigned || {};
  return (
    <>
      <tr onClick={() => setOpen((o) => !o)} style={{ cursor: "pointer" }}>
        <td><div className="row" style={{ gap: 8 }}><Icon name={open ? "chevronDown" : "chevronRight"} size={12} style={{ color: "var(--fg-4)" }} /><Avatar name={b.name} size="sm" /><span style={{ fontWeight: 600 }}>{b.name}</span></div></td>
        <td>{vsar(b.target)}</td>
        <td><span style={{ fontWeight: 700 }}>{vsar(b.closed)}</span> <span className="muted" style={{ fontSize: 11 }}>{b.attainmentPct != null ? `(${b.attainmentPct}%)` : ""}</span></td>
        <td>{vsar(b.forecast)}</td>
        <td style={{ color: b.gap > 0 ? "var(--color-orange)" : "var(--color-secondary)" }}>{vsar(b.gap)}</td>
        <td>{b.conversionRate != null ? b.conversionRate + "%" : "—"}</td>
        <td><Badge tone={st.tone}>{T(st.ar, st.en)}</Badge></td>
      </tr>
      {open ? (
        <tr><td colSpan={7} style={{ background: "var(--bg-2)", padding: "12px 16px" }}>
          <div className="row" style={{ gap: 10, flexWrap: "wrap", marginBottom: 8 }}>
            {[[T("فرص", "Opps"), a.opportunities], [T("اجتماعات", "Meetings"), a.meetings], [T("عروض", "Proposals"), a.proposals], [T("متابعات مستحقة", "Follow-ups due"), a.followups]].map(([k, v]) => (
              <div key={k} style={{ background: "var(--color-bg)", borderRadius: 8, padding: "6px 10px", minWidth: 78 }}>
                <div style={{ fontSize: 16, fontWeight: 800 }}>{v == null ? 0 : v}</div>
                <div style={{ fontSize: 10.5, color: "var(--fg-4)" }}>{k}</div>
              </div>
            ))}
          </div>
          <div style={{ fontSize: 12.5, color: "var(--fg-3)" }}><b style={{ color: "var(--fg-1)" }}>{T("الإجراء المطلوب", "Required action")}: </b>{L(b.requiredAction)}</div>
          {(b.responsibleOpps || []).length ? (
            <div style={{ marginTop: 8 }}>
              <div className="subtle" style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.04em", marginBottom: 4 }}>{T("أبرز الفرص المسؤول عنها", "Top responsible opportunities")}</div>
              {b.responsibleOpps.map((o) => (
                <div key={o.id} className="between" style={{ fontSize: 12.5, padding: "3px 0" }}><span style={{ maxWidth: "65%", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{o.name}</span><span style={{ fontWeight: 600, color: "var(--fg-3)" }}>{vsar(o.value)}</span></div>
              ))}
            </div>
          ) : null}
        </td></tr>
      ) : null}
    </>
  );
}
function AgentBoardSection({ cc, T, L }) {
  const board = cc && cc.agentBoard;
  if (!board) return null;
  if (!board.length) return <Card title={T("لوحة ملكية الوكلاء", "Agent ownership board")} flush><VEmpty icon="users" title={T("لا أهداف بعد", "No targets yet")} body={T("اضبط هدف كل وكيل من وكلاء الذكاء ← تعديل.", "Set each agent's target in AI Agents → Edit.")} /></Card>;
  return (
    <Card title={T("لوحة ملكية الوكلاء", "Agent ownership board")} flush action={<span className="subtle" style={{ fontSize: 11 }}>{T("اضغط وكيلًا للتفاصيل", "Tap an agent for detail")}</span>}>
      <div style={{ overflowX: "auto", width: "100%" }}>
        <table className="table" style={{ width: "100%", fontSize: 13, minWidth: 680 }}>
          <thead><tr>{[T("الوكيل", "Agent"), T("الهدف", "Target"), T("محقّق", "Progress"), T("متوقّع", "Forecast"), T("الفجوة", "Gap"), T("تحويل", "Conv."), T("الحالة", "Status")].map((h, i) => <th key={i}>{h}</th>)}</tr></thead>
          <tbody>
            {board.map((b) => <AgentOwnershipRow key={b.agentId} b={b} T={T} L={L} />)}
          </tbody>
        </table>
      </div>
    </Card>
  );
}

// Revenue Director recommendations — explainable allocation (who/why/impact/action).
function AllocationSection({ cc, T, L }) {
  const recs = cc && cc.allocation;
  if (!recs) return null;
  if (!recs.length) return null;
  return (
    <Card title={T("توصيات مدير الإيرادات", "Revenue Director recommendations")} flush>
      <div style={{ padding: "4px 0" }}>
        {recs.map((r, i) => (
          <div key={r.kind + i} className="row" style={{ padding: "12px 16px", borderBottom: "1px solid var(--border-1)", gap: 12, alignItems: "flex-start" }}>
            <span className="opp" style={{ width: 30, height: 30, borderRadius: 8, background: "var(--bg-2)", color: "var(--color-secondary)", flexShrink: 0 }}><Icon name={ALLOC_ICON[r.kind] || "zap"} size={14} /></span>
            <div style={{ minWidth: 0, flex: 1 }}>
              <div className="between" style={{ gap: 8, flexWrap: "wrap" }}>
                <span style={{ fontWeight: 700, fontSize: 13.5 }}>{L(r.title)}{r.detail ? <span className="subtle" style={{ fontWeight: 500 }}> · {r.detail}</span> : null}</span>
                {r.revenueImpact ? <span style={{ fontSize: 12.5, fontWeight: 700, color: "var(--color-secondary)", whiteSpace: "nowrap" }}>{r.revenueImpact}<span className="subtle" style={{ fontWeight: 500, fontSize: 11 }}> {L(r.revenueImpactLabel)}</span></span> : null}
              </div>
              <div style={{ fontSize: 12.5, color: "var(--fg-4)", marginTop: 2, lineHeight: 1.5 }}>{L(r.why)}</div>
              <div style={{ fontSize: 12.5, fontWeight: 600, color: "var(--color-secondary)", marginTop: 3 }}>→ {L(r.action)}</div>
            </div>
          </div>
        ))}
      </div>
    </Card>
  );
}

// Owner action plan — plain "to hit target, do this" list (Part 5).
function ActionPlanSection({ cc, T, L }) {
  const plan = cc && cc.actionPlan;
  if (!plan) return null;
  return (
    <Card title={T("خطة المالك — لتحقيق هدف هذا الشهر:", "Owner action plan — to hit this month's target:")} flush>
      <div style={{ padding: "4px 0" }}>
        {(plan.items || []).map((it) => (
          <div key={it.key} className="row" style={{ padding: "11px 16px", borderBottom: "1px solid var(--border-1)", gap: 12, alignItems: "center" }}>
            <span style={{ width: 24, height: 24, borderRadius: 7, background: it.key === "on_track" ? "var(--color-secondary)" : "var(--bg-2)", color: it.key === "on_track" ? "#fff" : "var(--color-secondary)", display: "inline-flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
              <Icon name={it.key === "on_track" ? "checkcircle" : "arrowRight"} size={13} />
            </span>
            <div style={{ fontSize: 13.5, lineHeight: 1.5 }}>{L(it.text)}</div>
          </div>
        ))}
      </div>
    </Card>
  );
}

// Revenue ownership summary — who owns the gap (Slice 3 STAGE 5). Owners sum to netAgentGap.
function GapOwnershipSection({ cc, T }) {
  const g = cc && cc.gapOwnership;
  if (!g || !g.targetSet) return null;
  const owners = g.owners || [];
  return (
    <Card title={T("ملكية الفجوة — من يملك الفجوة؟", "Gap ownership — who owns the gap?")} flush>
      <div style={{ padding: "12px 16px" }}>
        <div className="row" style={{ gap: 20, flexWrap: "wrap", marginBottom: owners.length ? 12 : 0 }}>
          <div><div style={{ fontSize: 20, fontWeight: 800, color: "var(--color-orange)", letterSpacing: "-0.02em" }}>{vsar(g.netAgentGap)}</div><div className="subtle" style={{ fontSize: 11.5 }}>{T("فجوة مملوكة للوكلاء", "gap owned by agents")}</div></div>
          {g.unallocated > 0 ? <div><div style={{ fontSize: 20, fontWeight: 800, letterSpacing: "-0.02em" }}>{vsar(g.unallocated)}</div><div className="subtle" style={{ fontSize: 11.5 }}>{T("غير مخصّصة", "unallocated")}</div></div> : null}
        </div>
        {owners.length ? owners.map((o) => {
          const st = AGENT_STATUS[o.status] || {};
          return (
            <div key={o.agentId} className="between" style={{ padding: "8px 0", borderTop: "1px solid var(--border-1)" }}>
              <div className="row" style={{ gap: 8 }}><Avatar name={o.name} size="sm" /><span style={{ fontWeight: 600, fontSize: 13 }}>{o.name}</span>{st.en ? <Badge tone={st.tone}>{T(st.ar, st.en)}</Badge> : null}</div>
              <div className="row" style={{ gap: 10 }}><span className="subtle" style={{ fontSize: 11.5 }}>{o.sharePct}%</span><span style={{ fontWeight: 700, color: "var(--color-orange)" }}>{vsar(o.gap)}</span></div>
            </div>
          );
        }) : <div className="subtle" style={{ fontSize: 13 }}>{T("لا فجوة مملوكة — كل وكيل عند هدفه أو يتجاوزه.", "No owned gap — every agent is at or above target.")}</div>}
        {g.companyGap !== g.netAgentGap ? (
          <div className="subtle" style={{ fontSize: 11, marginTop: 8, lineHeight: 1.5 }}>
            {g.companyGap > g.netAgentGap
              ? T(`فجوة هدف الشركة ${vsar(g.companyGap)} أكبر — ${vsar(g.unallocated)} غير مُسنَدة لمغلِّق${g.forecastBasisDiff > 0 ? `، و${vsar(g.forecastBasisDiff)} صفقات مغلقة عبر جهات الاتصال لا يحتسبها توقّع الفرص بعد` : ""}.`,
                 `Company target gap is ${vsar(g.companyGap)} — larger by ${vsar(g.unallocated)} not assigned to a closer${g.forecastBasisDiff > 0 ? `, plus ${vsar(g.forecastBasisDiff)} of won deals the company forecast doesn't yet count (closed via contacts, not opportunities)` : ""}.`)
              : T(`توقّع الشركة (خط أنابيب الفرص) متقدّم على لوحة الوكلاء، لذا فجوة الشركة ${vsar(g.companyGap)} أصغر من الفجوة المملوكة للوكلاء.`,
                 `Company forecast (opportunity pipeline) is ahead of the agent board, so the company gap (${vsar(g.companyGap)}) is smaller than the agent-owned gap.`)}
          </div>
        ) : null}
      </div>
    </Card>
  );
}

// Product ownership board (Slice 3 STAGE 4) — owner + real won/forecast/pipeline per line.
function ProductOwnershipSection({ cc, T, L }) {
  const p = cc && cc.productOwnership;
  if (!p || !p.rows) return null;
  const rows = p.rows.filter((r) => r.ownerName || r.current > 0 || r.forecast > 0 || r.pipeline > 0);
  if (!rows.length) return null;
  return (
    <Card title={T("لوحة ملكية المنتجات", "Product ownership board")} flush>
      <div style={{ overflowX: "auto", width: "100%" }}>
        <table className="table" style={{ width: "100%", fontSize: 13, minWidth: 620 }}>
          <thead><tr>{[T("المنتج", "Product"), T("المالك", "Owner"), T("محقّق", "Current"), T("متوقّع", "Forecast"), T("خط الأنابيب", "Pipeline"), T("الفجوة", "Gap")].map((h, i) => <th key={i}>{h}</th>)}</tr></thead>
          <tbody>
            {rows.map((r) => (
              <tr key={r.productType}>
                <td style={{ fontWeight: 600 }}>{L(r.label)}</td>
                <td>{r.ownerName ? <div className="row" style={{ gap: 8 }}><Avatar name={r.ownerName} size="sm" /><span>{r.ownerName}</span></div> : <span className="muted">{T("غير مُسنَد", "Unassigned")}</span>}</td>
                <td style={{ fontWeight: 600 }}>{vsar(r.current)}</td>
                <td>{vsar(r.forecast)}</td>
                <td>{vsar(r.pipeline)}</td>
                <td>{r.target != null ? <span style={{ color: r.gap > 0 ? "var(--color-orange)" : "var(--color-secondary)" }}>{vsar(r.gap)}</span> : <span className="muted">{T("لا هدف", "no target")}</span>}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      {!p.hasProductTargets ? <div className="subtle" style={{ fontSize: 11, padding: "10px 16px", borderTop: "1px solid var(--border-1)", lineHeight: 1.5 }}>{T("أهداف المنتجات لكل خط لم تُضبط بعد — تُعرض الإيرادات والتوقّعات الحقيقية. (ضبط أهداف المنتجات يأتي في شريحة لاحقة.)", "Per-line product targets not set yet — real revenue & forecast are shown. (Product targets come in a later slice.)")}</div> : null}
    </Card>
  );
}

// Accountability dashboard (Slice 3 STAGE 6).
function AccountabilitySection({ cc, T, L }) {
  const a = cc && cc.accountability;
  if (!a) return null;
  const agentRow = (val, valColor) => (x) => (
    <div key={x.agentId} className="between" style={{ fontSize: 12.5 }}>
      <div className="row" style={{ gap: 8, minWidth: 0 }}><Avatar name={x.name} size="sm" /><span style={{ fontWeight: 600, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{x.name}</span></div>
      <span style={{ fontWeight: 700, color: valColor || "var(--fg-2)", whiteSpace: "nowrap" }}>{val(x)}</span>
    </div>
  );
  const card = (title, items, render, emptyTone) => (
    <Card title={title}>
      {items && items.length ? <div className="col" style={{ gap: 8, marginTop: 4 }}>{items.map(render)}</div> : <div className="subtle" style={{ fontSize: 12.5 }}>{T("لا شيء", "None")}</div>}
    </Card>
  );
  return (
    <div>
      <div className="row" style={{ gap: 8, marginBottom: 14 }}><Icon name="users" size={18} style={{ color: "var(--color-secondary)" }} /><h6 style={{ margin: 0 }}>{T("لوحة المساءلة", "Revenue accountability")}</h6></div>
      <div className="grid" style={{ gridTemplateColumns: "repeat(auto-fit, minmax(250px, 1fr))", gap: 16 }}>
        {card(T("الأفضل أداءً", "Top performers"), a.topPerformers, agentRow((x) => (x.attainmentPct || 0) + "%", "var(--color-secondary)"))}
        {card(T("أكبر المساهمين", "Largest contributors"), a.largestContributors, agentRow((x) => vsar(x.closed), "var(--color-secondary)"))}
        {card(T("أكبر الفجوات", "Largest revenue gaps"), a.largestGaps, agentRow((x) => vsar(x.gap), "var(--color-orange)"))}
        {card(T("في خطر", "At risk"), a.atRisk, agentRow((x) => vsar(x.gap), "var(--color-orange)"))}
        {card(T("حالات حرجة", "Critical"), a.critical, agentRow((x) => vsar(x.gap), "var(--color-danger)"))}
        <Card title={T("أكبر الفرص (القيمة الكاملة)", "Biggest opportunities (full potential)")}>
          {a.biggestOpportunities && a.biggestOpportunities.length ? <div className="col" style={{ gap: 8, marginTop: 4 }}>{a.biggestOpportunities.map((o) => (
            <div key={o.id} className="between" style={{ fontSize: 12.5 }}><span style={{ maxWidth: "55%", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{o.name}{o.owner ? <span className="subtle"> · {o.owner}</span> : ""}</span><span className="row" style={{ gap: 6 }}>{o.roiScore != null ? <Badge tone="lime" title={T("درجة العائد", "ROI Score")}>{T("عائد", "ROI")} {o.roiScore}</Badge> : null}<span style={{ fontWeight: 700, color: "var(--color-secondary)" }}>{vsar(o.potential != null ? o.potential : o.value)}</span></span></div>
          ))}</div> : <div className="subtle" style={{ fontSize: 12.5 }}>{T("لا فرص مفتوحة بقيمة", "No valued open opportunities")}</div>}
        </Card>
      </div>
    </div>
  );
}

// Learning watch list (Slice 3 STAGE 9) — SURFACE only; feeds the future Learning Center.
function LearningWatchSection({ cc, T, L }) {
  const ls = cc && cc.learningSignals;
  if (!ls) return null;
  const watch = ls.agentsToWatch || [], lost = ls.lostReasons || [], under = ls.underperformingProducts || [];
  if (!watch.length && !lost.length && !under.length) return null;
  return (
    <Card title={T("قائمة متابعة للتعلّم", "Learning watch list")} flush>
      <div style={{ padding: "10px 16px 14px" }}>
        <div className="subtle" style={{ fontSize: 11.5, marginBottom: 10, lineHeight: 1.5 }}>{L(ls.note)}</div>
        {watch.length ? <div style={{ marginBottom: 8 }}><b style={{ fontSize: 12.5 }}>{T("وكلاء للمراجعة", "Agents to review")}: </b>{watch.map((w) => <Badge key={w.agentId} tone={(AGENT_STATUS[w.status] || {}).tone || "neutral"} style={{ marginInlineEnd: 4 }}>{w.name}</Badge>)}</div> : null}
        {lost.length ? <div style={{ marginBottom: 8, fontSize: 12.5 }}><b>{T("أسباب الخسارة المتكرّرة", "Repeated loss reasons")}: </b><span className="subtle">{lost.map((l, i) => `${l.reason} (${l.count})${i < lost.length - 1 ? " · " : ""}`)}</span></div> : null}
        {under.length ? <div style={{ fontSize: 12.5 }}><b>{T("منتجات ضعيفة الأداء", "Underperforming products")}: </b><span className="subtle">{under.map((u, i) => `${L(u.label)} (${u.won}W/${u.lost}L)${i < under.length - 1 ? " · " : ""}`)}</span></div> : null}
      </div>
    </Card>
  );
}

// ===== CEO MODE — the founder's 30-second decision view =====
const CEO_RISK_ICON = { leak: "alert", weak_pipeline: "trending", critical_agents: "users" };
function CeoStatCard({ label, value, sub, tone, big }) {
  return (
    <div className="card" style={{ padding: 18 }}>
      <div style={{ fontSize: 12, color: "var(--fg-4)", fontWeight: 600 }}>{label}</div>
      <div style={{ fontSize: big ? 30 : 26, fontWeight: 800, letterSpacing: "-0.02em", marginTop: 6, color: tone || "var(--fg-1)", overflowWrap: "anywhere", lineHeight: 1.05 }}>{value}</div>
      {sub ? <div style={{ fontSize: 12, color: "var(--fg-4)", marginTop: 4 }}>{sub}</div> : null}
    </div>
  );
}
// Revenue Director per-product allocation (Tranche C). CEO Mode shows ONLY the recommended path;
// Advanced shows the full path comparison + owner options + effort matrix + workload. Reads
// cc.productStrategy; honest "Needs more data" everywhere a field is null. Null-guarded → renders
// nothing when there is no strategy/target.
const STRAT_RISK_TONE = { low: "green", medium: "orange", high: "red" };
const STRAT_CAT_TONE = { "Quick Win": "green", "Strategic Bet": "purple", "High Revenue / High Effort": "orange", "Low Priority": "neutral", "Needs Proof First": "neutral" };
function RecommendedPathSummary({ cc, T, lang, onAdvanced }) {
  const ps = cc && cc.productStrategy;
  if (!ps || !ps.recommended) return null;
  const L = (x) => (x && typeof x === "object" ? (lang === "ar" ? x.ar : x.en) : x);
  const r = ps.recommended;
  return (
    <Card title={<span className="row" style={{ gap: 8 }}><Icon name="target" size={15} style={{ color: "var(--color-secondary)" }} />{T("أفضل مسار للوصول للهدف", "Best path to target")}</span>} flush>
      <div className="col" style={{ gap: 10, padding: 14 }}>
        <div className="row" style={{ gap: 8, flexWrap: "wrap", alignItems: "center" }}>
          <b style={{ fontSize: 15 }}>{L(r.label)}</b>
          <Badge tone={r.coversGap ? "green" : "orange"}>{r.coversGap ? T("يغطّي الفجوة", "covers the gap") : T("يقلّص الفجوة", "narrows the gap")}</Badge>
          <Badge tone={r.confidence === "measured" ? "green" : "neutral"}>{r.confidence === "measured" ? T("مُقاس", "measured") : T("بيانات غير كافية", "needs more data")}</Badge>
        </div>
        <div style={{ fontSize: 13, color: "var(--fg-2)", lineHeight: 1.5 }}>{L(r.why)}</div>
        <div className="row" style={{ gap: 20, flexWrap: "wrap" }}>
          <div><div className="subtle" style={{ fontSize: 11.5 }}>{T("الإيراد المتوقّع", "Expected revenue")}</div><b style={{ fontSize: 16, color: "var(--color-secondary)" }}>{vsar(r.expectedRevenue)}</b></div>
          <div><div className="subtle" style={{ fontSize: 11.5 }}>{T("صفقات", "Deals")}</div><b style={{ fontSize: 16 }}>{r.deals}</b></div>
          <div><div className="subtle" style={{ fontSize: 11.5 }}>{T("وكلاء", "Agents")}</div><b style={{ fontSize: 16 }}>{r.agentsRequired}</b></div>
          {r.focus ? <div style={{ minWidth: 0 }}><div className="subtle" style={{ fontSize: 11.5 }}>{T("ابدأ بـ", "Start with")}</div><b style={{ fontSize: 14 }}>{L(r.focus.label)}{r.focus.owner ? ` · ${r.focus.owner.name}` : ""}</b></div> : null}
        </div>
        <button className="btn btn--subtle btn--sm" style={{ alignSelf: "flex-start" }} onClick={onAdvanced}>{T("قارن كل المسارات في تخطيط الهدف ←", "Compare all paths in Target Planning →")}</button>
      </div>
    </Card>
  );
}
// P4 — Revenue Autopilot: the concrete product MIX to hit target ("Sell: 2× Growth + 1× Shopify ≈
// SAR 126,000"). Reads cc.revenueStrategyPlan (re-projection of the recommended path). CEO-mode.
// ============================================================================
// CEO REVENUE AUTOPILOT V3 — concise founder-facing presentation of the ceoAutopilot engine.
// All sections read cc.ceoAutopilot (operatingSystem payload). Honest empties; margin is shown
// as a LABELLED model assumption, probabilities only when the engine measured them.
// ============================================================================
const FM_TONE = { good: "var(--color-secondary)", warn: "var(--color-orange)", bad: "var(--color-danger)", action: "var(--color-secondary)", neutral: "var(--fg-3)" };
const FM_ICON = { target_status: "target", fastest_path: "zap", biggest_risk: "alert", biggest_opportunity: "trending", next_action: "arrowRight" };
const WL_TONE = { overloaded: "orange", underutilized: "blue", healthy: "green" };
const SEV_TONE = { high: "red", medium: "orange", low: "neutral" };

// PART 7 — Founder Mode: EXACTLY five cards (Target Status / Fastest Path / Biggest Risk /
// Biggest Opportunity / Next Action). No tables, no clutter. The glanceable CEO header.
function FounderModeSection({ cc, T, lang }) {
  const auto = cc && cc.ceoAutopilot;
  const fm = auto && auto.founderMode;
  if (!fm || !(fm.cards || []).length) return null;
  const L = (x) => (x && typeof x === "object" ? (lang === "ar" ? x.ar : x.en) : x);
  return (
    <div className="grid" style={{ gridTemplateColumns: "repeat(auto-fit, minmax(190px, 1fr))", gap: 12 }}>
      {fm.cards.map((c) => {
        const tone = FM_TONE[c.tone] || "var(--fg-3)";
        return (
          <div key={c.key} className="card" style={{ padding: 14, borderTop: "3px solid " + tone, display: "flex", flexDirection: "column", gap: 5, minWidth: 0 }}>
            <div className="row" style={{ gap: 6, alignItems: "center" }}>
              <Icon name={FM_ICON[c.key] || "info"} size={13} style={{ color: tone, flexShrink: 0 }} />
              <span className="subtle" style={{ fontSize: 11, fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.03em" }}>{L(c.title)}</span>
            </div>
            <div style={{ fontSize: 14.5, fontWeight: 800, lineHeight: 1.35, color: c.tone === "bad" ? "var(--color-danger)" : "var(--fg-1)" }}>{L(c.headline)}</div>
            {c.detail ? <div className="subtle" style={{ fontSize: 12, lineHeight: 1.45 }}>{L(c.detail)}</div> : null}
          </div>
        );
      })}
    </div>
  );
}

// PART 1 — Product Profitability: score 0–100 + the dimensions behind it. Margin is a labelled
// model heuristic; win% / cycle / competition show honest "—" when the engine has not measured them.
function ProductProfitabilitySection({ cc, T, lang }) {
  const auto = cc && cc.ceoAutopilot;
  const prof = auto && auto.productProfitability;
  if (!prof || !(prof.rows || []).length) return null;
  const L = (x) => (x && typeof x === "object" ? (lang === "ar" ? x.ar : x.en) : x);
  const ND = <span className="subtle">—</span>;
  const scoreTone = (s) => s >= 70 ? "green" : s >= 45 ? "neutral" : "orange";
  return (
    <Card title={<span className="row" style={{ gap: 8 }}><Icon name="trending" size={15} style={{ color: "var(--color-secondary)" }} />{T("ربحية المنتجات", "Product profitability")}</span>}
      action={<span className="subtle" style={{ fontSize: 11.5 }}>{T("الهامش تقدير حسب النموذج", "margin = model assumption")}</span>} flush>
      <div style={{ overflowX: "auto", width: "100%", padding: "4px 0" }}>
        <table className="table" style={{ width: "100%", minWidth: 640 }}>
          <thead><tr><th>{T("المنتج", "Product")}</th><th>{T("الدرجة", "Score")}</th><th>{T("الهامش (نموذج)", "Margin (model)")}</th><th>{T("احتمال الإغلاق", "Win %")}</th><th>{T("الدورة", "Cycle")}</th><th>{T("المنافسة", "Competition")}</th></tr></thead>
          <tbody>
            {prof.rows.map((r) => (
              <tr key={r.productType}>
                <td style={{ fontWeight: 600 }}>{L(r.label)}</td>
                <td><Badge tone={scoreTone(r.profitabilityScore)}>{r.profitabilityScore}/100</Badge></td>
                <td>{r.margin.score != null ? <span><b>{r.margin.score}</b> <span className="subtle" style={{ fontSize: 11 }}>{L(r.margin.modelLabel)}</span></span> : ND}</td>
                <td>{r.probabilityOfClosing != null ? r.probabilityOfClosing + "%" : ND}</td>
                <td>{r.salesCycle.days != null ? r.salesCycle.days + T("ي", "d") : ND}</td>
                <td>{r.competition.level === "unknown" ? ND : <Badge tone={r.competition.level === "high" ? "red" : r.competition.level === "medium" ? "orange" : "green"}>{r.competition.level}</Badge>}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      <div className="subtle" style={{ fontSize: 11, padding: "0 14px 12px", lineHeight: 1.5 }}>{L(prof.marginNote)}</div>
    </Card>
  );
}

// PART 2 — Revenue Priority Board: top pick per lens (why now) + the overall priority.
function RevenuePriorityBoardSection({ cc, T, lang }) {
  const auto = cc && cc.ceoAutopilot;
  const board = auto && auto.revenuePriorityBoard;
  if (!board || !(board.lenses || []).length) return null;
  const L = (x) => (x && typeof x === "object" ? (lang === "ar" ? x.ar : x.en) : x);
  return (
    <Card title={<span className="row" style={{ gap: 8 }}><Icon name="layers" size={15} style={{ color: "var(--color-secondary)" }} />{T("لوحة أولويات الإيراد", "Revenue priority board")}</span>} flush>
      <div className="col" style={{ gap: 10, padding: 14 }}>
        {board.topPick ? (
          <div className="card" style={{ padding: 10, background: "var(--bg-2)", borderInlineStart: "3px solid var(--color-secondary)" }}>
            <div style={{ fontSize: 13, lineHeight: 1.5 }}><b>{T("الأولوية الأولى: ", "Top priority: ")}</b>{L(board.topPick.label)} <span className="subtle">({board.topPick.score}/100)</span> — {L(board.topPick.whyNow)}</div>
          </div>
        ) : null}
        <div className="grid" style={{ gridTemplateColumns: "repeat(auto-fit, minmax(220px, 1fr))", gap: 10 }}>
          {board.lenses.map((l) => (
            <div key={l.key} style={{ background: "var(--bg-2)", borderRadius: 10, padding: "10px 12px", minWidth: 0 }}>
              <div className="subtle" style={{ fontSize: 11, fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.03em" }}>{L(l.label)}</div>
              {l.topPick ? <div style={{ marginTop: 4 }}><b style={{ fontSize: 13 }}>{L(l.topPick.label)}</b><div className="subtle" style={{ fontSize: 11.5, marginTop: 2, lineHeight: 1.4 }}>{L(l.topPick.why)}</div></div> : <div className="subtle" style={{ fontSize: 12, marginTop: 4 }}>{T("لا بيانات", "No data")}</div>}
            </div>
          ))}
        </div>
      </div>
    </Card>
  );
}

// PART 3 — Target Achievement Scenarios: real strategy paths (A/B/C…) + AI-Sales-Agent tier
// coverage. Probabilities are MEASURED-or-assumption (never fabricated).
function TargetScenariosSection({ cc, T, lang }) {
  const auto = cc && cc.ceoAutopilot;
  const sc = auto && auto.targetScenarios;
  if (!sc) return null;
  const L = (x) => (x && typeof x === "object" ? (lang === "ar" ? x.ar : x.en) : x);
  const title = <span className="row" style={{ gap: 8 }}><Icon name="target" size={15} style={{ color: "var(--color-secondary)" }} />{T("سيناريوهات الوصول للهدف", "Target achievement scenarios")}</span>;
  if (!sc.targetSet) return <Card title={title} flush><div className="subtle" style={{ fontSize: 12.5, padding: 14 }}>{L(sc.note)}</div></Card>;
  const probBadge = (p) => <Badge tone={p.state === "measured" ? "green" : "neutral"}>{p.state === "measured" ? T("مُقاس", "measured") : T("تقدير", "estimate")}</Badge>;
  return (
    <Card title={title} flush>
      <div className="col" style={{ gap: 14, padding: 14 }}>
        {(sc.scenarios || []).length ? (
          <div style={{ overflowX: "auto", width: "100%" }}>
            <table className="table" style={{ width: "100%", minWidth: 620 }}>
              <thead><tr><th>{T("سيناريو", "Scenario")}</th><th>{T("المزيج", "Mix")}</th><th>{T("الإيراد", "Revenue")}</th><th>{T("المخاطرة", "Risk")}</th><th>{T("الجهد", "Effort")}</th><th>{T("الاحتمال", "Probability")}</th></tr></thead>
              <tbody>
                {sc.scenarios.map((s) => (
                  <tr key={s.key}>
                    <td style={{ fontWeight: 700, whiteSpace: "nowrap" }}>{s.ref} · {L(s.label)}</td>
                    <td style={{ fontSize: 12 }}>{L(s.summary)}</td>
                    <td style={{ fontWeight: 700, color: "var(--color-secondary)" }}>{vsar(s.expectedRevenue)}{s.coversGap ? <Badge tone="green" style={{ marginInlineStart: 6 }}>{T("يغطّي", "covers")}</Badge> : null}</td>
                    <td><Badge tone={STRAT_RISK_TONE[s.risk && s.risk.en] || "neutral"}>{L(s.risk)}</Badge></td>
                    <td>{L(s.effort)}</td>
                    <td>{probBadge(s.probability)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ) : <div className="subtle" style={{ fontSize: 12.5 }}>{L(sc.note)}</div>}
        {(sc.aiSalesAgentScenarios || []).length ? (
          <div>
            <div className="subtle" style={{ fontSize: 11.5, fontWeight: 700, marginBottom: 6 }}>{T("مسار وكيل المبيعات الذكي (تغطية الفجوة)", "AI Sales Agent path (gap coverage)")}</div>
            <div className="grid" style={{ gridTemplateColumns: "repeat(auto-fit, minmax(180px, 1fr))", gap: 10 }}>
              {sc.aiSalesAgentScenarios.map((a) => (
                <div key={a.tier} style={{ background: "var(--bg-2)", borderRadius: 10, padding: "10px 12px" }}>
                  <div style={{ fontWeight: 700, fontSize: 13 }}>{L(a.name)} <span className="subtle" style={{ fontWeight: 400, fontSize: 11 }}>· {a.agentCountLabel}</span></div>
                  <div style={{ fontSize: 15, fontWeight: 800, color: "var(--color-secondary)", marginTop: 2 }}>{a.unitsToCoverGap}× <span style={{ fontSize: 12, fontWeight: 600, color: "var(--fg-2)" }}>= {vsar(a.coverageRevenue)}</span></div>
                  <div className="subtle" style={{ fontSize: 11, marginTop: 3 }}>{vsar(a.annualPrice)}{T("/سنة", "/yr")} · {T("أو", "or")} {vsar(a.installment.monthly)}×{a.installment.count} (+{a.installment.surchargePct}%)</div>
                  <div style={{ marginTop: 4 }}>{a.probability.state === "measured" ? <Badge tone="green">{T("فوز", "win")} {a.probability.winRate}%</Badge> : <Badge tone="neutral">{T("احتمال غير مقيس", "win rate not measured")}</Badge>}</div>
                </div>
              ))}
            </div>
          </div>
        ) : null}
      </div>
    </Card>
  );
}

// PART 4 — Agent Workload Balancer: Overloaded / Healthy / Underutilised + can-execute check.
function AgentWorkloadSection({ cc, T, lang }) {
  const auto = cc && cc.ceoAutopilot;
  const wl = auto && auto.agentWorkloadBalance;
  if (!wl || !(wl.agents || []).length) return null;
  const L = (x) => (x && typeof x === "object" ? (lang === "ar" ? x.ar : x.en) : x);
  const statusLabel = { overloaded: T("محمّل بالكامل", "Overloaded"), underutilized: T("سعة فائضة", "Underutilised"), healthy: T("سليم", "Healthy") };
  return (
    <Card title={<span className="row" style={{ gap: 8 }}><Icon name="users" size={15} style={{ color: "var(--color-secondary)" }} />{T("موازنة أعباء الوكلاء", "Agent workload balance")}</span>}
      action={<span className="subtle" style={{ fontSize: 11.5 }}>{T("الحدّ", "cap")} {wl.cap}</span>} flush>
      <div style={{ overflowX: "auto", width: "100%", padding: "4px 0" }}>
        <table className="table" style={{ width: "100%", minWidth: 600 }}>
          <thead><tr><th>{T("الوكيل", "Agent")}</th><th>{T("الحالة", "Status")}</th><th>{T("فرص مفتوحة", "Open opps")}</th><th>{T("محادثات", "Convos")}</th><th>{T("اجتماعات", "Mtgs")}</th><th>{T("الإشغال", "Load")}</th><th>{T("ينفّذ الخطة؟", "Can execute?")}</th></tr></thead>
          <tbody>
            {wl.agents.map((a) => (
              <tr key={a.agentId}>
                <td style={{ fontWeight: 600 }}>{a.name}</td>
                <td><Badge tone={WL_TONE[a.status] || "neutral"}>{statusLabel[a.status]}</Badge></td>
                <td>{a.openOpps}<span className="subtle">/{a.capacity}</span></td>
                <td>{a.conversations}</td>
                <td>{a.meetings}</td>
                <td>{a.utilizationPct}%</td>
                <td>{a.canExecutePlan === false ? <Badge tone="orange">{T("وزّع الفائض", "redistribute")}</Badge> : <Badge tone="green">{T("نعم", "yes")}</Badge>}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      <div className="subtle" style={{ fontSize: 11, padding: "0 14px 12px" }}>{L(wl.capNote)}</div>
    </Card>
  );
}

// PART 5 — Competitive Gap Strategy: founder-entered competitors + recommended positioning.
function CompetitiveGapSection({ cc, T, lang }) {
  const auto = cc && cc.ceoAutopilot;
  const g = auto && auto.competitiveGapStrategy;
  if (!g) return null;
  const L = (x) => (x && typeof x === "object" ? (lang === "ar" ? x.ar : x.en) : x);
  const title = <span className="row" style={{ gap: 8 }}><Icon name="shield" size={15} style={{ color: "var(--color-secondary)" }} />{T("استراتيجية الفجوة التنافسية", "Competitive gap strategy")}</span>;
  return (
    <Card title={title} flush>
      <div className="col" style={{ gap: 12, padding: 14 }}>
        <div className="card" style={{ padding: 10, background: "var(--bg-2)", borderInlineStart: "3px solid var(--color-secondary)" }}>
          <div style={{ fontSize: 12.5, fontWeight: 600, lineHeight: 1.5 }}>{L(g.defaultPositioning)}</div>
        </div>
        {!g.hasData ? <div className="subtle" style={{ fontSize: 12.5 }}>{L(g.note)}</div> : (
          <div className="col" style={{ gap: 10 }}>
            {g.competitors.map((c, i) => (
              <div key={i} style={{ borderBottom: "1px solid var(--border-1)", paddingBottom: 10 }}>
                <div className="row" style={{ gap: 8, flexWrap: "wrap", alignItems: "center" }}>
                  <b style={{ fontSize: 13.5 }}>{c.name}</b>
                  {c.deliveryTime ? <Badge tone="neutral">{T("تسليم", "delivery")}: {c.deliveryTime}</Badge> : null}
                  {c.realRecord && c.realRecord.lostTo > 0 ? <Badge tone="orange">{T("خسرنا", "lost")} {c.realRecord.lostTo}</Badge> : null}
                  {c.realRecord && c.realRecord.mentions > 0 ? <span className="subtle" style={{ fontSize: 11 }}>{c.realRecord.mentions} {T("إشارة", "mentions")}</span> : null}
                </div>
                {(c.weaknesses || []).length ? <div className="subtle" style={{ fontSize: 11.5, marginTop: 3 }}>{T("ضعفهم", "Their gaps")}: {c.weaknesses.join(" · ")}</div> : null}
                <div style={{ fontSize: 12, fontWeight: 600, color: "var(--color-secondary)", marginTop: 3, lineHeight: 1.5 }}>→ {L(c.recommendedPositioning)}</div>
              </div>
            ))}
          </div>
        )}
      </div>
    </Card>
  );
}

// PART 6 — Weekly Sales Playbook: focus % per product + per-agent weekly required activities.
function WeeklyPlaybookSection({ cc, T, lang }) {
  const auto = cc && cc.ceoAutopilot;
  const wk = auto && auto.weeklySalesPlan;
  if (!wk) return null;
  const L = (x) => (x && typeof x === "object" ? (lang === "ar" ? x.ar : x.en) : x);
  const title = <span className="row" style={{ gap: 8 }}><Icon name="calendar" size={15} style={{ color: "var(--color-secondary)" }} />{T("خطة المبيعات الأسبوعية", "Weekly sales playbook")}</span>;
  if (!wk.hasPlan) return <Card title={title} flush><div className="subtle" style={{ fontSize: 12.5, padding: 14 }}>{L(wk.note)}</div></Card>;
  const N = (v) => v == null ? <span className="subtle">—</span> : v;
  return (
    <Card title={title} action={wk.weeklyTarget ? <span className="subtle" style={{ fontSize: 12 }}>{T("هدف الأسبوع", "Weekly target")} {vsar(wk.weeklyTarget)}</span> : null} flush>
      <div className="col" style={{ gap: 12, padding: 14 }}>
        <div>
          <div className="subtle" style={{ fontSize: 11.5, fontWeight: 700, marginBottom: 6 }}>{T("التركيز حسب المنتج", "Focus by product")}</div>
          <div className="col" style={{ gap: 6 }}>
            {wk.focus.map((f) => (
              <div key={f.productType} className="between" style={{ gap: 10, alignItems: "center" }}>
                <span style={{ fontSize: 12.5, fontWeight: 600, minWidth: 120 }}>{L(f.label)}{f.recurring ? <Badge tone="purple" style={{ marginInlineStart: 6 }}>{T("متكرّر", "recurring")}</Badge> : null}</span>
                <div style={{ flex: 1, height: 7, background: "var(--bg-2)", borderRadius: 999, overflow: "hidden", minWidth: 60 }}><div style={{ width: f.focusPct + "%", height: "100%", background: "var(--color-secondary)" }} /></div>
                <b style={{ fontSize: 12.5, width: 38, textAlign: "end" }}>{f.focusPct}%</b>
              </div>
            ))}
          </div>
        </div>
        {(wk.agents || []).length ? (
          <div style={{ overflowX: "auto", width: "100%" }}>
            <div className="subtle" style={{ fontSize: 11.5, fontWeight: 700, marginBottom: 6 }}>{T("لكل وكيل / أسبوع", "Per agent / week")}</div>
            <table className="table" style={{ width: "100%", minWidth: 520 }}>
              <thead><tr><th>{T("الوكيل", "Agent")}</th><th>{T("اجتماعات", "Meetings")}</th><th>{T("عروض", "Proposals")}</th><th>{T("متابعات", "Follow-ups")}</th><th>{T("عروض حيّة", "Demos")}</th></tr></thead>
              <tbody>
                {wk.agents.map((a) => (
                  <tr key={a.agentId}>
                    <td style={{ fontWeight: 600 }}>{a.name}{a.overloaded ? <Badge tone="orange" style={{ marginInlineStart: 6 }}>{T("محمّل", "loaded")}</Badge> : null}</td>
                    <td>{N(a.required.meetings)}</td><td>{N(a.required.proposals)}</td><td>{N(a.required.followups)}</td><td>{N(a.required.demos)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ) : null}
      </div>
    </Card>
  );
}

// PART 8 — What NOT to sell: de-prioritise flags with REAL reasons (never a single guess).
function AvoidSellingSection({ cc, T, lang }) {
  const auto = cc && cc.ceoAutopilot;
  const av = auto && auto.avoidSelling;
  if (!av || !(av.flags || []).length) return null;
  const L = (x) => (x && typeof x === "object" ? (lang === "ar" ? x.ar : x.en) : x);
  return (
    <Card title={<span className="row" style={{ gap: 8 }}><Icon name="alert" size={15} style={{ color: "var(--color-orange)" }} />{T("ما لا يجب بيعه الآن", "What NOT to sell right now")}</span>} flush>
      <div className="col" style={{ gap: 0, padding: "4px 0" }}>
        {av.flags.map((f) => (
          <div key={f.productType} className="row" style={{ padding: "11px 16px", borderBottom: "1px solid var(--border-1)", gap: 10, alignItems: "flex-start" }}>
            <Badge tone={SEV_TONE[f.severity] || "neutral"}>{f.severity}</Badge>
            <div style={{ minWidth: 0, flex: 1 }}>
              <b style={{ fontSize: 13.5 }}>{L(f.label)}</b>
              <div className="subtle" style={{ fontSize: 12, marginTop: 2, lineHeight: 1.5 }}>{(f.reasons || []).map((r) => L(r)).join(" · ")}</div>
            </div>
          </div>
        ))}
      </div>
      <div className="subtle" style={{ fontSize: 11, padding: "8px 16px 12px", lineHeight: 1.5 }}>{L(av.note)}</div>
    </Card>
  );
}

// PART 9 — AI Sales Agent Focus: recommended tier + WHY + the 3 tiers (annual + 3× installment).
function AiSalesAgentFocusSection({ cc, T, lang }) {
  const auto = cc && cc.ceoAutopilot;
  const f = auto && auto.aiSalesAgentFocus;
  if (!f || !(f.tiers || []).length) return null;
  const L = (x) => (x && typeof x === "object" ? (lang === "ar" ? x.ar : x.en) : x);
  return (
    <Card title={<span className="row" style={{ gap: 8 }}><Icon name="zap" size={15} style={{ color: "var(--color-secondary)" }} />{T("تركيز وكيل المبيعات الذكي", "AI Sales Agent focus")}</span>} flush>
      <div className="col" style={{ gap: 12, padding: 14 }}>
        <div className="card" style={{ padding: 10, background: "var(--bg-2)", borderInlineStart: "3px solid var(--color-secondary)" }}>
          <div style={{ fontSize: 13, lineHeight: 1.5 }}><b>{T("موصى به: ", "Recommended: ")}{L(f.recommendedName)}</b> — {L(f.why)}</div>
          <div className="subtle" style={{ fontSize: 11.5, marginTop: 3 }}>{f.probabilityNote.state === "measured" ? `${T("فوز مقيس", "measured win")} ${f.probabilityNote.winRate}%` : L(f.probabilityNote)}</div>
        </div>
        <div className="grid" style={{ gridTemplateColumns: "repeat(auto-fit, minmax(170px, 1fr))", gap: 10 }}>
          {f.tiers.map((t) => {
            const isRec = t.tier === f.recommendedTier;
            return (
              <div key={t.tier} style={{ background: "var(--bg-2)", borderRadius: 10, padding: "10px 12px", border: isRec ? "2px solid var(--color-secondary)" : "2px solid transparent" }}>
                <div className="between" style={{ gap: 6 }}><b style={{ fontSize: 13 }}>{L(t.name)}</b>{isRec ? <Badge tone="green">{T("موصى", "pick")}</Badge> : null}</div>
                <div style={{ fontSize: 15, fontWeight: 800, color: "var(--color-secondary)", marginTop: 2 }}>{vsar(t.annual)}<span style={{ fontSize: 11, fontWeight: 500, color: "var(--fg-3)" }}>{T("/سنة", "/yr")}</span></div>
                <div className="subtle" style={{ fontSize: 11, marginTop: 3 }}>{T("أو", "or")} {vsar(t.installment.monthly)} × {t.installment.count} (+{t.installment.surchargePct}%)</div>
                <div className="subtle" style={{ fontSize: 11, marginTop: 2 }}>{t.agentCountLabel} {T("وكلاء", "agents")} · {L(t.forWho)}</div>
              </div>
            );
          })}
        </div>
        <div className="subtle" style={{ fontSize: 11, lineHeight: 1.5 }}>{L(f.installmentNote)}</div>
      </div>
    </Card>
  );
}

// ============================================================================
// SALES MANAGER EXECUTION BRIDGE — the Execution Board. CEO-Autopilot recommendations become
// manager-APPROVED executable work. CEO Mode shows the top 3; Advanced shows the full board.
// Nothing runs automatically — every action is Approve / Execute / Reject, through the existing
// action layer. Advisory actions (coach/pause/prioritise/review) are clearly marked.
// ============================================================================
const EXEC_TYPE_LABEL = {
  follow_up: { ar: "متابعة", en: "Follow-up" }, schedule_meeting: { ar: "اجتماع", en: "Meeting" }, create_proposal: { ar: "عرض", en: "Proposal" },
  create_payment_link: { ar: "رابط دفع", en: "Payment link" }, create_invoice: { ar: "فاتورة", en: "Invoice" }, create_installment_plan: { ar: "تقسيط", en: "Installments" }, create_subscription: { ar: "اشتراك", en: "Subscription" },
  check_payment: { ar: "حالة الدفع", en: "Payment status" }, assign_opportunity: { ar: "إسناد", en: "Assign" }, reassign_opportunity: { ar: "إعادة إسناد", en: "Reassign" },
  coach_agent: { ar: "تدريب", en: "Coaching" }, pause_low_priority_work: { ar: "إيقاف مؤقت", en: "Pause" }, prioritize_product: { ar: "أولوية", en: "Prioritise" }, review_lost_deal: { ar: "مراجعة", en: "Review" },
};
const EXEC_URGENCY_TONE = { high: "red", medium: "orange", low: "neutral" };
const EXEC_STATUS_TONE = { pending: "neutral", approved: "blue", executed: "green", rejected: "neutral", failed: "red", pending_approval: "orange" };

function ExecutionBoardSection({ cc, T, lang, mode = "advanced", readOnly }) {
  const plan = cc && cc.executionPlan;
  const { go } = useApp();
  const [busy, setBusy] = React.useState({});
  const L = (x) => (x && typeof x === "object" ? (lang === "ar" ? x.ar : x.en) : x);
  if (!plan || !(plan.actions || []).length) return null;
  const rows = mode === "ceo" ? (plan.top3 || []) : (plan.actions || []);
  if (!rows.length) return null;

  const [orch, setOrch] = React.useState("");
  const rules = plan.approvalRules || { autoApprove: false };
  const act = async (a, kind) => {
    setBusy((b) => ({ ...b, [a.signature]: true }));
    try {
      if (kind === "approve") await API.agentActions.executionApprove(a.signature);
      else if (kind === "reject") await API.agentActions.executionReject(a.signature);
      else await API.agentActions.executionExecute(a.signature);
      if (kind === "execute" && a.coachingLink) { try { go("agents"); window.dispatchEvent(new CustomEvent("maxab:navtab", { detail: { screen: "agents", tab: a.coachingLink.tab } })); } catch (e) {} }
      await Actions.loadValidation("commandCenter");
    } catch (e) {}
    setBusy((b) => ({ ...b, [a.signature]: false }));
  };
  // AI Orchestrator — toggle auto-approval, or run all low-risk (auto-tier) actions in one pass.
  const toggleAuto = async () => { setOrch("toggle"); try { await API.settings.update({ orchestratorAutoApprove: !rules.autoApprove }); await Actions.loadValidation("commandCenter"); } catch (e) {} setOrch(""); };
  const runSafe = async () => { setOrch("run"); try { await API.agentActions.executionRunAuto(); await Actions.loadValidation("commandCenter"); } catch (e) {} setOrch(""); };

  const Buttons = ({ a }) => {
    const isBusy = !!busy[a.signature];
    if (a.status === "executed") return <Badge tone="green">{a.advisory ? T("تم", "Done") : T("نُفّذ", "Executed")}</Badge>;
    if (a.status === "rejected") return <span className="subtle" style={{ fontSize: 11.5 }}>{T("مُستبعد", "Dismissed")}</span>;
    // Read-only (Revenue & Customer DATA screen): approving/executing is owned by the Revenue Director — link, don't act.
    if (readOnly) return <button className="btn btn--subtle btn--sm" onClick={() => navToRevenueDirector(go)}>{T("نفّذ في مدير الإيراد ←", "Act in Revenue Director →")}</button>;
    return (
      <div className="row" style={{ gap: 6, flexWrap: "wrap", justifyContent: "flex-end" }}>
        {!a.advisory && a.status !== "approved" ? <button className="btn btn--subtle btn--sm" disabled={isBusy} onClick={() => act(a, "approve")}>{T("اعتمد", "Approve")}</button> : null}
        <Button size="sm" variant="dark" disabled={isBusy} onClick={() => act(a, "execute")}>{a.advisory ? (a.coachingLink ? T("افتح", "Open") : T("علّم تم", "Mark done")) : T("نفّذ", "Execute")}</Button>
        <button className="btn btn--subtle btn--sm" disabled={isBusy} onClick={() => act(a, "reject")}>{T("استبعد", "Dismiss")}</button>
      </div>
    );
  };

  return (
    <Card title={<span className="row" style={{ gap: 8 }}><Icon name="zap" size={15} style={{ color: "var(--color-secondary)" }} />{T("لوحة التنفيذ — مدير المبيعات", "Execution Board — Sales Manager")}</span>}
      action={mode === "ceo" || readOnly
        ? <span className="subtle" style={{ fontSize: 11.5 }}>{plan.summary.executable} {T("قابلة للتنفيذ", "executable")} · {plan.summary.advisory} {T("إرشادية", "advisory")}</span>
        : <span className="row" style={{ gap: 6, flexWrap: "wrap", alignItems: "center" }}>
            <button className="btn btn--subtle btn--sm" disabled={orch === "toggle"} onClick={toggleAuto} title={T("الاعتماد التلقائي للإجراءات منخفضة المخاطر", "Auto-approve low-risk actions")}>{rules.autoApprove ? T("الاعتماد التلقائي: مُفعّل", "Auto-approve: ON") : T("الاعتماد التلقائي: معطّل", "Auto-approve: OFF")}</button>
            {rules.autoApprove && plan.autoApprovable > 0 ? <Button size="sm" variant="dark" disabled={orch === "run"} onClick={runSafe}>{orch === "run" ? "…" : `${T("نفّذ الآمنة", "Run safe")} (${plan.autoApprovable})`}</Button> : null}
          </span>} flush>
      <div style={{ padding: "4px 0" }}>
        {mode === "ceo" ? <div className="subtle" style={{ fontSize: 11.5, padding: "6px 16px 2px" }}>{T("أهم 3 إجراءات الآن — لا شيء يُنفّذ تلقائياً.", "Top 3 actions now — nothing runs automatically.")}</div> : null}
        {rows.map((a) => (
          <div key={a.signature} className="between" style={{ padding: "12px 16px", borderBottom: "1px solid var(--border-1)", gap: 12, alignItems: "flex-start", flexWrap: "wrap" }}>
            <div style={{ minWidth: 0, flex: 1 }}>
              <div className="row" style={{ gap: 6, flexWrap: "wrap", alignItems: "center", marginBottom: 3 }}>
                <Badge tone="neutral">{L(EXEC_TYPE_LABEL[a.type]) || a.type}</Badge>
                <Badge tone={EXEC_URGENCY_TONE[a.urgency] || "neutral"}>{a.urgency === "high" ? T("عاجل", "high") : a.urgency === "low" ? T("منخفض", "low") : T("متوسط", "med")}</Badge>
                {a.approvalPolicy ? <Badge tone={a.approvalPolicy.tier === "auto" ? "green" : "purple"} title={L(a.approvalPolicy.reason)}>{a.approvalPolicy.tier === "auto" ? T("تلقائي", "auto-OK") : T("يحتاج المؤسس", "founder")}</Badge> : null}
                {a.advisory ? <Badge tone="purple">{T("إرشادي", "advisory")}</Badge> : null}
                {a.status === "approved" ? <Badge tone={EXEC_STATUS_TONE.approved}>{T("معتمد", "approved")}</Badge> : null}
                {a.status === "failed" ? <Badge tone="red">{T("فشل", "failed")}</Badge> : null}
                {a.status === "pending_approval" ? <Badge tone="orange">{T("بانتظار اعتماد", "needs approval")}</Badge> : null}
              </div>
              <div style={{ fontWeight: 700, fontSize: 13.5 }}>{L(a.title)}</div>
              <div className="subtle" style={{ fontSize: 12, marginTop: 2, lineHeight: 1.5 }}>{L(a.reason)}{a.agent ? ` · ${a.agent.name}` : ""}{a.contactName ? ` · ${a.contactName}` : ""}</div>
              {!a.workloadSafe && a.workloadNote ? <div style={{ fontSize: 11.5, color: "var(--color-orange)", marginTop: 2 }}>⚠ {L(a.workloadNote)}</div> : null}
              {a.status === "executed" && a.result && a.result.message ? <div style={{ fontSize: 11.5, color: "var(--color-secondary)", marginTop: 2 }}>{L(a.result.message)}</div> : null}
            </div>
            <div className="row" style={{ gap: 10, flexShrink: 0, alignItems: "center" }}>
              {a.expectedImpactSar ? <div style={{ textAlign: "end" }}><div style={{ fontWeight: 800, color: "var(--color-secondary)", fontSize: 13.5 }}>{vsar(a.expectedImpactSar)}</div><div className="subtle" style={{ fontSize: 10.5 }}>{T("أثر متوقّع", "impact")}</div></div> : null}
              <Buttons a={a} />
            </div>
          </div>
        ))}
      </div>
      {mode !== "ceo" ? <div className="subtle" style={{ fontSize: 11, padding: "8px 16px 10px", lineHeight: 1.5 }}>{L(plan.note)} {plan.workloadGuard.overloaded.length ? `· ${T("محمّلون", "overloaded")}: ${plan.workloadGuard.overloaded.join("، ")}` : ""}</div> : null}
    </Card>
  );
}

// ============================================================================
// STRIPE REVENUE AUTOMATION — Danger Zone. Overdue-beyond-grace accounts surfaced for the FOUNDER
// to decide (keep / extend grace / suspend / reactivate). The system NEVER auto-suspends — only a
// founder decision changes an account's status. Reads cc.dangerZone (payment-monitor).
// ============================================================================
const DZ_DECISIONS = [
  { key: "keep_active", ar: "إبقاء نشط", en: "Keep active", tone: "subtle" },
  { key: "extend_grace", ar: "تمديد المهلة", en: "Extend grace", tone: "subtle" },
  { key: "suspend", ar: "إيقاف", en: "Suspend", tone: "dark" },
  { key: "reactivate", ar: "إعادة تفعيل", en: "Reactivate", tone: "subtle" },
];
function DangerZoneSection({ cc, T, lang }) {
  const dz = cc && cc.dangerZone;
  const [busy, setBusy] = React.useState({});
  const L = (x) => (x && typeof x === "object" ? (lang === "ar" ? x.ar : x.en) : x);
  if (!dz || !(dz.accounts || []).length) return null;
  const decide = async (contactId, decision) => {
    setBusy((b) => ({ ...b, [contactId]: true }));
    try { await API.payments.accountDecision(contactId, decision); await Actions.loadValidation("commandCenter"); } catch (e) {}
    setBusy((b) => ({ ...b, [contactId]: false }));
  };
  return (
    <Card title={<span className="row" style={{ gap: 8 }}><Icon name="alert" size={15} style={{ color: "var(--color-danger)" }} />{T("منطقة الخطر — حسابات متأخّرة", "Danger Zone — overdue accounts")}</span>}
      action={<span className="subtle" style={{ fontSize: 11.5 }}>{dz.count} · {vsar(dz.totalOverdue)} {T("متأخّر", "overdue")}</span>} flush>
      <div className="col" style={{ gap: 0, padding: "4px 0" }}>
        {dz.accounts.map((a) => (
          <div key={a.contactId} className="between" style={{ padding: "12px 16px", borderBottom: "1px solid var(--border-1)", gap: 12, alignItems: "flex-start", flexWrap: "wrap" }}>
            <div style={{ minWidth: 0, flex: 1 }}>
              <div className="row" style={{ gap: 6, flexWrap: "wrap", alignItems: "center" }}>
                <b style={{ fontSize: 13.5 }}>{a.name || a.contactId}</b>
                <Badge tone={a.severity === "defaulted" ? "red" : "orange"}>{a.severity === "defaulted" ? T("متعثّر", "defaulted") : T("متأخّر", "overdue")}</Badge>
                {a.founderDecision.decision !== "pending" ? <Badge tone="blue">{T("قرار", "decided")}: {a.founderDecision.decision}</Badge> : null}
              </div>
              <div className="subtle" style={{ fontSize: 12, marginTop: 2 }}>{vsar(a.overdueAmount)} · {a.daysOverdue} {T("يوم تأخير", "days overdue")}{a.earliestDue ? ` · ${T("استحقاق", "due")} ${a.earliestDue}` : ""}</div>
              <div style={{ fontSize: 11.5, color: "var(--color-orange)", marginTop: 2 }}>{L(a.recommendation)}</div>
            </div>
            <div className="row" style={{ gap: 6, flexShrink: 0, flexWrap: "wrap", justifyContent: "flex-end" }}>
              {DZ_DECISIONS.map((d) => (
                d.tone === "dark"
                  ? <Button key={d.key} size="sm" variant="dark" disabled={!!busy[a.contactId]} onClick={() => decide(a.contactId, d.key)}>{T(d.ar, d.en)}</Button>
                  : <button key={d.key} className="btn btn--subtle btn--sm" disabled={!!busy[a.contactId]} onClick={() => decide(a.contactId, d.key)}>{T(d.ar, d.en)}</button>
              ))}
            </div>
          </div>
        ))}
      </div>
      <div className="subtle" style={{ fontSize: 11, padding: "8px 16px 10px", lineHeight: 1.5 }}>{L(dz.policy)} {L(dz.deliveryNote)}</div>
    </Card>
  );
}

// ============================================================================
// REVENUE DIRECTOR V4 — VERTICAL INTELLIGENCE. Industry profitability scores (real data only) +
// the Revenue Director vertical answers. Honest "not enough data yet" until customers are tagged.
// ============================================================================
const VERT_LIST = [["real_estate","Real Estate"],["medical_supplies","Medical Supplies"],["clinics","Clinics"],["saas","SaaS"],["ecommerce","E-commerce"],["logistics","Logistics"],["education","Education"],["manufacturing","Manufacturing"],["other","Other"]];
function VerticalIntelligenceSection({ cc, T, lang }) {
  const vp = cc && cc.verticalProfitability;
  const va = cc && cc.verticalAnswers;
  if (!vp) return null;
  const L = (x) => (x && typeof x === "object" ? (lang === "ar" ? x.ar : x.en) : x);
  const ND = T("بيانات غير كافية", "not enough data yet");
  const ans = (a, label) => a ? (a.vertical ? <span><b>{L(a.label)}</b> <span className="subtle">· {a.value}</span></span> : <span className="subtle">{ND}</span>) : <span className="subtle">{ND}</span>;
  const ansRows = va ? [["most_profitable", T("الأعلى ربحية", "Most profitable")],["most_revenue", T("الأعلى إيراداً", "Most revenue")],["highest_close_rate", T("الأعلى تحويلاً", "Highest close rate")],["fastest_close", T("الأسرع إغلاقاً", "Fastest close")],["lowest_objection", T("الأقل اعتراضاً", "Lowest objection")],["renews_most", T("الأكثر تجديداً", "Renews most")],["easiest_implement", T("الأسهل تسليماً", "Easiest to deliver")],["highest_expansion", T("الأعلى توسّعاً", "Highest expansion")],["lowest_sales_effort", T("الأقل جهد بيع", "Lowest sales effort")],["target_next", T("استهدفه التالي", "Target next")],["avoid", T("تجنّبه", "Avoid")]] : [];
  return (
    <Card title={<span className="row" style={{ gap: 8 }}><Icon name="trending" size={15} style={{ color: "var(--color-secondary)" }} />{T("ذكاء القطاعات (الربحية حسب الصناعة)", "Vertical intelligence (profitability by industry)")}</span>}
      action={<span className="subtle" style={{ fontSize: 11.5 }}>{vp.taggedCustomers} {T("عميل مصنّف", "tagged")}</span>} flush>
      <div className="col" style={{ gap: 12, padding: 14 }}>
        {vp.untaggedNote ? <div className="card" style={{ padding: 10, background: "var(--bg-2)", borderInlineStart: "3px solid var(--color-orange)" }}><div style={{ fontSize: 12.5 }}>{L(vp.untaggedNote)}</div></div> : null}
        {vp.verticals.length ? (
          <div style={{ overflowX: "auto", width: "100%" }}>
            <table className="table" style={{ width: "100%", minWidth: 640 }}>
              <thead><tr><th>{T("القطاع", "Vertical")}</th><th>{T("الدرجة", "Score")}</th><th>{T("الإيراد", "Revenue")}</th><th>{T("التحويل", "Close")}</th><th>{T("الدورة", "Cycle")}</th><th>{T("التسليم", "Delivery")}</th></tr></thead>
              <tbody>
                {vp.verticals.map((r) => (
                  <tr key={r.vertical}>
                    <td style={{ fontWeight: 600 }}>{L(r.label)} <span className="subtle" style={{ fontSize: 11 }}>· {r.customers}</span></td>
                    <td>{r.score != null ? <Badge tone={r.score >= 70 ? "green" : r.score >= 45 ? "neutral" : "orange"}>{r.score}/100</Badge> : <span className="subtle" style={{ fontSize: 11.5 }}>{ND}</span>}</td>
                    <td>{vsar(r.revenue)}</td>
                    <td>{r.closeRate != null ? r.closeRate + "%" : <span className="subtle">—</span>}</td>
                    <td>{r.cycleDays != null ? r.cycleDays + T("ي", "d") : <span className="subtle">—</span>}</td>
                    <td><Badge tone={r.deliveryDifficulty === "high" ? "red" : r.deliveryDifficulty === "low" ? "green" : "neutral"}>{r.deliveryDifficulty}</Badge></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ) : null}
        {cc.verticalTargets && (cc.verticalTargets.verticals || []).length ? (
          <div>
            <div className="subtle" style={{ fontSize: 11.5, fontWeight: 700, marginBottom: 6 }}>{T("أهداف القطاعات (توزيع الهدف)", "Vertical targets (distributed)")}</div>
            <div className="col" style={{ gap: 6 }}>
              {cc.verticalTargets.verticals.map((v) => (
                <div key={v.vertical} className="between" style={{ gap: 10, padding: "5px 0", borderBottom: "1px solid var(--border-1)", flexWrap: "wrap" }}>
                  <div style={{ minWidth: 0 }}><b style={{ fontSize: 12.5 }}>{L(v.label)}</b> <span className="subtle" style={{ fontSize: 11 }}>· {v.sharePct}%</span><div className="subtle" style={{ fontSize: 10.5 }}>{L(v.why)}</div></div>
                  <b style={{ color: "var(--color-secondary)", whiteSpace: "nowrap" }}>{vsar(v.target)}</b>
                </div>
              ))}
            </div>
          </div>
        ) : null}
        {va && va.hasData ? (
          <div>
            <div className="subtle" style={{ fontSize: 11.5, fontWeight: 700, marginBottom: 6 }}>{T("إجابات مدير الإيرادات", "Revenue Director answers")}</div>
            <div className="grid" style={{ gridTemplateColumns: "repeat(auto-fit, minmax(220px, 1fr))", gap: 8 }}>
              {ansRows.map(([k, label]) => <div key={k} style={{ background: "var(--bg-2)", borderRadius: 8, padding: "8px 10px", fontSize: 12 }}><div className="subtle" style={{ fontSize: 10.5, fontWeight: 700, textTransform: "uppercase" }}>{label}</div>{ans(va[k])}</div>)}
            </div>
          </div>
        ) : null}
        <div className="subtle" style={{ fontSize: 11, lineHeight: 1.5 }}>{L(vp.note)}</div>
      </div>
    </Card>
  );
}

// V4 — Target evolution (growth ladder 250k→350k→500k→1M) + path questions.
function TargetEvolutionSection({ cc, T, lang }) {
  const te = cc && cc.targetEvolution;
  if (!te) return null;
  const L = (x) => (x && typeof x === "object" ? (lang === "ar" ? x.ar : x.en) : x);
  return (
    <Card title={<span className="row" style={{ gap: 8 }}><Icon name="target" size={15} style={{ color: "var(--color-secondary)" }} />{T("تطوّر الهدف (سُلّم النمو)", "Target evolution (growth ladder)")}</span>} flush>
      <div className="col" style={{ gap: 12, padding: 14 }}>
        <div className="row" style={{ gap: 8, flexWrap: "wrap" }}>
          {te.ladder.map((m) => (
            <div key={m.target} style={{ background: m.isCurrent ? "var(--color-primary-tint-soft)" : "var(--bg-2)", borderRadius: 10, padding: "8px 12px", border: m.reached ? "2px solid var(--color-secondary)" : "2px solid transparent" }}>
              <div style={{ fontWeight: 800, fontSize: 14 }}>{vsar(m.target)}{m.isCurrent ? <Badge tone="blue" style={{ marginInlineStart: 6 }}>{T("الحالي", "current")}</Badge> : null}</div>
              <div className="subtle" style={{ fontSize: 11 }}>{m.reached ? T("مُتحقّق", "reached") : T("الفجوة", "gap") + " " + vsar(m.gapFromForecast)}</div>
            </div>
          ))}
        </div>
        <div className="grid" style={{ gridTemplateColumns: "repeat(auto-fit, minmax(190px, 1fr))", gap: 8 }}>
          {[["fastest", te.paths.fastest],["safest", te.paths.safest],["highest_probability", te.paths.highest_probability],["highest_margin", te.paths.highest_margin],["lowest_delivery_risk", te.paths.lowest_delivery_risk],["most_profitable", te.paths.most_profitable],["lowest_workload", te.paths.lowest_workload]].filter(([,p])=>p).map(([k, p]) => (
            <div key={k} style={{ background: "var(--bg-2)", borderRadius: 8, padding: "8px 10px", fontSize: 12 }}><div className="subtle" style={{ fontSize: 10.5, fontWeight: 700, textTransform: "uppercase" }}>{L(p.label)}</div>{p.note ? <span className="subtle">{L(p.note)}</span> : p.summary ? <span>{L(p.summary)}</span> : p.productLabel ? <span><b>{L(p.productLabel)}</b></span> : p.verticalLabel ? <span><b>{L(p.verticalLabel)}</b></span> : "—"}</div>
          ))}
        </div>
        {te.recommendations ? (
          <div className="card" style={{ padding: 10, background: "var(--bg-2)", borderInlineStart: "3px solid var(--color-secondary)" }}>
            <div className="subtle" style={{ fontSize: 10.5, fontWeight: 700, textTransform: "uppercase", marginBottom: 4 }}>{T("توصية مدير الإيرادات", "Revenue Brain recommendation")}</div>
            <div className="row" style={{ gap: 14, flexWrap: "wrap", fontSize: 12 }}>
              <span>{T("منتج", "Product")}: <b>{te.recommendations.product.label ? L(te.recommendations.product.label) : <span className="subtle">{L(te.recommendations.product.note)}</span>}</b></span>
              <span>{T("باقة", "Package")}: <b>{te.recommendations.package.name ? L(te.recommendations.package.name) : <span className="subtle">{L(te.recommendations.package.note)}</span>}</b></span>
              <span>{T("قطاع", "Vertical")}: <b>{te.recommendations.vertical.label ? L(te.recommendations.vertical.label) : <span className="subtle">{L(te.recommendations.vertical.note)}</span>}</b></span>
            </div>
            <div style={{ fontSize: 12, marginTop: 4, lineHeight: 1.5 }}>{L(te.recommendations.strategy)}</div>
          </div>
        ) : null}
        <div className="subtle" style={{ fontSize: 11, lineHeight: 1.5 }}>{L(te.accountabilityNote)}</div>
      </div>
    </Card>
  );
}

// V4 — Reality Audit: every metric exposes source / calculation / confidence.
function RealityAuditSection({ cc, T, lang }) {
  const ra = cc && cc.realityAudit;
  if (!ra || !(ra.metrics || []).length) return null;
  const L = (x) => (x && typeof x === "object" ? (lang === "ar" ? x.ar : x.en) : x);
  const tone = { measured: "green", heuristic: "purple", config: "blue", not_enough_data: "neutral" };
  return (
    <Card title={<span className="row" style={{ gap: 8 }}><Icon name="shield" size={15} style={{ color: "var(--color-secondary)" }} />{T("تدقيق الواقع (مصدر كل رقم)", "Reality Audit (where every number comes from)")}</span>} flush>
      <div style={{ overflowX: "auto", width: "100%", padding: "4px 0" }}>
        <table className="table" style={{ width: "100%", minWidth: 640 }}>
          <thead><tr><th>{T("المقياس", "Metric")}</th><th>{T("القيمة", "Value")}</th><th>{T("المصدر", "Source")}</th><th>{T("الحساب", "Calculation")}</th><th>{T("الثقة", "Confidence")}</th></tr></thead>
          <tbody>
            {ra.metrics.map((m) => (
              <tr key={m.key}>
                <td style={{ fontWeight: 600 }}>{L(m.label)}</td>
                <td>{m.value != null ? m.value : <span className="subtle" style={{ fontSize: 11.5 }}>{T("بيانات غير كافية", "not enough data")}</span>}</td>
                <td className="subtle" style={{ fontSize: 11.5 }}>{L(m.source)}</td>
                <td className="subtle" style={{ fontSize: 11.5 }}>{L(m.calculation)}</td>
                <td><Badge tone={tone[m.confidence] || "neutral"}>{m.confidence === "not_enough_data" ? T("غير كافٍ", "n/a") : m.confidence}</Badge></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      <div className="subtle" style={{ fontSize: 11, padding: "0 14px 12px", lineHeight: 1.5 }}>{L(ra.policy)}</div>
    </Card>
  );
}

// ============================================================================
// EXECUTIVE OPERATIONS CENTER — the founder's single screen. EXACTLY 7 answers, no clutter.
// Reads cc.executiveOps (pure composition of existing engines). Rendered as the HOME screen.
// ============================================================================
function ExecutiveOpsPanel({ T, lang, go }) {
  useStore();
  const cc = vget("commandCenter");
  const L = (x) => (x && typeof x === "object" && !Array.isArray(x) ? (lang === "ar" ? x.ar : x.en) : x);
  if (!cc || cc.error || !cc.executiveOps) return <Card flush><VEmpty icon={cc && cc.error ? "alert" : "dollar"} title={cc && cc.error ? T("تعذّر التحميل", "Couldn't load") : T("جارٍ التحميل…", "Loading…")} body={cc && cc.error} /></Card>;
  const q = cc.executiveOps.questions || {};
  const fmCard = (c, n) => {
    const tone = FM_TONE[c && c.tone] || "var(--fg-3)";
    return (
      <div className="card" style={{ padding: 14, borderTop: "3px solid " + tone, display: "flex", flexDirection: "column", gap: 5, minWidth: 0 }}>
        <div className="row" style={{ gap: 6, alignItems: "center" }}><span style={{ width: 18, height: 18, borderRadius: 999, background: "var(--bg-2)", color: tone, display: "inline-flex", alignItems: "center", justifyContent: "center", fontWeight: 800, fontSize: 11 }}>{n}</span><span className="subtle" style={{ fontSize: 11, fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.03em" }}>{c ? L(c.title) : "—"}</span></div>
        <div style={{ fontSize: 14.5, fontWeight: 800, lineHeight: 1.35 }}>{c ? L(c.headline) : T("غير متاح", "Not available")}</div>
        {c && c.detail ? <div className="subtle" style={{ fontSize: 12, lineHeight: 1.45 }}>{L(c.detail)}</div> : null}
      </div>
    );
  };
  const listCard = (n, title, tone, value, sub, items, onGo) => (
    <button onClick={onGo} className="card" style={{ padding: 14, borderTop: "3px solid " + tone, display: "flex", flexDirection: "column", gap: 5, minWidth: 0, textAlign: "start", cursor: "pointer", background: "var(--bg-1)" }}>
      <div className="row" style={{ gap: 6, alignItems: "center" }}><span style={{ width: 18, height: 18, borderRadius: 999, background: "var(--bg-2)", color: tone, display: "inline-flex", alignItems: "center", justifyContent: "center", fontWeight: 800, fontSize: 11 }}>{n}</span><span className="subtle" style={{ fontSize: 11, fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.03em" }}>{title}</span></div>
      <div style={{ fontSize: 18, fontWeight: 800 }}>{value}{sub ? <span className="subtle" style={{ fontSize: 12, fontWeight: 500 }}> {sub}</span> : null}</div>
      {(items || []).slice(0, 3).map((it, i) => <div key={i} className="subtle" style={{ fontSize: 11.5, lineHeight: 1.4, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>· {it}</div>)}
    </button>
  );
  const churn = q.q5_customers_at_risk, ren = q.q6_upcoming_renewals, dec = q.q7_required_founder_decisions;
  return (
    <div className="col" style={{ gap: 14 }}>
      <div className="row" style={{ gap: 8, alignItems: "center" }}><Icon name="dollar" size={16} style={{ color: "var(--color-secondary)" }} /><b style={{ fontSize: 15 }}>{T("مركز العمليات التنفيذية", "Executive Operations Center")}</b><span className="subtle" style={{ fontSize: 12 }}>{T("7 أسئلة — لا شيء غير ذلك", "7 questions — nothing else")}</span></div>
      <div className="grid" style={{ gridTemplateColumns: "repeat(auto-fit, minmax(220px, 1fr))", gap: 12 }}>
        {fmCard(q.q1_revenue_target_status, 1)}
        {fmCard(q.q2_fastest_path, 2)}
        {fmCard(q.q3_biggest_risk, 3)}
        {fmCard(q.q4_biggest_opportunity, 4)}
        {listCard(5, T("عملاء معرّضون للتسرّب", "Customers at risk"), "var(--color-danger)", churn ? churn.count : 0, churn && churn.revenueAtRisk ? `· ${vsar(churn.revenueAtRisk)}` : "", (churn && churn.top || []).map((c) => `${c.name} — ${(c.signals[0] && L(c.signals[0])) || ""}`), () => go("validation"))}
        {listCard(6, T("تجديدات قادمة", "Upcoming renewals"), "var(--color-orange)", ren ? (ren.counts.d30 + ren.counts.d15 + ren.counts.d7 + ren.counts.overdue) : 0, ren && ren.counts.overdue ? `· ${ren.counts.overdue} ${T("متأخّر", "overdue")}` : "", (ren && ren.top || []).map((r) => `${r.name} — ${r.daysUntil < 0 ? T("متأخّر", "overdue") : r.daysUntil + T("ي", "d")}`), () => go("validation"))}
        {listCard(7, T("قرارات تتطلّب المؤسس", "Required founder decisions"), "var(--color-secondary)", dec ? dec.count : 0, "", (dec && dec.top || []).map((d) => L(d.title)), () => go("validation"))}
      </div>
      {/* V4 — which vertical is winning / sell next (real measured data, else honest empty) */}
      {cc.executiveOps.vertical ? (
        <div className="row" style={{ gap: 10, flexWrap: "wrap" }}>
          <div className="card" style={{ padding: "10px 14px", flex: 1, minWidth: 200, borderInlineStart: "3px solid var(--color-secondary)" }}>
            <div className="subtle" style={{ fontSize: 11, fontWeight: 700, textTransform: "uppercase" }}>{T("القطاع الرابح", "Winning vertical")}</div>
            <div style={{ fontWeight: 800, fontSize: 14, marginTop: 2 }}>{cc.executiveOps.vertical.winning && cc.executiveOps.vertical.winning.label ? L(cc.executiveOps.vertical.winning.label) : <span className="subtle" style={{ fontWeight: 500 }}>{T("بيانات غير كافية", "Not enough data yet")}</span>}</div>
          </div>
          <div className="card" style={{ padding: "10px 14px", flex: 1, minWidth: 200, borderInlineStart: "3px solid var(--color-orange)" }}>
            <div className="subtle" style={{ fontSize: 11, fontWeight: 700, textTransform: "uppercase" }}>{T("بِع التالي", "Sell next")}</div>
            <div style={{ fontWeight: 800, fontSize: 14, marginTop: 2 }}>{cc.executiveOps.vertical.sellNext && cc.executiveOps.vertical.sellNext.label ? L(cc.executiveOps.vertical.sellNext.label) : <span className="subtle" style={{ fontWeight: 500 }}>{T("بيانات غير كافية", "Not enough data yet")}</span>}</div>
          </div>
        </div>
      ) : null}
    </div>
  );
}

// Customer Success Department (RCC Advanced) — lifecycle book + onboarding + churn, with the
// founder CS actions (advance onboarding step / mark renewed). Reads cc.customerSuccess.
const CS_STAGE_TONE = { new_customer: "blue", onboarding: "blue", active: "green", expansion: "lime", renewal: "orange", renewed: "green", churn_risk: "red" };
function CustomerSuccessSection({ cc, T, lang }) {
  const book = cc && cc.customerSuccess;
  const [busy, setBusy] = React.useState({});
  const L = (x) => (x && typeof x === "object" ? (lang === "ar" ? x.ar : x.en) : x);
  if (!book || !(book.accounts || []).length) return null;
  const act = async (id, action, payload) => { setBusy((b) => ({ ...b, [id]: true })); try { await API.payments.csAction(id, action, payload); await Actions.loadValidation("commandCenter"); } catch (e) {} setBusy((b) => ({ ...b, [id]: false })); };
  const tagVertical = async (id, v) => { setBusy((b) => ({ ...b, [id]: true })); try { await API.validation.setVertical(id, v || null); await Actions.loadValidation("commandCenter"); } catch (e) {} setBusy((b) => ({ ...b, [id]: false })); };
  const stageLabel = { new_customer: T("عميل جديد", "New"), onboarding: T("تهيئة", "Onboarding"), active: T("نشط", "Active"), expansion: T("توسّع", "Expansion"), renewal: T("تجديد", "Renewal"), renewed: T("مُجدّد", "Renewed"), churn_risk: T("خطر تسرّب", "Churn risk") };
  return (
    <Card title={<span className="row" style={{ gap: 8 }}><Icon name="users" size={15} style={{ color: "var(--color-secondary)" }} />{T("قسم نجاح العملاء", "Customer Success Department")}</span>}
      action={<span className="subtle" style={{ fontSize: 11.5 }}>{book.total} {T("عميل", "customers")}</span>} flush>
      <div style={{ overflowX: "auto", width: "100%", padding: "4px 0" }}>
        <table className="table" style={{ width: "100%", minWidth: 720 }}>
          <thead><tr><th>{T("العميل", "Customer")}</th><th>{T("القطاع", "Vertical")}</th><th>{T("المرحلة", "Stage")}</th><th>{T("الاشتراك", "Subscription")}</th><th>{T("الصحّة", "Health")}</th><th>{T("التهيئة", "Onboarding")}</th><th>{T("التجديد", "Renewal")}</th><th></th></tr></thead>
          <tbody>
            {book.accounts.slice(0, 12).map((a) => (
              <tr key={a.contactId}>
                <td style={{ fontWeight: 600 }}>{a.name}{a.churnRisk ? <Badge tone="red" style={{ marginInlineStart: 6 }}>{T("خطر", "risk")}</Badge> : null}</td>
                <td><select className="select" disabled={!!busy[a.contactId]} value={a.vertical || ""} onChange={(e) => tagVertical(a.contactId, e.target.value)} style={{ height: 28, fontSize: 11.5, minWidth: 90 }}><option value="">{T("—", "—")}</option>{VERT_LIST.map(([k, l]) => <option key={k} value={k}>{l}</option>)}</select></td>
                <td><Badge tone={CS_STAGE_TONE[a.stage] || "neutral"}>{stageLabel[a.stage] || a.stage}</Badge></td>
                <td className="subtle" style={{ fontSize: 12 }}>{a.subscriptionState}</td>
                <td>{a.health.score != null ? <Badge tone={a.health.band === "healthy" ? "green" : a.health.band === "watch" ? "orange" : "red"}>{a.health.score}</Badge> : <span className="subtle" style={{ fontSize: 11.5 }}>{T("بيانات غير كافية", "not enough data")}</span>}</td>
                <td className="subtle" style={{ fontSize: 12 }}>{a.onboarding.done}/{a.onboarding.total}</td>
                <td className="subtle" style={{ fontSize: 12 }}>{a.renewal.date ? (a.renewal.daysUntil < 0 ? T("متأخّر", "overdue") : a.renewal.daysUntil + T("ي", "d")) : "—"}</td>
                <td><div className="row" style={{ gap: 4, justifyContent: "flex-end" }}>{a.recurring && a.stage === "renewal" ? <button className="btn btn--subtle btn--sm" disabled={!!busy[a.contactId]} onClick={() => act(a.contactId, "mark_renewed", {})}>{T("جُدِّد", "Renewed")}</button> : null}{!a.onboarding.complete ? <button className="btn btn--subtle btn--sm" disabled={!!busy[a.contactId]} onClick={() => { const next = (a.onboarding.steps.find((s) => !s.done) || {}).key; if (next) act(a.contactId, "complete_onboarding_step", { step: next }); }}>{T("خطوة تهيئة", "Onboard +1")}</button> : null}</div></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      <div className="subtle" style={{ fontSize: 11, padding: "0 14px 12px", lineHeight: 1.5 }}>{L(book.usageNote)}</div>
    </Card>
  );
}

// Required Founder Decisions — ONE consolidated queue (links to where to act). Reads cc.founderDecisions.
function FounderDecisionsSection({ cc, T, lang, go }) {
  const fd = cc && cc.founderDecisions;
  const L = (x) => (x && typeof x === "object" ? (lang === "ar" ? x.ar : x.en) : x);
  if (!fd || !(fd.items || []).length) return null;
  const catLabel = { payment: T("دفع", "payment"), custom_pricing: T("تسعير مخصّص", "custom pricing"), reassignment: T("إعادة إسناد", "reassignment"), suspension: T("إيقاف", "suspension"), discount: T("خصم/موافقة", "discount/approval"), approval: T("موافقة", "approval") };
  return (
    <Card title={<span className="row" style={{ gap: 8 }}><Icon name="alert" size={15} style={{ color: "var(--color-secondary)" }} />{T("قرارات تتطلّب المؤسس", "Required founder decisions")}</span>}
      action={<span className="subtle" style={{ fontSize: 11.5 }}>{fd.count} {T("معلّق", "pending")}</span>} flush>
      <div style={{ padding: "4px 0" }}>
        {fd.items.slice(0, 10).map((it, i) => (
          <div key={i} className="between" style={{ padding: "11px 16px", borderBottom: "1px solid var(--border-1)", gap: 10, alignItems: "flex-start", flexWrap: "wrap" }}>
            <div style={{ minWidth: 0, flex: 1 }}>
              <div className="row" style={{ gap: 6, flexWrap: "wrap", alignItems: "center" }}><Badge tone={it.category === "suspension" ? "red" : "neutral"}>{catLabel[it.category] || it.category}</Badge><b style={{ fontSize: 13.5 }}>{L(it.title)}</b></div>
              <div className="subtle" style={{ fontSize: 12, marginTop: 2 }}>{L(it.detail)}{it.actor ? ` · ${it.actor}` : ""}</div>
            </div>
            <div className="row" style={{ gap: 10, flexShrink: 0, alignItems: "center" }}>{it.impactSar ? <span style={{ fontWeight: 800, color: "var(--color-secondary)", fontSize: 13 }}>{vsar(it.impactSar)}</span> : null}</div>
          </div>
        ))}
      </div>
      <div className="subtle" style={{ fontSize: 11, padding: "8px 16px 10px", lineHeight: 1.5 }}>{L(fd.policy)} {T("اعمل عليها في لوحة التنفيذ / منطقة الخطر أدناه.", "Act on these in the Execution Board / Danger Zone below.")}</div>
    </Card>
  );
}

function RevenueStrategyPlanSection({ cc, T, lang }) {
  const plan = cc && cc.revenueStrategyPlan;
  if (!plan || !plan.hasPlan || !(plan.mix || []).length) return null;
  const L = (x) => (x && typeof x === "object" ? (lang === "ar" ? x.ar : x.en) : x);
  return (
    <Card title={<span className="row" style={{ gap: 8 }}><Icon name="zap" size={15} style={{ color: "var(--color-secondary)" }} />{T("خطة الإيراد المقترحة", "Revenue strategy plan")}</span>} flush>
      <div className="col" style={{ gap: 10, padding: 14 }}>
        <div style={{ fontSize: 14.5, fontWeight: 700, lineHeight: 1.5 }}>{L(plan.summary)}</div>
        <div className="row" style={{ gap: 8, flexWrap: "wrap", alignItems: "center" }}>
          <Badge tone={plan.coversGap ? "green" : "orange"}>{plan.coversGap ? T("يغطّي الهدف", "covers target") : T("يقلّص الفجوة", "narrows gap")}</Badge>
          {plan.confidence ? <Badge tone={plan.confidence === "measured" ? "green" : "neutral"}>{plan.confidence === "measured" ? T("مبني على بيانات حقيقية", "from real data") : T("بيانات غير كافية", "needs more data")}</Badge> : null}
          {plan.pathLabel ? <span className="subtle" style={{ fontSize: 12 }}>{L(plan.pathLabel)}</span> : null}
        </div>
        <div style={{ overflowX: "auto", width: "100%" }}>
          <table className="table" style={{ minWidth: 480, width: "100%" }}>
            <thead><tr><th>{T("المنتج", "Product")}</th><th>{T("العدد", "Count")}</th><th>{T("متوسط الصفقة", "Avg deal")}</th><th>{T("الإيراد", "Revenue")}</th><th>{T("المالك", "Owner")}</th></tr></thead>
            <tbody>
              {plan.mix.map((m) => (
                <tr key={m.productType}>
                  <td style={{ fontWeight: 600 }}>{L(m.label)}{m.recurring ? <Badge tone="purple" style={{ marginInlineStart: 6 }}>{T("متكرّر", "recurring")}</Badge> : null}</td>
                  <td><b>{m.count}×</b></td>
                  <td>{m.avgDeal != null ? vsar(m.avgDeal) : <span className="subtle">{T("—", "—")}</span>}</td>
                  <td style={{ fontWeight: 700, color: "var(--color-secondary)" }}>{vsar(m.expectedRevenue)}</td>
                  <td>{m.owner ? m.owner.name : <span className="subtle">{T("غير مسند", "Unassigned")}</span>}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        <div className="row" style={{ gap: 20, flexWrap: "wrap" }}>
          <div><div className="subtle" style={{ fontSize: 11.5 }}>{T("إجمالي متوقّع", "Total expected")}</div><b style={{ fontSize: 16, color: "var(--color-secondary)" }}>{vsar(plan.totalExpected)}</b></div>
          <div><div className="subtle" style={{ fontSize: 11.5 }}>{T("الهدف", "Target")}</div><b style={{ fontSize: 16 }}>{vsar(plan.target)}</b></div>
          <div><div className="subtle" style={{ fontSize: 11.5 }}>{T("إجمالي الصفقات", "Total deals")}</div><b style={{ fontSize: 16 }}>{plan.totalDeals}</b></div>
        </div>
      </div>
    </Card>
  );
}

// P5 — Target distribution: company → product → agent → activity, each with WHY + overload flag.
function TargetDistributionSection({ cc, T, lang }) {
  const d = cc && cc.targetDistribution;
  if (!d) return null;
  const L = (x) => (x && typeof x === "object" ? (lang === "ar" ? x.ar : x.en) : x);
  if (!d.targetSet) return <Card title={T("توزيع الهدف", "Target distribution")} flush><div className="subtle" style={{ padding: 14, fontSize: 12.5 }}>{L(d.note)}</div></Card>;
  return (
    <Card title={<span className="row" style={{ gap: 8 }}><Icon name="layers" size={15} style={{ color: "var(--color-secondary)" }} />{T("توزيع الهدف: شركة ← منتج ← وكيل", "Target distribution: company → product → agent")}</span>} flush>
      <div className="col" style={{ gap: 12, padding: 14 }}>
        <div className="subtle" style={{ fontSize: 12 }}>{T("الهدف", "Target")} {vsar(d.company.target)} · {T("الفجوة", "Gap")} {vsar(d.company.gap)}</div>
        <div>
          <div style={{ fontSize: 12, fontWeight: 700, marginBottom: 6 }}>{T("حسب المنتج", "By product")}</div>
          <div className="col" style={{ gap: 6 }}>
            {d.products.map((p) => (
              <div key={p.productType} className="between" style={{ gap: 10, padding: "6px 0", borderBottom: "1px solid var(--border-1)", flexWrap: "wrap" }}>
                <div style={{ minWidth: 0 }}><b style={{ fontSize: 13 }}>{L(p.label)}</b> <span className="subtle" style={{ fontSize: 11.5 }}>· {p.sharePct}%{p.owner ? ` · ${p.owner.name}` : ""}</span><div className="subtle" style={{ fontSize: 11 }}>{L(p.why)}</div></div>
                <b style={{ color: "var(--color-secondary)", whiteSpace: "nowrap" }}>{vsar(p.target)}</b>
              </div>
            ))}
          </div>
        </div>
        <div>
          <div style={{ fontSize: 12, fontWeight: 700, marginBottom: 6 }}>{T("حسب الوكيل", "By agent")}</div>
          <div className="col" style={{ gap: 6 }}>
            {d.agents.map((a) => (
              <div key={a.agentId} className="between" style={{ gap: 10, padding: "6px 0", borderBottom: "1px solid var(--border-1)", flexWrap: "wrap" }}>
                <div style={{ minWidth: 0 }}><span className="row" style={{ gap: 6 }}><b style={{ fontSize: 13 }}>{a.name}</b>{a.overloaded ? <Badge tone="orange">{T("محمّل بالكامل", "at capacity")}</Badge> : null}</span><div className="subtle" style={{ fontSize: 11 }}>{L(a.why)}{a.activities && a.activities.requiredMeetings != null ? ` · ${a.activities.requiredMeetings} ${T("اجتماع", "mtg")} · ${a.activities.requiredProposals} ${T("عرض", "prop")}` : ""}</div></div>
                <b style={{ whiteSpace: "nowrap" }}>{vsar(a.target)}</b>
              </div>
            ))}
          </div>
        </div>
        {d.capNote ? <div className="subtle" style={{ fontSize: 11 }}>{L(d.capNote)}</div> : null}
      </div>
    </Card>
  );
}
function ProductStrategySection({ cc, T, lang }) {
  const ps = cc && cc.productStrategy;
  if (!ps) return null;
  const L = (x) => (x && typeof x === "object" ? (lang === "ar" ? x.ar : x.en) : x);
  const ND = T("تحتاج بيانات أكثر", "Needs more data");
  const title = <span className="row" style={{ gap: 8 }}><Icon name="target" size={15} style={{ color: "var(--color-secondary)" }} />{T("استراتيجية الوصول للهدف (حسب المنتج)", "Target strategy — per product")}</span>;
  if (!ps.targetSet) return <Card title={title} flush><div className="subtle" style={{ fontSize: 12.5, padding: 14 }}>{T("اضبط هدف الإيراد الشهري لتظهر مسارات الوصول للهدف.", "Set a company monthly target to see the paths to it.")}</div></Card>;
  if (!ps.paths.length) return <Card title={title} flush><div className="subtle" style={{ fontSize: 12.5, padding: 14 }}>{ps.note === "on_track" ? T("على المسار — التوقّع يغطّي الهدف.", "On track — forecast covers the target.") : T("تحتاج بيانات أكثر: لا خطوط منتجات بسجلّ كافٍ لاقتراح مسار بعد.", "Needs more data: no product line has enough history to propose a path yet.")}</div></Card>;
  return (
    <Card title={title} flush>
      <div className="col" style={{ gap: 14, padding: 14 }}>
        {ps.recommended ? <div className="card" style={{ padding: 10, background: "var(--bg-2)", borderInlineStart: "3px solid var(--color-secondary)" }}><div style={{ fontSize: 12.5, lineHeight: 1.5 }}><b>{T("موصى به: ", "Recommended: ")}</b>{L(ps.recommended.label)} — {vsar(ps.recommended.expectedRevenue)} · {ps.recommended.deals} {T("صفقة", "deals")}. {L(ps.recommended.why)}</div></div> : null}
        <div>
          <div className="subtle" style={{ fontSize: 11.5, fontWeight: 700, marginBottom: 6 }}>{T("مقارنة المسارات", "Path comparison")}</div>
          <div style={{ overflowX: "auto", width: "100%" }}>
            <table className="table" style={{ width: "100%", minWidth: 560 }}>
              <thead><tr><th>{T("المسار", "Path")}</th><th>{T("الإيراد", "Revenue")}</th><th>{T("صفقات", "Deals")}</th><th>{T("وكلاء", "Agents")}</th><th>{T("المخاطرة", "Risk")}</th><th>{T("الثقة", "Confidence")}</th></tr></thead>
              <tbody>{ps.paths.map((p) => (
                <tr key={p.key}>
                  <td style={{ fontWeight: 600 }}>{L(p.label)}{p.coversGap ? <Badge tone="green" style={{ marginInlineStart: 6 }}>{T("يغطّي", "covers")}</Badge> : null}</td>
                  <td style={{ fontWeight: 700 }}>{vsar(p.expectedRevenue)}</td><td>{p.deals}</td><td>{p.agentsRequired}</td>
                  <td><Badge tone={STRAT_RISK_TONE[p.risk] || "neutral"}>{p.risk || ND}</Badge></td>
                  <td><Badge tone={p.confidence === "measured" ? "green" : "neutral"}>{p.confidence === "measured" ? T("مُقاس", "measured") : ND}</Badge></td>
                </tr>
              ))}</tbody>
            </table>
          </div>
        </div>
        {ps.ownerOptions && ps.ownerOptions.length ? (
          <div>
            <div className="subtle" style={{ fontSize: 11.5, fontWeight: 700, marginBottom: 6 }}>{T("خيارات القرار للمالك", "Owner decision options")}</div>
            <div className="grid" style={{ gridTemplateColumns: "repeat(auto-fit, minmax(150px, 1fr))", gap: 10 }}>
              {ps.ownerOptions.map((o) => (
                <div key={o.key} style={{ background: "var(--bg-2)", borderRadius: 10, padding: "10px 12px" }}>
                  <div style={{ fontWeight: 700, fontSize: 13 }}>{L(o.label)}</div>
                  <div style={{ fontSize: 15, fontWeight: 800, color: "var(--color-secondary)", marginTop: 3 }}>{vsar(o.expectedRevenue)}</div>
                  <div className="subtle" style={{ fontSize: 11.5, marginTop: 3 }}>{o.deals} {T("صفقة", "deals")} · <Badge tone={STRAT_RISK_TONE[o.risk] || "neutral"}>{o.risk || ND}</Badge>{o.timeToCashDays != null ? ` · ~${o.timeToCashDays}${T("ي", "d")}` : ""}</div>
                </div>
              ))}
            </div>
          </div>
        ) : null}
        <div>
          <div className="subtle" style={{ fontSize: 11.5, fontWeight: 700, marginBottom: 6 }}>{T("مصفوفة الجهد مقابل الإيراد", "Effort vs revenue matrix")}</div>
          <div style={{ overflowX: "auto", width: "100%" }}>
            <table className="table" style={{ width: "100%", minWidth: 560 }}>
              <thead><tr><th>{T("المنتج", "Product")}</th><th>{T("الإيراد المحتمل", "Revenue potential")}</th><th>{T("سهولة الإغلاق", "Ease")}</th><th>{T("الوقت للنقد", "Time-to-cash")}</th><th>{T("التصنيف", "Category")}</th></tr></thead>
              <tbody>{ps.effortMatrix.map((m) => (
                <tr key={m.productType}>
                  <td>{L(m.label)}</td><td>{vsar(m.revenuePotential)}</td>
                  <td>{m.easeOfClosing === "unknown" ? <span className="subtle">{ND}</span> : m.easeOfClosing}</td>
                  <td>{m.timeToCash === "unknown" ? <span className="subtle">{ND}</span> : m.timeToCash}</td>
                  <td><Badge tone={STRAT_CAT_TONE[m.category] || "neutral"}>{m.category}</Badge></td>
                </tr>
              ))}</tbody>
            </table>
          </div>
        </div>
        {ps.workload && (ps.workload.assignments || []).length ? (
          <div>
            <div className="subtle" style={{ fontSize: 11.5, fontWeight: 700, marginBottom: 6 }}>{T("توزيع العمل (حماية من الإرهاق)", "Workload allocation (overload-protected)")}</div>
            {ps.workload.assignments.map((a, i) => (
              <div key={i} className="between" style={{ padding: "8px 0", borderBottom: "1px solid var(--border-1)", gap: 10, flexWrap: "wrap" }}>
                <span style={{ fontSize: 12.5, fontWeight: 600, minWidth: 0 }}>{L(a.label)}{a.deals != null ? <span className="subtle" style={{ fontWeight: 400 }}> · {a.deals} {T("صفقة", "deals")}</span> : null}</span>
                <span className="row" style={{ gap: 6, flexWrap: "wrap", justifyContent: "flex-end" }}>
                  {(a.plan || []).map((p, j) => <Badge key={j} tone="neutral">{p.deals} → {p.name}</Badge>)}
                  {a.overloaded ? <Badge tone="orange">{T("أُعيد التوزيع", "redistributed")}</Badge> : null}
                  {!a.plan || !a.plan.length ? <span className="subtle" style={{ fontSize: 11.5 }}>{a.note ? L(a.note) : null}</span> : null}
                </span>
              </div>
            ))}
            <div className="subtle" style={{ fontSize: 11, marginTop: 6 }}>{L(ps.workload.capNote)}</div>
          </div>
        ) : null}
      </div>
    </Card>
  );
}

// ============================================================================
// PART 12/13 — REVENUE DIRECTOR CONSOLE. The action-first surface: edit the target (with the
// 250k/500k/1M ladder), choose Auto vs Manual for Execution / Target Vertical / Product Focus, read
// the recommended Revenue Director Plan (expected revenue + confidence + risk + required activities),
// and jump straight to the executable actions. Pure synthesis over EXISTING engines — every control
// is wired to a real switch (setCompanyTarget / orchestratorAutoApprove / campaignObjectives); no new
// math, nothing read-only, nothing fabricated. Honest empties when there's no target/plan yet.
// ============================================================================
const RDC_VERTICALS = ["Fashion", "Furniture", "Beauty", "Medical", "Services", "Real Estate", "Ecommerce"];
function ModeSeg({ value, onPick, busy, T }) {
  const opts = [["auto", T("تلقائي", "Auto")], ["manual", T("يدوي", "Manual")]];
  return (
    <div className="row" style={{ gap: 4 }}>
      {opts.map(([v, l]) => (
        <button key={v} disabled={busy} onClick={() => onPick(v)} style={{ padding: "5px 12px", borderRadius: 999, fontSize: 12, fontWeight: 700, border: "none", cursor: "pointer",
          background: value === v ? "var(--color-primary-tint-soft)" : "var(--bg-2)", color: value === v ? "var(--color-secondary)" : "var(--fg-3)" }}>{l}</button>
      ))}
    </div>
  );
}
function RevenueDirectorConsole({ cc, T, lang, readOnly, go }) {
  const data = useStore();
  const L = (x) => (x && typeof x === "object" && !Array.isArray(x) ? (lang === "ar" ? x.ar : x.en) : x);
  const cas = (cc && cc.cascade) || null;
  const auto = cc && cc.ceoAutopilot;
  const sc = auto && auto.targetScenarios;
  const plan = cc && cc.executionPlan;
  const settings = data.SETTINGS || {};
  const [busy, setBusy] = React.useState("");
  const [editing, setEditing] = React.useState(false);
  const [tv, setTv] = React.useState("");

  const reload = async () => { await Actions.loadValidation("commandCenter"); try { await Actions.loadValidation("ownerOverview"); } catch (_) {} };

  // Step 1 — target + ladder (reuses setCompanyTarget)
  const LADDER = [250000, 500000, 1000000];
  const curTarget = (settings.companyMonthlyTarget != null ? settings.companyMonthlyTarget : (cas && cas.targetSet ? cas.target : null));
  const setTarget = async (val) => { setBusy("target"); try { await Actions.setCompanyTarget({ monthly: val }); await reload(); setEditing(false); } catch (_) {} setBusy(""); };

  // Step 2 — execution mode (reuses orchestratorAutoApprove)
  const execAuto = !!(plan && plan.approvalRules && plan.approvalRules.autoApprove);
  const setExec = async (mode) => { setBusy("exec"); try { await API.settings.update({ orchestratorAutoApprove: mode === "auto" }); await reload(); } catch (_) {} setBusy(""); };

  // Steps 3/4 — vertical + product focus modes (manual selections mirror into campaignObjectives so
  // the EXISTING objectiveBias re-weights ranking; auto clears them → byte-identical empty path).
  const tvMode = settings.targetVerticalMode || "auto";
  const pfMode = settings.productFocusMode || "auto";
  const manualVertical = settings.manualVertical || "";
  const manualProduct = settings.manualProductFocus || "";
  const productOpts = (() => {
    const fromData = [...((data.MAXAB_PRODUCTS || []).map((p) => p.name)), ...((data.SERVICES || []).map((s) => s.name))].filter(Boolean);
    return fromData.length ? Array.from(new Set(fromData)) : ["AI Sales Agent", "Shopify Design", "Automation", "Website Design"];
  })();
  const syncObjectives = async (vertical, product) => {
    const objectives = [];
    if (vertical) objectives.push({ focus: "Focus " + vertical });
    if (product) objectives.push({ focus: "Focus " + product });
    try { await API.agentActions.setCampaignObjectives(objectives); } catch (_) {}
  };
  const setVMode = async (mode) => { setBusy("tv"); try { await API.settings.update({ targetVerticalMode: mode, ...(mode === "auto" ? { manualVertical: "" } : {}) }); await syncObjectives(mode === "manual" ? manualVertical : "", pfMode === "manual" ? manualProduct : ""); await reload(); } catch (_) {} setBusy(""); };
  const pickVertical = async (v) => { setBusy("tv"); try { await API.settings.update({ manualVertical: v, targetVerticalMode: "manual" }); await syncObjectives(v, pfMode === "manual" ? manualProduct : ""); await reload(); } catch (_) {} setBusy(""); };
  const setPMode = async (mode) => { setBusy("pf"); try { await API.settings.update({ productFocusMode: mode, ...(mode === "auto" ? { manualProductFocus: "" } : {}) }); await syncObjectives(tvMode === "manual" ? manualVertical : "", mode === "manual" ? manualProduct : ""); await reload(); } catch (_) {} setBusy(""); };
  const pickProduct = async (p) => { setBusy("pf"); try { await API.settings.update({ manualProductFocus: p, productFocusMode: "manual" }); await syncObjectives(tvMode === "manual" ? manualVertical : "", p); await reload(); } catch (_) {} setBusy(""); };

  // Step 5 — the recommended Revenue Director Plan (from targetScenarios)
  const recScenario = sc && Array.isArray(sc.scenarios) ? (sc.recommended ? sc.scenarios.find((s) => s.key === sc.recommended.key) : null) || sc.scenarios.find((s) => s.coversGap) || sc.scenarios[0] : null;
  const confLabel = recScenario ? (recScenario.probability && recScenario.probability.state === "measured" ? { t: "green", l: T("مُقاس", "Measured") } : recScenario.probability && recScenario.probability.state === "partial" ? { t: "orange", l: T("جزئي", "Partial") } : { t: "neutral", l: T("تقديري", "Estimate") }) : null;
  const riskTone = recScenario ? (STRAT_RISK_TONE[recScenario.risk && recScenario.risk.en] || "neutral") : "neutral";

  // Step 6 — run safe (auto-approvable) actions if execution mode is Auto
  const runSafe = async () => { setBusy("run"); try { await API.agentActions.executionRunAuto(); await reload(); } catch (_) {} setBusy(""); };

  const Step = ({ n, title, sub, right, children }) => (
    <div style={{ padding: "12px 0", borderBottom: "1px solid var(--border-1)" }}>
      <div className="between" style={{ gap: 10, flexWrap: "wrap", alignItems: "flex-start" }}>
        <div className="row" style={{ gap: 10, minWidth: 0 }}>
          <span style={{ width: 22, height: 22, borderRadius: 999, background: "var(--bg-2)", color: "var(--color-secondary)", display: "inline-flex", alignItems: "center", justifyContent: "center", fontWeight: 800, fontSize: 12, flexShrink: 0 }}>{n}</span>
          <div style={{ minWidth: 0 }}><b style={{ fontSize: 13.5 }}>{title}</b>{sub ? <div className="subtle" style={{ fontSize: 11.5 }}>{sub}</div> : null}</div>
        </div>
        {right || null}
      </div>
      {children ? <div style={{ marginTop: 10, marginInlineStart: 32 }}>{children}</div> : null}
    </div>
  );

  // SINGLE-OWNER read-only mode: in the Revenue & Customer DATA screen the console shows a snapshot and
  // links to the Revenue Director (the sole owner of Target → Plan → Approve → Execute) — no writers here.
  if (readOnly) {
    const modeTxt = execAuto ? T("تلقائي", "Auto") : T("يدوي", "Manual");
    const focusTxt = [tvMode === "manual" && manualVertical ? manualVertical : null, pfMode === "manual" && manualProduct ? manualProduct : null].filter(Boolean).join(" · ") || T("تلقائي", "Auto");
    return (
      <Card title={<span className="row" style={{ gap: 8 }}><Icon name="trending" size={16} style={{ color: "var(--color-secondary)" }} />{T("مدير الإيرادات — لقطة", "Revenue Director — snapshot")}</span>}
        action={<Button size="sm" icon="arrowRight" onClick={() => navToRevenueDirector(go)}>{T("افتح للتغيير", "Open to change")}</Button>} flush>
        <div className="col" style={{ gap: 6, padding: "4px 16px 14px" }}>
          <div className="row between" style={{ fontSize: 12.5 }}><span className="subtle">{T("الهدف الشهري", "Monthly target")}</span><b>{curTarget != null ? vsar(curTarget) : T("غير مضبوط", "not set")}</b></div>
          {cas && cas.targetSet ? <div className="row between" style={{ fontSize: 12.5 }}><span className="subtle">{T("المتوقّع · الفجوة", "Forecast · Gap")}</span><b>{vsar(cas.forecast)} · {vsar(cas.gap)}</b></div> : null}
          <div className="row between" style={{ fontSize: 12.5 }}><span className="subtle">{T("وضع التنفيذ", "Execution mode")}</span><b>{modeTxt}</b></div>
          <div className="row between" style={{ fontSize: 12.5 }}><span className="subtle">{T("التركيز", "Focus")}</span><b>{focusTxt}</b></div>
          {recScenario ? <div className="row between" style={{ fontSize: 12.5 }}><span className="subtle">{T("الخطة الموصى بها", "Recommended plan")}</span><b>{recScenario.ref} · {L(recScenario.label)}</b></div> : null}
          <div className="subtle" style={{ fontSize: 11.5, color: "var(--color-orange)", marginTop: 4 }}>{T("لضبط الهدف أو تغيير الخطة أو التنفيذ، افتح مدير الإيراد.", "To set the target, change the plan, or run actions, open the Revenue Director.")}</div>
        </div>
      </Card>
    );
  }
  return (
    <Card title={<span className="row" style={{ gap: 8 }}><Icon name="trending" size={16} style={{ color: "var(--color-secondary)" }} />{T("مدير الإيرادات — لوحة القرار", "Revenue Director — decision console")}</span>}
      action={<Badge tone="lime">{T("إجراءات لا تقارير", "Actions, not reports")}</Badge>} flush>
      <div style={{ padding: "2px 16px 8px" }}>
        {/* STEP 1 — Monthly target + ladder */}
        <Step n={1} title={T("الهدف الشهري", "Monthly target")}
          sub={cas && cas.targetSet ? `${T("متوقّع", "Forecast")} ${vsar(cas.forecast)} · ${T("الفجوة", "Gap")} ${vsar(cas.gap)}` : T("لم يُحدّد هدف بعد", "No target set yet")}
          right={<div className="row" style={{ gap: 8, alignItems: "center", flexWrap: "wrap" }}>
            <b style={{ fontSize: 16, color: "var(--color-secondary)" }}>{curTarget != null ? vsar(curTarget) : "—"}</b>
            <button className="btn btn--subtle btn--sm" disabled={busy === "target"} onClick={() => { setTv(curTarget != null ? String(curTarget) : ""); setEditing((v) => !v); }}>{editing ? T("إلغاء", "Cancel") : T("تعديل", "Edit")}</button>
          </div>}>
          <div className="row" style={{ gap: 6, flexWrap: "wrap", alignItems: "center" }}>
            <span className="subtle" style={{ fontSize: 11.5, marginInlineEnd: 2 }}>{T("سلّم النمو:", "Growth ladder:")}</span>
            {LADDER.map((v) => (
              <button key={v} disabled={busy === "target"} onClick={() => setTarget(v)} className={"btn btn--sm " + (curTarget === v ? "btn--dark" : "btn--subtle")}>{vsar(v)}</button>
            ))}
          </div>
          {editing ? (
            <div className="row" style={{ gap: 8, marginTop: 8, flexWrap: "wrap" }}>
              <input className="input" type="number" min="0" step="1000" value={tv} onChange={(e) => setTv(e.target.value)} style={{ maxWidth: 200 }} placeholder={String(250000)} />
              <Button size="sm" variant="dark" disabled={busy === "target" || tv === ""} onClick={() => setTarget(Number(tv))}>{busy === "target" ? T("جارٍ…", "Saving…") : T("حفظ", "Save")}</Button>
            </div>
          ) : null}
        </Step>

        {/* STEP 2 — Execution mode */}
        <Step n={2} title={T("وضع التنفيذ", "Execution mode")} sub={execAuto ? T("الإجراءات الآمنة تُنفَّذ تلقائياً — الأموال والإيقاف دائماً للمؤسس.", "Safe actions auto-run — money + suspension always founder.") : T("كل إجراء يحتاج اعتمادك.", "Every action needs your approval.")}
          right={<ModeSeg value={execAuto ? "auto" : "manual"} onPick={setExec} busy={busy === "exec"} T={T} />} />

        {/* STEP 3 — Target vertical */}
        <Step n={3} title={T("القطاع المستهدف", "Target vertical")} sub={tvMode === "manual" && manualVertical ? manualVertical : T("تلقائي — المحرّك يوزّع الهدف على القطاعات الأعلى.", "Auto — engine distributes the target across top verticals.")}
          right={<ModeSeg value={tvMode} onPick={setVMode} busy={busy === "tv"} T={T} />}>
          {tvMode === "manual" ? (
            <div className="row" style={{ gap: 6, flexWrap: "wrap" }}>
              {RDC_VERTICALS.map((v) => <button key={v} disabled={busy === "tv"} onClick={() => pickVertical(v)} className={"btn btn--sm " + (manualVertical === v ? "btn--dark" : "btn--subtle")}>{v}</button>)}
            </div>
          ) : null}
        </Step>

        {/* STEP 4 — Product focus */}
        <Step n={4} title={T("تركيز المنتج", "Product focus")} sub={pfMode === "manual" && manualProduct ? manualProduct : T("تلقائي — المحرّك يختار المنتج الأعلى ربحية.", "Auto — engine picks the highest-margin product.")}
          right={<ModeSeg value={pfMode} onPick={setPMode} busy={busy === "pf"} T={T} />}>
          {pfMode === "manual" ? (
            <div className="row" style={{ gap: 6, flexWrap: "wrap" }}>
              {productOpts.map((p) => <button key={p} disabled={busy === "pf"} onClick={() => pickProduct(p)} className={"btn btn--sm " + (manualProduct === p ? "btn--dark" : "btn--subtle")}>{p}</button>)}
            </div>
          ) : null}
        </Step>

        {/* STEP 5 — Revenue Director Plan */}
        <Step n={5} title={T("خطة مدير الإيرادات", "Revenue Director plan")}>
          {!sc || !sc.targetSet ? (
            <div className="subtle" style={{ fontSize: 12.5 }}>{T("اضبط هدفاً شهرياً لتوليد الخطة الموصى بها.", "Set a monthly target to generate the recommended plan.")}</div>
          ) : !recScenario ? (
            <div className="subtle" style={{ fontSize: 12.5 }}>{L(sc.note) || T("لا توجد بيانات كافية للخطة بعد.", "Not enough data for a plan yet.")}</div>
          ) : (
            <div style={{ background: "var(--bg-2)", borderRadius: 10, padding: "12px 14px" }}>
              <div className="between" style={{ gap: 8, flexWrap: "wrap", marginBottom: 6 }}>
                <b style={{ fontSize: 13.5 }}>{recScenario.ref} · {L(recScenario.label)}</b>
                <div className="row" style={{ gap: 6, flexWrap: "wrap" }}>
                  {confLabel ? <Badge tone={confLabel.t} title={T("ثقة الاحتمال", "Confidence")}>{confLabel.l}</Badge> : null}
                  <Badge tone={riskTone} title={T("المخاطرة", "Risk")}>{T("مخاطرة", "Risk")} {L(recScenario.risk)}</Badge>
                </div>
              </div>
              <div className="row" style={{ gap: 16, flexWrap: "wrap", marginBottom: 8 }}>
                <div><div className="subtle" style={{ fontSize: 11 }}>{T("الإيراد المتوقّع", "Expected revenue")}</div><b style={{ fontSize: 18, color: "var(--color-secondary)" }}>{vsar(recScenario.expectedRevenue)}</b>{recScenario.coversGap ? <Badge tone="green" style={{ marginInlineStart: 6 }}>{T("يغطّي الفجوة", "covers gap")}</Badge> : null}</div>
                <div><div className="subtle" style={{ fontSize: 11 }}>{T("الجهد", "Effort")}</div><b style={{ fontSize: 14 }}>{L(recScenario.effort)}</b></div>
              </div>
              <div className="subtle" style={{ fontSize: 11.5, fontWeight: 700, marginBottom: 4 }}>{T("الأنشطة المطلوبة", "Required activities")}</div>
              <div className="row" style={{ gap: 6, flexWrap: "wrap" }}>
                {(recScenario.mix || []).map((m, i) => <Badge key={i} tone="neutral">{m.count}× {L(m.label)}</Badge>)}
              </div>
              {recScenario.why ? <div className="subtle" style={{ fontSize: 11.5, marginTop: 8, lineHeight: 1.5 }}>{L(recScenario.why)}</div> : null}
            </div>
          )}
        </Step>

        {/* STEP 6 — Execute */}
        <Step n={6} title={T("التنفيذ", "Execute")}
          sub={plan && plan.summary ? `${plan.summary.executable} ${T("قابلة للتنفيذ", "executable")} · ${plan.summary.advisory} ${T("إرشادية", "advisory")}` : T("لا إجراءات بعد", "No actions yet")}
          right={<div className="row" style={{ gap: 6, flexWrap: "wrap" }}>
            {execAuto && plan && plan.autoApprovable > 0 ? <Button size="sm" variant="dark" disabled={busy === "run"} onClick={runSafe}>{busy === "run" ? "…" : `${T("نفّذ الآمنة", "Run safe")} (${plan.autoApprovable})`}</Button> : null}
            <span className="subtle" style={{ fontSize: 11.5, alignSelf: "center" }}>{T("اعتمد/نفّذ كل إجراء في لوحة التنفيذ ↓", "Approve / execute each action in the board ↓")}</span>
          </div>} />
      </div>
    </Card>
  );
}

function CeoModePanel({ T, onAdvanced }) {
  const { lang } = useLang();
  useStore();
  const { go } = useApp();
  const L = (x) => (x && typeof x === "object" && !Array.isArray(x) ? (lang === "ar" ? x.ar : x.en) : x);
  const cc = vget("commandCenter");
  if (!cc || cc.error || !cc.ceo) return <Card flush><VEmpty icon={cc && cc.error ? "alert" : "dollar"} title={cc && cc.error ? T("تعذّر التحميل", "Couldn't load") : T("جارٍ التحميل…", "Loading…")} body={cc && cc.error} /></Card>;
  const ceo = cc.ceo;
  const es = ceo.executiveSummary || {};
  const bandTone = es.band ? (es.band.key === "on_track" ? "var(--color-secondary)" : es.band.key === "at_risk" ? "var(--color-orange)" : es.band.key === "off_track" ? "var(--color-danger)" : "var(--fg-1)") : "var(--fg-1)";
  return (
    <div className="col" style={{ gap: 22 }}>
      {/* CEO REVENUE AUTOPILOT — Founder Mode: the 5 glanceable cards (Target / Fastest Path /
          Biggest Risk / Biggest Opportunity / Next Action). Concise, no clutter. The full target +
          Auto/Manual decision console now lives in the Target Planning tab. */}
      <FounderModeSection cc={cc} T={T} lang={lang} />

      {/* SALES MANAGER EXECUTION BRIDGE — the top 3 actions to approve/execute now (Command Center). */}
      <ExecutionBoardSection cc={cc} T={T} lang={lang} mode="ceo" readOnly go={go} />

      {/* CUSTOMER SUCCESS — the required founder decisions (one queue) right in the daily view. */}
      <FounderDecisionsSection cc={cc} T={T} lang={lang} go={go} />

      {/* SECTION 1 — Executive summary. When deals span MULTIPLE currencies the single-number
          roll-up would be misleading, so we refuse it and show revenue/pipeline/forecast BY
          currency (Part 1 Stage 3 — "no fake total"). Single-currency installs are unchanged. */}
      {cc.currencyContext && cc.currencyContext.mixed ? (
        <CeoCurrencyView ctx={cc.currencyContext} T={T} lang={lang} onAdvanced={onAdvanced} />
      ) : es.targetSet ? (
        <div className="grid" style={{ gridTemplateColumns: "repeat(auto-fit, minmax(150px, 1fr))", gap: 14 }}>
          <CeoStatCard label={T("الهدف", "Target")} value={vsar(es.target)} big />
          <CeoStatCard label={T("المتوقّع", "Forecast")} value={vsar(es.forecast)} tone="var(--color-secondary)" big />
          <CeoStatCard label={T("الفجوة", "Revenue gap")} value={vsar(es.gap)} tone={es.gap > 0 ? "var(--color-orange)" : "var(--color-secondary)"} big />
          <CeoStatCard label={T("التوقّع مقابل الهدف", "Forecast vs target")} value={es.coveragePct != null ? es.coveragePct + "%" : "—"} sub={T("حصة الهدف المغطّاة", "of target covered")} />
          <CeoStatCard label={T("الحالة", "Status")} value={L(es.band)} tone={bandTone} />
        </div>
      ) : (
        <div className="card" style={{ padding: 18 }}>
          <div className="row" style={{ gap: 10, flexWrap: "wrap", alignItems: "center" }}>
            <div style={{ flex: 1, minWidth: 220 }}><b style={{ fontSize: 15 }}>{T("لا يوجد هدف إيراد محدد", "No revenue target set")}</b><div className="subtle" style={{ fontSize: 13, marginTop: 4, lineHeight: 1.5 }}>{T("اضبط هدفًا شهريًا للشركة لتفعيل لوحة القيادة.", "Set a company monthly target to activate the command center.")}</div></div>
            <Button size="sm" variant="dark" onClick={onAdvanced}>{T("اضبط هدفًا", "Set a target")}</Button>
          </div>
        </div>
      )}

      {/* SECTION 2 — What should I do today (top revenue-impact actions) */}
      <Card title={T("ماذا أفعل اليوم؟", "What should I do today?")} flush>
        <div style={{ padding: "4px 0" }}>
          {(ceo.todayActions || []).length ? ceo.todayActions.map((a, i) => (
            <button key={a.kind + i} onClick={() => go(a.target || "opportunities")} className="between" style={{ width: "100%", textAlign: "start", padding: "13px 16px", borderBottom: "1px solid var(--border-1)", gap: 12, alignItems: "center", background: "transparent", cursor: "pointer" }}>
              <div className="row" style={{ gap: 12, alignItems: "center", minWidth: 0 }}>
                <span style={{ width: 26, height: 26, borderRadius: 999, background: "var(--bg-2)", color: "var(--color-secondary)", display: "inline-flex", alignItems: "center", justifyContent: "center", fontWeight: 800, fontSize: 13, flexShrink: 0 }}>{i + 1}</span>
                <div style={{ minWidth: 0 }}>
                  <div style={{ fontWeight: 700, fontSize: 14 }}>{L(a.title)}{a.detail ? <span className="subtle" style={{ fontWeight: 500 }}> · {a.detail}</span> : null}</div>
                  <div style={{ fontSize: 12.5, color: "var(--fg-4)", marginTop: 2 }}>{L(a.action)}</div>
                </div>
              </div>
              {a.impactSar > 0 ? <span style={{ fontWeight: 800, color: "var(--color-secondary)", whiteSpace: "nowrap", fontSize: 14 }}>+{vsar(a.impactSar)}</span> : <Icon name="chevronRight" size={16} style={{ color: "var(--fg-disabled)" }} />}
            </button>
          )) : <VEmpty icon="checkcircle" title={T("لا إجراءات عاجلة", "Nothing urgent")} body={T("لا توجد تحرّكات عالية الأثر الآن.", "No high-impact moves right now.")} />}
        </div>
      </Card>

      {/* SECTIONS 3+4 side by side on wide screens */}
      <div className="grid" style={{ gridTemplateColumns: "repeat(auto-fit, minmax(300px, 1fr))", gap: 16 }}>
        {/* SECTION 3 — Who needs attention */}
        <Card title={T("من يحتاج انتباهك؟", "Who needs my attention?")} flush>
          <div style={{ padding: "4px 0" }}>
            {(ceo.agentsNeedingAttention || []).length ? ceo.agentsNeedingAttention.map((a) => {
              const st = AGENT_STATUS[a.status] || {};
              return (
                <div key={a.agentId} className="between" style={{ padding: "11px 16px", borderBottom: "1px solid var(--border-1)", gap: 10 }}>
                  <div className="row" style={{ gap: 10, minWidth: 0 }}><Avatar name={a.name} size="sm" /><div style={{ minWidth: 0 }}><div style={{ fontWeight: 700, fontSize: 13.5 }}>{a.name}</div><div className="subtle" style={{ fontSize: 11.5 }}>{T("هدف", "Target")} {vsar(a.target)} · {T("متوقّع", "fcst")} {vsar(a.forecast)}</div></div></div>
                  <div style={{ textAlign: "end", flexShrink: 0 }}><div style={{ fontWeight: 800, color: "var(--color-orange)" }}>{vsar(a.gap)}</div>{st.en ? <Badge tone={st.tone}>{T(st.ar, st.en)}</Badge> : null}</div>
                </div>
              );
            }) : <VEmpty icon="checkcircle" title={T("الجميع على المسار", "Everyone's on track")} />}
          </div>
        </Card>

        {/* SECTION 4 — Biggest risks */}
        <Card title={T("أكبر المخاطر", "Biggest revenue risks")} flush>
          <div style={{ padding: "4px 0" }}>
            {(ceo.biggestRisks || []).length ? ceo.biggestRisks.map((r) => (
              <div key={r.key} className="row" style={{ padding: "11px 16px", borderBottom: "1px solid var(--border-1)", gap: 10, alignItems: "flex-start" }}>
                <Icon name={CEO_RISK_ICON[r.key] || "alert"} size={15} style={{ color: "var(--color-orange)", flexShrink: 0, marginTop: 2 }} />
                <div style={{ minWidth: 0, flex: 1 }}>
                  <div className="between" style={{ gap: 8, flexWrap: "wrap" }}><span style={{ fontWeight: 700, fontSize: 13.5 }}>{L(r.title)}</span>{r.impactSar > 0 ? <span style={{ fontWeight: 700, color: "var(--color-orange)", whiteSpace: "nowrap", fontSize: 12.5 }}>{vsar(r.impactSar)}</span> : null}</div>
                  <div style={{ fontSize: 12.5, color: "var(--fg-4)", marginTop: 2, lineHeight: 1.5 }}>{L(r.why)}</div>
                  <div style={{ fontSize: 12.5, fontWeight: 600, color: "var(--color-secondary)", marginTop: 3 }}>→ {L(r.action)}</div>
                </div>
              </div>
            )) : <VEmpty icon="checkcircle" title={T("لا مخاطر بارزة", "No major risks")} />}
          </div>
        </Card>
      </div>

      {/* SECTION 5 — Biggest opportunities */}
      <Card title={T("أكبر الفرص", "Biggest revenue opportunities")} flush>
        <div style={{ padding: "4px 0" }}>
          {(ceo.biggestOpportunities || []).length ? ceo.biggestOpportunities.map((o) => (
            <button key={o.id} onClick={() => go("opportunities")} className="between" style={{ width: "100%", textAlign: "start", padding: "12px 16px", borderBottom: "1px solid var(--border-1)", gap: 12, alignItems: "center", background: "transparent", cursor: "pointer" }}>
              <div className="row" style={{ gap: 10, minWidth: 0 }}><Icon name="trending" size={15} style={{ color: "var(--color-secondary)", flexShrink: 0 }} /><span style={{ fontWeight: 600, fontSize: 13.5, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{o.name}{o.owner ? <span className="subtle" style={{ fontWeight: 400 }}> · {o.owner}</span> : null}</span></div>
              <div className="row" style={{ gap: 10, flexShrink: 0, alignItems: "center" }}>{o.roiScore != null ? <Badge tone="lime" title={T("درجة العائد", "ROI Score")}>{T("عائد", "ROI")} {o.roiScore}</Badge> : null}<div style={{ textAlign: "end" }}><div style={{ fontWeight: 800, color: "var(--color-secondary)" }}>{vsar(o.potential)}</div><div className="subtle" style={{ fontSize: 11 }}>{T("القيمة الكاملة", "full potential")}</div></div></div>
            </button>
          )) : <VEmpty icon="dollar" title={T("لا فرص مفتوحة بقيمة", "No valued open opportunities")} body={T("ستظهر هنا فور دخول فرص حقيقية إلى خط الأنابيب.", "They appear here as real opportunities enter the pipeline.")} />}
        </div>
      </Card>

      {/* Revenue Director — recommended path to target (summary; the full product-mix plan, all paths
          and meetings now live in Target Planning / Product Strategy / Execution). */}
      <RecommendedPathSummary cc={cc} T={T} lang={lang} onAdvanced={onAdvanced} />
    </div>
  );
}

// Upcoming meetings — agent / prospect / opportunity / type / calendar status (Part 1 CEO +
// reused in Advanced). Reads cc.meetingsOverview (revenue-director). Honest empty state.
function UpcomingMeetingsSection({ cc, T, lang, go }) {
  const mo = cc && cc.meetingsOverview;
  if (!mo) return null;
  const rows = (mo.upcoming || []);
  const today = mo.today;
  const syncMeta = { synced: { tone: "green", ar: "في التقويم", en: "in Calendar" }, pending: { tone: "orange", ar: "قيد المزامنة", en: "syncing" }, skipped: { tone: "neutral", ar: "غير متزامن", en: "not synced" }, error: { tone: "red", ar: "فشل المزامنة", en: "sync failed" } };
  return (
    <Card title={<span className="row" style={{ gap: 8 }}><Icon name="calendar" size={15} style={{ color: "var(--color-secondary)" }} />{T("الاجتماعات القادمة", "Upcoming meetings")}</span>}
      action={<span className="subtle" style={{ fontSize: 12 }}>{mo.counts.upcoming} {T("هذا الأسبوع", "this week")} · {mo.counts.missed} {T("فائتة", "missed")}</span>} flush>
      <div style={{ overflowX: "auto", width: "100%" }}>
        {rows.length ? (
          <table className="table" style={{ minWidth: 640, width: "100%" }}>
            <thead><tr><th>{T("متى", "When")}</th><th>{T("العميل", "Prospect")}</th><th>{T("الوكيل", "Agent")}</th><th>{T("النوع", "Type")}</th><th>{T("التقويم", "Calendar")}</th></tr></thead>
            <tbody>
              {rows.map((m) => { const sm = syncMeta[m.calendarSync] || syncMeta.skipped; return (
                <tr key={m.id}>
                  <td style={{ whiteSpace: "nowrap", fontWeight: 600, color: m.date === today ? "var(--color-secondary)" : "var(--fg-2)" }}>{m.date === today ? T("اليوم", "Today") : m.date}{m.time ? " · " + m.time : ""}</td>
                  <td style={{ fontWeight: 600 }}>{m.contact || "—"}{m.opportunityId ? <span className="subtle" style={{ fontWeight: 400, fontSize: 11 }}> · {T("فرصة", "opp")}</span> : null}</td>
                  <td>{m.agent || "—"}</td>
                  <td>{m.channel === "google_meet" ? "Google Meet" : m.channel === "phone" ? T("هاتف", "Phone") : T("حضوري", "In person")}</td>
                  <td><Badge tone={sm.tone}>{lang === "ar" ? sm.ar : sm.en}</Badge>{m.meetLink ? <a href={m.meetLink} target="_blank" rel="noreferrer" style={{ marginInlineStart: 6, fontSize: 12, color: "var(--color-secondary)" }}>{T("رابط", "link")}</a> : null}</td>
                </tr>
              ); })}
            </tbody>
          </table>
        ) : <div style={{ padding: "18px 16px" }}><VEmpty icon="calendar" title={T("لا اجتماعات قادمة هذا الأسبوع", "No meetings this week")} body={T("ستظهر هنا الاجتماعات التي يحجزها الوكلاء.", "Meetings booked by your agents appear here.")} /></div>}
      </div>
    </Card>
  );
}

// [Revenue Section Rebuild] AdvancedRevenuePanel was removed here — the old single Advanced wall is
// now split across the 7 focused tab panels (TargetPlanning / ExecutionBoard / ProductStrategy /
// VerticalStrategy / CustomerSuccess / IntelligenceAudit) + the lean CeoModePanel. Every section it
// rendered is reused verbatim in exactly one of those panels (see REVENUE_SECTION_CLEANUP_REPORT.md).
// The funnel-health + setup-gates + finish-setup block lives in SetupHealthSection (Intelligence & Audit).

// ---- Real Performance (Parts 1 + 2) ----
function RealPerformancePanel({ T }) {
  useStore();
  const d = vget("report");
  if (!d || d.error) return <Card flush><VEmpty icon={d && d.error ? "alert" : "dollar"} title={d && d.error ? T("تعذّر التحميل", "Couldn't load") : T("جارٍ التحميل…", "Loading…")} body={d && d.error} /></Card>;
  return (
    <div className="col" style={{ gap: 16 }}>
      <div className="card" style={{ padding: 14, background: d.revenue.real > 0 ? "var(--bg-1)" : "var(--bg-2)", borderInlineStart: "3px solid " + (d.revenue.real > 0 ? "var(--color-secondary)" : "var(--color-orange)") }}>
        <div className="row" style={{ gap: 8, marginBottom: 4 }}><VLevelBadge level={d.overallValidationLevel} label={d.overallLabel} /><b style={{ fontSize: 14 }}>{T("مستوى التحقّق العام", "Overall validation level")}</b></div>
        <div style={{ fontSize: 13, color: "var(--fg-3)", lineHeight: 1.5 }}>{d.honest}</div>
      </div>
      <div className="grid" style={{ gridTemplateColumns: "repeat(auto-fit, minmax(160px, 1fr))", gap: 12 }}>
        <VStat label={T("إيراد حقيقي (Stripe)", "Real revenue (Stripe)")} value={vsar(d.revenue.real)} sub={d.revenue.realWonDeals + " " + T("صفقة", "deals")} tone={d.revenue.real > 0 ? "var(--color-secondary)" : undefined} />
        <VStat label={T("إيراد اصطناعي/تجريبي", "Synthetic / test value")} value={vsar(d.revenue.synthetic)} sub={T("معلّم يدويًا، بلا دفع", "operator-marked, no payment")} />
        <VStat label={T("عملاء حقيقيون", "Real customers")} value={d.realCustomers} />
        <VStat label={T("حصة الإيراد الحقيقي", "Real revenue share")} value={vpct(d.revenue.realShare)} />
      </div>
      <Card title={T("السجلات حسب مستوى التحقّق", "Records by validation level")} flush>
        <div style={{ padding: "4px 0" }}>
          {d.levels.map((l) => (
            <div key={l.level} className="between" style={{ padding: "10px 16px", borderBottom: "1px solid var(--border-1)" }}>
              <div className="row" style={{ gap: 10 }}><VLevelBadge level={l.level} label={l.label} /></div>
              <span style={{ fontWeight: 700 }}>{l.records}</span>
            </div>
          ))}
        </div>
      </Card>
    </div>
  );
}

// ---- Certifications (Part 3) ----
function CertificationPanel({ T }) {
  useStore();
  const d = vget("certification");
  if (!d || d.error) return <Card flush><VEmpty icon={d && d.error ? "alert" : "trophy"} title={d && d.error ? T("تعذّر التحميل", "Couldn't load") : T("جارٍ التحميل…", "Loading…")} body={d && d.error} /></Card>;
  return (
    <div className="col" style={{ gap: 14 }}>
      <div className="card" style={{ padding: 12, background: "var(--bg-2)" }}>
        <div style={{ fontSize: 13, color: "var(--fg-3)" }}>{d.honest}</div>
        <div className="row" style={{ gap: 6, marginTop: 8, flexWrap: "wrap" }}>{d.tiers.slice().reverse().map((t) => <Badge key={t.tier} tone="neutral">{t.tier}: {t.min}+ {T("صفقة حقيقية", "real deals")}</Badge>)}</div>
      </div>
      <Card title={T("شهادات الوكلاء (على صفقات حقيقية فقط)", "Agent certifications (real deals only)")} flush>
        <div style={{ overflowX: "auto", width: "100%" }}>
          <table className="tbl" style={{ width: "100%", fontSize: 13, borderCollapse: "collapse", minWidth: 560 }}>
            <thead><tr style={{ color: "var(--fg-4)" }}>{[T("الوكيل", "Agent"), T("صفقات حقيقية", "Real won"), T("إيراد حقيقي", "Real revenue"), T("الشهادة", "Certification"), T("التالي", "Next tier")].map((h, i) => <th key={i} style={{ padding: "8px 12px", textAlign: "start", fontWeight: 600, whiteSpace: "nowrap" }}>{h}</th>)}</tr></thead>
            <tbody>
              {d.agents.map((a) => (
                <tr key={a.agentId} style={{ borderTop: "1px solid var(--border-1)" }}>
                  <td style={{ padding: "8px 12px" }}><div className="row" style={{ gap: 8 }}><Avatar name={a.name} size="sm" /><span style={{ fontWeight: 600 }}>{a.name}</span></div></td>
                  <td style={{ padding: "8px 12px", fontWeight: 700 }}>{a.realWonDeals}</td>
                  <td style={{ padding: "8px 12px" }}>{vsar(a.realRevenue)}</td>
                  <td style={{ padding: "8px 12px" }}>{a.certified ? <Badge tone="lime">{a.certification}</Badge> : <span className="muted">{T("غير معتمد", "Not certified")}</span>}</td>
                  <td style={{ padding: "8px 12px", color: "var(--fg-4)" }}>{a.nextTier ? `${a.nextTier.tier} (+${a.nextTier.need})` : "—"}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </Card>
      <div style={{ fontSize: 12, color: "var(--fg-4)" }}>{d.note}</div>
    </div>
  );
}

// ---- Benchmark (Part 4) ----
function BenchmarkPanel({ T }) {
  useStore();
  const d = vget("benchmark");
  if (!d || d.error) return <Card flush><VEmpty icon={d && d.error ? "alert" : "trending"} title={d && d.error ? T("تعذّر التحميل", "Couldn't load") : T("جارٍ التحميل…", "Loading…")} body={d && d.error} /></Card>;
  return (
    <div className="col" style={{ gap: 12 }}>
      <div className="subtle" style={{ fontSize: 12 }}>{T("مصدر البيانات", "Data source")}: <Badge tone={d.dataSource === "synthetic_only" ? "orange" : "lime"}>{d.dataSource}</Badge> · {d.forecastAccuracyNote}</div>
      <Card title={T("مقارنة الوكلاء", "Agent benchmark")} flush>
        <div style={{ overflowX: "auto", width: "100%" }}>
          <table className="tbl" style={{ width: "100%", fontSize: 13, borderCollapse: "collapse", minWidth: 640 }}>
            <thead><tr style={{ color: "var(--fg-4)" }}>{[T("الوكيل", "Agent"), T("إيراد حقيقي", "Real rev"), T("إجمالي", "All rev"), T("تحويل", "Conv."), T("جودة الفرص", "Opp quality"), T("توقّع", "Forecast"), T("شهادة", "Cert")].map((h, i) => <th key={i} style={{ padding: "8px 12px", textAlign: "start", fontWeight: 600, whiteSpace: "nowrap" }}>{h}</th>)}</tr></thead>
            <tbody>
              {d.ranked.map((a, i) => (
                <tr key={a.agentId} style={{ borderTop: "1px solid var(--border-1)" }}>
                  <td style={{ padding: "8px 12px" }}><div className="row" style={{ gap: 8 }}><span style={{ width: 16, color: "var(--fg-4)" }}>{i + 1}</span><span style={{ fontWeight: 600 }}>{a.name}</span></div></td>
                  <td style={{ padding: "8px 12px", fontWeight: 700 }}>{vsar(a.realRevenue)}</td>
                  <td style={{ padding: "8px 12px", color: "var(--fg-4)" }}>{vsar(a.revenue)}</td>
                  <td style={{ padding: "8px 12px" }}>{vpct(a.conversionRate)}</td>
                  <td style={{ padding: "8px 12px" }}>{a.opportunityQuality == null ? "—" : a.opportunityQuality}</td>
                  <td style={{ padding: "8px 12px" }}>{a.forecast == null ? "—" : vsar(a.forecast)}</td>
                  <td style={{ padding: "8px 12px" }}>{a.certification ? <Badge tone="lime">{a.certification}</Badge> : "—"}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </Card>
    </div>
  );
}

// ---- Founder Review (Part 5) ----
function FounderReviewPanel({ T }) {
  useStore();
  const reviews = DATA.FOUNDER_REVIEWS || [];
  const agents = DATA.AGENTS || [];
  const [targetType, setTargetType] = React.useState("agent");
  const [targetId, setTargetId] = React.useState(agents[0] ? agents[0].id : "");
  const [action, setAction] = React.useState("improve");
  const [comment, setComment] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState("");
  const submit = async () => {
    setErr("");
    if (!targetId) { setErr(T("اختر هدفًا", "Pick a target")); return; }
    if ((action === "improve" || action === "comment") && !comment.trim()) { setErr(T("التعليق مطلوب", "Comment required")); return; }
    setBusy(true);
    try { const r = await Actions.createFounderReview({ targetType, targetId, action, comment, by: "founder" }); if (r && r.ok) { setComment(""); } else setErr((r && r.error) || "failed"); }
    catch (e) { setErr((e && e.message) || "failed"); } finally { setBusy(false); }
  };
  return (
    <div className="grid" style={{ gridTemplateColumns: "repeat(auto-fit, minmax(320px, 1fr))", gap: 16 }}>
      <Card title={T("مراجعة جديدة", "New review")}>
        <div className="col" style={{ gap: 10 }}>
          <select className="input" value={targetType} onChange={(e) => setTargetType(e.target.value)}>
            {["agent", "conversation", "opportunity", "proposal", "win", "loss", "followup"].map((t) => <option key={t} value={t}>{t}</option>)}
          </select>
          {targetType === "agent"
            ? <select className="input" value={targetId} onChange={(e) => setTargetId(e.target.value)}>{agents.map((a) => <option key={a.id} value={a.id}>{a.name}</option>)}</select>
            : <input className="input" placeholder={T("معرّف الهدف (id)", "Target id")} value={targetId} onChange={(e) => setTargetId(e.target.value)} />}
          <div className="row" style={{ gap: 6, flexWrap: "wrap" }}>
            {["approve", "reject", "improve", "comment"].map((a) => <button key={a} className={"btn btn--sm " + (action === a ? "btn--dark" : "btn--subtle")} onClick={() => setAction(a)}>{a}</button>)}
          </div>
          <textarea className="input" rows={3} placeholder={T("التعليق / التوجيه (يُغذّي تعلّم الوكيل)", "Comment / guidance (feeds the agent's learning)")} value={comment} onChange={(e) => setComment(e.target.value)} />
          {err && <div style={{ color: "var(--color-orange)", fontSize: 12 }}>{err}</div>}
          <div className="subtle" style={{ fontSize: 12 }}>{T("تُخزَّن المراجعة، و\"تحسين\" تصبح توجيهًا في تدريب الوكيل، ويُقاس الأثر من جودة المحادثات قبل/بعد.", "The review is stored; an 'improve' becomes a coaching directive, and impact is measured from conversation quality before/after.")}</div>
          <Button size="sm" onClick={submit} disabled={busy}>{busy ? T("جارٍ…", "Saving…") : T("حفظ المراجعة", "Save review")}</Button>
        </div>
      </Card>
      <Card title={T("المراجعات الأخيرة", "Recent reviews")} flush>
        <div style={{ padding: "4px 0" }}>
          {reviews.length ? reviews.slice(0, 20).map((r) => (
            <div key={r.id} style={{ padding: "10px 16px", borderBottom: "1px solid var(--border-1)" }}>
              <div className="row" style={{ gap: 8 }}><Badge tone={r.action === "approve" ? "lime" : r.action === "reject" ? "red" : "blue"}>{r.action}</Badge><span style={{ fontWeight: 600, fontSize: 13 }}>{r.targetType}</span><span className="muted" style={{ fontSize: 12 }}>{r.targetId}</span></div>
              {r.comment && <div style={{ fontSize: 13, color: "var(--fg-3)", marginTop: 3 }}>{r.comment}</div>}
            </div>
          )) : <VEmpty icon="message" title={T("لا مراجعات بعد", "No reviews yet")} body={T("راجع وكيلًا أو صفقة وقدّم ملاحظات Approve/Reject/Improve/Comment.", "Review an agent or deal and give Approve/Reject/Improve/Comment feedback.")} />}
        </div>
      </Card>
    </div>
  );
}

// ---- Human vs AI (Part 6) ----
function HumanVsAiPanel({ T }) {
  useStore();
  const d = vget("humanVsAi");
  if (!d || d.error) return <Card flush><VEmpty icon={d && d.error ? "alert" : "bot"} title={d && d.error ? T("تعذّر التحميل", "Couldn't load") : T("جارٍ التحميل…", "Loading…")} body={d && d.error} /></Card>;
  return (
    <div className="col" style={{ gap: 12 }}>
      <div className="grid" style={{ gridTemplateColumns: "repeat(auto-fit, minmax(200px, 1fr))", gap: 12 }}>
        {d.buckets.map((b) => (
          <div key={b.kind} className="card" style={{ padding: 16 }}>
            <div style={{ fontSize: 12, color: "var(--fg-4)", fontWeight: 600, textTransform: "uppercase" }}>{b.kind}</div>
            <div style={{ fontSize: 22, fontWeight: 800, marginTop: 4 }}>{vsar(b.revenue)}</div>
            <div style={{ fontSize: 12, color: "var(--fg-4)", marginTop: 2 }}>{b.opps} {T("فرص", "opps")} · {b.won} {T("فوز", "won")} · {vpct(b.revenueShare)} {T("حصة", "share")}</div>
          </div>
        ))}
      </div>
      <div style={{ fontSize: 12, color: "var(--fg-4)" }}>{d.note}</div>
    </div>
  );
}

// ---- Market Score (Part 7) ----
function MarketScorePanel({ T }) {
  useStore();
  const d = vget("marketScore");
  if (!d || d.error) return <Card flush><VEmpty icon={d && d.error ? "alert" : "target"} title={d && d.error ? T("تعذّر التحميل", "Couldn't load") : T("جارٍ التحميل…", "Loading…")} body={d && d.error} /></Card>;
  return (
    <div className="col" style={{ gap: 16 }}>
      <div className="card" style={{ padding: 20, textAlign: "center" }}>
        <div style={{ fontSize: 44, fontWeight: 800, letterSpacing: "-0.03em", color: d.score >= 70 ? "var(--color-secondary)" : d.score >= 40 ? "var(--color-blue)" : "var(--color-orange)" }}>{d.score}<span style={{ fontSize: 20, color: "var(--fg-4)" }}>/100</span></div>
        <Badge tone={d.verdict === "VALIDATED" ? "lime" : d.verdict === "PRE-VALIDATION" ? "orange" : "blue"}>{d.verdict}</Badge>
        <div style={{ fontSize: 13, color: "var(--fg-3)", marginTop: 10, maxWidth: 560, margin: "10px auto 0", lineHeight: 1.5 }}>{d.explanation}</div>
      </div>
      <Card title={T("العوامل (قابلة للتفسير)", "Factors (explainable)")} flush>
        <div style={{ padding: "4px 0" }}>
          {d.factors.map((f) => (
            <div key={f.key} className="between" style={{ padding: "10px 16px", borderBottom: "1px solid var(--border-1)" }}>
              <div><div style={{ fontWeight: 600, fontSize: 13 }}>{f.label}</div><div style={{ fontSize: 12, color: "var(--fg-4)" }}>{f.na || f.value == null ? T("غير متاح — يتطلب قياسًا", "N/A — needs instrumentation") : `${f.value} / ${f.target} ${T("هدف", "target")}`}</div></div>
              <Badge tone={f.contribution > 0 ? "lime" : "neutral"}>+{f.contribution}</Badge>
            </div>
          ))}
        </div>
      </Card>
      <div style={{ fontSize: 12, color: "var(--fg-4)" }}>{d.note}</div>
    </div>
  );
}

// ---- Evidence (Part 8) ----
function EvidencePanel({ T }) {
  useStore();
  const d = vget("evidence");
  if (!d || d.error) return <Card flush><VEmpty icon={d && d.error ? "alert" : "clipboard"} title={d && d.error ? T("تعذّر التحميل", "Couldn't load") : T("جارٍ التحميل…", "Loading…")} body={d && d.error} /></Card>;
  const Row = (items, render) => items && items.length ? items.map((it, i) => <div key={i} style={{ padding: "8px 16px", borderBottom: "1px solid var(--border-1)", fontSize: 13 }}>{render(it)}</div>) : <VEmpty title={T("لا عناصر", "None")} />;
  return (
    <div className="col" style={{ gap: 14 }}>
      <div className="card" style={{ padding: 12, background: "var(--bg-2)" }}><div style={{ fontSize: 13, color: "var(--fg-3)" }}>{d.honest}</div></div>
      <div className="grid" style={{ gridTemplateColumns: "repeat(auto-fit, minmax(300px, 1fr))", gap: 16 }}>
        <Card title={T("قصص نجاح", "Success stories") + ` (${d.counts.wins})`} flush><div style={{ padding: "4px 0" }}>{Row(d.wins, (w) => <div className="between"><span>{w.lead} <span className="muted">{w.service} · {w.angle || ""}</span></span><VLevelBadge level={w.validationLevel} label={w.validationLabel} /></div>)}</div></Card>
        <Card title={T("صفقات خاسرة", "Lost deals") + ` (${d.counts.losses})`} flush><div style={{ padding: "4px 0" }}>{Row(d.losses, (l) => <div className="between"><span>{l.lead} <span className="muted">{l.reason || ""}</span></span><VLevelBadge level={l.validationLevel} label={l.validationLabel} /></div>)}</div></Card>
      </div>
    </div>
  );
}

// ---- Product Validation (Parts 9 + 10) ----
function ProductValidationPanel({ T }) {
  useStore();
  const sub = vget("productSubscription");
  const sc = vget("productSourceCode");
  const Funnel = ({ d }) => (!d || d.error) ? <VEmpty title={T("جارٍ التحميل…", "Loading…")} /> : (
    <div className="col" style={{ gap: 8, fontSize: 13 }}>
      <div className="grid" style={{ gridTemplateColumns: "repeat(auto-fit, minmax(90px, 1fr))", gap: 8 }}>
        {[["Leads", d.leads], ["Opps", d.opportunities], ["Demos", d.demos], ["Trials", d.trials == null ? "N/A" : d.trials], ["Paid", d.paid]].map(([k, v]) => <div key={k} style={{ background: "var(--bg-2)", borderRadius: 10, padding: "8px 10px" }}><div style={{ fontWeight: 800 }}>{v}</div><div style={{ fontSize: 11, color: "var(--fg-4)" }}>{k}</div></div>)}
      </div>
      <div className="row" style={{ gap: 10, flexWrap: "wrap" }}>
        {d.mrr != null && <Badge tone="neutral">MRR {vsar(d.mrr)}</Badge>}
        {d.arr != null && <Badge tone="neutral">ARR {vsar(d.arr)}</Badge>}
        {d.oneTimeRevenue != null && <Badge tone="neutral">{T("لمرة واحدة", "One-time")} {vsar(d.oneTimeRevenue)}</Badge>}
        <Badge tone={d.signals.productMarketFit === "emerging" ? "lime" : "orange"}>PMF: {d.signals.productMarketFit}</Badge>
      </div>
      <div className="muted" style={{ fontSize: 12 }}>{d.honest}</div>
    </div>
  );
  return (
    <div className="grid" style={{ gridTemplateColumns: "repeat(auto-fit, minmax(320px, 1fr))", gap: 16 }}>
      <Card title={T("اشتراك وكيل المبيعات الذكي", "AI Sales Agent — Subscription")}><Funnel d={sub} /></Card>
      <Card title={T("ترخيص الكود المصدري", "AI Sales Agent — Source Code License")}><Funnel d={sc} /></Card>
    </div>
  );
}

// ---- Readiness (Part 12) ----
function ReadinessPanel({ T }) {
  useStore();
  const d = vget("readiness");
  if (!d || d.error) return <Card flush><VEmpty icon={d && d.error ? "alert" : "shield"} title={d && d.error ? T("تعذّر التحميل", "Couldn't load") : T("جارٍ التحميل…", "Loading…")} body={d && d.error} /></Card>;
  return (
    <div className="col" style={{ gap: 16 }}>
      <div className="card" style={{ padding: 14, borderInlineStart: "3px solid " + (d.gatesPassed === 3 ? "var(--color-secondary)" : "var(--color-orange)") }}>
        <b style={{ fontSize: 14 }}>{T("الجاهزية الإجمالية", "Overall readiness")}</b>
        <div style={{ fontSize: 13, color: "var(--fg-3)", marginTop: 4, lineHeight: 1.5 }}>{d.overall}</div>
      </div>
      <Card title={T("البوابات التشغيلية", "Operational gates") + ` (${d.gatesPassed}/3)`} flush>
        <div style={{ padding: "4px 0" }}>
          {d.gates.map((g, i) => (
            <div key={i} className="between" style={{ padding: "10px 16px", borderBottom: "1px solid var(--border-1)" }}>
              <span style={{ fontSize: 13 }}>{g.gate}</span>
              <div className="row" style={{ gap: 8 }}><span className="muted" style={{ fontSize: 12 }}>{g.detail}</span><Badge tone={g.ok ? "lime" : "red"}>{g.ok ? "PASS" : "BLOCKED"}</Badge></div>
            </div>
          ))}
        </div>
      </Card>
      <Card title={T("جاهزية وكلاء ما بعد البيع (بالأدلة)", "Post-sale agent readiness (evidence-based)")} flush>
        <div style={{ padding: "4px 0" }}>
          {d.questions.map((q, i) => (
            <div key={i} style={{ padding: "12px 16px", borderBottom: "1px solid var(--border-1)" }}>
              <div className="row" style={{ gap: 8 }}><Badge tone={q.verdict === "START_NOW" ? "lime" : "orange"}>{q.verdict}</Badge><span style={{ fontWeight: 700, fontSize: 14 }}>{q.capability}</span></div>
              <div style={{ fontSize: 13, color: "var(--fg-3)", marginTop: 3 }}>{q.reason}</div>
              <div style={{ fontSize: 12, color: "var(--fg-4)", marginTop: 3 }}>{T("يتطلب", "Requires")}: {q.requires}</div>
            </div>
          ))}
        </div>
      </Card>
      <div style={{ fontSize: 12, color: "var(--fg-4)" }}>{T("الأدلة الحقيقية", "Real evidence")}: {d.realEvidence.realCustomers} {T("عملاء", "customers")} · {d.realEvidence.realWonDeals} {T("صفقات", "deals")} · {vsar(d.realEvidence.realRevenue)} · {d.realEvidence.metricSnapshots} {T("لقطات", "snapshots")}</div>
    </div>
  );
}
