File size: 19,991 Bytes
e9d99da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ed6dfe5
 
 
e9d99da
 
 
 
ed6dfe5
e9d99da
 
ed6dfe5
 
e9d99da
ed6dfe5
 
 
 
 
e9d99da
9e3d558
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e9d99da
 
 
9e3d558
e9d99da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ed6dfe5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e9d99da
 
 
 
 
 
 
 
 
9e3d558
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e9d99da
 
ed6dfe5
 
 
 
 
 
 
 
 
 
9e3d558
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e9d99da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e3d558
e9d99da
 
 
9e3d558
e9d99da
 
 
 
 
 
 
 
 
 
 
9e3d558
e9d99da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from fastapi import FastAPI
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
import pathlib, os, uvicorn, base64

BASE = pathlib.Path(__file__).parent
app = FastAPI()
app.mount("/static", StaticFiles(directory=BASE), name="static")

# PDF 디렉토리 μ„€μ •
PDF_DIR = BASE / "pdf"
if not PDF_DIR.exists():
    PDF_DIR.mkdir(parents=True)

# PDF 파일 λͺ©λ‘ κ°€μ Έμ˜€κΈ°
def get_pdf_files():
    pdf_files = []
    if PDF_DIR.exists():
        pdf_files = [f for f in PDF_DIR.glob("*.pdf")]
    return pdf_files

# PDF 썸넀일 생성 및 ν”„λ‘œμ νŠΈ 데이터 μ€€λΉ„
def generate_pdf_projects():
    projects_data = []
    pdf_files = get_pdf_files()
    
    for pdf_file in pdf_files:
        projects_data.append({
            "path": str(pdf_file),
            "name": pdf_file.stem
        })
    
    return projects_data

