// components.jsx — shared UI for Gamingo Labs
const { useState, useEffect, useRef } = React;

// ── Icons ─────────────────────────────────────────────────────────────────────
const Ic = {
  Menu:  (p) => <svg {...p} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"><path d="M4 7h16M4 12h16M4 17h16"/></svg>,
  X:     (p) => <svg {...p} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"><path d="M6 6l12 12M18 6L6 18"/></svg>,
  Play:  (p) => <svg {...p} viewBox="0 0 24 24" fill="currentColor"><path d="M5 3l14 9-14 9z"/></svg>,
  Star:  (p) => <svg {...p} viewBox="0 0 24 24" fill="currentColor"><path d="M12 2l3 7 7 .6-5.3 4.7 1.6 7L12 17.7 5.7 21.3l1.6-7L2 9.6 9 9z"/></svg>,
  Arrow: (p) => <svg {...p} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14M13 5l7 7-7 7"/></svg>,
  Mail:  (p) => <svg {...p} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><rect x="2" y="4" width="20" height="16" rx="2"/><path d="M2 7l10 7 10-7"/></svg>,
  Chev:  (p) => <svg {...p} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round"><path d="M6 9l6 6 6-6"/></svg>,
};

// ── Star row ──────────────────────────────────────────────────────────────────
function Stars({ v = 0, size = 13 }) {
  const n = Math.round(v);
  return (
    <span style={{ display: 'inline-flex', gap: 2 }}>
      {[1,2,3,4,5].map(i => <Ic.Star key={i} width={size} height={size} style={{ color: i <= n ? 'var(--gl-yellow)' : 'var(--gl-muted)' }} />)}
    </span>
  );
}

// ── Game Card ─────────────────────────────────────────────────────────────────
function GameCard({ game, badge, goto }) {
  const handleClick = () => {
    if (goto) goto('game', { id: game.id });
    else window.open(game.playStoreUrl, '_blank');
  };
  return (
    <div className="gl-card" onClick={handleClick}
      style={{ cursor: 'pointer', overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
      {/* art */}
      <div style={{ position: 'relative', background: 'var(--gl-surface2)', height: 176, display: 'flex', alignItems: 'center', justifyContent: 'center', overflow: 'hidden', flexShrink: 0 }}>
        <div style={{ position: 'absolute', inset: 0, backgroundImage: 'repeating-linear-gradient(45deg,rgba(0,229,160,.024) 0,rgba(0,229,160,.024) 1px,transparent 0,transparent 50%)', backgroundSize: '14px 14px' }} />
        <div style={{ position: 'absolute', inset: 0, background: 'radial-gradient(ellipse at 50% -20%, rgba(0,229,160,.09), transparent 70%)' }} />
        <img src={game.icon} alt={game.title} loading="lazy" width={84} height={84}
          style={{ borderRadius: 18, boxShadow: '0 8px 28px rgba(0,0,0,.55)', position: 'relative', zIndex: 1 }}
          onError={e => { e.target.style.display = 'none'; }} />
        {badge && game.featured && <span className="gl-badge gl-badge-feat" style={{ position: 'absolute', top: 11, right: 11 }}>Featured</span>}
      </div>
      {/* body */}
      <div style={{ padding: '16px 18px 18px', flex: 1, display: 'flex', flexDirection: 'column', gap: 8 }}>
        <span style={{ fontSize: 10, fontWeight: 700, letterSpacing: '.12em', textTransform: 'uppercase', color: 'var(--gl-accent)', background: 'var(--gl-dim)', padding: '3px 10px', borderRadius: 999, width: 'fit-content' }}>{game.genre}</span>
        <div style={{ fontFamily: 'var(--gl-fd)', fontSize: 17, letterSpacing: '.03em', lineHeight: 1.15 }}>{game.title}</div>
        <p style={{ fontSize: 14, color: 'var(--gl-ink2)', lineHeight: 1.55, flex: 1 }}>{game.description}</p>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 4 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 5, fontSize: 12 }}>
            <Stars v={game.rating} size={12} />
            <span style={{ color: 'var(--gl-ink2)' }}>{game.rating}</span>
            <span style={{ color: 'var(--gl-muted)' }}>({game.downloads})</span>
          </div>
          <a href={game.playStoreUrl} target="_blank" rel="noreferrer"
            className="gl-btn gl-btn-sm gl-btn-outline"
            style={{ padding: '5px 13px', fontSize: 11 }}
            onClick={e => e.stopPropagation()}>
            <Ic.Play width={10} height={10} /> Play
          </a>
        </div>
      </div>
    </div>
  );
}

