/* ======================================================================
   DAR AYLA OPS — V2 · DATA LAYER (PRODUCTION)
   Fetches real data from Workers API, exposes window.DA_DATA
   Same interface as mock — UI components unchanged.
   ====================================================================== */

const SUITES = [
  { id:'halawah',  name:'Halawah',  color:'#c07d55', area:42, beds:'King',     view:'Patio',   capacity:2, floor:'RDC',  feature:'Chemin\u00e9e tadelakt',          basePrice:560,  highSeasonPrice:780,  notion:'https://notion.so/dar-ayla/suite-halawah',  amenities:['Chemin\u00e9e','Climatisation','Coffre','Mini-bar','TV cach\u00e9e','Wifi'] },
  { id:'hibah',    name:'Hibah',    color:'#7d9b8a', area:38, beds:'Queen',    view:'Jardin',  capacity:2, floor:'RDC',  feature:'Terrasse priv\u00e9e',            basePrice:530,  highSeasonPrice:740,  notion:'https://notion.so/dar-ayla/suite-hibah',    amenities:['Terrasse','Climatisation','Mini-bar','Wifi','Bain'] },
  { id:'hidaya',   name:'Hidaya',   color:'#c9a14a', area:46, beds:'King',     view:'Atlas',   capacity:2, floor:'1er',  feature:'Baignoire en pierre',        basePrice:610,  highSeasonPrice:870,  notion:'https://notion.so/dar-ayla/suite-hidaya',   amenities:['Baignoire pierre','Vue Atlas','Climatisation','Mini-bar','Wifi'] },
  { id:'zayna',    name:'Zayna',    color:'#a877a8', area:52, beds:'King + 1', view:'Piscine', capacity:3, floor:'1er',  feature:'Salon attenant',             basePrice:680,  highSeasonPrice:980,  notion:'https://notion.so/dar-ayla/suite-zayna',    amenities:['Salon','Vue piscine','3 pers.','Climatisation','Mini-bar'] },
  { id:'sahar',    name:'Sahar',    color:'#6b8aaa', area:40, beds:'Queen',    view:'M\u00e9dina',  capacity:2, floor:'1er',  feature:'Moucharabieh',               basePrice:520,  highSeasonPrice:730,  notion:'https://notion.so/dar-ayla/suite-sahar',    amenities:['Moucharabieh','Climatisation','Mini-bar','Wifi'] },
  { id:'kaouki',   name:'Kaouki',   color:'#5a9aaa', area:44, beds:'King',     view:'Oc\u00e9an',   capacity:2, floor:'2e',   feature:'Hammam privatif',            basePrice:720,  highSeasonPrice:990,  notion:'https://notion.so/dar-ayla/suite-kaouki',   amenities:['Hammam priv\u00e9','Vue oc\u00e9an','Climatisation','Mini-bar','Peignoirs'] },
  { id:'tadelakt', name:'Tadelakt', color:'#b89060', area:36, beds:'Queen',    view:'Patio',   capacity:2, floor:'RDC',  feature:'Murs tadelakt brut',         basePrice:480,  highSeasonPrice:680,  notion:'https://notion.so/dar-ayla/suite-tadelakt', amenities:['Tadelakt brut','Climatisation','Mini-bar','Wifi'] },
  { id:'patio',    name:'Patio',    color:'#7aaa6b', area:48, beds:'King + 2', view:'Patio',   capacity:4, floor:'RDC',  feature:'Suite familiale',            basePrice:740,  highSeasonPrice:1040, notion:'https://notion.so/dar-ayla/suite-patio',    amenities:['Famille 4 pers.','Lit enfants','Climatisation','Mini-bar'] },
  { id:'ayla',     name:'Ayla',     color:'#aaa07d', area:62, beds:'Royal',    view:'Panoramique', capacity:2, floor:'2e', feature:'Suite signature \u00b7 roof terrace', basePrice:980, highSeasonPrice:1380, notion:'https://notion.so/dar-ayla/suite-ayla',  amenities:['Roof terrace','Suite signature','Vue panoramique','Hammam','Service prioritaire'] },
];

/* Suite name → id lookup */
const _suiteIdMap = {};
SUITES.forEach(s => {
  _suiteIdMap[s.name.toLowerCase()] = s.id;
  _suiteIdMap[s.name] = s.id;
  _suiteIdMap[s.id] = s.id;
});

/* Date helpers */
const today = new Date();
const fmt = (d) => (typeof d === 'string' ? d : d.toISOString().slice(0,10));
const addD = (base, n) => { const d = new Date(typeof base === 'string' ? base : base); d.setDate(d.getDate()+n); return fmt(d); };
const todayStr = fmt(today);
function dayDiff(a, b) { return Math.max(1, (new Date(b) - new Date(a)) / 86400000); }

