'use client';

import React, { useState, useEffect, useMemo } from 'react';
import useSWR from 'swr';
import { useApi } from '@/lib/useApi';
import { SetPageHeader } from '@/components/layout/SetPageHeader';
import {
  getMealPlanByWeek,
  createMealPlan,
  updateMealPlan,
  getSuggestions,
  getShoppingGap,
  updateMealPlanStatus,
  MealPlanResponse,
} from '@/services/meal-plans';
import {
  getActiveNutritionTarget,
  setNutritionTarget,
  calculateTargetPreset,
  NutritionTargetResponse,
} from '@/services/nutrition-targets';
import { listRecipes } from '@/services/recipes';
import { MealType, MealPlanStatus } from '@meshitrack/shared';
import { Icon } from '@/components/ui/Icon';

// --- Utility Helpers ---
function getMonday(d: Date): Date {
  const date = new Date(d);
  const day = date.getDay();
  const diff = date.getDate() - day + (day === 0 ? -6 : 1);
  const mon = new Date(date.setDate(diff));
  mon.setHours(0, 0, 0, 0);
  return mon;
}

function toIsoDate(d: Date): string {
  const y = d.getFullYear();
  const m = String(d.getMonth() + 1).padStart(2, '0');
  const date = String(d.getDate()).padStart(2, '0');
  return `${y}-${m}-${date}`;
}

function addDays(d: Date, days: number): Date {
  const copy = new Date(d);
  copy.setDate(copy.getDate() + days);
  return copy;
}

function formatNiceDate(iso: string): string {
  const [y, m, d] = iso.split('-').map(Number);
  // Adjusting for locale timezone bias
  const date = new Date(y, m - 1, d);
  return date.toLocaleDateString(undefined, { weekday: 'short', month: 'short', day: 'numeric' });
}

const MEAL_TYPES = [MealType.BREAKFAST, MealType.LUNCH, MealType.DINNER, MealType.SNACK];

// Standard blank nutrition structure
const BLANK_NUTRITION = {
  calories: 0,
  protein: 0,
  carbs: 0,
  fat: 0,
  fiber: 0,
  sugar: 0,
  sodium: 0,
};

export default function MealPlansPage() {
  const { householdId, isLoading } = useApi();
  const [currentMonday, setCurrentMonday] = useState<Date>(() => getMonday(new Date()));
  const weekStr = useMemo(() => toIsoDate(currentMonday), [currentMonday]);

  if (isLoading) {
    return (
      <>
        <SetPageHeader title="Meal Planner" subtitle="Schedule your weekly nutrition" />
        <div style={{ padding: '28px 32px', display: 'grid', gridTemplateColumns: '7fr 3fr', gap: 24 }}>
          <div style={{ height: 400, background: 'var(--bg-elev)', borderRadius: 'var(--r-md)', opacity: 0.6 }} />
          <div style={{ height: 400, background: 'var(--bg-elev)', borderRadius: 'var(--r-md)', opacity: 0.6 }} />
        </div>
      </>
    );
  }

  if (!householdId) {
    return (
      <>
        <SetPageHeader title="Meal Planner" subtitle="Schedule your weekly nutrition" />
        <div style={{ padding: '28px 32px' }}>
          <div className="mt-card">
            <p style={{ color: 'var(--ink-muted)' }}>Please join a household to access the meal planner.</p>
          </div>
        </div>
      </>
    );
  }

  return (
    <>
      <SetPageHeader title="Meal Planner" subtitle="Schedule your weekly nutrition" />
      <MealPlannerDashboard
        householdId={householdId}
        currentMonday={currentMonday}
        setCurrentMonday={setCurrentMonday}
        weekStr={weekStr}
      />
    </>
  );
}

interface DashboardProps {
  householdId: string;
  currentMonday: Date;
  setCurrentMonday: React.Dispatch<React.SetStateAction<Date>>;
  weekStr: string;
}

