// pages.jsx — all public pages for Gamingo Labs
const { useState, useEffect } = React;

// ── HOME ──────────────────────────────────────────────────────────────────────
function PHome({ data, goto }) {
  const studio  = data?.studio   || {};
  const games   = data?.games    || [];
  const services= data?.services || [];
  const featured = games.filter(g => g.featured);

  return (
    <>
      {/* HERO */}
      <section style={{ minHeight: '100vh', display: 'flex', flexDirection: 'column', justifyContent: 'center', padding: 'clamp(80px,12vw,120px) 0 60px', position: 'relative', overflow: 'hidden' }}>
        <div className="gl-gridbg" style={{ maskImage: 'radial-gradient(ellipse 80% 80% at 50% 50%, black 25%, transparent 72%)' }} />
        <div className="gl-orb gl-float" style={{ width: 620, height: 620, background: 'radial-gradient(circle, rgba(0,229,160,.14), transparent 70%)', top: -180, right: -160, filter: 'blur(80px)' }} />
        <div className="gl-orb gl-float" style={{ width: 320, height: 320, background: 'radial-gradient(circle, rgba(0,184,122,.1), transparent 70%)', bottom: 80, left: '6%', filter: 'blur(60px)', animationDelay: '-3.5s', animationDuration: '9s' }} />

        <div style={{ position: 'relative', zIndex: 1, maxWidth: 1380, width: '100%', margin: '0 auto', padding: '0 5%' }}>
          <div className="gl-eye">{studio.eyebrow || 'Mobile Game Studio & Publisher'}</div>
          <h1 style={{ marginBottom: 24, lineHeight: 1 }}>
            GAMES<br /><span style={{ color: 'var(--gl-accent)' }} className="gl-glow-text">MAKE US!</span>
          </h1>
          <p style={{ fontSize: 'clamp(.95rem,2vw,1.15rem)', color: 'var(--gl-ink2)', maxWidth: 500, marginBottom: 44, lineHeight: 1.8, fontWeight: 300 }}>
            {studio.subTagline}
          </p>
          <div style={{ display: 'flex', gap: 14, flexWrap: 'wrap', marginBottom: 70 }}>
            <button className="gl-btn gl-btn-primary" onClick={() => goto('games')} style={{ padding: '13px 30px', fontSize: 15 }}>
              <Ic.Play width={13} height={13} /> See Our Games
            </button>
            <button className="gl-btn" onClick={() => goto('contact')} style={{ padding: '13px 30px', fontSize: 15 }}>
              Partner With Us <Ic.Arrow width={15} height={15} />
            </button>
          </div>
          {studio.stats?.length > 0 && (
            <div style={{ display: 'flex', gap: 40, flexWrap: 'wrap' }}>
              {studio.stats.map((s, i) => (
                <div key={i}>
                  <div style={{ fontFamily: 'var(--gl-fd)', fontSize: 'clamp(2rem,4vw,2.6rem)', color: 'var(--gl-accent)', lineHeight: 1, letterSpacing: '.04em' }}>{s.value}</div>
                  <div style={{ fontSize: 10, color: 'var(--gl-muted)', letterSpacing: '.12em', textTransform: 'uppercase', fontWeight: 600, marginTop: 5 }}>{s.label}</div>
                </div>
              ))}
            </div>
          )}
        </div>
      </section>

      <Marquee />

      {/* Featured Games */}
      <section className="gl-section">
        <SHead eye="Our Games" title="FEATURED TITLES" accent="FEATURED" sub="Puzzle, board, and sports games built for mobile players worldwide." />
        <div className="gl-auto">{featured.map(g => <GameCard key={g.id} game={g} badge goto={goto} />)}</div>
        <div style={{ marginTop: 32 }}>
          <button className="gl-btn gl-btn-outline" onClick={() => goto('games')}>View All Games <Ic.Arrow width={14} height={14} /></button>
        </div>
      </section>

      <div className="gl-hr" style={{ margin: '0 5%' }} />

      {/* Services preview */}
      <section className="gl-section">
        <SHead eye="What We Do" title="DEV. PUBLISH. GROW." sub="From building games to launching them globally — we do it all." />
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: 20 }}>
          {services.slice(0, 3).map((s, i) => <ServiceCard key={i} s={s} />)}
        </div>
      </section>

      <NLBand studio={studio} />
    </>
  );
}

// ── GAMES ─────────────────────────────────────────────────────────────────────
function PGames({ data }) {
  const [filter, setFilter] = useState('All');
  const games = data?.games || [];
  const genres = ['All', ...new Set(games.map(g => g.genre))];
  const filtered = filter === 'All' ? games : games.filter(g => g.genre === filter);

  return (
    <section className="gl-section">
      <SHead eye="Game Portfolio" title="OUR GAMES" sub="All titles available on Google Play. Tap any game to visit its store page." />
      <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', marginBottom: 40 }}>
        {genres.map(g => (
          <button key={g} className={`gl-btn gl-btn-sm ${g === filter ? 'gl-btn-outline' : ''}`}
            style={{ borderRadius: 999 }} onClick={() => setFilter(g)}>{g}</button>
        ))}
      </div>
      <div className="gl-auto">{filtered.map(g => <GameCard key={g.id} game={g} badge goto={goto} />)}</div>
    </section>
  );
}

