// ============ Shop Stock — สต็อกสินค้าหน้าร้านแยกสาขา ============
// ลิ้งกับยอดผลิต (productionEvents) อัปเดตจากพนักงานนับ (shopStockCounts)

// ---- helpers ----
function shopStockBalance(db, menuId, branchId) {
  const bal = (db.shopStock || []).find(b => b.menuId === menuId && b.branchId === branchId);
  return bal ? Number(bal.onHand) || 0 : 0;
}

function shopStockApply(db, menuId, branchId, qty, type, note, refId) {
  const now = new Date().toISOString();
  const mvId = 'SSM' + Date.now().toString(36).toUpperCase();
  const movement = { id: mvId, menuId, branchId, qty, type, note: note || '', refId: refId || '', createdAt: now };
  const existing = (db.shopStock || []).find(b => b.menuId === menuId && b.branchId === branchId);
  const newOnHand = (existing ? Number(existing.onHand) || 0 : 0) + qty;
  const shopStock = existing
    ? (db.shopStock || []).map(b => b.menuId === menuId && b.branchId === branchId ? { ...b, onHand: newOnHand, lastUpdatedAt: now } : b)
    : [...(db.shopStock || []), { menuId, branchId, onHand: newOnHand, lastUpdatedAt: now }];
  return {
    shopStock,
    shopStockMovements: [...(db.shopStockMovements || []), movement],
  };
}

// ---- confirm employee count → ปรับ balance ให้ตรงกับที่นับได้ ----
function shopStockConfirmCount(db, countRecord) {
  let updated = { ...db };
  (countRecord.items || []).forEach(item => {
    const prev = shopStockBalance(updated, item.menuId, countRecord.branchId);
    const diff = item.counted - prev;
    if (diff === 0) return;
    const result = shopStockApply(updated, item.menuId, countRecord.branchId, diff,
      'count', `นับสต็อก #${countRecord.id} โดย ${countRecord.submittedBy || 'พนักงาน'}`, countRecord.id);
    updated = { ...updated, ...result };
  });
  updated.shopStockCounts = (updated.shopStockCounts || []).map(c =>
    c.id === countRecord.id ? { ...c, status: 'confirmed', confirmedAt: new Date().toISOString() } : c
  );
  return updated;
}