// ── Blog Card ─────────────────────────────────────────────────────────────────
function BlogCard({ post, onClick }) {
  return (
    <div className="gl-card" onClick={onClick} style={{ cursor: 'pointer', overflow: 'hidden' }}>
      <div style={{ height: 144, background: 'var(--gl-surface2)', display: 'flex', alignItems: 'center', justifyContent: 'center', overflow: 'hidden', position: 'relative', flexShrink: 0 }}>
        <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(135deg, var(--gl-surface2) 0%, var(--gl-bg) 100%)' }} />
        {post.image && <img src={post.image} alt="" loading="lazy" width={52} height={52} style={{ borderRadius: 10, opacity: .75, position: 'relative', zIndex: 1 }} onError={e => e.target.style.display='none'} />}
      </div>
      <div style={{ padding: '15px 17px 18px' }}>
        <span style={{ fontSize: 10, fontWeight: 700, letterSpacing: '.12em', textTransform: 'uppercase', color: 'var(--gl-accent)', background: 'var(--gl-dim)', padding: '3px 10px', borderRadius: 999, display: 'inline-block', marginBottom: 10 }}>{post.category}</span>
        <div style={{ fontFamily: 'var(--gl-fd)', fontSize: 16, letterSpacing: '.02em', marginBottom: 7, lineHeight: 1.2 }}>{post.title}</div>
        <p style={{ fontSize: 14, color: 'var(--gl-ink2)', lineHeight: 1.6, marginBottom: 12 }}>{post.excerpt}</p>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', fontSize: 12, color: 'var(--gl-muted)' }}>
          <span>{glDate(post.published_at || post.date)}</span>
          <span style={{ color: 'var(--gl-accent)', fontWeight: 600 }}>Read →</span>
        </div>
      </div>
    </div>
  );
}

// ── Service Card ──────────────────────────────────────────────────────────────
function ServiceCard({ s }) {
  const [hov, setHov] = useState(false);
  return (
    <div className="gl-card" style={{ padding: 26, position: 'relative', overflow: 'hidden' }}
      onMouseEnter={() => setHov(true)} onMouseLeave={() => setHov(false)}>
      <div style={{ position: 'absolute', top: 0, left: 0, right: 0, height: 2, background: 'linear-gradient(90deg, transparent, var(--gl-accent), transparent)', opacity: hov ? 1 : 0, transition: 'opacity .25s' }} />
      <div style={{ fontSize: '1.9rem', marginBottom: 13 }}>{s.icon}</div>
      <div style={{ fontWeight: 700, fontSize: 15, marginBottom: 9 }}>{s.title}</div>
      <p style={{ fontSize: 15, color: 'var(--gl-ink2)', lineHeight: 1.7 }}>{s.description}</p>
    </div>
  );
}

