// discover.jsx — Discover page (Vidu-style, uses shared components)

const _discoverAPI = {
  banners: (position = 'discover') =>
    fetch('/api/v1/banners?position=' + position).then(r => r.json()),
  templates: (mediaType = '', category = '', q = '', page = 1, pageSize = 20) => {
    let url = '/api/v1/templates?page=' + page + '&page_size=' + pageSize;
    if (mediaType) url += '&media_type=' + mediaType;
    if (category) url += '&category=' + category;
    if (q) url += '&q=' + encodeURIComponent(q);
    return fetch(url).then(r => r.json());
  },
};

// ─── Banner carousel ──────────────────────────────────────────────────────────
const BannerCarousel = ({ banners }) => {
  const { isMobile } = useBreakpoint();
  if (isMobile || !banners || banners.length === 0) return null;
  return (
    <div className="yt-fadein" style={{ marginBottom: 28 }}>
      <Carousel items={banners} show={Math.min(3, banners.length)} gap={16} interval={5000} loop={banners.length > 3}
        renderItem={(b) => (
          <a href={b.link_url || '#'} className="yt-card" style={{ display: 'block', textDecoration: 'none' }}>
            <div style={{ position: 'relative', aspectRatio: '2.2/1', overflow: 'hidden', background: 'var(--bg-2)', borderRadius: 14 }}>
              <SafeMedia src={b.media_url} type={b.media_type}
                style={{ width: '100%', height: '100%' }} autoPlay loop />
              <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(180deg, transparent 30%, rgba(0,0,0,0.7) 100%)' }} />
              <div style={{ position: 'absolute', bottom: 16, left: 18, right: 18 }}>
                <div style={{ fontSize: 18, fontWeight: 700, color: '#fff', textShadow: '0 2px 8px rgba(0,0,0,0.5)' }}>{b.title}</div>
                {b.subtitle && <div style={{ fontSize: 12, color: 'rgba(255,255,255,0.75)', marginTop: 4 }}>{b.subtitle}</div>}
              </div>
            </div>
          </a>
        )} />
    </div>
  );
};

// InspirationCard is now in shared.jsx (window.InspirationCard)

// ─── Grid with NEW/HOT badges ────────────────────────────────────────────────
const DiscoverGrid = ({ templates }) => {
  const byDate = [...templates].sort((a, b) => new Date(b.created_at) - new Date(a.created_at));
  const newIds = new Set(byDate.slice(0, 4).map(t => t.id));
  const byUse = [...templates].filter(t => (t.use_count || 0) > 0).sort((a, b) => (b.use_count || 0) - (a.use_count || 0));
  const hotIds = new Set(byUse.slice(0, 3).map(t => t.id));
  // Cap column count so columns aren't empty when few items
  const cols = Math.min(5, Math.max(2, templates.length));
  return (
    <div className="yt-masonry" style={{ columnCount: cols }}>
      {templates.map(t => (
        <InspirationCard key={t.id} tpl={t} isNew={newIds.has(t.id) && !hotIds.has(t.id)} isHot={hotIds.has(t.id)} />
      ))}
    </div>
  );
};

