<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
    xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{/web/layout/homeLayout}">
<th:block layout:fragment="layout_css">
    <!-- GitHub Markdown 스타일 -->
    <link rel="stylesheet"
        href="https://cdnjs.cloudflare.com/ajax/libs/github-markdown-css/5.5.1/github-markdown-light.min.css">
    <!-- 코드 구문 강조 -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/github.min.css">
    <style>
        /* ========== 업로드 영역 ========== */
        .md-upload-zone {
            border: 2px dashed #d1d5db;
            border-radius: 12px;
            padding: 48px 24px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s ease;
            background: #f9fafb;
            margin-bottom: 24px;
        }

        .md-upload-zone:hover,
        .md-upload-zone.drag-over {
            border-color: #4a6cf7;
            background: #eff3ff;
        }

        .md-upload-zone .upload-icon {
            font-size: 48px;
            margin-bottom: 12px;
        }

        .md-upload-zone .upload-title {
            font-size: 18px;
            font-weight: 600;
            color: #374151;
            margin-bottom: 6px;
        }

        .md-upload-zone .upload-desc {
            font-size: 14px;
            color: #9ca3af;
        }

        .md-upload-zone input[type="file"] {
            display: none;
        }

        /* ========== 뷰어 헤더 ========== */
        .md-viewer-header {
            display: none;
            align-items: center;
            justify-content: space-between;
            background: #f6f8fa;
            border: 1px solid #d0d7de;
            border-bottom: none;
            border-radius: 8px 8px 0 0;
            padding: 10px 16px;
        }

        .md-viewer-header.active {
            display: flex;
        }

        .md-file-info {
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 14px;
            font-weight: 600;
            color: #24292f;
        }

        .md-file-info .file-icon {
            font-size: 16px;
        }

        .md-file-size {
            font-weight: 400;
            color: #656d76;
            font-size: 13px;
        }

        .md-viewer-actions {
            display: flex;
            gap: 8px;
        }

        .md-viewer-actions button {
            padding: 5px 14px;
            border: 1px solid #d0d7de;
            border-radius: 6px;
            background: #fff;
            font-size: 13px;
            cursor: pointer;
            color: #24292f;
            transition: all 0.15s ease;
        }

        .md-viewer-actions button:hover {
            background: #f3f4f6;
        }

        .md-viewer-actions button.btn-primary {
            background: #2da44e;
            color: #fff;
            border-color: #2da44e;
        }

        .md-viewer-actions button.btn-primary:hover {
            background: #218838;
        }

        /* ========== Markdown 렌더링 영역 ========== */
        .md-render-area {
            display: none;
            border: 1px solid #d0d7de;
            border-radius: 0 0 8px 8px;
            padding: 32px 40px;
            background: #fff;
            min-height: 200px;
            max-height: calc(100vh - 280px);
            overflow-y: auto;
        }

        .md-render-area.active {
            display: block;
        }

        /* GitHub Markdown 본문 커스터마이징 */
        .markdown-body {
            font-size: 15px;
            line-height: 1.8;
        }

        .markdown-body h1 {
            padding-bottom: 0.3em;
            border-bottom: 1px solid #d8dee4;
        }

        .markdown-body h2 {
            padding-bottom: 0.3em;
            border-bottom: 1px solid #d8dee4;
        }

        .markdown-body table {
            display: table;
            width: 100%;
        }

        .markdown-body table th,
        .markdown-body table td {
            padding: 8px 13px;
            border: 1px solid #d0d7de;
        }

        .markdown-body table th {
            background: #f6f8fa;
            font-weight: 600;
        }

        .markdown-body blockquote {
            border-left: 4px solid #d0d7de;
            color: #656d76;
            padding: 0 16px;
        }

        /* GitHub 스타일 Alert 박스 */
        .markdown-alert {
            padding: 12px 16px;
            margin-bottom: 16px;
            border-radius: 6px;
            border-left: 4px solid;
        }

        .markdown-alert-note {
            background: #ddf4ff;
            border-color: #54aeff;
        }

        .markdown-alert-tip {
            background: #dafbe1;
            border-color: #3fb950;
        }

        .markdown-alert-important {
            background: #fbefff;
            border-color: #a371f7;
        }

        .markdown-alert-warning {
            background: #fff8c5;
            border-color: #d29922;
        }

        .markdown-alert-caution {
            background: #ffebe9;
            border-color: #f85149;
        }

        .markdown-alert-title {
            font-weight: 600;
            margin-bottom: 4px;
            display: flex;
            align-items: center;
            gap: 6px;
        }

        /* ========== 원본 소스 뷰 ========== */
        .md-source-area {
            display: none;
            border: 1px solid #d0d7de;
            border-radius: 0 0 8px 8px;
            background: #fff;
            min-height: 200px;
            max-height: calc(100vh - 280px);
            overflow-y: auto;
        }

        .md-source-area.active {
            display: block;
        }

        .md-source-area pre {
            margin: 0;
            padding: 16px 24px;
            font-family: 'Consolas', 'Monaco', monospace;
            font-size: 13px;
            line-height: 1.6;
            white-space: pre-wrap;
            word-wrap: break-word;
            color: #24292f;
        }

        /* ========== 탭 버튼 ========== */
        .tab-btn.active-tab {
            background: #0969da !important;
            color: #fff !important;
            border-color: #0969da !important;
        }

        /* ========== 인쇄 시 스타일 ========== */
        @media print {

            .md-upload-zone,
            .md-viewer-header,
            .page_title {
                display: none !important;
            }

            .md-render-area {
                border: none !important;
                max-height: none !important;
                overflow: visible !important;
                padding: 0 !important;
            }
        }
    </style>
