// screens-learning.jsx — Phase 5 Learning & Optimization Platform UI.
// One hub screen with internal tabs. Every panel renders LIVE data from /api/learning/* and
// /api/experiments/*; nothing is hardcoded. Honest empty states everywhere — when a source is
// thin (e.g. <2 snapshots, <2 closed deals) the UI says so instead of faking a number.

const LRN = (lang, ar, en) => (lang === "ar" ? ar : en);
function lsar(n) { return window.fmtCurrency(n); }
function pctTxt(n) { return n == null ? "—" : n + "%"; }

function LrnEmpty({ icon, title, body }) {
  return <div style={{ padding: "26px 16px", textAlign: "center", color: "var(--fg-3)" }}>
    <Icon name={icon || "inbox"} size={26} style={{ color: "var(--fg-disabled)", marginBottom: 8 }} />
    <div style={{ fontWeight: 700, fontSize: 14, color: "var(--fg-1)" }}>{title}</div>
    {body && <div style={{ fontSize: 13, marginTop: 4, lineHeight: 1.5, maxWidth: 460, margin: "4px auto 0" }}>{body}</div>}
  </div>;
}
function LrnStat({ label, value, sub, tone }) {
  return <div className="card" style={{ padding: 16 }}>
    <div style={{ fontSize: 12, color: "var(--fg-4)", fontWeight: 600 }}>{label}</div>
    <div style={{ fontSize: 24, fontWeight: 800, letterSpacing: "-0.02em", marginTop: 4, color: tone || "var(--fg-1)" }}>{value}</div>
    {sub && <div style={{ fontSize: 12, color: "var(--fg-4)", marginTop: 2 }}>{sub}</div>}
  </div>;
}

const LEARNING_TABS = [
  { key: "executive", ar: "تنفيذي", en: "Executive" },
  { key: "agents", ar: "إرشاد الوكلاء", en: "Agent Coaching" },
  { key: "winloss", ar: "الفوز/الخسارة", en: "Win / Loss" },
  { key: "objections", ar: "الاعتراضات", en: "Objections" },
  { key: "followups", ar: "المتابعات", en: "Follow-ups" },
  { key: "experiments", ar: "التجارب", en: "Experiments" },
  { key: "playbooks", ar: "أدلة الإغلاق", en: "Playbooks" },
  { key: "insights", ar: "تحسين الإيراد", en: "Revenue Insights" },
];

function LearningScreen() {
  const { lang } = useLang();
  useStore();
  const T = (ar, en) => LRN(lang, ar, en);
  const [tab, setTab] = React.useState("executive");

  // Load the view backing this tab on mount / tab change (cached in DATA.LEARNING).
  React.useEffect(() => {
    if (tab === "experiments") { Actions.loadExperiments(); return; }
    const viewMap = { executive: "executive", agents: "training", winloss: "winloss", objections: "objections", followups: "followups", playbooks: "playbooks", insights: "insights" };
    const v = viewMap[tab]; if (v) Actions.loadLearning(v);
  }, [tab]);

  return (
    <div className="content__inner fade-up">
      <div className="between" style={{ marginBottom: 18, flexWrap: "wrap", gap: 10 }}>
        <div>
          <h4 style={{ marginBottom: 4 }}>{T("مركز التعلّم", "Learning Center")}</h4>
          <div className="subtle" style={{ fontSize: 13 }}>{T("كل رقم مشتق من صفقات وأحداث حقيقية — لا تقديرات وهمية.", "Every figure is derived from real deals and events — no fabricated analytics.")}</div>
        </div>
      </div>

      {/* tab bar */}
      <div className="chipscroll-wrap" style={{ marginBottom: 16 }}>
        <div className="chipscroll" style={{ gap: 6, paddingBottom: 6 }}>
          {LEARNING_TABS.map((tb) => (
            <button key={tb.key} className={"btn btn--sm " + (tab === tb.key ? "btn--dark" : "btn--subtle")} onClick={() => setTab(tb.key)} style={{ flexShrink: 0 }}>
              {T(tb.ar, tb.en)}
            </button>
          ))}
        </div>
      </div>

      {tab === "executive" && <ExecutivePanel T={T} />}
      {tab === "agents" && <AgentTrainingPanel T={T} />}
      {tab === "winloss" && <WinLossPanel T={T} />}
      {tab === "objections" && <ObjectionsPanel T={T} />}
      {tab === "followups" && <FollowupsPanel T={T} />}
      {tab === "experiments" && <ExperimentsPanel T={T} />}
      {tab === "playbooks" && <PlaybooksPanel T={T} />}
      {tab === "insights" && <RevenueInsightsPanel T={T} />}
    </div>
  );
}

