// screens-data.jsx — DATA section + CUSTOMERS + PRODUCTS front doors (action-first IA, reuse-only).
//
// These are NON-DESTRUCTIVE landing screens: no existing screen was removed. DATA is the single front
// door for read-only intelligence (each card says what the data means, why it matters, and a CTA that
// deep-links to the screen where the founder can act). CUSTOMERS + PRODUCTS group existing screens by
// what the founder is trying to do. Every CTA reuses the existing deep-link mechanism (window.__navTab).
const { useState: useDataState, useEffect: useDataEffect } = React;

// deepLink — reuse the shell's deep-link: set window.__navTab (tab/revtab) then navigate. Non-destructive.
function dataDeepLink(go, screen, opts) {
  try { if (opts) { window.__navTab = { screen, ...opts }; window.dispatchEvent(new CustomEvent("maxab:navtab", { detail: window.__navTab })); } } catch (e) {}
  go(screen);
}

// DataCard — what this means · why it matters · responsible director · expected impact · risk · CTA.
function DataCard({ icon, title, what, why, cta, onClick, stat, responsible, impact, risk }) {
  return (
    <Card><div className="col" style={{ gap: 8, padding: 6 }}>
      <div className="row" style={{ gap: 8, alignItems: "center" }}>
        <span className="opp" style={{ width: 34, height: 34, borderRadius: 10, background: "var(--bg-2)", color: "var(--color-secondary)", flexShrink: 0 }}><Icon name={icon} size={17} /></span>
        <b style={{ fontSize: 14 }}>{title}</b>
        {stat != null ? <Badge tone="neutral" style={{ marginInlineStart: "auto" }}>{stat}</Badge> : null}
      </div>
      <div style={{ fontSize: 12.5, color: "var(--fg-2)" }}>{what}</div>
      <div className="subtle" style={{ fontSize: 11.5 }}><b>{why.label}:</b> {why.text}</div>
      {(responsible || impact || risk) ? (
        <div className="row wrap subtle" style={{ fontSize: 11, gap: 10 }}>
          {responsible ? <span>{why.respLabel || "Responsible"}: <b>{responsible}</b></span> : null}
          {impact ? <span>{why.impactLabel || "Impact"}: <b>{impact}</b></span> : null}
          {risk ? <span>{why.riskLabel || "Risk"}: <Badge tone={risk === "low" ? "success" : risk === "medium" ? "warning" : "danger"}>{risk}</Badge></span> : null}
        </div>
      ) : null}
      <Button size="sm" variant="ghost" icon="arrowRight" onClick={onClick} style={{ alignSelf: "flex-start" }}>{cta}</Button>
    </div></Card>
  );
}

