/* Meal plan — Day view (default) + Week view with drag-drop, regenerate */
const { useState, useEffect, useMemo } = React;
const { Ring, Eyebrow, MacroBar, Placeholder, Icon, DataRow, NumberField } = window;

const SLOTS = [
  { id: "breakfast", time: "7:30",  label: "Breakfast" },
  { id: "snack1",    time: "10:00", label: "Snack" },
  { id: "lunch",     time: "12:30", label: "Lunch" },
  { id: "snack2",    time: "15:30", label: "Snack" },
  { id: "dinner",    time: "19:00", label: "Dinner" },
];

function MealPlan({ profile, plan, setPlan, weekPlan, setWeekPlan }) {
  const [view, setView] = useState("day"); // 'day' | 'week'
  const [recipeMeal, setRecipeMeal] = useState(null);
  const [regenCount, setRegenCount] = useState({});
  const [customOpen, setCustomOpen] = useState(false);
  const [customMacros, setCustomMacros] = useState({ kcal: 500, p: 35, c: 50, f: 12 });

  return (
    <div className="col fade-in" style={{ gap: 28 }}>
      <div className="between" style={{ alignItems: "end" }}>
        <div>
          <Eyebrow>Meal plan • Filipino-focused • Low sodium/fat</Eyebrow>
          <h1 className="h-hero" style={{ marginTop: 12, fontSize: 56 }}>
            {view === "day" ? <>Today's plan.</> : <>This week.</>}
          </h1>
        </div>
        <div className="row" style={{ gap: 10 }}>
          <div className="seg">
            <button className={view === "day"  ? "on" : ""} onClick={() => setView("day")}>Day</button>
            <button className={view === "week" ? "on" : ""} onClick={() => setView("week")}>Week</button>
          </div>
          <button className="btn btn-ghost btn-sm"><Icon name="plus" size={14} /> Add meal</button>
        </div>
      </div>

      {view === "day"
        ? <DayView profile={profile} plan={plan} setPlan={setPlan}
                   onRecipe={setRecipeMeal}
                   regenCount={regenCount} setRegenCount={setRegenCount}
                   openCustom={() => setCustomOpen(true)} />
        : <WeekView weekPlan={weekPlan} setWeekPlan={setWeekPlan} />}

      {recipeMeal && <RecipeModal meal={recipeMeal} onClose={() => setRecipeMeal(null)} />}
      {customOpen && <CustomMacrosModal
        macros={customMacros} setMacros={setCustomMacros}
        onClose={() => setCustomOpen(false)} />}
    </div>
  );
}

/* ============== DAY VIEW ============== */
function DayView({ profile, plan, setPlan, onRecipe, regenCount, setRegenCount, openCustom }) {
  const target = profile.target;
  const totals = useMemo(() => {
    let kcal = 0, p = 0, c = 0, f = 0;
    Object.values(plan).forEach(id => {
      const m = window.MOCK.MEAL_LIBRARY.find(x => x.id === id);
      if (m) { kcal += m.kcal; p += m.p; c += m.c; f += m.f; }
    });
    return { kcal, p, c, f };
  }, [plan]);

  function regenerate(slot) {
    const count = (regenCount[slot] || 0) + 1;
    if (count > 2) {
      openCustom();
      return;
    }
    setRegenCount(rc => ({ ...rc, [slot]: count }));
    const currentMeal = window.MOCK.MEAL_LIBRARY.find(m => m.id === plan[slot]);
    const pool = window.MOCK.MEAL_LIBRARY.filter(m =>
      m.slot === currentMeal.slot &&
      m.id !== currentMeal.id &&
      Math.abs(m.kcal - currentMeal.kcal) < 120
    );
    const next = pool[Math.floor(Math.random() * pool.length)] || currentMeal;
    setPlan(p => ({ ...p, [slot]: next.id }));
  }

  function onSwap(slotA, slotB) {
    setPlan(p => ({ ...p, [slotA]: p[slotB], [slotB]: p[slotA] }));
  }

  return (
    <>
      {/* Totals strip */}
      <div className="card" style={{ display: "flex", gap: 32, padding: 24, alignItems: "center" }}>
        <Ring value={totals.kcal} max={target} size={120} stroke={12}>
          <div className="mono" style={{ fontSize: 22, fontWeight: 700 }}>{totals.kcal}</div>
          <div className="muted mono" style={{ fontSize: 10 }}>of {target}</div>
        </Ring>
        <div style={{ flex: 1 }}>
          <div className="row" style={{ gap: 24, alignItems: "baseline" }}>
            <div>
              <div className="eyebrow">Day total</div>
              <div className="h-data" style={{ fontSize: 32 }}>{totals.kcal.toLocaleString()}<span className="muted" style={{ fontSize: 14, fontWeight: 400 }}> kcal</span></div>
            </div>
            <div className="muted mono" style={{ fontSize: 13 }}>
              {totals.kcal < target ? `${target - totals.kcal} left` : `${totals.kcal - target} over`}
            </div>
          </div>
          <div style={{ marginTop: 16 }}>
            <MacroBar p={totals.p} c={totals.c} f={totals.f} target={profile.macros} />
          </div>
        </div>
      </div>

      {/* Meal cards */}
      <div className="col" style={{ gap: 14 }}>
        {SLOTS.map(slot => {
          const meal = window.MOCK.MEAL_LIBRARY.find(m => m.id === plan[slot.id]);
          const regens = regenCount[slot.id] || 0;
          return (
            <DraggableMealRow key={slot.id}
              slot={slot} meal={meal} regens={regens}
              onRegen={() => regenerate(slot.id)}
              onRecipe={() => onRecipe(meal)}
              onSwap={onSwap}
            />
          );
        })}
        <button className="card" style={{
          padding: 18, border: "1.5px dashed var(--line)",
          display: "flex", alignItems: "center", justifyContent: "center", gap: 8,
          color: "var(--fg-muted)", cursor: "pointer",
        }}>
          <Icon name="plus" size={16} /> Add another meal or snack
        </button>
      </div>
    </>
  );
}

function DraggableMealRow({ slot, meal, regens, onRegen, onRecipe, onSwap }) {
  const [dragging, setDragging] = useState(false);
  const [hover, setHover] = useState(false);
  if (!meal) return null;

  return (
    <div className={"card meal-row " + (dragging ? "dragging" : "") + (hover ? " drag-over" : "")}
      draggable
      onDragStart={e => { e.dataTransfer.setData("text/plain", slot.id); setDragging(true); }}
      onDragEnd={() => setDragging(false)}
      onDragOver={e => { e.preventDefault(); setHover(true); }}
      onDragLeave={() => setHover(false)}
      onDrop={e => {
        e.preventDefault(); setHover(false);
        const from = e.dataTransfer.getData("text/plain");
        if (from && from !== slot.id) onSwap(from, slot.id);
      }}
      style={{ padding: 18 }}>
      <div className="col" style={{ alignItems: "center", gap: 4, color: "var(--fg-muted)", padding: "0 4px" }}>
        <Icon name="drag" size={16} />
        <div className="mono" style={{ fontSize: 11 }}>{slot.time}</div>
      </div>
      <div className="col" style={{ gap: 6 }}>
        <div className="row" style={{ gap: 8 }}>
          <span className="eyebrow">{slot.label}</span>
          {meal.tags.map(t => <span key={t} className="chip" style={{ fontSize: 10, padding: "2px 8px" }}>{t}</span>)}
        </div>
        <div style={{ fontWeight: 700, fontSize: 18 }}>{meal.name}</div>
        <div className="muted" style={{ fontSize: 13 }}>{meal.note}</div>
        <div className="row" style={{ gap: 16, marginTop: 4 }}>
          <span className="mono" style={{ fontSize: 13, fontWeight: 600 }}>
            <Icon name="flame" size={12} color="var(--accent)" /> {meal.kcal} kcal
          </span>
          <span className="mono muted" style={{ fontSize: 12 }}>
            <span className="tag-dot" style={{ background: "var(--m-protein)" }} />{meal.p}P
            <span className="tag-dot" style={{ background: "var(--m-carbs)", marginLeft: 10 }} />{meal.c}C
            <span className="tag-dot" style={{ background: "var(--m-fat)", marginLeft: 10 }} />{meal.f}F
          </span>
        </div>
      </div>
      <div className="col" style={{ gap: 8, alignItems: "stretch", minWidth: 160 }}>
        <button className="btn btn-primary btn-sm" onClick={onRecipe}>
          Suggested recipe
        </button>
        <button className="btn btn-ghost btn-sm" onClick={onRegen}>
          <Icon name="refresh" size={12} /> Regenerate
          <span className="mono" style={{ fontSize: 10, opacity: 0.7, marginLeft: 4 }}>
            {regens >= 2 ? "→ custom" : `${regens}/2`}
          </span>
        </button>
      </div>
    </div>
  );
}

/* ============== WEEK VIEW ============== */
function WeekView({ weekPlan, setWeekPlan }) {
  const [drag, setDrag] = useState(null); // { day, slot }
  const [overCell, setOverCell] = useState(null);

  function swap(a, b) {
    setWeekPlan(wp => {
      const next = wp.map(d => ({ ...d }));
      const va = next[a.dayIdx][a.slot];
      next[a.dayIdx][a.slot] = next[b.dayIdx][b.slot];
      next[b.dayIdx][b.slot] = va;
      return next;
    });
  }

  return (
    <div className="card flush" style={{ overflowX: "auto", WebkitOverflowScrolling: "touch" }}>
      <div className="between" style={{ padding: "16px 20px", borderBottom: "1px solid var(--line)" }}>
        <div className="row" style={{ gap: 12 }}>
          <Eyebrow>Week of Mar 10 — Mar 16</Eyebrow>
          <span className="muted" style={{ fontSize: 12 }}>Drag any meal to swap</span>
        </div>
        <div className="row" style={{ gap: 8 }}>
          <button className="btn btn-ghost btn-sm">‹ Prev</button>
          <button className="btn btn-ghost btn-sm">Next ›</button>
        </div>
      </div>

      <div className="week-grid">
        {/* Header row */}
        <div style={{ padding: 12, borderBottom: "1px solid var(--line)", borderRight: "1px solid var(--line)" }} />
        {weekPlan.map((d, i) => (
          <div key={d.day} style={{
            padding: 14, borderBottom: "1px solid var(--line)",
            borderRight: i < 6 ? "1px solid var(--line)" : "none",
            background: d.day === "Thu" ? "var(--accent-soft)" : "var(--bg)",
          }}>
            <div className="eyebrow">{d.day}</div>
            <div className="mono" style={{ fontSize: 12, marginTop: 4, color: "var(--fg)" }}>{10 + i}</div>
          </div>
        ))}

        {/* Slot rows */}
        {SLOTS.map(slot => (
          <React.Fragment key={slot.id}>
            <div style={{
              padding: 12,
              borderBottom: "1px solid var(--line-soft)",
              borderRight: "1px solid var(--line)",
              background: "var(--bg-soft)",
            }}>
              <div className="eyebrow">{slot.label}</div>
              <div className="mono muted" style={{ fontSize: 11, marginTop: 2 }}>{slot.time}</div>
            </div>
            {weekPlan.map((d, dayIdx) => {
              const meal = window.MOCK.MEAL_LIBRARY.find(m => m.id === d[slot.id]);
              const isOver = overCell && overCell.dayIdx === dayIdx && overCell.slot === slot.id;
              return (
                <div key={d.day + slot.id}
                  draggable
                  onDragStart={e => { e.dataTransfer.setData("text/plain", "ok"); setDrag({ dayIdx, slot: slot.id }); }}
                  onDragEnd={() => setDrag(null)}
                  onDragOver={e => { e.preventDefault(); setOverCell({ dayIdx, slot: slot.id }); }}
                  onDragLeave={() => setOverCell(null)}
                  onDrop={() => {
                    if (drag) swap(drag, { dayIdx, slot: slot.id });
                    setOverCell(null);
                  }}
                  className={isOver ? "drag-over" : ""}
                  style={{
                    padding: 10,
                    borderBottom: "1px solid var(--line-soft)",
                    borderRight: dayIdx < 6 ? "1px solid var(--line-soft)" : "none",
                    cursor: "grab",
                    minHeight: 90,
                    background: drag && drag.dayIdx === dayIdx && drag.slot === slot.id ? "var(--bg-soft)" : "transparent",
                    transition: "background .12s",
                  }}>
                  <div style={{ fontSize: 11, fontWeight: 600, lineHeight: 1.2, marginBottom: 4 }}>{meal?.name}</div>
                  <div className="mono muted" style={{ fontSize: 10 }}>{meal?.kcal} kcal</div>
                  <div className="row" style={{ gap: 4, marginTop: 4 }}>
                    <span className="tag-dot" style={{ background: "var(--m-protein)" }} />
                    <span className="mono" style={{ fontSize: 9, color: "var(--fg-muted)" }}>{meal?.p}</span>
                    <span className="tag-dot" style={{ background: "var(--m-carbs)", marginLeft: 4 }} />
                    <span className="mono" style={{ fontSize: 9, color: "var(--fg-muted)" }}>{meal?.c}</span>
                    <span className="tag-dot" style={{ background: "var(--m-fat)", marginLeft: 4 }} />
                    <span className="mono" style={{ fontSize: 9, color: "var(--fg-muted)" }}>{meal?.f}</span>
                  </div>
                </div>
              );
            })}
          </React.Fragment>
        ))}
      </div>
    </div>
  );
}

/* ============== RECIPE MODAL ============== */
function RecipeModal({ meal, onClose }) {
  const swaps = window.MOCK.RECIPE_SWAPS.default;
  return (
    <Modal onClose={onClose}>
      <div className="between" style={{ marginBottom: 20 }}>
        <div>
          <Eyebrow>Suggested recipe • Low sodium / low fat</Eyebrow>
          <h2 className="h-card" style={{ marginTop: 8, fontSize: 28 }}>{meal.name}</h2>
        </div>
        <button className="btn-icon btn btn-ghost" onClick={onClose}><Icon name="x" size={16} /></button>
      </div>
      <div className="row" style={{ gap: 16, marginBottom: 24, padding: "20px 24px", background: "var(--bg-soft)", borderRadius: 14 }}>
        <div className="col" style={{ flex: 1, gap: 8, justifyContent: "center" }}>
          <DataRow k="Calories" v={meal.kcal + " kcal"} />
          <DataRow k="Protein"  v={meal.p + " g"} muted />
          <DataRow k="Carbs"    v={meal.c + " g"} muted />
          <DataRow k="Fat"      v={meal.f + " g"} muted />
        </div>
      </div>

      <Eyebrow>Smart swaps</Eyebrow>
      <div className="col" style={{ gap: 8, marginTop: 12 }}>
        {swaps.map((s, i) => (
          <div key={i} className="row" style={{ gap: 12, padding: "10px 14px", background: "var(--bg-soft)", borderRadius: 10 }}>
            <span className="mono muted" style={{ fontSize: 12, width: 24 }}>{String(i + 1).padStart(2, "0")}</span>
            <div className="row" style={{ gap: 12, flex: 1, fontSize: 13 }}>
              <span style={{ textDecoration: "line-through", color: "var(--fg-muted)" }}>{s.from}</span>
              <Icon name="arrow" size={12} color="var(--fg-muted)" />
              <span style={{ fontWeight: 600 }}>{s.to}</span>
            </div>
          </div>
        ))}
      </div>

      <div className="row" style={{ marginTop: 28, gap: 10 }}>
        <button className="btn btn-primary">Save to favorites</button>
        <button className="btn btn-ghost">Print recipe</button>
      </div>
    </Modal>
  );
}

/* ============== CUSTOM MACROS MODAL ============== */
function CustomMacrosModal({ macros, setMacros, onClose }) {
  return (
    <Modal onClose={onClose}>
      <Eyebrow>You've used your 2 regenerates</Eyebrow>
      <h2 className="h-card" style={{ marginTop: 8, fontSize: 28, marginBottom: 8 }}>
        Tell us what you actually want.
      </h2>
      <p className="muted" style={{ fontSize: 14, marginBottom: 24 }}>
        We'll find a meal that hits these macros (±10%). Custom macros count toward your daily budget normally.
      </p>
      <div className="grid-2" style={{ gap: 14 }}>
        <NumberField label="Calories" value={macros.kcal}
          onChange={v => setMacros(m => ({ ...m, kcal: v }))} suffix="kcal" step={10} />
        <NumberField label="Protein" value={macros.p}
          onChange={v => setMacros(m => ({ ...m, p: v }))} suffix="g" />
        <NumberField label="Carbs" value={macros.c}
          onChange={v => setMacros(m => ({ ...m, c: v }))} suffix="g" />
        <NumberField label="Fat" value={macros.f}
          onChange={v => setMacros(m => ({ ...m, f: v }))} suffix="g" />
      </div>
      <div className="row" style={{ marginTop: 24, gap: 10 }}>
        <button className="btn btn-primary" onClick={onClose}>Find a meal</button>
        <button className="btn btn-ghost" onClick={onClose}>Cancel</button>
      </div>
    </Modal>
  );
}

/* ============== MODAL ============== */
function Modal({ onClose, children }) {
  useEffect(() => {
    const onKey = e => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [onClose]);
  return (
    <div onClick={onClose} style={{
      position: "fixed", inset: 0,
      background: "rgba(0,0,0,0.4)",
      backdropFilter: "blur(8px)",
      display: "flex", alignItems: "center", justifyContent: "center",
      zIndex: 100,
      animation: "fadeIn 0.2s ease both",
    }}>
      <div onClick={e => e.stopPropagation()}
           className="fade-in"
           style={{
             background: "var(--bg)", borderRadius: "var(--r-xl)",
             padding: 32, maxWidth: 560, width: "92%", maxHeight: "88vh", overflow: "auto",
             border: "1px solid var(--line)",
             boxShadow: "0 30px 80px rgba(0,0,0,0.15)",
           }}>
        {children}
      </div>
    </div>
  );
}

Object.assign(window, { MealPlan });