</th:block>
<th:block layout:fragment="layout_top_script">
    <script>
        let menuClass = "[[${param.menuClass}]]" == "" ? "" : "[[${param.menuClass}]]";
    </script>
</th:block>
<th:block layout:fragment="layout_content">
    <div class="center_box">
        <p class="page_title">Markdown 뷰어</p>

        <!-- 업로드 영역 -->
        <div class="md-upload-zone" id="uploadZone">
            <div class="upload-icon">📄</div>
            <div class="upload-title">Markdown 파일을 여기에 드래그 하거나 클릭하세요</div>
            <div class="upload-desc">.md 파일만 지원됩니다</div>
            <input type="file" id="fileInput" accept=".md,.markdown,.txt" />
        </div>

        <!-- 뷰어 헤더 -->
        <div class="md-viewer-header" id="viewerHeader">
            <div class="md-file-info">
                <span class="file-icon">📄</span>
                <span id="fileName">-</span>
                <span class="md-file-size" id="fileSize">-</span>
            </div>
            <div class="md-viewer-actions">
                <button class="tab-btn active-tab" id="btnPreview" onclick="showPreview()">미리보기</button>
                <button class="tab-btn" id="btnSource" onclick="showSource()">원본 소스</button>
                <button onclick="printMarkdown()">🖨️ 인쇄 / PDF</button>
                <button class="btn-primary" onclick="resetViewer()">다른 파일 열기</button>
            </div>
        </div>

        <!-- 렌더링된 Markdown -->
        <div class="md-render-area" id="renderArea">
            <div class="markdown-body" id="markdownBody"></div>
        </div>

        <!-- 원본 소스 -->
        <div class="md-source-area" id="sourceArea">
            <pre id="sourceCode"></pre>
        </div>
    </div>
