/* ------------------------------------------------------------------
   Little Healthy Plates — shared components
------------------------------------------------------------------ */

const { useState, useEffect, useRef, useMemo } = React;

/* ----- DATA ----- */
const EBOOKS = [
  {
    id: "picky",
    title: "The No-BS Toddler Table",
    subtitle: "End the dinner battles. Ditch the guilt. Raise a kid who actually eats.",
    author: "Nozima Kudrow",
    blurb: "A real-world playbook for parents of children ages 1–5. The single mindset shift that ends 80% of the fights, why toddlers reject food (and why it's normal), the phrases that work at the table, ten whole-food meals with picky-eater hacks built in, and a 14-day action plan. Not a fancy recipe book. Not a lecture. A no-BS guide rooted in research and real-parent results.",
    price: 9,
    pages: 31,
    format: "PDF",
    badge: "Bestseller",
    accent: "terracotta",
    cover: "cover-picky",
    realCover: "nobs",
    ages: "ages 1–5",
    inside: [
      "The single mindset shift that eliminates 80% of the fights",
      "Why toddlers reject food — and why it's completely normal",
      "Home setup tricks that cut daily mealtime chaos",
      "Phrases that actually help — and ones that backfire",
      "Ten family-friendly meals with picky-eater hacks built in",
      "A clear 14-day action plan to get started",
      "Red flags for when it's more than typical pickiness",
    ],
    chapters: [
      "Introduction — Why Mealtimes Feel Like War",
      "The One Mindset Shift",
      "Why Your Toddler Eats Like This",
      "Set the Stage",
      "The Try Bite & The Power of Exposure",
      "Cook With Them",
      "Words That Work",
      "Ten Toddler-Tested Recipes",
      "When to Worry",
      "Your First Two Weeks",
      "Going Deeper — Recommended Reading",
    ],
  },
  {
    id: "data",
    title: "One in Five",
    subtitle: "What's really making kids sicker — and why it's not your fault",
    author: "Nozima Kudrow",
    blurb: "An honest guide for parents. One in five American children now lives with obesity, and youth-onset type 2 diabetes — a disease so rare in kids it had to be renamed — is showing up in pediatric clinics across the country. This book walks through the research, plainly, with every claim sourced. Not a diet book. Not a guilt trip. A map for the food landscape we're all trying to raise children inside of.",
    price: 14,
    pages: 52,
    format: "PDF",
    badge: "New",
    accent: "sage",
    cover: "cover-data",
    inside: [
      "Plain-English summaries of 50+ peer-reviewed studies",
      "How a once-rare condition became one in five children",
      "What 'ultra-processed' actually means — and what the evidence shows",
      "Why sugary drinks get their own chapter",
      "The neighborhood, marketing, and economics behind it all",
      "Eight gentle steps for real families — no diets, no weigh-ins",
      "An honest 'what we still don't know' chapter",
      "A short glossary and 50+ source references",
    ],
    chapters: [
      "Welcome — How to use this guide",
      "What's Actually Happening — childhood obesity, in numbers",
      "The Disease That Had to Be Renamed — youth type 2 diabetes",
      "Ultra-Processed Foods — what the evidence really shows",
      "Sugary Drinks — and why fruit juice counts too",
      "The World Children Eat Inside — marketing, neighborhoods, economics",
      "The Early Years — how food preferences are formed",
      "What Helps — eight gentle steps for real families",
      "What We Still Don't Know — an honest accounting",
      "If You Read Only This Page · Glossary · References",
    ],
  },
  {
    id: "bundle",
    title: "The Whole Kitchen Bundle",
    subtitle: "Both books, one price",
    blurb: "Get both ebooks together and save. The 'why' and the 'how' — paired.",
    price: 19,
    originalPrice: 23,
    pages: 83,
    format: "PDF",
    badge: "Save $4",
    accent: "butter",
    cover: "cover-bundle",
    inside: [
      "Everything in The No-BS Toddler Table (31 pages)",
      "Everything in One in Five (52 pages)",
    ],
    chapters: [],
  },
];

/* ----- EBOOK COVER PLACEHOLDER ----- */
/* A type-led 'book cover' design — placeholder until real covers arrive.
   Each variant uses different colors but the same composition. */
