// screens-assem.jsx — CHAT WITH ASSEM: the single executive (CEO) interface above the platform.
// Assem reads the existing engines (via /api/assem/*) and answers; it never fabricates a metric and
// money/dangerous actions stay founder-gated. This screen is the chat + mode + snapshot + reports.
const ASSEM_MODE_META = {
  off: { tone: "neutral", ar: "متوقّف — تقارير فقط", en: "Off — reports only" },
  assisted: { tone: "blue", ar: "مساعد — يقترح ويعتمد المؤسس", en: "Assisted — proposes, you approve" },
  autonomous: { tone: "lime", ar: "مستقل — ينفّذ منخفض المخاطر ضمن الحدود", en: "Autonomous — auto-runs low-risk within limits" },
};

// lightweight markdown: **bold**, "- " list items, blank lines.
function AssemMd({ text }) {
  const lines = String(text || "").split("\n");
  const renderInline = (s) => {
    const parts = String(s).split(/(\*\*[^*]+\*\*)/g).filter(Boolean);
    return parts.map((p, i) => (/^\*\*[^*]+\*\*$/.test(p) ? <b key={i}>{p.slice(2, -2)}</b> : <span key={i}>{p}</span>));
  };
  return (
    <div className="col" style={{ gap: 3 }}>
      {lines.map((ln, i) => {
        if (!ln.trim()) return <div key={i} style={{ height: 4 }} />;
        if (/^- /.test(ln)) return <div key={i} className="row" style={{ gap: 7, alignItems: "flex-start", fontSize: 13, lineHeight: 1.5 }}><span style={{ color: "var(--color-secondary)", flexShrink: 0 }}>•</span><span>{renderInline(ln.slice(2))}</span></div>;
        return <div key={i} style={{ fontSize: 13.5, lineHeight: 1.55 }}>{renderInline(ln)}</div>;
      })}
    </div>
  );
}

const CONF_TONE = { measured: "lime", heuristic: "blue", config: "neutral", not_enough_data: "orange" };
function AssemRec({ r, lang }) {
  const T = (ar, en) => (lang === "ar" ? ar : en);
  const sar = (n) => (typeof n === "number" ? window.fmtCurrency(n) : null);
  return (
    <div className="card" style={{ padding: 11, background: "var(--bg-2)" }}>
      <div className="row" style={{ gap: 8, flexWrap: "wrap", alignItems: "center" }}>
        <b style={{ fontSize: 13 }}>{typeof r.title === "object" ? (lang === "ar" ? r.title.ar : r.title.en) : r.title}</b>
        <Badge tone={r.mode === "auto" ? "lime" : "neutral"}>{r.mode === "auto" ? T("تلقائي", "AUTO") : T("يدوي", "MANUAL")}</Badge>
        <Badge tone={CONF_TONE[r.confidence] || "neutral"}>{r.confidence}</Badge>
        {r.executionPolicy === "forbidden" ? <Badge tone="red">{T("ممنوع", "forbidden")}</Badge> : r.executionPolicy === "founder_approval" ? <Badge tone="orange">{T("موافقة المؤسس", "founder approval")}</Badge> : null}
      </div>
      {r.why ? <div className="subtle" style={{ fontSize: 12.5, marginTop: 4, lineHeight: 1.5 }}>{typeof r.why === "object" ? (lang === "ar" ? r.why.ar : r.why.en) : r.why}</div> : null}
      <div className="row" style={{ gap: 10, flexWrap: "wrap", marginTop: 6, fontSize: 11.5 }}>
        {r.expectedImpact != null ? <span className="subtle">{T("الأثر", "Impact")}: {sar(r.expectedImpact) || r.expectedImpact}</span> : null}
        {r.requiredBudget != null ? <span className="subtle">{T("الميزانية", "Budget")}: {sar(r.requiredBudget) || r.requiredBudget}</span> : null}
        {r.successProbability != null ? <span className="subtle">{T("الاحتمال", "Probability")}: {r.successProbability}</span> : null}
        {r.riskLevel ? <span className="subtle">{T("المخاطرة", "Risk")}: {r.riskLevel}</span> : null}
      </div>
    </div>
  );
}

// ---- V2 Commander views ----
const fmtSar = (n) => (typeof n === "number" ? window.fmtCurrency(n) : (n == null ? "—" : n));
const SEV_TONE = { high: "red", medium: "orange", low: "neutral" };
function Stat({ label, value, tone }) {
  return <div className="card" style={{ padding: 10, flex: "1 1 130px", minWidth: 110 }}><div className="subtle" style={{ fontSize: 11 }}>{label}</div><div style={{ fontSize: 18, fontWeight: 800, color: tone ? "var(--color-" + tone + ")" : "var(--fg-1)" }}>{value}</div></div>;
}

function AssemDashboardView({ lang }) {
  const T = (ar, en) => (lang === "ar" ? ar : en);
  const [d, setD] = React.useState(null);
  React.useEffect(() => { API.assem.dashboard(lang).then(setD).catch(() => {}); }, []);
  if (!d) return <div className="subtle" style={{ fontSize: 12.5, padding: 8 }}>{T("جارٍ التحميل…", "Loading…")}</div>;
  const rev = d.revenue || {};
  return (
    <div className="col" style={{ gap: 12 }}>
      <div className="row" style={{ gap: 8, flexWrap: "wrap" }}>
        <Stat label={T("الهدف", "Target")} value={rev.targetSet ? fmtSar(rev.target) : T("غير مضبوط", "not set")} />
        <Stat label={T("الفجوة", "Gap")} value={rev.gap != null ? fmtSar(rev.gap) : "—"} />
        <Stat label={T("إيراد مؤكَّد", "Verified rev.")} value={fmtSar(rev.paymentVerified ? rev.paymentVerified.total : 0)} tone="lime" />
        <Stat label={T("منطقة الخطر", "Danger Zone")} value={d.customerSuccess ? d.customerSuccess.dangerZone : 0} tone={d.customerSuccess && d.customerSuccess.dangerZone ? "orange" : null} />
        <Stat label={T("قرارات المؤسس", "Founder actions")} value={d.founderActionsRequired || 0} />
      </div>
      <div className="row" style={{ gap: 8, flexWrap: "wrap" }}>
        <Stat label={T("التوقّع", "Forecast")} value={fmtSar(d.sales && d.sales.forecast)} />
        <Stat label={T("خطر التسرب", "Churn risk")} value={d.customerSuccess ? d.customerSuccess.churn : 0} />
        <Stat label={T("تجديدات", "Renewals")} value={d.customerSuccess ? d.customerSuccess.renewals : 0} />
        <Stat label={T("وكلاء محمّلون", "Overloaded")} value={d.agentSummary ? d.agentSummary.overloaded : 0} tone={d.agentSummary && d.agentSummary.overloaded ? "orange" : null} />
        <Stat label={T("مخاطر تنفيذية", "Exec risks")} value={(d.executiveRisks || []).length} tone={(d.executiveRisks || []).length ? "red" : null} />
      </div>
      {(d.executiveRisks || []).length ? (
        <Card><div className="col" style={{ gap: 6, padding: 4 }}><b style={{ fontSize: 13 }}>{T("أهم المخاطر", "Top risks")}</b>{d.executiveRisks.map((r, i) => <div key={i} className="row" style={{ gap: 7, fontSize: 12.5, alignItems: "center" }}><Badge tone={SEV_TONE[r.severity] || "neutral"}>{r.severity}</Badge><span>{lang === "ar" ? r.message.ar : r.message.en}</span></div>)}</div></Card>
      ) : null}
      {(d.executiveOpportunities || []).length ? (
        <Card><div className="col" style={{ gap: 6, padding: 4 }}><b style={{ fontSize: 13 }}>{T("أهم الفرص", "Top opportunities")}</b>{d.executiveOpportunities.map((o, i) => <div key={i} className="row" style={{ gap: 7, fontSize: 12.5 }}>• {typeof (o.title || o.label) === "object" ? (lang === "ar" ? (o.title || o.label).ar : (o.title || o.label).en) : (o.title || o.label || o.type)}</div>)}</div></Card>
      ) : null}
    </div>
  );
}

function AssemCommandCenterView({ lang }) {
  const T = (ar, en) => (lang === "ar" ? ar : en);
  const [cc, setCc] = React.useState(null);
  React.useEffect(() => { API.assem.commandCenter().then(setCc).catch(() => {}); }, []);
  if (!cc) return <div className="subtle" style={{ fontSize: 12.5, padding: 8 }}>{T("جارٍ التحميل…", "Loading…")}</div>;
  const ST = { overloaded: "red", underutilized: "orange", healthy: "lime" };
  if (!cc.agents.length) return <div className="card" style={{ padding: 16, textAlign: "center", color: "var(--fg-3)" }}>{lang === "ar" ? (cc.note && cc.note.ar) : (cc.note && cc.note.en)}</div>;
  return (
    <div className="col" style={{ gap: 10 }}>
      <div className="row" style={{ gap: 8, flexWrap: "wrap" }}>
        <Stat label={T("وكلاء", "Agents")} value={cc.summary.total} />
        <Stat label={T("محمّلون", "Overloaded")} value={cc.summary.overloaded} tone={cc.summary.overloaded ? "orange" : null} />
        <Stat label={T("مهام محظورة", "Blocked")} value={cc.summary.blockedTotal} tone={cc.summary.blockedTotal ? "red" : null} />
        <Stat label={T("بانتظار الموافقة", "Waiting approval")} value={cc.summary.waitingApprovalsTotal} tone={cc.summary.waitingApprovalsTotal ? "orange" : null} />
      </div>
      {cc.agents.map((a) => (
        <div key={a.agentId} className="card" style={{ padding: 12 }}>
          <div className="between" style={{ gap: 8, flexWrap: "wrap" }}>
            <div className="row" style={{ gap: 8, flexWrap: "wrap", alignItems: "center" }}><b style={{ fontSize: 13.5 }}>{a.name}</b><Badge tone={ST[a.status] || "neutral"}>{a.status}</Badge>{a.utilizationPct != null ? <span className="subtle" style={{ fontSize: 11.5 }}>{a.utilizationPct}% {T("سعة", "util")}</span> : null}</div>
            <div className="row" style={{ gap: 10, fontSize: 11.5 }}>
              <span className="subtle">{T("نجاح", "Success")}: {a.successRate != null ? a.successRate + "%" : T("بيانات غير كافية", "n/a")}</span>
              <span className="subtle">{T("إيراد", "Revenue")}: {fmtSar(a.assigned.revenue)}</span>
            </div>
          </div>
          <div className="row" style={{ gap: 12, marginTop: 6, flexWrap: "wrap", fontSize: 11.5, color: "var(--fg-3)" }}>
            <span>{T("فرص", "Open")}: {a.workload.openOpps}</span>
            <span>{T("عروض", "Proposals")}: {a.workload.proposals}</span>
            <span>{T("متابعات", "Follow-ups")}: {a.workload.followups}</span>
            <span>{T("اجتماعات", "Meetings")}: {a.workload.meetings}</span>
            {a.blockedTasks ? <span style={{ color: "var(--color-red)" }}>{T("محظورة", "Blocked")}: {a.blockedTasks}</span> : null}
            {a.waitingApprovals ? <span style={{ color: "var(--color-orange)" }}>{T("تنتظر اعتماد", "Awaiting")}: {a.waitingApprovals}</span> : null}
            <span>{T("عملاء", "Customers")}: {a.assigned.customers}</span>
            <span>{T("حملات", "Campaigns")}: {a.assigned.campaigns}</span>
          </div>
        </div>
      ))}
    </div>
  );
}

const WAR_ROOMS_UI = [["revenue", { ar: "الإيراد", en: "Revenue" }], ["sales", { ar: "المبيعات", en: "Sales" }], ["customer_success", { ar: "نجاح العملاء", en: "Customer Success" }], ["competitor", { ar: "المنافسون", en: "Competitors" }]];
function AssemWarRoomsView({ lang }) {
  const T = (ar, en) => (lang === "ar" ? ar : en);
  const [room, setRoom] = React.useState("revenue");
  const [data, setData] = React.useState(null);
  React.useEffect(() => { setData(null); API.assem.warRoom(room, lang).then(setData).catch(() => {}); }, [room]);
  const L = (x) => (x && typeof x === "object" ? (lang === "ar" ? x.ar : x.en) : x);
  const Row = ({ k, v }) => v == null || v === "" ? null : <div className="row" style={{ gap: 8, fontSize: 12.5, padding: "4px 0", borderBottom: "1px solid var(--border-1)" }}><span className="subtle" style={{ minWidth: 150 }}>{k}</span><span style={{ fontWeight: 600 }}>{typeof v === "object" ? (v.name || L(v.label) || L(v) || JSON.stringify(v).slice(0, 60)) : String(v)}</span></div>;
  return (
    <div className="col" style={{ gap: 10 }}>
      <div className="chipscroll" style={{ gap: 6 }}>{WAR_ROOMS_UI.map(([k, lab]) => <button key={k} className={"btn btn--sm " + (room === k ? "btn--dark" : "btn--subtle")} style={{ flexShrink: 0 }} onClick={() => setRoom(k)}>{L(lab)}</button>)}</div>
      {!data ? <div className="subtle" style={{ fontSize: 12.5, padding: 8 }}>{T("جارٍ التحميل…", "Loading…")}</div> : (
        <Card><div className="col" style={{ gap: 2, padding: 6 }}>
          {room === "revenue" && <>
            <Row k={T("سبب التأخّر عن الهدف", "Why missing target")} v={L(data.missingTargetReason)} />
            {data.paths ? Object.entries({ [T("الأسرع", "Fastest")]: data.paths.fastest, [T("الأأمن", "Safest")]: data.paths.safest, [T("الأعلى احتمالاً", "Highest prob.")]: data.paths.highestProbability, [T("الأعلى هامشاً", "Highest margin")]: data.paths.highestMargin, [T("الأقل جهداً", "Lowest effort")]: data.paths.lowestEffort }).map(([k, v]) => <Row key={k} k={k} v={L(v)} />) : null}
            <Row k={T("أفضل قطاع", "Best vertical")} v={data.bestVertical} />
            <Row k={T("ما يجب أن يتوسّع", "Scale now")} v={L(data.scaleImmediately)} />
            <Row k={T("أكبر خطر", "Biggest risk")} v={L(data.biggestRisk)} />
          </>}
          {room === "sales" && <>
            <Row k={T("التوقّع", "Forecast")} v={fmtSar(data.pipeline && data.pipeline.forecast)} />
            <Row k={T("معدّل التحويل", "Conversion")} v={data.conversionRate != null ? data.conversionRate + "%" : null} />
            <Row k={T("صفقات مكسوبة", "Won deals")} v={data.wonDeals} />
            <Row k={T("أعلى وكيل إغلاقاً", "Top closer")} v={data.highestClosingAgent} />
            <Row k={T("أدنى وكيل إغلاقاً", "Lowest closer")} v={data.lowestClosingAgent} />
            <Row k={T("أفضل قطاع", "Best vertical")} v={data.bestVertical} />
          </>}
          {room === "customer_success" && <>
            <Row k={T("خطر التسرب", "Churn risk")} v={data.churnRisk} />
            <Row k={T("منطقة الخطر", "Danger Zone")} v={data.dangerZone} />
            <Row k={T("تجديدات", "Renewals")} v={data.renewals} />
            <Row k={T("فرص توسّع", "Expansion")} v={data.expansionOpportunities} />
          </>}
          {room === "competitor" && <>
            <Row k={T("من يفوز", "Who's winning")} v={data.winning} />
            <Row k={T("راقب", "Monitor")} v={data.monitor} />
            {(data.topThreats || []).map((t, i) => <Row key={i} k={T("تهديد", "Threat")} v={t.name || t} />)}
          </>}
          {data.note ? <div className="subtle" style={{ fontSize: 12, marginTop: 6 }}>{L(data.note)}</div> : null}
        </div></Card>
      )}
    </div>
  );
}

