// chrome.jsx — shared page shell for the editorial pages (Nav, Footer, Reveal, WRAP)
// Uses window globals from brand.jsx: BRAND, serif, sans, mono, LogoMark, Eyebrow

const { useEffect: useEffectC, useRef: useRefC, useState: useStateC } = React;

const WRAP = { maxWidth: 1180, margin: "0 auto", padding: "0 56px", width: "100%", boxSizing: "border-box" };

/* gentle scroll-reveal (visible by default for print / capture robustness) */
function Reveal({ children, delay = 0, y = 24, style = {} }) {
  const ref = useRefC(null);
  const [shown, setShown] = useStateC(true);
  useEffectC(() => {
    const el = ref.current;
    if (!el || !("IntersectionObserver" in window)) return;
    const rect = el.getBoundingClientRect();
    if (rect.top < window.innerHeight * 0.9) return;
    setShown(false);
    const io = new IntersectionObserver((es) => {
      es.forEach((e) => { if (e.isIntersecting) { setShown(true); io.unobserve(el); } });
    }, { threshold: 0.12, rootMargin: "0px 0px -6% 0px" });
    io.observe(el);
    return () => io.disconnect();
  }, []);
  return (
    <div ref={ref} style={{
      opacity: shown ? 1 : 0,
      transform: shown ? "none" : `translateY(${y}px)`,
      transition: `opacity .8s cubic-bezier(.2,.7,.3,1) ${delay}ms, transform .8s cubic-bezier(.2,.7,.3,1) ${delay}ms`,
      ...style,
    }}>{children}</div>
  );
}

const NAV_LINKS = [
  { label: "Home", href: "/" },
  { label: "Plans", href: "/plans" },
  { label: "Why Millets", href: "/why-millets" },
  { label: "How It Works", href: "/how-it-works" },
  { label: "Our Story", href: "/about" },
];

const PLAN_DROPDOWN_ITEMS = [
  { label: "Blood Pressure", href: "/plans/blood-pressure" },
  { label: "Diabetic-Friendly", href: "/plans/diabetic-friendly" },
  { label: "Fatty Liver", href: "/plans/fatty-liver" },
  { label: "Hormonal Balance", href: "/plans/hormonal-balance" },
  { label: "Weight Loss", href: "/plans/weight-loss" },
  { label: "30-Day Millet Diet", href: "/plans/millet-diet" },
];

function PlansDropdown({ active }) {
  const [hover, setHover] = useStateC(false);
  const timeout = useRefC(null);
  const show = () => { clearTimeout(timeout.current); setHover(true); };
  const hide = () => { timeout.current = setTimeout(() => setHover(false), 150); };
  return (
    <div style={{ position: "relative", display: "flex", alignItems: "center" }} onMouseEnter={show} onMouseLeave={hide}>
      <a href="/plans" style={{ fontSize: 13.5, textDecoration: "none", color: active ? BRAND.forest : BRAND.body, fontWeight: active ? 600 : 400, borderBottom: active ? `1.5px solid ${BRAND.gold}` : "none", paddingBottom: 3, whiteSpace: "nowrap", display: "inline-flex", alignItems: "center", gap: 4 }}>
        Plans <span style={{ fontSize: 9, opacity: 0.5, transition: "transform .2s", transform: hover ? "rotate(180deg)" : "none" }}>▾</span>
      </a>
      {hover && (
        <div style={{ position: "absolute", top: "100%", left: "50%", transform: "translateX(-50%)", paddingTop: 10, zIndex: 100 }}>
          <div style={{ background: "#fff", border: `1px solid ${BRAND.creamD}`, borderRadius: 14, boxShadow: "0 12px 40px rgba(27,58,45,.12)", padding: "8px 0", minWidth: 210 }}>
            {PLAN_DROPDOWN_ITEMS.map((p) => (
              <a key={p.label} href={p.href} style={{ display: "block", padding: "10px 20px", fontSize: 13.5, color: BRAND.forest, textDecoration: "none", fontWeight: 500, whiteSpace: "nowrap", transition: "background .15s" }} onMouseEnter={(e) => e.currentTarget.style.background = BRAND.sage} onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}>
                {p.label}
              </a>
            ))}
            <div style={{ height: 1, background: BRAND.creamD, margin: "6px 0" }} />
            <a href="/plans" style={{ display: "block", padding: "10px 20px", fontSize: 12.5, color: BRAND.goldD, textDecoration: "none", fontWeight: 600, whiteSpace: "nowrap" }} onMouseEnter={(e) => e.currentTarget.style.background = BRAND.sage} onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}>
              View all plans →
            </a>
          </div>
        </div>
      )}
    </div>
  );
}

