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
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
import { useState, useEffect } from "react";
import { db, auth } from "../firebase";
import { TEXT_COMPLETION_URL } from "../config";
import {
  doc,
  setDoc
} from "firebase/firestore";

function TrialTaskText({ trialIndex, totalTrials, trialId, onNext, onExitEarly, sessionId, participantNumber }) {
  const [trialData, setTrialData] = useState(null);
  const [order, setOrder] = useState([1, 2]);
  const [ratings, setRatings] = useState({ r1: null, r2: null });
  const [overallPreference, setOverallPreference] = useState(null); // 'A', 'Tie', or 'B'
  const [overallPreferenceChanges, setOverallPreferenceChanges] = useState([]);
  const [startTime, setStartTime] = useState(null);
  const [timestamps, setTimestamps] = useState({ r1: null, r2: null });
  const [ratingChanges, setRatingChanges] = useState({ r1: [], r2: [] });
  const [justification, setJustification] = useState("");
  const [isSubmitting, setIsSubmitting] = useState(false);
  const isAttentionCheck = trialIndex === 0;

  useEffect(() => {
    // Scroll to top when new trial loads
    window.scrollTo(0, 0);

    const loadTrial = async () => {
      try {
        // If this is the first trial, use it as an attention check
        if (isAttentionCheck) {
          const attentionCheckData = {
            id: "attention_check",
            query: "Hello AI! I need some help writing a text message",
            text_resp_1: "Of course! Who is the recipient and what would you like to convey in the message?",
            text_resp_2: "that doesn't sound like a bot. Here's a sample I tried:\n\nSup, it's [Name]. How are you? This is [name] speaking. I am calling to inquire about [insert product or service here]\n\nWhere am I going wrong?",
            prev_hist: "",
            conv_id: "attention",
            turn_no: "0",
            synth_text_1_rating: 85,
            synth_text_2_rating: 15,
            text_1_score: null,
            text_2_score: null
          };
          setTrialData(attentionCheckData);
        } else {
          // Load survey data from JSON
          const response = await fetch('/survey_data.json');
          const allSamples = await response.json();
          
          // Find the trial by ID
          const trial = allSamples.find(sample => sample.id.toString() === trialId.toString());
          
          if (trial) {
            setTrialData(trial);
          }
        }

        // Deterministic order assignment (ensures 5x5 split per modality)
        // Every 2 participants get the same order, alternating between [1,2] and [2,1]
        const orderFlip = Math.floor(participantNumber / 2) % 2;
        setOrder(orderFlip === 0 ? [1, 2] : [2, 1]);

        // Reset ratings and timestamps for new trial
        setRatings({ r1: null, r2: null });
        setTimestamps({ r1: null, r2: null });
        setRatingChanges({ r1: [], r2: [] });
        setOverallPreference(null);
        setOverallPreferenceChanges([]);
        setJustification("");
        setIsSubmitting(false);

        // Set start time
        setStartTime(Date.now());
      } catch (error) {
        console.error("Failed to load trial data:", error);
      }
    };

    loadTrial();
  }, [trialId, isAttentionCheck, participantNumber]);

  const handleSliderChange = (responseNum, value) => {
    setRatings((prev) => ({ ...prev, [`r${responseNum}`]: value }));
  };

  const handleSliderRelease = (responseNum, value) => {
    setTimestamps((prev) => ({
      ...prev,
      [`r${responseNum}`]: Date.now()
    }));

    // Determine the other rating's value
    const otherResponseNum = responseNum === 1 ? 2 : 1;
    const otherRatingValue = ratings[`r${otherResponseNum}`];

    setRatingChanges((prev) => ({
      ...prev,
      [`r${responseNum}`]: [
        ...prev[`r${responseNum}`],
        {
          value,
          timestamp: new Date().toISOString(),
          otherRatingValue
        }
      ]
    }));
  };

  const calculatePreferenceChanges = () => {
    // Build a timeline of all rating changes
    const timeline = [];

    ratingChanges.r1.forEach(change => {
      timeline.push({
        timestamp: change.timestamp,
        r1: change.value,
        r2: change.otherRatingValue
      });
    });

    ratingChanges.r2.forEach(change => {
      timeline.push({
        timestamp: change.timestamp,
        r1: change.otherRatingValue,
        r2: change.value
      });
    });

    // Sort by timestamp
    timeline.sort((a, b) => new Date(a.timestamp) - new Date(b.timestamp));

    // Count preference changes
    let preferenceChanges = 0;
    let lastPreference = null; // 'r1', 'r2', or 'tie'

    timeline.forEach(entry => {
      if (entry.r1 !== null && entry.r2 !== null) {
        let currentPreference;
        if (entry.r1 > entry.r2) {
          currentPreference = 'r1';
        } else if (entry.r2 > entry.r1) {
          currentPreference = 'r2';
        } else {
          currentPreference = 'tie';
        }

        if (lastPreference !== null && lastPreference !== currentPreference) {
          preferenceChanges++;
        }

        lastPreference = currentPreference;
      }
    });

    return preferenceChanges;
  };

  const handleOverallPreferenceChange = (newPreference) => {
    setOverallPreference(newPreference);
    setOverallPreferenceChanges((prev) => [
      ...prev,
      {
        value: newPreference,
        timestamp: new Date().toISOString(),
        previousValue: overallPreference
      }
    ]);
  };

  const handleSubmit = async (e) => {
    e.preventDefault();

    // Prevent double submission
    if (isSubmitting) return;
    if (ratings.r1 === null || ratings.r2 === null || overallPreference === null) return;

    setIsSubmitting(true);
    const endTime = Date.now();
    const totalPreferenceChanges = calculatePreferenceChanges();

    // Determine which response was shown first based on order
    const response1InOrder = order[0] === 1 ? trialData.text_resp_1 : trialData.text_resp_2;
    const response2InOrder = order[1] === 1 ? trialData.text_resp_1 : trialData.text_resp_2;

    const responseData = {
      // Participant and Trial Info
      participantId: auth.currentUser.uid,
      promptId: `${trialData.conv_id}_${trialData.turn_no}`,
      trialNumber: trialIndex, // Now 0 for attention check, 1-20 for real trials
      trialId: isAttentionCheck ? "attention_check" : trialId,
      
      // Content
      conversationHistory: trialData.prev_hist || "",
      query: trialData.query,
      responseText1: response1InOrder,
      responseText2: response2InOrder,
      numCharacters1: response1InOrder.length,
      numCharacters2: response2InOrder.length,
      
      // AI Ratings (original order)
      aiRatingResponse1: trialData.synth_text_1_rating,
      aiRatingResponse2: trialData.synth_text_2_rating,
      prismRating1: trialData.text_1_score || null,
      prismRating2: trialData.text_2_score || null,
      
      // Participant Ratings
      participantRatingNum: trialIndex + 1,
      ratingResponse1: ratings.r1,
      ratingResponse2: ratings.r2,
      
      // Timing
      taskStartTime: new Date(startTime).toISOString(),
      taskEndTime: new Date(endTime).toISOString(),
      timestampRating1: timestamps.r1 ? new Date(timestamps.r1).toISOString() : null,
      timestampRating2: timestamps.r2 ? new Date(timestamps.r2).toISOString() : null,
      totalTaskDurationMs: endTime - startTime,
      
      // Order Info
      orderPresented: order,
      responseShownFirst: order[0],
      originalResponse1ShownAs: order[0] === 1 ? "A" : "B",
      originalResponse2ShownAs: order[0] === 2 ? "A" : "B",
      
      // Metadata
      modality: "text",
      submittedAt: new Date().toISOString(),
      isAttentionCheck: isAttentionCheck,

      ratingChangeHistory1: ratingChanges.r1,
      ratingChangeHistory2: ratingChanges.r2,

      // Preference Changes
      totalPreferenceChanges: totalPreferenceChanges,

      // Overall Preference
      overallPreference: overallPreference,
      overallPreferenceChangeHistory: overallPreferenceChanges,

      // Justification
      preferenceJustification: justification.trim() || null,
    };

    const responseDocId = isAttentionCheck 
      ? `${auth.currentUser.uid}_${sessionId}_text_attention_check`
      : `${auth.currentUser.uid}_${sessionId}_text_${trialId}`;
    console.log(auth.currentUser?.uid, responseDocId);
    await setDoc(doc(db, "responses", responseDocId), responseData);

    onNext(); // move to next trial
  };

  if (!trialData) return <p>Loading trial...</p>;

  const [first, second] = order;

  return (
    <form onSubmit={handleSubmit} style={{ maxWidth: '1200px', margin: '0 auto', padding: '20px' }}>
      <h3>Trial {trialIndex} of {totalTrials - 1}</h3>

      {trialData.prev_hist && trialData.prev_hist.trim() && (
        <div style={{ marginBottom: '30px', padding: '15px', backgroundColor: '#f5f5f5', borderRadius: '8px' }}>
          <p style={{ margin: '0 0 15px 0', fontSize: '16px' }}><strong>Conversation History:</strong></p>
          <div style={{ backgroundColor: '#fff', padding: '15px', borderRadius: '5px', border: '1px solid #ddd' }}>
            {(() => {
              const parts = trialData.prev_hist.split(/role: (user|model)\\n response: /).filter(part => part.trim());
              const messages = [];
              
              for (let i = 0; i < parts.length; i += 2) {
                const role = parts[i];
                const content = parts[i + 1];
                if (role && content) {
                  messages.push({ role, content });
                }
              }
              
              return messages.map((message, index) => (
                <div key={index} style={{ 
                  margin: '15px 0', 
                  padding: '10px', 
                  borderRadius: '5px',
                  backgroundColor: message.role === 'user' ? '#f0f9ff' : '#fef2f2',
                  border: message.role === 'user' ? '1px solid #bfdbfe' : '1px solid #fecaca'
                }}>
                  <div style={{ 
                    fontWeight: 'bold', 
                    color: message.role === 'user' ? '#1e40af' : '#dc2626',
                    marginBottom: '5px'
                  }}>
                    {message.role === 'user' ? 'User' : 'Assistant'}:
                  </div>
                  <div style={{ whiteSpace: 'pre-wrap', lineHeight: '1.5' }}>
                    {message.content}
                  </div>
                </div>
              ));
            })()}
          </div>
        </div>
      )}
      
      <div style={{ marginBottom: '30px', padding: '15px', backgroundColor: '#f0f9ff', borderRadius: '8px', border: '1px solid #bfdbfe' }}>
        <p style={{ margin: '0', fontSize: '16px' }}>
          <strong style={{ color: '#1e40af' }}>User:</strong> <span style={{ color: '#000000' }}>{trialData.query}</span>
        </p>
      </div>
      
      <div style={{ display: 'flex', marginBottom: '30px', gap: '20px' }}>
        <div style={{ flex: '1', padding: '20px', border: '1px solid #ddd', borderRadius: '8px' }}>
          <h4>Response A</h4>
          <p style={{ whiteSpace: 'pre-wrap' }}>{first === 1 ? trialData.text_resp_1 : trialData.text_resp_2}</p>
        </div>
        <div style={{ width: '300px', padding: '20px', display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
          <label style={{ marginBottom: '10px' }}>Response Rating:</label>
          <input
            type="range"
            min="1"
            max="100"
            value={ratings.r1 ?? 50}
            onChange={(e) => handleSliderChange(1, parseInt(e.target.value))}
            onMouseUp={(e) => handleSliderRelease(1, parseInt(e.target.value))}
            onTouchEnd={(e) => handleSliderRelease(1, parseInt(e.target.value))}
            style={{ width: '100%', height: '30px', marginBottom: '5px' }}
          />
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '12px', color: '#666' }}>
            <span>Terrible</span>
            <span>Perfect</span>
          </div>
        </div>
      </div>

      <div style={{ display: 'flex', marginBottom: '30px', gap: '20px' }}>
        <div style={{ flex: '1', padding: '20px', border: '1px solid #ddd', borderRadius: '8px' }}>
          <h4>Response B</h4>
          <p style={{ whiteSpace: 'pre-wrap' }}>{second === 1 ? trialData.text_resp_1 : trialData.text_resp_2}</p>
        </div>
        <div style={{ width: '300px', padding: '20px', display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
          <label style={{ marginBottom: '10px' }}>Response Rating:</label>
          <input
            type="range"
            min="1"
            max="100"
            value={ratings.r2 ?? 50}
            onChange={(e) => handleSliderChange(2, parseInt(e.target.value))}
            onMouseUp={(e) => handleSliderRelease(2, parseInt(e.target.value))}
            onTouchEnd={(e) => handleSliderRelease(2, parseInt(e.target.value))}
            style={{ width: '100%', height: '30px', marginBottom: '5px' }}
          />
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '12px', color: '#666' }}>
            <span>Terrible</span>
            <span>Perfect</span>
          </div>
        </div>
      </div>

      <div style={{ marginBottom: '30px' }}>
        <label style={{ display: 'block', marginBottom: '10px', fontWeight: 'bold' }}>
          Overall, which response do you prefer?
        </label>
        <div style={{ display: 'flex', gap: '15px', justifyContent: 'center' }}>
          {['A', 'Tie', 'B'].map((option) => (
            <button
              key={option}
              type="button"
              onClick={() => handleOverallPreferenceChange(option)}
              style={{
                padding: '12px 30px',
                fontSize: '16px',
                backgroundColor: overallPreference === option ? '#007bff' : '#f0f0f0',
                color: overallPreference === option ? 'white' : '#333',
                border: overallPreference === option ? '2px solid #0056b3' : '2px solid #ddd',
                borderRadius: '5px',
                cursor: 'pointer',
                fontWeight: overallPreference === option ? 'bold' : 'normal',
                minWidth: '80px',
                transition: 'all 0.2s ease'
              }}
            >
              {option}
            </button>
          ))}
        </div>
      </div>

      <div style={{ marginBottom: '30px' }}>
        <label style={{ display: 'block', marginBottom: '10px', fontWeight: 'bold' }}>
          Why did you prefer one response over the other? (Optional)
        </label>
        <textarea
          value={justification}
          onChange={(e) => setJustification(e.target.value)}
          rows={4}
          style={{
            width: '100%',
            padding: '10px',
            fontSize: '14px',
            border: '1px solid #ddd',
            borderRadius: '5px',
            fontFamily: 'inherit',
            resize: 'vertical'
          }}
          placeholder="Please share your reasoning..."
        />
      </div>

      <div style={{ display: 'flex', gap: '15px', alignItems: 'center' }}>
        <button
          type="submit"
          disabled={isSubmitting || ratings.r1 === null || ratings.r2 === null || overallPreference === null}
          style={{
            padding: '10px 30px',
            fontSize: '16px',
            backgroundColor: !isSubmitting && ratings.r1 !== null && ratings.r2 !== null && overallPreference !== null ? '#007bff' : '#ccc',
            color: 'white',
            border: 'none',
            borderRadius: '5px',
            cursor: !isSubmitting && ratings.r1 !== null && ratings.r2 !== null && overallPreference !== null ? 'pointer' : 'not-allowed'
          }}
        >
          {isSubmitting ? 'Submitting...' : 'Submit Ratings'}
        </button>

        <button
          type="button"
          onClick={() => {
            if (window.confirm('Are you sure you want to exit the study early? Your progress will be saved but you will not complete the full study.')) {
              if (TEXT_COMPLETION_URL) window.location.href = TEXT_COMPLETION_URL;
              else if (typeof onExitEarly === 'function') onExitEarly();
            }
          }}
          style={{
            padding: '10px 20px',
            fontSize: '14px',
            backgroundColor: '#dc3545',
            color: 'white',
            border: 'none',
            borderRadius: '5px',
            cursor: 'pointer'
          }}
        >
          Exit Study Early
        </button>
      </div>
    </form>
  );
}

export default TrialTaskText;