/* Faderhead – Signal · Album page (ONE layout for every release).
   Hero (cover + album platform links) + optional video embed + tracklist.
   Loaded AFTER sig-catalog-links.jsx, sig-music.jsx and sig-album-content.jsx. */
/* global React, BroadcastBar, TopNav, NewsletterSignal, FooterSignal,
   Platform, RELEASES, ALBUMS, ALBUM_CONTENT, TrackNotes, TrackLinks,
   CATALOG_LINKS */

/* ── YouTube video embed helper ─────────────────────────
   Accepts a plain youtube.com/watch?v= or youtu.be/ URL.
   Returns an embed src string, or null for playlists / invalid URLs
   (playlists are already linked via the YouTube Music platform button). */
function ytEmbedSrc(url) {
  if (!url) return null;
  const videoMatch = url.match(/[?&]v=([^&]+)/);
  if (videoMatch) return "https://www.youtube.com/embed/" + videoMatch[1] + "?rel=0";
  const shortMatch = url.match(/youtu\.be\/([^?&]+)/);
  if (shortMatch) return "https://www.youtube.com/embed/" + shortMatch[1] + "?rel=0";
  return null; // playlist or unknown — skip embed
}

/* ── YouTube video section ───────────────────────────
   Click-to-play: thumbnail shown by default, swaps to iframe on click.
   Avoids iframe sandbox errors in the prototype preview; on the real site
   the iframe loads directly on click. */
function AlbumVideoEmbed({ url, compact }) {
  if (!url) return null;
  const [playing, setPlaying] = React.useState(false);

  let watchUrl = url;
  const shortMatch = url.match(/youtu\.be\/([^?&]+)/);
  if (shortMatch) watchUrl = "https://www.youtube.com/watch?v=" + shortMatch[1];

  const videoMatch = watchUrl.match(/[?&]v=([^&]+)/);
  const videoId = videoMatch ? videoMatch[1] : null;
  if (!videoId) return null;

  const thumb = `https://i.ytimg.com/vi/${videoId}/hqdefault.jpg`;
  const embedSrc = `https://www.youtube.com/embed/${videoId}?autoplay=1&rel=0`;

  return (
    <section className="sig-section" style={{ marginTop: compact ? 28 : 48 }}>
      <div className="sig-section-head">
        <h2 className="sig-section-h">Music Video</h2>
      </div>
      <div className="sig-video-card" style={{ maxWidth: 560 }}>
        {playing ? (
          <div className="sig-video-thumb">
            <iframe
              src={embedSrc}
              title="Music video"
              allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
              allowFullScreen
              style={{ position: "absolute", inset: 0, width: "100%", height: "100%", border: 0 }}
            ></iframe>
          </div>
        ) : (
          <button
            className="sig-video-thumb sig-video-thumb-btn"
            onClick={() => setPlaying(true)}
            aria-label="Play video"
          >
            <img src={thumb} alt="" className="sig-video-thumb-img" />
            <div className="sig-video-play">▶</div>
          </button>
        )}
        {!playing && (
          <a href={watchUrl} target="_blank" rel="noopener noreferrer" className="sig-video-cta mono">
            Watch on YouTube ↗
          </a>
        )}
      </div>
    </section>
  );
}

/* ── Platform buttons built from CATALOG_LINKS ──────── */
const PLATFORM_DEFS = [
  { key: "spotify",       name: "Spotify" },
  { key: "apple",         name: "Apple Music",    abbr: "AM" },
  { key: "youtube_music", name: "YouTube Music",  abbr: "YT" },
  { key: "amazon",        name: "Amazon Music",   abbr: "AZ" },
  { key: "bandcamp",      name: "Bandcamp",       abbr: "BC" },
];

function AlbumPlatforms({ albumId }) {
  const links = (window.CATALOG_LINKS || {})[albumId] || {};
  const available = PLATFORM_DEFS.filter((p) => links[p.key]);
  if (!available.length) {
    return (
      <p className="mono" style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 20 }}>
        // streaming links being added – check back soon.
      </p>
    );
  }
  return (
    <div className="sig-platforms">
      {available.map((p) => (
        <Platform key={p.key} name={p.name} abbr={p.abbr} url={links[p.key]} />
      ))}
    </div>
  );
}

/* ── Track row ───────────────────────────────────────── */
function TrackRow({ track, compact }) {
  const [open, setOpen] = React.useState(false);
  const hasNotes = !!(track.note || track.image || track.watch);
  const hasLinks = !!(track.links && Object.keys(track.links).length > 0);
  const hasExpander = hasNotes || hasLinks;

  const toggleLabel = open
    ? "close −"
    : hasNotes && hasLinks ? "notes & links +"
    : hasNotes ? "notes +"
    : hasLinks ? "links +"
    : "";

  return (
    <div className={`sig-trk${track.hot ? " hot" : ""}${hasExpander ? " notes" : ""}${open ? " open" : ""}`}>
      <div className="sig-trk-head" onClick={hasExpander ? () => setOpen((o) => !o) : undefined}>
        <span className="sig-trk-n">{String(track.n).padStart(2, "0")}</span>
        <div className="sig-trk-main">
          <span className="sig-trk-t">{track.t}</span>
        </div>
        <span className="sig-trk-r">{track.run || ""}</span>
        <span className={`sig-trk-x${hasNotes ? " accent" : ""}`}>{toggleLabel}</span>
      </div>
      {open && hasExpander && (
        <div className="sig-trk-body">
          <TrackLinks links={track.links} />
          <TrackNotes note={track.note} image={track.image} video={track.video} watch={track.watch} />
        </div>
      )}
    </div>
  );
}

