import React from 'react';
import { createRoot } from 'react-dom/client';
import LoginForm from './LoginForm';
import cssText from './styles.css?inline';

function mount(container, props) {
  const host = document.createElement('div');
  host.setAttribute('data-new-api-widget', 'login');
  container.appendChild(host);

  const shadow = host.attachShadow({ mode: 'open' });

  const style = document.createElement('style');
  style.textContent = cssText;
  shadow.appendChild(style);

  if (props.theme === 'dark') {
    host.setAttribute('theme', 'dark');
  }

  const mountPoint = document.createElement('div');
  shadow.appendChild(mountPoint);

  const root = createRoot(mountPoint);
  root.render(
    React.createElement(
      'div',
      { className: 'naw-container' },
      React.createElement('h1', { className: 'naw-title' }, '登 录'),
      React.createElement(LoginForm, {
        apiUrl: props.apiUrl,
        onSuccess: props.onSuccess,
        onError: props.onError,
      })
    )
  );

  return { host, root };
}

function init(options) {
  const container =
    typeof options.container === 'string'
      ? document.querySelector(options.container)
      : options.container;

  if (!container) {
    throw new Error('NewApiLoginWidget: container not found');
  }
  if (!options.apiUrl) {
    throw new Error('NewApiLoginWidget: apiUrl is required');
  }

  const { host, root } = mount(container, {
    apiUrl: options.apiUrl.replace(/\/+$/, ''),
    onSuccess: options.onSuccess,
    onError: options.onError,
    theme: options.theme || 'light',
  });

  return {
    destroy() {
      root.unmount();
      host.remove();
    },
  };
}

window.NewApiLoginWidget = { init: init };

export { init };
