// POS screen — order taking
// อัปเดต: submit ขายจริงไปที่ Cloudflare Workers API

const POS = ({ tweaks }) => {
  const { MENU, MILK_OPTIONS, SWEET_LEVELS } = window.BFData;
  const [orderType,    setOrderType]    = React.useState('dine');
  const [cat,          setCat]          = React.useState('all');
  const [cart,         setCart]         = React.useState([]);
  const [selectedLine, setSelectedLine] = React.useState(null);
  const [flash,        setFlash]        = React.useState(null);
  const [paying,       setPaying]       = React.useState(false);
  const [lastReceipt,  setLastReceipt]  = React.useState(null);
  const [mobileCartOpen, setMobileCartOpen] = React.useState(false);

  // Popular chips — จาก bestsellers ของ dashboard API
  const popular = React.useMemo(() => {
    const bs = window.BFData._dash?.bestsellers || [];
    return bs
      .slice(0, 4)
      .map(b => MENU.find(m => m.name === b.name))
      .filter(Boolean);
  }, []);

  const filteredMenu = React.useMemo(() => {
    if (cat === 'all')   return MENU.filter(m => m.cat !== 'addon');
    if (cat === 'addon') return MENU.filter(m => m.cat === 'addon');
    return MENU.filter(m => m.cat === cat);
  }, [cat, MENU]);

  const addItem = (item) => {
    const line = {
      key:            Date.now() + Math.random(),
      menu_id:        item.id,     // integer ID จาก DB — ใช้ส่ง API
      id:             item.id,
      name:           item.name,
      price:          item.price,
      delivery_price: item.delivery_price || item.price,  // ราคา Delivery (Grab)
      qty:            1,
      milk:           item.cat === 'addon' ? null : 'fresh',
      sweet:          item.cat === 'addon' ? null : 25,
      note:           '',
      temp:           item.temp,
      tone:           item.tone,
    };
    setCart(c => [...c, line]);
    setSelectedLine(line.key);
    setFlash(item.id);
    setTimeout(() => setFlash(null), 350);
  };

  const updateLine = (key, patch) =>
    setCart(c => c.map(l => l.key === key ? { ...l, ...patch } : l));
  const removeLine = (key) => {
    setCart(c => c.filter(l => l.key !== key));
    if (selectedLine === key) setSelectedLine(null);
  };

  const lineTotal = (l) => {
    const milkExtra = MILK_OPTIONS.find(m => m.id === l.milk)?.extra || 0;
    const basePrice = orderType === 'deli' ? l.delivery_price : l.price;
    return (basePrice + milkExtra) * l.qty;
  };
  const cartTotal = cart.reduce((s, l) => s + lineTotal(l), 0);
  const cartCount = cart.reduce((s, l) => s + l.qty, 0);
  const selected  = cart.find(l => l.key === selectedLine);

  const handleComplete = async (received, change, payMethod) => {
    setPaying(false);
    setFlash('paid');
    setLastReceipt({ total: cartTotal, received, change, count: cartCount });

    // บันทึกการขายไปที่ API
    try {
      await window.BFApi.recordSale(cart, orderType, payMethod, '');
      // รีโหลด dashboard data เบื้องหลัง
      window.BFApi.reloadDash().catch(() => {});
    } catch (e) {
      console.error('recordSale error:', e);
    }

    setTimeout(() => {
      setCart([]);
      setSelectedLine(null);
      setFlash(null);
      setLastReceipt(null);
    }, 1800);
  };

  return (
    <div className="bf-pos" data-density={tweaks.density}>
      {/* LEFT: menu */}
      <div className="bf-pos-left">
        <header className="bf-pos-header">
          <div className="bf-order-type">
            <button data-active={orderType === 'dine'} onClick={() => setOrderType('dine')}>Dine in</button>
            <button data-active={orderType === 'take'} onClick={() => setOrderType('take')}>Takeaway</button>
            <button data-active={orderType === 'deli'} onClick={() => setOrderType('deli')}>Delivery</button>
          </div>

          {tweaks.showPopular && popular.length > 0 && (
            <div className="bf-popular">
              <span className="bf-popular-label">ขายดี</span>
              {popular.map(p => (
                <button key={p.id} className="bf-popular-chip" onClick={() => addItem(p)}>
                  <TempBadge temp={p.temp} />
                  <span>{p.name}</span>
                </button>
              ))}
            </div>
          )}
        </header>

        <div className="bf-cat-tabs">
          {[
            { id: 'all',     label: 'ทั้งหมด' },
            { id: 'hot',     label: 'ร้อน'    },
            { id: 'cold',    label: 'เย็น'    },
            { id: 'special', label: 'พิเศษ'   },
            { id: 'addon',   label: 'เพิ่ม'   },
          ].map(c => (
            <button
              key={c.id}
              className={`bf-cat-tab ${cat === c.id ? 'is-active' : ''}`}
              onClick={() => setCat(c.id)}
            >
              {c.label}
            </button>
          ))}
        </div>

        <div className={`bf-menu-grid bf-grid-${tweaks.gridStyle}`}>
          {filteredMenu.map(m => (
            <button
              key={m.id}
              className={`bf-menu-tile ${flash === m.id ? 'is-flash' : ''}`}
              onClick={() => addItem(m)}
            >
              {tweaks.gridStyle !== 'iconic' && (
                <div className="bf-menu-img" style={{ background: TONE_BG[m.tone] || TONE_BG.black }}>
                  <div className="bf-menu-img-stripes" />
                  {m.cat !== 'addon' && (
                    <div className="bf-menu-glyph">
                      {m.temp === 'hot' ? '☕' : m.tone === 'matcha' ? '🍵' : '🧋'}
                    </div>
                  )}
                </div>
              )}
              <div className="bf-menu-meta">
                <div className="bf-menu-name">{m.name}</div>
                <div className="bf-menu-bottom">
                  <TempBadge temp={m.temp} />
                  <span className="bf-menu-price">
                    {orderType === 'deli' && m.delivery_price && m.delivery_price !== m.price
                      ? `฿${m.delivery_price}`
                      : `฿${m.price}`}
                  </span>
                </div>
              </div>
            </button>
          ))}
        </div>
      </div>

      {/* RIGHT: cart */}
      <aside className="bf-pos-right" data-open={String(mobileCartOpen)}>

        {/* ── Mobile bar (visible only on phone) ── */}
        <div className="bf-mobile-bar" onClick={() => setMobileCartOpen(o => !o)}>
          <div className="bf-mobile-bar-handle" />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div className="bf-eyebrow" style={{ fontSize: 10 }}>Order #{String(Date.now()).slice(-4)}</div>
            <div style={{ fontFamily: 'var(--bf-serif)', fontSize: 18, fontWeight: 600, lineHeight: 1.2 }}>
              {cartCount === 0 ? 'ออเดอร์ว่าง' : `${cartCount} แก้ว`}
            </div>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexShrink: 0 }}>
            <span style={{ fontFamily: 'Inter, sans-serif', fontSize: 22, fontWeight: 600, color: 'var(--bf-brand)', letterSpacing: '-0.01em' }}>
              {baht(cartTotal)}
            </span>
            <button
              className="bf-btn bf-btn-primary"
              style={{ padding: '8px 14px', fontSize: 12 }}
              disabled={!cart.length}
              onClick={(e) => { e.stopPropagation(); setPaying(true); }}
            >
              ชำระ
            </button>
          </div>
        </div>

        {/* ── Desktop cart head (hidden on mobile) ── */}
        <header className="bf-cart-head">
          <div>
            <div className="bf-eyebrow">Order #{String(Date.now()).slice(-4)}</div>
            <h2 className="bf-cart-title">{cartCount === 0 ? 'ออเดอร์ว่าง' : `${cartCount} แก้ว`}</h2>
          </div>
          <div className="bf-cart-meta">
            {orderType === 'dine' ? 'Dine in' : orderType === 'take' ? 'Takeaway' : 'Delivery'}
          </div>
        </header>

        <div className="bf-cart-list">
          {cart.length === 0 ? (
            <EmptyState
              icon={<Logo size={32} color="#c9bca0" />}
              title="แตะเมนูเพื่อเริ่มออเดอร์"
              hint="หรือใช้ Quick-add ที่ขายดี"
            />
          ) : (
            cart.map(l => (
              <CartLine
                key={l.key}
                line={l}
                selected={selectedLine === l.key}
                onSelect={() => setSelectedLine(l.key === selectedLine ? null : l.key)}
                onChange={p => updateLine(l.key, p)}
                onRemove={() => removeLine(l.key)}
                lineTotal={lineTotal(l)}
              />
            ))
          )}

          {/* ModPanel อยู่ใน scroll area — ไม่ดันปุ่มชำระเงินออก */}
          {selected && selected.milk !== null && (
            <ModPanel line={selected} onChange={p => updateLine(selected.key, p)} />
          )}
        </div>

        <footer className="bf-cart-foot">
          <div className="bf-total-row">
            <span>Total</span>
            <span className="bf-total-value">{baht(cartTotal)}</span>
          </div>
          <div className="bf-cart-actions">
            <button
              className="bf-btn bf-btn-ghost"
              disabled={!cart.length}
              onClick={() => { setCart([]); setSelectedLine(null); }}
            >
              ยกเลิก
            </button>
            <button
              className="bf-btn bf-btn-primary"
              disabled={!cart.length}
              onClick={() => setPaying(true)}
            >
              ชำระเงิน
            </button>
          </div>
        </footer>

        {flash === 'paid' && (
          <div className="bf-pay-flash">
            <Logo size={36} color="#f7f3ec" />
            <div>ชำระเงินสำเร็จ</div>
            {lastReceipt && lastReceipt.change > 0 && (
              <div className="bf-pay-flash-change">
                <div className="bf-eyebrow" style={{ color: 'rgba(247,243,236,0.6)' }}>เงินทอน</div>
                <div className="bf-pay-flash-amt">{baht(lastReceipt.change)}</div>
              </div>
            )}
          </div>
        )}

        {paying && (
          <PaymentModal
            total={cartTotal}
            cartCount={cartCount}
            orderType={orderType}
            onCancel={() => setPaying(false)}
            onComplete={handleComplete}
          />
        )}
      </aside>
    </div>
  );
};