/* Pricing helper */
function priceFor(suiteId, dateStr) {
  const s = SUITES.find(x => x.id===suiteId);
  if (!s) return 0;
  const d = new Date(dateStr);
  const dow = d.getDay();
  const month = d.getMonth();
  const highMonth = month === 3 || month === 4 || month === 9 || month === 10;
  const isWeekend = (dow === 5 || dow === 6);
  if (highMonth && isWeekend) return s.highSeasonPrice;
  if (highMonth) return Math.round((s.basePrice + s.highSeasonPrice) / 2);
  if (isWeekend) return Math.round(s.basePrice * 1.15);
  return s.basePrice;
}

/* Initials from name */
function initials(name) {
  if (!name) return '?';
  const parts = name.replace(/&/g,'').split(/\s+/).filter(Boolean);
  if (parts.length >= 2) return (parts[0][0] + parts[parts.length-1][0]).toUpperCase();
  return (parts[0] || '?').slice(0,2).toUpperCase();
}

/* Ensure array */
function ensureArr(v) {
  if (Array.isArray(v)) return v;
  if (typeof v === 'string' && v.trim()) return v.split(',').map(s => s.trim());
  return [];
}

/* ---- API FETCH ---- */
async function apiFetch(path) {
  try {
    const r = await fetch(path);
    if (!r.ok) { console.warn(`[data] ${path} → ${r.status}`); return null; }
    return r.json();
  } catch (e) { console.warn(`[data] ${path} error:`, e.message); return null; }
}

/* Map V1 API → V2 data format */
function mapReservation(r) {
  const suiteLabel = r.suiteLabel || (r.suiteLabels && r.suiteLabels[0]) || '';
  return {
    id: r.id,
    voyageur: r.voyageur || '',
    nationalite: r.nationalite || '',
    langue: ensureArr(r.langue),
    suiteId: _suiteIdMap[suiteLabel] || _suiteIdMap[suiteLabel.toLowerCase()] || suiteLabel.toLowerCase(),
    arrivee: r.arrivee || '',
    depart: r.depart || '',
    pax: r.personnes || 2,
    montant: r.montant || 0,
    canal: r.canal || 'Direct',
    statut: r.statut || '',
    heureCI: r.heureCI || '15:00',
    heureCO: r.heureCO || '11:00',
    allergies: r.allergies || '',
    regime: ensureArr(r.regime),
    tableHotes: ensureArr(r.tableHotes),
    petitDej: r.petitDej !== false,
    preferences: r.preferences || r.notes || '',
    refBooking: r.refBooking || r.id,
    portail: '',
    avatar: initials(r.voyageur),
    vip: !!r.vip,
    chatThread: r.chatThread || '',
  };
}

function mapHousekeeping(m) {
  const suiteLabels = m.suiteLabels || (m.suite ? [m.suite] : []);
  const suiteLabel = suiteLabels[0] || '';
  return {
    id: m.id,
    suiteId: _suiteIdMap[suiteLabel] || _suiteIdMap[suiteLabel.toLowerCase()] || suiteLabel.toLowerCase(),
    type: m.type || m.tache || '',
    date: m.date || '',
    assignee: m.assigne || m.assignee || '',
    status: m.statut || m.status || '',
    priority: m.priorite || m.priority || 'normal',
    startedAt: m.startedAt || null,
    completedAt: m.completedAt || null,
    linenSet: m.linenSet || '',
    notes: m.notes || '',
  };
}

function mapRequest(d) {
  return {
    id: d.id,
    resaId: d.resaId || '',
    type: d.tag || d.type || '',
    label: d.titre || d.label || '',
    assignee: d.assignee || '',
    status: d.statut || d.status || '',
    due: d.due || '',
    amount: d.amount || d.prix || 0,
    priority: d.priorite || d.priority || 'normal',
    notes: d.message || d.notes || '',
    notion: '',
    lodgify: '',
    whatsapp: '',
  };
}

function mapIncident(i) {
  return {
    id: i.id,
    suiteId: i.suiteId || (i.suite ? i.suite.toLowerCase() : ''),
    title: i.title || '',
    reportedBy: i.reportedBy || '',
    reportedAt: i.reportedAt || i.createdAt || '',
    status: i.status || '',
    assignee: i.assignee || '',
    priority: i.priority || 'normal',
    photos: i.photos || 0,
    eta: i.eta || '',
  };
}

function mapVendor(v) {
  return {
    id: v.id,
    name: v.name || '',
    role: v.role || '',
    phone: v.phone || '',
    whatsapp: v.phone || '',
    rating: v.rating || 0,
    missions: v.missions || 0,
    active: v.active !== false,
    partnerSpace: 'soon',
    city: v.ville || v.city || 'Marrakech',
  };
}