/* ── Back to music button ───────────────────────────── */
function BackToMusic({ go, from, compact }) {
  return (
    <div style={{ padding: compact ? "20px 0 0" : "28px 0 0" }}>
      <button
        onClick={() => go({ name: "music", tab: from })}
        className="mono"
        style={{ background: "none", border: "none", cursor: "pointer", padding: 0,
          fontSize: 12, letterSpacing: "0.1em", color: "var(--ink-3)",
          display: "flex", alignItems: "center", gap: 6 }}
      >← BACK TO MUSIC</button>
    </div>
  );
}

/* ── Album page ──────────────────────────────────────── */
function SigAlbum({ compact, albumId }) {
  const album = RELEASES.find((a) => a.id === albumId) || ALBUMS[0];
  const content = ALBUM_CONTENT[album.id] || {};
  const tracks = content.tracks || [];
  const links = (window.CATALOG_LINKS || {})[album.id] || {};

  const albIdx = ALBUMS.findIndex((a) => a.id === album.id);
  const kindLabel = album.kind === "ep" ? "EP" : album.kind === "single" ? "single" : album.kind === "compilation" ? "compilation" : "album";
  const posLabel = albIdx > -1 ? ` ${12 - albIdx} of 12` : "";

  const { route, go } = window.useNav();

  return (
    <>
      <BroadcastBar compact={compact} />
      <TopNav compact={compact} crumb={!compact && `/ MUSIC / ${album.title.toUpperCase()}`} />

      <div className="sig-shell">
        {/* Hero */}
        <section className="sig-alb-hero">
          <div>
            <div className="sig-eyebrow accent">// {kindLabel}{posLabel} · {album.year}{album.label ? ` · ${album.label}` : ""}</div>
            <h1 className="sig-alb-title">{album.title}</h1>
            <div className="sig-tags">
              {album.tracks && <span className="fh-tag">{album.tracks} tracks</span>}
              {album.feat && <span className="fh-tag">feat. {album.feat}</span>}
            </div>
            {content.blurb && (
              <p style={{ fontSize: compact ? 14 : 17, lineHeight: 1.55, color: "var(--ink-2)", maxWidth: 560, margin: "0 0 24px 0", textWrap: "pretty" }}>
                {content.blurb}
              </p>
            )}
            <AlbumPlatforms albumId={album.id} />
          </div>

          <div>
            {(() => {
              const cover = (window.COVERS || {})[album.id];
              return cover ? (
                <img src={cover} alt={`${album.title} cover art`} className="sig-cover" style={{ objectFit: "cover", objectPosition: "center top", display: "block" }} />
              ) : (
                <div className="sig-cover sig-ph">
                  <div>album cover · 1500 × 1500<small>{album.title.toLowerCase()} · {album.year}</small></div>
                </div>
              );
            })()}
            <div className="sig-cover-meta">
              <span>RELEASE · {content.releaseDate || album.year}</span>
              <span>{album.label ? `LABEL · ${album.label}` : album.kind ? album.kind.toUpperCase() : ""}</span>
            </div>
          </div>
        </section>

        {/* Back to music — above video */}
        <BackToMusic go={go} from={route.from} compact={compact} />

        {/* Music video embed — driven by the track with watch:"main", falls back to catalog-level video */}
        {(() => {
          const mainTrack = tracks.find((t) => t.watch === "main");
          const mainUrl = mainTrack ? mainTrack.video : links.video;
          return <AlbumVideoEmbed url={mainUrl} compact={compact} />;
        })()}

        {/* Tracklist */}
        <section className="sig-section" style={{ marginTop: compact ? 28 : 48 }}>
          <div className="sig-section-head">
            <h2 className="sig-section-h">Tracklist</h2>
            <div className="sig-section-meta">{tracks.length ? `${tracks.length} tracks` : "coming soon"}</div>
          </div>
          {tracks.length ? (
            <div className="sig-tracks">
              {tracks.map((t) => <TrackRow key={t.n} track={t} compact={compact} />)}
            </div>
          ) : (
            <div className="sig-more">// tracklist &amp; per-track links for {album.title.toLowerCase()} are being added.</div>
          )}
        </section>

        {/* Back to music — below tracklist */}
        <BackToMusic go={go} from={route.from} compact={compact} />

        {content.outro && (
          <section className="sig-section" style={{ marginTop: compact ? 24 : 40 }}>
            <div className="sig-section-head">
              <h2 className="sig-section-h">Overall Thoughts on This Album</h2>
            </div>
            <div style={{ fontSize: compact ? 14 : 16, lineHeight: 1.65, color: "var(--ink-2)", maxWidth: 640, textWrap: "pretty" }}>
              {typeof content.outro === 'string'
                ? content.outro.split('\\n\\n').map((p, i) => <p key={i} style={{ margin: "0 0 0.75em 0" }}>{p}</p>)
                : content.outro}
            </div>
          </section>
        )}

        <div style={{ marginTop: compact ? 32 : 56 }}>
          <NewsletterSignal compact={compact} />
        </div>
        <div style={{ marginTop: compact ? 32 : 56 }}>
          <FooterSignal compact={compact} />
        </div>
      </div>
    </>
  );
}

window.SigAlbum = SigAlbum;
