import React, {cloneElement, Suspense} from 'react';
import ReactDOM from 'react-dom/client';
import { createPortal } from 'react-dom';
import { SignIn, HeroTimeLine, WhiskeyDrop, AuthProvider, ProfileComponent, PrivateAreaMobileMenu,HeaderMenu, AccountUseInfo, Notification  } from '@beamsuntoryinc/react-module-cpms';


import './src/drupalSetting';
//https://dev-bs-whitelabel.sites-beamsuntory.com/fr.html
//https://localhost:4200/callback.html
const signIn = (
  <SignIn showMemberRegistration={true}/>
  );

const heroTimeLine = (
  <HeroTimeLine 
      url="https://dev-digital-profile.sites-beamsuntory.com/bsi"
    />
)


const reactComponentMapping = {
  signInComponent:signIn,
  heroTimeline:heroTimeLine,
  whiskeyDrop:<WhiskeyDrop />,
  accountUserMenu:<PrivateAreaMobileMenu />,
  accountHeaderMenu: <HeaderMenu />,
  accountUserInfo: <AccountUseInfo />,
  profileComponent: <ProfileComponent />,
  notificationComponent:<Notification />
} 


const bootstrapReactComponents = () => {
  // Locate all potential mma-react-component nodes to render components in.
  const mMAReactNodes = document.querySelectorAll('.component-react');
  const contextRoot = ReactDOM.createRoot(
    document.createElement('mma-react-root')
  );
  const portalPairs = [];
  mMAReactNodes.forEach((element) => {
    const componentName = element.getAttribute('key');
    const attributes = element.attributes;
    const attributeArray = Array.from(attributes);
    let attributeAsProp = {};
    attributeArray.forEach(attribute => {
      attributeAsProp[attribute.name] = attribute.value
    });
    // Use clone to extend the component so we can add the uuid to the component directly
    if (reactComponentMapping[componentName]) {
      const component = cloneElement(
        reactComponentMapping[componentName],
        { uuid: componentName }
      );
      // Only attempt to render component if it was part of the mapping.
      if (element && component) {
        portalPairs.push({
          component:component,
          element: element,
        });
      }
    }
  });
  contextRoot.render(
        <Suspense fallback={<div>Loading...</div>}>
          <AuthProvider>
            {portalPairs.map((pair) => {
                return createPortal(pair.component, pair.element);
              })}  
          </AuthProvider>
      </Suspense>   
  );
  return null;
};


const bootstrapAgeGateLogin = () => {
  const ageGateLoginContainer = document.querySelector(
    '[key="ageGateLogin"]'
  );
  const ageGateLoginRenderElem = document.querySelector('slot#login_form');
  const root = ageGateLoginRenderElem ? ReactDOM.createRoot(ageGateLoginRenderElem) : null;

  if (root && ageGateLoginContainer) {
    root.render(
      <Suspense fallback={<div>Loading...</div>}>
          <AuthProvider>
            <SignIn
              uuid={'signInComponent'}
              showMemberRegistration={false} 
              isAgeGateSignIn={true} 
            />
          </AuthProvider>
      </Suspense>   
    );
  }
};

document.addEventListener('DOMContentLoaded', () => {
  bootstrapReactComponents();
});


const waitForAgeGateDOM = (callback: () => void) => {
  const ageGateLoginDiv = document.querySelector('slot#login_form');
  if (ageGateLoginDiv) {
    callback();
  } else {
    setTimeout(() => {
      waitForAgeGateDOM(callback);
    }, 100);
  }
};

waitForAgeGateDOM(() => {
  bootstrapAgeGateLogin();
});