// Admin App · session gate + hash deep-link router (#/pipeline etc).

const ADMIN_SLUGS = { dash:'dashboard', onb:'pipeline', pubcrm:'publishers', pubintel:'intel', creators:'creators', biz:'business', growers:'growers', inbox:'submissions', desk:'content', studio:'studio', coverage:'coverage', reqs:'requests', spot:'spotlight', nl:'newsletter', video:'videos', pods:'podcasts', ads:'ads', synd:'syndication', rev:'revenue', acq:'acquisition', team:'team' };
const SLUG_TO_ROUTE = Object.fromEntries(Object.entries(ADMIN_SLUGS).map(([k,v])=>[v,k]));

function routeFromHash(){
  const slug = (location.hash||'').replace(/^#\/?/,'').toLowerCase();
  return SLUG_TO_ROUTE[slug] || 'dash';
}

// Error boundary · one broken view must not blank the whole console
class AdminBoundary extends React.Component{
  constructor(p){ super(p); this.state = {err:null}; }
  static getDerivedStateFromError(err){ return {err}; }
  componentDidUpdate(prev){ if(prev.routeKey!==this.props.routeKey && this.state.err) this.setState({err:null}); }
  render(){
    if(this.state.err) return (
      <div style={{padding:'60px 24px',textAlign:'center',fontFamily:'var(--sans)'}}>
        <div className="mono" style={{fontSize:10,letterSpacing:'.16em',color:'var(--red)'}}>VIEW ERROR</div>
        <div className="serif" style={{fontSize:20,fontWeight:700,margin:'10px 0 6px'}}>This section hit a snag.</div>
        <div style={{fontSize:12.5,color:'var(--mute)',maxWidth:420,margin:'0 auto 16px'}}>{String(this.state.err && this.state.err.message || this.state.err)}</div>
        <button className="btn k" onClick={()=>{ location.hash='#/dashboard'; this.setState({err:null}); }}>Back to dashboard</button>
      </div>
    );
    return this.props.children;
  }
}

function AdminApp(){
  const [sess, setSess]   = React.useState(getAdminSession());
  const [route, setRouteRaw] = React.useState(routeFromHash());

  React.useEffect(()=>{
    const auth = ()=>setSess(getAdminSession());
    const hash = ()=>setRouteRaw(routeFromHash());
    window.addEventListener('tuepac-auth', auth);
    window.addEventListener('hashchange', hash);
    return ()=>{ window.removeEventListener('tuepac-auth', auth); window.removeEventListener('hashchange', hash); };
  }, []);
  React.useEffect(()=>{ window.scrollTo(0,0); }, [route]);

  function setRoute(id){
    setRouteRaw(id);
    const slug = ADMIN_SLUGS[id]||'dashboard';
    if(location.hash !== '#/'+slug) history.replaceState(null,'','#/'+slug);
  }

  if(!sess) return <AdminLogin/>;

  const allowed = roleAllows(sess.role, route) ? route : 'dash';
  let View;
  if(allowed==='dash')          View = window.Dashboard;
  else if(allowed==='pubcrm')   View = window.PublisherCRM;
  else if(allowed==='pubintel') View = window.PublisherIntel;
  else if(allowed==='creators') View = window.CreatorCRM;
  else if(allowed==='acq')      View = window.Acquisition;
  else if(allowed==='biz')      View = window.BusinessHub;
  else if(allowed==='growers')  View = window.GrowersHub;
  else if(allowed==='inbox')    View = window.InboxView;
  else if(allowed==='desk')     View = window.ContentDesk;
  else if(allowed==='studio')   View = window.EditorialStudio;
  else if(allowed==='coverage') View = window.CoverageDesk;
  else if(allowed==='reqs')     View = window.ArticleRequests;
  else if(allowed==='spot')     View = window.SpotlightDesk;
  else if(allowed==='video')    View = window.VideoDesk;
  else if(allowed==='pods')     View = window.PodcastDesk;
  else if(allowed==='nl')       View = window.Newsletter;
  else if(allowed==='ads')      View = window.AdOps;
  else if(allowed==='synd')     View = window.Syndication;
  else if(allowed==='rev')      View = window.Revenue;
  else if(allowed==='onb')      View = window.Onboarding;
  else if(allowed==='team')     View = window.TeamSettings;
  else                          View = window.Dashboard;

  return <AdminBoundary routeKey={allowed}><View setRoute={setRoute}/></AdminBoundary>;
}

window.applySample && window.applySample((sessionStorage.getItem('tuepac_sim')||'sample')==='sample');
ReactDOM.createRoot(document.getElementById('root')).render(<AdminApp/>);
