// 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 [state, setState] = useState(initialState);
  const updateState = (update) => setState(Object.assign({}, state, update));

  useEffect(() => {
    // Update the document title using the browser API
    updateController(state);
  });

  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') {
      updateState(initialState);
      return;
    }

    updateState({mode, breakpoint})
  }


  function isActive(mode) {
    return mode === state.mode;
  }

  function updateController() {
    const unit = typeof state.breakpoint === 'string' ? '' : 'px';
    previewFrame.style.setProperty('--breakpoint', state.breakpoint + unit);
    previewFrame.classList.add('has-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);
}
