// mealplanner.jsx — the day-by-day meal explorer + FAQ accordion for the plan page
// Uses window globals: BRAND, serif, sans, mono, Ph, Eyebrow, WRAP, Reveal

const { useState: useStateM, useEffect: useEffectM } = React;

const MEAL_ORDER = [
  ["breakfast", "Breakfast", "Morning"],
  ["lunch", "Lunch", "Midday"],
  ["dinner", "Dinner", "Evening"],
];

function LockIcon({ size = 12 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" style={{ display: "block" }}>
      <rect x="4" y="10.5" width="16" height="10.5" rx="2.4" stroke="currentColor" strokeWidth="2" />
      <path d="M8 10.5V7a4 4 0 0 1 8 0v3.5" stroke="currentColor" strokeWidth="2" />
    </svg>
  );
}

function MealExplorer({ plan, duration }) {
  const [day, setDay] = useStateM(1);                 // 1-based
  // Full-menu plans (e.g. the Trial Meal Plan) show every day with nothing
  // locked, and only the days matching the customer's chosen duration —
  // there's no bigger plan being "sampled," this IS the whole product.
  const showFullMenu = !!plan.showFullMenu;
  const visibleDayCount = showFullMenu ? Math.min(duration || plan.days.length, plan.days.length) : plan.days.length;
  const unlocked = showFullMenu ? visibleDayCount : 6;  // sample days visible
  const totalDays = showFullMenu ? visibleDayCount : 30;
  const isLocked = !showFullMenu && day > unlocked;
  const data = plan.days[(day - 1) % plan.days.length];
  const tabDays = (showFullMenu ? plan.days.slice(0, visibleDayCount) : plan.days).map((d) => d.day);
  const hasSnack = !!data.snack;
  const mealCols = hasSnack ? [...MEAL_ORDER, ["snack", "Snack", "Anytime"]] : MEAL_ORDER;

  // If the customer switches duration (e.g. 10-day → 3-day) while viewing a
  // day that no longer exists, snap back to Day 1 instead of showing nothing.
  useEffectM(() => {
    if (day > visibleDayCount) setDay(1);
  }, [visibleDayCount]);

  return (
    <section style={{ background: BRAND.cream }}>
      <div style={{ ...WRAP, paddingTop: 88, paddingBottom: 88 }}>
        <Reveal>
          <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", flexWrap: "wrap", gap: 20, marginBottom: 30 }}>
            <div>
              <div style={{ fontFamily: mono, fontSize: 12, letterSpacing: ".08em", color: BRAND.goldD, textTransform: "uppercase", marginBottom: 12 }}>What you'll eat</div>
              <h2 style={{ fontFamily: serif, fontWeight: 700, fontSize: 42, color: BRAND.forest, margin: 0, letterSpacing: "-.015em", whiteSpace: "nowrap" }}>A day on the plan</h2>
            </div>
            <p style={{ fontSize: 14.5, lineHeight: 1.7, color: BRAND.body, margin: 0, maxWidth: 380 }}>
              {showFullMenu
                ? `Freshly-cooked meals every day, rotated across ${plan.millets.length} millet varieties. Every day of your trial is shown below — nothing hidden.`
                : `Three freshly-cooked meals a day, rotated across ${plan.millets.length} millet varieties. Browse a few sample days — your full ${totalDays}-day menu arrives with your order.`}
            </p>
          </div>
        </Reveal>

        {/* day tabs */}
        <Reveal delay={60}>
          <div style={{ display: "flex", gap: 9, flexWrap: "wrap", marginBottom: 26 }}>
            {tabDays.map((d) => {
              const locked = d > unlocked;
              const active = d === day;
              return (
                <button key={d} onClick={() => setDay(d)} style={{
                  display: "inline-flex", alignItems: "center", gap: 7, cursor: "pointer",
                  fontFamily: sans, fontSize: 13.5, fontWeight: 600,
                  padding: "10px 18px", borderRadius: 999,
                  border: `1px solid ${active ? BRAND.forest : BRAND.creamD}`,
                  background: active ? BRAND.forest : "#fff",
                  color: active ? "#fff" : locked ? BRAND.body : BRAND.forest,
                  transition: "all .2s ease", whiteSpace: "nowrap",
                }}>
                  Day {d}
                  {locked && <span style={{ display: "inline-flex", opacity: active ? 0.9 : 0.5 }}><LockIcon size={12} /></span>}
                </button>
              );
            })}
            {(totalDays - tabDays.length) > 0 && (
              <span style={{ display: "inline-flex", alignItems: "center", gap: 8, fontFamily: sans, fontSize: 13, fontWeight: 500, padding: "10px 18px", borderRadius: 999, border: `1px dashed ${BRAND.sageD}`, color: BRAND.body, whiteSpace: "nowrap" }}>
                + {totalDays - tabDays.length} more days <LockIcon size={12} />
              </span>
            )}
          </div>
        </Reveal>

        {/* day card */}
        <Reveal delay={100}>
          <div className="mealcard" style={{ background: "#fff", border: `1px solid ${BRAND.creamD}`, boxShadow: "0 14px 50px rgba(27,58,45,.08)", padding: "28px 32px 32px" }}>
            {/* header — day, millet of the day, meal count */}
            <div className="mf-meal-head" style={{ display: "flex", alignItems: "center", justifyContent: "space-between", flexWrap: "wrap", gap: "12px 18px" }}>
              <div style={{ display: "flex", alignItems: "center", gap: 14, flexWrap: "wrap" }}>
                <h3 style={{ fontFamily: serif, fontSize: 26, fontWeight: 700, color: BRAND.forest, margin: 0, whiteSpace: "nowrap" }}>Day {day}</h3>
                <span style={{ display: "inline-flex", flexDirection: "column", justifyContent: "center", background: BRAND.sage, border: `1px solid ${BRAND.sageD}`, borderRadius: 10, padding: "5px 14px" }}>
                  <span style={{ fontFamily: mono, fontSize: 9, letterSpacing: ".1em", textTransform: "uppercase", color: BRAND.goldD, whiteSpace: "nowrap", lineHeight: 1.3 }}>Millet of the day</span>
                  <span style={{ fontFamily: serif, fontSize: 15, fontWeight: 700, color: BRAND.forest, whiteSpace: "nowrap", lineHeight: 1.15 }}>{data.millet}</span>
                </span>
              </div>
              <span style={{ fontFamily: mono, fontSize: 11.5, color: BRAND.goldD, letterSpacing: ".04em", whiteSpace: "nowrap" }}>{mealCols.length} meals · freshly cooked</span>
            </div>
            <div style={{ width: 44, height: 2, background: BRAND.gold, margin: "14px 0 0" }} />

            {/* meals, one column each — each dish on its own line */}
            <div style={{ position: "relative", marginTop: 24 }}>
              <div className="mf-meal-cols" style={{
                display: "grid", gridTemplateColumns: `repeat(${mealCols.length}, 1fr)`, gap: 1,
                background: BRAND.creamD, border: `1px solid ${BRAND.creamD}`, borderRadius: 10, overflow: "hidden",
                filter: isLocked ? "blur(5px)" : "none", opacity: isLocked ? 0.5 : 1,
                pointerEvents: isLocked ? "none" : "auto", transition: "all .25s ease",
              }}>
                {mealCols.map(([key, label, when]) => {
                  const items = String(data[key] || "").split("·").map((s) => s.trim()).filter(Boolean);
                  return (
                    <div key={key} style={{ background: "#fff", padding: "20px 20px 22px" }}>
                      <div style={{ fontFamily: serif, fontSize: 18, fontWeight: 700, color: BRAND.forest }}>{label}</div>
                      <div style={{ fontFamily: mono, fontSize: 9.5, letterSpacing: ".1em", textTransform: "uppercase", color: BRAND.goldD, margin: "4px 0 14px" }}>{when}</div>
                      <ul style={{ listStyle: "none", margin: 0, padding: 0, display: "flex", flexDirection: "column", gap: 10 }}>
                        {items.map((item, n) => (
                          <li key={n} style={{ display: "grid", gridTemplateColumns: "auto 1fr", gap: 10, fontSize: 13.5, lineHeight: 1.5, color: BRAND.body }}>
                            <span aria-hidden="true" style={{ marginTop: 7, width: 4, height: 4, borderRadius: 999, background: BRAND.gold, flexShrink: 0 }} />
                            <span style={{ textWrap: "pretty" }}>{item}</span>
                          </li>
                        ))}
                      </ul>
                    </div>
                  );
                })}
              </div>

              {isLocked && (
                <div style={{ position: "absolute", inset: 0, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", textAlign: "center", padding: 30 }}>
                  <div style={{ width: 52, height: 52, borderRadius: "50%", background: BRAND.sage, color: BRAND.greenMed, display: "flex", alignItems: "center", justifyContent: "center", marginBottom: 16 }}><LockIcon size={22} /></div>
                  <div style={{ fontFamily: serif, fontSize: 22, fontWeight: 700, color: BRAND.forest, marginBottom: 8 }}>The full {totalDays} days, unlocked on order</div>
                  <p style={{ fontSize: 14, color: BRAND.body, maxWidth: 320, margin: "0 0 18px", lineHeight: 1.6 }}>Days 1–{unlocked} are a free preview. Choose your duration to receive the complete day-by-day menu.</p>
                  <button onClick={() => setDay(1)} style={{ cursor: "pointer", border: `1.5px solid ${BRAND.forest}`, background: "#fff", color: BRAND.forest, fontFamily: sans, fontSize: 13.5, fontWeight: 600, padding: "11px 22px", borderRadius: 999 }}>← Back to the preview</button>
                </div>
              )}
            </div>
          </div>
        </Reveal>

        <Reveal delay={60}>
          <p style={{ fontFamily: mono, fontSize: 11.5, color: BRAND.body, marginTop: 18, letterSpacing: ".02em" }}>
            {showFullMenu
              ? "This is your complete day-by-day menu for the trial — freshly prepared and delivered."
              : "* Sample menu. Your complete plan includes every day's breakfast, lunch and dinner — freshly prepared and delivered."}
          </p>
          <PlanDisclaimer variant="menu" style={{ marginTop: 12 }} />
        </Reveal>
      </div>
    </section>
  );
}

/* ── FAQ accordion ── */
function FAQ({ plan }) {
  const [open, setOpen] = useStateM(0);
  return (
    <section style={{ background: "#fff" }}>
      <div style={{ maxWidth: 860, margin: "0 auto", padding: "92px 56px", width: "100%", boxSizing: "border-box" }}>
        <Reveal>
          <div style={{ textAlign: "center", marginBottom: 40 }}>
            <Eyebrow style={{ color: BRAND.goldD }}>Good to know</Eyebrow>
            <h2 style={{ fontFamily: serif, fontWeight: 700, fontSize: 38, color: BRAND.forest, margin: "12px 0 0", letterSpacing: "-.01em" }}>Questions, answered</h2>
          </div>
        </Reveal>
        <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
          {plan.faqs.map(([q, a], i) => {
            const isOpen = open === i;
            return (
              <Reveal key={i} delay={i * 40}>
                <div style={{ border: `1px solid ${BRAND.creamD}`, background: isOpen ? BRAND.cream : "#fff", borderRadius: 14, overflow: "hidden", transition: "background .2s ease" }}>
                  <button onClick={() => setOpen(isOpen ? -1 : i)} style={{ width: "100%", display: "flex", alignItems: "center", justifyContent: "space-between", gap: 18, padding: "20px 24px", background: "none", border: "none", cursor: "pointer", textAlign: "left" }}>
                    <span style={{ fontFamily: serif, fontSize: 18, fontWeight: 700, color: BRAND.forest }}>{q}</span>
                    <span style={{ flexShrink: 0, width: 26, height: 26, borderRadius: "50%", border: `1.5px solid ${isOpen ? BRAND.forest : BRAND.sageD}`, display: "flex", alignItems: "center", justifyContent: "center", fontSize: 16, color: BRAND.forest, transform: isOpen ? "rotate(45deg)" : "none", transition: "transform .25s ease" }}>+</span>
                  </button>
                  {isOpen && (
                    <div style={{ padding: "0 24px 22px", maxWidth: 680 }}>
                      <p style={{ fontSize: 14.5, lineHeight: 1.72, color: BRAND.body, margin: 0 }}>{a}</p>
                    </div>
                  )}
                </div>
              </Reveal>
            );
          })}
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { MealExplorer, FAQ });
