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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// PDF Alchemist Pro - Main Application Logic

// Global State
const AppState = {
    pdfDoc: null,
    currentPage: 1,
    totalPages: 0,
    zoom: 1.0,
    rotation: 0,
    scale: 1.5,
    tool: 'select', // select, text, draw, highlight, erase
    pages: [],
    history: [],
    darkMode: false,
    filename: 'document.pdf'
};

// Initialize PDF.js worker
pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js';

// DOM Elements
const dropZone = document.getElementById('drop-zone');
const fileInput = document.getElementById('file-input');

// Event Listeners
document.addEventListener('DOMContentLoaded', () => {
    setupDragAndDrop();
    setupKeyboardShortcuts();
    loadDefaultPDF();
});

// Drag and Drop
function setupDragAndDrop() {
    ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
        document.body.addEventListener(eventName, preventDefaults, false);
    });

    function preventDefaults(e) {
        e.preventDefault();
        e.stopPropagation();
    }

    document.body.addEventListener('dragenter', () => {
        dropZone.classList.remove('hidden');
    });

    dropZone.addEventListener('dragleave', (e) => {
        if (e.target === dropZone) {
            dropZone.classList.add('hidden');
        }
    });

    dropZone.addEventListener('drop', (e) => {
        dropZone.classList.add('hidden');
        const files = e.dataTransfer.files;
        if (files.length && files[0].type === 'application/pdf') {
            loadPDF(files[0]);
        }
    });
}

// File Handling
function openFileDialog() {
    fileInput.click();
    fileInput.onchange = (e) => {
        if (e.target.files.length) {
            loadPDF(e.target.files[0]);
        }
    };
}

async function loadPDF(file) {
    try {
        showLoading(true);
        AppState.filename = file.name;
        const arrayBuffer = await file.arrayBuffer();
        const pdf = await pdfjsLib.getDocument({ data: arrayBuffer }).promise;
        AppState.pdfDoc = pdf;
        AppState.totalPages = pdf.numPages;
        AppState.currentPage = 1;
        AppState.pages = [];
        
        // Render all pages
        await renderAllPages();
        updateUI();
        showLoading(false);
    } catch (error) {
        console.error('Error loading PDF:', error);
        alert('Error loading PDF file. Please try again.');
        showLoading(false);
    }
}

async function loadDefaultPDF() {
    // Create a blank PDF page as placeholder
    const canvas = document.getElementById('main-canvas');
    if (canvas) {
        const ctx = canvas.getContext('2d');
        canvas.width = 600;
        canvas.height = 800;
        ctx.fillStyle = '#f8fafc';
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        ctx.strokeStyle = '#cbd5e1';
        ctx.strokeRect(50, 50, canvas.width - 100, canvas.height - 100);
        ctx.fillStyle = '#64748b';
        ctx.font = '20px Inter';
        ctx.textAlign = 'center';
        ctx.fillText('Drop a PDF file here or click Open', canvas.width / 2, canvas.height / 2);
    }
}

async function renderAllPages() {
    const container = document.getElementById('pages-container');
    if (!container) return;
    
    container.innerHTML = '';
    
    for (let i = 1; i <= AppState.totalPages; i++) {
        const pageDiv = document.createElement('div');
        pageDiv.className = 'pdf-page mb-4 relative';
        pageDiv.id = `page-${i}`;
        
        const canvas = document.createElement('canvas');
        canvas.className = 'shadow-lg mx-auto block';
        
        const page = await AppState.pdfDoc.getPage(i);
        const viewport = page.getViewport({ scale: AppState.scale * AppState.zoom });
        
        canvas.height = viewport.height;
        canvas.width = viewport.width;
        
        const renderContext = {
            canvasContext: canvas.getContext('2d'),
            viewport: viewport
        };
        
        await page.render(renderContext).promise;
        
        // Add text layer for selection
        const textLayer = document.createElement('div');
        textLayer.className = 'textLayer';
        textLayer.style.height = `${viewport.height}px`;
        textLayer.style.width = `${viewport.width}px`;
        
        const textContent = await page.getTextContent();
        const textLayerRender = {
            textContent: textContent,
            container: textLayer,
            viewport: viewport,
            textDivs: []
        };
        
        await pdfjsLib.renderTextLayer(textLayerRender).promise;
        
        pageDiv.appendChild(canvas);
        pageDiv.appendChild(textLayer);
        container.appendChild(pageDiv);
        
        // Add to thumbnail sidebar
        addThumbnail(canvas, i);
    }
    
    updateStatusBar();
}

