/* Bonyan ERP — Dashboard / home (لوحة مدير النظام) */
function DashboardScreen({ onNav }) {
  const I = window.BnyIcon;
  const D = window.BnyData;
  const { StatCard, Card, Badge, Money, Button } = window.BonyanDesignSystem_ad3ca0;
  const isMobile = window.useBnyMobile();
  window.useBnyInvoices(); // إعادة الرسم عند تعديل/حذف فاتورة من أي مكان
  const openInv = (no) => window.BnyOpenInvoice(no);

  // اشتقاقات حيّة
  const outOfStock = window.BnyOutOfStockMaterials();
  const lowStock = window.BnyLowStockMaterials();
  const topProducts = window.BnyTopProductsThisMonth(5);
  const stagnant = window.BnyStagnantMaterials();
  const stagDays = D.stagnantDays || 30;
  const aging = window.BnyDebtAging();
  // يشمل ديون الدولار، ويرتّب حسب القيمة المكافئة بالدينار (١٠٠$ = ١٥٠٬٠٠٠ د.ع)
  const debts = D.customers.filter((c) => c.balance > 0 || c.balanceUsd > 0).sort((a, b) => window.BnyDebtIqd(b) - window.BnyDebtIqd(a));
  // مؤشرات حيّة (تظهر صفرًا للمشترك الجديد — لا أرقام وهمية)
  const _today = new Date().toISOString().slice(0, 10);
  const salesMonth = (D.invoices || []).filter((i) => i.type === "sale" && i.cur === "iqd" && (i.date || "").slice(0, 7) === _today.slice(0, 7))
    .reduce((s, i) => s + (Number(i.total) || 0), 0);
  const invToday = (D.invoices || []).filter((i) => i.date === _today).length;
  const [showStockModal, setShowStockModal] = React.useState(false);
  const [selCustomer, setSelCustomer] = React.useState(null);

  const quick = [
    { label: "فاتورة بيع", icon: I.invoice, accent: true, go: "pos" },
    { label: "إضافة عميل", icon: I.users, go: "customers" },
    { label: "تسديد دين", icon: I.wallet, go: "customers" },
    { label: "فاتورة شراء", icon: I.supplier, go: "suppliers" },
  ];

  const sectionTwo = { display: "grid", gridTemplateColumns: isMobile ? "1fr" : "1fr 1fr", gap: "var(--space-7)" };

  return (
    <div style={{ padding: isMobile ? "var(--space-4)" : "var(--space-8)", display: "flex", flexDirection: "column", gap: isMobile ? "var(--space-4)" : "var(--space-7)" }}>
      {/* quick actions */}
      <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr 1fr" : "repeat(4,1fr)", gap: "var(--space-5)" }}>
        {quick.map((q) => (
          <button key={q.label} onClick={() => onNav(q.go)} className={"bny-quick" + (q.accent ? " bny-quick--accent" : "")}>
            <span className="bny-quick__icon"><q.icon size={22} /></span>
            <span className="bny-quick__label">{q.label}</span>
            <span className="bny-quick__chev" aria-hidden="true"><I.chevron size={18} /></span>
          </button>
        ))}
      </div>

      {/* KPIs — بطاقة تنبيه المخزون بارزة وقابلة للنقر */}
      <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr 1fr" : "repeat(4,1fr)", gap: "var(--space-5)" }}>
        <StatCard label="مبيعات الشهر (د.ع)" icon={<I.chart size={16} />} value={salesMonth.toLocaleString("en-US")} unit="د.ع" />
        <StatCard label="ديون معلقة" icon={<I.wallet size={16} />} value={debts.reduce((s, c) => s + c.balance, 0).toLocaleString("en-US")} unit="د.ع" />
        <StatCard label="فواتير اليوم" icon={<I.invoice size={16} />} value={String(invToday)} />
        <StockAlertCard outCount={outOfStock.length} lowCount={lowStock.length} onClick={() => setShowStockModal(true)} />
      </div>

      {/* تنبيه: مواد تحتاج شراء (نافدة + ستنفد قريبًا) — قصير + عرض الكل */}
      <ReorderCard items={lowStock} onSeeAll={() => { window.BnyPendingInvFilter = "reorder"; onNav("inventory"); }} />

      {/* الرسم البياني — منحنى خطي مقارن مع Tooltip */}
      <Card title="اتجاه الأرباح الشهرية" actions={<Button variant="ghost" size="sm" onClick={() => onNav("reports")}>التقارير</Button>}>
        <p style={{ color: "var(--text-muted)", fontSize: 12.5, margin: "0 0 6px" }}>مرّر أو انقر فوق أي شهر لعرض الرقم التفصيلي.</p>
        <window.BnyLineChart
          isMobile={isMobile}
          labels={D.profit.map((p) => p.m)}
          series={[{ name: "الأرباح", color: "var(--brand)", values: D.profit.map((p) => p.v) }]}
          unit="مليون د.ع" />
      </Card>

      {/* أعلى الديون المعلقة + أعمار الديون */}
      <div style={sectionTwo}>
        <Card title="أعلى الديون المعلقة" actions={<Button variant="ghost" size="sm" onClick={() => onNav("customers")}>الكل</Button>}>
          <div style={{ display: "flex", flexDirection: "column" }}>
            {debts.map((c, i) => {
              const over = c.balance > c.limit;
              return (
                <div key={c.id} onClick={() => setSelCustomer(c)} title="اعرض معلومات العميل"
                  onMouseEnter={(e) => (e.currentTarget.style.background = "var(--surface-hover)")}
                  onMouseLeave={(e) => (e.currentTarget.style.background = "transparent")}
                  style={{ display: "flex", alignItems: "center", gap: 12, padding: "11px 8px", margin: "0 -8px", borderRadius: "var(--radius-md)", borderBottom: i < debts.length - 1 ? "1px solid var(--border-subtle)" : "none", cursor: "pointer", transition: "background var(--dur-fast,160ms) ease" }}>
                  <div className="bny-avatar bny-avatar--sm">{c.name.split(" ").slice(0, 2).map((w) => w[0]).join("")}</div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 13, fontWeight: 600, color: "var(--text-strong)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{c.name}</div>
                    {over ? <span className="bny-badge bny-badge--danger" style={{ marginTop: 3 }}><span className="bny-badge__dot" />تجاوز السقف</span> : <span style={{ fontSize: 11, color: "var(--text-muted)" }}>ضمن الحد</span>}
                  </div>
                  <div style={{ textAlign: "end", flex: "none", display: "flex", flexDirection: "column", alignItems: "flex-end", gap: 2 }}>
                    {c.balance > 0 && <Money value={c.balance} unit="د.ع" tone="debt" />}
                    {c.balanceUsd > 0 && <Money value={c.balanceUsd} unit="$" tone="debt" />}
                  </div>
                  <span style={{ color: "var(--text-muted)", display: "inline-flex", flex: "none" }}><I.chevron size={16} /></span>
                </div>
              );
            })}
            {debts.length === 0 && <div style={{ padding: "20px 0", textAlign: "center", color: "var(--text-muted)", fontSize: 13 }}>لا ديون معلّقة</div>}
          </div>
        </Card>

        <OverdueInvoicesCard list={aging.list} onOpen={openInv} />
      </div>

      {/* أعلى 5 منتجات هذا الشهر + المواد الراكدة */}
      <div style={sectionTwo}>
        <Card title="أعلى 5 منتجات مبيعًا هذا الشهر">
          <div style={{ display: "flex", flexDirection: "column" }}>
            {topProducts.map((p, i) => (
              <div key={p.name} style={{ display: "flex", alignItems: "center", gap: 12, padding: "11px 0", borderBottom: i < topProducts.length - 1 ? "1px solid var(--border-subtle)" : "none" }}>
                <span style={{ display: "inline-flex", alignItems: "center", justifyContent: "center", width: 26, height: 26, borderRadius: "50%", background: i < 3 ? "var(--brand-soft)" : "var(--surface-sunken)", color: i < 3 ? "var(--brand-strong)" : "var(--text-muted)", fontSize: 12.5, fontWeight: 700, fontFamily: "var(--font-mono)", flex: "none" }}>{i + 1}</span>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13, fontWeight: 600, color: "var(--text-strong)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{p.name}</div>
                  <div style={{ fontSize: 11.5, color: "var(--text-muted)", fontFamily: "var(--font-mono)" }}>{p.qty.toLocaleString("en-US")} {p.unit} مُباعة</div>
                </div>
                <Money value={p.revenue} unit="د.ع" />
              </div>
            ))}
            {topProducts.length === 0 && <div style={{ padding: "20px 0", textAlign: "center", color: "var(--text-muted)", fontSize: 13 }}>لا مبيعات لهذا الشهر بعد</div>}
          </div>
        </Card>

        <Card title="المواد الراكدة" actions={<Button variant="ghost" size="sm" onClick={() => onNav("inventory")}>ضبط المدة</Button>}>
          <p style={{ color: "var(--text-muted)", fontSize: 12, margin: "0 0 8px" }}>لم تُبَع منذ {stagDays} يومًا أو أكثر — تُضبط المدة من إدارة المخازن.</p>
          <div style={{ display: "flex", flexDirection: "column" }}>
            {stagnant.slice(0, 6).map((x, i, arr) => (
              <div key={x.m.sku} onClick={() => onNav("inventory")} style={{ display: "flex", alignItems: "center", gap: 12, padding: "11px 0", borderBottom: i < arr.length - 1 ? "1px solid var(--border-subtle)" : "none", cursor: "pointer" }}>
                <span style={{ display: "inline-flex", alignItems: "center", justifyContent: "center", width: 34, height: 34, borderRadius: "var(--radius-md)", background: "var(--surface-sunken)", color: "var(--text-muted)", flex: "none" }}><I.inventory size={17} /></span>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13, fontWeight: 600, color: "var(--text-strong)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{x.m.name}</div>
                  <div style={{ fontSize: 11.5, color: "var(--text-muted)" }}>رصيد {x.m.stock.toLocaleString("en-US")} {x.m.unit} · {x.m.wh}</div>
                </div>
                <div style={{ textAlign: "end", flex: "none", fontSize: 12 }}>
                  {x.lastSold
                    ? <span style={{ color: "var(--text-muted)" }}>آخر بيع<br /><b style={{ color: "var(--text-strong)", fontFamily: "var(--font-mono)" }}>{window.BnyDate(x.lastSold)}</b></span>
                    : <span className="bny-badge bny-badge--danger"><span className="bny-badge__dot" />لم تُبَع</span>}
                </div>
              </div>
            ))}
            {stagnant.length === 0 && <div style={{ padding: "20px 0", textAlign: "center", color: "var(--text-muted)", fontSize: 13 }}>لا مواد راكدة ✓</div>}
          </div>
        </Card>
      </div>

      {showStockModal && <StockAlertModal out={outOfStock} low={lowStock} onClose={() => setShowStockModal(false)} onGo={() => { setShowStockModal(false); onNav("inventory"); }} />}
      {selCustomer && <CustomerInfoModal customer={selCustomer} onClose={() => setSelCustomer(null)} onNav={onNav} />}
    </div>
  );
}

