// BROADSHEET — dense multi-column newsprint grid.

const SOCIAL_ICONS = {
  instagram: (
    <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <rect x="3" y="3" width="18" height="18" rx="5" />
      <circle cx="12" cy="12" r="4" />
      <circle cx="17.5" cy="6.5" r="1" fill="currentColor" stroke="none" />
    </svg>
  ),
  youtube: (
    <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor" aria-hidden="true">
      <path d="M23 7.2a3 3 0 0 0-2.1-2.1C19.1 4.6 12 4.6 12 4.6s-7.1 0-8.9.5A3 3 0 0 0 1 7.2 31 31 0 0 0 .5 12 31 31 0 0 0 1 16.8a3 3 0 0 0 2.1 2.1c1.8.5 8.9.5 8.9.5s7.1 0 8.9-.5a3 3 0 0 0 2.1-2.1c.4-1.6.5-3.2.5-4.8s-.1-3.2-.5-4.8zM9.8 15.5V8.5l6.2 3.5-6.2 3.5z" />
    </svg>
  ),
  facebook: (
    <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor" aria-hidden="true">
      <path d="M22 12a10 10 0 1 0-11.6 9.9V14.9H7.9V12h2.5V9.8c0-2.5 1.5-3.9 3.7-3.9 1.1 0 2.2.2 2.2.2v2.5h-1.3c-1.2 0-1.6.8-1.6 1.6V12h2.7l-.4 2.9h-2.3v7A10 10 0 0 0 22 12z" />
    </svg>
  ),
  tiktok: (
    <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor" aria-hidden="true">
      <path d="M19.6 6.7a4.7 4.7 0 0 1-3.5-1.6 4.7 4.7 0 0 1-1.2-2.6V2h-3.4v13.4a2.5 2.5 0 1 1-1.8-2.4V9.5a5.9 5.9 0 1 0 5.2 5.9V9.6a8 8 0 0 0 4.7 1.5V7.8a4.7 4.7 0 0 1 0-1.1z" />
    </svg>
  ),
  spotify: (
    <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor" aria-hidden="true">
      <path d="M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20zm4.6 14.4a.6.6 0 0 1-.9.2c-2.4-1.5-5.5-1.8-9.1-1a.6.6 0 1 1-.3-1.2c4-.9 7.4-.5 10.1 1.1.3.2.4.6.2.9zm1.2-2.8a.8.8 0 0 1-1 .3c-2.8-1.7-7-2.2-10.3-1.2a.8.8 0 1 1-.4-1.4c3.7-1.1 8.4-.6 11.6 1.4.3.2.4.7.1 1zm.1-2.9C14.5 8.7 9.4 8.5 6.4 9.4a.9.9 0 1 1-.5-1.7c3.5-1.1 9.1-.9 12.7 1.2a.9.9 0 0 1-.9 1.6z" />
    </svg>
  ),
  soundcloud: (
    <svg viewBox="0 0 24 24" width="20" height="16" fill="currentColor" aria-hidden="true">
      <path d="M1 16.5h1V11h-1v5.5zm2.2 0h1V10h-1v6.5zm2.2 0h1V9h-1v7.5zm2.2 0h1V8.5h-1v8zm2.2 0h1V8h-1v8.5zm2.3 0h9.4a3 3 0 0 0 0-6 3.5 3.5 0 0 0-.6 0 5 5 0 0 0-9.7-.7v6.7h.9z" />
    </svg>
  ),
};

const SOCIAL_ORDER = ['instagram', 'youtube', 'spotify', 'soundcloud', 'tiktok', 'facebook'];

