<template>
  <div class="card mermaid-card">
    <div class="panel-title">
      <h3>{{ title }}</h3>
      <div class="actions">
        <button class="pill mono action" type="button" @click="open">Full screen</button>
        <span class="pill mono">Mermaid</span>
      </div>
    </div>
    <p class="description">{{ description }}</p>
    <div class="diagram" role="button" tabindex="0" @click="open" v-html="svgContent"></div>
    <div v-if="isOpen" class="overlay" @click.self="close">
      <div class="modal card glass">
        <div class="modal-head">
          <div>
            <div class="modal-title">{{ title }}</div>
            <div class="modal-sub mono">Click outside or press Esc to close</div>
          </div>
          <button class="close" type="button" @click="close">Close</button>
        </div>
        <div class="modal-body" v-html="svgContent"></div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, onUnmounted, ref, watch } from "vue";

const props = defineProps({
  title: String,
  description: String,
  diagram: String,
  cardId: String,
});

const svgContent = ref("");
const renderKey = ref(props.cardId || `mermaid-${Math.random().toString(36).slice(2)}`);
const isOpen = ref(false);
let initialized = false;
let scheduledHandle = null;
let scheduledKind = "";
let mermaidApi = null;

const renderDiagram = async () => {
  if (!props.diagram) return;
  if (!mermaidApi) {
    mermaidApi = (await import("mermaid")).default;
  }
  if (!initialized) {
    mermaidApi.initialize({
      startOnLoad: false,
      theme: "dark",
      securityLevel: "loose",
      themeVariables: {
        primaryColor: "#0b1228",
        primaryTextColor: "#e8f3ff",
        primaryBorderColor: "#00e5c5",
        lineColor: "#7f7cff",
        nodeTextColor: "#e8f3ff",
      },
    });
    initialized = true;
  }
  try {
    const { svg } = await mermaidApi.render(`${renderKey.value}-${Date.now()}`, props.diagram);
    svgContent.value = svg;
  } catch (err) {
    svgContent.value = `<pre class="mono" style="color:#ff4f93">Mermaid render error: ${err}</pre>`;
  }
};

/**
 * Cancel pending Mermaid rendering work before scheduling a replacement.
 *
 * @returns {void}
 */
function cancelScheduledRender() {
  if (!scheduledHandle) return;
  if (scheduledKind === "idle" && window.cancelIdleCallback) {
    window.cancelIdleCallback(scheduledHandle);
  } else {
    window.clearTimeout(scheduledHandle);
  }
  scheduledHandle = null;
  scheduledKind = "";
}

/**
 * Schedule Mermaid rendering during idle time when the browser supports it.
 *
 * WHY: diagrams are decorative and can be expensive, so rendering should not
 * compete with first paint or input responsiveness.
 *
 * @returns {void}
 */
function scheduleRenderDiagram() {
  cancelScheduledRender();
  if (!props.diagram) return;
  const runner = () => {
    scheduledHandle = null;
    scheduledKind = "";
    renderDiagram();
  };
  if (window.requestIdleCallback) {
    scheduledKind = "idle";
    scheduledHandle = window.requestIdleCallback(runner, { timeout: 1500 });
  } else {
    scheduledKind = "timeout";
    scheduledHandle = window.setTimeout(runner, 0);
  }
}

onMounted(scheduleRenderDiagram);
watch(
  () => props.diagram,
  () => scheduleRenderDiagram()
);

const onKeyDown = (event) => {
  if (event.key === "Escape") close();
};

const open = () => {
  if (!svgContent.value) scheduleRenderDiagram();
  isOpen.value = true;
};

const close = () => {
  isOpen.value = false;
};

watch(isOpen, (value) => {
  if (value) {
    document.body.style.overflow = "hidden";
    window.addEventListener("keydown", onKeyDown);
  } else {
    document.body.style.overflow = "";
    window.removeEventListener("keydown", onKeyDown);
  }
});

onUnmounted(() => {
  cancelScheduledRender();
  document.body.style.overflow = "";
  window.removeEventListener("keydown", onKeyDown);
});
</script>

<style scoped>
.mermaid-card {
  min-height: 300px;
  display: flex;
  flex-direction: column;
}

.actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.action {
  cursor: pointer;
}

.description {
  color: var(--text-muted);
  margin-top: 0;
}

.diagram {
  flex: 1;
  margin-top: 12px;
  padding: 10px;
  border-radius: var(--radius-sm);
  border: 1px dashed rgba(255, 255, 255, 0.08);
  background: rgba(255, 255, 255, 0.02);
  min-height: 170px;
  display: grid;
  place-items: center;
  overflow: auto;
  overscroll-behavior: contain;
  cursor: zoom-in;
}

.diagram:empty::before {
  content: "Rendering diagram...";
  color: var(--text-muted);
  font-size: 13px;
}

.diagram :deep(svg) {
  width: 100%;
  max-width: 100%;
  height: auto;
  display: block;
}

.diagram :deep(.label),
.modal-body :deep(.label) {
  font-family: "Space Grotesk", "Inter", system-ui, sans-serif;
}

.overlay {
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.72);
  display: grid;
  place-items: center;
  padding: 18px;
  z-index: 50;
}

.modal {
  width: min(1200px, 96vw);
  max-height: 92vh;
  overflow: hidden;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.modal-head {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 12px;
  padding: 14px 16px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.08);
}

.modal-title {
  font-weight: 800;
  color: var(--text-strong);
}

.modal-sub {
  color: var(--text-muted);
  font-size: 13px;
  margin-top: 4px;
}

.close {
  border: 1px solid rgba(255, 255, 255, 0.14);
  background: rgba(255, 255, 255, 0.04);
  color: var(--text-strong);
  padding: 8px 12px;
  border-radius: 10px;
  cursor: pointer;
}

.modal-body {
  padding: 12px;
  overflow: auto;
  max-height: calc(92vh - 64px);
}

.modal-body :deep(svg) {
  width: max(100%, 920px);
  max-width: none;
  height: auto;
}
</style>