function AssemAlertsView({ lang }) {
  const T = (ar, en) => (lang === "ar" ? ar : en);
  const [a, setA] = React.useState(null);
  const [si, setSi] = React.useState(null);
  React.useEffect(() => { API.assem.alerts(lang).then(setA).catch(() => {}); API.assem.selfImprovement(lang).then(setSi).catch(() => {}); }, []);
  return (
    <div className="col" style={{ gap: 12 }}>
      <Card><div className="col" style={{ gap: 6, padding: 4 }}>
        <b style={{ fontSize: 13 }}>{T("التنبيهات التنفيذية", "Executive alerts")} {a ? <span className="subtle">({a.count})</span> : null}</b>
        {!a ? <span className="subtle" style={{ fontSize: 12.5 }}>{T("جارٍ التحميل…", "Loading…")}</span> : (a.alerts.length ? a.alerts.map((x, i) => <div key={i} className="row" style={{ gap: 7, fontSize: 12.5, alignItems: "center" }}><Badge tone={SEV_TONE[x.severity] || "neutral"}>{x.severity}</Badge><span>{lang === "ar" ? x.message.ar : x.message.en}</span></div>) : <span className="subtle" style={{ fontSize: 12.5 }}>{lang === "ar" ? (a.note && a.note.ar) : (a.note && a.note.en)}</span>)}
      </div></Card>
      <Card><div className="col" style={{ gap: 6, padding: 4 }}>
        <b style={{ fontSize: 13 }}>{T("توصيات التحسين الذاتي", "Self-improvement recommendations")}</b>
        <div className="subtle" style={{ fontSize: 11, color: "var(--color-orange)" }}>{T("توصيات فقط — عاصم لا يعدّل الموجّهات أو يعيد التدريب أو يغيّر سلوك الإنتاج تلقائياً.", "Recommendations only — Assem never auto-modifies prompts, retrains, or changes production behavior.")}</div>
        {!si ? <span className="subtle" style={{ fontSize: 12.5 }}>{T("جارٍ التحميل…", "Loading…")}</span> : (si.recommendations.length ? si.recommendations.map((r, j) => <AssemRec key={j} r={r} lang={lang} />) : <span className="subtle" style={{ fontSize: 12.5 }}>{lang === "ar" ? (si.note && si.note.ar) : (si.note && si.note.en)}</span>)}
      </div></Card>
    </div>
  );
}

// ASSEM V3 — CTO/COO view: system health score + pillars + Claude-Code fix report + revenue↔CTO
// correlation + integration audit. Every number is real telemetry or labelled not_measured/not_available
// (truth over optimism). Read-only — Assem analyzes/recommends; it never deploys or applies a fix.
const CTO_BAND_TONE = { healthy: "var(--color-success)", fair: "var(--color-secondary)", degraded: "var(--color-warning, #B45309)", critical: "var(--color-danger)", unknown: "var(--fg-3)" };
const CTO_PILLAR_TONE = (p) => !p.measured ? "var(--fg-3)" : p.score >= 80 ? "var(--color-success)" : p.score >= 50 ? "var(--color-warning, #B45309)" : "var(--color-danger)";
function AssemCtoView({ lang }) {
  const T = (ar, en) => (lang === "ar" ? ar : en);
  const [h, setH] = React.useState(null);
  const [s, setS] = React.useState(null);
  const [fix, setFix] = React.useState(null);
  const [corr, setCorr] = React.useState(null);
  const [dr, setDr] = React.useState(null);     // V4 deployment readiness
  const [bl, setBl] = React.useState(null);     // V4 engineering backlog
  React.useEffect(() => {
    API.assem.systemHealth().then(setH).catch(() => {});
    API.assem.ctoStatus().then(setS).catch(() => {});
    API.assem.claudeFixReport().then(setFix).catch(() => {});
    API.assem.revenueCto().then(setCorr).catch(() => {});
    API.assem.deploymentReadiness().then(setDr).catch(() => {});
    API.assem.engBacklog().then(setBl).catch(() => {});
  }, []);
  const DR_TONE = { GO: "var(--color-success)", GO_ON_CREDENTIALS: "var(--color-warning, #B45309)", NO_GO: "var(--color-danger)" };
  return (
    <div className="col" style={{ gap: 12 }}>
      {/* System Health Score */}
      <Card><div className="col" style={{ gap: 8, padding: 4 }}>
        <div className="between">
          <b style={{ fontSize: 13 }}>{T("صحة النظام", "System health")}</b>
          {h ? <span style={{ fontSize: 22, fontWeight: 800, color: CTO_BAND_TONE[h.band] || "var(--fg-2)" }}>{h.score == null ? "—" : h.score}<span className="subtle" style={{ fontSize: 12, fontWeight: 600 }}> / 100 · {h.band}</span></span> : <span className="subtle" style={{ fontSize: 12 }}>{T("جارٍ التحميل…", "Loading…")}</span>}
        </div>
        {h ? <div className="subtle" style={{ fontSize: 11.5 }}>{h.coverage} · {lang === "ar" ? (h.explanation && h.explanation.ar) : (h.explanation && h.explanation.en)}</div> : null}
        {s ? <div className="row wrap" style={{ gap: 6, marginTop: 4 }}>
          {s.pillars.map((p) => <span key={p.key} className="row" style={{ gap: 5, fontSize: 11, padding: "3px 8px", borderRadius: 7, background: "var(--bg-2)", border: "1px solid var(--border-1)" }}><span className="sdot" style={{ background: CTO_PILLAR_TONE(p) }} />{lang === "ar" ? p.label.ar : p.label.en}: <b>{p.measured ? p.score : T("غير مقيس", "n/a")}</b></span>)}
        </div> : null}
      </div></Card>
      {/* V4 — Deployment readiness GO/NO-GO + engineering backlog */}
      {dr ? <Card><div className="col" style={{ gap: 8, padding: 4 }}>
        <div className="between">
          <b style={{ fontSize: 13 }}>{T("جاهزية النشر", "Deployment readiness")}</b>
          <span style={{ fontSize: 14, fontWeight: 800, color: DR_TONE[dr.verdict] || "var(--fg-2)" }}>{dr.verdict.replace(/_/g, " ")}</span>
        </div>
        <div className="subtle" style={{ fontSize: 11.5 }}>{lang === "ar" ? (dr.reasoning && dr.reasoning.ar) : (dr.reasoning && dr.reasoning.en)}</div>
        <div className="row wrap" style={{ gap: 5, marginTop: 2 }}>
          {dr.gates.map((g) => <span key={g.gate} className="row" style={{ gap: 4, fontSize: 10.5, padding: "2px 7px", borderRadius: 6, background: "var(--bg-2)", border: "1px solid var(--border-1)" }} title={g.reason}><span className="sdot" style={{ background: g.status === "pass" ? "var(--color-success)" : g.status === "fail" ? "var(--color-danger)" : g.status === "warn" ? "var(--color-warning, #B45309)" : "var(--fg-3)" }} />{g.gate.replace(/_/g, " ")}: {g.status}</span>)}
        </div>
      </div></Card> : null}
      {bl && bl.items && bl.items.length ? <Card><div className="col" style={{ gap: 6, padding: 4 }}>
        <b style={{ fontSize: 13 }}>{T("سجل العمل الهندسي (بالأولوية)", "Engineering backlog (priority-ranked)")} <span className="subtle">({bl.count})</span></b>
        {bl.items.slice(0, 6).map((it) => (
          <div key={it.id} className="row between" style={{ gap: 8, fontSize: 12 }}>
            <span className="row" style={{ gap: 6, minWidth: 0 }}><Badge tone={it.severity === "critical" ? "danger" : it.severity === "high" ? "warning" : "neutral"}>{it.severity}</Badge><span style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{it.title}</span></span>
            <span className="subtle" style={{ fontSize: 11, flexShrink: 0 }}>{it.category.replace(/_/g, " ")} · {T("أولوية", "P")} {it.priorityScore}</span>
          </div>
        ))}
      </div></Card> : null}

      {/* Revenue ↔ CTO correlation */}
      {corr ? <Card><div className="col" style={{ gap: 6, padding: 4 }}>
        <b style={{ fontSize: 13 }}>{T("ما الذي يعيق الإيراد تقنياً؟", "What's blocking revenue (technically)?")}</b>
        {[["blockingRevenue", T("يعيق الإيراد", "Blocking revenue")], ["reducingConversion", T("يخفض التحويل", "Reducing conversion")], ["causingAgentFailures", T("يسبب فشل الوكلاء", "Agent failures")]].map(([k, label]) => (
          <div key={k} className="row" style={{ gap: 7, fontSize: 12, alignItems: "baseline" }}>
            <span style={{ minWidth: 120, fontWeight: 600, color: "var(--fg-3)" }}>{label}</span>
            <span>{corr[k] && corr[k].issue ? <><Badge tone={corr[k].severity === "critical" ? "danger" : corr[k].severity === "high" ? "warning" : "neutral"}>{corr[k].issue}</Badge> — {corr[k].why}</> : <span className="subtle">{corr[k] && corr[k].why}</span>}</span>
          </div>
        ))}
        {corr.highestValueActivation && corr.highestValueActivation.integration ? <div className="row" style={{ gap: 7, fontSize: 12, marginTop: 2 }}><Icon name="sparkles" size={13} style={{ color: "var(--color-secondary)" }} /><b>{T("أعلى تفعيل قيمةً:", "Highest-value activation:")}</b> {corr.highestValueActivation.integration} — {corr.highestValueActivation.why}</div> : null}
      </div></Card> : null}
      {/* Claude-Code Fix Report */}
      <Card><div className="col" style={{ gap: 8, padding: 4 }}>
        <b style={{ fontSize: 13 }}>{T("تقرير إصلاح Claude Code", "Claude Code fix report")} {fix ? <span className="subtle">({fix.count})</span> : null}</b>
        <div className="subtle" style={{ fontSize: 11, color: "var(--color-orange)" }}>{T("توصية فقط — عاصم يحلّل ويوصي، ولا ينشر أو يطبّق إصلاحاً أو يبدّل مفتاحاً.", "Recommendation only — Assem analyzes + recommends; it never deploys, applies a fix, or rotates a key.")}</div>
        {!fix ? <span className="subtle" style={{ fontSize: 12.5 }}>{T("جارٍ التحميل…", "Loading…")}</span> : (fix.reports.length ? fix.reports.map((r) => (
          <div key={r.id} style={{ border: "1px solid var(--border-1)", borderRadius: 9, padding: "8px 10px" }}>
            <div className="between"><span className="row" style={{ gap: 6, fontWeight: 700, fontSize: 12.5 }}><Badge tone={r.severity === "critical" ? "danger" : r.severity === "high" ? "warning" : "neutral"}>{r.severity}</Badge>{r.component}</span><span className="subtle" style={{ fontSize: 11 }}>{T("خطر النشر:", "Deploy risk:")} {r.deploymentRisk} · ETA {r.eta}</span></div>
            <div style={{ fontSize: 12, marginTop: 4 }}><b>{T("السبب الجذري:", "Root cause:")}</b> {r.rootCause}</div>
            <div style={{ fontSize: 12, marginTop: 2 }}><b>{T("الإصلاح:", "Fix:")}</b> {r.fix}</div>
            <div className="subtle" style={{ fontSize: 11, marginTop: 3 }}>{T("ملفات:", "Files:")} {r.files.join(" · ")}</div>
          </div>
        )) : <span className="subtle" style={{ fontSize: 12.5 }}>{lang === "ar" ? (fix.note && fix.note.ar) : (fix.note && fix.note.en)}</span>)}
      </div></Card>
    </div>
  );
}

const ASSEM_VIEWS = [["chat", { ar: "المحادثة", en: "Chat" }], ["owner", { ar: "لوحة المالك", en: "Owner" }], ["companyos", { ar: "نظام الشركة", en: "Company OS" }], ["discounts", { ar: "الخصومات", en: "Discounts" }], ["dashboard", { ar: "اللوحة", en: "Dashboard" }], ["command", { ar: "قيادة الوكلاء", en: "Command Center" }], ["cto", { ar: "الإدارة التقنية", en: "CTO" }], ["warrooms", { ar: "غرف الحرب", en: "War Rooms" }], ["alerts", { ar: "التنبيهات", en: "Alerts" }]];

