/* Bonyan ERP — New invoice / POS
   Features: multi-unit selling, multi-currency, price lists + manual override,
   direct discount (amount/percent), and dual print copies (sales / picking). */
function PosScreen() {
  const I = window.BnyIcon;
  const D = window.BnyData;
  const shop = D.shop; // هوية المحل (تُخصَّص من شاشة الإعدادات)
  const { SearchBar, Card, Button, Money, Badge, Select, Avatar, Input, Switch } = window.BonyanDesignSystem_ad3ca0;
  const isMobile = window.useBnyMobile();
  const [q, setQ] = React.useState("");
  const [listening, setListening] = React.useState(false);
  // كل سطر يحمل معرّفًا فريدًا (rid) — يسمح بتكرار المادة بوحدات بيع مختلفة بلا تضارب
  const [lines, setLines] = React.useState([]); // فاتورة جديدة تبدأ فارغة — تُضاف الأصناف يدويًا
  // قوائم محليّة قابلة للإضافة (عميل/مؤسسة جديدة) — تُكتب في window.BnyData وتُربط لاحقًا بالـ backend
  const [custList, setCustList] = React.useState(() => D.customers.slice());
  const [orgList, setOrgList] = React.useState(() => (D.organizations || []).slice());
  const [cust, setCust] = React.useState(() => window.BnyWalkin() || D.customers[0]); // افتراضيًا: زبون مستطرق
  const [walkName, setWalkName] = React.useState("");      // اسم الزبون العابر — للطباعة فقط (لا يُسجَّل عميلًا)
  const [custQuery, setCustQuery] = React.useState("");
  const [custOpen, setCustOpen] = React.useState(false);
  const [showNewCust, setShowNewCust] = React.useState(false);
  const [mgrAsked, setMgrAsked] = React.useState(false);
  const orgName = (id) => (orgList.find((o) => o.id === id) || {}).name || "";
  // الاسم المعروض/المطبوع: للزبون المستطرق نستخدم الاسم العابر إن كُتب
  const custDisplayName = cust.walkin ? (walkName.trim() || cust.name) : cust.name;
  const [invCur, setInvCur] = React.useState("iqd");      // عملة الفاتورة: iqd | usd
  const [priceType, setPriceType] = React.useState("main"); // نوع التسعير
  const [discountType, setDiscountType] = React.useState("amount"); // amount | percent
  const [discountValue, setDiscountValue] = React.useState("");
  const [paid, setPaid] = React.useState("");                        // المبلغ المسدد
  const [invDate, setInvDate] = React.useState(() => window.BnyOps.todayIso()); // تاريخ الفاتورة (قابل للتغيير)
  const [printMode, setPrintMode] = React.useState("sales"); // sales | picking

  const isUsd = invCur === "usd";
  const curSym = window.BnyCur(invCur);

  // ---- unit + pricing helpers ----
  const unitLabel = (l) => (l.unitMode === "pack" && l.hasMultiUnits ? l.packUnit : l.unit);
  const factor = (l) => (l.unitMode === "pack" && l.hasMultiUnits ? l.subUnitCount : 1);
  const liveMat = (l) => D.materials.find((m) => m.sku === l.sku) || l;
  const basePrice = (l) => {                                // سعر الوحدة الصغرى للنوع المختار (يدوي لكل مادة)
    const m = liveMat(l);
    const map = isUsd ? m.pricesUsd : m.prices;
    if (map && map[priceType] != null) return map[priceType];
    if (map && map.main != null) return map.main;
    return isUsd ? m.priceUsd : m.price;
  };
  const computedUnit = (l) => basePrice(l) * factor(l);     // سعر الوحدة المختارة
  const effUnit = (l) => (l.priceOverride != null ? l.priceOverride : computedUnit(l)); // مع التعديل اليدوي
  const baseQty = (l) => (Number(l.qty) || 0) * factor(l);  // بالوحدة الصغرى (لتحديث المخزن)
  const lineTotal = (l) => effUnit(l) * (Number(l.qty) || 0);

  const clearOverrides = () => setLines((ls) => ls.map((l) => ({ ...l, priceOverride: undefined })));
  const setCurrency = (c) => { setInvCur(c); clearOverrides(); };
  const setType = (id) => { setPriceType(id); clearOverrides(); };

  const results = q ? D.materials.filter((m) => (m.name + m.sku + m.cat).includes(q)) : [];
  // اقتراحات إرشادية: الأكثر مبيعًا هذا الشهر، وإلا المتوفر في المخزن. فارغة إذا لا مواد.
  const inStock = D.materials.filter((m) => Number(m.stock) > 0);
  const topSell = window.BnyTopProductsThisMonth(8).map((p) => D.materials.find((m) => m.name === p.name)).filter(Boolean);
  const suggestPool = (topSell.length ? topSell : inStock).slice(0, 6);
  const exampleNames = suggestPool.slice(0, 2).map((m) => m.name);
  const searchPlaceholder = exampleNames.length ? ("أضف مادة… مثل: " + exampleNames.join(" أو ")) : (D.materials.length ? "ابحث عن مادة" : "");
  const add = (m) => {
    setLines((ls) => {
      // ادمج فقط مع سطر بنفس المادة ونفس وحدة البيع الأساسية؛ غير ذلك = سطر جديد مستقل
      const ex = ls.find((l) => l.sku === m.sku && l.unitMode === "base");
      if (ex) return ls.map((l) => (l === ex ? { ...l, qty: (Number(l.qty) || 0) + 1 } : l));
      return [...ls, { ...m, rid: bnyRid(), qty: 1, unitMode: "base" }];
    });
    setQ("");
  };
  const setQty = (rid, qty) => setLines((ls) => ls.map((l) => (l.rid === rid ? { ...l, qty } : l)));
  const stepQty = (l, d) => setQty(l.rid, Math.max(1, (Number(l.qty) || 0) + d));
  const typeQty = (l, raw) => setQty(l.rid, String(raw).replace(/[^\d.]/g, ""));       // إدخال مباشر
  const blurQty = (l) => { const n = parseFloat(l.qty); setQty(l.rid, (!n || n < 1) ? 1 : n); };
  const setMode = (rid, unitMode) => setLines((ls) => ls.map((l) => (l.rid === rid ? { ...l, unitMode, priceOverride: undefined } : l)));
  const setOverride = (rid, raw) => setLines((ls) => ls.map((l) => {
    if (l.rid !== rid) return l;
    const v = raw === "" ? undefined : Number(raw);
    return { ...l, priceOverride: (v == null || Number.isNaN(v)) ? undefined : v };
  }));
  const remove = (rid) => setLines((ls) => ls.filter((l) => l.rid !== rid));

  // إنشاء عميل/مؤسسة جديدة — تُحفظ محليًا وفي القاعدة (BnyOps)
  const createCustomer = async (data) => {
    try {
      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,
      });
      setCustList(D.customers.slice()); setCust(c); setCustOpen(false); setShowNewCust(false);
    } catch (e) {
      console.error(e); try { window.alert("تعذّر حفظ العميل — تحقّق من الاتصال."); } catch (x) {}
    }
  };
  const createOrg = (data) => {
    const id = "org-" + Date.now();
    const o = { id, name: data.name.trim(), phone: "", type: "شركة", notes: (data.notes || "").trim() };
    window.BnyOps.addOrganization(o); // يدفع محليًا فورًا ويثبّت في القاعدة
    setOrgList((D.organizations || []).slice());
    return o;
  };

  const subtotal = lines.reduce((s, l) => s + lineTotal(l), 0);
  const dv = Number(discountValue) || 0;
  let discountAmount = discountType === "percent" ? subtotal * dv / 100 : dv;
  discountAmount = Math.min(subtotal, Math.max(0, discountAmount));
  if (!isUsd) discountAmount = Math.round(discountAmount);
  const total = Math.max(0, subtotal - discountAmount);
  const paidNum = Math.min(total, Math.max(0, Number(paid) || 0)); // المسدد لا يتجاوز الإجمالي
  const remaining = Math.max(0, total - paidNum);                  // المتبقي (لحظي)
  const custBalance = isUsd ? cust.balanceUsd : cust.balance;
  const hasLimit = !!cust.limitEnabled; // السقف غير مفعّل افتراضيًا (ائتمان غير محدود)
  const custLimit = isUsd ? cust.limitUsd : cust.limit;
  const newBalance = custBalance + remaining; // يُضاف للدين المتبقي فقط (لا الإجمالي)
  const over = hasLimit && newBalance > custLimit && cust.type === "آجل";
  const [saved, setSaved] = React.useState(null);   // الفاتورة المحفوظة (بعد التأكيد)
  const [saving, setSaving] = React.useState(false);
  const invoiceNo = saved ? saved.no : String(((D.numbering || {}).sale || {}).next || "");
  const today = window.BnyDate(invDate); // يظهر في الطباعة بتاريخ الفاتورة المختار

  const printCopy = (mode) => { setPrintMode(mode); setTimeout(() => window.print(), 80); };

  // ---- حفظ وتأكيد البيع: فاتورة + خصم مخزون + رصيد وكشف العميل ----
  const canSave = lines.length > 0 && total > 0 && !over && !saving;
  const confirmSale = async () => {
    if (!canSave) return;
    setSaving(true);
    try {
      const inv = await window.BnyOps.saveSale({
        lines: lines.map((l) => ({ sku: l.sku, name: l.name, unitLabel: unitLabel(l), baseQty: baseQty(l), qty: Number(l.qty) || 0, price: effUnit(l) })),
        cust, party: custDisplayName, cur: invCur, total, paid: paidNum, remaining, date: invDate,
      });
      setSaved(inv);
    } catch (e) {
      console.error("Bonyan saveSale:", e);
      try { window.alert("تعذّر حفظ الفاتورة — تحقّق من الاتصال ثم أعد المحاولة."); } catch (x) {}
    }
    setSaving(false);
  };
  const resetSale = () => { setLines([]); setPaid(""); setDiscountValue(""); setWalkName(""); setSaved(null); setMgrAsked(false); setInvDate(window.BnyOps.todayIso()); };

  // ---- إرسال الفاتورة واتساب ----
  const waInvoice = () => {
    const itemsTxt = lines.map((l) => "• " + l.name + " — " + l.qty + " " + unitLabel(l)).join("\n");
    const msg = "فاتورة " + (saved ? "#" + saved.no + " " : "") + "من " + (shop.name || "بُنيان") + "\n"
      + "العميل: " + custDisplayName + "\n" + itemsTxt + "\n"
      + "الإجمالي: " + total.toLocaleString("en-US") + " " + curSym
      + (paidNum > 0 ? "\nالمسدد: " + paidNum.toLocaleString("en-US") + " " + curSym : "")
      + (remaining > 0 ? "\nالمتبقي: " + remaining.toLocaleString("en-US") + " " + curSym : "")
      + "\nشكرًا لتعاملكم معنا.";
    const url = cust.phone ? window.BnyWaLink(cust.phone, msg) : "https://wa.me/?text=" + encodeURIComponent(msg);
    try { window.open(url, "_blank"); } catch (e) {}
  };

  // فاصلة لكل 3 مراتب لمنع الخطأ
  const fmtNum = (n) => (n === "" || n == null) ? "" : Number(n).toLocaleString("en-US");
  const inputStyle = (overridden) => ({ height: 34, width: isMobile ? 120 : 140, fontSize: 13, padding: "0 8px", borderColor: overridden ? "var(--brand)" : "var(--border-strong)" });

  // editable per-line unit price (manual override) — thousands-separated for IQD
  const PriceInput = (l) => (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 5 }}>
      {isUsd ? (
        <input className="bny-input bny-input--numeric" type="number" min="0" step="0.5"
          value={effUnit(l)} onChange={(e) => setOverride(l.rid, e.target.value)}
          aria-label="سعر الوحدة" style={inputStyle(l.priceOverride != null)} />
      ) : (
        <input className="bny-input bny-input--numeric" type="text" inputMode="numeric"
          value={fmtNum(effUnit(l))} onChange={(e) => setOverride(l.rid, e.target.value.replace(/[^\d]/g, ""))}
          aria-label="سعر الوحدة" style={inputStyle(l.priceOverride != null)} />
      )}
      <span style={{ fontSize: 11, color: "var(--text-muted)" }}>{curSym} / {unitLabel(l)}</span>
    </span>
  );

  return (
    <div style={{ padding: isMobile ? "var(--space-5)" : "var(--space-8)", display: "grid", gridTemplateColumns: isMobile ? "1fr" : "1fr 360px", gap: "var(--space-7)", alignItems: "start" }}>
      {/* left: item search + lines */}
      <div style={{ display: "flex", flexDirection: "column", gap: "var(--space-6)" }}>
        <div style={{ position: "relative" }}>
          <SearchBar value={q} onChange={setQ} listening={listening} onVoice={() => setListening((v) => !v)}
            placeholder={searchPlaceholder} />
          {!q && suggestPool.length > 0 && (
            <div style={{ display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap", marginTop: 10 }}>
              <span style={{ fontSize: 12, color: "var(--text-muted)", fontWeight: 600 }}>{topSell.length ? "الأكثر طلبًا:" : "المتوفّرة:"}</span>
              {suggestPool.map((m) => (
                <button key={m.sku} type="button" onClick={() => add(m)}
                  style={{ display: "inline-flex", alignItems: "center", gap: 6, padding: "5px 11px", border: "1px solid var(--border-strong)", background: "var(--surface-sunken)", borderRadius: "999px", cursor: "pointer", fontSize: 12.5, color: "var(--text-body)", fontFamily: "var(--font-body)" }}>
                  <I.plus size={13} /> {m.name}
                </button>
              ))}
            </div>
          )}
          {results.length > 0 && (
            <div style={{ position: "absolute", insetInlineStart: 0, insetInlineEnd: 0, top: "calc(100% + 6px)", zIndex: 5, background: "#fff", border: "1px solid var(--border-subtle)", borderRadius: "var(--radius-lg)", boxShadow: "var(--shadow-lg)", overflow: "hidden" }}>
              {results.map((m) => (
                <div key={m.sku} onClick={() => add(m)} style={{ display: "flex", alignItems: "center", gap: 12, padding: "11px 14px", cursor: "pointer", borderBottom: "1px solid var(--border-subtle)" }}
                  onMouseEnter={(e) => (e.currentTarget.style.background = "var(--surface-hover)")} onMouseLeave={(e) => (e.currentTarget.style.background = "transparent")}>
                  <span style={{ display: "inline-flex", color: "var(--brand)" }}><I.inventory size={18} /></span>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 14, fontWeight: 600, color: "var(--text-strong)" }}>{m.name}</div>
                    <div style={{ fontSize: 12, color: "var(--text-muted)", fontFamily: "var(--font-mono)" }}>
                      {m.sku} · متوفر: {m.hasMultiUnits ? `${window.BnyStock(m)} (${m.stock.toLocaleString("en-US")} ${m.unit})` : `${m.stock} ${m.unit}`}
                    </div>
                  </div>
                  <Money value={basePrice(m)} unit={curSym} />
                </div>
              ))}
            </div>
          )}
        </div>

        <Card title={`أصناف الفاتورة (${lines.length})`}>
          {isMobile ? (
            <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
              {lines.map((l) => (
                <div key={l.rid} style={{ borderTop: "1px solid var(--border-subtle)", paddingTop: 10 }}>
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 8 }}>
                    <div style={{ minWidth: 0 }}>
                      <div style={{ fontSize: 14, fontWeight: 600, color: "var(--text-strong)" }}>{l.name}</div>
                      {l.unitMode === "pack" && l.hasMultiUnits
                        ? <div style={{ fontSize: 11, color: "var(--text-muted)", fontFamily: "var(--font-mono)" }}>= {baseQty(l)} {l.unit}</div>
                        : <div style={{ fontSize: 11, color: "var(--text-muted)" }}>{l.cat}</div>}
                    </div>
                    <button className="bny-iconbtn bny-iconbtn--sm" aria-label="حذف" onClick={() => remove(l.rid)} style={{ color: "var(--text-muted)", flex: "none" }}><I.trash size={16} /></button>
                  </div>
                  <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 10, marginTop: 8, flexWrap: "wrap" }}>
                    {l.hasMultiUnits ? (
                      <div className="bny-unit-toggle" role="group" aria-label="وحدة البيع">
                        <button type="button" aria-pressed={l.unitMode === "pack"} onClick={() => setMode(l.rid, "pack")}>{l.packUnit}</button>
                        <button type="button" aria-pressed={l.unitMode === "base"} onClick={() => setMode(l.rid, "base")}>{l.unit}</button>
                      </div>
                    ) : (
                      <span className="bny-unit-locked" title="وحدة ثابتة"><I.alert size={12} /> {l.unit}</span>
                    )}
                    <QtyInput l={l} onStep={stepQty} onType={typeQty} onBlur={blurQty} />
                  </div>
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 8, gap: 8, flexWrap: "wrap" }}>
                    {PriceInput(l)}
                    <span style={{ fontWeight: 700 }}><Money value={lineTotal(l)} unit={curSym} /></span>
                  </div>
                </div>
              ))}
            </div>
          ) : (
          <div style={{ overflowX: "auto" }}>
          <table style={{ width: "100%", borderCollapse: "collapse", minWidth: 620 }}>
            <thead>
              <tr style={{ color: "var(--text-muted)", fontSize: 12 }}>
                <th style={{ textAlign: "start", fontWeight: 600, padding: "0 0 10px" }}>المادة</th>
                <th style={{ textAlign: "center", fontWeight: 600, padding: "0 0 10px" }}>وحدة البيع</th>
                <th style={{ textAlign: "center", fontWeight: 600, padding: "0 0 10px" }}>الكمية</th>
                <th style={{ textAlign: "start", fontWeight: 600, padding: "0 0 10px" }}>سعر الوحدة</th>
                <th style={{ textAlign: "end", fontWeight: 600, padding: "0 0 10px" }}>المجموع</th>
                <th style={{ width: 36 }}></th>
              </tr>
            </thead>
            <tbody>
              {lines.map((l) => (
                <tr key={l.rid} style={{ borderTop: "1px solid var(--border-subtle)" }}>
                  <td style={{ padding: "12px 0" }}>
                    <div style={{ fontSize: 14, fontWeight: 600, color: "var(--text-strong)" }}>{l.name}</div>
                    {l.unitMode === "pack" && l.hasMultiUnits
                      ? <div style={{ fontSize: 11, color: "var(--text-muted)", fontFamily: "var(--font-mono)" }}>= {baseQty(l)} {l.unit} (خصم من المخزن)</div>
                      : <div style={{ fontSize: 11, color: "var(--text-muted)" }}>{l.cat}</div>}
                  </td>
                  <td style={{ padding: "12px 0", textAlign: "center" }}>
                    {l.hasMultiUnits ? (
                      <div className="bny-unit-toggle" role="group" aria-label="وحدة البيع">
                        <button type="button" aria-pressed={l.unitMode === "pack"} onClick={() => setMode(l.rid, "pack")}>{l.packUnit}</button>
                        <button type="button" aria-pressed={l.unitMode === "base"} onClick={() => setMode(l.rid, "base")}>{l.unit}</button>
                      </div>
                    ) : (
                      <span className="bny-unit-locked" title="وحدة ثابتة — لا يمكن تقسيمها">
                        <I.alert size={12} /> {l.unit}
                      </span>
                    )}
                  </td>
                  <td style={{ padding: "12px 0", textAlign: "center" }}>
                    <QtyInput l={l} onStep={stepQty} onType={typeQty} onBlur={blurQty} />
                  </td>
                  <td style={{ padding: "12px 0" }}>{PriceInput(l)}</td>
                  <td style={{ padding: "12px 0", textAlign: "end", fontWeight: 600 }}><Money value={lineTotal(l)} unit={curSym} /></td>
                  <td style={{ textAlign: "center" }}>
                    <button className="bny-iconbtn bny-iconbtn--sm" aria-label="حذف" onClick={() => remove(l.rid)} style={{ color: "var(--text-muted)" }}><I.trash size={16} /></button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
          </div>
          )}
        </Card>
      </div>

      {/* right: customer + totals */}
      <div style={{ display: "flex", flexDirection: "column", gap: "var(--space-6)", position: isMobile ? "static" : "sticky", top: "var(--space-8)" }}>
        <Card title="العميل">
          <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 14 }}>
            <Avatar name={custDisplayName} />
            <div style={{ flex: 1 }}>
              <div style={{ fontWeight: 600, color: "var(--text-strong)" }}>{custDisplayName}</div>
              <div style={{ fontSize: 12, color: "var(--text-muted)", fontFamily: cust.walkin ? "var(--font-body)" : "var(--font-mono)" }}>{cust.walkin ? "بيع سريع — زبون عابر" : cust.phone}</div>
            </div>
            <Badge tone={cust.walkin ? "warning" : (cust.type === "آجل" ? "brand" : "neutral")}>{cust.walkin ? "مستطرق" : cust.type}</Badge>
          </div>
          {/* اختيار العميل: بحث ذكي بالاسم/الهاتف/المؤسسة + زر عميل جديد */}
          <div style={{ position: "relative" }}>
            <div style={{ display: "flex", gap: 6 }}>
              <input className="bny-input" value={custOpen ? custQuery : cust.name}
                onFocus={() => { setCustOpen(true); setCustQuery(""); }}
                onChange={(e) => { setCustQuery(e.target.value); setCustOpen(true); }}
                placeholder="ابحث باسم العميل أو المؤسسة…" style={{ flex: 1 }} aria-label="اختيار العميل" />
              <button type="button" onClick={() => setShowNewCust(true)} title="عميل جديد" aria-label="عميل جديد"
                style={{ flex: "none", width: 42, border: "1px solid var(--border-strong)", background: "var(--brand-soft)", color: "var(--brand-strong)", borderRadius: "var(--radius-md)", cursor: "pointer", fontSize: 20, fontWeight: 700, lineHeight: 1 }}>+</button>
            </div>
            {custOpen && <div onClick={() => setCustOpen(false)} style={{ position: "fixed", inset: 0, zIndex: 9 }} />}
            {custOpen && (() => {
              const ql = custQuery.trim();
              const matches = custList.filter((c) => !ql || c.name.includes(ql) || (c.phone || "").includes(ql) || orgName(c.org).includes(ql));
              return (
                <div style={{ position: "absolute", insetInlineStart: 0, insetInlineEnd: 0, top: "calc(100% + 4px)", zIndex: 10, background: "#fff", border: "1px solid var(--border-subtle)", borderRadius: "var(--radius-md)", boxShadow: "var(--shadow-lg)", maxHeight: 260, overflowY: "auto" }}>
                  {matches.map((c) => (
                    <div key={c.id} onClick={() => { setCust(c); setCustOpen(false); setMgrAsked(false); }}
                      onMouseEnter={(e) => (e.currentTarget.style.background = "var(--surface-hover)")} onMouseLeave={(e) => (e.currentTarget.style.background = "transparent")}
                      style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8, padding: "9px 12px", cursor: "pointer", borderBottom: "1px solid var(--border-subtle)" }}>
                      <div style={{ minWidth: 0 }}>
                        <div style={{ fontSize: 13.5, fontWeight: 600, color: "var(--text-strong)" }}>{c.name}</div>
                        <div style={{ fontSize: 11.5, color: "var(--text-muted)" }}>{orgName(c.org) || c.type}{c.phone ? " · " + c.phone : ""}</div>
                      </div>
                      {cust.id === c.id && <span style={{ color: "var(--brand)", flex: "none" }}><I.check size={16} /></span>}
                    </div>
                  ))}
                  {matches.length === 0 && <div style={{ padding: "12px", textAlign: "center", color: "var(--text-muted)", fontSize: 13 }}>لا نتائج — <button type="button" onClick={() => setShowNewCust(true)} style={{ border: 0, background: "none", color: "var(--brand-strong)", cursor: "pointer", fontWeight: 600 }}>أضف عميلًا جديدًا</button></div>}
                </div>
              );
            })()}
          </div>
          {cust.walkin && (
            <div style={{ marginTop: 12 }}>
              <label style={{ fontSize: 12.5, fontWeight: 600, color: "var(--text-strong)", display: "block", marginBottom: 5 }}>اسم الزبون (عابر) — اختياري</label>
              <input className="bny-input" value={walkName} onChange={(e) => setWalkName(e.target.value)}
                placeholder="يُطبع على الفاتورة فقط، لا يُسجَّل عميلًا" aria-label="اسم الزبون العابر" />
            </div>
          )}
          <div style={{ display: "flex", justifyContent: "space-between", marginTop: 14, fontSize: 13 }}>
            <span style={{ color: "var(--text-muted)" }}>الرصيد الحالي ({curSym})</span>
            <Money value={custBalance} unit={curSym} tone={custBalance > 0 ? "debt" : "default"} />
          </div>
          <div style={{ display: "flex", justifyContent: "space-between", marginTop: 8, fontSize: 13 }}>
            <span style={{ color: "var(--text-muted)" }}>السقف الائتماني</span>
            {hasLimit ? <Money value={custLimit} unit={curSym} /> : <span style={{ color: "var(--text-muted)" }}>بدون سقف</span>}
          </div>
        </Card>

        <Card title="الإجمالي">
          {/* invoice settings: date + currency + price list */}
          <div style={{ display: "flex", flexDirection: "column", gap: 10, marginBottom: 14 }}>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8 }}>
              <span style={{ fontSize: 13, color: "var(--text-muted)" }}>تاريخ الفاتورة</span>
              <input className="bny-input" type="date" value={invDate} onChange={(e) => setInvDate(e.target.value || window.BnyOps.todayIso())}
                aria-label="تاريخ الفاتورة" style={{ height: 36, width: 175, padding: "0 10px", fontFamily: "var(--font-mono)", fontSize: 13 }} />
            </div>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8 }}>
              <span style={{ fontSize: 13, color: "var(--text-muted)" }}>عملة الفاتورة</span>
              <div className="bny-unit-toggle" role="group" aria-label="عملة الفاتورة">
                <button type="button" aria-pressed={!isUsd} onClick={() => setCurrency("iqd")}>د.ع</button>
                <button type="button" aria-pressed={isUsd} onClick={() => setCurrency("usd")}>دولار</button>
              </div>
            </div>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8 }}>
              <span style={{ fontSize: 13, color: "var(--text-muted)" }}>نوع التسعير</span>
              <div style={{ width: 175 }}>
                <Select value={priceType} onChange={(e) => setType(e.target.value)}>
                  {D.priceTypes.map((p) => <option key={p.id} value={p.id}>{p.name}</option>)}
                </Select>
              </div>
            </div>
          </div>

          <Row k="المجموع الفرعي" v={<Money value={subtotal} unit={curSym} />} />
          {/* direct discount: amount (currency) or percent */}
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "5px 0", fontSize: 14, gap: 8 }}>
            <span style={{ color: "var(--text-muted)" }}>الخصم</span>
            <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
              <div className="bny-unit-toggle" role="group" aria-label="نوع الخصم">
                <button type="button" aria-pressed={discountType === "amount"} onClick={() => setDiscountType("amount")}>{curSym}</button>
                <button type="button" aria-pressed={discountType === "percent"} onClick={() => setDiscountType("percent")}>%</button>
              </div>
              {discountType === "amount" && !isUsd ? (
                <input className="bny-input bny-input--numeric" type="text" inputMode="numeric"
                  value={fmtNum(discountValue)} onChange={(e) => setDiscountValue(e.target.value.replace(/[^\d]/g, ""))}
                  aria-label="قيمة الخصم" style={{ height: 34, width: 110, fontSize: 13, padding: "0 8px" }} />
              ) : (
                <input className="bny-input bny-input--numeric" type="number" min="0" value={discountValue}
                  onChange={(e) => setDiscountValue(e.target.value)} aria-label="قيمة الخصم"
                  style={{ height: 34, width: 92, fontSize: 13, padding: "0 8px" }} />
              )}
            </div>
          </div>
          {discountAmount > 0 && (
            <div style={{ display: "flex", justifyContent: "space-between", padding: "2px 0 4px", fontSize: 12.5, color: "var(--text-muted)" }}>
              <span>قيمة الخصم المطبّق</span><Money value={discountAmount} unit={curSym} tone="credit" />
            </div>
          )}
          <div style={{ borderTop: "1px dashed var(--border-strong)", margin: "12px 0" }} />
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
            <span style={{ fontWeight: 700, color: "var(--text-strong)", fontSize: 16 }}>الإجمالي</span>
            <Money value={total} unit={curSym} style={{ fontSize: 24, fontWeight: 700 }} />
          </div>
          {/* المبلغ المسدد → المتبقي (لحظي) */}
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8, marginTop: 12 }}>
            <span style={{ fontSize: 13, color: "var(--text-muted)" }}>المبلغ المسدد</span>
            <input className="bny-input bny-input--numeric" inputMode="decimal"
              value={isUsd ? paid : fmtNum(paid)}
              onChange={(e) => setPaid(isUsd ? e.target.value.replace(/[^\d.]/g, "") : e.target.value.replace(/[^\d]/g, ""))}
              placeholder="0" aria-label="المبلغ المسدد" style={{ height: 36, width: 140, fontSize: 13, padding: "0 8px", textAlign: "start" }} />
          </div>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginTop: 8 }}>
            <span style={{ fontSize: 13, fontWeight: 600, color: "var(--text-strong)" }}>المتبقي</span>
            <Money value={remaining} unit={curSym} tone={remaining > 0 ? "debt" : "default"} style={{ fontSize: 16, fontWeight: 700 }} />
          </div>
          {over && (
            <div style={{ display: "flex", gap: 9, alignItems: "flex-start", marginTop: 14, padding: "12px 14px", background: "var(--danger)", borderRadius: "var(--radius-md)", color: "#fff", fontSize: 12.5, lineHeight: 1.55, boxShadow: "var(--shadow-sm)" }}>
              <span style={{ flex: "none", marginTop: 1 }}><I.alert size={18} /></span>
              <span><b>تجاوز السقف الائتماني.</b> لا يمكن إتمام البيع الآجل. الرصيد بعد الفاتورة: <b>{newBalance.toLocaleString("en-US")} {curSym}</b> (السقف: {custLimit.toLocaleString("en-US")} {curSym}).</span>
            </div>
          )}
          <div style={{ display: "flex", flexDirection: "column", gap: 10, marginTop: 16 }}>
            {saved ? (
              <div style={{ display: "flex", flexDirection: "column", gap: 10, padding: 14, background: "var(--success-soft, #e6f7ef)", borderRadius: "var(--radius-md)" }}>
                <div style={{ display: "flex", alignItems: "center", gap: 8, color: "var(--success, #1d9e63)", fontWeight: 700, fontSize: 14.5 }}>
                  <I.check size={19} /> تم حفظ الفاتورة #{saved.no} بنجاح
                </div>
                <div style={{ fontSize: 12, color: "var(--text-muted)" }}>خُصم المخزون وحُدّث حساب العميل تلقائيًا.</div>
                <Button variant="accent" size="lg" block icon={<I.plus size={17} />} onClick={resetSale}>فاتورة جديدة</Button>
              </div>
            ) : (
              <Button variant="accent" size="lg" block icon={<I.check size={18} />} disabled={!canSave} onClick={confirmSale}>
                {saving ? "جارٍ الحفظ…" : "حفظ وتأكيد البيع"}
              </Button>
            )}
            {over && !saved && (
              mgrAsked
                ? <div style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 8, padding: "11px 12px", background: "var(--warning-soft)", color: "var(--warning-text)", borderRadius: "var(--radius-md)", fontSize: 13, fontWeight: 600 }}>
                    <I.cloud size={16} /> أُرسل طلب الإذن للمدير… بانتظار الموافقة
                  </div>
                : <Button variant="secondary" size="lg" block icon={<I.alert size={18} />} onClick={() => setMgrAsked(true)}>طلب إذن المدير</Button>
            )}
            <div style={{ display: "flex", gap: 10 }}>
              <Button variant="secondary" block icon={<I.printer size={16} />} onClick={() => printCopy("sales")}>طباعة بيع</Button>
              <Button variant="secondary" block icon={<I.printer size={16} />} onClick={() => printCopy("picking")}>نسخة تجهيز</Button>
            </div>
            <Button variant="secondary" block icon={<I.whatsapp size={16} />} onClick={waInvoice} disabled={lines.length === 0}>إرسال واتساب</Button>
          </div>
        </Card>
      </div>

      {showNewCust && <NewCustomerModal orgs={orgList} onCreateOrg={createOrg} onSave={createCustomer} onClose={() => setShowNewCust(false)} />}

      {/* A4 print view (hidden on screen, shown via @media print). Two copies:
          sales  → prices + totals, no warehouse, no price-list name.
          picking→ warehouse per item, no prices/totals. */}
      <div id="bny-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>
                {printMode !== "picking" && shop.address ? <div style={{ fontSize: 12, color: "var(--text-muted)" }}>{shop.address}</div> : null}
                {shop.phone ? <div style={{ fontSize: 12, color: "var(--text-muted)", fontFamily: "var(--font-mono)" }}>هاتف: {shop.phone}</div> : null}
              </div>
            </div>
            {printMode === "sales" ? (
              <div style={{ textAlign: "end", fontFamily: "var(--font-mono)", fontSize: 13 }}>
                <div><b>فاتورة بيع #{invoiceNo}</b></div>
                <div style={{ color: "var(--text-muted)" }}>التاريخ: {today}</div>
                <div style={{ color: "var(--text-muted)" }}>العملة: {isUsd ? "دولار ($)" : "دينار (د.ع)"}</div>
              </div>
            ) : (
              <div style={{ textAlign: "end", fontSize: 16, fontWeight: 700, color: "var(--blue-900)" }}>نسخة تجهيز</div>
            )}
          </div>
          {printMode === "sales" && (
            <div style={{ display: "flex", justifyContent: "space-between", fontSize: 13, marginBottom: 16 }}>
              <div><span style={{ color: "var(--text-muted)" }}>العميل: </span><b>{custDisplayName}</b></div>
              {cust.phone ? <div style={{ fontFamily: "var(--font-mono)" }}><span style={{ color: "var(--text-muted)" }}>الهاتف: </span>{cust.phone}</div> : null}
            </div>
          )}

          {printMode === "picking" ? (
            <>
              <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13 }}>
                <thead>
                  <tr style={{ background: "var(--concrete-100)" }}>
                    <th style={printTh}>المادة</th>
                    <th style={{ ...printTh, textAlign: "center" }}>الوحدة</th>
                    <th style={{ ...printTh, textAlign: "center" }}>الكمية (العدد)</th>
                  </tr>
                </thead>
                <tbody>
                  {lines.map((l) => (
                    <tr key={l.rid} style={{ borderBottom: "1px solid var(--border-subtle)" }}>
                      <td style={printTd}>{l.name}</td>
                      <td style={{ ...printTd, textAlign: "center" }}>{unitLabel(l)}</td>
                      <td style={{ ...printTd, textAlign: "center", fontFamily: "var(--font-mono)", fontWeight: 700 }}>
                        {l.qty}{l.unitMode === "pack" && l.hasMultiUnits ? ` (= ${baseQty(l)} ${l.unit})` : ""}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
              <div style={{ marginTop: 24, fontSize: 12, color: "var(--text-muted)", textAlign: "center" }}>نسخة تجهيز البضاعة — بدون أسعار · تُسلّم لعمّال المستودع</div>
            </>
          ) : (
            <>
              <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13 }}>
                <thead>
                  <tr style={{ background: "var(--concrete-100)" }}>
                    <th style={printTh}>المادة</th>
                    <th style={{ ...printTh, textAlign: "center" }}>الوحدة</th>
                    <th style={{ ...printTh, textAlign: "center" }}>الكمية</th>
                    <th style={printTh}>سعر الوحدة</th>
                    <th style={{ ...printTh, textAlign: "end" }}>المجموع</th>
                  </tr>
                </thead>
                <tbody>
                  {lines.map((l) => (
                    <tr key={l.rid} style={{ borderBottom: "1px solid var(--border-subtle)" }}>
                      <td style={printTd}>{l.name}</td>
                      <td style={{ ...printTd, textAlign: "center" }}>{unitLabel(l)}</td>
                      <td style={{ ...printTd, textAlign: "center", fontFamily: "var(--font-mono)" }}>{l.qty}</td>
                      <td style={{ ...printTd, fontFamily: "var(--font-mono)" }}>{effUnit(l).toLocaleString("en-US")} {curSym}</td>
                      <td style={{ ...printTd, textAlign: "end", fontFamily: "var(--font-mono)" }}>{lineTotal(l).toLocaleString("en-US")} {curSym}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
              <div style={{ display: "flex", justifyContent: "flex-start", marginTop: 18 }}>
                <div style={{ width: 260, fontSize: 14 }}>
                  <div style={{ display: "flex", justifyContent: "space-between", padding: "4px 0" }}><span style={{ color: "var(--text-muted)" }}>المجموع الفرعي</span><span style={{ fontFamily: "var(--font-mono)" }}>{subtotal.toLocaleString("en-US")} {curSym}</span></div>
                  {discountAmount > 0 && <div style={{ display: "flex", justifyContent: "space-between", padding: "4px 0" }}><span style={{ color: "var(--text-muted)" }}>الخصم</span><span style={{ fontFamily: "var(--font-mono)" }}>− {discountAmount.toLocaleString("en-US")} {curSym}</span></div>}
                  <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)" }}>{total.toLocaleString("en-US")} {curSym}</span></div>
                  {paidNum > 0 && <div style={{ display: "flex", justifyContent: "space-between", padding: "4px 0" }}><span style={{ color: "var(--text-muted)" }}>المسدّد</span><span style={{ fontFamily: "var(--font-mono)" }}>{paidNum.toLocaleString("en-US")} {curSym}</span></div>}
                  {remaining > 0 && <div style={{ display: "flex", justifyContent: "space-between", padding: "4px 0", fontWeight: 700 }}><span>المتبقي</span><span style={{ fontFamily: "var(--font-mono)" }}>{remaining.toLocaleString("en-US")} {curSym}</span></div>}
                </div>
              </div>
              <div style={{ marginTop: 28, fontSize: 11, color: "var(--text-muted)", textAlign: "center" }}>{shop.footer}</div>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

const qtyBtn = { width: 30, height: 30, border: "none", background: "var(--surface-sunken)", cursor: "pointer", fontSize: 16, color: "var(--text-body)", fontWeight: 600 };
const printTh = { textAlign: "start", fontWeight: 600, padding: "8px 10px", borderBottom: "1px solid var(--border-strong)" };
const printTd = { padding: "8px 10px" };
function Row({ k, v }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", padding: "5px 0", fontSize: 14 }}>
      <span style={{ color: "var(--text-muted)" }}>{k}</span>{v}
    </div>
  );
}
/* معرّف فريد لكل سطر فاتورة (يمنع تضارب تكرار نفس المادة بوحدات مختلفة) */
let bnyRowSeq = 0;
function bnyRid() { bnyRowSeq += 1; return "r" + bnyRowSeq + "-" + Date.now().toString(36); }

/* حقل الكمية: إدخال مباشر + زرّا زيادة/إنقاص */
function QtyInput({ l, onStep, onType, onBlur }) {
  return (
    <div style={{ display: "inline-flex", alignItems: "center", border: "1px solid var(--border-strong)", borderRadius: "var(--radius-md)", overflow: "hidden" }}>
      <button type="button" onClick={() => onStep(l, -1)} style={qtyBtn} aria-label="إنقاص">−</button>
      <input value={l.qty} onChange={(e) => onType(l, e.target.value)} onBlur={() => onBlur(l)} inputMode="decimal" aria-label="الكمية"
        style={{ width: 54, textAlign: "center", fontFamily: "var(--font-mono)", fontWeight: 600, border: "none", outline: "none", background: "transparent", fontSize: 14, padding: "6px 0", color: "var(--text-strong)" }} />
      <button type="button" onClick={() => onStep(l, 1)} style={qtyBtn} aria-label="زيادة">+</button>
    </div>
  );
}

const bnyModalOverlay = { position: "fixed", inset: 0, zIndex: 1000, background: "rgba(0,0,0,.45)", display: "flex", alignItems: "center", justifyContent: "center", padding: "var(--space-5)" };
const bnyModalHead = { display: "flex", alignItems: "center", gap: 10, padding: "16px 20px", borderBottom: "1px solid var(--border-subtle)" };
const bnyModalFoot = { padding: "12px 20px", borderTop: "1px solid var(--border-subtle)", display: "flex", justifyContent: "flex-end", gap: 8 };
const bnyXBtn = { border: 0, background: "none", cursor: "pointer", color: "var(--text-muted)", display: "inline-flex" };
const bnyLbl = { fontSize: 12.5, fontWeight: 600, color: "var(--text-strong)", display: "block", marginBottom: 5 };

/* نافذة عميل جديد سريع: اسم/هاتف/عنوان + تفعيل مؤسسة (مع إضافة مؤسسة) */
function NewCustomerModal({ orgs, onCreateOrg, onSave, onClose }) {
  const I = window.BnyIcon;
  const { Button, Input, Switch, Select } = window.BonyanDesignSystem_ad3ca0;
  const [name, setName] = React.useState("");
  const [phone, setPhone] = React.useState("");
  const [phone2, setPhone2] = React.useState("");
  const [showPhone2, setShowPhone2] = React.useState(false);
  const [address, setAddress] = React.useState("");
  const [hasOrg, setHasOrg] = React.useState(false);
  const [org, setOrg] = React.useState("");
  const [orgList, setOrgList] = React.useState(orgs || []);
  const [showOrg, setShowOrg] = React.useState(false);
  const canSave = name.trim() !== "";
  const save = () => { if (canSave) onSave({ name, phone, phone2, address, org: hasOrg ? (org || null) : null }); };
  const onNewOrg = (data) => { const o = onCreateOrg(data); setOrgList((l) => [...l, o]); setOrg(o.id); setHasOrg(true); setShowOrg(false); };
  return (
    <div onClick={onClose} style={bnyModalOverlay}>
      <div onClick={(e) => e.stopPropagation()} className="bny-card" style={{ width: "100%", maxWidth: 440, padding: 0, display: "flex", flexDirection: "column", maxHeight: "90vh" }}>
        <div style={bnyModalHead}><h3 style={{ margin: 0, fontSize: 17, flex: 1 }}>عميل جديد</h3><button onClick={onClose} style={bnyXBtn} aria-label="إغلاق"><I.x size={20} /></button></div>
        <div style={{ overflowY: "auto", padding: "14px 20px", display: "flex", flexDirection: "column", gap: 12 }}>
          <div><label style={bnyLbl}>الاسم الكامل *</label><Input value={name} onChange={(e) => setName(e.target.value)} placeholder="الاسم الكامل للعميل" autoFocus /></div>
          <div>
            <label style={bnyLbl}>رقم الهاتف (اختياري)</label>
            <Input value={phone} onChange={(e) => setPhone(e.target.value)} placeholder="07XXXXXXXXX" icon={<I.phone size={16} />} />
            {!showPhone2 ? (
              <button type="button" onClick={() => setShowPhone2(true)}
                style={{ marginTop: 7, border: 0, background: "none", color: "var(--brand-strong)", cursor: "pointer", fontSize: 12.5, fontWeight: 600, fontFamily: "var(--font-body)", display: "inline-flex", alignItems: "center", gap: 4, padding: 0 }}>
                <I.plus size={14} /> إضافة رقم هاتف آخر
              </button>
            ) : (
              <div style={{ marginTop: 8, display: "flex", gap: 6, alignItems: "center" }}>
                <div style={{ flex: 1 }}><Input value={phone2} onChange={(e) => setPhone2(e.target.value)} placeholder="رقم هاتف ثانٍ (اختياري)" icon={<I.phone size={16} />} /></div>
                <button type="button" onClick={() => { setShowPhone2(false); setPhone2(""); }} aria-label="حذف الرقم الثاني" title="حذف الرقم الثاني"
                  style={{ flex: "none", width: 40, height: 40, border: "1px solid var(--border-strong)", background: "none", color: "var(--danger)", borderRadius: "var(--radius-md)", cursor: "pointer", display: "inline-flex", alignItems: "center", justifyContent: "center" }}><I.trash size={16} /></button>
              </div>
            )}
          </div>
          <div><label style={bnyLbl}>العنوان (اختياري)</label><Input value={address} onChange={(e) => setAddress(e.target.value)} placeholder="المدينة — المنطقة / الشارع" /></div>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8, padding: "4px 0" }}>
            <span style={{ fontSize: 13.5, fontWeight: 600, color: "var(--text-strong)" }}>تابع لمؤسسة</span>
            <Switch checked={hasOrg} onChange={() => setHasOrg((v) => !v)} />
          </div>
          {hasOrg && (
            <div style={{ display: "flex", gap: 6, alignItems: "flex-end" }}>
              <div style={{ flex: 1 }}>
                <label style={bnyLbl}>المؤسسة</label>
                <Select value={org} onChange={(e) => setOrg(e.target.value)}>
                  <option value="">— اختر مؤسسة —</option>
                  {orgList.map((o) => <option key={o.id} value={o.id}>{o.name}</option>)}
                </Select>
              </div>
              <button type="button" onClick={() => setShowOrg(true)} title="مؤسسة جديدة" aria-label="مؤسسة جديدة"
                style={{ flex: "none", width: 42, height: 40, border: "1px solid var(--border-strong)", background: "var(--brand-soft)", color: "var(--brand-strong)", borderRadius: "var(--radius-md)", cursor: "pointer", fontSize: 20, fontWeight: 700 }}>+</button>
            </div>
          )}
        </div>
        <div style={bnyModalFoot}>
          <Button variant="secondary" onClick={onClose}>إلغاء</Button>
          <Button variant="accent" icon={<I.check size={16} />} onClick={save} disabled={!canSave}>حفظ العميل</Button>
        </div>
        {showOrg && <NewOrgModal onSave={onNewOrg} onClose={() => setShowOrg(false)} />}
      </div>
    </div>
  );
}