// ---------- Executive (Part 10) ----------
function ExecutivePanel({ T }) {
  useStore();
  const d = (DATA.LEARNING && DATA.LEARNING.executive) || null;
  if (!d) return <Card flush><LrnEmpty icon="trending" title={T("جارٍ التحميل…", "Loading executive view…")} /></Card>;
  if (d.error) return <Card flush><LrnEmpty icon="alert" title={T("تعذّر التحميل", "Couldn't load")} body={d.error} /></Card>;
  const h = d.headline || {};
  return (
    <div className="col" style={{ gap: 16 }}>
      <div className="grid" style={{ gridTemplateColumns: "repeat(auto-fit, minmax(160px, 1fr))", gap: 12 }}>
        <LrnStat label={T("الإيراد المُحقّق", "Revenue generated")} value={lsar(h.revenueGenerated)} />
        <LrnStat label={T("خط الأنابيب المتوقع", "Weighted pipeline")} value={lsar(h.pipelineExpected)} />
        <LrnStat label={T("معدّل الفوز", "Win rate")} value={pctTxt(h.winRate)} />
        <LrnStat label={T("معدّل التحويل", "Conversion")} value={pctTxt(h.conversionRate)} />
        <LrnStat label={T("الإيراد المعرّض للخطر", "Revenue at risk")} value={lsar(h.revenueAtRisk)} tone={h.revenueAtRisk > 0 ? "var(--color-orange)" : undefined} />
        <LrnStat label={T("جودة التعلّم", "Learning quality")} value={(h.learningQuality && h.learningQuality.score) || 0} sub={(h.learningQuality && h.learningQuality.verdict) || ""} />
      </div>

      <Card title={T("اتجاه الأداء", "Performance trend")}>
        {d.trend && d.trend.available
          ? <div>
              <div className="row" style={{ gap: 18, flexWrap: "wrap" }}>
                <TrendDelta T={T} label={T("الإيراد", "Revenue")} v={d.trend.change.revenue} money />
                <TrendDelta T={T} label={T("معدّل الفوز", "Win rate")} v={d.trend.change.winRate} pct />
                <TrendDelta T={T} label={T("التحويل", "Conversion")} v={d.trend.change.conversion} pct />
                <TrendDelta T={T} label={T("جودة التعلّم", "Learning quality")} v={d.trend.change.learningQuality} />
              </div>
              <div style={{ fontSize: 12, color: "var(--fg-4)", marginTop: 8 }}>{T("من", "From")} {d.trend.from} → {d.trend.to} · {d.trend.snapshotCount} {T("لقطة", "snapshots")}</div>
            </div>
          : <LrnEmpty icon="clock" title={T("يتم بناء السجل", "Building history")} body={(d.trendMeta && d.trendMeta.reason) || T("تظهر خطوط الاتجاه بعد التقاط لقطتين على الأقل (يوم بعد يوم).", "Trend lines appear once at least 2 daily snapshots exist.")} />}
        {d.mostImproved && <div className="row" style={{ gap: 8, marginTop: 12, padding: "10px 12px", background: "var(--bg-2)", borderRadius: 10 }}>
          <Icon name="trophy" size={16} style={{ color: "var(--color-secondary)" }} />
          <span style={{ fontSize: 13 }}>{T("الأكثر تحسّنًا:", "Most improved:")} <b>{d.mostImproved.name}</b> +{d.mostImproved.delta} {T("نقطة جودة", "quality pts")} ({d.mostImproved.from}→{d.mostImproved.to})</span>
        </div>}
      </Card>

      <div className="grid" style={{ gridTemplateColumns: "repeat(auto-fit, minmax(300px, 1fr))", gap: 16 }}>
        <Card title={T("لوحة المتصدّرين", "Leaderboard")} flush>
          <div style={{ padding: "4px 0" }}>
            {(d.leaderboard || []).length ? d.leaderboard.map((a, i) => (
              <div key={a.agentId} className="between" style={{ padding: "10px 16px", borderBottom: "1px solid var(--border-1)" }}>
                <div className="row" style={{ gap: 10 }}><span style={{ width: 18, color: "var(--fg-4)", fontWeight: 700 }}>{i + 1}</span><Avatar name={a.name} size="sm" /><span style={{ fontWeight: 600, fontSize: 13 }}>{a.name}</span></div>
                <div className="row" style={{ gap: 12 }}><span style={{ fontSize: 13, fontWeight: 700 }}>{lsar(a.metrics.revenueGenerated)}</span><Badge tone="neutral">{pctTxt(a.metrics.conversionRate)}</Badge></div>
              </div>
            )) : <LrnEmpty title={T("لا توجد بيانات أداء بعد", "No performance data yet")} />}
          </div>
        </Card>
        <Card title={T("أهم الاعتراضات", "Top objections")} flush>
          <div style={{ padding: "4px 0" }}>
            {(d.topObjections || []).length ? d.topObjections.map((o) => (
              <div key={o.objection} className="between" style={{ padding: "10px 16px", borderBottom: "1px solid var(--border-1)" }}>
                <span style={{ fontSize: 13, fontWeight: 600 }}>{o.objection}</span>
                <div className="row" style={{ gap: 8 }}><span style={{ fontSize: 12, color: "var(--fg-4)" }}>{o.faced}× </span><Badge tone={o.winRate >= 60 ? "lime" : o.winRate <= 30 ? "red" : "neutral"}>{pctTxt(o.winRate)}</Badge></div>
              </div>
            )) : <LrnEmpty title={T("لا اعتراضات مسجّلة بعد", "No objections recorded yet")} />}
          </div>
        </Card>
      </div>

      {(d.interventions || []).length > 0 && <Card title={T("تدخّلات مقترحة", "Suggested interventions")} flush>
        <div style={{ padding: "4px 0" }}>
          {d.interventions.slice(0, 6).map((iv, i) => (
            <div key={i} style={{ padding: "10px 16px", borderBottom: "1px solid var(--border-1)" }}>
              <div style={{ fontWeight: 600, fontSize: 13 }}>{iv.contact || iv.name || iv.leadName || "—"}</div>
              <div style={{ fontSize: 12, color: "var(--fg-3)", marginTop: 2 }}>{iv.reason || iv.recommendation || iv.action || ""}</div>
            </div>
          ))}
        </div>
      </Card>}
    </div>
  );
}
function TrendDelta({ T, label, v, money, pct }) {
  const up = (v || 0) > 0, flat = (v || 0) === 0;
  const col = flat ? "var(--fg-4)" : up ? "var(--color-secondary)" : "var(--color-orange)";
  const val = money ? lsar(Math.abs(v)) : (Math.abs(v) + (pct ? "%" : ""));
  return <div><div style={{ fontSize: 12, color: "var(--fg-4)" }}>{label}</div><div style={{ fontSize: 16, fontWeight: 800, color: col }}>{flat ? "±0" : (up ? "▲ " : "▼ ") + val}</div></div>;
}

