/**
 * InAppPreviewPane - Complete InApp preview with device frames and dynamic positioning
 */

import React, {
  useMemo, useRef, useEffect, useCallback,
} from 'react';
import PropTypes from 'prop-types';
import { injectIntl, intlShape } from 'react-intl';

import CapRow from '@capillarytech/cap-ui-library/CapRow';

// Components
import DeviceFrame from './DeviceFrame';
import ContentOverlay from './ContentOverlay';

// Context
import { useEditorContext } from '../common/EditorContext';

// Constants
import { LAYOUT_TYPES, SCROLL_POSITION_MULTIPLIERS } from './constants';

// Styles
import './_inAppPreviewPane.scss';

const InAppPreviewPane = ({
  intl,
  className = '',
  isFullscreenMode = false,
  isModalContext = false,
  layoutType: propLayoutType = LAYOUT_TYPES.MODAL,
}) => {
  const {
    content,
    activeDevice,
    getDeviceContent,
    layoutType: contextLayoutType,
    isFullscreenMode: contextIsFullscreenMode,
  } = useEditorContext();

  // Refs for adaptive scrolling
  const containerRef = useRef(null);
  const deviceContainerRef = useRef(null);

  // Use layoutType from context if available, otherwise fall back to prop
  const layoutType = contextLayoutType || propLayoutType;

  // Get current device content
  const currentContent = useMemo(() => {
    if (getDeviceContent) {
      return getDeviceContent(activeDevice);
    }
    return content?.content || '';
  }, [content?.content, activeDevice, getDeviceContent]);

  // Adaptive scrolling effect based on layout type (disabled for modal context)
  useEffect(() => {
    if (isModalContext || !containerRef.current || !deviceContainerRef.current) {
      return;
    }

    const container = containerRef.current;
    const deviceContainer = deviceContainerRef.current;

    const isComponentVisible = () => {
      // Use context fullscreen state with fallback to prop, then fallback to container visibility check
      const isFullscreen = contextIsFullscreenMode ?? isFullscreenMode;
      return !isFullscreen && container.offsetParent !== null;
    };

    const performAdaptiveScroll = () => {
      try {
        if (!isComponentVisible()) return;

        const containerHeight = container.clientHeight;
        const deviceHeight = deviceContainer.offsetHeight;
        const scrollableHeight = Math.max(0, deviceHeight - containerHeight);

        if (scrollableHeight <= 0) return;

        const scrollMultiplier = SCROLL_POSITION_MULTIPLIERS[layoutType] ?? SCROLL_POSITION_MULTIPLIERS[LAYOUT_TYPES.MODAL];
        const targetScrollTop = Math.max(0, scrollableHeight * scrollMultiplier);

        requestAnimationFrame(() => {
          container.scrollTo({
            top: targetScrollTop,
            behavior: 'smooth',
          });
        });
      } catch (error) {
        console.warn('Adaptive scroll error:', error);
      }
    };

    const timeoutId = setTimeout(performAdaptiveScroll, 150);
    return () => clearTimeout(timeoutId);
  }, [layoutType, isFullscreenMode, isModalContext, contextIsFullscreenMode]);


  // Generate CSS classes based on context
  const getContainerClasses = () => {
    const baseClass = 'inapp-preview-pane';
    const classes = [baseClass];

    if (isModalContext) {
      classes.push(`${baseClass}--modal-context`);
    }

    if (isFullscreenMode) {
      classes.push(`${baseClass}--fullscreen`);
    }

    if (className) {
      classes.push(className);
    }

    return classes.join(' ');
  };

  const getDeviceContainerClasses = () => {
    const baseClass = 'inapp-preview-pane__device-container';
    const classes = [baseClass];

    if (isModalContext) {
      classes.push(`${baseClass}--modal-context`);
    } else if (isFullscreenMode) {
      classes.push(`${baseClass}--fullscreen`);
    } else {
      classes.push(`${baseClass}--normal`);
    }

    return classes.join(' ');
  };

  const handleScroll = useCallback((e) => {
    // Basic scroll handling
  }, []);

  const handleWheel = useCallback((e) => {
    // Wheel event handling
  }, []);

  const handleTouchMove = useCallback((e) => {
    // Touch move handling
  }, []);

  return (
    <div
      ref={containerRef}
      className={getContainerClasses()}
      onScroll={handleScroll}
      onWheel={handleWheel}
      onTouchMove={handleTouchMove}
    >
      <CapRow
        useLegacy
        ref={deviceContainerRef}
        className={getDeviceContainerClasses()}
      >
        <DeviceFrame device={activeDevice}>
          <ContentOverlay
            layoutType={layoutType}
            content={currentContent}
            device={activeDevice}
            className="inapp-preview-pane__content-overlay"
          />
        </DeviceFrame>
      </CapRow>
    </div>
  );
};

InAppPreviewPane.propTypes = {
  intl: intlShape.isRequired,
  className: PropTypes.string,
  isFullscreenMode: PropTypes.bool,
  isModalContext: PropTypes.bool,
  layoutType: PropTypes.oneOf(Object.values(LAYOUT_TYPES)),
};

export default injectIntl(InAppPreviewPane);
