import React, { useEffect } from "react";

import "./SplitLayout.css";
import { renderProps, isDevaice, getCN, get_typeName } from "../utils";

function SplitLayout({
  children,
  scheme = `dark`,
  notification,
  modal,
  resizeAppHeight = 0,
  headerColor = true,
  center = false,
  tabbar,
  maxWidth,
  ...props
}: {
  [x: string]: any;
}) {
  function getScheme(scheme: any) {
    if (scheme == `vkcom_light`) return `light`;
    if (scheme == `client_light`) return `light`;
    if (scheme == `vkcom_dark`) return `dark`;
    if (scheme == `space_gray`) return `dark`;
    if (scheme == `dark`) return `dark`;
    return `light`;
  }

  useEffect(() => {
    const onPageLoad = () => {
      document.documentElement.dataset.loading = `true`;
    };

    if (document.readyState === 'complete') {
      onPageLoad();
    } else {
      window.addEventListener('DOMContentLoaded', onPageLoad, true);
      return () => window.removeEventListener('DOMContentLoaded', onPageLoad);
    }
  }, [document.readyState]);

  useEffect(() => {
    document.documentElement.dataset.theme = getScheme(scheme)
    document.documentElement.dataset.devaice = `${isDevaice()}`;

    if (headerColor) {
      var bodyStyles = window.getComputedStyle(document.body);
      var fooBar = bodyStyles.getPropertyValue('--html_background');
      document.querySelector("meta[name='theme-color']")?.setAttribute("content", "rgb(" + fooBar + ")");
    }
  }, [getScheme(scheme), isDevaice()])

  const appHeight = () => {
    const doc = document.documentElement
    doc.style.setProperty("--app-height", `${window.innerHeight}px`);
    doc.style.setProperty("--app-max-width", maxWidth ? `${maxWidth}px` : `100%`);
  }
  useEffect(() => {
    window.addEventListener("resize", appHeight)
    appHeight()
    return () => window.removeEventListener("resize", appHeight)
  }, [])

  useEffect(() => {
    appHeight()
  }, [maxWidth, window.innerHeight, resizeAppHeight])

  return (
    <div
      data-devaice={isDevaice()}
      data-center={center}
      data-tabbar={tabbar ? true : false}
      className="MYUI-SplitLayout"
    >
      <div {...renderProps(props)} className="MYUI-SplitLayout__children">
        {children}
        {tabbar && <div className="MYUI-SplitLayout--tabbar">{tabbar}</div>}
      </div>
      {notification && <div className="MYUI-SplitLayout--notification">{notification}</div>}
      {modal && <div className="MYUI-SplitLayout--modal">{modal}</div>}
    </div>
  );
}

export default SplitLayout;