// PHASE 20 — THE OWNER DASHBOARD. The owner's one screen: the 11 money metrics (real-or-NED + source), retention
// KPIs, and the no-fake-commerce audit. One fetch each; string-safe L(); display-only — nothing here sends or acts.
function OwnerDashboardView({ lang }) {
  const T = (ar, en) => (lang === "ar" ? ar : en);
  const L = (o) => (o == null ? "" : typeof o === "string" ? o : (lang === "ar" ? (o.ar || o.en) : (o.en || o.ar)) || "");
  const [d, setD] = React.useState(null);
  const [audit, setAudit] = React.useState(null);
  const [rcc, setRcc] = React.useState(null);   // Phase 20 v2 — the 8-question revenue command center
  React.useEffect(() => {
    API.assem.ownerDashboard().then((x) => setD(x || { error: true })).catch(() => setD({ error: true }));
    API.assem.noFakeCommerceAudit().then(setAudit).catch(() => {});
    API.assem.revenueCommandCenter().then(setRcc).catch(() => {});
  }, []);
  if (!d) return <Card><div className="skel" style={{ height: 200, borderRadius: 12 }} /></Card>;
  if (d.error || d.ok === false) return <div className="subtle" style={{ fontSize: 13 }}>{T("تعذّر تحميل لوحة المالك.", "Couldn't load the owner dashboard.")}</div>;
  const money = (n) => (n == null ? T("لا بيانات", "—") : (window.fmtCurrency ? window.fmtCurrency(n) : String(n)));
  const m = (mt) => (mt && mt.status === "active" ? mt.value : null);
  // the 11 metrics → cards (value or NED), each carrying its real source.
  const cards = [
    { k: T("إيراد اليوم", "Revenue today"), v: money(m(d.revenueToday)), tone: "green" },
    { k: T("إيراد الشهر", "Revenue this month"), v: money(m(d.revenueThisMonth)), tone: "green" },
    { k: T("قيمة خط الأنابيب", "Pipeline value"), v: money(m(d.pipelineValue)), tone: "info" },
    { k: T("عروض مفتوحة", "Open proposals"), v: m(d.openProposals) ?? T("لا بيانات", "—"), tone: "neutral" },
    { k: T("مدفوعات معلّقة", "Pending payments"), v: d.pendingPayments && d.pendingPayments.value ? `${d.pendingPayments.value.count} · ${money(d.pendingPayments.value.value)}` : T("لا بيانات", "—"), tone: "orange" },
    { k: T("اجتماعات قادمة", "Upcoming meetings"), v: m(d.upcomingMeetings) ?? T("لا بيانات", "—"), tone: "info" },
    { k: T("كبار العملاء", "VIP customers"), v: m(d.vipCustomers) ?? T("لا بيانات", "—"), tone: "lime" },
    { k: T("إيراد الإحالات", "Referral revenue"), v: T("لا بيانات", "NED"), tone: "dark", note: L(d.referralRevenue && d.referralRevenue.note) },
    { k: T("صحّة العملاء", "Customer health"), v: m(d.customerHealth) != null ? `${m(d.customerHealth)}/100` : T("لا بيانات", "—"), tone: "green" },
  ];
  return (
    <div className="col" style={{ gap: 12 }}>
      <Card><div className="col" style={{ gap: 4, padding: 10 }}>
        <strong style={{ fontSize: 14 }}>{T("لوحة المالك", "Owner dashboard")}</strong>
        <span className="subtle" style={{ fontSize: 11.5 }}>{T("كل رقم حقيقي أو «لا بيانات» مع مصدره — لا مال ملفّق.", "Every figure is real or NOT_ENOUGH_DATA with its source — no fabricated money.")}</span>
      </div></Card>

      <div className="row wrap" style={{ gap: 8 }}>
        {cards.map((c, i) => (
          <Card key={i} style={{ flex: "1 1 150px", minWidth: 140 }}><div className="col" style={{ gap: 3, padding: 10 }}>
            <div className="subtle" style={{ fontSize: 11 }}>{c.k}</div>
            <div style={{ fontSize: 18, fontWeight: 800, color: c.tone === "green" ? "var(--color-secondary)" : "var(--text-1)" }}>{c.v}</div>
            {c.note ? <div className="subtle" style={{ fontSize: 9.5 }}>{c.note}</div> : null}
          </div></Card>
        ))}
      </div>

      {/* campaign ROI + top opportunities */}
      <div className="row wrap" style={{ gap: 8 }}>
        <Card style={{ flex: "1 1 280px" }}><div className="col" style={{ gap: 6, padding: 10 }}>
          <b style={{ fontSize: 13 }}>{T("عائد الحملات", "Campaign ROI")}</b>
          {d.campaignROI && d.campaignROI.status === "active" ? (d.campaignROI.value || []).map((c, i) => (
            <div key={i} className="between" style={{ fontSize: 12 }}><span>{c.name}</span><b>{money(c.revenue)}</b></div>
          )) : <span className="subtle" style={{ fontSize: 12 }}>{T("لا إيراد محقَّق منسوب لحملة بعد.", "No verified campaign revenue yet.")}</span>}
        </div></Card>
        <Card style={{ flex: "1 1 280px" }}><div className="col" style={{ gap: 6, padding: 10 }}>
          <b style={{ fontSize: 13 }}>{T("أكبر الفرص", "Top opportunities")}</b>
          {d.topOpportunities && d.topOpportunities.status === "active" ? (d.topOpportunities.value || []).map((o, i) => (
            <div key={i} className="between" style={{ fontSize: 12 }}><span className="subtle">{o.contactId} · {o.stage || "—"}</span><b>{money(o.value)}</b></div>
          )) : <span className="subtle" style={{ fontSize: 12 }}>{T("لا فرص مفتوحة.", "No open opportunities.")}</span>}
        </div></Card>
      </div>

      {/* retention KPIs */}
      {d.retention ? (
        <Card><div className="col" style={{ gap: 6, padding: 10 }}>
          <b style={{ fontSize: 13 }}>{T("مؤشّرات الاحتفاظ", "Retention")}</b>
          <div className="row wrap" style={{ gap: 6 }}>
            {d.retention.repeatPurchaseRate != null ? <Badge tone="info">{T("شراء متكرّر", "Repeat purchase")}: {d.retention.repeatPurchaseRate}%</Badge> : null}
            {d.retention.retentionRate != null ? <Badge tone="green">{T("الاحتفاظ", "Retention")}: {d.retention.retentionRate}%</Badge> : null}
            {d.retention.churnRiskRate != null ? <Badge tone="orange">{T("خطر التسرّب", "Churn risk")}: {d.retention.churnRiskRate}%</Badge> : null}
            {d.retention.avgCustomerValue != null ? <Badge tone="neutral">{T("متوسّط قيمة العميل", "Avg value")}: {money(d.retention.avgCustomerValue)}</Badge> : null}
          </div>
        </div></Card>
      ) : null}

      {/* revenue command center — the 8 money questions (real-or-NED) */}
      {rcc && rcc.ok ? (() => {
        const q = rcc.questions; const val = (m) => (m && m.status === "active" ? m.value : null);
        const moneyFmt = (n) => (n == null ? T("لا بيانات", "—") : (window.fmtCurrency ? window.fmtCurrency(n) : String(n)));
        const rows = [
          [T("المال المُولَّد", "Money generated"), moneyFmt(val(q.moneyGenerated))],
          [T("المال المفقود", "Money lost"), val(q.moneyLost) ? moneyFmt(q.moneyLost.value.knownLostValue) : T("لا بيانات", "—")],
          [T("أفضل حملة", "Best campaign"), val(q.bestCampaign) ? q.bestCampaign.value.name : T("لا بيانات", "—")],
          [T("أسوأ حملة", "Worst campaign"), val(q.worstCampaign) ? q.worstCampaign.value.name : T("لا بيانات", "—")],
          [T("أسرع نمو", "Fastest growth"), val(q.fastestGrowth) ? String(q.fastestGrowth.value) : T("لا بيانات", "NED")],
          [T("أعلى عائد", "Highest ROI"), val(q.highestROI) ? String(q.highestROI.value) : T("لا بيانات", "NED")],
          [T("أعلى وكيل تحويلاً", "Top converting agent"), val(q.highestConvertingAgent) ? `${q.highestConvertingAgent.value.name} · ${q.highestConvertingAgent.value.winRate}%` : T("لا بيانات", "—")],
          [T("أدنى وكيل تحويلاً", "Lowest converting agent"), val(q.lowestConvertingAgent) ? `${q.lowestConvertingAgent.value.name} · ${q.lowestConvertingAgent.value.winRate}%` : T("لا بيانات", "—")],
        ];
        return (
          <Card><div className="col" style={{ gap: 6, padding: 10 }}>
            <b style={{ fontSize: 13 }}>{T("مركز قيادة الإيراد", "Revenue command center")}</b>
            <div className="row wrap" style={{ gap: 8 }}>
              {rows.map(([k, v], i) => (
                <div key={i} style={{ flex: "1 1 160px", minWidth: 150, padding: "6px 8px", borderRadius: 8, background: "var(--bg-2)", border: "1px solid var(--border-1)" }}>
                  <div className="subtle" style={{ fontSize: 10.5 }}>{k}</div>
                  <div style={{ fontSize: 13, fontWeight: 700 }}>{v}</div>
                </div>
              ))}
            </div>
            <span className="subtle" style={{ fontSize: 10, color: "var(--color-orange)" }}>{T("ROI/النمو «لا بيانات» حتى تُقاس التكلفة/التاريخ — لا رقم ملفّق.", "ROI/growth stay NED until cost/history are measured — never a fabricated number.")}</span>
          </div></Card>
        );
      })() : null}

      {/* no-fake-commerce audit */}
      {audit && audit.ok ? (
        <Card><div className="col" style={{ gap: 6, padding: 10 }}>
          <div className="between"><b style={{ fontSize: 13 }}>{T("تدقيق بلا تزييف", "No-fake-commerce audit")}</b><Badge tone={audit.allPass ? "green" : "danger"}>{audit.passed}/{audit.total}</Badge></div>
          <div className="col" style={{ gap: 2 }}>
            {(audit.checks || []).map((c, i) => <div key={i} className="row" style={{ gap: 6, fontSize: 11 }}><span>{c.pass ? "✓" : "✗"}</span><span className="subtle">{c.name.replace(/_/g, " ")}</span></div>)}
          </div>
        </div></Card>
      ) : null}

      <div className="subtle" style={{ fontSize: 10.5, color: "var(--color-orange)" }}>{T("عرض فقط — لا يُرسَل أو يُنفَّذ شيء من هنا؛ الدفع مؤكَّد عبر الويبهوك فقط.", "Display-only — nothing here sends or acts; payment is webhook-verified only.")}</div>
    </div>
  );
}

// PHASE 21 — THE COMPANY OPERATING SYSTEM. Run the whole company from one screen: business health, the approval
// center (every pending founder decision, ranked), company goals vs target, the executive calendar, recommendation
// impact, and the no-fake-operations audit. One fetch each; string-safe L(); display-only — nothing auto-executes.
// REAL CUSTOMER PILOT — PART 9/10. ONE operational pilot screen (every tile real-or-NED) + the exit decision
// (CONTINUE vs IMPROVE_BEFORE_SCALE, gated on verified paying customers). Pure reuse of the pilotSnapshot /
// pilotExitDecision composers; no new metric. Reachable from the ASSEM tab bar (AssemSupreme) and Company OS.
function PilotDashboardView({ lang }) {
  const T = (ar, en) => (lang === "ar" ? ar : en);
  const [ps, setPs] = React.useState(null);
  const [ped, setPed] = React.useState(null);
  React.useEffect(() => {
    API.assem.pilotSnapshot().then(setPs).catch(() => {});
    API.assem.pilotExitDecision().then(setPed).catch(() => {});
  }, []);
  const tile = (label, t) => { const ned = !t || t.status === "not_enough_data"; const v = t && (t.value != null ? (typeof t.value === "object" ? (t.value.count != null ? t.value.count : "") : t.value) : (t.count != null ? t.count : null)); return (<Card style={{ flex: "1 1 130px" }}><div className="col" style={{ gap: 2, padding: 10, alignItems: "center" }}><div className="subtle" style={{ fontSize: 11 }}>{label}</div><div style={{ fontSize: 20, fontWeight: 800 }}>{ned ? <span className="subtle" style={{ fontSize: 13 }}>{T("لا بيانات", "NED")}</span> : (v == null ? "—" : v)}</div></div></Card>); };
  if (!ps || !ps.ok) return (<Card><div className="col" style={{ gap: 4, padding: 10 }}><b style={{ fontSize: 13 }}>{T("لوحة الطيار", "Pilot dashboard")}</b><span className="subtle" style={{ fontSize: 11.5 }}>{T("جارِ التحميل…", "Loading…")}</span></div></Card>);
  return (
    <Card><div className="col" style={{ gap: 8, padding: 10 }}>
      <div className="between">
        <b style={{ fontSize: 13 }}>{T("لوحة الطيار", "Pilot dashboard")}</b>
        <Badge tone={ps.pilotMode && ps.pilotMode.active ? "green" : "neutral"}>{ps.pilotMode && ps.pilotMode.active ? T("الطيار مُفعّل", "Pilot active") : T("الطيار غير مفعّل", "Pilot off")}</Badge>
      </div>
      <div className="row wrap" style={{ gap: 8 }}>
        {tile(T("العملاء", "Leads"), ps.leads)}
        {tile(T("الاجتماعات", "Meetings"), ps.meetings)}
        {tile(T("العروض", "Proposals"), ps.proposals)}
        {tile(T("المدفوعات", "Payments"), ps.payments)}
        {tile(T("الإيراد", "Revenue"), ps.revenue)}
        {tile(T("صفقات خاسرة", "Lost deals"), ps.lostDeals)}
        {tile(T("إخفاقات الذاكرة", "Memory failures"), ps.memoryFailures && { value: ps.memoryFailures.contextFailures, status: ps.memoryFailures.status })}
      </div>
      <div className="between" style={{ fontSize: 11.5 }}>
        <span className="subtle">{T("رضا العملاء", "Customer feedback")}</span>
        <span className="subtle">{T("لا بيانات — لا مقياس رضا (لا رقم ملفّق)", "NOT_ENOUGH_DATA — no CSAT instrument (never fabricated)")}</span>
      </div>
      {ped && ped.ok ? (
        ped.status === "not_enough_data" ? (
          <div style={{ fontSize: 11.5, borderTop: "1px solid var(--border-1)", paddingTop: 6 }} className="subtle">
            {T("قرار الخروج", "Exit decision")}: <b>{T("لا بيانات كافية", "NOT_ENOUGH_DATA")}</b> — {T(`${ped.realCustomers}/${ped.threshold} عميل دافع مؤكّد`, `${ped.realCustomers}/${ped.threshold} verified paying customers`)}
          </div>
        ) : (
          <div className="row" style={{ fontSize: 12, borderTop: "1px solid var(--border-1)", paddingTop: 6, gap: 8, alignItems: "center" }}>
            <span>{T("قرار الخروج", "Exit decision")}:</span>
            <Badge tone={ped.verdict === "CONTINUE" ? "green" : "orange"}>{ped.verdict === "CONTINUE" ? T("استمرار", "CONTINUE") : T("حسِّن قبل التوسّع", "IMPROVE BEFORE SCALE")}</Badge>
            <span className="subtle">{ped.realCustomers} {T("عميل مؤكّد", "verified customers")}</span>
          </div>
        )
      ) : null}
      <span className="subtle" style={{ fontSize: 10, color: "var(--color-orange)" }}>{T("كل بطاقة حقيقية أو «لا بيانات»؛ قرار الخروج يُحسب من العملاء الدافعين المؤكّدين فقط.", "Every tile is real-or-NED; the exit verdict counts only webhook-verified paying customers.")}</span>
    </div></Card>
  );
}

