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

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

export function PreviewAppWindow({
  pathname,
  search = '',
  targetDescriptor = null,
  deviceMode = 'desktop',
}: PreviewAppWindowProps) {
  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
          title="Preview App"
          src={previewUrl}
          className="preview-app-window__frame"
          allow="clipboard-read; clipboard-write"
          referrerPolicy="same-origin"
        />
      </div>
    </div>
  );
}
