// running/src/nutrition.jsx — slice 12 of the module split.
//
// NUTRITION view: day-by-day intake vs targets, macro split, fuel
// timing, weight goal — all computation comes from context products
// (nutritionHistory, redsRisk via DataProvider → window.RedsRisk) and
// the UMD libs. Extracted verbatim from running/index.html; pure
// presentation over useData like Health (slice 10).

const { C, Card, Stat, Badge, Btn, TabBar, EmptyState, ChartTooltip, fmt, NutritionResetControl } = window.SharedUI;
const useData = () => (window.__appUseData ? window.__appUseData() : null);
const { useState, useEffect, useMemo } = React;
const {
  AreaChart, Area, LineChart, Line, BarChart, Bar, ComposedChart,
  XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer,
  PieChart, Pie, Cell, ReferenceLine, RadialBarChart, RadialBar,
} = Recharts;

    function Nutrition({ userId, activities, isOwner, hrZoneConfig }) {
      const { healthEntries30: healthEntries, nutritionHistory: nutHistoryAll,
              todayNutrition, refreshNutrition,
              supplements, saveSupplements, activePlan: todayPlan,
              redsRisk: nutRedsRisk } = useData();
      const [tab, setTab] = useState("Week");
      // Nutrition Week view navigation — 0 = current week, -1 = last week, …
      const [weekOffset, setWeekOffset] = useState(0);
      const [nutritionData, setNutritionData] = useState({});
      const [loadingPlan, setLoadingPlan] = useState(false);
      const [plan, setPlan] = useState(null);
      const [editingSuppIdx, setEditingSuppIdx] = useState(null); // index or "new"
      const [suppForm, setSuppForm] = useState({ name: "", pills: 1, timing: "AM", dose: "", category: "general", notes: "" });
      const [actSchedule, setActSchedule] = useState({ weekdayTime: "6:00 AM", weekendTime: "8:00 AM" });
      const [todayWorkout, setTodayWorkout] = useState(null);
      const [dynamicMacros, setDynamicMacros] = useState(null);
      // Auto-correct 100x macro inflation from the old MFP scraper bug (fixed in 9e52c64).
      // If a macro value exceeds 10x its physiological max, divide by 100.
      const fixMacro = (v, max) => {
        if (!v || v <= 0) return 0;
        if (v > max * 10) return Math.round(v / 100);
        return v > max ? 0 : v;
      };
      const sanitizeItem = (item) => ({
        ...item,
        calories: fixMacro(item.calories, 3000),
        protein: fixMacro(item.protein, 200),
        carbs: fixMacro(item.carbs, 500),
        fat: fixMacro(item.fat, 200),
        sodium: Math.min(item.sodium || 0, 10000),
        sugar: fixMacro(item.sugar, 300),
        fiber: fixMacro(item.fiber, 100),
      });
      const normalizeDiaryEntry = (entry) => {
        if (!entry) return entry;
        const result = { ...entry };
        // Sanitize totals
        if (result.totals) {
          result.totals = { ...result.totals,
            calories: fixMacro(result.totals.calories, 6000),
            protein: fixMacro(result.totals.protein, 350),
            carbs:   fixMacro(result.totals.carbs,   900),  // up to 900g in carb loading phase
            fat:     fixMacro(result.totals.fat,      250),
          };
        }
        // Sanitize individual meal items
        if (result.meals) {
          const cleaned = {};
          for (const [meal, items] of Object.entries(result.meals)) {
            cleaned[meal] = (items || []).map(sanitizeItem);
          }
          result.meals = cleaned;
        }
        if (result.items) {
          result.items = result.items.map(sanitizeItem);
        }
        return result;
      };

      // MFP Diary state
      const [diaryDate, setDiaryDate] = useState(new Date().toISOString().split("T")[0]);
      const [diaryData, setDiaryData] = useState(null);
      const [diaryHistory, setDiaryHistory] = useState([]);
      const [diaryLoading, setDiaryLoading] = useState(false);
      const [syncingMfp, setSyncingMfp] = useState(false);
      const [mfpConnected, setMfpConnected] = useState(null); // null=unknown, true/false
      const [mfpUsername, setMfpUsername] = useState("");
      const [mfpUsernameInput, setMfpUsernameInput] = useState("");
      const [mfpMsg, setMfpMsg] = useState(null);

      // RED-S awareness: healthEntries + nutHistoryAll now from DataProvider

      const today = new Date().toISOString().split("T")[0];
      const isWeekend = [0, 6].includes(new Date().getDay());

      // Sanity-check macro values — returns null for any that imply >4x the calorie total
      // or exceed physiologically possible daily intake.
      // Sync today's nutrition from DataProvider into local nutritionData state
      useEffect(() => {
        if (todayNutrition) setNutritionData(todayNutrition);
      }, [todayNutrition]);

      // Derive today's workout from DataProvider activePlan
      useEffect(() => {
        if (todayPlan?.weeks) {
          const dayNames = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
          const todayDayName = dayNames[new Date().getDay()];
          const currentWeek = todayPlan.weeks[todayPlan.weeks.length - 1];
          if (currentWeek?.days) {
            const dayMatch = currentWeek.days.find(d => d.day === todayDayName);
            if (dayMatch) setTodayWorkout(dayMatch);
          }
        }
      }, [todayPlan]);

      useEffect(() => {
        if (!userId) return;
        // Load activity schedule
        db.collection("users").doc(userId).collection("settings")
          .doc("activitySchedule").get().then(doc => {
            if (doc.exists) setActSchedule(prev => ({ ...prev, ...doc.data() }));
          });
        // Load dynamic macros (set by AI nutrition plan)
        db.collection("users").doc(userId).collection("settings")
          .doc("dynamicMacros").onSnapshot(doc => {
            if (doc.exists && doc.data().date === today) setDynamicMacros(doc.data().targets);
          });
      }, [userId]);

      // saveSupplements now from DataProvider

      const startEditSupp = (idx) => {
        if (idx === "new") {
          setSuppForm({ name: "", pills: 1, timing: "AM", dose: "", category: "general", notes: "" });
        } else {
          const s = supplements[idx];
          setSuppForm({ name: s.name || "", pills: s.pills || 1, timing: s.timing || "AM", dose: s.dose || s.dosage || "", category: s.category || "general", notes: s.notes || "" });
        }
        setEditingSuppIdx(idx);
      };

      const saveSuppForm = () => {
        if (!suppForm.name.trim()) return;
        const entry = { ...suppForm, name: suppForm.name.trim(), pills: parseInt(suppForm.pills) || 1 };
        let newList;
        if (editingSuppIdx === "new") {
          newList = [...supplements, entry];
        } else {
          newList = supplements.map((s, i) => i === editingSuppIdx ? entry : s);
        }
        saveSupplements(newList);
        setEditingSuppIdx(null);
      };

      const deleteSupp = (idx) => {
        if (!isOwner) return;
        saveSupplements(supplements.filter((_, i) => i !== idx));
        setEditingSuppIdx(null);
      };

      const duplicateSupp = (idx) => {
        const s = supplements[idx];
        const newEntry = { ...s, timing: s.timing === "AM" ? "PM" : "AM" };
        saveSupplements([...supplements, newEntry]);
      };

      // ── MFP Diary functions ──
      // Check if MFP is connected
      useEffect(() => {
        if (!userId) return;
        db.collection("users").doc(userId).collection("settings").doc("mfp").get().then(doc => {
          if (doc.exists && doc.data()?.username) {
            setMfpConnected(true);
            setMfpUsername(doc.data().username);
          } else {
            setMfpConnected(false);
          }
        }).catch(() => setMfpConnected(false));
      }, [userId]);

      // Load diary for selected date
      useEffect(() => {
        if (!userId || !diaryDate) return;
        setDiaryLoading(true);
        db.collection("users").doc(userId).collection("mfpDiary").doc(diaryDate)
          .get().then(doc => {
            setDiaryData(doc.exists ? normalizeDiaryEntry(doc.data()) : null);
            setDiaryLoading(false);
          }).catch(() => setDiaryLoading(false));
      }, [userId, diaryDate]);

      // Load last 28 days of diary history for trends + week view
      useEffect(() => {
        if (!userId || (tab !== "Diary" && tab !== "Week")) return;
        const cutoff = new Date();
        cutoff.setDate(cutoff.getDate() - 28);
        const startStr = cutoff.toISOString().split("T")[0];
        db.collection("users").doc(userId).collection("mfpDiary")
          .where("date", ">=", startStr)
          .orderBy("date", "desc")
          .get().then(snap => {
            setDiaryHistory(snap.docs.map(d => normalizeDiaryEntry(d.data())));
          });
      }, [userId, tab]);

      // One-click MFP sync via server-side Puppeteer
      const syncMfpNow = async (daysBack = 7) => {
        if (!isOwner) return;
        if (!mfpUsername) { setMfpMsg({ type: "error", text: "Set your MFP username first" }); return; }
        setSyncingMfp(true);
        setMfpMsg({ type: "info", text: `Syncing ${daysBack} days from MyFitnessPal...` });
        try {
          const fn = functions.httpsCallable("syncMfpServer");
          const result = await fn({ daysBack });
          const { saved, errors } = result.data;
          if (saved > 0) {
            setMfpMsg({ type: "success", text: `Synced ${saved} day${saved !== 1 ? "s" : ""} from MyFitnessPal${errors?.length ? ` (${errors.length} errors)` : ""}` });
          } else {
            setMfpMsg({ type: "error", text: "No food data found. Make sure your MFP diary is public and has logged food." });
          }
          // Reload current diary date
          const doc = await db.collection("users").doc(userId).collection("mfpDiary").doc(diaryDate).get();
          setDiaryData(doc.exists ? doc.data() : null);
          const fourteenDaysAgo = new Date();
          fourteenDaysAgo.setDate(fourteenDaysAgo.getDate() - 14);
          const snap = await db.collection("users").doc(userId).collection("mfpDiary")
            .where("date", ">=", fourteenDaysAgo.toISOString().split("T")[0])
            .orderBy("date", "desc").get();
          setDiaryHistory(snap.docs.map(d => normalizeDiaryEntry(d.data())));
          refreshNutrition(); // Refresh DataProvider's merged nutrition
        } catch (err) {
          console.error("[mfp sync]", err);
          setMfpMsg({ type: "error", text: err.message || "Sync failed" });
        }
        setSyncingMfp(false);
      };

      const [bookmarkletToken, setBookmarkletToken] = useState(null);
      const [showMfpPaste, setShowMfpPaste] = useState(false);
      const [mfpPasteText, setMfpPasteText] = useState("");

      // Parse pasted MFP diary text (plain text from Ctrl+A on MFP diary page)
      const parseMfpPaste = (text) => {
        const lines = text.split("\n").map(l => l.trim()).filter(Boolean);
        const meals = {};
        const items = [];
        let currentMeal = "";
        let totals = { calories: 0, protein: 0, carbs: 0, fat: 0 };
        const mealHeaders = ["breakfast", "lunch", "dinner", "snacks", "meal 1", "meal 2", "meal 3", "meal 4", "meal 5", "meal 6"];

        for (let i = 0; i < lines.length; i++) {
          const line = lines[i];
          const lower = line.toLowerCase();

          // Detect meal headers
          if (mealHeaders.some(m => lower === m || lower.startsWith(m + " total"))) {
            if (lower.includes("total")) continue; // skip totals row for meals
            currentMeal = line;
            if (!meals[currentMeal]) meals[currentMeal] = [];
            continue;
          }

          // Detect "Totals" row
          if (lower === "totals" || lower.startsWith("totals\t") || lower.startsWith("totals ")) {
            // Next values on same line or next line are the totals
            const nums = line.match(/[\d,]+/g);
            if (nums && nums.length >= 4) {
              totals = {
                calories: parseInt(nums[0].replace(/,/g, "")) || 0,
                carbs: parseInt(nums[1].replace(/,/g, "")) || 0,
                fat: parseInt(nums[2].replace(/,/g, "")) || 0,
                protein: parseInt(nums[3].replace(/,/g, "")) || 0,
              };
            }
            continue;
          }

          // Try to parse a food item line — look for a name followed by numbers
          // MFP format: "Food Name    Calories    Carbs    Fat    Protein" (tab or space separated)
          if (currentMeal) {
            // Split by tabs first, then by 2+ spaces
            let parts = line.split("\t").map(p => p.trim()).filter(Boolean);
            if (parts.length < 3) parts = line.split(/\s{2,}/).map(p => p.trim()).filter(Boolean);

            if (parts.length >= 2) {
              // Find where numbers start
              let nameEnd = -1;
              for (let j = 1; j < parts.length; j++) {
                if (/^[\d,]+$/.test(parts[j])) { nameEnd = j; break; }
              }
              if (nameEnd > 0) {
                const name = parts.slice(0, nameEnd).join(" ");
                const nums = parts.slice(nameEnd).map(n => parseInt(n.replace(/,/g, "")) || 0);
                if (name && nums.length >= 1 && !name.toLowerCase().includes("add food") && !name.toLowerCase().includes("quick tools")) {
                  const item = {
                    meal: currentMeal,
                    name,
                    calories: nums[0] || 0,
                    carbs: nums[1] || 0,
                    fat: nums[2] || 0,
                    protein: nums[3] || 0,
                  };
                  items.push(item);
                  meals[currentMeal].push(item);
                }
              }
            }
          }
        }

        // If totals weren't explicitly found, sum items
        if (totals.calories === 0 && items.length > 0) {
          totals = items.reduce((t, it) => ({
            calories: t.calories + it.calories,
            carbs: t.carbs + it.carbs,
            fat: t.fat + it.fat,
            protein: t.protein + it.protein,
          }), { calories: 0, carbs: 0, fat: 0, protein: 0 });
        }

        return { meals, items, totals };
      };

      const handleMfpPaste = async () => {
        if (!isOwner) return;
        if (!mfpPasteText.trim()) return;
        const { meals, items, totals } = parseMfpPaste(mfpPasteText);
        if (items.length === 0) {
          setMfpMsg({ type: "error", text: "Could not find any food items in the pasted text. Make sure you're copying from the MFP diary page (Ctrl+A then Ctrl+C)." });
          setShowMfpPaste(false);
          return;
        }
        // Save to Firestore directly (no server round-trip needed)
        try {
          const dateStr = diaryDate;
          const payload = {
            date: dateStr,
            meals,
            items,
            totals,
            source: "paste",
            syncedAt: firebase.firestore.FieldValue.serverTimestamp(),
          };
          await db.collection("users").doc(userId).collection("mfpDiary").doc(dateStr).set(payload);
          await db.collection("users").doc(userId).collection("nutrition").doc(dateStr).set({
            date: dateStr,
            calories: totals.calories,
            protein: totals.protein,
            carbs: totals.carbs,
            fat: totals.fat,
            source: "mfp_paste",
            updatedAt: firebase.firestore.FieldValue.serverTimestamp(),
          }, { merge: true });
          setDiaryData(payload);
          setMfpMsg({ type: "success", text: `Imported ${items.length} items, ${totals.calories} cal for ${dateStr}` });
          setShowMfpPaste(false);
          setMfpPasteText("");
        } catch (err) {
          setMfpMsg({ type: "error", text: "Save failed: " + err.message });
        }
      };

      const saveMfpCreds = async () => {
        if (!mfpUsernameInput.trim()) return;
        setMfpMsg(null);
        setSyncingMfp(true);
        try {
          // Generate a bookmarklet token if not already set
          const mfpDoc = await db.collection("users").doc(userId).collection("settings").doc("mfp").get();
          let token = mfpDoc.exists ? mfpDoc.data().bookmarkletToken : null;
          if (!token) {
            token = Array.from(crypto.getRandomValues(new Uint8Array(24)), b => b.toString(16).padStart(2,"0")).join("");
          }
          await db.collection("users").doc(userId).collection("settings").doc("mfp").set({
            username: mfpUsernameInput.trim(),
            bookmarkletToken: token,
            updatedAt: firebase.firestore.FieldValue.serverTimestamp(),
          }, { merge: true });
          setBookmarkletToken(token);
          setMfpConnected(true);
          setMfpUsername(mfpUsernameInput.trim());
          setMfpUsernameInput("");
          setMfpMsg({ type: "success", text: "Username saved! Use 'Paste from MFP' to sync your diary." });
        } catch (err) {
          setMfpMsg({ type: "error", text: err.message || "Failed to save" });
        }
        setSyncingMfp(false);
      };

      // Load bookmarklet token on mount
      useEffect(() => {
        if (!userId) return;
        db.collection("users").doc(userId).collection("settings").doc("mfp").get().then(doc => {
          if (doc.exists && doc.data().bookmarkletToken) setBookmarkletToken(doc.data().bookmarkletToken);
        });
      }, [userId]);

      // Flag foods near workouts (within 2hr before or 45min after)
      const flagPrePostWorkout = useMemo(() => {
        if (!diaryData || !activities) return {};
        const dayActivities = activities.filter(a => {
          const d = a.start_date?.toDate ? a.start_date.toDate() : new Date(a.start_date);
          return d.toISOString().split("T")[0] === diaryDate && (a.type === "Run" || a.type === "VirtualRun" || a.type === "Ride" || a.type === "Swim" || a.type === "WeightTraining" || a.type === "Workout");
        });
        if (dayActivities.length === 0) return {};
        const flags = {};
        const mealTimes = { Breakfast: 8, Lunch: 12, Dinner: 18, Snacks: 15 }; // rough hours
        dayActivities.forEach(act => {
          const actDate = act.start_date?.toDate ? act.start_date.toDate() : new Date(act.start_date);
          const actHour = actDate.getHours() + actDate.getMinutes() / 60;
          const actEndHour = actHour + (act.elapsed_time || act.moving_time || 3600) / 3600;
          Object.entries(mealTimes).forEach(([meal, hour]) => {
            if (hour >= actHour - 2 && hour <= actHour) flags[meal] = "pre";
            else if (hour >= actEndHour && hour <= actEndHour + 0.75) flags[meal] = "post";
          });
        });
        return flags;
      }, [diaryData, activities, diaryDate]);

      // Canonical macros for the day shown in the Diary tab: pulled from
      // the merged history (same source the Health page Today's Macros,
      // Macro Trends chart, and Week view read). Falls back to a derived
      // entry from raw diaryData only when the merged history hasn't
      // loaded yet, so all derived insights (commentary, deficit, macro
      // split, target progress) agree on the same numbers.
      const canonicalDay = useMemo(() => {
        const merged = nutHistoryAll?.find(h => h.date === diaryDate);
        if (merged) return merged;
        if (!diaryData) return null;
        const t = diaryData.totals || {};
        return {
          date: diaryDate,
          calories: Number(t.calories) || 0,
          protein:  Number(t.protein)  || 0,
          carbs:    Number(t.carbs)    || 0,
          fat:      Number(t.fat)      || 0,
          fiber:    Number(t.fiber)    || 0,
        };
      }, [nutHistoryAll, diaryDate, diaryData]);

      // Calorie deficit calculations
      const deficitCalcs = useMemo(() => {
        if (!canonicalDay || !canonicalDay.calories) return null;
        const bmr = 1800; // Rough estimate for active male runner
        const tdee = bmr * 1.4; // Moderate activity multiplier (running separate)
        const exerciseCals = diaryData?.exerciseCalories || activities.filter(a => {
          const d = a.start_date?.toDate ? a.start_date.toDate() : new Date(a.start_date);
          return d.toISOString().split("T")[0] === diaryDate;
        }).reduce((s, a) => s + (a.calories || 0), 0);
        const intake = canonicalDay.calories || 0;
        const deficitWithoutExercise = tdee - intake;
        const deficitWithExercise = (tdee + exerciseCals) - intake;
        const weeklyDeficit = deficitWithExercise * 7;
        const projectedWeeklyLoss = weeklyDeficit / 3500; // 3500 cal ≈ 1 lb
        return { intake, tdee, exerciseCals, deficitWithoutExercise, deficitWithExercise, projectedWeeklyLoss };
      }, [canonicalDay, diaryData, activities, diaryDate]);

      const saveSchedule = (updates) => {
        const newSched = { ...actSchedule, ...updates };
        setActSchedule(newSched);
        db.collection("users").doc(userId).collection("settings")
          .doc("activitySchedule").set(newSched, { merge: true });
      };

      // Calculate yesterday's calories burned
      const yesterdayCalories = useMemo(() => {
        const yd = new Date(); yd.setDate(yd.getDate() - 1); yd.setHours(0,0,0,0);
        const ydEnd = new Date(yd); ydEnd.setDate(yd.getDate() + 1);
        return activities.filter(a => {
          const d = a.start_date?.toDate ? a.start_date.toDate() : new Date(a.start_date);
          return d >= yd && d < ydEnd;
        }).reduce((s, a) => s + (a.calories || 0), 0);
      }, [activities]);

      const getTodaysPlan = async () => {
        setLoadingPlan(true);
        try {
          const nextRun = activities
            .filter(a => {
              const d = a.start_date?.toDate ? a.start_date.toDate() : new Date(a.start_date);
              return d >= new Date() && (a.type==="Run"||a.type==="VirtualRun");
            })
            .sort((a,b) => a.start_date?.seconds - b.start_date?.seconds)[0];

          const lastRun = activities
            .filter(a => {
              const d = a.start_date?.toDate ? a.start_date.toDate() : new Date(a.start_date);
              return d < new Date() && (a.type==="Run"||a.type==="VirtualRun");
            })
            .sort((a,b) => b.start_date?.seconds - a.start_date?.seconds)[0];

          const generateNutritionPlan = functions.httpsCallable("generateNutritionPlan");
          const result = await generateNutritionPlan({
            date: today,
            nutritionLog: nutritionData,
            nextRun: nextRun ? {
              distance: nextRun.distance,
              name: nextRun.name,
            } : null,
            lastRun: lastRun ? {
              distance: lastRun.distance,
              calories: lastRun.calories,
            } : null,
            supplements,
            schedule: actSchedule,
            todayWorkout,
            yesterdayCaloriesBurned: yesterdayCalories || 0,
          });
          setPlan(result.data);
        } catch (err) {
          console.error(err);
          setPlan({ error: "Failed to generate plan. Please try again." });
        }
        setLoadingPlan(false);
      };

      // nutRedsRisk from DataProvider (aliased above)

      const macroColors = { protein: C.purple, carbs: C.amber, fat: C.cyan, fiber: C.green };
      // Use dynamic macros (from AI) if available, otherwise defaults based on workout type
      const getDefaultTarget = (key) => {
        const isHard = todayWorkout && ["tempo","intervals","long","race_pace"].includes(todayWorkout.type);
        const isRest = !todayWorkout || todayWorkout.type === "rest";
        const defaults = {
          calories: isHard ? 2800 : isRest ? 2100 : 2400,
          protein: isHard ? 180 : 170,
          carbs: isHard ? 350 : isRest ? 200 : 280,
          fat: isHard ? 70 : isRest ? 90 : 80,
        };
        return defaults[key] || 0;
      };
      const todayMacros = [
        { key:"calories", label:"Calories", value: nutritionData.calories || 0, target: dynamicMacros?.calories || getDefaultTarget("calories"), unit:"kcal", color:C.pink },
        { key:"protein", label:"Protein", value: nutritionData.protein || 0, target: dynamicMacros?.protein || getDefaultTarget("protein"), unit:"g", color:C.purple },
        { key:"carbs", label:"Carbs", value: nutritionData.carbs || 0, target: dynamicMacros?.carbs || getDefaultTarget("carbs"), unit:"g", color:C.amber },
        { key:"fat", label:"Fat", value: nutritionData.fat || 0, target: dynamicMacros?.fat || getDefaultTarget("fat"), unit:"g", color:C.cyan },
      ];

      return (
        <div style={{display:"flex",flexDirection:"column",gap:20}}>
          <div>
            <div style={{fontFamily:"'Space Grotesk', sans-serif",fontSize:26,fontWeight:800,color:C.text,marginBottom:4}}>Nutrition</div>
            <div style={{color:C.textMuted,fontSize:13}}>Fueling insights & macro tracking</div>
          </div>

          {/* RED-S Alert Banner (shows when score < 80) */}
          {nutRedsRisk && nutRedsRisk.score < 80 && (
            <Card style={{borderColor:nutRedsRisk.riskColor+"50",background:nutRedsRisk.riskColor+"06",padding:14}}>
              <div style={{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12}}>
                <div style={{flex:1}}>
                  <div style={{display:"flex",alignItems:"center",gap:8,marginBottom:6}}>
                    <span style={{fontSize:13,fontWeight:700,color:nutRedsRisk.riskColor}}>RED-S Risk: {nutRedsRisk.riskLevel.toUpperCase()}</span>
                    <span style={{fontSize:11,color:C.textMuted}}>Score {nutRedsRisk.score}/100</span>
                    {nutRedsRisk.ea !== null && <span style={{fontSize:10,padding:"2px 6px",borderRadius:4,
                      background:nutRedsRisk.ea < 30 ? C.red+"20" : C.amber+"20",
                      color:nutRedsRisk.ea < 30 ? C.red : C.amber}}>EA: {nutRedsRisk.ea} kcal/kg</span>}
                  </div>
                  {nutRedsRisk.suggestions.slice(0,2).map((s,i) => (
                    <div key={i} style={{fontSize:11,color:C.textDim,lineHeight:1.6,marginBottom:2}}>{s}</div>
                  ))}
                </div>
                <div style={{position:"relative",width:44,height:44,flexShrink:0}}>
                  <svg viewBox="0 0 36 36" style={{transform:"rotate(-90deg)",width:44,height:44}}>
                    <circle cx="18" cy="18" r="15" fill="none" stroke={C.bg3} strokeWidth="3" />
                    <circle cx="18" cy="18" r="15" fill="none" stroke={nutRedsRisk.riskColor} strokeWidth="3"
                      strokeDasharray={`${nutRedsRisk.score * 0.942} 94.2`} strokeLinecap="round" />
                  </svg>
                  <div style={{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",
                    fontSize:12,fontWeight:800,color:nutRedsRisk.riskColor}}>{nutRedsRisk.score}</div>
                </div>
              </div>
            </Card>
          )}

          <TabBar tabs={["Week","Diary","Schedule","Pre/Post Run","Supplements"]} active={tab} onChange={tab => setTab(tab)} />

          {tab === "Week" && (() => {
            // Calculate week boundaries (Mon-Sun). weekOffset=0 is the
            // current week; negative values step backwards through history.
            const now = new Date();
            const dayOfWeek = now.getDay(); // 0=Sun
            const mondayOffset = dayOfWeek === 0 ? -6 : 1 - dayOfWeek;
            const baseMonday = new Date(now); baseMonday.setDate(now.getDate() + mondayOffset); baseMonday.setHours(0,0,0,0);
            const thisMonday = new Date(baseMonday); thisMonday.setDate(baseMonday.getDate() + (weekOffset * 7));
            const thisSunday = new Date(thisMonday); thisSunday.setDate(thisMonday.getDate() + 6);
            const prevMonday = new Date(thisMonday); prevMonday.setDate(thisMonday.getDate() - 7);
            const prevSunday = new Date(thisMonday); prevSunday.setDate(thisMonday.getDate() - 1);
            const isCurrentWeek = weekOffset === 0;

            const fmt2 = d => d.toISOString().split("T")[0];
            const dayNames = ["Mon","Tue","Wed","Thu","Fri","Sat","Sun"];

            // Build current week days array.
            // Source is the canonical merged history (nutrition + mfpDiary
            // run through mergeNutritionDay), NOT the raw mfpDiary docs.
            // Raw docs let the MFP "Your Daily Goal" row (≈1750 kcal) leak
            // through as if it were logged intake; the merge rejects that
            // and is the single source of truth every other view uses.
            const thisWeekDays = [];
            for (let i = 0; i < 7; i++) {
              const d = new Date(thisMonday); d.setDate(thisMonday.getDate() + i);
              const dateStr = fmt2(d);
              const entry = nutHistoryAll.find(h => h.date === dateStr);
              thisWeekDays.push({ day: dayNames[i], date: dateStr, data: entry || null });
            }

            // Build prior week days
            const prevWeekDays = [];
            for (let i = 0; i < 7; i++) {
              const d = new Date(prevMonday); d.setDate(prevMonday.getDate() + i);
              const dateStr = fmt2(d);
              const entry = nutHistoryAll.find(h => h.date === dateStr);
              prevWeekDays.push({ day: dayNames[i], date: dateStr, data: entry || null });
            }

            // Read macros from a merged history entry. The DataProvider
            // already ran every per-day record through mergeNutritionDay,
            // which is the single source of truth — it normalizes scraper
            // inflation, rejects MFP "Your Daily Goal" leaks, and per-macro
            // backfills any field the writer omitted (e.g. fiber from the
            // bookmarklet). This helper is just a safe accessor so the
            // Week view shows the same numbers the Health page does.
            const cleanMacros = (data) => {
              if (!data) return { calories: 0, protein: 0, carbs: 0, fat: 0 };
              return {
                calories: Number(data.calories) || 0,
                protein:  Number(data.protein)  || 0,
                carbs:    Number(data.carbs)    || 0,
                fat:      Number(data.fat)      || 0,
              };
            };

            // Helper: avg only days with data
            const weekAvg = (days, key) => {
              const withData = days.filter(d => d.data && cleanMacros(d.data)[key] > 0);
              if (withData.length === 0) return 0;
              const sum = withData.reduce((s, d) => s + cleanMacros(d.data)[key], 0);
              return Math.round(sum / withData.length);
            };
            const weekTotal = (days, key) => {
              return days.filter(d => d.data).reduce((s, d) => s + cleanMacros(d.data)[key], 0);
            };
            const daysLogged = (days) => days.filter(d => d.data && cleanMacros(d.data).calories > 0).length;

            // All-time (28-day) average from the merged history — only
            // days with real food. Merged entries are flat; goal-leak
            // days come back with calories 0 and are excluded here.
            const allWithData = nutHistoryAll.filter(h => cleanMacros(h).calories > 0);
            const allAvg = (key) => {
              if (allWithData.length === 0) return 0;
              const sum = allWithData.reduce((s, h) => s + cleanMacros(h)[key], 0);
              return Math.round(sum / allWithData.length);
            };

            const macros = ["calories", "protein", "carbs", "fat"];
            const macroLabels = { calories: "Calories", protein: "Protein", carbs: "Carbs", fat: "Fat" };
            const macroUnits = { calories: "kcal", protein: "g", carbs: "g", fat: "g" };
            const macroCol = { calories: C.pink, protein: C.purple, carbs: C.amber, fat: C.cyan };

            const thisAvg = {}; const prevAvg = {}; const avgAll = {};
            macros.forEach(k => { thisAvg[k] = weekAvg(thisWeekDays, k); prevAvg[k] = weekAvg(prevWeekDays, k); avgAll[k] = allAvg(k); });

            // Delta helper
            const delta = (curr, prev) => {
              if (!prev || prev === 0) return null;
              return Math.round(((curr - prev) / prev) * 100);
            };

            return (
            <div style={{display:"flex",flexDirection:"column",gap:16}}>
              {/* Week summary header */}
              <Card>
                <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:14,gap:12,flexWrap:"wrap"}}>
                  <div style={{display:"flex",alignItems:"center",gap:8}}>
                    <button onClick={() => setWeekOffset(o => o - 1)}
                      title="Previous week"
                      style={{background:"none",border:`1px solid ${C.border}`,borderRadius:6,padding:"4px 10px",cursor:"pointer",fontSize:12,color:C.textDim,fontFamily:"'IBM Plex Mono',monospace"}}>
                      ◀
                    </button>
                    <div>
                      <div style={{fontSize:13,fontWeight:700,color:C.text}}>
                        {weekOffset === 0 ? "This Week" : weekOffset === -1 ? "Last Week" : `${Math.abs(weekOffset)} Weeks Ago`}
                      </div>
                      <div style={{fontSize:11,color:C.textMuted}}>{fmt2(thisMonday)} → {fmt2(thisSunday)} · {daysLogged(thisWeekDays)} of 7 days logged</div>
                    </div>
                    <button onClick={() => setWeekOffset(o => Math.min(0, o + 1))}
                      disabled={isCurrentWeek}
                      title={isCurrentWeek ? "Already on the current week" : "Next week"}
                      style={{background:"none",border:`1px solid ${C.border}`,borderRadius:6,padding:"4px 10px",cursor:isCurrentWeek?"default":"pointer",fontSize:12,color:isCurrentWeek?C.border:C.textDim,fontFamily:"'IBM Plex Mono',monospace"}}>
                      ▶
                    </button>
                    {!isCurrentWeek && (
                      <button onClick={() => setWeekOffset(0)}
                        title="Jump back to the current week"
                        style={{background:"none",border:`1px solid ${C.cyan}40`,borderRadius:6,padding:"4px 10px",cursor:"pointer",fontSize:11,color:C.cyan,fontFamily:"'IBM Plex Mono',monospace"}}>
                        Today
                      </button>
                    )}
                  </div>
                  {mfpConnected && isCurrentWeek && (
                    <Btn onClick={() => { setTab("Diary"); }} variant="secondary" small>
                      + Log Food
                    </Btn>
                  )}
                </div>

                {/* Daily macro bars chart */}
                <ResponsiveContainer width="100%" height={160}>
                  <ComposedChart data={thisWeekDays.map(d => {
                    const m = cleanMacros(d.data);
                    return {
                      name: d.day,
                      calories: m.calories,
                      protein: m.protein,
                      carbs: m.carbs,
                      fat: m.fat,
                      hasData: !!(d.data && m.calories > 0),
                    };
                  })} margin={{top:5,right:5,left:-15,bottom:5}}>
                    <CartesianGrid strokeDasharray="3 3" stroke={C.border+"30"} />
                    <XAxis dataKey="name" tick={{fontSize:10,fill:C.textMuted}} />
                    <YAxis tick={{fontSize:10,fill:C.textMuted}} />
                    <Tooltip contentStyle={{background:C.bg2,border:`1px solid ${C.border}`,borderRadius:8,fontSize:11,color:C.text}} />
                    <Bar dataKey="calories" fill={C.pink+"70"} stroke={C.pink} strokeWidth={1} radius={[3,3,0,0]} name="Calories" />
                    <ReferenceLine y={1750} stroke={C.amber} strokeDasharray="6 3" label={{value:"Goal",position:"right",fontSize:9,fill:C.amber}} />
                    {avgAll.calories > 0 && <ReferenceLine y={avgAll.calories} stroke={C.textMuted} strokeDasharray="4 4" label={{value:"Avg",position:"left",fontSize:9,fill:C.textMuted}} />}
                  </ComposedChart>
                </ResponsiveContainer>
              </Card>

              {/* Daily averages comparison: This Week vs Prior Week vs Overall */}
              <Card>
                <div style={{fontSize:13,fontWeight:700,color:C.text,marginBottom:12}}>Daily Averages</div>
                <div style={{display:"grid",gridTemplateColumns:"auto 1fr 1fr 1fr",gap:"8px 16px",alignItems:"center"}}>
                  {/* Header row */}
                  <div style={{fontSize:10,color:C.textMuted}}></div>
                  <div style={{fontSize:10,color:C.textMuted,textAlign:"center",fontWeight:600}}>This Week</div>
                  <div style={{fontSize:10,color:C.textMuted,textAlign:"center",fontWeight:600}}>Last Week</div>
                  <div style={{fontSize:10,color:C.textMuted,textAlign:"center",fontWeight:600}}>28-Day Avg</div>

                  {macros.map(k => {
                    const d1 = delta(thisAvg[k], prevAvg[k]);
                    const d2 = delta(thisAvg[k], avgAll[k]);
                    return (
                      <React.Fragment key={k}>
                        <div style={{fontSize:12,fontWeight:600,color:macroCol[k]}}>{macroLabels[k]}</div>
                        <div style={{textAlign:"center"}}>
                          <div style={{fontSize:16,fontWeight:700,color:C.text}}>{thisAvg[k].toLocaleString()}</div>
                          <div style={{fontSize:10,color:C.textMuted}}>{macroUnits[k]}/day</div>
                        </div>
                        <div style={{textAlign:"center"}}>
                          <div style={{fontSize:14,fontWeight:600,color:C.textDim}}>{prevAvg[k].toLocaleString()}</div>
                          {d1 !== null && <div style={{fontSize:10,color: k === "fat" ? (d1 <= 0 ? C.green : C.red) : (d1 >= 0 ? C.green : C.red)}}>
                            {d1 > 0 ? "+" : ""}{d1}%
                          </div>}
                        </div>
                        <div style={{textAlign:"center"}}>
                          <div style={{fontSize:14,fontWeight:600,color:C.textDim}}>{avgAll[k].toLocaleString()}</div>
                          {d2 !== null && <div style={{fontSize:10,color: k === "fat" ? (d2 <= 0 ? C.green : C.red) : (d2 >= 0 ? C.green : C.red)}}>
                            {d2 > 0 ? "+" : ""}{d2}%
                          </div>}
                        </div>
                      </React.Fragment>
                    );
                  })}
                </div>
                <div style={{marginTop:10,fontSize:10,color:C.textMuted,fontStyle:"italic"}}>
                  Averages based on {daysLogged(thisWeekDays)} days this week, {daysLogged(prevWeekDays)} last week, {allWithData.length} days total
                </div>
              </Card>

              {/* Day-by-day breakdown */}
              <Card>
                <div style={{fontSize:13,fontWeight:700,color:C.text,marginBottom:10}}>Day by Day</div>
                <div style={{display:"flex",flexDirection:"column",gap:6}}>
                  {thisWeekDays.map((d, i) => {
                    const macros = cleanMacros(d.data);
                    const cal = macros.calories;
                    const pro = macros.protein;
                    const carb = macros.carbs;
                    const fat = macros.fat;
                    const isToday = d.date === today;
                    const isFuture = d.date > today;
                    const hasData = cal > 0;

                    return (
                      <div key={i} style={{
                        display:"flex",alignItems:"center",gap:10,padding:"8px 12px",
                        background: isToday ? C.cyan+"08" : "transparent",
                        border:`1px solid ${isToday ? C.cyan+"30" : C.border+"30"}`,
                        borderRadius:8,opacity: isFuture ? 0.4 : 1,
                      }}>
                        <div style={{width:36,fontSize:11,fontWeight:700,color: isToday ? C.cyan : C.textMuted}}>{d.day}</div>
                        <div style={{width:70,fontSize:10,color:C.textMuted}}>{d.date.slice(5)}</div>
                        {hasData ? (
                          <div style={{flex:1,display:"flex",gap:16,alignItems:"center"}}>
                            <div style={{fontSize:14,fontWeight:700,color:C.pink,minWidth:55}}>{cal.toLocaleString()}</div>
                            <div style={{display:"flex",gap:10,fontSize:11}}>
                              <span style={{color:C.purple}}>P {pro}g</span>
                              <span style={{color:C.amber}}>C {carb}g</span>
                              <span style={{color:C.cyan}}>F {fat}g</span>
                            </div>
                            {/* Mini bar showing cal vs avg */}
                            {avgAll.calories > 0 && (
                              <div style={{flex:1,maxWidth:80}}>
                                <div style={{height:4,background:C.bg3,borderRadius:2,overflow:"hidden"}}>
                                  <div style={{width:`${Math.min(100, cal / avgAll.calories * 100)}%`,height:"100%",
                                    background: cal > avgAll.calories * 1.1 ? C.red : cal < avgAll.calories * 0.9 ? C.amber : C.green,
                                    borderRadius:2}} />
                                </div>
                              </div>
                            )}
                          </div>
                        ) : (
                          <div style={{flex:1,fontSize:11,color:C.textMuted,fontStyle:"italic"}}>{isFuture ? "—" : "No data"}</div>
                        )}
                        {isToday && <span style={{fontSize:9,color:C.cyan,fontWeight:700,padding:"2px 6px",background:C.cyan+"15",borderRadius:4}}>TODAY</span>}
                      </div>
                    );
                  })}
                </div>
              </Card>

              {/* Macro split chart */}
              {daysLogged(thisWeekDays) > 0 && (
                <Card>
                  <div style={{fontSize:13,fontWeight:700,color:C.text,marginBottom:10}}>Macro Split (Week Avg)</div>
                  <div style={{display:"flex",gap:16,alignItems:"center",justifyContent:"center"}}>
                    {(() => {
                      const total = (thisAvg.protein || 0) + (thisAvg.carbs || 0) + (thisAvg.fat || 0);
                      if (total === 0) return <div style={{fontSize:11,color:C.textMuted}}>No macro data</div>;
                      const pctP = Math.round((thisAvg.protein / total) * 100);
                      const pctC = Math.round((thisAvg.carbs / total) * 100);
                      const pctF = 100 - pctP - pctC;
                      return (
                        <>
                          {/* Stacked bar */}
                          <div style={{flex:1,maxWidth:300}}>
                            <div style={{display:"flex",height:28,borderRadius:6,overflow:"hidden"}}>
                              <div style={{width:`${pctP}%`,background:C.purple,display:"flex",alignItems:"center",justifyContent:"center",fontSize:10,color:"#fff",fontWeight:700}}>{pctP}%</div>
                              <div style={{width:`${pctC}%`,background:C.amber,display:"flex",alignItems:"center",justifyContent:"center",fontSize:10,color:"#000",fontWeight:700}}>{pctC}%</div>
                              <div style={{width:`${pctF}%`,background:C.cyan,display:"flex",alignItems:"center",justifyContent:"center",fontSize:10,color:"#000",fontWeight:700}}>{pctF}%</div>
                            </div>
                            <div style={{display:"flex",justifyContent:"space-between",marginTop:6}}>
                              <span style={{fontSize:10,color:C.purple}}>Protein {thisAvg.protein}g</span>
                              <span style={{fontSize:10,color:C.amber}}>Carbs {thisAvg.carbs}g</span>
                              <span style={{fontSize:10,color:C.cyan}}>Fat {thisAvg.fat}g</span>
                            </div>
                          </div>
                        </>
                      );
                    })()}
                  </div>
                </Card>
              )}

              {/* AI Plan */}
              <Card>
                <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:16}}>
                  <div style={{fontSize:13,fontWeight:600,color:C.textDim}}>AI Nutrition Plan</div>
                  <Btn onClick={getTodaysPlan} disabled={loadingPlan} small>
                    {loadingPlan ? "Generating..." : "Generate Plan"}
                  </Btn>
                </div>
                {plan ? (
                  plan.error ? (
                    <div style={{color:C.red,fontSize:13}}>{plan.error}</div>
                  ) : (
                    <div style={{display:"flex",flexDirection:"column",gap:12}}>
                      {plan.summary && <div style={{fontSize:14,color:C.text,lineHeight:1.6}}>{plan.summary}</div>}
                      {plan.targets && (
                        <div style={{display:"grid",gridTemplateColumns:"repeat(4,1fr)",gap:12}}>
                          {Object.entries(plan.targets).map(([k,v]) => (
                            <div key={k} style={{textAlign:"center",padding:12,background:C.bg2,borderRadius:8}}>
                              <div style={{fontSize:18,fontWeight:700,color:macroColors[k]||C.cyan}}>{v}</div>
                              <div style={{fontSize:11,color:C.textMuted,textTransform:"capitalize"}}>{k}</div>
                            </div>
                          ))}
                        </div>
                      )}
                      {plan.meals && plan.meals.map((m,i) => (
                        <div key={i} style={{padding:"12px 16px",background:C.bg2,borderRadius:8}}>
                          <div style={{fontSize:12,fontWeight:700,color:C.cyan,marginBottom:4}}>{m.name}</div>
                          <div style={{fontSize:12,color:C.textDim,lineHeight:1.6}}>{m.description}</div>
                        </div>
                      ))}
                    </div>
                  )
                ) : (
                  <div style={{color:C.textMuted,fontSize:13}}>
                    Generate a personalized nutrition plan based on your training schedule and MyFitnessPal data.
                  </div>
                )}
              </Card>
          {/* ── Fuel Balance: Glycogen & Macro Guidance ── */}
          {nutRedsRisk?.fuel && (
            <Card style={{ borderColor: C.amber + "30" }}>
              <div style={{ display:"flex", justifyContent:"space-between", alignItems:"baseline", marginBottom:12 }}>
                <span style={{ fontSize:13, fontWeight:600, color:C.textDim }}>Fuel Balance</span>
                <span style={{ fontSize:10, color:C.textMuted }}>{nutRedsRisk.dataQuality?.nutritionDays || "?"}-day avg</span>
              </div>

              {/* Glycogen gauge — anchored tank when the athlete has
                  declared "stores full as of <date>" (settings/nutrition),
                  else the logged-food replenishment rate */}
              {(() => {
                const fuel = nutRedsRisk.fuel;
                const tank = fuel.glycogenTankPct != null;
                const pct = tank ? fuel.glycogenTankPct : fuel.glycogenPct;
                const col = pct >= 80 ? C.green : pct >= 50 ? C.amber : C.red;
                return (
              <div style={{ display:"flex", gap:16, alignItems:"center", marginBottom:14, padding:"10px 14px", background:C.bg2, borderRadius:8 }}>
                <div style={{ position:"relative", width:56, height:56, flexShrink:0 }}>
                  <svg viewBox="0 0 36 36" style={{ transform:"rotate(-90deg)", width:56, height:56 }}>
                    <circle cx="18" cy="18" r="15" fill="none" stroke={C.bg3} strokeWidth="4" />
                    <circle cx="18" cy="18" r="15" fill="none"
                      stroke={col}
                      strokeWidth="4" strokeDasharray={`${pct * 0.942} 94.2`} strokeLinecap="round" />
                  </svg>
                  <div style={{ position:"absolute", inset:0, display:"flex", alignItems:"center", justifyContent:"center",
                    fontSize:13, fontWeight:800, color: col }}>
                    {pct}%
                  </div>
                </div>
                <div style={{ flex:1 }}>
                  <div style={{ fontSize:12, fontWeight:700, color:C.text, marginBottom:4 }}>{tank ? "Glycogen Stores" : "Glycogen Replenishment"}</div>
                  {tank && (
                    <div style={{ fontSize:11, color:C.textMuted, marginBottom:4 }}>
                      ~<span style={{ color:col, fontWeight:700 }}>{fuel.glycogenTankG}g</span> of {fuel.maxGlycogenG}g capacity —
                      marked full at start of <span style={{ color:C.text, fontWeight:600 }}>{fuel.glycogenFullAsOf}</span>.
                      Logged carbs refill; run burn + baseline oxidation drain.
                      {fuel.glycogenHeldDays > 0 && (
                        <span> {fuel.glycogenHeldDays} day{fuel.glycogenHeldDays === 1 ? "" : "s"} with no food logged
                          {" "}held steady rather than counted as fasted — log to sharpen this.</span>
                      )}
                    </div>
                  )}
                  <div style={{ fontSize:11, color:C.textMuted, lineHeight:1.6 }}>
                    Daily carb usage: ~<span style={{ color:C.amber, fontWeight:600 }}>{fuel.dailyBaselineCarbBurnG}g</span> baseline (brain, organs, movement)
                    + <span style={{ color:C.amber, fontWeight:600 }}>{fuel.avgDailyCarbBurnG}g</span> exercise
                    = <span style={{ color:C.text, fontWeight:700 }}>{fuel.dailyGlycogenUsed}g/day</span> total.
                    {" "}Intake: ~<span style={{ color: fuel.glycogenBalance >= 0 ? C.green : C.red, fontWeight:600 }}>{fuel.dailyGlycogenReplenished}g</span>/day from carbs
                  </div>
                  {!tank && fuel.glycogenBalance < 0 && (
                    <div style={{ fontSize:11, color:C.red, fontWeight:600, marginTop:4 }}>
                      Deficit of {Math.abs(fuel.glycogenBalance)}g/day — glycogen stores depleting
                    </div>
                  )}
                  {!tank && fuel.glycogenBalance >= 0 && (
                    <div style={{ fontSize:11, color:C.green, fontWeight:600, marginTop:4 }}>
                      Surplus of +{fuel.glycogenBalance}g/day — stores maintaining well
                    </div>
                  )}
                </div>
              </div>
                );
              })()}

              {/* Athlete-declared reset — same control as the Summary RED-S card */}
              <NutritionResetControl isOwner={isOwner} />

              {/* Per-workout fuel breakdown */}
              {nutRedsRisk.fuel.activityFuel?.length > 0 && (
                <div style={{ marginBottom:14 }}>
                  <div style={{ fontSize:11, fontWeight:700, color:C.textDim, marginBottom:8 }}>Workout Fuel Estimates (7-day)</div>
                  <div style={{ display:"flex", flexDirection:"column", gap:6 }}>
                    {nutRedsRisk.fuel.activityFuel.map((f, i) => {
                      const dateStr = f.date.toLocaleDateString("en-US", { weekday:"short", month:"short", day:"numeric" });
                      return (
                        <div key={f.id || i} style={{ display:"grid", gridTemplateColumns:"1fr auto", gap:8, alignItems:"center",
                          padding:"8px 12px", background:C.bg2, borderRadius:8, border:`1px solid ${C.border}30` }}>
                          <div>
                            <div style={{ display:"flex", alignItems:"center", gap:8, marginBottom:4 }}>
                              <span style={{ fontSize:12, fontWeight:600, color:C.text }}>{f.name}</span>
                              <span style={{ fontSize:10, color:C.textMuted }}>{dateStr}</span>
                              {f.avgHR && <span style={{ fontSize:10, color:C.pink, fontWeight:600 }}>{f.avgHR} bpm → {f.zone}</span>}
                            </div>
                            <div style={{ display:"flex", alignItems:"center", gap:6 }}>
                              <span style={{ fontSize:10, color:C.textMuted }}>{f.distanceMi} mi · {f.durationMin} min · {f.totalCal} cal</span>
                            </div>
                            {/* Carb/fat stacked bar */}
                            <div style={{ display:"flex", height:6, borderRadius:3, overflow:"hidden", marginTop:4, width:"100%" }}>
                              <div style={{ width:`${f.carbPct}%`, background:C.amber, transition:"width 0.3s" }} />
                              <div style={{ width:`${100 - f.carbPct}%`, background:C.cyan, transition:"width 0.3s" }} />
                            </div>
                          </div>
                          <div style={{ textAlign:"right", minWidth:80 }}>
                            <div style={{ fontSize:12, fontWeight:700, color:C.amber }}>{f.carbG}g <span style={{ fontSize:9, fontWeight:400 }}>carb</span></div>
                            <div style={{ fontSize:12, fontWeight:700, color:C.cyan }}>{f.fatG}g <span style={{ fontSize:9, fontWeight:400 }}>fat</span></div>
                          </div>
                        </div>
                      );
                    })}
                  </div>
                  <div style={{ display:"flex", gap:12, marginTop:6, fontSize:10, color:C.textMuted }}>
                    <span><span style={{ display:"inline-block", width:8, height:8, borderRadius:2, background:C.amber, marginRight:4 }} />Carb burn</span>
                    <span><span style={{ display:"inline-block", width:8, height:8, borderRadius:2, background:C.cyan, marginRight:4 }} />Fat burn</span>
                    <span style={{ marginLeft:"auto", fontStyle:"italic" }}>Based on avg HR zone intensity</span>
                  </div>
                </div>
              )}

              {/* Macro targets vs actual */}
              <div style={{ display:"flex", flexDirection:"column", gap:10 }}>
                {[
                  {
                    label: "Carbs", actual: nutRedsRisk.fuel.avgCarbs, perKg: nutRedsRisk.fuel.carbsPerKg,
                    low: nutRedsRisk.fuel.carbTargetLow, high: nutRedsRisk.fuel.carbTargetHigh,
                    color: C.amber, unit: "g",
                    note: `${nutRedsRisk.fuel.carbLabel} training → need ${nutRedsRisk.fuel.carbTargetLow}-${nutRedsRisk.fuel.carbTargetHigh}g/day`,
                  },
                  {
                    label: "Protein", actual: nutRedsRisk.fuel.avgProtein, perKg: nutRedsRisk.fuel.proteinPerKgVal,
                    low: nutRedsRisk.fuel.proteinTargetLow, high: nutRedsRisk.fuel.proteinTargetHigh,
                    color: C.purple, unit: "g",
                    note: nutRedsRisk.fuel.inDeficit ? "In deficit → higher protein needed to preserve muscle" : "Endurance range",
                  },
                  {
                    label: "Fat", actual: nutRedsRisk.fuel.avgFat, perKg: nutRedsRisk.fuel.fatPerKg,
                    low: nutRedsRisk.fuel.fatTargetLow, high: nutRedsRisk.fuel.fatTargetHigh,
                    color: C.cyan, unit: "g",
                    note: "Minimum for hormone health & recovery",
                  },
                ].map(m => {
                  const status = m.actual < m.low ? "low" : m.actual > m.high ? "high" : "ok";
                  const statusColor = status === "low" ? C.red : status === "high" ? C.amber : C.green;
                  const pct = Math.min(100, Math.round((m.actual / m.high) * 100));
                  return (
                    <div key={m.label} style={{ padding:"8px 12px", background:C.bg2, borderRadius:8 }}>
                      <div style={{ display:"flex", justifyContent:"space-between", alignItems:"center", marginBottom:6 }}>
                        <div style={{ display:"flex", alignItems:"center", gap:8 }}>
                          <span style={{ fontSize:12, fontWeight:700, color:m.color }}>{m.label}</span>
                          <span style={{ fontSize:11, color:C.text, fontWeight:600 }}>{m.actual}{m.unit}</span>
                          <span style={{ fontSize:10, color:C.textMuted }}>({m.perKg} g/kg)</span>
                        </div>
                        <div style={{ display:"flex", alignItems:"center", gap:6 }}>
                          <span style={{ fontSize:10, color:C.textMuted }}>Target: {m.low}–{m.high}{m.unit}</span>
                          <span style={{ fontSize:9, fontWeight:700, color:statusColor, padding:"2px 6px", background:statusColor+"15", borderRadius:4 }}>
                            {status === "low" ? "↑ LOW" : status === "high" ? "↓ HIGH" : "✓ OK"}
                          </span>
                        </div>
                      </div>
                      {/* Progress bar */}
                      <div style={{ height:6, background:C.bg3, borderRadius:3, overflow:"hidden", marginBottom:4 }}>
                        <div style={{ width:`${pct}%`, height:"100%", borderRadius:3, transition:"width 0.3s",
                          background: status === "low" ? `linear-gradient(90deg, ${C.red}, ${C.amber})` : status === "high" ? C.amber : `linear-gradient(90deg, ${m.color}80, ${C.green})`,
                        }} />
                      </div>
                      <div style={{ fontSize:10, color:C.textMuted, fontStyle:"italic" }}>{m.note}</div>
                    </div>
                  );
                })}
              </div>

              {/* Actionable recommendations */}
              <div style={{ marginTop:12, padding:"10px 14px", background:C.bg2, borderRadius:8 }}>
                <div style={{ fontSize:11, fontWeight:700, color:C.textDim, marginBottom:6, textTransform:"uppercase", letterSpacing:"0.06em" }}>Recommendations</div>
                <div style={{ display:"flex", flexDirection:"column", gap:4, fontSize:11, color:C.textDim, lineHeight:1.6 }}>
                  {nutRedsRisk.fuel.avgCarbs < nutRedsRisk.fuel.carbTargetLow && (
                    <div style={{ display:"flex", gap:6, alignItems:"flex-start" }}>
                      <span style={{ color:C.red, fontWeight:700, flexShrink:0 }}>!</span>
                      <span><strong style={{color:C.amber}}>Increase carbs by {nutRedsRisk.fuel.carbTargetLow - nutRedsRisk.fuel.avgCarbs}g/day</strong> — glycogen stores are depleting faster than you're replenishing. Add oats, rice, fruit, or a pre-run snack.</span>
                    </div>
                  )}
                  {nutRedsRisk.fuel.avgCarbs >= nutRedsRisk.fuel.carbTargetLow && nutRedsRisk.fuel.avgCarbs <= nutRedsRisk.fuel.carbTargetHigh && (
                    <div style={{ display:"flex", gap:6, alignItems:"flex-start" }}>
                      <span style={{ color:C.green, fontWeight:700, flexShrink:0 }}>✓</span>
                      <span>Carb intake is well-matched to your training load. Maintain current levels.</span>
                    </div>
                  )}
                  {nutRedsRisk.fuel.avgProtein < nutRedsRisk.fuel.proteinTargetLow && (
                    <div style={{ display:"flex", gap:6, alignItems:"flex-start" }}>
                      <span style={{ color:C.red, fontWeight:700, flexShrink:0 }}>!</span>
                      <span><strong style={{color:C.purple}}>Increase protein by {nutRedsRisk.fuel.proteinTargetLow - nutRedsRisk.fuel.avgProtein}g/day</strong>{nutRedsRisk.fuel.inDeficit ? " — critical when in a calorie deficit to prevent muscle loss" : " — needed for recovery and adaptation"}. Add lean meat, eggs, Greek yogurt, or a shake post-run.</span>
                    </div>
                  )}
                  {nutRedsRisk.fuel.avgProtein >= nutRedsRisk.fuel.proteinTargetLow && (
                    <div style={{ display:"flex", gap:6, alignItems:"flex-start" }}>
                      <span style={{ color:C.green, fontWeight:700, flexShrink:0 }}>✓</span>
                      <span>Protein intake supports recovery{nutRedsRisk.fuel.inDeficit ? " and muscle preservation during deficit" : ""}. Good.</span>
                    </div>
                  )}
                  {nutRedsRisk.fuel.avgFat < nutRedsRisk.fuel.fatTargetLow && (
                    <div style={{ display:"flex", gap:6, alignItems:"flex-start" }}>
                      <span style={{ color:C.red, fontWeight:700, flexShrink:0 }}>!</span>
                      <span><strong style={{color:C.cyan}}>Fat too low ({nutRedsRisk.fuel.avgFat}g)</strong> — minimum {nutRedsRisk.fuel.fatTargetLow}g needed for testosterone, cortisol regulation, and joint health. Add nuts, avocado, olive oil.</span>
                    </div>
                  )}
                  {nutRedsRisk.fuel.avgFat >= nutRedsRisk.fuel.fatTargetLow && nutRedsRisk.fuel.avgFat <= nutRedsRisk.fuel.fatTargetHigh && (
                    <div style={{ display:"flex", gap:6, alignItems:"flex-start" }}>
                      <span style={{ color:C.green, fontWeight:700, flexShrink:0 }}>✓</span>
                      <span>Fat intake supports hormone health and recovery.</span>
                    </div>
                  )}
                </div>
              </div>
            </Card>
          )}
            </div>
            );
          })()}

          {tab === "Diary" && (
            <div style={{display:"flex",flexDirection:"column",gap:16}}>
              {/* MFP Connection */}
              {mfpConnected === false && (
                <Card style={{borderColor: C.amber+"40"}}>
                  <div style={{fontSize:13,fontWeight:700,color:C.text,marginBottom:8}}>Connect MyFitnessPal</div>
                  <div style={{fontSize:12,color:C.textMuted,marginBottom:8}}>
                    Enter your MFP username to sync your food diary from MyFitnessPal.
                  </div>
                  <div style={{fontSize:11,color:C.amber,marginBottom:12,padding:"8px 10px",background:C.amber+"08",borderRadius:6,lineHeight:1.6}}>
                    Your diary must be set to <strong>Public</strong>: MFP app &rarr; Settings &rarr; Diary Settings &rarr; Diary Sharing &rarr; Public
                  </div>
                  <div style={{display:"flex",gap:10,marginBottom:10}}>
                    <input value={mfpUsernameInput} onChange={e => setMfpUsernameInput(e.target.value)}
                      placeholder="MFP username (e.g. ccooke1981)" style={{flex:1}}
                      onKeyDown={e => e.key === "Enter" && saveMfpCreds()} />
                    <Btn onClick={saveMfpCreds} disabled={syncingMfp || !mfpUsernameInput.trim()} small>
                      {syncingMfp ? "Verifying..." : "Connect"}
                    </Btn>
                  </div>
                </Card>
              )}
              {mfpConnected && mfpUsername && (
                <div style={{fontSize:11,color:C.textMuted,display:"flex",alignItems:"center",gap:6}}>
                  <span style={{color:C.green}}>&#9679;</span> Connected as <strong style={{color:C.text}}>{mfpUsername}</strong>
                  <span style={{fontSize:10,color:C.textDim,marginLeft:8}}>Auto-syncs daily at 5 AM</span>
                </div>
              )}

              {mfpMsg && (
                <div style={{padding:"10px 14px",borderRadius:8,fontSize:12,
                  background: mfpMsg.type === "success" ? C.green+"15" : mfpMsg.type === "info" ? C.cyan+"15" : C.red+"15",
                  color: mfpMsg.type === "success" ? C.green : mfpMsg.type === "info" ? C.cyan : C.red,
                  border: `1px solid ${mfpMsg.type === "success" ? C.green : mfpMsg.type === "info" ? C.cyan : C.red}30`}}>
                  {mfpMsg.text}
                </div>
              )}

              {/* Date picker & sync */}
              <Card>
                <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:12}}>
                  <div style={{display:"flex",alignItems:"center",gap:10}}>
                    <button onClick={() => { const d = new Date(diaryDate); d.setDate(d.getDate()-1); setDiaryDate(d.toISOString().split("T")[0]); }}
                      style={{background:"none",border:`1px solid ${C.border}`,borderRadius:6,color:C.textDim,cursor:"pointer",padding:"4px 10px",fontSize:14}}>
                      &larr;
                    </button>
                    <input type="date" value={diaryDate} onChange={e => setDiaryDate(e.target.value)}
                      style={{textAlign:"center",fontSize:13,padding:"6px 12px",width:160}} />
                    <button onClick={() => { const d = new Date(diaryDate); d.setDate(d.getDate()+1); setDiaryDate(d.toISOString().split("T")[0]); }}
                      disabled={diaryDate >= today}
                      style={{background:"none",border:`1px solid ${C.border}`,borderRadius:6,color: diaryDate >= today ? C.bg3 : C.textDim,cursor: diaryDate >= today ? "default" : "pointer",padding:"4px 10px",fontSize:14}}>
                      &rarr;
                    </button>
                    {diaryDate === today && <Badge label="Today" color={C.cyan} />}
                  </div>
                  <div style={{display:"flex",gap:6}}>
                    {mfpConnected && (
                      <Btn onClick={() => setShowMfpPaste(true)} small>
                        📋 Paste from MFP
                      </Btn>
                    )}
                    {mfpConnected && mfpUsername && (
                      <Btn onClick={() => window.open(`https://www.myfitnesspal.com/food/diary/${mfpUsername}?date=${diaryDate}`, "_blank")} variant="secondary" small>
                        Open MFP ↗
                      </Btn>
                    )}
                  </div>
                </div>

                {/* Paste from MFP modal */}
                {showMfpPaste && (
                  <div style={{padding:"14px",background:C.bg2,border:`1px solid ${C.cyan}40`,borderRadius:10,marginBottom:8}}>
                    <div style={{fontSize:12,fontWeight:700,color:C.cyan,marginBottom:8}}>Paste from MyFitnessPal</div>
                    <div style={{fontSize:11,color:C.textMuted,marginBottom:10,lineHeight:1.6}}>
                      <strong>Steps:</strong> 1) Click "Open MFP" above to view your diary &nbsp;
                      2) On the MFP page, press <kbd style={{padding:"1px 5px",background:C.bg3,borderRadius:3,fontSize:10,border:`1px solid ${C.border}`}}>Ctrl+A</kbd> then <kbd style={{padding:"1px 5px",background:C.bg3,borderRadius:3,fontSize:10,border:`1px solid ${C.border}`}}>Ctrl+C</kbd> &nbsp;
                      3) Paste below and click Import
                    </div>
                    <textarea
                      value={mfpPasteText}
                      onChange={e => setMfpPasteText(e.target.value)}
                      placeholder="Paste your MFP diary page content here (Ctrl+V)..."
                      style={{width:"100%",minHeight:120,fontSize:11,padding:10,borderRadius:6,border:`1px solid ${C.border}`,background:C.bg,color:C.text,fontFamily:"'IBM Plex Mono',monospace",resize:"vertical"}}
                    />
                    <div style={{display:"flex",gap:8,marginTop:8}}>
                      <Btn onClick={handleMfpPaste} disabled={!mfpPasteText.trim()} small>
                        Import {diaryDate}
                      </Btn>
                      <button onClick={() => { setShowMfpPaste(false); setMfpPasteText(""); }} style={{
                        background:"none",border:`1px solid ${C.border}`,borderRadius:6,padding:"4px 12px",
                        color:C.textMuted,cursor:"pointer",fontSize:11,fontFamily:"'IBM Plex Mono',monospace",
                      }}>Cancel</button>
                    </div>
                  </div>
                )}

                {/* Auto-sync recommendation */}
                {mfpConnected && !showMfpPaste && (
                  <div style={{padding:"10px 14px",background:C.green+"08",border:`1px solid ${C.green}25`,borderRadius:8,marginBottom:8}}>
                    <div style={{fontSize:11,color:C.green,fontWeight:700,marginBottom:4}}>Recommended: Auto-Sync Extension</div>
                    <div style={{fontSize:10,color:C.textMuted,lineHeight:1.6}}>
                      Install the Tampermonkey userscript from the <strong style={{color:C.cyan}}>Settings</strong> tab — it auto-syncs your MFP diary every time you visit it. Zero clicks needed.
                    </div>
                  </div>
                )}

                {diaryDate !== today && (
                  <button onClick={() => setDiaryDate(today)}
                    style={{background:C.cyan+"10",border:`1px solid ${C.cyan}30`,borderRadius:6,color:C.cyan,
                      cursor:"pointer",padding:"4px 12px",fontSize:11,fontWeight:600,marginBottom:8,fontFamily:"'IBM Plex Mono', monospace"}}>
                    Jump to Today
                  </button>
                )}
              </Card>

              {/* ── Daily Commentary ── */}
              {canonicalDay && (() => {
                const t = canonicalDay;
                const cals = t.calories || 0;
                const p = t.protein || 0;
                const c = t.carbs || 0;
                const f = t.fat || 0;
                const pCals = p * 4;
                const cCals = c * 4;
                const fCals = f * 9;
                const totalMacroCals = pCals + cCals + fCals || 1;
                const pPct = Math.round(pCals / totalMacroCals * 100);
                const cPct = Math.round(cCals / totalMacroCals * 100);
                const fPct = Math.round(fCals / totalMacroCals * 100);
                const isWorkoutDay = Object.keys(flagPrePostWorkout).length > 0;
                const exerciseCals = activities.filter(a => {
                  const d = a.start_date?.toDate ? a.start_date.toDate() : new Date(a.start_date);
                  return d.toISOString().split("T")[0] === diaryDate;
                }).reduce((s, a) => s + (a.calories || 0), 0);
                const tdee = 1800 * 1.4;
                const netCals = cals - tdee - exerciseCals;

                // Generate commentary lines
                const notes = [];
                // Protein assessment for runner
                if (p < 100) notes.push({ icon: "!!", color: C.red, text: `Protein critically low at ${p}g. Runners need 1.2-1.6g/kg. Aim for 140-170g to support recovery.` });
                else if (p < 140) notes.push({ icon: "!", color: C.amber, text: `Protein at ${p}g is below target. Try adding a protein-rich snack to hit 140-170g for optimal muscle repair.` });
                else if (p >= 160) notes.push({ icon: "+", color: C.green, text: `Great protein intake at ${p}g. Well within the optimal range for a distance runner.` });

                // Calorie context
                if (cals > 0 && cals < 1400) notes.push({ icon: "!!", color: C.red, text: `Only ${cals} kcal logged. This is too low for training days and may impair recovery and performance.` });
                else if (isWorkoutDay && cals > 0 && cals < 2000) notes.push({ icon: "!", color: C.amber, text: `${cals} kcal on a workout day may be underfueling. Consider adding carbs around your session.` });
                else if (netCals < -800) notes.push({ icon: "+", color: C.green, text: `Strong calorie deficit of ${Math.abs(Math.round(netCals))} kcal. Sustainable pace for weight loss.` });
                else if (netCals > 200) notes.push({ icon: "~", color: C.amber, text: `Slight calorie surplus of ${Math.round(netCals)} kcal today. Fine for hard training days, watch it on rest days.` });

                // Macro balance
                if (cPct > 60) notes.push({ icon: "~", color: C.amber, text: `Carb-heavy day (${cPct}% of calories). Fine before a long run, otherwise consider more protein.` });
                else if (fPct > 45) notes.push({ icon: "~", color: C.amber, text: `Fat-heavy day (${fPct}% of calories). High fat can slow digestion before running.` });
                else if (pPct >= 25 && pPct <= 35 && cPct >= 35 && cPct <= 50) notes.push({ icon: "+", color: C.green, text: `Well-balanced macros: ${pPct}% protein, ${cPct}% carbs, ${fPct}% fat. Ideal for a runner.` });

                // Pre/post workout fueling
                if (isWorkoutDay) {
                  const hasPre = flagPrePostWorkout.Breakfast === "pre" || flagPrePostWorkout.Lunch === "pre" || flagPrePostWorkout.Snacks === "pre";
                  const hasPost = flagPrePostWorkout.Breakfast === "post" || flagPrePostWorkout.Lunch === "post" || flagPrePostWorkout.Dinner === "post";
                  if (!hasPre) notes.push({ icon: "?", color: C.textDim, text: "No clear pre-workout meal detected. Even a light carb snack 1-2hrs before helps performance." });
                  if (!hasPost) notes.push({ icon: "?", color: C.textDim, text: "No post-workout meal within 45 min. A protein+carb combo within that window accelerates recovery." });
                }

                // Fiber check
                if ((t.fiber || 0) > 0 && t.fiber < 20) notes.push({ icon: "~", color: C.amber, text: `Fiber at ${Math.round(t.fiber)}g — aim for 25-30g daily for gut health and satiety.` });

                // Multi-day trend awareness from RED-S engine
                if (nutRedsRisk) {
                  if (nutRedsRisk.ea !== null && nutRedsRisk.ea < 30) {
                    notes.push({ icon: "!!", color: C.red, text: `14-day energy availability is ${nutRedsRisk.ea} kcal/kg FFM — below the RED-S threshold of 30. Increase intake or reduce training volume.` });
                  }
                  if (nutRedsRisk.weightTrend === "rapid_loss") {
                    notes.push({ icon: "!", color: "#f97316", text: `Weight dropping ${Math.abs(nutRedsRisk.weightVelocity).toFixed(1)} lb/week — too fast. Risk of muscle loss and hormonal disruption. Slow to 0.5-0.75 lb/week.` });
                  }
                  if (nutRedsRisk.avgIntake !== null && nutRedsRisk.dataQuality.nutritionDays >= 5) {
                    const trend = nutRedsRisk.avgIntake < 1800 ? "low" : nutRedsRisk.avgIntake > 2800 ? "high" : null;
                    if (trend === "low") notes.push({ icon: "~", color: C.amber, text: `Your ${nutRedsRisk.dataQuality.nutritionDays}-day average intake is ${nutRedsRisk.avgIntake} kcal — consider if this supports your training.` });
                  }
                  if (nutRedsRisk.hrvTrend && parseInt(nutRedsRisk.hrvTrend) < -8) {
                    notes.push({ icon: "~", color: C.amber, text: "HRV has been declining over the past 2 weeks — underfueling can suppress autonomic recovery." });
                  }
                }

                if (notes.length === 0) notes.push({ icon: "+", color: C.green, text: "Solid nutrition day. Keep it up!" });

                return (
                  <Card style={{borderColor: C.cyan+"30"}}>
                    <div style={{fontSize:13,fontWeight:600,color:C.textDim,marginBottom:10}}>Daily Commentary</div>
                    <div style={{display:"flex",flexDirection:"column",gap:8}}>
                      {notes.map((n, i) => (
                        <div key={i} style={{display:"flex",gap:10,alignItems:"flex-start",padding:"8px 12px",
                          background:n.color+"08",borderRadius:6,borderLeft:`3px solid ${n.color}`}}>
                          <span style={{fontSize:14,fontWeight:800,color:n.color,flexShrink:0,width:18,textAlign:"center"}}>{n.icon}</span>
                          <span style={{fontSize:12,color:C.textDim,lineHeight:1.6}}>{n.text}</span>
                        </div>
                      ))}
                    </div>
                  </Card>
                );
              })()}

              {/* ── Energy Balance ── */}
              {deficitCalcs && (
                <Card>
                  <div style={{fontSize:13,fontWeight:600,color:C.textDim,marginBottom:12}}>Energy Balance</div>
                  <div style={{display:"grid",gridTemplateColumns:"repeat(3,1fr)",gap:12,marginBottom:12}}>
                    <div style={{textAlign:"center",padding:12,background:C.bg2,borderRadius:8}}>
                      <div style={{fontSize:20,fontWeight:700,color:C.pink}}>{Math.round(deficitCalcs.intake)}</div>
                      <div style={{fontSize:10,color:C.textMuted}}>Eaten (kcal)</div>
                    </div>
                    <div style={{textAlign:"center",padding:12,background:C.bg2,borderRadius:8}}>
                      <div style={{fontSize:20,fontWeight:700,color:C.amber}}>{Math.round(deficitCalcs.tdee)}</div>
                      <div style={{fontSize:10,color:C.textMuted}}>TDEE (kcal)</div>
                    </div>
                    <div style={{textAlign:"center",padding:12,background:C.bg2,borderRadius:8}}>
                      <div style={{fontSize:20,fontWeight:700,color:C.cyan}}>{Math.round(deficitCalcs.exerciseCals)}</div>
                      <div style={{fontSize:10,color:C.textMuted}}>Exercise (kcal)</div>
                    </div>
                  </div>

                  <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12}}>
                    <div style={{padding:12,background: deficitCalcs.deficitWithoutExercise > 0 ? C.green+"08" : C.red+"08",
                      borderRadius:8,border:`1px solid ${deficitCalcs.deficitWithoutExercise > 0 ? C.green : C.red}20`}}>
                      <div style={{fontSize:10,color:C.textMuted,textTransform:"uppercase",letterSpacing:"0.08em",marginBottom:4}}>Deficit (no exercise)</div>
                      <div style={{fontSize:18,fontWeight:700,color: deficitCalcs.deficitWithoutExercise > 0 ? C.green : C.red}}>
                        {deficitCalcs.deficitWithoutExercise > 0 ? "-" : "+"}{Math.abs(Math.round(deficitCalcs.deficitWithoutExercise))}
                        <span style={{fontSize:11,color:C.textMuted,marginLeft:4}}>kcal</span>
                      </div>
                    </div>
                    <div style={{padding:12,background: deficitCalcs.deficitWithExercise > 0 ? C.green+"08" : C.red+"08",
                      borderRadius:8,border:`1px solid ${deficitCalcs.deficitWithExercise > 0 ? C.green : C.red}20`}}>
                      <div style={{fontSize:10,color:C.textMuted,textTransform:"uppercase",letterSpacing:"0.08em",marginBottom:4}}>Deficit (with exercise)</div>
                      <div style={{fontSize:18,fontWeight:700,color: deficitCalcs.deficitWithExercise > 0 ? C.green : C.red}}>
                        {deficitCalcs.deficitWithExercise > 0 ? "-" : "+"}{Math.abs(Math.round(deficitCalcs.deficitWithExercise))}
                        <span style={{fontSize:11,color:C.textMuted,marginLeft:4}}>kcal</span>
                      </div>
                    </div>
                  </div>

                  {deficitCalcs.projectedWeeklyLoss !== 0 && (
                    <div style={{marginTop:12,padding:10,background:C.bg2,borderRadius:8,display:"flex",justifyContent:"space-between",alignItems:"center"}}>
                      <span style={{fontSize:12,color:C.textMuted}}>Projected weekly loss at this rate</span>
                      <span style={{fontSize:14,fontWeight:700,color: deficitCalcs.projectedWeeklyLoss > 0 ? C.green : C.red}}>
                        {deficitCalcs.projectedWeeklyLoss > 0 ? "" : "+"}{Math.abs(deficitCalcs.projectedWeeklyLoss).toFixed(1)} lb/wk
                      </span>
                    </div>
                  )}
                </Card>
              )}

              {/* ── Macro Breakdown Pie + Bar ── */}
              {canonicalDay && canonicalDay.calories > 0 && (() => {
                const t = canonicalDay;
                const pCals = (t.protein || 0) * 4;
                const cCals = (t.carbs || 0) * 4;
                const fCals = (t.fat || 0) * 9;
                const pieData = [
                  { name: "Protein", value: pCals, pct: Math.round(pCals / (pCals+cCals+fCals||1)*100), color: C.purple },
                  { name: "Carbs", value: cCals, pct: Math.round(cCals / (pCals+cCals+fCals||1)*100), color: C.amber },
                  { name: "Fat", value: fCals, pct: Math.round(fCals / (pCals+cCals+fCals||1)*100), color: C.cyan },
                ];
                // Per-meal calorie breakdown
                const mealData = ["Breakfast","Lunch","Dinner","Snacks"].map(meal => {
                  const items = diaryData?.meals?.[meal] || [];
                  return {
                    meal: meal.substring(0,5),
                    calories: items.reduce((s, f) => s + (f.calories||0), 0),
                    protein: items.reduce((s, f) => s + (f.protein||0), 0),
                    carbs: items.reduce((s, f) => s + (f.carbs||0), 0),
                    fat: items.reduce((s, f) => s + (f.fat||0), 0),
                  };
                }).filter(m => m.calories > 0);

                return (
                  <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:16}}>
                    <Card>
                      <div style={{fontSize:13,fontWeight:600,color:C.textDim,marginBottom:8}}>Macro Split</div>
                      <ResponsiveContainer width="100%" height={160}>
                        <PieChart>
                          <Pie data={pieData} dataKey="value" cx="50%" cy="50%" innerRadius={40} outerRadius={65} paddingAngle={3}>
                            {pieData.map((d, i) => <Cell key={i} fill={d.color} />)}
                          </Pie>
                          <Tooltip contentStyle={{background:C.bg2,border:`1px solid ${C.border}`,borderRadius:8,fontSize:11,color:C.text}}
                            formatter={(val, name) => [`${Math.round(val)} kcal`, name]} />
                        </PieChart>
                      </ResponsiveContainer>
                      <div style={{display:"flex",justifyContent:"center",gap:16,marginTop:4}}>
                        {pieData.map(d => (
                          <div key={d.name} style={{textAlign:"center"}}>
                            <div style={{fontSize:16,fontWeight:700,color:d.color}}>{d.pct}%</div>
                            <div style={{fontSize:9,color:C.textMuted}}>{d.name}</div>
                          </div>
                        ))}
                      </div>
                    </Card>
                    <Card>
                      <div style={{fontSize:13,fontWeight:600,color:C.textDim,marginBottom:8}}>By Meal</div>
                      <ResponsiveContainer width="100%" height={160}>
                        <BarChart data={mealData} layout="vertical" barSize={14}>
                          <CartesianGrid strokeDasharray="3 3" stroke={C.border} horizontal={false} />
                          <XAxis type="number" tick={{fill:C.textMuted,fontSize:10}} />
                          <YAxis type="category" dataKey="meal" tick={{fill:C.textMuted,fontSize:10}} width={40} />
                          <Tooltip contentStyle={{background:C.bg2,border:`1px solid ${C.border}`,borderRadius:8,fontSize:11,color:C.text}} />
                          <Bar dataKey="protein" stackId="a" fill={C.purple} name="Protein (g)" />
                          <Bar dataKey="carbs" stackId="a" fill={C.amber} name="Carbs (g)" />
                          <Bar dataKey="fat" stackId="a" fill={C.cyan} name="Fat (g)" radius={[0,4,4,0]} />
                        </BarChart>
                      </ResponsiveContainer>
                      <div style={{display:"flex",justifyContent:"center",gap:12,marginTop:4}}>
                        {mealData.map(m => (
                          <div key={m.meal} style={{textAlign:"center"}}>
                            <div style={{fontSize:14,fontWeight:700,color:C.pink}}>{m.calories}</div>
                            <div style={{fontSize:9,color:C.textMuted}}>{m.meal}</div>
                          </div>
                        ))}
                      </div>
                    </Card>
                  </div>
                );
              })()}

              {/* ── Macro Target Progress Radial ── */}
              {canonicalDay && canonicalDay.calories > 0 && (() => {
                const t = canonicalDay;
                const isHard = todayWorkout && ["tempo","intervals","long","race_pace"].includes(todayWorkout.type);
                const isRest = !todayWorkout || todayWorkout.type === "rest";
                const targets = {
                  calories: dynamicMacros?.calories || (isHard ? 2800 : isRest ? 2100 : 2400),
                  protein: dynamicMacros?.protein || (isHard ? 180 : 170),
                  carbs: dynamicMacros?.carbs || (isHard ? 350 : isRest ? 200 : 280),
                  fat: dynamicMacros?.fat || (isHard ? 70 : isRest ? 90 : 80),
                };
                const macros = [
                  { name: "Calories", value: Math.min(100, Math.round(((t.calories||0)/targets.calories)*100)), fill: C.pink },
                  { name: "Protein", value: Math.min(100, Math.round(((t.protein||0)/targets.protein)*100)), fill: C.purple },
                  { name: "Carbs", value: Math.min(100, Math.round(((t.carbs||0)/targets.carbs)*100)), fill: C.amber },
                  { name: "Fat", value: Math.min(100, Math.round(((t.fat||0)/targets.fat)*100)), fill: C.cyan },
                ];
                return (
                  <Card>
                    <div style={{fontSize:13,fontWeight:600,color:C.textDim,marginBottom:8}}>Target Progress</div>
                    <div style={{display:"grid",gridTemplateColumns:"repeat(4,1fr)",gap:8}}>
                      {macros.map(m => (
                        <div key={m.name} style={{textAlign:"center"}}>
                          <ResponsiveContainer width="100%" height={80}>
                            <RadialBarChart cx="50%" cy="50%" innerRadius="60%" outerRadius="90%" startAngle={90} endAngle={-270}
                              data={[{ value: m.value, fill: m.fill }]}>
                              <RadialBar background={{fill:C.bg3}} dataKey="value" cornerRadius={4} />
                            </RadialBarChart>
                          </ResponsiveContainer>
                          <div style={{fontSize:16,fontWeight:700,color:m.fill,marginTop:-4}}>{m.value}%</div>
                          <div style={{fontSize:9,color:C.textMuted}}>{m.name}</div>
                        </div>
                      ))}
                    </div>
                  </Card>
                );
              })()}

              {/* ── Food Diary ── */}
              {diaryLoading ? (
                <Card><div style={{textAlign:"center",padding:20,color:C.textMuted,fontSize:13}}>Loading diary...</div></Card>
              ) : diaryData ? (
                <Card>
                  <div style={{fontSize:13,fontWeight:600,color:C.textDim,marginBottom:12}}>Food Diary</div>
                  {["Breakfast","Lunch","Dinner","Snacks"].map(meal => {
                    const items = diaryData.meals?.[meal] || [];
                    if (items.length === 0) return null;
                    const flag = flagPrePostWorkout[meal];
                    const mealCals = items.reduce((s, f) => s + (f.calories || 0), 0);
                    return (
                      <div key={meal} style={{marginBottom:16}}>
                        <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:6}}>
                          <div style={{display:"flex",alignItems:"center",gap:8}}>
                            <span style={{fontSize:11,fontWeight:700,color: meal === "Breakfast" ? C.amber : meal === "Lunch" ? C.green : meal === "Dinner" ? C.purple : C.cyan,
                              textTransform:"uppercase",letterSpacing:"0.08em"}}>{meal}</span>
                            {flag && (
                              <span style={{fontSize:9,fontWeight:700,padding:"2px 6px",borderRadius:4,
                                background: flag === "pre" ? C.amber+"20" : C.green+"20",
                                color: flag === "pre" ? C.amber : C.green,
                                textTransform:"uppercase",letterSpacing:"0.05em"}}>
                                {flag === "pre" ? "Pre-Workout" : "Post-Workout"}
                              </span>
                            )}
                          </div>
                          <span style={{fontSize:11,color:C.textMuted}}>{mealCals} kcal</span>
                        </div>
                        <div style={{display:"flex",flexDirection:"column",gap:4}}>
                          {items.map((food, i) => (
                            <div key={i} style={{display:"flex",justifyContent:"space-between",alignItems:"center",
                              padding:"8px 12px",background:C.bg2,borderRadius:6,
                              borderLeft: flag ? `3px solid ${flag === "pre" ? C.amber : C.green}` : "none"}}>
                              <div style={{flex:1,minWidth:0}}>
                                <div style={{fontSize:12,color:C.text,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}}>
                                  {food.name}
                                </div>
                                {food.brand && <div style={{fontSize:10,color:C.textMuted}}>{food.brand}</div>}
                                {food.serving && <div style={{fontSize:10,color:C.textDim}}>{food.serving}</div>}
                              </div>
                              <div style={{display:"flex",gap:10,fontSize:11,color:C.textDim,flexShrink:0,marginLeft:12}}>
                                <span style={{color:C.pink}}>{food.calories || 0}</span>
                                <span>P:{food.protein || 0}g</span>
                                <span>C:{food.carbs || 0}g</span>
                                <span>F:{food.fat || 0}g</span>
                              </div>
                            </div>
                          ))}
                        </div>
                      </div>
                    );
                  })}

                  {/* Daily totals bar */}
                  <div style={{padding:12,background:C.bg2,borderRadius:8,marginTop:4,
                    display:"flex",justifyContent:"space-between",alignItems:"center",flexWrap:"wrap",gap:8}}>
                    <span style={{fontSize:12,fontWeight:700,color:C.text}}>Daily Totals</span>
                    <div style={{display:"flex",gap:12,fontSize:12,flexWrap:"wrap"}}>
                      <span style={{color:C.pink,fontWeight:600}}>{Math.round(diaryData.totals?.calories || 0)} kcal</span>
                      <span style={{color:C.textDim}}>P:{Math.round(diaryData.totals?.protein || 0)}g</span>
                      <span style={{color:C.textDim}}>C:{Math.round(diaryData.totals?.carbs || 0)}g</span>
                      <span style={{color:C.textDim}}>F:{Math.round(diaryData.totals?.fat || 0)}g</span>
                      {(diaryData.totals?.fiber || 0) > 0 && <span style={{color:C.textDim}}>Fiber:{Math.round(diaryData.totals.fiber)}g</span>}
                    </div>
                  </div>
                </Card>
              ) : (
                <Card>
                  <EmptyState icon="📋" title="No diary data"
                    sub={mfpConnected ? `No food logged for ${diaryDate}. Hit Sync to pull from MyFitnessPal.` : "Connect MyFitnessPal above to start syncing your food diary."} />
                </Card>
              )}

              {/* ── 14-Day Trends ── */}
              {nutHistoryAll.length >= 3 && (() => {
                // Source the canonical merged history (mergeNutritionDay
                // already rejects the MFP "Your Daily Goal" row leak).
                // Merged entries are flat; keep only real logged-food days.
                const validHistory = nutHistoryAll.filter(d => (d.calories || 0) > 0);
                if (validHistory.length < 3) return null;
                const sorted = validHistory.slice().sort((a, b) => (a.date||'').localeCompare(b.date||''));
                const chartData = sorted.map((d, i) => {
                  // 3-day rolling averages
                  const window3 = sorted.slice(Math.max(0, i-2), i+1);
                  const avg = (arr, key) => arr.length ? Math.round(arr.reduce((s, x) => s + (x[key]||0), 0) / arr.length) : 0;
                  return {
                    date: d.date?.substring(5),
                    fullDate: d.date,
                    calories: Math.round(d.calories || 0),
                    protein: Math.round(d.protein || 0),
                    fiber: Math.round(d.fiber || 0),
                    carbs: Math.max(0, Math.round((d.carbs || 0) - (d.fiber || 0))),
                    fat: Math.round(d.fat || 0),
                    avgCal: avg(window3, "calories"),
                    avgProtein: avg(window3, "protein"),
                  };
                });
                const avgAll = (key) => sorted.length ? Math.round(sorted.reduce((s, d) => s + (d[key]||0), 0) / sorted.length) : 0;
                const avgCals = avgAll("calories");
                const avgProtein = avgAll("protein");
                const avgCarbs = avgAll("carbs");
                const avgFat = avgAll("fat");
                const tdee = Math.round(1800 * 1.4);
                const avgDeficit = tdee - avgCals;
                const projLoss = (avgDeficit * 7 / 3500).toFixed(1);
                const consistency = sorted.filter(d => {
                  const c = d.calories || 0;
                  return c >= tdee * 0.6 && c <= tdee * 1.15;
                }).length;
                const consistencyPct = Math.round(consistency / sorted.length * 100);
                const proteinHitDays = sorted.filter(d => (d.protein||0) >= 140).length;
                const proteinHitPct = Math.round(proteinHitDays / sorted.length * 100);

                return (<>
                  {/* Calorie trend with rolling avg */}
                  <Card>
                    <div style={{fontSize:13,fontWeight:600,color:C.textDim,marginBottom:12}}>Calorie Trend ({sorted.length} days)</div>
                    <ResponsiveContainer width="100%" height={200}>
                      <ComposedChart data={chartData}>
                        <CartesianGrid strokeDasharray="3 3" stroke={C.border} />
                        <XAxis dataKey="date" tick={{fill:C.textMuted,fontSize:10}} />
                        <YAxis tick={{fill:C.textMuted,fontSize:10}} />
                        <Tooltip contentStyle={{background:C.bg2,border:`1px solid ${C.border}`,borderRadius:8,fontSize:11,color:C.text}} />
                        <ReferenceLine y={tdee} stroke={C.amber+"60"} strokeDasharray="6 3" label={{value:"TDEE",fill:C.amber,fontSize:9,position:"right"}} />
                        <Bar dataKey="calories" fill={C.pink+"60"} radius={[4,4,0,0]} name="Calories" />
                        <Line type="monotone" dataKey="avgCal" stroke={C.pink} strokeWidth={2} dot={false} name="3-day avg" />
                      </ComposedChart>
                    </ResponsiveContainer>
                  </Card>

                  {/* Macro trend area chart */}
                  <Card>
                    <div style={{fontSize:13,fontWeight:600,color:C.textDim,marginBottom:12}}>Macro Trend</div>
                    <ResponsiveContainer width="100%" height={180}>
                      <AreaChart data={chartData}>
                        <CartesianGrid strokeDasharray="3 3" stroke={C.border} />
                        <XAxis dataKey="date" tick={{fill:C.textMuted,fontSize:10}} />
                        <YAxis tick={{fill:C.textMuted,fontSize:10}} />
                        <Tooltip contentStyle={{background:C.bg2,border:`1px solid ${C.border}`,borderRadius:8,fontSize:11,color:C.text}} />
                        <Area type="monotone" dataKey="protein" stackId="1" stroke={C.purple} fill={C.purple+"30"} name="Protein (g)" />
                        <Area type="monotone" dataKey="fiber" stackId="1" stroke={C.green} fill={C.green+"30"} name="Fiber (g)" />
                        <Area type="monotone" dataKey="carbs" stackId="1" stroke={C.amber} fill={C.amber+"30"} name="Net Carbs (g)" />
                        <Area type="monotone" dataKey="fat" stackId="1" stroke={C.cyan} fill={C.cyan+"30"} name="Fat (g)" />
                      </AreaChart>
                    </ResponsiveContainer>
                  </Card>

                  {/* Summary stats grid */}
                  <Card>
                    <div style={{fontSize:13,fontWeight:600,color:C.textDim,marginBottom:12}}>Period Summary</div>
                    <div style={{display:"grid",gridTemplateColumns:"repeat(auto-fit,minmax(100px,1fr))",gap:10}}>
                      <div style={{textAlign:"center",padding:10,background:C.bg2,borderRadius:8}}>
                        <div style={{fontSize:18,fontWeight:700,color:C.pink}}>{avgCals}</div>
                        <div style={{fontSize:9,color:C.textMuted}}>Avg kcal/day</div>
                      </div>
                      <div style={{textAlign:"center",padding:10,background:C.bg2,borderRadius:8}}>
                        <div style={{fontSize:18,fontWeight:700,color:C.purple}}>{avgProtein}g</div>
                        <div style={{fontSize:9,color:C.textMuted}}>Avg Protein</div>
                      </div>
                      <div style={{textAlign:"center",padding:10,background:C.bg2,borderRadius:8}}>
                        <div style={{fontSize:18,fontWeight:700,color:C.amber}}>{avgCarbs}g</div>
                        <div style={{fontSize:9,color:C.textMuted}}>Avg Carbs</div>
                      </div>
                      <div style={{textAlign:"center",padding:10,background:C.bg2,borderRadius:8}}>
                        <div style={{fontSize:18,fontWeight:700,color:C.cyan}}>{avgFat}g</div>
                        <div style={{fontSize:9,color:C.textMuted}}>Avg Fat</div>
                      </div>
                      <div style={{textAlign:"center",padding:10,background: avgDeficit > 0 ? C.green+"10" : C.red+"10",borderRadius:8}}>
                        <div style={{fontSize:18,fontWeight:700,color: avgDeficit > 0 ? C.green : C.red}}>{projLoss > 0 ? "" : "+"}{Math.abs(projLoss)}</div>
                        <div style={{fontSize:9,color:C.textMuted}}>lb/wk proj</div>
                      </div>
                      <div style={{textAlign:"center",padding:10,background:C.bg2,borderRadius:8}}>
                        <div style={{fontSize:18,fontWeight:700,color: consistencyPct >= 70 ? C.green : consistencyPct >= 50 ? C.amber : C.red}}>{consistencyPct}%</div>
                        <div style={{fontSize:9,color:C.textMuted}}>Cal Consistency</div>
                      </div>
                      <div style={{textAlign:"center",padding:10,background:C.bg2,borderRadius:8}}>
                        <div style={{fontSize:18,fontWeight:700,color: proteinHitPct >= 70 ? C.green : proteinHitPct >= 50 ? C.amber : C.red}}>{proteinHitPct}%</div>
                        <div style={{fontSize:9,color:C.textMuted}}>Protein Target</div>
                      </div>
                    </div>
                  </Card>
                </>);
              })()}
            </div>
          )}

          {tab === "Schedule" && (
            <div style={{display:"flex",flexDirection:"column",gap:16}}>
              <Card>
                <div style={{fontSize:13,fontWeight:600,color:C.textDim,marginBottom:16}}>Workout Schedule</div>
                <div style={{fontSize:12,color:C.textMuted,marginBottom:16}}>
                  Set your typical workout times. Nutrition plans will be timed around these.
                </div>
                <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:20}}>
                  <div>
                    <div style={{fontSize:11,color:C.textMuted,textTransform:"uppercase",letterSpacing:"0.08em",marginBottom:8}}>Weekday Workout Time</div>
                    <select value={actSchedule.weekdayTime} onChange={e => saveSchedule({weekdayTime:e.target.value})} style={{width:"100%",fontSize:13,padding:"8px 10px"}}>
                      {["5:00 AM","5:30 AM","6:00 AM","6:30 AM","7:00 AM","7:30 AM","8:00 AM","11:00 AM","12:00 PM","4:00 PM","4:30 PM","5:00 PM","5:30 PM","6:00 PM","6:30 PM","7:00 PM","7:30 PM","8:00 PM"].map(t => <option key={t} value={t}>{t}</option>)}
                    </select>
                    <div style={{fontSize:11,color:C.textDim,marginTop:6}}>Mon–Fri runs/workouts</div>
                  </div>
                  <div>
                    <div style={{fontSize:11,color:C.textMuted,textTransform:"uppercase",letterSpacing:"0.08em",marginBottom:8}}>Weekend Workout Time</div>
                    <select value={actSchedule.weekendTime} onChange={e => saveSchedule({weekendTime:e.target.value})} style={{width:"100%",fontSize:13,padding:"8px 10px"}}>
                      {["6:00 AM","6:30 AM","7:00 AM","7:30 AM","8:00 AM","8:30 AM","9:00 AM","9:30 AM","10:00 AM","10:30 AM","11:00 AM","12:00 PM","1:00 PM","2:00 PM"].map(t => <option key={t} value={t}>{t}</option>)}
                    </select>
                    <div style={{fontSize:11,color:C.textDim,marginTop:6}}>Sat & Sun long runs/workouts</div>
                  </div>
                </div>
              </Card>

              {/* Weekly overview */}
              <Card>
                <div style={{fontSize:13,fontWeight:600,color:C.textDim,marginBottom:12}}>This Week's Plan</div>
                {todayWorkout ? (() => {
                  // Try to get the full week from plans
                  const dayNames = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"];
                  const todayIdx = (new Date().getDay() + 6) % 7; // Mon=0
                  return (
                    <div style={{display:"flex",flexDirection:"column",gap:6}}>
                      {dayNames.map((dayName, i) => {
                        const isToday = i === todayIdx;
                        const isWeekendDay = i >= 5;
                        const workoutTime = isWeekendDay ? actSchedule.weekendTime : actSchedule.weekdayTime;
                        return (
                          <div key={dayName} style={{
                            display:"flex",alignItems:"center",gap:12,padding:"8px 12px",
                            background: isToday ? C.cyan+"10" : "transparent", borderRadius:8,
                            border: isToday ? `1px solid ${C.cyan}30` : `1px solid transparent`,
                          }}>
                            <span style={{width:32,fontSize:11,fontWeight:700,color: isToday ? C.cyan : C.textMuted}}>{dayName.substring(0,3)}</span>
                            <span style={{fontSize:11,color:C.textDim,width:60}}>{workoutTime}</span>
                            {isToday && todayWorkout && (
                              <span style={{fontSize:11,color:C.text,fontWeight:600,textTransform:"capitalize"}}>
                                {todayWorkout.type?.replace("_"," ")} {todayWorkout.distanceMi ? `— ${todayWorkout.distanceMi} mi` : ""}
                              </span>
                            )}
                            {isToday && <span style={{fontSize:10,color:C.cyan,padding:"1px 6px",background:C.cyan+"20",borderRadius:4,marginLeft:"auto"}}>Today</span>}
                          </div>
                        );
                      })}
                    </div>
                  );
                })() : (
                  <div style={{color:C.textMuted,fontSize:12}}>Create a training plan to see your weekly schedule here.</div>
                )}
              </Card>

              <Card>
                <div style={{fontSize:13,fontWeight:600,color:C.textDim,marginBottom:12}}>Meal Timing Strategy</div>
                <div style={{display:"flex",flexDirection:"column",gap:8}}>
                  {(() => {
                    const wt = isWeekend ? actSchedule.weekendTime : actSchedule.weekdayTime;
                    // Parse time to calculate meal windows
                    const parseTime = (t) => {
                      const m = t.match(/(\d+):(\d+)\s*(AM|PM)/i);
                      if (!m) return 6;
                      let h = parseInt(m[1]); const min = parseInt(m[2]); const ampm = m[3].toUpperCase();
                      if (ampm === "PM" && h < 12) h += 12;
                      if (ampm === "AM" && h === 12) h = 0;
                      return h + min/60;
                    };
                    const fmtHr = (h) => {
                      const hr = Math.floor(h); const min = Math.round((h - hr) * 60);
                      const ampm = hr >= 12 ? "PM" : "AM";
                      const h12 = hr > 12 ? hr - 12 : hr === 0 ? 12 : hr;
                      return `${h12}:${String(min).padStart(2,"0")} ${ampm}`;
                    };
                    const workoutHr = parseTime(wt);
                    return [
                      { label: "Pre-workout meal", time: fmtHr(workoutHr - 2), desc: "Complex carbs + moderate protein", color: C.green },
                      { label: "Pre-workout snack", time: fmtHr(workoutHr - 0.5), desc: "Simple carbs — banana, gel, toast", color: C.amber },
                      { label: "Workout", time: wt, desc: todayWorkout ? `${todayWorkout.type} — ${todayWorkout.distanceMi || 0} mi` : "Per plan", color: C.cyan },
                      { label: "Post-workout recovery", time: fmtHr(workoutHr + 0.5), desc: "20-30g protein + 40-60g carbs within 30min", color: C.purple },
                      { label: "Recovery meal", time: fmtHr(workoutHr + 2), desc: "Balanced meal — lean protein, complex carbs, vegetables", color: C.pink },
                    ].map(item => (
                      <div key={item.label} style={{display:"flex",alignItems:"center",gap:12,padding:"8px 12px",background:C.bg2,borderRadius:8,borderLeft:`3px solid ${item.color}`}}>
                        <span style={{fontSize:11,color:item.color,fontWeight:700,width:55}}>{item.time}</span>
                        <div>
                          <div style={{fontSize:12,fontWeight:600,color:C.textDim}}>{item.label}</div>
                          <div style={{fontSize:11,color:C.textMuted}}>{item.desc}</div>
                        </div>
                      </div>
                    ));
                  })()}
                </div>
              </Card>
            </div>
          )}

          {tab === "Pre/Post Run" && (
            <div style={{display:"flex",flexDirection:"column",gap:16}}>
              <Card>
                <div style={{fontSize:13,fontWeight:600,color:C.green,marginBottom:16}}>Pre-Run Fueling</div>
                <div style={{display:"flex",flexDirection:"column",gap:10}}>
                  {[
                    {time:"2-3 hrs before",rec:"Full meal: oats, banana, toast with nut butter. 60-90g carbs, moderate protein, low fat.",color:C.cyan},
                    {time:"30-60 min before",rec:"Light snack: banana, energy bar, or toast. 30-40g simple carbs. Avoid high fiber/fat.",color:C.amber},
                    {time:"0-15 min before",rec:"Optional: energy gel or 100-200ml sports drink if run > 60 min.",color:C.green},
                  ].map(item => (
                    <div key={item.time} style={{padding:"12px 16px",background:C.bg2,borderRadius:8,borderLeft:`3px solid ${item.color}`}}>
                      <div style={{fontSize:11,color:item.color,marginBottom:4,fontWeight:600}}>{item.time}</div>
                      <div style={{fontSize:12,color:C.textDim,lineHeight:1.6}}>{item.rec}</div>
                    </div>
                  ))}
                </div>
              </Card>
              <Card>
                <div style={{fontSize:13,fontWeight:600,color:C.amber,marginBottom:16}}>Post-Run Recovery</div>
                <div style={{display:"flex",flexDirection:"column",gap:10}}>
                  {[
                    {time:"Within 30 min",rec:"Recovery window: 20-30g protein + 40-60g carbs. Chocolate milk, protein shake + banana, or Greek yogurt + fruit.",color:C.purple},
                    {time:"1-2 hrs after",rec:"Full meal: lean protein, complex carbs, vegetables. Replenish glycogen and support muscle repair.",color:C.cyan},
                    {time:"Hydration",rec:"500-700ml water per hour of running. Add electrolytes (sodium, potassium) for runs > 60 min.",color:C.green},
                  ].map(item => (
                    <div key={item.time} style={{padding:"12px 16px",background:C.bg2,borderRadius:8,borderLeft:`3px solid ${item.color}`}}>
                      <div style={{fontSize:11,color:item.color,marginBottom:4,fontWeight:600}}>{item.time}</div>
                      <div style={{fontSize:12,color:C.textDim,lineHeight:1.6}}>{item.rec}</div>
                    </div>
                  ))}
                </div>
              </Card>
            </div>
          )}

          {tab === "Supplements" && (
            <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
              <Card>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 16 }}>
                  <div style={{ fontSize: 13, fontWeight: 600, color: C.textDim }}>Supplement Stack</div>
                  <Btn onClick={() => startEditSupp("new")} variant="secondary" small>+ Add</Btn>
                </div>

                {/* Group by AM / PM / Other */}
                {["AM", "PM", "Pre-Run", "Post-Run", "With Food", "Bedtime"].map(group => {
                  const items = supplements.map((s, i) => ({ ...s, _idx: i })).filter(s => (s.timing || "AM") === group);
                  if (items.length === 0) return null;
                  return (
                    <div key={group} style={{ marginBottom: 16 }}>
                      <div style={{ fontSize: 10, fontWeight: 700, color: group === "AM" ? C.amber : group === "PM" ? C.purple : C.cyan,
                        textTransform: "uppercase", letterSpacing: 1, marginBottom: 8, paddingLeft: 4 }}>
                        {group}
                      </div>
                      <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
                        {items.map(s => (
                          <div key={s._idx} onClick={() => startEditSupp(s._idx)} style={{
                            display: "flex", justifyContent: "space-between", alignItems: "center",
                            padding: "10px 14px", background: C.bg2, borderRadius: 8, cursor: "pointer",
                            border: `1px solid ${editingSuppIdx === s._idx ? C.cyan : "transparent"}`,
                            transition: "border 0.2s",
                          }}>
                            <div style={{ flex: 1 }}>
                              <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                                <span style={{ fontSize: 13, fontWeight: 600, color: C.text }}>{s.name}</span>
                                {s.pills > 1 && <span style={{ fontSize: 10, fontWeight: 700, color: C.cyan,
                                  background: C.cyan + "15", padding: "2px 6px", borderRadius: 4 }}>×{s.pills}</span>}
                              </div>
                              <div style={{ fontSize: 11, color: C.textMuted, marginTop: 2 }}>
                                {s.pills === 1 ? "1 pill" : `${s.pills} pills`}{s.dose ? ` · ${s.dose}` : ""}
                                {s.notes ? ` · ${s.notes}` : ""}
                              </div>
                            </div>
                            <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
                              <Badge label={s.category || "general"} color={C.purple} />
                              <button onClick={(e) => { e.stopPropagation(); duplicateSupp(s._idx); }}
                                title={`Add ${s.timing === "AM" ? "PM" : "AM"} dose`}
                                style={{ background: "none", border: "none", cursor: "pointer", color: C.textMuted, fontSize: 14, padding: 2 }}>
                                +
                              </button>
                            </div>
                          </div>
                        ))}
                      </div>
                    </div>
                  );
                })}

                {/* Ungrouped supplements (timing doesn't match known groups) */}
                {(() => {
                  const knownGroups = ["AM", "PM", "Pre-Run", "Post-Run", "With Food", "Bedtime"];
                  const ungrouped = supplements.map((s, i) => ({ ...s, _idx: i })).filter(s => !knownGroups.includes(s.timing));
                  if (ungrouped.length === 0) return null;
                  return (
                    <div style={{ marginBottom: 16 }}>
                      <div style={{ fontSize: 10, fontWeight: 700, color: C.textMuted, textTransform: "uppercase", letterSpacing: 1, marginBottom: 8, paddingLeft: 4 }}>Other</div>
                      <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
                        {ungrouped.map(s => (
                          <div key={s._idx} onClick={() => startEditSupp(s._idx)} style={{
                            display: "flex", justifyContent: "space-between", alignItems: "center",
                            padding: "10px 14px", background: C.bg2, borderRadius: 8, cursor: "pointer",
                          }}>
                            <div>
                              <span style={{ fontSize: 13, fontWeight: 600, color: C.text }}>{s.name}</span>
                              <div style={{ fontSize: 11, color: C.textMuted }}>{s.pills || 1} pill{(s.pills||1)>1?"s":""}{s.dose ? ` · ${s.dose}` : ""} · {s.timing || "?"}</div>
                            </div>
                            <Badge label={s.category || "general"} color={C.purple} />
                          </div>
                        ))}
                      </div>
                    </div>
                  );
                })()}

                {supplements.length === 0 && (
                  <EmptyState icon="💊" title="No supplements added" sub="Tap + Add to build your supplement stack with AM/PM dosing" />
                )}
              </Card>

              {/* Edit / Add form */}
              {editingSuppIdx !== null && (
                <Card style={{ borderColor: C.cyan + "40" }}>
                  <div style={{ fontSize: 13, fontWeight: 700, color: C.text, marginBottom: 12 }}>
                    {editingSuppIdx === "new" ? "Add Supplement" : "Edit Supplement"}
                  </div>

                  <div style={{ display: "grid", gridTemplateColumns: "1fr 80px", gap: 10, marginBottom: 10 }}>
                    <div>
                      <label style={{ fontSize: 10, color: C.textMuted, textTransform: "uppercase", letterSpacing: 1 }}>Name</label>
                      <input value={suppForm.name} onChange={e => setSuppForm(p => ({ ...p, name: e.target.value }))}
                        placeholder="e.g. Vitamin D3" style={{
                        width: "100%", padding: "8px 10px", borderRadius: 6, border: `1px solid ${C.border}`,
                        background: C.bg2, color: C.text, fontSize: 13, fontFamily: "'IBM Plex Mono', monospace", boxSizing: "border-box",
                      }} />
                    </div>
                    <div>
                      <label style={{ fontSize: 10, color: C.textMuted, textTransform: "uppercase", letterSpacing: 1 }}>Pills</label>
                      <input type="number" min="1" max="20" value={suppForm.pills}
                        onChange={e => setSuppForm(p => ({ ...p, pills: e.target.value }))}
                        style={{
                        width: "100%", padding: "8px 10px", borderRadius: 6, border: `1px solid ${C.border}`,
                        background: C.bg2, color: C.text, fontSize: 13, fontFamily: "'IBM Plex Mono', monospace", boxSizing: "border-box", textAlign: "center",
                      }} />
                    </div>
                  </div>

                  <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, marginBottom: 10 }}>
                    <div>
                      <label style={{ fontSize: 10, color: C.textMuted, textTransform: "uppercase", letterSpacing: 1 }}>Timing</label>
                      <div style={{ display: "flex", flexWrap: "wrap", gap: 4, marginTop: 4 }}>
                        {["AM", "PM", "Pre-Run", "Post-Run", "With Food", "Bedtime"].map(t => (
                          <button key={t} onClick={() => setSuppForm(p => ({ ...p, timing: t }))} style={{
                            padding: "5px 10px", borderRadius: 6, fontSize: 11, fontWeight: 600, cursor: "pointer",
                            background: suppForm.timing === t ? (t === "AM" ? C.amber : t === "PM" ? C.purple : C.cyan) + "20" : C.bg2,
                            color: suppForm.timing === t ? (t === "AM" ? C.amber : t === "PM" ? C.purple : C.cyan) : C.textMuted,
                            border: `1px solid ${suppForm.timing === t ? (t === "AM" ? C.amber : t === "PM" ? C.purple : C.cyan) : C.border}`,
                          }}>{t}</button>
                        ))}
                      </div>
                    </div>
                    <div>
                      <label style={{ fontSize: 10, color: C.textMuted, textTransform: "uppercase", letterSpacing: 1 }}>Category</label>
                      <div style={{ display: "flex", flexWrap: "wrap", gap: 4, marginTop: 4 }}>
                        {["general", "performance", "recovery", "joint", "sleep", "immune"].map(c => (
                          <button key={c} onClick={() => setSuppForm(p => ({ ...p, category: c }))} style={{
                            padding: "5px 8px", borderRadius: 6, fontSize: 10, cursor: "pointer", textTransform: "capitalize",
                            background: suppForm.category === c ? C.purple + "20" : C.bg2,
                            color: suppForm.category === c ? C.purple : C.textMuted,
                            border: `1px solid ${suppForm.category === c ? C.purple : C.border}`,
                          }}>{c}</button>
                        ))}
                      </div>
                    </div>
                  </div>

                  <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, marginBottom: 14 }}>
                    <div>
                      <label style={{ fontSize: 10, color: C.textMuted, textTransform: "uppercase", letterSpacing: 1 }}>Dose (optional)</label>
                      <input value={suppForm.dose} onChange={e => setSuppForm(p => ({ ...p, dose: e.target.value }))}
                        placeholder="e.g. 1000 IU, 500mg" style={{
                        width: "100%", padding: "8px 10px", borderRadius: 6, border: `1px solid ${C.border}`,
                        background: C.bg2, color: C.text, fontSize: 12, fontFamily: "'IBM Plex Mono', monospace", boxSizing: "border-box",
                      }} />
                    </div>
                    <div>
                      <label style={{ fontSize: 10, color: C.textMuted, textTransform: "uppercase", letterSpacing: 1 }}>Notes (optional)</label>
                      <input value={suppForm.notes} onChange={e => setSuppForm(p => ({ ...p, notes: e.target.value }))}
                        placeholder="e.g. take with fat" style={{
                        width: "100%", padding: "8px 10px", borderRadius: 6, border: `1px solid ${C.border}`,
                        background: C.bg2, color: C.text, fontSize: 12, fontFamily: "'IBM Plex Mono', monospace", boxSizing: "border-box",
                      }} />
                    </div>
                  </div>

                  <div style={{ display: "flex", gap: 8, justifyContent: "space-between" }}>
                    <div style={{ display: "flex", gap: 8 }}>
                      <Btn onClick={saveSuppForm} variant="primary" small>Save</Btn>
                      <Btn onClick={() => setEditingSuppIdx(null)} variant="ghost" small>Cancel</Btn>
                    </div>
                    {editingSuppIdx !== "new" && (
                      <button onClick={() => deleteSupp(editingSuppIdx)} style={{
                        padding: "6px 12px", borderRadius: 6, border: `1px solid ${C.red}40`, cursor: "pointer",
                        background: "transparent", color: C.red, fontSize: 11, fontFamily: "'IBM Plex Mono', monospace",
                      }}>Delete</button>
                    )}
                  </div>
                </Card>
              )}

              {/* Quick summary */}
              {supplements.length > 0 && (
                <Card style={{ padding: "12px 16px" }}>
                  <div style={{ fontSize: 11, color: C.textMuted }}>
                    <strong style={{ color: C.text }}>{supplements.length}</strong> entries · <strong style={{ color: C.amber }}>{supplements.filter(s => s.timing === "AM").length}</strong> AM · <strong style={{ color: C.purple }}>{supplements.filter(s => s.timing === "PM").length}</strong> PM · <strong style={{ color: C.text }}>{supplements.reduce((s, x) => s + (parseInt(x.pills) || 1), 0)}</strong> total pills/day
                  </div>
                </Card>
              )}
            </div>
          )}
        </div>
      );
    }

window.AppViews = Object.assign(window.AppViews || {}, { Nutrition });
