// Shared store: service modes + orders + reservations, backed by localStorage
// with cross-tab sync via the `storage` event + a custom in-tab event.
const { useState: useStateST, useEffect: useEffectST, useSyncExternalStore } = React;

const LN_STORE_KEY = 'ln-store-v1';

// Local-timezone-safe YYYY-MM-DD. Do NOT use toISOString() (UTC) — in +TZ it
// shifts the date one day earlier around local midnight.
function lnLocalISODate(d) {
  const y = d.getFullYear();
  const m = String(d.getMonth() + 1).padStart(2, '0');
  const dd = String(d.getDate()).padStart(2, '0');
  return `${y}-${m}-${dd}`;
}

const LN_DEFAULT_STATE = {
  serviceModes: {
    takeaway:    'online', // online | phone | closed
    reservation: 'online',
    delivery:    'online',
  },
  settings: {
    phone: '+33 1 43 55 21 08',
    uberEatsUrl: 'https://www.ubereats.com/',
    phoneHours: 'Tous les jours · 11h30 – 22h30',
  },
  orders: [],       // { id, ref, createdAt, items:[{id,name,qty,price}], subtotal, fee, total, pickupTime, customer:{name,phone,email,note}, payment, status }
  reservations: [], // { id, ref, createdAt, date, time, party, customer:{name,phone,email,occasion,note}, status }
  seeded: false,
};

function lnRead() {
  try {
    const raw = localStorage.getItem(LN_STORE_KEY);
    if (!raw) return { ...LN_DEFAULT_STATE };
    const parsed = JSON.parse(raw);
    return {
      ...LN_DEFAULT_STATE,
      ...parsed,
      serviceModes: { ...LN_DEFAULT_STATE.serviceModes, ...(parsed.serviceModes || {}) },
      settings: { ...LN_DEFAULT_STATE.settings, ...(parsed.settings || {}) },
      orders: parsed.orders || [],
      reservations: parsed.reservations || [],
    };
  } catch { return { ...LN_DEFAULT_STATE }; }
}

function lnWrite(next) {
  localStorage.setItem(LN_STORE_KEY, JSON.stringify(next));
  window.dispatchEvent(new CustomEvent('ln-store-change'));
}

function lnUpdate(mutator) {
  const next = mutator(lnRead());
  lnWrite(next);
  return next;
}

// React subscription
const lnSubscribers = new Set();
function lnSubscribe(fn) {
  lnSubscribers.add(fn);
  return () => lnSubscribers.delete(fn);
}
function lnNotify() { lnSubscribers.forEach(f => f()); }
window.addEventListener('ln-store-change', lnNotify);
window.addEventListener('storage', (e) => { if (e.key === LN_STORE_KEY) lnNotify(); });

function useLnStore() {
  return useSyncExternalStore(lnSubscribe, () => {
    // snapshot ref stable across unchanged reads (localStorage string identity)
    const raw = localStorage.getItem(LN_STORE_KEY) || '';
    if (raw === useLnStore._raw) return useLnStore._cached;
    useLnStore._raw = raw;
    useLnStore._cached = lnRead();
    return useLnStore._cached;
  }, () => lnRead());
}

// ---- Public API ----
function lnSetServiceMode(service, mode) {
  lnUpdate(s => ({ ...s, serviceModes: { ...s.serviceModes, [service]: mode } }));
}
function lnUpdateSettings(patch) {
  lnUpdate(s => ({ ...s, settings: { ...s.settings, ...patch } }));
}
function lnAddOrder(order) {
  const withDefaults = {
    id: 'o_' + Math.random().toString(36).slice(2, 10),
    createdAt: Date.now(),
    status: 'new', // new | preparing | ready | completed | cancelled
    ...order,
  };
  lnUpdate(s => ({ ...s, orders: [withDefaults, ...s.orders] }));
  return withDefaults;
}
function lnUpdateOrderStatus(id, status) {
  lnUpdate(s => ({ ...s, orders: s.orders.map(o => o.id === id ? { ...o, status } : o) }));
}
function lnAddReservation(reservation) {
  const withDefaults = {
    id: 'r_' + Math.random().toString(36).slice(2, 10),
    createdAt: Date.now(),
    status: 'confirmed', // confirmed | seated | cancelled | no-show
    ...reservation,
  };
  lnUpdate(s => ({ ...s, reservations: [withDefaults, ...s.reservations] }));
  return withDefaults;
}
function lnUpdateReservationStatus(id, status) {
  lnUpdate(s => ({ ...s, reservations: s.reservations.map(r => r.id === id ? { ...r, status } : r) }));
}
function lnClearDemoData() {
  lnUpdate(s => ({ ...s, orders: [], reservations: [] }));
}

