/* global React, ReactDOM, BlogNav, PostCard, PostViz, Newsletter, Footer, LANES, POSTS, ALL_TOPICS, ALL_INDUSTRIES, ALL_MODES, Tag, Confidence, postHref */

function BlogIndex() {
  const [lane, setLane] = React.useState("all");
  const [topic, setTopic] = React.useState("all");
  const [industry, setIndustry] = React.useState("All");
  const [mode, setMode] = React.useState("All modes");

  const today = React.useMemo(() => new Date(), []);
  const published = React.useMemo(
    () => POSTS
      .filter((p) => new Date(p.publishAt) <= today)
      .sort((a, b) => new Date(b.publishAt) - new Date(a.publishAt)),
    [today]
  );

  const filtered = React.useMemo(() => {
    return published.filter((p) => {
      if (lane !== "all" && p.lane !== lane) return false;
      if (topic !== "all" && !p.tags.includes(topic)) return false;
      if (industry !== "All" && p.industry !== industry) return false;
      if (mode !== "All modes" && p.mode !== mode) return false;
      return true;
    });
  }, [published, lane, topic, industry, mode]);

  const featured = published.find((p) => p.featured) || published[0];
  const featuredVisible = featured && filtered.includes(featured);
  const gridPosts = filtered.filter((p) => !featuredVisible || p.id !== featured.id);

  const counts = {
    all: published.length,
    index: published.filter((p) => p.lane === "index").length,
    report: published.filter((p) => p.lane === "report").length,
    field: published.filter((p) => p.lane === "field").length,
    case: published.filter((p) => p.lane === "case").length,
  };

  return (
    <div className="blog-page app" data-density="comfortable">
      <BlogNav active="blog" />

      {/* HERO */}
      <header className="blog-hero">
        <div className="container">
          <div className="blog-hero__grid">
            <div>
              <div className="eyebrow">RESOURCES · THE EVIDENCE PRACTICE</div>
              <h1 className="blog-hero__title">
                Research writing for people who <em>defend</em> decisions.
              </h1>
            </div>
            <div className="blog-hero__meta">
              <div className="blog-hero__meta-label">PUBLISHED · MAY 2026</div>
              <div className="blog-hero__counts">
                <div><strong>{counts.index}</strong>Index</div>
                <div><strong>{counts.report}</strong>Reports</div>
                <div><strong>{counts.field}</strong>Field</div>
                <div><strong>{counts.case}</strong>Cases</div>
              </div>
            </div>
          </div>
        </div>
      </header>

      {/* FILTERS */}
      <div className="container">
        <div className="blog-filters">
          <div className="blog-filters__group">
            <span className="blog-filters__label">LANE</span>
            <FilterChip on={lane === "all"} onClick={() => setLane("all")}>All</FilterChip>
            {Object.entries(LANES).map(([k, v]) => (
              <FilterChip key={k} on={lane === k} onClick={() => setLane(k)}>{v.label}</FilterChip>
            ))}
          </div>
          <div className="blog-filters__divider" />
          <div className="blog-filters__group">
            <span className="blog-filters__label">TOPIC</span>
            <FilterChip on={topic === "all"} onClick={() => setTopic("all")}>any</FilterChip>
            {["methodology", "ux", "synthetic", "pricing", "onboarding", "video", "brand", "ethics"].map((t) => (
              <FilterChip key={t} on={topic === t} onClick={() => setTopic(t)}>#{t}</FilterChip>
            ))}
          </div>
          <div className="blog-filters__divider" />
          <div className="blog-filters__group">
            <span className="blog-filters__label">INDUSTRY</span>
            <select className="blog-filters__chip"
              value={industry} onChange={(e) => setIndustry(e.target.value)}
              style={{ appearance: "none", paddingRight: 22, backgroundImage: "linear-gradient(45deg, transparent 50%, var(--fg-muted) 50%), linear-gradient(135deg, var(--fg-muted) 50%, transparent 50%)", backgroundPosition: "calc(100% - 12px) 12px, calc(100% - 7px) 12px", backgroundSize: "5px 5px", backgroundRepeat: "no-repeat" }}>
              {ALL_INDUSTRIES.map((x) => <option key={x} value={x}>{x}</option>)}
            </select>
          </div>
          <div className="blog-filters__group">
            <span className="blog-filters__label">MODE</span>
            <select className="blog-filters__chip"
              value={mode} onChange={(e) => setMode(e.target.value)}
              style={{ appearance: "none", paddingRight: 22, backgroundImage: "linear-gradient(45deg, transparent 50%, var(--fg-muted) 50%), linear-gradient(135deg, var(--fg-muted) 50%, transparent 50%)", backgroundPosition: "calc(100% - 12px) 12px, calc(100% - 7px) 12px", backgroundSize: "5px 5px", backgroundRepeat: "no-repeat" }}>
              {ALL_MODES.map((x) => <option key={x} value={x}>{x}</option>)}
            </select>
          </div>
          <div style={{ marginLeft: "auto", fontFamily: "var(--mono)", fontSize: 11, color: "var(--fg-dim)", letterSpacing: "0.06em" }}>
            {filtered.length}/{published.length} RESULTS
          </div>
        </div>
      </div>

      {/* FEATURED POST */}
      {featuredVisible && (
        <section className="container">
          <div className="featured">
            <div className="featured__copy">
              <div className="featured__eyebrow">
                <b>{LANES[featured.lane].short}</b>
                <span>·</span>
                <span>FEATURED</span>
                <span>·</span>
                <span>{featured.read}</span>
              </div>
              <h2 className="featured__title">{featured.title}</h2>
              <p className="featured__lede">{featured.excerpt}</p>
              <div className="featured__byline">
                <strong>{featured.author.name}</strong>
                <span>{featured.author.role}</span>
                <span>{featured.date}</span>
              </div>
              <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginTop: 4 }}>
                {featured.tags.map((t) => <Tag key={t}>#{t}</Tag>)}
              </div>
              <div style={{ marginTop: 12 }}>
                <a href={postHref(featured)} className="btn btn--primary">
                  Read the essay <span className="btn-arrow">→</span>
                </a>
              </div>
            </div>
            <FeaturedViz />
          </div>
        </section>
      )}

      {/* POST GRID */}
      <section className="container">
        <div className="posts">
          {gridPosts.map((p, i) => <PostCard key={p.id} post={p} index={i} />)}
        </div>
      </section>

      {/* NEWSLETTER */}
      <section className="container">
        <Newsletter />
      </section>

      <Footer />
    </div>
  );
}