// P3·P6 — SALES INTELLIGENCE CENTER. Data is the EVIDENCE layer (Managers are the ACTION layer): every area
// names what it means + Impact/Risk/Owner + a one-click Go-to-action. Grouped into FIVE sections (Sales /
// Customer / Revenue / Agent / Company Intelligence). Reuse-only: `panel` = a real window-global analytics
// component (rendered inline); `deep` = a deep-link to the screen that owns it. The two genuinely-DUPLICATED
// ASSEM panels (Growth + Alerts — they also live in HEAD→ASSEM) are now deep-links, not mirrored dashboards,
// so Data no longer duplicates a manager dashboard. The 4 panels whose ONLY home is Data (Brain / Strategic /
// Director-coaching / Deploy) stay inline so no live engine is hidden (see SALES_INTELLIGENCE_CENTER_REPORT).
const DATA_SECTIONS = [["sales", "ذكاء المبيعات", "Sales Intelligence"], ["customer", "ذكاء العملاء", "Customer Intelligence"], ["revenue", "ذكاء الإيراد", "Revenue Intelligence"], ["agent", "ذكاء الوكلاء", "Agent Intelligence"], ["company", "ذكاء الشركة", "Company Intelligence"]];
function dataAreas(T) {
  return [
    // ── Sales Intelligence ──
    { key: "funnel", section: "sales", icon: "target", title: T("قمع المبيعات", "Sales Funnel"), deep: { screen: "head", director: "revenue" }, action: T("راجع اختناق القمع مع مدير الإيراد", "Review the funnel bottleneck with the Revenue Director"), director: "revenue" },
    { key: "intelligence", section: "sales", icon: "checkcircle", title: T("الذكاء وتدقيق الواقع", "Intelligence & Reality Audit"), deep: { screen: "validation", revtab: "intelligence" }, action: T("افتح الذكاء والتدقيق", "Open Intelligence & Audit") },
    { key: "vertical", section: "sales", icon: "grid", title: T("ذكاء القطاعات", "Vertical Intelligence"), deep: { screen: "validation", revtab: "vertical" }, action: T("افتح استراتيجية القطاع", "Open Vertical Strategy") },
    // ── Customer Intelligence ──
    { key: "journey", section: "customer", icon: "trending", title: T("رحلة العميل", "Customer Journey"), deep: { screen: "journey" }, action: T("افتح رحلة العميل", "Open the Customer Journey") },
    { key: "customers", section: "customer", icon: "users", title: T("العملاء والاحتفاظ", "Customers & retention"), deep: { screen: "customers" }, action: T("افتح حسابات العملاء", "Open customer accounts") },
    // ── Revenue Intelligence ──
    { key: "growth", section: "revenue", icon: "trending", title: T("محرّك النمو", "Growth Engine"), deep: { screen: "head", director: "revenue" }, action: T("اضبط أو ارفع الهدف الشهري مع مدير الإيراد", "Set or raise the monthly target with the Revenue Director"), director: "revenue" },
    { key: "revenue_data", section: "revenue", icon: "dollar", title: T("بيانات الإيراد", "Revenue data"), deep: { screen: "validation", revtab: "intelligence" }, action: T("افتح بيانات الإيراد", "Open revenue data"), director: "revenue" },
    // ── Agent Intelligence ──
    { key: "performance", section: "agent", icon: "trending", title: T("أداء الوكلاء وجاهزيتهم", "Agent performance & readiness"), deep: { screen: "agents", tab: "readiness" }, action: T("افتح الجاهزية والأداء", "Open Readiness & performance") },
    { key: "training", section: "agent", icon: "bot", title: T("إرشاد المديرين والوكلاء", "Director & agent coaching"), panel: "DirectorTrainingPanel", action: T("درّب مديراً في «المديرون»", "Coach a manager in Managers"), director: "assem" },
    { key: "knowledge", section: "agent", icon: "bot", title: T("قاعدة المعرفة", "Knowledge Base"), deep: { screen: "agents", tab: "learning" }, action: T("افتح مركز التعلّم", "Open the Learning Hub") },
    // ── Company Intelligence ──
    { key: "brain", section: "company", icon: "sparkles", title: T("دماغ الشركة", "Company Brain"), panel: "BrainPanel", action: T("طبّق درساً — وجّه مديراً في «المديرون»", "Apply a lesson — direct a manager in Managers"), director: "assem" },
    { key: "alerts", section: "company", icon: "alert", title: T("التنبيهات التنفيذية", "Executive Alerts"), deep: { screen: "head", director: "assem" }, action: T("نفّذ التنبيه الأعلى مع عاصم", "Act on the top alert with Assem"), director: "assem" },
    { key: "strategic", section: "company", icon: "target", title: T("التفكير الاستراتيجي", "Strategic Thinking"), panel: "StrategicPanel", action: T("أعطِ التركيز المختار كأمر لعاصم", "Give the chosen focus as a command to Assem"), director: "assem" },
    { key: "deploy", section: "company", icon: "wrench", title: T("مستشار النشر", "Deployment Advisor"), panel: "DeployAdvisorPanel", action: T("عالج بوابات النشر (المشغّل)", "Resolve deploy gates (operator)"), director: "cto" },
    { key: "awareness", section: "company", icon: "checkcircle", title: T("وعي عاصم", "Assem awareness"), deep: { screen: "head", director: "assem" }, action: T("افتح «المديرون»", "Open Managers") },
  ];
}
function DataScreen() {
  const { lang } = useLang();
  const { go } = useApp();
  const T = (ar, en) => (lang === "ar" ? ar : en);
  const AREAS = dataAreas(T);
  const [sel, setSel] = useDataState("funnel");
  const area = AREAS.find((a) => a.key === sel) || AREAS[0];
  // Part 9 — every DATA insight names the Responsible Director (who should act on it).
  const RESP = { funnel: T("مدير الإيراد", "Revenue Director"), journey: T("مدير نجاح العملاء", "Customer Success Director"), customers: T("مدير نجاح العملاء", "Customer Success Director"), revenue_data: T("مدير الإيراد", "Revenue Director"), brain: T("عاصم", "ASSEM"), growth: T("مدير الإيراد", "Revenue Director"), strategic: T("عاصم", "ASSEM"), alerts: T("عاصم (يوجّه المالك)", "ASSEM (routes to owner)"), training: T("عاصم", "ASSEM"), deploy: T("المدير التقني", "CTO"), intelligence: T("عاصم", "ASSEM"), vertical: T("مدير الإيراد", "Revenue Director"), orchestrator: T("مدير العمليات", "Operations Director"), performance: T("مدير العمليات", "Operations Director"), knowledge: T("المدير التقني", "CTO"), learning: T("عاصم", "ASSEM"), awareness: T("عاصم", "ASSEM") };
  const responsible = RESP[area.key] || T("عاصم", "ASSEM");
  // Part: every DATA insight names Expected Impact + Risk Level (qualitative, honest).
  const IMPACT = { brain: T("تعلّم أسرع → قرارات أفضل", "Faster learning → better decisions"), growth: T("مسار واضح لهدف أعلى", "A clear path to a higher target"), strategic: T("تركيز استراتيجي مبني على البيانات", "Data-backed strategic focus"), alerts: T("معالجة المخاطر قبل أن تكلّف", "Catch risks before they cost"), training: T("مديرون أقوى → تنفيذ أفضل", "Stronger directors → better execution"), deploy: T("إطلاق أكثر أماناً", "Safer releases"), intelligence: T("قرارات مبنية على أرقام حقيقية", "Decisions on real numbers"), vertical: T("توجيه البيع لأعلى ربحية", "Aim selling at the most profitable"), orchestrator: T("موثوقية تنفيذ أعلى", "Higher execution reliability"), performance: T("وكلاء أعلى أداءً", "Higher-performing agents"), knowledge: T("ردود ذكاء أدق", "Sharper AI replies"), learning: T("تكرار ما ينجح", "Repeat what works"), awareness: T("محاذاة المديرين", "Aligned directors") };
  const RISK = { brain: "low", growth: "low", strategic: "low", alerts: "medium", training: "low", deploy: "medium", intelligence: "low", vertical: "low", orchestrator: "medium", performance: "low", knowledge: "low", learning: "low", awareness: "low" };
  // Part 9 — every DATA area also names which AI WORKER agents consume this memory (static labels, like RESP/IMPACT).
  const AGENTS = { brain: T("كل وكلاء المبيعات", "All AI sales agents"), growth: T("وكلاء المبيعات", "Sales agents"), strategic: T("وكلاء المبيعات", "Sales agents"), alerts: T("وكلاء المبيعات والدعم", "Sales & support agents"), training: T("كل الوكلاء", "All agents"), deploy: T("لا وكلاء (المشغّل)", "None — operator only"), intelligence: T("وكلاء المبيعات", "Sales agents"), vertical: T("وكلاء المبيعات", "Sales agents"), orchestrator: T("وكلاء الردود", "AI reply agents"), performance: T("وكلاء المبيعات", "AI sales agents"), knowledge: T("وكلاء الردود", "AI reply agents"), learning: T("كل الوكلاء", "All agents"), awareness: T("وكلاء المبيعات", "Sales agents") };
  const impact = IMPACT[area.key] || T("يدعم قراراً تنفيذياً", "Supports an executive decision");
  const risk = RISK[area.key] || "low";
  const agents = AGENTS[area.key] || T("وكلاء المبيعات", "Sales agents");
  // Part 8 — every DATA area names its EDIT CAPABILITY: who can change this data, and where (honest;
  // most intelligence is read-only and is changed via the responsible director's own screen).
  const EDIT = { brain: T("المؤسس عبر عاصم", "Founder, via Assem"), growth: T("مدير الإيراد (الهدف والخطة)", "Revenue Director (target & plan)"), strategic: T("المؤسس عبر عاصم", "Founder, via Assem"), alerts: T("للقراءة فقط — عالجها مع المالك", "Read-only — act with the owner"), training: T("المؤسس يعتمد (لا تطبيق تلقائي)", "Founder approves (no auto-apply)"), deploy: T("المشغّل (اعتماد/تشغيل)", "Operator (credentials)"), intelligence: T("للقراءة فقط (تدقيق)", "Read-only (audit)"), vertical: T("مدير الإيراد (وسم القطاع)", "Revenue Director (vertical tags)"), orchestrator: T("للقراءة فقط (سجلات)", "Read-only (logs)"), performance: T("للقراءة فقط (مقاييس حية)", "Read-only (live metrics)"), knowledge: T("المؤسس/المدير التقني (يعتمد)", "Founder / CTO (approve)"), learning: T("للقراءة فقط (سجلّ)", "Read-only (history)"), awareness: T("للقراءة فقط", "Read-only") };
  const edit = EDIT[area.key] || T("للقراءة فقط", "Read-only");
  const Panel = area.panel ? window[area.panel] : null;
  const onAct = () => {
    if (area.deep) dataDeepLink(go, area.deep.screen, area.deep.tab ? { tab: area.deep.tab } : area.deep.revtab ? { revtab: area.deep.revtab } : area.deep.director ? { director: area.deep.director } : null);
    else if (area.director) dataDeepLink(go, "head", { director: area.director });
    else go(area.go || "head");
  };
  return (
    <div className="content__inner content__inner--wide fade-up" style={{ maxWidth: 1320 }}>
      <div style={{ marginBottom: 14 }}>
        <h4 style={{ margin: 0 }}>{T("مركز ذكاء المبيعات", "Sales Intelligence Center")}</h4>
        <div className="subtle" style={{ fontSize: 12.5 }}>{T("الأدلّة لا لوحات سلبية — كل رؤية لها معنى وأثر وخطر ومسؤول وإجراء بنقرة. البيانات تُثبت؛ المديرون يتصرّفون.", "Evidence, not passive dashboards — every insight names its meaning, impact, risk, owner and a one-click action. Data proves; Managers act.")}</div>
        {/* Part 10 — make explicit that DATA is a knowledge SOURCE, not a passive archive. */}
        <div className="row" style={{ gap: 7, marginTop: 8, fontSize: 11.5, padding: "7px 11px", borderRadius: 8, background: "var(--color-primary-tint-soft)", border: "1px solid var(--border-1)", alignItems: "center" }}>
          <Icon name="sparkles" size={14} style={{ color: "var(--color-secondary)", flexShrink: 0 }} />
          <span>{T("هذه البيانات مصدر معرفة يغذّي المديرين وعاصم والموظفين الأذكياء في توصياتهم وقراراتهم.", "This data is a knowledge source that feeds your Managers, Assem and the AI Agents in their recommendations and decisions.")}</span>
        </div>
      </div>
      <div className="row" style={{ gap: 14, alignItems: "flex-start", flexWrap: "wrap" }}>
        <div className="col" style={{ gap: 10, flex: "0 0 232px", minWidth: 212 }}>
          {DATA_SECTIONS.map(([sk, sar, sen]) => {
            const items = AREAS.filter((a) => a.section === sk);
            if (!items.length) return null;
            return (
              <div key={sk} className="col" style={{ gap: 3 }}>
                <div className="subtle" style={{ fontSize: 10.5, fontWeight: 700, textTransform: "uppercase", letterSpacing: 0.4, padding: "2px 4px", color: "var(--color-secondary)" }}>{lang === "ar" ? sar : sen}</div>
                {items.map((a) => (
                  <button key={a.key} onClick={() => setSel(a.key)} className="row" style={{ gap: 8, padding: "7px 11px", borderRadius: 10, border: "1px solid var(--border-1)", background: sel === a.key ? "var(--color-primary-tint-soft)" : "#fff", cursor: "pointer", textAlign: "start", fontSize: 12.5, fontWeight: sel === a.key ? 700 : 600, color: sel === a.key ? "var(--color-secondary)" : "var(--fg-2)" }}>
                    <Icon name={a.icon} size={15} />{a.title}
                  </button>
                ))}
              </div>
            );
          })}
        </div>
        <div className="col" style={{ gap: 12, flex: 1, minWidth: 320 }}>
          <Card><div className="between" style={{ padding: 6, gap: 10, flexWrap: "wrap" }}>
            <div className="col" style={{ gap: 2 }}>
              <div className="row" style={{ gap: 7, fontSize: 12.5 }}><Icon name="arrowRight" size={14} style={{ color: "var(--color-secondary)" }} /><b>{T("الإجراء الموصى به", "Recommended action")}:</b> {area.action}</div>
              <div className="row wrap subtle" style={{ fontSize: 11, gap: 10 }}>
                <span>{T("المسؤول", "Responsible")}: <b>{responsible}</b></span>
                <span>{T("الوكلاء المستفيدون", "Agents that use it")}: <b>{agents}</b></span>
                <span>{T("الأثر المتوقّع", "Expected impact")}: <b>{impact}</b></span>
                <span>{T("قابلية التعديل", "Edit capability")}: <b>{edit}</b></span>
                <span>{T("الخطر", "Risk")}: <Badge tone={risk === "low" ? "success" : risk === "medium" ? "warning" : "danger"}>{risk}</Badge></span>
              </div>
            </div>
            <Button size="sm" icon="arrowRight" onClick={onAct}>{T("اذهب للإجراء", "Go to action")}</Button>
          </div></Card>
          {Panel ? <Panel lang={lang} /> : (
            <Card><div className="col" style={{ gap: 6, padding: 8, alignItems: "center" }}>
              <Icon name={area.icon} size={28} style={{ color: "var(--color-secondary)" }} />
              <div className="subtle" style={{ fontSize: 12.5, textAlign: "center" }}>{T("هذه الشاشة تُفتح في مكانها الأصلي — اضغط الإجراء أعلاه.", "This screen opens in place — click the action above.")}</div>
            </div></Card>
          )}
        </div>
      </div>
    </div>
  );
}