/* بطاقة تنبيه المخزون — لون تحذيري بارز + قابلة للنقر */
function StockAlertCard({ outCount, lowCount, onClick }) {
  const I = window.BnyIcon;
  const critical = outCount > 0;
  // ألوان صريحة (hex) — لصق الشفافية على var() يُبطل الخلفية فيصبح النص غير مقروء
  const bg = critical ? "#D93B3B" : "#E08A00";
  const bg2 = critical ? "#B82F2F" : "#B86F00";
  return (
    <button onClick={onClick} title="اعرض المواد التي تحتاج إعادة طلب"
      style={{ textAlign: "start", cursor: "pointer", border: "none", borderRadius: "var(--radius-lg)", padding: "16px 18px", color: "#fff",
        background: "linear-gradient(135deg, " + bg + ", " + bg2 + ")", boxShadow: "0 6px 18px " + bg + "55", display: "flex", flexDirection: "column", gap: 8, position: "relative", overflow: "hidden", minHeight: 96 }}>
      <span style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 13, fontWeight: 600, opacity: 0.95 }}>
        <I.alert size={17} /> تنبيه المخزون
      </span>
      <span style={{ display: "flex", alignItems: "baseline", gap: 8 }}>
        <b style={{ fontSize: 26, fontFamily: "var(--font-mono)", lineHeight: 1 }}>{outCount}</b>
        <span style={{ fontSize: 13 }}>مادة نفدت</span>
        {lowCount > 0 && <span style={{ fontSize: 12.5, opacity: 0.9, marginInlineStart: "auto" }}>+ {lowCount} منخفضة</span>}
      </span>
      <span style={{ fontSize: 12, fontWeight: 600, display: "inline-flex", alignItems: "center", gap: 4, opacity: 0.95 }}>
        اعرض قائمة إعادة الطلب <I.chevron size={14} />
      </span>
    </button>
  );
}

