// ============================================================
// ELITE RECORDINGS
// ------------------------------------------------------------
// Public component: past Elite call recordings grid (10 cards).
// Non-elite users see only the first card unlocked; the rest
// display a padlock overlay. Last position is a "+N more" card
// that links to the full YouTube playlist.
//
// Admin component: lets admins paste a YouTube URL + title and
// inserts a new row; newest row becomes "the first recording".
// ============================================================

const ELITE_PLAYLIST_URL = 'https://www.youtube.com/playlist?list=PLnu6--ikU1FTTNts7iWOqIM7FgnpUP8lh';
const MAX_VISIBLE = 10;

function extractYouTubeId(url) {
  if (!url) return null;
  try {
    const m = String(url).match(
      /(?:v=|youtu\.be\/|\/embed\/|\/shorts\/|\/v\/|\/live\/)([\w-]{11})/
    );
    return m ? m[1] : null;
  } catch { return null; }
}

function ytThumb(videoId) {
  return videoId ? `https://i.ytimg.com/vi/${videoId}/hqdefault.jpg` : '';
}

function isEliteUser(user) {
  if (!user) return false;
  if (user.role === 'admin') return true;
  // Treat any user with role='elite' as Elite — admins assign this role
  // manually, so we don't require elite_status='active' here. The status
  // column is now informational (active/inactive/expired) and updated by
  // the admin when relevant, but does NOT gate access.
  return user.role === 'elite';
}

