// ============================================================================
//  Склад — власні склади Digitalshop (Новоселиця $ / Чернівці грн), окремо від
//  зовнішніх постачальників. Перегляд + правка Ціни (C) та Первинного залишку (D),
//  додавання/видалення товару, аналітика (Hotline + сайт + постачальники).
//  Бекенд: /api/warehouses* (server.js). Джерело правди — warehouses.js.
//  Бот / updateWarehouseSold / леджер — НЕ зачіпаються. F (=D−E) та I (сума) —
//  формули в таблиці, CRM їх не пише.
//  Дизайн із handoff_sklad_pack — mock замінено на реальні API-виклики.
//  Усе в IIFE: внутрішні імена не конфліктують з іншими компонентами CRM.
// ============================================================================
(function () {
  const { useState, useEffect, useRef, useMemo } = React;

  // одноразова ін'єкція анімацій (у проді цих keyframes може не бути)
  (function injectAnim() {
    if (document.getElementById("sklad-anim")) return;
    const s = document.createElement("style");
    s.id = "sklad-anim";
    s.textContent =
      "@keyframes spin{to{transform:rotate(360deg)}}" +
      "@keyframes skFade{from{opacity:0}to{opacity:1}}" +
      "@keyframes skSheetUp{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:none}}" +
      "@keyframes skFadeM{from{opacity:0}to{opacity:1}}" +
      "@keyframes skSheetUpM{from{transform:translateY(100%)}to{transform:translateY(0)}}";
    document.head.appendChild(s);
  })();

  // ---- Валюта / формати -----------------------------------------------------
  const CUR_SYM = { USD: "$", UAH: "₴", EUR: "€" };
  const CUR_LABEL = { USD: "USD", UAH: "грн", EUR: "EUR" };
  const fmtInt = n => Math.round(Number(n) || 0).toLocaleString("uk-UA").replace(/ /g, " ").replace(/,/g, " ");
  const fmtMoney = (n, cur = "UAH") => {
    if (n == null) return "—";
    const v = Number(n);
    const body = Number.isInteger(v) ? fmtInt(v) : v.toLocaleString("uk-UA", { minimumFractionDigits: 2, maximumFractionDigits: 2 }).replace(/ /g, " ");
    return cur === "USD" ? CUR_SYM.USD + body : body + " " + (CUR_SYM[cur] || "₴");
  };
  const fmtUAH = n => (n == null ? "—" : fmtInt(n) + " ₴");
  // сервер віддає stockFinal/sum; fallback — рахунок (оптимістичний UI)
  const calcFinal = it => (it.stockFinal != null ? it.stockFinal : Math.max(0, (it.stockPrimary || 0) - (it.sold || 0)));
  const calcSum = it => (it.sum != null ? it.sum : (it.price || 0) * calcFinal(it));

  // ---- Аналітика — реальні ендпоінти (як DetailPanel у Прайси) ---------------
  const SK_PALETTE = ["#3B82F6", "#F59E0B", "#8B5CF6", "#14B8A6", "#F43F5E", "#10B981", "#6366F1", "#EC4899"];
  const skSupColor = s => { let h = 0; const str = String(s || ""); for (let i = 0; i < str.length; i++) h = (h * 31 + str.charCodeAt(i)) | 0; return SK_PALETTE[Math.abs(h) % SK_PALETTE.length]; };
  const skNorm = s => String(s || "").toLowerCase().replace(/[^a-z0-9]/g, "");

  let _pcCache = { ts: 0, data: null };
  async function getPcProducts() {
    if (_pcCache.data && Date.now() - _pcCache.ts < 5 * 60 * 1000) return _pcCache.data;
    const j = await API.priceCacheProducts();
    const data = (j && (j.data || j.products)) || (Array.isArray(j) ? j : []);
    _pcCache = { ts: Date.now(), data };
    return data;
  }

  async function loadAnalytics(item, key) {
    const out = {
      horoshop: { price: null, url: "#" },
      hotline: { ok: true, found: false, offers: [], total: 0, ourRank: 0, url: "#" },
      suppliers: [],
    };
    const art = skNorm(item.article);
    // 1) ціна на сайті (ендпоінт віддає { found, data:{ price, url } })
    try {
      const hp = await API.findHoroshopProduct(item.article);
      const d = hp && hp.found && hp.data;
      if (d && d.price != null) out.horoshop = { price: Number(d.price) || null, url: d.url || "#" };
    } catch (e) {}
    // 2) Hotline + 3) постачальники (паралельно; ourRank спирається на horoshop.price)
    await Promise.all([
      (async () => {
        try {
          const h = await API.hotlineAudit(item.name, item.article || key);
          if (h && h.found) {
            const offers = (h.offers || []).map(o => ({
              shop: o.store || o.shop || o.name || ("Магазин " + (o.rank || "")),
              price: Number(o.price) || 0, rank: o.rank, us: !!o.us,
            }));
            const ours = offers.find(o => o.us);
            const ourRank = ours ? ours.rank
              : (out.horoshop.price != null ? offers.filter(o => o.price < out.horoshop.price).length + 1 : offers.length + 1);
            out.hotline = { ok: true, found: true, offers, total: h.total || offers.length, ourRank, url: h.url || "#" };
          }
        } catch (e) {}
      })(),
      (async () => {
        try {
          const prods = await getPcProducts();
          const prod = prods.find(p => skNorm(p.article) === art)
            || prods.find(p => (p.offers || []).some(o => skNorm(o.offerArt) === art));
          if (prod) {
            out.suppliers = (prod.offers || []).filter(o => Number(o.uah) > 0).map(o => ({
              sup: o.sup, label: String(o.sup || "—"), color: skSupColor(o.sup),
              uah: Math.round(Number(o.uah)), stock: !!o.stock, offerArt: o.offerArt || item.article,
            })).sort((a, b) => a.uah - b.uah);
          }
        } catch (e) {}
      })(),
    ]);
    return out;
  }

  // тост (спільний для desktop/mobile)
  function SkToast({ toast }) {
    if (!toast) return null;
    return (
      <div style={{ position: "fixed", bottom: 24, left: "50%", transform: "translateX(-50%)", zIndex: 60, display: "flex", alignItems: "center", gap: 10, padding: "12px 18px", background: "var(--bg-raised)", border: "1px solid var(--border-default)", borderRadius: 10, boxShadow: "var(--shadow-2)", animation: "skSheetUp 200ms ease" }}>
        <Icon name={toast.icon} size={17} color={toast.tone} /> <span style={{ fontSize: 13, color: "var(--fg-primary)" }}>{toast.text}</span>
      </div>
    );
  }

  // ======================= DESKTOP ===========================================

  function EditCell({ value, mono = true, align = "right", money, cur, saving, onCommit, title }) {
    const [draft, setDraft] = useState(String(value));
    const [focus, setFocus] = useState(false);
    useEffect(() => { if (!focus) setDraft(String(value)); }, [value, focus]);
    const commit = () => {
      setFocus(false);
      const n = parseFloat(String(draft).replace(",", "."));
      if (!isNaN(n) && n >= 0 && n !== value) onCommit(n);
      else setDraft(String(value));
    };
    return (
      <span style={{ position: "relative", display: "inline-flex", alignItems: "center", width: "100%", justifyContent: align === "right" ? "flex-end" : "flex-start" }}>
        <input value={draft} title={title} disabled={saving} inputMode="decimal"
          onChange={e => setDraft(e.target.value)}
          onFocus={e => { setFocus(true); e.target.select(); }}
          onBlur={commit}
          onKeyDown={e => { if (e.key === "Enter") e.currentTarget.blur(); if (e.key === "Escape") { setDraft(String(value)); e.currentTarget.blur(); } }}
          style={{
            width: "100%", boxSizing: "border-box", height: 30, padding: money ? "0 22px 0 8px" : "0 8px",
            textAlign: align, background: focus ? "var(--bg-base)" : "transparent",
            color: "var(--fg-primary)", border: `1px solid ${focus ? "var(--accent)" : "transparent"}`,
            borderRadius: 7, outline: "none", cursor: saving ? "wait" : "text",
            fontFamily: mono ? "var(--font-mono)" : "inherit", fontVariantNumeric: "tabular-nums",
            fontSize: 13, fontWeight: 600, opacity: saving ? 0.5 : 1,
            boxShadow: focus ? "0 0 0 3px var(--accent-soft)" : "none", transition: "border-color 120ms, box-shadow 120ms",
          }} />
        {money && !focus && <span style={{ position: "absolute", right: 8, color: "var(--fg-muted)", fontSize: 12, pointerEvents: "none" }}>{cur === "USD" ? "" : CUR_SYM[cur]}</span>}
        {saving && <span style={{ position: "absolute", right: 4, display: "inline-flex" }}><Icon name="loader-2" size={13} color="var(--accent)" style={{ animation: "spin .7s linear infinite" }} /></span>}
      </span>
    );
  }

  function StockFinal({ qty }) {
    const out = qty <= 0, low = qty > 0 && qty <= 5;
    const color = out ? "var(--fg-disabled)" : low ? "var(--warning)" : "var(--success)";
    return (
      <span style={{ display: "inline-flex", alignItems: "center", gap: 7, justifyContent: "flex-end", width: "100%" }}>
        <span style={{ width: 7, height: 7, borderRadius: "50%", background: color, flexShrink: 0 }} />
        <span style={{ fontFamily: "var(--font-mono)", fontVariantNumeric: "tabular-nums", fontSize: 13, fontWeight: 600, color: out ? "var(--fg-muted)" : "var(--fg-primary)" }}>{fmtInt(qty)}</span>
      </span>
    );
  }

  const SK_COLS = [
    ["article", "Артикул", 110, "left"], ["name", "Назва товару", "flex", "left"],
    ["price", "Ціна", 124, "right"], ["primary", "Первинний", 112, "right"],
    ["sold", "Продано", 96, "right"], ["stock", "Залишок", 110, "right"],
    ["sum", "Сума", 142, "right"], ["act", "", 84, "right"],
  ];
  const skCell = w => (w === "flex" ? { flex: "1 1 0", minWidth: 180 } : { flex: `0 0 ${w}px` });
  const skHead = { fontSize: 10.5, fontWeight: 600, letterSpacing: ".04em", textTransform: "uppercase", color: "var(--fg-muted)" };

  function TableHeader() {
    return (
      <div style={{ display: "flex", gap: 12, alignItems: "center", padding: "10px 24px", borderBottom: "1px solid var(--border-subtle)", background: "var(--bg-panel)", position: "sticky", top: 0, zIndex: 2 }}>
        {SK_COLS.map(([k, label, w, align]) => (
          <span key={k} style={{ ...skCell(w), ...skHead, textAlign: align }}>
            {label}{(k === "price" || k === "primary") && <Icon name="pencil" size={10} style={{ marginLeft: 4, opacity: .5, verticalAlign: "middle" }} />}
          </span>
        ))}
      </div>
    );
  }

  const skIconBtn = (on, danger) => ({
    width: 28, height: 28, border: `1px solid ${on ? (danger ? "var(--danger)" : "var(--accent)") : "var(--border-default)"}`,
    borderRadius: 7, background: on ? (danger ? "rgba(244,63,94,.14)" : "var(--accent-soft)") : "var(--bg-raised)",
    color: on ? (danger ? "var(--danger)" : "var(--accent)") : "var(--fg-secondary)",
    cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0,
  });

  function Row({ it, cur, savingField, expanded, analytics, onEdit, onToggle, onDelete }) {
    const [hover, setHover] = useState(false);
    const [confirm, setConfirm] = useState(false);
    const sum = calcSum(it), final = calcFinal(it);
    return (
      <>
        <div onMouseEnter={() => setHover(true)} onMouseLeave={() => { setHover(false); setConfirm(false); }} style={{
          display: "flex", gap: 12, alignItems: "center", padding: "5px 24px",
          borderBottom: expanded ? "1px solid var(--border-default)" : "1px solid var(--border-subtle)",
          background: expanded ? "var(--bg-hover)" : hover ? "var(--bg-hover)" : "transparent",
        }}>
          <span style={{ ...skCell(110), fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--fg-muted)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{it.article}</span>
          <span style={{ ...skCell("flex"), fontSize: 13, color: "var(--fg-primary)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }} title={it.name}>{it.name}</span>
          <span style={skCell(124)}><EditCell value={it.price} money cur={cur} align="right" saving={savingField === "price"} title="Ціна (колонка C)" onCommit={v => onEdit(it, "price", v)} /></span>
          <span style={skCell(112)}><EditCell value={it.stockPrimary} align="right" saving={savingField === "stock"} title="Первинний залишок (колонка D) — редагується" onCommit={v => onEdit(it, "stock", v)} /></span>
          <span style={{ ...skCell(96), textAlign: "right", fontFamily: "var(--font-mono)", fontVariantNumeric: "tabular-nums", fontSize: 13, color: "var(--fg-muted)" }}>{fmtInt(it.sold)}</span>
          <span style={skCell(110)}><StockFinal qty={final} /></span>
          <span style={{ ...skCell(142), textAlign: "right", fontFamily: "var(--font-mono)", fontVariantNumeric: "tabular-nums", fontSize: 13, fontWeight: 600, color: "var(--fg-secondary)" }}>{fmtMoney(sum, cur)}</span>
          <span style={{ ...skCell(84), display: "flex", justifyContent: "flex-end", alignItems: "center", gap: 6, position: "relative" }}>
            <button title="Аналітика · Hotline та постачальники" onClick={() => onToggle(it)} style={skIconBtn(expanded, false)}><Icon name="bar-chart-3" size={14} /></button>
            <button title="Видалити товар" onClick={() => setConfirm(true)} style={{ ...skIconBtn(false, true), opacity: hover || confirm ? 1 : 0.35 }}><Icon name="trash-2" size={14} /></button>
            {confirm && (
              <>
                <div onClick={() => setConfirm(false)} style={{ position: "fixed", inset: 0, zIndex: 14 }} />
                <div style={{ position: "absolute", top: "calc(100% + 6px)", right: 0, zIndex: 15, width: 232, padding: 13, background: "var(--bg-raised)", border: "1px solid var(--border-default)", borderRadius: 10, boxShadow: "var(--shadow-2)" }}>
                  <div style={{ fontSize: 12.5, fontWeight: 600, color: "var(--fg-primary)", marginBottom: 3 }}>Видалити рядок?</div>
                  <div style={{ fontSize: 11.5, color: "var(--fg-muted)", marginBottom: 11, lineHeight: 1.4 }}>«{it.name}» зникне з таблиці складу назавжди.</div>
                  <div style={{ display: "flex", gap: 7 }}>
                    <button onClick={() => setConfirm(false)} style={{ flex: 1, height: 30, border: "1px solid var(--border-default)", borderRadius: 7, background: "transparent", color: "var(--fg-secondary)", fontFamily: "inherit", fontSize: 12, cursor: "pointer" }}>Скасувати</button>
                    <button onClick={() => { setConfirm(false); onDelete(it); }} style={{ flex: 1, height: 30, border: 0, borderRadius: 7, background: "rgba(244,63,94,.16)", color: "var(--danger)", fontFamily: "inherit", fontSize: 12, fontWeight: 600, cursor: "pointer" }}>Видалити</button>
                  </div>
                </div>
              </>
            )}
          </span>
        </div>
        {expanded && <AnalyticsPanel data={analytics} item={it} />}
      </>
    );
  }

  function WarehouseSwitch({ list, active, onPick }) {
    return (
      <div style={{ display: "flex", gap: 3, padding: 3, background: "var(--bg-base)", borderRadius: 10, border: "1px solid var(--border-subtle)" }}>
        {list.map(w => {
          const on = active === w.key;
          return (
            <button key={w.key} onClick={() => onPick(w.key)} style={{
              display: "inline-flex", alignItems: "center", gap: 8, height: 32, padding: "0 14px", border: 0, borderRadius: 7,
              background: on ? "var(--bg-raised)" : "transparent", color: on ? "var(--fg-primary)" : "var(--fg-muted)",
              fontSize: 13, fontWeight: 600, cursor: "pointer", fontFamily: "inherit", boxShadow: on ? "var(--shadow-1)" : "none",
            }}>
              <Icon name="warehouse" size={15} /> {w.label}
              <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, fontWeight: 700, color: on ? "var(--accent)" : "var(--fg-disabled)" }}>{CUR_SYM[w.currency]}</span>
            </button>
          );
        })}
      </div>
    );
  }

  function AnHead({ icon, title, right }) {
    return (
      <div style={{ display: "flex", alignItems: "center", gap: 7, marginBottom: 10 }}>
        <Icon name={icon} size={14} color="var(--fg-muted)" />
        <span style={{ fontSize: 11, fontWeight: 600, letterSpacing: ".05em", textTransform: "uppercase", color: "var(--fg-muted)" }}>{title}</span>
        <div style={{ flex: 1 }} />{right}
      </div>
    );
  }
  const anCard = { background: "var(--bg-raised)", border: "1px solid var(--border-subtle)", borderRadius: 10, padding: 14, display: "flex", flexDirection: "column", minWidth: 0 };

  function AnalyticsPanel({ data, item }) {
    if (!data) {
      return (
        <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "22px 24px", background: "var(--bg-base)", borderBottom: "1px solid var(--border-default)", color: "var(--fg-muted)" }}>
          <Icon name="loader-2" size={16} color="var(--accent)" style={{ animation: "spin .8s linear infinite" }} />
          <span style={{ fontSize: 12.5 }}>Аналітика по «{item.name}»…</span>
        </div>
      );
    }
    const { horoshop, hotline, suppliers } = data;
    const cheapest = suppliers[0];
    return (
      <div style={{ display: "grid", gridTemplateColumns: "260px 1fr 1fr", gap: 12, padding: "16px 24px", background: "var(--bg-base)", borderBottom: "1px solid var(--border-default)", boxShadow: "inset 3px 0 0 var(--accent)" }}>
        <div style={anCard}>
          <AnHead icon="globe" title="На сайті · Horoshop" />
          <div style={{ fontFamily: "var(--font-mono)", fontVariantNumeric: "tabular-nums", fontSize: 22, fontWeight: 700, color: "var(--fg-primary)" }}>{fmtUAH(horoshop.price)}</div>
          <div style={{ fontSize: 11.5, color: "var(--fg-muted)", marginTop: 3 }}>роздрібна ціна продажу</div>
          {horoshop.url && horoshop.url !== "#" && <a href={horoshop.url} target="_blank" rel="noreferrer" style={{ marginTop: 12, fontSize: 12, color: "var(--accent)", textDecoration: "none", display: "inline-flex", alignItems: "center", gap: 5 }}><Icon name="external-link" size={13} /> Картка товару</a>}
        </div>
        <div style={anCard}>
          <AnHead icon="bar-chart-3" title="Hotline" right={hotline.found && hotline.url && hotline.url !== "#"
            ? <a href={hotline.url} target="_blank" rel="noreferrer" style={{ fontSize: 11.5, color: "var(--accent)", textDecoration: "none", display: "inline-flex", alignItems: "center", gap: 4 }}><Icon name="external-link" size={12} /> всі {hotline.total}</a> : null} />
          {!hotline.found ? (
            <div style={{ display: "flex", alignItems: "center", gap: 8, color: "var(--fg-muted)", fontSize: 12.5, padding: "8px 0" }}><Icon name="search-x" size={15} /> На Hotline не знайдено</div>
          ) : (
            <>
              <div style={{ display: "flex", alignItems: "baseline", gap: 10, marginBottom: 10, flexWrap: "wrap" }}>
                <span style={{ fontSize: 11.5, color: "var(--fg-muted)" }}>від</span>
                <span style={{ fontFamily: "var(--font-mono)", fontVariantNumeric: "tabular-nums", fontSize: 18, fontWeight: 700, whiteSpace: "nowrap", color: "var(--success)" }}>{fmtUAH(hotline.offers[0] && hotline.offers[0].price)}</span>
                <span style={{ fontSize: 11.5, color: "var(--fg-muted)" }}>· наша позиція</span>
                <span style={{ fontFamily: "var(--font-mono)", fontSize: 12.5, fontWeight: 700, color: hotline.ourRank <= 3 ? "var(--success)" : hotline.ourRank <= 6 ? "var(--warning)" : "var(--danger)" }}>#{hotline.ourRank}</span>
              </div>
              <div style={{ display: "flex", flexDirection: "column", gap: 1, maxHeight: 240, overflowY: "auto" }}>
                {hotline.offers.map((o, i) => (
                  <div key={i} style={{ display: "flex", alignItems: "center", gap: 10, padding: "5px 6px", borderRadius: 6, borderTop: o.rank === 1 ? "none" : "1px solid var(--border-subtle)", background: o.us ? "var(--accent-soft)" : "transparent" }}>
                    <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: o.us ? "var(--accent)" : "var(--fg-disabled)", fontWeight: o.us ? 700 : 400, width: 24 }}>#{o.rank}</span>
                    <span style={{ flex: 1, fontSize: 12.5, color: o.us ? "var(--accent)" : "var(--fg-secondary)", fontWeight: o.us ? 700 : 400, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{o.shop}{o.us ? " · ми" : ""}</span>
                    <span style={{ fontFamily: "var(--font-mono)", fontVariantNumeric: "tabular-nums", fontSize: 12.5, fontWeight: 600, whiteSpace: "nowrap", color: o.rank === 1 ? "var(--success)" : o.us ? "var(--accent)" : "var(--fg-primary)" }}>{fmtUAH(o.price)}</span>
                  </div>
                ))}
              </div>
            </>
          )}
        </div>
        <div style={anCard}>
          <AnHead icon="truck" title={`У постачальників · ${suppliers.length}`} />
          {suppliers.length === 0 ? (
            <div style={{ display: "flex", alignItems: "center", gap: 8, color: "var(--fg-muted)", fontSize: 12.5, padding: "8px 0" }}><Icon name="search-x" size={15} /> У постачальників не знайдено</div>
          ) : (
            <div style={{ display: "flex", flexDirection: "column", gap: 7 }}>
              {suppliers.map((s, i) => {
                const best = s === cheapest;
                return (
                  <div key={i} style={{ display: "flex", alignItems: "center", gap: 10, padding: "7px 9px", borderRadius: 8, background: best ? "rgba(16,185,129,.08)" : "var(--bg-base)", border: `1px solid ${best ? "rgba(16,185,129,.26)" : "var(--border-subtle)"}` }}>
                    <span style={{ display: "inline-flex", alignItems: "center", gap: 6, minWidth: 0 }}>
                      <span style={{ width: 7, height: 7, borderRadius: "50%", background: s.color, flexShrink: 0 }} />
                      <span style={{ fontSize: 12.5, fontWeight: 600, color: s.color, whiteSpace: "nowrap" }}>{s.label}</span>
                    </span>
                    <span style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, color: "var(--fg-disabled)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{s.offerArt}</span>
                    <div style={{ flex: 1 }} />
                    <span style={{ display: "inline-flex", alignItems: "center", gap: 5, fontSize: 11, color: s.stock ? "var(--fg-muted)" : "var(--fg-disabled)" }}>
                      <span style={{ width: 6, height: 6, borderRadius: "50%", background: s.stock ? "var(--success)" : "var(--fg-disabled)" }} />{s.stock ? "є" : "немає"}
                    </span>
                    <span style={{ fontFamily: "var(--font-mono)", fontVariantNumeric: "tabular-nums", fontSize: 13, fontWeight: 700, whiteSpace: "nowrap", color: best ? "var(--success)" : "var(--fg-primary)", minWidth: 64, textAlign: "right" }}>{fmtUAH(s.uah)}</span>
                  </div>
                );
              })}
            </div>
          )}
        </div>
      </div>
    );
  }

  function AddProductModal({ wh, onClose, onAdd }) {
    const cur = wh.currency;
    const [form, setForm] = useState({ article: "", name: "", price: "", stock: "" });
    const [busy, setBusy] = useState(false);
    const set = (k, v) => setForm(f => ({ ...f, [k]: v }));
    const valid = form.article.trim() && form.name.trim();
    const submit = () => { if (!valid || busy) return; setBusy(true); onAdd(form, () => setBusy(false)); };
    const field = (label, key, opts = {}) => (
      <label style={{ display: "flex", flexDirection: "column", gap: 6 }}>
        <span style={{ fontSize: 11.5, color: "var(--fg-muted)" }}>{label}{opts.req && <span style={{ color: "var(--danger)" }}> *</span>}</span>
        <div style={{ position: "relative" }}>
          <input value={form[key]} onChange={e => set(key, e.target.value)} inputMode={opts.num ? "decimal" : undefined} placeholder={opts.ph} autoFocus={opts.autoFocus}
            style={{ width: "100%", boxSizing: "border-box", height: 40, padding: opts.sym ? "0 26px 0 12px" : "0 12px", background: "var(--bg-base)", color: "var(--fg-primary)", border: "1px solid var(--border-default)", borderRadius: 9, fontSize: 13.5, outline: "none", fontFamily: opts.num ? "var(--font-mono)" : "inherit", fontWeight: opts.num ? 600 : 400 }}
            onFocus={e => e.target.style.borderColor = "var(--accent)"} onBlur={e => e.target.style.borderColor = "var(--border-default)"}
            onKeyDown={e => { if (e.key === "Enter" && key === "stock") submit(); }} />
          {opts.sym && <span style={{ position: "absolute", right: 12, top: "50%", transform: "translateY(-50%)", color: "var(--fg-muted)", fontSize: 13, pointerEvents: "none" }}>{opts.sym}</span>}
        </div>
      </label>
    );
    return (
      <div style={{ position: "fixed", inset: 0, zIndex: 50, display: "flex", alignItems: "center", justifyContent: "center", background: "rgba(0,0,0,.55)", animation: "skFade 140ms ease" }} onClick={onClose}>
        <div onClick={e => e.stopPropagation()} style={{ width: 460, maxWidth: "92vw", background: "var(--bg-panel)", border: "1px solid var(--border-default)", borderRadius: 14, boxShadow: "var(--shadow-2)", overflow: "hidden", animation: "skSheetUp 180ms ease" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "16px 18px", borderBottom: "1px solid var(--border-subtle)" }}>
            <div style={{ width: 32, height: 32, borderRadius: 9, background: "var(--accent-soft)", display: "flex", alignItems: "center", justifyContent: "center" }}><Icon name="plus" size={17} color="var(--accent)" /></div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 15, fontWeight: 600, color: "var(--fg-primary)" }}>Новий товар</div>
              <div style={{ fontSize: 11.5, color: "var(--fg-muted)" }}>Склад «{wh.label}» · ціна у {CUR_LABEL[cur]}</div>
            </div>
            <button onClick={onClose} style={{ width: 32, height: 32, border: 0, background: "transparent", color: "var(--fg-secondary)", borderRadius: 6, cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center" }}><Icon name="x" size={18} /></button>
          </div>
          <div style={{ padding: 18, display: "flex", flexDirection: "column", gap: 14 }}>
            {field("Артикул", "article", { req: true, ph: "DS-1200", autoFocus: true })}
            {field("Назва товару", "name", { req: true, ph: "iPhone 15 Pro 256GB…" })}
            <div style={{ display: "flex", gap: 12 }}>
              <div style={{ flex: 1 }}>{field("Ціна", "price", { num: true, ph: "0", sym: cur === "USD" ? "$" : "₴" })}</div>
              <div style={{ flex: 1 }}>{field("Первинний залишок", "stock", { num: true, ph: "0" })}</div>
            </div>
            <div style={{ display: "flex", gap: 8, alignItems: "center", fontSize: 11.5, color: "var(--fg-muted)", padding: "2px 0" }}>
              <Icon name="info" size={13} /> Запис у A,B,C,D · Продано (E) — 0 · Залишок/Сума — формули
            </div>
          </div>
          <div style={{ display: "flex", gap: 10, padding: "14px 18px", borderTop: "1px solid var(--border-subtle)" }}>
            <Button variant="ghost" onClick={onClose} style={{ flex: "0 0 auto" }}>Скасувати</Button>
            <div style={{ flex: 1 }} />
            <Button variant="primary" leftIcon={busy ? "loader-2" : "plus"} onClick={submit} disabled={!valid || busy}>{busy ? "Додаємо…" : "Додати товар"}</Button>
          </div>
        </div>
      </div>
    );
  }

  function SkladDesktop() {
    const [whList, setWhList] = useState([]);
    const [active, setActive] = useState(null);
    const [items, setItems] = useState([]);
    const [loading, setLoading] = useState(true);
    const [query, setQuery] = useState("");
    const [saving, setSaving] = useState(null);
    const [toast, setToast] = useState(null);
    const [expanded, setExpanded] = useState(null);
    const [analytics, setAnalytics] = useState({});
    const [addOpen, setAddOpen] = useState(false);

    const wh = whList.find(w => w.key === active);
    const cur = (wh && wh.currency) || "UAH";

    const showToast = (text, icon = "check-circle", tone = "var(--success)") => { setToast({ text, icon, tone }); setTimeout(() => setToast(null), 2600); };

    const loadItems = async (key) => {
      setLoading(true);
      try { setItems(await API.warehouseItems(key)); }
      catch (e) { setItems([]); showToast(e.message || "Помилка завантаження", "alert-triangle", "var(--danger)"); }
      finally { setLoading(false); }
    };

    useEffect(() => {
      let alive = true;
      API.warehouses().then(list => {
        if (!alive) return;
        setWhList(list);
        const first = list[0] && list[0].key;
        if (first) { setActive(first); loadItems(first); } else setLoading(false);
      }).catch(e => { if (alive) { setLoading(false); showToast(e.message || "Помилка", "alert-triangle", "var(--danger)"); } });
      return () => { alive = false; };
    }, []);

    const pickWh = key => { if (key === active) return; setActive(key); setQuery(""); setExpanded(null); setAnalytics({}); loadItems(key); };

    const toggleAnalytics = it => {
      if (expanded === it.row) { setExpanded(null); return; }
      setExpanded(it.row);
      if (analytics[it.row] === undefined) loadAnalytics(it, active).then(data => setAnalytics(a => ({ ...a, [it.row]: data })));
    };

    const onEdit = async (it, field, value) => {
      setSaving(`${it.row}:${field}`);
      try {
        const updated = await API.warehouseUpdate(active, { row: it.row, field, value });
        setItems(list => list.map(x => x.row === it.row ? updated : x));
        showToast(field === "price" ? `Ціну оновлено · ${it.article} · ${fmtMoney(value, cur)}` : `Залишок оновлено · ${it.article} · первинний ${fmtInt(value)}`);
      } catch (e) { showToast(e.message || "Помилка збереження", "alert-triangle", "var(--danger)"); }
      finally { setSaving(null); }
    };

    const onAdd = async (form, done) => {
      try {
        const it = await API.warehouseAdd(active, { article: form.article.trim(), name: form.name.trim(), price: parseFloat(String(form.price).replace(",", ".")) || 0, stock: parseInt(form.stock, 10) || 0 });
        setItems(list => [it, ...list]); setAddOpen(false);
        showToast(`Додано · ${it.article} · ${String(it.name).slice(0, 28)}`);
      } catch (e) { showToast(e.message || "Помилка додавання", "alert-triangle", "var(--danger)"); }
      finally { done && done(); }
    };

    const onDelete = async it => {
      const snapshot = items;
      setItems(list => list.filter(x => x.row !== it.row));
      if (expanded === it.row) setExpanded(null);
      try {
        await API.warehouseDelete(active, it.row);
        showToast(`Товар видалено · ${it.article}`, "trash-2", "var(--danger)");
        setItems(await API.warehouseItems(active)); // рядки нижче зсунулись
      } catch (e) { setItems(snapshot); showToast(e.message || "Помилка видалення", "alert-triangle", "var(--danger)"); }
    };

    const realItems = useMemo(() => items.filter(it => !it.isCategory), [items]);
    const list = useMemo(() => {
      const q = query.trim().toLowerCase();
      if (!q) return items;
      return items.filter(it => !it.isCategory && ((it.name || "").toLowerCase().includes(q) || (it.article || "").toLowerCase().includes(q)));
    }, [items, query]);
    const totalSum = useMemo(() => realItems.reduce((s, it) => s + calcSum(it), 0), [realItems]);

    return (
      <div style={{ flex: 1, minHeight: 0, display: "flex", flexDirection: "column", background: "var(--bg-base)", color: "var(--fg-primary)", overflow: "hidden" }}>
        <div style={{ height: 56, display: "flex", alignItems: "center", padding: "0 24px", gap: 16, borderBottom: "1px solid var(--border-subtle)", background: "var(--bg-panel)", flexShrink: 0 }}>
          <h1 style={{ fontSize: 16, fontWeight: 600, color: "var(--fg-primary)", margin: 0 }}>Склад</h1>
          <span style={{ fontSize: 12, color: "var(--fg-muted)" }}>Власні склади</span>
          {whList.length > 0 && <WarehouseSwitch list={whList} active={active} onPick={pickWh} />}
          <div style={{ flex: 1 }} />
          <span style={{ fontSize: 11.5, color: "var(--fg-muted)", display: "inline-flex", alignItems: "center", gap: 5 }}><Icon name="info" size={12} /> Продано — з бота · Залишок/Сума — формули</span>
          <Button variant="primary" leftIcon="plus" onClick={() => setAddOpen(true)} disabled={!active}>Додати товар</Button>
        </div>

        <div style={{ display: "flex", alignItems: "center", gap: 14, padding: "12px 24px", borderBottom: "1px solid var(--border-subtle)" }}>
          <div style={{ position: "relative", flex: "0 0 380px" }}>
            <Icon name="search" size={15} style={{ position: "absolute", left: 13, top: "50%", transform: "translateY(-50%)", color: "var(--accent)" }} />
            <input value={query} onChange={e => setQuery(e.target.value)} placeholder="Пошук — назва або артикул…" style={{ width: "100%", height: 38, boxSizing: "border-box", padding: "0 12px 0 38px", background: "var(--bg-panel)", color: "var(--fg-primary)", border: "1px solid var(--border-default)", borderRadius: 9, fontSize: 13, outline: "none", fontFamily: "inherit" }}
              onFocus={e => e.target.style.borderColor = "var(--accent)"} onBlur={e => e.target.style.borderColor = "var(--border-default)"} />
          </div>
          <div style={{ flex: 1 }} />
          <div style={{ display: "flex", alignItems: "center", gap: 18, padding: "8px 16px", background: "var(--bg-panel)", border: "1px solid var(--border-subtle)", borderRadius: 10 }}>
            <div style={{ display: "flex", flexDirection: "column", alignItems: "flex-start" }}>
              <span style={{ fontSize: 10.5, color: "var(--fg-muted)", letterSpacing: ".04em", textTransform: "uppercase" }}>Товарів</span>
              <span style={{ fontFamily: "var(--font-mono)", fontVariantNumeric: "tabular-nums", fontSize: 16, fontWeight: 700, color: "var(--fg-primary)" }}>{fmtInt(realItems.length)}</span>
            </div>
            <div style={{ width: 1, height: 30, background: "var(--border-default)" }} />
            <div style={{ display: "flex", flexDirection: "column", alignItems: "flex-start" }}>
              <span style={{ fontSize: 10.5, color: "var(--fg-muted)", letterSpacing: ".04em", textTransform: "uppercase" }}>Сума на складі · {CUR_LABEL[cur]}</span>
              <span style={{ fontFamily: "var(--font-mono)", fontVariantNumeric: "tabular-nums", fontSize: 16, fontWeight: 700, color: "var(--accent)" }}>{fmtMoney(totalSum, cur)}</span>
            </div>
          </div>
        </div>

        <div style={{ flex: 1, minHeight: 0, display: "flex", flexDirection: "column" }}>
          <div style={{ flex: 1, overflow: "auto" }}>
            <TableHeader />
            {loading ? (
              <div style={{ display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", padding: "80px 24px", gap: 14, color: "var(--fg-muted)" }}>
                <Icon name="loader-2" size={26} color="var(--accent)" style={{ animation: "spin .8s linear infinite" }} />
                <span style={{ fontSize: 13 }}>Завантаження залишків{wh ? ` · ${wh.label}` : ""}…</span>
              </div>
            ) : list.length === 0 ? (
              <div style={{ display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", padding: "72px 24px", gap: 14 }}>
                <div style={{ width: 56, height: 56, borderRadius: 14, background: "var(--bg-panel)", border: "1px solid var(--border-subtle)", display: "flex", alignItems: "center", justifyContent: "center" }}><Icon name="search-x" size={26} color="var(--fg-muted)" /></div>
                <div style={{ textAlign: "center" }}>
                  <div style={{ fontSize: 14, fontWeight: 600, color: "var(--fg-primary)" }}>{query ? `Нічого не знайдено за «${query}»` : "Склад порожній"}</div>
                  <div style={{ fontSize: 12.5, color: "var(--fg-muted)", marginTop: 5 }}>{query ? "Спробуйте інший запит" : "Додайте перший товар"}</div>
                </div>
                {query && <Button variant="secondary" leftIcon="rotate-ccw" onClick={() => setQuery("")}>Скинути пошук</Button>}
              </div>
            ) : list.map(it => it.isCategory ? (
              <div key={it.row} style={{ display: "flex", alignItems: "center", gap: 8, padding: "9px 24px", background: "var(--bg-panel)", borderBottom: "1px solid var(--border-subtle)" }}>
                <Icon name="folder" size={13} color="var(--fg-muted)" />
                <span style={{ fontSize: 11.5, fontWeight: 700, letterSpacing: ".04em", textTransform: "uppercase", color: "var(--fg-secondary)" }}>{it.name}</span>
              </div>
            ) : (
              <Row key={it.row} it={it} cur={cur}
                savingField={saving && saving.startsWith(it.row + ":") ? saving.split(":")[1] : null}
                expanded={expanded === it.row} analytics={analytics[it.row]}
                onEdit={onEdit} onToggle={toggleAnalytics} onDelete={onDelete} />
            ))}
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 8, padding: "8px 24px", borderTop: "1px solid var(--border-subtle)", fontSize: 11.5, color: "var(--fg-muted)", background: "var(--bg-panel)" }}>
            <Icon name="warehouse" size={13} /> {wh ? wh.label : "—"} · {fmtInt(list.length)} {list.length === 1 ? "позиція" : "позицій"}{query ? ` з ${realItems.length}` : ""}
            <div style={{ flex: 1 }} />
            <span style={{ display: "inline-flex", alignItems: "center", gap: 5 }}><Icon name="pencil" size={11} /> Ціна та Первинний — редагуються · Enter або клік поза полем</span>
          </div>
        </div>

        <SkToast toast={toast} />
        {addOpen && wh && <AddProductModal wh={wh} onClose={() => setAddOpen(false)} onAdd={onAdd} />}
      </div>
    );
  }

  // ======================= MOBILE ============================================

  function FieldEdit({ label, value, money, cur, saving, onCommit }) {
    const [draft, setDraft] = useState(String(value));
    const [focus, setFocus] = useState(false);
    useEffect(() => { if (!focus) setDraft(String(value)); }, [value, focus]);
    const commit = () => {
      setFocus(false);
      const n = parseFloat(String(draft).replace(",", "."));
      if (!isNaN(n) && n >= 0 && n !== value) onCommit(n); else setDraft(String(value));
    };
    return (
      <label style={{ display: "flex", flexDirection: "column", gap: 4, flex: 1, minWidth: 0 }}>
        <span style={{ fontSize: 10, fontWeight: 600, letterSpacing: ".04em", textTransform: "uppercase", color: "var(--accent)", display: "inline-flex", alignItems: "center", gap: 3 }}>{label} <Icon name="pencil" size={9} style={{ opacity: .7 }} /></span>
        <div style={{ position: "relative" }}>
          <input value={draft} disabled={saving} inputMode="decimal"
            onChange={e => setDraft(e.target.value)} onFocus={e => { setFocus(true); e.target.select(); }} onBlur={commit}
            onKeyDown={e => { if (e.key === "Enter") e.currentTarget.blur(); if (e.key === "Escape") { setDraft(String(value)); e.currentTarget.blur(); } }}
            style={{ width: "100%", boxSizing: "border-box", height: 44, padding: money && cur !== "USD" ? "0 26px 0 12px" : "0 12px", background: "var(--bg-base)", color: "var(--fg-primary)", border: `1px solid ${focus ? "var(--accent)" : "var(--border-default)"}`, borderRadius: 10, outline: "none", fontFamily: "var(--font-mono)", fontVariantNumeric: "tabular-nums", fontSize: 15, fontWeight: 700, opacity: saving ? 0.5 : 1, boxShadow: focus ? "0 0 0 3px var(--accent-soft)" : "none" }} />
          {money && cur !== "USD" && <span style={{ position: "absolute", right: 12, top: "50%", transform: "translateY(-50%)", color: "var(--fg-muted)", fontSize: 13, pointerEvents: "none" }}>{CUR_SYM[cur]}</span>}
          {saving && <span style={{ position: "absolute", right: 8, top: "50%", transform: "translateY(-50%)" }}><Icon name="loader-2" size={14} color="var(--accent)" style={{ animation: "spin .7s linear infinite" }} /></span>}
        </div>
      </label>
    );
  }
  function FieldRead({ label, value, color }) {
    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 4, flex: 1, minWidth: 0 }}>
        <span style={{ fontSize: 10, fontWeight: 600, letterSpacing: ".04em", textTransform: "uppercase", color: "var(--fg-muted)" }}>{label}</span>
        <div style={{ height: 44, display: "flex", alignItems: "center", padding: "0 4px", fontFamily: "var(--font-mono)", fontVariantNumeric: "tabular-nums", fontSize: 15, fontWeight: 700, color: color || "var(--fg-secondary)" }}>{value}</div>
      </div>
    );
  }
  function ItemCardM({ it, cur, savingField, onEdit, onAnalytics, onDelete }) {
    const final = calcFinal(it), sum = calcSum(it);
    const out = final <= 0, low = final > 0 && final <= 5;
    const dotColor = out ? "var(--fg-disabled)" : low ? "var(--warning)" : "var(--success)";
    return (
      <div style={{ padding: 14, borderRadius: 14, background: "var(--bg-panel)", border: "1px solid var(--border-subtle)", display: "flex", flexDirection: "column", gap: 12 }}>
        <div style={{ display: "flex", alignItems: "flex-start", gap: 10 }}>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 14, fontWeight: 600, color: "var(--fg-primary)", lineHeight: 1.3, display: "-webkit-box", WebkitLineClamp: 2, WebkitBoxOrient: "vertical", overflow: "hidden" }}>{it.name}</div>
            <div style={{ fontFamily: "var(--font-mono)", fontSize: 11.5, color: "var(--fg-muted)", marginTop: 4 }}>{it.article}</div>
          </div>
          <div style={{ display: "inline-flex", alignItems: "center", gap: 6, height: 26, padding: "0 10px", borderRadius: 999, background: "var(--bg-base)", border: "1px solid var(--border-subtle)", flexShrink: 0 }}>
            <span style={{ width: 7, height: 7, borderRadius: "50%", background: dotColor }} />
            <span style={{ fontFamily: "var(--font-mono)", fontSize: 12.5, fontWeight: 700, color: out ? "var(--fg-muted)" : "var(--fg-primary)" }}>{fmtInt(final)}</span>
            <span style={{ fontSize: 11, color: "var(--fg-muted)" }}>залишок</span>
          </div>
        </div>
        <div style={{ display: "flex", gap: 10 }}>
          <FieldEdit label="Ціна" value={it.price} money cur={cur} saving={savingField === "price"} onCommit={v => onEdit(it, "price", v)} />
          <FieldEdit label="Первинний" value={it.stockPrimary} saving={savingField === "stock"} onCommit={v => onEdit(it, "stock", v)} />
        </div>
        <div style={{ display: "flex", gap: 10, alignItems: "center", paddingTop: 2, borderTop: "1px solid var(--border-subtle)" }}>
          <FieldRead label="Продано" value={fmtInt(it.sold)} />
          <div style={{ width: 1, height: 30, background: "var(--border-subtle)" }} />
          <FieldRead label={`Сума · ${CUR_LABEL[cur]}`} value={fmtMoney(sum, cur)} color="var(--fg-primary)" />
        </div>
        <div style={{ display: "flex", gap: 8 }}>
          <Button variant="secondary" size="sm" leftIcon="bar-chart-3" onClick={() => onAnalytics(it)} style={{ flex: 1, height: 38 }}>Аналітика</Button>
          <button onClick={() => onDelete(it)} aria-label="Видалити" style={{ width: 44, height: 38, flexShrink: 0, border: "1px solid rgba(244,63,94,.3)", borderRadius: 10, background: "rgba(244,63,94,.1)", color: "var(--danger)", cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center" }}><Icon name="trash-2" size={16} /></button>
        </div>
      </div>
    );
  }
  function WarehouseSwitchM({ list, active, onPick }) {
    return (
      <div style={{ display: "flex", gap: 3, padding: 3, background: "var(--bg-panel)", borderRadius: 12, border: "1px solid var(--border-subtle)" }}>
        {list.map(w => {
          const on = active === w.key;
          return (
            <button key={w.key} onClick={() => onPick(w.key)} style={{ flex: 1, display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 7, height: 40, border: 0, borderRadius: 9, background: on ? "var(--bg-raised)" : "transparent", color: on ? "var(--fg-primary)" : "var(--fg-muted)", fontSize: 13.5, fontWeight: 600, cursor: "pointer", fontFamily: "inherit", boxShadow: on ? "var(--shadow-1)" : "none" }}>
              <Icon name="warehouse" size={15} /> {w.label}
              <span style={{ fontFamily: "var(--font-mono)", fontSize: 12, fontWeight: 700, color: on ? "var(--accent)" : "var(--fg-disabled)" }}>{CUR_SYM[w.currency]}</span>
            </button>
          );
        })}
      </div>
    );
  }
  function BottomSheet({ onClose, heightPct = 90, children }) {
    const [drag, setDrag] = useState(0);
    const start = useRef(null);
    const onDown = e => { start.current = (e.touches ? e.touches[0].clientY : e.clientY); };
    const onMove = e => { if (start.current == null) return; const y = (e.touches ? e.touches[0].clientY : e.clientY); setDrag(Math.max(0, y - start.current)); };
    const onUp = () => { if (drag > 110) onClose(); setDrag(0); start.current = null; };
    return (
      <div style={{ position: "fixed", inset: 0, zIndex: 40, display: "flex", flexDirection: "column", justifyContent: "flex-end" }}>
        <div onClick={onClose} style={{ position: "absolute", inset: 0, background: "rgba(0,0,0,.6)", animation: "skFadeM 160ms" }} />
        <div style={{ position: "relative", height: heightPct === "auto" ? "auto" : `${heightPct}%`, maxHeight: "94%", background: "var(--bg-panel)", borderTopLeftRadius: 18, borderTopRightRadius: 18, borderTop: "1px solid var(--border-default)", display: "flex", flexDirection: "column", overflow: "hidden", transform: `translateY(${drag}px)`, transition: start.current == null ? "transform 200ms cubic-bezier(.2,0,0,1)" : "none", animation: "skSheetUpM 240ms cubic-bezier(.2,0,0,1)" }}>
          <div onMouseDown={onDown} onMouseMove={onMove} onMouseUp={onUp} onTouchStart={onDown} onTouchMove={onMove} onTouchEnd={onUp} style={{ padding: "10px 0 6px", cursor: "grab", flexShrink: 0 }}>
            <div style={{ width: 36, height: 4, borderRadius: 2, background: "var(--border-strong)", margin: "0 auto" }} />
          </div>
          {children}
        </div>
      </div>
    );
  }
  function SheetHead({ title, sub, onClose }) {
    return (
      <div style={{ display: "flex", alignItems: "center", gap: 8, padding: "2px 12px 12px 16px", borderBottom: "1px solid var(--border-subtle)", flexShrink: 0 }}>
        <div style={{ flex: 1, minWidth: 0 }}>
          <h3 style={{ fontSize: 15, fontWeight: 600, margin: 0, color: "var(--fg-primary)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{title}</h3>
          {sub && <div style={{ fontSize: 11.5, color: "var(--fg-muted)", marginTop: 2 }}>{sub}</div>}
        </div>
        <button onClick={onClose} style={{ width: 32, height: 32, border: 0, background: "transparent", color: "var(--fg-secondary)", borderRadius: 6, cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center" }}><Icon name="x" size={18} /></button>
      </div>
    );
  }
  const mAnLabel = { fontSize: 10.5, fontWeight: 600, letterSpacing: ".05em", textTransform: "uppercase", color: "var(--fg-muted)", display: "flex", alignItems: "center", gap: 6, marginBottom: 10 };
  function AnalyticsSheet({ item, data, onClose }) {
    return (
      <BottomSheet onClose={onClose} heightPct={86}>
        <SheetHead title={item.name} sub={`Арт. ${item.article} · аналітика ринку`} onClose={onClose} />
        <div className="no-bar" style={{ flex: 1, overflow: "auto", padding: 16, display: "flex", flexDirection: "column", gap: 14 }}>
          {!data ? (
            <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 12, padding: "48px 0", color: "var(--fg-muted)" }}>
              <Icon name="loader-2" size={22} color="var(--accent)" style={{ animation: "spin .8s linear infinite" }} />
              <span style={{ fontSize: 12.5 }}>Завантаження аналітики…</span>
            </div>
          ) : (
            <>
              <div style={{ background: "var(--bg-base)", border: "1px solid var(--border-subtle)", borderRadius: 12, padding: 14 }}>
                <div style={mAnLabel}><Icon name="globe" size={13} /> На сайті · Horoshop</div>
                <div style={{ display: "flex", alignItems: "baseline", gap: 10 }}>
                  <span style={{ fontFamily: "var(--font-mono)", fontVariantNumeric: "tabular-nums", fontSize: 22, fontWeight: 700, color: "var(--fg-primary)" }}>{fmtUAH(data.horoshop.price)}</span>
                  <span style={{ fontSize: 11.5, color: "var(--fg-muted)" }}>роздрібна</span>
                </div>
              </div>
              <div style={{ background: "var(--bg-base)", border: "1px solid var(--border-subtle)", borderRadius: 12, padding: 14 }}>
                <div style={{ ...mAnLabel, justifyContent: "space-between" }}>
                  <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}><Icon name="bar-chart-3" size={13} /> Hotline</span>
                  {data.hotline.found && <span style={{ color: "var(--accent)", fontSize: 10.5 }}>всі {data.hotline.total}</span>}
                </div>
                {!data.hotline.found ? (
                  <div style={{ display: "flex", alignItems: "center", gap: 8, color: "var(--fg-muted)", fontSize: 12.5 }}><Icon name="search-x" size={15} /> На Hotline не знайдено</div>
                ) : (
                  <>
                    <div style={{ display: "flex", alignItems: "baseline", gap: 8, marginBottom: 10, flexWrap: "wrap" }}>
                      <span style={{ fontSize: 11.5, color: "var(--fg-muted)" }}>від</span>
                      <span style={{ fontFamily: "var(--font-mono)", fontVariantNumeric: "tabular-nums", fontSize: 17, fontWeight: 700, whiteSpace: "nowrap", color: "var(--success)" }}>{fmtUAH(data.hotline.offers[0] && data.hotline.offers[0].price)}</span>
                      <span style={{ fontSize: 11.5, color: "var(--fg-muted)" }}>· наша</span>
                      <span style={{ fontFamily: "var(--font-mono)", fontSize: 12.5, fontWeight: 700, color: data.hotline.ourRank <= 3 ? "var(--success)" : data.hotline.ourRank <= 6 ? "var(--warning)" : "var(--danger)" }}>#{data.hotline.ourRank}</span>
                    </div>
                    <div style={{ display: "flex", flexDirection: "column", gap: 1, maxHeight: 300, overflowY: "auto" }}>
                      {data.hotline.offers.map((o, i) => (
                        <div key={i} style={{ display: "flex", alignItems: "center", gap: 10, padding: "6px 6px", borderRadius: 6, borderTop: o.rank === 1 ? "none" : "1px solid var(--border-subtle)", background: o.us ? "var(--accent-soft)" : "transparent" }}>
                          <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: o.us ? "var(--accent)" : "var(--fg-disabled)", fontWeight: o.us ? 700 : 400, width: 24 }}>#{o.rank}</span>
                          <span style={{ flex: 1, fontSize: 13, color: o.us ? "var(--accent)" : "var(--fg-secondary)", fontWeight: o.us ? 700 : 400, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{o.shop}{o.us ? " · ми" : ""}</span>
                          <span style={{ fontFamily: "var(--font-mono)", fontVariantNumeric: "tabular-nums", fontSize: 13, fontWeight: 600, whiteSpace: "nowrap", color: o.rank === 1 ? "var(--success)" : o.us ? "var(--accent)" : "var(--fg-primary)" }}>{fmtUAH(o.price)}</span>
                        </div>
                      ))}
                    </div>
                  </>
                )}
              </div>
              <div style={{ background: "var(--bg-base)", border: "1px solid var(--border-subtle)", borderRadius: 12, padding: 14 }}>
                <div style={mAnLabel}><Icon name="truck" size={13} /> У постачальників · {data.suppliers.length}</div>
                {data.suppliers.length === 0 ? (
                  <div style={{ display: "flex", alignItems: "center", gap: 8, color: "var(--fg-muted)", fontSize: 12.5 }}><Icon name="search-x" size={15} /> Не знайдено</div>
                ) : (
                  <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                    {data.suppliers.map((s, i) => {
                      const best = i === 0;
                      return (
                        <div key={i} style={{ display: "flex", alignItems: "center", gap: 10, padding: "9px 11px", borderRadius: 9, background: best ? "rgba(16,185,129,.08)" : "var(--bg-panel)", border: `1px solid ${best ? "rgba(16,185,129,.26)" : "var(--border-subtle)"}` }}>
                          <span style={{ width: 8, height: 8, borderRadius: "50%", background: s.color, flexShrink: 0 }} />
                          <span style={{ fontSize: 13, fontWeight: 600, color: s.color, whiteSpace: "nowrap" }}>{s.label}</span>
                          <div style={{ flex: 1 }} />
                          <span style={{ display: "inline-flex", alignItems: "center", gap: 5, fontSize: 11, color: s.stock ? "var(--fg-muted)" : "var(--fg-disabled)" }}>
                            <span style={{ width: 6, height: 6, borderRadius: "50%", background: s.stock ? "var(--success)" : "var(--fg-disabled)" }} />{s.stock ? "є" : "немає"}
                          </span>
                          <span style={{ fontFamily: "var(--font-mono)", fontVariantNumeric: "tabular-nums", fontSize: 14, fontWeight: 700, whiteSpace: "nowrap", color: best ? "var(--success)" : "var(--fg-primary)" }}>{fmtUAH(s.uah)}</span>
                        </div>
                      );
                    })}
                  </div>
                )}
              </div>
            </>
          )}
        </div>
      </BottomSheet>
    );
  }
  function AddSheetM({ wh, onClose, onAdd }) {
    const cur = wh.currency;
    const [form, setForm] = useState({ article: "", name: "", price: "", stock: "" });
    const [busy, setBusy] = useState(false);
    const set = (k, v) => setForm(f => ({ ...f, [k]: v }));
    const valid = form.article.trim() && form.name.trim();
    const submit = () => { if (!valid || busy) return; setBusy(true); onAdd(form, () => setBusy(false)); };
    const field = (label, key, opts = {}) => (
      <label style={{ display: "flex", flexDirection: "column", gap: 6, flex: opts.flex || "1 1 auto" }}>
        <span style={{ fontSize: 11.5, color: "var(--fg-muted)" }}>{label}{opts.req && <span style={{ color: "var(--danger)" }}> *</span>}</span>
        <div style={{ position: "relative" }}>
          <input value={form[key]} onChange={e => set(key, e.target.value)} inputMode={opts.num ? "decimal" : undefined} placeholder={opts.ph}
            style={{ width: "100%", boxSizing: "border-box", height: 46, padding: opts.sym ? "0 28px 0 13px" : "0 13px", background: "var(--bg-base)", color: "var(--fg-primary)", border: "1px solid var(--border-default)", borderRadius: 11, fontSize: 15, outline: "none", fontFamily: opts.num ? "var(--font-mono)" : "inherit", fontWeight: opts.num ? 600 : 400 }} />
          {opts.sym && <span style={{ position: "absolute", right: 13, top: "50%", transform: "translateY(-50%)", color: "var(--fg-muted)", fontSize: 14, pointerEvents: "none" }}>{opts.sym}</span>}
        </div>
      </label>
    );
    return (
      <BottomSheet onClose={onClose} heightPct="auto">
        <SheetHead title="Новий товар" sub={`Склад «${wh.label}» · ціна у ${CUR_LABEL[cur]}`} onClose={onClose} />
        <div style={{ padding: 16, display: "flex", flexDirection: "column", gap: 14 }}>
          {field("Артикул", "article", { req: true, ph: "DS-1200" })}
          {field("Назва товару", "name", { req: true, ph: "iPhone 15 Pro 256GB…" })}
          <div style={{ display: "flex", gap: 12 }}>
            {field("Ціна", "price", { num: true, ph: "0", sym: cur === "USD" ? "$" : "₴" })}
            {field("Первинний", "stock", { num: true, ph: "0" })}
          </div>
          <Button variant="primary" leftIcon={busy ? "loader-2" : "plus"} onClick={submit} disabled={!valid || busy} style={{ width: "100%", marginTop: 4 }}>{busy ? "Додаємо…" : "Додати товар"}</Button>
        </div>
      </BottomSheet>
    );
  }
  function DeleteSheetM({ item, onClose, onConfirm }) {
    return (
      <BottomSheet onClose={onClose} heightPct="auto">
        <div style={{ padding: "8px 18px 18px", display: "flex", flexDirection: "column", gap: 14 }}>
          <div style={{ display: "flex", gap: 12, alignItems: "flex-start" }}>
            <div style={{ width: 38, height: 38, borderRadius: 10, background: "rgba(244,63,94,.14)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}><Icon name="trash-2" size={18} color="var(--danger)" /></div>
            <div>
              <div style={{ fontSize: 15, fontWeight: 600, color: "var(--fg-primary)" }}>Видалити товар?</div>
              <div style={{ fontSize: 12.5, color: "var(--fg-muted)", marginTop: 3, lineHeight: 1.4 }}>«{item.name}» зникне з таблиці складу назавжди (рядок видаляється).</div>
            </div>
          </div>
          <div style={{ display: "flex", gap: 10 }}>
            <Button variant="secondary" onClick={onClose} style={{ flex: 1 }}>Скасувати</Button>
            <Button variant="primary" leftIcon="trash-2" onClick={() => onConfirm(item)} style={{ flex: 1, background: "var(--danger)" }}>Видалити</Button>
          </div>
        </div>
      </BottomSheet>
    );
  }

  function SkladMobile({ onBack }) {
    const [whList, setWhList] = useState([]);
    const [active, setActive] = useState(null);
    const [items, setItems] = useState([]);
    const [loading, setLoading] = useState(true);
    const [query, setQuery] = useState("");
    const [saving, setSaving] = useState(null);
    const [toast, setToast] = useState(null);
    const [sheet, setSheet] = useState(null);
    const [analytics, setAnalytics] = useState({});

    const wh = whList.find(w => w.key === active);
    const cur = (wh && wh.currency) || "UAH";
    const showToast = (text, icon = "check-circle", tone = "var(--success)") => { setToast({ text, icon, tone }); setTimeout(() => setToast(null), 2400); };

    const loadItems = async (key) => {
      setLoading(true);
      try { setItems(await API.warehouseItems(key)); }
      catch (e) { setItems([]); showToast(e.message || "Помилка", "alert-triangle", "var(--danger)"); }
      finally { setLoading(false); }
    };
    useEffect(() => {
      let alive = true;
      API.warehouses().then(list => {
        if (!alive) return;
        setWhList(list); const first = list[0] && list[0].key;
        if (first) { setActive(first); loadItems(first); } else setLoading(false);
      }).catch(e => { if (alive) { setLoading(false); showToast(e.message || "Помилка", "alert-triangle", "var(--danger)"); } });
      return () => { alive = false; };
    }, []);

    const pickWh = key => { if (key === active) return; setActive(key); setQuery(""); setSheet(null); setAnalytics({}); loadItems(key); };
    const openAnalytics = it => {
      setSheet({ type: "an", item: it });
      if (analytics[it.row] === undefined) loadAnalytics(it, active).then(data => setAnalytics(a => ({ ...a, [it.row]: data })));
    };
    const doDelete = async it => {
      const snapshot = items;
      setItems(list => list.filter(x => x.row !== it.row)); setSheet(null);
      try { await API.warehouseDelete(active, it.row); showToast(`Товар видалено · ${it.article}`, "trash-2", "var(--danger)"); setItems(await API.warehouseItems(active)); }
      catch (e) { setItems(snapshot); showToast(e.message || "Помилка видалення", "alert-triangle", "var(--danger)"); }
    };
    const doAdd = async (form, done) => {
      try {
        const it = await API.warehouseAdd(active, { article: form.article.trim(), name: form.name.trim(), price: parseFloat(String(form.price).replace(",", ".")) || 0, stock: parseInt(form.stock, 10) || 0 });
        setItems(list => [it, ...list]); setSheet(null); showToast(`Додано · ${it.article}`);
      } catch (e) { showToast(e.message || "Помилка", "alert-triangle", "var(--danger)"); }
      finally { done && done(); }
    };
    const onEdit = async (it, field, value) => {
      setSaving(`${it.row}:${field}`);
      try {
        const updated = await API.warehouseUpdate(active, { row: it.row, field, value });
        setItems(list => list.map(x => x.row === it.row ? updated : x));
        showToast(field === "price" ? `Ціну оновлено · ${it.article}` : `Залишок оновлено · ${it.article}`);
      } catch (e) { showToast(e.message || "Помилка", "alert-triangle", "var(--danger)"); }
      finally { setSaving(null); }
    };

    const realItems = useMemo(() => items.filter(it => !it.isCategory), [items]);
    const list = useMemo(() => {
      const q = query.trim().toLowerCase();
      if (!q) return items;
      return items.filter(it => !it.isCategory && ((it.name || "").toLowerCase().includes(q) || (it.article || "").toLowerCase().includes(q)));
    }, [items, query]);
    const totalSum = useMemo(() => realItems.reduce((s, it) => s + calcSum(it), 0), [realItems]);

    return (
      <div style={{ height: "100%", display: "flex", flexDirection: "column", background: "var(--bg-base)", color: "var(--fg-primary)", position: "relative" }}>
        <div style={{ padding: "12px 16px 12px", display: "flex", flexDirection: "column", gap: 12, flexShrink: 0 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
            {onBack && <button onClick={onBack} aria-label="Назад" style={{ width: 32, height: 32, marginLeft: -6, border: 0, background: "transparent", color: "var(--fg-secondary)", borderRadius: 8, cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center" }}><Icon name="arrow-left" size={20} /></button>}
            <h1 style={{ fontSize: 19, fontWeight: 600, color: "var(--fg-primary)", margin: 0 }}>Склад</h1>
            <span style={{ fontSize: 12, color: "var(--fg-muted)" }}>Власні склади</span>
            <div style={{ flex: 1 }} />
            <button onClick={() => active && setSheet({ type: "add" })} style={{ display: "inline-flex", alignItems: "center", gap: 6, height: 34, padding: "0 12px", borderRadius: 9, border: 0, background: "var(--accent)", color: "#fff", fontFamily: "inherit", fontSize: 12.5, fontWeight: 600, cursor: "pointer" }}><Icon name="plus" size={15} /> Товар</button>
          </div>
          {whList.length > 0 && <WarehouseSwitchM list={whList} active={active} onPick={pickWh} />}
          <div style={{ display: "flex", alignItems: "center", gap: 14, padding: "10px 14px", background: "var(--bg-panel)", border: "1px solid var(--border-subtle)", borderRadius: 12 }}>
            <div style={{ display: "flex", flexDirection: "column" }}>
              <span style={{ fontSize: 10, color: "var(--fg-muted)", letterSpacing: ".04em", textTransform: "uppercase" }}>Товарів</span>
              <span style={{ fontFamily: "var(--font-mono)", fontVariantNumeric: "tabular-nums", fontSize: 17, fontWeight: 700 }}>{fmtInt(realItems.length)}</span>
            </div>
            <div style={{ width: 1, height: 30, background: "var(--border-default)" }} />
            <div style={{ display: "flex", flexDirection: "column" }}>
              <span style={{ fontSize: 10, color: "var(--fg-muted)", letterSpacing: ".04em", textTransform: "uppercase" }}>Сума на складі · {CUR_LABEL[cur]}</span>
              <span style={{ fontFamily: "var(--font-mono)", fontVariantNumeric: "tabular-nums", fontSize: 17, fontWeight: 700, color: "var(--accent)" }}>{fmtMoney(totalSum, cur)}</span>
            </div>
          </div>
          <div style={{ position: "relative" }}>
            <Icon name="search" size={15} style={{ position: "absolute", left: 12, top: "50%", transform: "translateY(-50%)", color: "var(--accent)" }} />
            <input value={query} onChange={e => setQuery(e.target.value)} placeholder="Назва або артикул…" style={{ width: "100%", height: 44, boxSizing: "border-box", padding: "0 12px 0 36px", background: "var(--bg-panel)", color: "var(--fg-primary)", border: "1px solid var(--border-default)", borderRadius: 12, fontSize: 14, outline: "none", fontFamily: "inherit" }} />
          </div>
        </div>
        <div className="no-bar" style={{ flex: 1, overflow: "auto", padding: "2px 16px 24px", display: "flex", flexDirection: "column", gap: 11 }}>
          {loading ? (
            <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 12, padding: "60px 24px", color: "var(--fg-muted)" }}>
              <Icon name="loader-2" size={24} color="var(--accent)" style={{ animation: "spin .8s linear infinite" }} />
              <span style={{ fontSize: 13 }}>Завантаження{wh ? ` · ${wh.label}` : ""}…</span>
            </div>
          ) : list.length === 0 ? (
            <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 12, padding: "56px 24px", textAlign: "center" }}>
              <div style={{ width: 52, height: 52, borderRadius: 14, background: "var(--bg-panel)", border: "1px solid var(--border-subtle)", display: "flex", alignItems: "center", justifyContent: "center" }}><Icon name="search-x" size={24} color="var(--fg-muted)" /></div>
              <div>
                <div style={{ fontSize: 13.5, fontWeight: 600, color: "var(--fg-primary)" }}>{query ? `Нічого за «${query}»` : "Склад порожній"}</div>
                <div style={{ fontSize: 12, color: "var(--fg-muted)", marginTop: 4 }}>{query ? "Спробуйте інший запит" : "Додайте перший товар"}</div>
              </div>
              {query && <Button variant="secondary" leftIcon="rotate-ccw" onClick={() => setQuery("")}>Скинути пошук</Button>}
            </div>
          ) : (
            <>
              <div style={{ fontSize: 11.5, color: "var(--fg-muted)", padding: "2px 2px 0" }}>
                <span style={{ fontFamily: "var(--font-mono)", color: "var(--fg-secondary)", fontWeight: 600 }}>{list.filter(it => !it.isCategory).length}</span>{query ? ` з ${realItems.length}` : ""} позицій
              </div>
              {list.map(it => it.isCategory ? (
                <div key={it.row} style={{ display: "flex", alignItems: "center", gap: 7, padding: "8px 4px 2px" }}>
                  <Icon name="folder" size={12} color="var(--fg-muted)" />
                  <span style={{ fontSize: 11, fontWeight: 700, letterSpacing: ".04em", textTransform: "uppercase", color: "var(--fg-secondary)" }}>{it.name}</span>
                </div>
              ) : (
                <ItemCardM key={it.row} it={it} cur={cur}
                  savingField={saving && saving.startsWith(it.row + ":") ? saving.split(":")[1] : null}
                  onEdit={onEdit} onAnalytics={openAnalytics} onDelete={it2 => setSheet({ type: "del", item: it2 })} />
              ))}
            </>
          )}
        </div>
        <SkToast toast={toast} />
        {sheet && sheet.type === "an" && <AnalyticsSheet item={sheet.item} data={analytics[sheet.item.row]} onClose={() => setSheet(null)} />}
        {sheet && sheet.type === "add" && wh && <AddSheetM wh={wh} onClose={() => setSheet(null)} onAdd={doAdd} />}
        {sheet && sheet.type === "del" && <DeleteSheetM item={sheet.item} onClose={() => setSheet(null)} onConfirm={doDelete} />}
      </div>
    );
  }

  // ======================= Блок «На складах зараз» (Банки) ====================
  function StockOnHand({ onOpenWarehouse }) {
    const [rows, setRows] = useState(null);
    useEffect(() => { let a = true; API.warehousesSummary().then(d => { if (a) setRows(d || []); }).catch(() => { if (a) setRows([]); }); return () => { a = false; }; }, []);
    return (
      <div style={{ background: "var(--bg-raised)", border: "1px solid var(--border-subtle)", borderRadius: 12, overflow: "hidden" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 9, padding: "13px 16px", borderBottom: "1px solid var(--border-subtle)" }}>
          <div style={{ width: 30, height: 30, borderRadius: 8, background: "var(--accent-soft)", display: "flex", alignItems: "center", justifyContent: "center" }}><Icon name="warehouse" size={16} color="var(--accent)" /></div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 13.5, fontWeight: 600, color: "var(--fg-primary)" }}>На складах зараз</div>
            <div style={{ fontSize: 11, color: "var(--fg-muted)" }}>Вартість залишків · окремо по валютах</div>
          </div>
        </div>
        {rows === null ? (
          <div style={{ display: "flex", alignItems: "center", justifyContent: "center", padding: "26px", color: "var(--fg-muted)" }}>
            <Icon name="loader-2" size={18} color="var(--accent)" style={{ animation: "spin .8s linear infinite" }} />
          </div>
        ) : (
          <div style={{ display: "flex", flexDirection: "column" }}>
            {rows.map((w, i) => {
              // Клікабельний (з переходом на склад) лише якщо переданий onOpenWarehouse.
              // У вкладці «Банки» це інфо-показник → рядок НЕ клікабельний (без курсора/ховера/шеврона).
              const clickable = typeof onOpenWarehouse === "function";
              const rowStyle = { display: "flex", alignItems: "center", gap: 12, padding: "13px 16px", border: 0, background: "transparent", fontFamily: "inherit", textAlign: "left", borderTop: i === 0 ? "none" : "1px solid var(--border-subtle)", cursor: clickable ? "pointer" : "default", width: "100%", boxSizing: "border-box" };
              const inner = (<>
                <div style={{ display: "flex", flexDirection: "column", gap: 2, minWidth: 0, flex: 1 }}>
                  <span style={{ fontSize: 13, fontWeight: 600, color: "var(--fg-primary)" }}>{w.label}</span>
                  <span style={{ fontSize: 11.5, color: "var(--fg-muted)" }}>{fmtInt(w.count)} позицій</span>
                </div>
                <div style={{ textAlign: "right" }}>
                  <div style={{ fontFamily: "var(--font-mono)", fontVariantNumeric: "tabular-nums", fontSize: 16, fontWeight: 700, color: "var(--fg-primary)" }}>{fmtMoney(w.totalSum, w.currency)}</div>
                  <div style={{ fontSize: 10.5, color: "var(--fg-muted)", letterSpacing: ".04em", textTransform: "uppercase" }}>{CUR_LABEL[w.currency]}</div>
                </div>
                {clickable && <Icon name="chevron-right" size={16} color="var(--fg-muted)" />}
              </>);
              return clickable ? (
                <button key={w.key} onClick={() => onOpenWarehouse(w.key)} style={rowStyle}
                  onMouseEnter={e => e.currentTarget.style.background = "var(--bg-hover)"} onMouseLeave={e => e.currentTarget.style.background = "transparent"}>
                  {inner}
                </button>
              ) : (
                <div key={w.key} style={rowStyle}>{inner}</div>
              );
            })}
          </div>
        )}
        <div style={{ padding: "9px 16px", borderTop: "1px solid var(--border-subtle)", background: "var(--bg-base)", display: "flex", alignItems: "center", gap: 6 }}>
          <Icon name="info" size={12} color="var(--fg-muted)" />
          <span style={{ fontSize: 11, color: "var(--fg-muted)" }}>Долар і гривня показані окремо — не сумуються в одну суму.</span>
        </div>
      </div>
    );
  }

  function Sklad({ isMobile, onBack }) { return isMobile ? <SkladMobile onBack={onBack} /> : <SkladDesktop />; }

  window.Sklad = Sklad;
  window.StockOnHand = StockOnHand;
})();
