// ============ Pricing Engine ============
// คำนวณราคาขายเป้าหมายจาก GP% เป้าหมาย + แสดงสถานะแต่ละเมนู

function PricingPage({ go }) {
  const { fdb: db, settings, upsert, flash } = useData();
  const [targetGP, setTargetGP] = React.useState(Number(settings.estGP) || 0.65);
  const [search, setSearch] = React.useState('');
  const [editId, setEditId] = React.useState(null);
  const [editPrice, setEditPrice] = React.useState('');

  const menus = React.useMemo(() => {
    return (db.menus || [])
      .filter(m => m.status !== 'inactive')
      .map(m => {
        const cost = Number(m.cost) || 0;
        const price = Number(m.price) || 0;
        const gp = price > 0 ? (price - cost) / price : null;
        const recPrice = cost > 0 ? Math.ceil(cost / (1 - targetGP) / 5) * 5 : null; // ปัดขึ้นทีละ 5 บาท
        const status = gp === null ? 'no-price'
          : gp >= targetGP ? 'ok'
          : gp >= targetGP - 0.1 ? 'warn'
          : 'low';
        return { ...m, cost, price, gp, recPrice, status };
      })
      .filter(m => !search || m.name.toLowerCase().includes(search.toLowerCase()))
      .sort((a, b) => {
        const order = { low: 0, warn: 1, 'no-price': 2, ok: 3 };
        return (order[a.status] ?? 9) - (order[b.status] ?? 9);
      });
  }, [db.menus, targetGP, search]);

  const stats = React.useMemo(() => {
    const withCost = menus.filter(m => m.cost > 0);
    return {
      total: menus.length,
      ok: menus.filter(m => m.status === 'ok').length,
      warn: menus.filter(m => m.status === 'warn').length,
      low: menus.filter(m => m.status === 'low').length,
      noPrice: menus.filter(m => m.status === 'no-price').length,
      avgGP: withCost.length ? withCost.reduce((s, m) => s + (m.gp || 0), 0) / withCost.length : 0,
    };
  }, [menus]);

  const savePrice = (menu) => {
    const p = Number(editPrice);
    if (!p || p <= 0) { flash('ราคาต้องมากกว่า 0', 'err'); return; }
    upsert('menus', { ...menu, price: p });
    flash(`อัปเดตราคา ${menu.name} → ฿${p} แล้ว`);
    setEditId(null);
  };

  const pct = v => v === null ? '–' : (v * 100).toFixed(1) + '%';
  const baht = v => v ? '฿' + Number(v).toLocaleString('th-TH') : '–';

  const statusColor = { ok: 'var(--green)', warn: 'var(--orange)', low: 'var(--red)', 'no-price': 'var(--ink-3)' };
  const statusLabel = { ok: 'ผ่าน', warn: 'ใกล้ต่ำ', low: 'ต่ำเกิน', 'no-price': 'ยังไม่ตั้งราคา' };

  return (
    <div style={{ maxWidth: 800, margin: '0 auto', padding: '0 0 80px' }}>
      {/* Summary Cards */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 10, marginBottom: 20 }}>
        {[
          { label: 'GP เฉลี่ย', value: pct(stats.avgGP), color: stats.avgGP >= targetGP ? 'var(--green)' : 'var(--red)' },
          { label: '✅ ผ่านเกณฑ์', value: stats.ok, color: 'var(--green)' },
          { label: '⚠️ ใกล้ต่ำ', value: stats.warn, color: 'var(--orange)' },
          { label: '❌ ต่ำเกิน', value: stats.low, color: 'var(--red)' },
        ].map(c => (
          <div key={c.label} style={{ background: 'var(--surface)', borderRadius: 14, padding: '14px 12px', textAlign: 'center', boxShadow: 'var(--shadow)' }}>
            <div style={{ fontSize: 22, fontWeight: 700, color: c.color }}>{c.value}</div>
            <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 2 }}>{c.label}</div>
          </div>
        ))}
      </div>

      {/* Controls */}
      <div style={{ display: 'flex', gap: 12, marginBottom: 16, flexWrap: 'wrap' }}>
        <div style={{ flex: 1, minWidth: 200 }}>
          <Input placeholder="ค้นหาเมนู..." value={search} onChange={e => setSearch(e.target.value)} />
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, background: 'var(--surface)', borderRadius: 10, padding: '8px 14px', boxShadow: 'var(--shadow)' }}>
          <span style={{ fontSize: 13, color: 'var(--ink-2)', whiteSpace: 'nowrap' }}>เป้า GP%</span>
          <input type="number" min="0.1" max="0.99" step="0.01"
            value={(targetGP * 100).toFixed(0)}
            onChange={e => setTargetGP(Math.min(0.99, Math.max(0.1, Number(e.target.value) / 100)))}
            style={{ width: 56, border: '1px solid var(--line-2)', borderRadius: 7, padding: '5px 8px', fontSize: 14, textAlign: 'center' }}
          />
          <span style={{ fontSize: 13 }}>%</span>
        </div>
      </div>

      {/* Table */}
      <div style={{ background: 'var(--surface)', borderRadius: 16, overflow: 'hidden', boxShadow: 'var(--shadow)' }}>
        {menus.length === 0 && (
          <div style={{ padding: 40, textAlign: 'center', color: 'var(--ink-3)' }}>ไม่พบเมนู</div>
        )}
        {menus.map((m, i) => (
          <div key={m.id} style={{
            padding: '13px 16px',
            borderBottom: i < menus.length - 1 ? '1px solid var(--line-2)' : 'none',
            display: 'flex', alignItems: 'center', gap: 12
          }}>
            {/* Status dot */}
            <div style={{ width: 8, height: 8, borderRadius: '50%', background: statusColor[m.status], flexShrink: 0 }} />

            {/* Name & status */}
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontWeight: 500, fontSize: 14, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{m.name}</div>
              <div style={{ fontSize: 12, color: statusColor[m.status], marginTop: 1 }}>{statusLabel[m.status]}</div>
            </div>

            {/* Cost */}
            <div style={{ textAlign: 'right', minWidth: 60 }}>
              <div style={{ fontSize: 13, color: 'var(--ink-2)' }}>ต้นทุน</div>
              <div style={{ fontSize: 14, fontWeight: 500 }}>{baht(m.cost)}</div>
            </div>

            {/* Current GP */}
            <div style={{ textAlign: 'right', minWidth: 54 }}>
              <div style={{ fontSize: 13, color: 'var(--ink-2)' }}>GP%</div>
              <div style={{ fontSize: 14, fontWeight: 600, color: statusColor[m.status] }}>{pct(m.gp)}</div>
            </div>

            {/* Price / edit */}
            <div style={{ textAlign: 'right', minWidth: 90 }}>
              {editId === m.id ? (
                <div style={{ display: 'flex', gap: 4, alignItems: 'center' }}>
                  <input type="number" autoFocus value={editPrice}
                    onChange={e => setEditPrice(e.target.value)}
                    onKeyDown={e => { if (e.key === 'Enter') savePrice(m); if (e.key === 'Escape') setEditId(null); }}
                    style={{ width: 72, border: '1px solid var(--accent)', borderRadius: 7, padding: '5px 8px', fontSize: 14, textAlign: 'right' }}
                  />
                  <button onClick={() => savePrice(m)} style={{ background: 'var(--accent)', color: '#fff', border: 'none', borderRadius: 7, padding: '5px 8px', cursor: 'pointer', fontSize: 13 }}>✓</button>
                  <button onClick={() => setEditId(null)} style={{ background: 'var(--chip)', border: 'none', borderRadius: 7, padding: '5px 8px', cursor: 'pointer', fontSize: 13 }}>✕</button>
                </div>
              ) : (
                <div>
                  <div style={{ fontSize: 13, color: 'var(--ink-2)' }}>ราคาขาย</div>
                  <button onClick={() => { setEditId(m.id); setEditPrice(String(m.price || m.recPrice || '')); }}
                    style={{ fontSize: 14, fontWeight: 600, background: 'none', border: 'none', cursor: 'pointer', color: m.price ? 'var(--ink)' : 'var(--accent)', padding: 0 }}>
                    {m.price ? baht(m.price) : '+ ตั้งราคา'}
                  </button>
                </div>
              )}
            </div>

            {/* Recommended price */}
            {m.recPrice && m.status !== 'ok' && editId !== m.id && (
              <div style={{ textAlign: 'right', minWidth: 76 }}>
                <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>แนะนำ</div>
                <button onClick={() => { setEditId(m.id); setEditPrice(String(m.recPrice)); }}
                  style={{ fontSize: 13, fontWeight: 600, color: 'var(--accent)', background: 'none', border: 'none', cursor: 'pointer', padding: 0 }}>
                  {baht(m.recPrice)}
                </button>
              </div>
            )}
          </div>
        ))}
      </div>

      {stats.noPrice > 0 && (
        <div style={{ marginTop: 12, padding: '10px 16px', background: 'var(--chip)', borderRadius: 10, fontSize: 13, color: 'var(--ink-2)' }}>
          ℹ️ มี {stats.noPrice} เมนูที่ยังไม่ได้ตั้งราคา — ไปเพิ่มที่หน้าเมนู & สูตร
        </div>
      )}
    </div>
  );
}

Object.assign(window, { PricingPage });
