// export function connectResponsiveness(rootAttributes) {
//   // API
//   return {
//     selectMode: (mode) => selectMode(mode),
//   }
// }
//

import React, {useEffect, useState} from 'react';
import * as ReactDOM from 'react-dom/client';
import {WrapperStyling} from "./responsive.style.js";
import {ResponsiveButton} from "./responsive-button/ResponsiveButton.jsx";

const modes = [
  'reset',
  'desktop',
  'tablet',
  'mobile'
];

function Responsive(props = {}) {
  props.rootAttributes = props.rootAttributes ?? {};

  const initialState = {mode: 'default', breakpoint: '100%'}
  const [mode, setMode] = useState(initialState.mode);
  const [breakpoint, setBreakpoint] = useState(initialState.breakpoint);

  useEffect(() => {
    updateController();
  }, [mode, breakpoint]);

  const previewFrame = props.rootAttributes.previewFrame;
  return render();

  //
  // Functions
  //

  function render() {
    return <WrapperStyling>
      {modes.map((mode) => {
        return <ResponsiveButton mode={mode}
                                 active={isActive(mode)}
                                 onSelect={(breakpoint) => selectMode(mode, breakpoint)}/>
      })}
    </WrapperStyling>;
  }

  function selectMode(mode, breakpoint) {
    if (mode === 'reset') {
      setMode(initialState.mode);
      setBreakpoint(initialState.breakpoint);
      return;
    }

    setMode(mode);
    setBreakpoint(breakpoint);
  }


  function isActive(requestedMode) {
    return mode === requestedMode;
  }

  function updateController() {
    let frameBreakpoint = breakpoint;
    if (typeof frameBreakpoint !== 'string') {
      const scrollbarWidth = 15;
      frameBreakpoint = (scrollbarWidth + frameBreakpoint) + 'px';
    }

    previewFrame.style.setProperty('--breakpoint', frameBreakpoint);
    previewFrame.classList.add('has-breakpoint');
    window.postMessage('responsiveUpdate');
    window.responsiveState = {mode, breakpoint};
  }

}

export function setupResponsiveness(rootAttributes) {
  // INIT
  const wrapper = document.createElement('div');
  document.querySelector('.page_toolbar__middle').prepend(wrapper)

  const root = ReactDOM.createRoot(wrapper);
  const html = (<Responsive rootAttributes={rootAttributes}/>);
  root.render(html);
}
