// Reel — main screens: Library, Folders, Search, Playlists, Settings, History, PrivateLock
const T = REEL_TOKENS;

const iconBtn = { width:38,height:38,borderRadius:19,border:'none',background:'transparent',color:T.text,display:'inline-flex',alignItems:'center',justifyContent:'center',cursor:'pointer',padding:0 };
const sectionHead = { display:'flex',alignItems:'center',justifyContent:'space-between',padding:'0 16px 0',marginBottom:2,fontSize:13,fontWeight:700,color:T.text };
const linkBtn = { border:'none',background:'transparent',color:T.textDim,fontSize:12,fontWeight:600,fontFamily:'inherit',cursor:'pointer',display:'flex',alignItems:'center',gap:4,padding:'4px 2px' };
const gridCard = { border:'none',background:'transparent',cursor:'pointer',padding:0,borderRadius:12,textAlign:'left',width:'100%',fontFamily:'inherit' };
const listRow  = { display:'flex',alignItems:'center',gap:12,padding:'8px 10px',border:'none',background:'transparent',cursor:'pointer',width:'100%',fontFamily:'inherit',color:T.text,borderRadius:10,textAlign:'left' };
const folderRow = { display:'flex',alignItems:'center',gap:14,padding:'12px 14px',border:'1px solid '+T.border,borderRadius:14,background:T.surface,width:'100%',fontFamily:'inherit',color:T.text,cursor:'pointer',textAlign:'left' };
const pillRow  = { flex:1,display:'flex',alignItems:'center',gap:10,padding:'12px 14px',border:'1px solid '+T.border,borderRadius:14,background:T.surface,fontFamily:'inherit',color:T.text,cursor:'pointer',textAlign:'left' };
const sectionHeadInline = { fontSize:11,fontWeight:700,color:T.textMuted,textTransform:'uppercase',letterSpacing:1.2,padding:'0 0 8px' };
const recentRow = { display:'flex',alignItems:'center',gap:12,padding:'10px 4px',border:'none',background:'transparent',color:T.text,fontFamily:'inherit',cursor:'pointer',width:'100%',fontSize:14 };
const resumeCard = { border:'none',background:'transparent',cursor:'pointer',padding:0,textAlign:'left',fontFamily:'inherit',flexShrink:0 };
const fileRow = { display:'flex',alignItems:'center',gap:12,padding:'10px 12px',border:'1px solid '+T.border,borderRadius:12,background:'transparent',color:T.text,fontFamily:'inherit',cursor:'pointer',width:'100%' };