function SiteNav({ active = "Plans" }) {
  const [open, setOpen] = useStateC(false);
  useEffectC(() => {
    document.body.style.overflow = open ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [open]);
  return (
    <React.Fragment>
      <header style={{ position: "sticky", top: 0, zIndex: 200, background: "rgba(249,246,240,.86)", backdropFilter: "blur(10px)", borderBottom: `1px solid ${BRAND.creamD}` }}>
        <div className="mf-nav-wrap" style={{ ...WRAP, display: "flex", alignItems: "center", justifyContent: "space-between", height: 76 }}>
          <a href="/" style={{ display: "flex", alignItems: "center", gap: 12, textDecoration: "none" }}>
            <LogoMark size={38} />
            <span style={{ fontFamily: serif, fontWeight: 700, fontSize: 20, color: BRAND.forest }}>Millets<span style={{ color: BRAND.greenMed }}>Fit</span></span>
          </a>
          <nav className="mf-nav-desktop" style={{ display: "flex", gap: 34 }}>
            {NAV_LINKS.map((l) => (
              l.label === "Plans"
                ? <PlansDropdown key="Plans" active={active === "Plans"} />
                : <a key={l.label} href={l.href} style={{ fontSize: 13.5, textDecoration: "none", color: l.label === active ? BRAND.forest : BRAND.body, fontWeight: l.label === active ? 600 : 400, borderBottom: l.label === active ? `1.5px solid ${BRAND.gold}` : "none", paddingBottom: 3, whiteSpace: "nowrap" }}>{l.label}</a>
            ))}
          </nav>
          <div className="mf-nav-actions" style={{ display: "flex", alignItems: "center", gap: 22 }}>
            <span className="mf-nav-account" style={{ fontSize: 13.5, color: BRAND.body }}>Account</span>
            <CartNavLink active={active === "Cart"} />
            <button className="mf-nav-burger" onClick={() => setOpen(true)} aria-label="Open menu" style={{ display: "none", cursor: "pointer", border: `1px solid ${BRAND.creamD}`, background: "#fff", width: 42, height: 42, borderRadius: 10, padding: 0, alignItems: "center", justifyContent: "center" }}>
              <svg width="18" height="14" viewBox="0 0 18 14" fill="none" stroke={BRAND.forest} strokeWidth="2" strokeLinecap="round">
                <path d="M1 1h16M1 7h16M1 13h16" />
              </svg>
            </button>
          </div>
        </div>
      </header>
      <MobileDrawer open={open} active={active} onClose={() => setOpen(false)} />
    </React.Fragment>
  );
}

function MobileDrawer({ open, active, onClose }) {
  return (
    <div style={{ position: "fixed", inset: 0, zIndex: 9999, pointerEvents: open ? "auto" : "none" }}>
      <div onClick={onClose} style={{ position: "absolute", inset: 0, background: "rgba(27,58,45,.55)", opacity: open ? 1 : 0, transition: "opacity .3s ease" }} />
      <aside style={{ position: "absolute", top: 0, right: 0, bottom: 0, width: "82%", maxWidth: 340, background: BRAND.cream, transform: open ? "translateX(0)" : "translateX(100%)", transition: "transform .35s cubic-bezier(.2,.7,.3,1)", display: "flex", flexDirection: "column", boxShadow: "0 0 60px rgba(27,58,45,.2)" }}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "18px 22px", borderBottom: `1px solid ${BRAND.creamD}` }}>
          <span style={{ fontFamily: mono, fontSize: 10.5, letterSpacing: ".12em", textTransform: "uppercase", color: BRAND.goldD }}>Menu</span>
          <button onClick={onClose} aria-label="Close menu" style={{ cursor: "pointer", border: "none", background: "transparent", color: BRAND.forest, fontSize: 24, lineHeight: 1, padding: 4 }}>×</button>
        </div>
        <nav style={{ display: "flex", flexDirection: "column", padding: "16px 22px 8px" }}>
          {NAV_LINKS.map((l) => (
            <a key={l.label} href={l.href} onClick={onClose} style={{ display: "flex", alignItems: "center", justifyContent: "space-between", fontFamily: serif, fontSize: 22, fontWeight: l.label === active ? 700 : 500, color: l.label === active ? BRAND.forest : BRAND.ink, padding: "16px 0", borderBottom: `1px solid ${BRAND.creamD}`, textDecoration: "none" }}>
              {l.label}
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ opacity: 0.5 }}><path d="M9 6l6 6-6 6" /></svg>
            </a>
          ))}
          <a href="/cart" onClick={onClose} style={{ display: "flex", alignItems: "center", justifyContent: "space-between", fontFamily: serif, fontSize: 22, fontWeight: 500, color: BRAND.forest, padding: "16px 0", textDecoration: "none" }}>
            Your cart
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ opacity: 0.5 }}><path d="M9 6l6 6-6 6" /></svg>
          </a>
        </nav>
        <div style={{ marginTop: "auto", padding: "22px", borderTop: `1px solid ${BRAND.creamD}` }}>
          <a href="/plans" onClick={onClose} style={{ display: "block", textAlign: "center", background: BRAND.forest, color: "#fff", padding: "16px 24px", borderRadius: 999, textDecoration: "none", fontWeight: 600, fontSize: 14.5, marginBottom: 12 }}>Explore plans →</a>
          <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12, color: BRAND.body }}>
            <span>Account</span>
            <span>Talk to us · WhatsApp</span>
          </div>
        </div>
      </aside>
    </div>
  );
}

