/* ============================================================
   COLLECTION PAGE — one style universe.
   Redesigned: refined sidebar (counts, active states, identity
   header) + a real responsive grid (up to 4/line, large tiles,
   wide blocks span 2 columns). Blocks render live in the style.
   ============================================================ */
(function(){
  const { cx, Glyph, G, MenuIcon, STYLES, STYLE_ORDER, MENU } = window;
  /* Empire UI brand colors — the sidebar/chrome wears the library identity */
  const BRAND = '#8a7bff', BRAND2 = '#2dd4ff', BGRAD = 'linear-gradient(135deg,#7a5cff,#2dd4ff)';

  /* count blocks per type / subtype from the global catalog */
  function counts(){
    const byType={}, bySub={};
    (window.BLOCKS||[]).forEach(b=>{
      byType[b.type]=(byType[b.type]||0)+1;
      bySub[b.type+'/'+b.subtype]=(bySub[b.type+'/'+b.subtype]||0)+1;
    });
    return { byType, bySub };
  }

  const TEMPS = {
    base: { label:'Neutral', icon:'M12 3a9 9 0 100 18 9 9 0 000-18z', color:'#9aa0aa' },
    warm: { label:'Warm',    icon:'M12 17a5 5 0 100-10 5 5 0 000 10zM12 1v2M12 21v2M4.2 4.2l1.4 1.4M18.4 18.4l1.4 1.4M1 12h2M21 12h2M4.2 19.8l1.4-1.4M18.4 5.6l1.4-1.4', color:'#f59e0b' },
    cool: { label:'Cool',    icon:'M12 2v20M2 12h20M5 5l14 14M19 5L5 19', color:'#38bdf8' },
  };
  function Sidebar({ s, filter, onFilter, expanded, onToggle, onClose, temp, onCycleTemp, onSwitchStyle }){
    const { byType, bySub } = counts();
    const tm = TEMPS[temp||'base'] || TEMPS.base;
    const accent = BRAND;            // sidebar chrome uses the LIBRARY brand color
    const total = (window.BLOCKS||[]).length;
    return (
      <div className="flex flex-col h-full" style={{
        background:'linear-gradient(180deg, color-mix(in oklab,'+BRAND+' 13%, transparent), color-mix(in oklab,'+BRAND2+' 6%, transparent) 38%, transparent 70%)',
      }}>
        {/* library identity + ambiance temperature toggle (click to change) */}
        <div className="px-3 pt-3 pb-3" style={{borderBottom:'1px solid color-mix(in oklab,'+BRAND+' 22%, var(--chrome-line))'}}>
          <button onClick={onCycleTemp} title="Click to change the ambiance temperature"
            className="w-full flex items-center gap-2.5 rounded-xl px-2 py-2 transition text-left"
            style={{background:'rgba(255,255,255,.02)'}}
            onMouseEnter={e=>e.currentTarget.style.background='rgba(255,255,255,.06)'}
            onMouseLeave={e=>e.currentTarget.style.background='rgba(255,255,255,.02)'}>
            <div className="w-8 h-8 rounded-xl grid place-items-center shrink-0" style={{background:BGRAD,boxShadow:'0 4px 14px color-mix(in oklab,'+BRAND+' 45%, transparent)'}}>
              <span className="font-black text-[14px] text-white">E</span>
            </div>
            <div className="min-w-0 flex-1">
              <div className="text-[13px] font-bold leading-tight truncate">{s.name}</div>
              <div className="text-[11px] flex items-center gap-1.5" style={{color:'var(--chrome-sub)'}}>
                <span className="flex -space-x-1">{s.swatch.slice(0,3).map((c,i)=>(<span key={i} className="w-2.5 h-2.5 rounded-full" style={{background:c,border:'1.5px solid #0e0e13'}}/>))}</span>
                EmpireUI
              </div>
            </div>
            <span className="shrink-0 inline-flex items-center gap-1.5 px-2 py-1 rounded-full text-[11px] font-semibold"
              style={{background:tm.color+'22',color:tm.color,border:'1px solid '+tm.color+'55'}}>
              <Glyph d={tm.icon} size={13}/>{tm.label}
            </span>
          </button>
          <div className="text-[10px] mt-1 px-2" style={{color:'var(--chrome-sub)'}}>Ambiance — tap to warm / cool the palette</div>
        </div>

        <div className="flex-1 overflow-y-auto thin-scroll p-2.5">
          <div className="px-2 pt-1 pb-2 text-[10px] font-bold uppercase tracking-[0.14em]" style={{color:'var(--chrome-sub)'}}>Components</div>

          <button onClick={()=>{onFilter({type:'all',subtype:null}); onClose&&onClose();}}
            className="w-full flex items-center gap-2.5 px-3 py-2.5 rounded-xl text-sm font-semibold transition mb-1"
            style={ filter.type==='all'
              ? { background:'color-mix(in oklab,'+accent+' 14%, transparent)', color:'var(--chrome-text)', boxShadow:'inset 0 0 0 1px color-mix(in oklab,'+accent+' 30%, transparent)' }
              : { color:'var(--chrome-sub)' }}>
            <MenuIcon name="grid" size={16}/>
            <span className="flex-1 text-left">All components</span>
            <span className="text-[11px] font-mono px-1.5 py-0.5 rounded-md" style={{background:'#1c1c24',color:'var(--chrome-sub)'}}>{total}</span>
          </button>

          {MENU.map(t=>{
            const open = expanded.has(t.id);
            const activeType = filter.type===t.id;
            const n = byType[t.id]||0;
            return (
              <div key={t.id} className="mb-0.5">
                <button onClick={()=>onToggle(t.id)}
                  className="w-full flex items-center gap-2.5 px-3 py-2.5 rounded-xl text-sm font-medium transition"
                  style={ activeType
                    ? { background:'rgba(255,255,255,.05)', color:'var(--chrome-text)' }
                    : { color:'var(--chrome-sub)' }}
                  onMouseEnter={e=>{ if(!activeType) e.currentTarget.style.background='rgba(255,255,255,.03)'; }}
                  onMouseLeave={e=>{ if(!activeType) e.currentTarget.style.background='transparent'; }}>
                  <span style={{color:open?accent:'inherit',transition:'color .2s'}}><MenuIcon name={t.icon} size={17}/></span>
                  <span className="flex-1 text-left">{t.label}</span>
                  <span className="text-[10px] font-mono px-1.5 py-0.5 rounded-md mr-0.5" style={{background:'#1c1c24',color:'var(--chrome-sub)'}}>{n}</span>
                  <span className="transition-transform" style={{transform:open?'rotate(90deg)':'none',opacity:.5}}>
                    <Glyph d="M9 6l6 6-6 6" size={12}/></span>
                </button>
                <div className="overflow-hidden transition-all duration-300" style={{maxHeight:open?t.subs.length*38+8:0,opacity:open?1:0}}>
                  <div className="pl-3 py-1 ml-[1.35rem] flex flex-col gap-0.5" style={{borderLeft:'1px solid var(--chrome-line)'}}>
                    {t.subs.map(sub=>{
                      const on = filter.type===t.id && filter.subtype===sub.id;
                      const sn = bySub[t.id+'/'+sub.id]||0;
                      return (
                        <button key={sub.id} onClick={()=>{onFilter({type:t.id,subtype:sub.id}); onClose&&onClose();}}
                          className="text-left text-[13px] pl-3 pr-2 py-1.5 rounded-lg transition relative flex items-center"
                          style={ on ? { color:accent, fontWeight:600, background:'color-mix(in oklab,'+accent+' 10%, transparent)' } : { color:'var(--chrome-sub)' }}
                          onMouseEnter={e=>{ if(!on) e.currentTarget.style.background='rgba(255,255,255,.03)'; }}
                          onMouseLeave={e=>{ if(!on) e.currentTarget.style.background='transparent'; }}>
                          {on && <span className="absolute -left-[14px] top-1/2 w-2 h-2 rounded-full -translate-y-1/2" style={{background:accent,boxShadow:'0 0 8px '+accent}}/>}
                          <span className="flex-1">{sub.label}</span>
                          <span className="text-[10px] opacity-60">{sn}</span>
                        </button>);
                    })}
                  </div>
                </div>
              </div>
            );
          })}

        </div>
      </div>
    );
  }

  /* one component, framed in a window, sized by the grid cell */
  function Window({ block, s, onOpen }){
    const sub = (window.MENU.find(t=>t.id===block.type)?.subs.find(x=>x.id===block.subtype)?.label)||block.subtype;
    return (
      <div className={cx('win group/win cursor-pointer flex flex-col', block.w===2?'sm:col-span-2':'')}
        onClick={()=>onOpen(block)}>
        <div className="win-bar">
          <span className="win-dot" style={{background:'#ff5f57'}}/><span className="win-dot" style={{background:'#febc2e'}}/><span className="win-dot" style={{background:'#28c840'}}/>
          <span className="ml-2 text-[11px] truncate" style={{color:'var(--chrome-sub)',fontFamily:'Space Mono,monospace'}}>{block.id}.tsx</span>
          <span className="ml-auto text-[11px] flex items-center gap-1 opacity-0 group-hover/win:opacity-100 transition" style={{color:'var(--chrome-sub)'}}>
            open <Glyph d={G.arrow} size={12}/>
          </span>
        </div>
        <div className={cx('win-canvas',s.canvas)} style={{minHeight:block.w===2?320:300,padding:'28px 24px'}}>
          {s.id==='retro' && <div className="rf-sun" style={{top:'-40%',opacity:.6}}/>}
          {s.id==='motion' && <div className="mo-blob" style={{width:120,height:120,top:-30,right:-20,opacity:.4}}/>}
          <div className="relative w-full flex items-center justify-center">{block.Render(s)}</div>
        </div>
        <div className="flex items-center justify-between px-4 py-3" style={{background:'#16161d',borderTop:'1px solid var(--chrome-line)'}}>
          <span className="text-[13px] font-semibold" style={{color:'var(--chrome-text)'}}>{block.title}</span>
          <span className="text-[10px] px-2 py-0.5 rounded-full uppercase tracking-wider shrink-0" style={{background:'#23232c',color:'var(--chrome-sub)'}}>{sub}</span>
        </div>
      </div>
    );
  }

  /* RIGHT sidebar — switch the active style universe */
  function StylesPanel({ s, onSwitchStyle, onClose }){
    const styleIds = window.STYLE_ALL || STYLE_ORDER;
    const ref = React.useRef(null);
    React.useEffect(()=>{ if(ref.current) ref.current.scrollIntoView({block:'nearest'}); }, [s.id]);
    return (
      <div className="flex flex-col h-full">
        <div className="px-4 pt-4 pb-3 flex items-center justify-between" style={{borderBottom:'1px solid var(--chrome-line)'}}>
          <span className="text-[11px] font-bold uppercase tracking-[0.14em]" style={{color:'var(--chrome-text)'}}>Styles</span>
          <span className="text-[10px] font-mono px-1.5 py-0.5 rounded-md" style={{background:'#1c1c24',color:'var(--chrome-sub)'}}>{styleIds.length}</span>
        </div>
        <div className="flex-1 overflow-y-auto thin-scroll p-2.5">
          {styleIds.map(id=>{
            const st=STYLES[id]; if(!st) return null; const on=id===s.id;
            return (
              <button key={id} ref={on?ref:null} onClick={()=>{onSwitchStyle&&onSwitchStyle(id); onClose&&onClose();}}
                className="w-full flex items-center gap-2.5 px-3 py-2 rounded-lg text-[13px] transition text-left mb-0.5"
                style={ on
                  ? { background:'color-mix(in oklab,'+st.cls.accent+' 16%, transparent)', color:'var(--chrome-text)', fontWeight:600, boxShadow:'inset 0 0 0 1px color-mix(in oklab,'+st.cls.accent+' 38%, transparent)' }
                  : { color:'var(--chrome-sub)' }}
                onMouseEnter={e=>{ if(!on) e.currentTarget.style.background='rgba(255,255,255,.04)'; }}
                onMouseLeave={e=>{ if(!on) e.currentTarget.style.background='transparent'; }}>
                <span className="flex -space-x-1 shrink-0">{st.swatch.slice(0,3).map((c,i)=><span key={i} className="w-3 h-3 rounded-full" style={{background:c,border:'1.5px solid #0e0e13'}}/>)}</span>
                <span className="flex-1 truncate">{st.name}</span>
                {on && <Glyph d={G.check} size={13}/>}
              </button>);
          })}
        </div>
      </div>
    );
  }

  function Collection({ s, blocks, filter, onFilter, expanded, onToggle, onOpenDetail, onSwitchStyle, onHome, drawer, setDrawer, temp, onCycleTemp }){
    const typeLabel = filter.type==='all' ? 'All components'
      : MENU.find(t=>t.id===filter.type)?.label + (filter.subtype?' · '+MENU.find(t=>t.id===filter.type)?.subs.find(x=>x.id===filter.subtype)?.label:'');
    const tempClass = temp==='warm' ? 'temp-warm' : temp==='cool' ? 'temp-cool' : 'temp-base';
    return (
      <div className="min-h-screen anim-fadeIn">
        {/* top bar */}
        <header className="sticky top-0 z-30 backdrop-blur-xl" style={{background:'rgba(11,11,15,.82)',borderBottom:'1px solid var(--chrome-line)'}}>
          <div className="px-4 md:px-6 h-16 flex items-center gap-3">
            <button onClick={onHome} className="flex items-center gap-2 px-2 py-1.5 rounded-lg hover:bg-white/5 shrink-0">
              <Glyph d="M15 18l-6-6 6-6" size={18}/><span className="font-bold tracking-tight hidden sm:inline">Empire<span style={{color:'#7a8aff'}}>UI</span></span>
            </button>
            <button onClick={()=>setDrawer(true)} className="lg:hidden p-2 rounded-lg hover:bg-white/5"><Glyph d="M4 6h16M4 12h16M4 18h16" size={20}/></button>
            <div className="h-6 w-px hidden sm:block" style={{background:'var(--chrome-line)'}}/>
            {/* current style label (switcher moved to the left sidebar) */}
            <div className="flex items-center gap-2 min-w-0">
              <span className="flex -space-x-1 shrink-0">{s.swatch.slice(0,3).map((c,i)=><span key={i} className="w-3.5 h-3.5 rounded-full" style={{background:c,border:'1.5px solid #0b0b0f'}}/>)}</span>
              <span className="font-bold tracking-tight truncate">{s.name}</span>
              <span className="text-[11px] px-2 py-0.5 rounded-full shrink-0 hidden sm:inline" style={{background:'#1c1c24',color:'var(--chrome-sub)'}}>{blocks.length} blocks</span>
            </div>
            <button className="ml-auto shrink-0 px-4 py-2 rounded-lg text-sm font-semibold" style={{background:'#fff',color:'#111'}}>Get this style</button>
          </div>
        </header>

        <div className="flex">
          {/* LEFT sidebar — flush to the edge: components + ambiance */}
          <aside className="hidden lg:block w-[264px] shrink-0 sticky top-16 self-start h-[calc(100vh-4rem)]" style={{borderRight:'1px solid var(--chrome-line)'}}>
            <Sidebar s={s} filter={filter} onFilter={onFilter} expanded={expanded} onToggle={onToggle} temp={temp} onCycleTemp={onCycleTemp} onSwitchStyle={onSwitchStyle}/>
          </aside>

          {/* main */}
          <main className="flex-1 min-w-0 px-5 md:px-10 py-8">
            <div className="flex items-end justify-between gap-4 mb-7 flex-wrap">
              <div>
                <div className="flex items-center gap-2 text-xs mb-1.5" style={{color:'var(--chrome-sub)'}}>
                  <span className="flex -space-x-1">{s.swatch.slice(0,4).map((c,i)=><span key={i} className="w-3 h-3 rounded-full" style={{background:c,border:'1.5px solid #0b0b0f'}}/>)}</span>
                  {s.name} universe
                </div>
                <h1 className="text-[28px] font-black tracking-tight leading-none">{typeLabel}</h1>
                <p className="text-sm mt-1.5" style={{color:'var(--chrome-sub)'}}>{blocks.length} block{blocks.length!==1?'s':''} · rendered live</p>
              </div>
            </div>

            {blocks.length===0 ? (
              <div className="rounded-2xl p-14 text-center" style={{border:'1px dashed var(--chrome-line)',color:'var(--chrome-sub)'}}>No blocks in this sub-type yet.</div>
            ) : (
              <div key={s.id+filter.type+filter.subtype}
                className={cx('grid gap-6 anim-swap temp-shift', tempClass)}
                style={{gridTemplateColumns:'repeat(auto-fill, minmax(min(100%, 320px), 1fr))'}}>
                {blocks.map(b=><Window key={b.id} block={b} s={s} onOpen={onOpenDetail}/>)}
              </div>
            )}
          </main>

          {/* RIGHT sidebar — style switcher */}
          <aside className="hidden lg:block w-[244px] shrink-0 sticky top-16 self-start h-[calc(100vh-4rem)]" style={{borderLeft:'1px solid var(--chrome-line)'}}>
            <StylesPanel s={s} onSwitchStyle={onSwitchStyle}/>
          </aside>
        </div>

        {/* mobile drawer */}
        {drawer && (
          <div className="fixed inset-0 z-50 lg:hidden">
            <div className="absolute inset-0 anim-fadeIn" style={{background:'rgba(0,0,0,.6)'}} onClick={()=>setDrawer(false)}/>
            <div className="absolute left-0 top-0 bottom-0 w-[284px] anim-fadeIn" style={{background:'#0e0e13',borderRight:'1px solid var(--chrome-line)'}}>
              <div className="flex items-center justify-between p-4" style={{borderBottom:'1px solid var(--chrome-line)'}}>
                <span className="font-bold">Components</span>
                <button onClick={()=>setDrawer(false)} className="p-1.5 rounded-lg hover:bg-white/5"><Glyph d="M6 6l12 12M18 6L6 18" size={18}/></button>
              </div>
              <div className="h-[calc(100vh-3.5rem)]">
                <Sidebar s={s} filter={filter} onFilter={onFilter} expanded={expanded} onToggle={onToggle} onClose={()=>setDrawer(false)} temp={temp} onCycleTemp={onCycleTemp} onSwitchStyle={onSwitchStyle}/>
              </div>
            </div>
          </div>
        )}
      </div>
    );
  }
  window.Collection = Collection;
})();