// ---- Seed: fake existing reservations + a couple of past orders so admin isn't empty ----
function lnSeedOnce() {
  const s = lnRead();
  if (s.seeded) return;
  const today = new Date();
  const iso = (d) => lnLocalISODate(d);
  const tomorrow = new Date(today); tomorrow.setDate(today.getDate()+1);
  const dayAfter = new Date(today); dayAfter.setDate(today.getDate()+2);

  const seededReservations = [
    { id: 'r_seed1', ref: 'RSV-4921', createdAt: Date.now()-3600_000*5, date: iso(today), time: '19:30', party: 4, customer: { name: 'Camille Rousseau', phone: '+33 6 12 34 56 78', email: 'camille@mail.fr', occasion: 'Anniversaire', note: 'Table calme si possible' }, status: 'confirmed' },
    { id: 'r_seed2', ref: 'RSV-4887', createdAt: Date.now()-3600_000*9, date: iso(today), time: '20:30', party: 2, customer: { name: 'Léo Bernard', phone: '+33 6 98 11 22 33', email: '', occasion: '', note: '' }, status: 'confirmed' },
    { id: 'r_seed3', ref: 'RSV-4903', createdAt: Date.now()-3600_000*22, date: iso(today), time: '21:00', party: 6, customer: { name: 'Amélie Nguyen', phone: '+33 6 55 44 33 22', email: 'a.nguyen@mail.fr', occasion: 'Dîner entre amis', note: '' }, status: 'confirmed' },
    { id: 'r_seed4', ref: 'RSV-4851', createdAt: Date.now()-3600_000*30, date: iso(tomorrow), time: '12:30', party: 3, customer: { name: 'Sophie Laurent', phone: '+33 6 77 88 99 00', email: '', occasion: '', note: 'Chaise bébé' }, status: 'confirmed' },
    { id: 'r_seed5', ref: 'RSV-4862', createdAt: Date.now()-3600_000*26, date: iso(tomorrow), time: '20:00', party: 2, customer: { name: 'Marc Dubois', phone: '+33 6 01 02 03 04', email: 'm.dubois@mail.fr', occasion: 'Romantique', note: '' }, status: 'confirmed' },
    { id: 'r_seed6', ref: 'RSV-4820', createdAt: Date.now()-3600_000*50, date: iso(dayAfter), time: '19:00', party: 5, customer: { name: 'Famille Chen', phone: '+33 6 44 55 66 77', email: '', occasion: '', note: '' }, status: 'confirmed' },
  ];

  const seededOrders = [
    { id: 'o_seed1', ref: 'LN-3318', createdAt: Date.now()-1000*60*42, items: [{ id:'shish-taouk', name:'Brochette shish taouk', qty:1, price:16 }, { id:'hummus', name:'Houmous maison', qty:1, price:7 }, { id:'fries', name:'Frites maison', qty:2, price:5.5 }], subtotal: 34, fee: 1.5, total: 35.5, pickupTime: '15min', customer: { name: 'Julien Moreau', phone: '+33 6 10 20 30 40', email: '', note: '' }, payment: 'card', status: 'completed' },
    { id: 'o_seed2', ref: 'LN-3322', createdAt: Date.now()-1000*60*18, items: [{ id:'wrap-falafel', name:'Wrap falafel', qty:2, price:11 }, { id:'tabbouleh', name:'Taboulé libanais', qty:1, price:7.5 }], subtotal: 29.5, fee: 1.5, total: 31, pickupTime: 'asap', customer: { name: 'Inès K.', phone: '+33 6 12 12 12 12', email: '', note: 'Sans oignons svp' }, payment: 'card', status: 'ready' },
    { id: 'o_seed3', ref: 'LN-3325', createdAt: Date.now()-1000*60*6, items: [{ id:'box-family', name:'Box famille', qty:1, price:58 }], subtotal: 58, fee: 1.5, total: 59.5, pickupTime: '30min', customer: { name: 'Pierre L.', phone: '+33 6 99 88 77 66', email: 'p.l@mail.fr', note: '' }, payment: 'counter', status: 'preparing' },
    { id: 'o_seed4', ref: 'LN-3327', createdAt: Date.now()-1000*60*2, items: [{ id:'moutabal', name:'Moutabal', qty:1, price:8.5 }, { id:'falafel-box', name:'Boîte de falafels', qty:1, price:12 }, { id:'wings', name:'Ailes de poulet grillées', qty:1, price:13.5 }], subtotal: 34, fee: 1.5, total: 35.5, pickupTime: 'asap', customer: { name: 'Sarah B.', phone: '+33 6 14 25 36 47', email: '', note: '' }, payment: 'card', status: 'new' },
  ];

  lnUpdate(prev => ({ ...prev, reservations: [...seededReservations, ...prev.reservations], orders: [...seededOrders, ...prev.orders], seeded: true }));
}

Object.assign(window, {
  lnRead, lnUpdate, useLnStore, lnLocalISODate,
  lnSetServiceMode, lnUpdateSettings,
  lnAddOrder, lnUpdateOrderStatus,
  lnAddReservation, lnUpdateReservationStatus,
  lnClearDemoData, lnSeedOnce,
});