function RecentSubmissions({ limit = 8 }) {
  const [tracks, setTracks] = useState([]);
  const [status, setStatus] = useState('loading');

  useEffect(() => {
    let alive = true;
    fetch('recent-submissions.php?limit=' + limit, { cache: 'no-store' })
      .then(r => r.ok ? r.json() : Promise.reject(new Error('HTTP ' + r.status)))
      .then(j => { if (!alive) return; setTracks(Array.isArray(j.tracks) ? j.tracks : []); setStatus('ready'); })
      .catch(() => { if (alive) setStatus('error'); });
    return () => { alive = false; };
  }, [limit]);

  if (status === 'loading') {
    return <div className="gkr-label" style={{ padding: '10px 0' }}>Loading submissions…</div>;
  }
  if (status === 'error' || !tracks.length) {
    return (
      <div className="gkr-label" style={{ padding: '10px 0', lineHeight: 1.5 }}>
        Inbox is quiet. <a href="#/artist-promotion" style={{ color: 'var(--accent)' }}>Send your track →</a>
      </div>
    );
  }

  return (
    <div style={{ display: 'grid', gap: 10, marginTop: 8 }}>
      {tracks.map((t, i) => {
        const audioUrl = t.uploadedFile || '';
        const isAudio = /\.(wav|mp3|m4a)$/i.test(audioUrl);
        const socials = t.socials || {};
        return (
          <article key={i} className="gkr-headline" style={{ paddingBottom: 12, borderBottom: '1px dashed var(--rule)' }}>
            <div style={{ display: 'flex', gap: 8, alignItems: 'center', marginBottom: 8 }}>
              <span className="gkr-kicker gkr-kicker--live">SUBMITTED</span>
              {t.genre && <span className="gkr-label">{t.genre}</span>}
              <span className="gkr-label" style={{ marginLeft: 'auto' }}>{timeAgo(t.submittedAt) || 'just now'}</span>
            </div>
            <h3 className="gkr-display" style={{ fontSize: 20, margin: '0 0 4px', textTransform: 'uppercase', letterSpacing: '-0.01em' }}>
              {t.trackTitle || 'Untitled'}
            </h3>
            <div style={{ fontFamily: 'var(--serif)', fontStyle: 'italic', fontSize: 14, color: 'var(--sub)', margin: '0 0 8px' }}>
              by {t.artistName || 'Unknown artist'}
            </div>
            {isAudio && (
              <audio controls preload="none" src={audioUrl} style={{ width: '100%', height: 32, marginBottom: 8 }} />
            )}
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 10, fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '.12em', textTransform: 'uppercase' }}>
              {audioUrl && !isAudio && (
                <a href={audioUrl} target="_blank" rel="noopener noreferrer" style={{ color: 'var(--accent, var(--fg))' }}>↓ FILE</a>
              )}
              {t.musicLink && (
                <a href={t.musicLink} target="_blank" rel="noopener noreferrer" style={{ color: 'var(--accent, var(--fg))' }}>♪ LINK</a>
              )}
              {t.website && (
                <a href={t.website} target="_blank" rel="noopener noreferrer" style={{ color: 'var(--accent, var(--fg))' }}>SITE</a>
              )}
              {SOCIAL_ORDER.map((key) => {
                const url = socials[key];
                if (!url) return null;
                return (
                  <a
                    key={key}
                    href={url}
                    target="_blank"
                    rel="noopener noreferrer"
                    title={key.charAt(0).toUpperCase() + key.slice(1)}
                    aria-label={key}
                    style={{ color: 'var(--accent, var(--fg))', display: 'inline-flex', alignItems: 'center' }}
                  >
                    {SOCIAL_ICONS[key]}
                  </a>
                );
              })}
            </div>
          </article>
        );
      })}
    </div>
  );
}