/* نافذة قائمة المواد التي تحتاج إعادة طلب (النافدة ثم المنخفضة) */
function StockAlertModal({ out, low, onClose, onGo }) {
  const I = window.BnyIcon;
  const { Button } = window.BonyanDesignSystem_ad3ca0;
  const lowOnly = low.filter((m) => m.stock > 0); // المنخفضة غير النافدة
  const Row = (m, tone) => (
    <div key={m.sku} style={{ display: "flex", alignItems: "center", gap: 12, padding: "12px 0", borderBottom: "1px solid var(--border-subtle)" }}>
      <span style={{ display: "inline-flex", alignItems: "center", justifyContent: "center", width: 34, height: 34, borderRadius: "var(--radius-md)", background: tone === "out" ? "var(--danger-soft)" : "var(--warning-soft, #fff4e0)", color: tone === "out" ? "var(--danger)" : "var(--amber-600, #b06f00)", flex: "none" }}><I.alert size={17} /></span>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 13.5, fontWeight: 600, color: "var(--text-strong)" }}>{m.name}</div>
        <div style={{ fontSize: 11.5, color: "var(--text-muted)", fontFamily: "var(--font-mono)" }}>{m.sku} · {m.wh}</div>
      </div>
      <div style={{ textAlign: "end", flex: "none" }}>
        <div style={{ fontFamily: "var(--font-mono)", fontWeight: 700, color: tone === "out" ? "var(--danger-text)" : "var(--text-strong)" }}>{m.stock.toLocaleString("en-US")} {m.unit}</div>
        <span className={"bny-badge bny-badge--" + (tone === "out" ? "danger" : "warning")} style={{ marginTop: 2 }}><span className="bny-badge__dot" />{tone === "out" ? "نفدت" : "منخفضة"} · حد {m.low}</span>
      </div>
    </div>
  );
  return (
    <div onClick={onClose} style={{ position: "fixed", inset: 0, zIndex: 1000, background: "rgba(0,0,0,.45)", display: "flex", alignItems: "center", justifyContent: "center", padding: "var(--space-5)" }}>
      <div onClick={(e) => e.stopPropagation()} className="bny-card" style={{ width: "100%", maxWidth: 540, maxHeight: "85vh", display: "flex", flexDirection: "column", padding: 0 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "16px 20px", borderBottom: "1px solid var(--border-subtle)" }}>
          <span style={{ display: "inline-flex", color: "var(--danger)" }}><I.alert size={20} /></span>
          <h3 style={{ margin: 0, fontSize: 17, flex: 1 }}>مواد تحتاج إعادة طلب</h3>
          <button onClick={onClose} style={{ border: 0, background: "none", cursor: "pointer", color: "var(--text-muted)", display: "inline-flex" }}><I.x size={20} /></button>
        </div>
        <div style={{ overflowY: "auto", padding: "4px 20px 16px" }}>
          {out.length > 0 && <div style={{ fontSize: 12.5, fontWeight: 700, color: "var(--danger)", margin: "12px 0 2px" }}>نفدت ({out.length})</div>}
          {out.map((m) => Row(m, "out"))}
          {lowOnly.length > 0 && <div style={{ fontSize: 12.5, fontWeight: 700, color: "var(--amber-600, #b06f00)", margin: "16px 0 2px" }}>منخفضة ({lowOnly.length})</div>}
          {lowOnly.map((m) => Row(m, "low"))}
          {out.length === 0 && lowOnly.length === 0 && <div style={{ padding: "28px 0", textAlign: "center", color: "var(--text-muted)" }}>كل المواد ضمن الحد ✓</div>}
        </div>
        <div style={{ padding: "12px 20px", borderTop: "1px solid var(--border-subtle)", display: "flex", justifyContent: "flex-end", gap: 8 }}>
          <Button variant="secondary" onClick={onClose}>إغلاق</Button>
          <Button variant="accent" icon={<I.inventory size={16} />} onClick={onGo}>فتح إدارة المخزن</Button>
        </div>
      </div>
    </div>
  );
}

