"use client";

import Image from "next/image";
import mbhsLogo from "@/public/images/mbhs-logo.png";
import { useState } from "react";
import { Link, useRouter, usePathname } from "@/i18n/navigation";
import FlagIcon from "@/components/ui/FlagIcon";
import { useParams } from "next/navigation";
import { useTranslations, useLocale } from "next-intl";
import { toast } from "react-hot-toast";
import {
  usePublicAssessmentControllerValidateTokenV1,
  usePublicAssessmentControllerGetQuestionsV1,
  usePublicAssessmentControllerSubmitAnswersV1,
} from "@/api/user/public-assessment/public-assessment";

// Disclaimer Screen Component
function DisclaimerScreen({ t, locale, router, pathname, onAccept }: {
  t: any;
  locale: string;
  router: any;
  pathname: string;
  onAccept: () => void;
}) {
  return (
    <div className="min-h-screen bg-gray-50">
      {/* Header */}
      <header className="bg-white border-b border-gray-100 sticky top-0 z-40">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex items-center justify-between h-16">
            <Link href="/" className="flex items-center gap-2">
              <Image src={mbhsLogo} alt="MBHS" width={40} height={40} className="w-10 h-10 rounded-lg" />
              <span className="text-xl font-bold text-gray-900">MBHS</span>
            </Link>
            <button
              onClick={() => { const newLocale = locale === "en" ? "es" : "en"; localStorage.setItem("lang", newLocale); router.replace(pathname, { locale: newLocale }); }}
              className="flex items-center gap-2 px-3 py-1.5 bg-gray-100 hover:bg-gray-200 rounded-full text-sm font-medium text-gray-700 transition cursor-pointer"
            >
              <FlagIcon locale={locale as "en" | "es"} />
              <span>{locale === "en" ? "EN" : "ES"}</span>
            </button>
          </div>
        </div>
      </header>

      {/* Content */}
      <main className="pt-8 pb-8">
        <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-8">
            {/* Title */}
            <div className="text-center mb-8">
              <h1 className="text-2xl sm:text-3xl font-semibold text-gray-900 mb-2">
                {t("individual.importantInfo.title")}
              </h1>
              <p className="text-gray-500">
                {t("individual.importantInfo.subtitle")}
              </p>
            </div>

            {/* Crisis Information Box */}
            <div className="bg-red-50 border border-red-100 rounded-xl p-6 mb-8">
              <div className="flex items-start gap-3 mb-4">
                <svg className="w-6 h-6 text-red-500 flex-shrink-0 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                  <path strokeLinecap="round" strokeLinejoin="round" d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" />
                </svg>
                <h2 className="text-lg font-semibold text-red-600">
                  {t("individual.importantInfo.crisisTitle")}
                </h2>
              </div>
              <p className="text-red-700 mb-4">
                {t("individual.importantInfo.crisisText1")}{" "}
                {t("individual.importantInfo.crisisText2")}
              </p>
              <div className="mb-4">
                <h3 className="font-semibold text-red-700 mb-2">
                  {t("individual.importantInfo.lifeline")}
                </h3>
                <ul className="space-y-1 text-red-700">
                  <li className="flex items-center gap-2">
                    <span className="w-1 h-1 bg-red-500 rounded-full"></span>
                    {t("individual.importantInfo.dial988")}
                  </li>
                  <li className="flex items-center gap-2">
                    <span className="w-1 h-1 bg-red-500 rounded-full"></span>
                    {t("individual.importantInfo.text988")}
                  </li>
                  <li className="flex items-center gap-2">
                    <span className="w-1 h-1 bg-red-500 rounded-full"></span>
                    {t("individual.importantInfo.visit988")}
                  </li>
                </ul>
              </div>
              <div>
                <h3 className="font-semibold text-red-700 mb-2">
                  {t("individual.importantInfo.nami")}
                </h3>
                <ul className="space-y-1 text-red-700">
                  <li className="flex items-center gap-2">
                    <span className="w-1 h-1 bg-red-500 rounded-full"></span>
                    {t("individual.importantInfo.namiCall")}
                  </li>
                  <li className="flex items-center gap-2">
                    <span className="w-1 h-1 bg-red-500 rounded-full"></span>
                    {t("individual.importantInfo.namiText")}
                  </li>
                  <li className="flex items-center gap-2">
                    <span className="w-1 h-1 bg-red-500 rounded-full"></span>
                    {t("individual.importantInfo.namiEmail")}
                  </li>
                </ul>
              </div>
            </div>

            {/* Risk Disclaimer & Informed Consent */}
            <div className="mb-8">
              <h2 className="text-xl font-semibold text-gray-900 mb-4">
                {t("individual.importantInfo.disclaimerTitle")}
              </h2>
              <p className="text-gray-600 mb-6">
                {t("individual.importantInfo.disclaimerText")}
              </p>
              <h3 className="font-semibold text-gray-900 mb-3">
                {t("individual.importantInfo.limitationsTitle")}
              </h3>
              <ul className="space-y-2 text-gray-600 mb-6">
                <li>{t("individual.importantInfo.limitation1")}</li>
                <li>{t("individual.importantInfo.limitation2")}</li>
                <li>{t("individual.importantInfo.limitation3")}</li>
                <li>{t("individual.importantInfo.limitation4")}</li>
              </ul>
              <h3 className="font-semibold text-gray-900 mb-3">
                {t("individual.importantInfo.expectTitle")}
              </h3>
              <ul className="space-y-2 text-gray-600">
                <li>{t("individual.importantInfo.expect1")}</li>
                <li>{t("individual.importantInfo.expect2")}</li>
                <li>{t("individual.importantInfo.expect3")}</li>
              </ul>
            </div>

            {/* Continue Button */}
            <div className="flex justify-center">
              <button
                onClick={onAccept}
                className="px-8 py-3 text-sm font-medium text-white bg-[#3B9EC9] rounded-full hover:bg-[#3B9EC9]/90 transition cursor-pointer"
              >
                {t("individual.importantInfo.acknowledgeBtn")}
              </button>
            </div>
          </div>
        </div>
      </main>
    </div>
  );
}