HTML = """
<!doctype html><html lang="ko"><head>
<meta charset="utf-8"><title>FlipBook Space</title>
<link rel="stylesheet" href="/static/flipbook.css">
<script src="/static/three.js"></script>
<script src="/static/iscroll.js"></script>
<script src="/static/mark.js"></script>
<script src="/static/mod3d.js"></script>
<script src="/static/pdf.js"></script>
<script src="/static/flipbook.js"></script>
<script src="/static/flipbook.book3.js"></script>
<script src="/static/flipbook.scroll.js"></script>
<script src="/static/flipbook.swipe.js"></script>
<script src="/static/flipbook.webgl.js"></script>
<style>
body{margin:0;background:#f0f0f0;font-family:sans-serif}
header{max-width:960px;margin:0 auto;padding:18px 20px;display:flex;align-items:center}
#homeBtn{display:none;width:38px;height:38px;border:none;border-radius:50%;cursor:pointer;
         background:#0077c2;color:#fff;font-size:20px;margin-right:12px}
#homeBtn:hover{background:#005999}
h2{margin:0;font-size:1.5rem;font-weight:600}
#home,#viewerPage{max-width:960px;margin:0 auto;padding:0 20px 40px}
.grid{display:grid;grid-template-columns:repeat(auto-fill,180px);gap:16px;margin-top:24px}
.card{
  background:#fff url('/static/book2.jpg') no-repeat center center;
  background-size: 169%;  /* λ°°κ²½ 이미지λ₯Ό ν˜„μž¬λ³΄λ‹€ 30% 더 킀움 (130% * 1.3 = 169%) */
  border:1px solid #ccc;
  border-radius:6px;
  cursor:pointer;
  box-shadow:0 2px 4px rgba(0,0,0,.12);
  width: 180px;
  height: 240px;
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
.card img{
  width:55%;  /* 썸넀일 크기 μ€„μž„ (배경이 μ»€μ Έμ„œ λΉ„μœ¨ μœ μ§€) */
  height:auto;
  object-fit:contain;
  position:absolute;  /* μ ˆλŒ€ μœ„μΉ˜λ‘œ λ³€κ²½ */
  top:50%;  /* μƒλ‹¨μ—μ„œ 50% */
  left:50%;  /* μ’ŒμΈ‘μ—μ„œ 50% */
  transform: translate(-50%, -70%);  /* μ •μ€‘μ•™μ—μ„œ 20% μœ„λ‘œ 이동 */
  border: 1px solid #ddd;
  box-shadow: 0 2px 5px rgba(0,0,0,0.2);
}
.card p{
  text-align:center;
  margin:6px 0;
  position: absolute;
  bottom: 10px;
  left: 50%;
  transform: translateX(-50%);
  background: rgba(255, 255, 255, 0.7);
  padding: 4px 8px;
  border-radius: 4px;
  width: 85%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 150px;
  font-size: 11px; /* κΈ°λ³Έ 16pxμ—μ„œ μ•½ 30% κ°μ†Œ */
}
button.upload{all:unset;cursor:pointer;border:1px solid #bbb;padding:8px 14px;border-radius:6px;background:#fff;margin:0 8px}
#viewer{
  width:90%;
  height:90vh;
  max-width:90%;
  margin:0; 
  background:#fff;
  border:1px solid #ddd;
  border-radius:8px;
  position:fixed;
  top:50%;
  left:50%;
  transform:translate(-50%, -50%);
  z-index:1000;
  box-shadow:0 4px 20px rgba(0,0,0,0.15);
  /* ν™”λ©΄ λΉ„μœ¨μ— 맞게 μ‘°μ • */
  max-height: calc(90vh - 40px); /* μ—¬λ°± κ³ λ € */
  aspect-ratio: auto; /* λΉ„μœ¨ μžλ™ μ‘°μ • */
  object-fit: contain; /* λ‚΄μš©λ¬Ό λΉ„μœ¨ μœ μ§€ */
  overflow: hidden; /* λ‚΄μš© λ„˜μΉ¨ λ°©μ§€ */
}

/* FlipBook μ»¨νŠΈλ‘€λ°” κ΄€λ ¨ μŠ€νƒ€μΌ μ˜€λ²„λΌμ΄λ“œ */
.flipbook-container .fb3d-menu-bar {
  z-index: 2000 !important; /* μ»¨νŠΈλ‘€λ°”κ°€ λ‹€λ₯Έ μš”μ†Œλ³΄λ‹€ μœ„μ— μ˜€λ„λ‘ 함 */
  opacity: 1 !important; /* 항상 ν‘œμ‹œλ˜λ„λ‘ 함 */
  bottom: 0 !important; /* ν•˜λ‹¨μ— κ³ μ • */
  background-color: rgba(0,0,0,0.7) !important; /* 배경색 μ„€μ • */
  border-radius: 0 0 8px 8px !important; /* ν•˜λ‹¨ λͺ¨μ„œλ¦¬λ§Œ λ‘₯κΈ€κ²Œ */
  padding: 8px 0 !important; /* μƒν•˜ νŒ¨λ”© μΆ”κ°€ */
}

.flipbook-container .fb3d-menu-bar > ul > li > img,
.flipbook-container .fb3d-menu-bar > ul > li > div {
  opacity: 1 !important; /* 메뉴 μ•„μ΄μ½˜ 항상 ν‘œμ‹œ */
  transform: scale(1.2) !important; /* μ•„μ΄μ½˜ 크기 μ•½κ°„ 킀움 */
}

.flipbook-container .fb3d-menu-bar > ul > li {
  margin: 0 8px !important; /* 메뉴 μ•„μ΄ν…œ 간격 μ‘°μ • */
}

/* 메뉴 툴팁 μŠ€νƒ€μΌ κ°œμ„  */
.flipbook-container .fb3d-menu-bar > ul > li > span {
  background-color: rgba(0,0,0,0.8) !important;
  color: white !important;
  border-radius: 4px !important;
  padding: 4px 8px !important;
  font-size: 12px !important;
  bottom: 45px !important; /* 툴팁 μœ„μΉ˜ μ‘°μ • */
}
</style></head><body>

<header>
  <button id="homeBtn" title="ν™ˆμœΌλ‘œ">🏠</button>
  <h2>My FlipBook Projects</h2>
</header>

<section id="home">
  <div>
    <label class="upload">πŸ“· 이미지 <input id="imgInput" type="file" accept="image/*" multiple hidden></label>
    <label class="upload">πŸ“„ PDF <input id="pdfInput" type="file" accept="application/pdf" hidden></label>
  </div>
  <div class="grid" id="grid"></div>
</section>

<section id="viewerPage" style="display:none">
  <div id="viewer"></div>
</section>

<script>
let projects=[], fb=null;
const grid=$id('grid'), viewer=$id('viewer');
pdfjsLib.GlobalWorkerOptions.workerSrc='/static/pdf.worker.js';

// μ„œλ²„μ—μ„œ 미리 λ‘œλ“œλœ PDF ν”„λ‘œμ νŠΈ
let serverProjects = [];

/* πŸ”Š μ˜€λ””μ˜€ unlock – λ‚΄μž₯ Audio 와 같은 MP3 경둜 μ‚¬μš© */
['click','touchstart'].forEach(evt=>{
  document.addEventListener(evt,function u(){new Audio('static/turnPage2.mp3')
        .play().then(a=>a.pause()).catch(()=>{});document.removeEventListener(evt,u,{capture:true});},
        {once:true,capture:true});
});

/* ── μœ ν‹Έ ── */
function $id(id){return document.getElementById(id)}
function addCard(i,thumb,title){
  const d=document.createElement('div');
  d.className='card';
  d.onclick=()=>open(i);
  
  // 제λͺ© 10κΈ€μž μ œν•œ 및 λ§μ€„μž„ν‘œ 처리
  const displayTitle = title ? 
    (title.length > 10 ? title.substring(0, 10) + '...' : title) : 
    'ν”„λ‘œμ νŠΈ ' + (i+1);
  
  d.innerHTML=`<img src="${thumb}"><p title="${title || 'ν”„λ‘œμ νŠΈ ' + (i+1)}">${displayTitle}</p>`;
  grid.appendChild(d);
}

/* ── 이미지 μ—…λ‘œλ“œ ── */
$id('imgInput').onchange=e=>{
  const files=[...e.target.files]; if(!files.length) return;
  const pages=[],tot=files.length;let done=0;
  files.forEach((f,i)=>{const r=new FileReader();r.onload=x=>{pages[i]={src:x.target.result,thumb:x.target.result};
      if(++done===tot) save(pages);};r.readAsDataURL(f);});
};

/* ── PDF μ—…λ‘œλ“œ ── */
$id('pdfInput').onchange=e=>{
  const file=e.target.files[0]; if(!file) return;
  const fr=new FileReader();
  fr.onload=v=>{
    pdfjsLib.getDocument({data:v.target.result}).promise.then(async pdf=>{
      const pages=[];
      for(let p=1;p<=pdf.numPages;p++){
        const pg=await pdf.getPage(p), vp=pg.getViewport({scale:1});
        const c=document.createElement('canvas');c.width=vp.width;c.height=vp.height;
        await pg.render({canvasContext:c.getContext('2d'),viewport:vp}).promise;
        pages.push({src:c.toDataURL(),thumb:c.toDataURL()});
      }
      save(pages, file.name.replace('.pdf', ''));
    });
  };fr.readAsArrayBuffer(file);
};

/* ── ν”„λ‘œμ νŠΈ μ €μž₯ ── */
function save(pages, title){
  const id=projects.push(pages)-1;
  addCard(id,pages[0].thumb, title);
}

/* ── μ„œλ²„ PDF λ‘œλ“œ ── */
async function loadServerPDFs() {
  try {
    const response = await fetch('/api/pdf-projects');
    serverProjects = await response.json();
    
    // μ„œλ²„ PDF λ‘œλ“œ 및 썸넀일 생성
    for(let i = 0; i < serverProjects.length; i++) {
      const project = serverProjects[i];
      const response = await fetch(`/api/pdf-thumbnail?path=${encodeURIComponent(project.path)}`);
      const data = await response.json();
      
      if(data.thumbnail) {
        const pages = [{
          src: data.thumbnail,
          thumb: data.thumbnail,
          path: project.path
        }];
        
        save(pages, project.name);
      }
    }
  } catch(error) {
    console.error('μ„œλ²„ PDF λ‘œλ“œ μ‹€νŒ¨:', error);
  }
}

/* ── μΉ΄λ“œ β†’ FlipBook ── */
function open(i){
  toggle(false);
  const pages = projects[i];
  
  // 둜컬 ν”„λ‘œμ νŠΈ λ˜λŠ” μ„œλ²„ PDF λ‘œλ“œ
  if(fb){fb.destroy();viewer.innerHTML='';}
  
  if(pages[0].path) {
    // λ‘œλ”© ν‘œμ‹œ
    viewer.innerHTML = '<div style="position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);text-align:center;"><div style="border:4px solid #f3f3f3;border-top:4px solid #3498db;border-radius:50%;width:50px;height:50px;margin:0 auto;animation:spin 2s linear infinite;"></div><p style="margin-top:20px;font-size:16px;">PDF λ‘œλ”© 쀑...</p></div>';
    
    // μŠ€νƒ€μΌ μΆ”κ°€
    if (!document.getElementById('loadingStyle')) {
      const style = document.createElement('style');
      style.id = 'loadingStyle';
      style.textContent = '@keyframes spin{0%{transform:rotate(0deg)}100%{transform:rotate(360deg)}}';
      document.head.appendChild(style);
    }
    
    // μ„œλ²„ PDF 파일 λ‘œλ“œ
    fetch(`/api/pdf-content?path=${encodeURIComponent(pages[0].path)}`)
      .then(response => {
        if (!response.ok) {
          throw new Error('PDF λ‘œλ“œ μ‹€νŒ¨: ' + response.statusText);
        }
        return response.arrayBuffer();
      })
      .then(pdfData => {
        // PDF 데이터 λ‘œλ“œ 확인 λ‘œκΉ…
        console.log('PDF 데이터 λ‘œλ“œ μ™„λ£Œ:', pdfData.byteLength + ' λ°”μ΄νŠΈ');
        
        return pdfjsLib.getDocument({data: pdfData}).promise;
      })
      .then(async pdf => {
        console.log('PDF λ¬Έμ„œ λ‘œλ“œ μ™„λ£Œ. νŽ˜μ΄μ§€ 수:', pdf.numPages);
        
        const pdfPages = [];
        const progressElement = viewer.querySelector('p');
        
        for(let p = 1; p <= pdf.numPages; p++) {
          if (progressElement) {
            progressElement.textContent = `PDF νŽ˜μ΄μ§€ λ‘œλ”© 쀑... (${p}/${pdf.numPages})`;
          }
          
          try {
            const pg = await pdf.getPage(p);
            const vp = pg.getViewport({scale: 1});
            const c = document.createElement('canvas');
            c.width = vp.width;
            c.height = vp.height;
            
            await pg.render({canvasContext: c.getContext('2d'), viewport: vp}).promise;
            pdfPages.push({src: c.toDataURL(), thumb: c.toDataURL()});
          } catch (pageError) {
            console.error(`νŽ˜μ΄μ§€ ${p} λ Œλ”λ§ 였λ₯˜:`, pageError);
          }
        }
        
        console.log('λͺ¨λ“  νŽ˜μ΄μ§€ λ Œλ”λ§ μ™„λ£Œ:', pdfPages.length);
        
        if (pdfPages.length > 0) {
          createFlipBook(pdfPages);
        } else {
          throw new Error('PDFμ—μ„œ νŽ˜μ΄μ§€λ₯Ό μΆ”μΆœν•  수 μ—†μŠ΅λ‹ˆλ‹€.');
        }
      })
      .catch(error => {
        console.error('PDF 처리 쀑 였λ₯˜ λ°œμƒ:', error);
        viewer.innerHTML = `<div style="position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);text-align:center;"><p style="color:red;font-size:16px;">PDFλ₯Ό λ‘œλ“œν•˜λŠ” 쀑 였λ₯˜κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€:<br>${error.message}</p><button id="backBtn" style="margin-top:20px;padding:10px 20px;background:#0077c2;color:white;border:none;border-radius:4px;cursor:pointer;">ν™ˆμœΌλ‘œ λŒμ•„κ°€κΈ°</button></div>`;
        
        document.getElementById('backBtn').addEventListener('click', function() {
          toggle(true);
        });
      });
  } else {
    // μ—…λ‘œλ“œλœ ν”„λ‘œμ νŠΈ 보기
    console.log('둜컬 μ—…λ‘œλ“œλœ ν”„λ‘œμ νŠΈ λ Œλ”λ§:', pages.length + 'νŽ˜μ΄μ§€');
    createFlipBook(pages);
  }
}

function createFlipBook(pages) {
  console.log('FlipBook 생성 μ‹œμž‘. νŽ˜μ΄μ§€ 수:', pages.length);
  
  try {
    // ν™”λ©΄ λΉ„μœ¨ 계산
    const calculateAspectRatio = () => {
      const windowWidth = window.innerWidth;
      const windowHeight = window.innerHeight;
      const aspectRatio = windowWidth / windowHeight;
      
      // λ„ˆλΉ„ λ˜λŠ” 높이 κΈ°μ€€μœΌλ‘œ μ΅œλŒ€ 90% μ œν•œ
      let width, height;
      if (aspectRatio > 1) { // κ°€λ‘œ ν™”λ©΄
        height = Math.min(windowHeight * 0.9, windowHeight - 40);
        width = height * aspectRatio * 0.8; // κ°€λ‘œ ν™”λ©΄μ—μ„œλŠ” μ•½κ°„ μ€„μž„
        if (width > windowWidth * 0.9) {
          width = windowWidth * 0.9;
          height = width / (aspectRatio * 0.8);
        }
      } else { // μ„Έλ‘œ ν™”λ©΄
        width = Math.min(windowWidth * 0.9, windowWidth - 40);
        height = width / aspectRatio * 0.9; // μ„Έλ‘œ ν™”λ©΄μ—μ„œλŠ” μ•½κ°„ 늘림
        if (height > windowHeight * 0.9) {
          height = windowHeight * 0.9;
          width = height * aspectRatio * 0.9;
        }
      }
      
      // 졜적 μ‚¬μ΄μ¦ˆ λ°˜ν™˜
      return {
        width: Math.round(width),
        height: Math.round(height)
      };
    };
    
    // 초기 ν™”λ©΄ λΉ„μœ¨ 계산
    const size = calculateAspectRatio();
    viewer.style.width = size.width + 'px';
    viewer.style.height = size.height + 'px';
    
    fb = new FlipBook(viewer, {
      pages: pages,
      viewMode: 'webgl',
      autoSize: true,
      flipDuration: 800,
      backgroundColor: '#fff',
      /* πŸ”Š λ‚΄μž₯ μ‚¬μš΄λ“œ */
      sound: true,
      assets: {flipMp3: 'static/turnPage2.mp3', hardFlipMp3: 'static/turnPage2.mp3'},
      controlsProps: {
        enableFullscreen: true,
        enableToc: true,
        enableDownload: false,
        enablePrint: false,
        enableZoom: true,
        enableShare: false,
        enableSearch: true,
        enableAutoPlay: true,
        enableAnnotation: false,
        enableSound: true,
        enableLightbox: false,
        layout: 10, // λ ˆμ΄μ•„μ›ƒ μ˜΅μ…˜
        skin: 'light', // μŠ€ν‚¨ μŠ€νƒ€μΌ
        autoNavigationTime: 3600, // μžλ™ λ„˜κΉ€ μ‹œκ°„(초)
        hideControls: false, // 컨트둀 μˆ¨κΉ€ λΉ„ν™œμ„±ν™”
        paddingTop: 10, // 상단 νŒ¨λ”©
        paddingLeft: 10, // 쒌츑 νŒ¨λ”©
        paddingRight: 10, // 우츑 νŒ¨λ”©
        paddingBottom: 10, // ν•˜λ‹¨ νŒ¨λ”©
        pageTextureSize: 1024, // νŽ˜μ΄μ§€ ν…μŠ€μ²˜ 크기
        thumbnails: true, // 섬넀일 ν™œμ„±ν™”
        autoHideControls: false, // μžλ™ μˆ¨κΉ€ λΉ„ν™œμ„±ν™”
        controlsTimeout: 8000 // 컨트둀 ν‘œμ‹œ μ‹œκ°„ μ—°μž₯
      }
    });
    
    // ν™”λ©΄ 크기 λ³€κ²½ μ‹œ FlipBook 크기 μ‘°μ •
    window.addEventListener('resize', () => {
      if (fb) {
        const newSize = calculateAspectRatio();
        viewer.style.width = newSize.width + 'px';
        viewer.style.height = newSize.height + 'px';
        fb.resize();
      }
    });
    
    // FlipBook 생성 ν›„ μ»¨νŠΈλ‘€λ°” κ°•μ œ ν‘œμ‹œ
    setTimeout(() => {
      try {
        // μ»¨νŠΈλ‘€λ°” κ΄€λ ¨ μš”μ†Œ μ°ΎκΈ° 및 μŠ€νƒ€μΌ 적용
        const menuBars = document.querySelectorAll('.flipbook-container .fb3d-menu-bar');
        if (menuBars && menuBars.length > 0) {
          menuBars.forEach(menuBar => {
            menuBar.style.display = 'block';
            menuBar.style.opacity = '1';
            menuBar.style.visibility = 'visible';
            menuBar.style.zIndex = '9999';
          });
        }
      } catch (e) {
        console.warn('μ»¨νŠΈλ‘€λ°” μŠ€νƒ€μΌ 적용 쀑 였λ₯˜:', e);
      }
    }, 1000);
    
    console.log('FlipBook 생성 μ™„λ£Œ');
  } catch (error) {
    console.error('FlipBook 생성 쀑 였λ₯˜ λ°œμƒ:', error);
    alert('FlipBook을 μƒμ„±ν•˜λŠ” 쀑 였λ₯˜κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€: ' + error.message);
  }
}

/* ── λ„€λΉ„κ²Œμ΄μ…˜ ── */
$id('homeBtn').onclick=()=>{
  if(fb) {
    fb.destroy();
    viewer.innerHTML = '';
    fb = null;
  }
  toggle(true);
};

function toggle(showHome){
  $id('home').style.display=showHome?'block':'none';
  $id('viewerPage').style.display=showHome?'none':'block';
  $id('homeBtn').style.display=showHome?'none':'inline-block';
  
  // μΆ”κ°€: 전체 ν™”λ©΄ λͺ¨λ“œμ—μ„œ homeBtn μœ„μΉ˜ μ‘°μ •
  if(!showHome) {
    $id('homeBtn').style.position = 'fixed';
    $id('homeBtn').style.top = '20px';
    $id('homeBtn').style.left = '20px';
    $id('homeBtn').style.zIndex = '9999';  // μ΅œμƒμœ„ z-index둜 λ³€κ²½
    $id('homeBtn').style.fontSize = '24px'; // 크기 증가
    $id('homeBtn').style.width = '48px';
    $id('homeBtn').style.height = '48px';
    $id('homeBtn').style.boxShadow = '0 2px 10px rgba(0,0,0,0.2)'; // 그림자 μΆ”κ°€
    
    // λ°°κ²½ μ˜€λ²„λ ˆμ΄ μΆ”κ°€
    document.body.style.backgroundColor = '#3a3a3a';
  } else {
    $id('homeBtn').style.position = '';
    $id('homeBtn').style.top = '';
    $id('homeBtn').style.left = '';
    $id('homeBtn').style.zIndex = '';
    $id('homeBtn').style.fontSize = '';
    $id('homeBtn').style.width = '';
    $id('homeBtn').style.height = '';
    $id('homeBtn').style.boxShadow = '';
    
    // λ°°κ²½ μ›λž˜λŒ€λ‘œ
    document.body.style.backgroundColor = '#f0f0f0';
  }
}

// νŽ˜μ΄μ§€ λ‘œλ“œ μ‹œ μ„œλ²„ PDF λ‘œλ“œ
window.addEventListener('DOMContentLoaded', loadServerPDFs);
</script>
</body></html>
"""

