"use client";
import Image from "next/image";
import { useRouter } from "next/navigation";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { IoClose } from "react-icons/io5";
import {
getSubmitPath,
hasCompletedMarriageProfileBasics,
} from "@/lib/get-submit-path";
import QuestionCard from "@/components/Componentes/question-card";
import RequiredStepsCard from "@/components/Componentes/required-steps-card";
import Button from "@/components/Componentes/button";
import InformationSheet from "@/components/Componentes/information-sheet";
import NavigationButton from "@/components/Componentes/navigation-button";
import { getQuestionAnswersStorageKey } from "@/components/Componentes/question-answer-storage";
import { FixToTheEnd } from "@/components/Componentes/fix-to-the-end";
import { PageBackground } from "@/components/Componentes/page-background";
import ErrorToast from "@/components/Componentes/error-toast";
import { useQueryClient } from "@tanstack/react-query";
import { useStartMarriageMatchMutation } from "@/hooks/marriage/use-match-start";
import { useMarriageProfileQuery } from "@/hooks/marriage/use-profile-main";
import {
getFormSection,
useFormOverviewQuery,
} from "@/hooks/marriage/use-form-schema";
import { convertOverviewToFrontendItems } from "@/lib/schema-adapter";
import type { QuestionListItem } from "@/lib/schema-adapter";
import { useCloseServiceOnBack } from "@/hooks/use-close-service-on-back";
import {
clearMatchStartGrace,
markMatchStarted,
} from "@/lib/match-start-grace";
import { localizePath } from "@/translations/config";
import { useI18n } from "@/translations/provider";
import SectionsRequest from "./sections-request";
import { getAssessmentLocalProgress } from "@/lib/assessment-progress";
import { REQUIRED_PROFILE_SECTION_COUNT } from "@/lib/marriage-profile-contract";
export default function QuestionsListPage() {
useCloseServiceOnBack();
const { dictionary: t, locale } = useI18n();
const router = useRouter();
const queryClient = useQueryClient();
const { data: profile, isLoading: isProfileLoading } =
useMarriageProfileQuery();
const { data: overview, isLoading: isSchemaLoading } = useFormOverviewQuery(
"profile",
locale,
);
const isSectionsLoading = false;
const profileTargetPath = useMemo(
() => (profile ? getSubmitPath(profile) : null),
[profile],
);
const isProfileRedirecting =
profileTargetPath !== null &&
profileTargetPath !== "/questions-list" &&
(!hasCompletedMarriageProfileBasics(profile) || profile?.can_edit_profile === false);
useEffect(() => {
if (isProfileRedirecting && profileTargetPath) {
router.replace(localizePath(profileTargetPath, locale));
}
}, [isProfileRedirecting, locale, profileTargetPath, router]);
const startMatchMutation = useStartMarriageMatchMutation({
onSuccess: () => {
markMatchStarted();
router.push(localizePath("/finding-match", locale));
},
onError: () => {
// Never pretend the request went through – the user stays here and can
// retry instead of being parked on the waiting screen forever.
clearMatchStartGrace();
},
});
const [isOptionalInfoSheetOpen, setIsOptionalInfoSheetOpen] = useState(false);
const [selectedSection, setSelectedSection] =
useState(null);
const questionListItems = useMemo(
() => convertOverviewToFrontendItems(overview),
[overview],
);
const [localAssessmentProgress, setLocalAssessmentProgress] = useState<
Map
>(new Map());
useEffect(() => {
const next = new Map();
for (const slug of ["personality_test", "glasser_5_needs_test"]) {
try {
const raw = window.localStorage.getItem(`marriage:tests:${slug}:draft`);
const draft = raw ? JSON.parse(raw) : null;
const progress = getAssessmentLocalProgress(draft, false);
if (progress > 0) next.set(slug, progress);
} catch {
// Ignore malformed local drafts.
}
}
setLocalAssessmentProgress(next);
}, [overview]);
const sectionProgressBySlug = useMemo(() => {
const progressBySlug = new Map();
if (overview?.progress?.sections_progress) {
Object.entries(overview.progress.sections_progress).forEach(
([slug, prog]) => {
progressBySlug.set(
slug,
Math.max(0, Math.min(100, Math.round(prog.completion_percent))),
);
},
);
}
localAssessmentProgress.forEach((progress, slug) => {
if ((progressBySlug.get(slug) ?? 0) < 100)
progressBySlug.set(slug, progress);
});
// Add fallback for combined section from the schema adapter which attaches it to questionListItems directly
questionListItems.forEach((item) => {
if (!progressBySlug.has(item.slug)) {
progressBySlug.set(item.slug, item.progress);
}
});
return progressBySlug;
}, [overview, questionListItems, localAssessmentProgress]);
const requiredQuestionListItems = useMemo(
() => questionListItems.filter((item) => Boolean(item.required)),
[questionListItems],
);
const completedRequiredSections = useMemo(
() =>
requiredQuestionListItems.filter(
(item) => (sectionProgressBySlug.get(item.slug) ?? 0) >= 100,
).length,
[requiredQuestionListItems, sectionProgressBySlug],
);
const [displayedRequiredSections, setDisplayedRequiredSections] = useState(
() => completedRequiredSections,
);
useEffect(() => {
if (displayedRequiredSections === completedRequiredSections) return;
if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) {
setDisplayedRequiredSections(completedRequiredSections);
return;
}
const direction = completedRequiredSections > displayedRequiredSections ? 1 : -1;
const distance = Math.abs(completedRequiredSections - displayedRequiredSections);
const interval = window.setInterval(() => {
setDisplayedRequiredSections((current) => {
const next = current + direction;
if (next === completedRequiredSections) window.clearInterval(interval);
return next;
});
}, Math.max(90, Math.floor(500 / distance)));
return () => window.clearInterval(interval);
}, [completedRequiredSections, displayedRequiredSections]);
const hasValidRequiredContract =
requiredQuestionListItems.length === REQUIRED_PROFILE_SECTION_COUNT;
useEffect(() => {
if (overview && !hasValidRequiredContract) {
console.error("Required section contract mismatch", {
expected: REQUIRED_PROFILE_SECTION_COUNT,
actual: requiredQuestionListItems.length,
});
}
}, [hasValidRequiredContract, overview, requiredQuestionListItems.length]);
const allRequiredSectionsCompleted = useMemo(() => {
if (!hasValidRequiredContract) {
return false;
}
return requiredQuestionListItems.every((item) => {
const progress = sectionProgressBySlug.get(item.slug) ?? 0;
return progress >= 100;
});
}, [hasValidRequiredContract, requiredQuestionListItems, sectionProgressBySlug]);
const profileStatus = profile?.status;
const isProfileSuspended = profileStatus === "suspended";
const isProfileBlocked =
profileStatus === "in_case" || profileStatus === "matched";
const canStartMatch =
!isProfileSuspended && !isProfileBlocked && allRequiredSectionsCompleted;
const [isSyncError, setIsSyncError] = useState(false);
const [isSyncing, setIsSyncing] = useState(false);
const [toastMessage, setToastMessage] = useState(null);
const syncPendingAnswers = useCallback(async () => {
if (!overview) return;
const { updateMarriageSectionData } = await import(
"@/hooks/marriage/use-section-data"
);
let currentVersion = overview.version;
for (const item of questionListItems) {
const storageKey = getQuestionAnswersStorageKey(item.slug);
const rawValue = window.localStorage.getItem(storageKey);
if (!rawValue) continue;
const storedValue = JSON.parse(rawValue);
if (!storedValue.pending_sync || !Array.isArray(storedValue.fields))
continue;
const pendingKeys = new Set(
Array.isArray(storedValue.pending_keys)
? storedValue.pending_keys
: storedValue.fields.map((field: { key: string }) => field.key),
);
for (const field of storedValue.fields) {
if (!pendingKeys.has(field.key)) continue;
const result = await updateMarriageSectionData(item.slug, {
version: currentVersion,
current_step: storedValue.current_step,
fields: [field],
});
currentVersion = result.version;
pendingKeys.delete(field.key);
storedValue.pending_keys = [...pendingKeys];
window.localStorage.setItem(storageKey, JSON.stringify(storedValue));
}
storedValue.pending_sync = false;
window.localStorage.setItem(storageKey, JSON.stringify(storedValue));
}
}, [overview, questionListItems]);
const prefetchSection = useCallback(
(item: QuestionListItem) => {
const href = localizePath(`/questions-list/${item.slug}`, locale);
router.prefetch(href);
if (
item.slug === "personality_test" ||
item.slug === "glasser_5_needs_test"
)
return;
void queryClient.prefetchQuery({
queryKey: ["marriage", "form-section", "profile", item.slug, locale],
queryFn: () => getFormSection("profile", item.slug, locale),
staleTime: 30 * 1000,
});
},
[locale, queryClient, router],
);
const viewportPrefetchChain = useRef(Promise.resolve());
const viewportPrefetchSlugs = useRef(new Set());
const enqueueViewportPrefetch = useCallback(
(item: QuestionListItem) => {
if (
item.slug === "personality_test" ||
item.slug === "glasser_5_needs_test" ||
viewportPrefetchSlugs.current.has(item.slug)
) {
return;
}
viewportPrefetchSlugs.current.add(item.slug);
viewportPrefetchChain.current = viewportPrefetchChain.current
.catch(() => undefined)
.then(() =>
queryClient.fetchQuery({
queryKey: [
"marriage",
"form-section",
"profile",
item.slug,
locale,
],
queryFn: () => getFormSection("profile", item.slug, locale),
staleTime: 30 * 1000,
}),
)
.then(() => undefined);
},
[locale, queryClient],
);
const prefetchQueueStarted = useRef(false);
useEffect(() => {
if (prefetchQueueStarted.current || !overview) return;
const likelySections = questionListItems
.filter(
(item) =>
item.required &&
(sectionProgressBySlug.get(item.slug) ?? item.progress) < 100,
)
.slice(0, 2);
if (likelySections.length === 0) return;
prefetchQueueStarted.current = true;
let cancelled = false;
const runQueue = async () => {
for (const item of likelySections) {
if (cancelled) return;
try {
await queryClient.fetchQuery({
queryKey: [
"marriage",
"form-section",
"profile",
item.slug,
locale,
],
queryFn: () => getFormSection("profile", item.slug, locale),
staleTime: 30 * 1000,
});
} catch {
// A later interaction or navigation can retry without blocking the list.
}
}
};
const schedule = () => void runQueue();
const idleWindow = window as Window & {
requestIdleCallback?: (
callback: () => void,
options?: { timeout: number },
) => number;
cancelIdleCallback?: (handle: number) => void;
};
const isIdleScheduled = Boolean(idleWindow.requestIdleCallback);
const handle = idleWindow.requestIdleCallback
? idleWindow.requestIdleCallback(schedule, { timeout: 750 })
: globalThis.setTimeout(schedule, 150);
return () => {
cancelled = true;
if (isIdleScheduled) idleWindow.cancelIdleCallback?.(handle as number);
else globalThis.clearTimeout(handle);
};
}, [locale, overview, queryClient, questionListItems, sectionProgressBySlug]);
useEffect(() => {
void syncPendingAnswers().catch(() => setIsSyncError(true));
const handleOnline = () => {
void syncPendingAnswers().catch(() => setIsSyncError(true));
};
window.addEventListener("online", handleOnline);
return () => window.removeEventListener("online", handleOnline);
}, [syncPendingAnswers]);
useEffect(() => {
if (startMatchMutation.isError || isSyncError) {
setToastMessage(
t[
"Sending the match request failed. Please check your connection and try again."
],
);
}
}, [
startMatchMutation.isError,
isSyncError,
t[
"Sending the match request failed. Please check your connection and try again."
],
]);
const handleCloseToast = () => {
setToastMessage(null);
setIsSyncError(false);
startMatchMutation.reset();
};
const isStartMatchDisabled =
startMatchMutation.isPending || isSyncing || !canStartMatch;
const hasIncompleteOptionalSections = useMemo(() => {
return questionListItems.some(
(item) =>
!item.required && (sectionProgressBySlug.get(item.slug) ?? 0) < 100,
);
}, [questionListItems, sectionProgressBySlug]);
const handleStartMatch = async () => {
if (isStartMatchDisabled || isSyncing) {
return;
}
setIsSyncing(true);
setIsSyncError(false);
try {
await syncPendingAnswers();
startMatchMutation.mutate();
} catch (err) {
console.error("Failed to sync pending sections:", err);
setIsSyncError(true);
} finally {
setIsSyncing(false);
}
};
if (
isProfileLoading ||
isSectionsLoading ||
isSchemaLoading ||
isProfileRedirecting
) {
return (
<>
{
e.preventDefault();
if (typeof window !== "undefined" && (window as any).HabibApp) {
(window as any).HabibApp.postMessage(
JSON.stringify({ action: "close_service" }),
);
} else {
router.push("/");
}
}}
/>
{t["Profile registration"]}
{/* Section Card Skeletons (solid blocks like the Meet/checkup
AppShimmer loading — one sweep band runs across each card) */}
{Array.from({ length: 6 }).map((_, idx) => (
))}
{t["Submit"]}
>
);
}
return (
<>
{toastMessage && (
)}
{isOptionalInfoSheetOpen ? (
{
t[
"You've completed all required fields. However, filling in all sections will help us find better matches for you"
]
}
}
onClose={() => setIsOptionalInfoSheetOpen(false)}
buttons={({ close }) => (
{t["Cancel"]}
{
close();
handleStartMatch();
}}
>
{t["Submit"]}
)}
/>
) : null}
{selectedSection ? (
(
{selectedSection.title}
)}
description={
{selectedSection.summary}
}
onClose={() => setSelectedSection(null)}
className="text-left"
/>
) : null}
{
e.preventDefault();
if (typeof window !== "undefined" && (window as any).HabibApp) {
(window as any).HabibApp.postMessage(
JSON.stringify({ action: "close_service" }),
);
} else {
router.push("/");
}
}}
/>
{t["Profile registration"]}
{questionListItems.map((item) => (
setSelectedSection(section)}
onNearViewport={enqueueViewportPrefetch}
onPrefetch={prefetchSection}
/>
))}
{
if (hasIncompleteOptionalSections) {
setIsOptionalInfoSheetOpen(true);
return;
}
handleStartMatch();
}}
>
{t["Submit"]}
>
);
}