// Invalid Token Screen Component
function InvalidTokenScreen({ t, locale, router, pathname }: {
  t: any;
  locale: string;
  router: any;
  pathname: string;
}) {
  return (
    <div className="min-h-screen bg-gray-50">
      {/* Header */}
      <header className="bg-white border-b border-gray-100 sticky top-0 z-40">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex items-center justify-between h-16">
            {/* Logo - links to home page */}
            <Link href="/" className="flex items-center gap-2">
              <Image src={mbhsLogo} alt="MBHS" width={40} height={40} className="w-10 h-10 rounded-lg" />
              <span className="text-xl font-bold text-gray-900">MBHS</span>
            </Link>

            {/* Language Toggle */}
            <button
              onClick={() => { const newLocale = locale === "en" ? "es" : "en"; localStorage.setItem("lang", newLocale); router.replace(pathname, { locale: newLocale }); }}
              className="flex items-center gap-2 px-3 py-1.5 bg-gray-100 hover:bg-gray-200 rounded-full text-sm font-medium text-gray-700 transition cursor-pointer"
            >
              <FlagIcon locale={locale as "en" | "es"} />
              <span>{locale === "en" ? "EN" : "ES"}</span>
            </button>
          </div>
        </div>
      </header>

      {/* Content */}
      <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <div className="flex flex-col items-center justify-center py-32">
          {/* Error Icon */}
          <div className="mb-6">
            <svg width="100" height="100" viewBox="0 0 100 100" fill="none" xmlns="http://www.w3.org/2000/svg">
              <circle cx="50" cy="50" r="45" stroke="#EF4444" strokeWidth="3" fill="none" />
              <path d="M35 35L65 65M65 35L35 65" stroke="#EF4444" strokeWidth="4" strokeLinecap="round" />
            </svg>
          </div>

          {/* Title */}
          <h2 className="text-xl font-bold text-gray-900 mb-2">
            {t("assessment.invalidToken")}
          </h2>

          {/* Description */}
          <p className="text-gray-500 text-sm text-center max-w-sm mb-6">
            {t("assessment.invalidTokenDescription")}
          </p>
        </div>
      </main>
    </div>
  );
}

