/* Medya app — derece, ders no ve konuya göre filtreli video listesi. */

const PAGE_SIZE = 12;

function youtubeUrl(item){
  if (item.type === 'playlist'){
    return 'https://www.youtube.com/playlist?list=' + item.playlistId;
  }
  if (item.playlistId){
    return 'https://www.youtube.com/watch?v=' + item.videoId + '&list=' + item.playlistId;
  }
  return 'https://www.youtube.com/watch?v=' + item.videoId;
}

function thumbUrl(item){
  if (item.thumb) return item.thumb;
  if (item.type === 'video' && item.videoId){
    return 'https://img.youtube.com/vi/' + item.videoId + '/mqdefault.jpg';
  }
  return null;
}

const AUTHOR_DEFAULT = 'mo';

function MediaApp(){
  const [activeAuthors, setActiveAuthors] = React.useState(new Set());
  const [activeCourses, setActiveCourses] = React.useState(new Set());
  const [activeLessons, setActiveLessons] = React.useState(new Set());
  const [activeTopics, setActiveTopics] = React.useState(new Set());
  const [search, setSearch] = React.useState('');
  const [sort, setSort] = React.useState('default');
  const [page, setPage] = React.useState(1);
  const listRef = React.useRef(null);
  const isInitial = React.useRef(true);

  const toggle = (set, setter, value) => {
    const n = new Set(set);
    n.has(value) ? n.delete(value) : n.add(value);
    setter(n);
    setPage(1);
  };

  const clearAll = () => {
    setActiveAuthors(new Set());
    setActiveCourses(new Set());
    setActiveLessons(new Set());
    setActiveTopics(new Set());
    setSearch('');
    setPage(1);
  };

  // Counts (unfiltered totals)
  const counts = React.useMemo(() => {
    const byAuthor = {};
    const byCourse = {};
    const byTopic = {};
    window.MEDIA.forEach(m => {
      const a = m.author || AUTHOR_DEFAULT;
      byAuthor[a] = (byAuthor[a] || 0) + 1;
      byCourse[m.course] = (byCourse[m.course] || 0) + 1;
      if (m.topic) byTopic[m.topic] = (byTopic[m.topic] || 0) + 1;
    });
    return { byAuthor, byCourse, byTopic };
  }, []);

  const presentTopics = React.useMemo(() =>
    (window.TOPICS || []).filter(t => (counts.byTopic[t.id] || 0) > 0)
  , [counts]);

  // Lesson options — distinct base lesson numbers (Math.floor) among items
  // that pass the course filter. Sub-parts like 2/1 and 2/2 collapse into
  // the base "2" pill, so picking 2 also surfaces 2/1 and 2/2.
  const lessonOptions = React.useMemo(() => {
    const seen = {};
    window.MEDIA.forEach(m => {
      if (m.lessonNum == null) return;
      if (activeCourses.size > 0 && !activeCourses.has(m.course)) return;
      const base = Math.floor(m.lessonNum);
      if (!seen[base]){
        seen[base] = { label: String(base), num: base };
      }
    });
    return Object.values(seen).sort((a, b) => a.num - b.num);
  }, [activeCourses]);

  // Filtered list
  const filtered = React.useMemo(() => {
    let r = window.MEDIA.slice();
    if (activeAuthors.size > 0){
      r = r.filter(m => activeAuthors.has(m.author || AUTHOR_DEFAULT));
    }
    if (activeCourses.size > 0){
      r = r.filter(m => activeCourses.has(m.course));
    }
    if (activeLessons.size > 0){
      r = r.filter(m =>
        m.lessonNum != null && activeLessons.has(String(Math.floor(m.lessonNum)))
      );
    }
    if (activeTopics.size > 0){
      r = r.filter(m => m.topic && activeTopics.has(m.topic));
    }
    if (search.trim()){
      const s = search.toLowerCase();
      r = r.filter(m =>
        (m.title || '').toLowerCase().includes(s) ||
        (m.subtitle || '').toLowerCase().includes(s)
      );
    }
    r.sort((a, b) => {
      switch(sort){
        case 'lesson-asc':
          return (a.lessonNum || 9999) - (b.lessonNum || 9999) ||
                 (a.title || '').localeCompare(b.title || '', 'tr');
        case 'lesson-desc':
          return (b.lessonNum || 0) - (a.lessonNum || 0) ||
                 (a.title || '').localeCompare(b.title || '', 'tr');
        case 'title-asc':
          return (a.title || '').localeCompare(b.title || '', 'tr');
        default: {
          // Course order (as declared in COURSES) then lesson number, then id.
          const order = Object.keys(window.COURSES);
          const ai = order.indexOf(a.course);
          const bi = order.indexOf(b.course);
          if (ai !== bi) return ai - bi;
          const an = a.lessonNum != null ? a.lessonNum : 9999;
          const bn = b.lessonNum != null ? b.lessonNum : 9999;
          return an - bn || (a.id || 0) - (b.id || 0);
        }
      }
    });
    return r;
  }, [activeAuthors, activeCourses, activeLessons, activeTopics, search, sort]);

  const totalPages = Math.max(1, Math.ceil(filtered.length / PAGE_SIZE));
  const safePage = Math.min(page, totalPages);
  const paged = filtered.slice((safePage-1)*PAGE_SIZE, safePage*PAGE_SIZE);

  React.useEffect(() => {
    if (isInitial.current){ isInitial.current = false; return; }
    const el = listRef.current;
    if (!el) return;
    const top = el.getBoundingClientRect().top + window.scrollY - 90;
    window.scrollTo({ top, behavior: 'smooth' });
  }, [page]);

  // Kategori filter: alphabetical (locale-aware against the active language)
  const courseList = Object.keys(window.COURSES).sort((a, b) =>
    window.tn(window.COURSES[a].name).localeCompare(
      window.tn(window.COURSES[b].name),
      window.LANG || 'tr')
  );

  return (
    <React.Fragment>
      <aside className="filters">
        <div className="filter-group">
          <h4>{window.t('filter.author')} <span className="count">{Object.keys(window.AUTHORS).reduce((s, a) => s + (counts.byAuthor[a] || 0), 0)}</span></h4>
          <div className="author-tabs">
            {Object.keys(window.AUTHORS).map(id => {
              const n = counts.byAuthor[id] || 0;
              const disabled = n === 0;
              return (
                <button key={id}
                  disabled={disabled}
                  className={activeAuthors.has(id) ? 'active' : (disabled ? 'is-disabled' : '')}
                  onClick={disabled ? undefined : () => toggle(activeAuthors, setActiveAuthors, id)}
                  title={disabled ? window.t('filters.disabled-tip-media') : undefined}>
                  {window.AUTHORS[id].short} <span className="yr">{n} {window.t('count.video')}</span>
                </button>
              );
            })}
          </div>
        </div>

        <div className="filter-group">
          <h4>{window.t('filter.category')} <span className="count">{window.MEDIA.length}</span></h4>
          {courseList.map(id => {
            const n = counts.byCourse[id] || 0;
            const disabled = n === 0;
            return (
              <div key={id}
                className={'filter-row ' + (activeCourses.has(id) ? 'active' : '') + (disabled ? ' is-disabled' : '')}
                onClick={disabled ? undefined : () => {
                  toggle(activeCourses, setActiveCourses, id);
                  // course değişince lesson seçimini sıfırla — etkin değilse karışıyor
                  setActiveLessons(new Set());
                }}>
                <span className="chk"></span>
                <span className="label">{window.tn(window.COURSES[id].name)}</span>
                <span className="num">{n}</span>
              </div>
            );
          })}
        </div>

        {lessonOptions.length > 0 && (
          <div className="filter-group">
            <h4>{window.t('filter.lesson')} <span className="count">{lessonOptions.length}</span></h4>
            <div className="lesson-pills">
              {lessonOptions.map(l => (
                <button key={l.label}
                  className={'lesson-pill ' + (activeLessons.has(l.label) ? 'active' : '')}
                  onClick={() => toggle(activeLessons, setActiveLessons, l.label)}>
                  {l.label}
                </button>
              ))}
            </div>
          </div>
        )}

        {presentTopics.length > 0 && (
          <div className="filter-group">
            <h4>{window.t('filter.topic')}</h4>
            {presentTopics.map(t => (
              <div key={t.id}
                className={'filter-row ' + (activeTopics.has(t.id) ? 'active' : '')}
                onClick={() => toggle(activeTopics, setActiveTopics, t.id)}>
                <span className="chk"></span>
                <span className="label">{window.tn(t.label)}</span>
                <span className="num">{counts.byTopic[t.id] || 0}</span>
              </div>
            ))}
          </div>
        )}

        <button className="clearbtn" onClick={clearAll}>
          {window.t('filters.clear')}
        </button>
      </aside>

      <main>
        <div className="results-head">
          <div className="results-count">
            <strong>{filtered.length}</strong> <em>{window.t('count.entries')}</em>
          </div>
          <div className="results-tools">
            <div className="search">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <circle cx="11" cy="11" r="7"/><path d="M21 21l-4.3-4.3"/>
              </svg>
              <input
                placeholder={window.t('search.media')}
                value={search}
                onChange={e => { setSearch(e.target.value); setPage(1); }}
              />
            </div>
            <div className="sort">
              <span>{window.t('sort.label')}</span>
              <select value={sort} onChange={e => setSort(e.target.value)}>
                <option value="default">{window.t('sort.default')}</option>
                <option value="lesson-asc">{window.t('sort.lesson-asc')}</option>
                <option value="lesson-desc">{window.t('sort.lesson-desc')}</option>
                <option value="title-asc">{window.t('sort.alpha')}</option>
              </select>
            </div>
          </div>
        </div>

        {(activeAuthors.size > 0 || activeCourses.size > 0 || activeLessons.size > 0 || activeTopics.size > 0 || search) && (
          <div className="active-chips">
            <span className="label">{window.t('filters.active')}</span>
            {Array.from(activeAuthors).map(a => (
              <span key={a} className="chip" onClick={() => toggle(activeAuthors, setActiveAuthors, a)}>
                {window.AUTHORS[a].name} <span className="x">×</span>
              </span>
            ))}
            {Array.from(activeCourses).map(c => (
              <span key={c} className="chip" onClick={() => toggle(activeCourses, setActiveCourses, c)}>
                {window.tn(window.COURSES[c].name)} <span className="x">×</span>
              </span>
            ))}
            {Array.from(activeLessons).map(l => (
              <span key={l} className="chip" onClick={() => toggle(activeLessons, setActiveLessons, l)}>
                {l}. {window.t('media.lesson')} <span className="x">×</span>
              </span>
            ))}
            {Array.from(activeTopics).map(t => (
              <span key={t} className="chip" onClick={() => toggle(activeTopics, setActiveTopics, t)}>
                {window.tn((window.TOPICS.find(x => x.id === t) || {}).label) || t} <span className="x">×</span>
              </span>
            ))}
            {search && (
              <span className="chip" onClick={() => setSearch('')}>
                "{search}" <span className="x">×</span>
              </span>
            )}
          </div>
        )}

        <div className="media-grid" ref={listRef}>
          {paged.map(item => {
            const courseLabel = window.tn((window.COURSES[item.course] || {}).short) || item.course;
            const t = thumbUrl(item);
            // Lesson cards: render localized "X. Ders/Lesson/Lektion".
            // Generic "Söyleşi / Röportaj" titles also get localized.
            // V. Seven items keep their specific descriptive titles.
            let titleLabel;
            if (item.lessonLabel){
              titleLabel = item.lessonLabel + '. ' + window.t('media.lesson-cap');
            } else if (item.title === 'Söyleşi / Röportaj'){
              titleLabel = window.t('media.interview-title');
            } else {
              titleLabel = item.title;
            }
            return (
              <a key={item.id}
                 href={youtubeUrl(item)}
                 target="_blank"
                 rel="noopener noreferrer"
                 className={'media-card ' + (item.type === 'playlist' ? 'is-playlist' : '')}>
                <div className="media-thumb">
                  {t
                    ? <img src={t} alt="" loading="lazy" />
                    : <div className="media-thumb-fallback">
                        <span className="media-thumb-tag">{item.type === 'playlist' ? window.t('media.playlist') : window.t('media.video')}</span>
                      </div>}
                  <span className="media-play">▶</span>
                </div>
                <div className="media-meta">
                  <span className="media-tag">
                    {courseLabel}
                    {item.lessonLabel ? ' · ' + item.lessonLabel + '. ' + window.t('media.lesson') : ''}
                  </span>
                  <h3 className="media-title">{titleLabel}</h3>
                  {item.subtitle && <p className="media-sub">{item.subtitle}</p>}
                  {item.duration && <span className="media-dur">{item.duration}</span>}
                </div>
              </a>
            );
          })}
        </div>

        {filtered.length === 0 && (
          <div style={{padding:'80px 0', textAlign:'center'}}>
            <p style={{fontFamily:'var(--serif)', fontSize:24, fontStyle:'italic', color:'var(--ink-mute)', margin:0}}>
              {window.t('empty.media')}
            </p>
            <button className="clearbtn" style={{maxWidth:240, margin:'24px auto 0'}} onClick={clearAll}>
              {window.t('filters.clear-short')}
            </button>
          </div>
        )}

        {filtered.length > PAGE_SIZE && (
          <div className="pagination">
            <button className="clearbtn" style={{width:'auto', padding:'10px 18px'}}
              disabled={safePage===1}
              onClick={()=>setPage(p=>Math.max(1, p-1))}>{window.t('page.prev')}</button>
            <div className="page-numbers">
              {Array.from({length: totalPages}, (_,i) => i+1).map(n => (
                <button key={n} className={n===safePage ? 'active' : ''} onClick={()=>setPage(n)}>{n}</button>
              ))}
            </div>
            <button className="clearbtn" style={{width:'auto', padding:'10px 18px'}}
              disabled={safePage===totalPages}
              onClick={()=>setPage(p=>Math.min(totalPages, p+1))}>{window.t('page.next')}</button>
          </div>
        )}
      </main>
    </React.Fragment>
  );
}

ReactDOM.createRoot(document.getElementById('media-app')).render(<MediaApp />);
