/* global React, ReactDOM, HeroStars, PixelIcon, ICON_BUDGET, ICON_TEACH, ICON_CHECK, PROJECTS, Breakout, useTweaks, TweaksPanel, TweakSection, TweakRadio, TweakSlider, TweakToggle, TweakSelect */
const { useEffect, useRef, useState } = React;

const TEAM = [
{
  name: 'Mike Evans',
  role: 'Founder · Engineer · Project Manager',
  bio: "Gaming has been my passion since I was 6 years old, and game development since I was 14. I started off small in GameMaker 2D before quickly moving onto Unity. Now, at 25 years old, I've grown to love development as a whole. Experience in tooling, project management, consulting and developer mentoring now helps enable me to use my game development skills to help others bring their game ideas to fruition.",
  img: 'assets/team-mike.avif',
  links: [{ label: 'mikethedevman.com', url: 'https://mikethedevman.com/' }]
},
{
  name: 'Ben Wilson',
  role: 'Narrative Designer',
  bio: "I have experience as a narrative designer, author, and games journalist. Being a police officer also involved its share of colorful writing. I spend much of my time reveling in the Y2K polygons of the PlayStation 2, playing bad games to see how bad they really are, and watching shows I can't understand in order to learn Spanish.",
  img: 'assets/team-ben.avif',
  links: [
  { label: 'benjensenwilson.com', url: 'https://benjensenwilson.com/' }]

},
{
  name: 'David Haverland',
  role: 'Engineer',
  bio: "Hi I'm Davo, with a Bachelor of Software Engineering, I have been making games and game dev tools for the past three and a half years at SkillsVR. I have spent most of my time creating tools to help speed up the game development process but also enjoy making games as a hobby. While at uni I worked with a team to help ship two games to steam, which both won awards at the NZ Pavs. Making games is a key part of my life and it is important to me to see other peoples visions shipped.",
  img: 'assets/team-david.avif',
  links: [{ label: 'david.sampletextstudios.com', url: 'https://david.sampletextstudios.com' }]
}];


const TESTIMONIALS = [
{
  project: 'RareIcon',
  quote: 'ByteBlast accelerated our Unity engineering by an order of magnitude. With Jigsaw guiding our migration to ECS/DOTS, we reached stable performance at 100,000+ entities in under 60 days.',
  name: 'h0lybyte',
  studio: 'KBVE',
  initials: 'HB',
  accent: 'cyan'
},
{
  project: 'Varadia',
  quote: "ByteBlast's team consistently met deadlines with professionalism and clear communication, helped our technical lead reorganize tasks to get the team back on schedule, and proved himself a valuable addition to our team.",
  name: 'Kanan Vegatti',
  studio: 'Altantra Entertainment',
  initials: 'KV',
  accent: 'amber'
}];


/* ============================================================
   NAV
   ============================================================ */
function Nav() {
  return (
    <nav className="bb-nav">
      <div className="bb-nav-inner">
        <a href="#top" className="bb-brand">
          <img src="assets/byteblast-logo.png" alt="Byte Blast" className="pixelated" />
          <span>BYTE BLAST</span>
        </a>
        <div className="bb-nav-links">
          <a href="#services" className="bb-glitch">Services</a>
          <a href="#projects" className="bb-glitch">Projects</a>
          <a href="#testimonials" className="bb-glitch">Word</a>
          <a href="#team" className="bb-glitch">Team</a>
        </div>
        <a href="https://byteblast.youcanbook.me/" target="_blank" rel="noopener" className="bb-btn" style={{ padding: '10px 14px', fontSize: 10, boxShadow: '4px 4px 0 #000' }}>
          Book Free Call
        </a>
      </div>
    </nav>);

}

/* ============================================================
   HERO
   ============================================================ */
