/** @jsx h */
import { h, render, Component } from 'nano-jsx'

class RickGamePanel extends Component {
  refs: { [key: string]: any } = {}
  canvas?: HTMLCanvasElement
  ctx?: CanvasRenderingContext2D
  x = 20
  y = 180
  vy = 0
  onGround = false
  gravity = 0.7
  jumpPower = -12
  isGameOver = false

  frame() {
    if (!this.ctx || this.isGameOver) return

    this.vy += this.gravity
    this.y += this.vy

    if (this.y >= 180) {
      this.y = 180
      this.vy = 0
      this.onGround = true
    }

    if (this.x > 250 && this.y > 160) {
      // Loss condition (simple hazard)
      this.isGameOver = true
      window.open('https://www.youtube.com/watch?v=dQw4w9WgXcQ', '_blank')
      return
    }

    this.draw()
    requestAnimationFrame(() => this.frame())
  }

  draw() {
    if (!this.ctx) return
    this.ctx.clearRect(0, 0, 300, 200)

    // Ground
    this.ctx.fillStyle = '#ccc'
    this.ctx.fillRect(0, 190, 300, 10)

    // Hazard block
    this.ctx.fillStyle = '#f33'
    this.ctx.fillRect(250, 180, 20, 10)

    // Player
    this.ctx.fillStyle = '#007bff'
    this.ctx.fillRect(this.x, this.y, 10, 10)
  }

  handleJump = () => {
    if (this.onGround) {
      this.vy = this.jumpPower
      this.onGround = false
    }
  }

  mounted() {
    this.canvas = this.refs['game'] as HTMLCanvasElement
    this.ctx = this.canvas?.getContext('2d') || undefined

    this.canvas?.addEventListener('click', this.handleJump)
    this.frame()
  }


  render() {
    return (
      <div
        style="
          background: #fefefe;
          color: #111;
          font-family: sans-serif;
          padding: 16px;
          border: 1px solid #ccc;
          border-radius: 10px;
          width: fit-content;
          box-shadow: 0 0 10px rgba(0,0,0,0.1);
        "
      >
        <div style="margin-bottom: 10px;">
          <strong>🎮 Rickjump Game</strong>
        </div>

        <canvas
          width="300"
          height="200"
          ref="game"
          style="border: 1px solid #aaa; background: #fff;"
        ></canvas>

        <div
          onclick={() =>
            window.open('https://www.youtube.com/watch?v=ZcoqR9Bwx1Y', '_blank')
          }
          style="margin-top: 14px; color: #666; font-size: 0.8em; cursor: pointer; text-decoration: underline;"
        >
          sans.
        </div>
      </div>
    )
  }
}

export function insertRickPanel(target: HTMLElement | string = document.body): void {
  const container = typeof target === 'string'
    ? document.querySelector(target)
    : target

  if (container instanceof HTMLElement) {
    render(<RickGamePanel />, container)
  }
}
