import { useState } from 'react';
import type { MindSpaceAsset } from '../types';
import { buildAssetPreviewFrameConfig } from '../utils/mindspaceCards';

export type WorkCoverMode = 'thumbnail-first' | 'preview-first' | 'preview-only';

export function WorkCover({
  thumbnailUrl,
  previewUrl,
  previewAsset,
  fallbackLabel,
  title,
  imageClassName = 'mindspace-item-cover-img',
  coverMode = 'thumbnail-first',
  previewFrameClassName = 'mindspace-preview-embed',
}: {
  thumbnailUrl: string;
  previewUrl?: string;
  previewAsset?: Pick<MindSpaceAsset, 'id' | 'mimeType'>;
  fallbackLabel: string;
  title: string;
  imageClassName?: string;
  coverMode?: WorkCoverMode;
  previewFrameClassName?: string;
}) {
  const [thumbFailed, setThumbFailed] = useState(false);
  const [previewFailed, setPreviewFailed] = useState(false);

  const previewFrame =
    previewAsset != null
      ? buildAssetPreviewFrameConfig(previewAsset)
      : previewUrl
        ? { src: previewUrl, sandbox: 'allow-same-origin' as const }
        : null;

  const showPreview =
    Boolean(previewFrame) &&
    !previewFailed &&
    (coverMode === 'preview-first' || coverMode === 'preview-only' || thumbFailed);

  if (showPreview && previewFrame) {
    return (
      <div className={previewFrameClassName} aria-hidden="true">
        <iframe
          title={`${title} 预览`}
          src={previewFrame.src}
          {...(previewFrame.sandbox ? { sandbox: previewFrame.sandbox } : {})}
          loading="lazy"
          onError={() => setPreviewFailed(true)}
        />
      </div>
    );
  }

  if (coverMode !== 'preview-only' && !thumbFailed) {
    return (
      <img
        className={imageClassName}
        src={thumbnailUrl}
        alt={`${title} 封面`}
        loading="lazy"
        onError={() => setThumbFailed(true)}
      />
    );
  }

  if (previewFrame && !previewFailed) {
    return (
      <div className={previewFrameClassName} aria-hidden="true">
        <iframe
          title={`${title} 预览`}
          src={previewFrame.src}
          {...(previewFrame.sandbox ? { sandbox: previewFrame.sandbox } : {})}
          loading="lazy"
          onError={() => setPreviewFailed(true)}
        />
      </div>
    );
  }

  return <span>{fallbackLabel}</span>;
}
