/* Bonyan ERP — Customers (مستقل أو تابع لشركة) + كشف حساب موظف/شركة + عملات */
function CustomersScreen() {
  const I = window.BnyIcon;
  const D = window.BnyData;
  const cur = window.BnyCur;
  const { Card, Button, Money, Badge, Tabs, Avatar, Input } = window.BonyanDesignSystem_ad3ca0;
  const isMobile = window.useBnyMobile();
  window.useBnyInvoices(); // إعادة الرسم عند تعديل/حذف فاتورة من أي مكان
  // أول عميل حقيقي (غير المستطرق) — أو العميل المطلوب من المساعد الصوتي
  const [sel, setSel] = React.useState(() => {
    const pid = window.BnyPendingCustomerId;
    if (pid != null) { window.BnyPendingCustomerId = null; const c = D.customers.find((x) => x.id === pid); if (c) return c; }
    return D.customers.find((c) => !c.walkin) || null;
  });
  const [tab, setTab] = React.useState("stmt");
  const [curFilter, setCurFilter] = React.useState("all"); // all | iqd | usd
  // نطاق الكشف — يبدأ بـ«الشركة» إن جاء الطلب من قسم الحسابات (مؤسسة)
  const [scope, setScope] = React.useState(() => {
    if (window.BnyPendingCustomerScope === "org") { window.BnyPendingCustomerScope = null; return "org"; }
    return "employee";
  });
  const [search, setSearch] = React.useState("");
  const [sort, setSort] = React.useState("debt-desc");      // debt-desc|debt-asc|date-desc|date-asc
  const [filterVal, setFilterVal] = React.useState("");     // org:ID | region:X | ""
  const [printCust, setPrintCust] = React.useState(null);   // العميل قيد سحب/طباعة الكشف
  const [showNew, setShowNew] = React.useState(false);       // نافذة عميل جديد
  const [showPay, setShowPay] = React.useState(false);       // نافذة تسديد دين
  const [showEdit, setShowEdit] = React.useState(false);     // نافذة تعديل بيانات العميل
  const [payInv, setPayInv] = React.useState(null);          // فاتورة قيد التسديد المنفرد
  const [delPay, setDelPay] = React.useState(null);          // دفعة قيد الحذف (تأكيد المدير)
  const [printMode, setPrintMode] = React.useState("stmt");  // stmt | inv | pay
  const saveEdit = async (patch) => {
    await window.BnyOps.updateCustomerInfo(sel, patch);
    setShowEdit(false); forceRender();
  };
  const doPayInvoice = async (amount) => {
    await window.BnyOps.payInvoice(payInv, amount);
    setPayInv(null); forceRender();
  };
  const confirmDeletePay = async (creds) => {
    await window.BnyOps.deleteCustomerPayment(delPay, creds); // يرمي خطأً إن رفضت القاعدة التخويل
    setDelPay(null); forceRender();
  };
  const doPrint = () => { if (sel) { setPrintMode(tab); setPrintCust(sel); } }; // يطبع التبويب الحالي

  // إضافة عميل جديد (محلي + قاعدة)
  const addCustomer = async (data) => {
    const c = await window.BnyOps.addCustomer({
      name: data.name.trim(), phone: (data.phone || "").trim(), phone2: (data.phone2 || "").trim(),
      address: (data.address || "").trim(), org: data.org || null,
    });
    setShowNew(false); selectCust(c); forceRender();
  };
  const createOrg = (data) => {
    const o = { id: "org-" + Date.now(), name: data.name.trim(), phone: "", type: "شركة", notes: (data.notes || "").trim() };
    window.BnyOps.addOrganization(o);
    return o;
  };
  // تسديد دين العميل المحدَّد
  const payDebt = async (amount, curKey) => {
    await window.BnyOps.payCustomer(sel, amount, curKey);
    setShowPay(false); forceRender();
  };
  // إرسال كشف مختصر عبر واتساب
  const waStatement = () => {
    const msg = "كشف حساب — " + sel.name + "\nمن " + ((D.shop && D.shop.name) || "بُنيان") + "\n"
      + "المستحق بالدينار: " + (sel.balance || 0).toLocaleString("en-US") + " د.ع\n"
      + (sel.balanceUsd ? "المستحق بالدولار: " + sel.balanceUsd.toLocaleString("en-US") + " $\n" : "")
      + "شكرًا لتعاملكم معنا.";
    const url = sel.phone ? window.BnyWaLink(sel.phone, msg) : "https://wa.me/?text=" + encodeURIComponent(msg);
    try { window.open(url, "_blank"); } catch (e) {}
  };
  React.useEffect(() => {
    if (!printCust) return;
    document.body.classList.add("bny-printing-stmt");
    const after = () => { document.body.classList.remove("bny-printing-stmt"); setPrintCust(null); };
    window.addEventListener("afterprint", after);
    const t = setTimeout(() => window.print(), 120);
    return () => { clearTimeout(t); window.removeEventListener("afterprint", after); document.body.classList.remove("bny-printing-stmt"); };
  }, [printCust]);

  const [, forceRender] = React.useReducer((x) => x + 1, 0);
  const selectCust = (c) => { setSel(c); setScope("employee"); };
  const toggleLimit = () => { sel.limitEnabled = !sel.limitEnabled; forceRender(); };
  const setLimitVal = (key, raw) => { sel[key] = Number(raw) || 0; forceRender(); };

  const s0 = sel || {}; // اشتقاقات آمنة حتى مع غياب عميل محدد (مشترك جديد)
  const org = s0.org ? D.organizations.find((o) => o.id === s0.org) : null;
  const orgScope = !!org && scope === "org";
  const members = org ? D.customers.filter((c) => c.org === org.id) : (sel ? [sel] : []);
  const memberIds = members.map((m) => m.id);
  const custName = (id) => { const c = D.customers.find((x) => x.id === id); return c ? c.name : ""; };
  const orgOf = (c) => (c.org ? D.organizations.find((o) => o.id === c.org) : null);

  const agg = (key) => members.reduce((s, m) => s + (m[key] || 0), 0);
  const bal = orgScope ? agg("balance") : (s0.balance || 0);
  const balUsd = orgScope ? agg("balanceUsd") : (s0.balanceUsd || 0);
  const lim = orgScope ? agg("limit") : (s0.limit || 0);
  const limUsd = orgScope ? agg("limitUsd") : (s0.limitUsd || 0);

  // الكشف مشتقّ من الفواتير + الدفعات (الأقدم أعلى، أحدث دفعة في الأسفل)
  const baseRows = !sel ? []
    : orgScope
      ? members.reduce((all, m) => all.concat(window.BnyCustStatement(m).map((r) => ({ ...r, cust: m.id }))), []).sort((a, b) => String(a.iso || "").localeCompare(String(b.iso || "")))
      : window.BnyCustStatement(sel);
  const stmtRows = baseRows.filter((s) => (curFilter === "all" || s.cur === curFilter) && (tab !== "pay" || s.credit > 0));
  // فواتير بيع العميل (لتبويب «الفواتير» + التسديد المنفرد) — الأحدث أولًا
  const custInvoices = !sel ? [] : window.BnyCustSaleInvoices(sel)
    .filter((i) => curFilter === "all" || i.cur === curFilter)
    .slice().sort((a, b) => String(b.date || "").localeCompare(String(a.date || "")));

  const CurFilter = () => (
    <div style={{ display: "flex", justifyContent: "flex-end", marginTop: 10 }}>
      <div className="bny-unit-toggle" role="group" aria-label="تصفية العملة">
        <button type="button" aria-pressed={curFilter === "all"} onClick={() => setCurFilter("all")}>الكل</button>
        <button type="button" aria-pressed={curFilter === "iqd"} onClick={() => setCurFilter("iqd")}>د.ع</button>
        <button type="button" aria-pressed={curFilter === "usd"} onClick={() => setCurFilter("usd")}>$</button>
      </div>
    </div>
  );

  // منطقة العميل من العنوان (المقطع بعد "—"، أول جزء قبل "،")
  const regionOf = (c) => { const a = (c.address || "").split("—")[1] || (c.address || ""); return a.split("،")[0].trim(); };
  const custSortOptions = [
    { key: "debt-desc", label: "المديونية: الأعلى أولًا" },
    { key: "debt-asc", label: "المديونية: الأقل أولًا" },
    { key: "date-desc", label: "الأحدث مديونية" },
    { key: "date-asc", label: "الأقدم مديونية" },
  ];
  const custFilterOptions = (() => {
    const opts = [];
    (D.organizations || []).forEach((o) => opts.push({ value: "org:" + o.id, label: "مؤسسة: " + o.name }));
    const regions = [];
    D.customers.filter((c) => !c.walkin).forEach((c) => { const r = regionOf(c); if (r && regions.indexOf(r) === -1) regions.push(r); });
    regions.forEach((r) => opts.push({ value: "region:" + r, label: "منطقة: " + r }));
    return opts;
  })();
  const toIqd = (c) => window.BnyToIqd(c.balance, c.balanceUsd);
  const custRows = D.customers.filter((c) => !c.walkin)
    .filter((c) => { const q = search.trim(); if (!q) return true; const o = orgOf(c); return c.name.includes(q) || (c.phone || "").includes(q) || (o && o.name.includes(q)); })
    .filter((c) => {
      if (!filterVal) return true;
      if (filterVal.indexOf("org:") === 0) return c.org === filterVal.slice(4);
      if (filterVal.indexOf("region:") === 0) return regionOf(c) === filterVal.slice(7);
      return true;
    })
    .slice()
    .sort((a, b) => {
      if (sort === "debt-desc") return toIqd(b) - toIqd(a);
      if (sort === "debt-asc") return toIqd(a) - toIqd(b);
      const da = window.BnyLastMovement(a.name, a.id, "cust") || "", db = window.BnyLastMovement(b.name, b.id, "cust") || "";
      if (da === db) return 0; if (!da) return 1; if (!db) return -1;
      return sort === "date-desc" ? (db < da ? -1 : 1) : (da < db ? -1 : 1);
    });

  // ---- كشف ديون العملاء الإجمالي ----
  const iqdOf = (amt, c) => (c === "usd" ? (Number(amt) || 0) * (D.usdRate || 1500) : (Number(amt) || 0));
  const lastPayOf = (c) => {
    const ps = (D.custPayments || []).filter((p) => p.cust === c.id);
    if (!ps.length) return "";
    const last = ps.slice().sort((a, b) => String(b.iso || "").localeCompare(String(a.iso || "")))[0];
    return last.disp || (last.iso ? window.BnyDate(last.iso) : "");
  };
  const custDebtRows = D.customers.filter((c) => !c.walkin).map((c) => {
    const invs = window.BnyCustSaleInvoices(c);
    const due = window.BnyCustDue(c); // المتبقّي = مجموع (إجمالي − مسدَّد) لكل فاتورة
    return {
      id: c.id, name: c.name,
      total: invs.reduce((s, i) => s + iqdOf(i.total, i.cur), 0),
      paid: invs.reduce((s, i) => s + iqdOf(i.paid, i.cur), 0),
      remaining: window.BnyToIqd(due.iqd, due.usd),
      extra: lastPayOf(c), _c: c,
    };
  }).sort((a, b) => b.remaining - a.remaining);
  const showDetail = (r) => { selectCust(r._c); try { window.scrollTo({ top: 0, behavior: "smooth" }); } catch (e) {} };
  // بيانات الطباعة حسب النمط: كشف كامل / الفواتير / الدفعات فقط
  const printData = (() => {
    if (!printCust) return { title: "", rows: [], cols: [] };
    if (printMode === "inv") {
      const rows = window.BnyCustSaleInvoices(printCust).slice().sort((a, b) => String(a.date || "").localeCompare(String(b.date || "")));
      return { title: "فواتير العميل", rows, cols: [
        { label: "التاريخ", mono: true, render: (i) => window.BnyDate(i.date) },
        { label: "الفاتورة", render: (i) => "#" + i.no },
        { label: "العملة", align: "center", render: (i) => cur(i.cur) },
        { label: "الإجمالي", align: "end", mono: true, render: (i) => Number(i.total || 0).toLocaleString("en-US") },
        { label: "المسدَّد", align: "end", mono: true, render: (i) => Number(i.paid || 0).toLocaleString("en-US") },
        { label: "المتبقّي", align: "end", mono: true, render: (i) => Math.max(0, (Number(i.total) || 0) - (Number(i.paid) || 0)).toLocaleString("en-US") },
      ] };
    }
    const all = window.BnyCustStatement(printCust);
    const rows = printMode === "pay" ? all.filter((r) => r.kind === "payment") : all;
    return { title: printMode === "pay" ? "دفعات العميل" : "كشف حساب عميل", rows, cols: [
      { label: "التاريخ", render: (s) => s.date, mono: true },
      { label: "البيان", render: (s) => s.ref },
      { label: "العملة", align: "center", render: (s) => cur(s.cur) },
      { label: "مدين", align: "end", mono: true, render: (s) => s.debit ? Number(s.debit).toLocaleString("en-US") : "—" },
      { label: "دائن", align: "end", mono: true, render: (s) => s.credit ? Number(s.credit).toLocaleString("en-US") : "—" },
    ] };
  })();

  return (
    <div style={{ padding: isMobile ? "var(--space-5)" : "var(--space-8)", display: "flex", flexDirection: "column", gap: "var(--space-7)" }}>
      <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr" : "320px 1fr", gap: "var(--space-7)", alignItems: "start" }}>
      {/* list */}
      <Card title="العملاء" actions={<Button size="sm" icon={<I.plus size={16} />} onClick={() => setShowNew(true)}>جديد</Button>}>
        <div style={{ display: "flex", gap: 8, marginBottom: 12 }}>
          <div style={{ flex: 1 }}><Input value={search} onChange={(e) => setSearch(e.target.value)} placeholder="ابحث عن عميل" icon={<I.search size={16} />} /></div>
          <window.BnyListFilter sort={sort} onSort={setSort} sortOptions={custSortOptions}
            filterVal={filterVal} onFilter={setFilterVal} filterOptions={custFilterOptions} filterLabel="التصفية حسب المؤسسة/المنطقة" />
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
          {custRows.length === 0 && <div style={{ padding: "20px 8px", textAlign: "center", color: "var(--text-muted)", fontSize: 13 }}>لا عملاء مطابقون</div>}
          {custRows.map((c) => {
            const on = sel && c.id === sel.id;
            const settled = c.balance === 0 && c.balanceUsd === 0;
            const co = orgOf(c);
            return (
              <button key={c.id} onClick={() => selectCust(c)} style={{
                display: "flex", alignItems: "center", gap: 11, padding: "10px 11px", borderRadius: "var(--radius-md)",
                border: "none", cursor: "pointer", textAlign: "start",
                background: on ? "var(--brand-soft)" : "transparent",
              }}>
                <Avatar name={c.name} size="sm" />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13.5, fontWeight: 600, color: "var(--text-strong)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{c.name}</div>
                  <div style={{ fontSize: 11, color: "var(--text-muted)", display: "flex", alignItems: "center", gap: 4, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
                    {co ? <><I.building size={11} /> {co.name}</> : "فرد مستقل"}
                  </div>
                </div>
                <div style={{ display: "flex", flexDirection: "column", alignItems: "flex-end", gap: 2 }}>
                  {settled && <Badge tone="success">مسدّد</Badge>}
                  {c.balance > 0 && <Money value={c.balance} unit="د.ع" tone="debt" style={{ fontSize: 12 }} />}
                  {c.balanceUsd > 0 && <Money value={c.balanceUsd} unit="$" tone="debt" style={{ fontSize: 12 }} />}
                </div>
              </button>
            );
          })}
        </div>
      </Card>

      {/* detail */}
      <div style={{ display: "flex", flexDirection: "column", gap: "var(--space-6)" }}>
        {!sel ? (
          <Card>
            <div style={{ padding: "40px 16px", textAlign: "center", display: "flex", flexDirection: "column", alignItems: "center", gap: 12 }}>
              <span style={{ color: "var(--text-faint)" }}><I.users size={40} /></span>
              <div style={{ fontWeight: 700, color: "var(--text-strong)", fontSize: 16 }}>لا عملاء بعد</div>
              <div style={{ fontSize: 13, color: "var(--text-muted)" }}>أضف أول عميل لعرض حسابه وكشوفه هنا.</div>
              <Button variant="accent" icon={<I.plus size={16} />} onClick={() => setShowNew(true)}>إضافة عميل</Button>
            </div>
          </Card>
        ) : (<>
        <Card>
          <div style={{ display: "flex", alignItems: "center", gap: 16 }}>
            <Avatar name={sel.name} size="lg" />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap" }}>
                <h2 style={{ fontSize: isMobile ? 18 : 20, margin: 0 }}>{sel.name}</h2>
                <Badge tone={sel.type === "آجل" ? "brand" : "neutral"}>{sel.type}</Badge>
              </div>
              <div style={{ display: "flex", alignItems: "center", gap: 6, color: "var(--text-muted)", fontSize: 13, marginTop: 4 }}>
                <I.phone size={14} /><span style={{ fontFamily: "var(--font-mono)" }}>{sel.phone}</span>
              </div>
              <div style={{ display: "flex", alignItems: "center", gap: 6, color: org ? "var(--brand-strong)" : "var(--text-muted)", fontSize: 13, marginTop: 3 }}>
                {org
                  ? <><I.building size={14} /><span>{org.name}{sel.title ? " · " + sel.title : ""}</span></>
                  : <><I.users size={14} /><span>فرد مستقل (غير تابع لمنظمة)</span></>}
              </div>
            </div>
            {!isMobile && (
              <div style={{ display: "flex", gap: 10 }}>
                <Button variant="secondary" icon={<I.settings size={16} />} onClick={() => setShowEdit(true)}>تعديل</Button>
                <Button variant="secondary" icon={<I.printer size={16} />} onClick={doPrint}>طباعة</Button>
                <Button variant="secondary" icon={<I.whatsapp size={16} />} onClick={waStatement}>إرسال كشف</Button>
                <Button variant="accent" icon={<I.wallet size={16} />} onClick={() => setShowPay(true)}>تسديد دين</Button>
              </div>
            )}
          </div>
          {isMobile && (
            <div style={{ display: "flex", gap: 10, marginTop: 14 }}>
              <Button variant="secondary" block icon={<I.settings size={16} />} onClick={() => setShowEdit(true)}>تعديل</Button>
              <Button variant="secondary" block icon={<I.printer size={16} />} onClick={doPrint}>طباعة</Button>
              <Button variant="secondary" block icon={<I.whatsapp size={16} />} onClick={waStatement}>إرسال كشف</Button>
              <Button variant="accent" block icon={<I.wallet size={16} />} onClick={() => setShowPay(true)}>تسديد دين</Button>
            </div>
          )}

          {/* نطاق الكشف: موظف أو الشركة كاملة (يظهر فقط للتابعين لمنظمة) */}
          {org && (
            <div style={{ display: "flex", alignItems: "center", gap: 10, marginTop: 16, flexWrap: "wrap" }}>
              <span style={{ fontSize: 13, color: "var(--text-muted)" }}>نطاق كشف الحساب</span>
              <div className="bny-unit-toggle" role="group" aria-label="نطاق الكشف">
                <button type="button" aria-pressed={!orgScope} onClick={() => setScope("employee")}>كشف الموظف</button>
                <button type="button" aria-pressed={orgScope} onClick={() => setScope("org")}>كشف {org.type === "منظمة" ? "المنظمة" : "الشركة"}</button>
              </div>
              {orgScope && <span style={{ fontSize: 12, color: "var(--text-muted)" }}>({members.length} موظفين · {org.name})</span>}
            </div>
          )}

          {/* الرصيد المستحق — العملتان منفصلتان، حسب النطاق */}
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14, marginTop: 16 }}>
            <Mini label={(orgScope ? "مستحق الشركة" : "مستحق") + " — دينار"} node={<Money value={bal} unit="د.ع" tone={bal > 0 ? "debt" : "credit"} style={{ fontSize: isMobile ? 19 : 22 }} />} />
            <Mini label={(orgScope ? "مستحق الشركة" : "مستحق") + " — دولار"} node={<Money value={balUsd} unit="$" tone={balUsd > 0 ? "debt" : "credit"} style={{ fontSize: isMobile ? 19 : 22 }} />} />
          </div>

          {/* السقف الائتماني: الحالة الافتراضية بدون سقف، يُفعَّل عند الحاجة */}
          {!orgScope && (
            <div style={{ marginTop: 14, padding: "12px 14px", background: "var(--surface-sunken)", borderRadius: "var(--radius-md)" }}>
              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 10, flexWrap: "wrap" }}>
                <div>
                  <div style={{ fontSize: 13, fontWeight: 600, color: "var(--text-strong)" }}>السقف الائتماني</div>
                  <div style={{ fontSize: 12, color: "var(--text-muted)", marginTop: 2 }}>{sel.limitEnabled ? "مفعّل — يمنع البيع الآجل عند تجاوزه" : "غير مفعّل — ائتمان غير محدود"}</div>
                </div>
                <div className="bny-switch" role="switch" aria-checked={sel.limitEnabled ? "true" : "false"} data-on={sel.limitEnabled ? "true" : "false"} onClick={toggleLimit}>
                  <span className="bny-switch__track"><span className="bny-switch__thumb" /></span>
                  <span className="bny-switch__label">{sel.limitEnabled ? "مفعّل" : "إيقاف"}</span>
                </div>
              </div>
              {sel.limitEnabled && (
                <div style={{ display: "flex", gap: 12, marginTop: 12, flexWrap: "wrap" }}>
                  <div style={{ flex: 1, minWidth: 130 }}>
                    <label style={{ fontSize: 12, color: "var(--text-muted)", display: "block", marginBottom: 5 }}>الحد (دينار)</label>
                    <input className="bny-input bny-input--numeric" type="text" inputMode="numeric" value={sel.limit ? sel.limit.toLocaleString("en-US") : ""} onChange={(e) => setLimitVal("limit", e.target.value.replace(/[^\d]/g, ""))} />
                  </div>
                  <div style={{ flex: 1, minWidth: 130 }}>
                    <label style={{ fontSize: 12, color: "var(--text-muted)", display: "block", marginBottom: 5 }}>الحد (دولار)</label>
                    <input className="bny-input bny-input--numeric" type="number" min="0" value={sel.limitUsd || 0} onChange={(e) => setLimitVal("limitUsd", e.target.value)} />
                  </div>
                </div>
              )}
            </div>
          )}
        </Card>

        <Card>
          <Tabs value={tab} onChange={setTab} items={[
            { value: "stmt", label: orgScope ? "كشف حساب الشركة" : "كشف الحساب" },
            { value: "inv", label: "الفواتير" },
            { value: "pay", label: "الدفعات" },
          ]} />
          <CurFilter />
          {tab === "inv" ? (
            <div style={{ display: "flex", flexDirection: "column", marginTop: 8 }}>
              {custInvoices.map((inv) => {
                const st = window.BnyInvStatus(inv);
                const rem = Math.max(0, (Number(inv.total) || 0) - (Number(inv.paid) || 0));
                const u = inv.cur === "usd" ? "$" : "د.ع";
                return (
                  <div key={inv.no} style={{ display: "flex", alignItems: "center", gap: 10, padding: "12px 4px", borderTop: "1px solid var(--border-subtle)", flexWrap: "wrap" }}>
                    <div style={{ flex: 1, minWidth: 150, cursor: "pointer" }} onClick={() => window.BnyOpenInvoice(inv.no)}>
                      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                        <span style={{ fontSize: 14, fontWeight: 600, color: "var(--text-link)" }}>فاتورة #{inv.no}</span>
                        <Badge tone={st.state}>{st.label}</Badge>
                      </div>
                      <div style={{ fontSize: 11.5, color: "var(--text-muted)", fontFamily: "var(--font-mono)", marginTop: 3 }}>
                        {inv.date} · الإجمالي {Number(inv.total || 0).toLocaleString("en-US")} {u} · مسدَّد {Number(inv.paid || 0).toLocaleString("en-US")} {u}
                      </div>
                    </div>
                    <div style={{ textAlign: "end", minWidth: 96 }}>
                      <div style={{ fontSize: 10.5, color: "var(--text-muted)" }}>المتبقّي</div>
                      <Money value={rem} unit={u} tone={rem > 0 ? "debt" : "credit"} />
                    </div>
                    {rem > 0
                      ? <Button variant="accent" size="sm" icon={<I.wallet size={14} />} onClick={() => setPayInv(inv)}>تسديد</Button>
                      : <Badge tone="success"><I.check size={12} /> مسددة</Badge>}
                  </div>
                );
              })}
              {custInvoices.length === 0 && <div style={{ padding: "24px", textAlign: "center", color: "var(--text-muted)" }}>لا فواتير لهذا العميل</div>}
            </div>
          ) : isMobile ? (
            <div style={{ display: "flex", flexDirection: "column", marginTop: 8 }}>
              {stmtRows.map((s, i) => {
                const canOpen = s.invNo && window.BnyInvoices && window.BnyInvoices.get(s.invNo);
                const isPay = s.kind === "payment";
                return (
                <div key={i} style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 10, padding: "11px 4px", borderTop: "1px solid var(--border-subtle)", borderRadius: "var(--radius-md)" }}>
                  <div style={{ minWidth: 0, flex: 1, cursor: canOpen ? "pointer" : "default" }} onClick={canOpen ? () => window.BnyOpenInvoice(s.invNo) : undefined}>
                    <div style={{ fontSize: 14, fontWeight: 500, color: canOpen ? "var(--text-link)" : "var(--text-strong)" }}>{s.ref}</div>
                    <div style={{ fontSize: 11, color: "var(--text-muted)", fontFamily: "var(--font-mono)", marginTop: 2 }}>
                      {s.date}{orgScope ? " · " + custName(s.cust) : ""} · {s.debit ? "مدين" : "دائن"} · {cur(s.cur)}
                    </div>
                  </div>
                  {s.debit ? <Money value={s.debit} unit={cur(s.cur)} tone="debt" /> : <Money value={s.credit} unit={cur(s.cur)} tone="credit" />}
                  {isPay && s._pay && <button className="bny-iconbtn bny-iconbtn--sm" title="حذف الدفعة" aria-label="حذف الدفعة" onClick={() => setDelPay(s._pay)} style={{ color: "var(--danger)", flex: "none" }}><I.trash size={15} /></button>}
                </div>
                );
              })}
              {stmtRows.length === 0 && <div style={{ padding: "20px", textAlign: "center", color: "var(--text-muted)" }}>لا توجد حركات</div>}
            </div>
          ) : (
          <div style={{ overflowX: "auto" }}>
          <table style={{ width: "100%", borderCollapse: "collapse", marginTop: 16, minWidth: orgScope ? 560 : 460 }}>
            <thead>
              <tr style={{ color: "var(--text-muted)", fontSize: 12 }}>
                <th style={{ textAlign: "start", fontWeight: 600, padding: "0 0 12px" }}>التاريخ</th>
                {orgScope && <th style={{ textAlign: "start", fontWeight: 600, padding: "0 0 12px" }}>الموظف</th>}
                <th style={{ textAlign: "start", fontWeight: 600, padding: "0 0 12px" }}>البيان</th>
                <th style={{ textAlign: "center", fontWeight: 600, padding: "0 0 12px" }}>العملة</th>
                <th style={{ textAlign: "end", fontWeight: 600, padding: "0 0 12px" }}>مدين</th>
                <th style={{ textAlign: "end", fontWeight: 600, padding: "0 0 12px" }}>دائن</th>
                <th style={{ width: 36, padding: "0 0 12px" }} />
              </tr>
            </thead>
            <tbody>
              {stmtRows.map((s, i) => {
                const canOpen = s.invNo && window.BnyInvoices && window.BnyInvoices.get(s.invNo);
                const isPay = s.kind === "payment";
                return (
                <tr key={i}
                  onMouseEnter={canOpen ? (e) => (e.currentTarget.style.background = "var(--surface-hover)") : undefined}
                  onMouseLeave={canOpen ? (e) => (e.currentTarget.style.background = "transparent") : undefined}
                  style={{ borderTop: "1px solid var(--border-subtle)", transition: "background var(--dur-fast,160ms) ease" }}>
                  <td onClick={canOpen ? () => window.BnyOpenInvoice(s.invNo) : undefined} style={{ padding: "13px 0", fontFamily: "var(--font-mono)", fontSize: 13, color: "var(--text-muted)", cursor: canOpen ? "pointer" : "default" }}>{s.date}</td>
                  {orgScope && <td style={{ padding: "13px 0", fontSize: 13 }}>{custName(s.cust)}</td>}
                  <td onClick={canOpen ? () => window.BnyOpenInvoice(s.invNo) : undefined} style={{ padding: "13px 0", fontSize: 14, fontWeight: 500, color: canOpen ? "var(--text-link)" : "var(--text-strong)", cursor: canOpen ? "pointer" : "default" }}>{s.ref}</td>
                  <td style={{ padding: "13px 0", textAlign: "center" }}><span className="bny-tag" style={{ fontSize: 11 }}>{cur(s.cur)}</span></td>
                  <td style={{ padding: "13px 0", textAlign: "end" }}>{s.debit ? <Money value={s.debit} unit={cur(s.cur)} tone="debt" /> : <span style={{ color: "var(--text-faint)" }}>—</span>}</td>
                  <td style={{ padding: "13px 0", textAlign: "end" }}>{s.credit ? <Money value={s.credit} unit={cur(s.cur)} tone="credit" /> : <span style={{ color: "var(--text-faint)" }}>—</span>}</td>
                  <td style={{ padding: "13px 0", textAlign: "center" }}>{isPay && s._pay ? <button className="bny-iconbtn bny-iconbtn--sm" title="حذف الدفعة" aria-label="حذف الدفعة" onClick={() => setDelPay(s._pay)} style={{ color: "var(--danger)" }}><I.trash size={15} /></button> : null}</td>
                </tr>
                );
              })}
            </tbody>
          </table>
          </div>
          )}
        </Card>
        </>)}
      </div>
      </div>

      {/* نوافذ: عميل جديد + تسديد دين */}
      {showNew && <window.BnyNewCustomerModal orgs={D.organizations || []} onCreateOrg={createOrg} onSave={addCustomer} onClose={() => setShowNew(false)} />}
      {showPay && sel && <window.BnyPayModal title="تسديد دين" entityName={sel.name} dueIqd={sel.balance || 0} dueUsd={sel.balanceUsd || 0} onSave={payDebt} onClose={() => setShowPay(false)} />}
      {showEdit && sel && <EditCustomerModal c={sel} orgs={D.organizations || []} onSave={saveEdit} onClose={() => setShowEdit(false)} />}
      {payInv && (
        <window.BnyPayModal
          title={"تسديد فاتورة #" + payInv.no}
          entityName={payInv.party}
          dueIqd={payInv.cur === "usd" ? 0 : Math.max(0, (Number(payInv.total) || 0) - (Number(payInv.paid) || 0))}
          dueUsd={payInv.cur === "usd" ? Math.max(0, (Number(payInv.total) || 0) - (Number(payInv.paid) || 0)) : 0}
          onSave={(amount) => doPayInvoice(amount)}
          onClose={() => setPayInv(null)} />
      )}

      {/* كشف الديون الإجمالي انتقل إلى قسم «الحسابات» */}

      {/* ورقة الكشف للطباعة/PDF (مخفية على الشاشة) */}
      {printCust && (
        <div id="bny-stmt-print">
          <window.BnyStatementSheet shop={D.shop || {}} title={printData.title}
            entityName={printCust.name} entityMeta={"رقم العميل: " + printCust.id + (printCust.phone ? " · " + printCust.phone : "")}
            cols={printData.cols}
            rows={printData.rows}
            totals={[
              { label: "الرصيد المستحق (دينار)", value: Number(printCust.balance || 0).toLocaleString("en-US") + " د.ع", strong: true },
              printCust.balanceUsd ? { label: "الرصيد المستحق (دولار)", value: Number(printCust.balanceUsd).toLocaleString("en-US") + " $", strong: true } : { label: "", value: "" },
            ].filter((t) => t.label)}
          />
        </div>
      )}
      {delPay && (
        <window.BnyManagerConfirm
          title="حذف دفعة مسددة"
          message={"سيُحذف تسديد بمبلغ " + Number(delPay.amount || 0).toLocaleString("en-US") + " " + cur(delPay.cur) + (delPay.invNo ? " على الفاتورة #" + delPay.invNo : "") + "، وسيعود هذا المبلغ إلى دين العميل. لا يمكن التراجع."}
          confirmLabel="حذف الدفعة"
          onConfirm={confirmDeletePay} onClose={() => setDelPay(null)} />
      )}
    </div>
  );
}