// PILOT FEEDBACK CENTER (read-only) — the ONE place that learns from real pilot customers. Founder daily digest +
// objections / feature requests / competitors / knowledge gaps / lost-deal analysis + the founder-approval learning
// queue (nothing auto-applied). Every section is real-or-NED from its existing source; nothing is fabricated.
function PilotFeedbackView({ lang }) {
  const T = (ar, en) => (lang === "ar" ? ar : en);
  const [center, setCenter] = React.useState(null);
  const [daily, setDaily] = React.useState(null);
  const [dash, setDash] = React.useState(null);
  const [queue, setQueue] = React.useState(null);
  const [loaded, setLoaded] = React.useState(false);
  React.useEffect(() => {
    Promise.all([
      API.assem.pilotFeedbackCenter().then(setCenter).catch(() => {}),
      API.assem.pilotFounderDaily().then(setDaily).catch(() => {}),
      API.assem.pilotDashboard().then(setDash).catch(() => {}),
      API.assem.pilotLearningQueue().then(setQueue).catch(() => {}),
    ]).then(() => setLoaded(true)).catch(() => setLoaded(true));
  }, []);
  const lbl = (x) => (x && typeof x === "object" ? T(x.ar, x.en) : x);
  const Section = ({ title, active, empty, children }) => (
    <Card><div className="col" style={{ gap: 6, padding: 10 }}>
      <b style={{ fontSize: 12.5 }}>{title}</b>
      {active ? children : <span className="subtle" style={{ fontSize: 11 }}>{empty || T("لا بيانات بعد — لا اختلاق.", "Not enough data yet — never fabricated.")}</span>}
    </div></Card>
  );
  const Chip = ({ children, tone }) => (<span style={{ fontSize: 11, padding: "2px 8px", borderRadius: 8, border: "1px solid var(--border-1)", background: tone === "warn" ? "var(--color-orange-tint, #fff4e6)" : "var(--bg-2)", whiteSpace: "nowrap" }}>{children}</span>);
  if (!loaded) return (<Card><div className="col" style={{ gap: 4, padding: 10 }}><b style={{ fontSize: 13 }}>{T("مركز ملاحظات الطيار", "Pilot Feedback Center")}</b><span className="subtle" style={{ fontSize: 11.5 }}>{T("جارِ التحميل…", "Loading…")}</span></div></Card>);
  const c = center || {};
  const metric = (label, m) => { const ned = !m || m.status === "not_enough_data" || m.value == null; return (<Card style={{ flex: "1 1 120px" }}><div className="col" style={{ gap: 2, padding: 9, alignItems: "center" }}><div className="subtle" style={{ fontSize: 10.5 }}>{label}</div><div style={{ fontSize: 17, fontWeight: 800 }}>{ned ? <span className="subtle" style={{ fontSize: 12 }}>{T("لا بيانات", "NED")}</span> : (typeof m.value === "number" ? m.value : m.value)}</div></div></Card>); };
  return (
    <div className="col" style={{ gap: 10 }}>
      <div className="between">
        <b style={{ fontSize: 13 }}>{T("مركز ملاحظات الطيار", "Pilot Feedback Center")}</b>
        <Badge tone={c.status === "active" ? "green" : "neutral"}>{c.status === "active" ? T(`${c.activeSections}/6 أقسام نشطة`, `${c.activeSections}/6 sections active`) : T("لا بيانات كافية", "Not enough data")}</Badge>
      </div>

      {/* PART8 — Founder daily digest (the headline) */}
      <Section title={T("مراجعة المؤسس الصباحية (أهم 10)", "Founder daily review (top 10)")} active={daily && daily.status === "active"} empty={T("لا ملاحظات طيار بعد.", "No pilot feedback yet.")}>
        <div className="col" style={{ gap: 5 }}>
          {(daily && daily.insights || []).map((i, k) => (
            <div key={k} className="row" style={{ gap: 7, alignItems: "center", fontSize: 11.5 }}>
              <Chip>{i.category}</Chip><span>{lbl(i.text)}</span>
            </div>
          ))}
        </div>
      </Section>

      {/* PART7 — ranked metrics */}
      <div className="row wrap" style={{ gap: 8 }}>
        {metric(T("معدّل الفوز", "Win rate"), dash && dash.winRate && { value: dash.winRate.value != null ? dash.winRate.value + "%" : null, status: dash.winRate.status })}
        {metric(T("متوسط الصفقة", "Avg deal"), dash && dash.avgDealSize)}
        {metric(T("دورة البيع (يوم)", "Sales cycle (d)"), dash && dash.avgSalesCycleDays)}
        {metric(T("أفضل وكيل", "Best agent"), dash && dash.mostSuccessfulAgent && { value: dash.mostSuccessfulAgent.name || dash.mostSuccessfulAgent.agentId || null, status: dash.mostSuccessfulAgent.status })}
      </div>

      {/* PART2 — objections */}
      <Section title={T("الاعتراضات (تصنيف ثابت)", "Objections (fixed taxonomy)")} active={c.objections && c.objections.status === "active"}>
        <div className="row wrap" style={{ gap: 6 }}>
          {((c.objections && c.objections.taxonomy) || []).slice(0, 8).map((o, k) => (<Chip key={k}>{lbl(o.label)} · {o.count}</Chip>))}
          {c.objections && c.objections.unknownCount ? <Chip tone="warn">{T(`غير معروف: ${c.objections.unknownCount} (بانتظار موافقتك)`, `unknown: ${c.objections.unknownCount} (needs approval)`)}</Chip> : null}
        </div>
      </Section>

      {/* PART4 — feature requests */}
      <Section title={T("طلبات الميزات (عملاء حقيقيون)", "Feature requests (real customers)")} active={c.featureRequests && c.featureRequests.status === "active"}>
        <div className="col" style={{ gap: 4 }}>
          {((c.featureRequests && c.featureRequests.requests) || []).slice(0, 6).map((r, k) => (
            <div key={k} className="row" style={{ gap: 7, alignItems: "center", fontSize: 11.5 }}><Chip>{r.customerCount} {T("عميل", "cust.")}</Chip><span>{r.title}</span><span className="subtle">· {r.priority}</span></div>
          ))}
        </div>
      </Section>

      {/* PART6 + PART5 + PART3 — competitors / knowledge gaps / lost deals */}
      <div className="row wrap" style={{ gap: 8 }}>
        <div style={{ flex: "1 1 220px" }}>
          <Section title={T("المنافسون", "Competitors")} active={c.competitors && c.competitors.status === "active"}>
            <div className="col" style={{ gap: 3, fontSize: 11.5 }}>{((c.competitors && c.competitors.mostLostAgainst) || []).slice(0, 4).map((x, k) => (<div key={k}>{T("خسارة أمام", "Lost to")} <b>{x.competitor}</b> ×{x.lostTo}</div>))}{((c.competitors && c.competitors.mostLostAgainst) || []).length === 0 ? ((c.competitors && c.competitors.topMentioned) || []).slice(0, 4).map((x, k) => (<div key={k}>{x.competitor} · {x.mentions} {T("ذكر", "mentions")}</div>)) : null}</div>
          </Section>
        </div>
        <div style={{ flex: "1 1 220px" }}>
          <Section title={T("ثغرات المعرفة (لم نُجب بثقة)", "Knowledge gaps")} active={c.knowledgeGaps && c.knowledgeGaps.status === "active"}>
            <div className="row wrap" style={{ gap: 6 }}>{((c.knowledgeGaps && c.knowledgeGaps.byType) || []).map((g, k) => (<Chip key={k}>{g.type} · {g.count}</Chip>))}</div>
          </Section>
        </div>
        <div style={{ flex: "1 1 220px" }}>
          <Section title={T("تحليل الصفقات الخاسرة", "Lost-deal analysis")} active={c.lostDeals && c.lostDeals.status === "active"}>
            <div className="col" style={{ gap: 3, fontSize: 11.5 }}>{((c.lostDeals && c.lostDeals.reasons) || []).slice(0, 5).map((r, k) => (<div key={k}><b>{r.primaryReason}</b> ×{r.count} {c.lostDeals.lowSample ? <span className="subtle">({T("إرشادي", "directional")})</span> : null}</div>))}</div>
          </Section>
        </div>
      </div>

      {/* PART9 — learning queue (founder approval; never auto-applied) */}
      <Section title={T("قائمة التعلّم (بانتظار موافقة المؤسس)", "Learning queue (awaiting founder approval)")} active={queue && queue.status === "active"} empty={T("لا تعلّمات بانتظار الموافقة.", "No learnings awaiting approval.")}>
        <div className="col" style={{ gap: 4 }}>
          {(queue && queue.items || []).slice(0, 8).map((it, k) => (
            <div key={k} className="row" style={{ gap: 7, alignItems: "center", fontSize: 11.5 }}><Chip tone="warn">{it.target}</Chip><span>{lbl(it.title)}</span></div>
          ))}
          <span className="subtle" style={{ fontSize: 10, color: "var(--color-orange)" }}>{T("يتطلّب موافقتك — لا يُطبَّق أي تعلّم تلقائياً على الإنتاج.", "Founder approval required — no learning is auto-applied to production.")}</span>
        </div>
      </Section>

      <span className="subtle" style={{ fontSize: 10, color: "var(--color-orange)" }}>{T("مصدر حقيقة واحد؛ كل قسم حقيقي أو «لا بيانات» من مصدره القائم؛ لا ذاكرة أو تحليلات مكرّرة، ولا رؤى ملفّقة.", "One source of truth; every section is real-or-NED from its existing source; no duplicated memory/analytics, no fabricated insight.")}</span>
    </div>
  );
}
window.PilotFeedbackView = PilotFeedbackView;

// PHASE 27 — BUSINESS INTELLIGENCE (read-only). ONE reachable screen: the executive monthly review, period
// comparison (meaningful movers), sales performance by dimension, customer + product intelligence, and the
// no-fake-BI audit. Every figure real-record-or-NED, statistically gated; never a fabricated trend/ROI.
function IntelligenceView({ lang }) {
  const T = (ar, en) => (lang === "ar" ? ar : en);
  const L = (o) => (o == null ? "" : typeof o === "string" ? o : (lang === "ar" ? (o.ar || o.en) : (o.en || o.ar)) || "");
  const [pc, setPc] = React.useState(null);
  const [sp, setSp] = React.useState(null);
  const [ci, setCi] = React.useState(null);
  const [pi, setPi] = React.useState(null);
  const [em, setEm] = React.useState(null);
  React.useEffect(() => {
    API.assem.periodComparison().then(setPc).catch(() => {});
    API.assem.salesPerformance().then(setSp).catch(() => {});
    API.assem.customerIntelligence().then(setCi).catch(() => {});
    API.assem.productIntelligence().then(setPi).catch(() => {});
    API.assem.executiveMonthlyReview().then(setEm).catch(() => {});
  }, []);
  const dirIcon = (d) => (d === "up" ? "▲" : d === "down" ? "▼" : "■");
  if (!pc) return (<Card><div className="col" style={{ gap: 4, padding: 10 }}><b style={{ fontSize: 13 }}>{T("ذكاء الأعمال", "Business Intelligence")}</b><span className="subtle" style={{ fontSize: 11.5 }}>{T("جارِ التحميل…", "Loading…")}</span></div></Card>);
  return (
    <div className="col" style={{ gap: 12 }}>
      <Card><div className="col" style={{ gap: 4, padding: 10 }}>
        <strong style={{ fontSize: 14 }}>{T("ذكاء الأعمال والتحسين المستمر", "Business intelligence & continuous optimization")}</strong>
        <span className="subtle" style={{ fontSize: 11.5 }}>{T("ماذا حدث · لماذا · ماذا بعد — كل رقم حقيقي أو «لا بيانات»، مُقيَّد إحصائياً؛ لا اتجاه ملفّق.", "What happened · why · what next — every figure real or NOT_ENOUGH_DATA, statistically gated; no fabricated trend.")}</span>
      </div></Card>
      {/* executive monthly review */}
      {em && em.ok ? (
        <Card><div className="col" style={{ gap: 5, padding: 10 }}>
          <div className="between"><b style={{ fontSize: 13 }}>{T("المراجعة الشهرية", "Monthly review")}</b><Badge tone="neutral">{em.month}</Badge></div>
          <div className="row wrap" style={{ gap: 8, fontSize: 12 }}>
            <Badge tone="green">{T("إيراد الشهر", "Revenue")}: {em.executiveSummary.status === "not_enough_data" ? T("لا بيانات", "NED") : em.executiveSummary.verifiedRevenueThisMonth}</Badge>
            <Badge tone="neutral">{T("معدل الفوز", "Win rate")}: {em.executiveSummary.winRate != null ? em.executiveSummary.winRate + "%" : T("لا بيانات", "NED")}</Badge>
            <Badge tone={em.strategicRisks.churnCount ? "orange" : "neutral"}>{T("مخاطر", "Risks")}: {(em.strategicRisks.items || []).length}</Badge>
            <Badge tone="neutral">{T("أولويات", "Priorities")}: {(em.topPriorities.items || []).length}</Badge>
          </div>
          {em.executiveSummary.lowSample ? <span className="subtle" style={{ fontSize: 10, color: "var(--color-orange)" }}>{T("عيّنة صغيرة — أرقام خام لا اتجاه مرتّب.", "Low sample — raw counts, not a ranked trend.")}</span> : null}
        </div></Card>
      ) : null}
      {/* period comparison movers */}
      {pc.ok && pc.status === "active" ? (
        <Card><div className="col" style={{ gap: 5, padding: 10 }}>
          <b style={{ fontSize: 13 }}>{T("التغييرات الجوهرية", "Meaningful changes")}</b>
          {(pc.windows || []).map((w, i) => (
            <div key={i} className="col" style={{ gap: 2, borderTop: i ? "1px solid var(--border-1)" : "none", paddingTop: i ? 5 : 0 }}>
              <span className="subtle" style={{ fontSize: 11 }}>{String(w.window).replace(/_/g, " ")}</span>
              {(w.movers || []).map((m, j) => <div key={j} className="between" style={{ fontSize: 11.5 }}><span>{String(m.kpi).replace(/_/g, " ")}</span><span style={{ color: m.direction === "up" ? "var(--color-secondary)" : "var(--color-danger)" }}>{dirIcon(m.direction)} {m.deltaPct}% <span className="subtle">({m.prior}→{m.this})</span></span></div>)}
            </div>
          ))}
        </div></Card>
      ) : <Card><div className="subtle" style={{ padding: 10, fontSize: 11.5 }}>{T("لا تغييرات جوهرية بعد — «لا بيانات».", "No meaningful changes yet — NOT_ENOUGH_DATA.")}</div></Card>}
      {/* sales performance dimensions */}
      {sp && sp.ok && sp.activeDimensions ? (
        <Card><div className="col" style={{ gap: 4, padding: 10 }}>
          <b style={{ fontSize: 13 }}>{T("أداء المبيعات", "Sales performance")}</b>
          {(sp.dimensions || []).filter((d) => d.status === "active").map((d, i) => (
            <div key={i} className="between" style={{ fontSize: 11.5 }}><span style={{ textTransform: "capitalize" }}>{String(d.dimension).replace(/_/g, " ")}</span><span className="subtle">{d.lowSample ? T("عيّنة صغيرة", "low sample") : T("أعلى محقِّق", "top")}</span></div>
          ))}
        </div></Card>
      ) : null}
      {/* customer + product intelligence */}
      {ci && ci.ok ? (
        <Card><div className="col" style={{ gap: 4, padding: 10 }}>
          <b style={{ fontSize: 13 }}>{T("ذكاء العملاء", "Customer intelligence")}</b>
          <div className="row wrap" style={{ gap: 8, fontSize: 12 }}>
            <Badge tone="neutral">{T("أعلى قيمة عمر", "Top LTV")}: {(ci.highestLtv.items || []).length || T("لا بيانات", "NED")}</Badge>
            <Badge tone={ci.highestChurnRisk.count ? "orange" : "neutral"}>{T("خطر تسرّب", "Churn risk")}: {ci.highestChurnRisk.count != null ? ci.highestChurnRisk.count : T("لا بيانات", "NED")}</Badge>
            <Badge tone="neutral">{T("صناعات وفيّة", "Loyal industries")}: {(ci.mostLoyalIndustries.items || []).length}</Badge>
            <Badge tone="neutral">{T("الإحالة (قيمة)", "Referral value")}: {T("لا بيانات", "NED")}</Badge>
          </div>
        </div></Card>
      ) : null}
      {pi && pi.ok && pi.status === "active" ? (
        <Card><div className="col" style={{ gap: 4, padding: 10 }}>
          <b style={{ fontSize: 13 }}>{T("ذكاء الخدمات", "Product intelligence")}</b>
          {(pi.services || []).slice(0, 6).map((s, i) => (
            <div key={i} className="between" style={{ fontSize: 11.5 }}><span>{s.service}</span><span className="subtle">{s.closeRate != null ? T("إغلاق", "close") + " " + s.closeRate + "%" : T("لا بيانات", "NED")}{s.avgDiscountPct != null ? " · " + T("خصم", "disc") + " " + s.avgDiscountPct + "%" : ""}</span></div>
          ))}
        </div></Card>
      ) : null}
    </div>
  );
}

