/* MaiAgent Partner Portal — 影音學習中心 (YouTube RSS 即時串接) */

const CHANNEL_ID  = 'UCyxosInZr7x9nStQ13qSxSw';
const CHANNEL_URL = 'https://www.youtube.com/@MaiAgent';

const RSS_URL = `https://www.youtube.com/feeds/videos.xml?channel_id=${CHANNEL_ID}`;

async function fetchYouTubeVideos() {
  // On Cloudflare Pages deployment: use same-origin Pages Function (no CORS)
  // On local dev (localhost): try direct fetch — Chrome allows it for localhost origins
  const isLocal = location.hostname === 'localhost' || location.hostname === '127.0.0.1';
  const endpoint = isLocal ? RSS_URL : '/api/yt-feed';

  const r = await fetch(endpoint, { signal: AbortSignal.timeout(10000) });
  if (!r.ok) throw new Error(`fetch ${r.status}`);
  const text = await r.text();
  const videos = parseRSS(text);
  if (videos.length === 0) throw new Error('empty');
  return videos;
}

const VH_TABS = [
  { id: 'all',      key: 'vh.tab.all' },
  { id: 'seminars', key: 'vh.tab.seminars' },
  { id: 'updates',  key: 'vh.tab.updates' },
];

const VH_GRADIENTS = [
  'linear-gradient(135deg,#0F1733,#1B2B5F)',
  'linear-gradient(135deg,#0D2B1A,#0E4A2E)',
  'linear-gradient(135deg,#1A0A2E,#2D1561)',
  'linear-gradient(135deg,#001A2C,#003558)',
  'linear-gradient(135deg,#1C1000,#3A2800)',
  'linear-gradient(135deg,#0B1F0F,#1A4020)',
];

// Shared: build a normalised video object from raw fields
function makeVideo(videoId, title, published, thumbnail) {
  const isSeminar = /EP\.?\s*\d+|研討會|seminar|雙周|bi-?weekly|技術|tech talk/i.test(title);
  const epMatch   = title.match(/EP\.?\s*(\d+)/i);
  const ep        = epMatch ? `EP.${epMatch[1]}` : null;
  const tags = [];
  if (/RAG/i.test(title))   tags.push('RAG');
  if (/MCP/i.test(title))   tags.push('MCP');
  if (/voice/i.test(title)) tags.push('Voice');
  if (/LINE/i.test(title))  tags.push('LINE');
  const ver = (title.match(/v\d+\.\d+/) || [])[0];
  if (ver) tags.push(ver);
  if (tags.length === 0) tags.push(isSeminar ? 'Tech' : 'Update');
  return { id: videoId, ep, titleZh: title, titleEn: title, date: published, youtubeId: videoId, duration: null, thumbnail, tags, category: isSeminar ? 'seminar' : 'update', isLive: true };
}