// ── Cart line ──────────────────────────────────────────────────────────────────
const CartLine = ({ line, selected, onSelect, onChange, onRemove, lineTotal }) => {
  const { MILK_OPTIONS } = window.BFData;
  const milkLabel = MILK_OPTIONS.find(m => m.id === line.milk)?.label;
  return (
    <div className={`bf-line ${selected ? 'is-selected' : ''}`} onClick={onSelect}>
      <div className="bf-line-swatch" style={{ background: TONE_BG[line.tone] || TONE_BG.black }} />
      <div className="bf-line-body">
        <div className="bf-line-top">
          <div className="bf-line-name">{line.name}</div>
          <button className="bf-line-x" onClick={e => { e.stopPropagation(); onRemove(); }} aria-label="remove">×</button>
        </div>
        {line.milk !== null && (
          <div className="bf-line-mods">{milkLabel} · หวาน {line.sweet}%</div>
        )}
        <div className="bf-line-bottom">
          <div onClick={e => e.stopPropagation()}>
            <Stepper value={line.qty} onChange={v => v === 0 ? onRemove() : onChange({ qty: v })} min={1} />
          </div>
          <div className="bf-line-price">{baht(lineTotal)}</div>
        </div>
      </div>
    </div>
  );
};

// ── Mod panel ──────────────────────────────────────────────────────────────────
const ModPanel = ({ line, onChange }) => {
  const { MILK_OPTIONS, SWEET_LEVELS } = window.BFData;
  const sweetCopy = line.sweet === 0 ? 'ไม่หวาน'
    : `หวาน ${line.sweet}% · ${(line.sweet * 0.3).toFixed(1)}ml น้ำเชื่อม`;
  return (
    <div className="bf-mod-panel">
      <div className="bf-mod-row">
        <div className="bf-mod-label">นม</div>
        <div className="bf-mod-opts">
          {MILK_OPTIONS.map(m => (
            <Pill key={m.id} active={line.milk === m.id} onClick={() => onChange({ milk: m.id })}>
              {m.label}{m.extra > 0 && <span className="bf-mod-extra"> +{m.extra}</span>}
            </Pill>
          ))}
        </div>
      </div>
      <div className="bf-mod-row">
        <div className="bf-mod-label">หวาน</div>
        <div className="bf-mod-opts">
          {SWEET_LEVELS.map(v => (
            <Pill key={v} active={line.sweet === v} onClick={() => onChange({ sweet: v })}>
              {v}%
            </Pill>
          ))}
        </div>
      </div>
      <div className="bf-barista-note">
        <div className="bf-barista-head">Barista note</div>
        <div className="bf-barista-body">{sweetCopy}</div>
      </div>
    </div>
  );
};

