// data.jsx — Butterfly Coffee POS: API client
// แทนที่ mock data ด้วย real API calls ไปที่ Cloudflare Workers

const API_BASE = 'https://butterfly-coffee.butterfly-coffee.workers.dev';

// ── Static config ──────────────────────────────────────────────────────────────
const MILK_OPTIONS = [
  { id: 'fresh',   label: 'นมสด',         extra: 0  },
  { id: 'oat',     label: 'นมโอ๊ต',       extra: 15 },
  { id: 'almond',  label: 'นมอัลมอนด์',   extra: 15 },
  { id: 'soy',     label: 'นมถั่วเหลือง', extra: 10 },
];

const SWEET_LEVELS = [0, 25, 50, 75, 100, 125];

const LOSS_TYPES = [
  'ออเดอร์ผิด', 'หมดอายุ', 'เสียหายจากโรงงาน',
  'เมล็ดกาแฟเสีย', 'ทำหก', 'แจกพนักงาน', 'อื่นๆ',
];

const THAI_DAYS = ['อา', 'จ', 'อ', 'พ', 'พฤ', 'ศ', 'ส'];

// ── Helper functions ───────────────────────────────────────────────────────────
function thaiDay(dateStr) {
  const d = new Date(dateStr + 'T12:00:00');
  return THAI_DAYS[d.getDay()];
}

function todayStr() {
  return new Date().toLocaleDateString('sv-SE', { timeZone: 'Asia/Bangkok' });
}

// กำหนด visual props (cat/temp/tone) จากชื่อเมนูภาษาไทย
function deriveVisualProps(name) {
  const isHot = name.includes('ร้อน') || name.includes('อุ่น');

  let tone = 'black';
  if      (name.includes('ลาเต้') || name.includes('คาปูชิโน่'))       tone = 'milky';
  else if (name.includes('มอคค่า') || name.includes('โกโก้'))          tone = 'chocolate';
  else if (name.includes('ชาเขียว') || name.includes('มัทฉะ'))         tone = 'matcha';
  else if (name.includes('ชาไทย'))                                       tone = 'tea';
  else if (name.includes('เอสเปรสโซ่'))                                 tone = 'espresso';

  let cat = 'special';
  if (isHot) cat = 'hot';
  else if (
    name.includes('เย็น') ||
    ['เอสเปรสโซ่','ลาเต้','อเมริกาโน่','คาปูชิโน่','มอคค่า'].some(k => name.includes(k))
  ) cat = 'cold';

  return { temp: isHot ? 'hot' : 'cold', tone, cat };
}

// คืนค่า tone จากชื่อเมนู (ใช้ใน dashboard ranking)
function toneForName(name) {
  const m = (window.BFData?.MENU || []).find(m => m.name === name);
  return m ? m.tone : 'black';
}
window.toneForName = toneForName;

// ── API fetch helper ───────────────────────────────────────────────────────────
async function apiFetch(path, options = {}) {
  const res = await fetch(API_BASE + path, {
    headers: { 'Content-Type': 'application/json' },
    ...options,
  });
  const data = await res.json();
  if (!res.ok) throw new Error(data.error || `API error ${res.status}`);
  return data;
}

// ── Main initializer — เรียกครั้งเดียวตอนโหลดแอป ──────────────────────────────
async function initBFData() {
  const [menus, dash, purchases, losses] = await Promise.all([
    apiFetch('/api/menus'),
    apiFetch('/api/dashboard'),
    apiFetch('/api/records/purchases'),
    apiFetch('/api/records/losses'),
  ]);

  // Normalize MENU — เพิ่ม visual props
  const MENU = menus.map(m => ({
    ...m,
    ...deriveVisualProps(m.name),
  }));

  // Normalize SALES_HISTORY จาก chart7 (สำหรับ POS popular ใช้ bestsellers แทน)
  const SALES_HISTORY = (dash.chart7 || []).map(d => ({
    date:    d.date,
    day:     thaiDay(d.date),
    revenue: d.revenue || 0,
    cost:    d.cost    || 0,
    cups:    d.cups    || 0,
    items:   {},
  }));

  // Normalize INVENTORY
  const INVENTORY = (dash.inventory || []).map(i => ({
    id:        i.id,
    name:      i.name,
    unit:      i.unit,
    stock:     i.stock,
    perDay:    i.perDay,
    days:      i.days,
    threshold: i.threshold,
    status:    i.status,
  }));

  // Normalize PURCHASES
  const PURCHASES = purchases.map(p => ({
    id:    p.id,
    date:  p.purchase_date,
    item:  p.ingredient_name,
    qty:   p.qty,
    unit:  p.unit || '',
    total: p.total_price,
    ingredient_id: p.ingredient_id,
  }));

  // Normalize LOSSES
  const LOSSES = losses.map(l => ({
    id:     l.id,
    date:   l.loss_date,
    type:   l.loss_type,
    detail: l.detail,
    value:  l.amount,
    note:   l.note || '',
  }));

  window.BFData = {
    MENU,
    MILK_OPTIONS,
    SWEET_LEVELS,
    SALES_HISTORY,
    HOURLY_TODAY: dash.hourly || [],
    INVENTORY,
    PURCHASES,
    LOSSES,
    LOSS_TYPES,
    _dash:  dash,       // raw dashboard data
    _today: todayStr(),
  };

  return window.BFData;
}

// ── API actions — เรียกจาก component ──────────────────────────────────────────
window.BFApi = {
  // POST /api/sales — บันทึกการขาย
  async recordSale(cart, orderType, payMethod, note = '') {
    const saleType = orderType === 'dine' ? 'ทานที่ร้าน'
                   : orderType === 'take' ? 'Takeaway' : 'Delivery';

    const isDelivery = orderType === 'deli';
    const cartPayload = cart.map(line => {
      const milkExtra = (window.BFData.MILK_OPTIONS.find(m => m.id === line.milk)?.extra || 0);
      // Delivery ใช้ delivery_price (ราคา Grab) แทน price ปกติ
      const basePrice = isDelivery ? (line.delivery_price || line.price) : line.price;
      const unitPrice = basePrice + milkExtra;
      return {
        menu_id:   line.menu_id,
        menu_name: line.name,
        qty:       line.qty,
        unit_price: unitPrice,
        sweet_pct:  line.sweet !== null ? line.sweet : 100,
        alt_milk:   line.milk !== 'fresh' && line.milk !== null,
      };
    });

    return apiFetch('/api/sales', {
      method: 'POST',
      body: JSON.stringify({
        date:      window.BFData._today,
        cart:      cartPayload,
        sale_type: saleType,
        pay_method: payMethod,
        note,
      }),
    });
  },

  // POST /api/records/purchases
  async addPurchase(data) {
    return apiFetch('/api/records/purchases', {
      method: 'POST',
      body: JSON.stringify(data),
    });
  },

  // POST /api/records/losses
  async addLoss(data) {
    return apiFetch('/api/records/losses', {
      method: 'POST',
      body: JSON.stringify(data),
    });
  },

  // โหลด dashboard ใหม่หลังจากบันทึกข้อมูล
  async reloadDash() {
    const dash = await apiFetch('/api/dashboard');
    window.BFData._dash = dash;
    window.BFData.HOURLY_TODAY = dash.hourly || [];
    window.BFData.INVENTORY = (dash.inventory || []).map(i => ({
      id: i.id, name: i.name, unit: i.unit,
      stock: i.stock, perDay: i.perDay, days: i.days,
      threshold: i.threshold, status: i.status,
    }));
    return dash;
  },
};

window.initBFData = initBFData;