// ── ABOUT ─────────────────────────────────────────────────────────────────────
function PAbout({ data }) {
  const s = data?.studio || {};
  const paras  = Array.isArray(s.aboutParagraphs) ? s.aboutParagraphs : [s.description || ''];
  const values = Array.isArray(s.values) ? s.values : [];

  return (
    <section className="gl-section">
      <div className="gl-2col">
        {/* Visual */}
        <div style={{ position: 'relative', height: 440, borderRadius: 'var(--gl-rl)', overflow: 'hidden', background: 'var(--gl-surface)', border: '1px solid var(--gl-line)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <div className="gl-gridbg" />
          <div className="gl-orb" style={{ width: 260, height: 260, background: 'radial-gradient(circle, rgba(0,229,160,.2), transparent 70%)', top: '50%', left: '50%', transform: 'translate(-50%,-50%)', filter: 'blur(50px)' }} />
          <div style={{ position: 'relative', zIndex: 2, textAlign: 'center' }}>
            <div className="gl-glow-text" style={{ fontFamily: 'var(--gl-fd)', fontSize: 'clamp(4rem,10vw,6rem)', color: 'var(--gl-accent)', lineHeight: 1, letterSpacing: '.06em' }}>GL</div>
            <div style={{ fontFamily: 'var(--gl-fd)', fontSize: '1.4rem', color: 'var(--gl-ink2)', marginTop: 8, letterSpacing: '.04em' }}>Games Make Us!</div>
          </div>
        </div>
        {/* Copy */}
        <div>
          <div className="gl-eye">About Us</div>
          <h2 style={{ marginBottom: 22 }}>WE LIVE &amp; <span style={{ color: 'var(--gl-accent)' }}>BREATHE</span> GAMES</h2>
          {paras.filter(Boolean).map((p, i) => (
            <p key={i} style={{ color: 'var(--gl-ink2)', marginBottom: 16, lineHeight: 1.8, fontWeight: 300 }}>{p}</p>
          ))}
          <div style={{ marginTop: 30, display: 'flex', flexDirection: 'column', gap: 11 }}>
            {values.map((v, i) => (
              <div key={i} style={{ display: 'flex', gap: 14, background: 'var(--gl-surface)', border: '1px solid var(--gl-line)', borderRadius: 'var(--gl-r)', padding: '15px 18px' }}>
                <div style={{ width: 8, height: 8, background: 'var(--gl-accent)', borderRadius: '50%', marginTop: 7, flexShrink: 0 }} />
                <div>
                  <div style={{ fontWeight: 700, fontSize: 15, marginBottom: 3 }}>{v.title}</div>
                  <div style={{ fontSize: 15, color: 'var(--gl-ink2)' }}>{v.desc}</div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

// ── SERVICES ──────────────────────────────────────────────────────────────────
function PServices({ data, goto }) {
  const services = data?.services || [];
  return (
    <section className="gl-section">
      <SHead eye="Services" title="WHAT WE OFFER" sub="Whether you're an indie dev looking for a publishing partner or a brand wanting a custom game — we've got you." />
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: 20 }}>
        {services.map((s, i) => <ServiceCard key={i} s={s} />)}
      </div>
      {/* CTA */}
      <div style={{ marginTop: 60, background: 'var(--gl-surface)', border: '1px solid var(--gl-lineA)', borderRadius: 'var(--gl-rl)', padding: 'clamp(36px,5vw,56px)', textAlign: 'center', position: 'relative', overflow: 'hidden' }}>
        <div style={{ position: 'absolute', inset: 0, background: 'radial-gradient(ellipse 60% 60% at 50% 0%, rgba(0,229,160,.07), transparent)', pointerEvents: 'none' }} />
        <div style={{ position: 'relative' }}>
          <div className="gl-eye" style={{ justifyContent: 'center' }}>Publishing Partnership</div>
          <h3 style={{ fontFamily: 'var(--gl-fd)', fontSize: 'clamp(2rem,4vw,3rem)', marginBottom: 14 }}>GOT A GREAT GAME IDEA?</h3>
          <p style={{ color: 'var(--gl-ink2)', maxWidth: 460, margin: '0 auto 28px', fontSize: 15, lineHeight: 1.75 }}>We partner with indie developers to fund, polish, publish, and grow mobile games. Let's talk.</p>
          <button className="gl-btn gl-btn-primary" onClick={() => goto('contact')} style={{ padding: '13px 34px', fontSize: 15 }}>
            Start a Conversation <Ic.Arrow width={14} height={14} />
          </button>
        </div>
      </div>
    </section>
  );
}

// ── BLOG ──────────────────────────────────────────────────────────────────────
function PBlog({ data, goto }) {
  const posts = data?.blog || [];
  return (
    <section className="gl-section">
      <SHead eye="Blog" title="STUDIO UPDATES" sub="Dev logs, game launches, tips and news from the Gamingo Labs team." />
      {posts.length === 0
        ? <p style={{ color: 'var(--gl-muted)', padding: '40px 0' }}>No posts yet — check back soon.</p>
        : <div className="gl-auto3">{posts.map(p => <BlogCard key={p.id || p.slug} post={p} onClick={() => goto('post', { slug: p.slug || p.id })} />)}</div>
      }
    </section>
  );
}

// ── BLOG POST ─────────────────────────────────────────────────────────────────
function PPost({ data, goto, slug }) {
  const [post, setPost] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!slug) { setLoading(false); return; }
    // Find in local data first
    const found = (data?.blog || []).find(p => (p.slug || p.id) === slug);
    if (found) { setPost(found); setLoading(false); return; }
    // Try API
    fetch('/api/blog.php?action=get&slug=' + encodeURIComponent(slug))
      .then(r => r.json())
      .then(j => { if (j.success && j.post) setPost(j.post); })
      .catch(() => {})
      .finally(() => setLoading(false));
  }, [slug]);

  if (loading) return <div style={{ padding: '80px 5%', color: 'var(--gl-muted)' }}>Loading…</div>;
  if (!post) return (
    <div style={{ padding: '80px 5%', textAlign: 'center' }}>
      <p style={{ color: 'var(--gl-muted)', marginBottom: 20 }}>Post not found.</p>
      <button className="gl-btn" onClick={() => goto('blog')}>← Back to Blog</button>
    </div>
  );

  const words = ((post.content || '') + ' ' + (post.excerpt || '')).split(/\s+/).length;
  const readMin = Math.max(1, Math.ceil(words / 200));
  const others = (data?.blog || []).filter(p => (p.slug || p.id) !== slug).slice(0, 3);

  return (
    <section className="gl-section" style={{ maxWidth: 800, margin: '0 auto' }}>
      <button className="gl-btn gl-btn-sm" onClick={() => goto('blog')} style={{ marginBottom: 36 }}>← Back to Blog</button>
      <span style={{ fontSize: 10, fontWeight: 700, letterSpacing: '.12em', textTransform: 'uppercase', color: 'var(--gl-accent)', background: 'var(--gl-dim)', padding: '4px 12px', borderRadius: 999, display: 'inline-block', marginBottom: 18 }}>{post.category}</span>
      <h1 style={{ fontSize: 'clamp(2rem,5vw,3.4rem)', marginBottom: 18, lineHeight: 1.08 }}>{post.title}</h1>
      <div style={{ display: 'flex', gap: 14, color: 'var(--gl-muted)', fontSize: 15, marginBottom: 44 }}>
        <span>{glDate(post.published_at || post.date)}</span>
        <span>·</span>
        <span>{readMin} min read</span>
      </div>
      {post.image && (
        <div style={{ width: '100%', height: 280, borderRadius: 'var(--gl-rl)', overflow: 'hidden', marginBottom: 44, background: 'var(--gl-surface)', display: 'flex', alignItems: 'center', justifyContent: 'center', position: 'relative' }}>
          <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(135deg, var(--gl-surface2), var(--gl-bg))' }} />
          <img src={post.image} alt={post.title} width={88} height={88} style={{ position: 'relative', zIndex: 1, borderRadius: 18, boxShadow: '0 8px 32px rgba(0,0,0,.55)' }} onError={e => e.target.style.display='none'} />
        </div>
      )}
      <div dangerouslySetInnerHTML={{ __html: glMd(post.content || post.excerpt || '') }} />
      {others.length > 0 && (
        <div style={{ marginTop: 52, paddingTop: 40, borderTop: '1px solid var(--gl-line)' }}>
          <div className="gl-eye" style={{ marginBottom: 22 }}>More Posts</div>
          <div className="gl-auto">{others.map(p => <BlogCard key={p.id||p.slug} post={p} onClick={() => goto('post', { slug: p.slug || p.id })} />)}</div>
        </div>
      )}
    </section>
  );
}

// ── VIDEOS ────────────────────────────────────────────────────────────────────
function PVideos({ data }) {
  const [gf, setGf] = useState('All');
  const [tf, setTf] = useState('All');
  const videos = data?.videos || [];
  const games  = data?.games  || [];
  const types = ['All', ...new Set(videos.map(v => v.type))];
  const filtered = videos.filter(v => (gf === 'All' || v.gameId === gf) && (tf === 'All' || v.type === tf));
  const typeColor = { Gameplay: { bg: 'rgba(0,229,160,.1)', color: 'var(--gl-accent)' }, Tutorial: { bg: 'rgba(255,209,102,.1)', color: 'var(--gl-yellow)' }, Tips: { bg: 'rgba(99,179,237,.1)', color: 'var(--gl-blue)' } };

  return (
    <section className="gl-section">
      <SHead eye="YouTube" title="WATCH & LEARN" sub="Gameplay trailers, tutorials, tips and tricks — all in one place." />
      <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 36 }}>
        <button className={`gl-btn gl-btn-sm ${gf === 'All' ? 'gl-btn-outline' : ''}`} style={{ borderRadius: 999 }} onClick={() => setGf('All')}>All Games</button>
        {games.map(g => <button key={g.id} className={`gl-btn gl-btn-sm ${gf === g.id ? 'gl-btn-outline' : ''}`} style={{ borderRadius: 999 }} onClick={() => setGf(g.id)}>{g.title.split('–')[0].trim()}</button>)}
        <span style={{ width: 1, background: 'var(--gl-line)', margin: '4px 4px' }} />
        {types.map(t => <button key={t} className={`gl-btn gl-btn-sm ${tf === t ? 'gl-btn-outline' : ''}`} style={{ borderRadius: 999 }} onClick={() => setTf(t)}>{t}</button>)}
      </div>
      {filtered.length === 0
        ? <p style={{ color: 'var(--gl-muted)' }}>No videos for this filter.</p>
        : <div className="gl-auto3">
            {filtered.map(v => {
              const game = games.find(g => g.id === v.gameId);
              const tc = typeColor[v.type] || typeColor.Gameplay;
              return (
                <div key={v.id} className="gl-card" style={{ overflow: 'hidden' }}>
                  <div style={{ position: 'relative', paddingBottom: '56.25%', background: 'var(--gl-bg)' }}>
                    <iframe src={'https://www.youtube.com/embed/' + v.youtubeId} title={v.title}
                      style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', border: 'none' }}
                      allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                      allowFullScreen loading="lazy" />
                  </div>
                  <div style={{ padding: 16 }}>
                    <span style={{ fontSize: 10, fontWeight: 700, letterSpacing: '.1em', textTransform: 'uppercase', padding: '3px 10px', borderRadius: 999, marginBottom: 8, display: 'inline-block', background: tc.bg, color: tc.color }}>{v.type}</span>
                    <div style={{ fontWeight: 700, fontSize: 15, marginBottom: 4, lineHeight: 1.3 }}>{v.title}</div>
                    <p style={{ fontSize: 15, color: 'var(--gl-ink2)', marginBottom: 10 }}>{v.description}</p>
                    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', fontSize: 11, color: 'var(--gl-muted)' }}>
                      {game && <span style={{ display: 'flex', alignItems: 'center', gap: 5 }}><img src={game.icon} alt="" width={14} height={14} style={{ borderRadius: 3 }} />{game.title.split('–')[0].trim()}</span>}
                      <span>{glDate(v.date)}</span>
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
      }
    </section>
  );
}

// ── PLAYER HUB ────────────────────────────────────────────────────────────────
function PPlayers({ data, goto }) {
  const [tab,     setTab]     = useState('tips');
  const [tFilter, setTFilter] = useState('All');
  const [fFilter, setFFilter] = useState('All');
  const [openFaq, setOpenFaq] = useState(null);
  const tips  = data?.tips  || [];
  const faq   = data?.faq   || [];
  const games = data?.games || [];
  const ftips = tFilter === 'All' ? tips : tips.filter(t => t.gameId === tFilter);
  const ffaq  = fFilter === 'All' ? faq  : faq.filter(f => f.gameId === fFilter || f.gameId === 'all');
  const diffC = { Beginner: { bg: 'rgba(0,229,160,.1)', color: 'var(--gl-accent)' }, Intermediate: { bg: 'rgba(255,209,102,.1)', color: 'var(--gl-yellow)' }, Advanced: { bg: 'rgba(255,77,109,.1)', color: 'var(--gl-red)' } };

  const Filters = ({ active, set }) => (
    <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 28 }}>
      <button className={`gl-btn gl-btn-sm ${active === 'All' ? 'gl-btn-outline' : ''}`} style={{ borderRadius: 999 }} onClick={() => set('All')}>All</button>
      {games.map(g => <button key={g.id} className={`gl-btn gl-btn-sm ${active === g.id ? 'gl-btn-outline' : ''}`} style={{ borderRadius: 999 }} onClick={() => set(g.id)}>{g.title.split('–')[0].trim()}</button>)}
    </div>
  );

  return (
    <section className="gl-section">
      <SHead eye="Player Hub" title="YOUR GAME HQ" accent="GAME HQ" sub="Tips, tricks, FAQs and support — everything you need to play better." />
      <div style={{ display: 'flex', gap: 8, marginBottom: 36, flexWrap: 'wrap' }}>
        {[['tips','💡 Tips & Tricks'],['faq','❓ FAQ'],['support','🛠️ Support']].map(([id, lbl]) => (
          <button key={id} className={`gl-btn ${tab === id ? 'gl-btn-outline' : ''}`} style={{ borderRadius: 999, padding: '10px 22px', fontSize: 15 }} onClick={() => setTab(id)}>{lbl}</button>
        ))}
      </div>

      {tab === 'tips' && (
        <>
          <Filters active={tFilter} set={setTFilter} />
          {ftips.length === 0
            ? <p style={{ color: 'var(--gl-muted)' }}>No tips for this game yet.</p>
            : <div className="gl-auto">
                {ftips.map(t => {
                  const game = games.find(g => g.id === t.gameId);
                  const dc = diffC[t.difficulty] || diffC.Beginner;
                  return (
                    <div key={t.id} className="gl-card" style={{ padding: 22, position: 'relative', overflow: 'hidden' }}>
                      <div style={{ position: 'absolute', left: 0, top: 0, bottom: 0, width: 3, background: 'var(--gl-accent)', borderRadius: '0 2px 2px 0' }} />
                      <span style={{ fontSize: 9, fontWeight: 700, letterSpacing: '.1em', textTransform: 'uppercase', padding: '2px 8px', borderRadius: 4, marginBottom: 10, display: 'inline-block', background: dc.bg, color: dc.color }}>{t.difficulty}</span>
                      <div style={{ fontWeight: 700, fontSize: 15, marginBottom: 8 }}>{t.title}</div>
                      <p style={{ fontSize: 15, color: 'var(--gl-ink2)', lineHeight: 1.7 }}>{t.content}</p>
                      {game && <div style={{ fontSize: 11, color: 'var(--gl-muted)', marginTop: 12, display: 'flex', alignItems: 'center', gap: 5 }}><img src={game.icon} alt="" width={14} height={14} style={{ borderRadius: 3 }} />{game.title.split('–')[0].trim()}</div>}
                    </div>
                  );
                })}
              </div>
          }
        </>
      )}

      {tab === 'faq' && (
        <>
          <Filters active={fFilter} set={setFFilter} />
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {ffaq.map((f, i) => (
              <div key={f.id || i} className="gl-card" style={{ overflow: 'hidden', borderColor: openFaq === i ? 'var(--gl-lineA)' : undefined }}>
                <div onClick={() => setOpenFaq(openFaq === i ? null : i)}
                  style={{ padding: '16px 20px', fontWeight: 600, fontSize: 15, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, userSelect: 'none' }}>
                  {f.question}
                  <Ic.Chev width={14} height={14} style={{ flexShrink: 0, transition: 'transform .2s', transform: openFaq === i ? 'rotate(180deg)' : 'none', color: openFaq === i ? 'var(--gl-accent)' : 'var(--gl-muted)' }} />
                </div>
                {openFaq === i && <div style={{ padding: '0 20px 18px', paddingTop: 14, fontSize: 15, color: 'var(--gl-ink2)', lineHeight: 1.75, borderTop: '1px solid var(--gl-line)' }}>{f.answer}</div>}
              </div>
            ))}
            {ffaq.length === 0 && <p style={{ color: 'var(--gl-muted)' }}>No FAQs for this game yet.</p>}
          </div>
        </>
      )}

      {tab === 'support' && <SupportForm data={data} />}
    </section>
  );
}

// ── PRESS ─────────────────────────────────────────────────────────────────────
function PPress({ data, goto }) {
  const pk    = data?.pressKit || {};
  const games = data?.games || [];
  const icoMap = { zip: '📦', pdf: '📄', png: '🖼️', svg: '✏️' };
  return (
    <section className="gl-section">
      <SHead eye="Press Kit" title="MEDIA & PRESS" sub={pk.description} />
      <div className="gl-25col">
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          {(pk.assets || []).map((a, i) => (
            <div key={i} className="gl-card" style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '17px 20px' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
                <span style={{ fontSize: '1.4rem' }}>{icoMap[a.type] || '📁'}</span>
                <div>
                  <div style={{ fontWeight: 600, fontSize: 15 }}>{a.name}</div>
                  <div style={{ fontSize: 11, color: 'var(--gl-muted)', textTransform: 'uppercase', letterSpacing: '.08em', marginTop: 2 }}>{a.type}</div>
                </div>
              </div>
              <a href={a.url} className="gl-btn gl-btn-sm">Download</a>
            </div>
          ))}
          {(pk.assets || []).length === 0 && <p style={{ color: 'var(--gl-muted)' }}>Press assets coming soon.</p>}
        </div>
        <div className="gl-card" style={{ padding: 32 }}>
          <div style={{ fontWeight: 700, fontSize: 18, marginBottom: 12 }}>Press Contact</div>
          <p style={{ color: 'var(--gl-ink2)', fontSize: 15, marginBottom: 18, lineHeight: 1.65 }}>For press inquiries, interviews, or review copies of our games.</p>
          <a href={'mailto:' + (pk.contact || 'press@gamingolabs.com')} style={{ display: 'flex', alignItems: 'center', gap: 10, background: 'var(--gl-dim)', border: '1px solid var(--gl-lineA)', borderRadius: 'var(--gl-r)', padding: '13px 16px', fontSize: 15, fontWeight: 500, color: 'var(--gl-accent)' }}>
            <Ic.Mail width={16} height={16} /> {pk.contact || 'press@gamingolabs.com'}
          </a>
          <button className="gl-btn gl-btn-block" onClick={() => goto('contact')} style={{ marginTop: 14 }}>Send a Message →</button>
        </div>
      </div>
      <div style={{ marginTop: 60 }}>
        <div className="gl-eye" style={{ marginBottom: 20 }}>Game Icons</div>
        <div style={{ display: 'flex', gap: 18, flexWrap: 'wrap' }}>
          {games.map(g => (
            <div key={g.id} className="gl-card" style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 10, padding: '18px 22px', minWidth: 124, textAlign: 'center' }}>
              <img src={g.icon} alt={g.title} width={60} height={60} style={{ borderRadius: 14, boxShadow: '0 6px 20px rgba(0,0,0,.5)' }} />
              <span style={{ fontSize: 12, fontWeight: 500, color: 'var(--gl-ink2)' }}>{g.title.split('–')[0].trim()}</span>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ── CONTACT ───────────────────────────────────────────────────────────────────
function PContact({ data }) {
  const s = data?.studio || {};
  const [f, setF] = useState({ name: '', email: '', subject: '', message: '' });
  const [done, setDone] = useState(null);
  const [busy, setBusy] = useState(false);

  const send = async () => {
    if (!f.name || !f.email || !f.subject || !f.message) { alert('Please fill in all fields.'); return; }
    setBusy(true);
    try {
      const r = await fetch('/api/tickets.php?action=submit', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ type: 'contact', ...f }) });
      const j = await r.json();
      if (j.success) { setDone(j.ticket_ref || 'OK'); setF({ name: '', email: '', subject: '', message: '' }); }
      else alert(j.error || 'Something went wrong. Try emailing us directly.');
    } catch { alert('Could not connect. Email us: ' + (s.email || 'contact@gamingolabs.com')); }
    setBusy(false);
  };

  const LINKS = [
    s.email         && { label: s.email,         href: 'mailto:' + s.email },
    s.googlePlayDev && { label: 'Google Play',    href: s.googlePlayDev },
    s.instagram     && { label: 'Instagram',      href: s.instagram },
    s.website       && { label: s.website?.replace('https://', ''), href: s.website },
  ].filter(Boolean);

  return (
    <section className="gl-section">
      <div className="gl-2col">
        <div>
          <div className="gl-eye">Contact</div>
          <h2 style={{ marginBottom: 18 }}>LET'S BUILD SOMETHING <span style={{ color: 'var(--gl-accent)' }}>GREAT</span></h2>
          <p style={{ color: 'var(--gl-ink2)', marginBottom: 36, lineHeight: 1.8, fontWeight: 300, maxWidth: 420 }}>Whether you're a player, press, partner, or indie developer looking for publishing support — we'd love to hear from you.</p>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            {LINKS.map((l, i) => (
              <a key={i} href={l.href} target="_blank" rel="noreferrer" className="gl-card"
                style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '15px 18px', fontSize: 15, fontWeight: 500 }}>
                <Ic.Arrow width={14} height={14} style={{ color: 'var(--gl-accent)', flexShrink: 0 }} /> {l.label}
              </a>
            ))}
          </div>
        </div>
        <div className="gl-card" style={{ padding: 34 }}>
          <div style={{ fontWeight: 700, fontSize: 18, marginBottom: 24 }}>Send a Message</div>
          {done ? (
            <div style={{ background: 'var(--gl-dim)', border: '1px solid var(--gl-lineA)', borderRadius: 'var(--gl-r)', padding: '18px 20px', color: 'var(--gl-accent)', lineHeight: 1.6, fontSize: 15 }}>
              ✓ Message received! Ref: <strong>{done}</strong>. We'll reply within 48 hours.
            </div>
          ) : (
            <>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, marginBottom: 14 }}>
                <div><label className="gl-label">Your Name</label><input className="gl-input" value={f.name} onChange={e => setF({...f,name:e.target.value})} placeholder="Jane Doe" /></div>
                <div><label className="gl-label">Email</label><input className="gl-input" type="email" value={f.email} onChange={e => setF({...f,email:e.target.value})} placeholder="you@email.com" /></div>
              </div>
              <div style={{ marginBottom: 14 }}>
                <label className="gl-label">Subject</label>
                <select className="gl-input" style={{ cursor: 'pointer' }} value={f.subject} onChange={e => setF({...f,subject:e.target.value})}>
                  <option value="">Select a topic…</option>
                  {['Publishing Partnership','Press / Media','Game Feedback','Business Inquiry','Other'].map(t => <option key={t}>{t}</option>)}
                </select>
              </div>
              <div style={{ marginBottom: 20 }}>
                <label className="gl-label">Message</label>
                <textarea className="gl-input" value={f.message} onChange={e => setF({...f,message:e.target.value})} placeholder="Tell us about your project or question…" style={{ resize: 'vertical', minHeight: 120 }} />
              </div>
              <button className="gl-btn gl-btn-primary gl-btn-block" onClick={send} disabled={busy}>{busy ? 'Sending…' : 'Send Message ✓'}</button>
            </>
          )}
        </div>
      </div>
    </section>
  );
}

