/* Bonyan ERP — Suppliers list + account statement (multi-currency: د.ع + $) */
function SuppliersScreen() {
  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(); // إعادة الرسم عند تعديل/حذف فاتورة شراء من أي مكان
  // المورد المطلوب من المساعد الصوتي، وإلا الأول — null لمشترك جديد بلا موردين
  const [sel, setSel] = React.useState(() => {
    const pid = window.BnyPendingSupplierId;
    if (pid != null) { window.BnyPendingSupplierId = null; const s = D.suppliers.find((x) => x.id === pid); if (s) return s; }
    return D.suppliers[0] || null;
  });
  const [tab, setTab] = React.useState("stmt");
  const [curFilter, setCurFilter] = React.useState("all"); // all | iqd | usd
  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("");     // type:نقدي | type:آجل | ""
  const [printSup, setPrintSup] = 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 | purch | pay
  const saveEdit = async (patch) => {
    await window.BnyOps.updateSupplierInfo(sel, patch);
    setShowEdit(false); forceRender();
  };
  const [, forceRender] = React.useReducer((x) => x + 1, 0);
  const doPayInvoice = async (amount) => { await window.BnyOps.payInvoice(payInv, amount); setPayInv(null); forceRender(); };
  const confirmDeletePay = async (creds) => { await window.BnyOps.deleteSupplierPayment(delPay, creds); setDelPay(null); forceRender(); };
  const doPrint = () => { if (sel) { setPrintMode(tab === "purch" ? "purch" : tab); setPrintSup(sel); } };

  const addSupplier = async (data) => {
    const s = await window.BnyOps.addSupplier({ name: data.name.trim(), phone: (data.phone || "").trim(), type: data.type || "نقدي" });
    setShowNew(false); setSel(s); forceRender();
  };
  const payOut = async (amount, curKey) => {
    await window.BnyOps.paySupplier(sel, amount, curKey);
    setShowPay(false); forceRender();
  };
  // فاتورة شراء جديدة للمورد المحدَّد: مسودة تُفتح للتحرير فورًا
  const newPurchase = async () => {
    const inv = await window.BnyOps.newPurchaseDraft(sel.name, sel.id);
    window.BnyOpenInvoice(inv.no);
  };
  React.useEffect(() => {
    if (!printSup) return;
    document.body.classList.add("bny-printing-stmt");
    const after = () => { document.body.classList.remove("bny-printing-stmt"); setPrintSup(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"); };
  }, [printSup]);

  // فواتير الشراء الفعلية للمورد (بالمتبقّي والتسديد) — الأحدث أولًا
  const purchases = !sel ? [] : window.BnySupPurchaseInvoices(sel)
    .filter((i) => curFilter === "all" || i.cur === curFilter)
    .slice().sort((a, b) => String(b.date || "").localeCompare(String(a.date || "")));
  // كشف الحساب مشتقّ (فواتير شراء + دفعات صادرة) — الأقدم أعلى، أحدث دفعة أسفل
  const stmtRows = !sel ? [] : window.BnySupStatement(sel)
    .filter((s) => (curFilter === "all" || s.cur === curFilter) && (tab !== "pay" || s.debit > 0));

  const CurFilter = () => (
    <div style={{ display: "flex", justifyContent: "flex-end", marginTop: 12 }}>
      <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 supSortOptions = [
    { key: "debt-desc", label: "المستحقّات: الأعلى أولًا" },
    { key: "debt-asc", label: "المستحقّات: الأقل أولًا" },
    { key: "date-desc", label: "الأحدث حركة" },
    { key: "date-asc", label: "الأقدم حركة" },
  ];
  const supFilterOptions = [
    { value: "type:نقدي", label: "النوع: نقدي" },
    { value: "type:آجل", label: "النوع: آجل" },
  ];
  const toIqd = (s) => window.BnyToIqd(s.payable, s.payableUsd);
  const supRows = D.suppliers
    .filter((s) => { const q = search.trim(); if (!q) return true; return s.name.includes(q) || (s.phone || "").includes(q); })
    .filter((s) => { if (!filterVal) return true; if (filterVal.indexOf("type:") === 0) return s.type === filterVal.slice(5); 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, "sup") || "", db = window.BnyLastMovement(b.name, b.id, "sup") || "";
      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 supDebtRows = D.suppliers.map((s) => {
    const invs = window.BnySupPurchaseInvoices(s);
    const due = window.BnySupDue(s);
    return {
      id: s.id, name: s.name,
      total: invs.reduce((x, i) => x + iqdOf(i.total, i.cur), 0),
      paid: invs.reduce((x, i) => x + iqdOf(i.paid, i.cur), 0),
      remaining: window.BnyToIqd(due.iqd, due.usd),
      extra: s.lastPay || "", _s: s,
    };
  }).sort((a, b) => b.remaining - a.remaining);
  const showSupDetail = (r) => { setSel(r._s); try { window.scrollTo({ top: 0, behavior: "smooth" }); } catch (e) {} };
  // بيانات الطباعة حسب النمط: كشف / فواتير الشراء / الدفعات الصادرة
  const printData = (() => {
    if (!printSup) return { title: "", rows: [], cols: [] };
    if (printMode === "purch") {
      const rows = window.BnySupPurchaseInvoices(printSup).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.BnySupStatement(printSup);
    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={supSortOptions}
            filterVal={filterVal} onFilter={setFilterVal} filterOptions={supFilterOptions} filterLabel="التصفية حسب النوع" />
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
          {supRows.length === 0 && <div style={{ padding: "20px 8px", textAlign: "center", color: "var(--text-muted)", fontSize: 13 }}>لا موردون مطابقون</div>}
          {supRows.map((s) => {
            const on = sel && s.id === sel.id;
            const settled = s.payable === 0 && s.payableUsd === 0;
            return (
              <button key={s.id} onClick={() => setSel(s)} 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={s.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" }}>{s.name}</div>
                  <div style={{ fontSize: 11, color: "var(--text-muted)", fontFamily: "var(--font-mono)" }}>{s.phone}</div>
                </div>
                <div style={{ display: "flex", flexDirection: "column", alignItems: "flex-end", gap: 2 }}>
                  {settled && <Badge tone="success">مسدّد</Badge>}
                  {s.payable > 0 && <Money value={s.payable} unit="د.ع" tone="debt" style={{ fontSize: 12 }} />}
                  {s.payableUsd > 0 && <Money value={s.payableUsd} 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.supplier 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>
                <span style={{ color: "var(--text-faint)" }}>· آخر دفعة {sel.lastPay}</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.invoice size={16} />} onClick={newPurchase}>فاتورة شراء</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.invoice size={16} />} onClick={newPurchase}>فاتورة شراء</Button>
              <Button variant="accent" block icon={<I.wallet size={16} />} onClick={() => setShowPay(true)}>تسديد دفعة</Button>
            </div>
          )}
          {/* المستحق للمورد — العملتان منفصلتان */}
          <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr 1fr" : "repeat(3,1fr)", gap: 14, marginTop: 20 }}>
            <Mini label="مستحق — دينار" node={<Money value={sel.payable} unit="د.ع" tone={sel.payable > 0 ? "debt" : "credit"} style={{ fontSize: isMobile ? 19 : 22 }} />} />
            <Mini label="مستحق — دولار" node={<Money value={sel.payableUsd} unit="$" tone={sel.payableUsd > 0 ? "debt" : "credit"} style={{ fontSize: isMobile ? 19 : 22 }} />} />
            <Mini label="إجمالي المشتريات (السنة)" node={
              <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
                <Money value={sel.purchasesYtd} unit="د.ع" style={{ fontSize: 15 }} />
                <Money value={sel.purchasesYtdUsd} unit="$" style={{ fontSize: 15 }} />
              </div>
            } />
          </div>
        </Card>

        <Card>
          <Tabs value={tab} onChange={setTab} items={[
            { value: "stmt", label: "كشف الحساب" },
            { value: "purch", label: "فواتير الشراء" },
            { value: "pay", label: "الدفعات الصادرة" },
          ]} />
          <CurFilter />

          {tab === "purch" ? (
            <div style={{ display: "flex", flexDirection: "column", marginTop: 8 }}>
              {purchases.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 }}>
                        {window.BnyDate(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>
                );
              })}
              {purchases.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} · {s.debit ? "دفعة صادرة" : "مشتريات"} · {cur(s.cur)}</div>
                  </div>
                  {s.debit ? <Money value={s.debit} unit={cur(s.cur)} tone="credit" /> : <Money value={s.credit} unit={cur(s.cur)} tone="debt" />}
                  {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: 520 }}>
              <thead>
                <tr style={{ color: "var(--text-muted)", fontSize: 12 }}>
                  <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>
                    <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="credit" /> : <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="debt" /> : <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>
                  );
                })}
                {stmtRows.length === 0 && <tr><td colSpan={6} style={{ padding: "24px 0", textAlign: "center", color: "var(--text-muted)" }}>لا توجد حركات</td></tr>}
              </tbody>
            </table>
            </div>
            )
          )}
        </Card>
        </>)}
      </div>
      </div>

      {/* نوافذ: مورد جديد + تسديد دفعة */}
      {showNew && <NewSupplierModal onSave={addSupplier} onClose={() => setShowNew(false)} />}
      {showPay && sel && <window.BnyPayModal title="تسديد دفعة للمورد" entityName={sel.name} dueIqd={sel.payable || 0} dueUsd={sel.payableUsd || 0} onSave={payOut} onClose={() => setShowPay(false)} />}
      {showEdit && sel && <EditSupplierModal s={sel} 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)} />
      )}
      {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)} />
      )}

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

      {/* ورقة الكشف للطباعة/PDF (مخفية على الشاشة) */}
      {printSup && (
        <div id="bny-stmt-print">
          <window.BnyStatementSheet shop={D.shop || {}} title={printData.title}
            entityName={printSup.name} entityMeta={"رقم المورد: " + printSup.id + (printSup.phone ? " · " + printSup.phone : "")}
            cols={printData.cols}
            rows={printData.rows}
            totals={[
              { label: "المستحق له (دينار)", value: Number(printSup.payable || 0).toLocaleString("en-US") + " د.ع", strong: true },
              printSup.payableUsd ? { label: "المستحق له (دولار)", value: Number(printSup.payableUsd).toLocaleString("en-US") + " $", strong: true } : { label: "", value: "" },
            ].filter((t) => t.label)}
          />
        </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>
  );
}
/* نافذة مورد جديد: اسم + هاتف + نوع */
function NewSupplierModal({ onSave, onClose }) {
  const I = window.BnyIcon;
  const { Button, Input } = window.BonyanDesignSystem_ad3ca0;
  const [name, setName] = React.useState("");
  const [phone, setPhone] = React.useState("");
  const [type, setType] = React.useState("نقدي");
  const [busy, setBusy] = React.useState(false);
  const lbl = { fontSize: 12.5, fontWeight: 600, color: "var(--text-strong)", display: "block", marginBottom: 5 };
  const save = async () => {
    if (!name.trim() || busy) return;
    setBusy(true);
    try { await onSave({ name, phone, type }); } 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 bny-card--pad" style={{ width: "100%", maxWidth: 400 }}>
        <h3 style={{ margin: "0 0 14px", fontSize: 17 }}>مورد جديد</h3>
        <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
          <div><label style={lbl}>اسم المورد *</label><Input value={name} onChange={(e) => setName(e.target.value)} placeholder="مثال: مصنع حديد النجف" autoFocus /></div>
          <div><label style={lbl}>رقم الهاتف</label><Input value={phone} onChange={(e) => setPhone(e.target.value)} placeholder="07XXXXXXXXX" icon={<I.phone size={15} />} /></div>
          <div>
            <label style={lbl}>نوع التعامل</label>
            <div className="bny-unit-toggle" role="group" aria-label="نوع التعامل" style={{ width: "100%" }}>
              <button type="button" style={{ flex: 1 }} aria-pressed={type === "نقدي"} onClick={() => setType("نقدي")}>نقدي</button>
              <button type="button" style={{ flex: 1 }} aria-pressed={type === "آجل"} onClick={() => setType("آجل")}>آجل</button>
            </div>
          </div>
        </div>
        <div style={{ display: "flex", gap: 8, justifyContent: "flex-end", marginTop: 16 }}>
          <Button variant="secondary" onClick={onClose}>إلغاء</Button>
          <Button variant="accent" icon={<I.check size={15} />} onClick={save} disabled={!name.trim() || busy}>{busy ? "جارٍ الحفظ…" : "إضافة المورد"}</Button>
        </div>
      </div>
    </div>
  );
}
/* نافذة تعديل بيانات مورد */
function EditSupplierModal({ s, onSave, onClose }) {
  const I = window.BnyIcon;
  const { Button, Input } = window.BonyanDesignSystem_ad3ca0;
  const [f, setF] = React.useState(() => ({ name: s.name || "", phone: s.phone || "", type: s.type || "نقدي" }));
  const [busy, setBusy] = React.useState(false);
  const set = (k, v) => setF((x) => ({ ...x, [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(), type: f.type }); }
    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 bny-card--pad" style={{ width: "100%", maxWidth: 400 }}>
        <h3 style={{ margin: "0 0 14px", fontSize: 17 }}>تعديل بيانات: {s.name}</h3>
        <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
          <div><label style={lbl}>اسم المورد *</label><Input value={f.name} onChange={(e) => set("name", e.target.value)} /></div>
          <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>
            <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>
          {f.name.trim() !== s.name && <p style={{ margin: 0, fontSize: 11.5, color: "var(--text-muted)" }}>تغيير الاسم سينعكس على كل فواتير الشراء تلقائيًا.</p>}
        </div>
        <div style={{ display: "flex", gap: 8, justifyContent: "flex-end", marginTop: 16 }}>
          <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>
  );
}
window.SuppliersScreen = SuppliersScreen;
