/* Bonyan ERP — نافذة الفاتورة الموحّدة (تُستخدم في كل النظام)
   تعرض كل تفاصيل الفاتورة: المعلومات + الأصناف (المواد المباعة/المشتراة)
   مع إمكانية التعديل (الأصناف، الكميات، الأسعار، الجهة، الدفع) والحذف.
   أي شاشة تفتح فاتورة عبر:  window.BnyOpenInvoice(invoiceNo) */

/* ---- مخزن مركزي بسيط لمزامنة التعديلات عبر كل الشاشات ---- */
(function () {
  var subs = new Set();
  function emit() { subs.forEach(function (fn) { try { fn(); } catch (e) {} }); }
  function syncLegacy(no, inv) {
    var D = window.BnyData, st = window.BnyInvStatus(inv);
    [D.recentInvoices, D.purchaseInvoices].forEach(function (arr) {
      if (!arr) return;
      arr.forEach(function (r) { if (r.no === no) { r.no = inv.no; r.total = inv.total; r.cur = inv.cur; r.status = st.label; r.state = st.state; } });
    });
  }
  // في الوضع المباشر: احفظ التغيير في Supabase أيضًا (دون تعطيل تجاوب الواجهة).
  function persist(op, args) {
    if (!window.BnyConfigured || !window.BnyDB) return;
    var fn = window.BnyDB[op];
    if (!fn) return;
    fn.apply(window.BnyDB, args).catch(function (e) {
      console.warn("بُنيان: فشل حفظ الفاتورة في الخادم", e);
      try { window.alert("تعذّر حفظ التغيير في الخادم. تحقّق من الاتصال ثم أعد المحاولة."); } catch (x) {}
    });
  }
  window.BnyInvoices = {
    get: function (no) { return (window.BnyData.invoices || []).find(function (i) { return i.no === no; }); },
    save: function (no, patch) {
      var old = this.get(no); // لقطة ما قبل التعديل (لحساب فروق المخزون/الأرصدة)
      window.BnyData.invoices = window.BnyData.invoices.map(function (i) { return i.no === no ? patch : i; });
      syncLegacy(no, patch);
      emit();
      persist("saveInvoice", [no, patch]);
      if (window.BnyOps) {
        window.BnyOps.invoiceEffects(old, patch); // إعادة ضبط المخزون والأرصدة بالفرق
        window.BnyOps.log("invoice_update", "تعديل الفاتورة #" + patch.no + " («" + (patch.party || "—") + "») — الإجمالي " + (patch.total || 0).toLocaleString("en-US") + " " + (patch.cur === "usd" ? "$" : "د.ع"), patch.no);
      }
    },
    remove: function (no) {
      var D = window.BnyData;
      var old = this.get(no); // لعكس أثرها (إرجاع المخزون وتخفيض الدين)
      D.invoices = D.invoices.filter(function (i) { return i.no !== no; });
      if (D.recentInvoices) D.recentInvoices = D.recentInvoices.filter(function (r) { return r.no !== no; });
      if (D.purchaseInvoices) D.purchaseInvoices = D.purchaseInvoices.filter(function (r) { return r.no !== no; });
      emit();
      persist("removeInvoice", [no]);
      if (window.BnyOps) {
        if (old) window.BnyOps.invoiceEffects(old, null); // عكس أثر الفاتورة المحذوفة
        window.BnyOps.log("invoice_delete", "حذف الفاتورة #" + no, no);
      }
    },
    add: function (inv, opts) { // إضافة فاتورة — applyEffects عند النسخ فقط (البيع من POS يطبّق أثره بنفسه)
      window.BnyData.invoices = [inv].concat(window.BnyData.invoices || []);
      emit();
      persist("saveInvoice", [inv.no, inv]); // في الوضع المباشر: إدراج جديد
      if (opts && opts.applyEffects && window.BnyOps) window.BnyOps.invoiceEffects(null, inv);
    },
    subscribe: function (fn) { subs.add(fn); return function () { subs.delete(fn); }; },
    touch: function () { emit(); }, // إجبار إعادة الرسم بعد تغيير مسدَّد فاتورة (تسديد)
  };
})();

