// ---------- Seed data ----------
const FLAVORS = [
  { id:'f1', name:'Signature Pistachio', color:'#7A9F5F', color2:'#B4C896', emoji:'🌱', price:2500, desc:'Pistachio and local milk, slow-roasted in N’Djamena with milk from the Chari plains.', signature:true },
  { id:'f2', name:'Strawberry Bliss',   color:'#C85A6A', color2:'#E8A2B0', emoji:'🍓', price:2000, desc:'Market-fresh strawberries folded through the night.', signature:true },
  { id:'f3', name:'Alphonso Mango',     color:'#E2A141', color2:'#F4CE83', emoji:'🥭', price:2200, desc:'Single-origin Alphonso, zero additives, sun-ripened.', signature:true },
  { id:'f4', name:'Wild Blueberry',     color:'#6A5AAB', color2:'#A598D0', emoji:'🫐', price:2300, desc:'Forest blueberries, touch of hibiscus, long churn.', signature:true },
  { id:'f5', name:'Dark Chocolate',     color:'#4A2C1C', color2:'#8C6547', emoji:'🍫', price:2400, desc:'72% single-estate cocoa, almost bitter, all soul.' },
  { id:'f6', name:'Vanilla Madagascar', color:'#E8D4A0', color2:'#F5E8C8', emoji:'🌼', price:2000, desc:'Bourbon pods steeped for 48 hours in whole cream.' },
  { id:'f7', name:'Hibiscus Sorbet',    color:'#B03E5A', color2:'#DC8497', emoji:'🌺', price:1800, desc:'Karkadé blossoms, zero dairy, electric finish.' },
  { id:'f8', name:'Tamarind & Lime',    color:'#9F6B2E', color2:'#CFA06C', emoji:'🍋', price:1900, desc:'Sharp, sweet, local. Our staff favorite.' },
];

const CHAD_NAMES = [
  'Khalid Hybah',
  'Fatimé Ousmane', 'Achille Ndilbé', 'Khadija Abakar',
  'Idris Bongor', 'Aïcha Déby', 'Roland Nadjilem', 'Zara Hissein',
  'Bichara Youssouf', 'Mariam Saleh', 'Hassan Brahim', 'Ngarta Mbaikoua',
  'Salma Haroun', 'Tchari Djimet', 'Noura Adoum', 'Oumar Tidjani',
];

const ROLES = ['boss','production_manager','accountant','employee'];
const DEPARTMENTS = ['Production','Hybah · rue de 40m','Hybah · Dembé','Hybah · Ambsatna','Hybah · Gassi','Finance','Logistics'];

function employeeAvatarUrl(fullName) {
  const q = encodeURIComponent(fullName || 'GH');
  return `https://ui-avatars.com/api/?name=${q}&background=251a12&color=ede0cc&size=128&bold=true`;
}

/** tenure_display_mode: how long-since-start is shown in HR: months | weeks | days */
const EMPLOYEES = CHAD_NAMES.map((n, i) => ({
  id: 'u' + (i+1),
  full_name: n,
  email: (i === 0 ? 'khalid.hybah' : n.toLowerCase().replace(/\s+/g,'.').replace(/[^a-z.]/g,'')) + '@gelatohouse.app',
  role: i === 0 ? 'boss' : i < 3 ? 'production_manager' : i < 5 ? 'accountant' : 'employee',
  status: i < 10 ? 'active' : i < 13 ? 'waitlist' : 'active',
  department: DEPARTMENTS[(i + 1) % DEPARTMENTS.length],
  salary: i === 0 ? 520000 : 180000 + (i % 6) * 45000,
  phone: '+235 6' + (10000000 + i*123457).toString().slice(0,8),
  join_date: i === 0 ? '2023-01-15' : `202${3 - (i%4)}-0${(i%9)+1}-1${i%9}`,
  tenure_display_mode: i % 3 === 0 ? 'months' : i % 3 === 1 ? 'weeks' : 'days',
  emergency_contact: CHAD_NAMES[(i+4) % CHAD_NAMES.length],
  initials: n.split(' ').map(p=>p[0]).join('').slice(0,2),
  avatar_url: employeeAvatarUrl(n),
}));

