// plandetail.jsx — MilletsFit single plan (product) page, Editorial Calm style
// Uses globals: BRAND, serif, sans, mono, Ph, Eyebrow, WRAP, Reveal, SiteNav, SiteFooter,
//               PLANS, getPlan, MealExplorer, FAQ

const { useState: useStateD, useEffect: useEffectD, useRef: useRefD } = React;

const DEFAULT_DURATIONS = [10, 20, 30];
const aed = (n) => `AED ${n.toLocaleString()}`;
// A plan's meals-per-day badge — most plans are 3 meals; a plan whose menu
// includes a snack (e.g. the Trial Meal Plan) shows 4.
const mealsPerDay = (plan) => (plan.days && plan.days[0] && plan.days[0].snack ? 4 : 3);

/* ── check bullet ── */
function Check() {
  return (
    <span style={{ flexShrink: 0, width: 18, height: 18, borderRadius: "50%", background: BRAND.sage, color: BRAND.greenMed, display: "inline-flex", alignItems: "center", justifyContent: "center", marginTop: 1 }}>
      <svg width="11" height="11" viewBox="0 0 24 24" fill="none"><path d="M5 12.5l4.5 4.5L19 7" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" /></svg>
    </span>
  );
}

/* ── image gallery ── */
function Gallery({ plan }) {
  const imgs = [plan.img, ...(plan.gallery || [])].filter(Boolean);
  const captions = ["plated meal", "the spread", "fresh ingredients", "daily delivery"];
  const [sel, setSel] = useStateD(0);
  const cur = imgs[sel];
  return (
    <div>
      <div style={{ padding: 12, background: "#fff", boxShadow: "0 24px 60px rgba(27,58,45,.12)" }}>
        <div style={{ position: "relative", height: 472, overflow: "hidden", background: "#fff" }}>
          <PImg src={cur} label={`${plan.slug.replace(/-/g, " ")} · ${captions[sel] || "meal"}`} tone={plan.tone} dark={plan.tone === "dark"} fit="contain" position="center" style={{ width: "100%", height: "100%" }} />
          <span style={{ position: "absolute", top: 14, left: 14, fontSize: 10.5, fontWeight: 700, letterSpacing: ".08em", textTransform: "uppercase", color: "#fff", background: plan.accent, padding: "6px 13px", borderRadius: 999, whiteSpace: "nowrap" }}>{plan.category}</span>
        </div>
      </div>
      {imgs.length > 1 && (
        <div className="gallery-thumbs" style={{ display: "flex", gap: 10, marginTop: 12 }}>
          {imgs.map((s, i) => (
            <button key={s} onClick={() => setSel(i)} style={{ width: 68, height: 68, padding: 4, background: "#fff", border: `1.5px solid ${i === sel ? BRAND.gold : BRAND.creamD}`, cursor: "pointer", borderRadius: 6, flexShrink: 0, overflow: "hidden" }}>
              <PImg src={s} label="" tone={plan.tone} dark={plan.tone === "dark"} style={{ width: "100%", height: "100%", objectFit: "cover", borderRadius: 4 }} />
            </button>
          ))}
        </div>
      )}
      <div style={{ fontFamily: mono, fontSize: 11, letterSpacing: ".05em", color: BRAND.goldD, marginTop: 14 }}>{captions[sel] || "meal"}</div>
    </div>
  );
}

