/* eslint-disable */
// Meal Planner — 3 tabs: Recipes, This Week, Pantry

const SEED_RECIPES = [
  { id: 1, name: "Tropical Curry Bowl",   servings: 4, ingredients: "1 cup rice, 1 lb chicken, 1 can coconut milk, 2 tbsp curry paste", instructions: "Cook rice. Sauté chicken. Add coconut milk + curry paste. Simmer 15 min.", notes: "Add lime at the end." },
  { id: 2, name: "Saturday Pancakes",     servings: 6, ingredients: "2 cups flour, 2 eggs, 1.5 cups milk, 1 tsp baking powder, 2 tbsp sugar", instructions: "Whisk dry, whisk wet, combine. Cook on medium heat.", notes: null },
  { id: 3, name: "Roasted Veggie Tacos",  servings: 4, ingredients: "1 sweet potato, 1 bell pepper, 1 red onion, 8 tortillas, cumin, lime", instructions: "Roast veggies at 425°F for 25 min. Warm tortillas. Assemble.", notes: "Cilantro-lime sauce works." },
];

const SEED_PLAN = {
  Monday:    { dinner: "Tropical Curry Bowl" },
  Tuesday:   { dinner: "Leftovers" },
  Wednesday: { dinner: "Roasted Veggie Tacos" },
  Thursday:  {},
  Friday:    { dinner: "Pizza night" },
  Saturday:  { breakfast: "Saturday Pancakes", dinner: "Eat out" },
  Sunday:    {},
};

const SEED_PANTRY = [
  { id: 1, item: "Coconut milk", quantity: 2, unit: "cans",  purchased: false },
  { id: 2, item: "Eggs",         quantity: 12, unit: "pcs",   purchased: false },
  { id: 3, item: "Tortillas",    quantity: 1,  unit: "pack",  purchased: true  },
  { id: 4, item: "Sweet potato", quantity: 3,  unit: "pcs",   purchased: false },
  { id: 5, item: "Curry paste",  quantity: 1,  unit: "jar",   purchased: true  },
];

const RecipeCard = ({ recipe, onDelete, onEdit }) => (
  <Card>
    <h3 className="text-xl font-bold text-gray-900 dark:text-white mb-2">{recipe.name}</h3>
    <p className="text-sm text-gray-600 dark:text-gray-400 mb-3">Serves {recipe.servings}</p>
    <p className="text-sm font-semibold text-gray-700 dark:text-gray-300 mb-1">Ingredients</p>
    <p className="text-sm text-gray-600 dark:text-gray-400 mb-3">{recipe.ingredients}</p>
    <p className="text-sm font-semibold text-gray-700 dark:text-gray-300 mb-1">Instructions</p>
    <p className="text-sm text-gray-600 dark:text-gray-400 mb-3">{recipe.instructions}</p>
    {recipe.notes && <p className="text-sm italic text-gray-600 dark:text-gray-400 mb-3">Notes: {recipe.notes}</p>}
    <div className="flex gap-3 text-sm">
      <button onClick={() => onEdit(recipe)} className="text-blue-600 dark:text-blue-400 hover:underline">Edit</button>
      <button onClick={() => onDelete(recipe.id)} className="text-red-600 dark:text-red-400 hover:underline">Delete</button>
    </div>
  </Card>
);

const PlanCard = ({ day, meals }) => (
  <Card>
    <h3 className="text-lg font-bold text-gray-900 dark:text-white mb-3">{day}</h3>
    {["breakfast", "lunch", "dinner"].map((type) => (
      <div className="mb-2" key={type}>
        <p className="text-sm font-semibold text-gray-700 dark:text-gray-300 capitalize">{type}</p>
        <p className="text-sm text-gray-600 dark:text-gray-400">{meals[type] || "Not planned"}</p>
      </div>
    ))}
  </Card>
);

