import Head from "next/head";
import Image from "next/image";
import styles from "../styles/Home.module.css";

import React from "react";

if (typeof window !== "undefined") {
  globalThis.Scan = await import("../lib/scan");
  await import("../lib/api.ts");
}

export async function getStaticProps(ctx) {
  return {
    props: {
      code: Bun.readFile(
        "/Users/jarred/Build/es-module-lexer/test/samples/magic-string.js"
      ),
      defaultFile: "magic-string.js",
    },
  };
}

var textDecoder = new TextDecoder();
export default function Home({ code, defaultFile }) {
  const fileNameRef = React.useRef();
  const [lexer, setLexer] = React.useState("");
  const [bunResult, setBunResult] = React.useState("");
  const [file, setFile] = React.useState(defaultFile);
  React.useEffect(() => {
    globalThis.Scan.start();
  }, []);

  const runBuild = React.useCallback(
    (event) => {
      globalThis.Scan.transform(
        event.target.value,
        fileNameRef.current.value
      ).then((result) => {
        setLexer(JSON.stringify(result.lexer, null, 2));
        setBunResult(JSON.stringify(result.bun, null, 2));
      }, console.error);
    },
    [fileNameRef, setBunResult, setLexer]
  );
  return (
    <div className={styles.container}>
      <Head>
        <title>Next.js</title>
        <meta name="description" content="Generated by create next app" />
        <link rel="icon" href="/favicon.ico" />
      </Head>

      <main className={styles.main}>
        <div>
          <input
            autoComplete="filename"
            type="text"
            placeholder="filename"
            value={file}
            onChange={(event) => setFile(event.target.value)}
            ref={fileNameRef}
          />
          <textarea onChange={runBuild} defaultValue={code}></textarea>

          <textarea readOnly value={bunResult}></textarea>
          <textarea readOnly value={lexer}></textarea>
        </div>
      </main>
    </div>
  );
}
