<template>
    <div class="viewer-layout h-full overflow-hidden">
        <!-- Main pane (full width, sidebar is now in AppSidebar) -->
        <main class="viewer-pane min-w-0 flex flex-col h-full overflow-hidden">
            <!-- Toolbar: floating panel groups -->
            <div class="viewer-toolbar" v-if="currentPath || fileType === 'dir'">
                <div class="viewer-panel breadcrumb-panel">
                    <span v-for="(crumb, i) in breadcrumbs" :key="i">
                        <span v-if="i > 0" class="breadcrumb-sep">/</span>
                        <span class="breadcrumb-item" :class="{ active: i === breadcrumbs.length - 1 }" @click="openFile(crumb.path)">{{ crumb.label }}</span>
                    </span>
                </div>
                <div class="viewer-toolbar-spacer"></div>
                <div v-if="fileType === 'md'" class="viewer-panel toggle-panel">
                    <button class="md-toggle-btn" :class="{ active: !mdRaw }" @click="mdRaw = false">Rendered</button>
                    <button class="md-toggle-btn" :class="{ active: mdRaw }" @click="mdRaw = true">Raw</button>
                </div>
                <a v-if="fileType && fileType !== 'dir'" class="viewer-panel download-panel" :href="downloadUrl" :download="fileName" title="Download">
                    <ArrowDownTrayIcon class="w-4 h-4" />
                </a>
            </div>

            <!-- Content -->
            <OverlayScrollbarsComponent class="content flex-1 min-h-0" :options="scrollbarOptions" element="div">
                <!-- Empty state (only when no fileType set at all) -->
                <div v-if="!currentPath && fileType !== 'dir'" class="viewer-empty">
                    <FolderOpenIcon class="w-8 h-8 text-text-dim" />
                    <p>Select a file from the tree</p>
                </div>

                <!-- Loading (delayed 3s) -->
                <div v-else-if="showLoading" class="viewer-loading">loading…</div>

                <!-- Error -->
                <div v-else-if="fetchError" class="viewer-error">{{ fetchError }}</div>

                <!-- Directory listing -->
                <div v-else-if="fileType === 'dir'" class="viewer-dir">
                    <div v-for="d in dirDirs" :key="d" class="dir-entry dir-entry--dir" @click="openFile(currentPath ? currentPath + '/' + d : d)">
                        <FolderIcon class="w-4 h-4" />
                        <span>{{ d }}/</span>
                    </div>
                    <div v-for="f in dirFiles" :key="f.path" class="dir-entry dir-entry--file" @click="openFile(f.path)">
                        <DocumentIcon class="w-4 h-4" />
                        <span>{{ f.name }}</span>
                    </div>
                    <div v-if="!dirDirs.length && !dirFiles.length" class="viewer-empty">
                        <p>Empty directory</p>
                    </div>
                </div>

                <!-- PDF -->
                <iframe
                    v-else-if="fileType === 'pdf'"
                    class="viewer-pdf"
                    :src="pdfSrc"
                    frameborder="0"
                />

                <!-- Markdown rendered -->
                <div
                    v-else-if="fileType === 'md' && !mdRaw"
                    class="viewer-md md-body"
                    v-html="renderedMd"
                    @copy="onCopy"
                />

                <!-- Markdown raw -->
                <div v-else-if="fileType === 'md' && mdRaw" class="viewer-raw-md">
                    <pre class="viewer-raw-code"><code><span v-for="(line, i) in contentLines" :key="i" class="code-line"><span class="line-num">{{ i + 1 }}</span>{{ line }}
</span></code></pre>
                </div>

                <!-- Text / code -->
                <pre v-else class="viewer-raw-code"><code><span v-for="(line, i) in contentLines" :key="i" class="code-line"><span class="line-num">{{ i + 1 }}</span>{{ line }}
</span></code></pre>
            </OverlayScrollbarsComponent>
        </main>
    </div>
</template>

<script setup lang="ts">
defineOptions({ name: 'ViewerView' });
import { OverlayScrollbarsComponent } from 'overlayscrollbars-vue';
import { scrollbarOptions } from '../composables/useScrollbar';
import { FolderOpenIcon, FolderIcon, DocumentIcon, ArrowDownTrayIcon } from '@heroicons/vue/20/solid';
import { useViewer } from '../composables/useViewer';

import { computed } from 'vue';
import { getApiBase } from '../utils/apiBase';

const {
  fstoken, viewerRoots, currentPath,
  content, fileType, loading, showLoading, fetchError,
  mdRaw, mdLineCount, renderedMd, pdfSrc,
  openFile, onCopy, dirFiles, dirDirs,
} = useViewer();

const contentLines = computed(() => content.value.split("\n"));
const fileName = computed(() => {
    if (!currentPath.value) return '';
    return currentPath.value.split('/').pop() || '';
});
const downloadUrl = computed(() => {
    if (!currentPath.value || !fstoken.value) return '';
    return `${getApiBase()}/api/viewer/file?path=${encodeURIComponent(currentPath.value)}&token=${encodeURIComponent(fstoken.value)}&dl=1`;
});
const breadcrumbs = computed(() => {
    const crumbs: { label: string; path: string }[] = [{ label: 'files', path: '' }];
    if (!currentPath.value) return crumbs;
    const parts = currentPath.value.split('/');
    for (let i = 0; i < parts.length; i++) {
        crumbs.push({ label: parts[i], path: parts.slice(0, i + 1).join('/') });
    }
    return crumbs;
});
</script>