function Hero({ heroVariant }) {
  return (
    <header className="hero" id="top" data-screen-label="Hero">
      <div className="hero-canvas" />
      <HeroStars variant={heroVariant} />
      <div className="hero-grid" />
      <div className="hero-vignette" />
      <div className="hero-scanlines" />

      {/* Floating sprites */}
      <PixelSprite type="coin" className="hero-sprite coin" />
      <PixelSprite type="ship" className="hero-sprite ship" />
      <PixelSprite type="star" className="hero-sprite star" />

      <div className="hero-inner">
        <div>
          <div className="hero-tag" data-comment-anchor="fcfd7ab463-div-94-11">
            <span className="blink" />
            <span>ACCEPTING CLIENTS</span>
          </div>
          <h1 className="hero-title">
            Let's Realize Your <span className="pop" data-comment-anchor="3801cdb01e-span-99-32">Awesome</span> Game Ideas
          </h1>
          <p className="hero-sub">
            High-quality, budget-conscious game development services and Unity tutoring. Our talented developers, designers and consultants are ready to bring your vision to life.
          </p>
          <div className="hero-ctas">
            <a href="https://byteblast.youcanbook.me/" target="_blank" rel="noopener" className="bb-btn">
              ▶ Book A Free Consultation
            </a>
            <a href="#projects" className="bb-btn bb-btn--ghost">
              View Past Work
            </a>
          </div>
          <div className="hero-stats">
            <div className="hero-stat"><span className="num">15+</span><span className="lbl">Shipped Titles</span></div>
            <div className="hero-stat" data-comment-anchor="b5c876e1f2-div-114-13"><span className="num">∞</span><span className="lbl">Lives Remaining</span></div>
          </div>
        </div>

        <div className="hero-cabinet">
          <div className="hero-cabinet-frame">
            <div className="hero-cabinet-marquee">★ INSERT COIN ★</div>
            <div className="hero-cabinet-screen">
              <img src="assets/byteblast-logo.png" alt="Byte Blast logo" className="pixelated" />
            </div>
            <div className="hero-cabinet-controls">
              <div className="hero-cabinet-joystick" />
              <div className="hero-cabinet-buttons">
                <span /><span /><span />
              </div>
            </div>
          </div>
        </div>
      </div>
    </header>);

}

function PixelSprite({ type, className }) {
  // Tiny inline SVG sprites — pixelated with shape-rendering
  const sprites = {
    coin:
    <svg width="40" height="40" viewBox="0 0 10 10" shapeRendering="crispEdges">
        {[
      '..####..',
      '.######.',
      '######.#',
      '######.#',
      '######.#',
      '######.#',
      '.######.',
      '..####..'].
      map((row, y) => row.split('').map((c, x) =>
      c === '#' ? <rect key={`${x}-${y}`} x={x + 1} y={y + 1} width="1" height="1" fill="#ffb627" /> :
      c === '.' ? null : null
      ))}
      </svg>,

    ship:
    <svg width="56" height="40" viewBox="0 0 14 10" shapeRendering="crispEdges">
        {[
      '......##......',
      '.....####.....',
      '....######....',
      '...########...',
      '..####..####..',
      '.####....####.',
      '..#.######.#..',
      '..............',
      '...#......#...',
      '..............'].
      map((row, y) => row.split('').map((c, x) =>
      c === '#' ? <rect key={`${x}-${y}`} x={x} y={y} width="1" height="1" fill="#5be7ff" /> : null
      ))}
      </svg>,

    star:
    <svg width="32" height="32" viewBox="0 0 8 8" shapeRendering="crispEdges">
        {[
      '...##...',
      '...##...',
      '##.##.##',
      '########',
      '########',
      '##.##.##',
      '...##...',
      '...##...'].
      map((row, y) => row.split('').map((c, x) =>
      c === '#' ? <rect key={`${x}-${y}`} x={x} y={y} width="1" height="1" fill="#ffb627" /> : null
      ))}
      </svg>

  };
  return <div className={className} aria-hidden="true">{sprites[type]}</div>;
}

/* ============================================================
   VALUE PROPS
   ============================================================ */