// ── SUPPORT FORM ──────────────────────────────────────────────────────────────
function SupportForm({ data }) {
  const games = data?.games || [];
  const studio = data?.studio || {};
  const [f, setF] = useState({ name: '', email: '', game: games[0]?.id || '', type: 'Bug / Crash', message: '' });
  const [done, setDone] = useState(null);
  const email = studio.supportEmail || studio.email || 'support@gamingolabs.com';

  const send = async () => {
    if (!f.name || !f.email || !f.message) { alert('Please fill all fields.'); return; }
    try {
      const r = await fetch('/api/tickets.php?action=submit', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ type: 'support', ...f, subject: f.type + ' — ' + f.game }) });
      const j = await r.json();
      if (j.success) setDone(j.ticket_ref || 'OK');
      else alert(j.error || 'Failed. Email us: ' + email);
    } catch { setDone('OFFLINE'); }
  };

  return (
    <div className="gl-2col">
      <div>
        <div style={{ fontWeight: 700, fontSize: 18, marginBottom: 12 }}>Get Help Fast</div>
        <p style={{ color: 'var(--gl-ink2)', fontSize: 15, marginBottom: 22, lineHeight: 1.7 }}>Having an issue with one of our games? Fill the form and our team will get back to you within 24 hours.</p>
        <a href={'mailto:' + email} className="gl-card" style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '15px 18px', fontSize: 15, fontWeight: 500 }}>
          <Ic.Mail width={16} height={16} style={{ color: 'var(--gl-accent)' }} /> {email}
        </a>
      </div>
      <div className="gl-card" style={{ padding: 28 }}>
        <div style={{ fontWeight: 700, fontSize: 15, marginBottom: 18 }}>Submit a Bug Report</div>
        {done ? (
          <div style={{ color: 'var(--gl-accent)', fontSize: 15 }}>✓ Report received! Ref: <strong>{done}</strong>. We'll reply within 24h.</div>
        ) : (
          <>
            <div style={{ marginBottom: 12 }}><label className="gl-label">Name</label><input className="gl-input" value={f.name} onChange={e => setF({...f,name:e.target.value})} placeholder="Your name" /></div>
            <div style={{ marginBottom: 12 }}><label className="gl-label">Email</label><input className="gl-input" type="email" value={f.email} onChange={e => setF({...f,email:e.target.value})} placeholder="your@email.com" /></div>
            <div style={{ marginBottom: 12 }}>
              <label className="gl-label">Which Game?</label>
              <select className="gl-input" value={f.game} onChange={e => setF({...f,game:e.target.value})}>
                {games.map(g => <option key={g.id} value={g.id}>{g.title}</option>)}
              </select>
            </div>
            <div style={{ marginBottom: 12 }}>
              <label className="gl-label">Issue Type</label>
              <select className="gl-input" value={f.type} onChange={e => setF({...f,type:e.target.value})}>
                {['Bug / Crash','Payment Issue','Account Problem','Gameplay Question','Feature Request','Other'].map(t => <option key={t}>{t}</option>)}
              </select>
            </div>
            <div style={{ marginBottom: 18 }}>
              <label className="gl-label">Describe the Issue</label>
              <textarea className="gl-input" value={f.message} onChange={e => setF({...f,message:e.target.value})} placeholder="Device model, Android version, steps to reproduce…" style={{ resize: 'vertical', minHeight: 90 }} />
            </div>
            <button className="gl-btn gl-btn-primary gl-btn-block" onClick={send}>Send Report ✓</button>
          </>
        )}
      </div>
    </div>
  );
}

