/* pages.jsx — production routes for the static site.
   Page copy, SEO titles and descriptions all come from window.CONTENT. */

function normalizePathname(pathname) {
  const clean = (pathname || "/").replace(/\/+$/, "");
  return clean || "/";
}

/* the /admin-editable SEO row for a path, if there is one */
function seoEntry(path) {
  return (CONTENT.seo || []).find((e) => normalizePathname(e.path) === path);
}

function getPageTitle(pathname) {
  const path = normalizePathname(pathname);
  if (path.startsWith("/products/")) {
    const product = PRODUCTS.find((p) => p.slug === path.split("/").pop());
    return product ? `${product.title} — ${SITE.name}` : `מוצר — ${SITE.name}`;
  }
  const entry = seoEntry(path);
  return (entry && entry.title) || SITE.seoTitle || SITE.name;
}

function getPageMeta(pathname) {
  const path = normalizePathname(pathname);
  const fallbackImage = SITE.ogImage || "/assets/book-cover.jpg";
  if (path.startsWith("/products/")) {
    const product = PRODUCTS.find((p) => p.slug === path.split("/").pop());
    if (product) {
      return {
        title: `${product.title} | ${SITE.name}`,
        description: product.summary,
        path,
        image: productImageSrc(product.img) || fallbackImage,
        type: "product",
        product,
      };
    }
  }
  const entry = seoEntry(path);
  return {
    title: getPageTitle(path),
    description: (entry && entry.description) || SITE.seoDescription || "",
    path,
    image: fallbackImage,
    type: "website",
  };
}

function upsertMeta(selector, attrs) {
  let node = document.head.querySelector(selector);
  if (!node) {
    node = document.createElement("meta");
    document.head.appendChild(node);
  }
  Object.entries(attrs).forEach(([key, value]) => node.setAttribute(key, value));
}

function routeLabel(path) {
  const entry = seoEntry(path);
  if (entry && entry.label) return entry.label;
  return getPageTitle(path).split("—")[0].trim();
}

function getBreadcrumbItems(meta) {
  const home = C("pages.productDetail.breadcrumbHome", "ראשי");
  const shop = C("pages.productDetail.breadcrumbShop", "מוצרים");
  if (meta.product) {
    return [
      { name: home, path:"/" },
      { name: shop, path:"/products" },
      { name: meta.product.title, path: meta.path },
    ];
  }
  if (meta.path === "/") return [{ name: home, path:"/" }];
  return [
    { name: home, path:"/" },
    { name: routeLabel(meta.path), path: meta.path },
  ];
}

function breadcrumbSchema(meta, origin) {
  return {
    "@type":"BreadcrumbList",
    "@id": new URL(`${meta.path}#breadcrumb`, origin).href,
    itemListElement: getBreadcrumbItems(meta).map((item, index) => ({
      "@type":"ListItem",
      position: index + 1,
      name: item.name,
      item: new URL(item.path, origin).href,
    })),
  };
}

function faqSchema(url) {
  if (typeof FAQS === "undefined" || !FAQS.length) return null;
  return {
    "@type":"FAQPage",
    "@id": `${url}#faq`,
    mainEntity: FAQS.map((item) => ({
      "@type":"Question",
      name: item.q,
      acceptedAnswer: {
        "@type":"Answer",
        text: item.a,
      },
    })),
  };
}

