import type { Plugin } from "vite";

const EDITOR_EMBED_URL =
  "https://cdn.juo.io/web/blocks/juo/editor/{{ editorVersion }}/juo-editor.embed.js";

export default function juo(): Plugin {
  return {
    name: "juo-editor",

    configureServer(server) {
      server.middlewares.use("/editor", (_req, res) => {
        res.writeHead(200, { "Content-Type": "text/html" });
        res.end(`<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Juo Blocks Editor</title>
    <link rel="preconnect" href="https://rsms.me/" />
    <link rel="stylesheet" href="https://rsms.me/inter/inter.css" />
    <style>
      html, body { margin: 0; padding: 0; height: 100%; overflow: hidden; font-family: InterVariable, Inter, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; }
      juo-editor { display: block; height: 100vh; }
    </style>
  </head>
  <body>
    <script type="module" src="${EDITOR_EMBED_URL}"></script>
    <juo-editor url="/?editor=true"></juo-editor>
  </body>
</html>`);
      });

      server.httpServer?.once("listening", () => {
        const address = server.httpServer?.address();
        const port =
          address && typeof address === "object" ? address.port : 5174;
        const base = `http://localhost:${port}`;
        server.config.logger.info(
          `\n  juo editor        ${base}/editor` +
            `\n  editor view mode  ${base}/` +
            `\n  blocks bundle     ${base}/src/main.ts\n`,
        );
      });
    },
  };
}