window.POS = POS;

// ── Payment modal ──────────────────────────────────────────────────────────────
const PaymentModal = ({ total, cartCount, orderType, onCancel, onComplete }) => {
  const [received,   setReceived]   = React.useState('');
  const [payMethod,  setPayMethod]  = React.useState('cash');
  const inputRef = React.useRef(null);

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

  const receivedNum = Number(received) || 0;
  const change = receivedNum - total;
  const ready  = receivedNum >= total;

  const suggestions = React.useMemo(() => {
    const set = new Set([total]);
    [50, 100, 500, 1000].forEach(step => {
      const n = Math.ceil(total / step) * step;
      if (n >= total) set.add(n);
    });
    return Array.from(set).sort((a, b) => a - b).slice(0, 5);
  }, [total]);

  const orderTypeLabel = orderType === 'dine' ? 'Dine in'
                       : orderType === 'take' ? 'Takeaway' : 'Delivery';

  React.useEffect(() => {
    const onKey = e => {
      if (e.key === 'Escape') onCancel();
      if (e.key === 'Enter' && ready) onComplete(receivedNum, change, payMethod);
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [ready, receivedNum, change, payMethod]);

  return (
    <div className="bf-pay-overlay" onClick={onCancel}>
      <div className="bf-pay-sheet" onClick={e => e.stopPropagation()}>
        <header className="bf-pay-head">
          <div>
            <div className="bf-eyebrow">รับชำระเงิน</div>
            <h2 className="bf-pay-title">ยอดที่ต้องจ่าย</h2>
          </div>
          <button className="bf-pay-close" onClick={onCancel} aria-label="cancel">×</button>
        </header>

        <div className="bf-pay-amount">
          <div className="bf-pay-total">{baht(total)}</div>
          <div className="bf-pay-meta">{cartCount} แก้ว · {orderTypeLabel}</div>
          {orderType === 'deli' && (() => {
            const DEL_GP = 0.30;
            const grabFee   = Math.round(total * DEL_GP);
            const netAmount = total - grabFee;
            return (
              <div style={{
                marginTop: 10, padding: '10px 14px', borderRadius: 10,
                background: 'rgba(255,160,50,0.12)', fontSize: 13,
                display: 'flex', flexDirection: 'column', gap: 4, textAlign: 'left',
              }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', color: 'var(--bf-text-2)' }}>
                  <span>ค่า Grab 30%</span>
                  <span>−{baht(grabFee)}</span>
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between', fontWeight: 700, color: 'var(--bf-text-1)' }}>
                  <span>ร้านได้จริง</span>
                  <span>{baht(netAmount)}</span>
                </div>
              </div>
            );
          })()}
        </div>

        <div className="bf-pay-method">
          <button
            className={`bf-pay-method-btn ${payMethod === 'cash' ? 'is-active' : ''}`}
            onClick={() => setPayMethod('cash')}
          >
            <span className="bf-pay-method-icon">฿</span>
            เงินสด
          </button>
          <button
            className={`bf-pay-method-btn ${payMethod === 'scan' ? 'is-active' : ''}`}
            onClick={() => setPayMethod('scan')}
          >
            <span className="bf-pay-method-icon">⊕</span>
            QR PromptPay
          </button>
        </div>

        {payMethod === 'cash' && (
          <>
            <div className="bf-pay-field">
              <label>ลูกค้าจ่ายเงิน</label>
              <div className="bf-pay-input-wrap">
                <span className="bf-pay-currency">฿</span>
                <input
                  ref={inputRef}
                  type="number"
                  min="0"
                  step="1"
                  inputMode="decimal"
                  placeholder="0"
                  value={received}
                  onChange={e => setReceived(e.target.value)}
                  className="bf-pay-input"
                />
              </div>
              <div className="bf-pay-suggest">
                {suggestions.map(n => (
                  <button
                    key={n}
                    type="button"
                    className={`bf-pay-chip ${n === total ? 'is-exact' : ''}`}
                    onClick={() => setReceived(String(n))}
                  >
                    {n === total ? 'พอดี' : `฿${n.toLocaleString('th-TH')}`}
                  </button>
                ))}
              </div>
            </div>

            <div className={`bf-pay-change ${ready ? 'is-ready' : ''} ${receivedNum > 0 && !ready ? 'is-short' : ''}`}>
              <div className="bf-pay-change-label">
                {receivedNum === 0 ? 'เงินทอน' : ready ? 'เงินทอน' : `ขาดอีก ${baht(total - receivedNum)}`}
              </div>
              <div className="bf-pay-change-value">
                {ready ? baht(change) : (receivedNum === 0 ? '—' : baht(0))}
              </div>
            </div>
          </>
        )}

        {payMethod === 'scan' && (
          <div style={{ padding: '24px 0', textAlign: 'center', color: 'var(--bf-text-2)' }}>
            <div style={{ fontSize: 48, marginBottom: 8 }}>⊕</div>
            <div>สแกน QR PromptPay</div>
            <div style={{ fontSize: 13, color: 'var(--bf-text-3)', marginTop: 4 }}>ยืนยันเมื่อรับเงินแล้ว</div>
          </div>
        )}

        <footer className="bf-pay-foot">
          <button className="bf-btn bf-btn-ghost" onClick={onCancel}>ยกเลิก</button>
          <button
            className="bf-btn bf-btn-primary"
            disabled={payMethod === 'cash' && !ready}
            onClick={() => onComplete(receivedNum, change, payMethod)}
          >
            {payMethod === 'scan' ? 'ยืนยันรับเงินแล้ว' : (ready ? `ยืนยัน · ทอน ${baht(change)}` : 'รอรับเงิน')}
          </button>
        </footer>
      </div>
    </div>
  );
};

window.PaymentModal = PaymentModal;
