/**
 * YouTube playlist for the "videoPlaylistSection".
 * The section stores the full list (editable in Sanity). At build time the playlist's public RSS
 * feed (no API key, latest 15 videos) is merged in, so new meditations appear on the next build
 * without anyone typing them in. If YouTube is unreachable the stored list is used as is.
 */
export type Video = { videoId: string; number?: number; title: string; duration?: string };

const SUFFIX = /\s*(?:\/\/|[-–])\s*מדיטציה ו?ד[י]?מיון מודרך.*$/;

/** "12. מז"ל - מקום זמן ולשון // מדיטציה ודמיון מודרך מאת שנינה" → { number: 12, title: 'מז"ל - מקום זמן ולשון' } */
export function parseTitle(raw: string): { number?: number; title: string } {
  const m = raw.match(/^\s*(\d+)\s*[.)]\s*(.*)$/);
  const rest = (m ? m[2] : raw).replace(SUFFIX, '').replace(/\s*\/\/\s*$/, '').trim();
  return { number: m ? Number(m[1]) : undefined, title: rest || raw.trim() };
}

export function playlistId(url: string | undefined): string | null {
  const m = (url ?? '').match(/[?&]list=([\w-]+)/);
  return m ? m[1] : null;
}

const decode = (s: string) =>
  s.replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&apos;/g, "'").replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&');

const feeds = new Map<string, Promise<Video[]>>();

function fetchFeed(id: string): Promise<Video[]> {
  if (!feeds.has(id)) {
    feeds.set(id, (async () => {
      try {
        const res = await fetch(`https://www.youtube.com/feeds/videos.xml?playlist_id=${id}`, { signal: AbortSignal.timeout(8000) });
        if (!res.ok) throw new Error(`HTTP ${res.status}`);
        const xml = await res.text();
        return [...xml.matchAll(/<entry>([\s\S]*?)<\/entry>/g)].map(([, e]) => {
          const videoId = e.match(/<yt:videoId>([^<]+)</)?.[1] ?? '';
          return { videoId, ...parseTitle(decode(e.match(/<title>([^<]*)</)?.[1] ?? '')) };
        }).filter((v) => v.videoId);
      } catch (err) {
        console.warn('[youtube] playlist feed skipped:', (err as Error).message);
        return [];
      }
    })());
  }
  return feeds.get(id)!;
}

/** Stored videos + any newer ones from the feed, in playlist order (by number, then as listed). */
export async function getPlaylistVideos(section: { playlistUrl?: string; videos?: Video[] }): Promise<Video[]> {
  const stored = (section.videos ?? []).filter((v) => v?.videoId);
  const id = playlistId(section.playlistUrl);
  const fresh = id ? await fetchFeed(id) : [];
  const known = new Set(stored.map((v) => v.videoId));
  const all = [...stored, ...fresh.filter((v) => !known.has(v.videoId)).reverse()];
  return all
    .map((v, i) => ({ v, i }))
    .sort((a, b) => (a.v.number ?? Infinity) - (b.v.number ?? Infinity) || a.i - b.i)
    .map(({ v }) => v);
}