function updateSeoMeta(pathname) {
  const meta = getPageMeta(pathname);
  const origin = window.location.origin;
  const url = new URL(meta.path, window.location.origin).href;
  const image = new URL(meta.image, window.location.origin).href;
  document.title = meta.title;
  upsertMeta('meta[name="description"]', { name:"description", content: meta.description });
  upsertMeta('meta[property="og:title"]', { property:"og:title", content: meta.title });
  upsertMeta('meta[property="og:description"]', { property:"og:description", content: meta.description });
  upsertMeta('meta[property="og:type"]', { property:"og:type", content: meta.type === "product" ? "product" : "website" });
  upsertMeta('meta[property="og:url"]', { property:"og:url", content: url });
  upsertMeta('meta[property="og:image"]', { property:"og:image", content: image });
  upsertMeta('meta[property="og:locale"]', { property:"og:locale", content:"he_IL" });
  upsertMeta('meta[property="og:site_name"]', { property:"og:site_name", content: SITE.name });
  upsertMeta('meta[name="twitter:card"]', { name:"twitter:card", content:"summary_large_image" });
  upsertMeta('meta[name="twitter:title"]', { name:"twitter:title", content: meta.title });
  upsertMeta('meta[name="twitter:description"]', { name:"twitter:description", content: meta.description });
  upsertMeta('meta[name="twitter:image"]', { name:"twitter:image", content: image });

  let canonical = document.head.querySelector('link[rel="canonical"]');
  if (!canonical) {
    canonical = document.createElement("link");
    canonical.setAttribute("rel", "canonical");
    document.head.appendChild(canonical);
  }
  canonical.setAttribute("href", url);

  const graph = [
    {
      "@type":"WebSite",
      "@id": `${origin}/#website`,
      name: SITE.name,
      url: origin,
      inLanguage:"he-IL",
    },
    {
      "@type":"Person",
      "@id": `${origin}/#author`,
      name: C("home.author.card.name", SITE.name),
      url: new URL("/about", window.location.origin).href,
    },
    {
      "@type":"WebPage",
      "@id": `${url}#webpage`,
      url,
      name: meta.title,
      description: meta.description,
      inLanguage:"he-IL",
      isPartOf: { "@id": `${origin}/#website` },
      breadcrumb: { "@id": new URL(`${meta.path}#breadcrumb`, origin).href },
      primaryImageOfPage: { "@type":"ImageObject", url: image },
    },
    breadcrumbSchema(meta, origin),
  ];
  if (meta.product) {
    const hasProductImage = Boolean(meta.product.img);
    graph.push({
      "@type": meta.product.slug === "manhigot-book" ? "Book" : "Product",
      "@id": `${url}#product`,
      name: meta.product.title,
      description: meta.product.summary,
      image: hasProductImage ? image : undefined,
      url,
      inLanguage:"he-IL",
      category: productCategoryLabels(meta.product).join(", "),
      brand: { "@type":"Brand", name: SITE.name },
      mainEntityOfPage: { "@id": `${url}#webpage` },
      author: meta.product.slug === "manhigot-book" ? { "@id": `${origin}/#author` } : undefined,
      offers: {
        "@type":"Offer",
        priceCurrency:"ILS",
        price: String(meta.product.price),
        url,
      },
    });
  }
  if (meta.path === "/faq") {
    const faq = faqSchema(url);
    if (faq) graph.push(faq);
  }
  if (meta.path === "/contact") {
    graph.push({
      "@type":"ContactPage",
      "@id": `${url}#contact`,
      url,
      name: meta.title,
      description: meta.description,
      mainEntity: { "@id": `${origin}/#website` },
    });
  }
  let schema = document.getElementById("sd-schema");
  if (!schema) {
    schema = document.createElement("script");
    schema.type = "application/ld+json";
    schema.id = "sd-schema";
    document.head.appendChild(schema);
  }
  schema.textContent = JSON.stringify({ "@context":"https://schema.org", "@graph": graph }, null, 2);
}

function PageShell({ palette, children }) {
  return (
    <>
      <AnnouncementBar palette={palette}/>
      <Nav palette={palette}/>
      <main>{children}</main>
      <Footer palette={palette}/>
      <FloatingWa palette={palette}/>
      <MobileBuyBar palette={palette}/>
    </>
  );
}

function HomePage({ palette }) {
  return (
    <>
      <Hero palette={palette} variant="editorial"/>
      <TrustStrip palette={palette}/>
      <Manifesto palette={palette}/>
      <ValueProps palette={palette}/>
      <AboutBook palette={palette}/>
      <ChapterTeaser palette={palette}/>
      <ForHer palette={palette}/>
      <BookInside palette={palette}/>
      <MeetAuthors palette={palette}/>
      <AuthorLetter palette={palette}/>
      <BatMitzvah palette={palette}/>
      <Products palette={palette}/>
      <WhoItsFor palette={palette}/>
      <VideoStories palette={palette}/>
      <Testimonials palette={palette}/>
      <TwoCreatingMeaning palette={palette}/>
      <PressBar palette={palette}/>
      <GroupPurchase palette={palette}/>
      <LeadMagnet palette={palette}/>
      <FAQ palette={palette}/>
    </>
  );
}

function SitePage({ path, palette }) {
  const route = normalizePathname(path);
  if (route.startsWith("/products/")) {
    return <ProductDetailPage palette={palette} slug={route.split("/").pop()}/>;
  }
  switch (route) {
    case "/": return <HomePage palette={palette}/>;
    case "/book": return <BookPage palette={palette}/>;
    case "/about": return <AboutPage palette={palette}/>;
    case "/products": return <ProductArchivePage palette={palette}/>;
    case "/bat-mitzvah": return <BatMitzvahGiftPage palette={palette}/>;
    case "/workshops": return <WorkshopsPage palette={palette}/>;
    case "/group": return <GroupPage palette={palette}/>;
    case "/sample": return <SampleRoutePage palette={palette}/>;
    case "/faq": return <FAQPage palette={palette}/>;
    case "/contact": return <ContactPage palette={palette}/>;
    case "/blog": return <BlogPage palette={palette}/>;
    case "/terms": return <LegalPage palette={palette} type="terms"/>;
    case "/privacy": return <LegalPage palette={palette} type="privacy"/>;
    case "/shipping": return <LegalPage palette={palette} type="shipping"/>;
    case "/refund": return <LegalPage palette={palette} type="refund"/>;
    case "/accessibility": return <LegalPage palette={palette} type="accessibility"/>;
    default: return <NotFoundPage palette={palette}/>;
  }
}

