/**
 * Lazy HTMLEditor Wrapper
 *
 * This file provides lazy loading for the HTMLEditor component to exclude it
 * from the initial bundle and load it only when needed.
 */

import React, { Suspense } from 'react';
import PropTypes from 'prop-types';
import CapSpin from '@capillarytech/cap-ui-library/CapSpin';

// Styles
import './_index.lazy.scss';

// Loading fallback component
const HTMLEditorFallback = ({ message }) => (
  <div className="html-editor-lazy-fallback">
    <CapSpin size="large" />
    <div className="html-editor-lazy-fallback__message">
      {message || 'Loading HTML Editor...'}
    </div>
  </div>
);

// Lazy load the main HTMLEditor component
const LazyHTMLEditor = React.lazy(() =>
  import('./HTMLEditor').then(module => {
    // Set global flag to indicate HTMLEditor is loaded
    if (typeof window !== 'undefined') {
      window.__htmlEditorLoaded = true;
    }
    return {
      default: module.default
    };
  })
);

/**
 * HTMLEditor with Lazy Loading
 *
 * This component wraps the HTMLEditor with React.lazy() and Suspense
 * to enable code splitting and reduce initial bundle size.
 */
const HTMLEditorLazy = (props) => {
  return (
    <Suspense fallback={<HTMLEditorFallback />}>
      <LazyHTMLEditor {...props} />
    </Suspense>
  );
};

// Forward all prop types from the original component
HTMLEditorLazy.propTypes = {
  // Core props
  variant: PropTypes.oneOf(['email', 'inapp']),
  layoutType: PropTypes.string,
  initialContent: PropTypes.oneOfType([PropTypes.string, PropTypes.object]),

  // Event handlers
  onSave: PropTypes.func,
  onContentChange: PropTypes.func,

  // Configuration
  className: PropTypes.string,
  readOnly: PropTypes.bool,
  showFullscreenButton: PropTypes.bool,
  autoSave: PropTypes.bool,
  autoSaveInterval: PropTypes.number,

  // React Intl (will be injected)
  intl: PropTypes.object
};

HTMLEditorLazy.defaultProps = {
  variant: 'email',
  initialContent: null,
  onSave: null,
  onContentChange: null,
  className: '',
  readOnly: false,
  showFullscreenButton: true,
  autoSave: true,
  autoSaveInterval: 30000
};

// Display name for debugging
HTMLEditorLazy.displayName = 'HTMLEditorLazy';

/**
 * Preload function to warm up the HTMLEditor
 * Call this when you know the user might need the editor soon
 */
export const preloadHTMLEditor = () => {
  // Preload the component in the background
  import('./HTMLEditor').then(() => {
    // Set global flag to indicate HTMLEditor is loaded
    if (typeof window !== 'undefined') {
      window.__htmlEditorLoaded = true;
    }
  }).catch(() => {
    // Silently handle preload failures
  });
};

/**
 * Check if HTMLEditor is already loaded
 */
export const isHTMLEditorLoaded = () => {
  // Simple check - in a real app you might want more sophisticated tracking
  return typeof window !== 'undefined' && window.__htmlEditorLoaded;
};

export default HTMLEditorLazy;
export { HTMLEditorFallback };