/* ── purchase panel ── */
function PurchasePanel({ plan, duration, setDuration, onAdd, added, innerRef }) {
  const price = plan.pricing[`d${duration}`];
  const perDay = Math.round(price / duration);
  const durations = (plan.durations || DEFAULT_DURATIONS).map((d) => ({ d, key: `d${d}` }));
  const longest = durations[durations.length - 1]?.d;
  return (
    <div ref={innerRef} style={{ alignSelf: "start" }}>
      <a href="/plans" style={{ fontFamily: mono, fontSize: 11.5, letterSpacing: ".06em", color: BRAND.body, textDecoration: "none" }}>Plans — {plan.category}</a>
      <h1 style={{ fontFamily: serif, fontWeight: 700, fontSize: 40, lineHeight: 1.08, color: BRAND.forest, margin: "14px 0 12px", letterSpacing: "-.015em" }}>{plan.name}</h1>
      <p style={{ fontSize: 15.5, lineHeight: 1.72, color: BRAND.body, margin: "18px 0 22px", maxWidth: 520 }}>{plan.intro}</p>

      {/* benefits */}
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "11px 18px", marginBottom: 26 }}>
        {plan.benefits.map((b) => (
          <div key={b} style={{ display: "flex", gap: 9, alignItems: "flex-start" }}>
            <Check />
            <span style={{ fontSize: 13.5, lineHeight: 1.45, color: BRAND.ink }}>{b}</span>
          </div>
        ))}
      </div>

      <div style={{ height: 1, background: BRAND.creamD, margin: "0 0 22px" }} />

      {/* duration */}
      <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", marginBottom: 12 }}>
        <span style={{ fontSize: 12.5, fontWeight: 700, letterSpacing: ".04em", color: BRAND.forest, textTransform: "uppercase" }}>Choose your duration</span>
        <span style={{ fontFamily: mono, fontSize: 11, color: BRAND.body }}>{mealsPerDay(plan)} meals / day</span>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: `repeat(${durations.length === 4 ? 2 : durations.length},1fr)`, gap: 10, marginBottom: 22 }}>
        {durations.map(({ d, key }) => {
          const active = d === duration;
          const pr = plan.pricing[key];
          const op = plan.oldPricing && plan.oldPricing[key];
          return (
            <button key={d} onClick={() => setDuration(d)} style={{ position: "relative", cursor: "pointer", textAlign: "left", padding: "14px 15px", borderRadius: 12, border: `1.5px solid ${active ? BRAND.forest : BRAND.creamD}`, background: active ? BRAND.forest : "#fff", transition: "all .2s ease" }}>
              {d === longest && durations.length > 1 && <span style={{ position: "absolute", top: -9, right: 10, fontSize: 9, fontWeight: 700, letterSpacing: ".06em", textTransform: "uppercase", color: BRAND.forest, background: BRAND.gold, padding: "3px 8px", borderRadius: 999 }}>Best value</span>}
              {d === 3 && <span style={{ position: "absolute", top: -9, left: 10, fontSize: 9, fontWeight: 700, letterSpacing: ".06em", textTransform: "uppercase", color: "#fff", background: BRAND.greenMed, padding: "3px 8px", borderRadius: 999 }}>Launch offer</span>}
              <div style={{ fontFamily: serif, fontSize: 20, fontWeight: 700, color: active ? "#fff" : BRAND.forest }}>{d}<span style={{ fontFamily: sans, fontSize: 11, fontWeight: 500 }}> days</span></div>
              {op && <div style={{ fontSize: 11, textDecoration: "line-through", color: active ? "rgba(255,255,255,.55)" : BRAND.body, marginTop: 4 }}>{aed(op)}</div>}
              <div style={{ fontSize: 13, fontWeight: 600, color: active ? BRAND.softGreen : BRAND.greenMed, marginTop: op ? 1 : 4 }}>{aed(pr)}</div>
              <div style={{ fontSize: 10.5, color: active ? "rgba(255,255,255,.6)" : BRAND.body, marginTop: 2 }}>{aed(Math.round(pr / d))}/day</div>
            </button>
          );
        })}
      </div>

      {/* price + cta */}
      <div style={{ display: "flex", alignItems: "center", gap: 22 }}>
        <div style={{ flexShrink: 0 }}>
          <div style={{ fontSize: 11, color: BRAND.body }}>Total · incl. VAT</div>
          {plan.oldPricing && plan.oldPricing[`d${duration}`] && <div style={{ fontSize: 13, textDecoration: "line-through", color: BRAND.body }}>{aed(plan.oldPricing[`d${duration}`])}</div>}
          <div style={{ fontFamily: serif, fontSize: 30, fontWeight: 700, color: BRAND.forest, lineHeight: 1.1 }}>{aed(price)}</div>
          <div style={{ fontSize: 11, color: BRAND.body }}>{aed(perDay)} per day</div>
        </div>
        <button onClick={onAdd} style={{ flex: 1, cursor: "pointer", border: "none", background: added ? BRAND.greenMed : BRAND.forest, color: "#fff", fontFamily: sans, fontSize: 15, fontWeight: 600, padding: "17px 24px", borderRadius: 999, transition: "background .2s ease", display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 10 }}>
          {added ? "✓ Added to cart" : "Add plan to cart"}
        </button>
      </div>

      {/* reassurance */}
      <div style={{ display: "flex", flexDirection: "column", gap: 8, marginTop: 22, paddingTop: 20, borderTop: `1px solid ${BRAND.creamD}` }}>
        {[["Allergies?", "On the checkout page, tell our team if you have any allergies."], ["Storage", "Keep refrigerated at 0–5°C and enjoy fresh."]].map(([t, d]) => (
          <div key={t} style={{ display: "flex", gap: 10, fontSize: 12.5, color: BRAND.body, lineHeight: 1.5 }}>
            <span style={{ fontFamily: mono, fontSize: 10.5, letterSpacing: ".06em", textTransform: "uppercase", color: BRAND.goldD, minWidth: 64, paddingTop: 1 }}>{t}</span>
            <span>{d}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ── the science band ── */
function ScienceBand({ plan }) {
  return (
    <section style={{ background: BRAND.sage }}>
      <div style={{ ...WRAP, padding: "84px 56px" }}>
        <div style={{ display: "grid", gridTemplateColumns: "1.05fr 0.95fr", gap: 64, alignItems: "center" }}>
          <Reveal>
            <div>
              <Eyebrow style={{ color: BRAND.goldD }}>The science</Eyebrow>
              <h2 style={{ fontFamily: serif, fontWeight: 700, fontSize: 38, color: BRAND.forest, margin: "14px 0 18px", letterSpacing: "-.01em", lineHeight: 1.12 }}>{plan.science.heading}</h2>
              <div style={{ width: 48, height: 2, background: BRAND.gold, margin: "0 0 22px" }} />
              <p style={{ fontSize: 16, lineHeight: 1.78, color: BRAND.body, margin: "0 0 30px", maxWidth: 500 }}>{plan.science.body}</p>
              <div style={{ display: "flex", gap: 0 }}>
                {plan.science.stats.map(([n, l], i) => (
                  <div key={l} style={{ paddingRight: 26, marginRight: 26, borderRight: i < 2 ? `1px solid ${BRAND.sageD}` : "none" }}>
                    <div style={{ fontFamily: serif, fontSize: 28, fontWeight: 700, color: BRAND.forest, lineHeight: 1 }}>{n}</div>
                    <div style={{ fontSize: 12, color: BRAND.body, marginTop: 6, maxWidth: 130 }}>{l}</div>
                  </div>
                ))}
              </div>
            </div>
          </Reveal>
          <Reveal delay={90} y={32}>
            <div style={{ position: "relative" }}>
              <div style={{ padding: 10, background: "#fff", boxShadow: "0 24px 60px rgba(27,58,45,.14)" }}>
                <PImg src={plan.sciImg} label="ingredient still life" tone={plan.tone} dark={plan.tone === "dark"} style={{ width: "100%", height: 380 }} />
              </div>
            </div>
          </Reveal>
        </div>
      </div>
    </section>
  );
}

/* ── convenience / how it arrives (forest band) ── */
function Convenience() {
  const steps = [
    ["Cooked fresh each morning", "Whole, single-origin millets prepared daily by our chefs — no preservatives."],
    ["Delivered to your door", "Daily or in 3-day packs across Dubai, Abu Dhabi, Sharjah & Ajman, in eco-friendly insulated packaging."],
    ["Keep it fresh", "Store your meals refrigerated at 0–5°C and enjoy them fresh through the day for the best taste."],
  ];
  return (
    <section style={{ background: BRAND.forest, position: "relative", overflow: "hidden" }}>
      <div style={{ position: "absolute", inset: 0, opacity: 0.5, background: "radial-gradient(circle at 14% 28%, rgba(115,173,146,.12), transparent 45%)" }} />
      <div style={{ ...WRAP, padding: "84px 56px", position: "relative" }}>
        <Reveal>
          <div style={{ textAlign: "center", marginBottom: 52 }}>
            <Eyebrow style={{ color: BRAND.gold }}>How it arrives</Eyebrow>
            <h2 style={{ fontFamily: serif, fontWeight: 700, fontSize: 38, color: "#fff", margin: "12px 0 0" }}>Fresh from our kitchen, every day</h2>
          </div>
        </Reveal>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 36 }}>
          {steps.map(([t, d], i) => (
            <Reveal key={t} delay={i * 90}>
              <div>
                <div style={{ fontFamily: serif, fontSize: 30, fontWeight: 700, color: BRAND.gold, marginBottom: 14 }}>0{i + 1}</div>
                <h3 style={{ fontFamily: serif, fontSize: 21, fontWeight: 700, color: "#fff", margin: "0 0 10px" }}>{t}</h3>
                <p style={{ fontSize: 14, lineHeight: 1.7, color: "rgba(255,255,255,.74)", margin: 0 }}>{d}</p>
              </div>
            </Reveal>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ── related plans ── */
function Related({ plan }) {
  const others = PLANS.filter((p) => p.slug !== plan.slug && !p.hidden).slice(0, 3);
  return (
    <section style={{ background: BRAND.cream }}>
      <div style={{ ...WRAP, padding: "84px 56px" }}>
        <Reveal>
          <div style={{ marginBottom: 32 }}>
            <Eyebrow style={{ color: BRAND.goldD }}>More plans</Eyebrow>
            <h2 style={{ fontFamily: serif, fontWeight: 700, fontSize: 34, color: BRAND.forest, margin: "12px 0 0" }}>You might also like</h2>
          </div>
        </Reveal>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 26 }}>
          {others.map((p, i) => (
            <Reveal key={p.slug} delay={i * 80}>
              <a href={PLAN_HREF[p.slug] || `/plans/product?plan=${p.slug}`} style={{ display: "block", textDecoration: "none", background: "#fff", border: `1px solid ${BRAND.creamD}` }}>
                <div style={{ padding: 9 }}>
                  <PImg src={p.img} label={`${p.slug.replace(/-/g, " ")} dish`} tone={p.tone} dark={p.tone === "dark"} fit="contain" position="center" style={{ width: "100%", height: 150, background: "#fff" }} />
                </div>
                <div style={{ padding: "6px 18px 20px" }}>
                  <div style={{ fontFamily: mono, fontSize: 10, letterSpacing: ".06em", textTransform: "uppercase", color: BRAND.goldD, marginBottom: 7 }}>{p.category}</div>
                  <h3 style={{ fontFamily: serif, fontSize: 18.5, fontWeight: 700, color: BRAND.forest, margin: "0 0 10px", lineHeight: 1.2 }}>{p.name}</h3>
                  <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
                    <span style={{ fontSize: 13, color: BRAND.body }}>From <strong style={{ color: BRAND.forest }}>{aed(p.pricing.d10)}</strong></span>
                    <span style={{ fontSize: 13, fontWeight: 600, color: BRAND.forest, borderBottom: `1.5px solid ${BRAND.gold}`, paddingBottom: 1 }}>View →</span>
                  </div>
                </div>
              </a>
            </Reveal>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ── reviews ── */
function StarRow({ rating, size = 15 }) {
  return (
    <span style={{ display: "inline-flex", gap: 2 }}>
      {[1, 2, 3, 4, 5].map((n) => (
        <svg key={n} width={size} height={size} viewBox="0 0 24 24" fill={n <= rating ? BRAND.gold : "none"} stroke={n <= rating ? BRAND.gold : BRAND.creamD} strokeWidth="1.5">
          <path d="M12 2.5l2.9 6.4 6.9.7-5.2 4.7 1.5 6.9L12 17.6l-6.1 3.6 1.5-6.9-5.2-4.7 6.9-.7z" strokeLinejoin="round" />
        </svg>
      ))}
    </span>
  );
}

function PlanReviews({ plan }) {
  const [data, setData] = useStateD(null);
  useEffectD(() => {
    fetch(`/api/reviews?action=list&slug=${plan.slug}`)
      .then((r) => (r.ok ? r.json() : null))
      .then(setData)
      .catch(() => setData(null));
  }, [plan.slug]);

  if (!data || data.count === 0) return null;

  return (
    <section style={{ background: "#fff" }}>
      <div style={{ maxWidth: 860, margin: "0 auto", padding: "80px 56px", width: "100%", boxSizing: "border-box" }}>
        <Reveal>
          <div style={{ textAlign: "center", marginBottom: 36 }}>
            <Eyebrow style={{ color: BRAND.goldD }}>Customer reviews</Eyebrow>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 12, margin: "14px 0 0" }}>
              <StarRow rating={Math.round(data.average)} size={20} />
              <span style={{ fontFamily: serif, fontSize: 22, fontWeight: 700, color: BRAND.forest }}>{data.average.toFixed(1)}</span>
              <span style={{ fontSize: 13.5, color: BRAND.body }}>· {data.count} review{data.count === 1 ? "" : "s"}</span>
            </div>
          </div>
        </Reveal>
        <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
          {data.reviews.map((r, i) => (
            <Reveal key={i} delay={i * 40}>
              <div style={{ border: `1px solid ${BRAND.creamD}`, borderRadius: 14, padding: "20px 24px" }}>
                <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12, marginBottom: r.text ? 10 : 0 }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                    <StarRow rating={r.rating} />
                    <strong style={{ fontFamily: sans, fontSize: 13.5, color: BRAND.forest }}>{r.name}</strong>
                  </div>
                  <span style={{ fontSize: 11.5, color: BRAND.body, whiteSpace: "nowrap" }}>{r.date}</span>
                </div>
                {r.text && <p style={{ fontSize: 14, lineHeight: 1.65, color: BRAND.body, margin: 0 }}>{r.text}</p>}
              </div>
            </Reveal>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ── sticky purchase bar ── */
function StickyBar({ plan, duration, show, onAdd, added }) {
  const price = plan.pricing[`d${duration}`];
  return (
    <div className="mf-sticky-bar" style={{ position: "fixed", left: 0, right: 0, bottom: 0, zIndex: 300, transform: show ? "translateY(0)" : "translateY(120%)", transition: "transform .35s cubic-bezier(.2,.7,.3,1)", background: "rgba(249,246,240,.94)", backdropFilter: "blur(12px)", borderTop: `1px solid ${BRAND.creamD}`, boxShadow: "0 -8px 30px rgba(27,58,45,.08)" }}>
      <div className="mf-sticky-inner" style={{ ...WRAP, display: "flex", alignItems: "center", justifyContent: "space-between", gap: 20, padding: "14px 56px" }}>
        <div className="mf-sticky-meta" style={{ display: "flex", alignItems: "center", gap: 16, minWidth: 0 }}>
          <div style={{ flexShrink: 0 }}><PImg src={plan.img} label="" tone={plan.tone} dark={plan.tone === "dark"} style={{ width: 46, height: 46 }} /></div>
          <div style={{ minWidth: 0 }}>
            <div className="mf-sticky-name" style={{ fontFamily: serif, fontSize: 17, fontWeight: 700, color: BRAND.forest, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{plan.name}</div>
            <div style={{ fontSize: 12, color: BRAND.body }}>{duration}-day · {aed(Math.round(price / duration))}/day</div>
          </div>
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 14, flexShrink: 0 }}>
          <div className="mf-sticky-total" style={{ textAlign: "right" }}>
            <div style={{ fontSize: 10.5, color: BRAND.body }}>Total</div>
            <div style={{ fontFamily: serif, fontSize: 20, fontWeight: 700, color: BRAND.forest, lineHeight: 1 }}>{aed(price)}</div>
          </div>
          <button onClick={onAdd} style={{ cursor: "pointer", border: "none", background: added ? BRAND.greenMed : BRAND.forest, color: "#fff", fontFamily: sans, fontSize: 14, fontWeight: 600, padding: "12px 22px", borderRadius: 999, whiteSpace: "nowrap" }}>{added ? "✓ Added" : "Add to cart"}</button>
        </div>
      </div>
    </div>
  );
}

/* ── page ── */
function PlanDetailPage() {
  const params = new URLSearchParams(window.location.search);
  const plan = getPlan(window.__PLAN_SLUG) || getPlan(params.get("plan")) || PLANS[0];
  const [duration, setDuration] = useStateD(() => (plan.durations && plan.durations[0]) || 10);
  const [added, setAdded] = useStateD(false);
  const [showBar, setShowBar] = useStateD(false);
  const panelRef = useRefD(null);

  const handleAdd = () => {
    try { window.CartAPI && window.CartAPI.add(plan.slug, duration, 1); } catch {}
    setAdded(true);
    clearTimeout(window.__addT);
    window.__addT = setTimeout(() => setAdded(false), 2400);
  };

  useEffectD(() => {
    const el = panelRef.current; if (!el || !("IntersectionObserver" in window)) return;
    const io = new IntersectionObserver(([e]) => setShowBar(!e.isIntersecting && e.boundingClientRect.top < 0), { rootMargin: "-100px 0px 0px 0px" });
    io.observe(el); return () => io.disconnect();
  }, []);

  return (
    <div style={{ background: BRAND.cream, fontFamily: sans, color: BRAND.ink, minHeight: "100vh" }}>
      <SiteNav active="Plans" />
      <section style={{ ...WRAP, paddingTop: 56, paddingBottom: 72 }}>
        <div style={{ display: "grid", gridTemplateColumns: "0.92fr 1.08fr", gap: 64, alignItems: "start" }}>
          <Reveal><Gallery plan={plan} /></Reveal>
          <Reveal delay={80}>
            <PurchasePanel plan={plan} duration={duration} setDuration={setDuration} onAdd={handleAdd} added={added} innerRef={panelRef} />
          </Reveal>
        </div>
      </section>
      <ScienceBand plan={plan} />
      <MealExplorer plan={plan} duration={duration} />
      <Convenience />
      <FAQ plan={plan} />
      <PlanReviews plan={plan} />
      <section style={{ ...WRAP, paddingTop: 4, paddingBottom: 8 }}>
        <Reveal><PlanDisclaimer style={{ marginTop: 0 }} /></Reveal>
      </section>
      <Related plan={plan} />
      <SiteFooter />
      <StickyBar plan={plan} duration={duration} show={showBar} onAdd={handleAdd} added={added} />
    </div>
  );
}

Object.assign(window, { PlanDetailPage });