/* a page title built from the editable "title" + coloured "titleAccent" pair */
function AccentTitle({ palette, text, accent }) {
  return (
    <>
      {text} {accent && <span style={{ color: palette.accent, fontStyle:"italic", fontWeight:500 }}>{accent}</span>}
    </>
  );
}

function PageHeader({ palette, eyebrow, title, text, children }) {
  return (
    <section className="pad-y" style={{ background: palette.bg, borderBottom:`1px solid ${palette.line}` }}>
      <div className="container">
        <div className="page-head" style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:48, alignItems:"end" }}>
          <div>
            <Eyebrow palette={palette}>{eyebrow}</Eyebrow>
            <h1 className="display" style={{ fontSize:"clamp(40px, 6vw, 82px)", lineHeight:.98, margin:"16px 0 0", maxWidth:"12ch" }}>{title}</h1>
          </div>
          <div>
            <p style={{ fontSize:17, lineHeight:1.75, color: palette.ink2, margin:"0 0 24px", maxWidth:"54ch" }}>{text}</p>
            {children}
          </div>
        </div>
      </div>
      <style>{`
        @media (max-width: 820px){ .page-head{ grid-template-columns: 1fr !important; gap: 28px !important; } }
      `}</style>
    </section>
  );
}

function ProductArchivePage({ palette }) {
  const c = C("pages.products", {});
  const [filter, setFilter] = React.useState("all");
  const filters = productFilters();
  const visible = filter === "all" ? PRODUCTS : PRODUCTS.filter((p) => (p.categories || []).includes(filter));
  const selected = filters.find(([key]) => key === filter) || filters[0] || ["all", ""];
  return (
    <>
      <PageHeader
        palette={palette}
        eyebrow={c.eyebrow}
        title={<AccentTitle palette={palette} text={c.title} accent={c.titleAccent}/>}
        text={c.text}
      >
        <div style={{ display:"flex", gap:8, flexWrap:"wrap" }}>
          {filters.map(([key,label])=>(
            <button key={key} type="button" onClick={()=>setFilter(key)} style={{ padding:"9px 16px", borderRadius:999, border: filter===key ? "none" : `1px solid ${palette.line}`, background: filter===key ? palette.ink : "transparent", color: filter===key ? palette.bg : palette.ink, fontWeight:600 }}>
              {label} <span style={{ opacity:.62 }}>{key === "all" ? PRODUCTS.length : PRODUCTS.filter((p)=>(p.categories||[]).includes(key)).length}</span>
            </button>
          ))}
        </div>
      </PageHeader>
      <section className="pad-y" style={{ background: palette.surface }}>
        <div className="container">
          <div style={{ display:"flex", alignItems:"center", justifyContent:"space-between", gap:18, flexWrap:"wrap", marginBottom:24 }}>
            <div style={{ color: palette.ink2, fontSize:14 }}>
              {c.countPre} <strong style={{ color: palette.ink }}>{visible.length}</strong> {c.countMid} <strong style={{ color: palette.ink }}>{selected[1]}</strong>
            </div>
            <a href={whatsappLink(c.helpWaMessage)} style={{ display:"inline-flex", alignItems:"center", gap:8, color: palette.accent, fontWeight:700, fontSize:14 }}>
              <IconWa size={16}/> {c.helpLabel}
            </a>
          </div>
          <div className="prod-grid" style={{ display:"grid", gridTemplateColumns:"repeat(4, 1fr)", gap:18 }}>
            {visible.map((product)=><ProductCard key={product.id} product={product} palette={palette}/>)}
          </div>
        </div>
        <style>{`
          @media (max-width: 1100px){ .prod-grid{ grid-template-columns: repeat(3, 1fr) !important; } }
          @media (max-width: 760px){ .prod-grid{ grid-template-columns: repeat(2, 1fr) !important; } }
          @media (max-width: 480px){ .prod-grid{ grid-template-columns: 1fr !important; } }
        `}</style>
      </section>
      <ShopOrderFlow palette={palette}/>
    </>
  );
}

