// Video desk · publish YouTube videos to the public Media page.
// Paste a link, we parse the ID, pull the thumbnail, and you publish. Embeds stream from YouTube; views and monetization stay with the channel.

function ytId(url){
  const m = String(url||'').match(/(?:youtu\.be\/|v=|shorts\/|embed\/|live\/)([A-Za-z0-9_-]{11})/);
  if(m) return m[1];
  const bare = String(url||'').trim();
  return /^[A-Za-z0-9_-]{11}$/.test(bare) ? bare : null;
}
window.ytId = ytId;

const VIDEOS_LS = 'tuepac_videos';
function loadVideos(){ try{ return JSON.parse(localStorage.getItem(VIDEOS_LS))||[]; }catch(e){ return []; } }
function persistVideos(list){ try{ localStorage.setItem(VIDEOS_LS, JSON.stringify(list)); }catch(e){} }
window.loadVideos = loadVideos;

const VID_TYPES = ['TUEPAC Original','Interview','Explainer','Event','Partner','HBCU'];

function VideoDesk({setRoute}){
  const [vids, setVids] = React.useState(loadVideos);
  const [url, setUrl] = React.useState('');
  const [title, setTitle] = React.useState('');
  const [kind, setKind] = React.useState('TUEPAC Original');
  const [src, setSrc] = React.useState('TUEPAC Originals');
  const [note, setNote] = React.useState('');
  const id = ytId(url);

  function save(list){ setVids(list); persistVideos(list); }
  function add(status){
    if(!id){ setNote('Paste a valid YouTube link first.'); return; }
    if(!title.trim()){ setNote('Give the video a title.'); return; }
    if(vids.some(v=>v.yt===id)){ setNote('That video is already in the library.'); return; }
    save([{k:'V'+Date.now().toString(36).toUpperCase(), yt:id, title:window.deDash(title.trim()), type:kind, src:src.trim()||'TUEPAC', status, added:new Date().toISOString().slice(0,10)}, ...vids]);
    setUrl(''); setTitle(''); setNote(status==='Published' ? '✓ Live on the Media page.' : '✓ Saved as draft.');
  }
  function setStatus(k, status){ save(vids.map(v=>v.k===k?{...v,status}:v)); }
  function remove(k){ save(vids.filter(v=>v.k!==k)); }

  return (
    <AdminShell route="video" setRoute={setRoute} title="Video desk" breadcrumb="CONTENT · VIDEO LIBRARY"
      actions={<a className="btn gh" href="Media.html#video" target="_blank" rel="noopener">View Media page ↗</a>}>

      <div className="split-4" style={{marginBottom:18}}>
        <Stat n={String(vids.filter(v=>v.status==='Published').length)} l="Published" d="live on Media page"/>
        <Stat n={String(vids.filter(v=>v.status==='Draft').length)} l="Drafts" d="not yet public"/>
        <Stat n={String(new Set(vids.map(v=>v.src)).size)} l="Sources" d="channels and partners"/>
        <Stat n="YouTube" l="Hosting" d="embeds stream from the channel"/>
      </div>

      <div className="lay2" style={{display:'grid',gridTemplateColumns:'1fr 1.4fr',gap:18,alignItems:'flex-start'}}>
        <Card title="Add a video" meta="paste a YouTube link">
          <div className="eyebrow" style={{marginBottom:5}}>YOUTUBE LINK</div>
          <input value={url} onChange={e=>{setUrl(e.target.value);setNote('');}} placeholder="https://youtube.com/watch?v=…"
            style={{width:'100%',padding:'8px 10px',border:'1px solid var(--rule-line)',background:'var(--bg)',fontSize:12.5,outline:'none',fontFamily:'var(--mono)'}}/>
          {url.trim() && !id && <div className="mono" style={{fontSize:9.5,color:'var(--red)',letterSpacing:'.08em',marginTop:5}}>NO VIDEO ID FOUND · WATCH, SHORTS, AND YOUTU.BE LINKS WORK</div>}
          {id && (
            <div style={{marginTop:10,border:'1px solid var(--rule-line)'}}>
              <img src={'https://i.ytimg.com/vi/'+id+'/hqdefault.jpg'} alt="" style={{width:'100%',display:'block',aspectRatio:'16/9',objectFit:'cover'}}/>
              <div className="mono" style={{fontSize:9,letterSpacing:'.1em',color:'var(--mute)',padding:'5px 8px'}}>ID {id} · THUMBNAIL PULLED FROM YOUTUBE</div>
            </div>
          )}
          <div className="eyebrow" style={{margin:'12px 0 5px'}}>TITLE</div>
          <input value={title} onChange={e=>setTitle(e.target.value)} placeholder="How it appears on the Media page"
            style={{width:'100%',padding:'8px 10px',border:'1px solid var(--rule-line)',background:'var(--bg)',fontSize:13,outline:'none',fontFamily:'var(--sans)'}}/>
          <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:10,marginTop:12}}>
            <div>
              <div className="eyebrow" style={{marginBottom:5}}>TYPE</div>
              <select value={kind} onChange={e=>setKind(e.target.value)} style={{width:'100%',padding:'8px 10px',border:'1px solid var(--rule-line)',background:'var(--bg)',fontSize:12.5,outline:'none',fontFamily:'var(--sans)'}}>
                {VID_TYPES.map(t=><option key={t}>{t}</option>)}
              </select>
            </div>
            <div>
              <div className="eyebrow" style={{marginBottom:5}}>SOURCE / CHANNEL</div>
              <input value={src} onChange={e=>setSrc(e.target.value)} style={{width:'100%',padding:'8px 10px',border:'1px solid var(--rule-line)',background:'var(--bg)',fontSize:12.5,outline:'none',fontFamily:'var(--sans)'}}/>
            </div>
          </div>
          <div style={{display:'flex',gap:8,marginTop:14}}>
            <button className="btn g" onClick={()=>add('Published')}>Publish to Media page</button>
            <button className="btn gh" onClick={()=>add('Draft')}>Save draft</button>
          </div>
          {note && <div className="mono" style={{fontSize:9.5,letterSpacing:'.08em',marginTop:8,color:note.startsWith('✓')?'var(--green)':'var(--red)'}}>{note.toUpperCase()}</div>}
          <div style={{marginTop:14,padding:'10px 12px',background:'var(--paper)',border:'1px solid var(--rule-line)',fontSize:11,color:'var(--ink-2)',lineHeight:1.5}}>
            <span className="mono" style={{fontSize:9,letterSpacing:'.14em',color:'var(--mute)'}}>RIGHTS</span><br/>
            Embeds play through YouTube's player, so views, ads, and monetization stay with the channel owner. Partner videos need embed permission confirmed in the Creator CRM before publishing.
          </div>
        </Card>

        <Card title="Video library" meta={`${vids.length} in library`}>
          {!vids.length && <div className="mono" style={{padding:'22px 0',fontSize:9.5,letterSpacing:'.1em',color:'var(--mute)'}}>NO VIDEOS YET · PASTE A YOUTUBE LINK TO START THE LIBRARY</div>}
          {vids.map(v=>(
            <div key={v.k} style={{display:'grid',gridTemplateColumns:'96px 1fr auto',gap:12,alignItems:'center',padding:'10px 0',borderBottom:'1px solid var(--rule-line)'}}>
              <img src={'https://i.ytimg.com/vi/'+v.yt+'/mqdefault.jpg'} alt="" style={{width:96,aspectRatio:'16/9',objectFit:'cover',display:'block',background:'var(--canvas)'}}/>
              <div style={{minWidth:0}}>
                <div style={{fontSize:13,fontWeight:600,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{v.title}</div>
                <div className="mono" style={{fontSize:9.5,color:'var(--mute)',letterSpacing:'.06em',marginTop:3}}>{v.type.toUpperCase()} · {v.src.toUpperCase()} · {v.added}</div>
              </div>
              <div style={{display:'flex',gap:6,alignItems:'center'}}>
                <Pill k={v.status==='Published'?'live':'muted'}>{v.status.toUpperCase()}</Pill>
                {v.status==='Published'
                  ? <button className="btn gh s" onClick={()=>setStatus(v.k,'Draft')} style={{padding:'2px 8px',fontSize:10}}>Unpublish</button>
                  : <button className="btn k s" onClick={()=>setStatus(v.k,'Published')} style={{padding:'2px 8px',fontSize:10}}>Publish</button>}
                <button className="btn gh s" onClick={()=>remove(v.k)} style={{padding:'2px 8px',fontSize:10,color:'var(--mute)'}}>×</button>
              </div>
            </div>
          ))}
        </Card>
      </div>

      <DopenessQueue/>
    </AdminShell>
  );
}

