/* 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. Uses allorigins as a CORS proxy
   (youtube RSS does not set Access-Control-Allow-Origin).
   ========================================================= */

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

// Try multiple CORS proxies — first that succeeds wins. Different proxies
// have different rate-limit windows, so listing a few raises hit-rate.
const PROXIES = [
  url => `https://api.allorigins.win/raw?url=${encodeURIComponent(url)}`,
  url => `https://corsproxy.io/?${encodeURIComponent(url)}`,
  url => `https://api.codetabs.com/v1/proxy?quest=${encodeURIComponent(url)}`,
  url => `https://thingproxy.freeboard.io/fetch/${url}`,
];

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.slice(0, 3).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();
    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 });

    const tryFetch = async (url) => {
      const res = await fetch(url, { cache: "no-cache" });
      if (!res.ok) throw new Error("status " + res.status);
      const text = await res.text();
      const videos = parseFeed(text);
      if (!videos.length) throw new Error("no entries");
      return videos;
    };

    (async () => {
      // Walk the proxy list; first success wins.
      for (const wrap of PROXIES) {
        if (cancelled) return;
        try {
          const videos = await tryFetch(wrap(FEED_URL));
          if (!cancelled) setState({ loading: false, videos, error: false });
          return;
        } catch (err) {
          // try next
        }
      }
      // Final last-ditch: direct (unlikely to work due to CORS, but cheap)
      try {
        const videos = await tryFetch(FEED_URL);
        if (!cancelled) setState({ loading: false, videos, error: false });
      } catch (e2) {
        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>
          <a href={CHANNEL_URL} target="_blank" rel="noopener noreferrer" className="yt-channel-link">
            @MaharaMedia <Icon name="arrow-right" size={12} strokeWidth={1.8} />
          </a>
        </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 });
