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

export function BlockText({ block }: { block: Extract<RenderableBlock, { type: "text" }> }) {
  const { sessionId, applyStep, setError } = useSession();

  useEffect(() => {
    if (!sessionId || !block.data.next) return;
    const timer = setTimeout(async () => {
      try {
        const { step } = await answerBlock(sessionId, block.id, {});
        applyStep(step);
      } catch (err) {
        setError((err as Error).message);
      }
    }, block.data.delay_ms ?? 600);
    return () => clearTimeout(timer);
  }, [sessionId, block, applyStep, setError]);

  return null;
}
