// playlists.jsx — "WHERE THE RAVEN NESTS"
// Single Supabase table `diaval_playlists` with `by_artist` flag.
// Two visual groups in one section: curated FOR Diaval (by_artist=false) on top,
// curated BY Diaval (by_artist=true) underneath. Same compact row format.

function StatBar({ value, max, color, dim, height = 6 }) {
  const pct = Math.min(1, value / Math.max(max, 1));
  return (
    <div style={{ height, background: dim, position: "relative", overflow: "hidden" }}>
      <div style={{ position: "absolute", top: 0, left: 0, height: "100%", width: `${pct * 100}%`, background: color }} />
    </div>
  );
}

function PlaylistRow({ p, i, total, hoverIdx, setHoverIdx, maxFollowers, S }) {
  const { isMobile } = (window.useViewport ? window.useViewport() : { isMobile: false });
  const followers = p.followers ?? 0;
  const hoverKey = `${p.by_artist ? "by" : "for"}-${i}`;
  const isHovered = hoverIdx === hoverKey;
  const sharedBg = isHovered ? S.concrete : (p.accent ? "rgba(190,33,30,0.04)" : "transparent");

  // Mobile: card layout — stacked rows, one playlist = one card
  if (isMobile) {
    return (
      <div
        onClick={() => p.spotify_url && window.open(p.spotify_url, "_blank", "noreferrer")}
        style={{
          position: "relative", overflow: "hidden",
          padding: "18px 14px",
          borderBottom: i < total - 1 ? `1px solid ${S.concreteHi}` : "none",
          cursor: p.spotify_url ? "pointer" : "default",
          background: p.accent ? "rgba(190,33,30,0.04)" : "transparent",
        }}>
        {/* Blurred cover-as-row-background */}
        {p.cover_url && (
          <>
            <div aria-hidden="true" style={{
              position: "absolute", inset: 0,
              backgroundImage: `url(${p.cover_url})`,
              backgroundSize: "cover", backgroundPosition: "center",
              filter: "blur(22px) saturate(1.35)",
              opacity: 0.24,
              transform: "scale(1.15)",
              pointerEvents: "none",
              zIndex: 0,
            }} />
            <div aria-hidden="true" style={{
              position: "absolute", inset: 0,
              background: "linear-gradient(180deg, rgba(2,3,10,0.85) 0%, rgba(2,3,10,0.55) 100%)",
              pointerEvents: "none",
              zIndex: 1,
            }} />
          </>
        )}
        <div style={{ position: "relative", zIndex: 2 }}>
        {/* row 1: # + cover + name + arrow */}
        <div style={{
          display: "grid",
          gridTemplateColumns: p.cover_url ? "32px 56px 1fr 20px" : "32px 1fr 20px",
          gap: 10, alignItems: "center", marginBottom: 8,
        }}>
          <div style={{ fontFamily: S.display, fontSize: 16, color: S.ash, letterSpacing: "-0.01em" }}>
            {String(i + 1).padStart(2, "0")}
          </div>
          {p.cover_url && (
            <img src={p.cover_url} alt="" loading="lazy"
              style={{ width: 56, height: 56, objectFit: "cover", border: `1px solid ${S.concreteHi}`, display: "block" }} />
          )}
          <div style={{ fontFamily: S.display, fontSize: 16, color: S.bone, letterSpacing: "0.02em", lineHeight: 1.2 }}>
            {window.decodeHtml(p.name)}
          </div>
          <div style={{ textAlign: "right" }}>
            <Glyph name="arrow" size={14} color={S.ashDim} />
          </div>
        </div>

        {/* row 2: curator/by-line */}
        <div style={{ paddingLeft: 42, fontSize: 12, color: S.ash, fontFamily: S.meta, fontStyle: "italic", marginBottom: 10 }}>
          {window.decodeHtml(p.curator) || (p.by_artist ? "by D//V" : "")}
        </div>

        {/* row 3: followers + (quality OR by-the-artist tag) */}
        <div style={{ paddingLeft: 42, display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14, marginBottom: 10 }}>
          <div>
            <div style={{ fontSize: 12, color: S.ashDim, letterSpacing: "0.25em", marginBottom: 2 }}>FOLLOWERS</div>
            <div style={{ fontFamily: S.display, fontSize: 16, color: S.bone, letterSpacing: "-0.01em", marginBottom: 4 }}>
              {followers.toLocaleString()}
            </div>
            <StatBar value={followers} max={maxFollowers} color={S.bloodHot} dim={S.concreteHi} />
          </div>
          {p.quality != null && (
            <div>
              <div style={{ fontSize: 12, color: S.ashDim, letterSpacing: "0.25em", marginBottom: 2 }}>QUALITY</div>
              <div style={{ display: "flex", alignItems: "baseline", gap: 4, marginBottom: 4 }}>
                <span style={{ fontFamily: S.display, fontSize: 16, color: p.quality >= 85 ? S.bloodHot : S.bone }}>{p.quality}</span>
                <span style={{ fontSize: 12, color: S.ashDim, letterSpacing: "0.2em" }}>/100</span>
              </div>
              <StatBar value={p.quality} max={100} color={p.quality >= 85 ? S.bloodHot : S.bone} dim={S.concreteHi} height={4} />
            </div>
          )}
        </div>

        {/* row 4: description for by-artist playlists only — FEAT. TRACK hidden
            (per-track feature can change; just show curator description if any) */}
        {p.by_artist && p.description && (
          <div style={{ paddingLeft: 42 }}>
            <div style={{ fontSize: 12, color: S.ash, fontFamily: S.meta, fontStyle: "italic", lineHeight: 1.5 }}>
              {window.decodeHtml(p.description)}
            </div>
          </div>
        )}

        </div>
      </div>
    );
  }

  // Desktop: 4-column row (FEAT. TRACK + QUALITY cells removed; remaining
  // columns expand horizontally to fill the freed space)
  const cols = "44px 3.6fr 1.4fr 36px";
  return (
    <div
      onMouseEnter={() => setHoverIdx(hoverKey)}
      onMouseLeave={() => setHoverIdx(null)}
      onClick={() => p.spotify_url && window.open(p.spotify_url, "_blank", "noreferrer")}
      style={{
        position: "relative", overflow: "hidden",
        padding: "20px 16px", borderBottom: i < total - 1 ? `1px solid ${S.concreteHi}` : "none",
        cursor: p.spotify_url ? "pointer" : "default",
        background: sharedBg,
        transition: "background .15s",
      }}>
      {/* Blurred cover-as-row-background — subtle color bleed without overpowering text */}
      {p.cover_url && (
        <>
          <div aria-hidden="true" style={{
            position: "absolute", inset: 0,
            backgroundImage: `url(${p.cover_url})`,
            backgroundSize: "cover", backgroundPosition: "center",
            filter: "blur(22px) saturate(1.35)",
            opacity: isHovered ? 0.32 : 0.22,
            transform: "scale(1.15)",
            pointerEvents: "none",
            transition: "opacity .2s",
            zIndex: 0,
          }} />
          <div aria-hidden="true" style={{
            position: "absolute", inset: 0,
            background: "linear-gradient(90deg, rgba(2,3,10,0.88) 0%, rgba(2,3,10,0.6) 55%, rgba(2,3,10,0.4) 100%)",
            pointerEvents: "none",
            zIndex: 1,
          }} />
        </>
      )}
      <div style={{
        position: "relative", zIndex: 2,
        display: "grid", gridTemplateColumns: cols, columnGap: 24,
        alignItems: "center",
      }}>
      <div style={{
        fontFamily: S.display, fontSize: 18, color: isHovered ? S.bloodHot : S.ash,
        letterSpacing: "-0.01em",
      }}>
        {String(i + 1).padStart(2, "0")}
      </div>
      <div style={{ display: "flex", alignItems: "center", gap: 16 }}>
        {p.cover_url && (
          <img src={p.cover_url} alt="" loading="lazy"
            style={{
              width: 62, height: 62, objectFit: "cover",
              border: `1px solid ${S.concreteHi}`, flexShrink: 0, display: "block",
            }} />
        )}
        <div style={{ minWidth: 0 }}>
          <div style={{ fontFamily: S.display, fontSize: 17, color: S.bone, letterSpacing: "0.02em", marginBottom: 4 }}>
            {window.decodeHtml(p.name)}
          </div>
          <div style={{ fontSize: 12, color: S.ash, letterSpacing: "0.04em", fontFamily: S.meta, marginBottom: p.by_artist && p.description ? 6 : 0 }}>
            {window.decodeHtml(p.curator) || (p.by_artist ? "by D//V" : "")}
          </div>
          {p.by_artist && p.description && (
            <div style={{ fontSize: 12, color: S.ash, fontFamily: S.meta, fontStyle: "italic", letterSpacing: "0.02em", lineHeight: 1.45 }}>
              {window.decodeHtml(p.description)}
            </div>
          )}
        </div>
      </div>
      <div style={{ alignSelf: "center" }}>
        <div style={{ fontFamily: S.display, fontSize: 18, color: S.bone, letterSpacing: "-0.01em" }}>
          {followers.toLocaleString()}
        </div>
        <div style={{ marginTop: 6, width: "85%" }}>
          <StatBar value={followers} max={maxFollowers} color={S.bloodHot} dim={S.concreteHi} />
        </div>
      </div>
      <div style={{ textAlign: "right", alignSelf: "center" }}>
        <Glyph name="arrow" size={14} color={isHovered ? S.bloodHot : S.ashDim} />
      </div>
      </div>
    </div>
  );
}