/** displayUnit = how stock is stored; inputUnitsAllowed = units staff can enter for usage / restock */
const INVENTORY = [
  { id:'i1',  name:'Whole Milk',             category:'milk',       quantity: 180, displayUnit:'L',   unit:'L',   min_threshold: 60,  cost_per_unit: 850,  supplier:'Laitière du Chari',   last_restocked:'2026-04-16', inputUnitsAllowed:['L','ml'] },
  { id:'i2',  name:'Heavy Cream',            category:'milk',       quantity:  22, displayUnit:'L',   unit:'L',   min_threshold: 30,  cost_per_unit: 1800, supplier:'Laitière du Chari',   last_restocked:'2026-04-14', inputUnitsAllowed:['L','ml'] },
  { id:'i3',  name:'Cane Sugar',             category:'sugar',      quantity:  85, displayUnit:'kg',  unit:'kg',  min_threshold: 40,  cost_per_unit: 700,  supplier:'Sucaf Tchad',         last_restocked:'2026-04-12', inputUnitsAllowed:['kg','g'] },
  { id:'i4',  name:'Fresh Strawberries',     category:'ingredient', quantity:  14, displayUnit:'kg',  unit:'kg',  min_threshold: 20,  cost_per_unit: 2200, supplier:'Jardin Amtiman',      last_restocked:'2026-04-18', inputUnitsAllowed:['kg','g'] },
  { id:'i5',  name:'Alphonso Mango Purée',   category:'ingredient', quantity:   4, displayUnit:'kg',  unit:'kg',  min_threshold: 15,  cost_per_unit: 5600, supplier:'Import · Mumbai',     last_restocked:'2026-04-02', inputUnitsAllowed:['kg','g'] },
  { id:'i6',  name:'Pistachio kernels (bulk)', category:'ingredient', quantity:   9, displayUnit:'kg',  unit:'kg',  min_threshold: 10,  cost_per_unit: 14500, supplier:'Import · MEA hub',  last_restocked:'2026-04-09', inputUnitsAllowed:['kg','g'] },
  { id:'i7',  name:'Madagascar Vanilla',     category:'ingredient', quantity:   0.8, displayUnit:'kg', unit:'kg', min_threshold: 1,   cost_per_unit: 68000, supplier:'Import · Antalaha',  last_restocked:'2026-03-22', inputUnitsAllowed:['kg','g'] },
  { id:'i8',  name:'Dark Chocolate 72%',     category:'ingredient', quantity:  28, displayUnit:'kg',  unit:'kg',  min_threshold: 15,  cost_per_unit: 8200, supplier:'Import · Lyon',       last_restocked:'2026-04-11', inputUnitsAllowed:['kg','g'] },
  { id:'i9',  name:'Hibiscus (Karkadé)',     category:'ingredient', quantity:  12, displayUnit:'kg',  unit:'kg',  min_threshold: 6,   cost_per_unit: 3400, supplier:'Marché de Dembé',     last_restocked:'2026-04-15', inputUnitsAllowed:['kg','g'] },
  { id:'i10', name:'Paper Cups · 120ml',     category:'packaging',  quantity: 340, displayUnit:'pcs', unit:'pcs', min_threshold: 400, cost_per_unit: 85,   supplier:'Packo Sarl',          last_restocked:'2026-04-10', inputUnitsAllowed:['pcs'] },
  { id:'i11', name:'Wooden Spoons',          category:'packaging',  quantity: 1200, displayUnit:'pcs', unit:'pcs', min_threshold: 500, cost_per_unit: 12,  supplier:'Packo Sarl',          last_restocked:'2026-04-10', inputUnitsAllowed:['pcs'] },
  { id:'i12', name:'Lemon Zest',             category:'ingredient', quantity:   2, displayUnit:'kg',  unit:'kg',  min_threshold: 2,   cost_per_unit: 1800, supplier:'Marché de Dembé',     last_restocked:'2026-04-17', inputUnitsAllowed:['kg','g'] },
  { id:'i13', name:'Yogurt starter culture', category:'bacteria',   quantity: 450, displayUnit:'g',   unit:'g',   min_threshold: 100, cost_per_unit: 120,  supplier:'Bioferm · EU',        last_restocked:'2026-04-10', inputUnitsAllowed:['g'] },
  { id:'i14', name:'Probiotic blend (produit premier)', category:'bacteria', quantity: 620, displayUnit:'g', unit:'g', min_threshold: 200, cost_per_unit: 95, supplier:'Marché pro · NDJ', last_restocked:'2026-04-08', inputUnitsAllowed:['g'] },
];