// ── Eyebrow + Title block ─────────────────────────────────────────────────────
function Eyebrow({ text }) {
  return <div className="gl-eye">{text}</div>;
}
function SHead({ eye, title, sub, accent, center }) {
  const parts = accent ? title.split(new RegExp(`(${accent})`, 'i')) : [title];
  return (
    <div style={center ? { textAlign: 'center' } : {}}>
      <Eyebrow text={eye} />
      <h2 style={{ marginBottom: 12 }}>
        {parts.map((p, i) =>
          p.toLowerCase() === (accent || '').toLowerCase()
            ? <span key={i} style={{ color: 'var(--gl-accent)' }}>{p}</span>
            : p
        )}
      </h2>
      {sub && <p style={{ color: 'var(--gl-ink2)', maxWidth: center ? 560 : 540, margin: center ? '0 auto 44px' : '0 0 44px', lineHeight: 1.75, fontWeight: 300 }}>{sub}</p>}
    </div>
  );
}

// ── Toast ─────────────────────────────────────────────────────────────────────
function Toast({ msg, clear }) {
  useEffect(() => {
    if (!msg) return;
    const t = setTimeout(clear, 3000);
    return () => clearTimeout(t);
  }, [msg]);
  if (!msg) return null;
  return (
    <div className="gl-toast-wrap" style={{
      position: 'fixed', bottom: 28, left: '50%', zIndex: 600,
      transform: 'translateX(-50%)',
      background: 'var(--gl-surface2)', color: 'var(--gl-ink)',
      padding: '13px 22px', borderRadius: 999,
      border: '1px solid var(--gl-lineA)',
      boxShadow: '0 8px 32px rgba(0,0,0,.55)',
      fontWeight: 600, fontSize: 14, display: 'flex', alignItems: 'center', gap: 10,
    }}>
      <span style={{ color: 'var(--gl-accent)' }}>▶</span> {msg}
    </div>
  );
}

// ── Header ────────────────────────────────────────────────────────────────────
function Header({ page, goto }) {
  const [scrolled, setScrolled] = useState(false);
  const [mob, setMob] = useState(false);
  useEffect(() => {
    const fn = () => setScrolled(window.scrollY > 20);
    window.addEventListener('scroll', fn, { passive: true });
    return () => window.removeEventListener('scroll', fn);
  }, []);

  const LINKS = [
    { id: 'home',     label: 'Home' },
    { id: 'games',    label: 'Games' },
    { id: 'about',    label: 'About' },
    { id: 'services', label: 'Services' },
    { id: 'blog',     label: 'Blog' },
    { id: 'videos',   label: 'Videos' },
    { id: 'players',  label: 'Player Hub' },
    { id: 'press',    label: 'Press Kit' },
  ];

  const navLink = (id, label) => (
    <button key={id} onClick={() => { goto(id); setMob(false); }}
      style={{
        padding: '7px 12px', fontSize: 14, fontWeight: 600, letterSpacing: '.03em', borderRadius: 8,
        color: page === id ? 'var(--gl-accent)' : 'var(--gl-ink2)',
        background: page === id ? 'var(--gl-dim)' : 'transparent',
        border: 'none', cursor: 'pointer', transition: 'all .15s',
        textTransform: 'none',
      }}>
      {label}
    </button>
  );

  return (
    <header style={{
      position: 'fixed', top: 0, left: 0, right: 0, zIndex: 500,
      background: scrolled ? 'rgba(7,9,13,.95)' : 'rgba(7,9,13,.72)',
      backdropFilter: 'blur(22px)',
      borderBottom: `1px solid ${scrolled ? 'var(--gl-lineA)' : 'var(--gl-line)'}`,
      transition: 'background .3s, border-color .3s',
    }}>
      <div style={{ maxWidth: 1380, margin: '0 auto', padding: '0 24px', height: 66, display: 'flex', alignItems: 'center', gap: 12 }}>
        {/* Logo */}
        <button onClick={() => goto('home')} style={{
          fontFamily: 'var(--gl-fd)', fontSize: 21, letterSpacing: '.06em', flexShrink: 0,
          border: 'none', background: 'none', cursor: 'pointer', color: 'var(--gl-ink)',
          display: 'flex', alignItems: 'center', gap: 0,
        }}>
          GAMINGO<span style={{ color: 'var(--gl-accent)' }}>LABS</span>
        </button>

        {/* Desktop nav */}
        <nav className="gl-hide-mob" style={{ display: 'flex', gap: 2, marginLeft: 16, flex: 1 }}>
          {LINKS.map(l => navLink(l.id, l.label))}
        </nav>

        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginLeft: 'auto' }}>
          <button onClick={() => goto('contact')} className="gl-btn gl-btn-primary gl-hide-mob" style={{ padding: '9px 22px', fontSize: 12 }}>
            Contact Us
          </button>
          <button className="gl-btn gl-btn-ghost gl-show-mob" onClick={() => setMob(!mob)} style={{ padding: 8 }}>
            {mob ? <Ic.X width={20} height={20} /> : <Ic.Menu width={20} height={20} />}
          </button>
        </div>
      </div>

      {/* Mobile menu */}
      {mob && (
        <div className="gl-show-mob" style={{ borderTop: '1px solid var(--gl-line)', background: 'rgba(7,9,13,.97)', padding: '14px 20px 20px', display: 'flex', flexDirection: 'column', gap: 4 }}>
          {LINKS.map(l => navLink(l.id, l.label))}
          <button onClick={() => { goto('contact'); setMob(false); }}
            className="gl-btn gl-btn-primary" style={{ marginTop: 8, width: '100%' }}>
            Contact Us
          </button>
        </div>
      )}
    </header>
  );
}