function Values() {
  return (
    <section className="bb-section" id="services" data-screen-label="Services">
      <div className="bb-wrap">
        <div className="bb-eyebrow">02 · WHAT WE DO</div>
        <h2 className="bb-section-title">Two paths. One studio.</h2>
        <p className="bb-section-lede" style={{ marginBottom: 56 }}>
          Whether you need a partner to ship your game or a guide to level up your engineering team, we've got a quarter for that.
        </p>

        <div className="values-grid" data-comment-anchor="e98a613466-div-208-9">
          <div className="value-card">
            <PixelIcon pattern={ICON_BUDGET} color="var(--bb-cyan)" />
            <h3>Game Development for Every Budget</h3>
            <p>
              Our expert team is dedicated to creating engaging gaming experiences without breaking the bank. We will work with you to find a good balance between cost and what your project can become.
            </p>
            <ul>
              <li>Architecture & engineering on Unity / C#</li>
              <li>Performance work — ECS / DOTS migrations, profiling, memory</li>
              <li>Production support, planning and team mentorship</li>
            </ul>
          </div>

          <div className="value-card value-card-accent">
            <PixelIcon pattern={ICON_TEACH} color="var(--bb-amber)" />
            <h3>Expert Tutoring for Unity Developers</h3>
            <p>Sharpen your skills with industry professionals who've actually shipped games.</p>
            <ul>
              <li>One-on-one sessions with industry professionals</li>
              <li>Flexible scheduling around your timezone</li>
              <li>Hands-on projects, not slide decks</li>
            </ul>
            <div className="footnote">※ C# knowledge required</div>
          </div>
        </div>
      </div>
    </section>);

}

/* ============================================================
   PROJECTS
   ============================================================ */
function Projects() {
  return (
    <section className="bb-section" id="projects" data-screen-label="Projects">
      <div className="bb-wrap">
        <div className="bb-eyebrow">03 · HIGH SCORES</div>
        <h2 className="bb-section-title">Selected Projects</h2>
        <p className="bb-section-lede" style={{ marginBottom: 56 }}>
          A handful of recent collaborations — click any cabinet to see it on Steam or the studio's site.
        </p>

        <div className="projects-grid">
          {PROJECTS.map((p) => {
            const Art = p.Art;
            return (
              <div key={p.title} className="project-card">
                <a href={p.url} target="_blank" rel="noopener" className="project-card-link">
                  <div className="crt-bezel">
                    <div className="crt-bezel-screen">
                      <Art />
                    </div>
                  </div>
                  <div className="project-meta">
                    <div>
                      <div className="project-title">{p.title}</div>
                      <div className="project-platform">{p.platform}</div>
                    </div>
                    <div className="project-arrow">▸▸</div>
                  </div>
                </a>
                <button
                  type="button"
                  className="project-case-btn"
                  onMouseEnter={(e) => {e.currentTarget.dataset.hover = '1';}}
                  onMouseLeave={(e) => {delete e.currentTarget.dataset.hover;}}
                  onFocus={(e) => {e.currentTarget.dataset.hover = '1';}}
                  onBlur={(e) => {delete e.currentTarget.dataset.hover;}}
                  aria-label="Case study coming soon">
                  <span className="default-label">▸ Read Case Study</span>
                  <span className="hover-label">⌛ Coming Soon</span>
                </button>
              </div>);

          })}
        </div>
      </div>
    </section>);

}

/* ============================================================
   TESTIMONIALS
   ============================================================ */
function Testimonials() {
  return (
    <section className="bb-section" id="testimonials" data-screen-label="Testimonials">
      <div className="bb-wrap">
        <div className="bb-eyebrow">04 · WORD ON THE STREET</div>
        <h2 className="bb-section-title">What clients say.</h2>
        <p className="bb-section-lede" style={{ marginBottom: 56 }}>
          Studios who've shipped with Byte Blast — in their own words.
        </p>

        <div className="tes-grid">
          {TESTIMONIALS.map((t) =>
          <figure key={t.name} className={`tes-card ${t.accent === 'amber' ? 'amber' : ''}`}>
              <div className="tes-tag">▶ {t.project.toUpperCase()}</div>
              <blockquote className="tes-quote">{t.quote}</blockquote>
              <figcaption className="tes-attr">
                <div className="tes-avatar">{t.initials}</div>
                <div>
                  <div className="tes-attr-name">{t.name}</div>
                  <div className="tes-attr-studio">{t.studio}</div>
                </div>
              </figcaption>
            </figure>
          )}
        </div>
      </div>
    </section>);

}

/* ============================================================
   TEAM — with pixelate canvas
   ============================================================ */
