"use client";
import Image from "next/image";
import { useRouter } from "next/navigation";
import type { ReactNode } from "react";
import { useCallback, useState } from "react";
import { localizePath } from "@/translations/config";
import { useI18n } from "@/translations/provider";
import { useQuestionAnswers } from "./question-answer-storage";
import QuestionProgressTracker, {
useQuestionProgress,
} from "./question-progress-tracker";
import QuestionSnapList from "./question-snap-list";
import type { QuestionField } from "@/lib/schema-adapter";
import NoticeBox from "./notice-box";
import AnswerPaceSheet from "@/app/questions-list/[slug]/answer-pace-sheet";
import { FixToTheEnd } from "./fix-to-the-end";
import Button from "./button";
import { markFirstEntryCompleted } from "@/lib/first-entry-helper";
type QuestionSectionFlowProps = {
children: ReactNode;
continueLabel: string;
exitHref: string;
total: number;
optionalQuestionIndexes: readonly number[];
questions?: readonly QuestionField[];
};
function SectionFlowContent({
children,
continueLabel,
exitHref,
optionalQuestionIndexes,
questions,
}: {
children: ReactNode;
continueLabel: string;
exitHref: string;
optionalQuestionIndexes: readonly number[];
questions?: readonly QuestionField[];
}) {
const router = useRouter();
const { dictionary: t, locale } = useI18n();
const { flushAnswers } = useQuestionAnswers();
const { markQuestionPassed, isCompleted } = useQuestionProgress();
const [activeQuestionIndex, setActiveQuestionIndex] = useState(0);
const [isSubmitting, setIsSubmitting] = useState(false);
const handleQuestionExit = useCallback(() => {
void flushAnswers({ force: true });
}, [flushAnswers]);
const handleSubmit = useCallback(async () => {
if (isSubmitting) {
return;
}
setIsSubmitting(true);
try {
markFirstEntryCompleted();
await flushAnswers({ force: true });
} catch {
// ignore
} finally {
const target = localizePath(exitHref || "/questions-list", locale);
router.push(target);
}
}, [exitHref, flushAnswers, locale, router, isSubmitting]);
const markOptionalQuestionsPassed = useCallback(
(currentIndex: number, nextIndex: number) => {
[currentIndex, nextIndex].forEach((questionIndex) => {
if (optionalQuestionIndexes.includes(questionIndex)) {
markQuestionPassed(questionIndex);
}
});
},
[markQuestionPassed, optionalQuestionIndexes],
);
const activeQuestion = questions?.[activeQuestionIndex];
const showNotice = activeQuestion?.showGuardianNotice;
const isUnder27 = activeQuestion?.required ?? false;
return (
<>