// ─────────────────────────────────────────────────────────────────────
// VideosView — Catalog · Videos tab
// ─────────────────────────────────────────────────────────────────────
// Renders music-video records sourced from window.RS.videos (88 records
// from the RS export). Each video points at a Recording (and through it
// at a Work). Surfaces:
//   • KPI strip (total videos, controlled %, with-ISRC, with-YouTube)
//   • Toolbar w/ view toggle (grid|table) and Content-ID filter
//   • Grid: thumbnail card → links to YouTube + recording row
//   • Table: ID · TITLE · RECORDING · ISRC · LINKS · CONTROLLED · CLAIMANT
//
// Click → opens the underlying recording in catalog (ScreenRecording).
// If a YouTube link exists we also render a quick-launch external icon.
// ─────────────────────────────────────────────────────────────────────

(function () {
  function VideosView({ go, q = '', view = 'grid' }) {
    const all = (window.RS && window.RS.videos) || [];

    // ── Filters ────────────────────────────────────────────────────────
    const [contentIdFilter, setContentIdFilter] = React.useState('any'); // any | claimed | none
    const [linkFilter, setLinkFilter] = React.useState('any'); // any | youtube | facebook | both | none

    // ── Search + filter pipeline ──────────────────────────────────────
    const filtered = React.useMemo(() => {
      const qq = (q || '').trim().toLowerCase();
      return all.filter((v) => {
        if (qq) {
          const hay = [
            v['Video Name'],
            v['Video ID'],
            v['Recording'],
            v['ISRC (Video)'],
            v['Content ID Claimants'],
          ].filter(Boolean).join(' ').toLowerCase();
          if (!hay.includes(qq)) return false;
        }
        if (contentIdFilter === 'claimed' && !v['Content ID Claimants']) return false;
        if (contentIdFilter === 'none' && v['Content ID Claimants']) return false;
        const hasYT = !!v['YouTube Link'];
        const hasFB = !!v['FB Video Link'];
        if (linkFilter === 'youtube' && !hasYT) return false;
        if (linkFilter === 'facebook' && !hasFB) return false;
        if (linkFilter === 'both' && !(hasYT && hasFB)) return false;
        if (linkFilter === 'none' && (hasYT || hasFB)) return false;
        return true;
      });
    }, [all, q, contentIdFilter, linkFilter]);

    // ── KPIs ──────────────────────────────────────────────────────────
    const kpis = React.useMemo(() => {
      const total = all.length;
      const controlled = all.filter((v) => (v['Controlled'] || '').toLowerCase().startsWith('y')).length;
      const withIsrc = all.filter((v) => v['ISRC (Video)']).length;
      const withYt = all.filter((v) => v['YouTube Link']).length;
      return { total, controlled, withIsrc, withYt };
    }, [all]);

    // ── Helpers ───────────────────────────────────────────────────────
    const ytEmbedThumb = (url) => {
      if (!url) return null;
      // youtu.be/ID  or  youtube.com/watch?v=ID
      let id = null;
      const m1 = url.match(/youtu\.be\/([\w-]+)/);
      const m2 = url.match(/[?&]v=([\w-]+)/);
      if (m1) id = m1[1];
      else if (m2) id = m2[1];
      return id ? `https://i.ytimg.com/vi/${id}/hqdefault.jpg` : null;
    };

    // Card click → open the video drawer (editable). Holding shift opens
    // the linked recording in catalog instead.
    const openRecording = (v, e) => {
      if (e && (e.shiftKey || e.metaKey)) {
        const recId = v['Recording'];
        const rec = (window.RECORDINGS || []).find((r) => r.title === recId || r.id === recId);
        if (rec) window.dispatchEvent(new CustomEvent('astro-open-recording', { detail: { id: rec.id } }));
        return;
      }
      window.dispatchEvent(new CustomEvent('astro-open-video', { detail: { id: v['Video ID'] } }));
    };

    // ── Header KPI strip ──────────────────────────────────────────────
    const kpiStrip = (
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)',
        borderTop: '1px solid var(--rule)', borderBottom: '1px solid var(--rule)', marginTop: 0 }}>
        {[
          { l: 'TOTAL VIDEOS', v: kpis.total.toLocaleString(), sub: 'in catalog' },
          { l: 'CONTROLLED', v: kpis.controlled, sub: kpis.total ? `${Math.round(100 * kpis.controlled / kpis.total)}% of catalog` : '—' },
          { l: 'WITH ISRC', v: kpis.withIsrc, sub: kpis.total ? `${Math.round(100 * kpis.withIsrc / kpis.total)}% registered` : '—' },
          { l: 'YOUTUBE LINKED', v: kpis.withYt, sub: kpis.total ? `${Math.round(100 * kpis.withYt / kpis.total)}% live` : '—' },
        ].map((s, i, arr) => (
          <div key={i} style={{ padding: '18px 16px', borderRight: i < arr.length - 1 ? '1px solid var(--rule)' : 'none' }}>
            <div className="ff-mono upper" style={{ fontSize: 10, fontWeight: 600, marginBottom: 6 }}>{s.l}</div>
            <div className="ff-display num" style={{ fontSize: 36, fontWeight: 600, letterSpacing: '-0.04em', lineHeight: 1 }}>{s.v}</div>
            <div className="ff-mono" style={{ fontSize: 10, color: 'var(--ink-3)', marginTop: 6 }}>{s.sub}</div>
          </div>
        ))}
      </div>
    );

    // ── Filter chips bar ──────────────────────────────────────────────
    const FilterChip = ({ active, onClick, children }) => (
      <button onClick={onClick} className="ff-mono upper"
        style={{
          padding: '5px 10px', fontSize: 10, letterSpacing: '.1em', fontWeight: 600,
          background: active ? 'var(--ink)' : 'transparent',
          color: active ? 'var(--bg)' : 'var(--ink-2)',
          border: '1px solid var(--rule)', cursor: 'pointer',
        }}>{children}</button>
    );

    const filtersRow = (
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: '10px 0', borderBottom: '1px solid var(--rule)' }}>
        <span className="ff-mono upper" style={{ fontSize: 10, letterSpacing: '.12em', color: 'var(--ink-3)' }}>
          {filtered.length} VIDEO{filtered.length === 1 ? '' : 'S'}{filtered.length !== all.length && ` · OF ${all.length}`}
        </span>
        <div style={{ display: 'flex', gap: 12, alignItems: 'center', flexWrap: 'wrap' }}>
          <span className="ff-mono upper" style={{ fontSize: 10, color: 'var(--ink-3)' }}>CONTENT ID</span>
          <div style={{ display: 'flex', gap: 0 }}>
            <FilterChip active={contentIdFilter === 'any'} onClick={() => setContentIdFilter('any')}>ANY</FilterChip>
            <FilterChip active={contentIdFilter === 'claimed'} onClick={() => setContentIdFilter('claimed')}>CLAIMED</FilterChip>
            <FilterChip active={contentIdFilter === 'none'} onClick={() => setContentIdFilter('none')}>UNCLAIMED</FilterChip>
          </div>
          <span style={{ width: 1, height: 14, background: 'var(--rule)' }} />
          <span className="ff-mono upper" style={{ fontSize: 10, color: 'var(--ink-3)' }}>LINKS</span>
          <div style={{ display: 'flex', gap: 0 }}>
            <FilterChip active={linkFilter === 'any'} onClick={() => setLinkFilter('any')}>ANY</FilterChip>
            <FilterChip active={linkFilter === 'youtube'} onClick={() => setLinkFilter('youtube')}>YT</FilterChip>
            <FilterChip active={linkFilter === 'facebook'} onClick={() => setLinkFilter('facebook')}>FB</FilterChip>
            <FilterChip active={linkFilter === 'both'} onClick={() => setLinkFilter('both')}>BOTH</FilterChip>
            <FilterChip active={linkFilter === 'none'} onClick={() => setLinkFilter('none')}>NONE</FilterChip>
          </div>
        </div>
      </div>
    );

    // ── Empty state ───────────────────────────────────────────────────
    const empty = (
      <div style={{ padding: '64px 24px', textAlign: 'center', color: 'var(--ink-3)' }}>
        <div className="ff-mono upper" style={{ fontSize: 11, letterSpacing: '.12em', marginBottom: 8 }}>NO VIDEOS MATCH</div>
        <div style={{ fontSize: 13 }}>Try clearing search or filters.</div>
      </div>
    );

    // ── Grid card ─────────────────────────────────────────────────────
    const Card = ({ v }) => {
      const yt = v['YouTube Link'];
      const fb = v['FB Video Link'];
      const thumb = ytEmbedThumb(yt);
      const claimed = !!v['Content ID Claimants'];
      const controlled = (v['Controlled'] || '').toLowerCase().startsWith('y');
      return (
        <div onClick={(e) => openRecording(v, e)}
          style={{
            borderRight: '1px solid var(--rule)', borderBottom: '1px solid var(--rule)',
            cursor: 'pointer', position: 'relative', background: 'var(--bg)',
          }}
          onMouseEnter={(e) => e.currentTarget.style.background = 'var(--bg-2)'}
          onMouseLeave={(e) => e.currentTarget.style.background = 'var(--bg)'}>
          {/* Thumbnail / placeholder */}
          <div style={{
            aspectRatio: '16/9', position: 'relative', overflow: 'hidden',
            background: thumb
              ? `center / cover no-repeat url("${thumb}")`
              : 'linear-gradient(135deg, var(--ink-5) 0%, var(--ink-4) 100%)',
            borderBottom: '1px solid var(--rule)',
          }}>
            {!thumb && (
              <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <svg width="42" height="42" viewBox="0 0 24 24" fill="none" stroke="var(--bg)" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" style={{ opacity: .55 }}>
                  <polygon points="23 7 16 12 23 17 23 7" />
                  <rect x="1" y="5" width="15" height="14" rx="2" ry="2" />
                </svg>
              </div>
            )}
            {/* Play overlay */}
            {thumb && (
              <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'rgba(0,0,0,.18)' }}>
                <div style={{
                  width: 44, height: 44, borderRadius: '50%',
                  background: 'rgba(0,0,0,.65)', backdropFilter: 'blur(4px)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                }}>
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="white"><polygon points="6 4 20 12 6 20 6 4" /></svg>
                </div>
              </div>
            )}
            {/* Top-right badges */}
            <div style={{ position: 'absolute', top: 8, right: 8, display: 'flex', gap: 6 }}>
              {claimed && (
                <span className="ff-mono upper" style={{
                  fontSize: 9, letterSpacing: '.08em', fontWeight: 700,
                  padding: '3px 6px', background: 'var(--ok, #1f7a3a)', color: 'white',
                }}>CID</span>
              )}
              {controlled && (
                <span className="ff-mono upper" style={{
                  fontSize: 9, letterSpacing: '.08em', fontWeight: 700,
                  padding: '3px 6px', background: 'var(--ink)', color: 'var(--bg)',
                }}>CTRL</span>
              )}
            </div>
            {/* Bottom-left ID stamp */}
            <span className="ff-mono" style={{
              position: 'absolute', bottom: 8, left: 8, fontSize: 10, fontWeight: 600,
              padding: '3px 6px', background: 'rgba(0,0,0,.65)', color: 'white', letterSpacing: '.04em',
            }}>{v['Video ID']}</span>
          </div>
          {/* Body */}
          <div style={{ padding: '12px 14px 14px' }}>
            <div style={{
              fontSize: 14, fontWeight: 600, lineHeight: 1.3, marginBottom: 4,
              overflow: 'hidden', textOverflow: 'ellipsis', display: '-webkit-box',
              WebkitLineClamp: 2, WebkitBoxOrient: 'vertical',
            }}>{v['Video Name']}</div>
            <div className="ff-mono" style={{ fontSize: 10, color: 'var(--ink-3)', display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' }}>
              {v['ISRC (Video)'] && (<>
                <span>{v['ISRC (Video)']}</span>
                <span style={{ opacity: .4 }}>·</span>
              </>)}
              <span>{v['Content ID Claimants'] || 'unclaimed'}</span>
            </div>
            {/* Footer: link icons */}
            <div style={{ display: 'flex', gap: 8, marginTop: 10 }}>
              {yt && (
                <a href={yt} target="_blank" rel="noopener" onClick={(e) => e.stopPropagation()}
                  style={{ display: 'inline-flex', alignItems: 'center', gap: 4,
                    padding: '3px 7px', border: '1px solid var(--rule)',
                    fontSize: 10, color: 'var(--ink-2)', textDecoration: 'none' }}
                  className="ff-mono upper">
                  <svg width="11" height="11" viewBox="0 0 24 24" fill="currentColor"><path d="M23.5 6.2s-.2-1.6-.9-2.3c-.9-.9-1.8-.9-2.2-1C17.1 2.6 12 2.6 12 2.6s-5.1 0-8.4.3c-.4.1-1.4.1-2.2 1-.7.7-.9 2.3-.9 2.3S0 8 0 9.9v1.7c0 1.9.2 3.7.2 3.7s.2 1.6.9 2.3c.9.9 2 .9 2.5 1 1.8.2 7.7.3 7.9.3.1 0 5.1 0 8.4-.3.4-.1 1.4-.1 2.2-1 .7-.7.9-2.3.9-2.3s.2-1.9.2-3.7v-1.7c0-1.9-.2-3.7-.2-3.7zM9.5 14.8V8.5l6.4 3.2-6.4 3.1z"/></svg>
                  YT
                </a>
              )}
              {fb && (
                <a href={fb} target="_blank" rel="noopener" onClick={(e) => e.stopPropagation()}
                  style={{ display: 'inline-flex', alignItems: 'center', gap: 4,
                    padding: '3px 7px', border: '1px solid var(--rule)',
                    fontSize: 10, color: 'var(--ink-2)', textDecoration: 'none' }}
                  className="ff-mono upper">
                  <svg width="11" height="11" viewBox="0 0 24 24" fill="currentColor"><path d="M14 13.5h2.5l1-4H14v-2c0-1 .5-2 2-2h1.5V2.1S16 2 14.7 2c-2.7 0-4.7 1.6-4.7 4.6v2.9H6.5v4H10V22h4V13.5z"/></svg>
                  FB
                </a>
              )}
              {!yt && !fb && (
                <span className="ff-mono upper" style={{ fontSize: 9, letterSpacing: '.1em', color: 'var(--ink-4)' }}>NO LINKS</span>
              )}
            </div>
          </div>
        </div>
      );
    };

    // ── Table row ─────────────────────────────────────────────────────
    const TableRow = ({ v }) => {
      const yt = v['YouTube Link'];
      const fb = v['FB Video Link'];
      const claimed = !!v['Content ID Claimants'];
      return (
        <div onClick={(e) => openRecording(v, e)}
          style={{
            display: 'grid',
            gridTemplateColumns: '110px 1.6fr 1.4fr 130px 110px 90px 1fr',
            gap: 14, padding: '12px 14px', borderBottom: '1px solid var(--rule-soft)',
            alignItems: 'center', cursor: 'pointer',
          }}
          onMouseEnter={(e) => e.currentTarget.style.background = 'var(--bg-2)'}
          onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}>
          <span className="ff-mono" style={{ fontSize: 11, fontWeight: 600 }}>{v['Video ID']}</span>
          <span style={{ fontSize: 13, fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{v['Video Name']}</span>
          <span style={{ fontSize: 12, color: 'var(--ink-2)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{v['Recording'] || '—'}</span>
          <span className="ff-mono" style={{ fontSize: 11, color: 'var(--ink-2)' }}>{v['ISRC (Video)'] || <span style={{ color: 'var(--ink-4)' }}>—</span>}</span>
          <div style={{ display: 'flex', gap: 6 }}>
            {yt && (<a href={yt} target="_blank" rel="noopener" onClick={(e) => e.stopPropagation()}
              className="ff-mono upper" style={{ fontSize: 10, padding: '2px 6px', border: '1px solid var(--rule)', color: 'var(--ink-2)', textDecoration: 'none' }}>YT</a>)}
            {fb && (<a href={fb} target="_blank" rel="noopener" onClick={(e) => e.stopPropagation()}
              className="ff-mono upper" style={{ fontSize: 10, padding: '2px 6px', border: '1px solid var(--rule)', color: 'var(--ink-2)', textDecoration: 'none' }}>FB</a>)}
            {!yt && !fb && (<span className="ff-mono" style={{ fontSize: 10, color: 'var(--ink-4)' }}>—</span>)}
          </div>
          <span className="ff-mono upper" style={{ fontSize: 10, fontWeight: 600,
            color: (v['Controlled'] || '').toLowerCase().startsWith('y') ? 'var(--ink)' : 'var(--ink-3)' }}>
            {v['Controlled'] || '—'}
          </span>
          <span style={{ fontSize: 12, color: claimed ? 'var(--ink)' : 'var(--ink-4)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
            {v['Content ID Claimants'] || <span className="ff-mono upper" style={{ fontSize: 10, letterSpacing: '.1em' }}>UNCLAIMED</span>}
          </span>
        </div>
      );
    };

    return (
      <div>
        {kpiStrip}
        {filtersRow}
        {filtered.length === 0 && empty}
        {filtered.length > 0 && view === 'grid' && (
          <div style={{
            display: 'grid', gridTemplateColumns: 'repeat(auto-fill,minmax(280px,1fr))', gap: 0,
            borderLeft: '1px solid var(--rule)', borderTop: '1px solid var(--rule)',
          }}>
            {filtered.map((v) => <Card key={v['Video ID']} v={v} />)}
          </div>
        )}
        {filtered.length > 0 && view === 'table' && (
          <div>
            <div className="ff-mono upper" style={{
              display: 'grid',
              gridTemplateColumns: '110px 1.6fr 1.4fr 130px 110px 90px 1fr',
              gap: 14, padding: '10px 14px', fontSize: 10, color: 'var(--ink-3)',
              background: 'var(--bg-2)', borderTop: '1px solid var(--rule)', borderBottom: '1px solid var(--rule)',
            }}>
              <span>VIDEO ID</span><span>TITLE</span><span>RECORDING</span>
              <span>ISRC</span><span>LINKS</span><span>CTRL</span><span>CID CLAIMANT</span>
            </div>
            {filtered.map((v) => <TableRow key={v['Video ID']} v={v} />)}
          </div>
        )}
      </div>
    );
  }

  Object.assign(window, { VideosView });
})();
