// Live — past performances, fed live from
// soundcloud.com/htxedifice/sets/live-performances via the Widget API.
// Each row = one performance with date, cover, title, length, link.

const LIVE_SLUG = 'live-performances';
const LIVE_SET_URL = `https://soundcloud.com/htxedifice/sets/${LIVE_SLUG}`;
const LIVE_IFRAME_SRC =
  'https://w.soundcloud.com/player/?url=' + encodeURIComponent(LIVE_SET_URL) +
  '&visual=false&show_artwork=false&show_user=false&auto_play=false';

// Parse a date out of a SoundCloud title — preferred over the upload date,
// since live recordings are often uploaded years after the event.
//   "Live at Foo 2024.05.12"  → 2024-05-12
//   "Foo Bar (May 2024)"      → 2024-05-01
//   "HTX (2015)"              → 2015-01-01
const TITLE_MONTHS = { jan: 0, feb: 1, mar: 2, apr: 3, may: 4, jun: 5, jul: 6, aug: 7, sep: 8, oct: 9, nov: 10, dec: 11 };
function parseTitleDate(title) {
  if (!title) return null;
  let m = title.match(/(?:^|\D)(\d{4})[.\-/\s](\d{1,2})[.\-/\s](\d{1,2})\b/);
  if (m) {
    const y = +m[1], mo = +m[2] - 1, d = +m[3];
    if (y >= 1990 && y <= 2099 && mo >= 0 && mo < 12 && d >= 1 && d <= 31) {
      return { date: new Date(Date.UTC(y, mo, d)), precision: 'day' };
    }
  }
  m = title.match(/\b(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]*\.?\s+(\d{4})\b/i);
  if (m) {
    const mi = TITLE_MONTHS[m[1].toLowerCase()];
    return { date: new Date(Date.UTC(+m[2], mi, 1)), precision: 'month' };
  }
  m = title.match(/\((\d{4})\)/) || title.match(/\b(20\d{2}|19\d{2})\b/);
  if (m) {
    return { date: new Date(Date.UTC(+m[1], 0, 1)), precision: 'year' };
  }
  return null;
}

function liveFmtDate(parsed, fallback) {
  if (parsed && parsed.date) {
    const d = parsed.date;
    if (parsed.precision === 'year') return String(d.getUTCFullYear());
    if (parsed.precision === 'month') return `${d.getUTCFullYear()}.${String(d.getUTCMonth() + 1).padStart(2, '0')}`;
    return `${d.getUTCFullYear()}.${String(d.getUTCMonth() + 1).padStart(2, '0')}.${String(d.getUTCDate()).padStart(2, '0')}`;
  }
  if (fallback) {
    const d = new Date(fallback);
    if (!isNaN(d.getTime())) {
      return `${d.getUTCFullYear()}.${String(d.getUTCMonth() + 1).padStart(2, '0')}.${String(d.getUTCDate()).padStart(2, '0')}`;
    }
  }
  return '—';
}
function liveFmtDur(ms) {
  if (!ms || ms < 1000) return '—';
  const s = Math.round(ms / 1000);
  const m = Math.floor(s / 60);
  const r = s % 60;
  if (m >= 60) {
    const h = Math.floor(m / 60);
    const rm = m % 60;
    return `${h}:${String(rm).padStart(2, '0')}:00`;
  }
  return `${String(m).padStart(2, '0')}:${String(r).padStart(2, '0')}`;
}
function liveTrackArt(url) {
  if (!url) return null;
  return url.replace(/-large\./, '-t200x200.');
}

// Hardcoded extras — standalone live tracks that aren't (yet) inside the
// `live-performances` set. Deduped against the live set by permalink.
const LIVE_STATIC_EXTRAS = [];

function Live({ t }) {
  const iframeRef = React.useRef(null);
  const [tracks, setTracks] = React.useState(LIVE_STATIC_EXTRAS);
  const [status, setStatus] = React.useState('loading'); // loading | live | offline

  React.useEffect(() => {
    if (!iframeRef.current || typeof SC === 'undefined' || !SC.Widget) {
      setStatus('offline');
      return;
    }
    const widget = SC.Widget(iframeRef.current);
    const seen = new Map();
    const timeouts = [];

    const sortKey = (x) => {
      const p = parseTitleDate(x.title);
      if (p && p.date) return p.date.getTime();
      return Date.parse(x.created_at) || 0;
    };

    const refresh = () => {
      widget.getSounds((sounds) => {
        if (!sounds || !sounds.length) return;
        for (const s of sounds) seen.set(s.id, s);
        const setTracks_ = Array.from(seen.values());
        const haveByUrl = new Set(setTracks_.map((s) => s.permalink_url));
        const merged = setTracks_.concat(LIVE_STATIC_EXTRAS.filter((x) => !haveByUrl.has(x.permalink_url)));
        merged.sort((a, b) => sortKey(b) - sortKey(a));
        setTracks(merged);
        setStatus('live');
      });
    };

    widget.bind(SC.Widget.Events.READY, () => {
      refresh();
      [800, 2000, 4500, 9000].forEach((d) => timeouts.push(setTimeout(refresh, d)));
    });

    const giveUp = setTimeout(() => {
      if (!seen.size) setStatus('offline');
    }, 12000);
    timeouts.push(giveUp);

    return () => timeouts.forEach(clearTimeout);
  }, []);

  return (
    <section id="live" data-screen-label="03 Live Recordings" className="sec sec-live">
      <SectionHead num="03" title="Live Recordings" sub="performances · live from SoundCloud" />

      <iframe
        ref={iframeRef}
        title="SoundCloud bridge — Live"
        src={LIVE_IFRAME_SRC}
        className="ro-sc-bridge"
        aria-hidden="true"
      />

      <div className="ro-controls">
        <div className="ro-count">[ {tracks.length} PERFORMANCES ]</div>
        <div className={`ro-status ro-status-${status}`}>
          {status === 'loading' ? '◐ SYNCING WITH SOUNDCLOUD'
            : status === 'live' ? '● LIVE FROM SOUNDCLOUD'
            : '○ OFFLINE'}
        </div>
      </div>

      {tracks.length === 0 ? (
        <div className="scf-empty">{status === 'offline' ? 'Could not reach SoundCloud.' : 'Loading performances…'}</div>
      ) : (
        <div className="ro-table">
          <div className="ro-row ro-row-live ro-head">
            <div>DATE</div>
            <div>COVER</div>
            <div>TITLE</div>
            <div>LEN</div>
            <div></div>
          </div>
          {tracks.map((tr) => (
            <a key={tr.id}
               className="ro-row ro-row-live"
               href={tr.permalink_url}
               target="_blank"
               rel="noreferrer">
              <div className="num">{liveFmtDate(parseTitleDate(tr.title), tr.created_at)}</div>
              <div className="ro-thumb">
                {tr.artwork_url
                  ? <img src={liveTrackArt(tr.artwork_url)} alt="" loading="lazy" decoding="async" />
                  : <div className="ro-thumb-blank" />}
              </div>
              <div className="ro-title-cell">
                <span className="ro-title-name">{tr.title || '—'}</span>
              </div>
              <div className="num">{liveFmtDur(tr.duration)}</div>
              <div className="ro-arrow">↗</div>
            </a>
          ))}
        </div>
      )}

      <div className="ro-foot">
        <div className="ro-foot-bracket">
          ━━ FULL PLAYLIST AT
          <a href={LIVE_SET_URL} target="_blank" rel="noreferrer">soundcloud.com/htxedifice/sets/{LIVE_SLUG}</a>
        </div>
      </div>
    </section>
  );
}

window.Live = Live;