function EbookCover({ ebook, size = "md" }) {
  // Books with a recreated real cover render their own component
  if (ebook.realCover === "nobs") return <NoBsCover size={size} />;

  const dims = {
    sm: { w: 130, h: 180, t: 14, sub: 8, hand: 18 },
    md: { w: 200, h: 280, t: 22, sub: 10, hand: 26 },
    lg: { w: 280, h: 400, t: 32, sub: 12, hand: 36 },
    xl: { w: 360, h: 500, t: 42, sub: 14, hand: 46 },
  }[size];

  const palettes = {
    "cover-picky": { bg: "#c4633e", panel: "#fdf9ef", ink: "#2a1d12", accent: "#7e8a6a" },
    "cover-data": { bg: "#5e6a4a", panel: "#f7f1e3", ink: "#2a1d12", accent: "#c4633e" },
    "cover-bundle": { bg: "#2a1d12", panel: "#ecb858", ink: "#2a1d12", accent: "#c4633e" },
  };
  const p = palettes[ebook.cover] || palettes["cover-picky"];

  return (
    <div
      className="ebook-cover"
      style={{
        width: dims.w,
        maxWidth: "100%",
        aspectRatio: `${dims.w} / ${dims.h}`,
        height: "auto",
        background: p.bg,
        color: p.panel,
        position: "relative",
        boxShadow:
          "0 1px 0 rgba(255,255,255,0.1) inset, 0 20px 40px -15px rgba(42,29,18,0.35), 0 4px 0 rgba(0,0,0,0.05)",
        display: "flex",
        flexDirection: "column",
        padding: dims.w * 0.08,
        fontFamily: "var(--f-display)",
        overflow: "hidden",
        borderRadius: 2,
      }}
    >
      {/* spine line */}
      <div style={{ position: "absolute", left: 6, top: 0, bottom: 0, width: 1, background: "rgba(255,255,255,0.12)" }} />
      {/* inner border */}
      <div style={{
        position: "absolute", inset: dims.w * 0.05,
        border: `1px solid ${p.panel}`, opacity: 0.35, pointerEvents: "none",
      }} />

      {/* top: small "LHP" */}
      <div style={{
        fontFamily: "var(--f-hand)",
        fontSize: dims.hand * 0.6,
        color: p.panel,
        opacity: 0.85,
        letterSpacing: "0.02em",
      }}>
        Little Healthy Plates
      </div>

      <div style={{ flex: 1, display: "flex", alignItems: "center", justifyContent: "center", flexDirection: "column", textAlign: "center", gap: dims.w * 0.04 }}>
        {/* decorative mark */}
        <svg width={dims.w * 0.18} height={dims.w * 0.18} viewBox="0 0 40 40">
          <circle cx="20" cy="20" r="18" fill="none" stroke={p.accent} strokeWidth="1.5" />
          <path d="M 12 20 Q 20 12 28 20 Q 20 28 12 20" fill={p.accent} opacity="0.7" />
        </svg>

        <div style={{
          fontStyle: "italic",
          fontSize: dims.t,
          lineHeight: 1,
          color: p.panel,
          textWrap: "balance",
          padding: `0 ${dims.w * 0.02}px`,
        }}>
          {ebook.title}
        </div>

        <div style={{
          fontFamily: "var(--f-body)",
          fontSize: dims.sub,
          letterSpacing: "0.15em",
          textTransform: "uppercase",
          color: p.panel,
          opacity: 0.75,
          padding: `0 ${dims.w * 0.04}px`,
          lineHeight: 1.4,
        }}>
          {ebook.subtitle}
        </div>
      </div>

      <div style={{
        fontFamily: "var(--f-hand)",
        fontSize: dims.hand,
        color: p.accent,
        textAlign: "center",
        lineHeight: 1,
      }}>
        {ebook.author ? ebook.author.toLowerCase() : "an ebook"}
      </div>
    </div>
  );
}

/* ----- REAL COVER: The No-BS Toddler Table -----
   Faithful recreation of the author's actual cover, as scalable SVG.
   Source page 612×792. Palette: cream #fbf3de, sage #7a8b5c,
   yellow #f0b435, red #e04a33, ink #1f1b17. */