// ── Footer ────────────────────────────────────────────────────────────────────
function Footer({ data, goto }) {
  const studio = data?.studio || GL_DATA.studio;
  const games = data?.games || GL_DATA.games;
  const year = new Date().getFullYear();
  const [email, setEmail] = useState('');
  const [done, setDone] = useState(false);

  const subscribe = async () => {
    if (!email.includes('@')) return;
    try {
      const r = await fetch('/api/newsletter.php?action=subscribe', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email }) });
      const j = await r.json();
      if (j.success || j.ok) { setDone(true); return; }
    } catch {}
    setDone(true); // graceful fallback
  };

  const Col = ({ title, links }) => (
    <div>
      <div style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '.14em', marginBottom: 16, opacity: .4, fontWeight: 700 }}>{title}</div>
      <ul style={{ listStyle: 'none', display: 'flex', flexDirection: 'column', gap: 11 }}>
        {links.map(l => (
          <li key={l.label}>
            {l.href
              ? <a href={l.href} target={l.ext ? '_blank' : undefined} rel={l.ext ? 'noreferrer' : undefined} style={{ fontSize: 15, opacity: .7, color: 'inherit', transition: 'opacity .15s' }} onMouseOver={e => e.target.style.opacity=1} onMouseOut={e => e.target.style.opacity=.7}>{l.label}</a>
              : <button onClick={l.fn} style={{ fontSize: 15, opacity: .7, color: 'inherit', background: 'none', border: 'none', cursor: 'pointer', padding: 0, transition: 'opacity .15s' }} onMouseOver={e => e.target.style.opacity=1} onMouseOut={e => e.target.style.opacity=.7}>{l.label}</button>
            }
          </li>
        ))}
      </ul>
    </div>
  );

  return (
    <footer style={{ background: 'var(--gl-surface)', borderTop: '1px solid var(--gl-line)', marginTop: 80 }}>
      <div style={{ height: 2, background: 'linear-gradient(90deg, var(--gl-accent) 0%, var(--gl-blue) 50%, var(--gl-purple) 100%)' }} />
      <div className="gl-footer" style={{ maxWidth: 1380, margin: '0 auto', padding: '52px 24px 32px' }}>
        {/* Brand */}
        <div>
          <button onClick={() => goto('home')} style={{ fontFamily: 'var(--gl-fd)', fontSize: 24, letterSpacing: '.06em', marginBottom: 14, display: 'block', color: 'var(--gl-ink)', background: 'none', border: 'none', cursor: 'pointer', padding: 0 }}>
            GAMINGO<span style={{ color: 'var(--gl-accent)' }}>LABS</span>
          </button>
          <p style={{ opacity: .6, maxWidth: 290, fontSize: 15, lineHeight: 1.65 }}>{studio.footerDesc}</p>
          <div style={{ marginTop: 20 }}>
            <div style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '.1em', opacity: .4, marginBottom: 10 }}>Stay in the loop</div>
            {done ? (
              <span style={{ fontSize: 14, color: 'var(--gl-accent)', fontWeight: 600 }}>▶ You're in!</span>
            ) : (
              <div style={{ display: 'flex', gap: 8 }}>
                <input value={email} onChange={e => setEmail(e.target.value)} onKeyDown={e => e.key === 'Enter' && subscribe()}
                  placeholder="your@email.com" className="gl-input"
                  style={{ background: 'rgba(255,255,255,.06)', border: '1px solid rgba(255,255,255,.1)', color: '#fff', flex: 1 }} />
                <button className="gl-btn gl-btn-primary" onClick={subscribe} style={{ flexShrink: 0, boxShadow: 'none', padding: '10px 18px' }}>Join</button>
              </div>
            )}
          </div>
          <div style={{ display: 'flex', gap: 10, marginTop: 18 }}>
            {studio.googlePlayDev && <a href={studio.googlePlayDev} target="_blank" rel="noreferrer" style={{ width: 36, height: 36, borderRadius: 9, border: '1px solid rgba(255,255,255,.12)', display: 'grid', placeItems: 'center', fontSize: 14, transition: 'border-color .18s' }} onMouseOver={e => e.currentTarget.style.borderColor='var(--gl-accent)'} onMouseOut={e => e.currentTarget.style.borderColor='rgba(255,255,255,.12)'}>▶</a>}
            {studio.instagram    && <a href={studio.instagram}    target="_blank" rel="noreferrer" style={{ width: 36, height: 36, borderRadius: 9, border: '1px solid rgba(255,255,255,.12)', display: 'grid', placeItems: 'center', fontSize: 14, transition: 'border-color .18s' }} onMouseOver={e => e.currentTarget.style.borderColor='var(--gl-accent)'} onMouseOut={e => e.currentTarget.style.borderColor='rgba(255,255,255,.12)'}>📷</a>}
          </div>
        </div>
        <Col title="Studio" links={[
          { label: 'Home',      fn: () => goto('home') },
          { label: 'About',     fn: () => goto('about') },
          { label: 'Services',  fn: () => goto('services') },
          { label: 'Blog',      fn: () => goto('blog') },
          { label: 'Videos',    fn: () => goto('videos') },
          { label: 'Press Kit', fn: () => goto('press') },
        ]} />
        <Col title="Games" links={games.map(g => ({ label: g.title.split('–')[0].trim(), href: g.playStoreUrl, ext: true }))} />
        <Col title="Contact" links={[
          studio.email        && { label: studio.email,       href: 'mailto:' + studio.email },
          studio.googlePlayDev && { label: 'Google Play',     href: studio.googlePlayDev, ext: true },
          { label: 'Privacy Policy', href: '/privacy-policy/' },
          { label: 'Contact Us',     fn: () => goto('contact') },
        ].filter(Boolean)} />
      </div>
      <div style={{ borderTop: '1px solid rgba(255,255,255,.05)', padding: '14px 24px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 8, maxWidth: 1380, margin: '0 auto', fontSize: 12, opacity: .35 }}>
        <span>© {studio.founded || 2020}–{year} {studio.name}. All rights reserved.</span>
        <span>Made with 🎮</span>
      </div>
    </footer>
  );
}

