/* Bonyan ERP — مكوّن رسم خطي مشترك (Line Chart) مع Tooltip وعلامات قيم.
   يُستخدم في لوحة التحكم والتقارير.
   props:
     labels  : ["نيسان","أيار",...]            أسماء المحور الأفقي
     series  : [{ name, color, values:[...] }]  خط واحد أو أكثر (مقارنة)
     height  : ارتفاع المخطط (px)
     fmt     : دالة تنسيق القيمة (افتراضي: فواصل إنجليزية)
     unit    : وحدة تُلحق بالقيمة في الـ tooltip (مثل "مليون د.ع")
*/
function BnyLineChart({ labels, series, height, isMobile, fmt, unit }) {
  const [active, setActive] = React.useState(null);
  labels = labels || [];
  series = series || [];
  fmt = fmt || ((v) => Number(v).toLocaleString("en-US"));
  const single = series.length === 1;
  const H = height || (isMobile ? 180 : 240);
  const padT = 26, padB = 30, chartH = H - padT - padB;
  const n = labels.length;

  if (!n || !series.length) {
    return <div style={{ height: H, display: "flex", alignItems: "center", justifyContent: "center", color: "var(--text-muted)", fontSize: 13 }}>لا توجد بيانات كافية لعرض الاتجاه</div>;
  }

  const allVals = series.reduce((a, s) => a.concat(s.values), []);
  const maxV = Math.max(...allVals, 1);
  const minV = Math.min(...allVals, 0);
  const span = (maxV - minV) || 1;
  const xOf = (i) => (n > 1 ? (i / (n - 1)) * 100 : 50);          // %
  const yOf = (v) => padT + (1 - (v - minV) / span) * chartH;     // px

  return (
    <div style={{ position: "relative", height: H, padding: "0 8px", userSelect: "none" }}
      onMouseLeave={() => setActive(null)}>
      <svg width="100%" height={H} viewBox={"0 0 100 " + H} preserveAspectRatio="none" style={{ display: "block", overflow: "visible" }}>
        {/* شبكة أفقية خفيفة */}
        {[0, 0.5, 1].map((t) => (
          <line key={t} x1="0" y1={padT + t * chartH} x2="100" y2={padT + t * chartH} stroke="var(--border-subtle)" strokeWidth="1" vectorEffect="non-scaling-stroke" opacity={t === 1 ? 1 : 0.5} />
        ))}
        {/* تعبئة أسفل الخط الأول */}
        {single && (
          <polyline points={"0," + (padT + chartH) + " " + series[0].values.map((v, i) => xOf(i) + "," + yOf(v)).join(" ") + " 100," + (padT + chartH)}
            fill={series[0].color || "var(--brand)"} opacity="0.08" stroke="none" />
        )}
        {/* الخطوط */}
        {series.map((s, si) => (
          <polyline key={si} points={s.values.map((v, i) => xOf(i) + "," + yOf(v)).join(" ")}
            fill="none" stroke={s.color || "var(--brand)"} strokeWidth="2.5" strokeLinejoin="round" strokeLinecap="round" vectorEffect="non-scaling-stroke" />
        ))}
        {/* خط عمودي للنقطة النشطة */}
        {active != null && (
          <line x1={xOf(active)} y1={padT - 6} x2={xOf(active)} y2={padT + chartH} stroke="var(--brand)" strokeWidth="1" strokeDasharray="3 3" vectorEffect="non-scaling-stroke" opacity="0.6" />
        )}
      </svg>

      {/* النقاط + علامات القيمة (للخط المفرد) عبر overlay لتفادي تشوّه الدوائر */}
      {series.map((s, si) => s.values.map((v, i) => {
        const on = active === i;
        return (
          <span key={si + "-" + i} style={{ position: "absolute", left: xOf(i) + "%", top: yOf(v), width: on ? 12 : 9, height: on ? 12 : 9, marginInlineStart: -(on ? 6 : 4.5), marginTop: -(on ? 6 : 4.5), borderRadius: "50%", background: on ? (s.color || "var(--brand)") : "#fff", border: "2.5px solid " + (s.color || "var(--brand)"), boxSizing: "border-box", pointerEvents: "none", transition: "all .12s ease" }} />
        );
      }))}
      {single && series[0].values.map((v, i) => (
        <span key={"lbl" + i} style={{ position: "absolute", left: xOf(i) + "%", top: yOf(v) - 20, transform: "translateX(-50%)", whiteSpace: "nowrap", fontFamily: "var(--font-mono)", fontSize: 11.5, fontWeight: 700, color: active === i ? "var(--brand-strong)" : "var(--text-muted)", pointerEvents: "none" }}>{fmt(v)}</span>
      ))}

      {/* أسماء الأشهر */}
      {labels.map((m, i) => (
        <span key={"m" + i} style={{ position: "absolute", left: xOf(i) + "%", bottom: 4, transform: "translateX(-50%)", whiteSpace: "nowrap", fontSize: 12, fontWeight: active === i ? 700 : 400, color: active === i ? "var(--brand-strong)" : "var(--text-muted)", pointerEvents: "none" }}>{m}</span>
      ))}

      {/* أعمدة لمس/تمرير شفافة لالتقاط النقطة النشطة (نقر أو تمرير) */}
      {labels.map((m, i) => {
        const gap = n > 1 ? 100 / (n - 1) : 100;
        return (
          <div key={"hit" + i} onMouseEnter={() => setActive(i)} onClick={() => setActive(active === i ? null : i)}
            style={{ position: "absolute", left: (n > 1 ? (i - 0.5) * gap : 0) + "%", top: 0, height: H, width: gap + "%", cursor: "pointer" }} />
        );
      })}

      {/* Tooltip */}
      {active != null && (
        <div style={{ position: "absolute", left: xOf(active) + "%", top: 0, transform: "translateX(-50%)", zIndex: 5, pointerEvents: "none",
          background: "var(--surface-raised, #fff)", border: "1px solid var(--border-strong)", borderRadius: "var(--radius-md)", boxShadow: "var(--shadow-md, 0 4px 14px rgba(0,0,0,.12))", padding: "8px 11px", minWidth: 120 }}>
          <div style={{ fontSize: 12, fontWeight: 700, color: "var(--text-strong)", marginBottom: series.length > 1 ? 6 : 2 }}>{labels[active]}</div>
          {series.map((s, si) => (
            <div key={si} style={{ display: "flex", alignItems: "center", gap: 6, fontSize: 12, whiteSpace: "nowrap" }}>
              {series.length > 1 && <span style={{ width: 9, height: 9, borderRadius: 2, background: s.color || "var(--brand)", flex: "none" }} />}
              {series.length > 1 && <span style={{ color: "var(--text-muted)" }}>{s.name}:</span>}
              <span style={{ fontFamily: "var(--font-mono)", fontWeight: 700, color: "var(--text-strong)" }}>{fmt(s.values[active])}{unit ? " " + unit : ""}</span>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
window.BnyLineChart = BnyLineChart;

/* أداة ترتيب + تصفية مشتركة (زر بجانب البحث → قائمة منسدلة).
   props: sort, onSort, sortOptions[{key,label}], filterVal, onFilter,
          filterOptions[{value,label}], filterLabel */
function BnyListFilter({ sort, onSort, sortOptions, filterVal, onFilter, filterOptions, filterLabel }) {
  const I = window.BnyIcon;
  const [open, setOpen] = React.useState(false);
  const defaultSort = sortOptions && sortOptions[0] && sortOptions[0].key;
  const active = (sort && sort !== defaultSort) || !!filterVal;
  return (
    <div style={{ position: "relative", flex: "none" }}>
      <button type="button" onClick={() => setOpen((o) => !o)} aria-label="ترتيب وتصفية" title="ترتيب وتصفية"
        style={{ width: 40, height: 40, border: "1px solid var(--border-strong)", background: active ? "var(--brand-soft)" : "var(--surface-card)", color: active ? "var(--brand-strong)" : "var(--text-body)", borderRadius: "var(--radius-md)", cursor: "pointer", display: "inline-flex", alignItems: "center", justifyContent: "center", position: "relative" }}>
        <I.filter size={17} />
        {active && <span style={{ position: "absolute", top: 6, insetInlineEnd: 6, width: 7, height: 7, borderRadius: "50%", background: "var(--brand)" }} />}
      </button>
      {open && (
        <>
          <div onClick={() => setOpen(false)} style={{ position: "fixed", inset: 0, zIndex: 19 }} />
          <div style={{ position: "absolute", insetInlineEnd: 0, top: "calc(100% + 6px)", zIndex: 20, width: 260, background: "var(--surface-card)", border: "1px solid var(--border-subtle)", borderRadius: "var(--radius-md)", boxShadow: "var(--shadow-lg)", padding: 12 }}>
            <div style={{ fontSize: 12, fontWeight: 700, color: "var(--text-muted)", marginBottom: 8 }}>الترتيب</div>
            <div style={{ display: "flex", flexDirection: "column", gap: 3, marginBottom: filterOptions && filterOptions.length ? 12 : 0 }}>
              {(sortOptions || []).map((o) => (
                <button key={o.key} type="button" onClick={() => onSort(o.key)}
                  style={{ display: "flex", alignItems: "center", gap: 6, padding: "8px 10px", borderRadius: "var(--radius-md)", border: "none", cursor: "pointer", textAlign: "start", background: sort === o.key ? "var(--brand-soft)" : "transparent", color: sort === o.key ? "var(--brand-strong)" : "var(--text-body)", fontWeight: sort === o.key ? 700 : 500, fontSize: 13, fontFamily: "var(--font-body)" }}>
                  <span style={{ width: 14, flex: "none", display: "inline-flex" }}>{sort === o.key ? <I.check size={14} /> : null}</span>{o.label}
                </button>
              ))}
            </div>
            {filterOptions && filterOptions.length > 0 && (
              <>
                <div style={{ fontSize: 12, fontWeight: 700, color: "var(--text-muted)", margin: "0 0 8px" }}>{filterLabel || "التصفية"}</div>
                <select className="bny-input" value={filterVal} onChange={(e) => onFilter(e.target.value)} style={{ width: "100%", height: 38 }}>
                  <option value="">الكل</option>
                  {filterOptions.map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}
                </select>
              </>
            )}
            {active && (
              <button type="button" onClick={() => { onSort(defaultSort); onFilter(""); }}
                style={{ marginTop: 12, width: "100%", border: "1px solid var(--border-subtle)", background: "var(--surface-sunken)", borderRadius: "var(--radius-md)", padding: "8px", cursor: "pointer", fontSize: 12.5, color: "var(--text-muted)", fontFamily: "var(--font-body)" }}>إعادة التعيين</button>
            )}
          </div>
        </>
      )}
    </div>
  );
}
window.BnyListFilter = BnyListFilter;

/* جدول كشف الديون الإجمالي (عملاء/موردون).
   rows: [{ id, name, total, paid, remaining, extra }]
   props: totalLabel, nameLabel, extraLabel, onRow(row), onPdf(row), onPrint(row) */
function BnyDebtSummary({ title, nameLabel, totalLabel, extraLabel, rows, onRow, onPdf, onPrint }) {
  const I = window.BnyIcon;
  const { Card, Money } = window.BonyanDesignSystem_ad3ca0;
  const fmt = (n) => Number(n || 0).toLocaleString("en-US");
  const th = { fontWeight: 600, padding: "0 10px 12px", whiteSpace: "nowrap" };
  const td = { padding: "13px 10px", whiteSpace: "nowrap" };
  const pdfBtn = { display: "inline-flex", alignItems: "center", gap: 4, padding: "5px 10px", border: "1px solid var(--border-strong)", background: "var(--surface-card)", color: "var(--brand-strong)", borderRadius: "var(--radius-md)", cursor: "pointer", fontSize: 12, fontWeight: 600, fontFamily: "var(--font-body)" };
  const cols = extraLabel ? 7 : 6;
  return (
    <Card title={title}>
      <div style={{ overflowX: "auto" }}>
        <table style={{ width: "100%", borderCollapse: "collapse", minWidth: 760 }}>
          <thead>
            <tr style={{ color: "var(--text-muted)", fontSize: 12 }}>
              <th style={{ ...th, textAlign: "start", paddingInlineStart: 4 }}>#</th>
              <th style={{ ...th, textAlign: "start" }}>{nameLabel}</th>
              <th style={{ ...th, textAlign: "end" }}>{totalLabel}</th>
              <th style={{ ...th, textAlign: "end" }}>المدفوع</th>
              <th style={{ ...th, textAlign: "end" }}>المتبقي / الدين</th>
              {extraLabel && <th style={{ ...th, textAlign: "center" }}>{extraLabel}</th>}
              <th style={{ ...th, textAlign: "center" }}>كشف</th>
            </tr>
          </thead>
          <tbody>
            {rows.map((r) => (
              <tr key={r.id} onClick={() => onRow && onRow(r)}
                onMouseEnter={(e) => (e.currentTarget.style.background = "var(--surface-hover)")} onMouseLeave={(e) => (e.currentTarget.style.background = "transparent")}
                style={{ borderTop: "1px solid var(--border-subtle)", cursor: onRow ? "pointer" : "default", transition: "background var(--dur-fast,160ms) ease" }}>
                <td style={{ ...td, fontFamily: "var(--font-mono)", color: "var(--text-muted)", paddingInlineStart: 4 }}>{r.id}</td>
                <td style={{ ...td, fontWeight: 600, color: "var(--text-strong)" }}>{r.name}</td>
                <td style={{ ...td, textAlign: "end", fontFamily: "var(--font-mono)" }}>{fmt(r.total)} د.ع</td>
                <td style={{ ...td, textAlign: "end", fontFamily: "var(--font-mono)", color: "var(--success)" }}>{fmt(r.paid)} د.ع</td>
                <td style={{ ...td, textAlign: "end" }}>{r.remaining > 0 ? <Money value={r.remaining} unit="د.ع" tone="debt" /> : <span className="bny-badge bny-badge--success"><span className="bny-badge__dot" />مسدّد</span>}</td>
                {extraLabel && <td style={{ ...td, textAlign: "center", fontFamily: "var(--font-mono)", fontSize: 12.5, color: "var(--text-muted)" }}>{r.extra || "—"}</td>}
                <td style={{ ...td, textAlign: "center" }} onClick={(e) => e.stopPropagation()}>
                  <div style={{ display: "inline-flex", gap: 5 }}>
                    <button type="button" style={pdfBtn} onClick={() => onPdf(r)} title="سحب كشف PDF"><I.printer size={13} /> PDF</button>
                    {onPrint && <button type="button" className="bny-iconbtn bny-iconbtn--sm" onClick={() => onPrint(r)} title="طباعة" style={{ color: "var(--text-muted)" }}><I.printer size={15} /></button>}
                  </div>
                </td>
              </tr>
            ))}
            {rows.length === 0 && <tr><td colSpan={cols} style={{ padding: 20, textAlign: "center", color: "var(--text-muted)" }}>لا بيانات</td></tr>}
          </tbody>
        </table>
      </div>
    </Card>
  );
}
window.BnyDebtSummary = BnyDebtSummary;

/* ورقة كشف حساب A4 للطباعة/PDF — ألوان ورقية ثابتة.
   props: shop, title, entityName, entityMeta, cols[{label,align,mono,render}], rows, totals[{label,value,strong}] */
function BnyStatementSheet({ shop, title, entityName, entityMeta, cols, rows, totals }) {
  shop = shop || {};
  return (
    <div className="bny-print-sheet" style={{ color: "#333" }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", borderBottom: "2px solid #0B2A47", paddingBottom: 16, marginBottom: 16 }}>
        <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: "#0B2A47" }}>{shop.name || "بُنيان"}</div>
            {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>{title}</b></div>
          <div style={{ color: "#555" }}>التاريخ: {window.BnyAr ? window.BnyAr(new Date().toLocaleDateString("en-GB")) : new Date().toLocaleDateString("en-GB")}</div>
        </div>
      </div>
      <div style={{ fontSize: 14, marginBottom: 14 }}><b>{entityName}</b>{entityMeta ? <span style={{ color: "#555" }}> · {entityMeta}</span> : null}</div>
      <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13 }}>
        <thead><tr style={{ background: "#f0efec" }}>{cols.map((c, i) => <th key={i} style={{ textAlign: c.align || "start", padding: "8px 10px", borderBottom: "1px solid #333", fontWeight: 600 }}>{c.label}</th>)}</tr></thead>
        <tbody>
          {rows.map((r, i) => <tr key={i} style={{ borderBottom: "1px solid #e5e3df" }}>{cols.map((c, j) => <td key={j} style={{ padding: "8px 10px", textAlign: c.align || "start", fontFamily: c.mono ? "var(--font-mono)" : "inherit" }}>{c.render(r)}</td>)}</tr>)}
          {rows.length === 0 && <tr><td colSpan={cols.length} style={{ padding: 14, textAlign: "center", color: "#777" }}>لا حركات</td></tr>}
        </tbody>
      </table>
      <div style={{ display: "flex", justifyContent: "flex-start", marginTop: 18 }}>
        <div style={{ width: 320, fontSize: 14 }}>
          {totals.map((t, i) => <div key={i} style={{ display: "flex", justifyContent: "space-between", padding: "6px 0", borderTop: t.strong ? "2px solid #0B2A47" : "none", fontWeight: t.strong ? 700 : 400 }}><span style={{ color: t.strong ? "#0B2A47" : "#555" }}>{t.label}</span><span style={{ fontFamily: "var(--font-mono)", color: t.strong ? "#0B2A47" : "#333" }}>{t.value}</span></div>)}
        </div>
      </div>
      {shop.footer ? <div style={{ marginTop: 24, fontSize: 11, color: "#555", textAlign: "center" }}>{shop.footer}</div> : null}
    </div>
  );
}
window.BnyStatementSheet = BnyStatementSheet;

/* مخطط أعمدة بسيط ونظيف (مجموعات شهرية × سلاسل) — بديل أبسط للمنحنى.
   groups: [{ label, values: { <key>: number } }]، series: [{ key, name, color }].
   valueLabel(g): نص مختصر يظهر أعلى كل مجموعة (اختياري). */
function BnyBars({ groups, series, isMobile, height, valueLabel }) {
  const H = height || (isMobile ? 150 : 210);
  let max = 1;
  groups.forEach((g) => series.forEach((s) => { max = Math.max(max, Number(g.values[s.key]) || 0); }));
  return (
    <div>
      <div style={{ display: "flex", alignItems: "flex-end", gap: isMobile ? 6 : 12, height: H }}>
        {groups.map((g, i) => (
          <div key={i} style={{ flex: 1, minWidth: 0, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "flex-end", height: "100%" }}>
            {valueLabel && <span style={{ fontSize: isMobile ? 9 : 10.5, fontWeight: 600, color: "var(--text-strong)", fontFamily: "var(--font-mono)", marginBottom: 4, whiteSpace: "nowrap" }}>{valueLabel(g)}</span>}
            <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "center", gap: isMobile ? 3 : 5, width: "100%", flex: 1 }}>
              {series.map((s) => {
                const v = Number(g.values[s.key]) || 0;
                const h = v > 0 ? Math.max(3, Math.round(v / max * 100)) : 0;
                return <div key={s.key} title={s.name + ": " + v.toLocaleString("en-US")}
                  style={{ width: isMobile ? "38%" : "30%", maxWidth: 30, height: h + "%", minHeight: v > 0 ? 3 : 0, background: s.color, borderRadius: "5px 5px 0 0", transition: "height .45s cubic-bezier(.4,0,.2,1)" }} />;
              })}
            </div>
            <span style={{ fontSize: isMobile ? 9.5 : 11, color: "var(--text-muted)", marginTop: 8, whiteSpace: "nowrap" }}>{g.label}</span>
          </div>
        ))}
      </div>
      <div style={{ display: "flex", gap: 18, justifyContent: "center", marginTop: 14, fontSize: 12, color: "var(--text-muted)", flexWrap: "wrap" }}>
        {series.map((s) => <span key={s.key} style={{ display: "inline-flex", alignItems: "center", gap: 6 }}><span style={{ width: 11, height: 11, borderRadius: 3, background: s.color }} />{s.name}</span>)}
      </div>
    </div>
  );
}
window.BnyBars = BnyBars;

/* نافذة تسديد دفعة (عميل أو مورد) — مبلغ + عملة، مع عرض المستحق الحالي */
function BnyPayModal({ title, entityName, dueIqd, dueUsd, onSave, onClose }) {
  const I = window.BnyIcon;
  const { Button } = window.BonyanDesignSystem_ad3ca0;
  const [cur, setCur] = React.useState(dueIqd > 0 || dueUsd <= 0 ? "iqd" : "usd");
  const [amount, setAmount] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  const isUsd = cur === "usd";
  const due = isUsd ? (dueUsd || 0) : (dueIqd || 0);
  const val = Number(String(amount).replace(/[^\d.]/g, "")) || 0;
  const fmt = (n) => Number(n || 0).toLocaleString("en-US");
  const save = async () => {
    if (val <= 0 || busy) return;
    setBusy(true);
    try { await onSave(Math.min(val, due || val), cur); } 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: 380 }}>
        <h3 style={{ margin: "0 0 4px", fontSize: 17 }}>{title}</h3>
        <div style={{ fontSize: 13, color: "var(--text-muted)", marginBottom: 14 }}>{entityName}</div>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 12 }}>
          <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={() => { setCur("iqd"); setAmount(""); }}>د.ع</button>
            <button type="button" aria-pressed={isUsd} onClick={() => { setCur("usd"); setAmount(""); }}>دولار</button>
          </div>
        </div>
        <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12.5, color: "var(--text-muted)", marginBottom: 8 }}>
          <span>المستحق الحالي</span>
          <b style={{ fontFamily: "var(--font-mono)", color: due > 0 ? "var(--danger-text)" : "var(--success)" }}>{fmt(due)} {isUsd ? "$" : "د.ع"}</b>
        </div>
        <input className="bny-input bny-input--numeric" inputMode="decimal" autoFocus
          value={isUsd ? amount : (amount ? Number(amount).toLocaleString("en-US") : "")}
          onChange={(e) => setAmount(e.target.value.replace(/[^\d.]/g, ""))}
          placeholder="مبلغ الدفعة" aria-label="مبلغ الدفعة"
          style={{ width: "100%", height: 44, fontSize: 16, fontWeight: 700, textAlign: "center", marginBottom: 8 }} />
        {due > 0 && (
          <button type="button" onClick={() => setAmount(String(due))}
            style={{ border: 0, background: "none", color: "var(--brand-strong)", cursor: "pointer", fontSize: 12.5, fontWeight: 600, fontFamily: "var(--font-body)", padding: 0, marginBottom: 12 }}>
            تسديد كامل ({fmt(due)})
          </button>
        )}
        <div style={{ display: "flex", gap: 8, justifyContent: "flex-end", marginTop: 6 }}>
          <Button variant="secondary" onClick={onClose}>إلغاء</Button>
          <Button variant="accent" icon={<I.check size={15} />} onClick={save} disabled={val <= 0 || busy}>{busy ? "جارٍ الحفظ…" : "تأكيد الدفعة"}</Button>
        </div>
      </div>
    </div>
  );
}
window.BnyPayModal = BnyPayModal;