// ── INDIVIDUAL GAME PAGE ─────────────────────────────────────────────────────
function PGame({ data, goto, gameId }) {
  const game = (data?.games || []).find(g => g.id === gameId);
  const tips  = (data?.tips  || []).filter(t => t.gameId === gameId);
  const faq   = (data?.faq   || []).filter(f => f.gameId === gameId || f.gameId === 'all');
  const videos = (data?.videos || []).filter(v => v.gameId === gameId);
  const otherGames = (data?.games || []).filter(g => g.id !== gameId).slice(0, 3);
  const [openFaq, setOpenFaq] = useState(null);
  const diffC = { Beginner: { bg: 'rgba(0,255,136,.1)', color: 'var(--gl-accent)' }, Intermediate: { bg: 'rgba(255,209,102,.1)', color: 'var(--gl-yellow)' }, Advanced: { bg: 'rgba(255,77,109,.1)', color: 'var(--gl-red)' } };

  if (!game) return (
    <section style={{ padding: '80px 5%', textAlign: 'center' }}>
      <p style={{ color: 'var(--gl-muted)', marginBottom: 20 }}>Game not found.</p>
      <button className="gl-btn" onClick={() => goto('games')}>← All Games</button>
    </section>
  );

  const stars = Math.round(game.rating || 0);
  const schema = {
    '@context': 'https://schema.org',
    '@type': 'VideoGame',
    name: game.title,
    description: game.longDescription || game.description,
    applicationCategory: 'GameApplication',
    operatingSystem: 'Android',
    genre: [game.genre, ...(game.subgenre ? game.subgenre.split(', ') : [])],
    url: `https://gamingolabs.com/games/${game.id}`,
    image: game.icon,
    aggregateRating: { '@type': 'AggregateRating', ratingValue: game.rating, ratingCount: game.ratingCount || 100, bestRating: 5, worstRating: 1 },
    offers: { '@type': 'Offer', price: '0', priceCurrency: 'USD', availability: 'https://schema.org/InStock' },
    publisher: { '@type': 'Organization', name: 'Gamingo Labs', url: 'https://gamingolabs.com' },
    author: { '@type': 'Organization', name: 'Gamingo Labs' },
    installUrl: game.playStoreUrl,
    downloadUrl: game.playStoreUrl,
  };

  // Inject SEO meta tags dynamically
  useEffect(() => {
    document.title = `${game.title} – Free Android Game | Gamingo Labs`;
    const setMeta = (sel, attr, val) => {
      let el = document.querySelector(sel);
      if (!el) { el = document.createElement('meta'); if (sel.includes('property')) el.setAttribute('property', sel.match(/property="([^"]+)"/)[1]); else el.setAttribute('name', sel.match(/name="([^"]+)"/)[1]); document.head.appendChild(el); }
      el.setAttribute(attr, val);
    };
    setMeta('meta[name="description"]', 'content', game.metaDescription || game.description);
    setMeta('meta[name="keywords"]', 'content', game.keywords || '');
    setMeta('meta[property="og:title"]', 'content', `${game.title} – Free Android Game`);
    setMeta('meta[property="og:description"]', 'content', game.metaDescription || game.description);
    setMeta('meta[property="og:image"]', 'content', game.icon);
    setMeta('meta[property="og:url"]', 'content', `https://gamingolabs.com/games/${game.id}`);
    setMeta('meta[property="og:type"]', 'content', 'website');
    setMeta('meta[name="twitter:card"]', 'content', 'summary_large_image');
    setMeta('meta[name="twitter:title"]', 'content', `${game.title} – Free Android Game`);
    setMeta('meta[name="twitter:description"]', 'content', game.metaDescription || game.description);
    setMeta('meta[name="twitter:image"]', 'content', game.icon);
    // JSON-LD
    let ld = document.getElementById('game-jsonld');
    if (!ld) { ld = document.createElement('script'); ld.type = 'application/ld+json'; ld.id = 'game-jsonld'; document.head.appendChild(ld); }
    ld.textContent = JSON.stringify(schema);
    return () => { if (ld) ld.remove(); };
  }, [game]);

  return (
    <>
      {/* Hero */}
      <section style={{ padding: 'clamp(70px,10vw,110px) 5% 60px', position: 'relative', overflow: 'hidden' }}>
        <div className="gl-gridbg" style={{ maskImage: 'radial-gradient(ellipse 80% 80% at 50% 50%, black 20%, transparent 75%)' }} />
        <div className="gl-orb gl-float" style={{ width: 500, height: 500, background: 'radial-gradient(circle, var(--gl-dim), transparent 70%)', top: -200, right: -100, filter: 'blur(80px)' }} />
        <div style={{ maxWidth: 1380, margin: '0 auto', position: 'relative', zIndex: 1 }}>
          <button onClick={() => goto('games')} className="gl-btn gl-btn-sm" style={{ marginBottom: 32 }}>← All Games</button>
          <div style={{ display: 'grid', gridTemplateColumns: 'auto 1fr', gap: 40, alignItems: 'flex-start' }} className="gl-2col">
            {/* Icon + CTA */}
            <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 20, minWidth: 200 }}>
              <div className="gl-card gl-glow" style={{ padding: 20, width: 180, height: 180, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <img src={game.icon} alt={game.title} width={140} height={140} style={{ borderRadius: 24, boxShadow: '0 8px 32px rgba(0,0,0,.5)' }} />
              </div>
              <a href={game.playStoreUrl} target="_blank" rel="noreferrer" className="gl-btn gl-btn-primary" style={{ width: '100%', justifyContent: 'center', fontSize: 14, padding: '14px 24px' }}>
                <Ic.Play width={14} height={14} /> Free Download
              </a>
              <div style={{ textAlign: 'center' }}>
                <div style={{ fontSize: 11, color: 'var(--gl-muted)', marginBottom: 4, letterSpacing: '.05em' }}>Available on</div>
                <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--gl-ink2)' }}>Google Play · Android</div>
              </div>
            </div>
            {/* Info */}
            <div>
              <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', marginBottom: 16 }}>
                <span style={{ fontSize: 10, fontWeight: 700, letterSpacing: '.12em', textTransform: 'uppercase', color: 'var(--gl-accent)', background: 'var(--gl-dim)', padding: '4px 12px', borderRadius: 999 }}>{game.genre}</span>
                <span style={{ fontSize: 10, fontWeight: 700, letterSpacing: '.12em', textTransform: 'uppercase', color: game.status === 'Live' ? 'var(--gl-accent)' : 'var(--gl-yellow)', background: 'rgba(0,255,136,.07)', padding: '4px 12px', borderRadius: 999 }}>{game.status}</span>
              </div>
              <h1 style={{ fontSize: 'clamp(2rem, 5vw, 4rem)', marginBottom: 16, lineHeight: 1.08 }}>{game.title}</h1>
              <p style={{ fontSize: 16, color: 'var(--gl-ink2)', marginBottom: 24, lineHeight: 1.8, maxWidth: 580, fontWeight: 300 }}>{game.longDescription || game.description}</p>
              {/* Rating + downloads */}
              <div style={{ display: 'flex', gap: 32, flexWrap: 'wrap', marginBottom: 32 }}>
                <div>
                  <div style={{ display: 'flex', gap: 3, marginBottom: 4 }}>
                    {[1,2,3,4,5].map(i => <Ic.Star key={i} width={16} height={16} style={{ color: i <= stars ? 'var(--gl-yellow)' : 'var(--gl-muted)' }} />)}
                  </div>
                  <div style={{ fontSize: 13, color: 'var(--gl-ink2)' }}><strong style={{ color: 'var(--gl-ink)', fontSize: 18 }}>{game.rating}</strong> / 5 · {(game.ratingCount||0).toLocaleString()} ratings</div>
                </div>
                <div>
                  <div style={{ fontSize: 28, fontFamily: 'var(--gl-fd)', color: 'var(--gl-accent)', lineHeight: 1 }}>{game.downloads}</div>
                  <div style={{ fontSize: 13, color: 'var(--gl-muted)', marginTop: 4 }}>Downloads</div>
                </div>
              </div>
              {/* Features grid */}
              {game.features?.length > 0 && (
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(220px, 1fr))', gap: 10 }}>
                  {game.features.map((f, i) => (
                    <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10, background: 'var(--gl-card)', border: '1px solid var(--gl-line)', borderRadius: 10, padding: '10px 14px', fontSize: 13, color: 'var(--gl-ink2)' }}>
                      <span style={{ color: 'var(--gl-accent)', fontSize: 14, flexShrink: 0 }}>✓</span> {f}
                    </div>
                  ))}
                </div>
              )}
            </div>
          </div>
        </div>
      </section>

      {/* Videos */}
      {videos.length > 0 && (
        <section className="gl-section">
          <SHead eye="Videos" title="WATCH GAMEPLAY" />
          <div className="gl-auto3">
            {videos.map(v => (
              <div key={v.id} className="gl-card" style={{ overflow: 'hidden' }}>
                <div style={{ position: 'relative', paddingBottom: '56.25%', background: 'var(--gl-bg)' }}>
                  <iframe src={'https://www.youtube.com/embed/' + v.youtubeId} title={v.title}
                    style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', border: 'none' }}
                    allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                    allowFullScreen loading="lazy" />
                </div>
                <div style={{ padding: '14px 16px' }}>
                  <div style={{ fontWeight: 600, fontSize: 14 }}>{v.title}</div>
                  <div style={{ fontSize: 12, color: 'var(--gl-ink2)', marginTop: 4 }}>{v.description}</div>
                </div>
              </div>
            ))}
          </div>
        </section>
      )}

      {/* Tips */}
      {tips.length > 0 && (
        <section className="gl-section" style={{ paddingTop: 0 }}>
          <SHead eye="Pro Tips" title="TIPS & TRICKS" sub={`Level up your ${game.shortTitle || game.title.split('–')[0].trim()} game with these pro strategies.`} />
          <div className="gl-auto">
            {tips.map(t => {
              const dc = diffC[t.difficulty] || diffC.Beginner;
              return (
                <div key={t.id} className="gl-card" style={{ padding: 22, position: 'relative', overflow: 'hidden' }}>
                  <div style={{ position: 'absolute', left: 0, top: 0, bottom: 0, width: 3, background: 'var(--gl-accent)', borderRadius: '0 2px 2px 0' }} />
                  <span style={{ fontSize: 9, fontWeight: 700, letterSpacing: '.1em', textTransform: 'uppercase', padding: '2px 8px', borderRadius: 4, marginBottom: 10, display: 'inline-block', background: dc.bg, color: dc.color }}>{t.difficulty}</span>
                  <div style={{ fontWeight: 700, fontSize: 14, marginBottom: 8 }}>{t.title}</div>
                  <p style={{ fontSize: 13, color: 'var(--gl-ink2)', lineHeight: 1.7 }}>{t.content}</p>
                </div>
              );
            })}
          </div>
        </section>
      )}

      {/* FAQ for this game */}
      {faq.length > 0 && (
        <section className="gl-section" style={{ paddingTop: 0 }}>
          {/* FAQ schema */}
          <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify({
            '@context': 'https://schema.org', '@type': 'FAQPage',
            mainEntity: faq.map(f => ({ '@type': 'Question', name: f.question, acceptedAnswer: { '@type': 'Answer', text: f.answer } }))
          }) }} />
          <SHead eye="FAQ" title={`${game.shortTitle || game.title.split('–')[0].trim().toUpperCase()} FAQ`} />
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10, maxWidth: 760 }}>
            {faq.map((f, i) => (
              <div key={f.id || i} className="gl-card" style={{ overflow: 'hidden', borderColor: openFaq === i ? 'var(--gl-lineA)' : undefined }}>
                <div onClick={() => setOpenFaq(openFaq === i ? null : i)}
                  style={{ padding: '16px 20px', fontWeight: 600, fontSize: 14, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, userSelect: 'none' }}>
                  {f.question}
                  <Ic.Chev width={14} height={14} style={{ flexShrink: 0, transition: 'transform .2s', transform: openFaq === i ? 'rotate(180deg)' : 'none', color: openFaq === i ? 'var(--gl-accent)' : 'var(--gl-muted)' }} />
                </div>
                {openFaq === i && <div style={{ padding: '0 20px 18px', paddingTop: 14, fontSize: 14, color: 'var(--gl-ink2)', lineHeight: 1.75, borderTop: '1px solid var(--gl-line)' }}>{f.answer}</div>}
              </div>
            ))}
          </div>
        </section>
      )}

      {/* CTA + other games */}
      <section className="gl-section" style={{ paddingTop: 0 }}>
        <div className="gl-card" style={{ padding: 'clamp(28px,5vw,52px)', textAlign: 'center', position: 'relative', overflow: 'hidden', marginBottom: 60 }}>
          <div style={{ position: 'absolute', inset: 0, background: 'radial-gradient(ellipse 60% 60% at 50% 0%, var(--gl-dim), transparent)', pointerEvents: 'none' }} />
          <div style={{ position: 'relative' }}>
            <h2 style={{ marginBottom: 14 }}>READY TO PLAY?</h2>
            <p style={{ color: 'var(--gl-ink2)', marginBottom: 28, fontSize: 15 }}>{game.title} is free on Google Play. Download now.</p>
            <a href={game.playStoreUrl} target="_blank" rel="noreferrer" className="gl-btn gl-btn-primary" style={{ padding: '14px 40px', fontSize: 15 }}>
              <Ic.Play width={14} height={14} /> Download Free on Google Play
            </a>
          </div>
        </div>

        {otherGames.length > 0 && (
          <>
            <SHead eye="More Games" title="YOU MIGHT ALSO LIKE" />
            <div className="gl-auto">{otherGames.map(g => <GameCard key={g.id} game={g} badge goto={goto} />)}</div>
          </>
        )}
      </section>
    </>
  );
}

Object.assign(window, { PHome, PGames, PGame, PAbout, PServices, PBlog, PPost, PVideos, PPlayers, PPress, PContact, SupportForm });
