// PepLab Co — Article detail page (/article/:slug)
// Renders one full article based on slug from URL query string

const { useState: useStateA, useEffect: useEffectA } = React;

// Read slug from URL: /article/:slug rewrites to /article.html?slug=:slug
const getSlugFromUrl = () => {
  try {
    const params = new URLSearchParams(window.location.search);
    const fromQuery = params.get("slug");
    if (fromQuery) return fromQuery;
    // Fallback: parse path /article/xxx
    const m = window.location.pathname.match(/\/article\/([^/?#]+)/);
    return m ? m[1] : null;
  } catch (e) {
    return null;
  }
};

// Render a single content block
const ArticleBlock = ({ block, idx }) => {
  switch (block.type) {
    case "h2":
      return (
        <h2
          id={`s-${idx}`}
          className="serif"
          style={{
            fontSize: "clamp(28px, 3.5vw, 40px)",
            lineHeight: 1.15,
            color: "var(--navy-deep)",
            fontWeight: 500,
            marginTop: 56,
            marginBottom: 20,
            letterSpacing: "-0.015em",
          }}
        >
          {block.text}
        </h2>
      );
    case "h3":
      return (
        <h3
          className="serif"
          style={{
            fontSize: 22,
            lineHeight: 1.25,
            color: "var(--navy-deep)",
            fontWeight: 500,
            marginTop: 36,
            marginBottom: 14,
          }}
        >
          {block.text}
        </h3>
      );
    case "p":
      return (
        <p
          style={{
            fontSize: 18,
            lineHeight: 1.7,
            color: "var(--graphite)",
            marginBottom: 22,
            fontWeight: 400,
          }}
        >
          {block.text}
        </p>
      );
    case "list":
      return (
        <ul
          style={{
            listStyle: "none",
            padding: 0,
            margin: "0 0 28px 0",
            display: "flex",
            flexDirection: "column",
            gap: 12,
          }}
        >
          {block.items.map((item, i) => (
            <li
              key={i}
              style={{
                display: "flex",
                gap: 14,
                fontSize: 17,
                lineHeight: 1.6,
                color: "var(--graphite)",
                paddingLeft: 0,
              }}
            >
              <span
                className="mono"
                style={{
                  color: "var(--champagne)",
                  fontSize: 12,
                  fontWeight: 500,
                  paddingTop: 5,
                  minWidth: 24,
                }}
              >
                0{i + 1}
              </span>
              <span>{item}</span>
            </li>
          ))}
        </ul>
      );
    case "callout":
      return (
        <aside
          style={{
            background: "var(--cream)",
            borderLeft: "3px solid var(--champagne)",
            padding: "24px 28px",
            margin: "32px 0",
            borderRadius: 2,
          }}
        >
          <p
            className="serif"
            style={{
              fontSize: 22,
              lineHeight: 1.4,
              color: "var(--navy-deep)",
              fontStyle: "italic",
              fontWeight: 400,
              margin: 0,
            }}
          >
            {block.text}
          </p>
        </aside>
      );
    case "quote":
      return (
        <blockquote
          style={{
            margin: "32px 0",
            paddingLeft: 24,
            borderLeft: "2px solid var(--champagne)",
          }}
        >
          <p
            className="serif"
            style={{
              fontSize: 24,
              lineHeight: 1.4,
              color: "var(--navy-deep)",
              fontStyle: "italic",
              fontWeight: 400,
            }}
          >
            "{block.text}"
          </p>
        </blockquote>
      );
    default:
      return null;
  }
};

// Hero of article page
const ArticleHero = ({ article }) => (
  <section
    style={{
      background: "var(--navy-deep)",
      color: "var(--white)",
      padding: "140px 0 80px",
      position: "relative",
      overflow: "hidden",
    }}
  >
    <div
      style={{
        position: "absolute",
        top: -50,
        right: -50,
        opacity: 0.06,
      }}
    >
      <PlMolecule size={400} color="var(--champagne)" />
    </div>
    <div className="container" style={{ position: "relative" }}>
      <a
        href="/#articulos"
        style={{
          display: "inline-flex",
          alignItems: "center",
          gap: 8,
          color: "rgba(255,255,255,0.6)",
          fontSize: 13,
          textDecoration: "none",
          marginBottom: 32,
          letterSpacing: "0.02em",
        }}
      >
        ← Volver a la guía
      </a>

      <div
        style={{
          display: "flex",
          alignItems: "center",
          gap: 14,
          marginBottom: 24,
        }}
      >
        <span className="hairline" style={{ background: "var(--champagne)" }} />
        <span
          className="uppercase-eyebrow"
          style={{ color: "var(--champagne)" }}
        >
          {article.tag} · Lectura {article.read}
        </span>
      </div>

      <h1
        className="serif"
        style={{
          fontSize: "clamp(36px, 6vw, 76px)",
          lineHeight: 1.05,
          fontWeight: 400,
          color: "var(--white)",
          letterSpacing: "-0.02em",
          maxWidth: 980,
          marginBottom: 28,
        }}
      >
        {article.title}
      </h1>

      <p
        style={{
          fontSize: 20,
          lineHeight: 1.5,
          color: "rgba(255,255,255,0.78)",
          maxWidth: 720,
          fontWeight: 300,
          marginBottom: 28,
        }}
      >
        {article.subtitle}
      </p>

      <div
        className="mono"
        style={{
          fontSize: 12,
          color: "rgba(255,255,255,0.55)",
          letterSpacing: "0.12em",
          textTransform: "uppercase",
          display: "flex",
          gap: 24,
          flexWrap: "wrap",
        }}
      >
        <span>{article.author}</span>
        <span>—</span>
        <span>{article.date}</span>
      </div>
    </div>
  </section>
);

// Featured image slot
const ArticleImage = ({ article }) => {
  if (!article.image) return null;
  return (
    <div className="container" style={{ marginTop: -40, marginBottom: 64 }}>
      <div
        style={{
          aspectRatio: "16/9",
          maxWidth: 1100,
          margin: "0 auto",
          overflow: "hidden",
          borderRadius: 4,
          boxShadow: "0 30px 80px rgba(11, 37, 69, 0.18)",
        }}
      >
        <img
          src={article.image}
          alt={article.title}
          style={{
            width: "100%",
            height: "100%",
            objectFit: "cover",
            display: "block",
          }}
        />
      </div>
    </div>
  );
};

// Body with sidebar TOC
const ArticleBody = ({ article }) => {
  const headings = article.body
    .map((b, idx) => ({ ...b, idx }))
    .filter((b) => b.type === "h2");

  return (
    <section style={{ background: "var(--white)", padding: "0 0 96px" }}>
      <div className="container">
        <div
          style={{
            display: "grid",
            gridTemplateColumns: "1fr 3fr",
            gap: 80,
            alignItems: "flex-start",
            maxWidth: 1100,
            margin: "0 auto",
          }}
          className="article-grid"
        >
          {/* Sidebar TOC */}
          <aside
            style={{
              position: "sticky",
              top: 120,
              alignSelf: "flex-start",
            }}
            className="article-toc"
          >
            <div
              className="uppercase-eyebrow"
              style={{ color: "var(--navy-deep)", marginBottom: 20 }}
            >
              En este artículo
            </div>
            <nav
              style={{
                display: "flex",
                flexDirection: "column",
                gap: 12,
                paddingLeft: 16,
                borderLeft: "1px solid var(--gray-line)",
              }}
            >
              {headings.map((h) => (
                <a
                  key={h.idx}
                  href={`#s-${h.idx}`}
                  style={{
                    color: "var(--gray-text)",
                    textDecoration: "none",
                    fontSize: 13,
                    lineHeight: 1.4,
                    transition: "color 0.2s",
                  }}
                  onMouseEnter={(e) =>
                    (e.currentTarget.style.color = "var(--navy-deep)")
                  }
                  onMouseLeave={(e) =>
                    (e.currentTarget.style.color = "var(--gray-text)")
                  }
                >
                  {h.text}
                </a>
              ))}
            </nav>
          </aside>

          {/* Body */}
          <article className="article-body" style={{ maxWidth: 720 }}>
            {article.body.map((block, idx) => (
              <ArticleBlock key={idx} block={block} idx={idx} />
            ))}
          </article>
        </div>
      </div>
    </section>
  );
};

// Related products card row
const RelatedProducts = ({ slugs, onSelect }) => {
  if (!slugs || slugs.length === 0) return null;
  const products = (window.PEPLAB_PRODUCTS || []).filter((p) =>
    slugs.includes(p.slug)
  );
  if (products.length === 0) return null;
  return (
    <section
      style={{
        background: "var(--ivory)",
        padding: "96px 0",
        borderTop: "1px solid rgba(201, 169, 97, 0.2)",
      }}
    >
      <div className="container">
        <div
          style={{
            display: "flex",
            alignItems: "center",
            gap: 14,
            marginBottom: 16,
          }}
        >
          <span className="hairline" />
          <span
            className="uppercase-eyebrow"
            style={{ color: "var(--navy-deep)" }}
          >
            Productos mencionados
          </span>
        </div>
        <h2
          className="serif"
          style={{
            fontSize: "clamp(28px, 3.5vw, 44px)",
            lineHeight: 1.1,
            color: "var(--navy-deep)",
            fontWeight: 400,
            marginBottom: 48,
          }}
        >
          Lo que aplica a este artículo.
        </h2>
        <div
          style={{
            display: "grid",
            gridTemplateColumns: `repeat(${Math.min(
              products.length,
              4
            )}, 1fr)`,
            gap: 24,
          }}
        >
          {products.map((p) => (
            <ProductCard key={p.slug} product={p} onSelect={onSelect} />
          ))}
        </div>
      </div>
    </section>
  );
};

// Related articles
const RelatedArticles = ({ slugs }) => {
  if (!slugs || slugs.length === 0) return null;
  const articles = slugs
    .map((s) => window.PEPLAB_ARTICLES[s])
    .filter(Boolean);
  if (articles.length === 0) return null;
  return (
    <section style={{ background: "var(--white)", padding: "96px 0" }}>
      <div className="container">
        <div
          style={{
            display: "flex",
            alignItems: "center",
            gap: 14,
            marginBottom: 16,
          }}
        >
          <span className="hairline" />
          <span
            className="uppercase-eyebrow"
            style={{ color: "var(--navy-deep)" }}
          >
            Sigue leyendo
          </span>
        </div>
        <h2
          className="serif"
          style={{
            fontSize: "clamp(28px, 3.5vw, 44px)",
            lineHeight: 1.1,
            color: "var(--navy-deep)",
            fontWeight: 400,
            marginBottom: 48,
          }}
        >
          Más sobre el tema.
        </h2>
        <div
          style={{
            display: "grid",
            gridTemplateColumns: `repeat(${Math.min(
              articles.length,
              3
            )}, 1fr)`,
            gap: 24,
          }}
        >
          {articles.map((a) => (
            <a
              key={a.slug}
              href={`/article/${a.slug}`}
              style={{
                display: "flex",
                flexDirection: "column",
                textDecoration: "none",
                color: "inherit",
                background: "var(--white)",
                border: "1px solid var(--gray-line)",
                borderRadius: 2,
                overflow: "hidden",
                transition: "all 0.3s",
              }}
              onMouseEnter={(e) => {
                e.currentTarget.style.transform = "translateY(-4px)";
                e.currentTarget.style.boxShadow =
                  "0 18px 40px rgba(11,37,69,0.10)";
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.transform = "none";
                e.currentTarget.style.boxShadow = "none";
              }}
            >
              <div style={{ aspectRatio: "16/10", overflow: "hidden" }}>
                {a.image ? (
                  <img
                    src={a.image}
                    alt={a.title}
                    loading="lazy"
                    decoding="async"
                    style={{
                      width: "100%",
                      height: "100%",
                      objectFit: "cover",
                      display: "block",
                    }}
                  />
                ) : (
                  <div className="lifestyle-placeholder">
                    <span className="placeholder-label dark">
                      EDITORIAL · {a.tag.toUpperCase()}
                    </span>
                  </div>
                )}
              </div>
              <div
                style={{
                  padding: "24px 22px 28px",
                  display: "flex",
                  flexDirection: "column",
                  flex: 1,
                }}
              >
                <div
                  className="mono"
                  style={{
                    fontSize: 10,
                    color: "var(--champagne)",
                    letterSpacing: "0.15em",
                    textTransform: "uppercase",
                    marginBottom: 12,
                  }}
                >
                  {a.tag} · {a.read}
                </div>
                <h3
                  className="serif"
                  style={{
                    fontSize: 20,
                    lineHeight: 1.2,
                    color: "var(--navy-deep)",
                    fontWeight: 500,
                    marginBottom: 12,
                    flex: 1,
                  }}
                >
                  {a.title}
                </h3>
                <div
                  style={{
                    color: "var(--navy-deep)",
                    fontWeight: 600,
                    fontSize: 12,
                    display: "inline-flex",
                    alignItems: "center",
                    gap: 6,
                  }}
                >
                  Leer <ArrowRight size={11} />
                </div>
              </div>
            </a>
          ))}
        </div>
      </div>
    </section>
  );
};

// Article CTA at end
const ArticleCTA = () => (
  <section
    style={{
      background: "var(--navy-deep)",
      color: "var(--white)",
      padding: "96px 0",
      textAlign: "center",
    }}
  >
    <div className="container">
      <PlMolecule size={48} color="var(--champagne)" />
      <h2
        className="serif"
        style={{
          fontSize: "clamp(32px, 4.5vw, 56px)",
          lineHeight: 1.05,
          fontWeight: 400,
          marginTop: 24,
          marginBottom: 16,
          letterSpacing: "-0.015em",
        }}
      >
        ¿Te quedaron dudas?
      </h2>
      <p
        style={{
          fontSize: 18,
          color: "rgba(255,255,255,0.7)",
          maxWidth: 540,
          margin: "0 auto 36px",
          lineHeight: 1.55,
          fontWeight: 300,
        }}
      >
        Escríbenos por WhatsApp y resolvemos cualquier consulta antes de tu
        pedido.
      </p>
      <a href={waUrl("Hola, tengo dudas sobre péptidos.")} target="_blank" rel="noopener noreferrer" className="btn btn-whatsapp">
        <WhatsAppIcon size={16} color="white" />
        Conversemos por WhatsApp
      </a>
    </div>
  </section>
);

// 404 article
const ArticleNotFound = () => (
  <section
    style={{
      minHeight: "70vh",
      display: "flex",
      alignItems: "center",
      justifyContent: "center",
      padding: "120px 0",
    }}
  >
    <div className="container" style={{ textAlign: "center" }}>
      <div
        className="uppercase-eyebrow"
        style={{ color: "var(--champagne)", marginBottom: 12 }}
      >
        Error 404
      </div>
      <h1
        className="serif"
        style={{
          fontSize: "clamp(36px, 5vw, 56px)",
          color: "var(--navy-deep)",
          fontWeight: 400,
          marginBottom: 24,
        }}
      >
        Artículo no encontrado.
      </h1>
      <p
        style={{
          fontSize: 17,
          color: "var(--gray-text)",
          maxWidth: 480,
          margin: "0 auto 32px",
          lineHeight: 1.6,
        }}
      >
        El artículo que buscas no existe o fue movido. Volvé al hub editorial
        para ver los disponibles.
      </p>
      <a href="/#articulos" className="btn btn-primary">
        Ver todos los artículos
      </a>
    </div>
  </section>
);

// Main App for /article route
function ArticleApp() {
  const [tweaks, setTweak] = useTweaks(
    /*EDITMODE-BEGIN*/ { aesthetic: "editorial", showAgeGate: true, motion: "high" } /*EDITMODE-END*/
  );
  const [scrolled, setScrolled] = useStateA(false);
  const [ageOk, setAgeOk] = useStateA(!tweaks.showAgeGate || ageVerified());
  const [activeProduct, setActiveProduct] = useStateA(null);
  const [cartOpen, setCartOpen] = useStateA(false);

  useEffectA(() => {
    const onScroll = () => setScrolled(window.scrollY > 60);
    window.addEventListener("scroll", onScroll);
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  useEffectA(() => {
    document.body.classList.toggle("reduce-motion", tweaks.motion === "low");
  }, [tweaks.motion]);

  // Restore aesthetic from localStorage
  const aestheticInitRef = React.useRef(false);
  useEffectA(() => {
    if (aestheticInitRef.current) return;
    aestheticInitRef.current = true;
    try {
      const saved = localStorage.getItem("peplab-aesthetic");
      if (saved && saved !== tweaks.aesthetic) setTweak("aesthetic", saved);
    } catch (e) {}
  }, []);

  useEffectA(() => {
    if (window.applyAesthetic) window.applyAesthetic(tweaks.aesthetic);
    try {
      localStorage.setItem("peplab-aesthetic", tweaks.aesthetic);
    } catch (e) {}
  }, [tweaks.aesthetic]);

  const slug = getSlugFromUrl();
  const article = slug ? window.PEPLAB_ARTICLES[slug] : null;

  // Update document title and meta dynamically
  useEffectA(() => {
    if (article) {
      document.title = `${article.title} · PepLab Co`;
      const desc = document.querySelector('meta[name="description"]');
      if (desc) desc.setAttribute("content", article.subtitle);
    }
  }, [article]);

  return (
    <div>
      <PlHeader scrolled={scrolled || true} onCartOpen={() => setCartOpen(true)} />
      <main>
        {article ? (
          <>
            <ArticleHero article={article} />
            <ArticleImage article={article} />
            <ArticleBody article={article} />
            <RelatedProducts
              slugs={article.relatedProducts}
              onSelect={setActiveProduct}
            />
            <RelatedArticles slugs={article.related} />
            <ArticleCTA />
          </>
        ) : (
          <ArticleNotFound />
        )}
      </main>
      <PlFooter />
      <StickyWA />
      <AestheticToggle
        aesthetic={tweaks.aesthetic}
        onChange={(v) => setTweak("aesthetic", v)}
      />

      {!ageOk && <AgeGate onPass={() => { markAgeVerified(); setAgeOk(true); }} />}
      <ProductDrawer
        product={activeProduct}
        onClose={() => setActiveProduct(null)}
      />
      <CartDrawer open={cartOpen} onClose={() => setCartOpen(false)} />
      <CartToast onCartOpen={() => setCartOpen(true)} />
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<ArticleApp />);