// Parse raw YouTube RSS XML → video objects (used by corsproxy path)
function parseRSS(text) {
  return text.split('<entry>').slice(1).map(entry => {
    const videoId   = (entry.match(/<yt:videoId>([^<]+)<\/yt:videoId>/) || [])[1];
    const rawTitle  = (entry.match(/<title>([^<]+)<\/title>/)           || [])[1] || '';
    const title     = rawTitle.replace(/&amp;/g,'&').replace(/&lt;/g,'<').replace(/&gt;/g,'>').replace(/&#39;/g,"'").replace(/&quot;/g,'"');
    const published = (entry.match(/<published>([^T<]+)/)               || [])[1] || '';
    const thumbnail = (entry.match(/media:thumbnail url="([^"]+)"/)     || [])[1] || '';
    if (!videoId || !title) return null;
    return makeVideo(videoId, title, published, thumbnail);
  }).filter(Boolean);
}


// Fallback: merge mock data when RSS unavailable
function getMockVideos() {
  return [
    ...TECH_SEMINARS.map(v  => ({ ...v, category: 'seminar' })),
    ...PRODUCT_UPDATES.map(v => ({ ...v, category: 'update'  })),
  ].sort((a, b) => b.date.localeCompare(a.date));
}

// ── Video card ─────────────────────────────────────────────
const VhVideoCard = ({ video, lang, t, onWatch, isLatest }) => {
  const seed = (video.id || '').replace(/\D/g,'').slice(-3);
  const bg   = VH_GRADIENTS[parseInt(seed || '0', 10) % VH_GRADIENTS.length];
  const isSeminar  = video.category === 'seminar';
  const catLabel   = t(isSeminar ? 'vh.cat.seminar' : 'vh.cat.update');
  const catColor   = isSeminar ? '#26C281' : '#1F4FFF';

  return (
    <div
      className="card--lift"
      style={{ background: 'white', border: '1px solid var(--mai-border)', borderRadius: 14, overflow: 'hidden', cursor: 'pointer', display: 'flex', flexDirection: 'column' }}
      onClick={() => onWatch(video)}
    >
      {/* Thumbnail */}
      <div style={{ aspectRatio: '16/9', position: 'relative', overflow: 'hidden', flexShrink: 0, background: bg, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        {video.thumbnail && (
          <img
            src={video.thumbnail}
            alt={video.titleZh}
            style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover' }}
            onError={e => { e.target.style.display = 'none'; }}
          />
        )}
        {/* Badges */}
        <div style={{ position: 'absolute', top: 10, left: 10, display: 'flex', gap: 6, flexWrap: 'wrap', zIndex: 2 }}>
          {video.ep && (
            <span style={{ background: 'rgba(0,0,0,0.55)', color: 'white', fontSize: 11, fontWeight: 700, padding: '3px 9px', borderRadius: 99, backdropFilter: 'blur(4px)' }}>
              {video.ep}
            </span>
          )}
          <span style={{ background: catColor, color: 'white', fontSize: 11, fontWeight: 700, padding: '3px 9px', borderRadius: 99 }}>
            {catLabel}
          </span>
          {isLatest && (
            <span style={{ background: '#FF7A3D', color: 'white', fontSize: 11, fontWeight: 700, padding: '3px 9px', borderRadius: 99 }}>
              NEW
            </span>
          )}
        </div>
        {/* Play button */}
        <div style={{ position: 'relative', zIndex: 2, width: 48, height: 48, borderRadius: '50%', background: 'rgba(0,0,0,0.5)', display: 'flex', alignItems: 'center', justifyContent: 'center', border: '2px solid rgba(255,255,255,0.4)', backdropFilter: 'blur(2px)' }}>
          <Icon name="play" size={18} style={{ color: 'white', marginLeft: 3 }} />
        </div>
        {/* Duration */}
        {video.duration && (
          <div style={{ position: 'absolute', bottom: 8, right: 10, background: 'rgba(0,0,0,0.65)', color: 'white', fontSize: 11, fontWeight: 600, padding: '3px 8px', borderRadius: 6, zIndex: 2 }}>
            {video.duration}
          </div>
        )}
      </div>

      {/* Body */}
      <div style={{ padding: '14px 16px 16px', flex: 1, display: 'flex', flexDirection: 'column', gap: 8 }}>
        <div style={{ fontSize: 13.5, fontWeight: 700, color: 'var(--mai-fg)', lineHeight: 1.45 }}>
          {lang === 'zh' ? video.titleZh : video.titleEn}
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 12, color: 'var(--mai-fg-3)' }}>
          <span className="row gap-1"><Icon name="calendar" size={12} />{video.date}</span>
        </div>
        <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginTop: 2 }}>
          {video.tags.map(tag => (
            <span key={tag} style={{ background: '#F0F4FF', color: '#1F4FFF', fontSize: 11, fontWeight: 600, padding: '2px 8px', borderRadius: 99 }}>{tag}</span>
          ))}
        </div>
      </div>
    </div>
  );
};