// ---------- Agent Training (Parts 1 + 6) ----------
function AgentTrainingPanel({ T }) {
  useStore();
  const [sel, setSel] = React.useState(null);
  const d = (DATA.LEARNING && DATA.LEARNING.training) || null;
  if (!d) return <Card flush><LrnEmpty icon="bot" title={T("جارٍ التحميل…", "Loading…")} /></Card>;
  const rows = d.leaderboard || [];
  const selected = sel && rows.find((r) => r.agentId === sel);
  return (
    <div className="grid" style={{ gridTemplateColumns: selected ? "repeat(auto-fit, minmax(320px, 1fr))" : "1fr", gap: 16 }}>
      <Card title={T("ملفات إرشاد الوكلاء", "Agent coaching profiles")} flush>
        <div style={{ overflowX: "auto" }}>
          <table className="tbl" style={{ width: "100%", fontSize: 13, borderCollapse: "collapse", minWidth: 640 }}>
            <thead><tr style={{ textAlign: "start", color: "var(--fg-4)" }}>
              {[T("الوكيل", "Agent"), T("إيراد", "Revenue"), T("فوز", "Won"), T("خسارة", "Lost"), T("تحويل", "Conv."), T("متوسط الصفقة", "Avg deal"), T("الدورة", "Cycle"), T("الجودة", "Quality")].map((h, i) => <th key={i} style={{ padding: "8px 12px", fontWeight: 600, whiteSpace: "nowrap" }}>{h}</th>)}
            </tr></thead>
            <tbody>
              {rows.length ? rows.map((a) => { const m = a.metrics; return (
                <tr key={a.agentId} onClick={() => setSel(a.agentId)} style={{ cursor: "pointer", borderTop: "1px solid var(--border-1)", background: sel === a.agentId ? "var(--bg-2)" : "transparent" }}>
                  <td style={{ padding: "8px 12px" }}><div className="row" style={{ gap: 8 }}><Avatar name={a.name} size="sm" /><span style={{ fontWeight: 600 }}>{a.name}</span></div></td>
                  <td style={{ padding: "8px 12px", fontWeight: 700 }}>{lsar(m.revenueGenerated)}</td>
                  <td style={{ padding: "8px 12px", color: "var(--color-secondary)" }}>{m.won}</td>
                  <td style={{ padding: "8px 12px", color: "var(--color-orange)" }}>{m.lost}</td>
                  <td style={{ padding: "8px 12px" }}>{pctTxt(m.conversionRate)}</td>
                  <td style={{ padding: "8px 12px" }}>{m.avgDealSize ? lsar(m.avgDealSize) : "—"}</td>
                  <td style={{ padding: "8px 12px" }}>{m.avgSalesCycleDays != null ? m.avgSalesCycleDays + "d" : "—"}</td>
                  <td style={{ padding: "8px 12px" }}>{m.responseQuality != null ? <span>{m.responseQuality}{typeof m.qualityTrend === "number" && m.qualityTrend !== 0 ? <span style={{ color: m.qualityTrend > 0 ? "var(--color-secondary)" : "var(--color-orange)", fontSize: 11 }}> {m.qualityTrend > 0 ? "▲" : "▼"}{Math.abs(m.qualityTrend)}</span> : null}</span> : "—"}</td>
                </tr>
              ); }) : <tr><td colSpan={8}><LrnEmpty title={T("لا يوجد وكلاء بعد", "No agents yet")} /></td></tr>}
            </tbody>
          </table>
        </div>
      </Card>
      {selected && <Card title={selected.name} action={<button className="btn btn--subtle btn--sm" onClick={() => setSel(null)}>{T("إغلاق", "Close")}</button>}>
        <div className="col" style={{ gap: 12 }}>
          {selected.selfCoaching && <div style={{ padding: "10px 12px", background: "var(--bg-2)", borderRadius: 10, fontSize: 13 }}><b>{T("التوجيه المُحقَن في برومبت هذا الوكيل:", "Coaching injected into this agent's prompt:")}</b><div style={{ marginTop: 4, color: "var(--fg-3)" }}>{selected.selfCoaching}</div></div>}
          <div>
            <div style={{ fontWeight: 700, fontSize: 13, marginBottom: 6 }}>{T("انتصارات أخيرة", "Recent wins")}</div>
            {selected.timeline.wins.length ? selected.timeline.wins.map((w, i) => <div key={i} style={{ fontSize: 12, color: "var(--fg-3)", padding: "3px 0" }}>✓ {w.lead} — {w.service || ""} {w.angle ? `· ${w.angle}` : ""}</div>) : <div className="muted" style={{ fontSize: 12 }}>{T("لا انتصارات مسجّلة", "No wins recorded")}</div>}
          </div>
          <div>
            <div style={{ fontWeight: 700, fontSize: 13, marginBottom: 6 }}>{T("خسائر أخيرة", "Recent losses")}</div>
            {selected.timeline.losses.length ? selected.timeline.losses.map((w, i) => <div key={i} style={{ fontSize: 12, color: "var(--fg-3)", padding: "3px 0" }}>✗ {w.lead} — {w.reason || ""}</div>) : <div className="muted" style={{ fontSize: 12 }}>{T("لا خسائر مسجّلة", "No losses recorded")}</div>}
          </div>
          {selected.timeline.objectionsHandled.length > 0 && <div>
            <div style={{ fontWeight: 700, fontSize: 13, marginBottom: 6 }}>{T("اعتراضات تم تجاوزها", "Objections overcome")}</div>
            <div className="row" style={{ gap: 6, flexWrap: "wrap" }}>{selected.timeline.objectionsHandled.map((o) => <Badge key={o} tone="lime">{o}</Badge>)}</div>
          </div>}
        </div>
      </Card>}
    </div>
  );
}