function CartNavLink({ active }) {
  const [n, setN] = useStateC(0);
  useEffectC(() => {
    const sync = () => setN((window.CartAPI && window.CartAPI.count()) || 0);
    sync();
    window.addEventListener("milletsfit:cart-updated", sync);
    window.addEventListener("storage", sync);
    return () => {
      window.removeEventListener("milletsfit:cart-updated", sync);
      window.removeEventListener("storage", sync);
    };
  }, []);
  return (
    <a href="/cart" style={{ display: "inline-flex", alignItems: "center", gap: 8, fontSize: 13, fontWeight: 600, color: BRAND.forest, borderBottom: `1.5px solid ${BRAND.gold}`, paddingBottom: 2, whiteSpace: "nowrap", textDecoration: "none" }}>
      <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ marginBottom: 1 }}>
        <path d="M3 4h2l2.4 12.3a2 2 0 0 0 2 1.7h8.2a2 2 0 0 0 2-1.6L21 8H6" />
        <circle cx="10" cy="21" r="1.2" />
        <circle cx="18" cy="21" r="1.2" />
      </svg>
      <span>Cart</span>
      <span style={{ display: "inline-flex", alignItems: "center", justifyContent: "center", minWidth: 20, height: 20, padding: "0 6px", borderRadius: 999, background: n > 0 ? BRAND.forest : "transparent", color: n > 0 ? "#fff" : BRAND.body, fontSize: 11, fontWeight: 700, border: n > 0 ? "none" : `1px solid ${BRAND.creamD}`, transition: "all .2s" }}>{n}</span>
    </a>
  );
}