// ── Video modal ────────────────────────────────────────────
const VhVideoModal = ({ video, lang, t, onClose }) => {
  if (!video) return null;
  const isSeminar = video.category === 'seminar';
  return (
    <div className="modal-backdrop" onClick={onClose} style={{ zIndex: 9999 }}>
      <div onClick={e => e.stopPropagation()} style={{ background: '#0a0c14', borderRadius: 16, width: '100%', maxWidth: 860, margin: 'auto', overflow: 'hidden', boxShadow: '0 24px 80px rgba(0,0,0,0.85)' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '14px 20px', borderBottom: '1px solid rgba(255,255,255,0.1)' }}>
          <div>
            <div style={{ display: 'flex', gap: 8, alignItems: 'center', marginBottom: 4 }}>
              {video.ep && <span style={{ color: '#26C281', fontSize: 12, fontWeight: 700 }}>{video.ep}</span>}
              <span style={{ background: 'rgba(255,255,255,0.1)', color: 'rgba(255,255,255,0.6)', fontSize: 11, fontWeight: 600, padding: '2px 8px', borderRadius: 99 }}>
                {t(isSeminar ? 'vh.cat.seminar' : 'vh.cat.update')}
              </span>
            </div>
            <div style={{ color: 'white', fontWeight: 700, fontSize: 15, lineHeight: 1.35 }}>
              {lang === 'zh' ? video.titleZh : video.titleEn}
            </div>
          </div>
          <button onClick={onClose} style={{ background: 'rgba(255,255,255,0.08)', border: 'none', color: 'white', borderRadius: 8, padding: '6px 12px', cursor: 'pointer', fontSize: 16, lineHeight: 1 }}>✕</button>
        </div>
        <div style={{ aspectRatio: '16/9', background: '#000' }}>
          <iframe
            src={`https://www.youtube.com/embed/${video.youtubeId}?autoplay=1&rel=0`}
            style={{ width: '100%', height: '100%', border: 'none', display: 'block' }}
            allow="autoplay; encrypted-media; picture-in-picture"
            allowFullScreen
          />
        </div>
        <div style={{ padding: '12px 20px 16px', display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap' }}>
          <span style={{ fontSize: 12, color: 'rgba(255,255,255,0.4)' }}>{video.date}</span>
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
            {video.tags.map(tag => (
              <span key={tag} style={{ background: 'rgba(31,79,255,0.25)', color: '#7BA7FF', fontSize: 11, fontWeight: 600, padding: '2px 8px', borderRadius: 99 }}>{tag}</span>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
};

// ── Skeleton card ──────────────────────────────────────────
const VhSkeleton = () => (
  <div style={{ background: 'white', border: '1px solid var(--mai-border)', borderRadius: 14, overflow: 'hidden' }}>
    <div style={{ aspectRatio: '16/9', background: '#EEF0F8' }} className="animate-pulse" />
    <div style={{ padding: '14px 16px 16px', display: 'flex', flexDirection: 'column', gap: 8 }}>
      <div style={{ height: 14, background: '#EEF0F8', borderRadius: 6, width: '85%' }} />
      <div style={{ height: 14, background: '#EEF0F8', borderRadius: 6, width: '60%' }} />
      <div style={{ height: 22, background: '#F4F6FF', borderRadius: 99, width: 60 }} />
    </div>
  </div>
);

// ── Main page ──────────────────────────────────────────────
const VideoHubPage = ({ t, lang }) => {
  const [tab,      setTab]      = React.useState('all');
  const [playing,  setPlaying]  = React.useState(null);
  const [videos,   setVideos]   = React.useState(null);   // null = loading
  const [usingMock, setUsingMock] = React.useState(false);

  React.useEffect(() => {
    fetchYouTubeVideos()
      .then(items => {
        const parsed = parseItems(items);
        if (parsed.length === 0) throw new Error('empty');
        setVideos(parsed);
      })
      .catch(() => {
        setVideos(getMockVideos());
        setUsingMock(true);
      });
  }, []);

  const isLoading = videos === null;

  const counts = React.useMemo(() => ({
    all:      (videos || []).length,
    seminars: (videos || []).filter(v => v.category === 'seminar').length,
    updates:  (videos || []).filter(v => v.category === 'update').length,
  }), [videos]);

  const filtered = !videos ? [] :
    tab === 'all'      ? videos :
    tab === 'seminars' ? videos.filter(v => v.category === 'seminar') :
                         videos.filter(v => v.category === 'update');

  const latestId = (videos || [])[0]?.id;

  return (
    <div className="page">
      <div className="page-header">
        <div className="page-header__title">
          <div className="page-header__eyebrow">{lang === 'zh' ? '夥伴中心' : 'Partner Hub'}</div>
          <h1>{t('vh.title')}</h1>
          <div className="page-header__sub">{t('vh.sub')}</div>
        </div>
        <div className="page-header__actions">
          <Btn variant="ghost" icon="play-circle" onClick={() => window.open(CHANNEL_URL, '_blank')}>
            {t('vh.youtube')}
          </Btn>
        </div>
      </div>

      {/* Mock data notice */}
      {usingMock && (
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '10px 14px', background: '#FFFBF0', border: '1px solid #FDE68A', borderRadius: 10, marginBottom: 16, fontSize: 12.5, color: '#B45309' }}>
          <Icon name="wifi-off" size={14} style={{ flexShrink: 0 }} />
          {lang === 'zh' ? '目前無法連線至 YouTube，顯示快取資料' : 'Unable to reach YouTube — showing cached data'}
        </div>
      )}

      {/* Tab bar */}
      <div className="table-toolbar" style={{ background: 'white', border: '1px solid var(--mai-border)', borderRadius: 12, marginBottom: 20 }}>
        <div className="table-toolbar__filters">
          {VH_TABS.map(x => (
            <button key={x.id} className={`filter-chip ${tab === x.id ? 'is-active' : ''}`} onClick={() => setTab(x.id)}>
              {t(x.key)}
              {!isLoading && <span className="filter-chip__count">{counts[x.id]}</span>}
            </button>
          ))}
        </div>
        {!isLoading && !usingMock && (
          <div style={{ fontSize: 12, color: 'var(--mai-fg-3)', paddingRight: 16, display: 'flex', alignItems: 'center', gap: 6 }}>
            <Icon name="check-circle" size={13} style={{ color: '#26C281' }} />
            {lang === 'zh' ? '已連線至 YouTube 頻道' : 'Live from YouTube'}
          </div>
        )}
      </div>

      {/* Grid */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill,minmax(288px,1fr))', gap: 18 }}>
        {isLoading
          ? Array.from({ length: 6 }).map((_, i) => <VhSkeleton key={i} />)
          : filtered.map(video => (
              <VhVideoCard
                key={video.id}
                video={video}
                lang={lang}
                t={t}
                onWatch={setPlaying}
                isLatest={video.id === latestId}
              />
            ))
        }
      </div>

      {!isLoading && filtered.length === 0 && (
        <div className="empty">
          <Icon name="video" />
          <div>{lang === 'zh' ? '目前沒有影片' : 'No videos yet'}</div>
        </div>
      )}

      {playing && <VhVideoModal video={playing} lang={lang} t={t} onClose={() => setPlaying(null)} />}
    </div>
  );
};

window.VideoHubPage = VideoHubPage;