function ProductDetailPage({ palette, slug }) {
  const product = PRODUCTS.find((p) => p.slug === slug);
  if (!product) return <NotFoundPage palette={palette}/>;
  const c = C("pages.productDetail", {});
  const discount = productDiscountPercent(product);
  const currentIndex = PRODUCTS.findIndex((p) => p.id === product.id);
  const previous = currentIndex > 0 ? PRODUCTS[currentIndex - 1] : null;
  const next = currentIndex < PRODUCTS.length - 1 ? PRODUCTS[currentIndex + 1] : null;
  const categoryLabels = productCategoryLabels(product);
  return (
    <>
      <section className="pad-y" style={{ background: palette.bg }}>
        <div className="container">
          <ProductBreadcrumb palette={palette} product={product}/>
          <div className="product-page" style={{ display:"grid", gridTemplateColumns:"minmax(280px, .85fr) 1.15fr", gap:64, alignItems:"center" }}>
            <div style={{ background: palette.surface, border:`1px solid ${palette.line}`, minHeight:440, display:"grid", placeItems:"center", padding:36 }}>
              {product.img === "book-cover" ? (
                <img src="/assets/book-cover.jpg" alt={product.title} style={{ maxHeight:380, maxWidth:"78%", filter:"drop-shadow(0 30px 45px rgba(28,24,21,.25))" }}/>
              ) : product.img ? (
                <img src={productImageSrc(product.img)} alt={product.title} style={{ maxWidth:"100%", maxHeight:420, objectFit:"contain", filter:"drop-shadow(0 24px 36px rgba(28,24,21,.18))" }}/>
              ) : (
                <PhotoPlaceholder label={product.title} palette={palette} tone={product.tone} ratio="4/5"/>
              )}
            </div>
            <div>
              <Eyebrow palette={palette}>{product.tag || "מוצר"}</Eyebrow>
              <h1 className="display" style={{ fontSize:"clamp(38px, 5vw, 68px)", lineHeight:1.02, margin:"16px 0 18px" }}>{product.title}</h1>
              <div style={{ display:"flex", gap:8, flexWrap:"wrap", margin:"0 0 18px" }}>
                {categoryLabels.map((label)=>(
                  <a key={label} href="/products" style={{ border:`1px solid ${palette.line}`, borderRadius:999, padding:"6px 12px", fontSize:12.5, color: palette.ink2, background: palette.surface }}>
                    {label}
                  </a>
                ))}
              </div>
              <p style={{ fontSize:18, lineHeight:1.7, color: palette.ink2, margin:"0 0 24px", maxWidth:"58ch" }}>{product.summary}</p>
              <div style={{ display:"grid", gridTemplateColumns:"repeat(3, minmax(0, 1fr))", gap:10, maxWidth:520, marginBottom:28 }} className="price-grid">
                <div style={{ background: palette.surface, border:`1px solid ${palette.line}`, borderRadius:8, padding:"14px 16px" }}>
                  <div style={{ fontSize:12, color: palette.ink2, marginBottom:4 }}>{c.priceLabel}</div>
                  <div className="display" style={{ fontSize:30, color: palette.accent, fontWeight:700 }}>{formatProductPrice(product.price)}</div>
                </div>
                <div style={{ background: palette.surface, border:`1px solid ${palette.line}`, borderRadius:8, padding:"14px 16px" }}>
                  <div style={{ fontSize:12, color: palette.ink2, marginBottom:4 }}>{c.wasLabel}</div>
                  <div className="display" style={{ fontSize:24, color: palette.ink, textDecoration: product.was ? "line-through" : "none", opacity: product.was ? .58 : 1 }}>{product.was ? formatProductPrice(product.was) : "-"}</div>
                </div>
                <div style={{ background: palette.surface, border:`1px solid ${palette.line}`, borderRadius:8, padding:"14px 16px" }}>
                  <div style={{ fontSize:12, color: palette.ink2, marginBottom:4 }}>{c.discountLabel}</div>
                  <div className="display" style={{ fontSize:24, color: palette.ink }}>{discount ? `${discount}%` : "-"}</div>
                </div>
              </div>
              <div style={{ display:"flex", gap:12, flexWrap:"wrap", marginBottom:30 }}>
                <PrimaryBtn palette={palette} size="lg" href={whatsappLink(`${c.orderWaPrefix} ${product.title}`)}>{c.orderCta}</PrimaryBtn>
                <GhostBtn palette={palette} size="lg" href={c.questionHref || "/contact"}>{c.questionCta}</GhostBtn>
              </div>
              <div style={{ borderTop:`1px solid ${palette.line}`, paddingTop:22 }}>
                <h2 className="display" style={{ fontSize:24, margin:"0 0 14px" }}>{c.includesTitle}</h2>
                <div style={{ display:"grid", gap:10 }}>
                  {(product.includes || []).map((item)=>(
                    <div key={item} style={{ display:"flex", alignItems:"center", gap:10, color: palette.ink2 }}>
                      <IconCheck size={16} stroke={palette.accent}/>{item}
                    </div>
                  ))}
                </div>
              </div>
            </div>
          </div>
        </div>
        <style>{`
          @media (max-width: 860px){ .product-page{ grid-template-columns: 1fr !important; gap: 36px !important; } }
          @media (max-width: 560px){ .price-grid{ grid-template-columns: 1fr !important; } }
        `}</style>
      </section>
      <ProductVideo palette={palette} product={product}/>
      <ShopOrderFlow palette={palette} compact/>
      <ProductPager palette={palette} previous={previous} next={next}/>
      <RelatedProducts palette={palette} product={product}/>
    </>
  );
}