/* كارت أعلى الفواتير تأخّرًا — انقر أي فاتورة لفتحها/تعديلها/حذفها */
function OverdueInvoicesCard({ list, onOpen }) {
  const I = window.BnyIcon;
  const { Card, Money } = window.BonyanDesignSystem_ad3ca0;
  const top = (list || []).slice(0, 5);
  return (
    <Card title="أعلى 5 فواتير تأخّرًا">
      <p style={{ color: "var(--text-muted)", fontSize: 12, margin: "0 0 6px" }}>انقر أي فاتورة لفتحها وتعديلها أو حذفها.</p>
      <div style={{ display: "flex", flexDirection: "column" }}>
        {top.map((r, i) => (
          <div key={r.no} onClick={() => onOpen(r.no)} title="افتح الفاتورة"
            onMouseEnter={(e) => (e.currentTarget.style.background = "var(--surface-hover)")}
            onMouseLeave={(e) => (e.currentTarget.style.background = "transparent")}
            style={{ display: "flex", alignItems: "center", gap: 10, padding: "11px 8px", margin: "0 -8px", borderRadius: "var(--radius-md)", borderBottom: i < top.length - 1 ? "1px solid var(--border-subtle)" : "none", cursor: "pointer", transition: "background var(--dur-fast,160ms) ease" }}>
            <span style={{ fontFamily: "var(--font-mono)", fontWeight: 700, color: "var(--text-strong)", flex: "none" }}>#{r.no}</span>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 13, fontWeight: 600, color: "var(--text-strong)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{r.party}</div>
              <span className="bny-badge bny-badge--danger" style={{ marginTop: 2 }}><span className="bny-badge__dot" />متأخرة {r.age} يومًا</span>
            </div>
            <div style={{ textAlign: "end", flex: "none" }}>
              <div style={{ fontSize: 10.5, color: "var(--text-muted)" }}>المتبقّي</div>
              <Money value={r.remaining} unit="د.ع" tone="debt" />
            </div>
            <span style={{ color: "var(--text-muted)", display: "inline-flex", flex: "none" }}><I.chevron size={16} /></span>
          </div>
        ))}
        {top.length === 0 && <div style={{ padding: "20px 0", textAlign: "center", color: "var(--text-muted)", fontSize: 13 }}>لا فواتير متأخّرة ✓</div>}
      </div>
    </Card>
  );
}

