import React from "react";
import { createRoot } from "react-dom/client";
import { Provider } from "react-redux";
import { store } from "./store";
import ToggleWrapper from "./ToggleWrapper";

import cssText from "./shadowCss";

function mountChat() {
  const host = document.getElementById("chat");
  if (!host) {
    console.warn('Mount point "#chat" not found');
    return;
  }

  // 1) Attach shadow root
  const shadow = host.attachShadow({ mode: 'open' });

  // 2) Style injection (compiled CSS)
  const style = document.createElement('style');
  style.textContent = cssText || "";
  shadow.appendChild(style);

  // 3) React mount point
  const mountPoint = document.createElement('div');
  shadow.appendChild(mountPoint);

  console.log('[Zozo Chat] about to render', { mountPoint });
  console.log('[Zozo Chat] cssText length', cssText.length);

  createRoot(mountPoint).render(
    <React.StrictMode>
      <Provider store={store}>
        <ToggleWrapper />
      </Provider>
    </React.StrictMode>
  );
}

// If DOM still loading, wait; otherwise mount immediately
if (document.readyState === "loading") {
  window.addEventListener("DOMContentLoaded", mountChat);
} else {
  mountChat();
}