function addThumbnail(canvas, pageNum) {
    const thumbnailContainer = document.getElementById('thumbnail-container');
    if (!thumbnailContainer) return;
    
    const thumb = document.createElement('div');
    thumb.className = `thumbnail mb-3 rounded-lg overflow-hidden bg-white shadow-sm ${pageNum === 1 ? 'active' : ''}`;
    thumb.onclick = () => scrollToPage(pageNum);
    
    const thumbCanvas = document.createElement('canvas');
    const scale = 0.2;
    thumbCanvas.width = canvas.width * scale;
    thumbCanvas.height = canvas.height * scale;
    
    const ctx = thumbCanvas.getContext('2d');
    ctx.drawImage(canvas, 0, 0, thumbCanvas.width, thumbCanvas.height);
    
    const label = document.createElement('div');
    label.className = 'text-center text-xs py-1 bg-gray-100 dark:bg-gray-800 text-gray-600 dark:text-gray-400 font-medium';
    label.textContent = pageNum;
    
    thumb.appendChild(thumbCanvas);
    thumb.appendChild(label);
    thumbnailContainer.appendChild(thumb);
}

// Navigation
function scrollToPage(pageNum) {
    const page = document.getElementById(`page-${pageNum}`);
    if (page) {
        page.scrollIntoView({ behavior: 'smooth', block: 'start' });
        AppState.currentPage = pageNum;
        updateThumbnails();
        updateStatusBar();
    }
}

function nextPage() {
    if (AppState.currentPage < AppState.totalPages) {
        scrollToPage(AppState.currentPage + 1);
    }
}

function prevPage() {
    if (AppState.currentPage > 1) {
        scrollToPage(AppState.currentPage - 1);
    }
}

function updateThumbnails() {
    const thumbnails = document.querySelectorAll('.thumbnail');
    thumbnails.forEach((thumb, index) => {
        if (index + 1 === AppState.currentPage) {
            thumb.classList.add('active');
        } else {
            thumb.classList.remove('active');
        }
    });
}

// Zoom Controls
function zoomIn() {
    AppState.zoom = Math.min(AppState.zoom + 0.25, 3.0);
    refreshZoom();
}

function zoomOut() {
    AppState.zoom = Math.max(AppState.zoom - 0.25, 0.25);
    refreshZoom();
}

function resetZoom() {
    AppState.zoom = 1.0;
    refreshZoom();
}

function refreshZoom() {
    const pages = document.querySelectorAll('.pdf-page');
    pages.forEach(page => {
        page.style.transform = `scale(${AppState.zoom})`;
        page.style.transformOrigin = 'top center';
    });
    updateStatusBar();
}

// Rotation
function rotateClockwise() {
    AppState.rotation = (AppState.rotation + 90) % 360;
    renderAllPages();
}

function rotateCounterClockwise() {
    AppState.rotation = (AppState.rotation - 90) % 360;
    if (AppState.rotation < 0) AppState.rotation += 360;
    renderAllPages();
}

// Tools
function setTool(toolName) {
    AppState.tool = toolName;
    
    // Update UI
    document.querySelectorAll('.tool-btn').forEach(btn => {
        btn.classList.remove('tool-active');
    });
    
    const activeBtn = document.querySelector(`[data-tool="${toolName}"]`);
    if (activeBtn) {
        activeBtn.classList.add('tool-active');
    }
    
    // Update cursor
    const canvas = document.getElementById('pages-container');
    if (canvas) {
        switch(toolName) {
            case 'text':
                canvas.style.cursor = 'text';
                break;
            case 'draw':
                canvas.style.cursor = 'crosshair';
                break;
            case 'highlight':
                canvas.style.cursor = 'text';
                break;
            default:
                canvas.style.cursor = 'default';
        }
    }
}

// Text Addition
function showTextModal() {
    document.getElementById('text-modal').classList.remove('hidden');
    document.getElementById('text-content').focus();
}

function addTextToPDF() {
    const text = document.getElementById('text-content').value;
    if (text.trim()) {
        // In a full implementation, this would add text to the PDF layer
        // For now, we'll add an overlay
        addTextOverlay(text);
        closeModal('text-modal');
        document.getElementById('text-content').value = '';
    }
}

function addTextOverlay(text) {
    const currentPageDiv = document.getElementById(`page-${AppState.currentPage}`);
    if (!currentPageDiv) return;
    
    const overlay = document.createElement('div');
    overlay.className = 'absolute bg-white/90 dark:bg-gray-800/90 p-2 rounded border border-primary-500 shadow-lg cursor-move';
    overlay.style.left = '50px';
    overlay.style.top = '50px';
    overlay.style.minWidth = '100px';
    overlay.style.zIndex = '1000';
    overlay.contentEditable = true;
    overlay.textContent = text;
    
    // Make draggable
    let isDragging = false;
    let currentX;
    let currentY;
    let initialX;
    let initialY;
    let xOffset = 0;
    let yOffset = 0;
    
    overlay.addEventListener('mousedown', dragStart);
    
    function dragStart(e) {
        if (e.target === overlay) {
            initialX = e.clientX - xOffset;
            initialY = e.clientY - yOffset;
            isDragging = true;
        }
    }
    
    document.addEventListener('mousemove', dragMove);
    document.addEventListener('mouseup', dragEnd);
    
    function dragMove(e) {
        if (isDragging) {
            e.preventDefault();
            currentX = e.clientX - initialX;
            currentY = e.clientY - initialY;
            xOffset = currentX;
            yOffset = currentY;
            
            overlay.style.transform = `translate(${currentX}px, ${currentY}px)`;
        }
    }
    
    function dragEnd() {
        initialX = currentX;
        initialY = currentY;
        isDragging = false;
    }
    
    currentPageDiv.appendChild(overlay);
    overlay.focus();
}

