import React from "react";
import * as TW from   "@twind/core";
import TWPreTail from "@twind/preset-tailwind";
import TWPreAuto from "@twind/preset-autoprefix";
import * as App from ">able/app.tsx";

const Configure =
{
  theme: {},
  presets: [TWPreTail(), TWPreAuto()],
  hash: false
} as TW.TwindUserConfig;

let TwindInst:TW.Twind<TW.BaseTheme, unknown>;
const TwindConfig = {...Configure, ...(App?.CSS || {})};
export const CustomTwindExtractor =(inMarkup:string)=> {
  if(!TwindInst)
  {
    TwindInst = TW.install(TwindConfig);
  }
  return TW.extract(inMarkup, TwindInst);
}

export const CustomApp = App.default;

const Shadow =(inElement:HTMLElement)=>
{
    const ShadowDOM = inElement.attachShadow({ mode: "open" });
    const ShadowDiv = document.createElement("div");
    const ShadowCSS = document.createElement("style");

    ShadowDOM.append(ShadowCSS);
    ShadowDOM.append(ShadowDiv);
    TW.observe(TW.twind(TwindConfig, TW.cssom(ShadowCSS)), ShadowDiv);
    return ShadowDiv;
};

export default async(inSelector:string, inShadow=false):Promise<(()=>void)|false>=>
{

  let dom = document.querySelector(inSelector);
  if(!dom)
  {
    console.log(`element "${inSelector}" not found.`);
    return false;
  }

  if(inShadow)
  {
    dom = Shadow(dom as HTMLElement);
  }
  else
  {
    TW.install(TwindConfig);
  }

  const app = React.createElement(()=> React.createElement(App.default, null), null);
  React.hydrate(app, dom);
  return ()=>dom && React.unmountComponentAtNode(dom);

};