// ============================================================
// PUBLIC: ELITE RECORDINGS GRID
// ============================================================
const EliteRecordings = ({ user, onNav }) => {
  const [items, setItems] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [err, setErr] = React.useState('');
  const [totalCount, setTotalCount] = React.useState(0);

  React.useEffect(() => {
    let cancelled = false;
    (async () => {
      if (!window.sb) { setLoading(false); return; }
      try {
        const { data, error, count } = await window.sb
          .from('elite_recordings')
          .select('*', { count: 'exact' })
          .order('created_at', { ascending: false })
          .limit(MAX_VISIBLE);
        if (cancelled) return;
        if (error) throw error;
        setItems(data || []);
        setTotalCount(count || 0);
      } catch (e) {
        if (!cancelled) setErr(e.message || 'Failed to load recordings');
      } finally {
        if (!cancelled) setLoading(false);
      }
    })();
    return () => { cancelled = true; };
  }, []);

  const elite = isEliteUser(user);
  const remaining = Math.max(0, totalCount - items.length);

  // Skeleton loader cards
  const skeleton = Array.from({ length: 6 }).map((_, i) => (
    <div key={`s-${i}`} className="rec-card rec-skel"><div className="rec-skel-thumb" /></div>
  ));

  return (
    <section className="elite-recordings-section">
      <div className="container">
        <div className="rec-head">
          <span className="eyebrow"><span className="dot" />ELITE CALLS · RECORDINGS</span>
          <h2>Înregistrările <span className="acid">Elite Calls.</span></h2>
          <p className="lead">
            {elite
              ? 'Acces complet la toate live call-urile arhivate. Click pe orice card pentru a deschide înregistrarea.'
              : 'Un singur call este deschis pentru toată lumea. Restul sunt rezervate membrilor Elite.'}
          </p>
        </div>

        {err && (
          <div className="rec-error">
            <Icon name="x" size={14} /> {err}
          </div>
        )}

        <div className="rec-grid">
          {loading ? skeleton : items.length === 0 ? (
            <div className="rec-empty">
              <Icon name="bolt" size={20} />
              <div>Niciun call încărcat încă. Reveniți curând.</div>
            </div>
          ) : (
            items.map((it, i) => {
              const locked = !elite && i !== 0;
              const vid = it.video_id || extractYouTubeId(it.youtube_url);
              const thumb = it.thumbnail || ytThumb(vid);
              const Wrapper = locked ? 'div' : 'a';
              const wrapperProps = locked
                ? { className: 'rec-card rec-card-locked', role: 'button', 'aria-disabled': true }
                : { className: 'rec-card', href: it.youtube_url, target: '_blank', rel: 'noopener noreferrer' };
              return (
                <Wrapper key={it.id} {...wrapperProps}>
                  <div className="rec-thumb">
                    {thumb && <img src={thumb} alt={it.title || 'Elite call'} loading="lazy" />}
                    <div className="rec-thumb-shade" />
                    {!locked && (
                      <div className="rec-play">
                        <Icon name="bolt" size={22} />
                      </div>
                    )}
                    {locked && (
                      <div className="rec-lock">
                        <div className="rec-lock-icon">
                          <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                            <rect x="3" y="11" width="18" height="11" rx="2"/>
                            <path d="M7 11V7a5 5 0 0 1 10 0v4"/>
                          </svg>
                        </div>
                        <div className="rec-lock-label">Elite Only</div>
                      </div>
                    )}
                    <div className="rec-idx">#{String(i + 1).padStart(2, '0')}</div>
                  </div>
                  <div className="rec-meta">
                    <div className="rec-title">{it.title || `Elite Call ${i + 1}`}</div>
                    <div className="rec-row">
                      <span className="rec-date">
                        {it.recorded_at
                          ? new Date(it.recorded_at).toLocaleDateString('ro-RO', { day: '2-digit', month: 'short', year: 'numeric' })
                          : new Date(it.created_at).toLocaleDateString('ro-RO', { day: '2-digit', month: 'short', year: 'numeric' })}
                      </span>
                      {!locked && <span className="rec-cta">Watch <Icon name="arrowUR" size={12} /></span>}
                      {locked && <span className="rec-cta-locked">Locked</span>}
                    </div>
                  </div>
                </Wrapper>
              );
            })
          )}

          {/* +N more card → playlist (only if there are actually more) */}
          {!loading && items.length > 0 && (
            <a className="rec-card rec-card-more"
               href={ELITE_PLAYLIST_URL}
               target="_blank"
               rel="noopener noreferrer">
              <div className="rec-more-inner">
                <div className="rec-more-icon">
                  <Icon name="arrowUR" size={26} />
                </div>
                <div className="rec-more-num">
                  +{remaining > 0 ? remaining : '∞'}
                </div>
                <div className="rec-more-label">
                  {remaining > 0 ? 'mai multe call-uri' : 'vezi playlist-ul complet'}
                </div>
                <div className="rec-more-link">Open playlist <Icon name="arrowUR" size={12} /></div>
              </div>
            </a>
          )}
        </div>

        {!elite && !loading && items.length > 0 && (
          <div className="rec-upsell">
            <div>
              <h3>Vrei să le vezi pe toate?</h3>
              <p>Aplică pentru Elite și deblochezi întreaga arhivă de live calls.</p>
            </div>
            <Button variant="acid" onClick={() => onNav && onNav('elite')}>Apply for Elite</Button>
          </div>
        )}
      </div>

      <style>{`
        .elite-recordings-section {
          position: relative;
          padding: 80px 0 60px;
        }
        .rec-head {
          text-align: center;
          max-width: 720px;
          margin: 0 auto 44px;
        }
        .rec-head .eyebrow { display: inline-flex; justify-content: center; }
        .rec-head h2 {
          margin-top: 18px;
          font-size: clamp(32px, 4.2vw, 52px);
          line-height: 1.05;
          letter-spacing: -0.03em;
        }
        .rec-head .acid {
          background: linear-gradient(180deg, #DCFF7A 0%, #B7FF1A 60%, #8FE000 100%);
          -webkit-background-clip: text; background-clip: text; color: transparent;
        }
        .rec-head .lead { margin: 16px auto 0; max-width: 560px; }

        .rec-error {
          display: inline-flex; align-items: center; gap: 8px;
          padding: 10px 14px;
          background: rgba(255, 80, 80, 0.08);
          border: 1px solid rgba(255, 80, 80, 0.25);
          color: #ff9090;
          border-radius: 10px;
          font-size: 13px;
          margin-bottom: 18px;
        }

        .rec-grid {
          display: grid;
          grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
          gap: 20px;
        }
        @media (max-width: 540px) {
          .rec-grid { grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); }
        }

        .rec-empty {
          grid-column: 1 / -1;
          padding: 40px 24px;
          text-align: center;
          display: grid; place-items: center; gap: 10px;
          background: rgba(255,255,255,0.03);
          border: 1px dashed rgba(255,255,255,0.10);
          border-radius: 18px;
          color: var(--text-mute);
        }
        .rec-empty svg { color: var(--acid); }

        .rec-card {
          display: flex;
          flex-direction: column;
          border-radius: 20px;
          overflow: hidden;
          background:
            linear-gradient(180deg, rgba(255,255,255,0.05) 0%, rgba(255,255,255,0.01) 100%),
            rgba(10, 10, 12, 0.7);
          border: 1px solid rgba(255,255,255,0.10);
          box-shadow:
            0 18px 50px rgba(0,0,0,0.55),
            inset 0 1px 0 rgba(255,255,255,0.06);
          text-decoration: none;
          color: inherit;
          transition: transform 0.35s cubic-bezier(0.22, 1, 0.36, 1), border-color 0.3s, box-shadow 0.3s;
          position: relative;
          isolation: isolate;
        }
        .rec-card:hover {
          transform: translateY(-4px);
          border-color: rgba(255,255,255,0.20);
          box-shadow:
            0 28px 60px rgba(0,0,0,0.65),
            inset 0 1px 0 rgba(255,255,255,0.10),
            0 0 40px rgba(183,255,26,0.08);
        }
        .rec-card-locked { cursor: not-allowed; }
        .rec-card-locked:hover { transform: none; box-shadow: 0 18px 50px rgba(0,0,0,0.55); }

        .rec-thumb {
          position: relative;
          width: 100%;
          aspect-ratio: 16 / 9;
          background: #050507;
          overflow: hidden;
        }
        .rec-thumb img {
          width: 100%; height: 100%;
          object-fit: cover;
          display: block;
          transition: transform 0.45s ease, filter 0.45s ease;
        }
        .rec-card:hover .rec-thumb img { transform: scale(1.06); }
        .rec-card-locked .rec-thumb img { filter: blur(8px) saturate(0.6) brightness(0.5); }
        .rec-thumb-shade {
          position: absolute; inset: 0;
          background: linear-gradient(180deg, rgba(0,0,0,0) 50%, rgba(0,0,0,0.55) 100%);
          pointer-events: none;
        }
        .rec-idx {
          position: absolute;
          top: 10px; left: 10px;
          font-family: 'JetBrains Mono', monospace;
          font-size: 10px;
          letter-spacing: 0.14em;
          padding: 4px 9px;
          border-radius: 999px;
          background: rgba(0,0,0,0.55);
          backdrop-filter: blur(6px);
          -webkit-backdrop-filter: blur(6px);
          border: 1px solid rgba(255,255,255,0.12);
          color: rgba(255,255,255,0.85);
        }
        .rec-play {
          position: absolute;
          inset: 0;
          display: grid; place-items: center;
          opacity: 0;
          transition: opacity 0.3s ease;
          z-index: 2;
        }
        .rec-play > * {
          width: 52px; height: 52px;
          border-radius: 50%;
          display: grid; place-items: center;
          background: linear-gradient(180deg, #C8FF35 0%, #A8F00B 100%);
          color: #050505;
          box-shadow: 0 8px 26px rgba(183,255,26,0.45), 0 0 36px rgba(183,255,26,0.35);
        }
        .rec-card:hover .rec-play { opacity: 1; }

        .rec-lock {
          position: absolute; inset: 0;
          display: grid; place-items: center; gap: 8px;
          color: rgba(255,255,255,0.85);
          z-index: 2;
        }
        .rec-lock-icon {
          width: 56px; height: 56px;
          border-radius: 50%;
          display: grid; place-items: center;
          background: rgba(255,255,255,0.06);
          backdrop-filter: blur(8px);
          -webkit-backdrop-filter: blur(8px);
          border: 1px solid rgba(255,255,255,0.16);
          box-shadow: 0 8px 22px rgba(0,0,0,0.45);
        }
        .rec-lock-label {
          font-family: 'JetBrains Mono', monospace;
          font-size: 10.5px;
          letter-spacing: 0.18em;
          text-transform: uppercase;
          color: var(--acid);
          padding: 4px 10px;
          border-radius: 999px;
          background: rgba(183,255,26,0.08);
          border: 1px solid rgba(183,255,26,0.22);
        }

        .rec-meta { padding: 14px 16px 16px; position: relative; }
        .rec-title {
          font-size: 14px;
          font-weight: 600;
          color: var(--text);
          line-height: 1.35;
          letter-spacing: -0.005em;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
          overflow: hidden;
          min-height: 38px;
        }
        .rec-row {
          margin-top: 10px;
          display: flex; justify-content: space-between; align-items: center;
          font-family: 'JetBrains Mono', monospace;
          font-size: 11px;
          letter-spacing: 0.08em;
        }
        .rec-date { color: var(--text-mute); }
        .rec-cta {
          color: var(--acid);
          display: inline-flex; align-items: center; gap: 4px;
          text-transform: uppercase;
        }
        .rec-cta-locked {
          color: var(--text-mute);
          text-transform: uppercase;
        }

        /* +N more card */
        .rec-card-more {
          cursor: pointer;
          background:
            radial-gradient(ellipse at top center, rgba(183,255,26,0.10) 0%, transparent 60%),
            linear-gradient(180deg, rgba(255,255,255,0.05) 0%, rgba(255,255,255,0.01) 100%),
            rgba(10, 10, 12, 0.7);
          border-color: rgba(183,255,26,0.22);
        }
        .rec-card-more:hover {
          border-color: rgba(183,255,26,0.5);
          box-shadow:
            0 28px 60px rgba(0,0,0,0.65),
            0 0 0 1px rgba(183,255,26,0.10) inset,
            0 0 50px rgba(183,255,26,0.18);
        }
        .rec-more-inner {
          padding: 24px;
          display: flex; flex-direction: column;
          align-items: center; justify-content: center;
          gap: 8px;
          text-align: center;
          height: 100%;
          min-height: 240px;
        }
        .rec-more-icon {
          width: 56px; height: 56px;
          border-radius: 50%;
          display: grid; place-items: center;
          background: linear-gradient(180deg, rgba(183,255,26,0.15) 0%, rgba(183,255,26,0.04) 100%);
          border: 1px solid rgba(183,255,26,0.30);
          color: var(--acid);
          margin-bottom: 6px;
          box-shadow: 0 0 30px rgba(183,255,26,0.20);
        }
        .rec-more-num {
          font-size: 38px;
          font-weight: 800;
          letter-spacing: -0.03em;
          color: var(--acid);
          text-shadow: 0 0 30px rgba(183,255,26,0.30);
          line-height: 1;
        }
        .rec-more-label {
          font-size: 13px;
          color: var(--text-dim);
          margin-top: 4px;
        }
        .rec-more-link {
          margin-top: 12px;
          font-family: 'JetBrains Mono', monospace;
          font-size: 11px;
          letter-spacing: 0.10em;
          text-transform: uppercase;
          color: var(--acid);
          display: inline-flex; align-items: center; gap: 4px;
          padding: 6px 12px;
          border-radius: 999px;
          background: rgba(183,255,26,0.08);
          border: 1px solid rgba(183,255,26,0.22);
        }

        /* Skeleton */
        .rec-skel-thumb {
          width: 100%; aspect-ratio: 16/9;
          background: linear-gradient(90deg, rgba(255,255,255,0.04), rgba(255,255,255,0.08), rgba(255,255,255,0.04));
          background-size: 200% 100%;
          animation: rec-skel 1.4s ease-in-out infinite;
        }
        @keyframes rec-skel {
          0% { background-position: 200% 0; }
          100% { background-position: -200% 0; }
        }

        /* Upsell */
        .rec-upsell {
          margin-top: 36px;
          padding: 22px 24px;
          display: flex; align-items: center; justify-content: space-between;
          gap: 24px;
          border-radius: 18px;
          background:
            linear-gradient(180deg, rgba(183,255,26,0.06) 0%, rgba(255,255,255,0.02) 100%),
            rgba(10, 10, 12, 0.6);
          border: 1px solid rgba(183,255,26,0.22);
          box-shadow: 0 18px 50px rgba(0,0,0,0.45);
        }
        .rec-upsell h3 { font-size: 18px; line-height: 1.2; }
        .rec-upsell p { color: var(--text-mute); font-size: 13px; margin-top: 4px; }
        @media (max-width: 540px) {
          .rec-upsell { flex-direction: column; align-items: stretch; text-align: center; }
        }
      `}</style>
    </section>
  );
};