function MealPlannerDashboard({ householdId, currentMonday, setCurrentMonday, weekStr }: DashboardProps) {
  const [isGoalModalOpen, setIsGoalModalOpen] = useState(false);
  const [activeRightTab, setActiveRightTab] = useState<'suggestions' | 'gap'>('suggestions');
  const [isAddingMeal, setIsAddingMeal] = useState<{ date: string; type: MealType } | null>(null);

  // --- Data Fetchers via SWR ---
  const { data: targetData, mutate: mutateTarget } = useSWR(
    householdId ? ['nutrition-targets', householdId] : null,
    () => getActiveNutritionTarget(householdId)
  );

  const activeTarget: NutritionTargetResponse | null = useMemo(() => {
    if (!targetData || 'message' in targetData) return null;
    return targetData;
  }, [targetData]);

  const { data: planData, mutate: mutatePlan, isLoading: planLoading } = useSWR(
    householdId && weekStr ? ['meal-plan', householdId, weekStr] : null,
    () => getMealPlanByWeek(householdId, weekStr)
  );

  const currentPlan: MealPlanResponse | null = useMemo(() => {
    if (!planData || 'message' in planData) return null;
    return planData;
  }, [planData]);

  const { data: recipeList } = useSWR(
    householdId ? ['recipes', householdId] : null,
    () => listRecipes(householdId, { limit: 100 })
  );

  const { data: suggestions } = useSWR(
    householdId ? ['suggestions', householdId] : null,
    () => getSuggestions(householdId, 5)
  );

  const { data: gapReport, mutate: mutateGap } = useSWR(
    householdId && currentPlan?._id ? ['gap', householdId, currentPlan._id] : null,
    () => getShoppingGap(householdId, currentPlan!._id)
  );

  // --- Day Schedule Calculations ---
  // Always ensure we have representations for the 7 days even if no plan doc exists yet.
  const weeklyDays = useMemo(() => {
    const arr = [];
    for (let i = 0; i < 7; i++) {
      const d = addDays(currentMonday, i);
      const dStr = toIsoDate(d);
      const planDay = currentPlan?.days.find((x) => x.date === dStr);
      arr.push({
        date: dStr,
        meals: planDay?.meals || [],
        dailyNutritionTotal: planDay?.dailyNutritionTotal || BLANK_NUTRITION,
      });
    }
    return arr;
  }, [currentMonday, currentPlan]);

  // --- Action Event Handlers ---
  const prevWeek = () => setCurrentMonday((m) => addDays(m, -7));
  const nextWeek = () => setCurrentMonday((m) => addDays(m, 7));
  const jumpToToday = () => setCurrentMonday(getMonday(new Date()));

  async function handleCreatePlan() {
    const initialDays = [];
    for (let i = 0; i < 7; i++) {
      initialDays.push({
        date: toIsoDate(addDays(currentMonday, i)),
        meals: [],
        dailyNutritionTotal: BLANK_NUTRITION,
      });
    }

    try {
      await createMealPlan(householdId, {
        weekStartDate: weekStr,
        days: initialDays,
        status: MealPlanStatus.DRAFT,
      });
      mutatePlan();
    } catch (err) {
      console.error('Failed to init weekly plan', err);
    }
  }

  async function handleAddMeal(recipeId: string, servings: number) {
    if (!isAddingMeal) return;
    const targetRecipe = recipeList?.data.find((r) => r._id === recipeId);
    if (!targetRecipe) return;

    const newMeal = {
      id: crypto.randomUUID(),
      type: isAddingMeal.type,
      recipeId: targetRecipe._id,
      recipeName: targetRecipe.name,
      servings,
      perServingNutrition: targetRecipe.perServingNutrition,
    };

    let workingPlan = currentPlan;
    if (!workingPlan) {
      const initialDays = [];
      for (let i = 0; i < 7; i++) {
        initialDays.push({
          date: toIsoDate(addDays(currentMonday, i)),
          meals: [],
          dailyNutritionTotal: BLANK_NUTRITION,
        });
      }
      workingPlan = await createMealPlan(householdId, {
        weekStartDate: weekStr,
        days: initialDays,
        status: MealPlanStatus.DRAFT,
      });
    }

    const updatedDays = workingPlan.days.map((day) => {
      if (day.date === isAddingMeal.date) {
        return {
          ...day,
          meals: [...day.meals, newMeal],
        };
      }
      return day;
    });

    try {
      await updateMealPlan(householdId, workingPlan._id, { days: updatedDays as any });
      mutatePlan();
      mutateGap();
      setIsAddingMeal(null);
    } catch (err) {
      console.error('Failed to add meal', err);
    }
  }

  async function handleRemoveMeal(dayDate: string, mealId: string) {
    if (!currentPlan) return;

    const updatedDays = currentPlan.days.map((day) => {
      if (day.date === dayDate) {
        return {
          ...day,
          meals: day.meals.filter((m) => m.id !== mealId),
        };
      }
      return day;
    });

    try {
      await updateMealPlan(householdId, currentPlan._id, { days: updatedDays as any });
      mutatePlan();
      mutateGap();
    } catch (err) {
      console.error('Failed to remove meal', err);
    }
  }

  async function handleToggleStatus() {
    if (!currentPlan) return;
    const nextStatus =
      currentPlan.status === MealPlanStatus.DRAFT ? MealPlanStatus.ACTIVE : MealPlanStatus.COMPLETED;
    try {
      await updateMealPlanStatus(householdId, currentPlan._id, nextStatus);
      mutatePlan();
    } catch (err) {
      console.error('Status toggle failed', err);
    }
  }

  // --- Drag and Drop Functionality ---
  const [dragOverDay, setDragOverDay] = useState<string | null>(null);

  function handleDragStart(e: React.DragEvent, sourceDayStr: string, mealId: string) {
    e.dataTransfer.setData('text/plain', JSON.stringify({ sourceDayStr, mealId }));
    e.dataTransfer.effectAllowed = 'move';
  }

  async function handleDrop(e: React.DragEvent, targetDayStr: string) {
    e.preventDefault();
    setDragOverDay(null);
    if (!currentPlan) return;

    try {
      const data = JSON.parse(e.dataTransfer.getData('text/plain'));
      const { sourceDayStr, mealId } = data;
      if (sourceDayStr === targetDayStr) return;

      // Find source meal
      const sourceDay = currentPlan.days.find((d) => d.date === sourceDayStr);
      const mealToMove = sourceDay?.meals.find((m) => m.id === mealId);
      if (!mealToMove) return;

      const updatedDays = currentPlan.days.map((day) => {
        if (day.date === sourceDayStr) {
          return { ...day, meals: day.meals.filter((m) => m.id !== mealId) };
        }
        if (day.date === targetDayStr) {
          return { ...day, meals: [...day.meals, mealToMove] };
        }
        return day;
      });

      // Optimistic mutate
      mutatePlan({ ...currentPlan, days: updatedDays as any }, false);
      await updateMealPlan(householdId, currentPlan._id, { days: updatedDays as any });
      mutatePlan();
      mutateGap();
    } catch (err) {
      console.error('Drop processing failed', err);
    }
  }

  return (
    <div style={{ padding: '0 32px 56px' }}>
      {/* --- Top Navigation Bar --- */}
      <div
        style={{
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          marginBottom: 24,
          flexWrap: 'wrap',
          gap: 16,
        }}
      >
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <button className="mt-btn mt-btn--ghost" onClick={prevWeek}>
            <Icon name="chevronLeft" size={16} />
          </button>
          <div style={{ textAlign: 'center', minWidth: 220 }}>
            <span style={{ fontSize: 16, fontWeight: 600, letterSpacing: '-0.01em' }}>
              Week of {formatNiceDate(weekStr)}
            </span>
          </div>
          <button className="mt-btn mt-btn--ghost" onClick={nextWeek}>
            <Icon name="chevronRight" size={16} />
          </button>
          <button
            className="mt-btn mt-btn--ghost"
            style={{ fontSize: 12, padding: '6px 10px' }}
            onClick={jumpToToday}
          >
            Today
          </button>
        </div>

        {/* Target summary card (glassmorphism feel) */}
        <div
          onClick={() => setIsGoalModalOpen(true)}
          style={{
            display: 'flex',
            alignItems: 'center',
            gap: 16,
            background: 'var(--bg-elev)',
            border: '1px solid var(--border)',
            padding: '8px 16px',
            borderRadius: 'var(--r-md)',
            cursor: 'pointer',
            transition: 'all 0.2s',
            boxShadow: 'var(--shadow-sm)',
          }}
          onMouseEnter={(e) => (e.currentTarget.style.transform = 'translateY(-1px)')}
          onMouseLeave={(e) => (e.currentTarget.style.transform = 'none')}
        >
          <Icon name="target" size={18} style={{ color: 'var(--brand)' }} />
          <div style={{ display: 'flex', flexDirection: 'column' }}>
            <span style={{ fontSize: 10, color: 'var(--ink-muted)', textTransform: 'uppercase', fontWeight: 600 }}>
              Nutrition Strategy
            </span>
            <span style={{ fontSize: 13, fontWeight: 600, display: 'flex', alignItems: 'center', gap: 8 }}>
              {activeTarget ? (
                <>
                  <span className="num">{activeTarget.dailyCalories} kcal</span>
                  <span style={{ color: 'var(--border-strong)' }}>|</span>
                  <span className="num" style={{ fontSize: 12, color: 'var(--ink-muted)', fontWeight: 500 }}>
                    {activeTarget.proteinG}g P · {activeTarget.carbsG}g C · {activeTarget.fatG}g F
                  </span>
                </>
              ) : (
                <span style={{ color: 'var(--warn)', fontWeight: 500 }}>Set Macro Goals +</span>
              )}
            </span>
          </div>
        </div>

        <div style={{ display: 'flex', gap: 8 }}>
          {currentPlan ? (
            <>
              <div
                className={`mt-pill ${currentPlan.status === 'active' ? 'mt-pill--ok' : 'mt-pill--ghost'}`}
                style={{ height: 32, display: 'flex', alignItems: 'center', textTransform: 'capitalize' }}
              >
                {currentPlan.status}
              </div>
              <button className="mt-btn mt-btn--primary" onClick={handleToggleStatus}>
                {currentPlan.status === 'draft' ? 'Activate Plan' : 'Complete'}
              </button>
            </>
          ) : (
            <button className="mt-btn mt-btn--primary" onClick={handleCreatePlan}>
              <Icon name="plus" size={16} /> Start Weekly Plan
            </button>
          )}
        </div>
      </div>

      {/* --- Workspace Layout --- */}
      <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 7.2fr) minmax(0, 2.8fr)', gap: 24 }}>
        {/* --- LEFT COLUMN: Calendar view --- */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          {planLoading ? (
            <div style={{ height: 300, background: 'var(--bg-elev)', borderRadius: 'var(--r-md)', opacity: 0.5 }} />
          ) : (
            weeklyDays.map((day) => {
              const isOverTarget = activeTarget && day.dailyNutritionTotal.calories > activeTarget.dailyCalories;
              const calPercentage = activeTarget
                ? Math.min(Math.round((day.dailyNutritionTotal.calories / activeTarget.dailyCalories) * 100), 100)
                : 0;

              return (
                <div
                  key={day.date}
                  onDragOver={(e) => {
                    e.preventDefault();
                    setDragOverDay(day.date);
                  }}
                  onDragLeave={() => setDragOverDay(null)}
                  onDrop={(e) => handleDrop(e, day.date)}
                  style={{
                    background: dragOverDay === day.date ? 'var(--brand-soft)' : 'var(--bg-elev)',
                    border: `1px solid ${dragOverDay === day.date ? 'var(--brand)' : 'var(--border)'}`,
                    borderRadius: 'var(--r-md)',
                    padding: '16px 20px',
                    boxShadow: 'var(--shadow-sm)',
                    transition: 'background 0.15s ease, border 0.15s ease',
                  }}
                >
                  {/* Day Title Strip */}
                  <div
                    style={{
                      display: 'flex',
                      justifyContent: 'space-between',
                      alignItems: 'center',
                      borderBottom: '1px solid var(--bg-inset)',
                      paddingBottom: 12,
                      marginBottom: 12,
                    }}
                  >
                    <div>
                      <div style={{ fontSize: 15, fontWeight: 600, color: 'var(--ink-strong)' }}>
                        {formatNiceDate(day.date)}
                      </div>
                    </div>

                    {/* Calibration progress bar */}
                    {activeTarget && (
                      <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 2 }}>
                          <span style={{ fontSize: 11, fontWeight: 600 }} className="num">
                            <span style={{ color: isOverTarget ? 'var(--danger)' : 'var(--brand)' }}>
                              {day.dailyNutritionTotal.calories}
                            </span>{' '}
                            / {activeTarget.dailyCalories} kcal
                          </span>
                          <div
                            style={{
                              width: 120,
                              height: 5,
                              background: 'var(--bg-inset)',
                              borderRadius: 3,
                              overflow: 'hidden',
                            }}
                          >
                            <div
                              style={{
                                width: `${calPercentage}%`,
                                height: '100%',
                                background: isOverTarget ? 'var(--danger)' : 'var(--brand)',
                                transition: 'width 0.4s ease',
                              }}
                            />
                          </div>
                        </div>
                      </div>
                    )}
                  </div>

                  {/* Meal Row Slots */}
                  <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12 }}>
                    {MEAL_TYPES.map((type) => {
                      const mealsForType = day.meals.filter((m) => m.type === type);

                      return (
                        <div
                          key={type}
                          style={{
                            background: 'var(--bg-inset)',
                            borderRadius: 'var(--r-sm)',
                            padding: 10,
                            minHeight: 110,
                            display: 'flex',
                            flexDirection: 'column',
                            gap: 6,
                          }}
                        >
                          <div
                            style={{
                              fontSize: 10,
                              fontWeight: 600,
                              textTransform: 'uppercase',
                              letterSpacing: '0.03em',
                              color: 'var(--ink-muted)',
                              marginBottom: 2,
                            }}
                          >
                            {type}
                          </div>

                          {mealsForType.map((meal) => (
                            <div
                              key={meal.id}
                              draggable
                              onDragStart={(e) => handleDragStart(e, day.date, meal.id)}
                              style={{
                                background: 'var(--bg-elev)',
                                border: '1px solid var(--border)',
                                borderRadius: 'var(--r-xs)',
                                padding: '6px 8px',
                                cursor: 'grab',
                                position: 'relative',
                                boxShadow: 'var(--shadow-sm)',
                              }}
                            >
                              <button
                                onClick={() => handleRemoveMeal(day.date, meal.id)}
                                style={{
                                  position: 'absolute',
                                  top: 4,
                                  right: 4,
                                  opacity: 0.5,
                                  color: 'var(--ink-muted)',
                                }}
                                onMouseEnter={(e) => (e.currentTarget.style.opacity = '1')}
                                onMouseLeave={(e) => (e.currentTarget.style.opacity = '0.5')}
                              >
                                <Icon name="x" size={12} />
                              </button>
                              <div
                                style={{
                                  fontSize: 12,
                                  fontWeight: 600,
                                  paddingRight: 12,
                                  whiteSpace: 'nowrap',
                                  overflow: 'hidden',
                                  textOverflow: 'ellipsis',
                                }}
                                title={meal.recipeName}
                              >
                                {meal.recipeName}
                              </div>
                              <div
                                style={{
                                  fontSize: 10,
                                  color: 'var(--ink-muted)',
                                  marginTop: 2,
                                  display: 'flex',
                                  justifyContent: 'space-between',
                                }}
                              >
                                <span>{meal.servings} svc</span>
                                <span className="num" style={{ fontWeight: 500 }}>
                                  {Math.round(meal.perServingNutrition.calories * meal.servings)} cal
                                </span>
                              </div>
                            </div>
                          ))}

                          {/* Quick inline Add button */}
                          <button
                            onClick={() => setIsAddingMeal({ date: day.date, type })}
                            style={{
                              marginTop: 'auto',
                              border: '1px dashed var(--border-strong)',
                              borderRadius: 'var(--r-xs)',
                              background: 'transparent',
                              color: 'var(--ink-muted)',
                              fontSize: 11,
                              padding: '4px 0',
                              display: 'flex',
                              alignItems: 'center',
                              justifyContent: 'center',
                              gap: 4,
                              transition: 'all 0.12s',
                            }}
                            onMouseEnter={(e) => {
                              e.currentTarget.style.background = 'var(--bg-elev)';
                              e.currentTarget.style.color = 'var(--ink)';
                            }}
                            onMouseLeave={(e) => {
                              e.currentTarget.style.background = 'transparent';
                              e.currentTarget.style.color = 'var(--ink-muted)';
                            }}
                          >
                            <Icon name="plus" size={12} /> Add
                          </button>
                        </div>
                      );
                    })}
                  </div>
                </div>
              );
            })
          )}
        </div>

        {/* --- RIGHT COLUMN: AI Suggestions & Live Shopping Gap Tabs --- */}
        <div>
          <div
            className="mt-card"
            style={{
              padding: 0,
              overflow: 'hidden',
              boxShadow: 'var(--shadow-md)',
              position: 'sticky',
              top: 24,
            }}
          >
            {/* Glass tab heads */}
            <div
              style={{
                display: 'grid',
                gridTemplateColumns: '1fr 1fr',
                background: 'var(--bg-inset)',
                borderBottom: '1px solid var(--border)',
              }}
            >
              {(['suggestions', 'gap'] as const).map((tab) => (
                <button
                  key={tab}
                  onClick={() => setActiveRightTab(tab)}
                  style={{
                    padding: '12px 0',
                    fontSize: 13,
                    fontWeight: 600,
                    textAlign: 'center',
                    color: activeRightTab === tab ? 'var(--ink-strong)' : 'var(--ink-muted)',
                    background: activeRightTab === tab ? 'var(--bg-elev)' : 'transparent',
                    borderBottom: activeRightTab === tab ? '2px solid var(--brand)' : 'none',
                    transition: 'all 0.12s',
                  }}
                >
                  {tab === 'suggestions' ? '🔥 Spark Recommendations' : '🛒 Store Deficits'}
                </button>
              ))}
            </div>

            {/* Tab content viewport */}
            <div style={{ padding: 20, maxHeight: '70vh', overflowY: 'auto' }}>
              {activeRightTab === 'suggestions' && (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
                  <div style={{ fontSize: 12, color: 'var(--ink-muted)', lineHeight: 1.4 }}>
                    Smart Ranking evaluates expiring pantry items, macro balances, and historical meal diversity.
                  </div>

                  {!suggestions || suggestions.length === 0 ? (
                    <div style={{ textAlign: 'center', padding: 24, color: 'var(--ink-faint)' }}>
                      No dynamic recommendations yet. Add inventory and recipes to spark.
                    </div>
                  ) : (
                    suggestions.map((s) => (
                      <div
                        key={s.recipeId}
                        style={{
                          border: '1px solid var(--border)',
                          borderRadius: 'var(--r-sm)',
                          padding: 12,
                          background: 'var(--bg-inset)',
                          display: 'flex',
                          flexDirection: 'column',
                          gap: 8,
                        }}
                      >
                        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                          <span style={{ fontWeight: 600, fontSize: 13, color: 'var(--ink-strong)' }}>
                            {s.recipeName}
                          </span>
                          <span
                            className="mt-pill mt-pill--brand"
                            style={{ fontWeight: 700, fontSize: 10 }}
                            title={`Coverage: ${s.scores.coverage}, Expiry: ${s.scores.urgency}, Nutrition: ${s.scores.nutrition}, Variety: ${s.scores.variety}`}
                          >
                            {Math.round(s.totalScore)}% Match
                          </span>
                        </div>

                        {/* Tiny reasoning badges */}
                        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>
                          {s.reasoning.map((r, idx) => (
                            <span
                              key={idx}
                              style={{
                                background: 'rgba(0, 0, 0, 0.04)',
                                border: '1px solid var(--border-strong)',
                                borderRadius: 4,
                                padding: '2px 6px',
                                fontSize: 10,
                                color: 'var(--ink-muted)',
                              }}
                            >
                              {r}
                            </span>
                          ))}
                        </div>
                      </div>
                    ))
                  )}
                </div>
              )}

              {activeRightTab === 'gap' && (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
                  <div style={{ fontSize: 12, color: 'var(--ink-muted)', lineHeight: 1.4 }}>
                    Contrasts quantities needed to cook scheduled recipes against active pantry inventory levels.
                  </div>

                  {!currentPlan ? (
                    <div style={{ textAlign: 'center', padding: 24, color: 'var(--ink-faint)' }}>
                      Initialize a plan to run inventory analyses.
                    </div>
                  ) : !gapReport || gapReport.missingItems.length === 0 ? (
                    <div
                      style={{
                        textAlign: 'center',
                        padding: '24px 16px',
                        color: 'var(--brand)',
                        background: 'var(--brand-soft)',
                        border: '1px solid var(--brand)',
                        borderRadius: 'var(--r-sm)',
                        fontWeight: 500,
                      }}
                    >
                      🎉 fully stocked! All required ingredients exist in your pantry.
                    </div>
                  ) : (
                    <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                      {gapReport.missingItems.map((item) => (
                        <div
                          key={item.productId}
                          style={{
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'space-between',
                            padding: '8px 12px',
                            borderRadius: 'var(--r-xs)',
                            background: 'var(--danger-soft)',
                            border: '1px solid color-mix(in oklab, var(--danger) 20%, transparent)',
                          }}
                        >
                          <div style={{ display: 'flex', flexDirection: 'column' }}>
                            <span style={{ fontSize: 12, fontWeight: 600, color: 'var(--ink-strong)' }}>
                              {item.productName}
                            </span>
                            <span style={{ fontSize: 10, color: 'var(--ink-muted)' }}>
                              Need: {item.requiredQuantity} {item.unit} · Stock: {item.pantryQuantity}
                            </span>
                          </div>
                          <div
                            className="num"
                            style={{ color: 'var(--danger)', fontWeight: 700, fontSize: 13 }}
                          >
                            +{Math.ceil(item.missingQuantity)} {item.unit}
                          </div>
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              )}
            </div>
          </div>
        </div>
      </div>

      {/* --- NUTRITION STRATEGY SETTINGS MODAL --- */}
      {isGoalModalOpen && (
        <NutritionGoalModal
          householdId={householdId}
          activeTarget={activeTarget}
          onClose={() => setIsGoalModalOpen(false)}
          onSaved={() => {
            mutateTarget();
            setIsGoalModalOpen(false);
          }}
        />
      )}

      {/* --- QUICK MEAL SELECTOR MODAL --- */}
      {isAddingMeal && (
        <AddMealModal
          recipes={recipeList?.data || []}
          dateStr={isAddingMeal.date}
          mealType={isAddingMeal.type}
          onClose={() => setIsAddingMeal(null)}
          onConfirm={handleAddMeal}
        />
      )}
    </div>
  );
}

// --- Nutrition Strategy Customizer ---
interface NutritionGoalModalProps {
  householdId: string;
  activeTarget: NutritionTargetResponse | null;
  onClose: () => void;
  onSaved: () => void;
}

function NutritionGoalModal({ householdId, activeTarget, onClose, onSaved }: NutritionGoalModalProps) {
  const [cals, setCals] = useState(activeTarget?.dailyCalories || 2000);
  const [pG, setPG] = useState(activeTarget?.proteinG || 150);
  const [cG, setCG] = useState(activeTarget?.carbsG || 200);
  const [fG, setFG] = useState(activeTarget?.fatG || 67);
  const [isSaving, setIsSaving] = useState(false);

  async function handleApplyPreset(strategy: 'maintenance' | 'loss' | 'gain') {
    try {
      const split = await calculateTargetPreset(householdId, cals, strategy);
      setPG(split.proteinG);
      setCG(split.carbsG);
      setFG(split.fatG);
    } catch (err) {
      console.error('Preset calc failed', err);
    }
  }

  async function handleSave() {
    setIsSaving(true);
    try {
      await setNutritionTarget(householdId, {
        dailyCalories: cals,
        proteinG: pG,
        carbsG: cG,
        fatG: fG,
        isActive: true,
      });
      onSaved();
    } catch (err) {
      console.error('Failed saving targets', err);
    } finally {
      setIsSaving(false);
    }
  }

  return (
    <div
      style={{
        position: 'fixed',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        background: 'rgba(0,0,0,0.4)',
        backdropFilter: 'blur(4px)',
        display: 'grid',
        placeItems: 'center',
        zIndex: 1000,
      }}
    >
      <div
        className="mt-card"
        style={{ width: '100%', maxWidth: 440, boxShadow: 'var(--shadow-lg)', animation: 'fadeIn 0.2s ease-out' }}
      >
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
          <span style={{ fontSize: 18, fontWeight: 600, fontFamily: 'var(--font-display)' }}>Nutrition Strategy</span>
          <button onClick={onClose} style={{ color: 'var(--ink-muted)' }}>
            <Icon name="x" size={20} />
          </button>
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          {/* Calorie Target Input */}
          <div>
            <label className="mt-field-label">Daily Calorie Target (kcal)</label>
            <input
              type="number"
              className="mt-field"
              style={{ fontSize: 16, fontWeight: 600 }}
              value={cals}
              onChange={(e) => setCals(Number(e.target.value))}
            />
          </div>

          {/* Quick Splits Presets */}
          <div>
            <label className="mt-field-label" style={{ marginBottom: 8 }}>
              Quick-Split Presets (Calculates Macros automatically)
            </label>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8 }}>
              <button className="mt-btn mt-btn--ghost" style={{ justifyContent: 'center' }} onClick={() => handleApplyPreset('maintenance')}>
                Maintain
              </button>
              <button className="mt-btn mt-btn--ghost" style={{ justifyContent: 'center' }} onClick={() => handleApplyPreset('loss')}>
                Loss (High P)
              </button>
              <button className="mt-btn mt-btn--ghost" style={{ justifyContent: 'center' }} onClick={() => handleApplyPreset('gain')}>
                Gain (High C)
              </button>
            </div>
          </div>

          <hr style={{ border: 'none', borderBottom: '1px dashed var(--border)' }} />

          {/* Granular Macro overrides */}
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12 }}>
            <div>
              <label className="mt-field-label">Protein (g)</label>
              <input type="number" className="mt-field" value={pG} onChange={(e) => setPG(Number(e.target.value))} />
            </div>
            <div>
              <label className="mt-field-label">Carbs (g)</label>
              <input type="number" className="mt-field" value={cG} onChange={(e) => setCG(Number(e.target.value))} />
            </div>
            <div>
              <label className="mt-field-label">Fat (g)</label>
              <input type="number" className="mt-field" value={fG} onChange={(e) => setFG(Number(e.target.value))} />
            </div>
          </div>

          {/* Math validation strip */}
          <div
            style={{
              fontSize: 11,
              color: 'var(--ink-muted)',
              background: 'var(--bg-inset)',
              padding: '8px 12px',
              borderRadius: 'var(--r-xs)',
              display: 'flex',
              justifyContent: 'space-between',
            }}
          >
            <span>Parsed splits sum:</span>
            <span className="num" style={{ fontWeight: 600 }}>
              {pG * 4 + cG * 4 + fG * 9} kcal
            </span>
          </div>

          {/* Foot Controls */}
          <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 12, marginTop: 8 }}>
            <button className="mt-btn mt-btn--ghost" onClick={onClose}>
              Cancel
            </button>
            <button className="mt-btn mt-btn--primary" disabled={isSaving} onClick={handleSave}>
              {isSaving ? 'Saving...' : 'Activate Goals'}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

