/* global React, window, DOMParser */
const { useState: useState_YT, useEffect: useEffect_YT } = React;

/* =========================================================
   YouTubeFeed — fetches latest 3 videos from a channel's RSS.
   No API key required. YouTube's RSS does not send CORS headers, so we
   walk an ordered list of JSON/proxy sources until one returns entries.
   ========================================================= */

const CHANNEL_ID = "UCnJqIFZlyCKeeW6Jkp5HZHw";
const CHANNEL_URL = `https://www.youtube.com/@MaharaMedia`;
const INSTAGRAM_URL = "https://www.instagram.com/mahara_media/";
const FEED_URL = `https://www.youtube.com/feeds/videos.xml?channel_id=${CHANNEL_ID}`;

function videoIdFrom(s) {
  if (!s) return "";
  const m = String(s).match(/(?:v=|yt:video:|\/vi\/|youtu\.be\/|\/embed\/)([A-Za-z0-9_-]{11})/);
  return m ? m[1] : "";
}

// Ordered source list — first one that returns entries wins.
// rss2json is CORS-friendly and returns JSON; the rest are raw-XML proxies.
const SOURCES = [
  {
    url: `https://api.rss2json.com/v1/api.json?rss_url=${encodeURIComponent(FEED_URL)}`,
    parse: (txt) => {
      const j = JSON.parse(txt);
      if (!j || !j.items) return [];
      return j.items
        .map(it => ({ id: videoIdFrom(it.link) || videoIdFrom(it.guid), title: it.title, published: it.pubDate }))
        .filter(v => v.id);
    },
  },
  { url: `https://corsproxy.io/?${encodeURIComponent(FEED_URL)}`,             parse: (t) => parseFeed(t) },
  { url: `https://api.codetabs.com/v1/proxy?quest=${encodeURIComponent(FEED_URL)}`, parse: (t) => parseFeed(t) },
  { url: FEED_URL, parse: (t) => parseFeed(t) },
];

function parseFeed(xmlText) {
  const doc = new DOMParser().parseFromString(xmlText, "text/xml");
  // Some proxies return JSON-wrapped text; guard against that.
  if (doc.querySelector("parsererror")) {
    try {
      const j = JSON.parse(xmlText);
      const inner = j.contents || j.body || j.data;
      if (typeof inner === "string") return parseFeed(inner);
    } catch {}
    return [];
  }
  const entries = [...doc.querySelectorAll("entry")];
  return entries.map(e => {
    const videoIdEl = e.getElementsByTagNameNS("http://www.youtube.com/xml/schemas/2015", "videoId")[0]
                    || [...e.children].find(c => c.localName === "videoId");
    const id = videoIdEl?.textContent?.trim() || videoIdFrom(e.querySelector("id")?.textContent);
    const title = e.querySelector("title")?.textContent?.trim() || "";
    const published = e.querySelector("published")?.textContent?.trim() || "";
    return { id, title, published };
  }).filter(v => v.id);
}

function formatDate(iso, lang) {
  if (!iso) return "";
  try {
    const d = new Date(iso);
    const opts = { year: "numeric", month: "short", day: "numeric" };
    return d.toLocaleDateString(lang === "ar" ? "ar-EG" : "en-US", opts);
  } catch { return ""; }
}

