const { useState, useEffect, useRef } = React;

/* ---------------- HOME ---------------- */
const TYPE_FILTERS = [
  {id:'anime', label:'أنمي'}, {id:'tv', label:'مسلسلات'}, {id:'movie', label:'أفلام'}
];
function HomeScreen({ctx}){
  const [filter,setFilter] = useState('anime');
  const pool = MAT.all.filter(a=>a.type===filter);
  const continueList = ctx.continueList();
  const latest = [...pool].sort((a,b)=>b.year-a.year).slice(0,10);
  return (
    <div className="mtv-screen">
      <Header onSearch={()=>ctx.go('search')} />
      <div className="type-seg">
        <i className="ind" style={{transform:`translateX(${TYPE_FILTERS.findIndex(f=>f.id===filter)*-100}%)`}}></i>
        {TYPE_FILTERS.map(f=> <div key={f.id} className={'seg-btn'+(filter===f.id?' active':'')} onClick={()=>setFilter(f.id)}>{f.label}</div>)}
      </div>
      {continueList.length>0 &&
        <div className="rail">
          <div className="rail-head"><span className="rail-title">متابعة المشاهدة</span></div>
          <div className="rail-track">
            {continueList.map((it,i)=>(
              <div className="card-cap" key={i} style={{width:150}} onClick={()=>ctx.resume(it)}>
                <MPoster item={it.anime} wide><div className="prog"><i style={{width:(it.progress*100)+'%'}}></i></div></MPoster>
                <div className="t">{it.anime.title}</div>
                <div className="m">{it.anime.type==='movie'?'استكمال':`م${it.season} ح${it.ep}`}</div>
              </div>
            ))}
          </div>
        </div>
      }
      {filter!=='movie' && <Rail title="أحدث الحلقات" items={latest} onOpen={(a)=>ctx.go('details',{item:a})} />}
      <div className="rail">
        <div className="rail-head"><span className="rail-title">{TYPE_FILTERS.find(f=>f.id===filter).label}</span></div>
        <div className="grid3">
          {[...pool].sort((a,b)=>b.year-a.year).map(a=>(
            <div key={a.id} onClick={()=>ctx.go('details',{item:a})}>
              <MPoster item={a}><span className="type-tag">{TYPE_LABEL[a.type]}</span></MPoster>
              <div className="t">{a.title}</div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

/* ---------------- CATEGORIES ---------------- */
function CategoriesScreen({ctx}){
  return (
    <div className="mtv-screen">
      <Header title="التصنيفات" />
      <div className="section-pad" style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:12,marginTop:8}}>
        {MAT.cats.map(c=>(
          <div key={c.name} onClick={()=>ctx.go('genre',{cat:c})}
            style={{borderRadius:16,padding:'22px 16px',background:`linear-gradient(135deg, ${c.hue}33, var(--surface2))`,border:'1px solid var(--border)',fontWeight:700,fontSize:15}}>
            {c.name}
          </div>
        ))}
      </div>
    </div>
  );
}
function GenreScreen({ctx, params}){
  const c = params.cat;
  const items = MAT.all.filter(a=>a.genres.includes(c.g));
  return (
    <div className="mtv-screen">
      <Header title={c.name} onBack={ctx.goBack} />
      <div className="grid3">
        {items.map(a=>(
          <div key={a.id} onClick={()=>ctx.go('details',{item:a})}>
            <MPoster item={a}><span className="type-tag">{TYPE_LABEL[a.type]}</span></MPoster>
            <div className="t">{a.title}</div>
          </div>
        ))}
      </div>
      {!items.length && <div className="empty"><div className="big">🔍</div>لا توجد نتائج</div>}
    </div>
  );
}

/* ---------------- LIBRARY (favorites + history) ---------------- */
function LibraryScreen({ctx}){
  const [tab,setTab] = useState('fav');
  const favItems = ctx.favorites.map(id=>ctx.byId(id)).filter(Boolean);
  const histItems = ctx.history;
  return (
    <div className="mtv-screen">
      <Header title="مكتبتي" />
      <div className="segment">
        <button className={tab==='fav'?'active':''} onClick={()=>setTab('fav')}>المفضلة</button>
        <button className={tab==='hist'?'active':''} onClick={()=>setTab('hist')}>السجل</button>
      </div>
      {tab==='fav' && (favItems.length ? favItems.map(a=>(
        <div className="list-row" key={a.id} onClick={()=>ctx.go('details',{item:a})}>
          <MPoster item={a}/>
          <div className="info"><div className="t">{a.title}</div><div className="m">{a.year} · {TYPE_LABEL[a.type]}</div></div>
          <div className="fav-x" onClick={(e)=>{e.stopPropagation();ctx.toggleFav(a.id);}}><MIcon name="x"/></div>
        </div>
      )) : <div className="empty"><div className="big">♡</div>لا توجد عناصر في المفضلة</div>)}
      {tab==='hist' && (histItems.length ? histItems.map((h,i)=>{
        const a = ctx.byId(h.animeId); if(!a) return null;
        return (
          <div className="list-row" key={i} onClick={()=>ctx.resume({anime:a,season:h.season,ep:h.ep,quality:h.quality})}>
            <MPoster item={a}><div className="prog"><i style={{width:(h.progress*100)+'%'}}></i></div></MPoster>
            <div className="info"><div className="t">{a.title}</div><div className="m">{a.type==='movie'?'فيلم':`م${h.season} ح${h.ep}`}</div></div>
          </div>
        );
      }) : <div className="empty"><div className="big">🕐</div>لا يوجد سجل مشاهدة</div>)}
    </div>
  );
}

/* ---------------- SEARCH ---------------- */
function SearchScreen({ctx}){
  const [q,setQ] = useState('');
  const results = q.trim() ? MAT.all.filter(a=>a.title.toLowerCase().includes(q.toLowerCase())) : [];
  return (
    <div className="mtv-screen">
      <Header onBack={ctx.goBack} />
      <div className="search-box">
        <MIcon name="search"/>
        <input autoFocus placeholder="ابحث عن أنمي، مسلسل أو فيلم..." value={q} onChange={e=>setQ(e.target.value)} />
        {q && <div onClick={()=>setQ('')}><MIcon name="x" style={{width:16,height:16}}/></div>}
      </div>
      {!q && <div className="empty"><div className="big">🔎</div>ابحث في كل المحتوى</div>}
      {q && !results.length && <div className="empty"><div className="big">✕</div>لا توجد نتائج لـ «{q}»</div>}
      {results.length>0 &&
        <div className="grid3">
          {results.map(a=>(
            <div key={a.id} onClick={()=>ctx.go('details',{item:a})}>
              <MPoster item={a}><span className="type-tag">{TYPE_LABEL[a.type]}</span></MPoster>
              <div className="t">{a.title}</div>
            </div>
          ))}
        </div>
      }
    </div>
  );
}

/* ---------------- DETAILS ---------------- */
function DetailsScreen({ctx, params}){
  const a = params.item;
  const [openSeason,setOpenSeason] = useState(0);
  const isFav = ctx.isFav(a.id);
  const inProgress = ctx.history.find(h=>h.animeId===a.id && h.progress>0.01 && h.progress<0.98);
  return (
    <div className="mtv-screen">
      <div className="d-banner">
        <MPoster item={a} wide />
        <div className="fade"></div>
        <div className="floatbar">
          <div className="icon-btn plain" onClick={ctx.goBack}><MIcon name="back"/></div>
        </div>
      </div>
      <div className="d-body">
        <div className="d-title">{a.title}</div>
        <div className="d-meta">
          <span className="star"><StarIcon style={{width:14,height:14}}/>{a.rating}</span>
          <span>{a.year}</span><span>·</span>
          <span>{a.type==='movie'?`${a.runtime} دقيقة`:`${a.seasons} مواسم`}</span>
          <span>·</span><span>{a.quality}</span>
        </div>
        <div className="d-genres">{a.genres.map(g=> <span className="d-genre" key={g}>{g}</span>)}</div>
        <div className="d-actions">
          <button className="btn primary" onClick={()=>ctx.playFirst(a)}><MIcon name="play" style={{width:18,height:18}}/>{inProgress? `استكمال المشاهدة${a.type==='movie'?'':` · ح${inProgress.ep}`}` : 'تشغيل'}</button>
          <button className={'btn ghost'+(isFav?' active':'')} onClick={()=>ctx.toggleFav(a.id)}><MIcon name={isFav?'heartFill':'heart'}/></button>
        </div>
        <div className="d-desc">{a.desc}</div>
        {!(a.type==='movie') &&
          <div className="d-seasons">
            {a.seasonsList.map((s,i)=>{
              const isOpen = openSeason===i;
              return (
                <div className="season-block" key={s.s}>
                  <div className="season-head" onClick={()=>setOpenSeason(isOpen?-1:i)}>
                    <span className="s-title">الموسم {s.s}</span>
                    <span className="s-count">{s.episodes.length} حلقة</span>
                    <MIcon name="chevDown" className={'s-chev'+(isOpen?' open':'')} />
                  </div>
                  {isOpen &&
                    <div className="season-eps">
                      {s.episodes.map(ep=>(
                        <div className="ep-row" key={ep.n} onClick={()=>ctx.go('player',{item:a, season:s.s, episode:ep.n, quality:a.quality})}>
                          <div className={'ep-num'+(ep.watched?' done':'')}>{ep.watched? <MIcon name="check" style={{width:14,height:14}}/> : ep.n}</div>
                          <div className="ep-info">
                            <div className="t">{ep.title}</div>
                            <div className="d">{ep.dur} دقيقة</div>
                            {ep.progress>0 && <div className="ep-prog"><i style={{width:(ep.progress*100)+'%'}}></i></div>}
                          </div>
                          <div className="ep-play"><MIcon name="play"/></div>
                        </div>
                      ))}
                    </div>
                  }
                </div>
              );
            })}
          </div>
        }
      </div>
    </div>
  );
}

/* ---------------- PLAYER ---------------- */
function PlayerScreen({ctx, params}){
  const a = params.item;
  const seasonNum = params.season, epNum = params.episode;
  const [quality,setQuality] = useState(params.quality || a.quality);
  const [progress,setProgress] = useState(()=> ctx.savedPos(a.id, seasonNum, epNum));
  const [playing,setPlaying] = useState(true);
  const [showQ,setShowQ] = useState(false);
  const [fullscreen,setFullscreen] = useState(false);
  const season = a.seasonsList.find(s=>s.s===seasonNum) || a.seasonsList[0];
  const ep = season.episodes.find(e=>e.n===epNum) || season.episodes[0];
  const durSec = (ep.dur||20)*60;

  useEffect(()=>{
    if(!playing) return;
    const id = setInterval(()=>{
      setProgress(p=>{
        const np = Math.min(1, p + (3/durSec));
        ctx.recordPlay(a, seasonNum, epNum, quality, np);
        if(np>=1){ clearInterval(id); }
        return np;
      });
    },1000);
    return ()=>clearInterval(id);
  },[playing, seasonNum, epNum, quality]);

  const curSec = Math.floor(progress*durSec);
  const fmt = s=>`${Math.floor(s/60)}:${String(Math.floor(s%60)).padStart(2,'0')}`;
  const nextEp = season.episodes.find(e=>e.n===epNum+1);
  const prevEp = season.episodes.find(e=>e.n===epNum-1);

  return (
    <div className={'p-root'+(fullscreen?' fs-active':'')}>
      <div className={'p-stage'+(fullscreen?' fs':'')}>
        <MPoster item={a} wide />
        <div className="p-overlay">
          <div className="p-top">
            <div className="back-btn" style={{color:'#fff'}} onClick={ctx.goBack}><MIcon name="back" style={{stroke:'#fff'}}/></div>
            <div className="info">
              <div className="t1">{a.title}</div>
              <div className="t2">{a.type==='movie'? a.title : `الموسم ${seasonNum} · الحلقة ${epNum}`}</div>
            </div>
            <div className="icon-btn plain" style={{color:'#fff'}} onClick={()=>setFullscreen(f=>!f)}><MIcon name="expand" style={{stroke:'#fff'}}/></div>
            <div className="icon-btn plain" style={{color:'#fff'}} onClick={()=>setShowQ(true)}><MIcon name="gear" style={{stroke:'#fff'}}/></div>
          </div>
          <div className="p-mid">
            {!(a.type==='movie') && <button className="sm" disabled={!prevEp} style={{opacity:prevEp?1:.3}} onClick={()=>prevEp && ctx.go('player',{item:a, season:seasonNum, episode:prevEp.n, quality})}><MIcon name="track" style={{transform:'scaleX(-1)'}}/></button>}
            <button className="sm" onClick={()=>setProgress(p=>Math.max(0,p-10/durSec))}><MIcon name="skipFwd" style={{transform:'scaleX(-1)'}}/></button>
            <button className="big" onClick={()=>setPlaying(p=>!p)}><MIcon name={playing?'pause':'play'}/></button>
            <button className="sm" onClick={()=>setProgress(p=>Math.min(1,p+10/durSec))}><MIcon name="skipFwd"/></button>
            {!(a.type==='movie') && <button className="sm" disabled={!nextEp} style={{opacity:nextEp?1:.3}} onClick={()=>nextEp && ctx.go('player',{item:a, season:seasonNum, episode:nextEp.n, quality})}><MIcon name="track"/></button>}
          </div>
          <div className="p-bottom">
            <div className="p-scrub">
              <span className="time">{fmt(curSec)}</span>
              <div className="p-bar"><i style={{width:(progress*100)+'%'}}></i></div>
              <span className="time">{fmt(durSec)}</span>
            </div>
          </div>
        </div>
      </div>

      {!fullscreen &&
        <div className="p-list section-pad">
          {a.type==='movie' ? <div className="d-desc">{a.desc}</div> :
            <React.Fragment>
              <div className="rail-title" style={{marginBottom:10}}>الموسم {seasonNum}</div>
              {season.episodes.map(e=>(
                <div className={'ep-row'+(e.n===epNum?' current':'')} key={e.n} onClick={()=>ctx.go('player',{item:a, season:seasonNum, episode:e.n, quality})}>
                  <div className={'ep-num'+(e.n===epNum?' done':'')}>{e.n}</div>
                  <div className="ep-info">
                    <div className="t">{e.title}</div>
                    <div className="d">{e.dur} دقيقة</div>
                    {e.n===epNum && <div className="ep-prog"><i style={{width:(progress*100)+'%'}}></i></div>}
                  </div>
                  <div className="ep-play"><MIcon name={e.n===epNum?(playing?'pause':'play'):'play'}/></div>
                </div>
              ))}
            </React.Fragment>
          }
        </div>
      }
      {showQ &&
        <Sheet title="جودة العرض" onClose={()=>setShowQ(false)}>
          {MAT.qualities.map(q=>(
            <div className="sheet-item" key={q} onClick={()=>{setQuality(q);setShowQ(false);}}>
              <span className={q===quality?'active':''}>{q}</span>{q===quality && <MIcon name="check"/>}
            </div>
          ))}
        </Sheet>
      }

    </div>
  );
}

/* ---------------- SETTINGS ---------------- */
function SettingsScreen({ctx}){
  const s = ctx.settings;
  return (
    <div className="mtv-screen">
      <Header title="الإعدادات" />
      <div className="setting-section">
        <div className="setting-label">التشغيل</div>
        <div className="setting-row">
          <div className="t">تشغيل تلقائي للحلقة التالية<div className="sub">ينتقل تلقائيًا عند الانتهاء</div></div>
          <div className={'switch'+(s.autoPlay?' on':'')} onClick={()=>ctx.setSetting('autoPlay',!s.autoPlay)}><i></i></div>
        </div>
        <div className="setting-row">
          <div className="t">استكمال المشاهدة<div className="sub">يبدأ من آخر نقطة توقف</div></div>
          <div className={'switch'+(s.resume?' on':'')} onClick={()=>ctx.setSetting('resume',!s.resume)}><i></i></div>
        </div>
        <div className="setting-row" style={{flexDirection:'column',alignItems:'flex-start',gap:10}}>
          <div className="t">الجودة الافتراضية</div>
          <div className="qsel">
            {['تلقائي','1080p','720p','480p'].map(q=>(
              <span key={q} className={s.defaultQuality===q?'on':''} onClick={()=>ctx.setSetting('defaultQuality',q)}>{q}</span>
            ))}
          </div>
        </div>
      </div>
      <div className="setting-section">
        <div className="setting-label">البيانات</div>
        <div className="setting-row" onClick={()=>{ctx.clearHistory(); ctx.toast('تم مسح السجل');}}>
          <div className="t danger-row">مسح سجل المشاهدة</div>
        </div>
        <div className="setting-row" onClick={()=>{ctx.clearFavorites(); ctx.toast('تم مسح المفضلة');}}>
          <div className="t danger-row">مسح قائمة المفضلة</div>
        </div>
      </div>
      <div className="setting-section">
        <div className="setting-label">حول التطبيق</div>
        <div className="setting-row"><div className="t">الإصدار<div className="sub">MY TV Mobile 1.0</div></div></div>
      </div>
    </div>
  );
}

Object.assign(window, { HomeScreen, CategoriesScreen, GenreScreen, LibraryScreen, SearchScreen, DetailsScreen, PlayerScreen, SettingsScreen });