function productCategoryLabels(product) {
  const filters = productFilters();
  const labels = (product.categories || [])
    .map((category) => (filters.find(([key]) => key === category) || [null, category])[1]);
  return [...new Set(labels)].slice(0, 4);
}

function ProductBreadcrumb({ palette, product }) {
  const c = C("pages.productDetail", {});
  return (
    <nav aria-label="breadcrumb" style={{ display:"flex", alignItems:"center", gap:8, flexWrap:"wrap", marginBottom:28, color: palette.ink2, fontSize:13 }}>
      <a href="/" style={{ color: palette.ink2 }}>{c.breadcrumbHome}</a>
      <span aria-hidden="true">/</span>
      <a href="/products" style={{ color: palette.ink2 }}>{c.breadcrumbShop}</a>
      <span aria-hidden="true">/</span>
      <span style={{ color: palette.ink, fontWeight:700 }}>{product.title}</span>
    </nav>
  );
}

function ShopOrderFlow({ palette, compact = false }) {
  const c = C("pages.orderFlow", {});
  const steps = c.steps || [];
  return (
    <section className={compact ? "" : "pad-y"} style={{ background: compact ? palette.bg : palette.ink, color: compact ? palette.ink : palette.bg, padding: compact ? "0 0 72px" : undefined }}>
      <div className="container">
        <div className="order-flow" style={{ display:"grid", gridTemplateColumns:"1fr 2fr", gap:28, alignItems:"stretch" }}>
          <div style={{ display:"flex", flexDirection:"column", justifyContent:"space-between", gap:20, background: compact ? palette.surface : "transparent", border: compact ? `1px solid ${palette.line}` : "none", borderRadius:8, padding: compact ? 24 : 0 }}>
            <div>
              <Eyebrow palette={palette} color={compact ? palette.accent : palette.gold}>{c.eyebrow}</Eyebrow>
              <h2 className="display" style={{ fontSize:"clamp(28px, 4vw, 44px)", lineHeight:1.08, margin:"14px 0 12px", color: compact ? palette.ink : palette.bg }}>
                {c.title}
              </h2>
              <p style={{ color: compact ? palette.ink2 : `${palette.bg}cc`, lineHeight:1.65, margin:0 }}>
                {c.text}
              </p>
            </div>
            <a href={whatsappLink(c.helpWaMessage)} style={{ display:"inline-flex", alignItems:"center", gap:8, color: compact ? palette.accent : palette.gold, fontWeight:700 }}>
              <IconWa size={16}/> {c.helpLabel}
            </a>
          </div>
          <div className="order-steps" style={{ display:"grid", gridTemplateColumns:`repeat(${Math.max(steps.length,1)}, 1fr)`, gap:14 }}>
            {steps.map((s,i)=>(
              <article key={i} style={{ background: compact ? palette.surface : `${palette.bg}10`, border:`1px solid ${compact ? palette.line : `${palette.bg}22`}`, borderRadius:8, padding:"22px 20px" }}>
                <div className="display" style={{ width:34, height:34, borderRadius:999, display:"grid", placeItems:"center", background: compact ? palette.accent : palette.gold, color: compact ? palette.bg : palette.ink, fontSize:18, fontWeight:700 }}>{s.n}</div>
                <h3 className="display" style={{ fontSize:22, margin:"18px 0 10px", color: compact ? palette.ink : palette.bg }}>{s.t}</h3>
                <p style={{ margin:0, color: compact ? palette.ink2 : `${palette.bg}c8`, lineHeight:1.6, fontSize:14 }}>{s.d}</p>
              </article>
            ))}
          </div>
        </div>
      </div>
      <style>{`
        @media (max-width: 900px){ .order-flow{ grid-template-columns: 1fr !important; } .order-steps{ grid-template-columns: 1fr !important; } }
      `}</style>
    </section>
  );
}

function ProductPager({ palette, previous, next }) {
  if (!previous && !next) return null;
  const c = C("pages.productDetail", {});
  const itemStyle = {
    background: palette.surface,
    border:`1px solid ${palette.line}`,
    borderRadius:8,
    padding:"20px 22px",
    display:"flex",
    alignItems:"center",
    justifyContent:"space-between",
    gap:18,
    minHeight:98,
  };
  return (
    <section style={{ background: palette.bg, padding:"0 0 72px" }}>
      <div className="container">
        <div className="product-pager" style={{ display:"grid", gridTemplateColumns:"repeat(2, 1fr)", gap:14 }}>
          {previous ? (
            <a href={`/products/${previous.slug}`} style={itemStyle}>
              <IconArrowR size={18} stroke={palette.accent}/>
              <span>
                <span style={{ display:"block", color: palette.ink2, fontSize:12, marginBottom:5 }}>{c.prevLabel}</span>
                <strong className="display" style={{ fontSize:20 }}>{previous.title}</strong>
              </span>
            </a>
          ) : <div/>}
          {next ? (
            <a href={`/products/${next.slug}`} style={itemStyle}>
              <span>
                <span style={{ display:"block", color: palette.ink2, fontSize:12, marginBottom:5 }}>{c.nextLabel}</span>
                <strong className="display" style={{ fontSize:20 }}>{next.title}</strong>
              </span>
              <IconArrowL size={18} stroke={palette.accent}/>
            </a>
          ) : <div/>}
        </div>
      </div>
      <style>{`@media (max-width: 720px){ .product-pager{ grid-template-columns: 1fr !important; } .product-pager > div:empty{ display:none; } }`}</style>
    </section>
  );
}