// --- Quick Meal Selector Overlay ---
interface AddMealModalProps {
  recipes: any[];
  dateStr: string;
  mealType: MealType;
  onClose: () => void;
  onConfirm: (recipeId: string, servings: number) => void;
}

function AddMealModal({ recipes, dateStr, mealType, onClose, onConfirm }: AddMealModalProps) {
  const [sel, setSel] = useState('');
  const [sv, setSv] = useState(1);

  function handleConfirm() {
    if (!sel) return;
    onConfirm(sel, sv);
  }

  return (
    <div
      style={{
        position: 'fixed',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        background: 'rgba(0,0,0,0.4)',
        backdropFilter: 'blur(4px)',
        display: 'grid',
        placeItems: 'center',
        zIndex: 1000,
      }}
    >
      <div className="mt-card" style={{ width: '100%', maxWidth: 400, boxShadow: 'var(--shadow-lg)' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
          <span style={{ fontSize: 16, fontWeight: 600 }}>
            Schedule {mealType} on {formatNiceDate(dateStr)}
          </span>
          <button onClick={onClose} style={{ color: 'var(--ink-muted)' }}>
            <Icon name="x" size={18} />
          </button>
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div>
            <label className="mt-field-label">Select Recipe</label>
            <select className="mt-field" value={sel} onChange={(e) => setSel(e.target.value)}>
              <option value="">-- Choose from Collection --</option>
              {recipes.map((r) => (
                <option key={r._id} value={r._id}>
                  {r.name} ({Math.round(r.perServingNutrition.calories)} kcal/svc)
                </option>
              ))}
            </select>
          </div>

          <div>
            <label className="mt-field-label">Servings</label>
            <input
              type="number"
              className="mt-field"
              step="0.5"
              min="0.5"
              value={sv}
              onChange={(e) => setSv(Number(e.target.value))}
            />
          </div>

          <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 12, marginTop: 8 }}>
            <button className="mt-btn mt-btn--ghost" onClick={onClose}>
              Cancel
            </button>
            <button className="mt-btn mt-btn--primary" disabled={!sel} onClick={handleConfirm}>
              Add to Plan
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