// ── Marquee ───────────────────────────────────────────────────────────────────
function Marquee() {
  const items = ['Mobile Gaming','Google Play','Carrom City','Pool City','Screwdle','Puzzle Games','Board Games','Sports Games','Online Multiplayer','Indie Dev','Game Publishing','Gamingo Labs'];
  const all = [...items, ...items];
  return (
    <div className="gl-mq">
      <div className="gl-mq-track">
        {all.map((it, i) => <span key={i} className="gl-mq-item">{it} <span className="gl-mq-dot">▶</span></span>)}
      </div>
    </div>
  );
}

// ── Page progress bar ─────────────────────────────────────────────────────────
function ProgressBar() {
  const [w, setW] = useState(0);
  useEffect(() => {
    setW(20);
    const t1 = setTimeout(() => setW(70), 200);
    const t2 = setTimeout(() => setW(100), 600);
    const t3 = setTimeout(() => setW(0), 950);
    return () => { clearTimeout(t1); clearTimeout(t2); clearTimeout(t3); };
  }, []);
  if (!w) return null;
  return <div id="gl-bar" style={{ width: w + '%' }} />;
}

// ── Newsletter CTA band ───────────────────────────────────────────────────────
function NLBand({ studio }) {
  const [email, setEmail] = useState('');
  const [done, setDone] = useState(false);
  const sub = async () => {
    if (!email.includes('@')) return alert('Enter a valid email');
    try {
      const r = await fetch('/api/newsletter.php?action=subscribe', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email }) });
      const j = await r.json();
      if (j.success || j.ok) { setDone(true); return; }
    } catch {}
    setDone(true);
  };
  return (
    <div style={{ maxWidth: 1380, margin: '0 auto 80px', padding: '0 5%' }}>
    <div style={{ background: 'var(--gl-surface)', border: '1px solid var(--gl-lineA)', borderRadius: 'var(--gl-rl)', padding: 'clamp(36px,5vw,60px) clamp(28px,5vw,56px)', textAlign: 'center', position: 'relative', overflow: 'hidden' }}>
      <div style={{ position: 'absolute', inset: 0, background: 'radial-gradient(ellipse 70% 70% at 50% 0%, rgba(0,229,160,.07), transparent)', pointerEvents: 'none' }} />
      <div style={{ position: 'relative' }}>
        <h2 style={{ marginBottom: 10 }}>STAY IN THE <span style={{ color: 'var(--gl-accent)' }}>LOOP</span></h2>
        <p style={{ color: 'var(--gl-ink2)', marginBottom: 28, fontSize: 14, maxWidth: 440, margin: '0 auto 28px' }}>{studio?.newsletterDesc || 'Game launches, dev updates and tips from the team.'}</p>
        {done
          ? <div style={{ color: 'var(--gl-accent)', fontWeight: 600, fontSize: 15 }}>▶ You're in! Game updates incoming.</div>
          : <div style={{ display: 'flex', gap: 12, maxWidth: 440, margin: '0 auto', flexWrap: 'wrap', justifyContent: 'center' }}>
              <input value={email} onChange={e => setEmail(e.target.value)} onKeyDown={e => e.key === 'Enter' && sub()} placeholder="your@email.com" className="gl-input" style={{ flex: 1, minWidth: 200 }} />
              <button className="gl-btn gl-btn-primary" onClick={sub}>Subscribe</button>
            </div>
        }
      </div>
    </div>
    </div>
  );
}