/* نافذة فرعية: مؤسسة جديدة (اسم + ملاحظات) */
function NewOrgModal({ onSave, onClose }) {
  const I = window.BnyIcon;
  const { Button, Input } = window.BonyanDesignSystem_ad3ca0;
  const [name, setName] = React.useState("");
  const [notes, setNotes] = React.useState("");
  const canSave = name.trim() !== "";
  return (
    <div onClick={onClose} style={{ ...bnyModalOverlay, zIndex: 1100 }}>
      <div onClick={(e) => e.stopPropagation()} className="bny-card" style={{ width: "100%", maxWidth: 400, padding: 0, display: "flex", flexDirection: "column" }}>
        <div style={bnyModalHead}><h3 style={{ margin: 0, fontSize: 16, flex: 1 }}>مؤسسة جديدة</h3><button onClick={onClose} style={bnyXBtn} aria-label="إغلاق"><I.x size={20} /></button></div>
        <div style={{ padding: "14px 20px", display: "flex", flexDirection: "column", gap: 12 }}>
          <div><label style={bnyLbl}>اسم المؤسسة *</label><Input value={name} onChange={(e) => setName(e.target.value)} placeholder="مثال: شركة الإعمار للمقاولات" autoFocus /></div>
          <div><label style={bnyLbl}>ملاحظات</label>
            <textarea value={notes} onChange={(e) => setNotes(e.target.value)} className="bny-input" rows={3}
              placeholder="ملاحظات اختيارية" style={{ resize: "vertical", minHeight: 70, padding: "8px 10px", fontFamily: "var(--font-body)", width: "100%", boxSizing: "border-box" }} />
          </div>
        </div>
        <div style={bnyModalFoot}>
          <Button variant="secondary" onClick={onClose}>إلغاء</Button>
          <Button variant="accent" icon={<I.check size={16} />} onClick={() => { if (canSave) onSave({ name, notes }); }} disabled={!canSave}>حفظ المؤسسة</Button>
        </div>
      </div>
    </div>
  );
}
window.PosScreen = PosScreen;
window.BnyNewCustomerModal = NewCustomerModal; // تُستخدم أيضًا من شاشة العملاء
window.BnyNewOrgModal = NewOrgModal;
