Files
nahodka-front/src/components/FullscreenAdOverlay.jsx
2026-09-23 23:38:54 +03:00

114 lines
4.2 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
const SKIP_DELAY_SECONDS = 5;
/**
* FullscreenAdOverlay — полноэкранный оверлей поверх всего интерфейса
* (z-index выше всех модалок). Кнопка закрытия появляется через 5 секунд
* (тот же паттерн таймера, что и в AdCard). Клик по видео открывает targetUrl
* в новой вкладке (если задан), не закрывая оверлей.
*
* Звук: мобильные браузеры блокируют autoplay со звуком (и останавливают видео
* при попытке программного unmute), поэтому стартуем строго muted — автоплей
* гарантирован на любом устройстве. Звук включается только вручную кнопкой 🔊.
*/
export default function FullscreenAdOverlay({ ad, onClose }) {
const { t } = useTranslation();
const [remaining, setRemaining] = useState(SKIP_DELAY_SECONDS);
const [soundOn, setSoundOn] = useState(false);
const videoRef = useRef(null);
useEffect(() => {
if (remaining <= 0) return;
const timerId = setTimeout(() => setRemaining((r) => r - 1), 1000);
return () => clearTimeout(timerId);
}, [remaining]);
// Автоплей: снимаем muted как свойство ДО старта (атрибут на iOS не всегда
// применяется вовремя), и дополнительно пробуем play() ещё раз, когда
// браузер загрузил данные/может воспроизвести — это покрывает случаи,
// когда первый play() отклонился «NotReady»/«Abort". Никаких автоматических
// размуток — они останавливают видео на мобильных.
useEffect(() => {
const videoNode = videoRef.current;
if (!videoNode) return;
videoNode.muted = true;
const tryPlay = () => {
videoNode.muted = true;
const promise = videoNode.play();
if (promise) promise.catch(() => {});
};
tryPlay();
videoNode.addEventListener("loadeddata", tryPlay);
videoNode.addEventListener("canplay", tryPlay);
return () => {
videoNode.removeEventListener("loadeddata", tryPlay);
videoNode.removeEventListener("canplay", tryPlay);
};
}, []);
const handleVideoClick = () => {
videoRef.current?.play().catch(() => {});
if (ad.targetUrl) {
window.open(ad.targetUrl, "_blank", "noopener,noreferrer");
}
};
const handleToggleSound = (e) => {
e.stopPropagation();
const videoNode = videoRef.current;
if (!videoNode) return;
const nextMuted = !videoNode.muted;
videoNode.muted = nextMuted;
videoNode.play().catch(() => {});
setSoundOn(!nextMuted);
};
return (
<div className="fs-ad-overlay">
<span className="fs-ad-label">{t('fullscreenAd.label')}</span>
<video
ref={(node) => {
videoRef.current = node;
if (node) node.muted = true; // свойство сразу при монтировании
}}
className="fs-ad-video"
src={ad.mediaUrl}
autoPlay
muted
controls={false}
playsInline
loop
preload="auto"
onClick={handleVideoClick}
/>
<button
type="button"
className="fs-ad-sound"
onClick={handleToggleSound}
aria-label={soundOn ? t('fullscreenAd.mute') : t('fullscreenAd.unmute')}
>
{soundOn ? "🔊" : "🔇"}
</button>
{remaining > 0 ? (
<span className="fs-ad-skip-timer">
{t('fullscreenAd.closeIn', { seconds: remaining })}
</span>
) : (
<button
type="button"
className="fs-ad-close"
onClick={onClose}
aria-label={t('common.close')}
>
✕
</button>
)}
</div>
);
}