// =============================================================================
// HELPERS — fonctions utilitaires
// =============================================================================

function genId() { return Math.random().toString(36).slice(2,10) + Date.now().toString(36).slice(-4); }
function formatPrice(n) { return (n || 0).toFixed(2).replace('.', ',') + ' €'; }

// === STOCK ===
function getEffectiveStock(drink, drinks) {
  if (!drink) return null;
  if (drink.parentId) {
    const parent = drinks.find(d => d.id === drink.parentId);
    if (!parent || !parent.stockEnabled) return null;
    return Math.floor((parent.stock || 0) * (drink.parentRatio || 1));
  }
  // Cocktails à ingrédients multiples : stock effectif = nb de cocktails encore réalisables
  if (drink.ingredients && drink.ingredients.length > 0) {
    let min = Infinity;
    let hasTrackedIngredient = false;
    for (const ing of drink.ingredients) {
      const parent = drinks.find(d => d.id === ing.parentId);
      if (!parent || !parent.stockEnabled) continue;
      if (!ing.amount || ing.amount <= 0) continue;
      hasTrackedIngredient = true;
      const possible = Math.floor((parent.stock || 0) / ing.amount);
      if (possible < min) min = possible;
    }
    return hasTrackedIngredient ? min : null;
  }
  if (!drink.stockEnabled) return null;
  return Math.floor(drink.stock || 0);
}
// Renvoie la liste des stocks à décrémenter quand on vend `drink`.
// Chaque cible : { drinkId, decrementPerUnit }.
function getStockTargets(drink, drinks) {
  if (!drink) return [];
  if (drink.parentId) {
    const parent = drinks.find(d => d.id === drink.parentId);
    if (!parent || !parent.stockEnabled) return [];
    return [{ drinkId: parent.id, decrementPerUnit: 1 / (drink.parentRatio || 1) }];
  }
  if (drink.ingredients && drink.ingredients.length > 0) {
    return drink.ingredients
      .map(ing => {
        const parent = drinks.find(d => d.id === ing.parentId);
        if (!parent || !parent.stockEnabled) return null;
        if (!ing.amount || ing.amount <= 0) return null;
        return { drinkId: parent.id, decrementPerUnit: ing.amount };
      })
      .filter(Boolean);
  }
  if (!drink.stockEnabled) return [];
  return [{ drinkId: drink.id, decrementPerUnit: 1 }];
}
function stockTotalValue(drinks) {
  let total = 0;
  drinks.forEach(d => {
    if (d.stockEnabled && !d.parentId) {
      total += (d.stock || 0) * (d.price || 0);
    }
  });
  return total;
}


// === IMAGE PROCESSING (compression côté client) ===
function processImage(file, maxDim = 500, quality = 0.75) {
  return new Promise((resolve, reject) => {
    if (!file || !file.type || !file.type.startsWith('image/')) {
      reject(new Error('Format non supporté')); return;
    }
    const reader = new FileReader();
    reader.onload = (e) => {
      const img = new Image();
      img.onload = () => {
        let { width, height } = img;
        if (width > maxDim || height > maxDim) {
          if (width > height) { height = Math.round(height * maxDim / width); width = maxDim; }
          else { width = Math.round(width * maxDim / height); height = maxDim; }
        }
        const canvas = document.createElement('canvas');
        canvas.width = width; canvas.height = height;
        const ctx = canvas.getContext('2d');
        ctx.fillStyle = '#FAF7F2';
        ctx.fillRect(0, 0, width, height);
        ctx.drawImage(img, 0, 0, width, height);
        resolve(canvas.toDataURL('image/jpeg', quality));
      };
      img.onerror = () => reject(new Error('Image invalide'));
      img.src = e.target.result;
    };
    reader.onerror = () => reject(new Error('Lecture impossible'));
    reader.readAsDataURL(file);
  });
}

// =============================================================================
// MULTI-EVENT HELPERS (ajouts pour la commercialisation V1)
// =============================================================================

// Hash SHA-256 d'un mot de passe avec un sel par événement.
// Note : pour la V1 gratuit nous nous contentons de SHA-256 + sel (suffisant pour
// un usage non-critique). Une vraie crypto (bcrypt/argon2) serait pertinente
// pour V2 si les enjeux deviennent sensibles.
async function hashPassword(password, salt) {
  const encoder = new TextEncoder();
  const data = encoder.encode((salt || '') + ':' + (password || ''));
  const hashBuffer = await crypto.subtle.digest('SHA-256', data);
  const hashArray = Array.from(new Uint8Array(hashBuffer));
  return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
}

// Génère un identifiant d'événement court et lisible (usage dans l'URL de partage)
function genEventId() {
  // 12 chars alphanumériques sans ambiguïté (pas de 0/O/1/l)
  const chars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
  let id = '';
  for (let i = 0; i < 12; i++) id += chars[Math.floor(Math.random() * chars.length)];
  return id;
}

// Récupère / mémorise / oublie le membre actif pour un événement donné
function getEventMember(eventId) {
  if (!eventId) return null;
  try { const raw = localStorage.getItem(eventStorageKey(eventId, 'member')); return raw ? JSON.parse(raw) : null; }
  catch { return null; }
}
function setEventMember(eventId, member) {
  if (!eventId) return;
  try { localStorage.setItem(eventStorageKey(eventId, 'member'), JSON.stringify(member)); } catch {}
}
function clearEventMember(eventId) {
  if (!eventId) return;
  try { localStorage.removeItem(eventStorageKey(eventId, 'member')); } catch {}
}

// Récupère l'eventId actif (dernier événement choisi sur cet appareil)
function getCurrentEventId() {
  try { return localStorage.getItem('caterii-current-event') || null; }
  catch { return null; }
}
function setCurrentEventId(eventId) {
  try {
    if (eventId) localStorage.setItem('caterii-current-event', eventId);
    else localStorage.removeItem('caterii-current-event');
  } catch {}
}

// Détecte un eventId dans l'URL (?event=xxx)
function getEventIdFromURL() {
  try {
    const params = new URLSearchParams(window.location.search);
    return params.get('event') || null;
  } catch { return null; }
}

// Construit le lien partageable pour les barmen
function buildEventShareLink(eventId) {
  if (!eventId) return '';
  const url = new URL(window.location.href);
  url.search = `?event=${eventId}`;
  url.hash = '';
  return url.toString();
}
