File size: 4,117 Bytes
b136cbe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
import { useEffect, useState } from "react";
import { db, auth } from "../firebase";
import {
  doc,
  getDoc,
  setDoc,
  runTransaction
} from "firebase/firestore";

function AssignModalityAndTrials({ onComplete }) {
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

  useEffect(() => {
    const assign = async () => {
      const uid = auth.currentUser?.uid;
      if (!uid) return setError("No authenticated user.");

      const participantRef = doc(db, "participants", uid);
      const participantSnap = await getDoc(participantRef);

      // If already assigned, skip
      if (participantSnap.exists() && participantSnap.data().assignedTrialIds) {
        onComplete(participantSnap.data());
        return;
      }

      try {
        // 1. Load survey data from JSON
        const response = await fetch('/survey_data.json');
        const allSamples = await response.json();

        if (!allSamples || allSamples.length === 0) {
          return setError("No survey data available.");
        }

        // 2. BALANCED SAMPLING: Use global counter to ensure equal distribution
        const TRIALS_PER_PARTICIPANT = 20;
        const totalTrials = allSamples.length;
        const numBlocks = Math.ceil(totalTrials / TRIALS_PER_PARTICIPANT);

        // Get next participant number using transaction to avoid race conditions
        const counterRef = doc(db, "system", "participantCounter");
        const participantNumber = await runTransaction(db, async (transaction) => {
          const counterDoc = await transaction.get(counterRef);
          const currentCount = counterDoc.exists() ? (counterDoc.data().count || 0) : 0;
          const nextCount = currentCount + 1;
          transaction.set(counterRef, { count: nextCount, lastUpdated: new Date().toISOString() }, { merge: true });
          return currentCount;
        });

        // 3. Deterministically assign modality (ensures 50/50 split)
        // Even participant numbers get text, odd get audio
        const modality = participantNumber % 2 === 0 ? "text" : "audio";

        // Determine which block this participant gets (round-robin)
        const blockIndex = participantNumber % numBlocks;

        // Get the trials for this block
        const startIdx = blockIndex * TRIALS_PER_PARTICIPANT;
        const endIdx = Math.min(startIdx + TRIALS_PER_PARTICIPANT, totalTrials);
        let blockTrials = allSamples.slice(startIdx, endIdx);

        // If the last block has fewer than 20 trials, wrap around to fill it
        if (blockTrials.length < TRIALS_PER_PARTICIPANT) {
          const needed = TRIALS_PER_PARTICIPANT - blockTrials.length;
          blockTrials = [...blockTrials, ...allSamples.slice(0, needed)];
        }

        // Shuffle within the block to randomize order
        const shuffled = [...blockTrials];
        for (let i = shuffled.length - 1; i > 0; i--) {
          const j = Math.floor(Math.random() * (i + 1));
          [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
        }

        const trialIds = shuffled.map((sample) => sample.id.toString());

        // 4. Update participant document
        await setDoc(
          participantRef,
          {
            modality,
            assignedTrialIds: trialIds,
            participantNumber,
            blockIndex,
            assignedAt: new Date().toISOString()
          },
          { merge: true }
        );

        onComplete({ modality, assignedTrialIds: trialIds, participantNumber });
      } catch (err) {
        console.error("Failed to load survey data:", err);
        setError("Failed to load survey data. Please try again later.");
      }
    };

    assign().catch((err) => {
      console.error("Assignment failed:", err);
      setError("Something went wrong. Please try again later.");
    }).finally(() => setLoading(false));
  }, [onComplete]);

  if (loading) return <p>Assigning you to a group...</p>;
  if (error) return <p style={{ color: "red" }}>{error}</p>;

  return null; // Done → parent will move forward
}

export default AssignModalityAndTrials;