function FootCol({ title, links }) {
  return (
    <div>
      <div style={{ fontFamily: sans, fontSize: 11, fontWeight: 700, letterSpacing: ".18em", textTransform: "uppercase", color: BRAND.gold, marginBottom: 14 }}>{title}</div>
      <ul style={{ listStyle: "none", margin: 0, padding: 0, display: "flex", flexDirection: "column", gap: 10 }}>
        {links.map((l) => <li key={l.label} style={{ fontSize: 13.5 }}><a href={l.href} style={{ color: "rgba(255,255,255,.7)", textDecoration: "none" }}>{l.label}</a></li>)}
      </ul>
    </div>
  );
}

function ContactItem({ icon, label, value, href }) {
  const valueEl = href
    ? <a href={href} style={{ color: "#fff", textDecoration: "none", fontSize: 15.5, fontFamily: serif, fontWeight: 600, lineHeight: 1.35, whiteSpace: "nowrap" }}>{value}</a>
    : <span style={{ color: "#fff", fontSize: 15.5, fontFamily: serif, fontWeight: 600, lineHeight: 1.35 }}>{value}</span>;
  return (
    <div style={{ display: "flex", gap: 16, alignItems: "flex-start" }}>
      <div style={{ flexShrink: 0, width: 42, height: 42, borderRadius: "50%", display: "flex", alignItems: "center", justifyContent: "center", background: "rgba(255,255,255,.06)", border: "1px solid rgba(255,255,255,.16)", color: BRAND.gold }}>
        {icon}
      </div>
      <div>
        <div style={{ fontFamily: sans, fontSize: 10.5, fontWeight: 700, letterSpacing: ".18em", textTransform: "uppercase", color: BRAND.gold, marginBottom: 5 }}>{label}</div>
        {valueEl}
      </div>
    </div>
  );
}

function ContactBand() {
  return (
    <div className="mf-contact-band" style={{ display: "grid", gridTemplateColumns: "minmax(220px,.8fr) 1.2fr", gap: 48, alignItems: "center", paddingBottom: 44, borderBottom: "1px solid rgba(255,255,255,.12)" }}>
      <div>
        <div style={{ fontFamily: sans, fontSize: 11, fontWeight: 700, letterSpacing: ".22em", textTransform: "uppercase", color: BRAND.gold, marginBottom: 14 }}>Get in touch</div>
        <h2 style={{ fontFamily: serif, fontWeight: 700, fontSize: 38, color: "#fff", margin: 0, letterSpacing: "-.015em", lineHeight: 1.05 }}>Contact Us</h2>
        <p style={{ fontSize: 14, lineHeight: 1.7, color: "rgba(255,255,255,.68)", margin: "14px 0 0", maxWidth: 280 }}>Questions about a plan or your delivery? We're here to help, every day.</p>
      </div>
      <div className="mf-contact-items" style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 32 }}>
        <ContactItem
          label="Visit"
          value={<span>Nooraniyah Bldg<br />Office 2F, Dubai</span>}
          icon={<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M20 10c0 6-8 12-8 12s-8-6-8-12a8 8 0 0 1 16 0Z" /><circle cx="12" cy="10" r="3" /></svg>}
        />
        <ContactItem
          label="Call"
          value="+971 55 417 7677"
          href="tel:+971554177677"
          icon={<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.8 19.8 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.8 19.8 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13.96.36 1.9.7 2.81a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45c.91.34 1.85.57 2.81.7A2 2 0 0 1 22 16.92Z" /></svg>}
        />
        <ContactItem
          label="Email"
          value="support@milletsfit.com"
          href="mailto:support@milletsfit.com"
          icon={<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="5" width="18" height="14" rx="2" /><path d="m3 7 9 6 9-6" /></svg>}
        />
      </div>
    </div>
  );
}

