import React from 'react'
import { resolveExerciseMediaFileUrl } from '../utils/exerciseMediaUrl'
import { sanitizeInlineMediaSize } from '../constants/inlineExerciseMedia'

/**
 * Ein ausgeliefertes exercise_media für Übungslisten (Liste + Inline gleiche Darstellung).
 * @param {{ media: object, exerciseId: number, layoutSize?: string }} props
 */
export default function ExerciseMediaEmbed({ exerciseId, media, layoutSize = 'medium' }) {
  const sz = sanitizeInlineMediaSize(layoutSize)
  const box =
    sz === 'small'
      ? { maxWidth: 'min(280px, 33vw)', marginTop: '0.5rem' }
      : sz === 'full'
        ? { maxWidth: '100%', marginTop: '0.5rem' }
        : { maxWidth: 'min(560px, 85vw)', marginTop: '0.5rem' }

  if (!media || exerciseId == null) return null

  if (media.asset_legal_hold_active) {
    return (
      <div style={{ ...box, color: 'var(--danger)', fontSize: '0.85rem', padding: '8px 0' }}>
        Medium nicht verfügbar (gesperrt)
      </div>
    )
  }

  if (media.embed_url) {
    return (
      <div
        style={{
          ...box,
          wordBreak: 'break-word',
          overflowWrap: 'anywhere',
          fontSize: sz === 'small' ? '0.88rem' : undefined,
        }}
      >
        <a href={media.embed_url} target="_blank" rel="noreferrer">
          {media.title?.trim() || media.embed_url}
        </a>
        {media.embed_platform && (
          <span style={{ color: 'var(--text2)', marginLeft: '0.35rem', fontSize: '0.82rem', display: 'inline' }}>
            ({media.embed_platform})
          </span>
        )}
      </div>
    )
  }
  const src = resolveExerciseMediaFileUrl(exerciseId, media)
  if (!src) return null
  if (media.media_type === 'image' || (media.mime_type && media.mime_type.startsWith('image/'))) {
    return (
      <div style={box}>
        <img
          src={src}
          alt={media.title || media.original_filename || ''}
          style={{ width: '100%', maxWidth: '100%', height: 'auto', borderRadius: '8px', display: 'block' }}
        />
      </div>
    )
  }
  if (media.media_type === 'video' || (media.mime_type && media.mime_type.startsWith('video/'))) {
    return (
      <div style={box}>
        <video
          src={src}
          controls
          style={{ width: '100%', maxWidth: '100%', borderRadius: '8px', verticalAlign: 'top' }}
        />
      </div>
    )
  }
  return (
    <div style={box}>
      <a href={src} target="_blank" rel="noreferrer" style={{ display: 'inline-block', marginTop: '0.25rem' }}>
        {media.title || media.original_filename || 'Datei öffnen'}
      </a>
    </div>
  )
}