function PlaylistsPage({ tab, onTabChange }) {
  const S = window.shellStyles;
  const { isMobile } = (window.useViewport ? window.useViewport() : { isMobile: false });
  const [hoverIdx, setHoverIdx] = React.useState(null);
  const [playlists, setPlaylists] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [loadError, setLoadError] = React.useState(null);

  React.useEffect(() => {
    let cancelled = false;
    window.diavalSupabase
      .from("diaval_playlists")
      .select("name, curator, description, followers, quality, since, track, note, spotify_url, by_artist, accent, position, cover_url")
      .eq("is_published", true)
      .order("by_artist", { ascending: true })
      .order("position", { ascending: true })
      .then(({ data, error }) => {
        if (cancelled) return;
        if (error) setLoadError(error.message);
        else setPlaylists(data ?? []);
        setLoading(false);
      });
    return () => { cancelled = true; };
  }, []);

  const curatedFor = playlists.filter(p => !p.by_artist);
  const curatedBy = playlists.filter(p => p.by_artist);
  const allFollowers = playlists.map(p => p.followers || 0);
  const maxFollowers = allFollowers.length ? Math.max(...allFollowers, 1) : 1;
  const colHeader = "44px 3.6fr 1.4fr 36px";

  return (
    <Shell tab={tab} onTabChange={onTabChange} page="005" broadcast="PLAYLISTS · WHERE THE RAVEN NESTS">
      <div style={{
        position: isMobile ? "relative" : "absolute",
        inset: isMobile ? "auto" : 0,
        overflow: isMobile ? "visible" : "auto",
      }}>
        {/* page header */}
        <div style={{ padding: isMobile ? "20px 16px 16px" : "32px 56px 20px", borderBottom: `1px solid ${S.concreteHi}` }}>
          <div style={{ fontSize: 12, color: S.bloodHot, letterSpacing: "0.3em", marginBottom: 8 }}>
            // V. PLAYLISTS · WHERE THE RAVEN NESTS
          </div>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", gap: 32 }}>
            <h2 style={{
              margin: 0, fontFamily: S.display, fontSize: isMobile ? 28 : 56, lineHeight: 0.92,
              letterSpacing: "-0.02em", color: S.bone,
            }}>
              SMALL ROOMS, <span style={{ color: S.bloodHot }}>LOUD ECHO.</span>
            </h2>
          </div>
        </div>

        {loading && (
          <div style={{ padding: "60px 56px", textAlign: "center", fontSize: 13, color: S.ashDim, letterSpacing: "0.3em" }}>
            ⸺ TUNING SIGNAL ⸺
          </div>
        )}
        {loadError && !loading && (
          <div style={{ padding: "40px 56px", border: `1px solid ${S.bloodHot}`, borderLeft: `3px solid ${S.bloodHot}`, margin: 24 }}>
            <div style={{ fontSize: 13, color: S.bloodHot, letterSpacing: "0.3em", marginBottom: 8 }}>◢ PLAYLIST FEED CORRUPTED</div>
            <div style={{ fontSize: 13, color: S.ash, fontStyle: "italic" }}>{loadError}</div>
          </div>
        )}

        {/* GROUP 1 — CURATED FOR DIAVAL */}
        {!loading && !loadError && curatedFor.length > 0 && (
          <section style={{ padding: isMobile ? "24px 16px" : "40px 56px 32px" }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 24, gap: 24 }}>
              <div>
                <div style={{ fontSize: 12, color: S.ashDim, letterSpacing: "0.4em", marginBottom: 6 }}>
                  ⸺ SECTION 01 ⸺
                </div>
                <h3 style={{
                  margin: 0, fontFamily: S.display, fontSize: 32, color: S.bone,
                  letterSpacing: "-0.01em",
                }}>
                  CURATED <span style={{ color: S.bloodHot }}>FOR</span> DIAVAL
                </h3>
                <div style={{ fontSize: 13, color: S.ash, marginTop: 6, fontStyle: "italic", letterSpacing: "0.02em" }}>
                  playlists that chose him · social proof, by the numbers
                </div>
              </div>
              <div style={{ textAlign: "right", fontSize: 12, color: S.ash, letterSpacing: "0.25em", lineHeight: 1.7 }}>
                <div><span style={{ color: S.bone, fontFamily: S.display, fontSize: 22 }}>{curatedFor.length.toString().padStart(2,"0")}</span>  PLAYLISTS</div>
                <div><span style={{ color: S.bone, fontFamily: S.display, fontSize: 22 }}>{curatedFor.reduce((a,b)=>a+(b.followers||0),0).toLocaleString()}</span>  COMBINED REACH</div>
              </div>
            </div>

            <div style={{ border: `1px solid ${S.concreteHi}` }}>
              {/* header row — hidden on mobile (cards don't need it) */}
              {!isMobile && (
                <div style={{
                  display: "grid", gridTemplateColumns: colHeader, columnGap: 24,
                  padding: "10px 16px", borderBottom: `1px solid ${S.concreteHi}`,
                  fontSize: 12, color: S.ashDim, letterSpacing: "0.3em", background: S.raven,
                }}>
                  <div>#</div>
                  <div>PLAYLIST · CURATOR</div>
                  <div>FOLLOWERS</div>
                  <div></div>
                </div>
              )}
              {curatedFor.map((p, i) => (
                <PlaylistRow key={`for-${i}`} p={p} i={i} total={curatedFor.length}
                  hoverIdx={hoverIdx} setHoverIdx={setHoverIdx} maxFollowers={maxFollowers} S={S} />
              ))}
            </div>
          </section>
        )}

        {/* GROUP 2 — CURATED BY DIAVAL */}
        {!loading && !loadError && curatedBy.length > 0 && (
          <section style={{
            padding: isMobile ? "24px 16px 32px" : "40px 56px 56px",
            borderTop: `1px solid ${S.concreteHi}`,
            background: `linear-gradient(180deg, ${S.raven} 0%, #050505 100%)`,
          }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 24, gap: 24 }}>
              <div>
                <div style={{ fontSize: 12, color: S.ashDim, letterSpacing: "0.4em", marginBottom: 6 }}>
                  ⸺ SECTION 02 ⸺
                </div>
                <h3 style={{
                  margin: 0, fontFamily: S.display, fontSize: 32, color: S.bone,
                  letterSpacing: "-0.01em",
                }}>
                  CURATED <span style={{ color: S.bloodHot }}>BY</span> DIAVAL
                </h3>
                <div style={{ fontSize: 13, color: S.ash, marginTop: 6, fontStyle: "italic", letterSpacing: "0.02em" }}>
                  his picks · taste proof, by the raven
                </div>
              </div>
              <div style={{ textAlign: "right", fontSize: 12, color: S.ash, letterSpacing: "0.25em", lineHeight: 1.7 }}>
                <div><span style={{ color: S.bone, fontFamily: S.display, fontSize: 22 }}>{curatedBy.length.toString().padStart(2,"0")}</span>  PLAYLISTS</div>
              </div>
            </div>

            <div style={{ border: `1px solid ${S.concreteHi}` }}>
              {!isMobile && (
                <div style={{
                  display: "grid", gridTemplateColumns: colHeader, columnGap: 24,
                  padding: "10px 16px", borderBottom: `1px solid ${S.concreteHi}`,
                  fontSize: 12, color: S.ashDim, letterSpacing: "0.3em", background: S.raven,
                }}>
                  <div>#</div>
                  <div>PLAYLIST · BY</div>
                  <div>FOLLOWERS</div>
                  <div></div>
                </div>
              )}
              {curatedBy.map((p, i) => (
                <PlaylistRow key={`by-${i}`} p={p} i={i} total={curatedBy.length}
                  hoverIdx={hoverIdx} setHoverIdx={setHoverIdx} maxFollowers={maxFollowers} S={S} />
              ))}
            </div>
          </section>
        )}
      </div>
    </Shell>
  );
}

window.PlaylistsPage = PlaylistsPage;
