UNPKG

analytica-frontend-lib

Version:

Repositório público dos componentes utilizados nas plataformas da Analytica Ensino

26,572 lines 1.01 MB
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/index.ts
var src_exports = {};
__export(src_exports, {
  ACTIVITY_AVAILABILITY: () => ACTIVITY_AVAILABILITY,
  ACTIVITY_FILTER_STATUS_OPTIONS: () => ACTIVITY_FILTER_STATUS_OPTIONS,
  ANSWER_STATUS: () => ANSWER_STATUS,
  AccordionGroup: () => AccordionGroup,
  ActivitiesHistory: () => ActivitiesHistory,
  ActivityApiStatus: () => GenericApiStatus,
  ActivityBadgeActionType: () => BadgeActionType,
  ActivityCardQuestionBanks: () => ActivityCardQuestionBanks,
  ActivityCardQuestionPreview: () => ActivityCardQuestionPreview,
  ActivityDetails: () => ActivityDetails,
  ActivityDisplayStatus: () => GenericDisplayStatus,
  ActivityDraftType: () => ActivityDraftType,
  ActivityFilters: () => ActivityFilters,
  ActivityFiltersPopover: () => ActivityFiltersPopover,
  ActivityPreview: () => ActivityPreview,
  ActivityStatus: () => ActivityStatus,
  ActivityType: () => ActivityType,
  Alert: () => Alert_default,
  AlertDialog: () => AlertDialog,
  AlertsManager: () => AlertsManager,
  AlertsManagerView: () => AlertsManagerView,
  AlternativesList: () => AlternativesList,
  AuthProvider: () => AuthProvider,
  Badge: () => Badge_default,
  BreadcrumbMenu: () => BreadcrumbMenu,
  Button: () => Button_default,
  CHAT_MESSAGE_TYPES: () => CHAT_MESSAGE_TYPES,
  CORRECTION_QUESTION_STATUS: () => QUESTION_STATUS2,
  Calendar: () => Calendar_default,
  CardAccordation: () => CardAccordation,
  CardActivitiesResults: () => CardActivitiesResults,
  CardAudio: () => CardAudio,
  CardPerformance: () => CardPerformance,
  CardProgress: () => CardProgress,
  CardQuestions: () => CardQuestions,
  CardResults: () => CardResults,
  CardSimulado: () => CardSimulado,
  CardSimulationHistory: () => CardSimulationHistory,
  CardStatus: () => CardStatus,
  CardTest: () => CardTest,
  CardTopic: () => CardTopic,
  Chat: () => Chat,
  ChatLoading: () => ChatLoading,
  CheckBox: () => CheckBox_default,
  CheckboxGroup: () => CheckboxGroup,
  CheckboxList: () => CheckboxList_default,
  CheckboxListItem: () => CheckboxListItem,
  Chips: () => Chips_default,
  CorrectActivityModal: () => CorrectActivityModal_default,
  CreateActivity: () => CreateActivity,
  DEFAULT_ACTIVITIES_PAGINATION: () => DEFAULT_ACTIVITIES_PAGINATION,
  DEFAULT_MODELS_PAGINATION: () => DEFAULT_MODELS_PAGINATION,
  DIFFICULTY_LEVEL_ENUM: () => DIFFICULTY_LEVEL_ENUM,
  DateTimeInput: () => DateTimeInput_default,
  Divider: () => Divider_default,
  DownloadButton: () => DownloadButton_default,
  DropdownMenu: () => DropdownMenu_default,
  DropdownMenuContent: () => DropdownMenuContent,
  DropdownMenuItem: () => DropdownMenuItem,
  DropdownMenuSeparator: () => DropdownMenuSeparator,
  DropdownMenuTrigger: () => DropdownMenuTrigger,
  ERROR_MESSAGES: () => ERROR_MESSAGES,
  EmptyState: () => EmptyState_default,
  FileAttachment: () => FileAttachment_default,
  FilterModal: () => FilterModal,
  GOAL_FILTER_STATUS_OPTIONS: () => GOAL_FILTER_STATUS_OPTIONS,
  GOAL_STATUS_OPTIONS: () => GOAL_STATUS_OPTIONS,
  GoalApiStatus: () => GenericApiStatus,
  GoalBadgeActionType: () => BadgeActionType,
  GoalDisplayStatus: () => GenericDisplayStatus,
  IconButton: () => IconButton_default,
  IconRender: () => IconRender_default,
  IconRoundedButton: () => IconRoundedButton_default,
  ImageUpload: () => ImageUpload,
  Input: () => Input_default,
  LatexRenderer: () => LatexRenderer_default,
  LoadingModal: () => loadingModal_default,
  Menu: () => Menu_default,
  MenuContent: () => MenuContent,
  MenuItem: () => MenuItem,
  MenuLabel: () => MenuLabel,
  MenuOverflow: () => MenuOverflow,
  Modal: () => Modal_default,
  MultipleChoiceList: () => MultipleChoiceList,
  NavButton: () => NavButton_default,
  NoSearchResult: () => NoSearchResult_default,
  NotFound: () => NotFound_default,
  NotificationCard: () => NotificationCard_default,
  NotificationEntityType: () => NotificationEntityType,
  PROFILE_ROLES: () => PROFILE_ROLES,
  ProfileMenuFooter: () => ProfileMenuFooter,
  ProfileMenuHeader: () => ProfileMenuHeader,
  ProfileMenuInfo: () => ProfileMenuInfo,
  ProfileMenuSection: () => ProfileMenuSection,
  ProfileMenuTrigger: () => ProfileMenuTrigger,
  ProfileToggleTheme: () => ProfileToggleTheme,
  ProgressBar: () => ProgressBar_default,
  ProgressCircle: () => ProgressCircle_default,
  ProtectedRoute: () => ProtectedRoute,
  PublicRoute: () => PublicRoute,
  QUESTION_DIFFICULTY: () => QUESTION_DIFFICULTY,
  QUESTION_STATUS: () => QUESTION_STATUS,
  QUESTION_STATUS_ENUM: () => QUESTION_STATUS_ENUM,
  QUESTION_TYPE: () => QUESTION_TYPE,
  QUIZ_TYPE: () => QUIZ_TYPE,
  QuestionsPdfContent: () => QuestionsPdfContent,
  QuestionsPdfGenerator: () => QuestionsPdfGenerator,
  Quiz: () => Quiz,
  QuizAlternative: () => QuizAlternative,
  QuizConnectDots: () => QuizConnectDots,
  QuizContent: () => QuizContent,
  QuizDissertative: () => QuizDissertative,
  QuizFooter: () => QuizFooter,
  QuizHeader: () => QuizHeader,
  QuizHeaderResult: () => QuizHeaderResult,
  QuizImageQuestion: () => QuizImageQuestion,
  QuizListResult: () => QuizListResult,
  QuizListResultByMateria: () => QuizListResultByMateria,
  QuizMultipleChoice: () => QuizMultipleChoice,
  QuizQuestionList: () => QuizQuestionList,
  QuizResultHeaderTitle: () => QuizResultHeaderTitle,
  QuizResultPerformance: () => QuizResultPerformance,
  QuizResultTitle: () => QuizResultTitle,
  QuizTitle: () => QuizTitle,
  QuizTrueOrFalse: () => QuizTrueOrFalse,
  Radio: () => Radio_default,
  RadioGroup: () => RadioGroup,
  RadioGroupItem: () => RadioGroupItem,
  RecommendedLessonDetails: () => RecommendedLessonDetails_default,
  RecommendedLessonsHistory: () => RecommendedLessonsHistory,
  STUDENT_ACTIVITY_STATUS: () => STUDENT_ACTIVITY_STATUS,
  SUBTYPE_ENUM: () => SUBTYPE_ENUM,
  Search: () => Search_default,
  Select: () => Select_default,
  SelectContent: () => SelectContent,
  SelectItem: () => SelectItem,
  SelectTrigger: () => SelectTrigger,
  SelectValue: () => SelectValue,
  SelectionButton: () => SelectionButton_default,
  SendActivityModal: () => SendActivityModal_default,
  Skeleton: () => Skeleton,
  SkeletonCard: () => SkeletonCard,
  SkeletonCircle: () => SkeletonCircle,
  SkeletonList: () => SkeletonList,
  SkeletonRectangle: () => SkeletonRectangle,
  SkeletonRounded: () => SkeletonRounded,
  SkeletonTable: () => SkeletonTable,
  SkeletonText: () => SkeletonText,
  StatisticsCard: () => StatisticsCard,
  Stepper: () => Stepper_default,
  StudentLessonStatus: () => StudentLessonStatus,
  StudentPerformanceModal: () => StudentPerformanceModal,
  SubjectEnum: () => SubjectEnum,
  SubjectInfo: () => SubjectInfo,
  Support: () => Support_default,
  SupportCategory: () => SupportCategory,
  SupportStatus: () => SupportStatus,
  Table: () => Table_default,
  TableBody: () => TableBody,
  TableCaption: () => TableCaption,
  TableCell: () => TableCell,
  TableFooter: () => TableFooter,
  TableHead: () => TableHead,
  TableHeader: () => TableHeader,
  TablePagination: () => TablePagination_default,
  TableProvider: () => TableProvider_default,
  TableRow: () => TableRow,
  Text: () => Text_default,
  TextArea: () => TextArea_default,
  ThemeToggle: () => ThemeToggle,
  TicketModal: () => TicketModal,
  Toast: () => Toast_default,
  Toaster: () => Toaster_default,
  VideoPlayer: () => VideoPlayer_default,
  WS_STATES: () => WS_STATES,
  Whiteboard: () => Whiteboard_default,
  activitiesHistoryApiResponseSchema: () => activitiesHistoryApiResponseSchema,
  activityModelsApiResponseSchema: () => activityModelsApiResponseSchema,
  buildUserFilterData: () => buildUserFilterData,
  cn: () => cn,
  convertActivityFiltersToQuestionsFilter: () => convertActivityFiltersToQuestionsFilter,
  createActivitiesHistoryHook: () => createActivitiesHistoryHook,
  createActivityFiltersDataHook: () => createActivityFiltersDataHook,
  createActivityModelsHook: () => createActivityModelsHook,
  createNotificationStore: () => createNotificationStore,
  createNotificationsHook: () => createNotificationsHook,
  createQuestionsListHook: () => createQuestionsListHook,
  createRecommendedLessonDetailsHook: () => createRecommendedLessonDetailsHook,
  createRecommendedLessonsHistoryHook: () => createRecommendedLessonsHistoryHook,
  createUseActivitiesHistory: () => createUseActivitiesHistory,
  createUseActivityFiltersData: () => createUseActivityFiltersData,
  createUseActivityModels: () => createUseActivityModels,
  createUseChat: () => createUseChat,
  createUseChatRooms: () => createUseChatRooms,
  createUseNotificationStore: () => createUseNotificationStore,
  createUseNotifications: () => createUseNotifications,
  createUseQuestionsList: () => createUseQuestionsList,
  createUseRecommendedLessonDetails: () => createUseRecommendedLessonDetails,
  createUseRecommendedLessonsHistory: () => createUseRecommendedLessonsHistory,
  createZustandAuthAdapter: () => createZustandAuthAdapter,
  deriveStudentStatus: () => deriveStudentStatus,
  determineGoalStatus: () => determineGoalStatus,
  formatDateToBrazilian: () => formatDateToBrazilian,
  formatDaysToComplete: () => formatDaysToComplete,
  formatFileSize: () => formatFileSize,
  formatQuestionNumbers: () => formatQuestionNumbers,
  formatTimeAgo: () => formatTimeAgo,
  formatTimeSpent: () => formatTimeSpent,
  generateFileId: () => generateFileId,
  getActivityStatusBadgeAction: () => getActivityStatusBadgeAction,
  getCategoryIcon: () => getCategoryIcon,
  getCategoryText: () => getCategoryText,
  getChatUserInfo: () => getChatUserInfo,
  getChatWsUrl: () => getChatWsUrl,
  getClassOptionsFromUserData: () => getClassOptionsFromUserData,
  getDeviceType: () => getDeviceType,
  getGoalStatusBadgeAction: () => getGoalStatusBadgeAction,
  getQuestionStatusBadgeConfig: () => getQuestionStatusBadgeConfig,
  getRootDomain: () => getRootDomain,
  getSchoolOptionsFromUserData: () => getSchoolOptionsFromUserData,
  getSchoolYearOptionsFromUserData: () => getSchoolYearOptionsFromUserData,
  getSelectedIdsFromCategories: () => getSelectedIdsFromCategories,
  getStatusBadge: () => getStatusBadge,
  getStatusBadgeAction: () => getStatusBadgeAction,
  getStatusBadgeConfig: () => getStatusBadgeConfig,
  getStatusText: () => getStatusText,
  getStudentStatusBadgeAction: () => getStudentStatusBadgeAction,
  getSubjectColorClass: () => getSubjectColorClass,
  getSubjectColorWithOpacity: () => getSubjectColorWithOpacity,
  getSubjectIcon: () => getSubjectIcon,
  getSubjectInfo: () => getSubjectInfo,
  getSubjectName: () => getSubjectName,
  getSubjectOptionsFromUserData: () => getSubjectOptionsFromUserData,
  goalApiResponseSchema: () => goalApiResponseSchema,
  goalDetailsApiResponseSchema: () => goalDetailsApiResponseSchema,
  goalsHistoryApiResponseSchema: () => goalsHistoryApiResponseSchema,
  handleActivityFetchError: () => handleActivityFetchError,
  handleGoalFetchError: () => handleGoalFetchError,
  handleLessonDetailsFetchError: () => handleLessonDetailsFetchError,
  handleModelFetchError: () => handleModelFetchError,
  historyApiResponseSchema: () => historyApiResponseSchema,
  isChatUserInfoValid: () => isChatUserInfoValid,
  isDeadlinePassed: () => isDeadlinePassed,
  isFormValid: () => isFormValid,
  isStepValid: () => isStepValid,
  mapActivityStatusToDisplay: () => mapActivityStatusToDisplay,
  mapApiStatusToInternal: () => mapApiStatusToInternal,
  mapInternalStatusToApi: () => mapInternalStatusToApi,
  mapQuestionTypeToEnum: () => mapQuestionTypeToEnum,
  mapQuestionTypeToEnumRequired: () => mapQuestionTypeToEnumRequired,
  mapSubjectEnumToName: () => mapSubjectEnumToName,
  mapSubjectNameToEnum: () => mapSubjectNameToEnum,
  questionTypeLabels: () => questionTypeLabels,
  supportSchema: () => supportSchema,
  syncDropdownState: () => syncDropdownState,
  toggleArrayItem: () => toggleArrayItem,
  toggleSingleValue: () => toggleSingleValue,
  transformActivityToTableItem: () => transformActivityToTableItem,
  transformGoalToTableItem: () => transformGoalToTableItem,
  transformModelToTableItem: () => transformModelToTableItem,
  useAlertFormStore: () => useAlertFormStore,
  useApiConfig: () => useApiConfig,
  useAppContent: () => useAppContent,
  useAppInitialization: () => useAppInitialization,
  useAppStore: () => useAppStore,
  useAuth: () => useAuth,
  useAuthGuard: () => useAuthGuard,
  useAuthStore: () => useAuthStore,
  useBreadcrumb: () => useBreadcrumb,
  useBreadcrumbBuilder: () => useBreadcrumbBuilder,
  useChat: () => useChat,
  useChatRooms: () => useChatRooms,
  useInstitutionId: () => useInstitutionId,
  useMobile: () => useMobile,
  useQuestionFiltersStore: () => useQuestionFiltersStore,
  useQuestionsPdfPrint: () => useQuestionsPdfPrint,
  useQuizStore: () => useQuizStore,
  useRouteAuth: () => useRouteAuth,
  useSendActivityModal: () => useSendActivityModal,
  useTableFilter: () => useTableFilter,
  useTableSort: () => useTableSort,
  useTheme: () => useTheme,
  useThemeStore: () => useThemeStore,
  useToastStore: () => ToastStore_default,
  useUrlAuthentication: () => useUrlAuthentication,
  useUrlParams: () => useUrlParams,
  validateActivityStep: () => validateActivityStep,
  validateDeadlineStep: () => validateDeadlineStep,
  validateRecipientStep: () => validateRecipientStep,
  validateStep: () => validateStep,
  withAuth: () => withAuth
});
module.exports = __toCommonJS(src_exports);

// src/utils/utils.ts
var import_clsx = require("clsx");
var import_tailwind_merge = require("tailwind-merge");

// src/utils/dropdown.ts
var syncDropdownState = (open, isActive, setActiveStates, key) => {
  if (!open && isActive) {
    setActiveStates((prev) => ({ ...prev, [key]: false }));
  }
};

// src/utils/activityFilters.ts
function getSelectedIdsFromCategories(categories, keys) {
  const result = {};
  for (const [outputKey, categoryKey] of Object.entries(keys)) {
    const category = categories.find((c) => c.key === categoryKey);
    result[outputKey] = category?.selectedIds || [];
  }
  return result;
}
function toggleArrayItem(array, item) {
  return array.includes(item) ? array.filter((i) => i !== item) : [...array, item];
}
function toggleSingleValue(currentValue, newValue) {
  return currentValue === newValue ? null : newValue;
}
function arraysEqual(a, b, comparator) {
  if (a.length !== b.length) return false;
  if (comparator) {
    const sortedA2 = [...a].sort(comparator);
    const sortedB2 = [...b].sort(comparator);
    return sortedA2.every((val, index) => val === sortedB2[index]);
  }
  const sortedA = [...a].sort((x, y) => String(x).localeCompare(String(y)));
  const sortedB = [...b].sort((x, y) => String(x).localeCompare(String(y)));
  return sortedA.every((val, index) => val === sortedB[index]);
}
function areFiltersEqual(filters1, filters2) {
  if (filters1 === filters2) return true;
  if (!filters1 || !filters2) return false;
  return arraysEqual(filters1.types, filters2.types) && arraysEqual(filters1.bankIds, filters2.bankIds) && arraysEqual(filters1.yearIds, filters2.yearIds) && arraysEqual(filters1.knowledgeIds, filters2.knowledgeIds) && arraysEqual(filters1.topicIds, filters2.topicIds) && arraysEqual(filters1.subtopicIds, filters2.subtopicIds) && arraysEqual(filters1.contentIds, filters2.contentIds);
}

// src/components/Quiz/useQuizStore.ts
var import_zustand = require("zustand");
var import_middleware = require("zustand/middleware");
var QUESTION_DIFFICULTY = /* @__PURE__ */ ((QUESTION_DIFFICULTY2) => {
  QUESTION_DIFFICULTY2["FACIL"] = "FACIL";
  QUESTION_DIFFICULTY2["MEDIO"] = "MEDIO";
  QUESTION_DIFFICULTY2["DIFICIL"] = "DIFICIL";
  return QUESTION_DIFFICULTY2;
})(QUESTION_DIFFICULTY || {});
var QUIZ_TYPE = /* @__PURE__ */ ((QUIZ_TYPE2) => {
  QUIZ_TYPE2["SIMULADO"] = "SIMULADO";
  QUIZ_TYPE2["QUESTIONARIO"] = "QUESTIONARIO";
  QUIZ_TYPE2["ATIVIDADE"] = "ATIVIDADE";
  return QUIZ_TYPE2;
})(QUIZ_TYPE || {});
var QUESTION_TYPE = /* @__PURE__ */ ((QUESTION_TYPE2) => {
  QUESTION_TYPE2["ALTERNATIVA"] = "ALTERNATIVA";
  QUESTION_TYPE2["DISSERTATIVA"] = "DISSERTATIVA";
  QUESTION_TYPE2["MULTIPLA_ESCOLHA"] = "MULTIPLA_ESCOLHA";
  QUESTION_TYPE2["VERDADEIRO_FALSO"] = "VERDADEIRO_FALSO";
  QUESTION_TYPE2["LIGAR_PONTOS"] = "LIGAR_PONTOS";
  QUESTION_TYPE2["PREENCHER"] = "PREENCHER";
  QUESTION_TYPE2["IMAGEM"] = "IMAGEM";
  return QUESTION_TYPE2;
})(QUESTION_TYPE || {});
var QUESTION_STATUS = /* @__PURE__ */ ((QUESTION_STATUS3) => {
  QUESTION_STATUS3["PENDENTE_AVALIACAO"] = "PENDENTE_AVALIACAO";
  QUESTION_STATUS3["RESPOSTA_CORRETA"] = "RESPOSTA_CORRETA";
  QUESTION_STATUS3["RESPOSTA_INCORRETA"] = "RESPOSTA_INCORRETA";
  QUESTION_STATUS3["NAO_RESPONDIDO"] = "NAO_RESPONDIDO";
  return QUESTION_STATUS3;
})(QUESTION_STATUS || {});
var ANSWER_STATUS = /* @__PURE__ */ ((ANSWER_STATUS2) => {
  ANSWER_STATUS2["RESPOSTA_CORRETA"] = "RESPOSTA_CORRETA";
  ANSWER_STATUS2["RESPOSTA_INCORRETA"] = "RESPOSTA_INCORRETA";
  ANSWER_STATUS2["PENDENTE_AVALIACAO"] = "PENDENTE_AVALIACAO";
  ANSWER_STATUS2["NAO_RESPONDIDO"] = "NAO_RESPONDIDO";
  return ANSWER_STATUS2;
})(ANSWER_STATUS || {});
var SUBTYPE_ENUM = /* @__PURE__ */ ((SUBTYPE_ENUM2) => {
  SUBTYPE_ENUM2["PROVA"] = "PROVA";
  SUBTYPE_ENUM2["ENEM_PROVA_1"] = "ENEM_PROVA_1";
  SUBTYPE_ENUM2["ENEM_PROVA_2"] = "ENEM_PROVA_2";
  SUBTYPE_ENUM2["VESTIBULAR"] = "VESTIBULAR";
  SUBTYPE_ENUM2["SIMULADO"] = "SIMULADO";
  SUBTYPE_ENUM2["SIMULADAO"] = "SIMULADAO";
  return SUBTYPE_ENUM2;
})(SUBTYPE_ENUM || {});
var MINUTE_INTERVAL_MS = 6e4;
var useQuizStore = (0, import_zustand.create)()(
  (0, import_middleware.devtools)(
    (set, get) => {
      let timerInterval = null;
      let minuteCallbackInterval = null;
      const startTimer = () => {
        if (get().isFinished) {
          return;
        }
        if (timerInterval) {
          clearInterval(timerInterval);
        }
        timerInterval = setInterval(() => {
          const { timeElapsed } = get();
          set({ timeElapsed: timeElapsed + 1 });
        }, 1e3);
      };
      const stopTimer = () => {
        if (timerInterval) {
          clearInterval(timerInterval);
          timerInterval = null;
        }
      };
      const setMinuteCallback = (callback) => {
        set({ minuteCallback: callback });
      };
      const startMinuteCallback = () => {
        const { minuteCallback, isFinished } = get();
        if (isFinished || !minuteCallback) {
          return;
        }
        if (minuteCallbackInterval) {
          clearInterval(minuteCallbackInterval);
        }
        minuteCallbackInterval = setInterval(() => {
          const {
            minuteCallback: currentCallback,
            isFinished: currentIsFinished
          } = get();
          if (currentIsFinished || !currentCallback) {
            stopMinuteCallback();
            return;
          }
          currentCallback();
        }, MINUTE_INTERVAL_MS);
      };
      const stopMinuteCallback = () => {
        if (minuteCallbackInterval) {
          clearInterval(minuteCallbackInterval);
          minuteCallbackInterval = null;
        }
      };
      return {
        // Initial State
        quiz: null,
        currentQuestionIndex: 0,
        selectedAnswers: {},
        userAnswers: [],
        timeElapsed: 0,
        isStarted: false,
        isFinished: false,
        userId: "",
        variant: "default",
        minuteCallback: null,
        dissertativeCharLimit: void 0,
        questionsResult: null,
        currentQuestionResult: null,
        // Setters
        setQuiz: (quiz) => set({ quiz }),
        setUserId: (userId) => set({ userId }),
        setUserAnswers: (userAnswers) => set({ userAnswers }),
        getUserId: () => get().userId,
        setVariant: (variant) => set({ variant }),
        setQuestionResult: (questionsResult) => set({ questionsResult }),
        setDissertativeCharLimit: (limit) => set({ dissertativeCharLimit: limit }),
        getDissertativeCharLimit: () => get().dissertativeCharLimit,
        // Navigation
        goToNextQuestion: () => {
          const { currentQuestionIndex, getTotalQuestions } = get();
          const totalQuestions = getTotalQuestions();
          if (currentQuestionIndex < totalQuestions - 1) {
            set({ currentQuestionIndex: currentQuestionIndex + 1 });
          }
        },
        goToPreviousQuestion: () => {
          const { currentQuestionIndex } = get();
          if (currentQuestionIndex > 0) {
            set({ currentQuestionIndex: currentQuestionIndex - 1 });
          }
        },
        goToQuestion: (index) => {
          const { getTotalQuestions } = get();
          const totalQuestions = getTotalQuestions();
          if (index >= 0 && index < totalQuestions) {
            set({ currentQuestionIndex: index });
          }
        },
        selectAnswer: (questionId, answerId) => {
          const { quiz, userAnswers } = get();
          if (!quiz) return;
          const activityId = quiz.id;
          const userId = get().getUserId();
          if (!userId || userId === "") {
            return;
          }
          const question = quiz.questions.find((q) => q.id === questionId);
          if (!question) return;
          const existingAnswerIndex = userAnswers.findIndex(
            (answer) => answer.questionId === questionId
          );
          const newUserAnswer = {
            questionId,
            activityId,
            userId,
            answer: question.questionType === "DISSERTATIVA" /* DISSERTATIVA */ ? answerId : null,
            optionId: question.questionType === "DISSERTATIVA" /* DISSERTATIVA */ ? null : answerId,
            questionType: question.questionType,
            answerStatus: "PENDENTE_AVALIACAO" /* PENDENTE_AVALIACAO */
          };
          let updatedUserAnswers;
          if (existingAnswerIndex !== -1) {
            updatedUserAnswers = [...userAnswers];
            updatedUserAnswers[existingAnswerIndex] = newUserAnswer;
          } else {
            updatedUserAnswers = [...userAnswers, newUserAnswer];
          }
          set({
            userAnswers: updatedUserAnswers
          });
        },
        selectMultipleAnswer: (questionId, answerIds) => {
          const { quiz, userAnswers } = get();
          if (!quiz) return;
          const activityId = quiz.id;
          const userId = get().getUserId();
          if (!userId || userId === "") {
            return;
          }
          const question = quiz.questions.find((q) => q.id === questionId);
          if (!question) return;
          const filteredUserAnswers = userAnswers.filter(
            (answer) => answer.questionId !== questionId
          );
          const newUserAnswers = answerIds.map(
            (answerId) => ({
              questionId,
              activityId,
              userId,
              answer: null,
              // selectMultipleAnswer is for non-dissertative questions
              optionId: answerId,
              // selectMultipleAnswer should only set optionId
              questionType: question.questionType,
              answerStatus: "PENDENTE_AVALIACAO" /* PENDENTE_AVALIACAO */
            })
          );
          const updatedUserAnswers = [
            ...filteredUserAnswers,
            ...newUserAnswers
          ];
          set({
            userAnswers: updatedUserAnswers
          });
        },
        selectDissertativeAnswer: (questionId, answer) => {
          const { quiz, userAnswers, dissertativeCharLimit } = get();
          if (!quiz) return;
          const activityId = quiz.id;
          const userId = get().getUserId();
          if (!userId || userId === "") {
            return;
          }
          const question = quiz.questions.find((q) => q.id === questionId);
          if (!question || question.questionType !== "DISSERTATIVA" /* DISSERTATIVA */) {
            return;
          }
          let validatedAnswer = answer;
          if (dissertativeCharLimit !== void 0 && answer.length > dissertativeCharLimit) {
            validatedAnswer = answer.substring(0, dissertativeCharLimit);
          }
          const existingAnswerIndex = userAnswers.findIndex(
            (answerItem) => answerItem.questionId === questionId
          );
          const newUserAnswer = {
            questionId,
            activityId,
            userId,
            answer: validatedAnswer,
            optionId: null,
            questionType: "DISSERTATIVA" /* DISSERTATIVA */,
            answerStatus: "PENDENTE_AVALIACAO" /* PENDENTE_AVALIACAO */
          };
          let updatedUserAnswers;
          if (existingAnswerIndex !== -1) {
            updatedUserAnswers = [...userAnswers];
            updatedUserAnswers[existingAnswerIndex] = newUserAnswer;
          } else {
            updatedUserAnswers = [...userAnswers, newUserAnswer];
          }
          set({
            userAnswers: updatedUserAnswers
          });
        },
        skipQuestion: () => {
          const { getCurrentQuestion, userAnswers, quiz } = get();
          const currentQuestion = getCurrentQuestion();
          if (!quiz) return;
          if (currentQuestion) {
            const activityId = quiz.id;
            const userId = get().getUserId();
            if (!userId || userId === "") {
              return;
            }
            const existingAnswerIndex = userAnswers.findIndex(
              (answer) => answer.questionId === currentQuestion.id
            );
            const newUserAnswer = {
              questionId: currentQuestion.id,
              activityId,
              userId,
              answer: null,
              optionId: null,
              questionType: currentQuestion.questionType,
              answerStatus: "PENDENTE_AVALIACAO" /* PENDENTE_AVALIACAO */
            };
            let updatedUserAnswers;
            if (existingAnswerIndex !== -1) {
              updatedUserAnswers = [...userAnswers];
              updatedUserAnswers[existingAnswerIndex] = newUserAnswer;
            } else {
              updatedUserAnswers = [...userAnswers, newUserAnswer];
            }
            set({
              userAnswers: updatedUserAnswers
            });
          }
        },
        skipCurrentQuestionIfUnanswered: () => {
          const { getCurrentQuestion, getCurrentAnswer, skipQuestion } = get();
          const currentQuestion = getCurrentQuestion();
          const currentAnswer = getCurrentAnswer();
          if (!currentQuestion) return;
          if (!currentAnswer || currentAnswer.optionId === null && currentAnswer.answer === null) {
            skipQuestion();
          }
        },
        addUserAnswer: (questionId, answerId) => {
          const { quiz, userAnswers } = get();
          if (!quiz) return;
          const activityId = quiz.id;
          const userId = get().getUserId();
          if (!userId || userId === "") {
            return;
          }
          const question = quiz.questions.find((q) => q.id === questionId);
          if (!question) return;
          const existingAnswerIndex = userAnswers.findIndex(
            (answer) => answer.questionId === questionId
          );
          const newUserAnswer = {
            questionId,
            activityId,
            userId,
            answer: question.questionType === "DISSERTATIVA" /* DISSERTATIVA */ ? answerId || null : null,
            optionId: question.questionType !== "DISSERTATIVA" /* DISSERTATIVA */ ? answerId || null : null,
            questionType: question.questionType,
            answerStatus: "PENDENTE_AVALIACAO" /* PENDENTE_AVALIACAO */
          };
          if (existingAnswerIndex !== -1) {
            const updatedUserAnswers = [...userAnswers];
            updatedUserAnswers[existingAnswerIndex] = newUserAnswer;
            set({ userAnswers: updatedUserAnswers });
          } else {
            set({ userAnswers: [...userAnswers, newUserAnswer] });
          }
        },
        startQuiz: () => {
          set({ isStarted: true, timeElapsed: 0 });
          startTimer();
          startMinuteCallback();
        },
        finishQuiz: () => {
          set({ isFinished: true });
          stopTimer();
          stopMinuteCallback();
        },
        resetQuiz: () => {
          stopTimer();
          stopMinuteCallback();
          set({
            quiz: null,
            currentQuestionIndex: 0,
            selectedAnswers: {},
            userAnswers: [],
            timeElapsed: 0,
            isStarted: false,
            isFinished: false,
            userId: "",
            variant: "default",
            minuteCallback: null,
            dissertativeCharLimit: void 0,
            questionsResult: null,
            currentQuestionResult: null
          });
        },
        // Timer
        updateTime: (time) => set({ timeElapsed: time }),
        startTimer,
        stopTimer,
        // Minute Callback
        setMinuteCallback,
        startMinuteCallback,
        stopMinuteCallback,
        // Getters
        getCurrentQuestion: () => {
          const { currentQuestionIndex, quiz } = get();
          if (!quiz) {
            return null;
          }
          return quiz.questions[currentQuestionIndex];
        },
        getTotalQuestions: () => {
          const { quiz } = get();
          return quiz?.questions?.length || 0;
        },
        getAnsweredQuestions: () => {
          const { userAnswers } = get();
          return userAnswers.filter(
            (answer) => answer.optionId !== null || answer.answer !== null
          ).length;
        },
        getUnansweredQuestions: () => {
          const { quiz, userAnswers } = get();
          if (!quiz) return [];
          const unansweredQuestions = [];
          quiz.questions.forEach((question, index) => {
            const userAnswer = userAnswers.find(
              (answer) => answer.questionId === question.id
            );
            const isAnswered = userAnswer && (userAnswer.optionId !== null || userAnswer.answer !== null);
            const isSkipped = userAnswer && userAnswer.optionId === null && userAnswer.answer === null;
            if (!isAnswered && !isSkipped) {
              unansweredQuestions.push(index + 1);
            }
          });
          return unansweredQuestions;
        },
        getSkippedQuestions: () => {
          const { userAnswers } = get();
          return userAnswers.filter(
            (answer) => answer.optionId === null && answer.answer === null
          ).length;
        },
        getProgress: () => {
          const { getTotalQuestions, getAnsweredQuestions } = get();
          const total = getTotalQuestions();
          const answered = getAnsweredQuestions();
          return total > 0 ? answered / total * 100 : 0;
        },
        isQuestionAnswered: (questionId) => {
          const { userAnswers } = get();
          const userAnswer = userAnswers.find(
            (answer) => answer.questionId === questionId
          );
          return userAnswer ? userAnswer.optionId !== null || userAnswer.answer !== null : false;
        },
        isQuestionSkipped: (questionId) => {
          const { userAnswers } = get();
          const userAnswer = userAnswers.find(
            (answer) => answer.questionId === questionId
          );
          return userAnswer ? userAnswer.optionId === null && userAnswer.answer === null : false;
        },
        getCurrentAnswer: () => {
          const { getCurrentQuestion, userAnswers } = get();
          const currentQuestion = getCurrentQuestion();
          if (!currentQuestion) return void 0;
          const userAnswer = userAnswers.find(
            (answer) => answer.questionId === currentQuestion.id
          );
          const hasAnswerContent = (ua) => !!ua && (ua.optionId !== null && ua.optionId !== "" || ua.answer !== null && ua.answer !== "");
          if (!hasAnswerContent(userAnswer)) {
            return void 0;
          }
          return userAnswer;
        },
        getAllCurrentAnswer: () => {
          const { getCurrentQuestion, userAnswers } = get();
          const currentQuestion = getCurrentQuestion();
          if (!currentQuestion) return void 0;
          const userAnswer = userAnswers.filter(
            (answer) => answer.questionId === currentQuestion.id
          );
          return userAnswer;
        },
        getQuizTitle: () => {
          const { quiz } = get();
          return quiz?.title || "Quiz";
        },
        formatTime: (seconds) => {
          const minutes = Math.floor(seconds / 60);
          const remainingSeconds = seconds % 60;
          return `${minutes.toString().padStart(2, "0")}:${remainingSeconds.toString().padStart(2, "0")}`;
        },
        getUserAnswers: () => {
          const { userAnswers } = get();
          return userAnswers;
        },
        getUnansweredQuestionsFromUserAnswers: () => {
          const { quiz, userAnswers } = get();
          if (!quiz) return [];
          const unansweredQuestions = [];
          quiz.questions.forEach((question, index) => {
            const userAnswer = userAnswers.find(
              (answer) => answer.questionId === question.id
            );
            const hasAnswer = userAnswer && (userAnswer.optionId !== null || userAnswer.answer !== null);
            const isSkipped = userAnswer && userAnswer.optionId === null && userAnswer.answer === null;
            if (!hasAnswer || isSkipped) {
              unansweredQuestions.push(index + 1);
            }
          });
          return unansweredQuestions;
        },
        getQuestionsGroupedBySubject: () => {
          const { getQuestionResult, quiz, variant } = get();
          const questions = variant == "result" ? getQuestionResult()?.answers : quiz?.questions;
          if (!questions) return {};
          const groupedQuestions = {};
          questions.forEach((question) => {
            const subjectId = question.knowledgeMatrix?.[0]?.subject?.id || "Sem mat\xE9ria";
            if (!groupedQuestions[subjectId]) {
              groupedQuestions[subjectId] = [];
            }
            groupedQuestions[subjectId].push(question);
          });
          return groupedQuestions;
        },
        // New methods for userAnswers
        getUserAnswerByQuestionId: (questionId) => {
          const { userAnswers } = get();
          return userAnswers.find((answer) => answer.questionId === questionId) || null;
        },
        isQuestionAnsweredByUserAnswers: (questionId) => {
          const { userAnswers } = get();
          const answer = userAnswers.find(
            (answer2) => answer2.questionId === questionId
          );
          return answer ? answer.optionId !== null || answer.answer !== null : false;
        },
        getQuestionStatusFromUserAnswers: (questionId) => {
          const { userAnswers } = get();
          const answer = userAnswers.find(
            (answer2) => answer2.questionId === questionId
          );
          if (!answer) return "unanswered";
          if (answer.optionId === null) return "skipped";
          return "answered";
        },
        getUserAnswersForActivity: () => {
          const { userAnswers } = get();
          return userAnswers;
        },
        setCurrentQuestion: (question) => {
          const { quiz, variant, questionsResult } = get();
          if (!quiz) return;
          let questionIndex = 0;
          if (variant == "result") {
            if (!questionsResult) return;
            const questionResult = questionsResult.answers.find((q) => q.id === question.id) ?? questionsResult.answers.find((q) => q.questionId === question.id);
            if (!questionResult) return;
            questionIndex = quiz.questions.findIndex(
              (q) => q.id === questionResult.questionId
            );
          } else {
            questionIndex = quiz.questions.findIndex(
              (q) => q.id === question.id
            );
          }
          if (questionIndex === -1) {
            return;
          }
          set({ currentQuestionIndex: questionIndex });
        },
        setAnswerStatus: (questionId, status) => {
          const { userAnswers } = get();
          const existingAnswerIndex = userAnswers.findIndex(
            (answer) => answer.questionId === questionId
          );
          if (existingAnswerIndex !== -1) {
            const updatedUserAnswers = [...userAnswers];
            updatedUserAnswers[existingAnswerIndex] = {
              ...updatedUserAnswers[existingAnswerIndex],
              answerStatus: status
            };
            set({ userAnswers: updatedUserAnswers });
          }
        },
        getAnswerStatus: (questionId) => {
          const { userAnswers } = get();
          const userAnswer = userAnswers.find(
            (answer) => answer.questionId === questionId
          );
          return userAnswer ? userAnswer.answerStatus : null;
        },
        getQuestionIndex: (questionId) => {
          const { questionsResult, variant, quiz } = get();
          if (variant == "result") {
            if (!questionsResult) return 0;
            let idx = questionsResult.answers.findIndex(
              (q) => q.questionId === questionId
            );
            if (idx === -1) {
              idx = questionsResult.answers.findIndex(
                (q) => q.id === questionId
              );
            }
            return idx !== -1 ? idx + 1 : 0;
          } else {
            if (!quiz) return 0;
            const idx = quiz.questions.findIndex((q) => q.id === questionId);
            return idx !== -1 ? idx + 1 : 0;
          }
        },
        // Question Result
        getQuestionResultByQuestionId: (questionId) => {
          const { questionsResult } = get();
          const question = questionsResult?.answers.find(
            (answer) => answer.questionId === questionId
          );
          return question || null;
        },
        getQuestionResultStatistics: () => {
          const { questionsResult } = get();
          return questionsResult?.statistics || null;
        },
        getQuestionResult: () => {
          const { questionsResult } = get();
          return questionsResult;
        },
        setQuestionsResult: (questionsResult) => {
          set({ questionsResult });
        },
        setCurrentQuestionResult: (currentQuestionResult) => {
          set({ currentQuestionResult });
        },
        getCurrentQuestionResult: () => {
          const { currentQuestionResult } = get();
          return currentQuestionResult;
        }
      };
    },
    {
      name: "quiz-store"
    }
  )
);

// src/utils/questionTypeUtils.ts
function mapQuestionTypeToEnum(type, fallback) {
  const upperType = type.toUpperCase();
  const typeMap = {
    ALTERNATIVA: "ALTERNATIVA" /* ALTERNATIVA */,
    DISSERTATIVA: "DISSERTATIVA" /* DISSERTATIVA */,
    MULTIPLA_ESCOLHA: "MULTIPLA_ESCOLHA" /* MULTIPLA_ESCOLHA */,
    VERDADEIRO_FALSO: "VERDADEIRO_FALSO" /* VERDADEIRO_FALSO */,
    IMAGEM: "IMAGEM" /* IMAGEM */,
    LIGAR_PONTOS: "LIGAR_PONTOS" /* LIGAR_PONTOS */,
    PREENCHER: "PREENCHER" /* PREENCHER */
  };
  return typeMap[upperType] ?? fallback ?? null;
}
function mapQuestionTypeToEnumRequired(type, fallback = "ALTERNATIVA" /* ALTERNATIVA */) {
  return mapQuestionTypeToEnum(type, fallback) ?? fallback;
}

// src/types/activityDetails.ts
var STUDENT_ACTIVITY_STATUS = {
  CONCLUIDO: "CONCLUIDO",
  AGUARDANDO_CORRECAO: "AGUARDANDO_CORRECAO",
  AGUARDANDO_RESPOSTA: "AGUARDANDO_RESPOSTA",
  NAO_ENTREGUE: "NAO_ENTREGUE"
};
var ACTIVITY_AVAILABILITY = {
  DISPONIVEL: "DISPONIVEL",
  NAO_INICIADA: "NAO_INICIADA",
  EXPIRADA: "EXPIRADA"
};

// src/utils/activityDetailsUtils.ts
var getStatusBadgeConfig = (status) => {
  const configs = {
    [STUDENT_ACTIVITY_STATUS.CONCLUIDO]: {
      label: "Conclu\xEDdo",
      bgColor: "bg-green-50",
      textColor: "text-green-800"
    },
    [STUDENT_ACTIVITY_STATUS.AGUARDANDO_CORRECAO]: {
      label: "Aguardando Corre\xE7\xE3o",
      bgColor: "bg-yellow-50",
      textColor: "text-yellow-800"
    },
    [STUDENT_ACTIVITY_STATUS.AGUARDANDO_RESPOSTA]: {
      label: "Aguardando Resposta",
      bgColor: "bg-blue-50",
      textColor: "text-blue-800"
    },
    [STUDENT_ACTIVITY_STATUS.NAO_ENTREGUE]: {
      label: "N\xE3o Entregue",
      bgColor: "bg-red-50",
      textColor: "text-red-800"
    },
    default: {
      label: "Desconhecido",
      bgColor: "bg-gray-50",
      textColor: "text-gray-800"
    }
  };
  return configs[status] ?? configs.default;
};
var formatTimeSpent = (seconds) => {
  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor(seconds % 3600 / 60);
  const secs = seconds % 60;
  return `${String(hours).padStart(2, "0")}:${String(minutes).padStart(2, "0")}:${String(secs).padStart(2, "0")}`;
};
var formatQuestionNumbers = (numbers) => {
  if (numbers.length === 0) return "-";
  return numbers.map((n) => String(n + 1).padStart(2, "0")).join(", ");
};
var formatDateToBrazilian = (dateString) => {
  const date = new Date(dateString);
  const day = String(date.getUTCDate()).padStart(2, "0");
  const month = String(date.getUTCMonth() + 1).padStart(2, "0");
  const year = date.getUTCFullYear();
  return `${day}/${month}/${year}`;
};

// src/utils/utils.ts
function cn(...inputs) {
  return (0, import_tailwind_merge.twMerge)((0, import_clsx.clsx)(inputs));
}
function getSubjectColorWithOpacity(hexColor, isDark) {
  if (!hexColor) return void 0;
  let color = hexColor.replace(/^#/, "").toLowerCase();
  if (isDark) {
    if (color.length === 8) {
      color = color.slice(0, 6);
    }
    return `#${color}`;
  } else {
    let resultColor;
    if (color.length === 6) {
      resultColor = `#${color}4d`;
    } else if (color.length === 8) {
      resultColor = `#${color}`;
    } else {
      resultColor = `#${color}`;
    }
    return resultColor;
  }
}

// src/components/Text/Text.tsx
var import_jsx_runtime = require("react/jsx-runtime");
var Text = ({
  children,
  size = "md",
  weight = "normal",
  color = "text-text-950",
  as,
  className = "",
  ...props
}) => {
  let sizeClasses = "";
  let weightClasses = "";
  const sizeClassMap = {
    "2xs": "text-2xs",
    xs: "text-xs",
    sm: "text-sm",
    md: "text-md",
    lg: "text-lg",
    xl: "text-xl",
    "2xl": "text-2xl",
    "3xl": "text-3xl",
    "4xl": "text-4xl",
    "5xl": "text-5xl",
    "6xl": "text-6xl"
  };
  sizeClasses = sizeClassMap[size] ?? sizeClassMap.md;
  const weightClassMap = {
    hairline: "font-hairline",
    light: "font-light",
    normal: "font-normal",
    medium: "font-medium",
    semibold: "font-semibold",
    bold: "font-bold",
    extrabold: "font-extrabold",
    black: "font-black"
  };
  weightClasses = weightClassMap[weight] ?? weightClassMap.normal;
  const baseClasses = "font-primary";
  const Component = as ?? "p";
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
    Component,
    {
      className: cn(baseClasses, sizeClasses, weightClasses, color, className),
      ...props,
      children
    }
  );
};
var Text_default = Text;

// src/components/Button/Button.tsx
var import_jsx_runtime2 = require("react/jsx-runtime");
var VARIANT_ACTION_CLASSES = {
  solid: {
    primary: "bg-primary-950 text-text border border-primary-950 hover:bg-primary-800 hover:border-primary-800 focus-visible:outline-none focus-visible:bg-primary-950 focus-visible:ring-2 focus-visible:ring-offset-0 focus-visible:ring-indicator-info active:bg-primary-700 active:border-primary-700 disabled:bg-primary-500 disabled:border-primary-500 disabled:opacity-40 disabled:cursor-not-allowed",
    positive: "bg-success-500 text-text border border-success-500 hover:bg-success-600 hover:border-success-600 focus-visible:outline-none focus-visible:bg-success-500 focus-visible:ring-2 focus-visible:ring-offset-0 focus-visible:ring-indicator-info active:bg-success-700 active:border-success-700 disabled:bg-success-500 disabled:border-success-500 disabled:opacity-40 disabled:cursor-not-allowed",
    negative: "bg-error-500 text-text border border-error-500 hover:bg-error-600 hover:border-error-600 focus-visible:outline-none focus-visible:bg-error-500 focus-visible:ring-2 focus-visible:ring-offset-0 focus-visible:ring-indicator-info active:bg-error-700 active:border-error-700 disabled:bg-error-500 disabled:border-error-500 disabled:opacity-40 disabled:cursor-not-allowed"
  },
  outline: {
    primary: "bg-transparent text-primary-950 border border-primary-950 hover:bg-background-50 hover:text-primary-400 hover:border-primary-400 focus-visible:border-0 focus-visible:outline-none focus-visible:text-primary-600 focus-visible:ring-2 focus-visible:ring-offset-0 focus-visible:ring-indicator-info active:text-primary-700 active:border-primary-700 disabled:opacity-40 disabled:cursor-not-allowed",
    positive: "bg-transparent text-success-500 border border-success-300 hover:bg-background-50 hover:text-success-400 hover:border-success-400 focus-visible:border-0 focus-visible:outline-none focus-visible:text-success-600 focus-visible:ring-2 focus-visible:ring-offset-0 focus-visible:ring-indicator-info active:text-success-700 active:border-success-700 disabled:opacity-40 disabled:cursor-not-allowed",
    negative: "bg-transparent text-error-500 border border-error-300 hover:bg-background-50 hover:text-error-400 hover:border-error-400 focus-visible:border-0 focus-visible:outline-none focus-visible:text-error-600 focus-visible:ring-2 focus-visible:ring-offset-0 focus-visible:ring-indicator-info active:text-error-700 active:border-error-700 disabled:opacity-40 disabled:cursor-not-allowed"
  },
  link: {
    primary: "bg-transparent text-primary-950 hover:text-primary-400 focus-visible:outline-none focus-visible:text-primary-600 focus-visible:ring-2 focus-visible:ring-offset-0 focus-visible:ring-indicator-info active:text-primary-700 disabled:opacity-40 disabled:cursor-not-allowed",
    positive: "bg-transparent text-success-500 hover:text-success-400 focus-visible:outline-none focus-visible:text-success-600 focus-visible:ring-2 focus-visible:ring-offset-0 focus-visible:ring-indicator-info active:text-success-700 disabled:opacity-40 disabled:cursor-not-allowed",
    negative: "bg-transparent text-error-500 hover:text-error-400 focus-visible:outline-none focus-visible:text-error-600 focus-visible:ring-2 focus-visible:ring-offset-0 focus-visible:ring-indicator-info active:text-error-700 disabled:opacity-40 disabled:cursor-not-allowed"
  }
};
var SIZE_CLASSES = {
  "extra-small": "text-xs px-3.5 py-2",
  small: "text-sm px-4 py-2.5",
  medium: "text-md px-5 py-2.5",
  large: "text-lg px-6 py-3",
  "extra-large": "text-lg px-7 py-3.5"
};
var Button = ({
  children,
  iconLeft,
  iconRight,
  size = "medium",
  variant = "solid",
  action = "primary",
  className = "",
  disabled,
  type = "button",
  ...props
}) => {
  const sizeClasses = SIZE_CLASSES[size];
  const variantClasses = VARIANT_ACTION_CLASSES[variant][action];
  const baseClasses = "inline-flex items-center justify-center rounded-full cursor-pointer font-medium";
  return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
    "button",
    {
      className: cn(baseClasses, variantClasses, sizeClasses, className),
      disabled,
      type,
      ...props,
      children: [
        iconLeft && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: "mr-2 flex items-center", children: iconLeft }),
        children,
        iconRight && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: "ml-2 flex items-center", children: iconRight })
      ]
    }
  );
};
var Button_default = Button;

// src/components/Badge/Badge.tsx
var import_phosphor_react = require("phosphor-react");
var import_jsx_runtime3 = require("react/jsx-runtime");
var VARIANT_ACTION_CLASSES2 = {
  solid: {
    error: "bg-error-background text-error-700 focus-visible:outline-none",
    warning: "bg-warning text-warning-800 focus-visible:outline-none",
    success: "bg-success text-success-800 focus-visible:outline-none",
    info: "bg-info text-info-800 focus-visible:outline-none",
    muted: "bg-background-muted text-background-800 focus-visible:outline-none"
  },
  outlined: {
    error: "bg-error text-error-700 border border-error-300 focus-visible:outline-none",
    warning: "bg-warning text-warning-800 border border-warning-300 focus-visible:outline-none",
    success: "bg-success text-success-800 border border-success-300 focus-visible:outline-none",
    info: "bg-info text-info-800 border border-info-300 focus-visible:outline-none",
    muted: "bg-background-muted text-background-800 border border-border-300 focus-visible:outline-none"
  },
  exams: {
    exam1: "bg-exam-1 text-info-700 focus-visible:outline-none",
    exam2: "bg-exam-2 text-typography-1 focus-visible:outline-none",
    exam3: "bg-exam-3 text-typography-2 focus-visible:outline-none",
    exam4: "bg-exam-4 text-success-700 focus-visible:outline-none"
  },
  examsOutlined: {
    exam1: "bg-exam-1 text-info-700 border border-info-700 focus-visible:outline-none",
    exam2: "bg-exam-2 text-typography-1 border border-typography-1 focus-visible:outline-none",
    exam3: "bg-exam-3 text-typography-2 border border-typography-2 focus-visible:outline-none",
    exam4: "bg-exam-4 text-success-700 border border-success-700 focus-visible:outline-none"
  },
  resultStatus: {
    negative: "bg-error text-error-800 focus-visible:outline-none",
    positive: "bg-success text-success-800 focus-visible:outline-none"
  },
  notification: "text-primary"
};
var SIZE_CLASSES2 = {
  small: "text-2xs px-2 py-1",
  medium: "text-xs px-2 py-1",
  large: "text-sm px-2 py-1"
};
var SIZE_CLASSES_ICON = {
  small: "size-3",
  medium: "size-3.5",
  large: "size-4"
};
var Badge = ({
  children,
  iconLeft,
  iconRight,
  size = "medium",
  variant = "solid",
  action = "error",
  className = "",
  notificationActive = false,
  ...props
}) => {
  const sizeClasses = SIZE_CLASSES2[size];
  const sizeClassesIcon = SIZE_CLASSES_ICON[size];
  const variantActionMap = VARIANT_ACTION_CLASSES2[variant] || {};
  const variantClasses = typeof variantActionMap === "string" ? variantActionMap : variantActionMap[action] ?? variantActionMap.muted ?? "";
  const baseClasses = "inline-flex items-center justify-center rounded-xs font-normal gap-1 relative";
  const baseClassesIcon = "flex items-center";
  if (variant === "notification") {
    return /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(
      "div",
      {
        className: cn(baseClasses, variantClasses, sizeClasses, className),
        ...props,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(import_phosphor_react.Bell, { size: 24, className: "text-current", "aria-hidden": "true" }),
          notificationActive && /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
            "span",
            {
              "data-testid": "notification-dot",
              className: "absolute top-[5px] right-[10px] block h-2 w-2 rounded-full bg-indicator-error ring-2 ring-white"
            }
          )
        ]
      }
    );
  }
  return /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(
    "div",
    {
      className: cn(baseClasses, variantClasses, sizeClasses, className),
      ...props,
      children: [
        iconLeft && /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { className: cn(baseClassesIcon, sizeClassesIcon), children: iconLeft }),
        children,
        iconRight && /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { className: cn(baseClassesIcon, sizeClassesIcon), children: iconRight })
      ]
    }
  );
};
var Badge_default = Badge;

// src/components/Alert/Alert.tsx
var import_phosphor_react2 = require("phosphor-react");
var import_jsx_runtime4 = require("react/jsx-runtime");
var VARIANT_ACTION_CLASSES3 = {
  solid: {
    default: "bg-background-50 border-transparent",
    info: "bg-info border-transparent",
    success: "bg-success border-transparent",
    warning: "bg-warning border-transparent",
    error: "bg-error border-transparent"
  },
  outline: {
    default: "bg-background border border-border-100",
    info: "bg-background border border-border-100",
    success: "bg-background border border-border-100",
    warning: "bg-background border border-border-100",
    error: "bg-background border border-border-100"
  }
};
var COLOR_CLASSES = {
  default: "text-text-950",
  info: "text-info-800",
  success: "text-success-800",
  warning: "text-warning-800",
  error: "text-error-800"
};
var ICONS = {
  default: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(import_phosphor_react2.CheckCircle, { size: 18 }),
  info: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(import_phosphor_react2.Info, { size: 18 }),
  success: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(import_phosphor_react2.CheckCircle, { size: 18 }),
  warning: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(import_phosphor_react2.WarningCircle, { size: 18 }),
  error: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(import_phosphor_react2.XCircle, { size: 18 })
};
var Alert = ({
  variant = "solid",
  title,
  description,
  action = "default",
  className,
  ...props
}) => {
  const baseClasses = "alert-wrapper flex items-start gap-2 w-[384px] py-3 px-4 font-inherit rounded-md";
  const variantClasses = VARIANT_ACTION_CLASSES3[variant][action];
  const variantColor = COLOR_CLASSES[action];
  const variantIcon = ICONS[action];
  const hasHeading = Boolean(title);
  return /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("div", { className: cn(baseClasses, variantClasses, className), ...props, children: [
    /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("span", { className: cn("mt-0.5", variantColor), children: variantIcon }),
    /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("div", { children: [
      hasHeading && /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
        Text_default,
        {
          size: "md",
          weight: "medium",
          color: variantColor,
          className: "mb-0.5",
          children: title
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
        Text_default,
        {
          size: hasHeading ? "sm" : "md",
          weight: "normal",
          color: !hasHeading ? variantColor : "text-text-700",
          children: description
        }
      )
    ] })
  ] });
};
var Alert_default = Alert;

// src/components/LatexRenderer/LatexRenderer.tsx
var import_katex_min = require("katex/dist/katex.min.css");
var import_react_katex = require("react-katex");
var import_dompurify = __toESM(require("dompurify"));
var import_html_react_parser = __toESM(require("html-react-parser"));
var import_jsx_runtime5 = require("react/jsx-runtime");
var sanitizeHtml = (value) => {
  return import_dompurify.default.sanitize(value, {
    ADD_ATTR: ["data-latex", "data-display-mode", "data-math", "data-math-id"]
  });
};
var decodeHtmlEntities = (str) => {
  const textarea = document.createElement("textarea");
  textarea.innerHTML = str;
  return textarea.value;
};
var cleanLatex = (str) => {
  return str.replaceAll(/[\u200B-\u200D\uFEFF]/g, "").trim();
};
var createMathReplacer = (mathParts, errorRenderer) => {
  return (domNode) => {
    if (domNode instanceof import_html_react_parser.Element && domNode.name === "span" && domNode.attribs["data-math-id"]) {
      const mathId = Number.parseInt(domNode.attribs["data-math-id"], 10);
      const mathPart = mathParts[mathId];
      if (!mathPart) return domNode;
      if (mathPart.type === "inline") {
        return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
          import_react_katex.InlineMath,
          {
            math: mathPart.latex,
            renderError: () => errorRenderer(mathPart.latex)
          },
          `math-${mathId}`
        );
      } else {
        return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("div", { className: "my-2.5 text-center", children: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
          import_react_katex.BlockMath,
          {
            math: mathPart.latex,
            renderError: () => errorRenderer(mathPart.latex)
          }
        ) }, `math-${mathId}`);
      }
    }
    return domNode;
  };
};
var LatexRenderer = ({
  content,
  className,
  style,
  onError
}) => {
  const renderContentWithMath = (htmlContent) => {
    if (!htmlContent) return null;
    let processedContent = htmlContent;
    const mathParts = [];
    const mathFormulaPattern = /<span[^>]*class="math-formula"[^>]*data-latex="([^"]*)"[^>]*>[\s\S]*?<\/span>/g;
    processedContent = processedContent.replaceAll(
      mathFormulaPattern,
      (match, latex) => {
        const isDisplayMode = match.includes('data-display-mode="true"');
        const id = mathParts.length;
        mathParts.push({
          id,
          type: isDisplayMode ? "block" : "inline",
          latex: cleanLatex(decodeHtmlEntities(latex))
        });
        return `<span data-math-id="${id}"></span>`;
      }
    );
    const wrappedMathPattern = /<span[^>]*class="math-expression"[^>]*data-math="([^"]*)"[^>]*>.*?<\/span>/g;
    processedContent = processedContent.replaceAll(
      wrappedMathPattern,
      (match, latex) => {
        const id = mathParts.length;
        mathParts.push({
          id,
          type: "inline",
          latex: cleanLatex(decodeHtmlEntities(latex))
        });
        return `<span data-math-id="${id}"></span>`;
      }
    );
    const doubleDollarPattern = /(?<!\\)\$\$([\s\S]+?)\$\$/g;
    processedContent = processedContent.replaceAll(
      doubleDollarPattern,
      (match, latex) => {
        const id = mathParts.length;
        mathParts.push({
          id,
          type: "block",
          latex: cleanLatex(latex)
        });
        return `<span data-math-id="${id}"></span>`;
      }
    );
    const singleDollarPattern = /(?<!\\)\$([\s\S]+?)\$/g;
    processedContent = processedContent.replaceAll(
      singleDollarPattern,
      (match, latex) => {
        const id = mathParts.length;
        mathParts.push({
          id,
          type: "inline",
          latex: cleanLatex(latex)
        });
        return `<span data-math-id="${id}"></span>`;
      }
    );
    const latexTagPattern = /(?:<latex>|&lt;latex&gt;)([\s\S]*?)(?:<\/latex>|&lt;\/latex&gt;)/g;
    processedContent = processedContent.replaceAll(
      latexTagPattern,
      (match, latex) => {
        const id = mathParts.length;
        mathParts.push({
          id,
          type: "inline",
          latex: cleanLatex(latex)
        });
        return `<span data-math-id="${id}"></span>`;
      }
    );
    const latexEnvPattern = /\\begin\{([^}]+)\}([\s\S]*?)\\end\{\1\}/g;
    processedContent = processedContent.replaceAll(latexEnvPattern, (match) => {
      const id = mathParts.length;
      mathParts.push({
        id,
        type: "block",
        latex: cleanLatex(match)
      });
      return `<span data-math-id="${id}"></span>`;
    });
    const sanitizedContent = sanitizeHtml(processedContent);
    const defaultErrorRenderer = (latex) => /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("span", { className: "text-red-600", children: [
      "Math Error: ",
      latex
    ] });
    const errorRenderer = onError || defaultErrorRenderer;
    const options = {
      replace: createMathReplacer(mathParts, errorRenderer)
    };
    return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_jsx_runtime5.Fragment, { children: (0, import_html_react_parser.default)(sanitizedContent, options) });
  };
  return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
    "div",
    {
      className: cn("whitespace-pre-wrap leading-relaxed", className),
      style,
      children: renderContentWithMath(content)
    }
  );
};
var LatexRenderer_default = LatexRenderer;

// src/components/IconButton/IconButton.tsx
var import_react = require("react");
var import_jsx_runtime6 = require("react/jsx-runtime");
var IconButton = (0, import_react.forwardRef)(
  ({ icon, size = "md", active = false, className = "", disabled, ...props }, ref) => {
    const baseClasses = [
      "inline-flex",
      "items-center",
      "justify-center",
      "rounded-lg",
      "font-medium",
      "bg-transparent",
      "text-text-950",
      "cursor-pointer",
      "hover:bg-primary-600",
      "hover:text-text",
      "focus-visible:outline-none",
      "focus-visible:ring-2",
      "focus-visible:ring-offset-0",
      "focus-visible:ring-indicator-info",
      "disabled:opacity-50",
      "disabled:cursor-not-allowed",
      "disabled:pointer-events-none"
    ];
    const sizeClasses = {
      sm: ["w-6", "h-6", "text-sm"],
      md: ["w-10", "h-10", "text-base"]
    };
    const activeClasses = active ? ["!bg-primary-50", "!text-primary-950", "hover:!bg-primary-100"] : [];
    const allClasses = [
      ...baseClasses,
      ...sizeClasses[size],
      ...activeClasses
    ].join(" ");
    const ariaLabel = props["aria-label"] ?? "Bot\xE3o de a\xE7\xE3o";
    return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
      "button",
      {
        ref,
        type: "button",
        className: cn(allClasses, className),
        disabled,
        "aria-pressed": active,
        "aria-label": ariaLabel,
        ...props,
        children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("span", { className: "flex items-center justify-center", children: icon })
      }
    );
  }
);
IconButton.displayName = "IconButton";
var IconButton_default = IconButton;

// src/components/IconRoundedButton/IconRoundedButton.tsx
var import_jsx_runtime7 = require("react/jsx-runtime");
var IconRoundedButton = ({
  icon,
  className = "",
  disabled,
  ...props
}) => {
  const baseClasses = [
    "inline-flex",
    "items-center",
    "justify-center",
    "w-8",
    "h-8",
    "rounded-full",
    "cursor-pointer",
    "border",
    "border-background-200",
    "bg-background",
    "text-text-950",
    "hover:shadow-hard-shadow-1",
    "focus-visible:outline-none",
    "focus-visible:shadow-hard-shadow-1",
    "focus-visible:ring-2",
    "focus-visible:ring-indicator-info",
    "focus-visible:ring-offset-0",
    "disabled:opacity-50",
    "disabled:cursor-not-allowed"
  ].join(" ");
  return /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(
    "button",
    {
      type: "button",
      className: cn(baseClasses, className),
      disabled,
      ...props,
      children: /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("span", { className: "flex items-center justify-center w-5 h-5", children: icon })
    }
  );
};
var IconRoundedButton_default = IconRoundedButton;

// src/components/NavButton/NavButton.tsx
var import_react2 = require("react");
var import_jsx_runtime8 = require("react/jsx-runtime");
var NavButton = (0, import_react2.forwardRef)(
  ({ icon, label, selected = false, className = "", disabled, ...props }, ref) => {
    const baseClasses = [
      "flex",
      "flex-col",
      "items-center",
      "justify-center",
      "gap-0.5",
      "px-12",
      "py-1",
      "rounded-sm",
      "cursor-pointer",
      "text-text-950",
      "text-xs",
      "font-medium",
      "hover:text-text",
      "hover:bg-primary-600",
      "focus-visible:outline-none",
      "focus-visible:ring-2",
      "focus-visible:ring-offset-0",
      "focus-visible:ring-indicator-info",
      "disabled:opacity-50",
      "disabled:cursor-not-allowed",
      "disabled:pointer-events-none"
    ];
    const stateClasses = selected ? ["bg-primary-50", "text-primary-950"] : [];
    const allClasses = [...baseClasses, ...stateClasses].join(" ");
    return /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)(
      "button",
      {
        ref,
        type: "button",
        className: cn(allClasses, className),
        disabled,
        "aria-pressed": selected,
        ...props,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("span", { className: "flex items-center justify-center w-5 h-5", children: icon }),
          /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("span", { className: "whitespace-nowrap", children: label })
        ]
      }
    );
  }
);
NavButton.displayName = "NavButton";
var NavButton_default = NavButton;

// src/components/SelectionButton/SelectionButton.tsx
var import_react3 = require("react");
var import_jsx_runtime9 = require("react/jsx-runtime");
var SelectionButton = (0, import_react3.forwardRef)(
  ({ icon, label, selected = false, className = "", disabled, ...props }, ref) => {
    const baseClasses = [
      "inline-flex",
      "items-center",
      "justify-start",
      "gap-2",
      "p-4",
      "rounded-xl",
      "cursor-pointer",
      "border",
      "border-border-50",
      "bg-background",
      "text-sm",
      "text-text-700",
      "font-bold",
      "shadow-soft-shadow-1",
      "hover:bg-background-100",
      "focus-visible:outline-none",
      "focus-visible:ring-2",
      "focus-visible:ring-indicator-info",
      "focus-visible:ring-offset-0",
      "focus-visible:shadow-none",
      "active:ring-2",
      "active:ring-primary-950",
      "active:ring-offset-0",
      "active:shadow-none",
      "disabled:opacity-50",
      "disabled:cursor-not-allowed"
    ];
    const stateClasses = selected ? ["ring-primary-950", "ring-2", "ring-offset-0", "shadow-none"] : [];
    const allClasses = [...baseClasses, ...stateClasses].join(" ");
    return /* @__PURE__ */ (0, import_jsx_runtime9.jsxs)(
      "button",
      {
        ref,
        type: "button",
        className: cn(allClasses, className),
        disabled,
        "aria-pressed": selected,
        ...props,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime9.jsx)("span", { className: "flex items-center justify-center w-6 h-6", children: icon }),
          /* @__PURE__ */ (0, import_jsx_runtime9.jsx)("span", { children: label })
        ]
      }
    );
  }
);
SelectionButton.displayName = "SelectionButton";
var SelectionButton_default = SelectionButton;

// src/components/CheckBox/CheckBox.tsx
var import_react4 = require("react");
var import_phosphor_react3 = require("phosphor-react");
var import_jsx_runtime10 = require("react/jsx-runtime");
var SIZE_CLASSES3 = {
  small: {
    checkbox: "w-4 h-4",
    // 16px x 16px
    textSize: "sm",
    spacing: "gap-1.5",
    // 6px
    borderWidth: "border-2",
    iconSize: 14,
    // pixels for Phosphor icons
    labelHeight: "h-[21px]"
  },
  medium: {
    checkbox: "w-5 h-5",
    // 20px x 20px
    textSize: "md",
    spacing: "gap-2",
    // 8px
    borderWidth: "border-2",
    iconSize: 16,
    // pixels for Phosphor icons
    labelHeight: "h-6"
  },
  large: {
    checkbox: "w-6 h-6",
    // 24px x 24px
    textSize: "lg",
    spacing: "gap-2",
    // 8px
    borderWidth: "border-[3px]",
    // 3px border
    iconSize: 20,
    // pixels for Phosphor icons
    labelHeight: "h-[27px]"
  }
};
var BASE_CHECKBOX_CLASSES = "rounded border cursor-pointer transition-all duration-200 flex items-center justify-center focus:outline-none";
var STATE_CLASSES = {
  default: {
    unchecked: "border-border-400 bg-background hover:border-border-500",
    checked: "border-primary-950 bg-primary-950 text-text hover:border-primary-800 hover:bg-primary-800"
  },
  hovered: {
    unchecked: "border-border-500 bg-background",
    checked: "border-primary-800 bg-primary-800 text-text"
  },
  focused: {
    unchecked: "border-indicator-info bg-background ring-2 ring-indicator-info/20",
    checked: "border-indicator-info bg-primary-950 text-text ring-2 ring-indicator-info/20"
  },
  invalid: {
    unchecked: "border-error-700 bg-background hover:border-error-600",
    checked: "border-error-700 bg-primary-950 text-text"
  },
  disabled: {
    unchecked: "border-border-400 bg-background cursor-not-allowed opacity-40",
    checked: "border-primary-600 bg-primary-600 text-text cursor-not-allowed opacity-40"
  }
};
var CheckBox = (0, import_react4.forwardRef)(
  ({
    label,
    size = "medium",
    state = "default",
    indeterminate = false,
    errorMessage,
    helperText,
    className = "",
    labelClassName = "",
    checked: checkedProp,
    disabled,
    id,
    onChange,
    ...props
  }, ref) => {
    const generatedId = (0, import_react4.useId)();
    const inputId = id ?? `checkbox-${generatedId}`;
    const [internalChecked, setInternalChecked] = (0, import_react4.useState)(false);
    const isControlled = checkedProp !== void 0;
    const checked = isControlled ? checkedProp : internalChecked;
    const handleChange = (event) => {
      if (!isControlled) {
        setInternalChecked(event.target.checked);
      }
      onChange?.(event);
    };
    const currentState = disabled ? "disabled" : state;
    const sizeClasses = SIZE_CLASSES3[size];
    const checkVariant = checked || indeterminate ? "checked" : "unchecked";
    const stylingClasses = STATE_CLASSES[currentState][checkVariant];
    const borderWidthClass = state === "focused" || state === "hovered" && size === "large" ? "border-[3px]" : sizeClasses.borderWidth;
    const checkboxClasses = cn(
      BASE_CHECKBOX_CLASSES,
      sizeClasses.checkbox,
      borderWidthClass,
      stylingClasses,
      className
    );
    const renderIcon = () => {
      if (indeterminate) {
        return /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
          import_phosphor_react3.Minus,
          {
            size: sizeClasses.iconSize,
            weight: "bold",
            color: "currentColor"
          }
        );
      }
      if (checked) {
        return /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
          import_phosphor_react3.Check,
          {
            size: sizeClasses.iconSize,
            weight: "bold",
            color: "currentColor"
          }
        );
      }
      return null;
    };
    return /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)("div", { className: "flex flex-col", children: [
      /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)(
        "div",
        {
          className: cn(
            "flex flex-row items-center",
            sizeClasses.spacing,
            disabled ? "opacity-40" : ""
          ),
          children: [
            /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
              "input",
              {
                ref,
                type: "checkbox",
                id: inputId,
                checked,
                disabled,
                onChange: handleChange,
                className: "sr-only",
                ...props
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime10.jsx)("label", { htmlFor: inputId, className: checkboxClasses, children: renderIcon() }),
            label && /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
              "div",
              {
                className: cn(
                  "flex flex-row items-center",
                  sizeClasses.labelHeight
                ),
                children: /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
                  Text_default,
                  {
                    as: "label",
                    htmlFor: inputId,
                    size: sizeClasses.textSize,
                    weight: "normal",
                    className: cn(
                      "cursor-pointer select-none leading-[150%] flex items-center font-roboto",
                      labelClassName
                    ),
                    children: label
                  }
                )
              }
            )
          ]
        }
      ),
      errorMessage && /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
        Text_default,
        {
          size: "sm",
          weight: "normal",
          className: "mt-1.5",
          color: "text-error-600",
          children: errorMessage
        }
      ),
      helperText && !errorMessage && /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
        Text_default,
        {
          size: "sm",
          weight: "normal",
          className: "mt-1.5",
          color: "text-text-500",
          children: helperText
        }
      )
    ] });
  }
);
CheckBox.displayName = "CheckBox";
var CheckBox_default = CheckBox;

// src/components/ImageUpload/ImageUpload.tsx
var import_react5 = require("react");
var import_phosphor_react4 = require("phosphor-react");
var import_jsx_runtime11 = require("react/jsx-runtime");
function ImageUpload({
  selectedFile,
  onFileSelect,
  onRemoveFile,
  buttonText = "Inserir imagem",
  buttonIcon,
  accept = "image/*",
  disabled = false,
  className,
  maxSize,
  onSizeError,
  onTypeError,
  variant = "default"
}) {
  const fileInputRef = (0, import_react5.useRef)(null);
  const [internalFile, setInternalFile] = (0, import_react5.useState)(null);
  const currentFile = selectedFile ?? internalFile;
  const hasFile = currentFile !== null;
  const handleButtonClick = () => {
    if (!disabled) {
      fileInputRef.current?.click();
    }
  };
  const handleFileChange = (event) => {
    const file = event.target.files?.[0];
    if (!file) return;
    const acceptedTypes = accept.split(",").map((type) => type.trim());
    const isValidType = acceptedTypes.some((type) => {
      if (type.endsWith("/*")) {
        const mainType = type.split("/")[0];
        return file.type.startsWith(mainType + "/");
      }
      if (type.startsWith(".")) {
        return file.name.toLowerCase().endsWith(type.toLowerCase());
      }
      return file.type === type;
    });
    if (!isValidType) {
      onTypeError?.(file);
      return;
    }
    if (maxSize && file.size > maxSize) {
      onSizeError?.(file, maxSize);
      return;
    }
    if (selectedFile === void 0) {
      setInternalFile(file);
    }
    onFileSelect?.(file);
    event.target.value = "";
  };
  const handleRemoveFile = () => {
    if (!disabled) {
      if (selectedFile === void 0) {
        setInternalFile(null);
      }
      onRemoveFile?.();
    }
  };
  if (variant === "compact") {
    return /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)("div", { className: cn("inline-flex items-center gap-2", className), children: [
      hasFile ? /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)("div", { className: "inline-flex items-center gap-2 bg-muted rounded-md px-3 py-1.5", children: [
        /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_phosphor_react4.Paperclip, { className: "h-4 w-4 text-text-800" }),
        /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(Text_default, { size: "sm", weight: "medium", className: "text-text-800", children: currentFile.name }),
        /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
          "button",
          {
            type: "button",
            onClick: handleRemoveFile,
            disabled,
            className: "hover:opacity-70 disabled:cursor-not-allowed disabled:opacity-50",
            "aria-label": "Remover imagem",
            title: "Remover imagem",
            children: /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_phosphor_react4.X, { className: "h-3 w-3 text-primary-950" })
          }
        )
      ] }) : /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)(
        Button_default,
        {
          type: "button",
          variant: "link",
          size: "extra-small",
          onClick: handleButtonClick,
          disabled,
          children: [
            buttonIcon || /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_phosphor_react4.Image, { className: "h-4 w-4" }),
            /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("span", { className: "ml-2", children: buttonText })
          ]
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
        "input",
        {
          ref: fileInputRef,
          type: "file",
          accept,
          className: "hidden",
          onChange: handleFileChange,
          disabled
        }
      )
    ] });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)("div", { className: cn("space-y-3", className), children: [
    hasFile ? /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("div", { className: "space-y-2", children: /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)("div", { className: "inline-flex items-center gap-2 bg-muted rounded-md px-3 py-2", children: [
      /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_phosphor_react4.Paperclip, { className: "h-4 w-4 text-text-800" }),
      /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(Text_default, { size: "sm", weight: "medium", className: "text-text-800", children: currentFile.name }),
      /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
        "button",
        {
          type: "button",
          onClick: handleRemoveFile,
          disabled,
          className: "hover:opacity-70 disabled:cursor-not-allowed disabled:opacity-50",
          children: /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_phosphor_react4.X, { className: "h-4 w-4 text-primary-950 cursor-pointer" })
        }
      )
    ] }) }) : /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)(
      Button_default,
      {
        type: "button",
        variant: "link",
        onClick: handleButtonClick,
        disabled,
        children: [
          buttonIcon || /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_phosphor_react4.Image, { className: "h-4 w-4 mr-2" }),
          buttonText
        ]
      }
    ),
    /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
      "input",
      {
        ref: fileInputRef,
        type: "file",
        accept,
        className: "hidden",
        onChange: handleFileChange,
        disabled
      }
    )
  ] });
}

// src/components/CheckBox/CheckboxList.tsx
var import_react6 = require("react");
var import_zustand2 = require("zustand");
var import_jsx_runtime12 = require("react/jsx-runtime");
var createCheckboxListStore = (name, defaultValues, disabled, onValuesChange) => (0, import_zustand2.create)((set, get) => ({
  values: defaultValues,
  setValues: (values) => {
    if (!get().disabled) {
      set({ values });
      get().onValuesChange?.(values);
    }
  },
  toggleValue: (value) => {
    if (!get().disabled) {
      const currentValues = get().values;
      const newValues = currentValues.includes(value) ? currentValues.filter((v) => v !== value) : [...currentValues, value];
      set({ values: newValues });
      get().onValuesChange?.(newValues);
    }
  },
  onValuesChange,
  disabled,
  name
}));
var useCheckboxListStore = (externalStore) => {
  if (!externalStore) {
    throw new Error("CheckboxListItem must be used within a CheckboxList");
  }
  return externalStore;
};
var injectStore = (children, store) => import_react6.Children.map(children, (child) => {
  if (!(0, import_react6.isValidElement)(child)) return child;
  const typedChild = child;
  const shouldInject = typedChild.type === CheckboxListItem;
  return (0, import_react6.cloneElement)(typedChild, {
    ...shouldInject ? { store } : {},
    ...typedChild.props.children ? { children: injectStore(typedChild.props.children, store) } : {}
  });
});
var CheckboxList = (0, import_react6.forwardRef)(
  ({
    values: propValues,
    defaultValues = [],
    onValuesChange,
    name: propName,
    disabled = false,
    className = "",
    children,
    ...props
  }, ref) => {
    const generatedId = (0, import_react6.useId)();
    const name = propName || `checkbox-list-${generatedId}`;
    const storeRef = (0, import_react6.useRef)(null);
    storeRef.current ??= createCheckboxListStore(
      name,
      defaultValues,
      disabled,
      onValuesChange
    );
    const store = storeRef.current;
    const { setValues } = (0, import_zustand2.useStore)(store, (s) => s);
    (0, import_react6.useEffect)(() => {
      const currentValues = store.getState().values;
      if (currentValues.length > 0 && onValuesChange) {
        onValuesChange(currentValues);
      }
    }, []);
    (0, import_react6.useEffect)(() => {
      if (propValues !== void 0) {
        setValues(propValues);
      }
    }, [propValues, setValues]);
    (0, import_react6.useEffect)(() => {
      store.setState({ disabled });
    }, [disabled, store]);
    return /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
      "div",
      {
        ref,
        className: cn("flex flex-col gap-2 w-full", className),
        "aria-label": name,
        ...props,
        children: injectStore(children, store)
      }
    );
  }
);
CheckboxList.displayName = "CheckboxList";
var CheckboxListItem = (0, import_react6.forwardRef)(
  ({
    value,
    store: externalStore,
    disabled: itemDisabled,
    size = "medium",
    state = "default",
    className = "",
    id,
    ...props
  }, ref) => {
    const store = useCheckboxListStore(externalStore);
    const {
      values: groupValues,
      toggleValue,
      disabled: groupDisabled,
      name
    } = (0, import_zustand2.useStore)(store);
    const generatedId = (0, import_react6.useId)();
    const inputId = id ?? `checkbox-item-${generatedId}`;
    const isChecked = groupValues.includes(value);
    const isDisabled = groupDisabled || itemDisabled;
    const currentState = isDisabled ? "disabled" : state;
    return /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
      CheckBox_default,
      {
        ref,
        id: inputId,
        name,
        value,
        checked: isChecked,
        disabled: isDisabled,
        size,
        state: currentState,
        className,
        onChange: () => {
          if (!isDisabled) {
            toggleValue(value);
          }
        },
        ...props
      }
    );
  }
);
CheckboxListItem.displayName = "CheckboxListItem";
var CheckboxList_default = CheckboxList;

// src/components/CheckBoxGroup/CheckBoxGroup.tsx
var import_react7 = require("react");

// src/components/CheckBoxGroup/CheckBoxGroup.helpers.ts
var areSelectedIdsEqual = (ids1, ids2) => {
  if (ids1 === ids2) return true;
  if (!ids1 || !ids2) return ids1 === ids2;
  if (ids1.length !== ids2.length) return false;
  for (let i = 0; i < ids1.length; i++) {
    if (ids1[i] !== ids2[i]) return false;
  }
  return true;
};
var isCategoryEnabled = (category, allCategories) => {
  if (!category.dependsOn || category.dependsOn.length === 0) {
    return true;
  }
  return category.dependsOn.every((depKey) => {
    const depCat = allCategories.find((c) => c.key === depKey);
    return depCat?.selectedIds && depCat.selectedIds.length > 0;
  });
};
var isItemMatchingFilter = (item, filter, allCategories) => {
  const parentCat = allCategories.find((c) => c.key === filter.key);
  const parentSelectedIds = parentCat?.selectedIds || [];
  const itemFieldValue = item[filter.internalField];
  return parentSelectedIds.includes(String(itemFieldValue));
};
var getBadgeText = (category, formattedItems) => {
  const visibleIds = formattedItems.flatMap((group) => group.itens || []).map((i) => i.id);
  const selectedVisibleCount = visibleIds.filter(
    (id) => category.selectedIds?.includes(id)
  ).length;
  const totalVisible = visibleIds.length;
  return `${selectedVisibleCount} de ${totalVisible} ${selectedVisibleCount === 1 ? "selecionado" : "selecionados"}`;
};
var handleAccordionValueChange = (value, categories, isCategoryEnabledFn) => {
  if (typeof value !== "string") {
    if (!value) {
      return "";
    }
    return null;
  }
  if (!value) {
    return "";
  }
  const category = categories.find((c) => c.key === value);
  if (!category) {
    return null;
  }
  const isEnabled = isCategoryEnabledFn(category);
  if (!isEnabled) {
    return null;
  }
  return value;
};
var calculateFormattedItemsForAutoSelection = (category, allCategories) => {
  if (!category?.dependsOn || category.dependsOn.length === 0) {
    return category?.itens || [];
  }
  const isEnabled = isCategoryEnabled(category, allCategories);
  if (!isEnabled) {
    return [];
  }
  const filters = category.filteredBy || [];
  if (filters.length === 0) {
    return category?.itens || [];
  }
  const selectedIdsArr = filters.map((f) => {
    const parentCat = allCategories.find((c) => c.key === f.key);
    if (!parentCat?.selectedIds?.length) {
      return [];
    }
    return parentCat.selectedIds;
  });
  if (selectedIdsArr.some((arr) => arr.length === 0)) {
    return [];
  }
  const filteredItems = (category.itens || []).filter(
    (item) => filters.every((filter) => isItemMatchingFilter(item, filter, allCategories))
  );
  return filteredItems;
};

// src/components/CheckBoxGroup/CheckBoxGroup.tsx
var import_jsx_runtime13 = require("react/jsx-runtime");
var CheckboxGroup = ({
  categories,
  onCategoriesChange,
  compactSingleItem = true,
  showDivider = true,
  showSingleItem = false
}) => {
  const [openAccordion, setOpenAccordion] = (0, import_react7.useState)("");
  const autoSelectionAppliedRef = (0, import_react7.useRef)(false);
  const onCategoriesChangeRef = (0, import_react7.useRef)(onCategoriesChange);
  const previousCategoriesRef = (0, import_react7.useRef)(categories);
  (0, import_react7.useEffect)(() => {
    onCategoriesChangeRef.current = onCategoriesChange;
  }, [onCategoriesChange]);
  const categoriesWithAutoSelection = (0, import_react7.useMemo)(() => {
    return categories.map((category) => {
      const filteredItems = calculateFormattedItemsForAutoSelection(
        category,
        categories
      );
      if (filteredItems.length === 1 && (!category.selectedIds || category.selectedIds.length === 0)) {
        return {
          ...category,
          selectedIds: [filteredItems[0].id]
        };
      }
      return category;
    });
  }, [categories]);
  (0, import_react7.useEffect)(() => {
    const categoriesChanged = categories !== previousCategoriesRef.current;
    if (!categoriesChanged && autoSelectionAppliedRef.current) {
      return;
    }
    previousCategoriesRef.current = categories;
    const hasAutoSelectionChanges = categoriesWithAutoSelection.some(
      (cat, index) => {
        const originalCat = categories[index];
        return !areSelectedIdsEqual(cat.selectedIds, originalCat.selectedIds);
      }
    );
    if (hasAutoSelectionChanges) {
      autoSelectionAppliedRef.current = true;
      onCategoriesChangeRef.current(categoriesWithAutoSelection);
    } else if (categoriesChanged) {
      autoSelectionAppliedRef.current = false;
    }
  }, [categoriesWithAutoSelection, categories]);
  const isCheckBoxIsSelected = (categoryKey, itemId) => {
    const category = categories.find((c) => c.key === categoryKey);
    if (!category) return false;
    return category.selectedIds?.includes(itemId) || false;
  };
  const isMinimalOneCheckBoxIsSelected = (categoryKey) => {
    const category = categories.find((c) => c.key === categoryKey);
    if (!category) return false;
    const formattedItems = getFormattedItems(categoryKey);
    const filteredItems = formattedItems.flatMap((group) => group.itens || []);
    const filteredItemIds = filteredItems.map((item) => item.id);
    return filteredItemIds.some(
      (itemId) => category.selectedIds?.includes(itemId)
    );
  };
  const createCombinations = (acc, currentArray) => {
    const combinations = [];
    for (const existingCombo of acc) {
      for (const item of currentArray) {
        combinations.push([...existingCombo, item]);
      }
    }
    return combinations;
  };
  const cartesian = (arr) => {
    return arr.reduce(createCombinations, [[]]);
  };
  const getSelectedIdsForFilters = (filters) => {
    return filters.map((f) => {
      const parentCat = categories.find((c) => c.key === f.key);
      if (!parentCat?.selectedIds?.length) {
        return [];
      }
      return parentCat.selectedIds;
    });
  };
  const generateSingleFilterLabel = (filter, comboId) => {
    const cat = categories.find((c) => c.key === filter.key);
    return cat?.itens?.find((i) => i.id === comboId)?.name || comboId;
  };
  const generateMultipleFiltersLabel = (filters, comboIds) => {
    const firstCat = categories.find((c) => c.key === filters[0].key);
    const firstVal = firstCat?.itens?.find((i) => i.id === comboIds[0])?.name || comboIds[0];
    const labelParts = [firstVal];
    for (let idx = 1; idx < filters.length; idx++) {
      const f = filters[idx];
      const cat = categories.find((c) => c.key === f.key);
      const val = cat?.itens?.find((i) => i.id === comboIds[idx])?.name || comboIds[idx];
      labelParts.push(`(${val})`);
    }
    return labelParts.join(" ");
  };
  const processCombination = (comboIds, filters, category, groupedMap) => {
    const filteredItems = (category?.itens || []).filter(
      (item) => filters.every((f, idx) => item[f.internalField] === comboIds[idx])
    );
    if (filteredItems.length === 0) return;
    let groupLabel = void 0;
    if (filters.length === 1) {
      groupLabel = generateSingleFilterLabel(filters[0], comboIds[0]);
    } else if (filters.length > 1) {
      groupLabel = generateMultipleFiltersLabel(filters, comboIds);
    }
    const key = groupLabel || "";
    if (!groupedMap[key]) {
      groupedMap[key] = groupLabel ? { groupLabel, itens: [] } : { itens: [] };
    }
    groupedMap[key].itens.push(...filteredItems);
  };
  const calculateFormattedItems = (categoryKey) => {
    const category = categories.find((c) => c.key === categoryKey);
    if (!category?.dependsOn || category.dependsOn.length === 0) {
      return [{ itens: category?.itens || [] }];
    }
    const isEnabled = category.dependsOn.every((depKey) => {
      const depCat = categories.find((c) => c.key === depKey);
      return depCat?.selectedIds && depCat.selectedIds.length > 0;
    });
    if (!isEnabled) {
      return [{ itens: [] }];
    }
    const filters = category.filteredBy || [];
    if (filters.length === 0) {
      return [{ itens: category?.itens || [] }];
    }
    const selectedIdsArr = getSelectedIdsForFilters(filters);
    if (selectedIdsArr.some((arr) => arr.length === 0)) {
      return [{ itens: [] }];
    }
    const combinations = cartesian(selectedIdsArr);
    const groupedMap = {};
    for (const comboIds of combinations) {
      processCombination(comboIds, filters, category, groupedMap);
    }
    const groupedItems = Object.values(groupedMap).filter(
      (g) => g.itens.length
    );
    return groupedItems.length ? groupedItems : [{ itens: [] }];
  };
  const formattedItemsMap = (0, import_react7.useMemo)(() => {
    const formattedItemsMap2 = {};
    for (const category of categories) {
      const formattedItems = calculateFormattedItems(category.key);
      formattedItemsMap2[category.key] = formattedItems;
    }
    return formattedItemsMap2;
  }, [categories]);
  const getFormattedItems = (categoryKey) => {
    return formattedItemsMap[categoryKey] || [{ itens: [] }];
  };
  const getBadgeText2 = (category) => {
    const formattedItems = getFormattedItems(category.key);
    return getBadgeText(category, formattedItems);
  };
  const isCategoryEnabled2 = (category) => {
    return isCategoryEnabled(category, categories);
  };
  const handleAccordionValueChange2 = (value) => {
    const newValue = handleAccordionValueChange(
      value,
      categories,
      isCategoryEnabled2
    );
    if (newValue !== null) {
      setOpenAccordion(newValue);
    }
  };
  const getDependentCategories = (categoryKey) => {
    return categories.filter((cat) => cat.dependsOn?.includes(categoryKey)).map((cat) => cat.key);
  };
  const findItemsToRemove = (depCategory, relevantFilter, deselectedItemId) => {
    return depCategory.itens?.filter(
      (item) => item[relevantFilter.internalField] === deselectedItemId
    ).map((item) => item.id) || [];
  };
  const processDependentCategory = (depCategoryKey, categoryKey, deselectedItemId, itemsToDeselect) => {
    const depCategory = categories.find((c) => c.key === depCategoryKey);
    if (!depCategory?.filteredBy) return;
    const relevantFilter = depCategory.filteredBy.find(
      (f) => f.key === categoryKey
    );
    if (!relevantFilter) return;
    const itemsToRemove = findItemsToRemove(
      depCategory,
      relevantFilter,
      deselectedItemId
    );
    if (itemsToRemove.length > 0) {
      itemsToDeselect[depCategoryKey] = itemsToRemove;
    }
  };
  const getItemsToDeselect = (categoryKey, deselectedItemId) => {
    const deselectedItem = categories.find((c) => c.key === categoryKey)?.itens?.find((item) => item.id === deselectedItemId);
    if (!deselectedItem) return {};
    const itemsToDeselect = {};
    const dependentCategories = getDependentCategories(categoryKey);
    for (const depCategoryKey of dependentCategories) {
      processDependentCategory(
        depCategoryKey,
        categoryKey,
        deselectedItemId,
        itemsToDeselect
      );
    }
    return itemsToDeselect;
  };
  const updateCategorySelectedIds = (updatedCategories, depCategoryIndex, depCategory, itemIds) => {
    const newSelectedIds = depCategory.selectedIds?.filter((id) => !itemIds.includes(id)) || [];
    updatedCategories[depCategoryIndex] = {
      ...depCategory,
      selectedIds: newSelectedIds
    };
    return updatedCategories;
  };
  const applyRecursiveCascade = (depCategoryKey, itemIds, updatedCategories) => {
    let result = updatedCategories;
    for (const itemId of itemIds) {
      result = applyCascadeDeselection(depCategoryKey, itemId, result);
    }
    return result;
  };
  const applyCascadeDeselection = (categoryKey, deselectedItemId, currentCategories) => {
    const itemsToDeselect = getItemsToDeselect(categoryKey, deselectedItemId);
    let updatedCategories = [...currentCategories];
    for (const [depCategoryKey, itemIds] of Object.entries(itemsToDeselect)) {
      const depCategoryIndex = updatedCategories.findIndex(
        (c) => c.key === depCategoryKey
      );
      if (depCategoryIndex !== -1) {
        const depCategory = updatedCategories[depCategoryIndex];
        updatedCategories = updateCategorySelectedIds(
          updatedCategories,
          depCategoryIndex,
          depCategory,
          itemIds
        );
        updatedCategories = applyRecursiveCascade(
          depCategoryKey,
          itemIds,
          updatedCategories
        );
      }
    }
    return updatedCategories;
  };
  const toggleAllInCategory = (categoryKey) => {
    const category = categories.find((c) => c.key === categoryKey);
    if (!category) return;
    const formattedItems = getFormattedItems(categoryKey);
    const filteredItems = formattedItems.flatMap((group) => group.itens || []);
    const filteredItemIds = filteredItems.map((item) => item.id);
    const selectedFilteredCount = filteredItemIds.filter(
      (itemId) => category.selectedIds?.includes(itemId)
    ).length;
    const allFilteredSelected = selectedFilteredCount === filteredItemIds.length;
    const newSelection = allFilteredSelected ? category.selectedIds?.filter((id) => !filteredItemIds.includes(id)) || [] : [
      ...category.selectedIds || [],
      ...filteredItemIds.filter(
        (id) => !category.selectedIds?.includes(id)
      )
    ];
    let updatedCategories = categories.map(
      (c) => c.key === categoryKey ? { ...c, selectedIds: newSelection } : c
    );
    if (allFilteredSelected) {
      for (const itemId of filteredItemIds) {
        updatedCategories = applyCascadeDeselection(
          categoryKey,
          itemId,
          updatedCategories
        );
      }
    }
    onCategoriesChange(updatedCategories);
  };
  const toggleItem = (categoryKey, itemId) => {
    const category = categories.find((c) => c.key === categoryKey);
    if (!category) return;
    const isCurrentlySelected = category.selectedIds?.includes(itemId);
    const newSelection = isCurrentlySelected ? category.selectedIds?.filter((id) => id !== itemId) : [...category.selectedIds || [], itemId];
    let updatedCategories = categories.map(
      (c) => c.key === categoryKey ? { ...c, selectedIds: newSelection } : c
    );
    if (isCurrentlySelected) {
      updatedCategories = applyCascadeDeselection(
        categoryKey,
        itemId,
        updatedCategories
      );
    }
    onCategoriesChange(updatedCategories);
  };
  const renderCheckboxItem = (item, categoryKey) => {
    const uniqueId = `${categoryKey}-${item.id}`;
    return /* @__PURE__ */ (0, import_jsx_runtime13.jsxs)(
      "div",
      {
        className: "flex items-center gap-3 px-2",
        role: "presentation",
        onClick: (e) => e.stopPropagation(),
        onMouseDown: (e) => e.stopPropagation(),
        onMouseUp: (e) => e.stopPropagation(),
        onKeyDown: (e) => e.stopPropagation(),
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(
            CheckBox_default,
            {
              id: uniqueId,
              checked: isCheckBoxIsSelected(categoryKey, item.id),
              onChange: () => toggleItem(categoryKey, item.id)
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(
            "label",
            {
              htmlFor: uniqueId,
              className: "text-sm text-text-950 cursor-pointer select-none",
              children: item.name
            }
          )
        ]
      },
      item.id
    );
  };
  const renderFormattedGroup = (formattedGroup, idx, categoryKey) => /* @__PURE__ */ (0, import_jsx_runtime13.jsxs)(
    "div",
    {
      className: "flex flex-col gap-3",
      children: [
        "groupLabel" in formattedGroup && formattedGroup.groupLabel && /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(Text_default, { size: "sm", className: "mt-2", weight: "semibold", children: formattedGroup.groupLabel }),
        formattedGroup.itens?.map(
          (item) => renderCheckboxItem(item, categoryKey)
        )
      ]
    },
    formattedGroup.groupLabel || `group-${idx}`
  );
  const renderAccordionTrigger = (category, isEnabled) => /* @__PURE__ */ (0, import_jsx_runtime13.jsxs)("div", { className: "flex items-center justify-between w-full p-2", children: [
    /* @__PURE__ */ (0, import_jsx_runtime13.jsxs)("div", { className: "flex items-center gap-3", children: [
      /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(
        CheckBox_default,
        {
          checked: isMinimalOneCheckBoxIsSelected(category.key),
          disabled: !isEnabled,
          indeterminate: isMinimalOneCheckBoxIsSelected(category.key),
          onChange: () => toggleAllInCategory(category.key)
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(
        Text_default,
        {
          size: "sm",
          weight: "medium",
          className: cn("text-text-800", !isEnabled && "opacity-40"),
          children: category.label
        }
      )
    ] }),
    (openAccordion === category.key || isEnabled) && /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(Badge_default, { variant: "solid", action: "info", children: getBadgeText2(category) })
  ] });
  const renderCompactSingleItem = (category) => {
    const formattedItems = getFormattedItems(category.key);
    const allItems = formattedItems.flatMap((group) => group.itens || []);
    if (allItems.length !== 1) {
      return null;
    }
    const singleItem = allItems[0];
    return /* @__PURE__ */ (0, import_jsx_runtime13.jsxs)(
      "div",
      {
        className: "flex items-center justify-between w-full px-3 py-2",
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(Text_default, { size: "sm", weight: "bold", className: "text-text-800", children: category.label }),
          /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(Text_default, { size: "sm", className: "text-text-950", children: singleItem.name })
        ]
      },
      category.key
    );
  };
  const renderCategoryAccordion = (category) => {
    const isEnabled = isCategoryEnabled2(category);
    const hasOnlyOneItem = category.itens?.length === 1;
    if (hasOnlyOneItem && !compactSingleItem && !showSingleItem) {
      return null;
    }
    const formattedItems = getFormattedItems(category.key);
    const allItems = formattedItems.flatMap((group) => group.itens || []);
    const hasOnlyOneAvailableItem = allItems.length === 1;
    if (compactSingleItem && hasOnlyOneAvailableItem && isEnabled) {
      return /* @__PURE__ */ (0, import_jsx_runtime13.jsxs)("div", { children: [
        renderCompactSingleItem(category),
        showDivider && /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(Divider_default, {})
      ] }, category.key);
    }
    const hasNoItems = formattedItems.every(
      (group) => !group.itens || group.itens.length === 0
    );
    return /* @__PURE__ */ (0, import_jsx_runtime13.jsxs)("div", { children: [
      /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(
        CardAccordation,
        {
          value: category.key,
          disabled: !isEnabled,
          className: cn(
            "bg-transparent border-0",
            openAccordion === category.key && "bg-background-50 border-none"
          ),
          trigger: renderAccordionTrigger(category, isEnabled),
          children: /* @__PURE__ */ (0, import_jsx_runtime13.jsx)("div", { className: "flex flex-col gap-3 pt-2", children: hasNoItems && isEnabled ? /* @__PURE__ */ (0, import_jsx_runtime13.jsx)("div", { className: "px-2 py-4", children: /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(Text_default, { size: "sm", className: "text-text-500 text-center", children: "Sem dados" }) }) : formattedItems.map(
            (formattedGroup, idx) => renderFormattedGroup(formattedGroup, idx, category.key)
          ) })
        }
      ),
      openAccordion !== category.key && showDivider && /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(Divider_default, {})
    ] }, category.key);
  };
  (0, import_react7.useEffect)(() => {
    if (!openAccordion) return;
    const category = categories.find((c) => c.key === openAccordion);
    if (!category) return;
    const isEnabled = isCategoryEnabled2(category);
    if (!isEnabled) {
      setTimeout(() => {
        setOpenAccordion("");
      }, 0);
    }
  }, [categories, openAccordion]);
  return /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(
    AccordionGroup,
    {
      type: "single",
      collapsible: true,
      value: openAccordion,
      onValueChange: handleAccordionValueChange2,
      children: categories.map(renderCategoryAccordion)
    }
  );
};

// src/components/AlertManager/AlertsManager.tsx
var import_react12 = require("react");
var import_phosphor_react7 = require("phosphor-react");

// src/components/AlertManager/useAlertForm.ts
var import_zustand3 = require("zustand");
var initialState = {
  title: "",
  message: "",
  image: null,
  date: "",
  time: "",
  sendToday: false,
  sendCopyToEmail: false,
  recipientCategories: {}
};
var useAlertFormStore = (0, import_zustand3.create)((set) => ({
  ...initialState,
  // Step 1 - Mensagem
  setTitle: (title) => set({ title }),
  setMessage: (message) => set({ message }),
  setImage: (image) => set({ image }),
  // Step 2 - Destinatários (Dinâmico)
  initializeCategory: (category) => set((state) => ({
    recipientCategories: {
      ...state.recipientCategories,
      [category.key]: {
        ...category,
        selectedIds: category.selectedIds || [],
        allSelected: category.allSelected || false
      }
    }
  })),
  updateCategoryItems: (key, items) => set((state) => {
    const base = state.recipientCategories[key] ?? {
      key,
      label: key,
      availableItems: [],
      selectedIds: [],
      allSelected: false
    };
    return {
      recipientCategories: {
        ...state.recipientCategories,
        [key]: { ...base, availableItems: items }
      }
    };
  }),
  updateCategorySelection: (key, selectedIds, allSelected) => set((state) => {
    const base = state.recipientCategories[key] ?? {
      key,
      label: key,
      availableItems: [],
      selectedIds: [],
      allSelected: false
    };
    return {
      recipientCategories: {
        ...state.recipientCategories,
        [key]: { ...base, selectedIds, allSelected }
      }
    };
  }),
  clearCategorySelection: (key) => set((state) => {
    const base = state.recipientCategories[key] ?? {
      key,
      label: key,
      availableItems: [],
      selectedIds: [],
      allSelected: false
    };
    return {
      recipientCategories: {
        ...state.recipientCategories,
        [key]: { ...base, selectedIds: [], allSelected: false }
      }
    };
  }),
  // Step 3 - Data de envio
  setDate: (date) => set({ date }),
  setTime: (time) => set({ time }),
  setSendToday: (sendToday) => {
    const now = /* @__PURE__ */ new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, "0");
    const day = String(now.getDate()).padStart(2, "0");
    const hours = String(now.getHours()).padStart(2, "0");
    const minutes = String(now.getMinutes()).padStart(2, "0");
    set({
      sendToday,
      date: `${year}-${month}-${day}`,
      time: `${hours}:${minutes}`
    });
  },
  setSendCopyToEmail: (sendCopyToEmail) => set({ sendCopyToEmail }),
  // Reset form
  resetForm: () => set(initialState)
}));

// src/components/AlertManager/AlertSteps/MessageStep.tsx
var import_shallow = require("zustand/react/shallow");

// src/components/Input/Input.tsx
var import_phosphor_react5 = require("phosphor-react");
var import_react8 = require("react");
var import_jsx_runtime14 = require("react/jsx-runtime");
var SIZE_CLASSES4 = {
  small: "text-sm",
  medium: "text-md",
  large: "text-lg",
  "extra-large": "text-xl"
};
var STATE_CLASSES2 = {
  default: "border-border-300 placeholder:text-text-600 hover:border-border-400",
  error: "border-2 border-indicator-error placeholder:text-text-600",
  disabled: "border-border-300 placeholder:text-text-600 cursor-not-allowed opacity-40",
  "read-only": "border-transparent !text-text-600 cursor-default focus:outline-none bg-transparent"
};
var VARIANT_CLASSES = {
  outlined: "border rounded-lg",
  underlined: "border-0 border-b rounded-none bg-transparent focus:outline-none focus:border-primary-950 focus:border-b-2",
  rounded: "border rounded-full"
};
var getActualState = (disabled, readOnly, errorMessage, state) => {
  if (disabled) return "disabled";
  if (readOnly) return "read-only";
  if (errorMessage) return "error";
  return state || "default";
};
var getIconSize = (size) => {
  const iconSizeClasses = {
    small: "w-4 h-4",
    medium: "w-5 h-5",
    large: "w-6 h-6",
    "extra-large": "w-7 h-7"
  };
  return iconSizeClasses[size] || iconSizeClasses.medium;
};
var getPasswordToggleConfig = (type, disabled, readOnly, showPassword, iconRight) => {
  const isPasswordType = type === "password";
  const shouldShowPasswordToggle = isPasswordType && !disabled && !readOnly;
  let actualIconRight = iconRight;
  let ariaLabel;
  if (shouldShowPasswordToggle) {
    actualIconRight = showPassword ? /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(import_phosphor_react5.EyeSlash, {}) : /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(import_phosphor_react5.Eye, {});
    ariaLabel = showPassword ? "Ocultar senha" : "Mostrar senha";
  }
  return { shouldShowPasswordToggle, actualIconRight, ariaLabel };
};
var getCombinedClasses = (actualState, variant) => {
  const stateClasses = STATE_CLASSES2[actualState];
  const variantClasses = VARIANT_CLASSES[variant];
  if (actualState === "error" && variant === "underlined") {
    return "border-0 border-b-2 border-indicator-error rounded-none bg-transparent focus:outline-none focus:border-primary-950 placeholder:text-text-600";
  }
  if (actualState === "read-only" && variant === "underlined") {
    return "border-0 border-b-0 rounded-none bg-transparent focus:outline-none !text-text-900 cursor-default";
  }
  return `${stateClasses} ${variantClasses}`;
};
var Input = (0, import_react8.forwardRef)(
  ({
    label,
    helperText,
    errorMessage,
    size = "medium",
    variant = "outlined",
    state = "default",
    iconLeft,
    iconRight,
    className = "",
    containerClassName = "",
    disabled,
    readOnly,
    required,
    id,
    type = "text",
    ...props
  }, ref) => {
    const [showPassword, setShowPassword] = (0, import_react8.useState)(false);
    const isPasswordType = type === "password";
    const actualType = isPasswordType && showPassword ? "text" : type;
    const actualState = getActualState(disabled, readOnly, errorMessage, state);
    const sizeClasses = SIZE_CLASSES4[size];
    const combinedClasses = (0, import_react8.useMemo)(
      () => getCombinedClasses(actualState, variant),
      [actualState, variant]
    );
    const iconSize = getIconSize(size);
    const baseClasses = `bg-background w-full py-2 ${actualState === "read-only" ? "px-0" : "px-3"} font-normal text-text-900 focus:outline-primary-950`;
    const generatedId = (0, import_react8.useId)();
    const inputId = id ?? `input-${generatedId}`;
    const togglePasswordVisibility = () => setShowPassword(!showPassword);
    const { shouldShowPasswordToggle, actualIconRight, ariaLabel } = getPasswordToggleConfig(
      type,
      disabled,
      readOnly,
      showPassword,
      iconRight
    );
    return /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)("div", { className: `${containerClassName}`, children: [
      label && /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(
        "label",
        {
          htmlFor: inputId,
          className: `block font-bold text-text-900 mb-1.5 ${sizeClasses}`,
          children: [
            label,
            " ",
            required && /* @__PURE__ */ (0, import_jsx_runtime14.jsx)("span", { className: "text-indicator-error", children: "*" })
          ]
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)("div", { className: "relative", children: [
        iconLeft && /* @__PURE__ */ (0, import_jsx_runtime14.jsx)("div", { className: "absolute left-3 top-1/2 transform -translate-y-1/2 pointer-events-none", children: /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(
          "span",
          {
            className: `${iconSize} text-text-400 flex items-center justify-center`,
            children: iconLeft
          }
        ) }),
        /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(
          "input",
          {
            ref,
            id: inputId,
            type: actualType,
            className: `${baseClasses} ${sizeClasses} ${combinedClasses} ${iconLeft ? "pl-10" : ""} ${actualIconRight ? "pr-10" : ""} ${className}`,
            disabled,
            readOnly,
            required,
            "aria-invalid": actualState === "error" ? "true" : void 0,
            ...props
          }
        ),
        actualIconRight && (shouldShowPasswordToggle ? /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(
          "button",
          {
            type: "button",
            className: "absolute right-3 top-1/2 transform -translate-y-1/2 cursor-pointer border-0 bg-transparent p-0",
            onClick: togglePasswordVisibility,
            "aria-label": ariaLabel,
            children: /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(
              "span",
              {
                className: `${iconSize} text-text-400 flex items-center justify-center hover:text-text-600 transition-colors`,
                children: actualIconRight
              }
            )
          }
        ) : /* @__PURE__ */ (0, import_jsx_runtime14.jsx)("div", { className: "absolute right-3 top-1/2 transform -translate-y-1/2 pointer-events-none", children: /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(
          "span",
          {
            className: `${iconSize} text-text-400 flex items-center justify-center`,
            children: actualIconRight
          }
        ) }))
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)("div", { className: "mt-1.5 gap-1.5", children: [
        helperText && /* @__PURE__ */ (0, import_jsx_runtime14.jsx)("p", { className: "text-sm text-text-500", children: helperText }),
        errorMessage && /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)("p", { className: "flex gap-1 items-center text-sm text-indicator-error", children: [
          /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(import_phosphor_react5.WarningCircle, { size: 16 }),
          " ",
          errorMessage
        ] })
      ] })
    ] });
  }
);
var Input_default = Input;

// src/components/TextArea/TextArea.tsx
var import_react9 = require("react");
var import_phosphor_react6 = require("phosphor-react");
var import_jsx_runtime15 = require("react/jsx-runtime");
var SIZE_CLASSES5 = {
  small: {
    textarea: "h-24 text-sm",
    // 96px height, 14px font
    textSize: "sm"
  },
  medium: {
    textarea: "h-24 text-base",
    // 96px height, 16px font
    textSize: "md"
  },
  large: {
    textarea: "h-24 text-lg",
    // 96px height, 18px font
    textSize: "lg"
  },
  extraLarge: {
    textarea: "h-24 text-xl",
    // 96px height, 20px font
    textSize: "xl"
  }
};
var BASE_TEXTAREA_CLASSES = "w-full box-border p-3 bg-background border border-solid rounded-[4px] resize-none focus:outline-none font-roboto font-normal leading-[150%] placeholder:text-text-600 transition-all duration-200";
var STATE_CLASSES3 = {
  default: {
    base: "border-border-300 bg-background text-text-600",
    hover: "hover:border-border-400",
    focus: "focus:border-border-500"
  },
  hovered: {
    base: "border-border-400 bg-background text-text-600",
    hover: "",
    focus: "focus:border-border-500"
  },
  focused: {
    base: "border-2 border-primary-950 bg-background text-text-900",
    hover: "",
    focus: ""
  },
  invalid: {
    base: "border-2 border-red-700 bg-white text-gray-800",
    hover: "hover:border-red-700",
    focus: "focus:border-red-700"
  },
  disabled: {
    base: "border-border-300 bg-background text-text-600 cursor-not-allowed opacity-40",
    hover: "",
    focus: ""
  }
};
var TextArea = (0, import_react9.forwardRef)(
  ({
    label,
    size = "medium",
    state = "default",
    errorMessage,
    helperMessage,
    className = "",
    labelClassName = "",
    disabled,
    id,
    onChange,
    placeholder,
    required,
    showCharacterCount = false,
    maxLength,
    value,
    ...props
  }, ref) => {
    const generatedId = (0, import_react9.useId)();
    const inputId = id ?? `textarea-${generatedId}`;
    const [isFocused, setIsFocused] = (0, import_react9.useState)(false);
    const currentLength = typeof value === "string" ? value.length : 0;
    const isNearLimit = maxLength && currentLength >= maxLength * 0.8;
    const handleChange = (event) => {
      onChange?.(event);
    };
    const handleFocus = (event) => {
      setIsFocused(true);
      props.onFocus?.(event);
    };
    const handleBlur = (event) => {
      setIsFocused(false);
      props.onBlur?.(event);
    };
    let currentState = disabled ? "disabled" : state;
    if (isFocused && currentState !== "invalid" && currentState !== "disabled") {
      currentState = "focused";
    }
    const sizeClasses = SIZE_CLASSES5[size];
    const stateClasses = STATE_CLASSES3[currentState];
    const textareaClasses = cn(
      BASE_TEXTAREA_CLASSES,
      sizeClasses.textarea,
      stateClasses.base,
      stateClasses.hover,
      stateClasses.focus,
      className
    );
    return /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)("div", { className: `flex flex-col`, children: [
      label && /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)(
        Text_default,
        {
          as: "label",
          htmlFor: inputId,
          size: sizeClasses.textSize,
          weight: "medium",
          color: "text-text-950",
          className: cn("mb-1.5", labelClassName),
          children: [
            label,
            " ",
            required && /* @__PURE__ */ (0, import_jsx_runtime15.jsx)("span", { className: "text-indicator-error", children: "*" })
          ]
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(
        "textarea",
        {
          ref,
          id: inputId,
          disabled,
          onChange: handleChange,
          onFocus: handleFocus,
          onBlur: handleBlur,
          className: textareaClasses,
          placeholder,
          required,
          maxLength,
          value,
          ...props
        }
      ),
      errorMessage && /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)("p", { className: "flex gap-1 items-center text-sm text-indicator-error mt-1.5", children: [
        /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(import_phosphor_react6.WarningCircle, { size: 16 }),
        " ",
        errorMessage
      ] }),
      !errorMessage && showCharacterCount && maxLength && /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)(
        Text_default,
        {
          size: "sm",
          weight: "normal",
          className: `mt-1.5 ${isNearLimit ? "text-indicator-warning" : "text-text-500"}`,
          children: [
            currentLength,
            "/",
            maxLength,
            " caracteres"
          ]
        }
      ),
      !errorMessage && helperMessage && !(showCharacterCount && maxLength) && /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(Text_default, { size: "sm", weight: "normal", className: "mt-1.5 text-text-500", children: helperMessage })
    ] });
  }
);
TextArea.displayName = "TextArea";
var TextArea_default = TextArea;

// src/components/AlertManager/AlertSteps/MessageStep.tsx
var import_jsx_runtime16 = require("react/jsx-runtime");
var MessageStep = ({
  labels,
  allowImageAttachment = true
}) => {
  const { title, message, image, setTitle, setMessage, setImage } = useAlertFormStore(
    (0, import_shallow.useShallow)((state) => ({
      title: state.title,
      message: state.message,
      image: state.image,
      setTitle: state.setTitle,
      setMessage: state.setMessage,
      setImage: state.setImage
    }))
  );
  const handleFileSelect = (file) => {
    setImage(file);
  };
  const handleRemoveFile = () => {
    setImage(null);
  };
  const isImageFile = image instanceof File;
  return /* @__PURE__ */ (0, import_jsx_runtime16.jsxs)("section", { className: "flex flex-col gap-4", children: [
    /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(
      Input_default,
      {
        required: true,
        label: labels?.titleLabel || "T\xEDtulo",
        placeholder: labels?.titlePlaceholder || "Digite o t\xEDtulo do aviso",
        variant: "rounded",
        value: title,
        onChange: (e) => setTitle(e.target.value)
      }
    ),
    /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(
      TextArea_default,
      {
        required: true,
        label: labels?.messageLabel || "Mensagem",
        placeholder: labels?.messagePlaceholder || "Digite a mensagem do aviso",
        value: message,
        onChange: (e) => setMessage(e.target.value)
      }
    ),
    allowImageAttachment && /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(
      ImageUpload,
      {
        selectedFile: isImageFile ? image : null,
        onFileSelect: handleFileSelect,
        onRemoveFile: handleRemoveFile
      }
    )
  ] });
};

// src/components/AlertManager/AlertSteps/RecipientsStep.tsx
var import_react10 = require("react");
var import_jsx_runtime17 = require("react/jsx-runtime");
var RecipientsStep = ({
  categories,
  labels,
  onCategoriesChange
}) => {
  const { recipientCategories, initializeCategory } = useAlertFormStore();
  (0, import_react10.useEffect)(() => {
    for (const category of categories) {
      const existingCategory = recipientCategories[category.key];
      if (!existingCategory) {
        initializeCategory({
          key: category.key,
          label: category.label,
          availableItems: category.itens || [],
          selectedIds: category.selectedIds || [],
          allSelected: false
        });
      }
    }
  }, [categories, recipientCategories, initializeCategory]);
  const handleCategoriesChange = (updatedCategories) => {
    for (const category of updatedCategories) {
      const selectedIds = category.selectedIds || [];
      const allSelected = selectedIds.length === (category.itens?.length || 0);
      initializeCategory({
        key: category.key,
        label: category.label,
        availableItems: category.itens || [],
        selectedIds,
        allSelected
      });
    }
    if (onCategoriesChange) {
      onCategoriesChange(updatedCategories);
    }
  };
  const syncedCategories = (0, import_react10.useMemo)(() => {
    return categories.map((category) => {
      const storeCategory = recipientCategories[category.key];
      if (storeCategory) {
        return {
          ...category,
          selectedIds: storeCategory.selectedIds
        };
      }
      return category;
    });
  }, [categories, recipientCategories]);
  return /* @__PURE__ */ (0, import_jsx_runtime17.jsxs)("section", { className: "flex flex-col gap-4", children: [
    /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(Text_default, { size: "lg", weight: "medium", className: "text-text-950", children: labels?.recipientsDescription || "Para quem voc\xEA vai enviar o aviso?" }),
    /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(
      CheckboxGroup,
      {
        categories: syncedCategories,
        onCategoriesChange: handleCategoriesChange
      }
    )
  ] });
};

// src/components/AlertManager/AlertSteps/DateStep.tsx
var import_jsx_runtime18 = require("react/jsx-runtime");
var DateStep = ({
  labels,
  allowScheduling = true,
  allowEmailCopy = true
}) => {
  const date = useAlertFormStore((state) => state.date);
  const time = useAlertFormStore((state) => state.time);
  const sendToday = useAlertFormStore((state) => state.sendToday);
  const sendCopyToEmail = useAlertFormStore((state) => state.sendCopyToEmail);
  const setDate = useAlertFormStore((state) => state.setDate);
  const setTime = useAlertFormStore((state) => state.setTime);
  const setSendToday = useAlertFormStore((state) => state.setSendToday);
  const setSendCopyToEmail = useAlertFormStore(
    (state) => state.setSendCopyToEmail
  );
  return /* @__PURE__ */ (0, import_jsx_runtime18.jsxs)("section", { className: "flex flex-col gap-4", children: [
    /* @__PURE__ */ (0, import_jsx_runtime18.jsxs)("span", { className: "flex flex-row items-center gap-6", children: [
      /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(
        Text_default,
        {
          weight: "normal",
          className: "cursor-pointer select-none leading-[150%] flex items-center font-roboto",
          children: labels?.sendTodayLabel || "Enviar Hoje?"
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(
        CheckBox_default,
        {
          label: "Sim",
          checked: sendToday,
          onChange: (e) => setSendToday(e.target.checked)
        }
      )
    ] }),
    allowScheduling && /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(
      DateTimeInput_default,
      {
        label: labels?.dateLabel || "Data de envio",
        date,
        time,
        onDateChange: setDate,
        onTimeChange: setTime,
        disabled: sendToday,
        timeLabel: labels?.timeLabel || "Hora de envio",
        testId: "alert-datetime"
      }
    ),
    allowEmailCopy && /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(
      CheckBox_default,
      {
        label: labels?.sendCopyToEmailLabel || "Enviar c\xF3pia para e-mail",
        checked: sendCopyToEmail,
        onChange: (e) => setSendCopyToEmail(e.target.checked)
      }
    )
  ] });
};

// src/components/AlertManager/AlertSteps/PreviewStep.tsx
var import_react11 = require("react");
var import_jsx_runtime19 = require("react/jsx-runtime");
var PreviewStep = ({ imageLink, defaultImage }) => {
  const title = useAlertFormStore((state) => state.title);
  const message = useAlertFormStore((state) => state.message);
  const image = useAlertFormStore((state) => state.image);
  const imageUrl = (0, import_react11.useMemo)(() => {
    if (globalThis.window === void 0) {
      return void 0;
    }
    if (image instanceof File) {
      return globalThis.window.URL.createObjectURL(image);
    }
    if (typeof image === "string") {
      return image;
    }
    return void 0;
  }, [image]);
  (0, import_react11.useEffect)(() => {
    return () => {
      if (globalThis.window !== void 0 && imageUrl && image instanceof File) {
        URL.revokeObjectURL(imageUrl);
      }
    };
  }, [imageUrl, image]);
  const finalImageUrl = imageLink || imageUrl || defaultImage || void 0;
  return /* @__PURE__ */ (0, import_jsx_runtime19.jsx)("section", { className: "flex flex-col gap-4", children: /* @__PURE__ */ (0, import_jsx_runtime19.jsxs)("div", { className: "bg-background-50 px-5 py-6 flex flex-col items-center gap-4 rounded-xl", children: [
    finalImageUrl && /* @__PURE__ */ (0, import_jsx_runtime19.jsx)("img", { src: finalImageUrl, alt: title || "Imagem do alerta" }),
    /* @__PURE__ */ (0, import_jsx_runtime19.jsxs)("div", { className: "flex flex-col items-center text-center gap-3", children: [
      /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(Text_default, { size: "lg", weight: "semibold", children: title || "Nenhum T\xEDtulo de Alerta" }),
      /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(Text_default, { size: "sm", weight: "normal", className: "text-text-500", children: message || "Aqui aparecer\xE1 a mensagem do alerta definido pelo usu\xE1rio" })
    ] })
  ] }) });
};

// src/components/AlertManager/validation.ts
var BASE_STEPS_COUNT = 4;
var validateMessageStep = (formData) => {
  if (!formData.title?.trim()) return "T\xEDtulo \xE9 obrigat\xF3rio";
  if (!formData.message?.trim()) return "Mensagem \xE9 obrigat\xF3ria";
  return true;
};
var validateRecipientsStep = (categories) => {
  if (categories.length === 0) return "Nenhuma categoria configurada";
  const lastCategory = categories.at(-1);
  if (!lastCategory?.selectedIds?.length) return "Selecione destinat\xE1rios";
  return true;
};
var validateDateStep = (formData) => {
  if (!formData.sendToday && !formData.date) return "Data \xE9 obrigat\xF3ria";
  return true;
};
var canFinish = (formData, categories) => {
  return validateMessageStep(formData) === true && validateRecipientsStep(categories) === true && validateDateStep(formData) === true;
};
var isCurrentStepValid = (currentStep, formData, categories, customSteps) => {
  return validateCurrentStep(currentStep, formData, categories, customSteps) === true;
};
var validateCurrentStep = (currentStep, formData, categories, customSteps) => {
  switch (currentStep) {
    case 0:
      return validateMessageStep(formData);
    case 1:
      return validateRecipientsStep(categories);
    case 2:
      return validateDateStep(formData);
    case 3:
      return true;
    default: {
      const currentStepConfig = customSteps?.[currentStep - BASE_STEPS_COUNT];
      return currentStepConfig?.validate ? currentStepConfig.validate(formData) : true;
    }
  }
};
var advanceToNextStep = (currentStep, completedSteps, setCompletedSteps, setCurrentStep) => {
  if (setCompletedSteps && !completedSteps.includes(currentStep)) {
    setCompletedSteps([...completedSteps, currentStep]);
  }
  if (setCurrentStep) {
    setCurrentStep(currentStep + 1);
  }
};
var handleNext = ({
  currentStep,
  steps,
  formData,
  categories,
  customSteps,
  completedSteps = [],
  setCompletedSteps,
  setCurrentStep
}) => {
  if (currentStep >= steps.length - 1) {
    return { success: false, error: "J\xE1 est\xE1 no \xFAltimo step" };
  }
  const validation = validateCurrentStep(
    currentStep,
    formData,
    categories,
    customSteps
  );
  if (validation !== true) {
    console.error("Valida\xE7\xE3o falhou:", validation);
    const errorMessage = typeof validation === "string" ? validation : "Preencha todos os campos obrigat\xF3rios";
    return { success: false, error: errorMessage };
  }
  advanceToNextStep(
    currentStep,
    completedSteps,
    setCompletedSteps,
    setCurrentStep
  );
  return { success: true };
};

// src/components/AlertManager/AlertsManager.tsx
var import_jsx_runtime20 = require("react/jsx-runtime");
var StepWrapper = ({ children }) => /* @__PURE__ */ (0, import_jsx_runtime20.jsx)("div", { children });
var AlertsManager = ({
  config,
  isOpen = false,
  onClose,
  imageLink,
  defaultImage
}) => {
  const [isModalOpen, setIsModalOpen] = (0, import_react12.useState)(isOpen);
  const [currentStep, setCurrentStep] = (0, import_react12.useState)(0);
  const [completedSteps, setCompletedSteps] = (0, import_react12.useState)([]);
  const [categories, setCategories] = (0, import_react12.useState)(config.categories);
  const formData = (0, import_react12.useSyncExternalStore)(
    useAlertFormStore.subscribe,
    useAlertFormStore.getState
  );
  (0, import_react12.useEffect)(() => {
    setIsModalOpen(isOpen);
  }, [isOpen]);
  const { labels, behavior, steps: customSteps } = config;
  const defaultSteps = [
    {
      id: "1",
      label: "Mensagem",
      state: "completed"
    },
    {
      id: "2",
      label: labels?.recipientsTitle || "Destinat\xE1rios",
      state: "current"
    },
    {
      id: "3",
      label: labels?.dateLabel || "Data de envio",
      state: "pending"
    },
    {
      id: "4",
      label: labels?.previewTitle || "Pr\xE9via",
      state: "pending"
    }
  ];
  const steps = customSteps || defaultSteps;
  const handleCloseModal = () => {
    setIsModalOpen(false);
    onClose?.();
  };
  const isCurrentStepValid2 = (0, import_react12.useCallback)(() => {
    return isCurrentStepValid(
      currentStep,
      formData,
      categories,
      customSteps
    );
  }, [currentStep, categories, customSteps, formData]);
  const canFinish2 = (0, import_react12.useCallback)(() => {
    return canFinish(formData, categories);
  }, [categories, formData]);
  const handleNext2 = (0, import_react12.useCallback)(() => {
    const result = handleNext({
      currentStep,
      steps,
      formData,
      categories,
      customSteps,
      completedSteps,
      setCompletedSteps,
      setCurrentStep
    });
    if (!result.success && result.error) {
      alert(result.error);
    }
  }, [
    currentStep,
    steps,
    categories,
    customSteps,
    completedSteps,
    setCompletedSteps,
    setCurrentStep,
    formData
  ]);
  const handlePrevious = (0, import_react12.useCallback)(() => {
    if (currentStep > 0) {
      setCurrentStep(currentStep - 1);
    }
  }, [currentStep, setCurrentStep]);
  const handleFinish = async () => {
    if (!completedSteps.includes(currentStep)) {
      setCompletedSteps([...completedSteps, currentStep]);
    }
    const alertData = {
      title: formData.title,
      message: formData.message,
      image: formData.image,
      date: formData.date,
      time: formData.time,
      sendToday: formData.sendToday,
      sendCopyToEmail: formData.sendCopyToEmail,
      recipientCategories: Object.fromEntries(
        Object.entries(formData.recipientCategories).map(([key, c]) => [
          key,
          {
            selectedIds: c.selectedIds || [],
            allSelected: !!c.allSelected
          }
        ])
      )
    };
    try {
      if (behavior?.onSendAlert) {
        await behavior.onSendAlert(alertData);
      } else {
        console.log("Dados do formul\xE1rio:", alertData);
        alert("Aviso enviado com sucesso!");
      }
      handleCloseModal();
    } catch (error) {
      console.error("Erro ao enviar aviso:", error);
    }
  };
  const dynamicSteps = steps.map(
    (step, index) => {
      if (completedSteps.includes(index)) {
        return { ...step, state: "completed" };
      }
      if (index === currentStep) {
        return { ...step, state: "current" };
      }
      return { ...step, state: "pending" };
    }
  );
  const currentStepContent = (0, import_react12.useMemo)(() => {
    if (customSteps?.[currentStep]?.component) {
      const CustomComponent = customSteps[currentStep].component;
      return /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(StepWrapper, { children: /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(CustomComponent, { onNext: handleNext2, onPrevious: handlePrevious }) });
    }
    switch (currentStep) {
      case 0:
        return /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(StepWrapper, { children: /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(
          MessageStep,
          {
            labels,
            allowImageAttachment: behavior?.allowImageAttachment
          }
        ) });
      case 1:
        return /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(StepWrapper, { children: /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(
          RecipientsStep,
          {
            categories,
            labels,
            onCategoriesChange: setCategories
          }
        ) });
      case 2:
        return /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(StepWrapper, { children: /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(
          DateStep,
          {
            labels,
            allowScheduling: behavior?.allowScheduling,
            allowEmailCopy: behavior?.allowEmailCopy
          }
        ) });
      case 3:
        return /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(StepWrapper, { children: /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(PreviewStep, { imageLink, defaultImage }) });
      default:
        return null;
    }
  }, [
    currentStep,
    customSteps,
    categories,
    labels,
    behavior,
    handleNext2,
    handlePrevious,
    imageLink,
    defaultImage
  ]);
  const isFirstStep = currentStep === 0;
  const isLastStep = currentStep === steps.length - 1;
  return /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(
    Modal_default,
    {
      isOpen: isModalOpen,
      onClose: handleCloseModal,
      title: labels?.modalTitle || "Enviar aviso",
      size: "md",
      contentClassName: "p-0",
      footer: /* @__PURE__ */ (0, import_jsx_runtime20.jsx)("div", { className: "flex gap-3 justify-end w-full", children: /* @__PURE__ */ (0, import_jsx_runtime20.jsxs)("div", { className: "flex gap-3", children: [
        /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(Button_default, { variant: "link", size: "small", onClick: handleCloseModal, children: labels?.cancelButton || "Cancelar" }),
        !isFirstStep && /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(
          Button_default,
          {
            variant: "outline",
            size: "small",
            iconLeft: /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(import_phosphor_react7.CaretLeft, {}),
            onClick: handlePrevious,
            children: labels?.previousButton || "Anterior"
          }
        ),
        isLastStep ? /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(
          Button_default,
          {
            variant: "solid",
            iconLeft: /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(import_phosphor_react7.PaperPlaneTilt, {}),
            size: "small",
            onClick: handleFinish,
            disabled: !canFinish2(),
            children: labels?.finishButton || "Enviar Aviso"
          }
        ) : /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(
          Button_default,
          {
            variant: "solid",
            iconRight: /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(import_phosphor_react7.CaretRight, {}),
            size: "small",
            onClick: handleNext2,
            disabled: !isCurrentStepValid2(),
            children: labels?.nextButton || "Pr\xF3ximo"
          }
        )
      ] }) }),
      children: /* @__PURE__ */ (0, import_jsx_runtime20.jsxs)("div", { className: "flex flex-col h-[calc(100vh-14rem)] max-h-[600px]", children: [
        /* @__PURE__ */ (0, import_jsx_runtime20.jsx)("div", { className: "shrink-0 px-6 pt-4", children: /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(
          Stepper_default,
          {
            steps: dynamicSteps,
            size: "small",
            showProgress: true,
            responsive: true,
            progressText: `Etapa ${currentStep + 1} de ${steps.length}`
          }
        ) }),
        /* @__PURE__ */ (0, import_jsx_runtime20.jsx)("div", { className: "flex-1 overflow-y-auto px-6 pb-4", children: currentStepContent })
      ] })
    }
  );
};

// src/components/Modal/Modal.tsx
var import_react13 = require("react");
var import_phosphor_react8 = require("phosphor-react");

// src/components/Modal/utils/videoUtils.ts
var isYouTubeUrl = (url) => {
  const youtubeRegex = /^(https?:\/\/)?((www|m|music)\.)?(youtube\.com|youtu\.be|youtube-nocookie\.com)\/.+/i;
  return youtubeRegex.test(url);
};
var isValidYouTubeHost = (host) => {
  if (host === "youtu.be") return "youtu.be";
  const isValidYouTubeCom = host === "youtube.com" || host.endsWith(".youtube.com") && /^(www|m|music)\.youtube\.com$/.test(host);
  if (isValidYouTubeCom) return "youtube";
  const isValidNoCookie = host === "youtube-nocookie.com" || host.endsWith(".youtube-nocookie.com") && /^(www|m|music)\.youtube-nocookie\.com$/.test(host);
  if (isValidNoCookie) return "nocookie";
  return null;
};
var extractYoutuBeId = (pathname) => {
  const firstSeg = pathname.split("/").filter(Boolean)[0];
  return firstSeg || null;
};
var extractYouTubeId = (pathname, searchParams) => {
  const parts = pathname.split("/").filter(Boolean);
  const [first, second] = parts;
  if (first === "embed" && second) return second;
  if (first === "shorts" && second) return second;
  if (first === "live" && second) return second;
  const v = searchParams.get("v");
  if (v) return v;
  return null;
};
var getYouTubeVideoId = (url) => {
  try {
    const u = new URL(url);
    const hostType = isValidYouTubeHost(u.hostname.toLowerCase());
    if (!hostType) return null;
    if (hostType === "youtu.be") {
      return extractYoutuBeId(u.pathname);
    }
    return extractYouTubeId(u.pathname, u.searchParams);
  } catch {
    return null;
  }
};
var getYouTubeEmbedUrl = (videoId) => {
  return `https://www.youtube-nocookie.com/embed/${videoId}?autoplay=0&rel=0&modestbranding=1`;
};

// src/components/Modal/Modal.tsx
var import_jsx_runtime21 = require("react/jsx-runtime");
var SIZE_CLASSES6 = {
  xs: "max-w-[360px]",
  sm: "max-w-[420px]",
  md: "max-w-[510px]",
  lg: "max-w-[640px]",
  xl: "max-w-[970px]"
};
var Modal = ({
  isOpen,
  onClose,
  title,
  children,
  size = "md",
  className = "",
  closeOnEscape = true,
  footer,
  hideCloseButton = false,
  variant = "default",
  description,
  image,
  imageAlt,
  actionLink,
  actionLabel,
  contentClassName = ""
}) => {
  const titleId = (0, import_react13.useId)();
  (0, import_react13.useEffect)(() => {
    if (!isOpen || !closeOnEscape) return;
    const handleEscape = (event) => {
      if (event.key === "Escape") {
        onClose();
      }
    };
    document.addEventListener("keydown", handleEscape);
    return () => document.removeEventListener("keydown", handleEscape);
  }, [isOpen, closeOnEscape, onClose]);
  (0, import_react13.useEffect)(() => {
    if (!isOpen) return;
    const scrollbarWidth = window.innerWidth - document.documentElement.clientWidth;
    const originalOverflow = document.body.style.overflow;
    const originalPaddingRight = document.body.style.paddingRight;
    document.body.style.overflow = "hidden";
    if (scrollbarWidth > 0) {
      document.body.style.paddingRight = `${scrollbarWidth}px`;
      const overlay = document.createElement("div");
      overlay.id = "modal-scrollbar-overlay";
      overlay.style.cssText = `
        position: fixed;
        top: 0;
        right: 0;
        width: ${scrollbarWidth}px;
        height: 100vh;
        background-color: rgb(0 0 0 / 0.6);
        z-index: 40;
        pointer-events: none;
      `;
      document.body.appendChild(overlay);
    }
    return () => {
      document.body.style.overflow = originalOverflow;
      document.body.style.paddingRight = originalPaddingRight;
      const overlay = document.getElementById("modal-scrollbar-overlay");
      if (overlay) {
        overlay.remove();
      }
    };
  }, [isOpen]);
  if (!isOpen) return null;
  const sizeClasses = SIZE_CLASSES6[size];
  const baseClasses = "bg-secondary-50 rounded-3xl shadow-hard-shadow-2 border border-border-100 w-full mx-4";
  const dialogResetClasses = "p-0 m-0 border-none outline-none max-h-none static";
  const modalClasses = cn(
    baseClasses,
    sizeClasses,
    dialogResetClasses,
    className
  );
  const normalizeUrl = (href) => /^https?:\/\//i.test(href) ? href : `https://${href}`;
  const handleActionClick = () => {
    if (actionLink) {
      window.open(normalizeUrl(actionLink), "_blank", "noopener,noreferrer");
    }
  };
  if (variant === "activity") {
    return /* @__PURE__ */ (0, import_jsx_runtime21.jsx)("div", { className: "fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-xs border-none p-0 m-0 w-full cursor-default", children: /* @__PURE__ */ (0, import_jsx_runtime21.jsxs)(
      "dialog",
      {
        className: modalClasses,
        "aria-labelledby": titleId,
        "aria-modal": "true",
        open: true,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime21.jsx)("div", { className: "flex justify-end p-6 pb-0", children: !hideCloseButton && /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(
            "button",
            {
              onClick: onClose,
              className: "p-1 text-text-500 hover:text-text-700 hover:bg-background-50 rounded-md transition-colors focus:outline-none focus:ring-2 focus:ring-indicator-info focus:ring-offset-2",
              "aria-label": "Fechar modal",
              children: /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(import_phosphor_react8.X, { size: 18 })
            }
          ) }),
          /* @__PURE__ */ (0, import_jsx_runtime21.jsxs)("div", { className: "flex flex-col items-center px-6 pb-6 gap-5", children: [
            image && /* @__PURE__ */ (0, import_jsx_runtime21.jsx)("div", { className: "flex justify-center", children: /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(
              "img",
              {
                src: image,
                alt: imageAlt ?? "",
                className: "w-[122px] h-[122px] object-contain"
              }
            ) }),
            /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(
              "h2",
              {
                id: titleId,
                className: "text-lg font-semibold text-text-950 text-center",
                children: title
              }
            ),
            description && /* @__PURE__ */ (0, import_jsx_runtime21.jsx)("p", { className: "text-sm font-normal text-text-400 text-center max-w-md leading-[21px]", children: description }),
            actionLink && /* @__PURE__ */ (0, import_jsx_runtime21.jsxs)("div", { className: "w-full", children: [
              (() => {
                const normalized = normalizeUrl(actionLink);
                const isYT = isYouTubeUrl(normalized);
                if (!isYT) return null;
                const id = getYouTubeVideoId(normalized);
                if (!id) {
                  return /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(
                    Button_default,
                    {
                      variant: "solid",
                      action: "primary",
                      size: "large",
                      className: "w-full",
                      onClick: handleActionClick,
                      children: actionLabel || "Iniciar Atividade"
                    }
                  );
                }
                return /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(
                  "iframe",
                  {
                    src: getYouTubeEmbedUrl(id),
                    className: "w-full aspect-video rounded-lg",
                    allowFullScreen: true,
                    allow: "accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",
                    title: "V\xEDdeo YouTube"
                  }
                );
              })(),
              !isYouTubeUrl(normalizeUrl(actionLink)) && /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(
                Button_default,
                {
                  variant: "solid",
                  action: "primary",
                  size: "large",
                  className: "w-full",
                  onClick: handleActionClick,
                  children: actionLabel || "Iniciar Atividade"
                }
              )
            ] })
          ] })
        ]
      }
    ) });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime21.jsx)("div", { className: "fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-xs border-none p-0 m-0 w-full cursor-default", children: /* @__PURE__ */ (0, import_jsx_runtime21.jsxs)(
    "dialog",
    {
      className: modalClasses,
      "aria-labelledby": titleId,
      "aria-modal": "true",
      open: true,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime21.jsxs)("div", { className: "flex items-center justify-between px-6 py-6", children: [
          /* @__PURE__ */ (0, import_jsx_runtime21.jsx)("h2", { id: titleId, className: "text-lg font-semibold text-text-950", children: title }),
          !hideCloseButton && /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(
            "button",
            {
              onClick: onClose,
              className: "p-1 text-text-500 hover:text-text-700 hover:bg-background-50 rounded-md transition-colors focus:outline-none focus:ring-2 focus:ring-indicator-info focus:ring-offset-2",
              "aria-label": "Fechar modal",
              children: /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(import_phosphor_react8.X, { size: 18 })
            }
          )
        ] }),
        children && /* @__PURE__ */ (0, import_jsx_runtime21.jsx)("div", { className: cn("px-6 pb-6", contentClassName), children: /* @__PURE__ */ (0, import_jsx_runtime21.jsx)("div", { className: "text-text-500 font-normal text-sm leading-6", children }) }),
        footer && /* @__PURE__ */ (0, import_jsx_runtime21.jsx)("div", { className: "flex justify-end gap-3 px-6 pb-6", children: footer })
      ]
    }
  ) });
};
var Modal_default = Modal;

// src/components/Divider/Divider.tsx
var import_jsx_runtime22 = require("react/jsx-runtime");
var Divider = ({
  orientation = "horizontal",
  className = "",
  ...props
}) => {
  const baseClasses = "bg-border-200 border-0";
  const orientationClasses = {
    horizontal: "w-full h-px",
    vertical: "h-full w-px"
  };
  return /* @__PURE__ */ (0, import_jsx_runtime22.jsx)(
    "hr",
    {
      className: cn(baseClasses, orientationClasses[orientation], className),
      "aria-orientation": orientation,
      ...props
    }
  );
};
var Divider_default = Divider;

// src/components/Table/Table.tsx
var import_react15 = require("react");
var import_phosphor_react10 = require("phosphor-react");

// src/components/NoSearchResult/NoSearchResult.tsx
var import_jsx_runtime23 = require("react/jsx-runtime");
var NoSearchResult = ({ image, title, description }) => {
  const displayTitle = title || "Nenhum resultado encontrado";
  const displayDescription = description || "N\xE3o encontramos nenhum resultado com esse nome. Tente revisar a busca ou usar outra palavra-chave.";
  return /* @__PURE__ */ (0, import_jsx_runtime23.jsxs)("div", { className: "flex flex-row justify-center items-center gap-8 w-full max-w-4xl min-h-96", children: [
    /* @__PURE__ */ (0, import_jsx_runtime23.jsx)("div", { className: "w-72 h-72 flex-shrink-0 relative", children: /* @__PURE__ */ (0, import_jsx_runtime23.jsx)(
      "img",
      {
        src: image,
        alt: "No search results",
        className: "w-full h-full object-contain"
      }
    ) }),
    /* @__PURE__ */ (0, import_jsx_runtime23.jsxs)("div", { className: "flex flex-col items-start w-full max-w-md", children: [
      /* @__PURE__ */ (0, import_jsx_runtime23.jsx)("div", { className: "flex flex-row justify-between items-end px-6 pt-6 pb-4 w-full rounded-t-xl", children: /* @__PURE__ */ (0, import_jsx_runtime23.jsx)(
        Text_default,
        {
          as: "h2",
          className: "text-text-950 font-semibold text-3xl leading-tight w-full flex items-center",
          children: displayTitle
        }
      ) }),
      /* @__PURE__ */ (0, import_jsx_runtime23.jsx)("div", { className: "flex flex-row justify-center items-center px-6 gap-2 w-full", children: /* @__PURE__ */ (0, import_jsx_runtime23.jsx)(Text_default, { className: "text-text-600 font-normal text-lg leading-relaxed w-full text-justify", children: displayDescription }) })
    ] })
  ] });
};
var NoSearchResult_default = NoSearchResult;

// src/components/EmptyState/EmptyState.tsx
var import_jsx_runtime24 = require("react/jsx-runtime");
var EmptyState = ({
  image,
  title,
  description,
  buttonText,
  buttonIcon,
  onButtonClick,
  buttonVariant = "solid",
  buttonAction = "primary"
}) => {
  const displayTitle = title || "Nenhum dado dispon\xEDvel";
  const displayDescription = description || "N\xE3o h\xE1 dados para exibir no momento.";
  return /* @__PURE__ */ (0, import_jsx_runtime24.jsxs)("div", { className: "flex flex-col justify-center items-center gap-6 w-full min-h-[705px] bg-background rounded-xl p-6", children: [
    image && /* @__PURE__ */ (0, import_jsx_runtime24.jsx)("img", { src: image, alt: displayTitle, className: "w-[170px] h-[150px]" }),
    /* @__PURE__ */ (0, import_jsx_runtime24.jsxs)("div", { className: "flex flex-col items-center gap-4 w-full max-w-[600px] px-6", children: [
      /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(
        Text_default,
        {
          as: "h2",
          className: "text-text-950 font-semibold text-3xl leading-[35px] text-center",
          children: displayTitle
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(Text_default, { className: "text-text-600 font-normal text-[18px] leading-[27px] text-center", children: displayDescription })
    ] }),
    buttonText && onButtonClick && /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(
      Button_default,
      {
        variant: buttonVariant,
        action: buttonAction,
        size: "large",
        onClick: onButtonClick,
        iconLeft: buttonIcon,
        className: "rounded-full px-5 py-2.5",
        children: buttonText
      }
    )
  ] });
};
var EmptyState_default = EmptyState;

// src/components/Skeleton/Skeleton.tsx
var import_react14 = require("react");
var import_jsx_runtime25 = require("react/jsx-runtime");
var SKELETON_ANIMATION_CLASSES = {
  pulse: "animate-pulse",
  none: ""
};
var SKELETON_VARIANT_CLASSES = {
  text: "h-4 bg-background-200 rounded",
  circular: "bg-background-200 rounded-full",
  rectangular: "bg-background-200",
  rounded: "bg-background-200 rounded-lg"
};
var SPACING_CLASSES = {
  none: "",
  small: "space-y-1",
  medium: "space-y-2",
  large: "space-y-3"
};
var Skeleton = (0, import_react14.forwardRef)(
  ({
    variant = "text",
    width,
    height,
    animation = "pulse",
    lines = 1,
    spacing = "none",
    className = "",
    children,
    ...props
  }, ref) => {
    const animationClass = SKELETON_ANIMATION_CLASSES[animation];
    const variantClass = SKELETON_VARIANT_CLASSES[variant];
    const spacingClass = SPACING_CLASSES[spacing];
    const style = {
      width: typeof width === "number" ? `${width}px` : width,
      height: typeof height === "number" ? `${height}px` : height
    };
    if (variant === "text" && lines > 1) {
      return /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(
        "div",
        {
          ref,
          className: cn("flex flex-col", spacingClass, className),
          ...props,
          children: Array.from({ length: lines }, (_, index) => /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(
            "div",
            {
              className: cn(variantClass, animationClass),
              style: index === lines - 1 ? { width: "60%" } : void 0
            },
            index
          ))
        }
      );
    }
    return /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(
      "div",
      {
        ref,
        className: cn(variantClass, animationClass, className),
        style,
        ...props,
        children
      }
    );
  }
);
var SkeletonText = (0, import_react14.forwardRef)(
  (props, ref) => /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(Skeleton, { ref, variant: "text", ...props })
);
var SkeletonCircle = (0, import_react14.forwardRef)((props, ref) => /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(Skeleton, { ref, variant: "circular", ...props }));
var SkeletonRectangle = (0, import_react14.forwardRef)((props, ref) => /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(Skeleton, { ref, variant: "rectangular", ...props }));
var SkeletonRounded = (0, import_react14.forwardRef)((props, ref) => /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(Skeleton, { ref, variant: "rounded", ...props }));
var SkeletonCard = (0, import_react14.forwardRef)(
  ({
    showAvatar = true,
    showTitle = true,
    showDescription = true,
    showActions = true,
    lines = 2,
    className = "",
    ...props
  }, ref) => {
    return /* @__PURE__ */ (0, import_jsx_runtime25.jsxs)(
      "div",
      {
        ref,
        className: cn(
          "w-full p-4 bg-background border border-border-200 rounded-lg",
          className
        ),
        ...props,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime25.jsxs)("div", { className: "flex items-start space-x-3", children: [
            showAvatar && /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(SkeletonCircle, { width: 40, height: 40 }),
            /* @__PURE__ */ (0, import_jsx_runtime25.jsxs)("div", { className: "flex-1 space-y-2", children: [
              showTitle && /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(SkeletonText, { width: "60%", height: 20 }),
              showDescription && /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(SkeletonText, { lines, spacing: "small" })
            ] })
          ] }),
          showActions && /* @__PURE__ */ (0, import_jsx_runtime25.jsxs)("div", { className: "flex justify-end space-x-2 mt-4", children: [
            /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(SkeletonRectangle, { width: 80, height: 32 }),
            /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(SkeletonRectangle, { width: 80, height: 32 })
          ] })
        ]
      }
    );
  }
);
var SkeletonList = (0, import_react14.forwardRef)(
  ({
    items = 3,
    showAvatar = true,
    showTitle = true,
    showDescription = true,
    lines = 1,
    className = "",
    ...props
  }, ref) => {
    return /* @__PURE__ */ (0, import_jsx_runtime25.jsx)("div", { ref, className: cn("space-y-3", className), ...props, children: Array.from({ length: items }, (_, index) => /* @__PURE__ */ (0, import_jsx_runtime25.jsxs)("div", { className: "flex items-start space-x-3 p-3", children: [
      showAvatar && /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(SkeletonCircle, { width: 32, height: 32 }),
      /* @__PURE__ */ (0, import_jsx_runtime25.jsxs)("div", { className: "flex-1 space-y-2", children: [
        showTitle && /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(SkeletonText, { width: "40%", height: 16 }),
        showDescription && /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(SkeletonText, { lines, spacing: "small" })
      ] })
    ] }, index)) });
  }
);
var SkeletonTable = (0, import_react14.forwardRef)(
  ({ rows = 5, columns = 4, showHeader = true, className = "", ...props }, ref) => {
    return /* @__PURE__ */ (0, import_jsx_runtime25.jsxs)("div", { ref, className: cn("w-full", className), ...props, children: [
      showHeader && /* @__PURE__ */ (0, import_jsx_runtime25.jsx)("div", { className: "flex space-x-2 mb-3", children: Array.from({ length: columns }, (_, index) => /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(
        SkeletonText,
        {
          width: `${100 / columns}%`,
          height: 20
        },
        index
      )) }),
      /* @__PURE__ */ (0, import_jsx_runtime25.jsx)("div", { className: "space-y-2", children: Array.from({ length: rows }, (_, rowIndex) => /* @__PURE__ */ (0, import_jsx_runtime25.jsx)("div", { className: "flex space-x-2", children: Array.from({ length: columns }, (_2, colIndex) => /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(
        SkeletonText,
        {
          width: `${100 / columns}%`,
          height: 16
        },
        colIndex
      )) }, rowIndex)) })
    ] });
  }
);

// src/components/Table/TablePagination.tsx
var import_phosphor_react9 = require("phosphor-react");
var import_jsx_runtime26 = require("react/jsx-runtime");
var TablePagination = ({
  totalItems,
  currentPage,
  totalPages,
  itemsPerPage,
  itemsPerPageOptions = [10, 20, 50, 100],
  onPageChange,
  onItemsPerPageChange,
  itemLabel = "itens",
  className,
  ...props
}) => {
  const startItem = (currentPage - 1) * itemsPerPage + 1;
  const handlePrevious = () => {
    if (currentPage > 1) {
      onPageChange(currentPage - 1);
    }
  };
  const handleNext2 = () => {
    if (currentPage < totalPages) {
      onPageChange(currentPage + 1);
    }
  };
  const handleItemsPerPageChange = (e) => {
    if (onItemsPerPageChange) {
      onItemsPerPageChange(Number(e.target.value));
    }
  };
  const isFirstPage = currentPage === 1;
  const isLastPage = currentPage === totalPages;
  return /* @__PURE__ */ (0, import_jsx_runtime26.jsxs)(
    "div",
    {
      className: cn(
        "flex flex-col sm:flex-row items-center gap-3 sm:gap-4 w-full bg-background-50 rounded-xl p-4",
        "sm:justify-between",
        className
      ),
      ...props,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime26.jsxs)("span", { className: "font-normal text-xs leading-[14px] text-text-800", children: [
          startItem,
          " de ",
          totalItems,
          " ",
          itemLabel
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime26.jsxs)("div", { className: "flex flex-wrap sm:flex-nowrap items-center gap-2 sm:gap-4 justify-center sm:justify-start", children: [
          onItemsPerPageChange && /* @__PURE__ */ (0, import_jsx_runtime26.jsxs)("div", { className: "relative", children: [
            /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(
              "select",
              {
                value: itemsPerPage,
                onChange: handleItemsPerPageChange,
                className: "w-24 h-9 py-0 px-3 pr-8 bg-background border border-border-300 rounded appearance-none cursor-pointer font-normal text-sm leading-[21px] text-text-900",
                "aria-label": "Items por p\xE1gina",
                children: itemsPerPageOptions.map((option) => /* @__PURE__ */ (0, import_jsx_runtime26.jsxs)("option", { value: option, children: [
                  option,
                  " itens"
                ] }, option))
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(
              import_phosphor_react9.CaretDown,
              {
                size: 14,
                weight: "regular",
                className: "absolute right-3 top-1/2 -translate-y-1/2 text-background-600 pointer-events-none"
              }
            )
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime26.jsxs)("span", { className: "font-normal text-xs leading-[14px] text-text-950", children: [
            "P\xE1gina ",
            currentPage,
            " de ",
            totalPages
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime26.jsxs)(
            "button",
            {
              onClick: handlePrevious,
              disabled: isFirstPage,
              className: cn(
                "flex flex-row justify-center items-center py-2 px-4 gap-2 rounded-3xl transition-all",
                isFirstPage ? "opacity-50 cursor-not-allowed" : "hover:bg-primary-950/10 cursor-pointer"
              ),
              "aria-label": "P\xE1gina anterior",
              children: [
                /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(import_phosphor_react9.CaretLeft, { size: 12, weight: "bold", className: "text-primary-950" }),
                /* @__PURE__ */ (0, import_jsx_runtime26.jsx)("span", { className: "font-medium text-xs leading-[14px] text-primary-950", children: "Anterior" })
              ]
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime26.jsxs)(
            "button",
            {
              onClick: handleNext2,
              disabled: isLastPage,
              className: cn(
                "flex flex-row justify-center items-center py-2 px-4 gap-2 rounded-3xl transition-all",
                isLastPage ? "opacity-50 cursor-not-allowed" : "hover:bg-primary-950/10 cursor-pointer"
              ),
              "aria-label": "Pr\xF3xima p\xE1gina",
              children: [
                /* @__PURE__ */ (0, import_jsx_runtime26.jsx)("span", { className: "font-medium text-xs leading-[14px] text-primary-950", children: "Pr\xF3xima" }),
                /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(import_phosphor_react9.CaretRight, { size: 12, weight: "bold", className: "text-primary-950" })
              ]
            }
          )
        ] })
      ]
    }
  );
};
TablePagination.displayName = "TablePagination";
var TablePagination_default = TablePagination;

// src/components/Table/Table.tsx
var import_jsx_runtime27 = require("react/jsx-runtime");
function useTableSort(data, options = {}) {
  const { syncWithUrl = false } = options;
  const getInitialState = () => {
    if (!syncWithUrl || globalThis.window === void 0) {
      return { column: null, direction: null };
    }
    const params = new URLSearchParams(globalThis.location.search);
    const sortBy = params.get("sortBy");
    const sort = params.get("sort");
    if (sortBy && sort && (sort === "ASC" || sort === "DESC")) {
      return {
        column: sortBy,
        direction: sort.toLowerCase()
      };
    }
    return { column: null, direction: null };
  };
  const initialState3 = getInitialState();
  const [sortColumn, setSortColumn] = (0, import_react15.useState)(
    initialState3.column
  );
  const [sortDirection, setSortDirection] = (0, import_react15.useState)(
    initialState3.direction
  );
  (0, import_react15.useEffect)(() => {
    if (!syncWithUrl || globalThis.window === void 0) return;
    const url = new URL(globalThis.location.href);
    const params = url.searchParams;
    if (sortColumn && sortDirection) {
      params.set("sortBy", sortColumn);
      params.set("sort", sortDirection.toUpperCase());
    } else {
      params.delete("sortBy");
      params.delete("sort");
    }
    globalThis.history.replaceState({}, "", url.toString());
  }, [sortColumn, sortDirection, syncWithUrl]);
  const handleSort = (column) => {
    if (sortColumn === column) {
      if (sortDirection === "asc") {
        setSortDirection("desc");
      } else if (sortDirection === "desc") {
        setSortColumn(null);
        setSortDirection(null);
      }
    } else {
      setSortColumn(column);
      setSortDirection("asc");
    }
  };
  const sortedData = (0, import_react15.useMemo)(() => {
    if (!sortColumn || !sortDirection) {
      return data;
    }
    return [...data].sort((a, b) => {
      const aValue = a[sortColumn];
      const bValue = b[sortColumn];
      if (typeof aValue === "string" && typeof bValue === "string") {
        const comparison = aValue.localeCompare(bValue);
        return sortDirection === "asc" ? comparison : -comparison;
      }
      if (typeof aValue === "number" && typeof bValue === "number") {
        return sortDirection === "asc" ? aValue - bValue : bValue - aValue;
      }
      return 0;
    });
  }, [data, sortColumn, sortDirection]);
  return { sortedData, sortColumn, sortDirection, handleSort };
}
var renderHeaderElements = (children) => {
  return import_react15.Children.map(children, (child) => {
    if ((0, import_react15.isValidElement)(child) && (child.type === TableCaption || child.type === TableHeader)) {
      return child;
    }
    return null;
  });
};
var getNoSearchResultContent = (config, defaultTitle, defaultDescription) => {
  if (config.component) {
    return config.component;
  }
  if (config.image) {
    return /* @__PURE__ */ (0, import_jsx_runtime27.jsx)(
      NoSearchResult_default,
      {
        image: config.image,
        title: config.title || defaultTitle,
        description: config.description || defaultDescription
      }
    );
  }
  return /* @__PURE__ */ (0, import_jsx_runtime27.jsxs)("div", { className: "text-center", children: [
    /* @__PURE__ */ (0, import_jsx_runtime27.jsx)("p", { className: "text-text-600 text-lg font-semibold mb-2", children: config.title || defaultTitle }),
    /* @__PURE__ */ (0, import_jsx_runtime27.jsx)("p", { className: "text-text-500 text-sm", children: config.description || defaultDescription })
  ] });
};
var getEmptyStateContent = (config, defaultTitle, defaultDescription) => {
  if (config?.component) {
    return config.component;
  }
  return /* @__PURE__ */ (0, import_jsx_runtime27.jsx)(
    EmptyState_default,
    {
      image: config?.image,
      title: config?.title || defaultTitle,
      description: config?.description || defaultDescription,
      buttonText: config?.buttonText,
      buttonIcon: config?.buttonIcon,
      onButtonClick: config?.onButtonClick,
      buttonVariant: config?.buttonVariant,
      buttonAction: config?.buttonAction
    }
  );
};
var renderTableWrapper = (variant, tableRef, className, children, stateContent, tableProps) => {
  return /* @__PURE__ */ (0, import_jsx_runtime27.jsxs)(
    "div",
    {
      className: cn(
        "relative w-full overflow-x-auto",
        variant === "default" && "border border-border-200 rounded-xl"
      ),
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime27.jsx)(
          "table",
          {
            ref: tableRef,
            className: cn(
              "analytica-table w-full caption-bottom text-sm border-separate border-spacing-0",
              className
            ),
            ...tableProps,
            children: renderHeaderElements(children)
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime27.jsx)("div", { className: "py-8 flex justify-center", children: stateContent })
      ]
    }
  );
};
var Table = (0, import_react15.forwardRef)(
  ({
    variant = "default",
    className,
    children,
    showLoading = false,
    loadingState,
    showNoSearchResult = false,
    noSearchResultState,
    showEmpty = false,
    emptyState,
    ...props
  }, ref) => {
    const defaultNoSearchResultState = {
      title: "Nenhum resultado encontrado",
      description: "N\xE3o encontramos nenhum resultado com esse nome. Tente revisar a busca ou usar outra palavra-chave."
    };
    const defaultEmptyState = {
      title: "Nenhum dado dispon\xEDvel",
      description: "N\xE3o h\xE1 dados para exibir no momento."
    };
    const finalNoSearchResultState = noSearchResultState || defaultNoSearchResultState;
    const finalEmptyState = emptyState || defaultEmptyState;
    if (showLoading) {
      const loadingContent = loadingState?.component || /* @__PURE__ */ (0, import_jsx_runtime27.jsx)(SkeletonTable, { rows: 5, columns: 4, showHeader: false });
      return renderTableWrapper(
        variant,
        ref,
        className,
        children,
        loadingContent,
        props
      );
    }
    if (showNoSearchResult) {
      const noSearchContent = getNoSearchResultContent(
        finalNoSearchResultState,
        defaultNoSearchResultState.title || "",
        defaultNoSearchResultState.description || ""
      );
      return renderTableWrapper(
        variant,
        ref,
        className,
        children,
        noSearchContent,
        props
      );
    }
    if (showEmpty) {
      const emptyContent = getEmptyStateContent(
        finalEmptyState,
        defaultEmptyState.title || "Nenhum dado dispon\xEDvel",
        defaultEmptyState.description || "N\xE3o h\xE1 dados para exibir no momento."
      );
      return renderTableWrapper(
        variant,
        ref,
        className,
        children,
        emptyContent,
        props
      );
    }
    return /* @__PURE__ */ (0, import_jsx_runtime27.jsx)(
      "div",
      {
        className: cn(
          "relative w-full overflow-x-auto",
          variant === "default" && "border border-border-200 rounded-xl"
        ),
        children: /* @__PURE__ */ (0, import_jsx_runtime27.jsxs)(
          "table",
          {
            ref,
            className: cn(
              variant === "default" && "analytica-table",
              variant === "default" && "border-separate border-spacing-0",
              "w-full caption-bottom text-sm",
              className
            ),
            ...props,
            children: [
              !import_react15.Children.toArray(children).some(
                (child) => (0, import_react15.isValidElement)(child) && child.type === TableCaption
              ) && /* @__PURE__ */ (0, import_jsx_runtime27.jsx)("caption", { className: "sr-only", children: "My Table" }),
              children
            ]
          }
        )
      }
    );
  }
);
Table.displayName = "Table";
var TableHeader = (0, import_react15.forwardRef)(({ className, ...props }, ref) => /* @__PURE__ */ (0, import_jsx_runtime27.jsx)(
  "thead",
  {
    ref,
    className: cn("[&_tr:first-child]:border-0", className),
    ...props
  }
));
TableHeader.displayName = "TableHeader";
var TableBody = (0, import_react15.forwardRef)(
  ({ className, variant = "default", ...props }, ref) => /* @__PURE__ */ (0, import_jsx_runtime27.jsx)(
    "tbody",
    {
      ref,
      className: cn(
        "[&_tr:last-child]:border-border-200",
        variant === "default" && "border-t border-border-200",
        className
      ),
      ...props
    }
  )
);
TableBody.displayName = "TableBody";
var TableFooter = (0, import_react15.forwardRef)(
  ({ variant = "default", className, ...props }, ref) => /* @__PURE__ */ (0, import_jsx_runtime27.jsx)(
    "tfoot",
    {
      ref,
      className: cn(
        "bg-background-50 font-medium [&>tr]:last:border-b-0 px-6 py-3.5",
        variant === "default" && "border-t border-border-200",
        className
      ),
      ...props
    }
  )
);
TableFooter.displayName = "TableFooter";
var VARIANT_STATES_ROW = {
  default: {
    default: "border border-border-200",
    defaultBorderless: "border-b border-border-200",
    borderless: ""
  },
  selected: {
    default: "border-b-2 border-indicator-primary",
    defaultBorderless: "border-b border-indicator-primary",
    borderless: "bg-indicator-primary/10"
  },
  invalid: {
    default: "border-b-2 border-indicator-error",
    defaultBorderless: "border-b border-indicator-error",
    borderless: "bg-indicator-error/10"
  },
  disabled: {
    default: "border-b border-border-100 bg-background-50 opacity-50 cursor-not-allowed",
    defaultBorderless: "border-b border-border-100 bg-background-50 opacity-50 cursor-not-allowed",
    borderless: "bg-background-50 opacity-50 cursor-not-allowed"
  }
};
var TableRow = (0, import_react15.forwardRef)(
  ({
    variant = "default",
    state = "default",
    clickable = false,
    className,
    ...props
  }, ref) => {
    return /* @__PURE__ */ (0, import_jsx_runtime27.jsx)(
      "tr",
      {
        ref,
        className: cn(
          "transition-colors",
          state === "disabled" ? "" : "hover:bg-muted/50",
          state === "disabled" || !clickable ? "" : "cursor-pointer",
          VARIANT_STATES_ROW[state][variant],
          className
        ),
        "aria-disabled": state === "disabled",
        ...props
      }
    );
  }
);
TableRow.displayName = "TableRow";
var TableHead = (0, import_react15.forwardRef)(
  ({
    className,
    sortable = true,
    sortDirection = null,
    onSort,
    children,
    ...props
  }, ref) => {
    const handleClick = () => {
      if (sortable && onSort) {
        onSort();
      }
    };
    return /* @__PURE__ */ (0, import_jsx_runtime27.jsx)(
      "th",
      {
        ref,
        className: cn(
          "h-10 px-6 py-3.5 text-left align-middle font-bold text-base text-text-800 tracking-[0.2px] leading-none [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px] whitespace-nowrap",
          sortable && "cursor-pointer select-none hover:bg-muted/30",
          className
        ),
        onClick: handleClick,
        ...props,
        children: /* @__PURE__ */ (0, import_jsx_runtime27.jsxs)("div", { className: "flex items-center gap-2", children: [
          children,
          sortable && /* @__PURE__ */ (0, import_jsx_runtime27.jsxs)("div", { className: "flex flex-col", children: [
            sortDirection === "asc" && /* @__PURE__ */ (0, import_jsx_runtime27.jsx)(import_phosphor_react10.CaretUp, { size: 16, weight: "fill", className: "text-text-800" }),
            sortDirection === "desc" && /* @__PURE__ */ (0, import_jsx_runtime27.jsx)(import_phosphor_react10.CaretDown, { size: 16, weight: "fill", className: "text-text-800" })
          ] })
        ] })
      }
    );
  }
);
TableHead.displayName = "TableHead";
var TableCell = (0, import_react15.forwardRef)(({ className, ...props }, ref) => /* @__PURE__ */ (0, import_jsx_runtime27.jsx)(
  "td",
  {
    ref,
    className: cn(
      "p-2 align-middle [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px] text-base font-normal text-text-800 leading-[150%] tracking-normal px-6 py-3.5 whitespace-nowrap",
      className
    ),
    ...props
  }
));
TableCell.displayName = "TableCell";
var TableCaption = (0, import_react15.forwardRef)(({ className, ...props }, ref) => /* @__PURE__ */ (0, import_jsx_runtime27.jsx)(
  "caption",
  {
    ref,
    className: cn(
      "border-t border-border-200 text-sm text-text-800 px-6 py-3.5",
      className
    ),
    ...props
  }
));
TableCaption.displayName = "TableCaption";
var Table_default = Table;

// src/components/AlertManagerView/AlertsManagerView.tsx
var import_phosphor_react11 = require("phosphor-react");
var import_jsx_runtime28 = require("react/jsx-runtime");
var AlertsManagerView = ({
  alertData,
  isOpen = false,
  onClose,
  imageLink,
  defaultImage,
  currentPage = 1,
  totalPages: externalTotalPages,
  onPageChange,
  itemsPerPage = 10
}) => {
  const totalPages = externalTotalPages ?? Math.ceil(alertData.recipients.length / itemsPerPage);
  const effectiveCurrentPage = Math.min(totalPages, Math.max(1, currentPage));
  const startIndex = (effectiveCurrentPage - 1) * itemsPerPage;
  const endIndex = startIndex + itemsPerPage;
  const paginatedRecipients = alertData.recipients.slice(startIndex, endIndex);
  const handleClose = () => {
    onClose?.();
  };
  const formatDate2 = (dateInput) => {
    const date = dateInput instanceof Date ? dateInput : new Date(dateInput);
    if (Number.isNaN(date.getTime())) return String(dateInput);
    return date.toLocaleDateString("pt-BR", {
      day: "2-digit",
      month: "2-digit",
      year: "numeric"
    });
  };
  return /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(
    Modal_default,
    {
      isOpen,
      onClose: handleClose,
      title: alertData.title,
      size: "md",
      contentClassName: "p-0",
      children: /* @__PURE__ */ (0, import_jsx_runtime28.jsx)("div", { className: "flex flex-col h-[calc(100vh-8rem)] max-h-[700px]", children: /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)("div", { className: "flex-1 overflow-y-auto px-6 py-4", children: [
        /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)("div", { className: "bg-background-50 px-5 py-6 flex flex-col items-center gap-4 rounded-xl mb-4", children: [
          (imageLink || alertData.image || defaultImage) && /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(
            "img",
            {
              src: imageLink || alertData.image || defaultImage || void 0,
              alt: alertData.title || "Imagem do alerta"
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)("div", { className: "flex flex-col items-center text-center gap-3", children: [
            /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Text_default, { size: "lg", weight: "semibold", children: alertData.title || "Sem T\xEDtulo" }),
            /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Text_default, { size: "sm", weight: "normal", className: "text-text-500", children: alertData.message || "Sem mensagem" })
          ] })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Divider_default, { className: "my-4" }),
        /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)("div", { className: "flex justify-between items-center mb-4 px-2", children: [
          /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Text_default, { size: "sm", weight: "bold", className: "text-text-700", children: "Enviado em" }),
          /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Text_default, { size: "sm", weight: "medium", className: "text-text-900", children: formatDate2(alertData.sentAt) })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Divider_default, { className: "my-4" }),
        /* @__PURE__ */ (0, import_jsx_runtime28.jsx)("div", { className: "mb-4", children: /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(Table_default, { variant: "borderless", className: "table-fixed", children: [
          /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(TableHeader, { children: /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(TableRow, { variant: "borderless", children: [
            /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(TableHead, { className: "py-2 px-3.5 text-start", children: "Destinat\xE1rio" }),
            /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(TableHead, { className: "py-2 px-3.5 w-[120px] text-start", children: "Status" })
          ] }) }),
          /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(TableBody, { variant: "borderless", children: paginatedRecipients.map((recipient) => /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(TableRow, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(TableCell, { className: "py-2 px-3.5 flex flex-row gap-2 text-start truncate", children: [
              /* @__PURE__ */ (0, import_jsx_runtime28.jsx)("div", { className: "rounded-full size-6 bg-primary-100 flex items-center justify-center", children: /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(import_phosphor_react11.User, { className: "text-primary-950", size: 18 }) }),
              recipient.name
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(TableCell, { className: "py-2 px-3.5 text-center", children: /* @__PURE__ */ (0, import_jsx_runtime28.jsx)("div", { className: "flex justify-center items-center gap-1", children: recipient.status === "viewed" ? /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Badge_default, { variant: "solid", action: "success", children: "Visualizado" }) : /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Badge_default, { variant: "solid", action: "error", children: "Pendente" }) }) })
          ] }, recipient.id)) })
        ] }) }),
        totalPages > 1 && /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)("div", { className: "flex justify-end items-center gap-2 bg-background-50 border border-border-200 py-3.5 px-2 rounded-b-2xl", children: [
          /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(Text_default, { size: "sm", className: "text-text-600", children: [
            "P\xE1gina ",
            effectiveCurrentPage,
            " de ",
            totalPages
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime28.jsx)("div", { className: "flex gap-2", children: onPageChange ? /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(import_jsx_runtime28.Fragment, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(
              Button_default,
              {
                variant: "link",
                size: "extra-small",
                onClick: () => onPageChange(Math.max(1, effectiveCurrentPage - 1)),
                disabled: effectiveCurrentPage === 1,
                iconLeft: /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(import_phosphor_react11.CaretLeft, {}),
                children: "Anterior"
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(
              Button_default,
              {
                variant: "link",
                size: "extra-small",
                onClick: () => onPageChange(
                  Math.min(totalPages, effectiveCurrentPage + 1)
                ),
                disabled: effectiveCurrentPage === totalPages,
                iconRight: /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(import_phosphor_react11.CaretRight, {}),
                children: "Pr\xF3ximo"
              }
            )
          ] }) : /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(import_jsx_runtime28.Fragment, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(
              Button_default,
              {
                variant: "link",
                size: "extra-small",
                disabled: effectiveCurrentPage === 1,
                iconLeft: /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(import_phosphor_react11.CaretLeft, {}),
                children: "Anterior"
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(
              Button_default,
              {
                variant: "link",
                size: "extra-small",
                disabled: effectiveCurrentPage === totalPages,
                iconRight: /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(import_phosphor_react11.CaretRight, {}),
                children: "Pr\xF3ximo"
              }
            )
          ] }) })
        ] })
      ] }) })
    }
  );
};

// src/components/Radio/Radio.tsx
var import_react16 = require("react");
var import_zustand4 = require("zustand");
var import_jsx_runtime29 = require("react/jsx-runtime");
var SIZE_CLASSES7 = {
  small: {
    radio: "w-5 h-5",
    textSize: "sm",
    spacing: "gap-1.5",
    borderWidth: "border-2",
    dotSize: "w-2.5 h-2.5",
    labelHeight: "h-5"
  },
  medium: {
    radio: "w-6 h-6",
    textSize: "md",
    spacing: "gap-2",
    borderWidth: "border-2",
    dotSize: "w-3 h-3",
    labelHeight: "h-6"
  },
  large: {
    radio: "w-7 h-7",
    textSize: "lg",
    spacing: "gap-2",
    borderWidth: "border-2",
    dotSize: "w-3.5 h-3.5",
    labelHeight: "h-7"
  },
  extraLarge: {
    radio: "w-8 h-8",
    textSize: "xl",
    spacing: "gap-3",
    borderWidth: "border-2",
    dotSize: "w-4 h-4",
    labelHeight: "h-8"
  }
};
var BASE_RADIO_CLASSES = "rounded-full border cursor-pointer transition-all duration-200 flex items-center justify-center focus:outline-none";
var STATE_CLASSES4 = {
  default: {
    unchecked: "border-border-400 bg-background hover:border-border-500",
    checked: "border-primary-950 bg-background hover:border-primary-800"
  },
  hovered: {
    unchecked: "border-border-500 bg-background",
    checked: "border-info-700 bg-background"
  },
  focused: {
    unchecked: "border-border-400 bg-background",
    checked: "border-primary-950 bg-background"
  },
  invalid: {
    unchecked: "border-border-400 bg-background",
    checked: "border-primary-950 bg-background"
  },
  disabled: {
    unchecked: "border-border-400 bg-background cursor-not-allowed",
    checked: "border-primary-950 bg-background cursor-not-allowed"
  }
};
var DOT_CLASSES = {
  default: "bg-primary-950",
  hovered: "bg-info-700",
  focused: "bg-primary-950",
  invalid: "bg-primary-950",
  disabled: "bg-primary-950"
};
var Radio = (0, import_react16.forwardRef)(
  ({
    label,
    size = "medium",
    state = "default",
    errorMessage,
    helperText,
    className = "",
    labelClassName = "",
    checked: checkedProp,
    defaultChecked = false,
    disabled,
    id,
    name,
    value,
    onChange,
    ...props
  }, ref) => {
    const generatedId = (0, import_react16.useId)();
    const inputId = id ?? `radio-${generatedId}`;
    const inputRef = (0, import_react16.useRef)(null);
    const [internalChecked, setInternalChecked] = (0, import_react16.useState)(defaultChecked);
    const isControlled = checkedProp !== void 0;
    const checked = isControlled ? checkedProp : internalChecked;
    const handleChange = (event) => {
      const newChecked = event.target.checked;
      if (!isControlled) {
        setInternalChecked(newChecked);
      }
      if (event.target) {
        event.target.blur();
      }
      onChange?.(event);
    };
    const currentState = disabled ? "disabled" : state;
    const sizeClasses = SIZE_CLASSES7[size];
    const actualRadioSize = sizeClasses.radio;
    const actualDotSize = sizeClasses.dotSize;
    const radioVariant = checked ? "checked" : "unchecked";
    const stylingClasses = STATE_CLASSES4[currentState][radioVariant];
    const getBorderWidth = () => {
      if (currentState === "focused") {
        return "border-2";
      }
      return sizeClasses.borderWidth;
    };
    const borderWidthClass = getBorderWidth();
    const radioClasses = cn(
      BASE_RADIO_CLASSES,
      actualRadioSize,
      borderWidthClass,
      stylingClasses,
      className
    );
    const dotClasses = cn(
      actualDotSize,
      "rounded-full",
      DOT_CLASSES[currentState],
      "transition-all duration-200"
    );
    const isWrapperNeeded = currentState === "focused" || currentState === "invalid";
    const wrapperBorderColor = currentState === "focused" ? "border-indicator-info" : "border-indicator-error";
    const getTextColor = () => {
      if (currentState === "disabled") {
        return checked ? "text-text-900" : "text-text-600";
      }
      if (currentState === "focused") {
        return "text-text-900";
      }
      return checked ? "text-text-900" : "text-text-600";
    };
    const getCursorClass = () => {
      return currentState === "disabled" ? "cursor-not-allowed" : "cursor-pointer";
    };
    return /* @__PURE__ */ (0, import_jsx_runtime29.jsxs)("div", { className: "flex flex-col", children: [
      /* @__PURE__ */ (0, import_jsx_runtime29.jsxs)(
        "div",
        {
          className: cn(
            "flex flex-row items-center",
            isWrapperNeeded ? cn("p-1 border-2", wrapperBorderColor, "rounded-lg gap-1.5") : sizeClasses.spacing,
            disabled ? "opacity-40" : ""
          ),
          children: [
            /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(
              "input",
              {
                ref: (node) => {
                  inputRef.current = node;
                  if (typeof ref === "function") ref(node);
                  else if (ref) ref.current = node;
                },
                type: "radio",
                id: inputId,
                checked,
                disabled,
                name,
                value,
                onChange: handleChange,
                className: "sr-only",
                style: {
                  position: "absolute",
                  left: "-9999px",
                  visibility: "hidden"
                },
                ...props
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(
              "button",
              {
                type: "button",
                className: radioClasses,
                disabled,
                "aria-pressed": checked,
                onClick: (e) => {
                  e.preventDefault();
                  if (!disabled) {
                    if (inputRef.current) {
                      inputRef.current.click();
                      inputRef.current.blur();
                    }
                  }
                },
                onKeyDown: (e) => {
                  if ((e.key === "Enter" || e.key === " ") && !disabled) {
                    e.preventDefault();
                    if (inputRef.current) {
                      inputRef.current.click();
                      inputRef.current.blur();
                    }
                  }
                },
                children: checked && /* @__PURE__ */ (0, import_jsx_runtime29.jsx)("div", { className: dotClasses })
              }
            ),
            label && /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(
              "div",
              {
                className: cn(
                  "flex flex-row items-center",
                  sizeClasses.labelHeight,
                  "flex-1 min-w-0"
                ),
                children: /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(
                  Text_default,
                  {
                    as: "label",
                    htmlFor: inputId,
                    size: sizeClasses.textSize,
                    weight: "normal",
                    className: cn(
                      getCursorClass(),
                      "select-none leading-normal flex items-center font-roboto truncate",
                      labelClassName
                    ),
                    color: getTextColor(),
                    children: label
                  }
                )
              }
            )
          ]
        }
      ),
      errorMessage && /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(
        Text_default,
        {
          size: "sm",
          weight: "normal",
          className: "mt-1.5 truncate",
          color: "text-error-600",
          children: errorMessage
        }
      ),
      helperText && !errorMessage && /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(
        Text_default,
        {
          size: "sm",
          weight: "normal",
          className: "mt-1.5 truncate",
          color: "text-text-500",
          children: helperText
        }
      )
    ] });
  }
);
Radio.displayName = "Radio";
var createRadioGroupStore = (name, defaultValue, disabled, onValueChange) => (0, import_zustand4.create)((set, get) => ({
  value: defaultValue,
  setValue: (value) => {
    if (!get().disabled) {
      set({ value });
      get().onValueChange?.(value);
    }
  },
  onValueChange,
  disabled,
  name
}));
var useRadioGroupStore = (externalStore) => {
  if (!externalStore) {
    throw new Error("RadioGroupItem must be used within a RadioGroup");
  }
  return externalStore;
};
var injectStore2 = (children, store) => import_react16.Children.map(children, (child) => {
  if (!(0, import_react16.isValidElement)(child)) return child;
  const typedChild = child;
  const shouldInject = typedChild.type === RadioGroupItem;
  return (0, import_react16.cloneElement)(typedChild, {
    ...shouldInject ? { store } : {},
    ...typedChild.props.children ? { children: injectStore2(typedChild.props.children, store) } : {}
  });
});
var RadioGroup = (0, import_react16.forwardRef)(
  ({
    value: propValue,
    defaultValue = "",
    onValueChange,
    name: propName,
    disabled = false,
    className = "",
    children,
    ...props
  }, ref) => {
    const generatedId = (0, import_react16.useId)();
    const name = propName || `radio-group-${generatedId}`;
    const storeRef = (0, import_react16.useRef)(null);
    storeRef.current ??= createRadioGroupStore(
      name,
      defaultValue,
      disabled,
      onValueChange
    );
    const store = storeRef.current;
    const { setValue } = (0, import_zustand4.useStore)(store, (s) => s);
    (0, import_react16.useEffect)(() => {
      const currentValue = store.getState().value;
      if (currentValue && onValueChange) {
        onValueChange(currentValue);
      }
    }, []);
    (0, import_react16.useEffect)(() => {
      if (propValue !== void 0) {
        setValue(propValue);
      }
    }, [propValue, setValue]);
    (0, import_react16.useEffect)(() => {
      store.setState({ disabled });
    }, [disabled, store]);
    return /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(
      "div",
      {
        ref,
        className,
        role: "radiogroup",
        "aria-label": name,
        ...props,
        children: injectStore2(children, store)
      }
    );
  }
);
RadioGroup.displayName = "RadioGroup";
var RadioGroupItem = (0, import_react16.forwardRef)(
  ({
    value,
    store: externalStore,
    disabled: itemDisabled,
    size = "medium",
    state = "default",
    className = "",
    id,
    ...props
  }, ref) => {
    const store = useRadioGroupStore(externalStore);
    const {
      value: groupValue,
      setValue,
      disabled: groupDisabled,
      name
    } = (0, import_zustand4.useStore)(store);
    const generatedId = (0, import_react16.useId)();
    const inputId = id ?? `radio-item-${generatedId}`;
    const isChecked = groupValue === value;
    const isDisabled = groupDisabled || itemDisabled;
    const currentState = isDisabled ? "disabled" : state;
    return /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(
      Radio,
      {
        ref,
        id: inputId,
        name,
        value,
        checked: isChecked,
        disabled: isDisabled,
        size,
        state: currentState,
        className,
        onChange: (e) => {
          if (e.target.checked && !isDisabled) {
            setValue(value);
          }
        },
        ...props
      }
    );
  }
);
RadioGroupItem.displayName = "RadioGroupItem";
var Radio_default = Radio;

// src/components/Toast/Toast.tsx
var import_phosphor_react12 = require("phosphor-react");
var import_jsx_runtime30 = require("react/jsx-runtime");
var VARIANT_ACTION_CLASSES4 = {
  solid: {
    warning: "bg-warning text-warning-600 border-none focus-visible:outline-none",
    success: "bg-success text-success-800 border-none focus-visible:outline-none",
    info: "bg-info text-info-600 border-none focus-visible:outline-none"
  },
  outlined: {
    warning: "bg-warning text-warning-600 border border-warning-300 focus-visible:outline-none",
    success: "bg-success text-success-800 border border-success-200 focus-visible:outline-none",
    info: "bg-info text-info-600 border border-info-600 focus-visible:outline-none"
  }
};
var iconMap = {
  success: import_phosphor_react12.CheckCircle,
  info: import_phosphor_react12.Info,
  warning: import_phosphor_react12.WarningCircle
};
var Toast = ({
  variant = "outlined",
  action = "success",
  className = "",
  onClose,
  title,
  description,
  position = "default",
  ...props
}) => {
  const variantClasses = VARIANT_ACTION_CLASSES4[variant][action];
  const positionClasses = {
    "top-left": "fixed top-4 left-4",
    "top-center": "fixed top-4 left-1/2 transform -translate-x-1/2",
    "top-right": "fixed top-4 right-4",
    "bottom-left": "fixed bottom-4 left-4",
    "bottom-center": "fixed bottom-4 left-1/2 transform -translate-x-1/2",
    "bottom-right": "fixed bottom-4 right-4",
    default: ""
  };
  const IconAction = iconMap[action] || iconMap["success"];
  const baseClasses = "max-w-[390px] w-full flex flex-row items-start justify-between shadow-lg rounded-lg border p-4 gap-6 group";
  return /* @__PURE__ */ (0, import_jsx_runtime30.jsxs)(
    "div",
    {
      role: "alert",
      "aria-live": "assertive",
      "aria-atomic": "true",
      className: cn(
        baseClasses,
        positionClasses[position],
        variantClasses,
        className
      ),
      ...props,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime30.jsxs)("div", { className: "flex flex-row items-start gap-3", children: [
          /* @__PURE__ */ (0, import_jsx_runtime30.jsx)("span", { className: "mt-1", "data-testid": `toast-icon-${action}`, children: /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(IconAction, {}) }),
          /* @__PURE__ */ (0, import_jsx_runtime30.jsxs)("div", { className: "flex flex-col items-start justify-start", children: [
            /* @__PURE__ */ (0, import_jsx_runtime30.jsx)("p", { className: "font-semibold text-md", children: title }),
            description && /* @__PURE__ */ (0, import_jsx_runtime30.jsx)("p", { className: "text-md text-text-900", children: description })
          ] })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(
          "button",
          {
            onClick: onClose,
            "aria-label": "Dismiss notification",
            className: "text-background-500 cursor-pointer opacity-0 group-hover:opacity-100 transition-opacity",
            children: /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(import_phosphor_react12.X, {})
          }
        )
      ]
    }
  );
};
var Toast_default = Toast;

// src/components/Toast/utils/ToastStore.ts
var import_zustand5 = require("zustand");
var useToastStore = (0, import_zustand5.create)((set) => ({
  toasts: [],
  addToast: (toast) => {
    const id = crypto.randomUUID();
    set((state) => ({
      toasts: [...state.toasts, { id, ...toast }]
    }));
  },
  removeToast: (id) => {
    set((state) => ({
      toasts: state.toasts.filter((t) => t.id !== id)
    }));
  }
}));
var ToastStore_default = useToastStore;

// src/components/Toast/utils/Toaster.tsx
var import_jsx_runtime31 = require("react/jsx-runtime");
var Toaster = () => {
  const toasts = ToastStore_default((state) => state.toasts);
  const removeToast = ToastStore_default((state) => state.removeToast);
  return /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(import_jsx_runtime31.Fragment, { children: toasts.map((toast) => /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(
    Toast_default,
    {
      title: toast.title,
      description: toast.description,
      variant: toast.variant,
      action: toast.action,
      position: toast.position,
      onClose: () => removeToast(toast.id)
    },
    toast.id
  )) });
};
var useToast = () => {
  const addToast = ToastStore_default((state) => state.addToast);
  const removeToast = ToastStore_default((state) => state.removeToast);
  return { addToast, removeToast };
};
var Toaster_default = Toaster;

// src/components/Search/Search.tsx
var import_phosphor_react15 = require("phosphor-react");
var import_react20 = require("react");

// src/components/DropdownMenu/DropdownMenu.tsx
var import_phosphor_react14 = require("phosphor-react");
var import_react19 = require("react");
var import_react_dom = require("react-dom");
var import_zustand7 = require("zustand");

// src/components/ThemeToggle/ThemeToggle.tsx
var import_phosphor_react13 = require("phosphor-react");
var import_react18 = require("react");

// src/hooks/useTheme.ts
var import_react17 = require("react");

// src/store/themeStore.ts
var import_zustand6 = require("zustand");
var import_middleware2 = require("zustand/middleware");
var applyThemeToDOM = (mode) => {
  const htmlElement = document.documentElement;
  const originalTheme = htmlElement.getAttribute("data-original-theme");
  if (mode === "dark") {
    htmlElement.setAttribute("data-theme", "dark");
    return true;
  } else if (mode === "light") {
    if (originalTheme) {
      htmlElement.setAttribute("data-theme", originalTheme);
    }
    return false;
  } else if (mode === "system") {
    const isSystemDark = window.matchMedia(
      "(prefers-color-scheme: dark)"
    ).matches;
    if (isSystemDark) {
      htmlElement.setAttribute("data-theme", "dark");
      return true;
    } else if (originalTheme) {
      htmlElement.setAttribute("data-theme", originalTheme);
      return false;
    }
  }
  return false;
};
var saveOriginalTheme = () => {
  const htmlElement = document.documentElement;
  const currentTheme = htmlElement.getAttribute("data-theme");
  if (currentTheme && !htmlElement.getAttribute("data-original-theme")) {
    htmlElement.setAttribute("data-original-theme", currentTheme);
  }
};
var useThemeStore = (0, import_zustand6.create)()(
  (0, import_middleware2.devtools)(
    (0, import_middleware2.persist)(
      (set, get) => ({
        // Initial state
        themeMode: "system",
        isDark: false,
        // Actions
        applyTheme: (mode) => {
          const isDark = applyThemeToDOM(mode);
          set({ isDark });
        },
        toggleTheme: () => {
          const { themeMode, applyTheme } = get();
          let newMode;
          if (themeMode === "light") {
            newMode = "dark";
          } else if (themeMode === "dark") {
            newMode = "light";
          } else {
            newMode = "dark";
          }
          set({ themeMode: newMode });
          applyTheme(newMode);
        },
        setTheme: (mode) => {
          const { applyTheme } = get();
          set({ themeMode: mode });
          applyTheme(mode);
        },
        initializeTheme: () => {
          const { themeMode, applyTheme } = get();
          saveOriginalTheme();
          applyTheme(themeMode);
        },
        handleSystemThemeChange: () => {
          const { themeMode, applyTheme } = get();
          if (themeMode === "system") {
            applyTheme("system");
          }
        }
      }),
      {
        name: "theme-store",
        // Nome da chave no localStorage
        partialize: (state) => ({
          themeMode: state.themeMode
        })
        // Só persiste o themeMode, não o isDark
      }
    ),
    {
      name: "theme-store"
    }
  )
);

// src/hooks/useTheme.ts
var useTheme = () => {
  const {
    themeMode,
    isDark,
    toggleTheme,
    setTheme,
    initializeTheme,
    handleSystemThemeChange
  } = useThemeStore();
  (0, import_react17.useEffect)(() => {
    initializeTheme();
    const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");
    mediaQuery.addEventListener("change", handleSystemThemeChange);
    return () => {
      mediaQuery.removeEventListener("change", handleSystemThemeChange);
    };
  }, [initializeTheme, handleSystemThemeChange]);
  return {
    themeMode,
    isDark,
    toggleTheme,
    setTheme
  };
};

// src/components/ThemeToggle/ThemeToggle.tsx
var import_jsx_runtime32 = require("react/jsx-runtime");
var ThemeToggle = ({
  variant = "default",
  onToggle
}) => {
  const { themeMode, setTheme } = useTheme();
  const [tempTheme, setTempTheme] = (0, import_react18.useState)(themeMode);
  (0, import_react18.useEffect)(() => {
    setTempTheme(themeMode);
  }, [themeMode]);
  const problemTypes = [
    {
      id: "light",
      title: "Claro",
      icon: /* @__PURE__ */ (0, import_jsx_runtime32.jsx)(import_phosphor_react13.Sun, { size: 24 })
    },
    {
      id: "dark",
      title: "Escuro",
      icon: /* @__PURE__ */ (0, import_jsx_runtime32.jsx)(import_phosphor_react13.Moon, { size: 24 })
    },
    {
      id: "system",
      title: "Sistema",
      icon: /* @__PURE__ */ (0, import_jsx_runtime32.jsx)(
        "svg",
        {
          width: "25",
          height: "25",
          viewBox: "0 0 25 25",
          fill: "none",
          xmlns: "http://www.w3.org/2000/svg",
          children: /* @__PURE__ */ (0, import_jsx_runtime32.jsx)(
            "path",
            {
              d: "M12.5 2.75C15.085 2.75276 17.5637 3.78054 19.3916 5.6084C21.2195 7.43628 22.2473 9.915 22.25 12.5C22.25 14.4284 21.6778 16.3136 20.6064 17.917C19.5352 19.5201 18.0128 20.7699 16.2314 21.5078C14.4499 22.2458 12.489 22.4387 10.5977 22.0625C8.70642 21.6863 6.96899 20.758 5.60547 19.3945C4.24197 18.031 3.31374 16.2936 2.9375 14.4023C2.56129 12.511 2.75423 10.5501 3.49219 8.76855C4.23012 6.98718 5.47982 5.46483 7.08301 4.39355C8.68639 3.32221 10.5716 2.75 12.5 2.75ZM11.75 4.28516C9.70145 4.47452 7.7973 5.42115 6.41016 6.94043C5.02299 8.4599 4.25247 10.4426 4.25 12.5C4.25247 14.5574 5.02299 16.5401 6.41016 18.0596C7.7973 19.5789 9.70145 20.5255 11.75 20.7148V4.28516Z",
              fill: "#525252"
            }
          )
        }
      )
    }
  ];
  const handleThemeSelect = (selectedTheme) => {
    if (variant === "with-save") {
      setTempTheme(selectedTheme);
    } else {
      setTheme(selectedTheme);
    }
    if (onToggle) {
      onToggle(selectedTheme);
    }
  };
  const currentTheme = variant === "with-save" ? tempTheme : themeMode;
  return /* @__PURE__ */ (0, import_jsx_runtime32.jsx)("div", { className: "flex flex-row gap-2 sm:gap-4 py-2", children: problemTypes.map((type) => /* @__PURE__ */ (0, import_jsx_runtime32.jsx)(
    SelectionButton_default,
    {
      icon: type.icon,
      label: type.title,
      selected: currentTheme === type.id,
      onClick: () => handleThemeSelect(type.id),
      className: "w-full p-2 sm:p-4"
    },
    type.id
  )) });
};

// src/components/DropdownMenu/DropdownMenu.tsx
var import_jsx_runtime33 = require("react/jsx-runtime");
function createDropdownStore() {
  return (0, import_zustand7.create)((set) => ({
    open: false,
    setOpen: (open) => set({ open })
  }));
}
var useDropdownStore = (externalStore) => {
  if (!externalStore) {
    throw new Error(
      "Component must be used within a DropdownMenu (store is missing)"
    );
  }
  return externalStore;
};
var injectStore3 = (children, store) => {
  return import_react19.Children.map(children, (child) => {
    if ((0, import_react19.isValidElement)(child)) {
      const typedChild = child;
      const displayName = typedChild.type.displayName;
      const allowed = [
        "DropdownMenuTrigger",
        "DropdownContent",
        "DropdownMenuContent",
        "DropdownMenuSeparator",
        "DropdownMenuItem",
        "MenuLabel",
        "ProfileMenuTrigger",
        "ProfileMenuHeader",
        "ProfileMenuFooter",
        "ProfileToggleTheme"
      ];
      let newProps = {};
      if (allowed.includes(displayName)) {
        newProps.store = store;
      }
      if (typedChild.props.children) {
        newProps.children = injectStore3(typedChild.props.children, store);
      }
      return (0, import_react19.cloneElement)(typedChild, newProps);
    }
    return child;
  });
};
var DropdownMenu = ({
  children,
  open: propOpen,
  onOpenChange
}) => {
  const storeRef = (0, import_react19.useRef)(null);
  storeRef.current ??= createDropdownStore();
  const store = storeRef.current;
  const { open, setOpen: storeSetOpen } = (0, import_zustand7.useStore)(store, (s) => s);
  const setOpen = (newOpen) => {
    storeSetOpen(newOpen);
  };
  const menuRef = (0, import_react19.useRef)(null);
  const handleArrowDownOrArrowUp = (event) => {
    const menuContent = menuRef.current?.querySelector('[role="menu"]');
    if (menuContent) {
      event.preventDefault();
      const items = Array.from(
        menuContent.querySelectorAll(
          '[role="menuitem"]:not([aria-disabled="true"])'
        )
      ).filter((el) => el instanceof HTMLElement);
      if (items.length === 0) return;
      const focusedItem = document.activeElement;
      const currentIndex = items.indexOf(focusedItem);
      let nextIndex;
      if (event.key === "ArrowDown") {
        nextIndex = currentIndex === -1 ? 0 : (currentIndex + 1) % items.length;
      } else {
        nextIndex = currentIndex === -1 ? items.length - 1 : (currentIndex - 1 + items.length) % items.length;
      }
      items[nextIndex]?.focus();
    }
  };
  const handleDownkey = (event) => {
    if (event.key === "Escape") {
      setOpen(false);
    } else if (event.key === "ArrowDown" || event.key === "ArrowUp") {
      handleArrowDownOrArrowUp(event);
    }
  };
  const handleClickOutside = (event) => {
    const target = event.target;
    if (menuRef.current?.contains(target)) {
      return;
    }
    if (target instanceof Element && target.closest('[data-dropdown-content="true"]')) {
      return;
    }
    setOpen(false);
  };
  (0, import_react19.useEffect)(() => {
    if (open) {
      document.addEventListener("pointerdown", handleClickOutside);
      document.addEventListener("keydown", handleDownkey);
    }
    return () => {
      document.removeEventListener("pointerdown", handleClickOutside);
      document.removeEventListener("keydown", handleDownkey);
    };
  }, [open]);
  (0, import_react19.useEffect)(() => {
    onOpenChange?.(open);
  }, [open, onOpenChange]);
  (0, import_react19.useEffect)(() => {
    if (propOpen !== void 0) {
      setOpen(propOpen);
    }
  }, [propOpen]);
  return /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("div", { className: "relative", ref: menuRef, children: injectStore3(children, store) });
};
var DropdownMenuTrigger = (0, import_react19.forwardRef)(({ className, children, onClick, store: externalStore, ...props }, ref) => {
  const store = useDropdownStore(externalStore);
  const open = (0, import_zustand7.useStore)(store, (s) => s.open);
  const toggleOpen = () => store.setState({ open: !open });
  return /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
    "button",
    {
      ref,
      type: "button",
      onClick: (e) => {
        e.stopPropagation();
        toggleOpen();
        onClick?.(e);
      },
      "aria-expanded": open,
      className: cn(
        "appearance-none bg-transparent border-none p-0",
        className
      ),
      ...props,
      children
    }
  );
});
DropdownMenuTrigger.displayName = "DropdownMenuTrigger";
var ITEM_SIZE_CLASSES = {
  small: "text-sm",
  medium: "text-md"
};
var SIDE_CLASSES = {
  top: "bottom-full",
  right: "top-full",
  bottom: "top-full",
  left: "top-full"
};
var ALIGN_CLASSES = {
  start: "left-0",
  center: "left-1/2 -translate-x-1/2",
  end: "right-0"
};
var MENUCONTENT_VARIANT_CLASSES = {
  menu: "p-1",
  profile: "p-6"
};
var MenuLabel = (0, import_react19.forwardRef)(({ className, inset, store: _store, ...props }, ref) => {
  return /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
    "div",
    {
      ref,
      className: cn("text-sm w-full", inset ? "pl-8" : "", className),
      ...props
    }
  );
});
MenuLabel.displayName = "MenuLabel";
var DropdownMenuContent = (0, import_react19.forwardRef)(
  ({
    className,
    align = "start",
    side = "bottom",
    variant = "menu",
    sideOffset = 4,
    children,
    store: externalStore,
    portal = false,
    triggerRef,
    ...props
  }, ref) => {
    const store = useDropdownStore(externalStore);
    const open = (0, import_zustand7.useStore)(store, (s) => s.open);
    const [isVisible, setIsVisible] = (0, import_react19.useState)(open);
    const [portalPosition, setPortalPosition] = (0, import_react19.useState)({ top: 0, left: 0 });
    const contentRef = (0, import_react19.useRef)(null);
    (0, import_react19.useEffect)(() => {
      if (open) {
        setIsVisible(true);
      } else {
        const timer = setTimeout(() => setIsVisible(false), 200);
        return () => clearTimeout(timer);
      }
    }, [open]);
    (0, import_react19.useLayoutEffect)(() => {
      if (portal && open && triggerRef?.current) {
        const rect = triggerRef.current.getBoundingClientRect();
        let top = rect.bottom + sideOffset;
        let left = rect.left;
        if (side === "left") {
          left = rect.left - sideOffset;
          top = rect.top;
        } else if (side === "right") {
          left = rect.right + sideOffset;
          top = rect.top;
        } else {
          if (align === "end") {
            left = rect.right;
          } else if (align === "center") {
            left = rect.left + rect.width / 2;
          }
          if (side === "top") {
            top = rect.top - sideOffset;
          }
        }
        setPortalPosition({ top, left });
      }
    }, [portal, open, triggerRef, align, side, sideOffset]);
    if (!isVisible) return null;
    const getPositionClasses = () => {
      if (portal) {
        return "fixed";
      }
      const vertical = SIDE_CLASSES[side];
      const horizontal = ALIGN_CLASSES[align];
      return `absolute ${vertical} ${horizontal}`;
    };
    const getPortalAlignStyle = () => {
      if (!portal) return {};
      const baseStyle = {
        top: portalPosition.top
      };
      if (align === "end") {
        baseStyle.right = window.innerWidth - portalPosition.left;
      } else if (align === "center") {
        baseStyle.left = portalPosition.left;
        baseStyle.transform = "translateX(-50%)";
      } else {
        baseStyle.left = portalPosition.left;
      }
      return baseStyle;
    };
    const variantClasses = MENUCONTENT_VARIANT_CLASSES[variant];
    const content = /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
      "div",
      {
        ref: portal ? contentRef : ref,
        role: "menu",
        "data-dropdown-content": "true",
        className: `
        bg-background z-50 min-w-[210px] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md border-border-100
        ${open ? "animate-in fade-in-0 zoom-in-95" : "animate-out fade-out-0 zoom-out-95"}
        ${getPositionClasses()}
        ${variantClasses}
        ${className}
      `,
        style: {
          ...portal ? getPortalAlignStyle() : {
            marginTop: side === "bottom" ? sideOffset : void 0,
            marginBottom: side === "top" ? sideOffset : void 0,
            marginLeft: side === "right" ? sideOffset : void 0,
            marginRight: side === "left" ? sideOffset : void 0
          }
        },
        ...props,
        children
      }
    );
    if (portal && typeof document !== "undefined") {
      return (0, import_react_dom.createPortal)(content, document.body);
    }
    return content;
  }
);
DropdownMenuContent.displayName = "DropdownMenuContent";
var DropdownMenuItem = (0, import_react19.forwardRef)(
  ({
    className,
    size = "small",
    children,
    iconRight,
    iconLeft,
    disabled = false,
    onClick,
    variant = "menu",
    store: externalStore,
    preventClose = false,
    ...props
  }, ref) => {
    const store = useDropdownStore(externalStore);
    const setOpen = (0, import_zustand7.useStore)(store, (s) => s.setOpen);
    const sizeClasses = ITEM_SIZE_CLASSES[size];
    const handleClick = (e) => {
      if (disabled) {
        e.preventDefault();
        e.stopPropagation();
        return;
      }
      if (e.type === "click") {
        onClick?.(e);
      } else if (e.type === "keydown") {
        if (e.key === "Enter" || e.key === " ") {
          onClick?.(e);
        }
        props.onKeyDown?.(e);
      }
      if (!preventClose) {
        setOpen(false);
      }
    };
    const getVariantClasses = () => {
      if (variant === "profile") {
        return "relative flex flex-row justify-between select-none items-center gap-2 rounded-sm p-4 text-sm outline-none transition-colors [&>svg]:size-6 [&>svg]:shrink-0";
      }
      return "relative flex select-none items-center gap-2 rounded-sm p-3 text-sm outline-none transition-colors [&>svg]:size-4 [&>svg]:shrink-0";
    };
    const getVariantProps = () => {
      return variant === "profile" ? { "data-variant": "profile" } : {};
    };
    return /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)(
      "div",
      {
        ref,
        role: "menuitem",
        ...getVariantProps(),
        "aria-disabled": disabled,
        className: `
          focus-visible:bg-background-50
           ${getVariantClasses()}
          ${sizeClasses}
          ${className}
          ${disabled ? "cursor-not-allowed text-text-400" : "cursor-pointer hover:bg-background-50 text-text-700 focus:bg-accent focus:text-accent-foreground hover:bg-accent hover:text-accent-foreground"}
        `,
        onClick: handleClick,
        onKeyDown: (e) => {
          if (e.key === "Enter" || e.key === " ") {
            e.preventDefault();
            e.stopPropagation();
            handleClick(e);
          }
        },
        tabIndex: disabled ? -1 : 0,
        ...props,
        children: [
          iconLeft,
          /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("div", { className: "w-full", children }),
          iconRight
        ]
      }
    );
  }
);
DropdownMenuItem.displayName = "DropdownMenuItem";
var DropdownMenuSeparator = (0, import_react19.forwardRef)(({ className, store: _store, ...props }, ref) => /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
  "div",
  {
    ref,
    className: cn("my-1 h-px bg-border-200", className),
    ...props
  }
));
DropdownMenuSeparator.displayName = "DropdownMenuSeparator";
var ProfileMenuTrigger = (0, import_react19.forwardRef)(({ className, onClick, store: externalStore, ...props }, ref) => {
  const store = useDropdownStore(externalStore);
  const open = (0, import_zustand7.useStore)(store, (s) => s.open);
  const toggleOpen = () => store.setState({ open: !open });
  return /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
    "button",
    {
      ref,
      className: cn(
        "rounded-lg size-10 bg-primary-50 flex items-center justify-center cursor-pointer",
        className
      ),
      onClick: (e) => {
        e.stopPropagation();
        toggleOpen();
        onClick?.(e);
      },
      "aria-expanded": open,
      ...props,
      children: /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("span", { className: "size-6 rounded-full bg-primary-100 flex items-center justify-center", children: /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(import_phosphor_react14.User, { className: "text-primary-950", size: 18 }) })
    }
  );
});
ProfileMenuTrigger.displayName = "ProfileMenuTrigger";
var ProfileMenuHeader = (0, import_react19.forwardRef)(({ className, name, email, photoUrl, store: _store, ...props }, ref) => {
  return /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)(
    "div",
    {
      ref,
      "data-component": "ProfileMenuHeader",
      className: cn(
        "flex flex-row gap-4 items-center min-w-[280px]",
        className
      ),
      ...props,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("span", { className: "w-16 h-16 bg-primary-100 rounded-full flex items-center justify-center overflow-hidden flex-shrink-0", children: photoUrl ? /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
          "img",
          {
            src: photoUrl,
            alt: "Foto de perfil",
            className: "w-full h-full object-cover"
          }
        ) : /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(import_phosphor_react14.User, { size: 34, className: "text-primary-800" }) }),
        /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)("div", { className: "flex flex-col min-w-0", children: [
          /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
            Text_default,
            {
              size: "xl",
              weight: "bold",
              color: "text-text-950",
              className: "truncate",
              children: name
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(Text_default, { size: "md", color: "text-text-600", className: "truncate", children: email })
        ] })
      ]
    }
  );
});
ProfileMenuHeader.displayName = "ProfileMenuHeader";
var ProfileMenuInfo = (0, import_react19.forwardRef)(
  ({
    className,
    schoolName,
    classYearName,
    schoolYearName,
    store: _store,
    ...props
  }, ref) => {
    return /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)(
      "div",
      {
        ref,
        "data-component": "ProfileMenuInfo",
        className: cn("flex flex-row gap-4 items-center", className),
        ...props,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("span", { className: "w-16 h-16" }),
          /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)("div", { className: "flex flex-col ", children: [
            /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(Text_default, { size: "md", color: "text-text-600", children: schoolName }),
            /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)("span", { className: "flex flex-row items-center gap-2", children: [
              /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(Text_default, { size: "md", color: "text-text-600", children: classYearName }),
              /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("p", { className: "text-text-600 text-xs align-middle", children: "\u25CF" }),
              /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(Text_default, { size: "md", color: "text-text-600", children: schoolYearName })
            ] })
          ] })
        ]
      }
    );
  }
);
ProfileMenuInfo.displayName = "ProfileMenuInfo";
var ProfileToggleTheme = ({
  store: externalStore,
  ...props
}) => {
  const { themeMode, setTheme } = useTheme();
  const [modalThemeToggle, setModalThemeToggle] = (0, import_react19.useState)(false);
  const [selectedTheme, setSelectedTheme] = (0, import_react19.useState)(themeMode);
  const internalStoreRef = (0, import_react19.useRef)(null);
  internalStoreRef.current ??= createDropdownStore();
  const store = externalStore ?? internalStoreRef.current;
  const setOpen = (0, import_zustand7.useStore)(store, (s) => s.setOpen);
  const handleClick = (e) => {
    e.preventDefault();
    e.stopPropagation();
    setModalThemeToggle(true);
  };
  const handleSave = () => {
    setTheme(selectedTheme);
    setModalThemeToggle(false);
    setOpen(false);
  };
  const handleCancel = () => {
    setSelectedTheme(themeMode);
    setModalThemeToggle(false);
    setOpen(false);
  };
  return /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)(import_jsx_runtime33.Fragment, { children: [
    /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
      DropdownMenuItem,
      {
        variant: "profile",
        preventClose: true,
        store,
        iconLeft: /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
          "svg",
          {
            width: "24",
            height: "24",
            viewBox: "0 0 25 25",
            fill: "none",
            xmlns: "http://www.w3.org/2000/svg",
            children: /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
              "path",
              {
                d: "M12.5 2.75C15.085 2.75276 17.5637 3.78054 19.3916 5.6084C21.2195 7.43628 22.2473 9.915 22.25 12.5C22.25 14.4284 21.6778 16.3136 20.6064 17.917C19.5352 19.5201 18.0128 20.7699 16.2314 21.5078C14.4499 22.2458 12.489 22.4387 10.5977 22.0625C8.70642 21.6863 6.96899 20.758 5.60547 19.3945C4.24197 18.031 3.31374 16.2936 2.9375 14.4023C2.56129 12.511 2.75423 10.5501 3.49219 8.76855C4.23012 6.98718 5.47982 5.46483 7.08301 4.39355C8.68639 3.32221 10.5716 2.75 12.5 2.75ZM11.75 4.28516C9.70145 4.47452 7.7973 5.42115 6.41016 6.94043C5.02299 8.4599 4.25247 10.4426 4.25 12.5C4.25247 14.5574 5.02299 16.5401 6.41016 18.0596C7.7973 19.5789 9.70145 20.5255 11.75 20.7148V4.28516Z",
                fill: "currentColor"
              }
            )
          }
        ),
        iconRight: /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(import_phosphor_react14.CaretRight, {}),
        onClick: handleClick,
        onKeyDown: (e) => {
          if (e.key === "Enter" || e.key === " ") {
            e.preventDefault();
            e.stopPropagation();
            setModalThemeToggle(true);
          }
        },
        ...props,
        children: /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(Text_default, { size: "md", color: "text-text-700", children: "Apar\xEAncia" })
      }
    ),
    /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
      Modal_default,
      {
        isOpen: modalThemeToggle,
        onClose: handleCancel,
        title: "Apar\xEAncia",
        size: "md",
        footer: /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)("div", { className: "flex gap-3", children: [
          /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(Button_default, { variant: "outline", onClick: handleCancel, children: "Cancelar" }),
          /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(Button_default, { variant: "solid", onClick: handleSave, children: "Salvar" })
        ] }),
        children: /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)("div", { className: "flex flex-col", children: [
          /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("p", { className: "text-sm text-text-500", children: "Escolha o tema:" }),
          /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(ThemeToggle, { variant: "with-save", onToggle: setSelectedTheme })
        ] })
      }
    )
  ] });
};
ProfileToggleTheme.displayName = "ProfileToggleTheme";
var ProfileMenuSection = (0, import_react19.forwardRef)(({ className, children, store: _store, ...props }, ref) => {
  return /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("div", { ref, className: cn("flex flex-col p-2", className), ...props, children });
});
ProfileMenuSection.displayName = "ProfileMenuSection";
var ProfileMenuFooter = ({
  className,
  disabled = false,
  onClick,
  store: externalStore,
  ...props
}) => {
  const store = useDropdownStore(externalStore);
  const setOpen = (0, import_zustand7.useStore)(store, (s) => s.setOpen);
  return /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)(
    Button_default,
    {
      variant: "outline",
      className: cn("w-full", className),
      disabled,
      onClick: (e) => {
        setOpen(false);
        onClick?.(e);
      },
      ...props,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("span", { className: "mr-2 flex items-center", children: /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(import_phosphor_react14.SignOut, { className: "text-inherit" }) }),
        /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(Text_default, { color: "inherit", children: "Sair" })
      ]
    }
  );
};
ProfileMenuFooter.displayName = "ProfileMenuFooter";
var DropdownMenu_default = DropdownMenu;

// src/components/Search/Search.tsx
var import_jsx_runtime34 = require("react/jsx-runtime");
var filterOptions = (options, query) => {
  if (!query || query.length < 1) return [];
  return options.filter(
    (option) => option.toLowerCase().includes(query.toLowerCase())
  );
};
var updateInputValue = (value, ref, onChange) => {
  if (!onChange) return;
  if (ref && "current" in ref && ref.current) {
    ref.current.value = value;
    const event = new Event("input", { bubbles: true });
    Object.defineProperty(event, "target", {
      writable: false,
      value: ref.current
    });
    onChange(event);
  } else {
    const event = {
      target: { value },
      currentTarget: { value }
    };
    onChange(event);
  }
};
var Search = (0, import_react20.forwardRef)(
  ({
    options = [],
    onSelect,
    onSearch,
    showDropdown: controlledShowDropdown,
    onDropdownChange,
    dropdownMaxHeight = 240,
    noResultsText = "Nenhum resultado encontrado",
    className = "",
    containerClassName = "",
    disabled,
    readOnly,
    id,
    onClear,
    value,
    onChange,
    placeholder = "Buscar...",
    onKeyDown: userOnKeyDown,
    ...props
  }, ref) => {
    const [dropdownOpen, setDropdownOpen] = (0, import_react20.useState)(false);
    const [forceClose, setForceClose] = (0, import_react20.useState)(false);
    const justSelectedRef = (0, import_react20.useRef)(false);
    const dropdownStore = (0, import_react20.useRef)(createDropdownStore()).current;
    const dropdownRef = (0, import_react20.useRef)(null);
    const inputElRef = (0, import_react20.useRef)(null);
    const filteredOptions = (0, import_react20.useMemo)(() => {
      if (!options.length) {
        return [];
      }
      const filtered = filterOptions(options, value || "");
      return filtered;
    }, [options, value]);
    const showDropdown = !forceClose && (controlledShowDropdown ?? (dropdownOpen && value && String(value).length > 0));
    const setOpenAndNotify = (open) => {
      setDropdownOpen(open);
      dropdownStore.setState({ open });
      onDropdownChange?.(open);
    };
    (0, import_react20.useEffect)(() => {
      if (justSelectedRef.current) {
        justSelectedRef.current = false;
        return;
      }
      if (forceClose) {
        setOpenAndNotify(false);
        return;
      }
      const shouldShow = Boolean(value && String(value).length > 0);
      setOpenAndNotify(shouldShow);
    }, [value, forceClose, onDropdownChange, dropdownStore]);
    const handleSelectOption = (option) => {
      justSelectedRef.current = true;
      setForceClose(true);
      onSelect?.(option);
      setOpenAndNotify(false);
      updateInputValue(option, ref, onChange);
    };
    (0, import_react20.useEffect)(() => {
      const handleClickOutside = (event) => {
        if (dropdownRef.current && !dropdownRef.current.contains(event.target)) {
          setOpenAndNotify(false);
        }
      };
      if (showDropdown) {
        document.addEventListener("mousedown", handleClickOutside);
      }
      return () => {
        document.removeEventListener("mousedown", handleClickOutside);
      };
    }, [showDropdown, dropdownStore, onDropdownChange]);
    const generatedId = (0, import_react20.useId)();
    const inputId = id ?? `search-${generatedId}`;
    const dropdownId = `${inputId}-dropdown`;
    const handleClear = () => {
      if (onClear) {
        onClear();
      } else {
        updateInputValue("", ref, onChange);
      }
    };
    const handleClearClick = (e) => {
      e.preventDefault();
      e.stopPropagation();
      handleClear();
    };
    const handleSearchIconClick = (e) => {
      e.preventDefault();
      e.stopPropagation();
      setTimeout(() => {
        inputElRef.current?.focus();
      }, 0);
    };
    const handleInputChange = (e) => {
      setForceClose(false);
      onChange?.(e);
      onSearch?.(e.target.value);
    };
    const handleKeyDown = (e) => {
      userOnKeyDown?.(e);
      if (e.defaultPrevented) return;
      if (e.key === "Enter") {
        e.preventDefault();
        if (showDropdown && filteredOptions.length > 0) {
          handleSelectOption(filteredOptions[0]);
        } else if (value) {
          onSearch?.(String(value));
          setForceClose(true);
          setOpenAndNotify(false);
        }
      }
    };
    const getInputStateClasses = (disabled2, readOnly2) => {
      if (disabled2) return "cursor-not-allowed opacity-40";
      if (readOnly2) return "cursor-default focus:outline-none !text-text-900";
      return "hover:border-border-400";
    };
    const hasValue = String(value ?? "").length > 0;
    const showClearButton = hasValue && !disabled && !readOnly;
    const showSearchIcon = !hasValue && !disabled && !readOnly;
    return /* @__PURE__ */ (0, import_jsx_runtime34.jsxs)(
      "div",
      {
        ref: dropdownRef,
        className: `w-full max-w-lg md:w-[488px] ${containerClassName}`,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime34.jsxs)("div", { className: "relative flex items-center", children: [
            /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(
              "input",
              {
                ref: (node) => {
                  if (ref) {
                    if (typeof ref === "function") ref(node);
                    else
                      ref.current = node;
                  }
                  inputElRef.current = node;
                },
                id: inputId,
                type: "text",
                className: `w-full py-0 px-4 pr-10 font-normal text-text-900 focus:outline-primary-950 border rounded-full bg-background focus:bg-primary-50 border-border-300 focus:border-2 focus:border-primary-950 h-10 placeholder:text-text-600 ${getInputStateClasses(disabled, readOnly)} ${className}`,
                value,
                onChange: handleInputChange,
                onKeyDown: handleKeyDown,
                disabled,
                readOnly,
                placeholder,
                "aria-expanded": showDropdown ? "true" : void 0,
                "aria-haspopup": options.length > 0 ? "listbox" : void 0,
                "aria-controls": showDropdown ? dropdownId : void 0,
                "aria-autocomplete": "list",
                role: options.length > 0 ? "combobox" : void 0,
                ...props
              }
            ),
            showClearButton && /* @__PURE__ */ (0, import_jsx_runtime34.jsx)("div", { className: "absolute right-3 top-1/2 transform -translate-y-1/2", children: /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(
              "button",
              {
                type: "button",
                className: "p-0 border-0 bg-transparent cursor-pointer",
                onMouseDown: handleClearClick,
                "aria-label": "Limpar busca",
                children: /* @__PURE__ */ (0, import_jsx_runtime34.jsx)("span", { className: "w-6 h-6 text-text-800 flex items-center justify-center hover:text-text-600 transition-colors", children: /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(import_phosphor_react15.X, {}) })
              }
            ) }),
            showSearchIcon && /* @__PURE__ */ (0, import_jsx_runtime34.jsx)("div", { className: "absolute right-3 top-1/2 transform -translate-y-1/2", children: /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(
              "button",
              {
                type: "button",
                className: "p-0 border-0 bg-transparent cursor-pointer",
                onMouseDown: handleSearchIconClick,
                "aria-label": "Buscar",
                children: /* @__PURE__ */ (0, import_jsx_runtime34.jsx)("span", { className: "w-6 h-6 text-text-800 flex items-center justify-center hover:text-text-600 transition-colors", children: /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(import_phosphor_react15.MagnifyingGlass, {}) })
              }
            ) })
          ] }),
          showDropdown && /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(DropdownMenu_default, { open: showDropdown, onOpenChange: setDropdownOpen, children: /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(
            DropdownMenuContent,
            {
              id: dropdownId,
              className: "w-full mt-1",
              style: { maxHeight: dropdownMaxHeight },
              align: "start",
              children: filteredOptions.length > 0 ? filteredOptions.map((option) => /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(
                DropdownMenuItem,
                {
                  onClick: () => handleSelectOption(option),
                  className: "text-text-700 text-base leading-6 cursor-pointer",
                  children: option
                },
                option
              )) : /* @__PURE__ */ (0, import_jsx_runtime34.jsx)("div", { className: "px-3 py-3 text-text-700 text-base", children: noResultsText })
            }
          ) })
        ]
      }
    );
  }
);
Search.displayName = "Search";
var Search_default = Search;

// src/components/Chips/Chips.tsx
var import_phosphor_react16 = require("phosphor-react");
var import_jsx_runtime35 = require("react/jsx-runtime");
var STATE_CLASSES5 = {
  default: "bg-background text-text-950 border border-border-100 hover:bg-secondary-50 hover:border-border-300",
  selected: "bg-info-background text-primary-950 border-2 border-primary-950 hover:bg-secondary-50 focus-visible:border-0"
};
var Chips = ({
  children,
  selected = false,
  className = "",
  disabled,
  type = "button",
  ...props
}) => {
  const stateClasses = selected ? STATE_CLASSES5.selected : STATE_CLASSES5.default;
  const baseClasses = "inline-flex items-center justify-center rounded-full cursor-pointer font-normal text-sm px-4 py-2 gap-2 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-0 focus-visible:ring-primary-600 disabled:opacity-40 disabled:cursor-not-allowed";
  return /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(
    "button",
    {
      className: cn(baseClasses, stateClasses, className),
      disabled,
      type,
      ...props,
      children: [
        selected && /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("span", { className: `flex items-center`, children: /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(import_phosphor_react16.Check, { weight: "bold", size: 16 }) }),
        /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("span", { className: "flex-1", children })
      ]
    }
  );
};
var Chips_default = Chips;

// src/components/ProgressBar/ProgressBar.tsx
var import_jsx_runtime36 = require("react/jsx-runtime");
var SIZE_CLASSES8 = {
  small: {
    container: "h-1",
    // 4px height (h-1 = 4px in Tailwind)
    bar: "h-1",
    // 4px height for the fill bar
    spacing: "gap-2",
    // 8px gap between label and progress bar
    layout: "flex-col",
    // vertical layout for small
    borderRadius: "rounded-full"
    // 9999px border radius
  },
  medium: {
    container: "h-2",
    // 8px height (h-2 = 8px in Tailwind)
    bar: "h-2",
    // 8px height for the fill bar
    spacing: "gap-2",
    // 8px gap between progress bar and label
    layout: "flex-row items-center",
    // horizontal layout for medium
    borderRadius: "rounded-lg"
    // 8px border radius
  }
};
var VARIANT_CLASSES2 = {
  blue: {
    background: "bg-background-300",
    // Background track color (#D5D4D4)
    fill: "bg-primary-700"
    // Blue for activity progress (#2271C4)
  },
  green: {
    background: "bg-background-300",
    // Background track color (#D5D4D4)
    fill: "bg-success-200"
    // Green for performance (#84D3A2)
  }
};
var calculateProgressValues = (value, max) => {
  const safeValue = isNaN(value) ? 0 : value;
  const clampedValue = Math.max(0, Math.min(safeValue, max));
  const percentage = max === 0 ? 0 : clampedValue / max * 100;
  return { clampedValue, percentage };
};
var shouldShowHeader = (label, showPercentage, showHitCount) => {
  return !!(label || showPercentage || showHitCount);
};
var getDisplayPriority = (showHitCount, showPercentage, label, clampedValue, max, percentage) => {
  if (showHitCount) {
    return {
      type: "hitCount",
      content: `${Math.round(clampedValue)} de ${max}`,
      hasMetrics: true
    };
  }
  if (showPercentage) {
    return {
      type: "percentage",
      content: `${Math.round(percentage)}%`,
      hasMetrics: true
    };
  }
  return {
    type: "label",
    content: label,
    hasMetrics: false
  };
};
var getCompactLayoutConfig = ({
  showPercentage,
  showHitCount,
  percentage,
  clampedValue,
  max,
  label,
  percentageClassName,
  labelClassName
}) => {
  const displayPriority = getDisplayPriority(
    showHitCount,
    showPercentage,
    label,
    clampedValue,
    max,
    percentage
  );
  return {
    color: displayPriority.hasMetrics ? "text-primary-600" : "text-primary-700",
    className: displayPriority.hasMetrics ? percentageClassName : labelClassName,
    content: displayPriority.content
  };
};
var getDefaultLayoutDisplayConfig = (size, label, showPercentage) => ({
  showHeader: size === "small" && !!(label || showPercentage),
  showPercentage: size === "medium" && showPercentage,
  showLabel: size === "medium" && !!label && !showPercentage
  // Only show label when percentage is not shown
});
var renderStackedHitCountDisplay = (showHitCount, showPercentage, clampedValue, max, percentage, percentageClassName) => {
  if (!showHitCount && !showPercentage) return null;
  const displayPriority = getDisplayPriority(
    showHitCount,
    showPercentage,
    null,
    // label is not relevant for stacked layout metrics display
    clampedValue,
    max,
    percentage
  );
  return /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(
    "div",
    {
      className: cn(
        "text-xs font-medium leading-[14px] text-right",
        percentageClassName
      ),
      children: displayPriority.type === "hitCount" ? /* @__PURE__ */ (0, import_jsx_runtime36.jsxs)(import_jsx_runtime36.Fragment, { children: [
        /* @__PURE__ */ (0, import_jsx_runtime36.jsx)("span", { className: "text-success-200", children: Math.round(clampedValue) }),
        /* @__PURE__ */ (0, import_jsx_runtime36.jsxs)("span", { className: "text-text-600", children: [
          " de ",
          max
        ] })
      ] }) : /* @__PURE__ */ (0, import_jsx_runtime36.jsxs)(Text_default, { size: "xs", weight: "medium", className: "text-success-200", children: [
        Math.round(percentage),
        "%"
      ] })
    }
  );
};
var ProgressBarBase = ({
  clampedValue,
  max,
  percentage,
  label,
  variantClasses,
  containerClassName,
  fillClassName
}) => /* @__PURE__ */ (0, import_jsx_runtime36.jsxs)(
  "div",
  {
    className: cn(
      containerClassName,
      variantClasses.background,
      "overflow-hidden relative"
    ),
    children: [
      /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(
        "progress",
        {
          value: clampedValue,
          max,
          "aria-label": typeof label === "string" ? `${label}: ${Math.round(percentage)}% complete` : `Progress: ${Math.round(percentage)}% of ${max}`,
          className: "absolute inset-0 w-full h-full opacity-0"
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(
        "div",
        {
          className: cn(
            fillClassName,
            variantClasses.fill,
            "transition-all duration-300 ease-out"
          ),
          style: { width: `${percentage}%` }
        }
      )
    ]
  }
);
var StackedLayout = ({
  className,
  label,
  showPercentage,
  showHitCount,
  labelClassName,
  percentageClassName,
  clampedValue,
  max,
  percentage,
  variantClasses,
  dimensions
}) => /* @__PURE__ */ (0, import_jsx_runtime36.jsxs)(
  "div",
  {
    className: cn(
      "flex flex-col items-start gap-2",
      dimensions.width,
      dimensions.height,
      className
    ),
    children: [
      shouldShowHeader(label, showPercentage, showHitCount) && /* @__PURE__ */ (0, import_jsx_runtime36.jsxs)("div", { className: "flex flex-row justify-between items-center w-full h-[19px]", children: [
        label && /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(
          Text_default,
          {
            as: "div",
            size: "md",
            weight: "medium",
            className: cn("text-text-600 leading-[19px]", labelClassName),
            children: label
          }
        ),
        renderStackedHitCountDisplay(
          showHitCount,
          showPercentage,
          clampedValue,
          max,
          percentage,
          percentageClassName
        )
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(
        ProgressBarBase,
        {
          clampedValue,
          max,
          percentage,
          label,
          variantClasses,
          containerClassName: "w-full h-2 rounded-lg",
          fillClassName: "h-2 rounded-lg shadow-hard-shadow-3"
        }
      )
    ]
  }
);
var CompactLayout = ({
  className,
  label,
  showPercentage,
  showHitCount,
  labelClassName,
  percentageClassName,
  clampedValue,
  max,
  percentage,
  variantClasses,
  dimensions
}) => {
  const {
    color,
    className: compactClassName,
    content
  } = getCompactLayoutConfig({
    showPercentage,
    showHitCount,
    percentage,
    clampedValue,
    max,
    label,
    percentageClassName,
    labelClassName
  });
  return /* @__PURE__ */ (0, import_jsx_runtime36.jsxs)(
    "div",
    {
      className: cn(
        "flex flex-col items-start gap-1",
        dimensions.width,
        dimensions.height,
        className
      ),
      children: [
        shouldShowHeader(label, showPercentage, showHitCount) && /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(
          Text_default,
          {
            as: "div",
            size: "sm",
            weight: "medium",
            color,
            className: cn("leading-4 w-full", compactClassName),
            children: content
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(
          ProgressBarBase,
          {
            clampedValue,
            max,
            percentage,
            label,
            variantClasses,
            containerClassName: "w-full h-1 rounded-full",
            fillClassName: "h-1 rounded-full"
          }
        )
      ]
    }
  );
};
var DefaultLayout = ({
  className,
  size,
  sizeClasses,
  variantClasses,
  label,
  showPercentage,
  labelClassName,
  percentageClassName,
  clampedValue,
  max,
  percentage
}) => {
  const gapClass = size === "medium" ? "gap-2" : sizeClasses.spacing;
  const progressBarClass = size === "medium" ? "flex-grow" : "w-full";
  const displayConfig = getDefaultLayoutDisplayConfig(
    size,
    label,
    showPercentage
  );
  return /* @__PURE__ */ (0, import_jsx_runtime36.jsxs)("div", { className: cn("flex", sizeClasses.layout, gapClass, className), children: [
    displayConfig.showHeader && /* @__PURE__ */ (0, import_jsx_runtime36.jsxs)("div", { className: "flex flex-row items-center justify-between w-full", children: [
      label && /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(
        Text_default,
        {
          as: "div",
          size: "xs",
          weight: "medium",
          className: cn(
            "text-text-950 leading-none tracking-normal text-center",
            labelClassName
          ),
          children: label
        }
      ),
      showPercentage && /* @__PURE__ */ (0, import_jsx_runtime36.jsxs)(
        Text_default,
        {
          size: "xs",
          weight: "medium",
          className: cn(
            "text-text-950 leading-none tracking-normal text-center",
            percentageClassName
          ),
          children: [
            Math.round(percentage),
            "%"
          ]
        }
      )
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(
      ProgressBarBase,
      {
        clampedValue,
        max,
        percentage,
        label,
        variantClasses,
        containerClassName: cn(
          progressBarClass,
          sizeClasses.container,
          sizeClasses.borderRadius
        ),
        fillClassName: cn(
          sizeClasses.bar,
          sizeClasses.borderRadius,
          "shadow-hard-shadow-3"
        )
      }
    ),
    displayConfig.showPercentage && /* @__PURE__ */ (0, import_jsx_runtime36.jsxs)(
      Text_default,
      {
        size: "xs",
        weight: "medium",
        className: cn(
          "text-text-950 leading-none tracking-normal text-center flex-none",
          percentageClassName
        ),
        children: [
          Math.round(percentage),
          "%"
        ]
      }
    ),
    displayConfig.showLabel && /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(
      Text_default,
      {
        as: "div",
        size: "xs",
        weight: "medium",
        className: cn(
          "text-text-950 leading-none tracking-normal text-center flex-none",
          labelClassName
        ),
        children: label
      }
    )
  ] });
};
var ProgressBar = ({
  value,
  max = 100,
  size = "medium",
  variant = "blue",
  layout = "default",
  label,
  showPercentage = false,
  showHitCount = false,
  className = "",
  labelClassName = "",
  percentageClassName = "",
  stackedWidth,
  stackedHeight,
  compactWidth,
  compactHeight
}) => {
  const { clampedValue, percentage } = calculateProgressValues(value, max);
  const sizeClasses = SIZE_CLASSES8[size];
  const variantClasses = VARIANT_CLASSES2[variant];
  if (layout === "stacked") {
    return /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(
      StackedLayout,
      {
        className,
        label,
        showPercentage,
        showHitCount,
        labelClassName,
        percentageClassName,
        clampedValue,
        max,
        percentage,
        variantClasses,
        dimensions: {
          width: stackedWidth ?? "w-[380px]",
          height: stackedHeight ?? "h-[35px]"
        }
      }
    );
  }
  if (layout === "compact") {
    return /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(
      CompactLayout,
      {
        className,
        label,
        showPercentage,
        showHitCount,
        labelClassName,
        percentageClassName,
        clampedValue,
        max,
        percentage,
        variantClasses,
        dimensions: {
          width: compactWidth ?? "w-[131px]",
          height: compactHeight ?? "h-[24px]"
        }
      }
    );
  }
  return /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(
    DefaultLayout,
    {
      className,
      size,
      sizeClasses,
      variantClasses,
      label,
      showPercentage,
      labelClassName,
      percentageClassName,
      clampedValue,
      max,
      percentage
    }
  );
};
var ProgressBar_default = ProgressBar;

// src/components/ProgressCircle/ProgressCircle.tsx
var import_jsx_runtime37 = require("react/jsx-runtime");
var SIZE_CLASSES9 = {
  small: {
    container: "w-[107px] h-[107px]",
    // 107px circle to fit labels like "CONCLUÍDO"
    strokeWidth: 4,
    // 4px stroke width - matches ProgressBar small (h-1)
    textSize: "2xl",
    // 24px for percentage (font-size: 24px)
    textWeight: "medium",
    // font-weight: 500
    labelSize: "2xs",
    // 10px for status label
    labelWeight: "bold",
    // font-weight: 700
    spacing: "gap-0",
    // Reduced gap between percentage and label for better spacing
    contentWidth: "max-w-[85px]"
    // Width to fit labels like "CONCLUÍDO" inside circle
  },
  medium: {
    container: "w-[152px] h-[152px]",
    // 151.67px ≈ 152px circle from design specs
    strokeWidth: 8,
    // 8px stroke width - matches ProgressBar medium (h-2)
    textSize: "2xl",
    // 24px for percentage (font-size: 24px)
    textWeight: "medium",
    // font-weight: 500
    labelSize: "xs",
    // 12px for status label (font-size: 12px)
    labelWeight: "medium",
    // font-weight: 500 (changed from bold)
    spacing: "gap-1",
    // 4px gap between percentage and label
    contentWidth: "max-w-[90px]"
    // Reduced width to fit text inside circle
  }
};
var VARIANT_CLASSES3 = {
  blue: {
    background: "stroke-primary-100",
    // Light blue background (#BBDCF7)
    fill: "stroke-primary-700",
    // Blue for activity progress (#2271C4)
    textColor: "text-primary-700",
    // Blue text color (#2271C4)
    labelColor: "text-text-700"
    // Gray text for label (#525252)
  },
  green: {
    background: "stroke-background-300",
    // Gray background (#D5D4D4 - matches design)
    fill: "stroke-success-200",
    // Green for performance (#84D3A2 - matches design)
    textColor: "text-text-800",
    // Dark gray text (#404040 - matches design)
    labelColor: "text-text-600"
    // Medium gray text for label (#737373 - matches design)
  }
};
var ProgressCircle = ({
  value,
  max = 100,
  size = "small",
  variant = "blue",
  label,
  showPercentage = true,
  className = "",
  labelClassName = "",
  percentageClassName = ""
}) => {
  const safeValue = isNaN(value) ? 0 : value;
  const clampedValue = Math.max(0, Math.min(safeValue, max));
  const percentage = max === 0 ? 0 : clampedValue / max * 100;
  const sizeClasses = SIZE_CLASSES9[size];
  const variantClasses = VARIANT_CLASSES3[variant];
  const radius = size === "small" ? 49 : 64;
  const circumference = 2 * Math.PI * radius;
  const strokeDashoffset = circumference - percentage / 100 * circumference;
  const center = size === "small" ? 53.5 : 76;
  const svgSize = size === "small" ? 107 : 152;
  return /* @__PURE__ */ (0, import_jsx_runtime37.jsxs)(
    "div",
    {
      className: cn(
        "relative flex flex-col items-center justify-center",
        sizeClasses.container,
        "rounded-lg",
        className
      ),
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime37.jsxs)(
          "svg",
          {
            className: "absolute inset-0 transform -rotate-90",
            width: svgSize,
            height: svgSize,
            viewBox: `0 0 ${svgSize} ${svgSize}`,
            "aria-hidden": "true",
            children: [
              /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(
                "circle",
                {
                  cx: center,
                  cy: center,
                  r: radius,
                  fill: "none",
                  strokeWidth: sizeClasses.strokeWidth,
                  className: cn(variantClasses.background, "rounded-lg")
                }
              ),
              /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(
                "circle",
                {
                  cx: center,
                  cy: center,
                  r: radius,
                  fill: "none",
                  strokeWidth: sizeClasses.strokeWidth,
                  strokeLinecap: "round",
                  strokeDasharray: circumference,
                  strokeDashoffset,
                  className: cn(
                    variantClasses.fill,
                    "transition-all duration-500 ease-out shadow-soft-shadow-3 rounded-lg"
                  )
                }
              )
            ]
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(
          "progress",
          {
            value: clampedValue,
            max,
            "aria-label": typeof label === "string" ? label : "Progress",
            className: "absolute opacity-0 w-0 h-0"
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime37.jsxs)(
          "div",
          {
            className: cn(
              "relative z-10 flex flex-col items-center justify-center",
              sizeClasses.spacing,
              sizeClasses.contentWidth
            ),
            children: [
              showPercentage && /* @__PURE__ */ (0, import_jsx_runtime37.jsxs)(
                Text_default,
                {
                  size: sizeClasses.textSize,
                  weight: sizeClasses.textWeight,
                  className: cn(
                    "text-center w-full",
                    variantClasses.textColor,
                    percentageClassName
                  ),
                  children: [
                    Math.round(percentage),
                    "%"
                  ]
                }
              ),
              label && /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(
                Text_default,
                {
                  as: "span",
                  size: sizeClasses.labelSize,
                  weight: sizeClasses.labelWeight,
                  className: cn(
                    variantClasses.labelColor,
                    "text-center uppercase tracking-wide truncate w-full",
                    labelClassName
                  ),
                  children: label
                }
              )
            ]
          }
        )
      ]
    }
  );
};
var ProgressCircle_default = ProgressCircle;

// src/components/Stepper/Stepper.tsx
var import_phosphor_react17 = require("phosphor-react");
var import_jsx_runtime38 = require("react/jsx-runtime");
var SIZE_CLASSES10 = {
  small: {
    container: "gap-2",
    // 8px gap as specified in CSS
    stepWidth: "w-[58px]",
    // exact 58px from CSS
    stepHeight: "h-[38px]",
    // exact 38px from CSS
    indicator: "w-5 h-5",
    // 20px as specified
    progressBar: "h-0.5",
    // 2px as specified
    indicatorTextSize: "2xs",
    // 10px as specified
    labelTextSize: "xs",
    // 12px as specified
    iconSize: "w-3 h-3"
    // 12px
  },
  medium: {
    container: "gap-3",
    // 12px (8px + 4px progression)
    stepWidth: "w-[110px]",
    // 110px (increased from 90px to fit "Endereço Residencial")
    stepHeight: "h-[48px]",
    // 48px (increased from 46px for better proportion)
    indicator: "w-6 h-6",
    // 24px (20px + 4px progression)
    progressBar: "h-0.5",
    // 2px maintained for consistency
    indicatorTextSize: "2xs",
    // 10px maintained for readability
    labelTextSize: "xs",
    // 12px maintained
    iconSize: "w-3.5 h-3.5"
    // 14px
  },
  large: {
    container: "gap-4",
    // 16px (12px + 4px progression)
    stepWidth: "w-[160px]",
    // 160px (increased from 140px to fit "Endereço Residencial")
    stepHeight: "h-[58px]",
    // 58px (increased from 54px for better proportion)
    indicator: "w-7 h-7",
    // 28px (24px + 4px progression)
    progressBar: "h-1",
    // 4px (increased for better visibility)
    indicatorTextSize: "xs",
    // 12px (increased for larger size)
    labelTextSize: "sm",
    // 14px (increased for larger size)
    iconSize: "w-4 h-4"
    // 16px
  },
  extraLarge: {
    container: "gap-5",
    // 20px (16px + 4px progression)
    stepWidth: "w-[200px]",
    // 200px (increased from 180px to ensure "Endereço Residencial" fits)
    stepHeight: "h-[68px]",
    // 68px (increased from 62px for better proportion)
    indicator: "w-8 h-8",
    // 32px (28px + 4px progression)
    progressBar: "h-1",
    // 4px maintained
    indicatorTextSize: "xs",
    // 12px maintained for readability
    labelTextSize: "sm",
    // 14px maintained
    iconSize: "w-[18px] h-[18px]"
    // 18px
  }
};
var STATE_CLASSES6 = {
  pending: {
    progressBar: "bg-text-400",
    // #A3A3A3
    indicator: "bg-text-400",
    // #A3A3A3
    indicatorText: "text-white",
    // Branco para contraste com background cinza
    label: "text-text-400"
    // #A3A3A3
  },
  current: {
    progressBar: "bg-primary-800",
    // #1C61B2 usando classe Tailwind padrão
    indicator: "bg-primary-800",
    // #1C61B2 usando classe Tailwind padrão
    indicatorText: "text-white",
    // Branco usando classe Tailwind padrão
    label: "text-primary-800"
    // #1C61B2 usando classe Tailwind padrão
  },
  completed: {
    progressBar: "bg-primary-400",
    // #48A0E8 para barra quando checked (completed)
    indicator: "bg-primary-400",
    // #48A0E8 para corresponder à barra de progresso
    indicatorText: "text-white",
    // Branco usando classe Tailwind padrão
    label: "text-primary-400"
    // #48A0E8 para corresponder à barra de progresso
  }
};
var Step = ({
  step,
  index,
  size: _size,
  sizeClasses,
  stateClasses,
  isLast: _isLast,
  className = ""
}) => {
  const stepNumber = index + 1;
  const isCompleted = step.state === "completed";
  const getAriaLabel = () => {
    let suffix = "";
    if (step.state === "completed") {
      suffix = " (conclu\xEDdo)";
    } else if (step.state === "current") {
      suffix = " (atual)";
    }
    return `${step.label}${suffix}`;
  };
  return /* @__PURE__ */ (0, import_jsx_runtime38.jsxs)(
    "div",
    {
      className: `
        flex flex-col justify-center items-center pb-2 gap-2
        ${sizeClasses.stepWidth} ${sizeClasses.stepHeight}
        flex-none flex-grow
        ${className}
        sm:max-w-[100px] md:max-w-[120px] lg:max-w-none xl:max-w-none
        sm:min-h-[40px] md:min-h-[45px] lg:min-h-none
        overflow-visible
      `,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime38.jsx)(
          "div",
          {
            className: `
          w-full ${sizeClasses.progressBar} ${stateClasses.progressBar}
          rounded-sm flex-none
        `
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime38.jsxs)(
          "div",
          {
            className: `
          flex flex-col sm:flex-row items-center
          gap-1 sm:gap-2 w-full sm:w-auto
          h-auto sm:h-5 flex-none
          overflow-visible
        `,
            children: [
              /* @__PURE__ */ (0, import_jsx_runtime38.jsx)(
                "div",
                {
                  className: `
            ${sizeClasses.indicator} ${stateClasses.indicator}
            rounded-full flex items-center justify-center relative
            flex-none transition-all duration-300 ease-out
          `,
                  "aria-label": getAriaLabel(),
                  children: isCompleted ? /* @__PURE__ */ (0, import_jsx_runtime38.jsx)(
                    import_phosphor_react17.Check,
                    {
                      weight: "bold",
                      className: `
                ${stateClasses.indicatorText}
                w-2.5 h-2.5 sm:w-3 sm:h-3 md:w-3 md:h-3 lg:w-3.5 lg:h-3.5
              `
                    }
                  ) : /* @__PURE__ */ (0, import_jsx_runtime38.jsx)(
                    Text_default,
                    {
                      size: sizeClasses.indicatorTextSize,
                      weight: "medium",
                      color: "",
                      className: cn(stateClasses.indicatorText, "leading-none"),
                      children: stepNumber
                    }
                  )
                }
              ),
              /* @__PURE__ */ (0, import_jsx_runtime38.jsx)(
                Text_default,
                {
                  size: sizeClasses.labelTextSize,
                  weight: "medium",
                  color: "",
                  className: cn(
                    stateClasses.label,
                    "leading-tight flex-none text-center sm:text-left break-words px-1 sm:px-0 max-w-full whitespace-normal"
                  ),
                  children: step.label
                }
              )
            ]
          }
        )
      ]
    }
  );
};
var calculateStepStates = (steps, currentStep) => {
  return steps.map((step, index) => {
    let stepState;
    if (index < currentStep) {
      stepState = "completed";
    } else if (index === currentStep) {
      stepState = "current";
    } else {
      stepState = "pending";
    }
    return {
      ...step,
      state: stepState
    };
  });
};
var getProgressText = (currentStep, totalSteps, customText) => {
  if (customText) return customText;
  return `Etapa ${currentStep + 1} de ${totalSteps}`;
};
var Stepper = ({
  steps: initialSteps,
  size = "medium",
  currentStep,
  className = "",
  stepClassName = "",
  showProgress = false,
  progressText,
  responsive = true
}) => {
  const sizeClasses = SIZE_CLASSES10[size];
  const steps = currentStep !== void 0 ? calculateStepStates(initialSteps, currentStep) : initialSteps;
  return /* @__PURE__ */ (0, import_jsx_runtime38.jsxs)(
    "fieldset",
    {
      className: cn(
        "flex flex-col gap-4 sm:gap-5 md:gap-6",
        className,
        "border-0 p-0 m-0"
      ),
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime38.jsx)("legend", { className: "absolute w-px h-px p-0 -m-px overflow-hidden whitespace-nowrap border-0", children: "Stepper de formul\xE1rio" }),
        showProgress && currentStep !== void 0 && /* @__PURE__ */ (0, import_jsx_runtime38.jsx)(
          Text_default,
          {
            size: "sm",
            weight: "medium",
            className: "text-text-600 text-center sm:text-left text-xs sm:text-sm",
            children: getProgressText(currentStep, steps.length, progressText)
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime38.jsx)(
          "div",
          {
            className: cn(
              "flex items-center",
              sizeClasses.container,
              responsive ? "flex-row overflow-x-auto overflow-y-hidden scrollbar-hide justify-start sm:justify-center md:justify-center lg:justify-center" : "flex-row justify-center",
              "max-w-full min-w-0 gap-2 sm:gap-3 md:gap-4 lg:gap-4"
            ),
            role: "tablist",
            "aria-label": "Progress steps",
            children: steps.map((step, index) => {
              const stateClasses = STATE_CLASSES6[step.state];
              return /* @__PURE__ */ (0, import_jsx_runtime38.jsx)(
                Step,
                {
                  step,
                  index,
                  size,
                  sizeClasses,
                  stateClasses,
                  isLast: index === steps.length - 1,
                  className: stepClassName
                },
                step.id
              );
            })
          }
        )
      ]
    }
  );
};
var Stepper_default = Stepper;

// src/components/Calendar/Calendar.tsx
var import_react21 = require("react");
var import_jsx_runtime39 = require("react/jsx-runtime");
var WEEK_DAYS = ["SEG", "TER", "QUA", "QUI", "SEX", "S\xC1B", "DOM"];
var WEEK_DAYS_SHORT = ["S", "T", "Q", "Q", "S", "S", "D"];
var MONTH_NAMES = [
  "Janeiro",
  "Fevereiro",
  "Mar\xE7o",
  "Abril",
  "Maio",
  "Junho",
  "Julho",
  "Agosto",
  "Setembro",
  "Outubro",
  "Novembro",
  "Dezembro"
];
var MonthYearPicker = ({
  monthPickerRef,
  availableYears,
  currentDate,
  onYearChange,
  onMonthChange
}) => /* @__PURE__ */ (0, import_jsx_runtime39.jsxs)(
  "div",
  {
    ref: monthPickerRef,
    className: "absolute top-full left-0 z-50 mt-1 bg-background rounded-lg shadow-lg border border-border-200 p-4 min-w-[280px]",
    children: [
      /* @__PURE__ */ (0, import_jsx_runtime39.jsxs)("div", { className: "mb-4", children: [
        /* @__PURE__ */ (0, import_jsx_runtime39.jsx)("h3", { className: "text-sm font-medium text-text-700 mb-2", children: "Selecionar Ano" }),
        /* @__PURE__ */ (0, import_jsx_runtime39.jsx)("div", { className: "grid grid-cols-4 gap-1 max-h-32 overflow-y-auto", children: availableYears.map((year) => /* @__PURE__ */ (0, import_jsx_runtime39.jsx)(
          "button",
          {
            onClick: () => onYearChange(year),
            className: `
              px-2 py-1 text-xs rounded text-center hover:bg-background-100 transition-colors
              ${year === currentDate.getFullYear() ? "bg-primary-800 text-text font-medium hover:text-text-950" : "text-text-700"}
            `,
            children: year
          },
          year
        )) })
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime39.jsxs)("div", { children: [
        /* @__PURE__ */ (0, import_jsx_runtime39.jsx)("h3", { className: "text-sm font-medium text-text-700 mb-2", children: "Selecionar M\xEAs" }),
        /* @__PURE__ */ (0, import_jsx_runtime39.jsx)("div", { className: "grid grid-cols-3 gap-1", children: MONTH_NAMES.map((month, index) => /* @__PURE__ */ (0, import_jsx_runtime39.jsx)(
          "button",
          {
            onClick: () => onMonthChange(index, currentDate.getFullYear()),
            className: `
              px-2 py-2 text-xs rounded text-center hover:bg-background-100 transition-colors
              ${index === currentDate.getMonth() ? "bg-primary-800 text-text font-medium hover:text-text-950" : "text-text-700"}
            `,
            children: month.substring(0, 3)
          },
          month
        )) })
      ] })
    ]
  }
);
var getDayStyles = (day, variant, showActivities) => {
  let dayStyle = "";
  let textStyle = "";
  if (variant === "selection" && day.isSelected) {
    dayStyle = "bg-primary-800";
    textStyle = "text-text";
  } else if (day.isToday) {
    textStyle = "text-primary-800";
  } else if (variant === "navigation" && showActivities && day.activities?.length) {
    const primaryActivity = day.activities[0];
    if (primaryActivity.status === "near-deadline") {
      dayStyle = "bg-warning-background border-2 border-warning-400";
      textStyle = "text-text-950";
    } else if (primaryActivity.status === "in-deadline") {
      dayStyle = "bg-success-background border-2 border-success-300";
      textStyle = "text-text-950";
    } else if (primaryActivity.status === "overdue") {
      dayStyle = "bg-error-background border-2 border-error-300";
      textStyle = "text-text-950";
    } else {
      dayStyle = "border-2 border-blue-500";
      textStyle = "text-blue-500";
    }
  } else {
    textStyle = "text-text-950 hover:bg-background-100";
  }
  return { dayStyle, textStyle };
};
var Calendar = ({
  variant = "selection",
  selectedDate,
  onDateSelect,
  onMonthChange,
  activities = {},
  showActivities = true,
  className = ""
}) => {
  const [currentDate, setCurrentDate] = (0, import_react21.useState)(selectedDate || /* @__PURE__ */ new Date());
  const [isMonthPickerOpen, setIsMonthPickerOpen] = (0, import_react21.useState)(false);
  const monthPickerRef = (0, import_react21.useRef)(null);
  const monthPickerContainerRef = (0, import_react21.useRef)(null);
  (0, import_react21.useEffect)(() => {
    const handleClickOutside = (event) => {
      if (monthPickerContainerRef.current && !monthPickerContainerRef.current.contains(event.target)) {
        setIsMonthPickerOpen(false);
      }
    };
    if (isMonthPickerOpen) {
      document.addEventListener("mousedown", handleClickOutside);
    }
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, [isMonthPickerOpen]);
  const today = /* @__PURE__ */ new Date();
  const availableYears = (0, import_react21.useMemo)(() => {
    const currentYear = (/* @__PURE__ */ new Date()).getFullYear();
    const years = [];
    for (let year = currentYear - 10; year <= currentYear + 10; year++) {
      years.push(year);
    }
    return years;
  }, []);
  const calendarData = (0, import_react21.useMemo)(() => {
    const year = currentDate.getFullYear();
    const month = currentDate.getMonth();
    const firstDay = new Date(year, month, 1);
    const startDate = new Date(firstDay);
    const firstDayOfWeek = (firstDay.getDay() + 6) % 7;
    startDate.setDate(startDate.getDate() - firstDayOfWeek);
    const days = [];
    const currentCalendarDate = new Date(startDate);
    for (let i = 0; i < 42; i++) {
      const dateKey = currentCalendarDate.toISOString().split("T")[0];
      const dayActivities = activities[dateKey] || [];
      days.push({
        date: new Date(currentCalendarDate),
        isCurrentMonth: currentCalendarDate.getMonth() === month,
        isToday: currentCalendarDate.getFullYear() === today.getFullYear() && currentCalendarDate.getMonth() === today.getMonth() && currentCalendarDate.getDate() === today.getDate(),
        isSelected: selectedDate ? currentCalendarDate.getFullYear() === selectedDate.getFullYear() && currentCalendarDate.getMonth() === selectedDate.getMonth() && currentCalendarDate.getDate() === selectedDate.getDate() : false,
        activities: dayActivities
      });
      currentCalendarDate.setDate(currentCalendarDate.getDate() + 1);
    }
    return days;
  }, [currentDate, selectedDate, activities]);
  const goToPreviousMonth = () => {
    const newDate = new Date(currentDate);
    newDate.setMonth(newDate.getMonth() - 1);
    setCurrentDate(newDate);
    onMonthChange?.(newDate);
  };
  const goToNextMonth = () => {
    const newDate = new Date(currentDate);
    newDate.setMonth(newDate.getMonth() + 1);
    setCurrentDate(newDate);
    onMonthChange?.(newDate);
  };
  const goToMonth = (month, year) => {
    const newDate = new Date(year, month, 1);
    setCurrentDate(newDate);
    setIsMonthPickerOpen(false);
    onMonthChange?.(newDate);
  };
  const handleYearChange = (year) => {
    const newDate = new Date(year, currentDate.getMonth(), 1);
    setCurrentDate(newDate);
  };
  const toggleMonthPicker = (event) => {
    event.stopPropagation();
    setIsMonthPickerOpen(!isMonthPickerOpen);
  };
  const handleDateSelect = (day) => {
    onDateSelect?.(day.date);
  };
  if (variant === "navigation") {
    return /* @__PURE__ */ (0, import_jsx_runtime39.jsxs)("div", { className: cn("bg-background rounded-xl pt-6", className), children: [
      /* @__PURE__ */ (0, import_jsx_runtime39.jsxs)("div", { className: "flex items-center justify-between mb-4 px-6", children: [
        /* @__PURE__ */ (0, import_jsx_runtime39.jsxs)("div", { className: "relative", ref: monthPickerContainerRef, children: [
          /* @__PURE__ */ (0, import_jsx_runtime39.jsxs)(
            "button",
            {
              onClick: toggleMonthPicker,
              className: "flex items-center group gap-1 rounded transition-colors cursor-pointer",
              children: [
                /* @__PURE__ */ (0, import_jsx_runtime39.jsxs)("span", { className: "text-sm font-medium text-text-600 group-hover:text-primary-950", children: [
                  MONTH_NAMES[currentDate.getMonth()],
                  " ",
                  currentDate.getFullYear()
                ] }),
                /* @__PURE__ */ (0, import_jsx_runtime39.jsx)(
                  "svg",
                  {
                    className: `w-4 h-4 text-primary-950 transition-transform ${isMonthPickerOpen ? "rotate-180" : ""}`,
                    fill: "none",
                    stroke: "currentColor",
                    viewBox: "0 0 24 24",
                    children: /* @__PURE__ */ (0, import_jsx_runtime39.jsx)(
                      "path",
                      {
                        strokeLinecap: "round",
                        strokeLinejoin: "round",
                        strokeWidth: 2,
                        d: "M19 9l-7 7-7-7"
                      }
                    )
                  }
                )
              ]
            }
          ),
          isMonthPickerOpen && /* @__PURE__ */ (0, import_jsx_runtime39.jsx)(
            MonthYearPicker,
            {
              monthPickerRef,
              availableYears,
              currentDate,
              onYearChange: handleYearChange,
              onMonthChange: goToMonth
            }
          )
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime39.jsxs)("div", { className: "flex items-center gap-10", children: [
          /* @__PURE__ */ (0, import_jsx_runtime39.jsx)(
            "button",
            {
              onClick: goToPreviousMonth,
              className: "p-1 rounded hover:bg-background-100 transition-colors",
              "aria-label": "M\xEAs anterior",
              children: /* @__PURE__ */ (0, import_jsx_runtime39.jsx)(
                "svg",
                {
                  className: "w-6 h-6 text-primary-950",
                  fill: "none",
                  stroke: "currentColor",
                  viewBox: "0 0 24 24",
                  children: /* @__PURE__ */ (0, import_jsx_runtime39.jsx)(
                    "path",
                    {
                      strokeLinecap: "round",
                      strokeLinejoin: "round",
                      strokeWidth: 2,
                      d: "M15 19l-7-7 7-7"
                    }
                  )
                }
              )
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime39.jsx)(
            "button",
            {
              onClick: goToNextMonth,
              className: "p-1 rounded hover:bg-background-100 transition-colors",
              "aria-label": "Pr\xF3ximo m\xEAs",
              children: /* @__PURE__ */ (0, import_jsx_runtime39.jsx)(
                "svg",
                {
                  className: "w-6 h-6 text-primary-950",
                  fill: "none",
                  stroke: "currentColor",
                  viewBox: "0 0 24 24",
                  children: /* @__PURE__ */ (0, import_jsx_runtime39.jsx)(
                    "path",
                    {
                      strokeLinecap: "round",
                      strokeLinejoin: "round",
                      strokeWidth: 2,
                      d: "M9 5l7 7-7 7"
                    }
                  )
                }
              )
            }
          )
        ] })
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime39.jsx)("div", { className: "grid grid-cols-7 gap-1 mb-2 px-3", children: WEEK_DAYS_SHORT.map((day, index) => /* @__PURE__ */ (0, import_jsx_runtime39.jsx)(
        "div",
        {
          className: "h-9 flex items-center justify-center text-xs font-normal text-text-600",
          children: day
        },
        `${day}-${index}`
      )) }),
      /* @__PURE__ */ (0, import_jsx_runtime39.jsx)("div", { className: "grid grid-cols-7 gap-1 px-3", children: calendarData.map((day) => {
        if (!day.isCurrentMonth) {
          return /* @__PURE__ */ (0, import_jsx_runtime39.jsx)(
            "div",
            {
              className: "flex items-center justify-center",
              children: /* @__PURE__ */ (0, import_jsx_runtime39.jsx)("div", { className: "w-9 h-9" })
            },
            day.date.getTime()
          );
        }
        const { dayStyle, textStyle } = getDayStyles(
          day,
          variant,
          showActivities
        );
        let spanClass = "";
        if (day.isSelected && day.isToday) {
          spanClass = "h-6 w-6 rounded-full bg-primary-800 text-text";
        } else if (day.isSelected) {
          spanClass = "h-6 w-6 rounded-full bg-primary-950 text-text";
        }
        return /* @__PURE__ */ (0, import_jsx_runtime39.jsx)(
          "div",
          {
            className: "flex items-center justify-center",
            children: /* @__PURE__ */ (0, import_jsx_runtime39.jsx)(
              "button",
              {
                className: `
                    w-9 h-9
                    flex items-center justify-center
                    text-md font-normal
                    cursor-pointer
                    rounded-full
                    ${dayStyle}
                    ${textStyle}
                  `,
                onClick: () => handleDateSelect(day),
                "aria-label": `${day.date.getDate()} de ${MONTH_NAMES[day.date.getMonth()]}`,
                "aria-current": day.isToday ? "date" : void 0,
                tabIndex: 0,
                children: /* @__PURE__ */ (0, import_jsx_runtime39.jsx)("span", { className: spanClass, children: day.date.getDate() })
              }
            )
          },
          day.date.getTime()
        );
      }) })
    ] });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime39.jsxs)("div", { className: cn("bg-background rounded-xl p-4", className), children: [
    /* @__PURE__ */ (0, import_jsx_runtime39.jsxs)("div", { className: "flex items-center justify-between mb-3.5", children: [
      /* @__PURE__ */ (0, import_jsx_runtime39.jsxs)("div", { className: "relative", ref: monthPickerContainerRef, children: [
        /* @__PURE__ */ (0, import_jsx_runtime39.jsxs)(
          "button",
          {
            onClick: toggleMonthPicker,
            className: "flex items-center gap-2 hover:bg-background-100 rounded px-2 py-1 transition-colors",
            children: [
              /* @__PURE__ */ (0, import_jsx_runtime39.jsxs)("h2", { className: "text-lg font-semibold text-text-950", children: [
                MONTH_NAMES[currentDate.getMonth()],
                " ",
                currentDate.getFullYear()
              ] }),
              /* @__PURE__ */ (0, import_jsx_runtime39.jsx)(
                "svg",
                {
                  className: `w-4 h-4 text-text-400 transition-transform ${isMonthPickerOpen ? "rotate-180" : ""}`,
                  fill: "none",
                  stroke: "currentColor",
                  viewBox: "0 0 24 24",
                  children: /* @__PURE__ */ (0, import_jsx_runtime39.jsx)(
                    "path",
                    {
                      strokeLinecap: "round",
                      strokeLinejoin: "round",
                      strokeWidth: 2,
                      d: "M19 9l-7 7-7-7"
                    }
                  )
                }
              )
            ]
          }
        ),
        isMonthPickerOpen && /* @__PURE__ */ (0, import_jsx_runtime39.jsx)(
          MonthYearPicker,
          {
            monthPickerRef,
            availableYears,
            currentDate,
            onYearChange: handleYearChange,
            onMonthChange: goToMonth
          }
        )
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime39.jsxs)("div", { className: "flex items-center gap-1", children: [
        /* @__PURE__ */ (0, import_jsx_runtime39.jsx)(
          "button",
          {
            onClick: goToPreviousMonth,
            className: "p-1 rounded-md hover:bg-background-100 transition-colors",
            "aria-label": "M\xEAs anterior",
            children: /* @__PURE__ */ (0, import_jsx_runtime39.jsx)(
              "svg",
              {
                className: "w-6 h-6 text-primary-950",
                fill: "none",
                stroke: "currentColor",
                viewBox: "0 0 24 24",
                children: /* @__PURE__ */ (0, import_jsx_runtime39.jsx)(
                  "path",
                  {
                    strokeLinecap: "round",
                    strokeLinejoin: "round",
                    strokeWidth: 2,
                    d: "M15 19l-7-7 7-7"
                  }
                )
              }
            )
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime39.jsx)(
          "button",
          {
            onClick: goToNextMonth,
            className: "p-1 rounded-md hover:bg-background-100 transition-colors",
            "aria-label": "Pr\xF3ximo m\xEAs",
            children: /* @__PURE__ */ (0, import_jsx_runtime39.jsx)(
              "svg",
              {
                className: "w-6 h-6 text-primary-950",
                fill: "none",
                stroke: "currentColor",
                viewBox: "0 0 24 24",
                children: /* @__PURE__ */ (0, import_jsx_runtime39.jsx)(
                  "path",
                  {
                    strokeLinecap: "round",
                    strokeLinejoin: "round",
                    strokeWidth: 2,
                    d: "M9 5l7 7-7 7"
                  }
                )
              }
            )
          }
        )
      ] })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime39.jsx)("div", { className: "grid grid-cols-7 mb-2", children: WEEK_DAYS.map((day) => /* @__PURE__ */ (0, import_jsx_runtime39.jsx)(
      "div",
      {
        className: "h-4 flex items-center justify-center text-xs font-semibold text-text-500",
        children: day
      },
      day
    )) }),
    /* @__PURE__ */ (0, import_jsx_runtime39.jsx)("div", { className: "grid grid-cols-7", children: calendarData.map((day) => {
      if (!day.isCurrentMonth) {
        return /* @__PURE__ */ (0, import_jsx_runtime39.jsx)(
          "div",
          {
            className: "flex items-center justify-center",
            children: /* @__PURE__ */ (0, import_jsx_runtime39.jsx)("div", { className: "w-10 h-10" })
          },
          day.date.getTime()
        );
      }
      const { dayStyle, textStyle } = getDayStyles(
        day,
        variant,
        showActivities
      );
      return /* @__PURE__ */ (0, import_jsx_runtime39.jsx)(
        "div",
        {
          className: "flex items-center justify-center",
          children: /* @__PURE__ */ (0, import_jsx_runtime39.jsx)(
            "button",
            {
              className: `
                  w-9 h-9
                  flex items-center justify-center
                  text-lg font-normal
                  cursor-pointer
                  rounded-full
                  focus:outline-none focus:ring-2 focus:ring-primary-600 focus:ring-offset-1
                  ${dayStyle}
                  ${textStyle}
                `,
              onClick: () => handleDateSelect(day),
              "aria-label": `${day.date.getDate()} de ${MONTH_NAMES[day.date.getMonth()]}`,
              "aria-current": day.isToday ? "date" : void 0,
              tabIndex: 0,
              children: day.date.getDate()
            }
          )
        },
        day.date.getTime()
      );
    }) })
  ] });
};
var Calendar_default = Calendar;

// src/components/DateTimeInput/DateTimeInput.tsx
var import_react22 = require("react");
var import_phosphor_react18 = require("phosphor-react");
var import_jsx_runtime40 = require("react/jsx-runtime");
var formatDateToInput = (dateObj) => {
  const year = dateObj.getFullYear();
  const month = String(dateObj.getMonth() + 1).padStart(2, "0");
  const day = String(dateObj.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
};
var DateTimeInput = ({
  label,
  date,
  time,
  onDateChange,
  onTimeChange,
  errorMessage,
  disabled = false,
  defaultTime = "00:00",
  testId,
  timeLabel = "Hora",
  className
}) => {
  const [isCalendarOpen, setIsCalendarOpen] = (0, import_react22.useState)(false);
  const [selectedDate, setSelectedDate] = (0, import_react22.useState)(
    date ? /* @__PURE__ */ new Date(`${date}T12:00:00`) : void 0
  );
  const triggerRef = (0, import_react22.useRef)(null);
  const handleDateSelect = (dateObj) => {
    setSelectedDate(dateObj);
    onDateChange(formatDateToInput(dateObj));
    if (!time) {
      onTimeChange(defaultTime);
    }
  };
  const handleDateInputChange = (e) => {
    const value = e.target.value;
    if (value.includes("T")) {
      const [datePart, timePart] = value.split("T");
      onDateChange(datePart);
      if (timePart) {
        onTimeChange(timePart);
      }
    } else {
      onDateChange(value);
    }
    if (value) {
      const dateValue = value.includes("T") ? value : `${value}T12:00:00`;
      const dateObj = new Date(dateValue);
      if (!Number.isNaN(dateObj.getTime())) {
        setSelectedDate(dateObj);
      }
    }
  };
  const handleTimeChange = (e) => {
    onTimeChange(e.target.value);
  };
  const inputValue = date ? `${date}T${time || defaultTime}` : "";
  return /* @__PURE__ */ (0, import_jsx_runtime40.jsxs)(
    DropdownMenu_default,
    {
      open: !disabled && isCalendarOpen,
      onOpenChange: (open) => {
        if (!disabled) {
          setIsCalendarOpen(open);
        }
      },
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime40.jsx)(
          DropdownMenuTrigger,
          {
            className,
            ref: triggerRef,
            disabled,
            children: /* @__PURE__ */ (0, import_jsx_runtime40.jsx)(
              Input_default,
              {
                label,
                type: "datetime-local",
                placeholder: "00/00/0000",
                value: inputValue,
                onChange: handleDateInputChange,
                variant: "rounded",
                errorMessage,
                disabled,
                "data-testid": testId ? `${testId}-input` : void 0,
                iconRight: /* @__PURE__ */ (0, import_jsx_runtime40.jsx)(import_phosphor_react18.CalendarBlank, { size: 14 }),
                className: "[&::-webkit-calendar-picker-indicator]:hidden"
              }
            )
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime40.jsxs)(
          DropdownMenuContent,
          {
            align: "start",
            className: "p-0 z-[100]",
            portal: true,
            triggerRef,
            children: [
              /* @__PURE__ */ (0, import_jsx_runtime40.jsx)(
                Calendar_default,
                {
                  variant: "selection",
                  selectedDate,
                  onDateSelect: handleDateSelect,
                  showActivities: false
                }
              ),
              /* @__PURE__ */ (0, import_jsx_runtime40.jsx)("div", { className: "p-3 border-t border-border-200", children: /* @__PURE__ */ (0, import_jsx_runtime40.jsx)(
                Input_default,
                {
                  label: timeLabel,
                  type: "time",
                  value: time || defaultTime,
                  onChange: handleTimeChange,
                  variant: "rounded",
                  "data-testid": testId ? `${testId}-time` : void 0
                }
              ) })
            ]
          }
        )
      ]
    }
  );
};
var DateTimeInput_default = DateTimeInput;

// src/components/CorrectActivityModal/CorrectActivityModal.tsx
var import_react29 = require("react");
var import_phosphor_react23 = require("phosphor-react");

// src/components/Alternative/Alternative.tsx
var import_phosphor_react19 = require("phosphor-react");
var import_react23 = require("react");
var import_jsx_runtime41 = require("react/jsx-runtime");
var AlternativesList = ({
  alternatives,
  name,
  defaultValue,
  value,
  onValueChange,
  disabled = false,
  layout = "default",
  className = "",
  mode = "interactive",
  selectedValue
}) => {
  const uniqueId = (0, import_react23.useId)();
  const groupName = name || `alternatives-${uniqueId}`;
  const [actualValue, setActualValue] = (0, import_react23.useState)(value);
  const isReadonly = mode === "readonly";
  const getStatusStyles2 = (status, isReadonly2) => {
    const hoverClass = isReadonly2 ? "" : "hover:bg-background-50";
    switch (status) {
      case "correct":
        return "bg-success-background border-success-300";
      case "incorrect":
        return "bg-error-background border-error-300";
      default:
        return `bg-background border-border-100 ${hoverClass}`;
    }
  };
  const getStatusBadge2 = (status) => {
    switch (status) {
      case "correct":
        return /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Badge_default, { variant: "solid", action: "success", iconLeft: /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(import_phosphor_react19.CheckCircle, {}), children: "Resposta correta" });
      case "incorrect":
        return /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Badge_default, { variant: "solid", action: "error", iconLeft: /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(import_phosphor_react19.XCircle, {}), children: "Resposta incorreta" });
      default:
        return null;
    }
  };
  const getLayoutClasses = () => {
    switch (layout) {
      case "compact":
        return "gap-2";
      case "detailed":
        return "gap-4";
      default:
        return "gap-3.5";
    }
  };
  const renderReadonlyAlternative = (alternative) => {
    const alternativeId = alternative.value;
    const isUserSelected = selectedValue === alternative.value;
    const isCorrectAnswer = alternative.status === "correct";
    let displayStatus = void 0;
    if (isUserSelected && !isCorrectAnswer) {
      displayStatus = "incorrect";
    } else if (isCorrectAnswer) {
      displayStatus = "correct";
    }
    const statusStyles = getStatusStyles2(displayStatus, true);
    const statusBadge = getStatusBadge2(displayStatus);
    const renderRadio = () => {
      const radioClasses = `w-6 h-6 rounded-full border-2 cursor-default transition-all duration-200 flex items-center justify-center ${isUserSelected ? "border-primary-950 bg-background" : "border-border-400 bg-background"}`;
      const dotClasses = "w-3 h-3 rounded-full bg-primary-950 transition-all duration-200";
      return /* @__PURE__ */ (0, import_jsx_runtime41.jsx)("div", { className: radioClasses, children: isUserSelected && /* @__PURE__ */ (0, import_jsx_runtime41.jsx)("div", { className: dotClasses }) });
    };
    if (layout === "detailed") {
      return /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(
        "div",
        {
          className: cn(
            "border-2 rounded-lg p-4 w-full",
            statusStyles,
            alternative.disabled ? "opacity-50" : ""
          ),
          children: /* @__PURE__ */ (0, import_jsx_runtime41.jsxs)("div", { className: "flex items-start justify-between gap-3", children: [
            /* @__PURE__ */ (0, import_jsx_runtime41.jsxs)("div", { className: "flex items-start gap-3 flex-1", children: [
              /* @__PURE__ */ (0, import_jsx_runtime41.jsx)("div", { className: "mt-1", children: renderRadio() }),
              /* @__PURE__ */ (0, import_jsx_runtime41.jsxs)("div", { className: "flex-1", children: [
                /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(
                  "p",
                  {
                    className: cn(
                      "block font-medium",
                      selectedValue === alternative.value || statusBadge ? "text-text-950" : "text-text-600"
                    ),
                    children: alternative.label
                  }
                ),
                alternative.description && /* @__PURE__ */ (0, import_jsx_runtime41.jsx)("p", { className: "text-sm text-text-600 mt-1", children: alternative.description })
              ] })
            ] }),
            statusBadge && /* @__PURE__ */ (0, import_jsx_runtime41.jsx)("div", { className: "flex-shrink-0", children: statusBadge })
          ] })
        },
        alternativeId
      );
    }
    return /* @__PURE__ */ (0, import_jsx_runtime41.jsxs)(
      "div",
      {
        className: cn(
          "flex flex-row justify-between items-start gap-2 p-2 rounded-lg w-full",
          statusStyles,
          alternative.disabled ? "opacity-50" : ""
        ),
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime41.jsxs)("div", { className: "flex items-center gap-2 flex-1", children: [
            renderRadio(),
            /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(
              "span",
              {
                className: cn(
                  "flex-1",
                  selectedValue === alternative.value || statusBadge ? "text-text-950" : "text-text-600"
                ),
                children: alternative.label
              }
            )
          ] }),
          statusBadge && /* @__PURE__ */ (0, import_jsx_runtime41.jsx)("div", { className: "flex-shrink-0", children: statusBadge })
        ]
      },
      alternativeId
    );
  };
  if (isReadonly) {
    return /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(
      "div",
      {
        className: cn("flex flex-col", getLayoutClasses(), "w-full", className),
        children: alternatives.map(
          (alternative) => renderReadonlyAlternative(alternative)
        )
      }
    );
  }
  return /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(
    RadioGroup,
    {
      name: groupName,
      defaultValue,
      value,
      onValueChange: (value2) => {
        setActualValue(value2);
        onValueChange?.(value2);
      },
      disabled,
      className: cn("flex flex-col", getLayoutClasses(), className),
      children: alternatives.map((alternative, index) => {
        const alternativeId = alternative.value || `alt-${index}`;
        const statusStyles = getStatusStyles2(alternative.status, false);
        const statusBadge = getStatusBadge2(alternative.status);
        if (layout === "detailed") {
          return /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(
            "div",
            {
              className: cn(
                "border-2 rounded-lg p-4 transition-all",
                statusStyles,
                alternative.disabled ? "opacity-50 cursor-not-allowed" : "cursor-pointer"
              ),
              children: /* @__PURE__ */ (0, import_jsx_runtime41.jsxs)("div", { className: "flex items-start justify-between gap-3", children: [
                /* @__PURE__ */ (0, import_jsx_runtime41.jsxs)("div", { className: "flex items-start gap-3 flex-1", children: [
                  /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(
                    RadioGroupItem,
                    {
                      value: alternative.value,
                      id: alternativeId,
                      disabled: alternative.disabled,
                      className: "mt-1"
                    }
                  ),
                  /* @__PURE__ */ (0, import_jsx_runtime41.jsxs)("div", { className: "flex-1", children: [
                    /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(
                      "label",
                      {
                        htmlFor: alternativeId,
                        className: cn(
                          "block font-medium",
                          actualValue === alternative.value ? "text-text-950" : "text-text-600",
                          alternative.disabled ? "cursor-not-allowed" : "cursor-pointer"
                        ),
                        children: alternative.label
                      }
                    ),
                    alternative.description && /* @__PURE__ */ (0, import_jsx_runtime41.jsx)("p", { className: "text-sm text-text-600 mt-1", children: alternative.description })
                  ] })
                ] }),
                statusBadge && /* @__PURE__ */ (0, import_jsx_runtime41.jsx)("div", { className: "flex-shrink-0", children: statusBadge })
              ] })
            },
            alternativeId
          );
        }
        return /* @__PURE__ */ (0, import_jsx_runtime41.jsxs)(
          "div",
          {
            className: cn(
              "flex flex-row justify-between gap-2 items-start p-2 rounded-lg transition-all",
              statusStyles,
              alternative.disabled ? "opacity-50 cursor-not-allowed" : ""
            ),
            children: [
              /* @__PURE__ */ (0, import_jsx_runtime41.jsxs)("div", { className: "flex items-center gap-2 flex-1", children: [
                /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(
                  RadioGroupItem,
                  {
                    value: alternative.value,
                    id: alternativeId,
                    disabled: alternative.disabled
                  }
                ),
                /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(
                  "label",
                  {
                    htmlFor: alternativeId,
                    className: cn(
                      "flex-1",
                      actualValue === alternative.value ? "text-text-950" : "text-text-600",
                      alternative.disabled ? "cursor-not-allowed" : "cursor-pointer"
                    ),
                    children: alternative.label
                  }
                )
              ] }),
              statusBadge && /* @__PURE__ */ (0, import_jsx_runtime41.jsx)("div", { className: "flex-shrink-0", children: statusBadge })
            ]
          },
          alternativeId
        );
      })
    }
  );
};
var HeaderAlternative = (0, import_react23.forwardRef)(
  ({ className, title, subTitle, content, ...props }, ref) => {
    return /* @__PURE__ */ (0, import_jsx_runtime41.jsxs)(
      "div",
      {
        ref,
        className: cn(
          "bg-background p-4 flex flex-col gap-4 rounded-xl",
          className
        ),
        ...props,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime41.jsxs)("span", { className: "flex flex-col", children: [
            /* @__PURE__ */ (0, import_jsx_runtime41.jsx)("p", { className: "text-text-950 font-bold text-lg", children: title }),
            /* @__PURE__ */ (0, import_jsx_runtime41.jsx)("p", { className: "text-text-700 text-sm ", children: subTitle })
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime41.jsx)("p", { className: "text-text-950 text-md", children: content })
        ]
      }
    );
  }
);

// src/components/Accordation/Accordation.tsx
var import_react26 = require("react");

// src/components/Card/Card.tsx
var import_react25 = require("react");
var import_phosphor_react20 = require("phosphor-react");

// src/components/IconRender/IconRender.tsx
var import_react24 = require("react");
var PhosphorIcons = __toESM(require("phosphor-react"));

// src/assets/icons/subjects/ChatPT.tsx
var import_jsx_runtime42 = require("react/jsx-runtime");
var ChatPT = ({ size, color }) => /* @__PURE__ */ (0, import_jsx_runtime42.jsxs)(
  "svg",
  {
    width: size,
    height: size,
    viewBox: "0 0 32 32",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    children: [
      /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(
        "path",
        {
          d: "M27 6H5.00004C4.4696 6 3.9609 6.21071 3.58582 6.58579C3.21075 6.96086 3.00004 7.46957 3.00004 8V28C2.99773 28.3814 3.10562 28.7553 3.31074 29.0768C3.51585 29.3984 3.80947 29.6538 4.15629 29.8125C4.42057 29.9356 4.7085 29.9995 5.00004 30C5.46954 29.9989 5.92347 29.8315 6.28129 29.5275L6.29254 29.5187L10.375 26H27C27.5305 26 28.0392 25.7893 28.4142 25.4142C28.7893 25.0391 29 24.5304 29 24V8C29 7.46957 28.7893 6.96086 28.4142 6.58579C28.0392 6.21071 27.5305 6 27 6ZM27 24H10C9.75992 24.0001 9.52787 24.0866 9.34629 24.2437L5.00004 28V8H27V24Z",
          fill: color
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(
        "path",
        {
          d: "M21.1758 12V20.5312H19.7168V12H21.1758ZM23.8535 12V13.1719H17.0625V12H23.8535Z",
          fill: color
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(
        "path",
        {
          d: "M13.2402 17.3496H11.0195V16.1836H13.2402C13.627 16.1836 13.9395 16.1211 14.1777 15.9961C14.416 15.8711 14.5898 15.6992 14.6992 15.4805C14.8125 15.2578 14.8691 15.0039 14.8691 14.7188C14.8691 14.4492 14.8125 14.1973 14.6992 13.9629C14.5898 13.7246 14.416 13.5332 14.1777 13.3887C13.9395 13.2441 13.627 13.1719 13.2402 13.1719H11.4707V20.5312H10V12H13.2402C13.9004 12 14.4609 12.1172 14.9219 12.3516C15.3867 12.582 15.7402 12.9023 15.9824 13.3125C16.2246 13.7188 16.3457 14.1836 16.3457 14.707C16.3457 15.2578 16.2246 15.7305 15.9824 16.125C15.7402 16.5195 15.3867 16.8223 14.9219 17.0332C14.4609 17.2441 13.9004 17.3496 13.2402 17.3496Z",
          fill: color
        }
      )
    ]
  }
);

// src/assets/icons/subjects/ChatEN.tsx
var import_jsx_runtime43 = require("react/jsx-runtime");
var ChatEN = ({ size, color }) => /* @__PURE__ */ (0, import_jsx_runtime43.jsxs)(
  "svg",
  {
    width: size,
    height: size,
    viewBox: "0 0 32 32",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    children: [
      /* @__PURE__ */ (0, import_jsx_runtime43.jsx)(
        "path",
        {
          d: "M27 6H5.00004C4.4696 6 3.9609 6.21071 3.58582 6.58579C3.21075 6.96086 3.00004 7.46957 3.00004 8V28C2.99773 28.3814 3.10562 28.7553 3.31074 29.0768C3.51585 29.3984 3.80947 29.6538 4.15629 29.8125C4.42057 29.9356 4.7085 29.9995 5.00004 30C5.46954 29.9989 5.92347 29.8315 6.28129 29.5275L6.29254 29.5187L10.375 26H27C27.5305 26 28.0392 25.7893 28.4142 25.4142C28.7893 25.0391 29 24.5304 29 24V8C29 7.46957 28.7893 6.96086 28.4142 6.58579C28.0392 6.21071 27.5305 6 27 6ZM27 24H10C9.75992 24.0001 9.52787 24.0866 9.34629 24.2437L5.00004 28V8H27V24Z",
          fill: color
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime43.jsx)(
        "path",
        {
          d: "M22.5488 12V20.5312H21.0781L17.252 14.4199V20.5312H15.7812V12H17.252L21.0898 18.123V12H22.5488Z",
          fill: color
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime43.jsx)(
        "path",
        {
          d: "M14.584 19.3652V20.5312H10.0547V19.3652H14.584ZM10.4707 12V20.5312H9V12H10.4707ZM13.9922 15.5625V16.7109H10.0547V15.5625H13.9922ZM14.5547 12V13.1719H10.0547V12H14.5547Z",
          fill: color
        }
      )
    ]
  }
);

// src/assets/icons/subjects/ChatES.tsx
var import_jsx_runtime44 = require("react/jsx-runtime");
var ChatES = ({ size, color }) => /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(
  "svg",
  {
    width: size,
    height: size,
    viewBox: "0 0 32 32",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    children: [
      /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(
        "path",
        {
          d: "M27 6H5.00004C4.4696 6 3.9609 6.21071 3.58582 6.58579C3.21075 6.96086 3.00004 7.46957 3.00004 8V28C2.99773 28.3814 3.10562 28.7553 3.31074 29.0768C3.51585 29.3984 3.80947 29.6538 4.15629 29.8125C4.42057 29.9356 4.7085 29.9995 5.00004 30C5.46954 29.9989 5.92347 29.8315 6.28129 29.5275L6.29254 29.5187L10.375 26H27C27.5305 26 28.0392 25.7893 28.4142 25.4142C28.7893 25.0391 29 24.5304 29 24V8C29 7.46957 28.7893 6.96086 28.4142 6.58579C28.0392 6.21071 27.5305 6 27 6ZM27 24H10C9.75992 24.0001 9.52787 24.0866 9.34629 24.2437L5.00004 28V8H27V24Z",
          fill: color
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(
        "path",
        {
          d: "M21.1426 17.8027C21.1426 17.627 21.1152 17.4707 21.0605 17.334C21.0098 17.1973 20.918 17.0723 20.7852 16.959C20.6523 16.8457 20.4648 16.7363 20.2227 16.6309C19.9844 16.5215 19.6797 16.4102 19.3086 16.2969C18.9023 16.1719 18.5273 16.0332 18.1836 15.8809C17.8438 15.7246 17.5469 15.5449 17.293 15.3418C17.0391 15.1348 16.8418 14.8984 16.7012 14.6328C16.5605 14.3633 16.4902 14.0527 16.4902 13.7012C16.4902 13.3535 16.5625 13.0371 16.707 12.752C16.8555 12.4668 17.0645 12.2207 17.334 12.0137C17.6074 11.8027 17.9297 11.6406 18.3008 11.5273C18.6719 11.4102 19.082 11.3516 19.5312 11.3516C20.1641 11.3516 20.709 11.4688 21.166 11.7031C21.627 11.9375 21.9805 12.252 22.2266 12.6465C22.4766 13.041 22.6016 13.4766 22.6016 13.9531H21.1426C21.1426 13.6719 21.082 13.4238 20.9609 13.209C20.8438 12.9902 20.6641 12.8184 20.4219 12.6934C20.1836 12.5684 19.8809 12.5059 19.5137 12.5059C19.166 12.5059 18.877 12.5586 18.6465 12.6641C18.416 12.7695 18.2441 12.9121 18.1309 13.0918C18.0176 13.2715 17.9609 13.4746 17.9609 13.7012C17.9609 13.8613 17.998 14.0078 18.0723 14.1406C18.1465 14.2695 18.2598 14.3906 18.4121 14.5039C18.5645 14.6133 18.7559 14.7168 18.9863 14.8145C19.2168 14.9121 19.4883 15.0059 19.8008 15.0957C20.2734 15.2363 20.6855 15.3926 21.0371 15.5645C21.3887 15.7324 21.6816 15.9238 21.916 16.1387C22.1504 16.3535 22.3262 16.5977 22.4434 16.8711C22.5605 17.1406 22.6191 17.4473 22.6191 17.791C22.6191 18.1504 22.5469 18.4746 22.4023 18.7637C22.2578 19.0488 22.0508 19.293 21.7812 19.4961C21.5156 19.6953 21.1953 19.8496 20.8203 19.959C20.4492 20.0645 20.0352 20.1172 19.5781 20.1172C19.168 20.1172 18.7637 20.0625 18.3652 19.9531C17.9707 19.8438 17.6113 19.6777 17.2871 19.4551C16.9629 19.2285 16.7051 18.9473 16.5137 18.6113C16.3223 18.2715 16.2266 17.875 16.2266 17.4219H17.6973C17.6973 17.6992 17.7441 17.9355 17.8379 18.1309C17.9355 18.3262 18.0703 18.4863 18.2422 18.6113C18.4141 18.7324 18.6133 18.8223 18.8398 18.8809C19.0703 18.9395 19.3164 18.9688 19.5781 18.9688C19.9219 18.9688 20.209 18.9199 20.4395 18.8223C20.6738 18.7246 20.8496 18.5879 20.9668 18.4121C21.084 18.2363 21.1426 18.0332 21.1426 17.8027Z",
          fill: color
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(
        "path",
        {
          d: "M15.4512 18.834V20H10.9219V18.834H15.4512ZM11.3379 11.4688V20H9.86719V11.4688H11.3379ZM14.8594 15.0312V16.1797H10.9219V15.0312H14.8594ZM15.4219 11.4688V12.6406H10.9219V11.4688H15.4219Z",
          fill: color
        }
      )
    ]
  }
);

// src/components/IconRender/IconRender.tsx
var import_jsx_runtime45 = require("react/jsx-runtime");
var IconRender = ({
  iconName,
  color = "#000000",
  size = 24,
  weight = "regular"
}) => {
  if (typeof iconName === "string") {
    switch (iconName) {
      case "Chat_PT":
        return /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(ChatPT, { size, color });
      case "Chat_EN":
        return /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(ChatEN, { size, color });
      case "Chat_ES":
        return /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(ChatES, { size, color });
      default: {
        const IconComponent = PhosphorIcons[iconName] || PhosphorIcons.Question;
        return /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(IconComponent, { size, color, weight });
      }
    }
  } else {
    return (0, import_react24.cloneElement)(iconName, {
      size,
      color: "currentColor"
    });
  }
};
var IconRender_default = IconRender;

// src/components/Card/Card.tsx
var import_jsx_runtime46 = require("react/jsx-runtime");
var CARD_BASE_CLASSES = {
  default: "w-full bg-background border border-border-50 rounded-xl",
  compact: "w-full bg-background border border-border-50 rounded-lg",
  minimal: "w-full bg-background border border-border-100 rounded-md"
};
var CARD_PADDING_CLASSES = {
  none: "",
  small: "p-2",
  medium: "p-4",
  large: "p-6"
};
var CARD_MIN_HEIGHT_CLASSES = {
  none: "",
  small: "min-h-16",
  medium: "min-h-20",
  large: "min-h-24"
};
var CARD_LAYOUT_CLASSES = {
  horizontal: "flex flex-row",
  vertical: "flex flex-col"
};
var CARD_CURSOR_CLASSES = {
  default: "",
  pointer: "cursor-pointer"
};
var CardBase = (0, import_react25.forwardRef)(
  ({
    children,
    variant = "default",
    layout = "horizontal",
    padding = "medium",
    minHeight = "medium",
    cursor = "default",
    className = "",
    ...props
  }, ref) => {
    const baseClasses = CARD_BASE_CLASSES[variant];
    const paddingClasses = CARD_PADDING_CLASSES[padding];
    const minHeightClasses = CARD_MIN_HEIGHT_CLASSES[minHeight];
    const layoutClasses = CARD_LAYOUT_CLASSES[layout];
    const cursorClasses = CARD_CURSOR_CLASSES[cursor];
    return /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
      "div",
      {
        ref,
        className: cn(
          baseClasses,
          paddingClasses,
          minHeightClasses,
          layoutClasses,
          cursorClasses,
          className
        ),
        ...props,
        children
      }
    );
  }
);
var ACTION_CARD_CLASSES = {
  warning: "bg-warning-background",
  success: "bg-success-200",
  error: "bg-error-100",
  info: "bg-info-background"
};
var ACTION_ICON_CLASSES = {
  warning: "bg-warning-300 text-text",
  success: "bg-indicator-positive text-text-950",
  error: "bg-indicator-negative text-text",
  info: "bg-info-500 text-text"
};
var ACTION_SUBTITLE_CLASSES = {
  warning: "text-warning-600",
  success: "text-success-700",
  error: "text-error-700",
  info: "text-info-700"
};
var ACTION_HEADER_CLASSES = {
  warning: "text-warning-300",
  success: "text-success-300",
  error: "text-error-300",
  info: "text-info-300"
};
var CardActivitiesResults = (0, import_react25.forwardRef)(
  ({
    icon,
    title,
    subTitle,
    header,
    extended = false,
    action = "success",
    description,
    className,
    ...props
  }, ref) => {
    const actionCardClasses = ACTION_CARD_CLASSES[action];
    const actionIconClasses = ACTION_ICON_CLASSES[action];
    const actionSubTitleClasses = ACTION_SUBTITLE_CLASSES[action];
    const actionHeaderClasses = ACTION_HEADER_CLASSES[action];
    return /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)(
      "div",
      {
        ref,
        className: cn(
          "w-full flex flex-col border border-border-50  bg-background rounded-xl",
          className
        ),
        ...props,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)(
            "div",
            {
              className: cn(
                "flex flex-col gap-1 items-center justify-center p-4",
                actionCardClasses,
                extended ? "rounded-t-xl" : "rounded-xl"
              ),
              children: [
                /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
                  "span",
                  {
                    className: cn(
                      "size-7.5 rounded-full flex items-center justify-center",
                      actionIconClasses
                    ),
                    children: icon
                  }
                ),
                /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
                  Text_default,
                  {
                    size: "2xs",
                    weight: "medium",
                    className: "text-text-800 uppercase truncate",
                    children: title
                  }
                ),
                /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
                  "p",
                  {
                    className: cn("text-lg font-bold truncate", actionSubTitleClasses),
                    children: subTitle
                  }
                )
              ]
            }
          ),
          extended && /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)("div", { className: "flex flex-col items-center gap-2.5 pb-9.5 pt-2.5", children: [
            /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
              "p",
              {
                className: cn(
                  "text-2xs font-medium uppercase truncate",
                  actionHeaderClasses
                ),
                children: header
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Badge_default, { size: "large", action: "info", children: description })
          ] })
        ]
      }
    );
  }
);
var CardQuestions = (0, import_react25.forwardRef)(
  ({
    header,
    state = "undone",
    className,
    onClickButton,
    valueButton,
    ...props
  }, ref) => {
    const isDone = state === "done";
    const stateLabel = isDone ? "Realizado" : "N\xE3o Realizado";
    const buttonLabel = isDone ? "Ver Resultado" : "Responder";
    return /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)(
      CardBase,
      {
        ref,
        layout: "horizontal",
        padding: "medium",
        minHeight: "medium",
        className: cn("justify-between gap-4", className),
        ...props,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)("section", { className: "flex flex-col gap-1 flex-1 min-w-0", children: [
            /* @__PURE__ */ (0, import_jsx_runtime46.jsx)("p", { className: "font-bold text-xs text-text-950 truncate", children: header }),
            /* @__PURE__ */ (0, import_jsx_runtime46.jsx)("div", { className: "flex flex-row gap-6 items-center", children: /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
              Badge_default,
              {
                size: "medium",
                variant: "solid",
                action: isDone ? "success" : "error",
                children: stateLabel
              }
            ) })
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime46.jsx)("span", { className: "flex-shrink-0", children: /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
            Button_default,
            {
              size: "extra-small",
              onClick: () => onClickButton?.(valueButton),
              className: "min-w-fit",
              children: buttonLabel
            }
          ) })
        ]
      }
    );
  }
);
var CardProgress = (0, import_react25.forwardRef)(
  ({
    header,
    subhead,
    initialDate,
    endDate,
    progress = 0,
    direction = "horizontal",
    icon,
    color = "#B7DFFF",
    progressVariant = "blue",
    showDates = true,
    className,
    ...props
  }, ref) => {
    const isHorizontal = direction === "horizontal";
    const contentComponent = {
      horizontal: /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)(import_jsx_runtime46.Fragment, { children: [
        showDates && /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)("div", { className: "flex flex-row gap-6 items-center", children: [
          initialDate && /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)("span", { className: "flex flex-row gap-1 items-center text-2xs", children: [
            /* @__PURE__ */ (0, import_jsx_runtime46.jsx)("p", { className: "text-text-800 font-semibold", children: "In\xEDcio" }),
            /* @__PURE__ */ (0, import_jsx_runtime46.jsx)("p", { className: "text-text-600", children: initialDate })
          ] }),
          endDate && /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)("span", { className: "flex flex-row gap-1 items-center text-2xs", children: [
            /* @__PURE__ */ (0, import_jsx_runtime46.jsx)("p", { className: "text-text-800 font-semibold", children: "Fim" }),
            /* @__PURE__ */ (0, import_jsx_runtime46.jsx)("p", { className: "text-text-600", children: endDate })
          ] })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)("span", { className: "grid grid-cols-[1fr_auto] items-center gap-2", children: [
          /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
            ProgressBar_default,
            {
              size: "small",
              value: progress,
              variant: progressVariant,
              "data-testid": "progress-bar"
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)(
            Text_default,
            {
              size: "xs",
              weight: "medium",
              className: cn(
                "text-text-950 leading-none tracking-normal text-center flex-none"
              ),
              children: [
                Math.round(progress),
                "%"
              ]
            }
          )
        ] })
      ] }),
      vertical: /* @__PURE__ */ (0, import_jsx_runtime46.jsx)("p", { className: "text-sm text-text-800", children: subhead })
    };
    return /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)(
      CardBase,
      {
        ref,
        layout: isHorizontal ? "horizontal" : "vertical",
        padding: "none",
        minHeight: "medium",
        cursor: "pointer",
        className: cn(isHorizontal ? "h-20" : "", className),
        ...props,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
            "div",
            {
              className: cn(
                "flex justify-center items-center [&>svg]:size-6 text-text-950",
                isHorizontal ? "min-w-[80px] min-h-[80px] rounded-l-xl" : "min-h-[50px] w-full rounded-t-xl",
                !color.startsWith("#") ? `${color}` : ""
              ),
              style: color.startsWith("#") ? { backgroundColor: color } : void 0,
              "data-testid": "icon-container",
              children: icon
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)(
            "div",
            {
              className: cn(
                "p-4 flex flex-col justify-between w-full h-full",
                !isHorizontal && "gap-4"
              ),
              children: [
                /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Text_default, { size: "sm", weight: "bold", className: "text-text-950 truncate", children: header }),
                contentComponent[direction]
              ]
            }
          )
        ]
      }
    );
  }
);
var CardTopic = (0, import_react25.forwardRef)(
  ({
    header,
    subHead,
    progress,
    showPercentage = false,
    progressVariant = "blue",
    className = "",
    ...props
  }, ref) => {
    return /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)(
      CardBase,
      {
        ref,
        layout: "vertical",
        padding: "small",
        minHeight: "medium",
        cursor: "pointer",
        className: cn("justify-center gap-2  py-2 px-4", className),
        ...props,
        children: [
          subHead && /* @__PURE__ */ (0, import_jsx_runtime46.jsx)("span", { className: "text-text-600 text-2xs flex flex-row gap-1", children: subHead.map((text, index) => /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)(import_react25.Fragment, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime46.jsx)("p", { children: text }),
            index < subHead.length - 1 && /* @__PURE__ */ (0, import_jsx_runtime46.jsx)("p", { children: "\u2022" })
          ] }, `${text} - ${index}`)) }),
          /* @__PURE__ */ (0, import_jsx_runtime46.jsx)("p", { className: "text-sm text-text-950 font-bold truncate", children: header }),
          /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)("span", { className: "grid grid-cols-[1fr_auto] items-center gap-2", children: [
            /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
              ProgressBar_default,
              {
                size: "small",
                value: progress,
                variant: progressVariant,
                "data-testid": "progress-bar"
              }
            ),
            showPercentage && /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)(
              Text_default,
              {
                size: "xs",
                weight: "medium",
                className: cn(
                  "text-text-950 leading-none tracking-normal text-center flex-none"
                ),
                children: [
                  Math.round(progress),
                  "%"
                ]
              }
            )
          ] })
        ]
      }
    );
  }
);
var CardPerformance = (0, import_react25.forwardRef)(
  ({
    header,
    progress,
    description = "Sem dados ainda! Voc\xEA ainda n\xE3o fez um question\xE1rio neste assunto.",
    actionVariant = "button",
    progressVariant = "blue",
    labelProgress = "",
    className = "",
    onClickButton,
    valueButton,
    ...props
  }, ref) => {
    const hasProgress = progress !== void 0;
    return /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)(
      CardBase,
      {
        ref,
        layout: "horizontal",
        padding: "medium",
        minHeight: "none",
        className: cn(
          actionVariant == "caret" ? "cursor-pointer" : "",
          className
        ),
        onClick: () => actionVariant == "caret" && onClickButton?.(valueButton),
        ...props,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)("div", { className: "w-full flex flex-col justify-between gap-2", children: [
            /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)("div", { className: "flex flex-row justify-between items-center gap-2", children: [
              /* @__PURE__ */ (0, import_jsx_runtime46.jsx)("p", { className: "text-lg font-bold text-text-950 truncate flex-1 min-w-0", children: header }),
              actionVariant === "button" && /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
                Button_default,
                {
                  variant: "outline",
                  size: "extra-small",
                  onClick: () => onClickButton?.(valueButton),
                  className: "min-w-fit flex-shrink-0",
                  children: "Ver Aula"
                }
              )
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime46.jsx)("div", { className: "w-full", children: hasProgress ? /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
              ProgressBar_default,
              {
                value: progress,
                label: `${progress}% ${labelProgress}`,
                variant: progressVariant
              }
            ) : /* @__PURE__ */ (0, import_jsx_runtime46.jsx)("p", { className: "text-xs text-text-600 truncate", children: description }) })
          ] }),
          actionVariant == "caret" && /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
            import_phosphor_react20.CaretRight,
            {
              className: "size-4.5 text-text-800 cursor-pointer",
              "data-testid": "caret-icon"
            }
          )
        ]
      }
    );
  }
);
var CardResults = (0, import_react25.forwardRef)(
  ({
    header,
    correct_answers,
    incorrect_answers,
    icon,
    direction = "col",
    color = "#B7DFFF",
    className,
    ...props
  }, ref) => {
    const isRow = direction == "row";
    return /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)(
      CardBase,
      {
        ref,
        layout: "horizontal",
        padding: "none",
        minHeight: "medium",
        className: cn("items-stretch cursor-pointer pr-4", className),
        ...props,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
            "div",
            {
              className: cn(
                "flex justify-center items-center [&>svg]:size-8 text-text-950 min-w-20 max-w-20 min-h-full rounded-l-xl"
              ),
              style: {
                backgroundColor: color
              },
              children: /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(IconRender_default, { iconName: icon, color: "currentColor", size: 20 })
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)("div", { className: "w-full flex flex-row justify-between items-center", children: [
            /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)(
              "div",
              {
                className: cn(
                  "p-4 flex flex-wrap justify-between w-full h-full",
                  isRow ? "flex-row items-center gap-2" : "flex-col"
                ),
                children: [
                  /* @__PURE__ */ (0, import_jsx_runtime46.jsx)("p", { className: "text-sm font-bold text-text-950 flex-1", children: header }),
                  /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)("span", { className: "flex flex-wrap flex-row gap-1 items-center", children: [
                    /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)(
                      Badge_default,
                      {
                        action: "success",
                        variant: "solid",
                        size: "large",
                        iconLeft: /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(import_phosphor_react20.CheckCircle, {}),
                        children: [
                          correct_answers,
                          " Corretas"
                        ]
                      }
                    ),
                    /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)(
                      Badge_default,
                      {
                        action: "error",
                        variant: "solid",
                        size: "large",
                        iconLeft: /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(import_phosphor_react20.XCircle, {}),
                        children: [
                          incorrect_answers,
                          " Incorretas"
                        ]
                      }
                    )
                  ] })
                ]
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(import_phosphor_react20.CaretRight, { className: "min-w-6 min-h-6 text-text-800" })
          ] })
        ]
      }
    );
  }
);
var CardStatus = (0, import_react25.forwardRef)(
  ({ header, className, status, label, ...props }, ref) => {
    const getLabelBadge = (status2) => {
      switch (status2) {
        case "correct":
          return "Correta";
        case "incorrect":
          return "Incorreta";
        case "unanswered":
          return "Em branco";
        case "pending":
          return "Avalia\xE7\xE3o pendente";
        default:
          return "Em branco";
      }
    };
    const getIconBadge = (status2) => {
      switch (status2) {
        case "correct":
          return /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(import_phosphor_react20.CheckCircle, {});
        case "incorrect":
          return /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(import_phosphor_react20.XCircle, {});
        case "pending":
          return /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(import_phosphor_react20.Clock, {});
        default:
          return /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(import_phosphor_react20.XCircle, {});
      }
    };
    const getActionBadge = (status2) => {
      switch (status2) {
        case "correct":
          return "success";
        case "incorrect":
          return "error";
        case "pending":
          return "info";
        default:
          return "info";
      }
    };
    return /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
      CardBase,
      {
        ref,
        layout: "horizontal",
        padding: "medium",
        minHeight: "medium",
        className: cn("items-center cursor-pointer", className),
        ...props,
        children: /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)("div", { className: "flex justify-between w-full h-full flex-row items-center gap-2", children: [
          /* @__PURE__ */ (0, import_jsx_runtime46.jsx)("p", { className: "text-sm font-bold text-text-950 truncate flex-1 min-w-0", children: header }),
          /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)("span", { className: "flex flex-row gap-1 items-center flex-shrink-0", children: [
            status && /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
              Badge_default,
              {
                action: getActionBadge(status),
                variant: "solid",
                size: "medium",
                iconLeft: getIconBadge(status),
                children: getLabelBadge(status)
              }
            ),
            label && /* @__PURE__ */ (0, import_jsx_runtime46.jsx)("p", { className: "text-sm text-text-800", children: label })
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(import_phosphor_react20.CaretRight, { className: "min-w-6 min-h-6 text-text-800 cursor-pointer flex-shrink-0 ml-2" })
        ] })
      }
    );
  }
);
var CardSettings = (0, import_react25.forwardRef)(
  ({ header, className, icon, ...props }, ref) => {
    return /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)(
      CardBase,
      {
        ref,
        layout: "horizontal",
        padding: "small",
        minHeight: "none",
        className: cn(
          "border-none items-center gap-2 text-text-700",
          className
        ),
        ...props,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime46.jsx)("span", { className: "[&>svg]:size-6", children: icon }),
          /* @__PURE__ */ (0, import_jsx_runtime46.jsx)("p", { className: "w-full text-sm truncate", children: header }),
          /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(import_phosphor_react20.CaretRight, { size: 24, className: "cursor-pointer" })
        ]
      }
    );
  }
);
var CardSupport = (0, import_react25.forwardRef)(
  ({ header, className, direction = "col", children, ...props }, ref) => {
    return /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)(
      CardBase,
      {
        ref,
        layout: "horizontal",
        padding: "medium",
        minHeight: "none",
        className: cn(
          "border-none items-center gap-2 text-text-700",
          className
        ),
        ...props,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)(
            "div",
            {
              className: cn(
                "w-full flex",
                direction == "col" ? "flex-col" : "flex-row items-center"
              ),
              children: [
                /* @__PURE__ */ (0, import_jsx_runtime46.jsx)("span", { className: "w-full min-w-0", children: /* @__PURE__ */ (0, import_jsx_runtime46.jsx)("p", { className: "text-sm text-text-950 font-bold truncate", children: header }) }),
                /* @__PURE__ */ (0, import_jsx_runtime46.jsx)("span", { className: "flex flex-row gap-1", children })
              ]
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(import_phosphor_react20.CaretRight, { className: "text-text-800 cursor-pointer", size: 24 })
        ]
      }
    );
  }
);
var CardForum = (0, import_react25.forwardRef)(
  ({
    title,
    content,
    comments,
    onClickComments,
    valueComments,
    onClickProfile,
    valueProfile,
    className = "",
    date,
    hour,
    ...props
  }, ref) => {
    return /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)(
      CardBase,
      {
        ref,
        layout: "horizontal",
        padding: "medium",
        minHeight: "none",
        variant: "minimal",
        className: cn("w-auto h-auto gap-3", className),
        ...props,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
            "button",
            {
              type: "button",
              "aria-label": "Ver perfil",
              onClick: () => onClickProfile?.(valueProfile),
              className: "min-w-8 h-8 rounded-full bg-background-950"
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)("div", { className: "flex flex-col gap-2 flex-1 min-w-0", children: [
            /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)("div", { className: "flex flex-row gap-1 items-center flex-wrap", children: [
              /* @__PURE__ */ (0, import_jsx_runtime46.jsx)("p", { className: "text-xs font-semibold text-primary-700 truncate", children: title }),
              /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)("p", { className: "text-xs text-text-600", children: [
                "\u2022 ",
                date,
                " \u2022 ",
                hour
              ] })
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime46.jsx)("p", { className: "text-text-950 text-sm line-clamp-2 truncate", children: content }),
            /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)(
              "button",
              {
                type: "button",
                "aria-label": "Ver coment\xE1rios",
                onClick: () => onClickComments?.(valueComments),
                className: "text-text-600 flex flex-row gap-2 items-center",
                children: [
                  /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(import_phosphor_react20.ChatCircleText, { "aria-hidden": "true", size: 16 }),
                  /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)("p", { className: "text-xs", children: [
                    comments,
                    " respostas"
                  ] })
                ]
              }
            )
          ] })
        ]
      }
    );
  }
);
var CardAudio = (0, import_react25.forwardRef)(
  ({
    src,
    title,
    onPlay,
    onPause,
    onEnded,
    onAudioTimeUpdate,
    loop = false,
    preload = "metadata",
    tracks,
    className,
    ...props
  }, ref) => {
    const [isPlaying, setIsPlaying] = (0, import_react25.useState)(false);
    const [currentTime, setCurrentTime] = (0, import_react25.useState)(0);
    const [duration, setDuration] = (0, import_react25.useState)(0);
    const [volume, setVolume] = (0, import_react25.useState)(1);
    const [showVolumeControl, setShowVolumeControl] = (0, import_react25.useState)(false);
    const [showSpeedMenu, setShowSpeedMenu] = (0, import_react25.useState)(false);
    const [playbackRate, setPlaybackRate] = (0, import_react25.useState)(1);
    const audioRef = (0, import_react25.useRef)(null);
    const volumeControlRef = (0, import_react25.useRef)(null);
    const speedMenuRef = (0, import_react25.useRef)(null);
    const formatTime3 = (time) => {
      const minutes = Math.floor(time / 60);
      const seconds = Math.floor(time % 60);
      return `${minutes}:${seconds.toString().padStart(2, "0")}`;
    };
    const handlePlayPause = () => {
      if (isPlaying) {
        audioRef.current?.pause();
        setIsPlaying(false);
        onPause?.();
      } else {
        audioRef.current?.play();
        setIsPlaying(true);
        onPlay?.();
      }
    };
    const handleTimeUpdate = () => {
      const current = audioRef.current?.currentTime ?? 0;
      const total = audioRef.current?.duration ?? 0;
      setCurrentTime(current);
      setDuration(total);
      onAudioTimeUpdate?.(current, total);
    };
    const handleLoadedMetadata = () => {
      setDuration(audioRef.current?.duration ?? 0);
    };
    const handleEnded = () => {
      setIsPlaying(false);
      setCurrentTime(0);
      onEnded?.();
    };
    const handleProgressClick = (e) => {
      const rect = e.currentTarget.getBoundingClientRect();
      const clickX = e.clientX - rect.left;
      const width = rect.width;
      const percentage = clickX / width;
      const newTime = percentage * duration;
      if (audioRef.current) {
        audioRef.current.currentTime = newTime;
      }
      setCurrentTime(newTime);
    };
    const handleVolumeChange = (e) => {
      const newVolume = parseFloat(e.target.value);
      setVolume(newVolume);
      if (audioRef.current) {
        audioRef.current.volume = newVolume;
      }
    };
    const toggleVolumeControl = () => {
      setShowVolumeControl(!showVolumeControl);
      setShowSpeedMenu(false);
    };
    const toggleSpeedMenu = () => {
      setShowSpeedMenu(!showSpeedMenu);
      setShowVolumeControl(false);
    };
    const handleSpeedChange = (speed) => {
      setPlaybackRate(speed);
      if (audioRef.current) {
        audioRef.current.playbackRate = speed;
      }
      setShowSpeedMenu(false);
    };
    const getVolumeIcon = () => {
      if (volume === 0) {
        return /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(import_phosphor_react20.SpeakerSimpleX, { size: 24 });
      }
      if (volume < 0.5) {
        return /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(import_phosphor_react20.SpeakerLow, { size: 24 });
      }
      return /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(import_phosphor_react20.SpeakerHigh, { size: 24 });
    };
    (0, import_react25.useEffect)(() => {
      const handleClickOutside = (event) => {
        if (volumeControlRef.current && !volumeControlRef.current.contains(event.target)) {
          setShowVolumeControl(false);
        }
        if (speedMenuRef.current && !speedMenuRef.current.contains(event.target)) {
          setShowSpeedMenu(false);
        }
      };
      document.addEventListener("mousedown", handleClickOutside);
      return () => {
        document.removeEventListener("mousedown", handleClickOutside);
      };
    }, []);
    return /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)(
      CardBase,
      {
        ref,
        layout: "horizontal",
        padding: "medium",
        minHeight: "none",
        className: cn(
          "flex flex-row w-auto h-14 items-center gap-2",
          className
        ),
        ...props,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
            "audio",
            {
              ref: audioRef,
              src,
              loop,
              preload,
              onTimeUpdate: handleTimeUpdate,
              onLoadedMetadata: handleLoadedMetadata,
              onEnded: handleEnded,
              "data-testid": "audio-element",
              "aria-label": title,
              children: tracks ? tracks.map((track) => /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
                "track",
                {
                  kind: track.kind,
                  src: track.src,
                  srcLang: track.srcLang,
                  label: track.label,
                  default: track.default
                },
                track.src
              )) : /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
                "track",
                {
                  kind: "captions",
                  src: "data:text/vtt;base64,",
                  srcLang: "pt",
                  label: "Sem legendas dispon\xEDveis"
                }
              )
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
            "button",
            {
              type: "button",
              onClick: handlePlayPause,
              disabled: !src,
              className: "cursor-pointer text-text-950 hover:text-primary-600 disabled:text-text-400 disabled:cursor-not-allowed",
              "aria-label": isPlaying ? "Pausar" : "Reproduzir",
              children: isPlaying ? /* @__PURE__ */ (0, import_jsx_runtime46.jsx)("div", { className: "w-6 h-6 flex items-center justify-center", children: /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)("div", { className: "flex gap-0.5", children: [
                /* @__PURE__ */ (0, import_jsx_runtime46.jsx)("div", { className: "w-1 h-4 bg-current rounded-sm" }),
                /* @__PURE__ */ (0, import_jsx_runtime46.jsx)("div", { className: "w-1 h-4 bg-current rounded-sm" })
              ] }) }) : /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(import_phosphor_react20.Play, { size: 24 })
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime46.jsx)("p", { className: "text-text-800 text-md font-medium min-w-[2.5rem]", children: formatTime3(currentTime) }),
          /* @__PURE__ */ (0, import_jsx_runtime46.jsx)("div", { className: "flex-1 relative", "data-testid": "progress-bar", children: /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
            "button",
            {
              type: "button",
              className: "w-full h-2 bg-border-100 rounded-full cursor-pointer",
              onClick: handleProgressClick,
              onKeyDown: (e) => {
                if (e.key === "Enter" || e.key === " ") {
                  e.preventDefault();
                  handleProgressClick(
                    e
                  );
                }
              },
              "aria-label": "Barra de progresso do \xE1udio",
              children: /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
                "div",
                {
                  className: "h-full bg-primary-600 rounded-full transition-all duration-100",
                  style: {
                    width: duration > 0 ? `${currentTime / duration * 100}%` : "0%"
                  }
                }
              )
            }
          ) }),
          /* @__PURE__ */ (0, import_jsx_runtime46.jsx)("p", { className: "text-text-800 text-md font-medium min-w-[2.5rem]", children: formatTime3(duration) }),
          /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)("div", { className: "relative h-6", ref: volumeControlRef, children: [
            /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
              "button",
              {
                type: "button",
                onClick: toggleVolumeControl,
                className: "cursor-pointer text-text-950 hover:text-primary-600",
                "aria-label": "Controle de volume",
                children: /* @__PURE__ */ (0, import_jsx_runtime46.jsx)("div", { className: "w-6 h-6 flex items-center justify-center", children: getVolumeIcon() })
              }
            ),
            showVolumeControl && /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
              "button",
              {
                type: "button",
                className: "absolute bottom-full right-0 mb-2 p-2 bg-background border border-border-100 rounded-lg shadow-lg focus:outline-none focus:ring-2 focus:ring-primary-500",
                onKeyDown: (e) => {
                  if (e.key === "Escape") {
                    setShowVolumeControl(false);
                  }
                },
                children: /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
                  "input",
                  {
                    type: "range",
                    min: "0",
                    max: "1",
                    step: "0.1",
                    value: volume,
                    onChange: handleVolumeChange,
                    onKeyDown: (e) => {
                      if (e.key === "ArrowUp" || e.key === "ArrowRight") {
                        e.preventDefault();
                        const newVolume = Math.min(
                          1,
                          Math.round((volume + 0.1) * 10) / 10
                        );
                        setVolume(newVolume);
                        if (audioRef.current) audioRef.current.volume = newVolume;
                      } else if (e.key === "ArrowDown" || e.key === "ArrowLeft") {
                        e.preventDefault();
                        const newVolume = Math.max(
                          0,
                          Math.round((volume - 0.1) * 10) / 10
                        );
                        setVolume(newVolume);
                        if (audioRef.current) audioRef.current.volume = newVolume;
                      }
                    },
                    className: "w-20 h-2 bg-border-100 rounded-lg appearance-none cursor-pointer",
                    style: {
                      background: `linear-gradient(to right, #3b82f6 0%, #3b82f6 ${volume * 100}%, #e5e7eb ${volume * 100}%, #e5e7eb 100%)`
                    },
                    "aria-label": "Volume",
                    "aria-valuenow": Math.round(volume * 100),
                    "aria-valuemin": 0,
                    "aria-valuemax": 100
                  }
                )
              }
            )
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)("div", { className: "relative h-6", ref: speedMenuRef, children: [
            /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
              "button",
              {
                type: "button",
                onClick: toggleSpeedMenu,
                className: "cursor-pointer text-text-950 hover:text-primary-600",
                "aria-label": "Op\xE7\xF5es de velocidade",
                children: /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(import_phosphor_react20.DotsThreeVertical, { size: 24 })
              }
            ),
            showSpeedMenu && /* @__PURE__ */ (0, import_jsx_runtime46.jsx)("div", { className: "absolute bottom-full right-0 mb-2 p-2 bg-background border border-border-100 rounded-lg shadow-lg min-w-24 z-10", children: /* @__PURE__ */ (0, import_jsx_runtime46.jsx)("div", { className: "flex flex-col gap-1", children: [
              { speed: 1, label: "1x" },
              { speed: 1.5, label: "1.5x" },
              { speed: 2, label: "2x" }
            ].map(({ speed, label }) => /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
              "button",
              {
                type: "button",
                onClick: () => handleSpeedChange(speed),
                className: cn(
                  "px-3 py-1 text-sm text-left rounded hover:bg-border-50 transition-colors",
                  playbackRate === speed ? "bg-primary-950 text-secondary-100 font-medium" : "text-text-950"
                ),
                children: label
              },
              speed
            )) }) })
          ] })
        ]
      }
    );
  }
);
var SIMULADO_BACKGROUND_CLASSES = {
  enem: "bg-exam-1",
  prova: "bg-exam-2",
  simuladao: "bg-exam-3",
  vestibular: "bg-exam-4"
};
var CardSimulado = (0, import_react25.forwardRef)(
  ({ title, duration, info, backgroundColor, className, ...props }, ref) => {
    const backgroundClass = SIMULADO_BACKGROUND_CLASSES[backgroundColor];
    return /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
      CardBase,
      {
        ref,
        layout: "horizontal",
        padding: "medium",
        minHeight: "none",
        cursor: "pointer",
        className: cn(
          `${backgroundClass} hover:shadow-soft-shadow-2 transition-shadow duration-200`,
          className
        ),
        ...props,
        children: /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)("div", { className: "flex justify-between items-center w-full gap-4", children: [
          /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)("div", { className: "flex flex-col gap-1 flex-1 min-w-0", children: [
            /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Text_default, { size: "lg", weight: "bold", className: "text-text-950 truncate", children: title }),
            /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)("div", { className: "flex items-center gap-4 text-text-700", children: [
              duration && /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)("div", { className: "flex items-center gap-1", children: [
                /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(import_phosphor_react20.Clock, { size: 16, className: "flex-shrink-0" }),
                /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Text_default, { size: "sm", children: duration })
              ] }),
              /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Text_default, { size: "sm", className: "truncate", children: info })
            ] })
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
            import_phosphor_react20.CaretRight,
            {
              size: 24,
              className: "text-text-800 flex-shrink-0",
              "data-testid": "caret-icon"
            }
          )
        ] })
      }
    );
  }
);
var CardTest = (0, import_react25.forwardRef)(
  ({
    title,
    duration,
    questionsCount,
    additionalInfo,
    selected = false,
    onSelect,
    className = "",
    ...props
  }, ref) => {
    const handleClick = () => {
      if (onSelect) {
        onSelect(!selected);
      }
    };
    const handleKeyDown = (event) => {
      if ((event.key === "Enter" || event.key === " ") && onSelect) {
        event.preventDefault();
        onSelect(!selected);
      }
    };
    const isSelectable = !!onSelect;
    const getQuestionsText = (count) => {
      const singular = count === 1 ? "quest\xE3o" : "quest\xF5es";
      return `${count} ${singular}`;
    };
    const displayInfo = questionsCount ? getQuestionsText(questionsCount) : additionalInfo || "";
    const baseClasses = "flex flex-row items-center p-4 gap-2 w-full max-w-full bg-background shadow-soft-shadow-1 rounded-xl isolate border-0 text-left";
    const interactiveClasses = isSelectable ? "cursor-pointer focus:outline-none focus:ring-2 focus:ring-primary-950 focus:ring-offset-2" : "";
    const selectedClasses = selected ? "ring-2 ring-primary-950 ring-offset-2" : "";
    if (isSelectable) {
      return /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
        "button",
        {
          ref,
          type: "button",
          className: cn(
            `${baseClasses} ${interactiveClasses} ${selectedClasses} ${className}`.trim()
          ),
          onClick: handleClick,
          onKeyDown: handleKeyDown,
          "aria-pressed": selected,
          ...props,
          children: /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)("div", { className: "flex flex-col justify-between gap-[27px] flex-grow min-h-[67px] w-full min-w-0", children: [
            /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
              Text_default,
              {
                size: "md",
                weight: "bold",
                className: "text-text-950 tracking-[0.2px] leading-[19px] truncate",
                children: title
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)("div", { className: "flex flex-row justify-start items-end gap-4 w-full", children: [
              duration && /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)("div", { className: "flex flex-row items-center gap-1 flex-shrink-0", children: [
                /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(import_phosphor_react20.Clock, { size: 16, className: "text-text-700" }),
                /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
                  Text_default,
                  {
                    size: "sm",
                    className: "text-text-700 leading-[21px] whitespace-nowrap",
                    children: duration
                  }
                )
              ] }),
              /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
                Text_default,
                {
                  size: "sm",
                  className: "text-text-700 leading-[21px] flex-grow truncate",
                  children: displayInfo
                }
              )
            ] })
          ] })
        }
      );
    }
    return /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
      "div",
      {
        ref,
        className: cn(`${baseClasses} ${className}`.trim()),
        ...props,
        children: /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)("div", { className: "flex flex-col justify-between gap-[27px] flex-grow min-h-[67px] w-full min-w-0", children: [
          /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
            Text_default,
            {
              size: "md",
              weight: "bold",
              className: "text-text-950 tracking-[0.2px] leading-[19px] truncate",
              children: title
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)("div", { className: "flex flex-row justify-start items-end gap-4 w-full", children: [
            duration && /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)("div", { className: "flex flex-row items-center gap-1 flex-shrink-0", children: [
              /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(import_phosphor_react20.Clock, { size: 16, className: "text-text-700" }),
              /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
                Text_default,
                {
                  size: "sm",
                  className: "text-text-700 leading-[21px] whitespace-nowrap",
                  children: duration
                }
              )
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
              Text_default,
              {
                size: "sm",
                className: "text-text-700 leading-[21px] flex-grow truncate min-w-0",
                children: displayInfo
              }
            )
          ] })
        ] })
      }
    );
  }
);
var SIMULATION_TYPE_STYLES = {
  enem: {
    background: "bg-exam-1",
    badge: "exam1",
    text: "Enem"
  },
  prova: {
    background: "bg-exam-2",
    badge: "exam2",
    text: "Prova"
  },
  simulado: {
    background: "bg-exam-3",
    badge: "exam3",
    text: "Simulad\xE3o"
  },
  vestibular: {
    background: "bg-exam-4",
    badge: "exam4",
    text: "Vestibular"
  }
};
var CardSimulationHistory = (0, import_react25.forwardRef)(({ data, onSimulationClick, className, ...props }, ref) => {
  return /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
    "div",
    {
      ref,
      className: cn("w-full max-w-[992px] h-auto", className),
      ...props,
      children: /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)("div", { className: "flex flex-col gap-0", children: [
        data.map((section, sectionIndex) => /* @__PURE__ */ (0, import_jsx_runtime46.jsx)("div", { className: "flex flex-col", children: /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)(
          "div",
          {
            className: cn(
              "flex flex-row justify-center items-start px-4 py-6 gap-2 w-full bg-background",
              sectionIndex === 0 ? "rounded-t-3xl" : ""
            ),
            children: [
              /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
                Text_default,
                {
                  size: "xs",
                  weight: "bold",
                  className: "text-text-800 w-11 flex-shrink-0",
                  children: section.date
                }
              ),
              /* @__PURE__ */ (0, import_jsx_runtime46.jsx)("div", { className: "flex flex-col gap-2 flex-1", children: section.simulations.map((simulation) => {
                const typeStyles = SIMULATION_TYPE_STYLES[simulation.type];
                return /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
                  CardBase,
                  {
                    layout: "horizontal",
                    padding: "medium",
                    minHeight: "none",
                    cursor: "pointer",
                    className: cn(
                      `${typeStyles.background} rounded-xl hover:shadow-soft-shadow-2 
                          transition-shadow duration-200 h-auto min-h-[61px]`
                    ),
                    onClick: () => onSimulationClick?.(simulation),
                    children: /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)("div", { className: "flex justify-between items-center w-full gap-2", children: [
                      /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)("div", { className: "flex flex-wrap flex-col justify-between sm:flex-row gap-2 flex-1 min-w-0", children: [
                        /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
                          Text_default,
                          {
                            size: "lg",
                            weight: "bold",
                            className: "text-text-950 truncate",
                            children: simulation.title
                          }
                        ),
                        /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)("div", { className: "flex items-center gap-2", children: [
                          /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
                            Badge_default,
                            {
                              variant: "examsOutlined",
                              action: typeStyles.badge,
                              size: "medium",
                              children: typeStyles.text
                            }
                          ),
                          /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Text_default, { size: "sm", className: "text-text-800 truncate", children: simulation.info })
                        ] })
                      ] }),
                      /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
                        import_phosphor_react20.CaretRight,
                        {
                          size: 24,
                          className: "text-text-800 flex-shrink-0",
                          "data-testid": "caret-icon"
                        }
                      )
                    ] })
                  },
                  simulation.id
                );
              }) })
            ]
          }
        ) }, section.date)),
        data.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime46.jsx)("div", { className: "w-full h-6 bg-background rounded-b-3xl" })
      ] })
    }
  );
});

// src/components/Accordation/Accordation.tsx
var import_phosphor_react21 = require("phosphor-react");
var import_jsx_runtime47 = require("react/jsx-runtime");
var CardAccordation = (0, import_react26.forwardRef)(
  ({
    trigger,
    children,
    className,
    defaultExpanded = false,
    expanded: controlledExpanded,
    onToggleExpanded,
    value,
    disabled = false,
    triggerClassName,
    contentClassName,
    ...props
  }, ref) => {
    const [internalExpanded, setInternalExpanded] = (0, import_react26.useState)(defaultExpanded);
    const generatedId = (0, import_react26.useId)();
    const contentId = value ? `accordion-content-${value}` : generatedId;
    const headerId = value ? `accordion-header-${value}` : `${generatedId}-header`;
    const isControlled = controlledExpanded !== void 0;
    const isExpanded = isControlled ? controlledExpanded : internalExpanded;
    (0, import_react26.useEffect)(() => {
      if (isControlled) {
        setInternalExpanded(controlledExpanded);
      }
    }, [isControlled, controlledExpanded]);
    const handleToggle = () => {
      if (disabled) return;
      const newExpanded = !isExpanded;
      if (!isControlled) {
        setInternalExpanded(newExpanded);
      }
      onToggleExpanded?.(newExpanded);
    };
    const handleKeyDown = (event) => {
      if (disabled) return;
      if (event.key === "Enter" || event.key === " ") {
        event.preventDefault();
        handleToggle();
      }
    };
    return /* @__PURE__ */ (0, import_jsx_runtime47.jsxs)(
      CardBase,
      {
        ref,
        layout: "vertical",
        padding: "none",
        minHeight: "none",
        className: cn("overflow-hidden", className),
        ...props,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime47.jsxs)(
            "button",
            {
              id: headerId,
              type: "button",
              onClick: handleToggle,
              onKeyDown: handleKeyDown,
              disabled,
              className: cn(
                "w-full cursor-pointer not-aria-expanded:rounded-xl aria-expanded:rounded-t-xl flex items-center justify-between gap-3 text-left transition-colors duration-200 focus:outline-none focus:border-2 focus:border-primary-950 focus:ring-inset px-2",
                disabled && "cursor-not-allowed text-text-400",
                triggerClassName
              ),
              "aria-expanded": isExpanded,
              "aria-controls": contentId,
              "aria-disabled": disabled,
              "data-value": value,
              children: [
                trigger,
                /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(
                  import_phosphor_react21.CaretRight,
                  {
                    size: 20,
                    className: cn(
                      "transition-transform duration-200 flex-shrink-0",
                      disabled ? "text-gray-400" : "text-text-700",
                      isExpanded ? "rotate-90" : "rotate-0"
                    ),
                    "data-testid": "accordion-caret"
                  }
                )
              ]
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(
            "section",
            {
              id: contentId,
              "aria-labelledby": headerId,
              "aria-hidden": !isExpanded,
              className: cn(
                "transition-all duration-300 ease-in-out overflow-hidden",
                isExpanded ? "max-h-screen opacity-100" : "max-h-0 opacity-0"
              ),
              "data-testid": "accordion-content",
              "data-value": value,
              children: /* @__PURE__ */ (0, import_jsx_runtime47.jsx)("div", { className: cn("p-4 pt-0", contentClassName), children })
            }
          )
        ]
      }
    );
  }
);
CardAccordation.displayName = "CardAccordation";

// src/components/Accordation/AccordionGroup.tsx
var import_react27 = require("react");
var import_zustand8 = require("zustand");
var import_jsx_runtime48 = require("react/jsx-runtime");
function createAccordionGroupStore(type, initialValue, collapsible) {
  return (0, import_zustand8.create)((set, get) => ({
    type,
    value: initialValue,
    collapsible,
    setValue: (value) => set({ value }),
    isItemExpanded: (itemValue) => {
      const state = get();
      if (state.type === "single") {
        return state.value === itemValue;
      } else {
        return Array.isArray(state.value) && state.value.includes(itemValue);
      }
    }
  }));
}
var injectStore4 = (children, store, indexRef, onItemToggle) => {
  return import_react27.Children.map(children, (child) => {
    if (!(0, import_react27.isValidElement)(child)) {
      return child;
    }
    const typedChild = child;
    const displayName = typedChild.type?.displayName;
    let newProps = {};
    if (displayName === "CardAccordation") {
      const itemValue = typedChild.props.value || `accordion-item-${indexRef.current++}`;
      const storeState = store.getState();
      const expanded = storeState.isItemExpanded(itemValue);
      newProps.value = itemValue;
      newProps.expanded = expanded;
      newProps.onToggleExpanded = (isExpanded) => {
        onItemToggle(itemValue, isExpanded);
        typedChild.props.onToggleExpanded?.(isExpanded);
      };
    }
    if (typedChild.props.children) {
      const processedChildren = injectStore4(
        typedChild.props.children,
        store,
        indexRef,
        onItemToggle
      );
      if (displayName === "CardAccordation") {
        newProps.children = processedChildren;
      } else if (processedChildren !== typedChild.props.children) {
        return (0, import_react27.cloneElement)(typedChild, { children: processedChildren });
      }
    }
    if (Object.keys(newProps).length > 0) {
      return (0, import_react27.cloneElement)(typedChild, newProps);
    }
    return child;
  });
};
var AccordionGroup = (0, import_react27.forwardRef)(
  ({
    type = "single",
    defaultValue,
    value: controlledValue,
    onValueChange,
    collapsible = true,
    children,
    className,
    ...props
  }, ref) => {
    const [internalValue, setInternalValue] = (0, import_react27.useState)(
      defaultValue || (type === "single" ? "" : [])
    );
    const isControlled = controlledValue !== void 0;
    const currentValue = isControlled ? controlledValue : internalValue;
    const storeRef = (0, import_react27.useRef)(null);
    if (storeRef.current) {
      storeRef.current.setState((prev) => {
        const nextState = {};
        if (prev.type !== type) {
          nextState.type = type;
        }
        if (prev.collapsible !== collapsible) {
          nextState.collapsible = collapsible;
        }
        return nextState;
      });
    } else {
      storeRef.current = createAccordionGroupStore(
        type,
        currentValue,
        collapsible
      );
    }
    const store = storeRef.current;
    (0, import_react27.useEffect)(() => {
      store.setState({ value: currentValue });
    }, [currentValue, store]);
    (0, import_react27.useEffect)(() => {
      if (!isControlled) {
        setInternalValue((prev) => {
          if (type === "single") {
            if (Array.isArray(prev)) {
              return prev[0] ?? "";
            }
            return typeof prev === "string" ? prev : "";
          }
          if (Array.isArray(prev)) {
            return prev;
          }
          return prev ? [prev] : [];
        });
      }
    }, [isControlled, type]);
    const handleItemToggle = (itemValue, isExpanded) => {
      const storeState = store.getState();
      let newValue;
      if (type === "single") {
        if (isExpanded) {
          newValue = itemValue;
        } else {
          newValue = collapsible ? "" : storeState.value;
        }
      } else {
        const currentArray = Array.isArray(storeState.value) ? storeState.value : [];
        if (isExpanded) {
          newValue = [...currentArray, itemValue];
        } else {
          newValue = currentArray.filter((v) => v !== itemValue);
        }
      }
      if (!isControlled) {
        setInternalValue(newValue);
      }
      store.setState({ value: newValue });
      onValueChange?.(newValue);
    };
    const indexRef = { current: 0 };
    const enhancedChildren = injectStore4(
      children,
      store,
      indexRef,
      handleItemToggle
    );
    return /* @__PURE__ */ (0, import_jsx_runtime48.jsx)("div", { ref, className, ...props, children: enhancedChildren });
  }
);
AccordionGroup.displayName = "AccordionGroup";

// src/components/FileAttachment/FileAttachment.tsx
var import_react28 = require("react");
var import_phosphor_react22 = require("phosphor-react");
var import_jsx_runtime49 = require("react/jsx-runtime");
var formatFileSize = (bytes) => {
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
  if (bytes < 1024 * 1024 * 1024)
    return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
  return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)} GB`;
};
var generateFileId = () => {
  return crypto.randomUUID();
};
var FileAttachment = ({
  files,
  onFilesAdd,
  onFileRemove,
  readOnly = false,
  buttonLabel = "Anexar",
  multiple = true,
  className,
  hideButton = false
}) => {
  const fileInputRef = (0, import_react28.useRef)(null);
  const handleFileChange = (event) => {
    const selectedFiles = event.target.files;
    if (selectedFiles && selectedFiles.length > 0) {
      const filesArray = Array.from(selectedFiles);
      onFilesAdd(filesArray);
    }
    if (fileInputRef.current) {
      fileInputRef.current.value = "";
    }
  };
  const handleAttachClick = () => {
    fileInputRef.current?.click();
  };
  return /* @__PURE__ */ (0, import_jsx_runtime49.jsxs)("div", { className: cn("flex flex-col gap-2", className), children: [
    /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(
      "input",
      {
        type: "file",
        ref: fileInputRef,
        className: "hidden",
        onChange: handleFileChange,
        multiple,
        "aria-label": "Selecionar arquivos"
      }
    ),
    !readOnly && !hideButton && /* @__PURE__ */ (0, import_jsx_runtime49.jsxs)(
      Button_default,
      {
        type: "button",
        variant: "outline",
        size: "small",
        onClick: handleAttachClick,
        className: "self-start flex items-center gap-2",
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(import_phosphor_react22.Paperclip, { size: 16 }),
          buttonLabel
        ]
      }
    ),
    files.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime49.jsx)("div", { className: "flex flex-wrap gap-2", children: files.map((attachedFile) => /* @__PURE__ */ (0, import_jsx_runtime49.jsxs)(
      "div",
      {
        className: "flex items-center gap-2 bg-background-50 px-3 py-2 rounded-lg border border-border-100",
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(import_phosphor_react22.FileText, { size: 16, className: "text-text-500 shrink-0" }),
          /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(Text_default, { className: "text-sm text-text-700 truncate max-w-[200px]", children: attachedFile.file.name }),
          /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(Text_default, { className: "text-xs text-text-400 shrink-0", children: formatFileSize(attachedFile.file.size) }),
          !readOnly && /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(
            "button",
            {
              type: "button",
              onClick: () => onFileRemove(attachedFile.id),
              className: "text-text-400 hover:text-error-500 transition-colors shrink-0",
              "aria-label": `Remover ${attachedFile.file.name}`,
              children: /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(import_phosphor_react22.X, { size: 14 })
            }
          )
        ]
      },
      attachedFile.id
    )) })
  ] });
};
var FileAttachment_default = FileAttachment;

// src/types/studentActivityCorrection.ts
var QUESTION_STATUS2 = {
  CORRETA: "CORRETA",
  INCORRETA: "INCORRETA",
  EM_BRANCO: "EM_BRANCO"
};
var getQuestionStatusBadgeConfig = (status) => {
  const configs = {
    [QUESTION_STATUS2.CORRETA]: {
      label: "Correta",
      bgColor: "bg-success-background",
      textColor: "text-success-800"
    },
    [QUESTION_STATUS2.INCORRETA]: {
      label: "Incorreta",
      bgColor: "bg-error-background",
      textColor: "text-error-800"
    },
    [QUESTION_STATUS2.EM_BRANCO]: {
      label: "Em branco",
      bgColor: "bg-gray-100",
      textColor: "text-gray-600"
    }
  };
  return configs[status];
};

// src/components/CorrectActivityModal/CorrectActivityModal.tsx
var import_jsx_runtime50 = require("react/jsx-runtime");
var variantConfig = {
  score: {
    bg: "bg-warning-background",
    text: "text-warning-600",
    iconBg: "bg-warning-300",
    iconColor: "text-white",
    IconComponent: import_phosphor_react23.Star
  },
  correct: {
    bg: "bg-success-200",
    text: "text-success-700",
    iconBg: "bg-indicator-positive",
    iconColor: "text-text-950",
    IconComponent: import_phosphor_react23.Medal
  },
  incorrect: {
    bg: "bg-error-100",
    text: "text-error-700",
    iconBg: "bg-indicator-negative",
    iconColor: "text-white",
    IconComponent: import_phosphor_react23.WarningCircle
  }
};
var StatCard = ({ label, value, variant }) => {
  const config = variantConfig[variant];
  const IconComponent = config.IconComponent;
  return /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)(
    "div",
    {
      className: cn(
        "border border-border-50 rounded-xl py-4 px-3 flex flex-col items-center justify-center gap-1",
        config.bg
      ),
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(
          "div",
          {
            className: cn(
              "w-[30px] h-[30px] rounded-2xl flex items-center justify-center",
              config.iconBg
            ),
            children: /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(
              IconComponent,
              {
                size: 16,
                className: config.iconColor,
                weight: "regular"
              }
            )
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(
          Text_default,
          {
            className: cn("text-2xs font-bold uppercase text-center", config.text),
            children: label
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Text_default, { className: cn("text-xl font-bold", config.text), children: value })
      ]
    }
  );
};
var CorrectActivityModal = ({
  isOpen,
  onClose,
  data,
  isViewOnly = false,
  onObservationSubmit
}) => {
  const [observation, setObservation] = (0, import_react29.useState)("");
  const [isObservationExpanded, setIsObservationExpanded] = (0, import_react29.useState)(false);
  const [isObservationSaved, setIsObservationSaved] = (0, import_react29.useState)(false);
  const [savedObservation, setSavedObservation] = (0, import_react29.useState)("");
  const [attachedFiles, setAttachedFiles] = (0, import_react29.useState)([]);
  const [savedFiles, setSavedFiles] = (0, import_react29.useState)([]);
  const fileInputRef = (0, import_react29.useRef)(null);
  (0, import_react29.useEffect)(() => {
    if (isOpen) {
      setObservation("");
      setIsObservationExpanded(false);
      setIsObservationSaved(false);
      setSavedObservation("");
      setAttachedFiles([]);
      setSavedFiles([]);
    }
  }, [isOpen, data?.studentId]);
  const handleOpenObservation = () => {
    setIsObservationExpanded(true);
  };
  const handleFilesAdd = (files) => {
    const newFile = files[0];
    if (newFile) {
      setAttachedFiles([{ file: newFile, id: generateFileId() }]);
    }
  };
  const handleFileRemove = (id) => {
    setAttachedFiles((prev) => prev.filter((f) => f.id !== id));
  };
  const handleSaveObservation = () => {
    if (observation.trim() || attachedFiles.length > 0) {
      setSavedObservation(observation);
      setSavedFiles([...attachedFiles]);
      setIsObservationSaved(true);
      setIsObservationExpanded(false);
      onObservationSubmit?.(
        observation,
        attachedFiles.map((f) => f.file)
      );
    }
  };
  const handleEditObservation = () => {
    setObservation(savedObservation);
    setAttachedFiles([...savedFiles]);
    setIsObservationSaved(false);
    setIsObservationExpanded(true);
  };
  if (!data) return null;
  const title = isViewOnly ? "Detalhes da atividade" : "Corrigir atividade";
  const formattedScore = data.score === null ? "-" : data.score.toFixed(1);
  const renderObservationSection = () => {
    if (isViewOnly) return null;
    if (isObservationSaved) {
      return /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)("div", { className: "bg-background border border-border-100 rounded-lg p-4 space-y-2", children: [
        /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)("div", { className: "flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3", children: [
          /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Text_default, { className: "text-sm font-bold text-text-950", children: "Observa\xE7\xE3o" }),
          /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)("div", { className: "flex items-center gap-3", children: [
            savedFiles.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)("div", { className: "flex items-center gap-2 px-5 h-10 bg-secondary-500 rounded-full min-w-0 max-w-[150px]", children: [
              /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(
                import_phosphor_react23.Paperclip,
                {
                  size: 18,
                  className: "text-text-800 flex-shrink-0"
                }
              ),
              /* @__PURE__ */ (0, import_jsx_runtime50.jsx)("span", { className: "text-base font-medium text-text-800 truncate", children: savedFiles[0].file.name })
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)(
              Button_default,
              {
                type: "button",
                variant: "outline",
                size: "small",
                onClick: handleEditObservation,
                className: "flex items-center gap-2 flex-shrink-0",
                children: [
                  /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(import_phosphor_react23.PencilSimple, { size: 16 }),
                  "Editar"
                ]
              }
            )
          ] })
        ] }),
        savedObservation && /* @__PURE__ */ (0, import_jsx_runtime50.jsx)("div", { className: "p-3 bg-background-50 rounded-lg", children: /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Text_default, { className: "text-sm text-text-700", children: savedObservation }) })
      ] });
    }
    if (isObservationExpanded) {
      return /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)("div", { className: "bg-background border border-border-100 rounded-lg p-4 space-y-3", children: [
        /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Text_default, { className: "text-sm font-bold text-text-950", children: "Observa\xE7\xE3o" }),
        /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(
          "textarea",
          {
            value: observation,
            onChange: (e) => setObservation(e.target.value),
            placeholder: "Escreva uma observa\xE7\xE3o para o estudante",
            className: "w-full min-h-[80px] p-3 border border-border-100 rounded-lg text-sm text-text-700 placeholder:text-text-400 resize-none focus:outline-none focus:ring-2 focus:ring-primary-500"
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(
          "input",
          {
            type: "file",
            ref: fileInputRef,
            className: "hidden",
            onChange: (e) => {
              const selectedFiles = e.target.files;
              if (selectedFiles && selectedFiles.length > 0) {
                handleFilesAdd(Array.from(selectedFiles));
              }
              if (fileInputRef.current) {
                fileInputRef.current.value = "";
              }
            },
            "aria-label": "Selecionar arquivo"
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)("div", { className: "flex flex-col-reverse sm:flex-row gap-3 sm:justify-between", children: [
          attachedFiles.length > 0 ? /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)("div", { className: "flex items-center justify-center gap-2 px-5 h-10 bg-secondary-500 rounded-full min-w-0 max-w-[150px]", children: [
            /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(import_phosphor_react23.Paperclip, { size: 18, className: "text-text-800 flex-shrink-0" }),
            /* @__PURE__ */ (0, import_jsx_runtime50.jsx)("span", { className: "text-base font-medium text-text-800 truncate", children: attachedFiles[0].file.name }),
            /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(
              "button",
              {
                type: "button",
                onClick: () => handleFileRemove(attachedFiles[0].id),
                className: "text-text-700 hover:text-text-800 flex-shrink-0",
                "aria-label": `Remover ${attachedFiles[0].file.name}`,
                children: /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(import_phosphor_react23.X, { size: 18 })
              }
            )
          ] }) : /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)(
            Button_default,
            {
              type: "button",
              variant: "outline",
              size: "small",
              onClick: () => fileInputRef.current?.click(),
              className: "flex items-center gap-2",
              children: [
                /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(import_phosphor_react23.Paperclip, { size: 18 }),
                "Anexar"
              ]
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(
            Button_default,
            {
              type: "button",
              size: "small",
              onClick: handleSaveObservation,
              disabled: !observation.trim() && attachedFiles.length === 0,
              children: "Salvar"
            }
          )
        ] }),
        data.observation && /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)("div", { className: "p-3 bg-background-50 rounded-lg", children: [
          /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Text_default, { className: "text-xs text-text-500", children: "Observa\xE7\xE3o anterior:" }),
          /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Text_default, { className: "text-sm text-text-700", children: data.observation })
        ] })
      ] });
    }
    return /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)("div", { className: "bg-background border border-border-100 rounded-lg p-4 flex flex-col sm:flex-row gap-3 sm:items-center sm:justify-between", children: [
      /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Text_default, { className: "text-sm font-bold text-text-950", children: "Observa\xE7\xE3o" }),
      /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Button_default, { type: "button", size: "small", onClick: handleOpenObservation, children: "Incluir" })
    ] });
  };
  return /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(
    Modal_default,
    {
      isOpen,
      onClose,
      title,
      size: "lg",
      contentClassName: "max-h-[80vh] overflow-y-auto",
      children: /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)("div", { className: "space-y-6", children: [
        /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)("div", { className: "flex items-center gap-3", children: [
          /* @__PURE__ */ (0, import_jsx_runtime50.jsx)("div", { className: "w-10 h-10 bg-primary-100 rounded-full flex items-center justify-center", children: /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Text_default, { className: "text-lg font-semibold text-primary-700", children: data.studentName.charAt(0).toUpperCase() }) }),
          /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Text_default, { className: "text-lg font-medium text-text-950", children: data.studentName })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)("div", { className: "grid grid-cols-3 gap-4", children: [
          /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(StatCard, { label: "Nota", value: formattedScore, variant: "score" }),
          /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(
            StatCard,
            {
              label: "N\xB0 de quest\xF5es corretas",
              value: data.correctCount,
              variant: "correct"
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(
            StatCard,
            {
              label: "N\xB0 de quest\xF5es incorretas",
              value: data.incorrectCount,
              variant: "incorrect"
            }
          )
        ] }),
        renderObservationSection(),
        /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)("div", { className: "space-y-2", children: [
          /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Text_default, { className: "text-sm font-bold text-text-950", children: "Respostas" }),
          /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(AccordionGroup, { type: "multiple", className: "space-y-2", children: data.questions.map((question) => {
            const badgeConfig = getQuestionStatusBadgeConfig(question.status);
            return /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(
              CardAccordation,
              {
                value: `question-${question.questionNumber}`,
                className: "bg-background rounded-xl",
                trigger: /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)("div", { className: "flex items-center justify-between w-full py-3 pr-2", children: [
                  /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)(Text_default, { className: "text-base font-bold text-text-950", children: [
                    "Quest\xE3o ",
                    question.questionNumber
                  ] }),
                  /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(
                    Badge_default,
                    {
                      className: cn(
                        "text-xs px-2 py-1",
                        badgeConfig.bgColor,
                        badgeConfig.textColor
                      ),
                      children: badgeConfig.label
                    }
                  )
                ] }),
                children: /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)("div", { className: "space-y-4 pt-2", children: [
                  question.questionText && /* @__PURE__ */ (0, import_jsx_runtime50.jsx)("div", { className: "text-sm text-text-700", children: question.questionText }),
                  question.alternatives && question.alternatives.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(
                    CardAccordation,
                    {
                      value: `alternatives-${question.questionNumber}`,
                      className: "border border-border-100 rounded-lg",
                      trigger: /* @__PURE__ */ (0, import_jsx_runtime50.jsx)("div", { className: "py-3 pr-2 w-full", children: /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Text_default, { className: "text-sm font-bold text-text-950", children: "Alternativas" }) }),
                      children: /* @__PURE__ */ (0, import_jsx_runtime50.jsx)("div", { className: "pt-2", children: /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(
                        AlternativesList,
                        {
                          mode: "readonly",
                          selectedValue: question.studentAnswer,
                          alternatives: question.alternatives.map(
                            (alt) => ({
                              value: alt.value,
                              label: alt.label,
                              status: alt.isCorrect ? "correct" : void 0
                            })
                          )
                        }
                      ) })
                    }
                  ),
                  (!question.alternatives || question.alternatives.length === 0) && /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)(import_jsx_runtime50.Fragment, { children: [
                    /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)("div", { className: "flex gap-2", children: [
                      /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Text_default, { className: "text-xs text-text-500", children: "Resposta do aluno:" }),
                      /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Text_default, { className: "text-xs text-text-700", children: question.studentAnswer || "N\xE3o respondeu" })
                    ] }),
                    /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)("div", { className: "flex gap-2", children: [
                      /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Text_default, { className: "text-xs text-text-500", children: "Resposta correta:" }),
                      /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Text_default, { className: "text-xs text-success-700", children: question.correctAnswer || "-" })
                    ] })
                  ] })
                ] })
              },
              question.questionNumber
            );
          }) })
        ] })
      ] })
    }
  );
};
var CorrectActivityModal_default = CorrectActivityModal;

// src/components/AlertDialog/AlertDialog.tsx
var import_react30 = require("react");
var import_jsx_runtime51 = require("react/jsx-runtime");
var SIZE_CLASSES11 = {
  "extra-small": "w-screen max-w-[324px]",
  small: "w-screen max-w-[378px]",
  medium: "w-screen max-w-[459px]",
  large: "w-screen max-w-[578px]",
  "extra-large": "w-screen max-w-[912px]"
};
var AlertDialog = (0, import_react30.forwardRef)(
  ({
    description,
    cancelButtonLabel = "Cancelar",
    submitButtonLabel = "Deletar",
    title,
    isOpen,
    closeOnBackdropClick = true,
    closeOnEscape = true,
    className = "",
    onSubmit,
    onChangeOpen,
    submitValue,
    onCancel,
    cancelValue,
    size = "medium",
    ...props
  }, ref) => {
    (0, import_react30.useEffect)(() => {
      if (!isOpen || !closeOnEscape) return;
      const handleEscape = (event) => {
        if (event.key === "Escape") {
          onChangeOpen(false);
        }
      };
      document.addEventListener("keydown", handleEscape);
      return () => document.removeEventListener("keydown", handleEscape);
    }, [isOpen, closeOnEscape]);
    (0, import_react30.useEffect)(() => {
      if (isOpen) {
        document.body.style.overflow = "hidden";
      } else {
        document.body.style.overflow = "unset";
      }
      return () => {
        document.body.style.overflow = "unset";
      };
    }, [isOpen]);
    const handleBackdropClick = (event) => {
      if (event.target === event.currentTarget && closeOnBackdropClick) {
        onChangeOpen(false);
      }
    };
    const handleBackdropKeyDown = (event) => {
      if (event.key === "Escape" && closeOnEscape) {
        onChangeOpen(false);
      }
    };
    const handleSubmit = () => {
      onChangeOpen(false);
      onSubmit?.(submitValue);
    };
    const handleCancel = () => {
      onChangeOpen(false);
      onCancel?.(cancelValue);
    };
    const sizeClasses = SIZE_CLASSES11[size];
    return /* @__PURE__ */ (0, import_jsx_runtime51.jsx)(import_jsx_runtime51.Fragment, { children: isOpen && /* @__PURE__ */ (0, import_jsx_runtime51.jsx)(
      "div",
      {
        className: "fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm",
        onClick: handleBackdropClick,
        onKeyDown: handleBackdropKeyDown,
        "data-testid": "alert-dialog-overlay",
        children: /* @__PURE__ */ (0, import_jsx_runtime51.jsxs)(
          "div",
          {
            ref,
            className: cn(
              "bg-background border border-border-100 rounded-lg shadow-lg p-6 m-3",
              sizeClasses,
              className
            ),
            ...props,
            children: [
              /* @__PURE__ */ (0, import_jsx_runtime51.jsx)(
                "h2",
                {
                  id: "alert-dialog-title",
                  className: "pb-3 text-xl font-semibold text-text-950",
                  children: title
                }
              ),
              /* @__PURE__ */ (0, import_jsx_runtime51.jsx)(
                "p",
                {
                  id: "alert-dialog-description",
                  className: "text-text-700 text-sm",
                  children: description
                }
              ),
              /* @__PURE__ */ (0, import_jsx_runtime51.jsxs)("div", { className: "flex flex-row items-center justify-end pt-4 gap-3", children: [
                /* @__PURE__ */ (0, import_jsx_runtime51.jsx)(Button_default, { variant: "outline", size: "small", onClick: handleCancel, children: cancelButtonLabel }),
                /* @__PURE__ */ (0, import_jsx_runtime51.jsx)(
                  Button_default,
                  {
                    variant: "solid",
                    size: "small",
                    action: "negative",
                    onClick: handleSubmit,
                    children: submitButtonLabel
                  }
                )
              ] })
            ]
          }
        )
      }
    ) });
  }
);
AlertDialog.displayName = "AlertDialog";

// src/components/LoadingModal/loadingModal.tsx
var import_react31 = require("react");
var import_jsx_runtime52 = require("react/jsx-runtime");
var LoadingModal = (0, import_react31.forwardRef)(
  ({ open, title = "Titulo...", subtitle = "Subtitulo...", ...props }, ref) => {
    if (!open) return null;
    return /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(
      "div",
      {
        ref,
        "aria-modal": "true",
        "aria-labelledby": "loading-modal-title",
        "aria-describedby": "loading-modal-subtitle",
        className: "fixed inset-0 z-50 flex items-center justify-center bg-background/90 backdrop-blur-xs",
        ...props,
        children: /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)("div", { className: "w-full max-w-[364px] flex flex-col items-center justify-center gap-14", children: [
          /* @__PURE__ */ (0, import_jsx_runtime52.jsx)("span", { className: "animate-spin", "aria-hidden": "true", children: /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(
            "svg",
            {
              width: "102",
              height: "102",
              viewBox: "0 0 102 102",
              fill: "none",
              xmlns: "http://www.w3.org/2000/svg",
              "aria-hidden": "true",
              focusable: false,
              children: [
                /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(
                  "path",
                  {
                    d: "M101.5 51C101.5 78.8904 78.8904 101.5 51 101.5C23.1096 101.5 0.5 78.8904 0.5 51C0.5 23.1096 23.1096 0.5 51 0.5C78.8904 0.5 101.5 23.1096 101.5 51ZM8.62286 51C8.62286 74.4043 27.5957 93.3771 51 93.3771C74.4043 93.3771 93.3771 74.4043 93.3771 51C93.3771 27.5957 74.4043 8.62286 51 8.62286C27.5957 8.62286 8.62286 27.5957 8.62286 51Z",
                    className: "fill-primary-100"
                  }
                ),
                /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(
                  "path",
                  {
                    d: "M97.4386 51C99.6816 51 101.517 52.8213 101.337 55.0571C100.754 62.2833 98.6212 69.3162 95.0643 75.6696C90.8444 83.207 84.7616 89.536 77.3975 94.0514C70.0333 98.5668 61.6339 101.118 53.0024 101.46C44.371 101.803 35.7959 99.9255 28.0971 96.0078C20.3982 92.0902 13.833 86.2631 9.02917 79.0838C4.22529 71.9045 1.34332 63.6129 0.658804 55.0017C-0.0257159 46.3906 1.51009 37.7479 5.1194 29.8997C8.16173 23.2845 12.5915 17.4202 18.0904 12.6959C19.7917 11.2341 22.3444 11.6457 23.6647 13.459C24.9851 15.2723 24.5702 17.7988 22.8916 19.2866C18.5048 23.1747 14.9608 27.9413 12.4992 33.2937C9.47048 39.8794 8.1817 47.132 8.75612 54.3581C9.33053 61.5841 11.7489 68.542 15.7801 74.5666C19.8113 80.5911 25.3205 85.4809 31.781 88.7684C38.2414 92.0559 45.4372 93.6312 52.6804 93.3438C59.9235 93.0564 66.9718 90.9158 73.1515 87.1267C79.3311 83.3375 84.4355 78.0266 87.9766 71.7015C90.8546 66.561 92.6217 60.8903 93.1827 55.0553C93.3973 52.8225 95.1955 51 97.4386 51Z",
                    className: "fill-primary-600"
                  }
                )
              ]
            }
          ) }),
          /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)("span", { className: "flex flex-col gap-4 text-center", children: [
            /* @__PURE__ */ (0, import_jsx_runtime52.jsx)("p", { id: "loading-modal-title", className: "text-text-950 text-lg", children: title }),
            /* @__PURE__ */ (0, import_jsx_runtime52.jsx)("p", { id: "loading-modal-subtitle", className: "text-text-600 text-lg", children: subtitle })
          ] })
        ] })
      }
    );
  }
);
var loadingModal_default = LoadingModal;

// src/components/NotificationCard/NotificationCard.tsx
var import_phosphor_react24 = require("phosphor-react");
var import_react33 = require("react");

// src/hooks/useMobile.ts
var import_react32 = require("react");
var MOBILE_WIDTH = 500;
var TABLET_WIDTH = 931;
var SMALL_MOBILE_WIDTH = 425;
var EXTRA_SMALL_MOBILE_WIDTH = 375;
var ULTRA_SMALL_MOBILE_WIDTH = 375;
var TINY_MOBILE_WIDTH = 320;
var DEFAULT_WIDTH = 1200;
var getWindowWidth = () => {
  if (typeof window === "undefined") {
    return DEFAULT_WIDTH;
  }
  return window.innerWidth;
};
var getDeviceType = () => {
  const width = getWindowWidth();
  return width < TABLET_WIDTH ? "responsive" : "desktop";
};
var useMobile = () => {
  const [isMobile, setIsMobile] = (0, import_react32.useState)(false);
  const [isTablet, setIsTablet] = (0, import_react32.useState)(false);
  const [isSmallMobile, setIsSmallMobile] = (0, import_react32.useState)(false);
  const [isExtraSmallMobile, setIsExtraSmallMobile] = (0, import_react32.useState)(false);
  const [isUltraSmallMobile, setIsUltraSmallMobile] = (0, import_react32.useState)(false);
  const [isTinyMobile, setIsTinyMobile] = (0, import_react32.useState)(false);
  (0, import_react32.useEffect)(() => {
    const checkScreenSize = () => {
      const width = getWindowWidth();
      setIsMobile(width < MOBILE_WIDTH);
      setIsTablet(width < TABLET_WIDTH);
      setIsSmallMobile(width < SMALL_MOBILE_WIDTH);
      setIsExtraSmallMobile(width < EXTRA_SMALL_MOBILE_WIDTH);
      setIsUltraSmallMobile(width < ULTRA_SMALL_MOBILE_WIDTH);
      setIsTinyMobile(width < TINY_MOBILE_WIDTH);
    };
    checkScreenSize();
    window.addEventListener("resize", checkScreenSize);
    return () => window.removeEventListener("resize", checkScreenSize);
  }, []);
  const getFormContainerClasses = () => {
    if (isMobile) {
      return "w-full px-4";
    }
    if (isTablet) {
      return "w-full px-6";
    }
    return "w-full max-w-[992px] mx-auto px-0";
  };
  const getMobileHeaderClasses = () => {
    return "flex flex-col items-start gap-4 mb-6";
  };
  const getDesktopHeaderClasses = () => {
    return "flex flex-row justify-between items-center gap-6 mb-8";
  };
  const getHeaderClasses = () => {
    return isMobile ? getMobileHeaderClasses() : getDesktopHeaderClasses();
  };
  const getVideoContainerClasses = () => {
    if (isTinyMobile) return "aspect-square";
    if (isExtraSmallMobile) return "aspect-[4/3]";
    if (isSmallMobile) return "aspect-[16/12]";
    return "aspect-video";
  };
  return {
    isMobile,
    isTablet,
    isSmallMobile,
    isExtraSmallMobile,
    isUltraSmallMobile,
    isTinyMobile,
    getFormContainerClasses,
    getHeaderClasses,
    getMobileHeaderClasses,
    getDesktopHeaderClasses,
    getVideoContainerClasses,
    getDeviceType
  };
};

// src/store/notificationStore.ts
var import_zustand9 = require("zustand");
var import_middleware3 = require("zustand/middleware");

// src/types/notifications.ts
var NotificationEntityType = /* @__PURE__ */ ((NotificationEntityType2) => {
  NotificationEntityType2["ACTIVITY"] = "ACTIVITY";
  NotificationEntityType2["TRAIL"] = "TRAIL";
  NotificationEntityType2["GOAL"] = "GOAL";
  return NotificationEntityType2;
})(NotificationEntityType || {});

// src/store/notificationStore.ts
var mapBackendNotification = (backendNotification) => {
  let type = "GENERAL";
  let entityType = null;
  if (backendNotification.entityType) {
    const backendEntityType = backendNotification.entityType.toUpperCase();
    switch (backendEntityType) {
      case "ACTIVITY" /* ACTIVITY */:
        type = "ACTIVITY";
        entityType = "ACTIVITY" /* ACTIVITY */;
        break;
      case "TRAIL" /* TRAIL */:
        type = "TRAIL";
        entityType = "TRAIL" /* TRAIL */;
        break;
      case "GOAL" /* GOAL */:
        type = "GOAL";
        entityType = "GOAL" /* GOAL */;
        break;
      default:
        break;
    }
  }
  return {
    id: backendNotification.id,
    title: backendNotification.title,
    message: backendNotification.description,
    type,
    isRead: backendNotification.read,
    createdAt: new Date(backendNotification.createdAt),
    entityType,
    entityId: backendNotification.entityId,
    sender: backendNotification.sender,
    activity: backendNotification.activity,
    goal: backendNotification.goal,
    actionLink: backendNotification.actionLink ?? null
  };
};
var groupNotificationsByTime = (notifications) => {
  const now = /* @__PURE__ */ new Date();
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
  const lastWeek = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1e3);
  const sortDesc = (a, b) => +new Date(b.createdAt) - +new Date(a.createdAt);
  const todayNotifications = notifications.filter((notification) => new Date(notification.createdAt) >= today).sort(sortDesc);
  const lastWeekNotifications = notifications.filter(
    (notification) => new Date(notification.createdAt) >= lastWeek && new Date(notification.createdAt) < today
  ).sort(sortDesc);
  const olderNotifications = notifications.filter((notification) => new Date(notification.createdAt) < lastWeek).sort(sortDesc);
  const groups = [];
  if (todayNotifications.length > 0) {
    groups.push({
      label: "Hoje",
      notifications: todayNotifications
    });
  }
  if (lastWeekNotifications.length > 0) {
    groups.push({
      label: "\xDAltima semana",
      notifications: lastWeekNotifications
    });
  }
  if (olderNotifications.length > 0) {
    groups.push({
      label: "Mais antigas",
      notifications: olderNotifications
    });
  }
  return groups;
};
var formatTimeAgo = (date) => {
  const now = /* @__PURE__ */ new Date();
  const diffInMs = now.getTime() - new Date(date).getTime();
  const diffInHours = Math.floor(diffInMs / (1e3 * 60 * 60));
  const diffInDays = Math.floor(diffInMs / (1e3 * 60 * 60 * 24));
  if (diffInHours < 24) {
    return `H\xE1 ${diffInHours}h`;
  } else if (diffInDays < 30) {
    const day = new Date(date).getDate();
    const months = [
      "Jan",
      "Fev",
      "Mar",
      "Abr",
      "Mai",
      "Jun",
      "Jul",
      "Ago",
      "Set",
      "Out",
      "Nov",
      "Dez"
    ];
    const month = months[new Date(date).getMonth()];
    return `${day} ${month}`;
  }
  return new Date(date).toLocaleDateString("pt-BR");
};
var createNotificationStore = (apiClient) => {
  return (0, import_zustand9.create)()(
    (0, import_middleware3.devtools)(
      (set, get) => ({
        // Initial state
        notifications: [],
        unreadCount: 0,
        loading: false,
        error: null,
        hasMore: true,
        currentPage: 1,
        // Actions
        fetchNotifications: async (params = {}) => {
          set({ loading: true, error: null });
          try {
            const response = await apiClient.get(
              "/notifications",
              { params: { ...params } }
            );
            const mappedNotifications = response.data.notifications.map(
              mapBackendNotification
            );
            const page = response.data.pagination.page;
            const totalPages = response.data.pagination.totalPages;
            const merged = params.page && params.page > 1 ? [...get().notifications, ...mappedNotifications] : mappedNotifications;
            const deduped = Array.from(
              new Map(merged.map((n) => [n.id, n])).values()
            );
            set({
              notifications: deduped,
              unreadCount: deduped.filter((n) => !n.isRead).length,
              hasMore: page < totalPages,
              currentPage: page,
              loading: false
            });
          } catch (error) {
            console.error("Error fetching notifications:", error);
            set({
              error: "Erro ao carregar notifica\xE7\xF5es",
              loading: false
            });
          }
        },
        markAsRead: async (id) => {
          const { notifications } = get();
          const notification = notifications.find((n) => n.id === id);
          if (notification?.isRead) {
            return;
          }
          try {
            await apiClient.patch(`/notifications/${id}`, { read: true });
            const updatedNotifications = notifications.map(
              (notification2) => notification2.id === id ? { ...notification2, isRead: true } : notification2
            );
            const unreadCount = updatedNotifications.filter(
              (n) => !n.isRead
            ).length;
            set({
              notifications: updatedNotifications,
              unreadCount
            });
          } catch (error) {
            console.error("Error marking notification as read:", error);
            set({ error: "Erro ao marcar notifica\xE7\xE3o como lida" });
          }
        },
        markAllAsRead: async () => {
          const { notifications } = get();
          try {
            const unreadNotifications = notifications.filter((n) => !n.isRead);
            await Promise.all(
              unreadNotifications.map(
                (notification) => apiClient.patch(`/notifications/${notification.id}`, {
                  read: true
                })
              )
            );
            const updatedNotifications = notifications.map((notification) => ({
              ...notification,
              isRead: true
            }));
            set({
              notifications: updatedNotifications,
              unreadCount: 0
            });
          } catch (error) {
            console.error("Error marking all notifications as read:", error);
            set({ error: "Erro ao marcar todas as notifica\xE7\xF5es como lidas" });
          }
        },
        deleteNotification: async (id) => {
          const { notifications } = get();
          try {
            await apiClient.delete(`/notifications/${id}`);
            const updatedNotifications = notifications.filter(
              (notification) => notification.id !== id
            );
            const unreadCount = updatedNotifications.filter(
              (n) => !n.isRead
            ).length;
            set({
              notifications: updatedNotifications,
              unreadCount
            });
          } catch (error) {
            console.error("Error deleting notification:", error);
            set({ error: "Erro ao deletar notifica\xE7\xE3o" });
          }
        },
        clearNotifications: () => {
          set({
            notifications: [],
            unreadCount: 0,
            hasMore: false,
            currentPage: 1
          });
        },
        resetError: () => {
          set({ error: null });
        },
        getGroupedNotifications: () => {
          const { notifications } = get();
          return groupNotificationsByTime(notifications);
        }
      }),
      {
        name: "notification-store"
      }
    )
  );
};

// src/assets/img/mock-content.png
var mock_content_default = "./mock-content-K2CDVG6P.png";

// src/components/NotificationCard/NotificationCard.tsx
var import_jsx_runtime53 = require("react/jsx-runtime");
var NotificationEmpty = ({
  emptyStateImage,
  emptyStateTitle = "Nenhuma notifica\xE7\xE3o no momento",
  emptyStateDescription = "Voc\xEA est\xE1 em dia com todas as novidades. Volte depois para conferir atualiza\xE7\xF5es!"
}) => {
  return /* @__PURE__ */ (0, import_jsx_runtime53.jsxs)("div", { className: "flex flex-col items-center justify-center gap-4 p-6 w-full", children: [
    emptyStateImage && /* @__PURE__ */ (0, import_jsx_runtime53.jsx)("div", { className: "w-20 h-20 flex items-center justify-center", children: /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(
      "img",
      {
        src: emptyStateImage,
        alt: "Sem notifica\xE7\xF5es",
        width: 82,
        height: 82,
        className: "object-contain"
      }
    ) }),
    /* @__PURE__ */ (0, import_jsx_runtime53.jsx)("h3", { className: "text-xl font-semibold text-text-950 text-center leading-[23px]", children: emptyStateTitle }),
    /* @__PURE__ */ (0, import_jsx_runtime53.jsx)("p", { className: "text-sm font-normal text-text-400 text-center max-w-[316px] leading-[21px]", children: emptyStateDescription })
  ] });
};
var NotificationHeader = ({
  unreadCount,
  variant = "modal"
}) => {
  return /* @__PURE__ */ (0, import_jsx_runtime53.jsxs)("div", { className: "flex items-center justify-between gap-2", children: [
    variant === "modal" ? /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(Text_default, { size: "sm", weight: "bold", className: "text-text-950", children: "Notifica\xE7\xF5es" }) : /* @__PURE__ */ (0, import_jsx_runtime53.jsx)("h3", { className: "text-sm font-semibold text-text-950", children: "Notifica\xE7\xF5es" }),
    unreadCount > 0 && /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(
      Badge_default,
      {
        variant: "solid",
        action: "info",
        size: "small",
        iconLeft: /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(import_phosphor_react24.Bell, { size: 12, "aria-hidden": "true", focusable: "false" }),
        className: "border-0",
        children: unreadCount === 1 ? "1 n\xE3o lida" : `${unreadCount} n\xE3o lidas`
      }
    )
  ] });
};
var SingleNotificationCard = ({
  title,
  message,
  time,
  isRead,
  onMarkAsRead,
  onDelete,
  onNavigate,
  actionLabel,
  className
}) => {
  const handleMarkAsRead = (e) => {
    e.preventDefault();
    e.stopPropagation();
    if (!isRead) {
      onMarkAsRead();
    }
  };
  const handleDelete = (e) => {
    e.preventDefault();
    e.stopPropagation();
    onDelete();
  };
  const handleNavigate = (e) => {
    e.stopPropagation();
    if (onNavigate) {
      onNavigate();
    }
  };
  return /* @__PURE__ */ (0, import_jsx_runtime53.jsxs)(
    "div",
    {
      className: cn(
        "flex flex-col justify-center items-start p-4 gap-2 w-full bg-background border-b border-border-200",
        "last:border-b-0",
        className
      ),
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime53.jsxs)("div", { className: "flex items-center gap-2 w-full", children: [
          !isRead && /* @__PURE__ */ (0, import_jsx_runtime53.jsx)("div", { className: "w-[7px] h-[7px] bg-info-300 rounded-full flex-shrink-0" }),
          /* @__PURE__ */ (0, import_jsx_runtime53.jsx)("h3", { className: "font-bold text-sm leading-4 text-text-950 flex-grow", children: title }),
          /* @__PURE__ */ (0, import_jsx_runtime53.jsxs)(DropdownMenu_default, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(
              DropdownMenuTrigger,
              {
                className: "flex-shrink-0 inline-flex items-center justify-center font-medium bg-transparent text-text-950 cursor-pointer hover:bg-info-50 w-6 h-6 rounded-lg",
                "aria-label": "Menu de a\xE7\xF5es",
                children: /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(import_phosphor_react24.DotsThreeVertical, { size: 24 })
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime53.jsxs)(DropdownMenuContent, { align: "end", className: "min-w-[160px]", children: [
              !isRead && /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(
                DropdownMenuItem,
                {
                  onClick: handleMarkAsRead,
                  className: "text-text-950",
                  children: "Marcar como lida"
                }
              ),
              /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(DropdownMenuItem, { onClick: handleDelete, className: "text-error-600", children: "Deletar" })
            ] })
          ] })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime53.jsx)("p", { className: "text-sm leading-[21px] text-text-800 w-full", children: message }),
        /* @__PURE__ */ (0, import_jsx_runtime53.jsxs)("div", { className: "flex items-center justify-between w-full", children: [
          /* @__PURE__ */ (0, import_jsx_runtime53.jsx)("span", { className: "text-sm font-medium text-text-400", children: time }),
          onNavigate && actionLabel && /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(
            "button",
            {
              type: "button",
              onClick: handleNavigate,
              className: "text-sm font-medium text-info-600 hover:text-info-700 cursor-pointer",
              children: actionLabel
            }
          )
        ] })
      ]
    }
  );
};
var NotificationList = ({
  groupedNotifications = [],
  loading = false,
  error = null,
  onRetry,
  onMarkAsReadById,
  onDeleteById,
  onNavigateById,
  onGlobalNotificationClick,
  getActionLabel,
  renderEmpty,
  className,
  emptyStateImage
}) => {
  const [globalNotificationModal, setGlobalNotificationModal] = (0, import_react33.useState)({ isOpen: false, notification: null });
  const handleGlobalNotificationClick = (notification) => {
    if (onGlobalNotificationClick) {
      onGlobalNotificationClick(notification);
    } else {
      setGlobalNotificationModal({
        isOpen: true,
        notification
      });
    }
  };
  if (error) {
    return /* @__PURE__ */ (0, import_jsx_runtime53.jsxs)("div", { className: "flex flex-col items-center gap-4 p-6 w-full", children: [
      /* @__PURE__ */ (0, import_jsx_runtime53.jsx)("p", { className: "text-sm text-error-600", children: error }),
      onRetry && /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(
        "button",
        {
          type: "button",
          onClick: onRetry,
          className: "text-sm text-info-600 hover:text-info-700",
          children: "Tentar novamente"
        }
      )
    ] });
  }
  if (loading) {
    return /* @__PURE__ */ (0, import_jsx_runtime53.jsx)("div", { className: "flex flex-col gap-0 w-full", children: ["skeleton-first", "skeleton-second", "skeleton-third"].map(
      (skeletonId) => /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(
        SkeletonCard,
        {
          className: "p-4 border-b border-border-200"
        },
        skeletonId
      )
    ) });
  }
  if (!groupedNotifications || groupedNotifications.length === 0) {
    return renderEmpty ? /* @__PURE__ */ (0, import_jsx_runtime53.jsx)("div", { className: "w-full", children: renderEmpty() }) : /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(NotificationEmpty, {});
  }
  return /* @__PURE__ */ (0, import_jsx_runtime53.jsxs)("div", { className: cn("flex flex-col gap-0 w-full", className), children: [
    groupedNotifications.map((group, idx) => /* @__PURE__ */ (0, import_jsx_runtime53.jsxs)("div", { className: "flex flex-col", children: [
      /* @__PURE__ */ (0, import_jsx_runtime53.jsx)("div", { className: "flex items-end px-4 py-6 pb-4", children: /* @__PURE__ */ (0, import_jsx_runtime53.jsx)("h4", { className: "text-lg font-bold text-text-500 flex-grow", children: group.label }) }),
      group.notifications.map((notification) => {
        const isGlobalNotification = !notification.entityType && !notification.entityId && !notification.activity && !notification.goal;
        let navigationHandler;
        if (isGlobalNotification) {
          navigationHandler = () => handleGlobalNotificationClick(notification);
        } else if (notification.entityType && notification.entityId && onNavigateById) {
          navigationHandler = () => onNavigateById(
            notification.entityType ?? void 0,
            notification.entityId ?? void 0
          );
        }
        let actionLabel;
        if (isGlobalNotification) {
          actionLabel = getActionLabel?.(void 0);
        } else {
          actionLabel = getActionLabel?.(
            notification.entityType ?? void 0
          );
        }
        return /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(
          SingleNotificationCard,
          {
            title: notification.title,
            message: notification.message,
            time: notification.time ?? formatTimeAgo(new Date(notification.createdAt)),
            isRead: notification.isRead,
            onMarkAsRead: () => onMarkAsReadById?.(notification.id),
            onDelete: () => onDeleteById?.(notification.id),
            onNavigate: navigationHandler,
            actionLabel
          },
          notification.id
        );
      })
    ] }, `${group.label}-${idx}`)),
    /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(
      Modal_default,
      {
        isOpen: globalNotificationModal.isOpen,
        onClose: () => setGlobalNotificationModal({ isOpen: false, notification: null }),
        title: globalNotificationModal.notification?.title || "",
        description: globalNotificationModal.notification?.message || "",
        variant: "activity",
        image: emptyStateImage || mock_content_default,
        actionLink: globalNotificationModal.notification?.actionLink || void 0,
        actionLabel: "Ver mais",
        size: "lg"
      }
    )
  ] });
};
var NotificationCenter = ({
  isActive,
  onToggleActive,
  unreadCount = 0,
  groupedNotifications = [],
  loading = false,
  error = null,
  onRetry,
  onMarkAsReadById,
  onDeleteById,
  onNavigateById,
  getActionLabel,
  onFetchNotifications,
  onMarkAllAsRead,
  onOpenChange,
  emptyStateImage,
  emptyStateTitle,
  emptyStateDescription,
  className
}) => {
  const { isMobile } = useMobile();
  const [isModalOpen, setIsModalOpen] = (0, import_react33.useState)(false);
  const [globalNotificationModal, setGlobalNotificationModal] = (0, import_react33.useState)({ isOpen: false, notification: null });
  const handleMobileClick = () => {
    setIsModalOpen(true);
    onFetchNotifications?.();
  };
  const handleDesktopClick = () => {
    onToggleActive?.();
  };
  const handleOpenChange = (open) => {
    const controlledByParent = typeof isActive === "boolean" && typeof onToggleActive === "function";
    onOpenChange?.(open);
    if (controlledByParent && !onOpenChange && !open && isActive) {
      onToggleActive?.();
    }
  };
  (0, import_react33.useEffect)(() => {
    if (isActive) {
      onFetchNotifications?.();
    }
  }, [isActive, onFetchNotifications]);
  const renderEmptyState = () => /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(
    NotificationEmpty,
    {
      emptyStateImage,
      emptyStateTitle,
      emptyStateDescription
    }
  );
  if (isMobile) {
    return /* @__PURE__ */ (0, import_jsx_runtime53.jsxs)(import_jsx_runtime53.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(
        IconButton_default,
        {
          active: isModalOpen,
          onClick: handleMobileClick,
          icon: /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(import_phosphor_react24.Bell, { size: 24, className: "text-primary" }),
          className
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(
        Modal_default,
        {
          isOpen: isModalOpen,
          onClose: () => setIsModalOpen(false),
          title: "Notifica\xE7\xF5es",
          size: "md",
          hideCloseButton: false,
          closeOnEscape: true,
          children: /* @__PURE__ */ (0, import_jsx_runtime53.jsxs)("div", { className: "flex flex-col h-full max-h-[80vh]", children: [
            /* @__PURE__ */ (0, import_jsx_runtime53.jsxs)("div", { className: "px-0 pb-3 border-b border-border-200", children: [
              /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(NotificationHeader, { unreadCount, variant: "modal" }),
              unreadCount > 0 && onMarkAllAsRead && /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(
                "button",
                {
                  type: "button",
                  onClick: onMarkAllAsRead,
                  className: "text-sm font-medium text-info-600 hover:text-info-700 cursor-pointer mt-2",
                  children: "Marcar todas como lidas"
                }
              )
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime53.jsx)("div", { className: "flex-1 overflow-y-auto", children: /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(
              NotificationList,
              {
                groupedNotifications,
                loading,
                error,
                onRetry,
                onMarkAsReadById,
                onDeleteById,
                onNavigateById: (entityType, entityId) => {
                  setIsModalOpen(false);
                  onNavigateById?.(entityType, entityId);
                },
                onGlobalNotificationClick: (notification) => {
                  setIsModalOpen(false);
                  setGlobalNotificationModal({
                    isOpen: true,
                    notification
                  });
                },
                getActionLabel,
                renderEmpty: renderEmptyState,
                emptyStateImage
              }
            ) })
          ] })
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(
        Modal_default,
        {
          isOpen: globalNotificationModal.isOpen,
          onClose: () => setGlobalNotificationModal({ isOpen: false, notification: null }),
          title: globalNotificationModal.notification?.title || "",
          variant: "activity",
          description: globalNotificationModal.notification?.message,
          image: emptyStateImage || mock_content_default,
          actionLink: globalNotificationModal.notification?.actionLink || void 0,
          actionLabel: "Ver mais",
          size: "lg"
        }
      )
    ] });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime53.jsxs)(import_jsx_runtime53.Fragment, { children: [
    /* @__PURE__ */ (0, import_jsx_runtime53.jsxs)(
      DropdownMenu_default,
      {
        ...typeof isActive === "boolean" ? { open: isActive, onOpenChange: handleOpenChange } : { onOpenChange: handleOpenChange },
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(DropdownMenuTrigger, { className: "text-primary cursor-pointer", children: /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(
            IconButton_default,
            {
              active: isActive,
              onClick: handleDesktopClick,
              icon: /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(
                import_phosphor_react24.Bell,
                {
                  size: 24,
                  className: isActive ? "text-primary-950" : "text-primary"
                }
              ),
              className
            }
          ) }),
          /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(
            DropdownMenuContent,
            {
              className: "min-w-[320px] max-w-[400px] max-h-[500px] overflow-hidden",
              side: "bottom",
              align: "end",
              children: /* @__PURE__ */ (0, import_jsx_runtime53.jsxs)("div", { className: "flex flex-col", children: [
                /* @__PURE__ */ (0, import_jsx_runtime53.jsxs)("div", { className: "px-4 py-3 border-b border-border-200", children: [
                  /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(
                    NotificationHeader,
                    {
                      unreadCount,
                      variant: "dropdown"
                    }
                  ),
                  unreadCount > 0 && onMarkAllAsRead && /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(
                    "button",
                    {
                      type: "button",
                      onClick: onMarkAllAsRead,
                      className: "text-sm font-medium text-info-600 hover:text-info-700 cursor-pointer mt-2",
                      children: "Marcar todas como lidas"
                    }
                  )
                ] }),
                /* @__PURE__ */ (0, import_jsx_runtime53.jsx)("div", { className: "max-h-[350px] overflow-y-auto", children: /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(
                  NotificationList,
                  {
                    groupedNotifications,
                    loading,
                    error,
                    onRetry,
                    onMarkAsReadById,
                    onDeleteById,
                    onNavigateById,
                    onGlobalNotificationClick: (notification) => {
                      setGlobalNotificationModal({
                        isOpen: true,
                        notification
                      });
                    },
                    getActionLabel,
                    renderEmpty: renderEmptyState,
                    emptyStateImage
                  }
                ) })
              ] })
            }
          )
        ]
      }
    ),
    /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(
      Modal_default,
      {
        isOpen: globalNotificationModal.isOpen,
        onClose: () => setGlobalNotificationModal({ isOpen: false, notification: null }),
        title: globalNotificationModal.notification?.title || "",
        variant: "activity",
        description: globalNotificationModal.notification?.message,
        image: emptyStateImage || mock_content_default,
        actionLink: globalNotificationModal.notification?.actionLink || void 0,
        actionLabel: "Ver mais",
        size: "lg"
      }
    )
  ] });
};
var NotificationCard = (props) => {
  switch (props.mode) {
    case "single":
      return /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(
        SingleNotificationCard,
        {
          title: props.title,
          message: props.message,
          time: props.time,
          isRead: props.isRead,
          onMarkAsRead: props.onMarkAsRead,
          onDelete: props.onDelete,
          onNavigate: props.onNavigate,
          actionLabel: props.actionLabel,
          className: props.className
        }
      );
    case "list":
      return /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(
        NotificationList,
        {
          groupedNotifications: props.groupedNotifications ?? (props.notifications ? [
            {
              label: "Notifica\xE7\xF5es",
              notifications: props.notifications
            }
          ] : []),
          loading: props.loading,
          error: props.error,
          onRetry: props.onRetry,
          onMarkAsReadById: props.onMarkAsReadById,
          onDeleteById: props.onDeleteById,
          onNavigateById: props.onNavigateById,
          onGlobalNotificationClick: props.onGlobalNotificationClick,
          getActionLabel: props.getActionLabel,
          renderEmpty: props.renderEmpty,
          className: props.className,
          emptyStateImage: props.emptyStateImage
        }
      );
    case "center":
      return /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(NotificationCenter, { ...props });
    default:
      return /* @__PURE__ */ (0, import_jsx_runtime53.jsx)("div", { className: "flex flex-col items-center gap-4 p-6 w-full", children: /* @__PURE__ */ (0, import_jsx_runtime53.jsx)("p", { className: "text-sm text-text-600", children: "Modo de notifica\xE7\xE3o n\xE3o reconhecido" }) });
  }
};
var NotificationCard_default = NotificationCard;

// src/assets/icons/subjects/BookOpenText.tsx
var import_jsx_runtime54 = require("react/jsx-runtime");
var BookOpenText = ({
  size,
  color
}) => /* @__PURE__ */ (0, import_jsx_runtime54.jsx)(
  "svg",
  {
    width: size,
    height: size,
    viewBox: "0 0 32 32",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    children: /* @__PURE__ */ (0, import_jsx_runtime54.jsx)(
      "path",
      {
        d: "M29 6H20C19.2238 6 18.4582 6.18073 17.7639 6.52786C17.0697 6.875 16.4657 7.37902 16 8C15.5343 7.37902 14.9303 6.875 14.2361 6.52786C13.5418 6.18073 12.7762 6 12 6H3C2.73478 6 2.48043 6.10536 2.29289 6.29289C2.10536 6.48043 2 6.73478 2 7V25C2 25.2652 2.10536 25.5196 2.29289 25.7071C2.48043 25.8946 2.73478 26 3 26H12C12.7956 26 13.5587 26.3161 14.1213 26.8787C14.6839 27.4413 15 28.2044 15 29C15 29.2652 15.1054 29.5196 15.2929 29.7071C15.4804 29.8946 15.7348 30 16 30C16.2652 30 16.5196 29.8946 16.7071 29.7071C16.8946 29.5196 17 29.2652 17 29C17 28.2044 17.3161 27.4413 17.8787 26.8787C18.4413 26.3161 19.2044 26 20 26H29C29.2652 26 29.5196 25.8946 29.7071 25.7071C29.8946 25.5196 30 25.2652 30 25V7C30 6.73478 29.8946 6.48043 29.7071 6.29289C29.5196 6.10536 29.2652 6 29 6ZM12 24H4V8H12C12.7956 8 13.5587 8.31607 14.1213 8.87868C14.6839 9.44129 15 10.2044 15 11V25C14.1353 24.3493 13.0821 23.9983 12 24ZM28 24H20C18.9179 23.9983 17.8647 24.3493 17 25V11C17 10.2044 17.3161 9.44129 17.8787 8.87868C18.4413 8.31607 19.2044 8 20 8H28V24ZM20 11H25C25.2652 11 25.5196 11.1054 25.7071 11.2929C25.8946 11.4804 26 11.7348 26 12C26 12.2652 25.8946 12.5196 25.7071 12.7071C25.5196 12.8946 25.2652 13 25 13H20C19.7348 13 19.4804 12.8946 19.2929 12.7071C19.1054 12.5196 19 12.2652 19 12C19 11.7348 19.1054 11.4804 19.2929 11.2929C19.4804 11.1054 19.7348 11 20 11ZM26 16C26 16.2652 25.8946 16.5196 25.7071 16.7071C25.5196 16.8946 25.2652 17 25 17H20C19.7348 17 19.4804 16.8946 19.2929 16.7071C19.1054 16.5196 19 16.2652 19 16C19 15.7348 19.1054 15.4804 19.2929 15.2929C19.4804 15.1054 19.7348 15 20 15H25C25.2652 15 25.5196 15.1054 25.7071 15.2929C25.8946 15.4804 26 15.7348 26 16ZM26 20C26 20.2652 25.8946 20.5196 25.7071 20.7071C25.5196 20.8946 25.2652 21 25 21H20C19.7348 21 19.4804 20.8946 19.2929 20.7071C19.1054 20.5196 19 20.2652 19 20C19 19.7348 19.1054 19.4804 19.2929 19.2929C19.4804 19.1054 19.7348 19 20 19H25C25.2652 19 25.5196 19.1054 25.7071 19.2929C25.8946 19.4804 26 19.7348 26 20Z",
        fill: color
      }
    )
  }
);

// src/assets/icons/subjects/HeadCircuit.tsx
var import_jsx_runtime55 = require("react/jsx-runtime");
var HeadCircuit = ({
  size,
  color
}) => /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(
  "svg",
  {
    width: size,
    height: size,
    viewBox: "0 0 32 32",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    children: /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(
      "path",
      {
        d: "M24.0625 21.4338C25.327 20.3715 26.3372 19.0392 27.0187 17.5348C27.7001 16.0304 28.0354 14.3924 28 12.7413C27.875 7.02751 23.2987 2.31626 17.595 2.01626C16.1233 1.93616 14.6506 2.15261 13.2642 2.65277C11.8778 3.15293 10.6061 3.92659 9.52453 4.92781C8.44297 5.92903 7.57365 7.13739 6.96819 8.48112C6.36272 9.82485 6.03347 11.2766 5.99997 12.75L3.19372 18.1475C3.18247 18.17 3.17122 18.1925 3.16122 18.215C2.96003 18.6839 2.94569 19.212 3.12114 19.6912C3.29659 20.1704 3.64855 20.5644 4.10497 20.7925L4.13622 20.8063L6.99997 22.1175V26C6.99997 26.5304 7.21068 27.0392 7.58576 27.4142C7.96083 27.7893 8.46954 28 8.99997 28H15C15.2652 28 15.5195 27.8947 15.7071 27.7071C15.8946 27.5196 16 27.2652 16 27C16 26.7348 15.8946 26.4804 15.7071 26.2929C15.5195 26.1054 15.2652 26 15 26H8.99997V21.4763C9.00011 21.2846 8.94517 21.0969 8.84168 20.9356C8.73818 20.7742 8.5905 20.646 8.41622 20.5663L4.99997 19L7.88372 13.4575C7.95889 13.3166 7.99878 13.1597 7.99997 13C7.99968 10.9604 8.69216 8.98124 9.96395 7.38674C11.2357 5.79224 13.0114 4.677 15 4.22376V6.17251C14.3328 6.4084 13.7704 6.87258 13.4123 7.48299C13.0543 8.0934 12.9235 8.81075 13.0432 9.50824C13.1628 10.2057 13.5252 10.8385 14.0663 11.2946C14.6074 11.7508 15.2923 12.0009 16 12.0009C16.7077 12.0009 17.3926 11.7508 17.9336 11.2946C18.4747 10.8385 18.8371 10.2057 18.9568 9.50824C19.0764 8.81075 18.9457 8.0934 18.5876 7.48299C18.2295 6.87258 17.6672 6.4084 17 6.17251V4.00001C17.1625 4.00001 17.325 4.00001 17.4875 4.01251C19.2608 4.11409 20.9649 4.73627 22.3864 5.80124C23.808 6.86621 24.8841 8.32669 25.48 10H23C22.8533 9.99995 22.7084 10.0322 22.5755 10.0944C22.4426 10.1566 22.3251 10.2473 22.2312 10.36L19.0425 14.1875C18.3774 13.9397 17.6462 13.9351 16.9781 14.1744C16.3099 14.4138 15.748 14.8817 15.3916 15.4954C15.0352 16.1092 14.9073 16.8292 15.0306 17.5281C15.1538 18.227 15.5203 18.8598 16.0652 19.3146C16.61 19.7694 17.2981 20.0168 18.0078 20.0132C18.7175 20.0095 19.4031 19.755 19.9432 19.2947C20.4834 18.8343 20.8433 18.1977 20.9594 17.4976C21.0754 16.7974 20.9402 16.0788 20.5775 15.4688L23.4687 12H25.9425C25.9725 12.26 25.9908 12.5225 25.9975 12.7875C26.0286 14.2198 25.7187 15.639 25.0931 16.9278C24.4676 18.2167 23.5445 19.3383 22.4 20.2C22.2589 20.3057 22.1484 20.4469 22.0794 20.6091C22.0105 20.7713 21.9857 20.9489 22.0075 21.1238L23.0075 29.1238C23.0379 29.3653 23.1554 29.5874 23.3379 29.7485C23.5203 29.9095 23.7553 29.9985 23.9987 29.9988C24.0405 29.9988 24.0822 29.9962 24.1237 29.9913C24.2541 29.975 24.3799 29.9333 24.4942 29.8684C24.6084 29.8035 24.7087 29.7168 24.7893 29.6131C24.87 29.5094 24.9295 29.3909 24.9643 29.2643C24.9992 29.1376 25.0087 29.0054 24.9925 28.875L24.0625 21.4338ZM16 10C15.8022 10 15.6088 9.94136 15.4444 9.83148C15.28 9.7216 15.1518 9.56542 15.0761 9.38269C15.0004 9.19997 14.9806 8.9989 15.0192 8.80492C15.0578 8.61094 15.153 8.43275 15.2929 8.2929C15.4327 8.15305 15.6109 8.05781 15.8049 8.01922C15.9989 7.98064 16.1999 8.00044 16.3827 8.07613C16.5654 8.15182 16.7216 8.27999 16.8314 8.44444C16.9413 8.60889 17 8.80223 17 9.00001C17 9.26523 16.8946 9.51958 16.7071 9.70712C16.5195 9.89465 16.2652 10 16 10ZM18 18C17.8022 18 17.6088 17.9414 17.4444 17.8315C17.28 17.7216 17.1518 17.5654 17.0761 17.3827C17.0004 17.2 16.9806 16.9989 17.0192 16.8049C17.0578 16.6109 17.153 16.4328 17.2929 16.2929C17.4327 16.153 17.6109 16.0578 17.8049 16.0192C17.9989 15.9806 18.1999 16.0004 18.3827 16.0761C18.5654 16.1518 18.7216 16.28 18.8314 16.4444C18.9413 16.6089 19 16.8022 19 17C19 17.2652 18.8946 17.5196 18.7071 17.7071C18.5195 17.8947 18.2652 18 18 18Z",
        fill: color
      }
    )
  }
);

// src/assets/icons/subjects/Microscope.tsx
var import_jsx_runtime56 = require("react/jsx-runtime");
var Microscope = ({
  size,
  color
}) => /* @__PURE__ */ (0, import_jsx_runtime56.jsx)(
  "svg",
  {
    width: size,
    height: size,
    viewBox: "0 0 32 32",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    children: /* @__PURE__ */ (0, import_jsx_runtime56.jsx)(
      "path",
      {
        d: "M28 26H25.4925C26.7637 24.4552 27.5898 22.5932 27.882 20.6142C28.1743 18.6351 27.9216 16.6138 27.1511 14.7676C26.3806 12.9213 25.1215 11.32 23.5092 10.1358C21.8968 8.95153 19.9922 8.22913 18 8.04625V4C18 3.46957 17.7893 2.96086 17.4142 2.58579C17.0391 2.21071 16.5304 2 16 2H10C9.46957 2 8.96086 2.21071 8.58579 2.58579C8.21071 2.96086 8 3.46957 8 4V17C8 17.5304 8.21071 18.0391 8.58579 18.4142C8.96086 18.7893 9.46957 19 10 19H16C16.5304 19 17.0391 18.7893 17.4142 18.4142C17.7893 18.0391 18 17.5304 18 17V10.0575C19.7643 10.2552 21.4306 10.9703 22.7895 12.1128C24.1483 13.2553 25.1389 14.7742 25.6366 16.4783C26.1343 18.1824 26.1169 19.9957 25.5866 21.69C25.0563 23.3842 24.0368 24.8838 22.6562 26H4C3.73478 26 3.48043 26.1054 3.29289 26.2929C3.10536 26.4804 3 26.7348 3 27C3 27.2652 3.10536 27.5196 3.29289 27.7071C3.48043 27.8946 3.73478 28 4 28H28C28.2652 28 28.5196 27.8946 28.7071 27.7071C28.8946 27.5196 29 27.2652 29 27C29 26.7348 28.8946 26.4804 28.7071 26.2929C28.5196 26.1054 28.2652 26 28 26ZM16 17H10V4H16V17ZM9 23C8.73478 23 8.48043 22.8946 8.29289 22.7071C8.10536 22.5196 8 22.2652 8 22C8 21.7348 8.10536 21.4804 8.29289 21.2929C8.48043 21.1054 8.73478 21 9 21H17C17.2652 21 17.5196 21.1054 17.7071 21.2929C17.8946 21.4804 18 21.7348 18 22C18 22.2652 17.8946 22.5196 17.7071 22.7071C17.5196 22.8946 17.2652 23 17 23H9Z",
        fill: color
      }
    )
  }
);

// src/enums/SubjectEnum.ts
var SubjectEnum = /* @__PURE__ */ ((SubjectEnum2) => {
  SubjectEnum2["FISICA"] = "F\xEDsica";
  SubjectEnum2["HISTORIA"] = "Hist\xF3ria";
  SubjectEnum2["LITERATURA"] = "Literatura";
  SubjectEnum2["GEOGRAFIA"] = "Geografia";
  SubjectEnum2["BIOLOGIA"] = "Biologia";
  SubjectEnum2["PORTUGUES"] = "Portugu\xEAs";
  SubjectEnum2["QUIMICA"] = "Qu\xEDmica";
  SubjectEnum2["ARTES"] = "Artes";
  SubjectEnum2["MATEMATICA"] = "Matem\xE1tica";
  SubjectEnum2["FILOSOFIA"] = "Filosofia";
  SubjectEnum2["ESPANHOL"] = "Espanhol";
  SubjectEnum2["REDACAO"] = "Reda\xE7\xE3o";
  SubjectEnum2["SOCIOLOGIA"] = "Sociologia";
  SubjectEnum2["INGLES"] = "Ingl\xEAs";
  SubjectEnum2["EDUCACAO_FISICA"] = "Ed. F\xEDsica";
  SubjectEnum2["TRILHAS"] = "Trilhas";
  return SubjectEnum2;
})(SubjectEnum || {});

// src/components/SubjectInfo/SubjectInfo.tsx
var import_phosphor_react25 = require("phosphor-react");
var import_jsx_runtime57 = require("react/jsx-runtime");
var SubjectInfo = {
  ["F\xEDsica" /* FISICA */]: {
    icon: /* @__PURE__ */ (0, import_jsx_runtime57.jsx)(import_phosphor_react25.Atom, { size: 17, color: "currentColor" }),
    colorClass: "bg-subject-1",
    name: "F\xEDsica" /* FISICA */
  },
  ["Hist\xF3ria" /* HISTORIA */]: {
    icon: /* @__PURE__ */ (0, import_jsx_runtime57.jsx)(import_phosphor_react25.Scroll, { size: 17, color: "currentColor" }),
    colorClass: "bg-subject-2",
    name: "Hist\xF3ria" /* HISTORIA */
  },
  ["Literatura" /* LITERATURA */]: {
    icon: /* @__PURE__ */ (0, import_jsx_runtime57.jsx)(BookOpenText, { size: 17, color: "currentColor" }),
    colorClass: "bg-subject-3",
    name: "Literatura" /* LITERATURA */
  },
  ["Geografia" /* GEOGRAFIA */]: {
    icon: /* @__PURE__ */ (0, import_jsx_runtime57.jsx)(import_phosphor_react25.GlobeHemisphereWest, { size: 17, color: "currentColor" }),
    colorClass: "bg-subject-4",
    name: "Geografia" /* GEOGRAFIA */
  },
  ["Biologia" /* BIOLOGIA */]: {
    icon: /* @__PURE__ */ (0, import_jsx_runtime57.jsx)(Microscope, { size: 17, color: "currentColor" }),
    colorClass: "bg-subject-5",
    name: "Biologia" /* BIOLOGIA */
  },
  ["Portugu\xEAs" /* PORTUGUES */]: {
    icon: /* @__PURE__ */ (0, import_jsx_runtime57.jsx)(ChatPT, { size: 17, color: "currentColor" }),
    colorClass: "bg-subject-6",
    name: "Portugu\xEAs" /* PORTUGUES */
  },
  ["Qu\xEDmica" /* QUIMICA */]: {
    icon: /* @__PURE__ */ (0, import_jsx_runtime57.jsx)(import_phosphor_react25.Flask, { size: 17, color: "currentColor" }),
    colorClass: "bg-subject-7",
    name: "Qu\xEDmica" /* QUIMICA */
  },
  ["Artes" /* ARTES */]: {
    icon: /* @__PURE__ */ (0, import_jsx_runtime57.jsx)(import_phosphor_react25.Palette, { size: 17, color: "currentColor" }),
    colorClass: "bg-subject-8",
    name: "Artes" /* ARTES */
  },
  ["Matem\xE1tica" /* MATEMATICA */]: {
    icon: /* @__PURE__ */ (0, import_jsx_runtime57.jsx)(import_phosphor_react25.MathOperations, { size: 17, color: "currentColor" }),
    colorClass: "bg-subject-9",
    name: "Matem\xE1tica" /* MATEMATICA */
  },
  ["Filosofia" /* FILOSOFIA */]: {
    icon: /* @__PURE__ */ (0, import_jsx_runtime57.jsx)(HeadCircuit, { size: 17, color: "currentColor" }),
    colorClass: "bg-subject-10",
    name: "Filosofia" /* FILOSOFIA */
  },
  ["Espanhol" /* ESPANHOL */]: {
    icon: /* @__PURE__ */ (0, import_jsx_runtime57.jsx)(ChatES, { size: 17, color: "currentColor" }),
    colorClass: "bg-subject-11",
    name: "Espanhol" /* ESPANHOL */
  },
  ["Reda\xE7\xE3o" /* REDACAO */]: {
    icon: /* @__PURE__ */ (0, import_jsx_runtime57.jsx)(import_phosphor_react25.ArticleNyTimes, { size: 17, color: "currentColor" }),
    colorClass: "bg-subject-12",
    name: "Reda\xE7\xE3o" /* REDACAO */
  },
  ["Sociologia" /* SOCIOLOGIA */]: {
    icon: /* @__PURE__ */ (0, import_jsx_runtime57.jsx)(import_phosphor_react25.Person, { size: 17, color: "currentColor" }),
    colorClass: "bg-subject-13",
    name: "Sociologia" /* SOCIOLOGIA */
  },
  ["Ingl\xEAs" /* INGLES */]: {
    icon: /* @__PURE__ */ (0, import_jsx_runtime57.jsx)(ChatEN, { size: 17, color: "currentColor" }),
    colorClass: "bg-subject-14",
    name: "Ingl\xEAs" /* INGLES */
  },
  ["Ed. F\xEDsica" /* EDUCACAO_FISICA */]: {
    icon: /* @__PURE__ */ (0, import_jsx_runtime57.jsx)(import_phosphor_react25.DribbbleLogo, { size: 17, color: "currentColor" }),
    colorClass: "bg-subject-15",
    name: "Ed. F\xEDsica" /* EDUCACAO_FISICA */
  },
  ["Trilhas" /* TRILHAS */]: {
    icon: /* @__PURE__ */ (0, import_jsx_runtime57.jsx)(import_phosphor_react25.BookBookmark, { size: 17, color: "currentColor" }),
    colorClass: "bg-subject-16",
    name: "Trilhas" /* TRILHAS */
  }
};
var getSubjectInfo = (subject) => {
  return SubjectInfo[subject] || {
    icon: /* @__PURE__ */ (0, import_jsx_runtime57.jsx)(import_phosphor_react25.Book, { size: 17, color: "currentColor" }),
    colorClass: "bg-subject-16",
    name: subject
  };
};
var getSubjectIcon = (subject) => {
  return SubjectInfo[subject].icon;
};
var getSubjectColorClass = (subject) => {
  return SubjectInfo[subject].colorClass;
};
var getSubjectName = (subject) => {
  return SubjectInfo[subject].name;
};

// src/hooks/useNotificationStore.ts
var createUseNotificationStore = (apiClient) => {
  return createNotificationStore(apiClient);
};

// src/hooks/useNotifications.ts
var import_react34 = require("react");
var createUseNotifications = (apiClient) => {
  const useNotificationStore = createUseNotificationStore(apiClient);
  return () => {
    const {
      notifications,
      unreadCount,
      loading,
      error,
      hasMore,
      currentPage,
      fetchNotifications,
      markAsRead,
      markAllAsRead,
      deleteNotification,
      clearNotifications,
      resetError,
      getGroupedNotifications
    } = useNotificationStore();
    const handleNavigate = (0, import_react34.useCallback)(
      (entityType, entityId, onAfterNavigate) => {
        if (entityType && entityId) {
          switch (entityType.toUpperCase()) {
            case "ACTIVITY" /* ACTIVITY */:
              window.location.href = `/atividades/${entityId}`;
              break;
            case "GOAL" /* GOAL */:
              window.location.href = `/painel/trilhas/${entityId}`;
              break;
            default:
              break;
          }
          onAfterNavigate?.();
        }
      },
      []
    );
    const getActionLabel = (0, import_react34.useCallback)(
      (entityType) => {
        if (!entityType) return "Ver mais";
        switch (entityType.toUpperCase()) {
          case "ACTIVITY" /* ACTIVITY */:
            return "Ver atividade";
          case "GOAL" /* GOAL */:
            return "Ver meta";
          default:
            return void 0;
        }
      },
      []
    );
    const markAsReadAndNavigate = (0, import_react34.useCallback)(
      async (id, entityType, entityId, onAfterNavigate) => {
        await markAsRead(id);
        if (entityType && entityId) {
          handleNavigate(entityType, entityId, onAfterNavigate);
        }
      },
      [markAsRead, handleNavigate]
    );
    const refreshNotifications = (0, import_react34.useCallback)(async () => {
      resetError();
      await fetchNotifications();
    }, [resetError, fetchNotifications]);
    const formatNotification = (0, import_react34.useCallback)(
      (notification) => ({
        ...notification,
        time: formatTimeAgo(notification.createdAt),
        entityType: notification.entityType || void 0,
        entityId: notification.entityId || void 0
      }),
      []
    );
    const getFormattedGroupedNotifications = (0, import_react34.useCallback)(() => {
      const groups = getGroupedNotifications();
      return groups.map((group) => ({
        ...group,
        notifications: group.notifications.map(formatNotification)
      }));
    }, [getGroupedNotifications, formatNotification]);
    return {
      // State
      notifications,
      unreadCount,
      loading,
      error,
      hasMore,
      currentPage,
      // Actions
      fetchNotifications,
      markAsRead,
      markAllAsRead,
      deleteNotification,
      clearNotifications,
      resetError,
      markAsReadAndNavigate,
      refreshNotifications,
      // Navigation
      handleNavigate,
      // Helpers
      getActionLabel,
      getGroupedNotifications,
      getFormattedGroupedNotifications
    };
  };
};
var createNotificationsHook = (apiClient) => {
  return createUseNotifications(apiClient);
};

// src/types/questionTypes.ts
var questionTypeLabels = {
  ["ALTERNATIVA" /* ALTERNATIVA */]: "Alternativa",
  ["VERDADEIRO_FALSO" /* VERDADEIRO_FALSO */]: "Verdadeiro ou Falso",
  ["DISSERTATIVA" /* DISSERTATIVA */]: "Discursiva",
  ["IMAGEM" /* IMAGEM */]: "Imagem",
  ["MULTIPLA_ESCOLHA" /* MULTIPLA_ESCOLHA */]: "M\xFAltipla Escolha",
  ["LIGAR_PONTOS" /* LIGAR_PONTOS */]: "Ligar Pontos",
  ["PREENCHER" /* PREENCHER */]: "Preencher Lacunas"
};

// src/hooks/useActivityFiltersData.ts
var import_react35 = require("react");
var areCategoriesSame = (prev, current) => {
  if (prev.length !== current.length) return false;
  return current.every((category) => {
    const prevCategory = prev.find((c) => c.key === category.key);
    if (!prevCategory) return false;
    const prevIds = (prevCategory.itens || []).map(
      (item) => item.id
    );
    const currentIds = (category.itens || []).map(
      (item) => item.id
    );
    if (prevIds.length !== currentIds.length) return false;
    return currentIds.every((id) => prevIds.includes(id));
  });
};
var mergeCategoriesWithSelection = (prev, current) => {
  return current.map((category) => {
    const prevCategory = prev.find((c) => c.key === category.key);
    if (!prevCategory) {
      return category;
    }
    const validSelectedIds = (prevCategory.selectedIds || []).filter(
      (id) => category.itens?.some((item) => item.id === id)
    );
    return {
      ...category,
      selectedIds: validSelectedIds
    };
  });
};
var mapSelectedNames = (ids, items) => {
  return ids.map((id) => {
    const item = items.find((t) => t.id === id);
    return item ? item.name : null;
  }).filter((name) => name !== null);
};
var useActivityFiltersDataImpl = (apiClient, options) => {
  const { selectedSubjects, institutionId } = options;
  const [banksState, setBanksState] = (0, import_react35.useState)({
    banks: [],
    bankYears: [],
    loading: false,
    error: null
  });
  const loadBanks = (0, import_react35.useCallback)(async () => {
    setBanksState((prev) => ({ ...prev, loading: true, error: null }));
    try {
      const response = await apiClient.get(
        "/questions/exam-institutions"
      );
      const banksMap = /* @__PURE__ */ new Map();
      const bankYearsArray = [];
      for (const item of response.data.data) {
        if (!item.questionBankName) continue;
        const existingBank = banksMap.get(item.questionBankName);
        if (existingBank) {
          if (!existingBank.years.includes(item.year)) {
            existingBank.years.push(item.year);
          }
          existingBank.questionsCount += item.questionsCount;
        } else {
          banksMap.set(item.questionBankName, {
            id: item.questionBankName,
            name: item.questionBankName,
            examInstitution: item.questionBankName,
            years: [item.year],
            questionsCount: item.questionsCount
          });
        }
        bankYearsArray.push({
          id: `${item.questionBankYearId}-${item.questionBankName}`,
          name: item.year,
          bankId: item.questionBankName
        });
      }
      const banks = Array.from(banksMap.values()).map((bank) => ({
        id: bank.id,
        name: bank.name,
        examInstitution: bank.examInstitution
      }));
      setBanksState({
        banks,
        bankYears: bankYearsArray,
        loading: false,
        error: null
      });
    } catch (error) {
      console.error("Erro ao carregar bancas de vestibular:", error);
      setBanksState((prev) => ({
        ...prev,
        loading: false,
        error: "Erro ao carregar bancas de vestibular"
      }));
    }
  }, [apiClient]);
  const [areasState, setAreasState] = (0, import_react35.useState)({
    knowledgeAreas: [],
    loading: false,
    error: null
  });
  const loadKnowledgeAreas = (0, import_react35.useCallback)(async () => {
    setAreasState((prev) => ({ ...prev, loading: true, error: null }));
    try {
      const response = await apiClient.get(
        "/knowledge/subjects"
      );
      setAreasState({
        knowledgeAreas: response.data.data,
        loading: false,
        error: null
      });
    } catch (error) {
      console.error("Erro ao carregar \xE1reas de conhecimento:", error);
      setAreasState((prev) => ({
        ...prev,
        loading: false,
        error: "Erro ao carregar \xE1reas de conhecimento"
      }));
    }
  }, [apiClient]);
  const [questionTypesState, setQuestionTypesState] = (0, import_react35.useState)({
    questionTypes: [],
    loading: false,
    error: null
  });
  const loadQuestionTypes = (0, import_react35.useCallback)(async () => {
    if (!institutionId) {
      setQuestionTypesState((prev) => ({
        ...prev,
        questionTypes: [],
        loading: false,
        error: null
      }));
      return;
    }
    setQuestionTypesState((prev) => ({
      ...prev,
      loading: true,
      error: null
    }));
    try {
      const response = await apiClient.get(
        `/institutions/${institutionId}/question-types`
      );
      const mappedTypes = response.data.data.questionTypes.map((type) => mapQuestionTypeToEnum(type)).filter((type) => type !== null);
      setQuestionTypesState({
        questionTypes: mappedTypes,
        loading: false,
        error: null
      });
    } catch (error) {
      console.error("Erro ao carregar tipos de quest\xF5es:", error);
      setQuestionTypesState((prev) => ({
        ...prev,
        loading: false,
        error: "Erro ao carregar tipos de quest\xF5es"
      }));
    }
  }, [apiClient, institutionId]);
  const [knowledgeStructure, setKnowledgeStructure] = (0, import_react35.useState)({
    topics: [],
    subtopics: [],
    contents: [],
    loading: false,
    error: null
  });
  const [knowledgeCategories, setKnowledgeCategories] = (0, import_react35.useState)([]);
  const previousSubjectsRef = (0, import_react35.useRef)(null);
  const loadTopics = (0, import_react35.useCallback)(
    async (subjectIds) => {
      if (subjectIds.length === 0) {
        setKnowledgeStructure({
          topics: [],
          subtopics: [],
          contents: [],
          loading: false,
          error: null
        });
        setKnowledgeCategories([]);
        return;
      }
      setKnowledgeStructure((prev) => ({
        ...prev,
        loading: true,
        error: null
      }));
      try {
        const response = await apiClient.post(
          "/knowledge/topics",
          { subjectIds }
        );
        const topics = response.data.data.map((topic) => ({
          id: topic.id,
          name: topic.name
        }));
        setKnowledgeStructure((prev) => ({
          ...prev,
          topics,
          subtopics: [],
          contents: [],
          loading: false,
          error: null
        }));
      } catch (error) {
        console.error("Erro ao carregar temas:", error);
        setKnowledgeStructure((prev) => ({
          ...prev,
          topics: [],
          subtopics: [],
          contents: [],
          loading: false,
          error: "Erro ao carregar temas"
        }));
      }
    },
    [apiClient]
  );
  const loadSubtopics = (0, import_react35.useCallback)(
    async (topicIds, options2 = {}) => {
      const { forceApi = false } = options2;
      if (topicIds.length === 0 && !forceApi) {
        setKnowledgeStructure((prev) => ({
          ...prev,
          subtopics: [],
          contents: [],
          loading: false,
          error: null
        }));
        return;
      }
      setKnowledgeStructure((prev) => ({
        ...prev,
        loading: topicIds.length > 0,
        error: null
      }));
      try {
        const response = await apiClient.post(
          "/knowledge/subtopics",
          { topicIds }
        );
        const subtopics = response.data.data.map(
          (subtopic) => ({
            id: subtopic.id,
            name: subtopic.name,
            topicId: subtopic.topicId || topicIds[0]
          })
        );
        setKnowledgeStructure((prev) => ({
          ...prev,
          subtopics,
          contents: [],
          loading: false,
          error: null
        }));
      } catch (error) {
        console.error("Erro ao carregar subtemas:", error);
        setKnowledgeStructure((prev) => ({
          ...prev,
          subtopics: [],
          contents: [],
          loading: false,
          error: "Erro ao carregar subtemas"
        }));
      }
    },
    [apiClient]
  );
  const loadContents = (0, import_react35.useCallback)(
    async (subtopicIds) => {
      if (subtopicIds.length === 0) {
        setKnowledgeStructure((prev) => ({
          ...prev,
          contents: [],
          loading: false,
          error: null
        }));
        return;
      }
      setKnowledgeStructure((prev) => ({
        ...prev,
        loading: true,
        error: null
      }));
      try {
        const response = await apiClient.post(
          "/knowledge/contents",
          { subtopicIds }
        );
        const contents = response.data.data.map(
          (content) => ({
            id: content.id,
            name: content.name,
            subtopicId: content.subtopicId || subtopicIds[0]
          })
        );
        setKnowledgeStructure((prev) => ({
          ...prev,
          contents,
          loading: false,
          error: null
        }));
      } catch (error) {
        console.error("Erro ao carregar conte\xFAdos:", error);
        setKnowledgeStructure((prev) => ({
          ...prev,
          contents: [],
          loading: false,
          error: "Erro ao carregar conte\xFAdos"
        }));
      }
    },
    [apiClient]
  );
  (0, import_react35.useEffect)(() => {
    const previousSubjects = previousSubjectsRef.current;
    const subjectsChanged = !previousSubjects || previousSubjects.length !== selectedSubjects.length || selectedSubjects.some((id, index) => id !== previousSubjects[index]);
    if (!subjectsChanged) return;
    previousSubjectsRef.current = selectedSubjects;
    if (selectedSubjects.length > 0) {
      loadTopics(selectedSubjects);
      return;
    }
    setKnowledgeStructure({
      topics: [],
      subtopics: [],
      contents: [],
      loading: false,
      error: null
    });
    setKnowledgeCategories([]);
  }, [selectedSubjects, loadTopics]);
  const handleCategoriesChange = (0, import_react35.useCallback)(
    (updatedCategories) => {
      const isFirstChange = knowledgeCategories.length === 0;
      const currentTemaCategory = knowledgeCategories.find(
        (c) => c.key === "tema"
      );
      const currentSubtemaCategory = knowledgeCategories.find(
        (c) => c.key === "subtema"
      );
      const currentSelectedTopicIds = currentTemaCategory?.selectedIds || [];
      const currentSelectedSubtopicIds = currentSubtemaCategory?.selectedIds || [];
      const temaCategory = updatedCategories.find((c) => c.key === "tema");
      const selectedTopicIds = temaCategory?.selectedIds || [];
      const subtemaCategory = updatedCategories.find(
        (c) => c.key === "subtema"
      );
      const selectedSubtopicIds = subtemaCategory?.selectedIds || [];
      setKnowledgeCategories(updatedCategories);
      const topicIdsChanged = isFirstChange || currentSelectedTopicIds.length !== selectedTopicIds.length || currentSelectedTopicIds.some(
        (id) => !selectedTopicIds.includes(id)
      ) || selectedTopicIds.some(
        (id) => !currentSelectedTopicIds.includes(id)
      );
      if (topicIdsChanged) {
        loadSubtopics(selectedTopicIds, {
          forceApi: selectedTopicIds.length === 0
        });
      }
      const subtopicIdsChanged = isFirstChange || currentSelectedSubtopicIds.length !== selectedSubtopicIds.length || currentSelectedSubtopicIds.some(
        (id) => !selectedSubtopicIds.includes(id)
      ) || selectedSubtopicIds.some(
        (id) => !currentSelectedSubtopicIds.includes(id)
      );
      if (subtopicIdsChanged) {
        if (selectedSubtopicIds.length > 0) {
          loadContents(selectedSubtopicIds);
        } else {
          loadContents([]);
        }
      }
    },
    [knowledgeCategories, loadSubtopics, loadContents]
  );
  (0, import_react35.useEffect)(() => {
    if (knowledgeStructure.topics.length === 0) {
      setKnowledgeCategories((prev) => {
        if (prev.length === 0) {
          return prev;
        }
        return [];
      });
      return;
    }
    const categories = [
      {
        key: "tema",
        label: "Tema",
        dependsOn: [],
        itens: knowledgeStructure.topics,
        selectedIds: []
      },
      {
        key: "subtema",
        label: "Subtema",
        dependsOn: ["tema"],
        itens: knowledgeStructure.subtopics,
        filteredBy: [{ key: "tema", internalField: "topicId" }],
        selectedIds: []
      },
      {
        key: "assunto",
        label: "Assunto",
        dependsOn: ["subtema"],
        itens: knowledgeStructure.contents,
        filteredBy: [{ key: "subtema", internalField: "subtopicId" }],
        selectedIds: []
      }
    ];
    setKnowledgeCategories(
      (prev) => areCategoriesSame(prev, categories) ? prev : mergeCategoriesWithSelection(prev, categories)
    );
  }, [
    selectedSubjects,
    knowledgeStructure.topics,
    knowledgeStructure.subtopics,
    knowledgeStructure.contents
  ]);
  const selectedKnowledgeSummary = (0, import_react35.useMemo)(() => {
    const temaCategory = knowledgeCategories.find((c) => c.key === "tema");
    const subtemaCategory = knowledgeCategories.find(
      (c) => c.key === "subtema"
    );
    const assuntoCategory = knowledgeCategories.find(
      (c) => c.key === "assunto"
    );
    const selectedTopics = mapSelectedNames(
      temaCategory?.selectedIds || [],
      knowledgeStructure.topics
    );
    const selectedSubtopics = mapSelectedNames(
      subtemaCategory?.selectedIds || [],
      knowledgeStructure.subtopics
    );
    const selectedContents = mapSelectedNames(
      assuntoCategory?.selectedIds || [],
      knowledgeStructure.contents
    );
    return {
      topics: selectedTopics,
      subtopics: selectedSubtopics,
      contents: selectedContents
    };
  }, [knowledgeCategories, knowledgeStructure]);
  const enableSummary = (0, import_react35.useMemo)(() => {
    return knowledgeStructure.topics.length === 1 || knowledgeStructure.subtopics.length === 1 || knowledgeStructure.contents.length === 1;
  }, [knowledgeStructure]);
  return {
    // Vestibular Banks
    banks: banksState.banks,
    bankYears: banksState.bankYears,
    loadingBanks: banksState.loading,
    banksError: banksState.error,
    loadBanks,
    // Knowledge Areas
    knowledgeAreas: areasState.knowledgeAreas,
    loadingSubjects: areasState.loading,
    subjectsError: areasState.error,
    loadKnowledgeAreas,
    // Knowledge Structure
    knowledgeStructure,
    knowledgeCategories,
    handleCategoriesChange,
    selectedKnowledgeSummary,
    enableSummary,
    loadTopics,
    loadSubtopics,
    loadContents,
    // Question Types
    questionTypes: questionTypesState.questionTypes,
    loadingQuestionTypes: questionTypesState.loading,
    questionTypesError: questionTypesState.error,
    loadQuestionTypes
  };
};
var createUseActivityFiltersData = (apiClient) => {
  return (options) => useActivityFiltersDataImpl(apiClient, options);
};
var createActivityFiltersDataHook = (apiClient) => {
  return createUseActivityFiltersData(apiClient);
};

// src/hooks/useQuestionsList.ts
var import_react36 = require("react");
var useQuestionsListImpl = (apiClient) => {
  const [state, setState] = (0, import_react36.useState)({
    questions: [],
    pagination: null,
    loading: false,
    loadingMore: false,
    error: null,
    currentFilters: null
  });
  const updateState = (0, import_react36.useCallback)((updates) => {
    setState((prev) => ({ ...prev, ...updates }));
  }, []);
  const handleError = (0, import_react36.useCallback)(
    (error) => {
      console.error("Erro ao carregar quest\xF5es:", error);
      let errorMessage = "Erro ao carregar quest\xF5es";
      if (error && typeof error === "object" && "response" in error) {
        const axiosError = error;
        errorMessage = axiosError?.response?.data?.message || axiosError?.message || errorMessage;
      } else if (error instanceof Error) {
        errorMessage = error.message;
      }
      updateState({
        loading: false,
        loadingMore: false,
        error: errorMessage
      });
    },
    [updateState]
  );
  const convertPagination = (pagination) => {
    if (!pagination) return null;
    return {
      page: pagination.page,
      pageSize: pagination.limit,
      total: pagination.total,
      totalPages: pagination.totalPages,
      hasNext: pagination.hasNext,
      hasPrevious: pagination.hasPrev
    };
  };
  const fetchQuestions = (0, import_react36.useCallback)(
    async (filters, append = false) => {
      if (append) {
        setState((prev) => ({ ...prev, loadingMore: true, error: null }));
      } else {
        updateState({ loading: true, error: null, questions: [] });
      }
      try {
        const validatedFilters = {
          ...filters
        };
        const response = await apiClient.post(
          "/questions/list",
          validatedFilters
        );
        setState((prev) => ({
          loading: false,
          loadingMore: false,
          questions: append ? [...prev.questions, ...response.data.data.questions] : response.data.data.questions,
          pagination: convertPagination(response.data.data.pagination),
          error: null,
          currentFilters: validatedFilters
        }));
      } catch (error) {
        setState((prev) => ({
          ...prev,
          loading: false,
          loadingMore: false
        }));
        handleError(error);
      }
    },
    [apiClient, updateState, handleError]
  );
  const fetchRandomQuestions = (0, import_react36.useCallback)(
    async (count, filters) => {
      try {
        const validatedFilters = {
          ...filters,
          randomQuestions: count
        };
        const response = await apiClient.post(
          "/questions/list",
          validatedFilters
        );
        return response.data.data.questions;
      } catch (error) {
        handleError(error);
        return [];
      }
    },
    [apiClient, handleError]
  );
  const fetchQuestionsByIds = (0, import_react36.useCallback)(
    async (questionIds) => {
      try {
        const body = {
          questionsIds: questionIds
        };
        const response = await apiClient.post(
          "/questions/by-ids",
          body
        );
        return response.data.data.questions;
      } catch (error) {
        handleError(error);
        return [];
      }
    },
    [apiClient, handleError]
  );
  const loadMore = (0, import_react36.useCallback)(async () => {
    setState((prev) => {
      const { currentFilters, pagination, loadingMore: isLoadingMore } = prev;
      if (isLoadingMore || !currentFilters || !pagination?.hasNext) {
        return prev;
      }
      const nextPageFilters = {
        ...currentFilters,
        page: pagination.page + 1
      };
      fetchQuestions(nextPageFilters, true).catch((error) => {
        console.error("Erro ao carregar mais quest\xF5es:", error);
      });
      return {
        ...prev,
        loadingMore: true
      };
    });
  }, [fetchQuestions]);
  const reset = (0, import_react36.useCallback)(() => {
    setState({
      questions: [],
      pagination: null,
      loading: false,
      loadingMore: false,
      error: null,
      currentFilters: null
    });
  }, []);
  return {
    ...state,
    fetchQuestions,
    fetchRandomQuestions,
    fetchQuestionsByIds,
    loadMore,
    reset
  };
};
var createUseQuestionsList = (apiClient) => {
  return () => useQuestionsListImpl(apiClient);
};
var createQuestionsListHook = (apiClient) => {
  return createUseQuestionsList(apiClient);
};

// src/components/ActivityCreate/ActivityCreate.tsx
var import_react38 = require("react");
var import_react_router_dom = require("react-router-dom");
var import_phosphor_react28 = require("phosphor-react");

// src/components/ActivityListQuestions/ActivityListQuestions.tsx
var import_react37 = require("react");
var import_phosphor_react26 = require("phosphor-react");

// src/utils/questionFiltersConverter.ts
var convertActivityFiltersToQuestionsFilter = (filters) => {
  return {
    types: filters.types.length > 0 ? filters.types : void 0,
    bankIds: filters.bankIds.length > 0 ? filters.bankIds : void 0,
    yearIds: filters.yearIds.length > 0 ? filters.yearIds : void 0,
    knowledgeIds: filters.knowledgeIds.length > 0 ? filters.knowledgeIds : void 0,
    topicIds: filters.topicIds.length > 0 ? filters.topicIds : void 0,
    subtopicIds: filters.subtopicIds.length > 0 ? filters.subtopicIds : void 0,
    contentIds: filters.contentIds.length > 0 ? filters.contentIds : void 0
  };
};

// src/components/ActivityListQuestions/ActivityListQuestions.tsx
var import_jsx_runtime58 = require("react/jsx-runtime");
var ActivityListQuestions = ({
  apiClient,
  onAddQuestion,
  addedQuestionIds = [],
  className
}) => {
  const { isDark } = useTheme();
  const [isModalOpen, setIsModalOpen] = (0, import_react37.useState)(false);
  const [questionCount, setQuestionCount] = (0, import_react37.useState)(1);
  const appliedFilters = useQuestionFiltersStore(
    (state) => state.appliedFilters
  );
  const addedQuestionIdsRef = (0, import_react37.useRef)(addedQuestionIds);
  (0, import_react37.useEffect)(() => {
    addedQuestionIdsRef.current = addedQuestionIds;
  }, [addedQuestionIds]);
  const useQuestionsList = (0, import_react37.useMemo)(
    () => createUseQuestionsList(apiClient),
    [apiClient]
  );
  const {
    questions: allQuestions,
    pagination,
    loading,
    loadingMore,
    error,
    fetchQuestions,
    fetchRandomQuestions,
    loadMore,
    reset
  } = useQuestionsList();
  const questions = (0, import_react37.useMemo)(() => {
    return allQuestions.filter(
      (question) => !addedQuestionIds.includes(question.id)
    );
  }, [allQuestions, addedQuestionIds]);
  const observerTarget = (0, import_react37.useRef)(null);
  const formatQuestionOptions = (questionOptions) => {
    return questionOptions.map((opt) => ({
      id: opt.id,
      option: opt.option
    }));
  };
  const getSubjectInfo2 = (question) => {
    if (!question.knowledgeMatrix || question.knowledgeMatrix.length === 0) {
      return { assunto: "Sem assunto", color: "#6B7280" };
    }
    const matrix = question.knowledgeMatrix[0];
    const subject = matrix.subject;
    const topic = matrix.topic;
    const subtopic = matrix.subtopic;
    if (!subject) {
      return { assunto: "Sem assunto", color: "#6B7280" };
    }
    const parts = [subject.name];
    if (topic?.name) parts.push(topic.name);
    if (subtopic?.name) parts.push(subtopic.name);
    return {
      assunto: parts.join(" - "),
      color: subject.color || "#6B7280"
    };
  };
  (0, import_react37.useEffect)(() => {
    if (appliedFilters) {
      const apiFilters = {
        ...convertActivityFiltersToQuestionsFilter(appliedFilters),
        ...addedQuestionIdsRef.current.length > 0 && {
          selectedQuestionsIds: addedQuestionIdsRef.current
        }
      };
      fetchQuestions(apiFilters, false);
    } else {
      reset();
    }
  }, [appliedFilters, fetchQuestions, reset]);
  (0, import_react37.useEffect)(() => {
    const observer = new IntersectionObserver(
      (entries) => {
        if (entries[0].isIntersecting && !loading && !loadingMore && pagination?.hasNext) {
          loadMore();
        }
      },
      { threshold: 0.1 }
    );
    const currentTarget = observerTarget.current;
    if (currentTarget) {
      observer.observe(currentTarget);
    }
    return () => {
      if (currentTarget) {
        observer.unobserve(currentTarget);
      }
    };
  }, [loading, loadingMore, pagination, loadMore]);
  const totalQuestions = pagination?.total || 0;
  const uniqueQuestion = () => {
    return totalQuestions === 1 ? "quest\xE3o" : "quest\xF5es";
  };
  const handleAddAutomatically = async () => {
    if (questionCount <= 0) return;
    try {
      const baseFilters = appliedFilters ? convertActivityFiltersToQuestionsFilter(appliedFilters) : {};
      const randomQuestions = await fetchRandomQuestions(questionCount, {
        ...baseFilters,
        ...addedQuestionIds.length > 0 && {
          selectedQuestionsIds: addedQuestionIds
        }
      });
      randomQuestions.forEach((question) => {
        if (onAddQuestion) {
          onAddQuestion(question);
        }
      });
      setIsModalOpen(false);
      setQuestionCount(1);
    } catch (error2) {
      console.error("Erro ao adicionar quest\xF5es automaticamente:", error2);
    }
  };
  const handleCloseModal = () => {
    setIsModalOpen(false);
    setQuestionCount(1);
  };
  const renderQuestionsContent = () => {
    if (loading && questions.length === 0) {
      return /* @__PURE__ */ (0, import_jsx_runtime58.jsx)("div", { className: "flex flex-col gap-2", children: [1, 2, 3].map((i) => /* @__PURE__ */ (0, import_jsx_runtime58.jsx)("div", { className: "p-4 border rounded", children: /* @__PURE__ */ (0, import_jsx_runtime58.jsx)(SkeletonText, { lines: 2 }) }, i)) });
    }
    if (error) {
      return /* @__PURE__ */ (0, import_jsx_runtime58.jsx)("div", { className: "flex items-center justify-center h-full", children: /* @__PURE__ */ (0, import_jsx_runtime58.jsxs)(Text_default, { size: "md", className: "text-text-600", children: [
        "Erro ao carregar quest\xF5es: ",
        error
      ] }) });
    }
    if (questions.length === 0) {
      return /* @__PURE__ */ (0, import_jsx_runtime58.jsx)("div", { className: "flex items-center justify-center h-full", children: /* @__PURE__ */ (0, import_jsx_runtime58.jsx)(Text_default, { size: "md", className: "text-text-600", children: "Nenhuma quest\xE3o encontrada. Aplique os filtros para buscar quest\xF5es." }) });
    }
    return /* @__PURE__ */ (0, import_jsx_runtime58.jsxs)(import_jsx_runtime58.Fragment, { children: [
      questions.map((question) => {
        const subjectInfo = getSubjectInfo2(question);
        const questionType = mapQuestionTypeToEnumRequired(
          question.questionType
        );
        return /* @__PURE__ */ (0, import_jsx_runtime58.jsx)(
          ActivityCardQuestionBanks,
          {
            question: question.options ? {
              options: formatQuestionOptions(
                question.options
              ),
              correctOptionIds: []
            } : void 0,
            questionType,
            iconName: "Atom",
            subjectColor: subjectInfo.color,
            isDark,
            assunto: subjectInfo.assunto,
            enunciado: question.statement,
            onAddToActivity: () => {
              if (onAddQuestion) {
                onAddQuestion(question);
              }
            }
          },
          question.id
        );
      }),
      pagination?.hasNext && /* @__PURE__ */ (0, import_jsx_runtime58.jsx)("div", { ref: observerTarget, className: "h-4 w-full", children: loadingMore && /* @__PURE__ */ (0, import_jsx_runtime58.jsx)("div", { className: "flex flex-col gap-2 py-4", children: [1, 2].map((i) => /* @__PURE__ */ (0, import_jsx_runtime58.jsx)("div", { className: "p-4 border rounded", children: /* @__PURE__ */ (0, import_jsx_runtime58.jsx)(SkeletonText, { lines: 2 }) }, i)) }) })
    ] });
  };
  return /* @__PURE__ */ (0, import_jsx_runtime58.jsxs)(
    "div",
    {
      className: `w-full flex flex-col p-4 gap-2 overflow-hidden h-full min-h-0 ${className || ""}`,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime58.jsxs)("div", { className: "flex flex-col gap-2 flex-shrink-0", children: [
          /* @__PURE__ */ (0, import_jsx_runtime58.jsxs)("section", { className: "flex flex-row items-center gap-2 text-text-950", children: [
            /* @__PURE__ */ (0, import_jsx_runtime58.jsx)(import_phosphor_react26.Notebook, { size: 24 }),
            /* @__PURE__ */ (0, import_jsx_runtime58.jsx)(Text_default, { size: "lg", weight: "bold", children: "Banco de quest\xF5es" })
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime58.jsxs)("section", { className: "flex flex-row justify-between items-center", children: [
            /* @__PURE__ */ (0, import_jsx_runtime58.jsx)(Text_default, { size: "sm", className: "text-text-800", children: loading ? "Carregando..." : `${totalQuestions} ${uniqueQuestion()} total` }),
            /* @__PURE__ */ (0, import_jsx_runtime58.jsx)(Button_default, { size: "small", onClick: () => setIsModalOpen(true), children: "Adicionar automaticamente" })
          ] })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime58.jsx)("div", { className: "flex flex-col gap-3 overflow-auto flex-1 min-h-0", children: renderQuestionsContent() }),
        /* @__PURE__ */ (0, import_jsx_runtime58.jsx)(
          Modal_default,
          {
            isOpen: isModalOpen,
            onClose: handleCloseModal,
            title: "Adicionar automaticamente",
            size: "md",
            hideCloseButton: true,
            contentClassName: "p-0",
            footer: /* @__PURE__ */ (0, import_jsx_runtime58.jsxs)("div", { className: "flex gap-3", children: [
              /* @__PURE__ */ (0, import_jsx_runtime58.jsx)(Button_default, { variant: "outline", onClick: handleCloseModal, children: "Cancelar" }),
              /* @__PURE__ */ (0, import_jsx_runtime58.jsx)(
                Button_default,
                {
                  variant: "solid",
                  onClick: handleAddAutomatically,
                  disabled: questionCount <= 0 || !appliedFilters,
                  children: "Adicionar"
                }
              )
            ] }),
            children: /* @__PURE__ */ (0, import_jsx_runtime58.jsx)("div", { className: "flex flex-col", children: /* @__PURE__ */ (0, import_jsx_runtime58.jsxs)("div", { className: "px-6 py-6 flex flex-col gap-4", children: [
              /* @__PURE__ */ (0, import_jsx_runtime58.jsx)(Text_default, { size: "sm", className: "text-text-600", children: "Defina a quantidade de quest\xF5es que voc\xEA quer que o sistema adicione automaticamente na sua atividade" }),
              /* @__PURE__ */ (0, import_jsx_runtime58.jsx)("div", { className: "flex flex-col gap-2", children: /* @__PURE__ */ (0, import_jsx_runtime58.jsx)(
                Input_default,
                {
                  type: "number",
                  min: 1,
                  value: questionCount > 0 ? questionCount : "",
                  onChange: (e) => {
                    const inputValue = e.target.value;
                    if (inputValue === "") {
                      setQuestionCount(0);
                      return;
                    }
                    const numValue = Number.parseInt(inputValue, 10);
                    if (!Number.isNaN(numValue) && numValue > 0) {
                      setQuestionCount(numValue);
                    }
                  },
                  placeholder: "Insira o n\xFAmero",
                  variant: "outlined"
                }
              ) })
            ] }) })
          }
        )
      ]
    }
  );
};

// src/components/ActivityCreate/ActivityCreate.types.ts
var ActivityType = /* @__PURE__ */ ((ActivityType2) => {
  ActivityType2["RASCUNHO"] = "RASCUNHO";
  ActivityType2["MODELO"] = "MODELO";
  ActivityType2["ATIVIDADE"] = "ATIVIDADE";
  return ActivityType2;
})(ActivityType || {});
var ActivityStatus = /* @__PURE__ */ ((ActivityStatus2) => {
  ActivityStatus2["A_VENCER"] = "A_VENCER";
  return ActivityStatus2;
})(ActivityStatus || {});

// src/components/ActivityCreate/ActivityCreate.utils.ts
var VALID_QUESTION_TYPES = new Set(Object.values(QUESTION_TYPE));
var isValidQuestionType = (type) => {
  return VALID_QUESTION_TYPES.has(type);
};
function convertFiltersToBackendFormat(filters) {
  if (!filters) {
    return {
      questionTypes: [],
      questionBanks: [],
      subjects: [],
      topics: [],
      subtopics: [],
      contents: []
    };
  }
  return {
    questionTypes: filters.types,
    questionBanks: filters.bankIds,
    subjects: filters.knowledgeIds,
    topics: filters.topicIds,
    subtopics: filters.subtopicIds,
    contents: filters.contentIds
  };
}
function convertBackendFiltersToActivityFiltersData(backendFilters) {
  if (!backendFilters) {
    return null;
  }
  return {
    types: (backendFilters.questionTypes || []).filter(isValidQuestionType),
    bankIds: backendFilters.questionBanks || [],
    knowledgeIds: backendFilters.subjects || [],
    topicIds: backendFilters.topics || [],
    subtopicIds: backendFilters.subtopics || [],
    contentIds: backendFilters.contents || [],
    yearIds: []
  };
}
function getSubjectName2(subjectId, knowledgeAreas) {
  if (!subjectId || !knowledgeAreas.length) {
    return null;
  }
  const subject = knowledgeAreas.find((area) => area.id === subjectId);
  return subject?.name || null;
}
function getActivityTypeLabel(type) {
  const activityTypeLabels = {
    ["RASCUNHO" /* RASCUNHO */]: "Rascunho",
    ["MODELO" /* MODELO */]: "Modelo",
    ["ATIVIDADE" /* ATIVIDADE */]: "Atividade"
  };
  return activityTypeLabels[type];
}
function generateTitle(type, subjectId, knowledgeAreas) {
  const typeLabel = getActivityTypeLabel(type);
  const subjectName = getSubjectName2(subjectId, knowledgeAreas);
  return subjectName ? `${typeLabel} - ${subjectName}` : typeLabel;
}
function formatTime(date) {
  const hours = date.getHours().toString().padStart(2, "0");
  const minutes = date.getMinutes().toString().padStart(2, "0");
  return `${hours}:${minutes}`;
}
function getTypeFromUrl(type) {
  switch (type) {
    case "RASCUNHO" /* RASCUNHO */:
      return "rascunho";
    case "MODELO" /* MODELO */:
      return "modelo";
    default:
      return "rascunho";
  }
}
function getTypeFromUrlString(type) {
  switch (type) {
    case "rascunho":
      return "RASCUNHO" /* RASCUNHO */;
    case "modelo":
      return "MODELO" /* MODELO */;
    default:
      return "RASCUNHO" /* RASCUNHO */;
  }
}
function convertQuestionToPreview(question) {
  const subjectInfo = question.knowledgeMatrix && question.knowledgeMatrix.length > 0 ? {
    subjectName: question.knowledgeMatrix[0].subject?.name || void 0,
    subjectColor: question.knowledgeMatrix[0].subject?.color || void 0,
    iconName: question.knowledgeMatrix[0].subject?.icon || void 0
  } : {};
  return {
    id: question.id,
    enunciado: question.statement,
    questionType: question.questionType,
    question: question.options ? {
      options: question.options.map(
        (opt) => ({
          id: opt.id,
          option: opt.option
        })
      ),
      correctOptionIds: []
    } : void 0,
    ...subjectInfo
  };
}
async function fetchAllStudents(apiClient) {
  const allStudents = [];
  let currentPage = 1;
  let totalPages = 1;
  const limit = 100;
  do {
    const response = await apiClient.get(`/students?page=${currentPage}&limit=${limit}`);
    const { students, pagination } = response.data.data;
    allStudents.push(...students);
    totalPages = pagination.totalPages;
    currentPage++;
  } while (currentPage <= totalPages);
  return allStudents;
}
async function loadCategoriesData(apiClient, existingCategories) {
  if (existingCategories.length > 0) {
    return existingCategories;
  }
  const [schoolsResponse, schoolYearsResponse, classesResponse, allStudents] = await Promise.all([
    apiClient.get(
      "/school"
    ),
    apiClient.get("/schoolYear"),
    apiClient.get("/classes"),
    fetchAllStudents(apiClient)
  ]);
  const schools = schoolsResponse.data.data.schools;
  const schoolYears = schoolYearsResponse.data.data.schoolYears;
  const classes = classesResponse.data.data.classes;
  const students = allStudents;
  const transformedCategories = [
    {
      key: "escola",
      label: "Escola",
      itens: schools.map((s) => ({ id: s.id, name: s.companyName })),
      selectedIds: []
    },
    {
      key: "serie",
      label: "S\xE9rie",
      dependsOn: ["escola"],
      filteredBy: [{ key: "escola", internalField: "schoolId" }],
      itens: schoolYears.map((sy) => ({
        id: sy.id,
        name: sy.name,
        schoolId: sy.schoolId
      })),
      selectedIds: []
    },
    {
      key: "turma",
      label: "Turma",
      dependsOn: ["serie"],
      filteredBy: [{ key: "serie", internalField: "schoolYearId" }],
      itens: classes.map((c) => ({
        id: c.id,
        name: c.name,
        schoolYearId: c.schoolYearId
      })),
      selectedIds: []
    },
    {
      key: "alunos",
      label: "Alunos",
      dependsOn: ["turma"],
      filteredBy: [{ key: "turma", internalField: "classId" }],
      itens: students.map((s) => ({
        id: s.id,
        name: s.name,
        classId: s.classId,
        studentId: s.id,
        userInstitutionId: s.userInstitutionId
      })),
      selectedIds: []
    }
  ];
  return transformedCategories;
}

// src/components/ActivityCreate/components/ActivityCreateSkeleton.tsx
var import_jsx_runtime59 = require("react/jsx-runtime");
var ActivityCreateSkeleton = () => {
  return /* @__PURE__ */ (0, import_jsx_runtime59.jsxs)(
    "div",
    {
      "data-testid": "create-activity-page",
      className: "flex flex-col w-full h-screen overflow-hidden p-5 bg-background",
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime59.jsxs)("div", { className: "w-full h-[80px] flex flex-row items-center justify-between px-6 gap-3 flex-shrink-0", children: [
          /* @__PURE__ */ (0, import_jsx_runtime59.jsx)("section", { className: "text-text-950", children: /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(Skeleton, { variant: "rectangular", width: 32, height: 32 }) }),
          /* @__PURE__ */ (0, import_jsx_runtime59.jsxs)("section", { className: "flex flex-col gap-0.5 w-full", children: [
            /* @__PURE__ */ (0, import_jsx_runtime59.jsxs)("div", { className: "flex flex-row items-center justify-between w-full text-text-950", children: [
              /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(SkeletonText, { width: 180, height: 24 }),
              /* @__PURE__ */ (0, import_jsx_runtime59.jsxs)("div", { className: "flex flex-row gap-4 items-center", children: [
                /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(SkeletonText, { width: 150, height: 16 }),
                /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(Skeleton, { variant: "rounded", width: 120, height: 32 }),
                /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(Skeleton, { variant: "rounded", width: 140, height: 32 })
              ] })
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(SkeletonText, { width: 400, height: 16 })
          ] })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime59.jsxs)("div", { className: "flex flex-row w-full flex-1 overflow-hidden gap-5 min-h-0", children: [
          /* @__PURE__ */ (0, import_jsx_runtime59.jsxs)("div", { className: "flex flex-col gap-3 overflow-hidden h-full min-h-0 max-h-full relative w-[400px] flex-shrink-0 p-4 bg-background", children: [
            /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(SkeletonText, { width: 150, height: 20 }),
            /* @__PURE__ */ (0, import_jsx_runtime59.jsxs)("div", { className: "flex flex-col gap-4 mt-4", children: [
              /* @__PURE__ */ (0, import_jsx_runtime59.jsxs)("div", { className: "flex flex-col gap-3", children: [
                /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(SkeletonText, { width: 120, height: 16 }),
                /* @__PURE__ */ (0, import_jsx_runtime59.jsx)("div", { className: "grid grid-cols-2 gap-2", children: [1, 2, 3, 4].map((i) => /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(
                  Skeleton,
                  {
                    variant: "rounded",
                    width: "100%",
                    height: 32
                  },
                  i
                )) })
              ] }),
              /* @__PURE__ */ (0, import_jsx_runtime59.jsxs)("div", { className: "flex flex-col gap-3", children: [
                /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(SkeletonText, { width: 140, height: 16 }),
                /* @__PURE__ */ (0, import_jsx_runtime59.jsx)("div", { className: "flex flex-col gap-2", children: [1, 2].map((i) => /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(
                  Skeleton,
                  {
                    variant: "rounded",
                    width: "100%",
                    height: 40
                  },
                  i
                )) })
              ] }),
              /* @__PURE__ */ (0, import_jsx_runtime59.jsxs)("div", { className: "flex flex-col gap-3", children: [
                /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(SkeletonText, { width: 80, height: 16 }),
                /* @__PURE__ */ (0, import_jsx_runtime59.jsx)("div", { className: "grid grid-cols-3 gap-3", children: [1, 2].map((i) => /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(
                  Skeleton,
                  {
                    variant: "rounded",
                    width: "100%",
                    height: 60
                  },
                  i
                )) })
              ] })
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime59.jsx)("div", { className: "mt-auto", children: /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(Skeleton, { variant: "rounded", width: "100%", height: 40 }) })
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime59.jsx)("div", { className: "flex-1 min-w-0 overflow-hidden h-full p-4", children: /* @__PURE__ */ (0, import_jsx_runtime59.jsxs)("div", { className: "flex flex-col gap-4 h-full", children: [
            /* @__PURE__ */ (0, import_jsx_runtime59.jsxs)("div", { className: "flex flex-row items-center justify-between", children: [
              /* @__PURE__ */ (0, import_jsx_runtime59.jsxs)("div", { className: "flex flex-row items-center gap-2", children: [
                /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(Skeleton, { variant: "rectangular", width: 24, height: 24 }),
                /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(SkeletonText, { width: 150, height: 20 })
              ] }),
              /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(Skeleton, { variant: "rounded", width: 180, height: 32 })
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime59.jsx)("div", { className: "flex flex-col gap-3 flex-1 overflow-auto", children: [1, 2, 3, 4, 5].map((i) => /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(SkeletonCard, { lines: 3 }, i)) })
          ] }) }),
          /* @__PURE__ */ (0, import_jsx_runtime59.jsx)("div", { className: "w-[470px] flex-shrink-0 overflow-hidden h-full min-h-0 p-4", children: /* @__PURE__ */ (0, import_jsx_runtime59.jsxs)("div", { className: "flex flex-col gap-4 h-full", children: [
            /* @__PURE__ */ (0, import_jsx_runtime59.jsxs)("div", { className: "flex flex-col gap-2", children: [
              /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(SkeletonText, { width: 200, height: 20 }),
              /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(SkeletonText, { width: 150, height: 16 })
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime59.jsx)("div", { className: "flex flex-col gap-3 flex-1 overflow-auto", children: [1, 2, 3, 4].map((i) => /* @__PURE__ */ (0, import_jsx_runtime59.jsxs)(
              "div",
              {
                className: "p-4 border border-border-200 rounded-lg",
                children: [
                  /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(SkeletonText, { lines: 2, spacing: "small" }),
                  /* @__PURE__ */ (0, import_jsx_runtime59.jsxs)("div", { className: "mt-3 flex gap-2", children: [
                    /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(Skeleton, { variant: "rounded", width: 60, height: 24 }),
                    /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(Skeleton, { variant: "rounded", width: 80, height: 24 })
                  ] })
                ]
              },
              i
            )) }),
            /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(Skeleton, { variant: "rounded", width: "100%", height: 36 })
          ] }) })
        ] })
      ]
    }
  );
};

// src/components/ActivityCreate/components/ActivityCreateHeader.tsx
var import_phosphor_react27 = require("phosphor-react");
var import_jsx_runtime60 = require("react/jsx-runtime");
var ActivityCreateHeader = ({
  activity,
  activityType,
  lastSavedAt,
  isSaving,
  questionsCount,
  onSaveModel,
  onSendActivity,
  onBack
}) => {
  const activityTypeLabel = getActivityTypeLabel(activityType);
  return /* @__PURE__ */ (0, import_jsx_runtime60.jsxs)("div", { className: "w-full h-[80px] flex flex-row items-center justify-between px-6 gap-3 flex-shrink-0", children: [
    /* @__PURE__ */ (0, import_jsx_runtime60.jsx)(
      Button_default,
      {
        onClick: onBack,
        "aria-label": "Voltar",
        type: "button",
        variant: "link",
        "data-testid": "back-button",
        children: /* @__PURE__ */ (0, import_jsx_runtime60.jsx)(import_phosphor_react27.CaretLeft, { size: 32 })
      }
    ),
    /* @__PURE__ */ (0, import_jsx_runtime60.jsxs)("section", { className: "flex flex-col gap-0.5 w-full", children: [
      /* @__PURE__ */ (0, import_jsx_runtime60.jsxs)("div", { className: "flex flex-row items-center justify-between w-full text-text-950", children: [
        /* @__PURE__ */ (0, import_jsx_runtime60.jsx)(Text_default, { size: "lg", weight: "bold", children: activity ? "Editar atividade" : "Criar atividade" }),
        /* @__PURE__ */ (0, import_jsx_runtime60.jsxs)("div", { className: "flex flex-row gap-4 items-center", children: [
          lastSavedAt ? /* @__PURE__ */ (0, import_jsx_runtime60.jsxs)(Text_default, { size: "sm", children: [
            activityTypeLabel,
            " salvo \xE0s ",
            formatTime(lastSavedAt)
          ] }) : /* @__PURE__ */ (0, import_jsx_runtime60.jsx)(Text_default, { size: "sm", children: isSaving ? "Salvando..." : "Nenhum rascunho salvo" }),
          /* @__PURE__ */ (0, import_jsx_runtime60.jsx)(Button_default, { size: "small", onClick: onSaveModel, children: "Salvar modelo" }),
          /* @__PURE__ */ (0, import_jsx_runtime60.jsx)(
            Button_default,
            {
              size: "small",
              iconLeft: /* @__PURE__ */ (0, import_jsx_runtime60.jsx)(import_phosphor_react27.PaperPlaneTilt, {}),
              onClick: onSendActivity,
              disabled: questionsCount === 0,
              children: "Enviar atividade"
            }
          )
        ] })
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime60.jsx)(Text_default, { size: "sm", children: "Crie uma atividade customizada adicionando quest\xF5es manualmente ou automaticamente." })
    ] })
  ] });
};

// src/components/ActivityCreate/ActivityCreate.tsx
var import_jsx_runtime61 = require("react/jsx-runtime");
var CreateActivity = ({
  apiClient,
  institutionId,
  isDark,
  onBack,
  onCreateActivity,
  onSaveModel
}) => {
  const params = (0, import_react_router_dom.useParams)();
  const navigate = (0, import_react_router_dom.useNavigate)();
  const applyFilters = useQuestionFiltersStore(
    (state) => state.applyFilters
  );
  const draftFilters = useQuestionFiltersStore(
    (state) => state.draftFilters
  );
  const appliedFilters = useQuestionFiltersStore(
    (state) => state.appliedFilters
  );
  const setDraftFilters = useQuestionFiltersStore(
    (state) => state.setDraftFilters
  );
  const addToast = ToastStore_default((state) => state.addToast);
  const [activity, setActivity] = (0, import_react38.useState)(null);
  const [preFilters, setPreFilters] = (0, import_react38.useState)(
    null
  );
  const [loading, setLoading] = (0, import_react38.useState)(false);
  const [questions, setQuestions] = (0, import_react38.useState)([]);
  const [loadingInitialQuestions, setLoadingInitialQuestions] = (0, import_react38.useState)(false);
  const [draftId, setDraftId] = (0, import_react38.useState)(params.id || null);
  const [activityType, setActivityType] = (0, import_react38.useState)(
    getTypeFromUrlString(params.type)
  );
  const [lastSavedAt, setLastSavedAt] = (0, import_react38.useState)(null);
  const [isSaving, setIsSaving] = (0, import_react38.useState)(false);
  const [isSendModalOpen, setIsSendModalOpen] = (0, import_react38.useState)(false);
  const [categories, setCategories] = (0, import_react38.useState)([]);
  const [isSendingActivity, setIsSendingActivity] = (0, import_react38.useState)(false);
  const hasFirstSaveBeenDone = (0, import_react38.useRef)(false);
  const saveTimeoutRef = (0, import_react38.useRef)(null);
  const lastSavedFiltersRef = (0, import_react38.useRef)(null);
  const lastSavedQuestionsRef = (0, import_react38.useRef)([]);
  const hasAppliedInitialFiltersRef = (0, import_react38.useRef)(false);
  const lastFetchedActivityIdRef = (0, import_react38.useRef)(null);
  const handleFiltersChange = (0, import_react38.useCallback)(
    (filters) => {
      setDraftFilters(filters);
    },
    [setDraftFilters]
  );
  const handleApplyFilters = (0, import_react38.useCallback)(() => {
    applyFilters();
  }, [applyFilters]);
  const useActivityFiltersData = createUseActivityFiltersData(apiClient);
  const { knowledgeAreas, loadKnowledgeAreas } = useActivityFiltersData({
    selectedSubjects: [],
    institutionId
  });
  const resolvedPreFilters = (0, import_react38.useMemo)(() => {
    if (!preFilters) {
      return null;
    }
    if (typeof preFilters === "object" && preFilters !== null && "filters" in preFilters) {
      return preFilters.filters;
    }
    return preFilters;
  }, [preFilters]);
  const initialFiltersData = (0, import_react38.useMemo)(() => {
    if (activity?.filters) {
      return convertBackendFiltersToActivityFiltersData(activity.filters);
    }
    if (resolvedPreFilters) {
      return convertBackendFiltersToActivityFiltersData(resolvedPreFilters);
    }
    return null;
  }, [activity?.filters, resolvedPreFilters]);
  (0, import_react38.useEffect)(() => {
    hasAppliedInitialFiltersRef.current = false;
  }, [activity?.id, activity?.filters, resolvedPreFilters]);
  (0, import_react38.useEffect)(() => {
    const fetchActivityDraft = async () => {
      if (params.id && params.id !== lastFetchedActivityIdRef.current) {
        setLoading(true);
        try {
          const response = await apiClient.get(`/activity-drafts/${params.id}`);
          const activityData = "data" in response.data ? response.data.data : response.data;
          setActivity(activityData);
          setPreFilters(activityData.filters);
          setDraftId(activityData.id || null);
          setActivityType(activityData.type);
          if (activityData.updatedAt) {
            setLastSavedAt(new Date(activityData.updatedAt));
          }
          lastFetchedActivityIdRef.current = params.id;
        } catch (error) {
          console.error("Erro ao buscar rascunho da atividade:", error);
          addToast({
            title: "Erro ao carregar atividade",
            description: error instanceof Error ? error.message : "Ocorreu um erro ao carregar a atividade. Tente novamente.",
            variant: "solid",
            action: "warning",
            position: "top-right"
          });
        } finally {
          setLoading(false);
        }
      }
    };
    fetchActivityDraft();
  }, [params.id, apiClient, addToast]);
  (0, import_react38.useEffect)(() => {
    if (activity?.id && activity?.type) {
      const urlType = getTypeFromUrl(activity.type);
      const currentUrlType = params.type;
      const currentUrlId = params.id;
      if (!currentUrlType || !currentUrlId || currentUrlId !== activity.id || currentUrlType !== urlType) {
        navigate(`/criar-atividade/${urlType}/${activity.id}`, {
          replace: true
        });
      }
    }
  }, [activity?.id, activity?.type, params.type, params.id, navigate]);
  const validateSaveConditions = (0, import_react38.useCallback)(() => {
    if (questions.length === 0 && !hasFirstSaveBeenDone.current) {
      return false;
    }
    if (!appliedFilters || appliedFilters.knowledgeIds.length === 0) {
      return false;
    }
    if (loadingInitialQuestions || isSaving) {
      return false;
    }
    return true;
  }, [questions.length, appliedFilters, loadingInitialQuestions, isSaving]);
  const createDraftPayload = (0, import_react38.useCallback)(() => {
    const subjectId = appliedFilters.knowledgeIds[0];
    const title = generateTitle(activityType, subjectId, knowledgeAreas);
    const filters = convertFiltersToBackendFormat(appliedFilters);
    const questionIds = questions.map((q) => q.id);
    return {
      type: activityType,
      title,
      subjectId,
      filters,
      questionIds
    };
  }, [appliedFilters, activityType, knowledgeAreas, questions]);
  const updateExistingDraft = (0, import_react38.useCallback)(
    async (payload) => {
      const response = await apiClient.patch(
        `/activity-drafts/${draftId}`,
        payload
      );
      lastSavedQuestionsRef.current = questions;
      lastSavedFiltersRef.current = appliedFilters;
      const savedDraft = response?.data?.data?.draft;
      setLastSavedAt(
        savedDraft?.updatedAt ? new Date(savedDraft.updatedAt) : /* @__PURE__ */ new Date()
      );
      if (savedDraft) {
        setActivity((prevActivity) => {
          if (!prevActivity || prevActivity.id !== savedDraft.id) {
            return {
              id: savedDraft.id,
              type: savedDraft.type,
              title: savedDraft.title,
              subjectId: savedDraft.subjectId,
              filters: savedDraft.filters,
              questionIds: questions.map((q) => q.id),
              updatedAt: savedDraft.updatedAt
            };
          }
          return {
            ...prevActivity,
            type: savedDraft.type,
            title: savedDraft.title,
            subjectId: savedDraft.subjectId,
            questionIds: questions.map((q) => q.id),
            updatedAt: savedDraft.updatedAt
          };
        });
        setActivityType(savedDraft.type);
        if (savedDraft.id) {
          lastFetchedActivityIdRef.current = savedDraft.id;
        }
      }
      if (payload.type === "MODELO" /* MODELO */ && onSaveModel && response?.data) {
        onSaveModel(response.data);
      }
    },
    [draftId, apiClient, questions, appliedFilters, onSaveModel]
  );
  const extractDraftFromResponse = (0, import_react38.useCallback)(
    (response) => {
      if (!response?.data) {
        console.error("\u274C Resposta vazia da API ao criar rascunho:", response);
        throw new Error("Invalid response: empty response from API");
      }
      let savedDraft;
      if (response.data.data?.draft) {
        savedDraft = response.data.data.draft;
      } else if (response.data && "draft" in response.data && typeof response.data === "object") {
        savedDraft = response.data?.draft;
      }
      if (!savedDraft?.id) {
        console.error("\u274C Resposta inv\xE1lida da API ao criar rascunho:", {
          response,
          responseData: response?.data,
          responseDataData: response?.data?.data,
          responseKeys: response?.data ? Object.keys(response.data) : [],
          responseDataKeys: response?.data?.data ? Object.keys(response.data.data) : []
        });
        throw new Error(
          "Invalid response: draft data is missing. Expected structure: response.data.data.draft"
        );
      }
      return savedDraft;
    },
    []
  );
  const updateStateAfterSave = (0, import_react38.useCallback)(
    (savedDraft, fullResponse, wasNewDraft = false) => {
      setDraftId(savedDraft.id);
      setLastSavedAt(
        savedDraft.updatedAt ? new Date(savedDraft.updatedAt) : /* @__PURE__ */ new Date()
      );
      lastSavedQuestionsRef.current = questions;
      lastSavedFiltersRef.current = appliedFilters;
      const updatedActivity = {
        id: savedDraft.id,
        type: savedDraft.type,
        title: savedDraft.title,
        subjectId: savedDraft.subjectId,
        filters: savedDraft.filters,
        questionIds: questions.map((q) => q.id),
        updatedAt: savedDraft.updatedAt
      };
      setActivity(updatedActivity);
      setActivityType(savedDraft.type);
      lastFetchedActivityIdRef.current = savedDraft.id;
      if (wasNewDraft && savedDraft.id) {
        const urlType = getTypeFromUrl(savedDraft.type);
        navigate(`/criar-atividade/${urlType}/${savedDraft.id}`, {
          replace: true
        });
      }
      if (savedDraft.type === "MODELO" /* MODELO */ && onSaveModel && fullResponse) {
        onSaveModel(fullResponse);
      }
    },
    [questions, appliedFilters, onSaveModel, navigate]
  );
  const saveDraft = (0, import_react38.useCallback)(async () => {
    if (!validateSaveConditions()) {
      return;
    }
    setIsSaving(true);
    try {
      const payload = createDraftPayload();
      if (draftId) {
        await updateExistingDraft(payload);
        return;
      }
      const response = await apiClient.post(
        "/activity-drafts",
        payload
      );
      hasFirstSaveBeenDone.current = true;
      const savedDraft = extractDraftFromResponse(response);
      updateStateAfterSave(savedDraft, response?.data, true);
    } catch (error) {
      console.error("\u274C Erro ao salvar rascunho:", error);
      const errorMessage = error instanceof Error ? error.message : "Ocorreu um erro ao salvar o rascunho. Tente novamente.";
      addToast({
        title: "Erro ao salvar rascunho",
        description: errorMessage,
        variant: "solid",
        action: "warning",
        position: "top-right"
      });
    } finally {
      setIsSaving(false);
    }
  }, [
    validateSaveConditions,
    createDraftPayload,
    draftId,
    updateExistingDraft,
    apiClient,
    extractDraftFromResponse,
    updateStateAfterSave,
    addToast
  ]);
  const handleSaveModel = (0, import_react38.useCallback)(async () => {
    setActivityType("MODELO" /* MODELO */);
  }, []);
  (0, import_react38.useEffect)(() => {
    loadKnowledgeAreas();
  }, [loadKnowledgeAreas]);
  (0, import_react38.useEffect)(() => {
    if (activity?.selectedQuestions && activity.selectedQuestions.length > 0) {
      setLoadingInitialQuestions(true);
      try {
        const previewQuestions = activity.selectedQuestions.map(
          (q) => convertQuestionToPreview(q)
        );
        setQuestions(previewQuestions);
        hasFirstSaveBeenDone.current = true;
        lastSavedQuestionsRef.current = previewQuestions;
      } catch (error) {
        console.error("\u274C Erro ao converter quest\xF5es:", error);
        const errorMessage = error instanceof Error ? error.message : "Ocorreu um erro ao carregar as quest\xF5es. Tente novamente.";
        addToast({
          title: "Erro ao carregar quest\xF5es",
          description: errorMessage,
          variant: "solid",
          action: "warning",
          position: "top-right"
        });
      } finally {
        setLoadingInitialQuestions(false);
      }
    }
  }, [activity?.selectedQuestions, addToast]);
  (0, import_react38.useEffect)(() => {
    if (hasAppliedInitialFiltersRef.current) {
      return;
    }
    if (!initialFiltersData) {
      return;
    }
    setDraftFilters(initialFiltersData);
    applyFilters();
    lastSavedFiltersRef.current = initialFiltersData;
    hasAppliedInitialFiltersRef.current = true;
  }, [initialFiltersData, setDraftFilters, applyFilters]);
  const saveDraftRef = (0, import_react38.useRef)(saveDraft);
  (0, import_react38.useEffect)(() => {
    saveDraftRef.current = saveDraft;
  }, [saveDraft]);
  (0, import_react38.useEffect)(() => {
    if (saveTimeoutRef.current) {
      clearTimeout(saveTimeoutRef.current);
    }
    if (loadingInitialQuestions) {
      return;
    }
    if (questions.length === 0 && !hasFirstSaveBeenDone.current) {
      return;
    }
    if (!appliedFilters || appliedFilters.knowledgeIds.length === 0) {
      return;
    }
    const questionIds = questions.map((q) => q.id).join(",");
    const lastSavedQuestionIds = lastSavedQuestionsRef.current.map((q) => q.id).join(",");
    const questionsChanged = questionIds !== lastSavedQuestionIds;
    const filtersChanged = !areFiltersEqual(
      lastSavedFiltersRef.current,
      appliedFilters
    );
    if (!questionsChanged && !filtersChanged && hasFirstSaveBeenDone.current) {
      return;
    }
    saveTimeoutRef.current = setTimeout(() => {
      saveDraftRef.current();
    }, 500);
    return () => {
      if (saveTimeoutRef.current) {
        clearTimeout(saveTimeoutRef.current);
      }
    };
  }, [questions, appliedFilters, activityType, loadingInitialQuestions]);
  (0, import_react38.useEffect)(() => {
    if (activityType === "MODELO" /* MODELO */ && hasFirstSaveBeenDone.current) {
      if (saveTimeoutRef.current) {
        clearTimeout(saveTimeoutRef.current);
      }
      saveDraftRef.current();
    }
  }, [activityType]);
  const handleAddQuestion = (0, import_react38.useCallback)((question) => {
    setQuestions((prev) => {
      if (prev.some((q) => q.id === question.id)) {
        return prev;
      }
      try {
        const previewQuestion = convertQuestionToPreview(question);
        return [...prev, previewQuestion];
      } catch (error) {
        console.error("Erro ao converter quest\xE3o para preview:", {
          questionId: question.id,
          questionType: question.questionType,
          error: error instanceof Error ? error.message : String(error),
          stack: error instanceof Error ? error.stack : void 0
        });
        return prev;
      }
    });
  }, []);
  const handleRemoveAll = (0, import_react38.useCallback)(() => {
    setQuestions([]);
  }, []);
  const handleRemoveQuestion = (0, import_react38.useCallback)((questionId) => {
    setQuestions((prev) => prev.filter((q) => q.id !== questionId));
  }, []);
  const handleReorder = (0, import_react38.useCallback)(
    (orderedQuestions) => {
      setQuestions(orderedQuestions);
      if (hasFirstSaveBeenDone.current && appliedFilters && appliedFilters.knowledgeIds.length > 0 && !loadingInitialQuestions && !isSaving) {
        if (saveTimeoutRef.current) {
          clearTimeout(saveTimeoutRef.current);
        }
        saveDraftRef.current();
      }
    },
    [appliedFilters, loadingInitialQuestions, isSaving]
  );
  const handleLoadCategoriesData = (0, import_react38.useCallback)(async () => {
    if (categories.length > 0) {
      return;
    }
    try {
      const transformedCategories = await loadCategoriesData(
        apiClient,
        categories
      );
      setCategories(transformedCategories);
    } catch (error) {
      console.error("Erro ao carregar categorias:", error);
      throw error;
    }
  }, [apiClient, categories]);
  const handleOpenSendModal = (0, import_react38.useCallback)(async () => {
    try {
      if (categories.length === 0) {
        await handleLoadCategoriesData();
      }
      setIsSendModalOpen(true);
    } catch (error) {
      console.error("Erro ao abrir modal de envio:", error);
      const errorMessage = error instanceof Error ? error.message : "Erro ao carregar dados. Por favor, tente novamente.";
      addToast({
        title: "Erro ao carregar dados",
        description: errorMessage,
        variant: "solid",
        action: "warning",
        position: "top-right"
      });
    }
  }, [questions.length, categories.length, handleLoadCategoriesData, addToast]);
  const handleSendActivity = (0, import_react38.useCallback)(
    async (formData) => {
      setIsSendingActivity(true);
      try {
        const subjectId = activity?.subjectId || appliedFilters?.knowledgeIds[0];
        if (!subjectId) {
          throw new Error("Subject ID n\xE3o encontrado");
        }
        const startDateTime = (/* @__PURE__ */ new Date(
          `${formData.startDate}T${formData.startTime}`
        )).toISOString();
        const finalDateTime = (/* @__PURE__ */ new Date(
          `${formData.finalDate}T${formData.finalTime}`
        )).toISOString();
        const activityPayload = {
          createdBySys: false,
          title: formData.title,
          subjectId,
          questionIds: questions.map((q) => q.id),
          subtype: formData.subtype,
          difficulty: "",
          notification: formData.notification || "",
          status: "A_VENCER" /* A_VENCER */,
          startDate: startDateTime,
          finalDate: finalDateTime,
          canRetry: formData.canRetry
        };
        const createActivityResponse = await apiClient.post(
          "/activities",
          activityPayload
        );
        const activityId = createActivityResponse?.data?.data?.id;
        if (!activityId) {
          throw new Error("ID da atividade n\xE3o retornado pela API");
        }
        if (onCreateActivity) {
          onCreateActivity(activityId, activityPayload);
        }
        const sendToStudentsPayload = {
          activityId,
          students: formData.students
        };
        const sendToStudentsResponse = await apiClient.post("/activities/send-to-students", sendToStudentsPayload);
        if (!createActivityResponse?.data) {
          throw new Error("Resposta inv\xE1lida ao criar atividade");
        }
        if (!sendToStudentsResponse?.data) {
          throw new Error(
            "Resposta inv\xE1lida ao enviar atividade para estudantes"
          );
        }
        setIsSendModalOpen(false);
        addToast({
          title: "Atividade enviada com sucesso!",
          description: "A atividade foi criada e enviada para os estudantes selecionados.",
          variant: "solid",
          action: "success",
          position: "top-right"
        });
      } catch (error) {
        console.error("Erro ao enviar atividade:", error);
        const errorMessage = error instanceof Error ? error.message : "Ocorreu um erro ao enviar a atividade. Tente novamente.";
        addToast({
          title: "Erro ao enviar atividade",
          description: errorMessage,
          variant: "solid",
          action: "warning",
          position: "top-right"
        });
        throw error;
      } finally {
        setIsSendingActivity(false);
      }
    },
    [activity, appliedFilters, questions, apiClient, addToast]
  );
  const addedQuestionIds = (0, import_react38.useMemo)(
    () => questions.map((q) => q.id),
    [questions]
  );
  if (loading) {
    return /* @__PURE__ */ (0, import_jsx_runtime61.jsx)(ActivityCreateSkeleton, {});
  }
  return /* @__PURE__ */ (0, import_jsx_runtime61.jsxs)(
    "div",
    {
      "data-testid": "create-activity-page",
      className: "flex flex-col w-full h-screen overflow-hidden p-5 bg-background",
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime61.jsx)(
          ActivityCreateHeader,
          {
            activity: activity || void 0,
            activityType,
            lastSavedAt,
            isSaving,
            questionsCount: questions.length,
            onSaveModel: handleSaveModel,
            onSendActivity: handleOpenSendModal,
            onBack
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime61.jsxs)("div", { className: "flex flex-row w-full flex-1 overflow-hidden gap-5 min-h-0", children: [
          /* @__PURE__ */ (0, import_jsx_runtime61.jsxs)("div", { className: "flex flex-col gap-3 overflow-hidden h-full min-h-0 max-h-full relative w-[400px] flex-shrink-0", children: [
            /* @__PURE__ */ (0, import_jsx_runtime61.jsx)("div", { className: "flex flex-col overflow-y-auto overflow-x-hidden flex-1 min-h-0 max-h-full", children: /* @__PURE__ */ (0, import_jsx_runtime61.jsx)(
              ActivityFilters,
              {
                apiClient,
                institutionId,
                variant: "default",
                onFiltersChange: handleFiltersChange,
                initialFilters: initialFiltersData || void 0
              }
            ) }),
            /* @__PURE__ */ (0, import_jsx_runtime61.jsx)("div", { className: "flex-shrink-0", children: /* @__PURE__ */ (0, import_jsx_runtime61.jsx)(
              Button_default,
              {
                size: "medium",
                iconLeft: /* @__PURE__ */ (0, import_jsx_runtime61.jsx)(import_phosphor_react28.Funnel, {}),
                onClick: handleApplyFilters,
                disabled: !draftFilters,
                className: "w-full",
                children: "Filtrar"
              }
            ) })
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime61.jsx)("div", { className: "flex-1 min-w-0 overflow-hidden h-full", children: /* @__PURE__ */ (0, import_jsx_runtime61.jsx)(
            ActivityListQuestions,
            {
              apiClient,
              onAddQuestion: handleAddQuestion,
              addedQuestionIds
            }
          ) }),
          /* @__PURE__ */ (0, import_jsx_runtime61.jsx)("div", { className: "w-[470px] flex-shrink-0 overflow-hidden h-full min-h-0", children: loadingInitialQuestions ? /* @__PURE__ */ (0, import_jsx_runtime61.jsxs)("div", { className: "flex flex-col gap-4 p-4", children: [
            /* @__PURE__ */ (0, import_jsx_runtime61.jsxs)("div", { className: "flex flex-col gap-2", children: [
              /* @__PURE__ */ (0, import_jsx_runtime61.jsx)(SkeletonText, { lines: 1, width: 200 }),
              /* @__PURE__ */ (0, import_jsx_runtime61.jsx)(SkeletonText, { lines: 1, width: 150 })
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime61.jsx)("div", { className: "flex flex-col gap-2", children: [1, 2, 3].map((i) => /* @__PURE__ */ (0, import_jsx_runtime61.jsx)("div", { className: "p-4 border rounded", children: /* @__PURE__ */ (0, import_jsx_runtime61.jsx)(SkeletonText, { lines: 2 }) }, i)) })
          ] }) : /* @__PURE__ */ (0, import_jsx_runtime61.jsx)(
            ActivityPreview,
            {
              questions,
              onRemoveAll: handleRemoveAll,
              onRemoveQuestion: handleRemoveQuestion,
              onReorder: handleReorder,
              isDark,
              className: "h-full overflow-y-auto"
            }
          ) })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime61.jsx)(
          SendActivityModal_default,
          {
            isOpen: isSendModalOpen,
            onClose: () => setIsSendModalOpen(false),
            onSubmit: handleSendActivity,
            categories,
            isLoading: isSendingActivity,
            onError: (error) => {
              console.error("Erro ao enviar atividade:", error);
              const errorMessage = error instanceof Error ? error.message : "Erro ao enviar atividade. Por favor, tente novamente.";
              addToast({
                title: "Erro ao enviar atividade",
                description: errorMessage,
                variant: "solid",
                action: "warning",
                position: "top-right"
              });
            }
          }
        )
      ]
    }
  );
};

// src/types/questions.ts
var DIFFICULTY_LEVEL_ENUM = /* @__PURE__ */ ((DIFFICULTY_LEVEL_ENUM2) => {
  DIFFICULTY_LEVEL_ENUM2["FACIL"] = "FACIL";
  DIFFICULTY_LEVEL_ENUM2["MEDIO"] = "MEDIO";
  DIFFICULTY_LEVEL_ENUM2["DIFICIL"] = "DIFICIL";
  return DIFFICULTY_LEVEL_ENUM2;
})(DIFFICULTY_LEVEL_ENUM || {});
var QUESTION_STATUS_ENUM = /* @__PURE__ */ ((QUESTION_STATUS_ENUM2) => {
  QUESTION_STATUS_ENUM2["APROVADO"] = "APROVADO";
  QUESTION_STATUS_ENUM2["REVISAR"] = "REVISAR";
  QUESTION_STATUS_ENUM2["REPROVADO"] = "REPROVADO";
  QUESTION_STATUS_ENUM2["DESATIVADO"] = "DESATIVADO";
  QUESTION_STATUS_ENUM2["CATEGORIZACAO"] = "CATEGORIZACAO";
  QUESTION_STATUS_ENUM2["DADOS_AUSENTES"] = "DADOS AUSENTES";
  return QUESTION_STATUS_ENUM2;
})(QUESTION_STATUS_ENUM || {});

// src/components/Filter/FilterModal.tsx
var import_jsx_runtime62 = require("react/jsx-runtime");
var FilterModal = ({
  isOpen,
  onClose,
  filterConfigs,
  onFiltersChange,
  onApply,
  onClear,
  title = "Filtros",
  size = "md",
  applyLabel = "Aplicar",
  clearLabel = "Limpar filtros"
}) => {
  const handleCategoryChange = (configIndex, updatedCategories) => {
    const newConfigs = [...filterConfigs];
    newConfigs[configIndex] = {
      ...newConfigs[configIndex],
      categories: updatedCategories
    };
    onFiltersChange(newConfigs);
  };
  const handleApply = () => {
    onApply();
    onClose();
  };
  const handleClear = () => {
    onClear();
  };
  return /* @__PURE__ */ (0, import_jsx_runtime62.jsx)(
    Modal_default,
    {
      isOpen,
      onClose,
      title,
      size,
      footer: /* @__PURE__ */ (0, import_jsx_runtime62.jsxs)("div", { className: "flex gap-3 justify-end w-full", children: [
        /* @__PURE__ */ (0, import_jsx_runtime62.jsx)(Button_default, { variant: "outline", onClick: handleClear, children: clearLabel }),
        /* @__PURE__ */ (0, import_jsx_runtime62.jsx)(Button_default, { onClick: handleApply, children: applyLabel })
      ] }),
      children: /* @__PURE__ */ (0, import_jsx_runtime62.jsx)("div", { className: "flex flex-col gap-6", children: filterConfigs.map((config, index) => /* @__PURE__ */ (0, import_jsx_runtime62.jsxs)("div", { className: "flex flex-col gap-4", children: [
        /* @__PURE__ */ (0, import_jsx_runtime62.jsxs)("div", { className: "flex items-center gap-2 text-text-400 text-sm font-medium uppercase", children: [
          config.key === "academic" && /* @__PURE__ */ (0, import_jsx_runtime62.jsxs)(
            "svg",
            {
              width: "16",
              height: "16",
              viewBox: "0 0 16 16",
              fill: "none",
              xmlns: "http://www.w3.org/2000/svg",
              className: "text-text-400",
              children: [
                /* @__PURE__ */ (0, import_jsx_runtime62.jsx)(
                  "path",
                  {
                    d: "M8 2L2 5.33333L8 8.66667L14 5.33333L8 2Z",
                    stroke: "currentColor",
                    strokeWidth: "1.5",
                    strokeLinecap: "round",
                    strokeLinejoin: "round"
                  }
                ),
                /* @__PURE__ */ (0, import_jsx_runtime62.jsx)(
                  "path",
                  {
                    d: "M2 10.6667L8 14L14 10.6667",
                    stroke: "currentColor",
                    strokeWidth: "1.5",
                    strokeLinecap: "round",
                    strokeLinejoin: "round"
                  }
                ),
                /* @__PURE__ */ (0, import_jsx_runtime62.jsx)(
                  "path",
                  {
                    d: "M2 8L8 11.3333L14 8",
                    stroke: "currentColor",
                    strokeWidth: "1.5",
                    strokeLinecap: "round",
                    strokeLinejoin: "round"
                  }
                )
              ]
            }
          ),
          config.key === "content" && /* @__PURE__ */ (0, import_jsx_runtime62.jsxs)(
            "svg",
            {
              width: "16",
              height: "16",
              viewBox: "0 0 16 16",
              fill: "none",
              xmlns: "http://www.w3.org/2000/svg",
              className: "text-text-400",
              children: [
                /* @__PURE__ */ (0, import_jsx_runtime62.jsx)(
                  "path",
                  {
                    d: "M3.33333 2H12.6667C13.403 2 14 2.59695 14 3.33333V12.6667C14 13.403 13.403 14 12.6667 14H3.33333C2.59695 14 2 13.403 2 12.6667V3.33333C2 2.59695 2.59695 2 3.33333 2Z",
                    stroke: "currentColor",
                    strokeWidth: "1.5",
                    strokeLinecap: "round",
                    strokeLinejoin: "round"
                  }
                ),
                /* @__PURE__ */ (0, import_jsx_runtime62.jsx)(
                  "path",
                  {
                    d: "M2 6H14",
                    stroke: "currentColor",
                    strokeWidth: "1.5",
                    strokeLinecap: "round",
                    strokeLinejoin: "round"
                  }
                ),
                /* @__PURE__ */ (0, import_jsx_runtime62.jsx)(
                  "path",
                  {
                    d: "M6 2V14",
                    stroke: "currentColor",
                    strokeWidth: "1.5",
                    strokeLinecap: "round",
                    strokeLinejoin: "round"
                  }
                )
              ]
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime62.jsx)("span", { children: config.label })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime62.jsx)(
          CheckboxGroup,
          {
            categories: config.categories,
            onCategoriesChange: (updatedCategories) => handleCategoryChange(index, updatedCategories)
          }
        )
      ] }, config.key)) })
    }
  );
};

// src/components/Filter/useTableFilter.ts
var import_react39 = require("react");
var useTableFilter = (initialConfigs, options = {}) => {
  const { syncWithUrl = false } = options;
  const getInitialState = (0, import_react39.useCallback)(() => {
    if (!syncWithUrl || globalThis.window === void 0) {
      return initialConfigs;
    }
    const params = new URLSearchParams(globalThis.window.location.search);
    const configsWithUrlState = initialConfigs.map((config) => ({
      ...config,
      categories: config.categories.map((category) => {
        const urlValue = params.get(`filter_${category.key}`);
        const selectedIds = urlValue ? urlValue.split(",").filter(Boolean) : [];
        return {
          ...category,
          selectedIds
        };
      })
    }));
    return configsWithUrlState;
  }, [initialConfigs, syncWithUrl]);
  const [filterConfigs, setFilterConfigs] = (0, import_react39.useState)(getInitialState);
  const activeFilters = (0, import_react39.useMemo)(() => {
    const filters = {};
    for (const config of filterConfigs) {
      for (const category of config.categories) {
        if (category.selectedIds && category.selectedIds.length > 0) {
          filters[category.key] = category.selectedIds;
        }
      }
    }
    return filters;
  }, [filterConfigs]);
  const hasActiveFilters = Object.keys(activeFilters).length > 0;
  const updateFilters = (0, import_react39.useCallback)((configs) => {
    setFilterConfigs(configs);
  }, []);
  const applyFilters = (0, import_react39.useCallback)(() => {
    if (!syncWithUrl || globalThis.window === void 0) {
      return;
    }
    const url = new URL(globalThis.window.location.href);
    const params = url.searchParams;
    for (const config of filterConfigs) {
      for (const category of config.categories) {
        const paramKey = `filter_${category.key}`;
        if (category.selectedIds && category.selectedIds.length > 0) {
          params.set(paramKey, category.selectedIds.join(","));
        } else {
          params.delete(paramKey);
        }
      }
    }
    globalThis.window.history.replaceState({}, "", url.toString());
  }, [filterConfigs, syncWithUrl]);
  const clearFilters = (0, import_react39.useCallback)(() => {
    const clearedConfigs = filterConfigs.map((config) => ({
      ...config,
      categories: config.categories.map((category) => ({
        ...category,
        selectedIds: []
      }))
    }));
    setFilterConfigs(clearedConfigs);
    if (syncWithUrl && globalThis.window !== void 0) {
      const url = new URL(globalThis.window.location.href);
      const params = url.searchParams;
      for (const config of filterConfigs) {
        for (const category of config.categories) {
          params.delete(`filter_${category.key}`);
        }
      }
      globalThis.window.history.replaceState({}, "", url.toString());
    }
  }, [filterConfigs, syncWithUrl]);
  (0, import_react39.useEffect)(() => {
    if (!syncWithUrl || globalThis.window === void 0) {
      return;
    }
    const handlePopState = () => {
      setFilterConfigs(getInitialState());
    };
    globalThis.window.addEventListener("popstate", handlePopState);
    return () => globalThis.window.removeEventListener("popstate", handlePopState);
  }, [syncWithUrl, getInitialState]);
  return {
    filterConfigs,
    activeFilters,
    hasActiveFilters,
    updateFilters,
    applyFilters,
    clearFilters
  };
};

// src/components/ActivityFilters/ActivityFilters.tsx
var import_react40 = require("react");
var import_jsx_runtime63 = require("react/jsx-runtime");
var questionTypesFallback = [
  "ALTERNATIVA" /* ALTERNATIVA */,
  "VERDADEIRO_FALSO" /* VERDADEIRO_FALSO */,
  "DISSERTATIVA" /* DISSERTATIVA */,
  "IMAGEM" /* IMAGEM */,
  "MULTIPLA_ESCOLHA" /* MULTIPLA_ESCOLHA */,
  "LIGAR_PONTOS" /* LIGAR_PONTOS */,
  "PREENCHER" /* PREENCHER */
];
var isValidBankYearItem = (item, bankIds) => {
  return !!item && typeof item.id === "string" && typeof item.bankId === "string" && bankIds.includes(item.bankId);
};
var deriveYearIdsFromBankIds = (yearItens, bankIds, explicitYearIds) => {
  if (explicitYearIds.length > 0) {
    return explicitYearIds;
  }
  return yearItens.filter((item) => isValidBankYearItem(item, bankIds)).map((item) => item.id);
};
var hasBankMatches = (bankIds, bankCategories) => {
  if (bankIds.length === 0) {
    return true;
  }
  return bankCategories.some(
    (category) => category.key === "banca" && (category.itens ?? []).some((item) => bankIds.includes(item.id))
  );
};
var hasYearMatches = (derivedYearIds, bankCategories) => {
  if (derivedYearIds.length === 0) {
    return true;
  }
  return bankCategories.some(
    (category) => category.key === "ano" && (category.itens ?? []).some((item) => derivedYearIds.includes(item.id))
  );
};
var updateBankCategory = (category, bankIds) => {
  const itens = category.itens ?? [];
  const selectedIds = itens.filter((item) => bankIds.includes(item.id)).map((item) => item.id);
  return { ...category, selectedIds };
};
var updateYearCategory = (category, derivedYearIds) => {
  const itens = category.itens ?? [];
  const selectedIds = itens.filter((item) => derivedYearIds.includes(item.id)).map((item) => item.id);
  return { ...category, selectedIds };
};
var updateBankCategoriesWithInitialFilters = (prevCategories, bankIds, derivedYearIds) => {
  return prevCategories.map((category) => {
    if (category.key === "banca") {
      return updateBankCategory(category, bankIds);
    }
    if (category.key === "ano") {
      return updateYearCategory(category, derivedYearIds);
    }
    return category;
  });
};
var getSelectedIdsForKnowledgeCategory = (category, filterIds) => {
  return (category.itens || []).filter((item) => filterIds.includes(item.id)).map((item) => item.id);
};
var updateTopicCategory = (category, topicIds, hasAppliedTopicsRef) => {
  const selectedIds = getSelectedIdsForKnowledgeCategory(category, topicIds);
  if (selectedIds.length > 0) {
    hasAppliedTopicsRef.current = true;
    return { category: { ...category, selectedIds }, changed: true };
  }
  return { category, changed: false };
};
var updateSubtopicCategory = (category, subtopicIds, hasAppliedSubtopicsRef) => {
  const selectedIds = getSelectedIdsForKnowledgeCategory(category, subtopicIds);
  if (selectedIds.length > 0) {
    hasAppliedSubtopicsRef.current = true;
    return { category: { ...category, selectedIds }, changed: true };
  }
  return { category, changed: false };
};
var updateContentCategory = (category, contentIds, hasAppliedContentsRef) => {
  const selectedIds = getSelectedIdsForKnowledgeCategory(category, contentIds);
  if (selectedIds.length > 0) {
    hasAppliedContentsRef.current = true;
    return { category: { ...category, selectedIds }, changed: true };
  }
  return { category, changed: false };
};
var QuestionTypeFilter = ({
  selectedTypes,
  onToggleType,
  allowedQuestionTypes
}) => {
  const availableQuestionTypes = allowedQuestionTypes || questionTypesFallback;
  return /* @__PURE__ */ (0, import_jsx_runtime63.jsxs)("div", { children: [
    /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(Text_default, { size: "sm", weight: "bold", className: "mb-3 block", children: "Tipo de quest\xE3o" }),
    /* @__PURE__ */ (0, import_jsx_runtime63.jsx)("div", { className: "grid grid-cols-2 gap-2", children: availableQuestionTypes.map((questionType) => /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(
      Chips_default,
      {
        selected: selectedTypes.includes(questionType),
        onClick: () => onToggleType(questionType),
        children: questionTypeLabels[questionType]
      },
      questionType
    )) })
  ] });
};
var BanksAndYearsFilter = ({
  banks,
  bankYears,
  bankCategories,
  onBankCategoriesChange,
  loading = false,
  error = null
}) => {
  if (loading) {
    return /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(Text_default, { size: "sm", className: "text-text-600", children: "Carregando bancas..." });
  }
  if (error) {
    return /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(Text_default, { size: "sm", className: "text-text-600", children: error });
  }
  if (banks.length === 0 && bankYears.length === 0) {
    return /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(Text_default, { size: "sm", className: "text-text-600", children: "Nenhuma banca encontrada" });
  }
  if (bankCategories.length > 0) {
    return /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(
      CheckboxGroup,
      {
        categories: bankCategories,
        onCategoriesChange: onBankCategoriesChange,
        compactSingleItem: true,
        showSingleItem: true
      }
    );
  }
  return null;
};
var SubjectsFilter = ({
  knowledgeAreas,
  selectedSubject,
  onSubjectChange,
  loading = false,
  error = null
}) => {
  const { isDark } = useTheme();
  if (loading) {
    return /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(Text_default, { size: "sm", className: "text-text-600", children: "Carregando mat\xE9rias..." });
  }
  if (error) {
    return /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(Text_default, { size: "sm", className: "text-text-600", children: error });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime63.jsx)("div", { className: "grid grid-cols-3 gap-3", children: knowledgeAreas.map((area) => /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(
    Radio_default,
    {
      value: area.id,
      checked: selectedSubject === area.id,
      onChange: () => onSubjectChange(area.id),
      label: /* @__PURE__ */ (0, import_jsx_runtime63.jsxs)("div", { className: "flex items-center gap-2 w-full min-w-0", children: [
        /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(
          "span",
          {
            className: "size-4 rounded-sm flex items-center justify-center shrink-0 text-text-950",
            style: {
              backgroundColor: getSubjectColorWithOpacity(
                area.color,
                isDark
              )
            },
            children: /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(
              IconRender_default,
              {
                iconName: area.icon || "BookOpen",
                size: 14,
                color: "currentColor"
              }
            )
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime63.jsx)("span", { className: "truncate flex-1", children: area.name })
      ] })
    },
    area.id
  )) });
};
var KnowledgeStructureFilter = ({
  knowledgeStructure,
  knowledgeCategories,
  handleCategoriesChange
}) => {
  return /* @__PURE__ */ (0, import_jsx_runtime63.jsxs)("div", { className: "mt-4", children: [
    /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(Text_default, { size: "sm", weight: "bold", className: "mb-3 block", children: "Tema, Subtema e Assunto" }),
    knowledgeStructure.loading && /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(Text_default, { size: "sm", className: "text-text-600 mb-3", children: "Carregando estrutura de conhecimento..." }),
    knowledgeStructure.error && /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(Text_default, { size: "sm", className: "mb-3 text-error-500", children: knowledgeStructure.error }),
    knowledgeCategories.length > 0 && handleCategoriesChange && /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(
      CheckboxGroup,
      {
        categories: knowledgeCategories,
        onCategoriesChange: handleCategoriesChange,
        compactSingleItem: false,
        showSingleItem: true
      }
    ),
    !knowledgeStructure.loading && knowledgeCategories.length === 0 && knowledgeStructure.topics.length === 0 && /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(Text_default, { size: "sm", className: "text-text-600", children: "Nenhum tema dispon\xEDvel para as mat\xE9rias selecionadas" })
  ] });
};
var FilterActions = ({
  onClearFilters,
  onApplyFilters
}) => {
  if (!onClearFilters && !onApplyFilters) {
    return null;
  }
  return /* @__PURE__ */ (0, import_jsx_runtime63.jsxs)("div", { className: "grid grid-cols-2 gap-2 justify-end mt-4 px-4 pt-4 border-t border-border-200", children: [
    onClearFilters && /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(Button_default, { variant: "link", onClick: onClearFilters, size: "small", children: "Limpar filtros" }),
    onApplyFilters && /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(Button_default, { variant: "outline", onClick: onApplyFilters, size: "small", children: "Filtrar" })
  ] });
};
var ActivityFilters = ({
  apiClient,
  onFiltersChange,
  variant = "default",
  institutionId = null,
  initialFilters = null,
  allowedQuestionTypes,
  onClearFilters,
  onApplyFilters
}) => {
  const useActivityFiltersData = createUseActivityFiltersData(apiClient);
  const [selectedQuestionTypes, setSelectedQuestionTypes] = (0, import_react40.useState)([]);
  const [selectedSubject, setSelectedSubject] = (0, import_react40.useState)(null);
  const {
    banks,
    bankYears,
    loadingBanks,
    banksError,
    knowledgeAreas,
    loadingSubjects,
    subjectsError,
    knowledgeStructure,
    knowledgeCategories,
    handleCategoriesChange,
    loadBanks,
    loadKnowledgeAreas,
    loadQuestionTypes,
    loadTopics,
    loadSubtopics,
    loadContents,
    questionTypes,
    loadingQuestionTypes,
    questionTypesError
  } = useActivityFiltersData({
    selectedSubjects: selectedSubject ? [selectedSubject] : [],
    institutionId
  });
  const prevAllowedQuestionTypesRef = (0, import_react40.useRef)(null);
  const hasAppliedBasicInitialFiltersRef = (0, import_react40.useRef)(false);
  const hasAppliedBankInitialFiltersRef = (0, import_react40.useRef)(false);
  const hasAppliedKnowledgeInitialFiltersRef = (0, import_react40.useRef)(false);
  const hasRequestedTopicsRef = (0, import_react40.useRef)(false);
  const hasRequestedSubtopicsRef = (0, import_react40.useRef)(false);
  const hasRequestedContentsRef = (0, import_react40.useRef)(false);
  const hasAppliedTopicsRef = (0, import_react40.useRef)(false);
  const hasAppliedSubtopicsRef = (0, import_react40.useRef)(false);
  const hasAppliedContentsRef = (0, import_react40.useRef)(false);
  const bankCategoriesRef = (0, import_react40.useRef)([]);
  const knowledgeCategoriesRef = (0, import_react40.useRef)([]);
  (0, import_react40.useEffect)(() => {
    if (!allowedQuestionTypes || allowedQuestionTypes.length === 0) {
      prevAllowedQuestionTypesRef.current = null;
      return;
    }
    const currentKey = allowedQuestionTypes.slice().sort((a, b) => {
      return a === b ? 0 : allowedQuestionTypes.indexOf(a) - allowedQuestionTypes.indexOf(b);
    }).join(",");
    const prevKey = prevAllowedQuestionTypesRef.current;
    if (currentKey === prevKey) {
      return;
    }
    prevAllowedQuestionTypesRef.current = currentKey;
    setSelectedQuestionTypes((prev) => {
      const filtered = prev.filter(
        (type) => allowedQuestionTypes.includes(type)
      );
      if (filtered.length !== prev.length) {
        return filtered;
      }
      const prevSet = new Set(prev);
      const filteredSet = new Set(filtered);
      if (prevSet.size !== filteredSet.size) {
        return filtered;
      }
      for (const item of prevSet) {
        if (!filteredSet.has(item)) {
          return filtered;
        }
      }
      return prev;
    });
  }, [allowedQuestionTypes]);
  const [bankCategories, setBankCategories] = (0, import_react40.useState)([]);
  (0, import_react40.useEffect)(() => {
    bankCategoriesRef.current = bankCategories;
  }, [bankCategories]);
  const selectedSubjects = (0, import_react40.useMemo)(
    () => selectedSubject ? [selectedSubject] : [],
    [selectedSubject]
  );
  const toggleQuestionType = (questionType) => {
    setSelectedQuestionTypes((prev) => toggleArrayItem(prev, questionType));
  };
  const handleSubjectChange = (subjectId) => {
    setSelectedSubject(toggleSingleValue(selectedSubject, subjectId));
  };
  const handleBankCategoriesChange = (updatedCategories) => {
    setBankCategories(updatedCategories);
  };
  (0, import_react40.useEffect)(() => {
    setBankCategories((prevCategories) => {
      const bankCategory = {
        key: "banca",
        label: "Banca",
        itens: banks.map((bank) => ({
          id: bank.id,
          name: bank.name || bank.examInstitution
        })),
        selectedIds: prevCategories.find((c) => c.key === "banca")?.selectedIds || []
      };
      const yearCategory = {
        key: "ano",
        label: "Ano",
        dependsOn: ["banca"],
        itens: bankYears.map((year) => ({
          id: year.id,
          name: year.name,
          bankId: year.bankId
        })),
        filteredBy: [{ key: "banca", internalField: "bankId" }],
        selectedIds: prevCategories.find((c) => c.key === "ano")?.selectedIds || []
      };
      return [bankCategory, yearCategory];
    });
  }, [banks, bankYears]);
  (0, import_react40.useEffect)(() => {
    knowledgeCategoriesRef.current = knowledgeCategories;
  }, [knowledgeCategories]);
  (0, import_react40.useEffect)(() => {
    hasAppliedBasicInitialFiltersRef.current = false;
    hasAppliedBankInitialFiltersRef.current = false;
    hasAppliedKnowledgeInitialFiltersRef.current = false;
    hasRequestedTopicsRef.current = false;
    hasRequestedSubtopicsRef.current = false;
    hasRequestedContentsRef.current = false;
    hasAppliedTopicsRef.current = false;
    hasAppliedSubtopicsRef.current = false;
    hasAppliedContentsRef.current = false;
  }, [initialFilters]);
  (0, import_react40.useEffect)(() => {
    if (!initialFilters || hasAppliedBasicInitialFiltersRef.current) {
      return;
    }
    if (initialFilters.types && initialFilters.types.length > 0) {
      setSelectedQuestionTypes(initialFilters.types);
    }
    if (initialFilters.knowledgeIds && initialFilters.knowledgeIds.length > 0) {
      setSelectedSubject(initialFilters.knowledgeIds[0]);
    }
    hasAppliedBasicInitialFiltersRef.current = true;
  }, [initialFilters]);
  (0, import_react40.useEffect)(() => {
    if (!initialFilters || hasAppliedBankInitialFiltersRef.current || bankCategoriesRef.current.length === 0) {
      return;
    }
    const bankIds = initialFilters.bankIds || [];
    const yearIds = initialFilters.yearIds || [];
    if (bankIds.length === 0 && yearIds.length === 0) {
      hasAppliedBankInitialFiltersRef.current = true;
      return;
    }
    const currentBankCategories = bankCategoriesRef.current;
    const yearCategory = currentBankCategories.find(
      (category) => category.key === "ano"
    );
    const yearItens = Array.isArray(yearCategory?.itens) ? yearCategory.itens : [];
    const derivedYearIds = deriveYearIdsFromBankIds(
      yearItens,
      bankIds,
      yearIds
    );
    if (!hasBankMatches(bankIds, currentBankCategories) || !hasYearMatches(derivedYearIds, currentBankCategories)) {
      return;
    }
    setBankCategories(
      (prevCategories) => updateBankCategoriesWithInitialFilters(
        prevCategories,
        bankIds,
        derivedYearIds
      )
    );
    hasAppliedBankInitialFiltersRef.current = true;
  }, [initialFilters, bankCategories]);
  (0, import_react40.useEffect)(() => {
    if (!initialFilters) {
      return;
    }
    const subjectIds = initialFilters.knowledgeIds || [];
    const topicIds = initialFilters.topicIds || [];
    const subtopicIds = initialFilters.subtopicIds || [];
    if (subjectIds.length > 0 && !hasRequestedTopicsRef.current) {
      if (loadTopics) {
        loadTopics(subjectIds);
      }
      hasRequestedTopicsRef.current = true;
    }
    if (topicIds.length > 0 && !hasRequestedSubtopicsRef.current) {
      if (loadSubtopics) {
        loadSubtopics(topicIds);
      }
      hasRequestedSubtopicsRef.current = true;
    }
    if (subtopicIds.length > 0 && !hasRequestedContentsRef.current) {
      if (loadContents) {
        loadContents(subtopicIds);
      }
      hasRequestedContentsRef.current = true;
    }
  }, [initialFilters, loadTopics, loadSubtopics, loadContents]);
  (0, import_react40.useEffect)(() => {
    if (!initialFilters || hasAppliedKnowledgeInitialFiltersRef.current || knowledgeCategoriesRef.current.length === 0 || !handleCategoriesChange) {
      return;
    }
    const topicIds = initialFilters.topicIds || [];
    const subtopicIds = initialFilters.subtopicIds || [];
    const contentIds = initialFilters.contentIds || [];
    const hasKnowledgeSelections = topicIds.length > 0 || subtopicIds.length > 0 || contentIds.length > 0;
    if (!hasKnowledgeSelections) {
      hasAppliedKnowledgeInitialFiltersRef.current = true;
      return;
    }
    const currentKnowledgeCategories = knowledgeCategoriesRef.current;
    let changed = false;
    const updatedCategories = currentKnowledgeCategories.map((category) => {
      if (category.key === "tema" && topicIds.length > 0 && !hasAppliedTopicsRef.current) {
        const result = updateTopicCategory(
          category,
          topicIds,
          hasAppliedTopicsRef
        );
        if (result.changed) {
          changed = true;
        }
        return result.category;
      }
      if (category.key === "subtema" && subtopicIds.length > 0 && !hasAppliedSubtopicsRef.current) {
        const result = updateSubtopicCategory(
          category,
          subtopicIds,
          hasAppliedSubtopicsRef
        );
        if (result.changed) {
          changed = true;
        }
        return result.category;
      }
      if (category.key === "assunto" && contentIds.length > 0 && !hasAppliedContentsRef.current) {
        const result = updateContentCategory(
          category,
          contentIds,
          hasAppliedContentsRef
        );
        if (result.changed) {
          changed = true;
        }
        return result.category;
      }
      return category;
    });
    if (changed) {
      handleCategoriesChange(updatedCategories);
    }
    if ((topicIds.length === 0 || hasAppliedTopicsRef.current) && (subtopicIds.length === 0 || hasAppliedSubtopicsRef.current) && (contentIds.length === 0 || hasAppliedContentsRef.current)) {
      hasAppliedKnowledgeInitialFiltersRef.current = true;
    }
  }, [initialFilters, knowledgeCategories, handleCategoriesChange]);
  (0, import_react40.useEffect)(() => {
    if (loadBanks) {
      loadBanks();
    }
    if (loadKnowledgeAreas) {
      loadKnowledgeAreas();
    }
    if (loadQuestionTypes) {
      loadQuestionTypes();
    }
  }, [loadBanks, loadKnowledgeAreas, loadQuestionTypes, institutionId]);
  const availableQuestionTypes = (0, import_react40.useMemo)(() => {
    const source = questionTypes && questionTypes.length > 0 ? questionTypes : questionTypesFallback;
    if (!allowedQuestionTypes || allowedQuestionTypes.length === 0) {
      return source;
    }
    return source.filter((type) => allowedQuestionTypes.includes(type));
  }, [questionTypes, allowedQuestionTypes]);
  const getSelectedKnowledgeIds = (0, import_react40.useCallback)(() => {
    return getSelectedIdsFromCategories(knowledgeCategories, {
      topicIds: "tema",
      subtopicIds: "subtema",
      contentIds: "assunto"
    });
  }, [knowledgeCategories]);
  const getSelectedBankIds = (0, import_react40.useCallback)(() => {
    return getSelectedIdsFromCategories(bankCategories, {
      bankIds: "banca",
      yearIds: "ano"
    });
  }, [bankCategories]);
  const onFiltersChangeRef = (0, import_react40.useRef)(onFiltersChange);
  (0, import_react40.useEffect)(() => {
    onFiltersChangeRef.current = onFiltersChange;
  }, [onFiltersChange]);
  const prevFiltersRef = (0, import_react40.useRef)(null);
  (0, import_react40.useEffect)(() => {
    const knowledgeIds = getSelectedKnowledgeIds();
    const bankIds = getSelectedBankIds();
    const filters = {
      types: selectedQuestionTypes,
      bankIds: bankIds.bankIds || [],
      yearIds: bankIds.yearIds || [],
      knowledgeIds: selectedSubjects,
      topicIds: knowledgeIds.topicIds,
      subtopicIds: knowledgeIds.subtopicIds,
      contentIds: knowledgeIds.contentIds
    };
    if (!areFiltersEqual(prevFiltersRef.current, filters)) {
      prevFiltersRef.current = filters;
      onFiltersChangeRef.current(filters);
    }
  }, [
    selectedQuestionTypes,
    selectedSubjects,
    knowledgeCategories,
    bankCategories,
    getSelectedKnowledgeIds,
    getSelectedBankIds
  ]);
  const containerClassName = variant === "popover" ? "w-full bg-background" : "w-[400px] flex-shrink-0 p-4 bg-background";
  const contentClassName = variant === "popover" ? "p-4" : "";
  return /* @__PURE__ */ (0, import_jsx_runtime63.jsxs)("div", { className: containerClassName, children: [
    variant === "default" && /* @__PURE__ */ (0, import_jsx_runtime63.jsx)("section", { className: "flex flex-row items-center gap-2 text-text-950 mb-4", children: /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(Text_default, { size: "lg", weight: "bold", children: "Filtro de quest\xF5es" }) }),
    /* @__PURE__ */ (0, import_jsx_runtime63.jsx)("div", { className: contentClassName, children: /* @__PURE__ */ (0, import_jsx_runtime63.jsxs)("section", { className: "flex flex-col gap-4", children: [
      /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(
        QuestionTypeFilter,
        {
          selectedTypes: selectedQuestionTypes,
          onToggleType: toggleQuestionType,
          allowedQuestionTypes: availableQuestionTypes
        }
      ),
      loadingQuestionTypes && /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(
        Text_default,
        {
          size: "sm",
          className: "text-text-600",
          "data-testid": "question-types-loading",
          children: "Carregando tipos de quest\xE3o..."
        }
      ),
      questionTypesError && /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(
        Text_default,
        {
          size: "sm",
          className: "text-error-500",
          "data-testid": "question-types-error",
          children: questionTypesError
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime63.jsxs)("div", { children: [
        /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(Text_default, { size: "sm", weight: "bold", className: "mb-3 block", children: "Banca de vestibular" }),
        /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(
          BanksAndYearsFilter,
          {
            banks,
            bankYears,
            bankCategories,
            onBankCategoriesChange: handleBankCategoriesChange,
            loading: loadingBanks,
            error: banksError
          }
        )
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime63.jsxs)("div", { children: [
        /* @__PURE__ */ (0, import_jsx_runtime63.jsx)("div", { className: "flex flex-row justify-between items-center mb-3", children: /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(Text_default, { size: "sm", weight: "bold", children: "Mat\xE9ria" }) }),
        /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(
          SubjectsFilter,
          {
            knowledgeAreas,
            selectedSubject,
            onSubjectChange: handleSubjectChange,
            loading: loadingSubjects,
            error: subjectsError
          }
        )
      ] }),
      selectedSubject && /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(
        KnowledgeStructureFilter,
        {
          knowledgeStructure,
          knowledgeCategories,
          handleCategoriesChange
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(
        FilterActions,
        {
          onClearFilters,
          onApplyFilters
        }
      )
    ] }) })
  ] });
};
var ActivityFiltersPopover = ({
  onFiltersChange,
  triggerLabel = "Filtro de quest\xF5es",
  ...activityFiltersProps
}) => {
  const [open, setOpen] = (0, import_react40.useState)(false);
  return /* @__PURE__ */ (0, import_jsx_runtime63.jsxs)(DropdownMenu_default, { open, onOpenChange: setOpen, children: [
    /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(DropdownMenuTrigger, { children: /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(Button_default, { variant: "outline", children: triggerLabel }) }),
    /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(
      DropdownMenuContent,
      {
        className: "w-[90vw] max-w-[400px] max-h-[calc(100vh-8rem)] overflow-y-auto p-0",
        align: "start",
        children: /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(
          ActivityFilters,
          {
            onFiltersChange,
            variant: "popover",
            ...activityFiltersProps
          }
        )
      }
    )
  ] });
};

// src/components/TableProvider/TableProvider.tsx
var import_react41 = require("react");
var import_phosphor_react29 = require("phosphor-react");
var import_jsx_runtime64 = require("react/jsx-runtime");
function TableProvider({
  data,
  headers,
  loading = false,
  variant = "default",
  enableSearch = false,
  enableFilters = false,
  enableTableSort = false,
  enablePagination = false,
  enableRowClick = false,
  initialFilters = [],
  paginationConfig = {},
  searchPlaceholder = "Buscar...",
  emptyState,
  loadingState,
  noSearchResultState,
  rowKey,
  onParamsChange,
  onRowClick,
  children
}) {
  const [searchQuery, setSearchQuery] = (0, import_react41.useState)("");
  const sortResultRaw = useTableSort(data, { syncWithUrl: true });
  const sortResult = enableTableSort ? sortResultRaw : {
    sortedData: data,
    sortColumn: null,
    sortDirection: null,
    handleSort: () => {
    }
  };
  const { sortedData, sortColumn, sortDirection, handleSort } = sortResult;
  const filterResultRaw = useTableFilter(initialFilters, { syncWithUrl: true });
  const disabledFilterResult = (0, import_react41.useMemo)(
    () => ({
      filterConfigs: [],
      activeFilters: {},
      hasActiveFilters: false,
      updateFilters: () => {
      },
      applyFilters: () => {
      },
      clearFilters: () => {
      }
    }),
    []
  );
  const filterResult = enableFilters ? filterResultRaw : disabledFilterResult;
  const {
    filterConfigs,
    activeFilters,
    hasActiveFilters,
    updateFilters,
    applyFilters,
    clearFilters
  } = filterResult;
  const {
    defaultItemsPerPage = 10,
    itemsPerPageOptions = [10, 20, 50, 100],
    itemLabel = "itens",
    totalItems,
    totalPages
  } = paginationConfig;
  const [currentPage, setCurrentPage] = (0, import_react41.useState)(1);
  const [itemsPerPage, setItemsPerPage] = (0, import_react41.useState)(defaultItemsPerPage);
  const [isFilterModalOpen, setIsFilterModalOpen] = (0, import_react41.useState)(false);
  const combinedParams = (0, import_react41.useMemo)(() => {
    const params = {
      page: currentPage,
      limit: itemsPerPage
    };
    if (enableSearch && searchQuery) {
      params.search = searchQuery;
    }
    if (enableFilters) {
      Object.assign(params, activeFilters);
    }
    if (enableTableSort && sortColumn && sortDirection) {
      params.sortBy = sortColumn;
      params.sortOrder = sortDirection;
    }
    return params;
  }, [
    currentPage,
    itemsPerPage,
    searchQuery,
    activeFilters,
    sortColumn,
    sortDirection,
    enableSearch,
    enableFilters,
    enableTableSort
  ]);
  (0, import_react41.useEffect)(() => {
    onParamsChange?.(combinedParams);
  }, [combinedParams]);
  const handleSearchChange = (0, import_react41.useCallback)((value) => {
    setSearchQuery(value);
    setCurrentPage(1);
  }, []);
  const handleFilterApply = (0, import_react41.useCallback)(() => {
    applyFilters();
    setIsFilterModalOpen(false);
    setCurrentPage(1);
  }, [applyFilters]);
  const handlePageChange = (0, import_react41.useCallback)((page) => {
    setCurrentPage(page);
  }, []);
  const handleItemsPerPageChange = (0, import_react41.useCallback)((items) => {
    setItemsPerPage(items);
    setCurrentPage(1);
  }, []);
  const handleRowClickInternal = (0, import_react41.useCallback)(
    (row, index) => {
      if (enableRowClick && onRowClick) {
        onRowClick(row, index);
      }
    },
    [enableRowClick, onRowClick]
  );
  const useInternalPagination = (0, import_react41.useMemo)(
    () => enablePagination && !onParamsChange && totalItems === void 0 && totalPages === void 0,
    [enablePagination, onParamsChange, totalItems, totalPages]
  );
  const calculatedTotalPages = totalPages ?? Math.ceil(
    (totalItems ?? (useInternalPagination ? sortedData.length : data.length)) / itemsPerPage
  );
  const calculatedTotalItems = totalItems ?? (useInternalPagination ? sortedData.length : data.length);
  const displayData = (0, import_react41.useMemo)(() => {
    if (!useInternalPagination) {
      return sortedData;
    }
    const start = (currentPage - 1) * itemsPerPage;
    return sortedData.slice(start, start + itemsPerPage);
  }, [useInternalPagination, sortedData, currentPage, itemsPerPage]);
  const isEmpty = data.length === 0;
  const showLoading = loading;
  const showNoSearchResult = !loading && data.length === 0 && searchQuery.trim() !== "";
  const showEmpty = !loading && data.length === 0 && searchQuery.trim() === "";
  const controls = (enableSearch || enableFilters) && /* @__PURE__ */ (0, import_jsx_runtime64.jsxs)("div", { className: "flex items-center gap-4", children: [
    enableFilters && /* @__PURE__ */ (0, import_jsx_runtime64.jsxs)(
      Button_default,
      {
        variant: "outline",
        size: "medium",
        onClick: () => setIsFilterModalOpen(true),
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime64.jsx)(import_phosphor_react29.Funnel, { size: 20 }),
          "Filtros",
          hasActiveFilters && /* @__PURE__ */ (0, import_jsx_runtime64.jsx)("span", { className: "ml-2 rounded-full bg-primary-500 px-2 py-0.5 text-xs text-white", children: Object.keys(activeFilters).length })
        ]
      }
    ),
    enableSearch && /* @__PURE__ */ (0, import_jsx_runtime64.jsx)("div", { className: "flex-1", children: /* @__PURE__ */ (0, import_jsx_runtime64.jsx)(
      Search_default,
      {
        value: searchQuery,
        onSearch: handleSearchChange,
        onClear: () => handleSearchChange(""),
        options: [],
        placeholder: searchPlaceholder
      }
    ) })
  ] });
  const table = /* @__PURE__ */ (0, import_jsx_runtime64.jsx)("div", { className: "w-full overflow-x-auto", children: /* @__PURE__ */ (0, import_jsx_runtime64.jsxs)(
    Table_default,
    {
      variant,
      showLoading,
      loadingState,
      showNoSearchResult,
      noSearchResultState,
      showEmpty,
      emptyState,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime64.jsx)("thead", { children: /* @__PURE__ */ (0, import_jsx_runtime64.jsx)(
          TableRow,
          {
            variant: variant === "borderless" ? "defaultBorderless" : "default",
            children: headers.map((header, index) => /* @__PURE__ */ (0, import_jsx_runtime64.jsx)(
              TableHead,
              {
                sortable: enableTableSort && header.sortable,
                sortDirection: enableTableSort && sortColumn === header.key ? sortDirection : null,
                onSort: () => enableTableSort && header.sortable && handleSort(header.key),
                className: header.className,
                style: header.width ? { width: header.width } : void 0,
                children: header.label
              },
              `header-${header.key}-${index}`
            ))
          }
        ) }),
        /* @__PURE__ */ (0, import_jsx_runtime64.jsx)(TableBody, { children: loading ? /* @__PURE__ */ (0, import_jsx_runtime64.jsx)(TableRow, { children: /* @__PURE__ */ (0, import_jsx_runtime64.jsx)(TableCell, { colSpan: headers.length, className: "text-center py-8", children: /* @__PURE__ */ (0, import_jsx_runtime64.jsx)("span", { className: "text-text-400 text-sm", children: "Carregando..." }) }) }) : displayData.map((row, rowIndex) => {
          const effectiveIndex = useInternalPagination ? (currentPage - 1) * itemsPerPage + rowIndex : rowIndex;
          const rowKeyValue = rowKey ? (() => {
            const keyValue = row[rowKey];
            if (keyValue === null || keyValue === void 0) {
              return `row-${effectiveIndex}`;
            }
            if (typeof keyValue === "object") {
              return JSON.stringify(keyValue);
            }
            return String(keyValue);
          })() : `row-${effectiveIndex}`;
          return /* @__PURE__ */ (0, import_jsx_runtime64.jsx)(
            TableRow,
            {
              variant: variant === "borderless" ? "defaultBorderless" : "default",
              clickable: enableRowClick,
              onClick: () => handleRowClickInternal(row, effectiveIndex),
              children: headers.map((header, cellIndex) => {
                const value = row[header.key];
                let defaultContent = "";
                if (value !== null && value !== void 0) {
                  if (typeof value === "string" || typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
                    defaultContent = String(value);
                  } else if (typeof value === "object") {
                    defaultContent = JSON.stringify(value);
                  } else if (typeof value === "function") {
                    defaultContent = "[Function]";
                  } else if (typeof value === "symbol") {
                    defaultContent = String(value);
                  }
                }
                const content = header.render ? header.render(value, row, effectiveIndex) : defaultContent;
                return /* @__PURE__ */ (0, import_jsx_runtime64.jsx)(
                  TableCell,
                  {
                    className: header.className,
                    style: {
                      textAlign: header.align
                    },
                    children: content
                  },
                  `cell-${effectiveIndex}-${cellIndex}`
                );
              })
            },
            rowKeyValue
          );
        }) })
      ]
    }
  ) });
  const pagination = enablePagination && !isEmpty && /* @__PURE__ */ (0, import_jsx_runtime64.jsx)("div", { className: "flex justify-end", children: /* @__PURE__ */ (0, import_jsx_runtime64.jsx)(
    TablePagination_default,
    {
      currentPage,
      totalPages: calculatedTotalPages,
      totalItems: calculatedTotalItems,
      itemsPerPage,
      itemsPerPageOptions,
      onPageChange: handlePageChange,
      onItemsPerPageChange: handleItemsPerPageChange,
      itemLabel
    }
  ) });
  if (children) {
    return /* @__PURE__ */ (0, import_jsx_runtime64.jsxs)(import_jsx_runtime64.Fragment, { children: [
      children({ controls, table, pagination }),
      enableFilters && /* @__PURE__ */ (0, import_jsx_runtime64.jsx)(
        FilterModal,
        {
          isOpen: isFilterModalOpen,
          onClose: () => setIsFilterModalOpen(false),
          filterConfigs,
          onFiltersChange: updateFilters,
          onApply: handleFilterApply,
          onClear: clearFilters
        }
      )
    ] });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime64.jsxs)("div", { className: "w-full space-y-4", children: [
    controls,
    table,
    pagination,
    enableFilters && /* @__PURE__ */ (0, import_jsx_runtime64.jsx)(
      FilterModal,
      {
        isOpen: isFilterModalOpen,
        onClose: () => setIsFilterModalOpen(false),
        filterConfigs,
        onFiltersChange: updateFilters,
        onApply: handleFilterApply,
        onClear: clearFilters
      }
    )
  ] });
}
var TableProvider_default = TableProvider;

// src/components/Select/Select.tsx
var import_zustand10 = require("zustand");
var import_react42 = require("react");
var import_phosphor_react30 = require("phosphor-react");
var import_jsx_runtime65 = require("react/jsx-runtime");
var VARIANT_CLASSES4 = {
  outlined: "border-2 rounded-lg focus:border-primary-950",
  underlined: "border-b-2 focus:border-primary-950",
  rounded: "border-2 rounded-full focus:border-primary-950"
};
var SIZE_CLASSES12 = {
  small: "text-sm",
  medium: "text-md",
  large: "text-lg",
  "extra-large": "text-lg"
};
var HEIGHT_CLASSES = {
  small: "h-8",
  medium: "h-9",
  large: "h-10",
  "extra-large": "h-12"
};
var PADDING_CLASSES = {
  small: "px-2 py-1",
  medium: "px-3 py-2",
  large: "px-4 py-3",
  "extra-large": "px-5 py-4"
};
var SIDE_CLASSES2 = {
  top: "bottom-full -translate-y-1",
  right: "top-full translate-y-1",
  bottom: "top-full translate-y-1",
  left: "top-full translate-y-1"
};
var ALIGN_CLASSES2 = {
  start: "left-0",
  center: "left-1/2 -translate-x-1/2",
  end: "right-0"
};
function createSelectStore(onValueChange) {
  return (0, import_zustand10.create)((set) => ({
    open: false,
    setOpen: (open) => set({ open }),
    value: "",
    setValue: (value) => set({ value }),
    selectedLabel: "",
    setSelectedLabel: (label) => set({ selectedLabel: label }),
    onValueChange
  }));
}
var useSelectStore = (externalStore) => {
  if (!externalStore) {
    throw new Error(
      "Component must be used within a Select (store is missing)"
    );
  }
  return externalStore;
};
function getLabelAsNode(children) {
  if (typeof children === "string" || typeof children === "number") {
    return children;
  }
  const flattened = import_react42.Children.toArray(children);
  if (flattened.length === 1) return flattened[0];
  return /* @__PURE__ */ (0, import_jsx_runtime65.jsx)(import_jsx_runtime65.Fragment, { children: flattened });
}
var injectStore5 = (children, store, size, selectId) => {
  return import_react42.Children.map(children, (child) => {
    if ((0, import_react42.isValidElement)(child)) {
      const typedChild = child;
      const newProps = {
        store
      };
      if (typedChild.type === SelectTrigger) {
        newProps.size = size;
        newProps.selectId = selectId;
      }
      if (typedChild.props.children) {
        newProps.children = injectStore5(
          typedChild.props.children,
          store,
          size,
          selectId
        );
      }
      return (0, import_react42.cloneElement)(typedChild, newProps);
    }
    return child;
  });
};
var Select = ({
  children,
  defaultValue = "",
  className,
  value: propValue,
  onValueChange,
  size = "small",
  label,
  helperText,
  errorMessage,
  id
}) => {
  const storeRef = (0, import_react42.useRef)(null);
  storeRef.current ??= createSelectStore(onValueChange);
  const store = storeRef.current;
  const selectRef = (0, import_react42.useRef)(null);
  const { open, setOpen, setValue, selectedLabel } = (0, import_zustand10.useStore)(store, (s) => s);
  const generatedId = (0, import_react42.useId)();
  const selectId = id ?? `select-${generatedId}`;
  const findLabelForValue = (children2, targetValue) => {
    let found = null;
    const search = (nodes) => {
      import_react42.Children.forEach(nodes, (child) => {
        if (!(0, import_react42.isValidElement)(child)) return;
        const typedChild = child;
        if (typedChild.type === SelectItem && typedChild.props.value === targetValue) {
          if (typeof typedChild.props.children === "string")
            found = typedChild.props.children;
        }
        if (typedChild.props.children && !found)
          search(typedChild.props.children);
      });
    };
    search(children2);
    return found;
  };
  (0, import_react42.useEffect)(() => {
    if (!selectedLabel && defaultValue) {
      const label2 = findLabelForValue(children, defaultValue);
      if (label2) store.setState({ selectedLabel: label2 });
    }
  }, [children, defaultValue, selectedLabel]);
  (0, import_react42.useEffect)(() => {
    const handleClickOutside = (event) => {
      if (selectRef.current && !selectRef.current.contains(event.target)) {
        setOpen(false);
      }
    };
    const handleArrowKeys = (event) => {
      const selectContent = selectRef.current?.querySelector('[role="menu"]');
      if (selectContent) {
        event.preventDefault();
        const items = Array.from(
          selectContent.querySelectorAll(
            '[role="menuitem"]:not([aria-disabled="true"])'
          )
        ).filter((el) => el instanceof HTMLElement);
        const focused = document.activeElement;
        const currentIndex = items.findIndex((item) => item === focused);
        let nextIndex = 0;
        if (event.key === "ArrowDown") {
          nextIndex = currentIndex === -1 ? 0 : (currentIndex + 1) % items.length;
        } else {
          nextIndex = currentIndex === -1 ? items.length - 1 : (currentIndex - 1 + items.length) % items.length;
        }
        items[nextIndex]?.focus();
      }
    };
    if (open) {
      document.addEventListener("mousedown", handleClickOutside);
      document.addEventListener("keydown", handleArrowKeys);
    }
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
      document.removeEventListener("keydown", handleArrowKeys);
    };
  }, [open]);
  (0, import_react42.useEffect)(() => {
    if (propValue) {
      setValue(propValue);
      const label2 = findLabelForValue(children, propValue);
      if (label2) store.setState({ selectedLabel: label2 });
    }
  }, [propValue]);
  const sizeClasses = SIZE_CLASSES12[size];
  return /* @__PURE__ */ (0, import_jsx_runtime65.jsxs)("div", { className: cn("w-full", className), children: [
    label && /* @__PURE__ */ (0, import_jsx_runtime65.jsx)(
      "label",
      {
        htmlFor: selectId,
        className: cn("block font-bold text-text-900 mb-1.5", sizeClasses),
        children: label
      }
    ),
    /* @__PURE__ */ (0, import_jsx_runtime65.jsx)("div", { className: cn("relative w-full"), ref: selectRef, children: injectStore5(children, store, size, selectId) }),
    (helperText || errorMessage) && /* @__PURE__ */ (0, import_jsx_runtime65.jsxs)("div", { className: "mt-1.5 gap-1.5", children: [
      helperText && /* @__PURE__ */ (0, import_jsx_runtime65.jsx)("p", { className: "text-sm text-text-500", children: helperText }),
      errorMessage && /* @__PURE__ */ (0, import_jsx_runtime65.jsxs)("p", { className: "flex gap-1 items-center text-sm text-indicator-error", children: [
        /* @__PURE__ */ (0, import_jsx_runtime65.jsx)(import_phosphor_react30.WarningCircle, { size: 16 }),
        " ",
        errorMessage
      ] })
    ] })
  ] });
};
var SelectValue = ({
  placeholder,
  store: externalStore
}) => {
  const store = useSelectStore(externalStore);
  const selectedLabel = (0, import_zustand10.useStore)(store, (s) => s.selectedLabel);
  const value = (0, import_zustand10.useStore)(store, (s) => s.value);
  return /* @__PURE__ */ (0, import_jsx_runtime65.jsx)("span", { className: "text-inherit flex gap-2 items-center", children: selectedLabel || placeholder || value });
};
var SelectTrigger = (0, import_react42.forwardRef)(
  ({
    className,
    invalid = false,
    variant = "outlined",
    store: externalStore,
    disabled,
    size = "medium",
    selectId,
    ...props
  }, ref) => {
    const store = useSelectStore(externalStore);
    const open = (0, import_zustand10.useStore)(store, (s) => s.open);
    const toggleOpen = () => store.setState({ open: !open });
    const variantClasses = VARIANT_CLASSES4[variant];
    const heightClasses = HEIGHT_CLASSES[size];
    const paddingClasses = PADDING_CLASSES[size];
    return /* @__PURE__ */ (0, import_jsx_runtime65.jsxs)(
      "button",
      {
        ref,
        id: selectId,
        className: cn(
          "flex w-full items-center justify-between border-border-300",
          heightClasses,
          paddingClasses,
          invalid && `${variant == "underlined" ? "border-b-2" : "border-2"} border-indicator-error text-text-600`,
          disabled ? "cursor-not-allowed text-text-400 pointer-events-none opacity-50" : "cursor-pointer hover:bg-background-50 focus:bg-accent focus:text-accent-foreground hover:bg-accent hover:text-accent-foreground",
          !invalid && !disabled ? "text-text-700" : "",
          variantClasses,
          className
        ),
        onClick: toggleOpen,
        "aria-expanded": open,
        "aria-haspopup": "listbox",
        "aria-controls": open ? "select-content" : void 0,
        ...props,
        children: [
          props.children,
          /* @__PURE__ */ (0, import_jsx_runtime65.jsx)(
            import_phosphor_react30.CaretDown,
            {
              className: cn(
                "h-[1em] w-[1em] opacity-50 transition-transform",
                open ? "rotate-180" : ""
              )
            }
          )
        ]
      }
    );
  }
);
SelectTrigger.displayName = "SelectTrigger";
var SelectContent = (0, import_react42.forwardRef)(
  ({
    children,
    className,
    align = "start",
    side = "bottom",
    store: externalStore,
    ...props
  }, ref) => {
    const store = useSelectStore(externalStore);
    const open = (0, import_zustand10.useStore)(store, (s) => s.open);
    if (!open) return null;
    const getPositionClasses = () => `w-full min-w-full absolute ${SIDE_CLASSES2[side]} ${ALIGN_CLASSES2[align]}`;
    return /* @__PURE__ */ (0, import_jsx_runtime65.jsx)(
      "div",
      {
        role: "menu",
        ref,
        className: cn(
          "bg-secondary z-50 min-w-[210px] max-h-[300px] overflow-y-auto overflow-x-hidden rounded-md border p-1 shadow-md border-border-100",
          getPositionClasses(),
          className
        ),
        ...props,
        children
      }
    );
  }
);
SelectContent.displayName = "SelectContent";
var SelectItem = (0, import_react42.forwardRef)(
  ({
    className,
    children,
    value,
    disabled = false,
    store: externalStore,
    ...props
  }, ref) => {
    const store = useSelectStore(externalStore);
    const {
      value: selectedValue,
      setValue,
      setOpen,
      setSelectedLabel,
      onValueChange
    } = (0, import_zustand10.useStore)(store, (s) => s);
    const handleClick = (e) => {
      const labelNode = getLabelAsNode(children);
      if (!disabled) {
        setValue(value);
        setSelectedLabel(labelNode);
        setOpen(false);
        onValueChange?.(value);
      }
      props.onClick?.(e);
    };
    return /* @__PURE__ */ (0, import_jsx_runtime65.jsxs)(
      "div",
      {
        role: "menuitem",
        "aria-disabled": disabled,
        ref,
        className: `
          bg-secondary focus-visible:bg-background-50
          relative flex select-none items-center gap-2 rounded-sm p-3 outline-none transition-colors [&>svg]:size-4 [&>svg]:shrink-0
          ${className}
          ${disabled ? "cursor-not-allowed text-text-400 pointer-events-none opacity-50" : "cursor-pointer hover:bg-background-50 text-text-700 focus:bg-accent focus:text-accent-foreground hover:bg-accent hover:text-accent-foreground"}
          ${selectedValue === value && "bg-background-50"}
        `,
        onClick: handleClick,
        onKeyDown: (e) => {
          if (e.key === "Enter" || e.key === " ") handleClick(e);
        },
        tabIndex: disabled ? -1 : 0,
        ...props,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime65.jsx)("span", { className: "absolute right-2 flex h-3.5 w-3.5 items-center justify-center", children: selectedValue === value && /* @__PURE__ */ (0, import_jsx_runtime65.jsx)(import_phosphor_react30.Check, { className: "" }) }),
          children
        ]
      }
    );
  }
);
SelectItem.displayName = "SelectItem";
var Select_default = Select;

// src/components/Menu/Menu.tsx
var import_zustand11 = require("zustand");
var import_react43 = require("react");
var import_phosphor_react31 = require("phosphor-react");
var import_jsx_runtime66 = require("react/jsx-runtime");
var createMenuStore = (onValueChange) => (0, import_zustand11.create)((set) => ({
  value: "",
  setValue: (value) => {
    set({ value });
    onValueChange?.(value);
  },
  onValueChange
}));
var useMenuStore = (externalStore) => {
  if (!externalStore) throw new Error("MenuItem must be inside Menu");
  return externalStore;
};
var VARIANT_CLASSES5 = {
  menu: "bg-background shadow-soft-shadow-1 px-6",
  menu2: "",
  "menu-overflow": "",
  breadcrumb: "bg-transparent shadow-none !px-0"
};
var Menu = (0, import_react43.forwardRef)(
  ({
    className,
    children,
    defaultValue,
    value: propValue,
    variant = "menu",
    onValueChange,
    ...props
  }, ref) => {
    const storeRef = (0, import_react43.useRef)(null);
    storeRef.current ??= createMenuStore(onValueChange);
    const store = storeRef.current;
    const { setValue } = (0, import_zustand11.useStore)(store, (s) => s);
    (0, import_react43.useEffect)(() => {
      setValue(propValue ?? defaultValue);
    }, [defaultValue, propValue, setValue]);
    const baseClasses = variant === "menu-overflow" ? "w-fit py-2 flex flex-row items-center justify-center" : "w-full py-2 flex flex-row items-center justify-center";
    const variantClasses = VARIANT_CLASSES5[variant];
    return /* @__PURE__ */ (0, import_jsx_runtime66.jsx)(
      "div",
      {
        ref,
        className: `
          ${baseClasses}
          ${variantClasses}
          ${className ?? ""}
        `,
        ...props,
        children: injectStore6(children, store)
      }
    );
  }
);
Menu.displayName = "Menu";
var MenuContent = (0, import_react43.forwardRef)(
  ({ className, children, variant = "menu", ...props }, ref) => {
    const baseClasses = "w-full flex flex-row items-center gap-2";
    const variantClasses = variant === "menu2" || variant === "menu-overflow" ? "overflow-x-auto scroll-smooth" : "";
    return /* @__PURE__ */ (0, import_jsx_runtime66.jsx)(
      "ul",
      {
        ref,
        className: `
          ${baseClasses}
          ${variantClasses}
          ${variant == "breadcrumb" ? "flex-wrap" : ""}
          ${className ?? ""}
        `,
        style: variant === "menu2" || variant === "menu-overflow" ? { scrollbarWidth: "none", msOverflowStyle: "none" } : void 0,
        ...props,
        children
      }
    );
  }
);
MenuContent.displayName = "MenuContent";
var MenuItem = (0, import_react43.forwardRef)(
  ({
    className,
    children,
    value,
    disabled = false,
    store: externalStore,
    variant = "menu",
    separator = false,
    ...props
  }, ref) => {
    const store = useMenuStore(externalStore);
    const { value: selectedValue, setValue } = (0, import_zustand11.useStore)(store, (s) => s);
    const handleClick = (e) => {
      if (!disabled) {
        setValue(value);
      }
      props.onClick?.(e);
    };
    const commonProps = {
      role: "menuitem",
      "aria-disabled": disabled,
      ref,
      onClick: handleClick,
      onKeyDown: (e) => {
        if (["Enter", " "].includes(e.key)) handleClick(e);
      },
      tabIndex: disabled ? -1 : 0,
      onMouseDown: (e) => {
        e.preventDefault();
      },
      ...props
    };
    const variants = {
      menu: /* @__PURE__ */ (0, import_jsx_runtime66.jsx)(
        "li",
        {
          "data-variant": "menu",
          className: `
            w-full flex flex-col items-center justify-center gap-0.5 py-1 px-2 rounded-sm font-medium text-xs
            [&>svg]:size-6 cursor-pointer hover:bg-primary-600 hover:text-text
            focus:outline-none focus:border-indicator-info focus:border-2
            ${selectedValue === value ? "bg-primary-50 text-primary-950" : "text-text-950"}
            ${className ?? ""}
          `,
          ...commonProps,
          children
        }
      ),
      menu2: /* @__PURE__ */ (0, import_jsx_runtime66.jsxs)(
        "li",
        {
          "data-variant": "menu2",
          className: `
            w-full flex flex-col items-center px-2 pt-4 gap-3 cursor-pointer focus:rounded-sm justify-center hover:bg-background-100 rounded-lg
            focus:outline-none focus:border-indicator-info focus:border-2
            ${selectedValue === value ? "" : "pb-4"}
          `,
          ...commonProps,
          children: [
            /* @__PURE__ */ (0, import_jsx_runtime66.jsx)(
              "span",
              {
                className: cn(
                  "flex flex-row items-center gap-2 px-4 text-text-950 text-xs font-bold",
                  className
                ),
                children
              }
            ),
            selectedValue === value && /* @__PURE__ */ (0, import_jsx_runtime66.jsx)("div", { className: "h-1 w-full bg-primary-950 rounded-lg" })
          ]
        }
      ),
      "menu-overflow": /* @__PURE__ */ (0, import_jsx_runtime66.jsxs)(
        "li",
        {
          "data-variant": "menu-overflow",
          className: `
            w-fit flex flex-col items-center px-2 pt-4 gap-3 cursor-pointer focus:rounded-sm justify-center hover:bg-background-100 rounded-lg
            focus:outline-none focus:border-indicator-info focus:border-2
            ${selectedValue === value ? "" : "pb-4"}
          `,
          ...commonProps,
          children: [
            /* @__PURE__ */ (0, import_jsx_runtime66.jsx)(
              "span",
              {
                className: cn(
                  "flex flex-row items-center gap-2 px-4 text-text-950 text-xs font-bold",
                  className
                ),
                children
              }
            ),
            selectedValue === value && /* @__PURE__ */ (0, import_jsx_runtime66.jsx)("div", { className: "h-1 w-full bg-primary-950 rounded-lg" })
          ]
        }
      ),
      breadcrumb: /* @__PURE__ */ (0, import_jsx_runtime66.jsxs)(
        "li",
        {
          "data-variant": "breadcrumb",
          className: `
            flex flex-row gap-2 items-center w-fit p-2 rounded-lg hover:text-primary-600 cursor-pointer font-bold text-xs
            focus:outline-none focus:border-indicator-info focus:border-2
            ${selectedValue === value ? "text-text-950" : "text-text-600"}
            ${className ?? ""}
          `,
          ...commonProps,
          children: [
            /* @__PURE__ */ (0, import_jsx_runtime66.jsx)(
              "span",
              {
                className: cn(
                  "border-b border-text-600 hover:border-primary-600 text-inherit text-xs",
                  selectedValue === value ? "border-b-0 font-bold" : "border-b-text-600"
                ),
                children
              }
            ),
            separator && /* @__PURE__ */ (0, import_jsx_runtime66.jsx)(
              import_phosphor_react31.CaretRight,
              {
                size: 16,
                className: "text-text-600",
                "data-testid": "separator"
              }
            )
          ]
        }
      )
    };
    return variants[variant] ?? variants["menu"];
  }
);
MenuItem.displayName = "MenuItem";
var internalScroll = (container, direction) => {
  if (!container) return;
  container.scrollBy({
    left: direction === "left" ? -150 : 150,
    behavior: "smooth"
  });
};
var internalCheckScroll = (container, setShowLeftArrow, setShowRightArrow) => {
  if (!container) return;
  const { scrollLeft, scrollWidth, clientWidth } = container;
  setShowLeftArrow(scrollLeft > 0);
  setShowRightArrow(scrollLeft + clientWidth < scrollWidth);
};
var MenuOverflow = ({
  children,
  className,
  defaultValue,
  value,
  onValueChange,
  ...props
}) => {
  const containerRef = (0, import_react43.useRef)(null);
  const [showLeftArrow, setShowLeftArrow] = (0, import_react43.useState)(false);
  const [showRightArrow, setShowRightArrow] = (0, import_react43.useState)(false);
  (0, import_react43.useEffect)(() => {
    const checkScroll = () => internalCheckScroll(
      containerRef.current,
      setShowLeftArrow,
      setShowRightArrow
    );
    checkScroll();
    const container = containerRef.current;
    container?.addEventListener("scroll", checkScroll);
    window.addEventListener("resize", checkScroll);
    return () => {
      container?.removeEventListener("scroll", checkScroll);
      window.removeEventListener("resize", checkScroll);
    };
  }, []);
  return /* @__PURE__ */ (0, import_jsx_runtime66.jsxs)(
    "div",
    {
      "data-testid": "menu-overflow-wrapper",
      className: cn("relative w-full overflow-hidden", className),
      children: [
        showLeftArrow && /* @__PURE__ */ (0, import_jsx_runtime66.jsxs)(
          "button",
          {
            onClick: () => internalScroll(containerRef.current, "left"),
            className: "absolute left-0 top-1/2 -translate-y-1/2 z-10 flex h-8 w-8 items-center justify-center rounded-full bg-white shadow-md cursor-pointer",
            "data-testid": "scroll-left-button",
            children: [
              /* @__PURE__ */ (0, import_jsx_runtime66.jsx)(import_phosphor_react31.CaretLeft, { size: 16 }),
              /* @__PURE__ */ (0, import_jsx_runtime66.jsx)("span", { className: "sr-only", children: "Scroll left" })
            ]
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime66.jsx)(
          Menu,
          {
            defaultValue,
            onValueChange,
            value,
            variant: "menu2",
            ...props,
            children: /* @__PURE__ */ (0, import_jsx_runtime66.jsx)(MenuContent, { ref: containerRef, variant: "menu2", children })
          }
        ),
        showRightArrow && /* @__PURE__ */ (0, import_jsx_runtime66.jsxs)(
          "button",
          {
            onClick: () => internalScroll(containerRef.current, "right"),
            className: "absolute right-0 top-1/2 -translate-y-1/2 z-10 flex h-8 w-8 items-center justify-center rounded-full bg-white shadow-md cursor-pointer",
            "data-testid": "scroll-right-button",
            children: [
              /* @__PURE__ */ (0, import_jsx_runtime66.jsx)(import_phosphor_react31.CaretRight, { size: 16 }),
              /* @__PURE__ */ (0, import_jsx_runtime66.jsx)("span", { className: "sr-only", children: "Scroll right" })
            ]
          }
        )
      ]
    }
  );
};
var injectStore6 = (children, store) => import_react43.Children.map(children, (child) => {
  if (!(0, import_react43.isValidElement)(child)) return child;
  const typedChild = child;
  const shouldInject = typedChild.type === MenuItem;
  return (0, import_react43.cloneElement)(typedChild, {
    ...shouldInject ? { store } : {},
    ...typedChild.props.children ? { children: injectStore6(typedChild.props.children, store) } : {}
  });
});
var Menu_default = Menu;

// src/components/StatisticsCard/StatisticsCard.tsx
var import_phosphor_react32 = require("phosphor-react");
var import_jsx_runtime67 = require("react/jsx-runtime");
var VARIANT_STYLES = {
  high: "bg-success-background",
  medium: "bg-warning-background",
  low: "bg-error-background",
  total: "bg-info-background"
};
var VALUE_TEXT_COLORS = {
  high: "text-success-700",
  medium: "text-warning-600",
  low: "text-error-700",
  total: "text-info-700"
};
var StatCard2 = ({ item, showPlaceholder = false }) => {
  return /* @__PURE__ */ (0, import_jsx_runtime67.jsxs)(
    "div",
    {
      className: `rounded-xl py-[17px] px-6 min-h-[105px] flex flex-col justify-center items-start gap-1 ${VARIANT_STYLES[item.variant]}`,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime67.jsx)(
          Text_default,
          {
            size: "4xl",
            weight: "bold",
            className: `${VALUE_TEXT_COLORS[item.variant]} leading-[42px] tracking-[0.2px] self-stretch`,
            children: showPlaceholder ? "-" : item.value
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime67.jsx)(
          Text_default,
          {
            size: "xs",
            weight: "bold",
            className: "uppercase text-[8px] leading-[9px] text-text-800 whitespace-nowrap",
            children: item.label
          }
        )
      ]
    }
  );
};
var getGridColumnsClass = (itemCount) => {
  if (itemCount === 4) return "lg:grid-cols-4";
  if (itemCount === 3) return "lg:grid-cols-3";
  if (itemCount === 2) return "lg:grid-cols-2";
  return "lg:grid-cols-1";
};
var StatisticsCard = ({
  title,
  data,
  showPlaceholder = false,
  emptyStateMessage,
  emptyStateButtonText,
  onEmptyStateButtonClick,
  dropdownOptions,
  selectedDropdownValue,
  onDropdownChange,
  selectPlaceholder = "Selecione um per\xEDodo",
  dropdownAriaLabel = "Filtro de per\xEDodo",
  className = ""
}) => {
  const hasData = data && data.length > 0;
  const gridColumnsClass = hasData ? getGridColumnsClass(data.length) : "";
  return /* @__PURE__ */ (0, import_jsx_runtime67.jsxs)(
    "div",
    {
      className: `bg-background rounded-xl p-4 h-auto lg:h-[185px] flex flex-col gap-2 ${className}`,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime67.jsxs)("div", { className: "flex flex-row justify-between items-center gap-4", children: [
          /* @__PURE__ */ (0, import_jsx_runtime67.jsx)(
            Text_default,
            {
              as: "h3",
              size: "sm",
              weight: "medium",
              color: "text-text-600",
              className: "flex-1 min-w-0",
              children: title
            }
          ),
          dropdownOptions && dropdownOptions.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime67.jsx)("div", { className: "w-[120px] min-w-[90px] sm:shrink-0", children: /* @__PURE__ */ (0, import_jsx_runtime67.jsxs)(
            Select_default,
            {
              value: selectedDropdownValue,
              onValueChange: onDropdownChange,
              size: "medium",
              children: [
                /* @__PURE__ */ (0, import_jsx_runtime67.jsx)(
                  SelectTrigger,
                  {
                    className: "border border-border-300 rounded [&>span]:whitespace-nowrap [&>span]:overflow-hidden [&>span]:text-ellipsis",
                    "aria-label": dropdownAriaLabel,
                    children: /* @__PURE__ */ (0, import_jsx_runtime67.jsx)(SelectValue, { placeholder: selectPlaceholder })
                  }
                ),
                /* @__PURE__ */ (0, import_jsx_runtime67.jsx)(SelectContent, { className: "min-w-[120px]", children: dropdownOptions.map((option) => /* @__PURE__ */ (0, import_jsx_runtime67.jsx)(
                  SelectItem,
                  {
                    value: option.value,
                    className: "whitespace-nowrap",
                    children: option.label
                  },
                  option.value
                )) })
              ]
            }
          ) })
        ] }),
        hasData ? /* @__PURE__ */ (0, import_jsx_runtime67.jsx)(
          "div",
          {
            className: `grid grid-cols-1 sm:grid-cols-2 gap-[13px] ${gridColumnsClass}`,
            children: data.map((item, index) => /* @__PURE__ */ (0, import_jsx_runtime67.jsx)(
              StatCard2,
              {
                item,
                showPlaceholder
              },
              `${item.variant}-${item.label}-${index}`
            ))
          }
        ) : /* @__PURE__ */ (0, import_jsx_runtime67.jsxs)("div", { className: "border border-dashed border-border-300 rounded-lg p-6 min-h-[105px] flex flex-col items-center justify-center gap-2", children: [
          /* @__PURE__ */ (0, import_jsx_runtime67.jsx)(
            Text_default,
            {
              size: "sm",
              color: "text-text-600",
              className: "text-center max-w-md",
              children: emptyStateMessage
            }
          ),
          onEmptyStateButtonClick && /* @__PURE__ */ (0, import_jsx_runtime67.jsx)(
            Button_default,
            {
              variant: "outline",
              action: "primary",
              size: "small",
              onClick: onEmptyStateButtonClick,
              iconLeft: /* @__PURE__ */ (0, import_jsx_runtime67.jsx)(import_phosphor_react32.Plus, { size: 16, weight: "bold" }),
              children: emptyStateButtonText
            }
          )
        ] })
      ]
    }
  );
};

// src/components/NotFound/NotFound.tsx
var import_jsx_runtime68 = require("react/jsx-runtime");
var NotFound = ({
  title,
  description,
  buttonText = "Voltar",
  onButtonClick,
  className = "",
  errorType = "404",
  customErrorCode
}) => {
  const getErrorCode = () => {
    if (errorType === "custom") {
      return customErrorCode?.trim() || "ERROR";
    }
    return errorType;
  };
  const getDefaultTitle = () => {
    switch (errorType) {
      case "404":
        return "P\xE1gina n\xE3o encontrada";
      case "500":
        return "Erro interno do servidor";
      default:
        return "Erro";
    }
  };
  const getDefaultDescription = () => {
    switch (errorType) {
      case "404":
        return "Oops! A p\xE1gina que voc\xEA est\xE1 procurando n\xE3o existe ou foi removida.";
      case "500":
        return "Algo deu errado em nossos servidores. Tente novamente mais tarde.";
      default:
        return "Ocorreu um erro inesperado.";
    }
  };
  const handleButtonClick = (event) => {
    event.preventDefault();
    onButtonClick?.();
  };
  const errorTitle = title || getDefaultTitle();
  const errorDescription = description || getDefaultDescription();
  const errorCode = getErrorCode();
  return /* @__PURE__ */ (0, import_jsx_runtime68.jsx)(
    "div",
    {
      className: cn(
        "flex flex-col w-full h-screen items-center justify-center bg-background-50 px-4",
        className
      ),
      children: /* @__PURE__ */ (0, import_jsx_runtime68.jsx)(
        "main",
        {
          role: "main",
          "aria-labelledby": "error-title",
          "aria-describedby": "error-description",
          className: "flex flex-col items-center text-center max-w-md space-y-6",
          children: /* @__PURE__ */ (0, import_jsx_runtime68.jsxs)("section", { "aria-label": `Erro ${errorCode}`, children: [
            /* @__PURE__ */ (0, import_jsx_runtime68.jsx)(
              "div",
              {
                className: "text-8xl font-bold text-primary-300 select-none",
                "aria-label": `C\xF3digo de erro: ${errorCode}`,
                children: errorCode
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime68.jsxs)("header", { className: "space-y-2", children: [
              /* @__PURE__ */ (0, import_jsx_runtime68.jsx)(
                Text_default,
                {
                  size: "xl",
                  weight: "bold",
                  className: "text-text-950",
                  id: "error-title",
                  "aria-level": 1,
                  children: errorTitle
                }
              ),
              /* @__PURE__ */ (0, import_jsx_runtime68.jsx)(Text_default, { size: "md", className: "text-text-600", id: "error-description", children: errorDescription })
            ] }),
            onButtonClick && /* @__PURE__ */ (0, import_jsx_runtime68.jsx)("nav", { "aria-label": "Navega\xE7\xE3o de erro", children: /* @__PURE__ */ (0, import_jsx_runtime68.jsx)(
              Button_default,
              {
                onClick: handleButtonClick,
                variant: "solid",
                size: "medium",
                className: "mt-8",
                "aria-describedby": "error-description",
                "aria-label": `${buttonText}. ${errorDescription}`,
                children: buttonText
              }
            ) })
          ] })
        }
      )
    }
  );
};
var NotFound_default = NotFound;

// src/components/VideoPlayer/VideoPlayer.tsx
var import_react45 = require("react");
var import_react_dom2 = require("react-dom");
var import_phosphor_react34 = require("phosphor-react");

// src/components/DownloadButton/DownloadButton.tsx
var import_react44 = require("react");
var import_phosphor_react33 = require("phosphor-react");
var import_jsx_runtime69 = require("react/jsx-runtime");
var getMimeType = (url) => {
  const extension = getFileExtension(url);
  const mimeTypes = {
    pdf: "application/pdf",
    png: "image/png",
    jpg: "image/jpeg",
    jpeg: "image/jpeg",
    mp3: "audio/mpeg",
    mp4: "video/mp4",
    vtt: "text/vtt"
  };
  return mimeTypes[extension] || "application/octet-stream";
};
var triggerDownload = async (url, filename) => {
  try {
    const response = await fetch(url, {
      mode: "cors",
      credentials: "same-origin"
    });
    if (!response.ok) {
      throw new Error(
        `Failed to fetch file: ${response.status} ${response.statusText}`
      );
    }
    const blob = await response.blob();
    const mimeType = getMimeType(url);
    const typedBlob = new Blob([blob], { type: mimeType });
    const blobUrl = URL.createObjectURL(typedBlob);
    const link = document.createElement("a");
    link.href = blobUrl;
    link.download = filename;
    link.rel = "noopener noreferrer";
    document.body.appendChild(link);
    link.click();
    link.remove();
    setTimeout(() => {
      URL.revokeObjectURL(blobUrl);
    }, 1e3);
  } catch (error) {
    console.warn("Fetch download failed, falling back to direct link:", error);
    const link = document.createElement("a");
    link.href = url;
    link.download = filename;
    link.rel = "noopener noreferrer";
    link.target = "_blank";
    document.body.appendChild(link);
    link.click();
    link.remove();
  }
};
var getFileExtension = (url) => {
  try {
    const u = new URL(url, globalThis.location?.origin || "http://localhost");
    url = u.pathname;
  } catch {
  }
  const path = url.split(/[?#]/)[0];
  const dot = path.lastIndexOf(".");
  return dot > -1 ? path.slice(dot + 1).toLowerCase() : "file";
};
var generateFilename = (contentType, url, lessonTitle = "aula") => {
  const sanitizedTitle = lessonTitle.toLowerCase().replaceAll(/[^a-z0-9\s]/g, "").replaceAll(/\s+/g, "-").substring(0, 50);
  const extension = getFileExtension(url);
  return `${sanitizedTitle}-${contentType}.${extension}`;
};
var DownloadButton = ({
  content,
  className,
  onDownloadStart,
  onDownloadComplete,
  onDownloadError,
  lessonTitle = "aula",
  disabled = false
}) => {
  const [isDownloading, setIsDownloading] = (0, import_react44.useState)(false);
  const isValidUrl = (0, import_react44.useCallback)((url) => {
    return Boolean(
      url && url.trim() !== "" && url !== "undefined" && url !== "null"
    );
  }, []);
  const getAvailableContent = (0, import_react44.useCallback)(() => {
    const downloads = [];
    if (isValidUrl(content.urlDoc)) {
      downloads.push({
        type: "documento",
        url: content.urlDoc,
        label: "Documento"
      });
    }
    if (isValidUrl(content.urlInitialFrame)) {
      downloads.push({
        type: "quadro-inicial",
        url: content.urlInitialFrame,
        label: "Quadro Inicial"
      });
    }
    if (isValidUrl(content.urlFinalFrame)) {
      downloads.push({
        type: "quadro-final",
        url: content.urlFinalFrame,
        label: "Quadro Final"
      });
    }
    if (isValidUrl(content.urlPodcast)) {
      downloads.push({
        type: "podcast",
        url: content.urlPodcast,
        label: "Podcast"
      });
    }
    if (isValidUrl(content.urlVideo)) {
      downloads.push({ type: "video", url: content.urlVideo, label: "V\xEDdeo" });
    }
    return downloads;
  }, [content, isValidUrl]);
  const handleDownload = (0, import_react44.useCallback)(async () => {
    if (disabled || isDownloading) return;
    const availableContent = getAvailableContent();
    if (availableContent.length === 0) {
      return;
    }
    setIsDownloading(true);
    try {
      for (let i = 0; i < availableContent.length; i++) {
        const item = availableContent[i];
        try {
          onDownloadStart?.(item.type);
          const filename = generateFilename(item.type, item.url, lessonTitle);
          await triggerDownload(item.url, filename);
          onDownloadComplete?.(item.type);
          if (i < availableContent.length - 1) {
            await new Promise((resolve) => setTimeout(resolve, 200));
          }
        } catch (error) {
          onDownloadError?.(
            item.type,
            error instanceof Error ? error : new Error(`Falha ao baixar ${item.label}`)
          );
        }
      }
    } finally {
      setIsDownloading(false);
    }
  }, [
    disabled,
    isDownloading,
    getAvailableContent,
    lessonTitle,
    onDownloadStart,
    onDownloadComplete,
    onDownloadError
  ]);
  const hasContent = getAvailableContent().length > 0;
  if (!hasContent) {
    return null;
  }
  return /* @__PURE__ */ (0, import_jsx_runtime69.jsx)("div", { className: cn("flex items-center", className), children: /* @__PURE__ */ (0, import_jsx_runtime69.jsx)(
    IconButton_default,
    {
      icon: /* @__PURE__ */ (0, import_jsx_runtime69.jsx)(import_phosphor_react33.DownloadSimple, { size: 24 }),
      onClick: handleDownload,
      disabled: disabled || isDownloading,
      "aria-label": (() => {
        if (isDownloading) {
          return "Baixando conte\xFAdo...";
        }
        const contentCount = getAvailableContent().length;
        const suffix = contentCount > 1 ? "s" : "";
        return `Baixar conte\xFAdo da aula (${contentCount} arquivo${suffix})`;
      })(),
      className: cn(
        "!bg-transparent hover:!bg-black/10 transition-colors",
        isDownloading && "opacity-60 cursor-not-allowed"
      )
    }
  ) });
};
var DownloadButton_default = DownloadButton;

// src/components/VideoPlayer/VideoPlayer.tsx
var import_jsx_runtime70 = require("react/jsx-runtime");
var CONTROLS_HIDE_TIMEOUT = 3e3;
var LEAVE_HIDE_TIMEOUT = 1e3;
var INIT_DELAY = 100;
var formatTime2 = (seconds) => {
  if (!seconds || Number.isNaN(seconds)) return "0:00";
  const mins = Math.floor(seconds / 60);
  const secs = Math.floor(seconds % 60);
  return `${mins}:${secs.toString().padStart(2, "0")}`;
};
var ProgressBar2 = ({
  currentTime,
  duration,
  progressPercentage,
  onSeek,
  className = "px-4 pb-2"
}) => /* @__PURE__ */ (0, import_jsx_runtime70.jsx)("div", { className, children: /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(
  "input",
  {
    type: "range",
    min: 0,
    max: duration || 100,
    value: currentTime,
    onChange: (e) => onSeek(Number.parseFloat(e.target.value)),
    className: "w-full h-1 bg-neutral-600 rounded-full appearance-none cursor-pointer slider:bg-primary-600 focus:outline-none focus:ring-2 focus:ring-primary-500",
    "aria-label": "Video progress",
    style: {
      background: `linear-gradient(to right, var(--color-primary-700) ${progressPercentage}%, var(--color-secondary-300) ${progressPercentage}%)`
    }
  }
) });
var VolumeControls = ({
  volume,
  isMuted,
  onVolumeChange,
  onToggleMute,
  iconSize = 24,
  showSlider = true
}) => /* @__PURE__ */ (0, import_jsx_runtime70.jsxs)("div", { className: "flex items-center gap-2", children: [
  /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(
    IconButton_default,
    {
      icon: isMuted ? /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(import_phosphor_react34.SpeakerSlash, { size: iconSize }) : /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(import_phosphor_react34.SpeakerHigh, { size: iconSize }),
      onClick: onToggleMute,
      "aria-label": isMuted ? "Unmute" : "Mute",
      className: "!bg-transparent !text-white hover:!bg-white/20"
    }
  ),
  showSlider && /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(
    "input",
    {
      type: "range",
      min: 0,
      max: 100,
      value: Math.round(volume * 100),
      onChange: (e) => onVolumeChange(Number.parseInt(e.target.value)),
      className: "w-20 h-1 bg-neutral-600 rounded-full appearance-none cursor-pointer focus:outline-none focus:ring-2 focus:ring-primary-500",
      "aria-label": "Volume control",
      style: {
        background: `linear-gradient(to right, var(--color-primary-700) ${volume * 100}%, var(--color-secondary-300) ${volume * 100}%)`
      }
    }
  )
] });
var SpeedMenu = ({
  showSpeedMenu,
  playbackRate,
  onToggleMenu,
  onSpeedChange,
  isFullscreen,
  iconSize = 24,
  isTinyMobile = false
}) => {
  const buttonRef = (0, import_react45.useRef)(null);
  const speedMenuContainerRef = (0, import_react45.useRef)(null);
  const speedMenuRef = (0, import_react45.useRef)(null);
  const getMenuPosition = () => {
    if (!buttonRef.current) return { top: 0, left: 0 };
    const rect = buttonRef.current.getBoundingClientRect();
    const menuHeight = isTinyMobile ? 150 : 180;
    const menuWidth = isTinyMobile ? 60 : 80;
    const padding = isTinyMobile ? 4 : 8;
    return {
      // Fixed coords are viewport-based — no scroll offsets.
      top: Math.max(padding, rect.top - menuHeight),
      left: Math.max(padding, rect.right - menuWidth)
    };
  };
  const position = getMenuPosition();
  (0, import_react45.useEffect)(() => {
    const handleClickOutside = (event) => {
      const target = event.target;
      const isOutsideContainer = speedMenuContainerRef.current && !speedMenuContainerRef.current.contains(target);
      const isOutsideMenu = speedMenuRef.current && !speedMenuRef.current.contains(target);
      if (isOutsideContainer && isOutsideMenu) {
        onToggleMenu();
      }
    };
    if (showSpeedMenu) {
      document.addEventListener("mousedown", handleClickOutside);
    }
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, [showSpeedMenu, onToggleMenu]);
  const menuContent = /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(
    "div",
    {
      ref: speedMenuRef,
      role: "menu",
      "aria-label": "Playback speed",
      className: isFullscreen ? "absolute bottom-12 right-0 bg-background border border-border-100 rounded-lg shadow-lg p-2 min-w-24 z-[9999]" : "fixed bg-background border border-border-100 rounded-lg shadow-lg p-2 min-w-24 z-[9999]",
      style: isFullscreen ? void 0 : {
        top: `${position.top}px`,
        left: `${position.left}px`
      },
      children: [0.5, 0.75, 1, 1.25, 1.5, 2].map((speed) => /* @__PURE__ */ (0, import_jsx_runtime70.jsxs)(
        "button",
        {
          role: "menuitemradio",
          "aria-checked": playbackRate === speed,
          onClick: () => onSpeedChange(speed),
          className: `block w-full text-left px-3 py-1 text-sm rounded hover:bg-border-50 transition-colors ${playbackRate === speed ? "bg-primary-950 text-secondary-100 font-medium" : "text-text-950"}`,
          children: [
            speed,
            "x"
          ]
        },
        speed
      ))
    }
  );
  const portalContent = showSpeedMenu && globalThis.window !== void 0 && globalThis.document !== void 0 && !!globalThis.document?.body ? (0, import_react_dom2.createPortal)(menuContent, globalThis.document.body) : null;
  return /* @__PURE__ */ (0, import_jsx_runtime70.jsxs)("div", { className: "relative", ref: speedMenuContainerRef, children: [
    /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(
      IconButton_default,
      {
        ref: buttonRef,
        icon: /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(import_phosphor_react34.DotsThreeVertical, { size: iconSize }),
        onClick: onToggleMenu,
        "aria-label": "Playback speed",
        "aria-haspopup": "menu",
        "aria-expanded": showSpeedMenu,
        className: "!bg-transparent !text-white hover:!bg-white/20"
      }
    ),
    showSpeedMenu && (isFullscreen ? menuContent : portalContent)
  ] });
};
var VideoPlayer = ({
  src,
  poster,
  subtitles,
  title,
  subtitle: subtitleText,
  initialTime = 0,
  onTimeUpdate,
  onProgress,
  onVideoComplete,
  className,
  autoSave = true,
  storageKey = "video-progress",
  downloadContent,
  showDownloadButton = false,
  onDownloadStart,
  onDownloadComplete,
  onDownloadError
}) => {
  const videoRef = (0, import_react45.useRef)(null);
  const { isUltraSmallMobile, isTinyMobile } = useMobile();
  const [isPlaying, setIsPlaying] = (0, import_react45.useState)(false);
  const [currentTime, setCurrentTime] = (0, import_react45.useState)(0);
  const [duration, setDuration] = (0, import_react45.useState)(0);
  const [isMuted, setIsMuted] = (0, import_react45.useState)(false);
  const [volume, setVolume] = (0, import_react45.useState)(1);
  const [isFullscreen, setIsFullscreen] = (0, import_react45.useState)(false);
  const [showControls, setShowControls] = (0, import_react45.useState)(true);
  const [hasCompleted, setHasCompleted] = (0, import_react45.useState)(false);
  const [showCaptions, setShowCaptions] = (0, import_react45.useState)(false);
  const [subtitlesValidation, setSubtitlesValidation] = (0, import_react45.useState)("idle");
  (0, import_react45.useEffect)(() => {
    setHasCompleted(false);
  }, [src]);
  const [playbackRate, setPlaybackRate] = (0, import_react45.useState)(1);
  const [showSpeedMenu, setShowSpeedMenu] = (0, import_react45.useState)(false);
  const lastSaveTimeRef = (0, import_react45.useRef)(0);
  const trackRef = (0, import_react45.useRef)(null);
  const controlsTimeoutRef = (0, import_react45.useRef)(null);
  const lastMousePositionRef = (0, import_react45.useRef)({ x: 0, y: 0 });
  const isUserInteracting = (0, import_react45.useCallback)(() => {
    if (showSpeedMenu) {
      return true;
    }
    const activeElement = document.activeElement;
    const videoContainer = videoRef.current?.parentElement;
    if (activeElement && videoContainer?.contains(activeElement)) {
      if (activeElement === videoRef.current) {
        return false;
      }
      const isControl = activeElement.matches("button, input, [tabindex]");
      if (isControl) {
        return true;
      }
    }
    return false;
  }, [showSpeedMenu]);
  const clearControlsTimeout = (0, import_react45.useCallback)(() => {
    if (controlsTimeoutRef.current) {
      clearTimeout(controlsTimeoutRef.current);
      controlsTimeoutRef.current = null;
    }
  }, []);
  const showControlsWithTimer = (0, import_react45.useCallback)(() => {
    setShowControls(true);
    clearControlsTimeout();
    if (isFullscreen) {
      if (isPlaying) {
        controlsTimeoutRef.current = globalThis.setTimeout(() => {
          setShowControls(false);
        }, CONTROLS_HIDE_TIMEOUT);
      }
    } else {
      controlsTimeoutRef.current = globalThis.setTimeout(() => {
        setShowControls(false);
      }, CONTROLS_HIDE_TIMEOUT);
    }
  }, [isFullscreen, isPlaying, clearControlsTimeout]);
  const handleMouseMove = (0, import_react45.useCallback)(
    (event) => {
      const currentX = event.clientX;
      const currentY = event.clientY;
      const lastPos = lastMousePositionRef.current;
      const hasMoved = Math.abs(currentX - lastPos.x) > 5 || Math.abs(currentY - lastPos.y) > 5;
      if (hasMoved) {
        lastMousePositionRef.current = { x: currentX, y: currentY };
        showControlsWithTimer();
      }
    },
    [showControlsWithTimer]
  );
  const handleMouseEnter = (0, import_react45.useCallback)(() => {
    showControlsWithTimer();
  }, [showControlsWithTimer]);
  const handleMouseLeave = (0, import_react45.useCallback)(() => {
    const userInteracting = isUserInteracting();
    clearControlsTimeout();
    if (!isFullscreen && !userInteracting) {
      controlsTimeoutRef.current = globalThis.setTimeout(() => {
        setShowControls(false);
      }, LEAVE_HIDE_TIMEOUT);
    }
  }, [isFullscreen, clearControlsTimeout, isUserInteracting]);
  (0, import_react45.useEffect)(() => {
    if (videoRef.current) {
      videoRef.current.volume = volume;
      videoRef.current.muted = isMuted;
    }
  }, [volume, isMuted]);
  (0, import_react45.useEffect)(() => {
    const video = videoRef.current;
    if (!video) return;
    const onPlay = () => setIsPlaying(true);
    const onPause = () => setIsPlaying(false);
    const onEnded = () => setIsPlaying(false);
    video.addEventListener("play", onPlay);
    video.addEventListener("pause", onPause);
    video.addEventListener("ended", onEnded);
    return () => {
      video.removeEventListener("play", onPlay);
      video.removeEventListener("pause", onPause);
      video.removeEventListener("ended", onEnded);
    };
  }, []);
  (0, import_react45.useEffect)(() => {
    const video = videoRef.current;
    if (!video) return;
    video.setAttribute("playsinline", "");
    video.setAttribute("webkit-playsinline", "");
  }, []);
  (0, import_react45.useEffect)(() => {
    if (isPlaying) {
      showControlsWithTimer();
    } else {
      clearControlsTimeout();
      if (isFullscreen) {
        setShowControls(true);
      } else {
        showControlsWithTimer();
      }
    }
  }, [isPlaying, isFullscreen, showControlsWithTimer, clearControlsTimeout]);
  (0, import_react45.useEffect)(() => {
    const video = videoRef.current;
    if (!video) return;
    const handleFullscreenChange = () => {
      const isCurrentlyFullscreen = !!document.fullscreenElement;
      setIsFullscreen(isCurrentlyFullscreen);
      if (isCurrentlyFullscreen) {
        showControlsWithTimer();
      }
    };
    const handleWebkitBeginFullscreen = () => {
      setIsFullscreen(true);
      showControlsWithTimer();
    };
    const handleWebkitEndFullscreen = () => {
      setIsFullscreen(false);
    };
    document.addEventListener("fullscreenchange", handleFullscreenChange);
    video.addEventListener(
      "webkitbeginfullscreen",
      handleWebkitBeginFullscreen
    );
    video.addEventListener("webkitendfullscreen", handleWebkitEndFullscreen);
    return () => {
      document.removeEventListener("fullscreenchange", handleFullscreenChange);
      video.removeEventListener(
        "webkitbeginfullscreen",
        handleWebkitBeginFullscreen
      );
      video.removeEventListener(
        "webkitendfullscreen",
        handleWebkitEndFullscreen
      );
    };
  }, [showControlsWithTimer]);
  (0, import_react45.useEffect)(() => {
    const init = () => {
      if (!isFullscreen) {
        showControlsWithTimer();
      }
    };
    let raf1 = 0, raf2 = 0, tid;
    if (globalThis.requestAnimationFrame === void 0) {
      tid = globalThis.setTimeout(init, INIT_DELAY);
      return () => {
        if (tid) clearTimeout(tid);
      };
    } else {
      raf1 = requestAnimationFrame(() => {
        raf2 = requestAnimationFrame(init);
      });
      return () => {
        cancelAnimationFrame(raf1);
        cancelAnimationFrame(raf2);
      };
    }
  }, []);
  const getInitialTime = (0, import_react45.useCallback)(() => {
    if (!autoSave || !storageKey) {
      return Number.isFinite(initialTime) && initialTime >= 0 ? initialTime : void 0;
    }
    const saved = Number(
      localStorage.getItem(`${storageKey}-${src}`) || Number.NaN
    );
    const hasValidInitial = Number.isFinite(initialTime) && initialTime >= 0;
    const hasValidSaved = Number.isFinite(saved) && saved >= 0;
    if (hasValidInitial) return initialTime;
    if (hasValidSaved) return saved;
    return void 0;
  }, [autoSave, storageKey, src, initialTime]);
  (0, import_react45.useEffect)(() => {
    const start = getInitialTime();
    if (start !== void 0 && videoRef.current) {
      videoRef.current.currentTime = start;
      setCurrentTime(start);
    }
  }, [getInitialTime]);
  const saveProgress = (0, import_react45.useCallback)(
    (time) => {
      if (!autoSave || !storageKey) return;
      const now = Date.now();
      if (now - lastSaveTimeRef.current > 5e3) {
        localStorage.setItem(`${storageKey}-${src}`, time.toString());
        lastSaveTimeRef.current = now;
      }
    },
    [autoSave, storageKey, src]
  );
  const togglePlayPause = (0, import_react45.useCallback)(async () => {
    const video = videoRef.current;
    if (!video) return;
    if (!video.paused) {
      video.pause();
      return;
    }
    try {
      await video.play();
    } catch {
    }
  }, []);
  const handleVolumeChange = (0, import_react45.useCallback)(
    (newVolume) => {
      const video = videoRef.current;
      if (!video) return;
      const volumeValue = newVolume / 100;
      video.volume = volumeValue;
      setVolume(volumeValue);
      const shouldMute = volumeValue === 0;
      const shouldUnmute = volumeValue > 0 && isMuted;
      if (shouldMute) {
        video.muted = true;
        setIsMuted(true);
      } else if (shouldUnmute) {
        video.muted = false;
        setIsMuted(false);
      }
    },
    [isMuted]
  );
  const toggleMute = (0, import_react45.useCallback)(() => {
    const video = videoRef.current;
    if (!video) return;
    if (isMuted) {
      const restoreVolume = volume > 0 ? volume : 0.5;
      video.volume = restoreVolume;
      video.muted = false;
      setVolume(restoreVolume);
      setIsMuted(false);
    } else {
      video.muted = true;
      setIsMuted(true);
    }
  }, [isMuted, volume]);
  const handleSeek = (0, import_react45.useCallback)((newTime) => {
    const video = videoRef.current;
    if (video) {
      video.currentTime = newTime;
    }
  }, []);
  const isSafariIOS = (0, import_react45.useCallback)(() => {
    const ua = navigator.userAgent;
    const isIOS = /iPad|iPhone|iPod/.test(ua);
    const isWebKit = /WebKit/.test(ua);
    const isNotChrome = !/CriOS|Chrome/.test(ua);
    return isIOS && isWebKit && isNotChrome;
  }, []);
  const toggleFullscreen = (0, import_react45.useCallback)(() => {
    const video = videoRef.current;
    const container = video?.parentElement;
    if (!video || !container) return;
    if (isSafariIOS()) {
      const videoElement = video;
      if (!isFullscreen && videoElement.webkitEnterFullscreen) {
        videoElement.webkitEnterFullscreen();
      } else if (isFullscreen && videoElement.webkitExitFullscreen) {
        videoElement.webkitExitFullscreen();
      }
    } else if (!isFullscreen && container.requestFullscreen) {
      container.requestFullscreen();
    } else if (isFullscreen && document.exitFullscreen) {
      document.exitFullscreen();
    }
  }, [isFullscreen, isSafariIOS]);
  const handleSpeedChange = (0, import_react45.useCallback)((speed) => {
    if (videoRef.current) {
      videoRef.current.playbackRate = speed;
      setPlaybackRate(speed);
      setShowSpeedMenu(false);
    }
  }, []);
  const toggleSpeedMenu = (0, import_react45.useCallback)(() => {
    setShowSpeedMenu(!showSpeedMenu);
  }, [showSpeedMenu]);
  const toggleCaptions = (0, import_react45.useCallback)(() => {
    if (!trackRef.current?.track || !subtitles || subtitlesValidation !== "valid")
      return;
    const newShowCaptions = !showCaptions;
    setShowCaptions(newShowCaptions);
    trackRef.current.track.mode = newShowCaptions ? "showing" : "hidden";
  }, [showCaptions, subtitles, subtitlesValidation]);
  const checkVideoCompletion = (0, import_react45.useCallback)(
    (progressPercent) => {
      if (progressPercent >= 95 && !hasCompleted) {
        setHasCompleted(true);
        onVideoComplete?.();
      }
    },
    [hasCompleted, onVideoComplete]
  );
  const handleTimeUpdate = (0, import_react45.useCallback)(() => {
    const video = videoRef.current;
    if (!video) return;
    const current = video.currentTime;
    setCurrentTime(current);
    saveProgress(current);
    onTimeUpdate?.(current);
    if (duration > 0) {
      const progressPercent = current / duration * 100;
      onProgress?.(progressPercent);
      checkVideoCompletion(progressPercent);
    }
  }, [duration, saveProgress, onTimeUpdate, onProgress, checkVideoCompletion]);
  const handleLoadedMetadata = (0, import_react45.useCallback)(() => {
    if (videoRef.current) {
      setDuration(videoRef.current.duration);
    }
  }, []);
  (0, import_react45.useEffect)(() => {
    const controller = new AbortController();
    const validateSubtitles = async () => {
      if (!subtitles) {
        setSubtitlesValidation("idle");
        return;
      }
      setSubtitlesValidation("validating");
      try {
        if (subtitles.startsWith("data:")) {
          setSubtitlesValidation("valid");
          return;
        }
        const response = await fetch(subtitles, {
          method: "HEAD",
          signal: controller.signal
        });
        if (response.ok) {
          const contentType = response.headers.get("content-type");
          const isValidType = !contentType || contentType.includes("text/vtt") || contentType.includes("text/plain") || contentType.includes("application/octet-stream");
          if (isValidType) {
            setSubtitlesValidation("valid");
          } else {
            setSubtitlesValidation("invalid");
            console.warn(
              `Subtitles URL has invalid content type: ${contentType}`
            );
          }
        } else {
          setSubtitlesValidation("invalid");
          console.warn(
            `Subtitles URL returned status: ${response.status} ${response.statusText}`
          );
        }
      } catch (error) {
        if (error instanceof Error && error.name === "AbortError") {
          return;
        }
        console.warn("Subtitles URL validation failed:", error);
        setSubtitlesValidation("invalid");
      }
    };
    validateSubtitles();
    return () => {
      controller.abort();
    };
  }, [subtitles]);
  (0, import_react45.useEffect)(() => {
    if (trackRef.current?.track) {
      trackRef.current.track.mode = showCaptions && subtitles && subtitlesValidation === "valid" ? "showing" : "hidden";
    }
  }, [subtitles, showCaptions, subtitlesValidation]);
  (0, import_react45.useEffect)(() => {
    const handleVisibilityChange = () => {
      if (document.hidden && isPlaying && videoRef.current) {
        videoRef.current.pause();
        setIsPlaying(false);
      }
    };
    const handleBlur = () => {
      if (isPlaying && videoRef.current) {
        videoRef.current.pause();
        setIsPlaying(false);
      }
    };
    document.addEventListener("visibilitychange", handleVisibilityChange);
    globalThis.addEventListener("blur", handleBlur);
    return () => {
      document.removeEventListener("visibilitychange", handleVisibilityChange);
      globalThis.removeEventListener("blur", handleBlur);
      clearControlsTimeout();
    };
  }, [isPlaying, clearControlsTimeout]);
  const progressPercentage = duration > 0 ? currentTime / duration * 100 : 0;
  const getIconSize2 = (0, import_react45.useCallback)(() => {
    if (isTinyMobile) return 18;
    if (isUltraSmallMobile) return 20;
    return 24;
  }, [isTinyMobile, isUltraSmallMobile]);
  const getControlsPadding = (0, import_react45.useCallback)(() => {
    if (isTinyMobile) return "px-2 pb-2 pt-1";
    if (isUltraSmallMobile) return "px-3 pb-3 pt-1";
    return "px-4 pb-4";
  }, [isTinyMobile, isUltraSmallMobile]);
  const getControlsGap = (0, import_react45.useCallback)(() => {
    if (isTinyMobile) return "gap-1";
    if (isUltraSmallMobile) return "gap-2";
    return "gap-4";
  }, [isTinyMobile, isUltraSmallMobile]);
  const getProgressBarPadding = (0, import_react45.useCallback)(() => {
    if (isTinyMobile) return "px-2 pb-1";
    if (isUltraSmallMobile) return "px-3 pb-1";
    return "px-4 pb-2";
  }, [isTinyMobile, isUltraSmallMobile]);
  const getCenterPlayButtonPosition = (0, import_react45.useCallback)(() => {
    if (isTinyMobile) return "items-center justify-center -translate-y-12";
    if (isUltraSmallMobile) return "items-center justify-center -translate-y-8";
    return "items-center justify-center";
  }, [isTinyMobile, isUltraSmallMobile]);
  const getTopControlsOpacity = (0, import_react45.useCallback)(() => {
    return showControls ? "opacity-100" : "opacity-0";
  }, [showControls]);
  const getBottomControlsOpacity = (0, import_react45.useCallback)(() => {
    return showControls ? "opacity-100" : "opacity-0";
  }, [showControls]);
  const seekBackward = (0, import_react45.useCallback)(() => {
    if (videoRef.current) {
      videoRef.current.currentTime -= 10;
    }
  }, []);
  const seekForward = (0, import_react45.useCallback)(() => {
    if (videoRef.current) {
      videoRef.current.currentTime += 10;
    }
  }, []);
  const increaseVolume = (0, import_react45.useCallback)(() => {
    handleVolumeChange(Math.min(100, volume * 100 + 10));
  }, [handleVolumeChange, volume]);
  const decreaseVolume = (0, import_react45.useCallback)(() => {
    handleVolumeChange(Math.max(0, volume * 100 - 10));
  }, [handleVolumeChange, volume]);
  const handleVideoKeyDown = (0, import_react45.useCallback)(
    (e) => {
      if (!e.key) return;
      e.stopPropagation();
      showControlsWithTimer();
      const keyHandlers = {
        " ": togglePlayPause,
        Enter: togglePlayPause,
        ArrowLeft: seekBackward,
        ArrowRight: seekForward,
        ArrowUp: increaseVolume,
        ArrowDown: decreaseVolume,
        m: toggleMute,
        M: toggleMute,
        f: toggleFullscreen,
        F: toggleFullscreen
      };
      const handler = keyHandlers[e.key];
      if (handler) {
        e.preventDefault();
        handler();
      }
    },
    [
      showControlsWithTimer,
      togglePlayPause,
      seekBackward,
      seekForward,
      increaseVolume,
      decreaseVolume,
      toggleMute,
      toggleFullscreen
    ]
  );
  const groupedSubTitleValid = subtitles && subtitlesValidation === "valid";
  return /* @__PURE__ */ (0, import_jsx_runtime70.jsxs)("div", { className: cn("flex flex-col", className), children: [
    (title || subtitleText) && /* @__PURE__ */ (0, import_jsx_runtime70.jsxs)("div", { className: "bg-subject-1 px-8 py-4 flex items-end justify-between min-h-20", children: [
      /* @__PURE__ */ (0, import_jsx_runtime70.jsxs)("div", { className: "flex flex-col gap-1", children: [
        title && /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(
          Text_default,
          {
            as: "h2",
            size: "lg",
            weight: "bold",
            color: "text-text-900",
            className: "leading-5 tracking-wide",
            children: title
          }
        ),
        subtitleText && /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(
          Text_default,
          {
            as: "p",
            size: "sm",
            weight: "normal",
            color: "text-text-600",
            className: "leading-5",
            children: subtitleText
          }
        )
      ] }),
      showDownloadButton && downloadContent && /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(
        DownloadButton_default,
        {
          content: downloadContent,
          lessonTitle: title,
          onDownloadStart,
          onDownloadComplete,
          onDownloadError,
          className: "flex-shrink-0"
        }
      )
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime70.jsxs)(
      "section",
      {
        className: cn(
          "relative w-full bg-background overflow-hidden group",
          "rounded-b-xl",
          // Hide cursor when controls are hidden and video is playing
          isPlaying && !showControls ? "cursor-none group-hover:cursor-default" : "cursor-default"
        ),
        "aria-label": title ? `Video player: ${title}` : "Video player",
        onMouseMove: handleMouseMove,
        onMouseEnter: handleMouseEnter,
        onTouchStart: handleMouseEnter,
        onMouseLeave: handleMouseLeave,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(
            "video",
            {
              ref: videoRef,
              src,
              poster,
              className: "w-full h-full object-contain analytica-video",
              controlsList: "nodownload",
              playsInline: true,
              onTimeUpdate: handleTimeUpdate,
              onLoadedMetadata: handleLoadedMetadata,
              onClick: togglePlayPause,
              onKeyDown: handleVideoKeyDown,
              tabIndex: 0,
              "aria-label": title ? `Video: ${title}` : "Video player",
              children: /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(
                "track",
                {
                  ref: trackRef,
                  kind: "captions",
                  src: groupedSubTitleValid ? subtitles : "data:text/vtt;charset=utf-8,WEBVTT",
                  srcLang: "pt-br",
                  label: groupedSubTitleValid ? "Legendas em Portugu\xEAs" : "Sem legendas dispon\xEDveis",
                  default: false
                }
              )
            }
          ),
          !isPlaying && /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(
            "div",
            {
              className: cn(
                "absolute inset-0 flex bg-black/30 transition-opacity",
                getCenterPlayButtonPosition()
              ),
              children: /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(
                IconButton_default,
                {
                  icon: /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(import_phosphor_react34.Play, { size: 32, weight: "regular", className: "ml-1" }),
                  onClick: togglePlayPause,
                  "aria-label": "Play video",
                  className: "!bg-transparent !text-white !w-auto !h-auto hover:!bg-transparent hover:!text-gray-200"
                }
              )
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(
            "div",
            {
              className: cn(
                "absolute top-0 left-0 right-0 p-4 bg-gradient-to-b from-black/70 to-transparent transition-opacity",
                getTopControlsOpacity()
              ),
              children: /* @__PURE__ */ (0, import_jsx_runtime70.jsx)("div", { className: "flex justify-start", children: /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(
                IconButton_default,
                {
                  icon: isFullscreen ? /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(import_phosphor_react34.ArrowsInSimple, { size: 24 }) : /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(import_phosphor_react34.ArrowsOutSimple, { size: 24 }),
                  onClick: toggleFullscreen,
                  "aria-label": isFullscreen ? "Exit fullscreen" : "Enter fullscreen",
                  className: "!bg-transparent !text-white hover:!bg-white/20"
                }
              ) })
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime70.jsxs)(
            "div",
            {
              className: cn(
                "absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/90 to-transparent transition-opacity",
                getBottomControlsOpacity()
              ),
              children: [
                /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(
                  ProgressBar2,
                  {
                    currentTime,
                    duration,
                    progressPercentage,
                    onSeek: handleSeek,
                    className: getProgressBarPadding()
                  }
                ),
                /* @__PURE__ */ (0, import_jsx_runtime70.jsxs)(
                  "div",
                  {
                    className: cn(
                      "flex items-center justify-between",
                      getControlsPadding()
                    ),
                    children: [
                      /* @__PURE__ */ (0, import_jsx_runtime70.jsxs)("div", { className: cn("flex items-center", getControlsGap()), children: [
                        /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(
                          IconButton_default,
                          {
                            icon: isPlaying ? /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(import_phosphor_react34.Pause, { size: getIconSize2() }) : /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(import_phosphor_react34.Play, { size: getIconSize2() }),
                            onClick: togglePlayPause,
                            "aria-label": isPlaying ? "Pause" : "Play",
                            className: "!bg-transparent !text-white hover:!bg-white/20"
                          }
                        ),
                        /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(
                          VolumeControls,
                          {
                            volume,
                            isMuted,
                            onVolumeChange: handleVolumeChange,
                            onToggleMute: toggleMute,
                            iconSize: getIconSize2(),
                            showSlider: !isUltraSmallMobile
                          }
                        ),
                        groupedSubTitleValid && /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(
                          IconButton_default,
                          {
                            icon: /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(import_phosphor_react34.ClosedCaptioning, { size: getIconSize2() }),
                            onClick: toggleCaptions,
                            "aria-label": showCaptions ? "Hide captions" : "Show captions",
                            className: cn(
                              "!bg-transparent hover:!bg-white/20",
                              showCaptions ? "!text-primary-400" : "!text-white"
                            )
                          }
                        ),
                        /* @__PURE__ */ (0, import_jsx_runtime70.jsxs)(Text_default, { size: "sm", weight: "medium", color: "text-white", children: [
                          formatTime2(currentTime),
                          " / ",
                          formatTime2(duration)
                        ] })
                      ] }),
                      /* @__PURE__ */ (0, import_jsx_runtime70.jsx)("div", { className: "flex items-center gap-4", children: /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(
                        SpeedMenu,
                        {
                          showSpeedMenu,
                          playbackRate,
                          onToggleMenu: toggleSpeedMenu,
                          onSpeedChange: handleSpeedChange,
                          iconSize: getIconSize2(),
                          isTinyMobile,
                          isFullscreen
                        }
                      ) })
                    ]
                  }
                )
              ]
            }
          )
        ]
      }
    )
  ] });
};
var VideoPlayer_default = VideoPlayer;

// src/components/Whiteboard/Whiteboard.tsx
var import_react46 = require("react");
var import_phosphor_react35 = require("phosphor-react");
var import_jsx_runtime71 = require("react/jsx-runtime");
var IMAGE_WIDTH = 225;
var IMAGE_HEIGHT = 90;
var Whiteboard = ({
  images,
  showDownload = true,
  className,
  onDownload,
  imagesPerRow = 2,
  ...rest
}) => {
  const [imageErrors, setImageErrors] = (0, import_react46.useState)(/* @__PURE__ */ new Set());
  const handleDownload = (0, import_react46.useCallback)(
    (image) => {
      if (onDownload) {
        onDownload(image);
      } else {
        const link = document.createElement("a");
        link.href = image.imageUrl;
        link.download = image.title || `whiteboard-${image.id}`;
        link.target = "_blank";
        link.rel = "noopener noreferrer";
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      }
    },
    [onDownload]
  );
  const handleImageError = (0, import_react46.useCallback)((imageId) => {
    setImageErrors((prev) => new Set(prev).add(imageId));
  }, []);
  const gridColsClass = images?.length === 1 ? "grid-cols-1" : {
    2: "grid-cols-1 sm:grid-cols-2",
    3: "grid-cols-1 sm:grid-cols-2 lg:grid-cols-3",
    4: "grid-cols-1 sm:grid-cols-2 lg:grid-cols-4"
  }[imagesPerRow];
  if (!images || images.length === 0) {
    return /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(
      "div",
      {
        className: cn(
          "flex items-center justify-center p-8 bg-background border border-border-50 rounded-xl",
          className
        ),
        ...rest,
        children: /* @__PURE__ */ (0, import_jsx_runtime71.jsx)("p", { className: "text-gray-400 text-sm", children: "Nenhuma imagem dispon\xEDvel" })
      }
    );
  }
  return /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(
    "div",
    {
      className: cn(
        "flex flex-col bg-background border border-border-50 p-4 gap-2 rounded-xl w-fit mx-auto",
        className
      ),
      ...rest,
      children: /* @__PURE__ */ (0, import_jsx_runtime71.jsx)("div", { className: cn("grid gap-4", gridColsClass), children: images.map((image) => /* @__PURE__ */ (0, import_jsx_runtime71.jsxs)(
        "div",
        {
          className: "relative group overflow-hidden bg-gray-100 rounded-lg",
          style: {
            width: `${IMAGE_WIDTH}px`
          },
          children: [
            /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(
              "div",
              {
                className: "relative",
                style: {
                  width: `${IMAGE_WIDTH}px`,
                  height: `${IMAGE_HEIGHT}px`
                },
                children: imageErrors.has(image.id) ? /* @__PURE__ */ (0, import_jsx_runtime71.jsx)("div", { className: "absolute inset-0 flex items-center justify-center bg-gray-200", children: /* @__PURE__ */ (0, import_jsx_runtime71.jsx)("p", { className: "text-gray-500 text-sm text-center px-2", children: "Imagem indispon\xEDvel" }) }) : /* @__PURE__ */ (0, import_jsx_runtime71.jsxs)(import_jsx_runtime71.Fragment, { children: [
                  /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(
                    "img",
                    {
                      src: image.imageUrl,
                      alt: image.title || `Whiteboard ${image.id}`,
                      className: "absolute inset-0 w-full h-full object-cover",
                      loading: "lazy",
                      onError: () => handleImageError(image.id)
                    }
                  ),
                  /* @__PURE__ */ (0, import_jsx_runtime71.jsx)("div", { className: "absolute inset-0 bg-gradient-to-t from-black/20 to-transparent" })
                ] })
              }
            ),
            showDownload && /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(
              "button",
              {
                type: "button",
                onClick: () => handleDownload(image),
                className: "cursor-pointer absolute bottom-3 right-3 flex items-center justify-center bg-black/20 backdrop-blur-sm rounded hover:bg-black/30 transition-colors duration-200 group/button w-6 h-6",
                "aria-label": `Download ${image.title || "imagem"}`,
                children: /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(
                  import_phosphor_react35.ArrowsOut,
                  {
                    size: 24,
                    weight: "regular",
                    className: "text-white group-hover/button:scale-110 transition-transform duration-200"
                  }
                )
              }
            )
          ]
        },
        image.id
      )) })
    }
  );
};
var Whiteboard_default = Whiteboard;

// src/components/Auth/Auth.tsx
var import_react47 = require("react");
var import_react_router_dom2 = require("react-router-dom");
var import_jsx_runtime72 = require("react/jsx-runtime");
var AuthContext = (0, import_react47.createContext)(void 0);
var AuthProvider = ({
  children,
  checkAuthFn,
  signOutFn,
  initialAuthState = {},
  getUserFn,
  getSessionFn,
  getTokensFn
}) => {
  const [authState, setAuthState] = (0, import_react47.useState)({
    isAuthenticated: false,
    isLoading: true,
    ...initialAuthState
  });
  const checkAuth = (0, import_react47.useCallback)(async () => {
    try {
      setAuthState((prev) => ({ ...prev, isLoading: true }));
      if (!checkAuthFn) {
        setAuthState((prev) => ({
          ...prev,
          isAuthenticated: false,
          isLoading: false
        }));
        return false;
      }
      const isAuth = await checkAuthFn();
      setAuthState((prev) => ({
        ...prev,
        isAuthenticated: isAuth,
        isLoading: false,
        user: getUserFn ? getUserFn() : prev.user,
        sessionInfo: getSessionFn ? getSessionFn() : prev.sessionInfo,
        tokens: getTokensFn ? getTokensFn() : prev.tokens
      }));
      return isAuth;
    } catch (error) {
      console.error("Erro ao verificar autentica\xE7\xE3o:", error);
      setAuthState((prev) => ({
        ...prev,
        isAuthenticated: false,
        isLoading: false
      }));
      return false;
    }
  }, [checkAuthFn, getUserFn, getSessionFn, getTokensFn]);
  const signOut = (0, import_react47.useCallback)(() => {
    if (signOutFn) {
      signOutFn();
    }
    setAuthState((prev) => ({
      ...prev,
      isAuthenticated: false,
      user: void 0,
      sessionInfo: void 0,
      tokens: void 0
    }));
  }, [signOutFn]);
  (0, import_react47.useEffect)(() => {
    checkAuth();
  }, [checkAuth]);
  const contextValue = (0, import_react47.useMemo)(
    () => ({
      ...authState,
      checkAuth,
      signOut
    }),
    [authState, checkAuth, signOut]
  );
  return /* @__PURE__ */ (0, import_jsx_runtime72.jsx)(AuthContext.Provider, { value: contextValue, children });
};
var useAuth = () => {
  const context = (0, import_react47.useContext)(AuthContext);
  if (context === void 0) {
    throw new Error("useAuth deve ser usado dentro de um AuthProvider");
  }
  return context;
};
var ProtectedRoute = ({
  children,
  redirectTo = "/",
  loadingComponent,
  additionalCheck
}) => {
  const { isAuthenticated, isLoading, ...authState } = useAuth();
  const defaultLoadingComponent = /* @__PURE__ */ (0, import_jsx_runtime72.jsx)("div", { className: "flex items-center justify-center min-h-screen", children: /* @__PURE__ */ (0, import_jsx_runtime72.jsx)("div", { className: "text-text-950 text-lg", children: "Carregando..." }) });
  if (isLoading) {
    return /* @__PURE__ */ (0, import_jsx_runtime72.jsx)(import_jsx_runtime72.Fragment, { children: loadingComponent || defaultLoadingComponent });
  }
  if (!isAuthenticated) {
    if (typeof window !== "undefined") {
      const rootDomain = getRootDomain();
      const currentLocation = `${window.location.protocol}//${window.location.hostname}${window.location.port ? ":" + window.location.port : ""}`;
      if (rootDomain !== currentLocation) {
        window.location.href = rootDomain;
        return null;
      }
    }
    return /* @__PURE__ */ (0, import_jsx_runtime72.jsx)(import_react_router_dom2.Navigate, { to: redirectTo, replace: true });
  }
  if (additionalCheck && !additionalCheck({ isAuthenticated, isLoading, ...authState })) {
    return /* @__PURE__ */ (0, import_jsx_runtime72.jsx)(import_react_router_dom2.Navigate, { to: redirectTo, replace: true });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime72.jsx)(import_jsx_runtime72.Fragment, { children });
};
var PublicRoute = ({
  children,
  redirectTo = "/painel",
  redirectIfAuthenticated = false,
  checkAuthBeforeRender = false
}) => {
  const { isAuthenticated, isLoading } = useAuth();
  if (checkAuthBeforeRender && isLoading) {
    return /* @__PURE__ */ (0, import_jsx_runtime72.jsx)("div", { className: "flex items-center justify-center min-h-screen", children: /* @__PURE__ */ (0, import_jsx_runtime72.jsx)("div", { className: "text-text-950 text-lg", children: "Carregando..." }) });
  }
  if (isAuthenticated && redirectIfAuthenticated) {
    return /* @__PURE__ */ (0, import_jsx_runtime72.jsx)(import_react_router_dom2.Navigate, { to: redirectTo, replace: true });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime72.jsx)(import_jsx_runtime72.Fragment, { children });
};
var withAuth = (Component, options = {}) => {
  return (props) => /* @__PURE__ */ (0, import_jsx_runtime72.jsx)(ProtectedRoute, { ...options, children: /* @__PURE__ */ (0, import_jsx_runtime72.jsx)(Component, { ...props }) });
};
var useAuthGuard = (options = {}) => {
  const authState = useAuth();
  const { requireAuth = true, customCheck } = options;
  const canAccess = !authState.isLoading && (requireAuth ? authState.isAuthenticated && (!customCheck || customCheck(authState)) : !authState.isAuthenticated || !customCheck || customCheck(authState));
  return {
    canAccess,
    isLoading: authState.isLoading,
    authState
  };
};
var useRouteAuth = (fallbackPath = "/") => {
  const { isAuthenticated, isLoading } = useAuth();
  const location = (0, import_react_router_dom2.useLocation)();
  const redirectToLogin = () => /* @__PURE__ */ (0, import_jsx_runtime72.jsx)(import_react_router_dom2.Navigate, { to: fallbackPath, state: { from: location }, replace: true });
  return {
    isAuthenticated,
    isLoading,
    redirectToLogin
  };
};
var getRootDomain = () => {
  const { hostname, protocol, port } = window.location;
  const portStr = port ? ":" + port : "";
  if (hostname === "localhost") {
    return `${protocol}//${hostname}${portStr}`;
  }
  const isIPv4 = /^\d{1,3}(?:\.\d{1,3}){3}$/.test(hostname);
  const isIPv6 = hostname.includes(":");
  if (isIPv4 || isIPv6) {
    return `${protocol}//${hostname}${portStr}`;
  }
  const parts = hostname.split(".");
  if (parts.length >= 3 && parts[parts.length - 2] === "com" && parts[parts.length - 1] === "br") {
    if (parts.length === 3) {
      return `${protocol}//${hostname}${portStr}`;
    }
    const base = parts.slice(-3).join(".");
    return `${protocol}//${base}${portStr}`;
  }
  if (parts.length > 2) {
    const base = parts.slice(-2).join(".");
    return `${protocol}//${base}${portStr}`;
  }
  return `${protocol}//${hostname}${portStr}`;
};

// src/components/Auth/zustandAuthAdapter.ts
function createZustandAuthAdapter(useAuthStore2) {
  return {
    /**
     * Check if the user is authenticated based on sessionInfo and tokens
     *
     * @returns {Promise<boolean>} Promise that resolves to authentication status
     */
    checkAuth: async () => {
      const { sessionInfo, tokens } = useAuthStore2.getState();
      return Boolean(sessionInfo && tokens);
    },
    /**
     * Get the current user from the store
     *
     * @returns {unknown} Current user data from the store
     */
    getUser: () => useAuthStore2.getState().user,
    /**
     * Get the current session information from the store
     *
     * @returns {unknown} Current session info from the store
     */
    getSessionInfo: () => useAuthStore2.getState().sessionInfo,
    /**
     * Get the current authentication tokens from the store
     *
     * @returns {unknown} Current tokens from the store
     */
    getTokens: () => useAuthStore2.getState().tokens,
    /**
     * Sign out the user by calling the store's signOut function if available
     *
     * @returns {void}
     */
    signOut: () => {
      const signOutFn = useAuthStore2.getState().signOut;
      if (typeof signOutFn === "function") signOutFn();
    }
  };
}

// src/components/Auth/useUrlAuthentication.ts
var import_react48 = require("react");
var import_react_router_dom3 = require("react-router-dom");
var getAuthParams = (location, extractParams) => {
  const searchParams = new URLSearchParams(location.search);
  return extractParams ? extractParams(searchParams) : {
    sessionId: searchParams.get("sessionId"),
    token: searchParams.get("token"),
    refreshToken: searchParams.get("refreshToken")
  };
};
var hasValidAuthParams = (authParams) => {
  return !!(authParams?.sessionId && authParams?.token && authParams?.refreshToken);
};
var hasValidProfileData = (data) => {
  return data !== null && typeof data === "object" && data !== void 0;
};
var handleProfileSelection = (responseData, setSelectedProfile) => {
  if (!setSelectedProfile) return;
  if (!hasValidProfileData(responseData)) return;
  const profileId = responseData.profileId;
  const isValidProfileId = profileId !== null && profileId !== void 0;
  if (isValidProfileId) {
    setSelectedProfile({
      id: profileId
    });
  }
};
var handleUserData = (responseData, setUser) => {
  if (!setUser) return;
  if (!hasValidProfileData(responseData)) return;
  const userId = responseData.userId;
  const userName = responseData.userName;
  const userEmail = responseData.userEmail;
  if (userId) {
    const userData = {
      id: userId
    };
    if (userName) {
      userData.name = userName;
    }
    if (userEmail) {
      userData.email = userEmail;
    }
    setUser(userData);
  }
};
function useUrlAuthentication(options) {
  const location = (0, import_react_router_dom3.useLocation)();
  const processedRef = (0, import_react48.useRef)(false);
  (0, import_react48.useEffect)(() => {
    const handleAuthentication = async () => {
      if (processedRef.current) {
        return;
      }
      const authParams = getAuthParams(location, options.extractParams);
      if (!hasValidAuthParams(authParams)) {
        return;
      }
      processedRef.current = true;
      try {
        options.setTokens({
          token: authParams.token,
          refreshToken: authParams.refreshToken
        });
        const maxRetries = options.maxRetries || 3;
        const retryDelay = options.retryDelay || 1e3;
        let retries = 0;
        let sessionData = null;
        while (retries < maxRetries && !sessionData) {
          try {
            const response = await options.api.get(options.endpoint, {
              headers: {
                Authorization: `Bearer ${authParams.token}`
              }
            });
            sessionData = response.data.data;
            break;
          } catch (error) {
            retries++;
            console.warn(
              `Tentativa ${retries}/${maxRetries} falhou para ${options.endpoint}:`,
              error
            );
            if (retries < maxRetries) {
              await new Promise(
                (resolve) => setTimeout(resolve, retryDelay * retries)
              );
            } else {
              throw error;
            }
          }
        }
        options.setSessionInfo(sessionData);
        handleProfileSelection(sessionData, options.setSelectedProfile);
        handleUserData(sessionData, options.setUser);
        options.clearParamsFromURL?.();
      } catch (error) {
        console.error("Erro ao obter informa\xE7\xF5es da sess\xE3o:", error);
        processedRef.current = false;
        options.onError?.(error);
      }
    };
    handleAuthentication();
  }, [
    location.search,
    options.setSessionInfo,
    options.setSelectedProfile,
    options.setUser,
    options.setTokens,
    options.api,
    options.endpoint,
    options.extractParams,
    options.clearParamsFromURL,
    options.maxRetries,
    options.retryDelay,
    options.onError
  ]);
}

// src/components/Auth/useApiConfig.ts
var import_react49 = require("react");
function useApiConfig(api) {
  return (0, import_react49.useMemo)(
    () => ({
      get: (endpoint, config) => api.get(endpoint, config)
    }),
    [api]
  );
}

// src/components/Quiz/Quiz.tsx
var import_phosphor_react38 = require("phosphor-react");
var import_react52 = require("react");

// src/components/Quiz/QuizContent.tsx
var import_react51 = require("react");

// src/components/MultipleChoice/MultipleChoice.tsx
var import_react50 = require("react");
var import_phosphor_react36 = require("phosphor-react");
var import_jsx_runtime73 = require("react/jsx-runtime");
var MultipleChoiceList = ({
  disabled = false,
  className = "",
  choices,
  name,
  selectedValues,
  onHandleSelectedValues,
  mode = "interactive"
}) => {
  const [actualValue, setActualValue] = (0, import_react50.useState)(selectedValues);
  (0, import_react50.useEffect)(() => {
    setActualValue(selectedValues);
  }, [selectedValues]);
  const getStatusBadge2 = (status) => {
    switch (status) {
      case "correct":
        return /* @__PURE__ */ (0, import_jsx_runtime73.jsx)(Badge_default, { variant: "solid", action: "success", iconLeft: /* @__PURE__ */ (0, import_jsx_runtime73.jsx)(import_phosphor_react36.CheckCircle, {}), children: "Resposta correta" });
      case "incorrect":
        return /* @__PURE__ */ (0, import_jsx_runtime73.jsx)(Badge_default, { variant: "solid", action: "error", iconLeft: /* @__PURE__ */ (0, import_jsx_runtime73.jsx)(import_phosphor_react36.XCircle, {}), children: "Resposta incorreta" });
      default:
        return null;
    }
  };
  const getStatusStyles2 = (status) => {
    switch (status) {
      case "correct":
        return "bg-success-background border-success-300";
      case "incorrect":
        return "bg-error-background border-error-300";
      default:
        return `bg-background border-border-100`;
    }
  };
  const renderVisualCheckbox = (isSelected, isDisabled) => {
    const checkboxClasses = cn(
      "w-5 h-5 rounded border-2 cursor-default transition-all duration-200 flex items-center justify-center",
      isSelected ? "border-primary-950 bg-primary-950 text-text" : "border-border-400 bg-background",
      isDisabled && "opacity-40 cursor-not-allowed"
    );
    return /* @__PURE__ */ (0, import_jsx_runtime73.jsx)("div", { className: checkboxClasses, children: isSelected && /* @__PURE__ */ (0, import_jsx_runtime73.jsx)(import_phosphor_react36.Check, { size: 16, weight: "bold" }) });
  };
  if (mode === "readonly") {
    return /* @__PURE__ */ (0, import_jsx_runtime73.jsx)("div", { className: cn("flex flex-col gap-2", className), children: choices.map((choice, i) => {
      const isSelected = actualValue?.includes(choice.value) || false;
      const statusStyles = getStatusStyles2(choice.status);
      const statusBadge = getStatusBadge2(choice.status);
      return /* @__PURE__ */ (0, import_jsx_runtime73.jsxs)(
        "div",
        {
          className: cn(
            "flex flex-row justify-between gap-2 items-start p-2 rounded-lg transition-all",
            statusStyles,
            choice.disabled ? "opacity-50 cursor-not-allowed" : ""
          ),
          children: [
            /* @__PURE__ */ (0, import_jsx_runtime73.jsxs)("div", { className: "flex items-center gap-2 flex-1", children: [
              renderVisualCheckbox(isSelected, choice.disabled || disabled),
              /* @__PURE__ */ (0, import_jsx_runtime73.jsx)(
                "span",
                {
                  className: cn(
                    "flex-1",
                    isSelected || choice.status && choice.status != "neutral" ? "text-text-950" : "text-text-600",
                    choice.disabled || disabled ? "cursor-not-allowed" : "cursor-default"
                  ),
                  children: choice.label
                }
              )
            ] }),
            statusBadge && /* @__PURE__ */ (0, import_jsx_runtime73.jsx)("div", { className: "flex-shrink-0", children: statusBadge })
          ]
        },
        `readonly-${choice.value}-${i}`
      );
    }) });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime73.jsx)(
    "div",
    {
      className: cn(
        "flex flex-row justify-between gap-2 items-start p-2 rounded-lg transition-all",
        disabled ? "opacity-50 cursor-not-allowed" : "",
        className
      ),
      children: /* @__PURE__ */ (0, import_jsx_runtime73.jsx)(
        CheckboxList_default,
        {
          name,
          values: actualValue,
          onValuesChange: (v) => {
            setActualValue(v);
            onHandleSelectedValues?.(v);
          },
          disabled,
          children: choices.map((choice, i) => /* @__PURE__ */ (0, import_jsx_runtime73.jsxs)(
            "div",
            {
              className: "flex flex-row gap-2 items-center",
              children: [
                /* @__PURE__ */ (0, import_jsx_runtime73.jsx)(
                  CheckboxListItem,
                  {
                    value: choice.value,
                    id: `interactive-${choice.value}-${i}`,
                    disabled: choice.disabled || disabled
                  }
                ),
                /* @__PURE__ */ (0, import_jsx_runtime73.jsx)(
                  "label",
                  {
                    htmlFor: `interactive-${choice.value}-${i}`,
                    className: cn(
                      "flex-1",
                      actualValue?.includes(choice.value) ? "text-text-950" : "text-text-600",
                      choice.disabled || disabled ? "cursor-not-allowed" : "cursor-pointer"
                    ),
                    children: choice.label
                  }
                )
              ]
            },
            `interactive-${choice.value}-${i}`
          ))
        }
      )
    }
  );
};

// src/components/Quiz/QuizContent.tsx
var import_phosphor_react37 = require("phosphor-react");

// src/assets/img/mock-image-question.png
var mock_image_question_default = "./mock-image-question-HEZCLFDL.png";

// src/components/Quiz/QuizContent.tsx
var import_jsx_runtime74 = require("react/jsx-runtime");
var getStatusBadge = (status) => {
  switch (status) {
    case "correct":
      return /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(Badge_default, { variant: "solid", action: "success", iconLeft: /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(import_phosphor_react37.CheckCircle, {}), children: "Resposta correta" });
    case "incorrect":
      return /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(Badge_default, { variant: "solid", action: "error", iconLeft: /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(import_phosphor_react37.XCircle, {}), children: "Resposta incorreta" });
    default:
      return null;
  }
};
var getStatusStyles = (variantCorrect) => {
  switch (variantCorrect) {
    case "correct":
      return "bg-success-background border-success-300";
    case "incorrect":
      return "bg-error-background border-error-300";
  }
};
var QuizSubTitle = (0, import_react51.forwardRef)(
  ({ subTitle, ...props }, ref) => {
    return /* @__PURE__ */ (0, import_jsx_runtime74.jsx)("div", { className: "px-4 pb-2 pt-6", ...props, ref, children: /* @__PURE__ */ (0, import_jsx_runtime74.jsx)("p", { className: "font-bold text-lg text-text-950", children: subTitle }) });
  }
);
var QuizContainer = (0, import_react51.forwardRef)(({ children, className, ...props }, ref) => {
  return /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(
    "div",
    {
      ref,
      className: cn(
        "bg-background rounded-t-xl px-4 pt-4 pb-[80px] h-auto flex flex-col gap-4 mb-auto",
        className
      ),
      ...props,
      children
    }
  );
});
var QuizAlternative = ({ paddingBottom }) => {
  const {
    getCurrentQuestion,
    selectAnswer,
    getQuestionResultByQuestionId,
    getCurrentAnswer,
    variant
  } = useQuizStore();
  const currentQuestion = getCurrentQuestion();
  const currentQuestionResult = getQuestionResultByQuestionId(
    currentQuestion?.id || ""
  );
  const currentAnswer = getCurrentAnswer();
  const alternatives = currentQuestion?.options?.map((option) => {
    let status = "neutral" /* NEUTRAL */;
    if (variant === "result") {
      const isCorrectOption = currentQuestionResult?.options?.find((op) => op.id === option.id)?.isCorrect || false;
      const isSelected = currentQuestionResult?.selectedOptions.some(
        (selectedOption) => selectedOption.optionId === option.id
      );
      const shouldShowCorrectAnswers = currentQuestionResult?.answerStatus !== "PENDENTE_AVALIACAO" /* PENDENTE_AVALIACAO */ && currentQuestionResult?.answerStatus !== "NAO_RESPONDIDO" /* NAO_RESPONDIDO */;
      if (shouldShowCorrectAnswers) {
        if (isCorrectOption) {
          status = "correct" /* CORRECT */;
        } else if (isSelected && !isCorrectOption) {
          status = "incorrect" /* INCORRECT */;
        } else {
          status = "neutral" /* NEUTRAL */;
        }
      } else {
        status = "neutral" /* NEUTRAL */;
      }
    }
    return {
      label: option.option,
      value: option.id,
      status
    };
  });
  if (!alternatives)
    return /* @__PURE__ */ (0, import_jsx_runtime74.jsx)("div", { children: /* @__PURE__ */ (0, import_jsx_runtime74.jsx)("p", { children: "N\xE3o h\xE1 Alternativas" }) });
  return /* @__PURE__ */ (0, import_jsx_runtime74.jsxs)(import_jsx_runtime74.Fragment, { children: [
    /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(QuizSubTitle, { subTitle: "Alternativas" }),
    /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(QuizContainer, { className: cn("", paddingBottom), children: /* @__PURE__ */ (0, import_jsx_runtime74.jsx)("div", { className: "space-y-4", children: /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(
      AlternativesList,
      {
        mode: variant === "default" ? "interactive" : "readonly",
        name: `question-${currentQuestion?.id || "1"}`,
        layout: "compact",
        alternatives,
        value: variant === "result" ? currentQuestionResult?.selectedOptions[0]?.optionId || "" : currentAnswer?.optionId || "",
        selectedValue: variant === "result" ? currentQuestionResult?.selectedOptions[0]?.optionId || "" : currentAnswer?.optionId || "",
        onValueChange: (value) => {
          if (currentQuestion) {
            selectAnswer(currentQuestion.id, value);
          }
        }
      },
      `question-${currentQuestion?.id || "1"}`
    ) }) })
  ] });
};
var QuizMultipleChoice = ({ paddingBottom }) => {
  const {
    getCurrentQuestion,
    selectMultipleAnswer,
    getAllCurrentAnswer,
    getQuestionResultByQuestionId,
    variant
  } = useQuizStore();
  const currentQuestion = getCurrentQuestion();
  const allCurrentAnswers = getAllCurrentAnswer();
  const currentQuestionResult = getQuestionResultByQuestionId(
    currentQuestion?.id || ""
  );
  const prevSelectedValuesRef = (0, import_react51.useRef)([]);
  const prevQuestionIdRef = (0, import_react51.useRef)("");
  const allCurrentAnswerIds = (0, import_react51.useMemo)(() => {
    return allCurrentAnswers?.map((answer) => answer.optionId) || [];
  }, [allCurrentAnswers]);
  const selectedValues = (0, import_react51.useMemo)(() => {
    return allCurrentAnswerIds?.filter((id) => id !== null) || [];
  }, [allCurrentAnswerIds]);
  const stableSelectedValues = (0, import_react51.useMemo)(() => {
    const currentQuestionId = currentQuestion?.id || "";
    const hasQuestionChanged = prevQuestionIdRef.current !== currentQuestionId;
    if (hasQuestionChanged) {
      prevQuestionIdRef.current = currentQuestionId;
      prevSelectedValuesRef.current = selectedValues;
      return selectedValues;
    }
    const hasValuesChanged = JSON.stringify(prevSelectedValuesRef.current) !== JSON.stringify(selectedValues);
    if (hasValuesChanged) {
      prevSelectedValuesRef.current = selectedValues;
      return selectedValues;
    }
    if (variant == "result") {
      return currentQuestionResult?.selectedOptions.map((op) => op.optionId) || [];
    } else {
      return prevSelectedValuesRef.current;
    }
  }, [
    selectedValues,
    currentQuestion?.id,
    variant,
    currentQuestionResult?.selectedOptions
  ]);
  const handleSelectedValues = (0, import_react51.useCallback)(
    (values) => {
      if (currentQuestion) {
        selectMultipleAnswer(currentQuestion.id, values);
      }
    },
    [currentQuestion, selectMultipleAnswer]
  );
  const questionKey = (0, import_react51.useMemo)(
    () => `question-${currentQuestion?.id || "1"}`,
    [currentQuestion?.id]
  );
  const choices = currentQuestion?.options?.map((option) => {
    let status = "neutral" /* NEUTRAL */;
    if (variant === "result") {
      const isCorrectOption = currentQuestionResult?.options?.find((op) => op.id === option.id)?.isCorrect || false;
      const isSelected = currentQuestionResult?.selectedOptions?.some(
        (op) => op.optionId === option.id
      );
      const shouldShowCorrectAnswers = currentQuestionResult?.answerStatus !== "PENDENTE_AVALIACAO" /* PENDENTE_AVALIACAO */ && currentQuestionResult?.answerStatus !== "NAO_RESPONDIDO" /* NAO_RESPONDIDO */;
      if (shouldShowCorrectAnswers) {
        if (isCorrectOption) {
          status = "correct" /* CORRECT */;
        } else if (isSelected && !isCorrectOption) {
          status = "incorrect" /* INCORRECT */;
        } else {
          status = "neutral" /* NEUTRAL */;
        }
      } else {
        status = "neutral" /* NEUTRAL */;
      }
    }
    return {
      label: option.option,
      value: option.id,
      status
    };
  });
  if (!choices)
    return /* @__PURE__ */ (0, import_jsx_runtime74.jsx)("div", { children: /* @__PURE__ */ (0, import_jsx_runtime74.jsx)("p", { children: "N\xE3o h\xE1 Escolhas Multiplas" }) });
  return /* @__PURE__ */ (0, import_jsx_runtime74.jsxs)(import_jsx_runtime74.Fragment, { children: [
    /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(QuizSubTitle, { subTitle: "Alternativas" }),
    /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(QuizContainer, { className: cn("", paddingBottom), children: /* @__PURE__ */ (0, import_jsx_runtime74.jsx)("div", { className: "space-y-4", children: /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(
      MultipleChoiceList,
      {
        choices,
        name: questionKey,
        selectedValues: stableSelectedValues,
        onHandleSelectedValues: handleSelectedValues,
        mode: variant === "default" ? "interactive" : "readonly"
      },
      questionKey
    ) }) })
  ] });
};
var QuizDissertative = ({ paddingBottom }) => {
  const {
    getCurrentQuestion,
    getCurrentAnswer,
    selectDissertativeAnswer,
    getQuestionResultByQuestionId,
    variant,
    getDissertativeCharLimit
  } = useQuizStore();
  const currentQuestion = getCurrentQuestion();
  const currentQuestionResult = getQuestionResultByQuestionId(
    currentQuestion?.id || ""
  );
  const currentAnswer = getCurrentAnswer();
  const textareaRef = (0, import_react51.useRef)(null);
  const charLimit = getDissertativeCharLimit();
  const handleAnswerChange = (value) => {
    if (currentQuestion) {
      selectDissertativeAnswer(currentQuestion.id, value);
    }
  };
  const adjustTextareaHeight = (0, import_react51.useCallback)(() => {
    if (textareaRef.current) {
      textareaRef.current.style.height = "auto";
      const scrollHeight = textareaRef.current.scrollHeight;
      const minHeight = 120;
      const maxHeight = 400;
      const newHeight = Math.min(Math.max(scrollHeight, minHeight), maxHeight);
      textareaRef.current.style.height = `${newHeight}px`;
    }
  }, []);
  (0, import_react51.useEffect)(() => {
    adjustTextareaHeight();
  }, [currentAnswer, adjustTextareaHeight]);
  if (!currentQuestion) {
    return /* @__PURE__ */ (0, import_jsx_runtime74.jsx)("div", { className: "space-y-4", children: /* @__PURE__ */ (0, import_jsx_runtime74.jsx)("p", { className: "text-text-600 text-md", children: "Nenhuma quest\xE3o dispon\xEDvel" }) });
  }
  const localAnswer = (variant == "result" ? currentQuestionResult?.answer : currentAnswer?.answer) || "";
  return /* @__PURE__ */ (0, import_jsx_runtime74.jsxs)(import_jsx_runtime74.Fragment, { children: [
    /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(QuizSubTitle, { subTitle: "Resposta" }),
    /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(QuizContainer, { className: cn(variant != "result" && paddingBottom), children: /* @__PURE__ */ (0, import_jsx_runtime74.jsx)("div", { className: "space-y-4 max-h-[600px] overflow-y-auto", children: variant === "default" ? /* @__PURE__ */ (0, import_jsx_runtime74.jsx)("div", { className: "space-y-4", children: /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(
      TextArea_default,
      {
        ref: textareaRef,
        placeholder: "Escreva sua resposta",
        value: localAnswer,
        onChange: (e) => handleAnswerChange(e.target.value),
        rows: 4,
        className: "min-h-[120px] max-h-[400px] resize-none overflow-y-auto",
        maxLength: charLimit,
        showCharacterCount: !!charLimit
      }
    ) }) : /* @__PURE__ */ (0, import_jsx_runtime74.jsx)("div", { className: "space-y-4", children: /* @__PURE__ */ (0, import_jsx_runtime74.jsx)("p", { className: "text-text-600 text-md whitespace-pre-wrap", children: localAnswer || "Nenhuma resposta fornecida" }) }) }) }),
    variant === "result" && currentQuestionResult?.answerStatus == "RESPOSTA_INCORRETA" /* RESPOSTA_INCORRETA */ && /* @__PURE__ */ (0, import_jsx_runtime74.jsxs)(import_jsx_runtime74.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(QuizSubTitle, { subTitle: "Observa\xE7\xE3o do professor" }),
      /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(QuizContainer, { className: cn("", paddingBottom), children: /* @__PURE__ */ (0, import_jsx_runtime74.jsx)("p", { className: "text-text-600 text-md whitespace-pre-wrap", children: currentQuestionResult?.teacherFeedback }) })
    ] })
  ] });
};
var QuizTrueOrFalse = ({ paddingBottom }) => {
  const { variant } = useQuizStore();
  const options = [
    {
      label: "25 metros",
      isCorrect: true
    },
    {
      label: "30 metros",
      isCorrect: false
    },
    {
      label: "40 metros",
      isCorrect: false
    },
    {
      label: "50 metros",
      isCorrect: false
    }
  ];
  const getLetterByIndex = (index) => String.fromCodePoint(97 + index);
  const isDefaultVariant = variant === "default";
  return /* @__PURE__ */ (0, import_jsx_runtime74.jsxs)(import_jsx_runtime74.Fragment, { children: [
    /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(QuizSubTitle, { subTitle: "Alternativas" }),
    /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(QuizContainer, { className: cn("", paddingBottom), children: /* @__PURE__ */ (0, import_jsx_runtime74.jsx)("div", { className: "flex flex-col gap-3.5", children: options.map((option, index) => {
      const variantCorrect = option.isCorrect ? "correct" : "incorrect";
      return /* @__PURE__ */ (0, import_jsx_runtime74.jsxs)(
        "section",
        {
          className: "flex flex-col gap-2",
          children: [
            /* @__PURE__ */ (0, import_jsx_runtime74.jsxs)(
              "div",
              {
                className: cn(
                  "flex flex-row justify-between items-center gap-2 p-2 rounded-md",
                  isDefaultVariant ? "" : getStatusStyles(variantCorrect)
                ),
                children: [
                  /* @__PURE__ */ (0, import_jsx_runtime74.jsx)("p", { className: "text-text-900 text-sm", children: getLetterByIndex(index).concat(") ").concat(option.label) }),
                  isDefaultVariant ? /* @__PURE__ */ (0, import_jsx_runtime74.jsxs)(Select_default, { size: "medium", children: [
                    /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(SelectTrigger, { className: "w-[180px]", children: /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(SelectValue, { placeholder: "Selecione opc\xE3o" }) }),
                    /* @__PURE__ */ (0, import_jsx_runtime74.jsxs)(SelectContent, { children: [
                      /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(SelectItem, { value: "V", children: "Verdadeiro" }),
                      /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(SelectItem, { value: "F", children: "Falso" })
                    ] })
                  ] }) : /* @__PURE__ */ (0, import_jsx_runtime74.jsx)("div", { className: "flex-shrink-0", children: getStatusBadge(variantCorrect) })
                ]
              }
            ),
            !isDefaultVariant && /* @__PURE__ */ (0, import_jsx_runtime74.jsxs)("span", { className: "flex flex-row gap-2 items-center", children: [
              /* @__PURE__ */ (0, import_jsx_runtime74.jsx)("p", { className: "text-text-800 text-2xs", children: "Resposta selecionada: V" }),
              !option.isCorrect && /* @__PURE__ */ (0, import_jsx_runtime74.jsx)("p", { className: "text-text-800 text-2xs", children: "Resposta correta: F" })
            ] })
          ]
        },
        option.label.concat(`-${index}`)
      );
    }) }) })
  ] });
};
var QuizConnectDots = ({ paddingBottom }) => {
  const { variant } = useQuizStore();
  const dotsOptions = [
    { label: "Ra\xE7\xE3o" },
    { label: "Rato" },
    { label: "Grama" },
    { label: "Peixe" }
  ];
  const options = [
    {
      label: "Cachorro",
      correctOption: "Ra\xE7\xE3o"
    },
    {
      label: "Gato",
      correctOption: "Rato"
    },
    {
      label: "Cabra",
      correctOption: "Grama"
    },
    {
      label: "Baleia",
      correctOption: "Peixe"
    }
  ];
  const mockUserAnswers = [
    {
      option: "Cachorro",
      dotOption: "Ra\xE7\xE3o",
      correctOption: "Ra\xE7\xE3o",
      isCorrect: true
    },
    {
      option: "Gato",
      dotOption: "Rato",
      correctOption: "Rato",
      isCorrect: true
    },
    {
      option: "Cabra",
      dotOption: "Peixe",
      correctOption: "Grama",
      isCorrect: false
    },
    {
      option: "Baleia",
      dotOption: "Grama",
      correctOption: "Peixe",
      isCorrect: false
    }
  ];
  const [userAnswers, setUserAnswers] = (0, import_react51.useState)(() => {
    if (variant === "result") {
      return mockUserAnswers;
    }
    return options.map((option) => ({
      option: option.label,
      dotOption: null,
      correctOption: option.correctOption,
      isCorrect: null
    }));
  });
  const handleSelectDot = (optionIndex, dotValue) => {
    setUserAnswers((prev) => {
      const next = [...prev];
      const { label: optionLabel, correctOption } = options[optionIndex];
      next[optionIndex] = {
        option: optionLabel,
        dotOption: dotValue,
        correctOption,
        isCorrect: dotValue ? dotValue === correctOption : null
      };
      return next;
    });
  };
  const getLetterByIndex = (index) => String.fromCodePoint(97 + index);
  const isDefaultVariant = variant === "default";
  const assignedDots = new Set(
    userAnswers.map((a) => a.dotOption).filter(Boolean)
  );
  return /* @__PURE__ */ (0, import_jsx_runtime74.jsxs)(import_jsx_runtime74.Fragment, { children: [
    /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(QuizSubTitle, { subTitle: "Alternativas" }),
    /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(QuizContainer, { className: cn("", paddingBottom), children: /* @__PURE__ */ (0, import_jsx_runtime74.jsx)("div", { className: "flex flex-col gap-3.5", children: options.map((option, index) => {
      const answer = userAnswers[index];
      const variantCorrect = answer.isCorrect ? "correct" : "incorrect";
      return /* @__PURE__ */ (0, import_jsx_runtime74.jsxs)("section", { className: "flex flex-col gap-2", children: [
        /* @__PURE__ */ (0, import_jsx_runtime74.jsxs)(
          "div",
          {
            className: cn(
              "flex flex-row justify-between items-center gap-2 p-2 rounded-md",
              isDefaultVariant ? "" : getStatusStyles(variantCorrect)
            ),
            children: [
              /* @__PURE__ */ (0, import_jsx_runtime74.jsx)("p", { className: "text-text-900 text-sm", children: getLetterByIndex(index) + ") " + option.label }),
              isDefaultVariant ? /* @__PURE__ */ (0, import_jsx_runtime74.jsxs)(
                Select_default,
                {
                  size: "medium",
                  value: answer.dotOption || void 0,
                  onValueChange: (value) => handleSelectDot(index, value),
                  children: [
                    /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(SelectTrigger, { className: "w-[180px]", children: /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(SelectValue, { placeholder: "Selecione op\xE7\xE3o" }) }),
                    /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(SelectContent, { children: dotsOptions.filter(
                      (dot) => !assignedDots.has(dot.label) || answer.dotOption === dot.label
                    ).map((dot) => /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(SelectItem, { value: dot.label, children: dot.label }, dot.label)) })
                  ]
                }
              ) : /* @__PURE__ */ (0, import_jsx_runtime74.jsx)("div", { className: "flex-shrink-0", children: answer.isCorrect === null ? null : getStatusBadge(variantCorrect) })
            ]
          }
        ),
        !isDefaultVariant && /* @__PURE__ */ (0, import_jsx_runtime74.jsxs)("span", { className: "flex flex-row gap-2 items-center", children: [
          /* @__PURE__ */ (0, import_jsx_runtime74.jsxs)("p", { className: "text-text-800 text-2xs", children: [
            "Resposta selecionada: ",
            answer.dotOption || "Nenhuma"
          ] }),
          !answer.isCorrect && /* @__PURE__ */ (0, import_jsx_runtime74.jsxs)("p", { className: "text-text-800 text-2xs", children: [
            "Resposta correta: ",
            answer.correctOption
          ] })
        ] })
      ] }, option.label);
    }) }) })
  ] });
};
var QuizFill = ({ paddingBottom }) => {
  const { variant } = useQuizStore();
  const options = [
    "ci\xEAncia",
    "disciplina",
    "\xE1rea",
    "especialidade",
    "varia\xE7\xF5es"
  ];
  const exampleText = `A meteorologia \xE9 a {{ciencia}} que estuda os fen\xF4menos atmosf\xE9ricos e suas {{varia\xE7\xF5es}}. Esta disciplina cient\xEDfica tem como objetivo principal {{objetivo}} o comportamento da atmosfera terrestre.

  Os meteorologistas utilizam diversos {{instrumentos}} para coletar dados atmosf\xE9ricos, incluindo term\xF4metros, bar\xF4metros e {{equipamentos}} modernos como radares meteorol\xF3gicos.`;
  const mockUserAnswers = [
    {
      selectId: "ciencia",
      userAnswer: "tecnologia",
      correctAnswer: "ci\xEAncia",
      isCorrect: false
    },
    {
      selectId: "varia\xE7\xF5es",
      userAnswer: "varia\xE7\xF5es",
      correctAnswer: "varia\xE7\xF5es",
      isCorrect: true
    },
    {
      selectId: "objetivo",
      userAnswer: "estudar",
      correctAnswer: "compreender",
      isCorrect: false
    },
    {
      selectId: "instrumentos",
      userAnswer: "ferramentas",
      correctAnswer: "instrumentos",
      isCorrect: false
    },
    {
      selectId: "equipamentos",
      userAnswer: "equipamentos",
      correctAnswer: "equipamentos",
      isCorrect: true
    }
  ];
  const [answers, setAnswers] = (0, import_react51.useState)({});
  const baseId = (0, import_react51.useId)();
  const getAvailableOptionsForSelect = (selectId) => {
    const usedOptions = new Set(
      Object.entries(answers).filter(([key]) => key !== selectId).map(([, value]) => value)
    );
    return options.filter((option) => !usedOptions.has(option));
  };
  const handleSelectChange = (selectId, value) => {
    const newAnswers = { ...answers, [selectId]: value };
    setAnswers(newAnswers);
  };
  const renderResolutionElement = (selectId) => {
    const mockAnswer = mockUserAnswers.find(
      (answer) => answer.selectId === selectId
    );
    return /* @__PURE__ */ (0, import_jsx_runtime74.jsx)("p", { className: "inline-flex mb-2.5 text-success-600 font-semibold text-md border-b-2 border-success-600", children: mockAnswer?.correctAnswer });
  };
  const renderDefaultElement = (selectId, startIndex, selectedValue, availableOptionsForThisSelect) => {
    return /* @__PURE__ */ (0, import_jsx_runtime74.jsxs)(
      Select_default,
      {
        value: selectedValue,
        onValueChange: (value) => handleSelectChange(selectId, value),
        className: "inline-flex mb-2.5",
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(SelectTrigger, { className: "inline-flex w-auto min-w-[140px] h-8 mx-1 bg-background border-gray-300", children: /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(SelectValue, { placeholder: "Selecione op\xE7\xE3o" }) }),
          /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(SelectContent, { children: availableOptionsForThisSelect.map((option, index) => /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(SelectItem, { value: option, children: option }, `${option}-${index}`)) })
        ]
      },
      `${selectId}-${startIndex}`
    );
  };
  const renderResultElement = (selectId) => {
    const mockAnswer = mockUserAnswers.find(
      (answer) => answer.selectId === selectId
    );
    if (!mockAnswer) return null;
    const action = mockAnswer.isCorrect ? "success" : "error";
    const icon = mockAnswer.isCorrect ? /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(import_phosphor_react37.CheckCircle, {}) : /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(import_phosphor_react37.XCircle, {});
    return /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(
      Badge_default,
      {
        variant: "solid",
        action,
        iconRight: icon,
        size: "large",
        className: "py-3 w-[180px] justify-between mb-2.5",
        children: /* @__PURE__ */ (0, import_jsx_runtime74.jsx)("span", { className: "text-text-900", children: mockAnswer.userAnswer })
      },
      selectId
    );
  };
  const renderTextWithSelects = (text, isResolution) => {
    const elements = [];
    let lastIndex = 0;
    let elementCounter = 0;
    const regex = /\{\{([\p{L}\p{M}\d_]+)\}\}/gu;
    let match;
    while ((match = regex.exec(text)) !== null) {
      const [fullMatch, selectId] = match;
      const startIndex = match.index;
      if (startIndex > lastIndex) {
        elements.push({
          element: text.slice(lastIndex, startIndex),
          id: `${baseId}-text-${++elementCounter}`
        });
      }
      const selectedValue = answers[selectId];
      const availableOptionsForThisSelect = getAvailableOptionsForSelect(selectId);
      if (isResolution) {
        elements.push({
          element: renderResolutionElement(selectId),
          id: `${baseId}-resolution-${++elementCounter}`
        });
      } else if (variant === "default") {
        elements.push({
          element: renderDefaultElement(
            selectId,
            startIndex,
            selectedValue,
            availableOptionsForThisSelect
          ),
          id: `${baseId}-select-${++elementCounter}`
        });
      } else {
        const resultElement = renderResultElement(selectId);
        if (resultElement) {
          elements.push({
            element: resultElement,
            id: `${baseId}-result-${++elementCounter}`
          });
        }
      }
      lastIndex = match.index + fullMatch.length;
    }
    if (lastIndex < text.length) {
      elements.push({
        element: text.slice(lastIndex),
        id: `${baseId}-text-${++elementCounter}`
      });
    }
    return elements;
  };
  return /* @__PURE__ */ (0, import_jsx_runtime74.jsxs)(import_jsx_runtime74.Fragment, { children: [
    /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(QuizSubTitle, { subTitle: "Alternativas" }),
    /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(QuizContainer, { className: "h-auto pb-0", children: /* @__PURE__ */ (0, import_jsx_runtime74.jsx)("div", { className: "space-y-6 px-4 h-auto", children: /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(
      "div",
      {
        className: cn(
          "text-lg text-text-900 leading-8 h-auto",
          variant != "result" && paddingBottom
        ),
        children: renderTextWithSelects(exampleText).map((element) => /* @__PURE__ */ (0, import_jsx_runtime74.jsx)("span", { children: element.element }, element.id))
      }
    ) }) }),
    variant === "result" && /* @__PURE__ */ (0, import_jsx_runtime74.jsxs)(import_jsx_runtime74.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(QuizSubTitle, { subTitle: "Resultado" }),
      /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(QuizContainer, { className: "h-auto pb-0", children: /* @__PURE__ */ (0, import_jsx_runtime74.jsx)("div", { className: "space-y-6 px-4", children: /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(
        "div",
        {
          className: cn("text-lg text-text-900 leading-8", paddingBottom),
          children: renderTextWithSelects(exampleText, true).map((element) => /* @__PURE__ */ (0, import_jsx_runtime74.jsx)("span", { children: element.element }, element.id))
        }
      ) }) })
    ] })
  ] });
};
var QuizImageQuestion = ({ paddingBottom }) => {
  const { variant } = useQuizStore();
  const correctPositionRelative = { x: 0.48, y: 0.45 };
  const calculateCorrectRadiusRelative = () => {
    const circleWidthRelative = 0.15;
    const circleHeightRelative = 0.3;
    const averageRadius = (circleWidthRelative + circleHeightRelative) / 4;
    const tolerance = 0.02;
    return averageRadius + tolerance;
  };
  const correctRadiusRelative = calculateCorrectRadiusRelative();
  const mockUserAnswerRelative = { x: 0.72, y: 0.348 };
  const [clickPositionRelative, setClickPositionRelative] = (0, import_react51.useState)(variant == "result" ? mockUserAnswerRelative : null);
  const convertToRelativeCoordinates = (x, y, rect) => {
    const safeWidth = Math.max(rect.width, 1e-3);
    const safeHeight = Math.max(rect.height, 1e-3);
    const xRelative = Math.max(0, Math.min(1, x / safeWidth));
    const yRelative = Math.max(0, Math.min(1, y / safeHeight));
    return { x: xRelative, y: yRelative };
  };
  const handleImageClick = (event) => {
    if (variant === "result") return;
    const rect = event.currentTarget.getBoundingClientRect();
    const x = event.clientX - rect.left;
    const y = event.clientY - rect.top;
    const positionRelative = convertToRelativeCoordinates(x, y, rect);
    setClickPositionRelative(positionRelative);
  };
  const handleKeyboardActivate = () => {
    if (variant === "result") return;
    setClickPositionRelative({ x: 0.5, y: 0.5 });
  };
  const isCorrect = () => {
    if (!clickPositionRelative) return false;
    const distance = Math.sqrt(
      Math.pow(clickPositionRelative.x - correctPositionRelative.x, 2) + Math.pow(clickPositionRelative.y - correctPositionRelative.y, 2)
    );
    return distance <= correctRadiusRelative;
  };
  const getUserCircleColorClasses = () => {
    if (variant === "default") {
      return "bg-indicator-primary/70 border-[#F8CC2E]";
    }
    if (variant === "result") {
      return isCorrect() ? "bg-success-600/70 border-white" : "bg-indicator-error/70 border-white";
    }
    return "bg-success-600/70 border-white";
  };
  return /* @__PURE__ */ (0, import_jsx_runtime74.jsxs)(import_jsx_runtime74.Fragment, { children: [
    /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(QuizSubTitle, { subTitle: "Clique na \xE1rea correta" }),
    /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(QuizContainer, { className: cn("", paddingBottom), children: /* @__PURE__ */ (0, import_jsx_runtime74.jsxs)(
      "div",
      {
        "data-testid": "quiz-image-container",
        className: "space-y-6 p-3 relative inline-block",
        children: [
          variant == "result" && /* @__PURE__ */ (0, import_jsx_runtime74.jsxs)(
            "div",
            {
              "data-testid": "quiz-legend",
              className: "flex items-center gap-4 text-xs",
              children: [
                /* @__PURE__ */ (0, import_jsx_runtime74.jsxs)("div", { className: "flex items-center gap-2", children: [
                  /* @__PURE__ */ (0, import_jsx_runtime74.jsx)("div", { className: "w-3 h-3 rounded-full bg-indicator-primary/70 border border-[#F8CC2E]" }),
                  /* @__PURE__ */ (0, import_jsx_runtime74.jsx)("span", { className: "text-text-600 font-medium text-sm", children: "\xC1rea correta" })
                ] }),
                /* @__PURE__ */ (0, import_jsx_runtime74.jsxs)("div", { className: "flex items-center gap-2", children: [
                  /* @__PURE__ */ (0, import_jsx_runtime74.jsx)("div", { className: "w-3 h-3 rounded-full bg-success-600/70 border border-white" }),
                  /* @__PURE__ */ (0, import_jsx_runtime74.jsx)("span", { className: "text-text-600 font-medium text-sm", children: "Resposta correta" })
                ] }),
                /* @__PURE__ */ (0, import_jsx_runtime74.jsxs)("div", { className: "flex items-center gap-2", children: [
                  /* @__PURE__ */ (0, import_jsx_runtime74.jsx)("div", { className: "w-3 h-3 rounded-full bg-indicator-error/70 border border-white" }),
                  /* @__PURE__ */ (0, import_jsx_runtime74.jsx)("span", { className: "text-text-600 font-medium text-sm", children: "Resposta incorreta" })
                ] })
              ]
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime74.jsxs)(
            "button",
            {
              "data-testid": "quiz-image-button",
              type: "button",
              className: "relative cursor-pointer w-full h-full border-0 bg-transparent p-0",
              onClick: handleImageClick,
              onKeyDown: (e) => {
                if (e.key === "Enter" || e.key === " ") {
                  e.preventDefault();
                  handleKeyboardActivate();
                }
              },
              "aria-label": "\xC1rea da imagem interativa",
              children: [
                /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(
                  "img",
                  {
                    "data-testid": "quiz-image",
                    src: mock_image_question_default,
                    alt: "Question",
                    className: "w-full h-auto rounded-md"
                  }
                ),
                variant === "result" && /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(
                  "div",
                  {
                    "data-testid": "quiz-correct-circle",
                    className: "absolute rounded-full bg-indicator-primary/70 border-4 border-[#F8CC2E] pointer-events-none",
                    style: {
                      minWidth: "50px",
                      maxWidth: "160px",
                      width: "15%",
                      aspectRatio: "1 / 1",
                      left: `calc(${correctPositionRelative.x * 100}% - 7.5%)`,
                      top: `calc(${correctPositionRelative.y * 100}% - 15%)`
                    }
                  }
                ),
                clickPositionRelative && /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(
                  "div",
                  {
                    "data-testid": "quiz-user-circle",
                    className: `absolute rounded-full border-4 pointer-events-none ${getUserCircleColorClasses()}`,
                    style: {
                      minWidth: "30px",
                      maxWidth: "52px",
                      width: "5%",
                      aspectRatio: "1 / 1",
                      left: `calc(${clickPositionRelative.x * 100}% - 2.5%)`,
                      top: `calc(${clickPositionRelative.y * 100}% - 2.5%)`
                    }
                  }
                )
              ]
            }
          )
        ]
      }
    ) })
  ] });
};

// src/components/Quiz/Quiz.tsx
var import_jsx_runtime75 = require("react/jsx-runtime");
var getQuizTypeConfig = (type) => {
  const QUIZ_TYPE_CONFIG = {
    ["SIMULADO" /* SIMULADO */]: {
      label: "Simulado",
      article: "o",
      preposition: "do"
    },
    ["QUESTIONARIO" /* QUESTIONARIO */]: {
      label: "Question\xE1rio",
      article: "o",
      preposition: "do"
    },
    ["ATIVIDADE" /* ATIVIDADE */]: {
      label: "Atividade",
      article: "a",
      preposition: "da"
    }
  };
  const config = QUIZ_TYPE_CONFIG[type];
  return config || QUIZ_TYPE_CONFIG["SIMULADO" /* SIMULADO */];
};
var getTypeLabel = (type) => {
  return getQuizTypeConfig(type).label;
};
var getCompletionTitle = (type) => {
  const config = getQuizTypeConfig(type);
  return `Voc\xEA concluiu ${config.article} ${config.label.toLowerCase()}!`;
};
var getExitConfirmationText = (type) => {
  const config = getQuizTypeConfig(type);
  return `Se voc\xEA sair ${config.preposition} ${config.label.toLowerCase()} agora, todas as respostas ser\xE3o perdidas.`;
};
var getFinishConfirmationText = (type) => {
  const config = getQuizTypeConfig(type);
  return `Tem certeza que deseja finalizar ${config.article} ${config.label.toLowerCase()}?`;
};
var Quiz = (0, import_react52.forwardRef)(({ children, className, variant = "default", ...props }, ref) => {
  const { setVariant } = useQuizStore();
  (0, import_react52.useEffect)(() => {
    setVariant(variant);
  }, [variant, setVariant]);
  return /* @__PURE__ */ (0, import_jsx_runtime75.jsx)("div", { ref, className: cn("flex flex-col", className), ...props, children });
});
var QuizTitle = (0, import_react52.forwardRef)(({ className, onBack, ...props }, ref) => {
  const {
    quiz,
    currentQuestionIndex,
    getTotalQuestions,
    getQuizTitle,
    timeElapsed,
    formatTime: formatTime3,
    isStarted
  } = useQuizStore();
  const [showExitConfirmation, setShowExitConfirmation] = (0, import_react52.useState)(false);
  const totalQuestions = getTotalQuestions();
  const quizTitle = getQuizTitle();
  const handleBackClick = () => {
    if (isStarted) {
      setShowExitConfirmation(true);
    } else {
      actionOnBack();
    }
  };
  const handleConfirmExit = () => {
    setShowExitConfirmation(false);
    actionOnBack();
  };
  const actionOnBack = () => {
    if (onBack) {
      onBack();
    } else {
      window.history.back();
    }
  };
  const handleCancelExit = () => {
    setShowExitConfirmation(false);
  };
  return /* @__PURE__ */ (0, import_jsx_runtime75.jsxs)(import_jsx_runtime75.Fragment, { children: [
    /* @__PURE__ */ (0, import_jsx_runtime75.jsxs)(
      "div",
      {
        ref,
        className: cn(
          "flex flex-row justify-between items-center relative p-2",
          className
        ),
        ...props,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(
            IconButton_default,
            {
              icon: /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(import_phosphor_react38.CaretLeft, { size: 24 }),
              size: "md",
              "aria-label": "Voltar",
              onClick: handleBackClick
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime75.jsxs)("span", { className: "flex flex-col gap-2 text-center", children: [
            /* @__PURE__ */ (0, import_jsx_runtime75.jsx)("p", { className: "text-text-950 font-bold text-md", children: quizTitle }),
            /* @__PURE__ */ (0, import_jsx_runtime75.jsx)("p", { className: "text-text-600 text-xs", children: totalQuestions > 0 ? `${currentQuestionIndex + 1} de ${totalQuestions}` : "0 de 0" })
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime75.jsx)("span", { className: "flex flex-row items-center justify-center", children: /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(Badge_default, { variant: "outlined", action: "info", iconLeft: /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(import_phosphor_react38.Clock, {}), children: isStarted ? formatTime3(timeElapsed) : "00:00" }) })
        ]
      }
    ),
    /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(
      AlertDialog,
      {
        isOpen: showExitConfirmation,
        onChangeOpen: setShowExitConfirmation,
        title: "Deseja sair?",
        description: getExitConfirmationText(quiz?.type || "SIMULADO" /* SIMULADO */),
        cancelButtonLabel: "Voltar e revisar",
        submitButtonLabel: "Sair Mesmo Assim",
        onSubmit: handleConfirmExit,
        onCancel: handleCancelExit
      }
    )
  ] });
});
var QuizHeader = () => {
  const { getCurrentQuestion, getQuestionIndex } = useQuizStore();
  const currentQuestion = getCurrentQuestion();
  let currentId = currentQuestion && "questionId" in currentQuestion ? currentQuestion.questionId : currentQuestion?.id;
  const questionIndex = getQuestionIndex(currentId);
  return /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(
    HeaderAlternative,
    {
      title: currentQuestion ? `Quest\xE3o ${questionIndex.toString().padStart(2, "0")}` : "Quest\xE3o",
      subTitle: currentQuestion?.knowledgeMatrix?.[0]?.topic?.name ?? "",
      content: currentQuestion?.statement ?? ""
    }
  );
};
var QuizContent = ({ paddingBottom }) => {
  const { getCurrentQuestion } = useQuizStore();
  const currentQuestion = getCurrentQuestion();
  const questionComponents = {
    ["ALTERNATIVA" /* ALTERNATIVA */]: QuizAlternative,
    ["MULTIPLA_ESCOLHA" /* MULTIPLA_ESCOLHA */]: QuizMultipleChoice,
    ["DISSERTATIVA" /* DISSERTATIVA */]: QuizDissertative,
    ["VERDADEIRO_FALSO" /* VERDADEIRO_FALSO */]: QuizTrueOrFalse,
    ["LIGAR_PONTOS" /* LIGAR_PONTOS */]: QuizConnectDots,
    ["PREENCHER" /* PREENCHER */]: QuizFill,
    ["IMAGEM" /* IMAGEM */]: QuizImageQuestion
  };
  const QuestionComponent = currentQuestion ? questionComponents[currentQuestion.questionType] : null;
  return QuestionComponent ? /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(QuestionComponent, { paddingBottom }) : null;
};
var QuizQuestionList = ({
  filterType = "all",
  onQuestionClick
} = {}) => {
  const {
    getQuestionsGroupedBySubject,
    goToQuestion,
    getQuestionStatusFromUserAnswers,
    getQuestionIndex
  } = useQuizStore();
  const groupedQuestions = getQuestionsGroupedBySubject();
  const getQuestionStatus = (questionId) => {
    return getQuestionStatusFromUserAnswers(questionId);
  };
  const filteredGroupedQuestions = Object.entries(groupedQuestions).reduce(
    (acc, [subjectId, questions]) => {
      const filteredQuestions = questions.filter((question) => {
        const status = getQuestionStatus(question.id);
        switch (filterType) {
          case "answered":
            return status === "answered";
          case "unanswered":
            return status === "unanswered" || status === "skipped";
          default:
            return true;
        }
      });
      if (filteredQuestions.length > 0) {
        acc[subjectId] = filteredQuestions;
      }
      return acc;
    },
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    {}
  );
  const getStatusLabel = (status) => {
    switch (status) {
      case "answered":
        return "Respondida";
      case "skipped":
        return "Em branco";
      default:
        return "Em branco";
    }
  };
  return /* @__PURE__ */ (0, import_jsx_runtime75.jsxs)("div", { className: "space-y-6 px-4 h-full", children: [
    Object.entries(filteredGroupedQuestions).length == 0 && /* @__PURE__ */ (0, import_jsx_runtime75.jsx)("div", { className: "flex items-center justify-center text-gray-500 py-8 h-full", children: /* @__PURE__ */ (0, import_jsx_runtime75.jsx)("p", { className: "text-lg", children: "Nenhum resultado" }) }),
    Object.entries(filteredGroupedQuestions).map(
      ([subjectId, questions]) => /* @__PURE__ */ (0, import_jsx_runtime75.jsxs)("section", { className: "flex flex-col gap-2", children: [
        /* @__PURE__ */ (0, import_jsx_runtime75.jsxs)("span", { className: "pt-6 pb-4 flex flex-row gap-2", children: [
          /* @__PURE__ */ (0, import_jsx_runtime75.jsx)("div", { className: "bg-primary-500 p-1 rounded-sm flex items-center justify-center", children: /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(import_phosphor_react38.BookOpen, { size: 17, className: "text-white" }) }),
          /* @__PURE__ */ (0, import_jsx_runtime75.jsx)("p", { className: "text-text-800 font-bold text-lg", children: questions?.[0]?.knowledgeMatrix?.[0]?.subject?.name ?? "Sem mat\xE9ria" })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime75.jsx)("ul", { className: "flex flex-col gap-2", children: questions.map((question) => {
          const status = getQuestionStatus(question.id);
          const questionNumber = getQuestionIndex(question.id);
          return /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(
            CardStatus,
            {
              header: `Quest\xE3o ${questionNumber.toString().padStart(2, "0")}`,
              label: getStatusLabel(status),
              onClick: () => {
                goToQuestion(questionNumber - 1);
                onQuestionClick?.();
              }
            },
            question.id
          );
        }) })
      ] }, subjectId)
    )
  ] });
};
var QuizFooter = (0, import_react52.forwardRef)(
  ({
    className,
    onGoToSimulated,
    onDetailResult,
    handleFinishSimulated,
    onGoToNextModule,
    onRepeat,
    onTryLater,
    resultImageComponent,
    resultIncorrectImageComponent,
    ...props
  }, ref) => {
    const {
      quiz,
      currentQuestionIndex,
      getTotalQuestions,
      goToNextQuestion,
      goToPreviousQuestion,
      getUnansweredQuestionsFromUserAnswers,
      getCurrentAnswer,
      skipQuestion,
      skipCurrentQuestionIfUnanswered,
      getCurrentQuestion,
      getQuestionStatusFromUserAnswers,
      variant,
      getQuestionResultStatistics
    } = useQuizStore();
    const totalQuestions = getTotalQuestions();
    const isFirstQuestion = currentQuestionIndex === 0;
    const isLastQuestion = currentQuestionIndex === totalQuestions - 1;
    const currentAnswer = getCurrentAnswer();
    const currentQuestion = getCurrentQuestion();
    const isCurrentQuestionSkipped = currentQuestion ? getQuestionStatusFromUserAnswers(currentQuestion.id) === "skipped" : false;
    const [activeModal, setActiveModal] = (0, import_react52.useState)(null);
    const [filterType, setFilterType] = (0, import_react52.useState)("all");
    const openModal = (modalName) => setActiveModal(modalName);
    const closeModal = () => setActiveModal(null);
    const isModalOpen = (modalName) => activeModal === modalName;
    const unansweredQuestions = getUnansweredQuestionsFromUserAnswers();
    const allQuestions = getTotalQuestions();
    const stats = getQuestionResultStatistics();
    const correctAnswers = stats?.correctAnswers;
    const totalAnswers = stats?.totalAnswered;
    const quizType = quiz?.type || "SIMULADO" /* SIMULADO */;
    const quizTypeLabel = getTypeLabel(quizType);
    const handleFinishQuiz = async () => {
      skipCurrentQuestionIfUnanswered();
      if (unansweredQuestions.length > 0) {
        openModal("alertDialog");
        return;
      }
      try {
        if (handleFinishSimulated) {
          await Promise.resolve(handleFinishSimulated());
        }
        if (quizType === "QUESTIONARIO" /* QUESTIONARIO */ && typeof correctAnswers === "number" && typeof totalAnswers === "number" && correctAnswers === totalAnswers) {
          openModal("modalQuestionnaireAllCorrect");
          return;
        }
        if (quizType === "QUESTIONARIO" /* QUESTIONARIO */ && typeof correctAnswers === "number" && correctAnswers === 0) {
          openModal("modalQuestionnaireAllIncorrect");
          return;
        }
        openModal("modalResult");
      } catch (err) {
        console.error("handleFinishSimulated failed:", err);
        return;
      }
    };
    const handleAlertSubmit = async () => {
      try {
        if (handleFinishSimulated) {
          await Promise.resolve(handleFinishSimulated());
        }
        if (quizType === "QUESTIONARIO" /* QUESTIONARIO */ && typeof correctAnswers === "number" && typeof totalAnswers === "number" && correctAnswers === totalAnswers) {
          openModal("modalQuestionnaireAllCorrect");
          return;
        }
        if (quizType === "QUESTIONARIO" /* QUESTIONARIO */ && typeof correctAnswers === "number" && correctAnswers === 0) {
          openModal("modalQuestionnaireAllIncorrect");
          return;
        }
        openModal("modalResult");
      } catch (err) {
        console.error("handleFinishSimulated failed:", err);
        closeModal();
        return;
      }
    };
    return /* @__PURE__ */ (0, import_jsx_runtime75.jsxs)(import_jsx_runtime75.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(
        "footer",
        {
          ref,
          className: cn(
            "w-full px-2 bg-background lg:max-w-[1000px] not-lg:max-w-[calc(100vw-32px)] border-t border-border-50 fixed bottom-0 min-h-[80px] flex flex-row justify-between items-center",
            className
          ),
          ...props,
          children: variant === "default" ? /* @__PURE__ */ (0, import_jsx_runtime75.jsxs)(import_jsx_runtime75.Fragment, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime75.jsxs)("div", { className: "flex flex-row items-center gap-1", children: [
              /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(
                IconButton_default,
                {
                  icon: /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(import_phosphor_react38.SquaresFour, { size: 24, className: "text-text-950" }),
                  size: "md",
                  onClick: () => openModal("modalNavigate")
                }
              ),
              isFirstQuestion ? /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(
                Button_default,
                {
                  variant: "outline",
                  size: "small",
                  onClick: () => {
                    skipQuestion();
                    goToNextQuestion();
                  },
                  children: "Pular"
                }
              ) : /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(
                Button_default,
                {
                  size: "medium",
                  variant: "link",
                  action: "primary",
                  iconLeft: /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(import_phosphor_react38.CaretLeft, { size: 18 }),
                  onClick: () => {
                    goToPreviousQuestion();
                  },
                  children: "Voltar"
                }
              )
            ] }),
            !isFirstQuestion && !isLastQuestion && /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(
              Button_default,
              {
                size: "small",
                variant: "outline",
                action: "primary",
                onClick: () => {
                  skipQuestion();
                  goToNextQuestion();
                },
                children: "Pular"
              }
            ),
            isLastQuestion ? /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(
              Button_default,
              {
                size: "medium",
                variant: "solid",
                action: "primary",
                onClick: handleFinishQuiz,
                children: "Finalizar"
              }
            ) : /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(
              Button_default,
              {
                size: "medium",
                variant: "link",
                action: "primary",
                iconRight: /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(import_phosphor_react38.CaretRight, { size: 18 }),
                disabled: !currentAnswer && !isCurrentQuestionSkipped,
                onClick: () => {
                  goToNextQuestion();
                },
                children: "Avan\xE7ar"
              }
            )
          ] }) : /* @__PURE__ */ (0, import_jsx_runtime75.jsx)("div", { className: "flex flex-row items-center justify-center w-full", children: /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(
            Button_default,
            {
              variant: "link",
              action: "primary",
              size: "medium",
              onClick: () => openModal("modalResolution"),
              children: "Ver resolu\xE7\xE3o"
            }
          ) })
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(
        AlertDialog,
        {
          isOpen: isModalOpen("alertDialog"),
          onChangeOpen: (open) => open ? openModal("alertDialog") : closeModal(),
          title: `Finalizar ${quizTypeLabel.toLowerCase()}?`,
          description: unansweredQuestions.length > 0 ? `Voc\xEA deixou as quest\xF5es ${unansweredQuestions.join(", ")} sem resposta. Finalizar agora pode impactar seu desempenho.` : getFinishConfirmationText(quizType),
          cancelButtonLabel: "Voltar e revisar",
          submitButtonLabel: "Finalizar Mesmo Assim",
          onSubmit: handleAlertSubmit
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(
        Modal_default,
        {
          isOpen: isModalOpen("modalResult"),
          onClose: closeModal,
          title: "",
          closeOnEscape: false,
          hideCloseButton: true,
          size: "md",
          children: /* @__PURE__ */ (0, import_jsx_runtime75.jsxs)("div", { className: "flex flex-col w-full h-full items-center justify-center gap-4", children: [
            resultImageComponent ? /* @__PURE__ */ (0, import_jsx_runtime75.jsx)("div", { className: "w-[282px] h-auto", children: resultImageComponent }) : /* @__PURE__ */ (0, import_jsx_runtime75.jsx)("div", { className: "w-[282px] h-[200px] bg-gray-100 rounded-md flex items-center justify-center", children: /* @__PURE__ */ (0, import_jsx_runtime75.jsx)("span", { className: "text-gray-500 text-sm", children: "Imagem de resultado" }) }),
            /* @__PURE__ */ (0, import_jsx_runtime75.jsxs)("div", { className: "flex flex-col gap-2 text-center", children: [
              /* @__PURE__ */ (0, import_jsx_runtime75.jsx)("h2", { className: "text-text-950 font-bold text-lg", children: getCompletionTitle(quizType) }),
              /* @__PURE__ */ (0, import_jsx_runtime75.jsxs)("p", { className: "text-text-500 font-sm", children: [
                "Voc\xEA acertou ",
                correctAnswers ?? "--",
                " de ",
                allQuestions,
                " ",
                "quest\xF5es."
              ] })
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime75.jsxs)("div", { className: "px-6 flex flex-row items-center gap-2 w-full", children: [
              /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(
                Button_default,
                {
                  variant: "outline",
                  className: "w-full",
                  size: "small",
                  onClick: onGoToSimulated,
                  children: quizTypeLabel === "Question\xE1rio" ? "Ir para aulas" : `Ir para ${quizTypeLabel.toLocaleLowerCase()}s`
                }
              ),
              /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(Button_default, { className: "w-full", onClick: onDetailResult, children: "Detalhar resultado" })
            ] })
          ] })
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(
        Modal_default,
        {
          isOpen: isModalOpen("modalNavigate"),
          onClose: closeModal,
          title: "Quest\xF5es",
          size: "lg",
          children: /* @__PURE__ */ (0, import_jsx_runtime75.jsxs)("div", { className: "flex flex-col w-full not-lg:h-[calc(100vh-200px)] lg:max-h-[687px] lg:h-[687px]", children: [
            /* @__PURE__ */ (0, import_jsx_runtime75.jsxs)("div", { className: "flex flex-row justify-between items-center py-6 pt-6 pb-4 border-b border-border-200 flex-shrink-0", children: [
              /* @__PURE__ */ (0, import_jsx_runtime75.jsx)("p", { className: "text-text-950 font-bold text-lg", children: "Filtrar por" }),
              /* @__PURE__ */ (0, import_jsx_runtime75.jsx)("span", { className: "max-w-[266px]", children: /* @__PURE__ */ (0, import_jsx_runtime75.jsxs)(Select_default, { value: filterType, onValueChange: setFilterType, children: [
                /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(
                  SelectTrigger,
                  {
                    variant: "rounded",
                    className: "max-w-[266px] min-w-[160px]",
                    children: /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(SelectValue, { placeholder: "Selecione uma op\xE7\xE3o" })
                  }
                ),
                /* @__PURE__ */ (0, import_jsx_runtime75.jsxs)(SelectContent, { children: [
                  /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(SelectItem, { value: "all", children: "Todas" }),
                  /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(SelectItem, { value: "unanswered", children: "Em branco" }),
                  /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(SelectItem, { value: "answered", children: "Respondidas" })
                ] })
              ] }) })
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime75.jsx)("div", { className: "flex flex-col gap-2 flex-1 min-h-0 overflow-y-auto", children: /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(
              QuizQuestionList,
              {
                filterType,
                onQuestionClick: closeModal
              }
            ) })
          ] })
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(
        Modal_default,
        {
          isOpen: isModalOpen("modalResolution"),
          onClose: closeModal,
          title: "Resolu\xE7\xE3o",
          size: "lg",
          children: currentQuestion?.solutionExplanation
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(
        Modal_default,
        {
          isOpen: isModalOpen("modalQuestionnaireAllCorrect"),
          onClose: closeModal,
          title: "",
          closeOnEscape: false,
          hideCloseButton: true,
          size: "md",
          children: /* @__PURE__ */ (0, import_jsx_runtime75.jsxs)("div", { className: "flex flex-col w-full h-full items-center justify-center gap-4", children: [
            resultImageComponent ? /* @__PURE__ */ (0, import_jsx_runtime75.jsx)("div", { className: "w-[282px] h-auto", children: resultImageComponent }) : /* @__PURE__ */ (0, import_jsx_runtime75.jsx)("div", { className: "w-[282px] h-[200px] bg-gray-100 rounded-md flex items-center justify-center", children: /* @__PURE__ */ (0, import_jsx_runtime75.jsx)("span", { className: "text-gray-500 text-sm", children: "Imagem de resultado" }) }),
            /* @__PURE__ */ (0, import_jsx_runtime75.jsxs)("div", { className: "flex flex-col gap-2 text-center", children: [
              /* @__PURE__ */ (0, import_jsx_runtime75.jsx)("h2", { className: "text-text-950 font-bold text-lg", children: "\u{1F389} Parab\xE9ns!" }),
              /* @__PURE__ */ (0, import_jsx_runtime75.jsx)("p", { className: "text-text-500 font-sm", children: "Voc\xEA concluiu o m\xF3dulo Movimento Uniforme." })
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime75.jsx)("div", { className: "px-6 flex flex-row items-center gap-2 w-full", children: /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(Button_default, { className: "w-full", onClick: onGoToNextModule, children: "Pr\xF3ximo m\xF3dulo" }) })
          ] })
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(
        Modal_default,
        {
          isOpen: isModalOpen("modalQuestionnaireAllIncorrect"),
          onClose: closeModal,
          title: "",
          closeOnEscape: false,
          hideCloseButton: true,
          size: "md",
          children: /* @__PURE__ */ (0, import_jsx_runtime75.jsxs)("div", { className: "flex flex-col w-full h-full items-center justify-center gap-4", children: [
            resultIncorrectImageComponent ? /* @__PURE__ */ (0, import_jsx_runtime75.jsx)("div", { className: "w-[282px] h-auto", children: resultIncorrectImageComponent }) : /* @__PURE__ */ (0, import_jsx_runtime75.jsx)("div", { className: "w-[282px] h-[200px] bg-gray-100 rounded-md flex items-center justify-center", children: /* @__PURE__ */ (0, import_jsx_runtime75.jsx)("span", { className: "text-gray-500 text-sm", children: "Imagem de resultado" }) }),
            /* @__PURE__ */ (0, import_jsx_runtime75.jsxs)("div", { className: "flex flex-col gap-2 text-center", children: [
              /* @__PURE__ */ (0, import_jsx_runtime75.jsx)("h2", { className: "text-text-950 font-bold text-lg", children: "\u{1F615} N\xE3o foi dessa vez..." }),
              /* @__PURE__ */ (0, import_jsx_runtime75.jsx)("p", { className: "text-text-500 font-sm", children: "Voc\xEA tirou 0 no question\xE1rio, mas n\xE3o se preocupe! Isso \xE9 apenas uma oportunidade de aprendizado." }),
              /* @__PURE__ */ (0, import_jsx_runtime75.jsx)("p", { className: "text-text-500 font-sm", children: "Que tal tentar novamente para melhorar sua nota? Estamos aqui para te ajudar a entender o conte\xFAdo e evoluir." }),
              /* @__PURE__ */ (0, import_jsx_runtime75.jsx)("p", { className: "text-text-500 font-sm", children: "Clique em Repetir Question\xE1rio e mostre do que voc\xEA \xE9 capaz! \u{1F4AA}" })
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime75.jsxs)("div", { className: "flex flex-row justify-center items-center gap-2 w-full", children: [
              /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(
                Button_default,
                {
                  type: "button",
                  variant: "link",
                  size: "small",
                  className: "w-auto",
                  onClick: () => {
                    closeModal();
                    openModal("alertDialogTryLater");
                  },
                  children: "Tentar depois"
                }
              ),
              /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(
                Button_default,
                {
                  variant: "outline",
                  size: "small",
                  className: "w-auto",
                  onClick: onDetailResult,
                  children: "Detalhar resultado"
                }
              ),
              /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(
                Button_default,
                {
                  className: "w-auto",
                  size: "small",
                  onClick: onGoToNextModule,
                  children: "Pr\xF3ximo m\xF3dulo"
                }
              )
            ] })
          ] })
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(
        AlertDialog,
        {
          isOpen: isModalOpen("alertDialogTryLater"),
          onChangeOpen: (open) => open ? openModal("alertDialogTryLater") : closeModal(),
          title: "Tentar depois?",
          description: "Voc\xEA optou por refazer o question\xE1rio mais tarde.\n\nLembre-se: enquanto n\xE3o refazer o question\xE1rio, sua nota permanecer\xE1 0 no sistema.",
          cancelButtonLabel: "Repetir question\xE1rio",
          submitButtonLabel: "Tentar depois",
          onSubmit: () => {
            onTryLater?.();
            closeModal();
          },
          onCancel: () => {
            onRepeat?.();
            closeModal();
          }
        }
      )
    ] });
  }
);

// src/components/Quiz/QuizResult.tsx
var import_react53 = require("react");
var import_phosphor_react39 = require("phosphor-react");
var import_jsx_runtime76 = require("react/jsx-runtime");
var QuizBadge = ({
  subtype
}) => {
  switch (subtype) {
    case "PROVA" /* PROVA */:
      return /* @__PURE__ */ (0, import_jsx_runtime76.jsx)(Badge_default, { variant: "examsOutlined", action: "exam2", "data-testid": "quiz-badge", children: "Prova" });
    case "ENEM_PROVA_1" /* ENEM_PROVA_1 */:
    case "ENEM_PROVA_2" /* ENEM_PROVA_2 */:
      return /* @__PURE__ */ (0, import_jsx_runtime76.jsx)(Badge_default, { variant: "examsOutlined", action: "exam1", "data-testid": "quiz-badge", children: "Enem" });
    case "VESTIBULAR" /* VESTIBULAR */:
      return /* @__PURE__ */ (0, import_jsx_runtime76.jsx)(Badge_default, { variant: "examsOutlined", action: "exam4", "data-testid": "quiz-badge", children: "Vestibular" });
    case "SIMULADO" /* SIMULADO */:
    case "SIMULADAO" /* SIMULADAO */:
    case void 0:
      return /* @__PURE__ */ (0, import_jsx_runtime76.jsx)(Badge_default, { variant: "examsOutlined", action: "exam3", "data-testid": "quiz-badge", children: "Simulad\xE3o" });
    default:
      return /* @__PURE__ */ (0, import_jsx_runtime76.jsx)(Badge_default, { variant: "solid", action: "info", "data-testid": "quiz-badge", children: subtype });
  }
};
var QuizHeaderResult = (0, import_react53.forwardRef)(
  ({ className, ...props }, ref) => {
    const {
      getQuestionResultByQuestionId,
      getCurrentQuestion,
      questionsResult
    } = useQuizStore();
    const [status, setStatus] = (0, import_react53.useState)(void 0);
    (0, import_react53.useEffect)(() => {
      const cq = getCurrentQuestion();
      if (!cq) {
        setStatus(void 0);
        return;
      }
      const qr = getQuestionResultByQuestionId(cq.id);
      setStatus(qr?.answerStatus);
    }, [
      getCurrentQuestion,
      getQuestionResultByQuestionId,
      getCurrentQuestion()?.id,
      questionsResult
    ]);
    const getClassesByAnswersStatus = () => {
      if (status === void 0) {
        return "bg-gray-100";
      }
      switch (status) {
        case "RESPOSTA_CORRETA" /* RESPOSTA_CORRETA */:
          return "bg-success-background";
        case "RESPOSTA_INCORRETA" /* RESPOSTA_INCORRETA */:
          return "bg-error-background";
        case "PENDENTE_AVALIACAO" /* PENDENTE_AVALIACAO */:
          return "bg-info-background";
        default:
          return "bg-error-background";
      }
    };
    const getLabelByAnswersStatus = () => {
      if (status === void 0) {
        return "Carregando...";
      }
      switch (status) {
        case "RESPOSTA_CORRETA" /* RESPOSTA_CORRETA */:
          return "\u{1F389} Parab\xE9ns!!";
        case "RESPOSTA_INCORRETA" /* RESPOSTA_INCORRETA */:
          return "N\xE3o foi dessa vez...";
        case "PENDENTE_AVALIACAO" /* PENDENTE_AVALIACAO */:
          return "Avalia\xE7\xE3o pendente";
        case "NAO_RESPONDIDO" /* NAO_RESPONDIDO */:
          return "N\xE3o foi dessa vez...voc\xEA deixou a resposta em branco";
        default:
          return "N\xE3o foi dessa vez...voc\xEA deixou a resposta em branco";
      }
    };
    return /* @__PURE__ */ (0, import_jsx_runtime76.jsxs)(
      "div",
      {
        ref,
        className: cn(
          "flex flex-row items-center gap-10 p-3.5 rounded-xl mb-4",
          getClassesByAnswersStatus(),
          className
        ),
        ...props,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime76.jsx)("p", { className: "text-text-950 font-bold text-lg", children: "Resultado" }),
          /* @__PURE__ */ (0, import_jsx_runtime76.jsx)("p", { className: "text-text-700 text-md", children: getLabelByAnswersStatus() })
        ]
      }
    );
  }
);
var QuizResultHeaderTitle = (0, import_react53.forwardRef)(({ className, showBadge = true, onRepeat, canRetry, ...props }, ref) => {
  const { quiz } = useQuizStore();
  return /* @__PURE__ */ (0, import_jsx_runtime76.jsxs)(
    "div",
    {
      ref,
      className: cn(
        "flex flex-row pt-4 justify-between items-center",
        className
      ),
      ...props,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime76.jsx)("p", { className: "text-text-950 font-bold text-2xl", children: "Resultado" }),
        /* @__PURE__ */ (0, import_jsx_runtime76.jsxs)("div", { className: "flex flex-row gap-3 items-center", children: [
          canRetry && onRepeat && /* @__PURE__ */ (0, import_jsx_runtime76.jsx)(
            Button_default,
            {
              variant: "solid",
              action: "primary",
              size: "medium",
              onClick: onRepeat,
              children: "Repetir question\xE1rio"
            }
          ),
          showBadge && /* @__PURE__ */ (0, import_jsx_runtime76.jsx)(QuizBadge, { subtype: quiz?.subtype || void 0 })
        ] })
      ]
    }
  );
});
var QuizResultTitle = (0, import_react53.forwardRef)(({ className, ...props }, ref) => {
  const { getQuizTitle } = useQuizStore();
  const quizTitle = getQuizTitle();
  return /* @__PURE__ */ (0, import_jsx_runtime76.jsx)(
    "p",
    {
      className: cn("pt-6 pb-4 text-text-950 font-bold text-lg", className),
      ref,
      ...props,
      children: quizTitle
    }
  );
});
var updateDifficultyStats = (stats, difficulty, isCorrect) => {
  if (difficulty === "FACIL" /* FACIL */) {
    stats.totalEasyQuestions++;
    if (isCorrect) stats.correctEasyAnswers++;
  } else if (difficulty === "MEDIO" /* MEDIO */) {
    stats.totalMediumQuestions++;
    if (isCorrect) stats.correctMediumAnswers++;
  } else if (difficulty === "DIFICIL" /* DIFICIL */) {
    stats.totalDifficultQuestions++;
    if (isCorrect) stats.correctDifficultAnswers++;
  }
};
var calculateAnswerStatistics = (answers) => {
  const stats = {
    correctAnswers: 0,
    correctEasyAnswers: 0,
    correctMediumAnswers: 0,
    correctDifficultAnswers: 0,
    totalEasyQuestions: 0,
    totalMediumQuestions: 0,
    totalDifficultQuestions: 0
  };
  for (const answer of answers) {
    const isCorrect = answer.answerStatus === "RESPOSTA_CORRETA" /* RESPOSTA_CORRETA */;
    if (isCorrect) {
      stats.correctAnswers++;
    }
    updateDifficultyStats(stats, answer.difficultyLevel, isCorrect);
  }
  return stats;
};
var QuizResultPerformance = (0, import_react53.forwardRef)(({ showDetails = true, ...props }, ref) => {
  const {
    getTotalQuestions,
    formatTime: formatTime3,
    getQuestionResultStatistics,
    getQuestionResult
  } = useQuizStore();
  const totalQuestions = getTotalQuestions();
  const questionResult = getQuestionResult();
  const stats = questionResult ? calculateAnswerStatistics(questionResult.answers) : {
    correctAnswers: 0,
    correctEasyAnswers: 0,
    correctMediumAnswers: 0,
    correctDifficultAnswers: 0,
    totalEasyQuestions: 0,
    totalMediumQuestions: 0,
    totalDifficultQuestions: 0
  };
  const percentage = totalQuestions > 0 ? Math.round(stats.correctAnswers / totalQuestions * 100) : 0;
  const classesJustifyBetween = showDetails ? "justify-between" : "justify-center";
  return /* @__PURE__ */ (0, import_jsx_runtime76.jsxs)(
    "div",
    {
      className: cn(
        "flex flex-row gap-6 p-6 rounded-xl bg-background",
        classesJustifyBetween
      ),
      ref,
      ...props,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime76.jsxs)("div", { className: "relative", children: [
          /* @__PURE__ */ (0, import_jsx_runtime76.jsx)(
            ProgressCircle_default,
            {
              size: "medium",
              variant: "green",
              value: percentage,
              showPercentage: false,
              label: ""
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime76.jsxs)("div", { className: "absolute inset-0 flex flex-col items-center justify-center", children: [
            showDetails && /* @__PURE__ */ (0, import_jsx_runtime76.jsxs)("div", { className: "flex items-center gap-1 mb-1", children: [
              /* @__PURE__ */ (0, import_jsx_runtime76.jsx)(import_phosphor_react39.Clock, { size: 12, weight: "regular", className: "text-text-800" }),
              /* @__PURE__ */ (0, import_jsx_runtime76.jsx)("span", { className: "text-2xs font-medium text-text-800", children: formatTime3(
                (getQuestionResultStatistics()?.timeSpent ?? 0) * 60
              ) })
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime76.jsxs)("div", { className: "text-2xl font-medium text-text-800 leading-7", children: [
              getQuestionResultStatistics()?.correctAnswers ?? "--",
              " de",
              " ",
              totalQuestions
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime76.jsx)("div", { className: "text-2xs font-medium text-text-600 mt-1", children: "Corretas" })
          ] })
        ] }),
        showDetails && /* @__PURE__ */ (0, import_jsx_runtime76.jsxs)("div", { className: "flex flex-col gap-4 w-full", children: [
          /* @__PURE__ */ (0, import_jsx_runtime76.jsx)(
            ProgressBar_default,
            {
              className: "w-full",
              layout: "stacked",
              variant: "green",
              value: stats.correctEasyAnswers,
              max: stats.totalEasyQuestions,
              label: "F\xE1ceis",
              showHitCount: true,
              labelClassName: "text-base font-medium text-text-800 leading-none",
              percentageClassName: "text-xs font-medium leading-[14px] text-right"
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime76.jsx)(
            ProgressBar_default,
            {
              className: "w-full",
              layout: "stacked",
              variant: "green",
              value: stats.correctMediumAnswers,
              max: stats.totalMediumQuestions,
              label: "M\xE9dias",
              showHitCount: true,
              labelClassName: "text-base font-medium text-text-800 leading-none",
              percentageClassName: "text-xs font-medium leading-[14px] text-right"
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime76.jsx)(
            ProgressBar_default,
            {
              className: "w-full",
              layout: "stacked",
              variant: "green",
              value: stats.correctDifficultAnswers,
              max: stats.totalDifficultQuestions,
              label: "Dif\xEDceis",
              showHitCount: true,
              labelClassName: "text-base font-medium text-text-800 leading-none",
              percentageClassName: "text-xs font-medium leading-[14px] text-right"
            }
          )
        ] })
      ]
    }
  );
});
var QuizListResult = (0, import_react53.forwardRef)(({ className, onSubjectClick, ...props }, ref) => {
  const { getQuestionsGroupedBySubject } = useQuizStore();
  const { isDark } = useTheme();
  const groupedQuestions = getQuestionsGroupedBySubject();
  const subjectsStats = Object.entries(groupedQuestions).map(
    ([subjectId, questions]) => {
      let correct = 0;
      let incorrect = 0;
      for (const question of questions) {
        if (question.answerStatus === "RESPOSTA_CORRETA" /* RESPOSTA_CORRETA */) {
          correct++;
        } else {
          incorrect++;
        }
      }
      return {
        subject: {
          name: questions?.[0]?.knowledgeMatrix?.[0]?.subject?.name ?? "Sem mat\xE9ria",
          id: subjectId,
          color: questions?.[0]?.knowledgeMatrix?.[0]?.subject?.color ?? "",
          icon: questions?.[0]?.knowledgeMatrix?.[0]?.subject?.icon ?? ""
        },
        correct,
        incorrect,
        total: questions.length
      };
    }
  );
  return /* @__PURE__ */ (0, import_jsx_runtime76.jsxs)("section", { ref, className, ...props, children: [
    /* @__PURE__ */ (0, import_jsx_runtime76.jsx)("p", { className: "pt-6 pb-4 text-text-950 font-bold text-lg", children: "Mat\xE9rias" }),
    /* @__PURE__ */ (0, import_jsx_runtime76.jsx)("ul", { className: "flex flex-col gap-2", children: subjectsStats.map((subject) => /* @__PURE__ */ (0, import_jsx_runtime76.jsx)("li", { children: /* @__PURE__ */ (0, import_jsx_runtime76.jsx)(
      CardResults,
      {
        onClick: () => onSubjectClick?.(subject.subject.id),
        className: "max-w-full",
        header: subject.subject.name,
        correct_answers: subject.correct,
        incorrect_answers: subject.incorrect,
        icon: subject.subject.icon || "Book",
        color: getSubjectColorWithOpacity(subject.subject.color, isDark) || void 0,
        direction: "row"
      }
    ) }, subject.subject.id)) })
  ] });
});
var QuizListResultByMateria = ({
  subject,
  onQuestionClick,
  subjectName
}) => {
  const { getQuestionsGroupedBySubject, getQuestionIndex } = useQuizStore();
  const groupedQuestions = getQuestionsGroupedBySubject();
  const answeredQuestions = groupedQuestions[subject] || [];
  const formattedQuestions = subject == "all" ? Object.values(groupedQuestions).flat() : answeredQuestions;
  return /* @__PURE__ */ (0, import_jsx_runtime76.jsxs)("div", { className: "flex flex-col", children: [
    /* @__PURE__ */ (0, import_jsx_runtime76.jsx)("div", { className: "flex flex-row pt-4 justify-between", children: /* @__PURE__ */ (0, import_jsx_runtime76.jsx)("p", { className: "text-text-950 font-bold text-2xl", children: subjectName || formattedQuestions?.[0]?.knowledgeMatrix?.[0]?.subject?.name || "Sem mat\xE9ria" }) }),
    /* @__PURE__ */ (0, import_jsx_runtime76.jsxs)("section", { className: "flex flex-col ", children: [
      /* @__PURE__ */ (0, import_jsx_runtime76.jsx)("p", { className: "pt-6 pb-4 text-text-950 font-bold text-lg", children: "Resultado das quest\xF5es" }),
      /* @__PURE__ */ (0, import_jsx_runtime76.jsx)("ul", { className: "flex flex-col gap-2 pt-4", children: formattedQuestions.map((question) => {
        const questionIndex = getQuestionIndex(
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          question.questionId ?? question.id
        );
        return /* @__PURE__ */ (0, import_jsx_runtime76.jsx)("li", { children: /* @__PURE__ */ (0, import_jsx_runtime76.jsx)(
          CardStatus,
          {
            className: "max-w-full",
            header: `Quest\xE3o ${questionIndex.toString().padStart(2, "0")}`,
            status: (() => {
              if (question.answerStatus === "RESPOSTA_CORRETA" /* RESPOSTA_CORRETA */)
                return "correct";
              if (question.answerStatus === "RESPOSTA_INCORRETA" /* RESPOSTA_INCORRETA */)
                return "incorrect";
              if (question.answerStatus === "NAO_RESPONDIDO" /* NAO_RESPONDIDO */)
                return "unanswered";
              if (question.answerStatus === "PENDENTE_AVALIACAO" /* PENDENTE_AVALIACAO */)
                return "pending";
              return void 0;
            })(),
            onClick: () => onQuestionClick?.(question)
          }
        ) }, question.id);
      }) })
    ] })
  ] });
};

// src/components/BreadcrumbMenu/BreadcrumbMenu.tsx
var import_react_router_dom4 = require("react-router-dom");
var import_jsx_runtime77 = require("react/jsx-runtime");
var BreadcrumbMenu = ({
  breadcrumbs,
  onBreadcrumbClick,
  className = "!px-0 py-4 flex-wrap w-full"
}) => {
  const navigate = (0, import_react_router_dom4.useNavigate)();
  const handleClick = (breadcrumb, index) => {
    if (onBreadcrumbClick) {
      onBreadcrumbClick(breadcrumb, index);
    }
    navigate(breadcrumb.url);
  };
  return /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(
    Menu,
    {
      value: `breadcrumb-${breadcrumbs.length - 1}`,
      defaultValue: "breadcrumb-0",
      variant: "breadcrumb",
      className,
      children: /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(MenuContent, { className: "w-full flex flex-row flex-wrap gap-2 !px-0", children: breadcrumbs.map((breadcrumb, index) => {
        const isLast = index === breadcrumbs.length - 1;
        const hasSeparator = !isLast;
        return /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(
          MenuItem,
          {
            variant: "breadcrumb",
            value: `breadcrumb-${index}`,
            className: "!p-0 whitespace-nowrap",
            onClick: () => handleClick(breadcrumb, index),
            separator: hasSeparator,
            children: breadcrumb.name
          },
          breadcrumb.id
        );
      }) })
    }
  );
};

// src/components/BreadcrumbMenu/useBreadcrumbBuilder.ts
var import_react54 = require("react");

// src/components/BreadcrumbMenu/breadcrumbStore.ts
var import_zustand12 = require("zustand");
var useBreadcrumbStore = (0, import_zustand12.create)((set, get) => ({
  breadcrumbs: {},
  setBreadcrumbs: (namespace, items) => {
    set((state) => ({
      breadcrumbs: {
        ...state.breadcrumbs,
        [namespace]: items
      }
    }));
  },
  addBreadcrumb: (namespace, item) => {
    set((state) => {
      const current = state.breadcrumbs[namespace] || [];
      return {
        breadcrumbs: {
          ...state.breadcrumbs,
          [namespace]: [...current, item]
        }
      };
    });
  },
  updateBreadcrumb: (namespace, itemId, updates) => {
    set((state) => {
      const current = state.breadcrumbs[namespace] || [];
      return {
        breadcrumbs: {
          ...state.breadcrumbs,
          [namespace]: current.map(
            (item) => item.id === itemId ? { ...item, ...updates } : item
          )
        }
      };
    });
  },
  removeBreadcrumbFrom: (namespace, itemId) => {
    set((state) => {
      const current = state.breadcrumbs[namespace] || [];
      const index = current.findIndex((item) => item.id === itemId);
      if (index === -1) return state;
      return {
        breadcrumbs: {
          ...state.breadcrumbs,
          [namespace]: current.slice(0, index)
        }
      };
    });
  },
  sliceBreadcrumbs: (namespace, index) => {
    set((state) => {
      const current = state.breadcrumbs[namespace] || [];
      return {
        breadcrumbs: {
          ...state.breadcrumbs,
          [namespace]: current.slice(0, index + 1)
        }
      };
    });
  },
  clearBreadcrumbs: (namespace) => {
    set((state) => {
      const { [namespace]: _, ...rest } = state.breadcrumbs;
      return {
        breadcrumbs: rest
      };
    });
  },
  getBreadcrumbs: (namespace) => {
    return get().breadcrumbs[namespace] || [];
  }
}));
var useBreadcrumb = (namespace) => {
  const store = useBreadcrumbStore();
  const breadcrumbs = store.breadcrumbs[namespace] || [];
  return {
    breadcrumbs,
    /**
     * Define todos os breadcrumbs de uma vez
     */
    setBreadcrumbs: (items) => {
      store.setBreadcrumbs(namespace, items);
    },
    /**
     * Adiciona um novo breadcrumb ao final
     */
    addBreadcrumb: (item) => {
      store.addBreadcrumb(namespace, item);
    },
    /**
     * Atualiza um breadcrumb existente
     */
    updateBreadcrumb: (itemId, updates) => {
      store.updateBreadcrumb(namespace, itemId, updates);
    },
    /**
     * Remove um breadcrumb e todos os seguintes
     */
    removeBreadcrumbFrom: (itemId) => {
      store.removeBreadcrumbFrom(namespace, itemId);
    },
    /**
     * Mantém apenas os breadcrumbs até o índice especificado (inclusivo)
     */
    sliceBreadcrumbs: (index) => {
      store.sliceBreadcrumbs(namespace, index);
    },
    /**
     * Limpa todos os breadcrumbs
     */
    clearBreadcrumbs: () => {
      store.clearBreadcrumbs(namespace);
    }
  };
};

// src/components/BreadcrumbMenu/useBreadcrumbBuilder.ts
var isBreadcrumbWithData = (level) => {
  return "data" in level;
};
var useBreadcrumbBuilder = (config) => {
  const { namespace, root, levels } = config;
  const { breadcrumbs, setBreadcrumbs, sliceBreadcrumbs } = useBreadcrumb(namespace);
  const levelDependencies = levels.map(
    (level) => isBreadcrumbWithData(level) ? level.data : null
  );
  const levelUrlIds = levels.map((level) => level.urlId);
  (0, import_react54.useEffect)(() => {
    const newBreadcrumbs = [root];
    const previousIds = [];
    for (const level of levels) {
      const { urlId } = level;
      if (isBreadcrumbWithData(level)) {
        const { data, getId, getName, getUrl } = level;
        if (!data) break;
        const dataId = getId(data);
        if (urlId === void 0 || dataId !== urlId) break;
        newBreadcrumbs.push({
          id: dataId,
          name: getName(data),
          url: getUrl(data, previousIds)
        });
        previousIds.push(dataId);
      } else {
        const { breadcrumb } = level;
        if (urlId === void 0) break;
        newBreadcrumbs.push(breadcrumb);
        previousIds.push(breadcrumb.id);
      }
    }
    setBreadcrumbs(newBreadcrumbs);
  }, [namespace, ...levelDependencies, ...levelUrlIds, root.id]);
  return {
    breadcrumbs,
    sliceBreadcrumbs
  };
};

// src/components/BreadcrumbMenu/useUrlParams.ts
var import_react55 = require("react");
var import_react_router_dom5 = require("react-router-dom");
var useUrlParams = (config) => {
  const location = (0, import_react_router_dom5.useLocation)();
  return (0, import_react55.useMemo)(() => {
    const segments = location.pathname.split("/").filter(Boolean);
    const params = {};
    for (const [key, index] of Object.entries(config)) {
      params[key] = segments[index];
    }
    return params;
  }, [location.pathname, config]);
};

// src/hooks/useAppInitialization.ts
var import_react57 = require("react");

// src/hooks/useInstitution.ts
var import_react56 = require("react");
function useInstitutionId() {
  const [institutionId, setInstitutionId] = (0, import_react56.useState)(() => {
    return document.querySelector('meta[name="institution-id"]')?.getAttribute("content") ?? null;
  });
  (0, import_react56.useEffect)(() => {
    const metaTag = document.querySelector('meta[name="institution-id"]');
    if (!metaTag) return;
    const observer = new MutationObserver(() => {
      const newValue = metaTag.getAttribute("content");
      setInstitutionId(newValue);
    });
    observer.observe(metaTag, {
      attributes: true,
      attributeFilter: ["content"]
    });
    return () => observer.disconnect();
  }, []);
  return institutionId;
}

// src/store/appStore.ts
var import_zustand13 = require("zustand");
var import_middleware4 = require("zustand/middleware");
var useAppStore = (0, import_zustand13.create)()(
  (0, import_middleware4.persist)(
    (set, get) => ({
      institutionId: null,
      initialized: false,
      /**
       * Set the institution ID
       * @param {string | null} institutionId - The institution ID from meta tag
       * @returns {void}
       */
      setInstitutionId: (institutionId) => {
        set({ institutionId });
      },
      /**
       * Set the initialized state
       * @param {boolean} initialized - Whether the app has been initialized
       * @returns {void}
       */
      setInitialized: (initialized) => {
        set({ initialized });
      },
      /**
       * Initialize the app by reading the institution ID from meta tag
       * @returns {void}
       */
      initialize: (id) => {
        const { initialized } = get();
        if (initialized) {
          return;
        }
        set({
          institutionId: id,
          initialized: true
        });
      }
    }),
    {
      name: "@app-storage:analytica:v2" /* APP_STORAGE */,
      storage: (0, import_middleware4.createJSONStorage)(() => localStorage)
    }
  )
);

// src/store/authStore.ts
var import_zustand14 = require("zustand");
var import_middleware5 = require("zustand/middleware");
var useAuthStore = (0, import_zustand14.create)()(
  (0, import_middleware5.persist)(
    (set, get) => ({
      user: null,
      tokens: null,
      isAuthenticated: false,
      profiles: [],
      selectedProfile: null,
      sessionInfo: null,
      /**
       * Set the current user
       * @param {User | null} user - The user object or null to clear
       * @returns {void}
       */
      setUser: (user) => {
        set({ user, isAuthenticated: !!user });
      },
      /**
       * Set the authentication tokens
       * @param {AuthTokens | null} tokens - The authentication tokens or null to clear
       * @returns {void}
       */
      setTokens: (tokens) => {
        set({ tokens });
      },
      /**
       * Set user profiles
       * @param {UserProfile[]} profiles - Array of user profiles
       * @returns {void}
       */
      setProfiles: (profiles) => {
        set({ profiles });
      },
      /**
       * Set the selected profile
       * @param {UserProfile | null} profile - The selected profile or null to clear
       * @returns {void}
       */
      setSelectedProfile: (profile) => {
        set({ selectedProfile: profile });
      },
      /**
       * Set the session info
       * @param {SessionInfo | null} sessionInfo - The session info or null to clear
       * @returns {void}
       */
      setSessionInfo: (sessionInfo) => {
        set({ sessionInfo });
      },
      /**
       * Sign in user with complete auth data
       * @param {User} user - The user object
       * @param {AuthTokens} tokens - The authentication tokens
       * @param {UserProfile[]} profiles - Array of user profiles
       * @returns {void}
       */
      signIn: (user, tokens, profiles) => {
        set({
          user,
          tokens,
          profiles,
          isAuthenticated: true
        });
      },
      /**
       * Sign out user and clear all auth data
       * @returns {void}
       */
      signOut: () => {
        set({
          user: null,
          tokens: null,
          isAuthenticated: false,
          profiles: [],
          selectedProfile: null,
          sessionInfo: null
        });
      },
      /**
       * Update user session data (after login completion)
       * @param {Partial<User>} sessionData - Partial user data to update
       * @returns {void}
       */
      updateUserSession: (sessionData) => {
        const { user } = get();
        if (user) {
          const updatedUser = { ...user, ...sessionData };
          set({ user: updatedUser });
        }
      }
    }),
    {
      name: "@auth-storage:analytica:v2" /* AUTH_STORAGE */,
      storage: (0, import_middleware5.createJSONStorage)(() => localStorage)
    }
  )
);

// src/hooks/useAppInitialization.ts
function useAppInitialization() {
  const getInstitutionId = useInstitutionId();
  const { initialize, initialized, institutionId } = useAppStore();
  const authFunctions = (0, import_react57.useMemo)(
    () => ({
      checkAuth: async () => {
        const { sessionInfo, tokens } = useAuthStore.getState();
        return Boolean(sessionInfo && tokens);
      },
      signOut: () => {
        const { signOut } = useAuthStore.getState();
        signOut();
      },
      getUser: () => {
        const { user } = useAuthStore.getState();
        return user;
      },
      getSessionInfo: () => {
        const { sessionInfo } = useAuthStore.getState();
        return sessionInfo;
      },
      getTokens: () => {
        const { tokens } = useAuthStore.getState();
        return tokens;
      }
    }),
    []
  );
  return {
    // Estado da inicialização
    getInstitutionId,
    initialize,
    initialized,
    institutionId,
    // Funções de autenticação
    authFunctions
  };
}

// src/hooks/useAppContent.ts
var import_react58 = require("react");
var import_react_router_dom6 = require("react-router-dom");
function useAppContent(config) {
  const navigate = (0, import_react_router_dom6.useNavigate)();
  const { setTokens, setSessionInfo, setSelectedProfile } = useAuthStore();
  const {
    api,
    getInstitutionId,
    initialize,
    initialized,
    endpoint = "/auth/session-info",
    maxRetries = 1,
    retryDelay = 2e3,
    onClearParamsFromURL,
    onError,
    onNotFoundNavigation
  } = config;
  const apiConfig = useApiConfig(api);
  useTheme();
  const handleNotFoundNavigation = () => {
    if (onNotFoundNavigation) {
      onNotFoundNavigation();
    } else {
      navigate("/painel");
    }
  };
  const handleSetSelectedProfile = (0, import_react58.useCallback)(
    (profile) => {
      setSelectedProfile(profile);
    },
    [setSelectedProfile]
  );
  const handleClearParamsFromURL = (0, import_react58.useCallback)(() => {
    if (onClearParamsFromURL) {
      onClearParamsFromURL();
    } else {
      globalThis.location.replace("/painel");
    }
  }, [onClearParamsFromURL]);
  const handleError = (0, import_react58.useCallback)(
    (error) => {
      if (onError) {
        onError(error);
      } else {
        console.error("Erro ao obter informa\xE7\xF5es da sess\xE3o:", error);
        navigate("/", { replace: true });
      }
    },
    [navigate, onError]
  );
  const urlAuthConfig = (0, import_react58.useMemo)(
    () => ({
      setTokens,
      setSessionInfo,
      setSelectedProfile: handleSetSelectedProfile,
      api: apiConfig,
      endpoint,
      clearParamsFromURL: handleClearParamsFromURL,
      maxRetries,
      retryDelay,
      onError: handleError
    }),
    [
      setTokens,
      setSessionInfo,
      handleSetSelectedProfile,
      apiConfig,
      endpoint,
      handleClearParamsFromURL,
      maxRetries,
      retryDelay,
      handleError
    ]
  );
  useUrlAuthentication(urlAuthConfig);
  const { sessionInfo } = useAuth();
  const institutionIdToUse = (0, import_react58.useMemo)(() => {
    return sessionInfo?.institutionId || getInstitutionId;
  }, [sessionInfo?.institutionId, getInstitutionId]);
  (0, import_react58.useEffect)(() => {
    if (institutionIdToUse && !initialized) {
      initialize(institutionIdToUse);
    }
  }, [institutionIdToUse, initialize, initialized]);
  return {
    handleNotFoundNavigation,
    urlAuthConfig,
    institutionIdToUse
  };
}

// src/store/questionFiltersStore.ts
var import_zustand15 = require("zustand");
var useQuestionFiltersStore = (0, import_zustand15.create)((set) => ({
  draftFilters: null,
  appliedFilters: null,
  setDraftFilters: (filters) => {
    set({ draftFilters: filters });
  },
  applyFilters: () => {
    set((state) => ({
      appliedFilters: state.draftFilters
    }));
  },
  clearFilters: () => {
    set({
      draftFilters: null,
      appliedFilters: null
    });
  }
}));

// src/components/ActivityCardQuestionBanks/ActivityCardQuestionBanks.tsx
var import_phosphor_react40 = require("phosphor-react");

// src/utils/questionRenderer.ts
var renderFromMap = (renderers, questionType) => {
  if (!questionType) return null;
  const renderer = renderers[questionType];
  return renderer ? renderer() : null;
};

// src/components/ActivityCardQuestionBanks/ActivityCardQuestionBanks.tsx
var import_react59 = require("react");
var import_jsx_runtime78 = require("react/jsx-runtime");
var ActivityCardQuestionBanks = ({
  question,
  questionType,
  iconName = "BookOpen",
  subjectColor = "#000000",
  isDark = false,
  onAddToActivity,
  assunto,
  enunciado
} = {}) => {
  const alternatives = (0, import_react59.useMemo)(() => {
    if (!question?.options || questionType !== "ALTERNATIVA" /* ALTERNATIVA */)
      return [];
    const correctOptionIds2 = question.correctOptionIds || [];
    return question.options.map((option) => {
      const isCorrect = correctOptionIds2.includes(option.id);
      return {
        value: option.id,
        label: option.option,
        status: isCorrect ? "correct" : void 0,
        disabled: !isCorrect
      };
    });
  }, [question, questionType]);
  const correctOptionId = (0, import_react59.useMemo)(() => {
    if (!question?.correctOptionIds || question.correctOptionIds.length === 0) {
      return void 0;
    }
    return question.correctOptionIds[0];
  }, [question]);
  const multipleChoices = (0, import_react59.useMemo)(() => {
    if (!question?.options || questionType !== "MULTIPLA_ESCOLHA" /* MULTIPLA_ESCOLHA */)
      return [];
    const correctOptionIds2 = question.correctOptionIds || [];
    return question.options.map((option) => {
      const isCorrect = correctOptionIds2.includes(option.id);
      return {
        value: option.id,
        label: option.option,
        status: isCorrect ? "correct" : void 0,
        disabled: !isCorrect
      };
    });
  }, [question, questionType]);
  const correctOptionIds = (0, import_react59.useMemo)(() => {
    return question?.correctOptionIds || [];
  }, [question]);
  const getStatusBadge2 = (status) => {
    switch (status) {
      case "correct":
        return /* @__PURE__ */ (0, import_jsx_runtime78.jsx)(Badge_default, { variant: "solid", action: "success", iconLeft: /* @__PURE__ */ (0, import_jsx_runtime78.jsx)(import_phosphor_react40.CheckCircle, {}), children: "Resposta correta" });
      case "incorrect":
        return /* @__PURE__ */ (0, import_jsx_runtime78.jsx)(Badge_default, { variant: "solid", action: "error", iconLeft: /* @__PURE__ */ (0, import_jsx_runtime78.jsx)(import_phosphor_react40.XCircle, {}), children: "Resposta incorreta" });
    }
  };
  const getStatusStyles2 = (status) => {
    switch (status) {
      case "correct":
        return "bg-success-background border-success-300";
      case "incorrect":
        return "bg-error-background border-error-300";
    }
  };
  const getLetterByIndex = (index) => String.fromCodePoint(97 + index);
  const renderAlternative = () => {
    if (!question || alternatives.length === 0) return null;
    return /* @__PURE__ */ (0, import_jsx_runtime78.jsx)("div", { className: "mt-4", children: /* @__PURE__ */ (0, import_jsx_runtime78.jsx)(
      AlternativesList,
      {
        alternatives,
        mode: "readonly",
        layout: "compact",
        selectedValue: correctOptionId,
        name: "teacher-question-view"
      }
    ) });
  };
  const renderMultipleChoice = () => {
    if (!question || multipleChoices.length === 0) return null;
    return /* @__PURE__ */ (0, import_jsx_runtime78.jsx)("div", { className: "mt-4", children: /* @__PURE__ */ (0, import_jsx_runtime78.jsx)(
      MultipleChoiceList,
      {
        choices: multipleChoices,
        mode: "readonly",
        selectedValues: correctOptionIds,
        name: "teacher-question-view-multiple"
      }
    ) });
  };
  const renderDissertative = () => {
    return /* @__PURE__ */ (0, import_jsx_runtime78.jsx)("div", { className: "mt-4 px-2 py-4", children: /* @__PURE__ */ (0, import_jsx_runtime78.jsx)(Text_default, { size: "sm", className: "text-text-600 italic", children: "Resposta do aluno" }) });
  };
  const renderTrueOrFalse = () => {
    if (!question || question.options.length === 0) return null;
    return /* @__PURE__ */ (0, import_jsx_runtime78.jsx)("div", { className: "mt-4", children: /* @__PURE__ */ (0, import_jsx_runtime78.jsx)("div", { className: "flex flex-col gap-3.5", children: question.options.map((option, index) => {
      const isCorrect = correctOptionIds.includes(option.id);
      const correctAnswer = isCorrect ? "Verdadeiro" : "Falso";
      const variantCorrect = "correct";
      return /* @__PURE__ */ (0, import_jsx_runtime78.jsx)("section", { className: "flex flex-col gap-2", children: /* @__PURE__ */ (0, import_jsx_runtime78.jsxs)(
        "div",
        {
          className: cn(
            "flex flex-row justify-between items-center gap-2 p-2 rounded-md border",
            getStatusStyles2(variantCorrect)
          ),
          children: [
            /* @__PURE__ */ (0, import_jsx_runtime78.jsx)(Text_default, { size: "sm", className: "text-text-900", children: getLetterByIndex(index).concat(") ").concat(option.option) }),
            /* @__PURE__ */ (0, import_jsx_runtime78.jsxs)("div", { className: "flex flex-row items-center gap-2 flex-shrink-0", children: [
              /* @__PURE__ */ (0, import_jsx_runtime78.jsxs)(Text_default, { size: "sm", className: "text-text-700", children: [
                "Resposta correta: ",
                correctAnswer
              ] }),
              getStatusBadge2(variantCorrect)
            ] })
          ]
        }
      ) }, option.id);
    }) }) });
  };
  const renderConnectDots = () => {
    return null;
  };
  const renderFill = () => {
    return null;
  };
  const renderImage = () => {
    return null;
  };
  const questionRenderers = {
    ["ALTERNATIVA" /* ALTERNATIVA */]: renderAlternative,
    ["MULTIPLA_ESCOLHA" /* MULTIPLA_ESCOLHA */]: renderMultipleChoice,
    ["DISSERTATIVA" /* DISSERTATIVA */]: renderDissertative,
    ["VERDADEIRO_FALSO" /* VERDADEIRO_FALSO */]: renderTrueOrFalse,
    ["LIGAR_PONTOS" /* LIGAR_PONTOS */]: renderConnectDots,
    ["PREENCHER" /* PREENCHER */]: renderFill,
    ["IMAGEM" /* IMAGEM */]: renderImage
  };
  return /* @__PURE__ */ (0, import_jsx_runtime78.jsxs)("div", { className: "w-full flex flex-col gap-2 px-4 py-6", children: [
    /* @__PURE__ */ (0, import_jsx_runtime78.jsxs)("section", { className: "flex flex-row gap-2 text-text-650", children: [
      /* @__PURE__ */ (0, import_jsx_runtime78.jsxs)("div", { className: "py-1 px-2 flex flex-row items-center gap-1", children: [
        /* @__PURE__ */ (0, import_jsx_runtime78.jsx)(
          "span",
          {
            className: "size-4 rounded-sm flex items-center justify-center shrink-0 text-text-950",
            style: {
              backgroundColor: getSubjectColorWithOpacity(subjectColor, isDark)
            },
            children: /* @__PURE__ */ (0, import_jsx_runtime78.jsx)(IconRender_default, { iconName, size: 14, color: "currentColor" })
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime78.jsx)(Text_default, { size: "sm", children: assunto || "Assunto n\xE3o informado" })
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime78.jsx)("div", { className: "py-1 px-2 flex flex-row items-center gap-1", children: /* @__PURE__ */ (0, import_jsx_runtime78.jsx)(Text_default, { size: "sm", className: "", children: questionType ? questionTypeLabels[questionType] : "Tipo de quest\xE3o" }) })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime78.jsxs)("section", { className: "flex flex-col gap-1", children: [
      /* @__PURE__ */ (0, import_jsx_runtime78.jsx)(Text_default, { size: "md", weight: "medium", className: "text-text-950 text-md", children: enunciado || "Enunciado n\xE3o informado" }),
      renderFromMap(questionRenderers, questionType)
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime78.jsx)("section", { children: /* @__PURE__ */ (0, import_jsx_runtime78.jsx)(
      Button_default,
      {
        size: "small",
        iconLeft: /* @__PURE__ */ (0, import_jsx_runtime78.jsx)(import_phosphor_react40.Plus, {}),
        className: "w-full",
        onClick: () => {
          if (onAddToActivity) {
            onAddToActivity();
          }
        },
        children: "Adicionar \xE0 atividade"
      }
    ) })
  ] });
};

// src/components/ActivityCardQuestionPreview/ActivityCardQuestionPreview.tsx
var import_react60 = require("react");
var import_phosphor_react41 = require("phosphor-react");
var import_jsx_runtime79 = require("react/jsx-runtime");
var QuestionHeader = ({
  badgeColor,
  iconName,
  subjectName,
  resolvedQuestionTypeLabel,
  position
}) => /* @__PURE__ */ (0, import_jsx_runtime79.jsxs)("div", { className: "flex flex-row gap-2 text-text-650", children: [
  /* @__PURE__ */ (0, import_jsx_runtime79.jsxs)("div", { className: "py-1 px-2 flex flex-row items-center gap-1", children: [
    /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(
      "span",
      {
        className: "size-4 rounded-sm flex items-center justify-center shrink-0 text-text-950",
        style: {
          backgroundColor: badgeColor
        },
        children: /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(
          IconRender_default,
          {
            iconName: iconName ?? "Book",
            size: 14,
            color: "currentColor"
          }
        )
      }
    ),
    /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(Text_default, { size: "sm", children: subjectName ?? "Assunto n\xE3o informado" })
  ] }),
  typeof position === "number" && /* @__PURE__ */ (0, import_jsx_runtime79.jsx)("div", { className: "py-1 px-2 flex flex-row items-center gap-1", children: /* @__PURE__ */ (0, import_jsx_runtime79.jsxs)(Text_default, { size: "sm", className: "text-text-700", children: [
    "#",
    position
  ] }) }),
  /* @__PURE__ */ (0, import_jsx_runtime79.jsx)("div", { className: "py-1 px-2 flex flex-row items-center gap-1", children: /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(Text_default, { size: "sm", className: "", children: resolvedQuestionTypeLabel ?? "Tipo de quest\xE3o" }) })
] });
var ActivityCardQuestionPreview = ({
  subjectName = "Assunto n\xE3o informado",
  subjectColor = "#000000",
  iconName = "Book",
  isDark = false,
  questionType,
  questionTypeLabel,
  enunciado = "Enunciado n\xE3o informado",
  question,
  defaultExpanded = false,
  value,
  className,
  children,
  position
}) => {
  const badgeColor = getSubjectColorWithOpacity(subjectColor, isDark) ?? subjectColor;
  const [isExpanded, setIsExpanded] = (0, import_react60.useState)(defaultExpanded);
  const correctOptionIds = question?.correctOptionIds || [];
  const resolvedQuestionTypeLabel = questionType && questionTypeLabels[questionType] ? questionTypeLabels[questionType] : questionTypeLabel || "Tipo de quest\xE3o";
  const safeSubjectName = subjectName ?? "Assunto n\xE3o informado";
  const safeIconName = iconName ?? "Book";
  const safeResolvedLabel = resolvedQuestionTypeLabel ?? "Tipo de quest\xE3o";
  const alternatives = (0, import_react60.useMemo)(() => {
    if (!question?.options || questionType !== "ALTERNATIVA" /* ALTERNATIVA */)
      return [];
    return question.options.map((option) => {
      const isCorrect = correctOptionIds.includes(option.id);
      return {
        value: option.id,
        label: option.option,
        status: isCorrect ? "correct" : void 0,
        disabled: !isCorrect
      };
    });
  }, [question, questionType, correctOptionIds]);
  const multipleChoices = (0, import_react60.useMemo)(() => {
    if (!question?.options || questionType !== "MULTIPLA_ESCOLHA" /* MULTIPLA_ESCOLHA */)
      return [];
    return question.options.map((option) => {
      const isCorrect = correctOptionIds.includes(option.id);
      return {
        value: option.id,
        label: option.option,
        status: isCorrect ? "correct" : void 0,
        disabled: !isCorrect
      };
    });
  }, [question, questionType, correctOptionIds]);
  const renderAlternative = () => {
    if (alternatives.length === 0) return null;
    return /* @__PURE__ */ (0, import_jsx_runtime79.jsx)("div", { className: "mt-4", children: /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(
      AlternativesList,
      {
        alternatives,
        mode: "readonly",
        layout: "compact",
        selectedValue: correctOptionIds[0],
        name: `preview-alternatives-${value ?? subjectName}`
      }
    ) });
  };
  const renderMultipleChoice = () => {
    if (multipleChoices.length === 0) return null;
    return /* @__PURE__ */ (0, import_jsx_runtime79.jsx)("div", { className: "mt-4", children: /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(
      MultipleChoiceList,
      {
        choices: multipleChoices,
        mode: "readonly",
        selectedValues: correctOptionIds,
        name: `preview-multiple-${value ?? subjectName}`
      }
    ) });
  };
  const renderTrueOrFalse = () => {
    if (!question?.options || question.options.length === 0) return null;
    return /* @__PURE__ */ (0, import_jsx_runtime79.jsx)("div", { className: "mt-4", children: /* @__PURE__ */ (0, import_jsx_runtime79.jsx)("div", { className: "flex flex-col gap-3.5", children: question.options.map((option, index) => {
      const isCorrect = correctOptionIds.includes(option.id);
      const correctAnswer = isCorrect ? "Verdadeiro" : "Falso";
      return /* @__PURE__ */ (0, import_jsx_runtime79.jsx)("section", { className: "flex flex-col gap-2", children: /* @__PURE__ */ (0, import_jsx_runtime79.jsxs)(
        "div",
        {
          className: cn(
            "flex flex-row justify-between items-center gap-2 p-2 rounded-md border",
            isCorrect ? "bg-success-background border-success-300" : "bg-error-background border-error-300"
          ),
          children: [
            /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(Text_default, { size: "sm", className: "text-text-900", children: String.fromCodePoint(97 + index).concat(") ").concat(option.option) }),
            /* @__PURE__ */ (0, import_jsx_runtime79.jsxs)("div", { className: "flex flex-row items-center gap-2 flex-shrink-0", children: [
              /* @__PURE__ */ (0, import_jsx_runtime79.jsxs)(Text_default, { size: "sm", className: "text-text-700", children: [
                "Resposta correta: ",
                correctAnswer
              ] }),
              /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(
                Badge_default,
                {
                  variant: "solid",
                  action: isCorrect ? "success" : "error",
                  iconLeft: isCorrect ? /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(import_phosphor_react41.CheckCircle, {}) : /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(import_phosphor_react41.XCircle, {}),
                  children: isCorrect ? "Resposta correta" : "Resposta incorreta"
                }
              )
            ] })
          ]
        }
      ) }, option.id);
    }) }) });
  };
  const renderDissertative = () => {
    return /* @__PURE__ */ (0, import_jsx_runtime79.jsx)("div", { className: "mt-4 px-2 py-4", children: /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(Text_default, { size: "sm", className: "text-text-600 italic", children: "Resposta do aluno" }) });
  };
  const renderConnectDots = () => null;
  const renderFill = () => null;
  const renderImage = () => null;
  const questionRenderers = {
    ["ALTERNATIVA" /* ALTERNATIVA */]: renderAlternative,
    ["MULTIPLA_ESCOLHA" /* MULTIPLA_ESCOLHA */]: renderMultipleChoice,
    ["DISSERTATIVA" /* DISSERTATIVA */]: renderDissertative,
    ["VERDADEIRO_FALSO" /* VERDADEIRO_FALSO */]: renderTrueOrFalse,
    ["LIGAR_PONTOS" /* LIGAR_PONTOS */]: renderConnectDots,
    ["PREENCHER" /* PREENCHER */]: renderFill,
    ["IMAGEM" /* IMAGEM */]: renderImage
  };
  return /* @__PURE__ */ (0, import_jsx_runtime79.jsxs)(
    "div",
    {
      className: "w-full",
      "data-position": position,
      role: "button",
      tabIndex: 0,
      "aria-expanded": isExpanded,
      onClick: () => {
        if (isExpanded) {
          setIsExpanded(false);
        }
      },
      onMouseDown: (event) => {
        const draggableAncestor = event.target.closest(
          '[data-draggable="true"]'
        );
        if (!draggableAncestor) {
          event.preventDefault();
        }
      },
      onKeyDown: (event) => {
        if (event.key === "Enter" || event.key === " ") {
          event.preventDefault();
          if (isExpanded) {
            setIsExpanded(false);
          }
        }
      },
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(
          "div",
          {
            "data-drag-preview": "true",
            className: "fixed -left-[9999px] -top-[9999px] pointer-events-none z-[9999] w-[440px]",
            children: /* @__PURE__ */ (0, import_jsx_runtime79.jsx)("div", { className: "w-full rounded-lg border border-border-200 bg-background", children: /* @__PURE__ */ (0, import_jsx_runtime79.jsxs)("div", { className: "w-full min-w-0 flex flex-col gap-2 py-2", children: [
              /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(
                QuestionHeader,
                {
                  badgeColor,
                  iconName: safeIconName,
                  subjectName: safeSubjectName,
                  resolvedQuestionTypeLabel: safeResolvedLabel,
                  position
                }
              ),
              /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(
                Text_default,
                {
                  size: "md",
                  weight: "medium",
                  className: "text-text-950 truncate px-3",
                  children: enunciado
                }
              )
            ] }) })
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime79.jsxs)(
          CardAccordation,
          {
            className: cn(
              "w-full rounded-lg border border-border-200 bg-background",
              className
            ),
            expanded: isExpanded,
            onToggleExpanded: setIsExpanded,
            defaultExpanded,
            value,
            trigger: /* @__PURE__ */ (0, import_jsx_runtime79.jsxs)("div", { className: "w-full min-w-0 flex flex-col gap-2 py-2", children: [
              /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(
                QuestionHeader,
                {
                  badgeColor,
                  iconName: safeIconName,
                  subjectName: safeSubjectName,
                  resolvedQuestionTypeLabel: safeResolvedLabel,
                  position
                }
              ),
              !isExpanded && /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(
                Text_default,
                {
                  size: "md",
                  weight: "medium",
                  className: "text-text-950 truncate px-3",
                  children: enunciado
                }
              )
            ] }),
            children: [
              /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(
                Text_default,
                {
                  size: "md",
                  weight: "medium",
                  className: "text-text-950 break-words whitespace-pre-wrap",
                  children: enunciado
                }
              ),
              renderFromMap(questionRenderers, questionType),
              children
            ]
          }
        )
      ]
    }
  );
};

// src/components/ActivityPreview/ActivityPreview.tsx
var import_react62 = require("react");
var import_phosphor_react42 = require("phosphor-react");

// src/components/QuestionsPdfGenerator/QuestionsPdfGenerator.tsx
var import_react61 = require("react");
var import_jsx_runtime80 = require("react/jsx-runtime");
var QuestionsPdfContent = (0, import_react61.forwardRef)(({ questions }, ref) => {
  const getLetterByIndex = (index) => {
    return String.fromCodePoint(97 + index);
  };
  const renderAlternative = (question) => {
    if (!question.question?.options || question.question.options.length === 0) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime80.jsx)(
      "ol",
      {
        type: "a",
        style: {
          marginTop: "12px",
          marginBottom: "12px",
          paddingLeft: "24px"
        },
        children: question.question.options.map((option) => /* @__PURE__ */ (0, import_jsx_runtime80.jsx)(
          "li",
          {
            style: {
              marginBottom: "8px",
              lineHeight: "1.6"
            },
            children: /* @__PURE__ */ (0, import_jsx_runtime80.jsx)(LatexRenderer_default, { content: option.option })
          },
          option.id
        ))
      }
    );
  };
  const renderMultipleChoice = (question) => {
    if (!question.question?.options || question.question.options.length === 0) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime80.jsx)(
      "div",
      {
        style: {
          marginTop: "12px",
          marginBottom: "12px"
        },
        children: question.question.options.map((option, index) => {
          const letter = getLetterByIndex(index);
          return /* @__PURE__ */ (0, import_jsx_runtime80.jsxs)(
            "div",
            {
              style: {
                marginBottom: "12px",
                display: "flex",
                alignItems: "flex-start",
                gap: "8px",
                lineHeight: "1.6"
              },
              children: [
                /* @__PURE__ */ (0, import_jsx_runtime80.jsx)(
                  "span",
                  {
                    style: {
                      marginTop: "2px",
                      minWidth: "20px",
                      fontSize: "16px"
                    },
                    children: "\u2610"
                  }
                ),
                /* @__PURE__ */ (0, import_jsx_runtime80.jsxs)(
                  "span",
                  {
                    style: {
                      fontWeight: "bold",
                      marginRight: "4px"
                    },
                    children: [
                      letter,
                      ")"
                    ]
                  }
                ),
                /* @__PURE__ */ (0, import_jsx_runtime80.jsx)("div", { style: { flex: 1 }, children: /* @__PURE__ */ (0, import_jsx_runtime80.jsx)(LatexRenderer_default, { content: option.option }) })
              ]
            },
            option.id
          );
        })
      }
    );
  };
  const renderDissertative = () => {
    return /* @__PURE__ */ (0, import_jsx_runtime80.jsx)(
      "div",
      {
        style: {
          marginTop: "12px",
          marginBottom: "12px"
        },
        children: /* @__PURE__ */ (0, import_jsx_runtime80.jsxs)(
          "div",
          {
            style: {
              display: "flex",
              alignItems: "flex-start",
              gap: "8px"
            },
            children: [
              /* @__PURE__ */ (0, import_jsx_runtime80.jsx)(
                "span",
                {
                  style: {
                    fontWeight: "bold",
                    marginTop: "2px"
                  },
                  children: "R:"
                }
              ),
              /* @__PURE__ */ (0, import_jsx_runtime80.jsx)(
                "div",
                {
                  style: {
                    minHeight: "150px",
                    flex: 1
                  }
                }
              )
            ]
          }
        )
      }
    );
  };
  const renderTrueOrFalse = (question) => {
    if (!question.question?.options || question.question.options.length === 0) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime80.jsx)("div", { style: { marginTop: "12px", marginBottom: "12px" }, children: question.question.options.map((option, index) => /* @__PURE__ */ (0, import_jsx_runtime80.jsxs)(
      "div",
      {
        style: {
          marginBottom: "16px",
          display: "flex",
          alignItems: "flex-start",
          gap: "12px"
        },
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime80.jsxs)(
            "span",
            {
              style: {
                fontWeight: "bold",
                minWidth: "20px"
              },
              children: [
                getLetterByIndex(index),
                ")"
              ]
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime80.jsx)("div", { style: { flex: 1 }, children: /* @__PURE__ */ (0, import_jsx_runtime80.jsx)(LatexRenderer_default, { content: option.option }) }),
          /* @__PURE__ */ (0, import_jsx_runtime80.jsx)(
            "span",
            {
              style: {
                marginLeft: "8px",
                whiteSpace: "nowrap",
                fontSize: "14px"
              },
              children: "( ) V ( ) F"
            }
          )
        ]
      },
      option.id
    )) });
  };
  const renderQuestionTypeContent = (question) => {
    const renderMap = {
      ["ALTERNATIVA" /* ALTERNATIVA */]: renderAlternative,
      ["MULTIPLA_ESCOLHA" /* MULTIPLA_ESCOLHA */]: renderMultipleChoice,
      ["DISSERTATIVA" /* DISSERTATIVA */]: () => renderDissertative(),
      ["VERDADEIRO_FALSO" /* VERDADEIRO_FALSO */]: renderTrueOrFalse,
      ["LIGAR_PONTOS" /* LIGAR_PONTOS */]: () => null,
      ["PREENCHER" /* PREENCHER */]: () => null,
      ["IMAGEM" /* IMAGEM */]: () => null
    };
    if (!question.questionType) {
      return null;
    }
    const renderFunction = renderMap[question.questionType];
    return renderFunction ? renderFunction(question) : null;
  };
  const renderQuestionContent = (question, index) => {
    const questionNumber = index + 1;
    return /* @__PURE__ */ (0, import_jsx_runtime80.jsxs)(
      "div",
      {
        style: {
          marginBottom: "32px",
          pageBreakInside: "avoid"
        },
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime80.jsxs)(
            "h3",
            {
              style: {
                fontSize: "16px",
                fontWeight: "bold",
                marginBottom: "12px",
                color: "#000"
              },
              children: [
                "Quest\xE3o ",
                questionNumber
              ]
            }
          ),
          question.enunciado && /* @__PURE__ */ (0, import_jsx_runtime80.jsx)(
            "div",
            {
              style: {
                marginBottom: "12px",
                lineHeight: "1.6",
                color: "#000"
              },
              children: /* @__PURE__ */ (0, import_jsx_runtime80.jsx)(LatexRenderer_default, { content: question.enunciado })
            }
          ),
          renderQuestionTypeContent(question)
        ]
      },
      question.id
    );
  };
  return /* @__PURE__ */ (0, import_jsx_runtime80.jsxs)(
    "div",
    {
      ref,
      className: "questions-pdf-container",
      style: {
        position: "fixed",
        left: 0,
        top: 0,
        width: "210mm",
        minHeight: "297mm",
        visibility: "hidden",
        pointerEvents: "none",
        zIndex: -1
      },
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime80.jsx)("style", { children: `
            @media print {
              @page {
                margin: 20mm;
                size: A4;
              }
              
              body {
                margin: 0;
                padding: 0;
              }
              
              .questions-pdf-container {
                position: static !important;
                left: auto !important;
                top: auto !important;
                visibility: visible !important;
                pointer-events: auto !important;
                z-index: auto !important;
                padding: 0;
                margin: 0;
                font-family: Arial, sans-serif;
                font-size: 14px;
                line-height: 1.6;
                color: #000;
                width: auto;
                min-height: auto;
              }
              
              .questions-pdf-container h3 {
                page-break-after: avoid;
              }
              
              .questions-pdf-container > div {
                page-break-inside: avoid;
              }
            }
          ` }),
        /* @__PURE__ */ (0, import_jsx_runtime80.jsx)("div", { style: { padding: "20px" }, children: questions.map(
          (question, index) => renderQuestionContent(question, index)
        ) })
      ]
    }
  );
});
QuestionsPdfContent.displayName = "QuestionsPdfContent";
var collectRelevantStyles = () => {
  const styles = [];
  const styleSheets = Array.from(document.styleSheets);
  styleSheets.forEach((styleSheet) => {
    try {
      const cssRules = styleSheet.cssRules || [];
      Array.from(cssRules).forEach((rule) => {
        const ruleText = rule.cssText;
        if (ruleText.includes("katex") || ruleText.includes("questions-pdf")) {
          styles.push(ruleText);
        }
      });
    } catch (error) {
      if (typeof console !== "undefined" && console.debug) {
        console.debug("Could not access stylesheet (likely CORS):", error);
      }
    }
  });
  return styles;
};
var generatePrintHTML = (contentHTML, styles) => {
  return `
    <!DOCTYPE html>
    <html>
      <head>
        <title>Quest\xF5es</title>
        <meta charset="utf-8">
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.27/dist/katex.min.css">
        <style>
          @page {
            margin: 20mm;
            size: A4;
          }
          
          * {
            box-sizing: border-box;
          }
          
          body {
            margin: 0;
            padding: 0;
            font-family: Arial, sans-serif;
            font-size: 14px;
            line-height: 1.6;
            color: #000;
          }
          
          .questions-pdf-container {
            position: static !important;
            visibility: visible !important;
            pointer-events: auto !important;
            z-index: auto !important;
            left: auto !important;
            top: auto !important;
            width: auto !important;
            min-height: auto !important;
            padding: 0;
            margin: 0;
          }
          
          .questions-pdf-container h3 {
            page-break-after: avoid;
            font-size: 16px;
            font-weight: bold;
            margin-bottom: 12px;
            color: #000;
          }
          
          .questions-pdf-container > div {
            page-break-inside: avoid;
          }
          
          ol {
            margin-top: 12px;
            margin-bottom: 12px;
            padding-left: 24px;
          }
          
          li {
            margin-bottom: 8px;
            line-height: 1.6;
          }
          
          ${styles.join("\n")}
        </style>
      </head>
      <body>
        <div class="questions-pdf-container">
          ${contentHTML}
        </div>
      </body>
    </html>
  `;
};
var setupPrintWindowHandler = (printWindow) => {
  printWindow.onload = () => {
    const printAndCleanup = () => {
      try {
        printWindow.print();
      } finally {
        setTimeout(() => {
          if (printWindow && !printWindow.closed) {
            printWindow.close();
          }
        }, 1e3);
      }
    };
    const fonts = printWindow.document.fonts;
    if (fonts && "ready" in fonts) {
      fonts.ready.then(() => {
        setTimeout(printAndCleanup, 100);
      }).catch(() => {
        setTimeout(printAndCleanup, 500);
      });
    } else {
      setTimeout(printAndCleanup, 500);
    }
  };
};
var useQuestionsPdfPrint = (questions, onPrint, onPrintError) => {
  const contentRef = (0, import_react61.useRef)(null);
  const handlePrint = (0, import_react61.useCallback)(() => {
    try {
      onPrint?.();
      if (!contentRef.current) {
        throw new Error("Elemento de PDF n\xE3o encontrado no DOM");
      }
      const printWindow = window.open("", "_blank");
      if (!printWindow) {
        throw new Error(
          "N\xE3o foi poss\xEDvel abrir a janela de impress\xE3o. Verifique se os pop-ups est\xE3o bloqueados."
        );
      }
      printWindow.opener = null;
      const contentHTML = contentRef.current.innerHTML;
      const styles = collectRelevantStyles();
      const htmlContent = generatePrintHTML(contentHTML, styles);
      const doc = printWindow.document;
      doc.open();
      doc.write(htmlContent);
      doc.close();
      setupPrintWindowHandler(printWindow);
    } catch (error) {
      const errorObj = error instanceof Error ? error : new Error(String(error));
      onPrintError?.(errorObj);
      console.error("Erro ao gerar PDF:", errorObj);
    }
  }, [onPrint, onPrintError]);
  return {
    contentRef,
    handlePrint
  };
};
var QuestionsPdfGenerator = ({
  questions,
  onPrint,
  onPrintError,
  children
}) => {
  const { contentRef, handlePrint } = useQuestionsPdfPrint(
    questions,
    onPrint,
    onPrintError
  );
  return /* @__PURE__ */ (0, import_jsx_runtime80.jsxs)(import_jsx_runtime80.Fragment, { children: [
    children?.(handlePrint),
    /* @__PURE__ */ (0, import_jsx_runtime80.jsx)("div", { style: { display: "none" }, children: /* @__PURE__ */ (0, import_jsx_runtime80.jsx)(QuestionsPdfContent, { ref: contentRef, questions }) })
  ] });
};

// src/components/ActivityPreview/ActivityPreview.tsx
var import_jsx_runtime81 = require("react/jsx-runtime");
var ActivityPreview = ({
  title = "Pr\xE9via da atividade",
  questions = [],
  onDownloadPdf,
  onRemoveAll,
  onRemoveQuestion,
  className,
  onReorder,
  onPositionsChange,
  isDark = false
}) => {
  const onPositionsChangeRef = (0, import_react62.useRef)(onPositionsChange);
  onPositionsChangeRef.current = onPositionsChange;
  const normalizeWithPositions = (0, import_react62.useMemo)(
    () => (items) => items.map((item, index) => ({
      ...item,
      position: index + 1
    })),
    []
  );
  const [orderedQuestions, setOrderedQuestions] = (0, import_react62.useState)(
    () => normalizeWithPositions(questions)
  );
  (0, import_react62.useEffect)(() => {
    const normalized = normalizeWithPositions(questions);
    setOrderedQuestions(normalized);
    onPositionsChangeRef.current?.(normalized);
  }, [questions, normalizeWithPositions]);
  const total = orderedQuestions.length;
  const totalLabel = total === 1 ? "1 quest\xE3o adicionada" : `${total} quest\xF5es adicionadas`;
  const { contentRef, handlePrint } = useQuestionsPdfPrint(
    orderedQuestions,
    onDownloadPdf
  );
  const handleDownloadPdf = () => {
    onDownloadPdf?.();
    setTimeout(() => {
      if (!contentRef.current) {
        console.error("Elemento de PDF n\xE3o encontrado no DOM");
        return;
      }
      if (typeof handlePrint === "function") {
        handlePrint();
      } else {
        console.error("handlePrint n\xE3o \xE9 uma fun\xE7\xE3o:", handlePrint);
      }
    }, 100);
  };
  const handleReorder = (fromId, toId) => {
    if (fromId === toId) return;
    const current = [...orderedQuestions];
    const fromIndex = current.findIndex((q) => q.id === fromId);
    const toIndex = current.findIndex((q) => q.id === toId);
    if (fromIndex === -1 || toIndex === -1) return;
    const [moved] = current.splice(fromIndex, 1);
    current.splice(toIndex, 0, moved);
    const normalized = normalizeWithPositions(current);
    setOrderedQuestions(normalized);
    onReorder?.(normalized);
    onPositionsChange?.(normalized);
  };
  return /* @__PURE__ */ (0, import_jsx_runtime81.jsxs)(
    "div",
    {
      className: cn(
        "w-full flex-shrink-0 p-4 rounded-lg bg-background flex flex-col gap-4",
        className
      ),
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime81.jsxs)("section", { className: "flex flex-row items-center gap-2 text-text-950", children: [
          /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(import_phosphor_react42.File, { size: 24 }),
          /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(Text_default, { size: "lg", weight: "bold", children: title })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime81.jsxs)("section", { className: "flex flex-row justify-between items-center", children: [
          /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(Text_default, { size: "sm", className: "text-text-800", children: totalLabel }),
          /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(
            Button_default,
            {
              size: "small",
              variant: "outline",
              iconLeft: /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(import_phosphor_react42.DownloadSimple, {}),
              onClick: handleDownloadPdf,
              children: "Baixar pdf"
            }
          )
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime81.jsx)("section", { className: "flex flex-col gap-3", children: orderedQuestions.map(
          ({
            id,
            subjectName = "Assunto n\xE3o informado",
            subjectColor = "#000000",
            iconName = "BookOpen",
            questionType,
            questionTypeLabel,
            enunciado,
            question,
            position
          }, index) => /* @__PURE__ */ (0, import_jsx_runtime81.jsxs)(
            "div",
            {
              draggable: true,
              "data-draggable": "true",
              role: "button",
              tabIndex: 0,
              "aria-label": `Mover quest\xE3o ${enunciado ?? id}`,
              onDragStart: (e) => {
                e.dataTransfer.setData("text/plain", id);
                if (e.currentTarget instanceof HTMLElement) {
                  const preview = e.currentTarget.querySelector(
                    '[data-drag-preview="true"]'
                  );
                  if (preview) {
                    e.dataTransfer.setDragImage(preview, 8, 8);
                  } else {
                    e.dataTransfer.setDragImage(e.currentTarget, 8, 8);
                  }
                }
              },
              onDragOver: (e) => {
                e.preventDefault();
              },
              onDrop: (e) => {
                e.preventDefault();
                const fromId = e.dataTransfer.getData("text/plain");
                handleReorder(fromId, id);
              },
              onKeyDown: (e) => {
                if (e.key === "ArrowUp" && index > 0) {
                  e.preventDefault();
                  const targetId = orderedQuestions[index - 1].id;
                  handleReorder(id, targetId);
                } else if (e.key === "ArrowDown" && index < orderedQuestions.length - 1) {
                  e.preventDefault();
                  const targetId = orderedQuestions[index + 1].id;
                  handleReorder(id, targetId);
                } else if (e.key === "Enter" || e.key === " ") {
                  e.preventDefault();
                }
              },
              className: "rounded-lg border border-border-200 bg-background relative group",
              children: [
                onRemoveQuestion && /* @__PURE__ */ (0, import_jsx_runtime81.jsx)("div", { className: "absolute top-2 right-2 z-10 opacity-0 group-hover:opacity-100 transition-opacity", children: /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(
                  IconButton_default,
                  {
                    size: "sm",
                    icon: /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(import_phosphor_react42.Trash, { size: 16 }),
                    onClick: (e) => {
                      e.stopPropagation();
                      onRemoveQuestion(id);
                    },
                    "aria-label": `Remover quest\xE3o ${position ?? index + 1}`
                  }
                ) }),
                /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(
                  ActivityCardQuestionPreview,
                  {
                    subjectName,
                    subjectColor,
                    iconName,
                    isDark,
                    questionType,
                    questionTypeLabel,
                    enunciado,
                    defaultExpanded: false,
                    question,
                    value: id,
                    position
                  }
                )
              ]
            },
            id
          )
        ) }),
        /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(Button_default, { variant: "outline", onClick: onRemoveAll, children: "Remover tudo" }),
        /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(QuestionsPdfContent, { ref: contentRef, questions: orderedQuestions })
      ]
    }
  );
};

// src/components/ActivityDetails/ActivityDetails.tsx
var import_react63 = require("react");
var import_phosphor_react43 = require("phosphor-react");
var import_jsx_runtime82 = require("react/jsx-runtime");
var createTableColumns = (onCorrectActivity) => [
  {
    key: "studentName",
    label: "Aluno",
    sortable: true,
    render: (value) => {
      const name = typeof value === "string" ? value : "";
      return /* @__PURE__ */ (0, import_jsx_runtime82.jsxs)("div", { className: "flex items-center gap-3", children: [
        /* @__PURE__ */ (0, import_jsx_runtime82.jsx)("div", { className: "w-6 h-6 bg-blue-100 rounded-full flex items-center justify-center", children: /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Text_default, { className: "text-xs font-semibold text-primary-700", children: name.charAt(0).toUpperCase() }) }),
        /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Text_default, { className: "text-sm font-normal text-text-950", children: name })
      ] });
    }
  },
  {
    key: "status",
    label: "Status",
    sortable: false,
    render: (value) => {
      const config = getStatusBadgeConfig(value);
      return /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(
        Badge_default,
        {
          className: `${config.bgColor} ${config.textColor} text-xs px-2 py-1`,
          children: config.label
        }
      );
    }
  },
  {
    key: "answeredAt",
    label: "Respondido em",
    sortable: true,
    render: (value) => {
      if (!value || typeof value !== "string") {
        return /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Text_default, { className: "text-sm text-text-400", children: "-" });
      }
      return /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Text_default, { className: "text-sm text-text-700", children: formatDateToBrazilian(value) });
    }
  },
  {
    key: "timeSpent",
    label: "Dura\xE7\xE3o",
    sortable: false,
    render: (value) => Number(value) > 0 ? /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Text_default, { className: "text-sm text-text-700", children: formatTimeSpent(Number(value)) }) : /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Text_default, { className: "text-sm text-text-400", children: "-" })
  },
  {
    key: "score",
    label: "Nota",
    sortable: true,
    render: (value) => value === null ? /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Text_default, { className: "text-sm text-text-400", children: "-" }) : /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Text_default, { className: "text-sm font-semibold text-text-950", children: Number(value).toFixed(1) })
  },
  {
    key: "actions",
    label: "Resultado",
    sortable: false,
    render: (_value, row) => {
      if (row.status === STUDENT_ACTIVITY_STATUS.AGUARDANDO_CORRECAO) {
        return /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(
          Button_default,
          {
            variant: "outline",
            size: "small",
            onClick: () => onCorrectActivity(row.studentId),
            className: "text-xs",
            children: "Corrigir atividade"
          }
        );
      }
      if (row.status === STUDENT_ACTIVITY_STATUS.CONCLUIDO || row.status === STUDENT_ACTIVITY_STATUS.NAO_ENTREGUE) {
        return /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(
          Button_default,
          {
            variant: "link",
            size: "small",
            onClick: () => onCorrectActivity(row.studentId),
            className: "text-xs",
            children: "Ver detalhes"
          }
        );
      }
      return null;
    }
  }
];
var ActivityDetails = ({
  activityId,
  fetchActivityDetails,
  fetchStudentCorrection,
  submitObservation,
  onBack,
  onViewActivity,
  emptyStateImage,
  mapSubjectNameToEnum: mapSubjectNameToEnum2
}) => {
  const { isMobile } = useMobile();
  const [page, setPage] = (0, import_react63.useState)(1);
  const [limit, setLimit] = (0, import_react63.useState)(10);
  const [sortBy, setSortBy] = (0, import_react63.useState)(void 0);
  const [sortOrder, setSortOrder] = (0, import_react63.useState)(
    void 0
  );
  const [data, setData] = (0, import_react63.useState)(null);
  const [correctionData, setCorrectionData] = (0, import_react63.useState)(null);
  const [loading, setLoading] = (0, import_react63.useState)(true);
  const [error, setError] = (0, import_react63.useState)(null);
  const [isModalOpen, setIsModalOpen] = (0, import_react63.useState)(false);
  const [isViewOnlyModal, setIsViewOnlyModal] = (0, import_react63.useState)(false);
  const [correctionError, setCorrectionError] = (0, import_react63.useState)(null);
  (0, import_react63.useEffect)(() => {
    const loadData = async () => {
      if (!activityId) return;
      setLoading(true);
      setError(null);
      try {
        const result = await fetchActivityDetails(activityId, {
          page,
          limit,
          sortBy,
          sortOrder
        });
        setData(result);
      } catch (err) {
        setError(
          err instanceof Error ? err.message : "Erro ao carregar detalhes"
        );
      } finally {
        setLoading(false);
      }
    };
    loadData();
  }, [activityId, page, limit, sortBy, sortOrder, fetchActivityDetails]);
  const handleCorrectActivity = (0, import_react63.useCallback)(
    async (studentId) => {
      const student = data?.students.find((s) => s.studentId === studentId);
      if (!student || !activityId) return;
      const isViewOnly = student.status !== STUDENT_ACTIVITY_STATUS.AGUARDANDO_CORRECAO;
      setIsViewOnlyModal(isViewOnly);
      setCorrectionError(null);
      try {
        const correction = await fetchStudentCorrection(activityId, studentId);
        setCorrectionData(correction);
        setIsModalOpen(true);
      } catch (err) {
        console.error("Failed to fetch student correction:", err);
        setCorrectionError(
          err instanceof Error ? err.message : "Erro ao carregar dados de corre\xE7\xE3o"
        );
      }
    },
    [data?.students, activityId, fetchStudentCorrection]
  );
  const handleCloseModal = (0, import_react63.useCallback)(() => {
    setIsModalOpen(false);
  }, []);
  const handleObservationSubmit = (0, import_react63.useCallback)(
    async (observation, files) => {
      if (!activityId || !correctionData?.studentId) return;
      try {
        await submitObservation(
          activityId,
          correctionData.studentId,
          observation,
          files
        );
        setIsModalOpen(false);
      } catch (err) {
        console.error("Failed to submit observation:", err);
      }
    },
    [activityId, correctionData?.studentId, submitObservation]
  );
  const tableData = (0, import_react63.useMemo)(() => {
    if (!data?.students) return [];
    return data.students.map((student) => ({
      id: student.studentId,
      studentId: student.studentId,
      studentName: student.studentName,
      status: student.status,
      answeredAt: student.answeredAt,
      timeSpent: student.timeSpent,
      score: student.score
    }));
  }, [data?.students]);
  const columns = (0, import_react63.useMemo)(
    () => createTableColumns(handleCorrectActivity),
    [handleCorrectActivity]
  );
  const handleTableParamsChange = (params) => {
    if (params.page) setPage(params.page);
    if (params.limit) setLimit(params.limit);
    if (params.sortBy !== void 0) {
      const sortByMap = {
        studentName: "name",
        answeredAt: "answeredAt",
        score: "score"
      };
      setSortBy(params.sortBy ? sortByMap[params.sortBy] : void 0);
    }
    if (params.sortOrder !== void 0) {
      setSortOrder(params.sortOrder);
    }
  };
  const handleViewActivity = () => {
    if (onViewActivity) {
      onViewActivity();
    }
  };
  const handleBack = () => {
    if (onBack) {
      onBack();
    }
  };
  const subjectEnum = data?.activity?.subjectName && mapSubjectNameToEnum2 ? mapSubjectNameToEnum2(data.activity.subjectName) : null;
  const subjectInfo = subjectEnum ? getSubjectInfo(subjectEnum) : null;
  if (loading && !data) {
    return /* @__PURE__ */ (0, import_jsx_runtime82.jsx)("div", { className: "flex flex-col w-full h-auto relative justify-center items-center mb-5 overflow-hidden", children: /* @__PURE__ */ (0, import_jsx_runtime82.jsxs)("div", { className: "flex flex-col w-full h-full max-w-[1150px] mx-auto z-10 lg:px-0 px-4 pt-4 gap-4", children: [
      /* @__PURE__ */ (0, import_jsx_runtime82.jsx)("div", { className: "flex items-center gap-2 py-4", children: /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(SkeletonText, { width: 100, height: 14 }) }),
      /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(SkeletonRounded, { className: "w-full h-[120px]" }),
      /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(
        "div",
        {
          className: cn(
            "grid gap-5",
            isMobile ? "grid-cols-2" : "grid-cols-5"
          ),
          children: [
            "total-students",
            "completed",
            "pending",
            "avg-score",
            "avg-time"
          ].map((id) => /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(SkeletonRounded, { className: "w-full h-[150px]" }, id))
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime82.jsx)("div", { className: "w-full bg-background rounded-xl p-6", children: /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(SkeletonTable, { rows: 5, columns: 6, showHeader: true }) })
    ] }) });
  }
  if (error || !data) {
    return /* @__PURE__ */ (0, import_jsx_runtime82.jsx)("div", { className: "flex flex-col w-full h-auto relative justify-center items-center mb-5", children: /* @__PURE__ */ (0, import_jsx_runtime82.jsx)("div", { className: "flex flex-col w-full h-full max-w-[1150px] mx-auto z-10 lg:px-0 px-4 pt-4", children: /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(
      EmptyState_default,
      {
        image: emptyStateImage,
        title: "Erro ao carregar detalhes",
        description: error || "N\xE3o foi poss\xEDvel carregar os detalhes da atividade"
      }
    ) }) });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime82.jsxs)("div", { className: "flex flex-col w-full h-auto relative justify-center items-center mb-5 overflow-hidden", children: [
    /* @__PURE__ */ (0, import_jsx_runtime82.jsxs)("div", { className: "flex flex-col w-full h-full max-w-[1150px] mx-auto z-10 lg:px-0 px-4 pt-4 gap-4", children: [
      /* @__PURE__ */ (0, import_jsx_runtime82.jsxs)("div", { className: "flex items-center gap-2 py-4", children: [
        /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(
          "button",
          {
            onClick: handleBack,
            className: "text-text-500 hover:text-text-700 text-sm font-bold underline",
            children: "Atividades"
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(import_phosphor_react43.CaretRight, { size: 16, className: "text-text-500" }),
        /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Text_default, { className: "text-text-950 text-sm font-bold", children: data.activity?.title || "Atividade" })
      ] }),
      data.activity && /* @__PURE__ */ (0, import_jsx_runtime82.jsx)("div", { className: "bg-background rounded-xl p-4 flex flex-col gap-2", children: /* @__PURE__ */ (0, import_jsx_runtime82.jsxs)("div", { className: "flex justify-between items-start", children: [
        /* @__PURE__ */ (0, import_jsx_runtime82.jsxs)("div", { className: "flex flex-col gap-2", children: [
          /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Text_default, { className: "text-2xl font-bold text-text-950", children: data.activity.title }),
          /* @__PURE__ */ (0, import_jsx_runtime82.jsxs)("div", { className: "flex items-center gap-2 flex-wrap", children: [
            /* @__PURE__ */ (0, import_jsx_runtime82.jsxs)(Text_default, { className: "text-sm text-text-500", children: [
              "In\xEDcio",
              " ",
              data.activity.startDate ? formatDateToBrazilian(data.activity.startDate) : "00/00/0000"
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime82.jsx)("span", { className: "w-1 h-1 rounded-full bg-text-500" }),
            /* @__PURE__ */ (0, import_jsx_runtime82.jsxs)(Text_default, { className: "text-sm text-text-500", children: [
              "Prazo final",
              " ",
              data.activity.finalDate ? formatDateToBrazilian(data.activity.finalDate) : "00/00/0000"
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime82.jsx)("span", { className: "w-1 h-1 rounded-full bg-text-500" }),
            /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Text_default, { className: "text-sm text-text-500", children: data.activity.schoolName }),
            /* @__PURE__ */ (0, import_jsx_runtime82.jsx)("span", { className: "w-1 h-1 rounded-full bg-text-500" }),
            /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Text_default, { className: "text-sm text-text-500", children: data.activity.year }),
            /* @__PURE__ */ (0, import_jsx_runtime82.jsx)("span", { className: "w-1 h-1 rounded-full bg-text-500" }),
            subjectInfo ? /* @__PURE__ */ (0, import_jsx_runtime82.jsxs)("div", { className: "flex items-center gap-1", children: [
              /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(
                "span",
                {
                  className: cn(
                    "w-[21px] h-[21px] flex items-center justify-center rounded-sm text-text-950 shrink-0",
                    subjectInfo.colorClass
                  ),
                  children: subjectInfo.icon
                }
              ),
              /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Text_default, { className: "text-sm text-text-500", children: data.activity.subjectName })
            ] }) : /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Text_default, { className: "text-sm text-text-500", children: data.activity.subjectName }),
            /* @__PURE__ */ (0, import_jsx_runtime82.jsx)("span", { className: "w-1 h-1 rounded-full bg-text-500" }),
            /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Text_default, { className: "text-sm text-text-500", children: data.activity.className })
          ] })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime82.jsxs)(
          Button_default,
          {
            size: "small",
            onClick: handleViewActivity,
            className: "bg-primary-950 text-text gap-2",
            children: [
              /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(import_phosphor_react43.File, { size: 16 }),
              "Ver atividade"
            ]
          }
        )
      ] }) }),
      /* @__PURE__ */ (0, import_jsx_runtime82.jsxs)(
        "div",
        {
          className: cn("grid gap-5", isMobile ? "grid-cols-2" : "grid-cols-5"),
          children: [
            /* @__PURE__ */ (0, import_jsx_runtime82.jsx)("div", { className: "border border-border-50 rounded-xl py-4 px-0 flex flex-col items-center justify-center gap-2 bg-primary-50", children: /* @__PURE__ */ (0, import_jsx_runtime82.jsxs)("div", { className: "relative w-[90px] h-[90px]", children: [
              /* @__PURE__ */ (0, import_jsx_runtime82.jsxs)("svg", { className: "w-full h-full transform -rotate-90", children: [
                /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(
                  "circle",
                  {
                    cx: "45",
                    cy: "45",
                    r: "40",
                    stroke: "var(--color-primary-100)",
                    strokeWidth: "8",
                    fill: "none"
                  }
                ),
                /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(
                  "circle",
                  {
                    cx: "45",
                    cy: "45",
                    r: "40",
                    stroke: "var(--color-primary-700)",
                    strokeWidth: "8",
                    fill: "none",
                    strokeDasharray: `${data.generalStats.completionPercentage / 100 * 251.2} 251.2`,
                    strokeLinecap: "round"
                  }
                )
              ] }),
              /* @__PURE__ */ (0, import_jsx_runtime82.jsxs)("div", { className: "absolute inset-0 flex flex-col items-center justify-center", children: [
                /* @__PURE__ */ (0, import_jsx_runtime82.jsxs)(Text_default, { className: "text-xl font-medium text-primary-600", children: [
                  Math.round(data.generalStats.completionPercentage),
                  "%"
                ] }),
                /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Text_default, { className: "text-2xs font-bold text-text-600 uppercase", children: "Conclu\xEDdo" })
              ] })
            ] }) }),
            /* @__PURE__ */ (0, import_jsx_runtime82.jsxs)("div", { className: "border border-border-50 rounded-xl py-4 px-3 flex flex-col items-center justify-center gap-1 bg-warning-background", children: [
              /* @__PURE__ */ (0, import_jsx_runtime82.jsx)("div", { className: "w-[30px] h-[30px] rounded-2xl flex items-center justify-center bg-warning-300", children: /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(import_phosphor_react43.Star, { size: 16, className: "text-white", weight: "regular" }) }),
              /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Text_default, { className: "text-2xs font-bold uppercase text-center text-warning-600", children: "M\xE9dia da Turma" }),
              /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Text_default, { className: "text-xl font-bold text-warning-600", children: data.generalStats.averageScore.toFixed(1) })
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime82.jsxs)("div", { className: "border border-border-50 rounded-xl py-2 px-3 flex flex-col items-center justify-center gap-1 bg-success-200", children: [
              /* @__PURE__ */ (0, import_jsx_runtime82.jsx)("div", { className: "w-[30px] h-[30px] rounded-2xl flex items-center justify-center bg-indicator-positive", children: /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(import_phosphor_react43.Medal, { size: 16, className: "text-text-950", weight: "regular" }) }),
              /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Text_default, { className: "text-2xs font-bold uppercase text-center text-success-700", children: "Quest\xF5es com mais acertos" }),
              /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Text_default, { className: "text-xl font-bold text-success-700", children: formatQuestionNumbers(data.questionStats.mostCorrect) })
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime82.jsxs)("div", { className: "border border-border-50 rounded-xl py-2 px-3 flex flex-col items-center justify-center gap-1 bg-error-100", children: [
              /* @__PURE__ */ (0, import_jsx_runtime82.jsx)("div", { className: "w-[30px] h-[30px] rounded-2xl flex items-center justify-center bg-indicator-negative", children: /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(
                import_phosphor_react43.WarningCircle,
                {
                  size: 16,
                  className: "text-white",
                  weight: "regular"
                }
              ) }),
              /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Text_default, { className: "text-2xs font-bold uppercase text-center text-error-700", children: "Quest\xF5es com mais erros" }),
              /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Text_default, { className: "text-xl font-bold text-error-700", children: formatQuestionNumbers(data.questionStats.mostIncorrect) })
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime82.jsxs)("div", { className: "border border-border-50 rounded-xl py-2 px-3 flex flex-col items-center justify-center gap-1 bg-info-background", children: [
              /* @__PURE__ */ (0, import_jsx_runtime82.jsx)("div", { className: "w-[30px] h-[30px] rounded-2xl flex items-center justify-center bg-info-500", children: /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(
                import_phosphor_react43.WarningCircle,
                {
                  size: 16,
                  className: "text-white",
                  weight: "regular"
                }
              ) }),
              /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Text_default, { className: "text-2xs font-bold uppercase text-center text-info-700", children: "Quest\xF5es n\xE3o respondidas" }),
              /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Text_default, { className: "text-xl font-bold text-info-700", children: formatQuestionNumbers(data.questionStats.notAnswered) })
            ] })
          ]
        }
      ),
      correctionError && /* @__PURE__ */ (0, import_jsx_runtime82.jsxs)("div", { className: "w-full bg-error-50 border border-error-200 rounded-xl p-4 flex items-center gap-3", children: [
        /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(import_phosphor_react43.WarningCircle, { size: 20, className: "text-error-600", weight: "fill" }),
        /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Text_default, { className: "text-error-700 text-sm", children: correctionError })
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime82.jsx)("div", { className: "w-full bg-background rounded-xl p-6 space-y-4", children: /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(
        TableProvider,
        {
          data: tableData,
          headers: columns,
          loading: false,
          variant: "borderless",
          enableTableSort: true,
          enablePagination: true,
          paginationConfig: {
            itemLabel: "alunos",
            itemsPerPageOptions: [10, 20, 50],
            defaultItemsPerPage: 10,
            totalItems: data.pagination.total,
            totalPages: data.pagination.totalPages
          },
          emptyState: {
            component: /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(
              EmptyState_default,
              {
                image: emptyStateImage,
                title: "Nenhum aluno encontrado",
                description: "N\xE3o h\xE1 alunos matriculados nesta atividade"
              }
            )
          },
          onParamsChange: handleTableParamsChange,
          children: ({ table, pagination }) => /* @__PURE__ */ (0, import_jsx_runtime82.jsxs)(import_jsx_runtime82.Fragment, { children: [
            table,
            pagination
          ] })
        }
      ) })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(
      CorrectActivityModal_default,
      {
        isOpen: isModalOpen,
        onClose: handleCloseModal,
        data: correctionData,
        isViewOnly: isViewOnlyModal,
        onObservationSubmit: handleObservationSubmit
      }
    )
  ] });
};

// src/components/Support/Support.tsx
var import_react66 = require("react");
var import_react_hook_form = require("react-hook-form");
var import_zod2 = require("@hookform/resolvers/zod");
var import_react67 = require("@phosphor-icons/react");
var import_dayjs2 = __toESM(require("dayjs"));

// src/components/Support/schema/index.ts
var import_zod = require("zod");
var supportSchema = import_zod.z.object({
  // Tipo de problema selecionado
  problemType: import_zod.z.enum(["tecnico", "acesso", "outros"], {
    // istanbul ignore next - errorMap é testado em runtime pelo zod real
    errorMap: (
      /* istanbul ignore next */
      () => ({
        message: "Campo obrigat\xF3rio! Por favor, preencha este campo para continuar."
      })
    )
  }),
  // Título do problema
  title: import_zod.z.string().min(1, "Campo obrigat\xF3rio! Por favor, preencha este campo para continuar.").min(5, "T\xEDtulo deve ter pelo menos 5 caracteres").max(100, "T\xEDtulo deve ter no m\xE1ximo 100 caracteres").trim(),
  // Descrição do problema
  description: import_zod.z.string().min(1, "Campo obrigat\xF3rio! Por favor, preencha este campo para continuar.").min(10, "Descri\xE7\xE3o deve ter pelo menos 10 caracteres").max(1e3, "Descri\xE7\xE3o deve ter no m\xE1ximo 1000 caracteres").trim()
});

// src/components/Support/components/TicketModal.tsx
var import_react65 = require("react");
var import_dayjs = __toESM(require("dayjs"));
var import_pt_br = require("dayjs/locale/pt-br");

// src/types/support.ts
var SupportStatus = /* @__PURE__ */ ((SupportStatus2) => {
  SupportStatus2["ABERTO"] = "aberto";
  SupportStatus2["RESPONDIDO"] = "respondido";
  SupportStatus2["ENCERRADO"] = "encerrado";
  return SupportStatus2;
})(SupportStatus || {});
var SupportCategory = /* @__PURE__ */ ((SupportCategory2) => {
  SupportCategory2["ACESSO"] = "acesso";
  SupportCategory2["TECNICO"] = "tecnico";
  SupportCategory2["OUTROS"] = "outros";
  return SupportCategory2;
})(SupportCategory || {});
var getStatusBadgeAction = (status) => {
  switch (status) {
    case "aberto" /* ABERTO */:
      return "success";
    case "respondido" /* RESPONDIDO */:
      return "warning";
    case "encerrado" /* ENCERRADO */:
      return "info";
    default:
      return "info";
  }
};
var getStatusText = (status) => {
  switch (status) {
    case "aberto" /* ABERTO */:
      return "Aberto";
    case "respondido" /* RESPONDIDO */:
      return "Respondido";
    case "encerrado" /* ENCERRADO */:
      return "Encerrado";
    default:
      return status;
  }
};
var getCategoryText = (category) => {
  if (!category) return "";
  switch (category) {
    case "acesso" /* ACESSO */:
      return "Acesso";
    case "tecnico" /* TECNICO */:
      return "T\xE9cnico";
    case "outros" /* OUTROS */:
      return "Outros";
    default:
      return category;
  }
};
var mapApiStatusToInternal = (apiStatus) => {
  switch (apiStatus) {
    case "ABERTO":
      return "aberto" /* ABERTO */;
    case "PENDENTE":
      return "respondido" /* RESPONDIDO */;
    case "FECHADO":
      return "encerrado" /* ENCERRADO */;
    default:
      return "aberto" /* ABERTO */;
  }
};
var mapInternalStatusToApi = (internalStatus) => {
  switch (internalStatus) {
    case "aberto" /* ABERTO */:
      return "ABERTO";
    case "respondido" /* RESPONDIDO */:
      return "PENDENTE";
    case "encerrado" /* ENCERRADO */:
      return "FECHADO";
    default:
      return "ABERTO";
  }
};

// src/components/Support/utils/supportUtils.tsx
var import_react64 = require("@phosphor-icons/react");
var import_jsx_runtime83 = require("react/jsx-runtime");
var getCategoryIcon = (category, size = 16) => {
  if (!category) return null;
  switch (category) {
    case "acesso" /* ACESSO */:
      return /* @__PURE__ */ (0, import_jsx_runtime83.jsx)(import_react64.KeyIcon, { size });
    case "tecnico" /* TECNICO */:
      return /* @__PURE__ */ (0, import_jsx_runtime83.jsx)(import_react64.BugIcon, { size });
    case "outros" /* OUTROS */:
      return /* @__PURE__ */ (0, import_jsx_runtime83.jsx)(import_react64.InfoIcon, { size });
    default:
      return /* @__PURE__ */ (0, import_jsx_runtime83.jsx)(import_react64.InfoIcon, { size });
  }
};

// src/components/Support/components/TicketModal.tsx
var import_jsx_runtime84 = require("react/jsx-runtime");
import_dayjs.default.locale("pt-br");
var AnswerSkeleton = () => /* @__PURE__ */ (0, import_jsx_runtime84.jsxs)("div", { className: "bg-background p-4 space-y-6 rounded-xl", children: [
  /* @__PURE__ */ (0, import_jsx_runtime84.jsxs)("div", { className: "flex items-center space-x-6", children: [
    /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(SkeletonText, { width: "80px", height: 16 }),
    /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(SkeletonText, { width: "200px", height: 16 })
  ] }),
  /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(Divider_default, {}),
  /* @__PURE__ */ (0, import_jsx_runtime84.jsxs)("div", { className: "flex items-start space-x-6", children: [
    /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(SkeletonText, { width: "80px", height: 16 }),
    /* @__PURE__ */ (0, import_jsx_runtime84.jsxs)("div", { className: "flex-1 space-y-2", children: [
      /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(SkeletonText, { width: "100%", height: 16 }),
      /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(SkeletonText, { width: "80%", height: 16 }),
      /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(SkeletonText, { width: "60%", height: 16 })
    ] })
  ] })
] });
var TicketModal = ({
  ticket,
  isOpen,
  onClose,
  onTicketClose,
  apiClient,
  userId
}) => {
  const [showCloseConfirmation, setShowCloseConfirmation] = (0, import_react65.useState)(false);
  const [responseText, setResponseText] = (0, import_react65.useState)("");
  const [answers, setAnswers] = (0, import_react65.useState)([]);
  const [isSubmittingAnswer, setIsSubmittingAnswer] = (0, import_react65.useState)(false);
  const [isLoadingAnswers, setIsLoadingAnswers] = (0, import_react65.useState)(false);
  const handleCloseTicket = () => {
    onTicketClose?.(ticket.id);
    setShowCloseConfirmation(false);
    onClose();
  };
  const fetchAnswers = (0, import_react65.useCallback)(async () => {
    if (!ticket.id || ticket.status !== "respondido" /* RESPONDIDO */) return;
    setIsLoadingAnswers(true);
    try {
      const response = await apiClient.get(
        `/support/answer/${ticket.id}`
      );
      setAnswers(response.data.data || []);
    } catch (error) {
      console.error("Erro ao buscar respostas:", error);
      setAnswers([]);
    } finally {
      setIsLoadingAnswers(false);
    }
  }, [ticket.id, ticket.status, apiClient]);
  const handleSubmitAnswer = async () => {
    if (!responseText.trim() || !userId || !ticket.id) {
      return;
    }
    setIsSubmittingAnswer(true);
    try {
      const requestData = {
        userId,
        supportId: ticket.id,
        answer: responseText.trim()
      };
      await apiClient.post(
        "/support/answer",
        requestData
      );
      setResponseText("");
      await fetchAnswers();
    } catch (error) {
      console.error("Erro ao enviar resposta:", error);
    } finally {
      setIsSubmittingAnswer(false);
    }
  };
  const canCloseTicket = ticket.status !== "encerrado" /* ENCERRADO */;
  (0, import_react65.useEffect)(() => {
    if (isOpen) {
      setResponseText("");
      (async () => {
        await fetchAnswers();
      })().catch((error) => {
        console.error("Erro ao carregar respostas:", error);
      });
    } else {
      setAnswers([]);
    }
  }, [isOpen, fetchAnswers]);
  return /* @__PURE__ */ (0, import_jsx_runtime84.jsxs)(import_jsx_runtime84.Fragment, { children: [
    /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(
      Modal_default,
      {
        isOpen,
        onClose,
        title: `Pedido: ${ticket.title}`,
        size: "lg",
        hideCloseButton: false,
        closeOnEscape: true,
        "data-testid": "ticket-modal",
        children: /* @__PURE__ */ (0, import_jsx_runtime84.jsxs)("div", { className: "flex flex-col h-full max-h-[80vh]", children: [
          /* @__PURE__ */ (0, import_jsx_runtime84.jsxs)("div", { className: "flex justify-between items-center mb-3", children: [
            /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(Text_default, { size: "md", weight: "bold", className: "text-text-950", children: "Detalhes" }),
            canCloseTicket && /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(
              Button_default,
              {
                variant: "outline",
                size: "small",
                action: "negative",
                onClick: () => setShowCloseConfirmation(true),
                children: "Encerrar Pedido"
              }
            )
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime84.jsxs)("div", { className: "flex-1 overflow-y-auto pr-2 space-y-6", children: [
            /* @__PURE__ */ (0, import_jsx_runtime84.jsxs)("div", { className: "bg-background p-4 space-y-6 rounded-xl", children: [
              /* @__PURE__ */ (0, import_jsx_runtime84.jsxs)("div", { className: "flex items-center space-x-6", children: [
                /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(
                  Text_default,
                  {
                    size: "md",
                    weight: "semibold",
                    className: "text-text-700 w-20",
                    children: "ID"
                  }
                ),
                /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(Text_default, { size: "md", weight: "normal", className: "text-text-600", children: ticket.id })
              ] }),
              /* @__PURE__ */ (0, import_jsx_runtime84.jsxs)("div", { className: "flex items-center space-x-6", children: [
                /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(
                  Text_default,
                  {
                    size: "md",
                    weight: "semibold",
                    className: "text-text-700 w-20",
                    children: "Aberto em"
                  }
                ),
                /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(Text_default, { size: "md", weight: "normal", className: "text-text-600", children: (0, import_dayjs.default)(ticket.createdAt).format("DD MMMM YYYY, [\xE0s] HH[h]") })
              ] }),
              /* @__PURE__ */ (0, import_jsx_runtime84.jsxs)("div", { className: "flex items-center space-x-6", children: [
                /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(
                  Text_default,
                  {
                    size: "md",
                    weight: "semibold",
                    className: "text-text-700 w-20",
                    children: "Status"
                  }
                ),
                /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(
                  Badge_default,
                  {
                    variant: "solid",
                    size: "small",
                    action: getStatusBadgeAction(ticket.status),
                    className: "w-fit",
                    children: getStatusText(ticket.status)
                  }
                )
              ] }),
              /* @__PURE__ */ (0, import_jsx_runtime84.jsxs)("div", { className: "flex items-center space-x-6", children: [
                /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(
                  Text_default,
                  {
                    size: "md",
                    weight: "semibold",
                    className: "text-text-700 w-20",
                    children: "Tipo"
                  }
                ),
                /* @__PURE__ */ (0, import_jsx_runtime84.jsxs)(
                  Badge_default,
                  {
                    variant: "solid",
                    size: "small",
                    action: "muted",
                    className: "w-fit",
                    children: [
                      getCategoryIcon(ticket.category),
                      getCategoryText(ticket.category)
                    ]
                  }
                )
              ] }),
              /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(Divider_default, {}),
              /* @__PURE__ */ (0, import_jsx_runtime84.jsxs)("div", { className: "flex items-start space-x-6", children: [
                /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(
                  Text_default,
                  {
                    size: "md",
                    weight: "semibold",
                    className: "text-text-700 w-20",
                    children: "Descri\xE7\xE3o"
                  }
                ),
                ticket.description && /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(Text_default, { size: "md", weight: "normal", className: "text-text-600", children: ticket.description })
              ] })
            ] }),
            ticket.status === "respondido" /* RESPONDIDO */ && isLoadingAnswers && /* @__PURE__ */ (0, import_jsx_runtime84.jsxs)(import_jsx_runtime84.Fragment, { children: [
              /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(Text_default, { size: "md", weight: "bold", className: "text-text-950 my-6", children: "Resposta de Suporte T\xE9cnico" }),
              /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(AnswerSkeleton, {})
            ] }),
            !isLoadingAnswers && answers.some((answer) => answer.userId !== userId) && /* @__PURE__ */ (0, import_jsx_runtime84.jsxs)(import_jsx_runtime84.Fragment, { children: [
              /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(Text_default, { size: "md", weight: "bold", className: "text-text-950 my-6", children: "Resposta de Suporte T\xE9cnico" }),
              answers.filter((answer) => answer.userId !== userId).sort(
                (a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
              ).slice(0, 1).map((answer) => /* @__PURE__ */ (0, import_jsx_runtime84.jsxs)(
                "div",
                {
                  className: "bg-background p-4 space-y-6 rounded-xl",
                  children: [
                    /* @__PURE__ */ (0, import_jsx_runtime84.jsxs)("div", { className: "flex items-center space-x-6", children: [
                      /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(
                        Text_default,
                        {
                          size: "md",
                          weight: "semibold",
                          className: "text-text-700 w-20",
                          children: "Recebido"
                        }
                      ),
                      /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(
                        Text_default,
                        {
                          size: "md",
                          weight: "normal",
                          className: "text-text-600",
                          children: (0, import_dayjs.default)(answer.createdAt).format(
                            "DD MMMM YYYY, [\xE0s] HH[h]"
                          )
                        }
                      )
                    ] }),
                    /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(Divider_default, {}),
                    /* @__PURE__ */ (0, import_jsx_runtime84.jsxs)("div", { className: "flex items-start space-x-6", children: [
                      /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(
                        Text_default,
                        {
                          size: "md",
                          weight: "semibold",
                          className: "text-text-700 w-20",
                          children: "Resposta"
                        }
                      ),
                      /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(
                        Text_default,
                        {
                          size: "md",
                          weight: "normal",
                          className: "text-text-600",
                          children: answer.answer
                        }
                      )
                    ] })
                  ]
                },
                answer.id
              ))
            ] }),
            !isLoadingAnswers && answers.some((answer) => answer.userId === userId) && /* @__PURE__ */ (0, import_jsx_runtime84.jsxs)(import_jsx_runtime84.Fragment, { children: [
              /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(Text_default, { size: "md", weight: "bold", className: "text-text-950 my-6", children: "Resposta enviada" }),
              answers.filter((answer) => answer.userId === userId).sort(
                (a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
              ).slice(0, 1).map((answer) => /* @__PURE__ */ (0, import_jsx_runtime84.jsxs)(
                "div",
                {
                  className: "bg-background p-4 space-y-6 rounded-xl",
                  children: [
                    /* @__PURE__ */ (0, import_jsx_runtime84.jsxs)("div", { className: "flex items-center space-x-6", children: [
                      /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(
                        Text_default,
                        {
                          size: "md",
                          weight: "semibold",
                          className: "text-text-700 w-20",
                          children: "Enviada"
                        }
                      ),
                      /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(
                        Text_default,
                        {
                          size: "md",
                          weight: "normal",
                          className: "text-text-600",
                          children: (0, import_dayjs.default)(answer.createdAt).format(
                            "DD MMMM YYYY, [\xE0s] HH[h]"
                          )
                        }
                      )
                    ] }),
                    /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(Divider_default, {}),
                    /* @__PURE__ */ (0, import_jsx_runtime84.jsxs)("div", { className: "flex items-start space-x-6", children: [
                      /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(
                        Text_default,
                        {
                          size: "md",
                          weight: "semibold",
                          className: "text-text-700 w-20",
                          children: "Resposta"
                        }
                      ),
                      /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(
                        Text_default,
                        {
                          size: "md",
                          weight: "normal",
                          className: "text-text-600",
                          children: answer.answer
                        }
                      )
                    ] })
                  ]
                },
                answer.id
              ))
            ] }),
            !isLoadingAnswers && answers.some((answer) => answer.userId !== userId) && /* @__PURE__ */ (0, import_jsx_runtime84.jsxs)(import_jsx_runtime84.Fragment, { children: [
              /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(Text_default, { size: "lg", weight: "bold", className: "text-text-950 my-6", children: "Responder" }),
              /* @__PURE__ */ (0, import_jsx_runtime84.jsxs)("div", { className: "space-y-4", children: [
                /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(
                  TextArea_default,
                  {
                    placeholder: "Detalhe o problema aqui.",
                    rows: 4,
                    className: "w-full",
                    value: responseText,
                    onChange: (e) => setResponseText(e.target.value)
                  }
                ),
                responseText.trim().length > 0 && /* @__PURE__ */ (0, import_jsx_runtime84.jsx)("div", { className: "flex justify-end", children: /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(
                  Button_default,
                  {
                    variant: "solid",
                    size: "medium",
                    onClick: handleSubmitAnswer,
                    disabled: isSubmittingAnswer,
                    children: isSubmittingAnswer ? "Enviando..." : "Enviar"
                  }
                ) })
              ] })
            ] })
          ] })
        ] })
      }
    ),
    /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(
      Modal_default,
      {
        isOpen: showCloseConfirmation,
        onClose: () => setShowCloseConfirmation(false),
        title: "Encerrar pedido?",
        size: "md",
        hideCloseButton: false,
        closeOnEscape: true,
        "data-testid": "close-ticket-modal",
        children: /* @__PURE__ */ (0, import_jsx_runtime84.jsxs)("div", { className: "space-y-6", children: [
          /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(Text_default, { size: "sm", weight: "normal", className: "text-text-700", children: "Ao encerrar este pedido, ele ser\xE1 fechado e n\xE3o poder\xE1 mais ser atualizado." }),
          /* @__PURE__ */ (0, import_jsx_runtime84.jsxs)("div", { className: "flex gap-3 justify-end", children: [
            /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(
              Button_default,
              {
                variant: "outline",
                size: "medium",
                onClick: () => setShowCloseConfirmation(false),
                children: "Cancelar"
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(
              Button_default,
              {
                variant: "solid",
                size: "medium",
                action: "negative",
                onClick: handleCloseTicket,
                children: "Encerrar"
              }
            )
          ] })
        ] })
      }
    )
  ] });
};

// src/assets/img/suporthistory.png
var suporthistory_default = "./suporthistory-W5LBGAUP.png";

// src/components/Support/Support.tsx
var import_jsx_runtime85 = require("react/jsx-runtime");
var TicketCard = ({
  ticket,
  onTicketClick
}) => /* @__PURE__ */ (0, import_jsx_runtime85.jsxs)(
  "button",
  {
    type: "button",
    className: "flex items-center justify-between p-4 bg-background rounded-xl cursor-pointer w-full text-left hover:bg-background-50 focus:outline-none focus:ring-2 focus:ring-primary-500 focus:ring-offset-2",
    onClick: () => onTicketClick(ticket),
    children: [
      /* @__PURE__ */ (0, import_jsx_runtime85.jsx)("div", { className: "flex flex-col", children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Text_default, { size: "xs", weight: "bold", className: "text-text-900", children: ticket.title }) }),
      /* @__PURE__ */ (0, import_jsx_runtime85.jsxs)("div", { className: "flex items-center gap-3", children: [
        /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(
          Badge_default,
          {
            variant: "solid",
            className: "flex items-center gap-1",
            action: getStatusBadgeAction(ticket.status),
            children: getStatusText(ticket.status)
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime85.jsxs)(Badge_default, { variant: "solid", className: "flex items-center gap-1", action: "muted", children: [
          getCategoryIcon(ticket.category, 18),
          getCategoryText(ticket.category)
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(import_react67.CaretRightIcon, { size: 24, className: "text-text-800" })
      ] })
    ]
  },
  ticket.id
);
var TicketGroup = ({
  date,
  tickets,
  onTicketClick
}) => /* @__PURE__ */ (0, import_jsx_runtime85.jsxs)("div", { className: "space-y-4", children: [
  /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Text_default, { size: "md", weight: "bold", className: "text-text-900", children: (0, import_dayjs2.default)(date).format("DD MMM YYYY") }),
  /* @__PURE__ */ (0, import_jsx_runtime85.jsx)("div", { className: "space-y-3", children: tickets.map((ticket) => /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(
    TicketCard,
    {
      ticket,
      onTicketClick
    },
    ticket.id
  )) })
] }, date);
var EmptyState2 = ({ imageSrc }) => /* @__PURE__ */ (0, import_jsx_runtime85.jsxs)("div", { className: "flex flex-row justify-center items-center mt-48", children: [
  imageSrc && /* @__PURE__ */ (0, import_jsx_runtime85.jsx)("img", { src: imageSrc, alt: "Imagem de suporte" }),
  /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Text_default, { size: "3xl", weight: "semibold", children: "Nenhum pedido encontrado." })
] });
var TicketSkeleton = () => /* @__PURE__ */ (0, import_jsx_runtime85.jsx)("div", { className: "space-y-6", children: [0, 1].map((groupIndex) => /* @__PURE__ */ (0, import_jsx_runtime85.jsxs)("div", { className: "space-y-4", children: [
  /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(SkeletonText, { width: "150px", height: 20 }),
  /* @__PURE__ */ (0, import_jsx_runtime85.jsx)("div", { className: "space-y-3", children: [0, 1].map((ticketIndex) => /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(
    SkeletonRounded,
    {
      width: "100%",
      height: 72,
      className: "p-4"
    },
    ticketIndex
  )) })
] }, groupIndex)) });
var Support = ({
  apiClient,
  userId,
  emptyStateImage,
  title = "Suporte",
  onTicketCreated,
  onTicketClosed
}) => {
  const [activeTab, setActiveTab] = (0, import_react66.useState)("criar-pedido");
  const [selectedProblem, setSelectedProblem] = (0, import_react66.useState)(null);
  const [statusFilter, setStatusFilter] = (0, import_react66.useState)("todos");
  const [categoryFilter, setCategoryFilter] = (0, import_react66.useState)("todos");
  const [selectedTicket, setSelectedTicket] = (0, import_react66.useState)(
    null
  );
  const [isModalOpen, setIsModalOpen] = (0, import_react66.useState)(false);
  const [submitError, setSubmitError] = (0, import_react66.useState)(null);
  const [showSuccessToast, setShowSuccessToast] = (0, import_react66.useState)(false);
  const [showCloseSuccessToast, setShowCloseSuccessToast] = (0, import_react66.useState)(false);
  const [showCloseErrorToast, setShowCloseErrorToast] = (0, import_react66.useState)(false);
  const [allTickets, setAllTickets] = (0, import_react66.useState)([]);
  const [loadingTickets, setLoadingTickets] = (0, import_react66.useState)(false);
  const [currentPage, setCurrentPage] = (0, import_react66.useState)(1);
  const ITEMS_PER_PAGE = 10;
  const handlePrevPage = () => {
    if (currentPage > 1) {
      setCurrentPage(currentPage - 1);
    }
  };
  const handleNextPage = () => {
    const totalPages2 = Math.ceil(filteredTickets.length / ITEMS_PER_PAGE);
    if (currentPage < totalPages2) {
      setCurrentPage(currentPage + 1);
    }
  };
  (0, import_react66.useEffect)(() => {
    if (activeTab === "historico") {
      fetchTickets(statusFilter);
      setCurrentPage(1);
    }
  }, [activeTab, statusFilter]);
  (0, import_react66.useEffect)(() => {
    setCurrentPage(1);
  }, [categoryFilter]);
  const convertApiTicketToComponent = (apiTicket) => {
    return {
      id: apiTicket.id,
      title: apiTicket.subject,
      status: mapApiStatusToInternal(apiTicket.status),
      createdAt: apiTicket.createdAt,
      category: apiTicket.type,
      description: apiTicket.description
    };
  };
  const filteredTickets = allTickets.map(convertApiTicketToComponent).filter((ticket) => {
    const categoryMatch = categoryFilter === "todos" || ticket.category === categoryFilter;
    return categoryMatch;
  }).sort(
    (a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
  );
  const totalPages = Math.ceil(filteredTickets.length / ITEMS_PER_PAGE);
  const startIndex = (currentPage - 1) * ITEMS_PER_PAGE;
  const endIndex = startIndex + ITEMS_PER_PAGE;
  const paginatedTickets = filteredTickets.slice(startIndex, endIndex);
  const groupedTickets = paginatedTickets.reduce(
    (groups, ticket) => {
      const date = (0, import_dayjs2.default)(ticket.createdAt).format("YYYY-MM-DD");
      if (!groups[date]) {
        groups[date] = [];
      }
      groups[date].push(ticket);
      return groups;
    },
    {}
  );
  const {
    register,
    handleSubmit,
    setValue,
    reset,
    formState: { errors, isSubmitting }
  } = (0, import_react_hook_form.useForm)({
    resolver: (0, import_zod2.zodResolver)(supportSchema),
    defaultValues: {
      problemType: void 0,
      title: "",
      description: ""
    }
  });
  const fetchTickets = async (status) => {
    setLoadingTickets(true);
    try {
      const params = new URLSearchParams({
        page: "1",
        limit: "100"
        // Buscar o máximo permitido pela API
      });
      if (status && status !== "todos") {
        const apiStatus = mapInternalStatusToApi(status);
        params.append("status", apiStatus);
      }
      const response = await apiClient.get(
        `/support?${params.toString()}`
      );
      setAllTickets(response.data.data.support);
    } catch (error) {
      console.error("Erro ao buscar tickets:", error);
      setAllTickets([]);
    } finally {
      setLoadingTickets(false);
    }
  };
  const handleProblemSelection = (type) => {
    setSelectedProblem(type);
    if (type) {
      setValue("problemType", type, { shouldValidate: true });
    }
  };
  const onSubmit = async (data) => {
    setSubmitError(null);
    try {
      const requestData = {
        subject: data.title,
        description: data.description,
        type: data.problemType
      };
      await apiClient.post(
        "/support",
        requestData
      );
      setShowSuccessToast(true);
      setTimeout(() => setShowSuccessToast(false), 4e3);
      setSelectedProblem(null);
      reset();
      setActiveTab("historico");
      fetchTickets(statusFilter);
      onTicketCreated?.();
    } catch (error) {
      console.error("Erro ao criar ticket de suporte:", error);
      setSubmitError("Erro ao criar ticket. Tente novamente.");
    }
  };
  const handleTicketClick = (ticket) => {
    setSelectedTicket(ticket);
    setIsModalOpen(true);
  };
  const handleModalClose = () => {
    setIsModalOpen(false);
    setSelectedTicket(null);
  };
  const handleTicketClose = async (ticketId) => {
    try {
      await apiClient.patch(`/support/${ticketId}`, {
        status: mapInternalStatusToApi("encerrado" /* ENCERRADO */)
      });
      setShowCloseSuccessToast(true);
      setTimeout(() => setShowCloseSuccessToast(false), 4e3);
      if (activeTab === "historico") {
        fetchTickets(statusFilter);
      }
      onTicketClosed?.();
    } catch (error) {
      console.error("Erro ao encerrar ticket:", error);
      setShowCloseErrorToast(true);
      setTimeout(() => setShowCloseErrorToast(false), 4e3);
    }
  };
  const problemTypes = [
    {
      id: "tecnico" /* TECNICO */,
      title: "T\xE9cnico",
      icon: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(import_react67.BugIcon, { size: 24 })
    },
    {
      id: "acesso" /* ACESSO */,
      title: "Acesso",
      icon: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(import_react67.KeyIcon, { size: 24 })
    },
    {
      id: "outros" /* OUTROS */,
      title: "Outros",
      icon: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(import_react67.InfoIcon, { size: 24 })
    }
  ];
  const emptyImage = emptyStateImage || suporthistory_default;
  return /* @__PURE__ */ (0, import_jsx_runtime85.jsxs)("div", { className: "flex flex-col w-full h-full relative justify-start items-center mb-5 overflow-y-auto", children: [
    /* @__PURE__ */ (0, import_jsx_runtime85.jsx)("div", { className: "flex flex-col w-full h-full max-w-[992px] z-10 lg:px-0 px-4", children: /* @__PURE__ */ (0, import_jsx_runtime85.jsxs)("div", { className: "space-y-4", children: [
      /* @__PURE__ */ (0, import_jsx_runtime85.jsxs)("div", { className: "flex w-full mb-4 flex-row items-center justify-between not-lg:gap-4 lg:gap-6", children: [
        /* @__PURE__ */ (0, import_jsx_runtime85.jsx)("h1", { className: "font-bold leading-[28px] tracking-[0.2px] text-text-950 text-xl mt-4 sm:text-2xl sm:flex-1 sm:self-end sm:mt-0", children: title }),
        /* @__PURE__ */ (0, import_jsx_runtime85.jsx)("div", { className: "sm:flex-shrink-0 sm:self-end", children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(
          Menu_default,
          {
            value: activeTab,
            defaultValue: "criar-pedido",
            variant: "menu2",
            onValueChange: (value) => setActiveTab(value),
            className: "bg-transparent shadow-none px-0",
            children: /* @__PURE__ */ (0, import_jsx_runtime85.jsxs)(MenuContent, { variant: "menu2", children: [
              /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(
                MenuItem,
                {
                  variant: "menu2",
                  value: "criar-pedido",
                  className: "whitespace-nowrap px-17 not-sm:px-5",
                  children: "Criar Pedido"
                }
              ),
              /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(
                MenuItem,
                {
                  variant: "menu2",
                  value: "historico",
                  className: "whitespace-nowrap px-17 not-sm:px-5",
                  children: "Hist\xF3rico"
                }
              )
            ] })
          }
        ) })
      ] }),
      activeTab === "criar-pedido" && /* @__PURE__ */ (0, import_jsx_runtime85.jsxs)("div", { className: "space-y-2", children: [
        /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Text_default, { as: "h2", size: "md", weight: "bold", className: "text-text-900", children: "Selecione o tipo de problema" }),
        /* @__PURE__ */ (0, import_jsx_runtime85.jsx)("div", { className: "flex flex-col sm:flex-row gap-2 sm:gap-4", children: problemTypes.map((type) => /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(
          SelectionButton_default,
          {
            icon: type.icon,
            label: type.title,
            selected: selectedProblem === type.id,
            onClick: () => handleProblemSelection(type.id),
            className: "w-full p-4"
          },
          type.id
        )) }),
        errors.problemType && /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Text_default, { size: "sm", className: "text-red-500 mt-1", children: errors.problemType.message })
      ] }),
      selectedProblem && activeTab === "criar-pedido" && /* @__PURE__ */ (0, import_jsx_runtime85.jsxs)("form", { onSubmit: handleSubmit(onSubmit), className: "space-y-4", children: [
        /* @__PURE__ */ (0, import_jsx_runtime85.jsx)("div", { className: "space-y-1", children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(
          Input_default,
          {
            size: "large",
            variant: "rounded",
            label: "T\xEDtulo",
            placeholder: "Digite o t\xEDtulo",
            ...register("title"),
            errorMessage: errors.title?.message
          }
        ) }),
        /* @__PURE__ */ (0, import_jsx_runtime85.jsx)("div", { className: "space-y-1", children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(
          TextArea_default,
          {
            size: "large",
            label: "Descri\xE7\xE3o",
            placeholder: "Descreva o problema aqui",
            ...register("description"),
            errorMessage: errors.description?.message
          }
        ) }),
        /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(
          Button_default,
          {
            size: "large",
            className: "float-end mt-10",
            type: "submit",
            disabled: isSubmitting,
            children: isSubmitting ? "Enviando..." : "Enviar Pedido"
          }
        ),
        submitError && /* @__PURE__ */ (0, import_jsx_runtime85.jsx)("div", { className: "mt-4 p-4 bg-red-100 border border-red-400 text-red-700 rounded", children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Text_default, { size: "sm", className: "text-red-700", children: submitError }) })
      ] }),
      activeTab === "historico" && /* @__PURE__ */ (0, import_jsx_runtime85.jsxs)("div", { className: "space-y-6", children: [
        /* @__PURE__ */ (0, import_jsx_runtime85.jsxs)("div", { className: "flex gap-4", children: [
          /* @__PURE__ */ (0, import_jsx_runtime85.jsx)("div", { className: "flex flex-col flex-1/2 space-y-1", children: /* @__PURE__ */ (0, import_jsx_runtime85.jsxs)(
            Select_default,
            {
              label: "Status",
              size: "large",
              value: statusFilter,
              onValueChange: setStatusFilter,
              children: [
                /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(SelectTrigger, { variant: "rounded", className: "", children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(SelectValue, { placeholder: "Todos" }) }),
                /* @__PURE__ */ (0, import_jsx_runtime85.jsxs)(SelectContent, { children: [
                  /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(SelectItem, { value: "todos", children: "Todos" }),
                  /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(SelectItem, { value: "aberto" /* ABERTO */, children: "Aberto" }),
                  /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(SelectItem, { value: "respondido" /* RESPONDIDO */, children: "Respondido" }),
                  /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(SelectItem, { value: "encerrado" /* ENCERRADO */, children: "Encerrado" })
                ] })
              ]
            }
          ) }),
          /* @__PURE__ */ (0, import_jsx_runtime85.jsx)("div", { className: "flex flex-col flex-1/2 space-y-1", children: /* @__PURE__ */ (0, import_jsx_runtime85.jsxs)(
            Select_default,
            {
              label: "Tipo",
              size: "large",
              value: categoryFilter,
              onValueChange: setCategoryFilter,
              children: [
                /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(SelectTrigger, { variant: "rounded", className: "", children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(SelectValue, { placeholder: "Todos" }) }),
                /* @__PURE__ */ (0, import_jsx_runtime85.jsxs)(SelectContent, { children: [
                  /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(SelectItem, { value: "todos", children: "Todos" }),
                  /* @__PURE__ */ (0, import_jsx_runtime85.jsxs)(SelectItem, { value: "tecnico" /* TECNICO */, children: [
                    /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(import_react67.BugIcon, { size: 16 }),
                    " T\xE9cnico"
                  ] }),
                  /* @__PURE__ */ (0, import_jsx_runtime85.jsxs)(SelectItem, { value: "acesso" /* ACESSO */, children: [
                    /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(import_react67.KeyIcon, { size: 16 }),
                    " Acesso"
                  ] }),
                  /* @__PURE__ */ (0, import_jsx_runtime85.jsxs)(SelectItem, { value: "outros" /* OUTROS */, children: [
                    /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(import_react67.InfoIcon, { size: 16 }),
                    " Outros"
                  ] })
                ] })
              ]
            }
          ) })
        ] }),
        (() => {
          if (loadingTickets) {
            return /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(TicketSkeleton, {});
          }
          if (Object.keys(groupedTickets).length === 0) {
            return /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(EmptyState2, { imageSrc: emptyImage });
          }
          return /* @__PURE__ */ (0, import_jsx_runtime85.jsx)("div", { className: "space-y-6", children: Object.entries(groupedTickets).sort(
            ([a], [b]) => new Date(b).getTime() - new Date(a).getTime()
          ).map(([date, tickets]) => /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(
            TicketGroup,
            {
              date,
              tickets,
              onTicketClick: handleTicketClick
            },
            date
          )) });
        })(),
        !loadingTickets && totalPages > 1 && /* @__PURE__ */ (0, import_jsx_runtime85.jsxs)("div", { className: "flex justify-center items-center gap-4 mt-6", children: [
          /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(
            Button_default,
            {
              variant: "outline",
              size: "small",
              onClick: handlePrevPage,
              disabled: currentPage === 1,
              children: "Anterior"
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime85.jsxs)(Text_default, { size: "sm", className: "text-text-600", children: [
            "P\xE1gina ",
            currentPage,
            " de ",
            totalPages
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(
            Button_default,
            {
              variant: "outline",
              size: "small",
              onClick: handleNextPage,
              disabled: currentPage === totalPages,
              children: "Pr\xF3xima"
            }
          )
        ] })
      ] })
    ] }) }),
    selectedTicket && /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(
      TicketModal,
      {
        ticket: selectedTicket,
        isOpen: isModalOpen,
        onClose: handleModalClose,
        onTicketClose: handleTicketClose,
        apiClient,
        userId
      }
    ),
    showSuccessToast && /* @__PURE__ */ (0, import_jsx_runtime85.jsx)("div", { className: "fixed top-4 left-1/2 transform -translate-x-1/2 z-50", children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(
      Toast_default,
      {
        title: "Pedido enviado!",
        description: "Agora voc\xEA pode acompanhar o andamento do seu pedido.",
        variant: "solid",
        onClose: () => setShowSuccessToast(false)
      }
    ) }),
    showCloseSuccessToast && /* @__PURE__ */ (0, import_jsx_runtime85.jsx)("div", { className: "fixed top-4 left-1/2 transform -translate-x-1/2 z-50", children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(
      Toast_default,
      {
        title: "Pedido encerrado!",
        description: "",
        variant: "solid",
        onClose: () => setShowCloseSuccessToast(false)
      }
    ) }),
    showCloseErrorToast && /* @__PURE__ */ (0, import_jsx_runtime85.jsx)("div", { className: "fixed top-4 left-1/2 transform -translate-x-1/2 z-50", children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(
      Toast_default,
      {
        title: "Erro ao encerrar pedido",
        description: "N\xE3o foi poss\xEDvel encerrar o pedido. Tente novamente.",
        variant: "solid",
        action: "warning",
        onClose: () => setShowCloseErrorToast(false)
      }
    ) })
  ] });
};
var Support_default = Support;

// src/components/SendActivityModal/SendActivityModal.tsx
var import_react68 = require("react");
var import_react69 = require("@phosphor-icons/react");

// src/components/SendActivityModal/hooks/useSendActivityModal.ts
var import_zustand16 = require("zustand");

// src/components/SendActivityModal/validation.ts
var import_zod3 = require("zod");
var ERROR_MESSAGES = {
  SUBTYPE_REQUIRED: "Campo obrigat\xF3rio! Por favor, selecione uma op\xE7\xE3o para continuar.",
  TITLE_REQUIRED: "Campo obrigat\xF3rio! Por favor, preencha este campo para continuar.",
  STUDENTS_REQUIRED: "Campo obrigat\xF3rio! Por favor, selecione pelo menos um aluno para continuar.",
  START_DATE_REQUIRED: "Campo obrigat\xF3rio! Por favor, preencha este campo para continuar.",
  FINAL_DATE_REQUIRED: "Campo obrigat\xF3rio! Por favor, preencha este campo para continuar.",
  FINAL_DATE_INVALID: "A data final deve ser maior ou igual \xE0 data inicial."
};
var activityStepSchema = import_zod3.z.object({
  subtype: import_zod3.z.enum(["TAREFA", "TRABALHO", "PROVA"], {
    errorMap: () => ({ message: ERROR_MESSAGES.SUBTYPE_REQUIRED })
  }),
  title: import_zod3.z.string({ required_error: ERROR_MESSAGES.TITLE_REQUIRED }).transform((val) => val.trim()).refine((val) => val.length > 0, {
    message: ERROR_MESSAGES.TITLE_REQUIRED
  }),
  notification: import_zod3.z.string().optional()
});
var recipientStepSchema = import_zod3.z.object({
  students: import_zod3.z.array(
    import_zod3.z.object({
      studentId: import_zod3.z.string(),
      userInstitutionId: import_zod3.z.string()
    }),
    {
      required_error: ERROR_MESSAGES.STUDENTS_REQUIRED,
      invalid_type_error: ERROR_MESSAGES.STUDENTS_REQUIRED
    }
  ).min(1, ERROR_MESSAGES.STUDENTS_REQUIRED)
});
var DATE_REGEX = /^\d{4}-\d{2}-\d{2}$/;
var TIME_REGEX = /^\d{2}:\d{2}$/;
var deadlineStepBaseSchema = import_zod3.z.object({
  startDate: import_zod3.z.string({
    required_error: ERROR_MESSAGES.START_DATE_REQUIRED,
    invalid_type_error: ERROR_MESSAGES.START_DATE_REQUIRED
  }).min(1, ERROR_MESSAGES.START_DATE_REQUIRED).regex(DATE_REGEX, ERROR_MESSAGES.START_DATE_REQUIRED),
  startTime: import_zod3.z.string().regex(TIME_REGEX).default("00:00"),
  finalDate: import_zod3.z.string({
    required_error: ERROR_MESSAGES.FINAL_DATE_REQUIRED,
    invalid_type_error: ERROR_MESSAGES.FINAL_DATE_REQUIRED
  }).min(1, ERROR_MESSAGES.FINAL_DATE_REQUIRED).regex(DATE_REGEX, ERROR_MESSAGES.FINAL_DATE_REQUIRED),
  finalTime: import_zod3.z.string().regex(TIME_REGEX).default("23:59"),
  canRetry: import_zod3.z.boolean().default(false)
});
var deadlineStepSchema = deadlineStepBaseSchema.refine(
  (data) => {
    const start = /* @__PURE__ */ new Date(`${data.startDate}T${data.startTime}`);
    const end = /* @__PURE__ */ new Date(`${data.finalDate}T${data.finalTime}`);
    return end >= start;
  },
  { message: ERROR_MESSAGES.FINAL_DATE_INVALID, path: ["finalDate"] }
);
function validateActivityStep(data) {
  const errors = {};
  const result = activityStepSchema.safeParse({
    subtype: data.subtype,
    title: data.title,
    notification: data.notification
  });
  if (!result.success) {
    result.error.issues.forEach((issue) => {
      const field = issue.path[0];
      if (field === "subtype" || field === "title") {
        errors[field] = issue.message;
      }
    });
  }
  return errors;
}
function validateRecipientStep(data) {
  const errors = {};
  const result = recipientStepSchema.safeParse({
    students: data.students ?? []
  });
  if (!result.success) {
    result.error.issues.forEach((issue) => {
      if (issue.path[0] === "students") {
        errors.students = issue.message;
      }
    });
  }
  return errors;
}
function validateDeadlineStep(data) {
  const errors = {};
  if (!data.startDate) {
    errors.startDate = ERROR_MESSAGES.START_DATE_REQUIRED;
  }
  if (!data.finalDate) {
    errors.finalDate = ERROR_MESSAGES.FINAL_DATE_REQUIRED;
  }
  if (data.startDate && data.finalDate) {
    const result = deadlineStepSchema.safeParse({
      startDate: data.startDate,
      startTime: data.startTime ?? "00:00",
      finalDate: data.finalDate,
      finalTime: data.finalTime ?? "23:59",
      canRetry: data.canRetry ?? false
    });
    if (!result.success) {
      result.error.issues.forEach((issue) => {
        const field = issue.path[0];
        if (field === "startDate" || field === "finalDate") {
          errors[field] = issue.message;
        }
      });
    }
  }
  return errors;
}
function validateStep(step, data) {
  switch (step) {
    case 1:
      return validateActivityStep(data);
    case 2:
      return validateRecipientStep(data);
    case 3:
      return validateDeadlineStep(data);
    default:
      return {};
  }
}
function isStepValid(step, data) {
  const errors = validateStep(step, data);
  return Object.keys(errors).length === 0;
}
function isFormValid(data) {
  return isStepValid(1, data) && isStepValid(2, data) && isStepValid(3, data);
}

// src/components/SendActivityModal/hooks/useSendActivityModal.ts
var initialState2 = {
  formData: {
    canRetry: false,
    startTime: "00:00",
    finalTime: "23:59"
  },
  currentStep: 1,
  completedSteps: [],
  errors: {},
  categories: []
};
function extractStudentsFromCategories(categories) {
  const studentsCategory = categories.find(
    (cat) => cat.key === "students" || cat.key === "alunos" || cat.key === "student"
  );
  if (!studentsCategory?.selectedIds || !studentsCategory.itens) {
    return [];
  }
  return studentsCategory.selectedIds.map((id) => {
    const student = studentsCategory.itens?.find((item) => item.id === id);
    if (student) {
      const rawStudentId = student.studentId;
      const rawUserInstId = student.userInstitutionId;
      const rawInstId = student.institutionId;
      const studentId = typeof rawStudentId === "string" || typeof rawStudentId === "number" ? String(rawStudentId) : student.id;
      let userInstitutionId = "";
      if (typeof rawUserInstId === "string" || typeof rawUserInstId === "number") {
        userInstitutionId = String(rawUserInstId);
      } else if (typeof rawInstId === "string" || typeof rawInstId === "number") {
        userInstitutionId = String(rawInstId);
      }
      if (!userInstitutionId) {
        return null;
      }
      return { studentId, userInstitutionId };
    }
    return null;
  }).filter(
    (s) => s !== null
  );
}
var useSendActivityModalStore = (0, import_zustand16.create)(
  (set, get) => ({
    ...initialState2,
    setFormData: (data) => {
      set((state) => ({
        formData: { ...state.formData, ...data }
      }));
    },
    goToStep: (step) => {
      if (step >= 1 && step <= 3) {
        set({ currentStep: step, errors: {} });
      }
    },
    nextStep: () => {
      const state = get();
      const isValid = state.validateCurrentStep();
      if (isValid && state.currentStep < 3) {
        set((prev) => ({
          currentStep: prev.currentStep + 1,
          completedSteps: prev.completedSteps.includes(prev.currentStep) ? prev.completedSteps : [...prev.completedSteps, prev.currentStep],
          errors: {}
        }));
        return true;
      }
      return isValid;
    },
    previousStep: () => {
      const state = get();
      if (state.currentStep > 1) {
        set({ currentStep: state.currentStep - 1, errors: {} });
      }
    },
    setErrors: (errors) => {
      set({ errors });
    },
    validateCurrentStep: () => {
      const state = get();
      let formDataToValidate = state.formData;
      let updatedFormData = state.formData;
      if (state.currentStep === 2 && state.categories.length > 0) {
        const students = extractStudentsFromCategories(state.categories);
        formDataToValidate = { ...state.formData, students };
        updatedFormData = formDataToValidate;
      }
      const errors = validateStep(state.currentStep, formDataToValidate);
      set({ formData: updatedFormData, errors });
      return Object.keys(errors).length === 0;
    },
    validateAllSteps: () => {
      const state = get();
      let formDataForStep2 = state.formData;
      if (state.categories.length > 0) {
        const students = extractStudentsFromCategories(state.categories);
        formDataForStep2 = { ...state.formData, students };
      }
      const errors1 = validateStep(1, state.formData);
      const errors2 = validateStep(2, formDataForStep2);
      const errors3 = validateStep(3, state.formData);
      const allErrors = { ...errors1, ...errors2, ...errors3 };
      set({ errors: allErrors });
      return Object.keys(allErrors).length === 0;
    },
    setCategories: (categories) => {
      const students = extractStudentsFromCategories(categories);
      set((state) => ({
        categories,
        formData: { ...state.formData, students }
      }));
    },
    reset: () => {
      set({
        ...initialState2,
        categories: []
      });
    }
  })
);
function useSendActivityModal() {
  return useSendActivityModalStore();
}

// src/components/SendActivityModal/types.ts
var ACTIVITY_TYPE_OPTIONS = [
  { value: "TAREFA", label: "Tarefa" },
  { value: "TRABALHO", label: "Trabalho" },
  { value: "PROVA", label: "Prova" }
];

// src/components/SendActivityModal/SendActivityModal.tsx
var import_jsx_runtime86 = require("react/jsx-runtime");
var STEPPER_STEPS = [
  { id: "activity", label: "Atividade", state: "pending" },
  { id: "recipient", label: "Destinat\xE1rio", state: "pending" },
  { id: "deadline", label: "Prazo", state: "pending" }
];
var SendActivityModal = ({
  isOpen,
  onClose,
  onSubmit,
  categories: initialCategories,
  onCategoriesChange,
  isLoading = false,
  onError,
  initialData
}) => {
  const store = useSendActivityModalStore();
  const reset = useSendActivityModalStore((state) => state.reset);
  const setCategories = useSendActivityModalStore(
    (state) => state.setCategories
  );
  const storeCategories = useSendActivityModalStore(
    (state) => state.categories
  );
  const categoriesInitialized = (0, import_react68.useRef)(false);
  const prevInitialDataRef = (0, import_react68.useRef)(
    void 0
  );
  (0, import_react68.useEffect)(() => {
    if (isOpen && initialCategories.length > 0 && !categoriesInitialized.current) {
      setCategories(initialCategories);
      categoriesInitialized.current = true;
    }
  }, [isOpen, initialCategories, setCategories]);
  (0, import_react68.useEffect)(() => {
    if (isOpen && initialData && prevInitialDataRef.current !== initialData) {
      store.setFormData({
        title: initialData.title ?? "",
        subtype: initialData.subtype ?? "TAREFA",
        notification: initialData.notification ?? ""
      });
      prevInitialDataRef.current = initialData;
    }
  }, [isOpen, initialData, store]);
  (0, import_react68.useEffect)(() => {
    if (!isOpen) {
      reset();
      categoriesInitialized.current = false;
      prevInitialDataRef.current = void 0;
    }
  }, [isOpen, reset]);
  const handleCategoriesChange = (0, import_react68.useCallback)(
    (updatedCategories) => {
      setCategories(updatedCategories);
      onCategoriesChange?.(updatedCategories);
    },
    [setCategories, onCategoriesChange]
  );
  const handleActivityTypeSelect = (0, import_react68.useCallback)(
    (subtype) => {
      store.setFormData({ subtype });
    },
    [store]
  );
  const handleTitleChange = (0, import_react68.useCallback)(
    (e) => {
      store.setFormData({ title: e.target.value });
    },
    [store]
  );
  const handleNotificationChange = (0, import_react68.useCallback)(
    (e) => {
      store.setFormData({ notification: e.target.value });
    },
    [store]
  );
  const handleStartDateChange = (0, import_react68.useCallback)(
    (date) => {
      store.setFormData({ startDate: date });
    },
    [store]
  );
  const handleStartTimeChange = (0, import_react68.useCallback)(
    (time) => {
      store.setFormData({ startTime: time });
    },
    [store]
  );
  const handleFinalDateChange = (0, import_react68.useCallback)(
    (date) => {
      store.setFormData({ finalDate: date });
    },
    [store]
  );
  const handleFinalTimeChange = (0, import_react68.useCallback)(
    (time) => {
      store.setFormData({ finalTime: time });
    },
    [store]
  );
  const handleRetryChange = (0, import_react68.useCallback)(
    (value) => {
      store.setFormData({ canRetry: value === "yes" });
    },
    [store]
  );
  const handleSubmit = (0, import_react68.useCallback)(async () => {
    const isValid = store.validateAllSteps();
    if (!isValid) return;
    try {
      const formData = store.formData;
      await onSubmit(formData);
    } catch (error) {
      if (onError) {
        onError(error);
      } else {
        console.error("Falha ao enviar atividade:", error);
      }
    }
  }, [store, onSubmit, onError]);
  const handleCancel = (0, import_react68.useCallback)(() => {
    onClose();
  }, [onClose]);
  const renderError = (error) => {
    if (!error) return null;
    return /* @__PURE__ */ (0, import_jsx_runtime86.jsxs)(
      Text_default,
      {
        as: "p",
        size: "sm",
        color: "text-error-600",
        className: "flex items-center gap-1 mt-1",
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(import_react69.WarningCircleIcon, { size: 16 }),
          error
        ]
      }
    );
  };
  const renderActivityStep = () => /* @__PURE__ */ (0, import_jsx_runtime86.jsxs)("div", { className: "flex flex-col gap-6", children: [
    /* @__PURE__ */ (0, import_jsx_runtime86.jsxs)("div", { children: [
      /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(Text_default, { size: "sm", weight: "medium", color: "text-text-700", className: "mb-3", children: "Tipo de atividade*" }),
      /* @__PURE__ */ (0, import_jsx_runtime86.jsx)("div", { className: "flex flex-wrap gap-2", children: ACTIVITY_TYPE_OPTIONS.map((type) => /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(
        Chips_default,
        {
          selected: store.formData.subtype === type.value,
          onClick: () => handleActivityTypeSelect(type.value),
          children: type.label
        },
        type.value
      )) }),
      renderError(store.errors.subtype)
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(
      Input_default,
      {
        label: "T\xEDtulo",
        placeholder: "Digite o t\xEDtulo da atividade",
        value: store.formData.title || "",
        onChange: handleTitleChange,
        variant: "rounded",
        required: true,
        errorMessage: store.errors.title
      }
    ),
    /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(
      TextArea_default,
      {
        label: "Mensagem da notifica\xE7\xE3o",
        placeholder: "Digite uma mensagem para a notifica\xE7\xE3o (opcional)",
        value: store.formData.notification || "",
        onChange: handleNotificationChange
      }
    )
  ] });
  const renderRecipientStep = () => {
    const categoriesToRender = storeCategories.length > 0 ? storeCategories : initialCategories;
    return /* @__PURE__ */ (0, import_jsx_runtime86.jsxs)("div", { className: "flex flex-col gap-4", children: [
      /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(Text_default, { size: "sm", weight: "medium", color: "text-text-700", children: "Para quem voc\xEA vai enviar a atividade?" }),
      /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(
        "div",
        {
          className: cn(
            "max-h-[300px] overflow-y-auto",
            "scrollbar-thin scrollbar-thumb-border-300 scrollbar-track-transparent"
          ),
          children: /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(
            CheckboxGroup,
            {
              categories: categoriesToRender,
              onCategoriesChange: handleCategoriesChange,
              compactSingleItem: true,
              showDivider: true
            }
          )
        }
      ),
      renderError(store.errors.students)
    ] });
  };
  const renderDeadlineStep = () => /* @__PURE__ */ (0, import_jsx_runtime86.jsxs)("div", { className: "flex flex-col gap-4 sm:gap-6 pt-6", children: [
    /* @__PURE__ */ (0, import_jsx_runtime86.jsxs)("div", { className: "grid grid-cols-2 gap-2", children: [
      /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(
        DateTimeInput_default,
        {
          label: "Iniciar em*",
          date: store.formData.startDate || "",
          time: store.formData.startTime || "",
          onDateChange: handleStartDateChange,
          onTimeChange: handleStartTimeChange,
          errorMessage: store.errors.startDate,
          defaultTime: "00:00",
          testId: "start-datetime",
          className: "w-full"
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(
        DateTimeInput_default,
        {
          label: "Finalizar at\xE9*",
          date: store.formData.finalDate || "",
          time: store.formData.finalTime || "",
          onDateChange: handleFinalDateChange,
          onTimeChange: handleFinalTimeChange,
          errorMessage: store.errors.finalDate,
          defaultTime: "23:59",
          testId: "final-datetime",
          className: "w-full"
        }
      )
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime86.jsxs)("div", { children: [
      /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(Text_default, { size: "sm", weight: "medium", color: "text-text-700", className: "mb-3", children: "Permitir refazer?" }),
      /* @__PURE__ */ (0, import_jsx_runtime86.jsxs)(
        RadioGroup,
        {
          value: store.formData.canRetry ? "yes" : "no",
          onValueChange: handleRetryChange,
          className: "flex flex-row gap-6",
          children: [
            /* @__PURE__ */ (0, import_jsx_runtime86.jsxs)("div", { className: "flex items-center gap-2", children: [
              /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(RadioGroupItem, { value: "yes", id: "radio-item-yes" }),
              /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(
                Text_default,
                {
                  as: "label",
                  size: "sm",
                  color: "text-text-700",
                  className: "cursor-pointer",
                  htmlFor: "radio-item-yes",
                  children: "Sim"
                }
              )
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime86.jsxs)("div", { className: "flex items-center gap-2", children: [
              /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(RadioGroupItem, { value: "no", id: "radio-item-no" }),
              /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(
                Text_default,
                {
                  as: "label",
                  size: "sm",
                  color: "text-text-700",
                  className: "cursor-pointer",
                  htmlFor: "radio-item-no",
                  children: "N\xE3o"
                }
              )
            ] })
          ]
        }
      )
    ] })
  ] });
  const renderStepContent = () => {
    switch (store.currentStep) {
      case 1:
        return renderActivityStep();
      case 2:
        return renderRecipientStep();
      case 3:
        return renderDeadlineStep();
      default:
        return null;
    }
  };
  const renderFooter = () => /* @__PURE__ */ (0, import_jsx_runtime86.jsxs)("div", { className: "flex flex-col-reverse sm:flex-row items-center justify-between gap-3 w-full", children: [
    /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(
      Button_default,
      {
        variant: "link",
        action: "primary",
        onClick: handleCancel,
        className: "w-full sm:w-auto",
        children: "Cancelar"
      }
    ),
    /* @__PURE__ */ (0, import_jsx_runtime86.jsxs)("div", { className: "flex flex-col-reverse sm:flex-row items-center gap-2 sm:gap-3 w-full sm:w-auto", children: [
      store.currentStep > 1 && /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(
        Button_default,
        {
          variant: "outline",
          action: "primary",
          onClick: store.previousStep,
          iconLeft: /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(import_react69.CaretLeftIcon, { size: 16 }),
          className: "w-full sm:w-auto",
          children: "Anterior"
        }
      ),
      store.currentStep < 3 ? /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(
        Button_default,
        {
          variant: "solid",
          action: "primary",
          onClick: () => store.nextStep(),
          iconRight: /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(import_react69.ArrowRightIcon, { size: 16 }),
          className: "w-full sm:w-auto",
          children: "Pr\xF3ximo"
        }
      ) : /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(
        Button_default,
        {
          variant: "solid",
          action: "primary",
          onClick: handleSubmit,
          disabled: isLoading,
          iconLeft: /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(import_react69.PaperPlaneTiltIcon, { size: 16 }),
          className: "w-full sm:w-auto",
          children: isLoading ? "Enviando..." : "Enviar atividade"
        }
      )
    ] })
  ] });
  return /* @__PURE__ */ (0, import_jsx_runtime86.jsxs)(
    Modal_default,
    {
      isOpen,
      onClose,
      title: "Enviar atividade",
      size: "md",
      footer: renderFooter(),
      contentClassName: "flex flex-col gap-8 sm:gap-10 max-h-[70vh] overflow-y-auto",
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(
          Stepper_default,
          {
            steps: STEPPER_STEPS,
            currentStep: store.currentStep - 1,
            size: "small"
          }
        ),
        renderStepContent()
      ]
    }
  );
};
var SendActivityModal_default = SendActivityModal;

// src/components/RecommendedLessonsHistory/RecommendedLessonsHistory.tsx
var import_react71 = require("react");
var import_phosphor_react44 = require("phosphor-react");

// src/types/common.ts
var GenericApiStatus = /* @__PURE__ */ ((GenericApiStatus2) => {
  GenericApiStatus2["A_VENCER"] = "A_VENCER";
  GenericApiStatus2["VENCIDA"] = "VENCIDA";
  GenericApiStatus2["CONCLUIDA"] = "CONCLUIDA";
  return GenericApiStatus2;
})(GenericApiStatus || {});
var GenericDisplayStatus = /* @__PURE__ */ ((GenericDisplayStatus4) => {
  GenericDisplayStatus4["ATIVA"] = "ATIVA";
  GenericDisplayStatus4["VENCIDA"] = "VENCIDA";
  GenericDisplayStatus4["CONCLUIDA"] = "CONCLU\xCDDA";
  return GenericDisplayStatus4;
})(GenericDisplayStatus || {});
var BadgeActionType = /* @__PURE__ */ ((BadgeActionType4) => {
  BadgeActionType4["SUCCESS"] = "success";
  BadgeActionType4["WARNING"] = "warning";
  BadgeActionType4["ERROR"] = "error";
  return BadgeActionType4;
})(BadgeActionType || {});
var getStatusBadgeAction2 = (status) => {
  const actionMap = {
    ["CONCLU\xCDDA" /* CONCLUIDA */]: "success" /* SUCCESS */,
    ["ATIVA" /* ATIVA */]: "warning" /* WARNING */,
    ["VENCIDA" /* VENCIDA */]: "error" /* ERROR */
  };
  return actionMap[status] ?? "warning" /* WARNING */;
};
var mapApiStatusToDisplay = (apiStatus) => {
  const statusMap = {
    ["A_VENCER" /* A_VENCER */]: "ATIVA" /* ATIVA */,
    ["VENCIDA" /* VENCIDA */]: "VENCIDA" /* VENCIDA */,
    ["CONCLUIDA" /* CONCLUIDA */]: "CONCLU\xCDDA" /* CONCLUIDA */
  };
  return statusMap[apiStatus];
};

// src/types/recommendedLessons.ts
var getGoalStatusBadgeAction = (status) => getStatusBadgeAction2(status);
var GOAL_FILTER_STATUS_OPTIONS = [
  { id: "VENCIDA" /* VENCIDA */, name: "Vencida" },
  { id: "A_VENCER" /* A_VENCER */, name: "Ativa" }
];
var GOAL_STATUS_OPTIONS = [
  { id: "A_VENCER" /* A_VENCER */, name: "A Vencer" },
  { id: "VENCIDA" /* VENCIDA */, name: "Vencida" },
  { id: "CONCLUIDA" /* CONCLUIDA */, name: "Conclu\xEDda" }
];
var StudentLessonStatus = /* @__PURE__ */ ((StudentLessonStatus2) => {
  StudentLessonStatus2["A_INICIAR"] = "A INICIAR";
  StudentLessonStatus2["EM_ANDAMENTO"] = "EM ANDAMENTO";
  StudentLessonStatus2["NAO_FINALIZADO"] = "N\xC3O FINALIZADO";
  StudentLessonStatus2["CONCLUIDO"] = "CONCLU\xCDDO";
  return StudentLessonStatus2;
})(StudentLessonStatus || {});
var getStudentStatusBadgeAction = (status) => {
  const actionMap = {
    ["CONCLU\xCDDO" /* CONCLUIDO */]: "success",
    ["EM ANDAMENTO" /* EM_ANDAMENTO */]: "info",
    ["A INICIAR" /* A_INICIAR */]: "warning",
    ["N\xC3O FINALIZADO" /* NAO_FINALIZADO */]: "error"
  };
  return actionMap[status] ?? "warning";
};
var isDeadlinePassed = (deadline) => {
  if (!deadline) return false;
  return new Date(deadline) < /* @__PURE__ */ new Date();
};
var deriveStudentStatus = (progress, completedAt, deadline) => {
  if (completedAt) return "CONCLU\xCDDO" /* CONCLUIDO */;
  if (progress === 100) return "CONCLU\xCDDO" /* CONCLUIDO */;
  if (isDeadlinePassed(deadline ?? null) && progress < 100) {
    return "N\xC3O FINALIZADO" /* NAO_FINALIZADO */;
  }
  if (progress === 0) return "A INICIAR" /* A_INICIAR */;
  if (progress > 0) return "EM ANDAMENTO" /* EM_ANDAMENTO */;
  return "A INICIAR" /* A_INICIAR */;
};
var formatDaysToComplete = (daysToComplete) => {
  if (daysToComplete === null) return null;
  if (daysToComplete === 1) return "1 dia";
  return `${daysToComplete} dias`;
};

// src/hooks/useRecommendedLessons.ts
var import_react70 = require("react");
var import_zod4 = require("zod");
var import_dayjs3 = __toESM(require("dayjs"));
var goalSubjectSchema = import_zod4.z.object({
  id: import_zod4.z.string().uuid(),
  name: import_zod4.z.string()
}).nullable();
var goalCreatorSchema = import_zod4.z.object({
  id: import_zod4.z.string().uuid(),
  name: import_zod4.z.string()
}).nullable();
var goalStatsSchema = import_zod4.z.object({
  totalStudents: import_zod4.z.number(),
  completedCount: import_zod4.z.number(),
  completionPercentage: import_zod4.z.number()
});
var goalBreakdownSchema = import_zod4.z.object({
  classId: import_zod4.z.string().uuid(),
  className: import_zod4.z.string(),
  schoolId: import_zod4.z.string(),
  schoolName: import_zod4.z.string(),
  studentCount: import_zod4.z.number(),
  completedCount: import_zod4.z.number()
});
var goalDataSchema = import_zod4.z.object({
  id: import_zod4.z.string().uuid(),
  title: import_zod4.z.string(),
  startDate: import_zod4.z.string().nullable(),
  finalDate: import_zod4.z.string().nullable(),
  createdAt: import_zod4.z.string(),
  progress: import_zod4.z.number(),
  totalLessons: import_zod4.z.number()
});
var goalHistoryItemSchema = import_zod4.z.object({
  goal: goalDataSchema,
  subject: goalSubjectSchema,
  creator: goalCreatorSchema,
  stats: goalStatsSchema,
  breakdown: import_zod4.z.array(goalBreakdownSchema)
});
var goalsHistoryApiResponseSchema = import_zod4.z.object({
  message: import_zod4.z.string(),
  data: import_zod4.z.object({
    goals: import_zod4.z.array(goalHistoryItemSchema),
    total: import_zod4.z.number()
  })
});
var determineGoalStatus = (finalDate, completionPercentage) => {
  if (completionPercentage === 100) {
    return "CONCLU\xCDDA" /* CONCLUIDA */;
  }
  if (finalDate) {
    const now = (0, import_dayjs3.default)();
    const deadline = (0, import_dayjs3.default)(finalDate);
    if (deadline.isBefore(now)) {
      return "VENCIDA" /* VENCIDA */;
    }
  }
  return "ATIVA" /* ATIVA */;
};
var transformGoalToTableItem = (item) => {
  const firstBreakdown = item.breakdown[0];
  const schoolName = firstBreakdown?.schoolName || "-";
  const className = firstBreakdown?.className || "-";
  const classDisplay = item.breakdown.length > 1 ? `${item.breakdown.length} turmas` : className;
  return {
    id: item.goal.id,
    startDate: item.goal.startDate ? (0, import_dayjs3.default)(item.goal.startDate).format("DD/MM") : "-",
    deadline: item.goal.finalDate ? (0, import_dayjs3.default)(item.goal.finalDate).format("DD/MM") : "-",
    title: item.goal.title,
    school: schoolName,
    year: "-",
    // API doesn't provide year directly
    subject: item.subject?.name || "-",
    class: classDisplay,
    status: determineGoalStatus(
      item.goal.finalDate,
      item.stats.completionPercentage
    ),
    completionPercentage: item.stats.completionPercentage
  };
};
var handleGoalFetchError = (error) => {
  if (error instanceof import_zod4.z.ZodError) {
    console.error("Erro ao validar dados de hist\xF3rico de aulas:", error);
    return "Erro ao validar dados de hist\xF3rico de aulas";
  }
  console.error("Erro ao carregar hist\xF3rico de aulas:", error);
  return "Erro ao carregar hist\xF3rico de aulas";
};
var createUseRecommendedLessonsHistory = (fetchGoalsHistory) => {
  return () => {
    const [state, setState] = (0, import_react70.useState)({
      goals: [],
      loading: false,
      error: null,
      pagination: {
        total: 0,
        page: 1,
        limit: 10,
        totalPages: 0
      }
    });
    const fetchGoals = (0, import_react70.useCallback)(
      async (filters) => {
        setState((prev) => ({ ...prev, loading: true, error: null }));
        try {
          const responseData = await fetchGoalsHistory(filters);
          const validatedData = goalsHistoryApiResponseSchema.parse(responseData);
          const tableItems = validatedData.data.goals.map(
            transformGoalToTableItem
          );
          const page = filters?.page || 1;
          const limit = filters?.limit || 10;
          const total = validatedData.data.total;
          const totalPages = Math.ceil(total / limit);
          setState({
            goals: tableItems,
            loading: false,
            error: null,
            pagination: {
              total,
              page,
              limit,
              totalPages
            }
          });
        } catch (error) {
          const errorMessage = handleGoalFetchError(error);
          setState((prev) => ({
            ...prev,
            loading: false,
            error: errorMessage
          }));
        }
      },
      [fetchGoalsHistory]
    );
    return {
      ...state,
      fetchGoals
    };
  };
};
var createRecommendedLessonsHistoryHook = createUseRecommendedLessonsHistory;

// src/components/RecommendedLessonsHistory/RecommendedLessonsHistory.tsx
var import_jsx_runtime87 = require("react/jsx-runtime");
var isNonEmptyArray = (param) => Array.isArray(param) && param.length > 0;
var extractFilterValue = (param) => {
  if (!isNonEmptyArray(param)) return {};
  return param.length === 1 ? { single: param[0] } : { multiple: param };
};
var buildFiltersFromParams = (params) => {
  const filters = {
    page: params.page,
    limit: params.limit
  };
  if (params.search) {
    filters.search = params.search;
  }
  if (isNonEmptyArray(params.status)) {
    filters.status = params.status[0];
  }
  const schoolFilter = extractFilterValue(params.school);
  if (schoolFilter.single) filters.schoolId = schoolFilter.single;
  if (schoolFilter.multiple) filters.schoolIds = schoolFilter.multiple;
  const classFilter = extractFilterValue(params.class);
  if (classFilter.single) filters.classId = classFilter.single;
  if (classFilter.multiple) filters.classIds = classFilter.multiple;
  if (isNonEmptyArray(params.students)) {
    filters.studentIds = params.students;
  }
  if (isNonEmptyArray(params.subject)) {
    filters.subjectId = params.subject[0];
  }
  if (params.startDate && typeof params.startDate === "string") {
    filters.startDate = params.startDate;
  }
  return filters;
};
var getSchoolOptions = (data) => {
  if (!data?.schools) return [];
  return data.schools.map((school) => ({
    id: school.id,
    name: school.name
  }));
};
var getSubjectOptions = (data) => {
  if (!data?.subjects) return [];
  return data.subjects.map((subject) => ({
    id: subject.id,
    name: subject.name
  }));
};
var getSchoolYearOptions = (data) => {
  if (!data?.schoolYears) return [];
  return data.schoolYears.map((year) => ({
    id: year.id,
    name: year.name
  }));
};
var getClassOptions = (data) => {
  if (!data?.classes) return [];
  return data.classes.map((cls) => ({
    id: cls.id,
    name: cls.name
  }));
};
var createGoalFiltersConfig = (userData) => [
  {
    key: "academic",
    label: "DADOS ACAD\xCAMICOS",
    categories: [
      {
        key: "school",
        label: "Escola",
        selectedIds: [],
        itens: getSchoolOptions(userData)
      },
      {
        key: "schoolYear",
        label: "S\xE9rie",
        selectedIds: [],
        itens: getSchoolYearOptions(userData)
      },
      {
        key: "class",
        label: "Turma",
        selectedIds: [],
        itens: getClassOptions(userData)
      },
      {
        key: "students",
        label: "Alunos",
        selectedIds: [],
        itens: []
      }
    ]
  },
  {
    key: "content",
    label: "CONTE\xDADO",
    categories: [
      {
        key: "knowledgeArea",
        label: "\xC1rea de conhecimento",
        selectedIds: [],
        itens: []
      },
      {
        key: "subject",
        label: "Mat\xE9ria",
        selectedIds: [],
        itens: getSubjectOptions(userData)
      },
      {
        key: "theme",
        label: "Tema",
        selectedIds: [],
        itens: []
      },
      {
        key: "subtheme",
        label: "Subtema",
        selectedIds: [],
        itens: []
      },
      {
        key: "topic",
        label: "Assunto",
        selectedIds: [],
        itens: []
      }
    ]
  },
  {
    key: "lesson",
    label: "AULA",
    categories: [
      {
        key: "status",
        label: "Status",
        selectedIds: [],
        itens: GOAL_FILTER_STATUS_OPTIONS
      }
    ]
  }
];
var createTableColumns2 = (mapSubjectNameToEnum2, onDeleteGoal, onEditGoal) => [
  {
    key: "startDate",
    label: "In\xEDcio",
    sortable: true
  },
  {
    key: "deadline",
    label: "Prazo",
    sortable: true
  },
  {
    key: "title",
    label: "T\xEDtulo",
    sortable: true,
    className: "max-w-[200px] truncate",
    render: (value) => {
      const title = typeof value === "string" ? value : "";
      return /* @__PURE__ */ (0, import_jsx_runtime87.jsx)(Text_default, { size: "sm", title, children: title });
    }
  },
  {
    key: "school",
    label: "Escola",
    sortable: true,
    className: "max-w-[150px] truncate",
    render: (value) => {
      const school = typeof value === "string" ? value : "";
      return /* @__PURE__ */ (0, import_jsx_runtime87.jsx)(Text_default, { size: "sm", title: school, children: school });
    }
  },
  {
    key: "year",
    label: "Ano",
    sortable: true
  },
  {
    key: "subject",
    label: "Mat\xE9ria",
    sortable: true,
    className: "max-w-[140px]",
    render: (value) => {
      const subjectName = typeof value === "string" ? value : "";
      const subjectEnum = mapSubjectNameToEnum2?.(subjectName);
      if (!subjectEnum) {
        return /* @__PURE__ */ (0, import_jsx_runtime87.jsx)(Text_default, { size: "sm", className: "truncate", title: subjectName, children: subjectName });
      }
      const subjectInfo = getSubjectInfo(subjectEnum);
      return /* @__PURE__ */ (0, import_jsx_runtime87.jsxs)("div", { className: "flex items-center gap-2", title: subjectName, children: [
        /* @__PURE__ */ (0, import_jsx_runtime87.jsx)(
          "span",
          {
            className: cn(
              "w-[21px] h-[21px] flex items-center justify-center rounded-sm text-text-950 shrink-0",
              subjectInfo.colorClass
            ),
            children: subjectInfo.icon
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime87.jsx)(Text_default, { size: "sm", className: "truncate", children: subjectName })
      ] });
    }
  },
  {
    key: "class",
    label: "Turma",
    sortable: true
  },
  {
    key: "status",
    label: "Status",
    sortable: true,
    render: (value) => {
      const status = typeof value === "string" ? value : "";
      if (!status) {
        return /* @__PURE__ */ (0, import_jsx_runtime87.jsx)(Text_default, { size: "sm", color: "text-text-500", children: "-" });
      }
      return /* @__PURE__ */ (0, import_jsx_runtime87.jsx)(
        Badge_default,
        {
          variant: "solid",
          action: getGoalStatusBadgeAction(status),
          size: "small",
          children: status
        }
      );
    }
  },
  {
    key: "completionPercentage",
    label: "Conclus\xE3o",
    sortable: true,
    render: (value) => /* @__PURE__ */ (0, import_jsx_runtime87.jsx)(
      ProgressBar_default,
      {
        value: Number(value),
        variant: "blue",
        size: "medium",
        layout: "compact",
        showPercentage: true,
        compactWidth: "w-[100px]"
      }
    )
  },
  {
    key: "actions",
    label: "",
    sortable: false,
    className: "w-20",
    render: (_value, row) => {
      const handleDelete = (e) => {
        e.stopPropagation();
        onDeleteGoal?.(row.id);
      };
      const handleEdit = (e) => {
        e.stopPropagation();
        onEditGoal?.(row.id);
      };
      return /* @__PURE__ */ (0, import_jsx_runtime87.jsxs)("div", { className: "flex justify-center gap-2", children: [
        /* @__PURE__ */ (0, import_jsx_runtime87.jsx)(
          IconButton_default,
          {
            icon: /* @__PURE__ */ (0, import_jsx_runtime87.jsx)(import_phosphor_react44.Trash, { size: 20 }),
            size: "sm",
            title: "Excluir",
            onClick: handleDelete
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime87.jsx)(
          IconButton_default,
          {
            icon: /* @__PURE__ */ (0, import_jsx_runtime87.jsx)(import_phosphor_react44.PencilSimple, { size: 20 }),
            size: "sm",
            title: "Editar",
            onClick: handleEdit
          }
        )
      ] });
    }
  },
  {
    key: "navigation",
    label: "",
    sortable: false,
    className: "w-12",
    render: () => /* @__PURE__ */ (0, import_jsx_runtime87.jsx)("div", { className: "flex justify-center", children: /* @__PURE__ */ (0, import_jsx_runtime87.jsx)(import_phosphor_react44.CaretRight, { size: 20, className: "text-text-600" }) })
  }
];
var RecommendedLessonsHistory = ({
  fetchGoalsHistory,
  onCreateLesson,
  onRowClick,
  onDeleteGoal,
  onEditGoal,
  emptyStateImage,
  noSearchImage,
  mapSubjectNameToEnum: mapSubjectNameToEnum2,
  userFilterData,
  title = "Hist\xF3rico de aulas recomendadas",
  createButtonText = "Criar aula",
  searchPlaceholder = "Buscar aula"
}) => {
  const [activeTab, setActiveTab] = (0, import_react71.useState)("history" /* HISTORY */);
  const fetchGoalsHistoryRef = (0, import_react71.useRef)(fetchGoalsHistory);
  fetchGoalsHistoryRef.current = fetchGoalsHistory;
  const useGoalsHistory = (0, import_react71.useMemo)(
    () => createUseRecommendedLessonsHistory(
      (filters) => fetchGoalsHistoryRef.current(filters)
    ),
    []
  );
  const {
    goals,
    loading,
    error,
    pagination,
    fetchGoals
  } = useGoalsHistory();
  const initialFilterConfigs = (0, import_react71.useMemo)(
    () => createGoalFiltersConfig(userFilterData),
    [userFilterData]
  );
  const tableColumns = (0, import_react71.useMemo)(
    () => createTableColumns2(mapSubjectNameToEnum2, onDeleteGoal, onEditGoal),
    [mapSubjectNameToEnum2, onDeleteGoal, onEditGoal]
  );
  const handleParamsChange = (0, import_react71.useCallback)(
    (params) => {
      const filters = buildFiltersFromParams(params);
      fetchGoals(filters);
    },
    [fetchGoals]
  );
  return /* @__PURE__ */ (0, import_jsx_runtime87.jsxs)(
    "div",
    {
      "data-testid": "recommended-lessons-history",
      className: "flex flex-col w-full h-auto relative justify-center items-center mb-5 overflow-hidden",
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime87.jsx)("span", { className: "absolute top-0 left-0 h-[150px] w-full z-0" }),
        /* @__PURE__ */ (0, import_jsx_runtime87.jsxs)("div", { className: "flex flex-col w-full h-full max-w-[1350px] mx-auto z-10 lg:px-0 px-4 pt-4 sm:pt-0", children: [
          /* @__PURE__ */ (0, import_jsx_runtime87.jsxs)("div", { className: "flex flex-col sm:flex-row w-full mb-6 items-start sm:items-center sm:justify-between gap-0 sm:gap-4", children: [
            /* @__PURE__ */ (0, import_jsx_runtime87.jsx)(
              Text_default,
              {
                as: "h1",
                weight: "bold",
                className: "leading-[28px] tracking-[0.2px] text-xl lg:text-2xl",
                children: title
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime87.jsx)("div", { className: "flex-shrink-0 lg:w-auto self-center sm:self-auto", children: /* @__PURE__ */ (0, import_jsx_runtime87.jsx)(
              Menu,
              {
                defaultValue: "history" /* HISTORY */,
                value: activeTab,
                onValueChange: (value) => setActiveTab(value),
                variant: "menu2",
                className: "bg-transparent shadow-none px-0",
                children: /* @__PURE__ */ (0, import_jsx_runtime87.jsxs)(
                  MenuContent,
                  {
                    variant: "menu2",
                    className: "w-full lg:w-auto max-w-full min-w-0",
                    children: [
                      /* @__PURE__ */ (0, import_jsx_runtime87.jsx)(
                        MenuItem,
                        {
                          variant: "menu2",
                          value: "history" /* HISTORY */,
                          "data-testid": "menu-item-history",
                          className: "whitespace-nowrap flex-1 lg:flex-none",
                          children: "Hist\xF3rico"
                        }
                      ),
                      /* @__PURE__ */ (0, import_jsx_runtime87.jsx)(
                        MenuItem,
                        {
                          variant: "menu2",
                          value: "drafts" /* DRAFTS */,
                          "data-testid": "menu-item-drafts",
                          className: "whitespace-nowrap flex-1 lg:flex-none",
                          children: "Rascunhos"
                        }
                      ),
                      /* @__PURE__ */ (0, import_jsx_runtime87.jsx)(
                        MenuItem,
                        {
                          variant: "menu2",
                          value: "models" /* MODELS */,
                          "data-testid": "menu-item-models",
                          className: "whitespace-nowrap flex-1 lg:flex-none",
                          children: "Modelos"
                        }
                      )
                    ]
                  }
                )
              }
            ) })
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime87.jsxs)("div", { className: "flex flex-col items-center w-full min-h-0 flex-1", children: [
            activeTab === "history" /* HISTORY */ && /* @__PURE__ */ (0, import_jsx_runtime87.jsx)(import_jsx_runtime87.Fragment, { children: error ? /* @__PURE__ */ (0, import_jsx_runtime87.jsx)("div", { className: "flex items-center justify-center bg-background rounded-xl w-full min-h-[705px]", children: /* @__PURE__ */ (0, import_jsx_runtime87.jsx)(Text_default, { size: "lg", color: "text-error-500", children: error }) }) : /* @__PURE__ */ (0, import_jsx_runtime87.jsx)("div", { className: "w-full", children: /* @__PURE__ */ (0, import_jsx_runtime87.jsx)(
              TableProvider,
              {
                data: goals,
                headers: tableColumns,
                loading,
                variant: "borderless",
                enableSearch: true,
                enableFilters: true,
                enableTableSort: true,
                enablePagination: true,
                enableRowClick: true,
                initialFilters: initialFilterConfigs,
                paginationConfig: {
                  itemLabel: "aulas",
                  itemsPerPageOptions: [10, 20, 50, 100],
                  defaultItemsPerPage: 10,
                  totalItems: pagination.total,
                  totalPages: pagination.totalPages
                },
                searchPlaceholder,
                noSearchResultState: {
                  image: noSearchImage
                },
                emptyState: {
                  component: /* @__PURE__ */ (0, import_jsx_runtime87.jsx)(
                    EmptyState_default,
                    {
                      image: emptyStateImage,
                      title: "Crie uma nova aula",
                      description: "Selecione um conjunto de aulas organizadas por tema e ajude seus alunos a estudarem de forma estruturada e eficiente!",
                      buttonText: createButtonText,
                      buttonIcon: /* @__PURE__ */ (0, import_jsx_runtime87.jsx)(import_phosphor_react44.Plus, { size: 18 }),
                      buttonVariant: "outline",
                      buttonAction: "primary",
                      onButtonClick: onCreateLesson
                    }
                  )
                },
                onParamsChange: handleParamsChange,
                onRowClick,
                children: (renderProps) => {
                  const {
                    controls,
                    table,
                    pagination: paginationComponent
                  } = renderProps;
                  return /* @__PURE__ */ (0, import_jsx_runtime87.jsxs)("div", { className: "space-y-4", children: [
                    /* @__PURE__ */ (0, import_jsx_runtime87.jsxs)("div", { className: "flex items-center justify-between gap-4", children: [
                      /* @__PURE__ */ (0, import_jsx_runtime87.jsx)(
                        Button_default,
                        {
                          variant: "solid",
                          action: "primary",
                          size: "medium",
                          onClick: onCreateLesson,
                          iconLeft: /* @__PURE__ */ (0, import_jsx_runtime87.jsx)(import_phosphor_react44.Plus, { size: 18, weight: "bold" }),
                          children: createButtonText
                        }
                      ),
                      controls
                    ] }),
                    /* @__PURE__ */ (0, import_jsx_runtime87.jsxs)("div", { className: "bg-background rounded-xl p-6 space-y-4", children: [
                      table,
                      paginationComponent
                    ] })
                  ] });
                }
              }
            ) }) }),
            activeTab === "drafts" /* DRAFTS */ && /* @__PURE__ */ (0, import_jsx_runtime87.jsx)("div", { className: "flex items-center justify-center bg-background rounded-xl w-full min-h-[705px]", children: /* @__PURE__ */ (0, import_jsx_runtime87.jsx)(Text_default, { size: "lg", color: "text-text-600", children: "Rascunhos em desenvolvimento" }) }),
            activeTab === "models" /* MODELS */ && /* @__PURE__ */ (0, import_jsx_runtime87.jsx)("div", { className: "flex items-center justify-center bg-background rounded-xl w-full min-h-[705px]", children: /* @__PURE__ */ (0, import_jsx_runtime87.jsx)(Text_default, { size: "lg", color: "text-text-600", children: "Modelos em desenvolvimento" }) })
          ] })
        ] })
      ]
    }
  );
};

// src/components/RecommendedLessonDetails/RecommendedLessonDetails.tsx
var import_react79 = require("react");

// src/components/RecommendedLessonDetails/components/Breadcrumb.tsx
var import_react72 = require("@phosphor-icons/react");
var import_jsx_runtime88 = require("react/jsx-runtime");
var Breadcrumb = ({ items, onItemClick }) => /* @__PURE__ */ (0, import_jsx_runtime88.jsx)("nav", { className: "flex items-center gap-2 text-sm", "aria-label": "Breadcrumb", children: items.map((item, index) => /* @__PURE__ */ (0, import_jsx_runtime88.jsxs)(
  Text_default,
  {
    as: "span",
    className: "flex items-center gap-2",
    children: [
      index > 0 && /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(import_react72.CaretRightIcon, { size: 14, className: "text-text-500" }),
      item.path ? /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(
        "button",
        {
          type: "button",
          onClick: () => onItemClick?.(item.path),
          className: "text-text-600 hover:text-primary-700 transition-colors",
          children: item.label
        }
      ) : /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Text_default, { as: "span", className: "text-text-950 font-medium", children: item.label })
    ]
  },
  item.path ?? item.label
)) });

// src/components/RecommendedLessonDetails/components/LessonHeader.tsx
var import_react73 = require("@phosphor-icons/react");

// src/components/RecommendedLessonDetails/utils/lessonDetailsUtils.ts
var formatDate = (dateString) => {
  if (!dateString) return "-";
  const date = new Date(dateString);
  if (Number.isNaN(date.getTime())) return "-";
  return date.toLocaleDateString("pt-BR", {
    day: "2-digit",
    month: "2-digit",
    year: "numeric"
  });
};
var transformStudentForDisplay = (student, deadline) => ({
  id: student.userInstitutionId,
  name: student.name,
  status: deriveStudentStatus(student.progress, student.completedAt, deadline),
  completionPercentage: student.progress,
  duration: formatDaysToComplete(student.daysToComplete)
});

// src/components/RecommendedLessonDetails/components/LessonHeader.tsx
var import_jsx_runtime89 = require("react/jsx-runtime");
var LessonHeader = ({
  data,
  onViewLesson,
  mapSubjectNameToEnum: mapSubjectNameToEnum2,
  viewLessonLabel
}) => {
  const { goal, breakdown } = data;
  const subjectName = goal.lessonsGoals[0]?.supLessonsProgress?.lesson?.subject?.name || "";
  const subjectEnum = mapSubjectNameToEnum2?.(subjectName);
  const subjectInfo = subjectEnum ? getSubjectInfo(subjectEnum) : null;
  return /* @__PURE__ */ (0, import_jsx_runtime89.jsx)("div", { className: "bg-background rounded-xl border border-border-50 p-6", children: /* @__PURE__ */ (0, import_jsx_runtime89.jsxs)("div", { className: "flex flex-col lg:flex-row lg:items-start lg:justify-between gap-4", children: [
    /* @__PURE__ */ (0, import_jsx_runtime89.jsxs)("div", { className: "flex flex-col gap-2", children: [
      /* @__PURE__ */ (0, import_jsx_runtime89.jsx)(
        Text_default,
        {
          as: "h1",
          size: "xl",
          weight: "bold",
          className: "text-text-950 lg:text-2xl",
          children: goal.title
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime89.jsxs)("div", { className: "flex flex-wrap items-center gap-2 text-sm text-text-600", children: [
        /* @__PURE__ */ (0, import_jsx_runtime89.jsxs)(Text_default, { as: "span", size: "sm", className: "text-text-600", children: [
          "In\xEDcio em ",
          formatDate(goal.startDate)
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime89.jsx)(Text_default, { as: "span", size: "sm", className: "text-text-400", children: "\u2022" }),
        /* @__PURE__ */ (0, import_jsx_runtime89.jsxs)(Text_default, { as: "span", size: "sm", className: "text-text-600", children: [
          "Prazo final ",
          formatDate(goal.finalDate)
        ] }),
        breakdown?.schoolName && /* @__PURE__ */ (0, import_jsx_runtime89.jsxs)(import_jsx_runtime89.Fragment, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime89.jsx)(Text_default, { as: "span", size: "sm", className: "text-text-400", children: "\u2022" }),
          /* @__PURE__ */ (0, import_jsx_runtime89.jsx)(Text_default, { as: "span", size: "sm", className: "text-text-600", children: breakdown.schoolName })
        ] }),
        subjectName && /* @__PURE__ */ (0, import_jsx_runtime89.jsxs)(import_jsx_runtime89.Fragment, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime89.jsx)(Text_default, { as: "span", size: "sm", className: "text-text-400", children: "\u2022" }),
          /* @__PURE__ */ (0, import_jsx_runtime89.jsxs)(Text_default, { as: "span", size: "sm", className: "flex items-center gap-1", children: [
            subjectInfo && /* @__PURE__ */ (0, import_jsx_runtime89.jsx)(
              Text_default,
              {
                as: "span",
                className: cn(
                  "size-5 rounded flex items-center justify-center text-white",
                  subjectInfo.colorClass
                ),
                children: subjectInfo.icon
              }
            ),
            subjectName
          ] })
        ] }),
        breakdown?.className && /* @__PURE__ */ (0, import_jsx_runtime89.jsxs)(import_jsx_runtime89.Fragment, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime89.jsx)(Text_default, { as: "span", size: "sm", className: "text-text-400", children: "\u2022" }),
          /* @__PURE__ */ (0, import_jsx_runtime89.jsx)(Text_default, { as: "span", size: "sm", className: "text-text-600", children: breakdown.className })
        ] })
      ] })
    ] }),
    onViewLesson && /* @__PURE__ */ (0, import_jsx_runtime89.jsx)(
      Button_default,
      {
        variant: "solid",
        action: "primary",
        size: "small",
        iconLeft: /* @__PURE__ */ (0, import_jsx_runtime89.jsx)(import_react73.BookBookmarkIcon, { size: 16 }),
        onClick: onViewLesson,
        children: viewLessonLabel
      }
    )
  ] }) });
};

// src/components/RecommendedLessonDetails/components/LoadingSkeleton.tsx
var import_jsx_runtime90 = require("react/jsx-runtime");
var LoadingSkeleton = () => /* @__PURE__ */ (0, import_jsx_runtime90.jsxs)("div", { className: "flex flex-col gap-6", children: [
  /* @__PURE__ */ (0, import_jsx_runtime90.jsx)(SkeletonText, { width: 256 }),
  /* @__PURE__ */ (0, import_jsx_runtime90.jsx)("div", { className: "bg-background rounded-xl border border-border-50 p-6", children: /* @__PURE__ */ (0, import_jsx_runtime90.jsxs)("div", { className: "flex flex-col gap-3", children: [
    /* @__PURE__ */ (0, import_jsx_runtime90.jsx)(SkeletonText, { width: "75%", height: 28 }),
    /* @__PURE__ */ (0, import_jsx_runtime90.jsx)(SkeletonText, { width: "50%" })
  ] }) }),
  /* @__PURE__ */ (0, import_jsx_runtime90.jsxs)("div", { className: "flex flex-col gap-4", children: [
    /* @__PURE__ */ (0, import_jsx_runtime90.jsx)(SkeletonText, { width: 192, height: 20 }),
    /* @__PURE__ */ (0, import_jsx_runtime90.jsxs)("div", { className: "grid grid-cols-1 md:grid-cols-3 gap-4", children: [
      /* @__PURE__ */ (0, import_jsx_runtime90.jsx)(SkeletonRounded, { height: 140 }),
      /* @__PURE__ */ (0, import_jsx_runtime90.jsx)(SkeletonRounded, { height: 140 }),
      /* @__PURE__ */ (0, import_jsx_runtime90.jsx)(SkeletonRounded, { height: 140 })
    ] })
  ] }),
  /* @__PURE__ */ (0, import_jsx_runtime90.jsx)("div", { className: "bg-background rounded-xl border border-border-50 p-4", children: /* @__PURE__ */ (0, import_jsx_runtime90.jsx)(SkeletonTable, { rows: 4, columns: 5 }) })
] });

// src/components/RecommendedLessonDetails/components/ResultsSection.tsx
var import_react74 = require("@phosphor-icons/react");
var import_jsx_runtime91 = require("react/jsx-runtime");
var ResultsSection = ({ data, labels }) => {
  const { details } = data;
  const { aggregated, contentPerformance } = details;
  return /* @__PURE__ */ (0, import_jsx_runtime91.jsxs)("div", { className: "flex flex-col gap-4", children: [
    /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(Text_default, { as: "h2", size: "md", weight: "semibold", className: "text-text-950", children: labels.resultsTitle }),
    /* @__PURE__ */ (0, import_jsx_runtime91.jsx)("div", { className: "bg-background rounded-xl border border-border-50 p-4", children: /* @__PURE__ */ (0, import_jsx_runtime91.jsxs)("div", { className: "grid grid-cols-1 md:grid-cols-3 gap-4", children: [
      /* @__PURE__ */ (0, import_jsx_runtime91.jsx)("div", { className: "flex flex-col items-center justify-center rounded-xl p-4 min-h-28 bg-primary-50", children: /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(
        ProgressCircle_default,
        {
          value: aggregated.completionPercentage,
          size: "small",
          variant: "blue",
          label: labels.completedLabel,
          showPercentage: true
        }
      ) }),
      /* @__PURE__ */ (0, import_jsx_runtime91.jsxs)("div", { className: "flex flex-col items-center justify-center rounded-xl p-4 min-h-28 bg-success-200", children: [
        /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(
          Text_default,
          {
            as: "span",
            className: "size-8 rounded-full flex items-center justify-center bg-warning-300 mb-2",
            children: /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(import_react74.TrophyIcon, { size: 18, weight: "fill", className: "text-white" })
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(
          Text_default,
          {
            size: "2xs",
            weight: "bold",
            className: "text-text-700 uppercase text-center leading-none mb-1",
            children: labels.bestResultLabel
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(
          Text_default,
          {
            size: "xl",
            weight: "bold",
            className: "text-success-700 text-center leading-none tracking-wide",
            children: contentPerformance.best?.contentName || "-"
          }
        )
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime91.jsxs)("div", { className: "flex flex-col items-center justify-center rounded-xl p-4 min-h-28 bg-error-100", children: [
        /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(
          Text_default,
          {
            as: "span",
            className: "size-8 rounded-full flex items-center justify-center bg-error-300 mb-2",
            children: /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(import_react74.WarningIcon, { size: 18, weight: "fill", className: "text-error-700" })
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(
          Text_default,
          {
            size: "2xs",
            weight: "bold",
            className: "text-text-700 uppercase text-center leading-none mb-1",
            children: labels.hardestTopicLabel
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(
          Text_default,
          {
            size: "xl",
            weight: "bold",
            className: "text-error-700 text-center leading-none tracking-wide",
            children: contentPerformance.worst?.contentName || "-"
          }
        )
      ] })
    ] }) })
  ] });
};

// src/components/RecommendedLessonDetails/components/StudentsTable.tsx
var import_react75 = require("react");
var import_react76 = require("@phosphor-icons/react");
var import_jsx_runtime92 = require("react/jsx-runtime");
var StudentsTable = ({
  students,
  onViewPerformance,
  labels,
  emptyMessage = "Nenhum aluno encontrado"
}) => {
  const { sortedData, sortColumn, sortDirection, handleSort } = useTableSort(students);
  const canViewPerformance = (0, import_react75.useCallback)((student) => {
    return student.status === "CONCLU\xCDDO" /* CONCLUIDO */ || student.status === "N\xC3O FINALIZADO" /* NAO_FINALIZADO */;
  }, []);
  return /* @__PURE__ */ (0, import_jsx_runtime92.jsx)("div", { className: "bg-background rounded-xl border border-border-50 overflow-hidden", children: /* @__PURE__ */ (0, import_jsx_runtime92.jsxs)(Table_default, { children: [
    /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(TableHeader, { children: /* @__PURE__ */ (0, import_jsx_runtime92.jsxs)(TableRow, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(
        TableHead,
        {
          sortable: true,
          sortDirection: sortColumn === "name" ? sortDirection : void 0,
          onSort: () => handleSort("name"),
          children: labels.studentColumn
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(
        TableHead,
        {
          sortable: true,
          sortDirection: sortColumn === "status" ? sortDirection : void 0,
          onSort: () => handleSort("status"),
          children: labels.statusColumn
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(
        TableHead,
        {
          sortable: true,
          sortDirection: sortColumn === "completionPercentage" ? sortDirection : void 0,
          onSort: () => handleSort("completionPercentage"),
          children: labels.completionColumn
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(TableHead, { children: labels.durationColumn }),
      /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(TableHead, { className: "w-[140px]" })
    ] }) }),
    /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(TableBody, { children: sortedData.length === 0 ? /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(TableRow, { children: /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(TableCell, { colSpan: 5, className: "text-center py-8", children: /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(Text_default, { size: "sm", className: "text-text-500", children: emptyMessage }) }) }) : sortedData.map((student) => /* @__PURE__ */ (0, import_jsx_runtime92.jsxs)(TableRow, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(TableCell, { children: /* @__PURE__ */ (0, import_jsx_runtime92.jsxs)("div", { className: "flex items-center gap-2", children: [
        /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(
          Text_default,
          {
            as: "span",
            className: "size-8 rounded-full bg-background-100 flex items-center justify-center",
            children: /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(import_react76.UserIcon, { size: 16, className: "text-text-500" })
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(Text_default, { size: "sm", className: "text-text-950", children: student.name })
      ] }) }),
      /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(TableCell, { children: /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(
        Badge_default,
        {
          variant: "solid",
          action: getStudentStatusBadgeAction(student.status),
          size: "small",
          children: student.status
        }
      ) }),
      /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(TableCell, { children: /* @__PURE__ */ (0, import_jsx_runtime92.jsxs)("div", { className: "flex flex-col gap-1 min-w-[120px]", children: [
        /* @__PURE__ */ (0, import_jsx_runtime92.jsxs)(Text_default, { size: "sm", className: "text-primary-700 font-medium", children: [
          student.completionPercentage,
          "%"
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(
          ProgressBar_default,
          {
            value: student.completionPercentage,
            size: "small",
            variant: "blue",
            className: "w-full max-w-[100px]"
          }
        )
      ] }) }),
      /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(TableCell, { children: /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(Text_default, { size: "sm", className: "text-text-700", children: student.duration ?? "-" }) }),
      /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(TableCell, { children: canViewPerformance(student) ? /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(
        Button_default,
        {
          variant: "outline",
          size: "extra-small",
          onClick: () => onViewPerformance?.(student.id),
          children: labels.viewPerformance
        }
      ) : /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(Button_default, { variant: "outline", size: "extra-small", disabled: true, children: labels.viewPerformance }) })
    ] }, student.id)) })
  ] }) });
};

// src/components/RecommendedLessonDetails/components/StudentPerformanceModal.tsx
var import_react77 = require("react");
var import_react78 = require("@phosphor-icons/react");

// src/components/RecommendedLessonDetails/types.ts
var DEFAULT_LABELS = {
  viewLesson: "Ver aula",
  viewPerformance: "Ver desempenho",
  resultsTitle: "Resultados da aula recomendada",
  completedLabel: "CONCLU\xCDDO",
  bestResultLabel: "MELHOR RESULTADO",
  hardestTopicLabel: "MAIOR DIFICULDADE",
  studentColumn: "Aluno",
  statusColumn: "Status",
  completionColumn: "Conclus\xE3o",
  durationColumn: "Dura\xE7\xE3o"
};
var DEFAULT_PERFORMANCE_LABELS = {
  title: "Desempenho",
  correctAnswersLabel: "N\xB0 DE QUEST\xD5ES CORRETAS",
  incorrectAnswersLabel: "N\xB0 DE QUEST\xD5ES INCORRETAS",
  bestResultLabel: "MELHOR RESULTADO",
  hardestTopicLabel: "MAIOR DIFICULDADE",
  lessonsTitle: "Aulas"
};

// src/components/RecommendedLessonDetails/components/StudentPerformanceModal.tsx
var import_jsx_runtime93 = require("react/jsx-runtime");
var PerformanceCard = ({
  icon,
  label,
  value,
  secondaryLabel,
  secondaryValue,
  variant
}) => {
  const headerBgColor = {
    success: "bg-success-200",
    error: "bg-error-100"
  }[variant];
  const valueColor = {
    success: "text-success-700",
    error: "text-error-700"
  }[variant];
  const iconBgColor = {
    success: "bg-warning-300",
    error: "bg-error-300"
  }[variant];
  const secondaryLabelColor = {
    success: "text-success-600",
    error: "text-error-600"
  }[variant];
  return /* @__PURE__ */ (0, import_jsx_runtime93.jsxs)("div", { className: "flex flex-col rounded-xl border border-border-50 bg-background overflow-hidden", children: [
    /* @__PURE__ */ (0, import_jsx_runtime93.jsxs)(
      "div",
      {
        className: `flex flex-col items-center justify-center p-4 gap-1 ${headerBgColor}`,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(
            Text_default,
            {
              as: "span",
              className: `size-8 rounded-full flex items-center justify-center ${iconBgColor}`,
              children: icon
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(
            Text_default,
            {
              size: "2xs",
              weight: "medium",
              className: "text-text-800 uppercase text-center leading-none",
              children: label
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(Text_default, { size: "xl", weight: "bold", className: `${valueColor} text-center`, children: value })
        ]
      }
    ),
    /* @__PURE__ */ (0, import_jsx_runtime93.jsxs)("div", { className: "flex flex-col items-center gap-2 px-4 py-3", children: [
      /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(
        Text_default,
        {
          size: "2xs",
          weight: "medium",
          className: `${secondaryLabelColor} uppercase text-center`,
          children: secondaryLabel
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(Badge_default, { size: "large", action: "info", children: secondaryValue || "-" })
    ] })
  ] });
};
var getAlternativeStatus = (isCorrect, isSelected) => {
  if (isCorrect) {
    return "correct";
  }
  if (isSelected) {
    return "incorrect";
  }
  return void 0;
};
var mapAlternatives = (question) => {
  return question.alternatives.map((alt) => ({
    value: alt.id,
    label: alt.text,
    status: getAlternativeStatus(alt.isCorrect, alt.isSelected)
  }));
};
var getSelectedValue = (question) => {
  const selected = question.alternatives.find((alt) => alt.isSelected);
  return selected?.id;
};
var QuestionAccordionItem = ({
  question,
  index
}) => /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(
  CardAccordation,
  {
    value: question.id,
    className: "bg-background rounded-xl border border-border-50",
    triggerClassName: "py-5 px-5",
    contentClassName: "px-5 pb-5",
    trigger: /* @__PURE__ */ (0, import_jsx_runtime93.jsxs)("div", { className: "flex items-center justify-between flex-1", children: [
      /* @__PURE__ */ (0, import_jsx_runtime93.jsxs)(Text_default, { size: "sm", weight: "semibold", className: "text-text-950", children: [
        "Quest\xE3o ",
        index + 1
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(
        Badge_default,
        {
          size: "small",
          action: question.isCorrect ? "success" : "error",
          variant: "solid",
          iconLeft: question.isCorrect ? /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(import_react78.CheckCircleIcon, {}) : /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(import_react78.XCircleIcon, {}),
          children: question.isCorrect ? "Correta" : "Incorreta"
        }
      )
    ] }),
    children: /* @__PURE__ */ (0, import_jsx_runtime93.jsxs)("div", { className: "flex flex-col gap-3", children: [
      /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(Text_default, { size: "sm", className: "text-text-700", children: question.statement }),
      /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(
        CardAccordation,
        {
          value: `${question.id}-alternatives`,
          className: "bg-background rounded-lg border border-border-50",
          triggerClassName: "py-5 px-5",
          contentClassName: "px-5 py-5",
          trigger: /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(Text_default, { size: "sm", weight: "medium", className: "text-text-800", children: "Alternativas" }),
          children: /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(
            AlternativesList,
            {
              mode: "readonly",
              alternatives: mapAlternatives(question),
              selectedValue: getSelectedValue(question),
              layout: "default"
            }
          )
        }
      )
    ] })
  }
);
var LessonAccordionItem = ({ lesson }) => /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(
  CardAccordation,
  {
    value: lesson.id,
    className: "bg-background rounded-xl border border-border-50",
    triggerClassName: "py-5 px-5",
    contentClassName: "px-5 pb-5",
    trigger: /* @__PURE__ */ (0, import_jsx_runtime93.jsxs)("div", { className: "flex flex-col gap-1 flex-1", children: [
      /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(Text_default, { size: "sm", weight: "semibold", className: "text-text-950", children: lesson.title }),
      /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(
        ProgressBar_default,
        {
          value: lesson.progress,
          variant: "blue",
          size: "medium",
          showPercentage: true,
          layout: "default"
        }
      )
    ] }),
    children: /* @__PURE__ */ (0, import_jsx_runtime93.jsx)("div", { className: "flex flex-col gap-2", children: lesson.questions.map((question, index) => /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(
      QuestionAccordionItem,
      {
        question,
        index
      },
      question.id
    )) })
  }
);
var LoadingSkeleton2 = () => /* @__PURE__ */ (0, import_jsx_runtime93.jsxs)("div", { className: "flex flex-col gap-4 animate-pulse", children: [
  /* @__PURE__ */ (0, import_jsx_runtime93.jsx)("div", { className: "h-6 bg-background-200 rounded w-48" }),
  /* @__PURE__ */ (0, import_jsx_runtime93.jsxs)("div", { className: "grid grid-cols-2 gap-3", children: [
    /* @__PURE__ */ (0, import_jsx_runtime93.jsx)("div", { className: "h-44 bg-background-200 rounded-xl" }),
    /* @__PURE__ */ (0, import_jsx_runtime93.jsx)("div", { className: "h-44 bg-background-200 rounded-xl" })
  ] })
] });
var PerformanceContent = ({
  data,
  labels
}) => /* @__PURE__ */ (0, import_jsx_runtime93.jsxs)("div", { className: "flex flex-col gap-5", children: [
  /* @__PURE__ */ (0, import_jsx_runtime93.jsxs)("div", { className: "flex items-center gap-2", children: [
    /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(
      Text_default,
      {
        as: "span",
        className: "size-8 rounded-full bg-background-100 flex items-center justify-center",
        children: /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(import_react78.UserIcon, { size: 16, className: "text-text-500" })
      }
    ),
    /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(Text_default, { size: "md", weight: "medium", className: "text-text-950", children: data.studentName })
  ] }),
  /* @__PURE__ */ (0, import_jsx_runtime93.jsxs)("div", { className: "grid grid-cols-2 gap-3", children: [
    /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(
      PerformanceCard,
      {
        icon: /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(
          import_react78.LightbulbFilamentIcon,
          {
            size: 18,
            weight: "fill",
            className: "text-white"
          }
        ),
        label: labels.correctAnswersLabel,
        value: data.correctAnswers,
        secondaryLabel: labels.bestResultLabel,
        secondaryValue: data.bestResult,
        variant: "success"
      }
    ),
    /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(
      PerformanceCard,
      {
        icon: /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(
          import_react78.WarningCircleIcon,
          {
            size: 18,
            weight: "fill",
            className: "text-error-700"
          }
        ),
        label: labels.incorrectAnswersLabel,
        value: data.incorrectAnswers,
        secondaryLabel: labels.hardestTopicLabel,
        secondaryValue: data.hardestTopic,
        variant: "error"
      }
    )
  ] }),
  data.lessons.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime93.jsxs)("div", { className: "flex flex-col gap-3", children: [
    /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(Text_default, { size: "md", weight: "semibold", className: "text-text-950", children: labels.lessonsTitle }),
    /* @__PURE__ */ (0, import_jsx_runtime93.jsx)("div", { className: "flex flex-col gap-2", children: data.lessons.map((lesson) => /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(LessonAccordionItem, { lesson }, lesson.id)) })
  ] })
] });
var renderModalContent = (loading, data, labels) => {
  if (loading) {
    return /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(LoadingSkeleton2, {});
  }
  if (data) {
    return /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(PerformanceContent, { data, labels });
  }
  return null;
};
var StudentPerformanceModal = ({
  isOpen,
  onClose,
  data,
  loading = false,
  labels: customLabels
}) => {
  const labels = (0, import_react77.useMemo)(
    () => ({ ...DEFAULT_PERFORMANCE_LABELS, ...customLabels }),
    [customLabels]
  );
  if (!data && !loading) {
    return null;
  }
  return /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(
    Modal_default,
    {
      isOpen,
      onClose,
      title: labels.title,
      size: "lg",
      contentClassName: "max-h-[70vh] overflow-y-auto",
      children: renderModalContent(loading, data, labels)
    }
  );
};

// src/components/RecommendedLessonDetails/RecommendedLessonDetails.tsx
var import_jsx_runtime94 = require("react/jsx-runtime");
var RecommendedLessonDetails = ({
  data,
  loading = false,
  error = null,
  onViewLesson,
  onViewStudentPerformance,
  onBreadcrumbClick,
  mapSubjectNameToEnum: mapSubjectNameToEnum2,
  breadcrumbs,
  labels: customLabels,
  className
}) => {
  const labels = (0, import_react79.useMemo)(
    () => ({ ...DEFAULT_LABELS, ...customLabels }),
    [customLabels]
  );
  const defaultBreadcrumbs = (0, import_react79.useMemo)(
    () => [
      { label: "Aulas recomendadas", path: "/aulas-recomendadas" },
      { label: data?.goal.title || "Detalhes" }
    ],
    [data?.goal.title]
  );
  const breadcrumbItems = breadcrumbs || defaultBreadcrumbs;
  const displayStudents = (0, import_react79.useMemo)(() => {
    if (!data?.details.students) return [];
    const deadline = data?.goal.finalDate;
    return data.details.students.map(
      (student) => transformStudentForDisplay(student, deadline)
    );
  }, [data?.details.students, data?.goal.finalDate]);
  if (loading) {
    return /* @__PURE__ */ (0, import_jsx_runtime94.jsx)(
      "div",
      {
        className: cn("flex flex-col gap-6", className),
        "data-testid": "lesson-details-loading",
        children: /* @__PURE__ */ (0, import_jsx_runtime94.jsx)(LoadingSkeleton, {})
      }
    );
  }
  if (error) {
    return /* @__PURE__ */ (0, import_jsx_runtime94.jsx)(
      "div",
      {
        className: cn(
          "flex flex-col items-center justify-center py-12",
          className
        ),
        "data-testid": "lesson-details-error",
        children: /* @__PURE__ */ (0, import_jsx_runtime94.jsx)(Text_default, { size: "md", className: "text-error-700", children: error })
      }
    );
  }
  if (!data) {
    return null;
  }
  return /* @__PURE__ */ (0, import_jsx_runtime94.jsxs)(
    "div",
    {
      className: cn("flex flex-col gap-6", className),
      "data-testid": "recommended-lesson-details",
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime94.jsx)(Breadcrumb, { items: breadcrumbItems, onItemClick: onBreadcrumbClick }),
        /* @__PURE__ */ (0, import_jsx_runtime94.jsx)(
          LessonHeader,
          {
            data,
            onViewLesson,
            mapSubjectNameToEnum: mapSubjectNameToEnum2,
            viewLessonLabel: labels.viewLesson
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime94.jsx)(ResultsSection, { data, labels }),
        /* @__PURE__ */ (0, import_jsx_runtime94.jsx)(
          StudentsTable,
          {
            students: displayStudents,
            onViewPerformance: onViewStudentPerformance,
            labels
          }
        )
      ]
    }
  );
};
var RecommendedLessonDetails_default = RecommendedLessonDetails;

// src/hooks/useRecommendedLessonDetails.ts
var import_react80 = require("react");
var import_zod5 = require("zod");
var goalLessonSubjectSchema = import_zod5.z.object({
  id: import_zod5.z.string(),
  name: import_zod5.z.string(),
  color: import_zod5.z.string(),
  icon: import_zod5.z.string()
});
var lessonContentSchema = import_zod5.z.object({
  id: import_zod5.z.string(),
  name: import_zod5.z.string()
});
var goalLessonSchema = import_zod5.z.object({
  id: import_zod5.z.string(),
  content: lessonContentSchema,
  subtopic: lessonContentSchema,
  topic: lessonContentSchema,
  subject: goalLessonSubjectSchema
});
var goalLessonProgressSchema = import_zod5.z.object({
  id: import_zod5.z.string(),
  userId: import_zod5.z.string(),
  lessonId: import_zod5.z.string(),
  progress: import_zod5.z.number(),
  lesson: goalLessonSchema
});
var goalLessonGoalItemSchema = import_zod5.z.object({
  goalId: import_zod5.z.string(),
  supLessonsProgressId: import_zod5.z.string(),
  supLessonsProgress: goalLessonProgressSchema
});
var goalMetadataSchema = import_zod5.z.object({
  id: import_zod5.z.string(),
  title: import_zod5.z.string(),
  startDate: import_zod5.z.string(),
  finalDate: import_zod5.z.string(),
  progress: import_zod5.z.number(),
  lessonsGoals: import_zod5.z.array(goalLessonGoalItemSchema)
});
var goalApiResponseSchema = import_zod5.z.object({
  message: import_zod5.z.string(),
  data: goalMetadataSchema
});
var goalDetailStudentSchema = import_zod5.z.object({
  userInstitutionId: import_zod5.z.string(),
  userId: import_zod5.z.string(),
  name: import_zod5.z.string(),
  progress: import_zod5.z.number(),
  completedAt: import_zod5.z.string().nullable(),
  avgScore: import_zod5.z.number().nullable(),
  daysToComplete: import_zod5.z.number().nullable()
});
var goalDetailAggregatedSchema = import_zod5.z.object({
  completionPercentage: import_zod5.z.number(),
  avgScore: import_zod5.z.number().nullable()
});
var goalDetailContentPerformanceItemSchema = import_zod5.z.object({
  contentId: import_zod5.z.string(),
  contentName: import_zod5.z.string(),
  rate: import_zod5.z.number()
}).nullable();
var goalDetailContentPerformanceSchema = import_zod5.z.object({
  best: goalDetailContentPerformanceItemSchema,
  worst: goalDetailContentPerformanceItemSchema
});
var goalDetailsDataSchema = import_zod5.z.object({
  students: import_zod5.z.array(goalDetailStudentSchema),
  aggregated: goalDetailAggregatedSchema,
  contentPerformance: goalDetailContentPerformanceSchema
});
var goalDetailsApiResponseSchema = import_zod5.z.object({
  message: import_zod5.z.string(),
  data: goalDetailsDataSchema
});
var goalBreakdownSchema2 = import_zod5.z.object({
  classId: import_zod5.z.string().uuid(),
  className: import_zod5.z.string(),
  schoolId: import_zod5.z.string(),
  schoolName: import_zod5.z.string(),
  studentCount: import_zod5.z.number(),
  completedCount: import_zod5.z.number()
});
var historyGoalItemSchema = import_zod5.z.object({
  goal: import_zod5.z.object({ id: import_zod5.z.string().uuid() }),
  breakdown: import_zod5.z.array(goalBreakdownSchema2)
});
var historyApiResponseSchema = import_zod5.z.object({
  message: import_zod5.z.string(),
  data: import_zod5.z.object({
    goals: import_zod5.z.array(historyGoalItemSchema),
    total: import_zod5.z.number()
  })
});
var handleLessonDetailsFetchError = (error) => {
  if (error instanceof import_zod5.z.ZodError) {
    console.error("Erro ao validar dados dos detalhes da aula:", error);
    return "Erro ao validar dados dos detalhes da aula";
  }
  console.error("Erro ao carregar detalhes da aula:", error);
  return "Erro ao carregar detalhes da aula";
};
var createUseRecommendedLessonDetails = (apiClient) => {
  return (lessonId) => {
    const [state, setState] = (0, import_react80.useState)({
      data: null,
      loading: true,
      error: null
    });
    const fetchLessonDetails = (0, import_react80.useCallback)(async () => {
      if (!lessonId) {
        setState({
          data: null,
          loading: false,
          error: "ID da aula n\xE3o encontrado"
        });
        return;
      }
      setState((prev) => ({ ...prev, loading: true, error: null }));
      try {
        const promises = [
          apiClient.fetchGoal(lessonId),
          apiClient.fetchGoalDetails(lessonId),
          apiClient.fetchBreakdown ? apiClient.fetchBreakdown(lessonId) : Promise.resolve(null)
        ];
        const [goalResponse, detailsResponse, historyResponse] = await Promise.all(promises);
        const validatedGoal = goalApiResponseSchema.parse(goalResponse);
        const validatedDetails = goalDetailsApiResponseSchema.parse(detailsResponse);
        let breakdown;
        if (historyResponse) {
          const validatedHistory = historyApiResponseSchema.parse(historyResponse);
          const historyItem = validatedHistory.data.goals.find(
            (g) => g.goal.id === lessonId
          );
          breakdown = historyItem?.breakdown[0];
        }
        const lessonData = {
          goal: validatedGoal.data,
          details: validatedDetails.data,
          breakdown
        };
        setState({
          data: lessonData,
          loading: false,
          error: null
        });
      } catch (error) {
        const errorMessage = handleLessonDetailsFetchError(error);
        setState({
          data: null,
          loading: false,
          error: errorMessage
        });
      }
    }, [lessonId]);
    (0, import_react80.useEffect)(() => {
      fetchLessonDetails();
    }, [fetchLessonDetails]);
    return {
      ...state,
      refetch: fetchLessonDetails
    };
  };
};
var createRecommendedLessonDetailsHook = createUseRecommendedLessonDetails;

// src/components/ActivitiesHistory/ActivitiesHistory.tsx
var import_react85 = require("react");

// src/components/ActivitiesHistory/tabs/HistoryTab.tsx
var import_react82 = require("react");
var import_phosphor_react46 = require("phosphor-react");

// src/components/ActivitiesHistory/components/ErrorDisplay.tsx
var import_jsx_runtime95 = require("react/jsx-runtime");
var ErrorDisplay = ({ error }) => /* @__PURE__ */ (0, import_jsx_runtime95.jsx)("div", { className: "flex items-center justify-center bg-background rounded-xl w-full min-h-[705px]", children: /* @__PURE__ */ (0, import_jsx_runtime95.jsx)(Text_default, { size: "lg", color: "text-error-500", children: error }) });

// src/components/ActivitiesHistory/config/historyTableColumns.tsx
var import_phosphor_react45 = require("phosphor-react");

// src/components/ActivitiesHistory/utils/renderSubjectCell.tsx
var import_jsx_runtime96 = require("react/jsx-runtime");
var renderSubjectCell = (subjectName, mapSubjectNameToEnum2, showEmptyDash = false) => {
  if (!subjectName) {
    return showEmptyDash ? /* @__PURE__ */ (0, import_jsx_runtime96.jsx)(Text_default, { size: "sm", color: "text-text-400", children: "-" }) : null;
  }
  const subjectEnum = mapSubjectNameToEnum2?.(subjectName);
  if (!subjectEnum) {
    return /* @__PURE__ */ (0, import_jsx_runtime96.jsx)(Text_default, { size: "sm", className: "truncate", title: subjectName, children: subjectName });
  }
  const subjectInfo = getSubjectInfo(subjectEnum);
  return /* @__PURE__ */ (0, import_jsx_runtime96.jsxs)("div", { className: "flex items-center gap-2", title: subjectName, children: [
    /* @__PURE__ */ (0, import_jsx_runtime96.jsx)(
      "span",
      {
        className: cn(
          "w-[21px] h-[21px] flex items-center justify-center rounded-sm text-text-950 shrink-0",
          subjectInfo.colorClass
        ),
        children: subjectInfo.icon
      }
    ),
    /* @__PURE__ */ (0, import_jsx_runtime96.jsx)(Text_default, { size: "sm", className: "truncate", children: subjectName })
  ] });
};

// src/components/ActivitiesHistory/utils/renderTruncatedText.tsx
var import_jsx_runtime97 = require("react/jsx-runtime");
var renderTruncatedText = (value) => {
  const text = typeof value === "string" ? value : "";
  return /* @__PURE__ */ (0, import_jsx_runtime97.jsx)(Text_default, { size: "sm", title: text, children: text });
};

// src/components/ActivitiesHistory/utils/filterBuilders.ts
var isNonEmptyArray2 = (param) => Array.isArray(param) && param.length > 0;
var isValidApiStatus = (value) => Object.values(GenericApiStatus).includes(value);
var buildHistoryFiltersFromParams = (params) => {
  const filters = {
    page: params.page,
    limit: params.limit
  };
  if (params.search) {
    filters.search = params.search;
  }
  if (isNonEmptyArray2(params.status) && isValidApiStatus(params.status[0])) {
    filters.status = params.status[0];
  }
  if (isNonEmptyArray2(params.school)) {
    filters.schoolId = params.school[0];
  }
  if (isNonEmptyArray2(params.subject)) {
    filters.subjectId = params.subject[0];
  }
  return filters;
};
var buildModelsFiltersFromParams = (params) => {
  const filters = {
    page: params.page,
    limit: params.limit
  };
  if (params.search) {
    filters.search = params.search;
  }
  if (isNonEmptyArray2(params.subject)) {
    filters.subjectId = params.subject[0];
  }
  return filters;
};

// src/components/ActivitiesHistory/utils/filterOptions.ts
var getSchoolOptions2 = (data) => {
  if (!data?.schools) return [];
  return data.schools.map((school) => ({
    id: school.id,
    name: school.name
  }));
};
var getSubjectOptions2 = (data) => {
  if (!data?.subjects) return [];
  return data.subjects.map((subject) => ({
    id: subject.id,
    name: subject.name
  }));
};

// src/types/activitiesHistory.ts
var ActivityDraftType = /* @__PURE__ */ ((ActivityDraftType2) => {
  ActivityDraftType2["MODELO"] = "MODELO";
  ActivityDraftType2["RASCUNHO"] = "RASCUNHO";
  return ActivityDraftType2;
})(ActivityDraftType || {});
var getActivityStatusBadgeAction = (status) => getStatusBadgeAction2(status);
var ACTIVITY_FILTER_STATUS_OPTIONS = [
  { id: "A_VENCER" /* A_VENCER */, name: "A Vencer" },
  { id: "VENCIDA" /* VENCIDA */, name: "Vencida" },
  { id: "CONCLUIDA" /* CONCLUIDA */, name: "Conclu\xEDda" }
];
var mapActivityStatusToDisplay = (apiStatus) => mapApiStatusToDisplay(apiStatus);

// src/components/ActivitiesHistory/config/historyTableColumns.tsx
var import_jsx_runtime98 = require("react/jsx-runtime");
var createHistoryTableColumns = (mapSubjectNameToEnum2) => [
  {
    key: "startDate",
    label: "In\xEDcio",
    sortable: true
  },
  {
    key: "deadline",
    label: "Prazo",
    sortable: true
  },
  {
    key: "title",
    label: "T\xEDtulo",
    sortable: true,
    className: "max-w-[200px] truncate",
    render: renderTruncatedText
  },
  {
    key: "school",
    label: "Escola",
    sortable: true,
    className: "max-w-[150px] truncate",
    render: renderTruncatedText
  },
  {
    key: "year",
    label: "Ano",
    sortable: true
  },
  {
    key: "subject",
    label: "Mat\xE9ria",
    sortable: true,
    className: "max-w-[140px]",
    render: (value) => {
      const subjectName = typeof value === "string" ? value : "";
      return renderSubjectCell(subjectName, mapSubjectNameToEnum2, false);
    }
  },
  {
    key: "class",
    label: "Turma",
    sortable: true
  },
  {
    key: "status",
    label: "Status",
    sortable: true,
    render: (value) => {
      const status = typeof value === "string" ? value : "";
      if (!status) {
        return /* @__PURE__ */ (0, import_jsx_runtime98.jsx)(Text_default, { size: "sm", color: "text-text-500", children: "-" });
      }
      return /* @__PURE__ */ (0, import_jsx_runtime98.jsx)(
        Badge_default,
        {
          variant: "solid",
          action: getActivityStatusBadgeAction(status),
          size: "small",
          children: status
        }
      );
    }
  },
  {
    key: "completionPercentage",
    label: "Conclus\xE3o",
    sortable: true,
    render: (value) => /* @__PURE__ */ (0, import_jsx_runtime98.jsx)(
      ProgressBar_default,
      {
        value: Number(value),
        variant: "blue",
        size: "medium",
        layout: "compact",
        showPercentage: true,
        compactWidth: "w-[100px]"
      }
    )
  },
  {
    key: "navigation",
    label: "",
    sortable: false,
    className: "w-12",
    render: () => /* @__PURE__ */ (0, import_jsx_runtime98.jsx)("div", { className: "flex justify-center", children: /* @__PURE__ */ (0, import_jsx_runtime98.jsx)(import_phosphor_react45.CaretRight, { size: 20, className: "text-text-600" }) })
  }
];

// src/components/ActivitiesHistory/config/historyFiltersConfig.ts
var createHistoryFiltersConfig = (userData) => [
  {
    key: "status",
    label: "STATUS",
    categories: [
      {
        key: "status",
        label: "Status da Atividade",
        selectedIds: [],
        itens: ACTIVITY_FILTER_STATUS_OPTIONS
      }
    ]
  },
  {
    key: "academic",
    label: "DADOS ACAD\xCAMICOS",
    categories: [
      {
        key: "school",
        label: "Escola",
        selectedIds: [],
        itens: getSchoolOptions2(userData)
      }
    ]
  },
  {
    key: "content",
    label: "CONTE\xDADO",
    categories: [
      {
        key: "subject",
        label: "Mat\xE9ria",
        selectedIds: [],
        itens: getSubjectOptions2(userData)
      }
    ]
  }
];

// src/hooks/useActivitiesHistory.ts
var import_react81 = require("react");
var import_zod7 = require("zod");
var import_dayjs4 = __toESM(require("dayjs"));

// src/utils/hookErrorHandler.ts
var import_zod6 = require("zod");
var createFetchErrorHandler = (validationErrorMessage, genericErrorMessage) => (error) => {
  if (error instanceof import_zod6.z.ZodError) {
    console.error(validationErrorMessage, error);
    return validationErrorMessage;
  }
  console.error(genericErrorMessage, error);
  return genericErrorMessage;
};

// src/hooks/useActivitiesHistory.ts
var activityHistoryResponseSchema = import_zod7.z.object({
  id: import_zod7.z.string().uuid(),
  title: import_zod7.z.string(),
  startDate: import_zod7.z.string().nullable(),
  finalDate: import_zod7.z.string().nullable(),
  status: import_zod7.z.nativeEnum(GenericApiStatus),
  completionPercentage: import_zod7.z.number().min(0).max(100),
  subjectId: import_zod7.z.string().uuid().optional().nullable(),
  schoolId: import_zod7.z.string().optional(),
  schoolName: import_zod7.z.string().optional(),
  year: import_zod7.z.string().optional(),
  className: import_zod7.z.string().optional(),
  subjectName: import_zod7.z.string().optional()
});
var activitiesHistoryApiResponseSchema = import_zod7.z.object({
  message: import_zod7.z.string(),
  data: import_zod7.z.object({
    activities: import_zod7.z.array(activityHistoryResponseSchema),
    pagination: import_zod7.z.object({
      total: import_zod7.z.number(),
      page: import_zod7.z.number(),
      limit: import_zod7.z.number(),
      totalPages: import_zod7.z.number()
    })
  })
});
var DEFAULT_ACTIVITIES_PAGINATION = {
  total: 0,
  page: 1,
  limit: 10,
  totalPages: 0
};
var transformActivityToTableItem = (activity) => {
  return {
    id: activity.id,
    startDate: activity.startDate ? (0, import_dayjs4.default)(activity.startDate).format("DD/MM") : "-",
    deadline: activity.finalDate ? (0, import_dayjs4.default)(activity.finalDate).format("DD/MM") : "-",
    title: activity.title,
    school: activity.schoolName || "-",
    year: activity.year || "-",
    subject: activity.subjectName || "-",
    class: activity.className || "-",
    status: mapActivityStatusToDisplay(activity.status),
    completionPercentage: activity.completionPercentage
  };
};
var handleActivityFetchError = createFetchErrorHandler(
  "Erro ao validar dados de hist\xF3rico de atividades",
  "Erro ao carregar hist\xF3rico de atividades"
);
var createUseActivitiesHistory = (fetchActivitiesHistory) => {
  return () => {
    const [state, setState] = (0, import_react81.useState)({
      activities: [],
      loading: false,
      error: null,
      pagination: DEFAULT_ACTIVITIES_PAGINATION
    });
    const fetchActivities = (0, import_react81.useCallback)(
      async (filters) => {
        setState((prev) => ({ ...prev, loading: true, error: null }));
        try {
          const responseData = await fetchActivitiesHistory(filters);
          const validatedData = activitiesHistoryApiResponseSchema.parse(responseData);
          const tableItems = validatedData.data.activities.map(
            transformActivityToTableItem
          );
          setState({
            activities: tableItems,
            loading: false,
            error: null,
            pagination: validatedData.data.pagination
          });
        } catch (error) {
          const errorMessage = handleActivityFetchError(error);
          setState((prev) => ({
            ...prev,
            loading: false,
            error: errorMessage
          }));
        }
      },
      [fetchActivitiesHistory]
    );
    return {
      ...state,
      fetchActivities
    };
  };
};
var createActivitiesHistoryHook = createUseActivitiesHistory;

// src/components/ActivitiesHistory/tabs/HistoryTab.tsx
var import_jsx_runtime99 = require("react/jsx-runtime");
var HistoryTab = ({
  fetchActivitiesHistory,
  onCreateActivity,
  onRowClick,
  emptyStateImage,
  noSearchImage,
  mapSubjectNameToEnum: mapSubjectNameToEnum2,
  userFilterData
}) => {
  const fetchActivitiesHistoryRef = (0, import_react82.useRef)(fetchActivitiesHistory);
  fetchActivitiesHistoryRef.current = fetchActivitiesHistory;
  const useActivitiesHistory = (0, import_react82.useMemo)(
    () => createUseActivitiesHistory(
      (filters) => fetchActivitiesHistoryRef.current(filters)
    ),
    []
  );
  const {
    activities,
    loading,
    error,
    pagination,
    fetchActivities
  } = useActivitiesHistory();
  const historyFilterConfigs = (0, import_react82.useMemo)(
    () => createHistoryFiltersConfig(userFilterData),
    [userFilterData]
  );
  const historyTableColumns = (0, import_react82.useMemo)(
    () => createHistoryTableColumns(mapSubjectNameToEnum2),
    [mapSubjectNameToEnum2]
  );
  const handleParamsChange = (0, import_react82.useCallback)(
    (params) => {
      const filters = buildHistoryFiltersFromParams(params);
      fetchActivities(filters);
    },
    [fetchActivities]
  );
  if (error) {
    return /* @__PURE__ */ (0, import_jsx_runtime99.jsx)(ErrorDisplay, { error });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime99.jsx)("div", { className: "w-full", children: /* @__PURE__ */ (0, import_jsx_runtime99.jsx)(
    TableProvider,
    {
      data: activities,
      headers: historyTableColumns,
      loading,
      variant: "borderless",
      enableSearch: true,
      enableFilters: true,
      enableTableSort: true,
      enablePagination: true,
      enableRowClick: true,
      initialFilters: historyFilterConfigs,
      paginationConfig: {
        itemLabel: "atividades",
        itemsPerPageOptions: [10, 20, 50, 100],
        defaultItemsPerPage: 10,
        totalItems: pagination.total,
        totalPages: pagination.totalPages
      },
      searchPlaceholder: "Buscar atividade",
      noSearchResultState: {
        image: noSearchImage
      },
      emptyState: {
        component: /* @__PURE__ */ (0, import_jsx_runtime99.jsx)(
          EmptyState_default,
          {
            image: emptyStateImage,
            title: "Incentive sua turma ao aprendizado",
            description: "Crie uma nova atividade e ajude seus alunos a colocarem o conte\xFAdo em pr\xE1tica!",
            buttonText: "Criar atividade",
            buttonIcon: /* @__PURE__ */ (0, import_jsx_runtime99.jsx)(import_phosphor_react46.Plus, { size: 18 }),
            buttonVariant: "outline",
            buttonAction: "primary",
            onButtonClick: onCreateActivity
          }
        )
      },
      onParamsChange: handleParamsChange,
      onRowClick,
      children: (renderProps) => {
        const {
          controls,
          table,
          pagination: paginationComponent
        } = renderProps;
        return /* @__PURE__ */ (0, import_jsx_runtime99.jsxs)("div", { className: "space-y-4", children: [
          /* @__PURE__ */ (0, import_jsx_runtime99.jsxs)("div", { className: "flex items-center justify-between gap-4", children: [
            /* @__PURE__ */ (0, import_jsx_runtime99.jsx)(
              Button_default,
              {
                variant: "solid",
                action: "primary",
                size: "medium",
                onClick: onCreateActivity,
                iconLeft: /* @__PURE__ */ (0, import_jsx_runtime99.jsx)(import_phosphor_react46.Plus, { size: 18, weight: "bold" }),
                children: "Criar atividade"
              }
            ),
            controls
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime99.jsxs)("div", { className: "bg-background rounded-xl p-6 space-y-4", children: [
            table,
            paginationComponent
          ] })
        ] });
      }
    }
  ) });
};

// src/components/ActivitiesHistory/tabs/ModelsTab.tsx
var import_react84 = require("react");
var import_phosphor_react48 = require("phosphor-react");

// src/components/ActivitiesHistory/config/modelsTableColumns.tsx
var import_phosphor_react47 = require("phosphor-react");
var import_jsx_runtime100 = require("react/jsx-runtime");
var createModelsTableColumns = (mapSubjectNameToEnum2, onSendActivity, onEditModel, onDeleteModel) => [
  {
    key: "title",
    label: "T\xEDtulo",
    sortable: true,
    className: "max-w-[400px]",
    render: (value) => {
      const title = typeof value === "string" ? value : "";
      return /* @__PURE__ */ (0, import_jsx_runtime100.jsx)(Text_default, { size: "sm", title, className: "truncate block", children: title });
    }
  },
  {
    key: "savedAt",
    label: "Salvo em",
    sortable: true,
    className: "w-[120px]"
  },
  {
    key: "subject",
    label: "Mat\xE9ria",
    sortable: true,
    className: "max-w-[160px]",
    render: (value) => {
      const subjectName = typeof value === "string" ? value : "";
      return renderSubjectCell(subjectName, mapSubjectNameToEnum2, true);
    }
  },
  {
    key: "actions",
    label: "",
    sortable: false,
    className: "w-[220px]",
    render: (_value, row) => {
      const handleSend = (e) => {
        e.stopPropagation();
        onSendActivity?.(row);
      };
      const handleEdit = (e) => {
        e.stopPropagation();
        onEditModel?.(row);
      };
      const handleDelete = (e) => {
        e.stopPropagation();
        onDeleteModel(row);
      };
      return /* @__PURE__ */ (0, import_jsx_runtime100.jsxs)("div", { className: "flex items-center gap-2 justify-end", children: [
        onSendActivity && /* @__PURE__ */ (0, import_jsx_runtime100.jsx)(
          Button_default,
          {
            variant: "outline",
            action: "primary",
            size: "small",
            iconLeft: /* @__PURE__ */ (0, import_jsx_runtime100.jsx)(import_phosphor_react47.PaperPlaneTilt, { size: 16 }),
            onClick: handleSend,
            "aria-label": "Enviar atividade",
            children: "Enviar atividade"
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime100.jsx)(
          IconButton_default,
          {
            icon: /* @__PURE__ */ (0, import_jsx_runtime100.jsx)(import_phosphor_react47.Trash, { size: 20 }),
            size: "md",
            onClick: handleDelete,
            "aria-label": "Deletar modelo",
            className: "text-text-600 hover:text-error-500 hover:bg-transparent"
          }
        ),
        onEditModel && /* @__PURE__ */ (0, import_jsx_runtime100.jsx)(
          IconButton_default,
          {
            icon: /* @__PURE__ */ (0, import_jsx_runtime100.jsx)(import_phosphor_react47.PencilSimple, { size: 20 }),
            size: "md",
            onClick: handleEdit,
            "aria-label": "Editar modelo",
            className: "text-text-600 hover:text-primary-700 hover:bg-transparent"
          }
        )
      ] });
    }
  }
];

// src/components/ActivitiesHistory/config/modelsFiltersConfig.ts
var createModelsFiltersConfig = (userData) => [
  {
    key: "content",
    label: "CONTE\xDADO",
    categories: [
      {
        key: "subject",
        label: "Mat\xE9ria",
        selectedIds: [],
        itens: getSubjectOptions2(userData)
      }
    ]
  }
];

// src/hooks/useActivityModels.ts
var import_react83 = require("react");
var import_zod8 = require("zod");
var import_dayjs5 = __toESM(require("dayjs"));
var activityDraftFiltersSchema = import_zod8.z.object({
  questionTypes: import_zod8.z.array(import_zod8.z.string()).optional(),
  questionBanks: import_zod8.z.array(import_zod8.z.string()).optional(),
  subjects: import_zod8.z.array(import_zod8.z.string()).optional(),
  topics: import_zod8.z.array(import_zod8.z.string()).optional(),
  subtopics: import_zod8.z.array(import_zod8.z.string()).optional(),
  contents: import_zod8.z.array(import_zod8.z.string()).optional()
}).nullable();
var activityModelResponseSchema = import_zod8.z.object({
  id: import_zod8.z.string().uuid(),
  type: import_zod8.z.nativeEnum(ActivityDraftType),
  title: import_zod8.z.string().nullable(),
  creatorUserInstitutionId: import_zod8.z.string().uuid().nullable(),
  subjectId: import_zod8.z.string().uuid().nullable(),
  filters: activityDraftFiltersSchema,
  createdAt: import_zod8.z.string(),
  updatedAt: import_zod8.z.string()
});
var activityModelsApiResponseSchema = import_zod8.z.object({
  message: import_zod8.z.string(),
  data: import_zod8.z.object({
    activityDrafts: import_zod8.z.array(activityModelResponseSchema),
    total: import_zod8.z.number()
  })
});
var DEFAULT_MODELS_PAGINATION = {
  total: 0,
  page: 1,
  limit: 10,
  totalPages: 0
};
var transformModelToTableItem = (model, subjectsMap) => {
  const subjectName = model.subjectId ? subjectsMap?.get(model.subjectId) || "" : "";
  return {
    id: model.id,
    title: model.title || "Sem t\xEDtulo",
    savedAt: (0, import_dayjs5.default)(model.createdAt).format("DD/MM/YYYY"),
    subject: subjectName,
    subjectId: model.subjectId
  };
};
var handleModelFetchError = createFetchErrorHandler(
  "Erro ao validar dados de modelos de atividades",
  "Erro ao carregar modelos de atividades"
);
var createUseActivityModels = (fetchActivityModels, deleteActivityModel) => {
  return () => {
    const [state, setState] = (0, import_react83.useState)({
      models: [],
      loading: false,
      error: null,
      pagination: DEFAULT_MODELS_PAGINATION
    });
    const fetchModels = (0, import_react83.useCallback)(
      async (filters, subjectsMap) => {
        setState((prev) => ({ ...prev, loading: true, error: null }));
        try {
          const responseData = await fetchActivityModels(filters);
          const validatedData = activityModelsApiResponseSchema.parse(responseData);
          const tableItems = validatedData.data.activityDrafts.map(
            (model) => transformModelToTableItem(model, subjectsMap)
          );
          const limit = filters?.limit || 10;
          const page = filters?.page || 1;
          const total = validatedData.data.total;
          const totalPages = Math.ceil(total / limit);
          setState({
            models: tableItems,
            loading: false,
            error: null,
            pagination: {
              total,
              page,
              limit,
              totalPages
            }
          });
        } catch (error) {
          const errorMessage = handleModelFetchError(error);
          setState((prev) => ({
            ...prev,
            loading: false,
            error: errorMessage
          }));
        }
      },
      [fetchActivityModels]
    );
    const deleteModel = (0, import_react83.useCallback)(
      async (id) => {
        try {
          await deleteActivityModel(id);
          return true;
        } catch (error) {
          console.error("Erro ao deletar modelo:", error);
          return false;
        }
      },
      [deleteActivityModel]
    );
    return {
      ...state,
      fetchModels,
      deleteModel
    };
  };
};
var createActivityModelsHook = createUseActivityModels;

// src/components/ActivitiesHistory/tabs/ModelsTab.tsx
var import_jsx_runtime101 = require("react/jsx-runtime");
var ModelsTab = ({
  fetchActivityModels,
  deleteActivityModel,
  onCreateModel,
  onSendActivity,
  onEditModel,
  emptyStateImage,
  noSearchImage,
  mapSubjectNameToEnum: mapSubjectNameToEnum2,
  userFilterData,
  subjectsMap
}) => {
  const [deleteDialogOpen, setDeleteDialogOpen] = (0, import_react84.useState)(false);
  const [modelToDelete, setModelToDelete] = (0, import_react84.useState)(null);
  const { addToast } = useToast();
  const fetchActivityModelsRef = (0, import_react84.useRef)(fetchActivityModels);
  fetchActivityModelsRef.current = fetchActivityModels;
  const deleteActivityModelRef = (0, import_react84.useRef)(deleteActivityModel);
  deleteActivityModelRef.current = deleteActivityModel;
  const subjectsMapRef = (0, import_react84.useRef)(subjectsMap);
  subjectsMapRef.current = subjectsMap;
  const useActivityModels = (0, import_react84.useMemo)(
    () => createUseActivityModels(
      (filters) => fetchActivityModelsRef.current(filters),
      (id) => deleteActivityModelRef.current(id)
    ),
    []
  );
  const {
    models,
    loading: modelsLoading,
    error: modelsError,
    pagination: modelsPagination,
    fetchModels,
    deleteModel
  } = useActivityModels();
  const modelsFilterConfigs = (0, import_react84.useMemo)(
    () => createModelsFiltersConfig(userFilterData),
    [userFilterData]
  );
  const handleDeleteClick = (0, import_react84.useCallback)((model) => {
    setModelToDelete(model);
    setDeleteDialogOpen(true);
  }, []);
  const modelsTableColumns = (0, import_react84.useMemo)(
    () => createModelsTableColumns(
      mapSubjectNameToEnum2,
      onSendActivity,
      onEditModel,
      handleDeleteClick
    ),
    [mapSubjectNameToEnum2, onSendActivity, onEditModel, handleDeleteClick]
  );
  const handleParamsChange = (0, import_react84.useCallback)(
    (params) => {
      const filters = buildModelsFiltersFromParams(params);
      fetchModels(filters, subjectsMapRef.current);
    },
    [fetchModels]
  );
  (0, import_react84.useEffect)(() => {
    fetchModels({ page: 1, limit: 10 }, subjectsMapRef.current);
  }, [fetchModels]);
  const handleConfirmDelete = (0, import_react84.useCallback)(async () => {
    if (modelToDelete) {
      const success = await deleteModel(modelToDelete.id);
      if (success) {
        addToast({ title: "Modelo deletado com sucesso", action: "success" });
        fetchModels({ page: 1, limit: 10 }, subjectsMapRef.current);
      } else {
        addToast({ title: "Erro ao deletar modelo", action: "warning" });
      }
    }
    setDeleteDialogOpen(false);
    setModelToDelete(null);
  }, [modelToDelete, deleteModel, fetchModels, addToast]);
  const handleCancelDelete = (0, import_react84.useCallback)(() => {
    setDeleteDialogOpen(false);
    setModelToDelete(null);
  }, []);
  return /* @__PURE__ */ (0, import_jsx_runtime101.jsxs)(import_jsx_runtime101.Fragment, { children: [
    /* @__PURE__ */ (0, import_jsx_runtime101.jsx)(Toaster_default, {}),
    modelsError ? /* @__PURE__ */ (0, import_jsx_runtime101.jsx)(ErrorDisplay, { error: modelsError }) : /* @__PURE__ */ (0, import_jsx_runtime101.jsx)("div", { className: "w-full", "data-testid": "activity-models-tab", children: /* @__PURE__ */ (0, import_jsx_runtime101.jsx)(
      TableProvider,
      {
        data: models,
        headers: modelsTableColumns,
        loading: modelsLoading,
        variant: "borderless",
        enableSearch: true,
        enableFilters: true,
        enableTableSort: true,
        enablePagination: true,
        initialFilters: modelsFilterConfigs,
        paginationConfig: {
          itemLabel: "modelos",
          itemsPerPageOptions: [10, 20, 50, 100],
          defaultItemsPerPage: 10,
          totalItems: modelsPagination.total,
          totalPages: modelsPagination.totalPages
        },
        searchPlaceholder: "Buscar modelo",
        noSearchResultState: {
          image: noSearchImage
        },
        emptyState: {
          component: /* @__PURE__ */ (0, import_jsx_runtime101.jsx)(
            EmptyState_default,
            {
              image: emptyStateImage,
              title: "Crie modelos para agilizar suas atividades",
              description: "Salve modelos de atividades para reutilizar e enviar rapidamente para suas turmas!",
              buttonText: "Criar modelo",
              buttonIcon: /* @__PURE__ */ (0, import_jsx_runtime101.jsx)(import_phosphor_react48.Plus, { size: 18 }),
              buttonVariant: "outline",
              buttonAction: "primary",
              onButtonClick: onCreateModel
            }
          )
        },
        onParamsChange: handleParamsChange,
        children: (renderProps) => {
          const {
            controls,
            table,
            pagination: paginationComponent
          } = renderProps;
          return /* @__PURE__ */ (0, import_jsx_runtime101.jsxs)("div", { className: "space-y-4", children: [
            /* @__PURE__ */ (0, import_jsx_runtime101.jsxs)("div", { className: "flex items-center justify-between gap-4", children: [
              /* @__PURE__ */ (0, import_jsx_runtime101.jsx)(
                Button_default,
                {
                  variant: "solid",
                  action: "primary",
                  size: "medium",
                  onClick: onCreateModel,
                  iconLeft: /* @__PURE__ */ (0, import_jsx_runtime101.jsx)(import_phosphor_react48.Plus, { size: 18, weight: "bold" }),
                  children: "Criar modelo"
                }
              ),
              controls
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime101.jsxs)("div", { className: "bg-background rounded-xl p-6 space-y-4", children: [
              table,
              paginationComponent
            ] })
          ] });
        }
      }
    ) }),
    /* @__PURE__ */ (0, import_jsx_runtime101.jsx)(
      AlertDialog,
      {
        isOpen: deleteDialogOpen,
        onChangeOpen: setDeleteDialogOpen,
        title: "Deletar modelo",
        description: `Tem certeza que deseja deletar o modelo "${modelToDelete?.title}"? Esta a\xE7\xE3o n\xE3o pode ser desfeita.`,
        submitButtonLabel: "Deletar",
        cancelButtonLabel: "Cancelar",
        onSubmit: handleConfirmDelete,
        onCancel: handleCancelDelete
      }
    )
  ] });
};

// src/components/ActivitiesHistory/tabs/DraftsTab.tsx
var import_jsx_runtime102 = require("react/jsx-runtime");
var DraftsTab = () => {
  return /* @__PURE__ */ (0, import_jsx_runtime102.jsx)("div", { className: "flex items-center justify-center bg-background rounded-xl w-full min-h-[705px]", children: /* @__PURE__ */ (0, import_jsx_runtime102.jsx)(Text_default, { size: "lg", color: "text-text-600", children: "Rascunhos em desenvolvimento" }) });
};

// src/components/ActivitiesHistory/ActivitiesHistory.tsx
var import_jsx_runtime103 = require("react/jsx-runtime");
var PAGE_TITLES = {
  ["history" /* HISTORY */]: "Hist\xF3rico de atividades",
  ["drafts" /* DRAFTS */]: "Rascunhos",
  ["models" /* MODELS */]: "Modelos de atividades"
};
var ActivitiesHistory = ({
  fetchActivitiesHistory,
  fetchActivityModels,
  deleteActivityModel,
  onCreateActivity,
  onCreateModel,
  onRowClick,
  onSendActivity,
  onEditModel,
  emptyStateImage,
  noSearchImage,
  mapSubjectNameToEnum: mapSubjectNameToEnum2,
  userFilterData,
  subjectsMap
}) => {
  const [activeTab, setActiveTab] = (0, import_react85.useState)("history" /* HISTORY */);
  return /* @__PURE__ */ (0, import_jsx_runtime103.jsxs)(
    "div",
    {
      "data-testid": "activities-history",
      className: "flex flex-col w-full h-auto relative justify-center items-center mb-5 overflow-hidden",
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime103.jsx)("span", { className: "absolute top-0 left-0 h-[150px] w-full z-0" }),
        /* @__PURE__ */ (0, import_jsx_runtime103.jsxs)("div", { className: "flex flex-col w-full h-full max-w-[1350px] mx-auto z-10 lg:px-0 px-4 pt-4 sm:pt-0", children: [
          /* @__PURE__ */ (0, import_jsx_runtime103.jsxs)("div", { className: "flex flex-col sm:flex-row w-full mb-6 items-start sm:items-center sm:justify-between gap-0 sm:gap-4", children: [
            /* @__PURE__ */ (0, import_jsx_runtime103.jsx)(
              Text_default,
              {
                as: "h1",
                weight: "bold",
                className: "leading-[28px] tracking-[0.2px] text-xl lg:text-2xl",
                children: PAGE_TITLES[activeTab]
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime103.jsx)("div", { className: "flex-shrink-0 lg:w-auto self-center sm:self-auto", children: /* @__PURE__ */ (0, import_jsx_runtime103.jsx)(
              Menu,
              {
                defaultValue: "history" /* HISTORY */,
                value: activeTab,
                onValueChange: (value) => setActiveTab(value),
                variant: "menu2",
                className: "bg-transparent shadow-none px-0",
                children: /* @__PURE__ */ (0, import_jsx_runtime103.jsxs)(
                  MenuContent,
                  {
                    variant: "menu2",
                    className: "w-full lg:w-auto max-w-full min-w-0",
                    children: [
                      /* @__PURE__ */ (0, import_jsx_runtime103.jsx)(
                        MenuItem,
                        {
                          variant: "menu2",
                          value: "history" /* HISTORY */,
                          "data-testid": "menu-item-history",
                          className: "whitespace-nowrap flex-1 lg:flex-none",
                          children: "Hist\xF3rico"
                        }
                      ),
                      /* @__PURE__ */ (0, import_jsx_runtime103.jsx)(
                        MenuItem,
                        {
                          variant: "menu2",
                          value: "drafts" /* DRAFTS */,
                          "data-testid": "menu-item-drafts",
                          className: "whitespace-nowrap flex-1 lg:flex-none",
                          children: "Rascunhos"
                        }
                      ),
                      /* @__PURE__ */ (0, import_jsx_runtime103.jsx)(
                        MenuItem,
                        {
                          variant: "menu2",
                          value: "models" /* MODELS */,
                          "data-testid": "menu-item-models",
                          className: "whitespace-nowrap flex-1 lg:flex-none",
                          children: "Modelos"
                        }
                      )
                    ]
                  }
                )
              }
            ) })
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime103.jsxs)("div", { className: "flex flex-col items-center w-full min-h-0 flex-1", children: [
            activeTab === "history" /* HISTORY */ && /* @__PURE__ */ (0, import_jsx_runtime103.jsx)(
              HistoryTab,
              {
                fetchActivitiesHistory,
                onCreateActivity,
                onRowClick,
                emptyStateImage,
                noSearchImage,
                mapSubjectNameToEnum: mapSubjectNameToEnum2,
                userFilterData
              }
            ),
            activeTab === "drafts" /* DRAFTS */ && /* @__PURE__ */ (0, import_jsx_runtime103.jsx)(DraftsTab, {}),
            activeTab === "models" /* MODELS */ && /* @__PURE__ */ (0, import_jsx_runtime103.jsx)(
              ModelsTab,
              {
                fetchActivityModels,
                deleteActivityModel,
                onCreateModel,
                onSendActivity,
                onEditModel,
                emptyStateImage,
                noSearchImage,
                mapSubjectNameToEnum: mapSubjectNameToEnum2,
                userFilterData,
                subjectsMap
              }
            )
          ] })
        ] })
      ]
    }
  );
};

// src/utils/subjectMappers.ts
var SUBJECT_NAME_MAPPING = {
  matem\u00E1tica: "Matem\xE1tica" /* MATEMATICA */,
  portugu\u00EAs: "Portugu\xEAs" /* PORTUGUES */,
  ci\u00EAncias: "Biologia" /* BIOLOGIA */,
  hist\u00F3ria: "Hist\xF3ria" /* HISTORIA */,
  geografia: "Geografia" /* GEOGRAFIA */,
  ingl\u00EAs: "Ingl\xEAs" /* INGLES */,
  "educa\xE7\xE3o f\xEDsica": "Ed. F\xEDsica" /* EDUCACAO_FISICA */,
  artes: "Artes" /* ARTES */,
  tecnologia: "Trilhas" /* TRILHAS */,
  f\u00EDsica: "F\xEDsica" /* FISICA */,
  literatura: "Literatura" /* LITERATURA */,
  biologia: "Biologia" /* BIOLOGIA */,
  qu\u00EDmica: "Qu\xEDmica" /* QUIMICA */,
  filosofia: "Filosofia" /* FILOSOFIA */,
  espanhol: "Espanhol" /* ESPANHOL */,
  reda\u00E7\u00E3o: "Reda\xE7\xE3o" /* REDACAO */,
  sociologia: "Sociologia" /* SOCIOLOGIA */,
  trilhas: "Trilhas" /* TRILHAS */
};
var mapSubjectNameToEnum = (subjectName) => {
  const normalized = subjectName.trim().toLowerCase();
  return SUBJECT_NAME_MAPPING[normalized] || null;
};
var mapSubjectEnumToName = (subjectEnum) => {
  const reverseMapping = {
    ["Matem\xE1tica" /* MATEMATICA */]: "Matem\xE1tica",
    ["Portugu\xEAs" /* PORTUGUES */]: "Portugu\xEAs",
    ["Biologia" /* BIOLOGIA */]: "Biologia",
    ["Hist\xF3ria" /* HISTORIA */]: "Hist\xF3ria",
    ["Geografia" /* GEOGRAFIA */]: "Geografia",
    ["Ingl\xEAs" /* INGLES */]: "Ingl\xEAs",
    ["Ed. F\xEDsica" /* EDUCACAO_FISICA */]: "Educa\xE7\xE3o F\xEDsica",
    ["Artes" /* ARTES */]: "Artes",
    ["F\xEDsica" /* FISICA */]: "F\xEDsica",
    ["Literatura" /* LITERATURA */]: "Literatura",
    ["Qu\xEDmica" /* QUIMICA */]: "Qu\xEDmica",
    ["Filosofia" /* FILOSOFIA */]: "Filosofia",
    ["Espanhol" /* ESPANHOL */]: "Espanhol",
    ["Reda\xE7\xE3o" /* REDACAO */]: "Reda\xE7\xE3o",
    ["Sociologia" /* SOCIOLOGIA */]: "Sociologia",
    ["Trilhas" /* TRILHAS */]: "Trilhas"
  };
  return reverseMapping[subjectEnum] || subjectEnum;
};

// src/utils/filterHelpers.ts
var getSchoolOptionsFromUserData = (userData) => {
  if (!userData?.userInstitutions) {
    return [];
  }
  const schoolsMap = /* @__PURE__ */ new Map();
  for (const userInst of userData.userInstitutions) {
    if (userInst.school?.id && userInst.school?.name) {
      schoolsMap.set(userInst.school.id, {
        id: userInst.school.id,
        name: userInst.school.name
      });
    }
  }
  return Array.from(schoolsMap.values()).sort(
    (a, b) => a.name.localeCompare(b.name, "pt-BR")
  );
};
var getSubjectOptionsFromUserData = (userData) => {
  if (!userData?.subTeacherTopicClasses) {
    return [];
  }
  const subjectsMap = /* @__PURE__ */ new Map();
  for (const subTeacher of userData.subTeacherTopicClasses) {
    if (subTeacher.subject?.id && subTeacher.subject?.name) {
      subjectsMap.set(subTeacher.subject.id, {
        id: subTeacher.subject.id,
        name: subTeacher.subject.name
      });
    }
  }
  return Array.from(subjectsMap.values()).sort(
    (a, b) => a.name.localeCompare(b.name, "pt-BR")
  );
};
var getSchoolYearOptionsFromUserData = (userData) => {
  if (!userData?.userInstitutions) {
    return [];
  }
  const schoolYearsMap = /* @__PURE__ */ new Map();
  for (const userInst of userData.userInstitutions) {
    if (userInst.schoolYear?.id && userInst.schoolYear?.name) {
      schoolYearsMap.set(userInst.schoolYear.id, {
        id: userInst.schoolYear.id,
        name: userInst.schoolYear.name
      });
    }
  }
  return Array.from(schoolYearsMap.values()).sort(
    (a, b) => a.name.localeCompare(b.name, "pt-BR")
  );
};
var getClassOptionsFromUserData = (userData) => {
  if (!userData) {
    return [];
  }
  const classesMap = /* @__PURE__ */ new Map();
  if (userData.userInstitutions) {
    for (const userInst of userData.userInstitutions) {
      if (userInst.class?.id && userInst.class?.name) {
        classesMap.set(userInst.class.id, {
          id: userInst.class.id,
          name: userInst.class.name
        });
      }
    }
  }
  if (userData.subTeacherTopicClasses) {
    for (const subTeacher of userData.subTeacherTopicClasses) {
      if (subTeacher.class?.id && subTeacher.class?.name) {
        classesMap.set(subTeacher.class.id, {
          id: subTeacher.class.id,
          name: subTeacher.class.name
        });
      }
    }
  }
  return Array.from(classesMap.values()).sort(
    (a, b) => a.name.localeCompare(b.name, "pt-BR")
  );
};
var buildUserFilterData = (userData) => ({
  schools: getSchoolOptionsFromUserData(userData),
  subjects: getSubjectOptionsFromUserData(userData)
});

// src/hooks/useChat.ts
var import_react86 = require("react");
var WS_STATES = {
  CONNECTING: 0,
  OPEN: 1,
  CLOSING: 2,
  CLOSED: 3
};
function useChat({
  wsUrl,
  token,
  roomId,
  userId,
  onConnect,
  onDisconnect,
  onError,
  autoReconnect = true,
  reconnectInterval = 3e3,
  maxReconnectAttempts = 5
}) {
  const [isConnected, setIsConnected] = (0, import_react86.useState)(false);
  const [messages, setMessages] = (0, import_react86.useState)([]);
  const [participants, setParticipants] = (0, import_react86.useState)([]);
  const [error, setError] = (0, import_react86.useState)(null);
  const wsRef = (0, import_react86.useRef)(null);
  const reconnectAttemptsRef = (0, import_react86.useRef)(0);
  const reconnectTimeoutRef = (0, import_react86.useRef)(
    null
  );
  const isManualDisconnectRef = (0, import_react86.useRef)(false);
  const isConnectingRef = (0, import_react86.useRef)(false);
  const connectRef = (0, import_react86.useRef)(() => {
  });
  const sendWsMessage = (0, import_react86.useCallback)((message) => {
    if (wsRef.current?.readyState === WS_STATES.OPEN) {
      wsRef.current.send(JSON.stringify(message));
    }
  }, []);
  const sendMessage = (0, import_react86.useCallback)(
    (content) => {
      const trimmedContent = content.trim();
      if (!trimmedContent) return;
      sendWsMessage({
        type: "message",
        payload: { content: trimmedContent }
      });
    },
    [sendWsMessage]
  );
  const leave = (0, import_react86.useCallback)(() => {
    isManualDisconnectRef.current = true;
    sendWsMessage({ type: "leave" });
    wsRef.current?.close(1e3, "User left");
  }, [sendWsMessage]);
  const handleMessage = (0, import_react86.useCallback)(
    (event) => {
      try {
        const data = JSON.parse(event.data);
        switch (data.type) {
          case "history":
            if (data.payload.messages) {
              setMessages(data.payload.messages);
            }
            break;
          case "participants":
            if (data.payload.participants) {
              setParticipants(data.payload.participants);
            }
            break;
          case "new_message":
            if (data.payload.message) {
              setMessages((prev) => [...prev, data.payload.message]);
            }
            break;
          case "user_joined":
            if (data.payload.user) {
              const user = data.payload.user;
              setParticipants((prev) => {
                const exists = prev.some(
                  (p) => p.userInstitutionId === user.userInstitutionId
                );
                if (exists) {
                  return prev.map(
                    (p) => p.userInstitutionId === user.userInstitutionId ? { ...p, isOnline: true } : p
                  );
                }
                return [
                  ...prev,
                  {
                    userInstitutionId: user.userInstitutionId,
                    name: user.name,
                    photo: user.photo,
                    role: user.role,
                    isOnline: true
                  }
                ];
              });
            }
            break;
          case "user_left":
            if (data.payload.user) {
              const user = data.payload.user;
              setParticipants(
                (prev) => prev.map(
                  (p) => p.userInstitutionId === user.userInstitutionId ? { ...p, isOnline: false } : p
                )
              );
            }
            break;
          case "error": {
            const errorMessage = data.payload.message_text || "Erro desconhecido";
            setError(new Error(errorMessage));
            onError?.(new Error(errorMessage));
            break;
          }
        }
      } catch (err) {
        console.error("Error parsing WebSocket message:", err);
      }
    },
    [onError]
  );
  const connect = (0, import_react86.useCallback)(() => {
    if (isConnectingRef.current) {
      return;
    }
    const url = new URL(wsUrl);
    url.searchParams.set("roomId", roomId);
    url.searchParams.set("token", token);
    if (wsRef.current) {
      wsRef.current.close();
    }
    isConnectingRef.current = true;
    const ws = new WebSocket(url.toString());
    wsRef.current = ws;
    ws.onopen = () => {
      isConnectingRef.current = false;
      setIsConnected(true);
      setError(null);
      reconnectAttemptsRef.current = 0;
      onConnect?.();
    };
    ws.onmessage = handleMessage;
    ws.onerror = () => {
      isConnectingRef.current = false;
      const error2 = new Error("Erro na conex\xE3o WebSocket");
      setError(error2);
      onError?.(error2);
    };
    ws.onclose = (event) => {
      isConnectingRef.current = false;
      setIsConnected(false);
      onDisconnect?.();
      if (autoReconnect && !isManualDisconnectRef.current && reconnectAttemptsRef.current < maxReconnectAttempts && event.code !== 4001 && // Unauthorized
      event.code !== 4002 && // Missing roomId
      event.code !== 4003) {
        reconnectAttemptsRef.current += 1;
        reconnectTimeoutRef.current = setTimeout(() => {
          connect();
        }, reconnectInterval);
      }
    };
  }, [
    wsUrl,
    roomId,
    token,
    handleMessage,
    onConnect,
    onDisconnect,
    onError,
    autoReconnect,
    reconnectInterval,
    maxReconnectAttempts
  ]);
  connectRef.current = connect;
  const reconnect = (0, import_react86.useCallback)(() => {
    isManualDisconnectRef.current = false;
    reconnectAttemptsRef.current = 0;
    connectRef.current();
  }, []);
  (0, import_react86.useEffect)(() => {
    if (!roomId) {
      return;
    }
    if (reconnectTimeoutRef.current) {
      clearTimeout(reconnectTimeoutRef.current);
      reconnectTimeoutRef.current = null;
    }
    isManualDisconnectRef.current = false;
    isConnectingRef.current = false;
    reconnectAttemptsRef.current = 0;
    if (wsRef.current) {
      wsRef.current.close(1e3, "Room changed");
      wsRef.current = null;
    }
    const timeoutId = setTimeout(() => {
      connectRef.current();
    }, 100);
    return () => {
      clearTimeout(timeoutId);
      isManualDisconnectRef.current = true;
      isConnectingRef.current = false;
      if (reconnectTimeoutRef.current) {
        clearTimeout(reconnectTimeoutRef.current);
      }
      wsRef.current?.close(1e3, "Component unmounted");
    };
  }, [roomId]);
  return {
    isConnected,
    messages,
    participants,
    sendMessage,
    leave,
    error,
    reconnect,
    currentUserId: userId
  };
}
function createUseChat(baseWsUrl) {
  return (options) => useChat({ ...options, wsUrl: baseWsUrl });
}

// src/hooks/useChatRooms.ts
var import_react87 = require("react");
function useChatRooms({
  apiClient
}) {
  const [rooms, setRooms] = (0, import_react87.useState)([]);
  const [availableUsers, setAvailableUsers] = (0, import_react87.useState)([]);
  const [loading, setLoading] = (0, import_react87.useState)(false);
  const [error, setError] = (0, import_react87.useState)(null);
  const fetchRooms = (0, import_react87.useCallback)(async () => {
    setLoading(true);
    setError(null);
    try {
      const response = await apiClient.get(
        "/chat/rooms"
      );
      setRooms(response.data.data.rooms);
    } catch (err) {
      const error2 = err instanceof Error ? err : new Error("Erro ao carregar salas");
      setError(error2);
      console.error("Error fetching chat rooms:", err);
    } finally {
      setLoading(false);
    }
  }, [apiClient]);
  const fetchAvailableUsers = (0, import_react87.useCallback)(async () => {
    setLoading(true);
    setError(null);
    try {
      const response = await apiClient.get(
        "/chat/available-users"
      );
      setAvailableUsers(response.data.data.users);
    } catch (err) {
      const error2 = err instanceof Error ? err : new Error("Erro ao carregar usu\xE1rios");
      setError(error2);
      console.error("Error fetching available users:", err);
    } finally {
      setLoading(false);
    }
  }, [apiClient]);
  const createRoom = (0, import_react87.useCallback)(
    async (participantIds) => {
      setLoading(true);
      setError(null);
      try {
        const response = await apiClient.post(
          "/chat/rooms",
          {
            participantIds
          }
        );
        await fetchRooms();
        return response.data.data.room;
      } catch (err) {
        const error2 = err instanceof Error ? err : new Error("Erro ao criar sala");
        setError(error2);
        console.error("Error creating chat room:", err);
        return null;
      } finally {
        setLoading(false);
      }
    },
    [apiClient, fetchRooms]
  );
  const clearError = (0, import_react87.useCallback)(() => {
    setError(null);
  }, []);
  return {
    rooms,
    availableUsers,
    loading,
    error,
    fetchRooms,
    fetchAvailableUsers,
    createRoom,
    clearError
  };
}
function createUseChatRooms(apiClient) {
  return () => useChatRooms({ apiClient });
}

// src/types/chat.ts
var PROFILE_ROLES = /* @__PURE__ */ ((PROFILE_ROLES2) => {
  PROFILE_ROLES2["SUPER_ADMIN"] = "SUPER_ADMIN";
  PROFILE_ROLES2["GENERAL_MANAGER"] = "GENERAL_MANAGER";
  PROFILE_ROLES2["REGIONAL_MANAGER"] = "REGIONAL_MANAGER";
  PROFILE_ROLES2["UNIT_MANAGER"] = "UNIT_MANAGER";
  PROFILE_ROLES2["TEACHER"] = "TEACHER";
  PROFILE_ROLES2["STUDENT"] = "STUDENT";
  return PROFILE_ROLES2;
})(PROFILE_ROLES || {});
var CHAT_MESSAGE_TYPES = {
  TEXT: "text",
  SYSTEM: "system"
};

// src/components/Chat/Chat.tsx
var import_react88 = require("react");
var import_react89 = require("@phosphor-icons/react");
var import_jsx_runtime104 = require("react/jsx-runtime");
var RoomItem = ({
  room,
  onClick,
  isActive
}) => /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(
  Button_default,
  {
    variant: "link",
    onClick,
    className: cn(
      "w-full p-3 rounded-lg text-left transition-colors justify-start h-auto",
      "hover:bg-background-100",
      isActive && "bg-primary-50 border-l-4 border-primary-500"
    ),
    children: /* @__PURE__ */ (0, import_jsx_runtime104.jsxs)("div", { className: "flex items-start gap-3 w-full", children: [
      /* @__PURE__ */ (0, import_jsx_runtime104.jsx)("div", { className: "w-10 h-10 rounded-full bg-primary-100 flex items-center justify-center flex-shrink-0", children: /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(import_react89.UsersIcon, { size: 20, className: "text-primary-600" }) }),
      /* @__PURE__ */ (0, import_jsx_runtime104.jsxs)("div", { className: "flex-1 min-w-0", children: [
        /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(Text_default, { size: "sm", weight: "semibold", className: "text-text-900 truncate", children: room.name }),
        room.lastMessage && /* @__PURE__ */ (0, import_jsx_runtime104.jsxs)(Text_default, { size: "xs", className: "text-text-500 truncate mt-1", children: [
          room.lastMessage.senderName,
          ": ",
          room.lastMessage.content
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime104.jsxs)(Text_default, { size: "xs", className: "text-text-400 mt-1", children: [
          room.participantCount,
          " participantes"
        ] })
      ] })
    ] })
  }
);
var MessageBubble = ({
  message,
  isOwn
}) => /* @__PURE__ */ (0, import_jsx_runtime104.jsxs)("div", { className: cn("flex gap-2 mb-3", isOwn && "flex-row-reverse"), children: [
  !isOwn && /* @__PURE__ */ (0, import_jsx_runtime104.jsx)("div", { className: "w-8 h-8 rounded-full bg-gray-200 flex items-center justify-center flex-shrink-0", children: message.senderPhoto ? /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(
    "img",
    {
      src: message.senderPhoto,
      alt: message.senderName,
      className: "w-8 h-8 rounded-full object-cover"
    }
  ) : /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(Text_default, { size: "xs", weight: "bold", className: "text-gray-600", children: message.senderName.charAt(0).toUpperCase() }) }),
  /* @__PURE__ */ (0, import_jsx_runtime104.jsxs)("div", { className: cn("max-w-[70%]", isOwn && "items-end"), children: [
    !isOwn && /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(Text_default, { size: "xs", className: "text-text-500 mb-1", children: message.senderName }),
    /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(
      "div",
      {
        className: cn(
          "px-4 py-2 rounded-2xl",
          isOwn ? "bg-primary-500 text-white rounded-br-md" : "bg-background-100 text-text-900 rounded-bl-md"
        ),
        children: /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(Text_default, { size: "sm", children: message.content })
      }
    ),
    /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(
      Text_default,
      {
        size: "xs",
        className: cn("text-text-400 mt-1", isOwn && "text-right"),
        children: new Date(message.createdAt).toLocaleTimeString("pt-BR", {
          hour: "2-digit",
          minute: "2-digit"
        })
      }
    )
  ] })
] });
var ParticipantItem = ({ participant }) => /* @__PURE__ */ (0, import_jsx_runtime104.jsxs)("div", { className: "flex items-center gap-2 py-2", children: [
  /* @__PURE__ */ (0, import_jsx_runtime104.jsxs)("div", { className: "relative", children: [
    /* @__PURE__ */ (0, import_jsx_runtime104.jsx)("div", { className: "w-8 h-8 rounded-full bg-gray-200 flex items-center justify-center", children: participant.photo ? /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(
      "img",
      {
        src: participant.photo,
        alt: participant.name,
        className: "w-8 h-8 rounded-full object-cover"
      }
    ) : /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(Text_default, { size: "xs", weight: "bold", className: "text-gray-600", children: participant.name.charAt(0).toUpperCase() }) }),
    participant.isOnline && /* @__PURE__ */ (0, import_jsx_runtime104.jsx)("div", { className: "absolute bottom-0 right-0 w-3 h-3 bg-green-500 rounded-full border-2 border-white" })
  ] }),
  /* @__PURE__ */ (0, import_jsx_runtime104.jsxs)("div", { className: "flex-1 min-w-0", children: [
    /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(Text_default, { size: "sm", className: "text-text-900 truncate", children: participant.name }),
    /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(Text_default, { size: "xs", className: "text-text-500", children: participant.role })
  ] })
] });
var UserSelector = ({
  users,
  selectedIds,
  onToggle
}) => /* @__PURE__ */ (0, import_jsx_runtime104.jsx)("div", { className: "space-y-2 max-h-64 overflow-y-auto", children: users.map((user) => /* @__PURE__ */ (0, import_jsx_runtime104.jsxs)(
  Button_default,
  {
    variant: "link",
    onClick: () => onToggle(user.userInstitutionId),
    className: cn(
      "w-full flex items-center gap-3 p-3 rounded-lg transition-colors justify-start h-auto",
      selectedIds.has(user.userInstitutionId) ? "bg-primary-50 border border-primary-500" : "bg-background-50 hover:bg-background-100 border border-transparent"
    ),
    children: [
      /* @__PURE__ */ (0, import_jsx_runtime104.jsx)("div", { className: "w-10 h-10 rounded-full bg-gray-200 flex items-center justify-center", children: user.photo ? /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(
        "img",
        {
          src: user.photo,
          alt: user.name,
          className: "w-10 h-10 rounded-full object-cover"
        }
      ) : /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(Text_default, { size: "sm", weight: "bold", className: "text-gray-600", children: user.name.charAt(0).toUpperCase() }) }),
      /* @__PURE__ */ (0, import_jsx_runtime104.jsxs)("div", { className: "flex-1 text-left", children: [
        /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(Text_default, { size: "sm", weight: "medium", className: "text-text-900", children: user.name }),
        /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(Text_default, { size: "xs", className: "text-text-500", children: user.profileName })
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(
        "div",
        {
          className: cn(
            "w-5 h-5 rounded-full border-2 flex items-center justify-center",
            selectedIds.has(user.userInstitutionId) ? "bg-primary-500 border-primary-500" : "border-gray-300"
          ),
          children: selectedIds.has(user.userInstitutionId) && /* @__PURE__ */ (0, import_jsx_runtime104.jsx)("div", { className: "w-2 h-2 bg-white rounded-full" })
        }
      )
    ]
  },
  user.userInstitutionId
)) });
function Chat(props) {
  const { userId, token } = props;
  if (!userId || !token) {
    return /* @__PURE__ */ (0, import_jsx_runtime104.jsx)("div", { className: "flex items-center justify-center h-96", children: /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(Text_default, { size: "sm", className: "text-text-500", children: "Carregando..." }) });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(ChatContent, { ...props });
}
function ChatContent({
  apiClient,
  wsUrl,
  token,
  userId,
  userName,
  userPhoto,
  userRole,
  className,
  initialRoomId,
  onRoomChange,
  onBackToList
}) {
  const [view, setView] = (0, import_react88.useState)("list");
  const [selectedRoom, setSelectedRoom] = (0, import_react88.useState)(
    null
  );
  const [selectedUserIds, setSelectedUserIds] = (0, import_react88.useState)(
    /* @__PURE__ */ new Set()
  );
  const [messageInput, setMessageInput] = (0, import_react88.useState)("");
  const [showCreateModal, setShowCreateModal] = (0, import_react88.useState)(false);
  const hasHandledInitialRoomRef = (0, import_react88.useRef)(false);
  const {
    rooms,
    availableUsers,
    loading: roomsLoading,
    error: roomsError,
    fetchRooms,
    fetchAvailableUsers,
    createRoom
  } = useChatRooms({ apiClient });
  const {
    isConnected,
    messages,
    participants,
    sendMessage,
    error: chatError
  } = useChat({
    wsUrl,
    token,
    roomId: selectedRoom?.id || "",
    userId,
    onConnect: () => console.log("Connected to chat"),
    onDisconnect: () => console.log("Disconnected from chat"),
    onError: (err) => console.error("Chat error:", err)
  });
  const getRoleLabel = () => {
    return userRole === "TEACHER" /* TEACHER */ ? "Professor" : "Aluno";
  };
  (0, import_react88.useEffect)(() => {
    fetchRooms();
  }, [fetchRooms]);
  (0, import_react88.useEffect)(() => {
    if (hasHandledInitialRoomRef.current) {
      return;
    }
    if (!initialRoomId || roomsLoading) {
      return;
    }
    if (rooms?.length > 0) {
      const room = rooms.find((r) => r.id === initialRoomId);
      if (room) {
        hasHandledInitialRoomRef.current = true;
        setSelectedRoom(room);
        setView("room");
      } else {
        hasHandledInitialRoomRef.current = true;
        onBackToList?.();
      }
    } else if (rooms !== void 0 && !roomsLoading) {
      hasHandledInitialRoomRef.current = true;
      onBackToList?.();
    }
  }, [initialRoomId, rooms, roomsLoading, onBackToList]);
  const handleSelectRoom = (0, import_react88.useCallback)(
    (room) => {
      setSelectedRoom(room);
      setView("room");
      onRoomChange?.(room.id);
    },
    [onRoomChange]
  );
  const handleOpenCreateModal = (0, import_react88.useCallback)(async () => {
    await fetchAvailableUsers();
    setSelectedUserIds(/* @__PURE__ */ new Set());
    setShowCreateModal(true);
  }, [fetchAvailableUsers]);
  const handleToggleUser = (0, import_react88.useCallback)((id) => {
    setSelectedUserIds((prev) => {
      const next = new Set(prev);
      if (next.has(id)) {
        next.delete(id);
      } else {
        next.add(id);
      }
      return next;
    });
  }, []);
  const handleCreateRoom = (0, import_react88.useCallback)(async () => {
    if (selectedUserIds.size === 0) return;
    const room = await createRoom(Array.from(selectedUserIds));
    if (room) {
      setShowCreateModal(false);
      setSelectedUserIds(/* @__PURE__ */ new Set());
      onRoomChange?.(room.id);
    }
  }, [selectedUserIds, createRoom, onRoomChange]);
  const handleSendMessage = (0, import_react88.useCallback)(() => {
    if (!messageInput.trim()) return;
    sendMessage(messageInput);
    setMessageInput("");
  }, [messageInput, sendMessage]);
  const handleBackToList = (0, import_react88.useCallback)(() => {
    setSelectedRoom(null);
    setView("list");
    onBackToList?.();
  }, [onBackToList]);
  const renderMessagesContent = () => {
    if (chatError) {
      return /* @__PURE__ */ (0, import_jsx_runtime104.jsx)("div", { className: "flex items-center justify-center h-full", children: /* @__PURE__ */ (0, import_jsx_runtime104.jsxs)("div", { className: "text-center", children: [
        /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(Text_default, { size: "sm", className: "text-red-500 mb-2", children: "Erro de conexao com o chat" }),
        /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(Text_default, { size: "xs", className: "text-text-500", children: "Tentando reconectar..." })
      ] }) });
    }
    const userMessages = messages?.filter(
      (message) => message.messageType !== CHAT_MESSAGE_TYPES.SYSTEM
    );
    if (!userMessages?.length) {
      return /* @__PURE__ */ (0, import_jsx_runtime104.jsx)("div", { className: "flex items-center justify-center h-full", children: /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(Text_default, { size: "sm", className: "text-text-500", children: "Nenhuma mensagem ainda. Comece a conversa!" }) });
    }
    return userMessages.map((message) => /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(
      MessageBubble,
      {
        message,
        isOwn: message.senderId === userId
      },
      message.id
    ));
  };
  const renderRoomList = () => /* @__PURE__ */ (0, import_jsx_runtime104.jsxs)("div", { className: "flex flex-col h-full", children: [
    /* @__PURE__ */ (0, import_jsx_runtime104.jsxs)("div", { className: "p-4 border-b border-background-200 flex items-center justify-between", children: [
      /* @__PURE__ */ (0, import_jsx_runtime104.jsxs)("div", { className: "flex items-center gap-3", children: [
        /* @__PURE__ */ (0, import_jsx_runtime104.jsx)("div", { className: "w-10 h-10 rounded-full bg-primary-100 flex items-center justify-center flex-shrink-0", children: userPhoto ? /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(
          "img",
          {
            src: userPhoto,
            alt: userName,
            className: "w-10 h-10 rounded-full object-cover"
          }
        ) : /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(Text_default, { size: "sm", weight: "bold", className: "text-primary-600", children: userName.charAt(0).toUpperCase() }) }),
        /* @__PURE__ */ (0, import_jsx_runtime104.jsxs)("div", { children: [
          /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(Text_default, { size: "lg", weight: "bold", className: "text-text-900", children: "Conversas" }),
          /* @__PURE__ */ (0, import_jsx_runtime104.jsxs)(Text_default, { size: "xs", className: "text-text-500", children: [
            userName,
            " - ",
            getRoleLabel()
          ] })
        ] })
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(
        Button_default,
        {
          variant: "solid",
          size: "small",
          onClick: handleOpenCreateModal,
          iconLeft: /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(import_react89.PlusIcon, { size: 16 }),
          children: "Nova conversa"
        }
      )
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime104.jsxs)("div", { className: "flex-1 overflow-y-auto p-2", children: [
      roomsError && /* @__PURE__ */ (0, import_jsx_runtime104.jsxs)("div", { className: "p-4 text-center", children: [
        /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(Text_default, { size: "sm", className: "text-red-500 mb-2", children: "Erro ao carregar conversas" }),
        /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(Button_default, { variant: "outline", size: "small", onClick: fetchRooms, children: "Tentar novamente" })
      ] }),
      !roomsError && roomsLoading && /* @__PURE__ */ (0, import_jsx_runtime104.jsx)("div", { className: "space-y-3 p-2", children: [1, 2, 3].map((i) => /* @__PURE__ */ (0, import_jsx_runtime104.jsxs)("div", { className: "flex items-center gap-3", children: [
        /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(SkeletonRounded, { className: "w-10 h-10" }),
        /* @__PURE__ */ (0, import_jsx_runtime104.jsxs)("div", { className: "flex-1", children: [
          /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(SkeletonText, { className: "w-3/4 h-4 mb-2" }),
          /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(SkeletonText, { className: "w-1/2 h-3" })
        ] })
      ] }, i)) }),
      !roomsError && !roomsLoading && !rooms?.length && /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(
        EmptyState_default,
        {
          title: "Nenhuma conversa",
          description: "Comece uma nova conversa clicando no botao acima"
        }
      ),
      !roomsError && !roomsLoading && !!rooms?.length && /* @__PURE__ */ (0, import_jsx_runtime104.jsx)("div", { className: "space-y-1", children: rooms.map((room) => /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(
        RoomItem,
        {
          room,
          onClick: () => handleSelectRoom(room),
          isActive: selectedRoom?.id === room.id
        },
        room.id
      )) })
    ] })
  ] });
  const renderChatRoom = () => {
    if (!selectedRoom) return null;
    return /* @__PURE__ */ (0, import_jsx_runtime104.jsxs)("div", { className: "flex h-full", children: [
      /* @__PURE__ */ (0, import_jsx_runtime104.jsxs)("div", { className: "flex-1 flex flex-col", children: [
        /* @__PURE__ */ (0, import_jsx_runtime104.jsxs)("div", { className: "p-4 border-b border-background-200 flex items-center gap-3", children: [
          /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(Button_default, { variant: "link", size: "small", onClick: handleBackToList, children: /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(import_react89.XIcon, { size: 20 }) }),
          /* @__PURE__ */ (0, import_jsx_runtime104.jsxs)("div", { className: "flex-1", children: [
            /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(Text_default, { size: "md", weight: "semibold", className: "text-text-900", children: selectedRoom.name }),
            /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(Text_default, { size: "xs", className: "text-text-500", children: isConnected ? "Conectado" : "Conectando..." })
          ] })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime104.jsx)("div", { className: "flex-1 overflow-y-auto p-4", children: renderMessagesContent() }),
        /* @__PURE__ */ (0, import_jsx_runtime104.jsx)("div", { className: "p-4 border-t border-background-200", children: /* @__PURE__ */ (0, import_jsx_runtime104.jsxs)("div", { className: "flex gap-2", children: [
          /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(
            Input_default,
            {
              placeholder: "Digite sua mensagem...",
              value: messageInput,
              onChange: (e) => setMessageInput(e.target.value),
              onKeyDown: (e) => {
                if (e.key === "Enter" && !e.shiftKey) {
                  e.preventDefault();
                  handleSendMessage();
                }
              },
              className: "flex-1"
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(
            Button_default,
            {
              variant: "solid",
              onClick: handleSendMessage,
              disabled: !messageInput.trim() || !isConnected,
              children: /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(import_react89.PaperPlaneTiltIcon, { size: 20 })
            }
          )
        ] }) })
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime104.jsxs)("div", { className: "w-64 border-l border-background-200 p-4 hidden lg:block", children: [
        /* @__PURE__ */ (0, import_jsx_runtime104.jsxs)(Text_default, { size: "sm", weight: "semibold", className: "text-text-900 mb-3", children: [
          "Participantes (",
          participants?.length ?? 0,
          ")"
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime104.jsx)("div", { className: "space-y-1", children: participants?.map((participant) => /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(
          ParticipantItem,
          {
            participant
          },
          participant.userInstitutionId
        )) })
      ] })
    ] });
  };
  return /* @__PURE__ */ (0, import_jsx_runtime104.jsxs)(
    "div",
    {
      className: cn(
        "bg-background rounded-xl border border-background-200 h-[600px]",
        className
      ),
      children: [
        view === "list" && renderRoomList(),
        view === "room" && renderChatRoom(),
        /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(
          Modal_default,
          {
            isOpen: showCreateModal,
            onClose: () => setShowCreateModal(false),
            title: "Nova conversa",
            children: /* @__PURE__ */ (0, import_jsx_runtime104.jsxs)("div", { className: "p-4", children: [
              /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(Text_default, { size: "sm", className: "text-text-600 mb-4", children: "Selecione os participantes para iniciar uma conversa" }),
              roomsLoading && /* @__PURE__ */ (0, import_jsx_runtime104.jsx)("div", { className: "space-y-3", children: [1, 2, 3].map((i) => /* @__PURE__ */ (0, import_jsx_runtime104.jsxs)("div", { className: "flex items-center gap-3", children: [
                /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(SkeletonRounded, { className: "w-10 h-10" }),
                /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(SkeletonText, { className: "flex-1 h-4" })
              ] }, i)) }),
              !roomsLoading && !availableUsers?.length && /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(Text_default, { size: "sm", className: "text-text-500 text-center py-4", children: "Nenhum usuario disponivel para chat" }),
              !roomsLoading && !!availableUsers?.length && /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(
                UserSelector,
                {
                  users: availableUsers,
                  selectedIds: selectedUserIds,
                  onToggle: handleToggleUser
                }
              ),
              /* @__PURE__ */ (0, import_jsx_runtime104.jsxs)("div", { className: "flex justify-end gap-2 mt-6", children: [
                /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(Button_default, { variant: "outline", onClick: () => setShowCreateModal(false), children: "Cancelar" }),
                /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(
                  Button_default,
                  {
                    variant: "solid",
                    onClick: handleCreateRoom,
                    disabled: selectedUserIds.size === 0 || roomsLoading,
                    children: "Criar conversa"
                  }
                )
              ] })
            ] })
          }
        )
      ]
    }
  );
}

// src/components/Chat/ChatLoading.tsx
var import_jsx_runtime105 = require("react/jsx-runtime");
function ChatLoading() {
  return /* @__PURE__ */ (0, import_jsx_runtime105.jsx)("div", { className: "flex items-center justify-center h-96", children: /* @__PURE__ */ (0, import_jsx_runtime105.jsx)(Text_default, { size: "sm", className: "text-text-500", children: "Carregando..." }) });
}

// src/utils/chatUtils.ts
var isChatUserInfoValid = (userInfo) => {
  return Boolean(userInfo.userId && userInfo.token);
};
var getChatWsUrl = (apiUrl) => {
  const baseUrl = apiUrl;
  return baseUrl.replace(/^http/, "ws") + "/chat/ws";
};
var getChatUserInfo = (user, tokens, sessionInfo, defaultUserName = "Usuario") => {
  const userId = String(user?.userInstitutionId ?? sessionInfo?.userId ?? "");
  const userName = String(
    user?.name ?? sessionInfo?.userName ?? defaultUserName
  );
  const photoUrl = String(
    user?.urlProfilePicture ?? sessionInfo?.urlProfilePicture ?? ""
  );
  const userPhoto = photoUrl || null;
  const token = tokens?.token || "";
  return {
    userId,
    userName,
    userPhoto,
    token
  };
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  ACTIVITY_AVAILABILITY,
  ACTIVITY_FILTER_STATUS_OPTIONS,
  ANSWER_STATUS,
  AccordionGroup,
  ActivitiesHistory,
  ActivityApiStatus,
  ActivityBadgeActionType,
  ActivityCardQuestionBanks,
  ActivityCardQuestionPreview,
  ActivityDetails,
  ActivityDisplayStatus,
  ActivityDraftType,
  ActivityFilters,
  ActivityFiltersPopover,
  ActivityPreview,
  ActivityStatus,
  ActivityType,
  Alert,
  AlertDialog,
  AlertsManager,
  AlertsManagerView,
  AlternativesList,
  AuthProvider,
  Badge,
  BreadcrumbMenu,
  Button,
  CHAT_MESSAGE_TYPES,
  CORRECTION_QUESTION_STATUS,
  Calendar,
  CardAccordation,
  CardActivitiesResults,
  CardAudio,
  CardPerformance,
  CardProgress,
  CardQuestions,
  CardResults,
  CardSimulado,
  CardSimulationHistory,
  CardStatus,
  CardTest,
  CardTopic,
  Chat,
  ChatLoading,
  CheckBox,
  CheckboxGroup,
  CheckboxList,
  CheckboxListItem,
  Chips,
  CorrectActivityModal,
  CreateActivity,
  DEFAULT_ACTIVITIES_PAGINATION,
  DEFAULT_MODELS_PAGINATION,
  DIFFICULTY_LEVEL_ENUM,
  DateTimeInput,
  Divider,
  DownloadButton,
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
  ERROR_MESSAGES,
  EmptyState,
  FileAttachment,
  FilterModal,
  GOAL_FILTER_STATUS_OPTIONS,
  GOAL_STATUS_OPTIONS,
  GoalApiStatus,
  GoalBadgeActionType,
  GoalDisplayStatus,
  IconButton,
  IconRender,
  IconRoundedButton,
  ImageUpload,
  Input,
  LatexRenderer,
  LoadingModal,
  Menu,
  MenuContent,
  MenuItem,
  MenuLabel,
  MenuOverflow,
  Modal,
  MultipleChoiceList,
  NavButton,
  NoSearchResult,
  NotFound,
  NotificationCard,
  NotificationEntityType,
  PROFILE_ROLES,
  ProfileMenuFooter,
  ProfileMenuHeader,
  ProfileMenuInfo,
  ProfileMenuSection,
  ProfileMenuTrigger,
  ProfileToggleTheme,
  ProgressBar,
  ProgressCircle,
  ProtectedRoute,
  PublicRoute,
  QUESTION_DIFFICULTY,
  QUESTION_STATUS,
  QUESTION_STATUS_ENUM,
  QUESTION_TYPE,
  QUIZ_TYPE,
  QuestionsPdfContent,
  QuestionsPdfGenerator,
  Quiz,
  QuizAlternative,
  QuizConnectDots,
  QuizContent,
  QuizDissertative,
  QuizFooter,
  QuizHeader,
  QuizHeaderResult,
  QuizImageQuestion,
  QuizListResult,
  QuizListResultByMateria,
  QuizMultipleChoice,
  QuizQuestionList,
  QuizResultHeaderTitle,
  QuizResultPerformance,
  QuizResultTitle,
  QuizTitle,
  QuizTrueOrFalse,
  Radio,
  RadioGroup,
  RadioGroupItem,
  RecommendedLessonDetails,
  RecommendedLessonsHistory,
  STUDENT_ACTIVITY_STATUS,
  SUBTYPE_ENUM,
  Search,
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
  SelectionButton,
  SendActivityModal,
  Skeleton,
  SkeletonCard,
  SkeletonCircle,
  SkeletonList,
  SkeletonRectangle,
  SkeletonRounded,
  SkeletonTable,
  SkeletonText,
  StatisticsCard,
  Stepper,
  StudentLessonStatus,
  StudentPerformanceModal,
  SubjectEnum,
  SubjectInfo,
  Support,
  SupportCategory,
  SupportStatus,
  Table,
  TableBody,
  TableCaption,
  TableCell,
  TableFooter,
  TableHead,
  TableHeader,
  TablePagination,
  TableProvider,
  TableRow,
  Text,
  TextArea,
  ThemeToggle,
  TicketModal,
  Toast,
  Toaster,
  VideoPlayer,
  WS_STATES,
  Whiteboard,
  activitiesHistoryApiResponseSchema,
  activityModelsApiResponseSchema,
  buildUserFilterData,
  cn,
  convertActivityFiltersToQuestionsFilter,
  createActivitiesHistoryHook,
  createActivityFiltersDataHook,
  createActivityModelsHook,
  createNotificationStore,
  createNotificationsHook,
  createQuestionsListHook,
  createRecommendedLessonDetailsHook,
  createRecommendedLessonsHistoryHook,
  createUseActivitiesHistory,
  createUseActivityFiltersData,
  createUseActivityModels,
  createUseChat,
  createUseChatRooms,
  createUseNotificationStore,
  createUseNotifications,
  createUseQuestionsList,
  createUseRecommendedLessonDetails,
  createUseRecommendedLessonsHistory,
  createZustandAuthAdapter,
  deriveStudentStatus,
  determineGoalStatus,
  formatDateToBrazilian,
  formatDaysToComplete,
  formatFileSize,
  formatQuestionNumbers,
  formatTimeAgo,
  formatTimeSpent,
  generateFileId,
  getActivityStatusBadgeAction,
  getCategoryIcon,
  getCategoryText,
  getChatUserInfo,
  getChatWsUrl,
  getClassOptionsFromUserData,
  getDeviceType,
  getGoalStatusBadgeAction,
  getQuestionStatusBadgeConfig,
  getRootDomain,
  getSchoolOptionsFromUserData,
  getSchoolYearOptionsFromUserData,
  getSelectedIdsFromCategories,
  getStatusBadge,
  getStatusBadgeAction,
  getStatusBadgeConfig,
  getStatusText,
  getStudentStatusBadgeAction,
  getSubjectColorClass,
  getSubjectColorWithOpacity,
  getSubjectIcon,
  getSubjectInfo,
  getSubjectName,
  getSubjectOptionsFromUserData,
  goalApiResponseSchema,
  goalDetailsApiResponseSchema,
  goalsHistoryApiResponseSchema,
  handleActivityFetchError,
  handleGoalFetchError,
  handleLessonDetailsFetchError,
  handleModelFetchError,
  historyApiResponseSchema,
  isChatUserInfoValid,
  isDeadlinePassed,
  isFormValid,
  isStepValid,
  mapActivityStatusToDisplay,
  mapApiStatusToInternal,
  mapInternalStatusToApi,
  mapQuestionTypeToEnum,
  mapQuestionTypeToEnumRequired,
  mapSubjectEnumToName,
  mapSubjectNameToEnum,
  questionTypeLabels,
  supportSchema,
  syncDropdownState,
  toggleArrayItem,
  toggleSingleValue,
  transformActivityToTableItem,
  transformGoalToTableItem,
  transformModelToTableItem,
  useAlertFormStore,
  useApiConfig,
  useAppContent,
  useAppInitialization,
  useAppStore,
  useAuth,
  useAuthGuard,
  useAuthStore,
  useBreadcrumb,
  useBreadcrumbBuilder,
  useChat,
  useChatRooms,
  useInstitutionId,
  useMobile,
  useQuestionFiltersStore,
  useQuestionsPdfPrint,
  useQuizStore,
  useRouteAuth,
  useSendActivityModal,
  useTableFilter,
  useTableSort,
  useTheme,
  useThemeStore,
  useToastStore,
  useUrlAuthentication,
  useUrlParams,
  validateActivityStep,
  validateDeadlineStep,
  validateRecipientStep,
  validateStep,
  withAuth
});
//# sourceMappingURL=index.js.map