<style scoped>
/* Viewer is now full-width — sidebar lives in AppSidebar */

.viewer-empty {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;
    gap: 8px;
    color: var(--text-dim);
}
.viewer-empty .empty-icon { font-size: 2rem; }
.viewer-empty p { margin: 0; }

/* Viewer toolbar: row of floating panel groups */
.viewer-toolbar {
    display: flex;
    align-items: center;
    gap: var(--panel-gap, 6px);
    padding: var(--panel-gap, 6px);
    padding-bottom: 0;
    flex-shrink: 0;
}
.viewer-toolbar-spacer { flex: 1; }

/* Shared panel pill style */
.viewer-panel {
    display: flex;
    align-items: center;
    background: var(--panel-bg);
    border-radius: var(--radius-panel, 12px);
    box-shadow: var(--panel-shadow);
    padding: 0 12px;
    height: 34px;
    font-size: 0.85rem;
}

.breadcrumb-panel {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    min-width: 0;
}
.breadcrumb-sep { color: var(--text-dim, #666); margin: 0 2px; }
.breadcrumb-item { cursor: pointer; color: var(--text-dim, #71B095); }
.breadcrumb-item:hover { color: var(--text, #ccc); }
.breadcrumb-item.active { color: var(--text, #ccc); cursor: default; }

.toggle-panel {
    gap: 2px;
    padding: 0 4px;
}

.download-panel {
    width: 34px;
    padding: 0;
    justify-content: center;
    color: var(--text-dim, #888);
    text-decoration: none;
    transition: color 0.15s;
}
.download-panel:hover { color: var(--text, #ccc); }

.viewer-loading, .viewer-error { padding: 20px; color: var(--text-dim); }
.viewer-error { color: var(--error); }

.viewer-dir { padding: 12px 16px; }
.dir-entry {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 6px 12px;
    cursor: pointer;
    border-radius: 4px;
    color: var(--text, #ccc);
}
.dir-entry:hover { background: var(--hover-bg, rgba(255,255,255,0.05)); }
.dir-entry--dir { color: var(--text-dim, #71B095); }
.dir-entry--file { color: var(--text, #ccc); }

.viewer-pdf { width: 100%; height: 100%; border: none; display: block; }

.viewer-text {
    margin: 0;
    padding: 12px 16px;
    line-height: 1.6;
    color: var(--text);
    white-space: pre-wrap;
    word-break: break-word;
}
</style>

<style>
/* Markdown body (not scoped — v-html bypasses scoped) */
/* MD toolbar */
.viewer-md-toolbar {
    display: flex;
    gap: 4px;
    padding: 6px 12px;
    background: var(--bg-dim, #1a1d23);
    flex-shrink: 0;
}
.md-toggle-btn {
    padding: 2px 10px;
    border-radius: var(--radius-sm, 6px);
    border: none;
    background: transparent;
    color: var(--text-dim, #888);
    cursor: pointer;
    transition: background 0.12s, color 0.12s;
}
.md-toggle-btn:hover {
    background: color-mix(in srgb, var(--accent) 10%, transparent);
    color: var(--text);
}
.md-toggle-btn.active {
    background: color-mix(in srgb, var(--accent) 18%, transparent);
    color: var(--accent);
}

/* Raw MD with line numbers */
.viewer-raw-md {
    display: flex;
    flex: 1;
    overflow: auto;
    font-family: var(--font-mono);
    line-height: 1.6;
}
.viewer-raw-gutter {
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    padding: 12px 8px 12px 12px;
    min-width: 3rem;
    color: var(--text-dim, #555);
    background: var(--bg-dim, #1a1d23);
    border-right: 1px solid var(--border, #2a2d35);
    user-select: none;
    flex-shrink: 0;
}
.viewer-raw-gutter span {
    display: block;
    line-height: 1.6;
}
.viewer-raw-code {
    flex: 1;
    margin: 0;
    padding: 12px 16px;
    overflow: visible;
    white-space: pre-wrap;
    word-break: break-word;
    background: transparent;
    color: var(--text, #abb2bf);
    line-height: 1.6;
}
.code-line { display: block; }
.line-num { display: inline-block; width: 3em; text-align: right; padding-right: 1em; color: var(--text-dim); opacity: 0.4; user-select: none; font-family: var(--font-mono); }
.viewer-raw-code code {
    background: none;
    padding: 0;
    font-size: inherit;
}

/* .md-body styles extracted to css/markdown.css */

@media (max-width: 639px) {
    .viewer-raw-gutter { display: none; }
    .viewer-raw-code { padding: 8px 12px; }
    .viewer-md-toolbar { padding: 6px 8px; }
    .md-toggle-btn { min-height: 36px; display: inline-flex; align-items: center; }
}
</style>