function RelatedProducts({ palette, product }) {
  const c = C("pages.productDetail", {});
  const related = PRODUCTS
    .filter((p) => p.id !== product.id && (p.categories || []).some((cat) => (product.categories || []).includes(cat)))
    .slice(0, 4);
  if (!related.length) return null;
  return (
    <section className="pad-y" style={{ background: palette.surface }}>
      <div className="container">
        <div style={{ display:"flex", alignItems:"end", justifyContent:"space-between", gap:18, flexWrap:"wrap", marginBottom:28 }}>
          <div>
            <Eyebrow palette={palette}>{c.relatedEyebrow}</Eyebrow>
            <h2 className="display" style={{ fontSize:"clamp(30px, 4vw, 46px)", margin:"14px 0 0" }}>{c.relatedTitle}</h2>
          </div>
          <GhostBtn palette={palette} href="/products">{c.relatedAll}</GhostBtn>
        </div>
        <div className="prod-grid" style={{ display:"grid", gridTemplateColumns:"repeat(4, 1fr)", gap:18 }}>
          {related.map((item)=><ProductCard key={item.id} product={item} palette={palette}/>)}
        </div>
      </div>
      <style>{`
        @media (max-width: 1100px){ .prod-grid{ grid-template-columns: repeat(3, 1fr) !important; } }
        @media (max-width: 760px){ .prod-grid{ grid-template-columns: repeat(2, 1fr) !important; } }
        @media (max-width: 480px){ .prod-grid{ grid-template-columns: 1fr !important; } }
      `}</style>
    </section>
  );
}

function BookPage({ palette }) {
  const c = C("pages.book", {});
  return (
    <>
      <PageHeader
        palette={palette}
        eyebrow={c.eyebrow}
        title={<AccentTitle palette={palette} text={c.title} accent={c.titleAccent}/>}
        text={c.text}
      >
        {c.ctaLabel && <PrimaryBtn palette={palette} href={c.ctaHref || "/products"}>{c.ctaLabel}</PrimaryBtn>}
      </PageHeader>
      <AboutBook palette={palette}/>
      <ChapterTeaser palette={palette}/>
      <BookInside palette={palette}/>
      <FAQ palette={palette}/>
    </>
  );
}

function AboutPage({ palette }) {
  return (
    <>
      <MeetAuthors palette={palette}/>
      <AuthorLetter palette={palette}/>
      <TwoCreatingMeaning palette={palette}/>
      <AboutNextSteps palette={palette}/>
    </>
  );
}

function AboutNextSteps({ palette }) {
  const c = C("pages.aboutNext", {});
  const items = c.items || [];
  return (
    <section className="pad-y" style={{ background: palette.bg }}>
      <div className="container">
        <div style={{ display:"grid", gridTemplateColumns:"1fr 1.4fr", gap:42, alignItems:"start" }} className="about-next">
          <div>
            <Eyebrow palette={palette}>{c.eyebrow}</Eyebrow>
            <h2 className="display" style={{ fontSize:"clamp(30px, 4vw, 48px)", lineHeight:1.08, margin:"14px 0 16px" }}>
              {c.title} <span style={{ color: palette.accent, fontStyle:"italic", fontWeight:500 }}>{c.titleAccent}</span>
            </h2>
            <p style={{ color: palette.ink2, lineHeight:1.7, margin:0, maxWidth:"48ch" }}>
              {c.text}
            </p>
          </div>
          <div className="about-next-grid" style={{ display:"grid", gridTemplateColumns:`repeat(${Math.max(items.length,1)}, 1fr)`, gap:14 }}>
            {items.map((it,i)=>(
              <a key={i} href={it.href} style={{ background: palette.surface, border:`1px solid ${palette.line}`, borderRadius:8, padding:"24px 22px", minHeight:178, display:"flex", flexDirection:"column", justifyContent:"space-between", gap:18 }}>
                <span>
                  <span className="display" style={{ display:"block", fontSize:23, fontWeight:700, marginBottom:10 }}>{it.t}</span>
                  <span style={{ display:"block", color: palette.ink2, fontSize:14, lineHeight:1.6 }}>{it.d}</span>
                </span>
                <span style={{ color: palette.accent, fontWeight:700, fontSize:14 }}>{c.linkLabel}</span>
              </a>
            ))}
          </div>
        </div>
      </div>
      <style>{`
        @media (max-width: 980px){ .about-next{ grid-template-columns: 1fr !important; } }
        @media (max-width: 760px){ .about-next-grid{ grid-template-columns: 1fr !important; } }
      `}</style>
    </section>
  );
}