function Pixelate({ src, alt, size = 120, factor = 1.5 }) {
  const canvasRef = useRef(null);
  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext('2d');
    const dpr = 1;
    canvas.width = size * dpr;
    canvas.height = size * dpr;
    const img = new Image();
    img.crossOrigin = 'anonymous';
    img.onload = () => {
      // Draw small, then scale up with smoothing off
      const lo = Math.floor(size / factor);
      const off = document.createElement('canvas');
      off.width = lo;off.height = lo;
      const octx = off.getContext('2d');
      octx.imageSmoothingEnabled = false;
      // cover crop
      const ar = img.width / img.height;
      let sw = img.width,sh = img.height,sx = 0,sy = 0;
      if (ar > 1) {sw = img.height;sx = (img.width - sw) / 2;} else
      {sh = img.width;sy = (img.height - sh) / 2;}
      octx.drawImage(img, sx, sy, sw, sh, 0, 0, lo, lo);
      // posterize colors slightly toward palette
      const data = octx.getImageData(0, 0, lo, lo);
      for (let i = 0; i < data.data.length; i += 4) {
        // quantize gently (8 levels)
        data.data[i] = Math.round(data.data[i] / 32) * 32;
        data.data[i + 1] = Math.round(data.data[i + 1] / 32) * 32;
        data.data[i + 2] = Math.round(data.data[i + 2] / 32) * 32;
      }
      octx.putImageData(data, 0, 0);
      ctx.imageSmoothingEnabled = false;
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      ctx.drawImage(off, 0, 0, canvas.width, canvas.height);
    };
    img.src = src;
  }, [src, size, factor]);
  return <canvas ref={canvasRef} aria-label={alt} role="img" style={{ width: size, height: size, imageRendering: 'pixelated' }} />;
}

function Team() {
  return (
    <section className="bb-section" id="team" data-screen-label="Team">
      <div className="bb-wrap">
        <div className="bb-eyebrow">05 · MEET PLAYER 1, 2 & 3</div>
        <h2 className="bb-section-title">Who are you working with?</h2>
        <p className="bb-section-lede" style={{ marginBottom: 56 }}>
          A small team of senior Unity engineers, designers and tutors. No agencies. No middlemen.
        </p>

        <div className="team-grid">
          {TEAM.map((m) =>
          <article key={m.name} className="team-card">
              <div className="team-portrait">
                <Pixelate src={m.img} alt={m.name} />
              </div>
              <div>
                <h3 className="team-name">{m.name}</h3>
                <div className="team-role">{m.role}</div>
              </div>
              <p className="team-bio">{m.bio}</p>
              {m.links.length > 0 &&
            <div className="team-links">
                  {m.links.map((l) =>
              <a key={l.url} href={l.url} target="_blank" rel="noopener" className="team-link">{l.label} ↗</a>
              )}
                </div>
            }
            </article>
          )}
        </div>
      </div>
    </section>);

}

/* ============================================================
   CTA + Footer
   ============================================================ */
function ClosingCTA() {
  return (
    <section className="cta-section" id="contact" data-screen-label="Closing CTA">
      <div className="cta-grid-bg" />
      <div className="bb-wrap cta-inner">
        <div className="bb-eyebrow" style={{ justifyContent: 'center' }}>06 · READY PLAYER ONE</div>
        <h2 className="cta-title">
          So What Are You Waiting For?<span className="blink-cur" />
        </h2>
        <p className="cta-sub">
          Pitch us your game. Or your stuck-in-mud Unity build. Or your half-baked idea on a napkin. The first call's free, and we'll tell you straight whether we can help.
        </p>
        <a href="https://byteblast.youcanbook.me/" target="_blank" rel="noopener" className="bb-btn" style={{ fontSize: 14, padding: '22px 32px' }}>
          ▶ Book A Free Consultation
        </a>
        <div style={{ marginTop: 28, fontFamily: 'var(--bb-mono)', fontSize: 11, color: 'var(--bb-mute)', letterSpacing: '0.16em' }}>
          PSST · TRY THE KONAMI CODE
        </div>
      </div>
    </section>);

}

