import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App.jsx";
import "./index.css";
import "./styles/widget.css";

// Attach the widget to a Shadow DOM host and inject CSS inside the shadow root
(async function mountWideAccessWidget() {
  const hostId = "wideaccess-widget-host";
  let host = document.getElementById(hostId);
  if (!host) {
    host = document.createElement("div");
    host.id = hostId;
    document.body.appendChild(host);
  }

  if (!host.attachShadow) {
    return;
  }
  const shadow = host.shadowRoot || host.attachShadow({ mode: "open" });
  // Expose for other modules (modals) to mount into the shadow root
  try {
    window.__WIDEACCESS_HOST__ = host;
    window.__WIDEACCESS_SHADOW__ = shadow;
  } catch (_) {}

  // Create container inside shadow for React
  let container = shadow.getElementById ? shadow.getElementById("wideaccess-widget-root") : null;
  if (!container) {
    container = document.createElement("div");
    container.id = "wideaccess-widget-root";
    shadow.appendChild(container);
  }

  // Load compiled CSS from WPWidgetConfig.cssUrl or from CDN (same folder where JS is hosted)
  try {
    // Check window.WPWidgetConfig.cssUrl first (for WordPress plugin), then fall back to env variable
    const cssUrl = window.WPWidgetConfig?.cssUrl;
    const res = await fetch(cssUrl, { credentials: "omit" });
    if (!res.ok) {
      console.error('[WideAccess] Failed to load CSS from', cssUrl);
      return;
    }
    const css = await res.text();
    const style = document.createElement("style");
    style.textContent = css;
    shadow.appendChild(style);
  } catch (e) {
    console.error('[WideAccess] Error injecting CSS into shadow root', e);
    return;
  }

  const root = ReactDOM.createRoot(container);
  root.render(<App />);
})();