// ============================================================
// ADMIN: ELITE RECORDINGS MANAGEMENT
// ============================================================
// Try fetching the public YouTube oEmbed metadata (no API key needed).
// Returns { title, author } or null on failure.
async function fetchYouTubeMeta(url) {
  try {
    const endpoint = `https://www.youtube.com/oembed?url=${encodeURIComponent(url)}&format=json`;
    const res = await fetch(endpoint);
    if (!res.ok) return null;
    const j = await res.json();
    return { title: j.title || '', author: j.author_name || '' };
  } catch { return null; }
}

const AdminRecordings = () => {
  const [items, setItems] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [err, setErr] = React.useState('');
  const [success, setSuccess] = React.useState('');
  const [submitting, setSubmitting] = React.useState(false);
  const [form, setForm] = React.useState({ title: '', youtube_url: '', recorded_at: '' });
  const [bulkOpen, setBulkOpen] = React.useState(false);
  const [bulkText, setBulkText] = React.useState('');
  const [bulkBusy, setBulkBusy] = React.useState(false);
  const [bulkLog, setBulkLog] = React.useState([]);

  const load = async () => {
    if (!window.sb) return;
    setLoading(true);
    const { data, error } = await window.sb
      .from('elite_recordings')
      .select('*')
      .order('created_at', { ascending: false });
    if (error) setErr(error.message);
    else setItems(data || []);
    setLoading(false);
  };

  React.useEffect(() => { load(); }, []);

  const flashSuccess = (msg) => {
    setSuccess(msg);
    setTimeout(() => setSuccess(''), 2400);
  };

  const onSubmit = async (e) => {
    e.preventDefault();
    setErr('');
    const url = form.youtube_url.trim();
    if (!url) { setErr('YouTube URL is required.'); return; }
    const vid = extractYouTubeId(url);
    if (!vid) { setErr('Could not extract a YouTube video ID from that URL.'); return; }
    setSubmitting(true);
    // Auto-fetch title from YouTube oEmbed if user didn't provide one
    let title = form.title.trim();
    if (!title) {
      const meta = await fetchYouTubeMeta(url);
      title = meta?.title || `Elite Call — ${vid}`;
    }
    const payload = {
      title,
      youtube_url: url,
      video_id: vid,
      thumbnail: ytThumb(vid),
      recorded_at: form.recorded_at || null,
    };
    const { error } = await window.sb.from('elite_recordings').insert(payload);
    setSubmitting(false);
    if (error) { setErr(error.message); return; }
    setForm({ title: '', youtube_url: '', recorded_at: '' });
    flashSuccess(`Added: "${title}" — now the most recent.`);
    load();
  };

  // Bulk add: paste many URLs (one per line), auto-fetch title for each.
  const onBulkSubmit = async (e) => {
    e.preventDefault();
    setErr(''); setBulkLog([]);
    const urls = bulkText.split('\n').map(s => s.trim()).filter(Boolean);
    if (urls.length === 0) { setErr('Paste at least one URL.'); return; }
    setBulkBusy(true);
    const log = [];
    // Dedupe by video_id
    const seen = new Set();
    for (const url of urls) {
      const vid = extractYouTubeId(url);
      if (!vid) { log.push({ url, status: 'skipped — bad URL' }); continue; }
      if (seen.has(vid)) { log.push({ url, status: 'skipped — duplicate' }); continue; }
      seen.add(vid);
      const meta = await fetchYouTubeMeta(url);
      const title = meta?.title || `Elite Call — ${vid}`;
      const { error } = await window.sb.from('elite_recordings').insert({
        title,
        youtube_url: url,
        video_id: vid,
        thumbnail: ytThumb(vid),
      });
      log.push({ url, status: error ? `error: ${error.message}` : `added — ${title.slice(0, 60)}` });
      setBulkLog([...log]); // live update
    }
    setBulkBusy(false);
    setBulkText('');
    flashSuccess(`Bulk add complete — ${log.filter(l => l.status.startsWith('added')).length} new.`);
    load();
  };

  const onDelete = async (id) => {
    if (!confirm('Delete this recording?')) return;
    const { error } = await window.sb.from('elite_recordings').delete().eq('id', id);
    if (error) { setErr(error.message); return; }
    flashSuccess('Deleted.');
    load();
  };

  return (
    <div>
      <div className="ap-head">
        <h2>Elite Recordings</h2>
        <p>Paste a YouTube URL — title is fetched automatically from the video metadata. Newest entry shows up first in the public grid.</p>
      </div>

      <form onSubmit={onSubmit} className="card card-pad-lg" style={{ marginBottom: 14 }}>
        <div className="ar-form-grid">
          <label className="ar-field">
            <span>YouTube URL</span>
            <input
              type="url"
              placeholder="https://www.youtube.com/watch?v=…  or  https://youtu.be/…"
              value={form.youtube_url}
              onChange={(e) => setForm({ ...form, youtube_url: e.target.value })}
              required
            />
          </label>
          <label className="ar-field">
            <span>Title (optional — auto from YouTube)</span>
            <input
              type="text"
              placeholder="Leave empty to fetch from YouTube"
              value={form.title}
              onChange={(e) => setForm({ ...form, title: e.target.value })}
            />
          </label>
          <label className="ar-field ar-field-sm">
            <span>Recorded at (optional)</span>
            <input
              type="date"
              value={form.recorded_at}
              onChange={(e) => setForm({ ...form, recorded_at: e.target.value })}
            />
          </label>
        </div>

        {err && <div className="ar-err">{err}</div>}
        {success && <div className="ar-ok">{success}</div>}

        <div style={{ marginTop: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
          <button type="button" className="ar-bulk-toggle" onClick={() => setBulkOpen(o => !o)}>
            <Icon name={bulkOpen ? 'chevDown' : 'chevRight'} size={13} />
            {bulkOpen ? 'Hide bulk add' : 'Bulk add multiple URLs'}
          </button>
          <Button variant="acid" type="submit" disabled={submitting}>
            {submitting ? 'Saving…' : 'Add recording'}
          </Button>
        </div>
      </form>

      {bulkOpen && (
        <form onSubmit={onBulkSubmit} className="card card-pad-lg ar-bulk" style={{ marginBottom: 22 }}>
          <h4 style={{ marginTop: 0 }}>Bulk add — one URL per line</h4>
          <p style={{ color: 'var(--text-mute)', fontSize: 13, marginTop: 6 }}>
            Each line is one YouTube URL. Titles are fetched automatically. Duplicates are skipped.
          </p>
          <textarea
            className="ar-bulk-area"
            rows={8}
            placeholder={`https://youtu.be/oUIv_52WzSA\nhttps://youtu.be/9tn2ajCBt3U\nhttps://youtu.be/6gIbfn6mmwA\n…`}
            value={bulkText}
            onChange={(e) => setBulkText(e.target.value)}
          />
          {bulkLog.length > 0 && (
            <div className="ar-bulk-log">
              {bulkLog.map((l, i) => (
                <div key={i} className={`ar-bulk-row ${l.status.startsWith('added') ? 'ok' : l.status.startsWith('skipped') ? 'skip' : 'err'}`}>
                  <span className="ar-bulk-url">{l.url}</span>
                  <span className="ar-bulk-status">{l.status}</span>
                </div>
              ))}
            </div>
          )}
          <div style={{ marginTop: 12, display: 'flex', justifyContent: 'flex-end' }}>
            <Button variant="acid" type="submit" disabled={bulkBusy}>
              {bulkBusy ? 'Processing…' : 'Add all'}
            </Button>
          </div>
        </form>
      )}

      <h3 style={{ fontSize: 16, marginBottom: 14 }}>Current recordings ({items.length})</h3>

      {loading ? (
        <div className="ar-loading">Loading…</div>
      ) : items.length === 0 ? (
        <div className="ar-empty">No recordings yet. Add the first one above.</div>
      ) : (
        <div className="ar-list">
          {items.map((it) => (
            <div key={it.id} className="ar-row">
              <img
                src={it.thumbnail || ytThumb(it.video_id || extractYouTubeId(it.youtube_url))}
                alt=""
                className="ar-thumb"
                loading="lazy"
              />
              <div className="ar-meta">
                <div className="ar-title">{it.title}</div>
                <div className="ar-sub">
                  <a href={it.youtube_url} target="_blank" rel="noopener noreferrer" className="ar-url">
                    {it.youtube_url}
                  </a>
                </div>
                <div className="ar-sub" style={{ marginTop: 4 }}>
                  Added {new Date(it.created_at).toLocaleString('ro-RO')}
                  {it.recorded_at && <> · Recorded {new Date(it.recorded_at).toLocaleDateString('ro-RO')}</>}
                </div>
              </div>
              <button className="ar-del" onClick={() => onDelete(it.id)} title="Delete">
                <Icon name="x" size={14} /> Delete
              </button>
            </div>
          ))}
        </div>
      )}

      <style>{`
        .ar-form-grid {
          display: grid;
          grid-template-columns: 1fr 1fr 200px;
          gap: 14px;
        }
        @media (max-width: 760px) { .ar-form-grid { grid-template-columns: 1fr; } }
        .ar-field { display: flex; flex-direction: column; gap: 6px; }
        .ar-field span {
          font-family: 'JetBrains Mono', monospace;
          font-size: 10.5px;
          letter-spacing: 0.14em;
          text-transform: uppercase;
          color: var(--text-mute);
        }
        .ar-field input {
          padding: 10px 12px;
          border-radius: 10px;
          background: rgba(255,255,255,0.04);
          border: 1px solid rgba(255,255,255,0.10);
          color: var(--text);
          font: inherit;
          outline: none;
          transition: border-color 0.2s, background 0.2s;
        }
        .ar-field input:focus {
          border-color: rgba(183,255,26,0.45);
          background: rgba(183,255,26,0.04);
        }
        .ar-err {
          margin-top: 12px;
          padding: 10px 12px;
          border-radius: 10px;
          background: rgba(255,80,80,0.08);
          border: 1px solid rgba(255,80,80,0.25);
          color: #ff9090; font-size: 13px;
        }
        .ar-ok {
          margin-top: 12px;
          padding: 10px 12px;
          border-radius: 10px;
          background: rgba(183,255,26,0.08);
          border: 1px solid rgba(183,255,26,0.32);
          color: var(--acid); font-size: 13px;
        }
        .ar-loading, .ar-empty {
          padding: 22px;
          text-align: center;
          color: var(--text-mute);
          border: 1px dashed rgba(255,255,255,0.10);
          border-radius: 14px;
          background: rgba(255,255,255,0.02);
        }
        .ar-list {
          display: grid;
          gap: 10px;
        }
        .ar-row {
          display: grid;
          grid-template-columns: 130px 1fr auto;
          gap: 14px;
          align-items: center;
          padding: 12px;
          border-radius: 14px;
          background: rgba(255,255,255,0.025);
          border: 1px solid rgba(255,255,255,0.08);
          transition: background 0.2s, border-color 0.2s;
        }
        .ar-row:hover { background: rgba(255,255,255,0.04); border-color: rgba(255,255,255,0.14); }
        .ar-thumb {
          width: 130px; aspect-ratio: 16/9;
          object-fit: cover;
          border-radius: 8px;
          background: #050507;
        }
        .ar-title { font-weight: 600; color: var(--text); }
        .ar-sub { font-size: 12px; color: var(--text-mute); }
        .ar-url {
          color: var(--text-mute);
          text-decoration: none;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          display: inline-block;
          max-width: 100%;
        }
        .ar-url:hover { color: var(--acid); }
        .ar-del {
          display: inline-flex; align-items: center; gap: 6px;
          padding: 8px 12px;
          border-radius: 10px;
          background: rgba(255,80,80,0.08);
          border: 1px solid rgba(255,80,80,0.22);
          color: #ff9090;
          font: inherit; font-size: 12px;
          cursor: pointer;
          transition: background 0.2s, border-color 0.2s;
        }
        .ar-del:hover { background: rgba(255,80,80,0.16); border-color: rgba(255,80,80,0.45); }
        .ar-bulk-toggle {
          display: inline-flex; align-items: center; gap: 8px;
          background: transparent;
          border: 1px solid rgba(255,255,255,0.10);
          color: var(--text-dim);
          padding: 8px 12px;
          border-radius: 10px;
          font: inherit; font-size: 12px;
          letter-spacing: 0.06em; text-transform: uppercase;
          font-family: 'JetBrains Mono', monospace;
          cursor: pointer;
          transition: border-color 0.2s, color 0.2s;
        }
        .ar-bulk-toggle:hover { border-color: rgba(183,255,26,0.32); color: var(--acid); }
        .ar-bulk-area {
          width: 100%;
          margin-top: 10px;
          padding: 12px 14px;
          background: rgba(0,0,0,0.35);
          border: 1px solid rgba(255,255,255,0.10);
          color: var(--text);
          border-radius: 10px;
          font-family: 'JetBrains Mono', monospace;
          font-size: 13px;
          line-height: 1.5;
          resize: vertical;
          outline: none;
        }
        .ar-bulk-area:focus { border-color: rgba(183,255,26,0.45); }
        .ar-bulk-log {
          margin-top: 14px;
          max-height: 240px;
          overflow-y: auto;
          padding: 10px 12px;
          background: rgba(0,0,0,0.35);
          border: 1px solid rgba(255,255,255,0.06);
          border-radius: 10px;
        }
        .ar-bulk-row {
          display: flex; gap: 10px; align-items: baseline;
          font-family: 'JetBrains Mono', monospace;
          font-size: 11.5px;
          padding: 4px 0;
          border-bottom: 1px dashed rgba(255,255,255,0.04);
        }
        .ar-bulk-row:last-child { border-bottom: 0; }
        .ar-bulk-url { color: var(--text-mute); flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
        .ar-bulk-status { font-size: 11px; }
        .ar-bulk-row.ok .ar-bulk-status { color: var(--acid); }
        .ar-bulk-row.skip .ar-bulk-status { color: var(--text-mute); }
        .ar-bulk-row.err .ar-bulk-status { color: #ff9090; }
        @media (max-width: 760px) {
          .ar-row { grid-template-columns: 100px 1fr; }
          .ar-thumb { width: 100px; }
          .ar-del { grid-column: 1 / -1; justify-self: stretch; justify-content: center; }
        }
      `}</style>
    </div>
  );
};

Object.assign(window, { EliteRecordings, AdminRecordings });