function NoBsCover({ size = "md" }) {
  const dims = {
    sm: { w: 130, h: 180 },
    md: { w: 200, h: 280 },
    lg: { w: 280, h: 400 },
    xl: { w: 360, h: 500 },
  }[size];

  const CREAM = "#fbf3de", SAGE = "#7a8b5c", YELLOW = "#f0b435", RED = "#e04a33", INK = "#1f1b17";
  const CX = 306;

  // a tiny doodle set drawn around the wordmark, in the cover palette
  const Carrot = ({ x, y, s = 1, fill = YELLOW }) => (
    <g transform={`translate(${x} ${y}) scale(${s})`}>
      <path d="M0 0 L10 26 L-10 26 Z" fill={fill} stroke={INK} strokeWidth="2.4" strokeLinejoin="round" />
      <path d="M0 -2 q-7 -11 -16 -11 M0 -2 q0 -13 0 -15 M0 -2 q7 -11 16 -11" fill="none" stroke={SAGE} strokeWidth="2.6" strokeLinecap="round" />
    </g>
  );
  const Leaf = ({ x, y, s = 1, fill = SAGE }) => (
    <g transform={`translate(${x} ${y}) scale(${s})`}>
      <path d="M0 0 Q16 -14 30 0 Q16 14 0 0 Z" fill={fill} stroke={INK} strokeWidth="2.4" strokeLinejoin="round" />
      <path d="M3 0 H27" stroke={INK} strokeWidth="2" opacity="0.6" />
    </g>
  );
  const Spoon = ({ x, y, s = 1 }) => (
    <g transform={`translate(${x} ${y}) scale(${s})`}>
      <ellipse cx="0" cy="0" rx="9" ry="12" fill={RED} stroke={INK} strokeWidth="2.4" />
      <line x1="0" y1="11" x2="0" y2="34" stroke={INK} strokeWidth="2.8" strokeLinecap="round" />
    </g>
  );

  return (
    <svg
      className="ebook-cover"
      width={dims.w}
      height={dims.h}
      viewBox="0 0 612 792"
      style={{ display: "block", width: "100%", maxWidth: dims.w, height: "auto", borderRadius: 2, boxShadow: "0 1px 0 rgba(255,255,255,0.1) inset, 0 20px 40px -15px rgba(42,29,18,0.4), 0 4px 0 rgba(0,0,0,0.05)" }}
    >
      <rect width="612" height="792" fill={CREAM} />
      {/* inner keyline frame */}
      <rect x="26" y="26" width="560" height="740" fill="none" stroke={INK} strokeWidth="2.5" />
      <rect x="34" y="34" width="544" height="724" fill="none" stroke={RED} strokeWidth="1.4" />

      {/* top eyebrow */}
      <text x={CX} y="108" textAnchor="middle" fontFamily="Archivo, sans-serif" fontWeight="700" fontSize="20" letterSpacing="10" fill={INK}>THE</text>

      {/* doodles flanking */}
      <Carrot x={150} y="92" s={1.05} />
      <Leaf x={420} y="104" s={1.05} />

      {/* WORDMARK */}
      <text x={CX} y="212" textAnchor="middle" fontFamily="Archivo, sans-serif" fontWeight="900" fontSize="96" letterSpacing="1" fill={RED}>NO-BS</text>
      <text x={CX} y="338" textAnchor="middle" fontFamily="Archivo, sans-serif" fontWeight="900" fontSize="92" letterSpacing="1" fill={INK}>TODDLER</text>
      <text x={CX} y="430" textAnchor="middle" fontFamily="Archivo, sans-serif" fontWeight="900" fontSize="92" letterSpacing="2" fill={INK}>TABLE</text>

      {/* sage rule + dots */}
      <line x1="176" y1="468" x2="436" y2="468" stroke={SAGE} strokeWidth="3" strokeLinecap="round" />
      <circle cx="306" cy="468" r="6" fill={YELLOW} stroke={INK} strokeWidth="2" />

      {/* subtitle */}
      <text x={CX} y="510" textAnchor="middle" fontFamily="Archivo, sans-serif" fontWeight="800" fontSize="22" letterSpacing="2" fill={RED}>END THE DINNER BATTLES.</text>
      <text x={CX} y="540" textAnchor="middle" fontFamily="Archivo, sans-serif" fontWeight="800" fontSize="22" letterSpacing="2" fill={RED}>DITCH THE GUILT.</text>
      <text x={CX} y="570" textAnchor="middle" fontFamily="Archivo, sans-serif" fontWeight="800" fontSize="22" letterSpacing="2" fill={RED}>RAISE A KID WHO ACTUALLY EATS.</text>

      {/* playbook line */}
      <text x={CX} y="612" textAnchor="middle" fontFamily="Archivo, sans-serif" fontWeight="600" fontStyle="italic" fontSize="20" fill={INK}>A real-world playbook for parents of children ages 1–5</text>

      {/* doodle row */}
      <Carrot x={250} y="648" s={0.95} fill={YELLOW} />
      <Spoon x={306} y="654" s={0.95} />
      <Leaf x={332} y="666" s={0.95} />

      {/* author block */}
      <text x={CX} y="704" textAnchor="middle" fontFamily="Archivo, sans-serif" fontWeight="600" fontSize="18" letterSpacing="6" fill={INK}>BY</text>
      <text x={CX} y="734" textAnchor="middle" fontFamily="Archivo, sans-serif" fontWeight="900" fontSize="30" letterSpacing="3" fill={INK}>NOZIMA KUDROW</text>
      <text x={CX} y="756" textAnchor="middle" fontFamily="Archivo, sans-serif" fontWeight="700" fontSize="15" letterSpacing="5" fill={SAGE}>LITTLE HEALTHY PLATES</text>
    </svg>
  );
}