// ── Top app bar ────────────────────────────────────────────────────────
function TopBar({ title, sub, onBack, actions=[], large=false }) {
  return (
    <div style={{ position:'sticky',top:0,zIndex:5,background:T.bg,padding:large?'14px 18px 8px':'14px 14px',borderBottom:'1px solid '+T.border,display:'flex',flexDirection:large?'column':'row',alignItems:large?'stretch':'center',gap:4 }}>
      <div style={{ display:'flex',alignItems:'center',gap:8,minHeight:32 }}>
        {onBack && <button onClick={onBack} style={{ ...iconBtn,marginLeft:-8 }}><Icon name="back" size={22}/></button>}
        {!large && <div style={{ flex:1,minWidth:0 }}>
          <div style={{ fontSize:17,fontWeight:700,letterSpacing:-0.2,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap' }}>{title}</div>
          {sub && <div style={{ fontSize:12,color:T.textDim,marginTop:1 }}>{sub}</div>}
        </div>}
        {large && <div style={{ flex:1 }}/>}
        <div style={{ display:'flex',gap:2 }}>
          {actions.map((a,i) => <button key={i} onClick={a.onClick} style={iconBtn} aria-label={a.name}><Icon name={a.name} size={20}/></button>)}
        </div>
      </div>
      {large && <div style={{ paddingTop:6 }}>
        <div style={{ fontSize:30,fontWeight:800,letterSpacing:-0.8 }}>{title}</div>
        {sub && <div style={{ fontSize:13,color:T.textDim,marginTop:2 }}>{sub}</div>}
      </div>}
    </div>
  );
}

// ── Tab bar ───────────────────────────────────────────────────────────
function TabBar({ tab, setTab, accent }) {
  const items = [
    { id:'home',      label:'Library',   icon:'home' },
    { id:'folders',   label:'Folders',   icon:'folder' },
    { id:'playlists', label:'Playlists', icon:'heart' },
    { id:'settings',  label:'Settings',  icon:'gear' },
  ];
  return (
    <div style={{ position:'sticky',bottom:0,background:T.bg,borderTop:'1px solid '+T.border,display:'flex',padding:'6px 6px 4px',paddingBottom:'calc(6px + env(safe-area-inset-bottom,0px))' }}>
      {items.map(it => {
        const active = tab === it.id;
        return (
          <button key={it.id} onClick={() => setTab(it.id)} style={{ flex:1,border:'none',background:'transparent',padding:'8px 4px',display:'flex',flexDirection:'column',alignItems:'center',gap:2,color:active?accent:T.textMuted,cursor:'pointer',fontFamily:'inherit' }}>
            <div style={{ padding:'4px 16px',borderRadius:14,background:active?accentSoftColor(accent):'transparent',transition:'background .15s' }}>
              <Icon name={it.icon} size={22}/>
            </div>
            <div style={{ fontSize:10.5,fontWeight:active?700:500,letterSpacing:0.1 }}>{it.label}</div>
          </button>
        );
      })}
    </div>
  );
}

// ── Now-playing mini bar ───────────────────────────────────────────────
function NowPlayingBar({ video, playing, onPlay, onExpand, accent }) {
  if (!video) return null;
  const progress = video.progress || 0;
  return (
    <div onClick={onExpand} style={{ margin:'0 8px 6px',borderRadius:14,background:T.surface2,border:'1px solid '+T.border,display:'flex',alignItems:'center',gap:10,padding:'6px 8px 6px 6px',cursor:'pointer',position:'relative',overflow:'hidden' }}>
      <div style={{ width:42,height:42,flexShrink:0 }}>
        <Thumbnail hue={video.hue} label="" aspect="1/1" radius={8}/>
      </div>
      <div style={{ flex:1,minWidth:0 }}>
        <div style={{ fontSize:13,fontWeight:600,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap' }}>{video.title}</div>
        <div style={{ fontSize:11,color:T.textDim,fontFamily:T.mono,marginTop:1 }}>{fmt(video.duration*(progress||0.3))} / {video.duration>0?fmt(video.duration):'--:--'}</div>
      </div>
      <button onClick={e=>{e.stopPropagation();onPlay();}} style={{ ...iconBtn,width:34,height:34,color:accent }}>
        <Icon name={playing?'pause':'play'} size={18} color={accent}/>
      </button>
      <div style={{ position:'absolute',left:0,right:0,bottom:0,height:2,background:'rgba(255,255,255,0.06)' }}>
        <div style={{ width:`${(progress||0.3)*100}%`,height:'100%',background:accent }}/>
      </div>
    </div>
  );
}

// ── Library / Home ────────────────────────────────────────────────────
function LibraryScreen({ videos, open, onSearch, layout, accent, onRescan, scanning }) {
  const [filter, setFilter] = React.useState('all');
  const recent = videos.filter(v => v.progress > 0 && v.progress < 1).sort((a,b) => b.lastPlayed - a.lastPlayed).slice(0, 6);
  const totalSize = videos.reduce((s,v) => s+(v.sizeBytes||0), 0);

  let shown = [...videos];
  if (filter === '4k')        shown = shown.filter(v => v.res.includes('4K'));
  else if (filter === 'fav')  shown = shown.filter(v => v.fav);
  else if (filter === 'unwatched') shown = shown.filter(v => !v.progress || v.progress === 0);
  else if (filter === 'today') {
    const today = new Date(); today.setHours(0,0,0,0);
    shown = shown.filter(v => v.modified >= today.getTime());
  }
  shown = shown.sort((a,b) => b.modified - a.modified);

  return (
    <div>
      <TopBar title="Reel" sub={videos.length > 0 ? `${videos.length} videos · ${REEL_SCANNER.fmtSize(totalSize)}` : 'No videos yet'}
        large actions={[{ name:'search', onClick:onSearch }, { name:'rotate', onClick:onRescan }]}/>
      <div style={{ display:'flex',gap:6,padding:'12px 16px 4px',overflowX:'auto',scrollbarWidth:'none' }}>
        {[['all','All'],['fav','Favorites'],['4k','4K'],['unwatched','Unwatched'],['today','Today']].map(([v,l]) => (
          <Chip key={v} active={filter===v} onClick={() => setFilter(v)}
            style={filter===v?{borderColor:accent,color:accent,background:accentSoftColor(accent)}:{}}>{l}</Chip>
        ))}
      </div>

      {scanning && (
        <div style={{ margin:'12px 16px',padding:'12px 16px',borderRadius:14,background:T.surface,border:'1px solid '+T.border,display:'flex',alignItems:'center',gap:12 }}>
          <style>{`@keyframes spin{to{transform:rotate(360deg)}}`}</style>
          <div style={{ width:20,height:20,border:'2px solid '+T.border,borderTopColor:accent,borderRadius:'50%',animation:'spin 0.8s linear infinite' }}/>
          <div style={{ fontSize:13,color:T.textDim }}>Scanning for new videos…</div>
        </div>
      )}

      {recent.length > 0 && (
        <section style={{ marginTop:14 }}>
          <div style={sectionHead}><span>Continue watching</span><button style={linkBtn}>See all</button></div>
          <div style={{ display:'flex',gap:12,padding:'10px 16px 6px',overflowX:'auto',scrollbarWidth:'none' }}>
            {recent.map(v => (
              <button key={v.id} onClick={() => open(v)} style={resumeCard}>
                <div style={{ width:200,position:'relative' }}>
                  <Thumbnail hue={v.hue} label={v.codec||''} radius={12}/>
                  <PlayBadge accent={accent}/>
                  <DurationBadge>{v.duration>0?fmt(v.duration):'?'}</DurationBadge>
                  <ResumeBar progress={v.progress} accent={accent}/>
                </div>
                <div style={{ padding:'8px 4px 0',textAlign:'left' }}>
                  <div style={{ fontSize:13,fontWeight:600,color:T.text,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap',maxWidth:200 }}>{v.title}</div>
                  <div style={{ fontSize:11,color:T.textDim,marginTop:2,fontFamily:T.mono }}>{Math.round((v.progress||0)*100)}% · {v.duration>0?fmt(v.duration*(1-(v.progress||0))):'?'} left</div>
                </div>
              </button>
            ))}
          </div>
        </section>
      )}

      <section style={{ marginTop:18,paddingBottom:90 }}>
        <div style={sectionHead}>
          <span>{filter==='all'?'All videos':filter==='fav'?'Favorites':filter==='4k'?'4K videos':filter==='unwatched'?'Unwatched':'Today'}</span>
          <div style={{ display:'flex',gap:4 }}>
            <button style={linkBtn}><Icon name="sort" size={14} style={{ verticalAlign:-2,marginRight:4 }}/>Newest</button>
          </div>
        </div>
        {videos.length === 0 ? (
          <EmptyState onScan={onRescan}/>
        ) : shown.length === 0 ? (
          <div style={{ padding:'60px 20px',textAlign:'center',color:T.textDim }}>
            <div style={{ fontSize:14 }}>No videos match this filter</div>
          </div>
        ) : layout === 'grid' ? (
          <div style={{ display:'grid',gridTemplateColumns:'1fr 1fr',gap:10,padding:'10px 16px 16px' }}>
            {shown.map(v => (
              <button key={v.id} onClick={() => open(v)} style={gridCard}>
                <div style={{ position:'relative' }}>
                  <Thumbnail hue={v.hue} label={v.codec||''} radius={10}/>
                  <DurationBadge>{v.duration>0?fmt(v.duration):'?'}</DurationBadge>
                  {v.progress>0&&v.progress<1&&<ResumeBar progress={v.progress} accent={accent}/>}
                  {v.fav&&<FavBadge accent={accent}/>}
                </div>
                <div style={{ padding:'8px 2px 4px',textAlign:'left' }}>
                  <div style={{ fontSize:13,fontWeight:600,lineHeight:1.25,color:T.text,display:'-webkit-box',WebkitLineClamp:2,WebkitBoxOrient:'vertical',overflow:'hidden' }}>{v.title}</div>
                  <div style={{ fontSize:11,color:T.textDim,marginTop:4,fontFamily:T.mono,display:'flex',gap:6 }}>
                    <span>{v.res||v.size.split(' ')[0]}</span><span style={{ color:T.textMuted }}>·</span><span>{v.size}</span>
                  </div>
                </div>
              </button>
            ))}
          </div>
        ) : (
          <div style={{ display:'flex',flexDirection:'column',gap:4,padding:'8px 8px 16px' }}>
            {shown.map(v => (
              <button key={v.id} onClick={() => open(v)} style={listRow}>
                <div style={{ width:92,flexShrink:0,position:'relative' }}>
                  <Thumbnail hue={v.hue} label={v.codec||''} radius={8}/>
                  <DurationBadge small>{v.duration>0?fmt(v.duration):'?'}</DurationBadge>
                  {v.progress>0&&v.progress<1&&<ResumeBar progress={v.progress} accent={accent}/>}
                </div>
                <div style={{ flex:1,minWidth:0,textAlign:'left' }}>
                  <div style={{ fontSize:14,fontWeight:600,lineHeight:1.2,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap' }}>{v.title}</div>
                  <div style={{ fontSize:11.5,color:T.textDim,marginTop:3,fontFamily:T.mono,display:'flex',gap:6,alignItems:'center' }}>
                    <span>{v.res||''}</span>{v.res&&<span style={{ color:T.textMuted }}>·</span>}<span>{v.size}</span>
                  </div>
                  <div style={{ fontSize:11,color:T.textMuted,marginTop:2 }}>{v.folder} · {v.modifiedStr||''}</div>
                </div>
                <button style={{ ...iconBtn,color:T.textDim }} onClick={e=>e.stopPropagation()}><Icon name="more" size={18}/></button>
              </button>
            ))}
          </div>
        )}
      </section>
    </div>
  );
}

function EmptyState({ onScan }) {
  return (
    <div style={{ padding:'60px 32px',textAlign:'center',display:'flex',flexDirection:'column',alignItems:'center',gap:20 }}>
      <div style={{ width:72,height:72,borderRadius:22,background:T.surface,border:'1px solid '+T.border,display:'flex',alignItems:'center',justifyContent:'center' }}>
        <Icon name="film" size={36} color={T.textMuted}/>
      </div>
      <div>
        <div style={{ fontSize:17,fontWeight:700,color:T.text }}>No videos yet</div>
        <div style={{ fontSize:13,color:T.textDim,marginTop:6,lineHeight:1.5 }}>Tap the scan button to find videos on your device.</div>
      </div>
      <button onClick={onScan} style={{ padding:'13px 28px',borderRadius:14,border:'none',background:T.accent,color:'#000',fontSize:14,fontWeight:700,fontFamily:'inherit',cursor:'pointer',display:'flex',alignItems:'center',gap:8 }}>
        <Icon name="scan" size={18} color="#000"/>Scan for videos
      </button>
    </div>
  );
}

// ── Folders ────────────────────────────────────────────────────────────
function FoldersScreen({ videos, openFolder, accent, onRescan }) {
  const folderMap = {};
  videos.forEach(v => {
    if (!folderMap[v.folder]) folderMap[v.folder] = { name:v.folder, videos:[], hue:v.hue };
    folderMap[v.folder].videos.push(v);
  });
  const folders = Object.values(folderMap).sort((a,b) => b.videos.length - a.videos.length);
  const totalSize = videos.reduce((s,v) => s+(v.sizeBytes||0), 0);

  return (
    <div>
      <TopBar title="Folders" sub={folders.length>0?`${folders.length} folders scanned`:'Not scanned yet'} large
        actions={[{ name:'rotate', onClick:onRescan },{ name:'more', onClick:()=>{} }]}/>
      {folders.length === 0 ? (
        <EmptyState onScan={onRescan}/>
      ) : (
        <div style={{ padding:'12px 14px 90px',display:'flex',flexDirection:'column',gap:8 }}>
          {folders.map(f => {
            const size = f.videos.reduce((s,v)=>s+(v.sizeBytes||0),0);
            return (
              <button key={f.name} onClick={() => openFolder(f)} style={folderRow}>
                <div style={{ display:'grid',gridTemplateColumns:'1fr 1fr',gridTemplateRows:'1fr 1fr',gap:2,width:64,height:64,flexShrink:0,borderRadius:10,overflow:'hidden' }}>
                  {[0,1,2,3].map(j => <Thumbnail key={j} hue={(f.hue+j*50)%360} label="" aspect="1/1" radius={0}/>)}
                </div>
                <div style={{ flex:1,minWidth:0,textAlign:'left' }}>
                  <div style={{ fontSize:14.5,fontWeight:600,fontFamily:T.mono,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap' }}>{f.name}</div>
                  <div style={{ fontSize:12,color:T.textDim,marginTop:3 }}>{f.videos.length} video{f.videos.length!==1?'s':''} · {REEL_SCANNER.fmtSize(size)}</div>
                </div>
                <Icon name="chev-right" size={18} color={T.textMuted}/>
              </button>
            );
          })}
        </div>
      )}
    </div>
  );
}

function FolderDetail({ folder, open, onBack, accent }) {
  const items = folder.videos || [];
  const size = items.reduce((s,v)=>s+(v.sizeBytes||0),0);
  return (
    <div>
      <TopBar title={folder.name} sub={`${items.length} videos · ${REEL_SCANNER.fmtSize(size)}`} onBack={onBack}
        actions={[{ name:'sort', onClick:()=>{} },{ name:'more', onClick:()=>{} }]}/>
      <div style={{ display:'flex',flexDirection:'column',gap:4,padding:'10px 8px 100px' }}>
        {items.map(v => (
          <button key={v.id} onClick={() => open(v)} style={listRow}>
            <div style={{ width:112,flexShrink:0,position:'relative' }}>
              <Thumbnail hue={v.hue} label={v.codec||''} radius={8}/>
              <DurationBadge small>{v.duration>0?fmt(v.duration):'?'}</DurationBadge>
              {v.progress>0&&v.progress<1&&<ResumeBar progress={v.progress} accent={accent}/>}
            </div>
            <div style={{ flex:1,minWidth:0,textAlign:'left' }}>
              <div style={{ fontSize:14,fontWeight:600,lineHeight:1.2,display:'-webkit-box',WebkitLineClamp:2,WebkitBoxOrient:'vertical',overflow:'hidden' }}>{v.title}</div>
              <div style={{ fontSize:11.5,color:T.textDim,marginTop:4,fontFamily:T.mono }}>{v.res||''}{v.res&&' · '}{v.size}</div>
              <div style={{ fontSize:11,color:T.textMuted,marginTop:2 }}>{v.modifiedStr||''}</div>
            </div>
          </button>
        ))}
      </div>
    </div>
  );
}

// ── Search ─────────────────────────────────────────────────────────────
function SearchScreen({ videos, onBack, open, accent }) {
  const [q, setQ] = React.useState('');
  const [recents, setRecents] = React.useState(() => {
    try { return JSON.parse(localStorage.getItem('reel-recent-search')||'[]'); } catch { return []; }
  });
  const results = q ? videos.filter(v => v.title.toLowerCase().includes(q.toLowerCase()) || v.folder.toLowerCase().includes(q.toLowerCase())) : [];
  const doSearch = (s) => {
    setQ(s);
    if (s) {
      const r = [s, ...recents.filter(x=>x!==s)].slice(0,8);
      setRecents(r);
      try { localStorage.setItem('reel-recent-search', JSON.stringify(r)); } catch {}
    }
  };
  return (
    <div>
      <div style={{ position:'sticky',top:0,zIndex:5,background:T.bg,borderBottom:'1px solid '+T.border,padding:'10px 10px',display:'flex',alignItems:'center',gap:8 }}>
        <button onClick={onBack} style={iconBtn}><Icon name="back" size={22}/></button>
        <div style={{ flex:1,display:'flex',alignItems:'center',gap:8,background:T.surface2,borderRadius:20,padding:'8px 14px',border:'1px solid '+T.border }}>
          <Icon name="search" size={18} color={T.textDim}/>
          <input value={q} onChange={e=>doSearch(e.target.value)} placeholder="Search videos, folders…"
            autoFocus
            style={{ flex:1,background:'transparent',border:'none',outline:'none',color:T.text,fontSize:14,fontFamily:'inherit' }}/>
          {q && <button onClick={()=>setQ('')} style={{ ...iconBtn,width:24,height:24,color:T.textDim }}><Icon name="close" size={16}/></button>}
        </div>
      </div>
      {!q && (
        <div style={{ padding:16 }}>
          <div style={{ fontSize:12,color:T.textMuted,textTransform:'uppercase',letterSpacing:1,marginBottom:10 }}>Recent searches</div>
          {recents.map(r => (
            <button key={r} style={recentRow} onClick={()=>setQ(r)}>
              <Icon name="search" size={16} color={T.textDim}/>
              <span style={{ flex:1,textAlign:'left' }}>{r}</span>
              <Icon name="close" size={14} color={T.textMuted}/>
            </button>
          ))}
          {recents.length === 0 && <div style={{ color:T.textMuted,fontSize:13,padding:'20px 0',textAlign:'center' }}>No recent searches</div>}
        </div>
      )}
      {q && (
        <>
          <div style={{ display:'flex',gap:6,padding:'12px 16px 4px',overflowX:'auto',scrollbarWidth:'none' }}>
            <Chip active style={{ borderColor:accent,color:accent,background:accentSoftColor(accent) }}>Videos · {results.length}</Chip>
          </div>
          <div style={{ display:'flex',flexDirection:'column',gap:4,padding:'10px 8px 100px' }}>
            {results.map(v => (
              <button key={v.id} onClick={() => open(v)} style={listRow}>
                <div style={{ width:96,flexShrink:0,position:'relative' }}>
                  <Thumbnail hue={v.hue} label={v.codec||''} radius={8}/>
                  <DurationBadge small>{v.duration>0?fmt(v.duration):'?'}</DurationBadge>
                </div>
                <div style={{ flex:1,minWidth:0,textAlign:'left' }}>
                  <div style={{ fontSize:14,fontWeight:600 }}><HighlightedText text={v.title} q={q} accent={accent}/></div>
                  <div style={{ fontSize:11.5,color:T.textDim,marginTop:3,fontFamily:T.mono }}>{v.folder}</div>
                </div>
              </button>
            ))}
            {results.length === 0 && (
              <div style={{ padding:'60px 20px',textAlign:'center',color:T.textDim }}>
                <div style={{ fontSize:14 }}>No videos match "{q}"</div>
              </div>
            )}
          </div>
        </>
      )}
    </div>
  );
}

function HighlightedText({ text, q, accent }) {
  if (!q) return text;
  const i = text.toLowerCase().indexOf(q.toLowerCase());
  if (i < 0) return text;
  return <>{text.slice(0,i)}<mark style={{ background:'transparent',color:accent,fontWeight:700 }}>{text.slice(i,i+q.length)}</mark>{text.slice(i+q.length)}</>;
}

// ── Playlists ──────────────────────────────────────────────────────────
function PlaylistsScreen({ videos, accent, onPrivate }) {
  const [playlists, setPlaylists] = React.useState([]);
  React.useEffect(() => {
    REEL_DB.getPlaylists().then(setPlaylists);
  }, []);
  const favVideos = videos.filter(v => v.fav);
  return (
    <div>
      <TopBar title="Playlists" sub={`${playlists.length} lists`} large
        actions={[{ name:'plus', onClick:()=>{} },{ name:'more', onClick:()=>{} }]}/>
      <div style={{ padding:'12px 14px',display:'flex',gap:8 }}>
        <button style={pillRow}>
          <Icon name="heart-fill" size={18} color={T.red}/>
          <div style={{ flex:1,textAlign:'left',minWidth:0 }}>
            <div style={{ fontSize:13.5,fontWeight:700 }}>Favorites</div>
            <div style={{ fontSize:11,color:T.textDim }}>{favVideos.length} videos</div>
          </div>
        </button>
        <button style={pillRow} onClick={onPrivate}>
          <Icon name="lock" size={18} color={accent}/>
          <div style={{ flex:1,textAlign:'left',minWidth:0 }}>
            <div style={{ fontSize:13.5,fontWeight:700 }}>Private</div>
            <div style={{ fontSize:11,color:T.textDim }}>Hidden · PIN</div>
          </div>
        </button>
      </div>
      <div style={{ padding:'4px 14px 100px',display:'flex',flexDirection:'column',gap:8 }}>
        <div style={sectionHeadInline}>My playlists</div>
        {playlists.length === 0 && (
          <div style={{ padding:'40px 20px',textAlign:'center',color:T.textMuted }}>
            <Icon name="plus" size={32} color={T.textMuted}/>
            <div style={{ fontSize:13,marginTop:12 }}>No playlists yet</div>
            <div style={{ fontSize:11,marginTop:4 }}>Tap + to create one</div>
          </div>
        )}
        {playlists.map(p => (
          <button key={p.id} style={folderRow}>
            <div style={{ position:'relative',width:72,height:72,flexShrink:0 }}>
              <Thumbnail hue={p.hue||120} label="" aspect="1/1" radius={10}/>
              <div style={{ position:'absolute',inset:0,background:'linear-gradient(135deg,rgba(0,0,0,0) 50%,rgba(0,0,0,0.5) 100%)',borderRadius:10,display:'flex',alignItems:'flex-end',justifyContent:'flex-end',padding:6 }}>
                <span style={{ fontSize:11,fontWeight:700,fontFamily:T.mono,color:'#fff' }}>{(p.videos||[]).length}</span>
              </div>
            </div>
            <div style={{ flex:1,minWidth:0,textAlign:'left' }}>
              <div style={{ fontSize:14.5,fontWeight:600 }}>{p.name}</div>
              <div style={{ fontSize:11.5,color:T.textDim,marginTop:3 }}>{(p.videos||[]).length} videos</div>
            </div>
            <Icon name="chev-right" size={18} color={T.textMuted}/>
          </button>
        ))}
      </div>
    </div>
  );
}

// ── History / Recordings screen ────────────────────────────────────────
function HistoryScreen({ onBack, open, videos, accent }) {
  const [history, setHistory] = React.useState([]);
  const [tab, setTabLocal] = React.useState('history');
  React.useEffect(() => {
    REEL_DB.getHistory().then(setHistory);
  }, []);

  const recordings = videos.filter(v => {
    const f = v.folder.toLowerCase();
    return f.includes('camera') || f.includes('recording') || f.includes('dcim') || f.includes('video') || f.includes('screen');
  }).sort((a,b) => b.modified - a.modified);

  return (
    <div style={{ display:'flex',flexDirection:'column',height:'100%' }}>
      <TopBar title="History" onBack={onBack}/>
      <div style={{ display:'flex',gap:0,padding:'0 16px 0',borderBottom:'1px solid '+T.border }}>
        {[['history','Watch history'],['recordings','Recordings']].map(([id,label]) => (
          <button key={id} onClick={() => setTabLocal(id)} style={{ ...iconBtn,width:'auto',padding:'10px 16px',borderRadius:0,fontSize:13,fontWeight:tab===id?700:500,color:tab===id?accent:T.textDim,borderBottom:tab===id?`2px solid ${accent}`:'2px solid transparent',marginBottom:-1 }}>
            {label}
          </button>
        ))}
      </div>
      <div style={{ flex:1,overflow:'auto',paddingBottom:20 }}>
        {tab === 'history' ? (
          history.length === 0 ? (
            <div style={{ padding:'60px 20px',textAlign:'center',color:T.textDim }}>
              <Icon name="history" size={40} color={T.textMuted}/>
              <div style={{ fontSize:14,marginTop:12 }}>No watch history yet</div>
              <div style={{ fontSize:12,marginTop:4 }}>Videos you play will appear here</div>
            </div>
          ) : (
            <div style={{ display:'flex',flexDirection:'column',gap:4,padding:'10px 8px' }}>
              {history.map((h,i) => {
                const vid = videos.find(v=>v.id===h.videoId);
                return (
                  <button key={i} onClick={() => vid && open(vid)} style={{ ...listRow,opacity:vid?1:0.5 }}>
                    <div style={{ width:80,flexShrink:0,position:'relative' }}>
                      <Thumbnail hue={h.hue||30} label="" radius={8}/>
                    </div>
                    <div style={{ flex:1,minWidth:0,textAlign:'left' }}>
                      <div style={{ fontSize:14,fontWeight:600,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap' }}>{h.title}</div>
                      <div style={{ fontSize:11.5,color:T.textDim,marginTop:3,fontFamily:T.mono }}>{h.folder}</div>
                      <div style={{ fontSize:11,color:T.textMuted,marginTop:2 }}>{REEL_SCANNER.relTime(h.playedAt)}</div>
                    </div>
                    <Icon name="play" size={18} color={T.textMuted}/>
                  </button>
                );
              })}
            </div>
          )
        ) : (
          recordings.length === 0 ? (
            <div style={{ padding:'60px 20px',textAlign:'center',color:T.textDim }}>
              <Icon name="video-rec" size={40} color={T.textMuted}/>
              <div style={{ fontSize:14,marginTop:12 }}>No recordings found</div>
              <div style={{ fontSize:12,marginTop:4 }}>Videos from Camera & Recordings folders appear here</div>
            </div>
          ) : (
            <div style={{ display:'flex',flexDirection:'column',gap:4,padding:'10px 8px' }}>
              {recordings.map(v => (
                <button key={v.id} onClick={() => open(v)} style={listRow}>
                  <div style={{ width:92,flexShrink:0,position:'relative' }}>
                    <Thumbnail hue={v.hue} label="" radius={8}/>
                    <DurationBadge small>{v.duration>0?fmt(v.duration):'?'}</DurationBadge>
                  </div>
                  <div style={{ flex:1,minWidth:0,textAlign:'left' }}>
                    <div style={{ fontSize:14,fontWeight:600,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap' }}>{v.title}</div>
                    <div style={{ fontSize:11.5,color:T.textDim,marginTop:3,fontFamily:T.mono }}>{v.size}</div>
                    <div style={{ fontSize:11,color:T.textMuted,marginTop:2 }}>{v.folder} · {v.modifiedStr}</div>
                  </div>
                </button>
              ))}
            </div>
          )
        )}
      </div>
    </div>
  );
}

// ── Settings ───────────────────────────────────────────────────────────
function SettingsScreen({ accent, tweaks, setTweak, onRescan, onHistory, videoCount }) {
  return (
    <div>
      <TopBar title="Settings" sub="Reel · v1.0.0" large/>
      <div style={{ padding:'14px 14px 100px' }}>
        <SettingsGroup title="Library">
          <SettingRow icon="folder" label="Videos found" value={`${videoCount} videos`}/>
          <SettingRow icon="rotate" label="Rescan folders" onClick={onRescan}/>
          <SettingRow icon="history" label="Watch history & recordings" onClick={onHistory}/>
          <SettingRow icon="grid" label="Default layout" value={tweaks.layout==='grid'?'Grid':'List'}
            onClick={() => setTweak('layout', tweaks.layout==='grid'?'list':'grid')}/>
        </SettingsGroup>
        <SettingsGroup title="Playback">
          <SettingRow icon="play-line" label="Resume from last position" toggle={true}/>
          <SettingRow icon="back10" label="Skip duration" value={`${tweaks.skipSeconds||10}s`}
            onClick={() => { const next={5:10,10:15,15:30,30:5}[tweaks.skipSeconds||10]; setTweak('skipSeconds',next); }}/>
          <SettingRow icon="speed" label="Default speed" value="1.0×"/>
          <SettingRow icon="aspect" label="Default aspect" value="Fit"/>
          <SettingRow icon="audio" label="Background audio" toggle={true}/>
          <SettingRow icon="pip" label="Picture-in-Picture" toggle={true}/>
        </SettingsGroup>
        <SettingsGroup title="Appearance">
          <SettingRow icon="moon" label="Theme" value={tweaks.theme==='dark'?'Dark':'Light'}
            onClick={() => setTweak('theme', tweaks.theme==='dark'?'light':'dark')}/>
          <div style={{ padding:'12px 14px',borderBottom:'1px solid '+T.border }}>
            <div style={{ fontSize:14,marginBottom:10,color:T.text }}>Accent colour</div>
            <div style={{ display:'flex',gap:8 }}>
              {['#f59e0b','#ef4444','#22c55e','#a78bfa','#4d8bff','#f0f0f0'].map(col => (
                <button key={col} onClick={() => setTweak('accent',col)} style={{ width:32,height:32,borderRadius:16,border:`2px solid ${tweaks.accent===col?'#fff':'transparent'}`,background:col,cursor:'pointer',padding:0 }}/>
              ))}
            </div>
          </div>
        </SettingsGroup>
        <SettingsGroup title="Subtitles">
          <SettingRow icon="cc" label="Auto-load embedded" toggle={true}/>
          <SettingRow icon="cc" label="Default style" value="Cinema"/>
        </SettingsGroup>
        <SettingsGroup title="Privacy">
          <SettingRow icon="lock" label="Private folder PIN" value="Set"/>
          <SettingRow icon="eye-off" label="Hide app in recents" toggle={false}/>
        </SettingsGroup>
        <SettingsGroup title="About">
          <SettingRow icon="star" label="Rate Reel"/>
          <SettingRow icon="file" label="Open source licenses"/>
        </SettingsGroup>
      </div>
    </div>
  );
}

function SettingsGroup({ title, children }) {
  return (
    <div style={{ marginBottom:20 }}>
      <div style={{ fontSize:11,fontWeight:700,color:T.textMuted,textTransform:'uppercase',letterSpacing:1.2,padding:'0 4px 8px' }}>{title}</div>
      <div style={{ background:T.surface,borderRadius:14,border:'1px solid '+T.border,overflow:'hidden' }}>{children}</div>
    </div>
  );
}

function SettingRow({ icon, label, value, toggle, onClick }) {
  const [on, setOn] = React.useState(toggle === true);
  return (
    <button onClick={() => { if(toggle!==undefined) setOn(o=>!o); else if(onClick) onClick(); }} style={{ width:'100%',display:'flex',alignItems:'center',gap:12,padding:'13px 14px',border:'none',borderBottom:'1px solid '+T.border,background:'transparent',color:T.text,cursor:'pointer',fontFamily:'inherit' }}>
      <Icon name={icon} size={18} color={T.textDim}/>
      <div style={{ flex:1,textAlign:'left',fontSize:14 }}>{label}</div>
      {value!==undefined&&<div style={{ fontSize:13,color:T.textDim }}>{value}</div>}
      {toggle!==undefined&&<Toggle on={on}/>}
      {value===undefined&&toggle===undefined&&<Icon name="chev-right" size={16} color={T.textMuted}/>}
    </button>
  );
}

function Toggle({ on, accent = T.accent }) {
  return (
    <div style={{ width:36,height:22,borderRadius:11,position:'relative',background:on?accent:T.surface3,transition:'background .15s' }}>
      <div style={{ position:'absolute',top:2,left:on?16:2,width:18,height:18,borderRadius:9,background:'#fff',transition:'left .15s',boxShadow:'0 1px 2px rgba(0,0,0,0.3)' }}/>
    </div>
  );
}

// ── Private folder PIN ─────────────────────────────────────────────────
function PrivateLock({ onBack, accent }) {
  const [pin, setPin] = React.useState('');
  const press = k => { if(k==='del') setPin(p=>p.slice(0,-1)); else if(pin.length<6) setPin(p=>p+k); };
  return (
    <div style={{ display:'flex',flexDirection:'column',height:'100%',background:T.bg }}>
      <TopBar title="Private folder" onBack={onBack}/>
      <div style={{ flex:1,display:'flex',flexDirection:'column',alignItems:'center',justifyContent:'center',gap:24,padding:24 }}>
        <div style={{ width:80,height:80,borderRadius:40,background:accentSoftColor(accent),display:'flex',alignItems:'center',justifyContent:'center' }}>
          <Icon name="lock" size={36} color={accent}/>
        </div>
        <div style={{ textAlign:'center' }}>
          <div style={{ fontSize:18,fontWeight:700 }}>Enter your PIN</div>
          <div style={{ fontSize:12,color:T.textDim,marginTop:4 }}>This folder is hidden from your library</div>
        </div>
        <div style={{ display:'flex',gap:14 }}>
          {[0,1,2,3,4,5].map(i => (
            <div key={i} style={{ width:14,height:14,borderRadius:7,background:i<pin.length?accent:'transparent',border:`1.5px solid ${i<pin.length?accent:T.borderStrong}` }}/>
          ))}
        </div>
      </div>
      <div style={{ padding:'0 32px 30px' }}>
        <div style={{ display:'grid',gridTemplateColumns:'repeat(3, 1fr)',gap:14 }}>
          {['1','2','3','4','5','6','7','8','9','','0','del'].map((k,i) => (
            <button key={i} onClick={() => k&&press(k)} disabled={!k} style={{ height:60,borderRadius:30,border:'none',background:k&&k!=='del'?T.surface:'transparent',color:T.text,fontSize:22,fontWeight:500,fontFamily:'inherit',cursor:k?'pointer':'default',display:'flex',alignItems:'center',justifyContent:'center' }}>
              {k==='del'?<Icon name="back" size={22}/>:k}
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}

// ── Small shared components ────────────────────────────────────────────
function PlayBadge({ accent }) {
  return (
    <div style={{ position:'absolute',left:10,top:10,width:32,height:32,borderRadius:16,background:'rgba(0,0,0,0.5)',backdropFilter:'blur(6px)',display:'flex',alignItems:'center',justifyContent:'center',border:'1px solid rgba(255,255,255,0.18)' }}>
      <Icon name="play" size={14} color="#fff"/>
    </div>
  );
}

function DurationBadge({ children, small }) {
  return (
    <div style={{ position:'absolute',right:6,bottom:6,padding:small?'2px 5px':'3px 6px',borderRadius:4,background:'rgba(0,0,0,0.7)',fontSize:small?10:11,fontFamily:T.mono,color:'#fff',fontWeight:600,letterSpacing:0.3 }}>{children}</div>
  );
}

function FavBadge({ accent }) {
  return (
    <div style={{ position:'absolute',left:6,top:6,width:22,height:22,borderRadius:11,background:'rgba(0,0,0,0.6)',backdropFilter:'blur(4px)',display:'flex',alignItems:'center',justifyContent:'center' }}>
      <Icon name="heart-fill" size={12} color={accent}/>
    </div>
  );
}

// ── Scan picker modal (shown when user taps rescan) ────────────────────
function ScanPickerModal({ accent, onPick, onClose }) {
  const supportsFS = 'showDirectoryPicker' in window;
  const options = [
    supportsFS && { mode:'fsa',    icon:'folder', title:'Scan a folder',   desc:'Pick a folder — Reel recurses all subfolders',      primary:true },
    {              mode:'folder',  icon:'scan',   title:'Browse folder',   desc:'File manager folder picker (Android compatible)',    primary:!supportsFS },
    {              mode:'files',   icon:'film',   title:'Pick video files',desc:'Choose specific videos from the media gallery',      primary:false },
  ].filter(Boolean);

  return (
    <div onClick={onClose} style={{ position:'fixed',inset:0,zIndex:50,background:'rgba(0,0,0,0.6)',backdropFilter:'blur(4px)',display:'flex',flexDirection:'column',justifyContent:'flex-end' }}>
      <div onClick={e=>e.stopPropagation()} style={{ background:T.surface,borderTopLeftRadius:24,borderTopRightRadius:24,borderTop:'1px solid '+T.border,padding:'16px 20px 32px' }}>
        <div style={{ width:38,height:4,borderRadius:2,background:'rgba(255,255,255,0.2)',margin:'0 auto 16px' }}/>
        <div style={{ fontSize:18,fontWeight:700,marginBottom:4 }}>Add videos</div>
        <div style={{ fontSize:13,color:T.textDim,marginBottom:18,lineHeight:1.5 }}>Choose how to scan — you can use all three methods to build your library.</div>
        <div style={{ display:'flex',flexDirection:'column',gap:10 }}>
          {options.map(opt => (
            <button key={opt.mode} onClick={() => onPick(opt.mode)} style={{ display:'flex',alignItems:'center',gap:14,padding:'14px',borderRadius:14,border:'1px solid',borderColor:opt.primary?accent:T.border,background:opt.primary?accentSoftColor(accent):'transparent',color:T.text,fontFamily:'inherit',cursor:'pointer',textAlign:'left',width:'100%' }}>
              <div style={{ width:44,height:44,borderRadius:12,background:opt.primary?accent:T.surface2,display:'flex',alignItems:'center',justifyContent:'center',flexShrink:0 }}>
                <Icon name={opt.icon} size={22} color={opt.primary?'#000':T.textDim}/>
              </div>
              <div style={{ flex:1,minWidth:0 }}>
                <div style={{ fontSize:14,fontWeight:700,color:opt.primary?accent:T.text }}>{opt.title}</div>
                <div style={{ fontSize:12,color:T.textDim,marginTop:2,lineHeight:1.4 }}>{opt.desc}</div>
              </div>
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { TopBar, TabBar, NowPlayingBar, LibraryScreen, FoldersScreen, FolderDetail, SearchScreen, PlaylistsScreen, HistoryScreen, SettingsScreen, PrivateLock, EmptyState, PlayBadge, DurationBadge, FavBadge, Toggle, SettingRow, SettingsGroup, HighlightedText, ScanPickerModal });
