/// <reference lib="dom" />
// Small game demo.

export const game = true

import type { GameContext, InputState } from "@/shared/game"
import { rng } from "@/shared/utils"

const WIDTH = 960
const HEIGHT = 540
const SPEED = 10
let x = rng(0, WIDTH)
let y = rng(0, HEIGHT)

type Cloud = { x: number; y: number; speed: number }
const clouds: Cloud[] = [
  { x: 300, y: 100, speed: 0.7 },
  { x: 600, y: 150, speed: 0.5 },
  { x: 75, y: 220, speed: 0.5 },
]

export function init() { console.log("init") }

export function update(_delta: number, input: InputState) {
  if (input.pressed.has("ArrowUp") || input.pressed.has("w")) y -= 1 * SPEED
  if (input.pressed.has("ArrowDown") || input.pressed.has("s")) y += 1 * SPEED

  if (input.pressed.has("ArrowLeft") || input.pressed.has("a")) x -= 1 * SPEED
  if (input.pressed.has("ArrowRight") || input.pressed.has("d")) x += 1 * SPEED

  for (const cloud of clouds) {
    cloud.x += cloud.speed
    if (cloud.x > WIDTH + 80) { // off screen
      cloud.x = -80
    }
  }
}

export function draw(ctx: GameContext) {
  ctx.clear()

  // sky background
  ctx.rectfill(0, 0, ctx.width, ctx.height, "skyblue")

  // sun
  ctx.circfill(800, 100, 50, "yellow")

  // grass
  ctx.rectfill(0, 400, ctx.width, ctx.height, "green")

  // clouds
  for (const cloud of clouds) {
    drawCloud(ctx, cloud.x, cloud.y)
  }

  // house body
  ctx.rectfill(200, 250, 400, 400, "sienna")

  // roof (triangle-ish with lines)
  ctx.trianglefill(200, 250, 400, 250, 300, 150, "brown")

  // door
  ctx.rectfill(280, 320, 320, 400, "darkred")

  // windows
  ctx.rectfill(220, 270, 260, 310, "lightblue")
  ctx.rectfill(340, 270, 380, 310, "lightblue")

  // player
  ctx.circfill(x, y, 10, "magenta")
  ctx.circ(x, y, 11, "white")

  // tree trunk
  ctx.rectfill(500, 300, 540, 400, "saddlebrown")

  // tree top (a few circles for puffiness)
  ctx.circfill(520, 280, 40, "darkgreen")
  ctx.circfill(480, 300, 40, "darkgreen")
  ctx.circfill(560, 300, 40, "darkgreen")
}

function drawCloud(ctx: GameContext, x: number, y: number) {
  ctx.circfill(x, y, 30, "white")
  ctx.circfill(x + 30, y - 10, 40, "white")
  ctx.circfill(x + 60, y, 30, "white")
  ctx.circfill(x + 30, y + 10, 35, "white")
}