// Kasir terminal — product picker + cart + tender
const { useState: useStateK, useMemo: useMemoK, useRef: useRefK, useEffect: useEffectK } = React;

function Kasir({ cabang, role, pushToast }) {
  const [cat, setCat] = useStateK('all');
  const [query, setQuery] = useStateK('');
  const [cart, setCart] = useStateK([]); // [{ sku, qty }]
  const [tender, setTender] = useStateK('cash');
  const [paid, setPaid] = useStateK(false);
  const inputRef = useRefK(null);

  useEffectK(() => { inputRef.current?.focus(); }, []);

  const filtered = useMemoK(() => {
    let list = PRODUCTS;
    if (cat !== 'all') list = list.filter(p => p.cat === cat);
    if (query.trim()) {
      const q = query.toLowerCase();
      list = list.filter(p => p.name.toLowerCase().includes(q) || p.sku.toLowerCase().includes(q) || p.barcode.includes(q));
    }
    return list.slice(0, 30);
  }, [cat, query]);

  const cartLines = cart.map(c => ({ ...c, p: PROD[c.sku], subtotal: PROD[c.sku].price * c.qty }));
  const subtotal = cartLines.reduce((s, l) => s + l.subtotal, 0);
  const ppn = 0; // not applied for warung
  const diskon = subtotal >= 100_000 && tender !== 'cash' ? Math.round(subtotal * 0.02) : 0;
  const total = subtotal + ppn - diskon;

  const addToCart = (sku) => {
    setPaid(false);
    setCart(prev => {
      const idx = prev.findIndex(x => x.sku === sku);
      if (idx >= 0) {
        const next = [...prev];
        next[idx] = { ...next[idx], qty: next[idx].qty + 1 };
        return next;
      }
      return [...prev, { sku, qty: 1 }];
    });
  };
  const setQty = (sku, qty) => {
    if (qty <= 0) { setCart(prev => prev.filter(x => x.sku !== sku)); return; }
    setCart(prev => prev.map(x => x.sku === sku ? { ...x, qty } : x));
  };
  const clearCart = () => { setCart([]); setPaid(false); };

  const onPay = () => {
    if (cart.length === 0) return;
    setPaid(true);
    pushToast && pushToast({ msg: 'Pembayaran berhasil. Struk dicetak.' });
  };

  return (
    <div className="pos-shell">
      {/* LEFT: products */}
      <div>
        <div className="pos-search">
          <Icon name="scan" size={18} className="icon" />
          <input
            ref={inputRef}
            value={query}
            onChange={e => setQuery(e.target.value)}
            placeholder="Pindai barcode atau cari produk (nama / SKU)…"
          />
          <span style={{fontSize:11, color:'hsl(var(--muted-foreground))'}}>F2 = Bayar · F4 = Hold</span>
        </div>

        <div className="pos-cat-tabs">
          {CATEGORIES.map(c => (
            <button
              key={c.id}
              className={'pos-cat-tab' + (cat === c.id ? ' active' : '')}
              onClick={() => setCat(c.id)}
            >
              {c.label}
            </button>
          ))}
        </div>

        <div className="pos-product-grid">
          {filtered.map(p => {
            const stock = p.stock[cabang] ?? 0;
            const low = stock < 10;
            const initials = p.name.split(/\s+/).slice(0, 2).map(x => x[0]).join('').toUpperCase();
            return (
              <button key={p.sku} className="pos-product" onClick={() => addToCart(p.sku)} disabled={stock <= 0}>
                <div className="pos-product-thumb">{initials}</div>
                <div className="pos-product-name">{p.name}</div>
                <div className="pos-product-price">{rupiah(p.price, { sym: true })}</div>
                <div className={'pos-product-stock' + (low ? ' low' : '')}>
                  Stok: {stock} {low && '· menipis'}
                </div>
              </button>
            );
          })}
          {filtered.length === 0 && (
            <div className="empty" style={{gridColumn:'1 / -1'}}>Tidak ada produk yang cocok.</div>
          )}
        </div>
      </div>

      {/* RIGHT: cart */}
      <div className="pos-cart">
        <div className="pos-cart-header">
          <div>
            <div style={{fontSize:13, fontWeight:600}}>Keranjang</div>
            <div style={{fontSize:11, color:'hsl(var(--muted-foreground))'}}>
              {cart.length} item · Kasir: {ROLES[role].name}
            </div>
          </div>
          <button className="btn ghost sm" onClick={clearCart} disabled={cart.length === 0}>
            <Icon name="trash" size={13} /> Kosongkan
          </button>
        </div>

        <div className="pos-cart-items">
          {cart.length === 0 && (
            <div className="empty" style={{padding:'40px 20px'}}>
              <Icon name="cart" size={28} className="icon" />
              <div style={{marginTop:8}}>Mulai pindai atau klik produk.</div>
            </div>
          )}
          {cartLines.map(l => (
            <div key={l.sku} className="pos-cart-item">
              <div className="pos-cart-item-name">
                {l.p.name}
                <div style={{fontSize:11, color:'hsl(var(--muted-foreground))', fontWeight:400, marginTop:2}}>
                  {l.p.sku} · {rupiah(l.p.price)}/pcs
                </div>
              </div>
              <div className="pos-cart-item-price">{rupiah(l.subtotal)}</div>
              <div className="pos-cart-item-qty" style={{gridColumn:'1 / -1'}}>
                <button className="pos-qty-btn" onClick={() => setQty(l.sku, l.qty - 1)}>−</button>
                <span style={{minWidth:24, textAlign:'center', fontVariantNumeric:'tabular-nums'}}>{l.qty}</span>
                <button className="pos-qty-btn" onClick={() => setQty(l.sku, l.qty + 1)}>+</button>
                <span style={{marginLeft:'auto', fontSize:11}}>Subtotal {rupiah(l.subtotal, { sym: true })}</span>
              </div>
            </div>
          ))}
        </div>

        <div className="pos-cart-summary">
          <div className="pos-cart-row">
            <span>Subtotal</span>
            <span style={{fontVariantNumeric:'tabular-nums'}}>{rupiah(subtotal, { sym: true })}</span>
          </div>
          {diskon > 0 && (
            <div className="pos-cart-row" style={{color:'hsl(152 65% 35%)'}}>
              <span>Diskon cashless 2%</span>
              <span style={{fontVariantNumeric:'tabular-nums'}}>−{rupiah(diskon, { sym: true })}</span>
            </div>
          )}
          <div className="pos-cart-row total">
            <span>Total</span>
            <span style={{fontVariantNumeric:'tabular-nums'}}>{rupiah(total, { sym: true })}</span>
          </div>

          <div style={{fontSize:11.5, fontWeight:600, color:'hsl(var(--muted-foreground))', marginTop:12, textTransform:'uppercase', letterSpacing:'0.05em'}}>Metode Bayar</div>
          <div className="pos-tender-grid">
            {[
              { id: 'cash',     label: 'Tunai',    icon: 'cashbox' },
              { id: 'qris',     label: 'QRIS',     icon: 'qris' },
              { id: 'transfer', label: 'Transfer', icon: 'bank' },
              { id: 'kartu',    label: 'Debit',    icon: 'receipt' },
            ].map(t => (
              <button
                key={t.id}
                className={'pos-tender' + (tender === t.id ? ' active' : '')}
                onClick={() => setTender(t.id)}
              >
                <Icon name={t.icon} size={20} />
                <span className="pos-tender-label">{t.label}</span>
              </button>
            ))}
          </div>
        </div>

        <div className="pos-cart-actions">
          <button className="btn outline" disabled={cart.length === 0}>
            <Icon name="clock" size={14} /> Hold
          </button>
          <button className="btn" onClick={onPay} disabled={cart.length === 0}>
            <Icon name="check" size={14} /> Bayar {total > 0 && rupiah(total, { sym: true })}
          </button>
        </div>

        {paid && (
          <div style={{padding:14, borderTop:'1px solid hsl(var(--border))'}}>
            <div className="receipt">{makeReceipt({ cartLines, subtotal, diskon, total, tender, role, cabang })}</div>
          </div>
        )}
      </div>
    </div>
  );
}