function CustomersScreen() {
  const { lang } = useLang();
  const { go } = useApp();
  const T = (ar, en) => (lang === "ar" ? ar : en);
  const whyL = T("لماذا يهم", "Why it matters");
  const RL = { label: whyL, respLabel: T("المسؤول", "Responsible"), impactLabel: T("الأثر", "Impact"), riskLabel: T("الخطر", "Risk") };
  const csDir = T("مدير نجاح العملاء", "Customer Success Director");
  const cards = [
    { icon: "heart", title: T("نجاح العملاء", "Customer Success"), what: T("الصحّة، التجديدات، مخاطر التسرّب، التوسّع، المنطقة الحرجة.", "Health, renewals, churn risk, expansion, and the danger zone."), why: { ...RL, text: T("احمِ الإيراد المتكرر وأطلق التوسّع.", "Protect recurring revenue and trigger expansion.") }, responsible: csDir, impact: T("احتفاظ أعلى وتوسّع", "Higher retention + expansion"), risk: "low", cta: T("افتح نجاح العملاء", "Open Customer Success"), onClick: () => dataDeepLink(go, "validation", { revtab: "success" }) },
    { icon: "message", title: T("الدعم", "Support"), what: T("تذاكر دعم العملاء الحاليين + مخاطر التجديد وأثر الإيراد.", "Existing-customer support tickets with renewal-risk and revenue impact."), why: { ...RL, text: T("حلّ مشكلات العملاء قبل أن تتحوّل إلى تسرّب.", "Resolve customer issues before they become churn.") }, responsible: csDir, impact: T("منع التسرّب", "Prevent churn"), risk: "medium", cta: T("افتح الدعم", "Open Support"), onClick: () => go("support") },
    { icon: "trending", title: T("توجيه نجاح العملاء", "CS direction"), what: T("تحدّث مع مدير نجاح العملاء وأعطِ توجيهات الاحتفاظ.", "Chat with the Customer Success Director and give retention direction."), why: { ...RL, text: T("وجّه الاحتفاظ من مكان واحد.", "Direct retention from one place.") }, responsible: csDir, impact: T("احتفاظ موجّه", "Directed retention"), risk: "low", cta: T("افتح مدير نجاح العملاء", "Open the CS Director"), onClick: () => dataDeepLink(go, "head", { director: "customer_success" }) },
  ];
  return (
    <div className="content__inner content__inner--wide fade-up" style={{ maxWidth: 1100 }}>
      <div style={{ marginBottom: 14 }}><h4 style={{ margin: 0 }}>{T("العملاء", "CUSTOMERS")}</h4><div className="subtle" style={{ fontSize: 12.5 }}>{T("احمِ العملاء الحاليين ونمِّهم.", "Protect and grow your existing customers.")}</div></div>
      <div className="grid" style={{ gridTemplateColumns: "repeat(auto-fill, minmax(300px, 1fr))", gap: 12 }}>{cards.map((c, i) => <DataCard key={i} {...c} />)}</div>
    </div>
  );
}