function invDisplayUnit(item) {
  return item.displayUnit || item.unit || 'kg';
}

function stockStatus(item) {
  if (item.quantity < item.min_threshold * 0.3) return 'critical';
  if (item.quantity < item.min_threshold) return 'low';
  return 'ok';
}

/** Four Hybah boutiques + usine — stable ids for saved expense data */
const OUTLET_LOCATIONS = [
  { id: 'loc_nassara',  name: 'Hybah · rue de 40m',  shortName: '40m',      kind: 'retail' },
  { id: 'loc_dembe',    name: 'Hybah · Dembé',       shortName: 'Dembé',    kind: 'retail' },
  { id: 'loc_amrigue',  name: 'Hybah · Ambsatna',    shortName: 'Ambsatna', kind: 'retail' },
  { id: 'loc_cd',       name: 'Hybah · Gassi',       shortName: 'Gassi',    kind: 'retail' },
  { id: 'loc_usine',    name: 'Usine · production', shortName: 'Usine',    kind: 'factory' },
];

function weightGrams(amount, unit) {
  if (unit === 'kg') return amount * 1000;
  if (unit === 'g') return amount;
  return amount;
}
function gramsToUnit(g, unit) {
  if (unit === 'kg') return g / 1000;
  if (unit === 'g') return g;
  return g;
}
function volumeMl(amount, unit) {
  if (unit === 'L') return amount * 1000;
  if (unit === 'ml') return amount;
  return amount;
}
function mlToUnit(ml, unit) {
  if (unit === 'L') return ml / 1000;
  if (unit === 'ml') return ml;
  return ml;
}

/** Converts an entered amount+unit into stock display units so we can subtract/add safely */
function quantityInDisplayUnits(item, amount, inputUnit) {
  const d = invDisplayUnit(item);
  if (['kg','g'].includes(d) && ['kg','g'].includes(inputUnit)) {
    return gramsToUnit(weightGrams(amount, inputUnit), d);
  }
  if (['L','ml'].includes(d) && ['L','ml'].includes(inputUnit)) {
    return mlToUnit(volumeMl(amount, inputUnit), d);
  }
  if (d === 'pcs' && inputUnit === 'pcs') return amount;
  return null;
}

function formatInvQty(q, unit) {
  const u = unit || 'kg';
  const decimals = u === 'pcs' ? 0 : (u === 'g' ? 0 : 2);
  return new Intl.NumberFormat('fr-FR', { maximumFractionDigits: decimals, minimumFractionDigits: 0 }).format(q);
}

/** Human tenure since join_date / start (for HR display) */
function formatTenureSince(isoStart, mode) {
  if (!isoStart) return '—';
  const a = new Date(isoStart + (isoStart.length <= 10 ? 'T12:00:00' : ''));
  const b = new Date();
  if (isNaN(a.getTime())) return '—';
  const dayMs = 86400000;
  const days = Math.max(0, Math.floor((b - a) / dayMs));
  if (mode === 'days') return days + (days === 1 ? ' day' : ' days');
  if (mode === 'weeks') {
    const w = Math.floor(days / 7);
    return w + (w === 1 ? ' week' : ' weeks');
  }
  let months = (b.getFullYear() - a.getFullYear()) * 12 + (b.getMonth() - a.getMonth());
  if (b.getDate() < a.getDate()) months -= 1;
  months = Math.max(0, months);
  return months + (months === 1 ? ' month' : ' months');
}

// Production batches (seed — merged with persisted user batches in admin-store.jsx)
const __BATCHES_SEED = [];
(function seedBatches(){
  const flavorNames = FLAVORS.map(f => f.name);
  const statuses = ['completed','completed','completed','completed','in_progress','planned'];
  for (let i=0; i<18; i++) {
    const d = new Date(2026, 3, 20 - Math.floor(i*0.7));
    __BATCHES_SEED.push({
      id:'b'+(i+1),
      flavor: flavorNames[i % flavorNames.length],
      quantity_kg: 8 + (i*3) % 22,
      batch_date: d.toISOString().slice(0,10),
      produced_by: EMPLOYEES[1 + (i%3)].full_name,
      status: statuses[i % statuses.length],
      notes: i%4===0 ? 'Extra churn for event weekend.' : '',
    });
  }
})();