function makeReceipt({ cartLines, subtotal, diskon, total, tender, role, cabang }) {
  const cab = CABANG_LIST.find(c => c.id === cabang)?.name || cabang;
  const now = new Date();
  const ts = now.toLocaleString('id-ID', { dateStyle: 'short', timeStyle: 'short' });
  const lines = [];
  lines.push('     TOKO SUMBER REJEKI');
  lines.push('   ' + cab);
  lines.push('   Jl. Merdeka Barat 88, Bekasi');
  lines.push('--------------------------------');
  lines.push(`Tgl : ${ts}`);
  lines.push(`Trx : TRX-${now.toISOString().slice(2,10).replace(/-/g,'')}-XXXX`);
  lines.push(`Kasir: ${ROLES[role].name}`);
  lines.push('--------------------------------');
  cartLines.forEach(l => {
    lines.push(l.p.name);
    const right = `${l.qty} x ${rupiah(l.p.price)} = ${rupiah(l.subtotal)}`;
    lines.push('  ' + right);
  });
  lines.push('--------------------------------');
  lines.push(`Subtotal       ${rupiah(subtotal).padStart(15)}`);
  if (diskon > 0) lines.push(`Diskon         ${('-' + rupiah(diskon)).padStart(15)}`);
  lines.push(`TOTAL          ${rupiah(total).padStart(15)}`);
  lines.push(`Bayar (${({cash:'Tunai',qris:'QRIS',transfer:'Transfer',kartu:'Debit'})[tender]})`);
  lines.push('--------------------------------');
  lines.push('   Terima kasih atas kunjungan');
  lines.push('       Selamat berbelanja!');
  return lines.join('\n');
}

Object.assign(window, { Kasir });
