/* Bonyan ERP — Inventory / warehouse */
function InventoryScreen({ user }) {
  const I = window.BnyIcon;
  const D = window.BnyData;
  const { Card, Button, Money, Badge, Select, Input } = window.BonyanDesignSystem_ad3ca0;
  const isMobile = window.useBnyMobile();
  const canCost = window.BnyCan(user, "purchase_price"); // رؤية سعر الشراء
  const canEdit = window.BnyCan(user, "inventory_edit");
  const [wh, setWh] = React.useState("all");
  // بحث معلّق من المساعد الصوتي (اسم مادة) — يُستهلك مرة واحدة
  const [q, setQ] = React.useState(() => {
    const s = window.BnyPendingInvSearch;
    if (s) { window.BnyPendingInvSearch = null; return s; }
    return "";
  });
  // all | low | out | reorder — قد يصل مطلوبًا من لوحة التحكم (عرض الكل)
  const [filter, setFilter] = React.useState(() => {
    var f = window.BnyPendingInvFilter; if (f) { window.BnyPendingInvFilter = null; return f; } return "all";
  });
  const [, forceRender] = React.useReducer((x) => x + 1, 0);
  const [editMat, setEditMat] = React.useState(null); // null | {} جديدة | {مادة} تعديل
  const [transferMat, setTransferMat] = React.useState(null); // مادة قيد النقل بين المخازن
  const [catF, setCatF] = React.useState("all"); // فلتر الفئة
  const saveMat = async (m) => { await window.BnyOps.saveMaterial(m); setEditMat(null); forceRender(); };
  // مدة الركود (متغيّر ديناميكي يُضبط هنا، افتراضي 30) — تعتمده لوحة التحكم
  const [stagDays, setStagDays] = React.useState(D.stagnantDays || 30);
  const onStagDays = (v) => setStagDays(window.BnySetStagnantDays(v));
  const stagnantSkus = React.useMemo(
    () => new Set(window.BnyStagnantMaterials(stagDays).map((x) => x.m.sku)),
    [stagDays, D.materials, D.invoices]
  );

  // computed inventory health (from data, not hardcoded)
  const lowCount = D.materials.filter((m) => m.stock > 0 && m.stock <= m.low).length;
  const outCount = D.materials.filter((m) => m.stock === 0).length;
  const totalValue = D.materials.reduce((s, m) => s + m.price * m.stock, 0);

  let rows = D.materials;
  if (wh !== "all") rows = rows.filter((m) => m.wh === wh);
  if (q) rows = rows.filter((m) => (m.name + m.sku + m.cat).includes(q));
  if (catF !== "all") rows = rows.filter((m) => m.cat === catF); // فلترة حسب الفئة
  if (filter === "low") rows = rows.filter((m) => m.stock > 0 && m.stock <= m.low);
  if (filter === "out") rows = rows.filter((m) => m.stock === 0);
  if (filter === "reorder") rows = rows.filter((m) => m.stock <= m.low); // نافدة + ستنفد قريبًا

  const stockBadge = (m) => {
    const base = m.stock === 0 ? <Badge tone="danger" dot>نفد</Badge>
      : m.stock <= m.low ? <Badge tone="warning" dot>منخفض</Badge>
      : <Badge tone="success" dot>متوفر</Badge>;
    if (!stagnantSkus.has(m.sku)) return base;
    return <span style={{ display: "inline-flex", alignItems: "center", gap: 6, flexWrap: "wrap" }}>{base}<span className="bny-tag" style={{ fontSize: 11, padding: "2px 8px", color: "var(--text-muted)" }}>راكد</span></span>;
  };

  return (
    <div style={{ padding: isMobile ? "var(--space-4)" : "var(--space-8)", display: "flex", flexDirection: "column", gap: isMobile ? "var(--space-4)" : "var(--space-6)" }}>
      <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr" : "2fr 1fr 1fr", gap: "var(--space-5)" }}>
        <SummaryTile icon={<I.inventory size={18} />} label="إجمالي قيمة المخزون" value={totalValue.toLocaleString("en-US")} unit="د.ع"
          active={filter === "all"} onClick={() => setFilter("all")} />
        <SummaryTile icon={<I.alert size={18} />} label="مواد منخفضة المخزون" value={String(lowCount)} sub="قاربت حد الطلب" tone="warning"
          active={filter === "low"} onClick={() => setFilter("low")} />
        <SummaryTile icon={<I.x size={18} />} label="مواد نافدة (رصيد صفر)" value={String(outCount)} sub="بحاجة لإعادة طلب" tone="danger"
          active={filter === "out"} onClick={() => setFilter("out")} />
      </div>

      <Card title={filter === "out" ? "المواد النافدة" : filter === "low" ? "المواد المنخفضة" : filter === "reorder" ? "مواد تحتاج شراء (نافدة + ستنفد قريبًا)" : "المواد والأصناف"}
        actions={canEdit ? <Button size="sm" icon={<I.plus size={16} />} onClick={() => setEditMat({})}>إضافة مادة</Button> : null}>
        <div style={{ display: "flex", gap: 12, marginBottom: 16, alignItems: "center", flexWrap: "wrap" }}>
          <div style={{ flex: 1, minWidth: 180, maxWidth: 320 }}>
            <Input value={q} onChange={(e) => setQ(e.target.value)} placeholder="ابحث عن مادة أو رمز أو فئة" icon={<I.search size={16} />} />
          </div>
          {(filter !== "all" || catF !== "all") && (
            <Button variant="ghost" size="sm" icon={<I.x size={16} />} onClick={() => { setFilter("all"); setCatF("all"); }}>إزالة الفلتر</Button>
          )}
          {canEdit && (
            <div style={{ display: "flex", alignItems: "center", gap: 6, marginInlineStart: "auto" }} title="المادة التي لم تُبَع خلال هذه المدة تُعدّ راكدة وتظهر في لوحة التحكم">
              <span style={{ fontSize: 12.5, color: "var(--text-muted)", whiteSpace: "nowrap" }}>مدة الركود (يوم)</span>
              <input className="bny-input bny-input--numeric" type="text" inputMode="numeric" value={stagDays}
                onChange={(e) => onStagDays(e.target.value.replace(/[^\d]/g, ""))}
                style={{ width: 64, height: 36, textAlign: "center", fontFamily: "var(--font-mono)" }} />
            </div>
          )}
          <div style={{ width: 170, marginInlineStart: canEdit ? 0 : "auto" }}>
            <Select value={catF} onChange={(e) => setCatF(e.target.value)} aria-label="فلترة حسب الفئة">
              <option value="all">كل الفئات</option>
              {(D.categories || []).map((c) => <option key={c.id} value={c.name}>{c.name}</option>)}
            </Select>
          </div>
          <div style={{ width: 170 }}>
            <Select value={wh} onChange={(e) => setWh(e.target.value)} aria-label="فلترة حسب المخزن">
              <option value="all">كل المخازن</option>
              {(D.warehouses || []).map((w) => <option key={w.id} value={w.name}>{w.name}</option>)}
            </Select>
          </div>
        </div>
        {isMobile ? (
          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            {rows.map((m) => (
              <div key={m.sku} className="bny-card" style={{ padding: "12px 14px" }} onClick={canEdit ? () => setEditMat({ ...m }) : undefined}>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 8 }}>
                  <div style={{ fontWeight: 600, color: "var(--text-strong)", fontSize: 14, flex: 1, minWidth: 0 }}>{m.name}</div>
                  {canEdit && (
                    <button className="bny-iconbtn bny-iconbtn--sm" title="نقل إلى مخزن آخر" aria-label="نقل إلى مخزن آخر"
                      onClick={(e) => { e.stopPropagation(); setTransferMat(m); }} style={{ color: "var(--brand)", flex: "none" }}><I.arrows size={15} /></button>
                  )}
                  {stockBadge(m)}
                </div>
                <div style={{ fontSize: 11.5, color: "var(--text-muted)", fontFamily: "var(--font-mono)", marginTop: 3 }}>
                  {m.sku} · {m.cat} · {m.wh}{m.hasMultiUnits ? ` · ${m.packUnit}=${m.subUnitCount}${m.unit}` : ""}
                </div>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", marginTop: 8 }}>
                  <div style={{ fontFamily: "var(--font-mono)", fontWeight: 600, fontSize: 13, color: m.stock === 0 ? "var(--danger-text)" : "var(--text-strong)" }}>
                    {m.hasMultiUnits
                      ? <span>{window.BnyStock(m)} <span style={{ color: "var(--text-muted)", fontWeight: 400 }}>({m.stock.toLocaleString("en-US")} {m.unit})</span></span>
                      : <span>{m.stock.toLocaleString("en-US")} <span style={{ color: "var(--text-muted)", fontWeight: 400 }}>{m.unit}</span></span>}
                  </div>
                  <div style={{ textAlign: "end" }}>
                    {canCost && <div style={{ fontSize: 11, color: "var(--text-muted)" }}>شراء: <Money value={m.cost} style={{ fontSize: 11 }} /></div>}
                    <Money value={m.price} />
                  </div>
                </div>
              </div>
            ))}
            {rows.length === 0 && <div style={{ padding: "24px", textAlign: "center", color: "var(--text-muted)" }}>لا توجد مواد مطابقة</div>}
          </div>
        ) : (
        <div style={{ overflowX: "auto" }}>
        <table style={{ width: "100%", borderCollapse: "collapse", minWidth: 720 }}>
          <thead>
            <tr style={{ color: "var(--text-muted)", fontSize: 12 }}>
              {["المادة", "الرمز", "الفئة", "المخزن", "الحالة", "الرصيد", ...(canCost ? ["سعر الشراء"] : []), "السعر", ...(canEdit ? [""] : [])].map((h, hi) => (
                <th key={hi} style={{ textAlign: (h === "الرصيد" || h === "سعر الشراء" || h === "السعر") ? "end" : "start", fontWeight: 600, padding: "0 0 12px" }}>{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {rows.map((m) => (
              <tr key={m.sku} style={{ borderTop: "1px solid var(--border-subtle)" }}>
                <td style={{ padding: "13px 0", fontSize: 14, fontWeight: 600, color: "var(--text-strong)" }}>
                  {m.name}
                  {m.hasMultiUnits && (
                    <span className="bny-tag" style={{ marginInlineStart: 8, fontSize: 11, padding: "2px 8px" }}>
                      {m.packUnit} = {m.subUnitCount} {m.unit}
                    </span>
                  )}
                </td>
                <td style={{ padding: "13px 0", fontFamily: "var(--font-mono)", fontSize: 12.5, color: "var(--text-muted)" }}>{m.sku}</td>
                <td style={{ padding: "13px 0" }}><span className="bny-tag">{m.cat}</span></td>
                <td style={{ padding: "13px 0", fontSize: 13 }}>{m.wh}</td>
                <td style={{ padding: "13px 0" }}>{stockBadge(m)}</td>
                <td style={{ padding: "13px 0", textAlign: "end", fontFamily: "var(--font-mono)", fontWeight: 600, color: m.stock === 0 ? "var(--danger-text)" : "var(--text-strong)" }}>
                  {m.hasMultiUnits ? (
                    <div style={{ lineHeight: 1.4 }}>
                      <div>{window.BnyStock(m)}</div>
                      <div style={{ color: "var(--text-muted)", fontWeight: 400, fontSize: 11 }}>{m.stock.toLocaleString("en-US")} {m.unit}</div>
                    </div>
                  ) : (
                    <span>{m.stock.toLocaleString("en-US")} <span style={{ color: "var(--text-muted)", fontWeight: 400, fontSize: 12 }}>{m.unit}</span></span>
                  )}
                </td>
                {canCost && <td style={{ padding: "13px 0", textAlign: "end" }}><Money value={m.cost} /></td>}
                <td style={{ padding: "13px 0", textAlign: "end" }}><Money value={m.price} /></td>
                {canEdit && (
                  <td style={{ padding: "13px 0", textAlign: "center", width: 76, whiteSpace: "nowrap" }}>
                    <button className="bny-iconbtn bny-iconbtn--sm" title="نقل إلى مخزن آخر" aria-label="نقل إلى مخزن آخر"
                      onClick={() => setTransferMat(m)} style={{ color: "var(--brand)" }}><I.arrows size={15} /></button>
                    <button className="bny-iconbtn bny-iconbtn--sm" title="تعديل المادة" aria-label="تعديل المادة"
                      onClick={() => setEditMat({ ...m })} style={{ color: "var(--text-muted)", marginInlineStart: 2 }}><I.settings size={15} /></button>
                  </td>
                )}
              </tr>
            ))}
            {rows.length === 0 && (
              <tr><td colSpan={(canCost ? 8 : 7) + (canEdit ? 1 : 0)} style={{ padding: "28px 0", textAlign: "center", color: "var(--text-muted)" }}>لا توجد مواد مطابقة</td></tr>
            )}
          </tbody>
        </table>
        </div>
        )}
      </Card>

      {editMat && <MaterialModal m={editMat} onSave={saveMat} onClose={() => setEditMat(null)} />}
      {transferMat && <TransferModal m={transferMat} onDone={() => { setTransferMat(null); forceRender(); }} onClose={() => setTransferMat(null)} />}
    </div>
  );
}

/* نافذة نقل مادة بين المخازن */
function TransferModal({ m, onDone, onClose }) {
  const I = window.BnyIcon;
  const D = window.BnyData;
  const { Button, Select } = window.BonyanDesignSystem_ad3ca0;
  const others = (D.warehouses || []).filter((w) => w.name !== m.wh);
  const [target, setTarget] = React.useState(others.length ? others[0].name : "");
  const [qty, setQty] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState("");
  const val = Number(String(qty).replace(/[^\d.]/g, "")) || 0;
  const lbl = { fontSize: 12.5, fontWeight: 600, color: "var(--text-strong)", display: "block", marginBottom: 5 };
  const doTransfer = async () => {
    if (busy) return;
    setBusy(true); setErr("");
    try {
      const res = await window.BnyOps.transferStock(m, target, val);
      onDone(res);
    } catch (e) { setErr(String((e && e.message) || e)); }
    finally { setBusy(false); }
  };
  return (
    <div onClick={onClose} style={{ position: "fixed", inset: 0, zIndex: 1000, background: "rgba(0,0,0,.45)", display: "flex", alignItems: "center", justifyContent: "center", padding: "var(--space-5)" }}>
      <div onClick={(e) => e.stopPropagation()} className="bny-card bny-card--pad" style={{ width: "100%", maxWidth: 400 }}>
        <h3 style={{ margin: "0 0 4px", fontSize: 17, display: "flex", alignItems: "center", gap: 8 }}><I.arrows size={18} /> نقل بين المخازن</h3>
        <div style={{ fontSize: 13, color: "var(--text-muted)", marginBottom: 14 }}>{m.name} · الرصيد الحالي: <b style={{ fontFamily: "var(--font-mono)", color: "var(--text-strong)" }}>{m.stock} {m.unit}</b></div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, marginBottom: 12 }}>
          <div>
            <label style={lbl}>من مخزن</label>
            <input className="bny-input" value={m.wh} disabled style={{ width: "100%", height: 40, background: "var(--surface-sunken)" }} aria-label="من مخزن" />
          </div>
          <div>
            <label style={lbl}>إلى مخزن *</label>
            <Select value={target} onChange={(e) => setTarget(e.target.value)}>
              {others.map((w) => <option key={w.id} value={w.name}>{w.name}</option>)}
            </Select>
          </div>
        </div>
        <div style={{ marginBottom: 8 }}>
          <label style={lbl}>الكمية المنقولة ({m.unit}) *</label>
          <input className="bny-input bny-input--numeric" inputMode="decimal" value={qty} autoFocus
            onChange={(e) => setQty(e.target.value.replace(/[^\d.]/g, ""))} placeholder={"بحد أقصى " + m.stock}
            style={{ width: "100%", height: 42, fontSize: 15, fontWeight: 700, textAlign: "center" }} aria-label="الكمية المنقولة" />
        </div>
        <button type="button" onClick={() => setQty(String(m.stock))}
          style={{ border: 0, background: "none", color: "var(--brand-strong)", cursor: "pointer", fontSize: 12.5, fontWeight: 600, fontFamily: "var(--font-body)", padding: 0, marginBottom: 10 }}>
          نقل كامل الرصيد ({m.stock})
        </button>
        {others.length === 0 && <div style={{ padding: "8px 12px", background: "var(--warning-soft)", color: "var(--warning-text)", borderRadius: "var(--radius-md)", fontSize: 12.5, marginBottom: 10 }}>لا يوجد مخزن آخر — أضف مخزنًا من «إدارة المخازن» أولًا.</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="accent" icon={<I.arrows size={15} />} onClick={doTransfer} disabled={val <= 0 || !target || busy}>{busy ? "جارٍ النقل…" : "تنفيذ النقل"}</Button>
        </div>
      </div>
    </div>
  );
}

/* نافذة إضافة/تعديل مادة */
function MaterialModal({ m, onSave, onClose }) {
  const I = window.BnyIcon;
  const D = window.BnyData;
  const { Button, Input, Select } = window.BonyanDesignSystem_ad3ca0;
  const isNew = !m.sku;
  const cats = D.categories || [];
  const whs = D.warehouses || [];
  const [f, setF] = React.useState(() => ({
    sku: m.sku || "", name: m.name || "", cat: m.cat || "", unit: m.unit || "قطعة",
    hasMultiUnits: !!m.hasMultiUnits, packUnit: m.packUnit || "", subUnitCount: m.subUnitCount || 1,
    price: m.price || 0, priceUsd: m.priceUsd || 0, cost: m.cost || 0,
    stock: m.stock || 0, low: m.low || 0, wh: m.wh || (whs[0] && whs[0].name) || "الرئيسي",
  }));
  const [busy, setBusy] = React.useState(false);
  const set = (k, v) => setF((s) => ({ ...s, [k]: v }));
  const num = (v) => Number(String(v).replace(/[^\d.]/g, "")) || 0;
  const lbl = { fontSize: 12.5, fontWeight: 600, color: "var(--text-strong)", display: "block", marginBottom: 5 };
  // الفئة إلزامية ويجب أن تطابق الفئات المُدارة (إدارة المخازن)
  const catValid = f.cat.trim() !== "" && cats.some((c) => c.name === f.cat);
  const canSave = f.name.trim() !== "" && f.unit.trim() !== "" && catValid && (!f.hasMultiUnits || (f.packUnit.trim() && f.subUnitCount > 1));
  const save = async () => {
    if (!canSave || busy) return;
    setBusy(true);
    try {
      const sku = f.sku.trim() || ("BNY-" + Date.now().toString(36).toUpperCase());
      await onSave({
        sku, name: f.name.trim(), cat: f.cat.trim(), unit: f.unit.trim(),
        hasMultiUnits: f.hasMultiUnits, packUnit: f.hasMultiUnits ? f.packUnit.trim() : undefined,
        subUnitCount: f.hasMultiUnits ? Math.max(2, num(f.subUnitCount)) : 1,
        price: num(f.price), priceUsd: Number(f.priceUsd) || 0, cost: num(f.cost),
        stock: num(f.stock), low: num(f.low), wh: f.wh.trim() || "الرئيسي",
      });
    } catch (e) { console.error(e); } finally { setBusy(false); }
  };
  const numInput = (key, ph) => (
    <input className="bny-input bny-input--numeric" inputMode="decimal" value={f[key]}
      onChange={(e) => set(key, e.target.value.replace(/[^\d.]/g, ""))} placeholder={ph || "0"}
      style={{ width: "100%", height: 38 }} aria-label={ph} />
  );
  return (
    <div onClick={onClose} style={{ position: "fixed", inset: 0, zIndex: 1000, background: "rgba(0,0,0,.45)", display: "flex", alignItems: "center", justifyContent: "center", padding: "var(--space-5)" }}>
      <div onClick={(e) => e.stopPropagation()} className="bny-card" style={{ width: "100%", maxWidth: 520, padding: 0, display: "flex", flexDirection: "column", maxHeight: "90vh" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "16px 20px", borderBottom: "1px solid var(--border-subtle)" }}>
          <h3 style={{ margin: 0, fontSize: 17, flex: 1 }}>{isNew ? "إضافة مادة جديدة" : "تعديل: " + m.name}</h3>
          <button onClick={onClose} style={{ border: 0, background: "none", cursor: "pointer", color: "var(--text-muted)", display: "inline-flex" }} aria-label="إغلاق"><I.x size={20} /></button>
        </div>
        <div style={{ overflowY: "auto", padding: "14px 20px", display: "flex", flexDirection: "column", gap: 12 }}>
          <div><label style={lbl}>اسم المادة *</label><Input value={f.name} onChange={(e) => set("name", e.target.value)} placeholder="مثال: حديد تسليح ١٦ ملم" autoFocus={isNew} /></div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
            <div><label style={lbl}>الرمز (SKU)</label><Input value={f.sku} onChange={(e) => set("sku", e.target.value)} placeholder="يُولَّد تلقائيًا إن تُرك" disabled={!isNew} /></div>
            <div>
              <label style={lbl}>الفئة *</label>
              <Select value={f.cat} onChange={(e) => set("cat", e.target.value)}>
                <option value="">— اختر فئة —</option>
                {cats.map((c) => <option key={c.id} value={c.name}>{c.name}</option>)}
              </Select>
              {!catValid && f.cat === "" && <div style={{ fontSize: 11, color: "var(--text-muted)", marginTop: 4 }}>إلزامية — تُدار الفئات من «إدارة المخازن»</div>}
            </div>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
            <div><label style={lbl}>الوحدة الأساسية *</label><Input value={f.unit} onChange={(e) => set("unit", e.target.value)} placeholder="قطعة / كيس / طن" /></div>
            <div>
              <label style={lbl}>المخزن *</label>
              <Select value={f.wh} onChange={(e) => set("wh", e.target.value)}>
                {whs.map((w) => <option key={w.id} value={w.name}>{w.name}</option>)}
              </Select>
            </div>
          </div>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8, padding: "2px 0" }}>
            <span style={{ fontSize: 13.5, fontWeight: 600, color: "var(--text-strong)" }}>وحدات متعددة (كرتون/قطعة)</span>
            <div className="bny-switch" role="switch" aria-checked={f.hasMultiUnits ? "true" : "false"} data-on={f.hasMultiUnits ? "true" : "false"} onClick={() => set("hasMultiUnits", !f.hasMultiUnits)}>
              <span className="bny-switch__track"><span className="bny-switch__thumb" /></span>
            </div>
          </div>
          {f.hasMultiUnits && (
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
              <div><label style={lbl}>الوحدة الكبرى *</label><Input value={f.packUnit} onChange={(e) => set("packUnit", e.target.value)} placeholder="كرتون" /></div>
              <div><label style={lbl}>عدد الوحدات الصغرى فيها *</label>{numInput("subUnitCount", "12")}</div>
            </div>
          )}
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 10 }}>
            <div><label style={lbl}>سعر البيع (د.ع)</label>{numInput("price")}</div>
            <div><label style={lbl}>سعر البيع ($)</label>
              <input className="bny-input bny-input--numeric" type="number" min="0" step="0.5" value={f.priceUsd}
                onChange={(e) => set("priceUsd", e.target.value)} style={{ width: "100%", height: 38 }} aria-label="سعر البيع بالدولار" />
            </div>
            <div><label style={lbl}>سعر الشراء (د.ع)</label>{numInput("cost")}</div>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
            <div><label style={lbl}>الرصيد الحالي</label>{numInput("stock")}</div>
            <div><label style={lbl}>حد التنبيه (منخفض)</label>{numInput("low")}</div>
          </div>
        </div>
        <div style={{ padding: "12px 20px", borderTop: "1px solid var(--border-subtle)", display: "flex", gap: 8, justifyContent: "flex-end" }}>
          <Button variant="secondary" onClick={onClose}>إلغاء</Button>
          <Button variant="accent" icon={<I.check size={15} />} onClick={save} disabled={!canSave || busy}>{busy ? "جارٍ الحفظ…" : isNew ? "إضافة المادة" : "حفظ التعديلات"}</Button>
        </div>
      </div>
    </div>
  );
}

