import { getWorldshaperStudioBodyMarkup, buildWorldshaperStudioStyles } from "./dom";
import {
  loadWorldshaperStudioBootstrap,
  loadStandaloneWorldshaperBootstrap,
} from "./bootstrap";
import { startWorldshaperStudio } from "./runtime";
import { applyWorldshaperThemePreset, fetchEditorSettings, getDefaultEditorSettings } from "./themePresets";

const POPUP_STYLE_ID = "worldshaper-studio-styles";

function ensurePopupStyles(): void {
  let styleEl = document.getElementById(POPUP_STYLE_ID) as HTMLStyleElement | null;
  if (!styleEl) {
    styleEl = document.createElement("style");
    styleEl.id = POPUP_STYLE_ID;
    document.head.appendChild(styleEl);
  }
  styleEl.textContent = buildWorldshaperStudioStyles();
}

function renderError(message: string): void {
  document.title = "Worldshaper";
  document.body.innerHTML = "";
  document.body.style.margin = "0";
  document.body.style.minHeight = "100vh";
  document.body.style.display = "grid";
  document.body.style.placeItems = "center";
  document.body.style.background = "#0a1020";
  document.body.style.color = "#d8e8ff";
  document.body.style.fontFamily = "Segoe UI, Arial, sans-serif";

  const panel = document.createElement("div");
  panel.style.maxWidth = "460px";
  panel.style.padding = "24px";
  panel.style.border = "1px solid #2e426c";
  panel.style.borderRadius = "10px";
  panel.style.background = "#0e1a33";
  panel.style.boxShadow = "0 12px 36px rgba(3, 8, 18, 0.45)";

  const heading = document.createElement("h1");
  heading.textContent = "Worldshaper Studio unavailable";
  heading.style.margin = "0 0 8px";
  heading.style.fontSize = "18px";

  const text = document.createElement("p");
  text.textContent = message;
  text.style.margin = "0";
  text.style.fontSize = "14px";
  text.style.lineHeight = "1.5";

  panel.appendChild(heading);
  panel.appendChild(text);
  document.body.appendChild(panel);
}

function renderLoading(message: string): void {
  document.title = "Worldshaper";
  document.body.innerHTML = "";
  document.body.style.margin = "0";
  document.body.style.minHeight = "100vh";
  document.body.style.display = "grid";
  document.body.style.placeItems = "center";
  document.body.style.background = "#0a1020";
  document.body.style.color = "#d8e8ff";
  document.body.style.fontFamily = "Segoe UI, Arial, sans-serif";

  const panel = document.createElement("div");
  panel.style.maxWidth = "460px";
  panel.style.padding = "24px";
  panel.style.border = "1px solid #223557";
  panel.style.borderRadius = "10px";
  panel.style.background = "#0e1a33";
  panel.style.boxShadow = "0 12px 36px rgba(3, 8, 18, 0.32)";

  const heading = document.createElement("h1");
  heading.textContent = "Loading Worldshaper Studio";
  heading.style.margin = "0 0 8px";
  heading.style.fontSize = "18px";

  const text = document.createElement("p");
  text.textContent = message;
  text.style.margin = "0";
  text.style.fontSize = "14px";
  text.style.lineHeight = "1.5";

  panel.appendChild(heading);
  panel.appendChild(text);
  document.body.appendChild(panel);
}

async function initWorldshaperStudioPopup(): Promise<void> {
  ensurePopupStyles();
  renderLoading("Preparing world data...");
  const params = new URLSearchParams(window.location.search);
  const token = params.get("token")?.trim() || "";
  const requestedWorldId = params.get("worldId")?.trim() || params.get("mapId")?.trim() || "";
  let bootstrap = loadWorldshaperStudioBootstrap(token);

  if (!bootstrap) {
    try {
      bootstrap = await loadStandaloneWorldshaperBootstrap(requestedWorldId, window.location.origin);
    } catch (error) {
      renderError(String(error || "Failed to load the Worldshaper Studio."));
      return;
    }
  }

  if (!bootstrap) {
    renderError("No world data was available for the editor.");
    return;
  }

  const editorSettings = await fetchEditorSettings(bootstrap.apiBase).catch(() => getDefaultEditorSettings());
  applyWorldshaperThemePreset(editorSettings.worldshaperStudio.themePreset);
  document.body.removeAttribute("style");
  document.body.innerHTML = getWorldshaperStudioBodyMarkup();
  document.title = "Worldshaper Studio - " + (bootstrap.mapName || bootstrap.mapId || "Untitled");
  startWorldshaperStudio(bootstrap, editorSettings);
}

void initWorldshaperStudioPopup();

