import { WorkerEntrypoint } from 'cloudflare:workers';
import { handleApi } from './api';
import { handleNewsletter } from './newsletter';
import type { Env } from './env';

function htmlResponse(html: string, init: ResponseInit = {}): Response {
  const headers = new Headers(init.headers);
  headers.set('Content-Type', 'text/html; charset=utf-8');
  headers.set('Cache-Control', 'no-store');
  return new Response(html, { ...init, headers });
}

export default class extends WorkerEntrypoint<Env> {
  async fetch(request: Request): Promise<Response> {
    const url = new URL(request.url);

    if (url.pathname === '/healthz') {
      return Response.json({ ok: true, env: this.env.APP_ENV });
    }

    if (url.pathname === '/api/status') {
      return Response.json({
        ok: true,
        env: this.env.APP_ENV,
        mailboxEmail: this.env.MAILBOX_EMAIL,
        now: new Date().toISOString(),
      });
    }

    const apiResponse = await handleApi(request, this.env);
    const newsletterResponse = await handleNewsletter(request, this.env);
    if (apiResponse) {
      return apiResponse;
    }

    if (newsletterResponse) {
      return newsletterResponse;
    }

    if (url.pathname === '/' || url.pathname === '/ui') {
      const html = `<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>CULTSCALE OS</title>
    <style>
      :root {
        --cult-black: #121212;
        --cult-accent: #1f1f1f;
        --cult-gray: #e6e6e6;
        --cult-white: #ffffff;
        --cult-gold: #b78a3c;
      }
      body {
        margin: 0;
        background: var(--cult-black);
        color: var(--cult-gray);
        font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto,
          Helvetica, Arial, "Apple Color Emoji", "Segoe UI Emoji";
        line-height: 1.45;
      }
      a {
        color: var(--cult-white);
        text-decoration: none;
        border-bottom: 1px solid rgba(255, 255, 255, 0.25);
      }
      a:hover {
        border-bottom-color: var(--cult-gold);
      }
      .wrap {
        max-width: 980px;
        margin: 0 auto;
        padding: 40px 20px;
      }
      .card {
        background: var(--cult-accent);
        border: 1px solid rgba(255, 255, 255, 0.08);
        border-radius: 16px;
        padding: 20px;
      }
      h1 {
        margin: 0 0 10px;
        color: var(--cult-white);
        font-size: 28px;
        letter-spacing: 0.02em;
      }
      .tagline {
        margin: 0 0 18px;
        color: var(--cult-gray);
        opacity: 0.9;
      }
      .meta {
        display: grid;
        grid-template-columns: 1fr;
        gap: 10px;
        margin-top: 16px;
        font-size: 14px;
      }
      .pill {
        display: inline-block;
        padding: 3px 10px;
        border-radius: 999px;
        background: rgba(183, 138, 60, 0.12);
        color: var(--cult-gold);
        border: 1px solid rgba(183, 138, 60, 0.25);
        font-weight: 600;
        letter-spacing: 0.02em;
      }
      code {
        font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas,
          "Liberation Mono", "Courier New", monospace;
        font-size: 0.95em;
      }
    </style>
  </head>
  <body>
    <div class="wrap">
      <div class="card">
        <div class="pill">LIVE</div>
        <h1>CULTSCALE OS</h1>
        <p class="tagline">Infrastructure for independent cinema.</p>

        <div class="meta">
          <div><strong>Environment:</strong> <code>${this.env.APP_ENV}</code></div>
          <div><strong>Mailbox:</strong> <code>${this.env.MAILBOX_EMAIL}</code></div>
          <div>
            <strong>Endpoints:</strong>
            <a href="/healthz">/healthz</a>,
            <a href="/api/status">/api/status</a>,
            <a href="/api/projects">/api/projects</a>,
            <a href="/api/tasks">/api/tasks</a>
          </div>
        </div>
      </div>
    </div>
  </body>
</html>`;
      return htmlResponse(html);
    }

    return new Response('Not Found', { status: 404 });
  }

  async scheduled(): Promise<void> {
    // Mailbox sync will run here (every 5 minutes).
  }
}