// ─── Main screen ──────────────────────────────────────────────────────────────
const DiscoverScreen = () => {
  const { t } = useI18n();
  const { isMobile, w } = useBreakpoint();
  const pagePad = isMobile ? '12px 12px 80px' : w >= 2560 ? '32px 48px 60px' : '24px 24px 60px';

  // Google OAuth callback is handled globally by api.js

  const [banners, setBanners] = React.useState(null);
  const [templates, setTemplates] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [page, setPage] = React.useState(1);
  const [hasMore, setHasMore] = React.useState(true);
  const [tab, setTab] = React.useState('all');
  const [category, setCategory] = React.useState(''); // '' | 'work' | 'template'
  const [searchInput, setSearchInput] = React.useState('');
  const [q, setQ] = React.useState(''); // 实际请求用的 query（debounced）
  const loaderRef = React.useRef(null);

  React.useEffect(() => {
    _discoverAPI.banners('discover').then(d => setBanners(d.items || []));
  }, []);

  // Debounce search input → q（350ms）
  React.useEffect(() => {
    const timer = setTimeout(() => setQ(searchInput.trim()), 350);
    return () => clearTimeout(timer);
  }, [searchInput]);

  // Reset on tab / category / q change
  React.useEffect(() => {
    setPage(1);
    setHasMore(true);
    setLoading(true);
  }, [tab, category, q]);

  // Fetch page
  React.useEffect(() => {
    if (!hasMore && page > 1) return;
    setLoading(true);
    const mediaType = tab === 'all' ? '' : tab;
    _discoverAPI.templates(mediaType, category, q, page, 20).then(d => {
      const items = d.items || [];
      setTemplates(prev => page === 1 ? items : [...prev, ...items]);
      setHasMore(items.length >= 20);
      setLoading(false);
    });
  }, [tab, category, q, page]);

  // Infinite scroll: observe sentinel
  React.useEffect(() => {
    const el = loaderRef.current;
    if (!el) return;
    const obs = new IntersectionObserver(entries => {
      if (entries[0].isIntersecting && hasMore && !loading) {
        setPage(p => p + 1);
      }
    }, { rootMargin: '200px' });
    obs.observe(el);
    return () => obs.disconnect();
  }, [hasMore, loading]);

  return (
    <AppShell active="discover">
      <div style={{ overflowY: 'auto', height: '100%' }}>
        <div style={{ padding: pagePad }}>

          {/* ── Banners ── */}
          {banners === null ? (
            <SkeletonBanner count={3} />
          ) : banners.length > 0 ? (
            <BannerCarousel banners={banners} />
          ) : null}

          {/* ── Header ── */}
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, marginBottom: 16, flexWrap: isMobile ? 'wrap' : 'nowrap' }}>
            <h2 style={{ fontSize: 22, fontWeight: 700, color: 'var(--fg-0)', margin: 0, flexShrink: 0 }}>{t('discover.title')}</h2>

            {/* 搜索框 */}
            <div style={{
              display: 'flex', alignItems: 'center', gap: 8,
              flex: isMobile ? '1 1 100%' : '0 1 320px',
              padding: '0 12px', height: 40, borderRadius: 999,
              background: 'rgba(255,255,255,0.04)', border: '1px solid var(--line-2)',
              transition: 'border-color .12s, box-shadow .12s',
            }}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="var(--fg-3)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ flexShrink: 0 }}>
                <circle cx="11" cy="11" r="7"/>
                <line x1="20" y1="20" x2="16.65" y2="16.65"/>
              </svg>
              <input
                type="search"
                value={searchInput}
                onChange={e => setSearchInput(e.target.value)}
                placeholder={t('discover.searchPlaceholder') || '搜索作品 / 提示词...'}
                aria-label="搜索"
                style={{
                  flex: 1, minWidth: 0, border: 'none', background: 'transparent',
                  outline: 'none', color: 'var(--fg-0)', fontSize: 13,
                }}
              />
              {searchInput && (
                <button onClick={() => setSearchInput('')} aria-label="清空搜索" style={{
                  width: 22, height: 22, borderRadius: 999, border: 'none',
                  background: 'rgba(255,255,255,0.08)', color: 'var(--fg-2)', cursor: 'pointer',
                  display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
                }}>
                  <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
                </button>
              )}
            </div>

            {/* 移动端隐藏 Submit；桌面端跳到视频创建页 */}
            {!isMobile && (
              <a href="/create2video?tab=ref" className="yt-btn yt-btn-ghost" style={{ height: 40, fontSize: 13, textDecoration: 'none', display: 'inline-flex', alignItems: 'center', gap: 6, flexShrink: 0 }}>
                <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></svg>
                {t('discover.submit')}
              </a>
            )}
          </div>

          {/* ── Filter pills ── */}
          <div style={{ display: 'flex', gap: 6, marginBottom: 24, alignItems: 'center', overflowX: isMobile ? 'auto' : 'visible', scrollbarWidth: 'none', flexShrink: 0 }}>
            {[
              { value: 'all', label: t('discover.all') },
              { value: 'image', label: t('creation.image') },
              { value: 'video', label: t('nav.video') },
            ].map(f => (
              <button key={f.value} onClick={() => setTab(f.value)}
                className={`yt-pill ${tab === f.value ? 'is-active' : ''}`}
                style={{ flexShrink: 0 }}>
                {f.label}
              </button>
            ))}
            <div style={{ width: 1, height: 16, background: 'var(--line-2)', margin: '0 4px', flexShrink: 0 }} />
            {[
              { value: '', label: t('discover.unlimited') },
              { value: 'work', label: t('discover.works') },
              { value: 'template', label: t('discover.templates') },
            ].map(f => (
              <button key={f.value} onClick={() => setCategory(f.value)}
                className={`yt-pill ${category === f.value ? 'is-active' : ''}`}
                style={{ flexShrink: 0 }}>
                {f.label}
              </button>
            ))}
          </div>

          {/* ── Grid ── */}
          {templates.length > 0 ? (
            <DiscoverGrid templates={templates} />
          ) : !loading ? (
            <EmptyState
              icon={tab === 'video' ? 'video' : 'image'}
              title={t('discover.noWorks')}
              subtitle={t('discover.publishInstructions')}
            />
          ) : null}

          {/* Loading / infinite scroll sentinel */}
          {loading && <SkeletonGrid count={10} />}
          <div ref={loaderRef} style={{ height: 1 }} />
          {!hasMore && templates.length > 0 && (
            <div style={{ textAlign: 'center', padding: '24px 0', color: 'var(--fg-3)', fontSize: 12 }}>— {t('discover.allLoaded')} —</div>
          )}

        </div>
      </div>
    </AppShell>
  );
};

Object.assign(window, { DiscoverScreen });