function EditorialDesk({ limit = 5 }) {
  const [posts, setPosts] = useState([]);
  const [status, setStatus] = useState('loading');

  useEffect(() => {
    let alive = true;
    fetch('/blog/posts.json', { cache: 'no-store' })
      .then(r => r.ok ? r.json() : Promise.reject(new Error('HTTP ' + r.status)))
      .then(j => {
        if (!alive) return;
        const list = Array.isArray(j.posts) ? j.posts.slice(0, limit) : [];
        setPosts(list);
        setStatus('ready');
      })
      .catch(() => { if (alive) setStatus('error'); });
    return () => { alive = false; };
  }, [limit]);

  if (status !== 'ready' || !posts.length) return null;

  const lead = posts[0];
  const rest = posts.slice(1);

  return (
    <>
      <div style={{ height: 22 }} />
      <SectionHead kicker="GKR EDITORIAL DESK" title="WRITTEN BY THE EDITORS" rightNote="DAILY · NOON ET" />
      <div className="gkr-editorial-grid" style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 28, marginTop: 14 }}>
        <article className="gkr-headline" style={{ borderTop: '2px solid var(--accent)', paddingTop: 14 }}>
          <div className="gkr-label" style={{ marginBottom: 6, color: 'var(--accent)' }}>
            EDITORIAL · {lead.date}{lead.word_count ? ` · ${lead.word_count} WORDS` : ''}
          </div>
          <h2 className="gkr-display" style={{ fontSize: 46, lineHeight: 1.02, letterSpacing: '-0.02em', margin: '0 0 12px' }}>
            <a href={`/blog/${lead.slug}.html`} style={{ color: 'var(--fg)', textDecoration: 'none' }}>{lead.title}</a>
          </h2>
          <p className="gkr-serif" style={{ fontSize: 18, lineHeight: 1.4, color: 'var(--sub)', fontStyle: 'italic', margin: '0 0 12px' }}>
            {lead.dek}
          </p>
          {Array.isArray(lead.tags) && lead.tags.length > 0 && (
            <div className="gkr-label" style={{ color: 'var(--accent)' }}>
              {lead.tags.slice(0, 5).join(' · ')}
            </div>
          )}
          <div style={{ marginTop: 12 }}>
            <a className="gkr-chip" href={`/blog/${lead.slug}.html`}>→ READ THE EDITORIAL</a>
          </div>
        </article>
        <div style={{ display: 'grid', gap: 14 }}>
          {rest.map(p => (
            <article key={p.slug} style={{ paddingBottom: 12, borderBottom: '1px dashed var(--rule)' }}>
              <div className="gkr-label" style={{ marginBottom: 4 }}>EDITORIAL · {p.date}</div>
              <h3 className="gkr-display" style={{ fontSize: 18, lineHeight: 1.1, margin: '0 0 6px' }}>
                <a href={`/blog/${p.slug}.html`} style={{ color: 'var(--fg)', textDecoration: 'none' }}>{p.title}</a>
              </h3>
              <p className="gkr-serif" style={{ fontSize: 13, lineHeight: 1.35, color: 'var(--sub)', fontStyle: 'italic', margin: 0 }}>
                {p.dek}
              </p>
            </article>
          ))}
          <div>
            <a className="gkr-label" href="/blog.html" style={{ color: 'var(--accent)', textDecoration: 'none' }}>→ ALL EDITORIALS</a>
          </div>
        </div>
      </div>
    </>
  );
}

