import { defineConfig } from "vite";
import solid from "solid-start";
import Icons from "unplugin-icons/vite";
import { promises as fs } from "fs";

const cleanSvg = (svgString: string) => {
  const foundSvgs = new RegExp("^[\\s\\S]*(<svg[\\s\\S]*)$", "m").exec(
    svgString
  );
  if (!foundSvgs || !foundSvgs[1]) {
    throw new Error("Svg was not readable");
  }

  let result = foundSvgs[1];
  result = result.replaceAll("\n", "");
  // Removing aria attributes because they screw up the lighthouse score :/
  result = result.replaceAll(/aria-\S+=".*?"/g, "");

  return result;
};

export default defineConfig({
  server: {
    host: "0.0.0.0",
  },
  ssr: {
    noExternal: ["solid-confetti-explosion"],
  },
  define: {
    __APP_VERSION__: JSON.stringify(process.env.npm_package_version),
    __BUILD_TIME__: JSON.stringify(new Date().getTime()),
  },
  plugins: [
    Icons({
      compiler: "solid",
      customCollections: {
        custom: {
          icon: () =>
            fs.readFile("./assets/icon-path.svg", "utf-8").then(cleanSvg),
          "lufrai-logo": () =>
            fs
              .readFile("./assets/lufrai/logo-current.svg", "utf-8")
              .then(cleanSvg),
          "lufrai-logo-www": () =>
            fs
              .readFile("./assets/lufrai/logo-www-current.svg", "utf-8")
              .then(cleanSvg),
        },
      },
      iconCustomizer(collection, icon, props) {
        if (collection !== "custom") {
          return;
        }

        // TODO: Icons should be coded like this: <AppIcon width="1em" height="100%" /> but this results in a rendering issue:
        // Discussion: https://discord.com/channels/722131463138705510/722167424186843267/989162440342241281
        // Workaround: We manually set width/height = 100% and override width css classes
        props.width = "100%";
        props.height = "100%";
      },
    }),
    solid(),
  ],
});