// PHASE 26 — AUTONOMOUS COMPANY (connect-only). ONE reachable read-only screen: the company event stream, the
// director-reaction routing, the end-of-day review, organizational memory, and the no-fake-autonomy audit. Every
// figure derives from a real record; nothing auto-executes.
function AutonomyView({ lang }) {
  const T = (ar, en) => (lang === "ar" ? ar : en);
  const [es, setEs] = React.useState(null);
  const [rx, setRx] = React.useState(null);
  const [eod, setEod] = React.useState(null);
  const [om, setOm] = React.useState(null);
  const [aa, setAa] = React.useState(null);
  React.useEffect(() => {
    API.assem.companyEventStream().then(setEs).catch(() => {});
    API.assem.companyReactions().then(setRx).catch(() => {});
    API.assem.endOfDayReview().then(setEod).catch(() => {});
    API.assem.organizationalMemory().then(setOm).catch(() => {});
    API.assem.companyAutonomyAudit().then(setAa).catch(() => {});
  }, []);
  const ned = (x) => !x || x.status === "not_enough_data";
  if (!es) return (<Card><div className="col" style={{ gap: 4, padding: 10 }}><b style={{ fontSize: 13 }}>{T("الشركة المستقلة", "Autonomous Company")}</b><span className="subtle" style={{ fontSize: 11.5 }}>{T("جارِ التحميل…", "Loading…")}</span></div></Card>);
  return (
    <div className="col" style={{ gap: 12 }}>
      <Card><div className="col" style={{ gap: 4, padding: 10 }}>
        <strong style={{ fontSize: 14 }}>{T("نظام التشغيل المستقل", "Autonomous operating system")}</strong>
        <span className="subtle" style={{ fontSize: 11.5 }}>{T("حدث واحد يشغّل السلسلة الصحيحة عبر كل الأقسام — كل حدث من سجلّ حقيقي؛ لا تنفيذ تلقائي.", "One event triggers the right chain across departments — every event from a real record; nothing auto-executes.")}</span>
      </div></Card>
      {aa && aa.ok ? (
        <Card><div className="between" style={{ padding: 10, fontSize: 12.5 }}>
          <b>{T("تدقيق الاستقلالية (بلا تزييف)", "Autonomy audit (no fake execution)")}</b>
          <Badge tone={aa.allPass ? "green" : "danger"}>{aa.passed}/{aa.total} {aa.allPass ? T("سليم", "clean") : T("فشل", "fail")}</Badge>
        </div></Card>
      ) : null}
      {es.ok && es.status === "active" ? (
        <Card><div className="col" style={{ gap: 5, padding: 10 }}>
          <div className="between"><b style={{ fontSize: 13 }}>{T("تيّار أحداث الشركة", "Company event stream")}</b><Badge tone="neutral">{es.total}</Badge></div>
          {(es.events || []).slice(0, 8).map((e, i) => (
            <div key={i} className="between" style={{ fontSize: 11.5, padding: "3px 0", borderTop: i ? "1px solid var(--border-1)" : "none", gap: 8, flexWrap: "wrap" }}>
              <span className="row" style={{ gap: 6 }}><Badge tone="neutral">{e.department}</Badge><span>{String(e.type).replace(/_/g, " ")}</span></span>
              <span className="subtle" style={{ fontSize: 10.5 }}>{String(e.at).slice(0, 10)} · {e.source}</span>
            </div>
          ))}
        </div></Card>
      ) : <Card><div className="subtle" style={{ padding: 10, fontSize: 11.5 }}>{T("لا أحداث بعد — «لا بيانات».", "No company events yet — NOT_ENOUGH_DATA.")}</div></Card>}
      {rx && rx.ok && rx.directors && rx.directors.length ? (
        <Card><div className="col" style={{ gap: 4, padding: 10 }}>
          <b style={{ fontSize: 13 }}>{T("تفاعل المديرين", "Director reactions")}</b>
          <div className="row wrap" style={{ gap: 8, fontSize: 12 }}>{rx.directors.map((d, i) => <Badge key={i} tone="neutral">{d}: {(rx.byDirector[d] || []).length}</Badge>)}</div>
          <span className="subtle" style={{ fontSize: 10 }}>{T("كل مدير يتفاعل فقط مع أحداث قسمه — توصية فقط، بموافقة.", "Each director reacts only to his department's events — recommend-only, approval-gated.")}</span>
        </div></Card>
      ) : null}
      {eod && eod.ok ? (
        <Card><div className="col" style={{ gap: 4, padding: 10 }}>
          <b style={{ fontSize: 13 }}>{T("مراجعة نهاية اليوم", "End-of-day review")}</b>
          <div className="row wrap" style={{ gap: 8, fontSize: 12 }}>
            <Badge tone="green">{T("إيراد اليوم", "Revenue today")}: {ned(eod.revenueToday) ? T("لا بيانات", "NED") : eod.revenueToday.value}</Badge>
            <Badge tone={eod.lostOpportunities.count ? "orange" : "neutral"}>{T("فرص مفقودة", "Lost")}: {eod.lostOpportunities.count}</Badge>
            <Badge tone={eod.supportIssues.open ? "orange" : "neutral"}>{T("دعم مفتوح", "Support")}: {eod.supportIssues.open != null ? eod.supportIssues.open : T("لا بيانات", "NED")}</Badge>
            <Badge tone={(eod.decisionsRequiredTomorrow.founderDecisions || eod.decisionsRequiredTomorrow.pendingApprovals) ? "danger" : "neutral"}>{T("قرارات الغد", "Decisions tomorrow")}: {eod.decisionsRequiredTomorrow.founderDecisions + eod.decisionsRequiredTomorrow.pendingApprovals}</Badge>
          </div>
        </div></Card>
      ) : null}
      {om && om.ok && om.status === "active" ? (
        <Card><div className="col" style={{ gap: 4, padding: 10 }}>
          <b style={{ fontSize: 13 }}>{T("الذاكرة التنظيمية", "Organizational memory")}</b>
          <div className="row wrap" style={{ gap: 8, fontSize: 11.5 }}>{Object.keys(om.categories).map((k, i) => <Badge key={i} tone="neutral">{String(k).replace(/_/g, " ")}: {om.categories[k].count}</Badge>)}</div>
        </div></Card>
      ) : null}
    </div>
  );
}

// PHASE 25 — REVENUE OPERATIONS (post-sale). ONE reachable read-only screen composing the honest engines:
// active customers / projects / overdue deliveries / upsell / referrals / support / health + delivery intelligence
// + the weekly operations review. Every tile real-or-NED; referral value/rate NED; no vanity.
function PostSaleOpsView({ lang }) {
  const T = (ar, en) => (lang === "ar" ? ar : en);
  const L = (o) => (o == null ? "" : typeof o === "string" ? o : (lang === "ar" ? (o.ar || o.en) : (o.en || o.ar)) || "");
  const [ro, setRo] = React.useState(null);
  const [wor, setWor] = React.useState(null);
  const [di, setDi] = React.useState(null);
  const [sm, setSm] = React.useState(null);
  React.useEffect(() => {
    API.assem.revenueOperations().then(setRo).catch(() => {});
    API.assem.weeklyOperationsReview().then(setWor).catch(() => {});
    API.assem.deliveryIntelligence().then(setDi).catch(() => {});
    API.assem.supportMetrics().then(setSm).catch(() => {});
  }, []);
  const isNed = (x) => !x || x.status === "not_enough_data";
  const tile = (label, val, ned) => (<Card style={{ flex: "1 1 120px" }}><div className="col" style={{ gap: 2, padding: 10, alignItems: "center" }}><div className="subtle" style={{ fontSize: 11 }}>{label}</div><div style={{ fontSize: 20, fontWeight: 800 }}>{ned ? <span className="subtle" style={{ fontSize: 13 }}>{T("لا بيانات", "NED")}</span> : (val == null ? "—" : val)}</div></div></Card>);
  const tierTone = (t) => (t === "high" ? "danger" : t === "medium" ? "orange" : "neutral");
  if (!ro || !ro.ok) return (<Card><div className="col" style={{ gap: 4, padding: 10 }}><b style={{ fontSize: 13 }}>{T("عمليات الإيراد", "Revenue Operations")}</b><span className="subtle" style={{ fontSize: 11.5 }}>{T("جارِ التحميل…", "Loading…")}</span></div></Card>);
  return (
    <div className="col" style={{ gap: 12 }}>
      <Card><div className="col" style={{ gap: 4, padding: 10 }}>
        <strong style={{ fontSize: 14 }}>{T("عمليات الإيراد — بعد البيع", "Revenue Operations — post-sale")}</strong>
        <span className="subtle" style={{ fontSize: 11.5 }}>{T("إدارة العملاء الدافعين: مشاريع/تسليم/دعم/تجديد/بيع إضافي/إحالة — كل رقم حقيقي أو «لا بيانات».", "Manage paying customers: projects / delivery / support / renewal / upsell / referral — every figure real or NOT_ENOUGH_DATA.")}</span>
      </div></Card>
      <div className="row wrap" style={{ gap: 8 }}>
        {tile(T("عملاء نشطون", "Active customers"), ro.activeCustomers.total, isNed(ro.activeCustomers))}
        {tile(T("مشاريع نشطة", "Active projects"), ro.activeProjects.total, isNed(ro.activeProjects))}
        {tile(T("تسليمات متأخّرة", "Overdue deliveries"), ro.overdueDeliveries.count, isNed(ro.overdueDeliveries))}
        {tile(T("فرص بيع إضافي", "Upsell opps"), ro.upsellOpportunities.count, isNed(ro.upsellOpportunities))}
        {tile(T("إحالات جاهزة", "Referrals ready"), ro.referrals.ready, isNed(ro.referrals))}
        {tile(T("دعم مفتوح", "Open support"), ro.support && ro.support.open, isNed(ro.support))}
        {tile(T("صحّة العميل", "Customer health"), ro.customerHealth && ro.customerHealth.value != null ? ro.customerHealth.value : null, isNed(ro.customerHealth) || !(ro.customerHealth && ro.customerHealth.value != null))}
      </div>
      <div className="between" style={{ fontSize: 11 }}><span className="subtle">{T("الإحالة (قيمة/معدّل)", "Referral (value/rate)")}</span><span className="subtle">{T("لا بيانات — غير مُقاس (لا يُلفّق)", "NOT_ENOUGH_DATA — uninstrumented (never fabricated)")}</span></div>
      {di && di.ok && di.status === "active" ? (
        <Card><div className="col" style={{ gap: 5, padding: 10 }}>
          <b style={{ fontSize: 13 }}>{T("ذكاء التسليم", "Delivery intelligence")}</b>
          <div className="row wrap" style={{ gap: 8, fontSize: 12 }}>
            <Badge tone="neutral">{T("معلّق", "Pending")}: {di.pending}</Badge>
            <Badge tone={di.overdue ? "danger" : "neutral"}>{T("متأخّر", "Overdue")}: {di.overdue}</Badge>
            <Badge tone={di.blocked ? "orange" : "neutral"}>{T("محظور", "Blocked")}: {di.blocked}</Badge>
            <Badge tone="green">{T("مكتمل", "Completed")}: {di.completed}</Badge>
            {di.bottleneck ? <Badge tone="orange">{T("اختناق", "Bottleneck")}: {di.bottleneck.stage} ({di.bottleneck.count})</Badge> : null}
          </div>
        </div></Card>
      ) : null}
      {wor && wor.ok && wor.laneCount ? (
        <Card><div className="col" style={{ gap: 6, padding: 10 }}>
          <b style={{ fontSize: 13 }}>{T("المراجعة الأسبوعية للعمليات", "Weekly operations review")}</b>
          {(wor.lanes || []).map((l, i) => (
            <div key={i} className="between" style={{ fontSize: 12, padding: "5px 0", borderTop: i ? "1px solid var(--border-1)" : "none", gap: 8, flexWrap: "wrap" }}>
              <span className="row" style={{ gap: 6 }}><Badge tone={tierTone(l.priority)}>{l.priority}</Badge><span>{l.lane.replace(/_/g, " ")}</span></span>
              <span className="subtle" style={{ fontSize: 11 }}>{L(l.why)} · {T("أثر تقدير", "est. impact")} · {T("ثقة", "conf")} {l.confidence}</span>
            </div>
          ))}
          <span className="subtle" style={{ fontSize: 10, color: "var(--color-orange)" }}>{T("كل توصية: سبب + أثر مقدّر + ثقة + مخاطرة؛ بموافقة؛ لا تنفيذ تلقائي.", "Each rec: why + estimated impact + confidence + risk; approval-gated; nothing auto-executes.")}</span>
        </div></Card>
      ) : null}
      {sm && sm.ok && sm.status === "active" ? (
        <Card><div className="col" style={{ gap: 4, padding: 10 }}>
          <b style={{ fontSize: 13 }}>{T("مقاييس الدعم", "Support metrics")}</b>
          <div className="row wrap" style={{ gap: 8, fontSize: 12 }}>
            <Badge tone={sm.unresolved ? "orange" : "green"}>{T("غير محلول", "Unresolved")}: {sm.unresolved}</Badge>
            <Badge tone="neutral">{T("متوسط الحلّ", "Avg resolution")}: {sm.avgResolutionHours != null ? sm.avgResolutionHours + "h" : T("لا بيانات", "NED")}</Badge>
            <Badge tone="neutral">{T("متوسط أول استجابة", "Avg first response")}: {sm.avgFirstResponseHours != null ? sm.avgFirstResponseHours + "h" : T("لا بيانات", "NED")}</Badge>
          </div>
        </div></Card>
      ) : null}
    </div>
  );
}

