File size: 11,269 Bytes
00373d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e49fcf4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
// /$$$$$$  /$$$$$$ /$$    /$$ /$$$$$$$$       /$$      /$$ /$$$$$$$$        /$$$$$$           /$$$$$  /$$$$$$  /$$$$$$$ 
// /$$__  $$|_  $$_/| $$   | $$| $$_____/      | $$$    /$$$| $$_____/       /$$__  $$         |__  $$ /$$__  $$| $$__  $$
// | $$  \__/  | $$  | $$   | $$| $$            | $$$$  /$$$$| $$            | $$  \ $$            | $$| $$  \ $$| $$  \ $$
// | $$ /$$$$  | $$  |  $$ / $$/| $$$$$         | $$ $$/$$ $$| $$$$$         | $$$$$$$$            | $$| $$  | $$| $$$$$$$ 
// | $$|_  $$  | $$   \  $$ $$/ | $$__/         | $$  $$$| $$| $$__/         | $$__  $$       /$$  | $$| $$  | $$| $$__  $$
// | $$  \ $$  | $$    \  $$$/  | $$            | $$\  $ | $$| $$            | $$  | $$      | $$  | $$| $$  | $$| $$  \ $$
// |  $$$$$$/ /$$$$$$   \  $/   | $$$$$$$$      | $$ \/  | $$| $$$$$$$$      | $$  | $$      |  $$$$$$/|  $$$$$$/| $$$$$$$/
// \______/ |______/    \_/    |________/      |__/     |__/|________/      |__/  |__/       \______/  \______/ |_______/ 
//
// Hi, I'm Roland and i'm looking for a job.
// Resume in /public/resume.pdf
// [email protected]
// https://www.linkedin.com/in/roland-vrignon/
//


'use client';
import { FC, useState, useEffect, Dispatch, SetStateAction } from 'react';
import Image from 'next/image';

interface Message {
  content: string;
  role: 'lawyer' | 'judge';
}

interface Chat {
  messages: Message[];
}

interface DefenseSceneProps {
  language: 'fr' | 'en' | 'es';
  requiredWords: string[];
  setNextScene: () => void;
  setChat: (chat: SetStateAction<Chat>) => void;
  setCurrentQuestion: Dispatch<SetStateAction<string>>;
  setReaction: Dispatch<SetStateAction<string>>;
  setRequiredWords: Dispatch<SetStateAction<string[]>>;
}