function SiteFooter() {
  return (
    <footer style={{ background: BRAND.forest, color: "#fff" }}>
      <div style={{ ...WRAP, padding: "56px 56px 32px" }}>
        <ContactBand />
        <div style={{ display: "flex", justifyContent: "space-between", flexWrap: "wrap", gap: 32, padding: "40px 0 36px", borderBottom: "1px solid rgba(255,255,255,.12)" }}>
          <div style={{ maxWidth: 300 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 11, marginBottom: 14 }}>
              <LogoMark size={36} ring={BRAND.softGreen} />
              <span style={{ fontFamily: serif, fontWeight: 700, fontSize: 19 }}>Millets<span style={{ color: BRAND.softGreen }}>Fit</span></span>
            </div>
            <p style={{ fontSize: 13.5, lineHeight: 1.7, color: "rgba(255,255,255,.68)", margin: 0 }}>Ancient grains. Modern nutrition. Delivered fresh across the UAE.</p>
          </div>
          <div style={{ display: "flex", gap: 64, flexWrap: "wrap" }}>
            <FootCol title="Plans" links={[
              { label: "Blood Pressure", href: "/plans/blood-pressure" },
              { label: "Diabetic-Friendly", href: "/plans/diabetic-friendly" },
              { label: "Fatty Liver", href: "/plans/fatty-liver" },
              { label: "Hormonal Balance", href: "/plans/hormonal-balance" },
              { label: "Weight Loss", href: "/plans/weight-loss" },
            ]} />
            <FootCol title="Explore" links={[
              { label: "Why Millets", href: "/why-millets" },
              { label: "How It Works", href: "/how-it-works" },
              { label: "Our Story", href: "/about" },
              { label: "Plans", href: "/plans" },
            ]} />
          </div>
        </div>
        <div style={{ paddingTop: 22, display: "flex", justifyContent: "space-between", flexWrap: "wrap", gap: 14, alignItems: "center" }}>
          <span style={{ fontSize: 12.5, color: "rgba(255,255,255,.5)" }}>© {new Date().getFullYear()} MilletsFit · Empowered Millets. All rights reserved.</span>
          <span style={{ display: "inline-flex", alignItems: "center", gap: 14, fontSize: 12.5, color: "rgba(255,255,255,.5)" }}>
            <a href="#" style={{ color: "rgba(255,255,255,.72)", textDecoration: "none" }}>Privacy</a>
            <span aria-hidden="true">·</span>
            <a href="/terms" style={{ color: "#fff", fontWeight: 600, textDecoration: "none", borderBottom: `1.5px solid ${BRAND.gold}`, paddingBottom: 2 }}>Terms &amp; Conditions</a>
          </span>
        </div>
      </div>
    </footer>
  );
}

/* reusable closing CTA (cream) */
function SiteCTA({ eyebrow = "Begin your journey", title = "Eat right. The rest follows.", body = "Choose a condition-specific millet plan, crafted by experts and delivered fresh across the Emirates." }) {
  return (
    <section style={{ ...WRAP, padding: "96px 56px", textAlign: "center" }}>
      <Reveal>
        <Eyebrow style={{ color: BRAND.goldD }}>{eyebrow}</Eyebrow>
        <h2 style={{ fontFamily: serif, fontWeight: 700, fontSize: 50, color: BRAND.forest, margin: "16px 0 18px", letterSpacing: "-.015em", textWrap: "balance" }}>{title}</h2>
        <p style={{ fontSize: 16.5, color: BRAND.body, maxWidth: 540, margin: "0 auto 36px", lineHeight: 1.7 }}>{body}</p>
        <div style={{ display: "inline-flex", gap: 16, flexWrap: "wrap", justifyContent: "center" }}>
          <a href="/plans" style={{ display: "inline-flex", alignItems: "center", gap: 10, background: BRAND.forest, color: "#fff", fontFamily: sans, fontSize: 15, fontWeight: 600, padding: "16px 32px", borderRadius: 999, textDecoration: "none" }}>Explore the six plans →</a>
          <a href="https://wa.me/971554177677" target="_blank" rel="noopener noreferrer" style={{ display: "inline-flex", alignItems: "center", color: BRAND.forest, fontFamily: sans, fontSize: 15, fontWeight: 600, padding: "16px 8px", textDecoration: "none", borderBottom: `1.5px solid ${BRAND.gold}` }}>Talk to us on WhatsApp</a>
        </div>
      </Reveal>
    </section>
  );
}

Object.assign(window, { WRAP, Reveal, SiteNav, SiteFooter, SiteCTA });