function WorkshopsPage({ palette }) {
  const c = C("pages.workshops", {});
  return (
    <>
      <PageHeader palette={palette} eyebrow={c.eyebrow}
        title={<AccentTitle palette={palette} text={c.title} accent={c.titleAccent}/>} text={c.text}>
        {c.ctaLabel && <PrimaryBtn palette={palette} href={whatsappLink(c.ctaWaMessage)}>{c.ctaLabel}</PrimaryBtn>}
      </PageHeader>
      <TwoCreatingMeaning palette={palette}/>
      <ContactBand palette={palette}/>
    </>
  );
}

function GroupPage({ palette }) {
  const c = C("pages.group", {});
  return (
    <>
      <PageHeader palette={palette} eyebrow={c.eyebrow}
        title={<AccentTitle palette={palette} text={c.title} accent={c.titleAccent}/>} text={c.text}/>
      <GroupPurchase palette={palette}/>
      <ContactBand palette={palette}/>
    </>
  );
}

function BatMitzvahGiftPage({ palette }) {
  const c = C("pages.batMitzvah", {});
  const giftProducts = (c.productSlugs || [])
    .map((slug) => PRODUCTS.find((product) => product.slug === slug))
    .filter(Boolean);
  const paths = c.paths || [];
  return (
    <>
      <PageHeader
        palette={palette}
        eyebrow={c.eyebrow}
        title={<AccentTitle palette={palette} text={c.title} accent={c.titleAccent}/>}
        text={c.text}
      >
        <div style={{ display:"flex", gap:12, flexWrap:"wrap" }}>
          {c.ctaLabel && <PrimaryBtn palette={palette} href={whatsappLink(c.ctaWaMessage)}>{c.ctaLabel}</PrimaryBtn>}
          {c.ghostLabel && <GhostBtn palette={palette} href={c.ghostHref || "/products"}>{c.ghostLabel}</GhostBtn>}
        </div>
      </PageHeader>
      <section className="pad-y" style={{ background: palette.surface }}>
        <div className="container">
          <div className="gift-paths" style={{ display:"grid", gridTemplateColumns:`repeat(${Math.max(paths.length,1)}, 1fr)`, gap:16, marginBottom:34 }}>
            {paths.map((p,i)=>(
              <article key={i} style={{ background: palette.bg, border:`1px solid ${palette.line}`, borderRadius:8, padding:"24px 22px" }}>
                <h2 className="display" style={{ fontSize:24, margin:"0 0 10px" }}>{p.t}</h2>
                <p style={{ color: palette.ink2, lineHeight:1.65, margin:0 }}>{p.d}</p>
              </article>
            ))}
          </div>
          <div style={{ display:"flex", alignItems:"end", justifyContent:"space-between", gap:18, flexWrap:"wrap", marginBottom:24 }}>
            <div>
              <Eyebrow palette={palette}>{c.listEyebrow}</Eyebrow>
              <h2 className="display" style={{ fontSize:"clamp(30px, 4vw, 46px)", margin:"14px 0 0" }}>{c.listTitle}</h2>
            </div>
            <a href={c.listLinkHref || "/group"} style={{ color: palette.accent, fontWeight:700, borderBottom:`1px solid ${palette.accent}` }}>{c.listLink}</a>
          </div>
          <div className="prod-grid" style={{ display:"grid", gridTemplateColumns:"repeat(4, 1fr)", gap:18 }}>
            {giftProducts.map((product)=><ProductCard key={product.id} product={product} palette={palette}/>)}
          </div>
        </div>
        <style>{`
          @media (max-width: 900px){ .gift-paths{ grid-template-columns: 1fr !important; } }
          @media (max-width: 1100px){ .prod-grid{ grid-template-columns: repeat(3, 1fr) !important; } }
          @media (max-width: 760px){ .prod-grid{ grid-template-columns: repeat(2, 1fr) !important; } }
          @media (max-width: 480px){ .prod-grid{ grid-template-columns: 1fr !important; } }
        `}</style>
      </section>
    </>
  );
}

function SampleRoutePage({ palette }) {
  const c = C("pages.sample", {});
  return (
    <>
      <PageHeader palette={palette} eyebrow={c.eyebrow}
        title={<AccentTitle palette={palette} text={c.title} accent={c.titleAccent}/>} text={c.text}/>
      <LeadMagnet palette={palette}/>
    </>
  );
}

