import { forwardRef, useMemo } from 'react';
import { getRegisteredAccessToken } from './tokenAccess';
import { buildPreviewRuntimeUrl, type PreviewTargetDescriptor } from './previewRuntime';

type PreviewAppWindowProps = {
  pathname: string;
  search?: string;
  targetDescriptor?: PreviewTargetDescriptor;
  deviceMode?: 'desktop' | 'mobile';
  reloadKey?: number;
};

export const PreviewAppWindow = forwardRef<HTMLIFrameElement, PreviewAppWindowProps>(function PreviewAppWindow(
  {
    pathname,
    search = '',
    targetDescriptor = null,
    deviceMode = 'desktop',
    reloadKey = 0,
  },
  ref,
) {
  const previewUrl = useMemo(
    () => buildPreviewRuntimeUrl(pathname, search, getRegisteredAccessToken(), targetDescriptor, deviceMode),
    [deviceMode, pathname, search, targetDescriptor],
  );

  return (
    <div
      className={`preview-app-window preview-app-window--${deviceMode}`}
      onPointerDown={(event) => event.stopPropagation()}
    >
      <div className={`preview-app-window__viewport preview-app-window__viewport--${deviceMode}`}>
        <iframe
          key={`${previewUrl}::${reloadKey}`}
          ref={ref}
          title="Preview App"
          src={previewUrl}
          className="preview-app-window__frame"
          allow="clipboard-read; clipboard-write"
          referrerPolicy="same-origin"
        />
      </div>
    </div>
  );
});