function CompanyOSView({ lang }) {
  const T = (ar, en) => (lang === "ar" ? ar : en);
  const L = (o) => (o == null ? "" : typeof o === "string" ? o : (lang === "ar" ? (o.ar || o.en) : (o.en || o.ar)) || "");
  const [bh, setBh] = React.useState(null);
  const [ac, setAc] = React.useState(null);
  const [cg, setCg] = React.useState(null);
  const [cal, setCal] = React.useState(null);
  const [ri, setRi] = React.useState(null);
  const [audit, setAudit] = React.useState(null);
  const [ov, setOv] = React.useState(null);     // FINAL — Assem oversight (one prioritized read)
  const [pr, setPr] = React.useState(null);     // FINAL — production readiness
  const [fa, setFa] = React.useState(null);     // FINAL — no-fake final audit
  React.useEffect(() => {
    API.assem.businessHealth().then(setBh).catch(() => {});
    API.assem.approvalCenter().then(setAc).catch(() => {});
    API.assem.companyGoals().then(setCg).catch(() => {});
    API.assem.executiveCalendar(30).then(setCal).catch(() => {});
    API.assem.recommendationImpact().then(setRi).catch(() => {});
    API.assem.noFakeOperationsAudit().then(setAudit).catch(() => {});
    API.assem.assemOversight().then(setOv).catch(() => {});
    API.assem.productionReadiness().then(setPr).catch(() => {});
    API.assem.noFakeFinalAudit().then(setFa).catch(() => {});
  }, []);
  const money = (n) => (n == null ? T("لا بيانات", "—") : (window.fmtCurrency ? window.fmtCurrency(n) : String(n)));
  const healthColor = bh && bh.health && bh.health.color === "green" ? "var(--color-secondary)" : bh && bh.health && bh.health.color === "yellow" ? "var(--color-orange)" : bh && bh.health && bh.health.color === "red" ? "var(--color-danger)" : "var(--fg-3)";
  const tierTone = (t) => (t === "high" ? "danger" : t === "medium" ? "orange" : "neutral");
  return (
    <div className="col" style={{ gap: 12 }}>
      <Card><div className="col" style={{ gap: 4, padding: 10 }}>
        <strong style={{ fontSize: 14 }}>{T("نظام تشغيل الشركة", "Company Operating System")}</strong>
        <span className="subtle" style={{ fontSize: 11.5 }}>{T("أدِر الشركة كاملة من مكان واحد — كل رقم حقيقي أو «لا بيانات»؛ لا تنفيذ تلقائي.", "Run the whole company from one place — every figure real or NOT_ENOUGH_DATA; nothing auto-executes.")}</span>
      </div></Card>

      {/* REAL CUSTOMER PILOT — one operational pilot screen + the exit decision (reusable component) */}
      <PilotDashboardView lang={lang} />

      {/* business health + pending decisions */}
      {bh && bh.ok ? (
        <div className="row wrap" style={{ gap: 8 }}>
          <Card style={{ flex: "1 1 160px" }}><div className="col" style={{ gap: 2, padding: 10, alignItems: "center" }}>
            <div className="subtle" style={{ fontSize: 11 }}>{T("صحّة العمل", "Business health")}</div>
            <div style={{ fontSize: 24, fontWeight: 800, color: healthColor }}>{bh.health && bh.health.score != null ? bh.health.score : T("لا بيانات", "—")}</div>
            <Badge tone={bh.health && bh.health.color === "green" ? "green" : bh.health && bh.health.color === "red" ? "danger" : "orange"}>{bh.health && bh.health.color ? bh.health.color : T("لا بيانات", "NED")}</Badge>
          </div></Card>
          <Card style={{ flex: "1 1 160px" }}><div className="col" style={{ gap: 2, padding: 10, alignItems: "center" }}>
            <div className="subtle" style={{ fontSize: 11 }}>{T("قرارات معلّقة", "Pending decisions")}</div>
            <div style={{ fontSize: 24, fontWeight: 800 }}>{bh.pendingDecisions}</div>
          </div></Card>
          <Card style={{ flex: "2 1 240px" }}><div className="col" style={{ gap: 4, padding: 10 }}>
            <b style={{ fontSize: 12.5 }}>{T("أهم المخاطر", "Top risks")}</b>
            {(bh.topRisks || []).length ? (bh.topRisks || []).slice(0, 4).map((r, i) => <div key={i} style={{ fontSize: 11.5 }}>⚠︎ {L(r.detail)} <span className="subtle">({r.source})</span></div>) : <span className="subtle" style={{ fontSize: 11.5 }}>{T("لا مخاطر عالية.", "No high risks.")}</span>}
          </div></Card>
        </div>
      ) : null}

      {/* approval center */}
      {ac && ac.ok ? (
        <Card><div className="col" style={{ gap: 6, padding: 10 }}>
          <div className="between"><b style={{ fontSize: 13 }}>{T("مركز الموافقات", "Approval center")}</b><Badge tone="neutral">{ac.count} · {ac.byTier.high}H/{ac.byTier.medium}M/{ac.byTier.low}L</Badge></div>
          {ac.count ? (ac.items || []).slice(0, 8).map((it, i) => (
            <div key={i} className="between" style={{ fontSize: 12, padding: "5px 0", borderTop: i ? "1px solid var(--border-1)" : "none", gap: 8, flexWrap: "wrap" }}>
              <span className="row" style={{ gap: 6 }}><Badge tone={tierTone(it.priority.tier)}>{it.priority.tier}</Badge><span>{L(it.title)}</span></span>
              <span className="subtle" style={{ fontSize: 10.5 }}>{it.source}{it.impactSar ? ` · ${money(it.impactSar)}` : ""}</span>
            </div>
          )) : <span className="subtle" style={{ fontSize: 12 }}>{T("لا قرارات معلّقة تحتاج المؤسس.", "No decisions awaiting the founder.")}</span>}
          <span className="subtle" style={{ fontSize: 10, color: "var(--color-orange)" }}>{T("الموافقة/الرفض يُسجَّل عبر بوابة المؤسس — لا تنفيذ تلقائي.", "Approve/reject rides the founder gate — nothing auto-executes.")}</span>
        </div></Card>
      ) : null}

      {/* company goals */}
      {cg && cg.ok ? (
        <Card><div className="col" style={{ gap: 6, padding: 10 }}>
          <b style={{ fontSize: 13 }}>{T("أهداف الشركة", "Company goals")} <span className="subtle" style={{ fontSize: 11 }}>({cg.period})</span></b>
          {(cg.goals || []).map((g, i) => (
            <div key={i} className="between" style={{ fontSize: 12 }}>
              <span style={{ textTransform: "capitalize" }}>{g.dimension}</span>
              <span>{g.status === "not_enough_data" ? <span className="subtle">{T("لا بيانات", "NED")}</span> : <span>{g.current == null ? "—" : g.current}{g.target ? <span className="subtle"> / {g.target} ({g.progress}%)</span> : <span className="subtle"> ({T("لا هدف", "no target")})</span>}</span>}</span>
            </div>
          ))}
        </div></Card>
      ) : null}

      {/* executive calendar */}
      {cal && cal.ok && cal.count ? (
        <Card><div className="col" style={{ gap: 5, padding: 10 }}>
          <b style={{ fontSize: 13 }}>{T("التقويم التنفيذي", "Executive calendar")} <span className="subtle" style={{ fontSize: 11 }}>({cal.count})</span></b>
          {(cal.events || []).slice(0, 10).map((e, i) => (
            <div key={i} className="row" style={{ gap: 8, fontSize: 11.5, alignItems: "baseline" }}>
              <span className="subtle" style={{ minWidth: 78, fontVariantNumeric: "tabular-nums" }}>{String(e.date).slice(0, 10)}</span>
              <Badge tone="neutral">{e.type}</Badge><span>{L(e.title) || e.title}</span>
            </div>
          ))}
        </div></Card>
      ) : null}

      {/* recommendation impact */}
      {ri && ri.ok && ri.total ? (
        <Card><div className="col" style={{ gap: 4, padding: 10 }}>
          <div className="between"><b style={{ fontSize: 13 }}>{T("أثر التوصيات", "Recommendation impact")}</b><Badge tone="neutral">{ri.counts.succeeded}✓ / {ri.counts.failed}✗ / {ri.counts.pending}⏳</Badge></div>
          {(ri.recommendations || []).slice(0, 6).map((r, i) => (
            <div key={i} className="between" style={{ fontSize: 11.5 }}>
              <span>{r.recommendation}</span>
              <span className="subtle">{r.result}{r.revenueImpact != null ? ` · ${money(r.revenueImpact)}` : ""}</span>
            </div>
          ))}
          <span className="subtle" style={{ fontSize: 10 }}>{T("الأثر المالي مقيس أو «فارغ» — لا رفع ملفّق.", "Revenue impact is measured or null — no fabricated lift.")}</span>
        </div></Card>
      ) : null}

      {/* FINAL PART 9 — Assem oversight (campaign / commerce / memory / approvals / risks / corrective actions, ranked) */}
      {ov && ov.ok ? (
        <Card><div className="col" style={{ gap: 6, padding: 10 }}>
          <div className="between"><b style={{ fontSize: 13 }}>{T("إشراف عاصم", "Assem oversight")}</b><Badge tone={ov.health === "needs_attention" ? "danger" : ov.health === "steady" ? "green" : "neutral"}>{ov.health === "needs_attention" ? T("يحتاج انتباه", "Needs attention") : ov.health === "steady" ? T("مستقر", "Steady") : T("لا بيانات", "NED")}</Badge></div>
          {(ov.lanes || []).length ? (ov.lanes || []).map((ln, i) => (
            <div key={i} className="between" style={{ fontSize: 12, padding: "5px 0", borderTop: i ? "1px solid var(--border-1)" : "none", gap: 8, flexWrap: "wrap" }}>
              <span className="row" style={{ gap: 6 }}><Badge tone={tierTone(ln.tier)}>{ln.tier}</Badge><span style={{ textTransform: "capitalize" }}>{String(ln.category).replace(/_/g, " ")}</span></span>
              <span className="subtle" style={{ fontSize: 10.5 }}>{L(ln.summary)}</span>
            </div>
          )) : <span className="subtle" style={{ fontSize: 12 }}>{T("لا إشارات تحتاج اهتماماً.", "No lanes need attention.")}</span>}
          {(ov.topCorrectiveActions || []).length ? (
            <div className="col" style={{ gap: 2, marginTop: 4 }}>
              <b style={{ fontSize: 11.5 }}>{T("أهم الإجراءات التصحيحية", "Top corrective actions")}</b>
              {(ov.topCorrectiveActions || []).map((r, i) => <div key={i} style={{ fontSize: 11 }}>→ <span className="subtle">{r.what} · {r.owner} · {r.approvalRequired ? T("بموافقة", "approval") : T("—", "—")}</span></div>)}
            </div>
          ) : null}
        </div></Card>
      ) : null}

      {/* FINAL PART 11 — production readiness */}
      {pr && pr.ok ? (
        <Card><div className="col" style={{ gap: 5, padding: 10 }}>
          <div className="between"><b style={{ fontSize: 13 }}>{T("جاهزية الإنتاج", "Production readiness")}</b><Badge tone={pr.summary.readinessScore >= 80 ? "green" : pr.summary.readinessScore >= 40 ? "orange" : "danger"}>{pr.summary.integrationsReady}/{pr.summary.integrationsTotal}</Badge></div>
          {(pr.integrations || []).map((it, i) => (
            <div key={i} className="between" style={{ fontSize: 11.5 }}>
              <span>{it.label}</span>
              <Badge tone={it.ready ? "green" : "orange"}>{it.ready ? T("جاهز", "ready") : ((it.missing && it.missing[0]) || it.status)}</Badge>
            </div>
          ))}
          <div className="row wrap" style={{ gap: 5, marginTop: 4 }}>
            <Badge tone={pr.paymentWebhook.ready ? "green" : "orange"}>{T("ويبهوك الدفع", "Payment webhook")}: {pr.paymentWebhook.status}</Badge>
            <Badge tone={pr.bookingWebhook.ready ? "green" : "orange"}>{T("ويبهوك الحجز", "Booking sync")}: {pr.bookingWebhook.status}</Badge>
            <Badge tone="neutral">{T("مستأجر واحد بالتصميم", "single-tenant by design")}</Badge>
          </div>
          <span className="subtle" style={{ fontSize: 10 }}>{T("كل إشارة حقيقية أو «إعداد مطلوب» — لا تزييف للجاهزية.", "Every signal is a real probe or 'setup required' — nothing faked ready.")}</span>
        </div></Card>
      ) : null}

      {/* no-fake-operations audit */}
      {audit && audit.ok ? (
        <Card><div className="col" style={{ gap: 4, padding: 10 }}>
          <div className="between"><b style={{ fontSize: 13 }}>{T("تدقيق بلا تزييف", "No-fake-operations audit")}</b><Badge tone={audit.allPass ? "green" : "danger"}>{audit.passed}/{audit.total}</Badge></div>
          {(audit.checks || []).map((c, i) => <div key={i} className="row" style={{ gap: 6, fontSize: 11 }}><span>{c.pass ? "✓" : "✗"}</span><span className="subtle">{c.name.replace(/_/g, " ")}</span></div>)}
        </div></Card>
      ) : null}

      {/* FINAL PART 12 — no-fake FINAL audit (composes every domain honesty audit) */}
      {fa && fa.ok ? (
        <Card><div className="col" style={{ gap: 4, padding: 10 }}>
          <div className="between"><b style={{ fontSize: 13 }}>{T("التدقيق النهائي بلا تزييف", "No-fake FINAL audit")}</b><Badge tone={fa.overallPass ? "green" : "danger"}>{fa.overallPass ? T("الكل ناجح", "all pass") : T("مراجعة", "review")} · {fa.totalPassed}/{fa.totalChecks}</Badge></div>
          {(fa.byAudit || []).map((a, i) => <div key={i} className="between" style={{ fontSize: 11 }}><span className="subtle">{a.label}</span><span>{a.allPass === null ? T("غير محمّل", "not loaded") : a.allPass ? `✓ ${a.passed}/${a.total}` : `✗ ${a.passed}/${a.total}`}</span></div>)}
          <span className="subtle" style={{ fontSize: 10 }}>{T("يركّب كل تدقيقات النزاهة — حقيقي أو «لا بيانات»؛ لا اختلاق.", "Composes every domain honesty audit — real-or-NED, nothing fabricated.")}</span>
        </div></Card>
      ) : null}

      <div className="subtle" style={{ fontSize: 10.5, color: "var(--color-orange)" }}>{T("عرض فقط — كل رقم حقيقي أو «لا بيانات»؛ لا تنفيذ تلقائي.", "Display-only — every figure real or NOT_ENOUGH_DATA; nothing auto-executes.")}</div>
    </div>
  );
}

