import { Hono } from "hono"
import { Prompt } from "./components/prompt"
import { serveStatic } from "hono/bun"
import { Layout } from "./layout"
import { isFile, transpile } from "./utils"

const app = new Hono()

app.get("/", (c) => c.html(Layout(<Prompt />)))
app.use("/vendor/*", serveStatic({ root: "./public" }))
app.use("/css/*", serveStatic({ root: "./src" }))

app.get("/js/:path{.+}", async (c) => {
  const path = "./src/js/" + c.req.param("path")
  const ts = path.endsWith(".js") ? path.replace(".js", ".ts") : path + ".ts"
  const tsx = path.endsWith(".js") ? path.replace(".js", ".tsx") : path + ".tsx"
  let javascript = ""

  if (isFile(ts)) {
    javascript = await transpile(ts)
  } else if (isFile(tsx)) {
    javascript = await transpile(tsx)
  } else if (isFile(path)) {
    javascript = await Bun.file(path).text()
  } else {
    return c.text("File not found", 404)
  }

  return new Response(javascript, { headers: { "Content-Type": "text/javascript" } })
})

export default app