export default function AssessmentPage() {
  const router = useRouter();
  const params = useParams();
  const t = useTranslations();
  const locale = useLocale();
  const pathname = usePathname();

  const token = params.token as string;

  // sessionStorage keys — scoped to token so different assessments don't share state
  const SS_DISC = `disclaimer_accepted_${token}`;
  const SS_QNUM = `assess_qnum_${token}`;
  const SS_ANS  = `assess_ans_${token}`;

  const [currentQuestion, setCurrentQuestion] = useState<number>(() => {
    if (typeof window !== "undefined") {
      return parseInt(sessionStorage.getItem(SS_QNUM) ?? "0", 10) || 0;
    }
    return 0;
  });
  const [answers, setAnswers] = useState<Record<string, number>>(() => {
    if (typeof window !== "undefined") {
      try { return JSON.parse(sessionStorage.getItem(SS_ANS) ?? "{}"); } catch { return {}; }
    }
    return {};
  });
  const [disclaimerAccepted, setDisclaimerAccepted] = useState(() => {
    if (typeof window !== "undefined") {
      return sessionStorage.getItem(SS_DISC) === "true";
    }
    return false;
  });

  const acceptDisclaimer = () => {
    sessionStorage.setItem(SS_DISC, "true");
    setDisclaimerAccepted(true);
  };

  // Validate token and get assessment info
  const {
    data: assessmentData,
    isLoading: isValidating,
    error: validationError,
  } = usePublicAssessmentControllerValidateTokenV1(token, {
    query: {
      enabled: !!token,
      retry: false,
    },
  });

  const assessmentInfo = (assessmentData as any)?.data;
  const clientName = assessmentInfo?.client_name || "";
  const assessmentStatus = assessmentInfo?.status;

  // Fetch questions - enabled when token validated and assessment is not in a terminal state.
  // Do NOT limit to exactly "pending" — backend may return other active-state values.
  const isTerminalStatus = assessmentStatus === "completed" || assessmentStatus === "expired";
  const shouldFetchQuestions = !!token && !isValidating && !validationError && !!assessmentInfo && !isTerminalStatus;

  const {
    data: questionsData,
    isLoading: isLoadingQuestions,
    error: questionsError,
  } = usePublicAssessmentControllerGetQuestionsV1(token, {
    query: {
      // Include locale in query key so questions re-fetch when language changes
      queryKey: [`/v1/public/assessment/${token}/questions`, locale],
      enabled: shouldFetchQuestions,
    },
  });

  // Submit answers mutation
  const submitAnswersMutation = usePublicAssessmentControllerSubmitAnswersV1();

  // Extract questions from response - handle different possible API response shapes
  const questionsResponse = questionsData as any;
  const questions: any[] =
    questionsResponse?.data?.questions ||
    questionsResponse?.data?.data?.questions ||
    (Array.isArray(questionsResponse?.data) ? questionsResponse.data : null) ||
    questionsResponse?.questions ||
    [];
  const totalQuestions = questions.length;
  const progress = totalQuestions > 0 ? Math.round(((currentQuestion + 1) / totalQuestions) * 100) : 0;

  const currentQuestionData = questions[currentQuestion];
  const selectedAnswer = currentQuestionData ? answers[currentQuestionData.uuid] : undefined;

  // Check if current question uses count-type response (Q29)
  const isQuestion29 = currentQuestion === 28 && totalQuestions === 29;
  const isCountType = currentQuestionData?.response_type === "count" || isQuestion29;

  // Answer options
  const answerOptions = isCountType
    ? [
        { value: 0, label: t("assessment.countOption0") },
        { value: 1, label: t("assessment.countOption1") },
        { value: 2, label: t("assessment.countOption2") },
        { value: 3, label: t("assessment.countOption3") },
      ]
    : [
        { value: 0, label: t("assessment.option0") },
        { value: 1, label: t("assessment.option1") },
        { value: 2, label: t("assessment.option2") },
        { value: 3, label: t("assessment.option3") },
      ];

  const handleSelectAnswer = (value: number) => {
    const currentQuestionUuid = questions[currentQuestion]?.uuid;
    if (currentQuestionUuid) {
      const updated = { ...answers, [currentQuestionUuid]: value };
      setAnswers(updated);
      sessionStorage.setItem(SS_ANS, JSON.stringify(updated));
    }
  };

  const handlePrevious = () => {
    if (currentQuestion > 0) {
      const prev = currentQuestion - 1;
      setCurrentQuestion(prev);
      sessionStorage.setItem(SS_QNUM, String(prev));
    }
  };

  const handleNext = () => {
    const currentQuestionUuid = questions[currentQuestion]?.uuid;
    const currentAnswer = answers[currentQuestionUuid];

    if (currentAnswer === undefined) {
      return; // No answer selected
    }

    // Save current answer to database
    submitAnswersMutation.mutate(
      {
        token: token,
        data: {
          answers: [
            {
              question_uuid: currentQuestionUuid,
              answer: currentAnswer,
            },
          ],
        },
      },
      {
        onSuccess: () => {
          if (currentQuestion < totalQuestions - 1) {
            // Move to next question
            const next = currentQuestion + 1;
            setCurrentQuestion(next);
            sessionStorage.setItem(SS_QNUM, String(next));
          } else {
            // Last question — clear session cache then navigate to results
            sessionStorage.removeItem(SS_DISC);
            sessionStorage.removeItem(SS_QNUM);
            sessionStorage.removeItem(SS_ANS);
            router.push(`/assessment/${token}/results`);
          }
        },
        onError: (error: any) => {
          console.error("Failed to save answer:", error);
          // Check if assessment is already completed
          if (error?.response?.data?.message?.includes("completed")) {
            router.push(`/assessment/${token}/results`);
            return;
          }
          toast.error(t("assessment.submitError"));
        },
      }
    );
  };

  const getOptionStyles = (_index: number, isSelected: boolean) => {
    if (isSelected) {
      return "bg-[#E8F7FA] border-[#3B9EC9] text-gray-900";
    }
    return "bg-white border-gray-300 text-gray-700";
  };

  const getRadioStyles = (_index: number, isSelected: boolean) => {
    if (isSelected) {
      return "border-[#3B9EC9] bg-[#3B9EC9]";
    }
    return "border-gray-300 bg-white";
  };

  // Loading state - only for initial validation
  if (isValidating) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <svg className="animate-spin w-10 h-10 text-[#3B9EC9] mx-auto mb-4" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
            <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
            <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
          </svg>
          <p className="text-gray-600">{t("assessment.loading")}</p>
        </div>
      </div>
    );
  }

  // Invalid token or error
  if (validationError || !assessmentInfo) {
    return (
      <InvalidTokenScreen
        t={t}
        locale={locale}
        router={router}
        pathname={pathname}
      />
    );
  }

  // Assessment already completed - redirect to results
  if (assessmentStatus === "completed") {
    router.push(`/assessment/${token}/results`);
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <svg className="animate-spin w-10 h-10 text-[#3B9EC9] mx-auto mb-4" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
            <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
            <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
          </svg>
          <p className="text-gray-600">{t("assessment.redirectingToResults")}</p>
        </div>
      </div>
    );
  }

  // Assessment expired
  if (assessmentStatus === "expired") {
    return (
      <div className="min-h-screen bg-gray-50">
        <header className="bg-white border-b border-gray-100 sticky top-0 z-40">
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div className="flex items-center justify-between h-16">
              <div className="flex items-center gap-2">
                <Image src={mbhsLogo} alt="MBHS" width={40} height={40} className="w-10 h-10 rounded-lg" />
                <span className="text-xl font-bold text-gray-900">MBHS</span>
              </div>
              <button
                onClick={() => { const newLocale = locale === "en" ? "es" : "en"; localStorage.setItem("lang", newLocale); router.replace(pathname, { locale: newLocale }); }}
                className="flex items-center gap-2 px-3 py-1.5 bg-gray-100 hover:bg-gray-200 rounded-full text-sm font-medium text-gray-700 transition cursor-pointer"
              >
                <FlagIcon locale={locale as "en" | "es"} />
                <span>{locale === "en" ? "EN" : "ES"}</span>
              </button>
            </div>
          </div>
        </header>
        <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
          <div className="flex flex-col items-center justify-center py-32">
            <div className="mb-6">
              <svg width="100" height="100" viewBox="0 0 100 100" fill="none" xmlns="http://www.w3.org/2000/svg">
                <circle cx="50" cy="50" r="45" stroke="#F59E0B" strokeWidth="3" fill="none" />
                <path d="M50 30V55M50 65V70" stroke="#F59E0B" strokeWidth="4" strokeLinecap="round" />
              </svg>
            </div>
            <h2 className="text-xl font-bold text-gray-900 mb-2">
              {t("assessment.expired")}
            </h2>
            <p className="text-gray-500 text-sm text-center max-w-sm">
              {t("assessment.expiredDescription")}
            </p>
          </div>
        </main>
      </div>
    );
  }

  // No questions loaded - show error if we're done loading and still have no questions
  if (questionsError || (shouldFetchQuestions && !isLoadingQuestions && questions.length === 0)) {
    return (
      <InvalidTokenScreen
        t={t}
        locale={locale}
        router={router}
        pathname={pathname}
      />
    );
  }

  // Still loading questions after validation passed
  if (shouldFetchQuestions && isLoadingQuestions) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <svg className="animate-spin w-10 h-10 text-[#3B9EC9] mx-auto mb-4" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
            <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
            <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
          </svg>
          <p className="text-gray-600">{t("assessment.loading")}</p>
        </div>
      </div>
    );
  }

  // Disclaimer Screen - shown before questions
  if (!disclaimerAccepted) {
    return (
      <DisclaimerScreen
        t={t}
        locale={locale}
        router={router}
        pathname={pathname}
        onAccept={acceptDisclaimer}
      />
    );
  }

  // Questions Screen
  return (
    <div className="min-h-screen bg-gray-50">
      {/* Header */}
      <header className="bg-white border-b border-gray-100 sticky top-0 z-40">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex items-center justify-between h-16">
            {/* Logo - links to home page */}
            <Link href="/" className="flex items-center gap-2">
              <Image src={mbhsLogo} alt="MBHS" width={40} height={40} className="w-10 h-10 rounded-lg" />
              <span className="text-xl font-bold text-gray-900">MBHS</span>
            </Link>

            {/* Right side */}
            <div className="flex items-center gap-4">
              {/* Language Toggle */}
              <button
                onClick={() => { const newLocale = locale === "en" ? "es" : "en"; localStorage.setItem("lang", newLocale); router.replace(pathname, { locale: newLocale }); }}
                className="flex items-center gap-2 px-3 py-1.5 bg-gray-100 hover:bg-gray-200 rounded-full text-sm font-medium text-gray-700 transition cursor-pointer"
              >
                <FlagIcon locale={locale as "en" | "es"} />
                <span>{locale === "en" ? "EN" : "ES"}</span>
              </button>
            </div>
          </div>
        </div>
      </header>

      {/* Main Content */}
      <main className="max-w-2xl mx-auto px-4 py-8">
        {/* Welcome Card */}
        {clientName && (
          <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-4 mb-6">
            <div className="flex items-center gap-4">
              <div className="w-12 h-12 rounded-full bg-[#3B9EC9]/10 flex items-center justify-center flex-shrink-0">
                <svg className="w-6 h-6 text-[#3B9EC9]" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M15.75 6a3.75 3.75 0 11-7.5 0 3.75 3.75 0 017.5 0zM4.501 20.118a7.5 7.5 0 0114.998 0A17.933 17.933 0 0112 21.75c-2.676 0-5.216-.584-7.499-1.632z" />
                </svg>
              </div>
              <div>
                <p className="text-sm text-gray-500">{t("assessment.welcome")}</p>
                <h3 className="text-lg font-semibold text-gray-900">{clientName}</h3>
              </div>
            </div>
          </div>
        )}

        {/* Screening Card */}
        <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-8">
          {/* Progress Header */}
          <div className="flex items-center justify-between mb-2">
            <span className="text-sm font-medium text-gray-700">
              {t("assessment.questionOf")} {currentQuestion + 1} {t("assessment.of")} {totalQuestions}
            </span>
            <span className="text-sm text-gray-500">{progress}% {t("assessment.complete")}</span>
          </div>

          {/* Progress Bar */}
          <div className="h-2 bg-gray-200 rounded-full mb-8 overflow-hidden">
            <div
              className="h-full bg-[#3B9EC9] rounded-full transition-all duration-300"
              style={{ width: `${progress}%` }}
            />
          </div>

          {/* Question */}
          <h2 className="text-lg font-medium text-gray-900 mb-6">
            {locale === "es" && currentQuestionData?.text_es
              ? currentQuestionData.text_es
              : (currentQuestionData?.text || "")}
          </h2>

          {/* Options */}
          <div className="space-y-3 mb-8">
            {answerOptions.map((option, index) => {
              const isSelected = selectedAnswer === option.value;
              return (
                <button
                  key={option.value}
                  onClick={() => handleSelectAnswer(option.value)}
                  className={`w-full flex items-center gap-4 px-5 py-4 rounded-xl border-2 transition cursor-pointer ${getOptionStyles(index, isSelected)}`}
                >
                  <div
                    className={`w-6 h-6 rounded-full border-2 flex items-center justify-center transition ${getRadioStyles(index, isSelected)}`}
                  >
                    {isSelected && (
                      <div className="w-2 h-2 rounded-full bg-white" />
                    )}
                  </div>
                  <span className="text-sm font-medium">{option.label}</span>
                </button>
              );
            })}
          </div>

          {/* Navigation Buttons */}
          <div className="flex items-center gap-4">
            <button
              onClick={handlePrevious}
              disabled={currentQuestion === 0}
              className="flex items-center gap-2 px-6 py-3 text-sm font-medium text-[#3B9EC9] bg-white border border-[#3B9EC9] rounded-full hover:bg-[#3B9EC9]/5 disabled:opacity-50 disabled:cursor-not-allowed transition cursor-pointer"
            >
              <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                <path strokeLinecap="round" strokeLinejoin="round" d="M15 19l-7-7 7-7" />
              </svg>
              {t("assessment.previous")}
            </button>
            <button
              onClick={handleNext}
              disabled={selectedAnswer === undefined || submitAnswersMutation.isPending}
              className="flex-1 flex items-center justify-center gap-2 px-6 py-3 text-sm font-medium text-white bg-[#3B9EC9] rounded-full hover:bg-[#2D8AB5] disabled:opacity-50 disabled:cursor-not-allowed transition cursor-pointer"
            >
              {submitAnswersMutation.isPending ? (
                <>
                  <div className="inline-block animate-spin rounded-full h-5 w-5 border-b-2 border-white"></div>
                  <span>{t("assessment.submitting")}</span>
                </>
              ) : (
                <>
                  {currentQuestion === totalQuestions - 1
                    ? t("assessment.submitAssessment")
                    : t("assessment.nextQuestion")
                  }
                  <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                    <path strokeLinecap="round" strokeLinejoin="round" d="M9 5l7 7-7 7" />
                  </svg>
                </>
              )}
            </button>
          </div>
        </div>
      </main>
    </div>
  );
}