function FAQPage({ palette }) {
  return (
    <FAQ palette={palette} asPage/>
  );
}

function ContactPage({ palette }) {
  const c = C("pages.contact", {});
  return (
    <>
      <PageHeader palette={palette} eyebrow={c.eyebrow}
        title={<AccentTitle palette={palette} text={c.title} accent={c.titleAccent}/>} text={c.text}/>
      <ContactBand palette={palette}/>
    </>
  );
}

function ContactBand({ palette }) {
  const items = [
    ["טלפון", CONTACT.phone, CONTACT.phoneHref, IconPhone],
    ["וואטסאפ", C("pages.contact.waLabel", "שלחו הודעה"), whatsappLink(), IconWa],
    ["אימייל", CONTACT.email, `mailto:${CONTACT.email}`, IconMail],
    ["אינסטגרם", CONTACT.instagramHandle, CONTACT.instagram, IconInsta],
  ];
  return (
    <section className="pad-y" style={{ background: palette.surface }}>
      <div className="container">
        <div className="contact-grid" style={{ display:"grid", gridTemplateColumns:"repeat(4, 1fr)", gap:16 }}>
          {items.map(([label,value,href,IconCmp])=>(
            <a key={label} href={href} style={{ background: palette.bg, border:`1px solid ${palette.line}`, borderRadius:8, padding:"24px 22px", display:"block" }}>
              <IconCmp size={24} stroke={palette.accent}/>
              <div className="display" style={{ fontSize:21, marginTop:16, fontWeight:700 }}>{label}</div>
              <div style={{ color: palette.ink2, fontSize:14, marginTop:6 }}>{value}</div>
            </a>
          ))}
        </div>
      </div>
      <style>{`
        @media (max-width: 860px){ .contact-grid{ grid-template-columns: 1fr 1fr !important; } }
        @media (max-width: 520px){ .contact-grid{ grid-template-columns: 1fr !important; } }
      `}</style>
    </section>
  );
}

function BlogPage({ palette }) {
  const c = C("pages.blog", {});
  return (
    <>
      <PageHeader palette={palette} eyebrow={c.eyebrow}
        title={<AccentTitle palette={palette} text={c.title} accent={c.titleAccent}/>} text={c.text}/>
      <section className="pad-y" style={{ background: palette.surface }}>
        <div className="container">
          <div style={{ background: palette.bg, border:`1px solid ${palette.line}`, borderRadius:8, padding:"32px 34px", maxWidth:760 }}>
            <h2 className="display" style={{ fontSize:30, margin:"0 0 12px" }}>{c.boxTitle}</h2>
            <p style={{ color: palette.ink2, lineHeight:1.7, margin:"0 0 24px" }}>
              {c.boxText}
            </p>
            {c.boxCta && <PrimaryBtn palette={palette} href={c.boxCtaHref || "/contact"}>{c.boxCta}</PrimaryBtn>}
          </div>
        </div>
      </section>
    </>
  );
}

function LegalPage({ palette, type }) {
  const legal = LEGAL || {};
  const page = legal[type] || legal.terms || {};
  return (
    <>
      <PageHeader palette={palette} eyebrow={legal.eyebrow} title={page.title} text={page.intro}/>
      <section className="pad-y" style={{ background: palette.surface }}>
        <div className="container" style={{ maxWidth:900 }}>
          <div style={{ background: palette.bg, border:`1px solid ${palette.line}`, borderRadius:8, padding:"34px 38px" }}>
            <ul style={{ margin:0, paddingInlineStart:22, color: palette.ink2, fontSize:16, lineHeight:1.9 }}>
              {(page.bullets || []).filter(Boolean).map((item,i)=><li key={i}>{item}</li>)}
            </ul>
            <div style={{ marginTop:28, paddingTop:22, borderTop:`1px solid ${palette.line}`, color: palette.ink2, fontSize:14 }}>
              {legal.contactPrefix} <a href={`mailto:${CONTACT.email}`} style={{ color: palette.accent, fontWeight:700 }}>{CONTACT.email}</a> · <a href={CONTACT.phoneHref} style={{ color: palette.accent, fontWeight:700 }}>{CONTACT.phone}</a>
            </div>
          </div>
        </div>
      </section>
    </>
  );
}

function NotFoundPage({ palette }) {
  const c = C("pages.notFound", {});
  return (
    <PageHeader
      palette={palette}
      eyebrow={c.eyebrow}
      title={<AccentTitle palette={palette} text={c.title} accent={c.titleAccent}/>}
      text={c.text}
    >
      <PrimaryBtn palette={palette} href="/">{c.ctaLabel}</PrimaryBtn>
    </PageHeader>
  );
}

Object.assign(window, {
  normalizePathname, getPageTitle, getPageMeta, updateSeoMeta, PageShell, HomePage, SitePage,
});