// PHASE 22A — Commerce → Discounts. The Discount Authority surface: founder CRUD, the approval queue (Agent→Manager
// →Director→Assem), performance (real-or-NED), and the no-fake audit. Display + controlled-action only; every figure
// is real or "—". The owner operating this screen approves at director/Assem authority.
function DiscountsView({ lang }) {
  const T = (ar, en) => (lang === "ar" ? ar : en);
  const L = (o) => (o == null ? "" : typeof o === "string" ? o : (lang === "ar" ? (o.ar || o.en) : (o.en || o.ar)) || "");
  const [discs, setDiscs] = React.useState(null);
  const [appr, setAppr] = React.useState(null);
  const [perf, setPerf] = React.useState(null);
  const [audit, setAudit] = React.useState(null);
  const [budgets, setBudgets] = React.useState(null);   // PHASE 22B
  const [winAn, setWinAn] = React.useState(null);
  const [misuse, setMisuse] = React.useState(null);
  const [form, setForm] = React.useState({ name: "", code: "", pct: "", expiryDate: "", maxUses: "" });
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState(null);
  const load = React.useCallback(() => {
    API.assem.discounts().then(setDiscs).catch(() => setDiscs({ discounts: [] }));
    API.assem.discountApprovals("revenue_director").then(setAppr).catch(() => {});
    API.assem.discountPerformance().then(setPerf).catch(() => {});
    API.assem.noFakeDiscountAudit().then(setAudit).catch(() => {});
    API.assem.discountBudgets().then(setBudgets).catch(() => {});
    API.assem.discountWinAnalysis().then(setWinAn).catch(() => {});
    API.assem.discountMisuseAudit().then(setMisuse).catch(() => {});
  }, []);
  React.useEffect(() => { load(); }, [load]);
  const create = () => {
    setBusy(true); setErr(null);
    API.assem.createDiscount({ name: form.name, code: form.code, discountPercentage: Number(form.pct), expiryDate: form.expiryDate || null, maxUses: form.maxUses ? Number(form.maxUses) : null })
      .then((r) => { if (r.ok === false) { setErr(r.error); } else { setForm({ name: "", code: "", pct: "", expiryDate: "", maxUses: "" }); load(); } })
      .catch((e) => setErr(String(e && e.message || e))).finally(() => setBusy(false));
  };
  const decide = (id, action) => { API.assem.decideDiscountApproval(id, { action, role: "revenue_director", actorId: "owner", reason: action === "approved" ? "approved by owner" : "declined by owner" }).then(load).catch(() => {}); };
  const tierTone = (lvl) => (lvl === 3 ? "danger" : lvl === 2 ? "orange" : "neutral");
  const money = (n) => (n == null ? T("لا بيانات", "—") : (window.fmtCurrency ? window.fmtCurrency(n) : String(n)));
  return (
    <div className="col" style={{ gap: 12 }}>
      <Card><div className="col" style={{ gap: 4, padding: 10 }}>
        <strong style={{ fontSize: 14 }}>{T("سلطة الخصومات والتفاوض", "Discount Authority & Negotiation")}</strong>
        <span className="subtle" style={{ fontSize: 11.5 }}>{T("خصومات مُتحكَّم بها بثلاث مستويات صلاحية — لا يصل خصم غير معتمد لأي عرض أو رابط دفع. كل رقم حقيقي أو «لا بيانات».", "Controlled discounts across 3 authority tiers — no unapproved discount ever reaches a proposal or a payment link. Every figure real or NOT_ENOUGH_DATA.")}</span>
      </div></Card>

      {/* create (founder) */}
      <Card><div className="col" style={{ gap: 8, padding: 10 }}>
        <b style={{ fontSize: 13 }}>{T("إنشاء خصم", "Create a discount")}</b>
        <div className="row wrap" style={{ gap: 6 }}>
          <input value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} placeholder={T("الاسم", "Name")} style={{ flex: "1 1 120px", fontSize: 12, padding: "6px 8px", borderRadius: 8, border: "1px solid var(--border-1)" }} />
          <input value={form.code} onChange={(e) => setForm({ ...form, code: e.target.value })} placeholder={T("الكود", "Code")} style={{ flex: "1 1 100px", fontSize: 12, padding: "6px 8px", borderRadius: 8, border: "1px solid var(--border-1)" }} />
          <input value={form.pct} onChange={(e) => setForm({ ...form, pct: e.target.value })} placeholder={T("٪", "%")} type="number" min="1" max="30" style={{ width: 64, fontSize: 12, padding: "6px 8px", borderRadius: 8, border: "1px solid var(--border-1)" }} />
          <input value={form.maxUses} onChange={(e) => setForm({ ...form, maxUses: e.target.value })} placeholder={T("حد الاستخدام", "Max uses")} type="number" style={{ width: 100, fontSize: 12, padding: "6px 8px", borderRadius: 8, border: "1px solid var(--border-1)" }} />
          <input value={form.expiryDate} onChange={(e) => setForm({ ...form, expiryDate: e.target.value })} type="date" style={{ fontSize: 12, padding: "6px 8px", borderRadius: 8, border: "1px solid var(--border-1)" }} />
          <button className="btn btn--primary btn--sm" disabled={busy || !form.code || !form.pct} onClick={create}>{T("إنشاء", "Create")}</button>
        </div>
        {form.pct ? <span className="subtle" style={{ fontSize: 11 }}>{T("المستوى المطلوب", "Authority")}: {Number(form.pct) <= 10 ? T("الوكيل (بلا موافقة)", "Agent (no approval)") : Number(form.pct) <= 20 ? T("مدير المبيعات (موافقة)", "Sales Manager (approval)") : Number(form.pct) <= 30 ? T("مدير الإيراد / عاصم", "Revenue Director / Assem") : T("خارج السياسة", "out of policy")}</span> : null}
        {err ? <span style={{ fontSize: 11.5, color: "var(--color-danger)" }}>⚠︎ {String(err).replace(/_/g, " ")}</span> : null}
      </div></Card>

      {/* discount list */}
      {discs && discs.discounts ? (
        <Card><div className="col" style={{ gap: 4, padding: 10 }}>
          <div className="between"><b style={{ fontSize: 13 }}>{T("الخصومات", "Discounts")}</b><Badge tone="neutral">{discs.discounts.length}</Badge></div>
          {discs.discounts.length ? discs.discounts.map((d, i) => (
            <div key={i} className="between" style={{ fontSize: 12, padding: "6px 0", borderTop: i ? "1px solid var(--border-1)" : "none", gap: 8, flexWrap: "wrap" }}>
              <span className="row" style={{ gap: 6 }}><Badge tone={tierTone(d.authorityLevel)}>L{d.authorityLevel}</Badge><b>{d.code}</b><span className="subtle">{d.discountPercentage}%</span><span style={{ fontSize: 11 }}>{d.name}</span></span>
              <span className="subtle" style={{ fontSize: 10.5 }}>{T("استُخدم", "used")} {d.usedCount}{d.maxUses != null ? `/${d.maxUses}` : ""}{d.expired ? ` · ${T("منتهٍ", "expired")}` : d.redeemable ? ` · ${T("نشط", "active")}` : ` · ${d.status}`}</span>
            </div>
          )) : <span className="subtle" style={{ fontSize: 12 }}>{T("لا خصومات بعد — أنشئ واحداً أعلاه.", "No discounts yet — create one above.")}</span>}
        </div></Card>
      ) : null}

      {/* approval queue */}
      {appr && appr.ok ? (
        <Card><div className="col" style={{ gap: 6, padding: 10 }}>
          <div className="between"><b style={{ fontSize: 13 }}>{T("طابور الموافقات", "Approval queue")}</b><Badge tone={appr.count ? "orange" : "neutral"}>{appr.count}</Badge></div>
          {appr.count ? appr.items.map((a, i) => (
            <div key={i} className="col" style={{ gap: 4, padding: "7px 0", borderTop: i ? "1px solid var(--border-1)" : "none" }}>
              <div className="between" style={{ flexWrap: "wrap", gap: 6 }}>
                <span className="row" style={{ gap: 6 }}><Badge tone={tierTone(a.requiredLevel)}>{a.requestedPct}%</Badge><span style={{ fontSize: 12 }}>{a.code || T("خصم", "discount")}</span><span className="subtle" style={{ fontSize: 10.5 }}>→ {a.requiredApprover}</span></span>
                <span className="row" style={{ gap: 5 }}>
                  <button className="btn btn--sm btn--primary" onClick={() => decide(a.id, "approved")}>{T("اعتماد", "Approve")}</button>
                  <button className="btn btn--sm btn--subtle" style={{ color: "var(--color-danger)" }} onClick={() => decide(a.id, "rejected")}>{T("رفض", "Reject")}</button>
                </span>
              </div>
              {a.justification ? <span className="subtle" style={{ fontSize: 10.5 }}>{T("السبب", "why")}: {a.justification.hasPriceObjection ? T("اعتراض سعر", "price objection") : T("ليس سعراً", "not price")}{a.discountAdvisable === false ? ` · ⚠︎ ${T("غير مُنصح به", "not advisable")}` : ""}</span> : null}
            </div>
          )) : <span className="subtle" style={{ fontSize: 12 }}>{T("لا موافقات معلّقة.", "No pending approvals.")}</span>}
          <span className="subtle" style={{ fontSize: 10, color: "var(--color-orange)" }}>{T("الرفض نهائي — لا تصعيد تلقائي. لا شيء يُطبَّق تلقائياً.", "Rejection is terminal — no auto-escalation. Nothing auto-applies.")}</span>
        </div></Card>
      ) : null}

      {/* performance */}
      {perf && perf.ok ? (
        <Card><div className="col" style={{ gap: 4, padding: 10 }}>
          <div className="between"><b style={{ fontSize: 13 }}>{T("أداء الخصومات", "Discount performance")}</b><Badge tone={perf.status === "active" ? "neutral" : "dark"}>{perf.totalUsages} {T("استخدام", "uses")}</Badge></div>
          <div className="row wrap" style={{ gap: 6 }}>
            <Badge tone="green">{T("صفقات مغلقة", "Closed")}: {perf.dealsClosed}</Badge>
            <Badge tone="lime">{T("إيراد", "Revenue")}: {money(perf.revenueGenerated)}</Badge>
            <Badge tone="neutral">{T("متوسّط الخصم", "Avg discount")}: {perf.averageDiscount == null ? "—" : perf.averageDiscount + "%"}</Badge>
            <Badge tone="orange">{T("إيراد متنازَل عنه", "Discounted away")}: {money(perf.marginImpact.revenueDiscountedAway)}</Badge>
          </div>
          <span className="subtle" style={{ fontSize: 10.5 }}>{T("أثر الهامش الحقيقي", "True gross-margin")}: {T("لا بيانات (يحتاج تكلفة المنتج)", "NOT_ENOUGH_DATA (needs COGS)")} · {T("رفع التحويل", "Conversion lift")}: {perf.conversionLift.measured ? perf.conversionLift.liftPct + "%" : T("لا بيانات كافية", "NOT_ENOUGH_DATA")}</span>
          {perf.bestCoupon ? <span className="subtle" style={{ fontSize: 11 }}>{T("أفضل كوبون", "Best coupon")}: <b>{perf.bestCoupon.code}</b> ({perf.bestCoupon.winRate}% {T("فوز", "win")}, {perf.bestCoupon.uses} {T("استخدام", "uses")})</span> : null}
        </div></Card>
      ) : null}

      {/* PHASE 22B — ROI revenue-ratio + win-without-discount (PART 3/6) */}
      {(perf && perf.ok && perf.roiMetrics) || (winAn && winAn.ok) ? (
        <Card><div className="col" style={{ gap: 6, padding: 10 }}>
          <b style={{ fontSize: 13 }}>{T("اقتصاد الخصومات", "Discount economics")}</b>
          {perf && perf.roiMetrics ? <div className="row wrap" style={{ gap: 6 }}>
            <Badge tone="lime">{T("إيراد لكل ريال خصم", "Revenue / 1 SAR discount")}: {perf.roiMetrics.revenuePerDiscountSar == null ? T("لا بيانات", "—") : perf.roiMetrics.revenuePerDiscountSar + "×"}</Badge>
            <Badge tone="dark">{T("هامش الربح الحقيقي", "True gross-margin")}: {T("لا بيانات (يحتاج تكلفة)", "NED (needs COGS)")}</Badge>
          </div> : null}
          {winAn && winAn.ok && winAn.status === "active" ? (
            <div className="grid" style={{ gridTemplateColumns: "1fr 1fr", gap: 8, marginTop: 2 }}>
              <div className="card" style={{ padding: 12 }}><div className="subtle" style={{ fontSize: 11 }}>{T("فوز بدون خصم", "Won WITHOUT discount")}</div><div style={{ fontSize: 18, fontWeight: 800 }}>{money(winAn.withoutDiscount.revenue)}</div><div className="subtle" style={{ fontSize: 10.5 }}>{winAn.withoutDiscount.deals} {T("صفقة", "deals")}</div></div>
              <div className="card" style={{ padding: 12 }}><div className="subtle" style={{ fontSize: 11 }}>{T("فوز بخصم", "Won WITH discount")}</div><div style={{ fontSize: 18, fontWeight: 800 }}>{money(winAn.withDiscount.revenue)}</div><div className="subtle" style={{ fontSize: 10.5 }}>{winAn.withDiscount.deals} {T("صفقة", "deals")}</div></div>
            </div>
          ) : null}
          <span className="subtle" style={{ fontSize: 10 }}>{T("النسبة إيراد لا ربح؛ المقارنة ارتباطية لا سببية. الهامش الحقيقي «لا بيانات» بلا تكلفة.", "Revenue ratio not profit; the comparison is correlation not causation. True margin is NED without COGS.")}</span>
        </div></Card>
      ) : null}

      {/* PHASE 22B — agent discount budgets (PART 1) */}
      {budgets && budgets.ok && (budgets.agents || []).length ? (
        <Card><div className="col" style={{ gap: 4, padding: 10 }}>
          <div className="between"><b style={{ fontSize: 13 }}>{T("ميزانيات خصم الوكلاء", "Agent discount budgets")} <span className="subtle" style={{ fontSize: 11 }}>({budgets.period})</span></b></div>
          {(budgets.agents || []).slice(0, 8).map((a, i) => (
            <div key={i} className="between" style={{ fontSize: 12, padding: "5px 0", borderTop: i ? "1px solid var(--border-1)" : "none", gap: 8, flexWrap: "wrap" }}>
              <span className="row" style={{ gap: 6 }}>{a.overBudget ? <Badge tone="danger">{T("تجاوز", "over")}</Badge> : null}<b>{a.agentName}</b></span>
              <span className="subtle" style={{ fontSize: 10.5 }}>{a.assigned == null ? T("لا ميزانية", "no budget") : `${T("استُخدم", "used")} ${money(a.used)} / ${money(a.assigned)} · ${T("متبقّ", "left")} ${money(a.remaining)}`}</span>
            </div>
          ))}
          <span className="subtle" style={{ fontSize: 10 }}>{T("المستخدَم = مجموع حقيقي لهذا الشهر؛ بلا ميزانية = «لا بيانات» لا سقف ملفّق.", "Used = real sum this month; an unconfigured budget is NED, never a fabricated cap.")}</span>
        </div></Card>
      ) : null}

      {/* PHASE 22B — reason analytics (PART 5) */}
      {perf && perf.ok && (perf.byReason || []).length ? (
        <Card><div className="col" style={{ gap: 4, padding: 10 }}>
          <b style={{ fontSize: 13 }}>{T("تحليل أسباب الخصم", "Discount reason analytics")}</b>
          {(perf.byReason || []).slice(0, 8).map((r, i) => (
            <div key={i} className="between" style={{ fontSize: 12, padding: "5px 0", borderTop: i ? "1px solid var(--border-1)" : "none", gap: 8, flexWrap: "wrap" }}>
              <span>{L(r.label) || r.key}</span>
              <span className="subtle" style={{ fontSize: 10.5 }}>{r.uses} {T("مرة", "uses")} · {r.dealsClosed} {T("فوز", "won")} · {money(r.revenueGenerated)} · {T("متوسط", "avg")} {r.averageDiscount == null ? "—" : r.averageDiscount + "%"}</span>
            </div>
          ))}
        </div></Card>
      ) : null}

      {/* PHASE 22B — misuse warnings (PART 8) */}
      {misuse && misuse.ok && misuse.flagCount ? (
        <Card><div className="col" style={{ gap: 4, padding: 10, borderInlineStart: "3px solid var(--color-orange)" }}>
          <div className="between"><b style={{ fontSize: 13 }}>{T("تنبيهات إساءة الخصم", "Discount misuse warnings")}</b><Badge tone="orange">{misuse.flagCount}</Badge></div>
          {(misuse.flags || []).slice(0, 6).map((f, i) => (
            <div key={i} className="col" style={{ gap: 1, padding: "5px 0", borderTop: i ? "1px solid var(--border-1)" : "none" }}>
              <span className="row" style={{ gap: 6, fontSize: 11.5 }}><Badge tone={f.severity === "high" ? "danger" : "orange"}>{f.type.replace(/_/g, " ")}</Badge><span>{L(f.evidence)}</span></span>
              <span className="subtle" style={{ fontSize: 10 }}>{T("الوكيل", "agent")}: {f.agentId || "—"} · {T("المدير", "manager")}: {f.responsibleManager || "—"} · {L(f.recommendedAction)}</span>
            </div>
          ))}
          <span className="subtle" style={{ fontSize: 10 }}>{T("تنبيهات للمراجعة فقط — كل تنبيه من سجلّ حقيقي؛ لا تنفيذ تلقائي.", "Advisory only — every flag cites a real record; nothing auto-acts.")}</span>
        </div></Card>
      ) : null}

      {/* no-fake audit */}
      {audit && audit.ok ? (
        <Card><div className="col" style={{ gap: 4, padding: 10 }}>
          <div className="between"><b style={{ fontSize: 13 }}>{T("تدقيق خصومات بلا تزييف", "No-fake-discount audit")}</b><Badge tone={audit.allPass ? "green" : "danger"}>{audit.passed}/{audit.total}</Badge></div>
          {(audit.checks || []).map((c, i) => <div key={i} className="row" style={{ gap: 6, fontSize: 11 }}><span>{c.pass ? "✓" : "✗"}</span><span className="subtle">{c.name.replace(/_/g, " ")}</span></div>)}
        </div></Card>
      ) : null}

      <div className="subtle" style={{ fontSize: 10.5, color: "var(--color-orange)" }}>{T("عرض + إجراء مُتحكَّم فيه — كل رقم حقيقي أو «لا بيانات»؛ لا خصم غير معتمد، لا تطبيق تلقائي.", "Display + controlled action — every figure real or NOT_ENOUGH_DATA; no unapproved discount, nothing auto-applies.")}</div>
    </div>
  );
}