function FilterChip({ on, onClick, children }) {
  return (
    <button className="blog-filters__chip" aria-pressed={on ? "true" : "false"} onClick={onClick}>
      {children}
    </button>
  );
}

// Featured visual — a collaged "evidence trail"
function FeaturedViz() {
  return (
    <div className="featured__viz">
      <div style={{ position: "absolute", inset: 0, background: "radial-gradient(ellipse 60% 50% at 80% 20%, color-mix(in oklab, var(--accent) 10%, transparent), transparent 60%)" }} />
      <div className="card__label" style={{ position: "relative", zIndex: 1 }}>
        <span className="card__label-dot" /> EVIDENCE TRAIL · 14 LINKS
      </div>
      <div style={{ position: "relative", zIndex: 1, marginTop: 18, display: "flex", flexDirection: "column", gap: 10 }}>
        <div style={{ padding: "10px 12px", border: "1px solid var(--border)", borderRadius: 8, background: "var(--bg-elev-2)" }}>
          <div style={{ fontFamily: "var(--mono)", fontSize: 10, color: "var(--fg-dim)", letterSpacing: "0.1em", marginBottom: 4 }}>RECOMMENDATION</div>
          <div style={{ fontSize: 14, fontWeight: 500, letterSpacing: "-0.005em" }}>Surface 'what's included' above the pricing CTA</div>
        </div>
        <div style={{ display: "flex", gap: 12, paddingLeft: 24, fontFamily: "var(--mono)", fontSize: 10, color: "var(--fg-dim)" }}>↓ traces to</div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
          <div style={{ padding: 10, border: "1px solid var(--border)", borderRadius: 6, background: "var(--bg)", fontSize: 12 }}>
            <div style={{ fontFamily: "var(--mono)", fontSize: 9, color: "var(--accent)", letterSpacing: "0.1em", marginBottom: 4 }}>CLIP · 02:14</div>
            <div style={{ color: "var(--fg-muted)", fontStyle: "italic" }}>"didn't explain what's included…"</div>
          </div>
          <div style={{ padding: 10, border: "1px solid var(--border)", borderRadius: 6, background: "var(--bg)", fontSize: 12 }}>
            <div style={{ fontFamily: "var(--mono)", fontSize: 9, color: "var(--accent)", letterSpacing: "0.1em", marginBottom: 4 }}>SIGNAL</div>
            <div style={{ color: "var(--fg-muted)" }}>Hesitation +42% at CTA</div>
          </div>
          <div style={{ padding: 10, border: "1px solid var(--border)", borderRadius: 6, background: "var(--bg)", fontSize: 12 }}>
            <div style={{ fontFamily: "var(--mono)", fontSize: 9, color: "var(--accent)", letterSpacing: "0.1em", marginBottom: 4 }}>SEGMENT</div>
            <div style={{ color: "var(--fg-muted)" }}>Mid-market · 8/12 agree</div>
          </div>
          <div style={{ padding: 10, border: "1px solid var(--border)", borderRadius: 6, background: "var(--bg)", fontSize: 12 }}>
            <div style={{ fontFamily: "var(--mono)", fontSize: 9, color: "var(--accent)", letterSpacing: "0.1em", marginBottom: 4 }}>CLIPS</div>
            <div style={{ color: "var(--fg-muted)" }}>+11 more supporting</div>
          </div>
        </div>
        <div style={{ marginTop: 6 }}>
          <Confidence pct={0.86} />
        </div>
      </div>
    </div>
  );
}

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