// Sales (last 30 days)
const SALES = [];
(function seedSales(){
  const today = new Date(2026, 3, 20);
  for (let d=30; d>=0; d--) {
    const date = new Date(today); date.setDate(today.getDate() - d);
    const weekendBoost = (date.getDay()===5 || date.getDay()===6) ? 1.6 : 1.0;
    FLAVORS.forEach((f, idx) => {
      const base = 40 + ((idx+1) * 7);
      const variance = Math.sin((d+idx)*1.3) * 12;
      const scoops = Math.max(10, Math.round((base + variance) * weekendBoost));
      SALES.push({
        id: `s${d}-${f.id}`,
        flavor: f.name,
        quantity_scoops: scoops,
        amount_fcfa: scoops * f.price,
        sale_date: date.toISOString().slice(0,10),
      });
    });
  }
})();

// Bank deposits
const DEPOSITS = [
  { id:'d1', amount_fcfa: 1850000, deposit_date:'2026-04-18', description:'Weekly revenue · Nassara + Dembé', bank_name:'Bank of Central Africa', receipt_number:'BCA-2026-0418-01', recorded_by:'Aïcha Déby' },
  { id:'d2', amount_fcfa: 920000,  deposit_date:'2026-04-15', description:'Event catering · Hilton Grand',   bank_name:'Société Générale Tchad', receipt_number:'SGT-2026-0415-09', recorded_by:'Aïcha Déby' },
  { id:'d3', amount_fcfa: 1420000, deposit_date:'2026-04-11', description:'Weekly revenue · all outlets',    bank_name:'Bank of Central Africa', receipt_number:'BCA-2026-0411-01', recorded_by:'Khadija Abakar' },
  { id:'d4', amount_fcfa: 680000,  deposit_date:'2026-04-08', description:'Wholesale · Hôtel Le Kanem',      bank_name:'Bank of Central Africa', receipt_number:'BCA-2026-0408-04', recorded_by:'Aïcha Déby' },
  { id:'d5', amount_fcfa: 1590000, deposit_date:'2026-04-04', description:'Weekly revenue',                  bank_name:'Bank of Central Africa', receipt_number:'BCA-2026-0404-01', recorded_by:'Aïcha Déby' },
  { id:'d6', amount_fcfa: 2100000, deposit_date:'2026-03-28', description:'Ramadan week revenue',            bank_name:'Société Générale Tchad', receipt_number:'SGT-2026-0328-11', recorded_by:'Khadija Abakar' },
];

const WARNINGS = [
  { id:'w1', employee_id:'u11', employee:'Hassan Brahim', reason:'Late arrival (3rd occurrence this month)', severity:'minor', issued_date:'2026-04-14', issued_by:'Khalid Hybah' },
  { id:'w2', employee_id:'u8',  employee:'Zara Hissein',  reason:'Failed to log production batch #B0189', severity:'minor', issued_date:'2026-04-02', issued_by:'Fatimé Ousmane' },
  { id:'w3', employee_id:'u12', employee:'Ngarta Mbaikoua', reason:'Hygiene protocol breach — reviewed', severity:'major', issued_date:'2026-03-22', issued_by:'Khalid Hybah' },
];

const LEAVES = [
  { id:'l1', employee_id:'u7',  employee:'Roland Nadjilem', start_date:'2026-04-28', end_date:'2026-05-02', reason:'Family wedding · Moundou', status:'pending' },
  { id:'l2', employee_id:'u9',  employee:'Bichara Youssouf', start_date:'2026-05-05', end_date:'2026-05-06', reason:'Medical', status:'pending' },
  { id:'l3', employee_id:'u5',  employee:'Idris Bongor', start_date:'2026-04-10', end_date:'2026-04-12', reason:'Personal', status:'approved' },
  { id:'l4', employee_id:'u11', employee:'Hassan Brahim', start_date:'2026-03-30', end_date:'2026-04-01', reason:'Family', status:'approved' },
];