function mapActivity(a) {
  return {
    id: a.id,
    at: a.at || a.createdAt || '',
    icon: a.type || a.icon || 'request',
    who: a.who || '',
    text: a.text || '',
  };
}

/* KPI compute */
function computeKPIs() {
  const D = window.DA_DATA;
  const active = D.RESERVATIONS.filter(r => r.arrivee <= todayStr && r.depart > todayStr);
  const arrivals = D.RESERVATIONS.filter(r => r.arrivee === todayStr);
  const departures = D.RESERVATIONS.filter(r => r.depart === todayStr);
  const pendingReq = D.REQUESTS.filter(r => r.status !== 'r\u00e9solu' && r.status !== 'fait' && r.status !== 'confirm\u00e9').length;
  const todoMng = D.HOUSEKEEPING.filter(m => m.date === todayStr && m.status !== 'fait').length;
  const openIncidents = D.INCIDENTS.filter(i => i.status !== 'r\u00e9solu').length;
  const occPct = Math.round((active.length / 9) * 100);
  const revToday = active.reduce((s,r) => s + r.montant / Math.max(1, dayDiff(r.arrivee, r.depart)), 0);
  const lowStock = D.INVENTORY.filter(i => i.alert).length;
  return { occPct, arrivals: arrivals.length, departures: departures.length, pendingReq, todoMng, openIncidents, revToday: Math.round(revToday), lowStock, active: active.length };
}

/* Initialize DA_DATA with empty defaults (UI renders immediately) */
window.DA_DATA = {
  SUITES,
  RESERVATIONS: [],
  CHAT_THREADS: {},
  HOUSEKEEPING: [],
  REQUESTS: [],
  INVENTORY: [],
  INCIDENTS: [],
  VENDORS: [],
  ACTIVITY: [],
  TODAY: today,
  todayStr,
  addD, fmt, dayDiff, computeKPIs, priceFor,
  _loaded: false,
};

/* Fetch all data from Workers API */
async function loadAllData() {
  const [resasRaw, menagesRaw, demandesRaw, inventaireRaw, incidentsRaw, prestatairesRaw, activityRaw, messagesRaw] =
    await Promise.all([
      apiFetch('/api/reservations'),
      apiFetch('/api/menages'),
      apiFetch('/api/demandes'),
      apiFetch('/api/inventaire'),
      apiFetch('/api/incidents'),
      apiFetch('/api/prestataires'),
      apiFetch('/api/activity'),
      apiFetch('/api/messages'),
    ]);

  const D = window.DA_DATA;

  // Reservations
  const resaArr = resasRaw ? (resasRaw.results || resasRaw) : [];
  D.RESERVATIONS = (Array.isArray(resaArr) ? resaArr : []).map(mapReservation);

  // Housekeeping
  D.HOUSEKEEPING = (Array.isArray(menagesRaw) ? menagesRaw : []).map(mapHousekeeping);

  // Requests (demandes)
  D.REQUESTS = (Array.isArray(demandesRaw) ? demandesRaw : []).map(mapRequest);

  // Inventory
  D.INVENTORY = (Array.isArray(inventaireRaw) ? inventaireRaw : []).map(i => ({
    ...i,
    alert: (i.stock || 0) < (i.min || 0),
  }));

  // Incidents
  D.INCIDENTS = (Array.isArray(incidentsRaw) ? incidentsRaw : []).map(mapIncident);

  // Vendors
  D.VENDORS = (Array.isArray(prestatairesRaw) ? prestatairesRaw : []).map(mapVendor);

  // Activity
  D.ACTIVITY = (Array.isArray(activityRaw) ? activityRaw : []).map(mapActivity);

  // Chat threads (keyed by thread ID from messages)
  D.CHAT_THREADS = {};
  D._rawMessages = [];
  if (Array.isArray(messagesRaw)) {
    D._rawMessages = messagesRaw;
    messagesRaw.forEach(t => {
      D.CHAT_THREADS[t.id] = [];
    });
  }

  D._loaded = true;
  window.dispatchEvent(new Event('da-data-loaded'));
  console.log('[Dar Ayla OPS] Data loaded:', D.RESERVATIONS.length, 'r\u00e9sas,', D.HOUSEKEEPING.length, 'm\u00e9nages,', D.REQUESTS.length, 'demandes');
}

/* Auto-refresh every 60s */
let _refreshTimer;
function startAutoRefresh() {
  _refreshTimer = setInterval(() => loadAllData(), 60000);
}
function stopAutoRefresh() { clearInterval(_refreshTimer); }

/* Trigger initial load */
loadAllData().then(startAutoRefresh);

/* Expose refresh function */
window.DA_REFRESH = loadAllData;
