File size: 26,447 Bytes
3e6b063
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
{% extends "base.html" %}

{% block title %}PDFly - Convert PDF to LaTeX | TexLab{% endblock %}

{% block extra_css %}
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.min.js"></script>
<style>

    .feature-card {

  display: inline-block;

  width: 100%;

  height: auto !important;

  padding: 20px 25px;

  margin-bottom: 20px;

  background: #fff;

  border-radius: 12px;

  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.05);

}

  .upload-area {

    border: 3px dashed #ddd;

    border-radius: 15px;

    padding: 40px 20px;

    text-align: center;

    transition: all 0.3s ease;

    cursor: pointer;

    background-color: #fafafa;

    margin-bottom: 20px;

  }



  .upload-area:hover {

    border-color: #667eea;

    background-color: #f0f4ff;

  }



  .upload-area.dragover {

    border-color: #667eea;

    background-color: #e0e7ff;

    transform: scale(1.02);

  }



  .upload-icon {

    font-size: 3rem;

    color: #667eea;

    margin-bottom: 15px;

  }



  .upload-text {

    font-size: 1.2rem;

    color: #555;

    margin-bottom: 10px;

  }



  .upload-hint {

    color: #888;

    font-size: 0.9rem;

  }



  .pdf-container {

    position: relative;

    margin: 20px 0;

    border: 1px solid #ddd;

    border-radius: 10px;

    overflow: auto;

    background: #525659;

    min-height: 500px;

    display: flex;

    align-items: center;

    justify-content: center;

  }



  #pdfCanvas {

    display: block;

    margin: 0 auto;

  }



  .pdf-placeholder {

    text-align: center;

    padding: 40px;

  }



  .highlight-overlay {

    position: absolute;

    border: 2px solid #4361ee;

    background-color: rgba(67, 97, 238, 0.3);

    cursor: crosshair;

  }



  .latex-output {

    background: #f8f9fa;

    border-radius: 10px;

    padding: 20px;

    border: 1px solid #eee;

    font-family: 'Consolas', 'Courier New', monospace;

    font-size: 1.1rem;

    white-space: pre-wrap;

    word-break: break-all;

    min-height: 100px;

    margin: 20px 0;

  }



  .rendered-output {

    background: white;

    border-radius: 10px;

    padding: 20px;

    border: 1px solid #eee;

    min-height: 100px;

    margin: 20px 0;

    text-align: center;

  }



  .solution-output {

    background: #e8f5e9;

    border-radius: 10px;

    padding: 20px;

    border: 1px solid #c8e6c9;

    margin: 20px 0;

    display: none;

  }



  .solution-title {

    color: #2e7d32;

    margin-bottom: 15px;

    font-weight: 600;

  }



  .solution-content {

    font-family: 'Consolas', 'Courier New', monospace;

    font-size: 1.1rem;

    white-space: pre-wrap;

  }



  .loading {

    display: none;

    text-align: center;

    padding: 20px;

  }



  .spinner {

    border: 4px solid rgba(0, 0, 0, 0.1);

    border-radius: 50%;

    border-top: 4px solid #667eea;

    width: 40px;

    height: 40px;

    animation: spin 1s linear infinite;

    margin: 0 auto 15px;

  }



  @keyframes spin {

    0% { transform: rotate(0deg); }

    100% { transform: rotate(360deg); }

  }



  .page-controls {

    display: flex;

    justify-content: center;

    gap: 15px;

    margin: 20px 0;

  }



  .page-indicator {

    padding: 10px 20px;

    background: #f8f9fa;

    border-radius: 20px;

    font-weight: 600;

  }



  .button-row {

    display: flex;

    gap: 15px;

    justify-content: center;

    margin: 20px 0;

    flex-wrap: wrap;

  }



  .highlighter-btn {

    background: linear-gradient(135deg, #4361ee 0%, #3a0ca3 100%);

    color: white;

    border: none;

    padding: 12px 25px;

    border-radius: 50px;

    font-weight: 600;

    transition: all 0.3s ease;

    font-size: 1rem;

  }



  .highlighter-btn:hover {

    transform: translateY(-3px);

    box-shadow: 0 5px 15px rgba(67, 97, 238, 0.4);

  }



  .highlighter-btn.active {

    background: #3a0ca3;

    box-shadow: 0 0 0 3px rgba(67, 97, 238, 0.5);

  }



  .file-info {

    background: #e3f2fd;

    border-radius: 10px;

    padding: 15px;

    margin: 15px 0;

    text-align: center;

  }



  .btn-success-gradient {

    background: linear-gradient(135deg, #28a745 0%, #20c997 100%);

    color: white;

    border: none;

    padding: 12px 25px;

    border-radius: 50px;

    font-weight: 600;

    transition: all 0.3s ease;

  }



  .btn-success-gradient:hover {

    transform: translateY(-3px);

    box-shadow: 0 5px 15px rgba(40, 167, 69, 0.4);

  }



  @media (max-width: 768px) {

    .pdf-container {

      min-height: 300px;

    }

    

    .button-row {

      flex-direction: column;

      align-items: center;

    }

    

    .button-row .btn {

      width: 100%;

      max-width: 300px;

    }

  }

</style>
{% endblock %}

{% block content %}
<div class="page-header">
  <h1 class="page-title"><i class="fas fa-bolt me-2"></i>PDFly - Smart PDF to LaTeX</h1>
  <p class="page-subtitle">
    Upload a PDF document, highlight areas with Converto, and convert them to clean, editable LaTeX code.
  </p>
</div>

<div class="row">
  <div class="col-lg-10 mx-auto">
    <div class="feature-card">
      <h3 class="section-title">Upload PDF Document</h3>
      
      <form id="uploadForm">
        <div class="upload-area" id="dropArea">
          <div class="upload-icon">
            <i class="fas fa-cloud-upload-alt"></i>
          </div>
          <h4 class="upload-text">Drag & Drop your PDF here</h4>
          <p class="upload-hint">or click to browse files (PDF only)</p>
          <input type="file" name="pdf_file" id="fileInput" accept=".pdf" required class="d-none">
        </div>
        
        <div class="text-center">
          <button type="submit" class="btn btn-primary-gradient">
            <i class="fas fa-upload me-2"></i>Upload PDF
          </button>
        </div>
      </form>
    </div>

    <div class="feature-card" id="pdfViewer" style="display: none;">
      <h3 class="section-title">PDF Document</h3>
      
      <div class="file-info">
        <i class="fas fa-file-pdf me-2"></i>
        <span id="fileName"></span> 
        (<span id="pageCount"></span> pages)
      </div>
      
      <div class="page-controls">
        <button id="prevPage" class="btn btn-neutral">
          <i class="fas fa-arrow-left"></i>
        </button>
        <div class="page-indicator">
          Page <span id="currentPage">1</span> of <span id="totalPages">1</span>
        </div>
        <button id="nextPage" class="btn btn-neutral">
          <i class="fas fa-arrow-right"></i>
        </button>
      </div>
      
      <div class="pdf-container" id="pdfContainer">
        <canvas id="pdfCanvas" style="max-width: 100%; height: auto;"></canvas>
      </div>
      
      <div class="text-center mt-3">
        <button id="highlighterBtn" class="highlighter-btn">
          <i class="fas fa-magic me-2"></i>Converto
        </button>
      </div>
      
      <div class="button-row">
        <button id="convertSelectedBtn" class="btn btn-primary-gradient" disabled>
          <i class="fas fa-cogs me-2"></i>Convert Selected Area to LaTeX
        </button>
        <button id="clearSelection" class="btn btn-neutral" disabled>
          <i class="fas fa-times-circle me-2"></i>Clear Highlight
        </button>
        <button id="convertAllBtn" class="btn btn-dark-gradient">
          <i class="fas fa-file-pdf me-2"></i>Convert Entire PDF
        </button>
      </div>
    </div>

    <div class="loading" id="loading">
      <div class="spinner"></div>
      <p>Processing your PDF... This may take a few seconds.</p>
    </div>

    <div class="feature-card" id="resultCard" style="display: none;">
      <h3 class="section-title">Generated LaTeX</h3>
      
      <div class="rendered-output">
        <!-- <h5>✅ Ready for Overleaf!</h5> -->
        <div id="renderedContent"></div>
        <div style="margin-top: 15px; padding: 15px; background: #e8f5e9; border-radius: 8px; text-align: left;">
          <strong>Latex Code will appear here</strong>
          <ul style="margin: 10px 0; padding-left: 20px;">
            
          </ul>
        </div>
      </div>
      
      <div class="latex-output" id="latexOutput" style="display: none;"></div>
      
      <div class="solution-output" id="solutionOutput">
        <h5 class="solution-title"><i class="fas fa-calculator me-2"></i>Solution</h5>
        <div class="solution-content" id="solutionContent"></div>
      </div>
      
      <div class="button-row">
        <button id="solveBtn" class="btn btn-secondary-gradient">
          <i class="fas fa-calculator me-2"></i>Solve Content
        </button>
        <button id="copyBtn" class="btn btn-primary-gradient">
          <i class="fas fa-copy me-2"></i>Copy to Clipboard
        </button>
        <button id="downloadLatexBtn" class="btn btn-success-gradient">
          <i class="fas fa-download me-2"></i>Download .tex File
        </button>
        <button id="newConversion" class="btn btn-neutral">
          <i class="fas fa-redo me-2"></i>Convert Another Area
        </button>
        <a href="/pdffly" class="btn btn-neutral">
          <i class="fas fa-file-pdf me-2"></i>Upload Another PDF
        </a>
      </div>
    </div>
  </div>
</div>
{% endblock %}

{% block extra_js %}
<script>

  // DOM elements

  const dropArea = document.getElementById('dropArea');

  const fileInput = document.getElementById('fileInput');

  const uploadForm = document.getElementById('uploadForm');

  const pdfViewer = document.getElementById('pdfViewer');

  const pdfContainer = document.getElementById('pdfContainer');

  const convertSelectedBtn = document.getElementById('convertSelectedBtn');

  const clearSelection = document.getElementById('clearSelection');

  const convertAllBtn = document.getElementById('convertAllBtn');

  const resultCard = document.getElementById('resultCard');

  const loading = document.getElementById('loading');

  const fileName = document.getElementById('fileName');

  const pageCount = document.getElementById('pageCount');

  const currentPage = document.getElementById('currentPage');

  const totalPages = document.getElementById('totalPages');

  const prevPage = document.getElementById('prevPage');

  const nextPage = document.getElementById('nextPage');

  const highlighterBtn = document.getElementById('highlighterBtn');

  const solveBtn = document.getElementById('solveBtn');

  const solutionOutput = document.getElementById('solutionOutput');

  

  // State variables

  let currentFilename = '';

  let highlight = null;

  let isHighlighting = false;

  let startX, startY;

  let isHighlighterMode = false;

  let currentLatex = '';

  let completeLatexDocument = '';

  let pdfDoc = null;

  let pageNum = 1;

  let pageRendering = false;

  let pageNumPending = null;

  let scale = 1.5;

  

  // Configure PDF.js worker

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

  

  // File upload handling

  dropArea.addEventListener('click', () => {

    fileInput.click();

  });

  

  // Drag and drop events

  dropArea.addEventListener('dragover', (e) => {

    e.preventDefault();

    dropArea.classList.add('dragover');

  });

  

  dropArea.addEventListener('dragleave', () => {

    dropArea.classList.remove('dragover');

  });

  

  dropArea.addEventListener('drop', (e) => {

    e.preventDefault();

    dropArea.classList.remove('dragover');

    

    if (e.dataTransfer.files.length) {

      fileInput.files = e.dataTransfer.files;

      // Trigger the form submission handler

      const event = new Event('submit', { bubbles: true, cancelable: true });

      uploadForm.dispatchEvent(event);

    }

  });



  // Render PDF page

  function renderPage(num) {

    pageRendering = true;

    pdfDoc.getPage(num).then(function(page) {

      const canvas = document.getElementById('pdfCanvas');

      const ctx = canvas.getContext('2d');

      const viewport = page.getViewport({scale: scale});

      

      canvas.height = viewport.height;

      canvas.width = viewport.width;

      

      const renderContext = {

        canvasContext: ctx,

        viewport: viewport

      };

      

      const renderTask = page.render(renderContext);

      renderTask.promise.then(function() {

        pageRendering = false;

        if (pageNumPending !== null) {

          renderPage(pageNumPending);

          pageNumPending = null;

        }

      });

    });

    

    currentPage.textContent = num;

  }

  

  // Queue page rendering

  function queueRenderPage(num) {

    if (pageRendering) {

      pageNumPending = num;

    } else {

      renderPage(num);

    }

  }

  

  // Load and display PDF

  function loadPDF(url) {

    pdfjsLib.getDocument(url).promise.then(function(pdf) {

      pdfDoc = pdf;

      totalPages.textContent = pdf.numPages;

      pageNum = 1;

      renderPage(pageNum);

      updatePageNavigation();

    });

  }



  // Form submission

  uploadForm.addEventListener('submit', async (e) => {

    e.preventDefault();

    

    const formData = new FormData();

    const file = fileInput.files[0];

    

    if (!file) {

      alert('Please select a PDF file');

      return;

    }

    

    formData.append('file', file);

    

    try {

      loading.style.display = 'block';

      

      const response = await fetch('/pdffly/upload', {

        method: 'POST',

        body: formData

      });

      

      const data = await response.json();

      

      if (data.success) {

        currentFilename = data.filename;

        

        // Update file info

        fileName.textContent = data.filename;

        pageCount.textContent = data.pages;

        totalPages.textContent = data.pages;

        currentPage.textContent = 1;

        

        // Load and render PDF

        loadPDF(data.pdf_path);

        

        // Display all LaTeX results

        let allLatex = '';

        data.results.forEach(result => {

          if (result.latex) {

            allLatex += `Page ${result.page}:\n${result.latex}\n\n`;

          } else if (result.error) {

            allLatex += `Page ${result.page}: Error - ${result.error}\n\n`;

          }

        });

        

        // Store complete document

        completeLatexDocument = data.complete_document || allLatex;

        

        // Show results immediately

        currentLatex = allLatex;

        document.getElementById('latexOutput').textContent = completeLatexDocument;

        document.getElementById('renderedContent').innerHTML = '<p><strong>✅ PDF converted to LaTeX successfully!</strong><br><small>The code has been cleaned and formatted for Overleaf compilation.</small></p>';

        resultCard.style.display = 'block';

        

        // Enable page navigation buttons

        updatePageNavigation();

        

        // Show PDF viewer

        document.querySelector('.feature-card:first-child').style.display = 'none';

        pdfViewer.style.display = 'block';

        

        // Add highlighting functionality

        addHighlightingFunctionality();

      } else {

        alert('Error: ' + (data.error || 'Unknown error'));

      }

    } catch (error) {

      console.error('Upload error:', error);

      alert('An error occurred during upload. Please try again.');

    } finally {

      loading.style.display = 'none';

    }

  });

  

  // Add highlighting functionality to PDF container

  function addHighlightingFunctionality() {

    pdfContainer.addEventListener('mousedown', startHighlight);

    pdfContainer.addEventListener('mousemove', updateHighlight);

    pdfContainer.addEventListener('mouseup', endHighlight);

  }

  

  // Toggle highlighter mode

  highlighterBtn.addEventListener('click', () => {

    isHighlighterMode = !isHighlighterMode;

    highlighterBtn.classList.toggle('active', isHighlighterMode);

    

    if (isHighlighterMode) {

      highlighterBtn.innerHTML = '<i class="fas fa-magic me-2"></i>Converto Active';

      pdfContainer.style.cursor = 'crosshair';

    } else {

      highlighterBtn.innerHTML = '<i class="fas fa-magic me-2"></i>Converto';

      pdfContainer.style.cursor = 'default';

      

      // Remove any existing highlight if exiting highlighter mode

      if (highlight) {

        highlight.remove();

        highlight = null;

        convertSelectedBtn.disabled = true;

        clearSelection.disabled = true;

      }

    }

  });

  

  // Start highlight

  function startHighlight(e) {

    if (!isHighlighterMode) return;

    

    isHighlighting = true;

    const rect = pdfContainer.getBoundingClientRect();

    startX = e.clientX - rect.left;

    startY = e.clientY - rect.top;

    

    // Remove existing highlight if any

    if (highlight) {

      highlight.remove();

      highlight = null;

    }

    

    // Create new highlight overlay

    highlight = document.createElement('div');

    highlight.className = 'highlight-overlay';

    highlight.style.left = startX + 'px';

    highlight.style.top = startY + 'px';

    highlight.style.width = '0px';

    highlight.style.height = '0px';

    

    pdfContainer.appendChild(highlight);

  }

  

  // Update highlight

  function updateHighlight(e) {

    if (!isHighlighting || !highlight || !isHighlighterMode) return;

    

    const rect = pdfContainer.getBoundingClientRect();

    const currentX = e.clientX - rect.left;

    const currentY = e.clientY - rect.top;

    

    const width = currentX - startX;

    const height = currentY - startY;

    

    highlight.style.width = Math.abs(width) + 'px';

    highlight.style.height = Math.abs(height) + 'px';

    

    if (width < 0) {

      highlight.style.left = currentX + 'px';

    }

    

    if (height < 0) {

      highlight.style.top = currentY + 'px';

    }

  }

  

  // End highlight

  function endHighlight() {

    if (!isHighlighting) return;

    isHighlighting = false;

    

    if (highlight) {

      const rect = highlight.getBoundingClientRect();

      const containerRect = pdfContainer.getBoundingClientRect();

      

      // Enable convert button if highlight is large enough

      if (rect.width > 20 && rect.height > 20) {

        convertSelectedBtn.disabled = false;

        clearSelection.disabled = false;

      } else {

        // Remove small highlights

        highlight.remove();

        highlight = null;

      }

    }

  }

  

  // Clear highlight

  clearSelection.addEventListener('click', () => {

    if (highlight) {

      highlight.remove();

      highlight = null;

      convertSelectedBtn.disabled = true;

      clearSelection.disabled = true;

    }

  });

  

  // Convert selected area

  convertSelectedBtn.addEventListener('click', async () => {

    if (!currentFilename) return;

    

    try {

      loading.style.display = 'block';

      resultCard.style.display = 'none';

      solutionOutput.style.display = 'none';

      

      // Get highlight coordinates if available

      let coordinates = null;

      if (highlight) {

        const rect = highlight.getBoundingClientRect();

        const containerRect = pdfContainer.getBoundingClientRect();

        coordinates = [

          rect.left - containerRect.left,

          rect.top - containerRect.top,

          rect.width,

          rect.height

        ];

      }

      

      const response = await fetch('/pdflly/process', {

        method: 'POST',

        headers: {

          'Content-Type': 'application/json'

        },

        body: JSON.stringify({

          filename: currentFilename,

          coordinates: coordinates,

          page: parseInt(currentPage.textContent) - 1

        })

      });

      

      const data = await response.json();

      

      if (data.success) {

        currentLatex = data.latex;

        

        // Display results

        document.getElementById('latexOutput').textContent = data.latex;

        document.getElementById('renderedContent').innerHTML = `$$${data.latex}$$`;

        

        // Render with MathJax if available

        if (typeof MathJax !== 'undefined') {

          MathJax.typesetPromise([document.getElementById('renderedContent')]);

        }

        

        // Show result card

        resultCard.style.display = 'block';

      } else {

        alert('Error: ' + data.error);

      }

    } catch (error) {

      console.error('Conversion error:', error);

      alert('An error occurred during conversion. Please try again.');

    } finally {

      loading.style.display = 'none';

    }

  });

  

  // Convert entire PDF

  convertAllBtn.addEventListener('click', async () => {

    if (!currentFilename) return;

    

    try {

      loading.style.display = 'block';

      resultCard.style.display = 'none';

      solutionOutput.style.display = 'none';

      

      const response = await fetch('/pdffly/process', {

        method: 'POST',

        headers: {

          'Content-Type': 'application/json'

        },

        body: JSON.stringify({

          filename: currentFilename,

          convert_all: true

        })

      });

      

      const data = await response.json();

      

      if (data.success) {

        currentLatex = data.latex;

        

        // Display results

        document.getElementById('latexOutput').textContent = data.latex;

        document.getElementById('renderedContent').innerHTML = '<p>Full PDF content converted to LaTeX</p>';

        

        // Show result card

        resultCard.style.display = 'block';

      } else {

        alert('Error: ' + (data.error || 'Unknown error'));

      }

    } catch (error) {

      console.error('Conversion error:', error);

      alert('An error occurred during conversion. Please try again.');

    } finally {

      loading.style.display = 'none';

    }

  });

  

  // Solve PDF content

  solveBtn.addEventListener('click', async () => {

    if (!currentLatex) return;

    

    try {

      loading.style.display = 'block';

      

      const response = await fetch('/pdffly/solve', {

        method: 'POST',

        headers: {

          'Content-Type': 'application/json'

        },

        body: JSON.stringify({ latex: currentLatex })

      });

      

      const data = await response.json();

      

      if (data.success) {

        const solution = data.solution;

        let solutionText = '';

        

        if (solution.type === 'equation') {

          solutionText = `Solutions:\n${solution.solutions.join('\n')}`;

        } else if (solution.type === 'expression') {

          solutionText = `Simplified:\n${solution.result}`;

        } else if (solution.type === 'numerical') {

          solutionText = `Numerical value:\n${solution.result}`;

        } else if (solution.type === 'system') {

          solutionText = `System solutions:\n${JSON.stringify(solution.solutions)}`;

        } else if (solution.type === 'error') {

          solutionText = `Error: ${solution.message}`;

        } else {

          solutionText = solution.message || 'Math solver integration pending';

        }

        

        document.getElementById('solutionContent').textContent = solutionText;

        solutionOutput.style.display = 'block';

      } else {

        alert('Error: ' + (data.error || 'Unknown error'));

      }

    } catch (error) {

      console.error('Solving error:', error);

      alert('An error occurred while solving the content. Please try again.');

    } finally {

      loading.style.display = 'none';

    }

  });

  

  // Copy to clipboard

  document.getElementById('copyBtn').addEventListener('click', () => {

    const latexText = completeLatexDocument || document.getElementById('latexOutput').textContent;

    navigator.clipboard.writeText(latexText).then(() => {

      alert('✅ Complete LaTeX document copied to clipboard!\nReady to paste into Overleaf.');

    }).catch(err => {

      console.error('Failed to copy: ', err);

      alert('Failed to copy LaTeX code. Please try again.');

    });

  });

  

  // Download LaTeX file

  document.getElementById('downloadLatexBtn').addEventListener('click', () => {

    const latexText = completeLatexDocument || document.getElementById('latexOutput').textContent;

    const blob = new Blob([latexText], { type: 'text/plain' });

    const url = URL.createObjectURL(blob);

    const a = document.createElement('a');

    a.href = url;

    a.download = (currentFilename.replace('.pdf', '') || 'converted') + '.tex';

    document.body.appendChild(a);

    a.click();

    document.body.removeChild(a);

    URL.revokeObjectURL(url);

    alert('✅ LaTeX file downloaded!\nYou can now upload it to Overleaf.');

  });

  

  // New conversion

  document.getElementById('newConversion').addEventListener('click', () => {

    resultCard.style.display = 'none';

    solutionOutput.style.display = 'none';

    if (highlight) {

      highlight.remove();

      highlight = null;

      convertSelectedBtn.disabled = true;

      clearSelection.disabled = true;

    }

  });

  

  // Update page navigation button states

  function updatePageNavigation() {

    const current = parseInt(currentPage.textContent);

    const total = parseInt(totalPages.textContent);

    

    prevPage.disabled = current <= 1;

    nextPage.disabled = current >= total;

  }

  

  // Page navigation

  prevPage.addEventListener('click', () => {

    if (pageNum <= 1) return;

    pageNum--;

    queueRenderPage(pageNum);

    updatePageNavigation();

    

    // Clear highlight when changing pages

    if (highlight) {

      highlight.remove();

      highlight = null;

      convertSelectedBtn.disabled = true;

      clearSelection.disabled = true;

    }

  });

  

  nextPage.addEventListener('click', () => {

    if (pageNum >= pdfDoc.numPages) return;

    pageNum++;

    queueRenderPage(pageNum);

    updatePageNavigation();

    

    // Clear highlight when changing pages

    if (highlight) {

      highlight.remove();

      highlight = null;

      convertSelectedBtn.disabled = true;

      clearSelection.disabled = true;

    }

  });

</script>
{% endblock %}