File size: 25,002 Bytes
4bf234c
a889f5f
 
4bf234c
 
 
 
 
 
 
 
 
 
a889f5f
 
 
 
 
 
4bf234c
a889f5f
 
4bf234c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a889f5f
 
 
 
4bf234c
 
 
 
 
a889f5f
 
 
 
 
 
 
 
 
 
 
 
 
 
4bf234c
 
a889f5f
 
4bf234c
 
 
a889f5f
 
4bf234c
a889f5f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4bf234c
a889f5f
 
 
 
 
 
 
 
 
4bf234c
a889f5f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4bf234c
a889f5f
4bf234c
 
a889f5f
 
4bf234c
 
 
 
 
 
a889f5f
 
4bf234c
 
 
 
a889f5f
 
 
 
 
4bf234c
 
 
 
 
 
 
 
 
 
 
 
 
a889f5f
4bf234c
 
 
a889f5f
 
 
 
 
4bf234c
 
 
 
 
 
 
 
 
 
a889f5f
 
4bf234c
 
 
 
 
 
 
 
a889f5f
4bf234c
 
 
 
a889f5f
4bf234c
a889f5f
 
4bf234c
 
 
 
 
 
 
 
 
 
a889f5f
 
 
4bf234c
 
 
a889f5f
4bf234c
 
 
a889f5f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4bf234c
 
a889f5f
 
 
 
4bf234c
a889f5f
 
 
4bf234c
a889f5f
 
 
4bf234c
 
a889f5f
 
 
4bf234c
a889f5f
 
 
 
 
 
 
4bf234c
 
 
a889f5f
4bf234c
 
 
a889f5f
 
4bf234c
a889f5f
 
 
 
 
 
 
 
 
 
4bf234c
 
a889f5f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4bf234c
 
 
a889f5f
 
 
 
 
 
4bf234c
a889f5f
4bf234c
a889f5f
 
4bf234c
 
 
 
 
 
d2c9f14
 
4bf234c
 
 
 
 
 
 
 
 
 
 
 
a889f5f
4bf234c
 
 
 
 
 
a889f5f
4bf234c
 
a889f5f
 
4bf234c
 
 
a889f5f
 
4bf234c
 
 
 
a889f5f
d2c9f14
4bf234c
 
 
a889f5f
4bf234c
a889f5f
4bf234c
 
 
 
a889f5f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4bf234c
a889f5f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4bf234c
a889f5f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4bf234c
a889f5f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4bf234c
a889f5f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4bf234c
a889f5f
 
 
4bf234c
a889f5f
4bf234c
 
a889f5f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4bf234c
a889f5f
4bf234c
 
a889f5f
4bf234c
 
 
 
a889f5f
4bf234c
 
 
 
a889f5f
 
 
 
 
 
 
 
 
 
 
4bf234c
a889f5f
 
 
4bf234c
a889f5f
4bf234c
a889f5f
 
 
 
 
 
 
 
 
4bf234c
 
 
a889f5f
 
 
 
4bf234c
 
 
 
a889f5f
 
 
 
4bf234c
 
 
 
 
 
 
a889f5f
4bf234c
 
 
a889f5f
4bf234c
 
 
 
 
 
 
 
 
a889f5f
 
4bf234c
a889f5f
4bf234c
 
 
 
 
 
 
 
 
 
a889f5f
4bf234c
 
 
 
 
 
 
 
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
import React, { useReducer, useState, useEffect, useRef, useCallback } from 'react';
import { Upload, Download, Layers, Image as ImageIcon, Wand2, Sliders, AlertCircle, CheckCircle, Trash2, ZoomIn, ZoomOut } from 'lucide-react';
import ImageTracer from 'imagetracerjs';

// --- State Management ---
const initialState = {
  status: 'IDLE',
  imageSrc: null,
  processedSvg: null,
  settings: {
    tolerance: 30,
    simplification: 0.5,
    colorCount: 2,
    bgColor: '#ffffff',
    scale: 1,
    ltres: 1,
    qtres: 1,
    pathomit: 8,
    rightangleenhance: true
  },
  error: null,
  zoom: 100
};