const PantryCard = ({ item, onToggle, onDelete, onEdit }) => (
  <Card className={item.purchased ? "opacity-75" : ""}>
    <div className="flex justify-between items-start">
      <div>
        <h3 className="text-lg font-bold text-gray-900 dark:text-white">{item.item}</h3>
        <p className="text-sm text-gray-600 dark:text-gray-400 mb-3">{item.quantity} {item.unit}</p>
      </div>
      <Pill tone={item.purchased ? "success" : "info"}>
        {item.purchased ? "✓ Stocked" : "Need to buy"}
      </Pill>
    </div>
    <div className="flex gap-3 mt-2 text-sm">
      <button onClick={() => onToggle(item.id)} className="text-green-600 dark:text-green-400 hover:underline">
        {item.purchased ? "Mark out" : "Mark Stocked"}
      </button>
      <button onClick={() => onEdit(item)} className="text-blue-600 dark:text-blue-400 hover:underline">Edit</button>
      <button onClick={() => onDelete(item.id)} className="text-red-600 dark:text-red-400 hover:underline">Delete</button>
    </div>
  </Card>
);

const MealPlannerScreen = () => {
  const [tab, setTab] = React.useState("recipes");
  const [recipes, setRecipes] = React.useState(() => {
    const stored = Storage.getArray('familyhub_recipes', 'recipes');
    return stored;
  });
  const [pantry, setPantry] = React.useState(() => {
    const stored = Storage.getArray('familyhub_pantry', 'items');
    return stored;
  });
  const [mealPlan, setMealPlan] = React.useState(() => {
    return Storage.get('familyhub_mealplan') || {};
  });
  const [showAddRecipe, setShowAddRecipe] = React.useState(false);
  const [showAddPantry, setShowAddPantry] = React.useState(false);
  const [recipeDraft, setRecipeDraft] = React.useState({ name: "", servings: "", ingredients: "", instructions: "", notes: "" });
  const [pantryDraft, setPantryDraft] = React.useState({ item: "", quantity: "", unit: "" });

  const saveRecipes = (r) => { setRecipes(r); Storage.set('familyhub_recipes', { recipes: r }); };
  const savePantry = (newPantry) => { setPantry(newPantry); Storage.set('familyhub_pantry', { items: newPantry }); };
  const saveMealPlan = (p) => { setMealPlan(p); Storage.set('familyhub_mealplan', p); };

  const [mealModal, setMealModal] = React.useState(null);
  const [customMeal, setCustomMeal] = React.useState("");
  const addMealToDay = (date, slot) => {
    setMealModal({ date, slot });
    setCustomMeal("");
  };
  const confirmMeal = (mealName) => {
    if (!mealName || !mealName.trim() || !mealModal) return;
    const updated = { ...mealPlan, [mealModal.date]: { ...(mealPlan[mealModal.date] || {}), [mealModal.slot]: mealName.trim() } };
    saveMealPlan(updated);
    setMealModal(null);
    setCustomMeal("");
  };
  const deleteMealFromDay = (date, slot) => {
    const dayPlan = { ...(mealPlan[date] || {}) };
    delete dayPlan[slot];
    const updated = { ...mealPlan, [date]: dayPlan };
    saveMealPlan(updated);
  };

  const addRecipe = () => {
    if (!recipeDraft.name.trim()) return;
    saveRecipes([...recipes, { id: Date.now(), ...recipeDraft, servings: parseInt(recipeDraft.servings) || 4 }]);
    setRecipeDraft({ name: "", servings: "", ingredients: "", instructions: "", notes: "" });
    setShowAddRecipe(false);
  };
  const deleteRecipe = (id) => { if (!window.confirm("Are you sure you want to delete this recipe?")) return; saveRecipes(recipes.filter(r => r.id !== id)); };
  const [editRecipe, setEditRecipe] = React.useState(null);
  const startEditRecipe = (r) => { setEditRecipe({ ...r }); };
  const saveEditRecipe = () => {
    if (!editRecipe.name.trim()) return;
    saveRecipes(recipes.map(r => r.id === editRecipe.id ? { ...r, name: editRecipe.name.trim(), servings: parseInt(editRecipe.servings) || 4, ingredients: editRecipe.ingredients, instructions: editRecipe.instructions, notes: editRecipe.notes } : r));
    setEditRecipe(null);
  };
  const [editPantryItem, setEditPantryItem] = React.useState(null);
  const startEditPantry = (p) => { setEditPantryItem({ ...p, quantity: String(p.quantity || '') }); };
  const saveEditPantry = () => {
    if (!editPantryItem.item.trim()) return;
    savePantry(pantry.map(p => p.id === editPantryItem.id ? { ...p, item: editPantryItem.item.trim(), quantity: parseInt(editPantryItem.quantity) || 1, unit: editPantryItem.unit } : p));
    setEditPantryItem(null);
  };
  const addPantryItem = () => {
    if (!pantryDraft.item.trim()) return;
    savePantry([...pantry, { id: Date.now(), ...pantryDraft, quantity: parseInt(pantryDraft.quantity) || 1, purchased: false }]);
    setPantryDraft({ item: "", quantity: "", unit: "" });
    setShowAddPantry(false);
  };
  const togglePantry = (id) => {
    const updated = pantry.map((i) => (i.id === id ? { ...i, purchased: !i.purchased } : i));
    savePantry(updated);
  };
  const deletePantryItem = (id) => { if (!window.confirm("Are you sure you want to delete this pantry item?")) return; savePantry(pantry.filter(p => p.id !== id)); };
  const needBuy = pantry.filter(p => !p.purchased).length;

  const Tab = ({ id, label }) => (
    <button
      onClick={() => setTab(id)}
      className={
        "px-4 py-2 border-b-2 transition-colors " +
        (tab === id
          ? "border-blue-500 text-blue-600 dark:text-blue-400 font-semibold"
          : "border-transparent text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200")
      }
    >
      {label}
    </button>
  );

  return (
    <section className="p-4 md:p-6">
      <div className="flex justify-between items-center mb-6">
        <h2 className="text-3xl font-bold text-gray-900 dark:text-white">Meal Planner</h2>
        <BtnPrimary onClick={() => setShowAddRecipe(true)}>+ Add Recipe</BtnPrimary>
      </div>

      {showAddRecipe && (
        <Modal title="Add Recipe" onClose={() => setShowAddRecipe(false)} onSubmit={addRecipe} submitLabel="Add Recipe">
          <div className="space-y-4">
            <div><Label required>Recipe Name</Label><Input placeholder="e.g. Tropical Curry Bowl" value={recipeDraft.name} onChange={e => setRecipeDraft({...recipeDraft, name: e.target.value})} autoFocus /></div>
            <div><Label>Servings</Label><Input type="number" placeholder="4" value={recipeDraft.servings} onChange={e => setRecipeDraft({...recipeDraft, servings: e.target.value})} /></div>
            <div><Label>Ingredients</Label><Textarea rows={3} placeholder="List ingredients..." value={recipeDraft.ingredients} onChange={e => setRecipeDraft({...recipeDraft, ingredients: e.target.value})} /></div>
            <div><Label>Instructions</Label><Textarea rows={3} placeholder="Steps..." value={recipeDraft.instructions} onChange={e => setRecipeDraft({...recipeDraft, instructions: e.target.value})} /></div>
            <div><Label>Notes</Label><Input placeholder="Optional notes" value={recipeDraft.notes} onChange={e => setRecipeDraft({...recipeDraft, notes: e.target.value})} /></div>
          </div>
        </Modal>
      )}
      {showAddPantry && (
        <Modal title="Add Pantry Item" onClose={() => setShowAddPantry(false)} onSubmit={addPantryItem} submitLabel="Add Item">
          <div className="space-y-4">
            <div><Label required>Item</Label><Input placeholder="e.g. Coconut milk" value={pantryDraft.item} onChange={e => setPantryDraft({...pantryDraft, item: e.target.value})} autoFocus /></div>
            <div><Label>Quantity</Label><Input type="number" placeholder="1" value={pantryDraft.quantity} onChange={e => setPantryDraft({...pantryDraft, quantity: e.target.value})} /></div>
            <div><Label>Unit</Label><Input placeholder="e.g. cans, pcs, pack" value={pantryDraft.unit} onChange={e => setPantryDraft({...pantryDraft, unit: e.target.value})} /></div>
          </div>
        </Modal>
      )}

      {mealModal && (
        <Modal title={"Plan " + mealModal.slot + " — " + mealModal.date} onClose={() => setMealModal(null)} submitLabel="Add Custom" onSubmit={() => confirmMeal(customMeal)}>
          <div className="space-y-4">
            {recipes.length > 0 && (
              <div>
                <Label>Pick from your recipes</Label>
                <div className="space-y-2 max-h-48 overflow-y-auto">
                  {recipes.map(r => (
                    <button key={r.id} onClick={() => confirmMeal(r.name)}
                      className="w-full text-left px-4 py-3 rounded-lg border border-gray-200 dark:border-gray-600 hover:bg-blue-50 dark:hover:bg-blue-900/30 transition-colors">
                      <span className="font-medium text-gray-900 dark:text-white">{r.name}</span>
                      {r.servings && <span className="text-xs text-gray-500 dark:text-gray-400 ml-2">Serves {r.servings}</span>}
                    </button>
                  ))}
                </div>
              </div>
            )}
            <div>
              <Label>Or type a custom meal</Label>
              <Input placeholder="e.g. Pizza night, Leftovers..." value={customMeal} onChange={e => setCustomMeal(e.target.value)} autoFocus={recipes.length === 0} />
            </div>
          </div>
        </Modal>
      )}

      <div className="flex gap-2 sm:gap-4 mb-6 border-b border-gray-200 dark:border-gray-700">
        <Tab id="recipes" label={`Recipes (${recipes.length})`} />
        <Tab id="plan"    label="This Week" />
        <Tab id="pantry"  label={`Pantry (${needBuy})`} />
      </div>

      {tab === "recipes" && (
        <div className="grid md:grid-cols-2 gap-6">
          {recipes.length === 0 && <p className="col-span-2 text-center text-gray-500 dark:text-gray-400 py-12">No recipes yet. Add one to get started!</p>}
          {recipes.map((r) => <RecipeCard key={r.id} recipe={r} onDelete={deleteRecipe} onEdit={startEditRecipe} />)}
        </div>
      )}
      {tab === "plan" && (
        <React.Fragment>
          <div className="flex justify-between items-center mb-4">
            <span className="text-sm text-gray-500 dark:text-gray-400 font-medium">This Week</span>
          </div>
          <Card className="!p-4">
            <WeekCalendar plan={mealPlan} onAddMeal={addMealToDay} onDeleteMeal={deleteMealFromDay} />
          </Card>
          <p className="text-xs text-gray-400 dark:text-gray-500 mt-2">Click + to add a meal · click an existing meal to remove it</p>
        </React.Fragment>
      )}
      {tab === "pantry" && (
        <React.Fragment>
          <BtnPrimary className="mb-4" onClick={() => setShowAddPantry(true)}>+ Add Item to Pantry</BtnPrimary>
          <div className="grid md:grid-cols-2 gap-4">
            {pantry.map((p) => <PantryCard key={p.id} item={p} onToggle={togglePantry} onDelete={deletePantryItem} onEdit={startEditPantry} />)}
          </div>
        </React.Fragment>
      )}

      {editRecipe && (
        <Modal title="Edit Recipe" onClose={() => setEditRecipe(null)} onSubmit={saveEditRecipe} submitLabel="Save">
          <div className="space-y-4">
            <div><Label required>Recipe Name</Label><Input value={editRecipe.name} onChange={e => setEditRecipe({...editRecipe, name: e.target.value})} autoFocus /></div>
            <div><Label>Servings</Label><Input type="number" value={editRecipe.servings} onChange={e => setEditRecipe({...editRecipe, servings: e.target.value})} /></div>
            <div><Label>Ingredients</Label><Textarea rows={3} value={editRecipe.ingredients || ''} onChange={e => setEditRecipe({...editRecipe, ingredients: e.target.value})} /></div>
            <div><Label>Instructions</Label><Textarea rows={3} value={editRecipe.instructions || ''} onChange={e => setEditRecipe({...editRecipe, instructions: e.target.value})} /></div>
            <div><Label>Notes</Label><Input value={editRecipe.notes || ''} onChange={e => setEditRecipe({...editRecipe, notes: e.target.value})} /></div>
          </div>
        </Modal>
      )}
      {editPantryItem && (
        <Modal title="Edit Pantry Item" onClose={() => setEditPantryItem(null)} onSubmit={saveEditPantry} submitLabel="Save">
          <div className="space-y-4">
            <div><Label required>Item</Label><Input value={editPantryItem.item} onChange={e => setEditPantryItem({...editPantryItem, item: e.target.value})} autoFocus /></div>
            <div><Label>Quantity</Label><Input type="number" value={editPantryItem.quantity} onChange={e => setEditPantryItem({...editPantryItem, quantity: e.target.value})} /></div>
            <div><Label>Unit</Label><Input value={editPantryItem.unit || ''} onChange={e => setEditPantryItem({...editPantryItem, unit: e.target.value})} /></div>
          </div>
        </Modal>
      )}
    </section>
  );
};

window.MealPlannerScreen = MealPlannerScreen;