// Waitlist users (feature requests)
const WAITLIST_USERS = [
  {
    id:'w_a', full_name:'Sadia Dingamadji', email:'sadia.d@gelatohouse.app', role:'accountant', department:'Finance',
    requested_at:'2026-04-17', phone:'+235 66 54 12 90',
    features: { view_inventory:true, view_production:true, view_sales:true, view_deposits:true, record_deposits:true, view_employees:false, hr_management:false, view_analytics:true, export_reports:true, edit_inventory:false, log_production:false }
  },
  {
    id:'w_b', full_name:'Emmanuel Koulamallah', email:'emmanuel.k@gelatohouse.app', role:'production_manager', department:'Production',
    requested_at:'2026-04-16', phone:'+235 99 12 34 56',
    features: { view_inventory:true, edit_inventory:true, view_production:true, log_production:true, view_sales:true, view_analytics:true, export_reports:false, view_deposits:false, record_deposits:false, view_employees:false, hr_management:false }
  },
  {
    id:'w_c', full_name:'Leïla Mahamat', email:'leila.m@gelatohouse.app', role:'employee', department:'Hybah · Dembé',
    requested_at:'2026-04-18', phone:'+235 66 88 22 14',
    features: { view_inventory:true, view_production:false, view_sales:false, log_production:false, edit_inventory:false, view_deposits:false, record_deposits:false, view_employees:false, hr_management:false, view_analytics:false, export_reports:false }
  },
];

const FEATURE_KEYS = [
  { key:'view_inventory',   label:'View Inventory' },
  { key:'edit_inventory',   label:'Edit / Update Inventory' },
  { key:'view_production',  label:'View Production Batches' },
  { key:'log_production',   label:'Log Production Batches' },
  { key:'view_sales',       label:'View Sales Data' },
  { key:'view_deposits',    label:'View Bank Deposits' },
  { key:'record_deposits',  label:'Record Bank Deposits' },
  { key:'view_expenses',    label:'Daily Expenses & Outlets' },
  { key:'view_employees',   label:'View Employee Directory' },
  { key:'hr_management',    label:'HR & Leave Management' },
  { key:'view_analytics',   label:'View Analytics & Reports' },
  { key:'export_reports',   label:'Export PDF Reports' },
];

// Default feature access per role
const ROLE_FEATURES = {
  boss: Object.fromEntries(FEATURE_KEYS.map(f=>[f.key, true])),
  production_manager: { view_inventory:true, edit_inventory:true, view_production:true, log_production:true, view_sales:true, view_analytics:true, export_reports:true, view_expenses:true, view_employees:false, hr_management:false, view_deposits:false, record_deposits:false },
  accountant: { view_inventory:true, view_production:true, view_sales:true, view_deposits:true, record_deposits:true, view_analytics:true, export_reports:true, view_expenses:true, view_employees:false, hr_management:false, edit_inventory:false, log_production:false },
  employee: { view_inventory:true, view_production:true, view_sales:false, view_expenses:false, view_deposits:false, record_deposits:false, view_employees:false, hr_management:false, view_analytics:false, export_reports:false, edit_inventory:false, log_production:false },
};

const AUDIT = [
  { id:'a1', created_at:'2026-04-20T09:12:00', user:'Fatimé Ousmane', action:'create', table_name:'production_batches', details:{ flavor:'Signature Pistachio', qty:18 } },
  { id:'a2', created_at:'2026-04-20T08:47:00', user:'Aïcha Déby', action:'create', table_name:'bank_deposits', details:{ amount:1850000, bank:'BCA' } },
  { id:'a3', created_at:'2026-04-20T08:04:00', user:'Khalid Hybah', action:'approve', table_name:'leave_requests', details:{ employee:'Idris Bongor' } },
  { id:'a4', created_at:'2026-04-19T19:22:00', user:'Khadija Abakar', action:'update', table_name:'inventory', details:{ item:'Cane Sugar', from:40, to:85 } },
  { id:'a5', created_at:'2026-04-19T16:01:00', user:'Khalid Hybah', action:'approve', table_name:'profiles', details:{ user:'Hassan Brahim', role:'employee' } },
  { id:'a6', created_at:'2026-04-19T14:38:00', user:'Fatimé Ousmane', action:'create', table_name:'production_batches', details:{ flavor:'Wild Blueberry', qty:12 } },
  { id:'a7', created_at:'2026-04-19T11:50:00', user:'Khalid Hybah', action:'create', table_name:'hr_warnings', details:{ employee:'Hassan Brahim', severity:'minor' } },
  { id:'a8', created_at:'2026-04-19T10:02:00', user:'Aïcha Déby', action:'create', table_name:'bank_deposits', details:{ amount:920000, bank:'SGT' } },
  { id:'a9', created_at:'2026-04-18T18:11:00', user:'Khadija Abakar', action:'delete', table_name:'inventory', details:{ item:'Expired cream (batch 04-09)' } },
  { id:'a10', created_at:'2026-04-18T15:45:00', user:'Fatimé Ousmane', action:'update', table_name:'production_batches', details:{ batch:'B0198', status:'completed' } },
];

