// Spotlight desk · nominations → vetting → publishing, plus the home-page rotation:
// one Legend (historical), one Leader (living legend), one Neighbor (everyday hero).

window.SPOT_NOMS = [];
const SPOT_ERAS   = ['Historical','Living legend','Rising'];
const SPOT_ARENAS = ['Valor','Sports','Business','Education','Everyday'];
const SPOT_SLOTS  = [ ['legend','The Legend','historical GOAT'], ['leader','The Leader','living legend'], ['neighbor','The Neighbor','everyday hero'] ];
const SLOT_BY_ERA = { 'Historical':'legend', 'Living legend':'leader', 'Rising':'neighbor' };

function spotLoad(k, fb){ try{ const v = JSON.parse(localStorage.getItem(k)); return v===null||v===undefined?fb:v; }catch(e){ return fb; } }
function spotSave(k, v){ try{ localStorage.setItem(k, JSON.stringify(v)); }catch(e){} }
function spotReadPhoto(file, cb){
  const r = new FileReader();
  r.onload = ()=>{ const img = new Image(); img.onload = ()=>{
    const s = Math.min(img.width, img.height), c = document.createElement('canvas'); c.width = c.height = 400;
    c.getContext('2d').drawImage(img, (img.width-s)/2, (img.height-s)/2, s, s, 0, 0, 400, 400);
    cb(c.toDataURL('image/jpeg', .82));
  }; img.src = r.result; };
  r.readAsDataURL(file);
}

