import React, { useEffect, useState, useRef, useCallback } from "react"; import { Tag } from "primereact/tag"; import Image from "next/image"; import ZapDisplay from "@/components/zaps/ZapDisplay"; import { useImageProxy } from "@/hooks/useImageProxy"; import GenericButton from "@/components/buttons/GenericButton"; import { useZapsQuery } from "@/hooks/nostrQueries/zaps/useZapsQuery"; import { nip19 } from "nostr-tools"; import { getTotalFromZaps } from "@/utils/lightning"; import dynamic from "next/dynamic"; import { Divider } from "primereact/divider"; import appConfig from "@/config/appConfig"; import useWindowWidth from "@/hooks/useWindowWidth"; import useTrackVideoLesson from '@/hooks/tracking/useTrackVideoLesson'; import { Menu } from "primereact/menu"; import { Toast } from "primereact/toast"; const MDDisplay = dynamic( () => import("@uiw/react-markdown-preview"), { ssr: false, } ); const VideoLesson = ({ lesson, course, decryptionPerformed, isPaid, setCompleted }) => { const [zapAmount, setZapAmount] = useState(0); const [nAddress, setNAddress] = useState(null); const { zaps, zapsLoading, zapsError } = useZapsQuery({ event: lesson, type: "lesson" }); const { returnImageProxy } = useImageProxy(); const windowWidth = useWindowWidth(); const isMobileView = windowWidth <= 768; const [videoDuration, setVideoDuration] = useState(null); const [videoPlayed, setVideoPlayed] = useState(false); const mdDisplayRef = useRef(null); const menuRef = useRef(null); const toastRef = useRef(null); const { isCompleted, isTracking, markLessonAsCompleted } = useTrackVideoLesson({ lessonId: lesson?.d, videoDuration, courseId: course?.d, videoPlayed, paidCourse: isPaid, decryptionPerformed }); const menuItems = [ { label: 'Mark as completed', icon: 'pi pi-check-circle', command: async () => { try { await markLessonAsCompleted(); setCompleted(lesson.id); toastRef.current.show({ severity: 'success', summary: 'Success', detail: 'Lesson marked as completed', life: 3000 }); } catch (error) { console.error('Failed to mark lesson as completed:', error); toastRef.current.show({ severity: 'error', summary: 'Error', detail: 'Failed to mark lesson as completed', life: 3000 }); } } } ]; useEffect(() => { const handleYouTubeMessage = (event) => { if (event.origin !== "https://www.youtube.com") return; try { const data = JSON.parse(event.data); if (data.event === "onReady") { event.source.postMessage('{"event":"listening"}', "https://www.youtube.com"); } else if (data.event === "infoDelivery" && data?.info && data?.info?.currentTime) { setVideoPlayed(true); setVideoDuration(data.info?.progressState?.duration); event.source.postMessage('{"event":"command","func":"getDuration","args":""}', "https://www.youtube.com"); } } catch (error) { console.error("Error parsing YouTube message:", error); } }; window.addEventListener("message", handleYouTubeMessage); return () => { window.removeEventListener("message", handleYouTubeMessage); }; }, []); const checkDuration = useCallback(() => { const videoElement = mdDisplayRef.current?.querySelector('video'); const youtubeIframe = mdDisplayRef.current?.querySelector('iframe[src*="youtube.com"]'); if (videoElement && videoElement.readyState >= 1) { setVideoDuration(Math.round(videoElement.duration)); setVideoPlayed(true); } else if (youtubeIframe) { youtubeIframe.contentWindow.postMessage('{"event":"listening"}', '*'); } }, []); useEffect(() => { if (isCompleted && !isTracking) { setCompleted(lesson.id); } }, [isCompleted, lesson.id, setCompleted, isTracking]); useEffect(() => { if (!zaps || zapsLoading || zapsError) return; const total = getTotalFromZaps(zaps, lesson); setZapAmount(total); }, [zaps, zapsLoading, zapsError, lesson]); useEffect(() => { const addr = nip19.naddrEncode({ pubkey: lesson.pubkey, kind: lesson.kind, identifier: lesson.d, relays: appConfig.defaultRelayUrls }); setNAddress(addr); }, [lesson]); useEffect(() => { if (decryptionPerformed && isPaid) { const timer = setTimeout(checkDuration, 500); return () => clearTimeout(timer); } else { const timer = setTimeout(checkDuration, 3000); return () => clearTimeout(timer); } }, [decryptionPerformed, isPaid, checkDuration]); const renderContent = () => { if (isPaid && decryptionPerformed) { return (
); } else if (isPaid && !decryptionPerformed) { return (

This content is paid and needs to be purchased before viewing.

); } else if (lesson?.content) { return (
); } return null; } return (
{renderContent()}

{lesson.title}

{lesson.topics && lesson.topics.length > 0 && ( lesson.topics.map((topic, index) => ( )) )}
{lesson.summary && (
{lesson.summary.split('\n').map((line, index) => (

{line}

))}
)}
{ window.open(`https://habla.news/a/${nAddress}`, '_blank'); }} />
{lesson?.additionalLinks && lesson.additionalLinks.length > 0 && (

External links:

menuRef.current.toggle(e)} aria-label="More options" className="p-button-text" tooltip={isMobileView ? null : "More options"} tooltipOptions={{ position: 'top' }} />
)} {!lesson?.additionalLinks || lesson.additionalLinks.length === 0 && (
menuRef.current.toggle(e)} aria-label="More options" className="p-button-text" tooltip={isMobileView ? null : "More options"} tooltipOptions={{ position: 'top' }} />
)}
) } export default VideoLesson;