import React from 'react';
import { createRoot } from 'react-dom/client';
import block from '../block.json';
import './../styles/common.scss';
import {
  getResponsivePaddingStyle,
  getResponsiveMarginStyle,
  getResponsiveWidthStyle
} from './../utils/styleHelpers';

import OurJourneyLayoutOne from './layouts/OurJourneyLayoutOne';
import OurJourneyLayoutTwo from './layouts/OurJourneyLayoutTwo';

// Extract default attributes from the block definition.
const defaultAttributes = Object.fromEntries(
  Object.entries( block.attributes ).map( ([ key, val ]) => [ key, val.default ])
);

/**
 * Determine the current device for responsive styles.
 */
const getDevice = () => {
  const width = window.innerWidth;
  if ( 767 >= width ) {
return 'mobile';
}
  if ( 1024 >= width ) {
return 'tablet';
}
  return 'desktop';
};

/**
 * Initializes all instances of the OurJourneyFrontend block on the page.
 *
 * For each element with the class 'our-journey-frontend', it:
 * - Reads serialized attributes from the element's data-attrs attribute.
 * - Merges them with the default attributes defined in block.json.
 * - Renders the React component into the element using React 18's createRoot API.
 */
document.querySelectorAll( '.our-journey-frontend' ).forEach( ( el ) => {
  try {

    // Parse the attributes stored in the element's data-attrs attribute.
    const savedAttrs = JSON.parse( el.dataset.attrs || '{}' );

    // Combine default attributes with any saved/overridden values.
    const attributes = {
      ...defaultAttributes,
      ...savedAttrs
    };

    const device = getDevice();

    // Compute style and apply directly to el.
    const styleObj = {
      backgroundColor: attributes.sectionBgColor || undefined,
      ...getResponsivePaddingStyle( attributes.sectionPadding, device ),
      ...getResponsiveMarginStyle( attributes.sectionMargin, device ),
      ...getResponsiveWidthStyle(
        attributes.sectionWidthType,
        attributes.sectionWidth,
        attributes.sectionWidthUnit,
        device
      )
    };
    Object.assign( el.style, styleObj );

     // Select layout dynamically.
    const layoutComponent =
      'layout-two' === attributes.layout ? OurJourneyLayoutTwo : OurJourneyLayoutOne;

    // Create a React root and render the frontend layout component.
    const root = createRoot( el );
    root.render( React.createElement( layoutComponent, { attributes }) );
  } catch ( err ) {
    console.error( 'Failed to initialize OurJourneyFrontend:', err );
  }
});