// ============ ShopStockPage ============
function ShopStockPage({ go }) {
  const { db, setDb, flash, settings } = useData();
  const branches = db.branches && db.branches.length ? db.branches : ['JE BAR'];
  const [branch, setBranch] = React.useState(branches[0]);

  // sync branch ถ้า branches เปลี่ยน
  React.useEffect(() => {
    if (!branches.includes(branch)) setBranch(branches[0]);
  }, [branches.join(',')]);

  // พนักงานเห็นแค่ฟอร์มนับสต็อก
  const isEmployee = React.useMemo(() => {
    try {
      const qs = new URLSearchParams(window.location.search);
      const qMode = (qs.get('mode') || qs.get('role') || '').toLowerCase();
      if (['employee','staff','emp'].includes(qMode)) return true;
      return (localStorage.getItem('jebar_runtime_mode') || '') === 'employee';
    } catch(e) { return false; }
  }, []);

  if (isEmployee) {
    return (
      <div className="view-enter" style={{ padding: '8px 0' }}>
        <StockCountForm db={db} setDb={setDb} flash={flash} defaultBranch={branch} />
      </div>
    );
  }

  const [tab, setTab] = React.useState('stock'); // stock | counts | history

  const baseMenus = (db.menus || [])
    .filter(m => m.status !== 'inactive' && m.category !== 'Beverage');

  // ลำดับ custom — เก็บใน db.shopStockMenuOrder เป็น array ของ menuId
  const savedOrder = db.shopStockMenuOrder || [];
  const menus = React.useMemo(() => {
    if (!savedOrder.length) return baseMenus.slice().sort((a,b) => String(a.id).localeCompare(String(b.id)));
    const ordered = savedOrder.map(id => baseMenus.find(m => m.id === id)).filter(Boolean);
    const rest = baseMenus.filter(m => !savedOrder.includes(m.id));
    return [...ordered, ...rest];
  }, [JSON.stringify(savedOrder), JSON.stringify(baseMenus.map(m=>m.id))]);

  // เปิด/ปิดการขายแต่ละเมนู per branch: db.shopStockActive[menuId_branchId] = true/false
  const activeKey = (menuId) => `${menuId}__${branch}`;
  const isActive = (menuId) => {
    const v = (db.shopStockActive || {})[activeKey(menuId)];
    return v === undefined ? true : v; // default = เปิด
  };
  const toggleActive = (menuId) => {
    const key = activeKey(menuId);
    const cur = isActive(menuId);
    setDb(prev => ({
      ...prev,
      shopStockActive: { ...(prev.shopStockActive || {}), [key]: !cur },
    }));
    flash(`${!cur ? '✅ เปิด' : '⛔ ปิด'}การขาย ${(menus.find(m=>m.id===menuId)||{}).name||menuId} ที่ ${branch}`);
  };

  const stockRows = menus.map(m => ({
    menu: m,
    onHand: shopStockBalance(db, m.id, branch),
    active: isActive(m.id),
  }));

  const activeRows = stockRows.filter(r => r.active);
  const totalItems = activeRows.filter(r => r.onHand > 0).length;
  const lowItems = activeRows.filter(r => r.onHand > 0 && r.onHand <= 3).length;
  const emptyItems = activeRows.filter(r => r.onHand <= 0).length;

  // pending counts
  const pendingCounts = (db.shopStockCounts || [])
    .filter(c => c.status === 'pending')
    .sort((a, b) => String(b.submittedAt).localeCompare(String(a.submittedAt)));

  // history movements for this branch
  const movements = (db.shopStockMovements || [])
    .filter(m => m.branchId === branch)
    .sort((a, b) => String(b.createdAt).localeCompare(String(a.createdAt)))
    .slice(0, 60);

  // inline adjust state: { [menuId]: { val, open } }
  const [inlineAdj, setInlineAdj] = React.useState({});
  // quick-add dropdown selection per row: { [menuId]: string }
  const [quickSel, setQuickSel] = React.useState({});

  const applyAdj = (menuId, delta) => {
    const q = parseFloat(delta);
    if (isNaN(q) || q === 0) return;
    const result = shopStockApply(db, menuId, branch, q, 'adjust', `ปรับสต็อก ${branch}`, '');
    setDb(prev => ({ ...prev, ...result }));
    setInlineAdj(prev => ({ ...prev, [menuId]: { val: '', open: false } }));
    flash(`ปรับ ${q > 0 ? '+' : ''}${q} ชิ้น`);
  };

  const confirmCount = (c) => {
    const updated = shopStockConfirmCount(db, c);
    setDb(updated);
    flash(`ยืนยันการนับสต็อกจาก ${c.branchId} แล้ว`);
  };

  const rejectCount = (c) => {
    setDb(prev => ({
      ...prev,
      shopStockCounts: (prev.shopStockCounts || []).map(x =>
        x.id === c.id ? { ...x, status: 'rejected', confirmedAt: new Date().toISOString() } : x
      ),
    }));
    flash('ปฏิเสธการนับแล้ว');
  };

  const fmtDt = iso => iso ? new Date(iso).toLocaleString('th-TH', { dateStyle: 'short', timeStyle: 'short' }) : '–';
  const typeLabel = t => ({ produce: '📦 ผลิต', count: '📋 นับสต็อก', adjust: '✏️ ปรับ', sale: '🛍 ขาย' })[t] || t;

  // ---- drag-to-reorder ----
  const [dragIdx, setDragIdx] = React.useState(null);
  const [overIdx, setOverIdx] = React.useState(null);
  const [ghost, setGhost] = React.useState(null); // { y, text }
  const touchDrag = React.useRef(null);
  const listRef = React.useRef();

  const commitOrder = (from, to) => {
    if (from == null || to == null || from === to) { setDragIdx(null); setOverIdx(null); setGhost(null); return; }
    const ids = menus.map(m => m.id);
    const moved = ids.splice(from, 1)[0];
    ids.splice(to, 0, moved);
    setDb(prev => ({ ...prev, shopStockMenuOrder: ids }));
    setDragIdx(null); setOverIdx(null); setGhost(null);
  };

  // mouse drag
  const onDragStart = (e, idx) => { e.dataTransfer.effectAllowed = 'move'; setDragIdx(idx); };
  const onDragOver  = (e, idx) => { e.preventDefault(); setOverIdx(idx); };
  const onDrop      = (e, idx) => { e.preventDefault(); commitOrder(dragIdx, idx); };
  const onDragEnd   = ()       => { setDragIdx(null); setOverIdx(null); };

  // touch drag — ต้องใช้ useEffect ให้ passive:false เพื่อกัน scroll
  React.useEffect(() => {
    const el = listRef.current;
    if (!el) return;
    const handleTouchMove = (e) => {
      if (!touchDrag.current) return;
      e.preventDefault(); // กัน scroll ขณะลาก
      const t = e.touches[0];
      const rows = Array.from(el.querySelectorAll('[data-row]'));
      let newOver = touchDrag.current.curIdx;
      for (let i = 0; i < rows.length; i++) {
        const rect = rows[i].getBoundingClientRect();
        if (t.clientY >= rect.top && t.clientY <= rect.bottom) { newOver = i; break; }
      }
      touchDrag.current.curIdx = newOver;
      setOverIdx(newOver);
      setGhost(g => g ? { ...g, y: t.clientY } : g);
    };
    el.addEventListener('touchmove', handleTouchMove, { passive: false });
    return () => el.removeEventListener('touchmove', handleTouchMove);
  }, [menus.length]);

  const onHandleTouch = (e, idx) => {
    e.stopPropagation();
    const t = e.touches[0];
    const menuName = menus[idx]?.name || '';
    touchDrag.current = { fromIdx: idx, curIdx: idx };
    setDragIdx(idx);
    setGhost({ y: t.clientY, text: menuName });
  };
  const onTouchEnd = () => {
    if (!touchDrag.current) return;
    commitOrder(touchDrag.current.fromIdx, touchDrag.current.curIdx);
    touchDrag.current = null;
  };

  // ปุ่มจัดกลุ่ม: เปิดขาย → บน, ปิดขาย → ล่าง
  const sortActiveFirst = () => {
    const activeIds = menus.filter(m => isActive(m.id)).map(m => m.id);
    const inactiveIds = menus.filter(m => !isActive(m.id)).map(m => m.id);
    setDb(prev => ({ ...prev, shopStockMenuOrder: [...activeIds, ...inactiveIds] }));
    flash('จัดกลุ่มแล้ว — รายการที่เปิดขายขึ้นบน');
  };

  const QUICK_OPTS = [
    { value: '1', label: '+1' },
    { value: '3', label: '+3' },
    { value: '5', label: '+5' },
    { value: '10', label: '+10' },
    { value: '-1', label: '-1' },
    { value: '-3', label: '-3' },
    { value: '-5', label: '-5' },
  ];

  return (
    <div className="view-enter" style={{ display: 'grid', gap: 18 }}>

      {/* branch selector — แสดงเฉพาะตอนมีหลายสาขา */}
      {branches.length > 1 && (
        <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
          {branches.map(b => (
            <button key={b} onClick={() => setBranch(b)} style={{
              padding: '8px 20px', borderRadius: 20, border: '1.5px solid',
              borderColor: b === branch ? 'var(--accent)' : 'var(--line)',
              background: b === branch ? 'var(--accent-soft)' : 'var(--chip)',
              color: b === branch ? 'var(--accent)' : 'var(--ink-2)',
              fontWeight: b === branch ? 700 : 400,
              cursor: 'pointer', fontSize: 14, fontFamily: 'inherit',
            }}>{b}</button>
          ))}
        </div>
      )}

      {/* KPI */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 14 }} className="r-2col">
        <Stat label="มีสินค้า" value={fmt(totalItems)} icon="layers" tone="var(--green)"
          sub={`จากที่เปิดขาย ${activeRows.length} เมนู`} />
        <Stat label="ใกล้หมด (≤3)" value={fmt(lowItems)} icon="warning" tone="var(--orange)"
          sub="ควรผลิตเพิ่ม" />
        <Stat label="หมดแล้ว" value={fmt(emptyItems)} icon="trash" tone="var(--red)"
          sub="ไม่มีสต็อก" />
      </div>

      {/* tabs */}
      <div style={{ display: 'flex', gap: 4, background: 'var(--chip)', borderRadius: 12, padding: 4, width: 'fit-content', flexWrap: 'wrap' }}>
        {[
          { id: 'stock', label: '📦 สต็อก' },
          { id: 'counts', label: `📋 รออนุมัติ${pendingCounts.length > 0 ? ` (${pendingCounts.length})` : ''}` },
          { id: 'history', label: '📜 ประวัติ' },
        ].map(t => (
          <button key={t.id} onClick={() => setTab(t.id)} style={{
            padding: '8px 16px', borderRadius: 9, border: 'none', cursor: 'pointer',
            fontSize: 13.5, fontFamily: 'inherit',
            background: tab === t.id ? 'var(--surface)' : 'transparent',
            color: tab === t.id ? 'var(--ink)' : 'var(--ink-2)',
            fontWeight: tab === t.id ? 600 : 400,
            boxShadow: tab === t.id ? 'var(--shadow-sm)' : 'none',
          }}>{t.label}</button>
        ))}
      </div>

      {/* stock tab */}
      {tab === 'stock' && (
        <Card>
          <SectionTitle
            sub={`สาขา ${branch} · toggle เปิด/ปิดการขาย · ⠿ ลากเรียงลำดับ`}
            right={<Button variant="secondary" onClick={sortActiveFirst}>⬆ จัดกลุ่ม</Button>}>
            สต็อกสินค้า — {branch}
          </SectionTitle>
          {menus.length === 0
            ? <Empty icon="cup" title="ยังไม่มีเมนู" sub="เพิ่มเมนูในหน้าเมนูก่อน" />
            : <div style={{ display: 'flex', flexDirection: 'column', gap: 0 }}>
                {/* header */}
                <div style={{ display: 'grid', gridTemplateColumns: '20px 36px 72px 1fr 72px 108px', gap: 8, fontSize: 11.5, color: 'var(--ink-3)', padding: '4px 4px 8px' }}>
                  <span/>
                  <span>ขาย</span><span>รหัส</span><span>เมนู</span>
                  <span style={{ textAlign: 'right' }}>คงเหลือ</span>
                  <span style={{ textAlign: 'center' }}>เพิ่ม/ลด</span>
                </div>
                <div ref={listRef} onTouchEnd={onTouchEnd}>
                {stockRows.map(({ menu: m, onHand, active }, rowI) => {
                  const tone = !active ? 'var(--ink-3)' : onHand <= 0 ? 'var(--red)' : onHand <= 3 ? 'var(--orange)' : 'var(--green)';
                  const adj = inlineAdj[m.id] || { val: '', open: false };
                  const qv = quickSel[m.id] || '1';
                  const isDragging = dragIdx === rowI;
                  const isOver = overIdx === rowI && dragIdx !== rowI;
                  return (
                    <div key={m.id} data-row={rowI}
                      draggable
                      onDragStart={e => onDragStart(e, rowI)}
                      onDragOver={e => onDragOver(e, rowI)}
                      onDrop={e => onDrop(e, rowI)}
                      onDragEnd={onDragEnd}
                      style={{
                        display: 'grid', gridTemplateColumns: '20px 36px 72px 1fr 72px 108px', gap: 8,
                        alignItems: 'center', padding: '9px 4px',
                        borderTop: isOver ? '2.5px solid var(--accent)' : '1px solid transparent',
                        borderBottom: '1px solid var(--line-2)',
                        opacity: isDragging ? 0.3 : active ? 1 : 0.45,
                        background: isDragging ? 'var(--accent-soft)' : 'transparent',
                        transition: 'opacity .15s',
                        userSelect: 'none',
                      }}>
                      {/* drag handle */}
                      <span
                        onTouchStart={e => onHandleTouch(e, rowI)}
                        style={{ fontSize: 16, color: 'var(--ink-3)', cursor: 'grab', touchAction: 'none',
                          display: 'flex', alignItems: 'center', justifyContent: 'center', lineHeight: 1,
                          WebkitUserSelect: 'none', padding: '4px 0' }}>
                        ⠿
                      </span>

                      {/* toggle เปิด/ปิด */}
                      <button onClick={() => toggleActive(m.id)} title={active ? 'ปิดการขาย' : 'เปิดการขาย'}
                        style={{
                          width: 28, height: 16, borderRadius: 8, border: 'none', cursor: 'pointer', padding: 0,
                          background: active ? 'var(--green)' : 'var(--ink-3)',
                          position: 'relative', transition: 'background .2s', flexShrink: 0,
                        }}>
                        <span style={{
                          position: 'absolute', top: 2, left: active ? 14 : 2,
                          width: 12, height: 12, borderRadius: '50%', background: '#fff',
                          transition: 'left .2s',
                        }} />
                      </button>

                      <Badge tone={!active ? 'gray' : onHand <= 0 ? 'red' : onHand <= 3 ? 'orange' : 'green'}
                        style={{ fontSize: 11, justifySelf: 'start' }}>{m.id}</Badge>
                      <span style={{ fontSize: 13.5 }}>{m.name}</span>

                      {/* ยอดคงเหลือ — กดแก้ inline */}
                      <input
                        type="number"
                        value={adj.open ? adj.val : onHand}
                        onFocus={() => setInlineAdj(prev => ({ ...prev, [m.id]: { val: String(onHand), open: true } }))}
                        onChange={e => setInlineAdj(prev => ({ ...prev, [m.id]: { val: e.target.value, open: true } }))}
                        onBlur={e => {
                          const newVal = parseFloat(e.target.value);
                          if (!isNaN(newVal) && newVal !== onHand) {
                            applyAdj(m.id, newVal - onHand);
                          } else {
                            setInlineAdj(prev => ({ ...prev, [m.id]: { val: '', open: false } }));
                          }
                        }}
                        onKeyDown={e => {
                          if (e.key === 'Enter') e.target.blur();
                          if (e.key === 'Escape') setInlineAdj(prev => ({ ...prev, [m.id]: { val: '', open: false } }));
                        }}
                        style={{
                          width: '100%', textAlign: 'right', fontWeight: 700, fontSize: 16,
                          color: adj.open ? 'var(--accent)' : tone,
                          background: adj.open ? 'var(--accent-soft)' : 'transparent',
                          border: adj.open ? '1.5px solid var(--accent)' : '1.5px solid transparent',
                          borderRadius: 8, padding: '3px 6px', fontFamily: 'inherit',
                          outline: 'none', cursor: 'text',
                        }}
                      />

                      {/* dropdown + ปุ่มยืนยัน */}
                      <div style={{ display: 'flex', gap: 4, alignItems: 'center' }}>
                        <select
                          value={qv}
                          onChange={e => setQuickSel(prev => ({ ...prev, [m.id]: e.target.value }))}
                          style={{
                            flex: 1, padding: '5px 4px', borderRadius: 8, border: '1px solid var(--line)',
                            background: 'var(--surface)', color: 'var(--ink)', fontSize: 13,
                            fontFamily: 'inherit', outline: 'none', cursor: 'pointer',
                          }}>
                          {QUICK_OPTS.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
                        </select>
                        <button onClick={() => applyAdj(m.id, parseFloat(qv))} style={{
                          padding: '5px 9px', borderRadius: 8, border: 'none',
                          background: parseFloat(qv) >= 0 ? 'var(--green)' : 'var(--red)',
                          color: '#fff', fontWeight: 700, fontSize: 14,
                          cursor: 'pointer', lineHeight: 1,
                        }}>✓</button>
                      </div>
                    </div>
                  );
                })}
                </div>{/* end listRef */}
              </div>}
        </Card>
      )}

      {/* pending counts tab */}
      {tab === 'counts' && (
        <Card>
          <SectionTitle sub="การนับสต็อกที่พนักงานส่งมา รอเจ้าของยืนยัน">รออนุมัติการนับ</SectionTitle>
          {pendingCounts.length === 0
            ? <Empty icon="doc" title="ไม่มีรายการรออนุมัติ" sub="เมื่อพนักงานส่งการนับสต็อก จะปรากฏที่นี่" />
            : pendingCounts.map(c => (
                <div key={c.id} style={{ border: '1px solid var(--line)', borderRadius: 14, padding: 16, marginBottom: 12 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
                    <div>
                      <div style={{ fontWeight: 700, fontSize: 15 }}>สาขา {c.branchId}</div>
                      <div style={{ fontSize: 12.5, color: 'var(--ink-3)' }}>
                        นับโดย {c.submittedBy || 'พนักงาน'} · {fmtDt(c.submittedAt)}
                      </div>
                    </div>
                    <Badge tone="orange">รอยืนยัน</Badge>
                  </div>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 6, marginBottom: 14 }}>
                    <div style={{ display: 'grid', gridTemplateColumns: '70px 1fr auto auto', gap: 8, fontSize: 11.5, color: 'var(--ink-3)', padding: '0 2px' }}>
                      <span>รหัส</span><span>เมนู</span><span>คงเหลือเดิม</span><span>นับได้</span>
                    </div>
                    {(c.items || []).map(item => {
                      const m = menus.find(x => x.id === item.menuId);
                      const diff = item.counted - (item.prevOnHand || 0);
                      return (
                        <div key={item.menuId} style={{ display: 'grid', gridTemplateColumns: '70px 1fr auto auto', gap: 8, alignItems: 'center', padding: '4px 2px', borderBottom: '1px solid var(--line-2)' }}>
                          <span style={{ fontSize: 11.5, color: 'var(--accent)', fontWeight: 600 }}>{item.menuId}</span>
                          <span style={{ fontSize: 13.5 }}>{item.menuName || m?.name || item.menuId}</span>
                          <span className="tnum" style={{ fontSize: 13, color: 'var(--ink-3)' }}>{item.prevOnHand || 0}</span>
                          <span className="tnum" style={{ fontWeight: 700, color: diff < 0 ? 'var(--red)' : diff > 0 ? 'var(--green)' : 'var(--ink-2)' }}>
                            {item.counted}
                            {diff !== 0 && <span style={{ fontSize: 11, marginLeft: 4 }}>({diff > 0 ? '+' : ''}{diff})</span>}
                          </span>
                        </div>
                      );
                    })}
                  </div>
                  <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
                    <Button variant="secondary" size="sm" onClick={() => rejectCount(c)}>ปฏิเสธ</Button>
                    <Button size="sm" icon="check" onClick={() => confirmCount(c)}>ยืนยันและปรับสต็อก</Button>
                  </div>
                </div>
              ))}
        </Card>
      )}

      {/* history tab */}
      {tab === 'history' && (
        <Card>
          <SectionTitle sub={`ความเคลื่อนไหวล่าสุด · สาขา ${branch}`}>ประวัติความเคลื่อนไหว</SectionTitle>
          {movements.length === 0
            ? <Empty icon="doc" title="ยังไม่มีประวัติ" sub="ประวัติจะปรากฏเมื่อมีการบันทึกผลิต/ปรับ/นับ" />
            : <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                {movements.map(mv => {
                  const m = menus.find(x => x.id === mv.menuId);
                  return (
                    <div key={mv.id} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '9px 4px', borderBottom: '1px solid var(--line-2)' }}>
                      <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
                        <span style={{ fontSize: 13 }}>{typeLabel(mv.type)}</span>
                        <div>
                          <div style={{ fontSize: 13.5, fontWeight: 500 }}>
                            <span style={{ fontSize: 11.5, color: 'var(--accent)', marginRight: 4 }}>[{mv.menuId}]</span>
                            {m?.name || mv.menuId}
                          </div>
                          {mv.note && <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>{mv.note}</div>}
                          <div style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>{fmtDt(mv.createdAt)}</div>
                        </div>
                      </div>
                      <span className="tnum" style={{ fontWeight: 700, fontSize: 15, color: mv.qty >= 0 ? 'var(--green)' : 'var(--red)' }}>
                        {mv.qty > 0 ? '+' : ''}{fmt(mv.qty, 0)}
                      </span>
                    </div>
                  );
                })}
              </div>}
        </Card>
      )}
      {/* ghost ลอยตามนิ้วขณะลาก */}
      {ghost && (
        <div style={{
          position: 'fixed', left: 16, right: 16,
          top: ghost.y - 22, pointerEvents: 'none', zIndex: 9999,
          background: 'var(--accent)', color: '#fff',
          borderRadius: 10, padding: '8px 14px', fontSize: 14, fontWeight: 600,
          boxShadow: '0 6px 24px rgba(0,0,0,.25)', opacity: 0.93,
        }}>{ghost.text}</div>
      )}
    </div>
  );
}

Object.assign(window, { ShopStockPage, shopStockApply, shopStockBalance, shopStockConfirmCount });
