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
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
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>MediaMaster Async</title>
    <script src="https://unpkg.com/react@18/umd/react.production.min.js"></script>
    <script src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script>
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://unpkg.com/lucide@latest"></script>
</head>
<body class="bg-slate-50 min-h-screen flex flex-col">
    <div id="root" class="flex-grow"></div>
    <script type="text/babel">
        const { useState, useEffect, useRef } = React;

        // アイコンコンポーネント
        const Icon = ({ name, className = "" }) => {
            useEffect(() => {
                if (window.lucide) {
                    window.lucide.createIcons();
                }
            }, [name]);
            return <i data-lucide={name} className={className}></i>;
        };

        const TOOLS = [
            { id: 'heic-jpg', title: 'HEIC → JPG', icon: 'image', color: 'bg-blue-500', description: 'iPhoneの写真を一般的な形式に変換' },
            { id: 'm4a-mp3', title: 'M4A → MP3', icon: 'music', color: 'bg-purple-500', description: 'Apple録音データをMP3に変換' },
            { id: 'mp4-mp3', title: '動画 → MP3', icon: 'volume-2', color: 'bg-orange-500', description: '動画から音声のみを抽出' },
            { id: 'jpeg-pdf', title: '画像 → PDF', icon: 'file-text', color: 'bg-red-500', description: '複数の画像を1つのPDFに結合' },
            { id: 'pdf-png', title: 'PDF → PNG', icon: 'files', color: 'bg-emerald-500', description: 'PDFの各ページを画像に変換' },
            { id: 'file-download', title: 'ファイル配布', icon: 'folder-down', color: 'bg-teal-500', description: 'パスワード認証でファイルをダウンロード' },
        ];

        function App() {
            const [selectedTool, setSelectedTool] = useState(null);
            const [files, setFiles] = useState([]);

            const [status, setStatus] = useState('idle');
            const [progress, setProgress] = useState(0);
            const [lastLog, setLastLog] = useState("");
            const [downloadUrl, setDownloadUrl] = useState(null);
            const [error, setError] = useState(null);
            const [isDragging, setIsDragging] = useState(false);

            const [filePassword, setFilePassword] = useState("");
            const [fileList, setFileList] = useState([]);
            const [selectedFiles, setSelectedFiles] = useState([]);
            const [fileError, setFileError] = useState(null);
            const [fileDownloading, setFileDownloading] = useState(false);

            const pollInterval = useRef(null);

            const handleFileChange = (e) => {
                setFiles(Array.from(e.target.files));
            };

            // ドラッグ&ドロップハンドラ
            const handleDragOver = (e) => {
                e.preventDefault();
                e.stopPropagation();
                setIsDragging(true);
            };

            const handleDragLeave = (e) => {
                e.preventDefault();
                e.stopPropagation();
                setIsDragging(false);
            };

            const handleDrop = (e) => {
                e.preventDefault();
                e.stopPropagation();
                setIsDragging(false);
                const dropped = Array.from(e.dataTransfer.files);
                if (dropped.length > 0) {
                    setFiles(dropped);
                }
            };

            const startProcessing = async () => {
                if (files.length === 0) return;

                setStatus('uploading');
                setProgress(10);
                setLastLog('サーバーにリクエストを送信中...');
                setDownloadUrl(null);
                setError(null);

                const formData = new FormData();
                formData.append('tool_id', selectedTool.id);
                files.forEach(file => formData.append('files', file));
                formData.append('output_format', 'mp3');

                try {
                    const res = await fetch('/api/convert', { method: 'POST', body: formData });
                    const data = await res.json();
                    
                    if (data.task_id) {
                        startPolling(data.task_id);
                    } else {
                        throw new Error(data.error || "リクエストに失敗しました");
                    }
                } catch (err) {
                    setStatus('failed');
                    setError(err.message || '通信エラーが発生しました');
                    setLastLog("処理に失敗しました");
                }
            };

            const startPolling = (tid) => {
                if (pollInterval.current) clearInterval(pollInterval.current);
                pollInterval.current = setInterval(async () => {
                    try {
                        const res = await fetch(`/api/status/${tid}`);
                        const data = await res.json();
                        
                        setStatus(data.status);
                        setProgress(data.progress || 0);
                        setLastLog(data.last_log || data.error || "");

                        if (data.status === 'completed') {
                            clearInterval(pollInterval.current);
                            setDownloadUrl(`/api/download/${tid}`);
                        } else if (data.status === 'failed') {
                            clearInterval(pollInterval.current);
                            setError(data.error || '不明なエラーが発生しました');
                        }
                    } catch (err) {
                        console.error('Polling error:', err);
                    }
                }, 2000);
            };

            const reset = () => {
                if (pollInterval.current) clearInterval(pollInterval.current);
                setSelectedTool(null);
                setFiles([]);
                setStatus('idle');
                setProgress(0);
                setLastLog("");
                setDownloadUrl(null);
                setError(null);
                setIsDragging(false);
            };

            const backToInput = () => {
                if (pollInterval.current) clearInterval(pollInterval.current);
                setStatus('idle');
                setProgress(0);
                setLastLog("");
                setDownloadUrl(null);
                setError(null);
            };

            const handleFileAuth = async () => {
                setFileError(null);
                try {
                    const res = await fetch('/api/files/auth', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ password: filePassword }),
                    });
                    const data = await res.json();
                    if (!res.ok) throw new Error(data.detail || "認証に失敗しました");
                    setFileList(data.files);
                } catch (err) {
                    setFileError(err.message);
                }
            };

            const handleFilesDownload = async () => {
                if (selectedFiles.length === 0) return;
                setFileDownloading(true);
                setFileError(null);
                try {
                    const res = await fetch('/api/files/download', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ password: filePassword, filenames: selectedFiles }),
                    });
                    if (!res.ok) {
                        const data = await res.json();
                        throw new Error(data.detail || "ダウンロードに失敗しました");
                    }
                    const blob = await res.blob();
                    const url = URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = 'download.zip';
                    a.click();
                    URL.revokeObjectURL(url);
                } catch (err) {
                    setFileError(err.message);
                } finally {
                    setFileDownloading(false);
                }
            };

            return (
                <div className="flex flex-col min-h-screen">
                    <div className="max-w-4xl mx-auto px-4 py-12 flex-grow w-full">
                        {/* Header */}
                        <div className="text-center mb-12">
                            <div className="inline-block p-3 bg-indigo-600 rounded-2xl mb-4 shadow-lg shadow-indigo-200">
                                <Icon name="zap" className="text-white w-8 h-8" />
                            </div>
                            <h1 className="text-4xl font-black text-slate-900 mb-2 tracking-tight">MediaMaster Async</h1>
                            <p className="text-slate-500 font-medium">高速・非同期メディア変換ツール</p>
                        </div>

                        {!selectedTool ? (
                            <div className="grid grid-cols-2 md:grid-cols-3 gap-4">
                                {TOOLS.map(tool => (
                                    <button
                                        key={tool.id}
                                        onClick={() => setSelectedTool(tool)}
                                        className="group p-6 bg-white rounded-3xl shadow-sm hover:shadow-xl transition-all duration-300 text-left border border-slate-100 hover:border-indigo-200 hover:-translate-y-1"
                                    >
                                        <div className={`inline-flex p-3 ${tool.color} rounded-2xl mb-4 shadow-lg`}>
                                            <Icon name={tool.icon} className="w-6 h-6 text-white" />
                                        </div>
                                        <p className="font-black text-slate-900 mb-1">{tool.title}</p>
                                        <p className="text-xs text-slate-400 font-medium leading-relaxed">{tool.description}</p>
                                    </button>
                                ))}
                            </div>
                        ) : selectedTool.id === 'file-download' ? (
                            <div className="max-w-lg mx-auto">
                                <div className="bg-white rounded-3xl shadow-sm border border-slate-100 overflow-hidden">
                                    {/* Tool Header */}
                                    <div className="bg-teal-500 p-6">
                                        <button onClick={reset} className="flex items-center gap-2 text-white/80 hover:text-white mb-4 text-sm font-bold transition-colors">
                                            <Icon name="arrow-left" className="w-4 h-4" />
                                            ツール選択に戻る
                                        </button>
                                        <div className="flex items-center gap-3">
                                            <Icon name="folder-down" className="w-8 h-8 text-white" />
                                            <div>
                                                <h2 className="text-xl font-black text-white">ファイル配布</h2>
                                                <p className="text-white/70 text-sm font-medium">パスワード認証でファイルをダウンロード</p>
                                            </div>
                                        </div>
                                    </div>
                                    {/* Content */}
                                    <div className="p-6 space-y-4">
                                        {fileList.length === 0 ? (
                                            <div className="space-y-4">
                                                <div>
                                                    <label className="block text-sm font-bold text-slate-600 mb-2">パスワード</label>
                                                    <input
                                                        type="password"
                                                        className="w-full p-4 bg-slate-50 border-2 border-slate-100 rounded-2xl focus:border-teal-500 focus:outline-none transition-all"
                                                        placeholder="パスワードを入力"
                                                        value={filePassword}
                                                        onChange={(e) => setFilePassword(e.target.value)}
                                                        onKeyDown={(e) => e.key === 'Enter' && handleFileAuth()}
                                                    />
                                                </div>
                                                {fileError && (
                                                    <div className="p-4 bg-rose-50 border border-rose-100 rounded-2xl text-rose-600 font-bold text-center text-sm">
                                                        {fileError}
                                                    </div>
                                                )}
                                                <button
                                                    onClick={handleFileAuth}
                                                    disabled={!filePassword}
                                                    className="w-full bg-slate-900 text-white py-4 rounded-2xl font-bold hover:bg-teal-600 disabled:bg-slate-200 transition-all"
                                                >
                                                    認証する
                                                </button>
                                            </div>
                                        ) : (
                                            <div className="space-y-4">
                                                <p className="text-sm font-bold text-slate-600">ダウンロードするファイルを選択してください</p>
                                                <div className="space-y-2 max-h-64 overflow-y-auto">
                                                    {fileList.map(fname => (
                                                        <label key={fname} className="flex items-center gap-3 p-3 bg-slate-50 rounded-2xl cursor-pointer hover:bg-teal-50 transition-colors">
                                                            <input
                                                                type="checkbox"
                                                                className="w-4 h-4 accent-teal-500"
                                                                checked={selectedFiles.includes(fname)}
                                                                onChange={(e) => {
                                                                    if (e.target.checked) {
                                                                        setSelectedFiles([...selectedFiles, fname]);
                                                                    } else {
                                                                        setSelectedFiles(selectedFiles.filter(f => f !== fname));
                                                                    }
                                                                }}
                                                            />
                                                            <Icon name="file" className="w-4 h-4 text-slate-400" />
                                                            <span className="text-sm font-medium text-slate-700">{fname}</span>
                                                        </label>
                                                    ))}
                                                </div>
                                                {fileError && (
                                                    <div className="p-4 bg-rose-50 border border-rose-100 rounded-2xl text-rose-600 font-bold text-center text-sm">
                                                        {fileError}
                                                    </div>
                                                )}
                                                <button
                                                    onClick={handleFilesDownload}
                                                    disabled={selectedFiles.length === 0 || fileDownloading}
                                                    className="w-full bg-slate-900 text-white py-4 rounded-2xl font-bold hover:bg-teal-600 disabled:bg-slate-200 transition-all flex items-center justify-center gap-2"
                                                >
                                                    <Icon name="download" className="w-5 h-5" />
                                                    {fileDownloading ? 'ダウンロード中...' : `${selectedFiles.length}件をダウンロード`}
                                                </button>
                                            </div>
                                        )}
                                    </div>
                                </div>
                            </div>
                        ) : (
                            <div className="max-w-lg mx-auto">
                                <div className="bg-white rounded-3xl shadow-sm border border-slate-100 overflow-hidden">
                                    {/* Tool Header */}
                                    <div className={`${selectedTool.color} p-6`}>
                                        <button onClick={reset} className="flex items-center gap-2 text-white/80 hover:text-white mb-4 text-sm font-bold transition-colors">
                                            <Icon name="arrow-left" className="w-4 h-4" />
                                            ツール選択に戻る
                                        </button>
                                        <div className="flex items-center gap-3">
                                            <Icon name={selectedTool.icon} className="w-8 h-8 text-white" />
                                            <div>
                                                <h2 className="text-xl font-black text-white">{selectedTool.title}</h2>
                                                <p className="text-white/70 text-sm font-medium">{selectedTool.description}</p>
                                            </div>
                                        </div>
                                    </div>

                                    {/* Content */}
                                    <div className="p-6 space-y-4">
                                        {status === 'idle' || status === 'uploading' ? (
                                            <>
                                                <div
                                                    className={`border-2 border-dashed rounded-3xl p-12 text-center transition-all ${
                                                        isDragging
                                                            ? 'border-indigo-500 bg-indigo-50'
                                                            : 'border-slate-200 bg-slate-50 hover:border-indigo-400'
                                                    }`}
                                                    onDragOver={handleDragOver}
                                                    onDragLeave={handleDragLeave}
                                                    onDrop={handleDrop}
                                                >
                                                    <input 
                                                        type="file" 
                                                        multiple 
                                                        className="hidden" 
                                                        id="fileInput"
                                                        onChange={handleFileChange}
                                                    />
                                                    <label htmlFor="fileInput" className="cursor-pointer block">
                                                        <Icon name="upload-cloud" className={`w-12 h-12 mx-auto mb-4 transition-colors ${isDragging ? 'text-indigo-500' : 'text-slate-300'}`} />
                                                        <p className="text-slate-600 font-bold mb-1">
                                                            {files.length > 0
                                                                ? `${files.length}個のファイルを選択中`
                                                                : isDragging
                                                                    ? 'ここにドロップ'
                                                                    : 'ファイルをドラッグ&ドロップ'}
                                                        </p>
                                                        <p className="text-slate-400 text-sm font-medium">またはクリックしてファイルを選択</p>
                                                    </label>
                                                </div>

                                                <button 
                                                    onClick={startProcessing} 
                                                    disabled={status !== 'idle' || files.length === 0}
                                                    className="w-full bg-slate-900 text-white py-4 rounded-2xl font-bold hover:bg-indigo-600 disabled:bg-slate-200 transition-all shadow-lg active:scale-[0.98]"
                                                >
                                                    処理開始
                                                </button>
                                            </>
                                        ) : (
                                            <div className="space-y-6 animate-in slide-in-from-bottom-2 duration-300">
                                                <div className="bg-slate-50 rounded-2xl p-6 border border-slate-100">
                                                    <div className="flex justify-between text-sm font-bold mb-3">
                                                        <span className={status === 'failed' ? 'text-rose-600' : 'text-indigo-600'}>
                                                            {status === 'completed' ? '完了しました' : lastLog}
                                                        </span>
                                                        <span className="text-slate-400">{progress}%</span>
                                                    </div>
                                                    <div className="w-full bg-slate-200 rounded-full h-3 overflow-hidden">
                                                        <div 
                                                            className={`h-full transition-all duration-500 shadow-lg ${status === 'failed' ? 'bg-rose-500' : 'bg-indigo-600'}`}
                                                            style={{ width: `${progress}%` }}
                                                        ></div>
                                                    </div>
                                                </div>

                                                {error && (
                                                    <div className="p-4 bg-rose-50 border border-rose-100 rounded-2xl text-rose-600 font-bold text-center text-sm">
                                                        {error}
                                                    </div>
                                                )}

                                                <div className="flex gap-4">
                                                    <button 
                                                        onClick={backToInput} 
                                                        className="flex-1 bg-slate-100 text-slate-600 py-4 rounded-2xl font-bold hover:bg-slate-200 transition-all"
                                                    >
                                                        入力に戻る
                                                    </button>
                                                    {downloadUrl && (
                                                        <a 
                                                            href={downloadUrl} 
                                                            className="flex-1 bg-emerald-500 text-white py-4 rounded-2xl font-bold text-center hover:bg-emerald-600 animate-pulse shadow-lg flex items-center justify-center gap-2"
                                                        >
                                                            <Icon name="download" className="w-5 h-5" />
                                                            ダウンロード
                                                        </a>
                                                    )}
                                                </div>
                                            </div>
                                        )}
                                    </div>
                                </div>
                            </div>
                        )}
                    </div>

                    {/* Footer */}
                    <footer className="py-8 text-center border-t border-slate-100">
                        <div className="flex items-center justify-center gap-2 text-slate-400 text-sm font-medium">
                            <span>© {new Date().getFullYear()}</span>
                            <span className="text-slate-900 font-black tracking-tight">HatakeyamaTechnology</span>
                            <span className="hidden sm:inline">|</span>
                            <span className="hidden sm:inline">All Rights Reserved.</span>
                        </div>
                    </footer>
                </div>
            );
        }

        const root = ReactDOM.createRoot(document.getElementById('root'));
        root.render(<App />);
    </script>
</body>
</html>