# Examples

This document provides practical examples for common use cases of the React QUML Player.

## Table of Contents

- [Basic Examples](#basic-examples)
- [Advanced Integration](#advanced-integration)
- [Framework-Specific Examples](#framework-specific-examples)
- [Customization Examples](#customization-examples)
- [Real-World Use Cases](#real-world-use-cases)

## Basic Examples

### 1. Simple Assessment Player

```tsx
import React from "react";
import { QumlPlayer } from "@tekdi/react-quml-player";
import "@tekdi/react-quml-player/dist/style.css";

function SimpleAssessment() {
  const config = {
    apiConfig: {
      host: "https://api.sunbird.org",
      endpoint: "/action/questionset/v2/hierarchy",
    },
    telemetryConfig: {
      pdata: { id: "simple-app", ver: "1.0.0", pid: "assessment" },
      env: "production",
      channel: "education",
    },
  };

  return (
    <div className="container mx-auto p-4">
      <h1 className="text-2xl font-bold mb-4">Math Assessment</h1>
      <QumlPlayer
        questionSetId="do_1234567890"
        config={config}
        onComplete={(results) => {
          alert(
            `Assessment completed! Score: ${results.score}/${results.maxScore}`
          );
        }}
      />
    </div>
  );
}

export default SimpleAssessment;
```

### 2. Assessment with Custom Styling

```tsx
import React from "react";
import { QumlPlayer } from "@tekdi/react-quml-player";
import "@tekdi/react-quml-player/dist/style.css";
import "./custom-assessment.css"; // Your custom styles

function StyledAssessment() {
  const config = {
    apiConfig: {
      host: process.env.REACT_APP_SUNBIRD_HOST,
      endpoint: "/action/questionset/v2/hierarchy",
    },
    telemetryConfig: {
      pdata: { id: "styled-app", ver: "1.0.0", pid: "assessment" },
      env: "production",
      channel: "education",
    },
    questionSetConfig: {
      showTimer: true,
      showProgress: true,
    },
  };

  return (
    <div className="assessment-wrapper">
      <header className="assessment-header">
        <h1>Science Quiz - Grade 8</h1>
        <p>Answer all questions to complete the assessment.</p>
      </header>

      <QumlPlayer
        questionSetId="science_grade8_quiz"
        config={config}
        className="custom-player-theme"
        onComplete={(results) => {
          const percentage = (results.score / results.maxScore) * 100;
          console.log(`Assessment completed with ${percentage.toFixed(1)}%`);
        }}
      />
    </div>
  );
}

export default StyledAssessment;
```

### 3. Assessment with Progress Tracking

```tsx
import React, { useState } from "react";
import { QumlPlayer, PlayerState } from "@tekdi/react-quml-player";

function ProgressTrackedAssessment() {
  const [progress, setProgress] = useState<PlayerState | null>(null);

  const handleStateChange = (state: PlayerState) => {
    setProgress(state);

    // Save progress to localStorage
    localStorage.setItem("assessment_progress", JSON.stringify(state));
  };

  const handleComplete = (results: any) => {
    // Clear saved progress
    localStorage.removeItem("assessment_progress");

    // Show results
    console.log("Assessment Results:", results);
  };

  return (
    <div className="assessment-container">
      {progress && (
        <div className="progress-info mb-4 p-3 bg-blue-50 rounded">
          <p>
            Question {progress.currentQuestionIndex + 1} of{" "}
            {progress.visitedQuestions.length}
          </p>
          <p>
            Current Score: {progress.score}/{progress.maxScore}
          </p>
          <p>
            Time Elapsed: {Math.floor(progress.duration / 60)}:
            {(progress.duration % 60).toString().padStart(2, "0")}
          </p>
        </div>
      )}

      <QumlPlayer
        questionSetId="tracked_assessment"
        config={config}
        onPlayerStateChange={handleStateChange}
        onComplete={handleComplete}
      />
    </div>
  );
}
```

## Advanced Integration

### 4. Multi-User Assessment Platform

```tsx
import React, { useContext, useEffect, useState } from "react";
import { QumlPlayer } from "@tekdi/react-quml-player";
import { UserContext } from "../contexts/UserContext";
import { AssessmentAPI } from "../services/api";

interface Assessment {
  id: string;
  title: string;
  description: string;
  duration: number;
  questionSetId: string;
}

function MultiUserAssessmentPlatform() {
  const { currentUser, userToken } = useContext(UserContext);
  const [assessments, setAssessments] = useState<Assessment[]>([]);
  const [selectedAssessment, setSelectedAssessment] =
    useState<Assessment | null>(null);

  useEffect(() => {
    loadUserAssessments();
  }, [currentUser]);

  const loadUserAssessments = async () => {
    try {
      const response = await AssessmentAPI.getUserAssessments(currentUser.id);
      setAssessments(response.data);
    } catch (error) {
      console.error("Failed to load assessments:", error);
    }
  };

  const startAssessment = (assessment: Assessment) => {
    setSelectedAssessment(assessment);
  };

  const handleAssessmentComplete = async (results: any) => {
    try {
      // Save results to backend
      await AssessmentAPI.saveAssessmentResults({
        userId: currentUser.id,
        assessmentId: selectedAssessment!.id,
        results,
      });

      // Update local state
      setSelectedAssessment(null);

      // Show success message
      alert("Assessment completed successfully!");
    } catch (error) {
      console.error("Failed to save results:", error);
    }
  };

  const config = {
    apiConfig: {
      host: process.env.REACT_APP_API_HOST,
      endpoint: "/api/questionset/v2/hierarchy",
      headers: {
        Authorization: `Bearer ${userToken}`,
        "X-User-Id": currentUser.id,
      },
    },
    telemetryConfig: {
      pdata: { id: "platform", ver: "2.0.0", pid: "assessment" },
      env: "production",
      channel: "education-platform",
      uid: currentUser.id,
      sid: currentUser.sessionId,
    },
  };

  if (selectedAssessment) {
    return (
      <div className="assessment-player">
        <div className="assessment-header">
          <h2>{selectedAssessment.title}</h2>
          <button
            onClick={() => setSelectedAssessment(null)}
            className="exit-button"
          >
            Exit Assessment
          </button>
        </div>

        <QumlPlayer
          questionSetId={selectedAssessment.questionSetId}
          config={config}
          onComplete={handleAssessmentComplete}
          onExit={() => setSelectedAssessment(null)}
        />
      </div>
    );
  }

  return (
    <div className="assessment-dashboard">
      <h1>Available Assessments</h1>
      <div className="assessment-grid">
        {assessments.map((assessment) => (
          <div key={assessment.id} className="assessment-card">
            <h3>{assessment.title}</h3>
            <p>{assessment.description}</p>
            <p>Duration: {assessment.duration} minutes</p>
            <button onClick={() => startAssessment(assessment)}>
              Start Assessment
            </button>
          </div>
        ))}
      </div>
    </div>
  );
}
```

### 5. Assessment with Real-time Analytics

```tsx
import React, { useCallback } from "react";
import { QumlPlayer, useTelemetry } from "@tekdi/react-quml-player";
import { AnalyticsService } from "../services/analytics";

function AnalyticsEnabledAssessment() {
  const telemetryConfig = {
    pdata: { id: "analytics-app", ver: "1.0.0", pid: "assessment" },
    env: "production",
    channel: "analytics-channel",
    uid: "user-123",
  };

  const { sendTelemetryEvent } = useTelemetry(telemetryConfig);

  const handleCustomAnalytics = useCallback(
    async (eventType: string, data: any) => {
      // Send to custom analytics service
      await AnalyticsService.track(eventType, {
        userId: "user-123",
        timestamp: Date.now(),
        ...data,
      });

      // Also send as telemetry
      await sendTelemetryEvent({
        eid: "CUSTOM",
        edata: {
          type: eventType,
          ...data,
        },
      });
    },
    [sendTelemetryEvent]
  );

  const handlePlayerStateChange = useCallback(
    (state: any) => {
      handleCustomAnalytics("progress_update", {
        questionIndex: state.currentQuestionIndex,
        score: state.score,
        timeElapsed: state.duration,
      });
    },
    [handleCustomAnalytics]
  );

  const config = {
    apiConfig: {
      host: "https://api.example.com",
      endpoint: "/api/questionset/v2/hierarchy",
    },
    telemetryConfig,
  };

  return (
    <QumlPlayer
      questionSetId="analytics_assessment"
      config={config}
      onPlayerStateChange={handlePlayerStateChange}
      onComplete={(results) => {
        handleCustomAnalytics("assessment_completed", results);
      }}
    />
  );
}
```

## Framework-Specific Examples

### 6. Next.js with SSR

```tsx
// pages/assessment/[...params].tsx
import { GetServerSideProps } from "next";
import { QumlPlayer, QumlConfig } from "@tekdi/react-quml-player";
import { getAssessmentConfig, validateUserAccess } from "../../lib/assessment";

interface Props {
  questionSetId: string;
  config: QumlConfig;
  userHasAccess: boolean;
}

export default function DynamicAssessment({
  questionSetId,
  config,
  userHasAccess,
}: Props) {
  if (!userHasAccess) {
    return (
      <div className="access-denied">
        <h1>Access Denied</h1>
        <p>You don't have permission to access this assessment.</p>
      </div>
    );
  }

  return (
    <div className="assessment-page">
      <QumlPlayer
        questionSetId={questionSetId}
        config={config}
        onComplete={(results) => {
          // Handle completion in Next.js
          window.location.href = `/results?score=${results.score}`;
        }}
      />
    </div>
  );
}

export const getServerSideProps: GetServerSideProps = async ({
  params,
  req,
}) => {
  const questionSetId = params?.params?.[0] as string;
  const userId = req.headers["x-user-id"] as string;

  try {
    const [config, userHasAccess] = await Promise.all([
      getAssessmentConfig(questionSetId),
      validateUserAccess(userId, questionSetId),
    ]);

    return {
      props: {
        questionSetId,
        config,
        userHasAccess,
      },
    };
  } catch (error) {
    return {
      notFound: true,
    };
  }
};
```

### 7. React Router with Protected Routes

```tsx
import React from "react";
import {
  Routes,
  Route,
  Navigate,
  useParams,
  useLocation,
} from "react-router-dom";
import { QumlPlayer } from "@tekdi/react-quml-player";
import { useAuth } from "../hooks/useAuth";
import { useAssessment } from "../hooks/useAssessment";

function ProtectedAssessmentRoute() {
  const { assessmentId } = useParams();
  const { user, isAuthenticated } = useAuth();
  const location = useLocation();

  if (!isAuthenticated) {
    return <Navigate to="/login" state={{ from: location }} replace />;
  }

  return <AssessmentPlayer assessmentId={assessmentId!} user={user} />;
}

function AssessmentPlayer({ assessmentId, user }: any) {
  const { assessment, config, loading, error } = useAssessment(assessmentId);

  if (loading) return <div>Loading assessment...</div>;
  if (error) return <div>Error: {error.message}</div>;

  return (
    <div className="protected-assessment">
      <header>
        <h1>{assessment.title}</h1>
        <p>Welcome, {user.name}</p>
      </header>

      <QumlPlayer
        questionSetId={assessment.questionSetId}
        config={{
          ...config,
          telemetryConfig: {
            ...config.telemetryConfig,
            uid: user.id,
          },
        }}
        onComplete={(results) => {
          // Handle completion with user context
          console.log(`${user.name} completed assessment:`, results);
        }}
      />
    </div>
  );
}

// App routing setup
function App() {
  return (
    <Routes>
      <Route
        path="/assessment/:assessmentId"
        element={<ProtectedAssessmentRoute />}
      />
      <Route path="/login" element={<LoginPage />} />
      <Route path="/" element={<Dashboard />} />
    </Routes>
  );
}
```

## Customization Examples

### 8. Custom Question Renderer

```tsx
import React from "react";
import { QumlPlayer } from "@tekdi/react-quml-player";

// Custom question renderer for interactive elements
function CustomInteractiveQuestion({ question, onResponse }: any) {
  const [selectedOption, setSelectedOption] = useState(null);

  const handleSubmit = () => {
    if (selectedOption) {
      onResponse({
        questionId: question.identifier,
        values: [selectedOption],
        score: calculateScore(selectedOption, question.correctAnswers),
        timeSpent: getTimeSpent(),
      });
    }
  };

  return (
    <div className="custom-question-container">
      <h3 className="question-title">{question.body}</h3>

      <div className="interactive-options">
        {question.options.map((option: any) => (
          <div
            key={option.identifier}
            className={`option-card ${
              selectedOption === option.value ? "selected" : ""
            }`}
            onClick={() => setSelectedOption(option.value)}
          >
            <div className="option-content">
              {option.media && (
                <img src={option.media[0].src} alt="Option visual" />
              )}
              <p>{option.text}</p>
            </div>
          </div>
        ))}
      </div>

      <button
        onClick={handleSubmit}
        disabled={!selectedOption}
        className="submit-button"
      >
        Submit Answer
      </button>
    </div>
  );
}

function CustomizedAssessment() {
  const customConfig = {
    // ... standard config
    questionSetConfig: {
      showTimer: true,
      showProgress: true,
      customRenderers: {
        INTERACTIVE: CustomInteractiveQuestion,
      },
    },
  };

  return (
    <QumlPlayer
      questionSetId="custom_interactive_assessment"
      config={customConfig}
    />
  );
}
```

### 9. Themed Assessment Platform

```tsx
import React, { createContext, useContext } from "react";
import { QumlPlayer } from "@tekdi/react-quml-player";

const ThemeContext = createContext("light");

const themes = {
  light: {
    background: "#ffffff",
    foreground: "#000000",
    primary: "#3b82f6",
    secondary: "#64748b",
  },
  dark: {
    background: "#0f172a",
    foreground: "#f8fafc",
    primary: "#60a5fa",
    secondary: "#94a3b8",
  },
  brand: {
    background: "#fef7ff",
    foreground: "#1e1b4b",
    primary: "#7c3aed",
    secondary: "#a855f7",
  },
};

function ThemedAssessment() {
  const theme = useContext(ThemeContext);
  const themeConfig = themes[theme] || themes.light;

  return (
    <div
      className="themed-assessment"
      style={
        {
          "--bg-color": themeConfig.background,
          "--text-color": themeConfig.foreground,
          "--primary-color": themeConfig.primary,
          "--secondary-color": themeConfig.secondary,
        } as React.CSSProperties
      }
    >
      <QumlPlayer
        questionSetId="themed_assessment"
        config={config}
        className="themed-player"
      />
    </div>
  );
}

function ThemeSelector() {
  const [currentTheme, setCurrentTheme] = useState("light");

  return (
    <ThemeContext.Provider value={currentTheme}>
      <div className="theme-controls">
        {Object.keys(themes).map((themeName) => (
          <button
            key={themeName}
            onClick={() => setCurrentTheme(themeName)}
            className={currentTheme === themeName ? "active" : ""}
          >
            {themeName.charAt(0).toUpperCase() + themeName.slice(1)}
          </button>
        ))}
      </div>
      <ThemedAssessment />
    </ThemeContext.Provider>
  );
}
```

## Real-World Use Cases

### 10. Corporate Training Platform

```tsx
import React, { useState, useEffect } from "react";
import { QumlPlayer } from "@tekdi/react-quml-player";
import { CorporateAPI } from "../services/corporate-api";

interface TrainingModule {
  id: string;
  title: string;
  description: string;
  questionSetId: string;
  requiredScore: number;
  attempts: number;
  maxAttempts: number;
}

function CorporateTrainingAssessment() {
  const [module, setModule] = useState<TrainingModule | null>(null);
  const [employeeData, setEmployeeData] = useState<any>(null);

  useEffect(() => {
    loadTrainingModule();
    loadEmployeeData();
  }, []);

  const loadTrainingModule = async () => {
    const moduleData = await CorporateAPI.getTrainingModule("safety-101");
    setModule(moduleData);
  };

  const loadEmployeeData = async () => {
    const employee = await CorporateAPI.getCurrentEmployee();
    setEmployeeData(employee);
  };

  const handleAssessmentComplete = async (results: any) => {
    const passed =
      results.score >= (module!.requiredScore * results.maxScore) / 100;

    try {
      await CorporateAPI.recordTrainingCompletion({
        employeeId: employeeData.id,
        moduleId: module!.id,
        score: results.score,
        maxScore: results.maxScore,
        passed,
        completionTime: new Date().toISOString(),
      });

      if (passed) {
        showSuccessModal(
          "Congratulations! You have successfully completed the training."
        );
      } else {
        const attemptsLeft = module!.maxAttempts - module!.attempts - 1;
        if (attemptsLeft > 0) {
          showRetryModal(
            `You need ${
              module!.requiredScore
            }% to pass. You have ${attemptsLeft} attempts left.`
          );
        } else {
          showFailureModal(
            "Training not completed. Please contact your supervisor."
          );
        }
      }
    } catch (error) {
      console.error("Failed to record completion:", error);
    }
  };

  if (!module || !employeeData) return <div>Loading...</div>;

  const config = {
    apiConfig: {
      host: process.env.REACT_APP_CORPORATE_API,
      endpoint: "/training/questionset/v1/hierarchy",
      headers: {
        Authorization: `Bearer ${employeeData.token}`,
        "X-Employee-Id": employeeData.id,
        "X-Department": employeeData.department,
      },
    },
    telemetryConfig: {
      pdata: { id: "corporate-training", ver: "1.0.0", pid: "training" },
      env: "production",
      channel: "corporate-learning",
      uid: employeeData.id,
      tags: ["training", "safety", "corporate"],
    },
    questionSetConfig: {
      showTimer: true,
      showProgress: true,
    },
  };

  return (
    <div className="corporate-training">
      <header className="training-header">
        <h1>{module.title}</h1>
        <div className="employee-info">
          <p>Employee: {employeeData.name}</p>
          <p>Department: {employeeData.department}</p>
          <p>
            Attempt: {module.attempts + 1} of {module.maxAttempts}
          </p>
        </div>
      </header>

      <div className="requirements">
        <p>Required Score: {module.requiredScore}%</p>
        <p>
          This assessment must be completed as part of your training
          requirements.
        </p>
      </div>

      <QumlPlayer
        questionSetId={module.questionSetId}
        config={config}
        onComplete={handleAssessmentComplete}
        className="corporate-player"
      />
    </div>
  );
}
```

### 11. Educational Institution System

```tsx
import React, { useState, useEffect } from "react";
import { QumlPlayer } from "@tekdi/react-quml-player";
import { AcademicAPI } from "../services/academic-api";

interface StudentData {
  id: string;
  name: string;
  grade: string;
  section: string;
  rollNumber: string;
}

interface ExamData {
  id: string;
  subject: string;
  chapter: string;
  duration: number;
  questionSetId: string;
  startTime: string;
  endTime: string;
}

function StudentExamPortal() {
  const [student, setStudent] = useState<StudentData | null>(null);
  const [exam, setExam] = useState<ExamData | null>(null);
  const [examStarted, setExamStarted] = useState(false);

  useEffect(() => {
    loadStudentData();
    loadCurrentExam();
  }, []);

  const loadStudentData = async () => {
    const studentData = await AcademicAPI.getCurrentStudent();
    setStudent(studentData);
  };

  const loadCurrentExam = async () => {
    const currentExam = await AcademicAPI.getCurrentExam();
    setExam(currentExam);
  };

  const startExam = () => {
    setExamStarted(true);
    AcademicAPI.recordExamStart(exam!.id, student!.id);
  };

  const handleExamComplete = async (results: any) => {
    try {
      await AcademicAPI.submitExamResults({
        studentId: student!.id,
        examId: exam!.id,
        answers: results.responses,
        score: results.score,
        maxScore: results.maxScore,
        timeSpent: results.duration,
        submittedAt: new Date().toISOString(),
      });

      // Redirect to results page
      window.location.href = "/exam-results";
    } catch (error) {
      alert("Failed to submit exam. Please contact your teacher.");
    }
  };

  if (!student || !exam) return <div>Loading...</div>;

  if (!examStarted) {
    return (
      <div className="exam-instructions">
        <h1>Exam Instructions</h1>
        <div className="exam-details">
          <p>
            <strong>Subject:</strong> {exam.subject}
          </p>
          <p>
            <strong>Chapter:</strong> {exam.chapter}
          </p>
          <p>
            <strong>Duration:</strong> {exam.duration} minutes
          </p>
          <p>
            <strong>Student:</strong> {student.name} (Roll: {student.rollNumber}
            )
          </p>
        </div>

        <div className="instructions">
          <ul>
            <li>Read all questions carefully before answering</li>
            <li>You cannot go back once you submit an answer</li>
            <li>Make sure you have stable internet connection</li>
            <li>Do not refresh the page during the exam</li>
          </ul>
        </div>

        <button onClick={startExam} className="start-exam-btn">
          Start Exam
        </button>
      </div>
    );
  }

  const config = {
    apiConfig: {
      host: process.env.REACT_APP_SCHOOL_API,
      endpoint: "/academic/questionset/v1/hierarchy",
      headers: {
        Authorization: `Bearer ${student.token}`,
        "X-Student-Id": student.id,
        "X-Exam-Id": exam.id,
      },
    },
    telemetryConfig: {
      pdata: { id: "school-system", ver: "1.0.0", pid: "examination" },
      env: "production",
      channel: "school-exams",
      uid: student.id,
      tags: ["exam", "academic", student.grade],
    },
    questionSetConfig: {
      showTimer: true,
      showProgress: true,
      autoSubmit: true, // Auto-submit when time expires
    },
  };

  return (
    <div className="exam-portal">
      <header className="exam-header">
        <h2>
          {exam.subject} - {exam.chapter}
        </h2>
        <div className="student-info">
          {student.name} | Grade {student.grade} | Section {student.section}
        </div>
      </header>

      <QumlPlayer
        questionSetId={exam.questionSetId}
        config={config}
        onComplete={handleExamComplete}
        className="exam-player"
      />
    </div>
  );
}
```

## Section-Level Skip Configuration

### Example: Mixed Skip Policy Assessment

This example demonstrates how to configure different skip policies for different sections within the same assessment.

```typescript
import React from "react";
import { QumlPlayer } from "react-quml-spark";

function MixedSkipPolicyAssessment() {
  const config = {
    apiConfig: {
      host: "https://your-api-host.com",
      endpoint: "/api/v1",
    },
    telemetryConfig: {
      pdata: { id: "mixed-assessment", ver: "1.0.0", pid: "assessment" },
      env: "production",
      channel: "education",
      uid: "student-123",
    },
  };

  // Question set with different skip policies per section
  const questionSetData = {
    identifier: "mixed-skip-assessment",
    name: "Assessment with Mixed Skip Policy",
    children: [
      {
        identifier: "practice-section",
        name: "Practice Section",
        allowSkip: true, // Allow skipping in practice
        children: [
          // Practice questions here
        ],
      },
      {
        identifier: "graded-section",
        name: "Graded Section",
        allowSkip: false, // No skipping in graded section
        children: [
          // Graded questions here
        ],
      },
      {
        identifier: "bonus-section",
        name: "Bonus Section",
        allowSkip: true, // Allow skipping bonus questions
        children: [
          // Bonus questions here
        ],
      },
    ],
  };

  const handleComplete = (results) => {
    console.log("Assessment completed:", results);
  };

  return (
    <div className="mixed-skip-assessment">
      <QumlPlayer
        config={{
          ...config,
          metadata: questionSetData,
        }}
        onComplete={handleComplete}
      />
    </div>
  );
}

export default MixedSkipPolicyAssessment;
```

These examples demonstrate various real-world scenarios and implementation patterns for the React QUML Player. Each example can be adapted to fit specific requirements and use cases.