function YouTubeFeed({ inline = false }) {
  const { L, lang } = useLang();
  const Y = L.youtube;
  const [state, setState] = useState_YT({ loading: true, videos: [], error: false });

  useEffect_YT(() => {
    let cancelled = false;
    setState({ loading: true, videos: [], error: false });

    // Fail fast: a hung proxy must never strand the chain
    const fetchWithTimeout = (url, ms = 6000) => {
      const ctl = typeof AbortController !== "undefined" ? new AbortController() : null;
      return new Promise((resolve, reject) => {
        const timer = setTimeout(() => {
          if (ctl) { try { ctl.abort(); } catch {} }
          reject(new Error("timeout"));
        }, ms);
        fetch(url, ctl ? { cache: "no-cache", signal: ctl.signal } : { cache: "no-cache" })
          .then(r => { clearTimeout(timer); resolve(r); })
          .catch(e => { clearTimeout(timer); reject(e); });
      });
    };

    const tryFetch = async (src) => {
      const res = await fetchWithTimeout(src.url);
      if (!res.ok) throw new Error("status " + res.status);
      const text = await res.text();
      let videos = [];
      try { videos = src.parse(text) || []; } catch { videos = []; }
      if (!videos.length) throw new Error("no entries");
      return videos.slice(0, 3);
    };

    (async () => {
      for (const src of SOURCES) {
        if (cancelled) return;
        try {
          const videos = await tryFetch(src);
          if (!cancelled) setState({ loading: false, videos, error: false });
          return;
        } catch (err) {
          // try the next source
        }
      }
      if (!cancelled) setState({ loading: false, videos: [], error: true });
    })();

    return () => { cancelled = true; };
  }, []);

  // --- Inline variant: vertical stack rendered inside the founder column ---
  if (inline) {
    return (
      <div className="yt-inline">
        <div className="yt-inline-head">
          <span>{Y.eyebrow}</span>
          <span className="yt-links">
            <a href={CHANNEL_URL} target="_blank" rel="noopener noreferrer" className="yt-channel-link">
              @MaharaMedia <Icon name="arrow-right" size={12} strokeWidth={1.8} />
            </a>
            <a href={INSTAGRAM_URL} target="_blank" rel="noopener noreferrer" className="ig-channel" aria-label="Mahara Media on Instagram">
              <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round">
                <rect x="2" y="2" width="20" height="20" rx="5.5"></rect>
                <circle cx="12" cy="12" r="4.2"></circle>
                <circle cx="17.4" cy="6.6" r="1.1" fill="currentColor" stroke="none"></circle>
              </svg>
              @mahara_media
            </a>
          </span>
        </div>
        <div className="yt-inline-list">
          {state.loading && [0,1,2].map(i => (
            <div key={i} className="yt-skeleton inline">
              <div className="thumb" />
              <div className="lns">
                <div className="ln short" />
                <div className="ln" />
              </div>
            </div>
          ))}

          {!state.loading && state.videos.map((v, i) => (
            <a key={v.id}
               className="yt-row"
               href={`https://www.youtube.com/watch?v=${v.id}`}
               target="_blank"
               rel="noopener noreferrer">
              <div className="yt-row-thumb">
                <img src={`https://i.ytimg.com/vi/${v.id}/hqdefault.jpg`}
                     alt={v.title} loading="lazy" />
                <span className="play"><Icon name="play" size={14} strokeWidth={1.6} /></span>
              </div>
              <div>
                <div className="date mono">{formatDate(v.published, lang)}</div>
                <div className="title">{v.title}</div>
              </div>
            </a>
          ))}

          {!state.loading && state.error && (
            <a className="yt-fallback"
               href={CHANNEL_URL}
               target="_blank"
               rel="noopener noreferrer"
               style={{ marginTop: 8 }}>
              <Icon name="play" size={14} strokeWidth={1.8} />
              {Y.fallbackCta}
            </a>
          )}
        </div>
      </div>
    );
  }

  // --- Full section variant (kept for fallback / future use) ---
  return (
    <section className="section">
      <div className="container">
        <Reveal><div className="section-eyebrow">{Y.eyebrow}</div></Reveal>
        <Reveal delay={60}>
          <h2 className="h-section">
            {Y.headline[0]}<br/>{Y.headline[1]}
          </h2>
        </Reveal>
        <Reveal delay={120}><p className="lead">{Y.sub}</p></Reveal>

        <div className="yt-grid">
          {state.loading && [0,1,2].map(i => (
            <div key={i} className="yt-skeleton">
              <div className="thumb" />
              <div className="ln" />
              <div className="ln short" />
            </div>
          ))}

          {!state.loading && state.videos.map((v, i) => (
            <Reveal key={v.id} delay={i * 80}>
              <a className="yt-card"
                 href={`https://www.youtube.com/watch?v=${v.id}`}
                 target="_blank"
                 rel="noopener noreferrer">
                <div className="yt-thumb">
                  <img src={`https://i.ytimg.com/vi/${v.id}/hqdefault.jpg`}
                       alt={v.title} loading="lazy" />
                  <span className="play"><Icon name="play" size={22} strokeWidth={1.6} /></span>
                  <span className="meta mono">YouTube</span>
                </div>
                <div className="title">{v.title}</div>
                <div className="date">{formatDate(v.published, lang)}</div>
              </a>
            </Reveal>
          ))}
        </div>

        {!state.loading && state.error && (
          <div style={{ marginTop: 16 }}>
            <a className="yt-fallback"
               href={CHANNEL_URL}
               target="_blank"
               rel="noopener noreferrer">
              <Icon name="play" size={14} strokeWidth={1.8} />
              {Y.fallbackCta}
            </a>
          </div>
        )}
      </div>
    </section>
  );
}

Object.assign(window, { YouTubeFeed });
