<template>
  <div class="book-panel">
    <div class="book-panel-header">
      <span class="book-panel-title">{{ bookTitle || 'Book' }} — p.&nbsp;{{ page }}</span>
      <div class="book-panel-nav">
        <button class="nav-btn" :disabled="page <= 1" @click="emit('navigate', page - 1)">&#8592;</button>
        <button class="nav-btn" @click="emit('navigate', page + 1)">&#8594;</button>
      </div>
      <button class="close-btn" @click="emit('close')" title="Close">&#x2715;</button>
    </div>

    <div class="book-panel-body">
      <div v-if="loading" class="panel-loading">
        <div class="spinner spinner-dark" style="width:24px;height:24px;margin:0 auto 0.5rem;"></div>
        <p>Loading page {{ page }}…</p>
      </div>
      <div v-else-if="error" class="panel-error">{{ error }}</div>
      <div v-else class="markdown-body" v-html="renderedHtml"></div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, onUnmounted } from 'vue'
import { api } from '@/services/api'

const props = defineProps<{
  bookId: string
  page: number
  bookTitle?: string
}>()

const emit = defineEmits<{
  close: []
  navigate: [page: number]
}>()

const loading = ref(false)
const error = ref<string | null>(null)
const renderedHtml = ref('')
let activeBlobUrls: string[] = []

onMounted(() => loadPage(props.page))

watch(() => [props.bookId, props.page], () => loadPage(props.page))

onUnmounted(() => {
  activeBlobUrls.forEach(u => URL.revokeObjectURL(u))
})

async function loadPage(page: number) {
  loading.value = true
  error.value = null
  renderedHtml.value = ''
  activeBlobUrls.forEach(u => URL.revokeObjectURL(u))
  activeBlobUrls = []

  try {
    const res = await api.get<string>(`/books/${props.bookId}/pages/${page}/html`, {
      headers: { Accept: 'text/html' },
      responseType: 'text'
    })
    renderedHtml.value = await resolveImages(res.data)
  } catch (e: any) {
    error.value = e.message ?? 'Failed to load page.'
  } finally {
    loading.value = false
  }
}

async function resolveImages(html: string): Promise<string> {
  const srcPattern = /src="(\/api\/v1\/figures\/[^"]+)"/g
  const matches = [...html.matchAll(srcPattern)]
  if (matches.length === 0) return html

  const unique = [...new Set(matches.map(m => m[1]))]
  const blobMap: Record<string, string> = {}

  await Promise.all(
    unique.map(async (src) => {
      try {
        const res = await api.get(src.replace(/^\/api\/v1/, ''), { responseType: 'blob' })
        const blobUrl = URL.createObjectURL(res.data)
        activeBlobUrls.push(blobUrl)
        blobMap[src] = blobUrl
      } catch {
        // leave original src
      }
    })
  )

  return html.replace(/src="(\/api\/v1\/figures\/[^"]+)"/g, (_, src) =>
    blobMap[src] ? `src="${blobMap[src]}"` : `src="${src}"`
  )
}
</script>

<style scoped>
.book-panel {
  display: flex;
  flex-direction: column;
  height: 100%;
  background: white;
  border-left: 1px solid #e2e8f0;
  border-radius: 0 10px 10px 0;
  overflow: hidden;
}

.book-panel-header {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.6rem 0.75rem;
  background: #f7fafc;
  border-bottom: 1px solid #e2e8f0;
  flex-shrink: 0;
}

.book-panel-title {
  flex: 1;
  font-size: 0.8rem;
  font-weight: 600;
  color: #2b6cb0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.book-panel-nav {
  display: flex;
  gap: 0.25rem;
}

.nav-btn {
  width: 1.75rem;
  height: 1.75rem;
  border: 1px solid #cbd5e0;
  border-radius: 5px;
  background: white;
  cursor: pointer;
  font-size: 0.85rem;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background 0.15s;
}
.nav-btn:hover:not(:disabled) { background: #ebf8ff; border-color: #3182ce; }
.nav-btn:disabled { opacity: 0.4; cursor: not-allowed; }

.close-btn {
  width: 1.75rem;
  height: 1.75rem;
  border: none;
  border-radius: 5px;
  background: none;
  cursor: pointer;
  font-size: 1rem;
  color: #718096;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background 0.15s, color 0.15s;
}
.close-btn:hover { background: #fed7d7; color: #742a2a; }

.book-panel-body {
  flex: 1;
  overflow-y: auto;
  padding: 1rem 1.25rem;
}

.panel-loading {
  text-align: center;
  padding: 2rem;
  color: #718096;
  font-size: 0.875rem;
}

.panel-error {
  padding: 1rem;
  background: #fff5f5;
  border: 1px solid #fed7d7;
  color: #742a2a;
  border-radius: 6px;
  font-size: 0.875rem;
}

.markdown-body {
  font-size: 0.9rem;
  line-height: 1.75;
  color: #2d3748;
}

.markdown-body :deep(h1),
.markdown-body :deep(h2),
.markdown-body :deep(h3) {
  color: #1a365d;
  font-weight: 600;
  margin: 1.25rem 0 0.5rem;
}
.markdown-body :deep(h2) { font-size: 1.05rem; border-bottom: 1px solid #e2e8f0; padding-bottom: 0.3rem; }
.markdown-body :deep(h3) { font-size: 0.95rem; }
.markdown-body :deep(p) { margin: 0.6rem 0; }
.markdown-body :deep(img) {
  max-width: 100%;
  border-radius: 6px;
  display: block;
  margin: 0.75rem auto;
  box-shadow: 0 1px 4px rgba(0,0,0,0.12);
}
.markdown-body :deep(ul),
.markdown-body :deep(ol) { padding-left: 1.4rem; margin: 0.5rem 0; }
.markdown-body :deep(code) {
  background: #f7fafc;
  border: 1px solid #e2e8f0;
  border-radius: 3px;
  padding: 0.1em 0.3em;
  font-size: 0.85em;
}
.markdown-body :deep(blockquote) {
  border-left: 3px solid #3182ce;
  padding-left: 0.75rem;
  color: #4a5568;
  margin: 0.5rem 0;
}
.markdown-body :deep(table) {
  width: 100%;
  border-collapse: collapse;
  font-size: 0.875em;
  margin: 0.75rem 0;
}
.markdown-body :deep(th),
.markdown-body :deep(td) {
  border: 1px solid #e2e8f0;
  padding: 0.35rem 0.6rem;
  text-align: left;
}
.markdown-body :deep(th) { background: #f7fafc; font-weight: 600; }
</style>