function SpotlightDesk({setRoute}){
  const [people, setPeople] = React.useState(()=>spotLoad('tuepac_spot_honorees', []));
  const [rot, setRot]       = React.useState(()=>spotLoad('tuepac_spot_rotation', {legend:null, leader:null, neighbor:null}));
  const [f, setF]           = React.useState('All');
  const [form, setForm]     = React.useState({name:'', era:'Rising', arena:'Everyday', city:'', story:'', photo:null});
  React.useEffect(()=>{ spotSave('tuepac_spot_honorees', people); }, [people]);
  React.useEffect(()=>{ spotSave('tuepac_spot_rotation', rot); }, [rot]);

  const tone = { New:'#B31942', Vetting:'#b8860b', Drafting:'#0A3161', Published:'#1f8a5b' };
  const STATUSES = ['New','Vetting','Drafting','Published'];
  const rows = people.filter(n=>f==='All'||n.status===f);

  function add(){
    if(!form.name.trim()) return;
    const p = {...form, name:form.name.trim(), city:form.city.trim(), story:form.story.trim(), id:'SP-'+Date.now(), status:'New', by:'Desk'};
    setPeople(prev=>[p, ...prev]);
    setForm({name:'', era:'Rising', arena:'Everyday', city:'', story:'', photo:null});
  }
  function setPhoto(id, file){ if(!file) return; spotReadPhoto(file, url=>setPeople(prev=>prev.map(p=>p.id===id?{...p,photo:url}:p))); }
  function setStatus(id, status){ setPeople(prev=>prev.map(p=>p.id===id?{...p,status}:p)); }
  function toRotation(p){ setRot(prev=>({...prev, [SLOT_BY_ERA[p.era]||'neighbor']: p.id})); }
  function clearSlot(s){ setRot(prev=>({...prev, [s]:null})); }
  const inRot = Object.values(rot);

  const inp = {border:'1px solid var(--rule-line)',padding:'8px 10px',background:'var(--bg)',outline:'none',fontSize:12.5,fontFamily:'var(--sans)',minWidth:0,width:'100%'};

  return (
    <AdminShell route="spot" setRoute={setRoute} title="Spotlight desk" breadcrumb="CONTENT · PEOPLE SPOTLIGHT"
      actions={<>
        <button className="btn gh">Nomination form ↗</button>
        <button className="btn g" onClick={()=>setRoute('studio')}>Draft profile in Studio →</button>
      </>}>

      <Card title="Add an honoree" meta="GOATs and everyday heroes alike · era decides their rotation slot"
        actions={<button className="btn g s" onClick={add} style={{opacity:form.name.trim()?1:.4}}>Add →</button>} style={{marginBottom:18}}>
        <div style={{display:'grid',gridTemplateColumns:'auto 1.2fr .9fr .9fr .9fr 1.6fr',gap:8,alignItems:'center'}}>
          <label style={{width:44,height:44,flex:'none',border:'1px dashed var(--rule-line)',background:form.photo?'url('+form.photo+') center/cover':'var(--canvas)',display:'flex',alignItems:'center',justifyContent:'center',cursor:'pointer',fontSize:9,fontFamily:'var(--mono)',color:'var(--mute)',letterSpacing:'.06em',textAlign:'center'}} title="Upload photo">
            {!form.photo && 'PHOTO'}
            <input type="file" accept="image/*" style={{display:'none'}} onChange={e=>{const f=e.target.files[0]; if(f) spotReadPhoto(f, url=>setForm(fm=>({...fm, photo:url})));}}/>
          </label>
          <input value={form.name} onChange={e=>setForm({...form,name:e.target.value})} placeholder="name" style={inp}/>
          <select value={form.era} onChange={e=>setForm({...form,era:e.target.value})} style={inp}>{SPOT_ERAS.map(x=><option key={x}>{x}</option>)}</select>
          <select value={form.arena} onChange={e=>setForm({...form,arena:e.target.value})} style={inp}>{SPOT_ARENAS.map(x=><option key={x}>{x}</option>)}</select>
          <input value={form.city} onChange={e=>setForm({...form,city:e.target.value})} placeholder="city, ST" style={inp}/>
          <input value={form.story} onChange={e=>setForm({...form,story:e.target.value})} onKeyDown={e=>{if(e.key==='Enter')add();}} placeholder="one-line story · e.g. Medal of Honor, Korea, 1952" style={inp}/>
        </div>
        <div className="mono" style={{fontSize:9.5,color:'var(--mute)',letterSpacing:'.1em',marginTop:8}}>HISTORICAL → LEGEND SLOT · LIVING LEGEND → LEADER SLOT · RISING → NEIGHBOR SLOT</div>
      </Card>

      <div className="split-4" style={{marginBottom:18}}>
        <Stat n={people.length} l="In the pipeline" d={null}/>
        <Stat n={people.filter(p=>p.status==='Published').length} l="Published" d="front page + newsletter"/>
        <Stat n={people.filter(p=>p.era==='Historical').length} l="Legends on file" d="the historical record"/>
        <Stat n={inRot.filter(Boolean).length+'/3'} l="Rotation filled" d="live on the front page"/>
      </div>

      <div style={{display:'grid',gridTemplateColumns:'1.4fr 1fr',gap:18,alignItems:'flex-start'}}>
        <Card title="Honorees" meta={rows.length+' shown'}
          actions={<Seg value={f} onChange={setF} options={['All','New','Vetting','Drafting','Published']}/>}>
          <div style={{overflowX:'auto',marginLeft:-14,marginRight:-14}}>
          <table className="tbl" style={{width:'100%',minWidth:560}}>
            <thead><tr><th>PERSON</th><th>ERA</th><th>ARENA</th><th>CITY</th><th>STATUS</th><th></th></tr></thead>
            <tbody>
              {!rows.length && <tr><td colSpan="6"><span className="mono" style={{fontSize:9.5,letterSpacing:'.1em',color:'var(--mute)'}}>NO HONOREES YET · ADD THE FIRST ONE ABOVE</span></td></tr>}
              {rows.map(n=>(
                <tr key={n.id}>
                  <td><div style={{display:'flex',gap:8,alignItems:'center'}}>
                    <label style={{width:30,height:30,flex:'none',borderRadius:'50%',border:'1px solid var(--rule-line)',background:n.photo?'url('+n.photo+') center/cover':'var(--canvas)',cursor:'pointer',display:'flex',alignItems:'center',justifyContent:'center',fontSize:11,color:'var(--mute)'}} title={n.photo?'Replace photo':'Add photo'}>
                      {!n.photo && '+'}
                      <input type="file" accept="image/*" style={{display:'none'}} onChange={e=>setPhoto(n.id, e.target.files[0])}/>
                    </label>
                    <div><div style={{fontSize:12.5,fontWeight:600}}>{n.name}</div><div style={{fontSize:10.5,color:'var(--mute)'}}>{n.story}</div></div>
                  </div></td>
                  <td className="mono" style={{fontSize:10,letterSpacing:'.04em'}}>{n.era.toUpperCase()}</td>
                  <td className="mono" style={{fontSize:10,letterSpacing:'.04em'}}>{n.arena.toUpperCase()}</td>
                  <td style={{fontSize:11.5}}>{n.city||' · '}</td>
                  <td><select value={n.status} onChange={e=>setStatus(n.id, e.target.value)} style={{border:'1px solid var(--rule-line)',background:'var(--bg)',fontFamily:'var(--mono)',fontSize:9.5,letterSpacing:'.08em',fontWeight:700,color:tone[n.status],padding:'3px 4px',outline:'none'}}>{STATUSES.map(s=><option key={s}>{s}</option>)}</select></td>
                  <td>{inRot.includes(n.id)
                    ? <span className="mono" style={{fontSize:9,letterSpacing:'.08em',color:'var(--green)'}}>IN ROTATION</span>
                    : <button className="btn gh s" onClick={()=>toRotation(n)}>→ Rotation</button>}</td>
                </tr>
              ))}
            </tbody>
          </table>
          </div>
        </Card>

        <div style={{display:'flex',flexDirection:'column',gap:18,minWidth:0}}>
          <Card title="Front-page rotation" meta="one legend · one leader · one neighbor">
            <div style={{display:'flex',flexDirection:'column'}}>
              {SPOT_SLOTS.map(([k,label,sub],i)=>{
                const p = people.find(x=>x.id===rot[k]);
                return (
                  <div key={k} style={{display:'grid',gridTemplateColumns:'1fr auto',gap:10,padding:'10px 0',borderBottom:i===2?'none':'1px solid var(--rule-line)',alignItems:'center'}}>
                    <div>
                      <div className="mono" style={{fontSize:9,letterSpacing:'.14em',color:'var(--mute)',textTransform:'uppercase'}}>{label} · {sub}</div>
                      {p ? <><div style={{fontSize:13,fontWeight:700,marginTop:3}}>{p.name}</div><div style={{fontSize:11,color:'var(--mute)'}}>{p.arena} · {p.story}</div></>
                        : <div style={{fontSize:12,color:'var(--mute)',marginTop:3}}>Empty · add an honoree with the matching era</div>}
                    </div>
                    {p && <button className="btn gh s" onClick={()=>clearSlot(k)}>×</button>}
                  </div>
                );
              })}
            </div>
            <div className="mono" style={{fontSize:9,letterSpacing:'.08em',color:'var(--mute)',marginTop:8}}>THE FRONT PAGE SPOTLIGHT RAIL READS THIS ROTATION · CHANGES SHOW ON RELOAD</div>
          </Card>

          <Card title="How a Spotlight ships" meta="profile · no news peg required">
            <div style={{display:'flex',flexDirection:'column',gap:12,padding:'4px 0'}}>
              {[['1','Nomination lands','Reader form, a desk, or a Member Voice poll.'],
                ['2','Vet & confirm','Editor verifies the story and gets the honoree\u2019s OK (estate or historians for legends).'],
                ['3','Assign or draft','Route to a member desk, or draft in the Studio (AI first pass).'],
                ['4','Publish & rotate','Spotlight section, People Index or Service & Valor entry, rotation slot, newsletter push.']].map(s=>(
                <div key={s[0]} style={{display:'flex',gap:12,alignItems:'flex-start'}}>
                  <span className="mono" style={{flex:'none',width:22,height:22,borderRadius:'50%',border:'1px solid var(--rule-line, #d8dee8)',display:'flex',alignItems:'center',justifyContent:'center',fontSize:10,fontWeight:700,color:'var(--navy, #0A3161)'}}>{s[0]}</span>
                  <div><div style={{fontSize:12.5,fontWeight:700}}>{s[1]}</div><div style={{fontSize:11.5,color:'var(--mute)',marginTop:2}}>{s[2]}</div></div>
                </div>
              ))}
            </div>
          </Card>
        </div>
      </div>
    </AdminShell>
  );
}

Object.assign(window, { SpotlightDesk });
