/**
 * Mounts the overlay Vue app inside a closed shadow root appended to
 * document.documentElement — the host page's CSS and CSP stay untouched.
 *
 * Styles strategy: Vite extracts everything imported by the content entry
 * (kit.css, phosphor icons, SFC styles) into assets/style.css. At runtime we
 * fetch it from the extension bundle, rewrite the kit's absolute /assets/ font
 * URLs to extension URLs, and adopt it as a constructable stylesheet — no
 * <style> injection into the page, so strict style-src pages stay happy.
 */
import { createApp, reactive } from "vue";
import browser from "webextension-polyfill";
import App from "./App.vue";
import "./overlay.css";
import "gnexus-ui-kit/dist/css/kit.css";
import "gnexus-ui-kit/dist/assets/fonts/phosphor-icons/src/css/icons.css";

export interface OverlayState {
  mode: "idle" | "picker";
  recording: boolean;
}

export interface Overlay {
  startPicker: () => void;
  setRecorderState: (recording: boolean) => void;
  destroy: () => void;
}

function rewriteKitAssetUrls(css: string): string {
  const base = browser.runtime.getURL("");
  return css
    .replaceAll("url(/assets/", `url(${base}assets/`)
    .replaceAll('url("/assets/', `url("${base}assets/`)
    .replaceAll("url('/assets/", `url('${base}assets/`);
}

export function mountOverlay(): Overlay {
  const host = document.createElement("div");
  host.id = "ltt-overlay-host";
  host.style.cssText = "all: initial; position: fixed; inset: 0; z-index: 2147483647; pointer-events: none;";
  document.documentElement.appendChild(host);

  const shadowRoot = host.attachShadow({ mode: "closed" });
  const mountPoint = document.createElement("div");
  mountPoint.style.cssText = "all: initial; pointer-events: none; width: 100%; height: 100%;";
  shadowRoot.appendChild(mountPoint);

  const state = reactive<OverlayState>({ mode: "idle", recording: false });
  const app = createApp(App, { state });
  app.mount(mountPoint);

  // styles load asynchronously; the overlay works unstyled until then
  void (async () => {
    try {
      const url = browser.runtime.getURL("assets/style.css");
      const text = await (await fetch(url)).text();
      const sheet = new CSSStyleSheet();
      sheet.replaceSync(rewriteKitAssetUrls(text));
      shadowRoot.adoptedStyleSheets = [...shadowRoot.adoptedStyleSheets, sheet];
    } catch {
      // styles are cosmetic — the overlay must keep working without them
    }
  })();

  return {
    startPicker: () => {
      state.mode = "picker";
state.recording = false;
    },
    setRecorderState: (recording: boolean) => {
      // only toggles the bar; picking stays opt-in via the bar's Note button
      state.recording = recording;
      if (!recording && state.mode === "picker") state.mode = "idle";
    },
    destroy: () => {
      app.unmount();
      host.remove();
    },
  };
}