// ---------- Win / Loss (Part 2) ----------
function WinLossPanel({ T }) {
  useStore();
  const d = (DATA.LEARNING && DATA.LEARNING.winloss) || null;
  if (!d) return <Card flush><LrnEmpty icon="trophy" title={T("جارٍ التحميل…", "Loading…")} /></Card>;
  if (!d.available) return <Card flush><LrnEmpty icon="trophy" title={T("لا توجد صفقات مغلقة بعد", "No closed deals yet")} body={T("يظهر تحليل الفوز/الخسارة بمجرد إغلاق صفقات (فوز/خسارة).", "Win/Loss analysis appears once deals are closed (won or lost).")} /></Card>;
  const wf = d.winningFactors, lf = d.lossFactors, r = d.reports;
  const ListCard = ({ title, items, render }) => <Card title={title} flush><div style={{ padding: "4px 0" }}>{items && items.length ? items.map((it, i) => <div key={i} style={{ padding: "8px 16px", borderBottom: "1px solid var(--border-1)", fontSize: 13 }}>{render(it)}</div>) : <LrnEmpty title={T("لا بيانات", "No data")} />}</div></Card>;
  return (
    <div className="col" style={{ gap: 16 }}>
      <div className="grid" style={{ gridTemplateColumns: "repeat(auto-fit, minmax(170px, 1fr))", gap: 12 }}>
        <LrnStat label={T("معدّل الفوز", "Win rate")} value={pctTxt(r.winRate)} sub={`${r.won} ${T("فوز", "won")} · ${r.lost} ${T("خسارة", "lost")}`} />
        <LrnStat label={T("أعلى عرض تحويلًا", "Top converting offer")} value={r.highestConvertingOffer ? r.highestConvertingOffer.key : "—"} sub={r.highestConvertingOffer ? pctTxt(r.highestConvertingOffer.winRate) : ""} />
        <LrnStat label={T("أفضل وكيل", "Top agent")} value={r.highestConvertingAgent ? r.highestConvertingAgent.name : "—"} sub={r.highestConvertingAgent ? lsar(r.highestConvertingAgent.revenue) : ""} />
        <LrnStat label={T("أفضل تسلسل متابعة", "Best follow-up seq.")} value={r.highestConvertingFollowUpSequence ? r.highestConvertingFollowUpSequence.sequence : "—"} sub={r.highestConvertingFollowUpSequence ? pctTxt(r.highestConvertingFollowUpSequence.winRate) : ""} />
      </div>
      <div className="grid" style={{ gridTemplateColumns: "repeat(auto-fit, minmax(300px, 1fr))", gap: 16 }}>
        <ListCard title={T("عوامل الفوز", "Winning factors")} items={wf.topWinningPlays} render={(p) => <div className="between"><span>{p.key}</span><Badge tone="lime">{p.count}×</Badge></div>} />
        <ListCard title={T("أسباب الخسارة", "Loss reasons")} items={lf.topReasons} render={(p) => <div className="between"><span>{p.key}</span><Badge tone="red">{p.count}×</Badge></div>} />
      </div>
      <div className="grid" style={{ gridTemplateColumns: "repeat(auto-fit, minmax(300px, 1fr))", gap: 16 }}>
        <ListCard title={T("اعتراضات تم تجاوزها", "Objections overcome")} items={wf.objectionsOvercome} render={(o) => <div className="between"><span>{o.objection} <span className="muted">({o.bestAngle})</span></span><Badge tone="lime">{pctTxt(o.winRate)}</Badge></div>} />
        <ListCard title={T("ثغرات التأهيل (BANT)", "Qualification gaps (BANT)")} items={lf.bantGaps} render={(p) => <div className="between"><span>{p.key}</span><Badge tone="orange">{p.count}×</Badge></div>} />
      </div>
    </div>
  );
}