function SummaryTile({ icon, label, value, unit, sub, tone, active, onClick }) {
  const color = tone === "danger" ? "var(--danger)" : tone === "warning" ? "var(--warning)" : "var(--brand)";
  const soft = tone === "danger" ? "var(--danger-soft)" : tone === "warning" ? "var(--warning-soft)" : "var(--brand-soft)";
  return (
    <button onClick={onClick} className="bny-card bny-card--interactive" style={{
      display: "flex", alignItems: "center", gap: 14, padding: "var(--space-6) var(--space-7)",
      textAlign: "start", cursor: "pointer", width: "100%",
      border: active ? `1px solid ${color}` : "1px solid var(--border-subtle)",
      boxShadow: active ? "var(--elevation-raised)" : "var(--elevation-card)",
    }}>
      <span style={{ display: "inline-flex", alignItems: "center", justifyContent: "center", width: 44, height: 44, borderRadius: "var(--radius-md)", background: soft, color }}>{icon}</span>
      <div>
        <div style={{ fontSize: 13, color: "var(--text-muted)", fontWeight: 500 }}>{label}</div>
        <div style={{ fontFamily: "var(--font-mono)", fontWeight: 700, fontSize: 22, color: "var(--text-strong)", marginTop: 2 }}>{value}{unit ? <span style={{ fontSize: 12, color: "var(--text-muted)", fontWeight: 500, marginInlineStart: 4 }}>{unit}</span> : null}</div>
        {sub ? <div style={{ fontSize: 11, color, fontWeight: 600, marginTop: 2 }}>{sub}</div> : null}
      </div>
    </button>
  );
}
window.InventoryScreen = InventoryScreen;