# API μ—”λ“œν¬μΈνŠΈ: PDF ν”„λ‘œμ νŠΈ λͺ©λ‘
@app.get("/api/pdf-projects")
async def get_pdf_projects():
    return generate_pdf_projects()

# API μ—”λ“œν¬μΈνŠΈ: PDF 썸넀일 생성
@app.get("/api/pdf-thumbnail")
async def get_pdf_thumbnail(path: str):
    try:
        import fitz  # PyMuPDF
        
        # PDF 파일 μ—΄κΈ°
        doc = fitz.open(path)
        
        # 첫 νŽ˜μ΄μ§€ κ°€μ Έμ˜€κΈ°
        if doc.page_count > 0:
            page = doc[0]
            # μΈλ„€μΌμš© 이미지 λ Œλ”λ§ (해상도 μ‘°μ •)
            pix = page.get_pixmap(matrix=fitz.Matrix(0.5, 0.5))
            img_data = pix.tobytes("png")
            
            # Base64 인코딩
            b64_img = base64.b64encode(img_data).decode('utf-8')
            return {"thumbnail": f"data:image/png;base64,{b64_img}"}
        
        return {"thumbnail": None}
    except Exception as e:
        return {"error": str(e), "thumbnail": None}

@app.get("/api/pdf-content")
async def get_pdf_content(path: str):
    try:
        # 파일 쑴재 μ—¬λΆ€ 확인
        pdf_path = pathlib.Path(path)
        if not pdf_path.exists():
            return {"error": f"νŒŒμΌμ„ 찾을 수 μ—†μŠ΅λ‹ˆλ‹€: {path}"}, 404

        # 파일 읽기
        with open(path, "rb") as pdf_file:
            content = pdf_file.read()
            
        # 파일λͺ… 처리 - URL μΈμ½”λ”©μœΌλ‘œ ν•œκΈ€ λ“± 특수 문자 처리
        import urllib.parse
        filename = pdf_path.name
        encoded_filename = urllib.parse.quote(filename)
        
        # 응닡 헀더 μ„€μ • - RFC 6266 ν‘œμ€€ μ‚¬μš©
        headers = {
            "Content-Type": "application/pdf",
            "Content-Disposition": f"inline; filename=\"{encoded_filename}\"; filename*=UTF-8''{encoded_filename}"
        }
        
        # 파일 μ½˜ν…μΈ  직접 λ°˜ν™˜ (dictκ°€ μ•„λ‹Œ Response 객체)
        from fastapi.responses import Response
        return Response(content=content, media_type="application/pdf")
    except Exception as e:
        import traceback
        error_details = traceback.format_exc()
        print(f"PDF μ½˜ν…μΈ  λ‘œλ“œ 였λ₯˜: {str(e)}\n{error_details}")
        
        # 였λ₯˜ 응닡 λ°˜ν™˜ (JSON ν˜•μ‹)
        from fastapi.responses import JSONResponse
        return JSONResponse(content={"error": str(e)}, status_code=500)

@app.get("/", response_class=HTMLResponse)
async def root():
    return HTML

if __name__ == "__main__":
    uvicorn.run("app:app", host="0.0.0.0", port=int(os.getenv("PORT", 7860)))