// DeepDives — the /deep-dives archive.
//
// Reads the thin public.deep_dives registry (published rows only, via RLS),
// newest first. Hero = the flagged `featured` row (fallback: most recent). Grid
// = the rest, paginated client-side (~PER_PAGE per "Load more"), since the set
// grows ~52/year. Cards/hero link to /deep-dive/{slug}; the dossier lives there.
//
// Layout (v2 redesign): a full-width dark weekly-email banner is the page
// headline; below it, on the cream, a de-boxed editorial hero and a de-boxed
// 4-up archive gallery. Each entry carries its emailed-Wednesday date. The
// banner's subscribe control reuses the shared <NewsletterSignup> (same handler
// + `subscribers` write as the footer/homepage) — no parallel signup path.
function DeepDives({ onDeepDive, onHome }) {
  const { useState, useEffect } = React;
  const CFG = window.BBR_DEEPDIVES || {};
  const LABEL = CFG.LABEL || "Deep Dives";
  const PER_PAGE = CFG.PER_PAGE || 12;

  const [rows, setRows] = useState(undefined); // undefined = loading
  const [pillar, setPillar] = useState(null);
  const [shown, setShown] = useState(PER_PAGE);

  useEffect(() => {
    let active = true;
    if (!window.BBR_supabase) { setRows([]); return; }
    window.BBR_supabase
      .from("deep_dives")
      .select("*")
      .eq("status", "published")
      .order("published_at", { ascending: false })
      .then(({ data }) => { if (active) setRows(Array.isArray(data) ? data : []); })
      .catch(() => { if (active) setRows([]); });
    return () => { active = false; };
  }, []);

  const coverFor = (r) => r.cover_url || ("/covers/" + r.slug + ".jpg");
  const onImgError = (e) => { e.target.style.visibility = "hidden"; };

  // Emailed-date eyebrow. Dives are published Sun/Mon but go out as the
  // Wednesday broadcast, so we surface that Wednesday. A date still in the
  // future (not yet sent) reads "EMAILS …"; a past one "EMAILED …". Real data
  // only: no published_at → no line (never fabricate a date). UTC so the stored
  // 07:00Z Wednesday renders as Wednesday for every viewer.
  const emailedLine = (r) => {
    if (!r || !r.published_at) return null;
    const d = new Date(r.published_at);
    if (isNaN(d.getTime())) return null;
    const dow = d.toLocaleDateString("en-GB", { weekday: "short", timeZone: "UTC" }).toUpperCase();
    const day = d.toLocaleDateString("en-GB", { day: "numeric", timeZone: "UTC" });
    const mon = d.toLocaleDateString("en-GB", { month: "short", timeZone: "UTC" }).toUpperCase();
    const verb = d.getTime() > Date.now() ? "EMAILS" : "EMAILED";
    return verb + " " + dow + " " + day + " " + mon + " " + d.getUTCFullYear();
  };

  if (rows === undefined) {
    return <div className="dd-state" style={{ maxWidth: 640, margin: "16vh auto", textAlign: "center", opacity: 0.7 }}>Loading…</div>;
  }

  // Pillars present across the set (for the optional filter chips).
  const pillars = [...new Set(rows.map(r => r.pillar).filter(Boolean))];

  // Featured hero: the flagged row, else the most recent.
  const hero = rows.find(r => r.featured) || rows[0] || null;

  // The grid is everything except the hero, filtered by the active pillar.
  let grid = rows.filter(r => !hero || r.id !== hero.id);
  if (pillar) grid = grid.filter(r => r.pillar === pillar);
  const visible = grid.slice(0, shown);

  const heroDate = emailedLine(hero);

  return (
    <>
      {/* 4a — full-width weekly-email banner: the headline of the page */}
      <section className="dd-banner">
        <div className="dd-banner-inner">
          <span className="dd-banner-eyebrow">A new dossier, every week</span>
          <h1 className="dd-banner-head">One record beyond the hundred, in your inbox <span className="dd-em">every Wednesday.</span></h1>
          <p className="dd-banner-sub">The full Lead-In treatment — the essay, the pressings, the history — on one album outside the ranked hundred. Subscribe and never miss a week.</p>
          {window.NewsletterSignup && (
            <div className="dd-banner-form">
              <NewsletterSignup variant="banner" source="deep-dives" />
            </div>
          )}
        </div>
      </section>

      <div className="dd-archive">
        {!rows.length && (
          <div className="dd-empty" style={{ textAlign: "center", opacity: 0.7, padding: "40px 0" }}>
            No deep dives published yet. Check back soon.
          </div>
        )}

        {/* 4b — featured hero, de-boxed on the cream */}
        {hero && (
          <button className="dd-hero" onClick={() => onDeepDive(hero.slug)} aria-label={"Read " + hero.title}>
            <div className="dd-hero-cover">
              <img src={coverFor(hero)} alt={hero.title + " — " + hero.artist} loading="lazy" onError={onImgError} />
            </div>
            <div className="dd-hero-body">
              <span className="dd-hero-eyebrow">Latest deep dive</span>
              {heroDate && <span className="dd-date">{heroDate}</span>}
              <h2 className="dd-hero-title">{hero.title}</h2>
              <div className="dd-hero-meta">{[hero.artist, hero.year].filter(Boolean).join(" · ")}</div>
              {hero.excerpt && <p className="dd-hero-excerpt">{hero.excerpt}</p>}
              <span className="dd-hero-cta">Read the dossier →</span>
            </div>
          </button>
        )}

        {pillars.length > 0 && (
          <div className="dd-filters">
            <button className={"dd-filter" + (pillar === null ? " is-active" : "")} onClick={() => { setPillar(null); setShown(PER_PAGE); }}>All</button>
            {pillars.map(p => (
              <button key={p} className={"dd-filter" + (pillar === p ? " is-active" : "")} onClick={() => { setPillar(p); setShown(PER_PAGE); }}>{p}</button>
            ))}
          </div>
        )}

        {/* 4c — de-boxed archive gallery */}
        {visible.length > 0 && (
          <section className="dd-archive-sec">
            <div className="dd-sec-eyebrow">The Archive · Every dive so far</div>
            <div className="dd-grid">
              {visible.map(r => {
                const d = emailedLine(r);
                return (
                  <button key={r.id} className="dd-card" onClick={() => onDeepDive(r.slug)} aria-label={"Read " + r.title}>
                    <div className="dd-card-cover">
                      <img src={coverFor(r)} alt={r.title + " — " + r.artist} loading="lazy" onError={onImgError} />
                    </div>
                    <div className="dd-card-body">
                      {d && <span className="dd-date dd-date-sm">{d}</span>}
                      <h3 className="dd-card-title">{r.title}</h3>
                      <div className="dd-card-meta">{[r.artist, r.year].filter(Boolean).join(" · ")}</div>
                    </div>
                  </button>
                );
              })}
            </div>
          </section>
        )}

        {shown < grid.length && (
          <div className="dd-more">
            <button className="cta cta-ghost" onClick={() => setShown(s => s + PER_PAGE)}>Load more</button>
          </div>
        )}
      </div>
    </>
  );
}

window.DeepDives = DeepDives;