/* ----- NAV ----- */
function Nav({ route, navigate, cart, openCart }) {
  const [menuOpen, setMenuOpen] = useState(false);
  const links = [
    { id: "home", label: "Home" },
    { id: "shop", label: "Shop" },
    { id: "recipes", label: "Recipes" },
    { id: "about", label: "About" },
    { id: "newsletter", label: "Newsletter" },
  ];
  const cartCount = cart.reduce((n, i) => n + i.qty, 0);

  const go = (id) => {
    setMenuOpen(false);
    navigate(id);
  };

  const openCartAndClose = () => {
    setMenuOpen(false);
    openCart();
  };

  useEffect(() => {
    if (!menuOpen) return;
    const onKey = (e) => { if (e.key === "Escape") setMenuOpen(false); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [menuOpen]);

  return (
    <nav className={"nav" + (menuOpen ? " is-menu-open" : "")}>
      <div className="nav-inner">
        <div className="nav-logo" onClick={() => go("home")} role="button">
          <span className="mark">lhp</span>
          <span>little healthy plates</span>
        </div>
        <div className="nav-actions">
          <button type="button" className="cart-pill cart-pill--header" onClick={openCartAndClose} aria-label={"Cart, " + cartCount + " items"}>
            Cart
            {cartCount > 0 && <span className="count">{cartCount}</span>}
          </button>
          <button
            type="button"
            className={"nav-burger" + (menuOpen ? " is-open" : "")}
            aria-label={menuOpen ? "Close menu" : "Open menu"}
            aria-expanded={menuOpen}
            aria-controls="mobile-nav"
            onClick={() => setMenuOpen(v => !v)}
          >
            <span />
            <span />
            <span />
          </button>
        </div>
        <div id="mobile-nav" className={"nav-links" + (menuOpen ? " is-open" : "")}>
          {links.map(l => (
            <button
              key={l.id}
              type="button"
              className={"nav-link " + (route === l.id ? "active" : "")}
              onClick={() => go(l.id)}
            >
              {l.label}
            </button>
          ))}
          <button type="button" className="cart-pill nav-links-cart" onClick={openCartAndClose}>
            Cart
            {cartCount > 0 && <span className="count">{cartCount}</span>}
          </button>
        </div>
      </div>
      {menuOpen && (
        <button type="button" className="nav-scrim" aria-label="Close menu" onClick={() => setMenuOpen(false)} />
      )}
    </nav>
  );
}

/* ----- FOOTER ----- */
function Footer({ navigate }) {
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer-grid">
          <div>
            <div style={{ fontFamily: "var(--f-display)", fontStyle: "italic", fontSize: 32, marginBottom: 12 }}>
              little healthy plates
            </div>
            <p style={{ color: "var(--ink-soft)", maxWidth: 380, fontSize: 15 }}>
              Real-food cooking for families who care.
              Written from my kitchen table, tested on my three picky kids.
            </p>
            <div style={{ marginTop: 24, fontFamily: "var(--f-hand)", fontSize: 26, color: "var(--terracotta-deep)" }}>
              — xo, the LHP kitchen
            </div>
          </div>
          <div>
            <h4>Explore</h4>
            <ul>
              <li><button onClick={() => navigate("shop")}>Shop ebooks</button></li>
              <li><button onClick={() => navigate("recipes")}>Recipes</button></li>
              <li><button onClick={() => navigate("about")}>About</button></li>
              <li><button onClick={() => navigate("newsletter")}>Newsletter</button></li>
            </ul>
          </div>
          <div>
            <h4>Find me</h4>
            <ul>
              <li><a href="https://www.instagram.com/littlehealthyplates/" target="_blank" rel="noopener noreferrer">Instagram</a></li>
              <li><a href="https://linktr.ee/littlehealthyplates" target="_blank" rel="noopener noreferrer">Linktree</a></li>
              <li><a href="mailto:kudrow.nozima@gmail.com">Contact</a></li>
            </ul>
          </div>
        </div>
        <div className="dotted" style={{ margin: "50px 0 20px" }} />
        <div className="footer-meta" style={{ display: "flex", justifyContent: "space-between", color: "var(--ink-mute)", fontSize: 13 }}>
          <div>© 2026 Little Healthy Plates</div>
          <div style={{ fontFamily: "var(--f-mono)", letterSpacing: "0.08em" }}>made with butter & a lot of patience</div>
        </div>
      </div>
    </footer>
  );
}

/* ----- TOAST ----- */
function Toast({ message, onDone }) {
  useEffect(() => {
    const t = setTimeout(onDone, 2700);
    return () => clearTimeout(t);
  }, [message]);
  if (!message) return null;
  return (
    <div className="toast">
      <span style={{ color: "var(--butter)" }}>✓</span>
      {message}
    </div>
  );
}

/* ----- CART DRAWER ----- */
function CartDrawer({ open, onClose, cart, removeItem, navigate }) {
  if (!open) return null;
  const subtotal = cart.reduce((s, i) => s + i.price * i.qty, 0);

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal-cart" onClick={(e) => e.stopPropagation()}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 6 }}>
          <h2 style={{ fontStyle: "italic", fontSize: 36 }}>Your basket</h2>
          <button className="cart-close" onClick={onClose} style={{ background: "none", border: "none", fontSize: 26, cursor: "pointer", color: "var(--ink)" }} aria-label="Close cart">×</button>
        </div>
        <div className="wavy" style={{ marginBottom: 24 }} />

        {cart.length === 0 && (
          <div style={{ padding: "60px 0", textAlign: "center" }}>
            <div className="hand" style={{ fontSize: 42, color: "var(--ink-mute)", marginBottom: 8 }}>nothing here yet</div>
            <p style={{ color: "var(--ink-soft)", marginBottom: 24 }}>
              The shop is just down the hall.
            </p>
            <button className="btn terracotta" onClick={() => { onClose(); navigate("shop"); }}>
              Browse ebooks →
            </button>
          </div>
        )}

        {cart.length > 0 && (
          <>
            <div style={{ display: "flex", flexDirection: "column", gap: 18, marginBottom: 30 }}>
              {cart.map(item => (
                <div key={item.id} style={{ display: "flex", gap: 14, alignItems: "flex-start", paddingBottom: 18, borderBottom: "1px dashed rgba(42,29,18,0.15)" }}>
                  <div style={{ flexShrink: 0 }}>
                    <EbookCover ebook={item} size="sm" />
                  </div>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontFamily: "var(--f-display)", fontStyle: "italic", fontSize: 22, lineHeight: 1.1 }}>{item.title}</div>
                    <div style={{ fontSize: 13, color: "var(--ink-mute)", marginTop: 4 }}>{item.format}</div>
                    <div style={{ marginTop: 10, display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                      <span className="hand" style={{ fontSize: 26, color: "var(--terracotta-deep)" }}>${item.price}</span>
                      <button onClick={() => removeItem(item.id)} style={{ background: "none", border: "none", color: "var(--ink-mute)", cursor: "pointer", fontSize: 12, textTransform: "uppercase", letterSpacing: "0.08em" }}>Remove</button>
                    </div>
                  </div>
                </div>
              ))}
            </div>

            <div style={{ background: "var(--cream)", padding: 20, borderRadius: 2, marginBottom: 20 }}>
              <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 8 }}>
                <span style={{ color: "var(--ink-soft)" }}>Subtotal</span>
                <span>${subtotal}</span>
              </div>
              <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 8, color: "var(--ink-soft)" }}>
                <span>Delivery</span>
                <span style={{ fontFamily: "var(--f-hand)", fontSize: 22, color: "var(--sage-deep)" }}>by email — free</span>
              </div>
              <div className="dotted" style={{ margin: "12px 0" }} />
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
                <span style={{ fontFamily: "var(--f-display)", fontSize: 22 }}>Total</span>
                <span style={{ fontFamily: "var(--f-display)", fontStyle: "italic", fontSize: 36 }}>${subtotal}</span>
              </div>
            </div>

            <button className="btn terracotta" style={{ width: "100%", justifyContent: "center", padding: "18px" }} onClick={() => { onClose(); navigate("checkout"); }}>
              Check out →
            </button>
            <p style={{ textAlign: "center", marginTop: 16, fontFamily: "var(--f-hand)", fontSize: 20, color: "var(--ink-mute)" }}>
              your books arrive in your inbox in minutes ✿
            </p>
          </>
        )}
      </div>
    </div>
  );
}

/* expose to other babel scripts */
Object.assign(window, { EBOOKS, EbookCover, NoBsCover, Nav, Footer, Toast, CartDrawer });
