// Compatibility shim — adapts existing data.jsx to the names used by pages-1/pages-2/logger.
// Also adds MEMBERS, HISTORY_STATS_BY_EXERCISE, exercise translations, cues, etc.

(function() {
  // Alias muscle groups under both names
  window.MUSCLES = window.MUSCLE_GROUPS;

  // Add `dateTs` and `prs` to history items
  window.HISTORY = window.HISTORY.map(w => ({
    ...w,
    dateTs: new Date(w.date).getTime(),
    prs: w.exercises.reduce((s, e) => s + e.sets.filter(x => x.isPR).length, 0),
  }));

  // Add per-template `runs` count from history
  window.TEMPLATES = window.TEMPLATES.map(t => ({
    ...t,
    runs: window.HISTORY.filter(w => w.templateId === t.id).length,
  }));

  // Add `fr` and `cues` to exercises (subset; fall back to `name`)
  const FR = {
    1: "Développé couché", 2: "Développé incliné haltères", 3: "Écarté poulie",
    4: "Pompes", 5: "Développé couché haltères", 6: "Pec deck",
    10: "Soulevé de terre", 11: "Tractions", 12: "Rowing barre",
    13: "Tirage poitrine", 14: "Rowing assis poulie", 15: "Rowing T-bar",
    20: "Squat arrière", 21: "Soulevé de terre roumain", 22: "Presse à cuisses",
    23: "Fentes marchées", 24: "Leg curl", 25: "Leg extension",
    26: "Squat bulgare", 27: "Mollets debout",
    30: "Développé militaire", 31: "Élévations latérales", 32: "Face pull",
    33: "Arnold press", 34: "Oiseau",
    40: "Curl barre", 41: "Curl marteau", 42: "Curl pupitre",
    50: "Extension triceps poulie", 51: "Skull crusher", 52: "Dips",
    60: "Planche", 61: "Relevé de jambes suspendu", 62: "Crunch poulie",
    63: "Russian twist",
    70: "Course tapis", 71: "Rameur", 72: "Vélo assault",
  };
  const CUES = {
    1: { en: ["Retract scapula, pin shoulders","Bar path: low chest, slight arc","Drive feet into floor"],
         fr: ["Rétracter les omoplates","Trajectoire: bas du sternum","Pousser les pieds au sol"] },
    20: { en: ["Brace core before unrack","Knees track over toes","Hip-hinge then descend"],
          fr: ["Gainer avant de sortir la barre","Genoux dans l'axe des pieds","Hanche puis descente"] },
    10: { en: ["Bar over mid-foot","Lats engaged, chest up","Push the floor away"],
          fr: ["Barre au-dessus du milieu du pied","Dorsaux engagés","Pousser le sol"] },
  };
  window.EXERCISES = window.EXERCISES.map(e => ({
    ...e,
    fr: FR[e.id] || e.name,
    cues: CUES[e.id] || { en: ["Maintain neutral spine","Control the eccentric","Full range of motion"],
                          fr: ["Garder le dos neutre","Contrôler la descente","Amplitude complète"] },
  }));

  // Per-exercise stats (sessions, best, e1RM)
  const stats = {};
  window.HISTORY.forEach(w => {
    w.exercises.forEach(e => {
      if (!stats[e.exerciseId]) stats[e.exerciseId] = { sessions: 0, bestWeight: 0, bestE1RM: 0 };
      stats[e.exerciseId].sessions++;
      e.sets.forEach(s => {
        if (s.weight > stats[e.exerciseId].bestWeight) stats[e.exerciseId].bestWeight = s.weight;
        const e1rm = s.weight * (1 + s.reps / 30);
        if (e1rm > stats[e.exerciseId].bestE1RM) stats[e.exerciseId].bestE1RM = Math.round(e1rm);
      });
    });
  });
  Object.keys(stats).forEach(k => {
    stats[k].bestWeight = stats[k].bestWeight + " kg";
    stats[k].bestE1RM = stats[k].bestE1RM + " kg";
  });
  window.HISTORY_STATS_BY_EXERCISE = stats;

  // Fix nutrition shape to match what NutritionPage expects
  const n = window.NUTRITION_TODAY;
  const totals = { kcal: 0, protein: 0, carbs: 0, fat: 0 };
  n.meals = n.meals.map(m => {
    let mk = 0, mp = 0, mc = 0, mf = 0;
    const items = m.items.map(it => {
      mk += it.cal; mp += it.p; mc += it.c; mf += it.f;
      return { name: it.name, fr: it.name, amount: "", kcal: it.cal };
    });
    totals.kcal += mk; totals.protein += mp; totals.carbs += mc; totals.fat += mf;
    return {
      type: m.type.charAt(0).toUpperCase() + m.type.slice(1),
      time: m.time,
      kcal: mk, protein: mp, carbs: mc, fat: mf,
      items,
    };
  });
  window.NUTRITION_TODAY = {
    ...n,
    goals: { kcal: n.goal.calories, protein: n.goal.protein, carbs: n.goal.carbs, fat: n.goal.fat },
    totals,
  };

  // BIOMETRICS — show recent first, ensure rounded numbers
  window.BIOMETRICS = window.BIOMETRICS.slice().reverse().slice(0, 8).map(b => ({
    ...b,
    chest: Math.round(b.chest * 10) / 10,
    waist: Math.round(b.waist * 10) / 10,
    arm: Math.round(b.arm * 10) / 10,
    thigh: Math.round(b.thigh * 10) / 10,
  }));

  window.MEMBERS = window.MEMBERS || [];

  // Add icons used by pages but not in primitives.jsx
  const origIcon = window.Icon;
  window.Icon = function PatchedIcon({ name, size = 18, stroke = 1.6, color = "currentColor" }) {
    const props = { width: size, height: size, viewBox: "0 0 24 24", fill: "none",
      stroke: color, strokeWidth: stroke, strokeLinecap: "round", strokeLinejoin: "round" };
    switch (name) {
      case "dumbbell": return <svg {...props}><path d="M2 10v4M5 7v10M9 4v16M15 4v16M19 7v10M22 10v4M9 12h6"/></svg>;
      case "weight": return <svg {...props}><path d="M5 7l1 13h12l1-13H5z"/><circle cx="12" cy="4" r="2"/></svg>;
      case "clock": return <svg {...props}><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 3"/></svg>;
      case "chevron-up": return <svg {...props}><path d="m6 15 6-6 6 6"/></svg>;
      case "play-circle": return <svg {...props}><circle cx="12" cy="12" r="9"/><path d="M10 8l6 4-6 4z" fill={color}/></svg>;
      case "user-plus": return <svg {...props}><circle cx="9" cy="8" r="4"/><path d="M3 21c0-4 3-7 6-7s6 3 6 7M19 8v6M16 11h6"/></svg>;
      case "user-check": return <svg {...props}><circle cx="9" cy="8" r="4"/><path d="M3 21c0-4 3-7 6-7s6 3 6 7M16 11l2 2 4-4"/></svg>;
      case "clipboard": return <svg {...props}><rect x="6" y="4" width="12" height="18" rx="2"/><path d="M9 4V2h6v2M9 10h6M9 14h6M9 18h4"/></svg>;
      case "credit-card": return <svg {...props}><rect x="2" y="6" width="20" height="13" rx="2"/><path d="M2 11h20M6 16h4"/></svg>;
      case "download": return <svg {...props}><path d="M12 4v12M6 11l6 6 6-6M4 20h16"/></svg>;
      default: return origIcon({ name, size, stroke, color });
    }
  };
})();