const DefenseScene: FC<DefenseSceneProps> = ({
  language,
  requiredWords,
  setNextScene,
  setCurrentQuestion,
  setChat,
  setReaction,
  setRequiredWords
}) => {
  const [answer, setAnswer] = useState('');
  const [insertedWords, setInsertedWords] = useState<boolean[]>([]);
  const [countdown, setCountdown] = useState(60);
  const [isTimeUp, setIsTimeUp] = useState(false);
  const [wordPositions, setWordPositions] = useState<Array<{ word: string; position: number }>>([]);
  const [mandatoryWords, setMandatoryWords] = useState(requiredWords);
  const [isLoading, setIsLoading] = useState(true);
  const [ words ] = useState(requiredWords);

  // Initialisation des mots obligatoires
  useEffect(() => {
    if (requiredWords.length > 0) {
      setMandatoryWords(requiredWords);
    }
    setReaction('');
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [requiredWords]);

  // Génération des positions et initialisation
  useEffect(() => {
    if (mandatoryWords.length > 0) {
      const positions = generateWordPositions(mandatoryWords);
      setWordPositions(positions);
      setInsertedWords(new Array(mandatoryWords.length).fill(false));
      setCurrentQuestion("");
      setIsLoading(false);
    }
  }, [mandatoryWords]); // eslint-disable-line react-hooks/exhaustive-deps

    // Reset des required words après initialisation
  useEffect(() => {
    if (!isLoading && wordPositions.length > 0) {
      setRequiredWords([]);
    }
  }, [isLoading, wordPositions.length]); // eslint-disable-line react-hooks/exhaustive-deps

  useEffect(() => {
    if (isTimeUp) {
      handleSubmit();
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isTimeUp])    

  // Timer et reset de la question
  useEffect(() => {
    // Timer
    const timer = setInterval(() => {
      setCountdown((prev) => {
        if (prev === 0) {
          clearInterval(timer);
          setIsTimeUp(true);
        }
        return prev - 1;
      });
    }, 1000);

    return () => clearInterval(timer);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []); // On garde uniquement la dépendance answer car handleSubmit est stable

  // Génère un nombre aléatoire entre 9 et 15
  const generateRandomNumber = () => {
    return Math.floor(Math.random() * (15 - 9 + 1)) + 9;
  };

  // Génère les positions pour les mots requis
  const generateWordPositions = (words: string[]) => {
    let currentPosition = generateRandomNumber(); // On commence à une position aléatoire
    return words.map(word => {
      const position = currentPosition;
      currentPosition += generateRandomNumber(); // Ajoute un nombre aléatoire de mots pour le prochain mot requis
      return {
        word,
        position
      };
    });
  };

  // Fonction pour compter les mots
  const countWords = (text: string) => {
    // Remplacer temporairement les expressions requises par un seul mot
    let modifiedText = text;
    wordPositions.forEach(({ word }) => {
      if (modifiedText.includes(word)) {
        // Remplace l'expression complète par un placeholder unique
        modifiedText = modifiedText.replace(word, 'SINGLEWORD');
      }
    });

    // Maintenant compte les mots normalement
    return modifiedText.trim().split(/\s+/).length || 0;
  };

  // Fonction pour vérifier si on doit insérer un mot obligatoire
  const checkAndInsertRequiredWord = (text: string) => {
    const currentWordCount = countWords(text);
    let newText = text;
    const newInsertedWords = [...insertedWords];
    let wordInserted = false;

    wordPositions.forEach((word, index) => {
      if (!insertedWords[index] && currentWordCount === word.position && text.endsWith(' ')) {
        newText = `${text}${word.word} `;
        newInsertedWords[index] = true;
        wordInserted = true;
      }
    });

    if (wordInserted) {
      setInsertedWords(newInsertedWords);
    }

    return newText;
  };

  // Fonction pour vérifier si on peut supprimer du texte
  const canDeleteAt = (text: string, cursorPosition: number) => {
    // const textBeforeCursor = text.substring(0, cursorPosition);
    // const wordsBeforeCursor = countWords(textBeforeCursor);

    return !wordPositions.some((word, index) => {
      if (!insertedWords[index]) return false;

      const wordStartPosition = text.indexOf(word.word);
      const wordEndPosition = wordStartPosition + word.word.length;

      return cursorPosition > wordStartPosition && cursorPosition <= wordEndPosition;
    });
  };

  const handleTextChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    const newText = e.target.value;
    setAnswer(newText);
    const cursorPosition = e.target.selectionStart;

    // Si c'est une suppression
    if (newText.length < answer.length) {
      if (!canDeleteAt(answer, cursorPosition)) {
        return;
      }
    }

    // Insertion normale + vérification des mots obligatoires
    const processedText = checkAndInsertRequiredWord(newText);
    setAnswer(processedText);
  };

  const handleSubmit = () => {
    setChat(prevChat => ({
      messages: [...prevChat.messages, { content: answer, role: 'lawyer', requiredWords: words }]
    }));
    setNextScene();
  };

  const formatTime = (seconds: number) => {
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${mins}:${secs.toString().padStart(2, '0')}`;
  };

  // Vérifie si la réponse est valide pour soumission
  const isAnswerValid = () => {
    const lastWordPosition = Math.max(...wordPositions.map(word => word.position));
    const currentWordCount = countWords(answer);
    return currentWordCount >= lastWordPosition && insertedWords.every(inserted => inserted);
  };

  return (
    <div className="relative w-screen h-screen">
      {/* Image de fond */}
      <Image
        src="https://ik.imagekit.io/z0tzxea0wgx/MistralGameJam/DD_attorney2_gbcNJRrYM.png?updatedAt=1737835883087"
        alt="Background"
        fill
        className="object-cover"
        priority
      />

      {/* Contenu avec overlay noir */}
      <div className="absolute inset-0">
        {isLoading ? (
          <div className="flex items-center justify-center h-full">
            <div className="text-2xl text-gray-300">
              {language === 'fr' ? 'Chargement...' : language === 'en' ? 'Loading...' : 'Cargando...'}
            </div>
          </div>
        ) : (
          <div className="flex flex-col justify-end p-8 h-full">
            {/* Header avec le compte à rebours */}
            <div className="flex justify-between items-center mb-6">
              <div className={`text-8xl roboto-slab ${countdown < 10 ? 'text-red-500' : 'text-white'}`}>
                {formatTime(countdown)}
              </div>
            </div>

            {/* Prochain mot requis */}
            <div className="mb-6">
              {wordPositions.map((item, index) => {
                // Ne montrer que le premier mot non inséré
                if (insertedWords[index] || index > 0 && !insertedWords[index - 1]) return null;
                const remainingWords = item.position - countWords(answer);
                return (
                  <div key={index} className="bg-black/60 border border-black border-8 p-6 text-white">
                    <span className="text-5xl text-sky-500 roboto-slab mt-2">
                      {item.word.toUpperCase()}
                    </span>
                    <span className="text-5xl text-white roboto-slab mt-2">                      {language === 'fr'
                      ? `dans `
                      : language === 'en'
                        ? `in `
                        : `en `
                    }</span>
                    <span className="text-5xl text-red-500 roboto-slab mt-2">{remainingWords}</span>
                    <span className="text-5xl text-white roboto-slab mt-2">                      {language === 'fr'
                      ? ` mots`
                      : language === 'en'
                        ? ` words`
                        : ` palabras`
                    }</span>
                  </div>
                );
              }).filter(Boolean)[0]}
            </div>

            {/* Zone de texte avec bouton submit en position absolue */}
            <div className="relative w-full mb-6">
              <textarea
                value={answer}
                onChange={handleTextChange}
                disabled={isTimeUp}
                placeholder={language === 'fr'
                  ? "Écrivez votre défense ici..."
                  : language === 'en'
                    ? "Write your defense here..."
                    : "Write your defense here..."}
                className="w-full p-6 bg-black/60 border border-black border-8 text-white text-4xl rounded-none focus:outline-none roboto-slab h-[30vh]"
              />

              {/* Bouton de soumission */}
              <button
                onClick={() => handleSubmit()}
                disabled={!isAnswerValid()}
                className={`absolute bottom-5 right-5 px-8 py-4 rounded-lg text-xl transition-all duration-300 ${isAnswerValid()
                    ? 'bg-sky-500 hover:bg-blue-700 cursor-pointer'
                    : 'bg-gray-600 cursor-not-allowed'
                  }`}
              >
                {language === 'fr' ? 'Soumettre' : language === 'en' ? 'Submit' : 'Submit'}
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default DefenseScene;