function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
import React, { memo, useMemo, useRef, useEffect, useState, useCallback } from 'react';
import { Image } from '@pisell/materials';
import "./index.less";

/**
 * MediaDisplay 媒体组件
 * @description 通用媒体展示组件，支持图片/视频展示
 * - 支持单个媒体或轮播（预留）
 * - 支持全屏模式
 * - 支持视频播放控制和状态回调
 */
var MediaDisplay = /*#__PURE__*/memo(function (props) {
  var _config$carouselItems3;
  var config = props.config,
    _props$className = props.className,
    className = _props$className === void 0 ? '' : _props$className,
    _props$fullscreen = props.fullscreen,
    fullscreen = _props$fullscreen === void 0 ? false : _props$fullscreen,
    _props$muted = props.muted,
    muted = _props$muted === void 0 ? true : _props$muted,
    _props$loop = props.loop,
    loop = _props$loop === void 0 ? false : _props$loop,
    onVideoEnded = props.onVideoEnded,
    onVideoStateChange = props.onVideoStateChange,
    _props$canClose = props.canClose,
    canClose = _props$canClose === void 0 ? true : _props$canClose,
    onClose = props.onClose;
  var videoRef = useRef(null);
  var _useState = useState('idle'),
    _useState2 = _slicedToArray(_useState, 2),
    videoState = _useState2[0],
    setVideoState = _useState2[1];
  var _useState3 = useState(false),
    _useState4 = _slicedToArray(_useState3, 2),
    isVideoEnded = _useState4[0],
    setIsVideoEnded = _useState4[1];

  /**
   * 获取当前要展示的媒体项
   * 如果只有一个媒体项，直接返回；否则返回第一个（轮播逻辑预留）
   */
  var currentMedia = useMemo(function () {
    var _config$carouselItems;
    if (config !== null && config !== void 0 && (_config$carouselItems = config.carouselItems) !== null && _config$carouselItems !== void 0 && _config$carouselItems.length) {
      // 目前只取第一个，轮播逻辑预留
      return config.carouselItems[0];
    }
    // 如果有 logo，构造为图片类型
    if (config !== null && config !== void 0 && config.logo) {
      return {
        type: 'image',
        url: config.logo
      };
    }
    return null;
  }, [config === null || config === void 0 ? void 0 : config.carouselItems, config === null || config === void 0 ? void 0 : config.logo]);

  /**
   * 是否为视频类型
   */
  var isVideo = (currentMedia === null || currentMedia === void 0 ? void 0 : currentMedia.type) === 'video';

  /**
   * 是否为单一媒体（不需要显示切换控件）
   */
  var isSingleMedia = useMemo(function () {
    var _config$carouselItems2;
    var itemCount = (config === null || config === void 0 || (_config$carouselItems2 = config.carouselItems) === null || _config$carouselItems2 === void 0 ? void 0 : _config$carouselItems2.length) || 0;
    // 只有一个轮播项，或者没有轮播项但有 logo
    return itemCount <= 1;
  }, [config === null || config === void 0 || (_config$carouselItems3 = config.carouselItems) === null || _config$carouselItems3 === void 0 ? void 0 : _config$carouselItems3.length]);

  /**
   * 更新视频播放状态
   */
  var updateVideoState = useCallback(function (state) {
    setVideoState(state);
    onVideoStateChange === null || onVideoStateChange === void 0 || onVideoStateChange(state);
  }, [onVideoStateChange]);

  /**
   * 处理视频播放结束
   */
  var handleVideoEnded = useCallback(function () {
    setIsVideoEnded(true);
    updateVideoState('ended');
    onVideoEnded === null || onVideoEnded === void 0 || onVideoEnded();

    // 如果可以关闭，触发关闭回调
    if (canClose) {
      onClose === null || onClose === void 0 || onClose();
    }
    // 如果不能关闭（初始化未完成），视频会停在最后一帧等待
    // 外部通过修改 canClose 为 true 后，组件会在下次渲染时触发 onClose
  }, [canClose, onClose, onVideoEnded, updateVideoState]);

  /**
   * 监听 canClose 变化，如果视频已结束且 canClose 变为 true，触发关闭
   */
  useEffect(function () {
    if (isVideoEnded && canClose) {
      onClose === null || onClose === void 0 || onClose();
    }
  }, [isVideoEnded, canClose, onClose]);

  /**
   * 视频事件处理
   */
  useEffect(function () {
    var video = videoRef.current;
    if (!video || !isVideo) return;
    var handlePlay = function handlePlay() {
      return updateVideoState('playing');
    };
    var handlePause = function handlePause() {
      return updateVideoState('paused');
    };
    var handleError = function handleError() {
      return updateVideoState('error');
    };
    var handleLoadedData = function handleLoadedData() {
      // 视频加载完成后自动播放
      video.play().catch(function (err) {
        console.warn('[MediaDisplay] 视频自动播放失败:', err);
        updateVideoState('error');
      });
    };
    video.addEventListener('play', handlePlay);
    video.addEventListener('pause', handlePause);
    video.addEventListener('ended', handleVideoEnded);
    video.addEventListener('error', handleError);
    video.addEventListener('loadeddata', handleLoadedData);
    return function () {
      video.removeEventListener('play', handlePlay);
      video.removeEventListener('pause', handlePause);
      video.removeEventListener('ended', handleVideoEnded);
      video.removeEventListener('error', handleError);
      video.removeEventListener('loadeddata', handleLoadedData);
    };
  }, [isVideo, handleVideoEnded, updateVideoState]);

  /** 品牌标语 */
  var slogan = config === null || config === void 0 ? void 0 : config.slogan;

  /**
   * 渲染媒体内容
   */
  var renderMedia = function renderMedia() {
    if (!currentMedia) {
      return null;
    }
    if (currentMedia.type === 'video') {
      return /*#__PURE__*/React.createElement("video", {
        style: {
          backgroundColor: currentMedia.backgroundColor
        },
        ref: videoRef,
        src: currentMedia.url,
        className: "media-display__video",
        muted: muted,
        loop: loop,
        playsInline: true,
        autoPlay: true
      });
    }
    if (currentMedia.type === 'logo') {
      return /*#__PURE__*/React.createElement("div", {
        className: "media-display__logo-wrapper"
      }, /*#__PURE__*/React.createElement(Image, {
        style: currentMedia.logoStyle,
        src: currentMedia.url,
        preview: false
      }));
    }

    // 图片类型
    return /*#__PURE__*/React.createElement("div", {
      className: "media-display__image-wrapper"
    }, /*#__PURE__*/React.createElement(Image, {
      style: {
        width: '100%',
        height: '100%',
        backgroundColor: currentMedia.backgroundColor
      },
      src: currentMedia.url,
      preview: false,
      alt: "Media",
      className: "media-display__image"
    }));
  };

  // 全屏模式
  if (fullscreen) {
    return /*#__PURE__*/React.createElement("div", {
      className: "media-display media-display--fullscreen ".concat(className).trim()
    }, renderMedia());
  }
  console.log(currentMedia, 'currentMedia');

  // 普通模式（品牌面板样式）
  return /*#__PURE__*/React.createElement("div", {
    className: "webpos-login-brand-panel-media ".concat(className).trim()
  }, /*#__PURE__*/React.createElement("div", {
    className: "webpos-login-brand-panel-media__content"
  }, /*#__PURE__*/React.createElement("div", {
    className: "webpos-login-brand-panel-media__logo-wrapper"
  }, renderMedia()), slogan && /*#__PURE__*/React.createElement("p", {
    className: "webpos-login-brand-panel-media__slogan"
  }, slogan), !isSingleMedia && /*#__PURE__*/React.createElement("div", {
    className: "webpos-login-brand-panel-media__carousel-controls"
  })));
});
MediaDisplay.displayName = 'MediaDisplay';
export default MediaDisplay;