import { useEffect } from "react";
import { useSession } from "../store/session";
import { answerBlock } from "../api/client";
import type { RenderableBlock } from "../types/flow";

type MediaBlock = Extract<RenderableBlock, { type: "image" | "video" }>;

export function BlockMedia({ block }: { block: MediaBlock }) {
  const { sessionId, applyStep, setError } = useSession();

  // Auto-avanca apos 3s pra image, ou aguarda video terminar
  useEffect(() => {
    if (!sessionId || !block.data.next) return;
    if (block.type === "video") return; // video usa onEnded
    const t = setTimeout(async () => {
      try {
        const { step } = await answerBlock(sessionId, block.id, {});
        applyStep(step);
      } catch (err) {
        setError((err as Error).message);
      }
    }, 3000);
    return () => clearTimeout(t);
  }, [sessionId, block, applyStep, setError]);

  async function onVideoEnded() {
    if (!sessionId) return;
    try {
      const { step } = await answerBlock(sessionId, block.id, {});
      applyStep(step);
    } catch (err) {
      setError((err as Error).message);
    }
  }

  if (block.type === "image") {
    return (
      <img
        src={block.data.url}
        alt={block.data.alt}
        className="max-h-80 w-full rounded-2xl object-cover"
      />
    );
  }

  return (
    <video
      src={block.data.url}
      autoPlay={block.data.autoplay}
      controls
      onEnded={onVideoEnded}
      className="w-full rounded-2xl"
    />
  );
}