// ---------- Objections (Part 5) ----------
function ObjectionsPanel({ T }) {
  useStore();
  const d = (DATA.LEARNING && DATA.LEARNING.objections) || null;
  if (!d) return <Card flush><LrnEmpty icon="shield" title={T("جارٍ التحميل…", "Loading…")} /></Card>;
  if (!d.available) return <Card flush><LrnEmpty icon="shield" title={T("لا اعتراضات بعد", "No objection data yet")} body={T("تُبنى قاعدة معرفة الاعتراضات من الصفقات المغلقة الحقيقية.", "The objection knowledge base is built from real closed deals.")} /></Card>;
  return (
    <Card title={T("قاعدة معرفة الاعتراضات", "Objection knowledge base")} flush>
      <div style={{ overflowX: "auto" }}>
        <table className="tbl" style={{ width: "100%", fontSize: 13, borderCollapse: "collapse", minWidth: 640 }}>
          <thead><tr style={{ color: "var(--fg-4)" }}>{[T("اعتراض", "Objection"), T("واجهه", "Faced"), T("فوز", "Won"), T("خسارة", "Lost"), T("معدل الفوز", "Win rate"), T("أفضل زاوية", "Best angle"), T("أثر الإيراد", "Revenue impact"), T("الحالة", "Status")].map((h, i) => <th key={i} style={{ padding: "8px 12px", textAlign: "start", fontWeight: 600, whiteSpace: "nowrap" }}>{h}</th>)}</tr></thead>
          <tbody>
            {d.objections.map((o) => (
              <tr key={o.objection} style={{ borderTop: "1px solid var(--border-1)" }}>
                <td style={{ padding: "8px 12px", fontWeight: 600 }}>{o.objection}</td>
                <td style={{ padding: "8px 12px" }}>{o.faced}</td>
                <td style={{ padding: "8px 12px", color: "var(--color-secondary)" }}>{o.won}</td>
                <td style={{ padding: "8px 12px", color: "var(--color-orange)" }}>{o.lost}</td>
                <td style={{ padding: "8px 12px" }}><Badge tone={o.winRate >= 60 ? "lime" : o.winRate <= 30 ? "red" : "neutral"}>{pctTxt(o.winRate)}</Badge></td>
                <td style={{ padding: "8px 12px", color: "var(--fg-3)" }}>{o.bestAngle || "—"}</td>
                <td style={{ padding: "8px 12px", fontWeight: 700 }}>{lsar(o.revenueImpact)}</td>
                <td style={{ padding: "8px 12px" }}><Badge tone={o.status === "promote" ? "lime" : o.status === "demote" ? "red" : "neutral"}>{o.status}</Badge></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </Card>
  );
}

// ---------- Follow-ups (Part 4) ----------
function FollowupsPanel({ T }) {
  useStore();
  const d = (DATA.LEARNING && DATA.LEARNING.followups) || null;
  if (!d) return <Card flush><LrnEmpty icon="clock" title={T("جارٍ التحميل…", "Loading…")} /></Card>;
  if (!d.available) return <Card flush><LrnEmpty icon="clock" title={T("لا متابعات بعد", "No follow-ups yet")} body={T("تظهر فعالية المتابعات بمجرد جدولتها للعملاء.", "Follow-up effectiveness appears once follow-ups are scheduled.")} /></Card>;
  const Tbl = ({ title, rows, keyLabel }) => <Card title={title} flush><div style={{ overflowX: "auto", padding: "4px 0" }}>{rows && rows.length ? rows.map((r, i) => (
    <div key={i} className="between" style={{ padding: "8px 16px", borderBottom: "1px solid var(--border-1)", fontSize: 13 }}>
      <span style={{ fontWeight: 600 }}>{r.key || r.sequence}</span>
      <div className="row" style={{ gap: 10 }}><span className="muted" style={{ fontSize: 12 }}>{(r.won || 0)}/{(r.won || 0) + (r.lost || 0) || r.total || 0}</span><Badge tone={r.winRate >= 50 ? "lime" : "neutral"}>{pctTxt(r.winRate)}</Badge></div>
    </div>
  )) : <LrnEmpty title={T("لا بيانات", "No data")} />}</div></Card>;
  return (
    <div className="col" style={{ gap: 16 }}>
      <div className="grid" style={{ gridTemplateColumns: "repeat(auto-fit, minmax(160px, 1fr))", gap: 12 }}>
        <LrnStat label={T("إجمالي المتابعات", "Total follow-ups")} value={d.totalFollowUps} />
        <LrnStat label={T("مكتملة", "Completed")} value={d.completed} />
        <LrnStat label={T("معلّقة", "Pending")} value={d.pending} />
        <LrnStat label={T("أفضل قناة", "Best channel")} value={d.recommendations.bestChannel ? d.recommendations.bestChannel.key : "—"} sub={d.recommendations.bestChannel ? pctTxt(d.recommendations.bestChannel.winRate) : ""} />
      </div>
      <div className="grid" style={{ gridTemplateColumns: "repeat(auto-fit, minmax(280px, 1fr))", gap: 16 }}>
        <Tbl title={T("حسب القناة", "By channel")} rows={d.byChannel} />
        <Tbl title={T("حسب الاهتمام", "By interest")} rows={d.byInterest} />
        <Tbl title={T("حسب طول التسلسل", "By sequence length")} rows={d.bySequenceLength} />
      </div>
      <div style={{ fontSize: 12, color: "var(--fg-4)" }}>{d.note}</div>
    </div>
  );
}

// ---------- Playbooks (Part 7) ----------
function PlaybooksPanel({ T }) {
  useStore();
  const d = (DATA.LEARNING && DATA.LEARNING.playbooks) || null;
  if (!d) return <Card flush><LrnEmpty icon="clipboard" title={T("جارٍ التحميل…", "Loading…")} /></Card>;
  return (
    <div className="col" style={{ gap: 14 }}>
      <div className="subtle" style={{ fontSize: 13 }}>{T("أدلة إغلاق تتولّد من نتائج حقيقية لكل منتج — تتطوّر مع كل صفقة تُغلق.", "Closing playbooks generated from real outcomes per product — they evolve with every closed deal.")}</div>
      <div className="grid" style={{ gridTemplateColumns: "repeat(auto-fit, minmax(320px, 1fr))", gap: 16 }}>
        {(d.playbooks || []).map((p) => (
          <Card key={p.product} title={p.label}>
            {!p.available
              ? <LrnEmpty icon="clipboard" title={T("بيانات غير كافية", "Not enough data")} body={p.reason} />
              : <div className="col" style={{ gap: 10, fontSize: 13 }}>
                  <div className="row" style={{ gap: 12 }}><Badge tone={p.winRate >= 50 ? "lime" : "neutral"}>{pctTxt(p.winRate)} {T("فوز", "win")}</Badge><span className="muted">{p.won}/{p.won + p.lost}</span><span style={{ fontWeight: 700 }}>{lsar(p.revenue)}</span></div>
                  {p.closingTactics.length > 0 && <div><b>{T("تكتيكات إغلاق رابحة", "Winning closing tactics")}</b><div style={{ marginTop: 4 }}>{p.closingTactics.map((c) => <Badge key={c.play} tone="lime" style={{ marginInlineEnd: 4 }}>{c.play} ({c.timesWon})</Badge>)}</div></div>}
                  {p.objectionHandling.length > 0 && <div><b>{T("معالجة الاعتراضات", "Objection handling")}</b>{p.objectionHandling.map((o) => <div key={o.objection} style={{ color: "var(--fg-3)", marginTop: 2 }}>• {o.objection} → {o.bestAngle || "—"} <span className="muted">({pctTxt(o.winRate)})</span></div>)}</div>}
                  {p.lossReasons.length > 0 && <div><b>{T("احذر من", "Avoid (loses deals)")}</b>{p.lossReasons.map((l) => <div key={l.key} style={{ color: "var(--color-orange)", marginTop: 2 }}>• {l.key} ({l.count}×)</div>)}</div>}
                  <div className="muted" style={{ fontSize: 12 }}>{p.meetingStrategy.recommendation}{p.avgFollowUpsToWin != null ? ` · ${T("متوسط المتابعات للفوز", "avg follow-ups to win")}: ${p.avgFollowUpsToWin}` : ""}</div>
                </div>}
          </Card>
        ))}
      </div>
    </div>
  );
}

// ---------- Revenue Insights (Part 9) ----------
function RevenueInsightsPanel({ T }) {
  useStore();
  const d = (DATA.LEARNING && DATA.LEARNING.insights) || null;
  if (!d) return <Card flush><LrnEmpty icon="dollar" title={T("جارٍ التحميل…", "Loading…")} /></Card>;
  return (
    <div className="col" style={{ gap: 16 }}>
      <LrnStat label={T("إجمالي الإيراد المعرّض للخطر", "Total revenue at risk")} value={lsar(d.totalRevenueAtRisk)} tone={d.totalRevenueAtRisk > 0 ? "var(--color-orange)" : undefined} />
      <Card title={T("رؤى تحسين الإيراد", "Revenue improvement insights")} flush>
        <div style={{ padding: "4px 0" }}>
          {(d.insights || []).length ? d.insights.map((it, i) => (
            <div key={i} style={{ padding: "12px 16px", borderBottom: "1px solid var(--border-1)" }}>
              <div className="between"><div className="row" style={{ gap: 8 }}><Badge tone={it.severity === "high" ? "red" : "orange"}>{it.severity}</Badge><span style={{ fontWeight: 700, fontSize: 14 }}>{it.title}</span></div><span style={{ fontWeight: 800 }}>{lsar(it.revenueAtRisk)}</span></div>
              <div style={{ fontSize: 13, color: "var(--fg-3)", marginTop: 4, lineHeight: 1.5 }}>{it.explanation}</div>
            </div>
          )) : <LrnEmpty icon="checkcircle" title={T("لا تسريبات إيراد مكتشفة", "No revenue leaks detected")} body={T("لا متابعات متأخرة ولا عروض راكدة الآن.", "No overdue follow-ups or stalled proposals right now.")} />}
        </div>
      </Card>
      {(d.strategicRecommendations || []).length > 0 && <Card title={T("توصيات استراتيجية", "Strategic recommendations")} flush>
        <div style={{ padding: "4px 0" }}>
          {d.strategicRecommendations.slice(0, 8).map((s, i) => (
            <div key={i} style={{ padding: "10px 16px", borderBottom: "1px solid var(--border-1)" }}>
              <div style={{ fontWeight: 600, fontSize: 13 }}>{s.title || s.type}</div>
              <div style={{ fontSize: 12, color: "var(--fg-3)", marginTop: 2 }}>{s.detail || s.why || s.reason || ""}</div>
            </div>
          ))}
        </div>
      </Card>}
      <div style={{ fontSize: 12, color: "var(--fg-4)" }}>{d.note}</div>
    </div>
  );
}

// ---------- Experiments (Part 3) ----------
function ExperimentsPanel({ T }) {
  useStore();
  const [creating, setCreating] = React.useState(false);
  const [resultsFor, setResultsFor] = React.useState(null);
  const [results, setResults] = React.useState(null);
  const exps = DATA.EXPERIMENTS || [];

  const openResults = async (id) => {
    setResultsFor(id); setResults(null);
    try { const r = await Actions.experimentResults(id); setResults(r); } catch (e) { setResults({ error: (e && e.message) || "failed" }); }
  };
  const setStatus = async (id, status) => { await Actions.updateExperiment(id, { status }); if (resultsFor === id) openResults(id); };

  return (
    <div className="col" style={{ gap: 16 }}>
      <div className="between">
        <div className="subtle" style={{ fontSize: 13 }}>{T("جرّب برومبتات مختلفة بأمان. التعيين حتمي حسب العميل والقياس من النتائج الحقيقية. الافتراضي: لا تجربة نشطة = لا تغيير في السلوك.", "Safely test different prompts. Assignment is deterministic per lead and measurement is from real outcomes. Default: no active experiment = no behavior change.")}</div>
        <Button size="sm" icon="plus" onClick={() => setCreating(true)}>{T("تجربة جديدة", "New experiment")}</Button>
      </div>

      {creating && <NewExperimentForm T={T} onClose={() => setCreating(false)} />}

      <Card title={T("التجارب", "Experiments")} flush>
        <div style={{ padding: "4px 0" }}>
          {exps.length ? exps.map((e) => (
            <div key={e.id} style={{ padding: "12px 16px", borderBottom: "1px solid var(--border-1)" }}>
              <div className="between" style={{ flexWrap: "wrap", gap: 8 }}>
                <div className="row" style={{ gap: 10 }}>
                  <Badge tone={e.status === "active" ? "lime" : e.status === "completed" ? "neutral" : e.status === "paused" ? "orange" : "neutral"}>{e.status}</Badge>
                  <span style={{ fontWeight: 700, fontSize: 14 }}>{e.name}</span>
                  <span className="muted" style={{ fontSize: 12 }}>{(e.variants || []).length} {T("متغيّرات", "variants")}</span>
                </div>
                <div className="row" style={{ gap: 6 }}>
                  {e.status === "draft" && <button className="btn btn--sm btn--primary" onClick={() => setStatus(e.id, "active")}>{T("تفعيل", "Activate")}</button>}
                  {e.status === "active" && <button className="btn btn--sm btn--subtle" onClick={() => setStatus(e.id, "paused")}>{T("إيقاف مؤقت", "Pause")}</button>}
                  {e.status === "paused" && <button className="btn btn--sm btn--primary" onClick={() => setStatus(e.id, "active")}>{T("استئناف", "Resume")}</button>}
                  {(e.status === "active" || e.status === "paused") && <button className="btn btn--sm btn--subtle" onClick={() => setStatus(e.id, "completed")}>{T("إنهاء", "Complete")}</button>}
                  <button className="btn btn--sm btn--dark" onClick={() => openResults(e.id)}>{T("النتائج", "Results")}</button>
                </div>
              </div>
              {e.hypothesis && <div style={{ fontSize: 12, color: "var(--fg-4)", marginTop: 4 }}>{e.hypothesis}</div>}
              <div className="row" style={{ gap: 6, marginTop: 6, flexWrap: "wrap" }}>{(e.variants || []).map((v) => <Badge key={v.id} tone={v.isControl ? "neutral" : "purple"}>{v.name}{v.isControl ? " (control)" : ""}</Badge>)}</div>
              {resultsFor === e.id && <ExperimentResults T={T} results={results} />}
            </div>
          )) : <LrnEmpty icon="zap" title={T("لا توجد تجارب بعد", "No experiments yet")} body={T("أنشئ تجربة A/B لمقارنة نسختين من برومبت الإغلاق.", "Create an A/B test to compare two versions of a closing prompt.")} />}
        </div>
      </Card>
    </div>
  );
}

function ExperimentResults({ T, results }) {
  if (!results) return <div className="muted" style={{ fontSize: 12, marginTop: 8 }}>{T("جارٍ حساب النتائج…", "Computing results…")}</div>;
  if (results.error) return <div style={{ fontSize: 12, marginTop: 8, color: "var(--color-orange)" }}>{results.error}</div>;
  return (
    <div style={{ marginTop: 10, padding: 12, background: "var(--bg-2)", borderRadius: 10 }}>
      <div style={{ overflowX: "auto" }}>
        <table className="tbl" style={{ width: "100%", fontSize: 12, borderCollapse: "collapse" }}>
          <thead><tr style={{ color: "var(--fg-4)" }}>{["Variant", "n", "Won", "Lost", "Win rate", "Revenue"].map((h, i) => <th key={i} style={{ padding: "4px 8px", textAlign: "start" }}>{h}</th>)}</tr></thead>
          <tbody>{(results.variants || []).map((v) => (
            <tr key={v.variantId} style={{ borderTop: "1px solid var(--border-1)" }}>
              <td style={{ padding: "4px 8px", fontWeight: 600 }}>{v.variantName}{v.isControl ? " (control)" : ""}</td>
              <td style={{ padding: "4px 8px" }}>{v.n}</td>
              <td style={{ padding: "4px 8px", color: "var(--color-secondary)" }}>{v.won}</td>
              <td style={{ padding: "4px 8px", color: "var(--color-orange)" }}>{v.lost}</td>
              <td style={{ padding: "4px 8px" }}>{pctTxt(v.winRate)}</td>
              <td style={{ padding: "4px 8px", fontWeight: 700 }}>{lsar(v.revenue)}</td>
            </tr>
          ))}</tbody>
        </table>
      </div>
      <div style={{ fontSize: 12, marginTop: 8, fontWeight: 600 }}>{results.comparison ? results.comparison.conclusion : ""}</div>
      <div style={{ fontSize: 11, color: "var(--fg-4)", marginTop: 2 }}>{T("الحد الأدنى للعيّنة لكل متغيّر:", "Min sample per variant:")} {results.minSample} · {results.totalClosed} {T("صفقة مغلقة موسومة", "closed deals tagged")}</div>
    </div>
  );
}

function NewExperimentForm({ T, onClose }) {
  const [name, setName] = React.useState("");
  const [hypothesis, setHypothesis] = React.useState("");
  const [directive, setDirective] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState("");
  const submit = async () => {
    setErr("");
    if (!name.trim() || !directive.trim()) { setErr(T("الاسم وتوجيه المتغيّر مطلوبان.", "Name and the variant directive are required.")); return; }
    setBusy(true);
    try {
      const r = await Actions.createExperiment({
        name, hypothesis,
        variants: [
          { name: T("الأساس (الحالي)", "Control (current)"), isControl: true },
          { name: T("المتغيّر", "Variant"), promptOverride: { extraDirective: directive } },
        ],
      });
      if (r && r.ok) { onClose(); } else { setErr((r && r.error) || "failed"); }
    } catch (e) { setErr((e && e.message) || "failed"); } finally { setBusy(false); }
  };
  return (
    <Card title={T("تجربة A/B جديدة", "New A/B experiment")} action={<button className="btn btn--subtle btn--sm" onClick={onClose}>{T("إلغاء", "Cancel")}</button>}>
      <div className="col" style={{ gap: 10 }}>
        <input className="input" placeholder={T("اسم التجربة", "Experiment name")} value={name} onChange={(e) => setName(e.target.value)} />
        <input className="input" placeholder={T("الفرضية (اختياري)", "Hypothesis (optional)")} value={hypothesis} onChange={(e) => setHypothesis(e.target.value)} />
        <textarea className="input" rows={2} placeholder={T("توجيه المتغيّر — يُضاف إلى برومبت الوكيل (مثال: اطلب الدفع في أول رد).", "Variant directive — appended to the agent prompt (e.g. ask for payment in the first reply).")} value={directive} onChange={(e) => setDirective(e.target.value)} />
        <div className="subtle" style={{ fontSize: 12 }}>{T("سيُقارن هذا المتغيّر مقابل السلوك الحالي (مجموعة تحكّم). التعيين حتمي حسب العميل.", "This variant is compared against current behavior (a control group). Assignment is deterministic per lead.")}</div>
        {err && <div style={{ color: "var(--color-orange)", fontSize: 12 }}>{err}</div>}
        <div className="row" style={{ gap: 8 }}><Button size="sm" onClick={submit} disabled={busy}>{busy ? T("جارٍ…", "Saving…") : T("إنشاء كمسودة", "Create as draft")}</Button></div>
      </div>
    </Card>
  );
}