const NOTIFICATIONS_BY_ROLE = {
  boss: [
    { id:'n1', title:'New account request', message:'Sadia Dingamadji requested an accountant account.', type:'info', read:false, created_at:'2026-04-20T07:40:00' },
    { id:'n2', title:'Low stock: Madagascar Vanilla', message:'Current stock is below minimum threshold (0.8 / 1.0 kg).', type:'warning', read:false, created_at:'2026-04-20T06:10:00' },
    { id:'n3', title:'Leave request pending', message:'Roland Nadjilem requested leave Apr 28 – May 2.', type:'info', read:false, created_at:'2026-04-19T20:02:00' },
    { id:'n4', title:'Weekly deposit recorded', message:'Aïcha Déby recorded 1,850,000 FCFA.', type:'success', read:true, created_at:'2026-04-18T17:22:00' },
  ],
  production_manager: [
    { id:'n1', title:'Batch completed', message:'Signature Pistachio — 18 kg completed.', type:'success', read:false, created_at:'2026-04-20T09:14:00' },
    { id:'n2', title:'Low stock: pistachio kernels', message:'9 kg remaining — order before Friday.', type:'warning', read:false, created_at:'2026-04-19T16:00:00' },
  ],
  accountant: [
    { id:'n1', title:'Deposit receipt ready', message:'BCA-2026-0418-01 uploaded to records.', type:'success', read:false, created_at:'2026-04-18T17:22:00' },
  ],
  employee: [
    { id:'n1', title:'Leave approved', message:'Your leave (Apr 10–12) was approved.', type:'success', read:true, created_at:'2026-04-09T10:02:00' },
  ],
};

function fmtFCFA(n) {
  return new Intl.NumberFormat('fr-FR').format(Math.round(n)) + ' FCFA';
}
function fmtNumber(n) {
  return new Intl.NumberFormat('fr-FR').format(Math.round(n));
}
function fmtDate(d) {
  if (!d) return '—';
  const date = typeof d === 'string' ? new Date(d) : d;
  return date.toLocaleDateString('en-GB', { day:'2-digit', month:'short', year:'numeric' });
}
function fmtDateTime(d) {
  const date = typeof d === 'string' ? new Date(d) : d;
  return date.toLocaleString('en-GB', { day:'2-digit', month:'short', hour:'2-digit', minute:'2-digit' });
}

window.BATCHES = __BATCHES_SEED.slice();
window.__BATCHES_SEED = __BATCHES_SEED;

window.__EMPLOYEES_BASE = EMPLOYEES.map((e) => ({ ...e }));

Object.assign(window, {
  FLAVORS, EMPLOYEES, INVENTORY, SALES, DEPOSITS, WARNINGS, LEAVES,
  WAITLIST_USERS, FEATURE_KEYS, ROLE_FEATURES, AUDIT, NOTIFICATIONS_BY_ROLE,
  CHAD_NAMES, DEPARTMENTS, ROLES, OUTLET_LOCATIONS,
  stockStatus, fmtFCFA, fmtNumber, fmtDate, fmtDateTime,
  invDisplayUnit, quantityInDisplayUnits, formatInvQty,
  weightGrams, gramsToUnit, volumeMl, mlToUnit,
  formatTenureSince, employeeAvatarUrl,
});