// ── Theme Switcher ────────────────────────────────────────────────────────────
const GL_THEMES = {
  obsidian: { name: 'Obsidian', sub: 'Dark · Green',  file: 'theme-obsidian.css', preview: ['#050507','#00ff88','#f8f8ff'] },
  midnight: { name: 'Midnight', sub: 'Dark · Violet', file: 'theme-midnight.css', preview: ['#06060e','#a855f7','#f0eeff'] },
  ember:    { name: 'Ember',    sub: 'Dark · Orange', file: 'theme-ember.css',    preview: ['#080503','#ff6b2b','#fff8f0'] },
  arctic:   { name: 'Arctic',   sub: 'Light · Blue',  file: 'theme-arctic.css',   preview: ['#f8faff','#0066ff','#0c1222'] },
};

function injectTheme(key) {
  const theme = GL_THEMES[key];
  if (!theme) return;
  const existing = document.getElementById('gl-theme-link');
  if (existing) existing.remove();
  const link = document.createElement('link');
  link.id = 'gl-theme-link';
  link.rel = 'stylesheet';
  link.href = '/' + theme.file;
  document.head.appendChild(link);
  try { localStorage.setItem('gl_theme', key); } catch {}
}

function ThemeSwitcher() {
  const [open, setOpen] = useState(false);
  const [active, setActive] = useState(() => { try { return localStorage.getItem('gl_theme') || 'obsidian'; } catch { return 'obsidian'; } });

  const pick = (key) => {
    injectTheme(key);
    setActive(key);
    setOpen(false);
  };

  return (
    <div style={{ position: 'fixed', bottom: 28, right: 28, zIndex: 400 }}>
      {open && (
        <div style={{
          position: 'absolute', bottom: 56, right: 0,
          background: 'var(--gl-surface2)', border: '1px solid var(--gl-lineA)',
          borderRadius: 'var(--gl-rl)', padding: 16,
          boxShadow: '0 8px 40px rgba(0,0,0,.55), 0 0 0 1px var(--gl-line)',
          width: 220, animation: 'glToast .2s ease',
        }}>
          <div style={{ fontSize: 9, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.16em', color: 'var(--gl-muted)', marginBottom: 12 }}>Theme</div>
          <div style={{ display: 'grid', gap: 8 }}>
            {Object.entries(GL_THEMES).map(([key, t]) => (
              <button key={key} onClick={() => pick(key)} style={{
                display: 'flex', alignItems: 'center', gap: 12,
                padding: '10px 12px', borderRadius: 10, cursor: 'pointer', textAlign: 'left',
                background: active === key ? 'var(--gl-dim)' : 'transparent',
                border: active === key ? '1px solid var(--gl-lineA)' : '1px solid var(--gl-line)',
                transition: 'all .15s',
              }}>
                <div style={{ display: 'flex', gap: 3, flexShrink: 0 }}>
                  {t.preview.map((c, i) => (
                    <div key={i} style={{ width: 16, height: 16, borderRadius: i===0?'5px 2px 2px 5px':i===2?'2px 5px 5px 2px':'2px', background: c, border: '1px solid rgba(255,255,255,.08)' }} />
                  ))}
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--gl-ink)', lineHeight: 1.2 }}>{t.name}</div>
                  <div style={{ fontSize: 10, color: 'var(--gl-muted)', marginTop: 2 }}>{t.sub}</div>
                </div>
                {active === key && <span style={{ color: 'var(--gl-accent)', fontSize: 14, flexShrink: 0 }}>✓</span>}
              </button>
            ))}
          </div>
          <div style={{ fontSize: 9, color: 'var(--gl-muted)', marginTop: 12, textAlign: 'center', letterSpacing: '.06em' }}>Saved to your browser</div>
        </div>
      )}
      <button onClick={() => setOpen(o => !o)} style={{
        width: 44, height: 44, borderRadius: 999, cursor: 'pointer',
        background: 'var(--gl-surface2)', border: '1px solid var(--gl-lineA)',
        boxShadow: '0 4px 18px rgba(0,0,0,.4)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontSize: 20, transition: 'transform .2s',
        transform: open ? 'rotate(30deg) scale(1.1)' : 'none',
      }} title="Change theme">🎨</button>
    </div>
  );
}

Object.assign(window, { Ic, Stars, GameCard, BlogCard, ServiceCard, Eyebrow, SHead, Toast, Header, Footer, Marquee, ProgressBar, NLBand, ThemeSwitcher, GL_THEMES, injectTheme });
