// VariationDense — desktop V3 layout for the news article.
// Three-column grid: 180px TOC / minmax(0,1fr) body / 280px promo + most-read.
// Reading progress bar wired to scroll position.

function CDReadingProgressBar({ height = 4 }) {
  const [pct, setPct] = cdUseState(0);

  cdUseEffect(() => {
    let raf = null;
    const update = () => {
      raf = null;
      const article = document.getElementById('cd-article-grid');
      if (!article) return;
      const articleTop = article.getBoundingClientRect().top + window.scrollY;
      const articleHeight = article.offsetHeight;
      const vh = window.innerHeight;
      const denom = Math.max(1, articleHeight - vh);
      const raw = (window.scrollY - articleTop) / denom;
      const clamped = Math.max(0, Math.min(1, raw));
      setPct(clamped);
    };
    const onScroll = () => {
      if (raf == null) {
        raf = window.requestAnimationFrame(update);
      }
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    update();
    return () => {
      window.removeEventListener('scroll', onScroll);
      if (raf != null) window.cancelAnimationFrame(raf);
    };
  }, []);

  return (
    <div
      role="progressbar"
      aria-valuemin="0"
      aria-valuemax="100"
      aria-valuenow={Math.round(pct * 100)}
      aria-label="Article reading progress"
      style={{ height: height, background: "#eee", overflow: "hidden" }}
    >
      <div style={{ width: `${pct * 100}%`, height: "100%", background: "#000", transition: "width 80ms linear" }} />
    </div>
  );
}

function VariationDense({ topic, mostRead, bodySize = 18 }) {
  const sections = [
    { id: "h2-1", label: topic.h2_1 },
    { id: "h2-2", label: topic.h2_2 },
    { id: "h2-3", label: topic.h2_3 },
    { id: "h2-4", label: topic.h2_4 },
  ];

  const onTocClick = (e, id) => {
    e.preventDefault();
    const el = document.getElementById(id);
    if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
  };

  return (
    <div className="cd-page-root" style={{ background: "#fff", color: "#000" }}>
      <CDMasthead dense />
      <article
        className="cd-article-container"
        style={{ maxWidth: 1280, margin: "0 auto", padding: "24px 32px 0" }}
      >
        <CDSectionLabel section={topic.section} eyebrow={topic.eyebrow} />
        <div
          id="cd-article-grid"
          className="cd-article-grid"
          style={{
            display: "grid",
            gridTemplateColumns: "180px minmax(0, 1fr) 280px",
            gap: 40,
            marginTop: 16,
            alignItems: "start",
          }}
        >
          {/* Left rail: TOC + reading progress */}
          <aside
            className="cd-left-rail"
            style={{
              position: "sticky",
              top: 24,
              fontFamily: "var(--body-font)",
              fontSize: 12,
            }}
          >
            <div
              style={{
                fontSize: 10,
                letterSpacing: 1.5,
                textTransform: "uppercase",
                fontWeight: 700,
                marginBottom: 12,
                paddingBottom: 8,
                borderBottom: "2px solid #000",
              }}
            >
              In this article
            </div>
            <ol style={{ margin: 0, padding: 0, listStyle: "none" }}>
              {sections.map((s, i) => (
                <li
                  key={s.id}
                  style={{ padding: "10px 0", borderBottom: "1px solid #eee", display: "flex", gap: 8 }}
                >
                  <span style={{ color: "#999", minWidth: 16 }}>{String(i + 1).padStart(2, "0")}</span>
                  <a
                    href={`#${s.id}`}
                    onClick={(e) => onTocClick(e, s.id)}
                    style={{
                      fontWeight: 500,
                      lineHeight: 1.35,
                      color: "#000",
                      textDecoration: "none",
                    }}
                  >
                    {s.label}
                  </a>
                </li>
              ))}
            </ol>
            <div style={{ marginTop: 24, paddingTop: 16, borderTop: "2px solid #000" }}>
              <div
                style={{
                  fontSize: 10,
                  letterSpacing: 1.5,
                  textTransform: "uppercase",
                  fontWeight: 700,
                  marginBottom: 8,
                }}
              >
                Reading progress
              </div>
              <CDReadingProgressBar />
              <div style={{ marginTop: 6, fontSize: 11, color: "#666" }}>{topic.readTime}</div>
            </div>
          </aside>

          {/* Center column: article body */}
          <div>
            <h1
              style={{
                fontFamily: "var(--headline-font)",
                fontWeight: 800,
                fontSize: 44,
                lineHeight: 1.08,
                letterSpacing: -0.8,
                margin: "8px 0 14px",
                textWrap: "balance",
              }}
            >
              {topic.headline}
            </h1>
            <p
              style={{
                fontFamily: "var(--body-font)",
                fontSize: 19,
                lineHeight: 1.5,
                color: "#333",
                margin: "0 0 22px",
              }}
            >
              {topic.dek}
            </p>
            <div
              style={{
                borderTop: "1px solid #000",
                borderBottom: "1px solid #ccc",
                padding: "12px 0",
                marginBottom: 24,
              }}
            >
              <CDByline
                author={topic.author}
                title={topic.authorTitle}
                date={topic.date}
                readTime={topic.readTime}
              />
            </div>
            <figure style={{ margin: 0, marginBottom: 28 }}>
              <img
                src="/images/hero.jpg"
                alt="A residential Australian kitchen mid-renovation, with exposed timber framing and dust sheets visible. Editorial illustration."
                style={{
                  width: "100%",
                  aspectRatio: "16/9",
                  objectFit: "cover",
                  display: "block",
                  border: "1px solid #d6d6d6",
                }}
              />
              <figcaption
                style={{
                  marginTop: 8,
                  fontSize: 12,
                  lineHeight: 1.4,
                  color: "#5a5a5a",
                  fontFamily: "var(--body-font)",
                }}
              >
                <span style={{ color: "#000", fontWeight: 600 }}>Photograph </span>
                ConstructionDaily / Investigative photography. Image illustrative — no specific contract or homeowner pictured.
              </figcaption>
            </figure>
            <CDArticleBody topic={topic} bodySize={bodySize} />
            <CDInlinePromo />
            <CDArticleBodyTail topic={topic} bodySize={bodySize} />
          </div>

          {/* Right rail: sticky promo + most read */}
          <div className="cd-right-rail">
            <CDSidebarPromo sticky compact />
            <div style={{ marginTop: 28 }}>
              <div
                style={{
                  fontFamily: "var(--body-font)",
                  fontSize: 10,
                  letterSpacing: 1.5,
                  textTransform: "uppercase",
                  fontWeight: 700,
                  marginBottom: 10,
                  paddingBottom: 6,
                  borderBottom: "1px solid #000",
                }}
              >
                Most read this week
              </div>
              {mostRead.map((t, i) => (
                <div
                  key={t}
                  style={{
                    padding: "10px 0",
                    borderBottom: "1px solid #eee",
                    display: "flex",
                    gap: 10,
                  }}
                >
                  <span
                    style={{
                      fontFamily: "var(--headline-font)",
                      fontWeight: 800,
                      fontSize: 22,
                      color: "#bbb",
                      minWidth: 24,
                    }}
                  >
                    {i + 1}
                  </span>
                  <span
                    style={{
                      fontFamily: "var(--headline-font)",
                      fontSize: 14,
                      lineHeight: 1.3,
                      fontWeight: 600,
                    }}
                  >
                    {t}
                  </span>
                </div>
              ))}
            </div>
          </div>
        </div>
      </article>
    </div>
  );
}

window.CDVariationDense = VariationDense;
