/* ============================================================
   HOMEPAGE — "Choose your style"
   A live museum: every one of the 40+ style cards renders in its
   own signature look, grouped into 6 families. Featured styles
   get a rich live-preview card + Explore; the rest are fully
   styled "Coming soon".
   ============================================================ */
(function(){
  const { cx, Glyph, G, STYLES, STYLE_ORDER, FAMILIES, TOTAL_STYLES } = window;
  const Bn='inline-flex items-center justify-center gap-2 cursor-pointer select-none whitespace-nowrap';
  const COPY={
    en:{featured:'★ FEATURED',live:'LIVE',month:'This month',action:'Action',blocks:'blocks',explore:'Explore',search:`Search ${TOTAL_STYLES} styles…`,tools:'Tools',templates:'Templates',blog:'Blog',pricing:'Pricing',docs:'Docs',signin:'Sign in',pro:'Get Pro',badgeA:'A component library organized by',badgeB:'style',badgeC:'not category',heroA:"Don’t pick a component.",heroB:'Pick a universe.',intro:`Empire UI is split by visual style — ${TOTAL_STYLES} of them, across 6 families. Every block inside a style already agrees with the others, so whatever you ship looks like one product, not a pile of parts.`,stats:['styles','families','blocks','live now'],requestTitle:"Don’t see your universe?",requestBody:'Every style here is one token object. New universes ship weekly — vote for what’s next.',request:'Request a style'},
    fr:{featured:'★ À LA UNE',live:'ACTIF',month:'Ce mois-ci',action:'Action',blocks:'blocs',explore:'Explorer',search:`Rechercher parmi ${TOTAL_STYLES} styles…`,tools:'Outils',templates:'Modèles',blog:'Blog',pricing:'Tarifs',docs:'Docs',signin:'Connexion',pro:'Passer Pro',badgeA:'Une bibliothèque de composants organisée par',badgeB:'style',badgeC:'et non par catégorie',heroA:'Ne choisissez pas un composant.',heroB:'Choisissez un univers.',intro:`Empire UI est organisée par style visuel — ${TOTAL_STYLES} univers répartis en 6 familles. Tous les blocs d’un même style parlent déjà le même langage, pour livrer un produit cohérent plutôt qu’un assemblage disparate.`,stats:['styles','familles','blocs','disponibles'],requestTitle:'Votre univers manque à l’appel ?',requestBody:'Chaque style repose sur un seul objet de tokens. De nouveaux univers arrivent chaque semaine — votez pour le prochain.',request:'Proposer un style'}
  };

  /* ---- FEATURED card: full live preview in its own CSS universe ---- */
  function FeaturedCard({ id, onOpen, delay, locale }){
    const s = STYLES[id];
    const t = COPY[locale]||COPY.en;
    const head = (extra='')=>cx(s.cls.display,s.cls.glow,extra);
    return (
      <div onClick={()=>onOpen(id)} role="button" tabIndex={0}
        onKeyDown={e=>{ if(e.key==='Enter'||e.key===' ')onOpen(id); }}
        className={cx(s.canvas,'gcard group relative text-left rounded-3xl overflow-hidden anim-fadeUp cursor-pointer')}
        style={{ animationDelay:`${delay}ms`, minHeight:360, border:'1px solid rgba(255,255,255,.1)', gridColumn:'span 1' }}>
        {id==='retro' && <div className="rf-sun"/>}
        {id==='motion' && <>
          <div className="mo-blob" style={{width:140,height:140,top:-30,right:-20}}/>
          <div className="mo-blob" style={{width:90,height:90,bottom:20,left:-20,animationDelay:'-4s'}}/>
        </>}
        <div className="relative p-6 flex flex-col h-full" style={{minHeight:360}}>
          <div className="flex items-center justify-between">
            <span className={cx(s.cls.chip,'px-2.5 py-1 text-[10px] font-bold tracking-wider')}>{t.featured}</span>
          </div>
          <div className="flex-1 flex flex-col items-center justify-center py-4">
            <div className={cx(s.cls.surface,'w-full max-w-[230px] p-4')}>
              <div className="flex items-center justify-between">
                <span className={cx('text-xs',s.cls.sub)}>{t.month}</span>
                <span className={cx(s.cls.chip,'px-2 py-0.5 text-[10px] font-bold')}>+12%</span>
              </div>
              <div className={head('text-2xl font-extrabold mt-1')}>$48.2k</div>
              <div className="flex gap-2 mt-3">
                <button className={cx(Bn,s.cls.btnPrimary,'px-3 py-1.5 text-xs flex-1')}>{t.action}</button>
                <button className={cx(Bn,s.cls.btn,'px-3 py-1.5 text-xs')}>···</button>
              </div>
            </div>
          </div>
          <div className="relative">
            <div className="flex items-end justify-between gap-3">
              <div>
                <div className={head('text-xl font-extrabold leading-tight')}>{s.name}</div>
                <div className={cx('text-[13px] mt-0.5',s.cls.sub)}>{s.tagline}</div>
              </div>
              <div className={cx('text-right text-xs shrink-0',s.cls.muted)}>{s.count}<br/>{t.blocks}</div>
            </div>
            <div className={cx('mt-3 flex items-center gap-2 text-sm font-semibold transition-transform group-hover:translate-x-1',s.cls.glow)} style={{color:s.cls.accent}}>
              {t.explore} <Glyph d={G.arrow} size={16}/>
            </div>
          </div>
        </div>
      </div>
    );
  }

  /* ---- GENERIC card: token-driven, renders in its own look ---- */
  function GenericCard({ st, delay, onOpen, locale }){
    const t = st.t;
    const copy = COPY[locale]||COPY.en;
    const isBlob = typeof t.radius==='string' && t.radius.includes('/');
    const isPill = String(t.radius).trim()==='999px';
    const rSurf = isBlob ? '28px' : (isPill ? '24px' : t.radius); // blob->soft round, cap pill (no ovals)
    const rCtrl = isBlob ? '999px' : t.radius;           // soft pill for controls on blob styles
    const btnStyle = t.btn || { background:t.accent, color:t.onAccent, borderRadius:rCtrl, border:'none', fontWeight:700 };
    return (
      <div onClick={()=>onOpen&&onOpen(st.id)} role="button" tabIndex={0}
        onKeyDown={e=>{ if((e.key==='Enter'||e.key===' ')&&onOpen)onOpen(st.id); }}
        className="gcard relative rounded-3xl overflow-hidden anim-fadeUp cursor-pointer"
        style={{ background:t.bg, fontFamily:t.font, minHeight:360, color:t.text,
          border:'1px solid rgba(255,255,255,.07)', '--sig':t.accent, animationDelay:`${delay}ms` }}>
        <div className={cx('sig','sig-'+t.sig)}/>
        <div className="relative p-6 flex flex-col h-full" style={{minHeight:360}}>
          <div className="flex items-center justify-between">
            <span className="px-2.5 py-1 text-[10px] font-bold tracking-wider rounded-full inline-flex items-center gap-1.5"
              style={{ background:t.accent+'22', color:t.accent, border:'1px solid '+t.accent+'55' }}>
              <span className="w-1.5 h-1.5 rounded-full" style={{background:t.accent}}/> {copy.live}
            </span>
          </div>

          {/* in-style mini preview */}
          <div className="flex-1 flex items-center justify-center py-4">
            <div className="w-full max-w-[230px] p-4" style={{ background:t.surface, color:t.text,
              borderRadius:rSurf, border:t.border, boxShadow:t.shadow }}>
              <div className="flex items-center justify-between" style={{fontSize:11}}>
                <span style={{color:t.sub}}>{copy.month}</span>
                <span className="px-2 py-0.5 font-bold" style={{ background:t.accent, color:t.onAccent, borderRadius:'999px', fontSize:10 }}>+12%</span>
              </div>
              <div className="font-extrabold mt-1" style={{ fontSize:t.font.includes('Press Start')?16:26, lineHeight:1.1 }}>$48.2k</div>
              <div className="flex gap-2 mt-3">
                <button className="px-3 py-1.5 text-xs flex-1" style={btnStyle}>{copy.action}</button>
                <button className="px-3 py-1.5 text-xs" style={{ background:'transparent', color:t.text, border:t.border, borderRadius:rCtrl }}>···</button>
              </div>
            </div>
          </div>

          <div>
            <div className="flex items-end justify-between gap-3">
              <div className="min-w-0">
                <div className="font-extrabold leading-tight truncate" style={{ fontSize:t.font.includes('Press Start')?14:19 }}>{st.name}</div>
                <div className="mt-1" style={{ fontSize:13, color:t.sub, lineHeight:1.3 }}>{st.vibe}</div>
              </div>
              <div className="text-right shrink-0" style={{ fontSize:11, color:t.sub }}>{st.count}<br/>{copy.blocks}</div>
            </div>
            <div className="mt-3 flex items-center gap-1.5 text-sm font-semibold transition-transform group-hover:translate-x-1" style={{color:t.accent}}>
              {copy.explore} <span>→</span>
            </div>
          </div>
        </div>
      </div>
    );
  }

  function Home({ onOpen, locale='en', languageControl }){
    const [q,setQ]=React.useState('');
    const [searchFocused,setSearchFocused]=React.useState(false);
    const t=COPY[locale]||COPY.en;
    let delayCounter = 0;
    return (
      <div className="min-h-screen">
        {/* global nav */}
        <nav className="sticky top-0 z-30 backdrop-blur-xl" style={{ background:'rgba(11,11,15,.72)', borderBottom:'1px solid var(--chrome-line)' }}>
          <div className="max-w-[1280px] mx-auto px-6 h-16 flex items-center gap-4">
            <div className="flex items-center gap-2.5">
              <div className="w-7 h-7 rounded-lg grid place-items-center" style={{background:'linear-gradient(135deg,#7a5cff,#2dd4ff)'}}>
                <span className="font-black text-[13px]">E</span></div>
              <span className="font-bold tracking-tight text-[15px]">Empire<span style={{color:'#7a8aff'}}>UI</span></span>
            </div>
            {/* Search bar with glow */}
            <div className="ml-4 hidden md:flex flex-1 max-w-[360px]" style={{position:'relative'}}>
              {/* glow */}
              <div style={{position:'absolute',inset:-1,borderRadius:999,background:'linear-gradient(135deg,#7c4dff,#c084fc,#38bdf8)',opacity:searchFocused?1:0,filter:'blur(8px)',transition:'opacity .3s',pointerEvents:'none',zIndex:0}}/>
              {/* border ring */}
              <div style={{position:'absolute',inset:-1,borderRadius:999,background:searchFocused?'linear-gradient(135deg,#7c4dff,#c084fc,#38bdf8)':'linear-gradient(135deg,rgba(255,255,255,.13),rgba(255,255,255,.05))',transition:'background .3s',pointerEvents:'none',zIndex:1}}/>
              {/* inner */}
              <div className="flex items-center gap-2 px-4 h-10 w-full" style={{position:'relative',zIndex:2,background:'rgba(11,11,15,.9)',backdropFilter:'blur(12px)',borderRadius:999,margin:1}}>
                <span style={{color:searchFocused?'#c4b5fd':'var(--chrome-sub)',transition:'color .3s',flexShrink:0}}><Glyph d={G.search} size={15}/></span>
                <input value={q} onChange={e=>setQ(e.target.value)}
                  onFocus={()=>setSearchFocused(true)} onBlur={()=>setSearchFocused(false)}
                  placeholder={t.search}
                  className="bg-transparent outline-none text-sm w-full" style={{color:'var(--chrome-text)',border:'none'}}/>
                <kbd className="text-[10px] px-2 py-0.5 rounded-full shrink-0" style={{background:'rgba(255,255,255,.07)',color:'var(--chrome-sub)',border:'1px solid rgba(255,255,255,.1)'}}>⌘K</kbd>
              </div>
            </div>
            <div className="ml-auto flex items-center gap-1">
              <a href="/tools" className="text-sm px-3 py-2 rounded-lg hover:bg-white/5 hidden md:inline-block" style={{color:'var(--chrome-sub)',textDecoration:'none'}}>{t.tools}</a>
              <a href="/templates" className="text-sm px-3 py-2 rounded-lg hover:bg-white/5 hidden lg:inline-block" style={{color:'var(--chrome-sub)',textDecoration:'none'}}>{t.templates}</a>
              <a href="/blog" className="text-sm px-3 py-2 rounded-lg hover:bg-white/5 hidden lg:inline-block" style={{color:'var(--chrome-sub)',textDecoration:'none'}}>{t.blog}</a>
              <a href="/mcp" className="text-sm px-3 py-2 rounded-lg hover:bg-white/5 hidden lg:inline-block" style={{color:'var(--chrome-sub)',textDecoration:'none'}}>MCP</a>
              <a href="/pricing" className="text-sm px-3 py-2 rounded-lg hover:bg-white/5 hidden sm:inline-block" style={{color:'var(--chrome-sub)',textDecoration:'none'}}>{t.pricing}</a>
              <a href="/docs" className="text-sm px-3 py-2 rounded-lg hover:bg-white/5 hidden sm:inline-block" style={{color:'var(--chrome-sub)',textDecoration:'none'}}>{t.docs}</a>
              <a href="/login" className="text-sm px-3 py-2 rounded-lg hidden sm:inline-block" style={{color:'var(--chrome-sub)',textDecoration:'none'}}>{t.signin}</a>
              {languageControl}
              <a href="/pricing" className="text-sm px-4 py-2 rounded-lg font-semibold ml-1" style={{background:'#fff',color:'#111',textDecoration:'none'}}>{t.pro}</a>
            </div>
          </div>
        </nav>

        {/* hero */}
        <header className="max-w-[1280px] mx-auto px-6 pt-20 pb-10 text-center">
          <div className="inline-flex items-center gap-2 px-3 py-1.5 rounded-full text-xs mb-6 anim-fadeUp"
            style={{background:'#15151b',border:'1px solid var(--chrome-line)',color:'var(--chrome-sub)'}}>
            <span className="w-1.5 h-1.5 rounded-full" style={{background:'#36d399'}}/> {t.badgeA} <b style={{color:'var(--chrome-text)'}}>{t.badgeB}</b>, {t.badgeC}
          </div>
          <h1 className="anim-fadeUp text-[clamp(40px,7vw,82px)] font-black leading-[0.95] tracking-tight" style={{animationDelay:'60ms'}}>
            {t.heroA}<br/>
            <span style={{background:'linear-gradient(120deg,#a78bfa,#2dd4ff,#ff6fd8)',WebkitBackgroundClip:'text',backgroundClip:'text',color:'transparent'}}>{t.heroB}</span>
          </h1>
          <p className="anim-fadeUp max-w-[580px] mx-auto mt-6 text-[17px] leading-relaxed" style={{animationDelay:'120ms',color:'var(--chrome-sub)'}}>
            {t.intro}
          </p>
          <div className="anim-fadeUp flex items-center justify-center gap-8 mt-8" style={{animationDelay:'160ms'}}>
            {[[TOTAL_STYLES,t.stats[0]],['6',t.stats[1]],['381',t.stats[2]],[TOTAL_STYLES,t.stats[3]]].map(([n,l])=>(
              <div key={l} className="text-center">
                <div className="text-2xl font-black">{n}</div>
                <div className="text-xs uppercase tracking-wider" style={{color:'var(--chrome-sub)'}}>{l}</div>
              </div>))}
          </div>
        </header>

        {/* families — every style live, featured ones sit in their own family */}
        <section className="max-w-[1280px] mx-auto px-6 pb-24">
          {FAMILIES.map((fam,fi)=>(
            <div key={fam.name} className="mt-12 first:mt-2">
              <div className="flex items-baseline gap-3 mb-5 pb-3" style={{borderBottom:'1px solid var(--chrome-line)'}}>
                <span className="text-xs font-mono px-2 py-1 rounded-md" style={{background:'#16161d',color:'var(--chrome-sub)'}}>{String.fromCharCode(65+fi)}</span>
                <h2 className="text-lg font-bold tracking-tight">{fam.name}</h2>
                <span className="text-sm hidden sm:inline" style={{color:'var(--chrome-sub)'}}>{fam.blurb}</span>
                <span className="ml-auto text-sm shrink-0" style={{color:'var(--chrome-sub)'}}>{fam.items.length}</span>
              </div>
              <div className="grid gap-5" style={{gridTemplateColumns:'repeat(auto-fill,minmax(252px,1fr))'}}>
                {fam.items.map(st=>{
                  const d = (delayCounter++ % 8) * 50;
                  return st.featured
                    ? <FeaturedCard key={st.id} id={st.id} onOpen={onOpen} delay={d} locale={locale}/>
                    : <GenericCard key={st.name} st={st} delay={d} onOpen={onOpen} locale={locale}/>;
                })}
              </div>
            </div>
          ))}

          {/* request CTA */}
          <div className="mt-12 rounded-3xl p-6 flex items-center gap-4 flex-wrap" style={{background:'#121218',border:'1px dashed var(--chrome-line)'}}>
            <div className="w-12 h-12 rounded-2xl grid place-items-center" style={{background:'#1b1b22',color:'var(--chrome-sub)'}}><Glyph d={G.plus} size={22}/></div>
            <div className="flex-1 min-w-[200px]">
              <div className="font-bold">{t.requestTitle}</div>
              <div className="text-sm" style={{color:'var(--chrome-sub)'}}>{t.requestBody}</div>
            </div>
            <button className="px-4 py-2.5 rounded-xl text-sm font-semibold" style={{background:'#1b1b22',color:'var(--chrome-text)',border:'1px solid var(--chrome-line)'}}>{t.request}</button>
          </div>
        </section>
      </div>
    );
  }
  window.Home = Home;
})();