function Footer() {
  return (
    <footer className="bb-footer">
      <div className="bb-wrap" style={{ display: 'flex', flexDirection: 'column', gap: 16, alignItems: 'center' }}>
        <img src="assets/byteblast-logo.png" alt="" className="pixelated" style={{ width: 48, height: 48 }} />
        <div>® 2025 BYTE BLAST · ALL RIGHTS RESERVED</div>
      </div>
    </footer>);

}

/* ============================================================
   APP
   ============================================================ */
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "palette": "classic",
  "pixelFont": "presstart",
  "heroVariant": "starfield",
  "scanlineIntensity": 0.08,
  "crtMode": false
} /*EDITMODE-END*/;

function App() {
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [konamiOpen, setKonamiOpen] = useState(false);

  // Apply palette + pixel font + scanlines
  useEffect(() => {
    const html = document.documentElement;
    html.classList.remove('palette-classic', 'palette-magenta', 'palette-amber', 'palette-phosphor');
    html.classList.add(`palette-${tweaks.palette}`);
    html.dataset.pixelFont = tweaks.pixelFont;
    html.style.setProperty('--scanline-opacity', String(tweaks.scanlineIntensity));
    html.classList.toggle('crt-mode', !!tweaks.crtMode);
  }, [tweaks.palette, tweaks.pixelFont, tweaks.scanlineIntensity, tweaks.crtMode]);

  // Konami listener
  useEffect(() => {
    const seq = ['ArrowUp', 'ArrowUp', 'ArrowDown', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'ArrowLeft', 'ArrowRight', 'b', 'a'];
    let buffer = [];
    const onKey = (e) => {
      buffer.push(e.key);
      if (buffer.length > seq.length) buffer = buffer.slice(-seq.length);
      if (buffer.length === seq.length && buffer.every((k, i) =>
      k.toLowerCase() === seq[i].toLowerCase()
      )) {
        setKonamiOpen(true);
        buffer = [];
      }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, []);

  return (
    <>
      <Nav />
      <main>
        <Hero heroVariant={tweaks.heroVariant} />
        <Values />
        <Projects />
        <Testimonials />
        <Team />
        <ClosingCTA />
      </main>
      <Footer />

      {konamiOpen && <Breakout onClose={() => setKonamiOpen(false)} />}

      <TweaksPanel title="Tweaks">
        <TweakSection title="Palette">
          <TweakRadio
            label="Theme"
            value={tweaks.palette}
            onChange={(v) => setTweak('palette', v)}
            options={[
            { value: 'classic', label: 'Classic' },
            { value: 'magenta', label: 'Magenta' },
            { value: 'amber', label: 'Amber' },
            { value: 'phosphor', label: 'Phosphor' }]
            } />
          
        </TweakSection>

        <TweakSection title="Typography">
          <TweakRadio
            label="Pixel Font"
            value={tweaks.pixelFont}
            onChange={(v) => setTweak('pixelFont', v)}
            options={[
            { value: 'presstart', label: 'Press Start' },
            { value: 'silkscreen', label: 'Silkscreen' },
            { value: 'vt323', label: 'VT323' }]
            } />
          
        </TweakSection>

        <TweakSection title="Hero Animation">
          <TweakRadio
            label="Variant"
            value={tweaks.heroVariant}
            onChange={(v) => setTweak('heroVariant', v)}
            options={[
            { value: 'starfield', label: 'Starfield' },
            { value: 'cityscape', label: 'Cityscape' },
            { value: 'wordmark', label: 'Snowfall' }]
            } />
          
        </TweakSection>

        <TweakSection title="CRT Effects">
          <TweakSlider
            label="Scanline Intensity"
            value={tweaks.scanlineIntensity}
            min={0} max={0.3} step={0.01}
            onChange={(v) => setTweak('scanlineIntensity', v)} />
          
          <TweakToggle
            label="Full-page CRT mode"
            value={tweaks.crtMode}
            onChange={(v) => setTweak('crtMode', v)} />
          
        </TweakSection>

        <TweakSection title="Easter egg">
          <div style={{ fontSize: 11, color: '#9aa6c8', lineHeight: 1.5 }}>
            Try the Konami code:<br />
            ↑ ↑ ↓ ↓ ← → ← → B A
          </div>
        </TweakSection>
      </TweaksPanel>
    </>);

}

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