-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.jsx
More file actions
750 lines (690 loc) · 33.2 KB
/
index.jsx
File metadata and controls
750 lines (690 loc) · 33.2 KB
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
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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
import { useState, useCallback, useRef, useEffect } from "react";
// ─── Crossword Layout Generator ───
function generateLayout(inputWords) {
const words = inputWords
.map((w) => ({ ...w, word: w.word.toUpperCase().replace(/[^A-Z]/g, "") }))
.filter((w) => w.word.length > 1 && w.word.length <= 18)
.sort((a, b) => b.word.length - a.word.length);
if (!words.length) return null;
const placed = [];
function canPlace(grid, word, row, col, dir) {
for (let i = 0; i < word.length; i++) {
const r = dir === "down" ? row + i : row;
const c = dir === "across" ? col + i : col;
const cell = grid[r]?.[c];
if (cell === undefined) return false;
if (cell !== "" && cell !== word[i]) return false;
if (cell === "") {
if (dir === "across") {
if (grid[r - 1]?.[c] !== undefined && grid[r - 1][c] !== "") return false;
if (grid[r + 1]?.[c] !== undefined && grid[r + 1][c] !== "") return false;
} else {
if (grid[r]?.[c - 1] !== undefined && grid[r][c - 1] !== "") return false;
if (grid[r]?.[c + 1] !== undefined && grid[r][c + 1] !== "") return false;
}
}
}
if (dir === "across") {
if (grid[row]?.[col - 1] !== undefined && grid[row][col - 1] !== "") return false;
if (grid[row]?.[col + word.length] !== undefined && grid[row][col + word.length] !== "") return false;
} else {
if (grid[row - 1]?.[col] !== undefined && grid[row - 1][col] !== "") return false;
if (grid[row + word.length]?.[col] !== undefined && grid[row + word.length][col] !== "") return false;
}
return true;
}
function placeWord(grid, word, row, col, dir) {
for (let i = 0; i < word.length; i++) {
const r = dir === "down" ? row + i : row;
const c = dir === "across" ? col + i : col;
grid[r][c] = word[i];
}
}
const SIZE = 25;
const CENTER = 12;
const grid = Array.from({ length: SIZE }, () => Array(SIZE).fill(""));
const first = words[0];
const startCol = CENTER - Math.floor(first.word.length / 2);
placeWord(grid, first.word, CENTER, startCol, "across");
placed.push({ ...first, row: CENTER, col: startCol, dir: "across" });
for (let wi = 1; wi < words.length; wi++) {
const w = words[wi];
let bestScore = -1;
let bestPlacement = null;
for (const p of placed) {
for (let pi = 0; pi < p.word.length; pi++) {
for (let wi2 = 0; wi2 < w.word.length; wi2++) {
if (p.word[pi] !== w.word[wi2]) continue;
const dir = p.dir === "across" ? "down" : "across";
let row, col;
if (dir === "down") { row = p.row - wi2; col = p.col + pi; }
else { row = p.row + pi; col = p.col - wi2; }
if (row < 0 || col < 0 || row + (dir === "down" ? w.word.length : 1) > SIZE || col + (dir === "across" ? w.word.length : 1) > SIZE) continue;
if (canPlace(grid, w.word, row, col, dir)) {
const score = wi2;
if (score > bestScore) { bestScore = score; bestPlacement = { row, col, dir }; }
}
}
}
}
if (bestPlacement) {
placeWord(grid, w.word, bestPlacement.row, bestPlacement.col, bestPlacement.dir);
placed.push({ ...w, ...bestPlacement });
}
}
let minR = SIZE, maxR = 0, minC = SIZE, maxC = 0;
for (let r = 0; r < SIZE; r++)
for (let c = 0; c < SIZE; c++)
if (grid[r][c] !== "") {
minR = Math.min(minR, r); maxR = Math.max(maxR, r);
minC = Math.min(minC, c); maxC = Math.max(maxC, c);
}
const trimmed = grid.slice(minR, maxR + 1).map((row) => row.slice(minC, maxC + 1));
const adjusted = placed.map((p) => ({ ...p, row: p.row - minR, col: p.col - minC }));
const rows = trimmed.length;
const cols = trimmed[0]?.length || 0;
let num = 1;
const numbering = {};
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
if (trimmed[r][c] === "") continue;
const startsAcross = (c === 0 || trimmed[r][c - 1] === "") && trimmed[r][c + 1] !== undefined && trimmed[r][c + 1] !== "";
const startsDown = (r === 0 || trimmed[r - 1]?.[c] === "") && trimmed[r + 1]?.[c] !== undefined && trimmed[r + 1][c] !== "";
if (startsAcross || startsDown) numbering[`${r},${c}`] = num++;
}
}
const acrossClues = [];
const downClues = [];
for (const p of adjusted) {
const n = numbering[`${p.row},${p.col}`];
if (!n) continue;
if (p.dir === "across") acrossClues.push({ number: n, clue: p.clue, word: p.word, row: p.row, col: p.col, dir: "across" });
else downClues.push({ number: n, clue: p.clue, word: p.word, row: p.row, col: p.col, dir: "down" });
}
acrossClues.sort((a, b) => a.number - b.number);
downClues.sort((a, b) => a.number - b.number);
return { grid: trimmed, numbering, acrossClues, downClues, rows, cols };
}
// ─── Helper: find the word covering cell (r,c) in the given direction ───
function getWordAtCell(puzzle, r, c, dir) {
const clues = dir === "across" ? puzzle.acrossClues : puzzle.downClues;
return clues.find((cl) => {
if (dir === "across") return cl.row === r && c >= cl.col && c < cl.col + cl.word.length;
return cl.col === c && r >= cl.row && r < cl.row + cl.word.length;
}) || null;
}
// ─── CSV / JSON Parser ───
function parseInput(text, type) {
if (type === "json") {
const data = JSON.parse(text);
return Array.isArray(data) ? data : data.words || [];
}
return text.trim().split("\n").slice(1).map((line) => {
const idx = line.indexOf(",");
if (idx === -1) return null;
return { word: line.slice(0, idx).trim(), clue: line.slice(idx + 1).trim() };
}).filter(Boolean);
}
// ─── Export to IPUZ ───
function exportIpuz(puzzle, title = "Cruzadinha") {
const grid = puzzle.grid.map((row) => row.map((cell) => (cell === "" ? "#" : "0")));
for (const [key, num] of Object.entries(puzzle.numbering)) {
const [r, c] = key.split(",").map(Number);
grid[r][c] = String(num);
}
return JSON.stringify({
"ipuz": "http://ipuz.org/v1#1",
"version": "http://ipuz.org/v1",
"kind": ["http://ipuz.org/crossword#1"],
"title": title,
"dimensions": { "width": puzzle.cols, "height": puzzle.rows },
"puzzle": grid,
"clues": {
"Across": puzzle.acrossClues.map((c) => [c.number, c.clue]),
"Down": puzzle.downClues.map((c) => [c.number, c.clue]),
},
}, null, 2);
}
// ─── Sample data ───
const SAMPLE_JSON = `[
{"word":"BROKER","clue":"Intermediário que roteia mensagens entre producers e consumers"},
{"word":"TOPIC","clue":"Canal lógico para onde as mensagens são publicadas"},
{"word":"OFFSET","clue":"Posição de uma mensagem dentro de uma partition"},
{"word":"PARTITION","clue":"Subdivisão de um topic para paralelismo"},
{"word":"CONSUMER","clue":"Aplicação que lê mensagens de um topic"},
{"word":"PRODUCER","clue":"Aplicação que publica mensagens em um topic"},
{"word":"ZOOKEEPER","clue":"Serviço de coordenação usado pelo Kafka (legado)"},
{"word":"REPLICA","clue":"Cópia de uma partition para tolerância a falhas"},
{"word":"LEADER","clue":"Replica primária responsável por leitura e escrita"},
{"word":"LAG","clue":"Atraso de um consumer em relação ao producer"}
]`;
const SAMPLE_CSV = `word,clue
BROKER,Intermediário que roteia mensagens entre producers e consumers
TOPIC,Canal lógico para onde as mensagens são publicadas
OFFSET,Posição de uma mensagem dentro de uma partition
PARTITION,Subdivisão de um topic para paralelismo
CONSUMER,Aplicação que lê mensagens de um topic
PRODUCER,Aplicação que publica mensagens em um topic
REPLICA,Cópia de uma partition para tolerância a falhas
LEADER,Replica primária responsável por leitura e escrita
LAG,Atraso de um consumer em relação ao producer`;
// ─── Main App ───
export default function App() {
const [screen, setScreen] = useState("import");
const [inputText, setInputText] = useState("");
const [inputType, setInputType] = useState("json");
const [puzzle, setPuzzle] = useState(null);
const [title, setTitle] = useState("Kafka Fundamentals");
const [userGrid, setUserGrid] = useState({});
const [checked, setChecked] = useState(false);
const [revealed, setRevealed] = useState({});
const [allRevealed, setAllRevealed] = useState(false);
const [copied, setCopied] = useState(false);
const [selected, setSelected] = useState(null);
const [error, setError] = useState("");
const fileRef = useRef();
// ─── Persist progress in artifact storage ───
const STORAGE_KEY = "crossforge_progress";
useEffect(() => {
if (!puzzle) return;
const save = async () => {
try {
await window.storage.set(STORAGE_KEY, JSON.stringify({
title, userGrid, checked, revealed,
selected, inputText, inputType,
}));
} catch (_) {}
};
save();
}, [userGrid, revealed, checked, selected]);
useEffect(() => {
const load = async () => {
try {
const result = await window.storage.get(STORAGE_KEY);
if (!result?.value) return;
const saved = JSON.parse(result.value);
if (!saved.inputText) return;
setInputText(saved.inputText);
setInputType(saved.inputType || "json");
setTitle(saved.title || "");
// Re-generate the puzzle from saved input, then restore state
const words = parseInput(saved.inputText, saved.inputType || "json");
if (!words.length) return;
const p = generateLayout(words);
if (!p) return;
setPuzzle(p);
setUserGrid(saved.userGrid || {});
setChecked(saved.checked || false);
setRevealed(saved.revealed || {});
setSelected(saved.selected || null);
setScreen("play");
} catch (_) {}
};
load();
}, []);
// ─── Decode shared puzzle from URL ───
useEffect(() => {
const params = new URLSearchParams(location.search);
const p = params.get("p");
if (!p) return;
const decode = async () => {
try {
const b64 = p.replace(/-/g, "+").replace(/_/g, "/");
const bytes = Uint8Array.from(atob(b64), c => c.charCodeAt(0));
const stream = new DecompressionStream("gzip");
const writer = stream.writable.getWriter();
writer.write(bytes);
writer.close();
const text = await new Response(stream.readable).text();
const { title: t, words } = JSON.parse(text);
const json = JSON.stringify(words);
setTitle(t);
setInputText(json);
setInputType("json");
const p2 = generateLayout(words.map(w => ({ ...w, word: w.word.toUpperCase().replace(/[^A-Z]/g, "") })));
if (!p2) return;
setPuzzle(p2);
setScreen("play");
} catch (e) {
console.error("Failed to decode shared puzzle:", e);
}
};
decode();
}, []);
const generate = useCallback(() => {
setError("");
try {
const words = parseInput(inputText, inputType);
if (!words.length) throw new Error("Nenhuma palavra encontrada.");
const p = generateLayout(words);
if (!p) throw new Error("Não foi possível gerar o layout.");
setPuzzle(p);
setUserGrid({});
setChecked(false);
setRevealed({});
setAllRevealed(false);
setSelected(null);
setScreen("play");
} catch (e) {
setError(e.message);
}
}, [inputText, inputType]);
const handleFile = (e) => {
const file = e.target.files[0];
if (!file) return;
const ext = file.name.split(".").pop().toLowerCase();
setInputType(ext === "csv" ? "csv" : "json");
const reader = new FileReader();
reader.onload = (ev) => setInputText(ev.target.result);
reader.readAsText(file);
};
const handleCellInput = (r, c, val) => {
const letter = val.replace(/[^a-zA-Z]/g, "").slice(-1).toUpperCase();
setUserGrid((prev) => ({ ...prev, [`${r},${c}`]: letter }));
setChecked(false);
};
const handleCellClick = (r, c) => {
if (!puzzle) return;
if (selected && selected.row === r && selected.col === c) {
// Toggle direction only if both axes have a word here
const hasAcross = !!getWordAtCell(puzzle, r, c, "across");
const hasDown = !!getWordAtCell(puzzle, r, c, "down");
if (hasAcross && hasDown)
setSelected((s) => ({ ...s, dir: s.dir === "across" ? "down" : "across" }));
} else {
// Keep current direction if valid, else switch
const dir = selected?.dir || "across";
const valid = !!getWordAtCell(puzzle, r, c, dir);
const other = dir === "across" ? "down" : "across";
setSelected({ row: r, col: c, dir: valid ? dir : other });
}
};
const checkAnswers = () => setChecked(true);
const reveal = () => {
const rev = {};
for (let r = 0; r < puzzle.rows; r++)
for (let c = 0; c < puzzle.cols; c++)
if (puzzle.grid[r][c] !== "") rev[`${r},${c}`] = true;
setRevealed(rev);
setAllRevealed(true);
};
const revealRandomWord = () => {
if (!puzzle) return;
const allClues = [...puzzle.acrossClues, ...puzzle.downClues];
const unrevealed = allClues.filter((cl) => {
for (let i = 0; i < cl.word.length; i++) {
const r = cl.dir === "down" ? cl.row + i : cl.row;
const c = cl.dir === "across" ? cl.col + i : cl.col;
if (!revealed[`${r},${c}`]) return true;
}
return false;
});
if (!unrevealed.length) return;
const pick = unrevealed[Math.floor(Math.random() * unrevealed.length)];
const newRevealed = { ...revealed };
for (let i = 0; i < pick.word.length; i++) {
const r = pick.dir === "down" ? pick.row + i : pick.row;
const c = pick.dir === "across" ? pick.col + i : pick.col;
newRevealed[`${r},${c}`] = true;
}
setRevealed(newRevealed);
// Highlight the revealed word
setSelected({ row: pick.row, col: pick.col, dir: pick.dir });
};
const reset = () => { setUserGrid({}); setChecked(false); setRevealed({}); setAllRevealed(false); };
const downloadIpuz = () => {
const content = exportIpuz(puzzle, title);
const blob = new Blob([content], { type: "application/json" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url; a.download = `${title.replace(/\s+/g, "_")}.ipuz`; a.click();
URL.revokeObjectURL(url);
};
const downloadJson = () => {
const blob = new Blob([inputText], { type: "application/json" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url; a.download = `${title.replace(/\s+/g, "_")}_words.json`; a.click();
URL.revokeObjectURL(url);
};
const sharePuzzle = async () => {
try {
const payload = JSON.stringify({ title, words: JSON.parse(inputText) });
const stream = new CompressionStream("gzip");
const writer = stream.writable.getWriter();
writer.write(new TextEncoder().encode(payload));
writer.close();
const compressed = await new Response(stream.readable).arrayBuffer();
const bytes = new Uint8Array(compressed);
const b64 = btoa(String.fromCharCode(...bytes))
.replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
const url = `${location.origin}${location.pathname}?p=${b64}`;
await navigator.clipboard.writeText(url);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
} catch (e) {
console.error("Share failed:", e);
}
};
const getCellState = (r, c) => {
const key = `${r},${c}`;
const correct = puzzle.grid[r][c];
const user = userGrid[key] || "";
if (revealed[key]) return "revealed";
if (checked && user) return user === correct ? "correct" : "wrong";
return "empty";
};
// Highlight cells that belong to the same word as the selected cell
const isInSelectedWord = (r, c) => {
if (!selected || !puzzle) return false;
const activeWord = getWordAtCell(puzzle, selected.row, selected.col, selected.dir);
if (!activeWord) return false;
if (selected.dir === "across")
return r === activeWord.row && c >= activeWord.col && c < activeWord.col + activeWord.word.length;
return c === activeWord.col && r >= activeWord.row && r < activeWord.row + activeWord.word.length;
};
return (
<div style={styles.app}>
<header style={styles.header}>
<div style={styles.logo}>
<span style={styles.logoBox}>✦</span>
<span style={styles.logoText}>CROSSFORGE</span>
</div>
<p style={styles.tagline}>cruzadinhas temáticas · importe · jogue · exporte</p>
</header>
{screen === "import" ? (
<ImportScreen
inputText={inputText} setInputText={setInputText}
inputType={inputType} setInputType={setInputType}
title={title} setTitle={setTitle}
error={error} generate={generate}
fileRef={fileRef} handleFile={handleFile}
SAMPLE_JSON={SAMPLE_JSON} SAMPLE_CSV={SAMPLE_CSV}
/>
) : (
<PlayScreen
puzzle={puzzle} title={title}
userGrid={userGrid} handleCellInput={handleCellInput}
handleCellClick={handleCellClick}
selected={selected} setSelected={setSelected}
getCellState={getCellState} isInSelectedWord={isInSelectedWord}
checked={checked} checkAnswers={checkAnswers}
reveal={reveal} revealRandomWord={revealRandomWord} reset={reset}
allRevealed={allRevealed}
sharePuzzle={sharePuzzle} copied={copied}
downloadIpuz={downloadIpuz} downloadJson={downloadJson}
setScreen={setScreen}
/>
)}
</div>
);
}
// ─── IMPORT SCREEN ───
function ImportScreen({ inputText, setInputText, inputType, setInputType, title, setTitle, error, generate, fileRef, handleFile, SAMPLE_JSON, SAMPLE_CSV }) {
return (
<main style={styles.importMain}>
<div style={styles.importCard}>
<div style={styles.fieldGroup}>
<label style={styles.label}>Título da cruzadinha</label>
<input style={styles.input} value={title} onChange={e => setTitle(e.target.value)} placeholder="Ex: Kafka Fundamentals" />
</div>
<div style={styles.fieldGroup}>
<label style={styles.label}>Formato</label>
<div style={styles.toggle}>
{["json", "csv"].map(t => (
<button key={t}
style={{ ...styles.toggleBtn, ...(inputType === t ? styles.toggleActive : {}) }}
onClick={() => { setInputType(t); setInputText(""); }}>
{t.toUpperCase()}
</button>
))}
</div>
</div>
<div style={styles.fieldGroup}>
<div style={styles.labelRow}>
<label style={styles.label}>Conteúdo</label>
<div style={{ display: "flex", gap: 8 }}>
<button style={styles.miniBtn} onClick={() => setInputText(inputType === "json" ? SAMPLE_JSON : SAMPLE_CSV)}>exemplo Kafka</button>
<button style={styles.miniBtn} onClick={() => fileRef.current.click()}>importar arquivo</button>
<input ref={fileRef} type="file" accept=".json,.csv" style={{ display: "none" }} onChange={handleFile} />
</div>
</div>
<textarea
style={styles.textarea}
value={inputText}
onChange={e => setInputText(e.target.value)}
placeholder={inputType === "json"
? `[\n {"word": "KAFKA", "clue": "Plataforma de streaming distribuído"},\n ...\n]`
: `word,clue\nKAFKA,Plataforma de streaming distribuído\n...`}
spellCheck={false}
/>
</div>
{error && <p style={styles.error}>⚠ {error}</p>}
<button style={styles.generateBtn} onClick={generate}>GERAR CRUZADINHA →</button>
<div style={styles.formatHint}>
<p style={styles.hintTitle}>Formato esperado</p>
<div style={styles.hintGrid}>
<div>
<p style={styles.hintLabel}>JSON</p>
<pre style={styles.hintCode}>{`[{"word":"KAFKA","clue":"..."}]`}</pre>
</div>
<div>
<p style={styles.hintLabel}>CSV</p>
<pre style={styles.hintCode}>{`word,clue\nKAFKA,...`}</pre>
</div>
</div>
</div>
</div>
</main>
);
}
// ─── PLAY SCREEN ───
function PlayScreen({ puzzle, title, userGrid, handleCellInput, handleCellClick, selected, setSelected, getCellState, isInSelectedWord, checked, checkAnswers, reveal, revealRandomWord, reset, downloadIpuz, downloadJson, setScreen, allRevealed, sharePuzzle, copied }) {
const CELL = 36;
const inputRefs = useRef({});
const selectedRef = useRef(selected);
useEffect(() => { selectedRef.current = selected; }, [selected]);
const focusCell = (r, c) => {
if (r >= 0 && r < puzzle.rows && c >= 0 && c < puzzle.cols && puzzle.grid[r]?.[c] !== "")
inputRefs.current[`${r},${c}`]?.focus();
};
const handleKey = (e, r, c) => {
const dir = selectedRef.current?.dir || "across";
if (e.key === "ArrowRight") { e.preventDefault(); setSelected(s => ({ ...s, row: r, col: c + 1, dir: "across" })); focusCell(r, c + 1); }
if (e.key === "ArrowLeft") { e.preventDefault(); setSelected(s => ({ ...s, row: r, col: c - 1, dir: "across" })); focusCell(r, c - 1); }
if (e.key === "ArrowDown") { e.preventDefault(); setSelected(s => ({ ...s, row: r + 1, col: c, dir: "down" })); focusCell(r + 1, c); }
if (e.key === "ArrowUp") { e.preventDefault(); setSelected(s => ({ ...s, row: r - 1, col: c, dir: "down" })); focusCell(r - 1, c); }
if (e.key === "Enter") {
e.preventDefault();
advanceFromCell(r, c);
}
if (e.key === "Backspace" && !userGrid[`${r},${c}`]) {
e.preventDefault();
if (dir === "across") { setSelected(s => ({ ...s, col: c - 1 })); focusCell(r, c - 1); }
else { setSelected(s => ({ ...s, row: r - 1 })); focusCell(r - 1, c); }
}
};
const advanceFromCell = (r, c) => {
// Shared advance logic used by both handleInput and Enter key.
// Tries the current direction first, then the other (handles intersections).
const preferredDir = selectedRef.current?.dir || "across";
const tryDir = (d) => {
const word = getWordAtCell(puzzle, r, c, d);
if (!word) return false;
const nr = d === "down" ? r + 1 : r;
const nc = d === "across" ? c + 1 : c;
const next = getWordAtCell(puzzle, nr, nc, d);
if (!next || next.number !== word.number) return false;
setSelected(s => ({ ...s, row: nr, col: nc, dir: d }));
focusCell(nr, nc);
return true;
};
if (!tryDir(preferredDir)) tryDir(preferredDir === "across" ? "down" : "across");
};
const handleInput = (e, r, c) => {
const val = e.target.value;
// On mobile, onChange may fire even when value didn't change (key re-tap on filled cell).
// Always save and always try to advance so filled intersections don't get stuck.
handleCellInput(r, c, val);
if (!val) return;
advanceFromCell(r, c);
};
const totalCells = puzzle.grid.flat().filter(c => c !== "").length;
const filledCells = Object.keys(userGrid).filter(k => {
const [r, c] = k.split(",").map(Number);
return puzzle.grid[r]?.[c] !== "" && userGrid[k];
}).length;
const progress = Math.round((filledCells / totalCells) * 100);
const stateColors = {
empty: { bg: "#1a1a2e", border: "#4a4a6a", text: "#e0e0ff" },
correct: { bg: "#0d3d2e", border: "#2ecc71", text: "#2ecc71" },
wrong: { bg: "#3d0d0d", border: "#e74c3c", text: "#e74c3c" },
revealed: { bg: "#2d1a0e", border: "#f39c12", text: "#f39c12" },
};
return (
<main style={styles.playMain}>
<div style={styles.playHeader}>
<button style={styles.backBtn} onClick={() => setScreen("import")}>← voltar</button>
<h1 style={styles.playTitle}>{title}</h1>
<div style={styles.progressBar}>
<div style={{ ...styles.progressFill, width: `${progress}%` }} />
<span style={styles.progressText}>{progress}%</span>
</div>
</div>
<div style={styles.playLayout}>
{/* Grid */}
<div style={styles.gridWrapper}>
<div style={{ display: "grid", gridTemplateColumns: `repeat(${puzzle.cols}, ${CELL}px)`, gap: 2 }}>
{puzzle.grid.map((row, r) =>
row.map((cell, c) => {
if (cell === "") return <div key={`${r},${c}`} style={{ width: CELL, height: CELL }} />;
const state = getCellState(r, c);
const colors = stateColors[state];
const num = puzzle.numbering[`${r},${c}`];
const isSel = selected?.row === r && selected?.col === c;
const isHighlighted = isInSelectedWord(r, c);
const displayVal = state === "revealed" ? cell : (userGrid[`${r},${c}`] || "");
return (
<div key={`${r},${c}`} style={{ position: "relative", width: CELL, height: CELL }}>
{num && <span style={styles.cellNum}>{num}</span>}
<input
ref={el => inputRefs.current[`${r},${c}`] = el}
maxLength={1}
value={displayVal}
readOnly={allRevealed}
onChange={allRevealed ? undefined : e => handleInput(e, r, c)}
onClick={() => handleCellClick(r, c)}
onKeyDown={allRevealed ? undefined : e => handleKey(e, r, c)}
style={{
width: CELL, height: CELL,
background: isSel ? "#3a2060" : isHighlighted ? "#1e1040" : colors.bg,
border: `2px solid ${isSel ? "#9b59b6" : colors.border}`,
color: colors.text,
fontSize: 16, fontWeight: 700,
textAlign: "center", textTransform: "uppercase",
cursor: allRevealed ? "default" : "pointer",
outline: "none",
fontFamily: "'Courier New', monospace",
transition: "all 0.15s",
boxSizing: "border-box",
}}
/>
</div>
);
})
)}
</div>
</div>
{/* Clues */}
<div style={styles.cluesPanel}>
<ClueSection title="HORIZONTAL" clues={puzzle.acrossClues} selected={selected} dir="across"
setSelected={setSelected} focusCell={focusCell} puzzle={puzzle} />
<ClueSection title="VERTICAL" clues={puzzle.downClues} selected={selected} dir="down"
setSelected={setSelected} focusCell={focusCell} puzzle={puzzle} />
</div>
</div>
{/* Actions */}
<div style={styles.actions}>
<button style={styles.actionBtn} onClick={checkAnswers}>verificar</button>
<button style={{ ...styles.actionBtn, ...styles.shareBtn }} onClick={sharePuzzle}>{copied ? "✓ copiado!" : "↗ compartilhar"}</button>
<button style={{ ...styles.actionBtn, ...styles.revealWordBtn }} onClick={revealRandomWord}>✦ revelar palavra</button>
<button style={styles.actionBtn} onClick={reveal}>revelar tudo</button>
<button style={styles.actionBtn} onClick={reset}>limpar</button>
<button style={{ ...styles.actionBtn, ...styles.exportBtn }} onClick={downloadIpuz}>↓ .ipuz</button>
<button style={{ ...styles.actionBtn, ...styles.exportBtn }} onClick={downloadJson}>↓ .json</button>
</div>
</main>
);
}
// ─── CLUE SECTION ───
function ClueSection({ title, clues, selected, dir, setSelected, focusCell, puzzle }) {
return (
<div style={styles.clueSection}>
<h3 style={styles.clueTitle}>{title}</h3>
{clues.map(cl => {
// Active if the selected cell sits inside this clue's word span
const activeWord = selected ? getWordAtCell(puzzle, selected.row, selected.col, dir) : null;
const isSel = activeWord?.number === cl.number && activeWord?.dir === cl.dir;
return (
<div
key={cl.number}
style={{ ...styles.clueItem, ...(isSel ? styles.clueItemActive : {}) }}
onClick={() => { setSelected({ row: cl.row, col: cl.col, dir }); focusCell(cl.row, cl.col); }}
>
<span style={styles.clueNum}>{cl.number}</span>
<span style={styles.clueText}>{cl.clue}</span>
</div>
);
})}
</div>
);
}
// ─── STYLES ───
const styles = {
app: { minHeight: "100vh", background: "#0d0d1a", color: "#e0e0ff", fontFamily: "'Georgia', serif" },
header: { borderBottom: "1px solid #2a2a4a", padding: "20px 32px 16px", display: "flex", alignItems: "baseline", gap: 24 },
logo: { display: "flex", alignItems: "center", gap: 10 },
logoBox: { fontSize: 20, color: "#9b59b6" },
logoText: { fontSize: 22, fontWeight: 700, letterSpacing: 6, color: "#c39bd3", fontFamily: "'Courier New', monospace" },
tagline: { fontSize: 12, color: "#5a5a8a", letterSpacing: 2, margin: 0, fontFamily: "sans-serif" },
importMain: { maxWidth: 700, margin: "40px auto", padding: "0 20px" },
importCard: { display: "flex", flexDirection: "column", gap: 24 },
fieldGroup: { display: "flex", flexDirection: "column", gap: 8 },
label: { fontSize: 11, letterSpacing: 3, color: "#8a8aaa", textTransform: "uppercase", fontFamily: "sans-serif" },
labelRow: { display: "flex", justifyContent: "space-between", alignItems: "center" },
input: { background: "#12122a", border: "1px solid #2a2a4a", borderRadius: 4, color: "#e0e0ff", padding: "10px 14px", fontSize: 15, fontFamily: "'Georgia', serif", outline: "none" },
toggle: { display: "flex", borderRadius: 4, overflow: "hidden", border: "1px solid #2a2a4a", width: "fit-content" },
toggleBtn: { background: "#12122a", border: "none", color: "#8a8aaa", padding: "8px 20px", cursor: "pointer", fontSize: 12, letterSpacing: 2, fontFamily: "sans-serif" },
toggleActive: { background: "#2a1a4a", color: "#c39bd3" },
miniBtn: { background: "transparent", border: "1px solid #2a2a4a", borderRadius: 3, color: "#8a8aaa", padding: "4px 10px", cursor: "pointer", fontSize: 11, letterSpacing: 1, fontFamily: "sans-serif" },
textarea: { background: "#12122a", border: "1px solid #2a2a4a", borderRadius: 4, color: "#c0c0e0", padding: 14, fontSize: 12, fontFamily: "'Courier New', monospace", resize: "vertical", minHeight: 200, outline: "none", lineHeight: 1.6 },
error: { color: "#e74c3c", fontSize: 13, fontFamily: "sans-serif", margin: 0 },
generateBtn: { background: "#6c3483", border: "none", borderRadius: 4, color: "#fff", padding: "14px 28px", fontSize: 13, letterSpacing: 3, cursor: "pointer", fontFamily: "sans-serif", fontWeight: 700, alignSelf: "flex-start" },
formatHint: { background: "#0a0a18", border: "1px solid #1a1a3a", borderRadius: 6, padding: 16 },
hintTitle: { fontSize: 11, letterSpacing: 2, color: "#5a5a8a", margin: "0 0 12px", fontFamily: "sans-serif" },
hintGrid: { display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 },
hintLabel: { fontSize: 11, color: "#9b59b6", margin: "0 0 6px", fontFamily: "sans-serif", letterSpacing: 1 },
hintCode: { color: "#8a8aaa", fontSize: 11, margin: 0, fontFamily: "'Courier New', monospace", lineHeight: 1.6 },
playMain: { padding: "24px 20px", maxWidth: 1100, margin: "0 auto" },
playHeader: { display: "flex", alignItems: "center", gap: 20, marginBottom: 24, flexWrap: "wrap" },
backBtn: { background: "transparent", border: "1px solid #2a2a4a", borderRadius: 3, color: "#8a8aaa", padding: "6px 14px", cursor: "pointer", fontSize: 12, fontFamily: "sans-serif" },
playTitle: { fontSize: 20, margin: 0, color: "#c39bd3", letterSpacing: 2, flex: 1 },
progressBar: { width: 160, height: 6, background: "#1a1a3a", borderRadius: 3, display: "flex", alignItems: "center" },
progressFill: { height: "100%", background: "#9b59b6", borderRadius: 3, transition: "width 0.3s" },
progressText: { fontSize: 10, color: "#8a8aaa", marginLeft: 8, fontFamily: "sans-serif" },
playLayout: { display: "flex", gap: 32, alignItems: "flex-start", flexWrap: "wrap" },
gridWrapper: { overflowX: "auto" },
cellNum: { position: "absolute", top: 1, left: 2, fontSize: 8, color: "#7a7aaa", zIndex: 1, pointerEvents: "none", lineHeight: 1, fontFamily: "sans-serif" },
cluesPanel: { flex: 1, minWidth: 260, display: "flex", flexDirection: "column", gap: 24 },
clueSection: {},
clueTitle: { fontSize: 10, letterSpacing: 3, color: "#9b59b6", margin: "0 0 10px", fontFamily: "sans-serif", borderBottom: "1px solid #1a1a3a", paddingBottom: 6 },
clueItem: { display: "flex", gap: 8, padding: "6px 8px", borderRadius: 3, cursor: "pointer", marginBottom: 2, alignItems: "flex-start" },
clueItemActive: { background: "#1e1040" },
clueNum: { fontSize: 11, color: "#9b59b6", minWidth: 20, fontFamily: "sans-serif", paddingTop: 1 },
clueText: { fontSize: 12, color: "#b0b0d0", lineHeight: 1.5, fontFamily: "sans-serif" },
actions: { display: "flex", gap: 10, marginTop: 24, flexWrap: "wrap" },
actionBtn: { background: "#12122a", border: "1px solid #2a2a4a", borderRadius: 3, color: "#a0a0c0", padding: "8px 16px", cursor: "pointer", fontSize: 12, letterSpacing: 1, fontFamily: "sans-serif" },
revealWordBtn: { borderColor: "#9b59b6", color: "#c39bd3", background: "#1a0a2e" },
shareBtn: { borderColor: "#1a7a4a", color: "#2ecc71", background: "#0a1f14" },
exportBtn: { borderColor: "#6c3483", color: "#c39bd3" },
};