/* خطّاف يُعيد رسم الشاشة عند أي تعديل/حذف فاتورة */
window.useBnyInvoices = function () {
  var r = React.useReducer(function (x) { return x + 1; }, 0);
  React.useEffect(function () { return window.BnyInvoices.subscribe(r[1]); }, []);
  return window.BnyData.invoices;
};

function bnyCloneInv(inv) {
  return Object.assign({}, inv, { items: (inv.items || []).map(function (it) { return Object.assign({}, it); }) });
}

/* ---- النافذة: مستند فاتورة كامل (عرض + تعديل + طباعة + حذف) ---- */
function BnyInvoiceModal({ no, onClose }) {
  const I = window.BnyIcon, cur = window.BnyCur, status = window.BnyInvStatus, fmtDate = window.BnyDate;
  const { Button, Input, Select } = window.BonyanDesignSystem_ad3ca0;
  const isMobile = window.useBnyMobile();
  const shop = window.BnyData.shop || {};
  const source = window.BnyInvoices.get(no);
  const [draft, setDraft] = React.useState(() => (source ? bnyCloneInv(source) : null));
  const [confirmDel, setConfirmDel] = React.useState(false);
  const [matQ, setMatQ] = React.useState("");        // بحث المواد (إضافة مادة)
  const [matOpen, setMatOpen] = React.useState(false);
  const [partyQ, setPartyQ] = React.useState("");    // بحث العميل/المورد
  const [partyOpen, setPartyOpen] = React.useState(false);
  const [pendingParty, setPendingParty] = React.useState(null); // جهة بانتظار تأكيد التغيير

  // تنظيف صنف الطباعة عند انتهاء الطباعة
  React.useEffect(() => {
    const after = () => document.body.classList.remove("bny-printing-inv");
    window.addEventListener("afterprint", after);
    return () => { window.removeEventListener("afterprint", after); document.body.classList.remove("bny-printing-inv"); };
  }, []);
  if (!source || !draft) return null;

  const sym = cur(draft.cur);
  const num = (v) => Number(v) || 0;
  const lineTotal = (it) => num(it.qty) * num(it.price);
  const subtotal = (draft.items || []).reduce((s, it) => s + lineTotal(it), 0);
  const paid = Math.min(subtotal, Math.max(0, num(draft.paid)));
  const remaining = Math.max(0, subtotal - paid);
  const st = status({ total: subtotal, paid });
  const fmt = (n) => Number(n).toLocaleString("en-US");
  const partyLabel = draft.type === "sale" ? "العميل" : "المورد";
  const printInvoice = () => { document.body.classList.add("bny-printing-inv"); setTimeout(() => window.print(), 60); };

  const setF = (k, v) => setDraft((d) => ({ ...d, [k]: v }));
  const setItem = (idx, k, v) => setDraft((d) => ({ ...d, items: d.items.map((it, i) => (i === idx ? { ...it, [k]: v } : it)) }));
  const addItem = () => setDraft((d) => ({ ...d, items: [...(d.items || []), { name: "", unit: "قطعة", qty: 1, price: 0 }] }));
  // إضافة مادة من المخزن (بحث لحظي) — تعبّئ الاسم والوحدة والسعر تلقائيًا
  const addMaterial = (m) => {
    const price = draft.cur === "usd" ? (m.priceUsd || (m.pricesUsd && m.pricesUsd.main) || 0) : (m.price || (m.prices && m.prices.main) || 0);
    setDraft((d) => ({ ...d, items: [...(d.items || []), { name: m.name, unit: m.unit, qty: 1, price: price, sku: m.sku }] }));
    setMatQ(""); setMatOpen(false);
  };
  const removeItem = (idx) => setDraft((d) => ({ ...d, items: d.items.filter((_, i) => i !== idx) }));

  // التحقق من رقم الفاتورة: غير فارغ وغير مكرّر (يقارن مع باقي الفواتير)
  const noTrim = (draft.no || "").trim();
  const dupNo = noTrim !== "" && (window.BnyData.invoices || []).some((i) => i.no === noTrim && i.no !== no);
  const noError = noTrim === "" ? "أدخل رقم الفاتورة" : dupNo ? "رقم الفاتورة مستخدم في فاتورة أخرى" : "";

  const save = () => {
    if (noError) return; // لا يُحفظ مع رقم فارغ أو مكرّر
    const digits = noTrim.replace(/[^\d]/g, "");
    const items = (draft.items || [])
      .map((it) => ({ name: (it.name || "").trim(), unit: (it.unit || "").trim() || "قطعة", qty: num(it.qty), price: num(it.price), sku: it.sku || undefined }))
      .filter((it) => it.name !== "");
    const total = items.reduce((s, it) => s + it.qty * it.price, 0);
    const clean = {
      ...draft, no: noTrim, num: digits ? parseInt(digits, 10) : 0,
      items, total, paid: Math.min(total, Math.max(0, num(draft.paid))), party: (draft.party || "").trim() || "—",
    };
    window.BnyInvoices.save(no, clean);
    onClose();
  };
  const del = () => { window.BnyInvoices.remove(no); onClose(); };

  // ---- styles ----
  const overlay = { position: "fixed", inset: 0, zIndex: 1000, background: "var(--surface-overlay)", display: "flex", alignItems: isMobile ? "flex-end" : "center", justifyContent: "center", padding: isMobile ? 0 : "var(--space-6)" };
  const sheet = { width: "100%", maxWidth: 880, maxHeight: isMobile ? "96vh" : "94vh", overflowY: "auto", background: "var(--surface-card)", border: "1px solid var(--border-strong)", borderRadius: isMobile ? "var(--radius-lg) var(--radius-lg) 0 0" : "var(--radius-lg)", boxShadow: "var(--shadow-lg)" };
  const head = { position: "sticky", top: 0, zIndex: 1, display: "flex", alignItems: "center", justifyContent: "space-between", gap: 10, padding: "16px 18px", borderBottom: "1px solid var(--border-subtle)", background: "var(--surface-card)" };
  const body = { padding: 18, display: "flex", flexDirection: "column", gap: 16 };
  const lbl = { fontSize: 12, color: "var(--text-muted)", fontWeight: 600, marginBottom: 6, display: "block" };
  const cellInput = { height: 34, width: "100%", fontSize: 13, padding: "0 8px" };

  const typeBadge = draft.type === "sale"
    ? <span className="bny-badge bny-badge--brand">بيع</span>
    : <span className="bny-badge bny-badge--warning">شراء</span>;

  return (
    <div style={overlay} onClick={onClose} role="dialog" aria-modal="true">
      <div style={sheet} onClick={(e) => e.stopPropagation()}>
        <div style={head}>
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <span style={{ fontFamily: "var(--font-mono)", fontWeight: 700, fontSize: 18, color: "var(--text-strong)" }}>فاتورة #{draft.no}</span>
            {typeBadge}
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <Button variant="secondary" size="sm" icon={<I.printer size={16} />} onClick={printInvoice}>طباعة</Button>
            <button className="bny-iconbtn" aria-label="إغلاق" onClick={onClose}><I.x size={18} /></button>
          </div>
        </div>

        <div style={body}>
          {/* هوية المحل (كما تظهر في الطباعة) */}
          <div style={{ display: "flex", alignItems: "center", gap: 12, paddingBottom: 14, borderBottom: "2px solid var(--brand)" }}>
            {shop.logo
              ? <img src={shop.logo} alt="" style={{ width: 46, height: 46, objectFit: "contain", borderRadius: 6 }} />
              : <img src="../../assets/logo/bonyan-mark.svg" alt="" style={{ width: 42, height: 42 }} />}
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 18, fontWeight: 700, color: "var(--text-strong)" }}>{shop.name || "بُنيان"}</div>
              <div style={{ fontSize: 12, color: "var(--text-muted)" }}>{[shop.address, shop.phone].filter(Boolean).join(" · ")}</div>
            </div>
            <div style={{ textAlign: "end", fontSize: 12, color: "var(--text-muted)", fontFamily: "var(--font-mono)" }}>
              <div>{draft.type === "sale" ? "فاتورة بيع" : "فاتورة شراء"}</div>
              <div>{fmtDate(draft.date)}</div>
            </div>
          </div>
          {/* معلومات الفاتورة */}
          <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr 1fr" : "1fr 1fr 1fr 1fr", gap: 12 }}>
            <div style={{ gridColumn: isMobile ? "span 2" : "auto" }}>
              <label style={lbl}>رقم الفاتورة</label>
              <Input value={draft.no} onChange={(e) => setF("no", e.target.value)} placeholder="مثال: 10429"
                error={noError || undefined} style={{ fontFamily: "var(--font-mono)" }} />
            </div>
            <div>
              <label style={lbl}>النوع</label>
              <Select value={draft.type} onChange={(e) => setF("type", e.target.value)}>
                <option value="sale">بيع</option>
                <option value="purchase">شراء</option>
              </Select>
            </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={draft.cur === "iqd"} onClick={() => setF("cur", "iqd")}>د.ع</button>
                <button type="button" style={{ flex: 1 }} aria-pressed={draft.cur === "usd"} onClick={() => setF("cur", "usd")}>دولار</button>
              </div>
            </div>
            <div style={{ gridColumn: isMobile ? "span 2" : "auto", position: "relative" }}>
              <label style={lbl}>{draft.type === "sale" ? "العميل" : "المورد"}</label>
              <input className="bny-input" value={partyOpen ? partyQ : draft.party}
                onFocus={() => { setPartyOpen(true); setPartyQ(""); }}
                onChange={(e) => { setPartyQ(e.target.value); setPartyOpen(true); }}
                placeholder="ابحث بالاسم…" aria-label="اختيار الجهة" style={{ width: "100%" }} />
              {partyOpen && (() => {
                const DB = window.BnyData;
                const src = draft.type === "sale" ? (DB.customers || []).filter((c) => !c.walkin) : (DB.suppliers || []);
                const ql = partyQ.trim();
                const opts = src.filter((x) => !ql || (x.name || "").includes(ql)).slice(0, 8);
                return (
                  <>
                    <div onClick={() => setPartyOpen(false)} style={{ position: "fixed", inset: 0, zIndex: 9 }} />
                    <div style={{ position: "absolute", insetInlineStart: 0, insetInlineEnd: 0, top: "calc(100% + 4px)", zIndex: 10, background: "var(--surface-card)", border: "1px solid var(--border-subtle)", borderRadius: "var(--radius-md)", boxShadow: "var(--shadow-lg)", maxHeight: 220, overflowY: "auto" }}>
                      {opts.map((x) => (
                        <div key={x.id} onClick={() => { setPartyOpen(false); if ((x.name || "") !== draft.party) setPendingParty({ name: x.name, id: x.id }); }}
                          onMouseEnter={(e) => (e.currentTarget.style.background = "var(--surface-hover)")} onMouseLeave={(e) => (e.currentTarget.style.background = "transparent")}
                          style={{ padding: "9px 12px", cursor: "pointer", borderBottom: "1px solid var(--border-subtle)", fontSize: 13, fontWeight: 600, color: "var(--text-strong)" }}>{x.name}</div>
                      ))}
                      {opts.length === 0 && <div style={{ padding: "12px", textAlign: "center", color: "var(--text-muted)", fontSize: 13 }}>لا نتائج</div>}
                    </div>
                  </>
                );
              })()}
            </div>
            <div style={{ gridColumn: isMobile ? "span 2" : "auto" }}>
              <label style={lbl}>التاريخ</label>
              <input className="bny-input" type="date" value={draft.date} onChange={(e) => setF("date", e.target.value)} style={{ width: "100%", height: 40, padding: "0 10px", fontFamily: "var(--font-mono)" }} />
            </div>
          </div>

          {/* الأصناف (المواد) */}
          <div>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 8, gap: 10, flexWrap: "wrap" }}>
              <span style={{ fontWeight: 700, color: "var(--text-strong)" }}>الأصناف ({(draft.items || []).length})</span>
              <div style={{ position: "relative", flex: "0 1 320px", minWidth: 200 }}>
                <div style={{ display: "flex", gap: 6 }}>
                  <input className="bny-input" value={matQ} onFocus={() => setMatOpen(true)}
                    onChange={(e) => { setMatQ(e.target.value); setMatOpen(true); }}
                    placeholder="إضافة مادة — بحث لحظي بالمخزن…" aria-label="إضافة مادة" style={{ flex: 1, height: 36, fontSize: 13 }} />
                  <Button variant="secondary" size="sm" icon={<I.plus size={15} />} onClick={addItem} title="إضافة صنف يدوي (بدون ربط بالمخزن)">يدوي</Button>
                </div>
                {matOpen && (() => {
                  const DB = window.BnyData; const ql = matQ.trim();
                  const ms = (DB.materials || []).filter((m) => !ql || (m.name + m.sku + (m.cat || "")).includes(ql)).slice(0, 8);
                  return (
                    <>
                      <div onClick={() => setMatOpen(false)} style={{ position: "fixed", inset: 0, zIndex: 9 }} />
                      <div style={{ position: "absolute", insetInlineStart: 0, insetInlineEnd: 0, top: "calc(100% + 4px)", zIndex: 10, background: "var(--surface-card)", border: "1px solid var(--border-subtle)", borderRadius: "var(--radius-md)", boxShadow: "var(--shadow-lg)", maxHeight: 240, overflowY: "auto" }}>
                        {ms.map((m) => (
                          <div key={m.sku} onClick={() => addMaterial(m)}
                            onMouseEnter={(e) => (e.currentTarget.style.background = "var(--surface-hover)")} onMouseLeave={(e) => (e.currentTarget.style.background = "transparent")}
                            style={{ display: "flex", justifyContent: "space-between", gap: 8, padding: "9px 12px", cursor: "pointer", borderBottom: "1px solid var(--border-subtle)" }}>
                            <div style={{ minWidth: 0 }}>
                              <div style={{ fontSize: 13, 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.stock} {m.unit}</div>
                            </div>
                            <span style={{ fontFamily: "var(--font-mono)", fontSize: 12.5, color: "var(--text-muted)", flex: "none" }}>{(draft.cur === "usd" ? (m.priceUsd || 0) : (m.price || 0)).toLocaleString("en-US")} {sym}</span>
                          </div>
                        ))}
                        {ms.length === 0 && <div style={{ padding: "12px", textAlign: "center", color: "var(--text-muted)", fontSize: 13 }}>لا مواد مطابقة</div>}
                      </div>
                    </>
                  );
                })()}
              </div>
            </div>

            {isMobile ? (
              <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
                {(draft.items || []).map((it, idx) => (
                  <div key={idx} style={{ border: "1px solid var(--border-subtle)", borderRadius: "var(--radius-md)", padding: 10, display: "flex", flexDirection: "column", gap: 8 }}>
                    <div style={{ display: "flex", gap: 8 }}>
                      <input className="bny-input" value={it.name} onChange={(e) => setItem(idx, "name", e.target.value)} placeholder="اسم المادة" style={{ ...cellInput, flex: 1 }} />
                      <button className="bny-iconbtn bny-iconbtn--sm" aria-label="حذف الصنف" onClick={() => removeItem(idx)} style={{ color: "var(--danger)", flex: "none" }}><I.trash size={15} /></button>
                    </div>
                    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 8 }}>
                      <input className="bny-input" value={it.unit} onChange={(e) => setItem(idx, "unit", e.target.value)} placeholder="الوحدة" style={cellInput} />
                      <input className="bny-input bny-input--numeric" type="number" min="0" value={it.qty} onChange={(e) => setItem(idx, "qty", e.target.value)} placeholder="الكمية" style={cellInput} />
                      <input className="bny-input bny-input--numeric" type="number" min="0" value={it.price} onChange={(e) => setItem(idx, "price", e.target.value)} placeholder="السعر" style={cellInput} />
                    </div>
                    <div style={{ textAlign: "end", fontSize: 13 }}>
                      <span style={{ color: "var(--text-muted)" }}>المجموع: </span>
                      <b style={{ fontFamily: "var(--font-mono)" }}>{fmt(lineTotal(it))} {sym}</b>
                    </div>
                  </div>
                ))}
                {(draft.items || []).length === 0 && <div style={{ padding: 16, textAlign: "center", color: "var(--text-muted)" }}>لا أصناف — أضِف صنفًا.</div>}
              </div>
            ) : (
              <div style={{ overflowX: "auto", border: "1px solid var(--border-subtle)", borderRadius: "var(--radius-md)" }}>
                <table style={{ width: "100%", borderCollapse: "collapse", minWidth: 560 }}>
                  <thead>
                    <tr style={{ color: "var(--text-muted)", fontSize: 12, background: "var(--surface-sunken)" }}>
                      <th style={{ ...mth, textAlign: "start" }}>المادة</th>
                      <th style={{ ...mth, width: 90 }}>الوحدة</th>
                      <th style={{ ...mth, width: 90 }}>الكمية</th>
                      <th style={{ ...mth, width: 120 }}>سعر الوحدة</th>
                      <th style={{ ...mth, textAlign: "end", width: 130 }}>المجموع</th>
                      <th style={{ ...mth, width: 40 }}></th>
                    </tr>
                  </thead>
                  <tbody>
                    {(draft.items || []).map((it, idx) => (
                      <tr key={idx} style={{ borderTop: "1px solid var(--border-subtle)" }}>
                        <td style={mtd}><input className="bny-input" value={it.name} onChange={(e) => setItem(idx, "name", e.target.value)} placeholder="اسم المادة" style={cellInput} /></td>
                        <td style={mtd}><input className="bny-input" value={it.unit} onChange={(e) => setItem(idx, "unit", e.target.value)} style={cellInput} /></td>
                        <td style={mtd}><input className="bny-input bny-input--numeric" type="number" min="0" value={it.qty} onChange={(e) => setItem(idx, "qty", e.target.value)} style={cellInput} /></td>
                        <td style={mtd}><input className="bny-input bny-input--numeric" type="number" min="0" value={it.price} onChange={(e) => setItem(idx, "price", e.target.value)} style={cellInput} /></td>
                        <td style={{ ...mtd, textAlign: "end", fontFamily: "var(--font-mono)", fontWeight: 600, whiteSpace: "nowrap" }}>{fmt(lineTotal(it))} {sym}</td>
                        <td style={{ ...mtd, textAlign: "center" }}><button className="bny-iconbtn bny-iconbtn--sm" aria-label="حذف الصنف" onClick={() => removeItem(idx)} style={{ color: "var(--danger)" }}><I.trash size={15} /></button></td>
                      </tr>
                    ))}
                    {(draft.items || []).length === 0 && (
                      <tr><td colSpan={6} style={{ padding: 16, textAlign: "center", color: "var(--text-muted)" }}>لا أصناف — أضِف صنفًا.</td></tr>
                    )}
                  </tbody>
                </table>
              </div>
            )}
          </div>

          {/* الإجمالي والدفع */}
          <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr" : "1fr 1fr", gap: 14, alignItems: "start" }}>
            <div>
              <label style={lbl}>المبلغ المسدّد ({sym})</label>
              <Input numeric type="number" min="0" value={draft.paid} onChange={(e) => setF("paid", e.target.value)} />
            </div>
            <div style={{ background: "var(--surface-sunken)", borderRadius: "var(--radius-md)", padding: "12px 14px", display: "flex", flexDirection: "column", gap: 8 }}>
              <div style={{ display: "flex", justifyContent: "space-between", fontSize: 13.5 }}>
                <span style={{ color: "var(--text-muted)" }}>الإجمالي</span>
                <b style={{ fontFamily: "var(--font-mono)" }}>{fmt(subtotal)} {sym}</b>
              </div>
              <div style={{ display: "flex", justifyContent: "space-between", fontSize: 13.5 }}>
                <span style={{ color: "var(--text-muted)" }}>المتبقي</span>
                <b style={{ fontFamily: "var(--font-mono)", color: remaining > 0 ? "var(--danger)" : "var(--success)" }}>{fmt(remaining)} {sym}</b>
              </div>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", fontSize: 13.5 }}>
                <span style={{ color: "var(--text-muted)" }}>الحالة</span>
                <span className={`bny-badge bny-badge--${st.state}`}><span className="bny-badge__dot" />{st.label}</span>
              </div>
            </div>
          </div>

          {/* أزرار */}
          {confirmDel ? (
            <div style={{ display: "flex", flexDirection: "column", gap: 10, padding: 14, background: "var(--danger-soft)", borderRadius: "var(--radius-md)" }}>
              <div style={{ display: "flex", gap: 8, alignItems: "flex-start", color: "var(--danger-text)", fontSize: 13.5, fontWeight: 600 }}>
                <I.alert size={18} /><span>هل أنت متأكد من حذف الفاتورة #{draft.no}؟ لا يمكن التراجع.</span>
              </div>
              <div style={{ display: "flex", gap: 10 }}>
                <Button variant="danger" block icon={<I.trash size={16} />} onClick={del}>نعم، احذف</Button>
                <Button variant="secondary" block onClick={() => setConfirmDel(false)}>تراجع</Button>
              </div>
            </div>
          ) : (
            <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
              <Button variant="danger" icon={<I.trash size={16} />} onClick={() => setConfirmDel(true)}>حذف الفاتورة</Button>
              <div style={{ flex: 1 }} />
              <Button variant="secondary" onClick={onClose}>إلغاء</Button>
              <Button variant="accent" icon={<I.check size={16} />} onClick={save} disabled={!!noError}>حفظ التعديلات</Button>
            </div>
          )}
        </div>

        {/* تأكيد تغيير الجهة قبل الاعتماد */}
        {pendingParty && (
          <div onClick={() => setPendingParty(null)} style={{ position: "fixed", inset: 0, zIndex: 1100, 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: 410 }}>
              <h3 style={{ margin: "0 0 8px", fontSize: 16 }}>تغيير {draft.type === "sale" ? "العميل" : "المورد"}</h3>
              <p style={{ margin: "0 0 16px", fontSize: 13, color: "var(--text-muted)", lineHeight: 1.6 }}>
                سيتم تغيير الجهة من «<b style={{ color: "var(--text-strong)" }}>{draft.party || "—"}</b>» إلى «<b style={{ color: "var(--text-strong)" }}>{pendingParty.name}</b>» في هذه الفاتورة. هل تريد التأكيد؟
              </p>
              <div style={{ display: "flex", gap: 8, justifyContent: "flex-end" }}>
                <Button variant="secondary" onClick={() => setPendingParty(null)}>إلغاء</Button>
                <Button variant="accent" icon={<I.check size={16} />} onClick={() => {
                  // اربط بالمعرّف أيضًا حتى لا يتأثر الحساب بتغيير الاسم لاحقًا
                  setDraft((d) => ({ ...d, party: pendingParty.name,
                    custId: d.type === "sale" ? pendingParty.id : d.custId,
                    supId: d.type === "purchase" ? pendingParty.id : d.supId }));
                  setPendingParty(null);
                }}>تأكيد التغيير</Button>
              </div>
            </div>
          </div>
        )}

        {/* ورقة الطباعة A4 (مخفية على الشاشة) */}
        <div id="bny-inv-print">
          <div className="bny-print-sheet">
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", borderBottom: "2px solid var(--blue-900)", paddingBottom: 16, marginBottom: 20 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
                {shop.logo
                  ? <img src={shop.logo} alt="" style={{ width: 54, height: 54, objectFit: "contain", borderRadius: 6 }} />
                  : <img src="../../assets/logo/bonyan-mark.svg" alt="" style={{ width: 48, height: 48 }} />}
                <div>
                  <div style={{ fontSize: 24, fontWeight: 700, color: "var(--blue-900)" }}>{shop.name || "بُنيان"}</div>
                  {shop.address ? <div style={{ fontSize: 12, color: "#555" }}>{shop.address}</div> : null}
                  {shop.phone ? <div style={{ fontSize: 12, color: "#555", fontFamily: "var(--font-mono)" }}>هاتف: {shop.phone}</div> : null}
                </div>
              </div>
              <div style={{ textAlign: "end", fontFamily: "var(--font-mono)", fontSize: 13 }}>
                <div><b>{draft.type === "sale" ? "فاتورة بيع" : "فاتورة شراء"} #{draft.no}</b></div>
                <div style={{ color: "#555" }}>التاريخ: {fmtDate(draft.date)}</div>
                <div style={{ color: "#555" }}>العملة: {draft.cur === "usd" ? "دولار ($)" : "دينار (د.ع)"}</div>
              </div>
            </div>
            <div style={{ display: "flex", justifyContent: "space-between", fontSize: 13, marginBottom: 16 }}>
              <div><span style={{ color: "#555" }}>{partyLabel}: </span><b>{draft.party}</b></div>
              <div><span style={{ color: "#555" }}>الحالة: </span><b>{st.label}</b></div>
            </div>
            <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13 }}>
              <thead>
                <tr style={{ background: "#f0efec" }}>
                  <th style={pTh}>المادة</th>
                  <th style={{ ...pTh, textAlign: "center" }}>الوحدة</th>
                  <th style={{ ...pTh, textAlign: "center" }}>الكمية</th>
                  <th style={pTh}>سعر الوحدة</th>
                  <th style={{ ...pTh, textAlign: "end" }}>المجموع</th>
                </tr>
              </thead>
              <tbody>
                {(draft.items || []).map((it, idx) => (
                  <tr key={idx} style={{ borderBottom: "1px solid #e5e3df" }}>
                    <td style={pTd}>{it.name}</td>
                    <td style={{ ...pTd, textAlign: "center" }}>{it.unit}</td>
                    <td style={{ ...pTd, textAlign: "center", fontFamily: "var(--font-mono)" }}>{num(it.qty)}</td>
                    <td style={{ ...pTd, fontFamily: "var(--font-mono)" }}>{fmt(num(it.price))} {sym}</td>
                    <td style={{ ...pTd, textAlign: "end", fontFamily: "var(--font-mono)" }}>{fmt(lineTotal(it))} {sym}</td>
                  </tr>
                ))}
              </tbody>
            </table>
            <div style={{ display: "flex", justifyContent: "flex-start", marginTop: 18 }}>
              <div style={{ width: 280, fontSize: 14 }}>
                <div style={{ display: "flex", justifyContent: "space-between", padding: "8px 0", borderTop: "2px solid var(--blue-900)", fontWeight: 700, fontSize: 16 }}><span>الإجمالي</span><span style={{ fontFamily: "var(--font-mono)" }}>{fmt(subtotal)} {sym}</span></div>
                <div style={{ display: "flex", justifyContent: "space-between", padding: "4px 0" }}><span style={{ color: "#555" }}>المسدّد</span><span style={{ fontFamily: "var(--font-mono)" }}>{fmt(paid)} {sym}</span></div>
                <div style={{ display: "flex", justifyContent: "space-between", padding: "4px 0" }}><span style={{ color: "#555" }}>المتبقي</span><span style={{ fontFamily: "var(--font-mono)" }}>{fmt(remaining)} {sym}</span></div>
              </div>
            </div>
            <div style={{ marginTop: 28, fontSize: 11, color: "#555", textAlign: "center" }}>{shop.footer || ""}</div>
          </div>
        </div>
      </div>
    </div>
  );
}
const pTh = { textAlign: "start", fontWeight: 600, padding: "8px 10px", borderBottom: "1px solid #333" };
const pTd = { padding: "8px 10px" };
const mth = { fontWeight: 600, padding: "10px 8px", textAlign: "center" };
const mtd = { padding: "6px 8px" };
window.BnyInvoiceModal = BnyInvoiceModal;

/* ---- المضيف: يُركَّب مرة واحدة في App، ويفتح أي فاتورة عند الطلب ---- */
function InvoiceModalHost() {
  const [no, setNo] = React.useState(null);
  React.useEffect(() => {
    window.__bnyOpenInvoice = (n) => setNo(n);
    return () => { window.__bnyOpenInvoice = null; };
  }, []);
  if (no == null) return null;
  return <BnyInvoiceModal key={no} no={no} onClose={() => setNo(null)} />;
}
window.InvoiceModalHost = InvoiceModalHost;

/* الواجهة العامة: استدعِها من أي شاشة لفتح فاتورة */
window.BnyOpenInvoice = function (no) { if (window.__bnyOpenInvoice) window.__bnyOpenInvoice(no); };

/* استخراج الفاتورة من نص بيان كشف الحساب (مثل: "فاتورة 10428"، "فاتورة شراء PINV-3391") */
window.BnyInvoiceFromRef = function (ref) {
  return (window.BnyData.invoices || []).find(function (iv) { return ref && ref.indexOf(iv.no) !== -1; }) || null;
};