/* نافذة تعديل بيانات عميل — الاسم/الهواتف/العنوان/النوع/المؤسسة */
function EditCustomerModal({ c, orgs, onSave, onClose }) {
  const I = window.BnyIcon;
  const { Button, Input, Select } = window.BonyanDesignSystem_ad3ca0;
  const [f, setF] = React.useState(() => ({ name: c.name || "", phone: c.phone || "", phone2: c.phone2 || "", address: c.address || "", type: c.type || "نقدي", org: c.org || "" }));
  const [busy, setBusy] = React.useState(false);
  const set = (k, v) => setF((s) => ({ ...s, [k]: v }));
  const lbl = { fontSize: 12.5, fontWeight: 600, color: "var(--text-strong)", display: "block", marginBottom: 5 };
  const save = async () => {
    if (!f.name.trim() || busy) return;
    setBusy(true);
    try { await onSave({ name: f.name.trim(), phone: f.phone.trim(), phone2: f.phone2.trim(), address: f.address.trim(), type: f.type, org: f.org || null }); }
    catch (e) { console.error(e); } finally { setBusy(false); }
  };
  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: 440, padding: 0, display: "flex", flexDirection: "column", maxHeight: "90vh" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "16px 20px", borderBottom: "1px solid var(--border-subtle)" }}>
          <h3 style={{ margin: 0, fontSize: 17, flex: 1 }}>تعديل بيانات: {c.name}</h3>
          <button onClick={onClose} style={{ border: 0, background: "none", cursor: "pointer", color: "var(--text-muted)", display: "inline-flex" }} aria-label="إغلاق"><I.x size={20} /></button>
        </div>
        <div style={{ overflowY: "auto", padding: "14px 20px", display: "flex", flexDirection: "column", gap: 12 }}>
          <div><label style={lbl}>الاسم الكامل *</label><Input value={f.name} onChange={(e) => set("name", e.target.value)} /></div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
            <div><label style={lbl}>الهاتف</label><Input value={f.phone} onChange={(e) => set("phone", e.target.value)} icon={<I.phone size={15} />} /></div>
            <div><label style={lbl}>هاتف ثانٍ</label><Input value={f.phone2} onChange={(e) => set("phone2", e.target.value)} /></div>
          </div>
          <div><label style={lbl}>العنوان</label><Input value={f.address} onChange={(e) => set("address", e.target.value)} /></div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
            <div>
              <label style={lbl}>نوع التعامل</label>
              <div className="bny-unit-toggle" role="group" style={{ width: "100%" }}>
                <button type="button" style={{ flex: 1 }} aria-pressed={f.type === "نقدي"} onClick={() => set("type", "نقدي")}>نقدي</button>
                <button type="button" style={{ flex: 1 }} aria-pressed={f.type === "آجل"} onClick={() => set("type", "آجل")}>آجل</button>
              </div>
            </div>
            <div>
              <label style={lbl}>المؤسسة</label>
              <Select value={f.org} onChange={(e) => set("org", e.target.value)}>
                <option value="">— مستقل —</option>
                {orgs.map((o) => <option key={o.id} value={o.id}>{o.name}</option>)}
              </Select>
            </div>
          </div>
          {f.name.trim() !== c.name && <p style={{ margin: 0, fontSize: 11.5, color: "var(--text-muted)" }}>تغيير الاسم سينعكس على كل فواتيره تلقائيًا — الحسابات مربوطة برقمه لا باسمه.</p>}
        </div>
        <div style={{ padding: "12px 20px", borderTop: "1px solid var(--border-subtle)", display: "flex", gap: 8, justifyContent: "flex-end" }}>
          <Button variant="secondary" onClick={onClose}>إلغاء</Button>
          <Button variant="accent" icon={<I.check size={15} />} onClick={save} disabled={!f.name.trim() || busy}>{busy ? "جارٍ الحفظ…" : "حفظ التعديلات"}</Button>
        </div>
      </div>
    </div>
  );
}

function Mini({ label, node }) {
  return (
    <div style={{ background: "var(--surface-sunken)", borderRadius: "var(--radius-md)", padding: "12px 14px" }}>
      <div style={{ fontSize: 12, color: "var(--text-muted)", marginBottom: 6 }}>{label}</div>
      {node}
    </div>
  );
}
window.CustomersScreen = CustomersScreen;
