-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathzip.js
More file actions
514 lines (465 loc) · 21.3 KB
/
zip.js
File metadata and controls
514 lines (465 loc) · 21.3 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
/**
* ZIP PUZZLE SOLVER & BUILDER
*
* A Zip puzzle is a grid-based logic puzzle where:
* - Numbered dots are placed on the grid (starting with 1)
* - Players must draw a path connecting all dots in numerical order
* - Walls (thick borders) block path movement between adjacent cells
* - The path must visit every numbered dot exactly once
* - Players can build puzzles by placing dots and walls
* - AI assistance helps create puzzles from screenshots
*/
// ===================================================================
// CONFIGURATION & CONSTANTS
// ===================================================================
const CELL=48; // Size of each grid cell in pixels
const DOT=16; // Size of numbered dots
let COLS=6, ROWS=6; // Grid dimensions (always square)
const MAXIMUM_SEARCH_TIME = 30000; // Maximum solver time in milliseconds
// Canvas setup for drawing the puzzle grid
const canvas=document.getElementById('board');
/**
* Resizes the canvas based on current grid dimensions
*/
function resizeCanvas(){
canvas.width=COLS*CELL;
canvas.height=ROWS*CELL;
}
resizeCanvas(); // Initialize canvas
// ===================================================================
// GAME STATE VARIABLES
// ===================================================================
// Puzzle state variables (start empty)
let dots={}; // Object mapping dot numbers to [row, col] positions
let walls=new Set(); // Set of wall edges between adjacent cells
// ===================================================================
// UTILITY FUNCTIONS
// ===================================================================
// Canvas context for drawing
const ctx=canvas.getContext('2d');
ctx.lineCap='round'; // Smooth line endings
/**
* Converts row,col coordinates to a single cell ID
* @param {number} r - Row coordinate
* @param {number} c - Column coordinate
* @returns {number} Cell ID
*/
const id = (r,c) => r*COLS+c;
/**
* Creates a unique key for an edge between two cells
* @param {number} r1 - Row of first cell
* @param {number} c1 - Column of first cell
* @param {number} r2 - Row of second cell
* @param {number} c2 - Column of second cell
* @returns {string} Edge key in format "r1,c1|r2,c2"
*/
const ek = (r1,c1,r2,c2) => `${r1},${c1}|${r2},${c2}`;
/**
* Checks if there's a wall between two adjacent cells
* @param {number} r1 - Row of first cell
* @param {number} c1 - Column of first cell
* @param {number} r2 - Row of second cell
* @param {number} c2 - Column of second cell
* @returns {boolean} True if wall exists between cells
*/
const hasE = (r1,c1,r2,c2) => walls.has(ek(r1,c1,r2,c2))||walls.has(ek(r2,c2,r1,c1));
// Direction vectors for adjacent cell movement (up, down, left, right)
const dirs=[[ -1,0],[1,0],[0,-1],[0,1]];
/**
* Gets the highest numbered dot currently placed
* @returns {number} Highest dot number (0 if no dots)
*/
function hiDot(){
return Math.max(0,...Object.keys(dots).map(Number));
}
/**
* Gets the next available dot number (lowest missing number)
* @returns {number} Next available dot number
*/
function nextDotNumber(){
const existing = Object.keys(dots).map(Number).sort((a,b) => a-b);
if(existing.length === 0) return 1;
// Find the first gap in the sequence
for(let i = 1; i <= existing.length; i++){
if(!existing.includes(i)) return i;
}
// No gaps, return next sequential number
return existing[existing.length - 1] + 1;
}
/******** DRAW ************************/
function drawBoard(){
ctx.clearRect(0,0,canvas.width,canvas.height);
// grid
ctx.strokeStyle='#fff'; ctx.lineWidth=1.5; // White grid lines
for(let i=0;i<=COLS;i++){ctx.beginPath();ctx.moveTo(i*CELL,0);ctx.lineTo(i*CELL,ROWS*CELL);ctx.stroke();}
for(let j=0;j<=ROWS;j++){ctx.beginPath();ctx.moveTo(0,j*CELL);ctx.lineTo(COLS*CELL,j*CELL);ctx.stroke();}
// walls
ctx.strokeStyle='#fff'; ctx.lineWidth=6;
walls.forEach(e=>{const[[r1,c1],[r2,c2]]=e.split('|').map(s=>s.split(',').map(Number)); if(r1===r2){const x=Math.max(c1,c2)*CELL; ctx.beginPath();ctx.moveTo(x,r1*CELL);ctx.lineTo(x,(r1+1)*CELL);ctx.stroke();} else {const y=Math.max(r1,r2)*CELL; ctx.beginPath();ctx.moveTo(c1*CELL,y);ctx.lineTo((c1+1)*CELL,y);ctx.stroke();}});
// dots
ctx.font='16px sans-serif'; ctx.textAlign='center'; ctx.textBaseline='middle';
for(const [num,[r,c]] of Object.entries(dots)){ if(r>=ROWS||c>=COLS) continue; ctx.fillStyle='#fff'; ctx.beginPath();ctx.arc(c*CELL+CELL/2,r*CELL+CELL/2,DOT,0,Math.PI*2);ctx.fill(); ctx.fillStyle='#000'; ctx.fillText(num,c*CELL+CELL/2,r*CELL+CELL/2);} }
function drawPath(p){ if(!p) return; ctx.strokeStyle='#ff8800'; ctx.lineWidth=4; ctx.beginPath(); ctx.moveTo(p[0][1]*CELL+CELL/2,p[0][0]*CELL+CELL/2); for(let i=1;i<p.length;i++){const[r,c]=p[i]; ctx.lineTo(c*CELL+CELL/2,r*CELL+CELL/2);} ctx.stroke(); }
/******** SOLVER (fast) **************/
function targetSeq(){return Object.keys(dots).map(Number).sort((a,b)=>a-b).slice(1);} // after 1
let searchMetrics={visited:0,backtracks:0};
// flag to signal aborting an animated search
let abortRequested = false;
// timestamp for measuring search duration
let searchStartTime = 0;
function fastSolve(){
if(!dots[1]) return null;
const total = ROWS * COLS;
const vis = new Uint8Array(total);
const stack = [];
const path = [];
const tgt = targetSeq();
const last = Math.max(...Object.keys(dots).map(Number));
// Time-limit guard
const deadline = Date.now() + MAXIMUM_SEARCH_TIME;
stack.push({r: dots[1][0], c: dots[1][1], idx: 0, stage: 0});
while(stack.length){
if (Date.now() > deadline) return null;
const n = stack.pop();
const k = id(n.r, n.c);
if(n.stage === 0){
if(vis[k]) continue;
vis[k] = 1; searchMetrics.visited++;
path.push([n.r, n.c]);
let idx = n.idx;
if(idx < tgt.length){
const [tr, tc] = dots[tgt[idx]] || [];
if(n.r === tr && n.c === tc){
idx++;
} else if(Object.entries(dots).some(([nm, [dr, dc]]) => +nm !== 1 && +nm !== tgt[idx] && dr === n.r && dc === n.c)){
searchMetrics.backtracks++;
vis[k] = 0;
path.pop();
continue;
}
}
if(path.length === total && idx === tgt.length && dots[last] && n.r === dots[last][0] && n.c === dots[last][1]){
return path;
}
stack.push({...n, idx, stage: 1});
for(const [dr, dc] of dirs){
const nr = n.r + dr;
const nc = n.c + dc;
if(nr < 0 || nr >= ROWS || nc < 0 || nc >= COLS) continue;
if(hasE(n.r, n.c, nr, nc) || vis[id(nr, nc)]) continue;
stack.push({r: nr, c: nc, idx, stage: 0});
}
} else {
searchMetrics.backtracks++;
vis[k] = 0;
path.pop();
}
}
return null;
}
// Animated solver
function animateSolve(){
const total = ROWS * COLS;
const vis = new Uint8Array(total);
const stack = [];
const path = [];
const tgt = targetSeq();
const last = Math.max(...Object.keys(dots).map(Number));
const delay = 20; // ms
stack.push({r: dots[1][0], c: dots[1][1], idx: 0, stage: 0});
function step(){
if(abortRequested){
abortBtn.style.display = 'none';
startBtn.disabled = false;
statusEl.textContent = 'Aborted';
return;
}
if(stack.length === 0){
abortBtn.style.display = 'none';
statusEl.textContent = '❌ no path';
startBtn.disabled = false;
return;
}
const n = stack.pop();
const k = id(n.r, n.c);
if(n.stage === 0){
if(!vis[k]){
vis[k] = 1; searchMetrics.visited++;
path.push([n.r, n.c]);
let idx = n.idx;
if(idx < tgt.length){
const [tr, tc] = dots[tgt[idx]] || [];
if(n.r === tr && n.c === tc){ idx++; }
else if(Object.entries(dots).some(([nm, [dr, dc]]) => +nm !== 1 && +nm !== tgt[idx] && dr === n.r && dc === n.c)){
searchMetrics.backtracks++;
vis[k] = 0;
path.pop();
updateUI();
return setTimeout(step, delay);
}
}
if(path.length === total && idx === tgt.length && dots[last] && n.r === dots[last][0] && n.c === dots[last][1]){
abortBtn.style.display = 'none';
drawBoard(); drawPath(path);
statusEl.textContent = '✅ solved';
visitedEl.innerHTML = `<strong>Cells Visited:</strong> ${searchMetrics.visited.toLocaleString()}`;
backtracksEl.innerHTML = `<strong>Backtracks:</strong> ${searchMetrics.backtracks.toLocaleString()}`;
startBtn.disabled = false;
return;
}
stack.push({...n, idx, stage: 1});
for(const [dr, dc] of dirs){
const nr = n.r + dr, nc = n.c + dc;
if(nr < 0 || nr >= ROWS || nc < 0 || nc >= COLS) continue;
if(hasE(n.r, n.c, nr, nc) || vis[id(nr, nc)]) continue;
stack.push({r: nr, c: nc, idx, stage: 0});
}
}
} else {
searchMetrics.backtracks++;
vis[k] = 0;
path.pop();
}
updateUI();
setTimeout(step, delay);
}
function updateUI(){
drawBoard(); drawPath(path);
statusEl.textContent = 'Searching...';
visitedEl.innerHTML = `<strong>Cells Visited:</strong> ${searchMetrics.visited.toLocaleString()}`;
backtracksEl.innerHTML = `<strong>Backtracks:</strong> ${searchMetrics.backtracks.toLocaleString()}`;
}
step();
}
/******** BUILD INTERACTION **********/
const buildStatus=document.getElementById('buildStatus');
function toggleWall(r1,c1,r2,c2){const k=ek(r1,c1,r2,c2),rev=ek(r2,c2,r1,c1); if(walls.delete(k)||walls.delete(rev)) return; walls.add(k);}
canvas.addEventListener('click',e=>{
if(!document.getElementById('aiTab').classList.contains('active')) return;
const rect=canvas.getBoundingClientRect();
const x=e.clientX-rect.left, y=e.clientY-rect.top;
const cellWidth=rect.width/COLS, cellHeight=rect.height/ROWS;
const c=Math.floor(x/cellWidth), r=Math.floor(y/(cellHeight)); if(r<0||r>=ROWS||c<0||c>=COLS) return;
const gx=x%cellWidth, gy=y%cellHeight, tol=cellWidth/6;
const L=(gx<tol), R=(cellWidth-gx)<tol, T=gy<tol, B=(cellHeight-gy)<tol;
const aiStatus = document.getElementById('aiStatus');
if(L&&c>0){toggleWall(r,c-1,r,c); if(aiStatus) aiStatus.textContent='toggled wall'; drawBoard(); checkSizeInputs(); return;}
if(R&&c<(COLS-1)){toggleWall(r,c,r,c+1); if(aiStatus) aiStatus.textContent='toggled wall'; drawBoard(); checkSizeInputs(); return;}
if(T&&r>0){toggleWall(r-1,c,r,c); if(aiStatus) aiStatus.textContent='toggled wall'; drawBoard(); checkSizeInputs(); return;}
if(B&&r<(ROWS-1)){toggleWall(r,c,r+1,c); if(aiStatus) aiStatus.textContent='toggled wall'; drawBoard(); checkSizeInputs(); return;}
// nodes
for(const [num,[dr,dc]] of Object.entries(dots)){ if(dr===r&&dc===c){ delete dots[num]; if(aiStatus) aiStatus.textContent=`Deleted node ${num}`; drawBoard(); checkSizeInputs(); return;} }
const next=nextDotNumber(); dots[next]=[r,c]; if(aiStatus) aiStatus.textContent=`Added node ${next}`; drawBoard(); checkSizeInputs();
});
/******** SIZE INPUTS ***************/
function clearAll(){ dots={}; walls=new Set(); drawBoard(); }
function checkSizeInputs(){ const disable = Object.keys(dots).length>0||walls.size>0; const s=document.getElementById('aiSizeInp'); if(s){ s.disabled=disable; } }
const aiSizeInp=document.getElementById('aiSizeInp');
if(aiSizeInp){ aiSizeInp.addEventListener('change',()=>{ if(aiSizeInp.disabled) return; COLS=ROWS=parseInt(aiSizeInp.value,10); resizeCanvas(); drawBoard(); }); }
/******** UI BUTTONS & TABS *********/
const clearBtn = document.getElementById('clearBtn');
if(clearBtn){ clearBtn.addEventListener('click',()=>{ clearAll(); const aiStatus = document.getElementById('aiStatus'); if(aiStatus) aiStatus.textContent='cleared — adjust size or add items'; checkSizeInputs(); }); }
const statusEl=document.getElementById('status'), startBtn=document.getElementById('startBtn'), abortBtn=document.getElementById('abortBtn'), animateChk=document.getElementById('animateChk'), visitedEl=document.getElementById('cellsVisited'), backtracksEl=document.getElementById('backtracks'), timerEl=document.getElementById('timer');
// Abort button requested flag handler
abortBtn.addEventListener('click', () => {
abortRequested = true;
abortBtn.style.display = 'none';
startBtn.disabled = false;
statusEl.textContent = 'Aborted';
});
startBtn.addEventListener('click',()=>{
statusEl.textContent='Searching...'; startBtn.disabled=true;
// reset abort flag and button
abortRequested = false;
abortBtn.style.display = 'none';
searchMetrics.visited=0; searchMetrics.backtracks=0;
visitedEl.innerHTML=''; backtracksEl.innerHTML='';
// reset and show timer
timerEl.innerHTML = '';
searchStartTime = Date.now();
drawBoard();
if(animateChk.checked){
// show abort button for animated search
abortBtn.style.display = 'inline-block';
animateSolve();
} else {
setTimeout(()=>{
drawBoard(); const sol=fastSolve(); if(sol){ drawPath(sol); statusEl.textContent='✅ solved'; } else { statusEl.textContent='❌ no path'; }
visitedEl.innerHTML=`<strong>Cells Visited:</strong> ${searchMetrics.visited.toLocaleString()}`;
backtracksEl.innerHTML=`<strong>Backtracks:</strong> ${searchMetrics.backtracks.toLocaleString()}`;
// display elapsed time
const elapsedMs = Date.now() - searchStartTime;
timerEl.innerHTML = `<strong>Time:</strong> ${(elapsedMs/1000).toFixed(3)} s`;
startBtn.disabled=false;
},0);
}
});
document.querySelectorAll('.tab-btn').forEach(btn=>btn.addEventListener('click',()=>{
document.querySelectorAll('.tab-btn').forEach(b=>b.classList.remove('active')); btn.classList.add('active');
document.querySelectorAll('.tab-content').forEach(p=>p.classList.remove('active')); document.getElementById(btn.dataset.tab).classList.add('active');
drawBoard(); }));
/******** INIT *********/
checkSizeInputs(); drawBoard();
/******** AI BUILD (Gemini) *********/
(function initAiBuild(){
const genBtn = document.getElementById('genPromptBtn');
const copyBtn = document.getElementById('copyPromptBtn');
const runBtn = document.getElementById('runAiBtn');
const applyBtn = document.getElementById('applyJsonBtn');
const promptBox = document.getElementById('aiPrompt');
const jsonBox = document.getElementById('aiJsonOut');
const aiStatus = document.getElementById('aiStatus');
const aiImage = document.getElementById('aiImage');
const pasteImgBtn = document.getElementById('pasteImgBtn');
const aiPreview = document.getElementById('aiPreview');
const aiKey = document.getElementById('aiKey');
try{ const v=localStorage.getItem('gemini_api_key'); if(v && !aiKey.value) aiKey.value=v; }catch{}
const aiSizeInp = document.getElementById('aiSizeInp');
if(!genBtn || !copyBtn || !applyBtn) return;
function getCurrentConfig(){
return {
cols: COLS,
rows: ROWS,
dots: {...dots},
walls: Array.from(walls)
};
}
function generateGeminiPrompt(){
const targetSize = aiSizeInp ? parseInt(aiSizeInp.value, 10) : 6;
const schema = `Required JSON format (no prose, JSON only):\n{\n "cols": <int>,\n "rows": <int>,\n "dots": {\n "1": [r, c],\n "2": [r, c]\n },\n "walls": ["r1,c1|r2,c2", ...]\n}`;
const guidance = `Rules:\n- Use zero-based indices (top-left is [0,0]).\n- Each entry in dots maps a number (as string) to [row, col].\n- Walls encode edges between orthogonally adjacent cells as "r1,c1|r2,c2".\n- Do not include diagonal walls.\n- Ensure cols*rows equals the number of cells implied by the grid.\n- If unclear, estimate and be conservative; prefer fewer dots/walls.\n- Output pure JSON only.`;
const imgNote = `A screenshot is provided. Infer the grid (${targetSize}x${targetSize}), dot numbers with their cells, and all walls between cells.`;
// const imgNote = aiImage && aiImage.files && aiImage.files[0] ? `A screenshot is provided. Infer the grid (cols x rows), dot numbers with their cells, and all walls between cells.` : `Use my current grid as context if needed, but produce a fresh full JSON.`;
const current = getCurrentConfig();
const context = `Existing context (may be empty): ${JSON.stringify(current)}`;
return [
'You are an expert at reading Zip puzzles from images and transcribing them. Given an image of a Zip puzzle, produce a structured JSON describing the grid, dots (numbered nodes), and walls (thick borders between adjacent cells).',
`grid is ${targetSize}x${targetSize}, analyze cell by cell to ensure maximum accuracy of the numbers and walls`,
imgNote,
guidance,
schema,
context
].join('\n\n');
}
function applyJsonToGrid(payload){
try{
const { cols, rows, dots: newDots, walls: newWalls } = payload || {};
if(typeof cols === 'number' && typeof rows === 'number'){
COLS = cols; ROWS = rows; resizeCanvas();
}
dots = {};
if(newDots && typeof newDots === 'object'){
for(const [k, v] of Object.entries(newDots)){
if(Array.isArray(v) && v.length===2){ dots[k] = [Number(v[0]), Number(v[1])]; }
}
}
walls = new Set();
if(Array.isArray(newWalls)){
for(const w of newWalls){ if(typeof w === 'string') walls.add(w); }
}
drawBoard(); checkSizeInputs();
aiStatus.textContent = 'Applied JSON to grid';
} catch(e){
aiStatus.textContent = 'Failed to apply JSON';
}
}
genBtn.addEventListener('click', ()=>{
promptBox.value = generateGeminiPrompt();
aiStatus.textContent = 'Prompt generated';
});
copyBtn.addEventListener('click', async ()=>{
try {
await navigator.clipboard.writeText(promptBox.value || '');
aiStatus.textContent = 'Prompt copied';
} catch {
aiStatus.textContent = 'Copy failed';
}
});
applyBtn.addEventListener('click', ()=>{
try{
const obj = JSON.parse(jsonBox.value || '{}');
applyJsonToGrid(obj);
} catch{
aiStatus.textContent = 'Invalid JSON';
}
});
async function fileToBase64(file){
return new Promise((resolve, reject)=>{
const reader = new FileReader();
reader.onload = ()=> resolve(reader.result.split(',')[1]);
reader.onerror = reject;
reader.readAsDataURL(file);
});
}
async function pasteImageFromClipboard(){
if(!navigator.clipboard || !navigator.clipboard.read){
aiStatus.textContent = 'Clipboard image read not supported';
return;
}
try{
const items = await navigator.clipboard.read();
for(const item of items){
for(const type of item.types){
if(type.startsWith('image/')){
const blob = await item.getType(type);
// Update docked preview
const url = URL.createObjectURL(blob);
const dock=document.getElementById('aiPreviewDock'); if(dock){ dock.src=url; dock.style.display='inline-block'; }
// Mirror into the file input for reuse in upload flow
try{
const file = new File([blob], 'clipboard-image.' + (type.split('/')[1]||'png'), { type });
// Note: programmatically setting <input type="file"> files is restricted in browsers
// We store it on the element for our flow instead
aiImage._clipboardFile = file;
} catch{}
aiStatus.textContent = 'Image pasted from clipboard';
return;
}
}
}
aiStatus.textContent = 'No image in clipboard';
} catch(e){
aiStatus.textContent = 'Failed to read clipboard';
}
}
if(pasteImgBtn){ pasteImgBtn.addEventListener('click', pasteImageFromClipboard); }
runBtn.addEventListener('click', async ()=>{
aiStatus.textContent = 'Calling Gemini...';
try{
const key = (aiKey && aiKey.value || '').trim();
try{ if(key) localStorage.setItem('gemini_api_key', key); }catch{}
if(!key){ aiStatus.textContent = 'Missing API key'; return; }
const url = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=${encodeURIComponent(key)}`;
const parts = [];
if(promptBox.value){ parts.push({text: promptBox.value}); }
let file = undefined;
if(aiImage && aiImage.files && aiImage.files[0]){
file = aiImage.files[0];
} else if(aiImage && aiImage._clipboardFile){
file = aiImage._clipboardFile;
}
if(file){
const b64 = await fileToBase64(file);
const mimeType = file.type || 'image/png';
parts.push({inline_data: { mime_type: mimeType, data: b64 }});
const url = URL.createObjectURL(file); const dock=document.getElementById('aiPreviewDock'); if(dock){ dock.src=url; dock.style.display='inline-block'; }
}
const body = { contents: [{ role: 'user', parts }] };
const resp = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body)
});
if(!resp.ok){ aiStatus.textContent = `HTTP ${resp.status}`; return; }
const data = await resp.json();
const text = data?.candidates?.[0]?.content?.parts?.[0]?.text || '';
if(!text){ aiStatus.textContent = 'Empty model response'; return; }
// Some models wrap JSON in ``` blocks; strip if present
const cleaned = text.replace(/^```[\s\S]*?\n/, '').replace(/```\s*$/, '');
jsonBox.value = cleaned;
aiStatus.textContent = 'Model response inserted; click Apply to Grid';
} catch(e){
aiStatus.textContent = 'Error calling Gemini';
}
});
})();