/* نافذة معلومات العميل الكاملة + رابط واتساب مباشر */
function CustomerInfoModal({ customer: c, onClose, onNav }) {
  const I = window.BnyIcon;
  const D = window.BnyData;
  const { Button } = window.BonyanDesignSystem_ad3ca0;
  const org = c.org ? (D.organizations || []).find((o) => o.id === c.org) : null;
  const shop = (D.shop && D.shop.name) || "بُنيان";
  const waMsg = "السلام عليكم " + c.name + "، نذكّركم بالرصيد المستحق لدى " + shop + (c.balance > 0 ? " بمبلغ " + c.balance.toLocaleString("en-US") + " د.ع" : "") + ". شكرًا لتعاملكم.";
  const wa = window.BnyWaLink(c.phone, waMsg);
  const initials = c.name.split(" ").slice(0, 2).map((w) => w[0]).join("");
  const Field = (icon, label, value, href) => value ? (
    <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "10px 0", borderBottom: "1px solid var(--border-subtle)" }}>
      <span style={{ color: "var(--text-muted)", display: "inline-flex", flex: "none" }}>{icon}</span>
      <span style={{ fontSize: 12.5, color: "var(--text-muted)", width: 80, flex: "none" }}>{label}</span>
      {href ? <a href={href} style={{ fontSize: 13.5, color: "var(--brand-strong)", fontWeight: 600, textDecoration: "none", fontFamily: "var(--font-mono)" }}>{value}</a>
        : <span style={{ fontSize: 13.5, color: "var(--text-strong)", fontWeight: 500 }}>{value}</span>}
    </div>
  ) : null;
  return (
    <div onClick={onClose} style={{ position: "fixed", inset: 0, zIndex: 1000, background: "rgba(0,0,0,.45)", display: "flex", alignItems: "center", justifyContent: "center", padding: "var(--space-5)" }}>
      <div onClick={(e) => e.stopPropagation()} className="bny-card" style={{ width: "100%", maxWidth: 460, maxHeight: "88vh", display: "flex", flexDirection: "column", padding: 0 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "18px 20px", borderBottom: "1px solid var(--border-subtle)" }}>
          <div className="bny-avatar" style={{ width: 46, height: 46, fontSize: 16 }}>{initials}</div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 17, fontWeight: 700, color: "var(--text-strong)" }}>{c.name}</div>
            <div style={{ fontSize: 12.5, color: "var(--text-muted)" }}>{c.title || (org ? org.name : (c.type === "نقدي" ? "عميل نقدي" : "عميل آجل"))}</div>
          </div>
          <button onClick={onClose} style={{ border: 0, background: "none", cursor: "pointer", color: "var(--text-muted)", display: "inline-flex" }}><I.x size={20} /></button>
        </div>
        <div style={{ overflowY: "auto", padding: "6px 20px 12px" }}>
          {Field(<I.phone size={16} />, "الهاتف", c.phone, c.phone ? "tel:" + c.phone : null)}
          {org && Field(<I.building size={16} />, "الجهة", org.name)}
          {org && org.phone && Field(<I.phone size={16} />, "هاتف الجهة", org.phone, "tel:" + org.phone)}
          {Field(<I.inventory size={16} />, "العنوان", c.address)}
          {Field(<I.card size={16} />, "النوع", c.type)}
          <div style={{ display: "flex", gap: 10, marginTop: 14 }}>
            <div style={{ flex: 1, background: "var(--danger-soft)", borderRadius: "var(--radius-md)", padding: "12px 14px" }}>
              <div style={{ fontSize: 11.5, color: "var(--danger-text)" }}>الرصيد المستحق (د.ع)</div>
              <div style={{ fontWeight: 700, fontSize: 18, color: "var(--danger-text)", fontFamily: "var(--font-mono)" }}>{(c.balance || 0).toLocaleString("en-US")}</div>
            </div>
            {c.balanceUsd ? <div style={{ flex: 1, background: "var(--surface-sunken)", borderRadius: "var(--radius-md)", padding: "12px 14px" }}>
              <div style={{ fontSize: 11.5, color: "var(--text-muted)" }}>بالدولار ($)</div>
              <div style={{ fontWeight: 700, fontSize: 18, color: "var(--text-strong)", fontFamily: "var(--font-mono)" }}>{(c.balanceUsd || 0).toLocaleString("en-US")}</div>
            </div> : null}
          </div>
          {c.limitEnabled && <div style={{ fontSize: 12, color: c.balance > c.limit ? "var(--danger)" : "var(--text-muted)", marginTop: 10 }}>
            السقف الائتماني: {c.limit.toLocaleString("en-US")} د.ع {c.balance > c.limit ? "— تجاوز السقف!" : ""}
          </div>}
        </div>
        <div style={{ padding: "12px 20px", borderTop: "1px solid var(--border-subtle)", display: "flex", gap: 8, flexWrap: "wrap" }}>
          {wa && <a href={wa} target="_blank" rel="noopener" style={{ flex: 1, minWidth: 150, textDecoration: "none" }}>
            <button style={{ width: "100%", border: 0, cursor: "pointer", borderRadius: "var(--radius-md)", padding: "11px 14px", background: "#25D366", color: "#fff", fontWeight: 700, fontSize: 14, fontFamily: "var(--font-body)", display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 8 }}>
              <I.whatsapp size={18} /> مراسلة واتساب
            </button>
          </a>}
          <Button variant="secondary" icon={<I.users size={16} />} onClick={() => { onClose(); onNav("customers"); }}>كشف الحساب</Button>
        </div>
      </div>
    </div>
  );
}
/* كارت «مواد تحتاج شراء» — تنبيه قصير (5) + عرض الكل (يفتح المخزن مفلترًا) */
function ReorderCard({ items, onSeeAll }) {
  const I = window.BnyIcon;
  const { Card, Button } = window.BonyanDesignSystem_ad3ca0;
  const all = items || [];
  const top = all.slice(0, 5);
  return (
    <Card title="مواد تحتاج شراء"
      actions={<Button variant="ghost" size="sm" icon={<I.chevron size={15} />} onClick={onSeeAll}>عرض الكل{all.length > 5 ? " (" + all.length + ")" : ""}</Button>}>
      <p style={{ color: "var(--text-muted)", fontSize: 12, margin: "0 0 8px" }}>مواد نفدت أو قاربت على النفاد — راجعها لإعادة الطلب.</p>
      <div style={{ display: "flex", flexDirection: "column" }}>
        {top.map((m, i) => {
          const out = Number(m.stock) === 0;
          return (
            <div key={m.sku} onClick={onSeeAll} title="افتح المخزن" style={{ display: "flex", alignItems: "center", gap: 12, padding: "11px 0", borderBottom: i < top.length - 1 ? "1px solid var(--border-subtle)" : "none", cursor: "pointer" }}>
              <span style={{ display: "inline-flex", alignItems: "center", justifyContent: "center", width: 34, height: 34, borderRadius: "var(--radius-md)", background: out ? "var(--danger-soft)" : "var(--warning-soft, #fff4e0)", color: out ? "var(--danger)" : "var(--amber-600, #b06f00)", flex: "none" }}><I.alert size={17} /></span>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13, fontWeight: 600, color: "var(--text-strong)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{m.name}</div>
                <div style={{ fontSize: 11.5, color: "var(--text-muted)" }}>{m.wh} · حد التنبيه {m.low} {m.unit}</div>
              </div>
              <div style={{ textAlign: "end", flex: "none" }}>
                <div style={{ fontFamily: "var(--font-mono)", fontWeight: 700, fontSize: 14, color: out ? "var(--danger-text)" : "var(--text-strong)" }}>{m.stock.toLocaleString("en-US")} {m.unit}</div>
                <span className={"bny-badge bny-badge--" + (out ? "danger" : "warning")} style={{ marginTop: 2 }}><span className="bny-badge__dot" />{out ? "نفدت" : "ستنفد قريبًا"}</span>
              </div>
            </div>
          );
        })}
        {top.length === 0 && <div style={{ padding: "20px 0", textAlign: "center", color: "var(--text-muted)", fontSize: 13 }}>كل المواد ضمن الحد ✓</div>}
      </div>
    </Card>
  );
}
window.DashboardScreen = DashboardScreen;