function Broadsheet() {
  const { data, openArticle, previewTrack, playPodcast } = useGKR();
  const { breaking, lead, releases, reviews, tours, features, charts, podcasts, videos } = data;

  return (
    <div className="gkr-art gkr-broadsheet" style={{ padding: 24 }}>
      <Masthead />
      <div style={{ marginTop: 10 }}>
        <LiveBar now={data.now} />
      </div>
      <Ticker items={breaking} />

      {/* GKR EDITORIAL DESK — original writing, surfaced above third-party news */}
      <EditorialDesk limit={5} />

      {/* LEAD + SIDEBAR */}
      <div style={{ height: 28 }} />
      <SectionHead kicker="FROM AROUND THE WEB" title="TODAY IN HIP-HOP NEWS" rightNote="SOURCED FEED" />
      <div className="gkr-broadsheet__grid" style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 28, marginTop: 14 }}>
        <div>
          <div className="gkr-label" style={{ marginBottom: 6 }}>{lead.kicker} · {lead.genre} · {lead.reading} MIN</div>
          <h2 className="gkr-display gkr-lead-title" style={{ fontSize: 92, margin: '0 0 10px', letterSpacing: '-0.02em' }}>{lead.title}</h2>
          <p className="gkr-serif" style={{ fontSize: 22, lineHeight: 1.3, margin: '0 0 14px', color: 'var(--sub)' }}>{lead.dek}</p>
          <div className="gkr-lead-actions" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '6px 0', borderTop: '1px solid var(--rule)', borderBottom: '1px solid var(--rule)' }}>
            <span className="gkr-label">{lead.byline}</span>
            <div style={{ display: 'flex', gap: 8 }}>
              <button className="gkr-chip" onClick={() => openArticle(lead)}>→ READ THE FEATURE</button>
              <ShareButton item={lead} />
            </div>
          </div>
          <div style={{ marginTop: 14 }}>
            <Placeholder tag={lead.genre} caption="COVER / FEATURE PHOTO" ratio="16 / 9" image={lead.image} alt={`Cover image for: ${lead.title}`} />
          </div>
          {(() => {
            const body = (lead.body && lead.body.length) ? lead.body : (lead.dek ? [lead.dek] : []);
            if (!body.length) return null;
            return (
              <div className="gkr-lead-body" style={{ columnCount: 2, columnGap: 24, fontFamily: 'var(--serif)', fontSize: 15, lineHeight: 1.45, color: 'var(--fg)', marginTop: 16 }}>
                {body.map((p, i) => {
                  const first = p.charAt(0);
                  const rest = p.slice(1);
                  const isLast = i === body.length - 1;
                  return (
                    <p key={i} style={{ margin: isLast ? 0 : '0 0 10px' }}>
                      {i === 0
                        ? <><span style={{ fontFamily: 'var(--display)', fontSize: 44, float: 'left', lineHeight: 0.85, padding: '4px 8px 0 0' }}>{first}</span>{rest}</>
                        : p}
                    </p>
                  );
                })}
              </div>
            );
          })()}
        </div>

        {/* SIDEBAR */}
        <aside>
          <SectionHead kicker="DEMO INBOX" title="RECENTLY SUBMITTED TRACKS" rightNote="NEWEST FIRST" />
          <RecentSubmissions limit={8} />

          <div style={{ height: 22 }} />
          <SectionHead kicker="BILLBOARD" title="THE GKR 08" rightNote="WEEK 17" />
          <div style={{ marginTop: 8 }}>
            {charts.slice(0,8).map(c => <ChartRow key={c.rank} c={c} />)}
          </div>

          <div style={{ height: 22 }} />
          <SectionHead kicker="AIR TIME" title="PODCASTS" rightNote="NEW EPS" />
          <div style={{ marginTop: 8 }}>
            {podcasts.map(p => (
              <div key={p.id} onClick={(e) => e.target.tagName !== 'BUTTON' && p.link && window.open(p.link, '_blank', 'noopener,noreferrer')} style={{ display: 'grid', gridTemplateColumns: 'auto 1fr auto', gap: 10, padding: '10px 0', borderBottom: '1px dashed var(--rule)', alignItems: 'center', cursor: p.link ? 'pointer' : 'default' }}>
                <button className="gkr-chip gkr-chip--accent" onClick={(e) => { e.stopPropagation(); playPodcast(p); }} title="Play podcast episode">▶</button>
                <div>
                  <div style={{ fontFamily: 'var(--display)', fontSize: 14, textTransform: 'uppercase' }}>{p.show}</div>
                  <div className="gkr-label">{p.ep} · {p.title}</div>
                </div>
                <div className="gkr-label">{p.len}</div>
              </div>
            ))}
          </div>
        </aside>
      </div>

      {/* FEATURES ROW */}
      <div style={{ height: 28 }} />
      <SectionHead kicker="LONG READS" title="FEATURES & INTERVIEWS" rightNote="THIS WEEK" />
      <div className="gkr-feature-grid" style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 24, marginTop: 14 }}>
        {features.map(f => <HeadlineLarge key={f.id} item={f} onOpen={openArticle} />)}
      </div>

      {/* THREE-UP SECTIONS */}
      <div style={{ height: 28 }} />
      <div className="gkr-section-grid" style={{ display: 'grid', gridTemplateColumns: '1.1fr 1fr 1fr', gap: 28 }}>
        <div>
          <SectionHead kicker="NEW PRESSINGS" title="RELEASES" rightNote="CATALOG N°" />
          <div style={{ marginTop: 6 }}>
            {releases.map(r => <ReleaseCard key={r.id} r={r} onPreview={previewTrack} />)}
          </div>
        </div>
        <div>
          <SectionHead kicker="CRITICS" title="REVIEWS" rightNote="/10" />
          <div style={{ marginTop: 6 }}>
            {reviews.map(v => <ReviewCard key={v.id} v={v} onOpen={(x) => openArticle({ ...x, title: x.artist + ' — ' + x.title, kicker: 'REVIEW', dek: x.blurb })} />)}
          </div>
        </div>
        <div>
          <SectionHead kicker="ON THE ROAD" title="TOUR DATES" rightNote="NEXT 30 DAYS" />
          <div style={{ marginTop: 6 }}>
            {tours.map(t => <TourRow key={t.id} t={t} />)}
          </div>
          <div style={{ height: 16 }} />
          <Newsletter />
        </div>
      </div>

      {/* VIDEO ROW (YouTube trending music chart, COLORS fallback) */}
      {videos && videos.length > 0 && (
        <>
          <div style={{ height: 28 }} />
          <SectionHead kicker="GKR TV" title={`VIDEO · ${(videos[0] && videos[0].source) || 'TRENDING'}`} rightNote="LATEST" />
          <div className="gkr-video-grid" style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 24, marginTop: 14 }}>
            {videos.map(v => (
              <article key={v.id} className="gkr-headline" onClick={() => openArticle(v)}>
                <Placeholder tag={v.genre} caption={'VIDEO / ' + v.id.toUpperCase()} ratio="16 / 9" image={v.image} alt={`Video: ${v.title}${v.source ? ' (' + v.source + ')' : ''}`} />
                <div style={{ display: 'flex', gap: 8, alignItems: 'center', marginTop: 10 }}>
                  <span className="gkr-kicker gkr-kicker--live">VIDEO</span>
                  <span className="gkr-label">{v.genre}</span>
                  <span className="gkr-label" style={{ marginLeft: 'auto' }}>{v.time || v.source || 'COLORS'}</span>
                </div>
                <h3 className="gkr-display" style={{ fontSize: 22, margin: '10px 0 6px' }}>{v.title}</h3>
                {v.dek && <p className="gkr-serif" style={{ fontStyle: 'italic', fontSize: 14, color: 'var(--sub)', margin: 0, lineHeight: 1.3 }}>{v.dek}</p>}
              </article>
            ))}
          </div>
        </>
      )}

      {/* FOOTER */}
      <div style={{ height: 26 }} />
      <div className="gkr-hair-4" />
      <div className="gkr-footer-social" style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, padding: '14px 0', borderBottom: '1px solid var(--rule)', fontFamily: 'var(--mono)', fontSize: 11, letterSpacing: '.14em', textTransform: 'uppercase', color: 'var(--sub)', flexWrap: 'wrap' }}>
        <span>FOLLOW @GETKNOWNRADIO</span>
        <nav aria-label="Social media" style={{ display: 'flex', gap: 14, alignItems: 'center', flexWrap: 'wrap' }}>
          <a href="https://instagram.com/GetKnownRadio" rel="noopener me" target="_blank" aria-label="Instagram" style={{ color: 'inherit', display: 'inline-flex', alignItems: 'center', gap: 6, textDecoration: 'none' }}>{SOCIAL_ICONS.instagram}<span>INSTAGRAM</span></a>
          <a href="https://x.com/GetKnownRadio" rel="noopener me" target="_blank" aria-label="X (Twitter)" style={{ color: 'inherit', display: 'inline-flex', alignItems: 'center', gap: 6, textDecoration: 'none' }}><span>X / TWITTER</span></a>
          <a href="https://youtube.com/@GetKnownRadio" rel="noopener me" target="_blank" aria-label="YouTube" style={{ color: 'inherit', display: 'inline-flex', alignItems: 'center', gap: 6, textDecoration: 'none' }}>{SOCIAL_ICONS.youtube}<span>YOUTUBE</span></a>
          <a href="https://tiktok.com/@GetKnownRadio" rel="noopener me" target="_blank" aria-label="TikTok" style={{ color: 'inherit', display: 'inline-flex', alignItems: 'center', gap: 6, textDecoration: 'none' }}>{SOCIAL_ICONS.tiktok}<span>TIKTOK</span></a>
        </nav>
      </div>
      <footer className="gkr-footer-row" style={{ display: 'flex', justifyContent: 'space-between', padding: '12px 0', fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '.14em', textTransform: 'uppercase', color: 'var(--sub)' }}>
        <span>GKR · ESTABLISHED 2022 · INDEPENDENT</span>
        <span>PRINTED ON THE INTERNET, DAILY</span>
        <span>© GET KNOWN RADIO — NO RIGHTS RESERVED</span>
      </footer>
    </div>
  );
}

window.Broadsheet = Broadsheet;
