import { createRoot } from "react-dom/client";
import "./styles/index.css";
import App from "./App";
import { vscode } from "./utils/vscode.js";
import InitForm from "./components/initForm.js";
import type { Suggestion } from "@codeflash/types";
import CodeflashLogo from "./components/logo.js";

window.vscode = vscode;

const isInitViewDisplayed = !!document.getElementById("initview-container");
if (isInitViewDisplayed) {
  let initFormRoot: ReturnType<typeof createRoot> | null = null;

  // will be called from InitWebviewProvider
  window.renderInitForm = function renderInitForm(
    suggestions: Record<string, Suggestion>,
    errorDetails?: string,
    pyprojectPath?: string,
  ) {
    if (!isInitViewDisplayed) {
      return;
    }

    const formContainer = document.getElementById("init-form-container");
    const initContent = document.getElementById("init-content");

    if (!formContainer) {
      console.error("init-form-container element not found");
      return;
    }

    // Hide the init content (loading/steps) and show form container
    if (initContent) {
      initContent.style.display = "none";
    }
    formContainer.style.display = "block";

    // Create root only once to avoid React warnings
    if (!initFormRoot) {
      initFormRoot = createRoot(formContainer);
    }

    initFormRoot.render(
      <InitForm
        suggestions={suggestions}
        errorDetails={errorDetails}
        pyprojectPath={pyprojectPath}
      />,
    );
  };

  /**
   * Function to hide form and show init content (called when returning from form)
   */
  window.hideInitForm = function hideInitForm() {
    const formContainer = document.getElementById("init-form-container");
    const initContent = document.getElementById("init-content");

    if (formContainer && initContent) {
      formContainer.style.display = "none";
      initContent.style.display = "flex";
    }
  };

  createRoot(document.getElementById("codeflash-logo-header")!).render(
    <CodeflashLogo width="80%" height="100%" />,
  );

  import("./initView/script.js");
} else {
  createRoot(document.getElementById("root")!).render(<App />);
}
