export function renderPaymentButton(
  action: string,
  completed: boolean = false
) {
  if (completed) {
    if (completed) return "Completed – Review Course";
  }
  return action === "pay"
    ? "Enroll Now"
    : action === "startCourse"
    ? "Start Course"
    : "Continue Watching";
}

export const getVideoDuration = async (videoUrl: string): Promise<number> => {
  return new Promise((resolve, reject) => {
    const video = document.createElement("video");
    video.src = videoUrl;
    video.preload = "metadata";

    video.addEventListener("loadedmetadata", () => {
      resolve(video.duration);
    });

    video.addEventListener("error", (err) => {
      console.error("Error loading video metadata:", err);
      reject(err);
    });
  });
};

export const getStepDuration = async (step: any): Promise<string> => {
  try {
    if (step.type === "video" && step.videoUrl) {
      const durationSeconds = await getVideoDuration(step.videoUrl);
      const minutes = Math.floor(durationSeconds / 60);
      const seconds = Math.floor(durationSeconds % 60);
      return `${minutes}:${seconds < 10 ? "0" : ""}${seconds}`;
    } else if (step.type === "article" && step.content) {
      const wordCount = step.content.split(/\s+/).length;
      const readingMinutes = Math.max(1, Math.ceil(wordCount / 200)); // 200 كلمة في الدقيقة تقريبًا
      return `${readingMinutes}:00`;
    } else {
      return "5:00";
    }
  } catch (error) {
    console.warn("Failed to get step duration:", error);
    return "5:00";
  }
};

export const getLessonDuration = async (lesson: any): Promise<string> => {
  let totalSeconds = 0;

  for (const step of lesson.steps) {
    if (step.type === "video" && step.videoUrl) {
      try {
        const duration = await getVideoDuration(step.videoUrl);
        totalSeconds += duration;
      } catch {
        totalSeconds += 300;
      }
    } else if (step.type === "article" && step.content) {
      const words = step.content.split(/\s+/).length;
      const readingTime = Math.max(60, Math.ceil((words / 200) * 60)); // 200 كلمة بالدقيقة
      totalSeconds += readingTime;
    } else {
      totalSeconds += 300;
    }
  }

  const hours = Math.floor(totalSeconds / 3600);
  const minutes = Math.floor((totalSeconds % 3600) / 60);
  return hours > 0 ? `${hours}h ${minutes}m` : `${minutes}m`;
};

export const getFullVideoUrl = (path: string | null | undefined) => {
  if (!path) return "";
  if (path.startsWith('http') || path.startsWith('blob:') || path.startsWith('data:')) {
    return path;
  }
  const baseUrl = process.env.NEXT_PUBLIC_API_URL?.replace(/\/+$/, '') || '';
  // Ensure the path starts with a single slash
  const formattedPath = path.startsWith('/') ? path : `/${path}`;
  return `${baseUrl}${formattedPath}`;
};