// Podcast desk · manage the shows listed on the public Media page.
// Shows live in localStorage 'tuepac_podcasts'; approved Podcast submissions from the inbox can be added in one click.

const PODS_LS = 'tuepac_podcasts';
function loadPods(){ try{ return JSON.parse(localStorage.getItem(PODS_LS))||[]; }catch(e){ return []; } }
function persistPods(list){ try{ localStorage.setItem(PODS_LS, JSON.stringify(list)); }catch(e){} }
window.loadPods = loadPods;

const POD_PLATFORMS = ['Spotify','Apple Podcasts','YouTube','Website','Instagram','TikTok','RSS feed'];

function PodcastDesk({setRoute}){
  const [pods, setPods] = React.useState(loadPods);
  const blank = {show:'', host:'', cadence:'', latest:'', sources:[]};
  const [f, setF] = React.useState(blank);
  const [srcType, setSrcType] = React.useState('Spotify');
  const [srcUrl, setSrcUrl] = React.useState('');
  const [note, setNote] = React.useState('');
  const subs = (()=>{ try{ return (JSON.parse(localStorage.getItem('tuepac_inbox'))||[]).filter(s=>s.type==='Podcast'&&s.status==='Approved'); }catch(e){ return []; } })();
  const claimable = subs.filter(s=>!pods.some(p=>p.show.toLowerCase()===(s.payload.show||'').toLowerCase()));

  function save(list){ setPods(list); persistPods(list); }
  function set(k,v){ setF(prev=>({...prev,[k]:v})); setNote(''); }
  function addSource(){
    if(!srcUrl.trim()) return;
    setF(prev=>({...prev, sources:[...prev.sources, {type:srcType, url:srcUrl.trim()}]}));
    setSrcUrl('');
  }
  function add(status){
    if(!f.show.trim()){ setNote('Give the show a name.'); return; }
    if(!f.sources.length){ setNote('Add at least one source link.'); return; }
    if(pods.some(p=>p.show.toLowerCase()===f.show.trim().toLowerCase())){ setNote('That show is already listed.'); return; }
    save([{k:'P'+Date.now().toString(36).toUpperCase(), show:window.deDash(f.show.trim()), host:f.host.trim()||'TUEPAC Desk', cadence:window.deDash(f.cadence.trim()), latest:window.deDash(f.latest.trim()), sources:f.sources, status, added:new Date().toISOString().slice(0,10)}, ...pods]);
    setF(blank); setNote(status==='Published' ? '✓ Live on the Media page.' : '✓ Saved as draft.');
  }
  function fromSub(s){
    const srcs = String(s.payload.sources||'').split(' · ').map(x=>{ const i=x.indexOf(': '); return i>0?{type:x.slice(0,i),url:x.slice(i+2)}:null; }).filter(Boolean);
    setF({show:s.payload.show||'', host:s.payload.host||'', cadence:'', latest:'', sources:srcs});
    setNote('Loaded from '+s.id+' · review and publish.');
  }
  function setStatus(k,status){ save(pods.map(p=>p.k===k?{...p,status}:p)); }
  function remove(k){ save(pods.filter(p=>p.k!==k)); }

  return (
    <AdminShell route="pods" setRoute={setRoute} title="Podcast desk" breadcrumb="CONTENT · SHOW DIRECTORY"
      actions={<a className="btn gh" href="Media.html#podcasts" target="_blank" rel="noopener">View Media page ↗</a>}>

      <div className="split-4" style={{marginBottom:18}}>
        <Stat n={String(pods.filter(p=>p.status==='Published').length)} l="Shows live" d="on the Media page"/>
        <Stat n={String(pods.filter(p=>p.status==='Draft').length)} l="Drafts" d="not yet public"/>
        <Stat n={String(claimable.length)} l="Approved submissions" d="ready to list"/>
        <Stat n="Multi-platform" l="Hosting" d="we list, creators host"/>
      </div>

      <div className="lay2" style={{display:'grid',gridTemplateColumns:'1fr 1.4fr',gap:18,alignItems:'flex-start'}}>
        <div style={{display:'flex',flexDirection:'column',gap:18}}>
          <Card title="Add a show" meta="one listing, every platform">
            <div className="eyebrow" style={{marginBottom:5}}>SHOW NAME</div>
            <input value={f.show} onChange={e=>set('show',e.target.value)} style={podInp()}/>
            <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:10,marginTop:12}}>
              <div><div className="eyebrow" style={{marginBottom:5}}>HOST</div><input value={f.host} onChange={e=>set('host',e.target.value)} style={podInp()}/></div>
              <div><div className="eyebrow" style={{marginBottom:5}}>CADENCE / BEAT</div><input value={f.cadence} onChange={e=>set('cadence',e.target.value)} placeholder="Weekly, capital and policy" style={podInp()}/></div>
            </div>
            <div className="eyebrow" style={{margin:'12px 0 5px'}}>LATEST EPISODE <span style={{color:'var(--mute)',textTransform:'none',letterSpacing:'.04em'}}>· optional</span></div>
            <input value={f.latest} onChange={e=>set('latest',e.target.value)} placeholder="E. 12, The case for a business index" style={podInp()}/>
            <div className="eyebrow" style={{margin:'12px 0 5px'}}>WHERE IT LIVES</div>
            <div style={{display:'flex',gap:6}}>
              <select value={srcType} onChange={e=>setSrcType(e.target.value)} style={{...podInp(),width:130,flex:'0 0 auto'}}>{POD_PLATFORMS.map(p=><option key={p}>{p}</option>)}</select>
              <input value={srcUrl} onChange={e=>setSrcUrl(e.target.value)} onKeyDown={e=>{if(e.key==='Enter')addSource();}} placeholder="Paste the link" style={podInp()}/>
              <button className="btn gh s" onClick={addSource} style={{flex:'0 0 auto'}}>＋ Add</button>
            </div>
            {!!f.sources.length && (
              <div style={{display:'flex',flexWrap:'wrap',gap:6,marginTop:8}}>
                {f.sources.map((s,i)=>(
                  <span key={i} className="mono" style={{fontSize:9.5,letterSpacing:'.06em',border:'1px solid var(--rule-line)',background:'var(--canvas)',padding:'3px 7px',display:'inline-flex',gap:6,alignItems:'center'}}>
                    <b>{s.type.toUpperCase()}</b> {s.url.replace(/^https?:\/\//,'').slice(0,26)}
                    <button onClick={()=>setF(prev=>({...prev,sources:prev.sources.filter((_,j)=>j!==i)}))} style={{border:0,background:'transparent',cursor:'pointer',color:'var(--mute)',fontSize:10,padding:0}}>✕</button>
                  </span>
                ))}
              </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('✓')||note.startsWith('Loaded')?'var(--green)':'var(--red)'}}>{note.toUpperCase()}</div>}
          </Card>

          <Card title="Approved submissions" meta={`${claimable.length} ready`}>
            {!claimable.length && <div className="mono" style={{padding:'14px 0',fontSize:9.5,letterSpacing:'.1em',color:'var(--mute)'}}>NONE WAITING · "GET YOUR SHOW ON TUEPAC" SUBMISSIONS LAND IN SUBMISSIONS FIRST</div>}
            {claimable.map(s=>(
              <div key={s.id} style={{display:'flex',gap:10,alignItems:'center',padding:'8px 0',borderBottom:'1px solid var(--rule-line)'}}>
                <div style={{flex:1,minWidth:0}}>
                  <div style={{fontSize:12.5,fontWeight:600}}>{s.payload.show}</div>
                  <div className="mono" style={{fontSize:9.5,color:'var(--mute)',letterSpacing:'.06em',marginTop:2}}>{(s.payload.host||'').toUpperCase()} · {s.id}</div>
                </div>
                <button className="btn k s" onClick={()=>fromSub(s)} style={{padding:'2px 8px',fontSize:10}}>Load →</button>
              </div>
            ))}
          </Card>
        </div>

        <Card title="Show directory" meta={`${pods.length} listed`}>
          {!pods.length && <div className="mono" style={{padding:'22px 0',fontSize:9.5,letterSpacing:'.1em',color:'var(--mute)'}}>NO SHOWS YET · ADD ONE OR LOAD AN APPROVED SUBMISSION</div>}
          {pods.map(p=>(
            <div key={p.k} style={{display:'grid',gridTemplateColumns:'1fr auto',gap:12,alignItems:'center',padding:'10px 0',borderBottom:'1px solid var(--rule-line)'}}>
              <div style={{minWidth:0}}>
                <div className="serif" style={{fontSize:14.5,fontWeight:700}}>{p.show}</div>
                <div className="mono" style={{fontSize:9.5,color:'var(--mute)',letterSpacing:'.06em',marginTop:3}}>
                  {p.host.toUpperCase()}{p.cadence?' · '+p.cadence.toUpperCase():''}{p.latest?' · '+p.latest.toUpperCase():''}
                </div>
                <div className="mono" style={{fontSize:9,color:'var(--navy)',letterSpacing:'.06em',marginTop:3}}>{p.sources.map(s=>s.type.toUpperCase()).join(' · ')}</div>
              </div>
              <div style={{display:'flex',gap:6,alignItems:'center'}}>
                <Pill k={p.status==='Published'?'live':'muted'}>{p.status.toUpperCase()}</Pill>
                {p.status==='Published'
                  ? <button className="btn gh s" onClick={()=>setStatus(p.k,'Draft')} style={{padding:'2px 8px',fontSize:10}}>Unpublish</button>
                  : <button className="btn k s" onClick={()=>setStatus(p.k,'Published')} style={{padding:'2px 8px',fontSize:10}}>Publish</button>}
                <button className="btn gh s" onClick={()=>remove(p.k)} style={{padding:'2px 8px',fontSize:10,color:'var(--mute)'}}>×</button>
              </div>
            </div>
          ))}
        </Card>
      </div>
    </AdminShell>
  );
}

function podInp(){ return {width:'100%',padding:'8px 10px',border:'1px solid var(--rule-line)',background:'var(--bg)',fontSize:12.5,outline:'none',fontFamily:'var(--sans)'}; }

window.PodcastDesk = PodcastDesk;