// Export/PDF Creation
async function showExportModal() {
    document.getElementById('export-modal').classList.remove('hidden');
    document.getElementById('export-filename').value = AppState.filename || 'edited-document.pdf';
}

async function exportPDF() {
    try {
        const filename = document.getElementById('export-filename').value || 'document.pdf';
        
        // Create a new PDF document
        const { PDFDocument } = PDFLib;
        const newPdfDoc = await PDFDocument.create();
        
        // Copy pages from existing PDF if available
        if (AppState.pdfDoc) {
            const existingPdfBytes = await fetch(AppState.pdfDoc._pdfInfo.url).then(res => res.arrayBuffer()).catch(() => null);
            if (existingPdfBytes) {
                const existingPdf = await PDFDocument.load(existingPdfBytes);
                const pages = await newPdfDoc.copyPages(existingPdf, existingPdf.getPageIndices());
                pages.forEach(page => newPdfDoc.addPage(page));
            }
        }
        
        // If no existing PDF, create blank page
        if (newPdfDoc.getPageCount() === 0) {
            newPdfDoc.addPage();
        }
        
        const pdfBytes = await newPdfDoc.save();
        const blob = new Blob([pdfBytes], { type: 'application/pdf' });
        saveAs(blob, filename);
        
        closeModal('export-modal');
    } catch (error) {
        console.error('Export error:', error);
        alert('Error exporting PDF. Please try again.');
    }
}

// Modal Controls
function closeModal(modalId) {
    document.getElementById(modalId).classList.add('hidden');
}

// UI Updates
function updateUI() {
    updateStatusBar();
    updateThumbnails();
}

function updateStatusBar() {
    const pageCount = document.getElementById('page-count');
    const currentPage = document.getElementById('current-page-input');
    const zoomLevel = document.getElementById('zoom-level');
    
    if (pageCount) pageCount.textContent = AppState.totalPages;
    if (currentPage) currentPage.value = AppState.currentPage;
    if (zoomLevel) zoomLevel.textContent = `${Math.round(AppState.zoom * 100)}%`;
}

function showLoading(show) {
    let loader = document.getElementById('global-loader');
    if (!loader && show) {
        loader = document.createElement('div');
        loader.id = 'global-loader';
        loader.className = 'fixed inset-0 bg-black/50 backdrop-blur-sm z-[9999] flex items-center justify-center';
        loader.innerHTML = '<div class="spinner"></div>';
        document.body.appendChild(loader);
    } else if (loader && !show) {
        loader.remove();
    }
}

// Keyboard Shortcuts
function setupKeyboardShortcuts() {
    document.addEventListener('keydown', (e) => {
        // Only if not in input
        if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA') return;
        
        if (e.ctrlKey || e.metaKey) {
            switch(e.key) {
                case 'o':
                    e.preventDefault();
                    openFileDialog();
                    break;
                case 's':
                    e.preventDefault();
                    showExportModal();
                    break;
                case '+':
                case '=':
                    e.preventDefault();
                    zoomIn();
                    break;
                case '-':
                    e.preventDefault();
                    zoomOut();
                    break;
                case '0':
                    e.preventDefault();
                    resetZoom();
                    break;
            }
        } else {
            switch(e.key) {
                case 'ArrowRight':
                case 'ArrowDown':
                    nextPage();
                    break;
                case 'ArrowLeft':
                case 'ArrowUp':
                    prevPage();
                    break;
                case 't':
                    setTool('text');
                    break;
                case 's':
                    setTool('select');
                    break;
                case 'h':
                    setTool('highlight');
                    break;
            }
        }
    });
}

// Theme Toggle
function toggleTheme() {
    AppState.darkMode = !AppState.darkMode;
    const html = document.documentElement;
    
    if (AppState.darkMode) {
        html.classList.add('dark');
        html.classList.remove('light');
    } else {
        html.classList.remove('dark');
        html.classList.add('light');
    }
    
    localStorage.setItem('theme', AppState.darkMode ? 'dark' : 'light');
}

// Initialize theme from localStorage
if (localStorage.getItem('theme') === 'dark' || 
    (!localStorage.getItem('theme') && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
    AppState.darkMode = true;
    document.documentElement.classList.add('dark');
}

// Sidebar Toggle
function toggleSidebar() {
    const sidebar = document.querySelector('sidebar-component');
    if (sidebar) {
        sidebar.classList.toggle('hidden');
    }
}

// Properties Panel Toggle
function toggleProperties() {
    const panel = document.querySelector('properties-panel');
    if (panel) {
        panel.classList.toggle('hidden');
        panel.classList.toggle('lg:block');
    }
}