function AssemScreen({ embedded } = {}) {
  const { lang } = useLang();
  const T = (ar, en) => (lang === "ar" ? ar : en);
  const [meta, setMeta] = React.useState(null);
  const [mode, setMode] = React.useState("off");
  const [snap, setSnap] = React.useState(null);
  const [msgs, setMsgs] = React.useState([]);      // { from:"founder"|"assem", text, answer, recs, citations, confidence }
  const [input, setInput] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  const [modeBusy, setModeBusy] = React.useState(false);
  const scrollRef = React.useRef(null);

  React.useEffect(() => {
    API.assem.meta().then((m) => { setMeta(m); setMode(m.mode); }).catch(() => {});
    API.assem.snapshot(lang).then(setSnap).catch(() => {});
  }, []);
  React.useEffect(() => { if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight; }, [msgs, busy]);

  const ask = async (q) => {
    const question = (q || input).trim();
    if (!question || busy) return;
    setMsgs((m) => [...m, { from: "founder", text: question }]);
    setInput(""); setBusy(true);
    try {
      const r = await API.assem.ask(question, lang);
      setMsgs((m) => [...m, { from: "assem", answer: r.answer, recs: r.recommendations || [], citations: r.citations || [], confidence: r.confidence, intent: r.intent }]);
    } catch (e) {
      setMsgs((m) => [...m, { from: "assem", answer: T("تعذّر الوصول للبيانات الآن.", "I couldn't reach the data just now."), recs: [], citations: [] }]);
    } finally { setBusy(false); }
  };
  const setAssemMode = async (m) => {
    setModeBusy(true);
    try { const r = await API.assem.setMode(m); if (r.ok) setMode(r.mode); } catch (e) {} finally { setModeBusy(false); }
  };

  const fmt = (n) => (typeof n === "number" ? window.fmtCurrency(n) : (n || "—"));
  const rev = snap && snap.revenue;
  const [view, setView] = React.useState("chat");   // V2 — Chat | Dashboard | Command Center | War Rooms | Alerts

  return (
    <div className={embedded ? "fade-up" : "content__inner fade-up"}>
      {!embedded && (
      <div className="between" style={{ marginBottom: 14, flexWrap: "wrap", gap: 10 }}>
        <div className="row" style={{ gap: 12, alignItems: "center" }}>
          <div style={{ width: 44, height: 44, borderRadius: 12, background: "var(--color-primary)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}><Icon name="sparkles" size={22} style={{ color: "#fff" }} /></div>
          <div>
            <h4 style={{ marginBottom: 2 }}>{T("عاصم — مديرك التنفيذي الذكي", "Assem — your AI CEO")}</h4>
            <div className="subtle" style={{ fontSize: 12.5, maxWidth: 560, lineHeight: 1.5 }}>{T("اسأله عن الإيراد، المبيعات، الحملات، العملاء، المنافسين، الأهداف، المخاطر، أو خطة نمو — يقرأ كل محرّكاتك ويجيب.", "Ask about revenue, sales, campaigns, customers, competitors, goals, risks, or a growth plan — he reads all your engines and answers.")}</div>
          </div>
        </div>
      </div>
      )}

      {/* Mode selector + guardrails — full screen only (hidden in embedded chat) */}
      {!embedded && (
      <Card style={{ marginBottom: 12 }}>
        <div className="col" style={{ gap: 8, padding: 4 }}>
          <div className="between" style={{ flexWrap: "wrap", gap: 8 }}>
            <b style={{ fontSize: 13 }}>{T("وضع عاصم", "Assem Mode")}</b>
            <div className="row" style={{ gap: 6 }}>
              {["off", "assisted", "autonomous"].map((m) => (
                <button key={m} className={"btn btn--sm " + (mode === m ? "btn--dark" : "btn--subtle")} onClick={() => setAssemMode(m)} disabled={modeBusy} style={{ textTransform: "capitalize" }}>{m}</button>
              ))}
            </div>
          </div>
          <div className="subtle" style={{ fontSize: 12, lineHeight: 1.5 }}>{meta && meta.capabilities ? (lang === "ar" ? meta.capabilities[mode].ar : meta.capabilities[mode].en) : ""}</div>
          <div className="subtle" style={{ fontSize: 11, color: "var(--color-orange)" }}>{T("في كل الأوضاع: لا إيقاف عملاء، لا حذف بيانات، لا تعديل تسعير، لا استرداد، لا إغلاق صفقات، لا إنفاق فوق الحدود.", "In every mode: never suspends customers, deletes data, modifies pricing, refunds, closes deals, or spends beyond limits.")}</div>
        </div>
      </Card>
      )}

      {/* V2 — Commander sub-nav (full screen only; embedded Managers view is chat-only) */}
      {!embedded && (
      <div className="chipscroll-wrap" style={{ marginBottom: 12 }}>
        <div className="chipscroll" style={{ gap: 6, paddingBottom: 4 }}>
          {ASSEM_VIEWS.map(([k, lab]) => <button key={k} className={"btn btn--sm " + (view === k ? "btn--dark" : "btn--subtle")} style={{ flexShrink: 0 }} onClick={() => setView(k)}>{lang === "ar" ? lab.ar : lab.en}</button>)}
        </div>
      </div>
      )}

      {/* Executive snapshot strip */}
      {view === "chat" && rev ? (
        <div className="row" style={{ gap: 8, flexWrap: "wrap", marginBottom: 12 }}>
          <div className="card" style={{ padding: 10, flex: "1 1 150px" }}><div className="subtle" style={{ fontSize: 11 }}>{T("الهدف الشهري", "Monthly target")}</div><div style={{ fontSize: 16, fontWeight: 800 }}>{rev.targetSet ? fmt(rev.target) : T("غير مضبوط", "not set")}</div></div>
          <div className="card" style={{ padding: 10, flex: "1 1 150px" }}><div className="subtle" style={{ fontSize: 11 }}>{T("الفجوة", "Gap")}</div><div style={{ fontSize: 16, fontWeight: 800 }}>{rev.gap != null ? fmt(rev.gap) : "—"}</div></div>
          <div className="card" style={{ padding: 10, flex: "1 1 150px" }}><div className="subtle" style={{ fontSize: 11 }}>{T("إيراد مؤكَّد بالدفع", "Verified revenue")}</div><div style={{ fontSize: 16, fontWeight: 800, color: "var(--color-lime, var(--color-primary))" }}>{fmt(rev.paymentVerified.total)}</div></div>
          <div className="card" style={{ padding: 10, flex: "1 1 130px" }}><div className="subtle" style={{ fontSize: 11 }}>{T("منطقة الخطر", "Danger Zone")}</div><div style={{ fontSize: 16, fontWeight: 800, color: snap.customers.dangerZone && snap.customers.dangerZone.count ? "var(--color-orange)" : "var(--fg-1)" }}>{snap.customers.dangerZone ? snap.customers.dangerZone.count : 0}</div></div>
          <div className="card" style={{ padding: 10, flex: "1 1 130px" }}><div className="subtle" style={{ fontSize: 11 }}>{T("قرارات تنتظرك", "Your decisions")}</div><div style={{ fontSize: 16, fontWeight: 800 }}>{snap.founderDecisions ? snap.founderDecisions.count : 0}</div></div>
        </div>
      ) : null}

      {/* Chat thread */}
      {view === "chat" && (<>
      <Card flush>
        <div ref={scrollRef} style={{ maxHeight: embedded ? 560 : 420, minHeight: embedded ? 320 : 0, overflowY: "auto", padding: 14, display: "flex", flexDirection: "column", gap: 12 }}>
          {!msgs.length ? (
            <div style={{ textAlign: "center", color: "var(--fg-3)", padding: "20px 10px" }}>
              <Icon name="sparkles" size={22} style={{ color: "var(--color-secondary)", marginBottom: 6 }} />
              <div style={{ fontSize: 13 }}>{T("ابدأ بسؤال — أو جرّب أحد الأمثلة بالأسفل.", "Ask me anything — or try an example below.")}</div>
            </div>
          ) : null}
          {msgs.map((m, i) => (
            m.from === "founder" ? (
              <div key={i} style={{ alignSelf: "flex-end", maxWidth: "85%", background: "var(--color-primary)", color: "#fff", padding: "9px 13px", borderRadius: "14px 14px 4px 14px", fontSize: 13.5 }}>{m.text}</div>
            ) : (
              <div key={i} style={{ alignSelf: "flex-start", maxWidth: "92%" }}>
                <div className="row" style={{ gap: 6, marginBottom: 4, alignItems: "center" }}><div style={{ width: 22, height: 22, borderRadius: 7, background: "var(--color-primary)", display: "flex", alignItems: "center", justifyContent: "center" }}><Icon name="sparkles" size={12} style={{ color: "#fff" }} /></div><b style={{ fontSize: 12 }}>Assem</b>{m.intent ? <Badge tone="neutral">{m.intent}</Badge> : null}</div>
                <div className="card" style={{ padding: 12 }}>
                  <AssemMd text={m.answer} />
                  {(m.recs || []).length ? <div className="col" style={{ gap: 6, marginTop: 10 }}>{m.recs.map((r, j) => <AssemRec key={j} r={r} lang={lang} />)}</div> : null}
                  {(m.citations || []).length ? <div className="row" style={{ gap: 6, flexWrap: "wrap", marginTop: 8 }}>{m.citations.map((c, j) => <Badge key={j} tone="purple">{c}</Badge>)}</div> : null}
                </div>
              </div>
            )
          ))}
          {busy ? <div style={{ alignSelf: "flex-start", color: "var(--fg-3)", fontSize: 12.5 }}>{T("عاصم يفكّر…", "Assem is thinking…")}</div> : null}
        </div>

        {/* example chips */}
        {meta && meta.examples ? (
          <div className="chipscroll" style={{ gap: 6, padding: "0 14px 10px" }}>
            {meta.examples.slice(0, 6).map((ex, i) => <button key={i} className="btn btn--sm btn--subtle" style={{ flexShrink: 0, fontSize: 11.5 }} onClick={() => ask(ex)}>{ex.replace(/^Assem,\s*/i, "")}</button>)}
          </div>
        ) : null}

        {/* input */}
        <div className="row" style={{ gap: 8, padding: 12, borderTop: "1px solid var(--border-1)" }}>
          <input className="input" style={{ flex: 1 }} dir="auto" value={input} onChange={(e) => setInput(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter") ask(); }} placeholder={T("اسأل عاصم…", "Ask Assem…")} />
          <Button variant="dark" onClick={() => ask()} disabled={busy || !input.trim()}>{T("إرسال", "Send")}</Button>
        </div>
      </Card>
      <div className="subtle" style={{ fontSize: 11, marginTop: 8, textAlign: "center" }}>{T("عاصم يقرأ بياناتك الحقيقية فقط — لا أرقام ملفّقة. عند نقص البيانات يقول «لا توجد بيانات كافية بعد».", "Assem reads only your real data — no fabricated numbers. When data is missing he says \"Not enough data yet.\"")}</div>
      </>)}
      {view === "owner" && <OwnerDashboardView lang={lang} />}
      {view === "companyos" && <CompanyOSView lang={lang} />}
      {view === "discounts" && <DiscountsView lang={lang} />}
      {view === "dashboard" && <AssemDashboardView lang={lang} />}
      {view === "command" && <AssemCommandCenterView lang={lang} />}
      {view === "cto" && <AssemCtoView lang={lang} />}
      {view === "warrooms" && <AssemWarRoomsView lang={lang} />}
      {view === "alerts" && <AssemAlertsView lang={lang} />}
    </div>
  );
}