</th:block>
<th:block layout:fragment="layout_script">
    <!-- Marked.js (Markdown 파서) -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/marked/12.0.1/marked.min.js"></script>
    <!-- Highlight.js (코드 구문 강조) -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
    <!-- Mermaid (다이어그램) -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/mermaid/10.9.0/mermaid.min.js"></script>

    <script>
        /* ===== 초기화 ===== */
        mermaid.initialize({ startOnLoad: false, theme: 'default' });

        /* ===== Marked 설정 ===== */
        const renderer = new marked.Renderer();

        // 코드 블록 렌더링 (mermaid 지원)
        renderer.code = function (code, language) {
            // marked v12 에서는 code가 객체일 수 있음
            if (typeof code === 'object') {
                language = code.lang;
                code = code.text;
            }
            if (language === 'mermaid') {
                return '<div class="mermaid">' + code + '</div>';
            }
            const validLang = !!(language && hljs.getLanguage(language));
            const highlighted = validLang
                ? hljs.highlight(code, { language: language }).value
                : hljs.highlightAuto(code).value;
            return '<pre><code class="hljs language-' + (language || '') + '">' + highlighted + '</code></pre>';
        };

        marked.setOptions({
            renderer: renderer,
            gfm: true,
            breaks: true,
            tables: true
        });

        /* ===== GitHub Alert 변환 ===== */
        function convertGithubAlerts(markdown) {
            const alertTypes = {
                'NOTE': { icon: 'ℹ️', title: 'Note' },
                'TIP': { icon: '💡', title: 'Tip' },
                'IMPORTANT': { icon: '❗', title: 'Important' },
                'WARNING': { icon: '⚠️', title: 'Warning' },
                'CAUTION': { icon: '🔴', title: 'Caution' }
            };

            return markdown.replace(
                /^>\s*\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\]\s*\n((?:>.*\n?)*)/gm,
                function (match, type, content) {
                    const alert = alertTypes[type];
                    const cleanContent = content.replace(/^>\s?/gm, '').trim();
                    return '<div class="markdown-alert markdown-alert-' + type.toLowerCase() + '">' +
                        '<div class="markdown-alert-title">' + alert.icon + ' ' + alert.title + '</div>' +
                        '<div>' + cleanContent + '</div>' +
                        '</div>\n';
                }
            );
        }

        /* ===== 파일 처리 ===== */
        function processFile(file) {
            if (!file) return;

            const reader = new FileReader();
            reader.onload = function (e) {
                const rawMarkdown = e.target.result;

                // 파일 정보 표시
                document.getElementById('fileName').textContent = file.name;
                document.getElementById('fileSize').textContent = formatFileSize(file.size);

                // 원본 소스 저장
                document.getElementById('sourceCode').textContent = rawMarkdown;

                // Markdown 렌더링
                const processedMd = convertGithubAlerts(rawMarkdown);
                document.getElementById('markdownBody').innerHTML = marked.parse(processedMd);

                // Mermaid 다이어그램 렌더링
                try {
                    mermaid.run({ nodes: document.querySelectorAll('.mermaid') });
                } catch (err) {
                    console.warn('Mermaid 렌더링 오류:', err);
                }

                // UI 전환
                document.getElementById('uploadZone').style.display = 'none';
                document.getElementById('viewerHeader').classList.add('active');
                document.getElementById('renderArea').classList.add('active');
                showPreview();
            };
            reader.readAsText(file, 'UTF-8');
        }

        /* ===== UI 컨트롤 ===== */
        function showPreview() {
            document.getElementById('renderArea').classList.add('active');
            document.getElementById('sourceArea').classList.remove('active');
            document.getElementById('btnPreview').classList.add('active-tab');
            document.getElementById('btnSource').classList.remove('active-tab');
        }

        function showSource() {
            document.getElementById('renderArea').classList.remove('active');
            document.getElementById('sourceArea').classList.add('active');
            document.getElementById('btnSource').classList.add('active-tab');
            document.getElementById('btnPreview').classList.remove('active-tab');
        }

        function resetViewer() {
            document.getElementById('uploadZone').style.display = '';
            document.getElementById('viewerHeader').classList.remove('active');
            document.getElementById('renderArea').classList.remove('active');
            document.getElementById('sourceArea').classList.remove('active');
            document.getElementById('markdownBody').innerHTML = '';
            document.getElementById('sourceCode').textContent = '';
            document.getElementById('fileInput').value = '';
        }

        function printMarkdown() {
            window.print();
        }

        function formatFileSize(bytes) {
            if (bytes < 1024) return bytes + ' B';
            if (bytes < 1048576) return (bytes / 1024).toFixed(1) + ' KB';
            return (bytes / 1048576).toFixed(1) + ' MB';
        }

        /* ===== 이벤트 바인딩 ===== */
        document.addEventListener('DOMContentLoaded', function () {
            const uploadZone = document.getElementById('uploadZone');
            const fileInput = document.getElementById('fileInput');

            // 클릭으로 파일 선택
            uploadZone.addEventListener('click', function () {
                fileInput.click();
            });

            fileInput.addEventListener('change', function (e) {
                if (e.target.files.length > 0) {
                    processFile(e.target.files[0]);
                }
            });

            // 드래그 앤 드롭
            uploadZone.addEventListener('dragover', function (e) {
                e.preventDefault();
                uploadZone.classList.add('drag-over');
            });

            uploadZone.addEventListener('dragleave', function () {
                uploadZone.classList.remove('drag-over');
            });

            uploadZone.addEventListener('drop', function (e) {
                e.preventDefault();
                uploadZone.classList.remove('drag-over');
                if (e.dataTransfer.files.length > 0) {
                    processFile(e.dataTransfer.files[0]);
                }
            });
        });
    </script>
</th:block>

</html>