const reducer = (state, action) => {
  switch (action.type) {
    case 'SET_STATUS':
      return { ...state, status: action.payload };
    case 'SET_IMAGE':
      return { ...state, imageSrc: action.payload, status: 'MASKING' };
    case 'SET_SETTINGS':
      return { ...state, settings: { ...state.settings, ...action.payload } };
    case 'SET_SVG':
      return { ...state, processedSvg: action.payload, status: 'READY' };
    case 'SET_ERROR':
      return { ...state, error: action.payload, status: 'IDLE' };
    case 'RESET':
      return initialState;
    case 'SET_ZOOM':
      return { ...state, zoom: action.payload };
    case 'CLEAR_SVG':
      return { ...state, processedSvg: null, status: 'MASKING' };
    default:
      return state;
  }
};

// --- Engine: HEIC to JPEG/Blob Conversion ---
const convertHeicToBlob = async (file) => {
  try {
    const heic2any = (await import('heic2any')).default;
    const converted = await heic2any({
      blob: file,
      toType: 'image/jpeg',
      quality: 0.9
    });
    return converted;
  } catch (error) {
    console.error('HEIC conversion failed:', error);
    return file;
  }
};

// --- Engine: Advanced Background Removal ---
const removeBackgroundAdvanced = (canvas, tolerance, bgColor) => {
  const ctx = canvas.getContext('2d');
  const width = canvas.width;
  const height = canvas.height;
  const imageData = ctx.getImageData(0, 0, width, height);
  const data = imageData.data;
  
  // Parse background color
  const bgRgb = hexToRgb(bgColor);
  
  for (let i = 0; i < data.length; i += 4) {
    const r = data[i];
    const g = data[i + 1];
    const b = data[i + 2];
    
    // Calculate color distance
    const distance = Math.sqrt(
      Math.pow(r - bgRgb.r, 2) +
      Math.pow(g - bgRgb.g, 2) +
      Math.pow(b - bgRgb.b, 2)
    );
    
    // Also check if pixel is close to white/light (common background)
    const brightness = (r + g + b) / 3;
    const isLightBackground = brightness > 240 && distance < 50;
    
    if (distance < tolerance || isLightBackground) {
      data[i + 3] = 0; // Set alpha to 0 (transparent)
    }
  }
  
  ctx.putImageData(imageData, 0, 0);
};

// Helper: Hex to RGB
const hexToRgb = (hex) => {
  const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return result ? {
    r: parseInt(result[1], 16),
    g: parseInt(result[2], 16),
    b: parseInt(result[3], 16)
  } : { r: 255, g: 255, b: 255 };
};

// --- Engine: Real SVG Vectorization ---
const vectorizeImage = (canvas, settings) => {
  return new Promise((resolve, reject) => {
    try {
      const tracerOptions = {
        ltres: settings.ltres,
        qtres: settings.qtres,
        pathomit: settings.pathomit,
        colorsampling: 2,
        numberofcolors: settings.colorCount,
        mincolorratio: 0,
        colorquantcycles: 3,
        scale: settings.scale,
        simplify: settings.simplification,
        rightangleenhance: settings.rightangleenhance,
        blurradius: 0,
        blurdelta: 20
      };
      
      ImageTracer.imageToSVG(
        canvas.toDataURL('image/png'),
        (svgString) => {
          resolve(svgString);
        },
        tracerOptions
      );
    } catch (error) {
      reject(error);
    }
  });
};

// --- Engine: SVG Sanitizer for Cutting Machines ---
const sanitizeSvgForCutting = (svgString) => {
  const parser = new DOMParser();
  const doc = parser.parseFromString(svgString, 'image/svg+xml');
  const svgElement = doc.querySelector('svg');

  if (!svgElement) return svgString;

  // Remove unwanted elements
  ['metadata', 'desc', 'style', 'image', 'clipPath', 'mask'].forEach(tag => {
    const elements = svgElement.querySelectorAll(tag);
    elements.forEach(el => el.remove());
  });

  // Set proper viewBox and dimensions
  svgElement.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
  svgElement.setAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink');
  
  // Convert all styles to attributes
  const elements = svgElement.querySelectorAll('*');
  elements.forEach(el => {
    const style = el.getAttribute('style');
    if (style) {
      const styleObj = {};
      style.split(';').forEach(rule => {
        const [prop, val] = rule.split(':');
        if (prop && val) styleObj[prop.trim()] = val.trim();
      });

      if (styleObj['fill']) el.setAttribute('fill', styleObj['fill']);
      if (styleObj['stroke']) el.setAttribute('stroke', styleObj['stroke']);
      if (styleObj['stroke-width']) el.setAttribute('stroke-width', styleObj['stroke-width']);
      if (styleObj['opacity']) el.setAttribute('opacity', styleObj['opacity']);
      
      el.removeAttribute('style');
    }
    
    // Ensure paths have proper fill for cutting
    if (el.tagName === 'path' && !el.getAttribute('fill')) {
      el.setAttribute('fill', '#000000');
    }
  });

  return `<?xml version="1.0" encoding="UTF-8"?>\n${svgElement.outerHTML}`;
};