// (ProductsScreen front-door removed — it was an unreachable dead route; the Products & Pricing config
//  is reached directly via DATA → "Products & Pricing" → AI Agents → Offers, so the extra door was redundant.)

// RevenueWorkflowPanel — Phase 10: action-first revenue flow. Set Target → Direction → Generate Plan →
// Review (AUTO/MANUAL per action) → Approve → Execute. 100% reuse: founderCommand (target),
// agentActions.executionPlan (the real Sales-Manager plan), execution approve/execute bridge.
function RevenueWorkflowPanel({ T }) {
  const lang = (document.documentElement.getAttribute("dir") === "rtl") ? "ar" : "en";
  const [step, setStep] = useDataState(1);
  const [target, setTarget] = useDataState("");
  const [direction, setDirection] = useDataState(null);   // "founder" | "ai"
  const [plan, setPlan] = useDataState(null);
  const [busy, setBusy] = useDataState(false);
  const [msg, setMsg] = useDataState(null);
  const tt = (ar, en) => (lang === "ar" ? ar : en);
  const setTargetCmd = () => {
    const n = Number(target || 0); if (n <= 0) { setMsg(tt("أدخل هدفاً صالحاً", "Enter a valid target")); return; }
    setBusy(true); setMsg(null);
    API.assem.founderCommand("set_revenue_target", n).then((r) => { if (r.ok) { setMsg(tt("تم ضبط الهدف", "Target set") + `: ${r.recalc && r.recalc.target ? r.recalc.target : n}`); setStep(2); } else setMsg(r.error || "failed"); }).catch((e) => setMsg(e.message)).finally(() => setBusy(false));
  };
  const generate = () => { setBusy(true); setMsg(null); API.agentActions.executionPlan().then((p) => { setPlan(p); setStep(4); }).catch((e) => setMsg(e.message)).finally(() => setBusy(false)); };
  const act = (fn, sig) => { setBusy(true); fn(sig).then(() => API.agentActions.executionPlan()).then((p) => setPlan(p)).catch((e) => setMsg(e.message)).finally(() => setBusy(false)); };
  const runAuto = () => { setBusy(true); API.agentActions.executionRunAuto().then(() => API.agentActions.executionPlan()).then((p) => setPlan(p)).catch((e) => setMsg(e.message)).finally(() => setBusy(false)); };
  const actions = (plan && (plan.actions || plan.plan && plan.plan.actions)) || [];
  const STEPS = [tt("الهدف", "Target"), tt("الاتجاه", "Direction"), tt("الخطة", "Plan"), tt("المراجعة", "Review"), tt("التنفيذ", "Execute")];
  return (
    <Card><div className="col" style={{ gap: 10, padding: 6 }}>
      <div className="between"><b style={{ fontSize: 14 }}>{tt("سير عمل الإيراد", "Revenue workflow")}</b>
        <div className="row" style={{ gap: 4 }}>{STEPS.map((s, i) => <span key={i} style={{ fontSize: 10.5, padding: "2px 7px", borderRadius: 6, background: step >= i + 1 ? "var(--color-primary-tint-soft)" : "var(--bg-2)", color: step >= i + 1 ? "var(--color-secondary)" : "var(--fg-4)", fontWeight: step === i + 1 ? 700 : 600 }}>{i + 1}. {s}</span>)}</div>
      </div>
      {/* Step 1 — Set Target */}
      <div className="row" style={{ gap: 6, alignItems: "center" }}>
        <span style={{ fontSize: 12.5, flex: "0 0 110px" }}>{tt("الهدف الشهري", "Monthly target")}</span>
        <input className="input" style={{ flex: "0 0 160px", fontSize: 12.5 }} type="number" placeholder="500000" value={target} onChange={(e) => setTarget(e.target.value)} />
        <Button size="sm" disabled={busy} onClick={setTargetCmd}>{tt("اضبط الهدف", "Set Target")}</Button>
      </div>
      {/* Step 2 — Direction */}
      {step >= 2 ? (
        <div className="row" style={{ gap: 8, alignItems: "center" }}>
          <span style={{ fontSize: 12.5, flex: "0 0 110px" }}>{tt("الاتجاه", "Direction")}</span>
          <Button size="sm" variant={direction === "founder" ? "primary" : "ghost"} onClick={() => { setDirection("founder"); setStep(3); }}>{tt("المؤسس يدوياً", "Founder Manual")}</Button>
          <Button size="sm" variant={direction === "ai" ? "primary" : "ghost"} onClick={() => { setDirection("ai"); setStep(3); }}>{tt("مدير الإيراد (ذكاء)", "Revenue Director AI")}</Button>
        </div>
      ) : null}
      {/* Step 3 — Generate Plan */}
      {step >= 3 ? <Button size="sm" disabled={busy} onClick={generate} style={{ alignSelf: "flex-start" }}>{tt("ولّد الخطة", "Generate Plan")}</Button> : null}
      {/* Step 4/5/6 — Review + Approve + Execute */}
      {step >= 4 && plan ? (
        <div className="col" style={{ gap: 6 }}>
          {direction === "ai" ? <Button size="sm" variant="ghost" icon="zap" disabled={busy} onClick={runAuto} style={{ alignSelf: "flex-start" }}>{tt("شغّل الإجراءات التلقائية", "Run AUTO actions")}</Button> : null}
          {actions.length ? actions.slice(0, 8).map((a, i) => {
            const auto = a.approvalPolicy && a.approvalPolicy.tier === "auto";
            return (
              <div key={a.signature || i} className="between" style={{ fontSize: 12, padding: "6px 8px", borderRadius: 8, background: "var(--bg-2)", border: "1px solid var(--border-1)", gap: 8, flexWrap: "wrap" }}>
                <span className="row" style={{ gap: 6 }}><Badge tone={auto ? "success" : "warning"}>{auto ? "AUTO" : "MANUAL"}</Badge>{a.title || a.type}{a.status ? <span className="subtle" style={{ fontSize: 11 }}>· {a.status}</span> : null}</span>
                <span className="row" style={{ gap: 4 }}>
                  {a.executable && a.status !== "executed" ? <Button size="sm" variant="ghost" disabled={busy} onClick={() => act(API.agentActions.executionApprove, a.signature)}>{tt("اعتمد", "Approve")}</Button> : null}
                  {a.executable && a.status !== "executed" ? <Button size="sm" disabled={busy} onClick={() => act(API.agentActions.executionExecute, a.signature)}>{tt("نفّذ", "Execute")}</Button> : null}
                </span>
              </div>
            );
          }) : <div className="subtle" style={{ fontSize: 12 }}>{tt("لا إجراءات قابلة للتنفيذ الآن.", "No executable actions right now.")}</div>}
        </div>
      ) : null}
      {msg ? <div className="subtle" style={{ fontSize: 11.5, color: "var(--color-secondary)" }}>{msg}</div> : null}
      <div className="subtle" style={{ fontSize: 10.5, color: "var(--color-orange)" }}>{tt("كل إجراء يمرّ عبر جسر التنفيذ المعتمد — المال يتطلّب موافقة المؤسس؛ لا تنفيذ تلقائي للمال.", "Every action goes through the approved execution bridge — money needs founder approval; no auto-spend.")}</div>
    </div></Card>
  );
}