function DopenessQueue(){
  const KEY='tuepac-dopeness-user';
  const load=()=>{ try{ return JSON.parse(localStorage.getItem(KEY))||[]; }catch(e){ return []; } };
  const [list,setList]=React.useState(load);
  const [url,setUrl]=React.useState(''); const [title,setTitle]=React.useState(''); const [cap,setCap]=React.useState(''); const [tag,setTag]=React.useState('Culture'); const [note,setNote]=React.useState('');
  function save(l){ setList(l); try{ localStorage.setItem(KEY,JSON.stringify(l)); }catch(e){} }
  function add(){
    const id=ytId(url);
    if(!id){ setNote('Paste a valid YouTube link first.'); return; }
    if(!title.trim()){ setNote('Give it a title.'); return; }
    save([{id,title:window.deDash(title.trim()),caption:window.deDash(cap.trim()),tag,credit:'Curated · TUEPAC'} ,...list]);
    setUrl('');setTitle('');setCap('');setNote('\u2713 Live on Daily Dopeness.');
  }
  return (
    <Card title="Daily Dopeness queue" meta="positive propaganda \u00b7 publishes straight to the collection"
      actions={<a className="btn gh s" href="Daily Dopeness.html" target="_blank" rel="noopener">View page \u2197</a>} style={{marginTop:18}}>
      <div style={{display:'grid',gridTemplateColumns:'1.2fr 1fr .7fr auto',gap:10,alignItems:'end'}}>
        <div><div className="eyebrow" style={{marginBottom:5}}>YOUTUBE LINK</div><input value={url} onChange={e=>{setUrl(e.target.value);setNote('');}} placeholder="https://youtube.com/watch?v=\u2026" style={{width:'100%',boxSizing:'border-box',border:'1px solid var(--rule-line)',padding:'9px 11px',background:'var(--bg)',outline:'none',fontSize:12,fontFamily:'var(--mono)'}}/></div>
        <div><div className="eyebrow" style={{marginBottom:5}}>TITLE</div><input value={title} onChange={e=>setTitle(e.target.value)} placeholder="what is it" style={{width:'100%',boxSizing:'border-box',border:'1px solid var(--rule-line)',padding:'9px 11px',background:'var(--bg)',outline:'none',fontSize:12}}/></div>
        <div><div className="eyebrow" style={{marginBottom:5}}>TAG</div><select value={tag} onChange={e=>setTag(e.target.value)} style={{width:'100%',border:'1px solid var(--rule-line)',padding:'9px 8px',background:'var(--bg)',outline:'none',fontSize:12}}>{['Culture','Joy','Film','Sport','Genius','History','Music'].map(t=><option key={t}>{t}</option>)}</select></div>
        <button className="btn g s" onClick={add}>Publish \u2192</button>
      </div>
      <div style={{marginTop:10}}><div className="eyebrow" style={{marginBottom:5}}>CAPTION \u00b7 YOUR VOICE ON IT</div><input value={cap} onChange={e=>setCap(e.target.value)} placeholder="why it's dope, in one line" style={{width:'100%',boxSizing:'border-box',border:'1px solid var(--rule-line)',padding:'9px 11px',background:'var(--bg)',outline:'none',fontSize:12}}/></div>
      {note && <div className="mono" style={{fontSize:10,letterSpacing:'.08em',color:'var(--green)',marginTop:8}}>{note}</div>}
      {list.length>0 && <table className="tbl" style={{marginTop:12,marginLeft:-14,marginRight:-14,width:'calc(100% + 28px)'}}>
        <thead><tr><th>VIDEO</th><th>TAG</th><th>CAPTION</th><th className="r"></th></tr></thead>
        <tbody>{list.map((d,i)=>(<tr key={d.id+i}>
          <td style={{fontSize:12.5,fontWeight:600}}>{d.title}</td>
          <td className="mono" style={{fontSize:10,letterSpacing:'.06em'}}>{(d.tag||'').toUpperCase()}</td>
          <td style={{fontSize:11.5,color:'var(--mute)',maxWidth:260,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>{d.caption}</td>
          <td className="r"><button className="btn gh s" onClick={()=>save(list.filter((_,j)=>j!==i))}>Remove</button></td>
        </tr>))}</tbody>
      </table>}
    </Card>
  );
}
window.VideoDesk = VideoDesk;
window.DopenessQueue = DopenessQueue;