// --- Main Application Component ---
export default function CutForgeStudio() {
  const [state, dispatch] = useReducer(reducer, initialState);
  const canvasRef = useRef(null);
  const imageRef = useRef(null);
  const containerRef = useRef(null);
  const [previewMode, setPreviewMode] = useState('original'); // 'original', 'masked', 'vector'

  // --- Handlers ---

  const handleFileUpload = async (e) => {
    const file = e.target.files[0];
    if (!file) return;

    dispatch({ type: 'SET_STATUS', payload: 'UPLOADING' });
    dispatch({ type: 'SET_ERROR', payload: null });

    try {
      let processedFile = file;
      
      // Handle HEIC files
      if (file.name.toLowerCase().endsWith('.heic')) {
        dispatch({ type: 'SET_STATUS', payload: 'UPLOADING' });
        processedFile = await convertHeicToBlob(file);
      }

      const url = URL.createObjectURL(processedFile);
      imageRef.current.src = url;
      
      imageRef.current.onload = () => {
        dispatch({ type: 'SET_IMAGE', payload: url });
        processImage(url);
      };
    } catch (err) {
      console.error('Upload error:', err);
      dispatch({ type: 'SET_ERROR', payload: 'Failed to load image. Please try again.' });
      dispatch({ type: 'SET_STATUS', payload: 'IDLE' });
    }
  };

  const processImage = useCallback((src) => {
    const canvas = canvasRef.current;
    const img = imageRef.current;
    
    if (!canvas || !img) return;
    
    // Set canvas dimensions (max 2000px for performance)
    const maxSize = 2000;
    let width = img.naturalWidth;
    let height = img.naturalHeight;
    
    if (width > maxSize || height > maxSize) {
      const ratio = Math.min(maxSize / width, maxSize / height);
      width = Math.floor(width * ratio);
      height = Math.floor(height * ratio);
    }
    
    canvas.width = width;
    canvas.height = height;
    
    const ctx = canvas.getContext('2d');
    ctx.drawImage(img, 0, 0, width, height);

    // Apply background removal
    removeBackgroundAdvanced(canvas, state.settings.tolerance, state.settings.bgColor);

    dispatch({ type: 'SET_STATUS', payload: 'MASKING' });
    setPreviewMode('masked');
  }, [state.settings.tolerance, state.settings.bgColor]);

  const generateVector = useCallback(async () => {
    if (!canvasRef.current) return;
    
    dispatch({ type: 'SET_STATUS', payload: 'VECTORIZING' });

    try {
      const rawSvg = await vectorizeImage(canvasRef.current, state.settings);
      const cleanSvg = sanitizeSvgForCutting(rawSvg);
      dispatch({ type: 'SET_SVG', payload: cleanSvg });
      setPreviewMode('vector');
    } catch (error) {
      console.error('Vectorization error:', error);
      dispatch({ type: 'SET_ERROR', payload: 'Vectorization failed. Try adjusting settings.' });
      dispatch({ type: 'SET_STATUS', payload: 'MASKING' });
    }
  }, [state.settings]);

  const downloadSvg = () => {
    if (!state.processedSvg) return;
    const blob = new Blob([state.processedSvg], { type: 'image/svg+xml;charset=utf-8' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `cutforge-${Date.now()}.svg`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  };

  const downloadPreview = () => {
    if (!canvasRef.current) return;
    const link = document.createElement('a');
    link.download = `cutforge-preview-${Date.now()}.png`;
    link.href = canvasRef.current.toDataURL('image/png');
    link.click();
  };

  const handleZoom = (delta) => {
    const newZoom = Math.max(25, Math.min(400, state.zoom + delta));
    dispatch({ type: 'SET_ZOOM', payload: newZoom });
  };

  const resetWorkspace = () => {
    dispatch({ type: 'RESET' });
    setPreviewMode('original');
    if (canvasRef.current) {
      const ctx = canvasRef.current.getContext('2d');
      ctx.clearRect(0, 0, canvasRef.current.width, canvasRef.current.height);
    }
  };

  // Re-process when settings change
  useEffect(() => {
    if (state.imageSrc && state.status === 'MASKING' || state.status === 'READY') {
      const timer = setTimeout(() => {
        processImage(state.imageSrc);
      }, 300);
      return () => clearTimeout(timer);
    }
  }, [state.settings.tolerance, state.settings.bgColor, state.imageSrc]);

  // --- Render Helpers ---

  const renderStatusBadge = () => {
    const config = {
      IDLE: { color: 'bg-gray-200 text-gray-600', label: 'Ready' },
      UPLOADING: { color: 'bg-saffron text-ink', label: 'Uploading...' },
      MASKING: { color: 'bg-forest text-white', label: 'Processing' },
      VECTORIZING: { color: 'bg-forest text-white animate-pulse', label: 'Vectorizing...' },
      READY: { color: 'bg-saffron text-ink', label: 'Complete' }
    };
    const { color, label } = config[state.status];
    return (
      <span className={`px-3 py-1 rounded-full text-xs font-bold uppercase tracking-widest ${color}`}>
        {label}
      </span>
    );
  };

  return (
    <div className="min-h-screen bg-bone font-sans text-ink flex flex-col overflow-hidden">
      {/* Header */}
      <header className="h-16 border-b border-ink/10 flex justify-between px-6 items-center sticky top-0 bg-bone/90 backdrop-blur z-10">
        <div className="flex items-center gap-2">
          <div className="w-8 h-8 bg-forest rounded-lg flex items-center justify-center text-white">
            <Layers size={20} />
          </div>
          <h1 className="font-serif font-bold text-xl tracking-tight">CutForge Studio</h1>
        </div>
        <div className="flex items-center gap-4">
          {renderStatusBadge()}
          <a 
            href="https://huggingface.co/spaces/akhaliq/anycoder" 
            target="_blank" 
            rel="noopener noreferrer"
            className="text-xs font-medium text-ink/60 hover:text-forest transition-colors underline"
          >
            Built with anycoder
          </a>
        </div>
      </header>

      {/* Main Grid Layout */}
      <main className="flex-1 grid grid-cols-12 h-[calc(100vh - 64px)]">
        
        {/* LEFT RAIL: Controls */}
        <aside className="col-span-3 border-r border-ink/10 bg-bone p-6 flex flex-col gap-6 overflow-y-auto">
          
          {/* Upload Section */}
          <div className="space-y-4">
            <h2 className="font-serif text-lg font-bold flex items-center gap-2">
              <Upload size={18} /> Source Image
            </h2>
            <div className="relative group cursor-pointer">
              <input 
                type="file" 
                accept=".png,.jpg,.jpeg,.heic,.webp" 
                onChange={handleFileUpload}
                className="absolute inset-0 w-full h-full opacity-0 z-10 cursor-pointer"
              />
              <div className="border-2 border-dashed border-ink/20 rounded-xl p-6 flex flex-col items-center justify-center text-center hover:border-forest hover:bg-forest/5 transition-all">
                <ImageIcon className="text-ink/40 mb-2" size={32} />
                <span className="text-sm font-medium">Drop Image or Click</span>
                <span className="text-xs text-ink/50 mt-1">PNG, JPG, HEIC, WebP</span>
              </div>
            </div>
          </div>

          {/* Preview Mode Toggle */}
          {state.imageSrc && (
            <div className="space-y-3">
              <h2 className="font-serif text-lg font-bold flex items-center gap-2">
                <ImageIcon size={18} /> Preview Mode
              </h2>
              <div className="grid grid-cols-3 gap-2">
                <button
                  onClick={() => setPreviewMode('original')}
                  className={`px-3 py-2 text-xs font-medium rounded-lg border transition-all ${
                    previewMode === 'original' 
                      ? 'bg-forest text-white border-forest' 
                      : 'bg-white text-ink border-ink/20 hover:border-forest'
                  }`}
                >
                  Original
                </button>
                <button
                  onClick={() => setPreviewMode('masked')}
                  className={`px-3 py-2 text-xs font-medium rounded-lg border transition-all ${
                    previewMode === 'masked' 
                      ? 'bg-forest text-white border-forest' 
                      : 'bg-white text-ink border-ink/20 hover:border-forest'
                  }`}
                >
                  Masked
                </button>
                <button
                  onClick={() => {
                    setPreviewMode('vector');
                    if (!state.processedSvg) generateVector();

                  className={`px-3 py-2 text-xs font-medium rounded-lg border transition-all ${
                    previewMode === 'vector' 
                      ? 'bg-forest text-white border-forest' 
                      : 'bg-white text-ink border-ink/20 hover:border-forest'
                  }`}
                >
                  Vector
                </button>
              </div>
            </div>
          )}

          {/* Controls Section */}
          {state.imageSrc && (
            <div className="space-y-5">
              <h2 className="font-serif text-lg font-bold flex items-center gap-2">
                <Sliders size={18} /> Settings
              </h2>

              {/* Tolerance Slider */}
              <div className="space-y-2">
                <div className="flex justify-between items-center">
                  <label className="text-xs font-bold uppercase tracking-wider text-ink/70">Background Tolerance</label>
                  <span className="text-xs font-mono bg-ink/10 px-2 py-1 rounded">{state.settings.tolerance}</span>
                </div>
                <input 
                  type="range" 
                  min="0" max="150" 
                  value={state.settings.tolerance}
                  onChange={(e) => dispatch({ type: 'SET_SETTINGS', payload: { tolerance: parseInt(e.target.value) } })}
                  className="w-full h-2 bg-ink/10 rounded-lg appearance-none cursor-pointer accent-forest"
                />
                <p className="text-xs text-ink/50">Higher = more aggressive removal</p>
              </div>

              {/* Background Color Picker */}
              <div className="space-y-2">
                <label className="text-xs font-bold uppercase tracking-wider text-ink/70">Background Color</label>
                <div className="flex gap-2">
                  <input 
                    type="color" 
                    value={state.settings.bgColor}
                    onChange={(e) => dispatch({ type: 'SET_SETTINGS', payload: { bgColor: e.target.value } })}
                    className="w-10 h-10 rounded border border-ink/20 cursor-pointer"
                  />
                  <input 
                    type="text" 
                    value={state.settings.bgColor}
                    onChange={(e) => dispatch({ type: 'SET_SETTINGS', payload: { bgColor: e.target.value } })}
                    className="flex-1 bg-white border border-ink/10 rounded px-3 text-sm font-mono"
                  />
                </div>
              </div>

              {/* Color Count */}
              <div className="space-y-2">
                <label className="text-xs font-bold uppercase tracking-wider text-ink/70">Color Count</label>
                <select 
                  value={state.settings.colorCount}
                  onChange={(e) => dispatch({ type: 'SET_SETTINGS', payload: { colorCount: parseInt(e.target.value) } })}
                  className="w-full bg-white border border-ink/10 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-forest"
                >
                  <option value="1">1 Color (Monochrome)</option>
                  <option value="2">2 Colors</option>
                  <option value="4">4 Colors</option>
                  <option value="8">8 Colors</option>
                  <option value="16">16 Colors</option>
                </select>
              </div>

              {/* Simplification Slider */}
              <div className="space-y-2">
                <div className="flex justify-between items-center">
                  <label className="text-xs font-bold uppercase tracking-wider text-ink/70">Path Simplification</label>
                  <span className="text-xs font-mono bg-ink/10 px-2 py-1 rounded">{state.settings.simplification}</span>
                </div>
                <input 
                  type="range" 
                  min="0" max="2" step="0.1"
                  value={state.settings.simplification}
                  onChange={(e) => dispatch({ type: 'SET_SETTINGS', payload: { simplification: parseFloat(e.target.value) } })}
                  className="w-full h-2 bg-ink/10 rounded-lg appearance-none cursor-pointer accent-forest"
                />
                <p className="text-xs text-ink/50">Higher = smoother paths</p>
              </div>

              {/* Line Threshold */}
              <div className="space-y-2">
                <div className="flex justify-between items-center">
                  <label className="text-xs font-bold uppercase tracking-wider text-ink/70">Line Threshold</label>
                  <span className="text-xs font-mono bg-ink/10 px-2 py-1 rounded">{state.settings.ltres}</span>
                </div>
                <input 
                  type="range" 
                  min="0.1" max="5" step="0.1"
                  value={state.settings.ltres}
                  onChange={(e) => dispatch({ type: 'SET_SETTINGS', payload: { ltres: parseFloat(e.target.value) } })}
                  className="w-full h-2 bg-ink/10 rounded-lg appearance-none cursor-pointer accent-forest"
                />
              </div>

              {/* Vectorize Button */}
              <button 
                onClick={generateVector}
                disabled={state.status === 'VECTORIZING'}
                className="w-full py-3 bg-forest hover:bg-forest/90 disabled:bg-ink/30 text-white font-medium rounded-lg transition-colors flex items-center justify-center gap-2"
              >
                <Wand2 size={16} /> 
                {state.status === 'VECTORIZING' ? 'Processing...' : 'Generate Vector'}
              </button>
            </div>
          )}

          {/* Actions */}
          <div className="mt-auto pt-6 border-t border-ink/10 space-y-3">
            {state.processedSvg && (
              <button 
                onClick={downloadSvg}
                className="w-full py-3 bg-ink hover:bg-ink/90 text-white font-medium rounded-lg transition-colors flex items-center justify-center gap-2"
              >
                <Download size={16} /> Download SVG
              </button>
            )}
            {state.imageSrc && (
              <button 
                onClick={downloadPreview}
                className="w-full py-3 bg-white border border-ink/20 hover:bg-ink/5 text-ink font-medium rounded-lg transition-colors flex items-center justify-center gap-2"
              >
                <Download size={16} /> Download Preview
              </button>
            )}
            <button 
              onClick={resetWorkspace}
              className="w-full py-3 bg-ink/5 hover:bg-ink/10 text-ink font-medium rounded-lg transition-colors flex items-center justify-center gap-2"
            >
              <Trash2 size={16} /> Reset Workspace
            </button>
          </div>
        </aside>

        {/* MAIN STAGE: Preview Area */}
        <section className="col-span-9 bg-white/50 relative flex flex-col">
          
          {/* Toolbar */}
          <div className="h-12 border-b border-ink/10 flex items-center justify-between px-6 bg-white">
            <div className="flex items-center gap-4">
              <span className="text-xs font-mono text-ink/50">
                {state.imageSrc ? `Image Loaded • ${previewMode.toUpperCase()} Mode` : 'Waiting for image...'}
              </span>
              {state.error && (
                <span className="text-xs font-medium text-red-600 flex items-center gap-1">
                  <AlertCircle size={12} /> {state.error}
                </span>
              )}
            </div>
            <div className="flex items-center gap-2">
              <button 
                onClick={() => handleZoom(-25)}
                className="p-2 hover:bg-ink/5 rounded transition-colors"
                title="Zoom Out"
              >
                <ZoomOut size={16} />
              </button>
              <span className="text-xs font-mono w-12 text-center">{state.zoom}%</span>
              <button 
                onClick={() => handleZoom(25)}
                className="p-2 hover:bg-ink/5 rounded transition-colors"
                title="Zoom In"
              >
                <ZoomIn size={16} />
              </button>
            </div>
          </div>

          {/* Canvas/SVG Container */}
          <div 
            ref={containerRef}
            className="flex-1 relative overflow-auto flex items-center justify-center p-8"
          >
            {/* Transparency Checkerboard Background */}
            <div className="absolute inset-0 bg-checkerboard bg-size-checkerboard opacity-50 pointer-events-none" />

            {state.imageSrc && (
              <div 
                className="relative shadow-2xl rounded-lg overflow-hidden bg-white transition-transform"
                style={{ transform: `scale(${state.zoom / 100})` }}
              >
                {/* Hidden Image Ref for processing */}
                <img ref={imageRef} className="hidden" alt="source" />
                
                {/* Canvas for Masking Preview */}
                <canvas 
                  ref={canvasRef} 
                  className="max-w-full max-h-full object-contain"
                  style={{ display: previewMode === 'vector' ? 'none' : 'block' }}
                />

                {/* SVG Output Overlay */}
                {state.processedSvg && previewMode === 'vector' && (
                  <div 
                    className="w-full h-full"
                    dangerouslySetInnerHTML={{ 
                      __html: state.processedSvg.replace('<svg', '<svg class="w-full h-full"') 

                  />
                )}
                
                {/* Loading Overlay */}
                {(state.status === 'UPLOADING' || state.status === 'VECTORIZING') && (
                  <div className="absolute inset-0 bg-bone/90 flex flex-col items-center justify-center z-20">
                    <Wand2 className="text-forest animate-spin mb-4" size={48} />
                    <p className="font-serif text-lg text-ink">Processing...</p>
                    <p className="text-xs font-mono text-ink/60 mt-2 uppercase tracking-widest">{state.status}</p>
                  </div>
                )}
              </div>
            )}

            {!state.imageSrc && (
              <div className="text-center opacity-40">
                <ImageIcon size={64} className="mx-auto mb-4 text-ink/20" />
                <p className="font-serif text-xl">No Image Loaded</p>
                <p className="text-sm text-ink/50 mt-2">Upload an image to get started</p>
              </div>
            )}
          </div>
        </section>
      </main>
    </div>
  );
}