/* نافذة تأكيد بصلاحية المدير:
   - المدير/المالك الحالي: تأكيد بسيط (نعم/لا).
   - الموظف العادي: يطلب اسم مستخدم + كلمة مرور مدير ويتحقق منها فعليًا. */
function BnyManagerConfirm({ title, message, confirmLabel, onConfirm, onClose }) {
  const I = window.BnyIcon;
  const { Button, Input } = window.BonyanDesignSystem_ad3ca0;
  const user = window.BnyCurrentUser || {};
  const isManager = user.role === "manager" || user.isOwner || user.owner;
  const [u, setU] = React.useState("");
  const [p, setP] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState("");
  const run = async () => {
    if (busy) return;
    setBusy(true); setErr("");
    try {
      // المدير/المالك: بلا بيانات. الموظف: يمرّر بيانات مدير.
      const creds = isManager ? null : { user: u.trim(), pass: p };
      // في الوضع التجريبي فقط نتحقق محليًا؛ في المباشر تتحقق دالة القاعدة (وفيها قفل تخمين).
      if (!isManager && !window.BnyConfigured) {
        const ok = await window.BnyVerifyManager(creds.user, creds.pass);
        if (!ok) { setErr("بيانات المدير غير صحيحة أو لا يملك الصلاحية"); setBusy(false); return; }
      }
      await onConfirm(creds);
    } catch (e) { setErr(String((e && e.message) || e)); setBusy(false); }
  };
  return (
    <div onClick={onClose} style={{ position: "fixed", inset: 0, zIndex: 1100, background: "rgba(0,0,0,.5)", 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 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 10 }}>
          <span style={{ display: "inline-flex", alignItems: "center", justifyContent: "center", width: 40, height: 40, borderRadius: "var(--radius-md)", background: "var(--danger-soft)", color: "var(--danger)", flex: "none" }}><I.alert size={22} /></span>
          <h3 style={{ margin: 0, fontSize: 17 }}>{title || "تأكيد العملية"}</h3>
        </div>
        <p style={{ fontSize: 13.5, color: "var(--text-body)", lineHeight: 1.7, margin: "0 0 14px" }}>{message}</p>
        {!isManager && (
          <div style={{ display: "flex", flexDirection: "column", gap: 10, marginBottom: 12 }}>
            <div style={{ fontSize: 12, color: "var(--text-muted)", fontWeight: 600 }}>هذه العملية تتطلب تخويل مدير:</div>
            <Input value={u} onChange={(e) => setU(e.target.value)} placeholder="اسم مستخدم المدير" icon={<I.users size={15} />} />
            <Input value={p} onChange={(e) => setP(e.target.value)} type="password" placeholder="كلمة مرور المدير" />
          </div>
        )}
        {err && <div style={{ padding: "8px 12px", background: "var(--danger-soft)", color: "var(--danger-text)", borderRadius: "var(--radius-md)", fontSize: 12.5, marginBottom: 10 }}>{err}</div>}
        <div style={{ display: "flex", gap: 8, justifyContent: "flex-end" }}>
          <Button variant="secondary" onClick={onClose}>إلغاء</Button>
          <Button variant="danger" icon={<I.trash size={15} />} onClick={run} disabled={busy || (!isManager && (!u.trim() || !p))}>{busy ? "جارٍ…" : (confirmLabel || "تأكيد الحذف")}</Button>
        </div>
      </div>
    </div>
  );
}
window.BnyManagerConfirm = BnyManagerConfirm;
