/* ============================================================
   APP ROOT — client-side routing + shared state.
   ============================================================ */
(function(){
  const { STYLES, BLOCKS, MENU, Home, Collection, Detail } = window;

  function App(){
    const [route,setRoute]=React.useState('home');          // 'home' | 'collection'
    const [styleId,setStyleId]=React.useState('glass');
    const [filter,setFilter]=React.useState({type:'all',subtype:null});
    const [expanded,setExpanded]=React.useState(new Set(['cards']));
    const [detail,setDetail]=React.useState(null);           // block or null
    const [drawer,setDrawer]=React.useState(false);
    const [temp,setTemp]=React.useState('base');             // ambiance: base | warm | cool

    const s = STYLES[styleId];
    const cycleTemp = ()=> setTemp(t=> t==='base' ? 'warm' : t==='warm' ? 'cool' : 'base');

    const filtered = React.useMemo(()=>{
      if(filter.type==='all') return BLOCKS;
      return BLOCKS.filter(b=> b.type===filter.type && (!filter.subtype || b.subtype===filter.subtype));
    },[filter]);

    const openStyle = (id)=>{ setStyleId(id); setRoute('collection'); setFilter({type:'all',subtype:null}); setExpanded(new Set(['cards'])); setTemp('base'); window.scrollTo(0,0); };
    const toggleType = (id)=> setExpanded(prev=>{ const n=new Set(prev); n.has(id)?n.delete(id):n.add(id); return n; });
    const navDetail = (dir)=>{
      if(!detail) return;
      const i = filtered.findIndex(b=>b.id===detail.id);
      const ni = (i+dir+filtered.length)%filtered.length;
      setDetail(filtered[ni]);
    };

    return (
      <React.Fragment>
        {route==='home'
          ? <Home onOpen={openStyle}/>
          : <Collection
              s={s} blocks={filtered} filter={filter} onFilter={setFilter}
              expanded={expanded} onToggle={toggleType}
              onOpenDetail={setDetail}
              onSwitchStyle={setStyleId}
              onHome={()=>{ setRoute('home'); window.scrollTo(0,0); }}
              drawer={drawer} setDrawer={setDrawer}
              temp={temp} onCycleTemp={cycleTemp}/>}
        {detail && <Detail block={detail} blocks={filtered} s={s}
          onClose={()=>setDetail(null)} onNav={navDetail} onSwitchStyle={setStyleId}/>}
      </React.Fragment>
    );
  }

  ReactDOM.createRoot(document.getElementById('root')).render(<App/>);
})();