// CUSTOMER JOURNEY board (P1/P2/P7) — the unified Lead→Payment→Onboarding→Renewal funnel, read-only over the
// existing engines (journeyOverview + commerceOverview). Every stage is REAL; payment_verified renders only
// from a verified payment (no operator toggle), so this board can never show a fake-paid order.
// Phase 18 — the Customer Journey as a LEARNING screen: per-campaign funnel + classified bottleneck + emotion +
// lost-deal reasons + winning factors + Revenue Director recommendations. Read-only; every figure real-or-NED.
function CampaignLearningSection({ lang }) {
  const tt = (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 [camps, setCamps] = React.useState(null);
  const [sel, setSel] = React.useState(null);
  const [intel, setIntel] = React.useState(null);
  const [learn, setLearn] = React.useState(null);
  React.useEffect(() => { API.campaigns.list().then((r) => { const list = (r.campaigns || r || []).filter((c) => c && c.id); setCamps(list); if (list[0]) setSel(list[0].id); }).catch(() => setCamps([])); }, []);
  React.useEffect(() => { if (!sel) return; setIntel(null); setLearn(null); API.assem.campaignIntelligence(sel).then(setIntel).catch(() => setIntel({ error: true })); API.assem.campaignLearning(sel).then(setLearn).catch(() => setLearn({ error: true })); }, [sel]);
  if (camps === null) return <Card><div className="skel" style={{ height: 80, borderRadius: 10 }} /></Card>;
  if (!camps.length) return <Card><div className="subtle" style={{ padding: 12, fontSize: 12.5 }}>{tt("لا حملات بعد — أنشئ حملة لترى قصّتها هنا.", "No campaigns yet — create one to see its story here.")}</div></Card>;
  const f = intel && !intel.error ? intel.funnel : null;
  const bn = intel && !intel.error ? intel.bottleneck : null;
  return (
    <Card><div className="col" style={{ gap: 8, padding: 10 }}>
      <div className="between" style={{ flexWrap: "wrap", gap: 8 }}>
        <strong style={{ fontSize: 13 }}>{tt("تعلّم من الحملات", "Learn from your campaigns")}</strong>
        <select value={sel || ""} onChange={(e) => setSel(e.target.value)} style={{ fontSize: 12, padding: "5px 8px", borderRadius: 8, border: "1px solid var(--border-1)", maxWidth: 220 }}>
          {camps.map((c) => <option key={c.id} value={c.id}>{c.name || c.id}</option>)}
        </select>
      </div>
      <span className="subtle" style={{ fontSize: 11 }}>{tt("لماذا تنجح الحملة ولماذا تفشل — كل حملة لها قمعها واختناقها ومشاعرها ودروسها.", "Why a campaign succeeds and why it fails — each campaign's own funnel, bottleneck, emotions, and lessons.")}</span>
      {!intel ? <div className="skel" style={{ height: 60, borderRadius: 10 }} /> : intel.error ? <span className="subtle" style={{ fontSize: 12 }}>—</span> : (
        <div className="col" style={{ gap: 8 }}>
          {/* funnel */}
          {f && (f.stages || []).length ? (
            <div className="row" style={{ gap: 5, flexWrap: "wrap" }}>
              {(f.stages || []).map((s, i) => (
                <div key={i} className="card" style={{ padding: 7, textAlign: "center", flex: "1 1 60px", minWidth: 56 }}>
                  <div style={{ fontSize: 14, fontWeight: 800 }}>{s.count}</div>
                  <div className="subtle" style={{ fontSize: 9 }}>{L(s.label) || s.key}{s.conversion != null ? ` · ${s.conversion}%` : ""}</div>
                </div>
              ))}
            </div>
          ) : <span className="subtle" style={{ fontSize: 12 }}>{tt("لا يكفي العملاء بعد لقياس القمع.", "Not enough leads yet to measure the funnel.")}</span>}
          {/* classified bottleneck */}
          {bn ? (
            <div className="row" style={{ gap: 8, background: "var(--bg-2)", border: "1px solid var(--border-1)", borderRadius: 10, padding: "8px 10px", flexWrap: "wrap" }}>
              <Badge tone="danger">{tt("أكبر اختناق", "Biggest bottleneck")}: {L(bn.label)}</Badge>
              <span className="subtle" style={{ fontSize: 11.5 }}>{L((bn.evidence || [])[0])} — {tt("الحل", "Fix")}: {L(bn.fix)} ({tt("المالك", "owner")}: {bn.owner})</span>
            </div>
          ) : null}
          {/* emotion + lost + won badges */}
          <div className="row" style={{ gap: 5, flexWrap: "wrap", fontSize: 11 }}>
            {intel.emotion && (intel.emotion.topRejecting || []).length ? <Badge tone="orange">{tt("أكثر رفضاً", "Rejects most")}: {L(intel.emotion.topRejecting[0].label)}</Badge> : null}
            {intel.emotion && (intel.emotion.topConverting || []).length ? <Badge tone="green">{tt("أكثر تحويلاً", "Converts most")}: {L(intel.emotion.topConverting[0].label)}</Badge> : null}
            {intel.lostDeals && intel.lostDeals.biggestReason ? <Badge tone="danger">{tt("أكبر سبب خسارة", "Top loss")}: {L(intel.lostDeals.biggestReason.label)}</Badge> : null}
            {intel.winningFactors && (intel.winningFactors.factors || []).length ? <Badge tone="lime">{tt("عامل فوز", "Won via")}: {L(intel.winningFactors.factors[0].label)}</Badge> : null}
          </div>
          {/* Revenue Director recommendations */}
          {learn && !learn.error && (learn.recommendations || []).length ? (
            <div className="col" style={{ gap: 3 }}>
              <strong style={{ fontSize: 12 }}>{tt("توصيات مدير الإيراد", "Revenue Director recommendations")}</strong>
              {(learn.recommendations || []).slice(0, 3).map((r, i) => <div key={i} style={{ fontSize: 11.5 }}>→ <span className="subtle">{L(r.recommendation)}</span> <Badge tone="neutral">{tt("بموافقة المؤسس", "approval")}</Badge></div>)}
            </div>
          ) : null}
        </div>
      )}
    </div></Card>
  );
}

function CustomerJourneyScreen() {
  const lang = (document.documentElement.getAttribute("dir") === "rtl") ? "ar" : "en";
  const tt = (ar, en) => (lang === "ar" ? ar : en);
  const [ov, setOv] = React.useState(null);
  const [board, setBoard] = React.useState(null);
  const [err, setErr] = React.useState(false);
  React.useEffect(() => {
    let live = true;
    Promise.all([API.metrics.journeyOverview(), API.metrics.commerceOverview()])
      .then(([o, b]) => { if (live) { setOv(o); setBoard(b); } })
      .catch(() => { if (live) setErr(true); });
    return () => { live = false; };
  }, []);
  const STAGE_LABEL = { lead: tt("عميل محتمل", "Lead"), qualification: tt("تأهيل", "Qualification"), recommendation: tt("توصية", "Recommendation"), offer: tt("عرض", "Offer"), payment: tt("دفع", "Payment"), booking: tt("حجز", "Booking"), onboarding: tt("تهيئة", "Onboarding"), success: tt("نجاح العميل", "Success"), renewal: tt("تجديد", "Renewal"), closed_lost: tt("خاسرة", "Closed-lost") };
  const TYPE_LABEL = { product_purchase: tt("شراء منتج", "Product"), service_purchase: tt("شراء خدمة", "Service"), appointment: tt("موعد", "Appointment"), consultation: tt("استشارة", "Consultation"), subscription: tt("اشتراك", "Subscription") };
  const CSTATE_STAGE = { checkout_started: "offer", item_selected: "offer", customer_details_collected: "offer", pending_payment: "payment", payment_verified: "payment", order_confirmed: "onboarding", booking_pending: "booking", booking_confirmed: "booking", onboarding_started: "onboarding", abandoned_checkout: "offer" };
  const kpi = (label, val, tone) => (
    <Card key={label}><div className="col" style={{ gap: 2, padding: 10, alignItems: "center", minWidth: 92 }}>
      <div style={{ fontSize: 22, fontWeight: 700, color: tone ? "var(--color-" + tone + ")" : "var(--text-1)" }}>{val}</div>
      <div className="subtle" style={{ fontSize: 11, textAlign: "center" }}>{label}</div>
    </div></Card>
  );
  return (
    <div className="col" style={{ gap: 12 }}>
      <Card><div className="col" style={{ gap: 4, padding: 10 }}>
        <div className="row" style={{ gap: 8, alignItems: "center" }}><Icon name="target" /><strong>{tt("رحلة العميل", "Customer Journey")}</strong></div>
        <div className="subtle" style={{ fontSize: 12 }}>{tt("عميل محتمل ← عرض ← دفع ← تهيئة ← تجديد — كل ذلك داخل واتساب. كل مرحلة حقيقية؛ لا يظهر طلب كمدفوع إلا بدفع مؤكَّد.", "Lead → Offer → Payment → Onboarding → Renewal — all inside WhatsApp. Every stage is real; an order shows paid only on a verified payment.")}</div>
      </div></Card>
      {err ? <Card><div className="subtle" style={{ padding: 12 }}>{tt("تعذّر تحميل الرحلات.", "Couldn't load journeys.")}</div></Card> : null}
      {ov && !ov.started ? (
        <Card><div className="col" style={{ padding: 14, gap: 4, alignItems: "center" }}>
          <Icon name="inbox" /><div className="subtle" style={{ fontSize: 12.5, textAlign: "center" }}>{tt("لا رحلات بدأت بعد — تظهر مع تقدّم المحادثات نحو عرض.", "No journeys started yet — they appear as conversations move toward an offer.")}</div>
        </div></Card>
      ) : null}
      {ov && ov.started ? (
        <div className="row" style={{ gap: 8, flexWrap: "wrap" }}>
          {kpi(tt("بدأت", "Started"), ov.started)}
          {kpi(tt("اكتملت", "Completed"), ov.completed, "success")}
          {kpi(tt("بانتظار الدفع", "Pending payment"), ov.pendingPayment, ov.pendingPayment ? "orange" : null)}
          {kpi(tt("حجوزات معلّقة", "Bookings pending"), ov.bookingsPending)}
          {kpi(tt("متروكة", "Abandoned"), ov.abandoned, ov.abandoned ? "danger" : null)}
        </div>
      ) : null}
      {ov && ov.started ? (
        <Card><div className="col" style={{ gap: 8, padding: 10 }}>
          <strong style={{ fontSize: 13 }}>{tt("حسب النوع", "By journey type")}</strong>
          <div className="row" style={{ gap: 6, flexWrap: "wrap" }}>
            {Object.keys(ov.byType || {}).map((k) => (
              <Badge key={k} tone={ov.byType[k] ? "info" : "neutral"}>{(TYPE_LABEL[k] || k) + ": " + (ov.byType[k] || 0)}</Badge>
            ))}
          </div>
          <strong style={{ fontSize: 13, marginTop: 4 }}>{tt("حسب المرحلة", "By stage")}</strong>
          <div className="row" style={{ gap: 6, flexWrap: "wrap" }}>
            {Object.keys(ov.byStage || {}).filter((k) => ov.byStage[k]).map((k) => (
              <Badge key={k} tone="neutral">{(STAGE_LABEL[k] || k) + ": " + ov.byStage[k]}</Badge>
            ))}
          </div>
        </div></Card>
      ) : null}
      {board && (board.items || []).length ? (
        <Card><div className="col" style={{ gap: 6, padding: 10 }}>
          <strong style={{ fontSize: 13 }}>{tt("الرحلات الجارية", "In-flight journeys")}</strong>
          {(board.items || []).slice(0, 30).map((it) => (
            <div key={it.opportunityId} className="between" style={{ fontSize: 12, padding: "6px 8px", borderRadius: 8, background: "var(--bg-2)", border: "1px solid var(--border-1)", gap: 8, flexWrap: "wrap" }}>
              <span className="row" style={{ gap: 6 }}><Badge tone="neutral">{it.kind || "product"}</Badge><span className="subtle">{it.opportunityId}</span></span>
              <Badge tone={it.state === "pending_payment" ? "orange" : it.state === "abandoned_checkout" ? "danger" : "info"}>{STAGE_LABEL[CSTATE_STAGE[it.state] || "offer"] || it.state}</Badge>
            </div>
          ))}
        </div></Card>
      ) : null}
      {/* Phase 18 — the journey is a LEARNING screen: per-campaign funnel/bottleneck/emotion/lessons. */}
      <CampaignLearningSection lang={lang} />
      <div className="subtle" style={{ fontSize: 10.5, color: "var(--color-orange)" }}>{tt("القراءة فقط — تتقدّم الرحلة عبر المحادثة والدفع المؤكَّد فقط؛ لا تعليم يدوي كاذب.", "Read-only — a journey advances only through the conversation + a verified payment; no manual fake-paid.")}</div>
    </div>
  );
}

// ───────────────────────────────────────────────────────────────────────────────────────────
// P3·P3 — SALES FUNNEL INTELLIGENCE (the Revenue Director OWNS it). Consumes the real sales-funnel
// engine (no new data): the unified Leads → Conversations → Qualified → Meetings → Proposals → Closed
// funnel with per-stage conversion / drop-off, the BOTTLENECK, its root-cause attribution (agent /
// objection / channel / segment), a derived (recommendation-only) action, and a per-campaign breakdown.
// HONEST: conversions are sample-gated (NED below threshold); "closed" = claimed-won, kept distinct from
// recognized cash; script attribution is surfaced as a real gap, never fabricated.
// ───────────────────────────────────────────────────────────────────────────────────────────
function funnelRecommendedAction(bottleneckLabel, attribution, tt) {
  const a = attribution || {};
  const topAgent = (a.byAgent || []).find((r) => r.key && r.key !== "unattributed");
  const topObj = (a.byObjection || [])[0];
  const topChan = (a.byChannel || []).find((r) => r.key && r.key !== "unattributed");
  if (topObj && topObj.key) return tt(`جهّز الوكلاء للتعامل مع اعتراض «${topObj.key}» — أكثر سبب توقّف عند ${bottleneckLabel}.`, `Equip agents to handle the “${topObj.key}” objection — the top blocker at ${bottleneckLabel}.`);
  if (topAgent && topAgent.key) return tt(`درّب «${topAgent.key}» — أغلب المتعثّرين عند ${bottleneckLabel} لديه.`, `Coach “${topAgent.key}” — most leads stalled at ${bottleneckLabel} are theirs.`);
  if (topChan && topChan.key) return tt(`راجع قناة «${topChan.key}» — أغلب التسرّب عند ${bottleneckLabel} منها.`, `Review the “${topChan.key}” channel — most drop-off at ${bottleneckLabel} is there.`);
  return tt(`افحص مرحلة ${bottleneckLabel} — هنا يتوقّف أغلب العملاء.`, `Investigate the ${bottleneckLabel} stage — that's where most leads stall.`);
}
function SalesFunnelPanel({ T }) {
  const lang = (document.documentElement.getAttribute("dir") === "rtl") ? "ar" : "en";
  const tt = (ar, en) => (lang === "ar" ? ar : en);
  const sl = (s) => (lang === "ar" ? s.ar : s.en) || s.key;
  const [data, setData] = React.useState(null);
  const [err, setErr] = React.useState(null);
  const [camps, setCamps] = React.useState(null);
  const [showCamps, setShowCamps] = React.useState(false);
  React.useEffect(() => { let a = true; API.metrics.salesFunnel().then((d) => a && setData(d)).catch((e) => a && setErr(e.message)); return () => { a = false; }; }, []);
  const loadCamps = () => { setShowCamps((v) => !v); if (!camps) API.metrics.campaignFunnels().then(setCamps).catch(() => {}); };
  if (err) return <Card><EmptyState icon="alert" title={tt("تعذّر تحميل القمع", "Could not load funnel")} subtitle={err} /></Card>;
  if (!data) return <Card><div className="skel" style={{ height: 160, borderRadius: 10 }} /></Card>;
  const stages = data.stages || [];
  const maxCount = Math.max(1, ...(stages.map((s) => s.count || 0)));
  const bl = data.bottleneck ? stages.find((s) => s.key === data.bottleneck.stage) : null;
  const blLabel = bl ? sl(bl) : "";
  const money = (n) => (typeof n === "number" ? n.toLocaleString() : n);
  return (
    <Card><div className="col" style={{ gap: 12, padding: 6 }}>
      <div className="between" style={{ gap: 8, flexWrap: "wrap" }}>
        <div className="row" style={{ gap: 8, alignItems: "center" }}><Icon name="target" size={16} style={{ color: "var(--color-secondary)" }} /><b style={{ fontSize: 14 }}>{tt("ذكاء قمع المبيعات", "Sales Funnel Intelligence")}</b></div>
        <Badge tone="info">{tt("المالك: مدير الإيراد", "Owner: Revenue Director")}</Badge>
      </div>
      {data.note ? <div className="subtle" style={{ fontSize: 11.5 }}>{lang === "ar" ? data.note.ar : data.note.en}</div> : null}

      {/* The funnel — Leads → … → Closed with per-stage count + conversion / drop-off to the next stage. */}
      <div className="col" style={{ gap: 4 }}>
        {stages.map((s, i) => {
          const w = Math.round(((s.count || 0) / maxCount) * 100);
          const isBl = bl && s.key === bl.key;
          return (
            <div key={s.key} className="col" style={{ gap: 2 }}>
              <div className="row" style={{ gap: 8, alignItems: "center" }}>
                <span style={{ flex: "0 0 116px", fontSize: 12, fontWeight: isBl ? 700 : 600, color: isBl ? "var(--color-orange)" : "var(--fg-2)" }}>{sl(s)}</span>
                <div style={{ flex: 1, height: 22, borderRadius: 6, background: "var(--bg-2)", overflow: "hidden", position: "relative" }}>
                  <div style={{ width: w + "%", height: "100%", background: isBl ? "var(--color-orange)" : "var(--color-secondary)", opacity: isBl ? 0.85 : 0.55, transition: "width .3s" }} />
                  <span style={{ position: "absolute", insetInlineStart: 8, top: 2, fontSize: 12, fontWeight: 700 }}>{s.count}</span>
                </div>
              </div>
              {i < stages.length - 1 ? (
                <div className="subtle" style={{ fontSize: 10.5, paddingInlineStart: 124 }}>
                  {s.conversion != null
                    ? <span>↓ {s.conversion}% {tt("تحويل", "convert")} · {s.dropOff}% {tt("تسرّب", "drop-off")}</span>
                    : <span>↓ {tt("بيانات غير كافية للتحويل", "not enough data for conversion")}</span>}
                </div>
              ) : null}
            </div>
          );
        })}
      </div>

      {/* Bottleneck + root-cause attribution + a derived recommended action (review before acting). */}
      {data.bottleneck && bl ? (
        <div className="col" style={{ gap: 6, padding: "9px 11px", borderRadius: "var(--radius-md)", background: "var(--color-orange-tint, #fff5ec)", border: "1px solid var(--color-orange)" }}>
          <div className="row" style={{ gap: 7, alignItems: "center" }}><Icon name="alert" size={14} style={{ color: "var(--color-orange)" }} /><b style={{ fontSize: 12.5 }}>{tt("الاختناق", "Bottleneck")}: {blLabel}</b><span className="subtle" style={{ fontSize: 11 }}>{data.bottleneck.conversion}% {tt("تحويل", "convert")} · {data.bottleneck.dropOff}% {tt("تسرّب", "drop-off")}</span></div>
          {data.attribution ? (
            <div className="row" style={{ gap: 12, flexWrap: "wrap", fontSize: 11 }}>
              {(data.attribution.byAgent || []).filter((r) => r.key && r.key !== "unattributed")[0] ? <span><b>{tt("الوكيل", "Agent")}:</b> {data.attribution.byAgent.filter((r) => r.key !== "unattributed")[0].key} ×{data.attribution.byAgent.filter((r) => r.key !== "unattributed")[0].count}</span> : null}
              {(data.attribution.byChannel || []).filter((r) => r.key && r.key !== "unattributed")[0] ? <span><b>{tt("القناة", "Channel")}:</b> {data.attribution.byChannel.filter((r) => r.key !== "unattributed")[0].key}</span> : null}
              {(data.attribution.byObjection || [])[0] ? <span><b>{tt("الاعتراض", "Objection")}:</b> {data.attribution.byObjection[0].key} ×{data.attribution.byObjection[0].count}</span> : null}
              {(data.attribution.bySegment || []).filter((r) => r.key && r.key !== "unattributed")[0] ? <span><b>{tt("الشريحة", "Segment")}:</b> {data.attribution.bySegment.filter((r) => r.key !== "unattributed")[0].key}</span> : null}
            </div>
          ) : null}
          <div className="row" style={{ gap: 6, alignItems: "flex-start" }}><Icon name="sparkles" size={13} style={{ color: "var(--color-secondary)", marginTop: 1, flexShrink: 0 }} /><span style={{ fontSize: 11.5 }}><b>{tt("إجراء مقترح", "Recommended action")}:</b> {funnelRecommendedAction(blLabel, data.attribution, tt)} <span className="subtle">({tt("راجعه قبل التنفيذ", "review before acting")})</span></span></div>
        </div>
      ) : (
        <div className="subtle" style={{ fontSize: 11.5, padding: "8px 11px", borderRadius: "var(--radius-md)", background: "var(--bg-2)", border: "1px solid var(--border-1)" }}>{tt("لا توجد بيانات كافية لتحديد الاختناق بعد — نحتاج عيّنة كافية في كل مرحلة.", "Not enough data to pinpoint a bottleneck yet — need a real sample at each stage.")}</div>
      )}

      {/* Claimed-won revenue, kept HONESTLY distinct from recognized cash. */}
      <div className="row" style={{ gap: 14, flexWrap: "wrap", fontSize: 11.5 }}>
        <span><b>{tt("مغلقة (مُعلَنة)", "Closed (claimed)")}:</b> {data.claimedWon} · {money(data.claimedWonRevenue)}</span>
        {data.overallConversion != null ? <span><b>{tt("تحويل إجمالي", "Overall")}:</b> {data.overallConversion}%</span> : null}
      </div>
      <div className="subtle" style={{ fontSize: 10 }}>{lang === "ar" ? data.revenueNote.ar : data.revenueNote.en}</div>
      <div className="subtle" style={{ fontSize: 10, color: "var(--color-orange)" }}>{lang === "ar" ? data.scriptAttributionGap.ar : data.scriptAttributionGap.en}</div>

      {/* Per-campaign funnels — each campaign has its OWN funnel + bottleneck (the mandate). */}
      <div className="col" style={{ gap: 8 }}>
        <Button size="sm" variant="ghost" onClick={loadCamps}>{showCamps ? tt("إخفاء القمع لكل حملة", "Hide per-campaign funnels") : tt("عرض القمع لكل حملة", "Show per-campaign funnels")}</Button>
        {showCamps ? (
          !camps ? <div className="skel" style={{ height: 60, borderRadius: 8 }} /> : (
            <div className="col" style={{ gap: 8 }}>
              {[...(camps.campaigns || []), camps.organic ? { campaignId: "__organic", name: camps.organic.name, funnel: camps.organic.funnel } : null].filter(Boolean).map((c) => {
                const f = c.funnel || {}; const cs = f.stages || [];
                const cbl = f.bottleneck ? cs.find((s) => s.key === f.bottleneck.stage) : null;
                const nm = typeof c.name === "string" ? c.name : (lang === "ar" ? c.name.ar : c.name.en);
                return (
                  <div key={c.campaignId} className="col" style={{ gap: 4, padding: "8px 10px", borderRadius: 8, background: "var(--bg-2)", border: "1px solid var(--border-1)" }}>
                    <div className="between" style={{ gap: 8, flexWrap: "wrap" }}><b style={{ fontSize: 12 }}>{nm}</b>{cbl ? <Badge tone="orange">{tt("اختناق", "Bottleneck")}: {sl(cbl)}</Badge> : <span className="subtle" style={{ fontSize: 10.5 }}>{tt("عيّنة غير كافية", "small sample")}</span>}</div>
                    <div className="row" style={{ gap: 6, flexWrap: "wrap", fontSize: 10.5 }}>{cs.map((s) => <span key={s.key} className="subtle">{sl(s)}: <b style={{ color: "var(--fg-2)" }}>{s.count}</b></span>)}</div>
                    {cbl ? <span style={{ fontSize: 10.5 }}><b>{tt("إجراء", "Action")}:</b> {funnelRecommendedAction(sl(cbl), f.attribution, tt)}</span> : null}
                  </div>
                );
              })}
            </div>
          )
        ) : null}
      </div>
    </div></Card>
  );
}

window.DataScreen = DataScreen;
window.CustomersScreen = CustomersScreen;
window.RevenueWorkflowPanel = RevenueWorkflowPanel;
window.CustomerJourneyScreen = CustomerJourneyScreen;
window.SalesFunnelPanel = SalesFunnelPanel;
