// Mock data for the prototype

const BRANCHES = [];   // Cleared — admin adds branches from the console

// Membership tiers are gated by accumulated POINTS (not THB spend).
//   1 point = ฿25 spent → these thresholds equate to roughly:
//     Silver   ฿0+      (everyone starts here)
//     Gold     ฿25,000+
//     Platinum ฿125,000+
//     Diamond  ฿500,000+
const TIERS = [
  { id: 'silver',   label: 'Silver',   min: 0     },
  { id: 'gold',     label: 'Gold',     min: 1000  },
  { id: 'platinum', label: 'Platinum', min: 5000  },
  { id: 'diamond',  label: 'Diamond',  min: 20000 },
];

// Default empty member state. When a customer logs in via LINE,
// the customer app fills in name/picture from their LIFF profile.
const MEMBER = {
  id: '',
  name: '',
  nameShort: '',
  tier: 'silver',
  points: 0,
  ytdSpend: 0,
  lifetime: 0,
  homeBranch: '',
  joined: '',
  phone: '',
  email: '',
  birthday: '',
};

const ORDERS  = [];  // Cleared — populated from real transactions
const COURSES = [];  // Cleared — populated from real course purchases

const REWARDS = [
  { id: 'r1', name: 'Glow IV Drip · 30min',         cost: 8000,  category: 'Treatment',
    grant: { kind: 'session', template: 'glow-iv', qty: 1 } },
  { id: 'r2', name: 'Birthday Couture Cake',         cost: 2400,  category: 'Lifestyle',
    grant: { kind: 'voucher', value: 2400 } },
  { id: 'r3', name: 'Hydrafacial · Express',         cost: 6000,  category: 'Treatment',
    grant: { kind: 'session', template: 'hydrafacial-md', qty: 1 } },
  { id: 'r4', name: 'La Mer Crème de la Mer · 30ml', cost: 12500, category: 'Gift',
    grant: { kind: 'physical', sku: 'lamer-30' } },
  { id: 'r5', name: 'Meso Glow · +1 session bonus',  cost: 5000,  category: 'Treatment',
    grant: { kind: 'session', template: 'meso-glow', qty: 1 } },
];

// ─────────────────────────────────────────────────────────────
// Staff & doctors — used by the accounting export and commission
// calculations. DF % is doctor fee, COMM % is staff commission.
// ─────────────────────────────────────────────────────────────
const DOCTORS = [
  { id: 'dr-pim',   name: 'Dr. Pim Charoenchai',  branch: 'thonglor',   df: 18, specialty: 'Injectable' },
  { id: 'dr-athit', name: 'Dr. Athit Roongruang', branch: 'thonglor',   df: 20, specialty: 'Laser' },
  { id: 'dr-noon',  name: 'Dr. Noon Suksawat',    branch: 'phromphong', df: 18, specialty: 'Facial' },
  { id: 'dr-orn',   name: 'Dr. Orn Phukamsai',    branch: 'siam',       df: 16, specialty: 'Injectable' },
  { id: 'dr-tan',   name: 'Dr. Tan Yodphakdee',   branch: 'central-wd', df: 17, specialty: 'Laser' },
  { id: 'dr-mai',   name: 'Dr. Mai Phongchana',   branch: 'asoke',      df: 18, specialty: 'Facial' },
];

const STAFF = [
  { id: 'staff-01', name: 'Praew Ratanasiri',   branch: 'thonglor',   role: 'Senior Consultant', commission: 3 },
  { id: 'staff-02', name: 'Bow Saetang',         branch: 'thonglor',   role: 'Consultant',         commission: 2 },
  { id: 'staff-03', name: 'Pim Chanwattana',    branch: 'phromphong', role: 'Senior Consultant', commission: 3 },
  { id: 'staff-04', name: 'Min Aroonjit',       branch: 'siam',       role: 'Consultant',         commission: 2 },
  { id: 'staff-05', name: 'Tukta Suriyo',       branch: 'central-wd', role: 'Consultant',         commission: 2 },
];

// Accounting transactions — one per treatment line.
const TRANSACTIONS = [];  // Cleared — wire to D1 when accounting is ready

// Legacy data record — the row that gets auto-merged when a new login
// matches an existing phone number. Demoed in the Legacy Merge screen.
const LEGACY_MATCH = {
  id: 'L-008412',
  source: 'Thonglor 2018 customer log',
  fullName: 'Apinya Suwanchart',
  phone: '+66 89 ••• 4127',
  lastVisit: 'Dec 2024',
  pointsBalance: 12480,
  courses: [
    { name: 'Meso Glow', remaining: '2 of 5 sessions' },
    { name: 'Botulinum', remaining: '36 of 100 units' },
  ],
  visits: 47,
  lifetimeSpend: 1240000,
};

function fmtTHB(n) { return '฿' + n.toLocaleString('en-US'); }
function fmtPts(n) { return n.toLocaleString('en-US') + ' pts'; }

function branchName(id) { return (BRANCHES.find(b => b.id === id) || {}).name || id; }
function doctorById(id) { return DOCTORS.find(d => d.id === id) || {}; }
function staffById(id) { return STAFF.find(s => s.id === id) || {}; }
function tierObj(id) { return TIERS.find(t => t.id === id) || TIERS[0]; }

// Auto-compute the customer's current tier from their points balance.
// Walk the tier list ascending; the highest tier whose `min` is <= pts wins.
function tierForPoints(pts) {
  const n = Number(pts || 0);
  let current = TIERS[0];
  for (const t of TIERS) {
    if (n >= t.min) current = t;
    else break;
  }
  return current;
}

// Progress toward the next tier — based on POINTS now, not THB lifetime.
function tierProgress(member) {
  const pts = Number(member?.points ?? member?.points_balance ?? 0);
  const current = tierForPoints(pts);
  const idx = TIERS.indexOf(current);
  const next = TIERS[idx + 1] || null;

  if (!next) {
    return {
      current, currentLabel: current.label,
      pct: 1, toNext: 0,
      nextLabel: 'Top tier', nextTier: null,
    };
  }
  const range = next.min - current.min;
  const into  = pts - current.min;
  return {
    current, currentLabel: current.label,
    pct: Math.min(1, Math.max(0, into / range)),
    toNext: Math.max(0, next.min - pts),
    nextLabel: next.label, nextTier: next,
  };
}

// Apply commission/DF formula to a transaction row.
//   DF       = revenue × doctor.df%
//   COMM     = revenue × staff.commission%
//   GROSS    = revenue − cogs − vat − df − comm
function computeRow(tx) {
  const d = doctorById(tx.doctorId);
  const s = staffById(tx.staffId);
  const df = Math.round(tx.revenue * (d.df || 0) / 100);
  const comm = Math.round(tx.revenue * (s.commission || 0) / 100);
  const gross = tx.revenue - tx.cogs - tx.vat - df - comm;
  return { ...tx, doctor: d, staff: s, df, comm, gross };
}

Object.assign(window, {
  BRANCHES, TIERS, MEMBER, ORDERS, COURSES, REWARDS,
  DOCTORS, STAFF, TRANSACTIONS, LEGACY_MATCH,
  fmtTHB, fmtPts, branchName, doctorById, staffById,
  tierObj, tierForPoints, tierProgress, computeRow,
});
