import { Hono } from 'hono'
import { readdirSync } from 'fs'
import { join } from 'path'
import { capitalize } from './utils'
import { Layout } from './layout'

const port = process.env.PORT ?? '3100'
const app = new Hono()

app.get('/:file', async c => {
  const file = c.req.param('file') ?? ''
  const fileName = (file).replace('.', '')
  const path = join(process.env.PWD ?? '.', `/src/${fileName}.tsx`)

  if (!(await Bun.file(path).exists()))
    return c.text('404 Not Found', 404)

  const page = await import(path + `?t=${Date.now()}`)
  return c.html(
    <Layout title={`<${capitalize(file)} />`}>
      <page.Test req={c.req} />
    </Layout>
  )
})

app.get('/', c => {
  return c.html(
    <Layout title="🐺 howl" showHomeLink={false}>
      <div style="padding: 24px;">
        <ul style="font-size: 18px; line-height: 2;">
          {testFiles().map(x => (
            <li>
              <a href={`/${x}`} style="color: #3b82f6; text-decoration: none;">
                {x}
              </a>
            </li>
          ))}
        </ul>
      </div>
    </Layout>
  )
})

function testFiles(): string[] {
  return readdirSync('./src')
    .filter(x => x.endsWith('.tsx') && !x.startsWith('index'))
    .map(x => x.replace('.tsx', ''))
    .sort()
}

export default {
  fetch: app.fetch,
  port
}