<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>KYT STT 서비스</title>
    <style>
        body {
            font-family: 'Arial', sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            text-align: center;
            background-color: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }
        h1 {
            color: #333;
            margin-bottom: 30px;
        }
        .upload-area {
            margin: 20px 0;
        }
        button {
            background-color: #4CAF50;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            margin-left: 10px;
        }
        button:hover {
            background-color: #45a049;
        }
        .result {
            margin-top: 20px;
            padding: 20px;
            border: 1px solid #ddd;
            border-radius: 5px;
            white-space: pre-wrap;
            text-align: left;
            background-color: #fafafa;
        }
        .loading {
            display: none;
            margin: 20px 0;
            color: #666;
        }
        #audioFile {
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
    </style>
</head>
<body>
    <div class="container" id="mainContainer" style="display: none;">
        <h1>KYT STT 서비스</h1>
        <div class="upload-area">
            <input type="file" id="audioFile" accept="audio/*,video/*">
            <button onclick="processFile()">변환하기</button>
            <button onclick="copyResult()" id="copyButton" style="display: none;">복사하기</button>
        </div>
        <div id="loading" class="loading">
            <p>처리중... 잠시만 기다려주세요.</p>
        </div>
        <div id="result" class="result"></div>
    </div>

    <div class="container" id="unauthorizedMessage" style="display: none;">
        <h1>접근 권한이 없습니다</h1>
        <p>메인 페이지에서 로그인 후 이용해주세요.</p>
    </div>
    <script>
        // 페이지 로드 시 인증 확인
        window.onload = function() {
            const urlParams = new URLSearchParams(window.location.search);
            const urlToken = urlParams.get('token');
            
            console.log('URL에서 받은 토큰:', urlToken);
            
            // 부모 창에 토큰 요청
            window.opener.postMessage('requestToken', '*');
            
            // 부모 창으로부터 토큰 받기
            window.addEventListener('message', function(event) {
                // 메인 페이지의 도메인 확인 (실제 도메인으로 변경 필요)
                if (event.data && event.data.token) {
                    const parentToken = event.data.token;
                    console.log('부모 창에서 받은 토큰:', parentToken);
                    
                    // 토큰 비교
                    if (urlToken === parentToken) {
                        console.log('인증 성공: STT 서비스 표시');
                        document.getElementById('mainContainer').style.display = 'block';
                        document.getElementById('unauthorizedMessage').style.display = 'none';
                    } else {
                        console.log('인증 실패: 토큰 불일치');
                        document.getElementById('mainContainer').style.display = 'none';
                        document.getElementById('unauthorizedMessage').style.display = 'block';
                    }
                }
            });
        };

        async function processFile() {
            const fileInput = document.getElementById('audioFile');
            const loadingDiv = document.getElementById('loading');
            const resultDiv = document.getElementById('result');
            const copyButton = document.getElementById('copyButton');
            
            if (!fileInput.files.length) {
                alert('파일을 선택해주세요.');
                return;
            }

            const formData = new FormData();
            formData.append('file', fileInput.files[0]);

            loadingDiv.style.display = 'block';
            resultDiv.textContent = '';
            copyButton.style.display = 'none';

            try {
                const response = await fetch('/process', {
                    method: 'POST',
                    body: formData
                });
                
                const data = await response.json();
                
                if (response.ok) {
                    console.log('변환 결과:', data.result);
                    resultDiv.textContent = data.result.join('\n');
                    copyButton.style.display = 'inline-block'; // 결과가 있을 때만 복사 버튼 표시
                } else {
                    throw new Error(data.error);
                }
            } catch (error) {
                console.error('에러:', error);
                resultDiv.textContent = `에러가 발생했습니다: ${error.message}`;
            } finally {
                loadingDiv.style.display = 'none';
            }
        }

        async function copyResult() {
            const resultDiv = document.getElementById('result');
            try {
                if (navigator.clipboard && navigator.clipboard.writeText) {
                    await navigator.clipboard.writeText(resultDiv.textContent);
                } else {
                    // 대체 복사 방법
                    const textarea = document.createElement('textarea');
                    textarea.value = resultDiv.textContent;
                    document.body.appendChild(textarea);
                    textarea.select();
                    document.execCommand('copy');
                    document.body.removeChild(textarea);
                }
                alert('클립보드에 복사되었습니다.');
            } catch (err) {
                console.error('복사 실패:', err);
                alert('복사에 실패했습니다.');
            }
        }
    </script>
</body>
</html>